@dark-engine/platform-server
Version:
Dark renderer for server
95 lines (94 loc) • 2.6 kB
JavaScript
import { NodeType, detectIsBoolean, detectIsString } from '@dark-engine/core';
import {
AS_ATTR,
CLASS_ATTR,
CLASS_NAME_ATTR,
EXCLUDE_ATTR_MARK,
TEXTAREA_TAG,
DANGER_HTML_ATTR,
detectIsVoidElement,
} from '@dark-engine/platform-browser';
import { illegal, escape } from '../utils';
class NativeElement {
type;
parentElement = null;
constructor(type) {
this.type = type;
}
}
class TagNativeElement extends NativeElement {
name = null;
attrs = {};
children = [];
constructor(name) {
super(NodeType.TAG);
this.name = name;
}
appendChild(element) {
if (this.attrs[DANGER_HTML_ATTR]) {
illegal(`The element with danger content can't have a children!`);
}
element.parentElement = this;
this.children.push(element);
}
setAttribute(name, value) {
let $name = name === CLASS_NAME_ATTR ? CLASS_ATTR : name;
if ($name[0] === EXCLUDE_ATTR_MARK) return;
if ($name === AS_ATTR) $name = name.slice(1, AS_ATTR.length);
this.attrs[$name] = detectIsString(value) && $name !== DANGER_HTML_ATTR ? escape(value) : value;
}
render(isOpening) {
const content = this.name === TEXTAREA_TAG ? this.children[0]?.render() || '' : this.attrs[DANGER_HTML_ATTR] || '';
const isVoid = detectIsVoidElement(this.name);
const attrs = getAttributes(this.attrs);
const chunk = isOpening
? isVoid
? `<${this.name}${attrs}>`
: `<${this.name}${attrs}>${content || ''}`
: isVoid
? ''
: `</${this.name}>`;
return chunk;
}
renderToString() {
const content = this.children.map(x => x.renderToString()).join('');
return this.render(true) + content + this.render(false);
}
}
class TextNativeElement extends NativeElement {
value = '';
constructor(text) {
super(NodeType.TEXT);
this.value = escape(text);
}
render() {
return this.value;
}
renderToString() {
return this.render();
}
}
class CommentNativeElement extends NativeElement {
value = '';
constructor(text) {
super(NodeType.COMMENT);
this.value = `<!--${escape(text)}-->`;
}
render() {
return this.value;
}
renderToString() {
return this.render();
}
}
function getAttributes(map) {
let attrs = '';
for (const key of Object.keys(map)) {
if (key === DANGER_HTML_ATTR) continue;
const attr = ' ' + (detectIsBoolean(map[key]) ? (map[key] === true ? key : '') : `${key}="${map[key]}"`);
attrs += attr;
}
return attrs;
}
export { NativeElement, TagNativeElement, TextNativeElement, CommentNativeElement };
//# sourceMappingURL=native-element.js.map