Skip to content

Commit

Permalink
feat: gives access to the hooks data through the Lexer object
Browse files Browse the repository at this point in the history
  • Loading branch information
bent10 committed Oct 1, 2023
1 parent 7574dc8 commit bd55ce7
Show file tree
Hide file tree
Showing 3 changed files with 37 additions and 3 deletions.
13 changes: 11 additions & 2 deletions packages/code-preview/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,11 +13,20 @@ export default function markedCodePreview(
return {
extensions: [
{
name: 'code',
name: 'fences',
level: 'block',
tokenizer(_, parent) {
const hooksData: Pick<Options, 'data'> = {}
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

Expand All @@ -28,7 +37,7 @@ export default function markedCodePreview(
transform(token, {
index,
parent,
data: { ...data, ...meta },
data: { ...hooksData, ...data, ...meta },
...restOptions
})
})
Expand Down
5 changes: 5 additions & 0 deletions packages/code-preview/test/__snapshots__/index.test.ts.snap
Original file line number Diff line number Diff line change
@@ -1,5 +1,10 @@
// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html

exports[`should have access to the hooks data 1`] = `
"<h1>Example</h1>
bar"
`;

exports[`should not transform code blocks that do not have \`preview\` attribute 1`] = `
"<pre><code class=\\"language-jsx\\">&lt;Foo /&gt;
</code></pre>
Expand Down
22 changes: 21 additions & 1 deletion packages/code-preview/test/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
<Foo />
\`\`\`
`
`

const html = new Marked()
.use({ gfm: true })
Expand Down

0 comments on commit bd55ce7

Please sign in to comment.