Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
microsoft
GitHub Repository: microsoft/vscode
Path: blob/main/src/vs/base/browser/dom.ts
3292 views
1
/*---------------------------------------------------------------------------------------------
2
* Copyright (c) Microsoft Corporation. All rights reserved.
3
* Licensed under the MIT License. See License.txt in the project root for license information.
4
*--------------------------------------------------------------------------------------------*/
5
6
import * as browser from './browser.js';
7
import { BrowserFeatures } from './canIUse.js';
8
import { IKeyboardEvent, StandardKeyboardEvent } from './keyboardEvent.js';
9
import { IMouseEvent, StandardMouseEvent } from './mouseEvent.js';
10
import { AbstractIdleValue, IntervalTimer, TimeoutTimer, _runWhenIdle, IdleDeadline } from '../common/async.js';
11
import { BugIndicatingError, onUnexpectedError } from '../common/errors.js';
12
import * as event from '../common/event.js';
13
import { KeyCode } from '../common/keyCodes.js';
14
import { Disposable, DisposableStore, IDisposable, toDisposable } from '../common/lifecycle.js';
15
import { RemoteAuthorities } from '../common/network.js';
16
import * as platform from '../common/platform.js';
17
import { URI } from '../common/uri.js';
18
import { hash } from '../common/hash.js';
19
import { CodeWindow, ensureCodeWindow, mainWindow } from './window.js';
20
import { isPointWithinTriangle } from '../common/numbers.js';
21
import { IObservable, derived, derivedOpts, IReader, observableValue } from '../common/observable.js';
22
23
export interface IRegisteredCodeWindow {
24
readonly window: CodeWindow;
25
readonly disposables: DisposableStore;
26
}
27
28
//# region Multi-Window Support Utilities
29
30
export const {
31
registerWindow,
32
getWindow,
33
getDocument,
34
getWindows,
35
getWindowsCount,
36
getWindowId,
37
getWindowById,
38
hasWindow,
39
onDidRegisterWindow,
40
onWillUnregisterWindow,
41
onDidUnregisterWindow
42
} = (function () {
43
const windows = new Map<number, IRegisteredCodeWindow>();
44
45
ensureCodeWindow(mainWindow, 1);
46
const mainWindowRegistration = { window: mainWindow, disposables: new DisposableStore() };
47
windows.set(mainWindow.vscodeWindowId, mainWindowRegistration);
48
49
const onDidRegisterWindow = new event.Emitter<IRegisteredCodeWindow>();
50
const onDidUnregisterWindow = new event.Emitter<CodeWindow>();
51
const onWillUnregisterWindow = new event.Emitter<CodeWindow>();
52
53
function getWindowById(windowId: number): IRegisteredCodeWindow | undefined;
54
function getWindowById(windowId: number | undefined, fallbackToMain: true): IRegisteredCodeWindow;
55
function getWindowById(windowId: number | undefined, fallbackToMain?: boolean): IRegisteredCodeWindow | undefined {
56
const window = typeof windowId === 'number' ? windows.get(windowId) : undefined;
57
58
return window ?? (fallbackToMain ? mainWindowRegistration : undefined);
59
}
60
61
return {
62
onDidRegisterWindow: onDidRegisterWindow.event,
63
onWillUnregisterWindow: onWillUnregisterWindow.event,
64
onDidUnregisterWindow: onDidUnregisterWindow.event,
65
registerWindow(window: CodeWindow): IDisposable {
66
if (windows.has(window.vscodeWindowId)) {
67
return Disposable.None;
68
}
69
70
const disposables = new DisposableStore();
71
72
const registeredWindow = {
73
window,
74
disposables: disposables.add(new DisposableStore())
75
};
76
windows.set(window.vscodeWindowId, registeredWindow);
77
78
disposables.add(toDisposable(() => {
79
windows.delete(window.vscodeWindowId);
80
onDidUnregisterWindow.fire(window);
81
}));
82
83
disposables.add(addDisposableListener(window, EventType.BEFORE_UNLOAD, () => {
84
onWillUnregisterWindow.fire(window);
85
}));
86
87
onDidRegisterWindow.fire(registeredWindow);
88
89
return disposables;
90
},
91
getWindows(): Iterable<IRegisteredCodeWindow> {
92
return windows.values();
93
},
94
getWindowsCount(): number {
95
return windows.size;
96
},
97
getWindowId(targetWindow: Window): number {
98
return (targetWindow as CodeWindow).vscodeWindowId;
99
},
100
hasWindow(windowId: number): boolean {
101
return windows.has(windowId);
102
},
103
getWindowById,
104
getWindow(e: Node | UIEvent | undefined | null): CodeWindow {
105
const candidateNode = e as Node | undefined | null;
106
if (candidateNode?.ownerDocument?.defaultView) {
107
return candidateNode.ownerDocument.defaultView.window as CodeWindow;
108
}
109
110
const candidateEvent = e as UIEvent | undefined | null;
111
if (candidateEvent?.view) {
112
return candidateEvent.view.window as CodeWindow;
113
}
114
115
return mainWindow;
116
},
117
getDocument(e: Node | UIEvent | undefined | null): Document {
118
const candidateNode = e as Node | undefined | null;
119
return getWindow(candidateNode).document;
120
}
121
};
122
})();
123
124
//#endregion
125
126
export function clearNode(node: HTMLElement): void {
127
while (node.firstChild) {
128
node.firstChild.remove();
129
}
130
}
131
132
class DomListener implements IDisposable {
133
134
private _handler: (e: any) => void;
135
private _node: EventTarget;
136
private readonly _type: string;
137
private readonly _options: boolean | AddEventListenerOptions;
138
139
constructor(node: EventTarget, type: string, handler: (e: any) => void, options?: boolean | AddEventListenerOptions) {
140
this._node = node;
141
this._type = type;
142
this._handler = handler;
143
this._options = (options || false);
144
this._node.addEventListener(this._type, this._handler, this._options);
145
}
146
147
dispose(): void {
148
if (!this._handler) {
149
// Already disposed
150
return;
151
}
152
153
this._node.removeEventListener(this._type, this._handler, this._options);
154
155
// Prevent leakers from holding on to the dom or handler func
156
this._node = null!;
157
this._handler = null!;
158
}
159
}
160
161
export function addDisposableListener<K extends keyof GlobalEventHandlersEventMap>(node: EventTarget, type: K, handler: (event: GlobalEventHandlersEventMap[K]) => void, useCapture?: boolean): IDisposable;
162
export function addDisposableListener(node: EventTarget, type: string, handler: (event: any) => void, useCapture?: boolean): IDisposable;
163
export function addDisposableListener(node: EventTarget, type: string, handler: (event: any) => void, options: AddEventListenerOptions): IDisposable;
164
export function addDisposableListener(node: EventTarget, type: string, handler: (event: any) => void, useCaptureOrOptions?: boolean | AddEventListenerOptions): IDisposable {
165
return new DomListener(node, type, handler, useCaptureOrOptions);
166
}
167
168
export interface IAddStandardDisposableListenerSignature {
169
(node: HTMLElement, type: 'click', handler: (event: IMouseEvent) => void, useCapture?: boolean): IDisposable;
170
(node: HTMLElement, type: 'mousedown', handler: (event: IMouseEvent) => void, useCapture?: boolean): IDisposable;
171
(node: HTMLElement, type: 'keydown', handler: (event: IKeyboardEvent) => void, useCapture?: boolean): IDisposable;
172
(node: HTMLElement, type: 'keypress', handler: (event: IKeyboardEvent) => void, useCapture?: boolean): IDisposable;
173
(node: HTMLElement, type: 'keyup', handler: (event: IKeyboardEvent) => void, useCapture?: boolean): IDisposable;
174
(node: HTMLElement, type: 'pointerdown', handler: (event: PointerEvent) => void, useCapture?: boolean): IDisposable;
175
(node: HTMLElement, type: 'pointermove', handler: (event: PointerEvent) => void, useCapture?: boolean): IDisposable;
176
(node: HTMLElement, type: 'pointerup', handler: (event: PointerEvent) => void, useCapture?: boolean): IDisposable;
177
(node: HTMLElement, type: string, handler: (event: any) => void, useCapture?: boolean): IDisposable;
178
}
179
function _wrapAsStandardMouseEvent(targetWindow: Window, handler: (e: IMouseEvent) => void): (e: MouseEvent) => void {
180
return function (e: MouseEvent) {
181
return handler(new StandardMouseEvent(targetWindow, e));
182
};
183
}
184
function _wrapAsStandardKeyboardEvent(handler: (e: IKeyboardEvent) => void): (e: KeyboardEvent) => void {
185
return function (e: KeyboardEvent) {
186
return handler(new StandardKeyboardEvent(e));
187
};
188
}
189
export const addStandardDisposableListener: IAddStandardDisposableListenerSignature = function addStandardDisposableListener(node: HTMLElement, type: string, handler: (event: any) => void, useCapture?: boolean): IDisposable {
190
let wrapHandler = handler;
191
192
if (type === 'click' || type === 'mousedown' || type === 'contextmenu') {
193
wrapHandler = _wrapAsStandardMouseEvent(getWindow(node), handler);
194
} else if (type === 'keydown' || type === 'keypress' || type === 'keyup') {
195
wrapHandler = _wrapAsStandardKeyboardEvent(handler);
196
}
197
198
return addDisposableListener(node, type, wrapHandler, useCapture);
199
};
200
201
export const addStandardDisposableGenericMouseDownListener = function addStandardDisposableListener(node: HTMLElement, handler: (event: any) => void, useCapture?: boolean): IDisposable {
202
const wrapHandler = _wrapAsStandardMouseEvent(getWindow(node), handler);
203
204
return addDisposableGenericMouseDownListener(node, wrapHandler, useCapture);
205
};
206
207
export const addStandardDisposableGenericMouseUpListener = function addStandardDisposableListener(node: HTMLElement, handler: (event: any) => void, useCapture?: boolean): IDisposable {
208
const wrapHandler = _wrapAsStandardMouseEvent(getWindow(node), handler);
209
210
return addDisposableGenericMouseUpListener(node, wrapHandler, useCapture);
211
};
212
export function addDisposableGenericMouseDownListener(node: EventTarget, handler: (event: any) => void, useCapture?: boolean): IDisposable {
213
return addDisposableListener(node, platform.isIOS && BrowserFeatures.pointerEvents ? EventType.POINTER_DOWN : EventType.MOUSE_DOWN, handler, useCapture);
214
}
215
216
export function addDisposableGenericMouseMoveListener(node: EventTarget, handler: (event: any) => void, useCapture?: boolean): IDisposable {
217
return addDisposableListener(node, platform.isIOS && BrowserFeatures.pointerEvents ? EventType.POINTER_MOVE : EventType.MOUSE_MOVE, handler, useCapture);
218
}
219
220
export function addDisposableGenericMouseUpListener(node: EventTarget, handler: (event: any) => void, useCapture?: boolean): IDisposable {
221
return addDisposableListener(node, platform.isIOS && BrowserFeatures.pointerEvents ? EventType.POINTER_UP : EventType.MOUSE_UP, handler, useCapture);
222
}
223
224
/**
225
* Execute the callback the next time the browser is idle, returning an
226
* {@link IDisposable} that will cancel the callback when disposed. This wraps
227
* [requestIdleCallback] so it will fallback to [setTimeout] if the environment
228
* doesn't support it.
229
*
230
* @param targetWindow The window for which to run the idle callback
231
* @param callback The callback to run when idle, this includes an
232
* [IdleDeadline] that provides the time alloted for the idle callback by the
233
* browser. Not respecting this deadline will result in a degraded user
234
* experience.
235
* @param timeout A timeout at which point to queue no longer wait for an idle
236
* callback but queue it on the regular event loop (like setTimeout). Typically
237
* this should not be used.
238
*
239
* [IdleDeadline]: https://developer.mozilla.org/en-US/docs/Web/API/IdleDeadline
240
* [requestIdleCallback]: https://developer.mozilla.org/en-US/docs/Web/API/Window/requestIdleCallback
241
* [setTimeout]: https://developer.mozilla.org/en-US/docs/Web/API/Window/setTimeout
242
*/
243
export function runWhenWindowIdle(targetWindow: Window | typeof globalThis, callback: (idle: IdleDeadline) => void, timeout?: number): IDisposable {
244
return _runWhenIdle(targetWindow, callback, timeout);
245
}
246
247
/**
248
* An implementation of the "idle-until-urgent"-strategy as introduced
249
* here: https://philipwalton.com/articles/idle-until-urgent/
250
*/
251
export class WindowIdleValue<T> extends AbstractIdleValue<T> {
252
constructor(targetWindow: Window | typeof globalThis, executor: () => T) {
253
super(targetWindow, executor);
254
}
255
}
256
257
/**
258
* Schedule a callback to be run at the next animation frame.
259
* This allows multiple parties to register callbacks that should run at the next animation frame.
260
* If currently in an animation frame, `runner` will be executed immediately.
261
* @return token that can be used to cancel the scheduled runner (only if `runner` was not executed immediately).
262
*/
263
export let runAtThisOrScheduleAtNextAnimationFrame: (targetWindow: Window, runner: () => void, priority?: number) => IDisposable;
264
/**
265
* Schedule a callback to be run at the next animation frame.
266
* This allows multiple parties to register callbacks that should run at the next animation frame.
267
* If currently in an animation frame, `runner` will be executed at the next animation frame.
268
* @return token that can be used to cancel the scheduled runner.
269
*/
270
export let scheduleAtNextAnimationFrame: (targetWindow: Window, runner: () => void, priority?: number) => IDisposable;
271
272
export function disposableWindowInterval(targetWindow: Window, handler: () => void | boolean /* stop interval */ | Promise<unknown>, interval: number, iterations?: number): IDisposable {
273
let iteration = 0;
274
const timer = targetWindow.setInterval(() => {
275
iteration++;
276
if ((typeof iterations === 'number' && iteration >= iterations) || handler() === true) {
277
disposable.dispose();
278
}
279
}, interval);
280
const disposable = toDisposable(() => {
281
targetWindow.clearInterval(timer);
282
});
283
return disposable;
284
}
285
286
export class WindowIntervalTimer extends IntervalTimer {
287
288
private readonly defaultTarget?: Window & typeof globalThis;
289
290
/**
291
*
292
* @param node The optional node from which the target window is determined
293
*/
294
constructor(node?: Node) {
295
super();
296
this.defaultTarget = node && getWindow(node);
297
}
298
299
override cancelAndSet(runner: () => void, interval: number, targetWindow?: Window & typeof globalThis): void {
300
return super.cancelAndSet(runner, interval, targetWindow ?? this.defaultTarget);
301
}
302
}
303
304
class AnimationFrameQueueItem implements IDisposable {
305
306
private _runner: () => void;
307
public priority: number;
308
private _canceled: boolean;
309
310
constructor(runner: () => void, priority: number = 0) {
311
this._runner = runner;
312
this.priority = priority;
313
this._canceled = false;
314
}
315
316
dispose(): void {
317
this._canceled = true;
318
}
319
320
execute(): void {
321
if (this._canceled) {
322
return;
323
}
324
325
try {
326
this._runner();
327
} catch (e) {
328
onUnexpectedError(e);
329
}
330
}
331
332
// Sort by priority (largest to lowest)
333
static sort(a: AnimationFrameQueueItem, b: AnimationFrameQueueItem): number {
334
return b.priority - a.priority;
335
}
336
}
337
338
(function () {
339
/**
340
* The runners scheduled at the next animation frame
341
*/
342
const NEXT_QUEUE = new Map<number /* window ID */, AnimationFrameQueueItem[]>();
343
/**
344
* The runners scheduled at the current animation frame
345
*/
346
const CURRENT_QUEUE = new Map<number /* window ID */, AnimationFrameQueueItem[]>();
347
/**
348
* A flag to keep track if the native requestAnimationFrame was already called
349
*/
350
const animFrameRequested = new Map<number /* window ID */, boolean>();
351
/**
352
* A flag to indicate if currently handling a native requestAnimationFrame callback
353
*/
354
const inAnimationFrameRunner = new Map<number /* window ID */, boolean>();
355
356
const animationFrameRunner = (targetWindowId: number) => {
357
animFrameRequested.set(targetWindowId, false);
358
359
const currentQueue = NEXT_QUEUE.get(targetWindowId) ?? [];
360
CURRENT_QUEUE.set(targetWindowId, currentQueue);
361
NEXT_QUEUE.set(targetWindowId, []);
362
363
inAnimationFrameRunner.set(targetWindowId, true);
364
while (currentQueue.length > 0) {
365
currentQueue.sort(AnimationFrameQueueItem.sort);
366
const top = currentQueue.shift()!;
367
top.execute();
368
}
369
inAnimationFrameRunner.set(targetWindowId, false);
370
};
371
372
scheduleAtNextAnimationFrame = (targetWindow: Window, runner: () => void, priority: number = 0) => {
373
const targetWindowId = getWindowId(targetWindow);
374
const item = new AnimationFrameQueueItem(runner, priority);
375
376
let nextQueue = NEXT_QUEUE.get(targetWindowId);
377
if (!nextQueue) {
378
nextQueue = [];
379
NEXT_QUEUE.set(targetWindowId, nextQueue);
380
}
381
nextQueue.push(item);
382
383
if (!animFrameRequested.get(targetWindowId)) {
384
animFrameRequested.set(targetWindowId, true);
385
targetWindow.requestAnimationFrame(() => animationFrameRunner(targetWindowId));
386
}
387
388
return item;
389
};
390
391
runAtThisOrScheduleAtNextAnimationFrame = (targetWindow: Window, runner: () => void, priority?: number) => {
392
const targetWindowId = getWindowId(targetWindow);
393
if (inAnimationFrameRunner.get(targetWindowId)) {
394
const item = new AnimationFrameQueueItem(runner, priority);
395
let currentQueue = CURRENT_QUEUE.get(targetWindowId);
396
if (!currentQueue) {
397
currentQueue = [];
398
CURRENT_QUEUE.set(targetWindowId, currentQueue);
399
}
400
currentQueue.push(item);
401
return item;
402
} else {
403
return scheduleAtNextAnimationFrame(targetWindow, runner, priority);
404
}
405
};
406
})();
407
408
export function measure(targetWindow: Window, callback: () => void): IDisposable {
409
return scheduleAtNextAnimationFrame(targetWindow, callback, 10000 /* must be early */);
410
}
411
412
export function modify(targetWindow: Window, callback: () => void): IDisposable {
413
return scheduleAtNextAnimationFrame(targetWindow, callback, -10000 /* must be late */);
414
}
415
416
/**
417
* Add a throttled listener. `handler` is fired at most every 8.33333ms or with the next animation frame (if browser supports it).
418
*/
419
export interface IEventMerger<R, E> {
420
(lastEvent: R | null, currentEvent: E): R;
421
}
422
423
const MINIMUM_TIME_MS = 8;
424
const DEFAULT_EVENT_MERGER: IEventMerger<Event, Event> = function (lastEvent: Event | null, currentEvent: Event) {
425
return currentEvent;
426
};
427
428
class TimeoutThrottledDomListener<R, E extends Event> extends Disposable {
429
430
constructor(node: any, type: string, handler: (event: R) => void, eventMerger: IEventMerger<R, E> = <any>DEFAULT_EVENT_MERGER, minimumTimeMs: number = MINIMUM_TIME_MS) {
431
super();
432
433
let lastEvent: R | null = null;
434
let lastHandlerTime = 0;
435
const timeout = this._register(new TimeoutTimer());
436
437
const invokeHandler = () => {
438
lastHandlerTime = (new Date()).getTime();
439
handler(<R>lastEvent);
440
lastEvent = null;
441
};
442
443
this._register(addDisposableListener(node, type, (e) => {
444
445
lastEvent = eventMerger(lastEvent, e);
446
const elapsedTime = (new Date()).getTime() - lastHandlerTime;
447
448
if (elapsedTime >= minimumTimeMs) {
449
timeout.cancel();
450
invokeHandler();
451
} else {
452
timeout.setIfNotSet(invokeHandler, minimumTimeMs - elapsedTime);
453
}
454
}));
455
}
456
}
457
458
export function addDisposableThrottledListener<R, E extends Event = Event>(node: any, type: string, handler: (event: R) => void, eventMerger?: IEventMerger<R, E>, minimumTimeMs?: number): IDisposable {
459
return new TimeoutThrottledDomListener<R, E>(node, type, handler, eventMerger, minimumTimeMs);
460
}
461
462
export function getComputedStyle(el: HTMLElement): CSSStyleDeclaration {
463
return getWindow(el).getComputedStyle(el, null);
464
}
465
466
export function getClientArea(element: HTMLElement, defaultValue?: Dimension, fallbackElement?: HTMLElement): Dimension {
467
const elWindow = getWindow(element);
468
const elDocument = elWindow.document;
469
470
// Try with DOM clientWidth / clientHeight
471
if (element !== elDocument.body) {
472
return new Dimension(element.clientWidth, element.clientHeight);
473
}
474
475
// 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
476
if (platform.isIOS && elWindow?.visualViewport) {
477
return new Dimension(elWindow.visualViewport.width, elWindow.visualViewport.height);
478
}
479
480
// Try innerWidth / innerHeight
481
if (elWindow?.innerWidth && elWindow.innerHeight) {
482
return new Dimension(elWindow.innerWidth, elWindow.innerHeight);
483
}
484
485
// Try with document.body.clientWidth / document.body.clientHeight
486
if (elDocument.body && elDocument.body.clientWidth && elDocument.body.clientHeight) {
487
return new Dimension(elDocument.body.clientWidth, elDocument.body.clientHeight);
488
}
489
490
// Try with document.documentElement.clientWidth / document.documentElement.clientHeight
491
if (elDocument.documentElement && elDocument.documentElement.clientWidth && elDocument.documentElement.clientHeight) {
492
return new Dimension(elDocument.documentElement.clientWidth, elDocument.documentElement.clientHeight);
493
}
494
495
if (fallbackElement) {
496
return getClientArea(fallbackElement, defaultValue);
497
}
498
499
if (defaultValue) {
500
return defaultValue;
501
}
502
503
throw new Error('Unable to figure out browser width and height');
504
}
505
506
class SizeUtils {
507
// Adapted from WinJS
508
// Converts a CSS positioning string for the specified element to pixels.
509
private static convertToPixels(element: HTMLElement, value: string): number {
510
return parseFloat(value) || 0;
511
}
512
513
private static getDimension(element: HTMLElement, cssPropertyName: string): number {
514
const computedStyle = getComputedStyle(element);
515
const value = computedStyle ? computedStyle.getPropertyValue(cssPropertyName) : '0';
516
return SizeUtils.convertToPixels(element, value);
517
}
518
519
static getBorderLeftWidth(element: HTMLElement): number {
520
return SizeUtils.getDimension(element, 'border-left-width');
521
}
522
static getBorderRightWidth(element: HTMLElement): number {
523
return SizeUtils.getDimension(element, 'border-right-width');
524
}
525
static getBorderTopWidth(element: HTMLElement): number {
526
return SizeUtils.getDimension(element, 'border-top-width');
527
}
528
static getBorderBottomWidth(element: HTMLElement): number {
529
return SizeUtils.getDimension(element, 'border-bottom-width');
530
}
531
532
static getPaddingLeft(element: HTMLElement): number {
533
return SizeUtils.getDimension(element, 'padding-left');
534
}
535
static getPaddingRight(element: HTMLElement): number {
536
return SizeUtils.getDimension(element, 'padding-right');
537
}
538
static getPaddingTop(element: HTMLElement): number {
539
return SizeUtils.getDimension(element, 'padding-top');
540
}
541
static getPaddingBottom(element: HTMLElement): number {
542
return SizeUtils.getDimension(element, 'padding-bottom');
543
}
544
545
static getMarginLeft(element: HTMLElement): number {
546
return SizeUtils.getDimension(element, 'margin-left');
547
}
548
static getMarginTop(element: HTMLElement): number {
549
return SizeUtils.getDimension(element, 'margin-top');
550
}
551
static getMarginRight(element: HTMLElement): number {
552
return SizeUtils.getDimension(element, 'margin-right');
553
}
554
static getMarginBottom(element: HTMLElement): number {
555
return SizeUtils.getDimension(element, 'margin-bottom');
556
}
557
}
558
559
// ----------------------------------------------------------------------------------------
560
// Position & Dimension
561
562
export interface IDimension {
563
readonly width: number;
564
readonly height: number;
565
}
566
567
export class Dimension implements IDimension {
568
569
static readonly None = new Dimension(0, 0);
570
571
constructor(
572
readonly width: number,
573
readonly height: number,
574
) { }
575
576
with(width: number = this.width, height: number = this.height): Dimension {
577
if (width !== this.width || height !== this.height) {
578
return new Dimension(width, height);
579
} else {
580
return this;
581
}
582
}
583
584
static is(obj: unknown): obj is IDimension {
585
return typeof obj === 'object' && typeof (<IDimension>obj).height === 'number' && typeof (<IDimension>obj).width === 'number';
586
}
587
588
static lift(obj: IDimension): Dimension {
589
if (obj instanceof Dimension) {
590
return obj;
591
} else {
592
return new Dimension(obj.width, obj.height);
593
}
594
}
595
596
static equals(a: Dimension | undefined, b: Dimension | undefined): boolean {
597
if (a === b) {
598
return true;
599
}
600
if (!a || !b) {
601
return false;
602
}
603
return a.width === b.width && a.height === b.height;
604
}
605
}
606
607
export interface IDomPosition {
608
readonly left: number;
609
readonly top: number;
610
}
611
612
export function getTopLeftOffset(element: HTMLElement): IDomPosition {
613
// Adapted from WinJS.Utilities.getPosition
614
// and added borders to the mix
615
616
let offsetParent = element.offsetParent;
617
let top = element.offsetTop;
618
let left = element.offsetLeft;
619
620
while (
621
(element = <HTMLElement>element.parentNode) !== null
622
&& element !== element.ownerDocument.body
623
&& element !== element.ownerDocument.documentElement
624
) {
625
top -= element.scrollTop;
626
const c = isShadowRoot(element) ? null : getComputedStyle(element);
627
if (c) {
628
left -= c.direction !== 'rtl' ? element.scrollLeft : -element.scrollLeft;
629
}
630
631
if (element === offsetParent) {
632
left += SizeUtils.getBorderLeftWidth(element);
633
top += SizeUtils.getBorderTopWidth(element);
634
top += element.offsetTop;
635
left += element.offsetLeft;
636
offsetParent = element.offsetParent;
637
}
638
}
639
640
return {
641
left: left,
642
top: top
643
};
644
}
645
646
export interface IDomNodePagePosition {
647
left: number;
648
top: number;
649
width: number;
650
height: number;
651
}
652
653
export function size(element: HTMLElement, width: number | null, height: number | null): void {
654
if (typeof width === 'number') {
655
element.style.width = `${width}px`;
656
}
657
658
if (typeof height === 'number') {
659
element.style.height = `${height}px`;
660
}
661
}
662
663
export function position(element: HTMLElement, top: number, right?: number, bottom?: number, left?: number, position: string = 'absolute'): void {
664
if (typeof top === 'number') {
665
element.style.top = `${top}px`;
666
}
667
668
if (typeof right === 'number') {
669
element.style.right = `${right}px`;
670
}
671
672
if (typeof bottom === 'number') {
673
element.style.bottom = `${bottom}px`;
674
}
675
676
if (typeof left === 'number') {
677
element.style.left = `${left}px`;
678
}
679
680
element.style.position = position;
681
}
682
683
/**
684
* Returns the position of a dom node relative to the entire page.
685
*/
686
export function getDomNodePagePosition(domNode: HTMLElement): IDomNodePagePosition {
687
const bb = domNode.getBoundingClientRect();
688
const window = getWindow(domNode);
689
return {
690
left: bb.left + window.scrollX,
691
top: bb.top + window.scrollY,
692
width: bb.width,
693
height: bb.height
694
};
695
}
696
697
/**
698
* Returns whether the element is in the bottom right quarter of the container.
699
*
700
* @param element the element to check for being in the bottom right quarter
701
* @param container the container to check against
702
* @returns true if the element is in the bottom right quarter of the container
703
*/
704
export function isElementInBottomRightQuarter(element: HTMLElement, container: HTMLElement): boolean {
705
const position = getDomNodePagePosition(element);
706
const clientArea = getClientArea(container);
707
708
return position.left > clientArea.width / 2 && position.top > clientArea.height / 2;
709
}
710
711
/**
712
* Returns the effective zoom on a given element before window zoom level is applied
713
*/
714
export function getDomNodeZoomLevel(domNode: HTMLElement): number {
715
let testElement: HTMLElement | null = domNode;
716
let zoom = 1.0;
717
do {
718
const elementZoomLevel = (getComputedStyle(testElement) as any).zoom;
719
if (elementZoomLevel !== null && elementZoomLevel !== undefined && elementZoomLevel !== '1') {
720
zoom *= elementZoomLevel;
721
}
722
723
testElement = testElement.parentElement;
724
} while (testElement !== null && testElement !== testElement.ownerDocument.documentElement);
725
726
return zoom;
727
}
728
729
730
// Adapted from WinJS
731
// Gets the width of the element, including margins.
732
export function getTotalWidth(element: HTMLElement): number {
733
const margin = SizeUtils.getMarginLeft(element) + SizeUtils.getMarginRight(element);
734
return element.offsetWidth + margin;
735
}
736
737
export function getContentWidth(element: HTMLElement): number {
738
const border = SizeUtils.getBorderLeftWidth(element) + SizeUtils.getBorderRightWidth(element);
739
const padding = SizeUtils.getPaddingLeft(element) + SizeUtils.getPaddingRight(element);
740
return element.offsetWidth - border - padding;
741
}
742
743
export function getTotalScrollWidth(element: HTMLElement): number {
744
const margin = SizeUtils.getMarginLeft(element) + SizeUtils.getMarginRight(element);
745
return element.scrollWidth + margin;
746
}
747
748
// Adapted from WinJS
749
// Gets the height of the content of the specified element. The content height does not include borders or padding.
750
export function getContentHeight(element: HTMLElement): number {
751
const border = SizeUtils.getBorderTopWidth(element) + SizeUtils.getBorderBottomWidth(element);
752
const padding = SizeUtils.getPaddingTop(element) + SizeUtils.getPaddingBottom(element);
753
return element.offsetHeight - border - padding;
754
}
755
756
// Adapted from WinJS
757
// Gets the height of the element, including its margins.
758
export function getTotalHeight(element: HTMLElement): number {
759
const margin = SizeUtils.getMarginTop(element) + SizeUtils.getMarginBottom(element);
760
return element.offsetHeight + margin;
761
}
762
763
// Gets the left coordinate of the specified element relative to the specified parent.
764
function getRelativeLeft(element: HTMLElement, parent: HTMLElement): number {
765
if (element === null) {
766
return 0;
767
}
768
769
const elementPosition = getTopLeftOffset(element);
770
const parentPosition = getTopLeftOffset(parent);
771
return elementPosition.left - parentPosition.left;
772
}
773
774
export function getLargestChildWidth(parent: HTMLElement, children: HTMLElement[]): number {
775
const childWidths = children.map((child) => {
776
return Math.max(getTotalScrollWidth(child), getTotalWidth(child)) + getRelativeLeft(child, parent) || 0;
777
});
778
const maxWidth = Math.max(...childWidths);
779
return maxWidth;
780
}
781
782
// ----------------------------------------------------------------------------------------
783
784
export function isAncestor(testChild: Node | null, testAncestor: Node | null): boolean {
785
return Boolean(testAncestor?.contains(testChild));
786
}
787
788
const parentFlowToDataKey = 'parentFlowToElementId';
789
790
/**
791
* Set an explicit parent to use for nodes that are not part of the
792
* regular dom structure.
793
*/
794
export function setParentFlowTo(fromChildElement: HTMLElement, toParentElement: Element): void {
795
fromChildElement.dataset[parentFlowToDataKey] = toParentElement.id;
796
}
797
798
function getParentFlowToElement(node: HTMLElement): HTMLElement | null {
799
const flowToParentId = node.dataset[parentFlowToDataKey];
800
if (typeof flowToParentId === 'string') {
801
return node.ownerDocument.getElementById(flowToParentId);
802
}
803
return null;
804
}
805
806
/**
807
* Check if `testAncestor` is an ancestor of `testChild`, observing the explicit
808
* parents set by `setParentFlowTo`.
809
*/
810
export function isAncestorUsingFlowTo(testChild: Node, testAncestor: Node): boolean {
811
let node: Node | null = testChild;
812
while (node) {
813
if (node === testAncestor) {
814
return true;
815
}
816
817
if (isHTMLElement(node)) {
818
const flowToParentElement = getParentFlowToElement(node);
819
if (flowToParentElement) {
820
node = flowToParentElement;
821
continue;
822
}
823
}
824
node = node.parentNode;
825
}
826
827
return false;
828
}
829
830
export function findParentWithClass(node: HTMLElement, clazz: string, stopAtClazzOrNode?: string | HTMLElement): HTMLElement | null {
831
while (node && node.nodeType === node.ELEMENT_NODE) {
832
if (node.classList.contains(clazz)) {
833
return node;
834
}
835
836
if (stopAtClazzOrNode) {
837
if (typeof stopAtClazzOrNode === 'string') {
838
if (node.classList.contains(stopAtClazzOrNode)) {
839
return null;
840
}
841
} else {
842
if (node === stopAtClazzOrNode) {
843
return null;
844
}
845
}
846
}
847
848
node = <HTMLElement>node.parentNode;
849
}
850
851
return null;
852
}
853
854
export function hasParentWithClass(node: HTMLElement, clazz: string, stopAtClazzOrNode?: string | HTMLElement): boolean {
855
return !!findParentWithClass(node, clazz, stopAtClazzOrNode);
856
}
857
858
export function isShadowRoot(node: Node): node is ShadowRoot {
859
return (
860
node && !!(<ShadowRoot>node).host && !!(<ShadowRoot>node).mode
861
);
862
}
863
864
export function isInShadowDOM(domNode: Node): boolean {
865
return !!getShadowRoot(domNode);
866
}
867
868
export function getShadowRoot(domNode: Node): ShadowRoot | null {
869
while (domNode.parentNode) {
870
if (domNode === domNode.ownerDocument?.body) {
871
// reached the body
872
return null;
873
}
874
domNode = domNode.parentNode;
875
}
876
return isShadowRoot(domNode) ? domNode : null;
877
}
878
879
/**
880
* Returns the active element across all child windows
881
* based on document focus. Falls back to the main
882
* window if no window has focus.
883
*/
884
export function getActiveElement(): Element | null {
885
let result = getActiveDocument().activeElement;
886
887
while (result?.shadowRoot) {
888
result = result.shadowRoot.activeElement;
889
}
890
891
return result;
892
}
893
894
/**
895
* Returns true if the focused window active element matches
896
* the provided element. Falls back to the main window if no
897
* window has focus.
898
*/
899
export function isActiveElement(element: Element): boolean {
900
return getActiveElement() === element;
901
}
902
903
/**
904
* Returns true if the focused window active element is contained in
905
* `ancestor`. Falls back to the main window if no window has focus.
906
*/
907
export function isAncestorOfActiveElement(ancestor: Element): boolean {
908
return isAncestor(getActiveElement(), ancestor);
909
}
910
911
/**
912
* Returns whether the element is in the active `document`. The active
913
* document has focus or will be the main windows document.
914
*/
915
export function isActiveDocument(element: Element): boolean {
916
return element.ownerDocument === getActiveDocument();
917
}
918
919
/**
920
* Returns the active document across main and child windows.
921
* Prefers the window with focus, otherwise falls back to
922
* the main windows document.
923
*/
924
export function getActiveDocument(): Document {
925
if (getWindowsCount() <= 1) {
926
return mainWindow.document;
927
}
928
929
const documents = Array.from(getWindows()).map(({ window }) => window.document);
930
return documents.find(doc => doc.hasFocus()) ?? mainWindow.document;
931
}
932
933
/**
934
* Returns the active window across main and child windows.
935
* Prefers the window with focus, otherwise falls back to
936
* the main window.
937
*/
938
export function getActiveWindow(): CodeWindow {
939
const document = getActiveDocument();
940
return (document.defaultView?.window ?? mainWindow) as CodeWindow;
941
}
942
943
interface IMutationObserver {
944
users: number;
945
readonly observer: MutationObserver;
946
readonly onDidMutate: event.Event<MutationRecord[]>;
947
}
948
949
export const sharedMutationObserver = new class {
950
951
readonly mutationObservers = new Map<Node, Map<number, IMutationObserver>>();
952
953
observe(target: Node, disposables: DisposableStore, options?: MutationObserverInit): event.Event<MutationRecord[]> {
954
let mutationObserversPerTarget = this.mutationObservers.get(target);
955
if (!mutationObserversPerTarget) {
956
mutationObserversPerTarget = new Map<number, IMutationObserver>();
957
this.mutationObservers.set(target, mutationObserversPerTarget);
958
}
959
960
const optionsHash = hash(options);
961
let mutationObserverPerOptions = mutationObserversPerTarget.get(optionsHash);
962
if (!mutationObserverPerOptions) {
963
const onDidMutate = new event.Emitter<MutationRecord[]>();
964
const observer = new MutationObserver(mutations => onDidMutate.fire(mutations));
965
observer.observe(target, options);
966
967
const resolvedMutationObserverPerOptions = mutationObserverPerOptions = {
968
users: 1,
969
observer,
970
onDidMutate: onDidMutate.event
971
};
972
973
disposables.add(toDisposable(() => {
974
resolvedMutationObserverPerOptions.users -= 1;
975
976
if (resolvedMutationObserverPerOptions.users === 0) {
977
onDidMutate.dispose();
978
observer.disconnect();
979
980
mutationObserversPerTarget?.delete(optionsHash);
981
if (mutationObserversPerTarget?.size === 0) {
982
this.mutationObservers.delete(target);
983
}
984
}
985
}));
986
987
mutationObserversPerTarget.set(optionsHash, mutationObserverPerOptions);
988
} else {
989
mutationObserverPerOptions.users += 1;
990
}
991
992
return mutationObserverPerOptions.onDidMutate;
993
}
994
};
995
996
export function createMetaElement(container: HTMLElement = mainWindow.document.head): HTMLMetaElement {
997
return createHeadElement('meta', container) as HTMLMetaElement;
998
}
999
1000
export function createLinkElement(container: HTMLElement = mainWindow.document.head): HTMLLinkElement {
1001
return createHeadElement('link', container) as HTMLLinkElement;
1002
}
1003
1004
function createHeadElement(tagName: string, container: HTMLElement = mainWindow.document.head): HTMLElement {
1005
const element = document.createElement(tagName);
1006
container.appendChild(element);
1007
return element;
1008
}
1009
1010
export function isHTMLElement(e: unknown): e is HTMLElement {
1011
// eslint-disable-next-line no-restricted-syntax
1012
return e instanceof HTMLElement || e instanceof getWindow(e as Node).HTMLElement;
1013
}
1014
1015
export function isHTMLAnchorElement(e: unknown): e is HTMLAnchorElement {
1016
// eslint-disable-next-line no-restricted-syntax
1017
return e instanceof HTMLAnchorElement || e instanceof getWindow(e as Node).HTMLAnchorElement;
1018
}
1019
1020
export function isHTMLSpanElement(e: unknown): e is HTMLSpanElement {
1021
// eslint-disable-next-line no-restricted-syntax
1022
return e instanceof HTMLSpanElement || e instanceof getWindow(e as Node).HTMLSpanElement;
1023
}
1024
1025
export function isHTMLTextAreaElement(e: unknown): e is HTMLTextAreaElement {
1026
// eslint-disable-next-line no-restricted-syntax
1027
return e instanceof HTMLTextAreaElement || e instanceof getWindow(e as Node).HTMLTextAreaElement;
1028
}
1029
1030
export function isHTMLInputElement(e: unknown): e is HTMLInputElement {
1031
// eslint-disable-next-line no-restricted-syntax
1032
return e instanceof HTMLInputElement || e instanceof getWindow(e as Node).HTMLInputElement;
1033
}
1034
1035
export function isHTMLButtonElement(e: unknown): e is HTMLButtonElement {
1036
// eslint-disable-next-line no-restricted-syntax
1037
return e instanceof HTMLButtonElement || e instanceof getWindow(e as Node).HTMLButtonElement;
1038
}
1039
1040
export function isHTMLDivElement(e: unknown): e is HTMLDivElement {
1041
// eslint-disable-next-line no-restricted-syntax
1042
return e instanceof HTMLDivElement || e instanceof getWindow(e as Node).HTMLDivElement;
1043
}
1044
1045
export function isSVGElement(e: unknown): e is SVGElement {
1046
// eslint-disable-next-line no-restricted-syntax
1047
return e instanceof SVGElement || e instanceof getWindow(e as Node).SVGElement;
1048
}
1049
1050
export function isMouseEvent(e: unknown): e is MouseEvent {
1051
// eslint-disable-next-line no-restricted-syntax
1052
return e instanceof MouseEvent || e instanceof getWindow(e as UIEvent).MouseEvent;
1053
}
1054
1055
export function isKeyboardEvent(e: unknown): e is KeyboardEvent {
1056
// eslint-disable-next-line no-restricted-syntax
1057
return e instanceof KeyboardEvent || e instanceof getWindow(e as UIEvent).KeyboardEvent;
1058
}
1059
1060
export function isPointerEvent(e: unknown): e is PointerEvent {
1061
// eslint-disable-next-line no-restricted-syntax
1062
return e instanceof PointerEvent || e instanceof getWindow(e as UIEvent).PointerEvent;
1063
}
1064
1065
export function isDragEvent(e: unknown): e is DragEvent {
1066
// eslint-disable-next-line no-restricted-syntax
1067
return e instanceof DragEvent || e instanceof getWindow(e as UIEvent).DragEvent;
1068
}
1069
1070
export const EventType = {
1071
// Mouse
1072
CLICK: 'click',
1073
AUXCLICK: 'auxclick',
1074
DBLCLICK: 'dblclick',
1075
MOUSE_UP: 'mouseup',
1076
MOUSE_DOWN: 'mousedown',
1077
MOUSE_OVER: 'mouseover',
1078
MOUSE_MOVE: 'mousemove',
1079
MOUSE_OUT: 'mouseout',
1080
MOUSE_ENTER: 'mouseenter',
1081
MOUSE_LEAVE: 'mouseleave',
1082
MOUSE_WHEEL: 'wheel',
1083
POINTER_UP: 'pointerup',
1084
POINTER_DOWN: 'pointerdown',
1085
POINTER_MOVE: 'pointermove',
1086
POINTER_LEAVE: 'pointerleave',
1087
CONTEXT_MENU: 'contextmenu',
1088
WHEEL: 'wheel',
1089
// Keyboard
1090
KEY_DOWN: 'keydown',
1091
KEY_PRESS: 'keypress',
1092
KEY_UP: 'keyup',
1093
// HTML Document
1094
LOAD: 'load',
1095
BEFORE_UNLOAD: 'beforeunload',
1096
UNLOAD: 'unload',
1097
PAGE_SHOW: 'pageshow',
1098
PAGE_HIDE: 'pagehide',
1099
PASTE: 'paste',
1100
ABORT: 'abort',
1101
ERROR: 'error',
1102
RESIZE: 'resize',
1103
SCROLL: 'scroll',
1104
FULLSCREEN_CHANGE: 'fullscreenchange',
1105
WK_FULLSCREEN_CHANGE: 'webkitfullscreenchange',
1106
// Form
1107
SELECT: 'select',
1108
CHANGE: 'change',
1109
SUBMIT: 'submit',
1110
RESET: 'reset',
1111
FOCUS: 'focus',
1112
FOCUS_IN: 'focusin',
1113
FOCUS_OUT: 'focusout',
1114
BLUR: 'blur',
1115
INPUT: 'input',
1116
// Local Storage
1117
STORAGE: 'storage',
1118
// Drag
1119
DRAG_START: 'dragstart',
1120
DRAG: 'drag',
1121
DRAG_ENTER: 'dragenter',
1122
DRAG_LEAVE: 'dragleave',
1123
DRAG_OVER: 'dragover',
1124
DROP: 'drop',
1125
DRAG_END: 'dragend',
1126
// Animation
1127
ANIMATION_START: browser.isWebKit ? 'webkitAnimationStart' : 'animationstart',
1128
ANIMATION_END: browser.isWebKit ? 'webkitAnimationEnd' : 'animationend',
1129
ANIMATION_ITERATION: browser.isWebKit ? 'webkitAnimationIteration' : 'animationiteration'
1130
} as const;
1131
1132
export interface EventLike {
1133
preventDefault(): void;
1134
stopPropagation(): void;
1135
}
1136
1137
export function isEventLike(obj: unknown): obj is EventLike {
1138
const candidate = obj as EventLike | undefined;
1139
1140
return !!(candidate && typeof candidate.preventDefault === 'function' && typeof candidate.stopPropagation === 'function');
1141
}
1142
1143
export const EventHelper = {
1144
stop: <T extends EventLike>(e: T, cancelBubble?: boolean): T => {
1145
e.preventDefault();
1146
if (cancelBubble) {
1147
e.stopPropagation();
1148
}
1149
return e;
1150
}
1151
};
1152
1153
export interface IFocusTracker extends Disposable {
1154
readonly onDidFocus: event.Event<void>;
1155
readonly onDidBlur: event.Event<void>;
1156
refreshState(): void;
1157
}
1158
1159
export function saveParentsScrollTop(node: Element): number[] {
1160
const r: number[] = [];
1161
for (let i = 0; node && node.nodeType === node.ELEMENT_NODE; i++) {
1162
r[i] = node.scrollTop;
1163
node = <Element>node.parentNode;
1164
}
1165
return r;
1166
}
1167
1168
export function restoreParentsScrollTop(node: Element, state: number[]): void {
1169
for (let i = 0; node && node.nodeType === node.ELEMENT_NODE; i++) {
1170
if (node.scrollTop !== state[i]) {
1171
node.scrollTop = state[i];
1172
}
1173
node = <Element>node.parentNode;
1174
}
1175
}
1176
1177
class FocusTracker extends Disposable implements IFocusTracker {
1178
1179
private readonly _onDidFocus = this._register(new event.Emitter<void>());
1180
get onDidFocus() { return this._onDidFocus.event; }
1181
1182
private readonly _onDidBlur = this._register(new event.Emitter<void>());
1183
get onDidBlur() { return this._onDidBlur.event; }
1184
1185
private _refreshStateHandler: () => void;
1186
1187
private static hasFocusWithin(element: HTMLElement | Window): boolean {
1188
if (isHTMLElement(element)) {
1189
const shadowRoot = getShadowRoot(element);
1190
const activeElement = (shadowRoot ? shadowRoot.activeElement : element.ownerDocument.activeElement);
1191
return isAncestor(activeElement, element);
1192
} else {
1193
const window = element;
1194
return isAncestor(window.document.activeElement, window.document);
1195
}
1196
}
1197
1198
constructor(element: HTMLElement | Window) {
1199
super();
1200
let hasFocus = FocusTracker.hasFocusWithin(element);
1201
let loosingFocus = false;
1202
1203
const onFocus = () => {
1204
loosingFocus = false;
1205
if (!hasFocus) {
1206
hasFocus = true;
1207
this._onDidFocus.fire();
1208
}
1209
};
1210
1211
const onBlur = () => {
1212
if (hasFocus) {
1213
loosingFocus = true;
1214
(isHTMLElement(element) ? getWindow(element) : element).setTimeout(() => {
1215
if (loosingFocus) {
1216
loosingFocus = false;
1217
hasFocus = false;
1218
this._onDidBlur.fire();
1219
}
1220
}, 0);
1221
}
1222
};
1223
1224
this._refreshStateHandler = () => {
1225
const currentNodeHasFocus = FocusTracker.hasFocusWithin(<HTMLElement>element);
1226
if (currentNodeHasFocus !== hasFocus) {
1227
if (hasFocus) {
1228
onBlur();
1229
} else {
1230
onFocus();
1231
}
1232
}
1233
};
1234
1235
this._register(addDisposableListener(element, EventType.FOCUS, onFocus, true));
1236
this._register(addDisposableListener(element, EventType.BLUR, onBlur, true));
1237
if (isHTMLElement(element)) {
1238
this._register(addDisposableListener(element, EventType.FOCUS_IN, () => this._refreshStateHandler()));
1239
this._register(addDisposableListener(element, EventType.FOCUS_OUT, () => this._refreshStateHandler()));
1240
}
1241
1242
}
1243
1244
refreshState() {
1245
this._refreshStateHandler();
1246
}
1247
}
1248
1249
/**
1250
* Creates a new `IFocusTracker` instance that tracks focus changes on the given `element` and its descendants.
1251
*
1252
* @param element The `HTMLElement` or `Window` to track focus changes on.
1253
* @returns An `IFocusTracker` instance.
1254
*/
1255
export function trackFocus(element: HTMLElement | Window): IFocusTracker {
1256
return new FocusTracker(element);
1257
}
1258
1259
export function after<T extends Node>(sibling: HTMLElement, child: T): T {
1260
sibling.after(child);
1261
return child;
1262
}
1263
1264
export function append<T extends Node>(parent: HTMLElement, child: T): T;
1265
export function append<T extends Node>(parent: HTMLElement, ...children: (T | string)[]): void;
1266
export function append<T extends Node>(parent: HTMLElement, ...children: (T | string)[]): T | void {
1267
parent.append(...children);
1268
if (children.length === 1 && typeof children[0] !== 'string') {
1269
return <T>children[0];
1270
}
1271
}
1272
1273
export function prepend<T extends Node>(parent: HTMLElement, child: T): T {
1274
parent.insertBefore(child, parent.firstChild);
1275
return child;
1276
}
1277
1278
/**
1279
* Removes all children from `parent` and appends `children`
1280
*/
1281
export function reset(parent: HTMLElement, ...children: Array<Node | string>): void {
1282
parent.textContent = '';
1283
append(parent, ...children);
1284
}
1285
1286
const SELECTOR_REGEX = /([\w\-]+)?(#([\w\-]+))?((\.([\w\-]+))*)/;
1287
1288
export enum Namespace {
1289
HTML = 'http://www.w3.org/1999/xhtml',
1290
SVG = 'http://www.w3.org/2000/svg'
1291
}
1292
1293
function _$<T extends Element>(namespace: Namespace, description: string, attrs?: { [key: string]: any }, ...children: Array<Node | string>): T {
1294
const match = SELECTOR_REGEX.exec(description);
1295
1296
if (!match) {
1297
throw new Error('Bad use of emmet');
1298
}
1299
1300
const tagName = match[1] || 'div';
1301
let result: T;
1302
1303
if (namespace !== Namespace.HTML) {
1304
result = document.createElementNS(namespace as string, tagName) as T;
1305
} else {
1306
result = document.createElement(tagName) as unknown as T;
1307
}
1308
1309
if (match[3]) {
1310
result.id = match[3];
1311
}
1312
if (match[4]) {
1313
result.className = match[4].replace(/\./g, ' ').trim();
1314
}
1315
1316
if (attrs) {
1317
Object.entries(attrs).forEach(([name, value]) => {
1318
if (typeof value === 'undefined') {
1319
return;
1320
}
1321
1322
if (/^on\w+$/.test(name)) {
1323
(<any>result)[name] = value;
1324
} else if (name === 'selected') {
1325
if (value) {
1326
result.setAttribute(name, 'true');
1327
}
1328
1329
} else {
1330
result.setAttribute(name, value);
1331
}
1332
});
1333
}
1334
1335
result.append(...children);
1336
1337
return result as T;
1338
}
1339
1340
export function $<T extends HTMLElement>(description: string, attrs?: { [key: string]: any }, ...children: Array<Node | string>): T {
1341
return _$(Namespace.HTML, description, attrs, ...children);
1342
}
1343
1344
$.SVG = function <T extends SVGElement>(description: string, attrs?: { [key: string]: any }, ...children: Array<Node | string>): T {
1345
return _$(Namespace.SVG, description, attrs, ...children);
1346
};
1347
1348
export function join(nodes: Node[], separator: Node | string): Node[] {
1349
const result: Node[] = [];
1350
1351
nodes.forEach((node, index) => {
1352
if (index > 0) {
1353
if (separator instanceof Node) {
1354
result.push(separator.cloneNode());
1355
} else {
1356
result.push(document.createTextNode(separator));
1357
}
1358
}
1359
1360
result.push(node);
1361
});
1362
1363
return result;
1364
}
1365
1366
export function setVisibility(visible: boolean, ...elements: HTMLElement[]): void {
1367
if (visible) {
1368
show(...elements);
1369
} else {
1370
hide(...elements);
1371
}
1372
}
1373
1374
export function show(...elements: HTMLElement[]): void {
1375
for (const element of elements) {
1376
element.style.display = '';
1377
element.removeAttribute('aria-hidden');
1378
}
1379
}
1380
1381
export function hide(...elements: HTMLElement[]): void {
1382
for (const element of elements) {
1383
element.style.display = 'none';
1384
element.setAttribute('aria-hidden', 'true');
1385
}
1386
}
1387
1388
function findParentWithAttribute(node: Node | null, attribute: string): HTMLElement | null {
1389
while (node && node.nodeType === node.ELEMENT_NODE) {
1390
if (isHTMLElement(node) && node.hasAttribute(attribute)) {
1391
return node;
1392
}
1393
1394
node = node.parentNode;
1395
}
1396
1397
return null;
1398
}
1399
1400
export function removeTabIndexAndUpdateFocus(node: HTMLElement): void {
1401
if (!node || !node.hasAttribute('tabIndex')) {
1402
return;
1403
}
1404
1405
// If we are the currently focused element and tabIndex is removed,
1406
// standard DOM behavior is to move focus to the <body> element. We
1407
// typically never want that, rather put focus to the closest element
1408
// in the hierarchy of the parent DOM nodes.
1409
if (node.ownerDocument.activeElement === node) {
1410
const parentFocusable = findParentWithAttribute(node.parentElement, 'tabIndex');
1411
parentFocusable?.focus();
1412
}
1413
1414
node.removeAttribute('tabindex');
1415
}
1416
1417
export function finalHandler<T extends Event>(fn: (event: T) => unknown): (event: T) => unknown {
1418
return e => {
1419
e.preventDefault();
1420
e.stopPropagation();
1421
fn(e);
1422
};
1423
}
1424
1425
export function domContentLoaded(targetWindow: Window): Promise<void> {
1426
return new Promise<void>(resolve => {
1427
const readyState = targetWindow.document.readyState;
1428
if (readyState === 'complete' || (targetWindow.document && targetWindow.document.body !== null)) {
1429
resolve(undefined);
1430
} else {
1431
const listener = () => {
1432
targetWindow.window.removeEventListener('DOMContentLoaded', listener, false);
1433
resolve();
1434
};
1435
1436
targetWindow.window.addEventListener('DOMContentLoaded', listener, false);
1437
}
1438
});
1439
}
1440
1441
/**
1442
* Find a value usable for a dom node size such that the likelihood that it would be
1443
* displayed with constant screen pixels size is as high as possible.
1444
*
1445
* e.g. We would desire for the cursors to be 2px (CSS px) wide. Under a devicePixelRatio
1446
* of 1.25, the cursor will be 2.5 screen pixels wide. Depending on how the dom node aligns/"snaps"
1447
* with the screen pixels, it will sometimes be rendered with 2 screen pixels, and sometimes with 3 screen pixels.
1448
*/
1449
export function computeScreenAwareSize(window: Window, cssPx: number): number {
1450
const screenPx = window.devicePixelRatio * cssPx;
1451
return Math.max(1, Math.floor(screenPx)) / window.devicePixelRatio;
1452
}
1453
1454
/**
1455
* Open safely a new window. This is the best way to do so, but you cannot tell
1456
* if the window was opened or if it was blocked by the browser's popup blocker.
1457
* If you want to tell if the browser blocked the new window, use {@link windowOpenWithSuccess}.
1458
*
1459
* See https://github.com/microsoft/monaco-editor/issues/601
1460
* To protect against malicious code in the linked site, particularly phishing attempts,
1461
* the window.opener should be set to null to prevent the linked site from having access
1462
* to change the location of the current page.
1463
* See https://mathiasbynens.github.io/rel-noopener/
1464
*/
1465
export function windowOpenNoOpener(url: string): void {
1466
// By using 'noopener' in the `windowFeatures` argument, the newly created window will
1467
// not be able to use `window.opener` to reach back to the current page.
1468
// See https://stackoverflow.com/a/46958731
1469
// See https://developer.mozilla.org/en-US/docs/Web/API/Window/open#noopener
1470
// However, this also doesn't allow us to realize if the browser blocked
1471
// the creation of the window.
1472
mainWindow.open(url, '_blank', 'noopener');
1473
}
1474
1475
/**
1476
* Open a new window in a popup. This is the best way to do so, but you cannot tell
1477
* if the window was opened or if it was blocked by the browser's popup blocker.
1478
* If you want to tell if the browser blocked the new window, use {@link windowOpenWithSuccess}.
1479
*
1480
* Note: this does not set {@link window.opener} to null. This is to allow the opened popup to
1481
* be able to use {@link window.close} to close itself. Because of this, you should only use
1482
* this function on urls that you trust.
1483
*
1484
* In otherwords, you should almost always use {@link windowOpenNoOpener} instead of this function.
1485
*/
1486
const popupWidth = 780, popupHeight = 640;
1487
export function windowOpenPopup(url: string): void {
1488
const left = Math.floor(mainWindow.screenLeft + mainWindow.innerWidth / 2 - popupWidth / 2);
1489
const top = Math.floor(mainWindow.screenTop + mainWindow.innerHeight / 2 - popupHeight / 2);
1490
mainWindow.open(
1491
url,
1492
'_blank',
1493
`width=${popupWidth},height=${popupHeight},top=${top},left=${left}`
1494
);
1495
}
1496
1497
/**
1498
* Attempts to open a window and returns whether it succeeded. This technique is
1499
* not appropriate in certain contexts, like for example when the JS context is
1500
* executing inside a sandboxed iframe. If it is not necessary to know if the
1501
* browser blocked the new window, use {@link windowOpenNoOpener}.
1502
*
1503
* See https://github.com/microsoft/monaco-editor/issues/601
1504
* See https://github.com/microsoft/monaco-editor/issues/2474
1505
* See https://mathiasbynens.github.io/rel-noopener/
1506
*
1507
* @param url the url to open
1508
* @param noOpener whether or not to set the {@link window.opener} to null. You should leave the default
1509
* (true) unless you trust the url that is being opened.
1510
* @returns boolean indicating if the {@link window.open} call succeeded
1511
*/
1512
export function windowOpenWithSuccess(url: string, noOpener = true): boolean {
1513
const newTab = mainWindow.open();
1514
if (newTab) {
1515
if (noOpener) {
1516
// see `windowOpenNoOpener` for details on why this is important
1517
(newTab as any).opener = null;
1518
}
1519
newTab.location.href = url;
1520
return true;
1521
}
1522
return false;
1523
}
1524
1525
export function animate(targetWindow: Window, fn: () => void): IDisposable {
1526
const step = () => {
1527
fn();
1528
stepDisposable = scheduleAtNextAnimationFrame(targetWindow, step);
1529
};
1530
1531
let stepDisposable = scheduleAtNextAnimationFrame(targetWindow, step);
1532
return toDisposable(() => stepDisposable.dispose());
1533
}
1534
1535
RemoteAuthorities.setPreferredWebSchema(/^https:/.test(mainWindow.location.href) ? 'https' : 'http');
1536
1537
export function triggerDownload(dataOrUri: Uint8Array | URI, name: string): void {
1538
1539
// If the data is provided as Buffer, we create a
1540
// blob URL out of it to produce a valid link
1541
let url: string;
1542
if (URI.isUri(dataOrUri)) {
1543
url = dataOrUri.toString(true);
1544
} else {
1545
const blob = new Blob([dataOrUri as Uint8Array<ArrayBuffer>]);
1546
url = URL.createObjectURL(blob);
1547
1548
// Ensure to free the data from DOM eventually
1549
setTimeout(() => URL.revokeObjectURL(url));
1550
}
1551
1552
// In order to download from the browser, the only way seems
1553
// to be creating a <a> element with download attribute that
1554
// points to the file to download.
1555
// See also https://developers.google.com/web/updates/2011/08/Downloading-resources-in-HTML5-a-download
1556
const activeWindow = getActiveWindow();
1557
const anchor = document.createElement('a');
1558
activeWindow.document.body.appendChild(anchor);
1559
anchor.download = name;
1560
anchor.href = url;
1561
anchor.click();
1562
1563
// Ensure to remove the element from DOM eventually
1564
setTimeout(() => anchor.remove());
1565
}
1566
1567
export function triggerUpload(): Promise<FileList | undefined> {
1568
return new Promise<FileList | undefined>(resolve => {
1569
1570
// In order to upload to the browser, create a
1571
// input element of type `file` and click it
1572
// to gather the selected files
1573
const activeWindow = getActiveWindow();
1574
const input = document.createElement('input');
1575
activeWindow.document.body.appendChild(input);
1576
input.type = 'file';
1577
input.multiple = true;
1578
1579
// Resolve once the input event has fired once
1580
event.Event.once(event.Event.fromDOMEventEmitter(input, 'input'))(() => {
1581
resolve(input.files ?? undefined);
1582
});
1583
1584
input.click();
1585
1586
// Ensure to remove the element from DOM eventually
1587
setTimeout(() => input.remove());
1588
});
1589
}
1590
1591
export interface INotification extends IDisposable {
1592
readonly onClick: event.Event<void>;
1593
}
1594
1595
export async function triggerNotification(message: string, options?: { detail?: string; sticky?: boolean }): Promise<INotification | undefined> {
1596
const permission = await Notification.requestPermission();
1597
if (permission !== 'granted') {
1598
return;
1599
}
1600
1601
const disposables = new DisposableStore();
1602
1603
const notification = new Notification(message, {
1604
body: options?.detail,
1605
requireInteraction: options?.sticky
1606
});
1607
1608
const onClick = new event.Emitter<void>();
1609
disposables.add(addDisposableListener(notification, 'click', () => onClick.fire()));
1610
disposables.add(addDisposableListener(notification, 'close', () => disposables.dispose()));
1611
1612
disposables.add(toDisposable(() => notification.close()));
1613
1614
return {
1615
onClick: onClick.event,
1616
dispose: () => disposables.dispose()
1617
};
1618
}
1619
1620
export enum DetectedFullscreenMode {
1621
1622
/**
1623
* The document is fullscreen, e.g. because an element
1624
* in the document requested to be fullscreen.
1625
*/
1626
DOCUMENT = 1,
1627
1628
/**
1629
* The browser is fullscreen, e.g. because the user enabled
1630
* native window fullscreen for it.
1631
*/
1632
BROWSER
1633
}
1634
1635
export interface IDetectedFullscreen {
1636
1637
/**
1638
* Figure out if the document is fullscreen or the browser.
1639
*/
1640
mode: DetectedFullscreenMode;
1641
1642
/**
1643
* Whether we know for sure that we are in fullscreen mode or
1644
* it is a guess.
1645
*/
1646
guess: boolean;
1647
}
1648
1649
export function detectFullscreen(targetWindow: Window): IDetectedFullscreen | null {
1650
1651
// Browser fullscreen: use DOM APIs to detect
1652
if (targetWindow.document.fullscreenElement || (<any>targetWindow.document).webkitFullscreenElement || (<any>targetWindow.document).webkitIsFullScreen) {
1653
return { mode: DetectedFullscreenMode.DOCUMENT, guess: false };
1654
}
1655
1656
// There is no standard way to figure out if the browser
1657
// is using native fullscreen. Via checking on screen
1658
// height and comparing that to window height, we can guess
1659
// it though.
1660
1661
if (targetWindow.innerHeight === targetWindow.screen.height) {
1662
// if the height of the window matches the screen height, we can
1663
// safely assume that the browser is fullscreen because no browser
1664
// chrome is taking height away (e.g. like toolbars).
1665
return { mode: DetectedFullscreenMode.BROWSER, guess: false };
1666
}
1667
1668
if (platform.isMacintosh || platform.isLinux) {
1669
// macOS and Linux do not properly report `innerHeight`, only Windows does
1670
if (targetWindow.outerHeight === targetWindow.screen.height && targetWindow.outerWidth === targetWindow.screen.width) {
1671
// if the height of the browser matches the screen height, we can
1672
// only guess that we are in fullscreen. It is also possible that
1673
// the user has turned off taskbars in the OS and the browser is
1674
// simply able to span the entire size of the screen.
1675
return { mode: DetectedFullscreenMode.BROWSER, guess: true };
1676
}
1677
}
1678
1679
// Not in fullscreen
1680
return null;
1681
}
1682
1683
type ModifierKey = 'alt' | 'ctrl' | 'shift' | 'meta';
1684
1685
export interface IModifierKeyStatus {
1686
altKey: boolean;
1687
shiftKey: boolean;
1688
ctrlKey: boolean;
1689
metaKey: boolean;
1690
lastKeyPressed?: ModifierKey;
1691
lastKeyReleased?: ModifierKey;
1692
event?: KeyboardEvent;
1693
}
1694
1695
export class ModifierKeyEmitter extends event.Emitter<IModifierKeyStatus> {
1696
1697
private readonly _subscriptions = new DisposableStore();
1698
private _keyStatus: IModifierKeyStatus;
1699
private static instance: ModifierKeyEmitter | undefined;
1700
1701
private constructor() {
1702
super();
1703
1704
this._keyStatus = {
1705
altKey: false,
1706
shiftKey: false,
1707
ctrlKey: false,
1708
metaKey: false
1709
};
1710
1711
this._subscriptions.add(event.Event.runAndSubscribe(onDidRegisterWindow, ({ window, disposables }) => this.registerListeners(window, disposables), { window: mainWindow, disposables: this._subscriptions }));
1712
}
1713
1714
private registerListeners(window: Window, disposables: DisposableStore): void {
1715
disposables.add(addDisposableListener(window, 'keydown', e => {
1716
if (e.defaultPrevented) {
1717
return;
1718
}
1719
1720
const event = new StandardKeyboardEvent(e);
1721
// If Alt-key keydown event is repeated, ignore it #112347
1722
// Only known to be necessary for Alt-Key at the moment #115810
1723
if (event.keyCode === KeyCode.Alt && e.repeat) {
1724
return;
1725
}
1726
1727
if (e.altKey && !this._keyStatus.altKey) {
1728
this._keyStatus.lastKeyPressed = 'alt';
1729
} else if (e.ctrlKey && !this._keyStatus.ctrlKey) {
1730
this._keyStatus.lastKeyPressed = 'ctrl';
1731
} else if (e.metaKey && !this._keyStatus.metaKey) {
1732
this._keyStatus.lastKeyPressed = 'meta';
1733
} else if (e.shiftKey && !this._keyStatus.shiftKey) {
1734
this._keyStatus.lastKeyPressed = 'shift';
1735
} else if (event.keyCode !== KeyCode.Alt) {
1736
this._keyStatus.lastKeyPressed = undefined;
1737
} else {
1738
return;
1739
}
1740
1741
this._keyStatus.altKey = e.altKey;
1742
this._keyStatus.ctrlKey = e.ctrlKey;
1743
this._keyStatus.metaKey = e.metaKey;
1744
this._keyStatus.shiftKey = e.shiftKey;
1745
1746
if (this._keyStatus.lastKeyPressed) {
1747
this._keyStatus.event = e;
1748
this.fire(this._keyStatus);
1749
}
1750
}, true));
1751
1752
disposables.add(addDisposableListener(window, 'keyup', e => {
1753
if (e.defaultPrevented) {
1754
return;
1755
}
1756
1757
if (!e.altKey && this._keyStatus.altKey) {
1758
this._keyStatus.lastKeyReleased = 'alt';
1759
} else if (!e.ctrlKey && this._keyStatus.ctrlKey) {
1760
this._keyStatus.lastKeyReleased = 'ctrl';
1761
} else if (!e.metaKey && this._keyStatus.metaKey) {
1762
this._keyStatus.lastKeyReleased = 'meta';
1763
} else if (!e.shiftKey && this._keyStatus.shiftKey) {
1764
this._keyStatus.lastKeyReleased = 'shift';
1765
} else {
1766
this._keyStatus.lastKeyReleased = undefined;
1767
}
1768
1769
if (this._keyStatus.lastKeyPressed !== this._keyStatus.lastKeyReleased) {
1770
this._keyStatus.lastKeyPressed = undefined;
1771
}
1772
1773
this._keyStatus.altKey = e.altKey;
1774
this._keyStatus.ctrlKey = e.ctrlKey;
1775
this._keyStatus.metaKey = e.metaKey;
1776
this._keyStatus.shiftKey = e.shiftKey;
1777
1778
if (this._keyStatus.lastKeyReleased) {
1779
this._keyStatus.event = e;
1780
this.fire(this._keyStatus);
1781
}
1782
}, true));
1783
1784
disposables.add(addDisposableListener(window.document.body, 'mousedown', () => {
1785
this._keyStatus.lastKeyPressed = undefined;
1786
}, true));
1787
1788
disposables.add(addDisposableListener(window.document.body, 'mouseup', () => {
1789
this._keyStatus.lastKeyPressed = undefined;
1790
}, true));
1791
1792
disposables.add(addDisposableListener(window.document.body, 'mousemove', e => {
1793
if (e.buttons) {
1794
this._keyStatus.lastKeyPressed = undefined;
1795
}
1796
}, true));
1797
1798
disposables.add(addDisposableListener(window, 'blur', () => {
1799
this.resetKeyStatus();
1800
}));
1801
}
1802
1803
get keyStatus(): IModifierKeyStatus {
1804
return this._keyStatus;
1805
}
1806
1807
get isModifierPressed(): boolean {
1808
return this._keyStatus.altKey || this._keyStatus.ctrlKey || this._keyStatus.metaKey || this._keyStatus.shiftKey;
1809
}
1810
1811
/**
1812
* Allows to explicitly reset the key status based on more knowledge (#109062)
1813
*/
1814
resetKeyStatus(): void {
1815
this.doResetKeyStatus();
1816
this.fire(this._keyStatus);
1817
}
1818
1819
private doResetKeyStatus(): void {
1820
this._keyStatus = {
1821
altKey: false,
1822
shiftKey: false,
1823
ctrlKey: false,
1824
metaKey: false
1825
};
1826
}
1827
1828
static getInstance() {
1829
if (!ModifierKeyEmitter.instance) {
1830
ModifierKeyEmitter.instance = new ModifierKeyEmitter();
1831
}
1832
1833
return ModifierKeyEmitter.instance;
1834
}
1835
1836
static disposeInstance() {
1837
if (ModifierKeyEmitter.instance) {
1838
ModifierKeyEmitter.instance.dispose();
1839
ModifierKeyEmitter.instance = undefined;
1840
}
1841
}
1842
1843
override dispose() {
1844
super.dispose();
1845
this._subscriptions.dispose();
1846
}
1847
}
1848
1849
export function getCookieValue(name: string): string | undefined {
1850
const match = document.cookie.match('(^|[^;]+)\\s*' + name + '\\s*=\\s*([^;]+)'); // See https://stackoverflow.com/a/25490531
1851
1852
return match ? match.pop() : undefined;
1853
}
1854
1855
export interface IDragAndDropObserverCallbacks {
1856
readonly onDragEnter?: (e: DragEvent) => void;
1857
readonly onDragLeave?: (e: DragEvent) => void;
1858
readonly onDrop?: (e: DragEvent) => void;
1859
readonly onDragEnd?: (e: DragEvent) => void;
1860
readonly onDragStart?: (e: DragEvent) => void;
1861
readonly onDrag?: (e: DragEvent) => void;
1862
readonly onDragOver?: (e: DragEvent, dragDuration: number) => void;
1863
}
1864
1865
export class DragAndDropObserver extends Disposable {
1866
1867
// A helper to fix issues with repeated DRAG_ENTER / DRAG_LEAVE
1868
// calls see https://github.com/microsoft/vscode/issues/14470
1869
// when the element has child elements where the events are fired
1870
// repeadedly.
1871
private counter: number = 0;
1872
1873
// Allows to measure the duration of the drag operation.
1874
private dragStartTime = 0;
1875
1876
constructor(private readonly element: HTMLElement, private readonly callbacks: IDragAndDropObserverCallbacks) {
1877
super();
1878
1879
this.registerListeners();
1880
}
1881
1882
private registerListeners(): void {
1883
if (this.callbacks.onDragStart) {
1884
this._register(addDisposableListener(this.element, EventType.DRAG_START, (e: DragEvent) => {
1885
this.callbacks.onDragStart?.(e);
1886
}));
1887
}
1888
1889
if (this.callbacks.onDrag) {
1890
this._register(addDisposableListener(this.element, EventType.DRAG, (e: DragEvent) => {
1891
this.callbacks.onDrag?.(e);
1892
}));
1893
}
1894
1895
this._register(addDisposableListener(this.element, EventType.DRAG_ENTER, (e: DragEvent) => {
1896
this.counter++;
1897
this.dragStartTime = e.timeStamp;
1898
1899
this.callbacks.onDragEnter?.(e);
1900
}));
1901
1902
this._register(addDisposableListener(this.element, EventType.DRAG_OVER, (e: DragEvent) => {
1903
e.preventDefault(); // needed so that the drop event fires (https://stackoverflow.com/questions/21339924/drop-event-not-firing-in-chrome)
1904
1905
this.callbacks.onDragOver?.(e, e.timeStamp - this.dragStartTime);
1906
}));
1907
1908
this._register(addDisposableListener(this.element, EventType.DRAG_LEAVE, (e: DragEvent) => {
1909
this.counter--;
1910
1911
if (this.counter === 0) {
1912
this.dragStartTime = 0;
1913
1914
this.callbacks.onDragLeave?.(e);
1915
}
1916
}));
1917
1918
this._register(addDisposableListener(this.element, EventType.DRAG_END, (e: DragEvent) => {
1919
this.counter = 0;
1920
this.dragStartTime = 0;
1921
1922
this.callbacks.onDragEnd?.(e);
1923
}));
1924
1925
this._register(addDisposableListener(this.element, EventType.DROP, (e: DragEvent) => {
1926
this.counter = 0;
1927
this.dragStartTime = 0;
1928
1929
this.callbacks.onDrop?.(e);
1930
}));
1931
}
1932
}
1933
1934
type HTMLElementAttributeKeys<T> = Partial<{ [K in keyof T]: T[K] extends Function ? never : T[K] extends object ? HTMLElementAttributeKeys<T[K]> : T[K] }>;
1935
type ElementAttributes<T> = HTMLElementAttributeKeys<T> & Record<string, any>;
1936
type RemoveHTMLElement<T> = T extends HTMLElement ? never : T;
1937
type UnionToIntersection<U> = (U extends any ? (k: U) => void : never) extends ((k: infer I) => void) ? I : never;
1938
type ArrayToObj<T extends readonly any[]> = UnionToIntersection<RemoveHTMLElement<T[number]>>;
1939
type HHTMLElementTagNameMap = HTMLElementTagNameMap & { '': HTMLDivElement };
1940
1941
type TagToElement<T> = T extends `${infer TStart}#${string}`
1942
? TStart extends keyof HHTMLElementTagNameMap
1943
? HHTMLElementTagNameMap[TStart]
1944
: HTMLElement
1945
: T extends `${infer TStart}.${string}`
1946
? TStart extends keyof HHTMLElementTagNameMap
1947
? HHTMLElementTagNameMap[TStart]
1948
: HTMLElement
1949
: T extends keyof HTMLElementTagNameMap
1950
? HTMLElementTagNameMap[T]
1951
: HTMLElement;
1952
1953
type TagToElementAndId<TTag> = TTag extends `${infer TTag}@${infer TId}`
1954
? { element: TagToElement<TTag>; id: TId }
1955
: { element: TagToElement<TTag>; id: 'root' };
1956
1957
type TagToRecord<TTag> = TagToElementAndId<TTag> extends { element: infer TElement; id: infer TId }
1958
? Record<(TId extends string ? TId : never) | 'root', TElement>
1959
: never;
1960
1961
type Child = HTMLElement | string | Record<string, HTMLElement>;
1962
1963
const H_REGEX = /(?<tag>[\w\-]+)?(?:#(?<id>[\w\-]+))?(?<class>(?:\.(?:[\w\-]+))*)(?:@(?<name>(?:[\w\_])+))?/;
1964
1965
/**
1966
* A helper function to create nested dom nodes.
1967
*
1968
*
1969
* ```ts
1970
* const elements = h('div.code-view', [
1971
* h('div.title@title'),
1972
* h('div.container', [
1973
* h('div.gutter@gutterDiv'),
1974
* h('div@editor'),
1975
* ]),
1976
* ]);
1977
* const editor = createEditor(elements.editor);
1978
* ```
1979
*/
1980
export function h<TTag extends string>
1981
(tag: TTag):
1982
TagToRecord<TTag> extends infer Y ? { [TKey in keyof Y]: Y[TKey] } : never;
1983
1984
export function h<TTag extends string, T extends Child[]>
1985
(tag: TTag, children: [...T]):
1986
(ArrayToObj<T> & TagToRecord<TTag>) extends infer Y ? { [TKey in keyof Y]: Y[TKey] } : never;
1987
1988
export function h<TTag extends string>
1989
(tag: TTag, attributes: Partial<ElementAttributes<TagToElement<TTag>>>):
1990
TagToRecord<TTag> extends infer Y ? { [TKey in keyof Y]: Y[TKey] } : never;
1991
1992
export function h<TTag extends string, T extends Child[]>
1993
(tag: TTag, attributes: Partial<ElementAttributes<TagToElement<TTag>>>, children: [...T]):
1994
(ArrayToObj<T> & TagToRecord<TTag>) extends infer Y ? { [TKey in keyof Y]: Y[TKey] } : never;
1995
1996
export function h(tag: string, ...args: [] | [attributes: { $: string } & Partial<ElementAttributes<HTMLElement>> | Record<string, any>, children?: any[]] | [children: any[]]): Record<string, HTMLElement> {
1997
let attributes: { $?: string } & Partial<ElementAttributes<HTMLElement>>;
1998
let children: (Record<string, HTMLElement> | HTMLElement)[] | undefined;
1999
2000
if (Array.isArray(args[0])) {
2001
attributes = {};
2002
children = args[0];
2003
} else {
2004
attributes = args[0] as any || {};
2005
children = args[1];
2006
}
2007
2008
const match = H_REGEX.exec(tag);
2009
2010
if (!match || !match.groups) {
2011
throw new Error('Bad use of h');
2012
}
2013
2014
const tagName = match.groups['tag'] || 'div';
2015
const el = document.createElement(tagName);
2016
2017
if (match.groups['id']) {
2018
el.id = match.groups['id'];
2019
}
2020
2021
const classNames = [];
2022
if (match.groups['class']) {
2023
for (const className of match.groups['class'].split('.')) {
2024
if (className !== '') {
2025
classNames.push(className);
2026
}
2027
}
2028
}
2029
if (attributes.className !== undefined) {
2030
for (const className of attributes.className.split('.')) {
2031
if (className !== '') {
2032
classNames.push(className);
2033
}
2034
}
2035
}
2036
if (classNames.length > 0) {
2037
el.className = classNames.join(' ');
2038
}
2039
2040
const result: Record<string, HTMLElement> = {};
2041
2042
if (match.groups['name']) {
2043
result[match.groups['name']] = el;
2044
}
2045
2046
if (children) {
2047
for (const c of children) {
2048
if (isHTMLElement(c)) {
2049
el.appendChild(c);
2050
} else if (typeof c === 'string') {
2051
el.append(c);
2052
} else if ('root' in c) {
2053
Object.assign(result, c);
2054
el.appendChild(c.root);
2055
}
2056
}
2057
}
2058
2059
for (const [key, value] of Object.entries(attributes)) {
2060
if (key === 'className') {
2061
continue;
2062
} else if (key === 'style') {
2063
for (const [cssKey, cssValue] of Object.entries(value)) {
2064
el.style.setProperty(
2065
camelCaseToHyphenCase(cssKey),
2066
typeof cssValue === 'number' ? cssValue + 'px' : '' + cssValue
2067
);
2068
}
2069
} else if (key === 'tabIndex') {
2070
el.tabIndex = value;
2071
} else {
2072
el.setAttribute(camelCaseToHyphenCase(key), value.toString());
2073
}
2074
}
2075
2076
result['root'] = el;
2077
2078
return result;
2079
}
2080
2081
/** @deprecated This is a duplication of the h function. Needs cleanup. */
2082
export function svgElem<TTag extends string>
2083
(tag: TTag):
2084
TagToRecord<TTag> extends infer Y ? { [TKey in keyof Y]: Y[TKey] } : never;
2085
/** @deprecated This is a duplication of the h function. Needs cleanup. */
2086
export function svgElem<TTag extends string, T extends Child[]>
2087
(tag: TTag, children: [...T]):
2088
(ArrayToObj<T> & TagToRecord<TTag>) extends infer Y ? { [TKey in keyof Y]: Y[TKey] } : never;
2089
/** @deprecated This is a duplication of the h function. Needs cleanup. */
2090
export function svgElem<TTag extends string>
2091
(tag: TTag, attributes: Partial<ElementAttributes<TagToElement<TTag>>>):
2092
TagToRecord<TTag> extends infer Y ? { [TKey in keyof Y]: Y[TKey] } : never;
2093
/** @deprecated This is a duplication of the h function. Needs cleanup. */
2094
export function svgElem<TTag extends string, T extends Child[]>
2095
(tag: TTag, attributes: Partial<ElementAttributes<TagToElement<TTag>>>, children: [...T]):
2096
(ArrayToObj<T> & TagToRecord<TTag>) extends infer Y ? { [TKey in keyof Y]: Y[TKey] } : never;
2097
/** @deprecated This is a duplication of the h function. Needs cleanup. */
2098
export function svgElem(tag: string, ...args: [] | [attributes: { $: string } & Partial<ElementAttributes<HTMLElement>> | Record<string, any>, children?: any[]] | [children: any[]]): Record<string, HTMLElement> {
2099
let attributes: { $?: string } & Partial<ElementAttributes<HTMLElement>>;
2100
let children: (Record<string, HTMLElement> | HTMLElement)[] | undefined;
2101
2102
if (Array.isArray(args[0])) {
2103
attributes = {};
2104
children = args[0];
2105
} else {
2106
attributes = args[0] as any || {};
2107
children = args[1];
2108
}
2109
2110
const match = H_REGEX.exec(tag);
2111
2112
if (!match || !match.groups) {
2113
throw new Error('Bad use of h');
2114
}
2115
2116
const tagName = match.groups['tag'] || 'div';
2117
const el = document.createElementNS('http://www.w3.org/2000/svg', tagName) as any as HTMLElement;
2118
2119
if (match.groups['id']) {
2120
el.id = match.groups['id'];
2121
}
2122
2123
const classNames = [];
2124
if (match.groups['class']) {
2125
for (const className of match.groups['class'].split('.')) {
2126
if (className !== '') {
2127
classNames.push(className);
2128
}
2129
}
2130
}
2131
if (attributes.className !== undefined) {
2132
for (const className of attributes.className.split('.')) {
2133
if (className !== '') {
2134
classNames.push(className);
2135
}
2136
}
2137
}
2138
if (classNames.length > 0) {
2139
el.className = classNames.join(' ');
2140
}
2141
2142
const result: Record<string, HTMLElement> = {};
2143
2144
if (match.groups['name']) {
2145
result[match.groups['name']] = el;
2146
}
2147
2148
if (children) {
2149
for (const c of children) {
2150
if (isHTMLElement(c)) {
2151
el.appendChild(c);
2152
} else if (typeof c === 'string') {
2153
el.append(c);
2154
} else if ('root' in c) {
2155
Object.assign(result, c);
2156
el.appendChild(c.root);
2157
}
2158
}
2159
}
2160
2161
for (const [key, value] of Object.entries(attributes)) {
2162
if (key === 'className') {
2163
continue;
2164
} else if (key === 'style') {
2165
for (const [cssKey, cssValue] of Object.entries(value)) {
2166
el.style.setProperty(
2167
camelCaseToHyphenCase(cssKey),
2168
typeof cssValue === 'number' ? cssValue + 'px' : '' + cssValue
2169
);
2170
}
2171
} else if (key === 'tabIndex') {
2172
el.tabIndex = value;
2173
} else {
2174
el.setAttribute(camelCaseToHyphenCase(key), value.toString());
2175
}
2176
}
2177
2178
result['root'] = el;
2179
2180
return result;
2181
}
2182
2183
function camelCaseToHyphenCase(str: string) {
2184
return str.replace(/([a-z])([A-Z])/g, '$1-$2').toLowerCase();
2185
}
2186
2187
export function copyAttributes(from: Element, to: Element, filter?: string[]): void {
2188
for (const { name, value } of from.attributes) {
2189
if (!filter || filter.includes(name)) {
2190
to.setAttribute(name, value);
2191
}
2192
}
2193
}
2194
2195
function copyAttribute(from: Element, to: Element, name: string): void {
2196
const value = from.getAttribute(name);
2197
if (value) {
2198
to.setAttribute(name, value);
2199
} else {
2200
to.removeAttribute(name);
2201
}
2202
}
2203
2204
export function trackAttributes(from: Element, to: Element, filter?: string[]): IDisposable {
2205
copyAttributes(from, to, filter);
2206
2207
const disposables = new DisposableStore();
2208
2209
disposables.add(sharedMutationObserver.observe(from, disposables, { attributes: true, attributeFilter: filter })(mutations => {
2210
for (const mutation of mutations) {
2211
if (mutation.type === 'attributes' && mutation.attributeName) {
2212
copyAttribute(from, to, mutation.attributeName);
2213
}
2214
}
2215
}));
2216
2217
return disposables;
2218
}
2219
2220
export function isEditableElement(element: Element): boolean {
2221
return element.tagName.toLowerCase() === 'input' || element.tagName.toLowerCase() === 'textarea' || isHTMLElement(element) && !!element.editContext;
2222
}
2223
2224
/**
2225
* Helper for calculating the "safe triangle" occluded by hovers to avoid early dismissal.
2226
* @see https://www.smashingmagazine.com/2023/08/better-context-menus-safe-triangles/ for example
2227
*/
2228
export class SafeTriangle {
2229
// 4 points (x, y), 8 length
2230
private points = new Int16Array(8);
2231
2232
constructor(
2233
private readonly originX: number,
2234
private readonly originY: number,
2235
target: HTMLElement
2236
) {
2237
const { top, left, right, bottom } = target.getBoundingClientRect();
2238
const t = this.points;
2239
let i = 0;
2240
2241
t[i++] = left;
2242
t[i++] = top;
2243
2244
t[i++] = right;
2245
t[i++] = top;
2246
2247
t[i++] = left;
2248
t[i++] = bottom;
2249
2250
t[i++] = right;
2251
t[i++] = bottom;
2252
}
2253
2254
public contains(x: number, y: number) {
2255
const { points, originX, originY } = this;
2256
for (let i = 0; i < 4; i++) {
2257
const p1 = 2 * i;
2258
const p2 = 2 * ((i + 1) % 4);
2259
if (isPointWithinTriangle(x, y, originX, originY, points[p1], points[p1 + 1], points[p2], points[p2 + 1])) {
2260
return true;
2261
}
2262
}
2263
2264
return false;
2265
}
2266
}
2267
2268
2269
export namespace n {
2270
function nodeNs<TMap extends Record<string, any>>(elementNs: string | undefined = undefined): DomTagCreateFn<TMap> {
2271
return (tag, attributes, children) => {
2272
const className = attributes.class;
2273
delete attributes.class;
2274
const ref = attributes.ref;
2275
delete attributes.ref;
2276
const obsRef = attributes.obsRef;
2277
delete attributes.obsRef;
2278
2279
return new ObserverNodeWithElement(tag as any, ref, obsRef, elementNs, className, attributes, children);
2280
};
2281
}
2282
2283
function node<TMap extends Record<string, any>, TKey extends keyof TMap>(tag: TKey, elementNs: string | undefined = undefined): DomCreateFn<TMap[TKey], TMap[TKey]> {
2284
const f = nodeNs(elementNs) as any;
2285
return (attributes, children) => {
2286
return f(tag, attributes, children);
2287
};
2288
}
2289
2290
export const div: DomCreateFn<HTMLDivElement, HTMLDivElement> = node<HTMLElementTagNameMap, 'div'>('div');
2291
2292
export const elem = nodeNs<HTMLElementTagNameMap>(undefined);
2293
2294
export const svg: DomCreateFn<SVGElementTagNameMap2['svg'], SVGElement> = node<SVGElementTagNameMap2, 'svg'>('svg', 'http://www.w3.org/2000/svg');
2295
2296
export const svgElem = nodeNs<SVGElementTagNameMap2>('http://www.w3.org/2000/svg');
2297
2298
export function ref<T = HTMLOrSVGElement>(): IRefWithVal<T> {
2299
let value: T | undefined = undefined;
2300
const result: IRef<T> = function (val: T) {
2301
value = val;
2302
};
2303
Object.defineProperty(result, 'element', {
2304
get() {
2305
if (!value) {
2306
throw new BugIndicatingError('Make sure the ref is set before accessing the element. Maybe wrong initialization order?');
2307
}
2308
return value;
2309
}
2310
});
2311
return result as any;
2312
}
2313
}
2314
type Value<T> = T | IObservable<T>;
2315
type ValueOrList<T> = Value<T> | ValueOrList<T>[];
2316
type ValueOrList2<T> = ValueOrList<T> | ValueOrList<ValueOrList<T>>;
2317
type HTMLOrSVGElement = HTMLElement | SVGElement;
2318
type SVGElementTagNameMap2 = {
2319
svg: SVGElement & {
2320
width: number;
2321
height: number;
2322
transform: string;
2323
viewBox: string;
2324
fill: string;
2325
};
2326
path: SVGElement & {
2327
d: string;
2328
stroke: string;
2329
fill: string;
2330
};
2331
linearGradient: SVGElement & {
2332
id: string;
2333
x1: string | number;
2334
x2: string | number;
2335
};
2336
stop: SVGElement & {
2337
offset: string;
2338
};
2339
rect: SVGElement & {
2340
x: number;
2341
y: number;
2342
width: number;
2343
height: number;
2344
fill: string;
2345
};
2346
defs: SVGElement;
2347
};
2348
type DomTagCreateFn<TMap extends Record<string, any>> = <TTag extends keyof TMap>(
2349
tag: TTag,
2350
attributes: ElementAttributeKeys<TMap[TTag]> & { class?: ValueOrList<string | false | undefined>; ref?: IRef<TMap[TTag]>; obsRef?: IRef<ObserverNodeWithElement<TMap[TTag]> | null> },
2351
children?: ChildNode
2352
) => ObserverNode<TMap[TTag]>;
2353
type DomCreateFn<TAttributes, TResult extends HTMLOrSVGElement> = (
2354
attributes: ElementAttributeKeys<TAttributes> & { class?: ValueOrList<string | false | undefined>; ref?: IRef<TResult>; obsRef?: IRef<ObserverNodeWithElement<TResult> | null> },
2355
children?: ChildNode
2356
) => ObserverNode<TResult>;
2357
2358
export type ChildNode = ValueOrList2<HTMLOrSVGElement | string | ObserverNode | undefined>;
2359
2360
export type IRef<T> = (value: T) => void;
2361
2362
export interface IRefWithVal<T> extends IRef<T> {
2363
readonly element: T;
2364
}
2365
2366
export abstract class ObserverNode<T extends HTMLOrSVGElement = HTMLOrSVGElement> {
2367
private readonly _deriveds: (IObservable<any>)[] = [];
2368
2369
protected readonly _element: T;
2370
2371
constructor(
2372
tag: string,
2373
ref: IRef<T> | undefined,
2374
obsRef: IRef<ObserverNodeWithElement<T> | null> | undefined,
2375
ns: string | undefined,
2376
className: ValueOrList<string | undefined | false> | undefined,
2377
attributes: ElementAttributeKeys<T>,
2378
children: ChildNode
2379
) {
2380
this._element = (ns ? document.createElementNS(ns, tag) : document.createElement(tag)) as unknown as T;
2381
if (ref) {
2382
ref(this._element);
2383
}
2384
if (obsRef) {
2385
this._deriveds.push(derived((_reader) => {
2386
obsRef(this as unknown as ObserverNodeWithElement<T>);
2387
_reader.store.add({
2388
dispose: () => {
2389
obsRef(null);
2390
}
2391
});
2392
}));
2393
}
2394
2395
if (className) {
2396
if (hasObservable(className)) {
2397
this._deriveds.push(derived(this, reader => {
2398
/** @description set.class */
2399
setClassName(this._element, getClassName(className, reader));
2400
}));
2401
} else {
2402
setClassName(this._element, getClassName(className, undefined));
2403
}
2404
}
2405
2406
for (const [key, value] of Object.entries(attributes)) {
2407
if (key === 'style') {
2408
for (const [cssKey, cssValue] of Object.entries(value)) {
2409
const key = camelCaseToHyphenCase(cssKey);
2410
if (isObservable(cssValue)) {
2411
this._deriveds.push(derivedOpts({ owner: this, debugName: () => `set.style.${key}` }, reader => {
2412
this._element.style.setProperty(key, convertCssValue(cssValue.read(reader)));
2413
}));
2414
} else {
2415
this._element.style.setProperty(key, convertCssValue(cssValue));
2416
}
2417
}
2418
} else if (key === 'tabIndex') {
2419
if (isObservable(value)) {
2420
this._deriveds.push(derived(this, reader => {
2421
/** @description set.tabIndex */
2422
this._element.tabIndex = value.read(reader) as any;
2423
}));
2424
} else {
2425
this._element.tabIndex = value;
2426
}
2427
} else if (key.startsWith('on')) {
2428
(this._element as any)[key] = value;
2429
} else {
2430
if (isObservable(value)) {
2431
this._deriveds.push(derivedOpts({ owner: this, debugName: () => `set.${key}` }, reader => {
2432
setOrRemoveAttribute(this._element, key, value.read(reader));
2433
}));
2434
} else {
2435
setOrRemoveAttribute(this._element, key, value);
2436
}
2437
}
2438
}
2439
2440
if (children) {
2441
function getChildren(reader: IReader | undefined, children: ValueOrList2<HTMLOrSVGElement | string | ObserverNode | undefined>): (HTMLOrSVGElement | string)[] {
2442
if (isObservable(children)) {
2443
return getChildren(reader, children.read(reader));
2444
}
2445
if (Array.isArray(children)) {
2446
return children.flatMap(c => getChildren(reader, c));
2447
}
2448
if (children instanceof ObserverNode) {
2449
if (reader) {
2450
children.readEffect(reader);
2451
}
2452
return [children._element];
2453
}
2454
if (children) {
2455
return [children];
2456
}
2457
return [];
2458
}
2459
2460
const d = derived(this, reader => {
2461
/** @description set.children */
2462
this._element.replaceChildren(...getChildren(reader, children));
2463
});
2464
this._deriveds.push(d);
2465
if (!childrenIsObservable(children)) {
2466
d.get();
2467
}
2468
}
2469
}
2470
2471
readEffect(reader: IReader | undefined): void {
2472
for (const d of this._deriveds) {
2473
d.read(reader);
2474
}
2475
}
2476
2477
keepUpdated(store: DisposableStore): ObserverNodeWithElement<T> {
2478
derived(reader => {
2479
/** update */
2480
this.readEffect(reader);
2481
}).recomputeInitiallyAndOnChange(store);
2482
return this as unknown as ObserverNodeWithElement<T>;
2483
}
2484
2485
/**
2486
* Creates a live element that will keep the element updated as long as the returned object is not disposed.
2487
*/
2488
toDisposableLiveElement() {
2489
const store = new DisposableStore();
2490
this.keepUpdated(store);
2491
return new LiveElement(this._element, store);
2492
}
2493
}
2494
function setClassName(domNode: HTMLOrSVGElement, className: string) {
2495
if (isSVGElement(domNode)) {
2496
domNode.setAttribute('class', className);
2497
} else {
2498
domNode.className = className;
2499
}
2500
}
2501
function resolve<T>(value: ValueOrList<T>, reader: IReader | undefined, cb: (val: T) => void): void {
2502
if (isObservable(value)) {
2503
cb(value.read(reader));
2504
return;
2505
}
2506
if (Array.isArray(value)) {
2507
for (const v of value) {
2508
resolve(v, reader, cb);
2509
}
2510
return;
2511
}
2512
cb(value as any);
2513
}
2514
function getClassName(className: ValueOrList<string | undefined | false> | undefined, reader: IReader | undefined): string {
2515
let result = '';
2516
resolve(className, reader, val => {
2517
if (val) {
2518
if (result.length === 0) {
2519
result = val;
2520
} else {
2521
result += ' ' + val;
2522
}
2523
}
2524
});
2525
return result;
2526
}
2527
function hasObservable(value: ValueOrList<unknown>): boolean {
2528
if (isObservable(value)) {
2529
return true;
2530
}
2531
if (Array.isArray(value)) {
2532
return value.some(v => hasObservable(v));
2533
}
2534
return false;
2535
}
2536
function convertCssValue(value: any): string {
2537
if (typeof value === 'number') {
2538
return value + 'px';
2539
}
2540
return value;
2541
}
2542
function childrenIsObservable(children: ValueOrList2<HTMLOrSVGElement | string | ObserverNode | undefined>): boolean {
2543
if (isObservable(children)) {
2544
return true;
2545
}
2546
if (Array.isArray(children)) {
2547
return children.some(c => childrenIsObservable(c));
2548
}
2549
return false;
2550
}
2551
2552
export class LiveElement<T extends HTMLOrSVGElement = HTMLElement> {
2553
constructor(
2554
public readonly element: T,
2555
private readonly _disposable: IDisposable
2556
) { }
2557
2558
dispose() {
2559
this._disposable.dispose();
2560
}
2561
}
2562
2563
export class ObserverNodeWithElement<T extends HTMLOrSVGElement = HTMLOrSVGElement> extends ObserverNode<T> {
2564
public get element() {
2565
return this._element;
2566
}
2567
2568
private _isHovered: IObservable<boolean> | undefined = undefined;
2569
2570
get isHovered(): IObservable<boolean> {
2571
if (!this._isHovered) {
2572
const hovered = observableValue<boolean>('hovered', false);
2573
this._element.addEventListener('mouseenter', (_e) => hovered.set(true, undefined));
2574
this._element.addEventListener('mouseleave', (_e) => hovered.set(false, undefined));
2575
this._isHovered = hovered;
2576
}
2577
return this._isHovered;
2578
}
2579
2580
private _didMouseMoveDuringHover: IObservable<boolean> | undefined = undefined;
2581
2582
get didMouseMoveDuringHover(): IObservable<boolean> {
2583
if (!this._didMouseMoveDuringHover) {
2584
let _hovering = false;
2585
const hovered = observableValue<boolean>('didMouseMoveDuringHover', false);
2586
this._element.addEventListener('mouseenter', (_e) => {
2587
_hovering = true;
2588
});
2589
this._element.addEventListener('mousemove', (_e) => {
2590
if (_hovering) {
2591
hovered.set(true, undefined);
2592
}
2593
});
2594
this._element.addEventListener('mouseleave', (_e) => {
2595
_hovering = false;
2596
hovered.set(false, undefined);
2597
});
2598
this._didMouseMoveDuringHover = hovered;
2599
}
2600
return this._didMouseMoveDuringHover;
2601
}
2602
}
2603
function setOrRemoveAttribute(element: HTMLOrSVGElement, key: string, value: unknown) {
2604
if (value === null || value === undefined) {
2605
element.removeAttribute(camelCaseToHyphenCase(key));
2606
} else {
2607
element.setAttribute(camelCaseToHyphenCase(key), String(value));
2608
}
2609
}
2610
2611
function isObservable<T>(obj: unknown): obj is IObservable<T> {
2612
return !!obj && (<IObservable<T>>obj).read !== undefined && (<IObservable<T>>obj).reportChanges !== undefined;
2613
}
2614
type ElementAttributeKeys<T> = Partial<{
2615
[K in keyof T]: T[K] extends Function ? never : T[K] extends object ? ElementAttributeKeys<T[K]> : Value<number | T[K] | undefined | null>;
2616
}>;
2617
2618