| 12 | } |
| 13 | |
| 14 | export function buildMarkdownPages(markdown = "", fallbackTitle = "Markdown") { |
| 15 | const source = String(markdown || ""); |
| 16 | const lines = source.split("\n"); |
| 17 | const pages = []; |
| 18 | let current = null; |
| 19 | let intro = []; |
| 20 | let introStart = 0; |
| 21 | let fenced = false; |
| 22 | let offset = 0; |
| 23 | |
| 24 | const startPage = (title, level, line, start) => { |
| 25 | if (current) { |
| 26 | current.end = start; |
| 27 | pages.push(finalizePage(current, pages.length, source)); |
| 28 | } |
| 29 | current = { |
| 30 | title: cleanHeadingText(title) || fallbackTitle, |
| 31 | level, |
| 32 | lines: [line], |
| 33 | start, |
| 34 | end: source.length, |
| 35 | }; |
| 36 | }; |
| 37 | |
| 38 | for (const [index, line] of lines.entries()) { |
| 39 | const lineStart = offset; |
| 40 | const lineEnd = lineStart + line.length + (index < lines.length - 1 ? 1 : 0); |
| 41 | if (/^\s*```/.test(line)) fenced = !fenced; |
| 42 | const match = !fenced ? line.match(PAGE_HEADING_RE) : null; |
| 43 | if (match) { |
| 44 | if (!current && intro.join("\n").trim()) { |
| 45 | pages.push(finalizePage({ |
| 46 | title: fallbackTitle, |
| 47 | level: 0, |
| 48 | lines: intro, |
| 49 | start: introStart, |
| 50 | end: lineStart, |
| 51 | }, pages.length, source)); |
| 52 | intro = []; |
| 53 | } |
| 54 | startPage(match[2], match[1].length, line, lineStart); |
| 55 | offset = lineEnd; |
| 56 | continue; |
| 57 | } |
| 58 | if (current) current.lines.push(line); |
| 59 | else intro.push(line); |
| 60 | offset = lineEnd; |
| 61 | } |
| 62 | |
| 63 | if (current) { |
| 64 | current.end = source.length; |
| 65 | pages.push(finalizePage(current, pages.length, source)); |
| 66 | } |
| 67 | else if (intro.join("\n").trim() || !pages.length) { |
| 68 | pages.push(finalizePage({ |
| 69 | title: fallbackTitle, |
| 70 | level: 0, |
| 71 | lines: intro, |