-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
1884 lines (1682 loc) · 87.2 KB
/
Copy pathapp.js
File metadata and controls
1884 lines (1682 loc) · 87.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// app.js — Full-page tab UI for PromptForge
// Uses chrome.storage.local via PromptStorage instead of Dexie
import * as PromptStorage from './promptStorage.js';
import { generateUUID } from './utils.js';
import { improvePrompt, generateVariants, suggestAllMetadata, checkConnection, autoSelectModel, looksLikeResponseInsteadOfPrompt, translatePrompt, DEFAULTS } from './ollama-service.js';
import { CATEGORIES as CATEGORY_DEFS, categoryNameFromId, canonicalCategoryId } from './categories.js';
import { t, relativeTimeLocalized } from './i18n.js';
import { getOpenAiSiteTabs, sendPromptToTab } from './integration-manager.js';
import * as AutoBackup from './autoBackup.js';
import { getSyncSettings, patchSyncSettings, saveDirHandle } from './sync/syncStore.js';
import { runSyncCycle, requestPermissionAndSync, startSyncWatcher, disconnectSync, nativeConnectFolder, nativeGetFolder } from './sync/syncEngine.js';
import { nativeHostAvailable } from './sync/nativeBridge.js';
import { SUPPORTED_LANGUAGES, DEFAULT_PROMPT_LANGUAGES, detectLanguage, languageMeta } from './language.js';
// ─── DOM helpers ──────────────────────────────────────────────────────────
function $(sel, parent = document) { return parent.querySelector(sel); }
function $$(sel, parent = document) { return Array.from(parent.querySelectorAll(sel)); }
// COMMENT: Close all open send dropdown menus in the library view
function closeAllSendMenus() {
$$('.send-dropdown-menu.show').forEach(m => m.classList.remove('show'));
}
// COMMENT: Menus previously stayed open until another Send button happened to
// be clicked. Send buttons stopPropagation, so opening one doesn't trip this.
document.addEventListener('click', () => closeAllSendMenus());
document.addEventListener('keydown', e => { if (e.key === 'Escape') closeAllSendMenus(); });
function el(tag, attrs = {}, children = []) {
const e = document.createElement(tag);
for (const [k, v] of Object.entries(attrs)) {
if (k === 'className') e.className = v;
else if (k.startsWith('on') && typeof v === 'function') e.addEventListener(k.slice(2).toLowerCase(), v);
else if (k === 'dataset') { for (const [dk, dv] of Object.entries(v)) e.dataset[dk] = dv; }
else if (v != null && typeof v !== 'function') e.setAttribute(k, v);
}
for (const c of children) {
if (typeof c === 'string') e.appendChild(document.createTextNode(c));
else if (c) e.appendChild(c);
}
return e;
}
function toast(msg, type = 'info', duration = 4000) {
const c = document.getElementById('toast-container');
if (!c) return;
const t = document.createElement('div');
t.className = `toast ${type}`;
t.textContent = msg;
c.appendChild(t);
// COMMENT: Callers always passed a third duration arg that was ignored.
setTimeout(() => { t.style.opacity = '0'; t.style.transition = 'opacity 0.2s'; setTimeout(() => t.remove(), 200); }, duration);
}
// COMMENT: v3 D-III — locale-aware relative time ("3天前" in zh locales).
function relativeTime(ts) {
return relativeTimeLocalized(ts);
}
// ─── Theme ────────────────────────────────────────────────────────────────
async function initTheme() {
const data = await chrome.storage.local.get({ theme: 'system' });
applyTheme(data.theme);
window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', async () => {
const d = await chrome.storage.local.get({ theme: 'system' });
if (d.theme === 'system') applyTheme('system');
});
}
function applyTheme(theme) {
if (theme === 'system') {
document.documentElement.setAttribute('data-theme', window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light');
} else {
document.documentElement.setAttribute('data-theme', theme);
}
}
// ─── Router ───────────────────────────────────────────────────────────────
const mainContent = document.getElementById('main-content');
const topnavLinks = document.querySelectorAll('.topnav-link');
function navigate(hash) { window.location.hash = hash; }
function setActiveNav(hash) {
const route = hash.startsWith('#/editor') ? 'editor' : hash.replace('#/', '');
topnavLinks.forEach(a => {
a.classList.toggle('active', a.dataset.route === route);
});
}
async function handleRoute() {
const hash = window.location.hash || '#/library';
setActiveNav(hash);
if (hash.startsWith('#/editor/')) {
const rawUuid = hash.split('/').slice(2).join('/');
let uuid;
try {
uuid = decodeURIComponent(rawUuid);
} catch {
// COMMENT: Malformed hash (e.g. #/editor/%ff) threw URIError and left
// the whole app on a blank screen with dead navigation.
toast('Invalid editor link.', 'error');
navigate('#/library');
return;
}
await renderEditor(mainContent, uuid, navigate);
} else if (hash === '#/editor') {
await renderEditor(mainContent, null, navigate);
} else if (hash === '#/settings') {
await renderSettings(mainContent);
} else {
await renderLibrary(mainContent, navigate);
}
}
// Click handlers for nav links
topnavLinks.forEach(a => {
a.addEventListener('click', e => {
e.preventDefault();
navigate(a.getAttribute('href'));
});
});
window.addEventListener('hashchange', handleRoute);
// ─── Library View ─────────────────────────────────────────────────────────
async function renderLibrary(container, onNavigate) {
container.innerHTML = '';
const wrapper = el('div', { className: 'library-container' });
// Header
const header = el('div', { className: 'library-header' });
header.appendChild(el('h2', {}, [t('lib_title', null, 'Library')]));
const newBtn = el('button', { className: 'btn btn-primary' }, [t('lib_new', null, '+ New Prompt')]);
newBtn.addEventListener('click', () => onNavigate('#/editor'));
header.appendChild(newBtn);
wrapper.appendChild(header);
// Controls
const controls = el('div', { className: 'library-controls' });
const search = el('input', { className: 'input library-search', type: 'text', placeholder: t('lib_search_ph', null, 'Search prompts…') });
controls.appendChild(search);
const sortSelect = el('select', { className: 'library-sort' });
for (const [v, key, fb] of [
['recentlyCreated', 'sort_recently_created', 'Recently Created'],
['recentlyModified', 'sort_recently_modified', 'Recently Modified'],
['recentlyUsed', 'sort_recently_used', 'Recently Used'],
['mostUsed', 'sort_most_used', 'Most Used'],
['alphabetical', 'sort_alphabetical', 'Alphabetical'],
]) {
sortSelect.appendChild(el('option', { value: v }, [t(key, null, fb)]));
}
controls.appendChild(sortSelect);
// COMMENT: v3 feature D — filter prompts by language. Prompts without a
// language (legacy, undetected) appear only under "All Languages".
const langFilter = el('select', { className: 'library-sort' });
langFilter.appendChild(el('option', { value: '' }, [t('lib_all_languages', null, 'All Languages')]));
for (const l of SUPPORTED_LANGUAGES) langFilter.appendChild(el('option', { value: l.code }, [l.label]));
langFilter.addEventListener('change', loadPrompts);
controls.appendChild(langFilter);
wrapper.appendChild(controls);
// Category pills
const pillsContainer = el('div', { className: 'category-pills' });
const allPill = el('button', { className: 'category-pill active' }, [t('lib_all', null, 'All')]);
pillsContainer.appendChild(allPill);
// COMMENT: C4 — category pills are keyed by canonical id; display names
// come from the registry (localised display names arrive with D-III).
let activeCategory = null;
for (const cat of [...CATEGORY_DEFS].sort((a, b) => a.name.localeCompare(b.name))) {
const pill = el('button', { className: 'category-pill' }, [t(`cat_${cat.id}`, null, cat.name)]);
pill.addEventListener('click', () => {
$$('.category-pill', pillsContainer).forEach(p => p.classList.remove('active'));
pill.classList.add('active');
activeCategory = cat.id;
loadPrompts();
});
pillsContainer.appendChild(pill);
}
allPill.addEventListener('click', () => {
$$('.category-pill', pillsContainer).forEach(p => p.classList.remove('active'));
allPill.classList.add('active');
activeCategory = null;
loadPrompts();
});
wrapper.appendChild(pillsContainer);
// Prompt list
const listArea = el('div', { className: 'prompt-list' });
wrapper.appendChild(listArea);
container.appendChild(wrapper);
let debounceTimer;
search.addEventListener('input', () => { clearTimeout(debounceTimer); debounceTimer = setTimeout(loadPrompts, 200); });
sortSelect.addEventListener('change', loadPrompts);
await loadPrompts();
async function loadPrompts() {
listArea.innerHTML = '';
const sortBy = sortSelect.value;
const searchVal = search.value.trim();
let prompts = await PromptStorage.getPrompts();
// Filter by archive (hide archived by default)
prompts = prompts.filter(p => !p._archived);
// Filter by category (C4 — match canonical id, deriving from legacy names)
if (activeCategory) prompts = prompts.filter(p => (p.categoryId || canonicalCategoryId(p.category)) === activeCategory);
// Filter by language (v3 feature D)
const langVal = langFilter.value;
if (langVal) prompts = prompts.filter(p => p.language === langVal);
// Filter by search (title, content, tags, category)
if (searchVal) {
const lower = searchVal.toLowerCase();
prompts = prompts.filter(p =>
(p.title || '').toLowerCase().includes(lower) ||
(p.content || '').toLowerCase().includes(lower) ||
(p.tags || []).some(t => t.toLowerCase().includes(lower)) ||
(p.category || '').toLowerCase().includes(lower)
);
}
// Sort
switch (sortBy) {
case 'recentlyUsed': prompts.sort((a, b) => new Date(b.lastUsedAt || b.createdAt) - new Date(a.lastUsedAt || a.createdAt)); break;
case 'mostUsed': prompts.sort((a, b) => (b.useCount || 0) - (a.useCount || 0)); break;
case 'recentlyModified': prompts.sort((a, b) => new Date(b.updatedAt || b.createdAt) - new Date(a.updatedAt || a.createdAt)); break;
case 'alphabetical': prompts.sort((a, b) => ((a.title || '~~~~~').toLowerCase().localeCompare((b.title || '~~~~~').toLowerCase()))); break;
default: prompts.sort((a, b) => new Date(b.createdAt) - new Date(a.createdAt)); break;
}
// v3 D-VI — group siblings by groupId for the language chips on cards.
const groupMates = new Map();
for (const p of prompts) {
if (!p.groupId) continue;
const arr = groupMates.get(p.groupId) || [];
arr.push(p);
groupMates.set(p.groupId, arr);
}
if (prompts.length === 0) {
listArea.appendChild(el('div', { className: 'empty-state' }, [
el('p', {}, [searchVal
? t('lib_empty_search', null, 'No prompts match your search.')
: t('lib_empty_none', null, 'No prompts yet. Click \'New Prompt\' to create your first one.')])
]));
return;
}
for (const p of prompts) {
const card = el('div', { className: 'prompt-list-card card' });
// Header
const hdr = el('div', { className: 'card-header' });
hdr.appendChild(el('h4', {}, [p.title || t('untitled', null, 'Untitled Prompt')]));
const favBtn = el('button', { className: `btn btn-sm ${(p.favorite ? 'btn-primary' : 'btn-secondary')}`, title: p.favorite ? t('fav_remove', null, 'Unfavorite') : t('fav_add', null, 'Favorite') }, [p.favorite ? '★' : '☆']);
favBtn.addEventListener('click', async () => {
await PromptStorage.updatePrompt(p.uuid, { favorite: !p.favorite });
loadPrompts();
});
hdr.appendChild(favBtn);
card.appendChild(hdr);
// Body
card.appendChild(el('div', { className: 'card-body' }, [(p.content || '').substring(0, 150)]));
// Footer
const footer = el('div', { className: 'card-footer' });
// v3 D-VI — group chips: EN · 简 · 繁 jump buttons across forked siblings.
const mates = p.groupId ? groupMates.get(p.groupId) : null;
const grouped = !!(mates && mates.length > 1);
if (p.language && !grouped) {
// COMMENT: Standalone language badge — suppressed for grouped prompts,
// where the chips below already mark the current language (bold).
const meta = languageMeta(p.language);
footer.appendChild(el('span', { className: 'tag', title: meta.label }, [meta.short]));
}
if (grouped) {
const LANG_ORDER = ['en', 'zh-HK', 'zh-CN'];
// COMMENT: Legacy/undetected siblings have language:null — fall back to
// offline detection so chips never render "NULL".
const effective = (m) => m.language || detectLanguage(m.content || '').code;
const sorted = [...mates].sort((a, b) => LANG_ORDER.indexOf(effective(a)) - LANG_ORDER.indexOf(effective(b)));
for (const m of sorted) {
const lang = effective(m);
if (!lang) continue;
const meta = languageMeta(lang);
const isCurrent = m.uuid === p.uuid;
const chip = el('span', {
className: 'tag',
title: `${meta.label} — ${m.title || t('untitled', null, 'Untitled Prompt')}`,
style: isCurrent
? 'cursor:default;font-weight:700;outline:1px solid var(--color-primary);'
: 'cursor:pointer;opacity:0.75;',
}, [meta.short]);
if (!isCurrent) {
chip.addEventListener('click', (e) => {
e.stopPropagation();
onNavigate(`#/editor/${encodeURIComponent(m.uuid)}`);
});
}
footer.appendChild(chip);
}
}
const tagsDiv = el('div', { className: 'tags' });
for (const t of (p.tags || [])) {
const tagSpan = el('span', { className: 'tag', style: 'cursor:pointer;' }, [t]);
tagSpan.title = `Search for "${t}"`;
tagSpan.addEventListener('click', (e) => {
e.stopPropagation();
search.value = t;
loadPrompts();
});
tagsDiv.appendChild(tagSpan);
}
footer.appendChild(tagsDiv);
const vCount = (p.versions || []).length || 1;
const when = relativeTime(p.updatedAt || p.createdAt);
footer.appendChild(el('span', {}, [t('card_stats', [String(vCount), String(p.useCount || 0), when], `v${vCount} · ${p.useCount || 0} uses · ${when}`)]));
card.appendChild(footer);
// Actions
const actions = el('div', { className: 'actions' });
const copyBtn = el('button', { className: 'btn btn-sm btn-primary' }, [t('btn_copy', null, 'Copy')]);
copyBtn.addEventListener('click', async () => {
try {
await navigator.clipboard.writeText(p.content);
// COMMENT: Atomic bump — the old read-from-stale-card-snapshot write
// raced with the floating panel and dropped increments.
await PromptStorage.bumpUseCount(p.uuid);
toast(t('toast_copied', null, 'Copied!'), 'success', 1000);
} catch { toast(t('toast_copy_failed', null, 'Copy failed'), 'error'); }
});
actions.appendChild(copyBtn);
const editBtn = el('button', { className: 'btn btn-sm btn-secondary' }, [t('btn_edit', null, 'Edit')]);
editBtn.addEventListener('click', () => onNavigate(`#/editor/${encodeURIComponent(p.uuid)}`));
actions.appendChild(editBtn);
// AI Suggest button — re-generate title, tags, category from content
const suggestBtn = el('button', { className: 'btn btn-sm btn-secondary' }, [t('btn_suggest', null, '✨ Suggest')]);
suggestBtn.title = t('btn_suggest_title', null, 'AI-suggest title, tags, and category from content');
suggestBtn.addEventListener('click', async () => {
suggestBtn.disabled = true;
suggestBtn.textContent = '…';
try {
// COMMENT: v3 feature D-II — suggest in the prompt's own language.
const metadata = await suggestAllMetadata(p.content, p.language || detectLanguage(p.content).code);
const filteredTags = metadata.tags.filter(t => t !== 'untagged');
const titleApplied = !!(metadata.title && metadata.title !== 'Untitled Prompt');
const tagsApplied = filteredTags.length > 0;
const categoryApplied = !!(metadata.category && metadata.category !== 'Other');
const newTitle = titleApplied ? metadata.title : p.title;
const newCategory = categoryApplied ? metadata.category : p.category;
const newTags = tagsApplied ? [...new Set([...(p.tags || []), ...filteredTags])] : p.tags;
await PromptStorage.updatePrompt(p.uuid, {
title: newTitle,
category: newCategory,
tags: newTags,
updatedAt: new Date().toISOString()
});
const parts = [];
if (titleApplied) parts.push('title');
if (tagsApplied) parts.push('tags');
if (categoryApplied) parts.push('category');
toast(parts.length ? `Suggested: ${parts.join(', ')}` : 'No new suggestions', parts.length ? 'success' : 'warning');
loadPrompts();
} catch (e) {
toast('Suggestion failed: ' + e.message, 'error');
} finally {
suggestBtn.disabled = false;
suggestBtn.textContent = '✨ Suggest';
}
});
actions.appendChild(suggestBtn);
const archiveBtn = el('button', { className: 'btn btn-sm btn-secondary' }, [t('btn_archive', null, 'Archive')]);
archiveBtn.addEventListener('click', async () => {
await PromptStorage.updatePrompt(p.uuid, { _archived: true });
loadPrompts();
});
actions.appendChild(archiveBtn);
// Send dropdown
const sendWrap = el('div', { className: 'send-dropdown' });
const sendBtn = el('button', { className: 'btn btn-sm btn-secondary' }, [t('btn_send', null, 'Send'), el('span', { style: 'margin-left:4px;font-size:10px;' }, ['▼'])]);
const sendMenu = el('div', { className: 'send-dropdown-menu' });
sendBtn.addEventListener('click', async (e) => {
e.stopPropagation();
const isOpen = sendMenu.classList.contains('show');
closeAllSendMenus();
if (isOpen) return;
sendMenu.innerHTML = '';
sendMenu.appendChild(el('div', { className: 'send-dropdown-item', style: 'color:var(--color-text-secondary);' }, [t('send_loading', null, 'Loading tabs…')]));
sendMenu.classList.add('show');
try {
const tabs = await getOpenAiSiteTabs();
sendMenu.innerHTML = '';
if (tabs.length === 0) {
sendMenu.appendChild(el('div', { className: 'send-dropdown-item', style: 'color:var(--color-text-secondary);font-style:italic;' }, [t('send_no_tabs', null, 'No AI site tabs open')]));
} else {
// Group by provider
const grouped = {};
for (const t of tabs) {
if (!grouped[t.providerName]) grouped[t.providerName] = [];
grouped[t.providerName].push(t);
}
for (const [providerName, providerTabs] of Object.entries(grouped)) {
const header = el('div', { className: 'send-dropdown-item', style: 'font-weight:600;color:var(--color-text-secondary);cursor:default;font-size:11px;' }, [providerName]);
sendMenu.appendChild(header);
for (const tab of providerTabs) {
const item = el('div', { className: 'send-dropdown-item' }, [
el('span', { style: 'overflow:hidden;text-overflow:ellipsis;white-space:nowrap;flex:1;' }, [tab.title || 'Untitled Tab'])
]);
item.addEventListener('click', async () => {
closeAllSendMenus();
const result = await sendPromptToTab(tab.tabId, p.content);
if (result.success) {
toast(t('send_sent', [tab.providerName], `Sent to ${tab.providerName}`), 'success');
await PromptStorage.bumpUseCount(p.uuid);
} else {
toast(t('send_failed', [result.error || 'unknown error'], 'Send failed: ' + (result.error || 'unknown error')), 'error');
}
});
sendMenu.appendChild(item);
}
}
}
} catch (err) {
sendMenu.innerHTML = '<div class="send-dropdown-item" style="color:var(--color-danger);">Error loading tabs</div>';
}
});
sendWrap.appendChild(sendBtn);
sendWrap.appendChild(sendMenu);
actions.appendChild(sendWrap);
card.appendChild(actions);
// Click card body to open editor (buttons still handle their own clicks)
card.addEventListener('click', (e) => {
if (e.target.closest('button, input, .send-dropdown-menu')) return;
onNavigate(`#/editor/${encodeURIComponent(p.uuid)}`);
});
listArea.appendChild(card);
}
}
}
// ─── Editor View ──────────────────────────────────────────────────────────
// COMMENT: Teardown ref only — the live controller is per-editor-session
// (declared inside renderEditor). The old module-level controller was shared
// across sessions: navigating away mid-stream then starting a new Improve let
// the old stream's finally{} null the new session's controller, killing its
// Stop button while the orphan kept writing into a detached textarea.
let activeEditorAbort = null;
async function renderEditor(container, promptUuid, onNavigate) {
// Abort any stream still running from the previous editor session.
if (activeEditorAbort) { activeEditorAbort.abort(); activeEditorAbort = null; }
container.innerHTML = '';
let improveController = null;
const wrapper = el('div', { className: 'editor-container' });
// Header
const header = el('div', { className: 'editor-header' });
const backBtn = el('button', { className: 'btn btn-secondary' }, ['← Library']);
backBtn.addEventListener('click', () => onNavigate('#/library'));
header.appendChild(backBtn);
const titleEl = el('h2', {}, [promptUuid ? t('editor_edit', null, 'Edit Prompt') : t('editor_new', null, 'New Prompt')]);
header.appendChild(titleEl);
header.appendChild(el('span', { className: 'editor-save-indicator', id: 'save-indicator' }));
// AI processing indicator: spinner + label, shown while Ollama is working
// (Improve / Variants / Auto-suggest). Stop for streaming Improve is the
// existing stopBtn in the actions row.
const aiStatus = el('span', { className: 'editor-ai-status', id: 'ai-status', style: 'display:none;' });
header.appendChild(aiStatus);
wrapper.appendChild(header);
function setAiStatus(label) {
aiStatus.innerHTML = '';
aiStatus.appendChild(el('span', { className: 'ai-spinner' }));
aiStatus.appendChild(document.createTextNode(' ' + label));
aiStatus.style.display = 'inline-flex';
}
function clearAiStatus() {
aiStatus.style.display = 'none';
aiStatus.innerHTML = '';
}
// Title
const titleInput = el('input', { className: 'editor-title-input', type: 'text', placeholder: t('editor_title_ph', null, 'Prompt title…') });
wrapper.appendChild(titleInput);
// Meta row
const metaRow = el('div', { className: 'editor-meta' });
// COMMENT: C4 — category select values are canonical ids; display names
// from the registry.
const catSelect = el('select', { className: 'editor-category-select' });
catSelect.appendChild(el('option', { value: '' }, [t('editor_uncategorized', null, 'Uncategorized')]));
for (const c of [...CATEGORY_DEFS].sort((a, b) => a.name.localeCompare(b.name))) {
catSelect.appendChild(el('option', { value: c.id }, [t(`cat_${c.id}`, null, c.name)]));
}
metaRow.appendChild(catSelect);
// COMMENT: v3 feature D — per-prompt language. "Auto" detects from content
// at save time; low-confidence/undetected results store null and can be set
// manually here afterwards.
const { promptLanguages } = await chrome.storage.local.get({ promptLanguages: DEFAULT_PROMPT_LANGUAGES });
const langSel = el('select', { className: 'editor-category-select' });
langSel.appendChild(el('option', { value: 'auto' }, [t('editor_lang_auto', null, 'Auto-detect language')]));
const langCodes = (Array.isArray(promptLanguages) && promptLanguages.length > 0) ? promptLanguages : DEFAULT_PROMPT_LANGUAGES;
for (const code of langCodes) {
const meta = languageMeta(code);
langSel.appendChild(el('option', { value: meta.code }, [meta.label]));
}
// COMMENT: v3 feature D-II — honor the user's default-language preference
// for new prompts (loading an existing prompt overrides this below).
const { defaultPromptLanguage } = await chrome.storage.local.get({ defaultPromptLanguage: 'auto' });
if (defaultPromptLanguage && defaultPromptLanguage !== 'auto'
&& [...langSel.options].some(o => o.value === defaultPromptLanguage)) {
langSel.value = defaultPromptLanguage;
}
metaRow.appendChild(langSel);
// COMMENT: v3 feature D-II — the effective language for AI operations:
// the selected one, or offline detection when the selector is on Auto.
function currentLanguage() {
return langSel.value === 'auto' ? detectLanguage(textarea.value).code : langSel.value;
}
// Tag input
const tagContainer = el('div', { style: 'flex:1;display:flex;align-items:center;gap:4px;flex-wrap:wrap;' });
const tagInput = el('input', { className: 'editor-tag-input', placeholder: t('editor_tag_ph', null, 'Add tag…'), autocomplete: 'off' });
let currentTags = [];
let currentGroupId = null; // v3 D-VI — language-linked fork group
function renderTags() {
tagContainer.innerHTML = '';
for (const t of currentTags) {
const pill = el('span', { className: 'tag' }, [t, ' ', el('span', { className: 'remove' }, ['×'])]);
pill.querySelector('.remove').addEventListener('click', () => { currentTags = currentTags.filter(x => x !== t); renderTags(); });
tagContainer.appendChild(pill);
}
tagContainer.appendChild(tagInput);
}
tagInput.addEventListener('keydown', e => {
if ((e.key === 'Enter' || e.key === ',') && tagInput.value.trim()) {
e.preventDefault();
// COMMENT: Strip ALL commas — only the first was removed, so pasting
// "a, b, c" created one tag containing commas.
const t = tagInput.value.replace(/,/g, '').trim().toLowerCase().replace(/\s+/g, '-');
if (!currentTags.includes(t)) { currentTags.push(t); renderTags(); }
tagInput.value = '';
}
});
renderTags();
metaRow.appendChild(tagContainer);
wrapper.appendChild(metaRow);
// Textarea
const textarea = el('textarea', { className: 'editor-textarea', placeholder: t('editor_content_ph', null, 'Write your prompt here…') });
wrapper.appendChild(textarea);
// Actions
const actions = el('div', { className: 'editor-actions' });
const saveBtn = el('button', { className: 'btn btn-primary' }, [t('editor_save', null, 'Save Prompt')]);
actions.appendChild(saveBtn);
const improveBtn = el('button', { className: 'btn btn-secondary' }, [t('editor_improve', null, 'Improve with AI')]);
actions.appendChild(improveBtn);
const stopBtn = el('button', { className: 'btn btn-danger', style: 'display:none;' }, [t('editor_stop', null, 'Stop')]);
actions.appendChild(stopBtn);
const variantsBtn = el('button', { className: 'btn btn-secondary' }, [t('editor_variants', null, 'Variants')]);
actions.appendChild(variantsBtn);
const translateBtn = el('button', { className: 'btn btn-secondary' }, [t('editor_translate', null, 'Translate')]);
actions.appendChild(translateBtn);
const forkBtn = el('button', { className: 'btn btn-secondary' }, [t('editor_fork', null, 'Fork ▾')]);
actions.appendChild(forkBtn);
const versionBtn = el('button', { className: 'btn btn-secondary' }, [t('editor_versions', null, 'Version History')]);
actions.appendChild(versionBtn);
wrapper.appendChild(actions);
container.appendChild(wrapper);
// Load existing prompt
if (promptUuid) {
try {
const prompts = await PromptStorage.getPrompts();
const p = prompts.find(x => x.uuid === promptUuid);
if (p) {
textarea.value = p.content || '';
currentGroupId = p.groupId || null;
if (p.title) titleInput.value = p.title;
const pCatId = p.categoryId || canonicalCategoryId(p.category);
if (pCatId) {
catSelect.value = pCatId;
} else if (p.category) {
// COMMENT: Custom/unknown category — keep it selectable verbatim so
// the next save doesn't silently wipe it.
if (![...catSelect.options].some(o => o.value === p.category)) {
catSelect.appendChild(el('option', { value: p.category }, [p.category]));
}
catSelect.value = p.category;
}
// COMMENT: v3 feature D — reflect the stored language; stays on
// "Auto-detect" if the stored value isn't in the active language set.
if (p.language && [...langSel.options].some(o => o.value === p.language)) {
langSel.value = p.language;
}
currentTags = [...(p.tags || [])];
renderTags();
} else {
toast('Prompt not found', 'error');
onNavigate('#/library');
return;
}
} catch (e) { toast('Error loading prompt: ' + e.message, 'error'); }
}
// Events
let dirty = false;
textarea.addEventListener('input', () => { dirty = true; });
textarea.addEventListener('keydown', e => {
if (e.key === 'Tab') {
e.preventDefault();
const start = textarea.selectionStart;
if (e.shiftKey && textarea.value.substring(start - 2, start) === ' ') {
textarea.value = textarea.value.substring(0, start - 2) + textarea.value.substring(start);
textarea.selectionStart = textarea.selectionEnd = start - 2;
} else {
textarea.value = textarea.value.substring(0, start) + ' ' + textarea.value.substring(textarea.selectionEnd);
textarea.selectionStart = textarea.selectionEnd = start + 2;
}
dirty = true;
}
if ((e.ctrlKey || e.metaKey) && e.key === 's') { e.preventDefault(); doSave(); }
});
saveBtn.addEventListener('click', doSave);
improveBtn.addEventListener('click', doImprove);
stopBtn.addEventListener('click', doStop);
variantsBtn.addEventListener('click', doVariants);
translateBtn.addEventListener('click', doTranslate);
forkBtn.addEventListener('click', () => {
// COMMENT: v3 feature D-VI — Fork ▾: duplicate (same language) or fork a
// translated copy into a language-linked group (shared groupId).
if (actions.querySelector('.fork-pick')) return;
const fromLang = currentLanguage();
const pick = el('select', { className: 'fork-pick', style: 'margin-left:8px;' });
pick.appendChild(el('option', { value: '' }, [t('editor_fork_menu', null, 'Fork / duplicate…')]));
pick.appendChild(el('option', { value: 'duplicate' }, [t('editor_duplicate', null, 'Duplicate (same language)')]));
for (const l of SUPPORTED_LANGUAGES) {
if (fromLang && l.code === fromLang) continue;
pick.appendChild(el('option', { value: 'fork:' + l.code }, [t('editor_fork_lang', [l.label], `Fork to ${l.label}`)]));
}
pick.addEventListener('change', () => {
const v = pick.value;
pick.remove();
if (v === 'duplicate') runFork(null);
else if (v.startsWith('fork:')) runFork(v.slice(5));
});
actions.appendChild(pick);
});
versionBtn.addEventListener('click', doVersionHistory);
async function doSave() {
const content = textarea.value.trim();
if (!content) { toast(t('toast_content_empty', null, 'Prompt content cannot be empty'), 'warning'); return; }
// COMMENT: v3 feature D — resolve the prompt's language. "Auto" runs
// offline detection; undetectable/mixed-script text stores null (no badge
// until the user picks one from the selector).
const languageResolved = langSel.value === 'auto' ? detectLanguage(content).code : langSel.value;
// COMMENT: C4 — resolve category to (canonical id, English display name).
const catIdResolved = canonicalCategoryId(catSelect.value);
const categoryResolved = catIdResolved ? categoryNameFromId(catIdResolved) : (catSelect.value || null);
const saveIndicator = document.getElementById('save-indicator');
const isFirstSave = !promptUuid;
const needsAutoSuggest = isFirstSave &&
(titleInput.value.trim() === '' || titleInput.value.trim() === 'Untitled Prompt') &&
currentTags.length === 0 &&
!catSelect.value;
// Check if auto-suggest is enabled in settings
let willAutoSuggest = false;
if (needsAutoSuggest) {
const settings = await chrome.storage.local.get({ autoSuggestMetadata: true });
willAutoSuggest = settings.autoSuggestMetadata;
}
saveBtn.disabled = true;
if (saveIndicator) saveIndicator.textContent = 'Saving…';
try {
if (isFirstSave) {
const result = await PromptStorage.savePrompt({
title: titleInput.value.trim() || 'Untitled Prompt',
content,
tags: [...currentTags],
category: categoryResolved,
categoryId: catIdResolved,
language: languageResolved
});
promptUuid = result.prompt.uuid;
titleEl.textContent = t('editor_edit', null, 'Edit Prompt');
} else {
await PromptStorage.updatePrompt(promptUuid, {
content,
title: titleInput.value.trim() || null,
tags: [...currentTags],
category: categoryResolved,
categoryId: catIdResolved,
language: languageResolved,
updatedAt: new Date().toISOString()
});
await PromptStorage.addVersion(promptUuid, content, 'manual_edit');
}
dirty = false;
// Auto-suggest metadata on first save (only when user didn't provide title, tags, or category)
if (willAutoSuggest) {
setAiStatus('Analyzing prompt…');
try {
const metadata = await suggestAllMetadata(content, languageResolved);
const filteredTags = metadata.tags.filter(t => t !== 'untagged');
const titleApplied = !!(metadata.title && metadata.title !== 'Untitled Prompt');
const tagsApplied = filteredTags.length > 0;
const categoryApplied = !!(metadata.category && metadata.category !== 'Other');
if (titleApplied) titleInput.value = metadata.title;
if (categoryApplied) catSelect.value = canonicalCategoryId(metadata.category) || metadata.category;
if (tagsApplied) { currentTags = filteredTags; renderTags(); }
const aiCatId = canonicalCategoryId(catSelect.value);
await PromptStorage.updatePrompt(promptUuid, {
title: titleInput.value || metadata.title,
category: aiCatId ? categoryNameFromId(aiCatId) : (catSelect.value || metadata.category),
categoryId: aiCatId,
tags: currentTags.length > 0 ? currentTags : filteredTags,
updatedAt: new Date().toISOString()
});
const parts = [];
if (titleApplied) parts.push(t('suggest_title', null, 'title'));
if (tagsApplied) parts.push(t('suggest_tags', null, 'tags'));
if (categoryApplied) parts.push(t('suggest_category', null, 'category'));
if (parts.length > 0) {
toast(t('toast_saved_auto', [parts.join(', ')], `Saved! Auto-filled ${parts.join(', ')}.`), 'success', 2500);
} else {
toast(t('toast_saved', null, 'Saved!'), 'success', 1500);
}
} catch (_) {
toast(t('toast_saved_skip', null, 'Saved! (AI suggestion skipped)'), 'warning', 2000);
}
} else {
toast('Saved!', 'success', 1500);
}
} catch (e) {
toast('Save failed: ' + e.message, 'error');
} finally {
saveBtn.disabled = false;
if (saveIndicator) saveIndicator.textContent = '';
clearAiStatus();
}
}
async function doImprove() {
const content = textarea.value.trim();
if (!content) { toast(t('toast_nothing_improve', null, 'Nothing to improve'), 'warning'); return; }
const snapshot = textarea.value;
if (promptUuid) await PromptStorage.addVersion(promptUuid, content, 'manual_edit');
improveBtn.disabled = true; improveBtn.textContent = t('panel_improving', null, 'Improving…');
stopBtn.style.display = 'inline-flex';
setAiStatus(t('panel_improving', null, 'Improving…'));
textarea.setAttribute('readonly', ''); textarea.style.opacity = '0.6';
improveController = new AbortController();
activeEditorAbort = improveController;
try {
let buffer = '';
const gen = await improvePrompt(content, { signal: improveController.signal, language: currentLanguage() });
for await (const chunk of gen) { buffer += chunk; textarea.value = buffer; }
buffer = buffer.replace(/^(?:here|sure|okay|the improved|improved|below)[^\n]*\n?/i, '').trim();
textarea.value = buffer;
// Sanity check: did the model produce a response instead of a rewritten prompt?
if (buffer && looksLikeResponseInsteadOfPrompt(buffer)) {
throw new Error('Model produced a response instead of a rewritten prompt');
}
if (promptUuid && buffer) {
await PromptStorage.addVersion(promptUuid, buffer, 'ai_improvement');
toast(t('toast_improved', null, 'Prompt improved!'), 'success');
}
} catch (e) {
if (!e.message.includes('aborted')) toast(t('toast_improve_failed', [e.message], 'Improvement failed: ' + e.message), 'error');
textarea.value = snapshot;
} finally {
if (activeEditorAbort === improveController) activeEditorAbort = null;
improveController = null; textarea.removeAttribute('readonly'); textarea.style.opacity = '1';
improveBtn.disabled = false; improveBtn.textContent = t('editor_improve', null, 'Improve with AI'); stopBtn.style.display = 'none';
clearAiStatus();
}
}
function doStop() { if (improveController) { improveController.abort(); improveController = null; } }
async function doVariants() {
const content = textarea.value.trim();
if (!content) { toast(t('toast_nothing_variants', null, 'Nothing to generate variants for'), 'warning'); return; }
variantsBtn.disabled = true; variantsBtn.textContent = t('panel_generating', null, 'Generating variants…');
setAiStatus(t('panel_generating', null, 'Generating variants…'));
try {
const variants = await generateVariants(content, 3, { language: currentLanguage() });
if (promptUuid) {
const g = generateUUID();
for (let i = 0; i < variants.length; i++) {
await PromptStorage.addVersion(promptUuid, variants[i], 'ai_variant', { variantGroup: g, variantIndex: i + 1 });
}
}
// Show modal
showVariantModal(variants, (text) => { textarea.value = text; dirty = true; toast(t('toast_variant_loaded', null, 'Variant loaded — edit and save'), 'success'); });
} catch (e) { toast(t('toast_variants_failed', [e.message], 'Variant generation failed: ' + e.message), 'error'); }
finally { variantsBtn.disabled = false; variantsBtn.textContent = t('editor_variants', null, 'Variants'); clearAiStatus(); }
}
// ── v3 feature D-V — translate/convert to another language ──
// Click shows an inline target picker; choosing a language streams the
// translation into the textarea (same UX as Improve), then stores it as a
// version ('ai_translation') and flips the prompt's language field.
function doTranslate() {
if (!promptUuid) { toast(t('toast_save_first', null, 'Save the prompt first'), 'warning'); return; }
if (actions.querySelector('.translate-pick')) return;
const fromLang = currentLanguage();
const pick = el('select', { className: 'translate-pick', style: 'margin-left:8px;' });
pick.appendChild(el('option', { value: '' }, [t('editor_translate_to', null, 'Translate to…')]));
for (const l of SUPPORTED_LANGUAGES) {
if (fromLang && l.code === fromLang) continue;
pick.appendChild(el('option', { value: l.code }, [l.label]));
}
pick.addEventListener('change', () => {
const to = pick.value;
pick.remove();
if (to) runTranslate(fromLang, to);
});
actions.appendChild(pick);
}
async function runTranslate(fromLang, toLang) {
const content = textarea.value.trim();
if (!content) return;
// Snapshot the current text as a version before overwriting it.
if (promptUuid) await PromptStorage.addVersion(promptUuid, content, 'manual_edit');
improveBtn.disabled = true;
translateBtn.disabled = true;
stopBtn.style.display = 'inline-flex';
textarea.setAttribute('readonly', ''); textarea.style.opacity = '0.6';
setAiStatus(t('editor_translating', null, 'Translating…'));
improveController = new AbortController();
activeEditorAbort = improveController;
try {
let buffer = '';
const gen = translatePrompt(content, toLang, { fromLang, signal: improveController.signal });
for await (const chunk of gen) { buffer += chunk; textarea.value = buffer; }
buffer = buffer.trim();
if (buffer && promptUuid) {
await PromptStorage.addVersion(promptUuid, buffer, 'ai_translation', { from: fromLang, to: toLang });
await PromptStorage.updatePrompt(promptUuid, { content: buffer, language: toLang, updatedAt: new Date().toISOString() });
langSel.value = toLang;
const label = languageMeta(toLang).label;
toast(t('toast_translated', [label], `Translated to ${label}`), 'success');
}
} catch (e) {
if (!e.message.includes('aborted')) toast(t('toast_translate_failed', [e.message], 'Translation failed: ' + e.message), 'error');
} finally {
if (activeEditorAbort === improveController) activeEditorAbort = null;
improveController = null; textarea.removeAttribute('readonly'); textarea.style.opacity = '1';
improveBtn.disabled = false; translateBtn.disabled = false; stopBtn.style.display = 'none';
clearAiStatus();
}
}
// ── v3 feature D-VI — fork/duplicate into a language-linked group ──
// toLang = null → plain duplicate; otherwise translate into a new sibling
// prompt sharing a groupId (created and back-filled onto the source on the
// first fork). Keeps titles identical — the group chips carry the language.
async function runFork(toLang) {
const content = textarea.value.trim();
if (!content) { toast(t('toast_content_empty', null, 'Prompt content cannot be empty'), 'warning'); return; }
const title = titleInput.value.trim() || t('untitled', null, 'Untitled Prompt');
const fromLang = currentLanguage();
let groupId = currentGroupId;
if (!groupId) {
groupId = generateUUID();
if (promptUuid) {
await PromptStorage.updatePrompt(promptUuid, { groupId });
currentGroupId = groupId;
}
}
// COMMENT: Bugfix — back-fill the source's stored language when it was
// never set (legacy/undetected), so the group's chips show a real
// language for the original instead of "NULL".
if (promptUuid && fromLang) {
const all = await PromptStorage.getPrompts();
const src = all.find(x => x.uuid === promptUuid);
if (src && !src.language) {
await PromptStorage.updatePrompt(promptUuid, { language: fromLang });
}
}
forkBtn.disabled = true;
let newContent = content;
let newLang = fromLang;
if (toLang && toLang !== fromLang) {
stopBtn.style.display = 'inline-flex';
setAiStatus(t('editor_translating', null, 'Translating…'));
improveController = new AbortController();
activeEditorAbort = improveController;
try {
let buffer = '';
const gen = translatePrompt(content, toLang, { fromLang, signal: improveController.signal });
for await (const chunk of gen) { buffer += chunk; }
newContent = buffer.trim();
if (!newContent) throw new Error('empty translation');
newLang = toLang;
} catch (e) {
if (!e.message.includes('aborted')) toast(t('toast_translate_failed', [e.message], 'Translation failed: ' + e.message), 'error');
return;
} finally {
if (activeEditorAbort === improveController) activeEditorAbort = null;
improveController = null;
stopBtn.style.display = 'none';
clearAiStatus();
}
}
try {
const forkCatId = canonicalCategoryId(catSelect.value);
const forkCat = forkCatId ? categoryNameFromId(forkCatId) : (catSelect.value || null);
const res = await PromptStorage.savePrompt({
title, content: newContent, language: newLang, groupId,
tags: [...currentTags], category: forkCat, categoryId: forkCatId,
});
if (toLang) {
const label = languageMeta(toLang).label;
toast(t('toast_forked', [label], `Forked to ${label}`), 'success');
} else {
toast(t('toast_duplicated', null, 'Duplicated'), 'success');
}
onNavigate(`#/editor/${encodeURIComponent(res.prompt.uuid)}`);
} catch (e) {
toast(t('toast_failed', [e.message], 'Failed: ' + e.message), 'error');
} finally {
forkBtn.disabled = false;
}
}
async function doVersionHistory() {
if (!promptUuid) { toast(t('toast_save_first', null, 'Save the prompt first'), 'warning'); return; }
const versions = await PromptStorage.getVersions(promptUuid);
showVersionModal(versions);
}
}
// ─── Modal helpers ────────────────────────────────────────────────────────
function showVariantModal(variants, onUse) {
const overlay = document.createElement('div');
overlay.className = 'modal-overlay';