@threadlabs/looma 0.45.1 → 0.46.1

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,5 +1,5 @@
1
1
  import { n as TABLE_CELL_BACKGROUND_PRESETS } from "./table-backgrounds.js";
2
- import { _ as normalizeLoomaChipTone, b as readLoomaAttributes, c as LOOMA_CONTAINER_NAMES, d as assignLoomaHeadingIds, f as formatLoomaAttributes, g as normalizeLoomaCalloutTone, h as loomaHeadingSlug, i as referenceDisplay, l as LOOMA_MENTION_HANDLE, m as loomaContainerMarker, n as LoomaReferencePresentation, p as loomaCodeFence, r as getReferenceDisplay, s as LOOMA_CHIP_TONES, t as LoomaReference, u as applyLoomaCodeNotation, v as parseLoomaAttributes, x as splitLoomaFrontmatter, y as parseLoomaFenceInfo } from "./reference-display.js";
2
+ import { _ as normalizeLoomaChipTone, c as LoomaReferencePresentation, g as normalizeLoomaCalloutTone, h as loomaHeadingSlug, l as getReferenceDisplay, m as assignLoomaHeadingIds, o as markdownToEditorDocument, p as LOOMA_CHIP_TONES, s as LoomaReference, u as referenceDisplay, v as splitLoomaFrontmatter } from "./expressmark.js";
3
3
  import { Extension, InputRule, Mark, Node as Node$1, PasteRule, callOrReturn, canInsertNode, combineTransactionSteps, escapeForRegEx, findChildren, findChildrenInRange, findParentNodeClosestToPos, getAttributes, getChangedRanges, getExtensionField, getMarksBetween, getText, getTextSerializersFromSchema, isNodeEmpty, isNodeSelection, markInputRule, markPasteRule, mergeAttributes, nodeInputRule, textInputRule, textblockTypeInputRule, wrappingInputRule } from "@tiptap/core";
4
4
  import { NodeSelection, Plugin, PluginKey, Selection, TextSelection } from "@tiptap/pm/state";
5
5
  import { Decoration, DecorationSet } from "@tiptap/pm/view";
@@ -9,8 +9,7 @@ import { dropCursor } from "@tiptap/pm/dropcursor";
9
9
  import { gapCursor } from "@tiptap/pm/gapcursor";
10
10
  import { createLowlight } from "lowlight";
11
11
  import { Mapping } from "@tiptap/pm/transform";
12
- import { MarkdownSerializer, defaultMarkdownSerializer } from "@tiptap/pm/markdown";
13
- import MarkdownIt from "markdown-it";
12
+ import { parse } from "expressmark";
14
13
  import { CellSelection, TableMap, addColumn, addColumnAfter, addColumnBefore, addRow, addRowAfter, addRowBefore, cellAround, columnResizing, deleteCellSelection, deleteColumn, deleteRow, deleteTable, fixTables, goToNextCell, mergeCells, moveTableColumn, moveTableRow, setCellAttr, splitCell, tableEditing, toggleHeader, toggleHeaderCell } from "@tiptap/pm/tables";
15
14
  //#region src/editor/extensions/active-block.ts
16
15
  /**
@@ -481,7 +480,6 @@ var labelFrom = (href, prefix) => href?.startsWith(`#${prefix}`) ? href.slice(pr
481
480
  var LOOMA_FOOTNOTE_LABEL = /^[^\s\]]+$/;
482
481
  var LOOMA_FOOTNOTE_INSERTED = "loomaFootnoteInserted";
483
482
  var REFERENCE = "loomaFootnoteReference";
484
- var NOTES = "loomaFootnotes";
485
483
  var NOTE = "loomaFootnote";
486
484
  var isLabel = (label) => LOOMA_FOOTNOTE_LABEL.test(label);
487
485
  /** Every label a reference or note in `doc` uses. */
@@ -510,13 +508,6 @@ function findLoomaFootnote(doc, label) {
510
508
  });
511
509
  return found;
512
510
  }
513
- function mapReferences(node, change) {
514
- if (node.type.name === REFERENCE) return change(node);
515
- if (node.isLeaf) return node;
516
- const children = [];
517
- node.content.forEach((child) => children.push(mapReferences(child, change)));
518
- return node.copy(Fragment.from(children));
519
- }
520
511
  function noteAt(doc, position) {
521
512
  const $position = doc.resolve(position);
522
513
  for (let depth = $position.depth; depth > 0; depth--) {
@@ -529,120 +520,115 @@ function noteAt(doc, position) {
529
520
  return null;
530
521
  }
531
522
  /**
532
- * Keeps footnotes on Looma Markdown's rule, so the saved HTML is the HTML Looma Markdown renders for
533
- * the same document. Notes are numbered by first reference, in the text and then in the notes, and
534
- * every reference carries its note's number and its place among that note's references. The notes
535
- * live in one `loomaFootnotes` section at the end of the document, in number order. A note no
536
- * reference points to leaves the document; a reference with no note gets one back, the note it last
537
- * had in this editor (so cutting a reference and pasting it keeps its note) or an empty one.
538
- * @invariant Changing nothing but text inside a note never rebuilds the section.
523
+ * Looma Markdown's footnote numbering for `content`, in document order. Notes are numbered by first
524
+ * reference, in the text and then in the notes, and every reference has its note's number and its
525
+ * place among that note's references. The first note for a label is its note, as with Markdown's
526
+ * definitions; any other note, or one nothing refers to, has no number.
539
527
  */
540
- function footnoteTransaction(state, known) {
541
- const { doc, schema } = state;
542
- const sections = [];
543
- const notes = /* @__PURE__ */ new Map();
544
- const body = [];
545
- doc.descendants((node, position) => {
546
- if (node.type.name === NOTES) {
547
- sections.push({
548
- node,
549
- position
550
- });
551
- node.forEach((note) => {
552
- if (!notes.has(note.attrs.label)) notes.set(note.attrs.label, note);
553
- });
554
- return false;
555
- }
556
- if (node.type.name === REFERENCE) body.push({
557
- node,
558
- position
528
+ function numberFootnotes(content) {
529
+ const references = [];
530
+ const notes = [];
531
+ const first = /* @__PURE__ */ new Map();
532
+ const visit = (fragment, note) => fragment.forEach((node) => {
533
+ if (node.type.name === REFERENCE) references.push({
534
+ label: String(node.attrs.label),
535
+ note
559
536
  });
537
+ else if (node.type.name === NOTE) {
538
+ notes.push(node);
539
+ if (!first.has(node.attrs.label)) first.set(node.attrs.label, node);
540
+ visit(node.content, node);
541
+ } else visit(node.content, note);
560
542
  });
561
- if (!sections.length && !body.length) return null;
543
+ visit(content, null);
562
544
  const order = [];
563
545
  const counts = /* @__PURE__ */ new Map();
564
- const numbered = (reference) => {
565
- const label = String(reference.attrs.label);
546
+ const numbered = /* @__PURE__ */ new Map();
547
+ const number = (index) => {
548
+ const { label } = references[index];
566
549
  if (!counts.has(label)) order.push(label);
567
550
  counts.set(label, (counts.get(label) ?? 0) + 1);
568
- const attrs = {
569
- ...reference.attrs,
551
+ numbered.set(index, {
570
552
  number: order.indexOf(label) + 1,
571
553
  occurrence: counts.get(label)
572
- };
573
- return attrs.number === reference.attrs.number && attrs.occurrence === reference.attrs.occurrence ? reference : reference.type.create(attrs, null, reference.marks);
554
+ });
574
555
  };
575
- const transaction = state.tr;
576
- for (const { node, position } of body) {
577
- const next = numbered(node);
578
- if (next !== node) transaction.setNodeMarkup(position, void 0, next.attrs);
579
- }
580
- const built = [];
581
- for (let index = 0; index < order.length; index++) {
582
- const label = order[index];
583
- const note = notes.get(label) ?? known.get(label) ?? schema.nodes[NOTE].create({ label }, schema.nodes.paragraph.create());
584
- built.push(mapReferences(note, numbered));
585
- }
586
- const wanted = built.map((note) => note.attrs.count === counts.get(note.attrs.label) ? note : note.type.create({
587
- ...note.attrs,
588
- count: counts.get(note.attrs.label)
589
- }, note.content));
590
- for (const note of [...notes.values(), ...wanted]) known.set(note.attrs.label, note);
591
- const section = wanted.length ? schema.nodes[NOTES].create(null, wanted) : null;
592
- const last = doc.lastChild?.type.name === NOTES ? {
593
- node: doc.lastChild,
594
- position: doc.content.size - doc.lastChild.nodeSize
595
- } : null;
596
- if (!(section && last && sections.length === 1 && last.node.eq(section)) && (sections.length || section)) {
597
- const { selection } = state;
598
- const inside = noteAt(doc, selection.from);
599
- const keep = inside && selection.to <= inside.start + inside.node.nodeSize ? {
600
- label: inside.node.attrs.label,
601
- start: inside.start
602
- } : null;
603
- for (const { node, position } of [...sections].reverse()) if (node !== last?.node) transaction.delete(position, position + node.nodeSize);
604
- if (last) {
605
- const position = transaction.mapping.map(last.position);
606
- if (section) transaction.replaceWith(position, position + last.node.nodeSize, section);
607
- else transaction.delete(position, position + last.node.nodeSize);
608
- } else if (section) transaction.insert(transaction.doc.content.size, section);
609
- const moved = keep && findLoomaFootnote(transaction.doc, keep.label);
610
- if (keep && moved) {
611
- const json = selection.toJSON();
612
- json.anchor += moved.position - keep.start;
613
- if (json.head !== void 0) json.head += moved.position - keep.start;
614
- try {
615
- transaction.setSelection(Selection.fromJSON(transaction.doc, json));
616
- } catch {}
617
- }
618
- }
619
- return transaction.docChanged ? transaction : null;
620
- }
621
- function appendBackLinks(item, label, number, count) {
622
- const document = item.ownerDocument;
623
- let paragraph = item.lastElementChild;
624
- if (paragraph?.nodeName !== "P") item.append(paragraph = document.createElement("p"));
625
- for (let occurrence = 1; occurrence <= count; occurrence++) {
626
- const link = document.createElement("a");
627
- link.setAttribute("href", `#fnref:${label}${occurrence > 1 ? `:${occurrence}` : ""}`);
628
- link.setAttribute("data-footnote-backref", "");
629
- link.setAttribute("aria-label", `Back to reference ${number}${occurrence > 1 ? `-${occurrence}` : ""}`);
630
- link.append("↩");
631
- if (occurrence > 1) link.append(Object.assign(document.createElement("sup"), { textContent: String(occurrence) }));
632
- paragraph.append(" ", link);
556
+ references.forEach((reference, index) => {
557
+ if (!reference.note) number(index);
558
+ });
559
+ for (let at = 0; at < order.length; at++) {
560
+ const note = first.get(order[at]);
561
+ references.forEach((reference, index) => {
562
+ if (note && reference.note === note) number(index);
563
+ });
633
564
  }
565
+ return {
566
+ order,
567
+ counts,
568
+ references: references.map((_reference, index) => numbered.get(index) ?? {
569
+ number: null,
570
+ occurrence: 1
571
+ }),
572
+ notes: notes.map((note) => ({
573
+ number: first.get(note.attrs.label) === note && counts.has(note.attrs.label) ? order.indexOf(note.attrs.label) + 1 : null,
574
+ count: counts.get(note.attrs.label) ?? 1
575
+ }))
576
+ };
634
577
  }
635
- function installSerializer(schema) {
636
- const serializer = DOMSerializer.fromSchema(schema);
637
- if (Object.prototype.hasOwnProperty.call(serializer, "serializeFragment")) return;
638
- const serializeFragment = serializer.serializeFragment;
639
- serializer.serializeFragment = function(fragment, options = {}, target) {
640
- const dom = serializeFragment.call(this, fragment, options, target);
641
- fragment.forEach((node, _offset, index) => {
642
- if (node.type.name === NOTE) appendBackLinks(dom.childNodes[index], String(node.attrs.label), index + 1, Number(node.attrs.count) || 1);
578
+ /**
579
+ * Keeps footnotes on Looma Markdown's rule (`numberFootnotes`). Each note stays where its definition
580
+ * is written. Removing a note's last reference removes the note; a reference with no note gets one
581
+ * back at the end of the document, the note it last had in this editor (so cutting a reference and
582
+ * pasting it keeps its note) or an empty one. A note nothing has referred to in this editor, as a
583
+ * document may define one, stays.
584
+ * @invariant Changing nothing but text inside a note never moves or renumbers a note.
585
+ */
586
+ function footnoteTransaction(state, previous, known) {
587
+ const { doc, schema } = state;
588
+ const references = [];
589
+ const notes = [];
590
+ doc.descendants((node, position) => {
591
+ if (node.type.name === REFERENCE) references.push({
592
+ node,
593
+ position
594
+ });
595
+ if (node.type.name === NOTE) notes.push({
596
+ node,
597
+ position
598
+ });
599
+ });
600
+ if (!references.length && !notes.length) return null;
601
+ previous?.descendants((node) => {
602
+ if (node.type.name === NOTE && !known.has(node.attrs.label)) known.set(node.attrs.label, node);
603
+ });
604
+ const numbering = numberFootnotes(doc.content);
605
+ const transaction = state.tr;
606
+ const update = ({ node, position }, attrs) => {
607
+ if (Object.entries(attrs).some(([key, value]) => node.attrs[key] !== value)) transaction.setNodeMarkup(position, void 0, {
608
+ ...node.attrs,
609
+ ...attrs
643
610
  });
644
- return dom;
645
611
  };
612
+ references.forEach((reference, index) => update(reference, numbering.references[index]));
613
+ notes.forEach((note, index) => {
614
+ update(note, numbering.notes[index]);
615
+ known.set(note.node.attrs.label, note.node);
616
+ });
617
+ const referenced = /* @__PURE__ */ new Set();
618
+ previous?.descendants((node) => {
619
+ if (node.type.name === REFERENCE) referenced.add(String(node.attrs.label));
620
+ });
621
+ for (const { node, position } of [...notes].reverse()) if (referenced.has(node.attrs.label) && !numbering.counts.has(node.attrs.label)) transaction.delete(transaction.mapping.map(position), transaction.mapping.map(position + node.nodeSize));
622
+ for (const label of numbering.order) {
623
+ if (notes.some(({ node }) => node.attrs.label === label)) continue;
624
+ const note = known.get(label) ?? schema.nodes[NOTE].create({ label }, schema.nodes.paragraph.create());
625
+ transaction.insert(transaction.doc.content.size, note.type.create({
626
+ ...note.attrs,
627
+ number: numbering.order.indexOf(label) + 1,
628
+ count: numbering.counts.get(label)
629
+ }, note.content));
630
+ }
631
+ return transaction.docChanged ? transaction : null;
646
632
  }
647
633
  /**
648
634
  * A footnote reference, `[^label]`, saved as `<sup><a data-footnote-ref>`. Typing or pasting
@@ -743,64 +729,158 @@ var LoomaFootnoteReference = Node$1.create({
743
729
  };
744
730
  }
745
731
  });
732
+ function appendBackLinks(item, label, number, count) {
733
+ const document = item.ownerDocument;
734
+ let paragraph = item.lastElementChild;
735
+ if (paragraph?.nodeName !== "P") item.append(paragraph = document.createElement("p"));
736
+ for (let occurrence = 1; occurrence <= count; occurrence++) {
737
+ const link = document.createElement("a");
738
+ link.setAttribute("href", `#fnref:${label}${occurrence > 1 ? `:${occurrence}` : ""}`);
739
+ link.setAttribute("data-footnote-backref", "");
740
+ link.setAttribute("aria-label", `Back to reference ${number}${occurrence > 1 ? `-${occurrence}` : ""}`);
741
+ link.append("↩");
742
+ if (occurrence > 1) link.append(Object.assign(document.createElement("sup"), { textContent: String(occurrence) }));
743
+ paragraph.append(" ", link);
744
+ }
745
+ }
746
+ function installSerializer(schema) {
747
+ const serializer = DOMSerializer.fromSchema(schema);
748
+ if (Object.prototype.hasOwnProperty.call(serializer, "serializeFragment")) return;
749
+ const serializeFragment = serializer.serializeFragment;
750
+ serializer.serializeFragment = function(fragment, options = {}, target) {
751
+ const dom = serializeFragment.call(this, fragment, options, target);
752
+ if (target) return dom;
753
+ const numbering = numberFootnotes(fragment);
754
+ const references = [...dom.querySelectorAll("a[data-footnote-ref]")];
755
+ const elements = [...dom.querySelectorAll("[data-looma-footnote]")];
756
+ if (references.length !== numbering.references.length || elements.length !== numbering.notes.length) return dom;
757
+ references.forEach((link, index) => {
758
+ const { number, occurrence } = numbering.references[index];
759
+ const label = labelFrom(link.getAttribute("href"), "fn:");
760
+ if (number !== null) link.textContent = String(number);
761
+ link.id = `fnref:${label}${occurrence > 1 ? `:${occurrence}` : ""}`;
762
+ });
763
+ const document = dom.ownerDocument;
764
+ const items = [];
765
+ elements.forEach((element, index) => {
766
+ const { number, count } = numbering.notes[index];
767
+ const label = element.getAttribute("data-label") ?? "";
768
+ element.remove();
769
+ if (number === null) return;
770
+ const item = document.createElement("li");
771
+ item.id = `fn:${label}`;
772
+ item.append(...element.querySelector(":scope > li").childNodes);
773
+ appendBackLinks(item, label, number, count);
774
+ items.push({
775
+ number,
776
+ item
777
+ });
778
+ });
779
+ if (!items.length) return dom;
780
+ const section = document.createElement("section");
781
+ section.setAttribute("data-footnotes", "");
782
+ section.className = "footnotes";
783
+ section.append(Object.assign(document.createElement("h2"), {
784
+ id: "footnote:label",
785
+ className: "sr-only",
786
+ textContent: "Footnotes"
787
+ }));
788
+ section.append(document.createElement("ol"));
789
+ section.lastElementChild.append(...items.sort((a, b) => a.number - b.number).map(({ item }) => item));
790
+ dom.append(section);
791
+ return dom;
792
+ };
793
+ }
794
+ var known = /* @__PURE__ */ new WeakMap();
795
+ var knownNotes = (editor) => known.get(editor) ?? known.set(editor, /* @__PURE__ */ new Map()).get(editor);
746
796
  /**
747
- * The document's notes, saved as `<section data-footnotes>` with its `<ol>`.
748
- * @invariant It holds only footnotes and stays the document's last block, one section in number order.
749
- * @ownership It owns footnote numbering and the back-links in serialized HTML for the whole editor.
797
+ * One note, `[^label]: …`, where its definition is written. Saved HTML collects the notes into
798
+ * one `<section data-footnotes>` whose `<li id="fn:label">` items read back as notes.
799
+ * @invariant `number` is its place in the numbering, or null when nothing refers to it; `count` is
800
+ * how many references point to it. Its back-links are presentation: the editor reads past them and
801
+ * writes them only into saved HTML.
802
+ * @ownership It owns footnote numbering and the notes section in serialized HTML for the whole editor.
750
803
  */
751
- var LoomaFootnotes = Node$1.create({
752
- name: NOTES,
804
+ var LoomaFootnote = Node$1.create({
805
+ name: NOTE,
753
806
  group: "block",
754
- content: `${NOTE}+`,
755
- isolating: true,
807
+ content: "block+",
808
+ defining: true,
809
+ addAttributes() {
810
+ return {
811
+ label: {
812
+ default: "",
813
+ parseHTML: (element) => element.getAttribute("data-label") ?? labelFrom(`#${element.id}`, "fn:") ?? "",
814
+ renderHTML: () => ({})
815
+ },
816
+ number: {
817
+ default: null,
818
+ renderHTML: () => ({})
819
+ },
820
+ count: {
821
+ default: 1,
822
+ parseHTML: (element) => element.querySelectorAll("a[data-footnote-backref]").length || 1,
823
+ renderHTML: () => ({})
824
+ }
825
+ };
826
+ },
756
827
  parseHTML() {
757
- return [{
758
- tag: "section[data-footnotes]",
759
- contentElement: "ol"
760
- }];
828
+ return [
829
+ {
830
+ tag: "section[data-footnotes]",
831
+ priority: 1100,
832
+ skip: true
833
+ },
834
+ {
835
+ tag: "section[data-footnotes] > h2",
836
+ priority: 1100,
837
+ ignore: true
838
+ },
839
+ {
840
+ tag: "section[data-footnotes] > ol",
841
+ priority: 1100,
842
+ skip: true
843
+ },
844
+ {
845
+ tag: "section[data-footnotes] > ol > li",
846
+ priority: 1100
847
+ },
848
+ {
849
+ tag: ":is(ol, ul)[data-looma-footnote]",
850
+ priority: 1100,
851
+ contentElement: ":scope > li"
852
+ },
853
+ {
854
+ tag: "a[data-footnote-backref]",
855
+ priority: 1100,
856
+ ignore: true
857
+ }
858
+ ];
761
859
  },
762
- renderHTML() {
860
+ renderHTML({ node }) {
861
+ const { label, number } = node.attrs;
763
862
  return [
764
- "section",
863
+ number === null ? "ul" : "ol",
765
864
  {
766
- "data-footnotes": "",
767
- class: "footnotes"
865
+ "data-looma-footnote": "",
866
+ "data-label": label,
867
+ id: `fn:${label}`,
868
+ ...number === null ? {} : { start: number }
768
869
  },
769
- [
770
- "h2",
771
- {
772
- id: "footnote:label",
773
- class: "sr-only"
774
- },
775
- "Footnotes"
776
- ],
777
- ["ol", 0]
870
+ ["li", 0]
778
871
  ];
779
872
  },
780
873
  onBeforeCreate() {
781
874
  installSerializer(this.editor.schema);
782
875
  },
783
876
  onCreate() {
784
- const transaction = footnoteTransaction(this.editor.state, this.storage.known);
877
+ const transaction = footnoteTransaction(this.editor.state, null, knownNotes(this.editor));
785
878
  if (transaction) this.editor.view.dispatch(transaction.setMeta("addToHistory", false));
786
879
  },
787
- addStorage: () => ({ known: /* @__PURE__ */ new Map() }),
788
880
  addProseMirrorPlugins() {
789
881
  return [new Plugin({
790
- appendTransaction: (transactions, _oldState, state) => transactions.some((transaction) => transaction.docChanged) ? footnoteTransaction(state, this.storage.known) : null,
791
- props: { transformPasted: (slice) => {
792
- const kept = [];
793
- slice.content.forEach((node) => {
794
- if (node.type.name === NOTES) node.forEach((note) => {
795
- this.storage.known.set(note.attrs.label, note);
796
- });
797
- else kept.push(node);
798
- });
799
- if (!kept.length || kept.length === slice.content.childCount) return slice;
800
- const content = Fragment.from(kept);
801
- const open = Slice.maxOpen(content);
802
- return new Slice(content, kept[0] === slice.content.firstChild ? slice.openStart : open.openStart, kept.at(-1) === slice.content.lastChild ? slice.openEnd : open.openEnd);
803
- } }
882
+ appendTransaction: (transactions, oldState, state) => transactions.some((transaction) => transaction.docChanged) ? footnoteTransaction(state, oldState.doc, knownNotes(this.editor)) : null,
883
+ props: { transformPasted: (slice) => slice.openEnd && slice.content.lastChild?.type.name === NOTE ? new Slice(slice.content, slice.openStart, 0) : slice }
804
884
  })];
805
885
  },
806
886
  addCommands() {
@@ -826,10 +906,8 @@ var LoomaFootnotes = Node$1.create({
826
906
  occurrence
827
907
  });
828
908
  if (!findLoomaFootnote(tr.doc, name)) {
829
- const note = state.schema.nodes[NOTE].create({ label: name }, state.schema.nodes.paragraph.create());
830
- if (tr.doc.lastChild?.type.name === NOTES) tr.insert(tr.doc.content.size - 1, note);
831
- else tr.insert(tr.doc.content.size, state.schema.nodes[NOTES].create(null, note));
832
- tr.setSelection(TextSelection.create(tr.doc, tr.doc.content.size - 3));
909
+ tr.insert(tr.doc.content.size, state.schema.nodes[NOTE].create({ label: name }, state.schema.nodes.paragraph.create()));
910
+ tr.setSelection(TextSelection.create(tr.doc, tr.doc.content.size - 2));
833
911
  }
834
912
  tr.scrollIntoView();
835
913
  return true;
@@ -872,46 +950,56 @@ var LoomaFootnotes = Node$1.create({
872
950
  };
873
951
  }
874
952
  });
953
+ //#endregion
954
+ //#region src/editor/extensions/link-definition.ts
875
955
  /**
876
- * One note, `[^label]: …`, saved as `<li id="fn:label">`.
877
- * @invariant It exists only inside `LoomaFootnotes`. `count` is how many references point to it. Its
878
- * back-links are presentation: the editor reads past them and writes them only into saved HTML.
956
+ * A link reference definition, `[label]: url "title"`, where it is written. A link that uses one
957
+ * keeps its label as `reference` and its spelling (`full`, `collapsed` or `shortcut`) as
958
+ * `referenceType`, and is written as a reference while the definition still gives its destination
959
+ * and title.
960
+ * @invariant It renders nothing in the editor, as in Markdown; saved HTML keeps it as a hidden
961
+ * element so the document reads back whole.
879
962
  */
880
- var LoomaFootnote = Node$1.create({
881
- name: NOTE,
882
- content: "block+",
883
- defining: true,
963
+ var LoomaLinkDefinition = Node$1.create({
964
+ name: "loomaLinkDefinition",
965
+ group: "block",
966
+ atom: true,
884
967
  addAttributes() {
968
+ const data = (name) => ({
969
+ default: null,
970
+ parseHTML: (element) => element.getAttribute(`data-${name}`),
971
+ renderHTML: (attributes) => attributes[name] === null ? {} : { [`data-${name}`]: attributes[name] }
972
+ });
885
973
  return {
886
- label: {
887
- default: "",
888
- parseHTML: (element) => labelFrom(`#${element.id}`, "fn:") ?? "",
889
- renderHTML: () => ({})
890
- },
891
- count: {
892
- default: 1,
893
- parseHTML: (element) => element.querySelectorAll("a[data-footnote-backref]").length || 1,
894
- renderHTML: () => ({})
895
- }
974
+ label: data("label"),
975
+ href: data("href"),
976
+ title: data("title")
896
977
  };
897
978
  },
898
- parseHTML() {
979
+ addGlobalAttributes() {
980
+ const data = (name, attribute) => ({
981
+ default: null,
982
+ parseHTML: (element) => element.getAttribute(attribute),
983
+ renderHTML: (attributes) => attributes[name] ? { [attribute]: attributes[name] } : {}
984
+ });
899
985
  return [{
900
- tag: "li",
901
- priority: 1100,
902
- context: `${NOTES}/`
903
- }, {
904
- tag: "a[data-footnote-backref]",
905
- priority: 1100,
906
- ignore: true
986
+ types: ["link"],
987
+ attributes: {
988
+ title: data("title", "title"),
989
+ reference: data("reference", "data-reference"),
990
+ referenceType: data("referenceType", "data-reference-type")
991
+ }
907
992
  }];
908
993
  },
909
- renderHTML({ node }) {
910
- return [
911
- "li",
912
- { id: `fn:${node.attrs.label}` },
913
- 0
914
- ];
994
+ parseHTML() {
995
+ return [{ tag: "div[data-looma-link-definition]" }];
996
+ },
997
+ renderHTML({ HTMLAttributes }) {
998
+ return ["div", {
999
+ ...HTMLAttributes,
1000
+ "data-looma-link-definition": "",
1001
+ hidden: ""
1002
+ }];
915
1003
  }
916
1004
  });
917
1005
  //#endregion
@@ -2988,7 +3076,7 @@ function decodeTlds(encoded) {
2988
3076
  /**
2989
3077
  * @type Required<Opts>
2990
3078
  */
2991
- var defaults$1 = {
3079
+ var defaults = {
2992
3080
  defaultProtocol: "http",
2993
3081
  events: null,
2994
3082
  format: noop,
@@ -3015,7 +3103,7 @@ var defaults$1 = {
3015
3103
  * Similar to render option
3016
3104
  */
3017
3105
  function Options(opts, defaultRender = null) {
3018
- let o = Object.assign({}, defaults$1);
3106
+ let o = Object.assign({}, defaults);
3019
3107
  if (opts) o = Object.assign(o, opts instanceof Options ? opts.o : opts);
3020
3108
  const ignoredTags = o.ignoreTags;
3021
3109
  const uppercaseIgnoredTags = [];
@@ -3026,7 +3114,7 @@ function Options(opts, defaultRender = null) {
3026
3114
  this.ignoreTags = uppercaseIgnoredTags;
3027
3115
  }
3028
3116
  Options.prototype = {
3029
- o: defaults$1,
3117
+ o: defaults,
3030
3118
  /**
3031
3119
  * @type string[]
3032
3120
  */
@@ -3063,7 +3151,7 @@ Options.prototype = {
3063
3151
  let option = this.o[key];
3064
3152
  if (!option) return option;
3065
3153
  if (typeof option === "object") {
3066
- option = token.t in option ? option[token.t] : defaults$1[key];
3154
+ option = token.t in option ? option[token.t] : defaults[key];
3067
3155
  if (typeof option === "function" && isCallable) option = option(operator, token);
3068
3156
  } else if (typeof option === "function" && isCallable) option = option(operator, token.t, token);
3069
3157
  return option;
@@ -3181,7 +3269,7 @@ MultiToken.prototype = {
3181
3269
  @method toObject
3182
3270
  @param {string} [protocol] `'http'` by default
3183
3271
  */
3184
- toObject(protocol = defaults$1.defaultProtocol) {
3272
+ toObject(protocol = defaults.defaultProtocol) {
3185
3273
  return {
3186
3274
  type: this.t,
3187
3275
  value: this.toString(),
@@ -3290,7 +3378,7 @@ var Url = createTokenClass("url", {
3290
3378
  @param {string} [scheme] default scheme (e.g., 'https')
3291
3379
  @return {string} the full href
3292
3380
  */
3293
- toHref(scheme = defaults$1.defaultProtocol) {
3381
+ toHref(scheme = defaults.defaultProtocol) {
3294
3382
  return this.hasProtocol() ? this.v : `${scheme}://${this.v}`;
3295
3383
  },
3296
3384
  /**
@@ -9872,839 +9960,6 @@ function createDOMPurify() {
9872
9960
  }
9873
9961
  var purify = createDOMPurify();
9874
9962
  //#endregion
9875
- //#region src/markdown/markdown-it.ts
9876
- var CONTAINER_OPEN = /^(:{3,})[ \t]*([A-Za-z][\w-]*)(?:[ \t]+(.*?))?[ \t]*$/;
9877
- var CONTAINER_CLOSE = /^:{3,}[ \t]*$/;
9878
- var FENCE_OPEN = /^(`{3,}|~{3,})/;
9879
- var TAB_LABEL = /^==[ \t]+(\S.*?)[ \t]*$/;
9880
- var OPEN_FLAG = /[ \t]*\{open\}$/;
9881
- var ALERT = /^\[!(NOTE|TIP|IMPORTANT|WARNING|CAUTION)\][ \t]*(?:\n|$)/i;
9882
- var LEAF = /^::([A-Za-z][\w-]*)(\{.*\})?[ \t]*$/;
9883
- var TASK = /^\[([ xX])\](?:[ \t]+|$)/;
9884
- var TOC_FORMATS = /* @__PURE__ */ new Set([
9885
- "plain",
9886
- "bulleted",
9887
- "numbered"
9888
- ]);
9889
- var PLACEMENTS = /* @__PURE__ */ new Set([
9890
- "block",
9891
- "center",
9892
- "wrap-left",
9893
- "wrap-right"
9894
- ]);
9895
- var opensContainer = (text) => {
9896
- const match = CONTAINER_OPEN.exec(text);
9897
- return match && LOOMA_CONTAINER_NAMES.has(match[2].toLowerCase()) ? match : null;
9898
- };
9899
- function lineText(state, line) {
9900
- return state.src.slice(state.bMarks[line] + state.tShift[line], state.eMarks[line]);
9901
- }
9902
- function frontmatter(state, startLine, _endLine, silent) {
9903
- if (startLine !== 0 || state.blkIndent !== 0) return false;
9904
- const split = splitLoomaFrontmatter(state.src);
9905
- if (!split) return false;
9906
- if (silent) return true;
9907
- const lines = split.source.split("\n").length;
9908
- const token = state.push("looma_frontmatter", "", 0);
9909
- Object.assign(token, {
9910
- content: split.yaml,
9911
- block: true,
9912
- hidden: true,
9913
- map: [0, lines]
9914
- });
9915
- state.env.frontmatter = split.yaml;
9916
- state.line = lines;
9917
- return true;
9918
- }
9919
- function container(state, startLine, endLine, silent) {
9920
- if (state.sCount[startLine] - state.blkIndent >= 4) return false;
9921
- const match = opensContainer(lineText(state, startLine));
9922
- if (!match) return false;
9923
- if (silent) return true;
9924
- const name = match[2].toLowerCase();
9925
- const grouped = name === "tabs" || name === "code-group";
9926
- const labels = [];
9927
- let depth = 1;
9928
- let fence = null;
9929
- let next = startLine + 1;
9930
- for (; next < endLine; next++) {
9931
- const text = lineText(state, next);
9932
- if (text && state.sCount[next] < state.blkIndent) break;
9933
- if (fence) {
9934
- const close = FENCE_OPEN.exec(text);
9935
- if (close && close[1][0] === fence.char && close[1].length >= fence.length && !text.slice(close[1].length).trim()) fence = null;
9936
- continue;
9937
- }
9938
- const opener = FENCE_OPEN.exec(text);
9939
- if (opener) {
9940
- fence = {
9941
- char: opener[1][0],
9942
- length: opener[1].length
9943
- };
9944
- continue;
9945
- }
9946
- if (CONTAINER_CLOSE.test(text)) {
9947
- if (--depth === 0) break;
9948
- } else if (opensContainer(text)) depth++;
9949
- else if (grouped && depth === 1) {
9950
- const label = TAB_LABEL.exec(text);
9951
- if (label) labels.push({
9952
- line: next,
9953
- label: label[1]
9954
- });
9955
- }
9956
- }
9957
- let title = (match[3] ?? "").trim();
9958
- const open = name === "details" && OPEN_FLAG.test(title);
9959
- if (name === "details") title = title.replace(OPEN_FLAG, "");
9960
- const parentType = state.parentType;
9961
- const lineMax = state.lineMax;
9962
- state.parentType = "container";
9963
- state.lineMax = next;
9964
- const opening = state.push("looma_container_open", "div", 1);
9965
- Object.assign(opening, {
9966
- info: name,
9967
- meta: {
9968
- title,
9969
- open
9970
- },
9971
- block: true,
9972
- map: [startLine, next],
9973
- markup: match[1]
9974
- });
9975
- const panel = (label, from, to) => {
9976
- state.push("looma_tab_open", "section", 1).meta = { label };
9977
- state.md.block.tokenize(state, from, to);
9978
- state.push("looma_tab_close", "section", -1);
9979
- };
9980
- if (labels.length) {
9981
- state.md.block.tokenize(state, startLine + 1, labels[0].line);
9982
- labels.forEach(({ line, label }, index) => panel(label, line + 1, labels[index + 1]?.line ?? next));
9983
- } else {
9984
- const first = state.tokens.length;
9985
- state.md.block.tokenize(state, startLine + 1, next);
9986
- if (name === "code-group") for (let index = state.tokens.length - 1; index >= first; index--) {
9987
- const token = state.tokens[index];
9988
- if (token.type !== "fence" || token.level !== opening.level + 1) continue;
9989
- const { title: fenceTitle, language } = parseLoomaFenceInfo(token.info);
9990
- const tabOpen = new state.Token("looma_tab_open", "section", 1);
9991
- tabOpen.meta = { label: fenceTitle ?? language ?? "Code" };
9992
- state.tokens.splice(index, 1, tabOpen, token, new state.Token("looma_tab_close", "section", -1));
9993
- }
9994
- }
9995
- const closing = state.push("looma_container_close", "div", -1);
9996
- Object.assign(closing, {
9997
- info: name,
9998
- meta: { title },
9999
- block: true,
10000
- markup: match[1]
10001
- });
10002
- state.parentType = parentType;
10003
- state.lineMax = lineMax;
10004
- state.line = Math.min(next + 1, endLine);
10005
- return true;
10006
- }
10007
- function leaf(state, startLine, _endLine, silent) {
10008
- if (state.sCount[startLine] - state.blkIndent >= 4) return false;
10009
- const match = LEAF.exec(lineText(state, startLine));
10010
- if (!match || match[1].toLowerCase() !== "toc") return false;
10011
- const attributes = match[2] ? parseLoomaAttributes(match[2]) : {};
10012
- if (!attributes) return false;
10013
- if (silent) return true;
10014
- const format = typeof attributes.format === "string" && TOC_FORMATS.has(attributes.format) ? attributes.format : "plain";
10015
- const depth = attributes.depth === "1" || attributes.depth === "2" ? Number(attributes.depth) : 3;
10016
- const token = state.push("looma_toc", "nav", 0);
10017
- Object.assign(token, {
10018
- block: true,
10019
- map: [startLine, startLine + 1],
10020
- meta: {
10021
- format,
10022
- depth
10023
- }
10024
- });
10025
- state.line = startLine + 1;
10026
- return true;
10027
- }
10028
- function alerts(state) {
10029
- const tokens = state.tokens;
10030
- for (let index = 0; index < tokens.length; index++) {
10031
- if (tokens[index].type !== "blockquote_open" || tokens[index + 1]?.type !== "paragraph_open") continue;
10032
- const inline = tokens[index + 2];
10033
- const match = inline?.type === "inline" ? ALERT.exec(inline.content) : null;
10034
- if (!match) continue;
10035
- inline.content = inline.content.slice(match[0].length);
10036
- if (!inline.content.trim()) tokens.splice(index + 1, 3);
10037
- tokens[index].tag = "ui-callout";
10038
- tokens[index].attrSet("tone", normalizeLoomaCalloutTone(match[1]));
10039
- for (let depth = 0, end = index; end < tokens.length; end++) if (tokens[end].type === "blockquote_open") depth++;
10040
- else if (tokens[end].type === "blockquote_close" && --depth === 0) {
10041
- tokens[end].tag = "ui-callout";
10042
- break;
10043
- }
10044
- }
10045
- }
10046
- function taskLists(state) {
10047
- const tokens = state.tokens;
10048
- for (let index = 0; index < tokens.length; index++) {
10049
- if (tokens[index].type !== "bullet_list_open") continue;
10050
- const level = tokens[index].level;
10051
- const items = [];
10052
- let isTaskList = true;
10053
- for (let cursor = index + 1; cursor < tokens.length; cursor++) {
10054
- const token = tokens[cursor];
10055
- if (token.type === "bullet_list_close" && token.level === level) break;
10056
- if (token.type !== "list_item_open" || token.level !== level + 1) continue;
10057
- const inline = tokens[cursor + 2];
10058
- const match = tokens[cursor + 1]?.type === "paragraph_open" && inline?.type === "inline" ? TASK.exec(inline.content) : null;
10059
- if (!match) {
10060
- isTaskList = false;
10061
- break;
10062
- }
10063
- items.push({
10064
- item: token,
10065
- inline,
10066
- checked: match[1] !== " "
10067
- });
10068
- }
10069
- if (!isTaskList || !items.length) continue;
10070
- tokens[index].attrSet("data-type", "taskList");
10071
- for (const { item, inline, checked } of items) {
10072
- inline.content = inline.content.replace(TASK, "");
10073
- item.attrSet("data-type", "taskItem");
10074
- item.attrSet("data-checked", String(checked));
10075
- inline.meta = {
10076
- ...inline.meta,
10077
- task: checked
10078
- };
10079
- }
10080
- }
10081
- }
10082
- function directive(state, silent) {
10083
- const { src, pos } = state;
10084
- if (src.charCodeAt(pos) !== 58) return false;
10085
- const name = /^:(chip)\[/.exec(src.slice(pos, pos + 10))?.[1];
10086
- if (!name) return false;
10087
- let label = "";
10088
- let index = pos + name.length + 2;
10089
- for (; index < state.posMax && src[index] !== "]"; index++) {
10090
- if (src[index] === "\\" && index + 1 < state.posMax) index++;
10091
- label += src[index];
10092
- }
10093
- if (src[index] !== "]") return false;
10094
- const read = src[index + 1] === "{" ? readLoomaAttributes(src, index + 1) : {
10095
- attributes: {},
10096
- end: index + 1
10097
- };
10098
- if (!read || read.end > state.posMax) return false;
10099
- if (!silent) {
10100
- const token = state.push(`looma_${name}`, "span", 0);
10101
- token.meta = {
10102
- label,
10103
- attributes: read.attributes
10104
- };
10105
- }
10106
- state.pos = read.end;
10107
- return true;
10108
- }
10109
- function mention(state, silent) {
10110
- const { src, pos } = state;
10111
- if (src.charCodeAt(pos) !== 64 || pos > 0 && !/\s/u.test(src[pos - 1])) return false;
10112
- let index = pos + 1;
10113
- let label = "";
10114
- if (src[index] === "[") {
10115
- for (index++; index < state.posMax && src[index] !== "]"; index++) {
10116
- if (src[index] === "\\" && index + 1 < state.posMax) index++;
10117
- label += src[index];
10118
- }
10119
- if (src[index] !== "]" || !label) return false;
10120
- index++;
10121
- } else {
10122
- label = LOOMA_MENTION_HANDLE.exec(src.slice(index, state.posMax))?.[0] ?? "";
10123
- if (!label) return false;
10124
- index += label.length;
10125
- }
10126
- let ref = src[index] === "#" ? LOOMA_MENTION_HANDLE.exec(src.slice(index + 1, state.posMax))?.[0] : void 0;
10127
- if (ref) index += ref.length + 1;
10128
- const read = src[index] === "{" ? readLoomaAttributes(src, index) : null;
10129
- if (read && read.end <= state.posMax) {
10130
- if (typeof read.attributes.ref === "string") ref ??= read.attributes.ref;
10131
- index = read.end;
10132
- }
10133
- if (!silent) state.push("looma_mention", "span", 0).meta = {
10134
- label,
10135
- ref
10136
- };
10137
- state.pos = index;
10138
- return true;
10139
- }
10140
- function inlineText(token) {
10141
- return (token?.children ?? []).map((child) => child.type === "image" ? inlineText(child) : child.content).join("");
10142
- }
10143
- function attributes(state) {
10144
- const headings = [];
10145
- const tokens = state.tokens;
10146
- for (let index = 0; index < tokens.length; index++) {
10147
- const token = tokens[index];
10148
- if (token.type !== "inline" || !token.children) continue;
10149
- const children = token.children;
10150
- if (typeof token.meta?.task === "boolean") {
10151
- const html = (content) => Object.assign(new state.Token("html_inline", "", 0), { content });
10152
- children.unshift(html(`<label><input type="checkbox" disabled=""${token.meta.task ? " checked=\"\"" : ""}> `));
10153
- children.push(html("</label>"));
10154
- }
10155
- for (let child = children.length - 3; child >= 0; child--) {
10156
- const text = children[child + 1];
10157
- if (children[child].type !== "link_open" || children[child].markup !== "linkify" || /^(?:[a-z][\w+.-]*:|www\.)/i.test(text.content)) continue;
10158
- children.splice(child, 3, Object.assign(new state.Token("text", "", 0), { content: text.content }));
10159
- }
10160
- if (tokens[index - 1]?.type === "heading_open") {
10161
- const last = children.at(-1);
10162
- const marker = last?.type === "text" ? /[ \t]+(\{[^{}]*\})$/.exec(last.content) : null;
10163
- const parsed = marker && parseLoomaAttributes(marker[1]);
10164
- let id;
10165
- if (last && marker && parsed && typeof parsed.id === "string") {
10166
- id = parsed.id;
10167
- last.content = last.content.slice(0, marker.index);
10168
- }
10169
- headings.push({
10170
- open: tokens[index - 1],
10171
- text: inlineText(token).trim(),
10172
- id
10173
- });
10174
- }
10175
- for (let child = 0; child < children.length; child++) {
10176
- const next = children[child + 1];
10177
- if (children[child].type !== "image" || next?.type !== "text" || !next.content.startsWith("{")) continue;
10178
- const read = readLoomaAttributes(next.content);
10179
- if (!read) continue;
10180
- applyImageAttributes(children[child], read.attributes);
10181
- next.content = next.content.slice(read.end);
10182
- if (!next.content) children.splice(child + 1, 1);
10183
- }
10184
- if (tokens[index - 1]?.type === "paragraph_open" && children.length === 1 && children[0].type === "image") {
10185
- tokens[index - 1].hidden = true;
10186
- tokens[index + 1].hidden = true;
10187
- }
10188
- }
10189
- const ids = assignLoomaHeadingIds(headings);
10190
- headings.forEach(({ open }, index) => open.attrSet("id", ids[index]));
10191
- }
10192
- function applyImageAttributes(image, attributes) {
10193
- for (const key of ["width", "height"]) {
10194
- const value = Number(attributes[key]);
10195
- if (Number.isSafeInteger(value) && value > 0) image.attrSet(key, String(value));
10196
- }
10197
- const placement = attributes.placement;
10198
- if (typeof placement === "string" && PLACEMENTS.has(placement) && placement !== "block") image.attrSet("data-placement", placement);
10199
- if (attributes.responsive === true) image.attrSet("data-looma-responsive", "");
10200
- }
10201
- var FOOTNOTE_DEFINITION = /^\[\^([^\s\]]+)\]:/;
10202
- var FOOTNOTE_REFERENCE = /^\[\^([^\s\]]+)\]/;
10203
- function footnoteDefinition(state, startLine, endLine, silent) {
10204
- if (state.sCount[startLine] - state.blkIndent >= 4) return false;
10205
- const start = state.bMarks[startLine] + state.tShift[startLine];
10206
- const match = FOOTNOTE_DEFINITION.exec(state.src.slice(start, state.eMarks[startLine]));
10207
- if (!match) return false;
10208
- if (silent) return true;
10209
- (state.env.footnotes ??= /* @__PURE__ */ new Set()).add(match[1]);
10210
- const open = state.push("looma_footnote_open", "li", 1);
10211
- Object.assign(open, {
10212
- meta: { label: match[1] },
10213
- block: true,
10214
- map: [startLine, startLine]
10215
- });
10216
- const saved = {
10217
- bMark: state.bMarks[startLine],
10218
- tShift: state.tShift[startLine],
10219
- sCount: state.sCount[startLine],
10220
- parentType: state.parentType
10221
- };
10222
- let position = start + match[0].length;
10223
- const contentStart = position;
10224
- let offset = state.sCount[startLine] + match[0].length;
10225
- const initial = offset;
10226
- while (position < state.eMarks[startLine] && (state.src[position] === " " || state.src[position] === " ")) {
10227
- offset += state.src[position] === " " ? 4 - (offset + state.bsCount[startLine]) % 4 : 1;
10228
- position++;
10229
- }
10230
- state.tShift[startLine] = position - contentStart;
10231
- state.sCount[startLine] = offset - initial;
10232
- state.bMarks[startLine] = contentStart;
10233
- state.blkIndent += 4;
10234
- state.parentType = "footnote";
10235
- if (state.sCount[startLine] < state.blkIndent) state.sCount[startLine] += state.blkIndent;
10236
- state.md.block.tokenize(state, startLine, endLine);
10237
- state.parentType = saved.parentType;
10238
- state.blkIndent -= 4;
10239
- state.tShift[startLine] = saved.tShift;
10240
- state.sCount[startLine] = saved.sCount;
10241
- state.bMarks[startLine] = saved.bMark;
10242
- open.map[1] = state.line;
10243
- state.push("looma_footnote_close", "li", -1).block = true;
10244
- return true;
10245
- }
10246
- function footnoteReference(state, silent) {
10247
- if (state.src.charCodeAt(state.pos) !== 91 || state.src.charCodeAt(state.pos + 1) !== 94) return false;
10248
- const match = FOOTNOTE_REFERENCE.exec(state.src.slice(state.pos, state.posMax));
10249
- if (!match || !state.env.footnotes?.has(match[1])) return false;
10250
- if (!silent) state.push("looma_footnote_ref", "sup", 0).meta = { label: match[1] };
10251
- state.pos += match[0].length;
10252
- return true;
10253
- }
10254
- function footnotes(state) {
10255
- const definitions = /* @__PURE__ */ new Map();
10256
- const body = [];
10257
- for (let index = 0; index < state.tokens.length; index++) {
10258
- const token = state.tokens[index];
10259
- if (token.type !== "looma_footnote_open") {
10260
- body.push(token);
10261
- continue;
10262
- }
10263
- let depth = 0, end = index;
10264
- for (; end < state.tokens.length; end++) if (state.tokens[end].type === "looma_footnote_open") depth++;
10265
- else if (state.tokens[end].type === "looma_footnote_close" && --depth === 0) break;
10266
- const label = token.meta.label;
10267
- if (!definitions.has(label)) definitions.set(label, state.tokens.slice(index, end + 1));
10268
- index = end;
10269
- }
10270
- if (!definitions.size) return;
10271
- const order = [];
10272
- const counts = /* @__PURE__ */ new Map();
10273
- const number = (tokens) => {
10274
- for (const token of tokens) for (const child of token.children ?? []) {
10275
- if (child.type !== "looma_footnote_ref") continue;
10276
- const label = child.meta.label;
10277
- if (!counts.has(label)) order.push(label);
10278
- const occurrence = (counts.get(label) ?? 0) + 1;
10279
- counts.set(label, occurrence);
10280
- child.meta = {
10281
- label,
10282
- number: order.indexOf(label) + 1,
10283
- occurrence
10284
- };
10285
- }
10286
- };
10287
- number(body);
10288
- const notes = [];
10289
- for (let index = 0; index < order.length; index++) {
10290
- const label = order[index];
10291
- const tokens = definitions.get(label);
10292
- number(tokens);
10293
- const backrefs = Object.assign(new state.Token("looma_footnote_backrefs", "", 0), { meta: {
10294
- label,
10295
- number: index + 1
10296
- } });
10297
- const last = tokens.length - 2;
10298
- if (tokens[last].type === "paragraph_close") tokens.splice(last, 0, backrefs);
10299
- else tokens.splice(last + 1, 0, new state.Token("paragraph_open", "p", 1), backrefs, new state.Token("paragraph_close", "p", -1));
10300
- notes.push(...tokens);
10301
- }
10302
- if (!notes.length) {
10303
- state.tokens = body;
10304
- return;
10305
- }
10306
- for (const note of notes) if (note.type === "looma_footnote_open") note.meta.count = counts.get(note.meta.label);
10307
- state.tokens = [
10308
- ...body,
10309
- Object.assign(new state.Token("looma_footnotes_open", "section", 1), { block: true }),
10310
- ...notes,
10311
- Object.assign(new state.Token("looma_footnotes_close", "section", -1), { block: true })
10312
- ];
10313
- }
10314
- function tableOfContents(tokens, format, depth, escape) {
10315
- const roots = [];
10316
- const ancestors = [];
10317
- tokens.forEach((token, index) => {
10318
- if (token.type !== "heading_open") return;
10319
- const level = Number(token.tag.slice(1));
10320
- const text = inlineText(tokens[index + 1]).trim();
10321
- if (level > depth || !text) return;
10322
- while (ancestors.length && ancestors[ancestors.length - 1].level >= level) ancestors.pop();
10323
- const entry = {
10324
- id: token.attrGet("id") ?? "",
10325
- text,
10326
- children: []
10327
- };
10328
- (ancestors.at(-1)?.entry.children ?? roots).push(entry);
10329
- ancestors.push({
10330
- level,
10331
- entry
10332
- });
10333
- });
10334
- const [list, item] = format === "plain" ? ["div", "div"] : [format === "numbered" ? "ol" : "ul", "li"];
10335
- const render = (entries) => `<${list} role="list">${entries.map(({ id, text, children }) => `<${item} role="listitem"><a href="#${escape(id)}">${escape(text)}</a>${children.length ? render(children) : ""}</${item}>`).join("")}</${list}>`;
10336
- return `<nav data-looma-toc="" data-format="${format}" data-depth="${depth}" aria-label="Table of contents"><strong>Table of contents</strong>${roots.length ? render(roots) : ""}</nav>\n`;
10337
- }
10338
- /**
10339
- * Adds Looma Markdown to a markdown-it instance: containers, alerts, task lists, footnotes, the table of
10340
- * contents, chips, mentions, brace attributes, heading anchors, code meta and front matter.
10341
- * @contract Renders the canonical HTML, which is the HTML LoomaEditor saves. It is not sanitized.
10342
- * Linkify and raw HTML are instance options; `createLoomaMarkdownIt` turns both on.
10343
- */
10344
- function loomaMarkdown$1(md, { codeNotation = "apply" } = {}) {
10345
- const escape = md.utils.escapeHtml;
10346
- md.block.ruler.before("table", "looma_frontmatter", frontmatter);
10347
- md.block.ruler.before("reference", "looma_footnote", footnoteDefinition, { alt: ["paragraph", "reference"] });
10348
- md.block.ruler.before("fence", "looma_container", container, { alt: [
10349
- "paragraph",
10350
- "reference",
10351
- "blockquote",
10352
- "list"
10353
- ] });
10354
- md.block.ruler.before("paragraph", "looma_leaf", leaf, { alt: [
10355
- "paragraph",
10356
- "reference",
10357
- "blockquote",
10358
- "list"
10359
- ] });
10360
- md.inline.ruler.before("link", "looma_directive", directive);
10361
- md.inline.ruler.before("link", "looma_mention", mention);
10362
- md.inline.ruler.before("link", "looma_footnote_ref", footnoteReference);
10363
- md.core.ruler.after("block", "looma_task_lists", taskLists);
10364
- md.core.ruler.before("inline", "looma_alerts", alerts);
10365
- md.core.ruler.before("text_join", "looma_attributes", attributes);
10366
- md.core.ruler.after("inline", "looma_footnotes", footnotes);
10367
- const rules = md.renderer.rules;
10368
- rules.looma_frontmatter = () => "";
10369
- rules.looma_container_open = (tokens, index) => {
10370
- const { info, meta } = tokens[index];
10371
- if (info === "details") return `<details${meta.open ? " open" : ""}><summary>${escape(meta.title || "Details")}</summary>\n`;
10372
- if (info === "figure") return "<figure>\n";
10373
- if (info === "tabs" || info === "code-group") return `<ui-tabs${info === "code-group" ? " class=\"code-group\"" : ""} group="${escape(meta.title || info)}">\n`;
10374
- return `<ui-callout tone="${normalizeLoomaCalloutTone(info)}"${meta.title ? ` heading="${escape(meta.title)}"` : ""}>\n`;
10375
- };
10376
- rules.looma_container_close = (tokens, index, _options, env) => {
10377
- const { info } = tokens[index];
10378
- if (info === "details") return "</details>\n";
10379
- if (info === "figure") {
10380
- const title = tokens[index].meta.title;
10381
- return `${title ? `<figcaption>${md.renderInline(title, env)}</figcaption>\n` : ""}</figure>\n`;
10382
- }
10383
- if (info === "tabs" || info === "code-group") return "</ui-tabs>\n";
10384
- return "</ui-callout>\n";
10385
- };
10386
- rules.looma_tab_open = (tokens, index) => `<section aria-label="${escape(tokens[index].meta.label)}">\n`;
10387
- rules.looma_tab_close = () => "</section>\n";
10388
- rules.looma_footnote_ref = (tokens, index) => {
10389
- const { label, number, occurrence } = tokens[index].meta;
10390
- return `<sup><a href="#fn:${escape(label)}" id="fnref:${escape(label)}${occurrence > 1 ? `:${occurrence}` : ""}" data-footnote-ref="" aria-describedby="footnote:label">${number}</a></sup>`;
10391
- };
10392
- rules.looma_footnote_backrefs = (tokens, index) => {
10393
- const { label, number } = tokens[index].meta;
10394
- const count = tokens.find((token) => token.type === "looma_footnote_open" && token.meta.label === label)?.meta.count ?? 1;
10395
- return Array.from({ length: count }, (_, occurrence) => {
10396
- const suffix = occurrence ? `:${occurrence + 1}` : "";
10397
- return ` <a href="#fnref:${escape(label)}${suffix}" data-footnote-backref="" aria-label="Back to reference ${number}${occurrence ? `-${occurrence + 1}` : ""}">↩${occurrence ? `<sup>${occurrence + 1}</sup>` : ""}</a>`;
10398
- }).join("");
10399
- };
10400
- rules.looma_footnotes_open = () => "<section data-footnotes=\"\" class=\"footnotes\">\n<h2 id=\"footnote:label\" class=\"sr-only\">Footnotes</h2>\n<ol>\n";
10401
- rules.looma_footnotes_close = () => "</ol>\n</section>\n";
10402
- rules.looma_footnote_open = (tokens, index) => `<li id="fn:${escape(tokens[index].meta.label)}">\n`;
10403
- rules.looma_footnote_close = () => "</li>\n";
10404
- rules.looma_toc = (tokens, index) => tableOfContents(tokens, tokens[index].meta.format, tokens[index].meta.depth, escape);
10405
- rules.looma_chip = (tokens, index) => {
10406
- const { label, attributes } = tokens[index].meta;
10407
- const tone = normalizeLoomaChipTone(attributes.tone);
10408
- return `<span data-looma-chip="" data-label="${escape(label)}" data-color="${tone}"${label ? "" : " data-placeholder=\"\""}>${escape(label)}</span>`;
10409
- };
10410
- rules.looma_mention = (tokens, index) => {
10411
- const { label, ref } = tokens[index].meta;
10412
- return `<span data-type="mention" class="looma-mention"${ref === void 0 ? "" : ` data-id="${escape(ref)}"`} data-label="${escape(label)}">@${escape(label)}</span>`;
10413
- };
10414
- const code = (content, info) => {
10415
- const { language, meta } = parseLoomaFenceInfo(info);
10416
- const source = content.replace(/\n$/, "");
10417
- return `<pre><code${language ? ` class="language-${escape(language)}"` : ""}${meta ? ` data-meta="${escape(meta)}"` : ""}>${escape(codeNotation === "keep" ? source : applyLoomaCodeNotation(source).code)}</code></pre>\n`;
10418
- };
10419
- rules.fence = (tokens, index) => code(tokens[index].content, tokens[index].info);
10420
- rules.code_block = (tokens, index) => code(tokens[index].content, "");
10421
- }
10422
- /**
10423
- * A markdown-it instance for Looma Markdown: raw HTML and GFM autolinks on, with `loomaMarkdown`.
10424
- * @contract Each call returns a new instance that callers may extend.
10425
- */
10426
- function createLoomaMarkdownIt(options = {}) {
10427
- return new MarkdownIt({
10428
- html: true,
10429
- linkify: true,
10430
- typographer: false
10431
- }).use(loomaMarkdown$1, options);
10432
- }
10433
- //#endregion
10434
- //#region src/editor/extensions/markdown.ts
10435
- /** The markdown-it instance LoomaEditor reads Looma Markdown with; code keeps its notation as source. */
10436
- var loomaMarkdown = createLoomaMarkdownIt({ codeNotation: "keep" });
10437
- /**
10438
- * Renders Looma Markdown as the HTML the editor parses.
10439
- * @contract The result is not sanitized; pass it to the editor's `setContent`, whose schema
10440
- * keeps only content it knows. Front matter renders nothing.
10441
- */
10442
- function loomaMarkdownToHtml(source) {
10443
- return loomaMarkdown.render(source);
10444
- }
10445
- var CONTAINERS = /* @__PURE__ */ new Set([
10446
- "loomaCallout",
10447
- "loomaExpand",
10448
- "loomaFigure",
10449
- "loomaTabs"
10450
- ]);
10451
- var containerDepth = (node) => {
10452
- let depth = 0;
10453
- node.descendants((child) => {
10454
- if (!CONTAINERS.has(child.type.name)) return true;
10455
- depth = Math.max(depth, 1 + containerDepth(child));
10456
- return false;
10457
- });
10458
- return depth;
10459
- };
10460
- var endLine = (state) => state.flushClose(1);
10461
- function writeContainer(state, node, opening, content = () => state.renderContent(node)) {
10462
- const marker = loomaContainerMarker(containerDepth(node));
10463
- state.write(`${marker} ${opening}`.trimEnd());
10464
- state.ensureNewLine();
10465
- content();
10466
- endLine(state);
10467
- state.write(marker);
10468
- state.closeBlock(node);
10469
- }
10470
- var defaults = defaultMarkdownSerializer.nodes;
10471
- var label = (text) => text.replace(/[\\\]]/g, "\\$&");
10472
- var ALIGNMENT = {
10473
- left: ":---",
10474
- center: ":---:",
10475
- right: "---:"
10476
- };
10477
- var NODES = {
10478
- paragraph: defaults.paragraph,
10479
- text: (state, node, parent, index) => {
10480
- const marker = /^:{3,}[ \t]*([A-Za-z][\w-]*)?/.exec(node.text ?? "");
10481
- if ((marker ? !marker[1] || LOOMA_CONTAINER_NAMES.has(marker[1].toLowerCase()) : /^::toc(?![\w-])/i.test(node.text ?? "")) && state.atBlank()) state.write("\\");
10482
- defaults.text(state, node, parent, index);
10483
- },
10484
- blockquote: defaults.blockquote,
10485
- horizontalRule: defaults.horizontal_rule,
10486
- bulletList: (state, node) => state.renderList(node, " ", () => "- "),
10487
- orderedList: (state, node) => {
10488
- const start = Number(node.attrs.start ?? 1);
10489
- state.renderList(node, " ", (index) => `${start + index}. `);
10490
- },
10491
- listItem: defaults.list_item,
10492
- taskList: (state, node) => state.renderList(node, " ", () => "- "),
10493
- taskItem: (state, node) => {
10494
- state.write(node.attrs.checked ? "[x] " : "[ ] ");
10495
- state.renderContent(node);
10496
- },
10497
- hardBreak: defaults.hard_break,
10498
- codeBlock: (state, node) => {
10499
- const fence = loomaCodeFence(node.textContent);
10500
- state.write(`${fence}${node.attrs.language ?? ""}${node.attrs.meta ? ` ${node.attrs.meta}` : ""}\n`);
10501
- state.text(node.textContent, false);
10502
- state.ensureNewLine();
10503
- state.write(fence);
10504
- state.closeBlock(node);
10505
- },
10506
- image: (state, node, parent, index) => {
10507
- defaults.image(state, node, parent, index);
10508
- const { width, height, placement, responsive } = node.attrs;
10509
- state.write(formatLoomaAttributes({
10510
- width,
10511
- height,
10512
- placement: placement && placement !== "block" ? placement : null,
10513
- responsive: responsive === true
10514
- }));
10515
- if (node.isBlock) state.closeBlock(node);
10516
- },
10517
- loomaCallout: (state, node) => writeContainer(state, node, `${node.attrs.tone} ${node.attrs.heading ?? ""}`),
10518
- loomaExpand: (state, node) => writeContainer(state, node, `details ${node.attrs.summary}${node.attrs.open ? " {open}" : ""}`),
10519
- loomaFigure: (state, node) => {
10520
- const caption = node.lastChild;
10521
- const marker = loomaContainerMarker(containerDepth(node));
10522
- state.write(`${marker} figure`);
10523
- if (caption.content.size) {
10524
- state.write(" ");
10525
- state.renderInline(caption, false);
10526
- }
10527
- state.ensureNewLine();
10528
- state.render(node.firstChild, node, 0);
10529
- endLine(state);
10530
- state.write(marker);
10531
- state.closeBlock(node);
10532
- },
10533
- loomaFigcaption: (state, node) => state.renderInline(node),
10534
- loomaTabs: (state, node) => {
10535
- const name = node.attrs.codeGroup ? "code-group" : "tabs";
10536
- const bare = node.attrs.codeGroup && Array.from({ length: node.childCount }, (_, index) => node.child(index)).every((tab) => {
10537
- const code = tab.firstChild;
10538
- if (tab.childCount !== 1 || code?.type.name !== "codeBlock") return false;
10539
- const { title, language } = parseLoomaFenceInfo(`${code.attrs.language ?? ""} ${code.attrs.meta ?? ""}`);
10540
- return tab.attrs.label === (title ?? language ?? "Code");
10541
- });
10542
- writeContainer(state, node, `${name} ${node.attrs.group && node.attrs.group !== name ? node.attrs.group : ""}`, () => node.forEach((tab, _offset, index) => {
10543
- if (index) endLine(state);
10544
- if (!bare) {
10545
- state.write(`== ${tab.attrs.label}`);
10546
- state.ensureNewLine();
10547
- }
10548
- state.renderContent(tab);
10549
- }));
10550
- },
10551
- loomaTab: (state, node) => state.renderContent(node),
10552
- loomaTableOfContents: (state, node) => {
10553
- const { format, depth } = node.attrs;
10554
- state.write(`::toc${formatLoomaAttributes({
10555
- depth: depth !== 3 ? depth : null,
10556
- format: format !== "plain" ? format : null
10557
- })}`);
10558
- state.closeBlock(node);
10559
- },
10560
- loomaFootnoteReference: (state, node) => state.write(`[^${node.attrs.label}]`),
10561
- loomaFootnotes: (state, node) => state.renderContent(node),
10562
- loomaFootnote: (state, node) => state.wrapBlock(" ", `[^${node.attrs.label}]: `, node, () => state.renderContent(node)),
10563
- loomaChip: (state, node) => {
10564
- const tone = normalizeLoomaChipTone(node.attrs.color);
10565
- state.write(`:chip[${label(String(node.attrs.label ?? ""))}]${formatLoomaAttributes({ tone: tone !== "neutral" ? tone : null })}`);
10566
- },
10567
- mention: (state, node) => {
10568
- const id = node.attrs.id == null ? "" : String(node.attrs.id);
10569
- const reference = !id ? "" : LOOMA_MENTION_HANDLE.exec(id)?.[0] === id ? `#${id}` : formatLoomaAttributes({ ref: id });
10570
- state.write(`@[${label(String(node.attrs.label || id))}]${reference}`);
10571
- },
10572
- loomaReference: (state, node) => {
10573
- const wrapper = document.createElement("span");
10574
- wrapper.append(DOMSerializer.fromSchema(node.type.schema).serializeNode(node));
10575
- state.write(wrapper.innerHTML);
10576
- }
10577
- };
10578
- var MARKS = {
10579
- bold: defaultMarkdownSerializer.marks.strong,
10580
- italic: defaultMarkdownSerializer.marks.em,
10581
- code: defaultMarkdownSerializer.marks.code,
10582
- link: defaultMarkdownSerializer.marks.link,
10583
- strike: {
10584
- open: "~~",
10585
- close: "~~",
10586
- mixable: true,
10587
- expelEnclosingWhitespace: true
10588
- },
10589
- underline: {
10590
- open: "<u>",
10591
- close: "</u>",
10592
- mixable: true
10593
- },
10594
- highlight: {
10595
- open: "<mark>",
10596
- close: "</mark>",
10597
- mixable: true
10598
- }
10599
- };
10600
- function customHeadingIds(doc) {
10601
- const headings = [];
10602
- doc.descendants((node) => {
10603
- if (node.type.name === "heading") headings.push({
10604
- text: node.textContent.trim(),
10605
- id: typeof node.attrs.id === "string" && node.attrs.id ? node.attrs.id : void 0
10606
- });
10607
- });
10608
- const marked = /* @__PURE__ */ new Set();
10609
- for (;;) {
10610
- const derived = assignLoomaHeadingIds(headings.map(({ text, id }, index) => ({
10611
- text,
10612
- id: marked.has(index) ? id : void 0
10613
- })));
10614
- const next = headings.findIndex(({ id }, index) => id && !marked.has(index) && derived[index] !== id);
10615
- if (next < 0) return marked;
10616
- marked.add(next);
10617
- }
10618
- }
10619
- /**
10620
- * Writes an editor document as Looma Markdown, the form `loomaMarkdownToHtml` and Markupress read.
10621
- * @contract Every node in the default preset has a Markdown form. A table that fits GFM is a GFM
10622
- * table and any other is HTML. Content from extensions outside the preset is written as its saved
10623
- * HTML, and marks without a Markdown form other than underline and highlight are dropped.
10624
- */
10625
- function loomaMarkdownFromDoc(doc) {
10626
- const schema = doc.type.schema;
10627
- const dom = DOMSerializer.fromSchema(schema);
10628
- const html = (node) => {
10629
- const holder = document.createElement("div");
10630
- holder.append(dom.serializeNode(node));
10631
- return holder.innerHTML;
10632
- };
10633
- const custom = customHeadingIds(doc);
10634
- let heading = 0;
10635
- const nodes = {
10636
- loomaTableOfContents: (state, node, parent, index) => {
10637
- if (node.childCount) {
10638
- state.write(html(node));
10639
- state.closeBlock(node);
10640
- } else NODES.loomaTableOfContents(state, node, parent, index);
10641
- },
10642
- loomaTabs: (state, node, parent, index) => {
10643
- if ([
10644
- node.attrs.defaultValue,
10645
- node.attrs.queryString,
10646
- node.attrs.lazy
10647
- ].some((value) => value !== null && value !== void 0) || Array.from({ length: node.childCount }, (_, index) => node.child(index)).some((tab) => tab.attrs.value !== null && tab.attrs.value !== void 0)) {
10648
- state.write(html(node));
10649
- state.closeBlock(node);
10650
- } else NODES.loomaTabs(state, node, parent, index);
10651
- },
10652
- heading: (state, node) => {
10653
- state.write(`${"#".repeat(node.attrs.level)} `);
10654
- state.renderInline(node, false);
10655
- if (custom.has(heading++)) state.write(` {#${node.attrs.id}}`);
10656
- else {
10657
- const out = state;
10658
- out.out = out.out.replace(/([ \t])\{([^{}]*\})$/, "$1\\{$2");
10659
- }
10660
- state.closeBlock(node);
10661
- },
10662
- table: (state, node) => {
10663
- state.write(gfmTable(node) ?? `<table><tbody>${Array.from({ length: node.childCount }, (_, index) => html(node.child(index))).join("")}</tbody></table>`.replace(/ (?:colspan|rowspan)="1"/g, ""));
10664
- state.closeBlock(node);
10665
- }
10666
- };
10667
- for (const name of Object.keys(schema.nodes)) nodes[name] ??= NODES[name] ?? ((state, node) => {
10668
- state.write(html(node));
10669
- if (node.isBlock) state.closeBlock(node);
10670
- });
10671
- const marks = {};
10672
- for (const name of Object.keys(schema.marks)) marks[name] = MARKS[name] ?? {
10673
- open: "",
10674
- close: ""
10675
- };
10676
- const serializer = new MarkdownSerializer(nodes, marks);
10677
- const inline = (paragraph) => serializer.serialize(schema.topNodeType.create(null, paragraph)).replace(/\|/g, "\\|");
10678
- function gfmTable(table) {
10679
- const rows = Array.from({ length: table.childCount }, (_, index) => table.child(index));
10680
- const width = rows[0]?.childCount ?? 0;
10681
- const alignments = [];
10682
- const lines = [];
10683
- for (const [rowIndex, row] of rows.entries()) {
10684
- if (row.childCount !== width) return null;
10685
- const cells = [];
10686
- for (let column = 0; column < width; column++) {
10687
- const cell = row.child(column);
10688
- const { colspan, rowspan, colwidth, backgroundColor, textAlign } = cell.attrs;
10689
- const paragraph = cell.firstChild;
10690
- if (cell.type.name === "tableHeader" !== (rowIndex === 0) || colspan !== 1 || rowspan !== 1 || colwidth || backgroundColor || cell.childCount !== 1 || paragraph?.type.name !== "paragraph") return null;
10691
- let hasBreak = false;
10692
- paragraph.descendants((child) => {
10693
- if (child.type.name === "hardBreak") hasBreak = true;
10694
- });
10695
- if (hasBreak) return null;
10696
- if (rowIndex === 0) alignments.push(textAlign ?? null);
10697
- else if ((textAlign ?? null) !== alignments[column]) return null;
10698
- cells.push(inline(paragraph));
10699
- }
10700
- lines.push(`| ${cells.join(" | ")} |`);
10701
- if (rowIndex === 0) lines.push(`| ${alignments.map((alignment) => ALIGNMENT[alignment] ?? "---").join(" | ")} |`);
10702
- }
10703
- return width ? lines.join("\n") : null;
10704
- }
10705
- return serializer.serialize(doc, { tightLists: true });
10706
- }
10707
- //#endregion
10708
9963
  //#region src/editor/extensions/smart-paste.ts
10709
9964
  var HTML_DOCUMENT_PATTERN = /<!doctype\s+html\b|<(?:html|body)\b[^>]*>/i;
10710
9965
  var HTML_PAIRED_TAG_PATTERN = /<(h[1-6]|p|ul|ol|li|blockquote|table|thead|tbody|tfoot|tr|th|td|figure|figcaption|article|section|header|footer|main|div|span|strong|em|b|i|a|code|pre)\b[^>]*>[\s\S]*?<\/\1\s*>/i;
@@ -10718,27 +9973,31 @@ function looksLikeDocumentHtml(value) {
10718
9973
  const prefix = value.slice(0, match.index).replace(/<!--[^]*?-->/g, "").replace(/<\?[^]*?\?>/g, "").trim();
10719
9974
  return !/[={};`"']|=>|\b(?:const|let|var|return|function|class|import|export)\b/.test(prefix);
10720
9975
  }
9976
+ var MARKDOWN_BLOCKS = /* @__PURE__ */ new Set([
9977
+ "list",
9978
+ "blockquote",
9979
+ "table",
9980
+ "container",
9981
+ "leaf",
9982
+ "footnoteDefinition",
9983
+ "definition"
9984
+ ]);
9985
+ var MARKDOWN_INLINES = /* @__PURE__ */ new Set([
9986
+ "image",
9987
+ "strong",
9988
+ "inline",
9989
+ "footnoteReference",
9990
+ "linkReference"
9991
+ ]);
10721
9992
  function looksLikeMarkdown(value) {
10722
- const tokens = loomaMarkdown.parse(value, {});
10723
- return tokens.some((token, index) => {
10724
- if (token.type === "heading_open") return Boolean(tokens[index + 1]?.content.trim());
10725
- if ([
10726
- "bullet_list_open",
10727
- "ordered_list_open",
10728
- "blockquote_open",
10729
- "fence",
10730
- "table_open",
10731
- "looma_container_open",
10732
- "looma_toc"
10733
- ].includes(token.type)) return true;
10734
- return token.type === "inline" && Boolean(token.children?.some((child) => child.type === "link_open" && child.markup !== "linkify" || [
10735
- "image",
10736
- "strong_open",
10737
- "looma_chip",
10738
- "looma_mention",
10739
- "looma_footnote_ref"
10740
- ].includes(child.type)));
10741
- });
9993
+ const visit = (node) => {
9994
+ if (node.type === "heading") return Boolean(node.value?.trim() || node.children?.length);
9995
+ if (MARKDOWN_BLOCKS.has(node.type) || MARKDOWN_INLINES.has(node.type)) return true;
9996
+ if (node.type === "code") return node.source?.form !== "indented";
9997
+ if (node.type === "link") return node.source?.form !== "bare";
9998
+ return (node.body ?? node.children ?? []).some(visit);
9999
+ };
10000
+ return visit(parse(value, { syntax: "compatible" }));
10742
10001
  }
10743
10002
  function hasRichClipboardStructure(value) {
10744
10003
  if (!value.trim()) return false;
@@ -10790,12 +10049,29 @@ function parseHtmlSlice(schema, value, fromHtml = false) {
10790
10049
  if (!container.textContent?.trim() && !container.querySelector("img, hr")) return Slice.empty;
10791
10050
  return DOMParser.fromSchema(schema).parseSlice(container, { preserveWhitespace: false });
10792
10051
  }
10793
- function escapeHtmlText(value) {
10794
- return value.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&#39;");
10052
+ function markdownSlice(schema, markdown, frontmatter) {
10053
+ let content;
10054
+ try {
10055
+ content = markdownToEditorDocument(markdown).content ?? [];
10056
+ } catch {
10057
+ return null;
10058
+ }
10059
+ if (frontmatter !== null) content.unshift({
10060
+ type: "codeBlock",
10061
+ attrs: { language: "yaml" },
10062
+ content: [{
10063
+ type: "text",
10064
+ text: frontmatter
10065
+ }]
10066
+ });
10067
+ if (!content.length) return Slice.empty;
10068
+ return Slice.maxOpen(Fragment.fromArray(content.map((node) => schema.nodeFromJSON(node))));
10795
10069
  }
10796
10070
  function documentSlice(schema, plainText) {
10797
10071
  const frontmatter = splitLoomaFrontmatter(plainText);
10798
- if (frontmatter || looksLikeMarkdown(plainText)) return parseHtmlSlice(schema, frontmatter ? `<pre><code class="language-yaml">${escapeHtmlText(frontmatter.source)}</code></pre>${loomaMarkdown.render(frontmatter.body)}` : loomaMarkdown.render(plainText));
10072
+ if (frontmatter) return markdownSlice(schema, frontmatter.body, frontmatter.source);
10073
+ const markdown = looksLikeMarkdown(plainText) ? markdownSlice(schema, plainText, null) : null;
10074
+ if (markdown) return markdown;
10799
10075
  if (looksLikeDocumentHtml(plainText)) return parseHtmlSlice(schema, plainText, true);
10800
10076
  return null;
10801
10077
  }
@@ -11478,7 +10754,7 @@ function getDefaultEditorExtensions(options = {}) {
11478
10754
  BulletList,
11479
10755
  OrderedList,
11480
10756
  ListItem,
11481
- TaskList,
10757
+ TaskList.extend({ content: "(taskItem|listItem)+" }),
11482
10758
  LoomaTaskItem.configure({ nested: false }),
11483
10759
  Blockquote,
11484
10760
  calloutNodeView ? LoomaCallout.extend({ addNodeView: () => documentContentNodeView(calloutNodeView) }) : LoomaCallout,
@@ -11489,8 +10765,8 @@ function getDefaultEditorExtensions(options = {}) {
11489
10765
  LoomaExpand.configure({ nodeView: expandNodeView ? documentContentNodeView(expandNodeView) : null }),
11490
10766
  LoomaTableOfContents.configure({ nodeView: tableOfContentsNodeView ?? null }),
11491
10767
  LoomaFootnoteReference,
11492
- LoomaFootnotes,
11493
10768
  LoomaFootnote,
10769
+ LoomaLinkDefinition,
11494
10770
  dividerNodeView ? HorizontalRule.extend({ addNodeView: () => dividerNodeView }) : HorizontalRule,
11495
10771
  HardBreak,
11496
10772
  History,
@@ -12509,4 +11785,4 @@ function createLoomaSlashCommandExtension(options = {}) {
12509
11785
  });
12510
11786
  }
12511
11787
  //#endregion
12512
- export { LOOMA_ACTIVE_BLOCK_BLUR_GRACE_MS as $, filterLoomaMentionItems as A, LOOMA_FOOTNOTE_LABEL as B, loomaMarkdownToHtml as C, createLoomaMentionExtension as D, LoomaMentionSuggestionPluginKey as E, LoomaTableOfContents as F, LoomaFigcaption as G, LoomaFootnoteReference as H, getTableOfContentsEntries as I, revealLoomaExpandAt as J, LoomaFigure as K, normalizeTableOfContentsConfig as L, LoomaImage as M, normalizeImageDimension as N, DEFAULT_MENTION_RESULT_LIMIT as O, normalizeImagePlacement as P, LoomaCallout as Q, LoomaTab as R, loomaMarkdownFromDoc as S, siteRelativeHref as T, LoomaFootnotes as U, LoomaFootnote as V, findLoomaFootnote as W, LoomaChip as X, LOOMA_CHIP_COLORS as Y, normalizeLoomaChipColor as Z, getActiveTableCellAlignment as _, getActiveTableUiState as a, setActiveTableCellBackground as b, insertTableAtRange as c, LoomaTableKit as d, LOOMA_ACTIVE_BLOCK_CLASS as et, getDefaultEditorExtensions as f, LoomaTableHeader as g, LoomaTableCell as h, getDefaultSlashCommands as i, normalizeMentionResultLimit as j, MAX_MENTION_RESULT_LIMIT as k, normalizeActiveTableColumnWidths as l, LoomaTable as m, createLoomaSlashCommandExtension as n, LoomaActiveBlock as nt, handleTableAction as o, getLoomaTableExtensions as p, LoomaExpand as q, filterLoomaSlashCommands as r, LoomaActiveBlockPluginKey as rt, handleTableOverlayAction as s, LoomaSlashCommand as t, LOOMA_ACTIVE_BLOCK_TYPING_IDLE_MS as tt, shouldShowTextFormattingToolbar as u, getActiveTableCellBackground as v, createSiteRelativeLinks as w, LoomaSmartPaste as x, setActiveTableCellAlignment as y, LoomaTabs as z };
11788
+ export { LOOMA_ACTIVE_BLOCK_TYPING_IDLE_MS as $, LoomaImage as A, LoomaFootnote as B, siteRelativeHref as C, MAX_MENTION_RESULT_LIMIT as D, DEFAULT_MENTION_RESULT_LIMIT as E, normalizeTableOfContentsConfig as F, LoomaExpand as G, findLoomaFootnote as H, LoomaTab as I, LoomaChip as J, revealLoomaExpandAt as K, LoomaTabs as L, normalizeImagePlacement as M, LoomaTableOfContents as N, filterLoomaMentionItems as O, getTableOfContentsEntries as P, LOOMA_ACTIVE_BLOCK_CLASS as Q, LoomaLinkDefinition as R, createSiteRelativeLinks as S, createLoomaMentionExtension as T, LoomaFigcaption as U, LoomaFootnoteReference as V, LoomaFigure as W, LoomaCallout as X, normalizeLoomaChipColor as Y, LOOMA_ACTIVE_BLOCK_BLUR_GRACE_MS as Z, getActiveTableCellAlignment as _, getActiveTableUiState as a, setActiveTableCellBackground as b, insertTableAtRange as c, LoomaTableKit as d, LoomaActiveBlock as et, getDefaultEditorExtensions as f, LoomaTableHeader as g, LoomaTableCell as h, getDefaultSlashCommands as i, normalizeImageDimension as j, normalizeMentionResultLimit as k, normalizeActiveTableColumnWidths as l, LoomaTable as m, createLoomaSlashCommandExtension as n, handleTableAction as o, getLoomaTableExtensions as p, LOOMA_CHIP_COLORS as q, filterLoomaSlashCommands as r, handleTableOverlayAction as s, LoomaSlashCommand as t, LoomaActiveBlockPluginKey as tt, shouldShowTextFormattingToolbar as u, getActiveTableCellBackground as v, LoomaMentionSuggestionPluginKey as w, LoomaSmartPaste as x, setActiveTableCellAlignment as y, LOOMA_FOOTNOTE_LABEL as z };