Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add Expressive Code to Starlight #742

Merged
merged 28 commits into from
Nov 20, 2023
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
Show all changes
28 commits
Select commit Hold shift + click to select a range
e11490d
Add Expressive Code to Starlight
hippotastic Sep 22, 2023
66dc164
Add min color contrast option, fix a11y issues
hippotastic Sep 22, 2023
6eac143
Merge branch 'main' into pr/742
delucis Oct 26, 2023
63a9c11
Merge branch 'main' into add-expressive-code
delucis Nov 1, 2023
cb40752
Refactor EC to use new fs translations system
delucis Oct 28, 2023
5e1ff49
Migrate to Expressive Code v0.27
hippotastic Nov 7, 2023
3e2abbb
Merge branch 'main' into add-expressive-code
hippotastic Nov 7, 2023
91848a1
Add MD authoring examples for EC features
hippotastic Nov 7, 2023
1bc73ed
Change EC default theme to "Night Owl"
hippotastic Nov 8, 2023
8ba9dcf
Update EC to make code block CSS cacheable
hippotastic Nov 11, 2023
f122453
Update EC dependency to fix APIRoute warning
hippotastic Nov 16, 2023
485772b
Merge branch 'main' into add-expressive-code
delucis Nov 17, 2023
af00d1d
Refactor `pathToLocale` helper for re-use
delucis Nov 18, 2023
5c614f9
Re-use `pathToLocale` in Expressive Code
delucis Nov 18, 2023
f2d9077
Rework EC docs in Markdown guide & Configuration reference
delucis Nov 18, 2023
1f7ca13
Add changeset
delucis Nov 18, 2023
6d9c7ff
Merge pull request #2 from withastro/chris/ec-docs
hippotastic Nov 19, 2023
6ef1ef7
Merge pull request #1 from withastro/chris/ec-refactoring
hippotastic Nov 19, 2023
7759b2a
Update authoring content with Sarah’s suggestions
delucis Nov 19, 2023
5026515
Implement suggestions from code review
hippotastic Nov 20, 2023
fa015f6
Update docs/src/content/docs/reference/configuration.mdx
hippotastic Nov 20, 2023
e26ed40
Update .changeset/sweet-berries-begin.md
hippotastic Nov 20, 2023
4d766e0
Apply configuration reference suggestions
delucis Nov 20, 2023
8c67efa
Update astro-expressive-code to 0.29.0
hippotastic Nov 20, 2023
efd1f63
Fix sentence
delucis Nov 20, 2023
44d3717
Update packages/starlight/integrations/expressive-code/index.ts
hippotastic Nov 20, 2023
597a46f
Update docs/src/content/docs/reference/configuration.mdx
hippotastic Nov 20, 2023
46103c7
Merge branch 'main' into add-expressive-code
delucis Nov 20, 2023
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions docs/src/content/docs/guides/i18n.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -202,6 +202,17 @@ You can provide translations for additional languages you support — or overrid
}
```

Starlight’s code blocks are powered by the [Expressive Code](https://github.com/expressive-code/expressive-code) library.
You can set translations for its UI strings in the same JSON file using `expressiveCode` keys:

```json
{
"expressiveCode.copyButtonCopied": "Copied!",
"expressiveCode.copyButtonTooltip": "Copy to clipboard",
"expressiveCode.terminalWindowFallbackTitle": "Terminal window"
}
```

Starlight’s search modal is powered by the [Pagefind](https://pagefind.app/) library.
You can set translations for Pagefind’s UI in the same JSON file using `pagefind` keys:

Expand Down
34 changes: 34 additions & 0 deletions docs/src/content/docs/reference/configuration.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,40 @@ type LogoConfig = { alt?: string; replacesTitle?: boolean } & (

Configure the table of contents shown on the right of each page. By default, `<h2>` and `<h3>` headings will be included in this table of contents.

### `expressiveCode`

**type:** `StarlightExpressiveCodeOptions | boolean`

Starlight uses [Expressive Code](https://github.com/expressive-code/expressive-code) to render code blocks on your site. The integration is enabled by default and can be disabled by passing `false` to this option.

You can customize your code blocks by passing an object with any of the following properties:

- `theme` — the color theme(s) that should be used to render code blocks. Supported values:
- any theme name bundled with Shiki (e.g. `dracula`)
- any theme object compatible with VS Code or Shiki (e.g. imported from an NPM theme package)
- any ExpressiveCodeTheme instance (e.g. using `ExpressiveCodeTheme.fromJSONString(...)` to load a custom JSON/JSONC theme file yourself)
- any combination of the above in an array

Defaults to the `['github-dark', 'github-light']` themes bundled with Shiki.

**Note**: If you pass an array of themes to this option, each code block in your markdown/MDX documents will be rendered using all themes. If you pass one dark and one light theme, Starlight will by default automatically add CSS to show only the theme that matches the current dark mode switch state. See the `useStarlightDarkModeSwitch` option to configure this behavior. If you turn it off, you will need to add your own CSS code to the site to ensure that only one theme is visible at any time.

To allow targeting all code blocks of a given theme through CSS, the theme property `name` is used to generate kebap-cased class names in the format `ec-theme-${name}`. For example, `theme: ['monokai', 'slack-ochin']` will render every code block twice, once with the class `ec-theme-monokai`, and once with `ec-theme-slack-ochin`.

- `useStarlightDarkModeSwitch` — determines if CSS code should be added that automatically displays dark or light code blocks depending on Starlight's dark mode switch state.

Defaults to `true` if the `theme` option is not set or contains one dark and one light theme, and `false` otherwise.

- `useStarlightUiThemeColors` — determines if Starlight's CSS variables should be used for the colors of UI elements (backgrounds, buttons, shadows etc.) instead of the colors provided by themes.

Defaults to `true` if the `theme` option is not set (= you are using the default themes), and `false` otherwise.

- `minSyntaxHighlightingColorContrast` — determines if Starlight should process the syntax highlighting colors of all themes to ensure an accessible minimum contrast ratio between foreground and background colors.

Defaults to `5.5`, which ensures a contrast ratio of at least 5.5:1. You can change the desired contrast ratio by providing another value, or turn the feature off by setting this option to `0`.

- See the [Expressive Code documentation](https://github.com/expressive-code/expressive-code/blob/main/packages/astro-expressive-code/README.md#configuration) to learn about all the other options.

### `editLink`

**type:** `{ baseUrl: string }`
Expand Down
4 changes: 4 additions & 0 deletions packages/starlight/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { spawn } from 'node:child_process';
import { dirname, relative } from 'node:path';
import { fileURLToPath } from 'node:url';
import { starlightAsides } from './integrations/asides';
import { starlightExpressiveCode } from './integrations/expressive-code';
import { starlightSitemap } from './integrations/sitemap';
import { vitePluginStarlightUserConfig } from './integrations/virtual-user-config';
import { errorMap } from './utils/error-map';
Expand Down Expand Up @@ -35,6 +36,9 @@ export default function StarlightIntegration(opts: StarlightUserConfig): AstroIn
entryPoint: '@astrojs/starlight/index.astro',
});
const integrations: AstroIntegration[] = [];
if (!config.integrations.find(({ name }) => name === 'astro-expressive-code')) {
integrations.push(...starlightExpressiveCode(userConfig));
}
if (!config.integrations.find(({ name }) => name === '@astrojs/sitemap')) {
integrations.push(starlightSitemap(userConfig));
}
Expand Down
265 changes: 265 additions & 0 deletions packages/starlight/integrations/expressive-code.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,265 @@
import path from 'node:path';
import fs from 'node:fs';
import {
astroExpressiveCode,
ExpressiveCodeTheme,
type AstroExpressiveCodeOptions,
ensureColorContrastOnBackground,
pluginFramesTexts,
PluginTexts,
type ThemeObjectOrShikiThemeName,
} from 'astro-expressive-code';
import type { AstroIntegration } from 'astro';
import type { StarlightConfig } from '../types';
import translations from '../translations';

export * from 'astro-expressive-code';

export type StarlightExpressiveCodeOptions = Omit<AstroExpressiveCodeOptions, 'theme' | 'useThemedSelectionColors'> & {
/**
* The color theme(s) that Starlight should use to render code blocks. Supported value types:
* - any theme name bundled with Shiki (e.g. `dracula`)
* - any theme object compatible with VS Code or Shiki (e.g. imported from an NPM theme package)
* - any ExpressiveCodeTheme instance (e.g. using `ExpressiveCodeTheme.fromJSONString(...)`
* to load a custom JSON/JSONC theme file yourself)
* - any combination of the above in an array
*
* Defaults to the `['github-dark', 'github-light']` themes bundled with Shiki.
*
* **Note**: If you pass an array of themes to this option, each code block in your
* markdown/MDX documents will be rendered using all themes. If you pass one dark and one light
* theme, Starlight will by default automatically add CSS to show only the theme that matches
* the current dark mode switch state. See the `useStarlightDarkModeSwitch` option to configure
* this behavior. If you turn it off, you will need to add your own CSS code to the site
* to ensure that only one theme is visible at any time.
*
* To allow targeting all code blocks of a given theme through CSS, the theme property `name`
* is used to generate kebap-cased class names in the format `ec-theme-${name}`.
* For example, `theme: ['monokai', 'slack-ochin']` will render every code block twice,
* once with the class `ec-theme-monokai`, and once with `ec-theme-slack-ochin`.
*/
theme?: ThemeObjectOrShikiThemeName | ThemeObjectOrShikiThemeName[] | undefined;
/**
* By default, Starlight renders selected text in code blocks using the browser's
* default style to maximize accessibility. If you want your selections to be more colorful,
* you can set this option to `true` to allow using theme selection colors instead.
*
* Note that you can override the individual selection colors defined by the theme
* using the `styleOverrides` option.
*/
useThemedSelectionColors?: boolean | undefined;
/**
* Determines if CSS code should be added to the site that automatically displays
* dark or light code blocks depending on Starlight's dark mode switch state.
*
* Defaults to `true` if the `theme` option is not set or contains one dark and one light theme,
* and `false` otherwise.
*/
useStarlightDarkModeSwitch?: boolean | undefined;
/**
* Determines if Starlight's CSS variables should be used for the colors of UI elements
* (backgrounds, buttons, shadows etc.) instead of the colors provided by themes.
*
* Defaults to `true` if the `theme` option is not set (= you are using the default themes),
* and `false` otherwise.
*/
useStarlightUiThemeColors?: boolean | undefined;
/**
* Determines if Starlight should process the syntax highlighting colors of all themes
* to ensure an accessible minimum contrast ratio between foreground and background colors.
*
* Defaults to `5.5`, which ensures a contrast ratio of at least 5.5:1.
* You can change the desired contrast ratio by providing another value,
* or turn the feature off by setting this option to `0`.
*/
minSyntaxHighlightingColorContrast?: number | undefined;
};

export const starlightExpressiveCode = (opts: StarlightConfig): AstroIntegration[] => {
const { locales, defaultLocale, expressiveCode } = opts;
if (expressiveCode === false) return [];
const config = typeof expressiveCode === 'object' ? expressiveCode : {};

const {
theme = ['github-dark', 'github-light'],
customizeTheme,
useThemedSelectionColors = false,
styleOverrides: {
textMarkers: textMarkersStyleOverrides,
...otherStyleOverrides
} = {},
useStarlightDarkModeSwitch,
useStarlightUiThemeColors = config.theme === undefined,
minSyntaxHighlightingColorContrast = 5.5,
plugins = [],
...rest
} = config;

const configuredThemesCount = (Array.isArray(theme) && theme.length) || 1;
if (useStarlightDarkModeSwitch !== false) {
const loadedThemes: ExpressiveCodeTheme[] = [];
const darkModeSwitchCss: string[] = [];
plugins.push({
name: 'Starlight Dark Mode Switch',
baseStyles: ({ theme, themeClassName }) => {
loadedThemes.push(theme);
darkModeSwitchCss.push(`
:root:not([data-theme='${theme.type}']) .${themeClassName} {
display: none;
}
`);
if (loadedThemes.length !== configuredThemesCount) return '';
const foundDarkThemes = loadedThemes.filter((t) => t.type === 'dark').length;
const foundLightThemes = loadedThemes.filter((t) => t.type === 'light').length;
const configuredThemesSupportDarkModeSwitch =
foundDarkThemes === 1 && foundLightThemes === 1;
if (!configuredThemesSupportDarkModeSwitch) {
if (useStarlightDarkModeSwitch === true)
console.warn(
`*** Warning: To support the config option "useStarlightDarkModeSwitch: true", please provide 1 dark and 1 light theme (found ${foundDarkThemes} and ${foundLightThemes}).\n`
);
return '';
}
return darkModeSwitchCss.join('\n');
},
});
}

if (useStarlightUiThemeColors === true && configuredThemesCount < 2)
console.warn(`*** Warning: Using the config option "useStarlightUiThemeColors: true" with only one theme is not recommended. For better color contrast, please provide 1 dark and 1 light theme.\n`);

// Add Expressive Code UI translations (if any) for all defined locales
if (locales) {
for (const locale in locales) {
const lang = locales[locale]?.lang;
if (!lang) continue;

addTranslations(lang, pluginFramesTexts, [
'expressiveCode.copyButtonCopied',
'expressiveCode.copyButtonTooltip',
'expressiveCode.terminalWindowFallbackTitle',
]);
}
}

return [
astroExpressiveCode({
theme,
customizeTheme: (theme) => {
if (useStarlightUiThemeColors) {
applyStarlightUiThemeColors(theme);
}
if (customizeTheme) {
theme = customizeTheme(theme) ?? theme;
}
if (minSyntaxHighlightingColorContrast > 0) {
ensureMinTokenColorContrast(theme, minSyntaxHighlightingColorContrast);
}
return theme;
},
useThemedSelectionColors,
styleOverrides: {
codeFontFamily: 'var(--__sl-font-mono)',
hippotastic marked this conversation as resolved.
Show resolved Hide resolved
codeFontSize: 'var(--sl-text-code)',
codeLineHeight: 'var(--sl-line-height)',
uiFontFamily: 'var(--__sl-font)',
textMarkers: {
defaultChroma: '45',
backgroundOpacity: '60%',
...textMarkersStyleOverrides,
},
hippotastic marked this conversation as resolved.
Show resolved Hide resolved
...otherStyleOverrides,
},
getBlockLocale: ({ file }) => {
// Root path: `src/content/docs/getting-started.mdx`
// Locale path: `src/content/docs/fr/getting-started.mdx`
// Part indices: 0 1 2 3 4
const pathParts = path.relative(file.cwd, file.path).split(/[\\/]/);
const localeOrFolder = pathParts[3];
const lang = localeOrFolder ? locales?.[localeOrFolder]?.lang : locales?.root?.lang;
const defaultLang = defaultLocale?.lang || defaultLocale?.locale;
const result = lang || defaultLang || 'en';

return result;
},
plugins,
...rest,
}),
];
};

function addTranslations<T extends PluginTexts<any>>(
lang: string,
target: T,
ids: (keyof (typeof translations)['en'])[]
) {
const builtinTexts = translations[lang];
let userTexts: Partial<(typeof translations)['en']> = {};
try {
// As Astro has not been initialized yet, we cannot use content collections directly
// and have to manually load any user-provided translations from the file system
userTexts = JSON.parse(fs.readFileSync(`src/content/i18n/${lang}.json`, 'utf8'));
delucis marked this conversation as resolved.
Show resolved Hide resolved
} catch (error) {
// We can safely ignore loading errors here as they will be reported by Starlight later
// if the JSON file exists and is invalid
}
ids.forEach((id) => {
const translation = userTexts[id] || builtinTexts?.[id];
if (!translation) return;
const ecId = (id as string).replace(/^expressiveCode\./, '');
target.overrideTexts(lang, { [ecId]: translation });
});
}

export function applyStarlightUiThemeColors(theme: ExpressiveCodeTheme) {
// Make borders slightly transparent
const borderColor = 'color-mix(in srgb, var(--sl-color-gray-5), transparent 25%)';
theme.colors['titleBar.border'] = borderColor;
theme.colors['editorGroupHeader.tabsBorder'] = borderColor;

// Use the same color for terminal title bar background and editor tab bar background
const backgroundColor =
theme.type === 'dark' ? 'var(--sl-color-black)' : 'var(--sl-color-gray-6)';
theme.colors['titleBar.activeBackground'] = backgroundColor;
theme.colors['editorGroupHeader.tabsBackground'] = backgroundColor;

// Use the same color for terminal titles and tab titles
theme.colors['titleBar.activeForeground'] = 'var(--sl-color-text)';
theme.colors['tab.activeForeground'] = 'var(--sl-color-text)';

// Set tab border colors
const activeBorderColor =
theme.type === 'dark' ? 'var(--sl-color-accent-high)' : 'var(--sl-color-accent)';
theme.colors['tab.activeBorder'] = 'transparent';
theme.colors['tab.activeBorderTop'] = activeBorderColor;

// Set theme `bg` color property for contrast calculations
theme.bg = theme.type === 'dark' ? '#23262f' : '#f6f7f9'
// Set actual background color to the appropriate Starlight CSS variable
const editorBackgroundColor =
theme.type === 'dark' ? 'var(--sl-color-gray-6)' : 'var(--sl-color-gray-7)';

theme.styleOverrides.frames = {
// Use the same color for editor background, terminal background and active tab background
editorBackground: editorBackgroundColor,
terminalBackground: editorBackgroundColor,
editorActiveTabBackground: editorBackgroundColor,
terminalTitlebarDotsForeground: borderColor,
terminalTitlebarDotsOpacity: '0.75',
inlineButtonForeground: 'var(--sl-color-text)',
frameBoxShadowCssValue: 'var(--sl-shadow-sm)',
hippotastic marked this conversation as resolved.
Show resolved Hide resolved
};

return theme;
}

export function ensureMinTokenColorContrast(theme: ExpressiveCodeTheme, minContrast: number) {
theme.settings.forEach((s) => {
if (!s.settings.foreground) return
const newColor = ensureColorContrastOnBackground(s.settings.foreground, theme.bg, minContrast);
if (newColor === s.settings.foreground) return
s.settings.foreground = newColor
})

return theme;
}
2 changes: 2 additions & 0 deletions packages/starlight/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -157,6 +157,7 @@
"./props": "./props.ts",
"./schema": "./schema.ts",
"./types": "./types.ts",
"./expressive-code": "./integrations/expressive-code.ts",
delucis marked this conversation as resolved.
Show resolved Hide resolved
"./index.astro": "./index.astro",
"./404.astro": "./404.astro"
},
Expand All @@ -174,6 +175,7 @@
"@astrojs/sitemap": "^3.0.0",
"@pagefind/default-ui": "^1.0.3",
"@types/mdast": "^3.0.11",
"astro-expressive-code": "^0.26.0",
"bcp-47": "^2.1.0",
"execa": "^8.0.1",
"hast-util-select": "^5.0.5",
Expand Down
11 changes: 11 additions & 0 deletions packages/starlight/schemas/expressiveCode.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import { z } from 'astro/zod';
import type { StarlightExpressiveCodeOptions } from '../integrations/expressive-code';

export const ExpressiveCodeSchema = () =>
z
.union([
z.custom<StarlightExpressiveCodeOptions>((value) => typeof value === 'object' && value),
delucis marked this conversation as resolved.
Show resolved Hide resolved
z.boolean(),
])
.describe('Define how code blocks are rendered by passing options to Expressive Code, or disable the integration by passing `false`.')
.optional();
Loading