fullscreen-engine 0.0.0-stage → 1.0.0

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,1183 @@
1
+ /*! fullscreen-engine v1.0.0 | MIT */
2
+ var FullscreenEngine = (function (exports) {
3
+ 'use strict';
4
+
5
+ /**
6
+ * Tiny event emitter. No dependencies.
7
+ */
8
+
9
+ class Emitter {
10
+ #listeners = new Map();
11
+
12
+ on(event, cb) {
13
+ if (typeof cb !== 'function') throw new TypeError('listener must be a function');
14
+ if (!this.#listeners.has(event)) this.#listeners.set(event, new Set());
15
+ this.#listeners.get(event).add(cb);
16
+ return () => this.off(event, cb);
17
+ }
18
+
19
+ once(event, cb) {
20
+ if (typeof cb !== 'function') throw new TypeError('listener must be a function');
21
+ const wrapper = (...args) => {
22
+ this.off(event, wrapper);
23
+ cb(...args);
24
+ };
25
+ wrapper._original = cb;
26
+ return this.on(event, wrapper);
27
+ }
28
+
29
+ off(event, cb) {
30
+ const set = this.#listeners.get(event);
31
+ if (!set) return;
32
+ if (set.has(cb)) {
33
+ set.delete(cb);
34
+ } else {
35
+ for (const fn of set) {
36
+ if (fn._original === cb) {
37
+ set.delete(fn);
38
+ break;
39
+ }
40
+ }
41
+ }
42
+ if (set.size === 0) this.#listeners.delete(event);
43
+ }
44
+
45
+ emit(event, ...args) {
46
+ const set = this.#listeners.get(event);
47
+ if (!set) return;
48
+ // copy so listeners can safely remove themselves
49
+ for (const cb of Array.from(set)) {
50
+ try {
51
+ cb(...args);
52
+ } catch (err) {
53
+ // don't break other listeners
54
+ // eslint-disable-next-line no-console
55
+ console.error(`[fullscreen-engine] listener error on "${event}":`, err);
56
+ }
57
+ }
58
+ }
59
+
60
+ clear() {
61
+ this.#listeners.clear();
62
+ }
63
+
64
+ listenerCount(event) {
65
+ return this.#listeners.get(event)?.size ?? 0;
66
+ }
67
+ }
68
+
69
+ /**
70
+ * Small, dependency-free helpers.
71
+ */
72
+
73
+ function isBrowser() {
74
+ return (
75
+ typeof window !== 'undefined' &&
76
+ typeof document !== 'undefined' &&
77
+ typeof document.createElement === 'function'
78
+ );
79
+ }
80
+
81
+ function isNode() {
82
+ return (
83
+ typeof process !== 'undefined' &&
84
+ !!(process.versions && process.versions.node) &&
85
+ !isBrowser()
86
+ );
87
+ }
88
+
89
+ function isElectron() {
90
+ if (!isBrowser()) return false;
91
+ return !!(
92
+ (window.process && window.process.versions && window.process.versions.electron) ||
93
+ typeof window.fsNative !== 'undefined'
94
+ );
95
+ }
96
+
97
+ /**
98
+ * Wrap a function that may or may not return a Promise
99
+ * (older prefixed fullscreen methods don't return one).
100
+ */
101
+ function maybePromise(fn) {
102
+ return new Promise((resolve, reject) => {
103
+ try {
104
+ const result = fn();
105
+ if (result && typeof result.then === 'function') {
106
+ result.then(resolve, reject);
107
+ } else {
108
+ resolve(result);
109
+ }
110
+ } catch (err) {
111
+ reject(err);
112
+ }
113
+ });
114
+ }
115
+
116
+ /**
117
+ * Vendor / prefix detection for fullscreen APIs.
118
+ * Works in browsers; returns null in Node/SSR.
119
+ */
120
+
121
+
122
+ const PREFIXES = ['webkit', 'moz', 'ms'];
123
+
124
+ function deriveVendorPrefix(reqMethod) {
125
+ if (!reqMethod) return '';
126
+ if (reqMethod.startsWith('webkit')) return 'webkit';
127
+ if (reqMethod.startsWith('moz')) return 'moz';
128
+ if (reqMethod.startsWith('ms')) return 'ms';
129
+ return '';
130
+ }
131
+
132
+ function detectEnvironment(root = null) {
133
+ if (!isBrowser()) return null;
134
+
135
+ const el = root || (typeof document !== 'undefined' ? document.documentElement : null);
136
+ if (!el) return null;
137
+
138
+ // request method
139
+ let request = null;
140
+ if (typeof el.requestFullscreen === 'function') request = 'requestFullscreen';
141
+ else {
142
+ for (const p of PREFIXES) {
143
+ const m = `${p}RequestFullscreen`;
144
+ const m2 = `${p}RequestFullScreen`; // Firefox older
145
+ if (typeof el[m] === 'function') { request = m; break; }
146
+ if (typeof el[m2] === 'function') { request = m2; break; }
147
+ }
148
+ }
149
+
150
+ // exit method
151
+ let exit = null;
152
+ if (typeof document.exitFullscreen === 'function') exit = 'exitFullscreen';
153
+ else {
154
+ for (const p of PREFIXES) {
155
+ const m = `${p}ExitFullscreen`;
156
+ const m2 = `${p}CancelFullScreen`;
157
+ if (typeof document[m] === 'function') { exit = m; break; }
158
+ if (typeof document[m2] === 'function') { exit = m2; break; }
159
+ }
160
+ }
161
+
162
+ // element property (who is fullscreen right now)
163
+ let elementProp = null;
164
+ for (const prop of [
165
+ 'fullscreenElement',
166
+ 'webkitFullscreenElement',
167
+ 'mozFullScreenElement',
168
+ 'msFullscreenElement'
169
+ ]) {
170
+ if (prop in document) { elementProp = prop; break; }
171
+ }
172
+
173
+ // enabled property (policy / iframe allowfullscreen check)
174
+ let enabledProp = null;
175
+ for (const prop of [
176
+ 'fullscreenEnabled',
177
+ 'webkitFullscreenEnabled',
178
+ 'mozFullScreenEnabled',
179
+ 'msFullscreenEnabled'
180
+ ]) {
181
+ if (prop in document) { enabledProp = prop; break; }
182
+ }
183
+ const policyAllowed = enabledProp ? Boolean(document[enabledProp]) : true;
184
+
185
+ const vendorPrefix = deriveVendorPrefix(request);
186
+
187
+ // change event name
188
+ let changeEvent = null;
189
+ for (const evt of [
190
+ 'fullscreenchange',
191
+ 'webkitfullscreenchange',
192
+ 'mozfullscreenchange',
193
+ 'MSFullscreenChange',
194
+ 'msfullscreenchange'
195
+ ]) {
196
+ if (`on${evt}` in document) { changeEvent = evt; break; }
197
+ }
198
+ if (!changeEvent) {
199
+ if (vendorPrefix === 'webkit') changeEvent = 'webkitfullscreenchange';
200
+ else if (vendorPrefix === 'moz') changeEvent = 'mozfullscreenchange';
201
+ else if (vendorPrefix === 'ms') changeEvent = 'MSFullscreenChange';
202
+ else changeEvent = 'fullscreenchange';
203
+ }
204
+
205
+ // error event name
206
+ let errorEvent = null;
207
+ for (const evt of [
208
+ 'fullscreenerror',
209
+ 'webkitfullscreenerror',
210
+ 'mozfullscreenerror',
211
+ 'MSFullscreenError',
212
+ 'msfullscreenerror'
213
+ ]) {
214
+ if (`on${evt}` in document) { errorEvent = evt; break; }
215
+ }
216
+ if (!errorEvent) {
217
+ if (vendorPrefix === 'webkit') errorEvent = 'webkitfullscreenerror';
218
+ else if (vendorPrefix === 'moz') errorEvent = 'mozfullscreenerror';
219
+ else if (vendorPrefix === 'ms') errorEvent = 'MSFullscreenError';
220
+ else errorEvent = 'fullscreenerror';
221
+ }
222
+
223
+ return {
224
+ request,
225
+ exit,
226
+ elementProp,
227
+ enabledProp,
228
+ changeEvent,
229
+ errorEvent,
230
+ supported: !!(request && exit && elementProp && policyAllowed)
231
+ };
232
+ }
233
+
234
+ /**
235
+ * CSS-based fake fullscreen fallback.
236
+ * Used when native API is unavailable (e.g. iPhone Safari)
237
+ * or when the request is rejected.
238
+ *
239
+ * This does NOT cover browser chrome; it only makes the target
240
+ * element fill the viewport. That's the best a page can do.
241
+ */
242
+
243
+ const styleRefCounts = new Map();
244
+ const lockRefCounts = new Map();
245
+
246
+ function sanitizeClassName(name, fallback) {
247
+ const cleaned = String(name || '').replace(/[^a-zA-Z0-9_-]/g, '_');
248
+ return cleaned || fallback;
249
+ }
250
+
251
+ function sanitizeZIndex(val) {
252
+ if (val === null || val === undefined || val === '' || typeof val === 'boolean') {
253
+ return 2147483647;
254
+ }
255
+ const num = Number(val);
256
+ return Number.isFinite(num) ? Math.trunc(num) : 2147483647;
257
+ }
258
+
259
+ function getStyleId(baseClass, lockClass, zIndex) {
260
+ return `__fullscreen_engine_style_${baseClass}_${lockClass}_${zIndex}__`;
261
+ }
262
+
263
+ function buildCSS(baseClass, lockClass, zIndex) {
264
+ return `
265
+ .${baseClass} {
266
+ position: fixed !important;
267
+ top: 0 !important;
268
+ left: 0 !important;
269
+ right: 0 !important;
270
+ bottom: 0 !important;
271
+ width: 100vw !important;
272
+ height: 100vh !important;
273
+ margin: 0 !important;
274
+ padding: 0 !important;
275
+ border: 0 !important;
276
+ z-index: ${zIndex} !important;
277
+ background: #000 !important;
278
+ overflow: auto !important;
279
+ }
280
+ html.${lockClass}, body.${lockClass} {
281
+ overflow: hidden !important;
282
+ }
283
+ `;
284
+ }
285
+
286
+ function ensureStyle(styleId, baseClass, lockClass, zIndex) {
287
+ if (typeof document === 'undefined') return;
288
+ if (document.getElementById(styleId)) return;
289
+ const style = document.createElement('style');
290
+ style.id = styleId;
291
+ style.textContent = buildCSS(baseClass, lockClass, zIndex);
292
+ (document.head || document.documentElement).appendChild(style);
293
+ }
294
+
295
+ function removeStyle(styleId) {
296
+ if (typeof document === 'undefined') return;
297
+ const style = document.getElementById(styleId);
298
+ if (style) style.remove();
299
+ }
300
+
301
+ function createFallback(opts) {
302
+ const baseClass = sanitizeClassName(opts.fallbackClass, 'fs-engine-active');
303
+ const lockClass = opts.lockBody === false ? '__no_lock__' : 'fs-engine-scroll-lock';
304
+ const zIndex = sanitizeZIndex(opts.zIndex);
305
+ const styleId = getStyleId(baseClass, lockClass, zIndex);
306
+ let active = false;
307
+ let activeTarget = null;
308
+ let styleRegistered = false;
309
+ let lockApplied = false;
310
+
311
+ function enter(target) {
312
+ if (typeof document === 'undefined' || !target || !target.classList) return;
313
+ if (!styleRegistered) {
314
+ styleRefCounts.set(styleId, (styleRefCounts.get(styleId) ?? 0) + 1);
315
+ styleRegistered = true;
316
+ }
317
+ ensureStyle(styleId, baseClass, lockClass, zIndex);
318
+ activeTarget = target;
319
+ target.classList.add(baseClass);
320
+ if (opts.lockBody !== false && !lockApplied) {
321
+ lockRefCounts.set(lockClass, (lockRefCounts.get(lockClass) ?? 0) + 1);
322
+ lockApplied = true;
323
+ document.documentElement.classList.add(lockClass);
324
+ document.body && document.body.classList.add(lockClass);
325
+ }
326
+ active = true;
327
+ }
328
+
329
+ function exit() {
330
+ if (typeof document === 'undefined') return;
331
+ if (activeTarget && activeTarget.classList) {
332
+ activeTarget.classList.remove(baseClass);
333
+ }
334
+ if (opts.lockBody !== false && lockApplied) {
335
+ lockApplied = false;
336
+ const nextLockCount = (lockRefCounts.get(lockClass) ?? 1) - 1;
337
+ if (nextLockCount <= 0) {
338
+ lockRefCounts.delete(lockClass);
339
+ document.documentElement.classList.remove(lockClass);
340
+ document.body && document.body.classList.remove(lockClass);
341
+ } else {
342
+ lockRefCounts.set(lockClass, nextLockCount);
343
+ }
344
+ }
345
+ activeTarget = null;
346
+ active = false;
347
+ }
348
+
349
+ function destroy() {
350
+ exit();
351
+ if (styleRegistered) {
352
+ styleRegistered = false;
353
+ const nextCount = (styleRefCounts.get(styleId) ?? 1) - 1;
354
+ if (nextCount <= 0) {
355
+ styleRefCounts.delete(styleId);
356
+ removeStyle(styleId);
357
+ } else {
358
+ styleRefCounts.set(styleId, nextCount);
359
+ }
360
+ }
361
+ }
362
+
363
+ return {
364
+ enter,
365
+ exit,
366
+ destroy,
367
+ get active() { return active; }
368
+ };
369
+ }
370
+
371
+ /**
372
+ * Auto-trigger controller for mouse hover and page scroll fullscreen activation.
373
+ *
374
+ * Pairs with CSS fallback (or Electron IPC bridge) so hover and scroll events
375
+ * can enter fullscreen without triggering browser user-gesture SecurityErrors.
376
+ */
377
+
378
+
379
+ const VALID_TRIGGERS = new Set(['manual', 'hover', 'scroll']);
380
+
381
+ function normalizeThreshold(val) {
382
+ if (val === null || val === '' || typeof val === 'boolean') return 100;
383
+ const num = Number(val);
384
+ return Number.isFinite(num) ? Math.max(0, num) : 100;
385
+ }
386
+
387
+ function normalizeTriggers(triggerOption) {
388
+ const raw = Array.isArray(triggerOption)
389
+ ? triggerOption
390
+ : triggerOption !== undefined && triggerOption !== null
391
+ ? [triggerOption]
392
+ : ['manual'];
393
+
394
+ for (const item of raw) {
395
+ if (!VALID_TRIGGERS.has(item)) {
396
+ throw new TypeError(`[fullscreen-engine] invalid trigger "${String(item)}": expected 'manual', 'hover', or 'scroll'`);
397
+ }
398
+ }
399
+
400
+ const hasHover = raw.includes('hover');
401
+ const hasScroll = raw.includes('scroll');
402
+
403
+ return {
404
+ list: raw,
405
+ hasHover,
406
+ hasScroll,
407
+ isAuto: hasHover || hasScroll
408
+ };
409
+ }
410
+
411
+ function createAutoTriggers({
412
+ triggers,
413
+ resolveHoverTarget,
414
+ resolveScrollTarget,
415
+ hoverDelay = 0,
416
+ scrollThreshold = 100,
417
+ autoExit = true,
418
+ suppressOnManualExit = true,
419
+ isActive,
420
+ onEnter,
421
+ onExit
422
+ }) {
423
+ if (!triggers.isAuto || !isBrowser()) {
424
+ return {
425
+ notifyManualExit() {},
426
+ destroy() {}
427
+ };
428
+ }
429
+
430
+ const threshold = normalizeThreshold(scrollThreshold);
431
+
432
+ let destroyed = false;
433
+ let activeSource = null; // 'hover' | 'scroll' | null
434
+ let isHovered = false;
435
+ let hoverTimer = null;
436
+ let domReadyBound = false;
437
+ let enterSeq = 0;
438
+ let pendingExitSeq = null;
439
+ const suppressed = {
440
+ hover: false,
441
+ scroll: false
442
+ };
443
+
444
+ function clearHoverTimer() {
445
+ if (hoverTimer !== null) {
446
+ clearTimeout(hoverTimer);
447
+ hoverTimer = null;
448
+ }
449
+ }
450
+
451
+ // ---------- Hover & Scroll target state ----------
452
+ let boundHoverEl = null;
453
+ let boundScrollEl = null;
454
+
455
+ function getScrollY() {
456
+ if (boundScrollEl && typeof window !== 'undefined' && boundScrollEl !== window) {
457
+ return boundScrollEl.scrollTop ?? 0;
458
+ }
459
+ if (typeof window === 'undefined') return 0;
460
+ return (
461
+ window.scrollY ??
462
+ window.pageYOffset ??
463
+ (typeof document !== 'undefined' && document.documentElement
464
+ ? document.documentElement.scrollTop
465
+ : 0) ??
466
+ 0
467
+ );
468
+ }
469
+
470
+ function isScrollPastThreshold() {
471
+ return getScrollY() >= threshold;
472
+ }
473
+
474
+ function triggerEnter(source) {
475
+ if (destroyed) return;
476
+ if (suppressed[source]) return;
477
+ if (isActive()) return;
478
+ activeSource = source;
479
+ const seq = ++enterSeq;
480
+ Promise.resolve(onEnter(source))
481
+ .then(() => {
482
+ if (destroyed || seq !== enterSeq) {
483
+ if (pendingExitSeq === seq && isActive()) {
484
+ pendingExitSeq = null;
485
+ Promise.resolve(onExit(source)).catch(() => {});
486
+ }
487
+ return;
488
+ }
489
+ if (!isActive() && activeSource === source) {
490
+ activeSource = null;
491
+ }
492
+ })
493
+ .catch(() => {
494
+ if (seq === enterSeq && activeSource === source) {
495
+ activeSource = null;
496
+ }
497
+ });
498
+ }
499
+
500
+ function triggerExit(source) {
501
+ if (destroyed || !autoExit) return;
502
+ if (activeSource !== source) return;
503
+
504
+ // Transfer ownership if the other trigger condition is still active
505
+ if (source === 'hover' && triggers.hasScroll && isScrollPastThreshold() && !suppressed.scroll) {
506
+ activeSource = 'scroll';
507
+ return;
508
+ }
509
+ if (source === 'scroll' && triggers.hasHover && isHovered && !suppressed.hover) {
510
+ activeSource = 'hover';
511
+ return;
512
+ }
513
+
514
+ if (!isActive()) {
515
+ pendingExitSeq = enterSeq;
516
+ activeSource = null;
517
+ return;
518
+ }
519
+
520
+ activeSource = null;
521
+ onExit(source);
522
+ }
523
+
524
+ // ---------- Hover handlers ----------
525
+ function onMouseEnter() {
526
+ if (destroyed) return;
527
+ isHovered = true;
528
+ if (suppressed.hover) return;
529
+
530
+ clearHoverTimer();
531
+ const delay = Math.max(0, Number(hoverDelay) || 0);
532
+ if (delay > 0) {
533
+ hoverTimer = setTimeout(() => {
534
+ hoverTimer = null;
535
+ if (isHovered && !destroyed) {
536
+ triggerEnter('hover');
537
+ }
538
+ }, delay);
539
+ } else {
540
+ triggerEnter('hover');
541
+ }
542
+ }
543
+
544
+ function onMouseLeave() {
545
+ if (destroyed) return;
546
+ isHovered = false;
547
+ clearHoverTimer();
548
+ suppressed.hover = false;
549
+ triggerExit('hover');
550
+ }
551
+
552
+ function bindHoverTarget() {
553
+ if (destroyed || !triggers.hasHover || boundHoverEl) return;
554
+ const el = typeof resolveHoverTarget === 'function' ? resolveHoverTarget() : null;
555
+ if (el && typeof el.addEventListener === 'function') {
556
+ boundHoverEl = el;
557
+ boundHoverEl.addEventListener('mouseenter', onMouseEnter);
558
+ boundHoverEl.addEventListener('mouseleave', onMouseLeave);
559
+ }
560
+ }
561
+
562
+ // ---------- Scroll handler ----------
563
+ function onScroll() {
564
+ if (destroyed) return;
565
+ if (isScrollPastThreshold()) {
566
+ triggerEnter('scroll');
567
+ } else {
568
+ suppressed.scroll = false;
569
+ triggerExit('scroll');
570
+ }
571
+ }
572
+
573
+ function bindScrollTarget() {
574
+ if (destroyed || !triggers.hasScroll || boundScrollEl) return;
575
+ const target =
576
+ typeof resolveScrollTarget === 'function'
577
+ ? resolveScrollTarget()
578
+ : typeof window !== 'undefined'
579
+ ? window
580
+ : null;
581
+ if (target && typeof target.addEventListener === 'function') {
582
+ boundScrollEl = target;
583
+ boundScrollEl.addEventListener('scroll', onScroll, { passive: true });
584
+ }
585
+ }
586
+
587
+ bindHoverTarget();
588
+ bindScrollTarget();
589
+
590
+ function onDomReady() {
591
+ domReadyBound = false;
592
+ bindHoverTarget();
593
+ bindScrollTarget();
594
+ }
595
+
596
+ const needsDeferredBind =
597
+ (triggers.hasHover && !boundHoverEl) || (triggers.hasScroll && !boundScrollEl);
598
+
599
+ if (
600
+ needsDeferredBind &&
601
+ typeof document !== 'undefined' &&
602
+ document.readyState === 'loading' &&
603
+ typeof document.addEventListener === 'function'
604
+ ) {
605
+ domReadyBound = true;
606
+ document.addEventListener('DOMContentLoaded', onDomReady, { once: true });
607
+ }
608
+
609
+ function notifyManualExit() {
610
+ if (destroyed) return;
611
+ clearHoverTimer();
612
+ enterSeq += 1;
613
+ pendingExitSeq = null;
614
+ if (suppressOnManualExit) {
615
+ if (isHovered) suppressed.hover = true;
616
+ if (isScrollPastThreshold()) suppressed.scroll = true;
617
+ }
618
+ activeSource = null;
619
+ }
620
+
621
+ function destroy() {
622
+ if (destroyed) return;
623
+ destroyed = true;
624
+ clearHoverTimer();
625
+ enterSeq += 1;
626
+ pendingExitSeq = null;
627
+ if (
628
+ domReadyBound &&
629
+ typeof document !== 'undefined' &&
630
+ typeof document.removeEventListener === 'function'
631
+ ) {
632
+ document.removeEventListener('DOMContentLoaded', onDomReady);
633
+ domReadyBound = false;
634
+ }
635
+ if (boundHoverEl && typeof boundHoverEl.removeEventListener === 'function') {
636
+ boundHoverEl.removeEventListener('mouseenter', onMouseEnter);
637
+ boundHoverEl.removeEventListener('mouseleave', onMouseLeave);
638
+ }
639
+ boundHoverEl = null;
640
+ if (boundScrollEl && typeof boundScrollEl.removeEventListener === 'function') {
641
+ boundScrollEl.removeEventListener('scroll', onScroll);
642
+ }
643
+ boundScrollEl = null;
644
+ activeSource = null;
645
+ }
646
+
647
+ return {
648
+ notifyManualExit,
649
+ destroy
650
+ };
651
+ }
652
+
653
+ /**
654
+ * Core engine: createFullscreen()
655
+ *
656
+ * Environment-aware. Works in:
657
+ * - Browser (native, with prefixes)
658
+ * - Electron renderer (via window.fsNative bridge)
659
+ * - SSR/Node (import safe; request() rejects gracefully)
660
+ *
661
+ * Fallback: CSS-based fake fullscreen when native is unavailable.
662
+ * Auto-triggers: Opt-in mouse hover and page scroll fullscreen activation.
663
+ */
664
+
665
+
666
+ function isValidElement(el) {
667
+ return (
668
+ typeof el === 'object' &&
669
+ el !== null &&
670
+ el.nodeType === 1 &&
671
+ typeof el.classList === 'object'
672
+ );
673
+ }
674
+
675
+ function normalizeAutoRelock(val) {
676
+ if (val === undefined || val === null || val === false) {
677
+ return { enabled: false, delay: 50, maxRetries: 3 };
678
+ }
679
+ if (val === true) {
680
+ return { enabled: true, delay: 50, maxRetries: 3 };
681
+ }
682
+ if (typeof val === 'object') {
683
+ const delayNum = Number(val.delay);
684
+ const retriesNum = Number(val.maxRetries);
685
+ return {
686
+ enabled: val.enabled ?? true,
687
+ delay: Number.isFinite(delayNum) ? Math.max(0, delayNum) : 50,
688
+ maxRetries: Number.isFinite(retriesNum) ? Math.max(1, Math.trunc(retriesNum)) : 3
689
+ };
690
+ }
691
+ throw new TypeError('[fullscreen-engine] invalid autoRelock option: expected boolean or object');
692
+ }
693
+
694
+ function createFullscreen(userOptions = {}) {
695
+ const triggers = normalizeTriggers(userOptions.trigger);
696
+ const relockConfig = normalizeAutoRelock(userOptions.autoRelock);
697
+
698
+ const fallbackOption = userOptions.fallback ?? 'none';
699
+ if (fallbackOption !== 'css' && fallbackOption !== 'none') {
700
+ throw new TypeError(`[fullscreen-engine] invalid fallback "${String(fallbackOption)}": expected 'css' or 'none'`);
701
+ }
702
+
703
+ if (userOptions.target !== undefined && userOptions.target !== null && !isValidElement(userOptions.target)) {
704
+ throw new TypeError('[fullscreen-engine] target must be a valid DOM Element');
705
+ }
706
+
707
+ const options = {
708
+ target: userOptions.target ?? null,
709
+ fallback: fallbackOption, // 'css' | 'none'
710
+ fallbackClass: userOptions.fallbackClass ?? 'fs-engine-active',
711
+ lockBody: userOptions.lockBody ?? true,
712
+ zIndex: userOptions.zIndex ?? 2147483647,
713
+ onError: userOptions.onError ?? null,
714
+ autoDetectElectron: userOptions.autoDetectElectron ?? true,
715
+ trigger: triggers.list,
716
+ hoverTarget: userOptions.hoverTarget ?? null,
717
+ hoverDelay: userOptions.hoverDelay ?? 0,
718
+ scrollTarget: userOptions.scrollTarget ?? null,
719
+ scrollThreshold: userOptions.scrollThreshold ?? 100,
720
+ autoExit: userOptions.autoExit ?? true,
721
+ suppressOnManualExit: userOptions.suppressOnManualExit ?? true,
722
+ autoRelock: relockConfig,
723
+ preventExit: userOptions.preventExit ?? false
724
+ };
725
+
726
+ const emitter = new Emitter();
727
+ const env = detectEnvironment();
728
+
729
+ function emitError(err) {
730
+ emitter.emit('error', err);
731
+ if (typeof options.onError === 'function') options.onError(err);
732
+ }
733
+
734
+ // Resolve target lazily (document may not exist in SSR)
735
+ function resolveTarget() {
736
+ if (options.target) return options.target;
737
+ if (typeof document !== 'undefined') return document.documentElement;
738
+ return null;
739
+ }
740
+
741
+ function resolveHoverTarget() {
742
+ if (options.hoverTarget) return options.hoverTarget;
743
+ return resolveTarget();
744
+ }
745
+
746
+ function resolveScrollTarget() {
747
+ if (options.scrollTarget) return options.scrollTarget;
748
+ if (typeof window !== 'undefined') return window;
749
+ return null;
750
+ }
751
+
752
+ // Electron bridge
753
+ const electronBridge =
754
+ options.autoDetectElectron && isElectron() && typeof window !== 'undefined'
755
+ ? window.fsNative || null
756
+ : null;
757
+
758
+ const hasNative = !!(env && env.supported);
759
+ const hasElectron = !!(electronBridge && typeof electronBridge.set === 'function');
760
+ const hasFallback =
761
+ userOptions.fallback !== undefined
762
+ ? options.fallback === 'css'
763
+ : triggers.isAuto || relockConfig.enabled;
764
+ const effectiveLockBody = triggers.hasScroll && options.autoExit ? false : options.lockBody;
765
+
766
+ const fallback = hasFallback
767
+ ? createFallback({
768
+ fallbackClass: options.fallbackClass,
769
+ lockBody: effectiveLockBody,
770
+ zIndex: options.zIndex
771
+ })
772
+ : null;
773
+
774
+ let destroyed = false;
775
+ let electronActive = false;
776
+ let lastActive = false;
777
+ let lastSource = 'none';
778
+ let electronUnsub = null;
779
+ let escapeBound = false;
780
+ let exitLocked = !!options.preventExit;
781
+ let manualUnlocking = false;
782
+ let relockTimer = null;
783
+ let relockRetries = 0;
784
+
785
+ function clearRelockTimer() {
786
+ if (relockTimer !== null) {
787
+ clearTimeout(relockTimer);
788
+ relockTimer = null;
789
+ }
790
+ }
791
+
792
+ function scheduleRelock() {
793
+ if (destroyed || !relockConfig.enabled || manualUnlocking) return;
794
+ if (relockRetries >= relockConfig.maxRetries) {
795
+ emitError(new Error('[fullscreen-engine] autoRelock failed after maxRetries'));
796
+ return;
797
+ }
798
+ clearRelockTimer();
799
+ relockTimer = setTimeout(() => {
800
+ relockTimer = null;
801
+ if (destroyed || !relockConfig.enabled || manualUnlocking || getState().active) return;
802
+ relockRetries += 1;
803
+ requestAuto()
804
+ .then(() => {
805
+ if (!destroyed && !getState().active && relockConfig.enabled && !manualUnlocking) {
806
+ scheduleRelock();
807
+ }
808
+ })
809
+ .catch((err) => {
810
+ emitError(err);
811
+ if (!destroyed && relockConfig.enabled && !manualUnlocking) {
812
+ scheduleRelock();
813
+ }
814
+ });
815
+ }, relockConfig.delay);
816
+ }
817
+
818
+ function onFallbackEscape(e) {
819
+ if (destroyed || !fallback || !fallback.active) return;
820
+ if (e && e.key === 'Escape') {
821
+ if (exitLocked) {
822
+ if (typeof e.preventDefault === 'function') e.preventDefault();
823
+ if (typeof e.stopPropagation === 'function') e.stopPropagation();
824
+ emitError(new Error('[fullscreen-engine] Exit blocked: preventExit is active'));
825
+ return;
826
+ }
827
+ exit().catch((err) => emitError(err));
828
+ }
829
+ }
830
+
831
+ function syncEscapeListener(isFallbackActive) {
832
+ if (typeof document === 'undefined') return;
833
+ if (isFallbackActive && !escapeBound) {
834
+ document.addEventListener('keydown', onFallbackEscape);
835
+ escapeBound = true;
836
+ } else if (!isFallbackActive && escapeBound) {
837
+ document.removeEventListener('keydown', onFallbackEscape);
838
+ escapeBound = false;
839
+ }
840
+ }
841
+
842
+ function getState() {
843
+ let active = false;
844
+ let source = 'none';
845
+ let element = null;
846
+
847
+ if (hasElectron && electronActive) {
848
+ active = true;
849
+ source = 'electron';
850
+ element = resolveTarget();
851
+ } else if (hasNative && typeof document !== 'undefined' && env.elementProp) {
852
+ const fsEl = document[env.elementProp];
853
+ if (fsEl) {
854
+ const target = options.target;
855
+ const matchesTarget =
856
+ !target ||
857
+ fsEl === target ||
858
+ (typeof target.contains === 'function' && target.contains(fsEl));
859
+ if (matchesTarget) {
860
+ active = true;
861
+ source = 'native';
862
+ element = fsEl;
863
+ }
864
+ }
865
+ }
866
+
867
+ if (!active && fallback && fallback.active) {
868
+ active = true;
869
+ source = 'fallback';
870
+ element = resolveTarget();
871
+ }
872
+
873
+ return {
874
+ active,
875
+ source,
876
+ element,
877
+ supported: hasNative || hasElectron || hasFallback
878
+ };
879
+ }
880
+
881
+ function notifyChange(force = false) {
882
+ const state = getState();
883
+ if (state.active && state.source !== 'fallback' && fallback && fallback.active) {
884
+ fallback.exit();
885
+ }
886
+ syncEscapeListener(state.active && state.source === 'fallback');
887
+ if (state.active) {
888
+ relockRetries = 0;
889
+ clearRelockTimer();
890
+ }
891
+ if (!force && state.active === lastActive && state.source === lastSource) return;
892
+ const wasActive = lastActive;
893
+ lastActive = state.active;
894
+ lastSource = state.source;
895
+ if (wasActive && !state.active) {
896
+ autoTriggers.notifyManualExit();
897
+ }
898
+ emitter.emit('change', state);
899
+ if (state.active) emitter.emit('enter', state);
900
+ else {
901
+ emitter.emit('exit', state);
902
+ if (wasActive && relockConfig.enabled && !manualUnlocking) {
903
+ scheduleRelock();
904
+ }
905
+ }
906
+ }
907
+
908
+ // Sync external Electron window state transitions (e.g. F11, Esc, macOS window button)
909
+ if (hasElectron) {
910
+ if (typeof electronBridge.onChange === 'function') {
911
+ electronUnsub = electronBridge.onChange((on) => {
912
+ if (destroyed) return;
913
+ electronActive = !!on;
914
+ notifyChange(false);
915
+ });
916
+ }
917
+ if (typeof electronBridge.get === 'function') {
918
+ Promise.resolve(electronBridge.get())
919
+ .then((on) => {
920
+ if (destroyed) return;
921
+ const next = !!on;
922
+ if (next !== electronActive) {
923
+ electronActive = next;
924
+ notifyChange(false);
925
+ }
926
+ })
927
+ .catch(() => {});
928
+ }
929
+ }
930
+
931
+ // ---------- native listener wiring ----------
932
+ function onNativeChange() {
933
+ if (destroyed) return;
934
+ notifyChange();
935
+ }
936
+ function onNativeError(e) {
937
+ if (destroyed) return;
938
+ const err = (e && (e.error || e)) || new Error('Fullscreen error');
939
+ emitError(err);
940
+ }
941
+
942
+ let nativeChangeBound = false;
943
+ function bindNativeListeners() {
944
+ if (!isBrowser() || !hasNative || nativeChangeBound) return;
945
+ document.addEventListener(env.changeEvent, onNativeChange);
946
+ document.addEventListener(env.errorEvent, onNativeError);
947
+ nativeChangeBound = true;
948
+ }
949
+ function unbindNativeListeners() {
950
+ if (!isBrowser() || !hasNative || !nativeChangeBound) return;
951
+ document.removeEventListener(env.changeEvent, onNativeChange);
952
+ document.removeEventListener(env.errorEvent, onNativeError);
953
+ nativeChangeBound = false;
954
+ }
955
+
956
+ bindNativeListeners();
957
+
958
+ // ---------- auto-trigger activation (gesture-safe) ----------
959
+ async function requestAuto() {
960
+ if (destroyed) return;
961
+ if (getState().active) return;
962
+
963
+ // 1. Electron native (IPC has no browser user-gesture restriction)
964
+ if (hasElectron) {
965
+ try {
966
+ const res = await Promise.resolve(electronBridge.set(true));
967
+ if (res === false) {
968
+ throw new Error('[fullscreen-engine] Electron bridge rejected fullscreen request');
969
+ }
970
+ electronActive = true;
971
+ notifyChange(false);
972
+ return;
973
+ } catch (err) {
974
+ emitError(err);
975
+ // fall through to CSS fallback
976
+ }
977
+ }
978
+
979
+ // 2. CSS fallback (avoids browser SecurityError on hover/scroll events)
980
+ if (hasFallback && fallback) {
981
+ const target = resolveTarget();
982
+ if (!target) return;
983
+ fallback.enter(target);
984
+ notifyChange(false);
985
+ }
986
+ }
987
+
988
+ async function exitInternal(fromAutoTrigger = false) {
989
+ if (destroyed) {
990
+ if (!fromAutoTrigger) throw new Error('[fullscreen-engine] instance destroyed');
991
+ return;
992
+ }
993
+ if (exitLocked && !fromAutoTrigger) {
994
+ const err = new Error('[fullscreen-engine] Exit blocked: preventExit is active');
995
+ emitError(err);
996
+ throw err;
997
+ }
998
+ if (!getState().active) return;
999
+ if (!fromAutoTrigger) {
1000
+ autoTriggers.notifyManualExit();
1001
+ }
1002
+
1003
+ if (hasElectron && electronActive) {
1004
+ try {
1005
+ const res = await Promise.resolve(electronBridge.set(false));
1006
+ if (res === true) {
1007
+ throw new Error('[fullscreen-engine] Electron bridge failed to exit fullscreen');
1008
+ }
1009
+ electronActive = false;
1010
+ } catch (err) {
1011
+ emitError(err);
1012
+ }
1013
+ }
1014
+
1015
+ if (
1016
+ hasNative &&
1017
+ isBrowser() &&
1018
+ env.elementProp &&
1019
+ document[env.elementProp] &&
1020
+ typeof document[env.exit] === 'function'
1021
+ ) {
1022
+ try {
1023
+ await maybePromise(() => document[env.exit]());
1024
+ } catch (err) {
1025
+ emitError(err);
1026
+ }
1027
+ }
1028
+
1029
+ if (fallback && fallback.active) {
1030
+ fallback.exit();
1031
+ }
1032
+
1033
+ notifyChange(false);
1034
+ }
1035
+
1036
+ const autoTriggers = createAutoTriggers({
1037
+ triggers,
1038
+ resolveHoverTarget,
1039
+ resolveScrollTarget,
1040
+ hoverDelay: options.hoverDelay,
1041
+ scrollThreshold: options.scrollThreshold,
1042
+ autoExit: options.autoExit,
1043
+ suppressOnManualExit: options.suppressOnManualExit,
1044
+ isActive: () => getState().active,
1045
+ onEnter: () => requestAuto(),
1046
+ onExit: () => exitInternal(true)
1047
+ });
1048
+
1049
+ // ---------- public API ----------
1050
+ async function request() {
1051
+ if (destroyed) throw new Error('[fullscreen-engine] instance destroyed');
1052
+ manualUnlocking = false;
1053
+ if (getState().active) return;
1054
+
1055
+ // 1. Electron native (do not fall through to Chromium HTML5 native)
1056
+ if (hasElectron) {
1057
+ try {
1058
+ const res = await Promise.resolve(electronBridge.set(true));
1059
+ if (res === false) {
1060
+ throw new Error('[fullscreen-engine] Electron bridge rejected fullscreen request');
1061
+ }
1062
+ electronActive = true;
1063
+ notifyChange(false);
1064
+ return;
1065
+ } catch (err) {
1066
+ emitError(err);
1067
+ // fall through to CSS fallback
1068
+ }
1069
+ } else if (hasNative) {
1070
+ // 2. Browser native
1071
+ const target = resolveTarget();
1072
+ if (!target) throw new Error('[fullscreen-engine] no target element');
1073
+ try {
1074
+ await maybePromise(() => target[env.request]());
1075
+ // Avoid duplicate emissions if native changeEvent already fired
1076
+ notifyChange(false);
1077
+ return;
1078
+ } catch (err) {
1079
+ emitError(err);
1080
+ // fall through to fallback
1081
+ }
1082
+ }
1083
+
1084
+ // 3. CSS fallback
1085
+ if (hasFallback && fallback) {
1086
+ const target = resolveTarget();
1087
+ if (!target) throw new Error('[fullscreen-engine] no target element for fallback');
1088
+ fallback.enter(target);
1089
+ notifyChange(false);
1090
+ return;
1091
+ }
1092
+
1093
+ throw new Error(
1094
+ '[fullscreen-engine] fullscreen unavailable: no native API, no Electron bridge, fallback disabled'
1095
+ );
1096
+ }
1097
+
1098
+ async function exit() {
1099
+ return exitInternal(false);
1100
+ }
1101
+
1102
+ async function toggle() {
1103
+ if (getState().active) return exit();
1104
+ return request();
1105
+ }
1106
+
1107
+ function unlock() {
1108
+ exitLocked = false;
1109
+ manualUnlocking = true;
1110
+ clearRelockTimer();
1111
+ relockRetries = 0;
1112
+ }
1113
+
1114
+ function isActive() {
1115
+ return getState().active;
1116
+ }
1117
+
1118
+ function isSupported() {
1119
+ return hasNative || hasElectron || hasFallback;
1120
+ }
1121
+
1122
+ function isFallback() {
1123
+ return getState().source === 'fallback';
1124
+ }
1125
+
1126
+ function on(event, cb) {
1127
+ return emitter.on(event, cb);
1128
+ }
1129
+ function once(event, cb) {
1130
+ return emitter.once(event, cb);
1131
+ }
1132
+ function off(event, cb) {
1133
+ return emitter.off(event, cb);
1134
+ }
1135
+
1136
+ function destroy() {
1137
+ if (destroyed) return;
1138
+ destroyed = true;
1139
+ clearRelockTimer();
1140
+ syncEscapeListener(false);
1141
+ unbindNativeListeners();
1142
+ if (typeof electronUnsub === 'function') {
1143
+ electronUnsub();
1144
+ electronUnsub = null;
1145
+ }
1146
+ autoTriggers.destroy();
1147
+ if (fallback) fallback.destroy();
1148
+ emitter.clear();
1149
+ }
1150
+
1151
+ // Expose current state snapshots
1152
+ const state = () => getState();
1153
+
1154
+ return {
1155
+ request,
1156
+ exit,
1157
+ toggle,
1158
+ unlock,
1159
+ isActive,
1160
+ isSupported,
1161
+ isFallback,
1162
+ getState: state,
1163
+ on,
1164
+ once,
1165
+ off,
1166
+ destroy,
1167
+ // convenience for debugging
1168
+ _env: env,
1169
+ _options: options
1170
+ };
1171
+ }
1172
+
1173
+ exports.Emitter = Emitter;
1174
+ exports.createFullscreen = createFullscreen;
1175
+ exports.detectEnvironment = detectEnvironment;
1176
+ exports.isBrowser = isBrowser;
1177
+ exports.isElectron = isElectron;
1178
+ exports.isNode = isNode;
1179
+
1180
+ return exports;
1181
+
1182
+ })({});
1183
+ //# sourceMappingURL=fullscreen.iife.js.map