@estiva-app/ui 0.81.0 → 0.82.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/editor.js CHANGED
@@ -275,7 +275,7 @@ function SelectionToolbar({ editor, marks = ["bold", "italic", "underline"], lin
275
275
  }
276
276
  ),
277
277
  children,
278
- actions.length > 0 && /* @__PURE__ */ jsx(ToolbarSeparator, {}),
278
+ actions.length > 0 && (marks.length > 0 || link || children) && /* @__PURE__ */ jsx(ToolbarSeparator, {}),
279
279
  actions.map((action) => /* @__PURE__ */ jsx(
280
280
  ToolbarButton,
281
281
  {
@@ -529,10 +529,8 @@ function ComposeBox({ editor, onSend, placeholder, tools, attachments, ready = f
529
529
 
530
530
  // src/CommentBox.tsx
531
531
  import { Fragment as Fragment2, useCallback as useCallback4, useEffect as useEffect4, useRef as useRef3, useState as useState4 } from "react";
532
- import { Extension as Extension9 } from "@tiptap/core";
533
- import { Plugin as Plugin7, PluginKey as PluginKey8, TextSelection as TextSelection2 } from "@tiptap/pm/state";
532
+ import { Extension as Extension10 } from "@tiptap/core";
534
533
  import { EditorContent as EditorContent2, useEditor } from "@tiptap/react";
535
- import StarterKit from "@tiptap/starter-kit";
536
534
  import { IconLock, IconPaperclip, IconSquareRounded } from "@tabler/icons-react";
537
535
  import { AttachmentCard } from "@estiva-app/ui";
538
536
 
@@ -1311,7 +1309,8 @@ var ReferenceNode = Node2.create({
1311
1309
  },
1312
1310
  renderHTML({ node }) {
1313
1311
  const embed = typeof node.attrs.embed === "string" ? { "data-embed": node.attrs.embed } : {};
1314
- const href = typeof node.attrs.href === "string" && node.attrs.href ? { "data-href": node.attrs.href } : {};
1312
+ const web = webUrl(typeof node.attrs.href === "string" ? node.attrs.href : null);
1313
+ const href = web ? { "data-href": web } : {};
1315
1314
  return ["span", { "data-reference": String(node.attrs.uri), ...embed, ...href }, String(node.attrs.href || node.attrs.uri)];
1316
1315
  },
1317
1316
  renderText({ node }) {
@@ -1691,6 +1690,41 @@ function urgentPubkeys(editor) {
1691
1690
  });
1692
1691
  return urgent.length > 0 ? urgent : void 0;
1693
1692
  }
1693
+ var PersonReference = Extension7.create({
1694
+ name: "personReference",
1695
+ addOptions() {
1696
+ return { people: () => [], uriOf: () => null, nodeName: "reference" };
1697
+ },
1698
+ addProseMirrorPlugins() {
1699
+ const options = this.options;
1700
+ return [
1701
+ Suggestion({
1702
+ editor: this.editor,
1703
+ char: "@",
1704
+ pluginKey: new PluginKey6("personReference"),
1705
+ ...listening("@"),
1706
+ // As `[`'s: only where the chip may go.
1707
+ allow: ({ state, range }) => {
1708
+ const type = state.schema.nodes[options.nodeName];
1709
+ return !!type && !!state.doc.resolve(range.from).parent.type.contentMatch.matchType(type);
1710
+ },
1711
+ items: ({ query }) => filterPeople(
1712
+ options.people().filter((person) => options.uriOf(person) !== null),
1713
+ query
1714
+ ),
1715
+ render: suggestionPopup(peopleMenu(false)),
1716
+ command: ({ editor, range, props: person }) => {
1717
+ const uri = options.uriOf(person);
1718
+ if (!uri) return;
1719
+ editor.chain().focus().insertContentAt(range, [
1720
+ { type: options.nodeName, attrs: { uri } },
1721
+ { type: "text", text: " " }
1722
+ ]).run();
1723
+ }
1724
+ })
1725
+ ];
1726
+ }
1727
+ });
1694
1728
  var REFERENCE_LIMIT = 6;
1695
1729
  function filterReferences(items, query) {
1696
1730
  const q = query.toLowerCase();
@@ -1918,9 +1952,113 @@ import { FieldLine } from "@estiva-app/ui";
1918
1952
  import { FilePicker } from "@estiva-app/ui";
1919
1953
  import { Kbd } from "@estiva-app/ui";
1920
1954
 
1921
- // src/PastedImages.ts
1955
+ // src/links.ts
1922
1956
  import { Extension as Extension8 } from "@tiptap/core";
1923
- import { Plugin as Plugin6, PluginKey as PluginKey7 } from "@tiptap/pm/state";
1957
+ import { Plugin as Plugin6, PluginKey as PluginKey7, TextSelection as TextSelection2 } from "@tiptap/pm/state";
1958
+ import { Decoration as Decoration3, DecorationSet as DecorationSet3 } from "@tiptap/pm/view";
1959
+ import StarterKit from "@tiptap/starter-kit";
1960
+ var LINK_ON_WORDS_TARGET = /^https?:\/\/[^\s)]+$/;
1961
+ var PasteOverWords = Extension8.create({
1962
+ name: "commentBoxPasteOverWords",
1963
+ priority: 1001,
1964
+ addProseMirrorPlugins() {
1965
+ return [
1966
+ new Plugin6({
1967
+ key: new PluginKey7("commentBoxPasteOverWords"),
1968
+ props: {
1969
+ handlePaste: (view, event) => {
1970
+ const url = (event.clipboardData?.getData("text/plain").trim() ?? "").replace(/[.,;:!?]+$/, "");
1971
+ const { state } = view;
1972
+ const { schema } = state;
1973
+ if (state.selection.empty || !schema.marks.link || !/^https?:\/\/\S+$/.test(url)) return false;
1974
+ const { $from, $to, from, to } = TextSelection2.between(state.selection.$from, state.selection.$to);
1975
+ let plain = $from.sameParent($to) && $from.parent.isTextblock && !$from.parent.type.spec.code;
1976
+ state.doc.nodesBetween(from, to, (node) => {
1977
+ if (!node.isInline) return true;
1978
+ if (!node.isText || node.marks.some((m) => m.type.spec.code || m.type.name === "code")) plain = false;
1979
+ return false;
1980
+ });
1981
+ if (plain && LINK_ON_WORDS_TARGET.test(url) && !/[[\]\n]/.test(state.doc.textBetween(from, to))) {
1982
+ view.dispatch(state.tr.addMark(from, to, schema.marks.link.create({ href: url })));
1983
+ return true;
1984
+ }
1985
+ const before = state.doc.textBetween(Math.max(to - 1, $to.start()), to, "", "\uFFFC");
1986
+ const inserted = before && !/\s/.test(before) ? ` ${url}` : url;
1987
+ const tr = state.tr.insertText(inserted, to);
1988
+ view.dispatch(tr.setSelection(TextSelection2.create(tr.doc, to + inserted.length)).scrollIntoView());
1989
+ return true;
1990
+ }
1991
+ }
1992
+ })
1993
+ ];
1994
+ }
1995
+ });
1996
+ var BoxKit = StarterKit.extend({
1997
+ addExtensions() {
1998
+ return (this.parent?.() ?? []).map((extension) => extension.name === "link" ? extension.extend({ inclusive: () => false }) : extension);
1999
+ }
2000
+ });
2001
+ var DocumentKit = StarterKit.extend({
2002
+ addExtensions() {
2003
+ return (this.parent?.() ?? []).map(
2004
+ (extension) => extension.name === "link" ? extension.extend({
2005
+ inclusive: () => false,
2006
+ addAttributes() {
2007
+ return { ...this.parent?.(), extra: { default: null, rendered: false, parseHTML: () => null } };
2008
+ }
2009
+ }) : extension
2010
+ );
2011
+ }
2012
+ });
2013
+ var LINK_SPLIT = /\[[^[\]\n]+\]\((?:https?:\/\/|mailto:)[^\s)]+\)|https?:\/\/[^\s]+/g;
2014
+ var TRAILING2 = /[.,;:!?)\]]+$/;
2015
+ var LINK_CLASS = "text-info-default underline underline-offset-2 cursor-pointer";
2016
+ var OPENABLE = /^(https?:\/\/|mailto:)/i;
2017
+ var LINK_MARK_ATTRIBUTES = { class: LINK_CLASS, "data-link-mark": "", target: "_blank", rel: "noopener noreferrer nofollow" };
2018
+ var LINK_TARGET = /\]\(([^\s)]+)\)$/;
2019
+ var BareLinks = Extension8.create({
2020
+ name: "bareLinks",
2021
+ addProseMirrorPlugins() {
2022
+ return [
2023
+ new Plugin6({
2024
+ key: new PluginKey7("bareLinks"),
2025
+ props: {
2026
+ // The one way a click opens an address: a bare one's decoration, or, while editing, a link on words (read only,
2027
+ // the link is a plain anchor and opens itself). Only its own attributes are read — never a chip's — and only an
2028
+ // address a reader may follow opens, always without handing the new tab this window.
2029
+ handleClick: (view, _pos, event) => {
2030
+ if (event.button !== 0) return false;
2031
+ const target = event.target;
2032
+ const bare = target?.closest?.("[data-bare-link]")?.getAttribute("data-bare-link");
2033
+ const onWords = view.editable ? target?.closest?.("a[data-link-mark]")?.getAttribute("href") : null;
2034
+ const href = bare ?? onWords;
2035
+ if (!href || !OPENABLE.test(href)) return false;
2036
+ window.open(href, "_blank", "noopener,noreferrer");
2037
+ return true;
2038
+ },
2039
+ decorations: ({ doc: doc2 }) => {
2040
+ const found = [];
2041
+ doc2.descendants((node, pos) => {
2042
+ if (!node.isText || !node.text) return;
2043
+ if (node.marks.some((mark) => mark.type.name === "code" || mark.type.name === "link")) return;
2044
+ for (const match of node.text.matchAll(LINK_SPLIT)) {
2045
+ if (match.index === void 0) continue;
2046
+ const text = match[0].startsWith("[") ? match[0] : match[0].replace(TRAILING2, "");
2047
+ const href = text.startsWith("[") ? LINK_TARGET.exec(text)?.[1] ?? "" : text;
2048
+ found.push(Decoration3.inline(pos + match.index, pos + match.index + text.length, { class: LINK_CLASS, ...href ? { "data-bare-link": href } : {} }));
2049
+ }
2050
+ });
2051
+ return found.length ? DecorationSet3.create(doc2, found) : null;
2052
+ }
2053
+ }
2054
+ })
2055
+ ];
2056
+ }
2057
+ });
2058
+
2059
+ // src/PastedImages.ts
2060
+ import { Extension as Extension9 } from "@tiptap/core";
2061
+ import { Plugin as Plugin7, PluginKey as PluginKey8 } from "@tiptap/pm/state";
1924
2062
  var IMAGE_EXTENSIONS = {
1925
2063
  "image/png": "png",
1926
2064
  "image/jpeg": "jpg",
@@ -1955,7 +2093,7 @@ function pastedImages(source, at = /* @__PURE__ */ new Date()) {
1955
2093
  (file) => hasUsableName(file.name) ? file : new File([file], pastedImageName(file.type, at, generated++), { type: file.type, lastModified: file.lastModified })
1956
2094
  );
1957
2095
  }
1958
- var PastedImages = Extension8.create({
2096
+ var PastedImages = Extension9.create({
1959
2097
  name: "pastedImages",
1960
2098
  addOptions() {
1961
2099
  return { onImages: () => false };
@@ -1963,8 +2101,8 @@ var PastedImages = Extension8.create({
1963
2101
  addProseMirrorPlugins() {
1964
2102
  const options = this.options;
1965
2103
  return [
1966
- new Plugin6({
1967
- key: new PluginKey7("pastedImages"),
2104
+ new Plugin7({
2105
+ key: new PluginKey8("pastedImages"),
1968
2106
  props: {
1969
2107
  handlePaste: (_view, event) => {
1970
2108
  const files = pastedImages(event.clipboardData);
@@ -1982,12 +2120,12 @@ import { Fragment as Fragment3, jsx as jsx7, jsxs as jsxs5 } from "react/jsx-run
1982
2120
  var ATTACH_EVENT = "commentbox:attach";
1983
2121
  var askForFile = (editor) => editor.view.dom.dispatchEvent(new CustomEvent(ATTACH_EVENT, { bubbles: true }));
1984
2122
  var commentBoxRows = {
1985
- file: { key: "insert-file", row: { label: "File" }, keywords: ["attach", "upload"], run: askForFile },
2123
+ file: { key: "insert-file", row: { label: "Upload" }, keywords: ["attach", "file", "picture"], run: askForFile },
1986
2124
  mention: { key: "insert-mention", row: { label: "Mention", shortcut: "@" }, keywords: ["@", "Mention a person"], run: typeTrigger("@") },
1987
2125
  urgent: { key: "insert-urgent", row: { label: "Urgent", shortcut: "!@" }, keywords: ["!@", "Urgent mention"], run: typeTrigger("!@") },
1988
2126
  reference: { key: "insert-reference", row: { label: "Reference", shortcut: "[" }, keywords: ["[", "Reference"], run: typeTrigger("[") }
1989
2127
  };
1990
- var BoxKeys = Extension9.create({
2128
+ var BoxKeys = Extension10.create({
1991
2129
  name: "commentBoxKeys",
1992
2130
  addOptions() {
1993
2131
  return { onEscape: () => false };
@@ -2000,47 +2138,6 @@ var BoxKeys = Extension9.create({
2000
2138
  };
2001
2139
  }
2002
2140
  });
2003
- var LINK_ON_WORDS_TARGET = /^https?:\/\/[^\s)]+$/;
2004
- var PasteOverWords = Extension9.create({
2005
- name: "commentBoxPasteOverWords",
2006
- priority: 1001,
2007
- addProseMirrorPlugins() {
2008
- return [
2009
- new Plugin7({
2010
- key: new PluginKey8("commentBoxPasteOverWords"),
2011
- props: {
2012
- handlePaste: (view, event) => {
2013
- const url = (event.clipboardData?.getData("text/plain").trim() ?? "").replace(/[.,;:!?]+$/, "");
2014
- const { state } = view;
2015
- const { schema } = state;
2016
- if (state.selection.empty || !schema.marks.link || !/^https?:\/\/\S+$/.test(url)) return false;
2017
- const { $from, $to, from, to } = TextSelection2.between(state.selection.$from, state.selection.$to);
2018
- let plain = $from.sameParent($to) && $from.parent.isTextblock && !$from.parent.type.spec.code;
2019
- state.doc.nodesBetween(from, to, (node) => {
2020
- if (node.isTextblock) return true;
2021
- if (!node.isText || node.marks.some((m) => m.type.spec.code || m.type.name === "code")) plain = false;
2022
- return false;
2023
- });
2024
- if (plain && LINK_ON_WORDS_TARGET.test(url) && !/[[\]\n]/.test(state.doc.textBetween(from, to))) {
2025
- view.dispatch(state.tr.addMark(from, to, schema.marks.link.create({ href: url })));
2026
- return true;
2027
- }
2028
- const before = state.doc.textBetween(Math.max(to - 1, $to.start()), to, "", "\uFFFC");
2029
- const inserted = before && !/\s/.test(before) ? ` ${url}` : url;
2030
- const tr = state.tr.insertText(inserted, to);
2031
- view.dispatch(tr.setSelection(TextSelection2.create(tr.doc, to + inserted.length)).scrollIntoView());
2032
- return true;
2033
- }
2034
- }
2035
- })
2036
- ];
2037
- }
2038
- });
2039
- var BoxKit = StarterKit.extend({
2040
- addExtensions() {
2041
- return (this.parent?.() ?? []).map((extension) => extension.name === "link" ? extension.extend({ inclusive: () => false }) : extension);
2042
- }
2043
- });
2044
2141
  var stillNamed = (removed, names) => [...removed].every((value) => names.includes(value)) ? removed : new Set([...removed].filter((value) => names.includes(value)));
2045
2142
  var SQUARE = /* @__PURE__ */ jsx7(IconSquareRounded, { size: 16, stroke: 1.5, className: "text-text-secondary" });
2046
2143
  var SMALL_SQUARE = /* @__PURE__ */ jsx7(IconSquareRounded, { size: 14, stroke: 1.5 });
@@ -2344,7 +2441,7 @@ function CommentBox({
2344
2441
 
2345
2442
  // src/InlineText.tsx
2346
2443
  import { useCallback as useCallback5, useEffect as useEffect5, useImperativeHandle as useImperativeHandle2, useRef as useRef4, useState as useState5 } from "react";
2347
- import { Extension as Extension10, Node as Node3 } from "@tiptap/core";
2444
+ import { Extension as Extension11, Node as Node3 } from "@tiptap/core";
2348
2445
  import { history, redo, undo } from "@tiptap/pm/history";
2349
2446
  import { EditorContent as EditorContent3, useEditor as useEditor2 } from "@tiptap/react";
2350
2447
  import { cn as cn3 } from "@estiva-app/ui";
@@ -2362,7 +2459,7 @@ var Paragraph = Node3.create({
2362
2459
  renderHTML: () => ["p", 0]
2363
2460
  });
2364
2461
  var Text = Node3.create({ name: "text" });
2365
- var Undo = Extension10.create({
2462
+ var Undo = Extension11.create({
2366
2463
  name: "inlineTextUndo",
2367
2464
  addProseMirrorPlugins: () => [history()],
2368
2465
  addKeyboardShortcuts() {
@@ -2462,9 +2559,9 @@ function InlineText({ value, placeholder, label, onCommit, onText, onEnter, vari
2462
2559
  }
2463
2560
 
2464
2561
  // src/CommentHighlights.ts
2465
- import { Extension as Extension11 } from "@tiptap/core";
2562
+ import { Extension as Extension12 } from "@tiptap/core";
2466
2563
  import { Plugin as Plugin8, PluginKey as PluginKey9 } from "@tiptap/pm/state";
2467
- import { Decoration as Decoration3, DecorationSet as DecorationSet3 } from "@tiptap/pm/view";
2564
+ import { Decoration as Decoration4, DecorationSet as DecorationSet4 } from "@tiptap/pm/view";
2468
2565
  var commentHighlightsKey = new PluginKey9("commentHighlights");
2469
2566
  var COMMENT_HIGHLIGHT_CLASSES = {
2470
2567
  rest: "cursor-pointer rounded-sm bg-warning-muted",
@@ -2584,7 +2681,7 @@ function placeOf(doc2, anchor, places = placesIn(doc2)) {
2584
2681
  if (endAt === -1 || quote.end === "") return reworded;
2585
2682
  return { state: "resolved", from: a.starts[startAt], to: b.ends[endAt + quote.end.length - 1], words: true };
2586
2683
  }
2587
- var CommentHighlights = Extension11.create({
2684
+ var CommentHighlights = Extension12.create({
2588
2685
  name: "commentHighlights",
2589
2686
  addOptions() {
2590
2687
  return { onSelect: null };
@@ -2610,16 +2707,16 @@ var CommentHighlights = Extension11.create({
2610
2707
  const place2 = placeOf(state.doc, anchor, places);
2611
2708
  if (place2.state !== "resolved") return [];
2612
2709
  const attrs = { class: anchor.id === active ? COMMENT_HIGHLIGHT_CLASSES.active : COMMENT_HIGHLIGHT_CLASSES.rest, "data-comment-id": anchor.id };
2613
- if (place2.words) return [Decoration3.inline(place2.from, place2.to, attrs)];
2710
+ if (place2.words) return [Decoration4.inline(place2.from, place2.to, attrs)];
2614
2711
  const blocks = [];
2615
2712
  state.doc.nodesBetween(place2.from, place2.to, (node, pos) => {
2616
2713
  if (pos < place2.from || pos + node.nodeSize > place2.to) return true;
2617
- blocks.push(Decoration3.node(pos, pos + node.nodeSize, attrs));
2714
+ blocks.push(Decoration4.node(pos, pos + node.nodeSize, attrs));
2618
2715
  return false;
2619
2716
  });
2620
2717
  return blocks;
2621
2718
  });
2622
- return drawn.length ? DecorationSet3.create(state.doc, drawn) : null;
2719
+ return drawn.length ? DecorationSet4.create(state.doc, drawn) : null;
2623
2720
  },
2624
2721
  handleClick(view, pos) {
2625
2722
  const { anchors } = commentHighlightsKey.getState(view.state) ?? { anchors: [] };
@@ -2744,7 +2841,7 @@ function anchorOfSelection(editor) {
2744
2841
  }
2745
2842
 
2746
2843
  // src/PastedMarkdown.ts
2747
- import { Extension as Extension12 } from "@tiptap/core";
2844
+ import { Extension as Extension13 } from "@tiptap/core";
2748
2845
  import { Slice } from "@tiptap/pm/model";
2749
2846
  import { Plugin as Plugin9, PluginKey as PluginKey10 } from "@tiptap/pm/state";
2750
2847
  function inTableCell($context) {
@@ -2755,7 +2852,7 @@ function inTableCell($context) {
2755
2852
  return false;
2756
2853
  }
2757
2854
  var hasTable = (blocks) => blocks.some((block) => block.type === "table" || hasTable(block.content ?? []));
2758
- var PastedMarkdown = Extension12.create({
2855
+ var PastedMarkdown = Extension13.create({
2759
2856
  name: "pastedMarkdown",
2760
2857
  addOptions() {
2761
2858
  return { read: () => void 0 };
@@ -3176,6 +3273,342 @@ function EditorTableControls({ editor, children, className }) {
3176
3273
  }
3177
3274
  );
3178
3275
  }
3276
+
3277
+ // src/DocumentEditor.tsx
3278
+ import { useCallback as useCallback7, useEffect as useEffect7, useRef as useRef6, useState as useState7 } from "react";
3279
+ import { TextSelection as TextSelection4 } from "@tiptap/pm/state";
3280
+ import { EditorContent as EditorContent4, useEditor as useEditor3, useEditorState as useEditorState2 } from "@tiptap/react";
3281
+ import { TableKit } from "@tiptap/extension-table";
3282
+ import { IconMessagePlus } from "@tabler/icons-react";
3283
+ import { Button as Button2 } from "@estiva-app/ui";
3284
+ import { FieldLine as FieldLine2 } from "@estiva-app/ui";
3285
+ import { FilePicker as FilePicker2 } from "@estiva-app/ui";
3286
+ import { richTextClassName as richTextClassName2 } from "@estiva-app/ui";
3287
+ import { Fragment as Fragment6, jsx as jsx11, jsxs as jsxs9 } from "react/jsx-runtime";
3288
+ function heldDocument(hold, key4) {
3289
+ const text = hold && key4 ? hold.text(key4) : void 0;
3290
+ if (!text) return null;
3291
+ try {
3292
+ const doc2 = JSON.parse(text);
3293
+ return doc2?.type === "doc" ? doc2 : null;
3294
+ } catch {
3295
+ return null;
3296
+ }
3297
+ }
3298
+ function DocumentEditor({
3299
+ value,
3300
+ format,
3301
+ codec,
3302
+ onCommit,
3303
+ label,
3304
+ placeholder,
3305
+ readOnly = false,
3306
+ changedBy = null,
3307
+ onLeftUnsaved,
3308
+ hold,
3309
+ holdKey,
3310
+ references,
3311
+ mentions,
3312
+ linkChips,
3313
+ upload,
3314
+ readMarkdown,
3315
+ table = true,
3316
+ onCommentOnSelection,
3317
+ blockRows,
3318
+ referenceView,
3319
+ attachmentView,
3320
+ cards,
3321
+ wrap,
3322
+ onEditor,
3323
+ extensions = []
3324
+ }) {
3325
+ const [failed, setFailed] = useState7(false);
3326
+ const [focused, setFocused] = useState7(false);
3327
+ const [uploadError, setUploadError] = useState7(null);
3328
+ const latest = useRef6({ value, format, codec, hold, references, mentions, upload, readMarkdown, onLeftUnsaved });
3329
+ useEffect7(() => {
3330
+ latest.current = { value, format, codec, hold, references, mentions, upload, readMarkdown, onLeftUnsaved };
3331
+ });
3332
+ const ended = () => latest.current.hold?.ended() ?? false;
3333
+ const [base, setBase] = useState7(value);
3334
+ const saved = useRef6(value);
3335
+ const [superseded, setSuperseded] = useState7(null);
3336
+ const own = useRef6(/* @__PURE__ */ new Set());
3337
+ const [saving, setSaving] = useState7(false);
3338
+ const committing = useRef6(false);
3339
+ const [held] = useState7(() => {
3340
+ const doc2 = heldDocument(hold, holdKey);
3341
+ try {
3342
+ return doc2 && codec.write(doc2).value !== value ? doc2 : null;
3343
+ } catch {
3344
+ return null;
3345
+ }
3346
+ });
3347
+ const [restored, setRestored] = useState7(held !== null);
3348
+ const typed = useRef6(held);
3349
+ const again = useRef6(false);
3350
+ const left = useRef6(false);
3351
+ const picking = useRef6(false);
3352
+ const picker = useRef6(null);
3353
+ const save = useCallback7(
3354
+ async (doc2) => {
3355
+ if (!doc2 || readOnly || ended()) return;
3356
+ if (committing.current) {
3357
+ again.current = true;
3358
+ return;
3359
+ }
3360
+ const next = latest.current.codec.write(doc2);
3361
+ if (next.value === saved.current) return;
3362
+ committing.current = true;
3363
+ setSaving(true);
3364
+ const replaced = latest.current.value;
3365
+ const editedFrom = saved.current;
3366
+ try {
3367
+ const ok = await onCommit(next.value, next.contentFormat, editedFrom);
3368
+ if (ok) {
3369
+ saved.current = next.value;
3370
+ shown.current = next.value;
3371
+ own.current.add(next.value);
3372
+ setSuperseded(replaced);
3373
+ setBase(next.value);
3374
+ setRestored(false);
3375
+ const store = latest.current.hold;
3376
+ if (store && holdKey && !store.ended()) store.release(holdKey);
3377
+ }
3378
+ if (left.current) {
3379
+ if (!ok && !ended()) latest.current.onLeftUnsaved?.();
3380
+ } else setFailed(!ok);
3381
+ } catch {
3382
+ if (left.current) {
3383
+ if (!ended()) latest.current.onLeftUnsaved?.();
3384
+ } else setFailed(true);
3385
+ } finally {
3386
+ committing.current = false;
3387
+ setSaving(false);
3388
+ if (again.current) {
3389
+ again.current = false;
3390
+ if (!ended()) void latestSave.current(typed.current);
3391
+ }
3392
+ }
3393
+ },
3394
+ [onCommit, holdKey, readOnly]
3395
+ );
3396
+ const holds = !!hold;
3397
+ useEffect7(() => {
3398
+ const store = latest.current.hold;
3399
+ if (!holds || !store || !holdKey) return;
3400
+ return store.register(holdKey, () => {
3401
+ const doc2 = typed.current;
3402
+ return doc2 && latest.current.codec.write(doc2).value !== saved.current ? JSON.stringify(doc2) : void 0;
3403
+ });
3404
+ }, [holdKey, holds]);
3405
+ const latestSave = useRef6(save);
3406
+ useEffect7(() => {
3407
+ latestSave.current = save;
3408
+ }, [save]);
3409
+ const shown = useRef6(value);
3410
+ const openPicker = () => {
3411
+ picking.current = true;
3412
+ const released = () => {
3413
+ picking.current = false;
3414
+ window.removeEventListener("focus", released);
3415
+ };
3416
+ window.addEventListener("focus", released);
3417
+ picker.current?.click();
3418
+ };
3419
+ const pickFile = useRef6(openPicker);
3420
+ pickFile.current = openPicker;
3421
+ const attach = async (chosen) => {
3422
+ const uploadOne = latest.current.upload;
3423
+ if (!uploadOne) return;
3424
+ setUploadError(null);
3425
+ try {
3426
+ for (const file of chosen) {
3427
+ const attrs = await uploadOne(file);
3428
+ if (!editor || editor.isDestroyed) return;
3429
+ editor.chain().focus().insertContent({ type: "attachment", attrs }).run();
3430
+ }
3431
+ } catch (error) {
3432
+ setUploadError(error instanceof Error ? error.message : String(error));
3433
+ }
3434
+ };
3435
+ const attachTo = useRef6(attach);
3436
+ attachTo.current = attach;
3437
+ const editor = useEditor3(
3438
+ {
3439
+ extensions: [
3440
+ DocumentKit.configure({
3441
+ strike: false,
3442
+ heading: { levels: [1, 2, 3] },
3443
+ dropcursor: blockDropCursor,
3444
+ codeBlock: false,
3445
+ // A link on words is made by pasting a URL over them or by the strip's Link, and opens on a click, as a bare
3446
+ // address does — through `BareLinks`, which opens only a followable address and never hands the tab this window;
3447
+ // Tiptap's own click opens without that. A bare address stays text: a link made on it by typing would change what is saved.
3448
+ link: { openOnClick: false, shouldAutoLink: () => false, HTMLAttributes: LINK_MARK_ATTRIBUTES }
3449
+ }),
3450
+ PasteOverWords,
3451
+ KeptSelection,
3452
+ BareLinks,
3453
+ CodeBlockColours,
3454
+ TableKit.configure({ table: { resizable: false } }),
3455
+ BlockId,
3456
+ Checklist,
3457
+ Callout,
3458
+ ReferenceNode.configure({ view: referenceView ?? null }),
3459
+ // The card a chip asks for, after its line (SPEC §13.3); drawn by the app's `cards`.
3460
+ ReferenceCards,
3461
+ // A click on a chip offers Open and its card.
3462
+ ReferenceMenu,
3463
+ UnknownBlock,
3464
+ AttachmentNode.configure({ view: attachmentView ?? null }),
3465
+ SlashCommands.configure({ sections: slashSections({ table, upload: !!upload, pickFile }) }),
3466
+ ...references ? [
3467
+ ReferenceTrigger.configure({
3468
+ items: () => [],
3469
+ sections: (query) => latest.current.references?.sections(query) ?? [],
3470
+ subscribe: (listener) => latest.current.references?.subscribe?.(listener) ?? (() => {
3471
+ }),
3472
+ nodeName: "reference",
3473
+ ariaLabel: references.ariaLabel,
3474
+ sectionLabel: references.sectionLabel,
3475
+ icon: references.icon ?? null
3476
+ })
3477
+ ] : [],
3478
+ ...mentions ? [PersonReference.configure({ people: () => latest.current.mentions?.people() ?? [], uriOf: (person) => latest.current.mentions?.uriOf(person) ?? null })] : [],
3479
+ ...linkChips ? [LinkChips.configure(linkChips)] : [],
3480
+ ...upload ? [
3481
+ // A pasted picture is placed as `/` File places one; text on the clipboard stays text.
3482
+ PastedImages.configure({
3483
+ onImages: (pasted) => {
3484
+ if (!latest.current.upload) return false;
3485
+ void attachTo.current(pasted);
3486
+ return true;
3487
+ }
3488
+ })
3489
+ ] : [],
3490
+ // Markdown pasted as plain text lands as the blocks it spells, tables included.
3491
+ ...readMarkdown ? [PastedMarkdown.configure({ read: (text) => latest.current.readMarkdown?.(text) })] : [],
3492
+ // Where each comment is, drawn as a decoration, so a save never carries it.
3493
+ ...onCommentOnSelection ? [CommentHighlights] : [],
3494
+ ...extensions
3495
+ ],
3496
+ // Made once. A value coming back must not rebuild the editor under the caret; see the effect below.
3497
+ content: held ?? codec.read(value, format),
3498
+ editable: !readOnly,
3499
+ editorProps: {
3500
+ // Focusable when read only too: the selection strip, and so Comment on its words, shows only in a focused view.
3501
+ attributes: { "aria-label": label, role: "textbox", "aria-multiline": "true", tabindex: "0", class: richTextClassName2("default", "outline-none") },
3502
+ handleKeyDown: (view, event) => {
3503
+ if (event.key !== "Escape") return false;
3504
+ if (isSuggestionOpen() || isReferenceMenuOpen(view.state)) return false;
3505
+ const { selection, tr } = view.state;
3506
+ if (!selection.empty) {
3507
+ view.dispatch(tr.setSelection(TextSelection4.create(tr.doc, selection.to)));
3508
+ return true;
3509
+ }
3510
+ view.dom.blur();
3511
+ return true;
3512
+ }
3513
+ },
3514
+ onUpdate: ({ editor: e, transaction }) => {
3515
+ typed.current = e.getJSON();
3516
+ if (isChecklistTick(transaction)) void latestSave.current(typed.current);
3517
+ },
3518
+ onFocus: () => setFocused(true),
3519
+ onBlur: () => {
3520
+ setFocused(false);
3521
+ if (picking.current) return;
3522
+ void latestSave.current(typed.current);
3523
+ }
3524
+ },
3525
+ []
3526
+ );
3527
+ const arrived = value !== base && value !== superseded && !own.current.has(value);
3528
+ if (arrived && (readOnly || !focused && !saving && !failed && !restored)) {
3529
+ own.current.clear();
3530
+ setBase(value);
3531
+ }
3532
+ const waiting = arrived && !readOnly && (focused || failed || restored);
3533
+ useEffect7(() => {
3534
+ saved.current = base;
3535
+ if (!editor || editor.isDestroyed || base === shown.current) return;
3536
+ editor.commands.setContent(latest.current.codec.read(base, latest.current.format), { emitUpdate: false });
3537
+ shown.current = base;
3538
+ typed.current = null;
3539
+ }, [editor, base]);
3540
+ useEffect7(() => {
3541
+ if (editor && !editor.isDestroyed && editor.isEditable === readOnly) editor.setEditable(!readOnly, false);
3542
+ }, [editor, readOnly]);
3543
+ const empty = useEditorState2({ editor, selector: ({ editor: ed }) => !ed || ed.isEmpty });
3544
+ const load = () => {
3545
+ setBase(latest.current.value);
3546
+ setFailed(false);
3547
+ setRestored(false);
3548
+ };
3549
+ useEffect7(
3550
+ () => () => {
3551
+ left.current = true;
3552
+ if (!ended()) void latestSave.current(typed.current);
3553
+ },
3554
+ []
3555
+ );
3556
+ useEffect7(() => {
3557
+ onEditor?.(editor);
3558
+ return () => onEditor?.(null);
3559
+ }, [editor, onEditor]);
3560
+ const who = changedBy?.name ?? "Someone";
3561
+ const drawn = /* @__PURE__ */ jsxs9("div", { className: "flex flex-col gap-1", children: [
3562
+ /* @__PURE__ */ jsxs9(EditorBlockHandle, { editor, actions: blockRows, children: [
3563
+ /* @__PURE__ */ jsx11(EditorTableControls, { editor, children: /* @__PURE__ */ jsx11(EditorContent4, { editor, className: "-mx-2 cursor-text px-2 py-1", "data-document-editor": "" }) }),
3564
+ empty && !readOnly && placeholder && /* @__PURE__ */ jsx11("span", { "aria-hidden": true, className: "pointer-events-none absolute left-0 top-1 text-body-2 text-text-muted", children: placeholder })
3565
+ ] }),
3566
+ cards?.(editor),
3567
+ (!readOnly || onCommentOnSelection) && /* @__PURE__ */ jsx11(
3568
+ SelectionToolbar,
3569
+ {
3570
+ editor,
3571
+ marks: readOnly ? [] : ["bold", "italic", "underline", "code"],
3572
+ link: !readOnly,
3573
+ actions: onCommentOnSelection ? [
3574
+ {
3575
+ label: "Comment",
3576
+ icon: /* @__PURE__ */ jsx11(IconMessagePlus, { size: 16, stroke: 1.5 }),
3577
+ run: (ed) => {
3578
+ const anchor = anchorOfSelection(ed);
3579
+ if (!anchor) return;
3580
+ ed.commands.setTextSelection(ed.state.selection.to);
3581
+ onCommentOnSelection(anchor);
3582
+ }
3583
+ }
3584
+ ] : []
3585
+ }
3586
+ ),
3587
+ /* @__PURE__ */ jsx11(ReferenceMenuView, { editor }),
3588
+ /* @__PURE__ */ jsx11(FilePicker2, { ref: picker, multiple: true, onPick: (files) => void attach(files) }),
3589
+ waiting && /* @__PURE__ */ jsxs9(FieldLine2, { tone: "helper", children: [
3590
+ `${who} saved a newer version.`,
3591
+ " ",
3592
+ /* @__PURE__ */ jsx11(Button2, { variant: "muted", size: "small", onMouseDown: (event) => event.preventDefault(), onClick: load, children: "Load it" }),
3593
+ " ",
3594
+ "(replaces your changes)"
3595
+ ] }),
3596
+ uploadError && /* @__PURE__ */ jsx11(FieldLine2, { tone: "error", children: uploadError }),
3597
+ failed && /* @__PURE__ */ jsx11(FieldLine2, { tone: "error", children: "Could not save. Your text is still here." })
3598
+ ] });
3599
+ return /* @__PURE__ */ jsx11(Fragment6, { children: wrap ? wrap(drawn, editor) : drawn });
3600
+ }
3601
+ function slashSections({ table, upload, pickFile }) {
3602
+ const insert = [
3603
+ // Three by three with a header row, as every app's Insert → Table makes it.
3604
+ ...table ? [{ key: "insert-table", row: { label: "Table" }, run: (editor) => void editor.chain().focus().insertTable({ rows: 3, cols: 3, withHeaderRow: true }).run() }] : [],
3605
+ // Offered only where the editor has the list the row opens.
3606
+ { key: "insert-link", row: { label: "File", shortcut: "[" }, keywords: ["[", "link", "reference"], needs: ["referenceTrigger"], run: typeTrigger("[") },
3607
+ ...upload ? [{ key: "insert-upload", row: { label: "Upload" }, keywords: ["attach", "file", "picture"], run: () => pickFile.current() }] : [],
3608
+ { key: "insert-mention", row: { label: "Mention", shortcut: "@" }, keywords: ["@", "person", "people"], needs: ["personReference"], run: typeTrigger("@") }
3609
+ ];
3610
+ return [formatSection("block"), ...insert.length > 0 ? [{ label: "Insert", commands: insert }] : []];
3611
+ }
3179
3612
  export {
3180
3613
  AttachmentNode,
3181
3614
  BlockId,
@@ -3188,6 +3621,7 @@ export {
3188
3621
  CommentHighlights,
3189
3622
  ComposeBox,
3190
3623
  ComposeKeys,
3624
+ DocumentEditor,
3191
3625
  EditorBlockHandle,
3192
3626
  EditorTableControls,
3193
3627
  FORMATS,
@@ -3197,6 +3631,7 @@ export {
3197
3631
  PastedImages,
3198
3632
  PastedMarkdown,
3199
3633
  PersonMention,
3634
+ PersonReference,
3200
3635
  ReferenceCards,
3201
3636
  ReferenceMenu,
3202
3637
  ReferenceMenuView,