-
Notifications
You must be signed in to change notification settings - Fork 17
/
$Window.js
1959 lines (1830 loc) · 72.2 KB
/
$Window.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
((exports) => {
const deprecatedEvents = {
"window-drag-start": "onBeforeDrag",
"title-change": "onTitleChange",
"icon-change": "onIconChange",
"close": "onBeforeClose",
"closed": "onClosed",
"window-focus": "onFocus", // never recommended
"window-blur": "onBlur", // never recommended
};
// @ts-ignore (not part of the public jQuery API)
const originalAdd = jQuery.event.add;
// @ts-ignore (not part of the public jQuery API, but I'm taking care that it shouldn't break if the signature changes)
jQuery.event.add = function (elem, types, ...otherArgs) {
if (typeof types === "string") {
for (const type of types.split(" ")) {
// Don't warn about native "close" event of <dialog> elements
if (type in deprecatedEvents && $(elem).is(".window")) {
const replacementMethod = deprecatedEvents[/** @type {keyof typeof deprecatedEvents} */(type)];
if (replacementMethod) {
console.trace(`DEPRECATED: use $window.${replacementMethod}(listener) instead of adding a jQuery event listener for "${types}"`);
}
}
}
}
originalAdd(elem, types, ...otherArgs);
};
// TODO: E\("([a-z]+)"\) -> "<$1>" or get rid of jQuery as a dependency
const E = document.createElement.bind(document);
/**
* @param {Element | object | null | undefined} element
* @returns {string}
*/
function element_to_string(element) {
// returns a CSS-selector-like string for the given element
// if (element instanceof Element) { // doesn't work with different window.Element from iframes
if (element && typeof element === "object" && "tagName" in element) {
return element.tagName.toLowerCase() +
(element.id ? "#" + element.id : "") +
(element.className ? "." + element.className.split(" ").join(".") : "") +
// @ts-ignore (duck typing is better here for cross-iframe code)
(element.src ? `[src="${element.src}"]` : "") + // Note: not escaped; may not actually work as a selector (but this is for debugging)
// @ts-ignore (duck typing is better here for cross-iframe code)
(element.srcdoc ? "[srcdoc]" : "") + // (srcdoc can be long)
// @ts-ignore (duck typing is better here for cross-iframe code)
(element.href ? `[href="${element.href}"]` : "");
} else if (element) {
return element.constructor.name;
} else {
return `${element}`;
}
}
/**
* @param {Node | Window} node
* @returns {node is HTMLIFrameElement}
*/
function is_iframe(node) {
// return node.tagName == "IFRAME"; // not ideal since it would check for a global named "tagName" in the case of the Window object
// return node instanceof HTMLIFrameElement; // not safe across iframe contexts, since each iframe has its own window.HTMLIFrameElement
return node instanceof node.ownerDocument.defaultView.HTMLIFrameElement;
}
/**
* @param {Node} node
* @returns {node is HTMLInputElement}
*/
function is_input(node) {
return node.nodeName.toLowerCase() === "input";
}
/**
* @param {Element} container_el
* @returns {JQuery<HTMLElement>}
*/
function find_tabstops(container_el) {
const $el = $(container_el);
// This function finds focusable controls, but not necessarily all of them;
// for radio elements, it only gives one: either the checked one, or the first one if none are checked.
// Note: for audio[controls], Chrome at least has two tabstops (the audio element and three dots menu button).
// It might be possible to detect this in the shadow DOM, I don't know, I haven't worked with the shadow DOM.
// But it might be more reliable to make a dummy tabstop element to detect when you tab out of the first/last element.
// Also for iframes!
// Assuming that doesn't mess with screen readers.
// Right now you can't tab to the three dots menu if it's the last element.
// @TODO: see what ally.js does. Does it handle audio[controls]? https://allyjs.io/api/query/tabsequence.html
let $controls = $el.find(`
input:enabled,
textarea:enabled,
select:enabled,
button:enabled,
a[href],
[tabIndex='0'],
details summary,
iframe,
object,
embed,
video[controls],
audio[controls],
[contenteditable]:not([contenteditable='false'])
`).filter(":visible");
// const $controls = $el.find(":tabbable"); // https://api.jqueryui.com/tabbable-selector/
// Radio buttons should be treated as a group with one tabstop.
// If there's no selected ("checked") radio, it should still visit the group,
// but if there is a selected radio in the group, it should skip all unselected radios in the group.
/** @type {Record<string, HTMLElement>} */
const radios = {}; // best radio found so far, per group
/** @type {HTMLElement[]} */
const to_skip = [];
for (const el of $controls.toArray()) {
if (is_input(el) && el.type === "radio") {
if (radios[el.name]) {
if (el.checked) {
to_skip.push(radios[el.name]);
radios[el.name] = el;
} else {
to_skip.push(el);
}
} else {
radios[el.name] = el;
}
}
}
const $tabstops = $controls.not(to_skip);
// debug viz:
// $tabstops.css({boxShadow: "0 0 2px 2px green"});
// $(to_skip).css({boxShadow: "0 0 2px 2px gray"})
return $tabstops;
}
var $G = $(window);
$Window.Z_INDEX = 5;
/** @type {(OSGUIWindow | null)[]} */
var minimize_slots = []; // for if there's no taskbar
function formatPropertyAccess(/** @type {string | symbol} */ prop) {
if (typeof prop === "symbol") {
return `[${String(prop)}]`;
} else if (/^\d+$/.test(prop)) {
return `[${prop}]`;
} else if (/^[a-zA-Z_$][0-9a-zA-Z_$]*$/.test(prop)) {
return `.${prop}`;
} else {
return `[${JSON.stringify(prop)}]`;
}
}
// @TODO: make this a class,
// instead of a weird pseudo-class
/**
* @param {OSGUIWindowOptions} [options]
* @returns {OSGUI$Window}
*/
function $Window(options = {}) {
// @TODO: handle all option defaults here
// and validate options.
// WOW, this is ugly. It's kind of impressive, almost.
/** @type {OSGUIWindow} */
var win = {};
// TODO: A $Window.fromElement (or similar) static method using a Map would be better for type checking.
// @ts-ignore
win.element = E("div");
/** @type {JQuery<HTMLElement>} */
var $window_element = $(win.element);
/** @type {OSGUI$Window} */
// @ts-ignore
var $win = new Proxy(win, {
get: function (_target, name) {
if (name in win) {
// @ts-ignore
return win[name];
} else if (name in $window_element) {
// @ts-ignore
if (/^0$/.test(name)) {
console.trace(`DEPRECATED: use $window.element instead of $window[0].`);
// @ts-ignore
} else if (/^first|last|get$/.test(name)) {
// Assuming 0 will be the argument since a $Window shouldn't have multiple elements.
console.trace(`DEPRECATED: use $window.element instead of $window${formatPropertyAccess(name)}(0).`);
} else if (name === "find") {
console.trace(`DEPRECATED: use $window.$content.find instead of $window.find, if possible; otherwise use $($window.element).find for a direct equivalent.`);
} else {
const accessor = formatPropertyAccess(name);
console.trace(`DEPRECATED: use $($window.element)${accessor} instead of $window${accessor} directly. Eventually jQuery will be removed from the library.`);
}
// @ts-ignore
if (typeof $window_element[name] === "function") {
// @ts-ignore
return $window_element[name].bind($window_element);
}
// @ts-ignore
return $window_element[name];
} else {
// Allow duck typing, as, for instance, jQuery checks for `object.window`
// and arbitrarily added properties.
// console.trace("Unknown property", name);
}
},
set: function (_target, name, value) {
if (name in win) {
// @ts-ignore
win[name] = value;
} else if (name in $window_element) {
const accessor = formatPropertyAccess(name);
console.trace(`DEPRECATED: use $($window.element)${accessor} instead of $window${accessor} directly.`);
// @ts-ignore
$window_element[name] = value;
} else {
// Allow adding arbitrary properties (though it's not recommended).
// console.trace("Unknown property", name);
}
return true;
}
});
win.element.$window = $win;
win.element.classList.add("window", "os-window");
win.element.id = `os-window-${Math.random().toString(36).substr(2, 9)}`;
document.body.appendChild(win.element);
win.elements = {
titlebar: E("div"),
_title_area: E("div"),
title: E("span"),
minimizeButton: E("button"),
maximizeButton: E("button"),
closeButton: E("button"),
content: E("div"),
};
win.$titlebar = $(win.elements.titlebar).addClass("window-titlebar").appendTo($window_element);
win.$title_area = $(win.elements._title_area).addClass("window-title-area").appendTo(win.$titlebar);
win.$title = $(win.elements.title).addClass("window-title").appendTo(win.$title_area);
if (options.toolWindow) {
options.minimizeButton = false;
options.maximizeButton = false;
}
if (options.minimizeButton !== false) {
win.$minimize = $(win.elements.minimizeButton).addClass("window-minimize-button window-action-minimize window-button").appendTo(win.$titlebar);
win.$minimize.attr("aria-label", "Minimize window"); // @TODO: for taskbarless minimized windows, "restore"
win.$minimize.append("<span class='window-button-icon'></span>");
}
if (options.maximizeButton !== false) {
win.$maximize = $(win.elements.maximizeButton).addClass("window-maximize-button window-action-maximize window-button").appendTo(win.$titlebar);
win.$maximize.attr("aria-label", "Maximize or restore window"); // @TODO: specific text for the state
if (!options.resizable) {
win.$maximize.prop("disabled", true);
}
win.$maximize.append("<span class='window-button-icon'></span>");
}
if (options.closeButton !== false) {
win.$x = $(win.elements.closeButton).addClass("window-close-button window-action-close window-button").appendTo(win.$titlebar);
win.$x.attr("aria-label", "Close window");
win.$x.append("<span class='window-button-icon'></span>");
}
win.$content = $(win.elements.content).addClass("window-content").appendTo($window_element);
win.$content.attr("tabIndex", "-1");
win.$content.css("outline", "none");
if (options.toolWindow) {
$window_element.addClass("tool-window");
}
if (options.parentWindow) {
options.parentWindow.addChildWindow($win);
// semantic parent logic is currently only suited for tool windows
// for dialog windows, it would make the dialog window not show as focused
// (alternatively, I could simply, when following the semantic parent chain, look for windows that are not tool windows)
if (options.toolWindow) {
win.element.dataset.semanticParent = options.parentWindow.element.id;
}
}
var $component = options.$component;
if (typeof options.icon === "object" && "tagName" in options.icon) {
options.icons = { any: options.icon };
} else if (options.icon) {
// old terrible API using globals that you have to define
console.warn("DEPRECATED: use options.icons instead of options.icon, e.g. new $Window({icons: {16: 'app-16x16.png', any: 'app-icon.svg'}})");
// @ts-ignore
if (typeof $Icon !== "undefined" && typeof TITLEBAR_ICON_SIZE !== "undefined") {
// @ts-ignore
win.icon_name = options.icon;
// @ts-ignore
win.$icon = $Icon(options.icon, TITLEBAR_ICON_SIZE).prependTo(win.$titlebar);
} else {
throw new Error("Use {icon: img_element} or {icons: {16: url_or_img_element}} options");
}
}
win.icons = options.icons || {};
let iconSize = 16;
/**
* @template {any[]} ArgsType
* @param {string} legacy_event_name
* @returns {[(callback: (...args: ArgsType) => void) => (() => void), (...args: ArgsType) => JQuery.Event]} [add_listener, trigger]
*/
const make_listenable = (legacy_event_name) => {
/** @type {((...args: ArgsType) => void)[]} */
let event_handlers = [];
const add_listener = (/** @type {(...args: ArgsType) => void} */ callback) => {
event_handlers.push(callback);
const dispose = () => {
event_handlers = event_handlers.filter(handler => handler !== callback);
};
return dispose;
};
/**
* @param {ArgsType} args
* @returns {JQuery.Event}
*/
const trigger = (...args) => {
for (const handler of event_handlers) {
handler(...args);
}
const legacy_event = jQuery.Event(legacy_event_name);
$window_element.trigger(legacy_event);
return legacy_event;
};
return [add_listener, trigger];
};
/** @type {[typeof win.onFocus, () => JQuery.Event]} */
const [onFocus, dispatch_focus] = make_listenable("window-focus");
/** @type {[typeof win.onBlur, () => JQuery.Event]} */
const [onBlur, dispatch_blur] = make_listenable("window-blur");
/** @type {[typeof win.onClosed, () => JQuery.Event]} */
const [onClosed, dispatch_closed] = make_listenable("closed");
/** @type {[typeof win.onBeforeClose, (event: {preventDefault: () => void}) => JQuery.Event]} */
const [onBeforeClose, dispatch_before_close] = make_listenable("close");
/** @type {[typeof win.onBeforeDrag, (event: {preventDefault: () => void}) => JQuery.Event]} */
const [onBeforeDrag, dispatch_before_drag] = make_listenable("window-drag-start");
/** @type {[typeof win.onTitleChange, () => JQuery.Event]} */
const [onTitleChange, dispatch_title_changed] = make_listenable("title-change");
/** @type {[typeof win.onIconChange, () => JQuery.Event]} */
const [onIconChange, dispatch_icon_changed] = make_listenable("icon-change");
Object.assign(win, { onFocus, onBlur, onClosed, onBeforeClose, onBeforeDrag, onTitleChange, onIconChange });
win.setTitlebarIconSize = function (target_icon_size) {
if (win.icons) {
win.$icon?.remove();
const iconNode = win.getIconAtSize(target_icon_size);
win.$icon = iconNode ? $(iconNode) : $();
win.$icon.prependTo(win.$titlebar);
}
iconSize = target_icon_size;
dispatch_icon_changed();
};
win.getTitlebarIconSize = function () {
return iconSize;
};
// @TODO: this could be a static method, like OSGUI.getIconAtSize(icons, targetSize)
win.getIconAtSize = function (target_icon_size) {
let icon_size;
if (win.icons[target_icon_size]) {
icon_size = target_icon_size;
} else if (win.icons["any"]) {
icon_size = "any";
} else {
// isFinite(parseFloat("123xyz")) // true
// isFinite("123xyz") // false
// isFinite(parseFloat(null)) // false
// isFinite(null) // true
// @ts-ignore
const sizes = Object.keys(win.icons).filter(size => isFinite(size) && isFinite(parseFloat(size)));
sizes.sort((a, b) => Math.abs(parseFloat(a) - target_icon_size) - Math.abs(parseFloat(b) - target_icon_size));
icon_size = sizes[0];
}
if (icon_size) {
const icon = win.icons[icon_size];
let icon_element;
if (typeof icon === "object" && "cloneNode" in icon) {
icon_element = icon.cloneNode(true);
} else {
icon_element = E("img");
const $icon = $(icon_element);
if (typeof icon === "string") {
$icon.attr("src", icon);
} else if ("srcset" in icon) {
$icon.attr("srcset", icon.srcset);
} else {
$icon.attr("src", icon.src);
}
$icon.attr({
width: icon_size,
height: icon_size,
draggable: false,
});
$icon.css({
width: target_icon_size,
height: target_icon_size,
});
}
return icon_element;
}
return null;
};
// @TODO: automatically update icon size based on theme (with a CSS variable)
win.setTitlebarIconSize(iconSize);
win.getIconName = () => {
console.warn("DEPRECATED: use $w.icons object instead of $w.icon_name");
return win.icon_name;
};
win.setIconByID = (icon_name) => {
console.warn("DEPRECATED: use $w.setIcons(icons) instead of $w.setIconByID(icon_name)");
var old_$icon = win.$icon;
// @ts-ignore
win.$icon = $Icon(icon_name, TITLEBAR_ICON_SIZE);
old_$icon.replaceWith(win.$icon);
win.icon_name = icon_name;
win.task?.updateIcon();
dispatch_icon_changed();
return win;
};
win.setIcons = (icons) => {
win.icons = icons;
win.setTitlebarIconSize(iconSize);
win.task?.updateIcon();
// dispatch_icon_changed already called by setTitlebarIconSize
};
if ($component) {
$window_element.addClass("component-window");
}
setTimeout(() => {
if (get_direction() == "rtl") {
$window_element.addClass("rtl"); // for reversing the titlebar gradient
}
}, 0);
/**
* @returns {"ltr" | "rtl"} writing/layout direction
*/
function get_direction() {
return window.get_direction ? window.get_direction() : /** @type {"ltr" | "rtl"} */(getComputedStyle(win.element).direction);
}
/**
* @param {{ innerWidth?: number, innerHeight?: number, outerWidth?: number, outerHeight?: number }} options
*/
win.setDimensions = ({ innerWidth, innerHeight, outerWidth, outerHeight }) => {
let width_from_frame, height_from_frame;
// It's good practice to make all measurements first, then update the DOM.
// Once you update the DOM, the browser has to recalculate layout, which can be slow.
if (innerWidth) {
width_from_frame = $window_element.outerWidth() - win.$content.outerWidth();
}
if (innerHeight) {
height_from_frame = $window_element.outerHeight() - win.$content.outerHeight();
const $menu_bar = win.$content.find(".menus"); // only if inside .content; might move to a slot outside .content later
if ($menu_bar.length) {
// maybe this isn't technically part of the frame, per se? but it's part of the non-client area, which is what I technically mean.
height_from_frame += $menu_bar.outerHeight();
}
}
if (outerWidth) {
$window_element.outerWidth(outerWidth);
}
if (outerHeight) {
$window_element.outerHeight(outerHeight);
}
if (innerWidth) {
$window_element.outerWidth(innerWidth + width_from_frame);
}
if (innerHeight) {
$window_element.outerHeight(innerHeight + height_from_frame);
}
};
win.setDimensions(options);
/** @type {OSGUI$Window[]} */
let child_$windows = [];
win.addChildWindow = ($child_window) => {
child_$windows.push($child_window);
};
const showAsFocused = () => {
if ($window_element.hasClass("focused")) {
return;
}
$window_element.addClass("focused");
dispatch_focus();
};
const stopShowingAsFocused = () => {
if (!$window_element.hasClass("focused")) {
return;
}
$window_element.removeClass("focused");
dispatch_blur();
};
win.focus = () => {
// showAsFocused();
win.bringToFront();
refocus();
};
win.blur = () => {
stopShowingAsFocused();
if (document.activeElement && document.activeElement.closest(".window") == win.element) {
document.activeElement.blur();
}
};
if (options.toolWindow) {
if (options.parentWindow) {
options.parentWindow.onFocus(showAsFocused);
options.parentWindow.onBlur(stopShowingAsFocused);
// TODO: also show as focused if focus is within the window
// initial state
// might need a setTimeout, idk...
if (document.activeElement && document.activeElement.closest(".window") == options.parentWindow.element) {
showAsFocused();
}
} else {
// the browser window is the parent window
// show focus whenever the browser window is focused
$(window).on("focus", showAsFocused);
$(window).on("blur", stopShowingAsFocused);
// initial state
if (document.hasFocus()) {
showAsFocused();
}
}
} else {
// global focusout is needed, to continue showing as focused while child windows or menu popups are focused (@TODO: Is this redundant with focusin?)
// global focusin is needed, to show as focused when a child window becomes focused (when perhaps nothing was focused before, so no focusout event)
// global blur is needed, to show as focused when an iframe gets focus, because focusin/out doesn't fire at all in that case
// global focus is needed, to stop showing as focused when an iframe loses focus
// pretty ridiculous!!
// but it still doesn't handle the case where the browser window is not focused, and the user clicks an iframe directly.
// for that, we need to listen inside the iframe, because no events are fired at all outside in that case,
// and :focus/:focus-within doesn't work with iframes so we can't even do a hack with transitionstart.
// @TODO: simplify the strategy; I ended up piling a few strategies on top of each other, and the earlier ones may be redundant.
// In particular, 1. I ended up making it proactively inject into iframes, rather than when focused since there's a case where focus can't be detected otherwise.
// 2. I ended up simulating focusin events for iframes.
// I may want to rely on that, or, I may want to remove that and set up a refocus chain directly instead,
// avoiding refocus() which may interfere with drag operations in an iframe when focusing the iframe (e.g. clicking into Paint to draw or drag a sub-window).
// console.log("adding global focusin/focusout/blur/focus for window", $w.element.id);
const global_focus_update_handler = make_focus_in_out_handler(win.element, true); // must be $w and not $content so semantic parent chain works, with [data-semantic-parent] pointing to the window not the content
window.addEventListener("focusin", global_focus_update_handler);
window.addEventListener("focusout", global_focus_update_handler);
window.addEventListener("blur", global_focus_update_handler);
window.addEventListener("focus", global_focus_update_handler);
/** @param {HTMLIFrameElement} iframe */
function setupIframe(iframe) {
if (!focus_update_handlers_by_container.has(iframe)) {
const iframe_update_focus = make_focus_in_out_handler(iframe, false);
// this also operates as a flag to prevent multiple handlers from being added, or waiting for the iframe to load duplicately
focus_update_handlers_by_container.set(iframe, iframe_update_focus);
// @TODO: try removing setTimeout(s)
setTimeout(() => { // for iframe src to be set? I forget.
// Note: try must be INSIDE setTimeout, not outside, to work.
try {
/** @param {() => void} callback */
const wait_for_iframe_load = (callback) => {
// Note: error may occur accessing iframe.contentDocument; this must be handled by the caller.
// To that end, this function must access it synchronously, to allow the caller to handle the error.
// @ts-ignore
if (iframe.contentDocument.readyState == "complete") {
callback();
} else {
// iframe.contentDocument.addEventListener("readystatechange", () => {
// if (iframe.contentDocument.readyState == "complete") {
// callback();
// }
// });
setTimeout(() => {
wait_for_iframe_load(callback);
}, 100);
}
};
wait_for_iframe_load(() => {
// console.log("adding focusin/focusout/blur/focus for iframe", iframe);
iframe.contentWindow.addEventListener("focusin", iframe_update_focus);
iframe.contentWindow.addEventListener("focusout", iframe_update_focus);
iframe.contentWindow.addEventListener("blur", iframe_update_focus);
iframe.contentWindow.addEventListener("focus", iframe_update_focus);
observeIframes(iframe.contentDocument);
});
} catch (error) {
warn_iframe_access(iframe, error);
}
}, 100);
}
}
/** @param {Document | Element} container_node */
function observeIframes(container_node) {
const observer = new MutationObserver((mutations) => {
for (const mutation of mutations) {
for (const node of mutation.addedNodes) {
if (is_iframe(node)) {
setupIframe(node);
}
}
}
});
observer.observe(container_node, { childList: true, subtree: true });
// needed in recursive calls (for iframes inside iframes)
// (for the window, it shouldn't be able to have iframes yet)
for (const iframe of container_node.querySelectorAll("iframe")) {
setupIframe(iframe);
}
}
observeIframes(win.$content[0]);
/**
* @param {HTMLElement} logical_container_el
* @param {boolean} is_root
* @returns {(event: FocusEvent | null) => void}
*/
function make_focus_in_out_handler(logical_container_el, is_root) {
// In case of iframes, logical_container_el is the iframe, and container_node is the iframe's contentDocument.
// container_node is not a parameter here because it can change over time, may be an empty document before the iframe is loaded.
return function handle_focus_in_out(event) {
const container_node = is_iframe(logical_container_el) ? logical_container_el.contentDocument : logical_container_el;
const document = container_node.ownerDocument ?? container_node;
// is this equivalent?
// const document = is_iframe(logical_container_el) ? logical_container_el.contentDocument : logical_container_el.ownerDocument;
// console.log(`handling ${event.type} for container`, container_el);
let newly_focused = event ? (event.type === "focusout" || event.type === "blur") ? event.relatedTarget : event.target : document.activeElement;
if (event?.type === "blur") {
newly_focused = null; // only handle iframe
}
// console.log(`[${$w.title()}] (is_root=${is_root})`, `newly_focused is (preliminarily)`, element_to_string(newly_focused), `\nlogical_container_el`, logical_container_el, `\ncontainer_node`, container_node, `\ndocument.activeElement`, document.activeElement, `\ndocument.hasFocus()`, document.hasFocus(), `\ndocument`, document);
// Iframes are stingy about focus events, so we need to check if focus is actually within an iframe.
if (
document.activeElement &&
is_iframe(document.activeElement) &&
(event?.type === "focusout" || event?.type === "blur") &&
!newly_focused // doesn't exist for security reasons in this case
) {
newly_focused = document.activeElement;
// console.log(`[${$w.title()}] (is_root=${is_root})`, `newly_focused is (actually)`, element_to_string(newly_focused));
}
const outside_or_at_exactly =
!newly_focused ||
// contains() only works with DOM nodes (elements and documents), not window objects.
// Since container_node is a DOM node, it will never have a Window inside of it (ignoring iframes).
newly_focused.window === newly_focused || // is a Window object (cross-frame test)
!container_node.contains(newly_focused); // Note: node.contains(node) === true
const firmly_outside = outside_or_at_exactly && container_node !== newly_focused;
// console.log(`[${$w.title()}] (is_root=${is_root})`, `outside_or_at_exactly=${outside_or_at_exactly}`, `firmly_outside=${firmly_outside}`);
if (firmly_outside && is_root) {
stopShowingAsFocused();
}
if (
!outside_or_at_exactly &&
newly_focused.tagName !== "HTML" &&
newly_focused.tagName !== "BODY" &&
newly_focused !== container_node &&
!newly_focused.matches(".window-content") &&
!newly_focused.closest(".menus") &&
!newly_focused.closest(".window-titlebar")
) {
last_focus_by_container.set(logical_container_el, newly_focused); // overwritten for iframes below
debug_focus_tracking(document, container_node, newly_focused, is_root);
}
if (
!outside_or_at_exactly &&
is_iframe(newly_focused)
) {
const iframe = newly_focused;
// console.log("iframe", iframe, onfocusin_by_container.has(iframe));
try {
const focus_in_iframe = iframe.contentDocument.activeElement;
if (
focus_in_iframe &&
focus_in_iframe.tagName !== "HTML" &&
focus_in_iframe.tagName !== "BODY" &&
!focus_in_iframe.closest(".menus")
) {
// last_focus_by_container.set(logical_container_el, iframe); // done above
last_focus_by_container.set(iframe, focus_in_iframe);
debug_focus_tracking(iframe.contentDocument, iframe.contentDocument, focus_in_iframe, is_root);
}
} catch (e) {
warn_iframe_access(iframe, e);
}
}
// For child windows and menu popups, follow "semantic parent" chain.
// Menu popups and child windows aren't descendants of the window they belong to,
// but should keep the window shown as focused.
// (In principle this sort of feature could be useful for focus tracking*,
// but right now it's only for child windows and menu popups, which should not be tracked for refocus,
// so I'm doing this after last_focus_by_container.set, for now anyway.)
// ((*: and it may even be surprising if it doesn't work, if one sees the attribute on menus and attempts to use it.
// But who's going to see that? The menus close so it's a pain to see the DOM structure! :P **))
// (((**: without window.debugKeepMenusOpen)))
if (is_root) {
do {
// if (!newly_focused?.closest) {
// console.warn("what is this?", newly_focused);
// break;
// }
const waypoint = newly_focused?.closest?.("[data-semantic-parent]");
if (waypoint) {
const id = waypoint.dataset.semanticParent;
const parent = waypoint.ownerDocument.getElementById(id);
// console.log("following semantic parent, from", newly_focused, "\nto", parent, "\nvia", waypoint);
newly_focused = parent;
if (!parent) {
console.warn("semantic parent not found with id", id);
break;
}
} else {
break;
}
} while (true);
}
// Note: allowing showing window as focused from listeners inside iframe (non-root) too,
// in order to handle clicking an iframe when the browser window was not previously focused (e.g. after reload)
if (
newly_focused &&
newly_focused.window !== newly_focused && // cross-frame test for Window object
container_node.contains(newly_focused)
) {
showAsFocused();
win.bringToFront();
if (!is_root) {
// trigger focusin events for iframes
// @TODO: probably don't need showAsFocused() here since it'll be handled externally (on this simulated focusin),
// and might not need a lot of other logic frankly if I'm simulating focusin events
/** @type {Element | null | undefined} */
let el = logical_container_el;
while (el) {
// console.log("dispatching focusin event for", el);
el.dispatchEvent(new Event("focusin", {
bubbles: true,
target: el,
view: el.ownerDocument.defaultView,
}));
el = el.ownerDocument.defaultView?.frameElement;
}
}
} else if (is_root) {
stopShowingAsFocused();
}
}
}
// initial state is unfocused
}
$window_element.css("touch-action", "none");
/** @type {HTMLElement | null | undefined} */
let minimize_target_el = null; // taskbar button (optional)
win.setMinimizeTarget = function (new_taskbar_button_el) {
minimize_target_el = new_taskbar_button_el;
};
/** @type {{$task: JQuery<HTMLElement>} | undefined} */
let task;
Object.defineProperty(win, "task", {
get() {
return task;
},
set(new_task) {
console.warn("DEPRECATED: use $w.setMinimizeTarget(taskbar_button_el) instead of setting $window.task object");
task = new_task;
},
});
/** @type {{ position: string; left: string; top: string; width: string; height: string; }} */
let before_minimize;
win.minimize = () => {
minimize_target_el = minimize_target_el || task?.$task[0];
if (animating_titlebar) {
when_done_animating_titlebar.push(win.minimize);
return;
}
if ($window_element.is(":visible")) {
if (minimize_target_el && !$window_element.hasClass("minimized-without-taskbar")) {
const before_rect = win.$titlebar[0].getBoundingClientRect();
const after_rect = minimize_target_el.getBoundingClientRect();
win.animateTitlebar(before_rect, after_rect, () => {
$window_element.hide();
win.blur();
});
$window_element.addClass("minimized");
} else {
// no taskbar
// @TODO: make this metrically similar to what Windows 98 does
// @TODO: DRY! This is copied heavily from maximize()
// @TODO: after minimize (without taskbar) and maximize, restore should restore original position before minimize
// OR should it not maximize but restore the unmaximized state? I think I tested it but I forget.
const to_width = 150;
const spacing = 10;
if ($window_element.hasClass("minimized-without-taskbar")) {
// unminimizing
minimize_slots[win._minimize_slot_index] = null;
} else {
// minimizing
let i = 0;
while (minimize_slots[i]) {
i++;
}
win._minimize_slot_index = i;
minimize_slots[i] = win;
}
const to_x = win._minimize_slot_index * (to_width + spacing) + 10;
const titlebar_height = win.$titlebar.outerHeight() ?? 0;
/** @type {{ position: string; left: string; top: string; width: string; height: string; }} */
let before_unminimize;
const instantly_minimize = () => {
before_minimize = {
position: $window_element.css("position"),
left: $window_element.css("left"),
top: $window_element.css("top"),
width: $window_element.css("width"),
height: $window_element.css("height"),
};
$window_element.addClass("minimized-without-taskbar");
if ($window_element.hasClass("maximized")) {
$window_element.removeClass("maximized");
$window_element.addClass("was-maximized");
win.$maximize.removeClass("window-action-restore");
win.$maximize.addClass("window-action-maximize");
}
win.$minimize.removeClass("window-action-minimize");
win.$minimize.addClass("window-action-restore");
if (before_unminimize) {
$window_element.css({
position: before_unminimize.position,
left: before_unminimize.left,
top: before_unminimize.top,
width: before_unminimize.width,
height: before_unminimize.height,
});
} else {
$window_element.css({
position: "fixed",
top: `calc(100% - ${titlebar_height + 5}px)`,
left: `${to_x}px`,
width: `${to_width}px`,
height: `${titlebar_height}px`,
});
}
};
const instantly_unminimize = () => {
before_unminimize = {
position: $window_element.css("position"),
left: $window_element.css("left"),
top: $window_element.css("top"),
width: $window_element.css("width"),
height: $window_element.css("height"),
};
$window_element.removeClass("minimized-without-taskbar");
if ($window_element.hasClass("was-maximized")) {
$window_element.removeClass("was-maximized");
$window_element.addClass("maximized");
win.$maximize.removeClass("window-action-maximize");
win.$maximize.addClass("window-action-restore");
}
win.$minimize.removeClass("window-action-restore");
win.$minimize.addClass("window-action-minimize");
$window_element.css({ width: "", height: "" });
if (before_minimize) {
$window_element.css({
position: before_minimize.position,
left: before_minimize.left,
top: before_minimize.top,
width: before_minimize.width,
height: before_minimize.height,
});
}
};
const before_rect = win.$titlebar[0].getBoundingClientRect();
let after_rect;
$window_element.css("transform", "");
if ($window_element.hasClass("minimized-without-taskbar")) {
instantly_unminimize();
after_rect = win.$titlebar[0].getBoundingClientRect();
instantly_minimize();
} else {
instantly_minimize();
after_rect = win.$titlebar[0].getBoundingClientRect();
instantly_unminimize();
}
win.animateTitlebar(before_rect, after_rect, () => {
if ($window_element.hasClass("minimized-without-taskbar")) {
instantly_unminimize();
} else {
instantly_minimize();
win.blur();
}
});
}
}
};
win.unminimize = () => {
if (animating_titlebar) {
when_done_animating_titlebar.push(win.unminimize);
return;
}
if ($window_element.hasClass("minimized-without-taskbar")) {
win.minimize(); // handles unminimization from this state
return;
}
if ($window_element.is(":hidden")) {
const before_rect = minimize_target_el.getBoundingClientRect();
$window_element.show();
const after_rect = win.$titlebar[0].getBoundingClientRect();
$window_element.hide();
win.animateTitlebar(before_rect, after_rect, () => {
$window_element.show();
win.bringToFront();
win.focus();
});
}
};
/** @type {{ position: string; left: string; top: string; width: string; height: string; }} */
let before_maximize;
win.maximize = () => {
if (!options.resizable) {
return;
}
if (animating_titlebar) {
when_done_animating_titlebar.push(win.maximize);
return;
}
if ($window_element.hasClass("minimized-without-taskbar")) {
win.minimize();
return;
}
const instantly_maximize = () => {
before_maximize = {
position: $window_element.css("position"),
left: $window_element.css("left"),
top: $window_element.css("top"),
width: $window_element.css("width"),
height: $window_element.css("height"),
};
$window_element.addClass("maximized");
const $taskbar = $(".taskbar");
const scrollbar_width = window.innerWidth - $(window).width();
const scrollbar_height = window.innerHeight - $(window).height();
const taskbar_height = $taskbar.length ? $taskbar.outerHeight() + 1 : 0;
$window_element.css({
position: "fixed",
top: 0,
left: 0,
width: `calc(100vw - ${scrollbar_width}px)`,
height: `calc(100vh - ${scrollbar_height}px - ${taskbar_height}px)`,
});
};
const instantly_unmaximize = () => {
$window_element.removeClass("maximized");
$window_element.css({ width: "", height: "" });
if (before_maximize) {
$window_element.css({
position: before_maximize.position,
left: before_maximize.left,
top: before_maximize.top,
width: before_maximize.width,
height: before_maximize.height,
});
}
};