diff --git a/docs/guide/pages-routing/markdown.md b/docs/guide/pages-routing/markdown.md index 10a9950d8..2bd7d673c 100644 --- a/docs/guide/pages-routing/markdown.md +++ b/docs/guide/pages-routing/markdown.md @@ -453,12 +453,14 @@ voidMarkdown({ shiki: { themes: { light: 'github-light', dark: 'github-dark' }, }, + copyLabel: 'Copy Code', }); ``` -| Option | Type | Default | Description | -| -------------- | -------------------------------- | ------------------------------------------------ | ------------------ | -| `shiki.themes` | `{ light: string; dark: string}` | `{ light: "github-light", dark: "github-dark" }` | Shiki color themes | +| Option | Type | Default | Description | +| -------------- | -------------------------------- | ------------------------------------------------ | --------------------------------------------------------- | +| `shiki.themes` | `{ light: string; dark: string}` | `{ light: "github-light", dark: "github-dark" }` | Shiki color themes | +| `copyLabel` | `string` | `"Copy Code"` | Title of the code block copy button, for translated sites | Code block languages load on demand from Shiki's bundled languages. diff --git a/packages/md/src/compile.ts b/packages/md/src/compile.ts index 8efe15a2b..48653d0c7 100644 --- a/packages/md/src/compile.ts +++ b/packages/md/src/compile.ts @@ -20,6 +20,7 @@ import { imagePlugin } from './plugins/image.ts'; import { lineNumberPlugin } from './plugins/line-numbers.ts'; import { linkPlugin } from './plugins/link.ts'; import { CODE_COPY_SCRIPT, preWrapperPlugin } from './plugins/pre-wrapper.ts'; +import { taskListPlugin } from './plugins/task-lists.ts'; import { tocPlugin } from './plugins/toc.ts'; export type Heading = Readonly<{ @@ -36,6 +37,8 @@ export type CompileResult = Readonly<{ }>; export type CompileOptions = Readonly<{ + /** Title of the code block copy button. Defaults to `Copy Code`. */ + copyLabel?: string; shiki?: { themes?: { light: string; dark: string }; /** @@ -102,7 +105,7 @@ async function createCompiler(options?: CompileOptions): Promise { }; // Code block wrapping (must come after shiki, before line-numbers) - markdown.use(preWrapperPlugin); + markdown.use(preWrapperPlugin, { copyLabel: options?.copyLabel }); markdown.use(containerPlugin); markdown.use(imagePlugin, { lazyLoading: true }); @@ -128,6 +131,8 @@ async function createCompiler(options?: CompileOptions): Promise { // heading-anchor targets. markdown.use(footnote); + markdown.use(taskListPlugin); + markdown.use(headingAnchorPlugin); markdown.use(tocPlugin); diff --git a/packages/md/src/plugin.ts b/packages/md/src/plugin.ts index 4cf797b1d..dce7d6fbe 100644 --- a/packages/md/src/plugin.ts +++ b/packages/md/src/plugin.ts @@ -40,6 +40,7 @@ export type MdPage = Readonly<{ }>; export type MarkdownOptions = Readonly<{ + copyLabel?: CompileOptions['copyLabel']; shiki?: CompileOptions['shiki']; }>; @@ -385,7 +386,10 @@ export function useFrontmatter() { return useContext(FrontmatterContext) ?? {}; }); const { compile } = await import('./compile.ts'); - const result = await compile(body, { shiki: options?.shiki }).catch((error: unknown) => { + const result = await compile(body, { + shiki: options?.shiki, + copyLabel: options?.copyLabel, + }).catch((error: unknown) => { throw createPageError(_id, error); }); diff --git a/packages/md/src/plugins/pre-wrapper.ts b/packages/md/src/plugins/pre-wrapper.ts index aafe4bb94..3319bf5b5 100644 --- a/packages/md/src/plugins/pre-wrapper.ts +++ b/packages/md/src/plugins/pre-wrapper.ts @@ -41,9 +41,11 @@ export const CODE_COPY_SCRIPT: string = /** * Wraps fenced code blocks with a language label and copy button. * Sets `env.codeCopy` so the page gets {@link CODE_COPY_SCRIPT}. + * `copyLabel` sets the copy button's title (default `Copy Code`). * Ported from VitePress. */ -export function preWrapperPlugin(md: MarkdownExit): void { +export function preWrapperPlugin(md: MarkdownExit, options?: { copyLabel?: string }): void { + const copyLabel = md.utils.escapeHtml(options?.copyLabel ?? 'Copy Code'); const fence = md.renderer.rules.fence as FenceRender; md.renderer.rules.fence = async (...args: Parameters) => { const [tokens, idx, , env] = args; @@ -58,7 +60,7 @@ export function preWrapperPlugin(md: MarkdownExit): void { const highlighted = await fence(...args); return ( `
` + - '' + + `` + `${lang}` + highlighted + `
` diff --git a/packages/md/src/plugins/task-lists.ts b/packages/md/src/plugins/task-lists.ts new file mode 100644 index 000000000..300edf069 --- /dev/null +++ b/packages/md/src/plugins/task-lists.ts @@ -0,0 +1,58 @@ +import type MarkdownExit from 'markdown-exit'; +import type { RuleCore, Token } from 'markdown-exit'; + +const markerRE = /^\[([ xX])\][ \t]+(?=\S)/; + +/** + * GitHub-style task lists: `- [ ] todo` and `- [x] done`. Each item gets a + * disabled checkbox and the `task-list-item` class, and its list gets + * `contains-task-list`, which the theme styles. + */ +export function taskListPlugin(md: MarkdownExit): void { + const rule: RuleCore = (state) => { + const tokens = state.tokens; + for (let index = 2; index < tokens.length; index++) { + const inline = tokens[index]; + if ( + inline.type !== 'inline' || + tokens[index - 1].type !== 'paragraph_open' || + tokens[index - 2].type !== 'list_item_open' + ) { + continue; + } + const match = markerRE.exec(inline.content); + const first = inline.children?.[0]; + if (!match || !first || first.type !== 'text' || !first.content.startsWith(match[0])) { + continue; + } + const item = tokens[index - 2]; + const checkbox = new state.Token('html_inline', '', 0); + checkbox.content = ` `; + first.content = first.content.slice(match[0].length); + inline.content = inline.content.slice(match[0].length); + inline.children!.unshift(checkbox); + item.attrJoin('class', 'task-list-item'); + const list = findParentList(tokens, index - 2); + if (list && !list.attrGet('class')?.split(' ').includes('contains-task-list')) { + list.attrJoin('class', 'contains-task-list'); + } + } + }; + md.core.ruler.after('inline', 'task_lists', rule); +} + +function findParentList(tokens: ReadonlyArray, itemIndex: number): Token | undefined { + const level = tokens[itemIndex].level - 1; + for (let index = itemIndex - 1; index >= 0; index--) { + const token = tokens[index]; + if ( + token.level === level && + (token.type === 'bullet_list_open' || token.type === 'ordered_list_open') + ) { + return token; + } + } + return undefined; +} diff --git a/packages/md/src/theme/code.css b/packages/md/src/theme/code.css index 918b7f4d4..4b511f668 100644 --- a/packages/md/src/theme/code.css +++ b/packages/md/src/theme/code.css @@ -50,7 +50,7 @@ .void-md div[class*='language-'] .copy { position: absolute; top: 0.5em; - right: 0.5em; + inset-inline-end: 0.5em; width: 2em; height: 2em; border: 1px solid var(--vmd-border, #e2e8f0); diff --git a/packages/md/src/theme/prose.css b/packages/md/src/theme/prose.css index c0e42b9a5..1f33919ef 100644 --- a/packages/md/src/theme/prose.css +++ b/packages/md/src/theme/prose.css @@ -87,7 +87,7 @@ /* Lists */ .void-md ul, .void-md ol { - padding-left: 1.5em; + padding-inline-start: 1.5em; margin-top: 0; margin-bottom: 1em; } @@ -163,9 +163,9 @@ /* Anchor links */ .void-md .header-anchor { - float: left; - margin-left: -0.87em; - padding-right: 0.23em; + float: inline-start; + margin-inline-start: -0.87em; + padding-inline-end: 0.23em; font-weight: 500; opacity: 0; transition: opacity 0.15s; @@ -181,20 +181,18 @@ } /* Task lists */ -.void-md ul.contains-task-list { - list-style: none; - padding-left: 0; -} - .void-md .task-list-item { - display: flex; - align-items: baseline; - gap: 0.5em; + list-style-type: none; } -.void-md .task-list-item input[type='checkbox'] { +.void-md .task-list-item-checkbox { + font: inherit; + width: 1em; + height: 1em; margin: 0; - flex-shrink: 0; + margin-inline-start: -1.5em; + margin-inline-end: 0.5em; + vertical-align: -0.125em; } /* Nested task lists */ diff --git a/packages/md/test/integration/theme-layout.test.ts b/packages/md/test/integration/theme-layout.test.ts new file mode 100644 index 000000000..3f50a8039 --- /dev/null +++ b/packages/md/test/integration/theme-layout.test.ts @@ -0,0 +1,97 @@ +import { readFileSync } from 'node:fs'; +import { chromium, type Browser } from 'playwright'; +import { afterAll, beforeAll, expect, it } from 'vite-plus/test'; +import { compile } from '../../src/compile.ts'; + +const css = ['reset.css', 'prose.css', 'code.css'] + .map((name) => readFileSync(new URL(`../../src/theme/${name}`, import.meta.url), 'utf8')) + .join('\n'); + +let browser: Browser; +let html: string; + +beforeAll(async () => { + const nested = await compile('- [ ] parent\n - [x] child\n - [ ] another child'); + const loose = await compile('- [ ] first paragraph\n\n second paragraph\n\n- ordinary item'); + const code = await compile('## Heading\n\n```js\nconst x = 1;\n```'); + html = `
+
${nested.html}
+
${loose.html}
+
${code.html}
+
`; + browser = await chromium.launch(); +}); + +afterAll(async () => { + await browser?.close(); +}); + +it.each(['ltr', 'rtl'])('keeps task-list content in block flow in %s', async (direction) => { + const page = await browser.newPage(); + try { + await page.setContent(`${html}`); + const layout = await page.evaluate(() => { + const parent = document.querySelector('#nested li')!; + const parentText = [...parent.childNodes].find((node) => node.nodeType === Node.TEXT_NODE)!; + const range = document.createRange(); + range.selectNode(parentText); + const paragraphs = document.querySelectorAll('#loose li:first-child > p'); + const ordinary = document.querySelector('#loose li:last-child')!; + return { + parentBottom: range.getBoundingClientRect().bottom, + childTop: parent.querySelector('ul')!.getBoundingClientRect().top, + firstParagraphBottom: paragraphs[0].getBoundingClientRect().bottom, + secondParagraphTop: paragraphs[1].getBoundingClientRect().top, + ordinaryMarker: getComputedStyle(ordinary).listStyleType, + taskMarker: getComputedStyle(parent).listStyleType, + checkboxes: [...document.querySelectorAll('input[type="checkbox"]')].map( + (input) => ({ disabled: input.disabled, checked: input.checked }), + ), + }; + }); + expect(layout.childTop).toBeGreaterThan(layout.parentBottom); + expect(layout.secondParagraphTop).toBeGreaterThanOrEqual(layout.firstParagraphBottom); + expect(layout.ordinaryMarker).not.toBe('none'); + expect(layout.taskMarker).toBe('none'); + expect(layout.checkboxes).toEqual([ + { disabled: true, checked: false }, + { disabled: true, checked: true }, + { disabled: true, checked: false }, + { disabled: true, checked: false }, + ]); + } finally { + await page.close(); + } +}); + +it.each(['ltr', 'rtl'])('positions heading anchors and copy buttons in %s', async (direction) => { + const page = await browser.newPage(); + try { + await page.setContent(`${html}`); + const layout = await page.evaluate(() => { + const rect = (selector: string) => + document.querySelector(selector)!.getBoundingClientRect().toJSON(); + return { + heading: rect('#code h2'), + anchor: rect('#code .header-anchor'), + code: rect('#code [class*="language-"]'), + copy: rect('#code .copy'), + }; + }); + if (direction === 'ltr') { + expect(layout.anchor.right).toBeLessThanOrEqual(layout.heading.left); + expect(layout.code.right - layout.copy.right).toBeLessThan( + layout.copy.left - layout.code.left, + ); + } else { + expect(layout.anchor.left).toBeGreaterThanOrEqual(layout.heading.right); + expect(layout.copy.left - layout.code.left).toBeLessThan( + layout.code.right - layout.copy.right, + ); + } + expect(layout.copy.left).toBeGreaterThan(layout.code.left); + expect(layout.copy.right).toBeLessThan(layout.code.right); + } finally { + await page.close(); + } +}); diff --git a/packages/md/test/unit/plugins.test.ts b/packages/md/test/unit/plugins.test.ts index 758d3c80e..3acaad78a 100644 --- a/packages/md/test/unit/plugins.test.ts +++ b/packages/md/test/unit/plugins.test.ts @@ -1,6 +1,7 @@ +import MarkdownExit from 'markdown-exit'; import { describe, expect, it } from 'vite-plus/test'; import { compile } from '../../src/compile.ts'; -import { CODE_COPY_SCRIPT } from '../../src/plugins/pre-wrapper.ts'; +import { CODE_COPY_SCRIPT, preWrapperPlugin } from '../../src/plugins/pre-wrapper.ts'; /** Runs the copy script, then clicks a copy button whose code block has these lines. */ function clickCopy(lines: Array, writeText: (text: string) => unknown): void { @@ -39,6 +40,18 @@ describe('plugins', () => { expect(result.html).toContain('class="lang"'); }); + it('uses Copy Code as the default copy button title', async () => { + const result = await compile('```js\nconst x = 1;\n```'); + expect(result.html).toContain(''); + }); + + it('uses the copyLabel option as the copy button title, escaped', async () => { + const md = new MarkdownExit({ html: true }); + md.use(preWrapperPlugin, { copyLabel: 'نسخ "الكود"' }); + const html = await md.renderAsync('```js\nconst x = 1;\n```'); + expect(html).toContain(''); + }); + it('adds one copy script per page with code blocks', async () => { const result = await compile('```js\nconst x = 1;\n```\n\n```sh\nnpm i\n```'); expect(result.html.match(/