1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
|
import type {
Blockquote,
Code,
Definition,
Delete,
Emphasis,
FootnoteDefinition,
FootnoteReference,
Heading,
Html,
Image,
InlineCode,
Link,
List,
ListItem,
Paragraph,
PhrasingContent,
Root,
RootContent,
Strong,
Table,
TableCell,
TableRow,
Text as MdastText,
ThematicBreak,
} from "mdast";
import type {
ContainerDirective,
LeafDirective,
TextDirective,
} from "mdast-util-directive";
import {
a,
article,
div,
elem,
Element,
img,
li,
Node,
ol,
p,
rawHTML,
section,
span,
text,
ul,
} from "../dom.ts";
type DirectiveNode = ContainerDirective | LeafDirective | TextDirective;
function isDirective(node: RootContent): node is DirectiveNode {
return (
node.type === "containerDirective" ||
node.type === "leafDirective" ||
node.type === "textDirective"
);
}
// Extract section ID and attributes from heading if present
// Supports syntax like {#id} or {#id attr="value"}
function extractSectionId(
node: Heading,
): {
id: string | null;
attributes: Record<string, string>;
children: Heading["children"];
} {
if (node.children.length === 0) {
return { id: null, attributes: {}, children: node.children };
}
const lastChild = node.children[node.children.length - 1];
if (lastChild && lastChild.type === "text") {
// Match {#id ...} or {#id attr="value" ...}
const match = lastChild.value.match(/\s*\{#([^\s}]+)([^}]*)\}\s*$/);
if (match) {
const id = match[1];
const attrString = match[2].trim();
const attributes: Record<string, string> = {};
// Parse attributes like toc="false" (supports smart quotes too)
// U+0022 = ", U+201C = ", U+201D = "
const attrRegex =
/(\w+)=["\u201c\u201d]([^"\u201c\u201d]*)["\u201c\u201d]/g;
let attrMatch;
while ((attrMatch = attrRegex.exec(attrString)) !== null) {
attributes[attrMatch[1]] = attrMatch[2];
}
const newValue = lastChild.value.replace(/\s*\{#[^}]+\}\s*$/, "");
if (newValue === "") {
return { id, attributes, children: node.children.slice(0, -1) };
} else {
const newChildren = [...node.children];
newChildren[newChildren.length - 1] = { ...lastChild, value: newValue };
return { id, attributes, children: newChildren };
}
}
}
return { id: null, attributes: {}, children: node.children };
}
function processBlock(node: RootContent): Element | Element[] | null {
switch (node.type) {
case "heading":
// Headings are handled specially in mdast2ndoc
return null;
case "paragraph":
return processParagraph(node);
case "thematicBreak":
return processThematicBreak(node);
case "blockquote":
return processBlockquote(node);
case "code":
return processCode(node);
case "list":
return processList(node);
case "table":
return processTable(node);
case "html":
return processHtmlBlock(node);
case "definition":
return processDefinition(node);
case "footnoteDefinition":
return processFootnoteDefinition(node);
default:
if (isDirective(node)) {
return processDirective(node);
}
return null;
}
}
function processParagraph(node: Paragraph): Element {
return p({}, ...node.children.map(processInline));
}
function processThematicBreak(_node: ThematicBreak): Element {
return elem("hr", {});
}
function processBlockquote(node: Blockquote): Element {
const children: Node[] = [];
for (const child of node.children) {
const result = processBlock(child);
if (result) {
if (Array.isArray(result)) {
children.push(...result);
} else {
children.push(result);
}
}
}
return elem("blockquote", {}, ...children);
}
function processCode(node: Code): Element {
const attributes: Record<string, string> = {};
if (node.lang) {
attributes.language = node.lang;
}
// Parse meta string for filename and numbered attributes
if (node.meta) {
const filenameMatch = node.meta.match(/filename="([^"]+)"/);
if (filenameMatch) {
attributes.filename = filenameMatch[1];
}
if (node.meta.includes("numbered")) {
attributes.numbered = "true";
}
}
return elem("codeblock", attributes, text(node.value));
}
function processList(node: List): Element {
const attributes: Record<string, string> = {};
attributes.__tight = node.spread === false ? "true" : "false";
const isTaskList = node.children.some(
(item) => item.checked !== null && item.checked !== undefined,
);
if (isTaskList) {
attributes.type = "task";
}
if (node.ordered && node.start !== null && node.start !== 1) {
attributes.start = node.start!.toString();
}
const children = node.children.map((item) =>
processListItem(item, isTaskList)
);
return node.ordered
? ol(attributes, ...children)
: ul(attributes, ...children);
}
function processListItem(node: ListItem, isTaskList: boolean): Element {
const attributes: Record<string, string> = {};
if (isTaskList) {
attributes.checked = node.checked ? "true" : "false";
}
const children: Node[] = [];
for (const child of node.children) {
const result = processBlock(child);
if (result) {
if (Array.isArray(result)) {
children.push(...result);
} else {
children.push(result);
}
}
}
return li(attributes, ...children);
}
function processTable(node: Table): Element {
const tableElement = elem("table", {});
const headerRows: Element[] = [];
const bodyRows: Element[] = [];
node.children.forEach((row, rowIndex) => {
const rowElement = processTableRow(row, rowIndex === 0, node.align);
if (rowIndex === 0) {
headerRows.push(rowElement);
} else {
bodyRows.push(rowElement);
}
});
if (headerRows.length > 0) {
tableElement.children.push(elem("thead", undefined, ...headerRows));
}
if (bodyRows.length > 0) {
tableElement.children.push(elem("tbody", undefined, ...bodyRows));
}
return tableElement;
}
function processTableRow(
node: TableRow,
isHeader: boolean,
alignments: (string | null)[] | null | undefined,
): Element {
const cells = node.children.map((cell, index) =>
processTableCell(cell, isHeader, alignments?.[index])
);
return elem("tr", {}, ...cells);
}
function processTableCell(
node: TableCell,
isHeader: boolean,
alignment: string | null | undefined,
): Element {
const attributes: Record<string, string> = {};
if (alignment && alignment !== "none") {
attributes.align = alignment;
}
return elem(
isHeader ? "th" : "td",
attributes,
...node.children.map(processInline),
);
}
function processHtmlBlock(node: Html): Element {
return div({ class: "raw-html" }, rawHTML(node.value));
}
function processDefinition(_node: Definition): null {
// Link definitions are handled elsewhere
return null;
}
function processFootnoteDefinition(node: FootnoteDefinition): Element {
const children: Node[] = [];
for (const child of node.children) {
const result = processBlock(child);
if (result) {
if (Array.isArray(result)) {
children.push(...result);
} else {
children.push(result);
}
}
}
return elem("footnote", { id: node.identifier }, ...children);
}
function processDirective(node: DirectiveNode): Element | null {
const name = node.name;
if (name === "note" || name === "edit") {
const attributes: Record<string, string> = {};
// Copy directive attributes
if (node.attributes) {
for (const [key, value] of Object.entries(node.attributes)) {
if (value !== undefined && value !== null) {
attributes[key] = String(value);
}
}
}
const children: Node[] = [];
if ("children" in node && node.children) {
for (const child of node.children as RootContent[]) {
const result = processBlock(child);
if (result) {
if (Array.isArray(result)) {
children.push(...result);
} else {
children.push(result);
}
}
}
}
return elem("note", attributes, ...children);
}
// For other directives, treat as div
const children: Node[] = [];
if ("children" in node && node.children) {
for (const child of node.children as RootContent[]) {
const result = processBlock(child);
if (result) {
if (Array.isArray(result)) {
children.push(...result);
} else {
children.push(result);
}
}
}
}
return div(
node.attributes as Record<string, string> || {},
...children,
);
}
function processInline(node: PhrasingContent): Node {
switch (node.type) {
case "text":
return processText(node);
case "emphasis":
return processEmphasis(node);
case "strong":
return processStrong(node);
case "inlineCode":
return processInlineCode(node);
case "link":
return processLink(node);
case "image":
return processImage(node);
case "delete":
return processDelete(node);
case "break":
return elem("br");
case "html":
return rawHTML(node.value);
case "footnoteReference":
return processFootnoteReference(node);
default:
// Handle any unexpected node types
if ("value" in node) {
return text(String(node.value));
}
if ("children" in node && Array.isArray(node.children)) {
return span(
{},
...node.children.map((c: PhrasingContent) => processInline(c)),
);
}
return text("");
}
}
function processText(node: MdastText): Node {
return text(node.value);
}
function processEmphasis(node: Emphasis): Element {
return elem("em", {}, ...node.children.map(processInline));
}
function processStrong(node: Strong): Element {
return elem("strong", {}, ...node.children.map(processInline));
}
function processInlineCode(node: InlineCode): Element {
return elem("code", {}, text(node.value));
}
function processLink(node: Link): Element {
const attributes: Record<string, string> = {};
if (node.url) {
attributes.href = node.url;
}
if (node.title) {
attributes.title = node.title;
}
// Detect autolinks (URL equals link text)
const isAutolink = node.children.length === 1 &&
node.children[0].type === "text" &&
node.children[0].value === node.url;
if (isAutolink) {
attributes.class = "url";
}
return a(attributes, ...node.children.map(processInline));
}
function processImage(node: Image): Element {
const attributes: Record<string, string> = {};
if (node.url) {
attributes.src = node.url;
}
if (node.alt) {
attributes.alt = node.alt;
}
if (node.title) {
attributes.title = node.title;
}
return img(attributes);
}
function processDelete(node: Delete): Element {
return elem("del", {}, ...node.children.map(processInline));
}
function processFootnoteReference(node: FootnoteReference): Element {
return elem("footnoteref", { reference: node.identifier });
}
// Build hierarchical section structure from flat mdast
// This mimics Djot's section structure where headings create nested sections
export function mdast2ndoc(root: Root): Element {
const footnotes: Element[] = [];
const nonFootnoteChildren: RootContent[] = [];
// Separate footnotes from other content
for (const child of root.children) {
if (child.type === "footnoteDefinition") {
const footnote = processFootnoteDefinition(child);
footnotes.push(footnote);
} else {
nonFootnoteChildren.push(child);
}
}
// Build hierarchical sections
const articleContent = buildSectionHierarchy(nonFootnoteChildren);
// Add footnotes section if any exist
if (footnotes.length > 0) {
const footnoteSection = section(
{ class: "footnotes" },
...footnotes,
);
articleContent.push(footnoteSection);
}
return elem(
"__root__",
undefined,
article(undefined, ...articleContent),
);
}
type SectionInfo = {
id: string | null;
attributes: Record<string, string>;
level: number;
heading: Element;
children: Node[];
};
function buildSectionHierarchy(nodes: RootContent[]): Node[] {
// Group nodes into sections based on headings
// Each heading starts a new section at its level
const result: Node[] = [];
const sectionStack: SectionInfo[] = [];
for (const node of nodes) {
if (node.type === "heading") {
const level = node.depth;
const { id, attributes, children } = extractSectionId(node);
// Create heading element
const headingElement = elem(
"h",
{},
...children.map(processInline),
);
// Close sections that are at same or deeper level
while (
sectionStack.length > 0 &&
sectionStack[sectionStack.length - 1].level >= level
) {
const closedSection = sectionStack.pop()!;
const sectionElement = createSectionElement(closedSection);
if (sectionStack.length > 0) {
// Add to parent section
sectionStack[sectionStack.length - 1].children.push(sectionElement);
} else {
// Add to result
result.push(sectionElement);
}
}
// Start new section
const newSection: SectionInfo = {
id,
attributes,
level,
heading: headingElement,
children: [],
};
sectionStack.push(newSection);
} else {
// Non-heading content
const processed = processBlock(node);
if (processed) {
if (sectionStack.length > 0) {
// Add to current section
if (Array.isArray(processed)) {
sectionStack[sectionStack.length - 1].children.push(...processed);
} else {
sectionStack[sectionStack.length - 1].children.push(processed);
}
} else {
// Content before any heading
if (Array.isArray(processed)) {
result.push(...processed);
} else {
result.push(processed);
}
}
}
}
}
// Close remaining sections
while (sectionStack.length > 0) {
const closedSection = sectionStack.pop()!;
const sectionElement = createSectionElement(closedSection);
if (sectionStack.length > 0) {
// Add to parent section
sectionStack[sectionStack.length - 1].children.push(sectionElement);
} else {
// Add to result
result.push(sectionElement);
}
}
return result;
}
function createSectionElement(sectionInfo: SectionInfo): Element {
const attributes: Record<string, string> = { ...sectionInfo.attributes };
if (sectionInfo.id) {
attributes.id = sectionInfo.id;
}
return section(
attributes,
sectionInfo.heading,
...sectionInfo.children,
);
}
|