create-markdown 0.2.2 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,1782 +0,0 @@
1
- // src/react/block-renderer.tsx
2
- import { jsxDEV, Fragment } from "react/jsx-dev-runtime";
3
- function BlockRenderer({
4
- blocks,
5
- className,
6
- customRenderers
7
- }) {
8
- return /* @__PURE__ */ jsxDEV("div", {
9
- className,
10
- children: blocks.map((block) => /* @__PURE__ */ jsxDEV(BlockElement, {
11
- block,
12
- customRenderers
13
- }, block.id, false, undefined, this))
14
- }, undefined, false, undefined, this);
15
- }
16
- function BlockElement({
17
- block,
18
- customRenderers
19
- }) {
20
- const CustomRenderer = customRenderers?.[block.type];
21
- if (CustomRenderer) {
22
- return /* @__PURE__ */ jsxDEV(CustomRenderer, {
23
- block
24
- }, undefined, false, undefined, this);
25
- }
26
- switch (block.type) {
27
- case "paragraph":
28
- return /* @__PURE__ */ jsxDEV(ParagraphRenderer, {
29
- block
30
- }, undefined, false, undefined, this);
31
- case "heading":
32
- return /* @__PURE__ */ jsxDEV(HeadingRenderer, {
33
- block
34
- }, undefined, false, undefined, this);
35
- case "bulletList":
36
- return /* @__PURE__ */ jsxDEV(BulletListRenderer, {
37
- block,
38
- customRenderers
39
- }, undefined, false, undefined, this);
40
- case "numberedList":
41
- return /* @__PURE__ */ jsxDEV(NumberedListRenderer, {
42
- block,
43
- customRenderers
44
- }, undefined, false, undefined, this);
45
- case "checkList":
46
- return /* @__PURE__ */ jsxDEV(CheckListRenderer, {
47
- block
48
- }, undefined, false, undefined, this);
49
- case "codeBlock":
50
- return /* @__PURE__ */ jsxDEV(CodeBlockRenderer, {
51
- block
52
- }, undefined, false, undefined, this);
53
- case "blockquote":
54
- return /* @__PURE__ */ jsxDEV(BlockquoteRenderer, {
55
- block
56
- }, undefined, false, undefined, this);
57
- case "table":
58
- return /* @__PURE__ */ jsxDEV(TableRenderer, {
59
- block
60
- }, undefined, false, undefined, this);
61
- case "image":
62
- return /* @__PURE__ */ jsxDEV(ImageRenderer, {
63
- block
64
- }, undefined, false, undefined, this);
65
- case "divider":
66
- return /* @__PURE__ */ jsxDEV(DividerRenderer, {}, undefined, false, undefined, this);
67
- case "callout":
68
- return /* @__PURE__ */ jsxDEV(CalloutRenderer, {
69
- block
70
- }, undefined, false, undefined, this);
71
- default:
72
- return null;
73
- }
74
- }
75
- function InlineContent({ spans }) {
76
- return /* @__PURE__ */ jsxDEV(Fragment, {
77
- children: spans.map((span, index) => /* @__PURE__ */ jsxDEV(SpanElement, {
78
- span
79
- }, index, false, undefined, this))
80
- }, undefined, false, undefined, this);
81
- }
82
- function SpanElement({ span }) {
83
- let content = span.text;
84
- const styles = span.styles;
85
- if (styles.code) {
86
- content = /* @__PURE__ */ jsxDEV("code", {
87
- children: content
88
- }, undefined, false, undefined, this);
89
- }
90
- if (styles.highlight) {
91
- content = /* @__PURE__ */ jsxDEV("mark", {
92
- children: content
93
- }, undefined, false, undefined, this);
94
- }
95
- if (styles.strikethrough) {
96
- content = /* @__PURE__ */ jsxDEV("del", {
97
- children: content
98
- }, undefined, false, undefined, this);
99
- }
100
- if (styles.underline) {
101
- content = /* @__PURE__ */ jsxDEV("u", {
102
- children: content
103
- }, undefined, false, undefined, this);
104
- }
105
- if (styles.italic) {
106
- content = /* @__PURE__ */ jsxDEV("em", {
107
- children: content
108
- }, undefined, false, undefined, this);
109
- }
110
- if (styles.bold) {
111
- content = /* @__PURE__ */ jsxDEV("strong", {
112
- children: content
113
- }, undefined, false, undefined, this);
114
- }
115
- if (styles.link) {
116
- content = /* @__PURE__ */ jsxDEV("a", {
117
- href: styles.link.url,
118
- title: styles.link.title,
119
- children: content
120
- }, undefined, false, undefined, this);
121
- }
122
- return /* @__PURE__ */ jsxDEV(Fragment, {
123
- children: content
124
- }, undefined, false, undefined, this);
125
- }
126
- function ParagraphRenderer({ block }) {
127
- return /* @__PURE__ */ jsxDEV("p", {
128
- children: /* @__PURE__ */ jsxDEV(InlineContent, {
129
- spans: block.content
130
- }, undefined, false, undefined, this)
131
- }, undefined, false, undefined, this);
132
- }
133
- function HeadingRenderer({ block }) {
134
- const Tag = `h${block.props.level}`;
135
- return /* @__PURE__ */ jsxDEV(Tag, {
136
- children: /* @__PURE__ */ jsxDEV(InlineContent, {
137
- spans: block.content
138
- }, undefined, false, undefined, this)
139
- }, undefined, false, undefined, this);
140
- }
141
- function BulletListRenderer({
142
- block,
143
- customRenderers
144
- }) {
145
- return /* @__PURE__ */ jsxDEV("ul", {
146
- children: block.children.map((child) => /* @__PURE__ */ jsxDEV("li", {
147
- children: [
148
- /* @__PURE__ */ jsxDEV(InlineContent, {
149
- spans: child.content
150
- }, undefined, false, undefined, this),
151
- child.children.length > 0 && /* @__PURE__ */ jsxDEV(BlockElement, {
152
- block: child,
153
- customRenderers
154
- }, undefined, false, undefined, this)
155
- ]
156
- }, child.id, true, undefined, this))
157
- }, undefined, false, undefined, this);
158
- }
159
- function NumberedListRenderer({
160
- block,
161
- customRenderers
162
- }) {
163
- return /* @__PURE__ */ jsxDEV("ol", {
164
- children: block.children.map((child) => /* @__PURE__ */ jsxDEV("li", {
165
- children: [
166
- /* @__PURE__ */ jsxDEV(InlineContent, {
167
- spans: child.content
168
- }, undefined, false, undefined, this),
169
- child.children.length > 0 && /* @__PURE__ */ jsxDEV(BlockElement, {
170
- block: child,
171
- customRenderers
172
- }, undefined, false, undefined, this)
173
- ]
174
- }, child.id, true, undefined, this))
175
- }, undefined, false, undefined, this);
176
- }
177
- function CheckListRenderer({ block }) {
178
- return /* @__PURE__ */ jsxDEV("div", {
179
- style: { display: "flex", alignItems: "flex-start", gap: "0.5rem" },
180
- children: [
181
- /* @__PURE__ */ jsxDEV("input", {
182
- type: "checkbox",
183
- checked: block.props.checked,
184
- readOnly: true,
185
- style: { marginTop: "0.25rem" }
186
- }, undefined, false, undefined, this),
187
- /* @__PURE__ */ jsxDEV("span", {
188
- style: { textDecoration: block.props.checked ? "line-through" : "none" },
189
- children: /* @__PURE__ */ jsxDEV(InlineContent, {
190
- spans: block.content
191
- }, undefined, false, undefined, this)
192
- }, undefined, false, undefined, this)
193
- ]
194
- }, undefined, true, undefined, this);
195
- }
196
- function CodeBlockRenderer({ block }) {
197
- const code = block.content.map((span) => span.text).join("");
198
- const language = block.props.language;
199
- return /* @__PURE__ */ jsxDEV("pre", {
200
- children: /* @__PURE__ */ jsxDEV("code", {
201
- className: language ? `language-${language}` : undefined,
202
- children: code
203
- }, undefined, false, undefined, this)
204
- }, undefined, false, undefined, this);
205
- }
206
- function BlockquoteRenderer({ block }) {
207
- return /* @__PURE__ */ jsxDEV("blockquote", {
208
- children: /* @__PURE__ */ jsxDEV(InlineContent, {
209
- spans: block.content
210
- }, undefined, false, undefined, this)
211
- }, undefined, false, undefined, this);
212
- }
213
- function TableRenderer({ block }) {
214
- const { headers, rows, alignments } = block.props;
215
- const getAlignment = (index) => {
216
- return alignments?.[index] ?? undefined;
217
- };
218
- return /* @__PURE__ */ jsxDEV("table", {
219
- children: [
220
- headers.length > 0 && /* @__PURE__ */ jsxDEV("thead", {
221
- children: /* @__PURE__ */ jsxDEV("tr", {
222
- children: headers.map((header, i) => /* @__PURE__ */ jsxDEV("th", {
223
- style: { textAlign: getAlignment(i) },
224
- children: header
225
- }, i, false, undefined, this))
226
- }, undefined, false, undefined, this)
227
- }, undefined, false, undefined, this),
228
- /* @__PURE__ */ jsxDEV("tbody", {
229
- children: rows.map((row, rowIndex) => /* @__PURE__ */ jsxDEV("tr", {
230
- children: row.map((cell, cellIndex) => /* @__PURE__ */ jsxDEV("td", {
231
- style: { textAlign: getAlignment(cellIndex) },
232
- children: cell
233
- }, cellIndex, false, undefined, this))
234
- }, rowIndex, false, undefined, this))
235
- }, undefined, false, undefined, this)
236
- ]
237
- }, undefined, true, undefined, this);
238
- }
239
- function ImageRenderer({ block }) {
240
- return /* @__PURE__ */ jsxDEV("figure", {
241
- children: [
242
- /* @__PURE__ */ jsxDEV("img", {
243
- src: block.props.url,
244
- alt: block.props.alt ?? "",
245
- title: block.props.title,
246
- width: block.props.width,
247
- height: block.props.height
248
- }, undefined, false, undefined, this),
249
- block.props.alt && /* @__PURE__ */ jsxDEV("figcaption", {
250
- children: block.props.alt
251
- }, undefined, false, undefined, this)
252
- ]
253
- }, undefined, true, undefined, this);
254
- }
255
- function DividerRenderer() {
256
- return /* @__PURE__ */ jsxDEV("hr", {}, undefined, false, undefined, this);
257
- }
258
- function CalloutRenderer({ block }) {
259
- const calloutType = block.props.type;
260
- const styles = {
261
- padding: "1rem",
262
- borderRadius: "0.25rem",
263
- borderLeft: "4px solid",
264
- marginBottom: "1rem"
265
- };
266
- const colors = {
267
- info: { borderColor: "#3b82f6", backgroundColor: "#eff6ff" },
268
- warning: { borderColor: "#f59e0b", backgroundColor: "#fffbeb" },
269
- tip: { borderColor: "#10b981", backgroundColor: "#ecfdf5" },
270
- danger: { borderColor: "#ef4444", backgroundColor: "#fef2f2" },
271
- note: { borderColor: "#6b7280", backgroundColor: "#f9fafb" }
272
- };
273
- const colorStyle = colors[calloutType] ?? colors.note;
274
- return /* @__PURE__ */ jsxDEV("div", {
275
- style: {
276
- ...styles,
277
- borderLeftColor: colorStyle.borderColor,
278
- backgroundColor: colorStyle.backgroundColor
279
- },
280
- role: "alert",
281
- children: [
282
- /* @__PURE__ */ jsxDEV("strong", {
283
- style: { textTransform: "capitalize", display: "block", marginBottom: "0.5rem" },
284
- children: calloutType
285
- }, undefined, false, undefined, this),
286
- /* @__PURE__ */ jsxDEV(InlineContent, {
287
- spans: block.content
288
- }, undefined, false, undefined, this)
289
- ]
290
- }, undefined, true, undefined, this);
291
- }
292
- // src/react/hooks.ts
293
- import { useState, useCallback, useMemo } from "react";
294
-
295
- // src/core/utils.ts
296
- var ID_CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
297
- var ID_LENGTH = 8;
298
- function generateId(length = ID_LENGTH) {
299
- let id = "";
300
- const charsLength = ID_CHARS.length;
301
- for (let i = 0;i < length; i++) {
302
- id += ID_CHARS.charAt(Math.floor(Math.random() * charsLength));
303
- }
304
- return id;
305
- }
306
- function deepClone(block, regenerateIds = true) {
307
- return {
308
- id: regenerateIds ? generateId() : block.id,
309
- type: block.type,
310
- content: block.content.map((span) => ({
311
- text: span.text,
312
- styles: { ...span.styles }
313
- })),
314
- children: block.children.map((child) => deepClone(child, regenerateIds)),
315
- props: { ...block.props }
316
- };
317
- }
318
- function deepCloneBlocks(blocks, regenerateIds = true) {
319
- return blocks.map((block) => deepClone(block, regenerateIds));
320
- }
321
- function spansToPlainText(spans) {
322
- return spans.map((span) => span.text).join("");
323
- }
324
- function plainSpan(text) {
325
- return { text, styles: {} };
326
- }
327
- function plainContent(text) {
328
- return [plainSpan(text)];
329
- }
330
-
331
- // src/core/document.ts
332
- var DOCUMENT_VERSION = 1;
333
- function createDocument(blocks = [], options = {}) {
334
- const { meta = {} } = options;
335
- return {
336
- version: DOCUMENT_VERSION,
337
- blocks: deepCloneBlocks(blocks, false),
338
- meta: {
339
- createdAt: new Date,
340
- updatedAt: new Date,
341
- ...meta
342
- }
343
- };
344
- }
345
- function insertBlock(doc, block, index) {
346
- const newBlocks = [...doc.blocks];
347
- const insertIndex = index ?? newBlocks.length;
348
- newBlocks.splice(insertIndex, 0, deepClone(block, false));
349
- return {
350
- ...doc,
351
- blocks: newBlocks,
352
- meta: {
353
- ...doc.meta,
354
- updatedAt: new Date
355
- }
356
- };
357
- }
358
- function appendBlock(doc, block) {
359
- return insertBlock(doc, block);
360
- }
361
- function removeBlock(doc, blockId) {
362
- const newBlocks = doc.blocks.filter((block) => block.id !== blockId);
363
- if (newBlocks.length === doc.blocks.length) {
364
- return doc;
365
- }
366
- return {
367
- ...doc,
368
- blocks: newBlocks,
369
- meta: {
370
- ...doc.meta,
371
- updatedAt: new Date
372
- }
373
- };
374
- }
375
- function updateBlock(doc, blockId, updates) {
376
- const blockIndex = doc.blocks.findIndex((block) => block.id === blockId);
377
- if (blockIndex === -1) {
378
- return doc;
379
- }
380
- const newBlocks = [...doc.blocks];
381
- const existingBlock = newBlocks[blockIndex];
382
- newBlocks[blockIndex] = {
383
- ...existingBlock,
384
- ...updates,
385
- id: existingBlock.id,
386
- type: existingBlock.type,
387
- content: updates.content ?? existingBlock.content,
388
- children: updates.children ?? existingBlock.children,
389
- props: updates.props ? { ...existingBlock.props, ...updates.props } : existingBlock.props
390
- };
391
- return {
392
- ...doc,
393
- blocks: newBlocks,
394
- meta: {
395
- ...doc.meta,
396
- updatedAt: new Date
397
- }
398
- };
399
- }
400
- function moveBlock(doc, blockId, newIndex) {
401
- const currentIndex = doc.blocks.findIndex((block) => block.id === blockId);
402
- if (currentIndex === -1) {
403
- return doc;
404
- }
405
- const targetIndex = Math.max(0, Math.min(newIndex, doc.blocks.length - 1));
406
- if (currentIndex === targetIndex) {
407
- return doc;
408
- }
409
- const newBlocks = [...doc.blocks];
410
- const [movedBlock] = newBlocks.splice(currentIndex, 1);
411
- newBlocks.splice(targetIndex, 0, movedBlock);
412
- return {
413
- ...doc,
414
- blocks: newBlocks,
415
- meta: {
416
- ...doc.meta,
417
- updatedAt: new Date
418
- }
419
- };
420
- }
421
- function findBlock(doc, blockId) {
422
- return doc.blocks.find((block) => block.id === blockId);
423
- }
424
- function getBlockIndex(doc, blockId) {
425
- return doc.blocks.findIndex((block) => block.id === blockId);
426
- }
427
- function updateMeta(doc, meta) {
428
- return {
429
- ...doc,
430
- meta: {
431
- ...doc.meta,
432
- ...meta,
433
- updatedAt: new Date
434
- }
435
- };
436
- }
437
- function clearBlocks(doc) {
438
- return {
439
- ...doc,
440
- blocks: [],
441
- meta: {
442
- ...doc.meta,
443
- updatedAt: new Date
444
- }
445
- };
446
- }
447
- function setBlocks(doc, blocks) {
448
- return {
449
- ...doc,
450
- blocks: deepCloneBlocks(blocks, false),
451
- meta: {
452
- ...doc.meta,
453
- updatedAt: new Date
454
- }
455
- };
456
- }
457
-
458
- // src/parsers/tokenizer.ts
459
- var PATTERNS = {
460
- heading: /^(#{1,6})\s+(.*)$/,
461
- setextH1: /^=+\s*$/,
462
- setextH2: /^-+\s*$/,
463
- bulletList: /^(\s*)([-*+])\s+(.*)$/,
464
- numberedList: /^(\s*)(\d+)\.\s+(.*)$/,
465
- checkList: /^(\s*)[-*+]\s+\[([ xX])\]\s+(.*)$/,
466
- codeFence: /^(\s*)(`{3,}|~{3,})(\w*)?\s*$/,
467
- blockquote: /^>\s?(.*)$/,
468
- callout: /^>\s*\[!(\w+)\]\s*$/,
469
- divider: /^(\s*)(-{3,}|\*{3,}|_{3,})\s*$/,
470
- tableRow: /^\|(.+)\|$/,
471
- tableSeparator: /^\|[\s\-:|]+\|$/,
472
- image: /^!\[([^\]]*)\]\(([^)]+)\)$/,
473
- blank: /^\s*$/
474
- };
475
- function tokenize(markdown) {
476
- const lines = markdown.split(/\r?\n/);
477
- const tokens = [];
478
- const state = {
479
- inCodeBlock: false,
480
- codeBlockFence: "",
481
- lineNumber: 0
482
- };
483
- for (let i = 0;i < lines.length; i++) {
484
- state.lineNumber = i + 1;
485
- const line = lines[i];
486
- const token = tokenizeLine(line, state, lines, i);
487
- if (token) {
488
- tokens.push(token);
489
- }
490
- }
491
- return tokens;
492
- }
493
- function tokenizeLine(line, state, allLines, lineIndex) {
494
- const lineNumber = state.lineNumber;
495
- if (state.inCodeBlock) {
496
- const fenceMatch = line.match(PATTERNS.codeFence);
497
- if (fenceMatch && line.trim().startsWith(state.codeBlockFence.charAt(0))) {
498
- state.inCodeBlock = false;
499
- state.codeBlockFence = "";
500
- return {
501
- type: "code_fence_end",
502
- raw: line,
503
- content: "",
504
- indent: 0,
505
- line: lineNumber
506
- };
507
- }
508
- return {
509
- type: "code_content",
510
- raw: line,
511
- content: line,
512
- indent: 0,
513
- line: lineNumber
514
- };
515
- }
516
- const codeFenceMatch = line.match(PATTERNS.codeFence);
517
- if (codeFenceMatch) {
518
- state.inCodeBlock = true;
519
- state.codeBlockFence = codeFenceMatch[2];
520
- const language = codeFenceMatch[3] || "";
521
- return {
522
- type: "code_fence_start",
523
- raw: line,
524
- content: "",
525
- indent: (codeFenceMatch[1] || "").length,
526
- line: lineNumber,
527
- meta: { language }
528
- };
529
- }
530
- if (PATTERNS.blank.test(line)) {
531
- return {
532
- type: "blank",
533
- raw: line,
534
- content: "",
535
- indent: 0,
536
- line: lineNumber
537
- };
538
- }
539
- const dividerMatch = line.match(PATTERNS.divider);
540
- if (dividerMatch) {
541
- const prevLine = lineIndex > 0 ? allLines[lineIndex - 1] : "";
542
- if (prevLine.trim() && !PATTERNS.blank.test(prevLine)) {
543
- if (PATTERNS.setextH2.test(line)) {}
544
- } else {
545
- return {
546
- type: "divider",
547
- raw: line,
548
- content: "",
549
- indent: (dividerMatch[1] || "").length,
550
- line: lineNumber
551
- };
552
- }
553
- }
554
- const headingMatch = line.match(PATTERNS.heading);
555
- if (headingMatch) {
556
- return {
557
- type: "heading",
558
- raw: line,
559
- content: headingMatch[2].trim(),
560
- indent: 0,
561
- line: lineNumber,
562
- meta: { level: headingMatch[1].length }
563
- };
564
- }
565
- const calloutMatch = line.match(PATTERNS.callout);
566
- if (calloutMatch) {
567
- return {
568
- type: "callout",
569
- raw: line,
570
- content: "",
571
- indent: 0,
572
- line: lineNumber,
573
- meta: { calloutType: calloutMatch[1].toLowerCase() }
574
- };
575
- }
576
- const blockquoteMatch = line.match(PATTERNS.blockquote);
577
- if (blockquoteMatch) {
578
- return {
579
- type: "blockquote",
580
- raw: line,
581
- content: blockquoteMatch[1],
582
- indent: 0,
583
- line: lineNumber
584
- };
585
- }
586
- const checkListMatch = line.match(PATTERNS.checkList);
587
- if (checkListMatch) {
588
- const checked = checkListMatch[2].toLowerCase() === "x";
589
- return {
590
- type: "check_list_item",
591
- raw: line,
592
- content: checkListMatch[3],
593
- indent: checkListMatch[1].length,
594
- line: lineNumber,
595
- meta: { checked }
596
- };
597
- }
598
- const bulletMatch = line.match(PATTERNS.bulletList);
599
- if (bulletMatch) {
600
- return {
601
- type: "bullet_list_item",
602
- raw: line,
603
- content: bulletMatch[3],
604
- indent: bulletMatch[1].length,
605
- line: lineNumber,
606
- meta: { listMarker: bulletMatch[2] }
607
- };
608
- }
609
- const numberedMatch = line.match(PATTERNS.numberedList);
610
- if (numberedMatch) {
611
- return {
612
- type: "numbered_list_item",
613
- raw: line,
614
- content: numberedMatch[3],
615
- indent: numberedMatch[1].length,
616
- line: lineNumber,
617
- meta: { listIndex: parseInt(numberedMatch[2], 10) }
618
- };
619
- }
620
- if (PATTERNS.tableSeparator.test(line)) {
621
- return {
622
- type: "table_separator",
623
- raw: line,
624
- content: line,
625
- indent: 0,
626
- line: lineNumber
627
- };
628
- }
629
- const tableRowMatch = line.match(PATTERNS.tableRow);
630
- if (tableRowMatch) {
631
- return {
632
- type: "table_row",
633
- raw: line,
634
- content: tableRowMatch[1],
635
- indent: 0,
636
- line: lineNumber
637
- };
638
- }
639
- const imageMatch = line.match(PATTERNS.image);
640
- if (imageMatch) {
641
- return {
642
- type: "image",
643
- raw: line,
644
- content: imageMatch[2],
645
- indent: 0,
646
- line: lineNumber,
647
- meta: { language: imageMatch[1] }
648
- };
649
- }
650
- if (PATTERNS.setextH1.test(line) || PATTERNS.setextH2.test(line)) {
651
- const prevLine = lineIndex > 0 ? allLines[lineIndex - 1] : "";
652
- if (prevLine.trim() && !PATTERNS.blank.test(prevLine)) {
653
- return {
654
- type: "heading",
655
- raw: line,
656
- content: prevLine.trim(),
657
- indent: 0,
658
- line: lineNumber,
659
- meta: { level: PATTERNS.setextH1.test(line) ? 1 : 2 }
660
- };
661
- }
662
- return {
663
- type: "divider",
664
- raw: line,
665
- content: "",
666
- indent: 0,
667
- line: lineNumber
668
- };
669
- }
670
- return {
671
- type: "paragraph",
672
- raw: line,
673
- content: line.trim(),
674
- indent: line.length - line.trimStart().length,
675
- line: lineNumber
676
- };
677
- }
678
-
679
- // src/parsers/inline.ts
680
- function parseInlineContent(text) {
681
- if (!text) {
682
- return [];
683
- }
684
- const tokens = tokenizeInline(text);
685
- return tokensToSpans(tokens);
686
- }
687
- function tokenizeInline(text) {
688
- const tokens = [];
689
- let remaining = text;
690
- let pos = 0;
691
- while (pos < remaining.length) {
692
- const matched = tryMatchInline(remaining, pos);
693
- if (matched) {
694
- if (matched.startIndex > pos) {
695
- tokens.push({
696
- type: "text",
697
- content: remaining.slice(pos, matched.startIndex)
698
- });
699
- }
700
- tokens.push(matched.token);
701
- pos = matched.endIndex;
702
- } else {
703
- pos++;
704
- }
705
- }
706
- return parseInlineTokens(text);
707
- }
708
- function parseInlineTokens(text) {
709
- const tokens = [];
710
- let i = 0;
711
- let textBuffer = "";
712
- const flushText = () => {
713
- if (textBuffer) {
714
- tokens.push({ type: "text", content: textBuffer });
715
- textBuffer = "";
716
- }
717
- };
718
- while (i < text.length) {
719
- if (text[i] === "\\" && i + 1 < text.length) {
720
- textBuffer += text[i + 1];
721
- i += 2;
722
- continue;
723
- }
724
- if (text[i] === "`") {
725
- const match = matchCode(text, i);
726
- if (match) {
727
- flushText();
728
- tokens.push(match.token);
729
- i = match.end;
730
- continue;
731
- }
732
- }
733
- if (text[i] === "[" || text[i] === "!" && text[i + 1] === "[") {
734
- const isImage = text[i] === "!";
735
- const match = matchLink(text, isImage ? i + 1 : i, isImage);
736
- if (match) {
737
- flushText();
738
- tokens.push(match.token);
739
- i = match.end;
740
- continue;
741
- }
742
- }
743
- if (text[i] === "*" || text[i] === "_") {
744
- const match = matchEmphasis(text, i);
745
- if (match) {
746
- flushText();
747
- tokens.push(match.token);
748
- i = match.end;
749
- continue;
750
- }
751
- }
752
- if (text[i] === "~" && text[i + 1] === "~") {
753
- const match = matchStrikethrough(text, i);
754
- if (match) {
755
- flushText();
756
- tokens.push(match.token);
757
- i = match.end;
758
- continue;
759
- }
760
- }
761
- if (text[i] === "=" && text[i + 1] === "=") {
762
- const match = matchHighlight(text, i);
763
- if (match) {
764
- flushText();
765
- tokens.push(match.token);
766
- i = match.end;
767
- continue;
768
- }
769
- }
770
- textBuffer += text[i];
771
- i++;
772
- }
773
- flushText();
774
- return tokens;
775
- }
776
- function matchCode(text, start) {
777
- let backticks = 0;
778
- let i = start;
779
- while (i < text.length && text[i] === "`") {
780
- backticks++;
781
- i++;
782
- }
783
- if (backticks === 0)
784
- return null;
785
- const closePattern = "`".repeat(backticks);
786
- const closeIndex = text.indexOf(closePattern, i);
787
- if (closeIndex === -1)
788
- return null;
789
- if (text[closeIndex + backticks] === "`") {
790
- return null;
791
- }
792
- const content = text.slice(i, closeIndex);
793
- return {
794
- token: { type: "code", content: content.trim() },
795
- end: closeIndex + backticks
796
- };
797
- }
798
- function matchLink(text, start, isImage = false) {
799
- if (text[start] !== "[")
800
- return null;
801
- let bracketDepth = 1;
802
- let i = start + 1;
803
- while (i < text.length && bracketDepth > 0) {
804
- if (text[i] === "[")
805
- bracketDepth++;
806
- else if (text[i] === "]")
807
- bracketDepth--;
808
- else if (text[i] === "\\")
809
- i++;
810
- i++;
811
- }
812
- if (bracketDepth !== 0)
813
- return null;
814
- const linkText = text.slice(start + 1, i - 1);
815
- if (text[i] !== "(")
816
- return null;
817
- const urlStart = i + 1;
818
- let urlEnd = urlStart;
819
- let parenDepth = 1;
820
- while (urlEnd < text.length && parenDepth > 0) {
821
- if (text[urlEnd] === "(")
822
- parenDepth++;
823
- else if (text[urlEnd] === ")")
824
- parenDepth--;
825
- else if (text[urlEnd] === "\\")
826
- urlEnd++;
827
- urlEnd++;
828
- }
829
- if (parenDepth !== 0)
830
- return null;
831
- const urlPart = text.slice(urlStart, urlEnd - 1).trim();
832
- let url = urlPart;
833
- let title;
834
- const titleMatch = urlPart.match(/^(.+?)\s+["'](.+?)["']$/);
835
- if (titleMatch) {
836
- url = titleMatch[1];
837
- title = titleMatch[2];
838
- }
839
- const children = parseInlineTokens(linkText);
840
- const token = isImage ? { type: "image", content: linkText, url, title, children } : { type: "link", content: linkText, url, title, children };
841
- return {
842
- token,
843
- end: isImage ? urlEnd + 1 : urlEnd
844
- };
845
- }
846
- function matchEmphasis(text, start) {
847
- const char = text[start];
848
- if (char !== "*" && char !== "_")
849
- return null;
850
- let count = 0;
851
- let i = start;
852
- while (i < text.length && text[i] === char && count < 3) {
853
- count++;
854
- i++;
855
- }
856
- if (count === 0)
857
- return null;
858
- const closePattern = char.repeat(count);
859
- let searchStart = i;
860
- while (searchStart < text.length) {
861
- const closeIndex = text.indexOf(closePattern, searchStart);
862
- if (closeIndex === -1)
863
- return null;
864
- if (text[closeIndex + count] === char) {
865
- searchStart = closeIndex + 1;
866
- continue;
867
- }
868
- if (text[closeIndex - 1] === " ") {
869
- searchStart = closeIndex + 1;
870
- continue;
871
- }
872
- const content = text.slice(i, closeIndex);
873
- if (!content.trim()) {
874
- searchStart = closeIndex + 1;
875
- continue;
876
- }
877
- const children = parseInlineTokens(content);
878
- if (count === 3) {
879
- return {
880
- token: {
881
- type: "bold",
882
- content,
883
- children: [{ type: "italic", content, children }]
884
- },
885
- end: closeIndex + count
886
- };
887
- } else if (count === 2) {
888
- return {
889
- token: { type: "bold", content, children },
890
- end: closeIndex + count
891
- };
892
- } else {
893
- return {
894
- token: { type: "italic", content, children },
895
- end: closeIndex + count
896
- };
897
- }
898
- }
899
- return null;
900
- }
901
- function matchStrikethrough(text, start) {
902
- if (text[start] !== "~" || text[start + 1] !== "~")
903
- return null;
904
- const closeIndex = text.indexOf("~~", start + 2);
905
- if (closeIndex === -1)
906
- return null;
907
- const content = text.slice(start + 2, closeIndex);
908
- if (!content.trim())
909
- return null;
910
- const children = parseInlineTokens(content);
911
- return {
912
- token: { type: "strikethrough", content, children },
913
- end: closeIndex + 2
914
- };
915
- }
916
- function matchHighlight(text, start) {
917
- if (text[start] !== "=" || text[start + 1] !== "=")
918
- return null;
919
- const closeIndex = text.indexOf("==", start + 2);
920
- if (closeIndex === -1)
921
- return null;
922
- const content = text.slice(start + 2, closeIndex);
923
- if (!content.trim())
924
- return null;
925
- const children = parseInlineTokens(content);
926
- return {
927
- token: { type: "highlight", content, children },
928
- end: closeIndex + 2
929
- };
930
- }
931
- function tokensToSpans(tokens) {
932
- const spans = [];
933
- for (const token of tokens) {
934
- const newSpans = tokenToSpans(token, {});
935
- spans.push(...newSpans);
936
- }
937
- return mergeAdjacentSpans(spans);
938
- }
939
- function tokenToSpans(token, inheritedStyles) {
940
- switch (token.type) {
941
- case "text":
942
- return [{ text: token.content, styles: { ...inheritedStyles } }];
943
- case "bold":
944
- return processStyledToken(token, { ...inheritedStyles, bold: true });
945
- case "italic":
946
- return processStyledToken(token, { ...inheritedStyles, italic: true });
947
- case "code":
948
- return [{ text: token.content, styles: { ...inheritedStyles, code: true } }];
949
- case "strikethrough":
950
- return processStyledToken(token, { ...inheritedStyles, strikethrough: true });
951
- case "highlight":
952
- return processStyledToken(token, { ...inheritedStyles, highlight: true });
953
- case "link":
954
- return processStyledToken(token, {
955
- ...inheritedStyles,
956
- link: { url: token.url || "", title: token.title }
957
- });
958
- case "image":
959
- return [{ text: `[image: ${token.content}]`, styles: inheritedStyles }];
960
- default:
961
- return [{ text: token.content, styles: inheritedStyles }];
962
- }
963
- }
964
- function processStyledToken(token, styles) {
965
- if (token.children && token.children.length > 0) {
966
- const spans = [];
967
- for (const child of token.children) {
968
- spans.push(...tokenToSpans(child, styles));
969
- }
970
- return spans;
971
- }
972
- return [{ text: token.content, styles }];
973
- }
974
- function mergeAdjacentSpans(spans) {
975
- if (spans.length === 0)
976
- return [];
977
- const merged = [spans[0]];
978
- for (let i = 1;i < spans.length; i++) {
979
- const current = spans[i];
980
- const previous = merged[merged.length - 1];
981
- if (stylesEqual(current.styles, previous.styles)) {
982
- previous.text += current.text;
983
- } else {
984
- merged.push(current);
985
- }
986
- }
987
- return merged;
988
- }
989
- function stylesEqual(a, b) {
990
- return a.bold === b.bold && a.italic === b.italic && a.underline === b.underline && a.strikethrough === b.strikethrough && a.code === b.code && a.highlight === b.highlight && linksEqual(a.link, b.link);
991
- }
992
- function linksEqual(a, b) {
993
- if (!a && !b)
994
- return true;
995
- if (!a || !b)
996
- return false;
997
- return a.url === b.url && a.title === b.title;
998
- }
999
- function tryMatchInline(text, pos) {
1000
- const matchers = [
1001
- () => matchCode(text, pos),
1002
- () => matchEmphasis(text, pos),
1003
- () => matchStrikethrough(text, pos),
1004
- () => matchHighlight(text, pos)
1005
- ];
1006
- for (const match of matchers) {
1007
- const result = match();
1008
- if (result) {
1009
- return {
1010
- token: result.token,
1011
- startIndex: pos,
1012
- endIndex: result.end
1013
- };
1014
- }
1015
- }
1016
- return null;
1017
- }
1018
-
1019
- // src/parsers/markdown.ts
1020
- var DEFAULT_OPTIONS = {
1021
- generateId,
1022
- strict: false
1023
- };
1024
- function markdownToBlocks(markdown, options = {}) {
1025
- const opts = { ...DEFAULT_OPTIONS, ...options };
1026
- const tokens = tokenize(markdown);
1027
- return parseTokens(tokens, opts);
1028
- }
1029
- function parseTokens(tokens, options) {
1030
- const blocks = [];
1031
- const state = {
1032
- options,
1033
- tokens,
1034
- index: 0
1035
- };
1036
- while (state.index < tokens.length) {
1037
- const token = tokens[state.index];
1038
- if (token.type === "blank") {
1039
- state.index++;
1040
- continue;
1041
- }
1042
- const block = parseBlock(state);
1043
- if (block) {
1044
- blocks.push(block);
1045
- }
1046
- }
1047
- return blocks;
1048
- }
1049
- function parseBlock(state) {
1050
- const token = state.tokens[state.index];
1051
- switch (token.type) {
1052
- case "heading":
1053
- return parseHeading(state);
1054
- case "paragraph":
1055
- return parseParagraph(state);
1056
- case "bullet_list_item":
1057
- return parseBulletList(state);
1058
- case "numbered_list_item":
1059
- return parseNumberedList(state);
1060
- case "check_list_item":
1061
- return parseCheckListItem(state);
1062
- case "code_fence_start":
1063
- return parseCodeBlock(state);
1064
- case "blockquote":
1065
- return parseBlockquote(state);
1066
- case "callout":
1067
- return parseCallout(state);
1068
- case "divider":
1069
- return parseDivider(state);
1070
- case "table_row":
1071
- return parseTable(state);
1072
- case "image":
1073
- return parseImage(state);
1074
- default:
1075
- state.index++;
1076
- return null;
1077
- }
1078
- }
1079
- function parseHeading(state) {
1080
- const token = state.tokens[state.index];
1081
- const level = token.meta?.level ?? 1;
1082
- const content = parseInlineContent(token.content);
1083
- state.index++;
1084
- return {
1085
- id: state.options.generateId(),
1086
- type: "heading",
1087
- content,
1088
- children: [],
1089
- props: { level }
1090
- };
1091
- }
1092
- function parseParagraph(state) {
1093
- const lines = [];
1094
- while (state.index < state.tokens.length && state.tokens[state.index].type === "paragraph") {
1095
- lines.push(state.tokens[state.index].content);
1096
- state.index++;
1097
- }
1098
- const content = parseInlineContent(lines.join(" "));
1099
- return {
1100
- id: state.options.generateId(),
1101
- type: "paragraph",
1102
- content,
1103
- children: [],
1104
- props: {}
1105
- };
1106
- }
1107
- function parseBulletList(state) {
1108
- const children = [];
1109
- const baseIndent = state.tokens[state.index].indent;
1110
- while (state.index < state.tokens.length && state.tokens[state.index].type === "bullet_list_item" && state.tokens[state.index].indent >= baseIndent) {
1111
- const token = state.tokens[state.index];
1112
- if (token.indent > baseIndent) {
1113
- state.index++;
1114
- continue;
1115
- }
1116
- const content = parseInlineContent(token.content);
1117
- children.push({
1118
- id: state.options.generateId(),
1119
- type: "paragraph",
1120
- content,
1121
- children: [],
1122
- props: {}
1123
- });
1124
- state.index++;
1125
- }
1126
- return {
1127
- id: state.options.generateId(),
1128
- type: "bulletList",
1129
- content: [],
1130
- children,
1131
- props: {}
1132
- };
1133
- }
1134
- function parseNumberedList(state) {
1135
- const children = [];
1136
- const baseIndent = state.tokens[state.index].indent;
1137
- while (state.index < state.tokens.length && state.tokens[state.index].type === "numbered_list_item" && state.tokens[state.index].indent >= baseIndent) {
1138
- const token = state.tokens[state.index];
1139
- if (token.indent > baseIndent) {
1140
- state.index++;
1141
- continue;
1142
- }
1143
- const content = parseInlineContent(token.content);
1144
- children.push({
1145
- id: state.options.generateId(),
1146
- type: "paragraph",
1147
- content,
1148
- children: [],
1149
- props: {}
1150
- });
1151
- state.index++;
1152
- }
1153
- return {
1154
- id: state.options.generateId(),
1155
- type: "numberedList",
1156
- content: [],
1157
- children,
1158
- props: {}
1159
- };
1160
- }
1161
- function parseCheckListItem(state) {
1162
- const token = state.tokens[state.index];
1163
- const checked = token.meta?.checked ?? false;
1164
- const content = parseInlineContent(token.content);
1165
- state.index++;
1166
- return {
1167
- id: state.options.generateId(),
1168
- type: "checkList",
1169
- content,
1170
- children: [],
1171
- props: { checked }
1172
- };
1173
- }
1174
- function parseCodeBlock(state) {
1175
- const startToken = state.tokens[state.index];
1176
- const language = startToken.meta?.language ?? "";
1177
- const codeLines = [];
1178
- state.index++;
1179
- while (state.index < state.tokens.length && state.tokens[state.index].type === "code_content") {
1180
- codeLines.push(state.tokens[state.index].content);
1181
- state.index++;
1182
- }
1183
- if (state.index < state.tokens.length && state.tokens[state.index].type === "code_fence_end") {
1184
- state.index++;
1185
- }
1186
- return {
1187
- id: state.options.generateId(),
1188
- type: "codeBlock",
1189
- content: plainContent(codeLines.join(`
1190
- `)),
1191
- children: [],
1192
- props: { language: language || undefined }
1193
- };
1194
- }
1195
- function parseBlockquote(state) {
1196
- const lines = [];
1197
- while (state.index < state.tokens.length && state.tokens[state.index].type === "blockquote") {
1198
- lines.push(state.tokens[state.index].content);
1199
- state.index++;
1200
- }
1201
- const content = parseInlineContent(lines.join(`
1202
- `));
1203
- return {
1204
- id: state.options.generateId(),
1205
- type: "blockquote",
1206
- content,
1207
- children: [],
1208
- props: {}
1209
- };
1210
- }
1211
- function parseCallout(state) {
1212
- const calloutToken = state.tokens[state.index];
1213
- const calloutType = calloutToken.meta?.calloutType ?? "note";
1214
- state.index++;
1215
- const lines = [];
1216
- while (state.index < state.tokens.length && state.tokens[state.index].type === "blockquote") {
1217
- lines.push(state.tokens[state.index].content);
1218
- state.index++;
1219
- }
1220
- const content = parseInlineContent(lines.join(`
1221
- `));
1222
- return {
1223
- id: state.options.generateId(),
1224
- type: "callout",
1225
- content,
1226
- children: [],
1227
- props: { type: calloutType }
1228
- };
1229
- }
1230
- function parseDivider(state) {
1231
- state.index++;
1232
- return {
1233
- id: state.options.generateId(),
1234
- type: "divider",
1235
- content: [],
1236
- children: [],
1237
- props: {}
1238
- };
1239
- }
1240
- function parseTable(state) {
1241
- const rows = [];
1242
- let headers = [];
1243
- let alignments = [];
1244
- let isFirstRow = true;
1245
- let hasSeparator = false;
1246
- while (state.index < state.tokens.length && (state.tokens[state.index].type === "table_row" || state.tokens[state.index].type === "table_separator")) {
1247
- const token = state.tokens[state.index];
1248
- if (token.type === "table_separator") {
1249
- alignments = parseTableAlignments(token.content);
1250
- hasSeparator = true;
1251
- state.index++;
1252
- continue;
1253
- }
1254
- const cells = token.content.split("|").map((cell) => cell.trim()).filter((cell) => cell !== "");
1255
- if (isFirstRow && !hasSeparator) {
1256
- headers = cells;
1257
- isFirstRow = false;
1258
- } else if (hasSeparator) {
1259
- rows.push(cells);
1260
- }
1261
- state.index++;
1262
- }
1263
- if (!hasSeparator && headers.length > 0) {
1264
- rows.unshift(headers);
1265
- headers = [];
1266
- }
1267
- return {
1268
- id: state.options.generateId(),
1269
- type: "table",
1270
- content: [],
1271
- children: [],
1272
- props: {
1273
- headers,
1274
- rows,
1275
- alignments: alignments.length > 0 ? alignments : undefined
1276
- }
1277
- };
1278
- }
1279
- function parseTableAlignments(separator) {
1280
- return separator.split("|").map((cell) => cell.trim()).filter((cell) => cell !== "").map((cell) => {
1281
- const leftColon = cell.startsWith(":");
1282
- const rightColon = cell.endsWith(":");
1283
- if (leftColon && rightColon)
1284
- return "center";
1285
- if (leftColon)
1286
- return "left";
1287
- if (rightColon)
1288
- return "right";
1289
- return null;
1290
- });
1291
- }
1292
- function parseImage(state) {
1293
- const token = state.tokens[state.index];
1294
- const url = token.content;
1295
- const alt = token.meta?.language ?? "";
1296
- state.index++;
1297
- return {
1298
- id: state.options.generateId(),
1299
- type: "image",
1300
- content: [],
1301
- children: [],
1302
- props: {
1303
- url,
1304
- alt: alt || undefined
1305
- }
1306
- };
1307
- }
1308
-
1309
- // src/serializers/markdown.ts
1310
- var DEFAULT_OPTIONS2 = {
1311
- lineEnding: `
1312
- `,
1313
- listIndent: 2,
1314
- headingStyle: "atx",
1315
- codeBlockStyle: "fenced",
1316
- bulletChar: "-",
1317
- emphasisChar: "*"
1318
- };
1319
- function blocksToMarkdown(blocks, options = {}) {
1320
- const opts = { ...DEFAULT_OPTIONS2, ...options };
1321
- const serializedBlocks = blocks.map((block, index) => serializeBlock(block, 0, opts, index, blocks));
1322
- return serializedBlocks.filter((s) => s !== null).join(opts.lineEnding + opts.lineEnding);
1323
- }
1324
- function serializeBlock(block, depth, options, index = 0, siblings = []) {
1325
- switch (block.type) {
1326
- case "paragraph":
1327
- return serializeParagraph(block, options);
1328
- case "heading":
1329
- return serializeHeading(block, options);
1330
- case "bulletList":
1331
- return serializeBulletList(block, depth, options);
1332
- case "numberedList":
1333
- return serializeNumberedList(block, depth, options, index, siblings);
1334
- case "checkList":
1335
- return serializeCheckList(block, depth, options);
1336
- case "codeBlock":
1337
- return serializeCodeBlock(block, options);
1338
- case "blockquote":
1339
- return serializeBlockquote(block, options);
1340
- case "table":
1341
- return serializeTable(block, options);
1342
- case "image":
1343
- return serializeImage(block);
1344
- case "divider":
1345
- return "---";
1346
- case "callout":
1347
- return serializeCallout(block, options);
1348
- default:
1349
- return serializeInlineContent(block.content, options);
1350
- }
1351
- }
1352
- function serializeParagraph(block, options) {
1353
- return serializeInlineContent(block.content, options);
1354
- }
1355
- function serializeHeading(block, options) {
1356
- const level = block.props.level;
1357
- const content = serializeInlineContent(block.content, options);
1358
- if (options.headingStyle === "setext" && (level === 1 || level === 2)) {
1359
- const underline = level === 1 ? "=" : "-";
1360
- return `${content}${options.lineEnding}${underline.repeat(content.length)}`;
1361
- }
1362
- return `${"#".repeat(level)} ${content}`;
1363
- }
1364
- function serializeBulletList(block, depth, options) {
1365
- const indent = " ".repeat(depth * options.listIndent);
1366
- const bullet = options.bulletChar;
1367
- return block.children.map((child) => {
1368
- const content = serializeListItemContent(child, depth, options);
1369
- return `${indent}${bullet} ${content}`;
1370
- }).join(options.lineEnding);
1371
- }
1372
- function serializeNumberedList(block, depth, options, _blockIndex = 0, _siblings = []) {
1373
- const indent = " ".repeat(depth * options.listIndent);
1374
- return block.children.map((child, index) => {
1375
- const content = serializeListItemContent(child, depth, options);
1376
- return `${indent}${index + 1}. ${content}`;
1377
- }).join(options.lineEnding);
1378
- }
1379
- function serializeCheckList(block, depth, options) {
1380
- const indent = " ".repeat(depth * options.listIndent);
1381
- const checked = block.props.checked ? "x" : " ";
1382
- const content = serializeInlineContent(block.content, options);
1383
- return `${indent}- [${checked}] ${content}`;
1384
- }
1385
- function serializeListItemContent(item, depth, options) {
1386
- if (item.children.length > 0) {
1387
- const content = serializeInlineContent(item.content, options);
1388
- const nestedContent = item.children.map((child, index) => serializeBlock(child, depth + 1, options, index, item.children)).join(options.lineEnding);
1389
- return `${content}${options.lineEnding}${nestedContent}`;
1390
- }
1391
- return serializeInlineContent(item.content, options);
1392
- }
1393
- function serializeCodeBlock(block, options) {
1394
- const code = spansToPlainText(block.content);
1395
- const language = block.props.language ?? "";
1396
- if (options.codeBlockStyle === "indented") {
1397
- return code.split(`
1398
- `).map((line) => ` ${line}`).join(options.lineEnding);
1399
- }
1400
- return `\`\`\`${language}${options.lineEnding}${code}${options.lineEnding}\`\`\``;
1401
- }
1402
- function serializeBlockquote(block, options) {
1403
- const content = serializeInlineContent(block.content, options);
1404
- return content.split(`
1405
- `).map((line) => `> ${line}`).join(options.lineEnding);
1406
- }
1407
- function serializeImage(block) {
1408
- const alt = block.props.alt ?? "";
1409
- const url = block.props.url ?? "";
1410
- const title = block.props.title;
1411
- if (title) {
1412
- return `![${alt}](${url} "${title}")`;
1413
- }
1414
- return `![${alt}](${url})`;
1415
- }
1416
- function serializeTable(block, options) {
1417
- const { headers, rows, alignments } = block.props;
1418
- const lineEnding = options.lineEnding;
1419
- const columnWidths = headers.map((header, i) => {
1420
- const rowWidths = rows.map((row) => (row[i] ?? "").length);
1421
- return Math.max(header.length, ...rowWidths, 3);
1422
- });
1423
- const headerRow = headers.map((header, i) => header.padEnd(columnWidths[i])).join(" | ");
1424
- const separatorRow = headers.map((_, i) => {
1425
- const width = columnWidths[i];
1426
- const alignment = alignments?.[i] ?? null;
1427
- if (alignment === "left")
1428
- return `:${"-".repeat(width - 1)}`;
1429
- if (alignment === "right")
1430
- return `${"-".repeat(width - 1)}:`;
1431
- if (alignment === "center")
1432
- return `:${"-".repeat(width - 2)}:`;
1433
- return "-".repeat(width);
1434
- }).join(" | ");
1435
- const dataRows = rows.map((row) => row.map((cell, i) => (cell ?? "").padEnd(columnWidths[i])).join(" | "));
1436
- return [
1437
- `| ${headerRow} |`,
1438
- `| ${separatorRow} |`,
1439
- ...dataRows.map((row) => `| ${row} |`)
1440
- ].join(lineEnding);
1441
- }
1442
- function serializeCallout(block, options) {
1443
- const type = block.props.type.toUpperCase();
1444
- const content = serializeInlineContent(block.content, options);
1445
- const lineEnding = options.lineEnding;
1446
- return `> [!${type}]${lineEnding}> ${content.split(`
1447
- `).join(`${lineEnding}> `)}`;
1448
- }
1449
- function serializeInlineContent(spans, options) {
1450
- return spans.map((span) => serializeSpan(span, options)).join("");
1451
- }
1452
- function serializeSpan(span, options) {
1453
- let text = span.text;
1454
- const styles = span.styles;
1455
- if (!hasStyles(styles)) {
1456
- return text;
1457
- }
1458
- if (styles.code) {
1459
- text = `\`${text}\``;
1460
- }
1461
- if (styles.highlight) {
1462
- text = `==${text}==`;
1463
- }
1464
- if (styles.strikethrough) {
1465
- text = `~~${text}~~`;
1466
- }
1467
- if (styles.bold && styles.italic) {
1468
- const char = options.emphasisChar;
1469
- text = `${char}${char}${char}${text}${char}${char}${char}`;
1470
- } else {
1471
- if (styles.italic) {
1472
- const char = options.emphasisChar;
1473
- text = `${char}${text}${char}`;
1474
- }
1475
- if (styles.bold) {
1476
- const char = options.emphasisChar;
1477
- text = `${char}${char}${text}${char}${char}`;
1478
- }
1479
- }
1480
- if (styles.underline) {
1481
- text = `<u>${text}</u>`;
1482
- }
1483
- if (styles.link) {
1484
- const { url, title } = styles.link;
1485
- if (title) {
1486
- text = `[${text}](${url} "${title}")`;
1487
- } else {
1488
- text = `[${text}](${url})`;
1489
- }
1490
- }
1491
- return text;
1492
- }
1493
- function hasStyles(styles) {
1494
- return !!(styles.bold || styles.italic || styles.underline || styles.strikethrough || styles.code || styles.highlight || styles.link);
1495
- }
1496
-
1497
- // src/react/hooks.ts
1498
- function useDocument(initialBlocks = [], options) {
1499
- const [document, setDocument] = useState(() => createDocument(initialBlocks, options));
1500
- const insert = useCallback((block, index) => {
1501
- setDocument((doc) => insertBlock(doc, block, index));
1502
- }, []);
1503
- const append = useCallback((block) => {
1504
- setDocument((doc) => appendBlock(doc, block));
1505
- }, []);
1506
- const remove = useCallback((blockId) => {
1507
- setDocument((doc) => removeBlock(doc, blockId));
1508
- }, []);
1509
- const update = useCallback((blockId, updates) => {
1510
- setDocument((doc) => updateBlock(doc, blockId, updates));
1511
- }, []);
1512
- const move = useCallback((blockId, newIndex) => {
1513
- setDocument((doc) => moveBlock(doc, blockId, newIndex));
1514
- }, []);
1515
- const find = useCallback((blockId) => findBlock(document, blockId), [document]);
1516
- const getIndex = useCallback((blockId) => getBlockIndex(document, blockId), [document]);
1517
- const clear = useCallback(() => {
1518
- setDocument((doc) => clearBlocks(doc));
1519
- }, []);
1520
- const set = useCallback((blocks) => {
1521
- setDocument((doc) => setBlocks(doc, blocks));
1522
- }, []);
1523
- const toMd = useCallback(() => blocksToMarkdown(document.blocks), [document]);
1524
- const fromMd = useCallback((markdown) => {
1525
- const blocks = markdownToBlocks(markdown);
1526
- setDocument((doc) => setBlocks(doc, blocks));
1527
- }, []);
1528
- const meta = useCallback((newMeta) => {
1529
- setDocument((doc) => updateMeta(doc, newMeta));
1530
- }, []);
1531
- return {
1532
- document,
1533
- blocks: document.blocks,
1534
- insertBlock: insert,
1535
- appendBlock: append,
1536
- removeBlock: remove,
1537
- updateBlock: update,
1538
- moveBlock: move,
1539
- findBlock: find,
1540
- getBlockIndex: getIndex,
1541
- clearBlocks: clear,
1542
- setBlocks: set,
1543
- setDocument,
1544
- toMarkdown: toMd,
1545
- fromMarkdown: fromMd,
1546
- updateMeta: meta
1547
- };
1548
- }
1549
- function useMarkdown(initialMarkdown = "") {
1550
- const [markdown, setMarkdownState] = useState(initialMarkdown);
1551
- const blocks = useMemo(() => markdownToBlocks(markdown), [markdown]);
1552
- const setMarkdown = useCallback((newMarkdown) => {
1553
- setMarkdownState(newMarkdown);
1554
- }, []);
1555
- const setBlocksFromBlocks = useCallback((newBlocks) => {
1556
- const newMarkdown = blocksToMarkdown(newBlocks);
1557
- setMarkdownState(newMarkdown);
1558
- }, []);
1559
- return {
1560
- markdown,
1561
- blocks,
1562
- setMarkdown,
1563
- setBlocks: setBlocksFromBlocks
1564
- };
1565
- }
1566
- function useBlockEditor(documentHook) {
1567
- const { document, blocks, removeBlock: removeBlock2, updateBlock: updateBlock2, moveBlock: moveBlock2, insertBlock: insertBlock2 } = documentHook;
1568
- const [selectedBlockId, setSelectedBlockId] = useState(null);
1569
- const selectedBlock = useMemo(() => selectedBlockId ? findBlock(document, selectedBlockId) : undefined, [document, selectedBlockId]);
1570
- const selectBlock = useCallback((blockId) => {
1571
- setSelectedBlockId(blockId);
1572
- }, []);
1573
- const selectNext = useCallback(() => {
1574
- if (!selectedBlockId) {
1575
- if (blocks.length > 0) {
1576
- setSelectedBlockId(blocks[0].id);
1577
- }
1578
- return;
1579
- }
1580
- const currentIndex = getBlockIndex(document, selectedBlockId);
1581
- if (currentIndex < blocks.length - 1) {
1582
- setSelectedBlockId(blocks[currentIndex + 1].id);
1583
- }
1584
- }, [document, blocks, selectedBlockId]);
1585
- const selectPrevious = useCallback(() => {
1586
- if (!selectedBlockId) {
1587
- if (blocks.length > 0) {
1588
- setSelectedBlockId(blocks[blocks.length - 1].id);
1589
- }
1590
- return;
1591
- }
1592
- const currentIndex = getBlockIndex(document, selectedBlockId);
1593
- if (currentIndex > 0) {
1594
- setSelectedBlockId(blocks[currentIndex - 1].id);
1595
- }
1596
- }, [document, blocks, selectedBlockId]);
1597
- const deleteSelected = useCallback(() => {
1598
- if (!selectedBlockId)
1599
- return;
1600
- const currentIndex = getBlockIndex(document, selectedBlockId);
1601
- removeBlock2(selectedBlockId);
1602
- if (blocks.length > 1) {
1603
- if (currentIndex < blocks.length - 1) {
1604
- setSelectedBlockId(blocks[currentIndex + 1].id);
1605
- } else if (currentIndex > 0) {
1606
- setSelectedBlockId(blocks[currentIndex - 1].id);
1607
- }
1608
- } else {
1609
- setSelectedBlockId(null);
1610
- }
1611
- }, [document, blocks, selectedBlockId, removeBlock2]);
1612
- const updateSelectedContent = useCallback((content) => {
1613
- if (!selectedBlockId)
1614
- return;
1615
- updateBlock2(selectedBlockId, { content });
1616
- }, [selectedBlockId, updateBlock2]);
1617
- const duplicateSelected = useCallback(() => {
1618
- if (!selectedBlockId || !selectedBlock)
1619
- return;
1620
- const currentIndex = getBlockIndex(document, selectedBlockId);
1621
- const clonedBlock = {
1622
- ...selectedBlock,
1623
- id: Math.random().toString(36).substring(2, 9)
1624
- };
1625
- insertBlock2(clonedBlock, currentIndex + 1);
1626
- setSelectedBlockId(clonedBlock.id);
1627
- }, [document, selectedBlockId, selectedBlock, insertBlock2]);
1628
- const moveSelectedUp = useCallback(() => {
1629
- if (!selectedBlockId)
1630
- return;
1631
- const currentIndex = getBlockIndex(document, selectedBlockId);
1632
- if (currentIndex > 0) {
1633
- moveBlock2(selectedBlockId, currentIndex - 1);
1634
- }
1635
- }, [document, selectedBlockId, moveBlock2]);
1636
- const moveSelectedDown = useCallback(() => {
1637
- if (!selectedBlockId)
1638
- return;
1639
- const currentIndex = getBlockIndex(document, selectedBlockId);
1640
- if (currentIndex < blocks.length - 1) {
1641
- moveBlock2(selectedBlockId, currentIndex + 1);
1642
- }
1643
- }, [document, blocks, selectedBlockId, moveBlock2]);
1644
- return {
1645
- selectedBlockId,
1646
- selectedBlock,
1647
- selectBlock,
1648
- selectNext,
1649
- selectPrevious,
1650
- deleteSelected,
1651
- updateSelectedContent,
1652
- duplicateSelected,
1653
- moveSelectedUp,
1654
- moveSelectedDown
1655
- };
1656
- }
1657
- // src/core/blocks.ts
1658
- function createBlock(type, content = [], props = {}, children = []) {
1659
- return {
1660
- id: generateId(),
1661
- type,
1662
- content,
1663
- children,
1664
- props
1665
- };
1666
- }
1667
- function text(content) {
1668
- return plainSpan(content);
1669
- }
1670
- function bold(content) {
1671
- return { text: content, styles: { bold: true } };
1672
- }
1673
- function italic(content) {
1674
- return { text: content, styles: { italic: true } };
1675
- }
1676
- function code(content) {
1677
- return { text: content, styles: { code: true } };
1678
- }
1679
- function link(content, url, title) {
1680
- return {
1681
- text: content,
1682
- styles: { link: { url, title } }
1683
- };
1684
- }
1685
- function paragraph(content) {
1686
- const textContent = typeof content === "string" ? plainContent(content) : content;
1687
- return createBlock("paragraph", textContent, {});
1688
- }
1689
- function heading(level, content) {
1690
- const textContent = typeof content === "string" ? plainContent(content) : content;
1691
- return createBlock("heading", textContent, { level });
1692
- }
1693
- var h1 = (content) => heading(1, content);
1694
- var h2 = (content) => heading(2, content);
1695
- var h3 = (content) => heading(3, content);
1696
- var h4 = (content) => heading(4, content);
1697
- var h5 = (content) => heading(5, content);
1698
- var h6 = (content) => heading(6, content);
1699
- function bulletList(items) {
1700
- const children = items.map((item) => {
1701
- if (typeof item === "string") {
1702
- return paragraph(item);
1703
- }
1704
- if (Array.isArray(item)) {
1705
- return paragraph(item);
1706
- }
1707
- return item;
1708
- });
1709
- return createBlock("bulletList", [], {}, children);
1710
- }
1711
- function numberedList(items) {
1712
- const children = items.map((item) => {
1713
- if (typeof item === "string") {
1714
- return paragraph(item);
1715
- }
1716
- if (Array.isArray(item)) {
1717
- return paragraph(item);
1718
- }
1719
- return item;
1720
- });
1721
- return createBlock("numberedList", [], {}, children);
1722
- }
1723
- function checkListItem(content, checked = false) {
1724
- const textContent = typeof content === "string" ? plainContent(content) : content;
1725
- return createBlock("checkList", textContent, { checked });
1726
- }
1727
- function checkList(items) {
1728
- return items.map((item) => checkListItem(item.content, item.checked ?? false));
1729
- }
1730
- function codeBlock(code2, language) {
1731
- return createBlock("codeBlock", plainContent(code2), { language });
1732
- }
1733
- function blockquote(content) {
1734
- const textContent = typeof content === "string" ? plainContent(content) : content;
1735
- return createBlock("blockquote", textContent, {});
1736
- }
1737
- function divider() {
1738
- return createBlock("divider", [], {});
1739
- }
1740
- function image(url, alt, options) {
1741
- return createBlock("image", [], {
1742
- url,
1743
- alt,
1744
- title: options?.title,
1745
- width: options?.width,
1746
- height: options?.height
1747
- });
1748
- }
1749
- function callout(type, content) {
1750
- const textContent = typeof content === "string" ? plainContent(content) : content;
1751
- return createBlock("callout", textContent, { type });
1752
- }
1753
- export {
1754
- useMarkdown,
1755
- useDocument,
1756
- useBlockEditor,
1757
- text,
1758
- paragraph,
1759
- numberedList,
1760
- link,
1761
- italic,
1762
- image,
1763
- heading,
1764
- h6,
1765
- h5,
1766
- h4,
1767
- h3,
1768
- h2,
1769
- h1,
1770
- divider,
1771
- codeBlock,
1772
- code,
1773
- checkListItem,
1774
- checkList,
1775
- callout,
1776
- bulletList,
1777
- bold,
1778
- blockquote,
1779
- InlineContent,
1780
- BlockRenderer,
1781
- BlockElement
1782
- };