nehan
Version:
Html layout engine for paged-media written in Typescript
76 lines • 3.02 kB
JavaScript
import { CssStyleSheet, NehanElement, UserAgentStyles, SelectorCache, CssLoader, Config, PseudoElementInitializer, ValidBlockSelector, } from "./public-api";
let defaultOptions = {
styleSheets: []
};
export class NehanDocument {
constructor(source, options = defaultOptions) {
this.source = Config.normalizeHtml(source);
this.styleSheets = [
new CssStyleSheet(UserAgentStyles)
].concat(options.styleSheets || []);
this.specStyleSheet = this.styleSheets.reduce((acm, stylesheet) => {
return acm.mergeStyleSheet(stylesheet);
}, new CssStyleSheet({}));
this.selectorCache = new SelectorCache();
this.selectorCache.clear();
this.$document = new DOMParser().parseFromString(this.source, "text/html");
if (Config.debugLayout) {
console.log(this.$document.body);
}
this.documentElement = this.createNehanElement(this.$document.documentElement);
const body = this.documentElement.querySelector("body");
if (!body) {
throw new Error("body not found");
}
this.body = body;
this.body.parent = this.documentElement;
this.body.acceptEffectorAll(new PseudoElementInitializer(this.specStyleSheet.getPseudoRules()));
CssLoader.loadAll(this.body);
this.body.acceptChildFilter(ValidBlockSelector.instance);
}
querySelectorAll(query) {
return this.documentElement.querySelectorAll(query);
}
querySelector(query) {
return this.documentElement.querySelector(query);
}
getElementById(id) {
return this.querySelector("#" + id);
}
getSelectorCache(selector) {
return this.selectorCache.getCache(selector);
}
addStyleSheet(stylesheet) {
this.styleSheets.push(stylesheet);
return this;
}
addSelectorCache(tag_name, element) {
this.selectorCache.addCache(tag_name, element);
}
createElement(tag_name) {
let element = this.createNativeElement(tag_name);
return this.createNehanElement(element);
}
createNativeElement(tag_name) {
return this.$document.createElement(tag_name);
}
createNehanElement(node) {
const tagName = ((node instanceof Element) ? node.tagName : (node instanceof Text) ? "(text)" : "??").toLowerCase();
if ((tagName === "body" || tagName === "html") && this.selectorCache.hasCache(tagName)) {
return this.selectorCache.getCache(tagName)[0];
}
const element = new NehanElement(node, this);
if (element.tagName === "body") {
this.body = element;
}
element.root = this;
this.selectorCache.addCache(tagName, element);
this.selectorCache.addCache("*", element);
return element;
}
createTextNode(text) {
const element = this.$document.createTextNode(text);
return this.createNehanElement(element);
}
}
//# sourceMappingURL=nehan-document.js.map