@june-ai/june-ui 0.2.2 → 0.2.4

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,3 +1,19 @@
1
+ import {
2
+ JuneError,
3
+ createDocumentExtensions,
4
+ debounce,
5
+ docKey,
6
+ docToHtml,
7
+ docToMarkdown,
8
+ emptyDoc,
9
+ isJuneError,
10
+ parseDocumentContent,
11
+ sanitizeHref,
12
+ slugify,
13
+ toJuneError,
14
+ wordCountOf
15
+ } from "./chunk-HFHRSNIL.js";
16
+
1
17
  // src/renderer/renderer.tsx
2
18
  import { Renderer } from "@openuidev/react-lang";
3
19
  import {
@@ -7,28 +23,6 @@ import {
7
23
  useRef
8
24
  } from "react";
9
25
 
10
- // src/errors/errors.ts
11
- var JuneError = class _JuneError extends Error {
12
- constructor(code, message, options = {}) {
13
- super(message);
14
- Object.setPrototypeOf(this, _JuneError.prototype);
15
- this.name = "JuneError";
16
- this.code = code;
17
- this.details = options.details;
18
- if (options.cause !== void 0) {
19
- this.cause = options.cause;
20
- }
21
- }
22
- };
23
- function isJuneError(value) {
24
- return value instanceof JuneError;
25
- }
26
- function toJuneError(error, fallbackCode, message) {
27
- if (error instanceof JuneError) return error;
28
- const text = message ?? (error instanceof Error ? error.message : String(error));
29
- return new JuneError(fallbackCode, text, { cause: error });
30
- }
31
-
32
26
  // src/actions/action-handler.ts
33
27
  function firstString(...values) {
34
28
  for (const v of values) if (typeof v === "string" && v.length > 0) return v;
@@ -91,21 +85,36 @@ function createActionHandler(options) {
91
85
  };
92
86
  }
93
87
 
94
- // src/themes/theme-provider.tsx
95
- import {
96
- useMemo,
97
- useSyncExternalStore
98
- } from "react";
88
+ // src/components/document-editor/document-context.ts
89
+ import { createContext, useContext, useSyncExternalStore } from "react";
90
+ var JuneDocumentContext = createContext({});
91
+ function useDocumentOptions() {
92
+ return useContext(JuneDocumentContext);
93
+ }
94
+ function useDocumentValue(store, id, selector) {
95
+ const read = () => selector(store.get(id));
96
+ return useSyncExternalStore(store.subscribe, read, read);
97
+ }
99
98
 
100
99
  // src/core/context.ts
101
- import { createContext, useContext } from "react";
102
- var JuneContext = createContext({
100
+ import { createContext as createContext2, useContext as useContext2 } from "react";
101
+ var JuneContext = createContext2({
103
102
  mode: "light",
104
103
  theme: "light"
105
104
  });
106
105
  function useJuneTheme() {
107
- return useContext(JuneContext);
106
+ return useContext2(JuneContext);
108
107
  }
108
+ var JuneRuntimeContext = createContext2({ isStreaming: false });
109
+ function useJuneRuntime() {
110
+ return useContext2(JuneRuntimeContext);
111
+ }
112
+
113
+ // src/themes/theme-provider.tsx
114
+ import {
115
+ useMemo,
116
+ useSyncExternalStore as useSyncExternalStore2
117
+ } from "react";
109
118
 
110
119
  // src/themes/dark.ts
111
120
  var darkTheme = {
@@ -143,7 +152,7 @@ function getServerSnapshot() {
143
152
  return "light";
144
153
  }
145
154
  function useResolvedTheme(mode) {
146
- const system = useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot);
155
+ const system = useSyncExternalStore2(subscribe, getSnapshot, getServerSnapshot);
147
156
  return mode === "system" ? system : mode;
148
157
  }
149
158
  function JuneThemeProvider({
@@ -194,6 +203,7 @@ var ATTACHABLE = /* @__PURE__ */ new Set([
194
203
  "CodeBlock",
195
204
  "CompositeCardBlock",
196
205
  "ContextCardBlock",
206
+ "DocumentEditor",
197
207
  "EditableTable",
198
208
  "EntityList",
199
209
  "Form",
@@ -632,6 +642,7 @@ function JuneRenderer(props) {
632
642
  isStreaming = false,
633
643
  mixedContent = true,
634
644
  renderText,
645
+ repair = true,
635
646
  theme,
636
647
  themeVars,
637
648
  className,
@@ -642,28 +653,15 @@ function JuneRenderer(props) {
642
653
  onAction,
643
654
  onError,
644
655
  onJuneError,
656
+ documents,
645
657
  loadingFallback = null,
646
658
  emptyFallback = null,
647
659
  errorFallback,
648
660
  resetKeys,
649
661
  ...rendererProps
650
662
  } = props;
651
- const latest = useRef({
652
- actions,
653
- confirmAction,
654
- parseActionEvent,
655
- onAction,
656
- onError,
657
- onJuneError
658
- });
659
- latest.current = {
660
- actions,
661
- confirmAction,
662
- parseActionEvent,
663
- onAction,
664
- onError,
665
- onJuneError
666
- };
663
+ const latest = useRef({ actions, confirmAction, parseActionEvent, onAction, onError, onJuneError });
664
+ latest.current = { actions, confirmAction, parseActionEvent, onAction, onError, onJuneError };
667
665
  const handleAction = useCallback((event) => {
668
666
  const l = latest.current;
669
667
  l.onAction?.(event);
@@ -677,17 +675,17 @@ function JuneRenderer(props) {
677
675
  }
678
676
  }, []);
679
677
  const handleParserErrors = useCallback((errors) => {
680
- const list = Array.isArray(errors) ? errors : [];
678
+ const list2 = Array.isArray(errors) ? errors : [];
681
679
  const l = latest.current;
682
- l.onError?.(list);
683
- const real = list.filter((e) => e?.severity !== "warning");
680
+ l.onError?.(list2);
681
+ const real = list2.filter((e) => e?.severity !== "warning");
684
682
  if (real.length > 0) {
685
683
  l.onJuneError?.(
686
684
  new JuneError("PARSE_ERROR", `OpenUI reported ${real.length} error(s)`, { details: real })
687
685
  );
688
686
  }
689
- if (list.length > 0 && !l.onError && !l.onJuneError) {
690
- console.warn("[june-ui] OpenUI reported errors:", list);
687
+ if (list2.length > 0 && !l.onError && !l.onJuneError) {
688
+ console.warn("[june-ui] OpenUI reported errors:", list2);
691
689
  }
692
690
  }, []);
693
691
  const handleBoundaryError = useCallback((error, info) => {
@@ -698,21 +696,32 @@ function JuneRenderer(props) {
698
696
  })
699
697
  );
700
698
  }, []);
699
+ const runtime = useMemo2(() => ({ isStreaming }), [isStreaming]);
700
+ const documentOptions = useMemo2(
701
+ () => ({
702
+ ...documents,
703
+ onError: (error) => {
704
+ documents?.onError?.(error);
705
+ latest.current.onJuneError?.(error);
706
+ }
707
+ }),
708
+ [documents]
709
+ );
701
710
  const parts = useMemo2(
702
711
  () => mixedContent && response ? splitResponse(response, { streaming: isStreaming }) : null,
703
712
  [mixedContent, response, isStreaming]
704
713
  );
705
714
  const uiText = useMemo2(() => {
706
715
  const raw = parts && !parts.pure ? parts.ui : response;
707
- if (!mixedContent || isStreaming || typeof raw !== "string" || raw.length === 0) return raw;
716
+ if (!repair || !mixedContent || isStreaming || typeof raw !== "string" || raw.length === 0) return raw;
708
717
  return normalizeProgram(raw);
709
- }, [parts, response, mixedContent, isStreaming]);
718
+ }, [parts, response, mixedContent, isStreaming, repair]);
710
719
  const hasUi = typeof uiText === "string" && uiText.trim().length > 0;
711
720
  const before = parts?.before ?? [];
712
721
  const after = parts?.after ?? [];
713
722
  const hasText = before.length + after.length > 0;
714
723
  const text = (value, index, key) => /* @__PURE__ */ jsx3(Fragment, { children: renderText ? renderText(value, index) : /* @__PURE__ */ jsx3("p", { className: "june-text", children: value }) }, key);
715
- return /* @__PURE__ */ jsx3(JuneThemeProvider, { mode: theme, vars: themeVars, className, style, children: /* @__PURE__ */ jsxs(
724
+ return /* @__PURE__ */ jsx3(JuneThemeProvider, { mode: theme, vars: themeVars, className, style, children: /* @__PURE__ */ jsx3(JuneRuntimeContext.Provider, { value: runtime, children: /* @__PURE__ */ jsx3(JuneDocumentContext.Provider, { value: documentOptions, children: /* @__PURE__ */ jsxs(
716
725
  JuneErrorBoundary,
717
726
  {
718
727
  fallback: errorFallback,
@@ -735,7 +744,7 @@ function JuneRenderer(props) {
735
744
  !hasUi && !hasText && (isStreaming ? loadingFallback : emptyFallback)
736
745
  ]
737
746
  }
738
- ) });
747
+ ) }) }) });
739
748
  }
740
749
 
741
750
  // src/components/library.ts
@@ -1058,33 +1067,1162 @@ function useJuneStream(options = {}) {
1058
1067
  );
1059
1068
  }
1060
1069
 
1061
- // src/core/JuneUI.tsx
1070
+ // src/components/document-editor/document-component.tsx
1071
+ import { defineComponent as defineComponent2 } from "@openuidev/react-lang";
1072
+ import { z } from "zod/v4";
1073
+
1074
+ // src/components/document-editor/document-draft.tsx
1075
+ import { jsx as jsx4, jsxs as jsxs2 } from "react/jsx-runtime";
1076
+ function DocumentDraft({ title, words, state }) {
1077
+ if (state === "empty") {
1078
+ return /* @__PURE__ */ jsx4("div", { className: "june-doc june-doc--draft", role: "alert", children: /* @__PURE__ */ jsx4("p", { className: "june-doc__draft-text", children: "No document content was received." }) });
1079
+ }
1080
+ return /* @__PURE__ */ jsxs2("div", { className: "june-doc june-doc--draft", role: "status", "aria-live": "polite", children: [
1081
+ title ? /* @__PURE__ */ jsx4("p", { className: "june-doc__draft-title", children: title }) : null,
1082
+ /* @__PURE__ */ jsx4("p", { className: "june-doc__draft-text", children: state === "drafting" ? `Drafting document\u2026${words ? ` ${words} words so far` : ""}` : "Loading editor\u2026" }),
1083
+ /* @__PURE__ */ jsxs2("div", { className: "june-doc__pulse", "aria-hidden": "true", children: [
1084
+ /* @__PURE__ */ jsx4("span", {}),
1085
+ /* @__PURE__ */ jsx4("span", {}),
1086
+ /* @__PURE__ */ jsx4("span", {})
1087
+ ] })
1088
+ ] });
1089
+ }
1090
+
1091
+ // src/components/document-editor/document-editor.tsx
1092
+ import { useEditor } from "@tiptap/react";
1093
+ import { useCallback as useCallback3, useEffect as useEffect2, useId, useMemo as useMemo4, useRef as useRef3, useState as useState3 } from "react";
1094
+
1095
+ // src/components/document-editor/document-content.tsx
1096
+ import { EditorContent } from "@tiptap/react";
1097
+ import { jsx as jsx5 } from "react/jsx-runtime";
1098
+ function DocumentContent({ editor }) {
1099
+ return /* @__PURE__ */ jsx5("div", { className: "june-doc__content", children: /* @__PURE__ */ jsx5(EditorContent, { editor }) });
1100
+ }
1101
+
1102
+ // src/components/document-editor/document-export.ts
1103
+ var escapeHtml = (value) => value.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
1104
+ var PRINT_CSS = 'body{font-family:system-ui,-apple-system,"Segoe UI",sans-serif;line-height:1.6;color:#111827;max-width:780px;margin:32px auto;padding:0 20px}h1,h2,h3{line-height:1.25}table{border-collapse:collapse;width:100%}th,td{border:1px solid #d1d5db;padding:6px 10px;text-align:left}blockquote{border-left:4px solid #d1d5db;margin:1em 0;padding-left:1em;color:#4b5563}pre,code{font-family:ui-monospace,Menlo,monospace;background:#f3f4f6}pre{padding:12px;overflow:auto}@media print{body{margin:0;max-width:none}}';
1105
+ function buildHtmlDocument(title, bodyHtml) {
1106
+ return `<!doctype html><html lang="en"><head><meta charset="utf-8"><title>${escapeHtml(
1107
+ title
1108
+ )}</title><style>${PRINT_CSS}</style></head><body><h1>${escapeHtml(title)}</h1>${bodyHtml}</body></html>`;
1109
+ }
1110
+ var textResult = (text, filename, mimeType) => ({
1111
+ filename,
1112
+ mimeType,
1113
+ text,
1114
+ blob: new Blob([text], { type: `${mimeType};charset=utf-8` })
1115
+ });
1116
+ var exportHtml = async (ctx) => {
1117
+ const { docToHtml: docToHtml2 } = await import("./document-engine-C6ILFMRP.js");
1118
+ return textResult(
1119
+ buildHtmlDocument(ctx.title, docToHtml2(ctx.json)),
1120
+ `${ctx.basename}.html`,
1121
+ "text/html"
1122
+ );
1123
+ };
1124
+ var exportMarkdown = async (ctx) => {
1125
+ const { docToMarkdown: docToMarkdown2 } = await import("./document-engine-C6ILFMRP.js");
1126
+ return textResult(
1127
+ `# ${ctx.title}
1128
+
1129
+ ${docToMarkdown2(ctx.json)}
1130
+ `,
1131
+ `${ctx.basename}.md`,
1132
+ "text/markdown"
1133
+ );
1134
+ };
1135
+ var exportTxt = async (ctx) => {
1136
+ const { docToText } = await import("./document-engine-C6ILFMRP.js");
1137
+ return textResult(`${ctx.title}
1138
+
1139
+ ${docToText(ctx.json)}
1140
+ `, `${ctx.basename}.txt`, "text/plain");
1141
+ };
1142
+ var ORDERED_REF = "june-ordered";
1143
+ var DOCX_MIME = "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
1144
+ function runs(d, node, fmt) {
1145
+ const out = [];
1146
+ for (const child of node.content ?? []) {
1147
+ if (child.type === "hardBreak") {
1148
+ out.push(new d.TextRun({ break: 1 }));
1149
+ continue;
1150
+ }
1151
+ if (child.type !== "text" || !child.text) continue;
1152
+ const marks = child.marks ?? [];
1153
+ const has = (type) => marks.some((m) => m.type === type);
1154
+ const link = marks.find((m) => m.type === "link");
1155
+ const run = new d.TextRun({
1156
+ text: child.text,
1157
+ bold: fmt.bold || has("bold") || void 0,
1158
+ italics: has("italic") || void 0,
1159
+ underline: has("underline") || link ? {} : void 0,
1160
+ strike: has("strike") || void 0,
1161
+ font: has("code") ? "Courier New" : void 0,
1162
+ color: link ? "0563C1" : void 0
1163
+ });
1164
+ const href = typeof link?.attrs?.href === "string" ? sanitizeHref(link.attrs.href) : null;
1165
+ out.push(href ? new d.ExternalHyperlink({ link: href, children: [run] }) : run);
1166
+ }
1167
+ return out;
1168
+ }
1169
+ function paragraph(d, node, fmt, extra = {}) {
1170
+ const align = node.attrs?.textAlign;
1171
+ return new d.Paragraph({
1172
+ children: runs(d, node, fmt),
1173
+ alignment: align === "center" ? d.AlignmentType.CENTER : align === "right" ? d.AlignmentType.RIGHT : align === "justify" ? d.AlignmentType.JUSTIFIED : void 0,
1174
+ indent: fmt.indent ? { left: fmt.indent } : void 0,
1175
+ border: fmt.quote ? { left: { color: "9CA3AF", space: 8, style: d.BorderStyle.SINGLE, size: 12 } } : void 0,
1176
+ spacing: { after: 120 },
1177
+ ...extra
1178
+ });
1179
+ }
1180
+ function list(d, node, fmt, level, state) {
1181
+ const ordered = node.type === "orderedList";
1182
+ const instance = ordered ? ++state.instance : 0;
1183
+ const out = [];
1184
+ for (const item of node.content ?? []) {
1185
+ let first = true;
1186
+ for (const child of item.content ?? []) {
1187
+ if (child.type === "bulletList" || child.type === "orderedList") {
1188
+ out.push(...list(d, child, fmt, level + 1, state));
1189
+ } else if (child.type === "paragraph" && first) {
1190
+ first = false;
1191
+ const lvl = Math.min(level, 2);
1192
+ out.push(
1193
+ paragraph(
1194
+ d,
1195
+ child,
1196
+ fmt,
1197
+ ordered ? { numbering: { reference: ORDERED_REF, level: lvl, instance } } : { bullet: { level: lvl } }
1198
+ )
1199
+ );
1200
+ } else {
1201
+ out.push(...blocks(d, [child], { ...fmt, indent: (fmt.indent ?? 0) + 720 * (level + 1) }, state));
1202
+ }
1203
+ }
1204
+ }
1205
+ return out;
1206
+ }
1207
+ function code(d, node) {
1208
+ const lines = (node.content ?? []).map((c) => c.text ?? "").join("").split("\n");
1209
+ return new d.Paragraph({
1210
+ children: lines.map((line, i) => new d.TextRun({ text: line, font: "Courier New", break: i ? 1 : void 0 })),
1211
+ spacing: { after: 120 },
1212
+ shading: { type: d.ShadingType.CLEAR, fill: "F3F4F6" }
1213
+ });
1214
+ }
1215
+ function table(d, node, state) {
1216
+ const rows = (node.content ?? []).map(
1217
+ (row) => new d.TableRow({
1218
+ children: (row.content ?? []).map((cell) => {
1219
+ const header = cell.type === "tableHeader";
1220
+ const children = blocks(d, cell.content, { bold: header }, state);
1221
+ return new d.TableCell({
1222
+ children: children.length ? children : [new d.Paragraph("")],
1223
+ shading: header ? { type: d.ShadingType.CLEAR, fill: "F3F4F6" } : void 0
1224
+ });
1225
+ })
1226
+ })
1227
+ );
1228
+ if (rows.length === 0) return new d.Paragraph("");
1229
+ return new d.Table({ rows, width: { size: 100, type: d.WidthType.PERCENTAGE } });
1230
+ }
1231
+ function blocks(d, nodes, fmt, state) {
1232
+ const headings = [d.HeadingLevel.HEADING_1, d.HeadingLevel.HEADING_2, d.HeadingLevel.HEADING_3];
1233
+ const out = [];
1234
+ for (const node of nodes ?? []) {
1235
+ switch (node.type) {
1236
+ case "paragraph":
1237
+ out.push(paragraph(d, node, fmt));
1238
+ break;
1239
+ case "heading": {
1240
+ const level = Math.min(Math.max(Number(node.attrs?.level) || 1, 1), 3);
1241
+ out.push(paragraph(d, node, fmt, { heading: headings[level - 1] }));
1242
+ break;
1243
+ }
1244
+ case "bulletList":
1245
+ case "orderedList":
1246
+ out.push(...list(d, node, fmt, 0, state));
1247
+ break;
1248
+ case "blockquote":
1249
+ out.push(...blocks(d, node.content, { ...fmt, quote: true, indent: (fmt.indent ?? 0) + 360 }, state));
1250
+ break;
1251
+ case "codeBlock":
1252
+ out.push(code(d, node));
1253
+ break;
1254
+ case "horizontalRule":
1255
+ out.push(
1256
+ new d.Paragraph({
1257
+ border: { bottom: { color: "9CA3AF", space: 1, style: d.BorderStyle.SINGLE, size: 6 } },
1258
+ spacing: { after: 120 }
1259
+ })
1260
+ );
1261
+ break;
1262
+ case "table":
1263
+ out.push(table(d, node, state));
1264
+ break;
1265
+ default:
1266
+ if (node.content) out.push(...blocks(d, node.content, fmt, state));
1267
+ }
1268
+ }
1269
+ return out;
1270
+ }
1271
+ var exportDocx = async (ctx) => {
1272
+ const d = await import("docx");
1273
+ const state = { instance: 0 };
1274
+ const children = [
1275
+ new d.Paragraph({ text: ctx.title, heading: d.HeadingLevel.TITLE }),
1276
+ ...blocks(d, ctx.json.content, {}, state)
1277
+ ];
1278
+ const doc = new d.Document({
1279
+ title: ctx.title,
1280
+ numbering: {
1281
+ config: [
1282
+ {
1283
+ reference: ORDERED_REF,
1284
+ levels: [0, 1, 2].map((level) => ({
1285
+ level,
1286
+ format: d.LevelFormat.DECIMAL,
1287
+ text: `%${level + 1}.`,
1288
+ alignment: d.AlignmentType.START,
1289
+ style: { paragraph: { indent: { left: 720 * (level + 1), hanging: 360 } } }
1290
+ }))
1291
+ }
1292
+ ]
1293
+ },
1294
+ sections: [{ children }]
1295
+ });
1296
+ const blob = await d.Packer.toBlob(doc);
1297
+ return { filename: `${ctx.basename}.docx`, mimeType: DOCX_MIME, blob };
1298
+ };
1299
+ function printHtml(html) {
1300
+ return new Promise((resolve, reject) => {
1301
+ const frame = document.createElement("iframe");
1302
+ frame.setAttribute("aria-hidden", "true");
1303
+ frame.style.cssText = "position:fixed;right:0;bottom:0;width:0;height:0;border:0;";
1304
+ const cleanup = () => setTimeout(() => frame.remove(), 500);
1305
+ frame.onload = () => {
1306
+ try {
1307
+ const win = frame.contentWindow;
1308
+ if (!win) throw new Error("The print frame is unavailable");
1309
+ win.addEventListener("afterprint", cleanup);
1310
+ win.focus();
1311
+ win.print();
1312
+ setTimeout(cleanup, 12e4);
1313
+ resolve();
1314
+ } catch (error) {
1315
+ cleanup();
1316
+ reject(error);
1317
+ }
1318
+ };
1319
+ frame.srcdoc = html;
1320
+ document.body.appendChild(frame);
1321
+ });
1322
+ }
1323
+ var exportPdf = async (ctx) => {
1324
+ const { docToHtml: docToHtml2 } = await import("./document-engine-C6ILFMRP.js");
1325
+ await printHtml(buildHtmlDocument(ctx.title, docToHtml2(ctx.json)));
1326
+ return { filename: `${ctx.basename}.pdf`, mimeType: "application/pdf", handled: true };
1327
+ };
1328
+ var registry = /* @__PURE__ */ new Map([
1329
+ ["html", exportHtml],
1330
+ ["markdown", exportMarkdown],
1331
+ ["txt", exportTxt],
1332
+ ["docx", exportDocx],
1333
+ ["pdf", exportPdf]
1334
+ ]);
1335
+ function registerDocumentExporter(format, exporter) {
1336
+ registry.set(format, exporter);
1337
+ }
1338
+ function listDocumentExporters() {
1339
+ return [...registry.keys()];
1340
+ }
1341
+ async function exportDocument(format, doc) {
1342
+ const exporter = registry.get(format);
1343
+ if (!exporter) throw new JuneError("EXPORT_ERROR", `No exporter is registered for "${format}"`);
1344
+ try {
1345
+ return await exporter({ ...doc, basename: slugify(doc.title) || "document" });
1346
+ } catch (error) {
1347
+ throw toJuneError(error, "EXPORT_ERROR", `Exporting ${format} failed`);
1348
+ }
1349
+ }
1350
+ function downloadResult(result) {
1351
+ if (!result.blob) return;
1352
+ const url = URL.createObjectURL(result.blob);
1353
+ const link = document.createElement("a");
1354
+ link.href = url;
1355
+ link.download = result.filename;
1356
+ document.body.appendChild(link);
1357
+ link.click();
1358
+ link.remove();
1359
+ setTimeout(() => URL.revokeObjectURL(url), 1e3);
1360
+ }
1361
+ async function copyDocumentToClipboard(doc) {
1362
+ const { docToHtml: docToHtml2, docToText } = await import("./document-engine-C6ILFMRP.js");
1363
+ const html = docToHtml2(doc.json);
1364
+ const text = `${doc.title}
1365
+
1366
+ ${docToText(doc.json)}`;
1367
+ try {
1368
+ if (typeof ClipboardItem !== "undefined" && navigator.clipboard?.write) {
1369
+ await navigator.clipboard.write([
1370
+ new ClipboardItem({
1371
+ "text/html": new Blob([html], { type: "text/html" }),
1372
+ "text/plain": new Blob([text], { type: "text/plain" })
1373
+ })
1374
+ ]);
1375
+ return true;
1376
+ }
1377
+ await navigator.clipboard.writeText(text);
1378
+ return true;
1379
+ } catch {
1380
+ return false;
1381
+ }
1382
+ }
1383
+
1384
+ // src/components/document-editor/document-merge.ts
1385
+ var MAX_CELLS = 4e6;
1386
+ function matchIndices(a, b) {
1387
+ const n = a.length;
1388
+ const m = b.length;
1389
+ if (n * m > MAX_CELLS) return null;
1390
+ const dp = Array.from({ length: n + 1 }, () => new Uint32Array(m + 1));
1391
+ for (let i2 = n - 1; i2 >= 0; i2--) {
1392
+ for (let j2 = m - 1; j2 >= 0; j2--) {
1393
+ dp[i2][j2] = a[i2] === b[j2] ? dp[i2 + 1][j2 + 1] + 1 : Math.max(dp[i2 + 1][j2], dp[i2][j2 + 1]);
1394
+ }
1395
+ }
1396
+ const matches = /* @__PURE__ */ new Map();
1397
+ let i = 0;
1398
+ let j = 0;
1399
+ while (i < n && j < m) {
1400
+ if (a[i] === b[j]) {
1401
+ matches.set(i, j);
1402
+ i++;
1403
+ j++;
1404
+ } else if (dp[i + 1][j] >= dp[i][j + 1]) i++;
1405
+ else j++;
1406
+ }
1407
+ return matches;
1408
+ }
1409
+ var same = (x, y) => x.length === y.length && x.every((v, i) => v === y[i]);
1410
+ function mergeBlocks(base, local, incoming) {
1411
+ if (same(local, base)) return { blocks: incoming, conflicts: 0 };
1412
+ if (same(incoming, base) || same(local, incoming)) return { blocks: local, conflicts: 0 };
1413
+ const ml = matchIndices(base, local);
1414
+ const mn = matchIndices(base, incoming);
1415
+ if (!ml || !mn) return { blocks: null, conflicts: 1 };
1416
+ const anchors = [...ml.keys()].filter((i) => mn.has(i)).sort((x, y) => x - y);
1417
+ const out = [];
1418
+ let conflicts = 0;
1419
+ let pb = -1;
1420
+ let pl = -1;
1421
+ let pn = -1;
1422
+ const region = (bEnd, lEnd, nEnd) => {
1423
+ const B = base.slice(pb + 1, bEnd);
1424
+ const L = local.slice(pl + 1, lEnd);
1425
+ const N = incoming.slice(pn + 1, nEnd);
1426
+ if (B.length === L.length && L.length === N.length) {
1427
+ for (let k = 0; k < B.length; k++) {
1428
+ if (L[k] === B[k]) out.push(N[k]);
1429
+ else if (N[k] === B[k] || N[k] === L[k]) out.push(L[k]);
1430
+ else {
1431
+ conflicts++;
1432
+ out.push(L[k]);
1433
+ }
1434
+ }
1435
+ return;
1436
+ }
1437
+ if (same(L, B)) out.push(...N);
1438
+ else if (same(N, B) || same(L, N)) out.push(...L);
1439
+ else {
1440
+ conflicts++;
1441
+ out.push(...L);
1442
+ }
1443
+ };
1444
+ for (const a of anchors) {
1445
+ const la = ml.get(a);
1446
+ const na = mn.get(a);
1447
+ region(a, la, na);
1448
+ out.push(local[la]);
1449
+ pb = a;
1450
+ pl = la;
1451
+ pn = na;
1452
+ }
1453
+ region(base.length, local.length, incoming.length);
1454
+ return { blocks: out, conflicts };
1455
+ }
1456
+ function mergeDocuments(base, local, incoming) {
1457
+ const toBlocks = (d) => (d.content ?? []).map((node) => JSON.stringify(node));
1458
+ const { blocks: blocks2, conflicts } = mergeBlocks(toBlocks(base), toBlocks(local), toBlocks(incoming));
1459
+ if (!blocks2) return { doc: local, conflicts: Math.max(1, conflicts) };
1460
+ if (blocks2.length === 0) return { doc: emptyDoc(), conflicts };
1461
+ return { doc: { type: "doc", content: blocks2.map((b) => JSON.parse(b)) }, conflicts };
1462
+ }
1463
+
1464
+ // src/components/document-editor/document-store.ts
1465
+ var incomingKey = (doc) => JSON.stringify([doc.title, docKey(doc.json)]);
1466
+ function createDocumentStore() {
1467
+ const records = /* @__PURE__ */ new Map();
1468
+ const listeners = /* @__PURE__ */ new Set();
1469
+ const emit = () => listeners.forEach((listener) => listener());
1470
+ const put = (record) => {
1471
+ records.set(record.id, record);
1472
+ emit();
1473
+ };
1474
+ const fresh2 = (doc) => ({
1475
+ id: doc.id,
1476
+ title: doc.title,
1477
+ documentType: doc.documentType,
1478
+ status: doc.status,
1479
+ json: doc.json,
1480
+ baseJson: doc.json,
1481
+ baseTitle: doc.title,
1482
+ lastIncomingKey: incomingKey(doc),
1483
+ revision: 0,
1484
+ origin: "external",
1485
+ pending: null,
1486
+ updatedAt: Date.now()
1487
+ });
1488
+ return {
1489
+ get: (id) => records.get(id),
1490
+ list: () => [...records.values()],
1491
+ subscribe: (listener) => {
1492
+ listeners.add(listener);
1493
+ return () => {
1494
+ listeners.delete(listener);
1495
+ };
1496
+ },
1497
+ receive(incoming) {
1498
+ const current = records.get(incoming.id);
1499
+ if (!current) {
1500
+ put(fresh2(incoming));
1501
+ return "created";
1502
+ }
1503
+ const key = incomingKey(incoming);
1504
+ if (current.lastIncomingKey === key) return "unchanged";
1505
+ const userEditedBody = docKey(current.json) !== docKey(current.baseJson);
1506
+ const userEditedTitle = current.title !== current.baseTitle;
1507
+ const title = userEditedTitle ? current.title : incoming.title;
1508
+ const meta = {
1509
+ documentType: incoming.documentType ?? current.documentType,
1510
+ status: incoming.status ?? current.status
1511
+ };
1512
+ if (!userEditedBody) {
1513
+ put({
1514
+ ...current,
1515
+ ...meta,
1516
+ title,
1517
+ baseTitle: incoming.title,
1518
+ json: incoming.json,
1519
+ baseJson: incoming.json,
1520
+ lastIncomingKey: key,
1521
+ revision: current.revision + 1,
1522
+ origin: "external",
1523
+ pending: null,
1524
+ updatedAt: Date.now()
1525
+ });
1526
+ return "applied";
1527
+ }
1528
+ const { doc, conflicts } = mergeDocuments(current.baseJson, current.json, incoming.json);
1529
+ if (conflicts === 0) {
1530
+ put({
1531
+ ...current,
1532
+ ...meta,
1533
+ title,
1534
+ baseTitle: incoming.title,
1535
+ json: doc,
1536
+ baseJson: incoming.json,
1537
+ lastIncomingKey: key,
1538
+ revision: current.revision + 1,
1539
+ origin: "external",
1540
+ pending: null,
1541
+ updatedAt: Date.now()
1542
+ });
1543
+ return "merged";
1544
+ }
1545
+ put({
1546
+ ...current,
1547
+ ...meta,
1548
+ lastIncomingKey: key,
1549
+ pending: { json: incoming.json, title: incoming.title, merged: doc, conflicts }
1550
+ });
1551
+ return "conflict";
1552
+ },
1553
+ hydrate(doc) {
1554
+ put(fresh2(doc));
1555
+ },
1556
+ edit(id, json, origin) {
1557
+ const current = records.get(id);
1558
+ if (!current || docKey(current.json) === docKey(json)) return;
1559
+ put({ ...current, json, origin, revision: current.revision + 1, updatedAt: Date.now() });
1560
+ },
1561
+ setTitle(id, title) {
1562
+ const current = records.get(id);
1563
+ if (!current || current.title === title) return;
1564
+ put({ ...current, title, updatedAt: Date.now() });
1565
+ },
1566
+ resolve(id, choice) {
1567
+ const current = records.get(id);
1568
+ const pending = current?.pending;
1569
+ if (!current || !pending) return;
1570
+ if (choice === "keep") {
1571
+ put({ ...current, baseJson: pending.json, baseTitle: pending.title, pending: null });
1572
+ return;
1573
+ }
1574
+ const json = choice === "merge" ? pending.merged : pending.json;
1575
+ const title = choice === "merge" ? current.title : pending.title;
1576
+ put({
1577
+ ...current,
1578
+ title,
1579
+ json,
1580
+ baseJson: pending.json,
1581
+ baseTitle: pending.title,
1582
+ revision: current.revision + 1,
1583
+ origin: "external",
1584
+ pending: null,
1585
+ updatedAt: Date.now()
1586
+ });
1587
+ },
1588
+ remove(id) {
1589
+ if (records.delete(id)) emit();
1590
+ }
1591
+ };
1592
+ }
1593
+ var defaultStore = null;
1594
+ function getDefaultDocumentStore() {
1595
+ if (!defaultStore) defaultStore = createDocumentStore();
1596
+ return defaultStore;
1597
+ }
1598
+
1599
+ // src/components/document-editor/document-title.tsx
1600
+ import { jsx as jsx6 } from "react/jsx-runtime";
1601
+ function DocumentTitle({ value, disabled, onChange }) {
1602
+ return /* @__PURE__ */ jsx6(
1603
+ "input",
1604
+ {
1605
+ className: "june-doc__title",
1606
+ "aria-label": "Document title",
1607
+ value,
1608
+ disabled,
1609
+ placeholder: "Untitled document",
1610
+ onChange: (e) => onChange(e.target.value)
1611
+ }
1612
+ );
1613
+ }
1614
+
1615
+ // src/components/document-editor/document-toolbar.tsx
1616
+ import { useEditorState } from "@tiptap/react";
1617
+ import { useState as useState2 } from "react";
1618
+ import { Fragment as Fragment2, jsx as jsx7, jsxs as jsxs3 } from "react/jsx-runtime";
1619
+ var FORMAT_LABELS = {
1620
+ html: "HTML",
1621
+ markdown: "Markdown",
1622
+ txt: "Plain text",
1623
+ docx: "Word (.docx)",
1624
+ pdf: "PDF (print)"
1625
+ };
1626
+ function Btn({ label, active, disabled, toggle, onClick, children }) {
1627
+ return /* @__PURE__ */ jsx7(
1628
+ "button",
1629
+ {
1630
+ type: "button",
1631
+ className: "june-doc__btn",
1632
+ "aria-label": label,
1633
+ title: label,
1634
+ "aria-pressed": toggle ? !!active : void 0,
1635
+ "data-active": active || void 0,
1636
+ disabled,
1637
+ onMouseDown: (e) => e.preventDefault(),
1638
+ onClick,
1639
+ children
1640
+ }
1641
+ );
1642
+ }
1643
+ function DocumentToolbar(props) {
1644
+ const { editor, editable, exportFormats, canSave, saveState, onExport, onCopy, onSave } = props;
1645
+ const [linkOpen, setLinkOpen] = useState2(false);
1646
+ const [linkValue, setLinkValue] = useState2("");
1647
+ const s = useEditorState({
1648
+ editor,
1649
+ selector: ({ editor: ed }) => ed ? {
1650
+ bold: ed.isActive("bold"),
1651
+ italic: ed.isActive("italic"),
1652
+ underline: ed.isActive("underline"),
1653
+ strike: ed.isActive("strike"),
1654
+ bullet: ed.isActive("bulletList"),
1655
+ ordered: ed.isActive("orderedList"),
1656
+ quote: ed.isActive("blockquote"),
1657
+ link: ed.isActive("link"),
1658
+ linkHref: ed.getAttributes("link").href ?? "",
1659
+ h1: ed.isActive("heading", { level: 1 }),
1660
+ h2: ed.isActive("heading", { level: 2 }),
1661
+ h3: ed.isActive("heading", { level: 3 }),
1662
+ left: ed.isActive({ textAlign: "left" }),
1663
+ center: ed.isActive({ textAlign: "center" }),
1664
+ right: ed.isActive({ textAlign: "right" }),
1665
+ justify: ed.isActive({ textAlign: "justify" }),
1666
+ inTable: ed.isActive("table"),
1667
+ canUndo: ed.can().undo(),
1668
+ canRedo: ed.can().redo()
1669
+ } : null
1670
+ });
1671
+ const run = () => editor?.chain().focus();
1672
+ const off = !editor || !editable;
1673
+ const heading = s?.h1 ? "1" : s?.h2 ? "2" : s?.h3 ? "3" : "p";
1674
+ const openLink = () => {
1675
+ setLinkValue(s?.linkHref ?? "");
1676
+ setLinkOpen(true);
1677
+ };
1678
+ const applyLink = () => {
1679
+ const href = sanitizeHref(linkValue);
1680
+ if (href) run()?.extendMarkRange("link").setLink({ href }).run();
1681
+ setLinkOpen(false);
1682
+ };
1683
+ const removeLink = () => {
1684
+ run()?.extendMarkRange("link").unsetLink().run();
1685
+ setLinkOpen(false);
1686
+ };
1687
+ return /* @__PURE__ */ jsxs3("div", { className: "june-doc__toolbar", role: "toolbar", "aria-label": "Document formatting", children: [
1688
+ editable ? /* @__PURE__ */ jsxs3(Fragment2, { children: [
1689
+ /* @__PURE__ */ jsxs3("div", { className: "june-doc__group", children: [
1690
+ /* @__PURE__ */ jsx7(Btn, { label: "Undo", disabled: off || !s?.canUndo, onClick: () => run()?.undo().run(), children: "\u21B6" }),
1691
+ /* @__PURE__ */ jsx7(Btn, { label: "Redo", disabled: off || !s?.canRedo, onClick: () => run()?.redo().run(), children: "\u21B7" })
1692
+ ] }),
1693
+ /* @__PURE__ */ jsx7("div", { className: "june-doc__group", children: /* @__PURE__ */ jsxs3(
1694
+ "select",
1695
+ {
1696
+ className: "june-doc__select",
1697
+ "aria-label": "Text style",
1698
+ disabled: off,
1699
+ value: heading,
1700
+ onChange: (e) => {
1701
+ const v = e.target.value;
1702
+ if (v === "p") run()?.setParagraph().run();
1703
+ else run()?.toggleHeading({ level: Number(v) }).run();
1704
+ },
1705
+ children: [
1706
+ /* @__PURE__ */ jsx7("option", { value: "p", children: "Paragraph" }),
1707
+ /* @__PURE__ */ jsx7("option", { value: "1", children: "Heading 1" }),
1708
+ /* @__PURE__ */ jsx7("option", { value: "2", children: "Heading 2" }),
1709
+ /* @__PURE__ */ jsx7("option", { value: "3", children: "Heading 3" })
1710
+ ]
1711
+ }
1712
+ ) }),
1713
+ /* @__PURE__ */ jsxs3("div", { className: "june-doc__group", children: [
1714
+ /* @__PURE__ */ jsx7(Btn, { label: "Bold", toggle: true, active: s?.bold, disabled: off, onClick: () => run()?.toggleBold().run(), children: /* @__PURE__ */ jsx7("b", { children: "B" }) }),
1715
+ /* @__PURE__ */ jsx7(Btn, { label: "Italic", toggle: true, active: s?.italic, disabled: off, onClick: () => run()?.toggleItalic().run(), children: /* @__PURE__ */ jsx7("i", { children: "I" }) }),
1716
+ /* @__PURE__ */ jsx7(Btn, { label: "Underline", toggle: true, active: s?.underline, disabled: off, onClick: () => run()?.toggleUnderline().run(), children: /* @__PURE__ */ jsx7("u", { children: "U" }) }),
1717
+ /* @__PURE__ */ jsx7(Btn, { label: "Strikethrough", toggle: true, active: s?.strike, disabled: off, onClick: () => run()?.toggleStrike().run(), children: /* @__PURE__ */ jsx7("s", { children: "S" }) })
1718
+ ] }),
1719
+ /* @__PURE__ */ jsxs3("div", { className: "june-doc__group", children: [
1720
+ /* @__PURE__ */ jsx7(Btn, { label: "Bullet list", toggle: true, active: s?.bullet, disabled: off, onClick: () => run()?.toggleBulletList().run(), children: "\u2022 List" }),
1721
+ /* @__PURE__ */ jsx7(Btn, { label: "Numbered list", toggle: true, active: s?.ordered, disabled: off, onClick: () => run()?.toggleOrderedList().run(), children: "1. List" }),
1722
+ /* @__PURE__ */ jsx7(Btn, { label: "Blockquote", toggle: true, active: s?.quote, disabled: off, onClick: () => run()?.toggleBlockquote().run(), children: "Quote" }),
1723
+ /* @__PURE__ */ jsx7(Btn, { label: "Link", toggle: true, active: s?.link, disabled: off, onClick: openLink, children: "Link" })
1724
+ ] }),
1725
+ /* @__PURE__ */ jsxs3("div", { className: "june-doc__group", children: [
1726
+ /* @__PURE__ */ jsx7(Btn, { label: "Align left", toggle: true, active: s?.left, disabled: off, onClick: () => run()?.setTextAlign("left").run(), children: "L" }),
1727
+ /* @__PURE__ */ jsx7(Btn, { label: "Align center", toggle: true, active: s?.center, disabled: off, onClick: () => run()?.setTextAlign("center").run(), children: "C" }),
1728
+ /* @__PURE__ */ jsx7(Btn, { label: "Align right", toggle: true, active: s?.right, disabled: off, onClick: () => run()?.setTextAlign("right").run(), children: "R" }),
1729
+ /* @__PURE__ */ jsx7(Btn, { label: "Justify", toggle: true, active: s?.justify, disabled: off, onClick: () => run()?.setTextAlign("justify").run(), children: "J" })
1730
+ ] }),
1731
+ /* @__PURE__ */ jsxs3("div", { className: "june-doc__group", children: [
1732
+ /* @__PURE__ */ jsx7(Btn, { label: "Insert table", disabled: off, onClick: () => run()?.insertTable({ rows: 3, cols: 3, withHeaderRow: true }).run(), children: "Table" }),
1733
+ s?.inTable ? /* @__PURE__ */ jsxs3(Fragment2, { children: [
1734
+ /* @__PURE__ */ jsx7(Btn, { label: "Add row below", disabled: off, onClick: () => run()?.addRowAfter().run(), children: "+Row" }),
1735
+ /* @__PURE__ */ jsx7(Btn, { label: "Add column right", disabled: off, onClick: () => run()?.addColumnAfter().run(), children: "+Col" }),
1736
+ /* @__PURE__ */ jsx7(Btn, { label: "Delete row", disabled: off, onClick: () => run()?.deleteRow().run(), children: "\u2212Row" }),
1737
+ /* @__PURE__ */ jsx7(Btn, { label: "Delete column", disabled: off, onClick: () => run()?.deleteColumn().run(), children: "\u2212Col" }),
1738
+ /* @__PURE__ */ jsx7(Btn, { label: "Delete table", disabled: off, onClick: () => run()?.deleteTable().run(), children: "Del table" })
1739
+ ] }) : null
1740
+ ] })
1741
+ ] }) : null,
1742
+ /* @__PURE__ */ jsxs3("div", { className: "june-doc__group june-doc__group--end", children: [
1743
+ /* @__PURE__ */ jsx7(Btn, { label: "Copy document", onClick: onCopy, children: "Copy" }),
1744
+ exportFormats.length > 0 ? /* @__PURE__ */ jsxs3(
1745
+ "select",
1746
+ {
1747
+ className: "june-doc__select",
1748
+ "aria-label": "Export document",
1749
+ value: "",
1750
+ onChange: (e) => e.target.value && onExport(e.target.value),
1751
+ children: [
1752
+ /* @__PURE__ */ jsx7("option", { value: "", children: "Export\u2026" }),
1753
+ exportFormats.map((f) => /* @__PURE__ */ jsx7("option", { value: f, children: FORMAT_LABELS[f] ?? f }, f))
1754
+ ]
1755
+ }
1756
+ ) : null,
1757
+ canSave ? /* @__PURE__ */ jsx7(Btn, { label: "Save", disabled: saveState === "saving" || saveState === "saved" || saveState === "idle", onClick: onSave, children: "Save" }) : null
1758
+ ] }),
1759
+ linkOpen ? /* @__PURE__ */ jsxs3("div", { className: "june-doc__linkbar", children: [
1760
+ /* @__PURE__ */ jsx7(
1761
+ "input",
1762
+ {
1763
+ "aria-label": "Link address",
1764
+ className: "june-doc__input",
1765
+ placeholder: "https://example.com",
1766
+ value: linkValue,
1767
+ autoFocus: true,
1768
+ onChange: (e) => setLinkValue(e.target.value),
1769
+ onKeyDown: (e) => {
1770
+ if (e.key === "Enter") applyLink();
1771
+ if (e.key === "Escape") setLinkOpen(false);
1772
+ }
1773
+ }
1774
+ ),
1775
+ /* @__PURE__ */ jsx7("button", { type: "button", className: "june-doc__btn", onClick: applyLink, children: "Apply" }),
1776
+ s?.link ? /* @__PURE__ */ jsx7("button", { type: "button", className: "june-doc__btn", onClick: removeLink, children: "Remove" }) : null,
1777
+ /* @__PURE__ */ jsx7("button", { type: "button", className: "june-doc__btn", onClick: () => setLinkOpen(false), children: "Cancel" })
1778
+ ] }) : null
1779
+ ] });
1780
+ }
1781
+
1782
+ // src/components/document-editor/document-types.ts
1783
+ var ALL_EXPORT_FORMATS = [
1784
+ "html",
1785
+ "markdown",
1786
+ "txt",
1787
+ "docx",
1788
+ "pdf"
1789
+ ];
1790
+
1791
+ // src/components/document-editor/document-editor.tsx
1792
+ import { jsx as jsx8, jsxs as jsxs4 } from "react/jsx-runtime";
1793
+ var snapshotOf = (r) => ({
1794
+ documentId: r.id,
1795
+ title: r.title,
1796
+ documentType: r.documentType,
1797
+ status: r.status,
1798
+ json: r.json
1799
+ });
1800
+ var SAVE_LABEL = {
1801
+ idle: "",
1802
+ dirty: "Unsaved changes",
1803
+ saving: "Saving\u2026",
1804
+ saved: "Saved",
1805
+ error: "Save failed"
1806
+ };
1807
+ function DocumentEditorImpl(props) {
1808
+ const {
1809
+ documentId,
1810
+ title: titleProp = "Untitled document",
1811
+ content,
1812
+ documentType,
1813
+ status = "draft",
1814
+ editable = true,
1815
+ exportFormats,
1816
+ theme = "auto",
1817
+ className
1818
+ } = props;
1819
+ const ctxOptions = useDocumentOptions();
1820
+ const options = useMemo4(() => ({ ...ctxOptions, ...props.options }), [ctxOptions, props.options]);
1821
+ const optionsRef = useRef3(options);
1822
+ optionsRef.current = options;
1823
+ const store = useMemo4(() => options.store ?? getDefaultDocumentStore(), [options.store]);
1824
+ const instanceId = useId();
1825
+ const { theme: contextTheme } = useJuneTheme();
1826
+ const resolvedTheme = theme === "auto" ? contextTheme : theme;
1827
+ const contentKey = typeof content === "string" ? content : content ? JSON.stringify(content) : "";
1828
+ const parsed = useMemo4(() => {
1829
+ if (!contentKey) return { json: null, error: null };
1830
+ try {
1831
+ return { json: parseDocumentContent(contentKey), error: null };
1832
+ } catch (e) {
1833
+ return { json: null, error: toJuneError(e, "DOCUMENT_ERROR") };
1834
+ }
1835
+ }, [contentKey]);
1836
+ useEffect2(() => {
1837
+ if (parsed.error) optionsRef.current.onError?.(parsed.error);
1838
+ }, [parsed.error]);
1839
+ const title = useDocumentValue(store, documentId, (r) => r?.title ?? titleProp);
1840
+ const pending = useDocumentValue(store, documentId, (r) => r?.pending ?? null);
1841
+ const words = useDocumentValue(store, documentId, (r) => r ? wordCountOf(r.json) : 0);
1842
+ const recordStatus = useDocumentValue(store, documentId, (r) => r?.status ?? status);
1843
+ const [saveState, setSaveState] = useState3("idle");
1844
+ const [notice, setNotice] = useState3(null);
1845
+ const lastSavedKey = useRef3("");
1846
+ const seenRevision = useRef3(store.get(documentId)?.revision ?? 0);
1847
+ const readyRef = useRef3(false);
1848
+ const flash = useCallback3((message) => {
1849
+ setNotice(message);
1850
+ }, []);
1851
+ useEffect2(() => {
1852
+ if (!notice) return;
1853
+ const t = setTimeout(() => setNotice(null), 3e3);
1854
+ return () => clearTimeout(t);
1855
+ }, [notice]);
1856
+ const emitChange = useCallback3(
1857
+ (source) => {
1858
+ const record = store.get(documentId);
1859
+ if (record) optionsRef.current.onDocumentChange?.({ ...snapshotOf(record), source });
1860
+ },
1861
+ [store, documentId]
1862
+ );
1863
+ const saveRef = useRef3(async () => {
1864
+ });
1865
+ const autosave = useMemo4(() => {
1866
+ const delay = options.autosaveDelay ?? 1500;
1867
+ return delay > 0 ? debounce(() => void saveRef.current(), delay) : null;
1868
+ }, [options.autosaveDelay]);
1869
+ useEffect2(() => () => autosave?.flush(), [autosave]);
1870
+ saveRef.current = async () => {
1871
+ const record = store.get(documentId);
1872
+ const onSave = optionsRef.current.onSave;
1873
+ if (!record || !onSave) return;
1874
+ const key = JSON.stringify([record.title, docKey(record.json)]);
1875
+ if (key === lastSavedKey.current) {
1876
+ setSaveState("saved");
1877
+ return;
1878
+ }
1879
+ setSaveState("saving");
1880
+ try {
1881
+ await onSave({
1882
+ ...snapshotOf(record),
1883
+ html: docToHtml(record.json),
1884
+ markdown: docToMarkdown(record.json)
1885
+ });
1886
+ lastSavedKey.current = key;
1887
+ const latest = store.get(documentId);
1888
+ const latestKey = latest ? JSON.stringify([latest.title, docKey(latest.json)]) : key;
1889
+ setSaveState(latestKey === key ? "saved" : "dirty");
1890
+ } catch (error) {
1891
+ setSaveState("error");
1892
+ optionsRef.current.onError?.(toJuneError(error, "DOCUMENT_ERROR", "Saving the document failed"));
1893
+ }
1894
+ };
1895
+ const markDirty = useCallback3(() => {
1896
+ if (!optionsRef.current.onSave) return;
1897
+ setSaveState("dirty");
1898
+ autosave?.();
1899
+ }, [autosave]);
1900
+ const [initialJson] = useState3(() => store.get(documentId)?.json ?? parsed.json ?? emptyDoc());
1901
+ const extensions = useMemo4(() => createDocumentExtensions(), []);
1902
+ const onUpdateRef = useRef3(() => {
1903
+ });
1904
+ onUpdateRef.current = (json) => {
1905
+ store.edit(documentId, json, instanceId);
1906
+ emitChange("user");
1907
+ markDirty();
1908
+ };
1909
+ const editor = useEditor({
1910
+ extensions,
1911
+ content: initialJson,
1912
+ editable,
1913
+ immediatelyRender: false,
1914
+ editorProps: {
1915
+ attributes: {
1916
+ class: "june-doc__prose",
1917
+ role: "textbox",
1918
+ "aria-multiline": "true",
1919
+ "aria-label": "Document content"
1920
+ }
1921
+ },
1922
+ onUpdate: ({ editor: ed }) => onUpdateRef.current(ed.getJSON())
1923
+ });
1924
+ useEffect2(() => {
1925
+ editor?.setEditable(editable);
1926
+ }, [editor, editable]);
1927
+ useEffect2(() => {
1928
+ if (!parsed.json) return;
1929
+ const outcome = store.receive({
1930
+ id: documentId,
1931
+ title: titleProp,
1932
+ json: parsed.json,
1933
+ documentType,
1934
+ status
1935
+ });
1936
+ if (outcome === "applied" || outcome === "merged") {
1937
+ emitChange(outcome === "applied" ? "ai" : "merge");
1938
+ markDirty();
1939
+ } else if (outcome === "conflict") {
1940
+ const record = store.get(documentId);
1941
+ optionsRef.current.onConflict?.({
1942
+ documentId,
1943
+ title: record?.title ?? titleProp,
1944
+ conflicts: record?.pending?.conflicts ?? 1
1945
+ });
1946
+ }
1947
+ }, [store, documentId, titleProp, parsed.json, documentType, status, emitChange, markDirty]);
1948
+ useEffect2(() => {
1949
+ if (!editor) return;
1950
+ const apply = () => {
1951
+ const record = store.get(documentId);
1952
+ if (!record || record.revision === seenRevision.current) return;
1953
+ seenRevision.current = record.revision;
1954
+ if (record.origin === instanceId) return;
1955
+ const { from, to } = editor.state.selection;
1956
+ editor.commands.setContent(record.json, { emitUpdate: false });
1957
+ if (editor.isFocused) {
1958
+ const size = editor.state.doc.content.size;
1959
+ editor.commands.setTextSelection({ from: Math.min(from, size), to: Math.min(to, size) });
1960
+ }
1961
+ };
1962
+ apply();
1963
+ return store.subscribe(apply);
1964
+ }, [editor, store, documentId, instanceId]);
1965
+ useEffect2(() => {
1966
+ if (!editor || readyRef.current) return;
1967
+ const record = store.get(documentId);
1968
+ if (!record) return;
1969
+ readyRef.current = true;
1970
+ lastSavedKey.current = JSON.stringify([record.title, docKey(record.json)]);
1971
+ optionsRef.current.onDocumentReady?.(snapshotOf(record));
1972
+ }, [editor, store, documentId, title]);
1973
+ const handleTitle = (value) => {
1974
+ store.setTitle(documentId, value);
1975
+ emitChange("user");
1976
+ markDirty();
1977
+ };
1978
+ const resolve = (choice) => {
1979
+ store.resolve(documentId, choice);
1980
+ if (choice !== "keep") {
1981
+ emitChange(choice === "merge" ? "merge" : "resolve");
1982
+ markDirty();
1983
+ }
1984
+ };
1985
+ const handleExport = async (format) => {
1986
+ const record = store.get(documentId);
1987
+ if (!record) return;
1988
+ try {
1989
+ const result = await exportDocument(format, {
1990
+ documentId,
1991
+ title: record.title,
1992
+ json: record.json
1993
+ // always the latest editor content
1994
+ });
1995
+ if (result.blob) downloadResult(result);
1996
+ optionsRef.current.onExport?.({ documentId, format, ...result });
1997
+ } catch (error) {
1998
+ optionsRef.current.onError?.(toJuneError(error, "EXPORT_ERROR"));
1999
+ flash("Export failed");
2000
+ }
2001
+ };
2002
+ const handleCopy = async () => {
2003
+ const record = store.get(documentId);
2004
+ if (!record) return;
2005
+ flash(await copyDocumentToClipboard({ title: record.title, json: record.json }) ? "Copied" : "Copy failed");
2006
+ };
2007
+ const formats = (exportFormats ?? [...ALL_EXPORT_FORMATS]).filter((f) => listDocumentExporters().includes(f));
2008
+ if (parsed.error && !store.get(documentId)) {
2009
+ return /* @__PURE__ */ jsxs4("div", { className: "june-doc june-doc--error", "data-theme": resolvedTheme, role: "alert", children: [
2010
+ /* @__PURE__ */ jsx8("p", { className: "june-doc__draft-text", children: "This document could not be displayed." }),
2011
+ /* @__PURE__ */ jsxs4("details", { children: [
2012
+ /* @__PURE__ */ jsx8("summary", { children: "Show raw content" }),
2013
+ /* @__PURE__ */ jsx8("pre", { className: "june-doc__raw", children: contentKey })
2014
+ ] })
2015
+ ] });
2016
+ }
2017
+ if (!editor) return /* @__PURE__ */ jsx8(DocumentDraft, { title, state: "loading" });
2018
+ const isDraft = recordStatus === "draft";
2019
+ return /* @__PURE__ */ jsxs4(
2020
+ "div",
2021
+ {
2022
+ className: className ? `june-doc ${className}` : "june-doc",
2023
+ "data-theme": resolvedTheme,
2024
+ "data-status": recordStatus,
2025
+ onKeyDown: (e) => {
2026
+ if ((e.ctrlKey || e.metaKey) && e.key.toLowerCase() === "s" && options.onSave) {
2027
+ e.preventDefault();
2028
+ void saveRef.current();
2029
+ }
2030
+ },
2031
+ children: [
2032
+ /* @__PURE__ */ jsxs4("div", { className: "june-doc__header", children: [
2033
+ /* @__PURE__ */ jsx8(DocumentTitle, { value: title, disabled: !editable, onChange: handleTitle }),
2034
+ isDraft ? /* @__PURE__ */ jsx8("span", { className: "june-doc__badge", children: "AI draft" }) : null
2035
+ ] }),
2036
+ pending ? /* @__PURE__ */ jsxs4("div", { className: "june-doc__banner", role: "status", children: [
2037
+ /* @__PURE__ */ jsxs4("span", { children: [
2038
+ "The assistant suggested changes that overlap your edits (",
2039
+ pending.conflicts,
2040
+ " ",
2041
+ pending.conflicts === 1 ? "section" : "sections",
2042
+ ")."
2043
+ ] }),
2044
+ /* @__PURE__ */ jsxs4("span", { className: "june-doc__banner-actions", children: [
2045
+ /* @__PURE__ */ jsx8("button", { type: "button", className: "june-doc__btn", onClick: () => resolve("merge"), children: "Merge, keep my edits" }),
2046
+ /* @__PURE__ */ jsx8("button", { type: "button", className: "june-doc__btn", onClick: () => resolve("replace"), children: "Use AI version" }),
2047
+ /* @__PURE__ */ jsx8("button", { type: "button", className: "june-doc__btn", onClick: () => resolve("keep"), children: "Keep mine" })
2048
+ ] })
2049
+ ] }) : null,
2050
+ /* @__PURE__ */ jsx8(
2051
+ DocumentToolbar,
2052
+ {
2053
+ editor,
2054
+ editable,
2055
+ exportFormats: formats,
2056
+ canSave: !!options.onSave,
2057
+ saveState,
2058
+ onExport: (f) => void handleExport(f),
2059
+ onCopy: () => void handleCopy(),
2060
+ onSave: () => void saveRef.current()
2061
+ }
2062
+ ),
2063
+ /* @__PURE__ */ jsx8(DocumentContent, { editor }),
2064
+ /* @__PURE__ */ jsxs4("div", { className: "june-doc__footer", "aria-live": "polite", children: [
2065
+ /* @__PURE__ */ jsxs4("span", { children: [
2066
+ words,
2067
+ " words"
2068
+ ] }),
2069
+ /* @__PURE__ */ jsx8("span", { children: notice ?? SAVE_LABEL[saveState] })
2070
+ ] })
2071
+ ]
2072
+ }
2073
+ );
2074
+ }
2075
+
2076
+ // src/components/document-editor/document-component.tsx
2077
+ import { jsx as jsx9 } from "react/jsx-runtime";
2078
+ var DOCUMENT_COMPONENT_DESCRIPTION = 'Custom component. An editable document. DocumentEditor(documentId, title, content, documentType?, status?, editable?, exportFormats?). Place it in the root container (Card or Stack). "content" is the full document body as one Markdown string. Reuse documentId when revising the same document. Use it only when the user asks to create or revise a document.';
2079
+ var documentProps = z.object({
2080
+ documentId: z.string().describe("Stable id. Reuse it when revising the same document."),
2081
+ title: z.string().describe("Document title. Do not repeat it as a heading in content."),
2082
+ content: z.string().describe("The whole document body as Markdown."),
2083
+ documentType: z.string().optional().describe("Kind of document, such as proposal, contract or invoice."),
2084
+ status: z.string().optional().describe('Use "draft" for generated documents.'),
2085
+ editable: z.boolean().optional().describe("Whether the user can edit. Defaults to true."),
2086
+ exportFormats: z.array(z.string()).optional().describe("Export formats to offer, such as html, markdown, docx.")
2087
+ });
2088
+ function DocumentEditor(props) {
2089
+ const { isStreaming } = useJuneRuntime();
2090
+ if (props.generating || isStreaming) {
2091
+ return /* @__PURE__ */ jsx9(DocumentDraft, { title: props.title, state: "drafting" });
2092
+ }
2093
+ return /* @__PURE__ */ jsx9(DocumentEditorImpl, { ...props });
2094
+ }
2095
+ function OpenUIDocument({ props }) {
2096
+ return /* @__PURE__ */ jsx9(
2097
+ DocumentEditor,
2098
+ {
2099
+ documentId: props.documentId,
2100
+ title: props.title,
2101
+ content: props.content,
2102
+ documentType: props.documentType,
2103
+ status: props.status,
2104
+ editable: props.editable,
2105
+ exportFormats: props.exportFormats
2106
+ }
2107
+ );
2108
+ }
2109
+ var JuneDocumentEditorComponent = defineComponent2({
2110
+ name: "DocumentEditor",
2111
+ description: DOCUMENT_COMPONENT_DESCRIPTION,
2112
+ props: documentProps,
2113
+ component: OpenUIDocument
2114
+ });
2115
+ function withDocumentEditor(library) {
2116
+ return library.extend({
2117
+ components: {
2118
+ add: [{ component: JuneDocumentEditorComponent, slots: ["Card"] }]
2119
+ }
2120
+ });
2121
+ }
2122
+
2123
+ // src/components/document-editor/document-instructions.ts
2124
+ var DEFAULT_TYPES = [
2125
+ "proposal",
2126
+ "report",
2127
+ "email",
2128
+ "letter",
2129
+ "invoice",
2130
+ "contract",
2131
+ "NDA",
2132
+ "memo",
2133
+ "meeting notes"
2134
+ ];
2135
+ function getDocumentEditorRules(options = {}) {
2136
+ const name = options.componentName ?? "DocumentEditor";
2137
+ const types = (options.documentTypes ?? DEFAULT_TYPES).join(", ");
2138
+ return [
2139
+ `WHEN TO USE ${name}: use it only when the user asks you to create, draft, write, prepare, generate or revise an editable document (${types}, or similar). Put the finished document inside ${name}.`,
2140
+ `WHEN NOT TO USE ${name}: for explanations ("explain what an NDA is"), factual answers, comparisons, brainstorming and general questions, answer with normal text and the other components. Never open ${name} for those.`,
2141
+ `${name}(documentId, title, content, documentType?, status?, editable?, exportFormats?): "content" is the whole document body as Markdown inside ONE double-quoted string. Write line breaks as \\n and escape double quotes as \\". Supported Markdown: headings (#, ##, ###), paragraphs, **bold**, *italic*, lists, > quotes, [links](https://...), and tables.`,
2142
+ `Do not repeat the title as a heading inside "content"; the title is shown separately. Structure the document with headings, short paragraphs and tables where useful. Keep a professional tone.`,
2143
+ `EDITING: when the user asks to change an existing document (add a section, rewrite a part, change the title), write ${name} again with the SAME documentId and the COMPLETE updated content, starting from the current document text you were given. Copy every unchanged section exactly as it was. Change only what was requested. The app merges your version with the user's own edits.`,
2144
+ `If the user asks for a document but leaves out details, write the document anyway and use clear placeholders such as [CLIENT NAME], [DATE], [AMOUNT]. Do not stop to ask unless the request is impossible to interpret.`,
2145
+ `Never invent legal, financial or business facts, prices, dates, names or figures. Use placeholders instead. Set status to "draft" for generated documents, and for legal or financial documents say in one short sentence outside the component that the document is a draft that should be reviewed by a professional.`,
2146
+ `You may add one short sentence before or after the component. Do not repeat the document text outside the component.`,
2147
+ ...options.extraRules ?? []
2148
+ ];
2149
+ }
2150
+ function getDocumentEditorInstructions(options = {}) {
2151
+ const rules = getDocumentEditorRules(options);
2152
+ return ["Document drafting:", ...rules.map((rule, i) => `${i + 1}. ${rule}`)].join("\n");
2153
+ }
2154
+ var EXAMPLE_NEW = 'root = Stack([doc])\ndoc = DocumentEditor("business-proposal", "Business Proposal", "## Executive Summary\\n\\nThis proposal outlines [SERVICE] for [CLIENT NAME].\\n\\n## Scope of Work\\n\\n- Discovery\\n- Delivery\\n\\n## Pricing\\n\\n| Item | Cost |\\n| --- | --- |\\n| Discovery | [AMOUNT] |", "proposal", "draft")';
2155
+ var EXAMPLE_EDIT = 'root = Stack([doc])\ndoc = DocumentEditor("business-proposal", "Business Proposal", "## Executive Summary\\n\\nThis proposal outlines [SERVICE] for [CLIENT NAME].\\n\\n## Scope of Work\\n\\n- Discovery\\n- Delivery\\n\\n## Pricing\\n\\n| Item | Cost |\\n| --- | --- |\\n| Discovery | [AMOUNT] |\\n| Delivery | [AMOUNT] |", "proposal", "draft")';
2156
+ function documentPromptOptions(options = {}) {
2157
+ return {
2158
+ additionalRules: getDocumentEditorRules(options),
2159
+ examples: [EXAMPLE_NEW, EXAMPLE_EDIT]
2160
+ };
2161
+ }
2162
+
2163
+ // src/components/document-editor/document-agent.ts
2164
+ var attr = (value) => value.replace(/"/g, "&quot;");
2165
+ async function serializeDocumentsForAgent(options = {}) {
2166
+ const store = options.store ?? getDefaultDocumentStore();
2167
+ const { docToMarkdown: docToMarkdown2 } = await import("./document-engine-C6ILFMRP.js");
2168
+ return store.list().filter((r) => !options.ids || options.ids.includes(r.id)).map(
2169
+ (r) => `<document id="${attr(r.id)}" title="${attr(r.title)}"${r.documentType ? ` type="${attr(r.documentType)}"` : ""}>
2170
+ ${docToMarkdown2(r.json)}
2171
+ </document>`
2172
+ ).join("\n\n");
2173
+ }
2174
+
2175
+ // src/components/june-library.ts
1062
2176
  import { openuiLibrary } from "@openuidev/react-ui";
1063
- import { jsx as jsx4 } from "react/jsx-runtime";
1064
- function JuneUI({ library = openuiLibrary, ...props }) {
1065
- return /* @__PURE__ */ jsx4(JuneRenderer, { library, ...props });
2177
+ var juneLibrary = withDocumentEditor(openuiLibrary);
2178
+
2179
+ // src/core/JuneUI.tsx
2180
+ import { jsx as jsx10 } from "react/jsx-runtime";
2181
+ function JuneUI({ library = juneLibrary, ...props }) {
2182
+ return /* @__PURE__ */ jsx10(JuneRenderer, { library, ...props });
1066
2183
  }
1067
2184
  export {
2185
+ ALL_EXPORT_FORMATS,
2186
+ DocumentEditor,
2187
+ JuneDocumentContext,
2188
+ JuneDocumentEditorComponent,
1068
2189
  JuneError,
1069
2190
  JuneErrorBoundary,
1070
2191
  JuneRenderer,
2192
+ JuneRuntimeContext,
1071
2193
  JuneThemeProvider,
1072
2194
  JuneUI,
1073
2195
  consumeStream,
2196
+ copyDocumentToClipboard,
1074
2197
  createActionHandler,
2198
+ createDocumentStore,
1075
2199
  createJuneLibrary,
1076
2200
  darkTheme,
1077
2201
  defaultParseActionEvent,
1078
2202
  defineJuneAction,
1079
2203
  defineJuneComponent,
2204
+ documentPromptOptions,
2205
+ downloadResult,
2206
+ exportDocument,
1080
2207
  fetchStream,
2208
+ getDefaultDocumentStore,
2209
+ getDocumentEditorInstructions,
2210
+ getDocumentEditorRules,
1081
2211
  isJuneError,
1082
2212
  jsonFieldExtractor,
2213
+ juneLibrary,
1083
2214
  lightTheme,
2215
+ listDocumentExporters,
2216
+ mergeDocuments,
2217
+ registerDocumentExporter,
1084
2218
  runAction,
2219
+ serializeDocumentsForAgent,
1085
2220
  sseToText,
1086
2221
  toJuneError,
2222
+ useDocumentOptions,
2223
+ useJuneRuntime,
1087
2224
  useJuneStream,
1088
2225
  useJuneTheme,
1089
- useResolvedTheme
2226
+ useResolvedTheme,
2227
+ withDocumentEditor
1090
2228
  };