From dfe6494f21999a3709f3e1b57a9393984907a971 Mon Sep 17 00:00:00 2001 From: Tony Brix Date: Sat, 20 Jan 2024 12:59:43 -0700 Subject: [PATCH] feat: flatten childToken arrays --- src/Instance.ts | 3 ++- test/unit/marked.test.js | 37 +++++++++++++++++++++++++++++++++++++ 2 files changed, 39 insertions(+), 1 deletion(-) diff --git a/src/Instance.ts b/src/Instance.ts index 2f8c7b6425..eb460e0642 100644 --- a/src/Instance.ts +++ b/src/Instance.ts @@ -63,7 +63,8 @@ export class Marked { const genericToken = token as Tokens.Generic; if (this.defaults.extensions?.childTokens?.[genericToken.type]) { this.defaults.extensions.childTokens[genericToken.type].forEach((childTokens) => { - values = values.concat(this.walkTokens(genericToken[childTokens], callback)); + const tokens = genericToken[childTokens].flat(Infinity) as Token[] | TokensList; + values = values.concat(this.walkTokens(tokens, callback)); }); } else if (genericToken.tokens) { values = values.concat(this.walkTokens(genericToken.tokens, callback)); diff --git a/test/unit/marked.test.js b/test/unit/marked.test.js index a56fd1f7d6..bbff1c04bf 100644 --- a/test/unit/marked.test.js +++ b/test/unit/marked.test.js @@ -395,6 +395,43 @@ describe('marked unit', () => { + '\n
Topic 2 walked - unwalked
Description 2 walked

\n'); }); + it('should walk child token arrays', () => { + const walkableDescription = { + extensions: [{ + name: 'walkableDescription', + level: 'inline', + start(src) { return src.indexOf(':'); }, + tokenizer(src, tokens) { + const rule = /^:([^:\n]+):([^:\n]*)(?:\n|$)/; + const match = rule.exec(src); + if (match) { + const token = { + type: 'walkableDescription', + raw: match[0], + dt: [this.lexer.inline(match[1].trim())], + dd: [[this.lexer.inline(match[2].trim())]] + }; + return token; + } + }, + renderer(token) { + return `\n
${this.parser.parseInline(token.dt[0])}
${this.parser.parseInline(token.dd[0][0])}
`; + }, + childTokens: ['dd', 'dt'] + }], + walkTokens(token) { + if (token.type === 'text') { + token.text += ' walked'; + } + } + }; + marked.use(walkableDescription); + const html = marked.parse(': Topic 1 : Description 1\n' + + ': **Topic 2** : *Description 2*'); + assert.strictEqual(html, '

\n

Topic 1 walked
Description 1 walked
' + + '\n
Topic 2 walked
Description 2 walked

\n'); + }); + describe('multiple extensions', () => { function createExtension(name) { return {