From 151ac309d8fda2f69b344c36afad019333923e34 Mon Sep 17 00:00:00 2001 From: "Daniel W. Hieber" Date: Thu, 19 Sep 2024 17:49:44 -0500 Subject: [PATCH] FIX: Inline translations duplicating surrounding content --- plugins/translations.js | 27 ++++++++++++++++----------- 1 file changed, 16 insertions(+), 11 deletions(-) diff --git a/plugins/translations.js b/plugins/translations.js index 59df1d0..3b8b229 100644 --- a/plugins/translations.js +++ b/plugins/translations.js @@ -14,7 +14,12 @@ export default function translations(md, { tag }) { const inlineTokens = token.children - for (const inlineToken of inlineTokens) { + // Process inlineTokens in reverse order. Not sure why, but content gets duplicated otherwise. + // The core rules in markdown-it itself iterate over the tokens in reverse order: + // https://github.com/markdown-it/markdown-it/blob/master/lib/rules_core/replacements.mjs + for (let i = inlineTokens.length - 1; i >= 0; i--) { + + const inlineToken = inlineTokens[i] if (inlineToken.type !== `text`) continue @@ -24,7 +29,7 @@ export default function translations(md, { tag }) { if (!matches.length) continue const newTokens = [] - let lastIndex = 0 // The index of the end of the previous match. + let lastIndex = 0 // The index of the end of the previous match. for (const match of matches) { @@ -51,18 +56,18 @@ export default function translations(md, { tag }) { newTokens.push(openingTag, contentToken, closingTag) // Add the new tokens. lastIndex = match.index + match[0].length // Update the index of the end of the previous match. - // If there is text after the last match, add it as a text token. - if (lastIndex < content.length) { - const textToken = new Token(`text`, ``, 0) - textToken.content = content.slice(lastIndex) - newTokens.push(textToken) - } - - // Replace the original token with the new tokens. - inlineTokens.splice(inlineTokens.indexOf(inlineToken), 1, ...newTokens) + } + // If there is text after the last match, add it as a text token. + if (lastIndex < content.length) { + const textToken = new Token(`text`, ``, 0) + textToken.content = content.slice(lastIndex) + newTokens.push(textToken) } + // Replace the original token with the new tokens. + inlineTokens.splice(i, 1, ...newTokens) + } }