From dbd8dd557bfccf75f8488a2f6ead8f28c3692093 Mon Sep 17 00:00:00 2001 From: Jan Andrle Date: Wed, 6 Sep 2023 14:54:02 +0200 Subject: [PATCH] :recycle: Refactor jsdom register function --- src/jsdom.d.ts | 1 + src/jsdom.js | 39 +++++++++++++++++++++++++++++---------- 2 files changed, 30 insertions(+), 10 deletions(-) diff --git a/src/jsdom.d.ts b/src/jsdom.d.ts index 54af1de..d4fb3a7 100644 --- a/src/jsdom.d.ts +++ b/src/jsdom.d.ts @@ -1,4 +1,5 @@ import { el, assign, on } from "../index.d"; +export * from "../index.d"; export function register(dom: typeof document): Promise<{ el: typeof el, assign: typeof assign, diff --git a/src/jsdom.js b/src/jsdom.js index cadbef4..6a580b8 100644 --- a/src/jsdom.js +++ b/src/jsdom.js @@ -1,11 +1,30 @@ -let keys= []; -export function register(dom){ - const window= dom.window; - if(!keys.length) - keys= Object.getOwnPropertyNames(window).filter((k) => !k.startsWith('_') && !(k in globalThis)); - keys.forEach(key=> globalThis[key]= window[key]); - global.document= window.document - global.window= window - window.console= global.console - return import("../index.js"); +const keys= [ "HTMLElement", "SVGElement", "DocumentFragment", "MutationObserver", "document" ]; +let dom_last; +export let el; +export let assign; +export let on; +export async function register(dom, keys_aditional= []){ + if(dom_last===dom) + return import("../index.js"); + + keys.push(...keys_aditional); + const w= dom.window; + keys.forEach(key=> globalThis[key]= w[key]); + globalThis.window= w; + w.console= globalThis.console; + + const m= await import("../index.js"); + el= m.el; + assign= m.assign; + on= m.on; + return m; +} +export function unregister(){ + if(!dom_last) + return false; + + keys.forEach(key=> Reflect.deleteProperty(globalThis, key)); + Reflect.deleteProperty(globalThis, "window"); + dom_last= undefined; + return true; }