UNPKG

nano-jsx

Version:

SSR first, lightweight 1kB JSX library.

125 lines 3.63 kB
import { escapeHtml } from './helpers.js'; export class HTMLElementSSR { constructor(tag) { this.isSelfClosing = false; this.nodeType = null; this.tagName = tag; const selfClosing = [ 'area', 'base', 'br', 'col', 'embed', 'hr', 'img', 'input', 'link', 'meta', 'param', 'source', 'track', 'wbr' ]; this.nodeType = 1; if (selfClosing.indexOf(tag) >= 0) { this._ssr = `<${tag} />`; this.isSelfClosing = true; } else { this._ssr = `<${tag}></${tag}>`; } } get outerHTML() { return this.toString(); } get innerHTML() { return this.innerText; } set innerHTML(text) { this.innerText = text; } get innerText() { var _a; const reg = /(^<[^>]+>)(.+)?(<\/[a-z0-9]+>$|\/>$)/gm; return ((_a = reg.exec(this._ssr)) === null || _a === void 0 ? void 0 : _a[2]) || ''; } set innerText(text) { const reg = /(^<[^>]+>)(.+)?(<\/[a-z0-9]+>$|\/>$)/gm; const replacer = (_match, p1, _p2, p3) => [p1, text, p3].join(''); this._ssr = this._ssr.replace(reg, replacer); } getAttribute(_name) { return null; } get classList() { const element = this._ssr; const classesRegex = /^<\w+.+(\sclass=")([^"]+)"/gm; return { add: (name) => { this.setAttribute('class', name); }, entries: { get length() { const classes = classesRegex.exec(element); if (classes && classes[2]) return classes[2].split(' ').length; return 0; } } }; } toString() { return this._ssr; } setAttributeNS(_namespace, name, value) { this.setAttribute(name, value); } setAttribute(name, value) { const replacer1 = (_match, p1, p2) => `${p1}${escapeHtml(name)}="${escapeHtml(value)}" ${p2}`; const replacer2 = (_match, p1, p2) => `${p1} ${escapeHtml(name)}="${escapeHtml(value)}"${p2}`; if (this.isSelfClosing) this._ssr = this._ssr.replace(/(^<[a-z0-9]+ )(.+)/gm, replacer1); else this._ssr = this._ssr.replace(/(^<[^>]+)(.+)/gm, replacer2); } append(child) { this.appendChild(child); } appendChild(child) { const index = this._ssr.lastIndexOf('</'); this._ssr = this._ssr.substring(0, index) + child + this._ssr.substring(index); } get children() { const reg = /<([a-z0-9]+)((?!<\/\1).)*<\/\1>/gms; const array = []; let match; while ((match = reg.exec(this.innerHTML)) !== null) { array.push(match[0].replace(/[\s]+/gm, ' ')); } return array; } addEventListener(_type, _listener, _options) { } } export class DocumentSSR { constructor() { this.body = this.createElement('body'); this.head = this.createElement('head'); } createElement(tag) { return new HTMLElementSSR(tag); } createElementNS(_URI, tag) { return this.createElement(tag); } createTextNode(text) { return escapeHtml(text); } querySelector(_query) { return undefined; } } const documentSSR = () => { return new DocumentSSR(); }; export { documentSSR }; //# sourceMappingURL=regexDom.js.map