Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 5 additions & 3 deletions docs/guide/pages-routing/markdown.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down
7 changes: 6 additions & 1 deletion packages/md/src/compile.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<{
Expand All @@ -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 };
/**
Expand Down Expand Up @@ -102,7 +105,7 @@ async function createCompiler(options?: CompileOptions): Promise<MarkdownExit> {
};

// 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 });
Expand All @@ -128,6 +131,8 @@ async function createCompiler(options?: CompileOptions): Promise<MarkdownExit> {
// heading-anchor targets.
markdown.use(footnote);

markdown.use(taskListPlugin);

markdown.use(headingAnchorPlugin);

markdown.use(tocPlugin);
Expand Down
6 changes: 5 additions & 1 deletion packages/md/src/plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ export type MdPage = Readonly<{
}>;

export type MarkdownOptions = Readonly<{
copyLabel?: CompileOptions['copyLabel'];
shiki?: CompileOptions['shiki'];
}>;

Expand Down Expand Up @@ -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);
});

Expand Down
6 changes: 4 additions & 2 deletions packages/md/src/plugins/pre-wrapper.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<FenceRender>) => {
const [tokens, idx, , env] = args;
Expand All @@ -58,7 +60,7 @@ export function preWrapperPlugin(md: MarkdownExit): void {
const highlighted = await fence(...args);
return (
`<div class="language-${lang}${active}">` +
'<button title="Copy Code" class="copy"></button>' +
`<button title="${copyLabel}" class="copy"></button>` +
`<span class="lang">${lang}</span>` +
highlighted +
`</div>`
Expand Down
58 changes: 58 additions & 0 deletions packages/md/src/plugins/task-lists.ts
Original file line number Diff line number Diff line change
@@ -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 = `<input class="task-list-item-checkbox" type="checkbox" disabled${
match[1] === ' ' ? '' : ' checked'
}> `;
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<Token>, 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;
}
2 changes: 1 addition & 1 deletion packages/md/src/theme/code.css
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
26 changes: 12 additions & 14 deletions packages/md/src/theme/prose.css
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}
Expand Down Expand Up @@ -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;
Expand All @@ -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 */
Expand Down
97 changes: 97 additions & 0 deletions packages/md/test/integration/theme-layout.test.ts
Original file line number Diff line number Diff line change
@@ -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 = `<style>${css}</style><main class="void-md" style="margin: 40px">
<section id="nested">${nested.html}</section>
<section id="loose">${loose.html}</section>
<section id="code">${code.html}</section>
</main>`;
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 dir="${direction}"><body>${html}</body></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<HTMLInputElement>('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 dir="${direction}"><body>${html}</body></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();
}
});
Loading