-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathzen-stuff.uc.js
More file actions
796 lines (697 loc) · 27.8 KB
/
Copy pathzen-stuff.uc.js
File metadata and controls
796 lines (697 loc) · 27.8 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
// ==UserScript==
// @include main
// @loadOrder 99999999999998
// @ignorecache
// ==/UserScript==
// zen-stuff.uc.js
// Dismissed downloads pile with messy-to-grid transition
(function () {
"use strict";
// Wait for browser window to be ready
if (location.href !== "chrome://browser/content/browser.xhtml") return;
const Utils = window.zenTidyDownloadsUtils;
if (!Utils) {
console.error("[Zen Stuff] zenTidyDownloadsUtils not loaded - ensure tidy-downloads-utils.uc.js loads first (check @loadOrder in headers)");
return;
}
if (
!window.zenStuffCore?.PileState ||
!window.zenStuffCore?.ErrorHandler ||
!window.zenStuffCore?.createFileSystemApi ||
!window.zenStuffCore?.createEventManagerApi ||
!window.zenStuffSession?.createSessionApi ||
!window.zenStuffPileDom?.createPileDomApi ||
!window.zenStuffPodElement?.createPodElementFactory ||
!window.zenStuffPileLayout?.createPileLayoutApi ||
!window.zenStuffContextFileOps?.createContextFileOpsApi ||
!window.zenStuffPileVisibility?.createPileVisibilityApi ||
!window.zenStuffPileMaskRepair?.createMaskRepairApi ||
!window.zenStuffPileThemeColors?.createPileThemeColorsApi ||
!window.zenStuffPilePrefs?.createPilePrefsApi
) {
console.error(
"[Zen Stuff] Required modules missing (zen-stuff-core, zen-stuff-session, zen-stuff-pile-dom, zen-stuff-pod-element, zen-stuff-pile-layout, zen-stuff-context-fileops, zen-stuff-pile-visibility, zen-stuff-pile-prefs, zen-stuff-pile-theme-colors, zen-stuff-pile-mask-repair)"
);
return;
}
// Single-flight: avoid duplicate pile registration if this script is evaluated twice.
if (window.__zenStuffPileBundleExecuted) {
console.warn("[Zen Stuff] Bundle already executed in this window; skipping duplicate load.");
return;
}
window.__zenStuffPileBundleExecuted = true;
const {
validateFilePathOrThrow,
validatePodData,
formatBytes,
TEXT_EXTENSIONS,
SYSTEM_ICON_EXTENSIONS,
readTextFilePreview,
filenameEndsWithExtensionFromSet
} = Utils;
const { PileState, ErrorHandler, createFileSystemApi, createEventManagerApi } = window.zenStuffCore;
// Configuration
const CONFIG = {
maxPileSize: 20, // Maximum pods to keep in pile
pileDisplayCount: 20, // Pods visible in messy pile
gridAnimationDelay: 15, // ms between pod animations
hoverDebounceMs: 50, // Hover debounce delay
pileRotationRange: 8, // degrees ±
pileOffsetRange: 8, // pixels ±
gridPadding: 12, // pixels between grid items
minPodSize: 45, // minimum pod size in grid
minSidePadding: 5, // minimum padding from sidebar edges
animationDuration: 150, // pod transition duration
containerAnimationDuration: 80, // container height/padding transition duration
maxRetryAttempts: 10, // Maximum initialization retry attempts
retryDelay: 500, // Delay between retry attempts
};
const state = new PileState();
const FileSystem = createFileSystemApi({ validateFilePathOrThrow });
const EventManager = createEventManagerApi({ state });
/** @type {ReturnType<typeof window.zenStuffContextFileOps.createContextFileOpsApi>|null} */
let fileOpsApi = null;
/** @type {ReturnType<typeof window.zenStuffPileVisibility.createPileVisibilityApi>|null} */
let pileVisibilityApi = null;
/** @type {ReturnType<typeof window.zenStuffPileMaskRepair.createMaskRepairApi>|null} */
let maskRepairApi = null;
/** @type {ReturnType<typeof window.zenStuffPilePrefs.createPilePrefsApi>|null} */
let pilePrefsApi = null;
// Text-file preview toggle for dismissed pods (disabled by default). Images always get previews.
let zenStuffFilePreviewEnabled = false;
try {
if (typeof Services !== "undefined" && Services.prefs) {
// Opt-in for text-file previews; images always show regardless.
zenStuffFilePreviewEnabled = Services.prefs.getBoolPref("extensions.downloads.enable_file_preview", false);
}
} catch (e) {
// Fallback to disabled if prefs are unavailable
zenStuffFilePreviewEnabled = false;
}
// Debug logging with conditional output
function debugLog(message, data = null) {
// Only log in development mode or when explicitly enabled
if (typeof window.zenDebugMode !== 'undefined' && window.zenDebugMode) {
try {
console.log(`[Dismissed Pile] ${message}`, data || '');
} catch (e) {
console.log(`[Dismissed Pile] ${message}`);
}
}
}
/**
* Pile hover gate tracing. **Off unless** `window.__zenPileHoverDebug === true` in this window
* (Browser Toolbox → browser chrome console).
*/
function pileHoverDebug(message, data) {
if (window.__zenPileHoverDebug !== true) return;
try {
console.info("[PileHoverDebug]", message, data !== undefined ? data : "");
} catch (_e) {
/* ignore */
}
}
const {
generatePilePosition,
generateGridPosition,
applyPilePosition,
applyGridPosition,
debounce,
updatePileContainerWidth
} = window.zenStuffPileLayout.createPileLayoutApi({ state, CONFIG, debugLog });
/** @type {{ createPodElement: function }|null} */
let zenStuffPodElementImpl = null;
function createPodElement(podData) {
if (!zenStuffPodElementImpl) {
if (!fileOpsApi) {
console.error("[Zen Stuff] fileOpsApi not initialized before createPodElement");
throw new Error("Zen Stuff file ops not ready");
}
zenStuffPodElementImpl = window.zenStuffPodElement.createPodElementFactory({
formatBytes,
readTextFilePreview,
filenameEndsWithExtensionFromSet,
TEXT_EXTENSIONS,
SYSTEM_ICON_EXTENSIONS,
getZenStuffFilePreviewEnabled: () => zenStuffFilePreviewEnabled,
debugLog,
FileSystem,
setPileContextMenuActive: (v) => {
state.pileContextMenuActive = v;
},
openPodFile: (p) => fileOpsApi.openPodFile(p),
showPodFileInExplorer: (p) => fileOpsApi.showPodFileInExplorer(p),
ensurePodContextMenu: () => fileOpsApi.ensurePodContextMenu(),
getPodContextMenu: () => fileOpsApi.getPodContextMenu(),
setPodContextMenuPodData: (d) => fileOpsApi.setPodContextMenuPodData(d)
});
}
return zenStuffPodElementImpl.createPodElement(podData);
}
// Initialize the pile system with proper error handling
async function init() {
if (state.isInitialized) {
return;
}
if (window.__zenStuffPileInitInProgress) {
debugLog("init skipped: already in progress (single-flight)");
return;
}
window.__zenStuffPileInitInProgress = true;
debugLog("Initializing dismissed downloads pile system");
try {
// Check retry limit
if (state.retryCount >= CONFIG.maxRetryAttempts) {
console.error('[Dismissed Pile] Max retry attempts reached, initialization failed');
return;
}
// Wait for the main download script to be available
if (!window.zenTidyDownloads) {
state.retryCount++;
debugLog(`Main download script not ready, retry ${state.retryCount}/${CONFIG.maxRetryAttempts}`);
setTimeout(init, CONFIG.retryDelay);
return;
}
// Wait for SessionStore to be ready
await initSessionStore();
await ErrorHandler.withRetry(async () => {
await findDownloadButton();
await createPileContainer();
setupEventListeners();
loadExistingDismissedPods();
});
state.isInitialized = true;
state.retryCount = 0; // Reset retry count on success
debugLog("Dismissed downloads pile system initialized successfully");
} catch (error) {
ErrorHandler.handleError(error, 'initialization');
state.retryCount++;
setTimeout(init, CONFIG.retryDelay);
} finally {
window.__zenStuffPileInitInProgress = false;
}
}
/** @type {ReturnType<typeof window.zenStuffSession.createSessionApi>|null} */
let sessionApi = null;
async function initSessionStore() {
await sessionApi.initSessionStore();
}
function saveDismissedPodToSession(podData) {
sessionApi.saveDismissedPodToSession(podData);
}
function removeDismissedPodFromSession(podKey) {
sessionApi.removeDismissedPodFromSession(podKey);
}
async function restoreDismissedPodsFromSession() {
await sessionApi.restoreDismissedPodsFromSession();
}
function updatePodKeysInSession() {
sessionApi.updatePodKeysInSession();
}
// Find the Firefox/Zen Library downloads button. The Library widget can be
// created or recreated after this script starts, so a watcher below keeps
// hover listeners pointed at the current preferred target.
async function findDownloadButton() {
try {
console.log(`[Zen Stuff] Auto-detecting download button (trying zen-library-button first)...`);
const found = await Utils.findZenDownloadButton();
if (!found?.button) {
throw new Error("Download button not found after all attempts");
}
const { button, kind, detail } = found;
state.downloadButton = button;
if (kind === "zen-library") {
console.log("[Zen Stuff] ✅ Found zen-library-button for hover detection (auto-detected)");
debugLog("Found zen-library-button for hover detection (auto-detected)");
} else if (kind === "selector") {
console.log(`[Zen Stuff] ✅ Found download button using selector: ${detail}`, button);
debugLog(`Found download button using selector: ${detail}`);
} else {
debugLog("Found download button using fallback method", button);
}
} catch (error) {
console.error('[DownloadButton] Error finding download button:', error);
throw error;
}
}
const pileDomApi = window.zenStuffPileDom.createPileDomApi({
state,
CONFIG,
debugLog,
setupPileBackgroundHoverEvents: () => maskRepairApi?.setupPileBackgroundHoverEvents?.(),
setupCompactModeObserver: () => pilePrefsApi?.setupCompactModeObserver?.()
});
async function createPileContainer() {
await pileDomApi.createPileContainer();
}
const themeColorsApi = window.zenStuffPileThemeColors.createPileThemeColorsApi({
state,
debugLog
});
pileVisibilityApi = window.zenStuffPileVisibility.createPileVisibilityApi({
state,
CONFIG,
debugLog,
pileHoverDebug,
createPodElement,
saveDismissedPodToSession,
removeDismissedPodFromSession,
updatePodKeysInSession,
generateGridPosition,
applyGridPosition,
updateDownloadsButtonVisibility: () => pilePrefsApi.updateDownloadsButtonVisibility(),
updatePodTextColors: () => themeColorsApi.updatePodTextColors(),
showPileBackground: () => maskRepairApi.showPileBackground(),
hidePileBackground: () => maskRepairApi.hidePileBackground(),
hideWorkspaceScrollboxAfter: () => maskRepairApi.hideWorkspaceScrollboxAfter(),
showWorkspaceScrollboxAfter: () => maskRepairApi.showWorkspaceScrollboxAfter(),
schedulePileLayoutRepair: (source, delayMs) => maskRepairApi.schedulePileLayoutRepair(source, delayMs),
setupPileBackgroundHoverEvents: () => maskRepairApi.setupPileBackgroundHoverEvents(),
updatePointerEvents: () => pilePrefsApi.updatePointerEvents(),
updatePileContainerWidth: () => updatePileContainerWidth(),
getAlwaysShowPile: () => pilePrefsApi.getAlwaysShowPile(),
shouldPileBeVisible: () => pilePrefsApi.shouldPileBeVisible(),
isContextMenuVisible: () => isContextMenuVisible()
});
maskRepairApi = window.zenStuffPileMaskRepair.createMaskRepairApi({
state,
debugLog,
getVisibilityApi: () => pileVisibilityApi,
updatePointerEvents: () => pilePrefsApi.updatePointerEvents(),
updatePileHeight: () => updatePileHeight(),
isContextMenuVisible: () => isContextMenuVisible(),
getAlwaysShowPile: () => pilePrefsApi.getAlwaysShowPile(),
generateGridPosition,
applyGridPosition,
updatePodTextColors: () => themeColorsApi.updatePodTextColors()
});
pilePrefsApi = window.zenStuffPilePrefs.createPilePrefsApi({
state,
debugLog,
getShowPile: () => pileVisibilityApi.showPile(),
getHidePile: () => pileVisibilityApi.hidePile(),
schedulePileLayoutRepair: (source, delayMs) => maskRepairApi.schedulePileLayoutRepair(source, delayMs)
});
sessionApi = window.zenStuffSession.createSessionApi({
debugLog,
validateFilePathOrThrow,
FileSystem,
state,
addPodToPile: (podData, animate) => pileVisibilityApi.addPodToPile(podData, animate),
updatePileVisibility,
updateDownloadsButtonVisibility: () => pilePrefsApi.updateDownloadsButtonVisibility(),
getAlwaysShowPile: () => pilePrefsApi.getAlwaysShowPile(),
shouldPileBeVisible: () => pilePrefsApi.shouldPileBeVisible(),
showPile
});
/** Tidy Downloads: skip sticky toolbar pod while pile is expanded (hover OR pinned/always-show), or while the user hovers the library/downloads button. */
function isPileCurrentlyExpanded() {
return !!(state.dynamicSizer && state.dynamicSizer.style.height && state.dynamicSizer.style.height !== "0px");
}
window.__zenDismissedPileIntegration = {
isHoveringPileArea: () => pileVisibilityApi?.isHoveringPileArea?.() === true,
isPileExpanded: () => isPileCurrentlyExpanded(),
shouldSuppressStickyPod: () =>
isPileCurrentlyExpanded() ||
pileVisibilityApi?.isHoveringPileArea?.() === true ||
state.downloadButton?.matches(":hover") === true
};
function schedulePileLayoutRepair(source, delayMs = 80) {
return maskRepairApi.schedulePileLayoutRepair(source, delayMs);
}
function recalculateLayout() {
return maskRepairApi.recalculateLayout();
}
function attachMediaToolbarResizeObserverOnce() {
if (state.mediaToolbarResizeObserver) return;
const mt = document.getElementById("zen-media-controls-toolbar");
if (!mt || typeof ResizeObserver === "undefined") return;
state.mediaToolbarResizeObserver = new ResizeObserver(() => {
if (
state.dismissedPods.size > 0 &&
state.dynamicSizer &&
state.dynamicSizer.style.height !== "0px"
) {
schedulePileLayoutRepair("media-toolbar-resize", 40);
}
});
state.mediaToolbarResizeObserver.observe(mt);
debugLog("[PileRepair] ResizeObserver attached to zen-media-controls-toolbar");
}
/**
* Window/document listeners and timers — must run only once per browser window so init retries
* (after partial failures) do not stack duplicate callbacks on zenTidyDownloads or document.
*/
function setupGlobalPileListeners() {
if (state.zenStuffGlobalPileListenersAttached) {
return;
}
state.zenStuffGlobalPileListenersAttached = true;
window.zenTidyDownloads.onPodDismissed((podData) => {
debugLog("Received pod dismissal:", podData);
addPodToPile(podData);
});
document.addEventListener("pod-dismissed-updated", (ev) => {
try {
const d = ev?.detail;
if (!d || typeof d !== "object") return;
const { oldKey, newKey, podData } = d;
if (oldKey && state.dismissedPods.has(oldKey)) {
removePodFromPile(oldKey);
}
if (podData && newKey) {
addPodToPile(podData, false);
}
} catch (err) {
debugLog("[Pile] pod-dismissed-updated handler error", err);
}
});
if (typeof window.zenTidyDownloads.onProgressPilePod === "function") {
window.zenTidyDownloads.onProgressPilePod((msg) => {
if (!msg || typeof msg !== "object") return;
if (msg.kind === "rekey" && msg.oldKey && msg.podData) {
removePodFromPile(msg.oldKey);
addPodToPile(msg.podData);
return;
}
if (msg.kind === "upsert" && msg.podData) {
addPodToPile(msg.podData);
}
});
debugLog("[Pile] Registered onProgressPilePod listener");
}
document.addEventListener("keydown", handleKeyDown);
document.addEventListener("keyup", handleKeyUp);
pilePrefsApi.setupPreferenceListener();
window.addEventListener("resize", debounce(recalculateLayout, 250));
document.addEventListener("zen-tidy-library-pie-updated", () => {
try {
if (state.dynamicSizer && state.dynamicSizer.style.height !== "0px") {
pileVisibilityApi?.syncLibraryPieDockForPile?.();
}
} catch (_e) {
/* ignore */
}
});
if (window.zenTidyDownloads && typeof window.zenTidyDownloads.onActualDownloadRemoved === "function") {
window.zenTidyDownloads.onActualDownloadRemoved((removedKey) => {
debugLog(`[PileSync] Received actual download removal notification for key: ${removedKey}`);
if (state.dismissedPods.has(removedKey)) {
removePodFromPile(removedKey);
debugLog(`[PileSync] Removed pod ${removedKey} from pile as it was cleared from Firefox list.`);
}
});
debugLog("[PileSync] Registered listener for actual download removals.");
} else {
debugLog("[PileSync] Could not register listener for actual download removals - API not found on main script.");
}
document.addEventListener("request-pile-expand", () => {
pileHoverDebug("request-pile-expand fired", { dismissedPods: state.dismissedPods.size });
if (state.dismissedPods.size > 0) {
pileHoverDebug("request-pile-expand → showPile");
showPile();
maskRepairApi.showPileBackground();
schedulePileLayoutRepair("request-pile-expand", 60);
} else {
pileHoverDebug("request-pile-expand no-op: dismissedPods empty");
}
});
document.addEventListener("click", (e) => {
if (window.zenPileContextMenu && !window.zenPileContextMenu.contextMenu.contains(e.target)) {
hideContextMenu();
}
});
if (state.pileLayoutRepairIntervalId) {
clearInterval(state.pileLayoutRepairIntervalId);
}
state.pileLayoutRepairIntervalId = setInterval(() => {
if (state.dismissedPods.size > 0) {
schedulePileLayoutRepair("interval", 0);
}
}, 90000);
attachMediaToolbarResizeObserverOnce();
debugLog("Global pile listeners attached (once per window)");
}
/**
* Hover listeners on the current download button and pile DOM — run after each pile container build.
*/
function setupDomPileHoverListeners() {
const prevBtn = state.pileHoverDownloadButtonEl;
if (prevBtn && prevBtn !== state.downloadButton) {
prevBtn.removeEventListener("mouseenter", handleDownloadButtonHover);
prevBtn.removeEventListener("mouseleave", handleDownloadButtonLeave);
}
if (state.downloadButton) {
state.downloadButton.removeEventListener("mouseenter", handleDownloadButtonHover);
state.downloadButton.removeEventListener("mouseleave", handleDownloadButtonLeave);
state.downloadButton.addEventListener("mouseenter", handleDownloadButtonHover);
state.downloadButton.addEventListener("mouseleave", handleDownloadButtonLeave);
state.pileHoverDownloadButtonEl = state.downloadButton;
pileHoverDebug("download button hover listeners attached", {
tag: state.downloadButton.tagName,
id: state.downloadButton.id,
localName: state.downloadButton.localName
});
} else {
pileHoverDebug("WARNING: no download button — library hover will never fire");
state.pileHoverDownloadButtonEl = null;
}
if (state.dynamicSizer) {
state.dynamicSizer.addEventListener("mouseenter", handleDynamicSizerHover);
state.dynamicSizer.addEventListener("mouseleave", handleDynamicSizerLeave);
debugLog("Added hover listeners to dynamic sizer");
}
if (state.pileContainer) {
state.pileContainer.addEventListener("mouseenter", handlePileHover);
state.pileContainer.addEventListener("mouseleave", handlePileLeave);
}
debugLog("DOM pile hover listeners attached");
}
function handleDownloadButtonTargetChange(found) {
const previous = state.downloadButton;
state.downloadButton = found?.button || null;
if (found?.kind === "zen-library") {
debugLog("Using zen-library-button for hover detection", found.button);
} else if (found?.kind === "selector") {
debugLog(`Using downloads button selector for hover detection: ${found.detail}`, found.button);
} else if (found?.kind === "fallback") {
debugLog("Using fallback download element for hover detection", found.button);
} else {
debugLog("No download hover target is currently available");
}
if (previous !== state.downloadButton || state.pileHoverDownloadButtonEl !== state.downloadButton) {
setupDomPileHoverListeners();
}
}
function watchDownloadButtonTarget() {
if (state.downloadButtonWatcherCleanup || !Utils.watchZenDownloadButton) return;
state.downloadButtonWatcherCleanup = Utils.watchZenDownloadButton(handleDownloadButtonTargetChange);
}
function setupEventListeners() {
setupGlobalPileListeners();
setupDomPileHoverListeners();
watchDownloadButtonTarget();
debugLog("Event listeners setup complete");
}
// Load any existing dismissed pods from main script
function loadExistingDismissedPods() {
const existingPods = window.zenTidyDownloads.dismissedPods.getAll();
existingPods.forEach((podData, key) => {
addPodToPile(podData, false); // Don't animate existing pods
});
debugLog(`Loaded ${existingPods.size} existing dismissed pods`);
// Restore dismissed pods from SessionStore
restoreDismissedPodsFromSession();
// If always-show mode is enabled and we have pods (including session-only restores), show the pile
if (pilePrefsApi.getAlwaysShowPile() && state.dismissedPods.size > 0) {
setTimeout(() => {
if (pilePrefsApi.shouldPileBeVisible()) {
showPile();
debugLog("[AlwaysShow] Showing pile on startup - always-show mode enabled");
}
}, 100); // Small delay to ensure DOM is ready
}
}
// Add a pod to the pile
function addPodToPile(podData, animate = true) {
return pileVisibilityApi.addPodToPile(podData, animate);
}
// Remove a pod from the pile
function removePodFromPile(podKey) {
return pileVisibilityApi.removePodFromPile(podKey);
}
// Update pile visibility based on pod count
function updatePileVisibility(shouldAnimate = false) {
return pileVisibilityApi.updatePileVisibility(shouldAnimate);
}
// Update pile height dynamically based on current pod count (max 4)
function updatePileHeight() {
return pileVisibilityApi.updatePileHeight();
}
// Download button hover handler
function handleDownloadButtonHover() {
return pileVisibilityApi.handleDownloadButtonHover();
}
// Download button leave handler
function handleDownloadButtonLeave() {
return pileVisibilityApi.handleDownloadButtonLeave();
}
// Dynamic sizer hover handler
function handleDynamicSizerHover() {
return pileVisibilityApi.handleDynamicSizerHover();
}
// Dynamic sizer leave handler
function handleDynamicSizerLeave(event) {
return pileVisibilityApi.handleDynamicSizerLeave(event);
}
// Pile hover handler (simplified - no mode transitions)
function handlePileHover() {
return pileVisibilityApi.handlePileHover();
}
// Pile leave handler (simplified)
function handlePileLeave(event) {
return pileVisibilityApi.handlePileLeave(event);
}
// Show the pile
function showPile() {
return pileVisibilityApi.showPile();
}
// Hide the pile
function hidePile() {
return pileVisibilityApi.hidePile();
}
// Check if main download script has active pods to disable hover
function shouldDisableHover() {
return pileVisibilityApi.shouldDisableHover();
}
// applyTabsWrapperMask and removeTabsWrapperMask function removed - logic replaced by CSS mask-image with --zen-pile-height variable
// Helper: is cursor over pile area (including bridge between button and pile)
function isHoveringPileArea() {
return pileVisibilityApi.isHoveringPileArea();
}
// Alt key handlers for always-show mode
function handleKeyDown(event) {
if (event.key === 'Alt' && !state.isAltPressed) {
state.isAltPressed = true;
debugLog("[AlwaysShow] Alt key pressed");
if (pilePrefsApi.getAlwaysShowPile() && state.dismissedPods.size > 0) {
// Hide pile when Alt is pressed in always-show mode
hidePile();
}
}
}
function handleKeyUp(event) {
if (event.key === 'Alt' && state.isAltPressed) {
state.isAltPressed = false;
debugLog("[AlwaysShow] Alt key released");
if (pilePrefsApi.getAlwaysShowPile() && state.dismissedPods.size > 0) {
// Show pile again when Alt is released in always-show mode
showPile();
}
}
}
// Cleanup function to prevent memory leaks
function cleanup() {
debugLog("Cleaning up dismissed downloads pile system");
try {
// Clear all timeouts
if (state.hoverTimeout) {
clearTimeout(state.hoverTimeout);
state.hoverTimeout = null;
}
if (state.pileRepairDebounceId) {
clearTimeout(state.pileRepairDebounceId);
state.pileRepairDebounceId = null;
}
if (state.pileLayoutRepairIntervalId) {
clearInterval(state.pileLayoutRepairIntervalId);
state.pileLayoutRepairIntervalId = null;
}
if (state.mediaToolbarResizeObserver) {
try {
state.mediaToolbarResizeObserver.disconnect();
} catch (_e) {
/* ignore */
}
state.mediaToolbarResizeObserver = null;
}
if (state.downloadButtonWatcherCleanup) {
try {
state.downloadButtonWatcherCleanup();
} catch (_e) {
/* ignore */
}
state.downloadButtonWatcherCleanup = null;
}
if (state.pileHoverDownloadButtonEl) {
state.pileHoverDownloadButtonEl.removeEventListener("mouseenter", handleDownloadButtonHover);
state.pileHoverDownloadButtonEl.removeEventListener("mouseleave", handleDownloadButtonLeave);
state.pileHoverDownloadButtonEl = null;
}
// Remove all event listeners
EventManager.cleanupAll();
// Remove preference observer
if (state.prefObserver) {
try {
Services.prefs.removeObserver(window.zenStuffPilePrefs.PREFS.alwaysShowPile, state.prefObserver);
} catch (error) {
console.warn('[Cleanup] Error removing preference observers:', error);
}
state.prefObserver = null;
}
// Remove DOM elements (bridge is not inside dynamicSizer — remove both)
if (state.hoverBridge && state.hoverBridge.parentNode) {
state.hoverBridge.parentNode.removeChild(state.hoverBridge);
}
state.hoverBridge = null;
if (state.dynamicSizer && state.dynamicSizer.parentNode) {
state.dynamicSizer.parentNode.removeChild(state.dynamicSizer);
}
state.dynamicSizer = null;
// Clear all state
state.clearAll();
state.isInitialized = false;
fileOpsApi?.clearGlobalMenuRef();
debugLog("Cleanup completed successfully");
} catch (error) {
ErrorHandler.handleError(error, 'cleanup');
}
}
fileOpsApi = window.zenStuffContextFileOps.createContextFileOpsApi({
state,
CONFIG,
debugLog,
FileSystem,
ErrorHandler,
validatePodData,
removePodFromPile,
generateGridPosition,
applyGridPosition,
hidePile,
showPile,
getAlwaysShowPile: () => pilePrefsApi.getAlwaysShowPile(),
shouldDisableHover,
isHoveringPileArea,
saveDismissedPodToSession,
schedulePileLayoutRepair,
updatePileVisibility,
updateDownloadsButtonVisibility: () => pilePrefsApi.updateDownloadsButtonVisibility()
});
function isContextMenuVisible() {
return fileOpsApi ? fileOpsApi.isContextMenuVisible() : false;
}
function hideContextMenu() {
try {
fileOpsApi?.hideContextMenu();
} catch (_e) {}
}
if (document.readyState === "complete") {
init();
} else {
window.addEventListener("load", init, { once: true });
}
window.addEventListener("beforeunload", cleanup, { once: true });
debugLog("Dismissed downloads pile script loaded");
// Store previous grid positions for each pod
if (!state._prevGridPositions) state._prevGridPositions = new Map();
})();