1
0
mirror of https://codeberg.org/setop/elm-scripting synced 2025-11-08 21:49:57 +00:00
Files
elm-scripting/dom.js
2025-09-26 01:22:28 +02:00

59 lines
1.6 KiB
JavaScript

function Node(parent, tag) {
this.parentNode = parent; // Node
this.pos = 0; // position in siblings list
this.tagName = tag;
this.text = null;
// attributes are stored directly on the node object
// see https://github.com/elm/virtual-dom/blob/master/src/Elm/Kernel/VirtualDom.js#L511
this.children = []; // List of Node
this.replaceChild = (newNode, domNode) => {
this.children[domNode.pos-1] = newNode;
newNode.pos = domNode.pos;
};
if (parent != null) {
this.pos = parent.children.push(this);
}
this.appendChild = (node) => {
node.pos = this.children.push(node);
}
this.dump = (d=0) => {
if (this.text != null) {
print(this.text);
return
}
std.printf("<%s", this.tagName)
// Set.difference(other) is not avalable in qjs
for (a of Object.keys(this)) {
if (!NodeKeys.has(a)) {
std.printf(' %s="%s"', a, this[a])
}
}
if (this.children.length==0) {
print("/>")
} else {
print(">")
for (c of this.children) {
c.dump(d+1)
}
print("</"+this.tagName+">");
}
}
return this;
}
var document = new Node(null, "document");
var target = new Node(document, "target");
const NodeKeys = new Set(Object.keys(target));
// getElementById is only used once, to get node Elm must hook into.
// so we don't need a full fledge implementation with lookup facilities
// just to return the target node
document.getElementById = (_id) => { return target}
document.createElement = (tag) => new Node(null, tag);
document.createTextNode = (text) => { t = new Node(null, "#text" ); t.text = text; return t }
try {
// here will come the Elm app code