diff --git a/.agents/DECISIONS.md b/.agents/DECISIONS.md index f37c44c..f6101b4 100644 --- a/.agents/DECISIONS.md +++ b/.agents/DECISIONS.md @@ -96,6 +96,7 @@ The choices that the code does not explain, with the options that were rejected. - **Expandable blocks collapse only in the client**, with `hidden="until-found"`, so a block is complete without JavaScript and find in page reveals lines. Collapsed lines use `content-visibility: hidden` because EC's `all: revert` removes the browser's until-found style. `auto` skips code tabs variants, runnable blocks and collapsible sections; the components remove an `auto` cap. - **The hidden-lines toggle label changes, with no `aria-pressed`**, which would contradict the label. Open hidden lines dim to 0.75 opacity by the user's choice; syntax colours stay at 3:1 or more, and the accessibility page lists it as an exception with `openOpacity: '1'` to turn it off. - **A manual selection leaves out closed hidden lines.** The copy button includes them. *Rejected:* a `copy` handler that adds them (the paste would differ from the selection). +- **Skipped code restyles a `// ...` line; it is not a marker between lines.** `[!code skip]` and its aliases stay a line of the block, by the user's choice, as the `// ...` comments they replace were: the line keeps its number, ranges count it, and it copies as a plain comment (`// text`, or `// ...` without text; an alias line as written). The comment stays in the line, selectable and `aria-hidden`, clipped like screen reader text (Chromium leaves zero-width text and flex items out of a selection); the badge after the indentation is the decoration, so screen readers read the badge and copy matches the line. The directive takes no `:N` and does nothing on a line with code, because it stands for a line of its own. Aliases are `commentAliases` (a comment that holds only the alias) and `bareAliases` (the alias alone on its line), each a map by language with `*` for the rest, so a site can read a bare `...` in YAML without reading it everywhere. A language entry replaces `*`, so `[]` opts a language out, and the site's keys merge over the defaults, so adding YAML keeps JSON. Defaults are `{ '*': ['...'] }` and `{ json: ['...'] }`, as an alias only changes how a line looks. The examples are for reading, not running, so the docs do not warn about bare aliases in languages where `...` is code. Aliases take no text, so `// ... more` stays as written. A language with `[]` in `notation.comments` has no comment syntax, so it reads no comment aliases, which keeps `...` in the docs' `md` source panes. *Rejected:* aliases off by default (existing `// ...` lines are what the feature is for); one `aliases` list with bare aliases only in JSON; a marker between lines with no line number (ranges after it moved, and it needed special cases at the end of a block, in hidden runs, in output and in print); copying nothing for the line; a `skip={range}` attribute (a range names lines, not the gaps between them); `:N` as a count of skipped lines that makes line numbers jump. ### Copy, run, playgrounds, placeholders diff --git a/.github/assets/readme/skipped-code.png b/.github/assets/readme/skipped-code.png new file mode 100644 index 0000000..bbb08dd Binary files /dev/null and b/.github/assets/readme/skipped-code.png differ diff --git a/AGENTS.md b/AGENTS.md index 15536b4..5be260b 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1,6 +1,6 @@ # Agent instructions -`starlight-codeblocks` is a Starlight plugin that adds 28 code block features on top of Expressive Code (EC), which renders every code block in Starlight. `packages/starlight-codeblocks/` is the plugin, `docs/` its Starlight docs site (it uses the plugin through `workspace:*`, and defines each feature's syntax and behaviour), `examples/astro/` a minimal Astro site without Starlight, and `skills/starlight-codeblocks/` an agent skill for people who use the plugin. +`starlight-codeblocks` is a Starlight plugin that adds 29 code block features on top of Expressive Code (EC), which renders every code block in Starlight. `packages/starlight-codeblocks/` is the plugin, `docs/` its Starlight docs site (it uses the plugin through `workspace:*`, and defines each feature's syntax and behaviour), `examples/astro/` a minimal Astro site without Starlight, and `skills/starlight-codeblocks/` an agent skill for people who use the plugin. - `.agents/DECISIONS.md`: design decisions and the rejected options. Search it before you change existing behaviour. - `.agents/WRITING-STYLE.md`: how the docs read, the feature page template and the glossary. diff --git a/README.md b/README.md index 5ce0b10..26cd8ac 100644 --- a/README.md +++ b/README.md @@ -2,7 +2,7 @@ starlight-codeblocks -A Starlight and Astro plugin that adds 28 features to code blocks, such as focus, line states, annotations, links to API docs and runnable examples. It builds on Expressive Code, so the code blocks you already have keep working. +A Starlight and Astro plugin that adds 29 features to code blocks, such as focus, line states, annotations, links to API docs and runnable examples. It builds on Expressive Code, so the code blocks you already have keep working. Using an agent? [Point it at the bundled skill](https://ewels.github.io/starlight-codeblocks/agent-skill/). @@ -244,6 +244,25 @@ Hide the imports and set-up that readers need to run an example but not to under +
+Skipped code + +Show a marker where a code block leaves out code, so readers know the file has more lines there. The copied code has no marker. + +````md +```js +app.get('/users', async (req, res) => { + // [!code skip] Not shown: Read the users from the database +}); +``` +```` + +A JavaScript block with a dotted line and the text Not shown: Read the users from the database in place of a function body. + +[Skipped code documentation](https://ewels.github.io/starlight-codeblocks/features/skipped-code/) + +
+
Expandable blocks diff --git a/docs/e2e/carousel.test.ts b/docs/e2e/carousel.test.ts index dcc253c..ecb8e00 100644 --- a/docs/e2e/carousel.test.ts +++ b/docs/e2e/carousel.test.ts @@ -149,7 +149,7 @@ test('a button or a dot shows its example, announces it and marks itself, and th await expect(page.locator('.carousel .slide:not([data-current])').first()).toBeHidden(); await expect(page.locator('.carousel .tile[aria-pressed="true"]')).toHaveCount(1); await expect(tile(page, 'Word-level diff')).toHaveAttribute('aria-pressed', 'true'); - await expect(page.locator('.carousel [data-status]')).toHaveText('Word-level diff, 18 of 27'); + await expect(page.locator('.carousel [data-status]')).toHaveText('Word-level diff, 19 of 28'); // The current button differs by more than colour. expect(await css(tile(page, 'Word-level diff'), 'fontWeight')).toBe('600'); expect(await css(tile(page, 'Footnotes'), 'fontWeight')).toBe('400'); @@ -159,7 +159,7 @@ test('a button or a dot shows its example, announces it and marks itself, and th await expect(dot(page, 'Focus')).toHaveAttribute('aria-current', 'true'); await expect(dot(page, 'Word-level diff')).toHaveAttribute('aria-current', 'false'); await expect(tile(page, 'Focus')).toHaveAttribute('aria-pressed', 'true'); - await expect(page.locator('.carousel [data-status]')).toHaveText(/^Focus, \d+ of 27$/); + await expect(page.locator('.carousel [data-status]')).toHaveText(/^Focus, \d+ of 28$/); await expect(page.locator('.carousel .rotation')).toHaveAccessibleName('Play'); }); @@ -173,8 +173,8 @@ test('the buttons are a flat list in sidebar order, in columns, with one dot eac await page.goto('./'); await expect(page.locator('.carousel .group-label')).toHaveCount(0); const tiles = page.locator('.carousel .tile'); - await expect(tiles).toHaveCount(27); - await expect(page.locator('.carousel .tile svg[aria-hidden], .carousel .tile [aria-hidden] svg')).toHaveCount(27); + await expect(tiles).toHaveCount(28); + await expect(page.locator('.carousel .tile svg[aria-hidden], .carousel .tile [aria-hidden] svg')).toHaveCount(28); const tileIds = await tiles.evaluateAll((els) => els.map((el) => el.getAttribute('data-feature'))); expect(tileIds).toEqual(sidebarIds.filter((id) => tileIds.includes(id))); @@ -189,9 +189,9 @@ test('the buttons are a flat list in sidebar order, in columns, with one dot eac expect(boxes.every(([x], i) => i === 0 || x >= (boxes[i - 1]?.[0] ?? 0))).toBe(true); for (const column of columns) expect(column).toEqual((columns[0] ?? []).slice(0, column.length)); // The phone viewport (360px) is too narrow for the auto column width, so it's forced to two. - if (phone()) expect(lengths).toEqual([14, 13]); + if (phone()) expect(lengths).toEqual([14, 14]); - await expect(page.locator('.carousel .dot')).toHaveCount(27); + await expect(page.locator('.carousel .dot')).toHaveCount(28); const order = await page.locator('.carousel .controls > *').evaluateAll((els) => els.map((el) => el.className)); expect(order.at(-1)).toContain('rotation'); }); @@ -316,7 +316,7 @@ test.describe('without JavaScript', () => { 'href', '/starlight-codeblocks/features/focus/', ); - await expect(page.locator('.carousel a.tile')).toHaveCount(27); + await expect(page.locator('.carousel a.tile')).toHaveCount(28); const docsLink = page.getByRole('link', { name: 'Read docs : Annotations' }); await expect(docsLink).toBeVisible(); await expect(docsLink).toHaveAttribute('href', '/starlight-codeblocks/features/annotations/'); diff --git a/docs/e2e/skipped-code.test.ts b/docs/e2e/skipped-code.test.ts new file mode 100644 index 0000000..ceeeb1a --- /dev/null +++ b/docs/e2e/skipped-code.test.ts @@ -0,0 +1,58 @@ +import { expect, test } from '@playwright/test'; +import { example } from './helpers.ts'; + +test.beforeEach(async ({ page }) => { + await page.goto('./features/skipped-code/'); +}); + +test('a marker starts at the indentation of its directive line, and every marker has the same height', async ({ + page, +}) => { + const markers = example(page).locator('.scb-skip-marker'); + await expect(markers).toHaveCount(2); + const result = await example(page) + .locator('pre code') + .evaluate((code) => { + const left = (el: Element) => el.getBoundingClientRect().left; + const range = document.createRange(); + range.selectNodeContents(code.querySelector('.ec-line .code span') as Node); + const probe = document.createElement('span'); + probe.textContent = 'xx'; + code.append(probe); + const ch = probe.getBoundingClientRect().width / 2; + probe.remove(); + const [indented, plain] = [...code.querySelectorAll('.scb-skip-marker')]; + const text = (marker?: Element) => left(marker?.querySelector('.scb-skip-text') as Element); + return { + lineStart: range.getBoundingClientRect().left, + indented: text(indented), + plain: text(plain), + ch, + heights: [indented, plain].map((m) => m?.getBoundingClientRect().height), + }; + }); + expect(Math.abs(result.plain - result.lineStart)).toBeLessThan(1); + expect(Math.abs(result.indented - result.plain - 2 * result.ch)).toBeLessThan(1); + expect(Math.abs((result.heights[0] ?? 0) - (result.heights[1] ?? 0))).toBeLessThan(1); +}); + +test('a manual selection copies each marker as its comment, as the copy button does', async ({ page }) => { + const { selected, copied } = await example(page) + .locator('figure') + .evaluate((figure) => { + getSelection()?.selectAllChildren(figure.querySelector('pre code') as Node); + return { + selected: getSelection()?.toString(), + copied: figure.querySelector('button[data-code]')?.getAttribute('data-code')?.replaceAll('\x7F', '\n'), + }; + }); + expect(selected).toContain(' // Not shown: Read the users from the database\n'); + expect(selected).not.toContain('Code not shown'); + expect(selected?.trimEnd()).toBe(copied?.trimEnd()); +}); + +test('a marker line hides its comment and shows its text', async ({ page }) => { + const line = example(page).locator('.scb-skip-line').first(); + await expect(line.locator('.scb-skip-source')).toHaveCSS('clip-path', 'inset(50%)'); + await expect(line.locator('.scb-skip-text')).toBeVisible(); +}); diff --git a/docs/src/components/FeatureCarousel.astro b/docs/src/components/FeatureCarousel.astro index c8ffa35..1066c1c 100644 --- a/docs/src/components/FeatureCarousel.astro +++ b/docs/src/components/FeatureCarousel.astro @@ -18,6 +18,7 @@ const icons: Record = { 'features/split-diff': lucide.GitCompare, 'features/code-walkthrough': lucide.Replace, 'features/hidden-lines': lucide.EyeOff, + 'features/skipped-code': lucide.Ellipsis, 'features/expandable-blocks': lucide.ChevronsUpDown, 'features/visible-whitespace': lucide.Pilcrow, 'features/colourised-brackets': lucide.Braces, diff --git a/docs/src/content/docs/comment-notation.mdx b/docs/src/content/docs/comment-notation.mdx index 4ae00a6..86dafa4 100644 --- a/docs/src/content/docs/comment-notation.mdx +++ b/docs/src/content/docs/comment-notation.mdx @@ -283,7 +283,9 @@ codeblocks({ }); ``` -An entry replaces the built-in syntax of that language. A language name or its alias works: an entry for `powershell` also applies to ` ```pwsh `. The built-in map: +An entry replaces the built-in syntax of that language. A language name or its alias works: an entry for `powershell` also applies to ` ```pwsh `. + +An empty list, such as `md: []`, turns off directives for that language, and the comment aliases of [skipped code](/starlight-codeblocks/features/skipped-code/). The built-in map: diff --git a/docs/src/content/docs/features/code-walkthrough.mdx b/docs/src/content/docs/features/code-walkthrough.mdx index 71f9a7a..c5f4fcc 100644 --- a/docs/src/content/docs/features/code-walkthrough.mdx +++ b/docs/src/content/docs/features/code-walkthrough.mdx @@ -247,6 +247,7 @@ def greet(name, greeting="Hello"): - A line that is new in the step gets a green tint, which fades out in 1 second. The green is the terminal green of the theme. - When the reader's system asks for reduced motion, the steps change without the animation. - A step with removed or added lines changes without the animation, so its diff colours and `+` and `-` markers stay in place. + - A step with a callout or a hidden lines marker changes without the animation. The animation does not have the height of these rows. ## Options diff --git a/docs/src/content/docs/features/skipped-code.mdx b/docs/src/content/docs/features/skipped-code.mdx new file mode 100644 index 0000000..4da514a --- /dev/null +++ b/docs/src/content/docs/features/skipped-code.mdx @@ -0,0 +1,197 @@ +--- +title: Skipped code +description: Show a marker where a code block leaves out code, so readers know the file has more lines there. +--- + +import { LinkCard } from '@astrojs/starlight/components'; +import Example from '../../../components/Example.astro'; +import Options from '../../../components/Options.astro'; + +An example often shows only part of a file. Authors then write a comment such as `// ...` where code is left out, and readers can mistake it for code. Skipped code draws that line as a marker, which looks different from the code. The line keeps its line number, and copies as a plain comment. Write the `[!code skip]` directive, with optional text. Existing `// ...` comments also show as markers, through [aliases](#aliases). + +export const basic = ` +\`\`\`js title="routes.js" +const app = express(); + +app.get('/users', async (req, res) => { + // [!code skip] Not shown: Read the users from the database +}); + +app.post('/users', async (req, res) => { + const user = await db.users.create(req.body); + res.status(201).json(user); +}); +// [!code skip] +\`\`\` +`; + + + +The first marker replaces the body of the `get` handler and shows the text after the directive. The second marker shows that the file goes on after the last line. Copying the block gives each marker as a comment, such as `// Not shown: Read the users from the database`. + +## Syntax + +| Syntax | Where | +|---|---| +| `[!code skip]` | Comment on its own line | +| `[!code skip] text` | Comment on its own line | + +Put the directive on its own line where the code is left out. That line shows as the marker, at the same indentation. Without text, the marker reads "Code not shown". The text can hold inline code, links and bold text. + +## Aliases + +Many pages already use `// ...` for code that they leave out. These lines are the same as `[!code skip]` by default, so existing pages show markers with no changes. A line is an alias if it holds one of these, and nothing else: + +- A comment alias: a comment with only the alias in it, in the comment syntax of the language, such as `// ...`, `# ...`, `/* ... */` or ``. By default, `...` in every language. +- A bare alias: the alias with no comment. By default, `...` in JSON. + +:::note[JSON] +JSON has no comments, so a JSON block cannot hold the `[!code skip]` directive. The default config has a bare alias for JSON, `bareAliases: { json: ['...'] }`, so write `...` alone on a line instead. +::: + +This JSON block shows two markers: + +export const json = ` +\`\`\`json title="package.json" +{ + "name": "my-site", + "scripts": { + "dev": "astro dev", + ... + }, + ... +} +\`\`\` +`; + + + +An alias changes only how the line looks. The line keeps its line number, line ranges count it, and the copied code has the `// ...` as written. An alias takes no text: for a marker with text, write `[!code skip] text`. + +Set `skippedCode.commentAliases` and `skippedCode.bareAliases` to change the aliases. Each is a list of aliases for each language, and `*` applies to every language without its own entry. The defaults are `commentAliases: { '*': ['...'] }` and `bareAliases: { json: ['...'] }`. Your entries merge over them, and `[]` turns aliases off for a language: + +```js title="astro.config.mjs" +codeblocks({ + skippedCode: { + // [!callout /commentAliases/] `// …` as well as `// ...`, and no comment aliases in Python. + commentAliases: { '*': ['...', '…'], python: [] }, + // [!callout /bareAliases/] `...` with no comment in YAML. JSON keeps its default. + bareAliases: { yaml: ['...'] }, + }, +}); +``` + +A language name or its alias works as a key: `yaml` also applies to ` ```yml `. To keep `// ...` as code in one block, add text to the comment, such as `// ... and so on`. A language with `[]` in `notation.comments` has no comment syntax, so it reads no comment aliases. + +## Examples + +### Skip code without text + +Without text, the marker reads "Code not shown". Use it when the code around the marker tells readers what is left out: + +export const noText = ` +\`\`\`ts title="cache.ts" +export class Cache { + private entries = new Map(); + + // [!code skip] + + get(key: string): T | undefined { + return this.entries.get(key); + } + // [!code skip] +} +\`\`\` +`; + + + +### Skip the start of a file + +A marker on the first line shows that the example starts in the middle of a file: + +export const start = ` +\`\`\`py title="report.py" +# [!code skip] Not shown: Imports and settings +def summarise(rows): + totals = {} + for row in rows: + totals[row["status"]] = totals.get(row["status"], 0) + 1 + return totals +\`\`\` +`; + + + +### Skip a section of a configuration file + +YAML uses `#` comments. For JSON, use `jsonc`, because JSON has no comments: + +export const config = ` +\`\`\`yaml title="docker-compose.yml" +services: + web: + image: nginx:1.27 + ports: + - "8080:80" + # [!code skip] Not shown: The database and cache services +volumes: + data: +\`\`\` +`; + + + +### Link to lines after a marker + +The marker is a line of the block, so it has a line number. With [line permalinks](/starlight-codeblocks/features/line-permalinks/), which the `id` attribute turns on, each number is a link. The `app.get` line below is line 3, as in the source: + +export const permalinks = ` +\`\`\`js title="routes.js" id="routes" +const app = express(); +// [!code skip] Not shown: Middleware and settings +app.get('/users', async (req, res) => { + const users = await db.users.findAll(); + res.json(users); +}); +\`\`\` +`; + + + +## Behaviour + +- The marker: + - A dotted rule across the line, with the text in a badge at the indentation of the directive line. + - The marker is not a button. Readers cannot open it, because the code is not in the block. +- Line numbers and ranges: + - The marker is a line of the block. It has a line number, and line ranges such as `{4}` count it. + - The line numbers do not jump over the skipped code. +- Copy and selection: + - The copy button and a manual selection copy the marker as a comment, such as `// ...`. The comment holds the text of the directive, or `...` when it has none. An alias line copies as written. +- Screen readers: + - Screen readers read the text of the marker in its place among the lines, and not the comment. +- Print: + - Markers print. + +## Options + + + +Turn the feature off for the whole site with `skippedCode: false`. The plugin then does not know the `[!code skip]` directive. It leaves the directive in the code as written, and logs a build warning. + + + +## Limitations + +- The directive needs a comment. JSON has no comments and can use only bare aliases, so its markers have no text. +- The directive goes on a line of its own. On a line with code, the plugin logs a warning and leaves it out. +- During the animation of a code walkthrough or scrollycoding step, a marker line shows empty. +- Line numbers do not jump over the skipped code. To start a block at a later number, use the `startLineNumber` attribute of Expressive Code. +- The copied code is incomplete, so it can fail to run. Do not use skipped code in a block with a **Run code** or playground button. + +## Related + +- [Hidden lines](/starlight-codeblocks/features/hidden-lines/): keep the lines in the block and the copied code, behind a marker that readers can open. +- [Expandable blocks](/starlight-codeblocks/features/expandable-blocks/): show a full file, cut to its first lines until the reader asks for the rest. +- [Comment notation](/starlight-codeblocks/comment-notation/): the directive syntax that `[!code skip]` uses. diff --git a/docs/src/content/docs/index.mdx b/docs/src/content/docs/index.mdx index 1a7590f..f94c328 100644 --- a/docs/src/content/docs/index.mdx +++ b/docs/src/content/docs/index.mdx @@ -4,7 +4,7 @@ description: A plugin for Starlight and Astro that adds focus, line states, anno template: splash hero: tagline: | - This plugin adds 28 features to the Expressive Code blocks of + This plugin adds 29 features to the Expressive Code blocks of Starlight and Astro sites. Use them to enrich code blocks. Using an agent? Point it at the bundled skill. @@ -231,6 +231,24 @@ for key, value in config.items(): + + +```js title="routes.js" +const app = express(); + +app.get('/users', async (req, res) => { + // [!code skip] Not shown: Read the users from the database +}); + +app.post('/users', async (req, res) => { + const user = await db.users.create(req.body); + res.status(201).json(user); +}); +// [!code skip] +``` + + + ```py title="report.py" expandable={8} apiLinks=false diff --git a/docs/src/content/docs/reference/expressive-code-plugins.mdx b/docs/src/content/docs/reference/expressive-code-plugins.mdx index 3e26b68..314bdf6 100644 --- a/docs/src/content/docs/reference/expressive-code-plugins.mdx +++ b/docs/src/content/docs/reference/expressive-code-plugins.mdx @@ -67,6 +67,7 @@ Each plugin takes the settings of its option, as the [options reference](/starli | `pluginPlaceholders(settings)` | `placeholders` | [Fill-in placeholders](/starlight-codeblocks/features/fill-in-placeholders/) | | `pluginMentions()` | `mentions` | [Code mentions](/starlight-codeblocks/features/code-mentions/) | | `pluginPermalinks()` | `permalinks` | [Line permalinks](/starlight-codeblocks/features/line-permalinks/) | +| `pluginSkippedCode()` | `skippedCode` | [Skipped code](/starlight-codeblocks/features/skipped-code/) | | `pluginHiddenLines()` | `hiddenLines` | [Hidden lines](/starlight-codeblocks/features/hidden-lines/) | | `pluginExpandable(settings)` | `expandable` | [Expandable blocks](/starlight-codeblocks/features/expandable-blocks/) | | `pluginPlayground(playgrounds)` | `playgrounds` | [Open in playground](/starlight-codeblocks/features/open-in-playground/) | diff --git a/docs/src/sidebar.mjs b/docs/src/sidebar.mjs index 1bbd3ec..c537bb0 100644 --- a/docs/src/sidebar.mjs +++ b/docs/src/sidebar.mjs @@ -29,6 +29,7 @@ export const sidebar = [ label: 'Make code easier to read', items: [ 'features/hidden-lines', + 'features/skipped-code', 'features/expandable-blocks', 'features/visible-whitespace', 'features/colourised-brackets', diff --git a/packages/starlight-codeblocks/CHANGELOG.md b/packages/starlight-codeblocks/CHANGELOG.md index c378b80..29f7bdf 100644 --- a/packages/starlight-codeblocks/CHANGELOG.md +++ b/packages/starlight-codeblocks/CHANGELOG.md @@ -7,6 +7,7 @@ - Markdown plugins: `starlight-codeblocks/markdown` exports a Markdown plugin for each feature that changes Markdown, such as `mdastCodeTabs()`, and `mdastCodeblocks()` for all of them. `codeblocks()` adds only the ones that the Markdown processor does not already list, in the correct order among them. A listed plugin for a feature that is off stops the build (#36) - Split diff: a **Unified** and **Split** switch in the title bar of each block that removes and adds lines. **Split** shows the old code on the left and the new code on the right, as a GitHub pull request does. `splitDiff.view`, `splitDiff.switch` and `splitDiff.sync` set the start view, remove the switch and stop it syncing across the page (#37) - Untitled blocks with title bar controls use the tab bar colours of titled blocks (#37) +- Skipped code: `[!code skip]` on its own line shows a marker in place of code that a block leaves out, at the indentation of its line. The text after the directive goes in the marker, else it reads "Code not shown". The line keeps its line number, and copies as a comment with the text, such as `// Not shown: Imports`. A comment that holds only `...`, such as `// ...`, and `...` alone on a line in JSON, also show as markers and copy as written. `skippedCode.commentAliases` and `skippedCode.bareAliases` change these aliases for each language. `skippedCode: false` turns the feature off (#28) ## 1.4.1 diff --git a/packages/starlight-codeblocks/README.md b/packages/starlight-codeblocks/README.md index 5ce0b10..26cd8ac 100644 --- a/packages/starlight-codeblocks/README.md +++ b/packages/starlight-codeblocks/README.md @@ -2,7 +2,7 @@ starlight-codeblocks -A Starlight and Astro plugin that adds 28 features to code blocks, such as focus, line states, annotations, links to API docs and runnable examples. It builds on Expressive Code, so the code blocks you already have keep working. +A Starlight and Astro plugin that adds 29 features to code blocks, such as focus, line states, annotations, links to API docs and runnable examples. It builds on Expressive Code, so the code blocks you already have keep working. Using an agent? [Point it at the bundled skill](https://ewels.github.io/starlight-codeblocks/agent-skill/). @@ -244,6 +244,25 @@ Hide the imports and set-up that readers need to run an example but not to under
+
+Skipped code + +Show a marker where a code block leaves out code, so readers know the file has more lines there. The copied code has no marker. + +````md +```js +app.get('/users', async (req, res) => { + // [!code skip] Not shown: Read the users from the database +}); +``` +```` + +A JavaScript block with a dotted line and the text Not shown: Read the users from the database in place of a function body. + +[Skipped code documentation](https://ewels.github.io/starlight-codeblocks/features/skipped-code/) + +
+
Expandable blocks diff --git a/packages/starlight-codeblocks/src/client/hidden-lines.ts b/packages/starlight-codeblocks/src/client/hidden-lines.ts index b8cc439..6f444fc 100644 --- a/packages/starlight-codeblocks/src/client/hidden-lines.ts +++ b/packages/starlight-codeblocks/src/client/hidden-lines.ts @@ -17,7 +17,7 @@ function setRun(block: Element, marker: Element, open: boolean) { line.nextElementSibling.classList.toggle(OPEN, open); // Opens a collapsed expandable block or collapsible section that holds the line. if (open && line) unhide(line); - for (let el = line?.previousElementSibling; el?.classList.contains('scb-callout'); el = el.previousElementSibling) { + for (let el = line?.previousElementSibling; el?.matches('.scb-callout'); el = el.previousElementSibling) { el.classList.toggle(OPEN, open); } } diff --git a/packages/starlight-codeblocks/src/components/animate.ts b/packages/starlight-codeblocks/src/components/animate.ts index cab86ad..8cff6cd 100644 --- a/packages/starlight-codeblocks/src/components/animate.ts +++ b/packages/starlight-codeblocks/src/components/animate.ts @@ -42,8 +42,8 @@ export function animate(group: HTMLElement, from: StepTokens, to: StepTokens) { if (real.length !== lines(to).length - 1) return () => {}; // The tokens have no line backgrounds or diff markers, so a diff would lose them until the animation ends. if (code.querySelector('.ec-line:is(.ins, .del)')) return () => {}; - // Callouts, hidden-line markers and section summaries take up height but have no tokens, so the block would jump. - const rows = code.querySelectorAll(':scope > :not(.ec-line, details), summary'); + // Callouts, hidden-line and skipped code markers, and section summaries change the height of the block, so it would jump. + const rows = code.querySelectorAll(':scope > :not(.ec-line, details), summary, .scb-skip-line'); if ([...rows].some((row) => row.checkVisibility())) return () => {}; const style = getComputedStyle(group.querySelector('figure') ?? group); const i = style.getPropertyValue('--ec-codeblocksWalkthrough-themeIndex').trim() || '0'; diff --git a/packages/starlight-codeblocks/src/components/tokens.ts b/packages/starlight-codeblocks/src/components/tokens.ts index 6e4ecb5..1b5931c 100644 --- a/packages/starlight-codeblocks/src/components/tokens.ts +++ b/packages/starlight-codeblocks/src/components/tokens.ts @@ -16,6 +16,8 @@ export interface Token { // Decorations that other features add inside a line. Keep in step with their unselectable elements. const DECORATIONS = `button, input, select, [popover], [aria-hidden="true"], .${DECORATION}`; +// The comment that a skipped code marker stands for, which is the line's code. +const SKIP_SOURCE = '.scb-skip-source'; /** The code lines of a block, without the lines that other plugins add, such as a collapsed section's summary. */ export function codeLines(root: Element): Element[] { @@ -44,7 +46,7 @@ export function readTokens(figure: Element): { code: string; lines: Token[][] } if (!content) continue; tokens.push({ content, offset, htmlStyle: styles.join(';') || undefined }); offset += content.length; - } else if (node.type === 'element' && !matches(DECORATIONS, node)) { + } else if (node.type === 'element' && (matches(SKIP_SOURCE, node) || !matches(DECORATIONS, node))) { const style = String(node.properties.style ?? ''); walk(node.children, style.startsWith('--') ? [...styles, style] : styles); } diff --git a/packages/starlight-codeblocks/src/expressive-code/comments.ts b/packages/starlight-codeblocks/src/expressive-code/comments.ts index 2edb822..3332ea5 100644 --- a/packages/starlight-codeblocks/src/expressive-code/comments.ts +++ b/packages/starlight-codeblocks/src/expressive-code/comments.ts @@ -35,14 +35,17 @@ export interface CommentSyntax { close?: string; } -export function commentSyntaxFor(language: string, overrides: Record = {}): CommentSyntax[] { +/** The entry of `map` for `language`, under its name or a Shiki alias of it. */ +export function forLanguage(language: string, map: Record): T | undefined { const key = language.toLowerCase(); const info = bundledLanguage(key); const keys = [key, ...(info ? [info.id, ...(info.aliases ?? [])] : [])]; - const own = (syntaxes: Record) => - keys.map((k) => (Object.hasOwn(syntaxes, k) ? syntaxes[k] : undefined)).find(Boolean); - const syntax = own(overrides) ?? own(defaultCommentSyntax) ?? []; - return syntax.map((entry) => { + return keys.map((k) => (Object.hasOwn(map, k) ? map[k] : undefined)).find(Boolean); +} + +export function commentSyntaxFor(language: string, overrides: Record = {}): CommentSyntax[] { + const syntax = forLanguage(language, overrides) ?? forLanguage(language, defaultCommentSyntax); + return (syntax ?? []).map((entry) => { const [open = '', close] = entry.trim().split(/\s+/); return { open, close }; }); diff --git a/packages/starlight-codeblocks/src/expressive-code/core.ts b/packages/starlight-codeblocks/src/expressive-code/core.ts index 69d5db6..0651c79 100644 --- a/packages/starlight-codeblocks/src/expressive-code/core.ts +++ b/packages/starlight-codeblocks/src/expressive-code/core.ts @@ -18,6 +18,7 @@ import { type ElementContent, EXIT, h, + matches, type Parents, select, selectAll, @@ -79,6 +80,7 @@ const decorations = [ 'squiggle-popover', 'squiggle-list', 'hidden-marker', + 'skip-marker', 'expandable-bar', 'steps-stepper', 'steps-controls', @@ -95,6 +97,8 @@ const decorations = [ * Gives each decoration the one class that tools reading the HTML can drop, such as starlight-llms-txt, * and keeps it out of the Pagefind index. Keep the list in step with new decorations. */ +export const isDecoration = (node: ElementContent) => node.type === 'element' && matches(decorations, node); + export function markDecorations(root: Parents) { for (const element of selectAll(decorations, root)) { const classes = element.properties.className as string[]; diff --git a/packages/starlight-codeblocks/src/expressive-code/hidden-lines.ts b/packages/starlight-codeblocks/src/expressive-code/hidden-lines.ts index ff7931a..eadf08e 100644 --- a/packages/starlight-codeblocks/src/expressive-code/hidden-lines.ts +++ b/packages/starlight-codeblocks/src/expressive-code/hidden-lines.ts @@ -2,9 +2,7 @@ import { AttachedPluginData, type ExpressiveCodeBlock, type ExpressiveCodeLine, - onBackground, PluginStyleSettings, - type StyleResolverFn, setAlpha, type UnresolvedStyleValue, } from '@expressive-code/core'; @@ -13,7 +11,7 @@ import { clientJsModules } from '../client-modules.ts'; import { uiTexts } from '../translations.ts'; import { addTitleBarControl, blockUid, type CodeblocksPlugin, insertBefore, lineElement } from './core.ts'; import { markedLines } from './notation.ts'; -import { PREFIX, solidCodeBackground, solidCodeForeground } from './styles.ts'; +import { markerColours, markerStyles, PREFIX, solidCodeForeground } from './styles.ts'; export interface HiddenLinesStyleSettings { badgeBackground: UnresolvedStyleValue; @@ -33,9 +31,7 @@ declare module '@expressive-code/core' { const styleSettings = new PluginStyleSettings({ defaultValues: { codeblocksHiddenLines: { - badgeBackground: (context: Parameters[0]) => - onBackground(setAlpha(context.resolveSetting('codeblocks.mutedForeground'), 0.1), solidCodeBackground(context)), - rule: ({ resolveSetting }) => setAlpha(resolveSetting('codeblocks.mutedForeground'), 0.35), + ...markerColours, ruleHover: ({ resolveSetting }) => resolveSetting('codeblocks.mutedForeground'), ruleOpen: ({ resolveSetting }) => setAlpha(resolveSetting('codeblocks.mutedForeground'), 0.22), openBackground: (context) => setAlpha(solidCodeForeground(context), 0.04), @@ -74,46 +70,30 @@ export function pluginHiddenLines(): CodeblocksPlugin { background: ${cssVar('codeblocksHiddenLines.openBackground')}; opacity: ${cssVar('codeblocksHiddenLines.openOpacity')}; } +${markerStyles(cssVar, `${PREFIX}-hidden-marker`, `${PREFIX}-hidden-marker span`, 'codeblocksHiddenLines', 'dashed')} .${PREFIX}-hidden-marker { display: flex; - align-items: center; - width: 100%; position: relative; - margin: 2px 0; + width: 100%; padding: 0; border: 0; background: none; - color: ${cssVar('codeblocks.mutedForeground')}; cursor: pointer; font: inherit; text-align: left; - user-select: none; - -webkit-user-select: none; } .${PREFIX}-hidden-marker::before { - content: ''; - position: absolute; - top: 50%; inset-inline: calc(var(--scb-gutter, 0px) + ${cssVar('codePaddingInline')}) ${cssVar('codePaddingInline')}; - border-top: 1px dashed ${cssVar('codeblocksHiddenLines.rule')}; - transform: translateY(-50%); } /* Where the copy button always shows, it sits over the end of the first line. */ @media (hover: none) { .${PREFIX}-hidden-marker:first-child::before { inset-inline-end: calc(${cssVar('codePaddingInline')} + 2.5rem); } } .${PREFIX}-hidden-marker span { - position: relative; - z-index: 1; display: inline-flex; align-items: center; /* The gutter width is in ch of the code font; the division undoes this span's smaller font size. */ margin-inline-start: calc(var(--scb-gutter, 0px) / 0.8125 + ${cssVar('codePaddingInline')}); - padding: 0.05em 0.65em; - border-radius: 999px; - background: ${cssVar('codeblocksHiddenLines.badgeBackground')}; - font-size: 0.8125em; - line-height: 1.6; } .${PREFIX}-hidden-marker:hover, .${PREFIX}-hidden-marker:focus-visible { color: ${cssVar('codeForeground')}; diff --git a/packages/starlight-codeblocks/src/expressive-code/index.ts b/packages/starlight-codeblocks/src/expressive-code/index.ts index 369c268..2648600 100644 --- a/packages/starlight-codeblocks/src/expressive-code/index.ts +++ b/packages/starlight-codeblocks/src/expressive-code/index.ts @@ -21,6 +21,7 @@ import { pluginPlaceholders } from './placeholders.ts'; import { pluginPlayground } from './playground.ts'; import { pluginRunnable } from './runnable.ts'; import { pluginShellCopy } from './shell-copy.ts'; +import { pluginSkippedCode } from './skipped-code.ts'; import { pluginSplitDiff } from './split-diff.ts'; import { pluginSquiggles } from './squiggles.ts'; import { pluginSwatches } from './swatches.ts'; @@ -51,6 +52,7 @@ export { pluginPlayground, pluginRunnable, pluginShellCopy, + pluginSkippedCode, pluginSplitDiff, pluginSquiggles, pluginSwatches, @@ -92,6 +94,7 @@ export function createPlugins(options: ResolvedOptions, base?: string): Expressi ...(options.placeholders ? [pluginPlaceholders(options.placeholders)] : []), ...(options.mentions ? [pluginMentions()] : []), ...(options.permalinks ? [pluginPermalinks()] : []), + ...(options.skippedCode ? [pluginSkippedCode(options.skippedCode)] : []), ...(options.hiddenLines ? [pluginHiddenLines()] : []), ...(options.expandable ? [pluginExpandable(options.expandable)] : []), // After shell copy, which changes the copied text that the playground gets, and after placeholders. diff --git a/packages/starlight-codeblocks/src/expressive-code/notation.ts b/packages/starlight-codeblocks/src/expressive-code/notation.ts index 13b21e4..63d3278 100644 --- a/packages/starlight-codeblocks/src/expressive-code/notation.ts +++ b/packages/starlight-codeblocks/src/expressive-code/notation.ts @@ -1,10 +1,20 @@ import { AttachedPluginData, type ExpressiveCodeBlock, type ExpressiveCodeLine } from '@expressive-code/core'; -import { type CommentSyntax, commentSyntaxFor } from './comments.ts'; +import { type CommentSyntax, commentSyntaxFor, forLanguage } from './comments.ts'; import { type CodeblocksPlugin, lineData, lineElement, numberedLines, resolveRange, warn } from './core.ts'; export interface DirectiveSpec { /** The directive takes the text after it, up to the next directive or the end of the comment. */ text?: boolean; + /** + * The directive stands for a line of its own: that line stays in the block, as a comment with the directive's text, + * or `...`. It takes no `:N`, and does nothing on a line with code. + */ + ownLine?: boolean; + /** + * Lines that are read as the directive, by language, with `*` for every language without an entry: + * a comment that holds only an alias, or a line that holds only a bare alias. + */ + aliases?: { comment?: Record; bare?: Record }; /** For the directives reference page. */ docs?: { description: string; @@ -29,6 +39,8 @@ export interface Directive { text?: string; /** The line of the directive in the code block source, from 1. */ sourceLine: number; + /** Read from an alias, such as `// ...`, not written as a directive. */ + alias?: boolean; } const wordChar = /[\w$]/; @@ -133,6 +145,7 @@ function interpret(token: Token, specs: DirectiveSpecs, sourceLine: number) { if (count < 1) return { problem: 'needs a count of 1 or more after the colon, such as `:3`' }; const spec = Object.hasOwn(specs, `code ${match[1]}`) ? specs[`code ${match[1]}`] : undefined; if (!spec) return { problem: 'is not a known directive' }; + if (spec.ownLine && match[2] !== undefined) return { problem: 'takes no count' }; items.push({ spec, directive: { name: `code ${match[1]}`, count, args: [], sourceLine } }); } return { items }; @@ -202,6 +215,8 @@ function findComment(text: string, first: number, syntaxes: CommentSyntax[]) { return best; } +const diffPrefix = /^[+-](?![+-])/; + /** Parses the directives in one line and returns the line without them. */ export function parseLine( text: string, @@ -235,7 +250,7 @@ export function parseLine( const [start, bodyStart, bodyEnd, end] = comment; const body = text.slice(bodyStart, bodyEnd); // Expressive Code strips a diff prefix only later, so `+ // [!code …]` still holds only directives. - const prefix = diff ? (text.match(/^[+-](?![+-])/)?.[0].length ?? 0) : 0; + const prefix = diff ? (text.match(diffPrefix)?.[0].length ?? 0) : 0; const hasCode = text.slice(prefix, start).trim() !== '' || text.slice(end).trim() !== ''; const directives: Directive[] = []; @@ -263,7 +278,8 @@ export function parseLine( for (const { spec, directive } of result.items) { directives.push(directive); // In `[!code ++ error] text`, the text goes to the first directive that takes text. - if (spec.text) textOf ??= directive; + // A directive that goes on its own line is dropped from a line with code, so it takes no text there. + if (spec.text && !(spec.ownLine && hasCode)) textOf ??= directive; } removedBefore = true; } @@ -272,8 +288,15 @@ export function parseLine( else keep(tail); remaining = unescapeDirectives(remaining); + const onlyDirectives = !hasCode && directives.length > 0 && remaining.trim() === ''; + const own = directives.find((directive) => specs[directive.name]?.ownLine); + if (own && onlyDirectives) { + const [open, close] = [text.slice(start, bodyStart), text.slice(bodyEnd, end)]; + const comment = `${open} ${own.text ?? '...'}${close ? ` ${close}` : ''}`; + return { text: text.slice(0, start) + comment, removed: false, directives }; + } // A line that holds only directives goes, as in Shiki's notation transformers. - if (!hasCode && directives.length > 0 && remaining.trim() === '') return { text: '', removed: true, directives }; + if (onlyDirectives) return { text: '', removed: true, directives }; const before = text.slice(0, start); const after = text.slice(end); const newText = @@ -286,9 +309,61 @@ export function parseLine( : text.slice(0, bodyStart) + (directives.length > 0 ? remaining.trimEnd() + (body.match(/\s*$/)?.[0] ?? '') : remaining) + text.slice(bodyEnd); + if (own) { + report(`\`[!${own.name}]\` goes on a line of its own. The line renders without it.`, sourceLine); + directives.splice(directives.indexOf(own), 1); + } return { text: newText, removed: false, directives }; } +type Aliases = [alias: string, name: string][]; + +export interface LineAliases { + comment: Aliases; + bare: Aliases; +} + +/** The name of the directive whose alias is all of `line`, or all of a comment that is all of `line`. */ +function aliasOf(line: string, syntaxes: CommentSyntax[], aliases: LineAliases, diff: boolean) { + const text = (diff ? line.replace(diffPrefix, '') : line).trim(); + const bodies = syntaxes + .filter(({ open, close }) => text.startsWith(open) && (!close || text.endsWith(close))) + .map(({ open, close }) => text.slice(open.length, close ? -close.length : undefined).trim()); + return (aliases.bare.find(([alias]) => alias === text) ?? + aliases.comment.find(([alias]) => bodies.includes(alias)))?.[1]; +} + +/** The aliases of every directive in `language`: its own entry, else `*`. */ +export function aliasesFor(specs: DirectiveSpecs, language: string): LineAliases { + const of = (kind: 'comment' | 'bare') => + Object.entries(specs).flatMap(([name, spec]) => { + const map = spec.aliases?.[kind] ?? {}; + return (forLanguage(language, map) ?? map['*'] ?? []).map((alias): [string, string] => [alias, name]); + }); + return { comment: of('comment'), bare: of('bare') }; +} + +const specsCache = new WeakMap }>(); + +/** The directives that every plugin declares, once for each list of plugins, and their aliases in `language`. */ +function specsOf(plugins: readonly unknown[], language: string) { + let found = specsCache.get(plugins); + if (!found) { + const specs: DirectiveSpecs = Object.assign( + {}, + ...plugins.map((plugin) => (plugin as CodeblocksPlugin).directives ?? {}), + ); + found = { specs, aliases: new Map() }; + specsCache.set(plugins, found); + } + let aliases = found.aliases.get(language); + if (!aliases) { + aliases = aliasesFor(found.specs, language); + found.aliases.set(language, aliases); + } + return { specs: found.specs, aliases }; +} + /** Parses every line, and moves the directives of removed lines to the line below them. */ export function parseNotation( lines: string[], @@ -296,8 +371,15 @@ export function parseNotation( specs: DirectiveSpecs, report: Report, diff = false, + aliases: LineAliases = { comment: [], bare: [] }, ): ParsedLine[] { - const parsed = lines.map((text, i) => parseLine(text, syntaxes, specs, report, i + 1, diff)); + const parsed = lines.map((text, i): ParsedLine => { + const name = aliasOf(text, syntaxes, aliases, diff); + if (name) + return { text, removed: false, directives: [{ name, count: 1, args: [], sourceLine: i + 1, alias: true }] }; + if (syntaxes.length === 0) return { text, removed: false, directives: [] }; + return parseLine(text, syntaxes, specs, report, i + 1, diff); + }); let pending: Directive[] = []; for (const line of parsed) { if (line.removed) { @@ -316,9 +398,7 @@ export function parseNotation( return false; }); } - for (const directive of pending) { - report(`\`[!${directive.name}]\` has no line below it.`, directive.sourceLine); - } + for (const directive of pending) report(`\`[!${directive.name}]\` has no line below it.`, directive.sourceLine); return parsed; } @@ -334,7 +414,9 @@ const notationData = new AttachedPluginData<{ run: ExpressiveCodeLine[]; specs: DirectiveSpecs; diffIndent: Map; -}>(() => ({ directives: [], removed: [], output: [], run: [], specs: {}, diffIndent: new Map() })); + /** A diff that Expressive Code leaves as written, so its lines keep their `+` and `-`. */ + realDiff: boolean; +}>(() => ({ directives: [], removed: [], output: [], run: [], specs: {}, diffIndent: new Map(), realDiff: false })); /** The directives in a code block, optionally only those with one name, such as `code focus`. */ export function getDirectives(codeBlock: ExpressiveCodeBlock, name?: string): BlockDirective[] { @@ -439,19 +521,19 @@ export function pluginNotation({ comments }: NotationOptions = {}): CodeblocksPl preprocessLanguage(context) { const { codeBlock, config } = context; const syntaxes = commentSyntaxFor(codeBlock.language, comments); - if (syntaxes.length === 0 || !/\[\\?!/.test(codeBlock.code)) return; - const specs: DirectiveSpecs = Object.assign( - {}, - ...config.plugins.map((plugin) => (plugin as CodeblocksPlugin).directives ?? {}), - ); + const { specs, aliases } = specsOf(config.plugins, codeBlock.language); const lines = codeBlock.getLines(); + // The text markers plugin reads the `useDiffSyntax` meta option only in `preprocessMetadata`. + const diff = codeBlock.metaOptions.getBoolean('useDiffSyntax') ?? Boolean(codeBlock.props.useDiffSyntax); + const hasDirectives = syntaxes.length > 0 && /\[\\?!/.test(codeBlock.code); + if (!hasDirectives && !lines.some(({ text }) => aliasOf(text, syntaxes, aliases, diff))) return; const parsed = parseNotation( lines.map((line) => line.text), syntaxes, specs, (message, line) => warn(context, message, line), - // The text markers plugin reads the `useDiffSyntax` meta option only in `preprocessMetadata`. - codeBlock.metaOptions.getBoolean('useDiffSyntax') ?? Boolean(codeBlock.props.useDiffSyntax), + diff, + aliases, ); const visible = lines.filter((_, i) => !parsed[i]?.removed); const marks = parsed.flatMap(({ directives }, i) => @@ -483,6 +565,7 @@ export function pluginNotation({ comments }: NotationOptions = {}): CodeblocksPl data.removed = lines.filter((_, i) => parsed[i]?.removed); data.output = output; data.run = run; + data.realDiff = diff && !diffColumns(lines.map((line) => line.text)); if (code.length < lines.length) remapCollapse(codeBlock, lines, code); parsed.forEach(({ directives }, i) => { if (directives.length === 0) return; @@ -491,6 +574,17 @@ export function pluginNotation({ comments }: NotationOptions = {}): CodeblocksPl const area = outputSet.has(line) ? output : runSet.has(line) ? run : code; const target = area.indexOf(line); for (const directive of directives) { + if (area !== code && specs[directive.name]?.ownLine) { + // Output can hold `# ...` of its own. + if (!directive.alias) { + warn( + context, + `\`[!${directive.name}]\` is not in the code, so it shows as a comment.`, + directive.sourceLine, + ); + } + continue; + } data.directives.push({ ...directive, lines: area.slice(target, target + directive.count) }); if (target + directive.count > area.length) { warn(context, `\`:${directive.count}\` runs past the last line of the block.`, directive.sourceLine); @@ -520,15 +614,16 @@ export function pluginNotation({ comments }: NotationOptions = {}): CodeblocksPl }, preprocessCode({ codeBlock }) { const syntaxes = commentSyntaxFor(codeBlock.language, comments); - const { removed, specs, diffIndent } = notationData.getOrCreateFor(codeBlock); - if (syntaxes.length === 0 || !/\[\\?!/.test(codeBlock.code)) return; + const { removed, specs, diffIndent, realDiff } = notationData.getOrCreateFor(codeBlock); for (const [line, columns] of diffIndent) line.editText(0, columns, ''); - for (const line of codeBlock.getLines()) { - // Other plugins can edit lines after the first parse, so parse the current text again. - const { text, removed: gone } = parseLine(line.text, syntaxes, specs, () => {}); - // The first parse kept this line, and blanking it would leave an empty line behind. - if (gone && !removed.includes(line)) continue; - if (text !== line.text) line.editText(0, line.text.length, text); + if (syntaxes.length > 0 && /\[\\?!/.test(codeBlock.code)) { + for (const line of codeBlock.getLines()) { + // Other plugins can edit lines after the first parse, so parse the current text again. + const { text, removed: gone } = parseLine(line.text, syntaxes, specs, () => {}, 1, realDiff); + // The first parse kept this line, and blanking it would leave an empty line behind. + if (gone && !removed.includes(line)) continue; + if (text !== line.text) line.editText(0, line.text.length, text); + } } for (const line of removed) { const index = codeBlock.getLines().indexOf(line); @@ -539,15 +634,20 @@ export function pluginNotation({ comments }: NotationOptions = {}): CodeblocksPl }; } -const diffLine = /^(([+-](?![+-]))?\s*)(.*)$/; +export const diffLine = /^(([+-](?![+-]))?\s*)(.*)$/; -/** The columns that Expressive Code's diff syntax removes from each line, as in its text markers plugin. */ -function diffColumns(lines: readonly ExpressiveCodeLine[]) { - if (lines.slice(0, 4).some((line) => /^([*+-]{3}\s|@@\s|[0-9,]+[acd][0-9,]+\s*$)/.test(line.text))) return undefined; - const parsed = lines.map((line) => line.text.match(diffLine) ?? []); - const indents = parsed.filter((m) => m[3]?.trim()).map((m) => m[1]?.length ?? 0); +/** + * The columns that Expressive Code's diff syntax removes from a line of a block with `lines`, + * as in its text markers plugin. `undefined` for a real diff, which it leaves as written. + */ +function diffColumns(lines: readonly string[]) { + if (lines.slice(0, 4).some((line) => /^([*+-]{3}\s|@@\s|[0-9,]+[acd][0-9,]+\s*$)/.test(line))) return undefined; + const indents = lines + .map((line) => line.match(diffLine) ?? []) + .filter((m) => m[3]?.trim()) + .map((m) => m[1]?.length ?? 0); const min = indents.length > 0 ? Math.min(...indents) : 0; - return new Map(lines.map((line, i) => [line, min || (parsed[i]?.[2] ? 1 : 0)])); + return (line: string) => min || (diffPrefix.test(line) ? 1 : 0); } /** @@ -556,11 +656,11 @@ function diffColumns(lines: readonly ExpressiveCodeLine[]) { */ function diffIndentFix(lines: readonly ExpressiveCodeLine[], visible: readonly ExpressiveCodeLine[]) { const fix = new Map(); - const all = diffColumns(lines); - const seen = diffColumns(visible); + const all = diffColumns(lines.map((line) => line.text)); + const seen = diffColumns(visible.map((line) => line.text)); if (!all || !seen) return fix; - for (const [line, columns] of seen) { - const extra = columns - (all.get(line) ?? 0); + for (const line of visible) { + const extra = seen(line.text) - all(line.text); if (extra > 0) fix.set(line, extra); } return fix; diff --git a/packages/starlight-codeblocks/src/expressive-code/skipped-code.ts b/packages/starlight-codeblocks/src/expressive-code/skipped-code.ts new file mode 100644 index 0000000..357d634 --- /dev/null +++ b/packages/starlight-codeblocks/src/expressive-code/skipped-code.ts @@ -0,0 +1,97 @@ +import { type ExpressiveCodeLine, PluginStyleSettings, type UnresolvedStyleValue } from '@expressive-code/core'; +import { addClassName, h, select } from '@expressive-code/core/hast'; +import { uiTexts } from '../translations.ts'; +import { type CodeblocksPlugin, isDecoration, lineElement } from './core.ts'; +import { inlineMarkdown } from './inline-markdown.ts'; +import { diffLine, getRenderedDirectives } from './notation.ts'; +import { markerColours, markerStyles, PREFIX } from './styles.ts'; + +export interface SkippedCodeStyleSettings { + badgeBackground: UnresolvedStyleValue; + rule: UnresolvedStyleValue; +} + +declare module '@expressive-code/core' { + export interface StyleSettings { + codeblocksSkippedCode: SkippedCodeStyleSettings; + } +} + +const styleSettings = new PluginStyleSettings({ defaultValues: { codeblocksSkippedCode: markerColours } }); + +export interface SkippedCodeSettings { + /** Comments that stand for `[!code skip]` when they hold only an alias, by language, with `*` for the others. */ + commentAliases?: Record; + /** Lines that stand for `[!code skip]` when they hold only an alias, by language, with `*` for the others. */ + bareAliases?: Record; +} + +export const defaultSkipAliases = { comment: { '*': ['...'] }, bare: { json: ['...'] } }; + +const trimmed = (aliases: Record) => + Object.fromEntries(Object.entries(aliases).map(([language, list]) => [language, list.map((alias) => alias.trim())])); + +/** Draws a `[!code skip]` line, which stands for code that the block leaves out, as a marker. */ +export function pluginSkippedCode({ + commentAliases = {}, + bareAliases = {}, +}: SkippedCodeSettings = {}): CodeblocksPlugin { + return { + name: 'starlight-codeblocks:skipped-code', + directives: { + 'code skip': { + text: true, + ownLine: true, + aliases: { + comment: trimmed({ ...defaultSkipAliases.comment, ...commentAliases }), + bare: trimmed({ ...defaultSkipAliases.bare, ...bareAliases }), + }, + docs: { + description: 'Shows a marker in place of code that the block leaves out.', + args: 'Optional. The text of the marker.', + example: { lang: 'js', code: 'function connect(host) {\n // [!code skip]\n return socket\n}' }, + page: 'features/skipped-code', + }, + }, + }, + styleSettings, + baseStyles: ({ cssVar }) => ` +${markerStyles(cssVar, `${PREFIX}-skip-marker`, `${PREFIX}-skip-text`, 'codeblocksSkippedCode', 'dotted')} +/* Not zero width or in a flex container: Chromium leaves either out of a manual selection. */ +.${PREFIX}-skip-source { position: absolute; width: 1px; height: 1px; overflow: hidden; clip-path: inset(50%); white-space: pre; } +.${PREFIX}-skip-marker { display: inline-flex; } +.${PREFIX}-skip-marker::before { inset-inline: ${cssVar('codePaddingInline')}; } +/* Where the copy button always shows, it sits over the end of the first line. */ +@media (hover: none) { + .ec-line:first-child .${PREFIX}-skip-marker::before { inset-inline-end: calc(${cssVar('codePaddingInline')} + 2.5rem); } +} +`, + hooks: { + postprocessRenderedBlock(context) { + const say = uiTexts(context.locale); + for (const { lines, text } of getRenderedDirectives(context, 'code skip')) { + const line = lines[0] as ExpressiveCodeLine; + const el = lineElement(line); + const code = el && select('.code', el); + if (!code) continue; + addClassName(el, `${PREFIX}-skip-line`); + // A real diff keeps its `+` or `-` prefix in the text. + const indent = line.text.match(diffLine)?.[1] ?? ''; + // Other plugins' labels, such as a line state message, stay around the code. + const first = code.children.findIndex((node) => !isDecoration(node)); + const last = code.children.findLastIndex((node) => !isDecoration(node)); + if (first === -1) continue; + code.children.splice( + first, + last - first + 1, + ...(indent ? [{ type: 'text' as const, value: indent }] : []), + h('span', { class: `${PREFIX}-skip-source`, ariaHidden: 'true' }, line.text.slice(indent.length)), + h('span', { class: `${PREFIX}-skip-marker` }, [ + h('span', { class: `${PREFIX}-skip-text` }, text ? inlineMarkdown(text) : say('skippedCode.marker')), + ]), + ); + } + }, + }, + }; +} diff --git a/packages/starlight-codeblocks/src/expressive-code/styles.ts b/packages/starlight-codeblocks/src/expressive-code/styles.ts index fc8babd..780a403 100644 --- a/packages/starlight-codeblocks/src/expressive-code/styles.ts +++ b/packages/starlight-codeblocks/src/expressive-code/styles.ts @@ -68,6 +68,48 @@ const tabBarBackground = ({ resolveSetting }: Context) => { } }; +/** Colours of a marker across the code, for the hidden lines and skipped code settings groups. */ +export const markerColours = { + badgeBackground: (context: Context) => + onBackground(setAlpha(context.resolveSetting('codeblocks.mutedForeground'), 0.1), solidCodeBackground(context)), + rule: ({ resolveSetting }: Context) => setAlpha(resolveSetting('codeblocks.mutedForeground'), 0.35), +}; + +/** + * A marker across the code, with a badge on a rule, as hidden lines and skipped code draw it. + * `group` holds the `markerColours` settings. + */ +export const markerStyles = ( + cssVar: ResolverContext['cssVar'], + marker: string, + badge: string, + group: 'codeblocksHiddenLines' | 'codeblocksSkippedCode', + border: 'dashed' | 'dotted', +) => ` +.${marker} { + align-items: center; + margin: 2px 0; + color: ${cssVar('codeblocks.mutedForeground')}; + user-select: none; + -webkit-user-select: none; +} +.${marker}::before { + content: ''; + position: absolute; + top: 50%; + border-top: 1px ${border} ${cssVar(`${group}.rule`)}; + transform: translateY(-50%); +} +.${badge} { + position: relative; + z-index: 1; + padding: 0.05em 0.65em; + border-radius: 999px; + background: ${cssVar(`${group}.badgeBackground`)}; + font-size: 0.8125em; + line-height: 1.6; +}`; + /** `colour`, lightened or darkened to at least `min` contrast on the code background. */ export const onCode = (context: Context, colour: string, min: number) => ensureColorContrastOnBackground(colour, solidCodeBackground(context), min); diff --git a/packages/starlight-codeblocks/src/languages/ca.ts b/packages/starlight-codeblocks/src/languages/ca.ts index c07ccae..ba045b6 100644 --- a/packages/starlight-codeblocks/src/languages/ca.ts +++ b/packages/starlight-codeblocks/src/languages/ca.ts @@ -24,6 +24,7 @@ export default { 'hiddenLines.hide_one': 'Amagar {{count}} línia', 'hiddenLines.hide_many': 'Amagar {{count}} de línies', 'hiddenLines.hide_other': 'Amagar {{count}} línies', + 'skippedCode.marker': 'Codi no mostrat', 'expandable.showAll_one': 'Mostrar {{count}} línia', 'expandable.showAll_many': 'Mostrar {{count}} de línies', 'expandable.showAll_other': 'Mostrar les {{count}} línies', diff --git a/packages/starlight-codeblocks/src/languages/de.ts b/packages/starlight-codeblocks/src/languages/de.ts index c487f76..0dc09cf 100644 --- a/packages/starlight-codeblocks/src/languages/de.ts +++ b/packages/starlight-codeblocks/src/languages/de.ts @@ -21,6 +21,7 @@ export default { 'hiddenLines.show_other': '{{count}} verborgene Zeilen anzeigen', 'hiddenLines.hide_one': '{{count}} Zeile verbergen', 'hiddenLines.hide_other': '{{count}} Zeilen verbergen', + 'skippedCode.marker': 'Code ausgelassen', 'expandable.showAll_one': '{{count}} Zeile anzeigen', 'expandable.showAll_other': 'Alle {{count}} Zeilen anzeigen', 'expandable.showFewer': 'Weniger Zeilen anzeigen', diff --git a/packages/starlight-codeblocks/src/languages/eo.ts b/packages/starlight-codeblocks/src/languages/eo.ts index b1aa9c0..0f871e3 100644 --- a/packages/starlight-codeblocks/src/languages/eo.ts +++ b/packages/starlight-codeblocks/src/languages/eo.ts @@ -21,6 +21,7 @@ export default { 'hiddenLines.show_other': 'Montri {{count}} kaŝitajn liniojn', 'hiddenLines.hide_one': 'Kaŝi {{count}} linion', 'hiddenLines.hide_other': 'Kaŝi {{count}} liniojn', + 'skippedCode.marker': 'Kodo ne montrita', 'expandable.showAll_one': 'Montri {{count}} linion', 'expandable.showAll_other': 'Montri ĉiujn {{count}} liniojn', 'expandable.showFewer': 'Montri malpli da linioj', diff --git a/packages/starlight-codeblocks/src/languages/es.ts b/packages/starlight-codeblocks/src/languages/es.ts index 32b1b22..ac8a9fe 100644 --- a/packages/starlight-codeblocks/src/languages/es.ts +++ b/packages/starlight-codeblocks/src/languages/es.ts @@ -24,6 +24,7 @@ export default { 'hiddenLines.hide_one': 'Ocultar {{count}} línea', 'hiddenLines.hide_many': 'Ocultar {{count}} de líneas', 'hiddenLines.hide_other': 'Ocultar {{count}} líneas', + 'skippedCode.marker': 'Código omitido', 'expandable.showAll_one': 'Mostrar {{count}} línea', 'expandable.showAll_many': 'Mostrar {{count}} de líneas', 'expandable.showAll_other': 'Mostrar las {{count}} líneas', diff --git a/packages/starlight-codeblocks/src/languages/fr.ts b/packages/starlight-codeblocks/src/languages/fr.ts index 1d7e6ef..83626fa 100644 --- a/packages/starlight-codeblocks/src/languages/fr.ts +++ b/packages/starlight-codeblocks/src/languages/fr.ts @@ -24,6 +24,7 @@ export default { 'hiddenLines.hide_one': 'Masquer {{count}} ligne', 'hiddenLines.hide_many': 'Masquer {{count}} de lignes', 'hiddenLines.hide_other': 'Masquer {{count}} lignes', + 'skippedCode.marker': 'Code omis', 'expandable.showAll_one': 'Afficher {{count}} ligne', 'expandable.showAll_many': 'Afficher {{count}} de lignes', 'expandable.showAll_other': 'Afficher les {{count}} lignes', diff --git a/packages/starlight-codeblocks/src/languages/hi.ts b/packages/starlight-codeblocks/src/languages/hi.ts index 7cb5ba0..fedd4bd 100644 --- a/packages/starlight-codeblocks/src/languages/hi.ts +++ b/packages/starlight-codeblocks/src/languages/hi.ts @@ -21,6 +21,7 @@ export default { 'hiddenLines.show_other': '{{count}} छिपी हुई पंक्तियाँ दिखाएँ', 'hiddenLines.hide_one': '{{count}} पंक्ति छिपाएँ', 'hiddenLines.hide_other': '{{count}} पंक्तियाँ छिपाएँ', + 'skippedCode.marker': 'कोड नहीं दिखाया गया', 'expandable.showAll_one': '{{count}} पंक्ति दिखाएँ', 'expandable.showAll_other': 'सभी {{count}} पंक्तियाँ दिखाएँ', 'expandable.showFewer': 'कम पंक्तियाँ दिखाएँ', diff --git a/packages/starlight-codeblocks/src/languages/id.ts b/packages/starlight-codeblocks/src/languages/id.ts index 3c8ae4b..e2b5ec0 100644 --- a/packages/starlight-codeblocks/src/languages/id.ts +++ b/packages/starlight-codeblocks/src/languages/id.ts @@ -18,6 +18,7 @@ export default { 'hiddenLines.marker_other': '{{count}} baris tersembunyi', 'hiddenLines.show_other': 'Tampilkan {{count}} baris tersembunyi', 'hiddenLines.hide_other': 'Sembunyikan {{count}} baris', + 'skippedCode.marker': 'Kode tidak ditampilkan', 'expandable.showAll_other': 'Tampilkan semua {{count}} baris', 'expandable.showFewer': 'Tampilkan lebih sedikit baris', 'splitDiff.view': 'Tampilan diff', diff --git a/packages/starlight-codeblocks/src/languages/it.ts b/packages/starlight-codeblocks/src/languages/it.ts index d153643..fd0cf04 100644 --- a/packages/starlight-codeblocks/src/languages/it.ts +++ b/packages/starlight-codeblocks/src/languages/it.ts @@ -24,6 +24,7 @@ export default { 'hiddenLines.hide_one': 'Nascondi {{count}} riga', 'hiddenLines.hide_many': 'Nascondi {{count}} di righe', 'hiddenLines.hide_other': 'Nascondi {{count}} righe', + 'skippedCode.marker': 'Codice omesso', 'expandable.showAll_one': 'Mostra {{count}} riga', 'expandable.showAll_many': 'Mostra {{count}} di righe', 'expandable.showAll_other': 'Mostra tutte le {{count}} righe', diff --git a/packages/starlight-codeblocks/src/languages/ja.ts b/packages/starlight-codeblocks/src/languages/ja.ts index b965a6a..fd655a4 100644 --- a/packages/starlight-codeblocks/src/languages/ja.ts +++ b/packages/starlight-codeblocks/src/languages/ja.ts @@ -18,6 +18,7 @@ export default { 'hiddenLines.marker_other': '非表示の {{count}} 行', 'hiddenLines.show_other': '非表示の {{count}} 行を表示', 'hiddenLines.hide_other': '{{count}} 行を非表示', + 'skippedCode.marker': 'コードは省略', 'expandable.showAll_other': '全 {{count}} 行を表示', 'expandable.showFewer': '表示する行を減らす', 'splitDiff.view': '差分の表示', diff --git a/packages/starlight-codeblocks/src/languages/ko.ts b/packages/starlight-codeblocks/src/languages/ko.ts index 82a68c4..d83c1f7 100644 --- a/packages/starlight-codeblocks/src/languages/ko.ts +++ b/packages/starlight-codeblocks/src/languages/ko.ts @@ -18,6 +18,7 @@ export default { 'hiddenLines.marker_other': '숨겨진 줄 {{count}}개', 'hiddenLines.show_other': '숨겨진 줄 {{count}}개 표시', 'hiddenLines.hide_other': '{{count}}줄 숨기기', + 'skippedCode.marker': '코드 생략', 'expandable.showAll_other': '전체 {{count}}줄 표시', 'expandable.showFewer': '더 적은 줄 표시', 'splitDiff.view': '차이 보기', diff --git a/packages/starlight-codeblocks/src/languages/nb.ts b/packages/starlight-codeblocks/src/languages/nb.ts index a370127..a3f14cb 100644 --- a/packages/starlight-codeblocks/src/languages/nb.ts +++ b/packages/starlight-codeblocks/src/languages/nb.ts @@ -21,6 +21,7 @@ export default { 'hiddenLines.show_other': 'Vis {{count}} skjulte linjer', 'hiddenLines.hide_one': 'Skjul {{count}} linje', 'hiddenLines.hide_other': 'Skjul {{count}} linjer', + 'skippedCode.marker': 'Kode utelatt', 'expandable.showAll_one': 'Vis {{count}} linje', 'expandable.showAll_other': 'Vis alle {{count}} linjene', 'expandable.showFewer': 'Vis færre linjer', diff --git a/packages/starlight-codeblocks/src/languages/pl.ts b/packages/starlight-codeblocks/src/languages/pl.ts index b6dba0c..8020014 100644 --- a/packages/starlight-codeblocks/src/languages/pl.ts +++ b/packages/starlight-codeblocks/src/languages/pl.ts @@ -27,6 +27,7 @@ export default { 'hiddenLines.hide_few': 'Ukryj {{count}} wiersze', 'hiddenLines.hide_many': 'Ukryj {{count}} wierszy', 'hiddenLines.hide_other': 'Ukryj {{count}} wiersza', + 'skippedCode.marker': 'Pominięty kod', 'expandable.showAll_one': 'Pokaż {{count}} wiersz', 'expandable.showAll_few': 'Pokaż wszystkie {{count}} wiersze', 'expandable.showAll_many': 'Pokaż wszystkie {{count}} wierszy', diff --git a/packages/starlight-codeblocks/src/languages/pt.ts b/packages/starlight-codeblocks/src/languages/pt.ts index 212cd65..e572d0f 100644 --- a/packages/starlight-codeblocks/src/languages/pt.ts +++ b/packages/starlight-codeblocks/src/languages/pt.ts @@ -24,6 +24,7 @@ export default { 'hiddenLines.hide_one': 'Ocultar {{count}} linha', 'hiddenLines.hide_many': 'Ocultar {{count}} de linhas', 'hiddenLines.hide_other': 'Ocultar {{count}} linhas', + 'skippedCode.marker': 'Código omitido', 'expandable.showAll_one': 'Mostrar {{count}} linha', 'expandable.showAll_many': 'Mostrar {{count}} de linhas', 'expandable.showAll_other': 'Mostrar todas as {{count}} linhas', diff --git a/packages/starlight-codeblocks/src/languages/ru.ts b/packages/starlight-codeblocks/src/languages/ru.ts index 1452498..4b815cc 100644 --- a/packages/starlight-codeblocks/src/languages/ru.ts +++ b/packages/starlight-codeblocks/src/languages/ru.ts @@ -27,6 +27,7 @@ export default { 'hiddenLines.hide_few': 'Скрыть {{count}} строки', 'hiddenLines.hide_many': 'Скрыть {{count}} строк', 'hiddenLines.hide_other': 'Скрыть {{count}} строки', + 'skippedCode.marker': 'Код опущен', 'expandable.showAll_one': 'Показать все {{count}} строку', 'expandable.showAll_few': 'Показать все {{count}} строки', 'expandable.showAll_many': 'Показать все {{count}} строк', diff --git a/packages/starlight-codeblocks/src/languages/sv.ts b/packages/starlight-codeblocks/src/languages/sv.ts index 0664565..a4f28fa 100644 --- a/packages/starlight-codeblocks/src/languages/sv.ts +++ b/packages/starlight-codeblocks/src/languages/sv.ts @@ -21,6 +21,7 @@ export default { 'hiddenLines.show_other': 'Visa {{count}} dolda rader', 'hiddenLines.hide_one': 'Dölj {{count}} rad', 'hiddenLines.hide_other': 'Dölj {{count}} rader', + 'skippedCode.marker': 'Kod utelämnad', 'expandable.showAll_one': 'Visa {{count}} rad', 'expandable.showAll_other': 'Visa alla {{count}} rader', 'expandable.showFewer': 'Visa färre rader', diff --git a/packages/starlight-codeblocks/src/languages/tr.ts b/packages/starlight-codeblocks/src/languages/tr.ts index 12816b6..bcf7be3 100644 --- a/packages/starlight-codeblocks/src/languages/tr.ts +++ b/packages/starlight-codeblocks/src/languages/tr.ts @@ -21,6 +21,7 @@ export default { 'hiddenLines.show_other': '{{count}} gizli satırı göster', 'hiddenLines.hide_one': '{{count}} satırı gizle', 'hiddenLines.hide_other': '{{count}} satırı gizle', + 'skippedCode.marker': 'Kod gösterilmiyor', 'expandable.showAll_one': '{{count}} satırı göster', 'expandable.showAll_other': 'Tüm {{count}} satırı göster', 'expandable.showFewer': 'Daha az satır göster', diff --git a/packages/starlight-codeblocks/src/languages/zh.ts b/packages/starlight-codeblocks/src/languages/zh.ts index dda67f0..d8161d8 100644 --- a/packages/starlight-codeblocks/src/languages/zh.ts +++ b/packages/starlight-codeblocks/src/languages/zh.ts @@ -18,6 +18,7 @@ export default { 'hiddenLines.marker_other': '已隐藏 {{count}} 行', 'hiddenLines.show_other': '显示隐藏的 {{count}} 行', 'hiddenLines.hide_other': '隐藏 {{count}} 行', + 'skippedCode.marker': '代码已省略', 'expandable.showAll_other': '显示全部 {{count}} 行', 'expandable.showFewer': '显示较少的行', 'splitDiff.view': '差异视图', diff --git a/packages/starlight-codeblocks/src/options.ts b/packages/starlight-codeblocks/src/options.ts index 21504be..6519368 100644 --- a/packages/starlight-codeblocks/src/options.ts +++ b/packages/starlight-codeblocks/src/options.ts @@ -2,6 +2,7 @@ import { nextflow } from './adapters/nextflow.ts'; import { python } from './adapters/python.ts'; import type { FileIconLanguage, FileIconSet, FileIconStyle } from './expressive-code/file-icons.ts'; import { fileIconSets, isCssColour } from './expressive-code/file-icons.ts'; +import { defaultSkipAliases } from './expressive-code/skipped-code.ts'; import { type SwatchDelimiters, type SwatchFormat, @@ -89,6 +90,7 @@ export interface CodeblocksOptions { annotations?: false | { style?: 'filled' | 'outline' }; footnotes?: false | { sticky?: boolean; style?: 'filled' | 'outline' }; hiddenLines?: false; + skippedCode?: false | { commentAliases?: Record; bareAliases?: Record }; shellCopy?: false | { prompts?: string[] }; wordDiff?: false | { minSimilarity?: number }; splitDiff?: false | { view?: 'unified' | 'split'; switch?: boolean; sync?: boolean }; @@ -194,6 +196,8 @@ const isString = (value: unknown) => typeof value === 'string'; const isStringArray = (value: unknown) => Array.isArray(value) && value.every(isString); const isRecordOf = (valid: (value: unknown) => boolean) => (value: unknown) => isObject(value) && Object.values(value).every(valid); +const isAliasList = (value: unknown) => + isStringArray(value) && (value as string[]).every((alias) => alias.trim() !== ''); const oneOf = (...values: string[]) => (value: unknown) => @@ -206,7 +210,7 @@ const isDelimiters = (value: unknown) => // Attributes and directives of other features, which a custom state name would clash with. const reservedStateNames = new Set( - 'title frame mark ins del collapse wrap lang focus hidden hide highlight whitespace brackets swatches expandable playground id placeholder annotations footnotes label prefix step runnable note warn'.split( + 'title frame mark ins del collapse wrap lang focus hidden hide skip highlight whitespace brackets swatches expandable playground id placeholder annotations footnotes label prefix step runnable note warn'.split( ' ', ), ); @@ -317,6 +321,28 @@ export const optionsReference: Record = { description: 'Hides lines that readers need to run the code but not to understand it.', page: 'features/hidden-lines', }, + skippedCode: { + directives: true, + description: 'Shows a marker in place of code that a block leaves out.', + page: 'features/skipped-code', + off: '`[!code skip]` then stays in the code as written.', + fields: { + commentAliases: { + type: 'Record', + default: defaultSkipAliases.comment, + description: + 'Comments that stand for `[!code skip]` when they hold only an alias, such as `// ...`, by language. `*` applies to every language without its own entry, and `[]` turns aliases off for a language. Your keys merge over the defaults.', + valid: isRecordOf(isAliasList), + }, + bareAliases: { + type: 'Record', + default: defaultSkipAliases.bare, + description: + 'Lines that stand for `[!code skip]` when they hold only an alias, with no comment, by language, such as `...` in JSON. `*` applies to every language without its own entry, and `[]` turns aliases off for a language. Your keys merge over the defaults.', + valid: isRecordOf(isAliasList), + }, + }, + }, shellCopy: { description: 'Adds a Copy commands button to terminal blocks with prompts, which copies the commands only.', page: 'features/smart-shell-copy', diff --git a/packages/starlight-codeblocks/src/reference.ts b/packages/starlight-codeblocks/src/reference.ts index e42f4b7..8fbe714 100644 --- a/packages/starlight-codeblocks/src/reference.ts +++ b/packages/starlight-codeblocks/src/reference.ts @@ -775,6 +775,19 @@ export const styleSettingsReference: Record = { openOpacity: { description: 'The opacity of the code of a hidden line that shows.' }, }, }, + codeblocksSkippedCode: { + page: 'features/skipped-code', + settings: { + badgeBackground: { + description: 'The background of the text on a marker.', + derived: '`codeblocks.mutedForeground` at 10% opacity on the code background.', + }, + rule: { + description: 'The dotted rule of a marker.', + derived: '`codeblocks.mutedForeground` at 35% opacity.', + }, + }, + }, codeblocksRunnable: { page: 'features/run-code', settings: { diff --git a/packages/starlight-codeblocks/src/translations.ts b/packages/starlight-codeblocks/src/translations.ts index 662467b..6de00e7 100644 --- a/packages/starlight-codeblocks/src/translations.ts +++ b/packages/starlight-codeblocks/src/translations.ts @@ -32,6 +32,7 @@ export const uiStrings = { 'hiddenLines.show_other': 'Show {{count}} hidden lines', 'hiddenLines.hide_one': 'Hide {{count}} line', 'hiddenLines.hide_other': 'Hide {{count}} lines', + 'skippedCode.marker': 'Code not shown', 'expandable.showAll_one': 'Show all {{count}} line', 'expandable.showAll_other': 'Show all {{count}} lines', 'expandable.showFewer': 'Show fewer lines', diff --git a/packages/starlight-codeblocks/test/compat.test.ts b/packages/starlight-codeblocks/test/compat.test.ts index cdeba7e..e61b43c 100644 --- a/packages/starlight-codeblocks/test/compat.test.ts +++ b/packages/starlight-codeblocks/test/compat.test.ts @@ -99,6 +99,8 @@ test('colours keep their contrast when a theme sets the code background to a CSS } const badge = get('codeblocksHiddenLines.badgeBackground'); expect(getColorContrast(get('codeblocks.mutedForeground'), badge), `${name} hidden`).toBeGreaterThanOrEqual(4.5); + const skipBadge = get('codeblocksSkippedCode.badgeBackground'); + expect(getColorContrast(get('codeblocks.mutedForeground'), skipBadge), `${name} skip`).toBeGreaterThanOrEqual(4.5); expect(getColorContrast(get('codeblocksPermalinks.foreground'), bg), `${name} permalink`).toBeGreaterThanOrEqual( 4.5, ); diff --git a/packages/starlight-codeblocks/test/decorations.test.ts b/packages/starlight-codeblocks/test/decorations.test.ts index e3dcdb2..140fd80 100644 --- a/packages/starlight-codeblocks/test/decorations.test.ts +++ b/packages/starlight-codeblocks/test/decorations.test.ts @@ -11,6 +11,7 @@ const blocks = [ block('js title="a.js" hidden={1} id="x" playground="typescript" run', 'setup();', 'main();'), block('js annotations="side"', 'run(a); // [!annotate] Runs it.'), block('sh placeholder="TOKEN"', 'curl -H "Bearer TOKEN"'), + block('js', 'a();', '// [!code skip]', 'b();', '// [!code skip] **Rest**'), ]; /** The text of each element that matches `selector` without the marked decorations, as a tool that drops `.scb-deco` reads it. */ diff --git a/packages/starlight-codeblocks/test/notation.test.ts b/packages/starlight-codeblocks/test/notation.test.ts index b8a2cae..0757228 100644 --- a/packages/starlight-codeblocks/test/notation.test.ts +++ b/packages/starlight-codeblocks/test/notation.test.ts @@ -1,6 +1,6 @@ import { describe, expect, test } from 'vitest'; -import { commentSyntaxFor } from '../src/expressive-code/comments.ts'; -import { type DirectiveSpecs, parseLine, parseNotation } from '../src/expressive-code/notation.ts'; +import { commentSyntaxFor, forLanguage } from '../src/expressive-code/comments.ts'; +import { aliasesFor, type DirectiveSpecs, parseLine, parseNotation } from '../src/expressive-code/notation.ts'; const specs: DirectiveSpecs = { 'code focus': {}, @@ -10,6 +10,11 @@ const specs: DirectiveSpecs = { mention: {}, callout: { text: true }, link: {}, + 'code skip': { + text: true, + ownLine: true, + aliases: { comment: { '*': ['...'], md: [] }, bare: { json: ['...'], yaml: ['…'] } }, + }, }; const js = commentSyntaxFor('js'); @@ -157,12 +162,50 @@ describe('parseNotation', () => { [expect.stringContaining('has no line below it'), 2], ]); }); + + test('keeps the line of an ownLine directive, as a comment with its text', () => { + const { parsed, problems } = parseBlock(['a()', ' // [!code skip] Rest', '/* [!code skip] */']); + expect(problems).toEqual([]); + expect(parsed.map(({ text, removed }) => [text, removed])).toEqual([ + ['a()', false], + [' // Rest', false], + ['/* ... */', false], + ]); + expect(parsed[1]?.directives).toMatchObject([{ name: 'code skip', text: 'Rest' }]); + expect(parseLine('+ // [!code skip]', js, specs, () => {}, 1, true).text).toBe('+ // ...'); + }); + + test('drops an ownLine directive on a line with code, or with a count', () => { + const { parsed, problems } = parseBlock(['a() // [!code skip]', '// [!code skip:2]', 'b()']); + expect(parsed[0]).toMatchObject({ text: 'a()', directives: [] }); + expect(parsed[1]).toMatchObject({ text: '// [!code skip:2]', directives: [] }); + expect(problems).toEqual([ + [expect.stringContaining('goes on a line of its own'), 1], + [expect.stringContaining('takes no count'), 2], + ]); + }); + + test('reads a line that holds only an alias, in a comment or bare, by language', () => { + const skip = (lines: string[], lang = 'js') => + parseNotation(lines, commentSyntaxFor(lang), specs, () => {}, false, aliasesFor(specs, lang)).map( + ({ removed, directives }) => (removed ? 'removed' : directives.map((d) => d.name).join()), + ); + expect(skip(['a()', ' // ...', 'b()'])).toEqual(['', 'code skip', '']); + expect(skip(['a()', '/* ... */'])).toEqual(['', 'code skip']); + expect(skip(['{', ' ...', '}'], 'json')).toEqual(['', 'code skip', '']); + expect(skip(['a() // ...', '// ... more', '...', '//...x', '[...a]'])).toEqual(['', '', '', '', '']); + expect(skip(['def f():', ' ...', '# ...'], 'py')).toEqual(['', '', 'code skip']); + expect(skip([''], 'md')).toEqual(['']); + expect(skip(['a: 1', '…', '...', '# ...'], 'yml')).toEqual(['', 'code skip', '', 'code skip']); + }); }); test('commentSyntaxFor uses the built-in map, Shiki aliases and the options', () => { expect(commentSyntaxFor('Python')).toEqual([{ open: '#', close: undefined }]); expect(commentSyntaxFor('css')).toEqual([{ open: '/*', close: '*/' }]); expect(commentSyntaxFor('json')).toEqual([]); + expect(forLanguage('yml', { yaml: 1 })).toBe(1); + expect(forLanguage('fsharp', { json: 1 })).toBeUndefined(); expect(commentSyntaxFor('pwsh')).toEqual(commentSyntaxFor('powershell')); expect(commentSyntaxFor('shellsession')).toEqual([{ open: '#', close: undefined }]); expect(commentSyntaxFor('pwsh', { powershell: ['//'] })).toEqual([{ open: '//', close: undefined }]); diff --git a/packages/starlight-codeblocks/test/options.test.ts b/packages/starlight-codeblocks/test/options.test.ts index ae2d01d..dddfac8 100644 --- a/packages/starlight-codeblocks/test/options.test.ts +++ b/packages/starlight-codeblocks/test/options.test.ts @@ -14,6 +14,7 @@ test('turns every feature on with defaults, in new objects on each call', () => expect(options.footnotes).toEqual({ sticky: false, style: 'outline' }); expect(options.shellCopy).toEqual({ prompts: ['$ ', '> '] }); expect(options.expandable).toEqual({ lines: 12, auto: false }); + expect(options.skippedCode).toEqual({ commentAliases: { '*': ['...'] }, bareAliases: { json: ['...'] } }); expect(options.inlineHighlighting).toEqual({ defaultLanguage: false }); expect(options.playgrounds).toEqual({}); expect(options.walkthrough).toEqual({ start: 1 }); @@ -62,6 +63,9 @@ test('rejects options that are not valid, with an OptionsError that names the op [{ annotations: { style: 'solid' } }, '`annotations.style` must be'], [{ footnotes: { style: 'solid' } }, '`footnotes.style` must be'], [{ expandable: { lines: 0 } }, '`expandable.lines` must be number, got 0'], + [{ skippedCode: { aliases: ['...'] } }, 'unknown option `skippedCode.aliases`'], + [{ skippedCode: { commentAliases: { '*': [' '] } } }, '`skippedCode.commentAliases` must be'], + [{ skippedCode: { bareAliases: { json: '...' } } }, '`skippedCode.bareAliases` must be'], [{ wordDiff: { minSimilarity: 2 } }, '`wordDiff.minSimilarity`'], [{ lineStates: { states: { todo: { label: 'To do', colour: '#fff' } } } }, '`lineStates.states` must be'], [{ lineStates: { states: { focus: { label: 'F', colour } } } }, '`lineStates.states`'], diff --git a/packages/starlight-codeblocks/test/skipped-code.test.ts b/packages/starlight-codeblocks/test/skipped-code.test.ts new file mode 100644 index 0000000..87b32a7 --- /dev/null +++ b/packages/starlight-codeblocks/test/skipped-code.test.ts @@ -0,0 +1,152 @@ +import { pluginLineNumbers } from '@expressive-code/plugin-line-numbers'; +import { fromHtml } from 'hast-util-from-html'; +import { expect, test } from 'vitest'; +import { readTokens } from '../src/components/tokens.ts'; +import { markDecorations } from '../src/expressive-code/core.ts'; +import { block, render } from './render.ts'; + +const skipLines = (html: string) => + html.match(/
]*>.*?<\/div><\/div>/g) ?? []; + +test('draws a [!code skip] line as a marker, and copies it as a comment', async () => { + const { html, copyText, warnings } = await render( + block('js', 'function connect() {', ' // [!code skip]', ' return socket;', '}'), + ); + expect(skipLines(html)).toEqual([ + '
Code not shown
', + ]); + expect(copyText).toBe('function connect() {\n // ...\n return socket;\n}'); + expect(warnings).toEqual([]); +}); + +test('takes the marker text from the directive, with inline Markdown, and copies the text in the comment', async () => { + const { html, copyText } = await render(block('py', 'import os', '# [!code skip] The `main()` function', 'main()')); + expect(skipLines(html)).toEqual([expect.stringContaining('The main() function')]); + expect(copyText).toBe('import os\n# The `main()` function\nmain()'); +}); + +test('counts a [!code skip] line in line numbers and ranges', async () => { + const { html } = await render(block('js {3}', 'a();', '// [!code skip]', 'b();')); + expect(html).toMatch(/
.*?b<\/span>/); + const numbered = await render(block('js showLineNumbers', 'a();', '// [!code skip]', 'b();'), {}, [ + pluginLineNumbers(), + ]); + expect(skipLines(numbered.html)).toEqual([expect.stringMatching(/class="ln"[^>]*>2a<.*scb-skip-line.*More<\/span><\/span><\/div><\/div><\/code>/); +}); + +test('hides a [!code skip] line in a hidden run with the run', async () => { + const { html } = await render(block('js hidden={2-4}', 'a();', 'b();', '// [!code skip] Inside', 'c();', 'd();')); + expect(skipLines(html)).toEqual([expect.stringContaining('scb-skip-line scb-hidden-line scb-no-print')]); +}); + +test('warns about a [!code skip] on a line with code, with a count, or in output', async () => { + const { html, warnings } = await render(block('js', 'a(); // [!code skip]', '// [!code skip:2]', 'b();')); + expect(skipLines(html)).toEqual([]); + expect(warnings).toEqual([ + expect.stringContaining('goes on a line of its own'), + expect.stringContaining('`[!code skip:2]` takes no count'), + ]); + const output = await render(block('sh', 'make', '# [!output]', 'built', '# [!code skip]')); + expect(output.warnings).toEqual([expect.stringContaining('is not in the code, so it shows as a comment')]); +}); + +test('keeps a [!code skip] line before [!output] in the code', async () => { + const { html, warnings } = await render(block('sh', 'make', '# [!code skip] More', '# [!output]', 'built')); + expect(warnings).toEqual([]); + expect(skipLines(html)).toEqual([expect.stringContaining('More')]); +}); + +test('keeps the diff prefix and indentation of a [!code skip] line', async () => { + const short = await render(block('diff lang="js"', ' function f() {', '+ // ...', '+ return 1;', ' }')); + expect(skipLines(short.html)).toEqual([expect.stringContaining('
+ { + const js = await render(block('js', 'function connect() {', ' // ...', ' return socket;', '}')); + const directive = await render(block('js', 'function connect() {', ' // [!code skip]', ' return socket;', '}')); + expect(js.html).toBe(directive.html); + const json = await render(block('json', '{', ' "a": 1,', ' ...', '}')); + expect(skipLines(json.html)).toHaveLength(1); + expect(json.copyText).toBe('{\n "a": 1,\n ...\n}'); + expect(json.warnings).toEqual([]); +}); + +test('leaves `...` with no alias for its language, or with more text, as written', async () => { + for (const md of [ + block('py', 'def f():', ' ...'), + block('yaml', 'a: 1', '...'), + block('js', 'f(...args) // ...', '// ... more', '// [...]', '...'), + block('json', '[', ' "..."', ']'), + ]) { + expect(skipLines((await render(md)).html)).toEqual([]); + } +}); + +test('takes aliases by language, with `*` for the others, merged over the defaults', async () => { + const skippedCode = { commentAliases: { '*': ['…'], py: [] }, bareAliases: { yml: ['...'] } }; + const lines = async (md: string) => skipLines((await render(md, { skippedCode })).html).length; + expect(await lines(block('js', 'a();', '// …', '// ...', 'b();'))).toBe(1); + expect(await lines(block('py', 'a()', '# …'))).toBe(0); + expect(await lines(block('yaml', 'a: 1', '...', '# …'))).toBe(2); + expect(await lines(block('json', '{', ' ...', '}'))).toBe(1); + const custom = await render(block('js', 'a();', '// …', 'b();'), { skippedCode }); + expect(custom.copyText).toBe('a();\n// …\nb();'); +}); + +test('renders as without the feature when a block skips nothing, and leaves the directive when it is off', async () => { + const md = block('js title="a.js" {1}', 'a()', 'b()'); + expect((await render(md)).html).toBe((await render(md, { skippedCode: false })).html); + const { copyText, warnings } = await render(block('js', 'a() // [!code skip]'), { skippedCode: false }); + expect(copyText).toBe('a() // [!code skip]'); + expect(warnings).toHaveLength(1); +}); + +test('keeps the line state message of a [!code skip] line', async () => { + const { html } = await render(block('js', 'a();', '// [!code warn] Careful', '// [!code skip]', 'b();')); + expect(skipLines(html)).toEqual([ + '
Warning:Code not shown Careful
', + ]); +}); + +test('reads no diff prefix in a line that the diff syntax already shortened', async () => { + const { html, warnings } = await render(block('diff lang="yaml"', ' a:', ' - # [!code highlight]', '+ b: 1')); + expect(html).not.toContain('[!code'); + expect(warnings).toEqual([]); +}); + +test('gives no warning for an alias in output, and leaves it as written', async () => { + const sh = await render(block('sh', 'make', '# [!output]', 'built', '# ...')); + expect(sh.warnings).toEqual([]); + expect(sh.copyText).toBe('make'); + expect(sh.html).toContain('# ...'); +}); + +test('gives the text of a dropped [!code skip] to the next directive that takes text', async () => { + const { html, warnings } = await render(block('js', 'a(); // [!code skip error] Bad call')); + expect(skipLines(html)).toEqual([]); + expect(html).toMatch(/scb-state-label[^>]*>.*Bad call/); + expect(warnings).toEqual([expect.stringContaining('goes on a line of its own')]); +}); + +test('reads the comment of a [!code skip] line as its tokens', async () => { + const { html } = await render(block('js', 'a();', ' // [!code skip]', 'b();')); + const tree = fromHtml(html, { fragment: true }); + markDecorations(tree); + expect(readTokens(tree as never).code).toBe('a();\n // ...\nb();'); +}); diff --git a/packages/starlight-codeblocks/test/styles.test.ts b/packages/starlight-codeblocks/test/styles.test.ts index dbc8524..893cbbb 100644 --- a/packages/starlight-codeblocks/test/styles.test.ts +++ b/packages/starlight-codeblocks/test/styles.test.ts @@ -29,6 +29,7 @@ test('muted text meets 4.5:1 on the tinted surfaces it sits on', async () => { const bg = get('codeBackground'); const surfaces = [ get('codeblocksHiddenLines.badgeBackground'), + get('codeblocksSkippedCode.badgeBackground'), mix(bg, get('codeForeground'), 0.05), getFirstStaticColor(get('frames.editorTabBarBackground')), ]; diff --git a/scripts/readme-media.mjs b/scripts/readme-media.mjs index 847bc51..c1f51ce 100644 --- a/scripts/readme-media.mjs +++ b/scripts/readme-media.mjs @@ -67,6 +67,7 @@ const features = [ await rec.hold(1000); }, }, + { slug: 'skipped-code' }, { slug: 'smart-shell-copy', run: async (page, rec) => { diff --git a/skills/starlight-codeblocks/SKILL.md b/skills/starlight-codeblocks/SKILL.md index d445039..9acb4b1 100644 --- a/skills/starlight-codeblocks/SKILL.md +++ b/skills/starlight-codeblocks/SKILL.md @@ -1,12 +1,12 @@ --- name: starlight-codeblocks -description: Write, choose and configure code block features on Astro Starlight sites that use the starlight-codeblocks plugin. Covers focus, line states, squiggles, comment notation directives, annotations, footnotes, inline callouts, side annotations, scrollycoding, code mentions, word-level diff, split diff, code walkthrough, hidden lines, expandable blocks, visible whitespace, colourised brackets, colour swatches, file icons, inline code highlighting, code links, API auto-linking, line permalinks, code tabs, fill-in placeholders, smart shell copy, open in playground and run code. Use when you install or configure starlight-codeblocks, when you write or edit code blocks in .md, .mdx or .mdoc pages of a site that has it, when you add these features to the existing pages of a site, or when you must choose how to explain, highlight, compare, shorten, link or run code in Starlight docs. +description: Write, choose and configure code block features on Astro Starlight sites that use the starlight-codeblocks plugin. Covers focus, line states, squiggles, comment notation directives, annotations, footnotes, inline callouts, side annotations, scrollycoding, code mentions, word-level diff, split diff, code walkthrough, hidden lines, skipped code, expandable blocks, visible whitespace, colourised brackets, colour swatches, file icons, inline code highlighting, code links, API auto-linking, line permalinks, code tabs, fill-in placeholders, smart shell copy, open in playground and run code. Use when you install or configure starlight-codeblocks, when you write or edit code blocks in .md, .mdx or .mdoc pages of a site that has it, when you add these features to the existing pages of a site, or when you must choose how to explain, highlight, compare, shorten, link or run code in Starlight docs. license: MIT --- # starlight-codeblocks -starlight-codeblocks is a Starlight plugin. It adds 28 features to the code blocks that Expressive Code renders. A feature starts only when a code block uses its attribute or its directive, so the plugin does not change existing pages. A few features apply to every block of a type: they are in [Features that start on their own](#features-that-start-on-their-own). +starlight-codeblocks is a Starlight plugin. It adds 29 features to the code blocks that Expressive Code renders. A feature starts only when a code block uses its attribute or its directive, so the plugin does not change existing pages. A few features apply to every block of a type: they are in [Features that start on their own](#features-that-start-on-their-own). Full docs: https://ewels.github.io/starlight-codeblocks/. Each page has a Markdown version at the same address with `.md` at the end. https://ewels.github.io/starlight-codeblocks/llms-full.txt has every page in one file. @@ -77,6 +77,7 @@ Use scrollycoding when prose explains the code step by step as the reader scroll | Goal | Use | Why | |---|---|---| | Imports and set-up that readers need to run the code but not to understand it | Hidden lines: `hidden={1-3}` or `[!code hide]` | Named lines go behind a marker. The copy button still copies them. | +| Code that the example leaves out, where authors write `// ...` | Skipped code: `[!code skip]`, or `// ...`, which is an alias by default | The line shows as a marker and copies as a comment. The copied code is incomplete. | | A long file that readers scan | Expandable block: `expandable` or `expandable={N}` | Shows the first lines, with a button that shows the rest. | | Indentation or tabs change the meaning (Make, Python, YAML) | Visible whitespace: `whitespace` or `whitespace="all"` | Shows spaces and tabs as faint glyphs. | | Deep nesting on dense lines | Colourised brackets: `brackets` | Colours bracket pairs by depth. | @@ -165,6 +166,7 @@ These features need no attribute. Know them, because they can change a block tha - File icons apply to every block with a title in an editor frame. Turn them off for a block with `icon=false`, or for a file type or a language with `false` in `fileIcons.files` or `fileIcons.languages`. - Expandable blocks apply to every block longer than `expandable.auto` lines, if the site sets that option. Turn it off for a block with `expandable=false`. - Inline code highlighting applies to all inline code, if the site sets `inlineHighlighting.defaultLanguage`. Keep one piece plain with `{:txt}`. +- Skipped code reads every comment that holds only `...`, such as `// ...` or `# ...`, as a marker by default. It also reads `...` alone on its line in JSON. `skippedCode.commentAliases` and `skippedCode.bareAliases` change these per language. Only the look of those lines changes: they keep their line numbers and copy as written. To keep `// ...` as code in one block, add text to the comment, such as `// ... and so on`. If a page shows one feature, keep the others out of its examples with these attributes. @@ -175,7 +177,7 @@ If a page shows one feature, keep the others out of its examples with these attr - For inline code highlighting, put the suffix inside the backticks: `` `res.ok{:js}` ``. MDX reads `` `res.ok`{:js} `` as a JavaScript expression and the build fails. - A directive with an unknown name, or of a feature that is off, stays in the code and logs a build warning. So does a directive outside a comment that the block's language reads. Read the build warnings after every change: each gives the file, the block and the line. - Each `id` for line permalinks must be unique on the page, and must not match a heading id. -- Hidden lines still run in the copied code, in playgrounds and with `runnable`. Code for a playground or the **Run code** button must be complete. +- Hidden lines still run in the copied code, in playgrounds and with `runnable`. Code for a playground or the **Run code** button must be complete, so it cannot use `[!code skip]`. - Fill-in placeholder values stay in the browser's `localStorage` by default. For secrets such as API tokens, set `placeholders: { storage: 'session' }`. - In Markdoc (`.mdoc`) files, put attributes in a `meta` attribute: `` ```js {% meta="focus={2}" %} ``. Code tabs and inline code highlighting do not work there. - The `` component of Starlight gets every feature inside a block. Give the attributes in its `meta` prop. diff --git a/skills/starlight-codeblocks/references/configuration.md b/skills/starlight-codeblocks/references/configuration.md index f3edb4c..0a9af90 100644 --- a/skills/starlight-codeblocks/references/configuration.md +++ b/skills/starlight-codeblocks/references/configuration.md @@ -16,7 +16,7 @@ codeblocks({ }); ``` -To turn on only some features, list their keys in `only`. Every other feature is then off. A feature that reads directives in comments also turns on `notation`, unless `notation: false`. These are focus, line states, callouts, squiggles, annotations, footnotes, hidden lines, code links, code mentions and run code. Settings for a feature that is not in `only` stop the build. +To turn on only some features, list their keys in `only`. Every other feature is then off. A feature that reads directives in comments also turns on `notation`, unless `notation: false`. These are focus, line states, callouts, squiggles, annotations, footnotes, hidden lines, skipped code, code links, code mentions and run code. Settings for a feature that is not in `only` stop the build. ```js codeblocks({ only: ['focus', 'codeTabs'], codeTabs: { control: 'menu' } }); @@ -32,6 +32,7 @@ codeblocks({ only: ['focus', 'codeTabs'], codeTabs: { control: 'menu' } }); | `annotations` | `style`: `'filled'` or `'outline'`, default `'filled'` | Annotations and side annotations | | `footnotes` | `sticky`: default `false`. `style`: `'filled'` or `'outline'`, default `'outline'` | Footnotes | | `hiddenLines` | None | Hidden lines | +| `skippedCode` | `commentAliases`: comments that are the same as `[!code skip]`, by language, with `*` for the others, default `{ '*': ['...'] }`. `bareAliases`: lines with no comment, default `{ json: ['...'] }`. Keys merge over the defaults; `[]` turns a language off | Skipped code | | `shellCopy` | `prompts`: default `['$ ', '> ']`. Python `>>>` sessions need no prompt setting | Smart shell copy | | `wordDiff` | `minSimilarity`: from 0 to 1, default `0.4` | Word-level diff | | `splitDiff` | `view`: `'unified'` or `'split'`, default `'unified'`. `switch`: default `true`. `sync`: default `true` | Split diff | diff --git a/skills/starlight-codeblocks/references/explain-code.md b/skills/starlight-codeblocks/references/explain-code.md index 5a81ca1..2e820c4 100644 --- a/skills/starlight-codeblocks/references/explain-code.md +++ b/skills/starlight-codeblocks/references/explain-code.md @@ -191,7 +191,7 @@ app.listen(3000); - Leave an empty line after `` and before ``. Each code block is one step, in order. Each keeps its other attributes, such as `title`. - The walkthrough opens on its first step. For a Before and After pair, put Before first and add `start="last"`: the reader sees and copies After, and **Next** animates the change. `start="2"` in quotes works too. Any other value, or a number outside the steps, logs a build warning and opens the first step. - The copy button copies the code of the current step. -- Arrow keys move between steps when a numbered step has focus. Under reduced motion, steps change without the animation. A step with removed or added lines also changes without it, so the diff colours stay. +- Arrow keys move between steps when a numbered step has focus. Under reduced motion, steps change without the animation. A step with removed or added lines also changes without it, so the diff colours stay. So does a step with a callout or a hidden lines marker. - A line that is new in a step flashes the theme's green, then fades out in 1 second. There is no flash under reduced motion. - Without JavaScript, and when the page prints, each step shows as a separate block with its label after the title. - The page loads the animation library, about 3 kB, only on pages with ``. diff --git a/skills/starlight-codeblocks/references/readability.md b/skills/starlight-codeblocks/references/readability.md index fefe8c2..8b312ef 100644 --- a/skills/starlight-codeblocks/references/readability.md +++ b/skills/starlight-codeblocks/references/readability.md @@ -3,6 +3,7 @@ Seven features make a block, or the code in the prose, easier to read. None of them changes the copied text. - If lines are needed to run the code but not to understand it, hide them with hidden lines. +- If the example leaves code out, mark the place with skipped code, in place of a `// ...` comment. - If the whole file matters but readers scan it, cap it with an expandable block. - If every line matters but a few matter more, use focus, in [draw-attention.md](draw-attention.md). - If the exact whitespace changes the meaning, show it with visible whitespace. @@ -38,6 +39,34 @@ createServer(handler).listen(port); - Option: `hiddenLines: false` ignores `hidden` and leaves `[!code hide]` in the code. - Expressive Code's `collapse={range}` comes from `@expressive-code/plugin-collapsible-sections`. It keeps a summary line for each section and works without JavaScript. Hidden lines take only a thin marker, have a directive and a show-all button, and need JavaScript to open. The docs compare them: https://ewels.github.io/starlight-codeblocks/features/hidden-lines/#hidden-lines-or-collapsible-sections +## Skipped code + +Docs: https://ewels.github.io/starlight-codeblocks/features/skipped-code/ + +Use where an example shows part of a file and leaves code out. The `// ...` line shows as a marker, so readers do not read it as code. Use hidden lines instead if the copied code must run. + +| Syntax | Where | +|---|---| +| `[!code skip]` | Comment on its own line where the code is left out | +| `[!code skip] text` | The same, with `text` on the marker in place of "Code not shown" | + +```js +app.get('/users', async (req, res) => { + // [!code skip] Not shown: Read the users from the database +}); +// [!code skip] +``` + +- The marker is a dotted rule with a badge, at the indentation of the directive line. It is not a button. +- The marker is a line of the block: it has a line number, and line ranges count it. +- The copied code has the marker as a comment: `// text`, or `// ...` without text. It has no skipped code. Do not use it in a block with a playground or the **Run code** button. +- On a line with code, or with a count (`:N`), the directive logs a warning and does nothing. +- Aliases: lines that are the same as `[!code skip]`. `skippedCode.commentAliases` (default `{ '*': ['...'] }`) reads a comment that holds only an alias (`// ...`, `# ...`). `skippedCode.bareAliases` (default `{ json: ['...'] }`) reads the alias alone on its line, with no comment. Both are by language: `*` applies to every language without its own entry, your keys merge over the defaults, and `[]` turns a language off. For a bare `...` in YAML, set `bareAliases: { yaml: ['...'] }`. +- An alias changes only how the line looks. Line numbers, ranges and the copied code stay the same. +- A comment with other text, such as `// ... and so on`, stays in the code. Use it to keep `// ...` as code in one block. For a marker with text, use `[!code skip] text`. +- During the animation of a code walkthrough or scrollycoding step, a marker line shows empty. +- `skippedCode: false` leaves `[!code skip]` in the code. + ## Expandable blocks Docs: https://ewels.github.io/starlight-codeblocks/features/expandable-blocks/