From a1d7b9d0ee8b7382050301981d800f4da5828c1f Mon Sep 17 00:00:00 2001 From: Zach Badgett Date: Wed, 17 Apr 2019 20:06:52 -0600 Subject: [PATCH] refactor: refactor code tab split --- packages/docusaurus-1.x/lib/core/Doc.js | 87 ++++++++++++++++++++++--- 1 file changed, 78 insertions(+), 9 deletions(-) diff --git a/packages/docusaurus-1.x/lib/core/Doc.js b/packages/docusaurus-1.x/lib/core/Doc.js index d31505f0bb5f7..306212950b25f 100644 --- a/packages/docusaurus-1.x/lib/core/Doc.js +++ b/packages/docusaurus-1.x/lib/core/Doc.js @@ -20,16 +20,85 @@ const translateThisDoc = translate( ); const splitTabsToTitleAndContent = content => { - const titles = content.match(//gms); - const tabs = content.split(//gms); - if (!titles || !tabs || !titles.length || !tabs.length) { - return []; + const lines = content.split(/\n/g); + let first = false; + let inBlock = false; + let whitespace = false; + const tc = []; + let current = { + content: [], + }; + lines.forEach(line => { + let pos = 0; + const end = line.length; + const isToken = (cline, cpos, ...chars) => { + for (let i = 0; i < chars.length; i++) { + if (cline.charCodeAt(pos) !== chars[i]) { + return false; + } + pos++; + } + return true; + }; + while (pos + 1 < end) { + for (let max = end; pos < max; pos++) { + if (line.charCodeAt(pos) !== 0x20 && line.charCodeAt(pos) !== 0x0a) { + break; + } + whitespace = true; + } + if (isToken(line, pos, 0x3c, 0x21, 0x2d, 0x2d) && !inBlock) { + if (current !== null && current.title !== undefined) { + tc.push({ + title: current.title.trim(), + content: current.content.join('\n'), + }); + current = { + content: [], + }; + } + first = true; + pos += 4; + let b0; + let b1; + const buf = []; + for (let max = end; pos < max; pos++) { + const b = line.charCodeAt(pos); + if (b0 === 0x2d && b1 === 0x2d) { + if (b !== 0x3e) { + throw new Error(`Invalid comment sequence "--"`); + } + break; + } + buf.push(b); + b0 = b1; + b1 = b; + } + line = '\n'; + current.title = String.fromCharCode(...buf).substring( + 0, + buf.length - 3, + ); + } + if (!first) { + throw new Error(`Invalid code tab markdown`); + } + if (isToken(line, pos, 0x60, 0x60, 0x60) && !whitespace) { + pos += 3; + inBlock = !inBlock; + } + pos++; + whitespace = false; + } + current.content.push(line); + }); + if (current !== null && current.title !== undefined) { + tc.push({ + title: current.title.trim(), + content: current.content.join('\n'), + }); } - tabs.shift(); - return titles.map((title, idx) => ({ - title: title.substring(4, title.length - 3).trim(), - content: tabs[idx], - })); + return tc; }; const cleanTheCodeTag = content => {