next-ai-editor 0.1.2 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (67) hide show
  1. package/dist/AIEditorProvider-CKA2K_g2.js +1428 -0
  2. package/dist/AIEditorProvider-CKA2K_g2.js.map +1 -0
  3. package/dist/AIEditorProvider-C_zRSAuV.cjs +1427 -0
  4. package/dist/AIEditorProvider-C_zRSAuV.cjs.map +1 -0
  5. package/dist/client/AIEditorProvider.d.ts +1 -33
  6. package/dist/client/AIEditorProvider.d.ts.map +1 -1
  7. package/dist/client/components/ChatPanel.d.ts +18 -0
  8. package/dist/client/components/ChatPanel.d.ts.map +1 -0
  9. package/dist/client/components/ControlPill.d.ts +8 -0
  10. package/dist/client/components/ControlPill.d.ts.map +1 -0
  11. package/dist/client/components/MessageItem.d.ts +7 -0
  12. package/dist/client/components/MessageItem.d.ts.map +1 -0
  13. package/dist/client/components/MessageList.d.ts +7 -0
  14. package/dist/client/components/MessageList.d.ts.map +1 -0
  15. package/dist/client/components/TaskHistoryPanel.d.ts +10 -0
  16. package/dist/client/components/TaskHistoryPanel.d.ts.map +1 -0
  17. package/dist/client/components/index.d.ts +11 -0
  18. package/dist/client/components/index.d.ts.map +1 -0
  19. package/dist/client/hooks/index.d.ts +3 -0
  20. package/dist/client/hooks/index.d.ts.map +1 -0
  21. package/dist/client/hooks/useChatStream.d.ts +66 -0
  22. package/dist/client/hooks/useChatStream.d.ts.map +1 -0
  23. package/dist/client/hooks/useHotReload.d.ts +10 -0
  24. package/dist/client/hooks/useHotReload.d.ts.map +1 -0
  25. package/dist/client/index.d.ts +3 -0
  26. package/dist/client/index.d.ts.map +1 -1
  27. package/dist/client.cjs +7 -1
  28. package/dist/client.cjs.map +1 -1
  29. package/dist/client.js +8 -2
  30. package/dist/client.js.map +1 -1
  31. package/dist/{index-3OMXRwpD.js → comments-D3m0RsOO.js} +505 -26
  32. package/dist/comments-D3m0RsOO.js.map +1 -0
  33. package/dist/{index-9QODCOgD.cjs → comments-Daur80r4.cjs} +492 -13
  34. package/dist/comments-Daur80r4.cjs.map +1 -0
  35. package/dist/index.cjs +34 -26
  36. package/dist/index.cjs.map +1 -1
  37. package/dist/index.js +22 -14
  38. package/dist/index.js.map +1 -1
  39. package/dist/next-ai-editor.css +880 -0
  40. package/dist/server/agent/sdk-client.d.ts +54 -0
  41. package/dist/server/agent/sdk-client.d.ts.map +1 -0
  42. package/dist/server/agent/session-store.d.ts +101 -0
  43. package/dist/server/agent/session-store.d.ts.map +1 -0
  44. package/dist/server/handlers/chat.d.ts +6 -0
  45. package/dist/server/handlers/chat.d.ts.map +1 -0
  46. package/dist/server/handlers/comments.d.ts +10 -0
  47. package/dist/server/handlers/comments.d.ts.map +1 -0
  48. package/dist/server/handlers/index.d.ts +2 -1
  49. package/dist/server/handlers/index.d.ts.map +1 -1
  50. package/dist/server/handlers/read.d.ts.map +1 -1
  51. package/dist/server/index.d.ts +1 -0
  52. package/dist/server/index.d.ts.map +1 -1
  53. package/dist/server/utils/ast.d.ts.map +1 -1
  54. package/dist/server/utils/source-map.d.ts +5 -0
  55. package/dist/server/utils/source-map.d.ts.map +1 -1
  56. package/dist/server.cjs +27 -25
  57. package/dist/server.cjs.map +1 -1
  58. package/dist/server.js +14 -12
  59. package/dist/shared/comment-types.d.ts +140 -0
  60. package/dist/shared/comment-types.d.ts.map +1 -0
  61. package/package.json +13 -4
  62. package/dist/AIEditorProvider-CFFnEtEB.js +0 -2170
  63. package/dist/AIEditorProvider-CFFnEtEB.js.map +0 -1
  64. package/dist/AIEditorProvider-CmiACRfw.cjs +0 -2169
  65. package/dist/AIEditorProvider-CmiACRfw.cjs.map +0 -1
  66. package/dist/index-3OMXRwpD.js.map +0 -1
  67. package/dist/index-9QODCOgD.cjs.map +0 -1
@@ -1,2170 +0,0 @@
1
- "use client";
2
- import { jsx, Fragment, jsxs } from "react/jsx-runtime";
3
- import { createContext, useState, useEffect, useCallback, useContext } from "react";
4
- import { Prism } from "react-syntax-highlighter";
5
- import { vscDarkPlus, vs } from "react-syntax-highlighter/dist/esm/styles/prism";
6
- import { c as cleanPath, s as shouldSkipPath } from "./path-utils-Bai2xKx9.js";
7
- const _AIEditorStorage = class _AIEditorStorage {
8
- // 5MB
9
- /**
10
- * Generate storage key from file path and component name
11
- * Format: "ai-editor:session:components/Header.tsx#Header"
12
- */
13
- static getSessionKey(filePath, componentName) {
14
- const normalizedPath = filePath.replace(/\\/g, "/");
15
- return `${this.STORAGE_PREFIX}${normalizedPath}#${componentName}`;
16
- }
17
- /**
18
- * Save session to localStorage
19
- */
20
- static saveSession(session) {
21
- try {
22
- const key = this.getSessionKey(
23
- session.sourceLocation.filePath,
24
- session.sourceLocation.componentName
25
- );
26
- if (this.getStorageSize() > this.MAX_STORAGE_SIZE) {
27
- console.warn("Storage size exceeded, pruning old sessions...");
28
- this.pruneOldSessions(7 * 24 * 60 * 60 * 1e3);
29
- }
30
- const serialized = JSON.stringify(session);
31
- localStorage.setItem(key, serialized);
32
- return true;
33
- } catch (e) {
34
- if (e instanceof Error && e.name === "QuotaExceededError") {
35
- console.error("localStorage quota exceeded");
36
- this.pruneOldSessions(7 * 24 * 60 * 60 * 1e3);
37
- try {
38
- const key = this.getSessionKey(
39
- session.sourceLocation.filePath,
40
- session.sourceLocation.componentName
41
- );
42
- const serialized = JSON.stringify(session);
43
- localStorage.setItem(key, serialized);
44
- return true;
45
- } catch {
46
- return false;
47
- }
48
- }
49
- console.error("Failed to save session:", e);
50
- return false;
51
- }
52
- }
53
- /**
54
- * Load session by filePath + componentName
55
- */
56
- static loadSession(filePath, componentName) {
57
- try {
58
- const key = this.getSessionKey(filePath, componentName);
59
- const stored = localStorage.getItem(key);
60
- if (!stored) return null;
61
- const session = JSON.parse(stored);
62
- if (!session.version || !session.sourceLocation || !session.editHistory) {
63
- console.warn("Invalid session schema, removing corrupted data");
64
- localStorage.removeItem(key);
65
- return null;
66
- }
67
- return session;
68
- } catch (e) {
69
- console.error("Failed to load session:", e);
70
- const key = this.getSessionKey(filePath, componentName);
71
- localStorage.removeItem(key);
72
- return null;
73
- }
74
- }
75
- /**
76
- * Delete specific session
77
- */
78
- static deleteSession(filePath, componentName) {
79
- try {
80
- const key = this.getSessionKey(filePath, componentName);
81
- localStorage.removeItem(key);
82
- } catch (e) {
83
- console.error("Failed to delete session:", e);
84
- }
85
- }
86
- /**
87
- * Get all session keys
88
- */
89
- static getAllSessionKeys() {
90
- const keys = [];
91
- try {
92
- for (let i = 0; i < localStorage.length; i++) {
93
- const key = localStorage.key(i);
94
- if (key && key.startsWith(this.STORAGE_PREFIX)) {
95
- keys.push(key);
96
- }
97
- }
98
- } catch (e) {
99
- console.error("Failed to get session keys:", e);
100
- }
101
- return keys;
102
- }
103
- /**
104
- * Clear all sessions
105
- */
106
- static clearAllSessions() {
107
- try {
108
- const keys = this.getAllSessionKeys();
109
- keys.forEach((key) => localStorage.removeItem(key));
110
- console.log(`Cleared ${keys.length} session(s)`);
111
- } catch (e) {
112
- console.error("Failed to clear sessions:", e);
113
- }
114
- }
115
- /**
116
- * Get total storage usage in bytes
117
- */
118
- static getStorageSize() {
119
- let total = 0;
120
- try {
121
- for (let i = 0; i < localStorage.length; i++) {
122
- const key = localStorage.key(i);
123
- if (key && key.startsWith(this.STORAGE_PREFIX)) {
124
- const value = localStorage.getItem(key);
125
- if (value) {
126
- total += (key.length + value.length) * 2;
127
- }
128
- }
129
- }
130
- } catch (e) {
131
- console.error("Failed to calculate storage size:", e);
132
- }
133
- return total;
134
- }
135
- /**
136
- * Remove sessions older than maxAge milliseconds
137
- */
138
- static pruneOldSessions(maxAge) {
139
- try {
140
- const now = Date.now();
141
- const keys = this.getAllSessionKeys();
142
- keys.forEach((key) => {
143
- const value = localStorage.getItem(key);
144
- if (!value) return;
145
- try {
146
- const session = JSON.parse(value);
147
- const age = now - session.lastModified;
148
- if (age > maxAge) {
149
- console.log(`Pruning old session: ${key} (age: ${Math.round(age / (24 * 60 * 60 * 1e3))} days)`);
150
- localStorage.removeItem(key);
151
- }
152
- } catch (e) {
153
- console.warn(`Removing corrupted session: ${key}`);
154
- localStorage.removeItem(key);
155
- }
156
- });
157
- } catch (e) {
158
- console.error("Failed to prune sessions:", e);
159
- }
160
- }
161
- /**
162
- * Compute SHA-256 hash of file content using Web Crypto API
163
- */
164
- static async hashFileContent(content) {
165
- try {
166
- const encoder = new TextEncoder();
167
- const data = encoder.encode(content);
168
- const hashBuffer = await crypto.subtle.digest("SHA-256", data);
169
- const hashArray = Array.from(new Uint8Array(hashBuffer));
170
- const hashHex = hashArray.map((byte) => byte.toString(16).padStart(2, "0")).join("");
171
- return hashHex;
172
- } catch (e) {
173
- console.error("Failed to hash content:", e);
174
- return this.simpleHash(content);
175
- }
176
- }
177
- /**
178
- * Simple hash fallback (for environments without Web Crypto API)
179
- */
180
- static simpleHash(str) {
181
- let hash = 0;
182
- for (let i = 0; i < str.length; i++) {
183
- const char = str.charCodeAt(i);
184
- hash = (hash << 5) - hash + char;
185
- hash = hash & hash;
186
- }
187
- return hash.toString(16);
188
- }
189
- /**
190
- * Get most recently modified session
191
- */
192
- static getLastActiveSession() {
193
- try {
194
- const keys = this.getAllSessionKeys();
195
- if (keys.length === 0) return null;
196
- let latestSession = null;
197
- let latestTime = 0;
198
- keys.forEach((key) => {
199
- const value = localStorage.getItem(key);
200
- if (!value) return;
201
- try {
202
- const session = JSON.parse(value);
203
- if (!session.version || !session.sourceLocation || !session.editHistory) {
204
- console.warn(`Skipping invalid session: ${key}`);
205
- return;
206
- }
207
- if (session.lastModified > latestTime) {
208
- latestTime = session.lastModified;
209
- latestSession = session;
210
- }
211
- } catch (e) {
212
- console.warn(`Skipping corrupted session: ${key}`);
213
- }
214
- });
215
- return latestSession;
216
- } catch (e) {
217
- console.error("Failed to get last active session:", e);
218
- return null;
219
- }
220
- }
221
- };
222
- _AIEditorStorage.STORAGE_PREFIX = "ai-editor:session:";
223
- _AIEditorStorage.VERSION = "1.0.0";
224
- _AIEditorStorage.MAX_STORAGE_SIZE = 5 * 1024 * 1024;
225
- let AIEditorStorage = _AIEditorStorage;
226
- function buildReadQueryParams(selectedSource, includeParent = true) {
227
- var _a, _b, _c, _d;
228
- const params = {
229
- path: selectedSource.filePath,
230
- line: String(selectedSource.lineNumber),
231
- tagName: ((_a = selectedSource.elementContext) == null ? void 0 : _a.tagName) || "",
232
- nthOfType: String(((_b = selectedSource.elementContext) == null ? void 0 : _b.nthOfType) || 0),
233
- textContent: ((_c = selectedSource.elementContext) == null ? void 0 : _c.textContent) || "",
234
- className: ((_d = selectedSource.elementContext) == null ? void 0 : _d.className) || ""
235
- };
236
- if (selectedSource.debugStack) {
237
- params.debugStack = selectedSource.debugStack;
238
- }
239
- if (includeParent && selectedSource.parentComponent) {
240
- params.parentFilePath = selectedSource.parentComponent.filePath;
241
- params.parentLine = String(selectedSource.parentComponent.lineNumber);
242
- params.parentComponentName = selectedSource.parentComponent.componentName;
243
- if (selectedSource.parentComponent.debugStack) {
244
- params.parentDebugStack = selectedSource.parentComponent.debugStack;
245
- }
246
- if (selectedSource.parentComponent.childKey) {
247
- params.childKey = selectedSource.parentComponent.childKey;
248
- }
249
- }
250
- return params;
251
- }
252
- function getFiberFromElement(element) {
253
- const key = Object.keys(element).find(
254
- (k) => k.startsWith("__reactFiber$") || k.startsWith("__reactInternalInstance$")
255
- );
256
- return key ? element[key] : null;
257
- }
258
- function getComponentName(fiber) {
259
- var _a, _b;
260
- if (!fiber) return "Unknown";
261
- const type = fiber.type;
262
- if ((_a = fiber._debugSource) == null ? void 0 : _a.fileName) {
263
- const fileName = fiber._debugSource.fileName;
264
- const match = fileName.match(/\/([^/]+)\.(tsx?|jsx?)$/);
265
- if (match) return match[1];
266
- }
267
- if (typeof type === "string") return type;
268
- if (typeof type === "function")
269
- return type.displayName || type.name || "Anonymous";
270
- if (type == null ? void 0 : type.displayName) return type.displayName;
271
- if ((_b = type == null ? void 0 : type.render) == null ? void 0 : _b.name) return type.render.name;
272
- if (fiber._debugStack) {
273
- const stack = String(fiber._debugStack.stack || fiber._debugStack);
274
- const match = stack.match(/at\s+([A-Z][a-zA-Z0-9]*)\s*\(/);
275
- if (match && match[1] !== "Object") {
276
- return match[1];
277
- }
278
- }
279
- return "Unknown";
280
- }
281
- function isUserComponent(fiber) {
282
- if (fiber.tag === 5 || fiber.tag === 6 || fiber.tag === 3) return false;
283
- const type = fiber.type;
284
- if (!type || typeof type === "string") return false;
285
- return true;
286
- }
287
- function countNthOfType(element, tagName) {
288
- let boundary = element.parentElement;
289
- while (boundary) {
290
- const fiber = getFiberFromElement(boundary);
291
- if (fiber && isUserComponent(fiber)) break;
292
- boundary = boundary.parentElement;
293
- }
294
- if (!boundary) boundary = element.parentElement;
295
- if (!boundary) return 1;
296
- const sameTagElements = [];
297
- if (boundary.tagName.toLowerCase() === tagName.toLowerCase()) {
298
- sameTagElements.push(boundary);
299
- }
300
- sameTagElements.push(...Array.from(boundary.querySelectorAll(tagName)));
301
- let count = 1;
302
- for (const el of sameTagElements) {
303
- if (el === element) break;
304
- count++;
305
- }
306
- return count;
307
- }
308
- function extractProps(fiber) {
309
- if (!fiber) return void 0;
310
- const fiberProps = fiber.memoizedProps || fiber.pendingProps;
311
- if (!fiberProps || typeof fiberProps !== "object") return void 0;
312
- const props = {};
313
- const identifyingKeys = [
314
- "id",
315
- "name",
316
- "type",
317
- "href",
318
- "src",
319
- "alt",
320
- "role",
321
- "aria-label",
322
- "data-testid"
323
- ];
324
- for (const key of identifyingKeys) {
325
- if (key in fiberProps && typeof fiberProps[key] === "string") {
326
- props[key] = fiberProps[key];
327
- }
328
- }
329
- if (fiberProps.style && typeof fiberProps.style === "object") {
330
- props._styleKeys = Object.keys(fiberProps.style).slice(0, 5);
331
- }
332
- return Object.keys(props).length > 0 ? props : void 0;
333
- }
334
- function captureElementContext(element, fiber) {
335
- const tagName = element.tagName.toLowerCase();
336
- let textContent;
337
- const directText = Array.from(element.childNodes).filter((n) => n.nodeType === Node.TEXT_NODE).map((n) => {
338
- var _a;
339
- return (_a = n.textContent) == null ? void 0 : _a.trim();
340
- }).filter(Boolean).join(" ");
341
- if (directText) {
342
- textContent = directText.slice(0, 50);
343
- } else if (element.textContent) {
344
- textContent = element.textContent.trim().slice(0, 50);
345
- }
346
- const className = typeof element.className === "string" ? element.className.slice(0, 100) : void 0;
347
- const nthOfType = countNthOfType(element, tagName);
348
- const key = (fiber == null ? void 0 : fiber.key) ? String(fiber.key) : void 0;
349
- const props = extractProps(fiber);
350
- return { tagName, textContent, className, key, nthOfType, props };
351
- }
352
- function extractFromDebugStack(fiber) {
353
- const stack = fiber._debugStack;
354
- if (!stack) return null;
355
- const stackStr = stack.stack || String(stack);
356
- const frames = stackStr.split("\n");
357
- const skipPatterns = [
358
- "node_modules",
359
- "SegmentViewNode",
360
- "LayoutRouter",
361
- "ErrorBoundary",
362
- "fakeJSXCallSite"
363
- ];
364
- for (const frame of frames) {
365
- if (skipPatterns.some((p) => frame.includes(p))) continue;
366
- const match = frame.match(/at\s+(\w+)\s+\((.+?):(\d+):(\d+)\)?$/);
367
- if (match) {
368
- const fileName = cleanPath(match[2].replace(/\?[^:]*$/, ""));
369
- if (!shouldSkipPath(fileName, ["ai-editor-provider"])) {
370
- return {
371
- fileName,
372
- lineNumber: parseInt(match[3], 10),
373
- columnNumber: parseInt(match[4], 10)
374
- };
375
- }
376
- }
377
- }
378
- return null;
379
- }
380
- function extractFromDebugOwner(fiber) {
381
- var _a, _b;
382
- const owner = fiber._debugOwner;
383
- if (!owner) return null;
384
- if ((_a = owner._debugSource) == null ? void 0 : _a.fileName) {
385
- return owner._debugSource;
386
- }
387
- const stack = owner.stack;
388
- if (Array.isArray(stack) && ((_b = stack[0]) == null ? void 0 : _b.fileName)) {
389
- return stack[0];
390
- }
391
- return null;
392
- }
393
- function findSourceFromFiber(fiber) {
394
- if (!fiber) return null;
395
- let actualComponentName = null;
396
- if (fiber._debugOwner && typeof fiber._debugOwner === "object") {
397
- const debugOwner = fiber._debugOwner;
398
- if (debugOwner.name && typeof debugOwner.name === "string") {
399
- actualComponentName = debugOwner.name;
400
- }
401
- }
402
- let current = fiber;
403
- const visited = /* @__PURE__ */ new Set();
404
- let iterations = 0;
405
- while (current && !visited.has(current) && iterations < 10) {
406
- iterations++;
407
- visited.add(current);
408
- const sourceData = current._debugSource || extractFromDebugStack(current) || extractFromDebugOwner(current);
409
- if (sourceData == null ? void 0 : sourceData.fileName) {
410
- const filePath = cleanPath(sourceData.fileName);
411
- if (!shouldSkipPath(filePath, ["ai-editor-provider"])) {
412
- if (actualComponentName) {
413
- const rawDebugStack = current._debugStack ? String(current._debugStack.stack || current._debugStack) : void 0;
414
- return {
415
- filePath,
416
- lineNumber: sourceData.lineNumber || 1,
417
- columnNumber: sourceData.columnNumber || 0,
418
- componentName: actualComponentName,
419
- debugStack: rawDebugStack
420
- };
421
- } else {
422
- let componentFiber = current;
423
- while (componentFiber) {
424
- if (isUserComponent(componentFiber)) {
425
- const componentName = getComponentName(componentFiber);
426
- const isNextJSInternal = [
427
- "Segment",
428
- "Boundary",
429
- "Router",
430
- "Handler",
431
- "Context",
432
- "Layout",
433
- "Template",
434
- "Scroll",
435
- "Focus",
436
- "Loading",
437
- "Error"
438
- ].some((pattern) => componentName.includes(pattern));
439
- if (!isNextJSInternal) {
440
- const rawDebugStack = current._debugStack ? String(current._debugStack.stack || current._debugStack) : void 0;
441
- return {
442
- filePath,
443
- lineNumber: sourceData.lineNumber || 1,
444
- columnNumber: sourceData.columnNumber || 0,
445
- componentName,
446
- debugStack: rawDebugStack
447
- };
448
- }
449
- }
450
- componentFiber = componentFiber.return || componentFiber._debugOwner || null;
451
- }
452
- }
453
- }
454
- }
455
- current = current.return || current._debugOwner || null;
456
- }
457
- return null;
458
- }
459
- function findParentComponentFromFiber(childFiber, childComponentName) {
460
- if (!childFiber) return null;
461
- let childComponentFiber = null;
462
- if (childFiber._debugOwner && typeof childFiber._debugOwner === "object") {
463
- const debugOwner = childFiber._debugOwner;
464
- if (debugOwner.type && typeof debugOwner.type === "function") {
465
- const ownerComponentName = getComponentName(debugOwner);
466
- if (ownerComponentName === childComponentName) {
467
- childComponentFiber = debugOwner;
468
- }
469
- }
470
- }
471
- if (!childComponentFiber) {
472
- let current2 = childFiber;
473
- let iterations2 = 0;
474
- while (current2 && iterations2 < 20) {
475
- iterations2++;
476
- const componentName = getComponentName(current2);
477
- current2.index;
478
- if (isUserComponent(current2)) {
479
- if (componentName === childComponentName) {
480
- childComponentFiber = current2;
481
- break;
482
- }
483
- }
484
- if (current2._debugOwner && typeof current2._debugOwner === "object") {
485
- const debugOwner = current2._debugOwner;
486
- if (debugOwner.name === childComponentName && !debugOwner.type) {
487
- const parent = current2.return;
488
- const parentDebugOwner = parent == null ? void 0 : parent._debugOwner;
489
- const isRootElement = !parentDebugOwner || parentDebugOwner.name !== childComponentName;
490
- if (isRootElement) {
491
- childComponentFiber = current2;
492
- break;
493
- }
494
- }
495
- }
496
- current2 = current2.return;
497
- }
498
- }
499
- let childKey;
500
- if (childComponentFiber == null ? void 0 : childComponentFiber.key) {
501
- childKey = String(childComponentFiber.key);
502
- } else if (childComponentFiber && typeof childComponentFiber.index === "number") {
503
- childKey = String(childComponentFiber.index);
504
- }
505
- if (childFiber._debugOwner && typeof childFiber._debugOwner === "object") {
506
- const debugOwner = childFiber._debugOwner;
507
- if (debugOwner.owner && debugOwner.owner.name) {
508
- const parentName = debugOwner.owner.name;
509
- const parentDebugLocation = debugOwner.owner.debugLocation;
510
- if (parentDebugLocation) {
511
- const stack = String(parentDebugLocation.stack || parentDebugLocation);
512
- return {
513
- filePath: "",
514
- // Will be resolved on server
515
- lineNumber: 0,
516
- columnNumber: 0,
517
- componentName: parentName,
518
- debugStack: stack,
519
- childKey
520
- };
521
- }
522
- }
523
- if (debugOwner.type && typeof debugOwner.type === "function") {
524
- const componentFiberOwner = debugOwner._debugOwner;
525
- if (componentFiberOwner && typeof componentFiberOwner === "object") {
526
- const parentName = componentFiberOwner.name;
527
- const parentDebugLocation = componentFiberOwner.debugLocation;
528
- if (parentName && typeof parentName === "string") {
529
- if (parentDebugLocation) {
530
- const stack = String(
531
- parentDebugLocation.stack || parentDebugLocation
532
- );
533
- return {
534
- filePath: "",
535
- // Will be resolved on server
536
- lineNumber: 0,
537
- columnNumber: 0,
538
- componentName: parentName,
539
- debugStack: stack,
540
- childKey
541
- };
542
- }
543
- }
544
- }
545
- }
546
- }
547
- let current = childFiber.return;
548
- const visited = /* @__PURE__ */ new Set();
549
- let iterations = 0;
550
- while (current && !visited.has(current) && iterations < 20) {
551
- iterations++;
552
- visited.add(current);
553
- if (isUserComponent(current)) {
554
- const componentName = getComponentName(current);
555
- if (componentName === childComponentName) {
556
- current = current._debugOwner || null;
557
- continue;
558
- }
559
- const shouldSkipComponent = componentName.includes("AIEditorProvider") || // Skip the AI Editor wrapper itself
560
- componentName.startsWith("__next") || // Skip all Next.js internal components like __next_root_layout_boundary__
561
- componentName.startsWith("_") || // Skip internal components starting with underscore
562
- [
563
- "Segment",
564
- "Boundary",
565
- "Router",
566
- "Handler",
567
- "Context",
568
- "Layout",
569
- "Template",
570
- "Scroll",
571
- "Focus",
572
- "Loading",
573
- "Error",
574
- "RootLayout",
575
- // Skip root layout wrapper
576
- "NotFound"
577
- ].some((pattern) => componentName.includes(pattern));
578
- if (shouldSkipComponent) {
579
- current = current._debugOwner || null;
580
- continue;
581
- }
582
- const sourceData = current._debugSource || extractFromDebugStack(current) || extractFromDebugOwner(current);
583
- if (sourceData == null ? void 0 : sourceData.fileName) {
584
- const filePath = cleanPath(sourceData.fileName);
585
- if (!shouldSkipPath(filePath, ["ai-editor-provider"])) {
586
- const rawDebugStack = current._debugStack ? String(current._debugStack.stack || current._debugStack) : void 0;
587
- return {
588
- filePath,
589
- lineNumber: sourceData.lineNumber || 1,
590
- columnNumber: sourceData.columnNumber || 0,
591
- componentName,
592
- debugStack: rawDebugStack,
593
- childKey
594
- };
595
- }
596
- }
597
- }
598
- const nextOwner = current._debugOwner;
599
- current = nextOwner || null;
600
- }
601
- const childDebugStack = childFiber._debugStack ? String(childFiber._debugStack.stack || childFiber._debugStack) : null;
602
- if (childDebugStack) {
603
- return {
604
- filePath: "",
605
- // Will be resolved on server from debugStack
606
- lineNumber: 0,
607
- columnNumber: 0,
608
- componentName: "",
609
- // Will be determined on server
610
- debugStack: childDebugStack,
611
- // Use child's debugStack for server-side resolution
612
- childKey
613
- };
614
- }
615
- return null;
616
- }
617
- function getSourceFromElement(element) {
618
- var _a;
619
- let current = element;
620
- let elementWithSource = null;
621
- let fiberWithSource = null;
622
- while (current && current !== document.body) {
623
- const fiber = getFiberFromElement(current);
624
- if (fiber) {
625
- const hasSourceInfo = ((_a = fiber._debugSource) == null ? void 0 : _a.fileName) || fiber._debugStack || fiber._debugOwner && typeof fiber._debugOwner === "object";
626
- if (hasSourceInfo && !fiberWithSource) {
627
- elementWithSource = current;
628
- fiberWithSource = fiber;
629
- }
630
- }
631
- current = current.parentElement;
632
- }
633
- if (!fiberWithSource || !elementWithSource) return null;
634
- const source = findSourceFromFiber(fiberWithSource);
635
- if (!source) return null;
636
- const elementContext = captureElementContext(elementWithSource, fiberWithSource);
637
- const parentComponent = findParentComponentFromFiber(
638
- fiberWithSource,
639
- source.componentName
640
- );
641
- return {
642
- ...source,
643
- elementContext,
644
- parentComponent: parentComponent || void 0
645
- };
646
- }
647
- if (typeof window !== "undefined") {
648
- window.__getSource = getSourceFromElement;
649
- }
650
- const ENABLE_SESSION_PERSISTENCE = false;
651
- const sourceResolutionCache = /* @__PURE__ */ new Map();
652
- const inflightSourceResolutions = /* @__PURE__ */ new Map();
653
- function inferComponentNameFromPath(filePath) {
654
- const fileName = filePath.split("/").pop() || "";
655
- const nameWithoutExt = fileName.replace(/\.(tsx?|jsx?)$/, "");
656
- return nameWithoutExt.charAt(0).toUpperCase() + nameWithoutExt.slice(1);
657
- }
658
- async function resolveSourceLocation(source) {
659
- if (typeof window === "undefined" || process.env.NODE_ENV !== "development") {
660
- return null;
661
- }
662
- if (!source.debugStack) {
663
- console.warn("No debugStack available for resolution:", source);
664
- return null;
665
- }
666
- const cacheKey = source.debugStack;
667
- const cached = sourceResolutionCache.get(cacheKey);
668
- if (cached) {
669
- const resolved2 = { ...source, ...cached };
670
- if (resolved2.componentName === "Unknown" && resolved2.filePath) {
671
- resolved2.componentName = inferComponentNameFromPath(resolved2.filePath);
672
- }
673
- return resolved2;
674
- }
675
- let inflight = inflightSourceResolutions.get(cacheKey);
676
- if (!inflight) {
677
- inflight = fetch("/api/ai-editor/resolve", {
678
- method: "POST",
679
- headers: { "Content-Type": "application/json" },
680
- body: JSON.stringify({ debugStack: cacheKey })
681
- }).then(async (res) => {
682
- if (!res.ok) {
683
- const errorText = await res.text();
684
- console.error(
685
- `Resolve API error ${res.status}:`,
686
- errorText,
687
- "for stack:",
688
- cacheKey.substring(0, 200)
689
- );
690
- return inferFilePathFromComponentName(source.componentName);
691
- }
692
- const data = await res.json();
693
- if ((data == null ? void 0 : data.success) && data.filePath && data.lineNumber) {
694
- const resolved2 = {
695
- filePath: data.filePath,
696
- lineNumber: data.lineNumber,
697
- columnNumber: typeof data.columnNumber === "number" ? data.columnNumber : source.columnNumber
698
- };
699
- sourceResolutionCache.set(cacheKey, resolved2);
700
- return resolved2;
701
- }
702
- console.warn("Resolve API returned unsuccessful response:", data);
703
- return inferFilePathFromComponentName(source.componentName);
704
- }).catch((err) => {
705
- console.error("Error calling resolve API:", err);
706
- return inferFilePathFromComponentName(source.componentName);
707
- }).finally(() => {
708
- inflightSourceResolutions.delete(cacheKey);
709
- });
710
- inflightSourceResolutions.set(cacheKey, inflight);
711
- }
712
- const resolvedInfo = await inflight;
713
- if (!resolvedInfo) return null;
714
- const resolved = {
715
- ...source,
716
- filePath: resolvedInfo.filePath,
717
- lineNumber: resolvedInfo.lineNumber,
718
- columnNumber: resolvedInfo.columnNumber
719
- };
720
- if (resolved.componentName === "Unknown" && resolved.filePath) {
721
- resolved.componentName = inferComponentNameFromPath(resolved.filePath);
722
- }
723
- return resolved;
724
- }
725
- async function inferFilePathFromComponentName(componentName) {
726
- if (!componentName || componentName === "Unknown") return null;
727
- const possiblePaths = [
728
- `components/${componentName}.tsx`,
729
- `components/${componentName}.jsx`,
730
- `app/${componentName}.tsx`,
731
- `app/${componentName}.jsx`,
732
- `src/components/${componentName}.tsx`,
733
- `src/components/${componentName}.jsx`
734
- ];
735
- for (const tryPath of possiblePaths) {
736
- try {
737
- const response = await fetch(
738
- `/api/ai-editor/absolute-path?path=${encodeURIComponent(tryPath)}`
739
- );
740
- if (response.ok) {
741
- const data = await response.json();
742
- if (data.success) {
743
- console.log(
744
- `Inferred file path for ${componentName}: ${tryPath}`
745
- );
746
- return {
747
- filePath: tryPath,
748
- lineNumber: 1,
749
- columnNumber: 0
750
- };
751
- }
752
- }
753
- } catch (err) {
754
- }
755
- }
756
- console.warn(`Could not infer file path for component: ${componentName}`);
757
- return null;
758
- }
759
- const EditorContext = createContext(null);
760
- function useAIEditor() {
761
- const ctx = useContext(EditorContext);
762
- if (!ctx) throw new Error("useAIEditor must be used within AIEditorProvider");
763
- return ctx;
764
- }
765
- function AIEditorProvider({
766
- children,
767
- theme = "dark"
768
- }) {
769
- const [isEnabled, setEnabled] = useState(false);
770
- const [selectedSource, setSelectedSource] = useState(
771
- null
772
- );
773
- const [selectedDOMElement, setSelectedDOMElement] = useState(
774
- null
775
- );
776
- const [isLoading, setIsLoading] = useState(false);
777
- const [editHistory, setEditHistory] = useState([]);
778
- const [showStaleWarning, setShowStaleWarning] = useState(false);
779
- const [staleSession, setStaleSession] = useState(null);
780
- const [hasActiveSession, setHasActiveSession] = useState(false);
781
- const [parentInstance, setParentInstance] = useState(null);
782
- const [suggestions, setSuggestions] = useState([]);
783
- const [suggestionsLoading, setSuggestionsLoading] = useState(false);
784
- const [lastAppliedSuggestion, setLastAppliedSuggestion] = useState(void 0);
785
- const [suggestionsCache, setSuggestionsCache] = useState(/* @__PURE__ */ new Map());
786
- useEffect(() => {
787
- const handleKey = (e) => {
788
- if ((e.ctrlKey || e.metaKey) && e.shiftKey && e.key.toLowerCase() === "e") {
789
- e.preventDefault();
790
- setEnabled((p) => !p);
791
- }
792
- };
793
- window.addEventListener("keydown", handleKey);
794
- return () => window.removeEventListener("keydown", handleKey);
795
- }, []);
796
- useEffect(() => {
797
- return;
798
- }, []);
799
- const restoreSession = useCallback(async (session) => {
800
- const sourceLocation = session.sourceLocation;
801
- setSelectedSource(sourceLocation);
802
- setEditHistory(session.editHistory);
803
- if (sourceLocation.debugStack) {
804
- const resolved = await resolveSourceLocation(sourceLocation);
805
- if (resolved) {
806
- setSelectedSource(resolved);
807
- }
808
- }
809
- }, []);
810
- const handleClearSession = useCallback(() => {
811
- if (selectedSource) {
812
- AIEditorStorage.deleteSession(
813
- selectedSource.filePath,
814
- selectedSource.componentName
815
- );
816
- setHasActiveSession(false);
817
- setSelectedSource(null);
818
- setEditHistory([]);
819
- }
820
- }, [selectedSource]);
821
- const submitEdit = useCallback(
822
- async (suggestion) => {
823
- if (!selectedSource)
824
- return { success: false, error: "No element selected" };
825
- const editId = Date.now().toString(36) + Math.random().toString(36).substring(2);
826
- const pendingEdit = {
827
- id: editId,
828
- suggestion,
829
- success: false,
830
- pending: true,
831
- timestamp: Date.now()
832
- };
833
- setEditHistory((prev) => [...prev, pendingEdit]);
834
- setIsLoading(true);
835
- try {
836
- const res = await fetch("/api/ai-editor/edit", {
837
- method: "POST",
838
- headers: { "Content-Type": "application/json" },
839
- body: JSON.stringify({
840
- filePath: selectedSource.filePath,
841
- lineNumber: selectedSource.lineNumber,
842
- componentName: selectedSource.componentName,
843
- suggestion,
844
- // NEW: Pass element context for precise matching
845
- elementContext: selectedSource.elementContext,
846
- // Pass debugStack for server-side source map resolution
847
- debugStack: selectedSource.debugStack,
848
- // Pass edit history for context
849
- editHistory: editHistory.map((item) => ({
850
- suggestion: item.suggestion,
851
- success: item.success
852
- })),
853
- // Pass parent instance if available
854
- parentInstance
855
- })
856
- });
857
- const result = await res.json();
858
- const completedEdit = {
859
- id: editId,
860
- suggestion,
861
- success: result.success,
862
- pending: false,
863
- error: result.error,
864
- timestamp: Date.now(),
865
- fileSnapshot: result.fileSnapshot,
866
- editedFilePath: result.editedFile,
867
- // Track which file was actually edited
868
- generatedCode: result.generatedCode,
869
- modifiedLines: result.modifiedLines
870
- };
871
- setEditHistory(
872
- (prev) => prev.map((item) => item.id === editId ? completedEdit : item)
873
- );
874
- if (ENABLE_SESSION_PERSISTENCE && selectedSource && result.fileSnapshot) ;
875
- return result;
876
- } catch (err) {
877
- const error = String(err);
878
- setEditHistory(
879
- (prev) => prev.map(
880
- (item) => item.id === editId ? { ...item, success: false, pending: false, error } : item
881
- )
882
- );
883
- return { success: false, error };
884
- } finally {
885
- setIsLoading(false);
886
- }
887
- },
888
- [selectedSource, editHistory, parentInstance]
889
- );
890
- const fetchSuggestions = useCallback(
891
- async (source, history, lastEdit, excludedSuggestions) => {
892
- var _a, _b, _c, _d;
893
- const CACHE_TTL = 3e4;
894
- const cacheKey = `${source.componentName}:${((_a = source.elementContext) == null ? void 0 : _a.tagName) || "div"}:${lastEdit || "initial"}`;
895
- console.log("[AI Editor] fetchSuggestions called. cacheKey:", cacheKey, "lastEdit:", lastEdit, "excludedSuggestions:", excludedSuggestions);
896
- const cached = !(excludedSuggestions == null ? void 0 : excludedSuggestions.length) ? suggestionsCache.get(cacheKey) : null;
897
- if (cached && Date.now() - cached.timestamp < CACHE_TTL) {
898
- console.log("[AI Editor] Using cached suggestions");
899
- setSuggestions(cached.suggestions);
900
- return;
901
- }
902
- console.log("[AI Editor] Fetching new suggestions from API");
903
- setSuggestionsLoading(true);
904
- try {
905
- const params = new URLSearchParams({
906
- componentName: source.componentName
907
- });
908
- if ((_b = source.elementContext) == null ? void 0 : _b.tagName) {
909
- params.append("elementTag", source.elementContext.tagName);
910
- }
911
- if ((_c = source.elementContext) == null ? void 0 : _c.className) {
912
- params.append("className", source.elementContext.className);
913
- }
914
- if ((_d = source.elementContext) == null ? void 0 : _d.textContent) {
915
- params.append("textContent", source.elementContext.textContent);
916
- }
917
- if (lastEdit) {
918
- params.append("lastSuggestion", lastEdit);
919
- }
920
- if (history.length > 0) {
921
- params.append(
922
- "editHistory",
923
- JSON.stringify(
924
- history.slice(-3).map((h) => ({ suggestion: h.suggestion, success: h.success }))
925
- )
926
- );
927
- }
928
- if (excludedSuggestions && excludedSuggestions.length > 0) {
929
- params.append("excludedSuggestions", JSON.stringify(excludedSuggestions));
930
- }
931
- const response = await fetch(`/api/ai-editor/suggestions?${params}`);
932
- const data = await response.json();
933
- if (data.success) {
934
- setSuggestions(data.suggestions);
935
- setSuggestionsCache((prev) => {
936
- const newCache = new Map(prev);
937
- newCache.set(cacheKey, {
938
- suggestions: data.suggestions,
939
- timestamp: Date.now()
940
- });
941
- return newCache;
942
- });
943
- } else {
944
- setSuggestions([]);
945
- }
946
- } catch (error) {
947
- setSuggestions([]);
948
- } finally {
949
- setSuggestionsLoading(false);
950
- }
951
- },
952
- [suggestionsCache, setSuggestions, setSuggestionsLoading, setSuggestionsCache]
953
- );
954
- const handleSelect = useCallback(
955
- (element, source) => {
956
- setSelectedDOMElement(element);
957
- setSelectedSource(source);
958
- setEditHistory([]);
959
- setParentInstance(null);
960
- resolveSourceLocation(source).then((resolved) => {
961
- if (resolved) {
962
- setSelectedSource((prev) => prev === source ? resolved : prev);
963
- }
964
- });
965
- },
966
- [setSelectedDOMElement, setSelectedSource, setParentInstance]
967
- );
968
- if (process.env.NODE_ENV !== "development") {
969
- return /* @__PURE__ */ jsx(Fragment, { children });
970
- }
971
- return /* @__PURE__ */ jsxs(
972
- EditorContext.Provider,
973
- {
974
- value: {
975
- isEnabled,
976
- setEnabled,
977
- selectedSource,
978
- setSelectedSource,
979
- selectedDOMElement,
980
- isLoading,
981
- setIsLoading,
982
- editHistory,
983
- setEditHistory,
984
- submitEdit,
985
- suggestions,
986
- suggestionsLoading,
987
- lastAppliedSuggestion,
988
- setLastAppliedSuggestion,
989
- fetchSuggestions
990
- },
991
- children: [
992
- children,
993
- isEnabled && /* @__PURE__ */ jsx(
994
- EditorOverlay,
995
- {
996
- theme,
997
- onSelect: handleSelect,
998
- showStaleWarning,
999
- staleSession,
1000
- hasActiveSession,
1001
- setShowStaleWarning,
1002
- setStaleSession,
1003
- setHasActiveSession,
1004
- restoreSession,
1005
- handleClearSession,
1006
- parentInstance,
1007
- setParentInstance
1008
- }
1009
- )
1010
- ]
1011
- }
1012
- );
1013
- }
1014
- function EditorOverlay({
1015
- theme,
1016
- onSelect,
1017
- showStaleWarning,
1018
- staleSession,
1019
- hasActiveSession,
1020
- setShowStaleWarning,
1021
- setStaleSession,
1022
- setHasActiveSession,
1023
- restoreSession,
1024
- handleClearSession,
1025
- parentInstance,
1026
- setParentInstance
1027
- }) {
1028
- var _a;
1029
- const {
1030
- selectedSource,
1031
- setSelectedSource,
1032
- submitEdit,
1033
- isLoading,
1034
- setIsLoading,
1035
- setEnabled,
1036
- selectedDOMElement,
1037
- editHistory,
1038
- setEditHistory,
1039
- suggestions,
1040
- suggestionsLoading,
1041
- lastAppliedSuggestion,
1042
- setLastAppliedSuggestion,
1043
- fetchSuggestions
1044
- } = useAIEditor();
1045
- const [hoveredSource, setHoveredSource] = useState(
1046
- null
1047
- );
1048
- const [hoveredElement, setHoveredElement] = useState(null);
1049
- const [hoveredRect, setHoveredRect] = useState(null);
1050
- const [mousePos, setMousePos] = useState({ x: 0, y: 0 });
1051
- const [isResolvingSource, setIsResolvingSource] = useState(false);
1052
- const [suggestion, setSuggestion] = useState("");
1053
- const [result, setResult] = useState(null);
1054
- const [code, setCode] = useState("");
1055
- const [codeLineStart, setCodeLineStart] = useState(1);
1056
- const [targetStartLine, setTargetStartLine] = useState(null);
1057
- const [targetEndLine, setTargetEndLine] = useState(null);
1058
- const [absolutePath, setAbsolutePath] = useState(null);
1059
- const [parsedComponentName, setParsedComponentName] = useState(
1060
- null
1061
- );
1062
- const [isSourcePreviewExpanded, setIsSourcePreviewExpanded] = useState(false);
1063
- const [isParentPreviewExpanded, setIsParentPreviewExpanded] = useState(false);
1064
- const [isEditHistoryExpanded, setIsEditHistoryExpanded] = useState(true);
1065
- const isDark = theme === "dark";
1066
- const refreshCodePreview = useCallback(async (source, options = {}) => {
1067
- const params = buildReadQueryParams(source, options.includeParent ?? true);
1068
- try {
1069
- const response = await fetch(`/api/ai-editor/read?` + new URLSearchParams(params));
1070
- const data = await response.json();
1071
- if (data.success) {
1072
- setCode(data.content);
1073
- setCodeLineStart(data.lineStart || 1);
1074
- setTargetStartLine(data.targetStartLine || null);
1075
- setTargetEndLine(data.targetEndLine || null);
1076
- setParentInstance(data.parentInstance || null);
1077
- if (data.componentName) {
1078
- setParsedComponentName(data.componentName);
1079
- }
1080
- }
1081
- } catch (error) {
1082
- console.error("Error refreshing code preview:", error);
1083
- }
1084
- }, []);
1085
- useEffect(() => {
1086
- if (selectedSource) {
1087
- refreshCodePreview(selectedSource);
1088
- fetchSuggestions(selectedSource, []);
1089
- fetch(
1090
- `/api/ai-editor/absolute-path?` + new URLSearchParams({ path: selectedSource.filePath })
1091
- ).then((r) => r.json()).then((d) => d.success && setAbsolutePath(d.absolutePath)).catch(() => setAbsolutePath(null));
1092
- } else {
1093
- setAbsolutePath(null);
1094
- setParsedComponentName(null);
1095
- }
1096
- }, [selectedSource, refreshCodePreview]);
1097
- useEffect(() => {
1098
- let lastEl = null;
1099
- let raf;
1100
- const onMove = (e) => {
1101
- setMousePos({ x: e.clientX, y: e.clientY });
1102
- if (selectedSource) return;
1103
- cancelAnimationFrame(raf);
1104
- raf = requestAnimationFrame(() => {
1105
- const el = document.elementFromPoint(e.clientX, e.clientY);
1106
- if (!el || el.closest(".ai-editor-ui") || el === lastEl) return;
1107
- lastEl = el;
1108
- const source = getSourceFromElement(el);
1109
- if (source) {
1110
- setHoveredElement(el);
1111
- setHoveredRect(el.getBoundingClientRect());
1112
- const isCompiledPath = source.filePath.includes(".next/") || source.filePath.includes("/chunks/") || source.filePath.startsWith("file://") || source.filePath.endsWith(".js") && (source.filePath.includes("/server/") || source.filePath.includes("/static/"));
1113
- if (isCompiledPath && source.debugStack) {
1114
- setIsResolvingSource(true);
1115
- resolveSourceLocation(source).then((resolved) => {
1116
- setIsResolvingSource(false);
1117
- if (resolved) {
1118
- console.log("Resolved source location:", resolved);
1119
- setHoveredSource(resolved);
1120
- } else {
1121
- console.warn(
1122
- "Failed to resolve source location for:",
1123
- source
1124
- );
1125
- setHoveredSource(source);
1126
- }
1127
- }).catch((err) => {
1128
- console.error("Error resolving source location:", err);
1129
- setIsResolvingSource(false);
1130
- setHoveredSource(source);
1131
- });
1132
- } else if (isCompiledPath && !source.debugStack) {
1133
- console.warn("Compiled path but no debugStack:", source);
1134
- setIsResolvingSource(false);
1135
- setHoveredSource(source);
1136
- } else {
1137
- setIsResolvingSource(false);
1138
- setHoveredSource(source);
1139
- }
1140
- } else {
1141
- setHoveredSource(null);
1142
- setHoveredElement(null);
1143
- setHoveredRect(null);
1144
- setIsResolvingSource(false);
1145
- }
1146
- });
1147
- };
1148
- const onClick = (e) => {
1149
- if (e.target.closest(".ai-editor-ui")) return;
1150
- if (hoveredSource && hoveredElement) {
1151
- e.preventDefault();
1152
- e.stopPropagation();
1153
- onSelect(hoveredElement, hoveredSource);
1154
- setSuggestion("");
1155
- setResult(null);
1156
- }
1157
- };
1158
- document.addEventListener("mousemove", onMove, { passive: true });
1159
- document.addEventListener("click", onClick, true);
1160
- return () => {
1161
- document.removeEventListener("mousemove", onMove);
1162
- document.removeEventListener("click", onClick, true);
1163
- cancelAnimationFrame(raf);
1164
- };
1165
- }, [hoveredSource, hoveredElement, selectedSource, onSelect]);
1166
- const handleSubmit = async () => {
1167
- if (!suggestion.trim()) return;
1168
- const appliedSuggestion = suggestion;
1169
- const res = await submitEdit(suggestion);
1170
- setResult(res);
1171
- if (res.success) {
1172
- setSuggestion("");
1173
- setLastAppliedSuggestion(appliedSuggestion);
1174
- if (selectedSource) {
1175
- await new Promise((resolve) => setTimeout(resolve, 100));
1176
- await refreshCodePreview(selectedSource);
1177
- console.log("[AI Editor] Fetching suggestions after edit:", appliedSuggestion);
1178
- fetchSuggestions(selectedSource, editHistory, appliedSuggestion);
1179
- }
1180
- setTimeout(() => setResult(null), 3e3);
1181
- }
1182
- };
1183
- const handleUndo = async () => {
1184
- if (editHistory.length === 0 || !selectedSource) return;
1185
- const lastSuccessfulEdit = [...editHistory].reverse().find((edit) => edit.success && edit.fileSnapshot);
1186
- if (!lastSuccessfulEdit) {
1187
- console.warn("No successful edit with snapshot found to undo");
1188
- return;
1189
- }
1190
- const fileToRestore = lastSuccessfulEdit.editedFilePath || selectedSource.filePath;
1191
- console.log(`[Undo] Restoring file: ${fileToRestore}`);
1192
- setIsLoading(true);
1193
- try {
1194
- const response = await fetch("/api/ai-editor/undo", {
1195
- method: "POST",
1196
- headers: { "Content-Type": "application/json" },
1197
- body: JSON.stringify({
1198
- filePath: fileToRestore,
1199
- content: lastSuccessfulEdit.fileSnapshot
1200
- })
1201
- });
1202
- const result2 = await response.json();
1203
- if (!result2.success) {
1204
- throw new Error(result2.error || "Undo failed");
1205
- }
1206
- setEditHistory((prev) => {
1207
- const lastIndex = prev.lastIndexOf(lastSuccessfulEdit);
1208
- return prev.filter((_, idx) => idx !== lastIndex);
1209
- });
1210
- await refreshCodePreview(selectedSource);
1211
- setResult({ success: true, error: void 0 });
1212
- setTimeout(() => setResult(null), 3e3);
1213
- } catch (error) {
1214
- console.error("Undo error:", error);
1215
- setResult({ success: false, error: String(error) });
1216
- } finally {
1217
- setIsLoading(false);
1218
- }
1219
- };
1220
- const handleRetry = async (editIndex) => {
1221
- const editToRetry = editHistory[editIndex];
1222
- if (!editToRetry) return;
1223
- const res = await submitEdit(editToRetry.suggestion);
1224
- if (res.success && selectedSource) {
1225
- await new Promise((resolve) => setTimeout(resolve, 100));
1226
- await refreshCodePreview(selectedSource, { includeParent: false });
1227
- }
1228
- };
1229
- const handleUndoAndRetry = async () => {
1230
- if (editHistory.length === 0 || !selectedSource) return;
1231
- const lastSuccessfulEdit = [...editHistory].reverse().find((edit) => edit.success && edit.fileSnapshot);
1232
- if (!lastSuccessfulEdit) {
1233
- console.warn("No successful edit with snapshot found to undo and retry");
1234
- return;
1235
- }
1236
- const fileToRestore = lastSuccessfulEdit.editedFilePath || selectedSource.filePath;
1237
- console.log(`[Undo & Retry] Restoring file: ${fileToRestore}`);
1238
- setIsLoading(true);
1239
- try {
1240
- const undoResponse = await fetch("/api/ai-editor/undo", {
1241
- method: "POST",
1242
- headers: { "Content-Type": "application/json" },
1243
- body: JSON.stringify({
1244
- filePath: fileToRestore,
1245
- content: lastSuccessfulEdit.fileSnapshot
1246
- })
1247
- });
1248
- const undoResult = await undoResponse.json();
1249
- if (!undoResult.success) {
1250
- throw new Error(undoResult.error || "Undo failed");
1251
- }
1252
- setEditHistory((prev) => {
1253
- const lastIndex = prev.lastIndexOf(lastSuccessfulEdit);
1254
- return prev.filter((_, idx) => idx !== lastIndex);
1255
- });
1256
- await refreshCodePreview(selectedSource);
1257
- setIsLoading(true);
1258
- const retryResult = await submitEdit(lastSuccessfulEdit.suggestion);
1259
- if (retryResult.success && selectedSource) {
1260
- await new Promise((resolve) => setTimeout(resolve, 100));
1261
- await refreshCodePreview(selectedSource);
1262
- }
1263
- if (retryResult.success) {
1264
- setResult({ success: true, error: void 0 });
1265
- } else {
1266
- setResult({ success: false, error: retryResult.error });
1267
- }
1268
- setTimeout(() => setResult(null), 3e3);
1269
- } catch (error) {
1270
- console.error("Undo and retry error:", error);
1271
- setResult({ success: false, error: String(error) });
1272
- } finally {
1273
- setIsLoading(false);
1274
- }
1275
- };
1276
- const handleDone = () => {
1277
- window.location.reload();
1278
- };
1279
- const c = {
1280
- bg: isDark ? "#0d0d14" : "#fff",
1281
- bgAlt: isDark ? "#16162a" : "#f5f5f5",
1282
- text: isDark ? "#e4e4e7" : "#18181b",
1283
- muted: isDark ? "#71717a" : "#a1a1aa",
1284
- accent: "#818cf8",
1285
- border: isDark ? "#27273f" : "#e4e4e7",
1286
- success: "#34d399",
1287
- error: "#f87171"
1288
- };
1289
- const elCtx = selectedSource == null ? void 0 : selectedSource.elementContext;
1290
- return /* @__PURE__ */ jsxs(
1291
- "div",
1292
- {
1293
- className: "ai-editor-ui",
1294
- style: { fontFamily: "system-ui, sans-serif" },
1295
- children: [
1296
- /* @__PURE__ */ jsx("style", { children: `
1297
- @keyframes ai-editor-spin {
1298
- from { transform: rotate(0deg); }
1299
- to { transform: rotate(360deg); }
1300
- }
1301
- ` }),
1302
- hoveredRect && !selectedSource && /* @__PURE__ */ jsx(
1303
- "div",
1304
- {
1305
- style: {
1306
- position: "fixed",
1307
- left: hoveredRect.left - 2,
1308
- top: hoveredRect.top - 2,
1309
- width: hoveredRect.width + 4,
1310
- height: hoveredRect.height + 4,
1311
- border: `2px solid ${c.accent}`,
1312
- borderRadius: 6,
1313
- background: `${c.accent}15`,
1314
- pointerEvents: "none",
1315
- zIndex: 99998
1316
- }
1317
- }
1318
- ),
1319
- hoveredSource && !selectedSource && !isResolvingSource && /* @__PURE__ */ jsxs(
1320
- "div",
1321
- {
1322
- style: {
1323
- position: "fixed",
1324
- left: Math.min(mousePos.x + 14, window.innerWidth - 340),
1325
- top: mousePos.y + 14,
1326
- background: c.bg,
1327
- color: c.text,
1328
- border: `1px solid ${c.border}`,
1329
- borderRadius: 10,
1330
- padding: "12px 16px",
1331
- fontSize: 12,
1332
- fontFamily: "ui-monospace, monospace",
1333
- zIndex: 99999,
1334
- boxShadow: `0 8px 30px rgba(0,0,0,${isDark ? 0.5 : 0.15})`,
1335
- maxWidth: 320,
1336
- pointerEvents: "none"
1337
- },
1338
- children: [
1339
- /* @__PURE__ */ jsxs(
1340
- "div",
1341
- {
1342
- style: {
1343
- fontWeight: 700,
1344
- color: c.accent,
1345
- marginBottom: 4,
1346
- fontSize: 14
1347
- },
1348
- children: [
1349
- "<",
1350
- hoveredSource.componentName,
1351
- " />"
1352
- ]
1353
- }
1354
- ),
1355
- /* @__PURE__ */ jsxs("div", { style: { color: c.muted, fontSize: 11 }, children: [
1356
- hoveredSource.filePath,
1357
- ":",
1358
- hoveredSource.lineNumber
1359
- ] }),
1360
- ((_a = hoveredSource.elementContext) == null ? void 0 : _a.textContent) && /* @__PURE__ */ jsxs(
1361
- "div",
1362
- {
1363
- style: {
1364
- color: c.muted,
1365
- fontSize: 10,
1366
- marginTop: 4,
1367
- fontStyle: "italic"
1368
- },
1369
- children: [
1370
- '"',
1371
- hoveredSource.elementContext.textContent,
1372
- '"'
1373
- ]
1374
- }
1375
- )
1376
- ]
1377
- }
1378
- ),
1379
- ENABLE_SESSION_PERSISTENCE,
1380
- selectedSource && /* @__PURE__ */ jsxs(
1381
- "div",
1382
- {
1383
- style: {
1384
- position: "fixed",
1385
- bottom: 20,
1386
- right: 20,
1387
- background: c.bg,
1388
- color: c.text,
1389
- borderRadius: 16,
1390
- padding: 24,
1391
- width: 560,
1392
- maxWidth: "calc(100vw - 40px)",
1393
- maxHeight: "calc(100vh - 40px)",
1394
- overflowY: "auto",
1395
- overflowX: "hidden",
1396
- zIndex: 1e5,
1397
- boxShadow: `0 24px 80px rgba(0,0,0,${isDark ? 0.6 : 0.25})`,
1398
- border: `1px solid ${c.border}`
1399
- },
1400
- children: [
1401
- /* @__PURE__ */ jsxs(
1402
- "div",
1403
- {
1404
- style: {
1405
- display: "flex",
1406
- justifyContent: "space-between",
1407
- marginBottom: 20
1408
- },
1409
- children: [
1410
- /* @__PURE__ */ jsxs("div", { children: [
1411
- /* @__PURE__ */ jsx(
1412
- "div",
1413
- {
1414
- style: {
1415
- fontSize: 11,
1416
- textTransform: "uppercase",
1417
- letterSpacing: 1,
1418
- color: c.muted
1419
- },
1420
- children: "Editing"
1421
- }
1422
- ),
1423
- /* @__PURE__ */ jsxs("div", { style: { fontSize: 20, fontWeight: 700, color: c.accent }, children: [
1424
- "<",
1425
- parsedComponentName || selectedSource.componentName,
1426
- " />"
1427
- ] }),
1428
- /* @__PURE__ */ jsx(
1429
- "div",
1430
- {
1431
- style: {
1432
- fontSize: 12,
1433
- color: c.muted,
1434
- fontFamily: "monospace",
1435
- marginTop: 4
1436
- },
1437
- children: /* @__PURE__ */ jsxs(
1438
- "a",
1439
- {
1440
- href: absolutePath ? `cursor://file/${absolutePath}:${selectedSource.lineNumber}` : `cursor://file/${selectedSource.filePath}:${selectedSource.lineNumber}`,
1441
- onClick: (e) => {
1442
- e.preventDefault();
1443
- e.stopPropagation();
1444
- const path = absolutePath || selectedSource.filePath;
1445
- const cursorPath = path.startsWith("/") ? path : `/${path}`;
1446
- window.location.href = `cursor://file${cursorPath}:${selectedSource.lineNumber}`;
1447
- },
1448
- style: {
1449
- color: c.accent,
1450
- textDecoration: "none",
1451
- cursor: "pointer",
1452
- borderBottom: `1px solid ${c.accent}40`
1453
- },
1454
- onMouseEnter: (e) => {
1455
- e.currentTarget.style.borderBottomColor = c.accent;
1456
- },
1457
- onMouseLeave: (e) => {
1458
- e.currentTarget.style.borderBottomColor = `${c.accent}40`;
1459
- },
1460
- children: [
1461
- selectedSource.filePath,
1462
- ":",
1463
- selectedSource.lineNumber
1464
- ]
1465
- }
1466
- )
1467
- }
1468
- ),
1469
- (elCtx == null ? void 0 : elCtx.textContent) && /* @__PURE__ */ jsxs(
1470
- "div",
1471
- {
1472
- style: {
1473
- fontSize: 11,
1474
- color: c.muted,
1475
- marginTop: 4,
1476
- fontStyle: "italic"
1477
- },
1478
- children: [
1479
- 'Element text: "',
1480
- elCtx.textContent,
1481
- '"'
1482
- ]
1483
- }
1484
- )
1485
- ] }),
1486
- /* @__PURE__ */ jsx(
1487
- "button",
1488
- {
1489
- onClick: () => setSelectedSource(null),
1490
- style: {
1491
- width: 36,
1492
- height: 36,
1493
- borderRadius: 10,
1494
- border: "none",
1495
- background: c.bgAlt,
1496
- color: c.muted,
1497
- fontSize: 20,
1498
- cursor: "pointer"
1499
- },
1500
- children: "×"
1501
- }
1502
- )
1503
- ]
1504
- }
1505
- ),
1506
- code && /* @__PURE__ */ jsxs("div", { style: { marginBottom: 20 }, children: [
1507
- /* @__PURE__ */ jsxs(
1508
- "button",
1509
- {
1510
- onClick: () => setIsSourcePreviewExpanded(!isSourcePreviewExpanded),
1511
- style: {
1512
- fontSize: 11,
1513
- fontWeight: 600,
1514
- marginBottom: 8,
1515
- color: c.muted,
1516
- textTransform: "uppercase",
1517
- background: "transparent",
1518
- border: "none",
1519
- padding: 0,
1520
- cursor: "pointer",
1521
- display: "flex",
1522
- alignItems: "center",
1523
- gap: 6
1524
- },
1525
- children: [
1526
- /* @__PURE__ */ jsx("span", { style: { fontSize: 10 }, children: isSourcePreviewExpanded ? "▼" : "▶" }),
1527
- "Source Preview"
1528
- ]
1529
- }
1530
- ),
1531
- isSourcePreviewExpanded && /* @__PURE__ */ jsx(
1532
- Prism,
1533
- {
1534
- language: "tsx",
1535
- style: isDark ? vscDarkPlus : vs,
1536
- showLineNumbers: true,
1537
- startingLineNumber: codeLineStart,
1538
- customStyle: {
1539
- background: c.bgAlt,
1540
- borderRadius: 10,
1541
- fontSize: 14,
1542
- margin: 0,
1543
- maxHeight: 180,
1544
- overflowX: "auto",
1545
- border: `1px solid ${c.border}`
1546
- },
1547
- lineNumberStyle: {
1548
- minWidth: "2.5em",
1549
- paddingRight: "1em",
1550
- color: c.muted,
1551
- textAlign: "right",
1552
- userSelect: "none"
1553
- },
1554
- wrapLines: true,
1555
- lineProps: (lineNumber) => {
1556
- const isHighlighted = targetStartLine !== null && targetEndLine !== null && lineNumber >= targetStartLine && lineNumber <= targetEndLine;
1557
- return {
1558
- style: {
1559
- backgroundColor: isHighlighted ? isDark ? "rgba(102, 126, 234, 0.15)" : "rgba(147, 197, 253, 0.3)" : "transparent"
1560
- }
1561
- };
1562
- },
1563
- children: code
1564
- }
1565
- )
1566
- ] }),
1567
- parentInstance && /* @__PURE__ */ jsxs("div", { style: { marginBottom: 20 }, children: [
1568
- /* @__PURE__ */ jsxs(
1569
- "button",
1570
- {
1571
- onClick: () => setIsParentPreviewExpanded(!isParentPreviewExpanded),
1572
- style: {
1573
- fontSize: 11,
1574
- fontWeight: 600,
1575
- marginBottom: 8,
1576
- color: c.muted,
1577
- textTransform: "uppercase",
1578
- background: "transparent",
1579
- border: "none",
1580
- padding: 0,
1581
- cursor: "pointer",
1582
- display: "flex",
1583
- alignItems: "center",
1584
- gap: 6
1585
- },
1586
- children: [
1587
- /* @__PURE__ */ jsx("span", { style: { fontSize: 10 }, children: isParentPreviewExpanded ? "▼" : "▶" }),
1588
- "Used In: ",
1589
- parentInstance.componentName,
1590
- " (",
1591
- parentInstance.filePath,
1592
- ")"
1593
- ]
1594
- }
1595
- ),
1596
- isParentPreviewExpanded && /* @__PURE__ */ jsx(
1597
- Prism,
1598
- {
1599
- language: "tsx",
1600
- style: isDark ? vscDarkPlus : vs,
1601
- showLineNumbers: true,
1602
- startingLineNumber: parentInstance.lineStart,
1603
- customStyle: {
1604
- background: c.bgAlt,
1605
- borderRadius: 10,
1606
- fontSize: 14,
1607
- margin: 0,
1608
- maxHeight: 180,
1609
- overflowX: "auto",
1610
- border: `1px solid ${c.border}`
1611
- },
1612
- lineNumberStyle: {
1613
- minWidth: "2.5em",
1614
- paddingRight: "1em",
1615
- color: c.muted,
1616
- textAlign: "right",
1617
- userSelect: "none"
1618
- },
1619
- wrapLines: true,
1620
- lineProps: (lineNumber) => {
1621
- const isUsageLine = lineNumber >= parentInstance.usageLineStart && lineNumber <= parentInstance.usageLineEnd;
1622
- return {
1623
- style: {
1624
- backgroundColor: isUsageLine ? isDark ? "rgba(255, 165, 0, 0.15)" : "rgba(255, 165, 0, 0.2)" : "transparent"
1625
- }
1626
- };
1627
- },
1628
- children: parentInstance.content
1629
- }
1630
- )
1631
- ] }),
1632
- editHistory.length > 0 && /* @__PURE__ */ jsxs("div", { style: { marginBottom: 20 }, children: [
1633
- /* @__PURE__ */ jsxs(
1634
- "button",
1635
- {
1636
- onClick: () => setIsEditHistoryExpanded(!isEditHistoryExpanded),
1637
- style: {
1638
- fontSize: 11,
1639
- fontWeight: 600,
1640
- marginBottom: 8,
1641
- color: c.muted,
1642
- textTransform: "uppercase",
1643
- background: "transparent",
1644
- border: "none",
1645
- padding: 0,
1646
- cursor: "pointer",
1647
- display: "flex",
1648
- alignItems: "center",
1649
- gap: 6
1650
- },
1651
- children: [
1652
- /* @__PURE__ */ jsx("span", { style: { fontSize: 10 }, children: isEditHistoryExpanded ? "▼" : "▶" }),
1653
- "Edit History (",
1654
- editHistory.length,
1655
- ")"
1656
- ]
1657
- }
1658
- ),
1659
- isEditHistoryExpanded && /* @__PURE__ */ jsx(
1660
- "div",
1661
- {
1662
- style: {
1663
- background: c.bgAlt,
1664
- borderRadius: 10,
1665
- border: `1px solid ${c.border}`,
1666
- maxHeight: 200,
1667
- overflow: "auto"
1668
- },
1669
- children: editHistory.map((item, idx) => {
1670
- const isLastEdit = idx === editHistory.length - 1;
1671
- const hasSnapshot = item.success && item.fileSnapshot;
1672
- return /* @__PURE__ */ jsx(
1673
- "div",
1674
- {
1675
- style: {
1676
- padding: "10px 14px",
1677
- borderBottom: idx < editHistory.length - 1 ? `1px solid ${c.border}` : "none"
1678
- },
1679
- children: /* @__PURE__ */ jsxs(
1680
- "div",
1681
- {
1682
- style: {
1683
- display: "flex",
1684
- alignItems: "flex-start",
1685
- gap: 8
1686
- },
1687
- children: [
1688
- /* @__PURE__ */ jsxs("div", { style: { flex: 1 }, children: [
1689
- /* @__PURE__ */ jsxs(
1690
- "div",
1691
- {
1692
- style: {
1693
- display: "flex",
1694
- alignItems: "center",
1695
- gap: 8,
1696
- marginBottom: 4
1697
- },
1698
- children: [
1699
- item.pending ? /* @__PURE__ */ jsx(
1700
- "div",
1701
- {
1702
- style: {
1703
- width: 16,
1704
- height: 16,
1705
- border: "2px solid transparent",
1706
- borderTopColor: c.accent,
1707
- borderRadius: "50%",
1708
- animation: "ai-editor-spin 0.8s linear infinite"
1709
- }
1710
- }
1711
- ) : /* @__PURE__ */ jsx(
1712
- "span",
1713
- {
1714
- style: {
1715
- color: item.success ? c.success : c.error,
1716
- fontSize: 16
1717
- },
1718
- children: item.success ? "✓" : "✗"
1719
- }
1720
- ),
1721
- /* @__PURE__ */ jsxs(
1722
- "span",
1723
- {
1724
- style: {
1725
- fontSize: 11,
1726
- color: c.muted
1727
- },
1728
- children: [
1729
- "Edit ",
1730
- idx + 1
1731
- ]
1732
- }
1733
- )
1734
- ]
1735
- }
1736
- ),
1737
- /* @__PURE__ */ jsx(
1738
- "div",
1739
- {
1740
- style: {
1741
- fontSize: 13,
1742
- color: c.text,
1743
- marginLeft: 24
1744
- },
1745
- children: item.suggestion
1746
- }
1747
- ),
1748
- item.error && /* @__PURE__ */ jsx(
1749
- "div",
1750
- {
1751
- style: {
1752
- fontSize: 11,
1753
- color: c.error,
1754
- marginLeft: 24,
1755
- marginTop: 4
1756
- },
1757
- children: item.error
1758
- }
1759
- )
1760
- ] }),
1761
- /* @__PURE__ */ jsxs("div", { style: { display: "flex", gap: 6, flexWrap: "wrap" }, children: [
1762
- isLastEdit && hasSnapshot && !item.pending && /* @__PURE__ */ jsxs(Fragment, { children: [
1763
- /* @__PURE__ */ jsx(
1764
- "button",
1765
- {
1766
- onClick: handleUndo,
1767
- disabled: isLoading,
1768
- style: {
1769
- padding: "4px 10px",
1770
- fontSize: 11,
1771
- borderRadius: 6,
1772
- border: "none",
1773
- background: isLoading ? c.muted : "#f59e0b",
1774
- color: "#fff",
1775
- fontWeight: 600,
1776
- cursor: isLoading ? "wait" : "pointer",
1777
- whiteSpace: "nowrap"
1778
- },
1779
- title: "Undo this edit",
1780
- onMouseEnter: (e) => {
1781
- if (!isLoading)
1782
- e.currentTarget.style.background = "#d97706";
1783
- },
1784
- onMouseLeave: (e) => {
1785
- if (!isLoading)
1786
- e.currentTarget.style.background = "#f59e0b";
1787
- },
1788
- children: "↶ Undo"
1789
- }
1790
- ),
1791
- /* @__PURE__ */ jsx(
1792
- "button",
1793
- {
1794
- onClick: handleUndoAndRetry,
1795
- disabled: isLoading,
1796
- style: {
1797
- padding: "4px 10px",
1798
- fontSize: 11,
1799
- borderRadius: 6,
1800
- border: "none",
1801
- background: isLoading ? c.muted : "#8b5cf6",
1802
- color: "#fff",
1803
- fontWeight: 600,
1804
- cursor: isLoading ? "wait" : "pointer",
1805
- whiteSpace: "nowrap"
1806
- },
1807
- title: "Undo and retry with AI",
1808
- onMouseEnter: (e) => {
1809
- if (!isLoading)
1810
- e.currentTarget.style.background = "#7c3aed";
1811
- },
1812
- onMouseLeave: (e) => {
1813
- if (!isLoading)
1814
- e.currentTarget.style.background = "#8b5cf6";
1815
- },
1816
- children: "↶↻ Undo & Retry"
1817
- }
1818
- )
1819
- ] }),
1820
- /* @__PURE__ */ jsx(
1821
- "button",
1822
- {
1823
- onClick: () => handleRetry(idx),
1824
- disabled: isLoading || item.pending,
1825
- style: {
1826
- padding: "4px 10px",
1827
- fontSize: 11,
1828
- borderRadius: 6,
1829
- border: "none",
1830
- background: isLoading || item.pending ? c.muted : c.accent,
1831
- color: "#fff",
1832
- fontWeight: 600,
1833
- cursor: isLoading || item.pending ? "wait" : "pointer",
1834
- whiteSpace: "nowrap"
1835
- },
1836
- title: "Retry this edit",
1837
- onMouseEnter: (e) => {
1838
- if (!isLoading && !item.pending)
1839
- e.currentTarget.style.background = "#6366f1";
1840
- },
1841
- onMouseLeave: (e) => {
1842
- if (!isLoading && !item.pending)
1843
- e.currentTarget.style.background = c.accent;
1844
- },
1845
- children: "↻ Retry"
1846
- }
1847
- )
1848
- ] })
1849
- ]
1850
- }
1851
- )
1852
- },
1853
- idx
1854
- );
1855
- })
1856
- }
1857
- )
1858
- ] }),
1859
- /* @__PURE__ */ jsxs("div", { style: { marginBottom: 20 }, children: [
1860
- /* @__PURE__ */ jsx(
1861
- "div",
1862
- {
1863
- style: {
1864
- fontSize: 11,
1865
- fontWeight: 600,
1866
- marginBottom: 8,
1867
- color: c.muted,
1868
- textTransform: "uppercase"
1869
- },
1870
- children: "Describe Changes"
1871
- }
1872
- ),
1873
- /* @__PURE__ */ jsx(
1874
- "textarea",
1875
- {
1876
- value: suggestion,
1877
- onChange: (e) => setSuggestion(e.target.value),
1878
- placeholder: `e.g., Make this ${(elCtx == null ? void 0 : elCtx.tagName) || "element"} blue with rounded corners...`,
1879
- autoFocus: true,
1880
- style: {
1881
- width: "100%",
1882
- height: 100,
1883
- padding: 14,
1884
- borderRadius: 10,
1885
- border: `1px solid ${c.border}`,
1886
- background: c.bgAlt,
1887
- color: c.text,
1888
- fontSize: 14,
1889
- resize: "vertical",
1890
- fontFamily: "inherit",
1891
- boxSizing: "border-box"
1892
- },
1893
- onKeyDown: (e) => {
1894
- if (e.key === "Enter" && (e.metaKey || e.ctrlKey)) {
1895
- e.preventDefault();
1896
- handleSubmit();
1897
- }
1898
- }
1899
- }
1900
- )
1901
- ] }),
1902
- (suggestions.length > 0 || suggestionsLoading) && /* @__PURE__ */ jsxs("div", { style: { marginBottom: 20 }, children: [
1903
- /* @__PURE__ */ jsxs(
1904
- "div",
1905
- {
1906
- style: {
1907
- fontSize: 11,
1908
- fontWeight: 600,
1909
- marginBottom: 8,
1910
- color: c.muted,
1911
- textTransform: "uppercase",
1912
- display: "flex",
1913
- alignItems: "center",
1914
- gap: 8
1915
- },
1916
- children: [
1917
- "Quick Suggestions",
1918
- suggestionsLoading ? /* @__PURE__ */ jsx(
1919
- "div",
1920
- {
1921
- style: {
1922
- width: 12,
1923
- height: 12,
1924
- border: "2px solid transparent",
1925
- borderTopColor: c.accent,
1926
- borderRadius: "50%",
1927
- animation: "ai-editor-spin 0.8s linear infinite"
1928
- }
1929
- }
1930
- ) : suggestions.length > 0 && selectedSource && /* @__PURE__ */ jsx(
1931
- "button",
1932
- {
1933
- onClick: () => {
1934
- console.log("[AI Editor] Refreshing suggestions, excluding:", suggestions);
1935
- fetchSuggestions(selectedSource, editHistory, lastAppliedSuggestion, suggestions);
1936
- },
1937
- disabled: isLoading,
1938
- style: {
1939
- background: "transparent",
1940
- border: "none",
1941
- padding: 4,
1942
- cursor: isLoading ? "wait" : "pointer",
1943
- color: c.muted,
1944
- fontSize: 14,
1945
- display: "flex",
1946
- alignItems: "center",
1947
- transition: "all 0.15s ease"
1948
- },
1949
- onMouseEnter: (e) => {
1950
- if (!isLoading) {
1951
- e.currentTarget.style.color = c.accent;
1952
- e.currentTarget.style.transform = "rotate(180deg)";
1953
- }
1954
- },
1955
- onMouseLeave: (e) => {
1956
- if (!isLoading) {
1957
- e.currentTarget.style.color = c.muted;
1958
- e.currentTarget.style.transform = "rotate(0deg)";
1959
- }
1960
- },
1961
- title: "Get different suggestions",
1962
- children: "↻"
1963
- }
1964
- )
1965
- ]
1966
- }
1967
- ),
1968
- /* @__PURE__ */ jsx(
1969
- "div",
1970
- {
1971
- style: {
1972
- display: "flex",
1973
- flexWrap: "wrap",
1974
- gap: 8
1975
- },
1976
- children: suggestionsLoading ? (
1977
- // Loading skeletons
1978
- Array.from({ length: 6 }).map((_, idx) => /* @__PURE__ */ jsx(
1979
- "div",
1980
- {
1981
- style: {
1982
- padding: "8px 14px",
1983
- borderRadius: 8,
1984
- background: c.bgAlt,
1985
- border: `1px solid ${c.border}`,
1986
- fontSize: 13,
1987
- height: 34,
1988
- width: Math.random() * 60 + 80,
1989
- // Variable width
1990
- opacity: 0.5
1991
- }
1992
- },
1993
- idx
1994
- ))
1995
- ) : suggestions.map((suggestionText, idx) => /* @__PURE__ */ jsx(
1996
- "button",
1997
- {
1998
- onClick: (e) => {
1999
- if (e.metaKey || e.ctrlKey) {
2000
- setSuggestion(suggestionText);
2001
- setTimeout(() => handleSubmit(), 50);
2002
- } else {
2003
- setSuggestion(suggestionText);
2004
- }
2005
- },
2006
- disabled: isLoading,
2007
- style: {
2008
- padding: "8px 14px",
2009
- borderRadius: 8,
2010
- border: `1px solid ${c.border}`,
2011
- background: c.bgAlt,
2012
- color: c.text,
2013
- fontSize: 13,
2014
- cursor: isLoading ? "wait" : "pointer",
2015
- transition: "all 0.15s ease",
2016
- whiteSpace: "nowrap"
2017
- },
2018
- onMouseEnter: (e) => {
2019
- if (!isLoading) {
2020
- e.currentTarget.style.background = c.accent + "20";
2021
- e.currentTarget.style.borderColor = c.accent;
2022
- e.currentTarget.style.transform = "translateY(-1px)";
2023
- }
2024
- },
2025
- onMouseLeave: (e) => {
2026
- if (!isLoading) {
2027
- e.currentTarget.style.background = c.bgAlt;
2028
- e.currentTarget.style.borderColor = c.border;
2029
- e.currentTarget.style.transform = "translateY(0)";
2030
- }
2031
- },
2032
- title: "Click to use • Cmd+Click to apply immediately",
2033
- children: suggestionText
2034
- },
2035
- idx
2036
- ))
2037
- }
2038
- )
2039
- ] }),
2040
- result && /* @__PURE__ */ jsx(
2041
- "div",
2042
- {
2043
- style: {
2044
- marginBottom: 20,
2045
- padding: 14,
2046
- borderRadius: 10,
2047
- background: result.success ? `${c.success}15` : `${c.error}15`,
2048
- color: result.success ? c.success : c.error,
2049
- fontWeight: 500
2050
- },
2051
- children: result.success ? "✓ Applied!" : `✗ ${result.error}`
2052
- }
2053
- ),
2054
- /* @__PURE__ */ jsxs("div", { style: { display: "flex", gap: 12, flexWrap: "wrap" }, children: [
2055
- /* @__PURE__ */ jsx(
2056
- "button",
2057
- {
2058
- onClick: () => setSelectedSource(null),
2059
- style: {
2060
- flex: "1 1 auto",
2061
- padding: "12px 20px",
2062
- borderRadius: 10,
2063
- border: `1px solid ${c.border}`,
2064
- background: "transparent",
2065
- color: c.text,
2066
- cursor: "pointer"
2067
- },
2068
- children: "Cancel"
2069
- }
2070
- ),
2071
- ENABLE_SESSION_PERSISTENCE,
2072
- editHistory.length > 0 && /* @__PURE__ */ jsx(
2073
- "button",
2074
- {
2075
- onClick: handleDone,
2076
- style: {
2077
- flex: "1 1 auto",
2078
- padding: "12px 20px",
2079
- borderRadius: 10,
2080
- border: `1px solid ${c.success}`,
2081
- background: "transparent",
2082
- color: c.success,
2083
- fontWeight: 600,
2084
- cursor: "pointer"
2085
- },
2086
- children: "Finish & Reload"
2087
- }
2088
- ),
2089
- /* @__PURE__ */ jsx(
2090
- "button",
2091
- {
2092
- onClick: handleSubmit,
2093
- disabled: isLoading || !suggestion.trim(),
2094
- style: {
2095
- flex: "2 1 auto",
2096
- padding: "12px 20px",
2097
- borderRadius: 10,
2098
- border: "none",
2099
- background: isLoading ? c.muted : c.accent,
2100
- color: "#fff",
2101
- fontWeight: 600,
2102
- cursor: isLoading ? "wait" : "pointer",
2103
- opacity: !suggestion.trim() ? 0.5 : 1
2104
- },
2105
- children: isLoading ? "Applying..." : "Apply Changes ⌘↵"
2106
- }
2107
- )
2108
- ] })
2109
- ]
2110
- }
2111
- ),
2112
- !selectedSource && /* @__PURE__ */ jsxs(
2113
- "div",
2114
- {
2115
- style: {
2116
- position: "fixed",
2117
- bottom: 20,
2118
- right: 20,
2119
- background: c.bg,
2120
- color: c.success,
2121
- padding: "10px 16px",
2122
- borderRadius: 20,
2123
- fontSize: 13,
2124
- fontWeight: 600,
2125
- zIndex: 99997,
2126
- display: "flex",
2127
- alignItems: "center",
2128
- gap: 8,
2129
- border: `1px solid ${c.border}`,
2130
- boxShadow: `0 4px 20px rgba(0,0,0,${isDark ? 0.4 : 0.1})`
2131
- },
2132
- children: [
2133
- /* @__PURE__ */ jsx(
2134
- "span",
2135
- {
2136
- style: {
2137
- width: 8,
2138
- height: 8,
2139
- borderRadius: "50%",
2140
- background: c.success
2141
- }
2142
- }
2143
- ),
2144
- "AI Editor",
2145
- /* @__PURE__ */ jsx("span", { style: { color: c.muted, fontSize: 11 }, children: "⌘⇧E" }),
2146
- ENABLE_SESSION_PERSISTENCE,
2147
- /* @__PURE__ */ jsx(
2148
- "button",
2149
- {
2150
- onClick: () => setEnabled(false),
2151
- style: {
2152
- background: "none",
2153
- border: "none",
2154
- color: c.muted,
2155
- cursor: "pointer"
2156
- },
2157
- children: "×"
2158
- }
2159
- )
2160
- ]
2161
- }
2162
- )
2163
- ]
2164
- }
2165
- );
2166
- }
2167
- export {
2168
- AIEditorProvider as A
2169
- };
2170
- //# sourceMappingURL=AIEditorProvider-CFFnEtEB.js.map