cliphaven 3.4.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,2143 @@
1
+ const $ = (id) => document.getElementById(id);
2
+ let timer = null;
3
+ let currentJobId = null;
4
+ let activeDownloadUrl = "";
5
+ let previewTimer = null;
6
+ let previewSeq = 0;
7
+ let lastPreviewUrl = "";
8
+ let currentTitleHint = "";
9
+ let currentDurationHint = 0;
10
+ const PLAYLIST_BATCH_INTERVAL_MS = 500;
11
+ const PLAYLIST_INITIAL_RENDER_BATCH = 38;
12
+ const PLAYLIST_RENDER_CHUNK_SIZE = 38;
13
+ let currentPlaylistCount = 0;
14
+ let isCurrentUrlPlaylist = false;
15
+ let currentPlaylistEntries = [];
16
+ let renderedPlaylistCount = 0;
17
+ let isPlaylistLoading = false;
18
+ let playlistSelectAllMode = true;
19
+ let playlistBatchTimer = null;
20
+ let playlistPollInFlight = false;
21
+ let lastCompletedPath = "";
22
+ let androidReqSeq = 0;
23
+ const androidPending = {};
24
+
25
+ window.__onAndroidApiResult = (reqId, data) => {
26
+ const cb = androidPending[reqId];
27
+ if (cb) {
28
+ delete androidPending[reqId];
29
+ cb(data);
30
+ }
31
+ };
32
+
33
+ function formatDisplayFolder(path) {
34
+ if (!path) return "";
35
+ let p = String(path).trim();
36
+ // Only format internal storage paths on Android; keep full desktop drive paths (C:\..., D:\..., /home/...) completely untouched
37
+ if (!window.ClipHavenAndroid) return p;
38
+ // Replace the leading storage root prefix with empty string ""
39
+ p = p.replace(/^\/(?:storage\/emulated\/\d+|storage\/sdcard\d+|sdcard)\/?/i, "");
40
+ p = p.replace(/^Internal Storage\/?/i, "");
41
+ return p || "Download/ClipHaven";
42
+ }
43
+
44
+ function normalizeInputUrl(raw) {
45
+ if (!raw) return "";
46
+ const s = String(raw).trim();
47
+ const httpMatch = s.match(/https?:\/\/[^\s<>"']+/i);
48
+ if (httpMatch) {
49
+ return httpMatch[0]
50
+ .replace(/[.,;)!\]>]+$/, "")
51
+ .replace(/^http:\/\//i, "https://");
52
+ }
53
+ const bareMatch = s.match(
54
+ /(?:www\.)?(?:[a-zA-Z0-9-]+\.)+[a-zA-Z]{2,}\/[^\s<>"']*/,
55
+ );
56
+ if (bareMatch) {
57
+ return "https://" + bareMatch[0].replace(/[.,;)!\]>]+$/, "");
58
+ }
59
+ return s;
60
+ }
61
+
62
+
63
+ // 0-KB Offline Subtle Sound FX (Web Audio API) & Haptic Feedback
64
+ let _uiAudioCtx = null;
65
+ function _ensureAudioCtx() {
66
+ try {
67
+ const Ctx = window.AudioContext || window.webkitAudioContext;
68
+ if (!Ctx) return null;
69
+ if (!_uiAudioCtx) _uiAudioCtx = new Ctx();
70
+ if (_uiAudioCtx.state === "suspended") _uiAudioCtx.resume().catch(() => {});
71
+ return _uiAudioCtx;
72
+ } catch (_) {
73
+ return null;
74
+ }
75
+ }
76
+ ["pointerdown", "keydown"].forEach((ev) => {
77
+ window.addEventListener(ev, () => { _ensureAudioCtx(); }, { once: true, passive: true });
78
+ });
79
+
80
+ function playUiTone(kind) {
81
+ try {
82
+ if (window.matchMedia && window.matchMedia("(prefers-reduced-motion: reduce)").matches) return;
83
+ const ctx = _ensureAudioCtx();
84
+ if (!ctx) return;
85
+ const run = () => {
86
+ try {
87
+ const now = ctx.currentTime + 0.005;
88
+ const playNote = (freq, startOffset, dur, peakGain, endFreq) => {
89
+ const osc = ctx.createOscillator();
90
+ const gain = ctx.createGain();
91
+ osc.type = "sine";
92
+ osc.frequency.setValueAtTime(freq, now + startOffset);
93
+ if (endFreq) osc.frequency.exponentialRampToValueAtTime(endFreq, now + startOffset + dur);
94
+ gain.gain.setValueAtTime(0.0001, now + startOffset);
95
+ gain.gain.exponentialRampToValueAtTime(peakGain, now + startOffset + 0.012);
96
+ gain.gain.exponentialRampToValueAtTime(0.0001, now + startOffset + dur);
97
+ osc.connect(gain);
98
+ gain.connect(ctx.destination);
99
+ osc.start(now + startOffset);
100
+ osc.stop(now + startOffset + dur + 0.02);
101
+ };
102
+ if (kind === "complete") {
103
+ playNote(523.25, 0, 0.15, 0.18);
104
+ playNote(659.25, 0.09, 0.22, 0.18);
105
+ } else if (kind === "pop") {
106
+ playNote(620, 0, 0.075, 0.14, 820);
107
+ } else if (kind === "error") {
108
+ playNote(240, 0, 0.18, 0.16, 175);
109
+ }
110
+ } catch (_) {}
111
+ };
112
+ if (ctx.state === "suspended") {
113
+ ctx.resume().then(run).catch(() => {});
114
+ } else {
115
+ run();
116
+ }
117
+ } catch (_) {}
118
+ }
119
+
120
+ function triggerHaptic(kind) {
121
+ try {
122
+ if (!navigator.vibrate) return;
123
+ if (kind === "complete") navigator.vibrate([14, 40, 22]);
124
+ else if (kind === "error") navigator.vibrate([28, 30, 28]);
125
+ else navigator.vibrate(10);
126
+ } catch (_) {}
127
+ }
128
+ let _lastStatusFeedbackKey = "";
129
+
130
+ function status(
131
+ title,
132
+ detail,
133
+ pct = 0,
134
+ pill = "Working",
135
+ cls = "",
136
+ speed = "",
137
+ eta = "",
138
+ showOpenBtn = false,
139
+ indeterminate = false,
140
+ playlistInfo = null,
141
+ ) {
142
+ $("status").classList.add("show");
143
+ const titleEl = $("title");
144
+ titleEl.className = "status-title " + cls;
145
+ if (cls === "ok") {
146
+ titleEl.textContent = "";
147
+ const svgNS = "http://www.w3.org/2000/svg";
148
+ const svg = document.createElementNS(svgNS, "svg");
149
+ svg.setAttribute("class", "status-check-svg");
150
+ svg.setAttribute("viewBox", "0 0 24 24");
151
+ svg.setAttribute("fill", "none");
152
+ svg.setAttribute("stroke", "currentColor");
153
+ svg.setAttribute("stroke-width", "2.6");
154
+ svg.setAttribute("stroke-linecap", "round");
155
+ svg.setAttribute("stroke-linejoin", "round");
156
+ const p = document.createElementNS(svgNS, "path");
157
+ p.setAttribute("d", "M20 6L9 17l-5-5");
158
+ svg.appendChild(p);
159
+ titleEl.appendChild(svg);
160
+ titleEl.appendChild(document.createTextNode(title));
161
+ } else {
162
+ titleEl.textContent = title;
163
+ }
164
+ const fbKey = `${cls}|${pill}|${title}`;
165
+ if (fbKey !== _lastStatusFeedbackKey) {
166
+ _lastStatusFeedbackKey = fbKey;
167
+ if (cls === "ok") {
168
+ playUiTone("complete");
169
+ triggerHaptic("complete");
170
+ } else if (cls === "err" || cls === "error") {
171
+ playUiTone("error");
172
+ triggerHaptic("error");
173
+ }
174
+ }
175
+ $("detail").textContent = String(detail || "").replace(/([KMGTP])iB/g, "$1B");
176
+
177
+ const progEl = $("progress");
178
+ const fillEl = $("progress-fill");
179
+ const clampedPct = Math.max(0, Math.min(100, pct));
180
+ const isDoneOrErr = cls === "ok" || cls === "err" || pill === "Cancelled";
181
+ if (indeterminate) {
182
+ progEl.removeAttribute("value");
183
+ progEl.classList.add("indeterminate");
184
+ if (fillEl) {
185
+ fillEl.classList.add("is-active", "is-indeterminate");
186
+ fillEl.style.width = "42%";
187
+ }
188
+ } else {
189
+ progEl.classList.remove("indeterminate");
190
+ progEl.value = clampedPct;
191
+ if (fillEl) {
192
+ fillEl.classList.remove("is-indeterminate");
193
+ fillEl.style.width = `${clampedPct}%`;
194
+ fillEl.classList.toggle("is-active", !isDoneOrErr && clampedPct > 0 && clampedPct < 100);
195
+ }
196
+ }
197
+ $("pill").textContent = pill;
198
+ $("pill").classList.toggle("done-pop", cls === "ok");
199
+
200
+ const plEl = $("playlist-pill");
201
+ if (playlistInfo && playlistInfo.total > 1) {
202
+ const idx = playlistInfo.index || 1;
203
+ const tot = playlistInfo.total;
204
+ const done = playlistInfo.done ?? Math.max(0, idx - 1);
205
+ const left = playlistInfo.left ?? Math.max(0, tot - idx);
206
+ plEl.textContent = `📑 ${idx}/${tot} • ${done} done • ${left} left`;
207
+ plEl.style.display = "inline-block";
208
+ } else {
209
+ plEl.style.display = "none";
210
+ }
211
+
212
+ const speedEl = $("speed-pill");
213
+ const etaEl = $("eta-pill");
214
+ if (speed) {
215
+ speedEl.textContent = "⚡ " + String(speed).replace(/([KMGTP])iB/g, "$1B");
216
+ speedEl.style.display = "inline-block";
217
+ } else {
218
+ speedEl.style.display = "none";
219
+ }
220
+ if (eta) {
221
+ etaEl.textContent = "⏱ ETA " + eta;
222
+ etaEl.style.display = "inline-block";
223
+ } else {
224
+ etaEl.style.display = "none";
225
+ }
226
+ $("open-folder-btn").style.display = showOpenBtn ? "inline-block" : "none";
227
+ }
228
+
229
+ async function api(path, opts = {}) {
230
+ if (window.ClipHavenAndroid) {
231
+ if (typeof window.ClipHavenAndroid.requestAsync === "function") {
232
+ const d = await new Promise((resolve) => {
233
+ const reqId = "req_" + ++androidReqSeq + "_" + Date.now();
234
+ androidPending[reqId] = resolve;
235
+ window.ClipHavenAndroid.requestAsync(
236
+ reqId,
237
+ path,
238
+ opts.method || "GET",
239
+ opts.body || "{}",
240
+ );
241
+ });
242
+ if (!d || d.ok === false) throw Error((d && d.error) || "Request failed");
243
+ return d;
244
+ }
245
+ if (typeof window.ClipHavenAndroid.request === "function") {
246
+ const rawResp = window.ClipHavenAndroid.request(
247
+ path,
248
+ opts.method || "GET",
249
+ opts.body || "{}",
250
+ );
251
+ const d = JSON.parse(rawResp);
252
+ if (d.ok === false) throw Error(d.error || "Request failed");
253
+ return d;
254
+ }
255
+ }
256
+
257
+ const r = await fetch(path, {
258
+ ...opts,
259
+ headers: {
260
+ "Content-Type": "application/json",
261
+ ...(opts.headers || {}),
262
+ },
263
+ });
264
+ let d;
265
+ try {
266
+ d = await r.json();
267
+ } catch {
268
+ throw Error(
269
+ "Backend response was not valid JSON. Check that ClipHaven is running.",
270
+ );
271
+ }
272
+ if (!r.ok || d.ok === false) throw Error(d.error || "Request failed");
273
+ return d;
274
+ }
275
+
276
+ // Theme management
277
+ const themeBtn = $("theme");
278
+ function applyTheme(t, animate = false) {
279
+ document.documentElement.setAttribute("data-theme", t);
280
+ localStorage.setItem("theme", t);
281
+ const isLight = t === "light";
282
+ const langNow = localStorage.getItem("cliphaven_lang") || "en";
283
+ const lbl = $("theme-label");
284
+ if (lbl) lbl.textContent = langNow === "bn" ? (isLight ? "ডার্ক" : "লাইট") : (isLight ? "Dark" : "Light");
285
+ const ic = $("theme-icon");
286
+ if (ic) {
287
+ ic.innerHTML = isLight
288
+ ? '<path d="M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79z"/>'
289
+ : '<circle cx="12" cy="12" r="5"/><line x1="12" y1="1" x2="12" y2="3"/><line x1="12" y1="21" x2="12" y2="23"/><line x1="4.22" y1="4.22" x2="5.64" y2="5.64"/><line x1="18.36" y1="18.36" x2="19.78" y2="19.78"/><line x1="1" y1="12" x2="3" y2="12"/><line x1="21" y1="12" x2="23" y2="12"/><line x1="4.22" y1="19.78" x2="5.64" y2="18.36"/><line x1="18.36" y1="5.64" x2="19.78" y2="4.22"/>';
290
+ if (animate) {
291
+ ic.classList.remove("icon-spin");
292
+ void ic.offsetWidth;
293
+ ic.classList.add("icon-spin");
294
+ }
295
+ }
296
+ }
297
+ applyTheme(
298
+ localStorage.getItem("theme") ||
299
+ (matchMedia("(prefers-color-scheme: light)").matches ? "light" : "dark"),
300
+ false,
301
+ );
302
+ themeBtn.onclick = () =>
303
+ applyTheme(
304
+ document.documentElement.getAttribute("data-theme") === "light" ? "dark" : "light",
305
+ true,
306
+ );
307
+
308
+ function compressPlaylistIndices(indices) {
309
+ if (!Array.isArray(indices) || !indices.length) return "";
310
+ const sorted = Array.from(
311
+ new Set(indices.map(Number).filter((n) => Number.isInteger(n) && n > 0)),
312
+ ).sort((a, b) => a - b);
313
+ if (!sorted.length) return "";
314
+ const ranges = [];
315
+ let start = sorted[0];
316
+ let prev = sorted[0];
317
+ for (let i = 1; i < sorted.length; i++) {
318
+ const cur = sorted[i];
319
+ if (cur === prev + 1) {
320
+ prev = cur;
321
+ } else {
322
+ ranges.push(start === prev ? `${start}` : `${start}-${prev}`);
323
+ start = cur;
324
+ prev = cur;
325
+ }
326
+ }
327
+ ranges.push(start === prev ? `${start}` : `${start}-${prev}`);
328
+ return ranges.join(",");
329
+ }
330
+
331
+ function getSelectedPlaylistIndices() {
332
+ const boxes = document.querySelectorAll(".pl-item-checkbox");
333
+ const totalKnown = Math.max(currentPlaylistEntries.length, currentPlaylistCount);
334
+ if (!boxes.length && !totalKnown) return [];
335
+ const selected = [];
336
+ boxes.forEach((b) => {
337
+ if (b.checked) selected.push(Number(b.value));
338
+ });
339
+ if (
340
+ playlistSelectAllMode &&
341
+ $("allow-playlist").checked &&
342
+ totalKnown > boxes.length
343
+ ) {
344
+ for (let i = boxes.length; i < totalKnown; i++) {
345
+ const item = currentPlaylistEntries[i];
346
+ const idx = (item && item.index) || i + 1;
347
+ selected.push(Number(idx));
348
+ }
349
+ }
350
+ return selected;
351
+ }
352
+
353
+ function getPlaylistItemsParam() {
354
+ const totalKnown = Math.max(currentPlaylistEntries.length, currentPlaylistCount);
355
+ if (!totalKnown) return "";
356
+ const boxes = document.querySelectorAll(".pl-item-checkbox");
357
+ if (!boxes.length) {
358
+ if (!$("allow-playlist").checked) {
359
+ return /\/playlist\b/i.test($("url").value) ? "1" : "";
360
+ }
361
+ return "";
362
+ }
363
+ const selected = getSelectedPlaylistIndices();
364
+ const allDomChecked =
365
+ boxes.length > 0 &&
366
+ Array.from(boxes).every((b) => b.checked) &&
367
+ playlistSelectAllMode;
368
+ if (!selected.length || (allDomChecked && selected.length >= totalKnown)) {
369
+ return "";
370
+ }
371
+ return compressPlaylistIndices(selected);
372
+ }
373
+
374
+ function updatePlaylistScrollHint() {
375
+ const scrollHint = $("playlist-scroll-hint");
376
+ if (!scrollHint) return;
377
+ const totalLoaded = currentPlaylistEntries.length;
378
+ const totalExpected = Math.max(totalLoaded, currentPlaylistCount);
379
+ if (!isCurrentUrlPlaylist || totalLoaded === 0) {
380
+ scrollHint.style.display = "none";
381
+ return;
382
+ }
383
+ if (isPlaylistLoading || renderedPlaylistCount < totalLoaded) {
384
+ const suffix = totalExpected > renderedPlaylistCount ? ` / ${totalExpected}` : "";
385
+ scrollHint.textContent = `⏳ Loaded ${renderedPlaylistCount}${suffix} videos…`;
386
+ scrollHint.style.display = "inline-block";
387
+ } else if (renderedPlaylistCount > 5) {
388
+ scrollHint.textContent = `↕ Scroll (${renderedPlaylistCount} videos)`;
389
+ scrollHint.style.display = "inline-block";
390
+ } else {
391
+ scrollHint.style.display = "none";
392
+ }
393
+ }
394
+
395
+ function stopPlaylistStream(notifyBackend = false) {
396
+ if (playlistBatchTimer) {
397
+ clearInterval(playlistBatchTimer);
398
+ playlistBatchTimer = null;
399
+ }
400
+ isPlaylistLoading = false;
401
+ playlistPollInFlight = false;
402
+ updatePlaylistScrollHint();
403
+ syncPlaylistBadgeText();
404
+ if (notifyBackend) {
405
+ api("/api/cancel-preview", { method: "POST", body: "{}" }).catch(() => {});
406
+ }
407
+ }
408
+
409
+ function createPlaylistRowElement(item, i, shouldCheck = true) {
410
+ const idx = item.index || i + 1;
411
+ const row = document.createElement("label");
412
+ row.className = "playlist-item-row";
413
+
414
+ const cb = document.createElement("input");
415
+ cb.type = "checkbox";
416
+ cb.className = "pl-item-checkbox";
417
+ cb.value = String(idx);
418
+ cb.checked = shouldCheck;
419
+ cb.onchange = () => {
420
+ const boxes = document.querySelectorAll(".pl-item-checkbox");
421
+ const allChecked = boxes.length > 0 && Array.from(boxes).every((b) => b.checked);
422
+ playlistSelectAllMode = allChecked;
423
+ $("allow-playlist").checked = allChecked;
424
+ updateExtraOptionsBadge();
425
+ };
426
+
427
+ const idxSpan = document.createElement("span");
428
+ idxSpan.className = "playlist-item-idx";
429
+ idxSpan.textContent = `#${idx}`;
430
+
431
+ const titleSpan = document.createElement("span");
432
+ titleSpan.className = "playlist-item-title";
433
+ titleSpan.textContent = item.title || `Video ${idx}`;
434
+
435
+ row.appendChild(cb);
436
+ row.appendChild(idxSpan);
437
+ row.appendChild(titleSpan);
438
+
439
+ if (item.duration) {
440
+ const durSpan = document.createElement("span");
441
+ durSpan.className = "playlist-item-dur";
442
+ durSpan.textContent = item.duration;
443
+ row.appendChild(durSpan);
444
+ }
445
+ return row;
446
+ }
447
+
448
+ function appendPlaylistBatch(maxCount = 100) {
449
+ const listEl = $("playlist-items-list");
450
+ if (!listEl || renderedPlaylistCount >= currentPlaylistEntries.length) return 0;
451
+ const endIdx = Math.min(
452
+ currentPlaylistEntries.length,
453
+ renderedPlaylistCount + maxCount,
454
+ );
455
+ const frag = document.createDocumentFragment();
456
+ const shouldCheck = playlistSelectAllMode && $("allow-playlist").checked;
457
+ for (let i = renderedPlaylistCount; i < endIdx; i++) {
458
+ const item = currentPlaylistEntries[i];
459
+ frag.appendChild(createPlaylistRowElement(item, i, shouldCheck));
460
+ }
461
+ listEl.appendChild(frag);
462
+ const added = endIdx - renderedPlaylistCount;
463
+ renderedPlaylistCount = endIdx;
464
+ return added;
465
+ }
466
+
467
+ function startPlaylistBatchLoop(cleanUrl, seq) {
468
+ if (playlistBatchTimer) clearInterval(playlistBatchTimer);
469
+ playlistBatchTimer = setInterval(async () => {
470
+ if (seq !== previewSeq || currentJobId) {
471
+ stopPlaylistStream(false);
472
+ return;
473
+ }
474
+ if (isPlaylistLoading && cleanUrl && !playlistPollInFlight) {
475
+ playlistPollInFlight = true;
476
+ try {
477
+ const d = await api("/api/info", {
478
+ method: "POST",
479
+ body: JSON.stringify({ url: cleanUrl, poll: true }),
480
+ });
481
+ if (seq !== previewSeq || currentJobId) {
482
+ stopPlaylistStream(false);
483
+ return;
484
+ }
485
+ const info = (d && d.info) || {};
486
+ if (
487
+ Array.isArray(info.entries) &&
488
+ info.entries.length >= currentPlaylistEntries.length
489
+ ) {
490
+ currentPlaylistEntries = info.entries;
491
+ }
492
+ currentPlaylistCount = Math.max(
493
+ currentPlaylistCount,
494
+ info.playlist_count || 0,
495
+ currentPlaylistEntries.length,
496
+ );
497
+ isPlaylistLoading = Boolean(info.playlist_loading);
498
+ } catch {
499
+ isPlaylistLoading = false;
500
+ } finally {
501
+ playlistPollInFlight = false;
502
+ }
503
+ }
504
+ if (renderedPlaylistCount < currentPlaylistEntries.length) {
505
+ const remaining = currentPlaylistEntries.length - renderedPlaylistCount;
506
+ const chunk = Math.min(PLAYLIST_RENDER_CHUNK_SIZE, remaining);
507
+ appendPlaylistBatch(chunk);
508
+ }
509
+ updatePlaylistScrollHint();
510
+ updateExtraOptionsBadge();
511
+ if (!isPlaylistLoading && renderedPlaylistCount >= currentPlaylistEntries.length) {
512
+ stopPlaylistStream(false);
513
+ }
514
+ }, PLAYLIST_BATCH_INTERVAL_MS);
515
+ }
516
+
517
+ function renderPlaylistSelector(entries, cleanUrl = "", seq = previewSeq) {
518
+ const selector = $("playlist-selector");
519
+ const listEl = $("playlist-items-list");
520
+ const scrollHint = $("playlist-scroll-hint");
521
+ if (playlistBatchTimer) {
522
+ clearInterval(playlistBatchTimer);
523
+ playlistBatchTimer = null;
524
+ }
525
+ listEl.innerHTML = "";
526
+ renderedPlaylistCount = 0;
527
+ if (!isCurrentUrlPlaylist || ((!entries || !entries.length) && !isPlaylistLoading)) {
528
+ selector.style.display = "none";
529
+ if (scrollHint) scrollHint.style.display = "none";
530
+ return;
531
+ }
532
+ selector.style.display = "block";
533
+ appendPlaylistBatch(PLAYLIST_INITIAL_RENDER_BATCH);
534
+ updatePlaylistScrollHint();
535
+ syncPlaylistBadgeText();
536
+
537
+ if (isPlaylistLoading || renderedPlaylistCount < currentPlaylistEntries.length) {
538
+ startPlaylistBatchLoop(cleanUrl, seq);
539
+ }
540
+ }
541
+
542
+ function isPlaylistUrlPattern(u) {
543
+ return /[?&]list=[^&#]+|\/playlist\b/i.test(String(u || ""));
544
+ }
545
+
546
+ function syncPlaylistCheckboxState(urlHint = "") {
547
+ const cb = $("allow-playlist");
548
+ if (!cb) return;
549
+ const canPlaylist = Boolean(
550
+ isCurrentUrlPlaylist || isPlaylistUrlPattern(urlHint || $("url").value),
551
+ );
552
+ cb.disabled = !canPlaylist;
553
+ if (!canPlaylist) {
554
+ cb.checked = false;
555
+ }
556
+ if (cb.parentElement) {
557
+ cb.parentElement.style.opacity = canPlaylist ? "1" : "0.5";
558
+ cb.parentElement.style.cursor = canPlaylist ? "pointer" : "not-allowed";
559
+ cb.parentElement.title = canPlaylist
560
+ ? ""
561
+ : "Download Entire Playlist is only available for playlist links";
562
+ }
563
+ }
564
+
565
+ // Extra Options active badge indicator & playlist badge sync
566
+ function syncPlaylistBadgeText() {
567
+ const badge = $("preview-playlist");
568
+ const selBadge = $("playlist-selector-badge");
569
+ if (!isCurrentUrlPlaylist) {
570
+ badge.style.display = "none";
571
+ if ($("playlist-selector")) $("playlist-selector").style.display = "none";
572
+ return;
573
+ }
574
+ const total = Math.max(currentPlaylistEntries.length, currentPlaylistCount);
575
+ const shownCount = renderedPlaylistCount || currentPlaylistEntries.length || total;
576
+ const stillWorking = isPlaylistLoading || renderedPlaylistCount < currentPlaylistEntries.length;
577
+ const boxes = document.querySelectorAll(".pl-item-checkbox");
578
+ let checkedDomCount = 0;
579
+ boxes.forEach((b) => {
580
+ if (b.checked) checkedDomCount++;
581
+ });
582
+ const isAll = $("allow-playlist").checked;
583
+ const hasCustomUncheck = boxes.length > 0 && checkedDomCount < boxes.length && checkedDomCount > 0;
584
+
585
+ if (boxes.length > 0 && checkedDomCount === 0) {
586
+ const countStr = shownCount > 1 ? ` (${shownCount}${stillWorking ? "…" : ""} videos)` : "";
587
+ badge.textContent = `📑 Playlist${countStr} • 0 Selected`;
588
+ if (selBadge) selBadge.textContent = "0 Selected";
589
+ } else if (hasCustomUncheck) {
590
+ badge.textContent = `✅ ${checkedDomCount}/${shownCount}${stillWorking ? "…" : ""} Videos Selected ▾`;
591
+ if (selBadge) selBadge.textContent = `${checkedDomCount} of ${shownCount}${stillWorking ? "…" : ""} Selected ▾`;
592
+ } else if (!isAll && boxes.length === 0) {
593
+ const countStr = shownCount > 1 ? ` (${shownCount}${stillWorking ? "…" : ""} videos)` : "";
594
+ badge.textContent = `📑 Playlist${countStr} • Single`;
595
+ if (selBadge) selBadge.textContent = "Single Video Only";
596
+ } else if (stillWorking) {
597
+ const targetStr = total > shownCount ? `/${total}` : "";
598
+ badge.textContent = `⏳ Playlist (${shownCount}${targetStr} loaded…) ▾`;
599
+ if (selBadge) selBadge.textContent = `⏳ ${shownCount}${targetStr} Loaded ▾`;
600
+ } else {
601
+ const countStr = shownCount > 1 ? ` (${shownCount} videos)` : "";
602
+ badge.textContent = `✅ All Playlist Videos${countStr} ▾`;
603
+ if (selBadge) selBadge.textContent = shownCount > 1 ? `All ${shownCount} Selected ▾` : "All Selected ▾";
604
+ }
605
+ badge.style.display = "inline-block";
606
+ }
607
+
608
+ function updateExtraOptionsBadge() {
609
+ const fmt = $("format").value;
610
+ const isAudio = ["mp3", "m4a", "wav"].includes(fmt);
611
+ const canThumb = ["mp4", "mkv", "mp3", "m4a"].includes(fmt);
612
+ const hasTrim =
613
+ $("start-time").value.trim() !== "" || $("end-time").value.trim() !== "";
614
+ const hasChecks =
615
+ (!isAudio && $("subtitles").checked) ||
616
+ (canThumb && $("embed-thumbnail").checked) ||
617
+ $("allow-playlist").checked;
618
+ syncPlaylistCheckboxState();
619
+ $("active-options-badge").style.display =
620
+ hasTrim || hasChecks ? "inline-block" : "none";
621
+ syncPlaylistBadgeText();
622
+ }
623
+
624
+ // Format & Quality toggle (also guards format-specific checkboxes)
625
+ $("format").onchange = () => {
626
+ const fmt = $("format").value;
627
+ const audio = ["mp3", "m4a", "wav"].includes(fmt);
628
+ const canThumb = ["mp4", "mkv", "mp3", "m4a"].includes(fmt);
629
+
630
+ $("quality").disabled = audio;
631
+ $("quality").style.opacity = audio ? "0.5" : "1";
632
+
633
+ $("subtitles").disabled = audio;
634
+ $("subtitles").parentElement.style.opacity = audio ? "0.5" : "1";
635
+ $("subtitles").parentElement.title = audio
636
+ ? "Subtitles apply to video formats (MP4, MKV, WEBM)"
637
+ : "";
638
+
639
+ $("embed-thumbnail").disabled = !canThumb;
640
+ $("embed-thumbnail").parentElement.style.opacity = canThumb ? "1" : "0.5";
641
+ $("embed-thumbnail").parentElement.title = canThumb
642
+ ? ""
643
+ : "Cover art embedding is supported for MP4, MKV, MP3, and M4A";
644
+
645
+ updateExtraOptionsBadge();
646
+ };
647
+ $("format").onchange();
648
+
649
+ // Save folder persistence & Browse button
650
+ $("folder").addEventListener("change", () => {
651
+ const val = formatDisplayFolder($("folder").value);
652
+ $("folder").value = val;
653
+ if (val) localStorage.setItem("cliphaven_folder", val);
654
+ });
655
+
656
+ $("browse-folder-btn").onclick = async () => {
657
+ const btn = $("browse-folder-btn");
658
+ const prevText = btn.textContent;
659
+ btn.disabled = true;
660
+ btn.textContent = "📁 Browsing…";
661
+ try {
662
+ const d = await api("/api/pick-folder", {
663
+ method: "POST",
664
+ body: JSON.stringify({ current: $("folder").value.trim() }),
665
+ });
666
+ if (!d.cancelled && d.folder) {
667
+ const displayPath = formatDisplayFolder(d.folder);
668
+ $("folder").value = displayPath;
669
+ localStorage.setItem("cliphaven_folder", displayPath);
670
+ }
671
+ } catch (e) {
672
+ status("Could not open folder picker", e.message, 0, "Error", "error");
673
+ } finally {
674
+ btn.disabled = false;
675
+ btn.textContent = prevText;
676
+ }
677
+ };
678
+
679
+ [
680
+ "start-time",
681
+ "end-time",
682
+ "subtitles",
683
+ "embed-thumbnail",
684
+ "allow-playlist",
685
+ ].forEach((id) => {
686
+ $(id).addEventListener("input", updateExtraOptionsBadge);
687
+ $(id).addEventListener("change", updateExtraOptionsBadge);
688
+ });
689
+
690
+ // Interactive playlist badge & selector buttons
691
+ $("preview-playlist").onclick = () => {
692
+ const selector = $("playlist-selector");
693
+ if (selector && selector.style.display !== "none") {
694
+ selector.open = !selector.open;
695
+ } else {
696
+ const cb = $("allow-playlist");
697
+ cb.checked = !cb.checked;
698
+ updateExtraOptionsBadge();
699
+ }
700
+ };
701
+
702
+ $("allow-playlist").addEventListener("change", () => {
703
+ const checked = $("allow-playlist").checked;
704
+ const boxes = document.querySelectorAll(".pl-item-checkbox");
705
+ playlistSelectAllMode = checked;
706
+ if (boxes.length) {
707
+ boxes.forEach((b) => (b.checked = checked));
708
+ }
709
+ updateExtraOptionsBadge();
710
+ });
711
+
712
+ $("pl-select-all-btn").onclick = () => {
713
+ playlistSelectAllMode = true;
714
+ document.querySelectorAll(".pl-item-checkbox").forEach((b) => (b.checked = true));
715
+ $("allow-playlist").checked = true;
716
+ updateExtraOptionsBadge();
717
+ };
718
+
719
+ $("pl-clear-all-btn").onclick = () => {
720
+ playlistSelectAllMode = false;
721
+ document.querySelectorAll(".pl-item-checkbox").forEach((b) => (b.checked = false));
722
+ $("allow-playlist").checked = false;
723
+ updateExtraOptionsBadge();
724
+ };
725
+
726
+ // Hide broken thumbnail images gracefully
727
+ $("preview-thumb").onerror = () => {
728
+ $("preview-thumb").style.display = "none";
729
+ };
730
+
731
+ // Clear URL button visibility & action
732
+ function syncClearBtn() {
733
+ $("clear-url-btn").style.display = $("url").value.trim() ? "grid" : "none";
734
+ }
735
+
736
+ $("clear-url-btn").onclick = () => {
737
+ $("url").value = "";
738
+ syncClearBtn();
739
+ hidePreview();
740
+ $("url").focus();
741
+ };
742
+
743
+ function extractYouTubeId(url) {
744
+ const m = String(url || "").match(/(?:v=|youtu\.be\/|\/shorts\/|\/live\/|\/embed\/)([A-Za-z0-9_-]{11})/);
745
+ return m ? m[1] : "";
746
+ }
747
+
748
+ // One-click Clipboard Paste button (triggers instant 0ms preview)
749
+ $("paste-btn").onclick = async () => {
750
+ try {
751
+ let text = "";
752
+ if (typeof window.ClipHavenAndroid !== "undefined" && typeof window.ClipHavenAndroid.readClipboard === "function") {
753
+ text = String(window.ClipHavenAndroid.readClipboard() || "");
754
+ } else if (navigator.clipboard && navigator.clipboard.readText) {
755
+ text = await navigator.clipboard.readText();
756
+ }
757
+ if (text && text.trim()) {
758
+ $("url").value = normalizeInputUrl(text.trim());
759
+ syncClearBtn();
760
+ if (window.__clipHavenUpdatePlatformIcon) window.__clipHavenUpdatePlatformIcon($("url").value);
761
+ if (window.__clipHavenSyncPrimaryBtn) window.__clipHavenSyncPrimaryBtn();
762
+ playUiTone("pop");
763
+ triggerHaptic("tap");
764
+ triggerPreview(true);
765
+ } else {
766
+ $("url").focus();
767
+ }
768
+ } catch {
769
+ $("url").focus();
770
+ }
771
+ };
772
+
773
+ // Auto Video Info Preview with sequence guard against race conditions
774
+ function hidePreview() {
775
+ if (window.__clipHavenUpdatePlatformIcon && !$("url").value.trim()) window.__clipHavenUpdatePlatformIcon("");
776
+ previewSeq++;
777
+ lastPreviewUrl = "";
778
+ stopPlaylistStream(true);
779
+ $("preview-card").style.display = "none";
780
+ $("playlist-selector").style.display = "none";
781
+ $("playlist-items-list").innerHTML = "";
782
+ currentTitleHint = "";
783
+ currentDurationHint = 0;
784
+ if (window.__clipHavenSetDuration) window.__clipHavenSetDuration(0);
785
+ currentPlaylistCount = 0;
786
+ currentPlaylistEntries = [];
787
+ renderedPlaylistCount = 0;
788
+ isPlaylistLoading = false;
789
+ playlistSelectAllMode = true;
790
+ isCurrentUrlPlaylist = false;
791
+ syncPlaylistCheckboxState("");
792
+ updateExtraOptionsBadge();
793
+ }
794
+
795
+ async function fetchPreview(rawUrl) {
796
+ const clean = normalizeInputUrl(rawUrl);
797
+ if (!clean || !clean.startsWith("https://")) {
798
+ hidePreview();
799
+ return;
800
+ }
801
+ if (clean === lastPreviewUrl) return;
802
+ lastPreviewUrl = clean;
803
+
804
+ const seq = ++previewSeq;
805
+ stopPlaylistStream(false);
806
+ currentTitleHint = "";
807
+ currentDurationHint = 0;
808
+ if (window.__clipHavenSetDuration) window.__clipHavenSetDuration(0);
809
+ currentPlaylistCount = 0;
810
+ currentPlaylistEntries = [];
811
+ renderedPlaylistCount = 0;
812
+ isPlaylistLoading = false;
813
+ playlistSelectAllMode = true;
814
+ isCurrentUrlPlaylist = isPlaylistUrlPattern(clean);
815
+ syncPlaylistCheckboxState(clean);
816
+ $("playlist-selector").style.display = "none";
817
+ $("playlist-items-list").innerHTML = "";
818
+ $("preview-card").style.display = "flex";
819
+ const ytId = extractYouTubeId(clean);
820
+ if (ytId) {
821
+ $("preview-thumb").src = `https://i.ytimg.com/vi/${ytId}/hqdefault.jpg`;
822
+ $("preview-thumb").style.display = "block";
823
+ } else {
824
+ $("preview-thumb").style.display = "none";
825
+ }
826
+ $("preview-title").textContent = "Checking video link…";
827
+ $("preview-uploader").textContent = "Please wait";
828
+ $("preview-dot").style.display = "none";
829
+ $("preview-duration").style.display = "none";
830
+ $("preview-playlist").style.display = "none";
831
+
832
+ try {
833
+ const d = await api("/api/info", {
834
+ method: "POST",
835
+ body: JSON.stringify({ url: clean }),
836
+ });
837
+ if (seq !== previewSeq) return;
838
+ const info = d.info || {};
839
+ currentTitleHint = info.title || "";
840
+ currentDurationHint = info.duration_seconds || 0;
841
+ if (window.__clipHavenSetDuration && currentDurationHint > 0) window.__clipHavenSetDuration(currentDurationHint);
842
+ isCurrentUrlPlaylist = Boolean(info.is_playlist);
843
+ currentPlaylistCount = info.playlist_count || 0;
844
+ currentPlaylistEntries = Array.isArray(info.entries) ? info.entries : [];
845
+ isPlaylistLoading = Boolean(info.playlist_loading);
846
+ playlistSelectAllMode = isCurrentUrlPlaylist;
847
+ // Default to downloading all playlist videos automatically when a playlist link is pasted
848
+ $("allow-playlist").checked = isCurrentUrlPlaylist;
849
+ renderPlaylistSelector(currentPlaylistEntries, clean, seq);
850
+ $("preview-title").textContent = info.title || "Video ready to download";
851
+ $("preview-uploader").textContent = info.uploader || "";
852
+ if (info.thumbnail) {
853
+ $("preview-thumb").src = info.thumbnail;
854
+ $("preview-thumb").style.display = "block";
855
+ }
856
+ let durationVerifiedByEngine = Boolean(info.duration && !info.duration_approx);
857
+ if (info.duration) {
858
+ $("preview-duration").textContent = info.duration;
859
+ $("preview-duration").style.display = "inline-flex";
860
+ }
861
+ if (!isCurrentUrlPlaylist && !currentJobId && (!info.duration || info.duration_approx)) {
862
+ // 1. Instant (~0.3-0.6s) lightweight duration fetch for YouTube single videos
863
+ if (!info.duration && ytId) {
864
+ api("/api/info", {
865
+ method: "POST",
866
+ body: JSON.stringify({ url: clean, fast_duration: true }),
867
+ })
868
+ .then((fastRes) => {
869
+ if (seq !== previewSeq || durationVerifiedByEngine || !fastRes || !fastRes.info || !fastRes.info.duration) return;
870
+ currentDurationHint = fastRes.info.duration_seconds || 0;
871
+ if (window.__clipHavenSetDuration && currentDurationHint > 0) window.__clipHavenSetDuration(currentDurationHint);
872
+ $("preview-duration").textContent = fastRes.info.duration;
873
+ $("preview-duration").style.display = "inline-flex";
874
+ })
875
+ .catch(() => {});
876
+ }
877
+ // 2. Non-blocking background yt-dlp verification/reconciliation & fallback
878
+ api("/api/info", {
879
+ method: "POST",
880
+ body: JSON.stringify({ url: clean, full: true, verify: true }),
881
+ })
882
+ .then((res) => {
883
+ if (seq !== previewSeq || !res || !res.info) return;
884
+ if (res.info.thumbnail && ($("preview-thumb").style.display === "none" || !$("preview-thumb").getAttribute("src"))) {
885
+ $("preview-thumb").src = res.info.thumbnail;
886
+ $("preview-thumb").style.display = "block";
887
+ }
888
+ if (!res.info.duration) return;
889
+ durationVerifiedByEngine = true;
890
+ const exactSec = res.info.duration_seconds || 0;
891
+ if (exactSec !== currentDurationHint || $("preview-duration").style.display === "none") {
892
+ currentDurationHint = exactSec;
893
+ if (window.__clipHavenSetDuration && currentDurationHint > 0) window.__clipHavenSetDuration(currentDurationHint);
894
+ $("preview-duration").textContent = res.info.duration;
895
+ $("preview-duration").style.display = "inline-flex";
896
+ }
897
+ })
898
+ .catch(() => {});
899
+ }
900
+ updateExtraOptionsBadge();
901
+ } catch (err) {
902
+ if (seq === previewSeq) {
903
+ $("preview-thumb").style.display = "none";
904
+ $("preview-dot").style.display = "none";
905
+ $("preview-duration").style.display = "none";
906
+ $("preview-playlist").style.display = "none";
907
+ syncPlaylistCheckboxState(clean);
908
+ $("preview-title").textContent = "Preview unavailable";
909
+ $("preview-uploader").textContent =
910
+ (err && err.message) || "Check link or click Download Now to try directly.";
911
+ }
912
+ }
913
+ }
914
+
915
+ function triggerPreview(immediate = false) {
916
+ syncClearBtn();
917
+ if (window.__clipHavenUpdatePlatformIcon) window.__clipHavenUpdatePlatformIcon($("url").value);
918
+ if (window.__clipHavenSyncPrimaryBtn) window.__clipHavenSyncPrimaryBtn();
919
+ if (previewTimer) clearTimeout(previewTimer);
920
+ if (immediate) {
921
+ fetchPreview($("url").value);
922
+ } else {
923
+ previewTimer = setTimeout(() => fetchPreview($("url").value), 180);
924
+ }
925
+ }
926
+
927
+ $("url").addEventListener("input", () => triggerPreview(false));
928
+ $("url").addEventListener("paste", () =>
929
+ setTimeout(() => {
930
+ const cleaned = normalizeInputUrl($("url").value);
931
+ if (cleaned && cleaned !== $("url").value) {
932
+ $("url").value = cleaned;
933
+ }
934
+ if (window.__clipHavenUpdatePlatformIcon) window.__clipHavenUpdatePlatformIcon($("url").value);
935
+ if (window.__clipHavenSyncPrimaryBtn) window.__clipHavenSyncPrimaryBtn();
936
+ triggerPreview(true);
937
+ }, 20),
938
+ );
939
+
940
+ // Open folder button
941
+ async function openFolder(pathOrJobId = {}) {
942
+ try {
943
+ await api("/api/open-folder", {
944
+ method: "POST",
945
+ body: JSON.stringify(pathOrJobId),
946
+ });
947
+ } catch (e) {
948
+ status("Could not open folder", e.message, 0, "Error", "error");
949
+ }
950
+ }
951
+
952
+ $("open-folder-btn").onclick = () => {
953
+ openFolder({ path: lastCompletedPath || $("folder").value.trim() });
954
+ };
955
+
956
+ // Recent Downloads History management
957
+ function getSavedHistory() {
958
+ try {
959
+ return JSON.parse(localStorage.getItem("cliphaven_history") || "[]");
960
+ } catch {
961
+ return [];
962
+ }
963
+ }
964
+
965
+ function addToHistory(item) {
966
+ const list = getSavedHistory().filter((x) => x.id !== item.id);
967
+ list.unshift({
968
+ id: item.id,
969
+ title: item.video_title || item.detail || "Downloaded clip",
970
+ format: item.format || "MP4",
971
+ quality: item.quality || "Best",
972
+ file_path: item.file_path || item.folder || "",
973
+ time: new Date().toLocaleTimeString([], {
974
+ hour: "2-digit",
975
+ minute: "2-digit",
976
+ }),
977
+ });
978
+ localStorage.setItem("cliphaven_history", JSON.stringify(list.slice(0, 8)));
979
+ renderHistory();
980
+ try {
981
+ const qUrl = new URLSearchParams(window.location.search).get("url");
982
+ if (qUrl && /^https?:\/\//i.test(qUrl.trim())) {
983
+ const cleaned = normalizeInputUrl(qUrl.trim());
984
+ if (cleaned) {
985
+ $("url").value = cleaned;
986
+ syncClearBtn();
987
+ if (window.__clipHavenUpdatePlatformIcon) window.__clipHavenUpdatePlatformIcon(cleaned);
988
+ if (window.__clipHavenSyncPrimaryBtn) window.__clipHavenSyncPrimaryBtn();
989
+ triggerPreview(true);
990
+ if (window.history && window.history.replaceState) {
991
+ window.history.replaceState({}, document.title, window.location.pathname);
992
+ }
993
+ }
994
+ }
995
+ } catch (_) {}
996
+ setTimeout(checkForAppUpdates, 700);
997
+ }
998
+
999
+ function renderHistory() {
1000
+ const list = getSavedHistory();
1001
+ const section = $("history-section");
1002
+ const container = $("history-list");
1003
+ if (!list.length) {
1004
+ section.style.display = "none";
1005
+ return;
1006
+ }
1007
+ section.style.display = "block";
1008
+ container.innerHTML = "";
1009
+ list.forEach((item) => {
1010
+ const row = document.createElement("div");
1011
+ row.className = "list-row history-item";
1012
+
1013
+ const meta = document.createElement("div");
1014
+ meta.className = "list-meta history-meta";
1015
+
1016
+ const title = document.createElement("div");
1017
+ title.className = "list-title history-title";
1018
+ title.textContent = item.title;
1019
+ title.title = item.title;
1020
+
1021
+ const sub = document.createElement("div");
1022
+ sub.className = "list-sub history-sub";
1023
+ const fmtTag = document.createElement("span");
1024
+ fmtTag.className = "fmt-tag";
1025
+ fmtTag.textContent = item.format || "MP4";
1026
+ const subInfo = document.createElement("span");
1027
+ subInfo.textContent = `${item.quality} • ${item.time}`;
1028
+ sub.appendChild(fmtTag);
1029
+ sub.appendChild(subInfo);
1030
+
1031
+ meta.appendChild(title);
1032
+ meta.appendChild(sub);
1033
+
1034
+ const openBtn = document.createElement("button");
1035
+ openBtn.type = "button";
1036
+ openBtn.className = "btn secondary sm";
1037
+ openBtn.style.flexShrink = "0";
1038
+ openBtn.textContent = "📂 Show";
1039
+ openBtn.onclick = () => openFolder({ path: item.file_path });
1040
+
1041
+ row.appendChild(meta);
1042
+ row.appendChild(openBtn);
1043
+ container.appendChild(row);
1044
+ });
1045
+ }
1046
+
1047
+ $("clear-history").onclick = () => {
1048
+ localStorage.removeItem("cliphaven_history");
1049
+ renderHistory();
1050
+ };
1051
+
1052
+ // Cancel download button
1053
+ $("cancel").onclick = async () => {
1054
+ if (!currentJobId) return;
1055
+ const cb = $("cancel");
1056
+ cb.disabled = true;
1057
+ try {
1058
+ await api("/api/cancel", {
1059
+ method: "POST",
1060
+ body: JSON.stringify({ id: currentJobId }),
1061
+ });
1062
+ } catch (e) {
1063
+ status("Cancel failed", e.message, 0, "Error", "error");
1064
+ } finally {
1065
+ cb.disabled = false;
1066
+ }
1067
+ };
1068
+
1069
+ // Poll active download job
1070
+ function startPolling(jobId) {
1071
+ if (timer) clearInterval(timer);
1072
+ currentJobId = jobId;
1073
+ let errCount = 0;
1074
+ localStorage.setItem("cliphaven_active_job", jobId);
1075
+ const b = $("start");
1076
+ const cb = $("cancel");
1077
+ b.disabled = true;
1078
+ window.__clipHavenSetBtn && window.__clipHavenSetBtn("downloading");
1079
+ cb.style.display = "inline-block";
1080
+
1081
+ timer = setInterval(async () => {
1082
+ try {
1083
+ const s = await api("/api/status?id=" + encodeURIComponent(jobId));
1084
+ errCount = 0;
1085
+ const isDone = s.state === "Complete";
1086
+ const isErr = s.state === "Error" || s.state === "Cancelled";
1087
+ if (s.file_path || s.folder) {
1088
+ lastCompletedPath = s.file_path || s.folder;
1089
+ }
1090
+ const plInfo =
1091
+ s.playlist_total && s.playlist_total > 1
1092
+ ? {
1093
+ index: s.playlist_index,
1094
+ total: s.playlist_total,
1095
+ done: s.playlist_done,
1096
+ left: s.playlist_left,
1097
+ }
1098
+ : null;
1099
+ status(
1100
+ s.title || s.state,
1101
+ s.detail || "",
1102
+ s.percent || 0,
1103
+ s.stage || s.state || "Working",
1104
+ isErr ? "error" : isDone ? "success" : "",
1105
+ s.speed || "",
1106
+ s.eta || "",
1107
+ isDone,
1108
+ Boolean(s.indeterminate && !isDone && !isErr),
1109
+ plInfo,
1110
+ );
1111
+ if (isDone || isErr) {
1112
+ clearInterval(timer);
1113
+ timer = null;
1114
+ b.disabled = false;
1115
+ window.__clipHavenSetBtn && window.__clipHavenSetBtn("ready");
1116
+ cb.style.display = "none";
1117
+ currentJobId = null;
1118
+ localStorage.removeItem("cliphaven_active_job");
1119
+ if (isDone) {
1120
+ const pillEl = $("pill");
1121
+ if (pillEl) {
1122
+ pillEl.className = "pill done-pop";
1123
+ pillEl.textContent = "✓ Done";
1124
+ }
1125
+ addToHistory({ id: jobId, url: activeDownloadUrl || $("url").value.trim(), format: $("format").value, ...s });
1126
+ }
1127
+ activeDownloadUrl = "";
1128
+ if (window.__clipHavenOnTransferEnd) window.__clipHavenOnTransferEnd(isDone);
1129
+ }
1130
+ } catch (err) {
1131
+ if (++errCount < 4) return;
1132
+ clearInterval(timer);
1133
+ timer = null;
1134
+ status("Status error", err.message, 0, "Error", "error");
1135
+ b.disabled = false;
1136
+ window.__clipHavenSetBtn && window.__clipHavenSetBtn("ready");
1137
+ cb.style.display = "none";
1138
+ currentJobId = null;
1139
+ localStorage.removeItem("cliphaven_active_job");
1140
+ }
1141
+ }, 750);
1142
+ }
1143
+
1144
+ // Form submission
1145
+ $("form").onsubmit = async (e) => {
1146
+ e.preventDefault();
1147
+ const b = $("start");
1148
+ const cb = $("cancel");
1149
+ if (window.__clipHavenIsPlaylistZero && window.__clipHavenIsPlaylistZero()) {
1150
+ window.__clipHavenFlashPlaylistErr && window.__clipHavenFlashPlaylistErr();
1151
+ return;
1152
+ }
1153
+ if (currentJobId) {
1154
+ if (window.__clipHavenTryAddUpNext && window.__clipHavenTryAddUpNext()) return;
1155
+ return;
1156
+ }
1157
+ if (b.disabled) return;
1158
+ if (timer) clearInterval(timer);
1159
+ // Stop any active background playlist preview stream so download gets 100% bandwidth & CPU
1160
+ stopPlaylistStream(true);
1161
+
1162
+ b.disabled = true;
1163
+ window.__clipHavenSetBtn && window.__clipHavenSetBtn("starting");
1164
+ cb.style.display = "none";
1165
+ cb.disabled = false;
1166
+ currentJobId = null;
1167
+
1168
+ const chosenFolder = $("folder").value.trim();
1169
+ if (chosenFolder) localStorage.setItem("cliphaven_folder", formatDisplayFolder(chosenFolder));
1170
+
1171
+ const fmt = $("format").value;
1172
+ const isAudio = ["mp3", "m4a", "wav"].includes(fmt);
1173
+ const canThumb = ["mp4", "mkv", "mp3", "m4a"].includes(fmt);
1174
+ const cleanUrl = normalizeInputUrl($("url").value);
1175
+ if (cleanUrl && cleanUrl !== $("url").value) {
1176
+ $("url").value = cleanUrl;
1177
+ syncClearBtn();
1178
+ }
1179
+
1180
+ status(
1181
+ "Starting download",
1182
+ "Checking video link and preparing stream…",
1183
+ 0,
1184
+ "Starting",
1185
+ "",
1186
+ "",
1187
+ "",
1188
+ false,
1189
+ true,
1190
+ );
1191
+ try {
1192
+ const d = await api("/api/download", {
1193
+ method: "POST",
1194
+ body: JSON.stringify({
1195
+ url: cleanUrl,
1196
+ folder: chosenFolder,
1197
+ quality: $("quality").value,
1198
+ format: fmt,
1199
+ start_time: $("start-time").value.trim(),
1200
+ end_time: $("end-time").value.trim(),
1201
+ subtitles: !isAudio && $("subtitles").checked,
1202
+ embed_thumbnail: canThumb && $("embed-thumbnail").checked,
1203
+ allow_playlist: $("allow-playlist").checked || Boolean(getPlaylistItemsParam()) || /\/playlist\b/i.test(cleanUrl),
1204
+ playlist_items: getPlaylistItemsParam(),
1205
+ title_hint: currentTitleHint,
1206
+ duration_hint: currentDurationHint,
1207
+ lang: localStorage.getItem("cliphaven_lang") || "en",
1208
+ thumb_url: ($("preview-thumb") && /^https?:/i.test($("preview-thumb").src || "")) ? $("preview-thumb").src : "",
1209
+ }),
1210
+ });
1211
+ activeDownloadUrl = cleanUrl;
1212
+ startPolling(d.id);
1213
+ window.__clipHavenSyncPrimaryBtn && window.__clipHavenSyncPrimaryBtn();
1214
+ } catch (err) {
1215
+ status("Could not start download", err.message, 0, "Error", "error");
1216
+ b.disabled = false;
1217
+ window.__clipHavenSetBtn && window.__clipHavenSetBtn("ready");
1218
+ cb.style.display = "none";
1219
+ currentJobId = null;
1220
+ }
1221
+ };
1222
+
1223
+
1224
+ // In-App Update Check & Self-Updater (Android Auto-Install + Desktop Modal)
1225
+ let updatePollTimer = null;
1226
+ let latestUpdateInfo = null;
1227
+
1228
+ function showUpdateModal(info) {
1229
+ latestUpdateInfo = info;
1230
+ const modal = $("update-modal");
1231
+ if (!modal) return;
1232
+ $("update-version-line").textContent = `v${info.current_version} → v${info.latest_version}`;
1233
+ $("update-notes-content").textContent =
1234
+ info.release_notes || "Performance improvements and updated platform extractors.";
1235
+ const isAndroid = Boolean(window.ClipHavenAndroid || info.is_android);
1236
+ $("update-modal-desc").textContent = isAndroid
1237
+ ? "Tap Update Now to download and install the update directly inside ClipHaven."
1238
+ : "A newer version of ClipHaven is ready. Click below to view and download the update.";
1239
+ $("update-now-btn").textContent = isAndroid ? "🚀 Update Now" : "🌐 View & Download Update";
1240
+ $("update-now-btn").disabled = false;
1241
+ $("update-later-btn").disabled = false;
1242
+ $("update-progress-wrap").style.display = "none";
1243
+ modal.style.display = "grid";
1244
+ }
1245
+
1246
+ $("update-later-btn").onclick = () => {
1247
+ if (updatePollTimer) {
1248
+ clearInterval(updatePollTimer);
1249
+ updatePollTimer = null;
1250
+ }
1251
+ $("update-modal").style.display = "none";
1252
+ };
1253
+
1254
+ $("update-now-btn").onclick = async () => {
1255
+ if (!latestUpdateInfo) return;
1256
+ const isAndroid = Boolean(window.ClipHavenAndroid || latestUpdateInfo.is_android);
1257
+ if (!isAndroid) {
1258
+ window.open(
1259
+ latestUpdateInfo.release_url || "https://github.com/AsadullahAlMunib/ClipHaven/releases/latest",
1260
+ "_blank",
1261
+ "noopener,noreferrer",
1262
+ );
1263
+ $("update-modal").style.display = "none";
1264
+ return;
1265
+ }
1266
+
1267
+ const nowBtn = $("update-now-btn");
1268
+ const laterBtn = $("update-later-btn");
1269
+ nowBtn.disabled = true;
1270
+ nowBtn.textContent = "Downloading…";
1271
+ $("update-progress-wrap").style.display = "block";
1272
+ $("update-progress-bar").value = 0;
1273
+ $("update-progress-text").textContent = "Starting background update download…";
1274
+
1275
+ try {
1276
+ await api("/api/self-update", {
1277
+ method: "POST",
1278
+ body: JSON.stringify({ apk_url: latestUpdateInfo.apk_url || "" }),
1279
+ });
1280
+ if (updatePollTimer) clearInterval(updatePollTimer);
1281
+ updatePollTimer = setInterval(async () => {
1282
+ try {
1283
+ const st = await api("/api/self-update-status");
1284
+ $("update-progress-bar").value = Math.max(0, Math.min(100, st.percent || 0));
1285
+ $("update-progress-text").textContent = st.detail || "Downloading update…";
1286
+ if (st.state === "Complete") {
1287
+ clearInterval(updatePollTimer);
1288
+ updatePollTimer = null;
1289
+ nowBtn.disabled = false;
1290
+ nowBtn.textContent = "📂 Open Downloads to Install";
1291
+ laterBtn.disabled = false;
1292
+ } else if (st.state === "Error") {
1293
+ clearInterval(updatePollTimer);
1294
+ updatePollTimer = null;
1295
+ nowBtn.disabled = false;
1296
+ nowBtn.textContent = "🔄 Retry Update";
1297
+ laterBtn.disabled = false;
1298
+ }
1299
+ } catch {
1300
+ // Ignore transient poll errors
1301
+ }
1302
+ }, 500);
1303
+ } catch (err) {
1304
+ $("update-progress-text").textContent = err.message || "Update failed.";
1305
+ nowBtn.disabled = false;
1306
+ nowBtn.textContent = "🔄 Retry Update";
1307
+ }
1308
+ };
1309
+
1310
+ async function checkForAppUpdates() {
1311
+ try {
1312
+ const info = await api("/api/check-update");
1313
+ if (info && info.update_available) {
1314
+ showUpdateModal(info);
1315
+ }
1316
+ } catch {
1317
+ // Silent failover if offline or GitHub API unreachable
1318
+ }
1319
+ }
1320
+
1321
+ // Startup initialization: load config, FFmpeg check, folder memory, and active job recovery
1322
+ (async function init() {
1323
+ renderHistory();
1324
+ const savedFolder = formatDisplayFolder(
1325
+ localStorage.getItem("cliphaven_folder") || "",
1326
+ );
1327
+ if (savedFolder) {
1328
+ $("folder").value = savedFolder;
1329
+ }
1330
+ try {
1331
+ const cfg = await api("/api/config");
1332
+ if (!savedFolder && cfg.default_folder) {
1333
+ $("folder").value = formatDisplayFolder(cfg.default_folder);
1334
+ }
1335
+ if (cfg.ffmpeg === false) {
1336
+ $("ffmpeg-warning").style.display = "block";
1337
+ }
1338
+ const jobsList = cfg.jobs || [];
1339
+ const savedJob = localStorage.getItem("cliphaven_active_job");
1340
+ const activeServerJob = jobsList
1341
+ .slice()
1342
+ .reverse()
1343
+ .find((j) => !["Complete", "Error", "Cancelled"].includes(j.state));
1344
+
1345
+ if (savedJob) {
1346
+ const match = jobsList.find((j) => j.id === savedJob);
1347
+ if (match && !["Complete", "Error", "Cancelled"].includes(match.state)) {
1348
+ startPolling(savedJob);
1349
+ } else {
1350
+ if (match && match.state === "Complete") {
1351
+ lastCompletedPath = match.file_path || match.folder || "";
1352
+ addToHistory(match);
1353
+ status(
1354
+ match.title || "Download complete!",
1355
+ match.detail || "",
1356
+ 100,
1357
+ "Complete",
1358
+ "success",
1359
+ "",
1360
+ "",
1361
+ true,
1362
+ );
1363
+ }
1364
+ localStorage.removeItem("cliphaven_active_job");
1365
+ if (activeServerJob) {
1366
+ startPolling(activeServerJob.id);
1367
+ }
1368
+ }
1369
+ } else if (activeServerJob) {
1370
+ startPolling(activeServerJob.id);
1371
+ }
1372
+ } catch {
1373
+ if (!$("folder").value) {
1374
+ $("folder").value = "Downloads";
1375
+ }
1376
+ }
1377
+ setTimeout(checkForAppUpdates, 1500);
1378
+ })();
1379
+
1380
+
1381
+ // ============================================================================
1382
+ // ClipHaven v3.3.0 UI Controller
1383
+ // ============================================================================
1384
+ (function initClipHavenV330UI() {
1385
+ const I18N = {
1386
+ en: {
1387
+ tagline: "Paste a link, pick a format, and save your clip in seconds.",
1388
+ docs_btn: "Docs",
1389
+ docs_full: "Documentation",
1390
+ url_label: "Video or Playlist URL",
1391
+ paste: "Paste",
1392
+ playlist_select: "Select Playlist Videos",
1393
+ select_all: "Select All",
1394
+ single_only: "Single Video",
1395
+ playlist_select_err: "Please select at least 1 video from the playlist to download.",
1396
+ mode_video: "Video",
1397
+ mode_audio: "Audio Only",
1398
+ format_label: "Format",
1399
+ quality_label: "Resolution",
1400
+ save_folder: "Save Folder",
1401
+ browse: "Browse",
1402
+ folder_hint: "Remembered automatically for next time.",
1403
+ extra_dropdown: "Clip Trimmer, Subtitles (CC) & Options",
1404
+ trim_title: "Trim Range",
1405
+ full_video: "Full video",
1406
+ reset: "Reset",
1407
+ start_time: "Start Time",
1408
+ end_time: "End Time",
1409
+ subtitles: "Original Subtitles (CC)",
1410
+ embed_thumb: "Embed Cover Art",
1411
+ entire_playlist: "Entire Playlist",
1412
+ download_now: "Download Now",
1413
+ download_next: "Download Next",
1414
+ downloading: "Downloading...",
1415
+ starting: "Starting...",
1416
+ skip_next: "Skip",
1417
+ cancel: "Cancel",
1418
+ ready: "Ready",
1419
+ ready_detail: "Paste a video link to begin.",
1420
+ open_folder: "Open Folder",
1421
+ up_next: "Up Next",
1422
+ history_title: "Recent Downloads",
1423
+ clear: "Clear",
1424
+ privacy_prefix: "100% local on",
1425
+ privacy_suffix: "Downloads run one by one to keep speed steady.",
1426
+ update_title: "New Update Available",
1427
+ update_desc: "A newer version of ClipHaven is available with latest improvements and extractor fixes.",
1428
+ release_notes: "View Release Notes",
1429
+ update_now: "Update Now",
1430
+ later: "Later",
1431
+ clamped_max: (m) => `Cannot exceed video length (${m}) — adjusted automatically.`,
1432
+ clamped_order: "Start time must be before End time — adjusted automatically.",
1433
+ clip_len: (s) => `Clip: ${s}`,
1434
+ added_next: "Added to Up Next — ready for another link.",
1435
+ copied: "Link copied!",
1436
+ dropped: "Link dropped!",
1437
+ already_running: "This video is already downloading. Paste a new link to download next.",
1438
+ },
1439
+ bn: {
1440
+ tagline: "লিংক পেস্ট করুন, ফরম্যাট বেছে নিন আর কয়েক সেকেন্ডেই সেভ করুন।",
1441
+ docs_btn: "নথি",
1442
+ docs_full: "নির্দেশিকা",
1443
+ url_label: "ভিডিও বা প্লেলিস্ট লিংক",
1444
+ paste: "পেস্ট",
1445
+ playlist_select: "প্লেলিস্টের ভিডিও বেছে নাও",
1446
+ select_all: "সব সিলেক্ট",
1447
+ single_only: "শুধু ১টি ভিডিও",
1448
+ playlist_select_err: "ডাউনলোড করতে প্লেলিস্ট থেকে অন্তত ১টি ভিডিও সিলেক্ট করুন।",
1449
+ mode_video: "ভিডিও",
1450
+ mode_audio: "শুধু অডিও",
1451
+ format_label: "ফরম্যাট",
1452
+ quality_label: "রেজুলেশন",
1453
+ save_folder: "সেভ ফোল্ডার",
1454
+ browse: "ব্রাউজ",
1455
+ folder_hint: "পরবর্তী ডাউনলোডের জন্য অটোমেটিক মনে থাকবে।",
1456
+ extra_dropdown: "ক্লিপ ট্রিমার, সাবটাইটেল (CC) ও অতিরিক্ত অপশন",
1457
+ trim_title: "ক্লিপ রেঞ্জ",
1458
+ full_video: "সম্পূর্ণ ভিডিও",
1459
+ reset: "রিসেট",
1460
+ start_time: "শুরুর সময়",
1461
+ end_time: "শেষের সময়",
1462
+ subtitles: "অরিজিনাল সাবটাইটেল (CC)",
1463
+ embed_thumb: "কভার আর্ট এম্বেড",
1464
+ entire_playlist: "পুরো প্লেলিস্ট",
1465
+ download_now: "ডাউনলোড শুরু",
1466
+ download_next: "পরে ডাউনলোড করুন",
1467
+ downloading: "ডাউনলোড চলছে...",
1468
+ starting: "শুরু হচ্ছে...",
1469
+ skip_next: "পরেরটি",
1470
+ cancel: "বাতিল",
1471
+ ready: "প্রস্তুত",
1472
+ ready_detail: "শুরু করতে একটি ভিডিও লিংক পেস্ট করুন।",
1473
+ open_folder: "ফোল্ডার খোলো",
1474
+ up_next: "পরবর্তী ডাউনলোড",
1475
+ history_title: "সম্প্রতি ডাউনলোড করা",
1476
+ clear: "ক্লিয়ার",
1477
+ privacy_prefix: "১০০% লোকাল ইঞ্জিন",
1478
+ privacy_suffix: "একের পর এক ডাউনলোড হওয়ায় স্পিড একদম স্থির থাকে।",
1479
+ update_title: "নতুন আপডেট পাওয়া গেছে",
1480
+ update_desc: "নতুন উন্নতি ও এক্সট্র্যাক্টর ফিক্সসহ ClipHaven-এর নতুন ভার্সন প্রস্তুত।",
1481
+ release_notes: "রিলিজ নোট দেখুন",
1482
+ update_now: "আপডেট করুন",
1483
+ later: "পরে",
1484
+ clamped_max: (m) => `ভিডিওর মোট সময়ের (${m}) বেশি দেওয়া যাবে না — অটো ঠিক করা হয়েছে।`,
1485
+ clamped_order: "শুরুর সময় শেষের সময়ের আগে হতে হবে — অটো ঠিক করা হয়েছে।",
1486
+ clip_len: (s) => `ক্লিপ: ${s}`,
1487
+ added_next: "পরবর্তী ডাউনলোডে যুক্ত হয়েছে — নতুন লিংক দিতে পারো।",
1488
+ copied: "লিংক কপি হয়েছে!",
1489
+ dropped: "লিংক ড্রপ করা হয়েছে!",
1490
+ already_running: "এই ভিডিওটি এখন ডাউনলোড হচ্ছে। নতুন লিংক পেস্ট করলে পরে ডাউনলোড হবে।",
1491
+ },
1492
+ };
1493
+
1494
+ let lang = localStorage.getItem("cliphaven_lang") || "en";
1495
+ let toastTimer = null;
1496
+ function showToast(msg) {
1497
+ const el = $("toast");
1498
+ if (!el) return;
1499
+ el.textContent = msg;
1500
+ el.classList.add("show");
1501
+ clearTimeout(toastTimer);
1502
+ toastTimer = setTimeout(() => el.classList.remove("show"), 2600);
1503
+ }
1504
+
1505
+ function applyLang(next) {
1506
+ lang = next === "bn" ? "bn" : "en";
1507
+ localStorage.setItem("cliphaven_lang", lang);
1508
+ if ($("lang-flag")) $("lang-flag").textContent = lang === "en" ? "🇧🇩" : "🇬🇧";
1509
+ if ($("lang-sm")) $("lang-sm").textContent = lang === "en" ? "বাং" : "EN";
1510
+ if ($("lang-md")) $("lang-md").textContent = lang === "en" ? "বাংলা" : "ENG";
1511
+ if ($("lang-lg")) $("lang-lg").textContent = lang === "en" ? "বাংলা" : "English";
1512
+
1513
+ const dict = I18N[lang];
1514
+ document.querySelectorAll("[data-i18n]").forEach((el) => {
1515
+ const k = el.getAttribute("data-i18n");
1516
+ if (dict[k] && typeof dict[k] === "string") el.textContent = dict[k];
1517
+ });
1518
+ applyTheme(document.documentElement.getAttribute("data-theme") || "dark", false);
1519
+ updateClipBadge();
1520
+ syncPrimaryBtn();
1521
+ }
1522
+
1523
+ if ($("lang-btn")) {
1524
+ $("lang-btn").addEventListener("click", () => applyLang(lang === "en" ? "bn" : "en"));
1525
+ }
1526
+
1527
+ const VIDEO_FMTS = [{ v: "mp4", l: "MP4" }, { v: "mkv", l: "MKV" }, { v: "webm", l: "WEBM" }];
1528
+ const AUDIO_FMTS = [{ v: "mp3", l: "MP3" }, { v: "m4a", l: "M4A" }, { v: "wav", l: "WAV" }];
1529
+ let activeMode = "video";
1530
+
1531
+ function renderFormatChips(selectedVal) {
1532
+ const wrap = $("format-chips");
1533
+ if (!wrap) return;
1534
+ const list = activeMode === "video" ? VIDEO_FMTS : AUDIO_FMTS;
1535
+ wrap.innerHTML = "";
1536
+ list.forEach((item, idx) => {
1537
+ const btn = document.createElement("button");
1538
+ btn.type = "button";
1539
+ btn.className = "chip" + ((selectedVal ? item.v === selectedVal : idx === 0) ? " active" : "");
1540
+ btn.textContent = item.l;
1541
+ btn.addEventListener("click", () => {
1542
+ wrap.querySelectorAll(".chip").forEach((c) => c.classList.remove("active"));
1543
+ btn.classList.add("active");
1544
+ $("format").value = item.v;
1545
+ $("format").dispatchEvent(new Event("change"));
1546
+ });
1547
+ wrap.appendChild(btn);
1548
+ });
1549
+ $("format").value = selectedVal || list[0].v;
1550
+ $("format").dispatchEvent(new Event("change"));
1551
+ if ($("quality-section")) $("quality-section").style.display = activeMode === "video" ? "flex" : "none";
1552
+ }
1553
+
1554
+ if ($("mode-video") && $("mode-audio")) {
1555
+ $("mode-video").addEventListener("click", () => {
1556
+ activeMode = "video";
1557
+ $("mode-tabs").classList.remove("is-audio");
1558
+ $("mode-video").classList.add("active");
1559
+ $("mode-audio").classList.remove("active");
1560
+ renderFormatChips("mp4");
1561
+ });
1562
+ $("mode-audio").addEventListener("click", () => {
1563
+ activeMode = "audio";
1564
+ $("mode-tabs").classList.add("is-audio");
1565
+ $("mode-audio").classList.add("active");
1566
+ $("mode-video").classList.remove("active");
1567
+ renderFormatChips("mp3");
1568
+ });
1569
+ renderFormatChips($("format").value || "mp4");
1570
+ }
1571
+
1572
+ if ($("quality-chips")) {
1573
+ $("quality-chips").querySelectorAll(".chip").forEach((btn) => {
1574
+ btn.addEventListener("click", () => {
1575
+ $("quality-chips").querySelectorAll(".chip").forEach((c) => c.classList.remove("active"));
1576
+ btn.classList.add("active");
1577
+ $("quality").value = btn.dataset.q;
1578
+ });
1579
+ });
1580
+ }
1581
+
1582
+ let knownDurationSec = 0;
1583
+ function secToTime(sec) {
1584
+ sec = Math.max(0, Math.floor(sec));
1585
+ const h = Math.floor(sec / 3600);
1586
+ const m = Math.floor((sec % 3600) / 60);
1587
+ const s = sec % 60;
1588
+ const pad = (n) => String(n).padStart(2, "0");
1589
+ return h > 0 ? `${h}:${pad(m)}:${pad(s)}` : `${pad(m)}:${pad(s)}`;
1590
+ }
1591
+
1592
+ function parseTimeSec(raw) {
1593
+ const s = String(raw || "").trim();
1594
+ if (!s) return null;
1595
+ if (/^\d+$/.test(s)) return parseInt(s, 10);
1596
+ const parts = s.split(":").map((p) => p.trim());
1597
+ if (parts.length < 2 || parts.length > 3 || parts.some((p) => !/^\d+$/.test(p))) return null;
1598
+ if (parts.length === 2) return parseInt(parts[0], 10) * 60 + parseInt(parts[1], 10);
1599
+ return parseInt(parts[0], 10) * 3600 + parseInt(parts[1], 10) * 60 + parseInt(parts[2], 10);
1600
+ }
1601
+
1602
+ let clampTimer = null;
1603
+ function showClampWarn(msg, inputEl) {
1604
+ if (!$("clamp-msg")) return;
1605
+ $("clamp-msg-text").textContent = msg;
1606
+ $("clamp-msg").classList.add("show");
1607
+ if (inputEl) inputEl.classList.add("input-clamped");
1608
+ clearTimeout(clampTimer);
1609
+ clampTimer = setTimeout(() => {
1610
+ $("clamp-msg").classList.remove("show");
1611
+ $("start-time").classList.remove("input-clamped");
1612
+ $("end-time").classList.remove("input-clamped");
1613
+ }, 3000);
1614
+ }
1615
+
1616
+ function updateClipBadge() {
1617
+ const badge = $("clip-len-badge");
1618
+ const resetBtn = $("reset-trim-btn");
1619
+ if (!badge) return;
1620
+ const sVal = $("start-time").value.trim();
1621
+ const eVal = $("end-time").value.trim();
1622
+ if (!sVal && !eVal) {
1623
+ badge.textContent = I18N[lang].full_video;
1624
+ if (resetBtn) resetBtn.style.display = "none";
1625
+ return;
1626
+ }
1627
+ if (resetBtn) resetBtn.style.display = "inline-flex";
1628
+ const sSec = parseTimeSec(sVal) || 0;
1629
+ const eSec = parseTimeSec(eVal) || knownDurationSec || 0;
1630
+ badge.textContent = eSec > sSec ? I18N[lang].clip_len(secToTime(eSec - sSec)) : `${sVal || "00:00"} – ${eVal || "End"}`;
1631
+ }
1632
+
1633
+ function updateSliderVisual() {
1634
+ if (!knownDurationSec || !$("range-start") || !$("range-end")) return;
1635
+ const s = Number($("range-start").value);
1636
+ const e = Number($("range-end").value);
1637
+ $("slider-fill").style.left = `${(s / knownDurationSec) * 100}%`;
1638
+ $("slider-fill").style.width = `${((e - s) / knownDurationSec) * 100}%`;
1639
+ updateClipBadge();
1640
+ updateExtraOptionsBadge();
1641
+ }
1642
+
1643
+ window.__clipHavenSetDuration = function (sec) {
1644
+ knownDurationSec = Math.max(0, Math.floor(sec || 0));
1645
+ const wrap = $("trim-slider-wrap");
1646
+ if (!wrap) return;
1647
+ if (knownDurationSec > 1) {
1648
+ wrap.style.display = "block";
1649
+ wrap.classList.remove("is-disabled");
1650
+ $("range-start").disabled = false;
1651
+ $("range-end").disabled = false;
1652
+ $("range-start").max = knownDurationSec;
1653
+ $("range-end").max = knownDurationSec;
1654
+ $("range-start").value = 0;
1655
+ $("range-end").value = knownDurationSec;
1656
+ if ($("slider-min-label")) $("slider-min-label").textContent = "00:00";
1657
+ $("slider-max-label").textContent = `Max: ${secToTime(knownDurationSec)}`;
1658
+ $("end-time").placeholder = `${secToTime(knownDurationSec)} (Full)`;
1659
+ updateSliderVisual();
1660
+ } else {
1661
+ wrap.style.display = "block";
1662
+ wrap.classList.add("is-disabled");
1663
+ $("range-start").disabled = true;
1664
+ $("range-end").disabled = true;
1665
+ $("range-start").value = 0;
1666
+ $("range-end").value = $("range-end").max || 600;
1667
+ $("slider-fill").style.left = "0%";
1668
+ $("slider-fill").style.width = "0%";
1669
+ if ($("slider-min-label")) $("slider-min-label").textContent = "";
1670
+ $("slider-max-label").textContent = "";
1671
+ $("end-time").placeholder = "End (e.g. 02:30)";
1672
+ updateClipBadge();
1673
+ }
1674
+ };
1675
+ window.__clipHavenSetDuration(0);
1676
+
1677
+ function showTip(which, sec) {
1678
+ if (!knownDurationSec) return;
1679
+ const tip = $(which === "start" ? "tip-start" : "tip-end");
1680
+ if (!tip) return;
1681
+ const pct = (sec / knownDurationSec) * 100;
1682
+ tip.style.left = `${Math.max(6, Math.min(94, pct))}%`;
1683
+ tip.textContent = secToTime(sec);
1684
+ tip.classList.add("show");
1685
+ }
1686
+ function hideTips() {
1687
+ $("tip-start") && $("tip-start").classList.remove("show");
1688
+ $("tip-end") && $("tip-end").classList.remove("show");
1689
+ }
1690
+
1691
+ if ($("range-start") && $("range-end")) {
1692
+ $("range-start").addEventListener("input", () => {
1693
+ let s = Number($("range-start").value);
1694
+ const e = Number($("range-end").value);
1695
+ if (s >= e) { s = Math.max(0, e - 1); $("range-start").value = s; }
1696
+ $("start-time").value = s > 0 ? secToTime(s) : "";
1697
+ updateSliderVisual();
1698
+ showTip("start", s);
1699
+ });
1700
+ $("range-end").addEventListener("input", () => {
1701
+ const s = Number($("range-start").value);
1702
+ let e = Number($("range-end").value);
1703
+ if (e <= s) { e = Math.min(knownDurationSec, s + 1); $("range-end").value = e; }
1704
+ $("end-time").value = e < knownDurationSec ? secToTime(e) : "";
1705
+ updateSliderVisual();
1706
+ showTip("end", e);
1707
+ });
1708
+ ["pointerup", "mouseup", "touchend", "change"].forEach((ev) => {
1709
+ $("range-start").addEventListener(ev, hideTips);
1710
+ $("range-end").addEventListener(ev, hideTips);
1711
+ });
1712
+ }
1713
+
1714
+ function validateManualTime(which) {
1715
+ const sEl = $("start-time");
1716
+ const eEl = $("end-time");
1717
+ let sSec = parseTimeSec(sEl.value);
1718
+ let eSec = parseTimeSec(eEl.value);
1719
+ if (knownDurationSec > 0) {
1720
+ if (which === "start" && sEl.value.trim() !== "" && sSec !== null) {
1721
+ if (sSec > knownDurationSec - 1) {
1722
+ sSec = Math.max(0, knownDurationSec - 1);
1723
+ sEl.value = secToTime(sSec);
1724
+ showClampWarn(I18N[lang].clamped_max(secToTime(knownDurationSec)), sEl);
1725
+ }
1726
+ const curEnd = eSec !== null ? Math.min(eSec, knownDurationSec) : knownDurationSec;
1727
+ if (sSec >= curEnd) {
1728
+ sSec = Math.max(0, curEnd - 1);
1729
+ sEl.value = secToTime(sSec);
1730
+ showClampWarn(I18N[lang].clamped_order, sEl);
1731
+ }
1732
+ $("range-start").value = sSec;
1733
+ } else if (which === "start") {
1734
+ $("range-start").value = 0;
1735
+ }
1736
+
1737
+ if (which === "end" && eEl.value.trim() !== "" && eSec !== null) {
1738
+ if (eSec > knownDurationSec) {
1739
+ eSec = knownDurationSec;
1740
+ eEl.value = secToTime(eSec);
1741
+ showClampWarn(I18N[lang].clamped_max(secToTime(knownDurationSec)), eEl);
1742
+ }
1743
+ const curStart = sSec !== null ? Math.max(0, sSec) : 0;
1744
+ if (eSec <= curStart) {
1745
+ eSec = Math.min(knownDurationSec, curStart + 1);
1746
+ eEl.value = secToTime(eSec);
1747
+ showClampWarn(I18N[lang].clamped_order, eEl);
1748
+ }
1749
+ $("range-end").value = eSec;
1750
+ } else if (which === "end") {
1751
+ $("range-end").value = knownDurationSec;
1752
+ }
1753
+ updateSliderVisual();
1754
+ } else {
1755
+ updateClipBadge();
1756
+ }
1757
+ }
1758
+
1759
+ ["change", "blur"].forEach((ev) => {
1760
+ $("start-time").addEventListener(ev, () => validateManualTime("start"));
1761
+ $("end-time").addEventListener(ev, () => validateManualTime("end"));
1762
+ });
1763
+
1764
+ if ($("reset-trim-btn")) {
1765
+ $("reset-trim-btn").addEventListener("click", () => {
1766
+ $("start-time").value = "";
1767
+ $("end-time").value = "";
1768
+ if (knownDurationSec > 0) {
1769
+ $("range-start").value = 0;
1770
+ $("range-end").value = knownDurationSec;
1771
+ updateSliderVisual();
1772
+ } else {
1773
+ updateClipBadge();
1774
+ updateExtraOptionsBadge();
1775
+ }
1776
+ });
1777
+ }
1778
+
1779
+ window.__clipHavenIsPlaylistZero = function () {
1780
+ const boxes = document.querySelectorAll(".pl-item-checkbox");
1781
+ if (!isCurrentUrlPlaylist || boxes.length === 0) return false;
1782
+ let checked = 0;
1783
+ boxes.forEach((b) => { if (b.checked) checked++; });
1784
+ return checked === 0;
1785
+ };
1786
+
1787
+ window.__clipHavenFlashPlaylistErr = function () {
1788
+ const err = $("playlist-err");
1789
+ if (!err) return;
1790
+ err.classList.add("show");
1791
+ err.classList.remove("shake");
1792
+ void err.offsetWidth;
1793
+ err.classList.add("shake");
1794
+ if ($("playlist-selector")) $("playlist-selector").open = true;
1795
+ };
1796
+
1797
+ function syncPlaylistZeroGuard() {
1798
+ const blocked = window.__clipHavenIsPlaylistZero();
1799
+ const err = $("playlist-err");
1800
+ if (err) err.classList.toggle("show", blocked);
1801
+ syncPrimaryBtn();
1802
+ }
1803
+
1804
+ if ($("playlist-items-list")) {
1805
+ $("playlist-items-list").addEventListener("change", syncPlaylistZeroGuard);
1806
+ }
1807
+ if ($("pl-select-all-btn")) {
1808
+ $("pl-select-all-btn").addEventListener("click", () => {
1809
+ document.querySelectorAll(".pl-item-checkbox").forEach((cb) => { cb.checked = true; });
1810
+ $("allow-playlist").checked = true;
1811
+ updateExtraOptionsBadge();
1812
+ syncPlaylistZeroGuard();
1813
+ });
1814
+ }
1815
+ if ($("pl-clear-all-btn")) {
1816
+ $("pl-clear-all-btn").addEventListener("click", () => {
1817
+ document.querySelectorAll(".pl-item-checkbox").forEach((cb) => { cb.checked = false; });
1818
+ $("allow-playlist").checked = false;
1819
+ updateExtraOptionsBadge();
1820
+ syncPlaylistZeroGuard();
1821
+ });
1822
+ }
1823
+ if ($("allow-playlist")) {
1824
+ $("allow-playlist").addEventListener("change", (e) => {
1825
+ const isChecked = Boolean(e.target.checked);
1826
+ document.querySelectorAll(".pl-item-checkbox").forEach((cb) => { cb.checked = isChecked; });
1827
+ updateExtraOptionsBadge();
1828
+ syncPlaylistZeroGuard();
1829
+ });
1830
+ }
1831
+ if ($("playlist-search")) {
1832
+ $("playlist-search").addEventListener("input", (e) => {
1833
+ const q = e.target.value.trim().toLowerCase();
1834
+ document.querySelectorAll("#playlist-items-list .playlist-item-row").forEach((row) => {
1835
+ row.style.display = !q || row.textContent.toLowerCase().includes(q) ? "flex" : "none";
1836
+ });
1837
+ });
1838
+ }
1839
+
1840
+ const STORAGE_UPNEXT = "cliphaven_upnext_v33";
1841
+ let upNext = [];
1842
+ try { upNext = JSON.parse(localStorage.getItem(STORAGE_UPNEXT) || "[]") || []; } catch (_) { upNext = []; }
1843
+ function saveUpNext() { try { localStorage.setItem(STORAGE_UPNEXT, JSON.stringify(upNext)); } catch (_) {} }
1844
+
1845
+ function setPrimaryVisual(mode) {
1846
+ const btn = $("start");
1847
+ const lbl = $("start-label");
1848
+ const ic = $("start-icon");
1849
+ if (!btn || !lbl || !ic) return;
1850
+ if (mode === "blocked") {
1851
+ btn.classList.add("is-blocked");
1852
+ btn.classList.remove("mode-next");
1853
+ btn.disabled = false;
1854
+ btn.setAttribute("aria-disabled", "true");
1855
+ return;
1856
+ }
1857
+ btn.classList.remove("is-blocked");
1858
+ btn.removeAttribute("aria-disabled");
1859
+
1860
+ if (mode === "next") {
1861
+ const wasNext = btn.classList.contains("mode-next");
1862
+ btn.classList.add("mode-next");
1863
+ btn.disabled = false;
1864
+ lbl.textContent = I18N[lang].download_next;
1865
+ ic.innerHTML = '<line x1="12" y1="5" x2="12" y2="19"/><line x1="5" y1="12" x2="19" y2="12"/>';
1866
+ if (!wasNext) {
1867
+ btn.classList.remove("morph-pop");
1868
+ void btn.offsetWidth;
1869
+ btn.classList.add("morph-pop");
1870
+ }
1871
+ } else if (mode === "downloading" || mode === "starting") {
1872
+ btn.classList.remove("mode-next");
1873
+ btn.disabled = true;
1874
+ lbl.textContent = mode === "starting" ? I18N[lang].starting : I18N[lang].downloading;
1875
+ ic.innerHTML = '<circle cx="12" cy="12" r="9"/><polyline points="12 7 12 12 15 15"/>';
1876
+ } else {
1877
+ btn.classList.remove("mode-next");
1878
+ btn.disabled = false;
1879
+ lbl.textContent = I18N[lang].download_now;
1880
+ ic.innerHTML = '<path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><polyline points="7 10 12 15 17 10"/><line x1="12" y1="15" x2="12" y2="3"/>';
1881
+ }
1882
+ }
1883
+
1884
+ function syncPrimaryBtn() {
1885
+ if (window.__clipHavenIsPlaylistZero()) {
1886
+ setPrimaryVisual("blocked");
1887
+ return;
1888
+ }
1889
+ const curUrl = normalizeInputUrl($("url").value);
1890
+ if (!currentJobId) {
1891
+ setPrimaryVisual("ready");
1892
+ } else if (curUrl && curUrl !== activeDownloadUrl) {
1893
+ setPrimaryVisual("next");
1894
+ } else {
1895
+ setPrimaryVisual("downloading");
1896
+ }
1897
+ if ($("skip-btn")) {
1898
+ $("skip-btn").style.display = currentJobId && upNext.length > 0 ? "inline-flex" : "none";
1899
+ }
1900
+ }
1901
+
1902
+ window.__clipHavenSetBtn = setPrimaryVisual;
1903
+ window.__clipHavenSyncPrimaryBtn = syncPrimaryBtn;
1904
+
1905
+ function renderUpNext() {
1906
+ saveUpNext();
1907
+ const sec = $("upnext-section");
1908
+ if (!sec) return;
1909
+ $("upnext-count").textContent = String(upNext.length);
1910
+ if ($("skip-btn")) $("skip-btn").style.display = currentJobId && upNext.length > 0 ? "inline-flex" : "none";
1911
+ if (!upNext.length) {
1912
+ sec.style.display = "none";
1913
+ return;
1914
+ }
1915
+ sec.style.display = "flex";
1916
+ const list = $("upnext-list");
1917
+ list.innerHTML = "";
1918
+ upNext.forEach((item, idx) => {
1919
+ const row = document.createElement("div");
1920
+ row.className = "list-row";
1921
+ const meta = document.createElement("div");
1922
+ meta.className = "list-meta";
1923
+ const t = document.createElement("div");
1924
+ t.className = "list-title";
1925
+ t.textContent = `${idx + 1}. ${item.title || item.url}`;
1926
+ const sub = document.createElement("div");
1927
+ sub.className = "list-sub";
1928
+ const fmtTag = document.createElement("span");
1929
+ fmtTag.className = "fmt-tag";
1930
+ fmtTag.textContent = item.format;
1931
+ sub.appendChild(fmtTag);
1932
+ const qSpan = document.createElement("span");
1933
+ qSpan.textContent = ["mp3", "m4a", "wav"].includes(item.format) ? "Audio" : (item.quality === "best" ? "Best" : `${item.quality}p`);
1934
+ sub.appendChild(qSpan);
1935
+ if (item.start_time || item.end_time) {
1936
+ const cSpan = document.createElement("span");
1937
+ cSpan.textContent = `• ${item.start_time || "00:00"}–${item.end_time || "End"}`;
1938
+ sub.appendChild(cSpan);
1939
+ }
1940
+ if (item.subtitles) {
1941
+ const ccSpan = document.createElement("span");
1942
+ ccSpan.textContent = "• CC";
1943
+ sub.appendChild(ccSpan);
1944
+ }
1945
+ meta.append(t, sub);
1946
+
1947
+ const acts = document.createElement("div");
1948
+ acts.className = "row-actions";
1949
+ if (idx > 0) {
1950
+ const upBtn = document.createElement("button");
1951
+ upBtn.type = "button";
1952
+ upBtn.className = "icon-sq-btn";
1953
+ upBtn.title = "Move up";
1954
+ upBtn.innerHTML = '<svg class="icon" style="width:13px;height:13px" viewBox="0 0 24 24"><polyline points="18 15 12 9 6 15"/></svg>';
1955
+ upBtn.addEventListener("click", () => {
1956
+ const [m] = upNext.splice(idx, 1);
1957
+ upNext.splice(idx - 1, 0, m);
1958
+ renderUpNext();
1959
+ });
1960
+ acts.appendChild(upBtn);
1961
+ }
1962
+ const rmBtn = document.createElement("button");
1963
+ rmBtn.type = "button";
1964
+ rmBtn.className = "icon-sq-btn";
1965
+ rmBtn.title = "Remove";
1966
+ rmBtn.innerHTML = '<svg class="icon" style="width:13px;height:13px" viewBox="0 0 24 24"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>';
1967
+ rmBtn.addEventListener("click", () => {
1968
+ upNext.splice(idx, 1);
1969
+ renderUpNext();
1970
+ });
1971
+ acts.appendChild(rmBtn);
1972
+
1973
+ row.append(meta, acts);
1974
+ list.appendChild(row);
1975
+ });
1976
+ }
1977
+
1978
+ window.__clipHavenTryAddUpNext = function () {
1979
+ const cleanUrl = normalizeInputUrl($("url").value);
1980
+ if (!cleanUrl || cleanUrl === activeDownloadUrl) {
1981
+ showToast(I18N[lang].already_running);
1982
+ return true;
1983
+ }
1984
+ const fmt = $("format").value;
1985
+ const isAudio = ["mp3", "m4a", "wav"].includes(fmt);
1986
+ const canThumb = ["mp4", "mkv", "mp3", "m4a"].includes(fmt);
1987
+ upNext.push({
1988
+ url: cleanUrl,
1989
+ title: ($("preview-card").style.display !== "none" && $("preview-title").textContent) || cleanUrl.replace(/^https?:\/\/(www\.)?/, "").slice(0, 44),
1990
+ folder: $("folder").value.trim(),
1991
+ quality: $("quality").value,
1992
+ format: fmt,
1993
+ start_time: $("start-time").value.trim(),
1994
+ end_time: $("end-time").value.trim(),
1995
+ subtitles: !isAudio && $("subtitles").checked,
1996
+ embed_thumbnail: canThumb && $("embed-thumbnail").checked,
1997
+ allow_playlist: $("allow-playlist").checked || Boolean(getPlaylistItemsParam()) || /\/playlist\b/i.test(cleanUrl),
1998
+ playlist_items: getPlaylistItemsParam(),
1999
+ title_hint: currentTitleHint,
2000
+ duration_hint: currentDurationHint,
2001
+ lang: localStorage.getItem("cliphaven_lang") || "en",
2002
+ thumb_url: ($("preview-thumb") && /^https?:/i.test($("preview-thumb").src || "")) ? $("preview-thumb").src : "",
2003
+ });
2004
+ renderUpNext();
2005
+ showToast(I18N[lang].added_next);
2006
+ $("url").value = "";
2007
+ syncClearBtn();
2008
+ hidePreview();
2009
+ updatePlatformIcon("");
2010
+ syncPrimaryBtn();
2011
+ return true;
2012
+ };
2013
+
2014
+ async function launchQueuedItem(item) {
2015
+ activeDownloadUrl = item.url;
2016
+ try {
2017
+ const d = await api("/api/download", {
2018
+ method: "POST",
2019
+ body: JSON.stringify(item),
2020
+ });
2021
+ startPolling(d.id);
2022
+ syncPrimaryBtn();
2023
+ } catch (err) {
2024
+ status("Could not start queued download", err.message, 0, "Error", "error");
2025
+ activeDownloadUrl = "";
2026
+ syncPrimaryBtn();
2027
+ }
2028
+ }
2029
+
2030
+ window.__clipHavenOnTransferEnd = function () {
2031
+ syncPrimaryBtn();
2032
+ if (upNext.length > 0) {
2033
+ const next = upNext.shift();
2034
+ renderUpNext();
2035
+ setTimeout(() => launchQueuedItem(next), 350);
2036
+ }
2037
+ };
2038
+
2039
+ if ($("clear-upnext-btn")) {
2040
+ $("clear-upnext-btn").addEventListener("click", () => { upNext = []; renderUpNext(); });
2041
+ }
2042
+ if ($("skip-btn")) {
2043
+ $("skip-btn").addEventListener("click", async () => {
2044
+ if (!upNext.length) return;
2045
+ if (currentJobId) {
2046
+ try { await api("/api/cancel", { method: "POST", body: JSON.stringify({ id: currentJobId }) }); } catch (_) {}
2047
+ }
2048
+ });
2049
+ }
2050
+
2051
+ let _lastPlatformSig = "";
2052
+ function updatePlatformIcon(raw) {
2053
+ const ic = $("url-platform-icon");
2054
+ if (!ic) return;
2055
+ const u = String(raw || "").toLowerCase();
2056
+ const prevHtml = ic.innerHTML;
2057
+ if (u.includes("youtube.com") || u.includes("youtu.be") || u.includes("youtube-nocookie.com")) {
2058
+ ic.style.color = "#ef4444";
2059
+ ic.innerHTML = '<rect x="2" y="5" width="20" height="14" rx="4"/><polygon points="10 9 15 12 10 15" fill="currentColor" stroke="none"/>';
2060
+ } else if (u.includes("facebook.com") || u.includes("fb.watch") || u.includes("fb.com") || u.includes("fb.gg")) {
2061
+ ic.style.color = "#3b82f6";
2062
+ ic.innerHTML = '<path d="M18 2h-3a5 5 0 0 0-5 5v3H7v4h3v8h4v-8h3l1-4h-4V7a1 1 0 0 1 1-1h3z"/>';
2063
+ } else if (u.includes("instagram.com") || u.includes("instagr.am")) {
2064
+ ic.style.color = "#ec4899";
2065
+ ic.innerHTML = '<rect x="3" y="3" width="18" height="18" rx="5"/><circle cx="12" cy="12" r="4"/><circle cx="17.5" cy="6.5" r="1" fill="currentColor" stroke="none"/>';
2066
+ } else if (u.includes("threads.net") || u.includes("threads.com")) {
2067
+ ic.style.color = "var(--text)";
2068
+ ic.innerHTML = '<circle cx="12" cy="12" r="9"/><path d="M15.5 11.5c0-2-1.4-3.5-3.5-3.5s-3.5 1.5-3.5 3.5 1.4 3.5 3.5 3.5c1.5 0 2.7-.7 3.2-1.8"/>';
2069
+ } else if (u.includes("tiktok.com")) {
2070
+ ic.style.color = "#14b8a6";
2071
+ ic.innerHTML = '<path d="M9 12a4 4 0 1 0 4 4V4a5 5 0 0 0 5 5"/>';
2072
+ } else if (u.includes("twitter.com") || u.includes("x.com") || u.includes("t.co/")) {
2073
+ ic.style.color = "var(--text)";
2074
+ ic.innerHTML = '<path d="M4 4l16 16M20 4L4 20"/>';
2075
+ } else if (u.includes("linkedin.com") || u.includes("lnkd.in")) {
2076
+ ic.style.color = "#0a66c2";
2077
+ ic.innerHTML = '<rect x="3" y="3" width="18" height="18" rx="3"/><line x1="8" y1="11" x2="8" y2="16"/><circle cx="8" cy="8" r="0.8" fill="currentColor"/><path d="M12 16v-5m0 2a2 2 0 0 1 4 0v3"/>';
2078
+ } else if (u.includes("reddit.com") || u.includes("redd.it")) {
2079
+ ic.style.color = "#ff4500";
2080
+ ic.innerHTML = '<circle cx="12" cy="14" r="6"/><circle cx="9.8" cy="13.5" r="0.9" fill="currentColor" stroke="none"/><circle cx="14.2" cy="13.5" r="0.9" fill="currentColor" stroke="none"/><path d="M12 8l1.5-4 3 .8"/>';
2081
+ } else if (u.includes("vimeo.com")) {
2082
+ ic.style.color = "#1ab7ea";
2083
+ ic.innerHTML = '<path d="M4 7c1.5-1.5 3.2-1 4 1.2l1.8 6.3c.6 2 1.6 2.5 3.2 1.2 2.4-2 4.8-5.2 5.4-7.2.5-1.6-.4-2.5-2-2.2-1.1.2-2 1-2.5 2"/>';
2084
+ } else if (u.includes("dailymotion.com") || u.includes("dai.ly")) {
2085
+ ic.style.color = "#00aaff";
2086
+ ic.innerHTML = '<circle cx="11" cy="13" r="5"/><line x1="16" y1="5" x2="16" y2="18"/>';
2087
+ } else if (u.includes("twitch.tv")) {
2088
+ ic.style.color = "#9146ff";
2089
+ ic.innerHTML = '<path d="M4 3h16v11l-4 4h-4l-3 3v-3H4z"/><line x1="10" y1="8" x2="10" y2="12"/><line x1="15" y1="8" x2="15" y2="12"/>';
2090
+ } else if (u.includes("pinterest.com") || u.includes("pin.it")) {
2091
+ ic.style.color = "#e60023";
2092
+ ic.innerHTML = '<circle cx="12" cy="12" r="9"/><path d="M10 18l1.5-6.5M9.5 11.5a3 3 0 1 1 5.2 2c-.7 1-1.9 1.3-2.9.8"/>';
2093
+ } else if (u.includes("soundcloud.com") || u.includes("snd.sc")) {
2094
+ ic.style.color = "#ff5500";
2095
+ ic.innerHTML = '<path d="M17.5 17H8a4 4 0 0 1-.5-7.97A5 5 0 0 1 17 10a3.5 3.5 0 0 1 .5 7z"/><line x1="3" y1="13" x2="3" y2="16"/>';
2096
+ } else {
2097
+ ic.style.color = "var(--text-dim)";
2098
+ ic.innerHTML = '<path d="M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71"/><path d="M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71"/>';
2099
+ }
2100
+ const sig = ic.style.color + "|" + ic.innerHTML;
2101
+ if (_lastPlatformSig && sig !== _lastPlatformSig && prevHtml !== ic.innerHTML) {
2102
+ ic.classList.remove("icon-pop");
2103
+ void ic.offsetWidth;
2104
+ ic.classList.add("icon-pop");
2105
+ }
2106
+ _lastPlatformSig = sig;
2107
+ }
2108
+
2109
+ window.__clipHavenUpdatePlatformIcon = updatePlatformIcon;
2110
+ window.__clipHavenSyncPrimaryBtn = syncPrimaryBtn;
2111
+ updatePlatformIcon($("url").value);
2112
+
2113
+ $("url").addEventListener("input", () => {
2114
+ updatePlatformIcon($("url").value);
2115
+ syncPrimaryBtn();
2116
+ });
2117
+
2118
+ const formCard = $("form");
2119
+ if (formCard) {
2120
+ formCard.addEventListener("dragover", (e) => { e.preventDefault(); formCard.classList.add("drag-over"); });
2121
+ ["dragleave", "dragend"].forEach((ev) => formCard.addEventListener(ev, () => formCard.classList.remove("drag-over")));
2122
+ formCard.addEventListener("drop", (e) => {
2123
+ e.preventDefault();
2124
+ formCard.classList.remove("drag-over");
2125
+ const dropped = (e.dataTransfer?.getData("text/uri-list") || e.dataTransfer?.getData("text/plain") || "").trim();
2126
+ if (dropped && /^https?:\/\//i.test(dropped)) {
2127
+ $("url").value = dropped;
2128
+ syncClearBtn();
2129
+ updatePlatformIcon(dropped);
2130
+ triggerPreview(true);
2131
+ syncPrimaryBtn();
2132
+ showToast(I18N[lang].dropped);
2133
+ }
2134
+ });
2135
+ }
2136
+
2137
+ document.addEventListener("keydown", (e) => {
2138
+ if ((e.ctrlKey || e.metaKey) && e.key === "Enter") $("form").requestSubmit();
2139
+ });
2140
+
2141
+ applyLang(lang);
2142
+ renderUpNext();
2143
+ })();