diff --git a/packages/code-preview/src/index.ts b/packages/code-preview/src/index.ts index 1b2434e..30c669f 100644 --- a/packages/code-preview/src/index.ts +++ b/packages/code-preview/src/index.ts @@ -13,11 +13,20 @@ export default function markedCodePreview( return { extensions: [ { - name: 'code', + name: 'fences', level: 'block', tokenizer(_, parent) { + const hooksData: Pick = {} const { data, ...restOptions } = options + if ( + this.lexer.options.hooks && + this.lexer.options.hooks !== null && + 'data' in this.lexer.options.hooks + ) { + Object.assign(hooksData, this.lexer.options.hooks.data) + } + parent.forEach((token, index) => { if (token.type !== 'code' || !token.lang) return @@ -28,7 +37,7 @@ export default function markedCodePreview( transform(token, { index, parent, - data: { ...data, ...meta }, + data: { ...hooksData, ...data, ...meta }, ...restOptions }) }) diff --git a/packages/code-preview/test/__snapshots__/index.test.ts.snap b/packages/code-preview/test/__snapshots__/index.test.ts.snap index e78047f..e059816 100644 --- a/packages/code-preview/test/__snapshots__/index.test.ts.snap +++ b/packages/code-preview/test/__snapshots__/index.test.ts.snap @@ -1,5 +1,10 @@ // Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html +exports[`should have access to the hooks data 1`] = ` +"

Example

+bar" +`; + exports[`should not transform code blocks that do not have \`preview\` attribute 1`] = ` "
<Foo />
 
diff --git a/packages/code-preview/test/index.test.ts b/packages/code-preview/test/index.test.ts index 55ca128..7615130 100644 --- a/packages/code-preview/test/index.test.ts +++ b/packages/code-preview/test/index.test.ts @@ -37,12 +37,32 @@ it('should use a custom template when provided in options', () => { expect(html).toMatchSnapshot() }) +it('should have access to the hooks data', () => { + const html = new Marked() + .use({ gfm: true }) + .use({ + hooks: { + preprocess(markdown) { + this.data = { foo: 'bar' } + return markdown + }, + postprocess(html) { + return html + } + } + }) + .use(markedCodePreview({ template: '{foo}' })) + .parse(md) + + expect(html).toMatchSnapshot() +}) + it('should not transform code blocks that do not have `preview` attribute', () => { const md = ` \`\`\`jsx \`\`\` - ` +` const html = new Marked() .use({ gfm: true })