/
Window.ts
703 lines (658 loc) · 23.5 KB
/
Window.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
import CustomElementRegistry from '../custom-element/CustomElementRegistry';
import Document from '../nodes/document/Document';
import HTMLDocument from '../nodes/html-document/HTMLDocument';
import XMLDocument from '../nodes/xml-document/XMLDocument';
import SVGDocument from '../nodes/svg-document/SVGDocument';
import Node from '../nodes/node/Node';
import NodeFilter from '../tree-walker/NodeFilter';
import Text from '../nodes/text/Text';
import Comment from '../nodes/comment/Comment';
import ShadowRoot from '../nodes/shadow-root/ShadowRoot';
import Element from '../nodes/element/Element';
import HTMLTemplateElement from '../nodes/html-template-element/HTMLTemplateElement';
import HTMLFormElement from '../nodes/html-form-element/HTMLFormElement';
import HTMLElement from '../nodes/html-element/HTMLElement';
import HTMLUnknownElement from '../nodes/html-unknown-element/HTMLUnknownElement';
import HTMLInputElement from '../nodes/html-input-element/HTMLInputElement';
import HTMLTextAreaElement from '../nodes/html-text-area-element/HTMLTextAreaElement';
import HTMLLinkElement from '../nodes/html-link-element/HTMLLinkElement';
import HTMLStyleElement from '../nodes/html-style-element/HTMLStyleElement';
import HTMLSlotElement from '../nodes/html-slot-element/HTMLSlotElement';
import HTMLLabelElement from '../nodes/html-label-element/HTMLLabelElement';
import HTMLMetaElement from '../nodes/html-meta-element/HTMLMetaElement';
import HTMLMediaElement from '../nodes/html-media-element/HTMLMediaElement';
import HTMLAudioElement from '../nodes/html-audio-element/HTMLAudioElement';
import HTMLVideoElement from '../nodes/html-video-element/HTMLVideoElement';
import HTMLBaseElement from '../nodes/html-base-element/HTMLBaseElement';
import HTMLDialogElement from '../nodes/html-dialog-element/HTMLDialogElement';
import SVGSVGElement from '../nodes/svg-element/SVGSVGElement';
import SVGElement from '../nodes/svg-element/SVGElement';
import HTMLScriptElement from '../nodes/html-script-element/HTMLScriptElement';
import HTMLImageElement from '../nodes/html-image-element/HTMLImageElement';
import { default as ImageImplementation } from '../nodes/html-image-element/Image';
import DocumentFragment from '../nodes/document-fragment/DocumentFragment';
import CharacterData from '../nodes/character-data/CharacterData';
import TreeWalker from '../tree-walker/TreeWalker';
import Event from '../event/Event';
import CustomEvent from '../event/events/CustomEvent';
import AnimationEvent from '../event/events/AnimationEvent';
import KeyboardEvent from '../event/events/KeyboardEvent';
import ProgressEvent from '../event/events/ProgressEvent';
import MediaQueryListEvent from '../event/events/MediaQueryListEvent';
import EventTarget from '../event/EventTarget';
import { URL, URLSearchParams } from 'url';
import Location from '../location/Location';
import NonImplementedEventTypes from '../event/NonImplementedEventTypes';
import MutationObserver from '../mutation-observer/MutationObserver';
import NonImplemenetedElementClasses from '../config/NonImplemenetedElementClasses';
import { default as DOMParserImplementation } from '../dom-parser/DOMParser';
import XMLSerializer from '../xml-serializer/XMLSerializer';
import ResizeObserver from '../resize-observer/ResizeObserver';
import Blob from '../file/Blob';
import File from '../file/File';
import DOMException from '../exception/DOMException';
import { default as FileReaderImplementation } from '../file/FileReader';
import History from '../history/History';
import CSSStyleSheet from '../css/CSSStyleSheet';
import CSSStyleDeclaration from '../css/declaration/CSSStyleDeclaration';
import CSS from '../css/CSS';
import CSSUnitValue from '../css/CSSUnitValue';
import CSSRule from '../css/CSSRule';
import CSSContainerRule from '../css/rules/CSSContainerRule';
import CSSFontFaceRule from '../css/rules/CSSFontFaceRule';
import CSSKeyframeRule from '../css/rules/CSSKeyframeRule';
import CSSKeyframesRule from '../css/rules/CSSKeyframesRule';
import CSSMediaRule from '../css/rules/CSSMediaRule';
import CSSStyleRule from '../css/rules/CSSStyleRule';
import MouseEvent from '../event/events/MouseEvent';
import PointerEvent from '../event/events/PointerEvent';
import FocusEvent from '../event/events/FocusEvent';
import WheelEvent from '../event/events/WheelEvent';
import DataTransfer from '../event/DataTransfer';
import DataTransferItem from '../event/DataTransferItem';
import DataTransferItemList from '../event/DataTransferItemList';
import InputEvent from '../event/events/InputEvent';
import UIEvent from '../event/UIEvent';
import ErrorEvent from '../event/events/ErrorEvent';
import StorageEvent from '../event/events/StorageEvent';
import Screen from '../screen/Screen';
import AsyncTaskManager from '../async-task-manager/AsyncTaskManager';
import IResponse from '../fetch/IResponse';
import IResponseInit from '../fetch/IResponseInit';
import IRequest from '../fetch/IRequest';
import IRequestInit from '../fetch/IRequestInit';
import IHeaders from '../fetch/IHeaders';
import IHeadersInit from '../fetch/IHeadersInit';
import Headers from '../fetch/Headers';
import { default as RequestImplementation } from '../fetch/Request';
import { default as ResponseImplementation } from '../fetch/Response';
import Storage from '../storage/Storage';
import IWindow from './IWindow';
import HTMLCollection from '../nodes/element/HTMLCollection';
import NodeList from '../nodes/node/NodeList';
import MediaQueryList from '../match-media/MediaQueryList';
import Selection from '../selection/Selection';
import Navigator from '../navigator/Navigator';
import MimeType from '../navigator/MimeType';
import MimeTypeArray from '../navigator/MimeTypeArray';
import Plugin from '../navigator/Plugin';
import PluginArray from '../navigator/PluginArray';
import FetchHandler from '../fetch/FetchHandler';
import { default as RangeImplementation } from '../range/Range';
import DOMRect from '../nodes/element/DOMRect';
import VMGlobalPropertyScript from './VMGlobalPropertyScript';
import * as PerfHooks from 'perf_hooks';
import VM from 'vm';
import { Buffer } from 'buffer';
import XMLHttpRequestImplementation from '../xml-http-request/XMLHttpRequest';
import XMLHttpRequestUpload from '../xml-http-request/XMLHttpRequestUpload';
import XMLHttpRequestEventTarget from '../xml-http-request/XMLHttpRequestEventTarget';
import Base64 from '../base64/Base64';
import IDocument from '../nodes/document/IDocument';
import Attr from '../nodes/attr/Attr';
import NamedNodeMap from '../named-node-map/NamedNodeMap';
import IElement from '../nodes/element/IElement';
import ProcessingInstruction from '../nodes/processing-instruction/ProcessingInstruction';
import IHappyDOMSettings from './IHappyDOMSettings';
import RequestInfo from '../fetch/RequestInfo';
const ORIGINAL_SET_TIMEOUT = setTimeout;
const ORIGINAL_CLEAR_TIMEOUT = clearTimeout;
const ORIGINAL_SET_INTERVAL = setInterval;
const ORIGINAL_CLEAR_INTERVAL = clearInterval;
/**
* Browser window.
*
* Reference:
* https://developer.mozilla.org/en-US/docs/Web/API/Window.
*/
export default class Window extends EventTarget implements IWindow {
// The Happy DOM property
public readonly happyDOM = {
whenAsyncComplete: async (): Promise<void> => {
return await this.happyDOM.asyncTaskManager.whenComplete();
},
cancelAsync: (): void => {
this.happyDOM.asyncTaskManager.cancelAll();
},
asyncTaskManager: new AsyncTaskManager(),
setInnerWidth: (width: number): void => {
if (this.innerWidth !== width) {
(<number>this.innerWidth) = width;
this.dispatchEvent(new Event('resize'));
}
},
setInnerHeight: (height: number): void => {
if (this.innerHeight !== height) {
(<number>this.innerHeight) = height;
this.dispatchEvent(new Event('resize'));
}
},
setURL: (url: string) => {
this.location.href = url;
},
settings: {
disableJavaScriptEvaluation: false,
disableJavaScriptFileLoading: false,
disableCSSFileLoading: false,
enableFileSystemHttpRequests: false
}
};
// Global classes
public readonly Node = Node;
public readonly HTMLElement = HTMLElement;
public readonly HTMLUnknownElement = HTMLUnknownElement;
public readonly HTMLTemplateElement = HTMLTemplateElement;
public readonly HTMLFormElement = HTMLFormElement;
public readonly HTMLInputElement = HTMLInputElement;
public readonly HTMLTextAreaElement = HTMLTextAreaElement;
public readonly HTMLImageElement = HTMLImageElement;
public readonly HTMLScriptElement = HTMLScriptElement;
public readonly HTMLLinkElement = HTMLLinkElement;
public readonly HTMLStyleElement = HTMLStyleElement;
public readonly HTMLLabelElement = HTMLLabelElement;
public readonly HTMLSlotElement = HTMLSlotElement;
public readonly HTMLMetaElement = HTMLMetaElement;
public readonly HTMLMediaElement = HTMLMediaElement;
public readonly HTMLAudioElement = HTMLAudioElement;
public readonly HTMLVideoElement = HTMLVideoElement;
public readonly HTMLBaseElement = HTMLBaseElement;
public readonly HTMLDialogElement = HTMLDialogElement;
public readonly Attr = Attr;
public readonly NamedNodeMap = NamedNodeMap;
public readonly SVGSVGElement = SVGSVGElement;
public readonly SVGElement = SVGElement;
public readonly Text = Text;
public readonly Comment = Comment;
public readonly ShadowRoot = ShadowRoot;
public readonly ProcessingInstruction = ProcessingInstruction;
public readonly Element = Element;
public readonly DocumentFragment = DocumentFragment;
public readonly CharacterData = CharacterData;
public readonly NodeFilter = NodeFilter;
public readonly TreeWalker = TreeWalker;
public readonly MutationObserver = MutationObserver;
public readonly Document = Document;
public readonly HTMLDocument = HTMLDocument;
public readonly XMLDocument = XMLDocument;
public readonly SVGDocument = SVGDocument;
public readonly Event = Event;
public readonly UIEvent = UIEvent;
public readonly CustomEvent = CustomEvent;
public readonly AnimationEvent = AnimationEvent;
public readonly KeyboardEvent = KeyboardEvent;
public readonly MouseEvent = MouseEvent;
public readonly PointerEvent = PointerEvent;
public readonly FocusEvent = FocusEvent;
public readonly WheelEvent = WheelEvent;
public readonly InputEvent = InputEvent;
public readonly ErrorEvent = ErrorEvent;
public readonly StorageEvent = StorageEvent;
public readonly ProgressEvent = ProgressEvent;
public readonly MediaQueryListEvent = MediaQueryListEvent;
public readonly EventTarget = EventTarget;
public readonly DataTransfer = DataTransfer;
public readonly DataTransferItem = DataTransferItem;
public readonly DataTransferItemList = DataTransferItemList;
public readonly URL = URL;
public readonly Location = Location;
public readonly CustomElementRegistry = CustomElementRegistry;
public readonly Window = <typeof Window>this.constructor;
public readonly XMLSerializer = XMLSerializer;
public readonly ResizeObserver = ResizeObserver;
public readonly CSSStyleSheet = CSSStyleSheet;
public readonly Blob = Blob;
public readonly File = File;
public readonly DOMException = DOMException;
public readonly History = History;
public readonly Screen = Screen;
public readonly Storage = Storage;
public readonly URLSearchParams = URLSearchParams;
public readonly HTMLCollection = HTMLCollection;
public readonly NodeList = NodeList;
public readonly CSSUnitValue = CSSUnitValue;
public readonly CSSRule = CSSRule;
public readonly CSSContainerRule = CSSContainerRule;
public readonly CSSFontFaceRule = CSSFontFaceRule;
public readonly CSSKeyframeRule = CSSKeyframeRule;
public readonly CSSKeyframesRule = CSSKeyframesRule;
public readonly CSSMediaRule = CSSMediaRule;
public readonly CSSStyleRule = CSSStyleRule;
public readonly Selection = Selection;
public readonly Navigator = Navigator;
public readonly MimeType = MimeType;
public readonly MimeTypeArray = MimeTypeArray;
public readonly Plugin = Plugin;
public readonly PluginArray = PluginArray;
public readonly Headers: { new (init?: IHeadersInit): IHeaders } = Headers;
public readonly DOMRect: typeof DOMRect;
public readonly Request: {
new (input: string | { href: string } | IRequest, init?: IRequestInit): IRequest;
};
public readonly Response: {
new (body?: NodeJS.ReadableStream | null, init?: IResponseInit): IResponse;
};
public readonly XMLHttpRequestUpload = XMLHttpRequestUpload;
public readonly XMLHttpRequestEventTarget = XMLHttpRequestEventTarget;
public readonly XMLHttpRequest;
public readonly DOMParser;
public readonly Range;
public readonly FileReader;
public readonly Image;
// Events
public onload: (event: Event) => void = null;
public onerror: (event: ErrorEvent) => void = null;
// Public Properties
public readonly document: Document;
public readonly customElements: CustomElementRegistry;
public readonly location: Location;
public readonly history: History;
public readonly navigator: Navigator;
public readonly console = console;
public readonly self = this;
public readonly top = this;
public readonly parent = this;
public readonly window = this;
public readonly globalThis = this;
public readonly screen: Screen;
public readonly devicePixelRatio = 1;
public readonly sessionStorage: Storage;
public readonly localStorage: Storage;
public readonly performance = PerfHooks.performance;
public readonly innerWidth: number;
public readonly innerHeight: number;
// Node.js Globals
public ArrayBuffer;
public Boolean;
public Buffer = Buffer;
public DataView;
public Date;
public Error;
public EvalError;
public Float32Array;
public Float64Array;
public GLOBAL;
public Infinity;
public Int16Array;
public Int32Array;
public Int8Array;
public Intl;
public JSON;
public Map;
public Math;
public NaN;
public Number;
public Promise;
public RangeError;
public ReferenceError;
public RegExp;
public Reflect;
public Set;
public Symbol;
public SyntaxError;
public String;
public TypeError;
public URIError;
public Uint16Array;
public Uint32Array;
public Uint8Array;
public Uint8ClampedArray;
public WeakMap;
public WeakSet;
public clearImmediate;
public decodeURI;
public decodeURIComponent;
public encodeURI;
public encodeURIComponent;
public escape;
public global;
public isFinite;
public isNaN;
public parseFloat;
public parseInt;
public process;
public root;
public setImmediate;
public queueMicrotask;
public undefined;
public unescape;
public gc;
public v8debug;
public AbortController;
public AbortSignal;
public Array;
public Object;
public Function;
// Private properties
private _setTimeout;
private _clearTimeout;
private _setInterval;
private _clearInterval;
/**
* Constructor.
*
* @param [options] Options.
* @param [options.innerWidth] Inner width. Defaults to "1024".
* @param [options.innerHeight] Inner height. Defaults to "768".
* @param [options.url] URL.
* @param [options.settings] Settings.
*/
constructor(options?: {
innerWidth?: number;
innerHeight?: number;
url?: string;
settings?: IHappyDOMSettings;
}) {
super();
this.customElements = new CustomElementRegistry();
this.location = new Location();
this.navigator = new Navigator();
this.history = new History();
this.screen = new Screen();
this.sessionStorage = new Storage();
this.localStorage = new Storage();
this.innerWidth = options?.innerWidth ? options.innerWidth : 1024;
this.innerHeight = options?.innerHeight ? options.innerHeight : 768;
if (options?.url) {
this.location.href = options.url;
}
if (options?.settings) {
this.happyDOM.settings = Object.assign(this.happyDOM.settings, options.settings);
}
this._setTimeout = ORIGINAL_SET_TIMEOUT;
this._clearTimeout = ORIGINAL_CLEAR_TIMEOUT;
this._setInterval = ORIGINAL_SET_INTERVAL;
this._clearInterval = ORIGINAL_CLEAR_INTERVAL;
// Non-implemented event types
for (const eventType of NonImplementedEventTypes) {
if (!this[eventType]) {
this[eventType] = Event;
}
}
// Non implemented element classes
for (const className of NonImplemenetedElementClasses) {
if (!this[className]) {
this[className] = HTMLElement;
}
}
// Binds all methods to "this", so that it will use the correct context when called globally.
for (const key of Object.getOwnPropertyNames(Window.prototype).concat(
Object.getOwnPropertyNames(EventTarget.prototype)
)) {
if (
key !== 'constructor' &&
key[0] !== '_' &&
key[0] === key[0].toLowerCase() &&
typeof this[key] === 'function'
) {
this[key] = this[key].bind(this);
}
}
HTMLDocument._defaultView = this;
const document = new HTMLDocument();
this.document = document;
// We need to set the correct owner document when the class is constructed.
// To achieve this we will extend the original implementation with a class that sets the owner document.
ResponseImplementation._ownerDocument = document;
RequestImplementation._ownerDocument = document;
ImageImplementation._ownerDocument = document;
FileReaderImplementation._ownerDocument = document;
DOMParserImplementation._ownerDocument = document;
RangeImplementation._ownerDocument = document;
XMLHttpRequestImplementation._ownerDocument = document;
/* eslint-disable jsdoc/require-jsdoc */
class Response extends ResponseImplementation {
public static _ownerDocument: IDocument = document;
}
class Request extends RequestImplementation {
public static _ownerDocument: IDocument = document;
}
class Image extends ImageImplementation {
public static _ownerDocument: IDocument = document;
}
class FileReader extends FileReaderImplementation {
public static _ownerDocument: IDocument = document;
}
class DOMParser extends DOMParserImplementation {
public static _ownerDocument: IDocument = document;
}
class XMLHttpRequest extends XMLHttpRequestImplementation {
public static _ownerDocument: IDocument = document;
}
class Range extends RangeImplementation {
public static _ownerDocument: IDocument = document;
}
/* eslint-enable jsdoc/require-jsdoc */
this.Response = Response;
this.Request = Request;
this.Image = Image;
this.FileReader = FileReader;
this.DOMParser = DOMParser;
this.XMLHttpRequest = XMLHttpRequest;
this.Range = Range;
this._setupVMContext();
this.document._onWindowReady();
}
/**
* The CSS interface holds useful CSS-related methods.
*
* @returns CSS interface.
*/
public get CSS(): CSS {
return new CSS();
}
/**
* Evaluates code.
*
* @override
* @param code Code.
* @returns Result.
*/
public eval(code: string): unknown {
if (VM.isContext(this)) {
return VM.runInContext(code, this);
}
return eval(code);
}
/**
* Returns an object containing the values of all CSS properties of an element.
*
* @param element Element.
* @returns CSS style declaration.
*/
public getComputedStyle(element: IElement): CSSStyleDeclaration {
return new CSSStyleDeclaration(element, true);
}
/**
* Returns selection.
*
* @returns Selection.
*/
public getSelection(): Selection {
return this.document.getSelection();
}
/**
* Scrolls to a particular set of coordinates.
*
* @param x X position or options object.
* @param y Y position.
*/
public scroll(x: { top?: number; left?: number; behavior?: string } | number, y?: number): void {
if (typeof x === 'object') {
if (x.behavior === 'smooth') {
this.setTimeout(() => {
if (x.top !== undefined) {
(<number>this.document.documentElement.scrollTop) = x.top;
}
if (x.left !== undefined) {
(<number>this.document.documentElement.scrollLeft) = x.left;
}
});
} else {
if (x.top !== undefined) {
(<number>this.document.documentElement.scrollTop) = x.top;
}
if (x.left !== undefined) {
(<number>this.document.documentElement.scrollLeft) = x.left;
}
}
} else if (x !== undefined && y !== undefined) {
(<number>this.document.documentElement.scrollLeft) = x;
(<number>this.document.documentElement.scrollTop) = y;
}
}
/**
* Scrolls to a particular set of coordinates.
*
* @param x X position or options object.
* @param y Y position.
*/
public scrollTo(
x: { top?: number; left?: number; behavior?: string } | number,
y?: number
): void {
this.scroll(x, y);
}
/**
* Returns a new MediaQueryList object that can then be used to determine if the document matches the media query string.
*
* @param mediaQueryString A string specifying the media query to parse into a MediaQueryList.
* @returns A new MediaQueryList.
*/
public matchMedia(mediaQueryString: string): MediaQueryList {
return new MediaQueryList(this, mediaQueryString);
}
/**
* Sets a timer which executes a function once the timer expires.
*
* @override
* @param callback Function to be executed.
* @param [delay=0] Delay in ms.
* @returns Timeout ID.
*/
public setTimeout(callback: () => void, delay = 0): NodeJS.Timeout {
const id = this._setTimeout(() => {
this.happyDOM.asyncTaskManager.endTimer(id);
callback();
}, delay);
this.happyDOM.asyncTaskManager.startTimer(id);
return id;
}
/**
* Cancels a timeout previously established by calling setTimeout().
*
* @override
* @param id ID of the timeout.
*/
public clearTimeout(id: NodeJS.Timeout): void {
this._clearTimeout(id);
this.happyDOM.asyncTaskManager.endTimer(id);
}
/**
* Calls a function with a fixed time delay between each call.
*
* @override
* @param callback Function to be executed.
* @param [delay=0] Delay in ms.
* @returns Interval ID.
*/
public setInterval(callback: () => void, delay = 0): NodeJS.Timeout {
const id = this._setInterval(callback, delay);
this.happyDOM.asyncTaskManager.startTimer(id);
return id;
}
/**
* Cancels a timed repeating action which was previously established by a call to setInterval().
*
* @override
* @param id ID of the interval.
*/
public clearInterval(id: NodeJS.Timeout): void {
this._clearInterval(id);
this.happyDOM.asyncTaskManager.endTimer(id);
}
/**
* Mock animation frames with timeouts.
*
* @override
* @param callback Callback.
* @returns Timeout ID.
*/
public requestAnimationFrame(callback: (timestamp: number) => void): NodeJS.Timeout {
return this.setTimeout(() => {
callback(this.performance.now());
});
}
/**
* Mock animation frames with timeouts.
*
* @override
* @param id Timeout ID.
*/
public cancelAnimationFrame(id: NodeJS.Timeout): void {
this.clearTimeout(id);
}
/**
* This method provides an easy, logical way to fetch resources asynchronously across the network.
*
* @override
* @param url URL.
* @param [init] Init.
* @returns Promise.
*/
public async fetch(url: RequestInfo, init?: IRequestInit): Promise<IResponse> {
return await FetchHandler.fetch(this.document, url, init);
}
/**
* Creates a Base64-encoded ASCII string from a binary string (i.e., a string in which each character in the string is treated as a byte of binary data).
*
* @see https://developer.mozilla.org/en-US/docs/Web/API/btoa
* @param data Binay data.
* @returns Base64-encoded string.
*/
public btoa(data: unknown): string {
return Base64.btoa(data);
}
/**
* Decodes a string of data which has been encoded using Base64 encoding.
*
* @see https://developer.mozilla.org/en-US/docs/Web/API/atob
* @see https://infra.spec.whatwg.org/#forgiving-base64-encode.
* @see Https://html.spec.whatwg.org/multipage/webappapis.html#btoa.
* @param data Binay string.
* @returns An ASCII string containing decoded data from encodedData.
*/
public atob(data: unknown): string {
return Base64.atob(data);
}
/**
* Setup of VM context.
*/
protected _setupVMContext(): void {
if (!VM.isContext(this)) {
VM.createContext(this);
// Sets global properties from the VM to the Window object.
// Otherwise "this.Array" will be undefined for example.
VM.runInContext(VMGlobalPropertyScript, this);
}
}
}