@agent-factory-platform/docs-react 0.5.0 → 0.7.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/index.js CHANGED
@@ -1,128 +1,136 @@
1
- import { jsx as t, jsxs as p, Fragment as De } from "react/jsx-runtime";
2
- import { Node as lt, mergeAttributes as ut } from "@tiptap/core";
3
- import dt from "@tiptap/extension-image";
4
- import ht from "@tiptap/extension-link";
5
- import mt from "@tiptap/extension-placeholder";
6
- import { TableKit as ft, TableCell as pt, TableHeader as gt } from "@tiptap/extension-table";
7
- import bt from "@tiptap/extension-text-align";
8
- import { TextStyle as vt, Color as kt, BackgroundColor as Dt } from "@tiptap/extension-text-style";
9
- import xt from "@tiptap/extension-task-item";
10
- import wt from "@tiptap/extension-task-list";
11
- import { Markdown as Ct } from "@tiptap/markdown";
12
- import { CellSelection as se } from "@tiptap/pm/tables";
13
- import { Slice as Ve } from "@tiptap/pm/model";
14
- import { useEditor as yt, EditorContent as zt } from "@tiptap/react";
15
- import { FloatingMenu as At, BubbleMenu as xe } from "@tiptap/react/menus";
16
- import St from "@tiptap/starter-kit";
17
- import { Toolbar as re, ToolbarSeparator as M, Input as we, IconTip as le, Pressable as v, MenuChoiceGroup as J, MenuCommandItem as S, Popover as Ce, ToolbarButton as F, Button as ne, Modal as Nt } from "@agent-factory-platform/ui-kit";
18
- import { Heading1 as ye, Heading2 as ze, Heading3 as Ae, List as Se, ListOrdered as Ne, ListChecks as Te, Quote as Re, SquareCode as Le, MessageSquareWarning as Me, Table2 as oe, Pilcrow as Be, Bold as Oe, Italic as Ee, Underline as He, Strikethrough as Ie, Code2 as Pe, Link2 as _e, Plus as Tt, Sparkles as je, ImagePlus as qe, Palette as $e, AlignLeft as Je, AlignCenter as Rt, AlignRight as Lt, Minus as Mt, ChevronDown as Bt, WandSparkles as Ot, BetweenHorizontalStart as Et, BetweenHorizontalEnd as Ht, Rows3 as It, BetweenVerticalStart as Pt, BetweenVerticalEnd as _t, Columns3 as jt, TableCellsMerge as qt, TableCellsSplit as $t, Trash2 as Jt } from "lucide-react";
19
- import { useMemo as Ft, useState as x, useSyncExternalStore as Kt, useRef as ie, useEffect as ae, useLayoutEffect as Wt } from "react";
20
- const W = "agentfactory.richtext.v1";
21
- function Vt(o) {
22
- return (o.split(".").at(-1) ?? o).replace(/([a-z])([A-Z])/g, "$1 $2").replace(/^./, (c) => c.toUpperCase());
1
+ var Gt = Object.defineProperty;
2
+ var Qt = (n, e, t) => e in n ? Gt(n, e, { enumerable: !0, configurable: !0, writable: !0, value: t }) : n[e] = t;
3
+ var p = (n, e, t) => Qt(n, typeof e != "symbol" ? e + "" : e, t);
4
+ import { jsx as i, jsxs as h, Fragment as Ke } from "react/jsx-runtime";
5
+ import { Node as Zt, mergeAttributes as en, getSchema as tn } from "@tiptap/core";
6
+ import nn from "@tiptap/extension-collaboration";
7
+ import sn from "@tiptap/extension-collaboration-caret";
8
+ import rn from "@tiptap/extension-image";
9
+ import on from "@tiptap/extension-link";
10
+ import an from "@tiptap/extension-placeholder";
11
+ import { TableKit as cn, TableCell as ln, TableHeader as dn } from "@tiptap/extension-table";
12
+ import un from "@tiptap/extension-text-align";
13
+ import { TextStyle as hn, Color as pn, BackgroundColor as fn } from "@tiptap/extension-text-style";
14
+ import mn from "@tiptap/extension-task-item";
15
+ import gn from "@tiptap/extension-task-list";
16
+ import { Markdown as vn } from "@tiptap/markdown";
17
+ import { CellSelection as Re } from "@tiptap/pm/tables";
18
+ import { Slice as xt } from "@tiptap/pm/model";
19
+ import { useEditor as bn, EditorContent as wn } from "@tiptap/react";
20
+ import { FloatingMenu as yn, BubbleMenu as Xe } from "@tiptap/react/menus";
21
+ import Sn from "@tiptap/starter-kit";
22
+ import { Toolbar as De, ToolbarSeparator as j, Input as Ue, IconTip as Te, Pressable as A, MenuChoiceGroup as oe, MenuCommandItem as P, Popover as We, ToolbarButton as ae, Button as U, Modal as kn, StateView as B, CardLabel as _, CardTitle as q, Card as Y, Tag as V, NativeSelect as Dn } from "@agent-factory-platform/ui-kit";
23
+ import { Heading1 as Ye, Heading2 as Ge, Heading3 as Qe, List as Ze, ListOrdered as et, ListChecks as tt, Quote as nt, SquareCode as st, MessageSquareWarning as rt, Table2 as Ce, Pilcrow as it, Bold as ot, Italic as at, Underline as ct, Strikethrough as lt, Code2 as dt, Link2 as ut, Plus as Cn, Sparkles as ht, ImagePlus as pt, Palette as ft, AlignLeft as mt, AlignCenter as xn, AlignRight as Nn, Minus as In, ChevronDown as An, WandSparkles as En, BetweenHorizontalStart as zn, BetweenHorizontalEnd as Rn, Rows3 as Un, BetweenVerticalStart as Tn, BetweenVerticalEnd as Ln, Columns3 as Pn, TableCellsMerge as Mn, TableCellsSplit as On, Trash2 as Nt, BookOpen as _n, ShieldCheck as qn, RefreshCw as Bn, Languages as Hn } from "lucide-react";
24
+ import { useMemo as jn, useState as E, useSyncExternalStore as pe, useRef as xe, useEffect as Ne, useLayoutEffect as Vn } from "react";
25
+ import { docsV1 as G, isRetryableRpcError as Le } from "@agent-factory-platform/client";
26
+ import { prosemirrorJSONToYXmlFragment as $n, yXmlFragmentToProsemirrorJSON as Fn } from "@tiptap/y-tiptap";
27
+ import * as M from "yjs";
28
+ const fe = "agentfactory.richtext.v1";
29
+ function Jn(n) {
30
+ return (n.split(".").at(-1) ?? n).replace(/([a-z])([A-Z])/g, "$1 $2").replace(/^./, (t) => t.toUpperCase());
23
31
  }
24
- const Fe = { status: "idle", output: "" }, Xt = () => () => {
32
+ const gt = { status: "idle", output: "" }, Kn = () => () => {
25
33
  };
26
- function Gt(o, i, c) {
27
- const h = o.state.doc.content.size, k = i.to - i.from;
28
- return o.commands.insertContentAt(i, c, { contentType: "markdown", updateSelection: !0 }), { from: i.from, to: i.from + o.state.doc.content.size - h + k };
34
+ function Xn(n, e, t) {
35
+ const s = n.state.doc.content.size, r = e.to - e.from;
36
+ return n.commands.insertContentAt(e, t, { contentType: "markdown", updateSelection: !0 }), { from: e.from, to: e.from + n.state.doc.content.size - s + r };
29
37
  }
30
- function Yt(o, i, c, h) {
38
+ function Wn(n, e, t, s) {
31
39
  try {
32
- return o.state.doc.slice(i.from, i.to).content.eq(h.content) ? (o.view.dispatch(o.state.tr.replaceRange(i.from, i.to, c)), !0) : !1;
40
+ return n.state.doc.slice(e.from, e.to).content.eq(s.content) ? (n.view.dispatch(n.state.tr.replaceRange(e.from, e.to, t)), !0) : !1;
33
41
  } catch {
34
42
  return !1;
35
43
  }
36
44
  }
37
- async function Qt(o, i, c) {
38
- const h = o.state.doc;
39
- if (!h.slice(i.range.from, i.range.to).content.eq(i.generated.content)) return;
40
- const k = o.state.tr.replaceRange(i.range.from, i.range.to, i.original), D = { schema: W, doc: k.doc.toJSON() }, C = String(await c(D));
41
- if (o.state.doc.eq(h))
42
- return o.view.dispatch(o.state.tr.replaceRange(i.range.from, i.range.to, i.original)), { value: D, revision: C };
45
+ async function Yn(n, e, t) {
46
+ const s = n.state.doc;
47
+ if (!s.slice(e.range.from, e.range.to).content.eq(e.generated.content)) return;
48
+ const r = n.state.tr.replaceRange(e.range.from, e.range.to, e.original), l = { schema: fe, doc: r.doc.toJSON() }, d = String(await t(l));
49
+ if (n.state.doc.eq(s))
50
+ return n.view.dispatch(n.state.tr.replaceRange(e.range.from, e.range.to, e.original)), { value: l, revision: d };
43
51
  }
44
- function Ut(o, i, c, h) {
45
- if (!Xe(o, i, c))
52
+ function Gn(n, e, t, s) {
53
+ if (!It(n, e, t))
46
54
  try {
47
- const k = Ve.fromJSON(o.schema, c.originalSlice), D = Gt(o, c.range, h);
48
- return { range: D, original: k, generated: o.state.doc.slice(D.from, D.to) };
55
+ const r = xt.fromJSON(n.schema, t.originalSlice), l = Xn(n, t.range, s);
56
+ return { range: l, original: r, generated: n.state.doc.slice(l.from, l.to) };
49
57
  } catch {
50
58
  return;
51
59
  }
52
60
  }
53
- function Xe(o, i, c) {
54
- if (i.documentId !== c.documentId || i.nodeId !== c.nodeId) return "identity";
55
- if (i.baseRevision !== c.baseRevision) return "revision";
56
- if (!c.originalSlice) return "missing_original";
57
- if (c.range.from < 0 || c.range.to < c.range.from || c.range.to > o.state.doc.content.size) return "range";
61
+ function It(n, e, t) {
62
+ if (e.documentId !== t.documentId || e.nodeId !== t.nodeId) return "identity";
63
+ if (e.baseRevision !== t.baseRevision) return "revision";
64
+ if (!t.originalSlice) return "missing_original";
65
+ if (t.range.from < 0 || t.range.to < t.range.from || t.range.to > n.state.doc.content.size) return "range";
58
66
  try {
59
- const h = Ve.fromJSON(o.schema, c.originalSlice);
60
- if (!o.state.doc.slice(c.range.from, c.range.to).content.eq(h.content)) return "selection";
67
+ const s = xt.fromJSON(n.schema, t.originalSlice);
68
+ if (!n.state.doc.slice(t.range.from, t.range.to).content.eq(s.content)) return "selection";
61
69
  } catch {
62
70
  return "invalid_slice";
63
71
  }
64
72
  }
65
- const Zt = lt.create({
73
+ const Qn = Zt.create({
66
74
  name: "callout",
67
75
  group: "block",
68
76
  content: "block+",
69
77
  defining: !0,
70
78
  parseHTML: () => [{ tag: "aside[data-callout]" }],
71
- renderHTML: ({ HTMLAttributes: o }) => ["aside", ut(o, { "data-callout": "info" }), 0]
72
- }), er = dt.extend({
79
+ renderHTML: ({ HTMLAttributes: n }) => ["aside", en(n, { "data-callout": "info" }), 0]
80
+ }), Zn = rn.extend({
73
81
  addAttributes() {
74
- var o;
75
- return { ...(o = this.parent) == null ? void 0 : o.call(this), asset_id: { default: null, parseHTML: (i) => i.getAttribute("data-asset-id"), renderHTML: (i) => i.asset_id ? { "data-asset-id": i.asset_id } : {} } };
82
+ var n;
83
+ return { ...(n = this.parent) == null ? void 0 : n.call(this), asset_id: { default: null, parseHTML: (e) => e.getAttribute("data-asset-id"), renderHTML: (e) => e.asset_id ? { "data-asset-id": e.asset_id } : {} } };
76
84
  }
77
- }), tr = ["var(--color-ink)", "var(--color-graphite)", "var(--color-rust)", "var(--color-data-blue)", "var(--color-success)", "var(--color-warning)", "var(--color-danger)"], K = ["var(--color-surface-muted)", "var(--color-surface-warm)", "var(--color-surface-cool)", "var(--color-data-4)", "var(--color-data-5)"], Ge = () => ({
85
+ }), es = ["var(--color-ink)", "var(--color-graphite)", "var(--color-rust)", "var(--color-data-blue)", "var(--color-success)", "var(--color-warning)", "var(--color-danger)"], de = ["var(--color-surface-muted)", "var(--color-surface-warm)", "var(--color-surface-cool)", "var(--color-data-4)", "var(--color-data-5)"], At = () => ({
78
86
  default: null,
79
- parseHTML: (o) => K.includes(o.style.backgroundColor) ? o.style.backgroundColor : null,
80
- renderHTML: ({ backgroundColor: o }) => o && K.includes(o) ? { style: `background-color: ${o}` } : {}
81
- }), rr = pt.extend({ addAttributes() {
82
- var o;
83
- return { ...(o = this.parent) == null ? void 0 : o.call(this), backgroundColor: Ge() };
84
- } }), nr = gt.extend({ addAttributes() {
85
- var o;
86
- return { ...(o = this.parent) == null ? void 0 : o.call(this), backgroundColor: Ge() };
87
- } }), Ke = () => ({ schema: W, doc: { type: "doc", content: [{ type: "paragraph" }] } });
88
- function We(o) {
89
- const i = (c) => {
90
- const h = c.type === "image" && c.attrs ? Object.fromEntries(Object.entries(c.attrs).filter(([k]) => k !== "src")) : c.attrs;
87
+ parseHTML: (n) => de.includes(n.style.backgroundColor) ? n.style.backgroundColor : null,
88
+ renderHTML: ({ backgroundColor: n }) => n && de.includes(n) ? { style: `background-color: ${n}` } : {}
89
+ }), ts = ln.extend({ addAttributes() {
90
+ var n;
91
+ return { ...(n = this.parent) == null ? void 0 : n.call(this), backgroundColor: At() };
92
+ } }), ns = dn.extend({ addAttributes() {
93
+ var n;
94
+ return { ...(n = this.parent) == null ? void 0 : n.call(this), backgroundColor: At() };
95
+ } }), vt = () => ({ schema: fe, doc: { type: "doc", content: [{ type: "paragraph" }] } });
96
+ function Pe(n) {
97
+ const e = (t) => {
98
+ const s = t.type === "image" && t.attrs ? Object.fromEntries(Object.entries(t.attrs).filter(([r]) => r !== "src")) : t.attrs;
91
99
  return {
92
- ...c,
93
- ...h ? { attrs: h } : {},
94
- ...c.content ? { content: c.content.map(i) } : {}
100
+ ...t,
101
+ ...s ? { attrs: s } : {},
102
+ ...t.content ? { content: t.content.map(e) } : {}
95
103
  };
96
104
  };
97
- return { schema: W, doc: i(o) };
105
+ return { schema: fe, doc: e(n) };
98
106
  }
99
- function Sr(o) {
100
- const i = JSON.parse(o);
101
- if (!i || typeof i != "object") throw new Error("invalid rich document");
102
- const c = i;
103
- if (c.doc === void 0)
104
- throw i.type === "doc" ? new Error("unsupported rich document schema") : new Error("invalid rich document");
105
- if (c.schema !== W) throw new Error("unsupported rich document schema");
106
- if (!c.doc || typeof c.doc != "object" || c.doc.type !== "doc") throw new Error("invalid rich document");
107
- return c;
107
+ function ss(n) {
108
+ const e = JSON.parse(n);
109
+ if (!e || typeof e != "object") throw new Error("invalid rich document");
110
+ const t = e;
111
+ if (t.doc === void 0)
112
+ throw e.type === "doc" ? new Error("unsupported rich document schema") : new Error("invalid rich document");
113
+ if (t.schema !== fe) throw new Error("unsupported rich document schema");
114
+ if (!t.doc || typeof t.doc != "object" || t.doc.type !== "doc") throw new Error("invalid rich document");
115
+ return t;
108
116
  }
109
- const or = (o) => {
110
- if (o.state.selection instanceof se) return !0;
111
- const { $from: i } = o.state.selection;
112
- for (let c = i.depth; c > 0; c -= 1) if (i.node(c).type.name === "table") return !0;
117
+ const rs = (n) => {
118
+ if (n.state.selection instanceof Re) return !0;
119
+ const { $from: e } = n.state.selection;
120
+ for (let t = e.depth; t > 0; t -= 1) if (e.node(t).type.name === "table") return !0;
113
121
  return !1;
114
- }, ir = (o, i) => {
115
- const c = o.state.selection.getBookmark(), h = o.isFocused;
116
- o.commands.setContent(i, { emitUpdate: !1 });
122
+ }, is = (n, e) => {
123
+ const t = n.state.selection.getBookmark(), s = n.isFocused;
124
+ n.commands.setContent(e, { emitUpdate: !1 });
117
125
  try {
118
- o.view.dispatch(o.state.tr.setSelection(c.resolve(o.state.doc)));
126
+ n.view.dispatch(n.state.tr.setSelection(t.resolve(n.state.doc)));
119
127
  } catch {
120
128
  }
121
- h && o.commands.focus();
122
- }, ar = (o) => [
123
- St.configure({ heading: { levels: [1, 2, 3] }, link: !1 }),
124
- ht.configure({ openOnClick: !0, autolink: !0, defaultProtocol: "https", protocols: ["http", "https", "mailto"], HTMLAttributes: { target: "_blank", rel: "noopener noreferrer" } }),
125
- er.configure({
129
+ s && n.commands.focus();
130
+ }, Et = (n, e) => [
131
+ Sn.configure({ heading: { levels: [1, 2, 3] }, link: !1, undoRedo: e ? !1 : {} }),
132
+ on.configure({ openOnClick: !0, autolink: !0, defaultProtocol: "https", protocols: ["http", "https", "mailto"], HTMLAttributes: { target: "_blank", rel: "noopener noreferrer" } }),
133
+ Zn.configure({
126
134
  allowBase64: !1,
127
135
  resize: {
128
136
  enabled: !0,
@@ -132,366 +140,1361 @@ const or = (o) => {
132
140
  alwaysPreserveAspectRatio: !0
133
141
  }
134
142
  }),
135
- ft.configure({ table: { resizable: !0, allowTableNodeSelection: !0 }, tableCell: !1, tableHeader: !1 }),
136
- rr,
137
- nr,
138
- bt.configure({ types: ["heading", "paragraph"], alignments: ["left", "center", "right"] }),
139
- vt,
140
- kt,
141
- Dt,
142
- wt,
143
- xt.configure({ nested: !0 }),
144
- Zt,
145
- mt.configure({ placeholder: o }),
146
- Ct
143
+ cn.configure({ table: { resizable: !0, allowTableNodeSelection: !0 }, tableCell: !1, tableHeader: !1 }),
144
+ ts,
145
+ ns,
146
+ un.configure({ types: ["heading", "paragraph"], alignments: ["left", "center", "right"] }),
147
+ hn,
148
+ pn,
149
+ fn,
150
+ gn,
151
+ mn.configure({ nested: !0 }),
152
+ Qn,
153
+ an.configure({ placeholder: n }),
154
+ vn,
155
+ ...e ? [nn.configure({ document: e.document, field: e.field ?? "prosemirror" })] : [],
156
+ ...e != null && e.awareness ? [sn.configure({ provider: { awareness: e.awareness }, user: e.user ?? {} })] : []
147
157
  ];
148
- function Nr({ value: o, editable: i, placeholder: c, ariaLabel: h, linkLabel: k = "Link address", saveLabel: D = "Save", surface: C = "panel", source: N, documentId: P = (N == null ? void 0 : N.id) ?? "", nodeId: R = (N == null ? void 0 : N.id) ?? "", baseRevision: B = "", assistant: g, assistantInstructions: Ye = {}, onChange: y, onAssistantCommit: V, onImageUpload: z, resolveImage: X, labels: Qe = {} }) {
149
- var ve;
150
- if (g && !V) throw new Error("RichDocument assistant requires onAssistantCommit");
151
- const n = (r) => Qe[r] ?? Vt(r), Ue = Ft(() => ar(c), [c]), [Ze, ue] = x(!1), [de, G] = x(!1), [O, T] = x(null), [he, Y] = x(!1), [et, _] = x(!1), [me, Q] = x(""), [j, w] = x(""), [tt, L] = x(), [E, U] = x(), [fe, q] = x(!1), [rt, nt] = x(0), m = Kt((g == null ? void 0 : g.subscribe) ?? Xt, (g == null ? void 0 : g.getSnapshot) ?? (() => Fe), (g == null ? void 0 : g.getSnapshot) ?? (() => Fe)), Z = ie(null), H = ie(null), I = ie(!1), ee = async (r, a) => {
152
- const s = H.current;
153
- if (!s || !z) return;
154
- let u;
158
+ function os({ value: n, editable: e, placeholder: t, ariaLabel: s, linkLabel: r = "Link address", saveLabel: l = "Save", surface: d = "panel", source: f, documentId: y = (f == null ? void 0 : f.id) ?? "", nodeId: x = (f == null ? void 0 : f.id) ?? "", baseRevision: b = "", collaboration: C, assistant: S, assistantInstructions: T = {}, onChange: I, onAssistantCommit: F, onImageUpload: z, resolveImage: me, labels: qt = {} }) {
159
+ var Fe;
160
+ if (S && !F) throw new Error("RichDocument assistant requires onAssistantCommit");
161
+ const c = (a) => qt[a] ?? Jn(a), Bt = jn(() => Et(t, C), [C, t]), [Ht, Oe] = E(!1), [_e, ge] = E(!1), [J, O] = E(null), [qe, ve] = E(!1), [jt, ne] = E(!1), [Be, be] = E(""), [se, R] = E(""), [Vt, H] = E(), [K, we] = E(), [He, re] = E(!1), [$t, Ft] = E(0), k = pe((S == null ? void 0 : S.subscribe) ?? Kn, (S == null ? void 0 : S.getSnapshot) ?? (() => gt), (S == null ? void 0 : S.getSnapshot) ?? (() => gt)), ye = xe(null), X = xe(null), W = xe(!1), Se = async (a, u) => {
162
+ const m = X.current;
163
+ if (!m || !z) return;
164
+ let v;
155
165
  try {
156
- u = await z(r);
166
+ v = await z(a);
157
167
  } catch {
158
168
  return;
159
169
  }
160
- const f = { type: "image", attrs: { src: u.url, asset_id: u.assetId } };
161
- a !== void 0 ? s.chain().focus().insertContentAt(a, f).run() : s.chain().focus().setImage(f.attrs).run();
162
- }, e = yt({
163
- extensions: Ue,
164
- content: (o ?? Ke()).doc,
170
+ const D = { type: "image", attrs: { src: v.url, asset_id: v.assetId } };
171
+ u !== void 0 ? m.chain().focus().insertContentAt(u, D).run() : m.chain().focus().setImage(D.attrs).run();
172
+ }, o = bn({
173
+ extensions: Bt,
174
+ content: C ? void 0 : (n ?? vt()).doc,
165
175
  contentType: "json",
166
- editable: i,
176
+ editable: e,
167
177
  immediatelyRender: !1,
168
178
  editorProps: {
169
- attributes: { class: C === "document" ? "docs-prose min-h-[520px] max-w-none px-0 pb-20 pt-5 outline-none" : "docs-prose min-h-[420px] max-w-none px-5 py-5 outline-none", "aria-label": h, role: i ? "textbox" : "document", "aria-multiline": i ? "true" : "false" },
170
- handlePaste: (r, a) => {
171
- var f, b, d;
172
- const s = [...((f = a.clipboardData) == null ? void 0 : f.files) ?? []].find((A) => A.type.startsWith("image/"));
173
- if (s && z)
174
- return ee(s), !0;
175
- const u = ((b = a.clipboardData) == null ? void 0 : b.getData("text/plain")) ?? "";
176
- return cr(u) ? ((d = H.current) == null || d.commands.insertContent(u, { contentType: "markdown" }), !0) : !1;
179
+ attributes: { class: d === "document" ? "docs-prose min-h-[520px] max-w-none px-0 pb-20 pt-5 outline-none" : "docs-prose min-h-[420px] max-w-none px-5 py-5 outline-none", "aria-label": s, role: e ? "textbox" : "document", "aria-multiline": e ? "true" : "false" },
180
+ handlePaste: (a, u) => {
181
+ var D, N, w;
182
+ const m = [...((D = u.clipboardData) == null ? void 0 : D.files) ?? []].find((L) => L.type.startsWith("image/"));
183
+ if (m && z)
184
+ return Se(m), !0;
185
+ const v = ((N = u.clipboardData) == null ? void 0 : N.getData("text/plain")) ?? "";
186
+ return as(v) ? ((w = X.current) == null || w.commands.insertContent(v, { contentType: "markdown" }), !0) : !1;
177
187
  },
178
- handleDrop: (r, a) => {
179
- var f, b;
180
- const s = [...((f = a.dataTransfer) == null ? void 0 : f.files) ?? []].find((d) => d.type.startsWith("image/"));
181
- if (!s || !z) return !1;
182
- const u = (b = r.posAtCoords({ left: a.clientX, top: a.clientY })) == null ? void 0 : b.pos;
183
- return ee(s, u), !0;
188
+ handleDrop: (a, u) => {
189
+ var D, N;
190
+ const m = [...((D = u.dataTransfer) == null ? void 0 : D.files) ?? []].find((w) => w.type.startsWith("image/"));
191
+ if (!m || !z) return !1;
192
+ const v = (N = a.posAtCoords({ left: u.clientX, top: u.clientY })) == null ? void 0 : N.pos;
193
+ return Se(m, v), !0;
184
194
  },
185
- handleKeyDown: (r, a) => {
186
- if (!i || !(a.metaKey || a.ctrlKey) || a.key.toLowerCase() !== "k") return !1;
187
- a.preventDefault(), a.stopPropagation();
188
- const s = H.current;
189
- return Q(String((s == null ? void 0 : s.getAttributes("link").href) ?? "https://")), _(!0), !0;
195
+ handleKeyDown: (a, u) => {
196
+ if (!e || !(u.metaKey || u.ctrlKey) || u.key.toLowerCase() !== "k") return !1;
197
+ u.preventDefault(), u.stopPropagation();
198
+ const m = X.current;
199
+ return be(String((m == null ? void 0 : m.getAttributes("link").href) ?? "https://")), ne(!0), !0;
190
200
  }
191
201
  },
192
- onUpdate: ({ editor: r, transaction: a }) => {
193
- ue(r.state.doc.textBetween(Math.max(0, r.state.doc.content.size - 2), r.state.doc.content.size, " ").endsWith("/")), !I.current && !a.getMeta("docsAssetProjection") && (y == null || y(We(r.getJSON())));
202
+ onUpdate: ({ editor: a, transaction: u }) => {
203
+ Oe(a.state.doc.textBetween(Math.max(0, a.state.doc.content.size - 2), a.state.doc.content.size, " ").endsWith("/")), !W.current && !u.getMeta("docsAssetProjection") && (I == null || I(Pe(a.getJSON())));
194
204
  }
195
205
  });
196
- ae(() => (H.current = e, () => {
197
- H.current = null;
198
- }), [e]), ae(() => {
199
- e == null || e.setEditable(i);
200
- }, [i, e]), Wt(() => {
201
- if (!e) return;
202
- const r = (o ?? Ke()).doc;
203
- if (JSON.stringify(e.getJSON()) !== JSON.stringify(r)) {
204
- I.current = !0;
206
+ Ne(() => (X.current = o, () => {
207
+ X.current = null;
208
+ }), [o]), Ne(() => {
209
+ o == null || o.setEditable(e);
210
+ }, [e, o]), Vn(() => {
211
+ if (!o || C) return;
212
+ const a = (n ?? vt()).doc;
213
+ if (JSON.stringify(o.getJSON()) !== JSON.stringify(a)) {
214
+ W.current = !0;
205
215
  try {
206
- ir(e, r);
216
+ is(o, a);
207
217
  } finally {
208
- I.current = !1;
218
+ W.current = !1;
209
219
  }
210
220
  }
211
- }, [e, o]), ae(() => {
212
- if (!e || !X) return;
213
- let r = !1, a;
214
- const s = [];
215
- return e.state.doc.descendants((u, f) => {
216
- const b = u.type.name === "image" ? String(u.attrs.asset_id ?? "") : "";
217
- b && s.push({ assetId: b, position: f });
218
- }), Promise.allSettled(s.map(async (u) => ({ ...u, ...await X(u.assetId) }))).then((u) => {
219
- if (r) return;
220
- let f = e.state.tr, b = Number.POSITIVE_INFINITY;
221
- for (const d of u) {
222
- if (d.status !== "fulfilled" || !d.value.url) continue;
223
- const A = f.doc.nodeAt(d.value.position);
224
- if (!(!A || String(A.attrs.asset_id ?? "") !== d.value.assetId) && (f = f.setNodeMarkup(d.value.position, void 0, { ...A.attrs, src: d.value.url }), d.value.expiresAt !== void 0)) {
225
- const ke = new Date(d.value.expiresAt).getTime();
226
- Number.isFinite(ke) && (b = Math.min(b, ke));
221
+ }, [C, o, n]), Ne(() => {
222
+ if (!o || !me) return;
223
+ let a = !1, u;
224
+ const m = [];
225
+ return o.state.doc.descendants((v, D) => {
226
+ const N = v.type.name === "image" ? String(v.attrs.asset_id ?? "") : "";
227
+ N && m.push({ assetId: N, position: D });
228
+ }), Promise.allSettled(m.map(async (v) => ({ ...v, ...await me(v.assetId) }))).then((v) => {
229
+ if (a) return;
230
+ let D = o.state.tr, N = Number.POSITIVE_INFINITY;
231
+ for (const w of v) {
232
+ if (w.status !== "fulfilled" || !w.value.url) continue;
233
+ const L = D.doc.nodeAt(w.value.position);
234
+ if (!(!L || String(L.attrs.asset_id ?? "") !== w.value.assetId) && (D = D.setNodeMarkup(w.value.position, void 0, { ...L.attrs, src: w.value.url }), w.value.expiresAt !== void 0)) {
235
+ const Je = new Date(w.value.expiresAt).getTime();
236
+ Number.isFinite(Je) && (N = Math.min(N, Je));
227
237
  }
228
238
  }
229
- f.docChanged && e.view.dispatch(f.setMeta("docsAssetProjection", !0).setMeta("addToHistory", !1)), Number.isFinite(b) && (a = setTimeout(() => nt((d) => d + 1), Math.max(1e3, b - Date.now() - 3e4)));
239
+ D.docChanged && o.view.dispatch(D.setMeta("docsAssetProjection", !0).setMeta("addToHistory", !1)), Number.isFinite(N) && (u = setTimeout(() => Ft((w) => w + 1), Math.max(1e3, N - Date.now() - 3e4)));
230
240
  }), () => {
231
- r = !0, a && clearTimeout(a);
241
+ a = !0, u && clearTimeout(u);
232
242
  };
233
- }, [e, rt, X, o]);
234
- const $ = (r) => {
235
- r(), ue(!1), e == null || e.commands.focus();
236
- }, pe = () => {
237
- e && (Q(String(e.getAttributes("link").href ?? "https://")), _(!0));
238
- }, ot = () => {
239
- if (!e) return;
240
- const r = me.trim();
241
- r ? e.chain().focus().extendMarkRange("link").setLink({ href: r }).run() : e.chain().focus().unsetLink().run(), _(!1);
242
- }, te = (r) => {
243
- if (!e || !g) return;
244
- const { from: a, to: s } = e.state.selection, u = e.state.doc.textBetween(a, s, `
245
- `), f = [];
246
- e.state.doc.nodesBetween(a, Math.max(a + 1, s), (d) => {
247
- if (d.type.name !== "image") return;
248
- const A = String(d.attrs.asset_id ?? "");
249
- A && f.push({ assetId: A });
243
+ }, [o, $t, me, n]);
244
+ const ie = (a) => {
245
+ a(), Oe(!1), o == null || o.commands.focus();
246
+ }, je = () => {
247
+ o && (be(String(o.getAttributes("link").href ?? "https://")), ne(!0));
248
+ }, Jt = () => {
249
+ if (!o) return;
250
+ const a = Be.trim();
251
+ a ? o.chain().focus().extendMarkRange("link").setLink({ href: a }).run() : o.chain().focus().unsetLink().run(), ne(!1);
252
+ }, ke = (a) => {
253
+ if (!o || !S) return;
254
+ const { from: u, to: m } = o.state.selection, v = o.state.doc.textBetween(u, m, `
255
+ `), D = [];
256
+ o.state.doc.nodesBetween(u, Math.max(u + 1, m), (w) => {
257
+ if (w.type.name !== "image") return;
258
+ const L = String(w.attrs.asset_id ?? "");
259
+ L && D.push({ assetId: L });
250
260
  });
251
- const b = Ye[r] ?? `${r === "explain" ? "Explain" : r === "rewrite" ? "Rewrite" : "Continue"} the selected document content.`;
252
- w(""), L(void 0), U(void 0), g.submit({
261
+ const N = T[a] ?? `${a === "explain" ? "Explain" : a === "rewrite" ? "Rewrite" : "Continue"} the selected document content.`;
262
+ R(""), H(void 0), we(void 0), S.submit({
253
263
  version: 2,
254
- operation: r,
255
- documentId: P,
256
- nodeId: R,
257
- baseRevision: String(B),
258
- range: { from: a, to: s },
259
- selection: u,
260
- instruction: b,
261
- context: `${e.getText({ blockSeparator: `
262
- ` }).slice(-12e3)}${f.length ? `
264
+ operation: a,
265
+ documentId: y,
266
+ nodeId: x,
267
+ baseRevision: String(b),
268
+ range: { from: u, to: m },
269
+ selection: v,
270
+ instruction: N,
271
+ context: `${o.getText({ blockSeparator: `
272
+ ` }).slice(-12e3)}${D.length ? `
263
273
 
264
- [Selected images: ${f.map((d) => d.assetId).join(", ")}]` : ""}`,
265
- originalSlice: e.state.doc.slice(a, s).toJSON(),
266
- images: f,
267
- source: N
268
- }).catch((d) => w(d instanceof Error ? d.message : String(d)));
269
- }, it = async () => {
270
- if (!e || !m.operation || !m.output) return;
271
- const r = Xe(e, { documentId: P, nodeId: R, baseRevision: String(B) }, m.operation);
272
- if (r) {
273
- L(r), w(n("richDocument.aiConflict"));
274
+ [Selected images: ${D.map((w) => w.assetId).join(", ")}]` : ""}`,
275
+ originalSlice: o.state.doc.slice(u, m).toJSON(),
276
+ images: D,
277
+ source: f
278
+ }).catch((w) => R(w instanceof Error ? w.message : String(w)));
279
+ }, Kt = async () => {
280
+ if (!o || !k.operation || !k.output) return;
281
+ const a = It(o, { documentId: y, nodeId: x, baseRevision: String(b) }, k.operation);
282
+ if (a) {
283
+ H(a), R(c("richDocument.aiConflict"));
274
284
  return;
275
285
  }
276
- I.current = !0;
277
- let a;
286
+ W.current = !0;
287
+ let u;
278
288
  try {
279
- a = Ut(e, { documentId: P, nodeId: R, baseRevision: String(B) }, m.operation, m.output);
289
+ u = Gn(o, { documentId: y, nodeId: x, baseRevision: String(b) }, k.operation, k.output);
280
290
  } finally {
281
- I.current = !1;
291
+ W.current = !1;
282
292
  }
283
- if (!a) {
284
- L("invalid_slice"), w(n("richDocument.aiConflict"));
293
+ if (!u) {
294
+ H("invalid_slice"), R(c("richDocument.aiConflict"));
285
295
  return;
286
296
  }
287
- const s = We(e.getJSON());
288
- q(!0), e.setEditable(!1);
297
+ const m = Pe(o.getJSON());
298
+ re(!0), o.setEditable(!1);
289
299
  try {
290
- const u = String(await V({ kind: "apply", value: s, nodeId: R, expectedRevision: String(B) }));
291
- w(""), L(void 0), U({ ...a, revision: u }), y == null || y(s, u);
300
+ const v = String(await F({ kind: "apply", value: m, nodeId: x, expectedRevision: String(b) }));
301
+ R(""), H(void 0), we({ ...u, revision: v }), I == null || I(m, v);
292
302
  } catch {
293
- Yt(e, a.range, a.original, a.generated), w(n("richDocument.aiConflict"));
303
+ Wn(o, u.range, u.original, u.generated), R(c("richDocument.aiConflict"));
294
304
  } finally {
295
- e.setEditable(i), q(!1);
305
+ o.setEditable(e), re(!1);
296
306
  }
297
- }, at = async () => {
298
- if (!(!e || !E)) {
299
- q(!0), e.setEditable(!1);
307
+ }, Xt = async () => {
308
+ if (!(!o || !K)) {
309
+ re(!0), o.setEditable(!1);
300
310
  try {
301
- const r = await Qt(e, E, (a) => V({ kind: "rollback", value: a, nodeId: R, expectedRevision: E.revision }));
302
- if (!r) {
303
- L("selection"), w(n("richDocument.aiConflict"));
311
+ const a = await Yn(o, K, (u) => F({ kind: "rollback", value: u, nodeId: x, expectedRevision: K.revision }));
312
+ if (!a) {
313
+ H("selection"), R(c("richDocument.aiConflict"));
304
314
  return;
305
315
  }
306
- w(""), L(void 0), U(void 0), y == null || y(r.value, r.revision);
316
+ R(""), H(void 0), we(void 0), I == null || I(a.value, a.revision);
307
317
  } catch {
308
- w(n("richDocument.aiConflict"));
318
+ R(c("richDocument.aiConflict"));
309
319
  } finally {
310
- e.setEditable(i), q(!1);
320
+ o.setEditable(e), re(!1);
311
321
  }
312
322
  }
313
- }, l = (r, a, s, u) => /* @__PURE__ */ t(F, { title: r, "aria-label": r, "aria-pressed": s, className: "aria-pressed:bg-surface-raised aria-pressed:text-ink", onClick: u, children: a }), ge = (r, a, s) => /* @__PURE__ */ t(F, { title: a, "aria-label": a, "aria-expanded": O === r, onMouseDown: (u) => u.preventDefault(), onClick: () => T((u) => u === r ? null : r), children: s }), ct = (r) => {
314
- r(), G(!1), e == null || e.commands.focus();
315
- }, be = e ? [
316
- [n("richDocument.heading1"), /* @__PURE__ */ t(ye, { size: 15, "aria-hidden": !0 }, "h1"), () => e.chain().focus().toggleHeading({ level: 1 }).run()],
317
- [n("richDocument.heading2"), /* @__PURE__ */ t(ze, { size: 15, "aria-hidden": !0 }, "h2"), () => e.chain().focus().toggleHeading({ level: 2 }).run()],
318
- [n("richDocument.heading3"), /* @__PURE__ */ t(Ae, { size: 15, "aria-hidden": !0 }, "h3"), () => e.chain().focus().toggleHeading({ level: 3 }).run()],
319
- [n("richDocument.bulletList"), /* @__PURE__ */ t(Se, { size: 15, "aria-hidden": !0 }, "bullet"), () => e.chain().focus().toggleBulletList().run()],
320
- [n("richDocument.orderedList"), /* @__PURE__ */ t(Ne, { size: 15, "aria-hidden": !0 }, "ordered"), () => e.chain().focus().toggleOrderedList().run()],
321
- [n("richDocument.taskList"), /* @__PURE__ */ t(Te, { size: 15, "aria-hidden": !0 }, "task"), () => e.chain().focus().toggleTaskList().run()],
322
- [n("richDocument.quote"), /* @__PURE__ */ t(Re, { size: 15, "aria-hidden": !0 }, "quote"), () => e.chain().focus().toggleBlockquote().run()],
323
- [n("richDocument.codeBlock"), /* @__PURE__ */ t(Le, { size: 15, "aria-hidden": !0 }, "code"), () => e.chain().focus().toggleCodeBlock().run()],
324
- [n("richDocument.callout"), /* @__PURE__ */ t(Me, { size: 15, "aria-hidden": !0 }, "callout"), () => e.chain().focus().wrapIn("callout").run()],
325
- [n("richDocument.table"), /* @__PURE__ */ t(oe, { size: 15, "aria-hidden": !0 }, "table"), () => e.chain().focus().insertTable({ rows: 3, cols: 3, withHeaderRow: !0 }).run()]
326
- ] : [], st = e ? [
327
- [n("richDocument.paragraph"), /* @__PURE__ */ t(Be, { size: 15, "aria-hidden": !0 }, "p"), () => e.chain().focus().setParagraph().run()],
328
- ...be.slice(0, 8)
323
+ }, g = (a, u, m, v) => /* @__PURE__ */ i(ae, { title: a, "aria-label": a, "aria-pressed": m, className: "aria-pressed:bg-surface-raised aria-pressed:text-ink", onClick: v, children: u }), Ve = (a, u, m) => /* @__PURE__ */ i(ae, { title: u, "aria-label": u, "aria-expanded": J === a, onMouseDown: (v) => v.preventDefault(), onClick: () => O((v) => v === a ? null : a), children: m }), Wt = (a) => {
324
+ a(), ge(!1), o == null || o.commands.focus();
325
+ }, $e = o ? [
326
+ [c("richDocument.heading1"), /* @__PURE__ */ i(Ye, { size: 15, "aria-hidden": !0 }, "h1"), () => o.chain().focus().toggleHeading({ level: 1 }).run()],
327
+ [c("richDocument.heading2"), /* @__PURE__ */ i(Ge, { size: 15, "aria-hidden": !0 }, "h2"), () => o.chain().focus().toggleHeading({ level: 2 }).run()],
328
+ [c("richDocument.heading3"), /* @__PURE__ */ i(Qe, { size: 15, "aria-hidden": !0 }, "h3"), () => o.chain().focus().toggleHeading({ level: 3 }).run()],
329
+ [c("richDocument.bulletList"), /* @__PURE__ */ i(Ze, { size: 15, "aria-hidden": !0 }, "bullet"), () => o.chain().focus().toggleBulletList().run()],
330
+ [c("richDocument.orderedList"), /* @__PURE__ */ i(et, { size: 15, "aria-hidden": !0 }, "ordered"), () => o.chain().focus().toggleOrderedList().run()],
331
+ [c("richDocument.taskList"), /* @__PURE__ */ i(tt, { size: 15, "aria-hidden": !0 }, "task"), () => o.chain().focus().toggleTaskList().run()],
332
+ [c("richDocument.quote"), /* @__PURE__ */ i(nt, { size: 15, "aria-hidden": !0 }, "quote"), () => o.chain().focus().toggleBlockquote().run()],
333
+ [c("richDocument.codeBlock"), /* @__PURE__ */ i(st, { size: 15, "aria-hidden": !0 }, "code"), () => o.chain().focus().toggleCodeBlock().run()],
334
+ [c("richDocument.callout"), /* @__PURE__ */ i(rt, { size: 15, "aria-hidden": !0 }, "callout"), () => o.chain().focus().wrapIn("callout").run()],
335
+ [c("richDocument.table"), /* @__PURE__ */ i(Ce, { size: 15, "aria-hidden": !0 }, "table"), () => o.chain().focus().insertTable({ rows: 3, cols: 3, withHeaderRow: !0 }).run()]
336
+ ] : [], Yt = o ? [
337
+ [c("richDocument.paragraph"), /* @__PURE__ */ i(it, { size: 15, "aria-hidden": !0 }, "p"), () => o.chain().focus().setParagraph().run()],
338
+ ...$e.slice(0, 8)
329
339
  ] : [];
330
- return /* @__PURE__ */ p("div", { className: C === "document" ? "relative min-w-0" : "relative min-w-0 overflow-hidden rounded-xl border border-border bg-pure-white", "data-rich-document": !0, "data-document-id": P || void 0, "data-node-id": R || void 0, "data-base-revision": String(B) || void 0, "data-editable": i || void 0, "data-surface": C, onDragOver: (r) => z && r.preventDefault(), children: [
331
- i && e && /* @__PURE__ */ p(re, { label: h, density: "compact", variant: C === "document" ? "bare" : "framed", className: C === "document" ? "sticky top-0 z-20 h-auto min-h-control-compact w-full flex-wrap border-b border-divider bg-pure-white py-1" : "h-auto min-h-control-compact flex-wrap rounded-none border-x-0 border-t-0", children: [
332
- l(n("richDocument.heading1"), /* @__PURE__ */ t(ye, { size: 15, "aria-hidden": !0 }), e.isActive("heading", { level: 1 }), () => e.chain().focus().toggleHeading({ level: 1 }).run()),
333
- l(n("richDocument.heading2"), /* @__PURE__ */ t(ze, { size: 15, "aria-hidden": !0 }), e.isActive("heading", { level: 2 }), () => e.chain().focus().toggleHeading({ level: 2 }).run()),
334
- l(n("richDocument.heading3"), /* @__PURE__ */ t(Ae, { size: 15, "aria-hidden": !0 }), e.isActive("heading", { level: 3 }), () => e.chain().focus().toggleHeading({ level: 3 }).run()),
335
- /* @__PURE__ */ t(M, {}),
336
- l(n("richDocument.bold"), /* @__PURE__ */ t(Oe, { size: 15, "aria-hidden": !0 }), e.isActive("bold"), () => e.chain().focus().toggleBold().run()),
337
- l(n("richDocument.italic"), /* @__PURE__ */ t(Ee, { size: 15, "aria-hidden": !0 }), e.isActive("italic"), () => e.chain().focus().toggleItalic().run()),
338
- l(n("richDocument.underline"), /* @__PURE__ */ t(He, { size: 15, "aria-hidden": !0 }), e.isActive("underline"), () => e.chain().focus().toggleUnderline().run()),
339
- l(n("richDocument.strike"), /* @__PURE__ */ t(Ie, { size: 15, "aria-hidden": !0 }), e.isActive("strike"), () => e.chain().focus().toggleStrike().run()),
340
- l(n("richDocument.code"), /* @__PURE__ */ t(Pe, { size: 15, "aria-hidden": !0 }), e.isActive("code"), () => e.chain().focus().toggleCode().run()),
341
- l(n("richDocument.link"), /* @__PURE__ */ t(_e, { size: 15, "aria-hidden": !0 }), e.isActive("link"), pe),
342
- /* @__PURE__ */ t(M, {}),
343
- l(n("richDocument.bulletList"), /* @__PURE__ */ t(Se, { size: 15, "aria-hidden": !0 }), e.isActive("bulletList"), () => e.chain().focus().toggleBulletList().run()),
344
- l(n("richDocument.orderedList"), /* @__PURE__ */ t(Ne, { size: 15, "aria-hidden": !0 }), e.isActive("orderedList"), () => e.chain().focus().toggleOrderedList().run()),
345
- l(n("richDocument.taskList"), /* @__PURE__ */ t(Te, { size: 15, "aria-hidden": !0 }), e.isActive("taskList"), () => e.chain().focus().toggleTaskList().run()),
346
- l(n("richDocument.quote"), /* @__PURE__ */ t(Re, { size: 15, "aria-hidden": !0 }), e.isActive("blockquote"), () => e.chain().focus().toggleBlockquote().run()),
347
- l(n("richDocument.codeBlock"), /* @__PURE__ */ t(Le, { size: 15, "aria-hidden": !0 }), e.isActive("codeBlock"), () => e.chain().focus().toggleCodeBlock().run()),
348
- l(n("richDocument.rule"), /* @__PURE__ */ t(Mt, { size: 15, "aria-hidden": !0 }), !1, () => e.chain().focus().setHorizontalRule().run()),
349
- l(n("richDocument.callout"), /* @__PURE__ */ t(Me, { size: 15, "aria-hidden": !0 }), e.isActive("callout"), () => e.chain().focus().wrapIn("callout").run()),
350
- l(n("richDocument.table"), /* @__PURE__ */ t(oe, { size: 15, "aria-hidden": !0 }), e.isActive("table"), () => e.chain().focus().insertTable({ rows: 3, cols: 3, withHeaderRow: !0 }).run()),
351
- z && l(n("richDocument.image"), /* @__PURE__ */ t(qe, { size: 15, "aria-hidden": !0 }), !1, () => {
352
- var r;
353
- return (r = Z.current) == null ? void 0 : r.click();
340
+ return /* @__PURE__ */ h("div", { className: d === "document" ? "relative min-w-0" : "relative min-w-0 overflow-hidden rounded-xl border border-border bg-pure-white", "data-rich-document": !0, "data-document-id": y || void 0, "data-node-id": x || void 0, "data-base-revision": String(b) || void 0, "data-editable": e || void 0, "data-surface": d, onDragOver: (a) => z && a.preventDefault(), children: [
341
+ e && o && /* @__PURE__ */ h(De, { label: s, density: "compact", variant: d === "document" ? "bare" : "framed", className: d === "document" ? "sticky top-0 z-20 h-auto min-h-control-compact w-full flex-wrap border-b border-divider bg-pure-white py-1" : "h-auto min-h-control-compact flex-wrap rounded-none border-x-0 border-t-0", children: [
342
+ g(c("richDocument.heading1"), /* @__PURE__ */ i(Ye, { size: 15, "aria-hidden": !0 }), o.isActive("heading", { level: 1 }), () => o.chain().focus().toggleHeading({ level: 1 }).run()),
343
+ g(c("richDocument.heading2"), /* @__PURE__ */ i(Ge, { size: 15, "aria-hidden": !0 }), o.isActive("heading", { level: 2 }), () => o.chain().focus().toggleHeading({ level: 2 }).run()),
344
+ g(c("richDocument.heading3"), /* @__PURE__ */ i(Qe, { size: 15, "aria-hidden": !0 }), o.isActive("heading", { level: 3 }), () => o.chain().focus().toggleHeading({ level: 3 }).run()),
345
+ /* @__PURE__ */ i(j, {}),
346
+ g(c("richDocument.bold"), /* @__PURE__ */ i(ot, { size: 15, "aria-hidden": !0 }), o.isActive("bold"), () => o.chain().focus().toggleBold().run()),
347
+ g(c("richDocument.italic"), /* @__PURE__ */ i(at, { size: 15, "aria-hidden": !0 }), o.isActive("italic"), () => o.chain().focus().toggleItalic().run()),
348
+ g(c("richDocument.underline"), /* @__PURE__ */ i(ct, { size: 15, "aria-hidden": !0 }), o.isActive("underline"), () => o.chain().focus().toggleUnderline().run()),
349
+ g(c("richDocument.strike"), /* @__PURE__ */ i(lt, { size: 15, "aria-hidden": !0 }), o.isActive("strike"), () => o.chain().focus().toggleStrike().run()),
350
+ g(c("richDocument.code"), /* @__PURE__ */ i(dt, { size: 15, "aria-hidden": !0 }), o.isActive("code"), () => o.chain().focus().toggleCode().run()),
351
+ g(c("richDocument.link"), /* @__PURE__ */ i(ut, { size: 15, "aria-hidden": !0 }), o.isActive("link"), je),
352
+ /* @__PURE__ */ i(j, {}),
353
+ g(c("richDocument.bulletList"), /* @__PURE__ */ i(Ze, { size: 15, "aria-hidden": !0 }), o.isActive("bulletList"), () => o.chain().focus().toggleBulletList().run()),
354
+ g(c("richDocument.orderedList"), /* @__PURE__ */ i(et, { size: 15, "aria-hidden": !0 }), o.isActive("orderedList"), () => o.chain().focus().toggleOrderedList().run()),
355
+ g(c("richDocument.taskList"), /* @__PURE__ */ i(tt, { size: 15, "aria-hidden": !0 }), o.isActive("taskList"), () => o.chain().focus().toggleTaskList().run()),
356
+ g(c("richDocument.quote"), /* @__PURE__ */ i(nt, { size: 15, "aria-hidden": !0 }), o.isActive("blockquote"), () => o.chain().focus().toggleBlockquote().run()),
357
+ g(c("richDocument.codeBlock"), /* @__PURE__ */ i(st, { size: 15, "aria-hidden": !0 }), o.isActive("codeBlock"), () => o.chain().focus().toggleCodeBlock().run()),
358
+ g(c("richDocument.rule"), /* @__PURE__ */ i(In, { size: 15, "aria-hidden": !0 }), !1, () => o.chain().focus().setHorizontalRule().run()),
359
+ g(c("richDocument.callout"), /* @__PURE__ */ i(rt, { size: 15, "aria-hidden": !0 }), o.isActive("callout"), () => o.chain().focus().wrapIn("callout").run()),
360
+ g(c("richDocument.table"), /* @__PURE__ */ i(Ce, { size: 15, "aria-hidden": !0 }), o.isActive("table"), () => o.chain().focus().insertTable({ rows: 3, cols: 3, withHeaderRow: !0 }).run()),
361
+ z && g(c("richDocument.image"), /* @__PURE__ */ i(pt, { size: 15, "aria-hidden": !0 }), !1, () => {
362
+ var a;
363
+ return (a = ye.current) == null ? void 0 : a.click();
354
364
  })
355
365
  ] }),
356
- z && /* @__PURE__ */ t(we, { ref: Z, type: "file", accept: "image/png,image/jpeg,image/webp,image/gif", className: "sr-only", tabIndex: -1, onChange: (r) => {
357
- var s;
358
- const a = (s = r.target.files) == null ? void 0 : s[0];
359
- a && ee(a), r.currentTarget.value = "";
366
+ z && /* @__PURE__ */ i(Ue, { ref: ye, type: "file", accept: "image/png,image/jpeg,image/webp,image/gif", className: "sr-only", tabIndex: -1, onChange: (a) => {
367
+ var m;
368
+ const u = (m = a.target.files) == null ? void 0 : m[0];
369
+ u && Se(u), a.currentTarget.value = "";
360
370
  } }),
361
- i && e && /* @__PURE__ */ t(At, { editor: e, options: { placement: "left-start" }, className: "z-40", children: /* @__PURE__ */ p("div", { className: "relative flex items-start gap-1", children: [
362
- /* @__PURE__ */ t(le, { label: n("richDocument.insertBlock"), children: /* @__PURE__ */ t(v, { type: "button", "aria-label": n("richDocument.insertBlock"), "aria-expanded": de, onMouseDown: (r) => r.preventDefault(), onClick: () => G((r) => !r), className: "grid size-8 place-items-center rounded-control border border-border bg-pure-white text-graphite shadow-soft hover:-translate-y-px hover:bg-surface-hover hover:text-ink", children: /* @__PURE__ */ t(Tt, { size: 16, "aria-hidden": !0 }) }) }),
363
- g && /* @__PURE__ */ t(le, { label: n("richDocument.aiContinue"), children: /* @__PURE__ */ t(v, { type: "button", "aria-label": n("richDocument.aiContinue"), onMouseDown: (r) => r.preventDefault(), onClick: () => te("continue"), className: "grid size-8 place-items-center rounded-control border border-border bg-pure-white text-rust shadow-soft hover:-translate-y-px hover:bg-surface-hover", children: /* @__PURE__ */ t(je, { size: 15, "aria-hidden": !0 }) }) }),
364
- de && /* @__PURE__ */ p(J, { label: n("richDocument.insertBlock"), className: "absolute left-10 top-0 grid w-52 gap-1 rounded-panel border border-border bg-surface-raised p-1 shadow-pop", children: [
365
- be.map(([r, a, s]) => /* @__PURE__ */ t(S, { asChild: !0, children: /* @__PURE__ */ p(v, { type: "button", onMouseDown: (u) => u.preventDefault(), onClick: () => ct(s), className: "flex min-h-10 items-center gap-2 rounded-control px-3 text-left font-sohne text-body-sm text-ink hover:bg-surface-hover", children: [
366
- a,
367
- /* @__PURE__ */ t("span", { children: r })
368
- ] }) }, r)),
369
- z && /* @__PURE__ */ t(S, { asChild: !0, children: /* @__PURE__ */ p(v, { type: "button", onMouseDown: (r) => r.preventDefault(), onClick: () => {
370
- var r;
371
- G(!1), (r = Z.current) == null || r.click();
371
+ e && o && /* @__PURE__ */ i(yn, { editor: o, options: { placement: "left-start" }, className: "z-40", children: /* @__PURE__ */ h("div", { className: "relative flex items-start gap-1", children: [
372
+ /* @__PURE__ */ i(Te, { label: c("richDocument.insertBlock"), children: /* @__PURE__ */ i(A, { type: "button", "aria-label": c("richDocument.insertBlock"), "aria-expanded": _e, onMouseDown: (a) => a.preventDefault(), onClick: () => ge((a) => !a), className: "grid size-8 place-items-center rounded-control border border-border bg-pure-white text-graphite shadow-soft hover:-translate-y-px hover:bg-surface-hover hover:text-ink", children: /* @__PURE__ */ i(Cn, { size: 16, "aria-hidden": !0 }) }) }),
373
+ S && /* @__PURE__ */ i(Te, { label: c("richDocument.aiContinue"), children: /* @__PURE__ */ i(A, { type: "button", "aria-label": c("richDocument.aiContinue"), onMouseDown: (a) => a.preventDefault(), onClick: () => ke("continue"), className: "grid size-8 place-items-center rounded-control border border-border bg-pure-white text-rust shadow-soft hover:-translate-y-px hover:bg-surface-hover", children: /* @__PURE__ */ i(ht, { size: 15, "aria-hidden": !0 }) }) }),
374
+ _e && /* @__PURE__ */ h(oe, { label: c("richDocument.insertBlock"), className: "absolute left-10 top-0 grid w-52 gap-1 rounded-panel border border-border bg-surface-raised p-1 shadow-pop", children: [
375
+ $e.map(([a, u, m]) => /* @__PURE__ */ i(P, { asChild: !0, children: /* @__PURE__ */ h(A, { type: "button", onMouseDown: (v) => v.preventDefault(), onClick: () => Wt(m), className: "flex min-h-10 items-center gap-2 rounded-control px-3 text-left font-sohne text-body-sm text-ink hover:bg-surface-hover", children: [
376
+ u,
377
+ /* @__PURE__ */ i("span", { children: a })
378
+ ] }) }, a)),
379
+ z && /* @__PURE__ */ i(P, { asChild: !0, children: /* @__PURE__ */ h(A, { type: "button", onMouseDown: (a) => a.preventDefault(), onClick: () => {
380
+ var a;
381
+ ge(!1), (a = ye.current) == null || a.click();
372
382
  }, className: "flex min-h-10 items-center gap-2 rounded-control px-3 text-left font-sohne text-body-sm text-ink hover:bg-surface-hover", children: [
373
- /* @__PURE__ */ t(qe, { size: 15, "aria-hidden": !0 }),
374
- /* @__PURE__ */ t("span", { children: n("richDocument.image") })
383
+ /* @__PURE__ */ i(pt, { size: 15, "aria-hidden": !0 }),
384
+ /* @__PURE__ */ i("span", { children: c("richDocument.image") })
375
385
  ] }) })
376
386
  ] })
377
387
  ] }) }),
378
- i && e && /* @__PURE__ */ t(xe, { editor: e, pluginKey: "richTextSelectionMenu", shouldShow: ({ editor: r, from: a, to: s }) => a !== s && !(r.state.selection instanceof se), options: { placement: "top" }, className: "z-40 shadow-pop", children: /* @__PURE__ */ p("div", { className: "relative", children: [
379
- /* @__PURE__ */ p(re, { label: n("richDocument.formatSelection"), density: "compact", className: "max-w-[calc(100vw-2rem)] overflow-x-auto bg-surface-raised", children: [
380
- ge("block", n("richDocument.paragraphStyle"), /* @__PURE__ */ p(De, { children: [
381
- /* @__PURE__ */ t(Be, { size: 15, "aria-hidden": !0 }),
382
- /* @__PURE__ */ t(Bt, { size: 11, "aria-hidden": !0 })
388
+ e && o && /* @__PURE__ */ i(Xe, { editor: o, pluginKey: "richTextSelectionMenu", shouldShow: ({ editor: a, from: u, to: m }) => u !== m && !(a.state.selection instanceof Re), options: { placement: "top" }, className: "z-40 shadow-pop", children: /* @__PURE__ */ h("div", { className: "relative", children: [
389
+ /* @__PURE__ */ h(De, { label: c("richDocument.formatSelection"), density: "compact", className: "max-w-[calc(100vw-2rem)] overflow-x-auto bg-surface-raised", children: [
390
+ Ve("block", c("richDocument.paragraphStyle"), /* @__PURE__ */ h(Ke, { children: [
391
+ /* @__PURE__ */ i(it, { size: 15, "aria-hidden": !0 }),
392
+ /* @__PURE__ */ i(An, { size: 11, "aria-hidden": !0 })
383
393
  ] })),
384
- ge("align", n("richDocument.alignment"), /* @__PURE__ */ t(Je, { size: 15, "aria-hidden": !0 })),
385
- /* @__PURE__ */ t(M, {}),
386
- l(n("richDocument.bold"), /* @__PURE__ */ t(Oe, { size: 15, "aria-hidden": !0 }), e.isActive("bold"), () => e.chain().focus().toggleBold().run()),
387
- l(n("richDocument.italic"), /* @__PURE__ */ t(Ee, { size: 15, "aria-hidden": !0 }), e.isActive("italic"), () => e.chain().focus().toggleItalic().run()),
388
- l(n("richDocument.underline"), /* @__PURE__ */ t(He, { size: 15, "aria-hidden": !0 }), e.isActive("underline"), () => e.chain().focus().toggleUnderline().run()),
389
- l(n("richDocument.strike"), /* @__PURE__ */ t(Ie, { size: 15, "aria-hidden": !0 }), e.isActive("strike"), () => e.chain().focus().toggleStrike().run()),
390
- l(n("richDocument.code"), /* @__PURE__ */ t(Pe, { size: 15, "aria-hidden": !0 }), e.isActive("code"), () => e.chain().focus().toggleCode().run()),
391
- /* @__PURE__ */ p(Ce, { title: n("richDocument.colors"), open: O === "color", onOpenChange: (r) => T(r ? "color" : null), side: "bottom", align: "end", trigger: /* @__PURE__ */ t(F, { title: n("richDocument.colors"), "aria-label": n("richDocument.colors"), "aria-expanded": O === "color", onMouseDown: (r) => r.preventDefault(), children: /* @__PURE__ */ t($e, { size: 15, "aria-hidden": !0 }) }), children: [
392
- /* @__PURE__ */ t(ce, { label: n("richDocument.textColor"), values: tr, onChoose: (r) => {
393
- e.chain().focus().setColor(r).run(), T(null);
394
+ Ve("align", c("richDocument.alignment"), /* @__PURE__ */ i(mt, { size: 15, "aria-hidden": !0 })),
395
+ /* @__PURE__ */ i(j, {}),
396
+ g(c("richDocument.bold"), /* @__PURE__ */ i(ot, { size: 15, "aria-hidden": !0 }), o.isActive("bold"), () => o.chain().focus().toggleBold().run()),
397
+ g(c("richDocument.italic"), /* @__PURE__ */ i(at, { size: 15, "aria-hidden": !0 }), o.isActive("italic"), () => o.chain().focus().toggleItalic().run()),
398
+ g(c("richDocument.underline"), /* @__PURE__ */ i(ct, { size: 15, "aria-hidden": !0 }), o.isActive("underline"), () => o.chain().focus().toggleUnderline().run()),
399
+ g(c("richDocument.strike"), /* @__PURE__ */ i(lt, { size: 15, "aria-hidden": !0 }), o.isActive("strike"), () => o.chain().focus().toggleStrike().run()),
400
+ g(c("richDocument.code"), /* @__PURE__ */ i(dt, { size: 15, "aria-hidden": !0 }), o.isActive("code"), () => o.chain().focus().toggleCode().run()),
401
+ /* @__PURE__ */ h(We, { title: c("richDocument.colors"), open: J === "color", onOpenChange: (a) => O(a ? "color" : null), side: "bottom", align: "end", trigger: /* @__PURE__ */ i(ae, { title: c("richDocument.colors"), "aria-label": c("richDocument.colors"), "aria-expanded": J === "color", onMouseDown: (a) => a.preventDefault(), children: /* @__PURE__ */ i(ft, { size: 15, "aria-hidden": !0 }) }), children: [
402
+ /* @__PURE__ */ i(Ie, { label: c("richDocument.textColor"), values: es, onChoose: (a) => {
403
+ o.chain().focus().setColor(a).run(), O(null);
394
404
  } }),
395
- /* @__PURE__ */ t(ce, { label: n("richDocument.backgroundColor"), values: K, onChoose: (r) => {
396
- e.chain().focus().setBackgroundColor(r).run(), T(null);
405
+ /* @__PURE__ */ i(Ie, { label: c("richDocument.backgroundColor"), values: de, onChoose: (a) => {
406
+ o.chain().focus().setBackgroundColor(a).run(), O(null);
397
407
  } }),
398
- /* @__PURE__ */ t(v, { type: "button", onMouseDown: (r) => r.preventDefault(), onClick: () => {
399
- e.chain().focus().unsetColor().unsetBackgroundColor().run(), T(null);
400
- }, className: "mt-2 min-h-9 w-full rounded-control text-caption text-graphite hover:bg-surface-hover hover:text-ink", children: n("richDocument.resetColors") })
408
+ /* @__PURE__ */ i(A, { type: "button", onMouseDown: (a) => a.preventDefault(), onClick: () => {
409
+ o.chain().focus().unsetColor().unsetBackgroundColor().run(), O(null);
410
+ }, className: "mt-2 min-h-9 w-full rounded-control text-caption text-graphite hover:bg-surface-hover hover:text-ink", children: c("richDocument.resetColors") })
401
411
  ] }),
402
- l(n("richDocument.link"), /* @__PURE__ */ t(_e, { size: 15, "aria-hidden": !0 }), e.isActive("link"), pe),
403
- g && /* @__PURE__ */ p(De, { children: [
404
- /* @__PURE__ */ t(M, {}),
405
- l(n("richDocument.aiExplain"), /* @__PURE__ */ t(je, { size: 15, "aria-hidden": !0 }), !1, () => te("explain")),
406
- l(n("richDocument.aiRewrite"), /* @__PURE__ */ t(Ot, { size: 15, "aria-hidden": !0 }), !1, () => te("rewrite"))
412
+ g(c("richDocument.link"), /* @__PURE__ */ i(ut, { size: 15, "aria-hidden": !0 }), o.isActive("link"), je),
413
+ S && /* @__PURE__ */ h(Ke, { children: [
414
+ /* @__PURE__ */ i(j, {}),
415
+ g(c("richDocument.aiExplain"), /* @__PURE__ */ i(ht, { size: 15, "aria-hidden": !0 }), !1, () => ke("explain")),
416
+ g(c("richDocument.aiRewrite"), /* @__PURE__ */ i(En, { size: 15, "aria-hidden": !0 }), !1, () => ke("rewrite"))
407
417
  ] })
408
418
  ] }),
409
- O === "block" && /* @__PURE__ */ t(J, { label: n("richDocument.paragraphStyle"), className: "af-layer-overlay absolute left-0 top-full mt-1 grid w-48 gap-1 rounded-panel border border-border bg-surface-raised p-1 shadow-pop", children: st.map(([r, a, s]) => /* @__PURE__ */ t(S, { asChild: !0, children: /* @__PURE__ */ p(v, { type: "button", onMouseDown: (u) => u.preventDefault(), onClick: () => {
410
- s(), T(null);
419
+ J === "block" && /* @__PURE__ */ i(oe, { label: c("richDocument.paragraphStyle"), className: "af-layer-overlay absolute left-0 top-full mt-1 grid w-48 gap-1 rounded-panel border border-border bg-surface-raised p-1 shadow-pop", children: Yt.map(([a, u, m]) => /* @__PURE__ */ i(P, { asChild: !0, children: /* @__PURE__ */ h(A, { type: "button", onMouseDown: (v) => v.preventDefault(), onClick: () => {
420
+ m(), O(null);
411
421
  }, className: "flex min-h-10 items-center gap-2 rounded-control px-3 text-left font-sohne text-body-sm text-ink hover:bg-surface-hover", children: [
412
- a,
413
- /* @__PURE__ */ t("span", { children: r })
414
- ] }) }, r)) }),
415
- O === "align" && /* @__PURE__ */ t(J, { label: n("richDocument.alignment"), className: "af-layer-overlay absolute left-9 top-full mt-1 grid w-40 gap-1 rounded-panel border border-border bg-surface-raised p-1 shadow-pop", children: [["left", n("richDocument.alignLeft"), /* @__PURE__ */ t(Je, { size: 15, "aria-hidden": !0 }, "left")], ["center", n("richDocument.alignCenter"), /* @__PURE__ */ t(Rt, { size: 15, "aria-hidden": !0 }, "center")], ["right", n("richDocument.alignRight"), /* @__PURE__ */ t(Lt, { size: 15, "aria-hidden": !0 }, "right")]].map(([r, a, s]) => /* @__PURE__ */ t(S, { asChild: !0, children: /* @__PURE__ */ p(v, { type: "button", onMouseDown: (u) => u.preventDefault(), onClick: () => {
416
- e.chain().focus().setTextAlign(String(r)).run(), T(null);
422
+ u,
423
+ /* @__PURE__ */ i("span", { children: a })
424
+ ] }) }, a)) }),
425
+ J === "align" && /* @__PURE__ */ i(oe, { label: c("richDocument.alignment"), className: "af-layer-overlay absolute left-9 top-full mt-1 grid w-40 gap-1 rounded-panel border border-border bg-surface-raised p-1 shadow-pop", children: [["left", c("richDocument.alignLeft"), /* @__PURE__ */ i(mt, { size: 15, "aria-hidden": !0 }, "left")], ["center", c("richDocument.alignCenter"), /* @__PURE__ */ i(xn, { size: 15, "aria-hidden": !0 }, "center")], ["right", c("richDocument.alignRight"), /* @__PURE__ */ i(Nn, { size: 15, "aria-hidden": !0 }, "right")]].map(([a, u, m]) => /* @__PURE__ */ i(P, { asChild: !0, children: /* @__PURE__ */ h(A, { type: "button", onMouseDown: (v) => v.preventDefault(), onClick: () => {
426
+ o.chain().focus().setTextAlign(String(a)).run(), O(null);
417
427
  }, className: "flex min-h-10 items-center gap-2 rounded-control px-3 text-left font-sohne text-body-sm text-ink hover:bg-surface-hover", children: [
418
- s,
419
- /* @__PURE__ */ t("span", { children: a })
420
- ] }) }, String(r))) })
428
+ m,
429
+ /* @__PURE__ */ i("span", { children: u })
430
+ ] }) }, String(a))) })
421
431
  ] }) }),
422
- i && e && /* @__PURE__ */ t(xe, { editor: e, pluginKey: "richTableMenu", shouldShow: ({ editor: r, from: a, to: s }) => (a === s || r.state.selection instanceof se) && or(r), options: { placement: "top" }, className: "z-40 shadow-pop", children: /* @__PURE__ */ t("div", { className: "relative", children: /* @__PURE__ */ p(re, { label: n("richDocument.tableActions"), density: "compact", className: "max-w-[calc(100vw-2rem)] overflow-x-auto bg-surface-raised", children: [
423
- l(n("richDocument.addRowBefore"), /* @__PURE__ */ t(Et, { size: 15, "aria-hidden": !0 }), !1, () => e.chain().focus().addRowBefore().run()),
424
- l(n("richDocument.addRowAfter"), /* @__PURE__ */ t(Ht, { size: 15, "aria-hidden": !0 }), !1, () => e.chain().focus().addRowAfter().run()),
425
- l(n("richDocument.deleteRow"), /* @__PURE__ */ t(It, { size: 15, "aria-hidden": !0 }), !1, () => e.chain().focus().deleteRow().run()),
426
- /* @__PURE__ */ t(M, {}),
427
- l(n("richDocument.addColumnBefore"), /* @__PURE__ */ t(Pt, { size: 15, "aria-hidden": !0 }), !1, () => e.chain().focus().addColumnBefore().run()),
428
- l(n("richDocument.addColumnAfter"), /* @__PURE__ */ t(_t, { size: 15, "aria-hidden": !0 }), !1, () => e.chain().focus().addColumnAfter().run()),
429
- l(n("richDocument.deleteColumn"), /* @__PURE__ */ t(jt, { size: 15, "aria-hidden": !0 }), !1, () => e.chain().focus().deleteColumn().run()),
430
- /* @__PURE__ */ t(M, {}),
431
- l(n("richDocument.mergeCells"), /* @__PURE__ */ t(qt, { size: 15, "aria-hidden": !0 }), !1, () => e.chain().focus().mergeCells().run()),
432
- l(n("richDocument.splitCell"), /* @__PURE__ */ t($t, { size: 15, "aria-hidden": !0 }), !1, () => e.chain().focus().splitCell().run()),
433
- /* @__PURE__ */ p(Ce, { title: n("richDocument.cellBackgroundColor"), open: he, onOpenChange: Y, side: "bottom", align: "end", trigger: /* @__PURE__ */ t(F, { title: n("richDocument.cellBackgroundColor"), "aria-label": n("richDocument.cellBackgroundColor"), "aria-expanded": he, onMouseDown: (r) => r.preventDefault(), children: /* @__PURE__ */ t($e, { size: 15, "aria-hidden": !0 }) }), children: [
434
- /* @__PURE__ */ t(ce, { label: n("richDocument.cellBackgroundColor"), values: K, onChoose: (r) => {
435
- e.chain().focus().setCellAttribute("backgroundColor", r).run(), Y(!1);
432
+ e && o && /* @__PURE__ */ i(Xe, { editor: o, pluginKey: "richTableMenu", shouldShow: ({ editor: a, from: u, to: m }) => (u === m || a.state.selection instanceof Re) && rs(a), options: { placement: "top" }, className: "z-40 shadow-pop", children: /* @__PURE__ */ i("div", { className: "relative", children: /* @__PURE__ */ h(De, { label: c("richDocument.tableActions"), density: "compact", className: "max-w-[calc(100vw-2rem)] overflow-x-auto bg-surface-raised", children: [
433
+ g(c("richDocument.addRowBefore"), /* @__PURE__ */ i(zn, { size: 15, "aria-hidden": !0 }), !1, () => o.chain().focus().addRowBefore().run()),
434
+ g(c("richDocument.addRowAfter"), /* @__PURE__ */ i(Rn, { size: 15, "aria-hidden": !0 }), !1, () => o.chain().focus().addRowAfter().run()),
435
+ g(c("richDocument.deleteRow"), /* @__PURE__ */ i(Un, { size: 15, "aria-hidden": !0 }), !1, () => o.chain().focus().deleteRow().run()),
436
+ /* @__PURE__ */ i(j, {}),
437
+ g(c("richDocument.addColumnBefore"), /* @__PURE__ */ i(Tn, { size: 15, "aria-hidden": !0 }), !1, () => o.chain().focus().addColumnBefore().run()),
438
+ g(c("richDocument.addColumnAfter"), /* @__PURE__ */ i(Ln, { size: 15, "aria-hidden": !0 }), !1, () => o.chain().focus().addColumnAfter().run()),
439
+ g(c("richDocument.deleteColumn"), /* @__PURE__ */ i(Pn, { size: 15, "aria-hidden": !0 }), !1, () => o.chain().focus().deleteColumn().run()),
440
+ /* @__PURE__ */ i(j, {}),
441
+ g(c("richDocument.mergeCells"), /* @__PURE__ */ i(Mn, { size: 15, "aria-hidden": !0 }), !1, () => o.chain().focus().mergeCells().run()),
442
+ g(c("richDocument.splitCell"), /* @__PURE__ */ i(On, { size: 15, "aria-hidden": !0 }), !1, () => o.chain().focus().splitCell().run()),
443
+ /* @__PURE__ */ h(We, { title: c("richDocument.cellBackgroundColor"), open: qe, onOpenChange: ve, side: "bottom", align: "end", trigger: /* @__PURE__ */ i(ae, { title: c("richDocument.cellBackgroundColor"), "aria-label": c("richDocument.cellBackgroundColor"), "aria-expanded": qe, onMouseDown: (a) => a.preventDefault(), children: /* @__PURE__ */ i(ft, { size: 15, "aria-hidden": !0 }) }), children: [
444
+ /* @__PURE__ */ i(Ie, { label: c("richDocument.cellBackgroundColor"), values: de, onChoose: (a) => {
445
+ o.chain().focus().setCellAttribute("backgroundColor", a).run(), ve(!1);
436
446
  } }),
437
- /* @__PURE__ */ t(v, { type: "button", onMouseDown: (r) => r.preventDefault(), onClick: () => {
438
- e.chain().focus().setCellAttribute("backgroundColor", null).run(), Y(!1);
439
- }, className: "mt-2 min-h-9 w-full rounded-control text-caption text-graphite hover:bg-surface-hover hover:text-ink", children: n("richDocument.resetCellBackground") })
447
+ /* @__PURE__ */ i(A, { type: "button", onMouseDown: (a) => a.preventDefault(), onClick: () => {
448
+ o.chain().focus().setCellAttribute("backgroundColor", null).run(), ve(!1);
449
+ }, className: "mt-2 min-h-9 w-full rounded-control text-caption text-graphite hover:bg-surface-hover hover:text-ink", children: c("richDocument.resetCellBackground") })
440
450
  ] }),
441
- l(n("richDocument.toggleHeaderRow"), /* @__PURE__ */ t(oe, { size: 15, "aria-hidden": !0 }), !1, () => e.chain().focus().toggleHeaderRow().run()),
442
- l(n("richDocument.deleteTable"), /* @__PURE__ */ t(Jt, { size: 15, "aria-hidden": !0 }), !1, () => e.chain().focus().deleteTable().run())
451
+ g(c("richDocument.toggleHeaderRow"), /* @__PURE__ */ i(Ce, { size: 15, "aria-hidden": !0 }), !1, () => o.chain().focus().toggleHeaderRow().run()),
452
+ g(c("richDocument.deleteTable"), /* @__PURE__ */ i(Nt, { size: 15, "aria-hidden": !0 }), !1, () => o.chain().focus().deleteTable().run())
443
453
  ] }) }) }),
444
- /* @__PURE__ */ t(zt, { editor: e }),
445
- g && !m.operation && j && /* @__PURE__ */ t("div", { role: "alert", className: "m-4 text-caption text-danger", children: j }),
446
- g && m.operation && /* @__PURE__ */ p("aside", { "data-testid": "document-assistant-operation", "data-run-id": m.runId, "data-status": m.status, "data-document-id": m.operation.documentId, "data-node-id": m.operation.nodeId, "data-base-revision": m.operation.baseRevision, "data-error-code": tt, className: "m-4 space-y-3 rounded-panel border border-border bg-surface-muted p-4", "aria-live": "polite", children: [
447
- /* @__PURE__ */ p("div", { className: "flex flex-wrap items-center justify-between gap-2", children: [
448
- /* @__PURE__ */ t("strong", { className: "font-sohne text-body-sm text-ink", children: n(`richDocument.ai.${m.operation.operation}`) }),
449
- /* @__PURE__ */ t("span", { className: "text-caption text-graphite", children: m.status })
454
+ /* @__PURE__ */ i(wn, { editor: o }),
455
+ S && !k.operation && se && /* @__PURE__ */ i("div", { role: "alert", className: "m-4 text-caption text-danger", children: se }),
456
+ S && k.operation && /* @__PURE__ */ h("aside", { "data-testid": "document-assistant-operation", "data-run-id": k.runId, "data-status": k.status, "data-document-id": k.operation.documentId, "data-node-id": k.operation.nodeId, "data-base-revision": k.operation.baseRevision, "data-error-code": Vt, className: "m-4 space-y-3 rounded-panel border border-border bg-surface-muted p-4", "aria-live": "polite", children: [
457
+ /* @__PURE__ */ h("div", { className: "flex flex-wrap items-center justify-between gap-2", children: [
458
+ /* @__PURE__ */ i("strong", { className: "font-sohne text-body-sm text-ink", children: c(`richDocument.ai.${k.operation.operation}`) }),
459
+ /* @__PURE__ */ i("span", { className: "text-caption text-graphite", children: k.status })
450
460
  ] }),
451
- m.output && /* @__PURE__ */ t("div", { "data-testid": "document-assistant-output", className: "whitespace-pre-wrap text-body-sm text-ink", children: m.output }),
452
- /* @__PURE__ */ p("div", { className: "flex flex-wrap gap-2", children: [
453
- m.status === "waiting_for_input" && /* @__PURE__ */ t(ne, { size: "compact", onClick: () => void g.resolvePending().catch((r) => w(r instanceof Error ? r.message : String(r))), children: n("richDocument.aiResume") }),
454
- m.status === "completed" && m.operation.operation !== "explain" && m.output && !E && /* @__PURE__ */ t(ne, { size: "compact", disabled: fe, onClick: () => void it(), children: n("richDocument.aiApply") }),
455
- E && /* @__PURE__ */ t(ne, { size: "compact", variant: "secondary", disabled: fe, onClick: () => void at(), children: n("richDocument.aiRollback") })
461
+ k.output && /* @__PURE__ */ i("div", { "data-testid": "document-assistant-output", className: "whitespace-pre-wrap text-body-sm text-ink", children: k.output }),
462
+ /* @__PURE__ */ h("div", { className: "flex flex-wrap gap-2", children: [
463
+ k.status === "waiting_for_input" && /* @__PURE__ */ i(U, { size: "compact", onClick: () => void S.resolvePending().catch((a) => R(a instanceof Error ? a.message : String(a))), children: c("richDocument.aiResume") }),
464
+ k.status === "completed" && k.operation.operation !== "explain" && k.output && !K && /* @__PURE__ */ i(U, { size: "compact", disabled: He, onClick: () => void Kt(), children: c("richDocument.aiApply") }),
465
+ K && /* @__PURE__ */ i(U, { size: "compact", variant: "secondary", disabled: He, onClick: () => void Xt(), children: c("richDocument.aiRollback") })
456
466
  ] }),
457
- (j || m.error) && /* @__PURE__ */ t("div", { role: "alert", className: "text-caption text-danger", children: j || ((ve = m.error) == null ? void 0 : ve.message) })
467
+ (se || k.error) && /* @__PURE__ */ i("div", { role: "alert", className: "text-caption text-danger", children: se || ((Fe = k.error) == null ? void 0 : Fe.message) })
458
468
  ] }),
459
- i && Ze && e && /* @__PURE__ */ p(J, { label: n("richDocument.slashCommands"), className: "absolute left-0 top-12 z-30 grid min-w-44 gap-1 rounded-panel border border-border bg-surface-raised p-1 shadow-pop", children: [
460
- /* @__PURE__ */ t(S, { asChild: !0, children: /* @__PURE__ */ t(v, { className: "h-row-default rounded-control px-3 text-left font-sohne text-body-sm text-ink hover:bg-surface-hover", onClick: () => $(() => e.chain().deleteRange({ from: e.state.selection.from - 1, to: e.state.selection.from }).toggleHeading({ level: 2 }).run()), children: n("richDocument.heading") }) }),
461
- /* @__PURE__ */ t(S, { asChild: !0, children: /* @__PURE__ */ t(v, { className: "h-row-default rounded-control px-3 text-left font-sohne text-body-sm text-ink hover:bg-surface-hover", onClick: () => $(() => e.chain().deleteRange({ from: e.state.selection.from - 1, to: e.state.selection.from }).toggleTaskList().run()), children: n("richDocument.taskList") }) }),
462
- /* @__PURE__ */ t(S, { asChild: !0, children: /* @__PURE__ */ t(v, { className: "h-row-default rounded-control px-3 text-left font-sohne text-body-sm text-ink hover:bg-surface-hover", onClick: () => $(() => e.chain().deleteRange({ from: e.state.selection.from - 1, to: e.state.selection.from }).wrapIn("callout").run()), children: n("richDocument.callout") }) }),
463
- /* @__PURE__ */ t(S, { asChild: !0, children: /* @__PURE__ */ t(v, { className: "h-row-default rounded-control px-3 text-left font-sohne text-body-sm text-ink hover:bg-surface-hover", onClick: () => $(() => e.chain().deleteRange({ from: e.state.selection.from - 1, to: e.state.selection.from }).insertTable({ rows: 3, cols: 3, withHeaderRow: !0 }).run()), children: n("richDocument.table") }) })
469
+ e && Ht && o && /* @__PURE__ */ h(oe, { label: c("richDocument.slashCommands"), className: "absolute left-0 top-12 z-30 grid min-w-44 gap-1 rounded-panel border border-border bg-surface-raised p-1 shadow-pop", children: [
470
+ /* @__PURE__ */ i(P, { asChild: !0, children: /* @__PURE__ */ i(A, { className: "h-row-default rounded-control px-3 text-left font-sohne text-body-sm text-ink hover:bg-surface-hover", onClick: () => ie(() => o.chain().deleteRange({ from: o.state.selection.from - 1, to: o.state.selection.from }).toggleHeading({ level: 2 }).run()), children: c("richDocument.heading") }) }),
471
+ /* @__PURE__ */ i(P, { asChild: !0, children: /* @__PURE__ */ i(A, { className: "h-row-default rounded-control px-3 text-left font-sohne text-body-sm text-ink hover:bg-surface-hover", onClick: () => ie(() => o.chain().deleteRange({ from: o.state.selection.from - 1, to: o.state.selection.from }).toggleTaskList().run()), children: c("richDocument.taskList") }) }),
472
+ /* @__PURE__ */ i(P, { asChild: !0, children: /* @__PURE__ */ i(A, { className: "h-row-default rounded-control px-3 text-left font-sohne text-body-sm text-ink hover:bg-surface-hover", onClick: () => ie(() => o.chain().deleteRange({ from: o.state.selection.from - 1, to: o.state.selection.from }).wrapIn("callout").run()), children: c("richDocument.callout") }) }),
473
+ /* @__PURE__ */ i(P, { asChild: !0, children: /* @__PURE__ */ i(A, { className: "h-row-default rounded-control px-3 text-left font-sohne text-body-sm text-ink hover:bg-surface-hover", onClick: () => ie(() => o.chain().deleteRange({ from: o.state.selection.from - 1, to: o.state.selection.from }).insertTable({ rows: 3, cols: 3, withHeaderRow: !0 }).run()), children: c("richDocument.table") }) })
464
474
  ] }),
465
- /* @__PURE__ */ t(Nt, { open: et, onClose: () => _(!1), title: k, closeLabel: n("common.close"), children: /* @__PURE__ */ p("div", { className: "space-y-4", children: [
466
- /* @__PURE__ */ t(we, { autoFocus: !0, type: "url", "aria-label": k, value: me, onChange: (r) => Q(r.target.value), placeholder: "https://" }),
467
- /* @__PURE__ */ t("div", { className: "flex justify-end", children: /* @__PURE__ */ t(v, { type: "button", onClick: ot, className: "min-h-11 rounded-full bg-ink px-5 font-sohne text-caption text-pure-white", children: D }) })
475
+ /* @__PURE__ */ i(kn, { open: jt, onClose: () => ne(!1), title: r, closeLabel: c("common.close"), children: /* @__PURE__ */ h("div", { className: "space-y-4", children: [
476
+ /* @__PURE__ */ i(Ue, { autoFocus: !0, type: "url", "aria-label": r, value: Be, onChange: (a) => be(a.target.value), placeholder: "https://" }),
477
+ /* @__PURE__ */ i("div", { className: "flex justify-end", children: /* @__PURE__ */ i(A, { type: "button", onClick: Jt, className: "min-h-11 rounded-full bg-ink px-5 font-sohne text-caption text-pure-white", children: l }) })
468
478
  ] }) })
469
479
  ] });
470
480
  }
471
- const cr = (o) => /(^|\n)(#{1,3} |[-*+] |\d+\. |> |```|---(?:\n|$)|- \[[ xX]\] )|\|.+\|\n\|(?:\s*:?-+:?\s*\|)+|\*\*[^*]+\*\*|~~[^~]+~~|`[^`]+`|\[[^\]]+\]\(https?:\/\/[^)]+\)/m.test(o);
472
- function ce({ label: o, values: i, onChoose: c }) {
473
- return /* @__PURE__ */ p("fieldset", { className: "mb-2", children: [
474
- /* @__PURE__ */ t("legend", { className: "mb-1 font-sohne text-caption text-graphite", children: o }),
475
- /* @__PURE__ */ t("div", { className: "flex flex-wrap gap-1", children: i.map((h, k) => {
476
- const D = `${o} ${k + 1}`;
477
- return /* @__PURE__ */ t(le, { label: D, children: /* @__PURE__ */ t(v, { type: "button", "aria-label": D, onMouseDown: (C) => C.preventDefault(), onClick: () => c(h), className: "size-8 rounded-control border border-border transition-transform hover:-translate-y-px hover:ring-2 hover:ring-rust/35", style: { backgroundColor: h } }) }, h);
481
+ const as = (n) => /(^|\n)(#{1,3} |[-*+] |\d+\. |> |```|---(?:\n|$)|- \[[ xX]\] )|\|.+\|\n\|(?:\s*:?-+:?\s*\|)+|\*\*[^*]+\*\*|~~[^~]+~~|`[^`]+`|\[[^\]]+\]\(https?:\/\/[^)]+\)/m.test(n);
482
+ function Ie({ label: n, values: e, onChoose: t }) {
483
+ return /* @__PURE__ */ h("fieldset", { className: "mb-2", children: [
484
+ /* @__PURE__ */ i("legend", { className: "mb-1 font-sohne text-caption text-graphite", children: n }),
485
+ /* @__PURE__ */ i("div", { className: "flex flex-wrap gap-1", children: e.map((s, r) => {
486
+ const l = `${n} ${r + 1}`;
487
+ return /* @__PURE__ */ i(Te, { label: l, children: /* @__PURE__ */ i(A, { type: "button", "aria-label": l, onMouseDown: (d) => d.preventDefault(), onClick: () => t(s), className: "size-8 rounded-control border border-border transition-transform hover:-translate-y-px hover:ring-2 hover:ring-rust/35", style: { backgroundColor: s } }) }, s);
478
488
  }) })
479
489
  ] });
480
490
  }
491
+ const bt = (n, e) => {
492
+ const t = n == null ? void 0 : n.target;
493
+ return (t == null ? void 0 : t.case) === "nodeId" ? `node:${t.value}` : `space:${(t == null ? void 0 : t.value) || e}`;
494
+ }, wt = {
495
+ spaces: [],
496
+ documents: [],
497
+ nodes: [],
498
+ trash: [],
499
+ revisions: [],
500
+ acl: [],
501
+ invites: [],
502
+ loading: !1
503
+ };
504
+ class vr {
505
+ constructor(e, t = "") {
506
+ p(this, "state");
507
+ p(this, "listeners", /* @__PURE__ */ new Set());
508
+ p(this, "generation", 0);
509
+ p(this, "getSnapshot", () => this.state);
510
+ p(this, "subscribe", (e) => (this.listeners.add(e), () => this.listeners.delete(e)));
511
+ p(this, "createSpace", (e) => this.run(async () => ({ spaces: [await this.transport.createSpace(e), ...this.state.spaces] })));
512
+ p(this, "updateSpace", (e) => this.run(async () => {
513
+ const t = await this.transport.updateSpace(e);
514
+ return { spaces: this.state.spaces.map((s) => s.id === t.id ? t : s) };
515
+ }));
516
+ p(this, "archiveSpace", (e) => this.run(async () => {
517
+ const t = await this.transport.archiveSpace(e);
518
+ return { spaces: this.state.spaces.map((s) => s.id === t.id ? t : s) };
519
+ }));
520
+ p(this, "leaveSpace", (e) => this.run(async () => (await this.transport.leaveSpace(e), { spaces: this.state.spaces.filter((t) => t.id !== e.spaceId) })));
521
+ p(this, "createNode", (e) => this.run(async () => {
522
+ const t = await this.transport.createNode(e);
523
+ return { nodes: [...this.state.nodes, t], documents: t.kind === G.NodeKind.DOCUMENT ? [...this.state.documents, t] : this.state.documents };
524
+ }));
525
+ p(this, "updateNode", (e) => this.run(async () => {
526
+ const t = await this.transport.updateNode(e);
527
+ return this.replaceNode(t);
528
+ }));
529
+ p(this, "moveNode", (e) => this.run(async () => {
530
+ const t = await this.transport.moveNode(e);
531
+ return this.replaceNode(t);
532
+ }));
533
+ p(this, "deleteNode", (e) => this.run(async () => {
534
+ const t = this.state.documents.find((s) => s.id === e.nodeId) ?? this.state.nodes.find((s) => s.id === e.nodeId);
535
+ return await this.transport.deleteNode(e), { nodes: this.state.nodes.filter((s) => s.id !== e.nodeId), documents: this.state.documents.filter((s) => s.id !== e.nodeId), trash: t ? [...this.state.trash, t] : this.state.trash };
536
+ }));
537
+ p(this, "restoreNode", (e) => this.run(async () => {
538
+ const t = await this.transport.restoreNode(e);
539
+ return { nodes: [...this.state.nodes, t], documents: t.kind === G.NodeKind.DOCUMENT ? [...this.state.documents, t] : this.state.documents, trash: this.state.trash.filter((s) => s.id !== t.id) };
540
+ }));
541
+ p(this, "restoreRevision", async (e) => {
542
+ const t = e.nodeId;
543
+ if (!t) throw new Error("node ID is required");
544
+ const s = this.generation, r = await this.transport.restoreRevision(e);
545
+ return s === this.generation && await this.openNode(t), r;
546
+ });
547
+ p(this, "setAcl", (e) => this.run(async () => {
548
+ const t = await this.transport.setAcl(e);
549
+ return { acl: [...this.state.acl.filter((s) => s.id !== t.id), t] };
550
+ }));
551
+ p(this, "revokeAcl", (e) => this.run(async () => {
552
+ await this.transport.revokeAcl(e);
553
+ const t = bt(e.resource, e.spaceId ?? "");
554
+ return { acl: this.state.acl.filter((s) => s.subjectId !== e.subjectId || bt(s.resource, s.spaceId) !== t) };
555
+ }));
556
+ p(this, "createInvite", (e) => this.run(async () => {
557
+ const t = await this.transport.createInvite(e);
558
+ return { invites: [...this.state.invites, t] };
559
+ }));
560
+ p(this, "revokeInvite", (e) => this.run(async () => (await this.transport.revokeInvite(e), { invites: this.state.invites.filter((t) => t.id !== e.inviteId) })));
561
+ this.transport = e, this.state = { ...wt, scope: t };
562
+ }
563
+ setScope(e) {
564
+ e !== this.state.scope && (this.generation += 1, this.state = { ...wt, scope: e }, this.listeners.forEach((t) => t()));
565
+ }
566
+ async refresh() {
567
+ return this.run(async () => ({ spaces: (await this.transport.listSpaces({})).spaces }));
568
+ }
569
+ async openSpace(e) {
570
+ return this.generation += 1, this.run(async () => {
571
+ const [t, s, r, l, d] = await Promise.all([
572
+ this.transport.listChildren({ spaceId: e }),
573
+ this.transport.listDocuments({ spaceId: e }),
574
+ this.transport.listTrash({ spaceId: e }),
575
+ this.transport.listAcl({ spaceId: e }),
576
+ this.transport.listInvites({ spaceId: e })
577
+ ]);
578
+ return { selectedSpaceId: e, nodes: t.nodes, documents: s.nodes, trash: r.nodes, acl: l.entries, invites: d.invites, selectedNode: void 0, revisions: [], index: void 0, localDraft: void 0, conflict: void 0 };
579
+ });
580
+ }
581
+ async openNode(e) {
582
+ this.generation += 1;
583
+ const t = this.state.scope;
584
+ return this.run(async () => {
585
+ const [s, r] = await Promise.all([
586
+ this.transport.getNode({ nodeId: e }),
587
+ this.transport.listRevisions({ nodeId: e })
588
+ ]), l = r.revisions.find((f) => f.number === s.revision), d = l && t === this.state.scope ? await this.transport.getRevisionIndexStatus({ nodeId: e, revisionId: l.id }) : void 0;
589
+ return { selectedNode: s, revisions: r.revisions, index: d, localDraft: void 0, conflict: void 0 };
590
+ });
591
+ }
592
+ async save(e, t, s = "") {
593
+ const r = this.requireNode(), l = this.generation;
594
+ this.update({ localDraft: { schema: e, contentJson: t, name: s }, conflict: void 0 });
595
+ try {
596
+ const d = await this.transport.saveRevision({ nodeId: r.id, expectedRevision: r.revision, schema: e, contentJson: t, name: s });
597
+ return l === this.generation && await this.openNode(r.id), d;
598
+ } catch (d) {
599
+ const f = d instanceof Error ? d : new Error(String(d));
600
+ throw l === this.generation && this.update({ loading: !1, conflict: f, error: void 0 }), f;
601
+ }
602
+ }
603
+ async saveAsCopy(e) {
604
+ const t = this.state.selectedSpaceId, s = this.state.localDraft;
605
+ if (!t || !s) throw new Error("a selected space and local draft are required");
606
+ const r = this.state.selectedNode, l = this.state.scope;
607
+ return this.run(async () => {
608
+ var f;
609
+ const d = await this.transport.createNode({
610
+ node: { id: crypto.randomUUID(), spaceId: t, parentId: (r == null ? void 0 : r.parentId) ?? "", kind: G.NodeKind.DOCUMENT, title: e, slug: "", locale: (r == null ? void 0 : r.locale) ?? "" },
611
+ expectedTreeVersion: ((f = this.state.spaces.find((y) => y.id === t)) == null ? void 0 : f.treeVersion) ?? 0n,
612
+ commandId: crypto.randomUUID()
613
+ });
614
+ if (l !== this.state.scope) throw new Error("account scope changed during save");
615
+ return await this.transport.saveRevision({ nodeId: d.id, expectedRevision: d.revision, ...s }), { selectedNode: d, conflict: void 0, localDraft: void 0 };
616
+ });
617
+ }
618
+ async retryIndex() {
619
+ const e = this.requireNode(), t = this.state.revisions.find((s) => s.number === e.revision);
620
+ if (!t) throw new Error("current revision is unavailable");
621
+ return this.run(async () => ({ index: await this.transport.retryRevisionIndex({ nodeId: e.id, revisionId: t.id, force: !0, commandId: crypto.randomUUID() }) }));
622
+ }
623
+ async requestTranslation(e, t) {
624
+ const s = this.requireNode();
625
+ return this.run(async () => (await this.transport.requestTranslation({ sourceNodeId: s.id, targetNodeId: e, targetLocale: t, commandId: crypto.randomUUID() }), {}));
626
+ }
627
+ async publishBundle(e, t, s) {
628
+ const r = this.state.selectedSpaceId;
629
+ if (!r) throw new Error("select a space before publishing");
630
+ return this.run(async () => (await this.transport.publishReleaseBundle({ spaceId: r, version: e, sourceLocale: t, releases: s.map((l) => ({ locale: l.locale, nodes: [...l.nodes] })), commandId: crypto.randomUUID() }), {}));
631
+ }
632
+ requireNode() {
633
+ if (!this.state.selectedNode) throw new Error("select a document first");
634
+ return this.state.selectedNode;
635
+ }
636
+ replaceNode(e) {
637
+ var t;
638
+ return { nodes: this.state.nodes.map((s) => s.id === e.id ? e : s), documents: this.state.documents.map((s) => s.id === e.id ? e : s), selectedNode: ((t = this.state.selectedNode) == null ? void 0 : t.id) === e.id ? e : this.state.selectedNode };
639
+ }
640
+ async run(e) {
641
+ const t = this.generation;
642
+ this.update({ loading: !0, error: void 0 });
643
+ try {
644
+ const s = await e();
645
+ return t === this.generation && this.update({ ...s, loading: !1 }), s;
646
+ } catch (s) {
647
+ const r = s instanceof Error ? s : new Error(String(s));
648
+ throw t === this.generation && this.update({ loading: !1, error: r }), r;
649
+ }
650
+ }
651
+ update(e) {
652
+ this.state = { ...this.state, ...e }, this.listeners.forEach((t) => t());
653
+ }
654
+ }
655
+ const cs = (n) => pe(n.subscribe, n.getSnapshot, n.getSnapshot);
656
+ function br({ controller: n }) {
657
+ var y, x;
658
+ const e = cs(n), [t, s] = E(""), [r, l] = E("1.0.0"), d = e.documents.filter((b) => {
659
+ var C;
660
+ return b.id !== ((C = e.selectedNode) == null ? void 0 : C.id);
661
+ }), f = d.find((b) => b.id === t) ?? d[0];
662
+ return e.error && !e.spaces.length ? /* @__PURE__ */ i(B, { title: "Docs unavailable", description: e.error.message, action: { label: "Retry", onClick: () => void n.refresh() } }) : /* @__PURE__ */ h("section", { className: "af-docs-workbench", "aria-label": "Docs workbench", children: [
663
+ /* @__PURE__ */ h("header", { children: [
664
+ /* @__PURE__ */ h("div", { children: [
665
+ /* @__PURE__ */ h(_, { children: [
666
+ /* @__PURE__ */ i(_n, { size: 14, "aria-hidden": !0 }),
667
+ " Docs repository"
668
+ ] }),
669
+ /* @__PURE__ */ h(q, { children: [
670
+ e.spaces.length,
671
+ " spaces"
672
+ ] })
673
+ ] }),
674
+ /* @__PURE__ */ i(U, { size: "compact", variant: "secondary", disabled: e.loading, onClick: () => void n.refresh(), children: e.loading ? "Loading…" : "Refresh" })
675
+ ] }),
676
+ e.spaces.length ? /* @__PURE__ */ i("div", { className: "af-docs-workbench__list", children: e.spaces.map((b) => /* @__PURE__ */ h(Y, { as: "article", children: [
677
+ /* @__PURE__ */ h("div", { children: [
678
+ /* @__PURE__ */ i(_, { children: b.locale || "default locale" }),
679
+ /* @__PURE__ */ i(q, { children: b.name }),
680
+ /* @__PURE__ */ i("p", { children: b.id })
681
+ ] }),
682
+ /* @__PURE__ */ i(U, { size: "compact", onClick: () => void n.openSpace(b.id), children: "Open" })
683
+ ] }, b.id)) }) : /* @__PURE__ */ i(B, { size: "sm", title: "No document spaces", description: "Accessible spaces appear here." }),
684
+ e.selectedSpaceId && /* @__PURE__ */ h("div", { className: "af-docs-workbench__summary", children: [
685
+ /* @__PURE__ */ h(V, { tone: "cool", children: [
686
+ e.nodes.length,
687
+ " root nodes · ",
688
+ e.documents.length,
689
+ " documents"
690
+ ] }),
691
+ /* @__PURE__ */ h(V, { tone: "neutral", children: [
692
+ /* @__PURE__ */ i(Nt, { size: 12, "aria-hidden": !0 }),
693
+ " ",
694
+ e.trash.length,
695
+ " trash"
696
+ ] }),
697
+ /* @__PURE__ */ h(V, { tone: "neutral", children: [
698
+ /* @__PURE__ */ i(qn, { size: 12, "aria-hidden": !0 }),
699
+ " ",
700
+ e.acl.length,
701
+ " grants"
702
+ ] }),
703
+ /* @__PURE__ */ h(V, { tone: "neutral", children: [
704
+ e.invites.length,
705
+ " invites"
706
+ ] })
707
+ ] }),
708
+ e.documents.length > 0 && /* @__PURE__ */ i("div", { className: "af-docs-workbench__list", children: e.documents.map((b) => /* @__PURE__ */ h(Y, { as: "article", children: [
709
+ /* @__PURE__ */ h("div", { children: [
710
+ /* @__PURE__ */ h(_, { children: [
711
+ "Revision ",
712
+ b.revision.toString(),
713
+ " · ",
714
+ b.locale
715
+ ] }),
716
+ /* @__PURE__ */ i(q, { children: b.title }),
717
+ /* @__PURE__ */ i("p", { children: b.id })
718
+ ] }),
719
+ /* @__PURE__ */ i(U, { size: "compact", variant: "secondary", onClick: () => void n.openNode(b.id), children: "Manage" })
720
+ ] }, b.id)) }),
721
+ e.selectedNode && /* @__PURE__ */ h(Y, { as: "section", children: [
722
+ /* @__PURE__ */ h("header", { children: [
723
+ /* @__PURE__ */ h("div", { children: [
724
+ /* @__PURE__ */ i(_, { children: "Selected document" }),
725
+ /* @__PURE__ */ i(q, { children: e.selectedNode.title })
726
+ ] }),
727
+ /* @__PURE__ */ i(V, { tone: ((y = e.index) == null ? void 0 : y.status) === G.RevisionIndexStatus.READY ? "success" : "warning", children: G.RevisionIndexStatus[((x = e.index) == null ? void 0 : x.status) ?? 0] })
728
+ ] }),
729
+ /* @__PURE__ */ h("p", { children: [
730
+ e.revisions.length,
731
+ " immutable revisions"
732
+ ] }),
733
+ /* @__PURE__ */ h("div", { className: "af-docs-workbench__actions", children: [
734
+ /* @__PURE__ */ h(U, { size: "compact", variant: "secondary", onClick: () => void n.retryIndex(), children: [
735
+ /* @__PURE__ */ i(Bn, { size: 14, "aria-hidden": !0 }),
736
+ " Retry index"
737
+ ] }),
738
+ d.length > 0 && /* @__PURE__ */ i(Dn, { label: "Translation target", value: (f == null ? void 0 : f.id) ?? "", options: d.map((b) => ({ value: b.id, label: `${b.title} · ${b.locale}` })), onChange: s }),
739
+ /* @__PURE__ */ h(U, { size: "compact", variant: "ghost", disabled: !f, onClick: () => f && void n.requestTranslation(f.id, f.locale), children: [
740
+ /* @__PURE__ */ i(Hn, { size: 14, "aria-hidden": !0 }),
741
+ " Translation workflow"
742
+ ] })
743
+ ] }),
744
+ /* @__PURE__ */ h("div", { className: "af-docs-workbench__actions", children: [
745
+ /* @__PURE__ */ i(Ue, { "aria-label": "Release version", value: r, onChange: (b) => l(b.target.value) }),
746
+ /* @__PURE__ */ i(U, { size: "compact", disabled: !f || !r, onClick: () => f && void n.publishBundle(r, e.selectedNode.locale, [{ locale: f.locale, nodes: [{ sourceNodeId: e.selectedNode.id, targetNodeId: f.id }] }]), children: "Publish locale bundle" })
747
+ ] }),
748
+ e.conflict && /* @__PURE__ */ h("div", { role: "alert", children: [
749
+ /* @__PURE__ */ i("strong", { children: "Concurrent save rejected." }),
750
+ " Local draft retained for retry or Save as copy."
751
+ ] })
752
+ ] })
753
+ ] });
754
+ }
755
+ class wr {
756
+ constructor(e) {
757
+ p(this, "state", { loading: !1 });
758
+ p(this, "listeners", /* @__PURE__ */ new Set());
759
+ p(this, "generation", 0);
760
+ p(this, "target", "");
761
+ p(this, "getSnapshot", () => this.state);
762
+ p(this, "subscribe", (e) => (this.listeners.add(e), () => this.listeners.delete(e)));
763
+ this.transport = e;
764
+ }
765
+ async load(e, t, s) {
766
+ const r = ++this.generation, l = JSON.stringify([e, t, s]);
767
+ this.target = l, this.update({ loading: !0, error: void 0 });
768
+ try {
769
+ const d = await this.transport.getLatestPublishedRelease({ tenantId: e, spaceId: t, locale: s });
770
+ r === this.generation && l === this.target && this.update({ release: d, loading: !1 });
771
+ } catch (d) {
772
+ const f = d instanceof Error ? d : new Error(String(d));
773
+ throw r === this.generation && l === this.target && this.update({ loading: !1, error: f }), f;
774
+ }
775
+ }
776
+ update(e) {
777
+ this.state = { ...this.state, ...e }, this.listeners.forEach((t) => t());
778
+ }
779
+ }
780
+ const ls = (n) => pe(n.subscribe, n.getSnapshot, n.getSnapshot);
781
+ function yr({ controller: n }) {
782
+ const e = ls(n);
783
+ return e.loading ? /* @__PURE__ */ i(B, { title: "Loading published documentation" }) : e.error ? /* @__PURE__ */ i(B, { title: "Published documentation unavailable", description: e.error.message }) : e.release ? /* @__PURE__ */ h("main", { className: "af-docs-workbench", "aria-label": "Published documentation", children: [
784
+ /* @__PURE__ */ i("header", { children: /* @__PURE__ */ h("div", { children: [
785
+ /* @__PURE__ */ h(_, { children: [
786
+ e.release.locale,
787
+ " · ",
788
+ e.release.version
789
+ ] }),
790
+ /* @__PURE__ */ i(q, { children: "Published documentation" })
791
+ ] }) }),
792
+ e.release.nodes.map((t) => /* @__PURE__ */ i(Y, { as: "article", children: /* @__PURE__ */ h("div", { children: [
793
+ /* @__PURE__ */ i(_, { children: t.slug }),
794
+ /* @__PURE__ */ i(q, { children: t.title }),
795
+ /* @__PURE__ */ i(ds, { node: t })
796
+ ] }) }, t.nodeId))
797
+ ] }) : /* @__PURE__ */ i(B, { title: "No published documentation" });
798
+ }
799
+ function ds({ node: n }) {
800
+ try {
801
+ return /* @__PURE__ */ i(os, { value: ss(n.contentJson), editable: !1, placeholder: "", ariaLabel: n.title, surface: "document" });
802
+ } catch {
803
+ return /* @__PURE__ */ i(B, { size: "sm", title: "Published content is incompatible" });
804
+ }
805
+ }
806
+ const zt = Math.floor, us = (n, e) => n < e ? n : e, hs = (n, e) => n > e ? n : e, Rt = 128, ce = 127, ps = Number.MAX_SAFE_INTEGER, fs = () => /* @__PURE__ */ new Set(), ms = Array.from, gs = (n) => {
807
+ const e = unescape(encodeURIComponent(n)), t = e.length, s = new Uint8Array(t);
808
+ for (let r = 0; r < t; r++)
809
+ s[r] = /** @type {number} */
810
+ e.codePointAt(r);
811
+ return s;
812
+ }, te = (
813
+ /** @type {TextEncoder} */
814
+ typeof TextEncoder < "u" ? new TextEncoder() : null
815
+ ), vs = (n) => te.encode(n), bs = te ? vs : gs;
816
+ let Q = typeof TextDecoder > "u" ? null : new TextDecoder("utf-8", { fatal: !0, ignoreBOM: !0 });
817
+ Q && Q.decode(new Uint8Array()).length === 1 && (Q = null);
818
+ class ws {
819
+ constructor() {
820
+ this.cpos = 0, this.cbuf = new Uint8Array(100), this.bufs = [];
821
+ }
822
+ }
823
+ const ys = () => new ws(), Ss = (n) => {
824
+ let e = n.cpos;
825
+ for (let t = 0; t < n.bufs.length; t++)
826
+ e += n.bufs[t].length;
827
+ return e;
828
+ }, ks = (n) => {
829
+ const e = new Uint8Array(Ss(n));
830
+ let t = 0;
831
+ for (let s = 0; s < n.bufs.length; s++) {
832
+ const r = n.bufs[s];
833
+ e.set(r, t), t += r.length;
834
+ }
835
+ return e.set(new Uint8Array(n.cbuf.buffer, 0, n.cpos), t), e;
836
+ }, ue = (n, e) => {
837
+ const t = n.cbuf.length;
838
+ n.cpos === t && (n.bufs.push(n.cbuf), n.cbuf = new Uint8Array(t * 2), n.cpos = 0), n.cbuf[n.cpos++] = e;
839
+ }, $ = (n, e) => {
840
+ for (; e > ce; )
841
+ ue(n, Rt | ce & e), e = zt(e / 128);
842
+ ue(n, ce & e);
843
+ }, Me = new Uint8Array(3e4), Ds = Me.length / 3, Cs = (n, e) => {
844
+ if (e.length < Ds) {
845
+ const t = te.encodeInto(e, Me).written || 0;
846
+ $(n, t);
847
+ for (let s = 0; s < t; s++)
848
+ ue(n, Me[s]);
849
+ } else
850
+ As(n, bs(e));
851
+ }, xs = (n, e) => {
852
+ const t = unescape(encodeURIComponent(e)), s = t.length;
853
+ $(n, s);
854
+ for (let r = 0; r < s; r++)
855
+ ue(
856
+ n,
857
+ /** @type {number} */
858
+ t.codePointAt(r)
859
+ );
860
+ }, Ns = te && /** @type {any} */
861
+ te.encodeInto ? Cs : xs, Is = (n, e) => {
862
+ const t = n.cbuf.length, s = n.cpos, r = us(t - s, e.length), l = e.length - r;
863
+ n.cbuf.set(e.subarray(0, r), s), n.cpos += r, l > 0 && (n.bufs.push(n.cbuf), n.cbuf = new Uint8Array(hs(t * 2, l)), n.cbuf.set(e.subarray(r)), n.cpos = l);
864
+ }, As = (n, e) => {
865
+ $(n, e.byteLength), Is(n, e);
866
+ }, Ut = (n) => new Error(n), Es = Ut("Unexpected end of array"), zs = Ut("Integer out of Range");
867
+ class Rs {
868
+ /**
869
+ * @param {Uint8Array<Buf>} uint8Array Binary data to decode
870
+ */
871
+ constructor(e) {
872
+ this.arr = e, this.pos = 0;
873
+ }
874
+ }
875
+ const Us = (n) => new Rs(n), Ts = (n, e) => {
876
+ const t = new Uint8Array(n.arr.buffer, n.pos + n.arr.byteOffset, e);
877
+ return n.pos += e, t;
878
+ }, Ls = (n) => Ts(n, Z(n)), yt = (n) => n.arr[n.pos++], Z = (n) => {
879
+ let e = 0, t = 1;
880
+ const s = n.arr.length;
881
+ for (; n.pos < s; ) {
882
+ const r = n.arr[n.pos++];
883
+ if (e = e + (r & ce) * t, t *= 128, r < Rt)
884
+ return e;
885
+ if (e > ps)
886
+ throw zs;
887
+ }
888
+ throw Es;
889
+ }, Ps = (n) => {
890
+ let e = Z(n);
891
+ if (e === 0)
892
+ return "";
893
+ {
894
+ let t = String.fromCodePoint(yt(n));
895
+ if (--e < 100)
896
+ for (; e--; )
897
+ t += String.fromCodePoint(yt(n));
898
+ else
899
+ for (; e > 0; ) {
900
+ const s = e < 1e4 ? e : 1e4, r = n.arr.subarray(n.pos, n.pos + s);
901
+ n.pos += s, t += String.fromCodePoint.apply(
902
+ null,
903
+ /** @type {any} */
904
+ r
905
+ ), e -= s;
906
+ }
907
+ return decodeURIComponent(escape(t));
908
+ }
909
+ }, Ms = (n) => (
910
+ /** @type any */
911
+ Q.decode(Ls(n))
912
+ ), Os = Q ? Ms : Ps, he = Date.now, Ae = () => /* @__PURE__ */ new Map(), _s = (n, e, t) => {
913
+ let s = n.get(e);
914
+ return s === void 0 && n.set(e, s = t()), s;
915
+ };
916
+ class qs {
917
+ constructor() {
918
+ this._observers = Ae();
919
+ }
920
+ /**
921
+ * @param {N} name
922
+ * @param {function} f
923
+ */
924
+ on(e, t) {
925
+ _s(this._observers, e, fs).add(t);
926
+ }
927
+ /**
928
+ * @param {N} name
929
+ * @param {function} f
930
+ */
931
+ once(e, t) {
932
+ const s = (...r) => {
933
+ this.off(e, s), t(...r);
934
+ };
935
+ this.on(e, s);
936
+ }
937
+ /**
938
+ * @param {N} name
939
+ * @param {function} f
940
+ */
941
+ off(e, t) {
942
+ const s = this._observers.get(e);
943
+ s !== void 0 && (s.delete(t), s.size === 0 && this._observers.delete(e));
944
+ }
945
+ /**
946
+ * Emit a named event. All registered event listeners that listen to the
947
+ * specified name will receive the event.
948
+ *
949
+ * @todo This should catch exceptions
950
+ *
951
+ * @param {N} name The event name.
952
+ * @param {Array<any>} args The arguments that are applied to the event listener.
953
+ */
954
+ emit(e, t) {
955
+ return ms((this._observers.get(e) || Ae()).values()).forEach((s) => s(...t));
956
+ }
957
+ destroy() {
958
+ this._observers = Ae();
959
+ }
960
+ }
961
+ const St = Symbol("Equality"), Bs = Object.keys, kt = (n) => Bs(n).length, Hs = (n, e) => Object.prototype.hasOwnProperty.call(n, e), ee = (n, e) => {
962
+ if (n === e)
963
+ return !0;
964
+ if (n == null || e == null || n.constructor !== e.constructor && (n.constructor || Object) !== (e.constructor || Object))
965
+ return !1;
966
+ if (n[St] != null)
967
+ return n[St](e);
968
+ switch (n.constructor) {
969
+ case ArrayBuffer:
970
+ n = new Uint8Array(n), e = new Uint8Array(e);
971
+ // eslint-disable-next-line no-fallthrough
972
+ case Uint8Array: {
973
+ if (n.byteLength !== e.byteLength)
974
+ return !1;
975
+ for (let t = 0; t < n.length; t++)
976
+ if (n[t] !== e[t])
977
+ return !1;
978
+ break;
979
+ }
980
+ case Set: {
981
+ if (n.size !== e.size)
982
+ return !1;
983
+ for (const t of n)
984
+ if (!e.has(t))
985
+ return !1;
986
+ break;
987
+ }
988
+ case Map: {
989
+ if (n.size !== e.size)
990
+ return !1;
991
+ for (const t of n.keys())
992
+ if (!e.has(t) || !ee(n.get(t), e.get(t)))
993
+ return !1;
994
+ break;
995
+ }
996
+ case void 0:
997
+ case Object:
998
+ if (kt(n) !== kt(e))
999
+ return !1;
1000
+ for (const t in n)
1001
+ if (!Hs(n, t) || !ee(n[t], e[t]))
1002
+ return !1;
1003
+ break;
1004
+ case Array:
1005
+ if (n.length !== e.length)
1006
+ return !1;
1007
+ for (let t = 0; t < n.length; t++)
1008
+ if (!ee(n[t], e[t]))
1009
+ return !1;
1010
+ break;
1011
+ default:
1012
+ return !1;
1013
+ }
1014
+ return !0;
1015
+ }, Ee = 3e4;
1016
+ class Tt extends qs {
1017
+ /**
1018
+ * @param {Y.Doc} doc
1019
+ */
1020
+ constructor(e) {
1021
+ super(), this.doc = e, this.clientID = e.clientID, this.states = /* @__PURE__ */ new Map(), this.meta = /* @__PURE__ */ new Map(), this._checkInterval = /** @type {any} */
1022
+ setInterval(() => {
1023
+ const t = he();
1024
+ this.getLocalState() !== null && Ee / 2 <= t - /** @type {{lastUpdated:number}} */
1025
+ this.meta.get(this.clientID).lastUpdated && this.setLocalState(this.getLocalState());
1026
+ const s = [];
1027
+ this.meta.forEach((r, l) => {
1028
+ l !== this.clientID && Ee <= t - r.lastUpdated && this.states.has(l) && s.push(l);
1029
+ }), s.length > 0 && Lt(this, s, "timeout");
1030
+ }, zt(Ee / 10)), e.on("destroy", () => {
1031
+ this.destroy();
1032
+ }), this.setLocalState({});
1033
+ }
1034
+ destroy() {
1035
+ this.emit("destroy", [this]), this.setLocalState(null), super.destroy(), clearInterval(this._checkInterval);
1036
+ }
1037
+ /**
1038
+ * @return {Object<string,any>|null}
1039
+ */
1040
+ getLocalState() {
1041
+ return this.states.get(this.clientID) || null;
1042
+ }
1043
+ /**
1044
+ * @param {Object<string,any>|null} state
1045
+ */
1046
+ setLocalState(e) {
1047
+ const t = this.clientID, s = this.meta.get(t), r = s === void 0 ? 0 : s.clock + 1, l = this.states.get(t);
1048
+ e === null ? this.states.delete(t) : this.states.set(t, e), this.meta.set(t, {
1049
+ clock: r,
1050
+ lastUpdated: he()
1051
+ });
1052
+ const d = [], f = [], y = [], x = [];
1053
+ e === null ? x.push(t) : l == null ? e != null && d.push(t) : (f.push(t), ee(l, e) || y.push(t)), (d.length > 0 || y.length > 0 || x.length > 0) && this.emit("change", [{ added: d, updated: y, removed: x }, "local"]), this.emit("update", [{ added: d, updated: f, removed: x }, "local"]);
1054
+ }
1055
+ /**
1056
+ * @param {string} field
1057
+ * @param {any} value
1058
+ */
1059
+ setLocalStateField(e, t) {
1060
+ const s = this.getLocalState();
1061
+ s !== null && this.setLocalState({
1062
+ ...s,
1063
+ [e]: t
1064
+ });
1065
+ }
1066
+ /**
1067
+ * @return {Map<number,Object<string,any>>}
1068
+ */
1069
+ getStates() {
1070
+ return this.states;
1071
+ }
1072
+ }
1073
+ const Lt = (n, e, t) => {
1074
+ const s = [];
1075
+ for (let r = 0; r < e.length; r++) {
1076
+ const l = e[r];
1077
+ if (n.states.has(l)) {
1078
+ if (n.states.delete(l), l === n.clientID) {
1079
+ const d = (
1080
+ /** @type {MetaClientState} */
1081
+ n.meta.get(l)
1082
+ );
1083
+ n.meta.set(l, {
1084
+ clock: d.clock + 1,
1085
+ lastUpdated: he()
1086
+ });
1087
+ }
1088
+ s.push(l);
1089
+ }
1090
+ }
1091
+ s.length > 0 && (n.emit("change", [{ added: [], updated: [], removed: s }, t]), n.emit("update", [{ added: [], updated: [], removed: s }, t]));
1092
+ }, Pt = (n, e, t = n.states) => {
1093
+ const s = e.length, r = ys();
1094
+ $(r, s);
1095
+ for (let l = 0; l < s; l++) {
1096
+ const d = e[l], f = t.get(d) || null, y = (
1097
+ /** @type {MetaClientState} */
1098
+ n.meta.get(d).clock
1099
+ );
1100
+ $(r, d), $(r, y), Ns(r, JSON.stringify(f));
1101
+ }
1102
+ return ks(r);
1103
+ }, Mt = (n, e, t) => {
1104
+ const s = Us(e), r = he(), l = [], d = [], f = [], y = [], x = Z(s);
1105
+ for (let b = 0; b < x; b++) {
1106
+ const C = Z(s);
1107
+ let S = Z(s);
1108
+ const T = JSON.parse(Os(s)), I = n.meta.get(C), F = n.states.get(C), z = I === void 0 ? 0 : I.clock;
1109
+ (z < S || z === S && T === null && n.states.has(C)) && (T === null ? C === n.clientID && n.getLocalState() != null ? S++ : n.states.delete(C) : n.states.set(C, T), n.meta.set(C, {
1110
+ clock: S,
1111
+ lastUpdated: r
1112
+ }), I === void 0 && T !== null ? l.push(C) : I !== void 0 && T === null ? y.push(C) : T !== null && (ee(T, F) || f.push(C), d.push(C)));
1113
+ }
1114
+ (l.length > 0 || f.length > 0 || y.length > 0) && n.emit("change", [{
1115
+ added: l,
1116
+ updated: f,
1117
+ removed: y
1118
+ }, t]), (l.length > 0 || d.length > 0 || y.length > 0) && n.emit("update", [{
1119
+ added: l,
1120
+ updated: d,
1121
+ removed: y
1122
+ }, t]);
1123
+ }, Dt = {
1124
+ connected: !1,
1125
+ connecting: !1,
1126
+ serverSequence: 0n,
1127
+ stateVector: {},
1128
+ updates: [],
1129
+ cursors: {}
1130
+ };
1131
+ class Sr {
1132
+ constructor(e) {
1133
+ p(this, "state", Dt);
1134
+ p(this, "listeners", /* @__PURE__ */ new Set());
1135
+ p(this, "generation", 0);
1136
+ p(this, "desired");
1137
+ p(this, "pendingUpdates", /* @__PURE__ */ new Map());
1138
+ p(this, "reconnecting");
1139
+ p(this, "getSnapshot", () => this.state);
1140
+ p(this, "subscribe", (e) => (this.listeners.add(e), () => this.listeners.delete(e)));
1141
+ this.transport = e;
1142
+ }
1143
+ async connect(e, t, s = 0n) {
1144
+ this.disconnect();
1145
+ const r = ++this.generation;
1146
+ this.desired = { nodeId: e, clientId: t }, this.pendingUpdates.clear(), this.update({ ...Dt, connecting: !0, nodeId: e, serverSequence: s });
1147
+ try {
1148
+ await this.open(r, e, t, s);
1149
+ } catch (l) {
1150
+ throw r === this.generation && this.update({ ...this.state, connecting: !1, error: l instanceof Error ? l : new Error(String(l)) }), l;
1151
+ }
1152
+ }
1153
+ async push(e, t) {
1154
+ const s = this.requireSession();
1155
+ try {
1156
+ this.applyUpdate(await this.transport.pushCollaboration({ sessionId: s, clientClock: e, update: t }));
1157
+ } catch (r) {
1158
+ throw Le(r) && this.connectionLost(this.generation, r), r;
1159
+ }
1160
+ }
1161
+ async updateCursor(e) {
1162
+ const t = this.requireSession();
1163
+ await this.transport.updateCollaborationPresence({ sessionId: t, cursor: e });
1164
+ }
1165
+ async sync(e = this.state.serverSequence) {
1166
+ const t = this.requireSession();
1167
+ let s = e;
1168
+ for (; ; ) {
1169
+ const r = await this.transport.syncCollaboration({ sessionId: t, afterSequence: s });
1170
+ if (this.applyReady(r), !r.hasMore) return;
1171
+ if (this.state.serverSequence <= s) throw new Error("collaboration sync did not advance");
1172
+ s = this.state.serverSequence;
1173
+ }
1174
+ }
1175
+ waitForConnection() {
1176
+ return this.state.connected ? Promise.resolve() : this.desired ? new Promise((e, t) => {
1177
+ const s = this.subscribe(() => {
1178
+ this.state.connected ? (s(), e()) : this.desired || (s(), t(this.state.error ?? new Error("collaboration is not connected")));
1179
+ });
1180
+ }) : Promise.reject(new Error("collaboration is not connected"));
1181
+ }
1182
+ disconnect() {
1183
+ const e = this.state.sessionId;
1184
+ this.desired = void 0, this.generation += 1, this.update({ ...this.state, connected: !1, connecting: !1, disconnectedReason: "client_closed", cursors: {} }), e && Promise.resolve(this.transport.closeCollaboration({ sessionId: e })).catch(() => {
1185
+ });
1186
+ }
1187
+ reportError(e) {
1188
+ this.update({ ...this.state, error: e instanceof Error ? e : new Error(String(e)) });
1189
+ }
1190
+ async consume(e, t) {
1191
+ try {
1192
+ for await (const s of t) {
1193
+ if (e !== this.generation) return;
1194
+ const r = s.kind;
1195
+ if (r.case === "ready")
1196
+ this.applyReady(r.value), r.value.hasMore && await this.sync(this.state.serverSequence);
1197
+ else if (r.case === "update")
1198
+ this.applyUpdate(r.value);
1199
+ else if (r.case === "presence") {
1200
+ if (r.value.sessionId === this.state.sessionId) continue;
1201
+ const l = { ...this.state.cursors };
1202
+ r.value.active ? l[r.value.sessionId] = { subjectId: r.value.subjectId, cursor: r.value.cursor } : delete l[r.value.sessionId], this.update({ ...this.state, cursors: l });
1203
+ } else if (r.case === "disconnected") {
1204
+ r.value.reason === "authorization_revoked" || r.value.reason === "client_closed" ? (this.desired = void 0, this.generation += 1, this.update({ ...this.state, connected: !1, connecting: !1, disconnectedReason: r.value.reason, cursors: {} })) : this.connectionLost(e, new Error(r.value.reason));
1205
+ return;
1206
+ }
1207
+ }
1208
+ e === this.generation && this.connectionLost(e, new Error("stream_closed"));
1209
+ } catch (s) {
1210
+ this.connectionLost(e, s);
1211
+ }
1212
+ }
1213
+ requireSession() {
1214
+ if (!this.state.sessionId || !this.state.connected) throw new Error("collaboration is not connected");
1215
+ return this.state.sessionId;
1216
+ }
1217
+ applyReady(e) {
1218
+ const t = this.contiguous(e.updates), s = {};
1219
+ for (const r of e.presences ?? [])
1220
+ r.active && r.sessionId !== e.sessionId && (s[r.sessionId] = { subjectId: r.subjectId, cursor: r.cursor });
1221
+ this.update({
1222
+ ...this.state,
1223
+ connected: !0,
1224
+ connecting: !1,
1225
+ nodeId: e.nodeId,
1226
+ sessionId: e.sessionId,
1227
+ clientId: e.clientId,
1228
+ serverSequence: t.serverSequence,
1229
+ stateVector: $s(this.state.stateVector, e.stateVector),
1230
+ updates: t.updates,
1231
+ cursors: s,
1232
+ disconnectedReason: void 0,
1233
+ error: void 0
1234
+ });
1235
+ }
1236
+ applyUpdate(e) {
1237
+ const t = this.contiguous([e]);
1238
+ this.update({
1239
+ ...this.state,
1240
+ serverSequence: t.serverSequence,
1241
+ updates: t.updates
1242
+ });
1243
+ }
1244
+ contiguous(e) {
1245
+ for (const r of e)
1246
+ if (!(r.serverSequence <= this.state.serverSequence)) {
1247
+ if (!this.pendingUpdates.has(r.serverSequence) && this.pendingUpdates.size >= 128)
1248
+ throw new Error("collaboration sequence gap exceeds 128 buffered updates");
1249
+ this.pendingUpdates.set(r.serverSequence, r);
1250
+ }
1251
+ let t = this.state.serverSequence;
1252
+ const s = [...this.state.updates];
1253
+ for (; ; ) {
1254
+ const r = this.pendingUpdates.get(t + 1n);
1255
+ if (!r) break;
1256
+ this.pendingUpdates.delete(t + 1n), s.push(r), t += 1n;
1257
+ }
1258
+ return { serverSequence: t, updates: s };
1259
+ }
1260
+ async open(e, t, s, r) {
1261
+ const l = await this.transport.openCollaboration({ nodeId: t, clientId: s, afterSequence: r });
1262
+ if (e !== this.generation) {
1263
+ await Promise.resolve(this.transport.closeCollaboration({ sessionId: l.sessionId })).catch(() => {
1264
+ });
1265
+ return;
1266
+ }
1267
+ this.applyReady(l), this.consume(e, this.transport.followCollaboration({
1268
+ sessionId: l.sessionId,
1269
+ afterSequence: this.state.serverSequence
1270
+ })), l.hasMore && await this.sync(this.state.serverSequence);
1271
+ }
1272
+ connectionLost(e, t) {
1273
+ if (e !== this.generation || !this.desired) return;
1274
+ const s = t instanceof Error ? t : new Error(String(t));
1275
+ if (this.update({ ...this.state, connected: !1, connecting: !1, disconnectedReason: s.message, cursors: {}, error: s }), !this.reconnecting) {
1276
+ const r = this.reconnect().finally(() => {
1277
+ this.reconnecting === r && (this.reconnecting = void 0);
1278
+ });
1279
+ this.reconnecting = r;
1280
+ }
1281
+ }
1282
+ async reconnect() {
1283
+ const e = this.desired;
1284
+ if (!e) return;
1285
+ const t = this.state.sessionId, s = ++this.generation;
1286
+ t && Promise.resolve(this.transport.closeCollaboration({ sessionId: t })).catch(() => {
1287
+ });
1288
+ let r = this.state.error ?? new Error("collaboration disconnected");
1289
+ for (let l = 0; s === this.generation && this.desired === e; l += 1) {
1290
+ if (s !== this.generation || this.desired !== e) return;
1291
+ l > 0 && await Fs(Math.min(50 * 2 ** (l - 1), 5e3)), this.update({ ...this.state, connecting: !0, disconnectedReason: void 0 });
1292
+ try {
1293
+ await this.open(s, e.nodeId, e.clientId, this.state.serverSequence);
1294
+ return;
1295
+ } catch (d) {
1296
+ if (r = d instanceof Error ? d : new Error(String(d)), this.update({ ...this.state, connecting: !1, disconnectedReason: r.message, error: r }), !Le(d)) {
1297
+ this.desired = void 0;
1298
+ return;
1299
+ }
1300
+ }
1301
+ }
1302
+ }
1303
+ update(e) {
1304
+ this.state = e, this.listeners.forEach((t) => t());
1305
+ }
1306
+ }
1307
+ const Ct = Symbol("docs-collaboration-remote"), le = Symbol("docs-collaboration-presence"), ze = 64 * 1024;
1308
+ class kr {
1309
+ constructor(e, t, s, r = "prosemirror") {
1310
+ p(this, "document", new M.Doc());
1311
+ p(this, "awareness", new Tt(this.document));
1312
+ p(this, "user");
1313
+ p(this, "editorCollaboration");
1314
+ p(this, "unsubscribe");
1315
+ p(this, "presenceClients", /* @__PURE__ */ new Map());
1316
+ p(this, "appliedPresence", /* @__PURE__ */ new Map());
1317
+ p(this, "clockClientId", crypto.randomUUID());
1318
+ p(this, "clientClock", 0n);
1319
+ p(this, "appliedSequence", 0n);
1320
+ p(this, "queuedUpdates", []);
1321
+ p(this, "pumping");
1322
+ p(this, "presencePending", Promise.resolve());
1323
+ p(this, "terminalUpdateError");
1324
+ p(this, "oversizedUpdate", !1);
1325
+ p(this, "applyRemoteUpdates", () => {
1326
+ for (const t of this.controller.getSnapshot().updates)
1327
+ t.serverSequence <= this.appliedSequence || (M.applyUpdate(this.document, t.update, Ct), this.appliedSequence = t.serverSequence);
1328
+ const e = this.controller.getSnapshot().cursors;
1329
+ for (const t of this.presenceClients.keys())
1330
+ e[t] || (Lt(this.awareness, [...this.presenceClients.get(t) ?? []], le), this.presenceClients.delete(t), this.appliedPresence.delete(t));
1331
+ for (const [t, s] of Object.entries(e)) {
1332
+ if (s.cursor.length === 0 || js(this.appliedPresence.get(t), s.cursor)) continue;
1333
+ const r = /* @__PURE__ */ new Set(), l = ({ added: d, updated: f }) => {
1334
+ for (const y of [...d, ...f]) r.add(y);
1335
+ };
1336
+ this.awareness.on("update", l);
1337
+ try {
1338
+ Mt(this.awareness, Vs(s.cursor, s.subjectId), le);
1339
+ } catch {
1340
+ continue;
1341
+ } finally {
1342
+ this.awareness.off("update", l);
1343
+ }
1344
+ r.size > 0 && this.presenceClients.set(t, r), this.appliedPresence.set(t, s.cursor);
1345
+ }
1346
+ });
1347
+ p(this, "pushLocalUpdate", (e, t) => {
1348
+ var d;
1349
+ if (t === Ct) return;
1350
+ const s = this.oversizedUpdate ? M.encodeStateAsUpdate(this.document) : e;
1351
+ if (s.length > ze) {
1352
+ this.oversizedUpdate = !0, this.terminalUpdateError = new Error(`collaboration update exceeds ${ze} bytes`), this.controller.reportError(this.terminalUpdateError);
1353
+ return;
1354
+ }
1355
+ this.oversizedUpdate = !1, this.terminalUpdateError = void 0;
1356
+ const r = this.queuedUpdates.at(-1), l = r && r.clock === void 0 ? M.mergeUpdates([r.bytes, s]) : s;
1357
+ r && r.clock === void 0 && l.length <= ze ? r.bytes = l : this.queuedUpdates.push({ bytes: s }), (d = this.ensurePump()) == null || d.catch((f) => this.controller.reportError(f));
1358
+ });
1359
+ p(this, "pushLocalPresence", (e, t) => {
1360
+ if (t === le || !this.controller.getSnapshot().connected) return;
1361
+ const s = Pt(this.awareness, [this.awareness.clientID]);
1362
+ this.presencePending = this.presencePending.catch(() => {
1363
+ }).then(() => this.controller.updateCursor(s)), this.presencePending.catch((r) => this.controller.reportError(r));
1364
+ });
1365
+ this.controller = e, this.clientId = t, this.initialValue = s, this.field = r, this.user = { name: t, color: _t(t) }, this.editorCollaboration = { document: this.document, awareness: this.awareness, user: this.user }, this.awareness.setLocalStateField("user", this.user), this.unsubscribe = e.subscribe(this.applyRemoteUpdates), this.document.on("update", this.pushLocalUpdate), this.awareness.on("update", this.pushLocalPresence);
1366
+ }
1367
+ async connect(e, t = 0n) {
1368
+ this.oversizedUpdate || (this.terminalUpdateError = void 0), await this.controller.connect(e, this.clockClientId, t), this.applyRemoteUpdates();
1369
+ const s = this.controller.getSnapshot(), r = s.stateVector[s.clientId ?? this.clientId] ?? 0n;
1370
+ if (r > this.clientClock && (this.clientClock = r), s.serverSequence === 0n && this.document.getXmlFragment(this.field).length === 0 && this.initialValue) {
1371
+ const l = tn(Et("")), d = new M.Doc();
1372
+ d.clientID = Ot(JSON.stringify(this.initialValue)), $n(l, this.initialValue.doc, d.getXmlFragment(this.field)), M.applyUpdate(this.document, M.encodeStateAsUpdate(d));
1373
+ }
1374
+ await this.flush(), this.pushLocalPresence({ added: [this.awareness.clientID], updated: [], removed: [] }, void 0);
1375
+ }
1376
+ snapshot() {
1377
+ return Pe(Fn(this.document.getXmlFragment(this.field)));
1378
+ }
1379
+ async checkpoint(e, t) {
1380
+ return await this.flush(), await this.controller.sync(), this.applyRemoteUpdates(), await this.flush(), String(await t(this.snapshot(), {
1381
+ expectedRevision: String(e),
1382
+ collaborationSequence: this.controller.getSnapshot().serverSequence
1383
+ }));
1384
+ }
1385
+ flush() {
1386
+ return this.terminalUpdateError ? Promise.reject(this.terminalUpdateError) : this.ensurePump() ?? Promise.resolve();
1387
+ }
1388
+ disconnect() {
1389
+ this.controller.disconnect();
1390
+ }
1391
+ destroy() {
1392
+ this.unsubscribe(), this.document.off("update", this.pushLocalUpdate), this.awareness.off("update", this.pushLocalPresence), this.disconnect(), this.awareness.destroy(), this.document.destroy();
1393
+ }
1394
+ ensurePump() {
1395
+ if (this.queuedUpdates.length === 0) return this.pumping;
1396
+ if (!this.pumping) {
1397
+ const e = this.pump().finally(() => {
1398
+ this.pumping === e && (this.pumping = void 0);
1399
+ });
1400
+ this.pumping = e;
1401
+ }
1402
+ return this.pumping;
1403
+ }
1404
+ async pump() {
1405
+ for (; this.queuedUpdates.length > 0; ) {
1406
+ const e = this.queuedUpdates.shift(), t = e.clock ?? (e.clock = ++this.clientClock);
1407
+ try {
1408
+ for (; ; ) {
1409
+ await this.controller.waitForConnection();
1410
+ try {
1411
+ await this.controller.push(t, e.bytes);
1412
+ break;
1413
+ } catch (s) {
1414
+ if (!Le(s))
1415
+ throw this.terminalUpdateError = s instanceof Error ? s : new Error(String(s)), this.terminalUpdateError;
1416
+ }
1417
+ }
1418
+ } catch (s) {
1419
+ throw this.queuedUpdates.unshift(e), s;
1420
+ }
1421
+ }
1422
+ }
1423
+ }
1424
+ function Ot(n) {
1425
+ let e = 2166136261;
1426
+ for (let t = 0; t < n.length; t += 1) e = Math.imul(e ^ n.charCodeAt(t), 16777619);
1427
+ return e >>> 0 || 1;
1428
+ }
1429
+ function _t(n) {
1430
+ return `hsl(${Ot(n) % 360} 62% 42%)`;
1431
+ }
1432
+ function js(n, e) {
1433
+ return (n == null ? void 0 : n.length) === e.length && n.every((t, s) => t === e[s]);
1434
+ }
1435
+ function Vs(n, e) {
1436
+ const t = new M.Doc(), s = new Tt(t);
1437
+ try {
1438
+ Mt(s, n, le);
1439
+ const r = [...s.getStates().keys()];
1440
+ for (const l of r) {
1441
+ const d = s.getStates().get(l) ?? {};
1442
+ s.states.set(l, { ...d, user: { name: e, color: _t(e) } });
1443
+ }
1444
+ return Pt(s, r);
1445
+ } finally {
1446
+ s.destroy(), t.destroy();
1447
+ }
1448
+ }
1449
+ function $s(n, e) {
1450
+ const t = { ...n };
1451
+ for (const [s, r] of Object.entries(e ?? {})) t[s] = t[s] > r ? t[s] : r;
1452
+ return t;
1453
+ }
1454
+ const Fs = (n) => new Promise((e) => setTimeout(e, n)), Js = (n) => pe(n.subscribe, n.getSnapshot, n.getSnapshot);
1455
+ function Dr({ controller: n }) {
1456
+ const e = Js(n);
1457
+ return e.error ? /* @__PURE__ */ i(B, { size: "sm", title: "Live editing unavailable", description: e.error.message }) : /* @__PURE__ */ h(Y, { as: "section", children: [
1458
+ /* @__PURE__ */ h("header", { children: [
1459
+ /* @__PURE__ */ h("div", { children: [
1460
+ /* @__PURE__ */ i(_, { children: "Live document" }),
1461
+ /* @__PURE__ */ i(q, { children: e.nodeId ?? "No document selected" })
1462
+ ] }),
1463
+ /* @__PURE__ */ i(V, { tone: e.connected ? "success" : "neutral", children: e.connecting ? "Connecting" : e.connected ? "Connected" : "Disconnected" })
1464
+ ] }),
1465
+ /* @__PURE__ */ h("p", { children: [
1466
+ Object.keys(e.cursors).length,
1467
+ " remote editors · durable sequence ",
1468
+ e.serverSequence.toString()
1469
+ ] }),
1470
+ e.disconnectedReason && /* @__PURE__ */ i("p", { role: "status", children: e.disconnectedReason }),
1471
+ (e.connected || e.connecting) && /* @__PURE__ */ i(U, { size: "compact", variant: "secondary", onClick: () => n.disconnect(), children: "Disconnect" })
1472
+ ] });
1473
+ }
481
1474
  export {
482
- W as RICH_DOCUMENT_SCHEMA,
483
- Nr as RichDocument,
484
- Nr as RichDocumentEditor,
485
- Ut as applyDocumentAssistantOutput,
486
- Qt as commitDocumentAssistantRollback,
487
- Xe as documentAssistantConflict,
488
- We as durableRichDocumentContent,
489
- Ke as emptyRichDocument,
490
- cr as looksLikeMarkdown,
491
- Sr as parseRichDocument,
492
- Gt as replaceAssistantMarkdown,
493
- ir as replaceDocumentContent,
494
- ar as richDocumentExtensions,
495
- Yt as rollbackAssistantRange,
496
- or as selectionInsideTable
1475
+ Dr as DocsCollaboration,
1476
+ Sr as DocsCollaborationController,
1477
+ br as DocsWorkbench,
1478
+ vr as DocsWorkbenchController,
1479
+ yr as PublishedDocs,
1480
+ wr as PublishedDocsController,
1481
+ fe as RICH_DOCUMENT_SCHEMA,
1482
+ os as RichDocument,
1483
+ os as RichDocumentEditor,
1484
+ kr as YjsDocsCollaborationAdapter,
1485
+ Gn as applyDocumentAssistantOutput,
1486
+ Yn as commitDocumentAssistantRollback,
1487
+ It as documentAssistantConflict,
1488
+ Pe as durableRichDocumentContent,
1489
+ vt as emptyRichDocument,
1490
+ as as looksLikeMarkdown,
1491
+ ss as parseRichDocument,
1492
+ Xn as replaceAssistantMarkdown,
1493
+ is as replaceDocumentContent,
1494
+ Et as richDocumentExtensions,
1495
+ Wn as rollbackAssistantRange,
1496
+ rs as selectionInsideTable,
1497
+ Js as useDocsCollaboration,
1498
+ cs as useDocsWorkbench,
1499
+ ls as usePublishedDocs
497
1500
  };