-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpopup.js
More file actions
1609 lines (1386 loc) · 47.2 KB
/
Copy pathpopup.js
File metadata and controls
1609 lines (1386 loc) · 47.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
// ============================================
// CONSTANTS & CONFIGURATION
// ============================================
const CONFIG = {
AUDIO_VOLUME: 0.5,
TAG_MAX_LENGTH: 22,
DEBOUNCE_DELAY: 300,
TRASH_CAP: 50, // max items kept in the trash (oldest are purged)
UNDO_DURATION: 2500, // how long the undo toast stays up (ms)
DONATE_PROMPT_CHANCE: 0.35, // chance to show the donate callout on open
DONATE_PROMPT_COOLDOWN: 3 * 60 * 60 * 1000, // min time between prompts (ms)
STORAGE_KEYS: {
VIDEOS: 'savedVideos',
DELETED: 'deletedVideos',
SOUND: 'soundEnabled',
SUPPORTER: 'supporter',
LAST_PROMPT: 'lastDonatePrompt',
HIDE_JM_BANNER: 'hideJobsMatchBanner',
REV: 'wleRev'
},
WRITE_ATTEMPTS: 6,
// Peppered SHA-256 of supporter unlock material. Plaintext is not in this repository.
UNLOCK: {
p: '13c7fd3a9477bf036da5c0d02bb1dc85',
d: ['5fa8fb99e05a8273b4214a4ca1e2ad01', '4916f0d411ef0b67ac58851273d0363a']
}
};
// ============================================
// AUDIO MANAGEMENT (Singleton Pattern)
// ============================================
const AudioManager = {
clickAudio: null,
init() {
if (!this.clickAudio) {
this.clickAudio = new Audio('sounds/click.wav');
this.clickAudio.volume = CONFIG.AUDIO_VOLUME;
}
return this.clickAudio;
},
play(soundEnabled) {
if (!soundEnabled) return;
const audio = this.init();
audio.currentTime = 0;
audio.play().catch(e => console.warn("Audio play blocked:", e));
},
cleanup() {
if (this.clickAudio) {
this.clickAudio.pause();
this.clickAudio.currentTime = 0;
this.clickAudio = null;
}
}
};
// ============================================
// DOM ELEMENT CACHE
// ============================================
const DOMCache = {
soundBtn: null,
tagSearchInput: null,
videoList: null,
tutorial: null,
settingsModal: null,
viewTabs: null,
toast: null,
trashActions: null,
emptyTrashBtn: null,
searchWrap: null,
donateBtn: null,
donateCallout: null,
scrollContainer: null,
jmBanner: null,
hideBannerRow: null,
hideBannerSwitch: null,
hideBannerHint: null,
supporterUnlock: null,
supporterCodeInput: null,
supporterUnlockBtn: null,
supporterUnlockStatus: null,
init() {
this.soundBtn = document.getElementById('toggle-sound');
this.tagSearchInput = document.getElementById('tag-search');
this.videoList = document.getElementById('video-list');
this.tutorial = document.getElementById('tutorial');
this.settingsModal = document.getElementById('settings-modal');
this.viewTabs = document.getElementById('view-tabs');
this.toast = document.getElementById('wle-toast');
this.trashActions = document.getElementById('trash-actions');
this.emptyTrashBtn = document.getElementById('empty-trash');
this.searchWrap = document.querySelector('.searchbar-wrap');
this.donateBtn = document.getElementById('ko-fi-button');
this.donateCallout = document.getElementById('donate-callout');
this.scrollContainer = document.querySelector('main');
this.jmBanner = document.getElementById('jobsmatch-banner');
this.hideBannerRow = document.getElementById('hide-banner-row');
this.hideBannerSwitch = document.getElementById('toggle-hide-banner');
this.hideBannerHint = document.getElementById('hide-banner-hint');
this.supporterUnlock = document.getElementById('supporter-unlock');
this.supporterCodeInput = document.getElementById('supporter-code');
this.supporterUnlockBtn = document.getElementById('supporter-unlock-btn');
this.supporterUnlockStatus = document.getElementById('supporter-unlock-status');
}
};
// ============================================
// STATE MANAGEMENT
// ============================================
const AppState = {
soundEnabled: true,
tagQuery: '',
tagQueryMode: 'contains',
draggedItemIndex: null,
view: 'active', // 'active' | 'archive' | 'trash'
supporter: false,
hideJobsMatchBanner: false,
setSoundEnabled(value) {
this.soundEnabled = value;
chrome.storage.local.set({ [CONFIG.STORAGE_KEYS.SOUND]: value });
},
setTagQuery(value, mode = 'contains') {
this.tagQuery = value.trim().toLowerCase();
this.tagQueryMode = mode;
},
setView(view) {
this.view = view;
}
};
// ============================================
// DRAG AUTO-SCROLL
// Native HTML5 drag doesn't scroll the list; when the pointer nears the top
// or bottom edge of the scroll container we nudge it, so items can be dragged
// beyond the currently visible area.
// ============================================
const DragScroller = {
raf: null,
pointerY: 0,
active: false,
EDGE: 55, // px hot-zone at top/bottom
SPEED: 14, // max px scrolled per frame
start() {
if (this.active) return;
this.active = true;
this.raf = requestAnimationFrame(() => this.tick());
},
update(y) {
this.pointerY = y;
},
stop() {
this.active = false;
if (this.raf) {
cancelAnimationFrame(this.raf);
this.raf = null;
}
},
tick() {
if (!this.active) {
this.raf = null;
return;
}
const c = DOMCache.scrollContainer;
if (c) {
const rect = c.getBoundingClientRect();
// The top of the list is overlaid by the sticky tabs + searchbar, so the
// real top boundary of the hot-zone is the BOTTOM of that sticky header —
// otherwise the upper hot-zone hides behind it and never triggers.
let topBound = rect.top;
const header = (DOMCache.searchWrap && DOMCache.searchWrap.offsetParent !== null)
? DOMCache.searchWrap
: DOMCache.viewTabs;
if (header) {
topBound = Math.max(topBound, header.getBoundingClientRect().bottom);
}
const top = this.pointerY - topBound;
const bottom = rect.bottom - this.pointerY;
let dy = 0;
if (top < this.EDGE) {
dy = -Math.ceil(Math.min(1, (this.EDGE - top) / this.EDGE) * this.SPEED);
} else if (bottom < this.EDGE) {
dy = Math.ceil(Math.min(1, (this.EDGE - bottom) / this.EDGE) * this.SPEED);
}
if (dy) c.scrollTop += dy;
}
this.raf = requestAnimationFrame(() => this.tick());
}
};
// ============================================
// UTILITY FUNCTIONS
// ============================================
const Utils = {
colorFromTagName(name) {
const s = String(name || '').trim().toLowerCase();
let hash = 0;
for (let i = 0; i < s.length; i++) {
hash = (hash * 31 + s.charCodeAt(i)) | 0;
}
const h = Math.abs(hash) % 360;
return `hsl(${h} 70% 45%)`;
},
/**
* Normalize video object structure.
* IMPORTANT: tag colors are ALWAYS recomputed from the tag name and never
* trusted from storage — this keeps imported data safe (a hostile `color`
* field such as `url(...)` could otherwise trigger a network request).
* Uses Utils.colorFromTagName (not this.) because it runs as a .map() callback.
*/
normalizeVideo(video) {
if (!video || typeof video !== 'object') {
return null;
}
const tags = Array.isArray(video?.tags) ? video.tags : [];
const normalizedTags = tags
.filter((t) => t && typeof t.name === 'string' && t.name.trim().length > 0)
.map((t) => ({
name: String(t.name).trim(),
color: Utils.colorFromTagName(t.name),
}));
return {
...video,
title: video.title || 'Untitled Video',
url: video.url || '',
tags: normalizedTags,
watched: video.watched === true,
watchedAt: typeof video.watchedAt === 'number' ? video.watchedAt : null,
savedAt: typeof video.savedAt === 'number' ? video.savedAt : null,
};
},
debounce(func, wait) {
let timeout;
return function executedFunction(...args) {
const later = () => {
clearTimeout(timeout);
func(...args);
};
clearTimeout(timeout);
timeout = setTimeout(later, wait);
};
},
createBtnIcon(src, alt = '') {
const img = document.createElement('img');
img.className = 'btn-icon';
img.src = src;
img.alt = alt;
img.decoding = 'async';
img.loading = 'lazy';
return img;
}
};
// ============================================
// STORAGE OPERATIONS
// ============================================
const StorageManager = {
_queue: Promise.resolve(),
enqueue(fn) {
const next = this._queue.then(fn, fn);
this._queue = next.catch((error) => {
console.error('Storage queue error:', error);
});
return next;
},
getRaw(defaults) {
return new Promise((resolve, reject) => {
chrome.storage.local.get(defaults, (data) => {
if (chrome.runtime.lastError) reject(chrome.runtime.lastError);
else resolve(data);
});
});
},
setRaw(values) {
return new Promise((resolve, reject) => {
chrome.storage.local.set(values, () => {
if (chrome.runtime.lastError) reject(chrome.runtime.lastError);
else resolve();
});
});
},
normalizeList(videos) {
return (videos || [])
.map((v) => Utils.normalizeVideo(v))
.filter((v) => v !== null);
},
normalizeDeleted(deleted) {
return (deleted || [])
.map((v) => {
const norm = Utils.normalizeVideo(v);
if (!norm) return null;
norm.deletedAt = typeof v.deletedAt === 'number' ? v.deletedAt : Date.now();
norm._idx = typeof v._idx === 'number' ? v._idx : null;
return norm;
})
.filter((v) => v !== null);
},
async getVideos() {
try {
const data = await this.getRaw({ [CONFIG.STORAGE_KEYS.VIDEOS]: [] });
return this.normalizeList(data[CONFIG.STORAGE_KEYS.VIDEOS]);
} catch (error) {
console.error('Storage read error:', error);
return [];
}
},
async getDeleted() {
try {
const data = await this.getRaw({ [CONFIG.STORAGE_KEYS.DELETED]: [] });
return this.normalizeDeleted(data[CONFIG.STORAGE_KEYS.DELETED]);
} catch (error) {
console.error('Storage read error:', error);
return [];
}
},
notifyWriteError(error) {
console.error('Storage write error:', error);
const msg = String(error && (error.message || error));
showToast(/quota/i.test(msg) ? 'Could not save — storage may be full' : 'Could not save list');
},
/**
* Read-modify-write both lists in one set(). Retries if another writer
* changed storage between the snapshot and the write.
*/
async mutateLists(mutator) {
return this.enqueue(async () => {
const keys = {
[CONFIG.STORAGE_KEYS.VIDEOS]: [],
[CONFIG.STORAGE_KEYS.DELETED]: [],
[CONFIG.STORAGE_KEYS.REV]: 0
};
for (let attempt = 0; attempt < CONFIG.WRITE_ATTEMPTS; attempt++) {
const data = await this.getRaw(keys);
const snapV = JSON.stringify(data[CONFIG.STORAGE_KEYS.VIDEOS] || []);
const snapD = JSON.stringify(data[CONFIG.STORAGE_KEYS.DELETED] || []);
const rev = data[CONFIG.STORAGE_KEYS.REV] || 0;
const ctx = {
videos: this.normalizeList(data[CONFIG.STORAGE_KEYS.VIDEOS]),
deleted: this.normalizeDeleted(data[CONFIG.STORAGE_KEYS.DELETED]),
result: undefined
};
mutator(ctx);
const latest = await this.getRaw(keys);
if (
JSON.stringify(latest[CONFIG.STORAGE_KEYS.VIDEOS] || []) !== snapV ||
JSON.stringify(latest[CONFIG.STORAGE_KEYS.DELETED] || []) !== snapD ||
(latest[CONFIG.STORAGE_KEYS.REV] || 0) !== rev
) {
await new Promise((r) => setTimeout(r, 16 * (attempt + 1)));
continue;
}
await this.setRaw({
[CONFIG.STORAGE_KEYS.VIDEOS]: ctx.videos,
[CONFIG.STORAGE_KEYS.DELETED]: ctx.deleted,
[CONFIG.STORAGE_KEYS.REV]: rev + 1
});
return ctx.result;
}
throw new Error('Storage write conflict');
});
},
async updateVideoByUrl(url, updates) {
try {
return await this.mutateLists((ctx) => {
const idx = ctx.videos.findIndex((v) => v.url === url);
if (idx === -1) {
ctx.result = false;
return;
}
ctx.videos[idx] = { ...ctx.videos[idx], ...updates };
ctx.result = true;
});
} catch (error) {
this.notifyWriteError(error);
return false;
}
},
async toggleWatched(url) {
try {
return await this.mutateLists((ctx) => {
const idx = ctx.videos.findIndex((v) => v.url === url);
if (idx === -1) {
ctx.result = { ok: false };
return;
}
const watched = !ctx.videos[idx].watched;
ctx.videos[idx] = {
...ctx.videos[idx],
watched,
watchedAt: watched ? Date.now() : null
};
ctx.result = { ok: true, watched };
});
} catch (error) {
this.notifyWriteError(error);
return { ok: false };
}
},
async softDelete(urls) {
try {
return await this.mutateLists((ctx) => {
const urlSet = new Set(urls);
const now = Date.now();
const moved = [];
const remaining = [];
ctx.videos.forEach((v, i) => {
if (urlSet.has(v.url)) {
moved.push({ ...v, deletedAt: now, _idx: i });
} else {
remaining.push(v);
}
});
if (moved.length === 0) {
ctx.result = [];
return;
}
ctx.videos = remaining;
ctx.deleted = [...moved, ...ctx.deleted].slice(0, CONFIG.TRASH_CAP);
ctx.result = moved.map((m) => m.url);
});
} catch (error) {
this.notifyWriteError(error);
return [];
}
},
async restore(urls) {
try {
return await this.mutateLists((ctx) => {
const urlSet = new Set(urls);
const toRestore = ctx.deleted.filter((d) => urlSet.has(d.url));
const remainingTrash = ctx.deleted.filter((d) => !urlSet.has(d.url));
toRestore.sort((a, b) => (a._idx ?? Number.MAX_SAFE_INTEGER) - (b._idx ?? Number.MAX_SAFE_INTEGER));
toRestore.forEach((d) => {
const clean = { ...d };
delete clean.deletedAt;
delete clean._idx;
const pos = typeof d._idx === 'number'
? Math.min(Math.max(d._idx, 0), ctx.videos.length)
: ctx.videos.length;
ctx.videos.splice(pos, 0, clean);
});
ctx.deleted = remainingTrash;
ctx.result = true;
});
} catch (error) {
this.notifyWriteError(error);
return false;
}
},
async permanentDelete(urls) {
try {
return await this.mutateLists((ctx) => {
const urlSet = new Set(urls);
ctx.deleted = ctx.deleted.filter((d) => !urlSet.has(d.url));
ctx.result = true;
});
} catch (error) {
this.notifyWriteError(error);
return false;
}
},
async emptyTrash() {
try {
return await this.mutateLists((ctx) => {
ctx.deleted = [];
ctx.result = true;
});
} catch (error) {
this.notifyWriteError(error);
return false;
}
},
async reorder(fromIndex, toIndex) {
try {
return await this.mutateLists((ctx) => {
if (
fromIndex < 0 ||
toIndex < 0 ||
fromIndex >= ctx.videos.length
) {
ctx.result = false;
return;
}
const [item] = ctx.videos.splice(fromIndex, 1);
if (!item) {
ctx.result = false;
return;
}
const dest = Math.min(toIndex, ctx.videos.length);
ctx.videos.splice(dest, 0, item);
ctx.result = true;
});
} catch (error) {
this.notifyWriteError(error);
return false;
}
},
async getAllTagNames() {
const videos = await this.getVideos();
const seen = new Map();
videos.forEach((v) => {
(v.tags || []).forEach((t) => {
const key = t.name.toLowerCase();
if (!seen.has(key)) seen.set(key, t.name);
});
});
return [...seen.values()];
}
};
// ============================================
// VIDEO ITEM CREATION
// ============================================
const VideoItemFactory = {
/**
* @param {object} video
* @param {number} index position in the full saved-videos array (for drag reorder)
* @param {'active'|'archive'|'trash'} mode
*/
create(video, index, mode = 'active') {
const li = document.createElement('li');
li.className = 'video-item';
li.dataset.url = video.url;
li.dataset.index = String(index);
const editable = mode !== 'trash';
const canDrag = mode === 'active' && !AppState.tagQuery;
li.draggable = canDrag;
if (mode === 'active' && AppState.tagQuery) li.classList.add('drag-disabled');
const { row, tagAddBtn } = this.createVideoRow(video, index, mode, canDrag);
li.appendChild(row);
if (editable) {
const tagRow = this.createTagRow(video, li, tagAddBtn);
li.appendChild(tagRow);
} else if (Array.isArray(video.tags) && video.tags.length) {
// Read-only tags in the trash view
const tagRow = document.createElement('div');
tagRow.className = 'tag-row';
video.tags.forEach((tag) => tagRow.appendChild(this.createReadonlyPill(tag)));
li.appendChild(tagRow);
}
if (canDrag) this.attachDragListeners(li);
return li;
},
createVideoRow(video, index, mode, canDrag) {
const row = document.createElement('div');
row.className = 'video-row';
const left = document.createElement('div');
left.className = 'video-left';
if (canDrag) {
left.appendChild(this.createDragHandle());
}
left.appendChild(this.createTitle(video.title));
const { actions, tagAddBtn } = this.createActions(index, mode, video);
row.append(left, actions);
return { row, tagAddBtn };
},
createDragHandle() {
const handle = document.createElement('div');
handle.className = 'drag-handle';
handle.title = AppState.tagQuery ? 'Clear search to reorder' : 'Hold and drag to reorder';
handle.appendChild(Utils.createBtnIcon('icons/buttons/menu-burger.svg', ''));
return handle;
},
createTitle(title) {
const titleEl = document.createElement('span');
titleEl.className = 'video-title';
titleEl.textContent = title;
return titleEl;
},
makeIconButton(className, iconSrc, title) {
const btn = document.createElement('button');
btn.className = `icon-btn ${className}`;
btn.type = 'button';
btn.title = title;
btn.setAttribute('aria-label', title);
btn.appendChild(Utils.createBtnIcon(iconSrc, ''));
return btn;
},
createActions(index, mode, video) {
const actions = document.createElement('div');
actions.className = 'video-actions';
let tagAddBtn = null;
if (mode === 'trash') {
const restoreBtn = this.makeIconButton('restore-btn', 'icons/buttons/rotate-left.svg', 'Restore video');
const permaBtn = this.makeIconButton('perma-delete-btn', 'icons/buttons/trash-xmark.svg', 'Delete permanently');
actions.append(restoreBtn, permaBtn);
return { actions, tagAddBtn };
}
// active / archive
if (mode === 'archive') {
const unwatchBtn = this.makeIconButton('watch-toggle-btn', 'icons/buttons/rotate-left.svg', 'Move back to To Watch');
actions.appendChild(unwatchBtn);
} else {
const watchedBtn = this.makeIconButton('watch-toggle-btn', 'icons/buttons/check.svg', 'Mark as watched');
actions.appendChild(watchedBtn);
}
tagAddBtn = this.makeIconButton('tag-add-btn', 'icons/buttons/tags.svg', 'Add tag');
actions.appendChild(tagAddBtn);
const delBtn = this.makeIconButton('delete-btn', 'icons/buttons/cross-small.svg', 'Remove video');
delBtn.dataset.index = String(index);
actions.appendChild(delBtn);
return { actions, tagAddBtn };
},
createTagRow(video, li, tagAddBtn) {
const tagRow = document.createElement('div');
tagRow.className = 'tag-row';
const tags = Array.isArray(video.tags) ? video.tags : [];
tags.forEach(tag => {
const pill = this.createTagPill(tag, li);
tagRow.appendChild(pill);
});
const tagEditor = this.createTagInput(li, tagAddBtn, video);
tagRow.appendChild(tagEditor);
return tagRow;
},
createReadonlyPill(tag) {
const pill = document.createElement('span');
pill.className = 'tag-pill tag-pill-readonly';
pill.style.background = tag.color;
const pillText = document.createElement('span');
pillText.className = 'tag-pill-text';
pillText.textContent = tag.name;
pill.appendChild(pillText);
return pill;
},
createTagPill(tag, li) {
const pill = document.createElement('span');
pill.className = 'tag-pill';
pill.style.background = tag.color;
pill.title = `Filter by "${tag.name}"`;
const pillText = document.createElement('span');
pillText.className = 'tag-pill-text';
pillText.textContent = tag.name;
const pillRemove = document.createElement('button');
pillRemove.className = 'tag-pill-remove';
pillRemove.type = 'button';
pillRemove.title = 'Remove tag';
pillRemove.textContent = '×';
pill.append(pillText, pillRemove);
pill.addEventListener('click', (e) => {
if (e.target?.closest('.tag-pill-remove')) return;
e.preventDefault();
e.stopPropagation();
if (DOMCache.tagSearchInput) {
DOMCache.tagSearchInput.value = tag.name;
}
AppState.setTagQuery(tag.name, 'exact');
displayVideos();
});
pillRemove.addEventListener('click', async (e) => {
e.preventDefault();
e.stopPropagation();
try {
const videos = await StorageManager.getVideos();
const video = videos.find((v) => v.url === li.dataset.url);
if (!video) return;
const nextTags = (video.tags || []).filter(
(t) => t.name.toLowerCase() !== tag.name.toLowerCase()
);
await StorageManager.updateVideoByUrl(video.url, { tags: nextTags });
displayVideos();
} catch (error) {
console.error('Error removing tag:', error);
}
});
return pill;
},
/**
* Add a tag (by name) to a video. Returns true on success or if it already
* exists. Shared by the Enter key and the autocomplete suggestions.
*/
async addTag(videoUrl, name) {
const clean = (name || '').trim();
if (!clean || !videoUrl) return false;
try {
const videos = await StorageManager.getVideos();
const video = videos.find((v) => v.url === videoUrl);
if (!video) return false;
const existing = video.tags || [];
if (existing.some((t) => t.name.toLowerCase() === clean.toLowerCase())) {
return true; // already present — treat as success
}
const newTag = { name: clean, color: Utils.colorFromTagName(clean) };
return await StorageManager.updateVideoByUrl(videoUrl, {
tags: [...existing, newTag]
});
} catch (error) {
console.error('Error adding tag:', error);
return false;
}
},
createTagInput(li, tagAddBtn, video) {
const wrap = document.createElement('span');
wrap.className = 'tag-input-wrap';
wrap.style.display = 'none';
const tagInput = document.createElement('input');
tagInput.className = 'tag-input';
tagInput.type = 'text';
tagInput.placeholder = 'Tag…';
tagInput.maxLength = CONFIG.TAG_MAX_LENGTH;
const suggestions = document.createElement('div');
suggestions.className = 'tag-suggestions';
suggestions.hidden = true;
wrap.append(tagInput, suggestions);
let tagUniverse = [];
const existingLower = () => new Set((video.tags || []).map((t) => t.name.toLowerCase()));
const closeEditor = () => {
wrap.style.display = 'none';
tagInput.value = '';
suggestions.hidden = true;
suggestions.textContent = '';
};
const openEditor = async () => {
wrap.style.display = 'inline-flex';
tagInput.value = '';
suggestions.hidden = true;
suggestions.textContent = '';
tagInput.focus();
tagUniverse = await StorageManager.getAllTagNames();
};
const commit = async (name) => {
const clean = (name || '').trim();
if (!clean) { closeEditor(); return; }
const ok = await VideoItemFactory.addTag(li.dataset.url, clean);
if (ok) {
displayVideos(); // rebuilds the list (editor closes with it)
} else {
closeEditor();
}
};
const renderSuggestions = (query) => {
const q = query.trim().toLowerCase();
suggestions.textContent = '';
if (!q) { suggestions.hidden = true; return; }
const exclude = existingLower();
const matches = tagUniverse
.filter((n) => n.toLowerCase().includes(q) && !exclude.has(n.toLowerCase()))
.slice(0, 6);
if (matches.length === 0) { suggestions.hidden = true; return; }
matches.forEach((name) => {
const item = document.createElement('button');
item.type = 'button';
item.className = 'tag-suggestion';
const dot = document.createElement('span');
dot.className = 'tag-suggestion-dot';
dot.style.background = Utils.colorFromTagName(name);
const label = document.createElement('span');
label.className = 'tag-suggestion-label';
label.textContent = name;
item.append(dot, label);
// mousedown (not click): fires before the input's blur tears the list down
item.addEventListener('mousedown', (e) => {
e.preventDefault();
commit(name);
});
suggestions.appendChild(item);
});
suggestions.hidden = false;
};
if (tagAddBtn) {
tagAddBtn.addEventListener('click', (e) => {
e.preventDefault();
e.stopPropagation();
if (wrap.style.display === 'none') {
openEditor();
} else {
closeEditor();
}
});
}
wrap.addEventListener('click', (e) => e.stopPropagation());
tagInput.addEventListener('input', () => renderSuggestions(tagInput.value));
tagInput.addEventListener('keydown', (e) => {
if (e.key === 'Escape') {
e.preventDefault();
e.stopPropagation();
closeEditor();
return;
}
if (e.key === 'Enter') {
e.preventDefault();
e.stopPropagation();
commit(tagInput.value);
}
});
// Clicking away (with nothing selected) closes the editor — fix for the
// input staying open when left empty. The timeout lets a suggestion's
// mousedown run first.
tagInput.addEventListener('blur', () => {
setTimeout(() => {
if (document.activeElement !== tagInput) closeEditor();
}, 120);
});
return wrap;
},
attachDragListeners(li) {
li.addEventListener('dragstart', () => {
if (AppState.tagQuery) return;
AppState.draggedItemIndex = parseInt(li.dataset.index, 10);
DragScroller.start();
setTimeout(() => li.classList.add('dragging'), 0);
});
li.addEventListener('dragend', () => {
DragScroller.stop();
li.classList.remove('dragging');
document.querySelectorAll('.video-item').forEach(el => el.classList.remove('drop-target'));
});
li.addEventListener('dragover', (e) => {
if (AppState.tagQuery) return;
e.preventDefault();
const targetIndex = parseInt(li.dataset.index, 10);
if (AppState.draggedItemIndex !== null && AppState.draggedItemIndex !== targetIndex) {
li.classList.add('drop-target');
}
});
li.addEventListener('dragleave', () => {
li.classList.remove('drop-target');
});
li.addEventListener('drop', async (e) => {
if (AppState.tagQuery) return;
e.preventDefault();
li.classList.remove('drop-target');
const targetIndex = parseInt(li.dataset.index, 10);
if (AppState.draggedItemIndex === null || AppState.draggedItemIndex === targetIndex) return;
try {
await StorageManager.reorder(AppState.draggedItemIndex, targetIndex);
displayVideos();
} catch (error) {
console.error('Error reordering videos:', error);
}
});
}
};
// ============================================
// DISPLAY LOGIC
// ============================================
async function displayVideos() {
try {
if (!DOMCache.videoList || !DOMCache.tutorial) {
console.error('Required DOM elements not found');
return;
}
const [savedVideos, deletedVideos] = await Promise.all([
StorageManager.getVideos(),
StorageManager.getDeleted()
]);
const activeVideos = savedVideos.filter((v) => !v.watched);
const archivedVideos = savedVideos.filter((v) => v.watched);
updateTabCounts(activeVideos.length, archivedVideos.length, deletedVideos.length);
// Tag search only applies to active/archive; the "Empty trash" bar only
// shows in the trash view (so there is no single control wiping everything).
if (DOMCache.searchWrap) DOMCache.searchWrap.style.display = AppState.view === 'trash' ? 'none' : '';
if (DOMCache.trashActions) {
DOMCache.trashActions.classList.toggle('visible', AppState.view === 'trash' && deletedVideos.length > 0);
}
DOMCache.videoList.textContent = '';
// ---- TRASH VIEW ----
if (AppState.view === 'trash') {
if (deletedVideos.length === 0) {
showTutorial('Trash is empty', 'Deleted videos appear here so you can restore them. Items are removed automatically once the trash is full.');
return;
}
DOMCache.tutorial.style.display = 'none';
const frag = document.createDocumentFragment();
deletedVideos.forEach((video) => {
frag.appendChild(VideoItemFactory.create(video, -1, 'trash'));
});
DOMCache.videoList.appendChild(frag);
return;
}
// ---- ACTIVE / ARCHIVE VIEWS ----
const source = AppState.view === 'archive' ? archivedVideos : activeVideos;
if (source.length === 0) {
if (AppState.view === 'archive') {