1
0
mirror of https://github.com/jaandrle/deka-dom-el synced 2024-11-23 17:19:37 +01:00
deka-dom-el/bs/docs/jsdom.js

43 lines
1.4 KiB
JavaScript
Raw Normal View History

2023-09-26 16:02:10 +02:00
import { JSDOM } from "jsdom";
const html_default= "<!doctype html><html><head><meta charset=\"utf-8\"></head><body></body></html>";
let keys= [];
let dom= null;
import { relative } from 'node:path';
import { writeFileSync } from 'node:fs';
2023-11-30 17:05:19 +01:00
/** @param {string} html */
2023-09-26 16:02:10 +02:00
export function createHTMl(html, options= {}){
if(!html) html= html_default;
if(dom) cleanHTML();
// set a default url if we don't get one - otherwise things explode when we copy localstorage keys
if (!('url' in options)) { Object.assign(options, { url: 'http://localhost:3000' }) }
2024-11-22 16:26:42 +01:00
2023-09-26 16:02:10 +02:00
dom= new JSDOM(html, options);
const window= dom.window;
return {
dom,
writeToFS({ html, css }){
if(css) this.style.writeToFile(css, relative(html, css).slice(1));
if(html) writeFileSync(html, dom.serialize());
},
2023-11-30 17:05:19 +01:00
/** @param {string[]} [names] */
registerGlobally(...names){
keys.push(...names);
if(!keys.length)
keys= Object.getOwnPropertyNames(window).filter((k) => !k.startsWith('_') && !(k in globalThis));
keys.forEach(key=> globalThis[key]= window[key]);
globalThis.document= window.document
globalThis.window= window
window.console= globalThis.console
return this;
},
serialize(){ return dom.serialize(); },
window, document: window.document
2023-09-26 16:02:10 +02:00
};
}
export function cleanHTML(){
if(!dom) return;
keys.forEach(key=> delete globalThis[key]);
2023-11-30 17:05:19 +01:00
keys.length= 0;
2023-09-26 16:02:10 +02:00
dom= false;
}