Skip to content

Commit 6737d6d

Browse files
committed
Add better script tracking
1 parent 03267bc commit 6737d6d

File tree

6 files changed

+455
-427
lines changed

6 files changed

+455
-427
lines changed

src/ai_dom_editor/editor/ai_dom_editor.js

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -53,10 +53,10 @@ class AIDOMEditor {
5353
});
5454
}
5555

56-
setCurrentScript(scriptName) {
57-
if (scriptName) {
58-
this.currentScript = { name: scriptName };
59-
this.elements.currentScriptName.textContent = scriptName;
56+
setCurrentScript(script) {
57+
if (script) {
58+
this.currentScript = script;
59+
this.elements.currentScriptName.textContent = script.name;
6060
this.elements.currentScriptDisplay.style.display = "flex";
6161
this.elements.headerTitle.style.display = "none";
6262
} else {
@@ -91,7 +91,7 @@ class AIDOMEditor {
9191

9292
if (this.currentScript) {
9393
await chrome.storage.local.set({
94-
[storageKey]: this.currentScript.name,
94+
[storageKey]: this.currentScript,
9595
});
9696
} else {
9797
await chrome.storage.local.remove(storageKey);
@@ -113,16 +113,16 @@ class AIDOMEditor {
113113
const siteUrl = `${url.protocol}//${url.hostname}`;
114114
const storageKey = `aiCurrentScript_${siteUrl}`;
115115

116-
const { [storageKey]: scriptName } = await chrome.storage.local.get(
116+
const { [storageKey]: script } = await chrome.storage.local.get(
117117
storageKey
118118
);
119-
if (scriptName) {
119+
if (script) {
120120
// Verify the script actually exists before restoring
121121
const { scripts = [] } = await chrome.storage.local.get("scripts");
122-
const scriptExists = scripts.some((s) => s.name === scriptName);
122+
const scriptExists = scripts.some((s) => s.id === script.id);
123123

124124
if (scriptExists) {
125-
this.setCurrentScript(scriptName);
125+
this.setCurrentScript(script);
126126
} else {
127127
// Script doesn't exist anymore, clear the stored state
128128
await chrome.storage.local.remove(storageKey);

src/ai_dom_editor/editor/helpers/api_handler.js

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -241,6 +241,13 @@ export class ApiHandler {
241241
return content.trim();
242242
}
243243

244+
// Extract script name from content
245+
_extractScriptName(content) {
246+
if (!content || typeof content !== 'string') return null;
247+
const match = content.match(/Script Name:\s*(.+?)(?=\n|$)/i);
248+
return match && match[1] ? match[1].trim() : null;
249+
}
250+
244251
// Primary method to call AI APIs. Returns { type: 'script', code: '...' }
245252
async callAIAPI(userMessage, domSummary, previousCode = null) {
246253

@@ -260,6 +267,7 @@ The user wants to modify the above script.
260267

261268
systemPrompt += `
262269
Your task is to generate JavaScript code to modify the page based on the user's request.
270+
- Provide a concise, descriptive name for the script in the format "Script Name: [Your Script Name]".
263271
- Use specific selectors. Prefer IDs, then classes, then tags.
264272
- You can use Greasemonkey APIs: GM_addStyle, GM_setValue, GM_getValue, GM_deleteValue, GM_listValues, GM_xmlhttpRequest, GM_notification, GM_addElement, GM_registerMenuCommand, GM_openInTab, GM_setClipboard, GM_download, GM_getResourceText, unsafeWindow.
265273
- Write immediately executable code.
@@ -402,10 +410,12 @@ Your response is only the JavaScript code.`;
402410
}
403411

404412
const code = this._extractCode(content);
413+
const scriptName = this._extractScriptName(content);
405414

406415
return {
407416
type: 'script',
408-
code: code
417+
code: code,
418+
name: scriptName
409419
};
410420
} catch (err) {
411421
console.error('AI API Error:', err);

src/ai_dom_editor/editor/helpers/event_handler.js

Lines changed: 9 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -127,20 +127,20 @@ export class EventHandler {
127127
const textAfterAt = message.substring(atIndex + 1);
128128
let matchedScript = null;
129129

130-
for (const scriptName of allScripts) {
131-
if (textAfterAt.startsWith(scriptName)) {
132-
if (!matchedScript || scriptName.length > matchedScript.length) {
133-
matchedScript = scriptName;
130+
for (const script of allScripts) {
131+
if (textAfterAt.startsWith(script.name)) {
132+
if (!matchedScript || script.name.length > matchedScript.name.length) {
133+
matchedScript = script;
134134
}
135135
}
136136
}
137137

138138
if (matchedScript) {
139139
try {
140-
const fullCode = await this.editor.userscriptHandler.getScriptContent(matchedScript);
140+
const fullCode = await this.editor.userscriptHandler.getScriptContent(matchedScript.name);
141141
previousCode = ScriptAnalyzer.extractCodeFromIIFE(fullCode);
142142
this.editor.setCurrentScript(matchedScript);
143-
const promptWithoutScriptRef = message.substring(0, atIndex) + textAfterAt.substring(matchedScript.length);
143+
const promptWithoutScriptRef = message.substring(0, atIndex) + textAfterAt.substring(matchedScript.name.length);
144144
userMessage = promptWithoutScriptRef.trim();
145145
} catch (error) {
146146
this.editor.chatManager.addMessage('assistant', `Error: ${error.message}`);
@@ -170,10 +170,11 @@ export class EventHandler {
170170
code: JSON.stringify(response, null, 2),
171171
actions: response
172172
});
173-
} else if (response.type === 'script' && response.code) {
173+
} else if (response.type === 'script') {
174174
this.editor.chatManager.addMessage('assistant', 'I\'ve generated this code for you:', {
175175
code: response.code,
176-
isScript: true
176+
isScript: true,
177+
name: response.name
177178
});
178179
} else {
179180
this.editor.chatManager.addMessage('assistant', 'Unexpected response format from AI', { error: true });

src/ai_dom_editor/editor/helpers/ui_manager.js

Lines changed: 13 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -46,7 +46,9 @@ export class UIManager {
4646
const editLink = document.createElement("a");
4747
editLink.className = "btn-text icon-btn";
4848
editLink.title = "Open in editor";
49-
editLink.href = chrome.runtime.getURL("editor/editor.html");
49+
editLink.href = `${chrome.runtime.getURL(
50+
"editor/editor.html"
51+
)}?id=${this.editor.currentScript.id}`;
5052
editLink.target = "_blank";
5153
editLink.innerHTML = `<i data-feather="edit-2" width="16" height="16"></i>`;
5254
// Insert before the action button
@@ -148,7 +150,8 @@ export class UIManager {
148150
const codePreview = this.createCodePreview(
149151
data.code,
150152
data.actions,
151-
data.isScript
153+
data.isScript,
154+
data.name
152155
);
153156
content.appendChild(codePreview);
154157
}
@@ -157,7 +160,7 @@ export class UIManager {
157160
return messageEl;
158161
}
159162

160-
createCodePreview(code, actions, isScript) {
163+
createCodePreview(code, actions, isScript, name) {
161164
const preview = document.createElement("div");
162165
preview.className = "code-preview";
163166

@@ -193,7 +196,9 @@ export class UIManager {
193196
const editLink = document.createElement("a");
194197
editLink.className = "btn-text icon-btn";
195198
editLink.title = "Open in editor";
196-
editLink.href = chrome.runtime.getURL("editor/editor.html");
199+
editLink.href = `${chrome.runtime.getURL("editor/editor.html")}?id=${
200+
this.editor.currentScript.id
201+
}`;
197202
editLink.target = "_blank";
198203
editLink.innerHTML = `<i data-feather="edit-2" width="16" height="16"></i>`;
199204
actionsDiv.appendChild(editLink);
@@ -222,7 +227,7 @@ export class UIManager {
222227
code
223228
);
224229
} else {
225-
this.editor.userscriptHandler.createUserscript(code);
230+
this.editor.userscriptHandler.createUserscript(code, name);
226231
}
227232
});
228233

@@ -331,13 +336,13 @@ export class UIManager {
331336
const selector = document.createElement("div");
332337
selector.className = "script-selector";
333338

334-
scripts.forEach((scriptName) => {
339+
scripts.forEach((script) => {
335340
const item = document.createElement("div");
336341
item.className = "script-item";
337-
item.textContent = scriptName;
342+
item.textContent = script.name;
338343
item.addEventListener("click", () => {
339344
const atIndex = input.value.lastIndexOf("@");
340-
input.value = input.value.substring(0, atIndex + 1) + scriptName + " ";
345+
input.value = input.value.substring(0, atIndex + 1) + script.name + " ";
341346
this.hideScriptSelector();
342347
input.focus();
343348
});

src/ai_dom_editor/editor/helpers/userscript_handler.js

Lines changed: 25 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,7 @@ export class UserscriptHandler {
3636
});
3737
}
3838

39-
async createUserscript(code) {
39+
async createUserscript(code, name) {
4040
try {
4141
const [tab] = await chrome.tabs.query({
4242
active: true,
@@ -53,10 +53,8 @@ export class UserscriptHandler {
5353

5454
const detectedApis = ScriptAnalyzer.detectGMApiUsage(scriptCode);
5555
const suggestedRunAt = ScriptAnalyzer.suggestRunAt(scriptCode);
56-
const scriptName = ScriptAnalyzer.generateScriptName(
57-
url.hostname,
58-
userPrompt
59-
);
56+
const scriptName =
57+
name || ScriptAnalyzer.generateScriptName(url.hostname, userPrompt);
6058

6159
const metadata = {
6260
name: scriptName,
@@ -75,18 +73,29 @@ export class UserscriptHandler {
7573
metadata
7674
);
7775

78-
// Send to editor
79-
chrome.runtime.sendMessage({
80-
action: "createScriptFromAI",
81-
script: finalScript,
82-
url: tab.url,
83-
});
84-
85-
this.editor.chatManager.addMessage(
86-
"assistant",
87-
"✓ Script created and opened in editor!"
76+
chrome.runtime.sendMessage(
77+
{
78+
action: "createScriptFromAI",
79+
script: finalScript,
80+
url: tab.url,
81+
},
82+
(response) => {
83+
if (response.error) {
84+
console.error("Error creating script:", response.error);
85+
this.editor.chatManager.addMessage(
86+
"assistant",
87+
`Error creating script: ${response.error}`,
88+
{ error: true }
89+
);
90+
return;
91+
}
92+
this.editor.chatManager.addMessage(
93+
"assistant",
94+
"✓ Script created!"
95+
);
96+
this.editor.setCurrentScript(response.script);
97+
}
8898
);
89-
this.editor.setCurrentScript(scriptName);
9099
} catch (error) {
91100
console.error("Error creating userscript:", error);
92101
this.editor.chatManager.addMessage(

0 commit comments

Comments
 (0)