@estiva-app/ui 0.75.0 → 0.76.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.
package/dist/editor.js CHANGED
@@ -457,10 +457,10 @@ var ComposeKeys = Extension2.create({
457
457
  });
458
458
  function isEmptyDoc(editor) {
459
459
  const doc2 = editor.state.doc;
460
- if (doc2.textContent.length > 0) return false;
460
+ if (doc2.textContent.trim().length > 0) return false;
461
461
  let empty = true;
462
462
  doc2.descendants((node) => {
463
- if (node.isAtom && node.type.name !== "hardBreak") empty = false;
463
+ if (node.isAtom && !node.isText && node.type.name !== "hardBreak") empty = false;
464
464
  });
465
465
  return empty;
466
466
  }
@@ -527,1679 +527,2024 @@ function ComposeBox({ editor, onSend, placeholder, tools, attachments, ready = f
527
527
  ] }) });
528
528
  }
529
529
 
530
- // src/InlineText.tsx
531
- import { useCallback as useCallback3, useEffect as useEffect3, useImperativeHandle as useImperativeHandle2, useRef as useRef3, useState as useState3 } from "react";
532
- import { Extension as Extension3, Node as Node2 } from "@tiptap/core";
533
- import { history, redo, undo } from "@tiptap/pm/history";
530
+ // src/CommentBox.tsx
531
+ import { useCallback as useCallback4, useEffect as useEffect4, useRef as useRef3, useState as useState4 } from "react";
532
+ import { Extension as Extension9 } from "@tiptap/core";
534
533
  import { EditorContent as EditorContent2, useEditor } from "@tiptap/react";
535
- import { cn as cn2 } from "@estiva-app/ui";
536
- import { jsx as jsx4, jsxs as jsxs3 } from "react/jsx-runtime";
537
- var VARIANT = {
538
- title: "text-h2 text-text-primary",
539
- summary: "text-body-1 text-text-secondary"
540
- };
541
- var ROOM = "-mx-2 px-2 py-1";
542
- var OneLine = Node2.create({ name: "doc", topNode: true, content: "paragraph" });
543
- var Paragraph = Node2.create({
544
- name: "paragraph",
545
- content: "text*",
546
- parseHTML: () => [{ tag: "p" }],
547
- renderHTML: () => ["p", 0]
548
- });
549
- var Text = Node2.create({ name: "text" });
550
- var Undo = Extension3.create({
551
- name: "inlineTextUndo",
552
- addProseMirrorPlugins: () => [history()],
553
- addKeyboardShortcuts() {
554
- const run = (command) => () => command(this.editor.state, this.editor.view.dispatch);
555
- return { "Mod-z": run(undo), "Shift-Mod-z": run(redo), "Mod-y": run(redo) };
556
- }
557
- });
558
- var doc = (text) => ({ type: "doc", content: [{ type: "paragraph", content: text ? [{ type: "text", text }] : [] }] });
559
- var oneLine = (text) => text.replace(/\s+/g, " ").trim();
560
- function InlineText({ value, placeholder, label, onCommit, onText, onEnter, variant = "title", clearable = false, readOnly = false, className, ref }) {
561
- const saved = useRef3(value);
562
- const [empty, setEmpty] = useState3(!value);
563
- const latest = useRef3({ onEnter, onText, onCommit, clearable, value });
564
- latest.current = { onEnter, onText, onCommit, clearable, value };
565
- const pending = useRef3(null);
566
- const save = useCallback3(async (text) => {
567
- const next = oneLine(text);
568
- if (next === saved.current || next === pending.current) return;
569
- if (!next && !latest.current.clearable) return;
570
- pending.current = next;
571
- try {
572
- if (await latest.current.onCommit(next)) saved.current = next;
573
- } finally {
574
- if (pending.current === next) pending.current = null;
575
- }
576
- }, []);
577
- const editor = useEditor({
578
- extensions: [OneLine, Paragraph, Text, Undo],
579
- content: doc(value),
580
- editable: !readOnly,
581
- editorProps: {
582
- attributes: {
583
- "aria-label": label,
584
- role: "textbox",
585
- "aria-multiline": "false",
586
- "aria-placeholder": placeholder,
587
- ...readOnly ? { "aria-readonly": "true" } : {},
588
- class: "outline-none"
589
- },
590
- handleKeyDown: (view, event) => {
591
- if (event.key === "Enter") {
592
- event.preventDefault();
593
- void save(view.state.doc.textContent);
594
- latest.current.onEnter?.();
595
- return true;
596
- }
597
- if (event.key === "Escape") {
598
- view.dom.blur();
599
- return true;
600
- }
601
- return false;
602
- },
603
- // A paste is its plain text on this one line, whatever it was copied from.
604
- handlePaste: (view, event) => {
605
- const text = event.clipboardData?.getData("text/plain");
606
- if (text == null) return false;
607
- view.dispatch(view.state.tr.insertText(text.replace(/\s+/g, " ")));
608
- return true;
609
- }
610
- },
611
- onFocus: ({ editor: e }) => latest.current.onText?.(e.getText()),
612
- onUpdate: ({ editor: e }) => {
613
- setEmpty(e.isEmpty);
614
- latest.current.onText?.(e.getText());
615
- },
616
- onBlur: ({ editor: e }) => {
617
- latest.current.onText?.(null);
618
- if (e.isEmpty && saved.current && !latest.current.clearable) {
619
- e.commands.setContent(doc(saved.current), { emitUpdate: false });
620
- setEmpty(false);
621
- return;
622
- }
623
- const { value: current } = latest.current;
624
- if (oneLine(e.getText()) === saved.current && current !== saved.current && pending.current === null) {
625
- e.commands.setContent(doc(current), { emitUpdate: false });
626
- saved.current = current;
627
- setEmpty(!current);
628
- return;
629
- }
630
- void save(e.getText());
631
- }
632
- }, [readOnly]);
633
- useEffect3(() => {
634
- if (!editor || editor.isDestroyed || value === saved.current || editor.isFocused) return;
635
- if (oneLine(editor.getText()) !== saved.current) return;
636
- editor.commands.setContent(doc(value), { emitUpdate: false });
637
- saved.current = value;
638
- setEmpty(!value);
639
- }, [editor, value]);
640
- useImperativeHandle2(ref, () => ({
641
- focus: (at = "start") => editor?.commands.focus(at)
642
- }), [editor]);
643
- return /* @__PURE__ */ jsxs3("div", { className: cn2("relative", VARIANT[variant], className), children: [
644
- /* @__PURE__ */ jsx4(EditorContent2, { editor, className: cn2(ROOM, !readOnly && "cursor-text") }),
645
- empty && !readOnly && /* @__PURE__ */ jsx4("span", { "aria-hidden": true, className: "pointer-events-none absolute left-0 top-1 text-text-muted", children: placeholder })
646
- ] });
647
- }
534
+ import StarterKit from "@tiptap/starter-kit";
535
+ import { IconLock, IconPaperclip, IconSquareRounded } from "@tabler/icons-react";
536
+ import { AttachmentCard } from "@estiva-app/ui";
648
537
 
649
- // src/CommentHighlights.ts
650
- import { Extension as Extension4 } from "@tiptap/core";
538
+ // src/BlockNodes.tsx
539
+ import { Extension as Extension6, InputRule, Node as Node2 } from "@tiptap/core";
540
+ import { DOMSerializer } from "@tiptap/pm/model";
541
+ import { Plugin as Plugin5, PluginKey as PluginKey5 } from "@tiptap/pm/state";
542
+ import { Mapping, ReplaceAroundStep } from "@tiptap/pm/transform";
543
+ import { NodeViewWrapper, ReactNodeViewRenderer, ReactRenderer as ReactRenderer2 } from "@tiptap/react";
544
+ import { Checkbox } from "@estiva-app/ui";
545
+ import { calloutLook } from "@estiva-app/ui";
546
+
547
+ // src/ReferenceMenu.tsx
548
+ import { useCallback as useCallback3 } from "react";
549
+ import { Extension as Extension5 } from "@tiptap/core";
550
+ import { useEditorState } from "@tiptap/react";
551
+ import { NodeSelection as NodeSelection2, Plugin as Plugin4, PluginKey as PluginKey4, TextSelection } from "@tiptap/pm/state";
552
+ import { ReplaceStep } from "@tiptap/pm/transform";
553
+ import { IconCheck } from "@tabler/icons-react";
554
+
555
+ // src/LinkChips.ts
556
+ import { Extension as Extension3 } from "@tiptap/core";
557
+ import { closeHistory } from "@tiptap/pm/history";
651
558
  import { Plugin as Plugin2, PluginKey as PluginKey2 } from "@tiptap/pm/state";
652
- import { Decoration as Decoration2, DecorationSet as DecorationSet2 } from "@tiptap/pm/view";
653
- var commentHighlightsKey = new PluginKey2("commentHighlights");
654
- var COMMENT_HIGHLIGHT_CLASSES = {
655
- rest: "cursor-pointer rounded-sm bg-warning-muted",
656
- active: "cursor-pointer rounded-sm bg-warning-muted underline decoration-warning-default decoration-2 underline-offset-4"
657
- };
658
- var QUOTE_WHOLE_MAX = 1e3;
659
- var QUOTE_END_LENGTH = 150;
660
- var QUOTE_CONTEXT_LENGTH = 32;
661
- function placesIn(doc2) {
662
- const places = /* @__PURE__ */ new Map();
663
- const walk = (parent, parentPos) => {
664
- parent.forEach((node, offset, index) => {
665
- const pos = parentPos + offset;
666
- const id = node.attrs.blockId;
667
- if (typeof id === "string" && id && !places.has(id)) places.set(id, { node, pos, parent: parentPos, index });
668
- if (!node.isTextblock && !node.isLeaf) walk(node, pos + 1);
669
- });
670
- };
671
- walk(doc2, 0);
672
- return places;
673
- }
674
- function textOf(block) {
675
- let text = "";
676
- const starts = [];
677
- const ends = [];
678
- const add = (chars, start, end) => {
679
- for (let i = 0; i < chars.length; i++) starts.push(start), ends.push(end);
680
- text += chars;
681
- };
682
- const walk = (node, pos) => {
683
- if (node.isTextblock) {
684
- node.forEach((child, offset) => {
685
- const at = pos + 1 + offset;
686
- if (child.isText && child.text) {
687
- for (let i = 0; i < child.text.length; i++) starts.push(at + i), ends.push(at + i + 1);
688
- text += child.text;
689
- } else if (child.type.name === "hardBreak") add("\n", at, at + child.nodeSize);
690
- else if (child.isInline && child.isLeaf) add(String(child.attrs.href || child.attrs.uri || ""), at, at + child.nodeSize);
691
- });
692
- return;
693
- }
694
- if (node.type.name === "listItem") {
695
- node.forEach((child, offset) => void (LISTS.has(child.type.name) || walk(child, pos + 1 + offset)));
696
- return;
697
- }
698
- const children = LISTS.has(node.type.name) ? itemsOf(node, pos) : childrenOf(node, pos);
699
- children.forEach(({ node: child, pos: at }, index) => {
700
- if (index > 0) add("\n", at, at);
701
- walk(child, at);
702
- });
703
- };
704
- walk(block.node, block.pos);
705
- return { text, starts, ends };
706
- }
707
- var LISTS = /* @__PURE__ */ new Set(["bulletList", "orderedList"]);
708
- function childrenOf(node, pos) {
559
+ var key = new PluginKey2("linkChips");
560
+ var CHIPS_MADE = "linkChipsMade";
561
+ var PASTES_KEPT = 8;
562
+ var LINK_OR_URL = /(\[[^[\]\n]+\]\((?:https?:\/\/|mailto:)[^\s)]+\))|(https?:\/\/[^\s<>"'`]+)/g;
563
+ var TRAILING = /* @__PURE__ */ new Set([".", ",", ";", ":", "!", "?", ")", "]"]);
564
+ function urlRuns(text) {
565
+ if (!text.includes("://")) return [];
709
566
  const out = [];
710
- node.forEach((child, offset) => void out.push({ node: child, pos: pos + 1 + offset }));
567
+ for (const m of text.matchAll(LINK_OR_URL)) {
568
+ if (m[1]) continue;
569
+ const start = m.index;
570
+ if (text.slice(Math.max(0, start - 2), start) === "](" || text[start - 1] === "[") continue;
571
+ let end = m[0].length;
572
+ while (end > 0 && TRAILING.has(m[0][end - 1])) end--;
573
+ out.push({ url: m[0].slice(0, end), from: start, to: start + end, end: start + m[0].length });
574
+ }
711
575
  return out;
712
576
  }
713
- function itemsOf(list, pos) {
714
- return childrenOf(list, pos).flatMap((item) => [item, ...childrenOf(item.node, item.pos).flatMap((c) => LISTS.has(c.node.type.name) ? itemsOf(c.node, c.pos) : [])]);
577
+ function findLinkChips(doc2, selection, referenceOf, pasted = []) {
578
+ const found = { chips: [], fills: [], open: [] };
579
+ const open = /* @__PURE__ */ new Set();
580
+ doc2.descendants((node, pos) => {
581
+ if (node.type.spec.code) return false;
582
+ if (node.type.name === "reference") {
583
+ const href = typeof node.attrs.href === "string" ? node.attrs.href : "";
584
+ if (href && !node.attrs.uri) {
585
+ const uri = referenceOf?.(href);
586
+ if (uri) found.fills.push({ pos, uri });
587
+ else open.add(href);
588
+ }
589
+ return false;
590
+ }
591
+ if (!node.isText || !node.text) return true;
592
+ if (node.marks.some((m) => m.type.spec.code || m.type.name === "code")) return false;
593
+ const link = node.marks.find((m) => m.type.name === "link");
594
+ if (link && !(link.attrs.href === node.text && /^https?:\/\//.test(node.text))) return false;
595
+ const runs = link ? [{ url: node.text, from: 0, to: node.text.length, end: node.text.length }] : urlRuns(node.text);
596
+ for (const run of runs) {
597
+ const from = pos + run.from;
598
+ const to = pos + run.to;
599
+ const wasPasted = pasted.some((range) => range.from <= from && pos + run.end <= range.to);
600
+ const typing = selection && selection.to > from && selection.from <= pos + run.end;
601
+ if (typing && !(selection.empty && wasPasted)) continue;
602
+ const uri = referenceOf?.(run.url);
603
+ if (uri) found.chips.push({ from, to, url: run.url, uri, marks: node.marks.filter((m) => m !== link).map((m) => m.type.name), pasted: wasPasted });
604
+ else open.add(run.url);
605
+ }
606
+ return false;
607
+ });
608
+ found.open = [...open];
609
+ return found;
715
610
  }
716
- function find(text, words, from, context) {
717
- let first = -1;
718
- for (let at = text.indexOf(words, from); at !== -1; at = text.indexOf(words, at + 1)) {
719
- if (first === -1) first = at;
720
- if (context(at)) return at;
611
+ function apply(state, found) {
612
+ if (!found.chips.length && !found.fills.length) return null;
613
+ const type = state.schema.nodes.reference;
614
+ if (!type) return null;
615
+ const tr = state.tr;
616
+ for (const { pos, uri } of found.fills) {
617
+ const node = tr.doc.nodeAt(pos);
618
+ if (node) tr.setNodeMarkup(pos, void 0, { ...node.attrs, uri });
721
619
  }
722
- return first;
620
+ for (const chip of [...found.chips].reverse()) {
621
+ tr.replaceWith(chip.from, chip.to, type.create({ uri: chip.uri, href: chip.url, marks: chip.marks }));
622
+ }
623
+ const pasted = found.chips.some((chip) => chip.pasted);
624
+ tr.setMeta(CHIPS_MADE, { pasted });
625
+ return pasted ? closeHistory(tr) : tr.setMeta("addToHistory", false);
723
626
  }
724
- function runIn(doc2, places, ids) {
725
- const present = ids.map((id) => places.get(id)).filter((p) => !!p);
726
- if (present.length === 0) return null;
727
- const byParent = /* @__PURE__ */ new Map();
728
- for (const p of present) byParent.set(p.parent, [...byParent.get(p.parent) ?? [], p]);
729
- const group = [...byParent.values()].reduce((best, one) => one.length > best.length ? one : best);
730
- const low = Math.min(...group.map((p) => p.index));
731
- const high = Math.max(...group.map((p) => p.index));
732
- const contentStart = group[0].parent;
733
- const parent = contentStart === 0 ? doc2 : doc2.nodeAt(contentStart - 1);
734
- if (!parent) return group;
735
- const run = [];
736
- parent.forEach((node, offset, index) => {
737
- if (index >= low && index <= high) run.push({ node, pos: contentStart + offset, parent: contentStart, index });
738
- });
739
- return run;
740
- }
741
- function placeOf(doc2, anchor, places = placesIn(doc2)) {
742
- const run = runIn(doc2, places, anchor.blocks);
743
- if (!run) return { state: "detached" };
744
- const from = run[0].pos;
745
- const to = run[run.length - 1].pos + run[run.length - 1].node.nodeSize;
746
- const { quote } = anchor;
747
- if (!quote) return { state: "resolved", from, to, words: false };
748
- const reworded = { state: "reworded", from, to };
749
- const firstId = anchor.blocks[0];
750
- const lastId = anchor.blocks[anchor.blocks.length - 1];
751
- const first = run.findIndex((p) => p.node.attrs.blockId === firstId);
752
- const last = run.findIndex((p) => p.node.attrs.blockId === lastId);
753
- if (first === -1 || last === -1 || last < first) return reworded;
754
- const a = textOf(run[first]);
755
- const b = first === last ? a : textOf(run[last]);
756
- const prefix = quote.prefix && quote.prefix.length <= QUOTE_CONTEXT_LENGTH ? quote.prefix : void 0;
757
- const suffix = quote.suffix && quote.suffix.length <= QUOTE_CONTEXT_LENGTH ? quote.suffix : void 0;
758
- const before = (text, i) => !prefix || text.slice(Math.max(0, i - prefix.length), i) === prefix;
759
- const after = (text, i) => !suffix || text.slice(i, i + suffix.length) === suffix;
760
- if (quote.end === void 0) {
761
- const at = find(a.text, quote.start, 0, (i) => before(a.text, i) && after(a.text, i + quote.start.length));
762
- if (at === -1 || quote.start === "") return reworded;
763
- return { state: "resolved", from: a.starts[at], to: a.ends[at + quote.start.length - 1], words: true };
764
- }
765
- const startAt = find(a.text, quote.start, 0, (i) => before(a.text, i));
766
- if (startAt === -1 || quote.start === "") return reworded;
767
- const endFrom = first === last ? startAt + quote.start.length : 0;
768
- const endAt = find(b.text, quote.end, endFrom, (i) => after(b.text, i + quote.end.length));
769
- if (endAt === -1 || quote.end === "") return reworded;
770
- return { state: "resolved", from: a.starts[startAt], to: b.ends[endAt + quote.end.length - 1], words: true };
627
+ function refreshLinkChips(editor) {
628
+ if (editor.isDestroyed) return;
629
+ const chips = key.getState(editor.state);
630
+ if (!chips) return;
631
+ const tr = apply(editor.state, findLinkChips(editor.state.doc, editor.state.selection, chips.options.referenceOf, chips.pasted));
632
+ if (tr) editor.view.dispatch(tr);
771
633
  }
772
- var CommentHighlights = Extension4.create({
773
- name: "commentHighlights",
634
+ var LinkChips = Extension3.create({
635
+ name: "linkChips",
774
636
  addOptions() {
775
- return { onSelect: null };
637
+ return { referenceOf: null, ask: null, limit: 24 };
776
638
  },
777
639
  addProseMirrorPlugins() {
778
640
  const options = this.options;
779
641
  const editor = this.editor;
780
642
  return [
781
643
  new Plugin2({
782
- key: commentHighlightsKey,
644
+ key,
645
+ // The options, where `refreshLinkChips` can read them from the state alone, and where the last pastes landed.
783
646
  state: {
784
- init: () => ({ anchors: [], active: null }),
785
- apply(tr, previous) {
786
- const meta = tr.getMeta(commentHighlightsKey);
787
- return meta ?? previous;
647
+ init: () => ({ options, pasted: [] }),
648
+ apply: (tr, value, before, after) => {
649
+ if (!tr.docChanged) return value;
650
+ const pasted = value.pasted.map((range) => ({ from: tr.mapping.map(range.from, 1), to: tr.mapping.map(range.to, -1), size: range.to - range.from })).filter((range) => range.from < range.to && range.to - range.from === range.size).map(({ from, to }) => ({ from, to }));
651
+ if (tr.getMeta("uiEvent") === "paste") {
652
+ const from = tr.mapping.map(before.selection.from, -1);
653
+ if (from < after.selection.to) pasted.push({ from, to: after.selection.to });
654
+ }
655
+ return { options, pasted: pasted.slice(-PASTES_KEPT) };
788
656
  }
789
657
  },
790
- props: {
791
- decorations(state) {
792
- const { anchors, active } = commentHighlightsKey.getState(state) ?? { anchors: [], active: null };
793
- const places = placesIn(state.doc);
794
- const drawn = anchors.flatMap((anchor) => {
795
- const place2 = placeOf(state.doc, anchor, places);
796
- if (place2.state !== "resolved") return [];
797
- const attrs = { class: anchor.id === active ? COMMENT_HIGHLIGHT_CLASSES.active : COMMENT_HIGHLIGHT_CLASSES.rest, "data-comment-id": anchor.id };
798
- if (place2.words) return [Decoration2.inline(place2.from, place2.to, attrs)];
799
- const blocks = [];
800
- state.doc.nodesBetween(place2.from, place2.to, (node, pos) => {
801
- if (pos < place2.from || pos + node.nodeSize > place2.to) return true;
802
- blocks.push(Decoration2.node(pos, pos + node.nodeSize, attrs));
803
- return false;
804
- });
805
- return blocks;
806
- });
807
- return drawn.length ? DecorationSet2.create(state.doc, drawn) : null;
808
- },
809
- handleClick(view, pos) {
810
- const { anchors } = commentHighlightsKey.getState(view.state) ?? { anchors: [] };
811
- const places = placesIn(view.state.doc);
812
- let hit = null;
813
- for (const anchor of anchors) {
814
- const place2 = placeOf(view.state.doc, anchor, places);
815
- if (place2.state !== "resolved" || pos < place2.from || pos >= place2.to) continue;
816
- const size = place2.to - place2.from;
817
- if (!hit || size < hit.size) hit = { id: anchor.id, size };
658
+ appendTransaction: (trs, _old, state) => {
659
+ if (!trs.some((tr) => tr.docChanged || tr.selectionSet)) return null;
660
+ return apply(state, findLinkChips(state.doc, state.selection, options.referenceOf, key.getState(state)?.pasted));
661
+ },
662
+ view: (view) => {
663
+ const asked = /* @__PURE__ */ new Set();
664
+ const look = (state) => {
665
+ if (!options.ask) return;
666
+ const { open } = findLinkChips(state.doc, state.selection, options.referenceOf, key.getState(state)?.pasted);
667
+ const waiting = new Set(open);
668
+ for (const url of asked) if (!waiting.has(url)) asked.delete(url);
669
+ const fresh = open.filter((url) => !asked.has(url)).slice(0, Math.max(0, options.limit - asked.size));
670
+ if (!fresh.length) return;
671
+ for (const url of fresh) asked.add(url);
672
+ const forget = () => {
673
+ for (const url of fresh) asked.delete(url);
674
+ };
675
+ let answer;
676
+ try {
677
+ answer = options.ask(fresh);
678
+ } catch {
679
+ forget();
680
+ return;
818
681
  }
819
- if (hit) {
820
- options.onSelect?.(hit.id);
821
- editor.emit("commentSelect", { id: hit.id });
682
+ void Promise.resolve(answer).then(() => refreshLinkChips(editor), forget);
683
+ };
684
+ look(view.state);
685
+ queueMicrotask(() => {
686
+ try {
687
+ refreshLinkChips(editor);
688
+ } catch {
822
689
  }
823
- return false;
824
- }
690
+ });
691
+ return {
692
+ update: (next, prev) => {
693
+ if (next.state.doc !== prev.doc || !next.state.selection.eq(prev.selection)) look(next.state);
694
+ }
695
+ };
825
696
  }
826
697
  })
827
698
  ];
828
699
  }
829
700
  });
830
- function setCommentAnchors(editor, anchors, active = null) {
831
- if (editor.isDestroyed) return;
832
- editor.view.dispatch(editor.state.tr.setMeta(commentHighlightsKey, { anchors, active }));
833
- }
834
- function commentPlace(editor, anchor) {
835
- return placeOf(editor.state.doc, anchor);
836
- }
837
- function commentElement(editor, anchor) {
838
- const drawn = editor.view.dom.querySelector(`[data-comment-id="${CSS.escape(anchor.id)}"]`);
839
- if (drawn) return drawn;
840
- const place2 = placeOf(editor.state.doc, anchor);
841
- if (place2.state === "detached") return null;
842
- const dom = editor.view.nodeDOM(place2.from);
843
- return dom instanceof HTMLElement ? dom : null;
844
- }
845
- function quoteText(quote) {
846
- return quote.end ? `${quote.start} \u2026 ${quote.end}` : quote.start;
701
+
702
+ // src/ReferenceMenu.tsx
703
+ import { MenuItem, MenuSection, MenuSeparator } from "@estiva-app/ui";
704
+ import { Popover as Popover2 } from "@estiva-app/ui";
705
+
706
+ // src/ReferenceCards.ts
707
+ import { Extension as Extension4 } from "@tiptap/core";
708
+ import { NodeSelection, Plugin as Plugin3, PluginKey as PluginKey3 } from "@tiptap/pm/state";
709
+ import { Decoration as Decoration2, DecorationSet as DecorationSet2 } from "@tiptap/pm/view";
710
+ import { useEffect as useEffect3, useState as useState3 } from "react";
711
+ function layoutOf(raw) {
712
+ if (typeof raw !== "string" || raw === "" || raw === "none") return void 0;
713
+ return raw === "detailed" ? "detailed" : "compact";
847
714
  }
848
- function headOf(text, length) {
849
- if (text.length <= length) return text;
850
- const cut = text.lastIndexOf(" ", length);
851
- return text.slice(0, cut > length / 2 ? cut : length);
715
+ function referenceCardPlacements(doc2) {
716
+ const out = [];
717
+ const seen = /* @__PURE__ */ new Map();
718
+ doc2.descendants((node, pos, parent) => {
719
+ if (!node.isTextblock) return true;
720
+ const cards = [];
721
+ node.forEach((child) => {
722
+ if (child.type.name !== "reference") return;
723
+ const layout = layoutOf(child.attrs.embed);
724
+ if (layout && child.attrs.uri) cards.push({ uri: String(child.attrs.uri), layout });
725
+ });
726
+ if (cards.length) {
727
+ const id = node.attrs.blockId ?? parent?.attrs.blockId;
728
+ const base = id ? `b:${String(id)}` : `p:${pos}`;
729
+ const n = seen.get(base) ?? 0;
730
+ seen.set(base, n + 1);
731
+ out.push({ key: n ? `${base}:${n}` : base, pos: pos + node.nodeSize - 1, cards });
732
+ }
733
+ return false;
734
+ });
735
+ return out;
852
736
  }
853
- function tailOf(text, length) {
854
- if (text.length <= length) return text;
855
- const from = text.length - length;
856
- const cut = text.indexOf(" ", from);
857
- return text.slice(cut !== -1 && cut < from + length / 2 ? cut + 1 : from);
737
+ var key2 = new PluginKey3("referenceCards");
738
+ function elementFor(storage, slotKey) {
739
+ let element = storage.elements.get(slotKey);
740
+ if (!element) {
741
+ element = document.createElement("div");
742
+ element.setAttribute("data-reference-cards", slotKey);
743
+ element.setAttribute("contenteditable", "false");
744
+ storage.elements.set(slotKey, element);
745
+ }
746
+ return element;
858
747
  }
859
- function occurrences(text, words) {
860
- let count = 0;
861
- for (let at = text.indexOf(words); words && at !== -1; at = text.indexOf(words, at + 1)) count++;
862
- return count;
748
+ function storageOf(editor) {
749
+ return editor.storage.referenceCards;
863
750
  }
864
- function offsetIn(block, pos) {
865
- const at = block.starts.findIndex((start) => start >= pos);
866
- return at === -1 ? block.starts.length : at;
751
+ var ReferenceCards = Extension4.create({
752
+ name: "referenceCards",
753
+ addStorage() {
754
+ return { elements: /* @__PURE__ */ new Map() };
755
+ },
756
+ addProseMirrorPlugins() {
757
+ const storage = this.storage;
758
+ const decorate = (doc2) => DecorationSet2.create(
759
+ doc2,
760
+ referenceCardPlacements(doc2).map(
761
+ (p) => Decoration2.widget(p.pos, () => elementFor(storage, p.key), {
762
+ key: p.key,
763
+ side: 1,
764
+ ignoreSelection: true,
765
+ // A click on a card is the card's, not a caret placement in the line.
766
+ stopEvent: () => true
767
+ })
768
+ )
769
+ );
770
+ return [
771
+ new Plugin3({
772
+ key: key2,
773
+ state: {
774
+ init: (_, state) => decorate(state.doc),
775
+ apply: (tr, set) => tr.docChanged ? decorate(tr.doc) : set
776
+ },
777
+ props: { decorations: (state) => key2.getState(state) }
778
+ })
779
+ ];
780
+ }
781
+ });
782
+ function useReferenceCards(editor) {
783
+ const [slots, setSlots] = useState3([]);
784
+ useEffect3(() => {
785
+ if (!editor) return;
786
+ const storage = storageOf(editor);
787
+ if (!storage) return;
788
+ let last = "";
789
+ const read = () => {
790
+ if (editor.isDestroyed) return;
791
+ const next = referenceCardPlacements(editor.state.doc).map((p) => ({ key: p.key, element: elementFor(storage, p.key), cards: p.cards }));
792
+ const signature = JSON.stringify(next.map((s) => [s.key, s.cards]));
793
+ if (signature === last) return;
794
+ last = signature;
795
+ const live = new Set(next.map((s) => s.key));
796
+ for (const k of storage.elements.keys()) if (!live.has(k)) storage.elements.delete(k);
797
+ setSlots(next);
798
+ };
799
+ read();
800
+ editor.on("transaction", read);
801
+ return () => {
802
+ editor.off("transaction", read);
803
+ };
804
+ }, [editor]);
805
+ return slots;
867
806
  }
868
- function anchorOfSelection(editor) {
869
- const { doc: doc2, selection } = editor.state;
870
- if (selection.empty) return null;
871
- const { $from, $to } = selection;
872
- const places = placesIn(doc2);
873
- const around = (depth) => {
874
- for (let d = depth; d > 0; d--) {
875
- const id = $from.node(d).attrs.blockId;
876
- if (typeof id === "string" && id && places.has(id)) return places.get(id);
877
- }
878
- return void 0;
879
- };
880
- let run;
881
- if ($from.parent === $to.parent && $from.parent.isTextblock) {
882
- const found = around($from.depth);
883
- if (!found) return null;
884
- run = [found];
885
- } else {
886
- const depth = $from.sharedDepth($to.pos);
887
- const low = $from.index(depth);
888
- const high = $to.pos >= $to.end(depth) ? $from.node(depth).childCount - 1 : $to.index(depth);
889
- run = [];
890
- for (let i = low; i <= high; i++) {
891
- const id = $from.node(depth).child(i).attrs.blockId;
892
- const place2 = typeof id === "string" ? places.get(id) : void 0;
893
- if (!place2) {
894
- const found = around(depth);
895
- if (!found) return null;
896
- run = [found];
897
- break;
807
+ function referenceAtSelection(state) {
808
+ const { selection } = state;
809
+ let found = null;
810
+ if (selection instanceof NodeSelection) {
811
+ if (selection.node.type.name === "reference") found = { pos: selection.from, node: selection.node };
812
+ } else if (!selection.empty) {
813
+ let only = true;
814
+ state.doc.nodesBetween(selection.from, selection.to, (node2, pos2) => {
815
+ if (node2.type.name === "reference") {
816
+ if (found) only = false;
817
+ found = { pos: pos2, node: node2 };
818
+ return false;
898
819
  }
899
- run.push(place2);
900
- }
901
- }
902
- let firstText = textOf(run[0]);
903
- let lastText = run.length === 1 ? firstText : textOf(run[run.length - 1]);
904
- let start = offsetIn(firstText, selection.from);
905
- let end = offsetIn(lastText, selection.to);
906
- if (run.length > 1 && start >= firstText.text.length) run = run.slice(1), firstText = textOf(run[0]), start = 0;
907
- if (run.length > 1 && end <= 0) run = run.slice(0, -1), lastText = textOf(run[run.length - 1]), end = lastText.text.length;
908
- if (run.length === 1) lastText = firstText;
909
- if (run.length === 1 && firstText.text && start >= end) return null;
910
- if (run.length === 1 && firstText.text && !firstText.text.slice(start, end).replace(/\n/g, "")) return null;
911
- const blocks = run.map((p) => p.node.attrs.blockId);
912
- if (start === 0 && end >= lastText.text.length) return { blocks };
913
- const single = run.length === 1;
914
- const quote = { start: "" };
915
- if (single && end - start <= QUOTE_WHOLE_MAX) {
916
- quote.start = firstText.text.slice(start, end);
917
- } else {
918
- const startWords = single ? firstText.text.slice(start, end) : firstText.text.slice(start);
919
- const endWords = single ? startWords : lastText.text.slice(0, end);
920
- quote.start = headOf(startWords, QUOTE_END_LENGTH);
921
- quote.end = tailOf(endWords, QUOTE_END_LENGTH);
820
+ if (node2.isText) {
821
+ const from = Math.max(selection.from, pos2) - pos2;
822
+ const to = Math.min(selection.to, pos2 + node2.nodeSize) - pos2;
823
+ if ((node2.text ?? "").slice(from, to).trim() !== "") only = false;
824
+ }
825
+ return true;
826
+ });
827
+ if (!only) found = null;
922
828
  }
923
- if (!quote.start || quote.end === "") return { blocks };
924
- const prefix = firstText.text.slice(Math.max(0, start - QUOTE_CONTEXT_LENGTH), start);
925
- const suffix = lastText.text.slice(end, end + QUOTE_CONTEXT_LENGTH);
926
- if (prefix && occurrences(firstText.text, quote.start) > 1) quote.prefix = prefix;
927
- if (suffix && occurrences(lastText.text, quote.end ?? quote.start) > 1) quote.suffix = suffix;
928
- return { blocks, quote };
829
+ if (!found) return null;
830
+ const { pos, node } = found;
831
+ if (!node.attrs.uri) return null;
832
+ return { pos, uri: String(node.attrs.uri ?? ""), layout: layoutOf(node.attrs.embed) ?? "none" };
833
+ }
834
+ function setReferenceCard(editor, layout) {
835
+ const at = referenceAtSelection(editor.state);
836
+ return at ? setReferenceCardAt(editor, at.pos, layout) : false;
837
+ }
838
+ function setReferenceCardAt(editor, pos, layout) {
839
+ const node = editor.state.doc.nodeAt(pos);
840
+ if (!node || node.type.name !== "reference" || !node.attrs.uri) return false;
841
+ const wasNode = editor.state.selection instanceof NodeSelection && editor.state.selection.from === pos;
842
+ const tr = editor.state.tr.setNodeMarkup(pos, void 0, { ...node.attrs, embed: layout === "none" ? null : layout });
843
+ if (wasNode) tr.setSelection(NodeSelection.create(tr.doc, pos));
844
+ editor.view.dispatch(tr);
845
+ return true;
929
846
  }
930
847
 
931
- // src/PastedImages.ts
932
- import { Extension as Extension5 } from "@tiptap/core";
933
- import { Plugin as Plugin3, PluginKey as PluginKey3 } from "@tiptap/pm/state";
934
- var IMAGE_EXTENSIONS = {
935
- "image/png": "png",
936
- "image/jpeg": "jpg",
937
- "image/gif": "gif",
938
- "image/webp": "webp",
939
- "image/heic": "heic",
940
- "image/heif": "heif",
941
- "image/svg+xml": "svg"
942
- };
943
- var GENERIC_STEMS = /* @__PURE__ */ new Set(["image", "blob", "unknown", "untitled", "screenshot"]);
944
- function extensionFor(contentType) {
945
- const type = contentType.toLowerCase();
946
- return IMAGE_EXTENSIONS[type] ?? type.split("/")[1]?.split("+")[0] ?? "png";
848
+ // src/ReferenceMenu.tsx
849
+ import { Fragment, jsx as jsx4, jsxs as jsxs3 } from "react/jsx-runtime";
850
+ var key3 = new PluginKey4("referenceMenu");
851
+ var LAYOUTS = [
852
+ { layout: "none", label: "None" },
853
+ { layout: "compact", label: "Compact" },
854
+ { layout: "detailed", label: "Detailed" }
855
+ ];
856
+ function chipTarget(view, pos) {
857
+ const dom = view.nodeDOM(pos);
858
+ return dom instanceof HTMLElement ? dom.querySelector("a[href], button") : null;
947
859
  }
948
- function pastedImageName(contentType, at = /* @__PURE__ */ new Date(), index = 0) {
949
- const pad = (n) => String(n).padStart(2, "0");
950
- const stamp = `${at.getFullYear()}-${pad(at.getMonth() + 1)}-${pad(at.getDate())} ${pad(at.getHours())}-${pad(at.getMinutes())}-${pad(at.getSeconds())}`;
951
- const nth = index > 0 ? ` (${index + 1})` : "";
952
- return `Screenshot ${stamp}${nth}.${extensionFor(contentType)}`;
860
+ function webHref(view, pos) {
861
+ const href = view.state.doc.nodeAt(pos)?.attrs.href;
862
+ return typeof href === "string" && /^https?:\/\//i.test(href) ? href : "";
953
863
  }
954
- function hasUsableName(name) {
955
- const dot = name.lastIndexOf(".");
956
- if (dot <= 0 || dot === name.length - 1) return false;
957
- return !GENERIC_STEMS.has(name.slice(0, dot).toLowerCase());
864
+ function rowsOf(view, pos) {
865
+ const open = chipTarget(view, pos) || webHref(view, pos) ? ["open"] : [];
866
+ return view.state.doc.nodeAt(pos)?.attrs.uri ? [...open, ...LAYOUTS.map((card) => card.layout)] : open;
958
867
  }
959
- function pastedImages(source, at = /* @__PURE__ */ new Date()) {
960
- if (!source) return [];
961
- if (source.getData("text/plain").trim() !== "") return [];
962
- const images = Array.from(source.files ?? []).filter((f) => f.type.toLowerCase().startsWith("image/"));
963
- let generated = 0;
964
- return images.map(
965
- (file) => hasUsableName(file.name) ? file : new File([file], pastedImageName(file.type, at, generated++), { type: file.type, lastModified: file.lastModified })
966
- );
868
+ function chipAt(state, pos) {
869
+ const node = state.doc.nodeAt(pos);
870
+ return node && node.type.name === "reference" ? node : null;
967
871
  }
968
- var PastedImages = Extension5.create({
969
- name: "pastedImages",
970
- addOptions() {
971
- return { onImages: () => false };
972
- },
973
- addProseMirrorPlugins() {
974
- const options = this.options;
975
- return [
976
- new Plugin3({
977
- key: new PluginKey3("pastedImages"),
978
- props: {
979
- handlePaste: (_view, event) => {
980
- const files = pastedImages(event.clipboardData);
981
- return files.length > 0 && options.onImages(files);
982
- }
983
- }
984
- })
985
- ];
872
+ function justPlaced(tr, state) {
873
+ if (!tr.docChanged || tr.getMeta("history$") || tr.getMeta("preventUpdate")) return null;
874
+ const whole = tr.steps.some((step) => step instanceof ReplaceStep && step.from === 0 && step.to === tr.before.content.size);
875
+ if (whole && tr.getMeta("uiEvent") !== "paste") return null;
876
+ const made = tr.getMeta(CHIPS_MADE);
877
+ if (made && !made.pasted) return null;
878
+ const { selection } = state;
879
+ if (!selection.empty) return null;
880
+ let at = selection.from;
881
+ let before = selection.$from.nodeBefore;
882
+ if (!made && before?.isText && before.text === " ") {
883
+ at -= 1;
884
+ before = state.doc.resolve(at).nodeBefore;
986
885
  }
987
- });
988
-
989
- // src/PastedMarkdown.ts
990
- import { Extension as Extension6 } from "@tiptap/core";
991
- import { Slice } from "@tiptap/pm/model";
992
- import { Plugin as Plugin4, PluginKey as PluginKey4 } from "@tiptap/pm/state";
993
- function inTableCell($context) {
994
- for (let depth = $context.depth; depth > 0; depth--) {
995
- const role = $context.node(depth).type.spec.tableRole;
996
- if (role === "cell" || role === "header_cell") return true;
886
+ if (!before || before.type.name !== "reference" || !before.attrs.uri) return null;
887
+ const pos = at - before.nodeSize;
888
+ const old = tr.mapping.invert().map(pos);
889
+ const was = tr.before.nodeAt(old);
890
+ if (was && was.type.name === "reference" && was.attrs.uri === before.attrs.uri && tr.mapping.map(old, 1) === pos) return null;
891
+ return pos;
892
+ }
893
+ function dispatchMenu(view, next) {
894
+ view.dispatch(view.state.tr.setMeta(key3, next));
895
+ }
896
+ var passing = false;
897
+ function openChip(view, pos) {
898
+ const target = chipTarget(view, pos);
899
+ if (target) {
900
+ passing = true;
901
+ try {
902
+ target.click();
903
+ } finally {
904
+ passing = false;
905
+ }
906
+ return;
997
907
  }
998
- return false;
908
+ const href = webHref(view, pos);
909
+ if (href) window.open(href, "_blank", "noopener,noreferrer");
999
910
  }
1000
- var hasTable = (blocks) => blocks.some((block) => block.type === "table" || hasTable(block.content ?? []));
1001
- var PastedMarkdown = Extension6.create({
1002
- name: "pastedMarkdown",
1003
- addOptions() {
1004
- return { read: () => void 0 };
1005
- },
911
+ function choose(editor, pos, row) {
912
+ dispatchMenu(editor.view, null);
913
+ if (row === "open") openChip(editor.view, pos);
914
+ else if (row) setReferenceCardAt(editor, pos, row);
915
+ }
916
+ function isReferenceMenuOpen(state) {
917
+ return !!key3.getState(state);
918
+ }
919
+ function referenceMenuClick(editor, pos) {
920
+ if (passing || editor.isDestroyed || !editor.isEditable || key3.getState(editor.state) === void 0) return false;
921
+ if (!chipAt(editor.state, pos) || rowsOf(editor.view, pos).length === 0) return false;
922
+ editor.view.dispatch(caretAfter(editor.state, pos).setMeta(key3, { pos, active: -1 }));
923
+ return true;
924
+ }
925
+ function caretAfter(state, pos) {
926
+ const node = state.doc.nodeAt(pos);
927
+ return state.tr.setSelection(TextSelection.create(state.doc, pos + (node?.nodeSize ?? 1)));
928
+ }
929
+ var ReferenceMenu = Extension5.create({
930
+ name: "referenceMenu",
931
+ // Before the editor's own keys, so Enter on a highlighted row is the row's, not a new line.
932
+ priority: 1e3,
1006
933
  addProseMirrorPlugins() {
1007
- const options = this.options;
934
+ const editor = this.editor;
1008
935
  return [
1009
936
  new Plugin4({
1010
- key: new PluginKey4("pastedMarkdown"),
1011
- props: {
1012
- // Reached only for a text paste outside code; `plain` is the Shift paste.
1013
- clipboardTextParser: (text, $context, plain, view) => {
1014
- if (plain) return void 0;
1015
- try {
1016
- const blocks = options.read(text.replace(/\r\n?/g, "\n"))?.content ?? [];
1017
- if (blocks.every((block) => block.type === "paragraph")) return void 0;
1018
- if (inTableCell($context) && hasTable(blocks)) return void 0;
1019
- return Slice.maxOpen(view.state.schema.nodeFromJSON({ type: "doc", content: blocks }).content);
1020
- } catch {
1021
- return void 0;
1022
- }
937
+ key: key3,
938
+ state: {
939
+ init: () => null,
940
+ apply: (tr, value, before, after) => {
941
+ const meta = tr.getMeta(key3);
942
+ if (meta !== void 0) return meta;
943
+ const placed = justPlaced(tr, after);
944
+ if (placed !== null) return { pos: placed, active: -1 };
945
+ if (!value) return null;
946
+ const pos = tr.mapping.map(value.pos);
947
+ if (!chipAt(after, pos)) return null;
948
+ if (tr.docChanged && !tr.getMeta("appendedTransaction") && tr.getMeta(CHIPS_MADE) === void 0) return null;
949
+ const onChip = after.selection instanceof NodeSelection2 && after.selection.from === pos;
950
+ if (tr.selectionSet && !after.selection.eq(before.selection) && !onChip) return null;
951
+ return pos === value.pos ? value : { ...value, pos };
952
+ }
953
+ },
954
+ props: {
955
+ handleDOMEvents: {
956
+ // Focus gone, the keys no longer reach the menu, and a card chosen now would miss the save on leaving (code review).
957
+ blur: (view) => {
958
+ if (key3.getState(view.state)) dispatchMenu(view, null);
959
+ return false;
960
+ }
961
+ },
962
+ handleKeyDown: (view, event) => {
963
+ if (event.shiftKey || event.ctrlKey || event.metaKey || event.altKey) return false;
964
+ const open = key3.getState(view.state);
965
+ if (!open) {
966
+ const { selection } = view.state;
967
+ if (event.key !== "Enter" || !view.editable || !(selection instanceof NodeSelection2) || selection.node.type.name !== "reference") return false;
968
+ if (rowsOf(view, selection.from).length === 0) return false;
969
+ view.dispatch(caretAfter(view.state, selection.from).setMeta(key3, { pos: selection.from, active: 0 }));
970
+ return true;
971
+ }
972
+ const rows = rowsOf(view, open.pos);
973
+ if (event.key === "Escape") {
974
+ dispatchMenu(view, null);
975
+ return true;
976
+ }
977
+ if (rows.length === 0) return false;
978
+ if (event.key === "ArrowDown") {
979
+ dispatchMenu(view, { ...open, active: (open.active + 1) % rows.length });
980
+ return true;
981
+ }
982
+ if (event.key === "ArrowUp") {
983
+ dispatchMenu(view, { ...open, active: open.active <= 0 ? rows.length - 1 : open.active - 1 });
984
+ return true;
985
+ }
986
+ if (event.key === "Enter" && open.active >= 0) {
987
+ choose(editor, open.pos, rows[open.active]);
988
+ return true;
989
+ }
990
+ return false;
1023
991
  }
1024
992
  }
1025
993
  })
1026
994
  ];
1027
995
  }
1028
996
  });
1029
-
1030
- // src/CodeBlockColours.ts
1031
- import { CodeBlockLowlight } from "@tiptap/extension-code-block-lowlight";
1032
-
1033
- // src/codeColours.ts
1034
- import { createElement } from "react";
1035
- import { common, createLowlight } from "lowlight";
1036
- var instance;
1037
- function lowlight() {
1038
- return instance ??= createLowlight(common);
997
+ function ReferenceMenuView({ editor }) {
998
+ const shown = useEditorState({
999
+ editor,
1000
+ selector: ({ editor: ed }) => {
1001
+ if (!ed || ed.isDestroyed) return null;
1002
+ const open = key3.getState(ed.state);
1003
+ if (!open) return null;
1004
+ const node = chipAt(ed.state, open.pos);
1005
+ if (!node) return null;
1006
+ const embed = node.attrs.embed;
1007
+ const layout = embed === "detailed" ? "detailed" : typeof embed === "string" && embed !== "" && embed !== "none" ? "compact" : "none";
1008
+ return { pos: open.pos, active: open.active, named: !!node.attrs.uri, layout };
1009
+ }
1010
+ });
1011
+ const keepFocus2 = useCallback3((list) => {
1012
+ const panel = list?.closest('[role="dialog"]');
1013
+ if (!panel) return;
1014
+ const keep = (event) => event.preventDefault();
1015
+ panel.addEventListener("mousedown", keep);
1016
+ return () => panel.removeEventListener("mousedown", keep);
1017
+ }, []);
1018
+ const live = shown && editor && !editor.isDestroyed ? editor : null;
1019
+ const dom = live && shown ? live.view.nodeDOM(shown.pos) : null;
1020
+ const anchor = dom instanceof HTMLElement ? dom : null;
1021
+ const rows = live && shown ? rowsOf(live.view, shown.pos) : [];
1022
+ const opens = rows[0] === "open";
1023
+ const run = (row) => {
1024
+ if (editor && shown) choose(editor, shown.pos, row);
1025
+ };
1026
+ return (
1027
+ // finalFocus={false}: focus never left the text.
1028
+ /* @__PURE__ */ jsx4(
1029
+ Popover2,
1030
+ {
1031
+ anchor,
1032
+ open: !!shown && !!anchor && rows.length > 0,
1033
+ onOpenChange: (next) => {
1034
+ if (!next && editor && !editor.isDestroyed && key3.getState(editor.state)) dispatchMenu(editor.view, null);
1035
+ },
1036
+ side: "bottom",
1037
+ align: "left",
1038
+ ariaLabel: "Link",
1039
+ finalFocus: false,
1040
+ children: shown && /* @__PURE__ */ jsxs3("div", { ref: keepFocus2, role: "menu", "aria-label": "Link", className: "flex flex-col gap-0.5", children: [
1041
+ opens && /* @__PURE__ */ jsx4(
1042
+ MenuItem,
1043
+ {
1044
+ role: "menuitem",
1045
+ tabIndex: -1,
1046
+ label: "Open",
1047
+ selected: shown.active === 0,
1048
+ onMouseDown: (event) => {
1049
+ event.preventDefault();
1050
+ run("open");
1051
+ }
1052
+ }
1053
+ ),
1054
+ shown.named && /* @__PURE__ */ jsxs3(Fragment, { children: [
1055
+ opens && /* @__PURE__ */ jsx4(MenuSeparator, {}),
1056
+ /* @__PURE__ */ jsx4("div", { role: "group", "aria-label": "Card", children: /* @__PURE__ */ jsx4(MenuSection, { label: "Card", children: LAYOUTS.map(({ layout, label }, i) => /* @__PURE__ */ jsx4(
1057
+ MenuItem,
1058
+ {
1059
+ role: "menuitemradio",
1060
+ "aria-checked": shown.layout === layout,
1061
+ tabIndex: -1,
1062
+ label,
1063
+ selected: shown.active === i + (opens ? 1 : 0),
1064
+ trailing: shown.layout === layout ? /* @__PURE__ */ jsx4(IconCheck, { size: 16, "aria-hidden": true }) : void 0,
1065
+ onMouseDown: (event) => {
1066
+ event.preventDefault();
1067
+ run(layout);
1068
+ }
1069
+ },
1070
+ layout
1071
+ )) }) })
1072
+ ] })
1073
+ ] })
1074
+ }
1075
+ )
1076
+ );
1039
1077
  }
1040
1078
 
1041
- // src/CodeBlockColours.ts
1042
- var namedOnly = {
1043
- highlight: (language, value) => lowlight().highlight(language, value),
1044
- highlightAuto: (value) => ({ type: "root", children: [{ type: "text", value }], data: { language: void 0, relevance: 0 } }),
1045
- listLanguages: () => lowlight().listLanguages(),
1046
- registered: (language) => lowlight().registered(language)
1047
- };
1048
- var CodeBlockColours = CodeBlockLowlight.configure({ lowlight: namedOnly });
1049
-
1050
- // src/EditorBlockHandle.tsx
1051
- import { useMemo } from "react";
1052
- import { IconCopy, IconTrash } from "@tabler/icons-react";
1053
- import { BlockHandle, blockAtY } from "@estiva-app/ui";
1054
- import { Selection } from "@tiptap/pm/state";
1055
- import { MenuItem, MenuSub } from "@estiva-app/ui";
1056
-
1057
- // src/ComposerTriggers.tsx
1058
- import { Extension as Extension7 } from "@tiptap/core";
1059
- import { PluginKey as PluginKey5 } from "@tiptap/pm/state";
1060
- import Mention from "@tiptap/extension-mention";
1061
- import Suggestion from "@tiptap/suggestion";
1062
- import { NodeViewWrapper, ReactNodeViewRenderer } from "@tiptap/react";
1063
- import { Avatar } from "@estiva-app/ui";
1064
- import { EnterHint } from "@estiva-app/ui";
1065
- import { inlineChipClassName } from "@estiva-app/ui";
1066
- import { WithTooltip } from "@estiva-app/ui";
1067
- import { jsx as jsx5, jsxs as jsxs4 } from "react/jsx-runtime";
1068
- var PEOPLE_LIMIT = 6;
1069
- function filterPeople(people, query) {
1070
- const q = query.toLowerCase();
1071
- return people.filter((person) => q === "" || person.name.toLowerCase().includes(q)).slice(0, PEOPLE_LIMIT);
1079
+ // src/BlockNodes.tsx
1080
+ import { jsx as jsx5 } from "react/jsx-runtime";
1081
+ var BLOCK_TYPES = [
1082
+ "paragraph",
1083
+ "heading",
1084
+ "bulletList",
1085
+ "orderedList",
1086
+ "listItem",
1087
+ "blockquote",
1088
+ "codeBlock",
1089
+ "horizontalRule",
1090
+ // A table and everything inside it (UIG-18): a row or a cell whose id was
1091
+ // re-minted on each save would detach any comment anchored to it.
1092
+ "table",
1093
+ "tableRow",
1094
+ "tableHeader",
1095
+ "tableCell",
1096
+ // Without this an attachment's id is re-minted on every save, and every
1097
+ // comment anchored to it stops resolving.
1098
+ "attachment"
1099
+ ];
1100
+ var BLOCK_TYPE_SET = new Set(BLOCK_TYPES);
1101
+ function newBlockId() {
1102
+ return Array.from(crypto.getRandomValues(new Uint8Array(6)), (b) => b.toString(16).padStart(2, "0")).join("");
1072
1103
  }
1073
- function peopleMenu(urgent) {
1074
- const section = urgent ? "Urgent mention" : "People";
1075
- return {
1076
- ariaLabel: section,
1077
- // The people and the reference lists are the same box: 658px, capped at 360.
1078
- width: "w-[658px]",
1079
- maxHeight: "max-h-[360px]",
1080
- sections: (people) => [{ label: section, items: people, className: "px-3 py-1" }],
1081
- itemKey: (person) => person.id,
1082
- row: (person) => ({
1083
- label: person.name,
1084
- description: person.description,
1085
- leading: person.avatar ?? /* @__PURE__ */ jsx5(Avatar, { size: 32, alt: person.name }),
1086
- hint: /* @__PURE__ */ jsx5(EnterHint, {}),
1087
- size: "tall"
1088
- })
1089
- };
1104
+ function holdsText(node) {
1105
+ let found = false;
1106
+ node.descendants((child) => {
1107
+ if (found) return false;
1108
+ if (child.isText && child.text !== "" || child.type.name === "hardBreak" || child.type.name === "reference") found = true;
1109
+ return !found;
1110
+ });
1111
+ return found;
1090
1112
  }
1091
- function optionsOf(editor, name) {
1092
- return editor.extensionManager.extensions.find((one) => one.name === name)?.options;
1113
+ function claimsIn(doc2) {
1114
+ const claims = /* @__PURE__ */ new Map();
1115
+ doc2.descendants((node, pos, parent) => {
1116
+ const fixed = node.type.name === "unknownBlock";
1117
+ if (!fixed && !BLOCK_TYPE_SET.has(node.type.name)) return;
1118
+ if (parent?.type.name === "listItem" && LISTS.has(node.type.name)) return;
1119
+ const id = node.attrs.blockId;
1120
+ if (typeof id !== "string" || id === "") return;
1121
+ const copies = claims.get(id);
1122
+ if (copies) copies.push({ pos, node, fixed });
1123
+ else claims.set(id, [{ pos, node, fixed }]);
1124
+ });
1125
+ return claims;
1093
1126
  }
1094
- var listening = (stop) => ({
1095
- allowSpaces: true,
1096
- shouldShow: ({ query }) => !/^\s/.test(query) && !query.includes(stop)
1097
- });
1098
- function personSuggestion(urgent, name) {
1099
- return {
1100
- ...urgent ? { char: "!@" } : {},
1101
- // A second `@` starts another mention; the first one has ended.
1102
- ...listening("@"),
1103
- items: ({ query, editor }) => filterPeople(optionsOf(editor, name)?.people() ?? [], query),
1104
- render: suggestionPopup(peopleMenu(urgent)),
1105
- command: ({ editor, range, props: person }) => {
1106
- editor.chain().focus().insertContentAt(range, [
1107
- { type: name, attrs: { id: person.id, label: person.name, pubkey: person.pubkey ?? null } },
1108
- { type: "text", text: " " }
1109
- ]).run();
1110
- }
1111
- };
1127
+ function carriedOn(copies, before, mapping) {
1128
+ if (before.node.isLeaf) {
1129
+ const at2 = mapping.map(before.pos, 1);
1130
+ return copies.find((c) => c.pos === at2);
1131
+ }
1132
+ const at = mapping.map(textStart(before), 1);
1133
+ return copies.find((c) => c.pos < at && at < c.pos + c.node.nodeSize);
1112
1134
  }
1113
- var HEX_KEY = /^[0-9a-f]{64}$/;
1114
- var NOSTR_URI = /^nostr:[a-z0-9]+$/i;
1115
- var fromData = (name, valid) => ({
1116
- parseHTML: (element) => {
1117
- const value = element.getAttribute(`data-${name}`);
1118
- return value !== null && (!valid || valid.test(value)) ? value : null;
1119
- },
1120
- // The node's own `renderHTML` writes it.
1121
- renderHTML: () => ({})
1122
- });
1123
- var personAttributes = () => ({
1124
- id: { default: null, ...fromData("id") },
1125
- label: { default: null, ...fromData("label") },
1126
- /**
1127
- * The person's Nostr key, when they have one — SPEC §13.1. `id` is the app's
1128
- * own and means nothing to another app; this is what the body is written
1129
- * with, so a mention survives a rename.
1130
- */
1131
- pubkey: { default: null, ...fromData("pubkey", HEX_KEY) }
1132
- });
1133
- function personData(attrs) {
1134
- return {
1135
- "data-id": String(attrs.id ?? ""),
1136
- "data-label": String(attrs.label ?? ""),
1137
- ...typeof attrs.pubkey === "string" && attrs.pubkey ? { "data-pubkey": attrs.pubkey } : {}
1135
+ function textStart({ pos, node }) {
1136
+ let start = pos + 1;
1137
+ if (!node.isTextblock) {
1138
+ let found = false;
1139
+ node.descendants((child, at) => {
1140
+ if (found) return false;
1141
+ if (child.isTextblock) {
1142
+ start = pos + 1 + at + 1;
1143
+ found = true;
1144
+ }
1145
+ return !found;
1146
+ });
1147
+ }
1148
+ return start;
1149
+ }
1150
+ function repeatedBlockIds(doc2, before, mapping) {
1151
+ const claims = claimsIn(doc2);
1152
+ let previous;
1153
+ const losers = [];
1154
+ for (const [id, copies] of claims) {
1155
+ if (copies.length < 2) continue;
1156
+ previous ??= claimsIn(before);
1157
+ const original = previous.get(id)?.[0];
1158
+ const owner = copies.find((c) => c.fixed) ?? (original && carriedOn(copies, original, mapping)) ?? copies.find((c) => holdsText(c.node)) ?? copies[0];
1159
+ for (const copy of copies) if (copy !== owner && !copy.fixed) losers.push(copy.pos);
1160
+ }
1161
+ return losers;
1162
+ }
1163
+ var BLOCK_CONTAINERS = /* @__PURE__ */ new Set(["bulletList", "orderedList", "table", "tableRow", "tableHeader", "tableCell"]);
1164
+ var FLATTENED = /* @__PURE__ */ new Set(["listItem", "blockquote"]);
1165
+ var LISTS = /* @__PURE__ */ new Set(["bulletList", "orderedList"]);
1166
+ function innerLists(item, pos) {
1167
+ const out = [];
1168
+ item.forEach((child, offset) => {
1169
+ if (LISTS.has(child.type.name)) out.push({ pos: pos + 1 + offset, node: child });
1170
+ });
1171
+ return out;
1172
+ }
1173
+ var idOf = (node) => {
1174
+ const id = node.attrs.blockId;
1175
+ return typeof id === "string" && id !== "" ? id : void 0;
1176
+ };
1177
+ function addressedBlocks(doc2) {
1178
+ const out = [];
1179
+ const visit = (node, pos) => {
1180
+ if (!BLOCK_TYPE_SET.has(node.type.name)) return;
1181
+ out.push({ pos, node });
1182
+ if (BLOCK_CONTAINERS.has(node.type.name)) node.forEach((child, offset) => visit(child, pos + 1 + offset));
1183
+ if (node.type.name === "listItem") {
1184
+ for (const list of innerLists(node, pos)) list.node.forEach((child, offset) => visit(child, list.pos + 1 + offset));
1185
+ }
1138
1186
  };
1187
+ doc2.forEach((node, offset) => visit(node, offset));
1188
+ return out;
1139
1189
  }
1140
- var PersonMention = Mention.extend({
1141
- name: "mention",
1142
- addOptions() {
1143
- return { ...this.parent(), HTMLAttributes: {}, people: () => [], suggestion: personSuggestion(false, this.name) };
1144
- },
1145
- addAttributes: personAttributes,
1146
- renderHTML({ node }) {
1147
- return ["span", { "data-mention": "true", ...personData(node.attrs), class: inlineChipClassName("person", "cursor-default") }, `@${node.attrs.label}`];
1148
- },
1149
- parseHTML() {
1150
- return [{ tag: "span[data-mention]" }];
1190
+ function unnamedBlocks(doc2) {
1191
+ return addressedBlocks(doc2).filter((b) => idOf(b.node) === void 0).map((b) => b.pos);
1192
+ }
1193
+ function hiddenIds(doc2) {
1194
+ const out = [];
1195
+ doc2.descendants((node, pos) => {
1196
+ if (!FLATTENED.has(node.type.name)) return;
1197
+ node.forEach((child, offset) => {
1198
+ const inner = child.isTextblock || node.type.name === "listItem" && LISTS.has(child.type.name);
1199
+ if (inner && idOf(child) !== void 0) out.push(pos + 1 + offset);
1200
+ });
1201
+ });
1202
+ return out;
1203
+ }
1204
+ function handedOver(doc2, before, mapping, unnamed) {
1205
+ const out = /* @__PURE__ */ new Map();
1206
+ if (unnamed.length === 0) return out;
1207
+ const now = new Set(addressedBlocks(doc2).map((b) => idOf(b.node)));
1208
+ const gone = addressedBlocks(before).filter((b) => !b.node.isLeaf && idOf(b.node) !== void 0 && !now.has(idOf(b.node))).map((b) => ({ ...b, start: textStart(b) })).sort((a, b) => a.start - b.start || b.pos - a.pos);
1209
+ for (const old of gone) {
1210
+ const id = idOf(old.node);
1211
+ const { pos: at, deleted } = mapping.mapResult(old.start, -1);
1212
+ if (deleted) continue;
1213
+ let inner;
1214
+ for (const pos of unnamed) {
1215
+ if (out.has(pos)) continue;
1216
+ if (pos < at && at < pos + doc2.nodeAt(pos).nodeSize && (inner === void 0 || pos > inner)) inner = pos;
1217
+ }
1218
+ if (inner !== void 0) {
1219
+ out.set(inner, id);
1220
+ now.add(id);
1221
+ }
1151
1222
  }
1152
- });
1153
- var UrgentPersonMention = Mention.extend({
1154
- name: "urgentMention",
1155
- addOptions() {
1156
- return { ...this.parent(), HTMLAttributes: {}, people: () => [], suggestion: personSuggestion(true, this.name) };
1223
+ return out;
1224
+ }
1225
+ function bringsInBlocks(transactions) {
1226
+ return transactions.some(
1227
+ (tr) => tr.steps.some((step) => {
1228
+ if (step instanceof ReplaceAroundStep) return true;
1229
+ const slice = step.slice;
1230
+ let blocks = false;
1231
+ slice?.content.forEach((node) => {
1232
+ if (node.isBlock) blocks = true;
1233
+ });
1234
+ return blocks;
1235
+ })
1236
+ );
1237
+ }
1238
+ var BlockId = Extension6.create({
1239
+ name: "blockId",
1240
+ onCreate() {
1241
+ const { state, view } = this.editor;
1242
+ const unnamed = unnamedBlocks(state.doc);
1243
+ if (unnamed.length === 0) return;
1244
+ const tr = state.tr;
1245
+ for (const pos of unnamed) tr.setNodeAttribute(pos, "blockId", newBlockId());
1246
+ view.dispatch(tr.setMeta("addToHistory", false).setMeta("preventUpdate", true));
1157
1247
  },
1158
- addAttributes: personAttributes,
1159
- renderHTML({ node }) {
1248
+ addProseMirrorPlugins() {
1160
1249
  return [
1161
- "span",
1162
- { "data-urgent-mention": "true", ...personData(node.attrs), class: inlineChipClassName("urgent", "cursor-default") },
1163
- `@${node.attrs.label}`
1250
+ new Plugin5({
1251
+ key: new PluginKey5("blockIdSplit"),
1252
+ appendTransaction: (transactions, old, state) => {
1253
+ if (!bringsInBlocks(transactions)) return null;
1254
+ const mapping = new Mapping();
1255
+ for (const tr2 of transactions) mapping.appendMapping(tr2.mapping);
1256
+ const unnamed = unnamedBlocks(state.doc);
1257
+ const handed = handedOver(state.doc, old.doc, mapping, unnamed);
1258
+ const ids = /* @__PURE__ */ new Map();
1259
+ for (const pos of repeatedBlockIds(state.doc, old.doc, mapping)) ids.set(pos, newBlockId());
1260
+ for (const pos of unnamed) ids.set(pos, handed.get(pos) ?? newBlockId());
1261
+ for (const pos of hiddenIds(state.doc)) ids.set(pos, null);
1262
+ if (ids.size === 0) return null;
1263
+ const tr = state.tr;
1264
+ for (const [pos, id] of ids) tr.setNodeAttribute(pos, "blockId", id);
1265
+ return tr;
1266
+ }
1267
+ })
1164
1268
  ];
1165
1269
  },
1166
- parseHTML() {
1167
- return [{ tag: "span[data-urgent-mention]" }];
1270
+ addGlobalAttributes() {
1271
+ return [
1272
+ {
1273
+ types: BLOCK_TYPES,
1274
+ attributes: {
1275
+ blockId: {
1276
+ default: null,
1277
+ parseHTML: (element) => element.getAttribute("data-block-id"),
1278
+ renderHTML: (attributes) => attributes.blockId ? { "data-block-id": String(attributes.blockId) } : {}
1279
+ }
1280
+ }
1281
+ }
1282
+ ];
1168
1283
  }
1169
1284
  });
1170
- function urgentPubkeys(editor) {
1171
- const urgent = [];
1172
- editor.state.doc.descendants((node) => {
1173
- if (node.type.name === "urgentMention" && typeof node.attrs.pubkey === "string" && node.attrs.pubkey) urgent.push(node.attrs.pubkey);
1174
- });
1175
- return urgent.length > 0 ? urgent : void 0;
1176
- }
1177
- var REFERENCE_LIMIT = 6;
1178
- function filterReferences(items, query) {
1179
- const q = query.toLowerCase();
1180
- const shown = q ? items.filter((item) => (item.search ?? item.snippet).toLowerCase().includes(q) || item.label.toLowerCase().includes(q)) : [...items];
1181
- return shown.slice(-REFERENCE_LIMIT);
1182
- }
1183
- var captionOf = (label, snippet) => snippet ? `${label}: ${snippet}` : label;
1184
- var CaptionedReference = Mention.extend({
1185
- name: "captionedReference",
1285
+ var webUrl = (raw) => raw && /^https?:\/\/\S+$/i.test(raw) ? raw : null;
1286
+ var ReferenceNode = Node2.create({
1287
+ name: "reference",
1186
1288
  group: "inline",
1187
1289
  inline: true,
1188
1290
  atom: true,
1291
+ selectable: true,
1292
+ draggable: false,
1189
1293
  addOptions() {
1190
- return { ...this.parent(), HTMLAttributes: {}, icon: null, iconFor: void 0, suggestion: { char: "\0", items: () => [] } };
1294
+ return { view: null };
1191
1295
  },
1192
1296
  addAttributes() {
1193
1297
  return {
1194
- id: { default: null, ...fromData("id") },
1195
- label: { default: null, ...fromData("label") },
1196
- snippet: { default: "", parseHTML: (element) => element.getAttribute("data-snippet") ?? "", renderHTML: () => ({}) },
1197
- uri: { default: null, ...fromData("uri", NOSTR_URI) }
1298
+ // A pasted URL chip keeps only its URL: what it names is the editor's to resolve (`LinkChips`), never
1299
+ // the clipboard's, which could show one object while saving another URL (security review).
1300
+ uri: { default: "", parseHTML: (element) => webUrl(element.getAttribute("data-href")) ? "" : element.getAttribute("data-reference") ?? "" },
1301
+ marks: { default: [] },
1302
+ embed: { default: null, parseHTML: (element) => element.getAttribute("data-embed") },
1303
+ extra: { default: null, parseHTML: () => null },
1304
+ // An http(s) URL only: `LinkChips` makes no other, and a pasted `javascript:` must not reach a saved link.
1305
+ href: { default: null, parseHTML: (element) => webUrl(element.getAttribute("data-href")) }
1198
1306
  };
1199
1307
  },
1308
+ parseHTML() {
1309
+ return [{ tag: "span[data-reference]" }];
1310
+ },
1200
1311
  renderHTML({ node }) {
1201
- return [
1202
- "span",
1203
- { [`data-${this.name.replace(/[A-Z]/g, (c) => `-${c.toLowerCase()}`)}`]: "true", "data-id": String(node.attrs.id ?? ""), "data-label": String(node.attrs.label ?? ""), "data-snippet": String(node.attrs.snippet ?? ""), ...node.attrs.uri ? { "data-uri": String(node.attrs.uri) } : {}, class: inlineChipClassName("neutral", "cursor-default") },
1204
- captionOf(node.attrs.label, node.attrs.snippet)
1205
- ];
1312
+ const embed = typeof node.attrs.embed === "string" ? { "data-embed": node.attrs.embed } : {};
1313
+ const href = typeof node.attrs.href === "string" && node.attrs.href ? { "data-href": node.attrs.href } : {};
1314
+ return ["span", { "data-reference": String(node.attrs.uri), ...embed, ...href }, String(node.attrs.href || node.attrs.uri)];
1315
+ },
1316
+ renderText({ node }) {
1317
+ return String(node.attrs.href || node.attrs.uri);
1318
+ },
1319
+ addNodeView() {
1320
+ const View = this.options.view;
1321
+ if (!View) return null;
1322
+ return ReactNodeViewRenderer(({ node, editor, getPos }) => {
1323
+ const uri = String(node.attrs.uri ?? "");
1324
+ const href = typeof node.attrs.href === "string" && node.attrs.href ? node.attrs.href : void 0;
1325
+ return /* @__PURE__ */ jsx5(
1326
+ NodeViewWrapper,
1327
+ {
1328
+ as: "span",
1329
+ className: "inline",
1330
+ onClickCapture: (event) => {
1331
+ const pos = getPos();
1332
+ if (typeof pos !== "number" || !referenceMenuClick(editor, pos)) return;
1333
+ event.preventDefault();
1334
+ event.stopPropagation();
1335
+ },
1336
+ children: uri ? /* @__PURE__ */ jsx5(View, { uri, ...href ? { href } : {} }) : /* @__PURE__ */ jsx5("span", { children: href })
1337
+ }
1338
+ );
1339
+ });
1340
+ }
1341
+ });
1342
+ var UnknownBlock = Node2.create({
1343
+ name: "unknownBlock",
1344
+ group: "block",
1345
+ atom: true,
1346
+ selectable: true,
1347
+ addAttributes() {
1348
+ return {
1349
+ blockId: { default: null },
1350
+ source: { default: null },
1351
+ text: { default: "" }
1352
+ };
1206
1353
  },
1207
1354
  parseHTML() {
1208
- return [{ tag: `span[data-${this.name.replace(/[A-Z]/g, (c) => `-${c.toLowerCase()}`)}]` }];
1355
+ return [{ tag: "div[data-unknown-block]" }];
1356
+ },
1357
+ renderHTML({ node }) {
1358
+ return ["div", { "data-unknown-block": String(node.attrs.blockId ?? "") }, String(node.attrs.text ?? "")];
1209
1359
  },
1210
1360
  addNodeView() {
1211
- const { icon, iconFor } = this.options;
1212
- return ReactNodeViewRenderer(
1213
- ({ node }) => (
1214
- // The caption is cut at 24ch, so the whole of it is on hover, in the package's tooltip (UIG-14) — as Peek's sent chip has it.
1215
- /* @__PURE__ */ jsx5(NodeViewWrapper, { as: "span", children: /* @__PURE__ */ jsx5(WithTooltip, { inline: true, label: captionOf(node.attrs.label, node.attrs.snippet), children: /* @__PURE__ */ jsxs4("span", { className: inlineChipClassName("neutral", "max-w-[24ch] cursor-default"), children: [
1216
- /* @__PURE__ */ jsx5("span", { className: "flex items-center justify-center w-4 h-4 shrink-0 text-text-secondary", children: iconFor?.(node.attrs.uri ?? null) ?? icon }),
1217
- /* @__PURE__ */ jsx5("span", { className: "truncate", children: captionOf(node.attrs.label, node.attrs.snippet) })
1218
- ] }) }) })
1219
- ),
1220
- { as: "span" }
1221
- );
1361
+ return ReactNodeViewRenderer(UnknownBlockView);
1222
1362
  }
1223
1363
  });
1224
- function referenceMenu({ ariaLabel, sectionLabel, icon, iconFor }) {
1225
- return {
1226
- ariaLabel,
1227
- width: "w-[658px]",
1228
- maxHeight: "max-h-[360px]",
1229
- sections: (items) => {
1230
- const groups = [];
1231
- for (const item of items) {
1232
- const label = item.section ?? sectionLabel;
1233
- const last = groups[groups.length - 1];
1234
- if (last?.label === label) last.items.push(item);
1235
- else groups.push({ label, items: [item], className: "px-2" });
1236
- }
1237
- return groups;
1238
- },
1239
- itemKey: (item) => `reference-${item.id}`,
1240
- row: (item) => ({
1241
- leading: item.icon ?? iconFor?.(item.uri) ?? icon,
1242
- label: captionOf(item.label, item.snippet),
1243
- // A summary is the second line, and where the thing sits moves up beside the label (SUM-7's story).
1244
- ...item.summary ? { description: item.summary, aside: item.description } : { description: item.description },
1245
- hint: /* @__PURE__ */ jsx5(EnterHint, {})
1246
- })
1247
- };
1364
+ function UnknownBlockView({ node }) {
1365
+ const source = node.attrs.source;
1366
+ const text = String(node.attrs.text ?? "");
1367
+ return /* @__PURE__ */ jsx5(
1368
+ NodeViewWrapper,
1369
+ {
1370
+ "data-block-id": source?.id,
1371
+ "data-block-type": source?.type,
1372
+ className: "rounded-md border border-border-default bg-bg-inset px-2 py-1 text-text-secondary",
1373
+ children: text || `A ${source?.type ?? "block"} this app cannot edit yet.`
1374
+ }
1375
+ );
1248
1376
  }
1249
- var listed = (options, query) => options.sections ? options.sections(query).flatMap((section) => section.items.map((item) => ({ ...item, section: section.label }))) : filterReferences(options.items(), query);
1250
- var ReferenceTrigger = Extension7.create({
1251
- name: "referenceTrigger",
1377
+ var AttachmentNode = Node2.create({
1378
+ name: "attachment",
1379
+ group: "block",
1380
+ atom: true,
1381
+ selectable: true,
1382
+ draggable: false,
1252
1383
  addOptions() {
1253
- return { items: () => [], nodeName: "captionedReference", ariaLabel: "References", sectionLabel: "References", icon: null };
1384
+ return { view: null };
1254
1385
  },
1255
- addProseMirrorPlugins() {
1256
- const options = this.options;
1257
- return [
1258
- Suggestion({
1259
- editor: this.editor,
1260
- char: "[",
1261
- pluginKey: new PluginKey5("referenceTrigger"),
1262
- ...listening("]"),
1263
- // As a mention's: only where the chip may go.
1264
- allow: ({ state, range }) => {
1265
- const type = state.schema.nodes[options.nodeName];
1266
- return !!type && !!state.doc.resolve(range.from).parent.type.contentMatch.matchType(type);
1267
- },
1268
- items: ({ query }) => listed(options, query),
1269
- render: suggestionPopup({ ...referenceMenu(options), subscribe: options.subscribe, refresh: (query) => listed(options, query) }),
1270
- command: ({ editor, range, props: item }) => {
1271
- editor.chain().focus().insertContentAt(range, [
1272
- { type: options.nodeName, attrs: { id: item.id, label: item.label, snippet: item.snippet, uri: item.uri } },
1273
- { type: "text", text: " " }
1274
- ]).run();
1275
- }
1276
- })
1277
- ];
1386
+ addAttributes() {
1387
+ return {
1388
+ url: { default: "" },
1389
+ m: { default: "" },
1390
+ x: { default: "" },
1391
+ size: { default: 0 },
1392
+ dim: { default: null },
1393
+ thumb: { default: null },
1394
+ alt: { default: null },
1395
+ filename: { default: null }
1396
+ };
1397
+ },
1398
+ parseHTML() {
1399
+ return [{ tag: "div[data-attachment-block]" }];
1400
+ },
1401
+ renderHTML({ node }) {
1402
+ return ["div", { "data-attachment-block": String(node.attrs.x ?? "") }, String(node.attrs.filename ?? "attachment")];
1403
+ },
1404
+ addNodeView() {
1405
+ const View = this.options.view;
1406
+ if (!View) return null;
1407
+ return ReactNodeViewRenderer(({ node }) => /* @__PURE__ */ jsx5(NodeViewWrapper, { className: "my-2", children: /* @__PURE__ */ jsx5(View, { attrs: node.attrs }) }));
1278
1408
  }
1279
1409
  });
1280
- var offers = (editor, command) => !command.needs || command.needs.every((name) => editor.extensionManager.extensions.some((extension) => extension.name === name));
1281
- var FORMATS = [
1282
- { id: "paragraph", label: "Text" },
1283
- { id: "heading", label: "Heading", trigger: "#" },
1284
- { id: "subheading", label: "Subheading", trigger: "##" },
1285
- { id: "quote", label: "Quote", trigger: ">" },
1286
- { id: "code", label: "Code", trigger: "`", blockTrigger: "```" },
1287
- { id: "bulletList", label: "Bulleted list", trigger: "-" },
1288
- { id: "orderedList", label: "Numbered list", trigger: "1." }
1289
- ];
1290
- var DOCUMENT_FORMATS = [
1291
- { id: "checklist", label: "Checklist", trigger: "[]" },
1292
- { id: "note", label: "Note" },
1293
- { id: "warning", label: "Warning" }
1294
- ];
1295
- function applyFormat(editor, id, code = "inline") {
1296
- const chain = editor.chain().focus();
1297
- const run = (command, ...args) => {
1298
- const named2 = chain[command];
1299
- return named2 ? named2(...args).run() : false;
1410
+ var TICK = "checklistTick";
1411
+ function isChecklistTick(transaction) {
1412
+ return transaction.getMeta(TICK) === true;
1413
+ }
1414
+ function named(chain, command, ...args) {
1415
+ const own = chain[command];
1416
+ return own ? own(...args) : chain;
1417
+ }
1418
+ function itemAtCaret(state) {
1419
+ const { $from } = state.selection;
1420
+ if ($from.depth < 2) return null;
1421
+ const item = $from.node(-1);
1422
+ if (item.type.name !== "listItem" || $from.index(-1) !== 0) return null;
1423
+ return { node: item, pos: $from.before(-1) };
1424
+ }
1425
+ var sameAttrs = (a, b) => Object.keys({ ...a.attrs, ...b.attrs }).every((key4) => a.attrs[key4] === b.attrs[key4]);
1426
+ function listItemView(editor, node, view, getPos) {
1427
+ const toDOM = node.type.spec.toDOM;
1428
+ const { dom, contentDOM } = toDOM ? DOMSerializer.renderSpec(document, toDOM(node)) : { dom: document.createElement("li"), contentDOM: void 0 };
1429
+ const checked = node.attrs.checked;
1430
+ if (typeof checked !== "boolean") return { dom, contentDOM: contentDOM ?? dom, update: (next) => next.type === node.type && sameAttrs(next, node) };
1431
+ const li = dom;
1432
+ const box = document.createElement("span");
1433
+ box.contentEditable = "false";
1434
+ box.setAttribute("data-checklist-box", "");
1435
+ const body = document.createElement("div");
1436
+ li.replaceChildren(box, body);
1437
+ const tick = (next) => {
1438
+ const pos = getPos();
1439
+ if (pos === void 0 || !view.editable) return;
1440
+ view.dispatch(view.state.tr.setNodeAttribute(pos, "checked", next).setMeta(TICK, true));
1300
1441
  };
1301
- switch (id) {
1302
- case "paragraph":
1303
- return run("setParagraph");
1304
- case "heading":
1305
- return run("setHeading", { level: 1 });
1306
- case "subheading":
1307
- return run("setHeading", { level: 2 });
1308
- case "quote":
1309
- return run("toggleBlockquote");
1310
- case "bulletList":
1311
- return run("toggleBulletList");
1312
- case "orderedList":
1313
- return run("toggleOrderedList");
1314
- case "code":
1315
- return run(code === "block" ? "toggleCodeBlock" : "toggleCode");
1316
- case "checklist": {
1317
- if (!editor.isActive("listItem") && !run("toggleBulletList")) return false;
1318
- if (typeof editor.getAttributes("listItem").checked === "boolean") return true;
1319
- return editor.chain().updateAttributes("listItem", { checked: false }).run();
1320
- }
1321
- case "note":
1322
- case "warning": {
1323
- if (!editor.isActive("blockquote") && !run("toggleBlockquote")) return false;
1324
- return editor.chain().updateAttributes("blockquote", { tone: id }).run();
1442
+ let words = node.firstChild?.textContent.trim() || "Item";
1443
+ const props = () => ({ checked, onChange: view.editable ? tick : void 0, "aria-label": words });
1444
+ const renderer = new ReactRenderer2(Checkbox, { editor, props: props(), as: "span" });
1445
+ box.appendChild(renderer.element);
1446
+ let drawn = "";
1447
+ const sync = () => {
1448
+ const now = `${view.editable}:${words}`;
1449
+ if (now === drawn) return;
1450
+ drawn = now;
1451
+ renderer.updateProps(props());
1452
+ for (const [name, value] of Object.entries({ role: "checkbox", "aria-checked": String(checked), "aria-readonly": "true", "aria-label": words })) {
1453
+ if (view.editable) box.removeAttribute(name);
1454
+ else box.setAttribute(name, value);
1325
1455
  }
1326
- default:
1327
- return false;
1328
- }
1329
- }
1330
- var KEYWORDS = {
1331
- checklist: ["todo", "task"],
1332
- note: ["callout"],
1333
- warning: ["callout"]
1334
- };
1335
- var NEEDS = {
1336
- checklist: ["checklist"],
1337
- note: ["callout"],
1338
- warning: ["callout"]
1339
- };
1340
- function formatSection(code = "inline") {
1341
- return {
1342
- label: "Format",
1343
- commands: (code === "block" ? [...FORMATS, ...DOCUMENT_FORMATS] : FORMATS).map((format) => ({
1344
- key: `format-${format.id}`,
1345
- row: { label: format.label, shortcut: code === "block" && format.blockTrigger || format.trigger },
1346
- keywords: [format.id, ...KEYWORDS[format.id] ?? []],
1347
- ...NEEDS[format.id] ? { needs: NEEDS[format.id] } : {},
1348
- run: (editor) => {
1349
- applyFormat(editor, format.id, code);
1350
- }
1351
- }))
1352
1456
  };
1353
- }
1354
- function typeTrigger(input) {
1355
- return (editor) => {
1356
- requestAnimationFrame(() => editor.commands.insertContent(input));
1457
+ sync();
1458
+ editor.on("update", sync);
1459
+ return {
1460
+ dom: li,
1461
+ contentDOM: body,
1462
+ update: (next) => {
1463
+ if (next.type !== node.type || !sameAttrs(next, node)) return false;
1464
+ words = next.firstChild?.textContent.trim() || "Item";
1465
+ sync();
1466
+ return true;
1467
+ },
1468
+ stopEvent: (event) => box.contains(event.target),
1469
+ ignoreMutation: (mutation) => box.contains(mutation.target),
1470
+ destroy: () => {
1471
+ editor.off("update", sync);
1472
+ renderer.destroy();
1473
+ }
1357
1474
  };
1358
1475
  }
1359
- function matches(command, q) {
1360
- return [command.row.label, ...command.keywords ?? []].some((text) => text.toLowerCase().includes(q));
1361
- }
1362
- function filterSlashSections(sections, query) {
1363
- const q = query.toLowerCase();
1364
- return sections.map((section) => ({ ...section, commands: q ? section.commands.filter((command) => matches(command, q)) : section.commands }));
1365
- }
1366
- var SlashCommands = Extension7.create({
1367
- name: "slashCommands",
1368
- addOptions() {
1369
- return { sections: [formatSection()] };
1476
+ var Checklist = Extension6.create({
1477
+ name: "checklist",
1478
+ // Before the list item's own Enter and Backspace.
1479
+ priority: 101,
1480
+ addGlobalAttributes() {
1481
+ return [
1482
+ {
1483
+ types: ["listItem"],
1484
+ attributes: {
1485
+ checked: {
1486
+ default: null,
1487
+ keepOnSplit: false,
1488
+ parseHTML: (element) => {
1489
+ const value = element.getAttribute("data-checked");
1490
+ return value === "true" ? true : value === "false" ? false : null;
1491
+ },
1492
+ renderHTML: (attributes) => typeof attributes.checked === "boolean" ? { "data-checked": String(attributes.checked) } : {}
1493
+ }
1494
+ }
1495
+ }
1496
+ ];
1370
1497
  },
1371
- addProseMirrorPlugins() {
1372
- const sections = this.options.sections;
1498
+ addInputRules() {
1373
1499
  return [
1374
- Suggestion({
1375
- editor: this.editor,
1376
- char: "/",
1377
- startOfLine: false,
1378
- pluginKey: new PluginKey5("slashCommands"),
1379
- items: ({ query, editor }) => filterSlashSections(sections, query).flatMap(
1380
- (section, at) => section.commands.filter((command) => offers(editor, command)).map((command) => ({ ...command, section: at }))
1381
- ),
1382
- command: ({ editor, range, props }) => {
1383
- editor.chain().focus().deleteRange(range).run();
1384
- props.run(editor);
1385
- },
1386
- render: suggestionPopup({
1387
- ariaLabel: "Commands",
1388
- width: "w-[300px]",
1389
- maxHeight: "max-h-[400px]",
1390
- sections: (rows) => sections.map((section, at) => ({ label: section.label, items: rows.filter((row) => row.section === at) })),
1391
- itemKey: (row) => row.key,
1392
- row: (row) => row.row
1393
- })
1500
+ new InputRule({
1501
+ find: /^\[([ xX]?)\]\s$/,
1502
+ handler: ({ state, range, match, chain }) => {
1503
+ const checked = match[1].toLowerCase() === "x";
1504
+ const inList = itemAtCaret(state) !== null;
1505
+ if (!inList && !chain().toggleBulletList) return null;
1506
+ const deleted = chain().deleteRange(range);
1507
+ const listed2 = inList ? deleted : named(deleted, "toggleBulletList");
1508
+ listed2.updateAttributes("listItem", { checked }).run();
1509
+ }
1510
+ })
1511
+ ];
1512
+ },
1513
+ addKeyboardShortcuts() {
1514
+ return {
1515
+ Enter: () => {
1516
+ const { state } = this.editor;
1517
+ const item = itemAtCaret(state);
1518
+ const { $from, empty } = state.selection;
1519
+ if (!item || typeof item.node.attrs.checked !== "boolean") return false;
1520
+ if (!empty) return this.editor.chain().deleteSelection().splitListItem("listItem", { checked: false }).run();
1521
+ if ($from.parent.content.size === 0) return false;
1522
+ if ($from.parentOffset > 0) return this.editor.commands.splitListItem("listItem", { checked: false });
1523
+ return this.editor.chain().splitListItem("listItem", { checked: item.node.attrs.checked }).command(({ tr }) => {
1524
+ tr.setNodeAttribute(tr.mapping.map(item.pos), "checked", false);
1525
+ return true;
1526
+ }).run();
1527
+ },
1528
+ Backspace: () => {
1529
+ const { state } = this.editor;
1530
+ const item = itemAtCaret(state);
1531
+ const { $from, empty } = state.selection;
1532
+ if (!item || !empty || $from.parentOffset > 0 || typeof item.node.attrs.checked !== "boolean") return false;
1533
+ this.editor.view.dispatch(state.tr.setNodeAttribute(item.pos, "checked", null));
1534
+ return true;
1535
+ }
1536
+ };
1537
+ },
1538
+ addProseMirrorPlugins() {
1539
+ const editor = this.editor;
1540
+ return [
1541
+ new Plugin5({
1542
+ key: new PluginKey5("checklist"),
1543
+ props: { nodeViews: { listItem: (node, view, getPos) => listItemView(editor, node, view, getPos) } }
1394
1544
  })
1395
1545
  ];
1396
1546
  }
1397
1547
  });
1548
+ var Callout = Extension6.create({
1549
+ name: "callout",
1550
+ addGlobalAttributes() {
1551
+ return [
1552
+ {
1553
+ types: ["blockquote"],
1554
+ attributes: {
1555
+ tone: {
1556
+ default: null,
1557
+ parseHTML: (element) => element.getAttribute("data-tone"),
1558
+ // As `RichText` draws it: the tone as written, and the look it is drawn in.
1559
+ renderHTML: (attributes) => typeof attributes.tone === "string" ? { "data-tone": attributes.tone, "data-callout": calloutLook(attributes.tone) } : {}
1560
+ }
1561
+ }
1562
+ }
1563
+ ];
1564
+ }
1565
+ });
1398
1566
 
1399
- // src/EditorBlockHandle.tsx
1400
- import { Fragment, jsx as jsx6, jsxs as jsxs5 } from "react/jsx-runtime";
1401
- function editorBlocks(view) {
1402
- const out = [];
1403
- view.state.doc.forEach((node, pos) => {
1404
- const element = view.nodeDOM(pos);
1405
- if (element instanceof HTMLElement) out.push({ id: node.attrs.blockId || void 0, element, pos });
1406
- });
1407
- return out;
1567
+ // src/CommentBox.tsx
1568
+ import { Button } from "@estiva-app/ui";
1569
+ import { Card } from "@estiva-app/ui";
1570
+ import { cn as cn2 } from "@estiva-app/ui";
1571
+
1572
+ // src/ComposerTriggers.tsx
1573
+ import { Extension as Extension7 } from "@tiptap/core";
1574
+ import { PluginKey as PluginKey6 } from "@tiptap/pm/state";
1575
+ import Mention from "@tiptap/extension-mention";
1576
+ import Suggestion from "@tiptap/suggestion";
1577
+ import { NodeViewWrapper as NodeViewWrapper2, ReactNodeViewRenderer as ReactNodeViewRenderer2 } from "@tiptap/react";
1578
+ import { Avatar } from "@estiva-app/ui";
1579
+ import { EnterHint } from "@estiva-app/ui";
1580
+ import { inlineChipClassName } from "@estiva-app/ui";
1581
+ import { WithTooltip } from "@estiva-app/ui";
1582
+ import { jsx as jsx6, jsxs as jsxs4 } from "react/jsx-runtime";
1583
+ var PEOPLE_LIMIT = 6;
1584
+ function filterPeople(people, query) {
1585
+ const q = query.toLowerCase();
1586
+ return people.filter((person) => q === "" || person.name.toLowerCase().includes(q)).slice(0, PEOPLE_LIMIT);
1408
1587
  }
1409
- function duplicateBlock(editor, pos) {
1410
- const node = editor.state.doc.nodeAt(pos);
1411
- if (!node) return false;
1412
- editor.view.dispatch(editor.state.tr.insert(pos + node.nodeSize, node).scrollIntoView());
1413
- editor.commands.focus(pos + node.nodeSize + 1);
1414
- return true;
1588
+ function peopleMenu(urgent) {
1589
+ const section = urgent ? "Urgent mention" : "People";
1590
+ return {
1591
+ ariaLabel: section,
1592
+ // The people and the reference lists are the same box: 658px, capped at 360.
1593
+ width: "w-[658px]",
1594
+ maxHeight: "max-h-[360px]",
1595
+ sections: (people) => [{ label: section, items: people, className: "px-3 py-1" }],
1596
+ itemKey: (person) => person.id,
1597
+ row: (person) => ({
1598
+ label: person.name,
1599
+ description: person.description,
1600
+ leading: person.avatar ?? /* @__PURE__ */ jsx6(Avatar, { size: 32, alt: person.name }),
1601
+ hint: /* @__PURE__ */ jsx6(EnterHint, {}),
1602
+ size: "tall"
1603
+ })
1604
+ };
1415
1605
  }
1416
- function deleteBlock(editor, pos) {
1417
- const { state } = editor;
1418
- const node = state.doc.nodeAt(pos);
1419
- if (!node) return false;
1420
- const tr = state.doc.childCount === 1 ? state.tr.replaceWith(pos, pos + node.nodeSize, state.schema.nodes.paragraph.create()) : state.tr.delete(pos, pos + node.nodeSize);
1421
- editor.view.dispatch(tr);
1422
- editor.commands.focus(Math.min(pos + 1, editor.state.doc.content.size));
1423
- return true;
1606
+ function optionsOf(editor, name) {
1607
+ return editor.extensionManager.extensions.find((one) => one.name === name)?.options;
1424
1608
  }
1425
- function moveBlock(editor, from, to) {
1426
- const node = editor.state.doc.nodeAt(from);
1427
- if (!node || to >= from && to <= from + node.nodeSize) return false;
1428
- const tr = editor.state.tr.delete(from, from + node.nodeSize);
1429
- const at = tr.mapping.map(to);
1430
- editor.view.dispatch(tr.insert(at, node).scrollIntoView());
1431
- editor.commands.focus(at + 1);
1432
- return true;
1609
+ var listening = (stop) => ({
1610
+ allowSpaces: true,
1611
+ shouldShow: ({ query }) => !/^\s/.test(query) && !query.includes(stop)
1612
+ });
1613
+ function personSuggestion(urgent, name) {
1614
+ return {
1615
+ ...urgent ? { char: "!@" } : {},
1616
+ // A second `@` starts another mention; the first one has ended.
1617
+ ...listening("@"),
1618
+ items: ({ query, editor }) => filterPeople(optionsOf(editor, name)?.people() ?? [], query),
1619
+ render: suggestionPopup(peopleMenu(urgent)),
1620
+ command: ({ editor, range, props: person }) => {
1621
+ editor.chain().focus().insertContentAt(range, [
1622
+ { type: name, attrs: { id: person.id, label: person.name, pubkey: person.pubkey ?? null } },
1623
+ { type: "text", text: " " }
1624
+ ]).run();
1625
+ }
1626
+ };
1433
1627
  }
1434
- function startBlockDrag(editor, pos, event, image) {
1435
- editor.commands.setNodeSelection(pos);
1436
- const { view } = editor;
1437
- const slice = view.state.selection.content();
1438
- const { dom, text } = view.serializeForClipboard(slice);
1439
- const transfer = event.dataTransfer;
1440
- if (transfer) {
1441
- transfer.clearData();
1442
- transfer.setData("text/html", dom.innerHTML);
1443
- transfer.setData("text/plain", text);
1444
- transfer.effectAllowed = "copyMove";
1445
- if (image) transfer.setDragImage(image, 0, 0);
1628
+ var HEX_KEY = /^[0-9a-f]{64}$/;
1629
+ var NOSTR_URI = /^nostr:[a-z0-9]+$/i;
1630
+ var fromData = (name, valid) => ({
1631
+ parseHTML: (element) => {
1632
+ const value = element.getAttribute(`data-${name}`);
1633
+ return value !== null && (!valid || valid.test(value)) ? value : null;
1634
+ },
1635
+ // The node's own `renderHTML` writes it.
1636
+ renderHTML: () => ({})
1637
+ });
1638
+ var personAttributes = () => ({
1639
+ id: { default: null, ...fromData("id") },
1640
+ label: { default: null, ...fromData("label") },
1641
+ /**
1642
+ * The person's Nostr key, when they have one — SPEC §13.1. `id` is the app's
1643
+ * own and means nothing to another app; this is what the body is written
1644
+ * with, so a mention survives a rename.
1645
+ */
1646
+ pubkey: { default: null, ...fromData("pubkey", HEX_KEY) }
1647
+ });
1648
+ function personData(attrs) {
1649
+ return {
1650
+ "data-id": String(attrs.id ?? ""),
1651
+ "data-label": String(attrs.label ?? ""),
1652
+ ...typeof attrs.pubkey === "string" && attrs.pubkey ? { "data-pubkey": attrs.pubkey } : {}
1653
+ };
1654
+ }
1655
+ var PersonMention = Mention.extend({
1656
+ name: "mention",
1657
+ addOptions() {
1658
+ return { ...this.parent(), HTMLAttributes: {}, people: () => [], suggestion: personSuggestion(false, this.name) };
1659
+ },
1660
+ addAttributes: personAttributes,
1661
+ renderHTML({ node }) {
1662
+ return ["span", { "data-mention": "true", ...personData(node.attrs), class: inlineChipClassName("person", "cursor-default") }, `@${node.attrs.label}`];
1663
+ },
1664
+ parseHTML() {
1665
+ return [{ tag: "span[data-mention]" }];
1446
1666
  }
1447
- view.dragging = { slice, move: true };
1667
+ });
1668
+ var UrgentPersonMention = Mention.extend({
1669
+ name: "urgentMention",
1670
+ addOptions() {
1671
+ return { ...this.parent(), HTMLAttributes: {}, people: () => [], suggestion: personSuggestion(true, this.name) };
1672
+ },
1673
+ addAttributes: personAttributes,
1674
+ renderHTML({ node }) {
1675
+ return [
1676
+ "span",
1677
+ { "data-urgent-mention": "true", ...personData(node.attrs), class: inlineChipClassName("urgent", "cursor-default") },
1678
+ `@${node.attrs.label}`
1679
+ ];
1680
+ },
1681
+ parseHTML() {
1682
+ return [{ tag: "span[data-urgent-mention]" }];
1683
+ }
1684
+ });
1685
+ function urgentPubkeys(editor) {
1686
+ const urgent = [];
1687
+ editor.state.doc.descendants((node) => {
1688
+ if (node.type.name === "urgentMention" && typeof node.attrs.pubkey === "string" && node.attrs.pubkey) urgent.push(node.attrs.pubkey);
1689
+ });
1690
+ return urgent.length > 0 ? urgent : void 0;
1448
1691
  }
1449
- var blockDropCursor = { color: false, class: "bg-accent-primary" };
1450
- var NOTHING_YET = { find: () => null, rows: () => null, startDrag: () => {
1451
- }, drop: () => {
1452
- }, endDrag: () => {
1453
- }, onChange: () => () => {
1454
- } };
1455
- function EditorBlockHandle({ editor, turnInto = turnIntoRows, actions, children, className }) {
1456
- const editing = useMemo(() => {
1457
- if (!editor) return NOTHING_YET;
1458
- let dragged;
1692
+ var REFERENCE_LIMIT = 6;
1693
+ function filterReferences(items, query) {
1694
+ const q = query.toLowerCase();
1695
+ const shown = q ? items.filter((item) => (item.search ?? item.snippet).toLowerCase().includes(q) || item.label.toLowerCase().includes(q)) : [...items];
1696
+ return shown.slice(-REFERENCE_LIMIT);
1697
+ }
1698
+ var captionOf = (label, snippet) => snippet ? `${label}: ${snippet}` : label;
1699
+ var CaptionedReference = Mention.extend({
1700
+ name: "captionedReference",
1701
+ group: "inline",
1702
+ inline: true,
1703
+ atom: true,
1704
+ addOptions() {
1705
+ return { ...this.parent(), HTMLAttributes: {}, icon: null, iconFor: void 0, suggestion: { char: "\0", items: () => [] } };
1706
+ },
1707
+ addAttributes() {
1459
1708
  return {
1460
- find: (y) => blockAtY(editorBlocks(editor.view), y),
1461
- rows: (block) => {
1462
- const pos = block.pos;
1463
- if (!editor.isEditable) return null;
1464
- const node = pos === void 0 ? null : editor.state.doc.nodeAt(pos);
1465
- if (pos === void 0 || !node) return null;
1466
- const turnRows = typeof turnInto === "function" ? turnInto(node, editor) : node.isTextblock ? turnInto : [];
1467
- return /* @__PURE__ */ jsxs5(Fragment, { children: [
1468
- turnRows.length > 0 && /* @__PURE__ */ jsx6(MenuSub, { label: "Turn into", children: turnRows.map((row) => /* @__PURE__ */ jsx6(
1469
- MenuItem,
1470
- {
1471
- label: row.label,
1472
- selected: row.active?.(node) ?? false,
1473
- onClick: () => {
1474
- if (node.isTextblock) editor.chain().focus().setTextSelection(pos + 1).run();
1475
- row.run(editor, pos);
1476
- }
1477
- },
1478
- row.label
1479
- )) }),
1480
- /* @__PURE__ */ jsx6(MenuItem, { label: "Duplicate", leading: /* @__PURE__ */ jsx6(IconCopy, { size: 16, stroke: 1.5, className: "text-text-secondary" }), onClick: () => duplicateBlock(editor, pos) }),
1481
- /* @__PURE__ */ jsx6(MenuItem, { label: "Delete", destructive: true, leading: /* @__PURE__ */ jsx6(IconTrash, { size: 16, stroke: 1.5, className: "text-error-default" }), onClick: () => deleteBlock(editor, pos) })
1482
- ] });
1483
- },
1484
- startDrag: (block, event) => {
1485
- dragged = block.pos;
1486
- if (block.pos !== void 0) startBlockDrag(editor, block.pos, event, block.element);
1487
- },
1488
- drop: (target, after) => {
1489
- const node = target.pos === void 0 ? null : editor.state.doc.nodeAt(target.pos);
1490
- if (dragged === void 0 || target.pos === void 0 || !node) return;
1491
- moveBlock(editor, dragged, after ? target.pos + node.nodeSize : target.pos);
1492
- },
1493
- // ProseMirror clears `dragging` on its own dragend, which a drag started outside its element never reaches.
1494
- endDrag: () => setTimeout(() => editor.view.dragging = null, 50),
1495
- onChange: (changed) => {
1496
- editor.on("update", changed);
1497
- return () => {
1498
- editor.off("update", changed);
1499
- };
1500
- }
1709
+ id: { default: null, ...fromData("id") },
1710
+ label: { default: null, ...fromData("label") },
1711
+ snippet: { default: "", parseHTML: (element) => element.getAttribute("data-snippet") ?? "", renderHTML: () => ({}) },
1712
+ uri: { default: null, ...fromData("uri", NOSTR_URI) }
1501
1713
  };
1502
- }, [editor, turnInto]);
1503
- return /* @__PURE__ */ jsx6(BlockHandle, { editing, actions, className, children });
1504
- }
1505
- var LISTS2 = ["bulletList", "orderedList"];
1506
- var isList = (node) => LISTS2.includes(node.type.name);
1507
- function listItems(list, at) {
1508
- const out = [];
1509
- list.descendants((node, pos) => {
1510
- if (node.type.name === "listItem") out.push({ node, pos: at + 1 + pos });
1511
- });
1512
- return out;
1513
- }
1514
- var isChecklistItem = ({ node }) => typeof node.attrs.checked === "boolean";
1515
- var isChecklist = (list) => listItems(list, 0).every(isChecklistItem);
1516
- var isPlainList = (list, type) => list.type.name === type && !listItems(list, 0).some(isChecklistItem);
1517
- var hasExtension = (editor, name) => editor.extensionManager.extensions.some((e) => e.name === name);
1518
- function caretInto(editor, pos) {
1519
- const { state } = editor;
1520
- editor.view.dispatch(state.tr.setSelection(Selection.near(state.doc.resolve(Math.min(pos + 1, state.doc.content.size)))));
1521
- editor.commands.focus();
1522
- }
1523
- function turnListInto(editor, pos, kind) {
1524
- const { state } = editor;
1525
- const list = state.doc.nodeAt(pos);
1526
- if (!list || !isList(list)) return false;
1527
- const tr = state.tr;
1528
- if (kind === "text") {
1529
- const blocks = [];
1530
- for (const { node: item } of listItems(list, pos)) {
1531
- item.forEach((child, _offset, index) => {
1532
- if (isList(child)) return;
1533
- blocks.push(child.type.create({ ...child.attrs, blockId: index === 0 ? item.attrs.blockId : null }, child.content, child.marks));
1534
- });
1535
- }
1536
- tr.replaceWith(pos, pos + list.nodeSize, blocks);
1537
- } else {
1538
- const type = kind === "checklist" ? list.type : state.schema.nodes[kind];
1539
- if (list.type !== type) tr.setNodeMarkup(pos, type, list.attrs);
1540
- list.descendants((node, at) => {
1541
- if (isList(node) && node.type !== type) tr.setNodeMarkup(pos + 1 + at, type, node.attrs);
1542
- });
1543
- for (const { node, pos: at } of listItems(list, pos)) {
1544
- const checked = kind === "checklist" ? typeof node.attrs.checked === "boolean" ? node.attrs.checked : false : null;
1545
- if (node.attrs.checked !== checked) tr.setNodeAttribute(at, "checked", checked);
1546
- }
1547
- }
1548
- if (tr.docChanged) editor.view.dispatch(tr.scrollIntoView());
1549
- caretInto(editor, pos);
1550
- return true;
1551
- }
1552
- function turnQuoteInto(editor, pos, kind) {
1553
- const { state } = editor;
1554
- const quote = state.doc.nodeAt(pos);
1555
- if (!quote || quote.type.name !== "blockquote") return false;
1556
- const tr = state.tr;
1557
- if (kind === "text") {
1558
- const blocks = [];
1559
- quote.forEach((child) => blocks.push(blocks.length === 0 ? child.type.create({ ...child.attrs, blockId: quote.attrs.blockId }, child.content, child.marks) : child));
1560
- tr.replaceWith(pos, pos + quote.nodeSize, blocks);
1561
- } else {
1562
- const tone = kind === "quote" ? null : kind;
1563
- if ((quote.attrs.tone ?? null) !== tone) tr.setNodeAttribute(pos, "tone", tone);
1564
- }
1565
- if (tr.docChanged) editor.view.dispatch(tr.scrollIntoView());
1566
- caretInto(editor, pos);
1567
- return true;
1568
- }
1569
- function isFormat(node, id) {
1570
- if (id === "paragraph") return node.type.name === "paragraph";
1571
- if (id === "heading") return node.type.name === "heading" && node.attrs.level === 1;
1572
- if (id === "subheading") return node.type.name === "heading" && node.attrs.level === 2;
1573
- if (id === "code") return node.type.name === "codeBlock";
1574
- return false;
1575
- }
1576
- function turnIntoRows(node, editor) {
1577
- const checklist = hasExtension(editor, "checklist");
1578
- const callout = hasExtension(editor, "callout");
1579
- if (node.isTextblock) {
1580
- const document2 = DOCUMENT_FORMATS.filter((f) => f.id === "checklist" ? checklist : callout);
1581
- return [...FORMATS, ...document2].map((format) => ({
1582
- label: format.label,
1583
- run: (e) => void applyFormat(e, format.id, "block"),
1584
- active: (n) => isFormat(n, format.id)
1585
- }));
1586
- }
1587
- if (isList(node)) {
1588
- const rows = [
1589
- { label: "Bulleted list", run: (e, pos) => void turnListInto(e, pos, "bulletList"), active: (n) => isPlainList(n, "bulletList") },
1590
- { label: "Numbered list", run: (e, pos) => void turnListInto(e, pos, "orderedList"), active: (n) => isPlainList(n, "orderedList") }
1714
+ },
1715
+ renderHTML({ node }) {
1716
+ return [
1717
+ "span",
1718
+ { [`data-${this.name.replace(/[A-Z]/g, (c) => `-${c.toLowerCase()}`)}`]: "true", "data-id": String(node.attrs.id ?? ""), "data-label": String(node.attrs.label ?? ""), "data-snippet": String(node.attrs.snippet ?? ""), ...node.attrs.uri ? { "data-uri": String(node.attrs.uri) } : {}, class: inlineChipClassName("neutral", "cursor-default") },
1719
+ captionOf(node.attrs.label, node.attrs.snippet)
1591
1720
  ];
1592
- if (checklist) rows.push({ label: "Checklist", run: (e, pos) => void turnListInto(e, pos, "checklist"), active: isChecklist });
1593
- rows.push({ label: "Text", run: (e, pos) => void turnListInto(e, pos, "text") });
1594
- return rows;
1595
- }
1596
- if (node.type.name === "blockquote") {
1597
- const rows = [{ label: "Quote", run: (e, pos) => void turnQuoteInto(e, pos, "quote"), active: (n) => !n.attrs.tone }];
1598
- if (callout) {
1599
- rows.push({ label: "Note", run: (e, pos) => void turnQuoteInto(e, pos, "note"), active: (n) => n.attrs.tone === "note" });
1600
- rows.push({ label: "Warning", run: (e, pos) => void turnQuoteInto(e, pos, "warning"), active: (n) => n.attrs.tone === "warning" });
1601
- }
1602
- rows.push({ label: "Text", run: (e, pos) => void turnQuoteInto(e, pos, "text") });
1603
- return rows;
1604
- }
1605
- return [];
1606
- }
1607
-
1608
- // src/EditorTableControls.tsx
1609
- import { useCallback as useCallback4, useEffect as useEffect4, useRef as useRef4, useState as useState4 } from "react";
1610
- import { TextSelection } from "@tiptap/pm/state";
1611
- import { addColumnAfter, addColumnBefore, addRowAfter, addRowBefore, deleteColumn, deleteRow, deleteTable, toggleHeader } from "@tiptap/pm/tables";
1612
- import { IconColumnInsertLeft, IconColumnInsertRight, IconGripHorizontal, IconGripVertical, IconPlus, IconRowInsertBottom, IconRowInsertTop, IconTrash as IconTrash2 } from "@tabler/icons-react";
1613
- import { cn as cn3 } from "@estiva-app/ui";
1614
- import { IconButton as IconButton2 } from "@estiva-app/ui";
1615
- import { Menu, MenuItem as MenuItem2, MenuSeparator } from "@estiva-app/ui";
1616
- import { Fragment as Fragment2, jsx as jsx7, jsxs as jsxs6 } from "react/jsx-runtime";
1617
- function inCell(editor, cell, command) {
1618
- const { view } = editor;
1619
- if (!view.dom.contains(cell)) return false;
1620
- const at = view.posAtDOM(cell, 0);
1621
- view.dispatch(view.state.tr.setSelection(TextSelection.near(view.state.doc.resolve(at))));
1622
- const done = command(view.state, view.dispatch, view);
1623
- editor.commands.focus();
1624
- return done;
1625
- }
1626
- function isHeaderRow(row) {
1627
- return row.cells.length > 0 && Array.from(row.cells).every((c) => c.tagName === "TH");
1628
- }
1629
- function deleteTableRow(editor, cell) {
1630
- const row = cell.closest("tr");
1631
- const table = cell.closest("table");
1632
- if (!row || !table || table.rows.length <= 1) return inCell(editor, cell, deleteTable);
1633
- const header = isHeaderRow(row);
1634
- return inCell(editor, cell, header ? (state, dispatch, view) => deleteRow(state, dispatch) && (!view || toggleHeader("row")(view.state, view.dispatch)) : deleteRow);
1635
- }
1636
- function deleteTableColumn(editor, cell) {
1637
- const row = cell.closest("tr");
1638
- return inCell(editor, cell, row && row.cells.length > 1 ? deleteColumn : deleteTable);
1639
- }
1640
- function appendTableRow(editor, table) {
1641
- const last = table.rows[table.rows.length - 1]?.cells[0];
1642
- return !!last && inCell(editor, last, addRowAfter);
1643
- }
1644
- function appendTableColumn(editor, table) {
1645
- const first = table.rows[0];
1646
- const last = first?.cells[first.cells.length - 1];
1647
- return !!last && inCell(editor, last, addColumnAfter);
1648
- }
1649
- function place(frame, { table, row, cell }) {
1650
- const at = frame.getBoundingClientRect();
1651
- const t = table.getBoundingClientRect();
1652
- const r = row.getBoundingClientRect();
1653
- const c = cell.getBoundingClientRect();
1654
- return {
1655
- tableBox: { top: t.top - at.top, left: t.left - at.left, width: t.width, height: t.height },
1656
- rowBox: { top: r.top - at.top, height: r.height },
1657
- columnBox: { left: c.left - at.left, width: c.width }
1658
- };
1659
- }
1660
- var ICON = { size: 16, stroke: 1.5, className: "text-text-secondary" };
1661
- var keepFocus = (e) => e.preventDefault();
1662
- var HANDLE_BOX = cn3(FLOATING_SURFACE_CLASSES, "shadow-none");
1663
- function EditorTableControls({ editor, children, className }) {
1664
- const frame = useRef4(null);
1665
- const [hovered, setHovered] = useState4(null);
1666
- const [menu, setMenu] = useState4(null);
1667
- const editable = !!editor && editor.isEditable;
1668
- const follow = useCallback4(
1669
- (target) => {
1670
- if (!editor || !frame.current || !(target instanceof Element)) return;
1671
- if (target.closest("[data-table-control]")) return;
1672
- const cell = target.closest("td, th");
1673
- const row = cell?.closest("tr");
1674
- const table = row?.closest("table");
1675
- if (!cell || !row || !table || !editor.view.dom.contains(table)) {
1676
- setHovered(null);
1677
- return;
1678
- }
1679
- const next = { table, row, cell, ...place(frame.current, { table, row, cell }) };
1680
- setHovered((was) => was && was.cell === cell && JSON.stringify([was.tableBox, was.rowBox, was.columnBox]) === JSON.stringify([next.tableBox, next.rowBox, next.columnBox]) ? was : next);
1681
- },
1682
- [editor]
1683
- );
1684
- useEffect4(() => {
1685
- if (!editor) return;
1686
- const changed = ({ transaction }) => {
1687
- if (transaction.docChanged && !menu) setHovered(null);
1688
- };
1689
- editor.on("transaction", changed);
1690
- return () => {
1691
- editor.off("transaction", changed);
1692
- };
1693
- }, [editor, menu]);
1694
- const shown = editable ? hovered : null;
1695
- const run = (act) => () => {
1696
- if (editor) act();
1697
- setMenu(null);
1698
- setHovered(null);
1699
- };
1700
- return /* @__PURE__ */ jsxs6(
1701
- "div",
1702
- {
1703
- ref: frame,
1704
- className: cn3("relative", className),
1705
- onMouseMove: (e) => {
1706
- if (!menu) follow(e.target);
1707
- },
1708
- onMouseLeave: () => {
1709
- if (!menu) setHovered(null);
1710
- },
1711
- children: [
1712
- children,
1713
- shown && editor && /* @__PURE__ */ jsxs6(Fragment2, { children: [
1714
- /* @__PURE__ */ jsx7("div", { "data-table-control": true, className: cn3(HANDLE_BOX, "absolute -translate-x-1/2 -translate-y-1/2"), style: { left: shown.tableBox.left, top: shown.rowBox.top + shown.rowBox.height / 2 }, children: /* @__PURE__ */ jsxs6(
1715
- Menu,
1716
- {
1717
- open: menu === "row",
1718
- onOpenChange: (open) => setMenu(open ? "row" : null),
1719
- trigger: /* @__PURE__ */ jsx7(IconButton2, { "aria-label": "Row menu", tooltip: "Row", className: "h-6 w-4 p-0", children: /* @__PURE__ */ jsx7(IconGripVertical, { size: 16, stroke: 1.5 }) }),
1720
- children: [
1721
- !isHeaderRow(shown.row) && /* @__PURE__ */ jsx7(MenuItem2, { label: "Insert above", leading: /* @__PURE__ */ jsx7(IconRowInsertTop, { ...ICON }), onClick: run(() => inCell(editor, shown.cell, addRowBefore)) }),
1722
- /* @__PURE__ */ jsx7(MenuItem2, { label: "Insert below", leading: /* @__PURE__ */ jsx7(IconRowInsertBottom, { ...ICON }), onClick: run(() => inCell(editor, shown.cell, addRowAfter)) }),
1723
- /* @__PURE__ */ jsx7(MenuSeparator, {}),
1724
- /* @__PURE__ */ jsx7(MenuItem2, { label: "Delete", destructive: true, leading: /* @__PURE__ */ jsx7(IconTrash2, { size: 16, stroke: 1.5, className: "text-error-default" }), onClick: run(() => deleteTableRow(editor, shown.cell)) }),
1725
- /* @__PURE__ */ jsx7(MenuItem2, { label: "Delete table", destructive: true, leading: /* @__PURE__ */ jsx7(IconTrash2, { size: 16, stroke: 1.5, className: "text-error-default" }), onClick: run(() => inCell(editor, shown.cell, deleteTable)) })
1726
- ]
1727
- }
1728
- ) }),
1729
- /* @__PURE__ */ jsx7("div", { "data-table-control": true, className: cn3(HANDLE_BOX, "absolute -translate-x-1/2 -translate-y-1/2"), style: { left: shown.columnBox.left + shown.columnBox.width / 2, top: shown.tableBox.top }, children: /* @__PURE__ */ jsxs6(
1730
- Menu,
1731
- {
1732
- open: menu === "column",
1733
- onOpenChange: (open) => setMenu(open ? "column" : null),
1734
- trigger: /* @__PURE__ */ jsx7(IconButton2, { "aria-label": "Column menu", tooltip: "Column", className: "h-4 w-6 p-0", children: /* @__PURE__ */ jsx7(IconGripHorizontal, { size: 16, stroke: 1.5 }) }),
1735
- children: [
1736
- /* @__PURE__ */ jsx7(MenuItem2, { label: "Insert left", leading: /* @__PURE__ */ jsx7(IconColumnInsertLeft, { ...ICON }), onClick: run(() => inCell(editor, shown.cell, addColumnBefore)) }),
1737
- /* @__PURE__ */ jsx7(MenuItem2, { label: "Insert right", leading: /* @__PURE__ */ jsx7(IconColumnInsertRight, { ...ICON }), onClick: run(() => inCell(editor, shown.cell, addColumnAfter)) }),
1738
- /* @__PURE__ */ jsx7(MenuSeparator, {}),
1739
- /* @__PURE__ */ jsx7(MenuItem2, { label: "Delete", destructive: true, leading: /* @__PURE__ */ jsx7(IconTrash2, { size: 16, stroke: 1.5, className: "text-error-default" }), onClick: run(() => deleteTableColumn(editor, shown.cell)) }),
1740
- /* @__PURE__ */ jsx7(MenuItem2, { label: "Delete table", destructive: true, leading: /* @__PURE__ */ jsx7(IconTrash2, { size: 16, stroke: 1.5, className: "text-error-default" }), onClick: run(() => inCell(editor, shown.cell, deleteTable)) })
1741
- ]
1742
- }
1743
- ) }),
1744
- shown.row === shown.table.rows[shown.table.rows.length - 1] && /* @__PURE__ */ jsx7("div", { "data-table-control": true, className: cn3(HANDLE_BOX, "absolute flex h-4"), style: { left: shown.tableBox.left, top: shown.tableBox.top + shown.tableBox.height, width: shown.tableBox.width }, children: /* @__PURE__ */ jsx7(IconButton2, { "aria-label": "Add row", tooltip: "Add row", className: "h-full w-full p-0", onMouseDown: keepFocus, onClick: run(() => appendTableRow(editor, shown.table)), children: /* @__PURE__ */ jsx7(IconPlus, { size: 12, stroke: 1.5 }) }) }),
1745
- shown.cell === shown.row.cells[shown.row.cells.length - 1] && /* @__PURE__ */ jsx7("div", { "data-table-control": true, className: cn3(HANDLE_BOX, "absolute flex w-4"), style: { left: shown.tableBox.left + shown.tableBox.width, top: shown.tableBox.top, height: shown.tableBox.height }, children: /* @__PURE__ */ jsx7(IconButton2, { "aria-label": "Add column", tooltip: "Add column", className: "h-full w-full p-0", onMouseDown: keepFocus, onClick: run(() => appendTableColumn(editor, shown.table)), children: /* @__PURE__ */ jsx7(IconPlus, { size: 12, stroke: 1.5 }) }) })
1746
- ] })
1747
- ]
1748
- }
1749
- );
1750
- }
1751
-
1752
- // src/BlockNodes.tsx
1753
- import { Extension as Extension11, InputRule, Node as Node3 } from "@tiptap/core";
1754
- import { DOMSerializer } from "@tiptap/pm/model";
1755
- import { Plugin as Plugin8, PluginKey as PluginKey9 } from "@tiptap/pm/state";
1756
- import { Mapping, ReplaceAroundStep } from "@tiptap/pm/transform";
1757
- import { NodeViewWrapper as NodeViewWrapper2, ReactNodeViewRenderer as ReactNodeViewRenderer2, ReactRenderer as ReactRenderer2 } from "@tiptap/react";
1758
- import { Checkbox } from "@estiva-app/ui";
1759
- import { calloutLook } from "@estiva-app/ui";
1760
-
1761
- // src/ReferenceMenu.tsx
1762
- import { useCallback as useCallback5 } from "react";
1763
- import { Extension as Extension10 } from "@tiptap/core";
1764
- import { useEditorState } from "@tiptap/react";
1765
- import { NodeSelection as NodeSelection2, Plugin as Plugin7, PluginKey as PluginKey8, TextSelection as TextSelection2 } from "@tiptap/pm/state";
1766
- import { ReplaceStep } from "@tiptap/pm/transform";
1767
- import { IconCheck } from "@tabler/icons-react";
1768
-
1769
- // src/LinkChips.ts
1770
- import { Extension as Extension8 } from "@tiptap/core";
1771
- import { closeHistory } from "@tiptap/pm/history";
1772
- import { Plugin as Plugin5, PluginKey as PluginKey6 } from "@tiptap/pm/state";
1773
- var key = new PluginKey6("linkChips");
1774
- var CHIPS_MADE = "linkChipsMade";
1775
- var PASTES_KEPT = 8;
1776
- var LINK_OR_URL = /(\[[^[\]\n]+\]\((?:https?:\/\/|mailto:)[^\s)]+\))|(https?:\/\/[^\s<>"'`]+)/g;
1777
- var TRAILING = /* @__PURE__ */ new Set([".", ",", ";", ":", "!", "?", ")", "]"]);
1778
- function urlRuns(text) {
1779
- if (!text.includes("://")) return [];
1780
- const out = [];
1781
- for (const m of text.matchAll(LINK_OR_URL)) {
1782
- if (m[1]) continue;
1783
- const start = m.index;
1784
- if (text.slice(Math.max(0, start - 2), start) === "](" || text[start - 1] === "[") continue;
1785
- let end = m[0].length;
1786
- while (end > 0 && TRAILING.has(m[0][end - 1])) end--;
1787
- out.push({ url: m[0].slice(0, end), from: start, to: start + end, end: start + m[0].length });
1721
+ },
1722
+ parseHTML() {
1723
+ return [{ tag: `span[data-${this.name.replace(/[A-Z]/g, (c) => `-${c.toLowerCase()}`)}]` }];
1724
+ },
1725
+ addNodeView() {
1726
+ const { icon, iconFor } = this.options;
1727
+ return ReactNodeViewRenderer2(
1728
+ ({ node }) => (
1729
+ // The caption is cut at 24ch, so the whole of it is on hover, in the package's tooltip (UIG-14) — as Peek's sent chip has it.
1730
+ /* @__PURE__ */ jsx6(NodeViewWrapper2, { as: "span", children: /* @__PURE__ */ jsx6(WithTooltip, { inline: true, label: captionOf(node.attrs.label, node.attrs.snippet), children: /* @__PURE__ */ jsxs4("span", { className: inlineChipClassName("neutral", "max-w-[24ch] cursor-default"), children: [
1731
+ /* @__PURE__ */ jsx6("span", { className: "flex items-center justify-center w-4 h-4 shrink-0 text-text-secondary", children: iconFor?.(node.attrs.uri ?? null) ?? icon }),
1732
+ /* @__PURE__ */ jsx6("span", { className: "truncate", children: captionOf(node.attrs.label, node.attrs.snippet) })
1733
+ ] }) }) })
1734
+ ),
1735
+ { as: "span" }
1736
+ );
1788
1737
  }
1789
- return out;
1790
- }
1791
- function findLinkChips(doc2, selection, referenceOf, pasted = []) {
1792
- const found = { chips: [], fills: [], open: [] };
1793
- const open = /* @__PURE__ */ new Set();
1794
- doc2.descendants((node, pos) => {
1795
- if (node.type.spec.code) return false;
1796
- if (node.type.name === "reference") {
1797
- const href = typeof node.attrs.href === "string" ? node.attrs.href : "";
1798
- if (href && !node.attrs.uri) {
1799
- const uri = referenceOf?.(href);
1800
- if (uri) found.fills.push({ pos, uri });
1801
- else open.add(href);
1738
+ });
1739
+ function referenceMenu({ ariaLabel, sectionLabel, icon, iconFor }) {
1740
+ return {
1741
+ ariaLabel,
1742
+ width: "w-[658px]",
1743
+ maxHeight: "max-h-[360px]",
1744
+ sections: (items) => {
1745
+ const groups = [];
1746
+ for (const item of items) {
1747
+ const label = item.section ?? sectionLabel;
1748
+ const last = groups[groups.length - 1];
1749
+ if (last?.label === label) last.items.push(item);
1750
+ else groups.push({ label, items: [item], className: "px-2" });
1802
1751
  }
1803
- return false;
1804
- }
1805
- if (!node.isText || !node.text) return true;
1806
- if (node.marks.some((m) => m.type.spec.code || m.type.name === "code")) return false;
1807
- const link = node.marks.find((m) => m.type.name === "link");
1808
- if (link && !(link.attrs.href === node.text && /^https?:\/\//.test(node.text))) return false;
1809
- const runs = link ? [{ url: node.text, from: 0, to: node.text.length, end: node.text.length }] : urlRuns(node.text);
1810
- for (const run of runs) {
1811
- const from = pos + run.from;
1812
- const to = pos + run.to;
1813
- const wasPasted = pasted.some((range) => range.from <= from && pos + run.end <= range.to);
1814
- const typing = selection && selection.to > from && selection.from <= pos + run.end;
1815
- if (typing && !(selection.empty && wasPasted)) continue;
1816
- const uri = referenceOf?.(run.url);
1817
- if (uri) found.chips.push({ from, to, url: run.url, uri, marks: node.marks.filter((m) => m !== link).map((m) => m.type.name), pasted: wasPasted });
1818
- else open.add(run.url);
1819
- }
1820
- return false;
1821
- });
1822
- found.open = [...open];
1823
- return found;
1824
- }
1825
- function apply(state, found) {
1826
- if (!found.chips.length && !found.fills.length) return null;
1827
- const type = state.schema.nodes.reference;
1828
- if (!type) return null;
1829
- const tr = state.tr;
1830
- for (const { pos, uri } of found.fills) {
1831
- const node = tr.doc.nodeAt(pos);
1832
- if (node) tr.setNodeMarkup(pos, void 0, { ...node.attrs, uri });
1833
- }
1834
- for (const chip of [...found.chips].reverse()) {
1835
- tr.replaceWith(chip.from, chip.to, type.create({ uri: chip.uri, href: chip.url, marks: chip.marks }));
1836
- }
1837
- const pasted = found.chips.some((chip) => chip.pasted);
1838
- tr.setMeta(CHIPS_MADE, { pasted });
1839
- return pasted ? closeHistory(tr) : tr.setMeta("addToHistory", false);
1840
- }
1841
- function refreshLinkChips(editor) {
1842
- if (editor.isDestroyed) return;
1843
- const chips = key.getState(editor.state);
1844
- if (!chips) return;
1845
- const tr = apply(editor.state, findLinkChips(editor.state.doc, editor.state.selection, chips.options.referenceOf, chips.pasted));
1846
- if (tr) editor.view.dispatch(tr);
1752
+ return groups;
1753
+ },
1754
+ itemKey: (item) => `reference-${item.id}`,
1755
+ row: (item) => ({
1756
+ leading: item.icon ?? iconFor?.(item.uri) ?? icon,
1757
+ label: captionOf(item.label, item.snippet),
1758
+ // A summary is the second line, and where the thing sits moves up beside the label (SUM-7's story).
1759
+ ...item.summary ? { description: item.summary, aside: item.description } : { description: item.description },
1760
+ hint: /* @__PURE__ */ jsx6(EnterHint, {})
1761
+ })
1762
+ };
1847
1763
  }
1848
- var LinkChips = Extension8.create({
1849
- name: "linkChips",
1764
+ var listed = (options, query) => options.sections ? options.sections(query).flatMap((section) => section.items.map((item) => ({ ...item, section: section.label }))) : filterReferences(options.items(), query);
1765
+ var ReferenceTrigger = Extension7.create({
1766
+ name: "referenceTrigger",
1850
1767
  addOptions() {
1851
- return { referenceOf: null, ask: null, limit: 24 };
1768
+ return { items: () => [], nodeName: "captionedReference", ariaLabel: "References", sectionLabel: "References", icon: null };
1852
1769
  },
1853
1770
  addProseMirrorPlugins() {
1854
1771
  const options = this.options;
1855
- const editor = this.editor;
1856
1772
  return [
1857
- new Plugin5({
1858
- key,
1859
- // The options, where `refreshLinkChips` can read them from the state alone, and where the last pastes landed.
1860
- state: {
1861
- init: () => ({ options, pasted: [] }),
1862
- apply: (tr, value, before, after) => {
1863
- if (!tr.docChanged) return value;
1864
- const pasted = value.pasted.map((range) => ({ from: tr.mapping.map(range.from, 1), to: tr.mapping.map(range.to, -1), size: range.to - range.from })).filter((range) => range.from < range.to && range.to - range.from === range.size).map(({ from, to }) => ({ from, to }));
1865
- if (tr.getMeta("uiEvent") === "paste") {
1866
- const from = tr.mapping.map(before.selection.from, -1);
1867
- if (from < after.selection.to) pasted.push({ from, to: after.selection.to });
1868
- }
1869
- return { options, pasted: pasted.slice(-PASTES_KEPT) };
1870
- }
1871
- },
1872
- appendTransaction: (trs, _old, state) => {
1873
- if (!trs.some((tr) => tr.docChanged || tr.selectionSet)) return null;
1874
- return apply(state, findLinkChips(state.doc, state.selection, options.referenceOf, key.getState(state)?.pasted));
1773
+ Suggestion({
1774
+ editor: this.editor,
1775
+ char: "[",
1776
+ pluginKey: new PluginKey6("referenceTrigger"),
1777
+ ...listening("]"),
1778
+ // As a mention's: only where the chip may go.
1779
+ allow: ({ state, range }) => {
1780
+ const type = state.schema.nodes[options.nodeName];
1781
+ return !!type && !!state.doc.resolve(range.from).parent.type.contentMatch.matchType(type);
1875
1782
  },
1876
- view: (view) => {
1877
- const asked = /* @__PURE__ */ new Set();
1878
- const look = (state) => {
1879
- if (!options.ask) return;
1880
- const { open } = findLinkChips(state.doc, state.selection, options.referenceOf, key.getState(state)?.pasted);
1881
- const waiting = new Set(open);
1882
- for (const url of asked) if (!waiting.has(url)) asked.delete(url);
1883
- const fresh = open.filter((url) => !asked.has(url)).slice(0, Math.max(0, options.limit - asked.size));
1884
- if (!fresh.length) return;
1885
- for (const url of fresh) asked.add(url);
1886
- const forget = () => {
1887
- for (const url of fresh) asked.delete(url);
1888
- };
1889
- let answer;
1890
- try {
1891
- answer = options.ask(fresh);
1892
- } catch {
1893
- forget();
1894
- return;
1895
- }
1896
- void Promise.resolve(answer).then(() => refreshLinkChips(editor), forget);
1897
- };
1898
- look(view.state);
1899
- queueMicrotask(() => {
1900
- try {
1901
- refreshLinkChips(editor);
1902
- } catch {
1903
- }
1904
- });
1905
- return {
1906
- update: (next, prev) => {
1907
- if (next.state.doc !== prev.doc || !next.state.selection.eq(prev.selection)) look(next.state);
1908
- }
1909
- };
1783
+ items: ({ query }) => listed(options, query),
1784
+ render: suggestionPopup({ ...referenceMenu(options), subscribe: options.subscribe, refresh: (query) => listed(options, query) }),
1785
+ command: ({ editor, range, props: item }) => {
1786
+ editor.chain().focus().insertContentAt(range, [
1787
+ { type: options.nodeName, attrs: { id: item.id, label: item.label, snippet: item.snippet, uri: item.uri } },
1788
+ { type: "text", text: " " }
1789
+ ]).run();
1910
1790
  }
1911
1791
  })
1912
1792
  ];
1913
1793
  }
1914
1794
  });
1795
+ var offers = (editor, command) => !command.needs || command.needs.every((name) => editor.extensionManager.extensions.some((extension) => extension.name === name));
1796
+ var FORMATS = [
1797
+ { id: "paragraph", label: "Text" },
1798
+ { id: "heading", label: "Heading", trigger: "#" },
1799
+ { id: "subheading", label: "Subheading", trigger: "##" },
1800
+ { id: "quote", label: "Quote", trigger: ">" },
1801
+ { id: "code", label: "Code", trigger: "`", blockTrigger: "```" },
1802
+ { id: "bulletList", label: "Bulleted list", trigger: "-" },
1803
+ { id: "orderedList", label: "Numbered list", trigger: "1." }
1804
+ ];
1805
+ var DOCUMENT_FORMATS = [
1806
+ { id: "checklist", label: "Checklist", trigger: "[]" },
1807
+ { id: "note", label: "Note" },
1808
+ { id: "warning", label: "Warning" }
1809
+ ];
1810
+ function applyFormat(editor, id, code = "inline") {
1811
+ const chain = editor.chain().focus();
1812
+ const run = (command, ...args) => {
1813
+ const named2 = chain[command];
1814
+ return named2 ? named2(...args).run() : false;
1815
+ };
1816
+ switch (id) {
1817
+ case "paragraph":
1818
+ return run("setParagraph");
1819
+ case "heading":
1820
+ return run("setHeading", { level: 1 });
1821
+ case "subheading":
1822
+ return run("setHeading", { level: 2 });
1823
+ case "quote":
1824
+ return run("toggleBlockquote");
1825
+ case "bulletList":
1826
+ return run("toggleBulletList");
1827
+ case "orderedList":
1828
+ return run("toggleOrderedList");
1829
+ case "code":
1830
+ return run(code === "block" ? "toggleCodeBlock" : "toggleCode");
1831
+ case "checklist": {
1832
+ if (!editor.isActive("listItem") && !run("toggleBulletList")) return false;
1833
+ if (typeof editor.getAttributes("listItem").checked === "boolean") return true;
1834
+ return editor.chain().updateAttributes("listItem", { checked: false }).run();
1835
+ }
1836
+ case "note":
1837
+ case "warning": {
1838
+ if (!editor.isActive("blockquote") && !run("toggleBlockquote")) return false;
1839
+ return editor.chain().updateAttributes("blockquote", { tone: id }).run();
1840
+ }
1841
+ default:
1842
+ return false;
1843
+ }
1844
+ }
1845
+ var KEYWORDS = {
1846
+ checklist: ["todo", "task"],
1847
+ note: ["callout"],
1848
+ warning: ["callout"]
1849
+ };
1850
+ var NEEDS = {
1851
+ checklist: ["checklist"],
1852
+ note: ["callout"],
1853
+ warning: ["callout"]
1854
+ };
1855
+ function formatSection(code = "inline") {
1856
+ return {
1857
+ label: "Format",
1858
+ commands: (code === "block" ? [...FORMATS, ...DOCUMENT_FORMATS] : FORMATS).map((format) => ({
1859
+ key: `format-${format.id}`,
1860
+ row: { label: format.label, shortcut: code === "block" && format.blockTrigger || format.trigger },
1861
+ keywords: [format.id, ...KEYWORDS[format.id] ?? []],
1862
+ ...NEEDS[format.id] ? { needs: NEEDS[format.id] } : {},
1863
+ run: (editor) => {
1864
+ applyFormat(editor, format.id, code);
1865
+ }
1866
+ }))
1867
+ };
1868
+ }
1869
+ function typeTrigger(input) {
1870
+ return (editor) => {
1871
+ requestAnimationFrame(() => editor.commands.insertContent(input));
1872
+ };
1873
+ }
1874
+ function matches(command, q) {
1875
+ return [command.row.label, ...command.keywords ?? []].some((text) => text.toLowerCase().includes(q));
1876
+ }
1877
+ function filterSlashSections(sections, query) {
1878
+ const q = query.toLowerCase();
1879
+ return sections.map((section) => ({ ...section, commands: q ? section.commands.filter((command) => matches(command, q)) : section.commands }));
1880
+ }
1881
+ var SlashCommands = Extension7.create({
1882
+ name: "slashCommands",
1883
+ addOptions() {
1884
+ return { sections: [formatSection()] };
1885
+ },
1886
+ addProseMirrorPlugins() {
1887
+ const sections = this.options.sections;
1888
+ return [
1889
+ Suggestion({
1890
+ editor: this.editor,
1891
+ char: "/",
1892
+ startOfLine: false,
1893
+ pluginKey: new PluginKey6("slashCommands"),
1894
+ items: ({ query, editor }) => filterSlashSections(sections, query).flatMap(
1895
+ (section, at) => section.commands.filter((command) => offers(editor, command)).map((command) => ({ ...command, section: at }))
1896
+ ),
1897
+ command: ({ editor, range, props }) => {
1898
+ editor.chain().focus().deleteRange(range).run();
1899
+ props.run(editor);
1900
+ },
1901
+ render: suggestionPopup({
1902
+ ariaLabel: "Commands",
1903
+ width: "w-[300px]",
1904
+ maxHeight: "max-h-[400px]",
1905
+ sections: (rows) => sections.map((section, at) => ({ label: section.label, items: rows.filter((row) => row.section === at) })),
1906
+ itemKey: (row) => row.key,
1907
+ row: (row) => row.row
1908
+ })
1909
+ })
1910
+ ];
1911
+ }
1912
+ });
1915
1913
 
1916
- // src/ReferenceMenu.tsx
1917
- import { MenuItem as MenuItem3, MenuSection, MenuSeparator as MenuSeparator2 } from "@estiva-app/ui";
1918
- import { Popover as Popover2 } from "@estiva-app/ui";
1914
+ // src/CommentBox.tsx
1915
+ import { FieldLine } from "@estiva-app/ui";
1916
+ import { FilePicker } from "@estiva-app/ui";
1917
+ import { Kbd } from "@estiva-app/ui";
1919
1918
 
1920
- // src/ReferenceCards.ts
1921
- import { Extension as Extension9 } from "@tiptap/core";
1922
- import { NodeSelection, Plugin as Plugin6, PluginKey as PluginKey7 } from "@tiptap/pm/state";
1923
- import { Decoration as Decoration3, DecorationSet as DecorationSet3 } from "@tiptap/pm/view";
1924
- import { useEffect as useEffect5, useState as useState5 } from "react";
1925
- function layoutOf(raw) {
1926
- if (typeof raw !== "string" || raw === "" || raw === "none") return void 0;
1927
- return raw === "detailed" ? "detailed" : "compact";
1919
+ // src/PastedImages.ts
1920
+ import { Extension as Extension8 } from "@tiptap/core";
1921
+ import { Plugin as Plugin6, PluginKey as PluginKey7 } from "@tiptap/pm/state";
1922
+ var IMAGE_EXTENSIONS = {
1923
+ "image/png": "png",
1924
+ "image/jpeg": "jpg",
1925
+ "image/gif": "gif",
1926
+ "image/webp": "webp",
1927
+ "image/heic": "heic",
1928
+ "image/heif": "heif",
1929
+ "image/svg+xml": "svg"
1930
+ };
1931
+ var GENERIC_STEMS = /* @__PURE__ */ new Set(["image", "blob", "unknown", "untitled", "screenshot"]);
1932
+ function extensionFor(contentType) {
1933
+ const type = contentType.toLowerCase();
1934
+ return IMAGE_EXTENSIONS[type] ?? type.split("/")[1]?.split("+")[0] ?? "png";
1928
1935
  }
1929
- function referenceCardPlacements(doc2) {
1930
- const out = [];
1931
- const seen = /* @__PURE__ */ new Map();
1932
- doc2.descendants((node, pos, parent) => {
1933
- if (!node.isTextblock) return true;
1934
- const cards = [];
1935
- node.forEach((child) => {
1936
- if (child.type.name !== "reference") return;
1937
- const layout = layoutOf(child.attrs.embed);
1938
- if (layout && child.attrs.uri) cards.push({ uri: String(child.attrs.uri), layout });
1939
- });
1940
- if (cards.length) {
1941
- const id = node.attrs.blockId ?? parent?.attrs.blockId;
1942
- const base = id ? `b:${String(id)}` : `p:${pos}`;
1943
- const n = seen.get(base) ?? 0;
1944
- seen.set(base, n + 1);
1945
- out.push({ key: n ? `${base}:${n}` : base, pos: pos + node.nodeSize - 1, cards });
1946
- }
1947
- return false;
1948
- });
1949
- return out;
1936
+ function pastedImageName(contentType, at = /* @__PURE__ */ new Date(), index = 0) {
1937
+ const pad = (n) => String(n).padStart(2, "0");
1938
+ const stamp = `${at.getFullYear()}-${pad(at.getMonth() + 1)}-${pad(at.getDate())} ${pad(at.getHours())}-${pad(at.getMinutes())}-${pad(at.getSeconds())}`;
1939
+ const nth = index > 0 ? ` (${index + 1})` : "";
1940
+ return `Screenshot ${stamp}${nth}.${extensionFor(contentType)}`;
1950
1941
  }
1951
- var key2 = new PluginKey7("referenceCards");
1952
- function elementFor(storage, slotKey) {
1953
- let element = storage.elements.get(slotKey);
1954
- if (!element) {
1955
- element = document.createElement("div");
1956
- element.setAttribute("data-reference-cards", slotKey);
1957
- element.setAttribute("contenteditable", "false");
1958
- storage.elements.set(slotKey, element);
1959
- }
1960
- return element;
1942
+ function hasUsableName(name) {
1943
+ const dot = name.lastIndexOf(".");
1944
+ if (dot <= 0 || dot === name.length - 1) return false;
1945
+ return !GENERIC_STEMS.has(name.slice(0, dot).toLowerCase());
1961
1946
  }
1962
- function storageOf(editor) {
1963
- return editor.storage.referenceCards;
1947
+ function pastedImages(source, at = /* @__PURE__ */ new Date()) {
1948
+ if (!source) return [];
1949
+ if (source.getData("text/plain").trim() !== "") return [];
1950
+ const images = Array.from(source.files ?? []).filter((f) => f.type.toLowerCase().startsWith("image/"));
1951
+ let generated = 0;
1952
+ return images.map(
1953
+ (file) => hasUsableName(file.name) ? file : new File([file], pastedImageName(file.type, at, generated++), { type: file.type, lastModified: file.lastModified })
1954
+ );
1964
1955
  }
1965
- var ReferenceCards = Extension9.create({
1966
- name: "referenceCards",
1967
- addStorage() {
1968
- return { elements: /* @__PURE__ */ new Map() };
1956
+ var PastedImages = Extension8.create({
1957
+ name: "pastedImages",
1958
+ addOptions() {
1959
+ return { onImages: () => false };
1969
1960
  },
1970
1961
  addProseMirrorPlugins() {
1971
- const storage = this.storage;
1972
- const decorate = (doc2) => DecorationSet3.create(
1973
- doc2,
1974
- referenceCardPlacements(doc2).map(
1975
- (p) => Decoration3.widget(p.pos, () => elementFor(storage, p.key), {
1976
- key: p.key,
1977
- side: 1,
1978
- ignoreSelection: true,
1979
- // A click on a card is the card's, not a caret placement in the line.
1980
- stopEvent: () => true
1981
- })
1982
- )
1983
- );
1962
+ const options = this.options;
1984
1963
  return [
1985
1964
  new Plugin6({
1986
- key: key2,
1987
- state: {
1988
- init: (_, state) => decorate(state.doc),
1989
- apply: (tr, set) => tr.docChanged ? decorate(tr.doc) : set
1990
- },
1991
- props: { decorations: (state) => key2.getState(state) }
1965
+ key: new PluginKey7("pastedImages"),
1966
+ props: {
1967
+ handlePaste: (_view, event) => {
1968
+ const files = pastedImages(event.clipboardData);
1969
+ return files.length > 0 && options.onImages(files);
1970
+ }
1971
+ }
1992
1972
  })
1993
1973
  ];
1994
1974
  }
1995
1975
  });
1996
- function useReferenceCards(editor) {
1997
- const [slots, setSlots] = useState5([]);
1998
- useEffect5(() => {
1999
- if (!editor) return;
2000
- const storage = storageOf(editor);
2001
- if (!storage) return;
2002
- let last = "";
2003
- const read = () => {
2004
- if (editor.isDestroyed) return;
2005
- const next = referenceCardPlacements(editor.state.doc).map((p) => ({ key: p.key, element: elementFor(storage, p.key), cards: p.cards }));
2006
- const signature = JSON.stringify(next.map((s) => [s.key, s.cards]));
2007
- if (signature === last) return;
2008
- last = signature;
2009
- const live = new Set(next.map((s) => s.key));
2010
- for (const k of storage.elements.keys()) if (!live.has(k)) storage.elements.delete(k);
2011
- setSlots(next);
1976
+
1977
+ // src/CommentBox.tsx
1978
+ import { ToolbarButton as ToolbarButton2 } from "@estiva-app/ui";
1979
+ import { Fragment as Fragment2, jsx as jsx7, jsxs as jsxs5 } from "react/jsx-runtime";
1980
+ var ATTACH_EVENT = "commentbox:attach";
1981
+ var askForFile = (editor) => editor.view.dom.dispatchEvent(new CustomEvent(ATTACH_EVENT, { bubbles: true }));
1982
+ var commentBoxRows = {
1983
+ file: { key: "insert-file", row: { label: "File" }, keywords: ["attach", "upload"], run: askForFile },
1984
+ mention: { key: "insert-mention", row: { label: "Mention", shortcut: "@" }, keywords: ["@", "Mention a person"], run: typeTrigger("@") },
1985
+ urgent: { key: "insert-urgent", row: { label: "Urgent", shortcut: "!@" }, keywords: ["!@", "Urgent mention"], run: typeTrigger("!@") },
1986
+ reference: { key: "insert-reference", row: { label: "Reference", shortcut: "[" }, keywords: ["[", "Reference"], run: typeTrigger("[") }
1987
+ };
1988
+ var BoxKeys = Extension9.create({
1989
+ name: "commentBoxKeys",
1990
+ addOptions() {
1991
+ return { onEscape: () => false };
1992
+ },
1993
+ addKeyboardShortcuts() {
1994
+ return {
1995
+ "Mod-Enter": ({ editor }) => editor.storage.composeKeys?.send?.() ?? false,
1996
+ // Open now, with no grace: the first Escape closes a list, the next is a deliberate cancel (suggestionPopup).
1997
+ Escape: () => isSuggestionOpen() ? false : this.options.onEscape()
2012
1998
  };
2013
- read();
2014
- editor.on("transaction", read);
1999
+ }
2000
+ });
2001
+ var SQUARE = /* @__PURE__ */ jsx7(IconSquareRounded, { size: 16, stroke: 1.5, className: "text-text-secondary" });
2002
+ var SMALL_SQUARE = /* @__PURE__ */ jsx7(IconSquareRounded, { size: 14, stroke: 1.5 });
2003
+ var fileCount = 0;
2004
+ function CommentBox({
2005
+ people,
2006
+ references,
2007
+ referencesChanged,
2008
+ referenceIcon,
2009
+ insert = [],
2010
+ code = "block",
2011
+ send,
2012
+ showsAtOnce = false,
2013
+ label,
2014
+ placeholder,
2015
+ draft,
2016
+ edit,
2017
+ upload,
2018
+ accept,
2019
+ closed,
2020
+ referenceView,
2021
+ extensions = [],
2022
+ autoFocus,
2023
+ onSent,
2024
+ onRefused,
2025
+ className
2026
+ }) {
2027
+ const [files, setFiles] = useState4(edit?.files ?? []);
2028
+ const [sending, setSending] = useState4(false);
2029
+ const [refused, setRefused] = useState4(null);
2030
+ const picker = useRef3(null);
2031
+ const root = useRef3(null);
2032
+ const latest = useRef3({ edit, people, references, referencesChanged, referenceIcon, upload, draft });
2033
+ latest.current = { edit, people, references, referencesChanged, referenceIcon, upload, draft };
2034
+ const save = useRef3(() => false);
2035
+ const attachFiles = useCallback4((picked) => {
2036
+ const uploadOne = latest.current.upload;
2037
+ if (!uploadOne || latest.current.edit) return false;
2038
+ for (const file of picked) {
2039
+ fileCount += 1;
2040
+ const id = `file-${fileCount}`;
2041
+ setFiles((all) => [...all, { id, name: file.name, size: file.size, contentType: file.type, state: "uploading" }]);
2042
+ uploadOne(file).then(
2043
+ (answer) => setFiles(
2044
+ (all) => all.map((f) => f.id !== id ? f : answer.accepted ? { ...f, state: "ready", value: answer.value } : { ...f, state: "failed", note: answer.reason })
2045
+ ),
2046
+ () => setFiles((all) => all.map((f) => f.id === id ? { ...f, state: "failed", note: "It could not be uploaded." } : f))
2047
+ );
2048
+ }
2049
+ return true;
2050
+ }, []);
2051
+ const rows = insert.filter((c) => !((edit || !upload) && c.key === commentBoxRows.file.key) && !(edit && c.key === commentBoxRows.urgent.key));
2052
+ const sections = useRef3([]).current;
2053
+ sections.splice(0, sections.length, formatSection(code), ...rows.length > 0 ? [{ label: "Insert", commands: rows }] : []);
2054
+ const iconFor = useCallback4((uri) => latest.current.referenceIcon?.(uri), []);
2055
+ const editor = useEditor({
2056
+ extensions: [
2057
+ StarterKit.configure({ link: { openOnClick: false } }),
2058
+ KeptSelection,
2059
+ ComposeKeys,
2060
+ BoxKeys.configure({
2061
+ onEscape: () => {
2062
+ const editing = latest.current.edit;
2063
+ if (!editing) return false;
2064
+ editing.onCancel();
2065
+ return true;
2066
+ }
2067
+ }),
2068
+ PersonMention.configure({ people: () => latest.current.people }),
2069
+ // An edit makes nobody urgent (CON-24): `!@` opens no list there, as `/` offers no Urgent.
2070
+ UrgentPersonMention.extend({
2071
+ addOptions() {
2072
+ const parent = this.parent();
2073
+ return { ...parent, suggestion: { ...parent.suggestion, allow: () => !latest.current.edit } };
2074
+ }
2075
+ }).configure({ people: () => latest.current.people }),
2076
+ CaptionedReference.configure({ icon: SMALL_SQUARE, iconFor }),
2077
+ ReferenceTrigger.configure({
2078
+ items: () => [],
2079
+ sections: (query) => latest.current.references?.(query) ?? [],
2080
+ subscribe: (listener) => latest.current.referencesChanged?.(listener) ?? (() => {
2081
+ }),
2082
+ ariaLabel: "References",
2083
+ sectionLabel: "References",
2084
+ icon: SQUARE,
2085
+ iconFor
2086
+ }),
2087
+ SlashCommands.configure({ sections }),
2088
+ ReferenceNode.configure({ view: referenceView ?? null }),
2089
+ PastedImages.configure({ onImages: attachFiles }),
2090
+ ...extensions
2091
+ ],
2092
+ content: edit?.body ?? draft?.read(),
2093
+ editable: !closed,
2094
+ editorProps: { attributes: { class: COMPOSE_EDITOR_CLASSES, role: "textbox", "aria-multiline": "true", "aria-label": label } }
2095
+ });
2096
+ useEffect4(() => {
2097
+ if (!editor || edit) return;
2098
+ const keep = () => {
2099
+ const kept = latest.current.draft;
2100
+ if (!kept) return;
2101
+ if (isEmptyDoc(editor)) kept.clear();
2102
+ else kept.write(editor.getJSON());
2103
+ };
2104
+ editor.on("update", keep);
2015
2105
  return () => {
2016
- editor.off("transaction", read);
2106
+ editor.off("update", keep);
2017
2107
  };
2108
+ }, [editor, edit]);
2109
+ useEffect4(() => {
2110
+ editor?.setEditable(!closed && !sending);
2111
+ }, [editor, closed, sending]);
2112
+ useEffect4(() => {
2113
+ if (!editor || !(autoFocus || edit)) return;
2114
+ const frame = requestAnimationFrame(() => editor.commands.focus("end"));
2115
+ return () => cancelAnimationFrame(frame);
2018
2116
  }, [editor]);
2019
- return slots;
2117
+ useEffect4(() => {
2118
+ const box = root.current;
2119
+ if (!box || !upload || edit) return;
2120
+ const ask = () => picker.current?.click();
2121
+ box.addEventListener(ATTACH_EVENT, ask);
2122
+ return () => box.removeEventListener(ATTACH_EVENT, ask);
2123
+ }, [upload, edit]);
2124
+ const uploading = files.some((f) => f.state === "uploading");
2125
+ const ready = files.some((f) => f.state === "ready");
2126
+ const go = useCallback4(
2127
+ (ed) => {
2128
+ const body = ed.getJSON();
2129
+ const sent = files.filter((f) => f.state === "ready");
2130
+ setRefused(null);
2131
+ const answered = (answer) => answer.catch(() => ({ accepted: false, reason: "try again in a moment" }));
2132
+ if (showsAtOnce) {
2133
+ setFiles((all) => all.filter((f) => f.state !== "ready"));
2134
+ draft?.clear();
2135
+ onSent?.(body, sent);
2136
+ void answered(send(body, sent)).then((answer) => {
2137
+ if (answer.accepted) return;
2138
+ onRefused?.();
2139
+ if (ed.isDestroyed) {
2140
+ draft?.write(body);
2141
+ return;
2142
+ }
2143
+ if (isEmptyDoc(ed)) ed.commands.setContent(body);
2144
+ else ed.commands.insertContentAt(0, body.content ?? []);
2145
+ ed.commands.focus("end");
2146
+ setFiles((all) => [...sent, ...all]);
2147
+ setRefused(answer.reason);
2148
+ });
2149
+ return true;
2150
+ }
2151
+ setSending(true);
2152
+ void answered(send(body, sent)).then((answer) => {
2153
+ setSending(false);
2154
+ if (!answer.accepted) {
2155
+ setRefused(answer.reason);
2156
+ return;
2157
+ }
2158
+ if (!ed.isDestroyed) ed.commands.clearContent(true);
2159
+ setFiles((all) => all.filter((f) => !sent.includes(f)));
2160
+ draft?.clear();
2161
+ onSent?.(body, sent);
2162
+ });
2163
+ return false;
2164
+ },
2165
+ [files, showsAtOnce, send, draft, onSent, onRefused]
2166
+ );
2167
+ save.current = () => {
2168
+ if (!editor || !edit || sending || uploading) return true;
2169
+ setRefused(null);
2170
+ setSending(true);
2171
+ void edit.onSave(editor.getJSON(), files).catch(() => ({ accepted: false, reason: "try again in a moment" })).then((answer) => {
2172
+ setSending(false);
2173
+ if (!answer.accepted) setRefused(answer.reason);
2174
+ });
2175
+ return true;
2176
+ };
2177
+ useEffect4(() => {
2178
+ if (!editor || !edit) return;
2179
+ const storage = editor.storage.composeKeys;
2180
+ if (!storage) return;
2181
+ storage.send = () => save.current();
2182
+ return () => {
2183
+ storage.send = null;
2184
+ };
2185
+ }, [editor, edit]);
2186
+ if (closed) {
2187
+ return /* @__PURE__ */ jsxs5(Card, { fill: "inset", className: cn2("flex items-start gap-3 px-4 py-3", className), children: [
2188
+ /* @__PURE__ */ jsx7(IconLock, { size: 16, stroke: 1.5, className: "mt-0.5 shrink-0 text-text-muted", "aria-hidden": true }),
2189
+ /* @__PURE__ */ jsx7("p", { className: "text-body-2 text-text-secondary", children: closed.reason })
2190
+ ] });
2191
+ }
2192
+ const fileCards = files.length > 0 ? /* @__PURE__ */ jsx7(Fragment2, { children: files.map((f) => /* @__PURE__ */ jsx7(
2193
+ AttachmentCard,
2194
+ {
2195
+ pending: true,
2196
+ name: f.name,
2197
+ size: f.size,
2198
+ contentType: f.contentType,
2199
+ state: f.state,
2200
+ note: f.note,
2201
+ onRemove: () => setFiles((all) => all.filter((one) => one !== f))
2202
+ },
2203
+ f.id
2204
+ )) }) : void 0;
2205
+ const refusedLine = refused && /* @__PURE__ */ jsx7(FieldLine, { tone: "error", children: edit ? `Not saved: ${refused}. Your changes are still in the box.` : `Not sent: ${refused}. Your text is back in the box.` });
2206
+ if (edit) {
2207
+ return /* @__PURE__ */ jsxs5("div", { className: cn2("flex flex-col gap-1", className), children: [
2208
+ /* @__PURE__ */ jsxs5("div", { className: cn2(WRITING_BOX_CLASSES, "focus-within:border-border-strong transition-colors", sending && "[&_.ProseMirror]:text-text-muted"), children: [
2209
+ /* @__PURE__ */ jsx7(EditorContent2, { editor }),
2210
+ fileCards && /* @__PURE__ */ jsx7("div", { className: "flex flex-wrap gap-2", children: fileCards }),
2211
+ /* @__PURE__ */ jsxs5("div", { className: "flex items-center justify-between gap-2", children: [
2212
+ /* @__PURE__ */ jsxs5("span", { className: "flex items-center gap-1 text-caption text-text-muted", children: [
2213
+ /* @__PURE__ */ jsx7(Kbd, { children: "Esc" }),
2214
+ " to cancel \xB7 ",
2215
+ /* @__PURE__ */ jsx7(Kbd, { children: "Enter" }),
2216
+ " to save"
2217
+ ] }),
2218
+ /* @__PURE__ */ jsxs5("div", { className: "flex items-center gap-2", children: [
2219
+ /* @__PURE__ */ jsx7(Button, { variant: "outlined", size: "small", onClick: edit.onCancel, children: "Cancel" }),
2220
+ /* @__PURE__ */ jsx7(Button, { variant: "primary", size: "small", disabled: uploading || sending, onClick: () => save.current(), children: "Save" })
2221
+ ] })
2222
+ ] })
2223
+ ] }),
2224
+ sending && /* @__PURE__ */ jsx7(FieldLine, { children: "Saving\u2026" }),
2225
+ refusedLine
2226
+ ] });
2227
+ }
2228
+ const onDrop = (event) => {
2229
+ const dropped = Array.from(event.dataTransfer?.files ?? []);
2230
+ if (dropped.length === 0 || !upload) return;
2231
+ event.preventDefault();
2232
+ attachFiles(dropped);
2233
+ };
2234
+ return /* @__PURE__ */ jsxs5("div", { ref: root, className: cn2("flex flex-col gap-1", className), onDragOver: upload ? (e) => e.preventDefault() : void 0, onDrop, children: [
2235
+ /* @__PURE__ */ jsx7(
2236
+ ComposeBox,
2237
+ {
2238
+ editor,
2239
+ onSend: go,
2240
+ placeholder,
2241
+ tools: upload ? /* @__PURE__ */ jsx7(ToolbarButton2, { tooltip: "Attach a file", "aria-label": "Attach a file", disabled: sending, onClick: () => picker.current?.click(), children: /* @__PURE__ */ jsx7(IconPaperclip, { size: 16, stroke: 1.5 }) }) : void 0,
2242
+ attachments: fileCards,
2243
+ ready,
2244
+ holding: uploading || sending,
2245
+ selection: { link: true },
2246
+ className: cn2(sending && "[&_[data-composer-editor]]:text-text-muted")
2247
+ }
2248
+ ),
2249
+ upload && /* @__PURE__ */ jsx7(FilePicker, { ref: picker, multiple: true, accept, onPick: attachFiles }),
2250
+ sending && /* @__PURE__ */ jsx7(FieldLine, { children: "Sending\u2026" }),
2251
+ uploading && !sending && /* @__PURE__ */ jsx7(FieldLine, { children: "Uploading\u2026 Send waits for the file." }),
2252
+ refusedLine
2253
+ ] });
2020
2254
  }
2021
- function referenceAtSelection(state) {
2022
- const { selection } = state;
2023
- let found = null;
2024
- if (selection instanceof NodeSelection) {
2025
- if (selection.node.type.name === "reference") found = { pos: selection.from, node: selection.node };
2026
- } else if (!selection.empty) {
2027
- let only = true;
2028
- state.doc.nodesBetween(selection.from, selection.to, (node2, pos2) => {
2029
- if (node2.type.name === "reference") {
2030
- if (found) only = false;
2031
- found = { pos: pos2, node: node2 };
2255
+
2256
+ // src/InlineText.tsx
2257
+ import { useCallback as useCallback5, useEffect as useEffect5, useImperativeHandle as useImperativeHandle2, useRef as useRef4, useState as useState5 } from "react";
2258
+ import { Extension as Extension10, Node as Node3 } from "@tiptap/core";
2259
+ import { history, redo, undo } from "@tiptap/pm/history";
2260
+ import { EditorContent as EditorContent3, useEditor as useEditor2 } from "@tiptap/react";
2261
+ import { cn as cn3 } from "@estiva-app/ui";
2262
+ import { jsx as jsx8, jsxs as jsxs6 } from "react/jsx-runtime";
2263
+ var VARIANT = {
2264
+ title: "text-h2 text-text-primary",
2265
+ summary: "text-body-1 text-text-secondary"
2266
+ };
2267
+ var ROOM = "-mx-2 px-2 py-1";
2268
+ var OneLine = Node3.create({ name: "doc", topNode: true, content: "paragraph" });
2269
+ var Paragraph = Node3.create({
2270
+ name: "paragraph",
2271
+ content: "text*",
2272
+ parseHTML: () => [{ tag: "p" }],
2273
+ renderHTML: () => ["p", 0]
2274
+ });
2275
+ var Text = Node3.create({ name: "text" });
2276
+ var Undo = Extension10.create({
2277
+ name: "inlineTextUndo",
2278
+ addProseMirrorPlugins: () => [history()],
2279
+ addKeyboardShortcuts() {
2280
+ const run = (command) => () => command(this.editor.state, this.editor.view.dispatch);
2281
+ return { "Mod-z": run(undo), "Shift-Mod-z": run(redo), "Mod-y": run(redo) };
2282
+ }
2283
+ });
2284
+ var doc = (text) => ({ type: "doc", content: [{ type: "paragraph", content: text ? [{ type: "text", text }] : [] }] });
2285
+ var oneLine = (text) => text.replace(/\s+/g, " ").trim();
2286
+ function InlineText({ value, placeholder, label, onCommit, onText, onEnter, variant = "title", clearable = false, readOnly = false, className, ref }) {
2287
+ const saved = useRef4(value);
2288
+ const [empty, setEmpty] = useState5(!value);
2289
+ const latest = useRef4({ onEnter, onText, onCommit, clearable, value });
2290
+ latest.current = { onEnter, onText, onCommit, clearable, value };
2291
+ const pending = useRef4(null);
2292
+ const save = useCallback5(async (text) => {
2293
+ const next = oneLine(text);
2294
+ if (next === saved.current || next === pending.current) return;
2295
+ if (!next && !latest.current.clearable) return;
2296
+ pending.current = next;
2297
+ try {
2298
+ if (await latest.current.onCommit(next)) saved.current = next;
2299
+ } finally {
2300
+ if (pending.current === next) pending.current = null;
2301
+ }
2302
+ }, []);
2303
+ const editor = useEditor2({
2304
+ extensions: [OneLine, Paragraph, Text, Undo],
2305
+ content: doc(value),
2306
+ editable: !readOnly,
2307
+ editorProps: {
2308
+ attributes: {
2309
+ "aria-label": label,
2310
+ role: "textbox",
2311
+ "aria-multiline": "false",
2312
+ "aria-placeholder": placeholder,
2313
+ ...readOnly ? { "aria-readonly": "true" } : {},
2314
+ class: "outline-none"
2315
+ },
2316
+ handleKeyDown: (view, event) => {
2317
+ if (event.key === "Enter") {
2318
+ event.preventDefault();
2319
+ void save(view.state.doc.textContent);
2320
+ latest.current.onEnter?.();
2321
+ return true;
2322
+ }
2323
+ if (event.key === "Escape") {
2324
+ view.dom.blur();
2325
+ return true;
2326
+ }
2032
2327
  return false;
2328
+ },
2329
+ // A paste is its plain text on this one line, whatever it was copied from.
2330
+ handlePaste: (view, event) => {
2331
+ const text = event.clipboardData?.getData("text/plain");
2332
+ if (text == null) return false;
2333
+ view.dispatch(view.state.tr.insertText(text.replace(/\s+/g, " ")));
2334
+ return true;
2033
2335
  }
2034
- if (node2.isText) {
2035
- const from = Math.max(selection.from, pos2) - pos2;
2036
- const to = Math.min(selection.to, pos2 + node2.nodeSize) - pos2;
2037
- if ((node2.text ?? "").slice(from, to).trim() !== "") only = false;
2336
+ },
2337
+ onFocus: ({ editor: e }) => latest.current.onText?.(e.getText()),
2338
+ onUpdate: ({ editor: e }) => {
2339
+ setEmpty(e.isEmpty);
2340
+ latest.current.onText?.(e.getText());
2341
+ },
2342
+ onBlur: ({ editor: e }) => {
2343
+ latest.current.onText?.(null);
2344
+ if (e.isEmpty && saved.current && !latest.current.clearable) {
2345
+ e.commands.setContent(doc(saved.current), { emitUpdate: false });
2346
+ setEmpty(false);
2347
+ return;
2038
2348
  }
2039
- return true;
2040
- });
2041
- if (!only) found = null;
2042
- }
2043
- if (!found) return null;
2044
- const { pos, node } = found;
2045
- if (!node.attrs.uri) return null;
2046
- return { pos, uri: String(node.attrs.uri ?? ""), layout: layoutOf(node.attrs.embed) ?? "none" };
2047
- }
2048
- function setReferenceCard(editor, layout) {
2049
- const at = referenceAtSelection(editor.state);
2050
- return at ? setReferenceCardAt(editor, at.pos, layout) : false;
2051
- }
2052
- function setReferenceCardAt(editor, pos, layout) {
2053
- const node = editor.state.doc.nodeAt(pos);
2054
- if (!node || node.type.name !== "reference" || !node.attrs.uri) return false;
2055
- const wasNode = editor.state.selection instanceof NodeSelection && editor.state.selection.from === pos;
2056
- const tr = editor.state.tr.setNodeMarkup(pos, void 0, { ...node.attrs, embed: layout === "none" ? null : layout });
2057
- if (wasNode) tr.setSelection(NodeSelection.create(tr.doc, pos));
2058
- editor.view.dispatch(tr);
2059
- return true;
2349
+ const { value: current } = latest.current;
2350
+ if (oneLine(e.getText()) === saved.current && current !== saved.current && pending.current === null) {
2351
+ e.commands.setContent(doc(current), { emitUpdate: false });
2352
+ saved.current = current;
2353
+ setEmpty(!current);
2354
+ return;
2355
+ }
2356
+ void save(e.getText());
2357
+ }
2358
+ }, [readOnly]);
2359
+ useEffect5(() => {
2360
+ if (!editor || editor.isDestroyed || value === saved.current || editor.isFocused) return;
2361
+ if (oneLine(editor.getText()) !== saved.current) return;
2362
+ editor.commands.setContent(doc(value), { emitUpdate: false });
2363
+ saved.current = value;
2364
+ setEmpty(!value);
2365
+ }, [editor, value]);
2366
+ useImperativeHandle2(ref, () => ({
2367
+ focus: (at = "start") => editor?.commands.focus(at)
2368
+ }), [editor]);
2369
+ return /* @__PURE__ */ jsxs6("div", { className: cn3("relative", VARIANT[variant], className), children: [
2370
+ /* @__PURE__ */ jsx8(EditorContent3, { editor, className: cn3(ROOM, !readOnly && "cursor-text") }),
2371
+ empty && !readOnly && /* @__PURE__ */ jsx8("span", { "aria-hidden": true, className: "pointer-events-none absolute left-0 top-1 text-text-muted", children: placeholder })
2372
+ ] });
2060
2373
  }
2061
2374
 
2062
- // src/ReferenceMenu.tsx
2063
- import { Fragment as Fragment3, jsx as jsx8, jsxs as jsxs7 } from "react/jsx-runtime";
2064
- var key3 = new PluginKey8("referenceMenu");
2065
- var LAYOUTS = [
2066
- { layout: "none", label: "None" },
2067
- { layout: "compact", label: "Compact" },
2068
- { layout: "detailed", label: "Detailed" }
2069
- ];
2070
- function chipTarget(view, pos) {
2071
- const dom = view.nodeDOM(pos);
2072
- return dom instanceof HTMLElement ? dom.querySelector("a[href], button") : null;
2375
+ // src/CommentHighlights.ts
2376
+ import { Extension as Extension11 } from "@tiptap/core";
2377
+ import { Plugin as Plugin7, PluginKey as PluginKey8 } from "@tiptap/pm/state";
2378
+ import { Decoration as Decoration3, DecorationSet as DecorationSet3 } from "@tiptap/pm/view";
2379
+ var commentHighlightsKey = new PluginKey8("commentHighlights");
2380
+ var COMMENT_HIGHLIGHT_CLASSES = {
2381
+ rest: "cursor-pointer rounded-sm bg-warning-muted",
2382
+ active: "cursor-pointer rounded-sm bg-warning-muted underline decoration-warning-default decoration-2 underline-offset-4"
2383
+ };
2384
+ var QUOTE_WHOLE_MAX = 1e3;
2385
+ var QUOTE_END_LENGTH = 150;
2386
+ var QUOTE_CONTEXT_LENGTH = 32;
2387
+ function placesIn(doc2) {
2388
+ const places = /* @__PURE__ */ new Map();
2389
+ const walk = (parent, parentPos) => {
2390
+ parent.forEach((node, offset, index) => {
2391
+ const pos = parentPos + offset;
2392
+ const id = node.attrs.blockId;
2393
+ if (typeof id === "string" && id && !places.has(id)) places.set(id, { node, pos, parent: parentPos, index });
2394
+ if (!node.isTextblock && !node.isLeaf) walk(node, pos + 1);
2395
+ });
2396
+ };
2397
+ walk(doc2, 0);
2398
+ return places;
2073
2399
  }
2074
- function webHref(view, pos) {
2075
- const href = view.state.doc.nodeAt(pos)?.attrs.href;
2076
- return typeof href === "string" && /^https?:\/\//i.test(href) ? href : "";
2400
+ function textOf(block) {
2401
+ let text = "";
2402
+ const starts = [];
2403
+ const ends = [];
2404
+ const add = (chars, start, end) => {
2405
+ for (let i = 0; i < chars.length; i++) starts.push(start), ends.push(end);
2406
+ text += chars;
2407
+ };
2408
+ const walk = (node, pos) => {
2409
+ if (node.isTextblock) {
2410
+ node.forEach((child, offset) => {
2411
+ const at = pos + 1 + offset;
2412
+ if (child.isText && child.text) {
2413
+ for (let i = 0; i < child.text.length; i++) starts.push(at + i), ends.push(at + i + 1);
2414
+ text += child.text;
2415
+ } else if (child.type.name === "hardBreak") add("\n", at, at + child.nodeSize);
2416
+ else if (child.isInline && child.isLeaf) add(String(child.attrs.href || child.attrs.uri || ""), at, at + child.nodeSize);
2417
+ });
2418
+ return;
2419
+ }
2420
+ if (node.type.name === "listItem") {
2421
+ node.forEach((child, offset) => void (LISTS2.has(child.type.name) || walk(child, pos + 1 + offset)));
2422
+ return;
2423
+ }
2424
+ const children = LISTS2.has(node.type.name) ? itemsOf(node, pos) : childrenOf(node, pos);
2425
+ children.forEach(({ node: child, pos: at }, index) => {
2426
+ if (index > 0) add("\n", at, at);
2427
+ walk(child, at);
2428
+ });
2429
+ };
2430
+ walk(block.node, block.pos);
2431
+ return { text, starts, ends };
2077
2432
  }
2078
- function rowsOf(view, pos) {
2079
- const open = chipTarget(view, pos) || webHref(view, pos) ? ["open"] : [];
2080
- return view.state.doc.nodeAt(pos)?.attrs.uri ? [...open, ...LAYOUTS.map((card) => card.layout)] : open;
2433
+ var LISTS2 = /* @__PURE__ */ new Set(["bulletList", "orderedList"]);
2434
+ function childrenOf(node, pos) {
2435
+ const out = [];
2436
+ node.forEach((child, offset) => void out.push({ node: child, pos: pos + 1 + offset }));
2437
+ return out;
2081
2438
  }
2082
- function chipAt(state, pos) {
2083
- const node = state.doc.nodeAt(pos);
2084
- return node && node.type.name === "reference" ? node : null;
2439
+ function itemsOf(list, pos) {
2440
+ return childrenOf(list, pos).flatMap((item) => [item, ...childrenOf(item.node, item.pos).flatMap((c) => LISTS2.has(c.node.type.name) ? itemsOf(c.node, c.pos) : [])]);
2085
2441
  }
2086
- function justPlaced(tr, state) {
2087
- if (!tr.docChanged || tr.getMeta("history$") || tr.getMeta("preventUpdate")) return null;
2088
- const whole = tr.steps.some((step) => step instanceof ReplaceStep && step.from === 0 && step.to === tr.before.content.size);
2089
- if (whole && tr.getMeta("uiEvent") !== "paste") return null;
2090
- const made = tr.getMeta(CHIPS_MADE);
2091
- if (made && !made.pasted) return null;
2092
- const { selection } = state;
2093
- if (!selection.empty) return null;
2094
- let at = selection.from;
2095
- let before = selection.$from.nodeBefore;
2096
- if (!made && before?.isText && before.text === " ") {
2097
- at -= 1;
2098
- before = state.doc.resolve(at).nodeBefore;
2442
+ function find(text, words, from, context) {
2443
+ let first = -1;
2444
+ for (let at = text.indexOf(words, from); at !== -1; at = text.indexOf(words, at + 1)) {
2445
+ if (first === -1) first = at;
2446
+ if (context(at)) return at;
2099
2447
  }
2100
- if (!before || before.type.name !== "reference" || !before.attrs.uri) return null;
2101
- const pos = at - before.nodeSize;
2102
- const old = tr.mapping.invert().map(pos);
2103
- const was = tr.before.nodeAt(old);
2104
- if (was && was.type.name === "reference" && was.attrs.uri === before.attrs.uri && tr.mapping.map(old, 1) === pos) return null;
2105
- return pos;
2448
+ return first;
2106
2449
  }
2107
- function dispatchMenu(view, next) {
2108
- view.dispatch(view.state.tr.setMeta(key3, next));
2450
+ function runIn(doc2, places, ids) {
2451
+ const present = ids.map((id) => places.get(id)).filter((p) => !!p);
2452
+ if (present.length === 0) return null;
2453
+ const byParent = /* @__PURE__ */ new Map();
2454
+ for (const p of present) byParent.set(p.parent, [...byParent.get(p.parent) ?? [], p]);
2455
+ const group = [...byParent.values()].reduce((best, one) => one.length > best.length ? one : best);
2456
+ const low = Math.min(...group.map((p) => p.index));
2457
+ const high = Math.max(...group.map((p) => p.index));
2458
+ const contentStart = group[0].parent;
2459
+ const parent = contentStart === 0 ? doc2 : doc2.nodeAt(contentStart - 1);
2460
+ if (!parent) return group;
2461
+ const run = [];
2462
+ parent.forEach((node, offset, index) => {
2463
+ if (index >= low && index <= high) run.push({ node, pos: contentStart + offset, parent: contentStart, index });
2464
+ });
2465
+ return run;
2109
2466
  }
2110
- var passing = false;
2111
- function openChip(view, pos) {
2112
- const target = chipTarget(view, pos);
2113
- if (target) {
2114
- passing = true;
2115
- try {
2116
- target.click();
2117
- } finally {
2118
- passing = false;
2119
- }
2120
- return;
2467
+ function placeOf(doc2, anchor, places = placesIn(doc2)) {
2468
+ const run = runIn(doc2, places, anchor.blocks);
2469
+ if (!run) return { state: "detached" };
2470
+ const from = run[0].pos;
2471
+ const to = run[run.length - 1].pos + run[run.length - 1].node.nodeSize;
2472
+ const { quote } = anchor;
2473
+ if (!quote) return { state: "resolved", from, to, words: false };
2474
+ const reworded = { state: "reworded", from, to };
2475
+ const firstId = anchor.blocks[0];
2476
+ const lastId = anchor.blocks[anchor.blocks.length - 1];
2477
+ const first = run.findIndex((p) => p.node.attrs.blockId === firstId);
2478
+ const last = run.findIndex((p) => p.node.attrs.blockId === lastId);
2479
+ if (first === -1 || last === -1 || last < first) return reworded;
2480
+ const a = textOf(run[first]);
2481
+ const b = first === last ? a : textOf(run[last]);
2482
+ const prefix = quote.prefix && quote.prefix.length <= QUOTE_CONTEXT_LENGTH ? quote.prefix : void 0;
2483
+ const suffix = quote.suffix && quote.suffix.length <= QUOTE_CONTEXT_LENGTH ? quote.suffix : void 0;
2484
+ const before = (text, i) => !prefix || text.slice(Math.max(0, i - prefix.length), i) === prefix;
2485
+ const after = (text, i) => !suffix || text.slice(i, i + suffix.length) === suffix;
2486
+ if (quote.end === void 0) {
2487
+ const at = find(a.text, quote.start, 0, (i) => before(a.text, i) && after(a.text, i + quote.start.length));
2488
+ if (at === -1 || quote.start === "") return reworded;
2489
+ return { state: "resolved", from: a.starts[at], to: a.ends[at + quote.start.length - 1], words: true };
2121
2490
  }
2122
- const href = webHref(view, pos);
2123
- if (href) window.open(href, "_blank", "noopener,noreferrer");
2124
- }
2125
- function choose(editor, pos, row) {
2126
- dispatchMenu(editor.view, null);
2127
- if (row === "open") openChip(editor.view, pos);
2128
- else if (row) setReferenceCardAt(editor, pos, row);
2129
- }
2130
- function isReferenceMenuOpen(state) {
2131
- return !!key3.getState(state);
2132
- }
2133
- function referenceMenuClick(editor, pos) {
2134
- if (passing || editor.isDestroyed || !editor.isEditable || key3.getState(editor.state) === void 0) return false;
2135
- if (!chipAt(editor.state, pos) || rowsOf(editor.view, pos).length === 0) return false;
2136
- editor.view.dispatch(caretAfter(editor.state, pos).setMeta(key3, { pos, active: -1 }));
2137
- return true;
2138
- }
2139
- function caretAfter(state, pos) {
2140
- const node = state.doc.nodeAt(pos);
2141
- return state.tr.setSelection(TextSelection2.create(state.doc, pos + (node?.nodeSize ?? 1)));
2142
- }
2143
- var ReferenceMenu = Extension10.create({
2144
- name: "referenceMenu",
2145
- // Before the editor's own keys, so Enter on a highlighted row is the row's, not a new line.
2146
- priority: 1e3,
2491
+ const startAt = find(a.text, quote.start, 0, (i) => before(a.text, i));
2492
+ if (startAt === -1 || quote.start === "") return reworded;
2493
+ const endFrom = first === last ? startAt + quote.start.length : 0;
2494
+ const endAt = find(b.text, quote.end, endFrom, (i) => after(b.text, i + quote.end.length));
2495
+ if (endAt === -1 || quote.end === "") return reworded;
2496
+ return { state: "resolved", from: a.starts[startAt], to: b.ends[endAt + quote.end.length - 1], words: true };
2497
+ }
2498
+ var CommentHighlights = Extension11.create({
2499
+ name: "commentHighlights",
2500
+ addOptions() {
2501
+ return { onSelect: null };
2502
+ },
2147
2503
  addProseMirrorPlugins() {
2504
+ const options = this.options;
2148
2505
  const editor = this.editor;
2149
2506
  return [
2150
2507
  new Plugin7({
2151
- key: key3,
2508
+ key: commentHighlightsKey,
2152
2509
  state: {
2153
- init: () => null,
2154
- apply: (tr, value, before, after) => {
2155
- const meta = tr.getMeta(key3);
2156
- if (meta !== void 0) return meta;
2157
- const placed = justPlaced(tr, after);
2158
- if (placed !== null) return { pos: placed, active: -1 };
2159
- if (!value) return null;
2160
- const pos = tr.mapping.map(value.pos);
2161
- if (!chipAt(after, pos)) return null;
2162
- if (tr.docChanged && !tr.getMeta("appendedTransaction") && tr.getMeta(CHIPS_MADE) === void 0) return null;
2163
- const onChip = after.selection instanceof NodeSelection2 && after.selection.from === pos;
2164
- if (tr.selectionSet && !after.selection.eq(before.selection) && !onChip) return null;
2165
- return pos === value.pos ? value : { ...value, pos };
2510
+ init: () => ({ anchors: [], active: null }),
2511
+ apply(tr, previous) {
2512
+ const meta = tr.getMeta(commentHighlightsKey);
2513
+ return meta ?? previous;
2166
2514
  }
2167
2515
  },
2168
2516
  props: {
2169
- handleDOMEvents: {
2170
- // Focus gone, the keys no longer reach the menu, and a card chosen now would miss the save on leaving (code review).
2171
- blur: (view) => {
2172
- if (key3.getState(view.state)) dispatchMenu(view, null);
2173
- return false;
2174
- }
2517
+ decorations(state) {
2518
+ const { anchors, active } = commentHighlightsKey.getState(state) ?? { anchors: [], active: null };
2519
+ const places = placesIn(state.doc);
2520
+ const drawn = anchors.flatMap((anchor) => {
2521
+ const place2 = placeOf(state.doc, anchor, places);
2522
+ if (place2.state !== "resolved") return [];
2523
+ const attrs = { class: anchor.id === active ? COMMENT_HIGHLIGHT_CLASSES.active : COMMENT_HIGHLIGHT_CLASSES.rest, "data-comment-id": anchor.id };
2524
+ if (place2.words) return [Decoration3.inline(place2.from, place2.to, attrs)];
2525
+ const blocks = [];
2526
+ state.doc.nodesBetween(place2.from, place2.to, (node, pos) => {
2527
+ if (pos < place2.from || pos + node.nodeSize > place2.to) return true;
2528
+ blocks.push(Decoration3.node(pos, pos + node.nodeSize, attrs));
2529
+ return false;
2530
+ });
2531
+ return blocks;
2532
+ });
2533
+ return drawn.length ? DecorationSet3.create(state.doc, drawn) : null;
2175
2534
  },
2176
- handleKeyDown: (view, event) => {
2177
- if (event.shiftKey || event.ctrlKey || event.metaKey || event.altKey) return false;
2178
- const open = key3.getState(view.state);
2179
- if (!open) {
2180
- const { selection } = view.state;
2181
- if (event.key !== "Enter" || !view.editable || !(selection instanceof NodeSelection2) || selection.node.type.name !== "reference") return false;
2182
- if (rowsOf(view, selection.from).length === 0) return false;
2183
- view.dispatch(caretAfter(view.state, selection.from).setMeta(key3, { pos: selection.from, active: 0 }));
2184
- return true;
2185
- }
2186
- const rows = rowsOf(view, open.pos);
2187
- if (event.key === "Escape") {
2188
- dispatchMenu(view, null);
2189
- return true;
2190
- }
2191
- if (rows.length === 0) return false;
2192
- if (event.key === "ArrowDown") {
2193
- dispatchMenu(view, { ...open, active: (open.active + 1) % rows.length });
2194
- return true;
2195
- }
2196
- if (event.key === "ArrowUp") {
2197
- dispatchMenu(view, { ...open, active: open.active <= 0 ? rows.length - 1 : open.active - 1 });
2198
- return true;
2535
+ handleClick(view, pos) {
2536
+ const { anchors } = commentHighlightsKey.getState(view.state) ?? { anchors: [] };
2537
+ const places = placesIn(view.state.doc);
2538
+ let hit = null;
2539
+ for (const anchor of anchors) {
2540
+ const place2 = placeOf(view.state.doc, anchor, places);
2541
+ if (place2.state !== "resolved" || pos < place2.from || pos >= place2.to) continue;
2542
+ const size = place2.to - place2.from;
2543
+ if (!hit || size < hit.size) hit = { id: anchor.id, size };
2199
2544
  }
2200
- if (event.key === "Enter" && open.active >= 0) {
2201
- choose(editor, open.pos, rows[open.active]);
2202
- return true;
2545
+ if (hit) {
2546
+ options.onSelect?.(hit.id);
2547
+ editor.emit("commentSelect", { id: hit.id });
2203
2548
  }
2204
2549
  return false;
2205
2550
  }
@@ -2208,575 +2553,525 @@ var ReferenceMenu = Extension10.create({
2208
2553
  ];
2209
2554
  }
2210
2555
  });
2211
- function ReferenceMenuView({ editor }) {
2212
- const shown = useEditorState({
2213
- editor,
2214
- selector: ({ editor: ed }) => {
2215
- if (!ed || ed.isDestroyed) return null;
2216
- const open = key3.getState(ed.state);
2217
- if (!open) return null;
2218
- const node = chipAt(ed.state, open.pos);
2219
- if (!node) return null;
2220
- const embed = node.attrs.embed;
2221
- const layout = embed === "detailed" ? "detailed" : typeof embed === "string" && embed !== "" && embed !== "none" ? "compact" : "none";
2222
- return { pos: open.pos, active: open.active, named: !!node.attrs.uri, layout };
2223
- }
2224
- });
2225
- const keepFocus2 = useCallback5((list) => {
2226
- const panel = list?.closest('[role="dialog"]');
2227
- if (!panel) return;
2228
- const keep = (event) => event.preventDefault();
2229
- panel.addEventListener("mousedown", keep);
2230
- return () => panel.removeEventListener("mousedown", keep);
2231
- }, []);
2232
- const live = shown && editor && !editor.isDestroyed ? editor : null;
2233
- const dom = live && shown ? live.view.nodeDOM(shown.pos) : null;
2234
- const anchor = dom instanceof HTMLElement ? dom : null;
2235
- const rows = live && shown ? rowsOf(live.view, shown.pos) : [];
2236
- const opens = rows[0] === "open";
2237
- const run = (row) => {
2238
- if (editor && shown) choose(editor, shown.pos, row);
2239
- };
2240
- return (
2241
- // finalFocus={false}: focus never left the text.
2242
- /* @__PURE__ */ jsx8(
2243
- Popover2,
2244
- {
2245
- anchor,
2246
- open: !!shown && !!anchor && rows.length > 0,
2247
- onOpenChange: (next) => {
2248
- if (!next && editor && !editor.isDestroyed && key3.getState(editor.state)) dispatchMenu(editor.view, null);
2249
- },
2250
- side: "bottom",
2251
- align: "left",
2252
- ariaLabel: "Link",
2253
- finalFocus: false,
2254
- children: shown && /* @__PURE__ */ jsxs7("div", { ref: keepFocus2, role: "menu", "aria-label": "Link", className: "flex flex-col gap-0.5", children: [
2255
- opens && /* @__PURE__ */ jsx8(
2256
- MenuItem3,
2257
- {
2258
- role: "menuitem",
2259
- tabIndex: -1,
2260
- label: "Open",
2261
- selected: shown.active === 0,
2262
- onMouseDown: (event) => {
2263
- event.preventDefault();
2264
- run("open");
2265
- }
2266
- }
2267
- ),
2268
- shown.named && /* @__PURE__ */ jsxs7(Fragment3, { children: [
2269
- opens && /* @__PURE__ */ jsx8(MenuSeparator2, {}),
2270
- /* @__PURE__ */ jsx8("div", { role: "group", "aria-label": "Card", children: /* @__PURE__ */ jsx8(MenuSection, { label: "Card", children: LAYOUTS.map(({ layout, label }, i) => /* @__PURE__ */ jsx8(
2271
- MenuItem3,
2272
- {
2273
- role: "menuitemradio",
2274
- "aria-checked": shown.layout === layout,
2275
- tabIndex: -1,
2276
- label,
2277
- selected: shown.active === i + (opens ? 1 : 0),
2278
- trailing: shown.layout === layout ? /* @__PURE__ */ jsx8(IconCheck, { size: 16, "aria-hidden": true }) : void 0,
2279
- onMouseDown: (event) => {
2280
- event.preventDefault();
2281
- run(layout);
2282
- }
2283
- },
2284
- layout
2285
- )) }) })
2286
- ] })
2287
- ] })
2288
- }
2289
- )
2290
- );
2556
+ function setCommentAnchors(editor, anchors, active = null) {
2557
+ if (editor.isDestroyed) return;
2558
+ editor.view.dispatch(editor.state.tr.setMeta(commentHighlightsKey, { anchors, active }));
2291
2559
  }
2292
-
2293
- // src/BlockNodes.tsx
2294
- import { jsx as jsx9 } from "react/jsx-runtime";
2295
- var BLOCK_TYPES = [
2296
- "paragraph",
2297
- "heading",
2298
- "bulletList",
2299
- "orderedList",
2300
- "listItem",
2301
- "blockquote",
2302
- "codeBlock",
2303
- "horizontalRule",
2304
- // A table and everything inside it (UIG-18): a row or a cell whose id was
2305
- // re-minted on each save would detach any comment anchored to it.
2306
- "table",
2307
- "tableRow",
2308
- "tableHeader",
2309
- "tableCell",
2310
- // Without this an attachment's id is re-minted on every save, and every
2311
- // comment anchored to it stops resolving.
2312
- "attachment"
2313
- ];
2314
- var BLOCK_TYPE_SET = new Set(BLOCK_TYPES);
2315
- function newBlockId() {
2316
- return Array.from(crypto.getRandomValues(new Uint8Array(6)), (b) => b.toString(16).padStart(2, "0")).join("");
2560
+ function commentPlace(editor, anchor) {
2561
+ return placeOf(editor.state.doc, anchor);
2317
2562
  }
2318
- function holdsText(node) {
2319
- let found = false;
2320
- node.descendants((child) => {
2321
- if (found) return false;
2322
- if (child.isText && child.text !== "" || child.type.name === "hardBreak" || child.type.name === "reference") found = true;
2323
- return !found;
2324
- });
2325
- return found;
2563
+ function commentElement(editor, anchor) {
2564
+ const drawn = editor.view.dom.querySelector(`[data-comment-id="${CSS.escape(anchor.id)}"]`);
2565
+ if (drawn) return drawn;
2566
+ const place2 = placeOf(editor.state.doc, anchor);
2567
+ if (place2.state === "detached") return null;
2568
+ const dom = editor.view.nodeDOM(place2.from);
2569
+ return dom instanceof HTMLElement ? dom : null;
2326
2570
  }
2327
- function claimsIn(doc2) {
2328
- const claims = /* @__PURE__ */ new Map();
2329
- doc2.descendants((node, pos, parent) => {
2330
- const fixed = node.type.name === "unknownBlock";
2331
- if (!fixed && !BLOCK_TYPE_SET.has(node.type.name)) return;
2332
- if (parent?.type.name === "listItem" && LISTS3.has(node.type.name)) return;
2333
- const id = node.attrs.blockId;
2334
- if (typeof id !== "string" || id === "") return;
2335
- const copies = claims.get(id);
2336
- if (copies) copies.push({ pos, node, fixed });
2337
- else claims.set(id, [{ pos, node, fixed }]);
2338
- });
2339
- return claims;
2571
+ function quoteText(quote) {
2572
+ return quote.end ? `${quote.start} \u2026 ${quote.end}` : quote.start;
2340
2573
  }
2341
- function carriedOn(copies, before, mapping) {
2342
- if (before.node.isLeaf) {
2343
- const at2 = mapping.map(before.pos, 1);
2344
- return copies.find((c) => c.pos === at2);
2574
+ function headOf(text, length) {
2575
+ if (text.length <= length) return text;
2576
+ const cut = text.lastIndexOf(" ", length);
2577
+ return text.slice(0, cut > length / 2 ? cut : length);
2578
+ }
2579
+ function tailOf(text, length) {
2580
+ if (text.length <= length) return text;
2581
+ const from = text.length - length;
2582
+ const cut = text.indexOf(" ", from);
2583
+ return text.slice(cut !== -1 && cut < from + length / 2 ? cut + 1 : from);
2584
+ }
2585
+ function occurrences(text, words) {
2586
+ let count = 0;
2587
+ for (let at = text.indexOf(words); words && at !== -1; at = text.indexOf(words, at + 1)) count++;
2588
+ return count;
2589
+ }
2590
+ function offsetIn(block, pos) {
2591
+ const at = block.starts.findIndex((start) => start >= pos);
2592
+ return at === -1 ? block.starts.length : at;
2593
+ }
2594
+ function anchorOfSelection(editor) {
2595
+ const { doc: doc2, selection } = editor.state;
2596
+ if (selection.empty) return null;
2597
+ const { $from, $to } = selection;
2598
+ const places = placesIn(doc2);
2599
+ const around = (depth) => {
2600
+ for (let d = depth; d > 0; d--) {
2601
+ const id = $from.node(d).attrs.blockId;
2602
+ if (typeof id === "string" && id && places.has(id)) return places.get(id);
2603
+ }
2604
+ return void 0;
2605
+ };
2606
+ let run;
2607
+ if ($from.parent === $to.parent && $from.parent.isTextblock) {
2608
+ const found = around($from.depth);
2609
+ if (!found) return null;
2610
+ run = [found];
2611
+ } else {
2612
+ const depth = $from.sharedDepth($to.pos);
2613
+ const low = $from.index(depth);
2614
+ const high = $to.pos >= $to.end(depth) ? $from.node(depth).childCount - 1 : $to.index(depth);
2615
+ run = [];
2616
+ for (let i = low; i <= high; i++) {
2617
+ const id = $from.node(depth).child(i).attrs.blockId;
2618
+ const place2 = typeof id === "string" ? places.get(id) : void 0;
2619
+ if (!place2) {
2620
+ const found = around(depth);
2621
+ if (!found) return null;
2622
+ run = [found];
2623
+ break;
2624
+ }
2625
+ run.push(place2);
2626
+ }
2345
2627
  }
2346
- const at = mapping.map(textStart(before), 1);
2347
- return copies.find((c) => c.pos < at && at < c.pos + c.node.nodeSize);
2628
+ let firstText = textOf(run[0]);
2629
+ let lastText = run.length === 1 ? firstText : textOf(run[run.length - 1]);
2630
+ let start = offsetIn(firstText, selection.from);
2631
+ let end = offsetIn(lastText, selection.to);
2632
+ if (run.length > 1 && start >= firstText.text.length) run = run.slice(1), firstText = textOf(run[0]), start = 0;
2633
+ if (run.length > 1 && end <= 0) run = run.slice(0, -1), lastText = textOf(run[run.length - 1]), end = lastText.text.length;
2634
+ if (run.length === 1) lastText = firstText;
2635
+ if (run.length === 1 && firstText.text && start >= end) return null;
2636
+ if (run.length === 1 && firstText.text && !firstText.text.slice(start, end).replace(/\n/g, "")) return null;
2637
+ const blocks = run.map((p) => p.node.attrs.blockId);
2638
+ if (start === 0 && end >= lastText.text.length) return { blocks };
2639
+ const single = run.length === 1;
2640
+ const quote = { start: "" };
2641
+ if (single && end - start <= QUOTE_WHOLE_MAX) {
2642
+ quote.start = firstText.text.slice(start, end);
2643
+ } else {
2644
+ const startWords = single ? firstText.text.slice(start, end) : firstText.text.slice(start);
2645
+ const endWords = single ? startWords : lastText.text.slice(0, end);
2646
+ quote.start = headOf(startWords, QUOTE_END_LENGTH);
2647
+ quote.end = tailOf(endWords, QUOTE_END_LENGTH);
2648
+ }
2649
+ if (!quote.start || quote.end === "") return { blocks };
2650
+ const prefix = firstText.text.slice(Math.max(0, start - QUOTE_CONTEXT_LENGTH), start);
2651
+ const suffix = lastText.text.slice(end, end + QUOTE_CONTEXT_LENGTH);
2652
+ if (prefix && occurrences(firstText.text, quote.start) > 1) quote.prefix = prefix;
2653
+ if (suffix && occurrences(lastText.text, quote.end ?? quote.start) > 1) quote.suffix = suffix;
2654
+ return { blocks, quote };
2348
2655
  }
2349
- function textStart({ pos, node }) {
2350
- let start = pos + 1;
2351
- if (!node.isTextblock) {
2352
- let found = false;
2353
- node.descendants((child, at) => {
2354
- if (found) return false;
2355
- if (child.isTextblock) {
2356
- start = pos + 1 + at + 1;
2357
- found = true;
2358
- }
2359
- return !found;
2360
- });
2656
+
2657
+ // src/PastedMarkdown.ts
2658
+ import { Extension as Extension12 } from "@tiptap/core";
2659
+ import { Slice } from "@tiptap/pm/model";
2660
+ import { Plugin as Plugin8, PluginKey as PluginKey9 } from "@tiptap/pm/state";
2661
+ function inTableCell($context) {
2662
+ for (let depth = $context.depth; depth > 0; depth--) {
2663
+ const role = $context.node(depth).type.spec.tableRole;
2664
+ if (role === "cell" || role === "header_cell") return true;
2361
2665
  }
2362
- return start;
2666
+ return false;
2363
2667
  }
2364
- function repeatedBlockIds(doc2, before, mapping) {
2365
- const claims = claimsIn(doc2);
2366
- let previous;
2367
- const losers = [];
2368
- for (const [id, copies] of claims) {
2369
- if (copies.length < 2) continue;
2370
- previous ??= claimsIn(before);
2371
- const original = previous.get(id)?.[0];
2372
- const owner = copies.find((c) => c.fixed) ?? (original && carriedOn(copies, original, mapping)) ?? copies.find((c) => holdsText(c.node)) ?? copies[0];
2373
- for (const copy of copies) if (copy !== owner && !copy.fixed) losers.push(copy.pos);
2668
+ var hasTable = (blocks) => blocks.some((block) => block.type === "table" || hasTable(block.content ?? []));
2669
+ var PastedMarkdown = Extension12.create({
2670
+ name: "pastedMarkdown",
2671
+ addOptions() {
2672
+ return { read: () => void 0 };
2673
+ },
2674
+ addProseMirrorPlugins() {
2675
+ const options = this.options;
2676
+ return [
2677
+ new Plugin8({
2678
+ key: new PluginKey9("pastedMarkdown"),
2679
+ props: {
2680
+ // Reached only for a text paste outside code; `plain` is the Shift paste.
2681
+ clipboardTextParser: (text, $context, plain, view) => {
2682
+ if (plain) return void 0;
2683
+ try {
2684
+ const blocks = options.read(text.replace(/\r\n?/g, "\n"))?.content ?? [];
2685
+ if (blocks.every((block) => block.type === "paragraph")) return void 0;
2686
+ if (inTableCell($context) && hasTable(blocks)) return void 0;
2687
+ return Slice.maxOpen(view.state.schema.nodeFromJSON({ type: "doc", content: blocks }).content);
2688
+ } catch {
2689
+ return void 0;
2690
+ }
2691
+ }
2692
+ }
2693
+ })
2694
+ ];
2374
2695
  }
2375
- return losers;
2696
+ });
2697
+
2698
+ // src/CodeBlockColours.ts
2699
+ import { CodeBlockLowlight } from "@tiptap/extension-code-block-lowlight";
2700
+
2701
+ // src/codeColours.ts
2702
+ import { createElement } from "react";
2703
+ import { common, createLowlight } from "lowlight";
2704
+ var instance;
2705
+ function lowlight() {
2706
+ return instance ??= createLowlight(common);
2376
2707
  }
2377
- var BLOCK_CONTAINERS = /* @__PURE__ */ new Set(["bulletList", "orderedList", "table", "tableRow", "tableHeader", "tableCell"]);
2378
- var FLATTENED = /* @__PURE__ */ new Set(["listItem", "blockquote"]);
2379
- var LISTS3 = /* @__PURE__ */ new Set(["bulletList", "orderedList"]);
2380
- function innerLists(item, pos) {
2708
+
2709
+ // src/CodeBlockColours.ts
2710
+ var namedOnly = {
2711
+ highlight: (language, value) => lowlight().highlight(language, value),
2712
+ highlightAuto: (value) => ({ type: "root", children: [{ type: "text", value }], data: { language: void 0, relevance: 0 } }),
2713
+ listLanguages: () => lowlight().listLanguages(),
2714
+ registered: (language) => lowlight().registered(language)
2715
+ };
2716
+ var CodeBlockColours = CodeBlockLowlight.configure({ lowlight: namedOnly });
2717
+
2718
+ // src/EditorBlockHandle.tsx
2719
+ import { useMemo } from "react";
2720
+ import { IconCopy, IconTrash } from "@tabler/icons-react";
2721
+ import { BlockHandle, blockAtY } from "@estiva-app/ui";
2722
+ import { Selection } from "@tiptap/pm/state";
2723
+ import { MenuItem as MenuItem2, MenuSub } from "@estiva-app/ui";
2724
+ import { Fragment as Fragment3, jsx as jsx9, jsxs as jsxs7 } from "react/jsx-runtime";
2725
+ function editorBlocks(view) {
2381
2726
  const out = [];
2382
- item.forEach((child, offset) => {
2383
- if (LISTS3.has(child.type.name)) out.push({ pos: pos + 1 + offset, node: child });
2727
+ view.state.doc.forEach((node, pos) => {
2728
+ const element = view.nodeDOM(pos);
2729
+ if (element instanceof HTMLElement) out.push({ id: node.attrs.blockId || void 0, element, pos });
2384
2730
  });
2385
2731
  return out;
2386
2732
  }
2387
- var idOf = (node) => {
2388
- const id = node.attrs.blockId;
2389
- return typeof id === "string" && id !== "" ? id : void 0;
2390
- };
2391
- function addressedBlocks(doc2) {
2392
- const out = [];
2393
- const visit = (node, pos) => {
2394
- if (!BLOCK_TYPE_SET.has(node.type.name)) return;
2395
- out.push({ pos, node });
2396
- if (BLOCK_CONTAINERS.has(node.type.name)) node.forEach((child, offset) => visit(child, pos + 1 + offset));
2397
- if (node.type.name === "listItem") {
2398
- for (const list of innerLists(node, pos)) list.node.forEach((child, offset) => visit(child, list.pos + 1 + offset));
2399
- }
2400
- };
2401
- doc2.forEach((node, offset) => visit(node, offset));
2402
- return out;
2733
+ function duplicateBlock(editor, pos) {
2734
+ const node = editor.state.doc.nodeAt(pos);
2735
+ if (!node) return false;
2736
+ editor.view.dispatch(editor.state.tr.insert(pos + node.nodeSize, node).scrollIntoView());
2737
+ editor.commands.focus(pos + node.nodeSize + 1);
2738
+ return true;
2403
2739
  }
2404
- function unnamedBlocks(doc2) {
2405
- return addressedBlocks(doc2).filter((b) => idOf(b.node) === void 0).map((b) => b.pos);
2740
+ function deleteBlock(editor, pos) {
2741
+ const { state } = editor;
2742
+ const node = state.doc.nodeAt(pos);
2743
+ if (!node) return false;
2744
+ const tr = state.doc.childCount === 1 ? state.tr.replaceWith(pos, pos + node.nodeSize, state.schema.nodes.paragraph.create()) : state.tr.delete(pos, pos + node.nodeSize);
2745
+ editor.view.dispatch(tr);
2746
+ editor.commands.focus(Math.min(pos + 1, editor.state.doc.content.size));
2747
+ return true;
2406
2748
  }
2407
- function hiddenIds(doc2) {
2749
+ function moveBlock(editor, from, to) {
2750
+ const node = editor.state.doc.nodeAt(from);
2751
+ if (!node || to >= from && to <= from + node.nodeSize) return false;
2752
+ const tr = editor.state.tr.delete(from, from + node.nodeSize);
2753
+ const at = tr.mapping.map(to);
2754
+ editor.view.dispatch(tr.insert(at, node).scrollIntoView());
2755
+ editor.commands.focus(at + 1);
2756
+ return true;
2757
+ }
2758
+ function startBlockDrag(editor, pos, event, image) {
2759
+ editor.commands.setNodeSelection(pos);
2760
+ const { view } = editor;
2761
+ const slice = view.state.selection.content();
2762
+ const { dom, text } = view.serializeForClipboard(slice);
2763
+ const transfer = event.dataTransfer;
2764
+ if (transfer) {
2765
+ transfer.clearData();
2766
+ transfer.setData("text/html", dom.innerHTML);
2767
+ transfer.setData("text/plain", text);
2768
+ transfer.effectAllowed = "copyMove";
2769
+ if (image) transfer.setDragImage(image, 0, 0);
2770
+ }
2771
+ view.dragging = { slice, move: true };
2772
+ }
2773
+ var blockDropCursor = { color: false, class: "bg-accent-primary" };
2774
+ var NOTHING_YET = { find: () => null, rows: () => null, startDrag: () => {
2775
+ }, drop: () => {
2776
+ }, endDrag: () => {
2777
+ }, onChange: () => () => {
2778
+ } };
2779
+ function EditorBlockHandle({ editor, turnInto = turnIntoRows, actions, children, className }) {
2780
+ const editing = useMemo(() => {
2781
+ if (!editor) return NOTHING_YET;
2782
+ let dragged;
2783
+ return {
2784
+ find: (y) => blockAtY(editorBlocks(editor.view), y),
2785
+ rows: (block) => {
2786
+ const pos = block.pos;
2787
+ if (!editor.isEditable) return null;
2788
+ const node = pos === void 0 ? null : editor.state.doc.nodeAt(pos);
2789
+ if (pos === void 0 || !node) return null;
2790
+ const turnRows = typeof turnInto === "function" ? turnInto(node, editor) : node.isTextblock ? turnInto : [];
2791
+ return /* @__PURE__ */ jsxs7(Fragment3, { children: [
2792
+ turnRows.length > 0 && /* @__PURE__ */ jsx9(MenuSub, { label: "Turn into", children: turnRows.map((row) => /* @__PURE__ */ jsx9(
2793
+ MenuItem2,
2794
+ {
2795
+ label: row.label,
2796
+ selected: row.active?.(node) ?? false,
2797
+ onClick: () => {
2798
+ if (node.isTextblock) editor.chain().focus().setTextSelection(pos + 1).run();
2799
+ row.run(editor, pos);
2800
+ }
2801
+ },
2802
+ row.label
2803
+ )) }),
2804
+ /* @__PURE__ */ jsx9(MenuItem2, { label: "Duplicate", leading: /* @__PURE__ */ jsx9(IconCopy, { size: 16, stroke: 1.5, className: "text-text-secondary" }), onClick: () => duplicateBlock(editor, pos) }),
2805
+ /* @__PURE__ */ jsx9(MenuItem2, { label: "Delete", destructive: true, leading: /* @__PURE__ */ jsx9(IconTrash, { size: 16, stroke: 1.5, className: "text-error-default" }), onClick: () => deleteBlock(editor, pos) })
2806
+ ] });
2807
+ },
2808
+ startDrag: (block, event) => {
2809
+ dragged = block.pos;
2810
+ if (block.pos !== void 0) startBlockDrag(editor, block.pos, event, block.element);
2811
+ },
2812
+ drop: (target, after) => {
2813
+ const node = target.pos === void 0 ? null : editor.state.doc.nodeAt(target.pos);
2814
+ if (dragged === void 0 || target.pos === void 0 || !node) return;
2815
+ moveBlock(editor, dragged, after ? target.pos + node.nodeSize : target.pos);
2816
+ },
2817
+ // ProseMirror clears `dragging` on its own dragend, which a drag started outside its element never reaches.
2818
+ endDrag: () => setTimeout(() => editor.view.dragging = null, 50),
2819
+ onChange: (changed) => {
2820
+ editor.on("update", changed);
2821
+ return () => {
2822
+ editor.off("update", changed);
2823
+ };
2824
+ }
2825
+ };
2826
+ }, [editor, turnInto]);
2827
+ return /* @__PURE__ */ jsx9(BlockHandle, { editing, actions, className, children });
2828
+ }
2829
+ var LISTS3 = ["bulletList", "orderedList"];
2830
+ var isList = (node) => LISTS3.includes(node.type.name);
2831
+ function listItems(list, at) {
2408
2832
  const out = [];
2409
- doc2.descendants((node, pos) => {
2410
- if (!FLATTENED.has(node.type.name)) return;
2411
- node.forEach((child, offset) => {
2412
- const inner = child.isTextblock || node.type.name === "listItem" && LISTS3.has(child.type.name);
2413
- if (inner && idOf(child) !== void 0) out.push(pos + 1 + offset);
2414
- });
2833
+ list.descendants((node, pos) => {
2834
+ if (node.type.name === "listItem") out.push({ node, pos: at + 1 + pos });
2415
2835
  });
2416
2836
  return out;
2417
2837
  }
2418
- function handedOver(doc2, before, mapping, unnamed) {
2419
- const out = /* @__PURE__ */ new Map();
2420
- if (unnamed.length === 0) return out;
2421
- const now = new Set(addressedBlocks(doc2).map((b) => idOf(b.node)));
2422
- const gone = addressedBlocks(before).filter((b) => !b.node.isLeaf && idOf(b.node) !== void 0 && !now.has(idOf(b.node))).map((b) => ({ ...b, start: textStart(b) })).sort((a, b) => a.start - b.start || b.pos - a.pos);
2423
- for (const old of gone) {
2424
- const id = idOf(old.node);
2425
- const { pos: at, deleted } = mapping.mapResult(old.start, -1);
2426
- if (deleted) continue;
2427
- let inner;
2428
- for (const pos of unnamed) {
2429
- if (out.has(pos)) continue;
2430
- if (pos < at && at < pos + doc2.nodeAt(pos).nodeSize && (inner === void 0 || pos > inner)) inner = pos;
2838
+ var isChecklistItem = ({ node }) => typeof node.attrs.checked === "boolean";
2839
+ var isChecklist = (list) => listItems(list, 0).every(isChecklistItem);
2840
+ var isPlainList = (list, type) => list.type.name === type && !listItems(list, 0).some(isChecklistItem);
2841
+ var hasExtension = (editor, name) => editor.extensionManager.extensions.some((e) => e.name === name);
2842
+ function caretInto(editor, pos) {
2843
+ const { state } = editor;
2844
+ editor.view.dispatch(state.tr.setSelection(Selection.near(state.doc.resolve(Math.min(pos + 1, state.doc.content.size)))));
2845
+ editor.commands.focus();
2846
+ }
2847
+ function turnListInto(editor, pos, kind) {
2848
+ const { state } = editor;
2849
+ const list = state.doc.nodeAt(pos);
2850
+ if (!list || !isList(list)) return false;
2851
+ const tr = state.tr;
2852
+ if (kind === "text") {
2853
+ const blocks = [];
2854
+ for (const { node: item } of listItems(list, pos)) {
2855
+ item.forEach((child, _offset, index) => {
2856
+ if (isList(child)) return;
2857
+ blocks.push(child.type.create({ ...child.attrs, blockId: index === 0 ? item.attrs.blockId : null }, child.content, child.marks));
2858
+ });
2431
2859
  }
2432
- if (inner !== void 0) {
2433
- out.set(inner, id);
2434
- now.add(id);
2860
+ tr.replaceWith(pos, pos + list.nodeSize, blocks);
2861
+ } else {
2862
+ const type = kind === "checklist" ? list.type : state.schema.nodes[kind];
2863
+ if (list.type !== type) tr.setNodeMarkup(pos, type, list.attrs);
2864
+ list.descendants((node, at) => {
2865
+ if (isList(node) && node.type !== type) tr.setNodeMarkup(pos + 1 + at, type, node.attrs);
2866
+ });
2867
+ for (const { node, pos: at } of listItems(list, pos)) {
2868
+ const checked = kind === "checklist" ? typeof node.attrs.checked === "boolean" ? node.attrs.checked : false : null;
2869
+ if (node.attrs.checked !== checked) tr.setNodeAttribute(at, "checked", checked);
2435
2870
  }
2436
2871
  }
2437
- return out;
2438
- }
2439
- function bringsInBlocks(transactions) {
2440
- return transactions.some(
2441
- (tr) => tr.steps.some((step) => {
2442
- if (step instanceof ReplaceAroundStep) return true;
2443
- const slice = step.slice;
2444
- let blocks = false;
2445
- slice?.content.forEach((node) => {
2446
- if (node.isBlock) blocks = true;
2447
- });
2448
- return blocks;
2449
- })
2450
- );
2872
+ if (tr.docChanged) editor.view.dispatch(tr.scrollIntoView());
2873
+ caretInto(editor, pos);
2874
+ return true;
2451
2875
  }
2452
- var BlockId = Extension11.create({
2453
- name: "blockId",
2454
- onCreate() {
2455
- const { state, view } = this.editor;
2456
- const unnamed = unnamedBlocks(state.doc);
2457
- if (unnamed.length === 0) return;
2458
- const tr = state.tr;
2459
- for (const pos of unnamed) tr.setNodeAttribute(pos, "blockId", newBlockId());
2460
- view.dispatch(tr.setMeta("addToHistory", false).setMeta("preventUpdate", true));
2461
- },
2462
- addProseMirrorPlugins() {
2463
- return [
2464
- new Plugin8({
2465
- key: new PluginKey9("blockIdSplit"),
2466
- appendTransaction: (transactions, old, state) => {
2467
- if (!bringsInBlocks(transactions)) return null;
2468
- const mapping = new Mapping();
2469
- for (const tr2 of transactions) mapping.appendMapping(tr2.mapping);
2470
- const unnamed = unnamedBlocks(state.doc);
2471
- const handed = handedOver(state.doc, old.doc, mapping, unnamed);
2472
- const ids = /* @__PURE__ */ new Map();
2473
- for (const pos of repeatedBlockIds(state.doc, old.doc, mapping)) ids.set(pos, newBlockId());
2474
- for (const pos of unnamed) ids.set(pos, handed.get(pos) ?? newBlockId());
2475
- for (const pos of hiddenIds(state.doc)) ids.set(pos, null);
2476
- if (ids.size === 0) return null;
2477
- const tr = state.tr;
2478
- for (const [pos, id] of ids) tr.setNodeAttribute(pos, "blockId", id);
2479
- return tr;
2480
- }
2481
- })
2482
- ];
2483
- },
2484
- addGlobalAttributes() {
2485
- return [
2486
- {
2487
- types: BLOCK_TYPES,
2488
- attributes: {
2489
- blockId: {
2490
- default: null,
2491
- parseHTML: (element) => element.getAttribute("data-block-id"),
2492
- renderHTML: (attributes) => attributes.blockId ? { "data-block-id": String(attributes.blockId) } : {}
2493
- }
2494
- }
2495
- }
2496
- ];
2876
+ function turnQuoteInto(editor, pos, kind) {
2877
+ const { state } = editor;
2878
+ const quote = state.doc.nodeAt(pos);
2879
+ if (!quote || quote.type.name !== "blockquote") return false;
2880
+ const tr = state.tr;
2881
+ if (kind === "text") {
2882
+ const blocks = [];
2883
+ quote.forEach((child) => blocks.push(blocks.length === 0 ? child.type.create({ ...child.attrs, blockId: quote.attrs.blockId }, child.content, child.marks) : child));
2884
+ tr.replaceWith(pos, pos + quote.nodeSize, blocks);
2885
+ } else {
2886
+ const tone = kind === "quote" ? null : kind;
2887
+ if ((quote.attrs.tone ?? null) !== tone) tr.setNodeAttribute(pos, "tone", tone);
2497
2888
  }
2498
- });
2499
- var webUrl = (raw) => raw && /^https?:\/\/\S+$/i.test(raw) ? raw : null;
2500
- var ReferenceNode = Node3.create({
2501
- name: "reference",
2502
- group: "inline",
2503
- inline: true,
2504
- atom: true,
2505
- selectable: true,
2506
- draggable: false,
2507
- addOptions() {
2508
- return { view: null };
2509
- },
2510
- addAttributes() {
2511
- return {
2512
- // A pasted URL chip keeps only its URL: what it names is the editor's to resolve (`LinkChips`), never
2513
- // the clipboard's, which could show one object while saving another URL (security review).
2514
- uri: { default: "", parseHTML: (element) => webUrl(element.getAttribute("data-href")) ? "" : element.getAttribute("data-reference") ?? "" },
2515
- marks: { default: [] },
2516
- embed: { default: null, parseHTML: (element) => element.getAttribute("data-embed") },
2517
- extra: { default: null, parseHTML: () => null },
2518
- // An http(s) URL only: `LinkChips` makes no other, and a pasted `javascript:` must not reach a saved link.
2519
- href: { default: null, parseHTML: (element) => webUrl(element.getAttribute("data-href")) }
2520
- };
2521
- },
2522
- parseHTML() {
2523
- return [{ tag: "span[data-reference]" }];
2524
- },
2525
- renderHTML({ node }) {
2526
- const embed = typeof node.attrs.embed === "string" ? { "data-embed": node.attrs.embed } : {};
2527
- const href = typeof node.attrs.href === "string" && node.attrs.href ? { "data-href": node.attrs.href } : {};
2528
- return ["span", { "data-reference": String(node.attrs.uri), ...embed, ...href }, String(node.attrs.href || node.attrs.uri)];
2529
- },
2530
- renderText({ node }) {
2531
- return String(node.attrs.href || node.attrs.uri);
2532
- },
2533
- addNodeView() {
2534
- const View = this.options.view;
2535
- if (!View) return null;
2536
- return ReactNodeViewRenderer2(({ node, editor, getPos }) => {
2537
- const uri = String(node.attrs.uri ?? "");
2538
- const href = typeof node.attrs.href === "string" && node.attrs.href ? node.attrs.href : void 0;
2539
- return /* @__PURE__ */ jsx9(
2540
- NodeViewWrapper2,
2541
- {
2542
- as: "span",
2543
- className: "inline",
2544
- onClickCapture: (event) => {
2545
- const pos = getPos();
2546
- if (typeof pos !== "number" || !referenceMenuClick(editor, pos)) return;
2547
- event.preventDefault();
2548
- event.stopPropagation();
2549
- },
2550
- children: uri ? /* @__PURE__ */ jsx9(View, { uri, ...href ? { href } : {} }) : /* @__PURE__ */ jsx9("span", { children: href })
2551
- }
2552
- );
2553
- });
2889
+ if (tr.docChanged) editor.view.dispatch(tr.scrollIntoView());
2890
+ caretInto(editor, pos);
2891
+ return true;
2892
+ }
2893
+ function isFormat(node, id) {
2894
+ if (id === "paragraph") return node.type.name === "paragraph";
2895
+ if (id === "heading") return node.type.name === "heading" && node.attrs.level === 1;
2896
+ if (id === "subheading") return node.type.name === "heading" && node.attrs.level === 2;
2897
+ if (id === "code") return node.type.name === "codeBlock";
2898
+ return false;
2899
+ }
2900
+ function turnIntoRows(node, editor) {
2901
+ const checklist = hasExtension(editor, "checklist");
2902
+ const callout = hasExtension(editor, "callout");
2903
+ if (node.isTextblock) {
2904
+ const document2 = DOCUMENT_FORMATS.filter((f) => f.id === "checklist" ? checklist : callout);
2905
+ return [...FORMATS, ...document2].map((format) => ({
2906
+ label: format.label,
2907
+ run: (e) => void applyFormat(e, format.id, "block"),
2908
+ active: (n) => isFormat(n, format.id)
2909
+ }));
2554
2910
  }
2555
- });
2556
- var UnknownBlock = Node3.create({
2557
- name: "unknownBlock",
2558
- group: "block",
2559
- atom: true,
2560
- selectable: true,
2561
- addAttributes() {
2562
- return {
2563
- blockId: { default: null },
2564
- source: { default: null },
2565
- text: { default: "" }
2566
- };
2567
- },
2568
- parseHTML() {
2569
- return [{ tag: "div[data-unknown-block]" }];
2570
- },
2571
- renderHTML({ node }) {
2572
- return ["div", { "data-unknown-block": String(node.attrs.blockId ?? "") }, String(node.attrs.text ?? "")];
2573
- },
2574
- addNodeView() {
2575
- return ReactNodeViewRenderer2(UnknownBlockView);
2911
+ if (isList(node)) {
2912
+ const rows = [
2913
+ { label: "Bulleted list", run: (e, pos) => void turnListInto(e, pos, "bulletList"), active: (n) => isPlainList(n, "bulletList") },
2914
+ { label: "Numbered list", run: (e, pos) => void turnListInto(e, pos, "orderedList"), active: (n) => isPlainList(n, "orderedList") }
2915
+ ];
2916
+ if (checklist) rows.push({ label: "Checklist", run: (e, pos) => void turnListInto(e, pos, "checklist"), active: isChecklist });
2917
+ rows.push({ label: "Text", run: (e, pos) => void turnListInto(e, pos, "text") });
2918
+ return rows;
2576
2919
  }
2577
- });
2578
- function UnknownBlockView({ node }) {
2579
- const source = node.attrs.source;
2580
- const text = String(node.attrs.text ?? "");
2581
- return /* @__PURE__ */ jsx9(
2582
- NodeViewWrapper2,
2583
- {
2584
- "data-block-id": source?.id,
2585
- "data-block-type": source?.type,
2586
- className: "rounded-md border border-border-default bg-bg-inset px-2 py-1 text-text-secondary",
2587
- children: text || `A ${source?.type ?? "block"} this app cannot edit yet.`
2588
- }
2589
- );
2590
- }
2591
- var AttachmentNode = Node3.create({
2592
- name: "attachment",
2593
- group: "block",
2594
- atom: true,
2595
- selectable: true,
2596
- draggable: false,
2597
- addOptions() {
2598
- return { view: null };
2599
- },
2600
- addAttributes() {
2601
- return {
2602
- url: { default: "" },
2603
- m: { default: "" },
2604
- x: { default: "" },
2605
- size: { default: 0 },
2606
- dim: { default: null },
2607
- thumb: { default: null },
2608
- alt: { default: null },
2609
- filename: { default: null }
2610
- };
2611
- },
2612
- parseHTML() {
2613
- return [{ tag: "div[data-attachment-block]" }];
2614
- },
2615
- renderHTML({ node }) {
2616
- return ["div", { "data-attachment-block": String(node.attrs.x ?? "") }, String(node.attrs.filename ?? "attachment")];
2617
- },
2618
- addNodeView() {
2619
- const View = this.options.view;
2620
- if (!View) return null;
2621
- return ReactNodeViewRenderer2(({ node }) => /* @__PURE__ */ jsx9(NodeViewWrapper2, { className: "my-2", children: /* @__PURE__ */ jsx9(View, { attrs: node.attrs }) }));
2920
+ if (node.type.name === "blockquote") {
2921
+ const rows = [{ label: "Quote", run: (e, pos) => void turnQuoteInto(e, pos, "quote"), active: (n) => !n.attrs.tone }];
2922
+ if (callout) {
2923
+ rows.push({ label: "Note", run: (e, pos) => void turnQuoteInto(e, pos, "note"), active: (n) => n.attrs.tone === "note" });
2924
+ rows.push({ label: "Warning", run: (e, pos) => void turnQuoteInto(e, pos, "warning"), active: (n) => n.attrs.tone === "warning" });
2925
+ }
2926
+ rows.push({ label: "Text", run: (e, pos) => void turnQuoteInto(e, pos, "text") });
2927
+ return rows;
2622
2928
  }
2623
- });
2624
- var TICK = "checklistTick";
2625
- function isChecklistTick(transaction) {
2626
- return transaction.getMeta(TICK) === true;
2929
+ return [];
2627
2930
  }
2628
- function named(chain, command, ...args) {
2629
- const own = chain[command];
2630
- return own ? own(...args) : chain;
2931
+
2932
+ // src/EditorTableControls.tsx
2933
+ import { useCallback as useCallback6, useEffect as useEffect6, useRef as useRef5, useState as useState6 } from "react";
2934
+ import { TextSelection as TextSelection2 } from "@tiptap/pm/state";
2935
+ import { addColumnAfter, addColumnBefore, addRowAfter, addRowBefore, deleteColumn, deleteRow, deleteTable, toggleHeader } from "@tiptap/pm/tables";
2936
+ import { IconColumnInsertLeft, IconColumnInsertRight, IconGripHorizontal, IconGripVertical, IconPlus, IconRowInsertBottom, IconRowInsertTop, IconTrash as IconTrash2 } from "@tabler/icons-react";
2937
+ import { cn as cn4 } from "@estiva-app/ui";
2938
+ import { IconButton as IconButton2 } from "@estiva-app/ui";
2939
+ import { Menu, MenuItem as MenuItem3, MenuSeparator as MenuSeparator2 } from "@estiva-app/ui";
2940
+ import { Fragment as Fragment4, jsx as jsx10, jsxs as jsxs8 } from "react/jsx-runtime";
2941
+ function inCell(editor, cell, command) {
2942
+ const { view } = editor;
2943
+ if (!view.dom.contains(cell)) return false;
2944
+ const at = view.posAtDOM(cell, 0);
2945
+ view.dispatch(view.state.tr.setSelection(TextSelection2.near(view.state.doc.resolve(at))));
2946
+ const done = command(view.state, view.dispatch, view);
2947
+ editor.commands.focus();
2948
+ return done;
2631
2949
  }
2632
- function itemAtCaret(state) {
2633
- const { $from } = state.selection;
2634
- if ($from.depth < 2) return null;
2635
- const item = $from.node(-1);
2636
- if (item.type.name !== "listItem" || $from.index(-1) !== 0) return null;
2637
- return { node: item, pos: $from.before(-1) };
2950
+ function isHeaderRow(row) {
2951
+ return row.cells.length > 0 && Array.from(row.cells).every((c) => c.tagName === "TH");
2638
2952
  }
2639
- var sameAttrs = (a, b) => Object.keys({ ...a.attrs, ...b.attrs }).every((key4) => a.attrs[key4] === b.attrs[key4]);
2640
- function listItemView(editor, node, view, getPos) {
2641
- const toDOM = node.type.spec.toDOM;
2642
- const { dom, contentDOM } = toDOM ? DOMSerializer.renderSpec(document, toDOM(node)) : { dom: document.createElement("li"), contentDOM: void 0 };
2643
- const checked = node.attrs.checked;
2644
- if (typeof checked !== "boolean") return { dom, contentDOM: contentDOM ?? dom, update: (next) => next.type === node.type && sameAttrs(next, node) };
2645
- const li = dom;
2646
- const box = document.createElement("span");
2647
- box.contentEditable = "false";
2648
- box.setAttribute("data-checklist-box", "");
2649
- const body = document.createElement("div");
2650
- li.replaceChildren(box, body);
2651
- const tick = (next) => {
2652
- const pos = getPos();
2653
- if (pos === void 0 || !view.editable) return;
2654
- view.dispatch(view.state.tr.setNodeAttribute(pos, "checked", next).setMeta(TICK, true));
2655
- };
2656
- let words = node.firstChild?.textContent.trim() || "Item";
2657
- const props = () => ({ checked, onChange: view.editable ? tick : void 0, "aria-label": words });
2658
- const renderer = new ReactRenderer2(Checkbox, { editor, props: props(), as: "span" });
2659
- box.appendChild(renderer.element);
2660
- let drawn = "";
2661
- const sync = () => {
2662
- const now = `${view.editable}:${words}`;
2663
- if (now === drawn) return;
2664
- drawn = now;
2665
- renderer.updateProps(props());
2666
- for (const [name, value] of Object.entries({ role: "checkbox", "aria-checked": String(checked), "aria-readonly": "true", "aria-label": words })) {
2667
- if (view.editable) box.removeAttribute(name);
2668
- else box.setAttribute(name, value);
2669
- }
2670
- };
2671
- sync();
2672
- editor.on("update", sync);
2953
+ function deleteTableRow(editor, cell) {
2954
+ const row = cell.closest("tr");
2955
+ const table = cell.closest("table");
2956
+ if (!row || !table || table.rows.length <= 1) return inCell(editor, cell, deleteTable);
2957
+ const header = isHeaderRow(row);
2958
+ return inCell(editor, cell, header ? (state, dispatch, view) => deleteRow(state, dispatch) && (!view || toggleHeader("row")(view.state, view.dispatch)) : deleteRow);
2959
+ }
2960
+ function deleteTableColumn(editor, cell) {
2961
+ const row = cell.closest("tr");
2962
+ return inCell(editor, cell, row && row.cells.length > 1 ? deleteColumn : deleteTable);
2963
+ }
2964
+ function appendTableRow(editor, table) {
2965
+ const last = table.rows[table.rows.length - 1]?.cells[0];
2966
+ return !!last && inCell(editor, last, addRowAfter);
2967
+ }
2968
+ function appendTableColumn(editor, table) {
2969
+ const first = table.rows[0];
2970
+ const last = first?.cells[first.cells.length - 1];
2971
+ return !!last && inCell(editor, last, addColumnAfter);
2972
+ }
2973
+ function place(frame, { table, row, cell }) {
2974
+ const at = frame.getBoundingClientRect();
2975
+ const t = table.getBoundingClientRect();
2976
+ const r = row.getBoundingClientRect();
2977
+ const c = cell.getBoundingClientRect();
2673
2978
  return {
2674
- dom: li,
2675
- contentDOM: body,
2676
- update: (next) => {
2677
- if (next.type !== node.type || !sameAttrs(next, node)) return false;
2678
- words = next.firstChild?.textContent.trim() || "Item";
2679
- sync();
2680
- return true;
2681
- },
2682
- stopEvent: (event) => box.contains(event.target),
2683
- ignoreMutation: (mutation) => box.contains(mutation.target),
2684
- destroy: () => {
2685
- editor.off("update", sync);
2686
- renderer.destroy();
2687
- }
2979
+ tableBox: { top: t.top - at.top, left: t.left - at.left, width: t.width, height: t.height },
2980
+ rowBox: { top: r.top - at.top, height: r.height },
2981
+ columnBox: { left: c.left - at.left, width: c.width }
2688
2982
  };
2689
2983
  }
2690
- var Checklist = Extension11.create({
2691
- name: "checklist",
2692
- // Before the list item's own Enter and Backspace.
2693
- priority: 101,
2694
- addGlobalAttributes() {
2695
- return [
2696
- {
2697
- types: ["listItem"],
2698
- attributes: {
2699
- checked: {
2700
- default: null,
2701
- keepOnSplit: false,
2702
- parseHTML: (element) => {
2703
- const value = element.getAttribute("data-checked");
2704
- return value === "true" ? true : value === "false" ? false : null;
2705
- },
2706
- renderHTML: (attributes) => typeof attributes.checked === "boolean" ? { "data-checked": String(attributes.checked) } : {}
2707
- }
2708
- }
2709
- }
2710
- ];
2711
- },
2712
- addInputRules() {
2713
- return [
2714
- new InputRule({
2715
- find: /^\[([ xX]?)\]\s$/,
2716
- handler: ({ state, range, match, chain }) => {
2717
- const checked = match[1].toLowerCase() === "x";
2718
- const inList = itemAtCaret(state) !== null;
2719
- if (!inList && !chain().toggleBulletList) return null;
2720
- const deleted = chain().deleteRange(range);
2721
- const listed2 = inList ? deleted : named(deleted, "toggleBulletList");
2722
- listed2.updateAttributes("listItem", { checked }).run();
2723
- }
2724
- })
2725
- ];
2726
- },
2727
- addKeyboardShortcuts() {
2728
- return {
2729
- Enter: () => {
2730
- const { state } = this.editor;
2731
- const item = itemAtCaret(state);
2732
- const { $from, empty } = state.selection;
2733
- if (!item || typeof item.node.attrs.checked !== "boolean") return false;
2734
- if (!empty) return this.editor.chain().deleteSelection().splitListItem("listItem", { checked: false }).run();
2735
- if ($from.parent.content.size === 0) return false;
2736
- if ($from.parentOffset > 0) return this.editor.commands.splitListItem("listItem", { checked: false });
2737
- return this.editor.chain().splitListItem("listItem", { checked: item.node.attrs.checked }).command(({ tr }) => {
2738
- tr.setNodeAttribute(tr.mapping.map(item.pos), "checked", false);
2739
- return true;
2740
- }).run();
2741
- },
2742
- Backspace: () => {
2743
- const { state } = this.editor;
2744
- const item = itemAtCaret(state);
2745
- const { $from, empty } = state.selection;
2746
- if (!item || !empty || $from.parentOffset > 0 || typeof item.node.attrs.checked !== "boolean") return false;
2747
- this.editor.view.dispatch(state.tr.setNodeAttribute(item.pos, "checked", null));
2748
- return true;
2984
+ var ICON = { size: 16, stroke: 1.5, className: "text-text-secondary" };
2985
+ var keepFocus = (e) => e.preventDefault();
2986
+ var HANDLE_BOX = cn4(FLOATING_SURFACE_CLASSES, "shadow-none");
2987
+ function EditorTableControls({ editor, children, className }) {
2988
+ const frame = useRef5(null);
2989
+ const [hovered, setHovered] = useState6(null);
2990
+ const [menu, setMenu] = useState6(null);
2991
+ const editable = !!editor && editor.isEditable;
2992
+ const follow = useCallback6(
2993
+ (target) => {
2994
+ if (!editor || !frame.current || !(target instanceof Element)) return;
2995
+ if (target.closest("[data-table-control]")) return;
2996
+ const cell = target.closest("td, th");
2997
+ const row = cell?.closest("tr");
2998
+ const table = row?.closest("table");
2999
+ if (!cell || !row || !table || !editor.view.dom.contains(table)) {
3000
+ setHovered(null);
3001
+ return;
2749
3002
  }
3003
+ const next = { table, row, cell, ...place(frame.current, { table, row, cell }) };
3004
+ setHovered((was) => was && was.cell === cell && JSON.stringify([was.tableBox, was.rowBox, was.columnBox]) === JSON.stringify([next.tableBox, next.rowBox, next.columnBox]) ? was : next);
3005
+ },
3006
+ [editor]
3007
+ );
3008
+ useEffect6(() => {
3009
+ if (!editor) return;
3010
+ const changed = ({ transaction }) => {
3011
+ if (transaction.docChanged && !menu) setHovered(null);
2750
3012
  };
2751
- },
2752
- addProseMirrorPlugins() {
2753
- const editor = this.editor;
2754
- return [
2755
- new Plugin8({
2756
- key: new PluginKey9("checklist"),
2757
- props: { nodeViews: { listItem: (node, view, getPos) => listItemView(editor, node, view, getPos) } }
2758
- })
2759
- ];
2760
- }
2761
- });
2762
- var Callout = Extension11.create({
2763
- name: "callout",
2764
- addGlobalAttributes() {
2765
- return [
2766
- {
2767
- types: ["blockquote"],
2768
- attributes: {
2769
- tone: {
2770
- default: null,
2771
- parseHTML: (element) => element.getAttribute("data-tone"),
2772
- // As `RichText` draws it: the tone as written, and the look it is drawn in.
2773
- renderHTML: (attributes) => typeof attributes.tone === "string" ? { "data-tone": attributes.tone, "data-callout": calloutLook(attributes.tone) } : {}
2774
- }
2775
- }
2776
- }
2777
- ];
2778
- }
2779
- });
3013
+ editor.on("transaction", changed);
3014
+ return () => {
3015
+ editor.off("transaction", changed);
3016
+ };
3017
+ }, [editor, menu]);
3018
+ const shown = editable ? hovered : null;
3019
+ const run = (act) => () => {
3020
+ if (editor) act();
3021
+ setMenu(null);
3022
+ setHovered(null);
3023
+ };
3024
+ return /* @__PURE__ */ jsxs8(
3025
+ "div",
3026
+ {
3027
+ ref: frame,
3028
+ className: cn4("relative", className),
3029
+ onMouseMove: (e) => {
3030
+ if (!menu) follow(e.target);
3031
+ },
3032
+ onMouseLeave: () => {
3033
+ if (!menu) setHovered(null);
3034
+ },
3035
+ children: [
3036
+ children,
3037
+ shown && editor && /* @__PURE__ */ jsxs8(Fragment4, { children: [
3038
+ /* @__PURE__ */ jsx10("div", { "data-table-control": true, className: cn4(HANDLE_BOX, "absolute -translate-x-1/2 -translate-y-1/2"), style: { left: shown.tableBox.left, top: shown.rowBox.top + shown.rowBox.height / 2 }, children: /* @__PURE__ */ jsxs8(
3039
+ Menu,
3040
+ {
3041
+ open: menu === "row",
3042
+ onOpenChange: (open) => setMenu(open ? "row" : null),
3043
+ trigger: /* @__PURE__ */ jsx10(IconButton2, { "aria-label": "Row menu", tooltip: "Row", className: "h-6 w-4 p-0", children: /* @__PURE__ */ jsx10(IconGripVertical, { size: 16, stroke: 1.5 }) }),
3044
+ children: [
3045
+ !isHeaderRow(shown.row) && /* @__PURE__ */ jsx10(MenuItem3, { label: "Insert above", leading: /* @__PURE__ */ jsx10(IconRowInsertTop, { ...ICON }), onClick: run(() => inCell(editor, shown.cell, addRowBefore)) }),
3046
+ /* @__PURE__ */ jsx10(MenuItem3, { label: "Insert below", leading: /* @__PURE__ */ jsx10(IconRowInsertBottom, { ...ICON }), onClick: run(() => inCell(editor, shown.cell, addRowAfter)) }),
3047
+ /* @__PURE__ */ jsx10(MenuSeparator2, {}),
3048
+ /* @__PURE__ */ jsx10(MenuItem3, { label: "Delete", destructive: true, leading: /* @__PURE__ */ jsx10(IconTrash2, { size: 16, stroke: 1.5, className: "text-error-default" }), onClick: run(() => deleteTableRow(editor, shown.cell)) }),
3049
+ /* @__PURE__ */ jsx10(MenuItem3, { label: "Delete table", destructive: true, leading: /* @__PURE__ */ jsx10(IconTrash2, { size: 16, stroke: 1.5, className: "text-error-default" }), onClick: run(() => inCell(editor, shown.cell, deleteTable)) })
3050
+ ]
3051
+ }
3052
+ ) }),
3053
+ /* @__PURE__ */ jsx10("div", { "data-table-control": true, className: cn4(HANDLE_BOX, "absolute -translate-x-1/2 -translate-y-1/2"), style: { left: shown.columnBox.left + shown.columnBox.width / 2, top: shown.tableBox.top }, children: /* @__PURE__ */ jsxs8(
3054
+ Menu,
3055
+ {
3056
+ open: menu === "column",
3057
+ onOpenChange: (open) => setMenu(open ? "column" : null),
3058
+ trigger: /* @__PURE__ */ jsx10(IconButton2, { "aria-label": "Column menu", tooltip: "Column", className: "h-4 w-6 p-0", children: /* @__PURE__ */ jsx10(IconGripHorizontal, { size: 16, stroke: 1.5 }) }),
3059
+ children: [
3060
+ /* @__PURE__ */ jsx10(MenuItem3, { label: "Insert left", leading: /* @__PURE__ */ jsx10(IconColumnInsertLeft, { ...ICON }), onClick: run(() => inCell(editor, shown.cell, addColumnBefore)) }),
3061
+ /* @__PURE__ */ jsx10(MenuItem3, { label: "Insert right", leading: /* @__PURE__ */ jsx10(IconColumnInsertRight, { ...ICON }), onClick: run(() => inCell(editor, shown.cell, addColumnAfter)) }),
3062
+ /* @__PURE__ */ jsx10(MenuSeparator2, {}),
3063
+ /* @__PURE__ */ jsx10(MenuItem3, { label: "Delete", destructive: true, leading: /* @__PURE__ */ jsx10(IconTrash2, { size: 16, stroke: 1.5, className: "text-error-default" }), onClick: run(() => deleteTableColumn(editor, shown.cell)) }),
3064
+ /* @__PURE__ */ jsx10(MenuItem3, { label: "Delete table", destructive: true, leading: /* @__PURE__ */ jsx10(IconTrash2, { size: 16, stroke: 1.5, className: "text-error-default" }), onClick: run(() => inCell(editor, shown.cell, deleteTable)) })
3065
+ ]
3066
+ }
3067
+ ) }),
3068
+ shown.row === shown.table.rows[shown.table.rows.length - 1] && /* @__PURE__ */ jsx10("div", { "data-table-control": true, className: cn4(HANDLE_BOX, "absolute flex h-4"), style: { left: shown.tableBox.left, top: shown.tableBox.top + shown.tableBox.height, width: shown.tableBox.width }, children: /* @__PURE__ */ jsx10(IconButton2, { "aria-label": "Add row", tooltip: "Add row", className: "h-full w-full p-0", onMouseDown: keepFocus, onClick: run(() => appendTableRow(editor, shown.table)), children: /* @__PURE__ */ jsx10(IconPlus, { size: 12, stroke: 1.5 }) }) }),
3069
+ shown.cell === shown.row.cells[shown.row.cells.length - 1] && /* @__PURE__ */ jsx10("div", { "data-table-control": true, className: cn4(HANDLE_BOX, "absolute flex w-4"), style: { left: shown.tableBox.left + shown.tableBox.width, top: shown.tableBox.top, height: shown.tableBox.height }, children: /* @__PURE__ */ jsx10(IconButton2, { "aria-label": "Add column", tooltip: "Add column", className: "h-full w-full p-0", onMouseDown: keepFocus, onClick: run(() => appendTableColumn(editor, shown.table)), children: /* @__PURE__ */ jsx10(IconPlus, { size: 12, stroke: 1.5 }) }) })
3070
+ ] })
3071
+ ]
3072
+ }
3073
+ );
3074
+ }
2780
3075
  export {
2781
3076
  AttachmentNode,
2782
3077
  BlockId,
@@ -2785,6 +3080,7 @@ export {
2785
3080
  CaptionedReference,
2786
3081
  Checklist,
2787
3082
  CodeBlockColours,
3083
+ CommentBox,
2788
3084
  CommentHighlights,
2789
3085
  ComposeBox,
2790
3086
  ComposeKeys,
@@ -2811,6 +3107,7 @@ export {
2811
3107
  appendTableRow,
2812
3108
  applyFormat,
2813
3109
  blockDropCursor,
3110
+ commentBoxRows,
2814
3111
  commentElement,
2815
3112
  commentPlace,
2816
3113
  deleteBlock,