-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcontent.shared.js
More file actions
1049 lines (953 loc) · 49.1 KB
/
Copy pathcontent.shared.js
File metadata and controls
1049 lines (953 loc) · 49.1 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
/* ============================================================================
Prompt Manager Shared UI Helpers (content.shared.js)
COMMENT: Houses TagService, TagUI, and PromptUI so content.js stays lean.
============================================================================ */
(function registerPromptManagerShared() {
function initPromptManagerShared() {
if (window.__OPM_PROMPT_SHARED__) return;
window.__OPM_PROMPT_SHARED__ = true;
const createEl = window.createEl;
const getMode = window.getMode;
const getIconFilterFn = window.getIconFilter;
const showEl = window.showEl;
const hideEl = window.hideEl;
const SELECTORS = window.SELECTORS;
const PanelRouter = window.PanelRouter;
const PanelView = window.PanelView;
const PromptUIManager = window.PromptUIManager;
const PromptStorageManager = window.PromptStorageManager;
if (!createEl || !getMode || !showEl || !hideEl || !SELECTORS || !PanelRouter || !PanelView || !PromptUIManager || !PromptStorageManager) {
window.__OPM_PROMPT_SHARED__ = false;
console.warn('[PromptManager] Shared helpers unavailable; deferring initialization.');
return;
}
const fallbackIconFilter = 'invert(37%) sepia(74%) saturate(380%) hue-rotate(175deg) brightness(93%) contrast(88%)';
const iconFilter = () => (typeof getIconFilterFn === 'function' ? getIconFilterFn() : fallbackIconFilter);
// COMMENT: v3 D-IV — i18n accessor over the window contract (the bundled
// i18n.js module is exposed by content.js before this init runs).
const tt = (key, subs, fallback) => (window.PFI18n ? window.PFI18n.t(key, subs || null, fallback) : fallback);
// COMMENT: B2 — search/filter data lives in this in-memory index keyed by
// uuid. Prompt titles/bodies/tags are never mirrored into DOM data-*
// attributes, where host-page JavaScript could scrape the whole library.
// Items in the page DOM carry only data-uuid; filtering (content.js)
// looks entries up here. Stale entries (deleted prompts) never match a
// live DOM item and are overwritten on the next render.
window.__PF_PROMPT_INDEX = window.__PF_PROMPT_INDEX || new Map();
const indexPromptForSearch = (prompt) => {
if (!prompt || !prompt.uuid) return;
window.__PF_PROMPT_INDEX.set(prompt.uuid, {
title: (prompt.title || '').toLowerCase(),
content: (prompt.content || '').toLowerCase(),
tags: Array.isArray(prompt.tags) ? prompt.tags.map(t => String(t).toLowerCase()) : []
});
};
const ICON_SVGS = {
list: `<img src="${chrome.runtime.getURL('icons/list.svg')}" width="16" height="16" alt="${tt('panel_icon_list', null, 'List Prompts')}" title="${tt('panel_icon_list', null, 'List Prompts')}" style="filter: ${iconFilter()}">`,
add: `<img src="${chrome.runtime.getURL('icons/new.svg')}" width="16" height="16" alt="${tt('panel_icon_add', null, 'Add Prompt')}" title="${tt('panel_icon_add', null, 'Add Prompt')}" style="filter: ${iconFilter()}">`,
delete: `<img src="${chrome.runtime.getURL('icons/delete.svg')}" width="16" height="16" alt="${tt('panel_icon_delete', null, 'Delete')}" title="${tt('panel_icon_delete', null, 'Delete')}" style="filter: ${iconFilter()}">`,
edit: `<img src="${chrome.runtime.getURL('icons/edit.svg')}" width="16" height="16" alt="${tt('panel_icon_edit', null, 'Edit')}" title="${tt('panel_icon_edit', null, 'Edit')}" style="filter: ${iconFilter()}">`,
settings: `<img src="${chrome.runtime.getURL('icons/settings.svg')}" width="16" height="16" alt="${tt('panel_icon_settings', null, 'Settings')}" title="${tt('panel_icon_settings', null, 'Settings')}" style="filter: ${iconFilter()}">`,
help: `<img src="${chrome.runtime.getURL('icons/help.svg')}" width="16" height="16" alt="${tt('panel_icon_help', null, 'Help')}" title="${tt('panel_icon_help', null, 'Help')}" style="filter: ${iconFilter()}">`,
};
const TagService = (() => {
const computeCounts = (prompts = []) => {
const counts = new Map();
prompts.forEach(p => (Array.isArray(p.tags) ? p.tags : []).forEach(t => {
const key = String(t).trim();
if (!key) return;
counts.set(key, (counts.get(key) || 0) + 1);
}));
return counts;
};
const getCounts = async (prompts) => {
if (!Array.isArray(prompts)) {
try { prompts = await window.PromptStorageManager.getPrompts(); } catch (_) { prompts = []; }
}
return computeCounts(prompts);
};
const getOrderedTags = async (countsOrPrompts) => {
const counts = countsOrPrompts instanceof Map ? countsOrPrompts : await getCounts(countsOrPrompts);
const order = await window.PromptStorageManager.getTagsOrder();
const tags = Array.from(counts.keys());
const missing = tags.filter(t => !order.includes(t)).sort((a, b) => a.localeCompare(b));
return [...order.filter(t => counts.has(t)), ...missing];
};
const getSuggestions = async ({ term = '', exclude = new Set() } = {}) => {
const counts = await getCounts();
const ordered = await getOrderedTags(counts);
const lcTerm = term.trim().toLowerCase();
return ordered.filter(t => !exclude.has(t) && (lcTerm === '' || String(t).toLowerCase().includes(lcTerm)));
};
return { getCounts, getOrderedTags, getSuggestions };
})();
window.TagService = TagService;
const TagUI = (() => {
// COMMENT: One set of document/window listeners shared by every tag input,
// registered once per page. Previously each createTagInput() added three
// permanent listeners that were never removed — a leak on every form open,
// also retaining detached form DOM.
if (!window.__PF_TAG_UI_GLOBAL_LISTENERS) {
window.__PF_TAG_UI_GLOBAL_LISTENERS = true;
const repositionActive = () => {
const a = window.__pfActiveTagSuggestions;
if (a && a.suggestions.style.display !== 'none') a.position();
};
document.addEventListener('click', (evt) => {
const a = window.__pfActiveTagSuggestions;
if (a && a.suggestions.style.display !== 'none' && !a.suggestions.contains(evt.target)) {
a.suggestions.style.display = 'none';
}
});
window.addEventListener('resize', repositionActive);
window.addEventListener('scroll', repositionActive, true);
}
const createTagInput = ({ initialTags = [] } = {}) => {
const tagsSet = new Set(Array.isArray(initialTags) ? initialTags : []);
const row = createEl('div', { className: `opm-tag-row opm-${getMode()}` });
const pills = createEl('div', { className: 'opm-tags-container' });
const input = createEl('input', { attributes: { type: 'text', placeholder: tt('panel_tags_ph', null, 'Tags') }, className: `opm-tag-input opm-${getMode()}` });
const suggestions = createEl('div', { className: `opm-tag-suggestions opm-${getMode()}`, styles: { display: 'none' } });
let activeIndex = -1; let options = [];
const renderPills = () => {
pills.innerHTML = '';
Array.from(tagsSet).forEach(tag => {
// COMMENT: text node, not innerHTML — tags come from storage/import and may contain markup
const pill = createEl('span', { className: `opm-tag-pill opm-${getMode()}` }, [String(tag)]);
const removeBtn = createEl('button', { className: 'opm-tag-remove', innerHTML: '×' });
removeBtn.addEventListener('click', (e) => {
e.stopPropagation();
tagsSet.delete(tag);
if (pill && pill.parentNode) pill.parentNode.removeChild(pill);
});
pill.appendChild(removeBtn);
pills.appendChild(pill);
});
};
const mountSuggestionsPortal = () => {
const root = document.getElementById(SELECTORS.ROOT) || document.body;
if (suggestions.parentElement !== root) root.appendChild(suggestions);
suggestions.style.position = 'fixed';
suggestions.style.zIndex = '100000';
};
const positionSuggestions = () => {
const rect = row.getBoundingClientRect();
suggestions.style.left = `${Math.max(0, rect.left)}px`;
const spaceAbove = rect.top;
const desiredHeight = Math.min(160, window.innerHeight * 0.4);
if (spaceAbove > desiredHeight + 8) {
suggestions.style.top = `${rect.top}px`;
suggestions.style.transform = 'translateY(-100%)';
} else {
suggestions.style.top = `${rect.bottom}px`;
suggestions.style.transform = 'translateY(2px)';
}
suggestions.style.minWidth = `${Math.max(180, rect.width - 12)}px`;
};
const addTag = (val) => {
const tag = (val || '').trim().toLowerCase().replace(/\s+/g, '-');
if (!tag || tagsSet.has(tag)) return;
tagsSet.add(tag);
renderPills();
activeIndex = -1;
suggestions.style.display = 'none';
};
const refreshSuggestions = async () => {
options = await TagService.getSuggestions({ term: input.value, exclude: tagsSet });
suggestions.innerHTML = '';
options.forEach((t, idx) => {
const item = createEl('div', { className: 'opm-tag-suggestion-item' }, [t]);
if (idx === activeIndex) item.classList.add('active');
item.addEventListener('mousedown', e => { e.preventDefault(); addTag(t); input.value = ''; suggestions.style.display = 'none'; });
suggestions.appendChild(item);
});
if (options.length > 0) {
mountSuggestionsPortal();
positionSuggestions();
suggestions.style.display = 'block';
} else {
suggestions.style.display = 'none';
}
};
input.addEventListener('input', () => {
activeIndex = -1;
const term = input.value.trim();
if (term.length === 0) { suggestions.style.display = 'none'; options = []; return; }
refreshSuggestions();
});
input.addEventListener('keydown', e => {
if (e.key === 'Enter') { e.preventDefault(); if (activeIndex >= 0 && activeIndex < options.length) { addTag(options[activeIndex]); input.value = ''; } else { addTag(input.value); input.value = ''; } suggestions.style.display = 'none'; }
if (e.key === 'ArrowDown') { e.preventDefault(); activeIndex = Math.min(activeIndex + 1, options.length - 1); refreshSuggestions(); }
if (e.key === 'ArrowUp') { e.preventDefault(); activeIndex = Math.max(activeIndex - 1, -1); refreshSuggestions(); }
if (e.key === 'Escape') { suggestions.style.display = 'none'; }
});
input.addEventListener('focus', () => { suggestions.style.display = 'none'; });
input.addEventListener('blur', () => { suggestions.style.display = 'none'; });
// COMMENT: Register this input with the shared global listeners above.
window.__pfActiveTagSuggestions = { suggestions, position: positionSuggestions };
renderPills();
row.append(pills, input);
return { element: row, getTags: () => Array.from(tagsSet) };
};
return { createTagInput };
})();
window.TagUI = TagUI;
const PromptUI = (() => {
const State = {
manuallyOpened: false,
inVariableInputMode: false,
closeTimer: null
};
const Elements = {
createPanelContent() {
return createEl('div', { id: SELECTORS.PANEL_CONTENT });
},
createTagsBar({ tags = [], counts = new Map(), onSelect, selectedTag = 'all' } = {}) {
const bar = createEl('div', { className: `opm-tags-filter-bar opm-${getMode()}` });
window.ScrollVisibilityManager?.observe(bar);
const makePill = (label, isSelected = false) => {
const pill = createEl('button', { className: `opm-tag-pill-filter opm-${getMode()}`, attributes: { 'aria-pressed': String(!!isSelected) } });
pill.textContent = label;
return pill;
};
let current = selectedTag || 'all';
const updateSelected = (nextTag) => {
current = nextTag;
Array.from(bar.children).forEach(child => {
const isSelected = child.dataset && child.dataset.tag === current;
child.setAttribute('aria-pressed', String(isSelected));
});
};
const allPill = makePill('All', (selectedTag || 'all') === 'all');
allPill.dataset.tag = 'all';
allPill.addEventListener('click', e => { e.stopPropagation(); if (typeof onSelect === 'function') onSelect('all'); updateSelected('all'); });
bar.appendChild(allPill);
tags.forEach(tag => {
const count = counts.get(tag) || 0;
const pill = makePill(count > 0 ? `${tag}` : tag, (selectedTag || 'all') === tag);
pill.dataset.tag = tag;
pill.addEventListener('click', e => { e.stopPropagation(); if (typeof onSelect === 'function') onSelect(tag); updateSelected(tag); });
bar.appendChild(pill);
});
return bar;
},
createItemsContainer({ mode = 'list' } = {}) {
const classes = [
SELECTORS.PROMPT_ITEMS_CONTAINER,
'opm-prompt-list-items',
'opm-view-list',
`opm-${getMode()}`
];
if (mode === 'edit') classes.push('opm-edit-mode');
return createEl('div', { className: classes.join(' ') });
},
createPromptItem(prompt) {
const item = createEl('div', {
className: `opm-prompt-list-item opm-${getMode()}`,
eventListeners: {
click: () => PromptUIManager.emitPromptSelect(prompt),
mouseenter: () => {
document.querySelectorAll(`#${SELECTORS.ROOT} .opm-prompt-list-item`).forEach(i => i.classList.remove('opm-keyboard-selected'));
PromptUIManager.cancelCloseTimer();
}
}
});
const text = createEl('div', { styles: { flex: '1' } });
text.textContent = prompt.title;
item.appendChild(text);
// COMMENT: B2 — uuid only; searchable fields go in the in-memory index.
item.dataset.uuid = prompt.uuid;
indexPromptForSearch(prompt);
return item;
},
createEditablePromptItem(prompt, idx, reorder) {
const item = createEl('div', {
className: `opm-prompt-list-item opm-${getMode()}`,
styles: {
justifyContent: 'space-between',
padding: '6px 12px',
margin: '6px 0',
borderRadius: '10px',
gap: '8px'
},
eventListeners: {
click: () => PromptUIManager.emitPromptSelect(prompt),
mouseenter: () => {
document.querySelectorAll(`#${SELECTORS.ROOT} .opm-prompt-list-item`).forEach(i => i.classList.remove('opm-keyboard-selected'));
PromptUIManager.cancelCloseTimer();
}
}
});
item.dataset.index = idx;
// COMMENT: B2 — uuid only; searchable fields go in the in-memory index.
item.dataset.uuid = prompt.uuid;
indexPromptForSearch(prompt);
const dragHandle = createEl('div', {
className: 'opm-drag-handle opm-edit-only',
innerHTML: `
<img
src="${chrome.runtime.getURL('icons/drag_indicator.svg')}"
width="16"
height="16"
alt="Drag handle"
title="Drag to reorder"
style="display: block; opacity: 0.9; filter: ${iconFilter()}"
>
`,
styles: {
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
width: '16px',
height: '16px',
margin: '0',
flex: '0 0 auto',
cursor: 'grab',
userSelect: 'none',
opacity: '0.9'
}
});
reorder?.wireItem(item, idx, dragHandle);
const info = createEl('div', { styles: { display: 'flex', flexDirection: 'column', flex: '1', gap: '2px' } });
const text = createEl('div', { styles: { flex: '0 0 auto' } });
text.textContent = prompt.title;
info.appendChild(text);
const actions = createEl('div', { className: 'opm-edit-only', styles: { display: 'flex', gap: '4px', flex: '0 0 auto' } });
const editIcon = Elements.createIconButton('edit', (e) => { e.stopPropagation(); window.PromptUIManager.showEditForm(prompt); });
const deleteIcon = Elements.createIconButton('delete', (e) => {
e.stopPropagation();
if (confirm(tt('panel_delete_confirm', [prompt.title], 'Delete "' + prompt.title + '"?'))) window.PromptUIManager.deletePrompt(prompt.uuid);
});
actions.append(editIcon, deleteIcon);
item.append(dragHandle, info, actions);
return item;
},
createIconButton(type, onClick) {
return createEl('button', { className: 'opm-icon-button', eventListeners: { click: onClick }, innerHTML: ICON_SVGS[type] || '' });
},
createMenuBar() {
const bar = createEl('div', { styles: { display: 'flex', alignItems: 'center', justifyContent: 'space-evenly', width: '100%' } });
const btns = ['list', 'add', 'edit', 'help', 'settings'];
const actions = {
list: e => { e.stopPropagation(); PromptUIManager.manuallyOpened = true; PanelRouter.mount(PanelView.LIST); },
add: e => { e.stopPropagation(); PromptUIManager.manuallyOpened = true; PanelRouter.mount(PanelView.CREATE); },
edit: e => { e.stopPropagation(); PromptUIManager.manuallyOpened = true; PanelRouter.mount(PanelView.EDIT); },
settings: e => { e.stopPropagation(); PromptUIManager.manuallyOpened = true; PanelRouter.mount(PanelView.SETTINGS); },
help: e => { e.stopPropagation(); PromptUIManager.manuallyOpened = true; PanelRouter.mount(PanelView.HELP); },
};
btns.forEach(type => bar.appendChild(Elements.createIconButton(type, actions[type])));
return bar;
},
createBottomMenu() {
const menu = createEl('div', {
className: `opm-bottom-menu opm-${getMode()}`,
styles: { display: 'flex', flexDirection: 'column', gap: '10px', padding: '10px 10px 5px 10px', borderTop: '1px solid var(--light-border)' }
});
const search = createEl('input', {
id: SELECTORS.PROMPT_SEARCH_INPUT,
className: `opm-search-input opm-${getMode()}`,
attributes: { type: 'text', placeholder: tt('panel_ph_search', null, 'Type to search'), style: 'border-radius: 4px;' }
});
search.addEventListener('input', e => { PromptUIManager.filterPromptItems(e.target.value); });
menu.appendChild(search);
menu.appendChild(Elements.createMenuBar());
return menu;
},
createToggleRow({ labelText, getValue, onToggle }) {
const row = createEl('div', { styles: { display: 'flex', justifyContent: 'space-between', alignItems: 'center' } });
const label = createEl('label', { innerHTML: labelText, styles: { fontSize: '14px' } });
const toggleSwitch = createEl('div', {
className: `opm-toggle-switch opm-${getMode()}`
});
const applyValue = (active) => {
if (active) toggleSwitch.classList.add('active'); else toggleSwitch.classList.remove('active');
};
toggleSwitch.addEventListener('click', e => {
e.stopPropagation();
const nextActive = !toggleSwitch.classList.contains('active');
applyValue(nextActive);
Promise.resolve(onToggle?.(nextActive)).catch(err => console.error('[PromptManager] Toggle handler failed:', err));
});
Promise.resolve(getValue?.())
.then(applyValue)
.catch(err => console.warn('[PromptManager] Failed to initialize toggle state:', err));
row.append(label, toggleSwitch);
return row;
}
};
const Reorder = {
attach(promptsContainer, prompts, onReorder) {
let isDragging = false;
let dragSrcEl = null;
let ghost = null;
let autoScrollTimer = null;
const SCROLL_ZONE_PX = 40;
const SCROLL_SPEED_PX = 8;
const getListItems = () => Array.from(promptsContainer.children).filter(c => c.classList.contains('opm-prompt-list-item'));
const cleanup = () => {
isDragging = false;
if (ghost) { ghost.remove(); ghost = null; }
if (dragSrcEl) {
dragSrcEl.style.opacity = '';
dragSrcEl = null;
}
if (autoScrollTimer) { clearInterval(autoScrollTimer); autoScrollTimer = null; }
document.body.style.cursor = '';
document.removeEventListener('mousemove', handleMouseMove);
document.removeEventListener('mouseup', handleMouseUp);
};
const handleMouseMove = (e) => {
if (!isDragging || !ghost) return;
e.preventDefault();
// Move ghost
const ghostHeight = ghost.offsetHeight;
ghost.style.top = `${e.clientY - (ghostHeight / 2)}px`;
ghost.style.left = `${e.clientX + 10}px`;
// Auto scroll
const rect = promptsContainer.getBoundingClientRect();
if (autoScrollTimer) clearInterval(autoScrollTimer);
autoScrollTimer = null;
if (e.clientY < rect.top + SCROLL_ZONE_PX) {
autoScrollTimer = setInterval(() => { promptsContainer.scrollTop -= SCROLL_SPEED_PX; }, 16);
} else if (e.clientY > rect.bottom - SCROLL_ZONE_PX) {
autoScrollTimer = setInterval(() => { promptsContainer.scrollTop += SCROLL_SPEED_PX; }, 16);
}
// Swap logic
const mouseY = e.clientY;
const items = getListItems();
let target = null;
for (const item of items) {
if (item === dragSrcEl) continue;
const r = item.getBoundingClientRect();
const mid = r.top + (r.height / 2);
if (mouseY < mid) {
target = item;
break;
}
}
if (target) {
if (dragSrcEl.nextElementSibling !== target) {
promptsContainer.insertBefore(dragSrcEl, target);
}
} else {
if (dragSrcEl.nextElementSibling) {
promptsContainer.appendChild(dragSrcEl);
}
}
};
const handleMouseUp = (e) => {
if (!isDragging) return;
const items = getListItems();
const newOrderIndices = items.map(item => parseInt(item.dataset.index, 10));
cleanup();
let changed = false;
for (let i = 0; i < newOrderIndices.length; i++) {
if (newOrderIndices[i] !== i) {
changed = true;
break;
}
}
if (changed) {
const newPrompts = newOrderIndices.map(originalIdx => prompts[originalIdx]);
onReorder(newPrompts);
}
};
const wireItem = (item, index, handle) => {
handle.style.cursor = 'grab';
handle.addEventListener('dragstart', (e) => e.preventDefault());
handle.addEventListener('mousedown', (e) => {
if (e.button !== 0) return;
const mode = window.PromptUIManager?.state?.listMode;
if (mode !== 'edit') return;
e.preventDefault();
e.stopPropagation();
isDragging = true;
dragSrcEl = item;
const rect = item.getBoundingClientRect();
ghost = item.cloneNode(true);
Object.assign(ghost.style, {
position: 'fixed',
top: `${rect.top}px`,
left: `${rect.left}px`,
width: `${rect.width}px`,
height: `${rect.height}px`,
zIndex: '99999',
pointerEvents: 'none',
opacity: '0.95',
boxShadow: '0 8px 20px rgba(0,0,0,0.2)',
transform: 'scale(1.02)',
margin: '0',
transition: 'none',
backgroundColor: getMode() === 'dark' ? 'var(--dark-bg)' : 'var(--light-bg)'
});
const root = document.getElementById(SELECTORS.ROOT);
if (root) root.appendChild(ghost);
else document.body.appendChild(ghost);
item.style.opacity = '0.0';
document.body.style.cursor = 'grabbing';
handle.style.cursor = 'grabbing';
document.addEventListener('mousemove', handleMouseMove);
document.addEventListener('mouseup', handleMouseUp);
});
};
return { wireItem };
}
};
const Views = {
createPromptForm({ initialTitle = '', initialContent = '', submitLabel = null, onSubmit, initialCategory = null, initialLanguage = null }) {
const form = createEl('div', { className: `opm-form-container opm-create-form opm-${getMode()}`, styles: { padding: '0', display: 'flex', flexDirection: 'column', gap: '4px' } });
const titleIn = createEl('input', { attributes: { placeholder: tt('panel_ph_title', null, 'Prompt Title') }, className: `opm-input-field opm-${getMode()}`, styles: { borderRadius: '4px' } });
const contentArea = createEl('textarea', {
attributes: { placeholder: tt('panel_ph_write', null, 'Write your prompt. Use hashtags for #variables#') },
className: `opm-textarea-field opm-${getMode()}`,
styles: { flex: '1 1 auto', minHeight: '0', height: 'auto' }
});
titleIn.value = initialTitle;
contentArea.value = initialContent;
// Category select — COMMENT: value stays the canonical English name
// (save contract); the LABEL is localised (v3 D-IV).
const catSelect = createEl('select', { className: `opm-input-field opm-${getMode()}`, styles: { borderRadius: '4px', fontSize: '13px' } });
catSelect.appendChild(createEl('option', { attributes: { value: '' } }, [tt('panel_uncategorized', null, 'Uncategorized')]));
for (const c of (window.PFCategories || [])) {
const o = createEl('option', { attributes: { value: c.name } }, [tt(`cat_${c.id}`, null, c.name)]);
if (c.name === initialCategory) o.selected = true;
catSelect.appendChild(o);
}
// COMMENT: v3 feature D — language select; "Auto" resolves via offline
// detection (window.PFLanguage) at save time.
const langSelect = createEl('select', { className: `opm-input-field opm-${getMode()}`, styles: { borderRadius: '4px', fontSize: '13px' } });
langSelect.appendChild(createEl('option', { attributes: { value: 'auto' } }, ['Auto-detect language']));
if (window.PFLanguage) {
for (const l of window.PFLanguage.SUPPORTED_LANGUAGES) {
const o = createEl('option', { attributes: { value: l.code } }, [l.label]);
if (l.code === initialLanguage) o.selected = true;
langSelect.appendChild(o);
}
}
const saveBtn = createEl('button', { innerHTML: submitLabel || tt('panel_save', null, 'Save'), className: `opm-button opm-${getMode()}` });
saveBtn.addEventListener('click', async e => {
e.stopPropagation();
const t = titleIn.value.trim(), c = contentArea.value.trim();
if (!t || !c) { alert(tt('panel_fill_both', null, 'Please fill in both title and content.')); return; }
const cat = catSelect.value || null;
const language = langSelect.value === 'auto'
? (window.PFLanguage ? window.PFLanguage.detectLanguage(c).code : null)
: langSelect.value;
if (typeof onSubmit === 'function') await onSubmit({ title: t, content: c, category: cat, language });
});
form.append(titleIn, contentArea, catSelect, langSelect, saveBtn);
form.addEventListener('click', e => e.stopPropagation());
return form;
},
renderPromptList(prompts = [], { mode = 'list' } = {}) {
const content = Elements.createPanelContent();
const tagsHost = createEl('div', { className: `opm-tags-filter-host opm-${getMode()}`, styles: { display: 'none' } });
content.appendChild(tagsHost);
const itemsContainer = Elements.createItemsContainer({ mode });
const reorder = Reorder.attach(
itemsContainer,
prompts,
async (newPrompts) => {
prompts.splice(0, prompts.length, ...newPrompts);
Array.from(itemsContainer.children)
.filter(node => node.classList?.contains('opm-prompt-list-item'))
.forEach((node, idx) => { node.dataset.index = idx; });
if (window.PromptUIManager?.state?.listMode === 'edit') {
window.PromptUIManager.requestListRefreshSuppression?.();
}
await window.PromptStorageManager.setPrompts(newPrompts);
}
);
prompts.forEach((p, idx) => {
const item = Elements.createEditablePromptItem(p, idx, reorder);
itemsContainer.appendChild(item);
});
content.appendChild(itemsContainer);
content.appendChild(Elements.createBottomMenu());
(async () => {
try {
const enableTags = await window.PromptStorageManager.getEnableTags();
if (!enableTags) { tagsHost.style.display = 'none'; return; }
const counts = await TagService.getCounts(prompts);
if (counts.size === 0) { tagsHost.style.display = 'none'; return; }
const ordered = await TagService.getOrderedTags(counts);
let persisted = 'all';
try { persisted = (await window.PromptStorageManager.getActiveTagFilter() || 'all').toLowerCase(); } catch (_) { persisted = 'all'; }
const prev = (window.PromptUIManager.activeTagFilter || persisted || 'all').toLowerCase();
const selected = prev !== 'all' && counts.has(prev) ? prev : 'all';
window.PromptUIManager.activeTagFilter = selected;
const bar = Elements.createTagsBar({
tags: ordered,
counts,
selectedTag: selected,
onSelect: (tag) => { window.PromptUIManager.filterByTag(tag); }
});
tagsHost.replaceWith(bar);
window.PromptUIManager.filterByTag(selected);
window.ScrollVisibilityManager?.observe(bar);
} catch (_) { tagsHost.style.display = 'none'; }
})();
return content;
},
async createPromptCreationForm(prefill = '') {
const search = document.getElementById(SELECTORS.PROMPT_SEARCH_INPUT);
if (search) search.style.display = 'none';
const enableTags = await window.PromptStorageManager.getEnableTags();
const form = createEl('div', { className: `opm-form-container opm-${getMode()}`, styles: { padding: '0', display: 'flex', flexDirection: 'column', gap: '8px' } });
const titleIn = createEl('input', { attributes: { placeholder: tt('panel_ph_title', null, 'Prompt Title') }, className: `opm-input-field opm-${getMode()}`, styles: { borderRadius: '4px' } });
const contentArea = createEl('textarea', {
attributes: { placeholder: tt('panel_ph_enter', null, 'Enter your prompt here. Add variables with #examplevariable#') },
className: `opm-textarea-field opm-${getMode()}`,
styles: { flex: '1 1 auto', minHeight: '0', height: 'auto' }
});
titleIn.value = '';
contentArea.value = prefill || '';
// Category select — value = English name (save contract), label localised.
const catSelect = createEl('select', { className: `opm-input-field opm-${getMode()}`, styles: { borderRadius: '4px', fontSize: '13px' } });
catSelect.appendChild(createEl('option', { attributes: { value: '' } }, [tt('panel_uncategorized', null, 'Uncategorized')]));
for (const c of (window.PFCategories || [])) catSelect.appendChild(createEl('option', { attributes: { value: c.name } }, [tt(`cat_${c.id}`, null, c.name)]));
// COMMENT: v3 feature D — language select; "Auto" resolves via offline
// detection at save time.
const langSelect = createEl('select', { className: `opm-input-field opm-${getMode()}`, styles: { borderRadius: '4px', fontSize: '13px' } });
langSelect.appendChild(createEl('option', { attributes: { value: 'auto' } }, ['Auto-detect language']));
if (window.PFLanguage) {
for (const l of window.PFLanguage.SUPPORTED_LANGUAGES) {
langSelect.appendChild(createEl('option', { attributes: { value: l.code } }, [l.label]));
}
}
let tagsBlock = null;
let tagInput = null;
if (enableTags) {
const label = createEl('label', { styles: { fontSize: '12px', fontWeight: 'bold' } });
tagInput = TagUI.createTagInput();
tagsBlock = createEl('div');
tagsBlock.append(label, tagInput.element);
}
const saveBtn = createEl('button', { innerHTML: tt('panel_create', null, 'Create Prompt'), className: `opm-button opm-${getMode()}` });
saveBtn.addEventListener('click', async e => {
e.stopPropagation();
const t = titleIn.value.trim(), c = contentArea.value.trim();
if (!t || !c) { alert(tt('panel_fill_both', null, 'Please fill in both title and content.')); return; }
const tags = enableTags && tagInput ? tagInput.getTags() : [];
const cat = catSelect.value || null;
const language = langSelect.value === 'auto'
? (window.PFLanguage ? window.PFLanguage.detectLanguage(c).code : null)
: langSelect.value;
const res = await window.PromptStorageManager.savePrompt({ title: t, content: c, tags, category: cat, language });
if (!res.success) { alert(tt('panel_save_error', null, 'Error saving prompt.')); return; }
window.PanelRouter.mount(window.PanelView.LIST);
});
form.append(titleIn, contentArea, catSelect, langSelect);
if (tagsBlock) form.append(tagsBlock);
form.append(saveBtn);
form.addEventListener('click', e => e.stopPropagation());
return form;
},
createSettingsForm() {
const form = createEl('div', { className: `opm-form-container opm-${getMode()}`, styles: { padding: '12px', display: 'flex', flexDirection: 'column', gap: '8px' } });
const title = createEl('div', { styles: { fontWeight: 'bold', fontSize: '16px', marginBottom: '10px' }, innerHTML: tt('panel_settings_title', null, 'Settings') });
const settings = createEl('div', { styles: { display: 'flex', flexDirection: 'column', gap: '12px' } });
settings.appendChild(Elements.createToggleRow({
labelText: tt('panel_hot_corner', null, 'Hot Corner Mode'),
getValue: async () => (await window.PromptStorageManager.getDisplayMode()) === 'hotCorner',
onToggle: async (active) => {
const newMode = active ? 'hotCorner' : 'standard';
await window.PromptStorageManager.saveDisplayMode(newMode);
await window.PromptUIManager.refreshDisplayMode();
}
}));
settings.appendChild(Elements.createToggleRow({
labelText: 'Append prompts to text',
getValue: async () => await window.PromptStorageManager.getDisableOverwrite(),
onToggle: async (active) => { await window.PromptStorageManager.saveDisableOverwrite(active); }
}));
settings.appendChild(Elements.createToggleRow({
labelText: tt('panel_enable_tags', null, 'Enable tags'),
getValue: async () => await window.PromptStorageManager.getEnableTags(),
onToggle: async (active) => { await window.PromptStorageManager.saveEnableTags(active); }
}));
settings.appendChild(Elements.createToggleRow({
labelText: tt('panel_force_dark', null, 'Force Dark Mode'),
getValue: async () => {
const enabled = await window.PromptStorageManager.getForceDarkMode();
window.isDarkModeForced = !!enabled;
return enabled;
},
onToggle: async (active) => {
window.isDarkModeForced = active;
await window.PromptStorageManager.saveForceDarkMode(active);
window.PromptUIManager.updateThemeForUI();
}
}));
// Ollama / Full Settings link
const fullSettingsBtn = createEl('button', {
innerHTML: tt('panel_open_full', null, 'Open Full Settings ↗'),
className: `opm-button opm-${getMode()}`,
styles: { marginTop: '4px' }
});
fullSettingsBtn.addEventListener('click', e => {
e.stopPropagation();
chrome.runtime.sendMessage({ type: 'OPEN_APP_TAB', path: '#/settings' });
});
settings.appendChild(fullSettingsBtn);
const hint = createEl('div', {
styles: { fontSize: '11px', color: getMode() === 'dark' ? '#aaa' : '#666', marginTop: '2px' },
innerHTML: 'Ollama config, model selection, and integrations are in full settings.'
});
settings.appendChild(hint);
const dataSectionTitle = createEl('div', { styles: { fontWeight: 'bold', fontSize: '14px', marginTop: '6px' }, innerHTML: tt('panel_prompt_mgmt', null, 'Prompt Management') });
const dataActions = createEl('div', { styles: { display: 'flex', gap: '8px' } });
const exportBtn = createEl('button', { innerHTML: tt('panel_export', null, 'Export'), className: `opm-button opm-${getMode()}` });
exportBtn.addEventListener('click', async e => {
e.stopPropagation();
try {
const prompts = await window.PromptStorageManager.getPrompts();
const json = JSON.stringify(prompts, null, 2);
const blob = new Blob([json], { type: 'application/json' });
const url = URL.createObjectURL(blob);
const a = createEl('a', { attributes: { href: url, download: `prompts-${new Date().toISOString().split('T')[0]}.json` } });
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
URL.revokeObjectURL(url);
} catch (err) {
alert('Export failed.');
}
});
const importBtn = createEl('button', { innerHTML: tt('panel_import', null, 'Import'), className: `opm-button opm-${getMode()}` });
importBtn.addEventListener('click', async e => {
e.stopPropagation();
const fileInput = createEl('input', { attributes: { type: 'file', accept: '.json' } });
fileInput.addEventListener('change', async event => {
const file = event.target.files[0];
if (file) {
try {
const text = await file.text();
const imported = JSON.parse(text);
if (!Array.isArray(imported)) throw new Error('Invalid format');
const merged = await window.PromptStorageManager.mergeImportedPrompts(imported);
window.PromptUIManager.refreshPromptList(merged);
importBtn.textContent = tt('panel_import_success', null, 'Import successful!');
setTimeout(() => importBtn.textContent = tt('panel_import', null, 'Import'), window.IMPORT_SUCCESS_RESET_MS || 2000);
} catch (err) {
alert('Invalid JSON file format.');
}
}
});
fileInput.click();
});
dataActions.append(exportBtn, importBtn);
const deleteAllBtn = createEl('button', {
innerHTML: tt('panel_delete_all', null, 'Delete all prompts'),
className: `opm-button opm-${getMode()}`,
styles: { backgroundColor: '#9CA3AF', marginTop: '4px' }
});
deleteAllBtn.addEventListener('click', async e => {
e.stopPropagation();
if (!confirm('Delete ALL prompts? This cannot be undone.')) return;
try {
await window.PromptStorageManager.setPrompts([]);
window.PanelRouter.mount(window.PanelView.SETTINGS);
} catch (_) {
alert('Failed to delete prompts.');
}
});
const tagMgmtTitle = createEl('div', { styles: { fontWeight: 'bold', fontSize: '14px', marginTop: '12px', display: 'none' }, innerHTML: tt('panel_tag_mgmt', null, 'Tag management') });
const tagMgmtContainer = createEl('div', { styles: { display: 'none', flexDirection: 'column', gap: '6px' } });
(async () => {
try {
const enableTags = await window.PromptStorageManager.getEnableTags();
if (!enableTags) { tagMgmtTitle.style.display = 'none'; tagMgmtContainer.style.display = 'none'; return; }
tagMgmtTitle.style.display = '';
tagMgmtContainer.style.display = '';
let counts = await TagService.getCounts();
const row = createEl('div', { className: 'opm-tags-mgmt-container' });
let finalOrder = await TagService.getOrderedTags(counts);
const placeholder = createEl('span', { className: `opm-tag-pill opm-${getMode()} opm-drop-placeholder`, innerHTML: ' ' });
let dragFromIndex = null;
const pillsOnly = () => Array.from(row.children).filter(n => n.classList && n.classList.contains('opm-tag-pill') && n !== placeholder);
const insertPlaceholderAt = (clientX, clientY) => {
const pills = pillsOnly();
if (pills.length === 0) { row.appendChild(placeholder); return; }
let inserted = false;
for (let i = 0; i < pills.length; i++) {
const rect = pills[i].getBoundingClientRect();
if (clientY >= rect.top && clientY <= rect.bottom) {
placeholder.style.width = `${rect.width}px`;
const before = clientX < rect.left + rect.width / 2;
if (before) {
if (pills[i].previousSibling !== placeholder) row.insertBefore(placeholder, pills[i]);
} else {
if (pills[i].nextSibling !== placeholder) row.insertBefore(placeholder, pills[i].nextSibling);
}
inserted = true;
break;
}
}
if (!inserted) {
const first = pills[0];
const last = pills[pills.length - 1];
const firstRect = first.getBoundingClientRect();
const lastRect = last.getBoundingClientRect();
placeholder.style.width = `${(firstRect || lastRect).width}px`;
if (clientY < firstRect.top) {
if (first.previousSibling !== placeholder) row.insertBefore(placeholder, first);
} else {
if (last.nextSibling !== placeholder) row.insertBefore(placeholder, last.nextSibling);
}
}
};
row.addEventListener('dragover', e => {
e.preventDefault();
e.dataTransfer.dropEffect = 'move';
insertPlaceholderAt(e.clientX, e.clientY);
});
row.addEventListener('drop', async e => {
e.preventDefault();
const nodes = Array.from(row.children);
let to = 0;
for (let i = 0; i < nodes.length; i++) {
const node = nodes[i];
if (node === placeholder) break;
if (node.classList && node.classList.contains('opm-tag-pill')) to++;
}
let from = dragFromIndex;
if (from === null) {
const txt = e.dataTransfer.getData('text/plain');
const parsed = parseInt(txt, 10);
from = Number.isNaN(parsed) ? null : parsed;
}
if (from === null || from === to) {
if (placeholder.parentNode) placeholder.parentNode.removeChild(placeholder);
dragFromIndex = null;
return;
}
if (from < to) to = to - 1;
const moved = finalOrder.splice(from, 1)[0];
finalOrder.splice(Math.max(0, Math.min(finalOrder.length, to)), 0, moved);
await window.PromptStorageManager.saveTagsOrder(finalOrder);
if (placeholder.parentNode) placeholder.parentNode.removeChild(placeholder);
dragFromIndex = null;
render();
});
const render = () => {
row.innerHTML = '';
finalOrder.forEach((tag, idx) => {
const n = counts.get(tag) || 0;
const pill = createEl('span', { className: `opm-tag-pill opm-${getMode()}` });
const handle = createEl('span', {
styles: { display: 'inline-flex', alignItems: 'center', marginRight: '6px', cursor: 'grab' },
innerHTML: `
<img
src="${chrome.runtime.getURL('icons/drag_indicator.svg')}"
width="14"
height="14"
alt="Drag"
title="Drag to reorder"
style="opacity: 0.9; filter: ${iconFilter()}"
>
`
});
handle.setAttribute('draggable', 'true');
handle.addEventListener('dragstart', e => {
e.stopPropagation();
e.dataTransfer.effectAllowed = 'move';
e.dataTransfer.setData('text/plain', String(idx));
dragFromIndex = idx;
try {
const rect = pill.getBoundingClientRect();
const offsetX = Math.min(8, rect.width / 2);
const offsetY = Math.min(8, rect.height / 2);
e.dataTransfer.setDragImage(pill, offsetX, offsetY);
} catch (_) {}
});
handle.addEventListener('dragend', () => {
if (placeholder.parentNode) placeholder.parentNode.removeChild(placeholder);
dragFromIndex = null;
});
const label = createEl('span', {}, [`${tag} (${n})`]);
const removeBtn = createEl('button', { innerHTML: '×', styles: { marginLeft: '6px', border: 'none', background: 'transparent', cursor: 'pointer', fontSize: '14px', lineHeight: '1' } });
removeBtn.addEventListener('click', async (e) => {
e.stopPropagation();
if (!confirm(tt('panel_remove_tag_confirm', [tag], `Remove tag "${tag}" from all prompts?`))) return;
try {
const prompts = await window.PromptStorageManager.getPrompts();
const updated = prompts.map(p => {
const nextTags = Array.isArray(p.tags) ? p.tags.filter(t => t !== tag) : [];
return { ...p, tags: nextTags };
});
await window.PromptStorageManager.setPrompts(updated);
counts = await TagService.getCounts(updated);
finalOrder = finalOrder.filter(t => t !== tag);
await window.PromptStorageManager.saveTagsOrder(finalOrder);
render();
} catch (_) { /* ignore */ }
});
pill.append(handle, label, removeBtn);
row.appendChild(pill);
});
};
render();
tagMgmtContainer.appendChild(row);
} catch (_) { /* ignore */ }
})();
form.append(title, settings, dataSectionTitle, dataActions, deleteAllBtn, tagMgmtTitle, tagMgmtContainer);
return form;
},
};
const Behaviors = {
showList(listEl) {
showEl(listEl);
},
hideList(listEl) {
hideEl(listEl);
},
startCloseTimer(listEl, onClose) {
if (State.closeTimer) clearTimeout(State.closeTimer);
State.closeTimer = setTimeout(() => {
try { if (typeof onClose === 'function') onClose(); } finally {
Behaviors.hideList(listEl);
State.closeTimer = null;
}
}, window.PROMPT_CLOSE_DELAY || 10000);