summaryrefslogtreecommitdiffhomepage
path: root/services/blog/nuldoc-src/djot/djot2ndoc.ts
blob: 627e8d63193f92c4f5d6d010745dd61e0d4c5b25 (plain)
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
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
import {
  Block as DjotBlock,
  BlockQuote as DjotBlockQuote,
  BulletList as DjotBulletList,
  CodeBlock as DjotCodeBlock,
  Definition as DjotDefinition,
  DefinitionList as DjotDefinitionList,
  DefinitionListItem as DjotDefinitionListItem,
  Delete as DjotDelete,
  DisplayMath as DjotDisplayMath,
  Div as DjotDiv,
  Doc as DjotDoc,
  DoubleQuoted as DjotDoubleQuoted,
  Email as DjotEmail,
  Emph as DjotEmph,
  FootnoteReference as DjotFootnoteReference,
  HardBreak as DjotHardBreak,
  Heading as DjotHeading,
  Image as DjotImage,
  Inline as DjotInline,
  InlineMath as DjotInlineMath,
  Insert as DjotInsert,
  Link as DjotLink,
  ListItem as DjotListItem,
  Mark as DjotMark,
  NonBreakingSpace as DjotNonBreakingSpace,
  OrderedList as DjotOrderedList,
  Para as DjotPara,
  RawBlock as DjotRawBlock,
  RawInline as DjotRawInline,
  Section as DjotSection,
  SingleQuoted as DjotSingleQuoted,
  SmartPunctuation as DjotSmartPunctuation,
  SoftBreak as DjotSoftBreak,
  Span as DjotSpan,
  Str as DjotStr,
  Strong as DjotStrong,
  Subscript as DjotSubscript,
  Superscript as DjotSuperscript,
  Symb as DjotSymb,
  Table as DjotTable,
  TaskList as DjotTaskList,
  TaskListItem as DjotTaskListItem,
  Term as DjotTerm,
  ThematicBreak as DjotThematicBreak,
  Url as DjotUrl,
  Verbatim as DjotVerbatim,
} from "@djot/djot";
import { addClass, elem, Element, Node, rawHTML, text } from "../dom.ts";

function processBlock(node: DjotBlock): Element {
  switch (node.tag) {
    case "section":
      return processSection(node);
    case "para":
      return processPara(node);
    case "heading":
      return processHeading(node);
    case "thematic_break":
      return processThematicBreak(node);
    case "block_quote":
      return processBlockQuote(node);
    case "code_block":
      return processCodeBlock(node);
    case "bullet_list":
      return processBulletList(node);
    case "ordered_list":
      return processOrderedList(node);
    case "task_list":
      return processTaskList(node);
    case "definition_list":
      return processDefinitionList(node);
    case "table":
      return processTable(node);
    case "div":
      return processDiv(node);
    case "raw_block":
      return processRawBlock(node);
  }
}

function processSection(node: DjotSection): Element {
  return elem(
    "section",
    node.attributes,
    ...node.children.map(processBlock),
  );
}

function processPara(node: DjotPara): Element {
  return elem(
    "p",
    node.attributes,
    ...node.children.map(processInline),
  );
}

function processHeading(node: DjotHeading): Element {
  return elem("h", node.attributes, ...node.children.map(processInline));
}

function processThematicBreak(node: DjotThematicBreak): Element {
  return elem("hr", node.attributes);
}

function processBlockQuote(node: DjotBlockQuote): Element {
  return elem(
    "blockquote",
    node.attributes,
    ...node.children.map(processBlock),
  );
}

function processCodeBlock(node: DjotCodeBlock): Element {
  const attributes = node.attributes || {};
  if (node.lang) {
    attributes.language = node.lang;
  }
  if (node.attributes?.filename) {
    attributes.filename = node.attributes.filename;
  }
  if (node.attributes?.numbered) {
    attributes.numbered = "true";
  }
  return elem("codeblock", attributes, text(node.text));
}

function processBulletList(node: DjotBulletList): Element {
  const attributes = node.attributes || {};
  attributes.__tight = node.tight ? "true" : "false";
  return elem("ul", attributes, ...node.children.map(processListItem));
}

function processOrderedList(node: DjotOrderedList): Element {
  const attributes = node.attributes || {};
  attributes.__tight = node.tight ? "true" : "false";
  if (node.start !== undefined && node.start !== 1) {
    attributes.start = node.start.toString();
  }
  return elem("ol", attributes, ...node.children.map(processListItem));
}

function processTaskList(node: DjotTaskList): Element {
  const attributes = node.attributes || {};
  attributes.type = "task";
  attributes.__tight = node.tight ? "true" : "false";
  return elem("ul", attributes, ...node.children.map(processTaskListItem));
}

function processListItem(node: DjotListItem): Element {
  return elem(
    "li",
    node.attributes,
    ...node.children.map(processBlock),
  );
}

function processTaskListItem(node: DjotTaskListItem): Element {
  const attributes = node.attributes || {};
  attributes.checked = node.checkbox === "checked" ? "true" : "false";
  return elem("li", attributes, ...node.children.map(processBlock));
}

function processDefinitionList(node: DjotDefinitionList): Element {
  return elem(
    "dl",
    node.attributes,
    ...node.children.flatMap(processDefinitionListItem),
  );
}

function processDefinitionListItem(node: DjotDefinitionListItem): Element[] {
  return [
    processTerm(node.children[0]),
    processDefinition(node.children[1]),
  ];
}

function processTerm(node: DjotTerm): Element {
  return elem(
    "dt",
    node.attributes,
    ...node.children.map(processInline),
  );
}

function processDefinition(node: DjotDefinition): Element {
  return elem(
    "dd",
    node.attributes,
    ...node.children.map(processBlock),
  );
}

function processTable(node: DjotTable): Element {
  // Tables in Djot have a caption as first child and then rows
  // For now, we'll create a basic table structure and ignore caption
  const tableElement = elem("table", node.attributes);

  // Process caption if it exists (first child)
  if (node.children.length > 0 && node.children[0].tag === "caption") {
    const caption = elem(
      "caption",
      undefined,
      ...node.children[0].children.map(processInline),
    );
    tableElement.children.push(caption);
  }

  // Group rows into thead, tbody based on head property
  const headerRows: Element[] = [];
  const bodyRows: Element[] = [];

  // Start from index 1 to skip caption
  for (let i = 1; i < node.children.length; i++) {
    const row = node.children[i];
    if (row.tag === "row") {
      const rowElement = elem(
        "tr",
        row.attributes,
        ...row.children.map((cell) => {
          const cellAttributes = cell.attributes || {};
          // Set alignment attribute if needed
          if (cell.align !== "default") {
            cellAttributes.align = cell.align;
          }
          return elem(
            cell.head ? "th" : "td",
            cellAttributes,
            ...cell.children.map(processInline),
          );
        }),
      );

      if (row.head) {
        headerRows.push(rowElement);
      } else {
        bodyRows.push(rowElement);
      }
    }
  }

  // Add thead and tbody if needed
  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 processInline(node: DjotInline): Node {
  switch (node.tag) {
    case "str":
      return processStr(node);
    case "soft_break":
      return processSoftBreak(node);
    case "hard_break":
      return processHardBreak(node);
    case "verbatim":
      return processVerbatim(node);
    case "emph":
      return processEmph(node);
    case "strong":
      return processStrong(node);
    case "link":
      return processLink(node);
    case "image":
      return processImage(node);
    case "mark":
      return processMark(node);
    case "superscript":
      return processSuperscript(node);
    case "subscript":
      return processSubscript(node);
    case "insert":
      return processInsert(node);
    case "delete":
      return processDelete(node);
    case "email":
      return processEmail(node);
    case "footnote_reference":
      return processFootnoteReference(node);
    case "url":
      return processUrl(node);
    case "span":
      return processSpan(node);
    case "inline_math":
      return processInlineMath(node);
    case "display_math":
      return processDisplayMath(node);
    case "non_breaking_space":
      return processNonBreakingSpace(node);
    case "symb":
      return processSymb(node);
    case "raw_inline":
      return processRawInline(node);
    case "double_quoted":
      return processDoubleQuoted(node);
    case "single_quoted":
      return processSingleQuoted(node);
    case "smart_punctuation":
      return processSmartPunctuation(node);
  }
}

function processStr(node: DjotStr): Node {
  return text(node.text);
}

function processSoftBreak(_node: DjotSoftBreak): Node {
  return text("\n");
}

function processHardBreak(_node: DjotHardBreak): Node {
  return elem("br");
}

function processVerbatim(node: DjotVerbatim): Element {
  return elem("code", node.attributes, text(node.text));
}

function processEmph(node: DjotEmph): Element {
  return elem(
    "em",
    node.attributes,
    ...node.children.map(processInline),
  );
}

function processStrong(node: DjotStrong): Element {
  return elem(
    "strong",
    node.attributes,
    ...node.children.map(processInline),
  );
}

function processLink(node: DjotLink): Element {
  const attributes = node.attributes || {};
  if (node.destination !== undefined) {
    attributes.href = node.destination;
  }
  return elem("a", attributes, ...node.children.map(processInline));
}

function processImage(node: DjotImage): Element {
  const attributes = node.attributes || {};
  if (node.destination !== undefined) {
    attributes.src = node.destination;
  }

  // Alt text is derived from children in Djot
  const alt = node.children
    .map((child) => {
      if (child.tag === "str") {
        return child.text;
      }
      return "";
    })
    .join("");

  if (alt) {
    attributes.alt = alt;
  }

  return elem("img", attributes);
}

function processMark(node: DjotMark): Element {
  return elem(
    "mark",
    node.attributes,
    ...node.children.map(processInline),
  );
}

function processSuperscript(node: DjotSuperscript): Element {
  return elem(
    "sup",
    node.attributes,
    ...node.children.map(processInline),
  );
}

function processSubscript(node: DjotSubscript): Element {
  return elem(
    "sub",
    node.attributes,
    ...node.children.map(processInline),
  );
}

function processInsert(node: DjotInsert): Element {
  return elem(
    "ins",
    node.attributes,
    ...node.children.map(processInline),
  );
}

function processDelete(node: DjotDelete): Element {
  return elem(
    "del",
    node.attributes,
    ...node.children.map(processInline),
  );
}

function processEmail(node: DjotEmail): Element {
  return elem("email", node.attributes, text(node.text));
}

function processFootnoteReference(node: DjotFootnoteReference): Element {
  return elem("footnoteref", { reference: node.text });
}

function processUrl(node: DjotUrl): Element {
  const e = elem(
    "a",
    {
      href: node.text,
      ...node.attributes,
    },
    text(node.text),
  );
  addClass(e, "url");
  return e;
}

function processSpan(node: DjotSpan): Element {
  return elem(
    "span",
    node.attributes,
    ...node.children.map(processInline),
  );
}

function processInlineMath(node: DjotInlineMath): Element {
  // For inline math, we'll wrap it in a span with a class
  return elem(
    "span",
    {
      class: "math inline",
      ...node.attributes,
    },
    text(node.text),
  );
}

function processDisplayMath(node: DjotDisplayMath): Element {
  // For display math, we'll wrap it in a div with a class
  return elem(
    "div",
    {
      class: "math display",
      ...node.attributes,
    },
    text(node.text),
  );
}

function processNonBreakingSpace(_node: DjotNonBreakingSpace): Node {
  return text("\u00A0"); // Unicode non-breaking space
}

function processSymb(node: DjotSymb): Node {
  // Map symbol aliases to their Unicode characters
  const symbolMap: Record<string, string> = {
    "->": "→",
    "<-": "←",
    "<->": "↔",
    "=>": "⇒",
    "<=": "⇐",
    "<=>": "⇔",
    "--": "–", // en dash
    "---": "—", // em dash
    "...": "…", // ellipsis
    // Add more symbol mappings as needed
  };

  const symbolText = symbolMap[node.alias] || node.alias;

  return text(symbolText);
}

function processRawInline(node: DjotRawInline): Node {
  // If the format is HTML, return as raw HTML
  if (node.format === "html" || node.format === "HTML") {
    return rawHTML(node.text);
  }

  // For other formats, just return as text
  return text(node.text);
}

function processDoubleQuoted(node: DjotDoubleQuoted): Node {
  const children = node.children.map(processInline);
  const attributes = node.attributes || {};

  if (
    children.length === 1 && children[0].kind === "text" &&
    Object.keys(attributes).length === 0
  ) {
    const content = children[0].content;
    return text(`\u201C${content}\u201D`);
  } else {
    return elem("span", node.attributes, ...children);
  }
}

function processSingleQuoted(node: DjotSingleQuoted): Node {
  const children = node.children.map(processInline);
  const attributes = node.attributes || {};

  if (
    children.length === 1 && children[0].kind === "text" &&
    Object.keys(attributes).length === 0
  ) {
    const content = children[0].content;
    return text(`\u2018${content}\u2019`);
  } else {
    return elem("span", node.attributes, ...children);
  }
}

function processSmartPunctuation(node: DjotSmartPunctuation): Node {
  // Map smart punctuation types to Unicode characters
  const punctuationMap: Record<string, string> = {
    left_single_quote: "\u2018", // '
    right_single_quote: "\u2019", // '
    left_double_quote: "\u201C", // "
    right_double_quote: "\u201D", // "
    ellipses: "\u2026", // …
    em_dash: "\u2014", // —
    en_dash: "\u2013", // –
  };

  return text(punctuationMap[node.type] || node.text);
}

function processDiv(node: DjotDiv): Element {
  if (node.attributes?.class === "note") {
    delete node.attributes.class;
    return elem(
      "note",
      node.attributes,
      ...node.children.map(processBlock),
    );
  }

  if (node.attributes?.class === "edit") {
    delete node.attributes.class;
    return elem(
      "note",
      node.attributes,
      ...node.children.map(processBlock),
    );
  }

  return elem(
    "div",
    node.attributes,
    ...node.children.map(processBlock),
  );
}

function processRawBlock(node: DjotRawBlock): Element {
  // If the format is HTML, wrap the HTML content in a div
  if (node.format === "html" || node.format === "HTML") {
    return elem("div", { class: "raw-html" }, rawHTML(node.text));
  }

  // For other formats, wrap in a pre tag
  return elem("pre", { "data-format": node.format }, text(node.text));
}

export function djot2ndoc(doc: DjotDoc): Element {
  const children: Node[] = [];
  for (const child of doc.children) {
    children.push(processBlock(child));
  }

  // Process footnotes if any exist
  if (doc.footnotes && Object.keys(doc.footnotes).length > 0) {
    const footnoteSection = elem("section", { class: "footnotes" });

    for (const [id, footnote] of Object.entries(doc.footnotes)) {
      const footnoteElement = elem(
        "footnote",
        { id },
        ...footnote.children.map(processBlock),
      );
      footnoteSection.children.push(footnoteElement);
    }

    children.push(footnoteSection);
  }

  return elem("__root__", undefined, elem("article", undefined, ...children));
}