@milkdown/crepe 7.20.0 → 7.21.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 (173) hide show
  1. package/lib/cjs/builder.js +1 -0
  2. package/lib/cjs/builder.js.map +1 -1
  3. package/lib/cjs/feature/ai/index.js +1492 -0
  4. package/lib/cjs/feature/ai/index.js.map +1 -0
  5. package/lib/cjs/feature/block-edit/index.js +1 -0
  6. package/lib/cjs/feature/block-edit/index.js.map +1 -1
  7. package/lib/cjs/feature/code-mirror/index.js +1 -0
  8. package/lib/cjs/feature/code-mirror/index.js.map +1 -1
  9. package/lib/cjs/feature/cursor/index.js +1 -0
  10. package/lib/cjs/feature/cursor/index.js.map +1 -1
  11. package/lib/cjs/feature/image-block/index.js +1 -0
  12. package/lib/cjs/feature/image-block/index.js.map +1 -1
  13. package/lib/cjs/feature/latex/index.js +2 -0
  14. package/lib/cjs/feature/latex/index.js.map +1 -1
  15. package/lib/cjs/feature/link-tooltip/index.js +1 -0
  16. package/lib/cjs/feature/link-tooltip/index.js.map +1 -1
  17. package/lib/cjs/feature/list-item/index.js +1 -0
  18. package/lib/cjs/feature/list-item/index.js.map +1 -1
  19. package/lib/cjs/feature/placeholder/index.js +1 -0
  20. package/lib/cjs/feature/placeholder/index.js.map +1 -1
  21. package/lib/cjs/feature/table/index.js +1 -0
  22. package/lib/cjs/feature/table/index.js.map +1 -1
  23. package/lib/cjs/feature/toolbar/index.js +488 -3
  24. package/lib/cjs/feature/toolbar/index.js.map +1 -1
  25. package/lib/cjs/feature/top-bar/index.js +1 -0
  26. package/lib/cjs/feature/top-bar/index.js.map +1 -1
  27. package/lib/cjs/index.js +1424 -25
  28. package/lib/cjs/index.js.map +1 -1
  29. package/lib/cjs/llm-providers/anthropic/index.js +147 -0
  30. package/lib/cjs/llm-providers/anthropic/index.js.map +1 -0
  31. package/lib/cjs/llm-providers/openai/index.js +138 -0
  32. package/lib/cjs/llm-providers/openai/index.js.map +1 -0
  33. package/lib/esm/builder.js +1 -0
  34. package/lib/esm/builder.js.map +1 -1
  35. package/lib/esm/feature/ai/index.js +1487 -0
  36. package/lib/esm/feature/ai/index.js.map +1 -0
  37. package/lib/esm/feature/block-edit/index.js +1 -0
  38. package/lib/esm/feature/block-edit/index.js.map +1 -1
  39. package/lib/esm/feature/code-mirror/index.js +1 -0
  40. package/lib/esm/feature/code-mirror/index.js.map +1 -1
  41. package/lib/esm/feature/cursor/index.js +1 -0
  42. package/lib/esm/feature/cursor/index.js.map +1 -1
  43. package/lib/esm/feature/image-block/index.js +1 -0
  44. package/lib/esm/feature/image-block/index.js.map +1 -1
  45. package/lib/esm/feature/latex/index.js +2 -0
  46. package/lib/esm/feature/latex/index.js.map +1 -1
  47. package/lib/esm/feature/link-tooltip/index.js +1 -0
  48. package/lib/esm/feature/link-tooltip/index.js.map +1 -1
  49. package/lib/esm/feature/list-item/index.js +1 -0
  50. package/lib/esm/feature/list-item/index.js.map +1 -1
  51. package/lib/esm/feature/placeholder/index.js +1 -0
  52. package/lib/esm/feature/placeholder/index.js.map +1 -1
  53. package/lib/esm/feature/table/index.js +1 -0
  54. package/lib/esm/feature/table/index.js.map +1 -1
  55. package/lib/esm/feature/toolbar/index.js +490 -5
  56. package/lib/esm/feature/toolbar/index.js.map +1 -1
  57. package/lib/esm/feature/top-bar/index.js +1 -0
  58. package/lib/esm/feature/top-bar/index.js.map +1 -1
  59. package/lib/esm/index.js +1414 -15
  60. package/lib/esm/index.js.map +1 -1
  61. package/lib/esm/llm-providers/anthropic/index.js +145 -0
  62. package/lib/esm/llm-providers/anthropic/index.js.map +1 -0
  63. package/lib/esm/llm-providers/openai/index.js +136 -0
  64. package/lib/esm/llm-providers/openai/index.js.map +1 -0
  65. package/lib/theme/common/ai.css +446 -0
  66. package/lib/theme/common/code-mirror.css +14 -0
  67. package/lib/theme/common/diff.css +177 -0
  68. package/lib/theme/common/style.css +2 -0
  69. package/lib/tsconfig.tsbuildinfo +1 -1
  70. package/lib/types/feature/ai/ai.spec.d.ts +2 -0
  71. package/lib/types/feature/ai/ai.spec.d.ts.map +1 -0
  72. package/lib/types/feature/ai/commands.d.ts +24 -0
  73. package/lib/types/feature/ai/commands.d.ts.map +1 -0
  74. package/lib/types/feature/ai/context.d.ts +4 -0
  75. package/lib/types/feature/ai/context.d.ts.map +1 -0
  76. package/lib/types/feature/ai/diff-actions/index.d.ts +12 -0
  77. package/lib/types/feature/ai/diff-actions/index.d.ts.map +1 -0
  78. package/lib/types/feature/ai/diff-actions/view.d.ts +21 -0
  79. package/lib/types/feature/ai/diff-actions/view.d.ts.map +1 -0
  80. package/lib/types/feature/ai/index.d.ts +7 -0
  81. package/lib/types/feature/ai/index.d.ts.map +1 -0
  82. package/lib/types/feature/ai/instruction-tooltip/component.d.ts +26 -0
  83. package/lib/types/feature/ai/instruction-tooltip/component.d.ts.map +1 -0
  84. package/lib/types/feature/ai/instruction-tooltip/index.d.ts +17 -0
  85. package/lib/types/feature/ai/instruction-tooltip/index.d.ts.map +1 -0
  86. package/lib/types/feature/ai/instruction-tooltip/suggestions.d.ts +50 -0
  87. package/lib/types/feature/ai/instruction-tooltip/suggestions.d.ts.map +1 -0
  88. package/lib/types/feature/ai/instruction-tooltip/view.d.ts +19 -0
  89. package/lib/types/feature/ai/instruction-tooltip/view.d.ts.map +1 -0
  90. package/lib/types/feature/ai/streaming-indicator.d.ts +9 -0
  91. package/lib/types/feature/ai/streaming-indicator.d.ts.map +1 -0
  92. package/lib/types/feature/ai/types.d.ts +58 -0
  93. package/lib/types/feature/ai/types.d.ts.map +1 -0
  94. package/lib/types/feature/index.d.ts +4 -1
  95. package/lib/types/feature/index.d.ts.map +1 -1
  96. package/lib/types/feature/latex/inline-tooltip/inline-tooltip.spec.d.ts +2 -0
  97. package/lib/types/feature/latex/inline-tooltip/inline-tooltip.spec.d.ts.map +1 -0
  98. package/lib/types/feature/latex/inline-tooltip/view.d.ts.map +1 -1
  99. package/lib/types/feature/loader.d.ts.map +1 -1
  100. package/lib/types/feature/toolbar/config.d.ts.map +1 -1
  101. package/lib/types/feature/toolbar/index.d.ts +1 -0
  102. package/lib/types/feature/toolbar/index.d.ts.map +1 -1
  103. package/lib/types/icons/ai.d.ts +2 -0
  104. package/lib/types/icons/ai.d.ts.map +1 -0
  105. package/lib/types/icons/chevron-left.d.ts +2 -0
  106. package/lib/types/icons/chevron-left.d.ts.map +1 -0
  107. package/lib/types/icons/chevron-right.d.ts +2 -0
  108. package/lib/types/icons/chevron-right.d.ts.map +1 -0
  109. package/lib/types/icons/enter-key.d.ts +2 -0
  110. package/lib/types/icons/enter-key.d.ts.map +1 -0
  111. package/lib/types/icons/grammar-check.d.ts +2 -0
  112. package/lib/types/icons/grammar-check.d.ts.map +1 -0
  113. package/lib/types/icons/index.d.ts +11 -0
  114. package/lib/types/icons/index.d.ts.map +1 -1
  115. package/lib/types/icons/longer.d.ts +2 -0
  116. package/lib/types/icons/longer.d.ts.map +1 -0
  117. package/lib/types/icons/retry.d.ts +2 -0
  118. package/lib/types/icons/retry.d.ts.map +1 -0
  119. package/lib/types/icons/send-prompt.d.ts +2 -0
  120. package/lib/types/icons/send-prompt.d.ts.map +1 -0
  121. package/lib/types/icons/send.d.ts +2 -0
  122. package/lib/types/icons/send.d.ts.map +1 -0
  123. package/lib/types/icons/shorter.d.ts +2 -0
  124. package/lib/types/icons/shorter.d.ts.map +1 -0
  125. package/lib/types/icons/translate.d.ts +2 -0
  126. package/lib/types/icons/translate.d.ts.map +1 -0
  127. package/lib/types/llm-providers/anthropic/index.d.ts +21 -0
  128. package/lib/types/llm-providers/anthropic/index.d.ts.map +1 -0
  129. package/lib/types/llm-providers/openai/index.d.ts +15 -0
  130. package/lib/types/llm-providers/openai/index.d.ts.map +1 -0
  131. package/lib/types/llm-providers/providers.spec.d.ts +2 -0
  132. package/lib/types/llm-providers/providers.spec.d.ts.map +1 -0
  133. package/lib/types/llm-providers/shared.d.ts +16 -0
  134. package/lib/types/llm-providers/shared.d.ts.map +1 -0
  135. package/package.json +18 -2
  136. package/src/feature/ai/ai.spec.ts +742 -0
  137. package/src/feature/ai/commands.ts +257 -0
  138. package/src/feature/ai/context.ts +45 -0
  139. package/src/feature/ai/diff-actions/index.ts +95 -0
  140. package/src/feature/ai/diff-actions/view.ts +237 -0
  141. package/src/feature/ai/index.ts +118 -0
  142. package/src/feature/ai/instruction-tooltip/component.tsx +414 -0
  143. package/src/feature/ai/instruction-tooltip/index.ts +101 -0
  144. package/src/feature/ai/instruction-tooltip/suggestions.ts +249 -0
  145. package/src/feature/ai/instruction-tooltip/view.ts +159 -0
  146. package/src/feature/ai/streaming-indicator.ts +183 -0
  147. package/src/feature/ai/types.ts +178 -0
  148. package/src/feature/index.ts +8 -2
  149. package/src/feature/latex/inline-tooltip/inline-tooltip.spec.ts +81 -0
  150. package/src/feature/latex/inline-tooltip/view.ts +2 -0
  151. package/src/feature/loader.ts +4 -0
  152. package/src/feature/toolbar/config.ts +27 -1
  153. package/src/feature/toolbar/index.ts +1 -0
  154. package/src/icons/ai.ts +14 -0
  155. package/src/icons/chevron-left.ts +15 -0
  156. package/src/icons/chevron-right.ts +15 -0
  157. package/src/icons/enter-key.ts +13 -0
  158. package/src/icons/grammar-check.ts +13 -0
  159. package/src/icons/index.ts +11 -0
  160. package/src/icons/longer.ts +13 -0
  161. package/src/icons/retry.ts +13 -0
  162. package/src/icons/send-prompt.ts +13 -0
  163. package/src/icons/send.ts +13 -0
  164. package/src/icons/shorter.ts +13 -0
  165. package/src/icons/translate.ts +13 -0
  166. package/src/llm-providers/anthropic/index.ts +132 -0
  167. package/src/llm-providers/openai/index.ts +109 -0
  168. package/src/llm-providers/providers.spec.ts +472 -0
  169. package/src/llm-providers/shared.ts +160 -0
  170. package/src/theme/common/ai.css +430 -0
  171. package/src/theme/common/code-mirror.css +14 -0
  172. package/src/theme/common/diff.css +196 -0
  173. package/src/theme/common/style.css +2 -0
@@ -0,0 +1,1487 @@
1
+ import { diffComponentConfig, diffComponent } from '@milkdown/kit/component/diff';
2
+ import { diffPluginKey, clearDiffReviewCmd, acceptAllDiffsCmd, diffConfig, diff } from '@milkdown/kit/plugin/diff';
3
+ import { streamingPluginKey, startStreamingCmd, abortStreamingCmd, pushChunkCmd, endStreamingCmd, streamingConfig, streaming } from '@milkdown/kit/plugin/streaming';
4
+ import { createSlice } from '@milkdown/kit/ctx';
5
+ import { editorViewCtx, serializerCtx, commandsCtx } from '@milkdown/kit/core';
6
+ import { aiBuildContextError, aiProviderError } from '@milkdown/kit/exception';
7
+ import { $ctx, $command, $prose } from '@milkdown/kit/utils';
8
+ import { TextSelection, PluginKey, Plugin } from '@milkdown/kit/prose/state';
9
+ import DOMPurify from 'dompurify';
10
+ import { TooltipProvider, tooltipFactory } from '@milkdown/kit/plugin/tooltip';
11
+ import { posToDOMRect } from '@milkdown/kit/prose';
12
+ import { defineComponent, ref, watch, computed, h, nextTick, createApp } from 'vue';
13
+ import { Icon } from '@milkdown/kit/component';
14
+ import { DecorationSet, Decoration } from '@milkdown/kit/prose/view';
15
+
16
+ createSlice([], "FeaturesCtx");
17
+ createSlice({}, "CrepeCtx");
18
+ function useCrepeFeatures(ctx) {
19
+ return ctx.use("FeaturesCtx");
20
+ }
21
+ function crepeFeatureConfig(feature) {
22
+ return (ctx) => {
23
+ useCrepeFeatures(ctx).update((features) => {
24
+ if (features.includes(feature)) {
25
+ return features;
26
+ }
27
+ return [...features, feature];
28
+ });
29
+ };
30
+ }
31
+
32
+ var CrepeFeature = /* @__PURE__ */ ((CrepeFeature2) => {
33
+ CrepeFeature2["CodeMirror"] = "code-mirror";
34
+ CrepeFeature2["ListItem"] = "list-item";
35
+ CrepeFeature2["LinkTooltip"] = "link-tooltip";
36
+ CrepeFeature2["Cursor"] = "cursor";
37
+ CrepeFeature2["ImageBlock"] = "image-block";
38
+ CrepeFeature2["BlockEdit"] = "block-edit";
39
+ CrepeFeature2["Toolbar"] = "toolbar";
40
+ CrepeFeature2["Placeholder"] = "placeholder";
41
+ CrepeFeature2["Table"] = "table";
42
+ CrepeFeature2["Latex"] = "latex";
43
+ CrepeFeature2["TopBar"] = "top-bar";
44
+ CrepeFeature2["AI"] = "ai";
45
+ return CrepeFeature2;
46
+ })(CrepeFeature || {});
47
+
48
+ function defaultBuildContext(ctx, instruction) {
49
+ var _a;
50
+ const view = ctx.get(editorViewCtx);
51
+ const serializer = ctx.get(serializerCtx);
52
+ const { state } = view;
53
+ const document = serializer(state.doc);
54
+ let selection = "";
55
+ if (!state.selection.empty) {
56
+ const { from, to } = state.selection;
57
+ const slice = state.doc.slice(from, to);
58
+ const { schema } = state.doc.type;
59
+ let wrapper = schema.topNodeType.createAndFill(null, slice.content);
60
+ if (!wrapper) {
61
+ const paragraph = (_a = schema.nodes.paragraph) == null ? void 0 : _a.createAndFill(
62
+ null,
63
+ slice.content
64
+ );
65
+ if (paragraph) wrapper = schema.topNodeType.createAndFill(null, paragraph);
66
+ }
67
+ selection = wrapper ? serializer(wrapper) : state.doc.textBetween(from, to);
68
+ }
69
+ return { document, selection, instruction };
70
+ }
71
+
72
+ const aiProviderConfig = $ctx(
73
+ {
74
+ provider: void 0,
75
+ buildContext: void 0,
76
+ diffReviewOnEnd: true,
77
+ onError: (error) => {
78
+ console.error(`[milkdown/ai] [${error.code}]`, error);
79
+ },
80
+ aiIcon: void 0
81
+ },
82
+ "aiProviderConfig"
83
+ );
84
+ const aiSessionCtx = $ctx(
85
+ {
86
+ abortController: null,
87
+ label: "",
88
+ lastInstruction: "",
89
+ lastLabel: void 0,
90
+ lastFrom: -1,
91
+ lastTo: -1,
92
+ diffOwnedByAI: false
93
+ },
94
+ "aiSession"
95
+ );
96
+ function emitAIError(ctx, error) {
97
+ const config = ctx.get(aiProviderConfig.key);
98
+ try {
99
+ config.onError(error);
100
+ } catch (handlerError) {
101
+ console.error("[milkdown/ai] onError handler failed:", handlerError);
102
+ }
103
+ }
104
+ function clearActiveSession(ctx) {
105
+ const current = ctx.get(aiSessionCtx.key);
106
+ ctx.set(aiSessionCtx.key, {
107
+ ...current,
108
+ abortController: null,
109
+ label: ""
110
+ });
111
+ }
112
+ async function runProvider(ctx, provider, promptContext, abortController) {
113
+ try {
114
+ const iterable = provider(promptContext, abortController.signal);
115
+ const commands = ctx.get(commandsCtx);
116
+ for await (const chunk of iterable) {
117
+ if (abortController.signal.aborted) break;
118
+ commands.call(pushChunkCmd.key, chunk);
119
+ }
120
+ if (abortController.signal.aborted) return;
121
+ const config = ctx.get(aiProviderConfig.key);
122
+ if (config.diffReviewOnEnd) {
123
+ const cur = ctx.get(aiSessionCtx.key);
124
+ ctx.set(aiSessionCtx.key, { ...cur, diffOwnedByAI: true });
125
+ }
126
+ const dispatched = commands.call(endStreamingCmd.key, {
127
+ diffReview: config.diffReviewOnEnd
128
+ });
129
+ if (config.diffReviewOnEnd && !dispatched) {
130
+ const cur = ctx.get(aiSessionCtx.key);
131
+ ctx.set(aiSessionCtx.key, { ...cur, diffOwnedByAI: false });
132
+ }
133
+ } catch (error) {
134
+ if (abortController.signal.aborted) return;
135
+ const milkdownError = aiProviderError(error);
136
+ emitAIError(ctx, milkdownError);
137
+ const commands = ctx.get(commandsCtx);
138
+ commands.call(abortStreamingCmd.key, { keep: false });
139
+ } finally {
140
+ const current = ctx.get(aiSessionCtx.key);
141
+ if (current.abortController === abortController) {
142
+ clearActiveSession(ctx);
143
+ }
144
+ }
145
+ }
146
+ const runAICmd = $command("RunAI", (ctx) => {
147
+ return (options) => (state, dispatch) => {
148
+ var _a, _b, _c, _d;
149
+ if (!(options == null ? void 0 : options.instruction)) return false;
150
+ const config = ctx.get(aiProviderConfig.key);
151
+ if (!config.provider) return false;
152
+ const session = ctx.get(aiSessionCtx.key);
153
+ if (session.abortController) return false;
154
+ if ((_a = streamingPluginKey.getState(state)) == null ? void 0 : _a.active) return false;
155
+ if ((_b = diffPluginKey.getState(state)) == null ? void 0 : _b.active) return false;
156
+ if (!dispatch) return true;
157
+ const abortController = new AbortController();
158
+ const { from, to } = state.selection;
159
+ ctx.set(aiSessionCtx.key, {
160
+ abortController,
161
+ label: (_c = options.label) != null ? _c : "",
162
+ lastInstruction: options.instruction,
163
+ lastLabel: options.label,
164
+ lastFrom: from,
165
+ lastTo: to,
166
+ // Reset every run; only the success path that hands off to diff
167
+ // review flips it back on.
168
+ diffOwnedByAI: false
169
+ });
170
+ const commands = ctx.get(commandsCtx);
171
+ const insertAt = state.selection.empty ? "cursor" : "selection";
172
+ if (!commands.call(startStreamingCmd.key, { insertAt })) {
173
+ clearActiveSession(ctx);
174
+ return false;
175
+ }
176
+ let promptContext;
177
+ try {
178
+ const buildContext = (_d = config.buildContext) != null ? _d : defaultBuildContext;
179
+ promptContext = buildContext(ctx, options.instruction);
180
+ } catch (error) {
181
+ const milkdownError = aiBuildContextError(error);
182
+ emitAIError(ctx, milkdownError);
183
+ commands.call(abortStreamingCmd.key, { keep: false });
184
+ clearActiveSession(ctx);
185
+ return false;
186
+ }
187
+ void runProvider(ctx, config.provider, promptContext, abortController);
188
+ return true;
189
+ };
190
+ });
191
+ const abortAICmd = $command("AbortAI", (ctx) => {
192
+ return (options) => (state, dispatch) => {
193
+ var _a;
194
+ const session = ctx.get(aiSessionCtx.key);
195
+ if (!dispatch) return !!session.abortController;
196
+ if (!session.abortController) return false;
197
+ session.abortController.abort();
198
+ clearActiveSession(ctx);
199
+ if ((_a = streamingPluginKey.getState(state)) == null ? void 0 : _a.active) {
200
+ const commands = ctx.get(commandsCtx);
201
+ commands.call(abortStreamingCmd.key, options);
202
+ }
203
+ return true;
204
+ };
205
+ });
206
+
207
+ const aiIcon = `
208
+ <svg
209
+ xmlns="http://www.w3.org/2000/svg"
210
+ width="24"
211
+ height="24"
212
+ viewBox="0 0 24 24"
213
+ >
214
+ <path
215
+ fill="currentColor"
216
+ d="M19 9l1.25-2.75L23 5l-2.75-1.25L19 1l-1.25 2.75L15 5l2.75 1.25zm0 14l1.25-2.75L23 19l-2.75-1.25L19 15l-1.25 2.75L15 19l2.75 1.25zM9 20l3-6.5L18 10l-6-3.5L9 0L6 6.5L0 10l6 3.5z"
217
+ transform="translate(3 3) scale(0.75)"
218
+ />
219
+ </svg>
220
+ `;
221
+
222
+ const chevronLeftIcon = `
223
+ <svg
224
+ xmlns="http://www.w3.org/2000/svg"
225
+ fill="none"
226
+ viewBox="0 0 24 24"
227
+ stroke-width="1.5"
228
+ stroke="currentColor"
229
+ >
230
+ <path
231
+ stroke-linecap="round"
232
+ stroke-linejoin="round"
233
+ d="M15.75 19.5L8.25 12l7.5-7.5"
234
+ />
235
+ </svg>
236
+ `;
237
+
238
+ const chevronRightIcon = `
239
+ <svg
240
+ xmlns="http://www.w3.org/2000/svg"
241
+ fill="none"
242
+ viewBox="0 0 24 24"
243
+ stroke-width="1.5"
244
+ stroke="currentColor"
245
+ >
246
+ <path
247
+ stroke-linecap="round"
248
+ stroke-linejoin="round"
249
+ d="M8.25 4.5l7.5 7.5-7.5 7.5"
250
+ />
251
+ </svg>
252
+ `;
253
+
254
+ const clearIcon = `
255
+ <svg
256
+ xmlns="http://www.w3.org/2000/svg"
257
+ width="24"
258
+ height="24"
259
+ viewBox="0 0 24 24"
260
+ >
261
+ <g clip-path="url(#clip0_1098_15553)">
262
+ <path
263
+ d="M18.3007 5.70973C17.9107 5.31973 17.2807 5.31973 16.8907 5.70973L12.0007 10.5897L7.1107 5.69973C6.7207 5.30973 6.0907 5.30973 5.7007 5.69973C5.3107 6.08973 5.3107 6.71973 5.7007 7.10973L10.5907 11.9997L5.7007 16.8897C5.3107 17.2797 5.3107 17.9097 5.7007 18.2997C6.0907 18.6897 6.7207 18.6897 7.1107 18.2997L12.0007 13.4097L16.8907 18.2997C17.2807 18.6897 17.9107 18.6897 18.3007 18.2997C18.6907 17.9097 18.6907 17.2797 18.3007 16.8897L13.4107 11.9997L18.3007 7.10973C18.6807 6.72973 18.6807 6.08973 18.3007 5.70973Z"
264
+ />
265
+ </g>
266
+ <defs>
267
+ <clipPath id="clip0_1098_15553">
268
+ <rect width="24" height="24" />
269
+ </clipPath>
270
+ </defs>
271
+ </svg>
272
+ `;
273
+
274
+ const confirmIcon = `
275
+ <svg
276
+ xmlns="http://www.w3.org/2000/svg"
277
+ width="24"
278
+ height="24"
279
+ viewBox="0 0 24 24"
280
+ fill="none"
281
+ >
282
+ <g clip-path="url(#clip0_1013_1606)">
283
+ <path
284
+ d="M9.00012 16.1998L5.50012 12.6998C5.11012 12.3098 4.49012 12.3098 4.10012 12.6998C3.71012 13.0898 3.71012 13.7098 4.10012 14.0998L8.29012 18.2898C8.68012 18.6798 9.31012 18.6798 9.70012 18.2898L20.3001 7.69982C20.6901 7.30982 20.6901 6.68982 20.3001 6.29982C19.9101 5.90982 19.2901 5.90982 18.9001 6.29982L9.00012 16.1998Z"
285
+ fill="#817567"
286
+ />
287
+ </g>
288
+ <defs>
289
+ <clipPath id="clip0_1013_1606">
290
+ <rect width="24" height="24" />
291
+ </clipPath>
292
+ </defs>
293
+ </svg>
294
+ `;
295
+
296
+ const editIcon = `
297
+ <svg
298
+ xmlns="http://www.w3.org/2000/svg"
299
+ width="24"
300
+ height="24"
301
+ viewBox="0 0 24 24"
302
+ >
303
+ <g clip-path="url(#clip0_1013_1585)">
304
+ <path
305
+ d="M14.06 9.02L14.98 9.94L5.92 19H5V18.08L14.06 9.02ZM17.66 3C17.41 3 17.15 3.1 16.96 3.29L15.13 5.12L18.88 8.87L20.71 7.04C21.1 6.65 21.1 6.02 20.71 5.63L18.37 3.29C18.17 3.09 17.92 3 17.66 3ZM14.06 6.19L3 17.25V21H6.75L17.81 9.94L14.06 6.19Z"
306
+ />
307
+ </g>
308
+ <defs>
309
+ <clipPath id="clip0_1013_1585">
310
+ <rect width="24" height="24" />
311
+ </clipPath>
312
+ </defs>
313
+ </svg>
314
+ `;
315
+
316
+ const enterKeyIcon = `
317
+ <svg
318
+ xmlns="http://www.w3.org/2000/svg"
319
+ width="24"
320
+ height="24"
321
+ viewBox="0 0 24 24"
322
+ >
323
+ <path
324
+ fill="currentColor"
325
+ d="M9 16l-5-5l5-5l1.4 1.4L7.825 10H18V6h2v6H7.825l2.575 2.6z"
326
+ />
327
+ </svg>
328
+ `;
329
+
330
+ const grammarCheckIcon = `
331
+ <svg
332
+ xmlns="http://www.w3.org/2000/svg"
333
+ width="24"
334
+ height="24"
335
+ viewBox="0 0 24 24"
336
+ >
337
+ <path
338
+ fill="currentColor"
339
+ d="M9.55 17.575L4.225 12.25l1.4-1.425L9.55 14.75l8.825-8.825l1.4 1.425z"
340
+ />
341
+ </svg>
342
+ `;
343
+
344
+ const longerIcon = `
345
+ <svg
346
+ xmlns="http://www.w3.org/2000/svg"
347
+ width="24"
348
+ height="24"
349
+ viewBox="0 0 24 24"
350
+ >
351
+ <path
352
+ fill="currentColor"
353
+ d="M3 18v-2h13v2zm0-5v-2h18v2zm0-5V6h18v2zm15 13v-3h-3v-2h3v-3h2v3h3v2h-3v3z"
354
+ />
355
+ </svg>
356
+ `;
357
+
358
+ const retryIcon = `
359
+ <svg
360
+ xmlns="http://www.w3.org/2000/svg"
361
+ width="24"
362
+ height="24"
363
+ viewBox="0 0 24 24"
364
+ >
365
+ <path
366
+ fill="currentColor"
367
+ d="M12 20q-3.35 0-5.675-2.325T4 12q0-3.35 2.325-5.675T12 4q1.725 0 3.3.713T18 6.75V4h2v7h-7V9h4.2q-.8-1.4-2.187-2.2T12 6Q9.5 6 7.75 7.75T6 12q0 2.5 1.75 4.25T12 18q1.925 0 3.475-1.1T17.65 14h2.1q-.7 2.65-2.85 4.325T12 20"
368
+ />
369
+ </svg>
370
+ `;
371
+
372
+ const sendIcon = `
373
+ <svg
374
+ xmlns="http://www.w3.org/2000/svg"
375
+ width="24"
376
+ height="24"
377
+ viewBox="0 0 24 24"
378
+ >
379
+ <path
380
+ fill="currentColor"
381
+ d="M11 20V7.825l-5.6 5.6L4 12l8-8l8 8l-1.4 1.425l-5.6-5.6V20z"
382
+ />
383
+ </svg>
384
+ `;
385
+
386
+ const sendPromptIcon = `
387
+ <svg
388
+ xmlns="http://www.w3.org/2000/svg"
389
+ width="24"
390
+ height="24"
391
+ viewBox="0 0 24 24"
392
+ >
393
+ <path
394
+ fill="currentColor"
395
+ d="M3 20v-6l8-2l-8-2V4l19 8z"
396
+ />
397
+ </svg>
398
+ `;
399
+
400
+ const shorterIcon = `
401
+ <svg
402
+ xmlns="http://www.w3.org/2000/svg"
403
+ width="24"
404
+ height="24"
405
+ viewBox="0 0 24 24"
406
+ >
407
+ <path
408
+ fill="currentColor"
409
+ d="M5 13v-2h14v2z"
410
+ />
411
+ </svg>
412
+ `;
413
+
414
+ const translateIcon = `
415
+ <svg
416
+ xmlns="http://www.w3.org/2000/svg"
417
+ width="24"
418
+ height="24"
419
+ viewBox="0 0 24 24"
420
+ >
421
+ <path
422
+ fill="currentColor"
423
+ d="m12.9 16l-2.55-2.5l.05-.05q1.45-1.6 2.262-3.117T13.95 7H16V5h-6V3H8v2H2v2h9.1q-.5 1.2-1.225 2.387T8 11.7q-.6-.6-1.187-1.412T5.85 8.6H3.85q.5 1.4 1.3 2.7T6.95 13.7L2.85 17.75L4.25 19.15L8 15.4L10.55 17.95zM18.5 22h-2L21 10h2l4.5 12h-2l-1.05-3h-4.9zm1.6-5h3.6l-1.8-5.1z"
424
+ />
425
+ </svg>
426
+ `;
427
+
428
+ var __typeError$3 = (msg) => {
429
+ throw TypeError(msg);
430
+ };
431
+ var __accessCheck$3 = (obj, member, msg) => member.has(obj) || __typeError$3("Cannot " + msg);
432
+ var __privateGet$3 = (obj, member, getter) => (__accessCheck$3(obj, member, "read from private field"), getter ? getter.call(obj) : member.get(obj));
433
+ var __privateAdd$3 = (obj, member, value) => member.has(obj) ? __typeError$3("Cannot add the same private member more than once") : member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
434
+ var __privateSet$3 = (obj, member, value, setter) => (__accessCheck$3(obj, member, "write to private field"), member.set(obj, value), value);
435
+ var __privateMethod = (obj, member, method) => (__accessCheck$3(obj, member, "access private method"), method);
436
+ var _panel, _host, _retryBtn, _config, _visible, _diffActive, _diffStartDoc, _ownedByAI, _DiffActionsPanelView_instances, findHost_fn, makeButton_fn, makeShortcutChip_fn, _retry, canRetry_fn, _rejectAll, _acceptAll;
437
+ const PANEL_CLASS = "milkdown-ai-diff-actions";
438
+ function setSanitizedIcon(host, svg) {
439
+ host.innerHTML = DOMPurify.sanitize(svg.trim());
440
+ }
441
+ function createIcon(svg) {
442
+ const span = document.createElement("span");
443
+ span.className = `${PANEL_CLASS}-icon`;
444
+ setSanitizedIcon(span, svg);
445
+ return span;
446
+ }
447
+ class DiffActionsPanelView {
448
+ constructor(ctx, view, config) {
449
+ this.ctx = ctx;
450
+ __privateAdd$3(this, _DiffActionsPanelView_instances);
451
+ __privateAdd$3(this, _panel);
452
+ __privateAdd$3(this, _host);
453
+ __privateAdd$3(this, _retryBtn);
454
+ __privateAdd$3(this, _config);
455
+ __privateAdd$3(this, _visible, false);
456
+ /// Tracks the diff plugin's `active` flag across transactions so we
457
+ /// can detect false→true / true→false edges independently of whether
458
+ /// the panel is actually being shown.
459
+ __privateAdd$3(this, _diffActive, false);
460
+ /// Doc snapshot at the moment diff review activated. If the live doc
461
+ /// drifts from this snapshot the user has accepted some per-change
462
+ /// diffs and the stored `lastFrom`/`lastTo` no longer point at the
463
+ /// original range — Retry is unsafe at that point.
464
+ __privateAdd$3(this, _diffStartDoc, null);
465
+ /// Whether the active diff review came from this AI session's
466
+ /// streaming hand-off (vs being started manually via
467
+ /// `startDiffReviewCmd`). Captured at the false→true transition.
468
+ /// The panel only renders when this is true so it doesn't take over
469
+ /// non-AI diff flows that exist independently of the AI feature.
470
+ __privateAdd$3(this, _ownedByAI, false);
471
+ __privateAdd$3(this, _retry, () => {
472
+ const session = this.ctx.get(aiSessionCtx.key);
473
+ if (!session.lastInstruction) return;
474
+ if (!__privateGet$3(this, _ownedByAI) || !__privateMethod(this, _DiffActionsPanelView_instances, canRetry_fn).call(this)) return;
475
+ const commands = this.ctx.get(commandsCtx);
476
+ commands.call(clearDiffReviewCmd.key);
477
+ const editorView = this.ctx.get(editorViewCtx);
478
+ const { doc } = editorView.state;
479
+ const from = Math.min(Math.max(session.lastFrom, 0), doc.content.size);
480
+ const to = Math.min(Math.max(session.lastTo, 0), doc.content.size);
481
+ editorView.dispatch(
482
+ editorView.state.tr.setSelection(
483
+ TextSelection.create(editorView.state.doc, from, to)
484
+ )
485
+ );
486
+ commands.call(runAICmd.key, {
487
+ instruction: session.lastInstruction,
488
+ label: session.lastLabel
489
+ });
490
+ });
491
+ __privateAdd$3(this, _rejectAll, () => {
492
+ this.ctx.get(commandsCtx).call(clearDiffReviewCmd.key);
493
+ });
494
+ __privateAdd$3(this, _acceptAll, () => {
495
+ this.ctx.get(commandsCtx).call(acceptAllDiffsCmd.key);
496
+ });
497
+ __privateSet$3(this, _config, config);
498
+ __privateSet$3(this, _host, __privateMethod(this, _DiffActionsPanelView_instances, findHost_fn).call(this, view));
499
+ const panel = document.createElement("div");
500
+ panel.className = PANEL_CLASS;
501
+ panel.dataset.show = "false";
502
+ __privateSet$3(this, _retryBtn, __privateMethod(this, _DiffActionsPanelView_instances, makeButton_fn).call(this, "retry", config.retryIcon, config.retryLabel, __privateGet$3(this, _retry)));
503
+ panel.appendChild(__privateGet$3(this, _retryBtn));
504
+ panel.appendChild(
505
+ __privateMethod(this, _DiffActionsPanelView_instances, makeButton_fn).call(this, "reject", config.rejectIcon, config.rejectAllLabel, __privateGet$3(this, _rejectAll))
506
+ );
507
+ const acceptBtn = __privateMethod(this, _DiffActionsPanelView_instances, makeButton_fn).call(this, "accept", config.acceptIcon, config.acceptAllLabel, __privateGet$3(this, _acceptAll));
508
+ acceptBtn.appendChild(__privateMethod(this, _DiffActionsPanelView_instances, makeShortcutChip_fn).call(this));
509
+ panel.appendChild(acceptBtn);
510
+ __privateSet$3(this, _panel, panel);
511
+ __privateGet$3(this, _host).appendChild(panel);
512
+ this.update(view);
513
+ }
514
+ update(view) {
515
+ var _a;
516
+ const diffActive = !!((_a = diffPluginKey.getState(view.state)) == null ? void 0 : _a.active);
517
+ if (diffActive !== __privateGet$3(this, _diffActive)) {
518
+ __privateSet$3(this, _diffActive, diffActive);
519
+ if (diffActive) {
520
+ const session = this.ctx.get(aiSessionCtx.key);
521
+ __privateSet$3(this, _ownedByAI, session.diffOwnedByAI);
522
+ __privateSet$3(this, _diffStartDoc, view.state.doc);
523
+ } else {
524
+ __privateSet$3(this, _ownedByAI, false);
525
+ __privateSet$3(this, _diffStartDoc, null);
526
+ const session = this.ctx.get(aiSessionCtx.key);
527
+ if (session.diffOwnedByAI) {
528
+ this.ctx.set(aiSessionCtx.key, {
529
+ ...session,
530
+ diffOwnedByAI: false
531
+ });
532
+ }
533
+ }
534
+ }
535
+ const shouldShow = diffActive && __privateGet$3(this, _ownedByAI);
536
+ if (shouldShow !== __privateGet$3(this, _visible)) {
537
+ __privateSet$3(this, _visible, shouldShow);
538
+ __privateGet$3(this, _panel).dataset.show = shouldShow ? "true" : "false";
539
+ }
540
+ if (shouldShow) {
541
+ const session = this.ctx.get(aiSessionCtx.key);
542
+ const docUntouched = !!__privateGet$3(this, _diffStartDoc) && view.state.doc.eq(__privateGet$3(this, _diffStartDoc));
543
+ __privateGet$3(this, _retryBtn).disabled = !session.lastInstruction || !docUntouched;
544
+ }
545
+ }
546
+ destroy() {
547
+ __privateGet$3(this, _panel).remove();
548
+ }
549
+ }
550
+ _panel = new WeakMap();
551
+ _host = new WeakMap();
552
+ _retryBtn = new WeakMap();
553
+ _config = new WeakMap();
554
+ _visible = new WeakMap();
555
+ _diffActive = new WeakMap();
556
+ _diffStartDoc = new WeakMap();
557
+ _ownedByAI = new WeakMap();
558
+ _DiffActionsPanelView_instances = new WeakSet();
559
+ findHost_fn = function(view) {
560
+ var _a;
561
+ return (_a = view.dom.closest(".milkdown")) != null ? _a : document.body;
562
+ };
563
+ makeButton_fn = function(variant, icon, label, onClick) {
564
+ const btn = document.createElement("button");
565
+ btn.type = "button";
566
+ btn.className = `${PANEL_CLASS}-btn ${PANEL_CLASS}-btn-${variant}`;
567
+ btn.appendChild(createIcon(icon));
568
+ const text = document.createElement("span");
569
+ text.textContent = label;
570
+ btn.appendChild(text);
571
+ btn.addEventListener("mousedown", (e) => e.preventDefault());
572
+ btn.addEventListener("click", (e) => {
573
+ e.preventDefault();
574
+ e.stopPropagation();
575
+ onClick();
576
+ });
577
+ return btn;
578
+ };
579
+ makeShortcutChip_fn = function() {
580
+ const shortcut = document.createElement("span");
581
+ shortcut.className = `${PANEL_CLASS}-shortcut`;
582
+ const cmd = document.createElement("span");
583
+ cmd.textContent = __privateGet$3(this, _config).modSymbol;
584
+ const enter = document.createElement("span");
585
+ enter.className = `${PANEL_CLASS}-shortcut-icon`;
586
+ setSanitizedIcon(enter, __privateGet$3(this, _config).enterKeyIcon);
587
+ shortcut.append(cmd, enter);
588
+ return shortcut;
589
+ };
590
+ _retry = new WeakMap();
591
+ canRetry_fn = function() {
592
+ if (!__privateGet$3(this, _diffStartDoc)) return false;
593
+ const editorView = this.ctx.get(editorViewCtx);
594
+ return editorView.state.doc.eq(__privateGet$3(this, _diffStartDoc));
595
+ };
596
+ _rejectAll = new WeakMap();
597
+ _acceptAll = new WeakMap();
598
+
599
+ const diffActionsPanelKey = new PluginKey("CREPE_AI_DIFF_ACTIONS_PANEL");
600
+ const DEFAULT_DIFF_ACTIONS_RETRY_LABEL = "Retry";
601
+ const DEFAULT_DIFF_ACTIONS_REJECT_ALL_LABEL = "Reject all";
602
+ const DEFAULT_DIFF_ACTIONS_ACCEPT_ALL_LABEL = "Accept all";
603
+ function detectModSymbol() {
604
+ var _a, _b, _c, _d;
605
+ if (typeof navigator === "undefined") return "\u2318";
606
+ const ua = navigator;
607
+ const platform = (_d = (_c = (_b = (_a = ua.userAgentData) == null ? void 0 : _a.platform) != null ? _b : ua.platform) != null ? _c : ua.userAgent) != null ? _d : "";
608
+ return /mac|iphone|ipad|ipod/i.test(platform) ? "\u2318" : "Ctrl";
609
+ }
610
+ const DEFAULT_DIFF_ACTIONS_MOD_SYMBOL = detectModSymbol();
611
+ function resolveDiffActionsConfig(options) {
612
+ var _a, _b, _c, _d, _e, _f, _g;
613
+ const { config, enterKeyIcon: enterKeyIcon$1 } = options;
614
+ return {
615
+ retryLabel: (_a = config == null ? void 0 : config.retryLabel) != null ? _a : DEFAULT_DIFF_ACTIONS_RETRY_LABEL,
616
+ rejectAllLabel: (_b = config == null ? void 0 : config.rejectAllLabel) != null ? _b : DEFAULT_DIFF_ACTIONS_REJECT_ALL_LABEL,
617
+ acceptAllLabel: (_c = config == null ? void 0 : config.acceptAllLabel) != null ? _c : DEFAULT_DIFF_ACTIONS_ACCEPT_ALL_LABEL,
618
+ retryIcon: (_d = config == null ? void 0 : config.retryIcon) != null ? _d : retryIcon,
619
+ rejectIcon: (_e = config == null ? void 0 : config.rejectIcon) != null ? _e : clearIcon,
620
+ acceptIcon: (_f = config == null ? void 0 : config.acceptIcon) != null ? _f : confirmIcon,
621
+ enterKeyIcon: enterKeyIcon$1 != null ? enterKeyIcon$1 : enterKeyIcon,
622
+ modSymbol: (_g = config == null ? void 0 : config.modSymbol) != null ? _g : DEFAULT_DIFF_ACTIONS_MOD_SYMBOL
623
+ };
624
+ }
625
+ function diffActionsPanelPlugin(options = {}) {
626
+ const resolved = resolveDiffActionsConfig(options);
627
+ return $prose((ctx) => {
628
+ return new Plugin({
629
+ key: diffActionsPanelKey,
630
+ view(view) {
631
+ return new DiffActionsPanelView(ctx, view, resolved);
632
+ },
633
+ props: {
634
+ handleKeyDown(view, event) {
635
+ var _a;
636
+ if (event.key !== "Enter") return false;
637
+ if (!(event.metaKey || event.ctrlKey)) return false;
638
+ if (!((_a = diffPluginKey.getState(view.state)) == null ? void 0 : _a.active)) return false;
639
+ if (!ctx.get(aiSessionCtx.key).diffOwnedByAI) return false;
640
+ event.preventDefault();
641
+ const commands = ctx.get(commandsCtx);
642
+ commands.call(acceptAllDiffsCmd.key);
643
+ return true;
644
+ }
645
+ }
646
+ });
647
+ });
648
+ }
649
+
650
+ var __typeError$2 = (msg) => {
651
+ throw TypeError(msg);
652
+ };
653
+ var __accessCheck$2 = (obj, member, msg) => member.has(obj) || __typeError$2("Cannot " + msg);
654
+ var __privateGet$2 = (obj, member, getter) => (__accessCheck$2(obj, member, "read from private field"), getter ? getter.call(obj) : member.get(obj));
655
+ var __privateAdd$2 = (obj, member, value) => member.has(obj) ? __typeError$2("Cannot add the same private member more than once") : member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
656
+ var __privateSet$2 = (obj, member, value, setter) => (__accessCheck$2(obj, member, "write to private field"), member.set(obj, value), value);
657
+ var _nodes, _removeById;
658
+ function createSubmenuBuilder(node) {
659
+ const builder = {
660
+ addItem: (id, item) => {
661
+ node.items.set(id, item);
662
+ return builder;
663
+ },
664
+ removeItem: (id) => {
665
+ node.items.delete(id);
666
+ return builder;
667
+ },
668
+ getItem: (id) => node.items.get(id),
669
+ clear: () => {
670
+ node.items.clear();
671
+ return builder;
672
+ }
673
+ };
674
+ return builder;
675
+ }
676
+ class AISuggestionsBuilder {
677
+ constructor() {
678
+ __privateAdd$2(this, _nodes, []);
679
+ this.addItem = (id, item) => {
680
+ __privateGet$2(this, _removeById).call(this, id);
681
+ __privateGet$2(this, _nodes).push({ kind: "item", id, item });
682
+ return this;
683
+ };
684
+ /// Add a submenu. Populate items via the optional `build` callback,
685
+ /// or call `getSubmenu(id)` afterward. Returns `this` so calls can be
686
+ /// chained at the parent level alongside `addItem`.
687
+ this.addSubmenu = (id, def, build) => {
688
+ __privateGet$2(this, _removeById).call(this, id);
689
+ const node = { def, items: /* @__PURE__ */ new Map() };
690
+ if (build) build(createSubmenuBuilder(node));
691
+ __privateGet$2(this, _nodes).push({ kind: "submenu", id, node });
692
+ return this;
693
+ };
694
+ this.removeItem = (id) => {
695
+ __privateGet$2(this, _removeById).call(this, id);
696
+ return this;
697
+ };
698
+ this.getItem = (id) => {
699
+ const node = __privateGet$2(this, _nodes).find((n) => n.kind === "item" && n.id === id);
700
+ return (node == null ? void 0 : node.kind) === "item" ? node.item : void 0;
701
+ };
702
+ /// Return a builder that mutates the submenu's items in place.
703
+ /// Multiple calls return distinct builder objects backed by the same
704
+ /// underlying node, so changes are always visible.
705
+ this.getSubmenu = (id) => {
706
+ const node = __privateGet$2(this, _nodes).find((n) => n.kind === "submenu" && n.id === id);
707
+ return (node == null ? void 0 : node.kind) === "submenu" ? createSubmenuBuilder(node.node) : void 0;
708
+ };
709
+ this.clear = () => {
710
+ __privateSet$2(this, _nodes, []);
711
+ return this;
712
+ };
713
+ this.build = () => {
714
+ const main = [];
715
+ const submenus = {};
716
+ for (const node of __privateGet$2(this, _nodes)) {
717
+ if (node.kind === "item") {
718
+ main.push({ kind: "item", id: node.id, item: node.item });
719
+ } else {
720
+ main.push({ kind: "submenu", id: node.id, def: node.node.def });
721
+ submenus[node.id] = {
722
+ def: node.node.def,
723
+ items: Array.from(node.node.items.entries()).map(([id, item]) => ({
724
+ id,
725
+ item
726
+ }))
727
+ };
728
+ }
729
+ }
730
+ return { main, submenus };
731
+ };
732
+ __privateAdd$2(this, _removeById, (id) => {
733
+ __privateSet$2(this, _nodes, __privateGet$2(this, _nodes).filter((n) => n.id !== id));
734
+ });
735
+ }
736
+ }
737
+ _nodes = new WeakMap();
738
+ _removeById = new WeakMap();
739
+ function applyDefaultSuggestions(builder) {
740
+ builder.addItem("improve", {
741
+ icon: aiIcon,
742
+ label: "Improve writing",
743
+ streamingLabel: "Improving writing",
744
+ prompt: "Improve the writing while preserving the original meaning."
745
+ }).addItem("grammar", {
746
+ icon: grammarCheckIcon,
747
+ label: "Fix grammar & spelling",
748
+ streamingLabel: "Fixing grammar & spelling",
749
+ prompt: "Fix any grammar and spelling errors without changing the meaning."
750
+ }).addItem("shorter", {
751
+ icon: shorterIcon,
752
+ label: "Make shorter",
753
+ streamingLabel: "Making shorter",
754
+ prompt: "Make this shorter while preserving the key information."
755
+ }).addItem("longer", {
756
+ icon: longerIcon,
757
+ label: "Make longer",
758
+ streamingLabel: "Expanding",
759
+ prompt: "Expand this with more detail and examples."
760
+ });
761
+ builder.addSubmenu(
762
+ "tone",
763
+ {
764
+ icon: editIcon,
765
+ label: "Change tone\u2026",
766
+ title: "Change tone",
767
+ searchPlaceholder: "Search tones\u2026"
768
+ },
769
+ (sub) => {
770
+ const tones = [
771
+ ["professional", "Professional"],
772
+ ["casual", "Casual"],
773
+ ["confident", "Confident"],
774
+ ["friendly", "Friendly"],
775
+ ["direct", "Direct"],
776
+ ["formal", "Formal"]
777
+ ];
778
+ for (const [id, label] of tones) {
779
+ sub.addItem(id, {
780
+ icon: editIcon,
781
+ label,
782
+ streamingLabel: "Adjusting tone",
783
+ prompt: `Rewrite this in a ${label.toLowerCase()} tone.`
784
+ });
785
+ }
786
+ }
787
+ );
788
+ builder.addSubmenu(
789
+ "translate",
790
+ {
791
+ icon: translateIcon,
792
+ label: "Translate\u2026",
793
+ title: "Translate",
794
+ searchPlaceholder: "Search languages\u2026"
795
+ },
796
+ (sub) => {
797
+ const languages = [
798
+ ["english", "English", "English"],
799
+ ["chinese", "Chinese", "Chinese (Simplified)"],
800
+ ["japanese", "Japanese", "Japanese"],
801
+ ["korean", "Korean", "Korean"],
802
+ ["spanish", "Spanish", "Spanish"],
803
+ ["french", "French", "French"],
804
+ ["german", "German", "German"]
805
+ ];
806
+ for (const [id, label, promptName] of languages) {
807
+ sub.addItem(id, {
808
+ icon: translateIcon,
809
+ label,
810
+ streamingLabel: `Translating to ${label}`,
811
+ prompt: `Translate this to ${promptName}.`
812
+ });
813
+ }
814
+ }
815
+ );
816
+ }
817
+
818
+ function keepAlive(..._args) {
819
+ }
820
+
821
+ keepAlive(h);
822
+ function renderHighlighted(label, query) {
823
+ const q = query.trim();
824
+ if (!q) return [label];
825
+ const lower = label.toLowerCase();
826
+ const lq = q.toLowerCase();
827
+ const idx = lower.indexOf(lq);
828
+ if (idx === -1) return [label];
829
+ return [
830
+ label.slice(0, idx),
831
+ h("mark", null, label.slice(idx, idx + q.length)),
832
+ label.slice(idx + q.length)
833
+ ];
834
+ }
835
+ const AIInstructionInput = defineComponent({
836
+ props: {
837
+ placeholder: { type: Object, required: true },
838
+ resetSignal: { type: Object, required: true },
839
+ suggestions: { type: Object, required: true },
840
+ chrome: { type: Object, required: true },
841
+ onConfirm: { type: Function, required: true },
842
+ onCancel: { type: Function, required: true }
843
+ },
844
+ setup({
845
+ placeholder,
846
+ resetSignal,
847
+ suggestions,
848
+ chrome,
849
+ onConfirm,
850
+ onCancel
851
+ }) {
852
+ const inputValue = ref("");
853
+ const view = ref({ kind: "main" });
854
+ const selectedIndex = ref(0);
855
+ const inputRef = ref(null);
856
+ const listRef = ref(null);
857
+ const listboxId = `ai-instruction-list-${Math.random().toString(36).slice(2, 9)}`;
858
+ const optionId = (idx) => `${listboxId}-opt-${idx}`;
859
+ watch(resetSignal, () => {
860
+ inputValue.value = "";
861
+ view.value = { kind: "main" };
862
+ selectedIndex.value = 0;
863
+ });
864
+ const allItems = computed(() => {
865
+ if (view.value.kind === "submenu") {
866
+ const submenu = suggestions.submenus[view.value.id];
867
+ if (!submenu) return [];
868
+ return submenu.items.map(({ id, item }) => ({
869
+ id,
870
+ icon: item.icon,
871
+ label: item.label,
872
+ hasSubmenu: false,
873
+ prompt: { text: item.prompt, streamingLabel: item.streamingLabel }
874
+ }));
875
+ }
876
+ return suggestions.main.map((entry) => {
877
+ if (entry.kind === "item") {
878
+ return {
879
+ id: entry.id,
880
+ icon: entry.item.icon,
881
+ label: entry.item.label,
882
+ hasSubmenu: false,
883
+ prompt: {
884
+ text: entry.item.prompt,
885
+ streamingLabel: entry.item.streamingLabel
886
+ }
887
+ };
888
+ }
889
+ return {
890
+ id: entry.id,
891
+ icon: entry.def.icon,
892
+ label: entry.def.label,
893
+ hasSubmenu: true
894
+ };
895
+ });
896
+ });
897
+ const currentSubmenuDef = computed(() => {
898
+ var _a, _b;
899
+ if (view.value.kind !== "submenu") return null;
900
+ return (_b = (_a = suggestions.submenus[view.value.id]) == null ? void 0 : _a.def) != null ? _b : null;
901
+ });
902
+ const filteredItems = computed(() => {
903
+ const q = inputValue.value.trim().toLowerCase();
904
+ if (!q) return allItems.value;
905
+ return allItems.value.filter(
906
+ (item) => item.label.toLowerCase().includes(q)
907
+ );
908
+ });
909
+ const showSendAsPrompt = computed(() => inputValue.value.trim().length > 0);
910
+ const totalItems = computed(
911
+ () => filteredItems.value.length + (showSendAsPrompt.value ? 1 : 0)
912
+ );
913
+ watch([filteredItems, view, showSendAsPrompt], () => {
914
+ selectedIndex.value = showSendAsPrompt.value ? filteredItems.value.length : 0;
915
+ });
916
+ const focusInput = () => {
917
+ void nextTick(() => {
918
+ var _a;
919
+ return (_a = inputRef.value) == null ? void 0 : _a.focus();
920
+ });
921
+ };
922
+ const enterSubmenu = (id) => {
923
+ view.value = { kind: "submenu", id };
924
+ inputValue.value = "";
925
+ selectedIndex.value = 0;
926
+ focusInput();
927
+ };
928
+ const exitSubmenu = () => {
929
+ view.value = { kind: "main" };
930
+ inputValue.value = "";
931
+ selectedIndex.value = 0;
932
+ focusInput();
933
+ };
934
+ const runItem = (item) => {
935
+ if (item.hasSubmenu) {
936
+ enterSubmenu(item.id);
937
+ } else if (item.prompt) {
938
+ onConfirm(item.prompt.text, item.prompt.streamingLabel);
939
+ inputValue.value = "";
940
+ }
941
+ };
942
+ const submitRaw = () => {
943
+ const v = inputValue.value.trim();
944
+ if (!v) return;
945
+ onConfirm(v);
946
+ inputValue.value = "";
947
+ };
948
+ const onSelectCurrent = () => {
949
+ const idx = selectedIndex.value;
950
+ const items = filteredItems.value;
951
+ if (idx < items.length) {
952
+ runItem(items[idx]);
953
+ } else if (showSendAsPrompt.value) {
954
+ submitRaw();
955
+ }
956
+ };
957
+ const scrollToSelected = () => {
958
+ void nextTick(() => {
959
+ const list = listRef.value;
960
+ if (!list) return;
961
+ const el = list.querySelector(
962
+ `[data-index="${selectedIndex.value}"]`
963
+ );
964
+ el == null ? void 0 : el.scrollIntoView({ block: "nearest" });
965
+ });
966
+ };
967
+ const onKeydown = (e) => {
968
+ e.stopPropagation();
969
+ if (e.key === "ArrowDown") {
970
+ e.preventDefault();
971
+ if (totalItems.value === 0) return;
972
+ selectedIndex.value = (selectedIndex.value + 1) % totalItems.value;
973
+ scrollToSelected();
974
+ return;
975
+ }
976
+ if (e.key === "ArrowUp") {
977
+ e.preventDefault();
978
+ if (totalItems.value === 0) return;
979
+ selectedIndex.value = (selectedIndex.value - 1 + totalItems.value) % totalItems.value;
980
+ scrollToSelected();
981
+ return;
982
+ }
983
+ if (e.key === "Enter") {
984
+ e.preventDefault();
985
+ onSelectCurrent();
986
+ return;
987
+ }
988
+ if (e.key === "Escape") {
989
+ e.preventDefault();
990
+ if (view.value.kind === "submenu") exitSubmenu();
991
+ else onCancel();
992
+ return;
993
+ }
994
+ if (e.key === "Backspace" && inputValue.value === "" && view.value.kind === "submenu") {
995
+ e.preventDefault();
996
+ exitSubmenu();
997
+ }
998
+ };
999
+ const onItemPointerDown = (e) => {
1000
+ e.preventDefault();
1001
+ };
1002
+ return () => {
1003
+ const items = filteredItems.value;
1004
+ const showPrompt = showSendAsPrompt.value;
1005
+ const submenuDef = currentSubmenuDef.value;
1006
+ return /* @__PURE__ */ h("div", { class: "ai-instruction" }, /* @__PURE__ */ h("div", { class: "ai-instruction-input" }, /* @__PURE__ */ h("span", { class: "ai-instruction-input-prefix" }, /* @__PURE__ */ h(Icon, { icon: chrome.aiIcon })), /* @__PURE__ */ h(
1007
+ "input",
1008
+ {
1009
+ ref: inputRef,
1010
+ class: "ai-instruction-input-field",
1011
+ role: "combobox",
1012
+ "aria-expanded": "true",
1013
+ "aria-autocomplete": "list",
1014
+ "aria-controls": listboxId,
1015
+ "aria-activedescendant": totalItems.value > 0 ? optionId(selectedIndex.value) : void 0,
1016
+ placeholder: submenuDef ? submenuDef.searchPlaceholder : placeholder.value,
1017
+ value: inputValue.value,
1018
+ onInput: (e) => {
1019
+ inputValue.value = e.target.value;
1020
+ },
1021
+ onKeydown
1022
+ }
1023
+ ), /* @__PURE__ */ h(
1024
+ "button",
1025
+ {
1026
+ type: "button",
1027
+ class: "ai-instruction-submit",
1028
+ "aria-label": chrome.submitButtonLabel,
1029
+ disabled: !showPrompt,
1030
+ onMousedown: onItemPointerDown,
1031
+ onClick: submitRaw
1032
+ },
1033
+ /* @__PURE__ */ h(Icon, { icon: chrome.sendIcon })
1034
+ )), /* @__PURE__ */ h(
1035
+ "div",
1036
+ {
1037
+ class: "ai-instruction-list",
1038
+ ref: listRef,
1039
+ id: listboxId,
1040
+ role: "listbox",
1041
+ "aria-label": chrome.listboxLabel
1042
+ },
1043
+ submenuDef && /* @__PURE__ */ h(
1044
+ "button",
1045
+ {
1046
+ type: "button",
1047
+ class: "ai-instruction-back",
1048
+ onMousedown: onItemPointerDown,
1049
+ onClick: exitSubmenu
1050
+ },
1051
+ /* @__PURE__ */ h("span", { class: "ai-instruction-back-icon", "aria-hidden": "true" }, /* @__PURE__ */ h(Icon, { icon: chrome.chevronLeftIcon })),
1052
+ /* @__PURE__ */ h("span", null, submenuDef.title)
1053
+ ),
1054
+ items.length > 0 && /* @__PURE__ */ h("div", { class: "ai-instruction-section" }, /* @__PURE__ */ h("div", { class: "ai-instruction-section-header" }, chrome.suggestionsHeaderLabel), items.map((item, idx) => /* @__PURE__ */ h(
1055
+ "div",
1056
+ {
1057
+ key: item.id,
1058
+ id: optionId(idx),
1059
+ "data-index": idx,
1060
+ role: "option",
1061
+ "aria-selected": idx === selectedIndex.value,
1062
+ class: [
1063
+ "ai-instruction-item",
1064
+ idx === selectedIndex.value ? "active" : ""
1065
+ ],
1066
+ onMousedown: onItemPointerDown,
1067
+ onClick: () => runItem(item),
1068
+ onPointerenter: () => {
1069
+ selectedIndex.value = idx;
1070
+ }
1071
+ },
1072
+ /* @__PURE__ */ h("span", { class: "ai-instruction-item-icon" }, /* @__PURE__ */ h(Icon, { icon: item.icon })),
1073
+ /* @__PURE__ */ h("span", { class: "ai-instruction-item-label" }, renderHighlighted(item.label, inputValue.value)),
1074
+ item.hasSubmenu && /* @__PURE__ */ h("span", { class: "ai-instruction-item-arrow" }, /* @__PURE__ */ h(Icon, { icon: chrome.chevronRightIcon }))
1075
+ ))),
1076
+ showPrompt && /* @__PURE__ */ h("div", { class: "ai-instruction-section" }, /* @__PURE__ */ h("div", { class: "ai-instruction-section-header" }, chrome.sendAsPromptHeaderLabel), /* @__PURE__ */ h(
1077
+ "div",
1078
+ {
1079
+ id: optionId(items.length),
1080
+ "data-index": items.length,
1081
+ role: "option",
1082
+ "aria-selected": selectedIndex.value === items.length,
1083
+ class: [
1084
+ "ai-instruction-item",
1085
+ "ai-instruction-item-prompt",
1086
+ selectedIndex.value === items.length ? "active" : ""
1087
+ ],
1088
+ onMousedown: onItemPointerDown,
1089
+ onClick: submitRaw,
1090
+ onPointerenter: () => {
1091
+ selectedIndex.value = items.length;
1092
+ }
1093
+ },
1094
+ /* @__PURE__ */ h("span", { class: "ai-instruction-item-icon" }, /* @__PURE__ */ h(Icon, { icon: chrome.sendPromptIcon })),
1095
+ /* @__PURE__ */ h("span", { class: "ai-instruction-item-label" }, chrome.sendAsPromptLabel, " ", /* @__PURE__ */ h("span", { class: "ai-instruction-item-quote" }, '"', inputValue.value, '"')),
1096
+ /* @__PURE__ */ h("span", { class: "ai-instruction-item-shortcut" }, /* @__PURE__ */ h(Icon, { icon: chrome.enterKeyIcon }))
1097
+ ))
1098
+ ));
1099
+ };
1100
+ }
1101
+ });
1102
+
1103
+ var __typeError$1 = (msg) => {
1104
+ throw TypeError(msg);
1105
+ };
1106
+ var __accessCheck$1 = (obj, member, msg) => member.has(obj) || __typeError$1("Cannot " + msg);
1107
+ var __privateGet$1 = (obj, member, getter) => (__accessCheck$1(obj, member, "read from private field"), getter ? getter.call(obj) : member.get(obj));
1108
+ var __privateAdd$1 = (obj, member, value) => member.has(obj) ? __typeError$1("Cannot add the same private member more than once") : member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
1109
+ var __privateSet$1 = (obj, member, value, setter) => (__accessCheck$1(obj, member, "write to private field"), member.set(obj, value), value);
1110
+ var _content, _provider, _app, _placeholder, _resetSignal, _from, _to, _wantsShow, _onConfirm, _onCancel;
1111
+ class AIInstructionTooltipView {
1112
+ constructor(ctx, view, config) {
1113
+ this.ctx = ctx;
1114
+ __privateAdd$1(this, _content);
1115
+ __privateAdd$1(this, _provider);
1116
+ __privateAdd$1(this, _app);
1117
+ __privateAdd$1(this, _placeholder);
1118
+ __privateAdd$1(this, _resetSignal);
1119
+ __privateAdd$1(this, _from, -1);
1120
+ __privateAdd$1(this, _to, -1);
1121
+ /// Source of truth for "should the palette currently be showing".
1122
+ /// `TooltipProvider.shouldShow` reads this so that forwarding `update()`
1123
+ /// to the provider on every editor transition (needed to keep the
1124
+ /// floating position in sync with layout changes) doesn't dismiss the
1125
+ /// palette behind our back.
1126
+ __privateAdd$1(this, _wantsShow, false);
1127
+ __privateAdd$1(this, _onConfirm, (instruction, label) => {
1128
+ if (!instruction.trim()) return;
1129
+ const commands = this.ctx.get(commandsCtx);
1130
+ const accepted = commands.call(runAICmd.key, { instruction, label });
1131
+ if (!accepted) return;
1132
+ __privateSet$1(this, _wantsShow, false);
1133
+ __privateGet$1(this, _provider).hide();
1134
+ });
1135
+ __privateAdd$1(this, _onCancel, () => {
1136
+ __privateSet$1(this, _wantsShow, false);
1137
+ __privateGet$1(this, _provider).hide();
1138
+ });
1139
+ this.show = (from, to) => {
1140
+ __privateSet$1(this, _from, from);
1141
+ __privateSet$1(this, _to, to);
1142
+ __privateGet$1(this, _resetSignal).value++;
1143
+ __privateSet$1(this, _wantsShow, true);
1144
+ const view = this.ctx.get(editorViewCtx);
1145
+ __privateGet$1(this, _provider).show(
1146
+ { getBoundingClientRect: () => posToDOMRect(view, from, to) },
1147
+ view
1148
+ );
1149
+ requestAnimationFrame(() => {
1150
+ var _a;
1151
+ (_a = __privateGet$1(this, _content).querySelector("input")) == null ? void 0 : _a.focus();
1152
+ });
1153
+ };
1154
+ this.update = (view, prevState) => {
1155
+ const { selection } = view.state;
1156
+ const isTextSelection = selection instanceof TextSelection;
1157
+ const movedRange = selection.from !== __privateGet$1(this, _from) || selection.to !== __privateGet$1(this, _to);
1158
+ if (!isTextSelection || movedRange) {
1159
+ __privateSet$1(this, _wantsShow, false);
1160
+ __privateGet$1(this, _provider).hide();
1161
+ return;
1162
+ }
1163
+ __privateGet$1(this, _provider).update(view, prevState);
1164
+ };
1165
+ this.destroy = () => {
1166
+ __privateGet$1(this, _app).unmount();
1167
+ __privateGet$1(this, _provider).destroy();
1168
+ __privateGet$1(this, _content).remove();
1169
+ };
1170
+ __privateSet$1(this, _placeholder, ref(config.placeholder));
1171
+ __privateSet$1(this, _resetSignal, ref(0));
1172
+ const content = document.createElement("div");
1173
+ content.className = "milkdown-ai-instruction";
1174
+ const app = createApp(AIInstructionInput, {
1175
+ placeholder: __privateGet$1(this, _placeholder),
1176
+ resetSignal: __privateGet$1(this, _resetSignal),
1177
+ suggestions: config.suggestions,
1178
+ chrome: config.chrome,
1179
+ onConfirm: __privateGet$1(this, _onConfirm),
1180
+ onCancel: __privateGet$1(this, _onCancel)
1181
+ });
1182
+ app.mount(content);
1183
+ __privateSet$1(this, _app, app);
1184
+ __privateSet$1(this, _content, content);
1185
+ __privateSet$1(this, _provider, new TooltipProvider({
1186
+ content,
1187
+ debounce: 0,
1188
+ offset: 10,
1189
+ shouldShow: () => __privateGet$1(this, _wantsShow),
1190
+ floatingUIOptions: {
1191
+ placement: "bottom"
1192
+ }
1193
+ }));
1194
+ __privateGet$1(this, _provider).onHide = () => {
1195
+ __privateSet$1(this, _wantsShow, false);
1196
+ requestAnimationFrame(() => {
1197
+ try {
1198
+ const root = __privateGet$1(this, _content).getRootNode();
1199
+ const active = root.activeElement;
1200
+ if (!active || !__privateGet$1(this, _content).contains(active)) return;
1201
+ const v = this.ctx.get(editorViewCtx);
1202
+ v.dom.focus({ preventScroll: true });
1203
+ } catch (e) {
1204
+ }
1205
+ });
1206
+ };
1207
+ __privateGet$1(this, _provider).update(view);
1208
+ }
1209
+ }
1210
+ _content = new WeakMap();
1211
+ _provider = new WeakMap();
1212
+ _app = new WeakMap();
1213
+ _placeholder = new WeakMap();
1214
+ _resetSignal = new WeakMap();
1215
+ _from = new WeakMap();
1216
+ _to = new WeakMap();
1217
+ _wantsShow = new WeakMap();
1218
+ _onConfirm = new WeakMap();
1219
+ _onCancel = new WeakMap();
1220
+
1221
+ const defaultAPI = {
1222
+ show: () => {
1223
+ }
1224
+ };
1225
+ const aiInstructionTooltipAPI = $ctx(
1226
+ { ...defaultAPI },
1227
+ "aiInstructionTooltipAPI"
1228
+ );
1229
+ const aiInstructionTooltip = tooltipFactory("CREPE_AI_INSTRUCTION");
1230
+ const DEFAULT_SUGGESTIONS_HEADER_LABEL = "SUGGESTIONS";
1231
+ const DEFAULT_SEND_AS_PROMPT_HEADER_LABEL = "SEND AS PROMPT";
1232
+ const DEFAULT_SEND_AS_PROMPT_LABEL = "Ask AI:";
1233
+ const DEFAULT_SUBMIT_BUTTON_LABEL = "Send prompt";
1234
+ const DEFAULT_LISTBOX_LABEL = "AI suggestions";
1235
+ const DEFAULT_INSTRUCTION_PLACEHOLDER = "Tell AI what to do with the selection\u2026";
1236
+ function resolveChrome(config) {
1237
+ var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k;
1238
+ return {
1239
+ aiIcon: (_a = config == null ? void 0 : config.aiIcon) != null ? _a : aiIcon,
1240
+ sendIcon: (_b = config == null ? void 0 : config.sendIcon) != null ? _b : sendIcon,
1241
+ sendPromptIcon: (_c = config == null ? void 0 : config.sendPromptIcon) != null ? _c : sendPromptIcon,
1242
+ enterKeyIcon: (_d = config == null ? void 0 : config.enterKeyIcon) != null ? _d : enterKeyIcon,
1243
+ chevronLeftIcon: (_e = config == null ? void 0 : config.chevronLeftIcon) != null ? _e : chevronLeftIcon,
1244
+ chevronRightIcon: (_f = config == null ? void 0 : config.chevronRightIcon) != null ? _f : chevronRightIcon,
1245
+ suggestionsHeaderLabel: (_g = config == null ? void 0 : config.suggestionsHeaderLabel) != null ? _g : DEFAULT_SUGGESTIONS_HEADER_LABEL,
1246
+ sendAsPromptHeaderLabel: (_h = config == null ? void 0 : config.sendAsPromptHeaderLabel) != null ? _h : DEFAULT_SEND_AS_PROMPT_HEADER_LABEL,
1247
+ sendAsPromptLabel: (_i = config == null ? void 0 : config.sendAsPromptLabel) != null ? _i : DEFAULT_SEND_AS_PROMPT_LABEL,
1248
+ submitButtonLabel: (_j = config == null ? void 0 : config.submitButtonLabel) != null ? _j : DEFAULT_SUBMIT_BUTTON_LABEL,
1249
+ listboxLabel: (_k = config == null ? void 0 : config.listboxLabel) != null ? _k : DEFAULT_LISTBOX_LABEL
1250
+ };
1251
+ }
1252
+ function resolveViewConfig(config) {
1253
+ var _a, _b;
1254
+ const builder = new AISuggestionsBuilder();
1255
+ applyDefaultSuggestions(builder);
1256
+ (_a = config == null ? void 0 : config.buildAISuggestions) == null ? void 0 : _a.call(config, builder);
1257
+ return {
1258
+ placeholder: (_b = config == null ? void 0 : config.instructionPlaceholder) != null ? _b : DEFAULT_INSTRUCTION_PLACEHOLDER,
1259
+ chrome: resolveChrome(config),
1260
+ suggestions: builder.build()
1261
+ };
1262
+ }
1263
+ function configureAIInstructionTooltip(config) {
1264
+ return (ctx) => {
1265
+ const viewConfig = resolveViewConfig(config);
1266
+ let tooltipView = null;
1267
+ ctx.update(aiInstructionTooltipAPI.key, (api) => ({
1268
+ ...api,
1269
+ show: (from, to) => {
1270
+ tooltipView == null ? void 0 : tooltipView.show(from, to);
1271
+ }
1272
+ }));
1273
+ ctx.set(aiInstructionTooltip.key, {
1274
+ view: (view) => {
1275
+ tooltipView = new AIInstructionTooltipView(ctx, view, viewConfig);
1276
+ return tooltipView;
1277
+ }
1278
+ });
1279
+ };
1280
+ }
1281
+
1282
+ var __typeError = (msg) => {
1283
+ throw TypeError(msg);
1284
+ };
1285
+ var __accessCheck = (obj, member, msg) => member.has(obj) || __typeError("Cannot " + msg);
1286
+ var __privateGet = (obj, member, getter) => (__accessCheck(obj, member, "read from private field"), getter ? getter.call(obj) : member.get(obj));
1287
+ var __privateAdd = (obj, member, value) => member.has(obj) ? __typeError("Cannot add the same private member more than once") : member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
1288
+ var __privateSet = (obj, member, value, setter) => (__accessCheck(obj, member, "write to private field"), member.set(obj, value), value);
1289
+ var _spinner, _label, _fallbackLabel, _start, _lastLabelText, _rafId, _tick;
1290
+ const CLASS_PREFIX = "milkdown-ai-streaming";
1291
+ const SPINNER_PERIOD_MS = 800;
1292
+ const DEFAULT_STREAMING_FALLBACK_LABEL = "Generating";
1293
+ const DEFAULT_STREAMING_CANCEL_HINT = "Esc to cancel";
1294
+ const indicatorKey = new PluginKey(
1295
+ "CREPE_AI_STREAMING_INDICATOR"
1296
+ );
1297
+ class IndicatorWidget {
1298
+ constructor(ctx, fallbackLabel, cancelHint) {
1299
+ __privateAdd(this, _spinner);
1300
+ __privateAdd(this, _label);
1301
+ __privateAdd(this, _fallbackLabel);
1302
+ __privateAdd(this, _start, performance.now());
1303
+ __privateAdd(this, _lastLabelText, "");
1304
+ __privateAdd(this, _rafId, 0);
1305
+ __privateAdd(this, _tick, () => {
1306
+ const elapsed = performance.now() - __privateGet(this, _start);
1307
+ const angle = elapsed / SPINNER_PERIOD_MS * 360;
1308
+ __privateGet(this, _spinner).style.transform = `rotate(${angle}deg)`;
1309
+ __privateSet(this, _rafId, requestAnimationFrame(__privateGet(this, _tick)));
1310
+ });
1311
+ __privateSet(this, _fallbackLabel, fallbackLabel);
1312
+ const dom = document.createElement("span");
1313
+ dom.className = `${CLASS_PREFIX}-indicator`;
1314
+ dom.contentEditable = "false";
1315
+ dom.setAttribute("role", "status");
1316
+ dom.setAttribute("aria-live", "polite");
1317
+ const spinner = document.createElement("span");
1318
+ spinner.className = `${CLASS_PREFIX}-spinner`;
1319
+ spinner.setAttribute("aria-hidden", "true");
1320
+ dom.appendChild(spinner);
1321
+ const label = document.createElement("span");
1322
+ label.className = `${CLASS_PREFIX}-label`;
1323
+ dom.appendChild(label);
1324
+ const escHint = document.createElement("span");
1325
+ escHint.className = `${CLASS_PREFIX}-esc`;
1326
+ escHint.textContent = cancelHint;
1327
+ dom.appendChild(escHint);
1328
+ this.dom = dom;
1329
+ __privateSet(this, _spinner, spinner);
1330
+ __privateSet(this, _label, label);
1331
+ this.setLabel(ctx);
1332
+ __privateGet(this, _tick).call(this);
1333
+ }
1334
+ setLabel(ctx) {
1335
+ const session = ctx.get(aiSessionCtx.key);
1336
+ const text = `${session.label || __privateGet(this, _fallbackLabel)}\u2026`;
1337
+ if (text === __privateGet(this, _lastLabelText)) return;
1338
+ __privateSet(this, _lastLabelText, text);
1339
+ __privateGet(this, _label).textContent = text;
1340
+ }
1341
+ destroy() {
1342
+ if (__privateGet(this, _rafId)) cancelAnimationFrame(__privateGet(this, _rafId));
1343
+ __privateSet(this, _rafId, 0);
1344
+ }
1345
+ }
1346
+ _spinner = new WeakMap();
1347
+ _label = new WeakMap();
1348
+ _fallbackLabel = new WeakMap();
1349
+ _start = new WeakMap();
1350
+ _lastLabelText = new WeakMap();
1351
+ _rafId = new WeakMap();
1352
+ _tick = new WeakMap();
1353
+ function streamingIndicatorPlugin(options = {}) {
1354
+ var _a, _b;
1355
+ const { config } = options;
1356
+ const fallbackLabel = (_a = config == null ? void 0 : config.fallbackLabel) != null ? _a : DEFAULT_STREAMING_FALLBACK_LABEL;
1357
+ const cancelHint = (_b = config == null ? void 0 : config.cancelHint) != null ? _b : DEFAULT_STREAMING_CANCEL_HINT;
1358
+ return $prose((ctx) => {
1359
+ let widget = null;
1360
+ function ensureWidget() {
1361
+ if (!widget) widget = new IndicatorWidget(ctx, fallbackLabel, cancelHint);
1362
+ else widget.setLabel(ctx);
1363
+ return widget;
1364
+ }
1365
+ function dropWidget() {
1366
+ if (widget) {
1367
+ widget.destroy();
1368
+ widget = null;
1369
+ }
1370
+ }
1371
+ function buildSet(doc, insertEndPos) {
1372
+ const pos = Math.min(insertEndPos, doc.content.size);
1373
+ const decoration = Decoration.widget(pos, ensureWidget().dom, {
1374
+ side: 1,
1375
+ key: "ai-streaming-indicator"
1376
+ });
1377
+ return DecorationSet.create(doc, [decoration]);
1378
+ }
1379
+ return new Plugin({
1380
+ key: indicatorKey,
1381
+ state: {
1382
+ init: () => DecorationSet.empty,
1383
+ apply(tr, decorations, _oldState, newState) {
1384
+ const streaming = streamingPluginKey.getState(newState);
1385
+ if (!(streaming == null ? void 0 : streaming.active) || streaming.insertEndPos == null) {
1386
+ dropWidget();
1387
+ return DecorationSet.empty;
1388
+ }
1389
+ if (tr.getMeta(streamingPluginKey) || tr.docChanged) {
1390
+ return buildSet(newState.doc, streaming.insertEndPos);
1391
+ }
1392
+ return decorations.map(tr.mapping, tr.doc);
1393
+ }
1394
+ },
1395
+ view() {
1396
+ return {
1397
+ destroy() {
1398
+ dropWidget();
1399
+ }
1400
+ };
1401
+ },
1402
+ props: {
1403
+ decorations(state) {
1404
+ var _a2;
1405
+ return (_a2 = indicatorKey.getState(state)) != null ? _a2 : DecorationSet.empty;
1406
+ },
1407
+ handleKeyDown(view, event) {
1408
+ var _a2;
1409
+ if (event.key !== "Escape") return false;
1410
+ const commands = ctx.get(commandsCtx);
1411
+ if (ctx.get(aiSessionCtx.key).abortController) {
1412
+ event.preventDefault();
1413
+ commands.call(abortAICmd.key, { keep: true });
1414
+ return true;
1415
+ }
1416
+ if ((_a2 = streamingPluginKey.getState(view.state)) == null ? void 0 : _a2.active) {
1417
+ event.preventDefault();
1418
+ commands.call(abortStreamingCmd.key, { keep: true });
1419
+ return true;
1420
+ }
1421
+ return false;
1422
+ }
1423
+ }
1424
+ });
1425
+ });
1426
+ }
1427
+
1428
+ const CREPE_CUSTOM_BLOCK_TYPES = ["table", "image-block", "code_block"];
1429
+ const CREPE_IGNORE_ATTRS = { heading: ["id"] };
1430
+ const ai = (editor, config) => {
1431
+ var _a, _b;
1432
+ const diffCfg = (_a = config == null ? void 0 : config.diff) != null ? _a : {};
1433
+ const streamingCfg = (_b = config == null ? void 0 : config.streaming) != null ? _b : {};
1434
+ editor.config(crepeFeatureConfig(CrepeFeature.AI)).config((ctx) => {
1435
+ ctx.update(diffConfig.key, (prev) => {
1436
+ var _a2;
1437
+ return {
1438
+ ...prev,
1439
+ ignoreAttrs: (_a2 = diffCfg.ignoreAttrs) != null ? _a2 : CREPE_IGNORE_ATTRS
1440
+ };
1441
+ });
1442
+ const { ignoreAttrs: _, ...componentConfig } = diffCfg;
1443
+ ctx.update(diffComponentConfig.key, (prev) => {
1444
+ var _a2;
1445
+ return {
1446
+ ...prev,
1447
+ customBlockTypes: (_a2 = componentConfig.customBlockTypes) != null ? _a2 : CREPE_CUSTOM_BLOCK_TYPES,
1448
+ ...componentConfig
1449
+ };
1450
+ });
1451
+ }).use(diff).use(diffComponent).config((ctx) => {
1452
+ ctx.update(streamingConfig.key, (prev) => {
1453
+ var _a2;
1454
+ return {
1455
+ ...prev,
1456
+ ...streamingCfg,
1457
+ ignoreAttrs: (_a2 = streamingCfg.ignoreAttrs) != null ? _a2 : CREPE_IGNORE_ATTRS,
1458
+ // Wire diffReviewOnEnd into the streaming plugin so manual
1459
+ // endStreamingCmd calls (outside runAICmd) also respect it.
1460
+ // Only override if the user explicitly set it — otherwise
1461
+ // keep the streaming plugin's own default so tests and
1462
+ // manual-streaming use cases aren't surprised.
1463
+ ...(config == null ? void 0 : config.diffReviewOnEnd) !== void 0 ? { diffReviewOnEnd: config.diffReviewOnEnd } : {}
1464
+ };
1465
+ });
1466
+ }).use(streaming).config((ctx) => {
1467
+ ctx.update(aiProviderConfig.key, (prev) => {
1468
+ var _a2;
1469
+ return {
1470
+ ...prev,
1471
+ ...(config == null ? void 0 : config.provider) !== void 0 ? { provider: config.provider } : {},
1472
+ ...(config == null ? void 0 : config.buildContext) !== void 0 ? { buildContext: config.buildContext } : {},
1473
+ diffReviewOnEnd: (_a2 = config == null ? void 0 : config.diffReviewOnEnd) != null ? _a2 : prev.diffReviewOnEnd,
1474
+ ...(config == null ? void 0 : config.onError) !== void 0 ? { onError: config.onError } : {},
1475
+ ...(config == null ? void 0 : config.aiIcon) !== void 0 ? { aiIcon: config.aiIcon } : {}
1476
+ };
1477
+ });
1478
+ }).use(aiProviderConfig).use(aiSessionCtx).use(runAICmd).use(abortAICmd).config(configureAIInstructionTooltip(config)).use(aiInstructionTooltipAPI).use(aiInstructionTooltip).use(streamingIndicatorPlugin({ config: config == null ? void 0 : config.streamingIndicator })).use(
1479
+ diffActionsPanelPlugin({
1480
+ config: config == null ? void 0 : config.diffActions,
1481
+ enterKeyIcon: config == null ? void 0 : config.enterKeyIcon
1482
+ })
1483
+ );
1484
+ };
1485
+
1486
+ export { abortAICmd, ai, defaultBuildContext, runAICmd };
1487
+ //# sourceMappingURL=index.js.map