Skip to content

Commit 13ca7fb

Browse files
harshbhxcpojer
andauthored
fix(md): render task lists and support right-to-left pages (#811)
Fixes #802 ## Summary Covers all four items of #802 for `@void/md`: task lists render as checkboxes, heading anchors and the code copy button mirror correctly on right-to-left pages, and the copy button title can be translated with a new `copyLabel` option. ## Problem 1. **Task lists.** The guide lists task lists as covered by the theme, and `prose.css` styles `.contains-task-list` and `.task-list-item`, but nothing in `compile.ts` produces them, so `- [ ] item` renders as the literal text `[ ] item`. 2. **Heading anchors in RTL.** `.header-anchor` in `packages/md/src/theme/prose.css` uses `float: left`, `margin-left` and `padding-right`, so in a `dir="rtl"` page the `#` sticks out past the left edge. 3. **Copy button in RTL.** `.copy` in `packages/md/src/theme/code.css` uses `right: 0.5em`. 4. **Copy button label.** `title="Copy Code"` in `packages/md/src/plugins/pre-wrapper.ts` is fixed in English. ## Solution 1. A small core rule in `packages/md/src/plugins/task-lists.ts`, registered in `compile.ts`. For a list item whose first paragraph starts with `[ ]`, `[x]` or `[X]` followed by text, it removes the marker, prepends a disabled checkbox (`checked` for `x`), adds `task-list-item` to the `li` and `contains-task-list` to its list. Look-alikes (`[ ]` with nothing after it, `[x]no space`, a marker mid-line, outside a list) are left alone. No new dependency; the class names match the existing CSS. 2. `float: inline-start`, `margin-inline-start`, `padding-inline-end`. Left-to-right pages render the same as before. 3. `inset-inline-end` instead of `right`. Same for left-to-right. 4. New `copyLabel` option on `voidMarkdown()` and `compile()`, default `Copy Code`, HTML-escaped before it goes into the `title` attribute. ## Changes | File | Change | |------|--------| | `packages/md/src/plugins/task-lists.ts` | New core rule for task lists | | `packages/md/src/compile.ts` | Register the plugin, `copyLabel` option, pass it to the pre-wrapper | | `packages/md/src/plugin.ts` | `copyLabel` in `MarkdownOptions`, passed to `compile()` | | `packages/md/src/plugins/pre-wrapper.ts` | Take `copyLabel` (default `Copy Code`), escaped | | `packages/md/src/theme/prose.css` | Logical properties for `.header-anchor` | | `packages/md/src/theme/code.css` | `inset-inline-end` for `.copy` | | `docs/guide/pages-routing/markdown.md` | Document `copyLabel` in Plugin Options | | `packages/md/test/unit/plugins.test.ts` | Task list tests, default and custom copy label tests | | `packages/md/test/unit/theme-css.test.ts` | Checks the anchor and copy button CSS use logical properties | ## Before / After Input `- [ ] todo` / `- [x] done`: Before: `<ul><li>[ ] todo</li><li>[x] done</li></ul>` After: ```html <ul class="contains-task-list"> <li class="task-list-item"><input class="task-list-item-checkbox" type="checkbox" disabled> todo</li> <li class="task-list-item"><input class="task-list-item-checkbox" type="checkbox" disabled checked> done</li> </ul> ``` Copy label: ```ts voidMarkdown({ copyLabel: 'نسخ الكود' }); // <button title="نسخ الكود" class="copy"></button> ``` ## How to test 1. Add a task list to any `.md` page in a playground using `@void/md` and check the checkboxes. 2. Set `dir="rtl"` on a page with headings and code blocks: the heading `#` should sit at the right of the heading and the copy button at the left end of the code block. 3. Set `copyLabel` in `voidMarkdown()` and hover the copy button. ## Testing done - [x] New unit tests for task lists (tight, loose, nested, ordered, look-alikes), for the default and custom (escaped) copy label, and for the logical properties in the two CSS rules - [x] The whole CI workflow (build and typecheck, unit tests including `vp check`, both integration shards) passed on my fork: https://github.com/harshbhx/void/actions/runs/43419615669. Earlier fork runs caught two mistakes in my own work (the list class was added once per item; two files not formatted), both fixed - [ ] No browser check: the RTL mirroring and the checkbox look are not verified visually, the CSS test only checks the property names - [ ] The new tests were not run against the unpatched code ## Notes for reviewers - Checkboxes are always `disabled`, like GitHub's rendering, since pages are static HTML. - `copyLabel` is read when the markdown compiler is first created, like `shiki`. --------- Co-authored-by: Christoph Nakazawa <cnakazawa@cloudflare.com>
1 parent d74ed2c commit 13ca7fb

9 files changed

Lines changed: 258 additions & 23 deletions

File tree

‎docs/guide/pages-routing/markdown.md‎

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -453,12 +453,14 @@ voidMarkdown({
453453
shiki: {
454454
themes: { light: 'github-light', dark: 'github-dark' },
455455
},
456+
copyLabel: 'Copy Code',
456457
});
457458
```
458459

459-
| Option | Type | Default | Description |
460-
| -------------- | -------------------------------- | ------------------------------------------------ | ------------------ |
461-
| `shiki.themes` | `{ light: string; dark: string}` | `{ light: "github-light", dark: "github-dark" }` | Shiki color themes |
460+
| Option | Type | Default | Description |
461+
| -------------- | -------------------------------- | ------------------------------------------------ | --------------------------------------------------------- |
462+
| `shiki.themes` | `{ light: string; dark: string}` | `{ light: "github-light", dark: "github-dark" }` | Shiki color themes |
463+
| `copyLabel` | `string` | `"Copy Code"` | Title of the code block copy button, for translated sites |
462464

463465
Code block languages load on demand from Shiki's bundled languages.
464466

‎packages/md/src/compile.ts‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@ import { imagePlugin } from './plugins/image.ts';
2020
import { lineNumberPlugin } from './plugins/line-numbers.ts';
2121
import { linkPlugin } from './plugins/link.ts';
2222
import { CODE_COPY_SCRIPT, preWrapperPlugin } from './plugins/pre-wrapper.ts';
23+
import { taskListPlugin } from './plugins/task-lists.ts';
2324
import { tocPlugin } from './plugins/toc.ts';
2425

2526
export type Heading = Readonly<{
@@ -36,6 +37,8 @@ export type CompileResult = Readonly<{
3637
}>;
3738

3839
export type CompileOptions = Readonly<{
40+
/** Title of the code block copy button. Defaults to `Copy Code`. */
41+
copyLabel?: string;
3942
shiki?: {
4043
themes?: { light: string; dark: string };
4144
/**
@@ -102,7 +105,7 @@ async function createCompiler(options?: CompileOptions): Promise<MarkdownExit> {
102105
};
103106

104107
// Code block wrapping (must come after shiki, before line-numbers)
105-
markdown.use(preWrapperPlugin);
108+
markdown.use(preWrapperPlugin, { copyLabel: options?.copyLabel });
106109

107110
markdown.use(containerPlugin);
108111
markdown.use(imagePlugin, { lazyLoading: true });
@@ -128,6 +131,8 @@ async function createCompiler(options?: CompileOptions): Promise<MarkdownExit> {
128131
// heading-anchor targets.
129132
markdown.use(footnote);
130133

134+
markdown.use(taskListPlugin);
135+
131136
markdown.use(headingAnchorPlugin);
132137

133138
markdown.use(tocPlugin);

‎packages/md/src/plugin.ts‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,7 @@ export type MdPage = Readonly<{
4040
}>;
4141

4242
export type MarkdownOptions = Readonly<{
43+
copyLabel?: CompileOptions['copyLabel'];
4344
shiki?: CompileOptions['shiki'];
4445
}>;
4546

@@ -385,7 +386,10 @@ export function useFrontmatter() { return useContext(FrontmatterContext) ?? {};
385386
});
386387

387388
const { compile } = await import('./compile.ts');
388-
const result = await compile(body, { shiki: options?.shiki }).catch((error: unknown) => {
389+
const result = await compile(body, {
390+
shiki: options?.shiki,
391+
copyLabel: options?.copyLabel,
392+
}).catch((error: unknown) => {
389393
throw createPageError(_id, error);
390394
});
391395

‎packages/md/src/plugins/pre-wrapper.ts‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -41,9 +41,11 @@ export const CODE_COPY_SCRIPT: string =
4141
/**
4242
* Wraps fenced code blocks with a language label and copy button.
4343
* Sets `env.codeCopy` so the page gets {@link CODE_COPY_SCRIPT}.
44+
* `copyLabel` sets the copy button's title (default `Copy Code`).
4445
* Ported from VitePress.
4546
*/
46-
export function preWrapperPlugin(md: MarkdownExit): void {
47+
export function preWrapperPlugin(md: MarkdownExit, options?: { copyLabel?: string }): void {
48+
const copyLabel = md.utils.escapeHtml(options?.copyLabel ?? 'Copy Code');
4749
const fence = md.renderer.rules.fence as FenceRender;
4850
md.renderer.rules.fence = async (...args: Parameters<FenceRender>) => {
4951
const [tokens, idx, , env] = args;
@@ -58,7 +60,7 @@ export function preWrapperPlugin(md: MarkdownExit): void {
5860
const highlighted = await fence(...args);
5961
return (
6062
`<div class="language-${lang}${active}">` +
61-
'<button title="Copy Code" class="copy"></button>' +
63+
`<button title="${copyLabel}" class="copy"></button>` +
6264
`<span class="lang">${lang}</span>` +
6365
highlighted +
6466
`</div>`
Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
import type MarkdownExit from 'markdown-exit';
2+
import type { RuleCore, Token } from 'markdown-exit';
3+
4+
const markerRE = /^\[([ xX])\][ \t]+(?=\S)/;
5+
6+
/**
7+
* GitHub-style task lists: `- [ ] todo` and `- [x] done`. Each item gets a
8+
* disabled checkbox and the `task-list-item` class, and its list gets
9+
* `contains-task-list`, which the theme styles.
10+
*/
11+
export function taskListPlugin(md: MarkdownExit): void {
12+
const rule: RuleCore = (state) => {
13+
const tokens = state.tokens;
14+
for (let index = 2; index < tokens.length; index++) {
15+
const inline = tokens[index];
16+
if (
17+
inline.type !== 'inline' ||
18+
tokens[index - 1].type !== 'paragraph_open' ||
19+
tokens[index - 2].type !== 'list_item_open'
20+
) {
21+
continue;
22+
}
23+
const match = markerRE.exec(inline.content);
24+
const first = inline.children?.[0];
25+
if (!match || !first || first.type !== 'text' || !first.content.startsWith(match[0])) {
26+
continue;
27+
}
28+
const item = tokens[index - 2];
29+
const checkbox = new state.Token('html_inline', '', 0);
30+
checkbox.content = `<input class="task-list-item-checkbox" type="checkbox" disabled${
31+
match[1] === ' ' ? '' : ' checked'
32+
}> `;
33+
first.content = first.content.slice(match[0].length);
34+
inline.content = inline.content.slice(match[0].length);
35+
inline.children!.unshift(checkbox);
36+
item.attrJoin('class', 'task-list-item');
37+
const list = findParentList(tokens, index - 2);
38+
if (list && !list.attrGet('class')?.split(' ').includes('contains-task-list')) {
39+
list.attrJoin('class', 'contains-task-list');
40+
}
41+
}
42+
};
43+
md.core.ruler.after('inline', 'task_lists', rule);
44+
}
45+
46+
function findParentList(tokens: ReadonlyArray<Token>, itemIndex: number): Token | undefined {
47+
const level = tokens[itemIndex].level - 1;
48+
for (let index = itemIndex - 1; index >= 0; index--) {
49+
const token = tokens[index];
50+
if (
51+
token.level === level &&
52+
(token.type === 'bullet_list_open' || token.type === 'ordered_list_open')
53+
) {
54+
return token;
55+
}
56+
}
57+
return undefined;
58+
}

‎packages/md/src/theme/code.css‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -50,7 +50,7 @@
5050
.void-md div[class*='language-'] .copy {
5151
position: absolute;
5252
top: 0.5em;
53-
right: 0.5em;
53+
inset-inline-end: 0.5em;
5454
width: 2em;
5555
height: 2em;
5656
border: 1px solid var(--vmd-border, #e2e8f0);

‎packages/md/src/theme/prose.css‎

Lines changed: 12 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -87,7 +87,7 @@
8787
/* Lists */
8888
.void-md ul,
8989
.void-md ol {
90-
padding-left: 1.5em;
90+
padding-inline-start: 1.5em;
9191
margin-top: 0;
9292
margin-bottom: 1em;
9393
}
@@ -163,9 +163,9 @@
163163

164164
/* Anchor links */
165165
.void-md .header-anchor {
166-
float: left;
167-
margin-left: -0.87em;
168-
padding-right: 0.23em;
166+
float: inline-start;
167+
margin-inline-start: -0.87em;
168+
padding-inline-end: 0.23em;
169169
font-weight: 500;
170170
opacity: 0;
171171
transition: opacity 0.15s;
@@ -181,20 +181,18 @@
181181
}
182182

183183
/* Task lists */
184-
.void-md ul.contains-task-list {
185-
list-style: none;
186-
padding-left: 0;
187-
}
188-
189184
.void-md .task-list-item {
190-
display: flex;
191-
align-items: baseline;
192-
gap: 0.5em;
185+
list-style-type: none;
193186
}
194187

195-
.void-md .task-list-item input[type='checkbox'] {
188+
.void-md .task-list-item-checkbox {
189+
font: inherit;
190+
width: 1em;
191+
height: 1em;
196192
margin: 0;
197-
flex-shrink: 0;
193+
margin-inline-start: -1.5em;
194+
margin-inline-end: 0.5em;
195+
vertical-align: -0.125em;
198196
}
199197

200198
/* Nested task lists */
Lines changed: 97 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,97 @@
1+
import { readFileSync } from 'node:fs';
2+
import { chromium, type Browser } from 'playwright';
3+
import { afterAll, beforeAll, expect, it } from 'vite-plus/test';
4+
import { compile } from '../../src/compile.ts';
5+
6+
const css = ['reset.css', 'prose.css', 'code.css']
7+
.map((name) => readFileSync(new URL(`../../src/theme/${name}`, import.meta.url), 'utf8'))
8+
.join('\n');
9+
10+
let browser: Browser;
11+
let html: string;
12+
13+
beforeAll(async () => {
14+
const nested = await compile('- [ ] parent\n - [x] child\n - [ ] another child');
15+
const loose = await compile('- [ ] first paragraph\n\n second paragraph\n\n- ordinary item');
16+
const code = await compile('## Heading\n\n```js\nconst x = 1;\n```');
17+
html = `<style>${css}</style><main class="void-md" style="margin: 40px">
18+
<section id="nested">${nested.html}</section>
19+
<section id="loose">${loose.html}</section>
20+
<section id="code">${code.html}</section>
21+
</main>`;
22+
browser = await chromium.launch();
23+
});
24+
25+
afterAll(async () => {
26+
await browser?.close();
27+
});
28+
29+
it.each(['ltr', 'rtl'])('keeps task-list content in block flow in %s', async (direction) => {
30+
const page = await browser.newPage();
31+
try {
32+
await page.setContent(`<html dir="${direction}"><body>${html}</body></html>`);
33+
const layout = await page.evaluate(() => {
34+
const parent = document.querySelector('#nested li')!;
35+
const parentText = [...parent.childNodes].find((node) => node.nodeType === Node.TEXT_NODE)!;
36+
const range = document.createRange();
37+
range.selectNode(parentText);
38+
const paragraphs = document.querySelectorAll('#loose li:first-child > p');
39+
const ordinary = document.querySelector('#loose li:last-child')!;
40+
return {
41+
parentBottom: range.getBoundingClientRect().bottom,
42+
childTop: parent.querySelector('ul')!.getBoundingClientRect().top,
43+
firstParagraphBottom: paragraphs[0].getBoundingClientRect().bottom,
44+
secondParagraphTop: paragraphs[1].getBoundingClientRect().top,
45+
ordinaryMarker: getComputedStyle(ordinary).listStyleType,
46+
taskMarker: getComputedStyle(parent).listStyleType,
47+
checkboxes: [...document.querySelectorAll<HTMLInputElement>('input[type="checkbox"]')].map(
48+
(input) => ({ disabled: input.disabled, checked: input.checked }),
49+
),
50+
};
51+
});
52+
expect(layout.childTop).toBeGreaterThan(layout.parentBottom);
53+
expect(layout.secondParagraphTop).toBeGreaterThanOrEqual(layout.firstParagraphBottom);
54+
expect(layout.ordinaryMarker).not.toBe('none');
55+
expect(layout.taskMarker).toBe('none');
56+
expect(layout.checkboxes).toEqual([
57+
{ disabled: true, checked: false },
58+
{ disabled: true, checked: true },
59+
{ disabled: true, checked: false },
60+
{ disabled: true, checked: false },
61+
]);
62+
} finally {
63+
await page.close();
64+
}
65+
});
66+
67+
it.each(['ltr', 'rtl'])('positions heading anchors and copy buttons in %s', async (direction) => {
68+
const page = await browser.newPage();
69+
try {
70+
await page.setContent(`<html dir="${direction}"><body>${html}</body></html>`);
71+
const layout = await page.evaluate(() => {
72+
const rect = (selector: string) =>
73+
document.querySelector(selector)!.getBoundingClientRect().toJSON();
74+
return {
75+
heading: rect('#code h2'),
76+
anchor: rect('#code .header-anchor'),
77+
code: rect('#code [class*="language-"]'),
78+
copy: rect('#code .copy'),
79+
};
80+
});
81+
if (direction === 'ltr') {
82+
expect(layout.anchor.right).toBeLessThanOrEqual(layout.heading.left);
83+
expect(layout.code.right - layout.copy.right).toBeLessThan(
84+
layout.copy.left - layout.code.left,
85+
);
86+
} else {
87+
expect(layout.anchor.left).toBeGreaterThanOrEqual(layout.heading.right);
88+
expect(layout.copy.left - layout.code.left).toBeLessThan(
89+
layout.code.right - layout.copy.right,
90+
);
91+
}
92+
expect(layout.copy.left).toBeGreaterThan(layout.code.left);
93+
expect(layout.copy.right).toBeLessThan(layout.code.right);
94+
} finally {
95+
await page.close();
96+
}
97+
});

0 commit comments

Comments
 (0)