-
Notifications
You must be signed in to change notification settings - Fork 29.2k
/
dom.ts
2536 lines (2130 loc) · 78.8 KB
/
dom.ts
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
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as browser from './browser.js';
import { BrowserFeatures } from './canIUse.js';
import { IKeyboardEvent, StandardKeyboardEvent } from './keyboardEvent.js';
import { IMouseEvent, StandardMouseEvent } from './mouseEvent.js';
import { AbstractIdleValue, IntervalTimer, TimeoutTimer, _runWhenIdle, IdleDeadline } from '../common/async.js';
import { onUnexpectedError } from '../common/errors.js';
import * as event from '../common/event.js';
import dompurify from './dompurify/dompurify.js';
import { KeyCode } from '../common/keyCodes.js';
import { Disposable, DisposableStore, IDisposable, toDisposable } from '../common/lifecycle.js';
import { RemoteAuthorities, Schemas } from '../common/network.js';
import * as platform from '../common/platform.js';
import { URI } from '../common/uri.js';
import { hash } from '../common/hash.js';
import { CodeWindow, ensureCodeWindow, mainWindow } from './window.js';
import { isPointWithinTriangle } from '../common/numbers.js';
export interface IRegisteredCodeWindow {
readonly window: CodeWindow;
readonly disposables: DisposableStore;
}
//# region Multi-Window Support Utilities
export const {
registerWindow,
getWindow,
getDocument,
getWindows,
getWindowsCount,
getWindowId,
getWindowById,
hasWindow,
onDidRegisterWindow,
onWillUnregisterWindow,
onDidUnregisterWindow
} = (function () {
const windows = new Map<number, IRegisteredCodeWindow>();
ensureCodeWindow(mainWindow, 1);
const mainWindowRegistration = { window: mainWindow, disposables: new DisposableStore() };
windows.set(mainWindow.vscodeWindowId, mainWindowRegistration);
const onDidRegisterWindow = new event.Emitter<IRegisteredCodeWindow>();
const onDidUnregisterWindow = new event.Emitter<CodeWindow>();
const onWillUnregisterWindow = new event.Emitter<CodeWindow>();
function getWindowById(windowId: number): IRegisteredCodeWindow | undefined;
function getWindowById(windowId: number | undefined, fallbackToMain: true): IRegisteredCodeWindow;
function getWindowById(windowId: number | undefined, fallbackToMain?: boolean): IRegisteredCodeWindow | undefined {
const window = typeof windowId === 'number' ? windows.get(windowId) : undefined;
return window ?? (fallbackToMain ? mainWindowRegistration : undefined);
}
return {
onDidRegisterWindow: onDidRegisterWindow.event,
onWillUnregisterWindow: onWillUnregisterWindow.event,
onDidUnregisterWindow: onDidUnregisterWindow.event,
registerWindow(window: CodeWindow): IDisposable {
if (windows.has(window.vscodeWindowId)) {
return Disposable.None;
}
const disposables = new DisposableStore();
const registeredWindow = {
window,
disposables: disposables.add(new DisposableStore())
};
windows.set(window.vscodeWindowId, registeredWindow);
disposables.add(toDisposable(() => {
windows.delete(window.vscodeWindowId);
onDidUnregisterWindow.fire(window);
}));
disposables.add(addDisposableListener(window, EventType.BEFORE_UNLOAD, () => {
onWillUnregisterWindow.fire(window);
}));
onDidRegisterWindow.fire(registeredWindow);
return disposables;
},
getWindows(): Iterable<IRegisteredCodeWindow> {
return windows.values();
},
getWindowsCount(): number {
return windows.size;
},
getWindowId(targetWindow: Window): number {
return (targetWindow as CodeWindow).vscodeWindowId;
},
hasWindow(windowId: number): boolean {
return windows.has(windowId);
},
getWindowById,
getWindow(e: Node | UIEvent | undefined | null): CodeWindow {
const candidateNode = e as Node | undefined | null;
if (candidateNode?.ownerDocument?.defaultView) {
return candidateNode.ownerDocument.defaultView.window as CodeWindow;
}
const candidateEvent = e as UIEvent | undefined | null;
if (candidateEvent?.view) {
return candidateEvent.view.window as CodeWindow;
}
return mainWindow;
},
getDocument(e: Node | UIEvent | undefined | null): Document {
const candidateNode = e as Node | undefined | null;
return getWindow(candidateNode).document;
}
};
})();
//#endregion
export function clearNode(node: HTMLElement): void {
while (node.firstChild) {
node.firstChild.remove();
}
}
class DomListener implements IDisposable {
private _handler: (e: any) => void;
private _node: EventTarget;
private readonly _type: string;
private readonly _options: boolean | AddEventListenerOptions;
constructor(node: EventTarget, type: string, handler: (e: any) => void, options?: boolean | AddEventListenerOptions) {
this._node = node;
this._type = type;
this._handler = handler;
this._options = (options || false);
this._node.addEventListener(this._type, this._handler, this._options);
}
dispose(): void {
if (!this._handler) {
// Already disposed
return;
}
this._node.removeEventListener(this._type, this._handler, this._options);
// Prevent leakers from holding on to the dom or handler func
this._node = null!;
this._handler = null!;
}
}
export function addDisposableListener<K extends keyof GlobalEventHandlersEventMap>(node: EventTarget, type: K, handler: (event: GlobalEventHandlersEventMap[K]) => void, useCapture?: boolean): IDisposable;
export function addDisposableListener(node: EventTarget, type: string, handler: (event: any) => void, useCapture?: boolean): IDisposable;
export function addDisposableListener(node: EventTarget, type: string, handler: (event: any) => void, options: AddEventListenerOptions): IDisposable;
export function addDisposableListener(node: EventTarget, type: string, handler: (event: any) => void, useCaptureOrOptions?: boolean | AddEventListenerOptions): IDisposable {
return new DomListener(node, type, handler, useCaptureOrOptions);
}
export interface IAddStandardDisposableListenerSignature {
(node: HTMLElement, type: 'click', handler: (event: IMouseEvent) => void, useCapture?: boolean): IDisposable;
(node: HTMLElement, type: 'mousedown', handler: (event: IMouseEvent) => void, useCapture?: boolean): IDisposable;
(node: HTMLElement, type: 'keydown', handler: (event: IKeyboardEvent) => void, useCapture?: boolean): IDisposable;
(node: HTMLElement, type: 'keypress', handler: (event: IKeyboardEvent) => void, useCapture?: boolean): IDisposable;
(node: HTMLElement, type: 'keyup', handler: (event: IKeyboardEvent) => void, useCapture?: boolean): IDisposable;
(node: HTMLElement, type: 'pointerdown', handler: (event: PointerEvent) => void, useCapture?: boolean): IDisposable;
(node: HTMLElement, type: 'pointermove', handler: (event: PointerEvent) => void, useCapture?: boolean): IDisposable;
(node: HTMLElement, type: 'pointerup', handler: (event: PointerEvent) => void, useCapture?: boolean): IDisposable;
(node: HTMLElement, type: string, handler: (event: any) => void, useCapture?: boolean): IDisposable;
}
function _wrapAsStandardMouseEvent(targetWindow: Window, handler: (e: IMouseEvent) => void): (e: MouseEvent) => void {
return function (e: MouseEvent) {
return handler(new StandardMouseEvent(targetWindow, e));
};
}
function _wrapAsStandardKeyboardEvent(handler: (e: IKeyboardEvent) => void): (e: KeyboardEvent) => void {
return function (e: KeyboardEvent) {
return handler(new StandardKeyboardEvent(e));
};
}
export const addStandardDisposableListener: IAddStandardDisposableListenerSignature = function addStandardDisposableListener(node: HTMLElement, type: string, handler: (event: any) => void, useCapture?: boolean): IDisposable {
let wrapHandler = handler;
if (type === 'click' || type === 'mousedown' || type === 'contextmenu') {
wrapHandler = _wrapAsStandardMouseEvent(getWindow(node), handler);
} else if (type === 'keydown' || type === 'keypress' || type === 'keyup') {
wrapHandler = _wrapAsStandardKeyboardEvent(handler);
}
return addDisposableListener(node, type, wrapHandler, useCapture);
};
export const addStandardDisposableGenericMouseDownListener = function addStandardDisposableListener(node: HTMLElement, handler: (event: any) => void, useCapture?: boolean): IDisposable {
const wrapHandler = _wrapAsStandardMouseEvent(getWindow(node), handler);
return addDisposableGenericMouseDownListener(node, wrapHandler, useCapture);
};
export const addStandardDisposableGenericMouseUpListener = function addStandardDisposableListener(node: HTMLElement, handler: (event: any) => void, useCapture?: boolean): IDisposable {
const wrapHandler = _wrapAsStandardMouseEvent(getWindow(node), handler);
return addDisposableGenericMouseUpListener(node, wrapHandler, useCapture);
};
export function addDisposableGenericMouseDownListener(node: EventTarget, handler: (event: any) => void, useCapture?: boolean): IDisposable {
return addDisposableListener(node, platform.isIOS && BrowserFeatures.pointerEvents ? EventType.POINTER_DOWN : EventType.MOUSE_DOWN, handler, useCapture);
}
export function addDisposableGenericMouseMoveListener(node: EventTarget, handler: (event: any) => void, useCapture?: boolean): IDisposable {
return addDisposableListener(node, platform.isIOS && BrowserFeatures.pointerEvents ? EventType.POINTER_MOVE : EventType.MOUSE_MOVE, handler, useCapture);
}
export function addDisposableGenericMouseUpListener(node: EventTarget, handler: (event: any) => void, useCapture?: boolean): IDisposable {
return addDisposableListener(node, platform.isIOS && BrowserFeatures.pointerEvents ? EventType.POINTER_UP : EventType.MOUSE_UP, handler, useCapture);
}
/**
* Execute the callback the next time the browser is idle, returning an
* {@link IDisposable} that will cancel the callback when disposed. This wraps
* [requestIdleCallback] so it will fallback to [setTimeout] if the environment
* doesn't support it.
*
* @param targetWindow The window for which to run the idle callback
* @param callback The callback to run when idle, this includes an
* [IdleDeadline] that provides the time alloted for the idle callback by the
* browser. Not respecting this deadline will result in a degraded user
* experience.
* @param timeout A timeout at which point to queue no longer wait for an idle
* callback but queue it on the regular event loop (like setTimeout). Typically
* this should not be used.
*
* [IdleDeadline]: https://developer.mozilla.org/en-US/docs/Web/API/IdleDeadline
* [requestIdleCallback]: https://developer.mozilla.org/en-US/docs/Web/API/Window/requestIdleCallback
* [setTimeout]: https://developer.mozilla.org/en-US/docs/Web/API/Window/setTimeout
*/
export function runWhenWindowIdle(targetWindow: Window | typeof globalThis, callback: (idle: IdleDeadline) => void, timeout?: number): IDisposable {
return _runWhenIdle(targetWindow, callback, timeout);
}
/**
* An implementation of the "idle-until-urgent"-strategy as introduced
* here: https://philipwalton.com/articles/idle-until-urgent/
*/
export class WindowIdleValue<T> extends AbstractIdleValue<T> {
constructor(targetWindow: Window | typeof globalThis, executor: () => T) {
super(targetWindow, executor);
}
}
/**
* Schedule a callback to be run at the next animation frame.
* This allows multiple parties to register callbacks that should run at the next animation frame.
* If currently in an animation frame, `runner` will be executed immediately.
* @return token that can be used to cancel the scheduled runner (only if `runner` was not executed immediately).
*/
export let runAtThisOrScheduleAtNextAnimationFrame: (targetWindow: Window, runner: () => void, priority?: number) => IDisposable;
/**
* Schedule a callback to be run at the next animation frame.
* This allows multiple parties to register callbacks that should run at the next animation frame.
* If currently in an animation frame, `runner` will be executed at the next animation frame.
* @return token that can be used to cancel the scheduled runner.
*/
export let scheduleAtNextAnimationFrame: (targetWindow: Window, runner: () => void, priority?: number) => IDisposable;
export function disposableWindowInterval(targetWindow: Window, handler: () => void | boolean /* stop interval */ | Promise<unknown>, interval: number, iterations?: number): IDisposable {
let iteration = 0;
const timer = targetWindow.setInterval(() => {
iteration++;
if ((typeof iterations === 'number' && iteration >= iterations) || handler() === true) {
disposable.dispose();
}
}, interval);
const disposable = toDisposable(() => {
targetWindow.clearInterval(timer);
});
return disposable;
}
export class WindowIntervalTimer extends IntervalTimer {
private readonly defaultTarget?: Window & typeof globalThis;
/**
*
* @param node The optional node from which the target window is determined
*/
constructor(node?: Node) {
super();
this.defaultTarget = node && getWindow(node);
}
override cancelAndSet(runner: () => void, interval: number, targetWindow?: Window & typeof globalThis): void {
return super.cancelAndSet(runner, interval, targetWindow ?? this.defaultTarget);
}
}
class AnimationFrameQueueItem implements IDisposable {
private _runner: () => void;
public priority: number;
private _canceled: boolean;
constructor(runner: () => void, priority: number = 0) {
this._runner = runner;
this.priority = priority;
this._canceled = false;
}
dispose(): void {
this._canceled = true;
}
execute(): void {
if (this._canceled) {
return;
}
try {
this._runner();
} catch (e) {
onUnexpectedError(e);
}
}
// Sort by priority (largest to lowest)
static sort(a: AnimationFrameQueueItem, b: AnimationFrameQueueItem): number {
return b.priority - a.priority;
}
}
(function () {
/**
* The runners scheduled at the next animation frame
*/
const NEXT_QUEUE = new Map<number /* window ID */, AnimationFrameQueueItem[]>();
/**
* The runners scheduled at the current animation frame
*/
const CURRENT_QUEUE = new Map<number /* window ID */, AnimationFrameQueueItem[]>();
/**
* A flag to keep track if the native requestAnimationFrame was already called
*/
const animFrameRequested = new Map<number /* window ID */, boolean>();
/**
* A flag to indicate if currently handling a native requestAnimationFrame callback
*/
const inAnimationFrameRunner = new Map<number /* window ID */, boolean>();
const animationFrameRunner = (targetWindowId: number) => {
animFrameRequested.set(targetWindowId, false);
const currentQueue = NEXT_QUEUE.get(targetWindowId) ?? [];
CURRENT_QUEUE.set(targetWindowId, currentQueue);
NEXT_QUEUE.set(targetWindowId, []);
inAnimationFrameRunner.set(targetWindowId, true);
while (currentQueue.length > 0) {
currentQueue.sort(AnimationFrameQueueItem.sort);
const top = currentQueue.shift()!;
top.execute();
}
inAnimationFrameRunner.set(targetWindowId, false);
};
scheduleAtNextAnimationFrame = (targetWindow: Window, runner: () => void, priority: number = 0) => {
const targetWindowId = getWindowId(targetWindow);
const item = new AnimationFrameQueueItem(runner, priority);
let nextQueue = NEXT_QUEUE.get(targetWindowId);
if (!nextQueue) {
nextQueue = [];
NEXT_QUEUE.set(targetWindowId, nextQueue);
}
nextQueue.push(item);
if (!animFrameRequested.get(targetWindowId)) {
animFrameRequested.set(targetWindowId, true);
targetWindow.requestAnimationFrame(() => animationFrameRunner(targetWindowId));
}
return item;
};
runAtThisOrScheduleAtNextAnimationFrame = (targetWindow: Window, runner: () => void, priority?: number) => {
const targetWindowId = getWindowId(targetWindow);
if (inAnimationFrameRunner.get(targetWindowId)) {
const item = new AnimationFrameQueueItem(runner, priority);
let currentQueue = CURRENT_QUEUE.get(targetWindowId);
if (!currentQueue) {
currentQueue = [];
CURRENT_QUEUE.set(targetWindowId, currentQueue);
}
currentQueue.push(item);
return item;
} else {
return scheduleAtNextAnimationFrame(targetWindow, runner, priority);
}
};
})();
export function measure(targetWindow: Window, callback: () => void): IDisposable {
return scheduleAtNextAnimationFrame(targetWindow, callback, 10000 /* must be early */);
}
export function modify(targetWindow: Window, callback: () => void): IDisposable {
return scheduleAtNextAnimationFrame(targetWindow, callback, -10000 /* must be late */);
}
/**
* Add a throttled listener. `handler` is fired at most every 8.33333ms or with the next animation frame (if browser supports it).
*/
export interface IEventMerger<R, E> {
(lastEvent: R | null, currentEvent: E): R;
}
const MINIMUM_TIME_MS = 8;
const DEFAULT_EVENT_MERGER: IEventMerger<Event, Event> = function (lastEvent: Event | null, currentEvent: Event) {
return currentEvent;
};
class TimeoutThrottledDomListener<R, E extends Event> extends Disposable {
constructor(node: any, type: string, handler: (event: R) => void, eventMerger: IEventMerger<R, E> = <any>DEFAULT_EVENT_MERGER, minimumTimeMs: number = MINIMUM_TIME_MS) {
super();
let lastEvent: R | null = null;
let lastHandlerTime = 0;
const timeout = this._register(new TimeoutTimer());
const invokeHandler = () => {
lastHandlerTime = (new Date()).getTime();
handler(<R>lastEvent);
lastEvent = null;
};
this._register(addDisposableListener(node, type, (e) => {
lastEvent = eventMerger(lastEvent, e);
const elapsedTime = (new Date()).getTime() - lastHandlerTime;
if (elapsedTime >= minimumTimeMs) {
timeout.cancel();
invokeHandler();
} else {
timeout.setIfNotSet(invokeHandler, minimumTimeMs - elapsedTime);
}
}));
}
}
export function addDisposableThrottledListener<R, E extends Event = Event>(node: any, type: string, handler: (event: R) => void, eventMerger?: IEventMerger<R, E>, minimumTimeMs?: number): IDisposable {
return new TimeoutThrottledDomListener<R, E>(node, type, handler, eventMerger, minimumTimeMs);
}
export function getComputedStyle(el: HTMLElement): CSSStyleDeclaration {
return getWindow(el).getComputedStyle(el, null);
}
export function getClientArea(element: HTMLElement, fallback?: HTMLElement): Dimension {
const elWindow = getWindow(element);
const elDocument = elWindow.document;
// Try with DOM clientWidth / clientHeight
if (element !== elDocument.body) {
return new Dimension(element.clientWidth, element.clientHeight);
}
// If visual view port exits and it's on mobile, it should be used instead of window innerWidth / innerHeight, or document.body.clientWidth / document.body.clientHeight
if (platform.isIOS && elWindow?.visualViewport) {
return new Dimension(elWindow.visualViewport.width, elWindow.visualViewport.height);
}
// Try innerWidth / innerHeight
if (elWindow?.innerWidth && elWindow.innerHeight) {
return new Dimension(elWindow.innerWidth, elWindow.innerHeight);
}
// Try with document.body.clientWidth / document.body.clientHeight
if (elDocument.body && elDocument.body.clientWidth && elDocument.body.clientHeight) {
return new Dimension(elDocument.body.clientWidth, elDocument.body.clientHeight);
}
// Try with document.documentElement.clientWidth / document.documentElement.clientHeight
if (elDocument.documentElement && elDocument.documentElement.clientWidth && elDocument.documentElement.clientHeight) {
return new Dimension(elDocument.documentElement.clientWidth, elDocument.documentElement.clientHeight);
}
if (fallback) {
return getClientArea(fallback);
}
throw new Error('Unable to figure out browser width and height');
}
class SizeUtils {
// Adapted from WinJS
// Converts a CSS positioning string for the specified element to pixels.
private static convertToPixels(element: HTMLElement, value: string): number {
return parseFloat(value) || 0;
}
private static getDimension(element: HTMLElement, cssPropertyName: string, jsPropertyName: string): number {
const computedStyle = getComputedStyle(element);
const value = computedStyle ? computedStyle.getPropertyValue(cssPropertyName) : '0';
return SizeUtils.convertToPixels(element, value);
}
static getBorderLeftWidth(element: HTMLElement): number {
return SizeUtils.getDimension(element, 'border-left-width', 'borderLeftWidth');
}
static getBorderRightWidth(element: HTMLElement): number {
return SizeUtils.getDimension(element, 'border-right-width', 'borderRightWidth');
}
static getBorderTopWidth(element: HTMLElement): number {
return SizeUtils.getDimension(element, 'border-top-width', 'borderTopWidth');
}
static getBorderBottomWidth(element: HTMLElement): number {
return SizeUtils.getDimension(element, 'border-bottom-width', 'borderBottomWidth');
}
static getPaddingLeft(element: HTMLElement): number {
return SizeUtils.getDimension(element, 'padding-left', 'paddingLeft');
}
static getPaddingRight(element: HTMLElement): number {
return SizeUtils.getDimension(element, 'padding-right', 'paddingRight');
}
static getPaddingTop(element: HTMLElement): number {
return SizeUtils.getDimension(element, 'padding-top', 'paddingTop');
}
static getPaddingBottom(element: HTMLElement): number {
return SizeUtils.getDimension(element, 'padding-bottom', 'paddingBottom');
}
static getMarginLeft(element: HTMLElement): number {
return SizeUtils.getDimension(element, 'margin-left', 'marginLeft');
}
static getMarginTop(element: HTMLElement): number {
return SizeUtils.getDimension(element, 'margin-top', 'marginTop');
}
static getMarginRight(element: HTMLElement): number {
return SizeUtils.getDimension(element, 'margin-right', 'marginRight');
}
static getMarginBottom(element: HTMLElement): number {
return SizeUtils.getDimension(element, 'margin-bottom', 'marginBottom');
}
}
// ----------------------------------------------------------------------------------------
// Position & Dimension
export interface IDimension {
readonly width: number;
readonly height: number;
}
export class Dimension implements IDimension {
static readonly None = new Dimension(0, 0);
constructor(
readonly width: number,
readonly height: number,
) { }
with(width: number = this.width, height: number = this.height): Dimension {
if (width !== this.width || height !== this.height) {
return new Dimension(width, height);
} else {
return this;
}
}
static is(obj: unknown): obj is IDimension {
return typeof obj === 'object' && typeof (<IDimension>obj).height === 'number' && typeof (<IDimension>obj).width === 'number';
}
static lift(obj: IDimension): Dimension {
if (obj instanceof Dimension) {
return obj;
} else {
return new Dimension(obj.width, obj.height);
}
}
static equals(a: Dimension | undefined, b: Dimension | undefined): boolean {
if (a === b) {
return true;
}
if (!a || !b) {
return false;
}
return a.width === b.width && a.height === b.height;
}
}
export interface IDomPosition {
readonly left: number;
readonly top: number;
}
export function getTopLeftOffset(element: HTMLElement): IDomPosition {
// Adapted from WinJS.Utilities.getPosition
// and added borders to the mix
let offsetParent = element.offsetParent;
let top = element.offsetTop;
let left = element.offsetLeft;
while (
(element = <HTMLElement>element.parentNode) !== null
&& element !== element.ownerDocument.body
&& element !== element.ownerDocument.documentElement
) {
top -= element.scrollTop;
const c = isShadowRoot(element) ? null : getComputedStyle(element);
if (c) {
left -= c.direction !== 'rtl' ? element.scrollLeft : -element.scrollLeft;
}
if (element === offsetParent) {
left += SizeUtils.getBorderLeftWidth(element);
top += SizeUtils.getBorderTopWidth(element);
top += element.offsetTop;
left += element.offsetLeft;
offsetParent = element.offsetParent;
}
}
return {
left: left,
top: top
};
}
export interface IDomNodePagePosition {
left: number;
top: number;
width: number;
height: number;
}
export function size(element: HTMLElement, width: number | null, height: number | null): void {
if (typeof width === 'number') {
element.style.width = `${width}px`;
}
if (typeof height === 'number') {
element.style.height = `${height}px`;
}
}
export function position(element: HTMLElement, top: number, right?: number, bottom?: number, left?: number, position: string = 'absolute'): void {
if (typeof top === 'number') {
element.style.top = `${top}px`;
}
if (typeof right === 'number') {
element.style.right = `${right}px`;
}
if (typeof bottom === 'number') {
element.style.bottom = `${bottom}px`;
}
if (typeof left === 'number') {
element.style.left = `${left}px`;
}
element.style.position = position;
}
/**
* Returns the position of a dom node relative to the entire page.
*/
export function getDomNodePagePosition(domNode: HTMLElement): IDomNodePagePosition {
const bb = domNode.getBoundingClientRect();
const window = getWindow(domNode);
return {
left: bb.left + window.scrollX,
top: bb.top + window.scrollY,
width: bb.width,
height: bb.height
};
}
/**
* Returns the effective zoom on a given element before window zoom level is applied
*/
export function getDomNodeZoomLevel(domNode: HTMLElement): number {
let testElement: HTMLElement | null = domNode;
let zoom = 1.0;
do {
const elementZoomLevel = (getComputedStyle(testElement) as any).zoom;
if (elementZoomLevel !== null && elementZoomLevel !== undefined && elementZoomLevel !== '1') {
zoom *= elementZoomLevel;
}
testElement = testElement.parentElement;
} while (testElement !== null && testElement !== testElement.ownerDocument.documentElement);
return zoom;
}
// Adapted from WinJS
// Gets the width of the element, including margins.
export function getTotalWidth(element: HTMLElement): number {
const margin = SizeUtils.getMarginLeft(element) + SizeUtils.getMarginRight(element);
return element.offsetWidth + margin;
}
export function getContentWidth(element: HTMLElement): number {
const border = SizeUtils.getBorderLeftWidth(element) + SizeUtils.getBorderRightWidth(element);
const padding = SizeUtils.getPaddingLeft(element) + SizeUtils.getPaddingRight(element);
return element.offsetWidth - border - padding;
}
export function getTotalScrollWidth(element: HTMLElement): number {
const margin = SizeUtils.getMarginLeft(element) + SizeUtils.getMarginRight(element);
return element.scrollWidth + margin;
}
// Adapted from WinJS
// Gets the height of the content of the specified element. The content height does not include borders or padding.
export function getContentHeight(element: HTMLElement): number {
const border = SizeUtils.getBorderTopWidth(element) + SizeUtils.getBorderBottomWidth(element);
const padding = SizeUtils.getPaddingTop(element) + SizeUtils.getPaddingBottom(element);
return element.offsetHeight - border - padding;
}
// Adapted from WinJS
// Gets the height of the element, including its margins.
export function getTotalHeight(element: HTMLElement): number {
const margin = SizeUtils.getMarginTop(element) + SizeUtils.getMarginBottom(element);
return element.offsetHeight + margin;
}
// Gets the left coordinate of the specified element relative to the specified parent.
function getRelativeLeft(element: HTMLElement, parent: HTMLElement): number {
if (element === null) {
return 0;
}
const elementPosition = getTopLeftOffset(element);
const parentPosition = getTopLeftOffset(parent);
return elementPosition.left - parentPosition.left;
}
export function getLargestChildWidth(parent: HTMLElement, children: HTMLElement[]): number {
const childWidths = children.map((child) => {
return Math.max(getTotalScrollWidth(child), getTotalWidth(child)) + getRelativeLeft(child, parent) || 0;
});
const maxWidth = Math.max(...childWidths);
return maxWidth;
}
// ----------------------------------------------------------------------------------------
export function isAncestor(testChild: Node | null, testAncestor: Node | null): boolean {
return Boolean(testAncestor?.contains(testChild));
}
const parentFlowToDataKey = 'parentFlowToElementId';
/**
* Set an explicit parent to use for nodes that are not part of the
* regular dom structure.
*/
export function setParentFlowTo(fromChildElement: HTMLElement, toParentElement: Element): void {
fromChildElement.dataset[parentFlowToDataKey] = toParentElement.id;
}
function getParentFlowToElement(node: HTMLElement): HTMLElement | null {
const flowToParentId = node.dataset[parentFlowToDataKey];
if (typeof flowToParentId === 'string') {
return node.ownerDocument.getElementById(flowToParentId);
}
return null;
}
/**
* Check if `testAncestor` is an ancestor of `testChild`, observing the explicit
* parents set by `setParentFlowTo`.
*/
export function isAncestorUsingFlowTo(testChild: Node, testAncestor: Node): boolean {
let node: Node | null = testChild;
while (node) {
if (node === testAncestor) {
return true;
}
if (isHTMLElement(node)) {
const flowToParentElement = getParentFlowToElement(node);
if (flowToParentElement) {
node = flowToParentElement;
continue;
}
}
node = node.parentNode;
}
return false;
}
export function findParentWithClass(node: HTMLElement, clazz: string, stopAtClazzOrNode?: string | HTMLElement): HTMLElement | null {
while (node && node.nodeType === node.ELEMENT_NODE) {
if (node.classList.contains(clazz)) {
return node;
}
if (stopAtClazzOrNode) {
if (typeof stopAtClazzOrNode === 'string') {
if (node.classList.contains(stopAtClazzOrNode)) {
return null;
}
} else {
if (node === stopAtClazzOrNode) {
return null;
}
}
}
node = <HTMLElement>node.parentNode;
}
return null;
}
export function hasParentWithClass(node: HTMLElement, clazz: string, stopAtClazzOrNode?: string | HTMLElement): boolean {
return !!findParentWithClass(node, clazz, stopAtClazzOrNode);
}
export function isShadowRoot(node: Node): node is ShadowRoot {
return (
node && !!(<ShadowRoot>node).host && !!(<ShadowRoot>node).mode
);
}
export function isInShadowDOM(domNode: Node): boolean {
return !!getShadowRoot(domNode);
}
export function getShadowRoot(domNode: Node): ShadowRoot | null {
while (domNode.parentNode) {
if (domNode === domNode.ownerDocument?.body) {
// reached the body
return null;
}
domNode = domNode.parentNode;
}
return isShadowRoot(domNode) ? domNode : null;
}
/**
* Returns the active element across all child windows
* based on document focus. Falls back to the main
* window if no window has focus.
*/
export function getActiveElement(): Element | null {
let result = getActiveDocument().activeElement;
while (result?.shadowRoot) {
result = result.shadowRoot.activeElement;
}
return result;
}
/**
* Returns true if the focused window active element matches
* the provided element. Falls back to the main window if no
* window has focus.
*/
export function isActiveElement(element: Element): boolean {
return getActiveElement() === element;
}
/**
* Returns true if the focused window active element is contained in
* `ancestor`. Falls back to the main window if no window has focus.
*/
export function isAncestorOfActiveElement(ancestor: Element): boolean {
return isAncestor(getActiveElement(), ancestor);
}
/**
* Returns whether the element is in the active `document`. The active
* document has focus or will be the main windows document.
*/
export function isActiveDocument(element: Element): boolean {
return element.ownerDocument === getActiveDocument();
}
/**
* Returns the active document across main and child windows.
* Prefers the window with focus, otherwise falls back to
* the main windows document.
*/
export function getActiveDocument(): Document {
if (getWindowsCount() <= 1) {
return mainWindow.document;
}
const documents = Array.from(getWindows()).map(({ window }) => window.document);
return documents.find(doc => doc.hasFocus()) ?? mainWindow.document;
}
/**
* Returns the active window across main and child windows.
* Prefers the window with focus, otherwise falls back to
* the main window.
*/
export function getActiveWindow(): CodeWindow {
const document = getActiveDocument();
return (document.defaultView?.window ?? mainWindow) as CodeWindow;
}
const globalStylesheets = new Map<HTMLStyleElement /* main stylesheet */, Set<HTMLStyleElement /* aux window clones that track the main stylesheet */>>();
export function isGlobalStylesheet(node: Node): boolean {
return globalStylesheets.has(node as HTMLStyleElement);
}
/**
* A version of createStyleSheet which has a unified API to initialize/set the style content.
*/
export function createStyleSheet2(): WrappedStyleElement {
return new WrappedStyleElement();
}
class WrappedStyleElement {
private _currentCssStyle = '';
private _styleSheet: HTMLStyleElement | undefined = undefined;
public setStyle(cssStyle: string): void {
if (cssStyle === this._currentCssStyle) {
return;
}
this._currentCssStyle = cssStyle;
if (!this._styleSheet) {
this._styleSheet = createStyleSheet(mainWindow.document.head, (s) => s.innerText = cssStyle);
} else {
this._styleSheet.innerText = cssStyle;
}
}
public dispose(): void {
if (this._styleSheet) {
this._styleSheet.remove();
this._styleSheet = undefined;
}
}
}
export function createStyleSheet(container: HTMLElement = mainWindow.document.head, beforeAppend?: (style: HTMLStyleElement) => void, disposableStore?: DisposableStore): HTMLStyleElement {
const style = document.createElement('style');
style.type = 'text/css';
style.media = 'screen';
beforeAppend?.(style);
container.appendChild(style);
if (disposableStore) {
disposableStore.add(toDisposable(() => style.remove()));
}
// With <head> as container, the stylesheet becomes global and is tracked
// to support auxiliary windows to clone the stylesheet.
if (container === mainWindow.document.head) {
const globalStylesheetClones = new Set<HTMLStyleElement>();
globalStylesheets.set(style, globalStylesheetClones);
for (const { window: targetWindow, disposables } of getWindows()) {
if (targetWindow === mainWindow) {
continue; // main window is already tracked
}
const cloneDisposable = disposables.add(cloneGlobalStyleSheet(style, globalStylesheetClones, targetWindow));
disposableStore?.add(cloneDisposable);
}
}
return style;
}
export function cloneGlobalStylesheets(targetWindow: Window): IDisposable {
const disposables = new DisposableStore();
for (const [globalStylesheet, clonedGlobalStylesheets] of globalStylesheets) {
disposables.add(cloneGlobalStyleSheet(globalStylesheet, clonedGlobalStylesheets, targetWindow));
}
return disposables;