@collabchron/notiq 1.1.12 → 1.2.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.
Files changed (146) hide show
  1. package/dist/AICommandBarPlugin-ZEC755KY.mjs +27 -0
  2. package/dist/{AIDialog-RHRYHSVN.mjs → AIDialog-HJW6PQPR.mjs} +11 -12
  3. package/dist/{AudioComponent-CKLMLB5T.mjs → AudioComponent-W5XMZPQB.mjs} +10 -6
  4. package/dist/{DynamicBlockComponent-2LOADZUX.mjs → DynamicBlockComponent-CHRL2GAQ.mjs} +7 -6
  5. package/dist/{EquationComponent-4NFG55NQ.mjs → EquationComponent-GNQHG53L.mjs} +26 -7
  6. package/dist/{ExcalidrawComponent-BMSYIPP6.mjs → ExcalidrawComponent-POMYXDSG.mjs} +33 -6
  7. package/dist/{FileComponent-Y56MX5QD.mjs → FileComponent-EOVCH4V5.mjs} +9 -5
  8. package/dist/{HintComponet-ET7M2Q7S.mjs → HintComponet-QXL5ESND.mjs} +32 -8
  9. package/dist/{InlineImageComponent-FVTA4LXZ.mjs → InlineImageComponent-KDN3VGZC.mjs} +8 -3
  10. package/dist/{StoryBuilderComponent-JN4ZPZOW.mjs → StoryBuilderComponent-CBRFPFTR.mjs} +8 -9
  11. package/dist/{chunk-6UVNHT3T.mjs → chunk-4SYRK2NH.mjs} +23 -1
  12. package/dist/chunk-5CJZC5IB.mjs +9086 -0
  13. package/dist/{chunk-FO7M3X2B.mjs → chunk-6NK5DONB.mjs} +1 -1
  14. package/dist/{chunk-N6ILV6NF.mjs → chunk-ACW4DLVO.mjs} +21 -7
  15. package/dist/chunk-BCGD2YXP.mjs +574 -0
  16. package/dist/{chunk-TC3IISJZ.mjs → chunk-BTR3TPIN.mjs} +18 -5
  17. package/dist/{chunk-ZYJ7KABY.mjs → chunk-CQCS5YPS.mjs} +3 -5
  18. package/dist/{chunk-T2UBAZ66.mjs → chunk-D4UBNSUW.mjs} +1 -1
  19. package/dist/{chunk-KNW2CGIP.mjs → chunk-DBRZIA43.mjs} +4 -1
  20. package/dist/{chunk-CDAMHK63.mjs → chunk-GJK2L7ZM.mjs} +23 -2
  21. package/dist/{chunk-ELBTVBTS.mjs → chunk-IKYVBTCJ.mjs} +43 -20
  22. package/dist/chunk-IXRA5D53.mjs +10447 -0
  23. package/dist/{chunk-W6VQSFE5.mjs → chunk-J2CEQXG4.mjs} +1 -1
  24. package/dist/{chunk-43Z4Z2KD.mjs → chunk-JTNLN4JI.mjs} +1 -1
  25. package/dist/{chunk-OE5JRLCN.mjs → chunk-ONOHG5NB.mjs} +6 -4
  26. package/dist/{chunk-QNIY45SF.mjs → chunk-OO42URWA.mjs} +27 -6
  27. package/dist/chunk-PBVRSNGU.mjs +129 -0
  28. package/dist/chunk-QCS57TIF.mjs +1794 -0
  29. package/dist/chunk-RNEIJRUS.mjs +60 -0
  30. package/dist/chunk-TJPTGECP.mjs +1556 -0
  31. package/dist/{chunk-XYMXGU4T.mjs → chunk-TMYRA2W4.mjs} +1 -1
  32. package/dist/{chunk-ZFV2HGD3.mjs → chunk-UNEFOZTS.mjs} +1 -1
  33. package/dist/chunk-X4NI7EQS.mjs +282 -0
  34. package/dist/{chunk-5D4JF3ZZ.mjs → chunk-XAJ4GACN.mjs} +171 -49
  35. package/dist/{chunk-7QRJVZQY.mjs → chunk-YVUQRJVV.mjs} +63 -18
  36. package/dist/components/editor/index.d.ts +1 -1
  37. package/dist/components/editor/nodes/EquationNode/EquationNode.d.ts +1 -0
  38. package/dist/components/editor/nodes/Hint/index.d.ts +2 -1
  39. package/dist/components/editor/plugins/AICommandBarPlugin/index.d.ts +73 -1
  40. package/dist/components/editor/plugins/DraggableBlockPlugin/index.d.ts +25 -3
  41. package/dist/components/editor/plugins/InlineCopilotPlugin/index.d.ts +16 -3
  42. package/dist/components/editor/plugins/LinkWithMetaData/index.d.ts +20 -25
  43. package/dist/components/editor/plugins/MarkdownPastePlugin/index.d.ts +5 -0
  44. package/dist/components/editor/plugins/MarkdownTransformers/index.d.ts +2 -0
  45. package/dist/components/editor/plugins/SlashCommand/index.d.ts +18 -1
  46. package/dist/components/editor/plugins/SmartTypographyPlugin/index.d.ts +26 -0
  47. package/dist/components/editor/utils/aiStream.d.ts +27 -0
  48. package/dist/components/editor/utils/excalidrawDiagramBuilder.d.ts +29 -0
  49. package/dist/components/editor/utils/markdownTransformers.d.ts +4 -1
  50. package/dist/components/editor/utils/url.d.ts +16 -4
  51. package/dist/components/providers/AIContext.d.ts +8 -0
  52. package/dist/components/ui/equation/equationTypography.d.ts +23 -0
  53. package/dist/core/extension.d.ts +3 -1
  54. package/dist/core/extensions/blocks-kit.d.ts +22 -1
  55. package/dist/core/extensions/copilot-and-collab.d.ts +15 -1
  56. package/dist/core/react/NotiqContent.d.ts +4 -1
  57. package/dist/core/react/index.d.ts +1 -0
  58. package/dist/core/react/node-renderers.d.ts +73 -0
  59. package/dist/core.js +15429 -13116
  60. package/dist/core.mjs +47 -39
  61. package/dist/hooks/instructions-messages.d.ts +13 -4
  62. package/dist/{image-QPB2CVXP.mjs → image-AL6PHM2A.mjs} +17 -12
  63. package/dist/index.js +15526 -13194
  64. package/dist/index.mjs +64 -60
  65. package/dist/{insert-audio-I3PD6JFS.mjs → insert-audio-CRWR7EO5.mjs} +4 -6
  66. package/dist/{insert-file-PHR7XL4V.mjs → insert-file-I73AZW3L.mjs} +4 -6
  67. package/dist/{insert-gif-R5ZO4JHC.mjs → insert-gif-KWRC3ACT.mjs} +1 -1
  68. package/dist/{insert-image-PLBZELHK.mjs → insert-image-XIY6BGW5.mjs} +4 -3
  69. package/dist/{insert-poll-6BCIFY5G.mjs → insert-poll-J5YVZNZ4.mjs} +4 -3
  70. package/dist/{insert-table-ZRJP6X52.mjs → insert-table-OIMJRFFK.mjs} +1 -1
  71. package/dist/{poll-component-VHMM5KKZ.mjs → poll-component-TVHXIKGQ.mjs} +3 -2
  72. package/dist/react.js +14747 -12554
  73. package/dist/react.mjs +40 -38
  74. package/dist/{stepper-KNITDVLG.mjs → stepper-ILF7YXTO.mjs} +63 -73
  75. package/dist/styles/notiq.css +1 -1
  76. package/package.json +2 -2
  77. package/src/styles/notiq.css +20 -0
  78. package/dist/AICommandBarPlugin-TADJ3X2Y.mjs +0 -12
  79. package/dist/CodeActionMenuPlugin-FGH6HZLL.mjs +0 -14
  80. package/dist/CollaborationPlugin-TIZOQBUT.mjs +0 -405
  81. package/dist/CollaboratorsBar-AMPIAUOY.mjs +0 -20
  82. package/dist/CommentsPlugin-SDJJTUGK.mjs +0 -19
  83. package/dist/ExcalidrawPlugin-QLPGJPSX.mjs +0 -14
  84. package/dist/ExportPlugin-MJHYKQZJ.mjs +0 -43
  85. package/dist/FloatingLinkEditorPlugin-MABB34L7.mjs +0 -12
  86. package/dist/FloatingTextFormatToolbarPlugin-BXCPN3KD.mjs +0 -45
  87. package/dist/InlineCopilotPlugin-PNS5Y6OO.mjs +0 -360
  88. package/dist/MobileToolbar-KV5DX4ED.mjs +0 -982
  89. package/dist/SlashCommand-SPR7G5EI.mjs +0 -39
  90. package/dist/TableCellActionMenuPlugin-YWBA64J7.mjs +0 -838
  91. package/dist/TableHoverActionsPlugin-2EIXHEXN.mjs +0 -265
  92. package/dist/TemplatePlugin-HNTPEXBB.mjs +0 -9
  93. package/dist/ToolbarPlugin-F52PVNXU.mjs +0 -823
  94. package/dist/VersionHistoryPlugin-YWGCREKA.mjs +0 -371
  95. package/dist/background-color-RW5JYLMG.mjs +0 -425
  96. package/dist/block-format-TODFREE2.mjs +0 -14
  97. package/dist/chunk-22ZIL6NH.mjs +0 -88
  98. package/dist/chunk-2LNT36RL.mjs +0 -555
  99. package/dist/chunk-37LC44W3.mjs +0 -2677
  100. package/dist/chunk-3IILA3IP.mjs +0 -28
  101. package/dist/chunk-4DVIYZVB.mjs +0 -193
  102. package/dist/chunk-4FFTOZGJ.mjs +0 -103
  103. package/dist/chunk-4UMUPCDK.mjs +0 -68
  104. package/dist/chunk-6D6QLRYR.mjs +0 -238
  105. package/dist/chunk-6FQFPPLG.mjs +0 -785
  106. package/dist/chunk-ACV47ZKE.mjs +0 -201
  107. package/dist/chunk-BGV62GC2.mjs +0 -26
  108. package/dist/chunk-C4JWLBYN.mjs +0 -132
  109. package/dist/chunk-CLRSETYQ.mjs +0 -431
  110. package/dist/chunk-D3IOUQFR.mjs +0 -441
  111. package/dist/chunk-EEBA6OAH.mjs +0 -59
  112. package/dist/chunk-EIZMKFHF.mjs +0 -32
  113. package/dist/chunk-ENH2IOHI.mjs +0 -1828
  114. package/dist/chunk-EVPWKNE4.mjs +0 -27
  115. package/dist/chunk-HOZ4QRFV.mjs +0 -536
  116. package/dist/chunk-IAFCQV3Z.mjs +0 -349
  117. package/dist/chunk-J6ZUY5BY.mjs +0 -202
  118. package/dist/chunk-K5OAFEVY.mjs +0 -191
  119. package/dist/chunk-KXRLARGI.mjs +0 -26
  120. package/dist/chunk-LBGM4VVZ.mjs +0 -409
  121. package/dist/chunk-LLGVCM7M.mjs +0 -809
  122. package/dist/chunk-LU2XWLOE.mjs +0 -219
  123. package/dist/chunk-LVRJM45C.mjs +0 -171
  124. package/dist/chunk-MSAO3YFB.mjs +0 -144
  125. package/dist/chunk-N3KDPSRI.mjs +0 -496
  126. package/dist/chunk-OXWTZV3U.mjs +0 -174
  127. package/dist/chunk-PD5K4AGP.mjs +0 -64
  128. package/dist/chunk-PFH63ZU4.mjs +0 -33
  129. package/dist/chunk-R7WFRENU.mjs +0 -262
  130. package/dist/chunk-RAVYEEIC.mjs +0 -36
  131. package/dist/chunk-RJQTA6HG.mjs +0 -358
  132. package/dist/chunk-SAOJHVPE.mjs +0 -153
  133. package/dist/chunk-SYUCM5G5.mjs +0 -111
  134. package/dist/chunk-VGAX6YEY.mjs +0 -399
  135. package/dist/chunk-VNDDDXGH.mjs +0 -682
  136. package/dist/chunk-WUVIQCX7.mjs +0 -944
  137. package/dist/chunk-XNJNT6PC.mjs +0 -1701
  138. package/dist/chunk-XYLTLGY5.mjs +0 -775
  139. package/dist/chunk-ZKZ7MLSS.mjs +0 -165
  140. package/dist/color-S55XFDYQ.mjs +0 -13
  141. package/dist/font-IJKFR4BM.mjs +0 -12
  142. package/dist/font-size-3HMJHKO2.mjs +0 -15
  143. package/dist/insert-node-DGCZBGKG.mjs +0 -243
  144. package/dist/table-dropdown-4VCRSQB6.mjs +0 -391
  145. package/dist/text-align-TEB4S52S.mjs +0 -121
  146. package/dist/text-format-T3IY7FBI.mjs +0 -15
@@ -0,0 +1,1556 @@
1
+ import {
2
+ nodes_default,
3
+ useAI
4
+ } from "./chunk-BCGD2YXP.mjs";
5
+ import {
6
+ NOTIQ_TRANSFORMERS
7
+ } from "./chunk-QCS57TIF.mjs";
8
+ import {
9
+ cn
10
+ } from "./chunk-JHXDLYEV.mjs";
11
+ import {
12
+ __spreadValues,
13
+ init_react_shim
14
+ } from "./chunk-WYCFGRFJ.mjs";
15
+
16
+ // src/components/editor/plugins/AICommandBarPlugin/index.tsx
17
+ init_react_shim();
18
+ import { useState, useEffect, useRef, useCallback, useMemo } from "react";
19
+ import { createPortal } from "react-dom";
20
+ import { useLexicalComposerContext } from "@lexical/react/LexicalComposerContext";
21
+ import {
22
+ $createParagraphNode as $createParagraphNode2,
23
+ $getNodeByKey,
24
+ $getRoot as $getRoot2,
25
+ $getSelection as $getSelection2,
26
+ $isRangeSelection as $isRangeSelection2,
27
+ $parseSerializedNode as $parseSerializedNode2,
28
+ COMMAND_PRIORITY_CRITICAL,
29
+ createCommand,
30
+ KEY_DOWN_COMMAND
31
+ } from "lexical";
32
+ import {
33
+ Sparkles,
34
+ Loader2,
35
+ Check,
36
+ X,
37
+ RotateCcw,
38
+ CornerDownLeft,
39
+ ChevronRight,
40
+ Wand2,
41
+ Languages,
42
+ FileText,
43
+ ListChecks,
44
+ Lightbulb,
45
+ Table2,
46
+ PenLine,
47
+ MessageSquare,
48
+ GitCompareArrows,
49
+ Square,
50
+ SlidersHorizontal,
51
+ Brain,
52
+ Globe,
53
+ Image as ImageIcon,
54
+ Shapes
55
+ } from "lucide-react";
56
+
57
+ // src/components/editor/utils/diffUtils.ts
58
+ init_react_shim();
59
+ function tokenize(text) {
60
+ return text.match(/\S+|\s+/g) || [];
61
+ }
62
+ function computeWordDiff(original, updated) {
63
+ const origTokens = tokenize(original);
64
+ const upTokens = tokenize(updated);
65
+ const n = origTokens.length;
66
+ const m = upTokens.length;
67
+ if (n === 0 && m === 0) return [];
68
+ if (n === 0) return [{ type: "added", text: updated }];
69
+ if (m === 0) return [{ type: "removed", text: original }];
70
+ if (n > 1500 || m > 1500) {
71
+ return [
72
+ { type: "removed", text: original },
73
+ { type: "added", text: updated }
74
+ ];
75
+ }
76
+ const dp = Array.from(
77
+ { length: n + 1 },
78
+ () => new Array(m + 1).fill(0)
79
+ );
80
+ for (let i2 = 1; i2 <= n; i2++) {
81
+ for (let j2 = 1; j2 <= m; j2++) {
82
+ if (origTokens[i2 - 1] === upTokens[j2 - 1]) {
83
+ dp[i2][j2] = dp[i2 - 1][j2 - 1] + 1;
84
+ } else {
85
+ dp[i2][j2] = Math.max(dp[i2 - 1][j2], dp[i2][j2 - 1]);
86
+ }
87
+ }
88
+ }
89
+ const parts = [];
90
+ let i = n;
91
+ let j = m;
92
+ while (i > 0 || j > 0) {
93
+ if (i > 0 && j > 0 && origTokens[i - 1] === upTokens[j - 1]) {
94
+ parts.unshift({ type: "unchanged", text: origTokens[i - 1] });
95
+ i--;
96
+ j--;
97
+ } else if (j > 0 && (i === 0 || dp[i][j - 1] >= dp[i - 1][j])) {
98
+ parts.unshift({ type: "added", text: upTokens[j - 1] });
99
+ j--;
100
+ } else if (i > 0 && (j === 0 || dp[i][j - 1] < dp[i - 1][j])) {
101
+ parts.unshift({ type: "removed", text: origTokens[i - 1] });
102
+ i--;
103
+ }
104
+ }
105
+ const merged = [];
106
+ for (const part of parts) {
107
+ if (merged.length > 0 && merged[merged.length - 1].type === part.type) {
108
+ merged[merged.length - 1].text += part.text;
109
+ } else {
110
+ merged.push(__spreadValues({}, part));
111
+ }
112
+ }
113
+ return merged;
114
+ }
115
+
116
+ // src/hooks/instructions-messages.ts
117
+ init_react_shim();
118
+ var WRITING_STYLE_PRESETS = {
119
+ balanced: {
120
+ label: "Balanced",
121
+ instruction: "Write in clear, natural, engaging prose. Balance conciseness with warmth and strong structure."
122
+ },
123
+ technical: {
124
+ label: "Technical Docs",
125
+ instruction: "Write like senior engineering documentation: precise terminology, active voice, zero marketing fluff, concrete examples, and crisp scannable structure."
126
+ },
127
+ editorial: {
128
+ label: "Editorial",
129
+ instruction: "Write with compelling narrative flow, vivid transitions, varied sentence rhythm, and strong opening hooks."
130
+ },
131
+ executive: {
132
+ label: "Executive Brief",
133
+ instruction: "Lead with the bottom line (BLUF). Use tight bullet points, quantified tradeoffs, and decisive, action-oriented language."
134
+ },
135
+ academic: {
136
+ label: "Academic",
137
+ instruction: "Use formal, objective, well-qualified prose with rigorous logical transitions and precise definitions."
138
+ }
139
+ };
140
+
141
+ // src/components/editor/utils/aiStream.ts
142
+ init_react_shim();
143
+ import {
144
+ $createParagraphNode,
145
+ $createTextNode,
146
+ $getRoot,
147
+ $getSelection,
148
+ $isElementNode,
149
+ $isRangeSelection,
150
+ $isTextNode,
151
+ $parseSerializedNode,
152
+ createEditor
153
+ } from "lexical";
154
+ import { $convertFromMarkdownString } from "@lexical/markdown";
155
+ var AI_GENERATED_STYLE = "color: #7c3aed; background-color: rgba(139, 92, 246, 0.08); border-radius: 3px;";
156
+ var AI_CARET_STYLE = "color: #7c3aed; font-size: 0.78em; animation: notiq-ai-pulse 1s ease-in-out infinite;";
157
+ var AI_CARET_TEXT = " \u25CF";
158
+ var cachedDetachedEditor = null;
159
+ var cachedNodesRef = null;
160
+ function getDetachedMarkdownEditor(nodes) {
161
+ if (cachedDetachedEditor && cachedNodesRef === nodes) {
162
+ return cachedDetachedEditor;
163
+ }
164
+ cachedNodesRef = nodes;
165
+ cachedDetachedEditor = createEditor({
166
+ namespace: "notiq-ai-markdown-parser",
167
+ nodes: [...nodes],
168
+ onError: (err) => {
169
+ console.warn("[Notiq AI Stream Parser]:", err);
170
+ }
171
+ });
172
+ return cachedDetachedEditor;
173
+ }
174
+ function sanitizeStreamingMarkdown(raw) {
175
+ var _a;
176
+ if (!raw) return "";
177
+ let text = raw.replace(/\r\n/g, "\n");
178
+ text = text.replace(/<[a-zA-Z][^>\n]*$/, "");
179
+ const mathMatches = text.match(/\$\$/g);
180
+ if (mathMatches && mathMatches.length % 2 === 1) {
181
+ const lastIdx = text.lastIndexOf("$$");
182
+ text = text.slice(0, lastIdx);
183
+ }
184
+ const fenceMatches = text.match(/^```/gm);
185
+ if (fenceMatches && fenceMatches.length % 2 === 1) {
186
+ const lastFenceIdx = text.lastIndexOf("```");
187
+ const tail = text.slice(lastFenceIdx);
188
+ if (/^```excalidraw\b/i.test(tail)) {
189
+ text = text.slice(0, lastFenceIdx) + "> \u{1F3A8} *Drawing interactive Excalidraw diagram...*";
190
+ } else {
191
+ text = text + "\n```";
192
+ }
193
+ }
194
+ const lines = text.split("\n");
195
+ const collapsed = [];
196
+ for (let i = 0; i < lines.length; i++) {
197
+ const line = lines[i];
198
+ const calloutMatch = line.match(
199
+ /^(>\s*\[!(?:NOTE|TIP|IMPORTANT|WARNING|CAUTION|INFO|ERROR)\])\s*(.*)$/i
200
+ );
201
+ if (calloutMatch) {
202
+ const tag = calloutMatch[1];
203
+ const parts = [];
204
+ if ((_a = calloutMatch[2]) == null ? void 0 : _a.trim()) {
205
+ parts.push(calloutMatch[2].trim());
206
+ }
207
+ while (i + 1 < lines.length && /^>\s?(.*)$/.test(lines[i + 1])) {
208
+ const nextLine = lines[i + 1];
209
+ if (/^>\s*\[!/i.test(nextLine)) break;
210
+ const body = nextLine.replace(/^>\s?/, "").trim();
211
+ if (body) parts.push(body);
212
+ i++;
213
+ }
214
+ collapsed.push(parts.length > 0 ? `${tag} ${parts.join(" ")}` : tag);
215
+ } else {
216
+ collapsed.push(line);
217
+ }
218
+ }
219
+ text = collapsed.join("\n");
220
+ return text;
221
+ }
222
+ function $serializeNodeTree(node) {
223
+ const json = node.exportJSON();
224
+ if ($isElementNode(node)) {
225
+ json.children = node.getChildren().map($serializeNodeTree);
226
+ }
227
+ return json;
228
+ }
229
+ function serializeMarkdownToNodes(markdown, nodes) {
230
+ const sanitized = sanitizeStreamingMarkdown(markdown);
231
+ if (!sanitized.trim()) return [];
232
+ const detached = getDetachedMarkdownEditor(nodes);
233
+ let serializedChildren = [];
234
+ detached.update(
235
+ () => {
236
+ $getRoot().clear();
237
+ $convertFromMarkdownString(sanitized, NOTIQ_TRANSFORMERS);
238
+ serializedChildren = $getRoot().getChildren().map($serializeNodeTree);
239
+ },
240
+ { discrete: true }
241
+ );
242
+ return serializedChildren;
243
+ }
244
+ function hydrateSerializedAINodes(serialized, options = {}) {
245
+ const created = [];
246
+ for (const item of serialized) {
247
+ try {
248
+ const node = $parseSerializedNode(item);
249
+ markSubtreeAsAIGenerated(node);
250
+ created.push(node);
251
+ } catch (err) {
252
+ console.warn("[Notiq AI Hydrate]: skipped node", item == null ? void 0 : item.type, err);
253
+ }
254
+ }
255
+ if (created.length === 0) {
256
+ const p = $createParagraphNode();
257
+ created.push(p);
258
+ }
259
+ if (options.showCaret) {
260
+ appendCaretToLastTextContainer(created);
261
+ }
262
+ return created;
263
+ }
264
+ function markSubtreeAsAIGenerated(node) {
265
+ if ($isTextNode(node)) {
266
+ const existing = node.getStyle();
267
+ if (!existing.includes(AI_GENERATED_STYLE)) {
268
+ const prefix = existing && !existing.trim().endsWith(";") ? `${existing}; ` : existing;
269
+ node.setStyle(`${prefix}${AI_GENERATED_STYLE}`);
270
+ }
271
+ return;
272
+ }
273
+ if ($isElementNode(node)) {
274
+ for (const child of node.getChildren()) {
275
+ markSubtreeAsAIGenerated(child);
276
+ }
277
+ }
278
+ }
279
+ function stripAIStyleFromSubtree(node) {
280
+ if ($isTextNode(node)) {
281
+ const style = node.getStyle();
282
+ if (style.includes(AI_GENERATED_STYLE)) {
283
+ const cleaned = style.replace(AI_GENERATED_STYLE, "").trim();
284
+ node.setStyle(cleaned);
285
+ }
286
+ if (node.getTextContent() === AI_CARET_TEXT && node.getStyle().includes("notiq-ai-pulse")) {
287
+ node.remove();
288
+ }
289
+ return;
290
+ }
291
+ if ($isElementNode(node)) {
292
+ for (const child of node.getChildren()) {
293
+ stripAIStyleFromSubtree(child);
294
+ }
295
+ }
296
+ }
297
+ function appendCaretToLastTextContainer(nodes) {
298
+ for (let i = nodes.length - 1; i >= 0; i--) {
299
+ const target = findDeepestTextContainer(nodes[i]);
300
+ if (target) {
301
+ const caretNode = $createTextNode(AI_CARET_TEXT);
302
+ caretNode.setStyle(AI_CARET_STYLE);
303
+ target.append(caretNode);
304
+ return;
305
+ }
306
+ }
307
+ }
308
+ function findDeepestTextContainer(node) {
309
+ if (!$isElementNode(node)) return null;
310
+ const children = node.getChildren();
311
+ for (let i = children.length - 1; i >= 0; i--) {
312
+ const child = children[i];
313
+ if ($isElementNode(child) && !child.isInline()) {
314
+ const deeper = findDeepestTextContainer(child);
315
+ if (deeper) return deeper;
316
+ }
317
+ }
318
+ if (node.canBeEmpty() || children.length > 0) {
319
+ return node;
320
+ }
321
+ return null;
322
+ }
323
+ function extractSurroundingContext(editor, maxBlocksBefore = 3, maxBlocksAfter = 2) {
324
+ let result = "";
325
+ editor.getEditorState().read(() => {
326
+ var _a;
327
+ const root = $getRoot();
328
+ const children = root.getChildren();
329
+ if (children.length === 0) return;
330
+ const outline = [];
331
+ for (const child of children) {
332
+ if (child.getType() === "heading") {
333
+ const tag = ((_a = child.getTag) == null ? void 0 : _a.call(child)) || "h2";
334
+ const text = child.getTextContent().trim();
335
+ if (text) outline.push(`${tag.toUpperCase()}: ${text}`);
336
+ }
337
+ }
338
+ let activeIdx = children.length - 1;
339
+ const selection = $getSelection();
340
+ if ($isRangeSelection(selection)) {
341
+ const anchorNode = selection.anchor.getNode();
342
+ const top = anchorNode.getKey() === "root" ? null : anchorNode.getTopLevelElementOrThrow();
343
+ if (top) {
344
+ const idx = children.findIndex((c) => c.getKey() === top.getKey());
345
+ if (idx !== -1) activeIdx = idx;
346
+ }
347
+ }
348
+ const start = Math.max(0, activeIdx - maxBlocksBefore);
349
+ const end = Math.min(children.length, activeIdx + maxBlocksAfter + 1);
350
+ const windowText = children.slice(start, end).map((c) => c.getTextContent().trim()).filter(Boolean).join("\n\n");
351
+ const parts = [];
352
+ if (outline.length > 0) {
353
+ parts.push(`Document Outline:
354
+ ${outline.slice(0, 12).join("\n")}`);
355
+ }
356
+ if (windowText) {
357
+ parts.push(`Surrounding Context:
358
+ ${windowText}`);
359
+ }
360
+ result = parts.join("\n\n");
361
+ });
362
+ return result;
363
+ }
364
+
365
+ // src/components/editor/plugins/AICommandBarPlugin/index.tsx
366
+ import { Fragment, jsx, jsxs } from "react/jsx-runtime";
367
+ var OPEN_AI_COMMAND_BAR_COMMAND = createCommand("OPEN_AI_COMMAND_BAR_COMMAND");
368
+ function extractThinkingAndSources(raw) {
369
+ let text = raw;
370
+ let thinking = "";
371
+ const sources = [];
372
+ const closedThinkMatch = text.match(/<thinking>([\s\S]*?)<\/thinking>/i);
373
+ if (closedThinkMatch) {
374
+ thinking = closedThinkMatch[1].trim();
375
+ text = text.replace(/<thinking>[\s\S]*?<\/thinking>\s*/i, "");
376
+ } else {
377
+ const openIdx = text.search(/<thinking>/i);
378
+ if (openIdx !== -1) {
379
+ thinking = text.slice(openIdx + "<thinking>".length).trim();
380
+ text = text.slice(0, openIdx);
381
+ }
382
+ }
383
+ const sourcesMatch = text.match(/<!--SOURCES:([\s\S]*?)-->/);
384
+ if (sourcesMatch) {
385
+ try {
386
+ const parsed = JSON.parse(sourcesMatch[1]);
387
+ if (Array.isArray(parsed)) {
388
+ for (const item of parsed) {
389
+ if (item && typeof item.url === "string" && typeof item.title === "string") {
390
+ sources.push({ title: item.title, url: item.url });
391
+ }
392
+ }
393
+ }
394
+ } catch (e) {
395
+ }
396
+ text = text.replace(/\n?<!--SOURCES:[\s\S]*?-->/g, "");
397
+ } else {
398
+ const partialIdx = text.indexOf("<!--SOURCES:");
399
+ if (partialIdx !== -1) {
400
+ text = text.slice(0, partialIdx);
401
+ }
402
+ }
403
+ return {
404
+ thinking,
405
+ sources,
406
+ content: text.trimStart()
407
+ };
408
+ }
409
+ var SELECTION_PRESETS = [
410
+ {
411
+ id: "improve",
412
+ action: "ImproveWriting",
413
+ label: "Improve writing",
414
+ keywords: ["improve", "polish", "rewrite", "better"],
415
+ icon: Wand2
416
+ },
417
+ {
418
+ id: "grammar",
419
+ action: "FixSpellingGrammar",
420
+ label: "Fix grammar & spelling",
421
+ keywords: ["fix", "grammar", "spelling", "proofread"],
422
+ icon: Check
423
+ },
424
+ {
425
+ id: "shorter",
426
+ action: "MakeShort",
427
+ label: "Make shorter",
428
+ keywords: ["shorter", "concise", "trim", "condense"],
429
+ icon: Sparkles
430
+ },
431
+ {
432
+ id: "longer",
433
+ action: "MakeLong",
434
+ label: "Make longer",
435
+ keywords: ["longer", "expand", "elaborate", "detail"],
436
+ icon: Sparkles
437
+ },
438
+ {
439
+ id: "simplify",
440
+ action: "SimplifyLanguage",
441
+ label: "Simplify language",
442
+ keywords: ["simplify", "clear", "easy", "plain"],
443
+ icon: SlidersHorizontal
444
+ },
445
+ {
446
+ id: "explain",
447
+ action: "default",
448
+ label: "Explain",
449
+ keywords: ["explain", "clarify", "what", "meaning"],
450
+ prompt: "Explain the selected text clearly with key takeaways.",
451
+ icon: MessageSquare
452
+ },
453
+ {
454
+ id: "tone",
455
+ action: "Tone",
456
+ label: "Change tone",
457
+ keywords: ["tone", "professional", "casual", "friendly", "academic"],
458
+ icon: Wand2,
459
+ hasSubmenu: "tone"
460
+ },
461
+ {
462
+ id: "translate",
463
+ action: "Translate",
464
+ label: "Translate",
465
+ keywords: ["translate", "language", "spanish", "french", "german"],
466
+ icon: Languages,
467
+ hasSubmenu: "language"
468
+ }
469
+ ];
470
+ var CURSOR_PRESETS = [
471
+ {
472
+ id: "continue",
473
+ action: "autoComplete",
474
+ label: "Continue writing",
475
+ keywords: ["continue", "write", "complete", "next"],
476
+ icon: PenLine
477
+ },
478
+ {
479
+ id: "research-write",
480
+ action: "default",
481
+ label: "Research & write",
482
+ keywords: ["research", "search", "web", "sources", "facts", "investigate"],
483
+ prompt: "Research this topic and write a well-structured, fact-grounded section with key takeaways.",
484
+ icon: Globe,
485
+ think: true,
486
+ research: true
487
+ },
488
+ {
489
+ id: "draw-diagram",
490
+ action: "default",
491
+ label: "Draw diagram (Excalidraw)",
492
+ keywords: ["diagram", "flowchart", "architecture", "draw", "excalidraw", "chart"],
493
+ prompt: "Draw an interactive Excalidraw architecture or workflow diagram for this topic.",
494
+ icon: Shapes,
495
+ think: true
496
+ },
497
+ {
498
+ id: "add-visuals",
499
+ action: "default",
500
+ label: "Insert images & visuals",
501
+ keywords: ["image", "inline", "visual", "picture", "illustration"],
502
+ prompt: "Create a visual overview with both a block image and an inline image for this topic.",
503
+ icon: ImageIcon,
504
+ think: true
505
+ },
506
+ {
507
+ id: "summary",
508
+ action: "Summarize",
509
+ label: "Add a summary",
510
+ keywords: ["summary", "summarize", "tldr", "recap"],
511
+ prompt: "Summarize the document into crisp, structured key points.",
512
+ icon: FileText
513
+ },
514
+ {
515
+ id: "md-sample",
516
+ action: "default",
517
+ label: "Generate Markdown sample",
518
+ keywords: ["markdown", "sample", "demo", "template", "mdx"],
519
+ prompt: "Generate a rich Markdown showcase with headings, a blockquote, a task list, a code block, inline math $E = mc^2$, and a comparison table.",
520
+ icon: Sparkles
521
+ },
522
+ {
523
+ id: "outline",
524
+ action: "Steps",
525
+ label: "Write an outline",
526
+ keywords: ["outline", "steps", "roadmap", "structure"],
527
+ prompt: "Create a structured step-by-step outline for this topic.",
528
+ icon: ListChecks
529
+ },
530
+ {
531
+ id: "brainstorm",
532
+ action: "default",
533
+ label: "Brainstorm ideas",
534
+ keywords: ["brainstorm", "ideas", "creative", "suggest"],
535
+ prompt: "Brainstorm 5 creative, actionable ideas related to this document.",
536
+ icon: Lightbulb
537
+ },
538
+ {
539
+ id: "table",
540
+ action: "default",
541
+ label: "Create comparison table",
542
+ keywords: ["table", "compare", "comparison", "matrix"],
543
+ prompt: "Create a clean Markdown comparison table summarizing the key options.",
544
+ icon: Table2
545
+ }
546
+ ];
547
+ var TONES = ["Professional", "Casual", "Direct", "Academic", "Friendly"];
548
+ var LANGUAGES = ["Spanish", "French", "German", "Japanese", "Chinese", "Arabic"];
549
+ function AICommandBarPlugin({
550
+ headless = false,
551
+ apiEndpoint: propApiEndpoint,
552
+ render,
553
+ onStateChange
554
+ } = {}) {
555
+ const [editor] = useLexicalComposerContext();
556
+ const {
557
+ apiEndpoint: contextApiEndpoint,
558
+ writingStyle: configWritingStyle,
559
+ styleGuide: configStyleGuide
560
+ } = useAI();
561
+ const apiEndpoint = propApiEndpoint || contextApiEndpoint;
562
+ const [writingStyle, setWritingStyle] = useState(() => {
563
+ if (typeof window !== "undefined") {
564
+ const saved = localStorage.getItem("notiq_ai_writing_style");
565
+ if (saved && saved in WRITING_STYLE_PRESETS) {
566
+ return saved;
567
+ }
568
+ }
569
+ return configWritingStyle && configWritingStyle in WRITING_STYLE_PRESETS ? configWritingStyle : "balanced";
570
+ });
571
+ const [customStyleGuide, setCustomStyleGuide] = useState(() => {
572
+ if (typeof window !== "undefined") {
573
+ return localStorage.getItem("notiq_ai_style_guide") || configStyleGuide || "";
574
+ }
575
+ return configStyleGuide || "";
576
+ });
577
+ const [showStyleEditor, setShowStyleEditor] = useState(false);
578
+ const [phase, setPhase] = useState("closed");
579
+ const [coords, setCoords] = useState(null);
580
+ const [prompt, setPrompt] = useState("");
581
+ const [followUpPrompt, setFollowUpPrompt] = useState("");
582
+ const [selectedText, setSelectedText] = useState("");
583
+ const [streamedText, setStreamedText] = useState("");
584
+ const [showDiff, setShowDiff] = useState(false);
585
+ const [thinkEnabled, setThinkEnabled] = useState(true);
586
+ const [researchEnabled, setResearchEnabled] = useState(false);
587
+ const [showTrace, setShowTrace] = useState(false);
588
+ const [activeLabel, setActiveLabel] = useState("Writing...");
589
+ const [errorMsg, setErrorMsg] = useState(null);
590
+ const [highlightedIndex, setHighlightedIndex] = useState(0);
591
+ const [activeSubmenu, setActiveSubmenu] = useState(null);
592
+ const containerRef = useRef(null);
593
+ const inputRef = useRef(null);
594
+ const followUpRef = useRef(null);
595
+ const abortControllerRef = useRef(null);
596
+ const generatedKeysRef = useRef([]);
597
+ const anchorAfterKeyRef = useRef(null);
598
+ const replacedBlockSnapshotRef = useRef(null);
599
+ const lastRequestRef = useRef(null);
600
+ const presets = useMemo(
601
+ () => selectedText.trim().length > 0 ? SELECTION_PRESETS : CURSOR_PRESETS,
602
+ [selectedText]
603
+ );
604
+ const parsedStream = useMemo(
605
+ () => extractThinkingAndSources(streamedText),
606
+ [streamedText]
607
+ );
608
+ const canShowDiff = phase === "review" && selectedText.trim().length > 0 && parsedStream.content.trim().length > 0;
609
+ const diffParts = useMemo(() => {
610
+ if (!canShowDiff || !showDiff) return [];
611
+ return computeWordDiff(selectedText, parsedStream.content);
612
+ }, [canShowDiff, showDiff, selectedText, parsedStream.content]);
613
+ const filteredPresets = useMemo(() => {
614
+ const q = prompt.trim().toLowerCase();
615
+ if (!q) return presets;
616
+ return presets.filter(
617
+ (p) => p.label.toLowerCase().includes(q) || p.keywords.some((kw) => kw.includes(q))
618
+ );
619
+ }, [presets, prompt]);
620
+ useEffect(() => {
621
+ setHighlightedIndex(0);
622
+ }, [prompt, phase]);
623
+ const wordCount = useMemo(() => {
624
+ const trimmed = streamedText.trim();
625
+ return trimmed ? trimmed.split(/\s+/).length : 0;
626
+ }, [streamedText]);
627
+ const scrollLastGeneratedIntoView = useCallback(() => {
628
+ const keys = generatedKeysRef.current;
629
+ if (keys.length === 0) return;
630
+ const el = editor.getElementByKey(keys[keys.length - 1]);
631
+ if (el) {
632
+ const rect = el.getBoundingClientRect();
633
+ if (rect.bottom > window.innerHeight - 110 || rect.top < 80) {
634
+ el.scrollIntoView({ behavior: "smooth", block: "nearest" });
635
+ }
636
+ }
637
+ }, [editor]);
638
+ const applyStreamedMarkdownToEditor = useCallback(
639
+ (markdown, showCaret) => {
640
+ const serialized = serializeMarkdownToNodes(markdown, nodes_default);
641
+ editor.update(
642
+ () => {
643
+ var _a;
644
+ const root = $getRoot2();
645
+ const newNodes = hydrateSerializedAINodes(serialized, { showCaret });
646
+ const existingKeys = generatedKeysRef.current;
647
+ if (existingKeys.length > 0) {
648
+ const firstExisting = $getNodeByKey(existingKeys[0]);
649
+ if (firstExisting && firstExisting.isAttached()) {
650
+ const insertIndex = firstExisting.getIndexWithinParent();
651
+ for (const key of existingKeys) {
652
+ const oldNode = $getNodeByKey(key);
653
+ if (oldNode && oldNode.isAttached()) {
654
+ oldNode.remove();
655
+ }
656
+ }
657
+ root.splice(insertIndex, 0, newNodes);
658
+ generatedKeysRef.current = newNodes.map((n) => n.getKey());
659
+ return;
660
+ }
661
+ }
662
+ const anchorKey = anchorAfterKeyRef.current;
663
+ const anchorNode = anchorKey ? $getNodeByKey(anchorKey) : null;
664
+ if (anchorNode && anchorNode.isAttached()) {
665
+ const isEmptyAnchor = ((_a = replacedBlockSnapshotRef.current) == null ? void 0 : _a.replacedEmpty) && anchorNode.getTextContent().trim() === "";
666
+ const anchorIndex = anchorNode.getIndexWithinParent();
667
+ if (isEmptyAnchor) {
668
+ anchorNode.remove();
669
+ root.splice(anchorIndex, 0, newNodes);
670
+ } else {
671
+ root.splice(anchorIndex + 1, 0, newNodes);
672
+ }
673
+ } else {
674
+ root.append(...newNodes);
675
+ }
676
+ generatedKeysRef.current = newNodes.map((n) => n.getKey());
677
+ },
678
+ { discrete: true, tag: "notiq-ai-stream" }
679
+ );
680
+ },
681
+ [editor]
682
+ );
683
+ const captureAnchorFromSelection = useCallback(() => {
684
+ let targetText = "";
685
+ let docContext = "";
686
+ editor.getEditorState().read(() => {
687
+ const root = $getRoot2();
688
+ docContext = root.getTextContent();
689
+ const selection = $getSelection2();
690
+ if ($isRangeSelection2(selection)) {
691
+ targetText = selection.getTextContent();
692
+ const anchorNode = selection.anchor.getNode();
693
+ const topElement = anchorNode.getKey() === "root" ? root.getLastChild() : anchorNode.getTopLevelElementOrThrow();
694
+ if (topElement) {
695
+ anchorAfterKeyRef.current = topElement.getKey();
696
+ const isEmpty = topElement.getTextContent().trim() === "";
697
+ replacedBlockSnapshotRef.current = {
698
+ replacedEmpty: isEmpty,
699
+ originalText: targetText,
700
+ originalNodes: [topElement.exportJSON()]
701
+ };
702
+ } else {
703
+ anchorAfterKeyRef.current = null;
704
+ replacedBlockSnapshotRef.current = null;
705
+ }
706
+ } else {
707
+ const last = root.getLastChild();
708
+ anchorAfterKeyRef.current = last ? last.getKey() : null;
709
+ replacedBlockSnapshotRef.current = last ? {
710
+ replacedEmpty: last.getTextContent().trim() === "",
711
+ originalText: "",
712
+ originalNodes: [last.exportJSON()]
713
+ } : null;
714
+ }
715
+ });
716
+ return { targetText, docContext };
717
+ }, [editor]);
718
+ const resetSessionState = useCallback(() => {
719
+ if (abortControllerRef.current) {
720
+ abortControllerRef.current.abort();
721
+ abortControllerRef.current = null;
722
+ }
723
+ generatedKeysRef.current = [];
724
+ anchorAfterKeyRef.current = null;
725
+ replacedBlockSnapshotRef.current = null;
726
+ setPhase("closed");
727
+ setCoords(null);
728
+ setPrompt("");
729
+ setFollowUpPrompt("");
730
+ setSelectedText("");
731
+ setStreamedText("");
732
+ setShowDiff(false);
733
+ setShowTrace(false);
734
+ setErrorMsg(null);
735
+ setActiveSubmenu(null);
736
+ }, []);
737
+ const handleDiscard = useCallback(() => {
738
+ if (abortControllerRef.current) {
739
+ abortControllerRef.current.abort();
740
+ abortControllerRef.current = null;
741
+ }
742
+ const keys = [...generatedKeysRef.current];
743
+ const snapshot = replacedBlockSnapshotRef.current;
744
+ if (keys.length > 0) {
745
+ editor.update(
746
+ () => {
747
+ const firstNode = $getNodeByKey(keys[0]);
748
+ if (firstNode && (snapshot == null ? void 0 : snapshot.replacedEmpty) && snapshot.originalNodes.length > 0) {
749
+ try {
750
+ const restored = $parseSerializedNode2(snapshot.originalNodes[0]);
751
+ firstNode.insertBefore(restored);
752
+ } catch (e) {
753
+ firstNode.insertBefore($createParagraphNode2());
754
+ }
755
+ }
756
+ for (const key of keys) {
757
+ const node = $getNodeByKey(key);
758
+ if (node) node.remove();
759
+ }
760
+ },
761
+ { discrete: true }
762
+ );
763
+ }
764
+ resetSessionState();
765
+ editor.focus();
766
+ }, [editor, resetSessionState]);
767
+ const handleAccept = useCallback(() => {
768
+ const keys = [...generatedKeysRef.current];
769
+ if (keys.length > 0) {
770
+ editor.update(
771
+ () => {
772
+ for (const key of keys) {
773
+ const node = $getNodeByKey(key);
774
+ if (node) {
775
+ stripAIStyleFromSubtree(node);
776
+ }
777
+ }
778
+ const last = $getNodeByKey(keys[keys.length - 1]);
779
+ if (last && "selectEnd" in last && typeof last.selectEnd === "function") {
780
+ last.selectEnd();
781
+ }
782
+ },
783
+ { discrete: true }
784
+ );
785
+ }
786
+ resetSessionState();
787
+ editor.focus();
788
+ }, [editor, resetSessionState]);
789
+ const runAction = useCallback(
790
+ async (action, contextText, customQuestion, label, options) => {
791
+ var _a, _b;
792
+ const useThink = (_a = options == null ? void 0 : options.think) != null ? _a : thinkEnabled;
793
+ const useResearch = (_b = options == null ? void 0 : options.research) != null ? _b : researchEnabled;
794
+ setErrorMsg(null);
795
+ setActiveSubmenu(null);
796
+ setActiveLabel(
797
+ label || (useResearch ? "Researching & writing..." : useThink ? "Thinking & writing..." : "Writing...")
798
+ );
799
+ setPhase("streaming");
800
+ setStreamedText("");
801
+ setShowDiff(false);
802
+ setShowTrace(false);
803
+ setShowTrace(false);
804
+ lastRequestRef.current = {
805
+ action,
806
+ context: contextText,
807
+ question: customQuestion,
808
+ label
809
+ };
810
+ if (abortControllerRef.current) {
811
+ abortControllerRef.current.abort();
812
+ }
813
+ const controller = new AbortController();
814
+ abortControllerRef.current = controller;
815
+ let accumulated = "";
816
+ let renderTimer = null;
817
+ const scheduleRender = (final = false) => {
818
+ if (final) {
819
+ if (renderTimer !== null) {
820
+ clearTimeout(renderTimer);
821
+ renderTimer = null;
822
+ }
823
+ const parsed = extractThinkingAndSources(accumulated);
824
+ if (parsed.content.trim()) {
825
+ applyStreamedMarkdownToEditor(parsed.content, false);
826
+ scrollLastGeneratedIntoView();
827
+ }
828
+ return;
829
+ }
830
+ if (renderTimer !== null) return;
831
+ renderTimer = setTimeout(() => {
832
+ renderTimer = null;
833
+ if (!controller.signal.aborted) {
834
+ const parsed = extractThinkingAndSources(accumulated);
835
+ if (parsed.content.trim()) {
836
+ applyStreamedMarkdownToEditor(parsed.content, true);
837
+ scrollLastGeneratedIntoView();
838
+ }
839
+ }
840
+ }, 80);
841
+ };
842
+ try {
843
+ const savedProvider = typeof window !== "undefined" ? localStorage.getItem("notiq_ai_provider") : void 0;
844
+ const savedKey = typeof window !== "undefined" ? localStorage.getItem("notiq_ai_api_key") : void 0;
845
+ const response = await fetch(apiEndpoint || "/api/ai", {
846
+ method: "POST",
847
+ headers: { "Content-Type": "application/json" },
848
+ body: JSON.stringify({
849
+ action,
850
+ context: contextText || "",
851
+ prompt: customQuestion || contextText || "",
852
+ userQuestion: customQuestion || "",
853
+ writingStyle,
854
+ styleGuide: customStyleGuide.trim() || void 0,
855
+ think: useThink,
856
+ research: useResearch,
857
+ modelProvider: savedProvider && savedProvider !== "auto" ? savedProvider : void 0,
858
+ apiKey: (savedKey == null ? void 0 : savedKey.trim()) || void 0
859
+ }),
860
+ signal: controller.signal
861
+ });
862
+ if (!response.ok || !response.body) {
863
+ const errText = await response.text().catch(() => "");
864
+ throw new Error(errText || `AI service returned ${response.status}`);
865
+ }
866
+ const reader = response.body.getReader();
867
+ const decoder = new TextDecoder();
868
+ while (true) {
869
+ const { value, done } = await reader.read();
870
+ if (done) break;
871
+ const chunk = decoder.decode(value, { stream: true });
872
+ accumulated += chunk;
873
+ setStreamedText(accumulated);
874
+ scheduleRender(false);
875
+ }
876
+ scheduleRender(true);
877
+ setPhase("review");
878
+ } catch (err) {
879
+ if ((err == null ? void 0 : err.name) === "AbortError") {
880
+ if (accumulated.trim()) {
881
+ applyStreamedMarkdownToEditor(accumulated, false);
882
+ setPhase("review");
883
+ } else {
884
+ handleDiscard();
885
+ }
886
+ return;
887
+ }
888
+ console.error("[Notiq AI Command Bar Error]:", err);
889
+ setErrorMsg((err == null ? void 0 : err.message) || "Failed to contact AI service.");
890
+ if (accumulated.trim()) {
891
+ applyStreamedMarkdownToEditor(accumulated, false);
892
+ setPhase("review");
893
+ } else {
894
+ setPhase("prompt");
895
+ }
896
+ } finally {
897
+ abortControllerRef.current = null;
898
+ }
899
+ },
900
+ [
901
+ apiEndpoint,
902
+ applyStreamedMarkdownToEditor,
903
+ handleDiscard,
904
+ scrollLastGeneratedIntoView
905
+ ]
906
+ );
907
+ const handleStopStreaming = useCallback(() => {
908
+ if (abortControllerRef.current) {
909
+ abortControllerRef.current.abort();
910
+ }
911
+ }, []);
912
+ const handleRetry = useCallback(() => {
913
+ const last = lastRequestRef.current;
914
+ if (!last) return;
915
+ runAction(last.action, last.context, last.question, last.label);
916
+ }, [runAction]);
917
+ const openBar = useCallback(
918
+ (payload) => {
919
+ if (generatedKeysRef.current.length > 0) {
920
+ handleAccept();
921
+ }
922
+ const { targetText, docContext } = captureAnchorFromSelection();
923
+ const domSelection = window.getSelection();
924
+ let top = 140;
925
+ let left = Math.max(20, window.innerWidth / 2 - 260);
926
+ if (domSelection && domSelection.rangeCount > 0) {
927
+ const rect = domSelection.getRangeAt(0).getBoundingClientRect();
928
+ if (rect.width > 0 || rect.height > 0) {
929
+ left = Math.max(
930
+ 16,
931
+ Math.min(window.innerWidth - 540, rect.left)
932
+ );
933
+ top = rect.bottom + 10;
934
+ if (top + 320 > window.innerHeight) {
935
+ top = Math.max(20, rect.top - 300);
936
+ }
937
+ }
938
+ }
939
+ setCoords({ top, left });
940
+ setSelectedText(targetText);
941
+ setPrompt((payload == null ? void 0 : payload.initialPrompt) || "");
942
+ setStreamedText("");
943
+ setShowDiff(false);
944
+ setShowTrace(false);
945
+ setErrorMsg(null);
946
+ setActiveSubmenu(null);
947
+ setPhase("prompt");
948
+ setTimeout(() => {
949
+ var _a;
950
+ (_a = inputRef.current) == null ? void 0 : _a.focus();
951
+ }, 40);
952
+ if (payload == null ? void 0 : payload.action) {
953
+ runAction(
954
+ payload.action,
955
+ targetText || docContext,
956
+ payload.initialPrompt,
957
+ payload.action
958
+ );
959
+ }
960
+ },
961
+ [captureAnchorFromSelection, handleAccept, runAction]
962
+ );
963
+ useEffect(() => {
964
+ return editor.registerCommand(
965
+ KEY_DOWN_COMMAND,
966
+ (event) => {
967
+ if ((event.metaKey || event.ctrlKey) && event.key.toLowerCase() === "k") {
968
+ event.preventDefault();
969
+ if (phase === "closed") {
970
+ openBar();
971
+ } else if (phase === "prompt") {
972
+ resetSessionState();
973
+ }
974
+ return true;
975
+ }
976
+ if (event.key === "Escape") {
977
+ if (phase === "streaming") {
978
+ event.preventDefault();
979
+ handleStopStreaming();
980
+ return true;
981
+ }
982
+ if (phase === "prompt") {
983
+ event.preventDefault();
984
+ resetSessionState();
985
+ return true;
986
+ }
987
+ if (phase === "review") {
988
+ event.preventDefault();
989
+ handleDiscard();
990
+ return true;
991
+ }
992
+ }
993
+ if ((event.metaKey || event.ctrlKey) && event.key === "Enter" && phase === "review") {
994
+ event.preventDefault();
995
+ handleAccept();
996
+ return true;
997
+ }
998
+ return false;
999
+ },
1000
+ COMMAND_PRIORITY_CRITICAL
1001
+ );
1002
+ }, [
1003
+ editor,
1004
+ phase,
1005
+ openBar,
1006
+ resetSessionState,
1007
+ handleStopStreaming,
1008
+ handleDiscard,
1009
+ handleAccept
1010
+ ]);
1011
+ useEffect(() => {
1012
+ if (phase === "closed") return;
1013
+ const onKeyDown = (e) => {
1014
+ if (e.key === "Escape") {
1015
+ e.preventDefault();
1016
+ if (phase === "streaming") handleStopStreaming();
1017
+ else if (phase === "review") handleDiscard();
1018
+ else resetSessionState();
1019
+ } else if ((e.metaKey || e.ctrlKey) && e.key === "Enter" && phase === "review") {
1020
+ e.preventDefault();
1021
+ handleAccept();
1022
+ }
1023
+ };
1024
+ window.addEventListener("keydown", onKeyDown);
1025
+ return () => window.removeEventListener("keydown", onKeyDown);
1026
+ }, [phase, handleStopStreaming, handleDiscard, handleAccept, resetSessionState]);
1027
+ useEffect(() => {
1028
+ return editor.registerCommand(
1029
+ OPEN_AI_COMMAND_BAR_COMMAND,
1030
+ (payload) => {
1031
+ openBar(payload);
1032
+ return true;
1033
+ },
1034
+ COMMAND_PRIORITY_CRITICAL
1035
+ );
1036
+ }, [editor, openBar]);
1037
+ useEffect(() => {
1038
+ if (phase !== "prompt") return;
1039
+ const handleClickOutside = (e) => {
1040
+ if (containerRef.current && !containerRef.current.contains(e.target)) {
1041
+ resetSessionState();
1042
+ }
1043
+ };
1044
+ document.addEventListener("mousedown", handleClickOutside);
1045
+ return () => document.removeEventListener("mousedown", handleClickOutside);
1046
+ }, [phase, resetSessionState]);
1047
+ const executePreset = (preset) => {
1048
+ if (preset.hasSubmenu) {
1049
+ setActiveSubmenu(activeSubmenu === preset.hasSubmenu ? null : preset.hasSubmenu);
1050
+ return;
1051
+ }
1052
+ let docContext = selectedText;
1053
+ if (!docContext) {
1054
+ docContext = extractSurroundingContext(editor);
1055
+ }
1056
+ runAction(
1057
+ preset.action,
1058
+ docContext,
1059
+ preset.prompt,
1060
+ `${preset.label}...`,
1061
+ { think: preset.think, research: preset.research }
1062
+ );
1063
+ };
1064
+ const handlePromptSubmit = (e) => {
1065
+ e == null ? void 0 : e.preventDefault();
1066
+ const trimmed = prompt.trim();
1067
+ if (!trimmed && filteredPresets[highlightedIndex]) {
1068
+ executePreset(filteredPresets[highlightedIndex]);
1069
+ return;
1070
+ }
1071
+ if (trimmed) {
1072
+ let docContext = selectedText;
1073
+ if (!docContext) {
1074
+ docContext = extractSurroundingContext(editor);
1075
+ }
1076
+ runAction("default", docContext, trimmed, "Writing...");
1077
+ }
1078
+ };
1079
+ const handlePromptKeyDown = (e) => {
1080
+ if (e.key === "ArrowDown") {
1081
+ if (filteredPresets.length > 0) {
1082
+ e.preventDefault();
1083
+ setHighlightedIndex((prev) => (prev + 1) % filteredPresets.length);
1084
+ }
1085
+ } else if (e.key === "ArrowUp") {
1086
+ if (filteredPresets.length > 0) {
1087
+ e.preventDefault();
1088
+ setHighlightedIndex(
1089
+ (prev) => (prev - 1 + filteredPresets.length) % filteredPresets.length
1090
+ );
1091
+ }
1092
+ } else if (e.key === "Enter" && !e.shiftKey) {
1093
+ e.preventDefault();
1094
+ const trimmed = prompt.trim();
1095
+ if (!trimmed && filteredPresets[highlightedIndex]) {
1096
+ executePreset(filteredPresets[highlightedIndex]);
1097
+ } else {
1098
+ handlePromptSubmit();
1099
+ }
1100
+ }
1101
+ };
1102
+ const handleFollowUpSubmit = (e) => {
1103
+ e.preventDefault();
1104
+ const trimmed = followUpPrompt.trim();
1105
+ if (!trimmed) return;
1106
+ setFollowUpPrompt("");
1107
+ runAction("default", streamedText || selectedText, trimmed, "Refining...");
1108
+ };
1109
+ const commandBarState = {
1110
+ phase,
1111
+ coords,
1112
+ prompt,
1113
+ setPrompt,
1114
+ followUpPrompt,
1115
+ setFollowUpPrompt,
1116
+ selectedText,
1117
+ streamedText,
1118
+ thinking: parsedStream.thinking,
1119
+ sources: parsedStream.sources,
1120
+ content: parsedStream.content,
1121
+ thinkEnabled,
1122
+ setThinkEnabled,
1123
+ researchEnabled,
1124
+ setResearchEnabled,
1125
+ activeLabel,
1126
+ errorMsg,
1127
+ presets,
1128
+ open: openBar,
1129
+ close: resetSessionState,
1130
+ runAction,
1131
+ executePreset,
1132
+ accept: handleAccept,
1133
+ discard: handleDiscard,
1134
+ retry: handleRetry,
1135
+ stopStreaming: handleStopStreaming
1136
+ };
1137
+ useEffect(() => {
1138
+ onStateChange == null ? void 0 : onStateChange(commandBarState);
1139
+ }, [
1140
+ phase,
1141
+ coords,
1142
+ prompt,
1143
+ followUpPrompt,
1144
+ selectedText,
1145
+ streamedText,
1146
+ thinkEnabled,
1147
+ researchEnabled,
1148
+ activeLabel,
1149
+ errorMsg
1150
+ ]);
1151
+ if (render) {
1152
+ return /* @__PURE__ */ jsx(Fragment, { children: render(commandBarState) });
1153
+ }
1154
+ if (headless || phase === "closed" || typeof document === "undefined") {
1155
+ return null;
1156
+ }
1157
+ return createPortal(
1158
+ /* @__PURE__ */ jsxs(Fragment, { children: [
1159
+ phase === "prompt" && coords && /* @__PURE__ */ jsxs(
1160
+ "div",
1161
+ {
1162
+ ref: containerRef,
1163
+ style: {
1164
+ top: `${coords.top}px`,
1165
+ left: `${coords.left}px`
1166
+ },
1167
+ className: "fixed z-50 w-[520px] max-w-[calc(100vw-2rem)] rounded-2xl border border-zinc-200/90 dark:border-zinc-800/90 bg-white/95 dark:bg-zinc-950/95 backdrop-blur-xl shadow-2xl shadow-violet-500/10 overflow-hidden animate-in fade-in zoom-in-95 duration-150",
1168
+ children: [
1169
+ /* @__PURE__ */ jsxs(
1170
+ "form",
1171
+ {
1172
+ onSubmit: handlePromptSubmit,
1173
+ className: "flex items-center gap-2.5 px-3.5 py-2.5 border-b border-zinc-100 dark:border-zinc-800/80",
1174
+ children: [
1175
+ /* @__PURE__ */ jsx("div", { className: "flex h-6 w-6 shrink-0 items-center justify-center rounded-lg bg-violet-500/10 text-violet-600 dark:text-violet-400", children: /* @__PURE__ */ jsx(Sparkles, { className: "h-3.5 w-3.5" }) }),
1176
+ /* @__PURE__ */ jsx(
1177
+ "input",
1178
+ {
1179
+ ref: inputRef,
1180
+ type: "text",
1181
+ value: prompt,
1182
+ onChange: (e) => setPrompt(e.target.value),
1183
+ onKeyDown: handlePromptKeyDown,
1184
+ placeholder: selectedText ? "Ask AI to edit selection..." : "Ask AI anything...",
1185
+ className: "flex-1 bg-transparent text-sm text-zinc-900 dark:text-zinc-100 placeholder:text-zinc-400 focus:outline-none"
1186
+ }
1187
+ ),
1188
+ prompt.trim() ? /* @__PURE__ */ jsxs(
1189
+ "button",
1190
+ {
1191
+ type: "submit",
1192
+ className: "inline-flex items-center gap-1 rounded-lg bg-violet-600 hover:bg-violet-500 px-2.5 py-1 text-xs font-medium text-white shadow-sm transition-colors",
1193
+ children: [
1194
+ /* @__PURE__ */ jsx("span", { children: "Ask" }),
1195
+ /* @__PURE__ */ jsx(CornerDownLeft, { className: "h-3 w-3" })
1196
+ ]
1197
+ }
1198
+ ) : /* @__PURE__ */ jsx("kbd", { className: "hidden sm:inline-flex items-center gap-0.5 rounded-md border border-zinc-200 dark:border-zinc-800 bg-zinc-50 dark:bg-zinc-900 px-1.5 py-0.5 text-[10px] font-medium text-zinc-400", children: "\u2318K" })
1199
+ ]
1200
+ }
1201
+ ),
1202
+ /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-1.5 px-3.5 py-1.5 border-b border-zinc-100 dark:border-zinc-800/80 bg-zinc-50/60 dark:bg-zinc-900/40 text-[11px]", children: [
1203
+ /* @__PURE__ */ jsxs(
1204
+ "button",
1205
+ {
1206
+ type: "button",
1207
+ onClick: () => setThinkEnabled((v) => !v),
1208
+ className: `inline-flex items-center gap-1 rounded-full px-2.5 py-0.5 font-medium transition-colors ${thinkEnabled ? "bg-violet-600/15 text-violet-700 dark:text-violet-300 border border-violet-500/30" : "text-zinc-500 hover:bg-zinc-200/60 dark:hover:bg-zinc-800 border border-transparent"}`,
1209
+ title: "Reason step-by-step before writing",
1210
+ children: [
1211
+ /* @__PURE__ */ jsx(Brain, { className: "h-3 w-3" }),
1212
+ /* @__PURE__ */ jsx("span", { children: "Think" })
1213
+ ]
1214
+ }
1215
+ ),
1216
+ /* @__PURE__ */ jsxs(
1217
+ "button",
1218
+ {
1219
+ type: "button",
1220
+ onClick: () => setResearchEnabled((v) => !v),
1221
+ className: `inline-flex items-center gap-1 rounded-full px-2.5 py-0.5 font-medium transition-colors ${researchEnabled ? "bg-sky-600/15 text-sky-700 dark:text-sky-300 border border-sky-500/30" : "text-zinc-500 hover:bg-zinc-200/60 dark:hover:bg-zinc-800 border border-transparent"}`,
1222
+ title: "Search & cite live web sources while writing",
1223
+ children: [
1224
+ /* @__PURE__ */ jsx(Globe, { className: "h-3 w-3" }),
1225
+ /* @__PURE__ */ jsx("span", { children: "Research" })
1226
+ ]
1227
+ }
1228
+ ),
1229
+ /* @__PURE__ */ jsx("span", { className: "ml-auto text-[10px] text-zinc-400 hidden sm:inline", children: "Images \xB7 Inline visuals \xB7 Excalidraw diagrams" })
1230
+ ] }),
1231
+ errorMsg && /* @__PURE__ */ jsx("div", { className: "px-3.5 py-2 text-xs text-rose-600 dark:text-rose-400 bg-rose-50/80 dark:bg-rose-950/30 border-b border-rose-200/60 dark:border-rose-900/50", children: errorMsg }),
1232
+ filteredPresets.length > 0 && /* @__PURE__ */ jsx("div", { className: "max-h-72 overflow-y-auto p-1.5 space-y-0.5", children: filteredPresets.map((preset, idx) => {
1233
+ const Icon = preset.icon;
1234
+ const isActive = idx === highlightedIndex;
1235
+ return /* @__PURE__ */ jsxs("div", { children: [
1236
+ /* @__PURE__ */ jsxs(
1237
+ "button",
1238
+ {
1239
+ type: "button",
1240
+ onMouseEnter: () => setHighlightedIndex(idx),
1241
+ onClick: () => executePreset(preset),
1242
+ className: cn(
1243
+ "w-full flex items-center justify-between px-2.5 py-2 rounded-xl text-[13px] transition-colors text-left",
1244
+ isActive ? "bg-violet-500/10 text-violet-950 dark:text-violet-100" : "text-zinc-700 dark:text-zinc-300 hover:bg-zinc-100/80 dark:hover:bg-zinc-900/80"
1245
+ ),
1246
+ children: [
1247
+ /* @__PURE__ */ jsxs("span", { className: "flex items-center gap-2.5", children: [
1248
+ /* @__PURE__ */ jsx(
1249
+ Icon,
1250
+ {
1251
+ className: cn(
1252
+ "h-4 w-4",
1253
+ isActive ? "text-violet-600 dark:text-violet-400" : "text-zinc-400 dark:text-zinc-500"
1254
+ )
1255
+ }
1256
+ ),
1257
+ /* @__PURE__ */ jsx("span", { className: "font-medium", children: preset.label })
1258
+ ] }),
1259
+ preset.hasSubmenu && /* @__PURE__ */ jsx(ChevronRight, { className: "h-3.5 w-3.5 text-zinc-400" })
1260
+ ]
1261
+ }
1262
+ ),
1263
+ preset.hasSubmenu === "tone" && activeSubmenu === "tone" && /* @__PURE__ */ jsx("div", { className: "flex flex-wrap gap-1.5 px-3 py-2 ml-6", children: TONES.map((tone) => /* @__PURE__ */ jsx(
1264
+ "button",
1265
+ {
1266
+ type: "button",
1267
+ onClick: () => runAction(
1268
+ "Tone",
1269
+ selectedText,
1270
+ `Rewrite in a ${tone} tone.`,
1271
+ `Applying ${tone} tone...`
1272
+ ),
1273
+ className: "rounded-lg border border-zinc-200 dark:border-zinc-800 bg-zinc-50 dark:bg-zinc-900 hover:border-violet-400 hover:bg-violet-500/10 px-2.5 py-1 text-xs font-medium text-zinc-700 dark:text-zinc-200 transition-colors",
1274
+ children: tone
1275
+ },
1276
+ tone
1277
+ )) }),
1278
+ preset.hasSubmenu === "language" && activeSubmenu === "language" && /* @__PURE__ */ jsx("div", { className: "flex flex-wrap gap-1.5 px-3 py-2 ml-6", children: LANGUAGES.map((lang) => /* @__PURE__ */ jsx(
1279
+ "button",
1280
+ {
1281
+ type: "button",
1282
+ onClick: () => runAction(
1283
+ "Translate",
1284
+ selectedText,
1285
+ `Translate to ${lang}.`,
1286
+ `Translating to ${lang}...`
1287
+ ),
1288
+ className: "rounded-lg border border-zinc-200 dark:border-zinc-800 bg-zinc-50 dark:bg-zinc-900 hover:border-violet-400 hover:bg-violet-500/10 px-2.5 py-1 text-xs font-medium text-zinc-700 dark:text-zinc-200 transition-colors",
1289
+ children: lang
1290
+ },
1291
+ lang
1292
+ )) })
1293
+ ] }, preset.id);
1294
+ }) }),
1295
+ /* @__PURE__ */ jsxs("div", { className: "border-t border-zinc-100 dark:border-zinc-800/80 bg-zinc-50/70 dark:bg-zinc-900/50 px-3 py-1.5", children: [
1296
+ /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-between gap-2", children: [
1297
+ /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-1 overflow-x-auto scrollbar-none", children: [
1298
+ /* @__PURE__ */ jsx("span", { className: "text-[11px] font-medium text-zinc-400 mr-1 shrink-0", children: "Voice:" }),
1299
+ Object.keys(WRITING_STYLE_PRESETS).map(
1300
+ (styleKey) => {
1301
+ const active = writingStyle === styleKey;
1302
+ return /* @__PURE__ */ jsx(
1303
+ "button",
1304
+ {
1305
+ type: "button",
1306
+ onClick: () => {
1307
+ setWritingStyle(styleKey);
1308
+ if (typeof window !== "undefined") {
1309
+ localStorage.setItem("notiq_ai_writing_style", styleKey);
1310
+ }
1311
+ },
1312
+ className: cn(
1313
+ "rounded-md px-2 py-0.5 text-[11px] font-medium transition-colors shrink-0",
1314
+ active ? "bg-violet-600 text-white shadow-sm" : "text-zinc-500 dark:text-zinc-400 hover:bg-zinc-200/70 dark:hover:bg-zinc-800"
1315
+ ),
1316
+ children: WRITING_STYLE_PRESETS[styleKey].label
1317
+ },
1318
+ styleKey
1319
+ );
1320
+ }
1321
+ )
1322
+ ] }),
1323
+ /* @__PURE__ */ jsx(
1324
+ "button",
1325
+ {
1326
+ type: "button",
1327
+ onClick: () => setShowStyleEditor((v) => !v),
1328
+ className: cn(
1329
+ "text-[11px] font-medium px-2 py-0.5 rounded-md transition-colors shrink-0",
1330
+ customStyleGuide.trim() || showStyleEditor ? "text-violet-600 dark:text-violet-400 bg-violet-500/10" : "text-zinc-400 hover:text-zinc-600 dark:hover:text-zinc-300"
1331
+ ),
1332
+ title: "Train AI with custom style rules",
1333
+ children: showStyleEditor ? "Done" : customStyleGuide.trim() ? "Rules \u2713" : "+ Rules"
1334
+ }
1335
+ )
1336
+ ] }),
1337
+ showStyleEditor && /* @__PURE__ */ jsx("div", { className: "mt-1.5 pb-1", children: /* @__PURE__ */ jsx(
1338
+ "input",
1339
+ {
1340
+ type: "text",
1341
+ value: customStyleGuide,
1342
+ onChange: (e) => {
1343
+ setCustomStyleGuide(e.target.value);
1344
+ if (typeof window !== "undefined") {
1345
+ localStorage.setItem("notiq_ai_style_guide", e.target.value);
1346
+ }
1347
+ },
1348
+ placeholder: "Custom voice rules (e.g. active voice, concise, no jargon)...",
1349
+ className: "w-full rounded-lg border border-zinc-200 dark:border-zinc-800 bg-white dark:bg-zinc-950 px-2.5 py-1 text-xs text-zinc-800 dark:text-zinc-200 placeholder:text-zinc-400 focus:outline-none focus:border-violet-400"
1350
+ }
1351
+ ) })
1352
+ ] })
1353
+ ]
1354
+ }
1355
+ ),
1356
+ phase === "streaming" && /* @__PURE__ */ jsxs("div", { className: "fixed bottom-8 left-1/2 -translate-x-1/2 z-[9999] flex flex-col items-center gap-2 max-w-[calc(100vw-2rem)]", children: [
1357
+ parsedStream.thinking && /* @__PURE__ */ jsxs("div", { className: "w-[min(34rem,calc(100vw-2rem))] max-h-32 overflow-y-auto rounded-2xl border border-violet-200/80 dark:border-violet-800/60 bg-white/95 dark:bg-zinc-950/95 backdrop-blur-xl px-3.5 py-2.5 text-[11px] leading-relaxed text-zinc-600 dark:text-zinc-300 shadow-lg animate-in fade-in slide-in-from-bottom-2 duration-150", children: [
1358
+ /* @__PURE__ */ jsxs("div", { className: "mb-1 flex items-center gap-1.5 text-[10px] font-semibold uppercase tracking-wider text-violet-600 dark:text-violet-400", children: [
1359
+ /* @__PURE__ */ jsx(Brain, { className: "h-3 w-3 animate-pulse" }),
1360
+ /* @__PURE__ */ jsx("span", { children: "AI Thinking" })
1361
+ ] }),
1362
+ /* @__PURE__ */ jsx("div", { className: "whitespace-pre-wrap", children: parsedStream.thinking })
1363
+ ] }),
1364
+ /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-3 rounded-full border border-violet-200/80 dark:border-violet-800/60 bg-white/95 dark:bg-zinc-900/95 backdrop-blur-xl px-4 py-2 shadow-xl shadow-violet-500/15 animate-in fade-in slide-in-from-bottom-2 duration-150", children: [
1365
+ /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2 text-xs font-medium text-zinc-700 dark:text-zinc-200", children: [
1366
+ /* @__PURE__ */ jsx(Loader2, { className: "h-3.5 w-3.5 animate-spin text-violet-600 dark:text-violet-400" }),
1367
+ /* @__PURE__ */ jsx("span", { children: activeLabel }),
1368
+ wordCount > 0 && /* @__PURE__ */ jsxs("span", { className: "text-[11px] text-zinc-400 tabular-nums", children: [
1369
+ wordCount,
1370
+ "w"
1371
+ ] })
1372
+ ] }),
1373
+ /* @__PURE__ */ jsx("div", { className: "h-3.5 w-px bg-zinc-200 dark:bg-zinc-800" }),
1374
+ /* @__PURE__ */ jsxs(
1375
+ "button",
1376
+ {
1377
+ type: "button",
1378
+ onClick: handleStopStreaming,
1379
+ className: "inline-flex items-center gap-1.5 rounded-full bg-zinc-100 hover:bg-zinc-200 dark:bg-zinc-800 dark:hover:bg-zinc-700 px-2.5 py-1 text-xs font-medium text-zinc-700 dark:text-zinc-200 transition-colors",
1380
+ children: [
1381
+ /* @__PURE__ */ jsx(Square, { className: "h-2.5 w-2.5 fill-current" }),
1382
+ /* @__PURE__ */ jsx("span", { children: "Stop" }),
1383
+ /* @__PURE__ */ jsx("kbd", { className: "rounded bg-white/80 dark:bg-zinc-900 px-1 py-0.5 text-[10px] text-zinc-400 border border-zinc-200/80 dark:border-zinc-700", children: "Esc" })
1384
+ ]
1385
+ }
1386
+ )
1387
+ ] })
1388
+ ] }),
1389
+ phase === "review" && /* @__PURE__ */ jsxs("div", { className: "fixed bottom-8 left-1/2 -translate-x-1/2 z-[9999] flex flex-col items-center gap-2 max-w-[calc(100vw-2rem)]", children: [
1390
+ showTrace && (parsedStream.thinking || parsedStream.sources.length > 0) && /* @__PURE__ */ jsxs("div", { className: "w-[min(40rem,calc(100vw-2rem))] max-h-52 overflow-y-auto rounded-2xl border border-violet-200/90 dark:border-violet-800/70 bg-white/95 dark:bg-zinc-950/95 backdrop-blur-xl p-3 text-xs leading-relaxed shadow-2xl shadow-violet-500/15 animate-in fade-in slide-in-from-bottom-2 duration-150 space-y-2.5", children: [
1391
+ parsedStream.thinking && /* @__PURE__ */ jsxs("div", { children: [
1392
+ /* @__PURE__ */ jsxs("div", { className: "mb-1 flex items-center justify-between text-[10px] font-semibold uppercase tracking-wider text-violet-600 dark:text-violet-400", children: [
1393
+ /* @__PURE__ */ jsxs("span", { className: "inline-flex items-center gap-1", children: [
1394
+ /* @__PURE__ */ jsx(Brain, { className: "h-3 w-3" }),
1395
+ "AI Reasoning"
1396
+ ] }),
1397
+ /* @__PURE__ */ jsx(
1398
+ "button",
1399
+ {
1400
+ type: "button",
1401
+ onClick: () => setShowTrace(false),
1402
+ className: "rounded px-1.5 py-0.5 hover:bg-zinc-100 dark:hover:bg-zinc-800 text-zinc-500",
1403
+ children: "Hide"
1404
+ }
1405
+ )
1406
+ ] }),
1407
+ /* @__PURE__ */ jsx("div", { className: "whitespace-pre-wrap text-zinc-600 dark:text-zinc-300", children: parsedStream.thinking })
1408
+ ] }),
1409
+ parsedStream.sources.length > 0 && /* @__PURE__ */ jsxs("div", { children: [
1410
+ /* @__PURE__ */ jsxs("div", { className: "mb-1 flex items-center gap-1 text-[10px] font-semibold uppercase tracking-wider text-sky-600 dark:text-sky-400", children: [
1411
+ /* @__PURE__ */ jsx(Globe, { className: "h-3 w-3" }),
1412
+ "Research Sources (",
1413
+ parsedStream.sources.length,
1414
+ ")"
1415
+ ] }),
1416
+ /* @__PURE__ */ jsx("div", { className: "flex flex-wrap gap-1.5", children: parsedStream.sources.map((src, i) => /* @__PURE__ */ jsx(
1417
+ "a",
1418
+ {
1419
+ href: src.url,
1420
+ target: "_blank",
1421
+ rel: "noopener noreferrer",
1422
+ className: "inline-flex items-center gap-1 rounded-lg border border-sky-500/30 bg-sky-500/10 px-2 py-0.5 text-[11px] font-medium text-sky-700 dark:text-sky-300 hover:bg-sky-500/20 transition-colors",
1423
+ children: /* @__PURE__ */ jsx("span", { className: "truncate max-w-[14rem]", children: src.title })
1424
+ },
1425
+ i
1426
+ )) })
1427
+ ] })
1428
+ ] }),
1429
+ showDiff && diffParts.length > 0 && /* @__PURE__ */ jsxs("div", { className: "w-[min(40rem,calc(100vw-2rem))] max-h-48 overflow-y-auto rounded-2xl border border-violet-200/90 dark:border-violet-800/70 bg-white/95 dark:bg-zinc-950/95 backdrop-blur-xl p-3 text-xs leading-relaxed shadow-2xl shadow-violet-500/15 animate-in fade-in slide-in-from-bottom-2 duration-150", children: [
1430
+ /* @__PURE__ */ jsxs("div", { className: "mb-1.5 flex items-center justify-between text-[10px] font-semibold uppercase tracking-wider text-zinc-400", children: [
1431
+ /* @__PURE__ */ jsx("span", { children: "Inline Diff (Original vs. AI)" }),
1432
+ /* @__PURE__ */ jsx(
1433
+ "button",
1434
+ {
1435
+ type: "button",
1436
+ onClick: () => setShowDiff(false),
1437
+ className: "rounded px-1.5 py-0.5 hover:bg-zinc-100 dark:hover:bg-zinc-800 text-zinc-500",
1438
+ children: "Hide"
1439
+ }
1440
+ )
1441
+ ] }),
1442
+ /* @__PURE__ */ jsx("div", { className: "whitespace-pre-wrap break-words text-zinc-700 dark:text-zinc-200", children: diffParts.map((part, idx) => {
1443
+ if (part.type === "added") {
1444
+ return /* @__PURE__ */ jsx(
1445
+ "ins",
1446
+ {
1447
+ className: "rounded bg-emerald-500/15 px-0.5 text-emerald-700 dark:text-emerald-300 no-underline",
1448
+ children: part.text
1449
+ },
1450
+ idx
1451
+ );
1452
+ }
1453
+ if (part.type === "removed") {
1454
+ return /* @__PURE__ */ jsx(
1455
+ "del",
1456
+ {
1457
+ className: "rounded bg-rose-500/15 px-0.5 text-rose-600 dark:text-rose-400 line-through",
1458
+ children: part.text
1459
+ },
1460
+ idx
1461
+ );
1462
+ }
1463
+ return /* @__PURE__ */ jsx("span", { children: part.text }, idx);
1464
+ }) })
1465
+ ] }),
1466
+ /* @__PURE__ */ jsxs("div", { className: "flex flex-wrap items-center gap-2 rounded-2xl border border-violet-200/90 dark:border-violet-800/70 bg-white/95 dark:bg-zinc-950/95 backdrop-blur-xl p-1.5 pl-3 shadow-2xl shadow-violet-500/15 animate-in fade-in slide-in-from-bottom-2 duration-150", children: [
1467
+ /* @__PURE__ */ jsx(Sparkles, { className: "h-3.5 w-3.5 text-violet-600 dark:text-violet-400 shrink-0" }),
1468
+ /* @__PURE__ */ jsx("form", { onSubmit: handleFollowUpSubmit, className: "flex items-center", children: /* @__PURE__ */ jsx(
1469
+ "input",
1470
+ {
1471
+ ref: followUpRef,
1472
+ type: "text",
1473
+ value: followUpPrompt,
1474
+ onChange: (e) => setFollowUpPrompt(e.target.value),
1475
+ placeholder: "Refine (e.g. shorter, add table)...",
1476
+ className: "w-44 sm:w-56 bg-transparent text-xs text-zinc-900 dark:text-zinc-100 placeholder:text-zinc-400 focus:outline-none"
1477
+ }
1478
+ ) }),
1479
+ /* @__PURE__ */ jsx("div", { className: "h-4 w-px bg-zinc-200 dark:bg-zinc-800" }),
1480
+ (parsedStream.thinking || parsedStream.sources.length > 0) && /* @__PURE__ */ jsxs(
1481
+ "button",
1482
+ {
1483
+ type: "button",
1484
+ onClick: () => setShowTrace((prev) => !prev),
1485
+ className: `inline-flex items-center gap-1 rounded-xl px-2.5 py-1.5 text-xs font-medium transition-colors ${showTrace ? "bg-sky-100 text-sky-700 dark:bg-sky-900/50 dark:text-sky-300" : "text-zinc-600 dark:text-zinc-300 hover:bg-zinc-100 dark:hover:bg-zinc-900"}`,
1486
+ title: "View AI thinking & research sources",
1487
+ children: [
1488
+ /* @__PURE__ */ jsx(Brain, { className: "h-3.5 w-3.5" }),
1489
+ /* @__PURE__ */ jsx("span", { className: "hidden sm:inline", children: parsedStream.sources.length > 0 ? `Sources (${parsedStream.sources.length})` : "Thoughts" })
1490
+ ]
1491
+ }
1492
+ ),
1493
+ canShowDiff && /* @__PURE__ */ jsxs(
1494
+ "button",
1495
+ {
1496
+ type: "button",
1497
+ onClick: () => setShowDiff((prev) => !prev),
1498
+ className: `inline-flex items-center gap-1 rounded-xl px-2.5 py-1.5 text-xs font-medium transition-colors ${showDiff ? "bg-violet-100 text-violet-700 dark:bg-violet-900/50 dark:text-violet-300" : "text-zinc-600 dark:text-zinc-300 hover:bg-zinc-100 dark:hover:bg-zinc-900"}`,
1499
+ title: "Compare original vs. AI rewrite",
1500
+ children: [
1501
+ /* @__PURE__ */ jsx(GitCompareArrows, { className: "h-3.5 w-3.5" }),
1502
+ /* @__PURE__ */ jsx("span", { className: "hidden sm:inline", children: "Diff" })
1503
+ ]
1504
+ }
1505
+ ),
1506
+ /* @__PURE__ */ jsxs(
1507
+ "button",
1508
+ {
1509
+ type: "button",
1510
+ onClick: handleRetry,
1511
+ className: "inline-flex items-center gap-1 rounded-xl px-2.5 py-1.5 text-xs font-medium text-zinc-600 dark:text-zinc-300 hover:bg-zinc-100 dark:hover:bg-zinc-900 transition-colors",
1512
+ title: "Regenerate",
1513
+ children: [
1514
+ /* @__PURE__ */ jsx(RotateCcw, { className: "h-3.5 w-3.5" }),
1515
+ /* @__PURE__ */ jsx("span", { className: "hidden sm:inline", children: "Retry" })
1516
+ ]
1517
+ }
1518
+ ),
1519
+ /* @__PURE__ */ jsxs(
1520
+ "button",
1521
+ {
1522
+ type: "button",
1523
+ onClick: handleDiscard,
1524
+ className: "inline-flex items-center gap-1 rounded-xl px-2.5 py-1.5 text-xs font-medium text-zinc-600 dark:text-zinc-300 hover:bg-rose-50 hover:text-rose-600 dark:hover:bg-rose-950/40 dark:hover:text-rose-400 transition-colors",
1525
+ title: "Discard (Esc)",
1526
+ children: [
1527
+ /* @__PURE__ */ jsx(X, { className: "h-3.5 w-3.5" }),
1528
+ /* @__PURE__ */ jsx("span", { children: "Discard" })
1529
+ ]
1530
+ }
1531
+ ),
1532
+ /* @__PURE__ */ jsxs(
1533
+ "button",
1534
+ {
1535
+ type: "button",
1536
+ onClick: handleAccept,
1537
+ className: "inline-flex items-center gap-1.5 rounded-xl bg-violet-600 hover:bg-violet-500 px-3 py-1.5 text-xs font-medium text-white shadow-sm transition-colors",
1538
+ title: "Accept (\u2318Enter)",
1539
+ children: [
1540
+ /* @__PURE__ */ jsx(Check, { className: "h-3.5 w-3.5" }),
1541
+ /* @__PURE__ */ jsx("span", { children: "Accept" })
1542
+ ]
1543
+ }
1544
+ )
1545
+ ] })
1546
+ ] })
1547
+ ] }),
1548
+ document.body
1549
+ );
1550
+ }
1551
+
1552
+ export {
1553
+ OPEN_AI_COMMAND_BAR_COMMAND,
1554
+ extractThinkingAndSources,
1555
+ AICommandBarPlugin
1556
+ };