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