Skip to main content

DOM_SHIM_JS

Constant DOM_SHIM_JS 

Source
pub const DOM_SHIM_JS: &str = "// A minimal DOM, sufficient to exercise the renderer.\n//\n// The renderer is the half of the runtime that a signal test cannot reach,\n// and it is where the interesting failures live: keyed reconciliation\n// moving the wrong node, a text binding replacing rather than updating,\n// an attribute effect that never detaches. Testing it needs a document.\n//\n// This is deliberately not a browser. It implements exactly the surface\n// `dom.js` and `elements.js` touch, so that a test failing here means the\n// runtime is wrong rather than the shim being incomplete. Anything the\n// runtime starts using that is missing will throw rather than silently\n// no-op \u{2014} a shim that quietly returns undefined would make the tests lie.\n\nlet nodeSerial = 1;\n\n// `dom.js` tests `child instanceof Node`, so the shim needs a real\n// constructor rather than plain objects \u{2014} otherwise every append silently\n// falls through to the string branch and renders \"[object Object]\".\n/** The `nodeType` constants the runtime actually branches on. */\nconst NODE_TYPE = { element: 1, text: 3, comment: 8, fragment: 11 };\n\nclass Node {\n  // On the prototype, NOT in the object literal below: `Object.assign`\n  // invokes a getter and copies its value, which would freeze\n  // `nextSibling` at creation time. That silently broke `dynamic()` \u{2014}\n  // its `clearBetween` walk found nothing to remove, so `when` appended\n  // each new branch beside the old one instead of replacing it.\n  get nextSibling() {\n    const siblings = this.parentNode ? this.parentNode.childNodes : null;\n    if (!siblings) return null;\n    const index = siblings.indexOf(this);\n    return index >= 0 && index + 1 < siblings.length ? siblings[index + 1] : null;\n  }\n\n  // Live, for the same reason. Generated code walks a clone by\n  // `firstChild`/`nextSibling` offsets computed at compile time, so a\n  // stale value here would point every binding at the wrong node.\n  get firstChild() {\n    return this.childNodes.length > 0 ? this.childNodes[0] : null;\n  }\n\n  get lastChild() {\n    return this.childNodes.length > 0 ? this.childNodes[this.childNodes.length - 1] : null;\n  }\n\n  get nodeType() {\n    return NODE_TYPE[this.kind];\n  }\n}\n\nfunction baseNode(kind) {\n  return Object.assign(new Node(), {\n    __id: nodeSerial++,\n    kind,\n    parentNode: null,\n    childNodes: [],\n\n    appendChild(child) {\n      return this.insertBefore(child, null);\n    },\n\n    insertBefore(child, reference) {\n      if (child.kind === \'fragment\') {\n        // A fragment inserts its children and empties itself, as in a browser.\n        for (const grandchild of [...child.childNodes]) {\n          this.insertBefore(grandchild, reference);\n        }\n        child.childNodes.length = 0;\n        return child;\n      }\n      if (child.parentNode) child.parentNode.removeChild(child);\n      const index = reference === null ? this.childNodes.length : this.childNodes.indexOf(reference);\n      if (index < 0) throw new Error(\'insertBefore: reference node is not a child\');\n      this.childNodes.splice(index, 0, child);\n      child.parentNode = this;\n      return child;\n    },\n\n    removeChild(child) {\n      const index = this.childNodes.indexOf(child);\n      if (index < 0) throw new Error(\'removeChild: node is not a child\');\n      this.childNodes.splice(index, 1);\n      child.parentNode = null;\n      return child;\n    },\n\n    remove() {\n      if (this.parentNode) this.parentNode.removeChild(this);\n    },\n\n    replaceChildren(...nodes) {\n      for (const child of [...this.childNodes]) this.removeChild(child);\n      for (const node of nodes) this.appendChild(node);\n    },\n\n    // What `template()` hands out per instantiation. A shallow clone would\n    // silently produce an empty region, so `deep` is honoured rather than\n    // ignored.\n    cloneNode(deep = false) {\n      let copy;\n      if (this.kind === \'element\') {\n        copy = createElement(this.tagName);\n        for (const [name, value] of Object.entries(this.attributes)) {\n          copy.setAttribute(name, value);\n        }\n      } else if (this.kind === \'text\') {\n        copy = createTextNode(this.nodeValue);\n      } else if (this.kind === \'comment\') {\n        copy = createComment(this.nodeValue);\n      } else {\n        copy = createDocumentFragment();\n      }\n      if (deep) {\n        for (const child of this.childNodes) copy.appendChild(child.cloneNode(true));\n      }\n      return copy;\n    },\n\n    // The \u{a7}16.3.6 parity test\'s assertion: the tree `elements.js` builds\n    // node by node must equal the tree the compiler\'s markup parses into.\n    // Attribute ORDER is not part of the comparison, as in a browser.\n    isEqualNode(other) {\n      if (!other || this.kind !== other.kind) return false;\n      if (this.kind === \'text\' || this.kind === \'comment\') {\n        return this.nodeValue === other.nodeValue;\n      }\n      if (this.kind === \'element\') {\n        if (this.tagName !== other.tagName) return false;\n        const names = Object.keys(this.attributes).sort();\n        const otherNames = Object.keys(other.attributes).sort();\n        if (names.length !== otherNames.length) return false;\n        for (let i = 0; i < names.length; i += 1) {\n          if (names[i] !== otherNames[i]) return false;\n          if (this.attributes[names[i]] !== other.attributes[names[i]]) return false;\n        }\n      }\n      if (this.childNodes.length !== other.childNodes.length) return false;\n      for (let i = 0; i < this.childNodes.length; i += 1) {\n        if (!this.childNodes[i].isEqualNode(other.childNodes[i])) return false;\n      }\n      return true;\n    },\n  });\n}\n\n// The two `innerHTML` accessors, defined once and shared by every node\n// rather than rebuilt per element.\n//\n// They were built inside `createElement`, which allocated a descriptor and\n// two closures for every node the suite made. Keyed reconciliation makes\n// thousands, and the extra garbage was enough to bring a collection down\n// inside a `Set` iteration \u{2014} where this engine\'s finaliser panics on a\n// borrow it already holds. Sharing them is the same behaviour with a\n// fraction of the allocation: both read `this`, so neither needs a\n// per-node binding.\n\n// `template()` is the whole of the emitted render path: one static HTML\n// string parsed once, cloned per instantiation. Without `content` and an\n// `innerHTML` that really parses, the shim would make every generated\n// program render nothing while reporting no error.\nconst TEMPLATE_INNER_HTML = {\n  get() {\n    return serialize(this.content);\n  },\n  set(value) {\n    this.content = parseHtml(String(value));\n  },\n};\n\n// `markup()` in `dom.js` assigns `innerHTML` on an ordinary element \u{2014} the\n// one place in the runtime that parses HTML. It must really parse here\n// too, or a test asserting the rendered structure of a post would pass\n// against a shim that stored a string and built no nodes.\nconst ELEMENT_INNER_HTML = {\n  get() {\n    return serialize(this);\n  },\n  set(value) {\n    const parsed = parseHtml(String(value));\n    for (const child of this.childNodes) child.parentNode = null;\n    this.childNodes = [];\n    for (const child of [...parsed.childNodes]) {\n      child.parentNode = this;\n      this.childNodes.push(child);\n    }\n  },\n};\n\n// `NumberInput` and `DateInput` bind through `valueAsNumber` in both\n// directions (#45, #48), so a shim that did not derive it from `value`\n// would make every such binding read `undefined` and write\n// unconditionally \u{2014} the suite would pass over a control that does\n// nothing. Shared rather than built per node, for the allocation reason\n// the two `innerHTML` descriptors above are.\n//\n// \u{26a0}\u{fe0f} THIS IS NOT THE BROWSER\'S ALGORITHM AND CANNOT BE. A real number\n// field runs HTML\'s value sanitisation, which empties `value` while the\n// reader is part way through `1.` or `-`; this keeps the text it was\n// given. So the half-typed states belong to the browser suite\n// (`zdc-cli/tests/browser.rs`), exactly as the parser\'s insertion modes\n// do. What is faithful here is everything either side of them: a complete\n// number, a complete `YYYY-MM-DD`, and the empty box.\nconst VALUE_AS_NUMBER = {\n  get() {\n    if (this.attributes.type === \'date\') {\n      const day = /^(\\d{4})-(\\d{2})-(\\d{2})$/.exec(this.value);\n      return day ? Date.UTC(Number(day[1]), Number(day[2]) - 1, Number(day[3])) : NaN;\n    }\n    return this.value.trim() === \'\' ? NaN : Number(this.value);\n  },\n  set(number) {\n    if (Number.isNaN(number)) {\n      this.value = \'\';\n    } else if (this.attributes.type === \'date\') {\n      this.value = new Date(number).toISOString().slice(0, 10);\n    } else {\n      this.value = String(number);\n    }\n  },\n  configurable: true,\n};\n\nfunction createElement(tag) {\n  const node = baseNode(\'element\');\n  node.tagName = tag;\n  node.attributes = {};\n  node.listeners = {};\n  // `dom.js` routes `value` and `checked` to properties rather than\n  // attributes, guarded by `\'value\' in node`. Form controls must therefore\n  // have them present, and other elements must not.\n  if (tag === \'input\' || tag === \'textarea\' || tag === \'select\') {\n    node.value = \'\';\n    node.checked = false;\n  }\n  if (tag === \'input\') {\n    Object.defineProperty(node, \'valueAsNumber\', VALUE_AS_NUMBER);\n  }\n  node.style = {\n    properties: {},\n    setProperty(name, value) {\n      this.properties[name] = value;\n    },\n  };\n  node.setAttribute = function (name, value) {\n    this.attributes[name] = String(value);\n  };\n  node.removeAttribute = function (name) {\n    delete this.attributes[name];\n  };\n  node.addEventListener = function (event, handler) {\n    (this.listeners[event] ??= []).push(handler);\n  };\n  // Test-only: deliver an event without a full event system.\n  node.fire = function (event, payload = {}) {\n    for (const handler of this.listeners[event] ?? []) {\n      handler({ target: this, ...payload });\n    }\n  };\n  // `template()` is the whole of the emitted render path: one static HTML\n  // string parsed once, cloned per instantiation. Without `content` and an\n  // `innerHTML` that really parses, the shim would make every generated\n  // program render nothing while reporting no error.\n  if (tag === \'template\') {\n    node.content = createDocumentFragment();\n    Object.defineProperty(node, \'innerHTML\', TEMPLATE_INNER_HTML);\n  } else {\n    Object.defineProperty(node, \'innerHTML\', ELEMENT_INNER_HTML);\n  }\n  return node;\n}\n\n// --- the HTML parser ------------------------------------------------------\n//\n// Only what the compiler\'s nine built-in elements can produce: start tags\n// with quoted or bare attribute values, end tags, void elements, comments,\n// and text with the five escapes the emitter writes. Anything it does not\n// understand throws, because a parser that silently skipped a construct\n// would move every subsequent `nextSibling` offset by one and point every\n// binding after it at the wrong node \u{2014} the exact failure \u{a7}16.10 names as\n// having no compile-time signal.\n\nconst VOID_ELEMENTS = new Set([\n  \'area\', \'base\', \'br\', \'col\', \'embed\', \'hr\', \'img\',\n  \'input\', \'link\', \'meta\', \'param\', \'source\', \'track\', \'wbr\',\n]);\n\nfunction decodeEntities(text) {\n  return text\n    .replace(/&lt;/g, \'<\')\n    .replace(/&gt;/g, \'>\')\n    .replace(/&quot;/g, \'\"\')\n    .replace(/&#39;/g, \"\'\")\n    .replace(/&amp;/g, \'&\');\n}\n\n/** Parse a start tag, returning its name, attributes, and end offset. */\nfunction parseStartTag(source, start) {\n  let i = start + 1;\n  let name = \'\';\n  while (i < source.length && /[A-Za-z0-9-]/.test(source[i])) name += source[i++];\n  if (name === \'\') throw new Error(`template HTML: expected a tag name at ${start}`);\n\n  const attributes = {};\n  for (;;) {\n    while (i < source.length && /\\s/.test(source[i])) i += 1;\n    if (i >= source.length) throw new Error(\'template HTML: unterminated start tag\');\n    if (source[i] === \'/\') {\n      i += 1;\n      continue;\n    }\n    if (source[i] === \'>\') {\n      i += 1;\n      break;\n    }\n\n    let attribute = \'\';\n    while (i < source.length && !/[\\s=>/]/.test(source[i])) attribute += source[i++];\n    if (attribute === \'\') throw new Error(`template HTML: expected an attribute name at ${i}`);\n\n    let value = \'\';\n    while (i < source.length && /\\s/.test(source[i])) i += 1;\n    if (source[i] === \'=\') {\n      i += 1;\n      while (i < source.length && /\\s/.test(source[i])) i += 1;\n      const quote = source[i];\n      if (quote === \'\"\' || quote === \"\'\") {\n        i += 1;\n        const close = source.indexOf(quote, i);\n        if (close < 0) throw new Error(\'template HTML: unterminated attribute value\');\n        value = decodeEntities(source.slice(i, close));\n        i = close + 1;\n      } else {\n        while (i < source.length && !/[\\s>]/.test(source[i])) value += source[i++];\n        value = decodeEntities(value);\n      }\n    }\n    attributes[attribute] = value;\n  }\n  return { name, attributes, end: i };\n}\n\nfunction parseHtml(source) {\n  const root = createDocumentFragment();\n  const stack = [root];\n  const top = () => stack[stack.length - 1];\n  let i = 0;\n\n  const addText = (raw) => {\n    if (raw.length > 0) top().appendChild(createTextNode(decodeEntities(raw)));\n  };\n\n  while (i < source.length) {\n    const lt = source.indexOf(\'<\', i);\n    if (lt < 0) {\n      addText(source.slice(i));\n      break;\n    }\n    addText(source.slice(i, lt));\n\n    if (source.startsWith(\'<!--\', lt)) {\n      const close = source.indexOf(\'-->\', lt + 4);\n      if (close < 0) throw new Error(\'template HTML: unterminated comment\');\n      top().appendChild(createComment(source.slice(lt + 4, close)));\n      i = close + 3;\n      continue;\n    }\n\n    if (source.startsWith(\'</\', lt)) {\n      const close = source.indexOf(\'>\', lt);\n      if (close < 0) throw new Error(\'template HTML: unterminated end tag\');\n      if (stack.length === 1) throw new Error(\'template HTML: end tag with no open element\');\n      stack.pop();\n      i = close + 1;\n      continue;\n    }\n\n    const tag = parseStartTag(source, lt);\n    const element = createElement(tag.name);\n    for (const [name, value] of Object.entries(tag.attributes)) {\n      element.setAttribute(name, value);\n    }\n    top().appendChild(element);\n    if (!VOID_ELEMENTS.has(tag.name)) stack.push(element);\n    i = tag.end;\n  }\n\n  if (stack.length !== 1) throw new Error(\'template HTML: unclosed element\');\n  return root;\n}\n\nfunction createTextNode(value) {\n  const node = baseNode(\'text\');\n  node.nodeValue = String(value);\n  return node;\n}\n\nfunction createComment(value) {\n  const node = baseNode(\'comment\');\n  node.nodeValue = String(value);\n  return node;\n}\n\nfunction createDocumentFragment() {\n  const node = baseNode(\'fragment\');\n  node.append = function (...children) {\n    for (const child of children) this.appendChild(child);\n  };\n  return node;\n}\n\n// The document\'s own listener table, for `keys.js`.\n//\n// A pair rather than one function, because what `keys.js` claims is that a\n// discarded listener *stops firing*, and a shim whose `removeEventListener`\n// is a no-op would agree with a runtime that never called it. `fire` walks\n// the registered list, so a listener that was removed is a listener that is\n// not there.\nconst documentListeners = {};\n\nconst document = {\n  createElement,\n  createTextNode,\n  createComment,\n  createDocumentFragment,\n  addEventListener(event, handler) {\n    (documentListeners[event] ??= []).push(handler);\n  },\n  removeEventListener(event, handler) {\n    const registered = documentListeners[event];\n    if (!registered) return;\n    const at = registered.indexOf(handler);\n    if (at !== -1) registered.splice(at, 1);\n  },\n  /** How many listeners are registered \u{2014} the leak check. */\n  listenerCount(event) {\n    return (documentListeners[event] ?? []).length;\n  },\n  /** Test-only: deliver `payload` to every registered listener. */\n  fire(event, payload = {}) {\n    for (const handler of (documentListeners[event] ?? []).slice()) {\n      handler({ type: event, target: null, ...payload });\n    }\n  },\n};\n\n/** Serialise a subtree so assertions can be written against a string. */\nfunction html(node) {\n  if (node.kind === \'text\') return node.nodeValue;\n  if (node.kind === \'comment\') return \'\';\n  const inner = node.childNodes.map(html).join(\'\');\n  if (node.kind === \'fragment\') return inner;\n  const attrs = Object.entries(node.attributes)\n    .map(([k, v]) => (v === \'\' ? ` ${k}` : ` ${k}=\"${v}\"`))\n    .join(\'\');\n  return `<${node.tagName}${attrs}>${inner}</${node.tagName}>`;\n}\n\n/**\n * Serialise a subtree for a parity assertion, holding back nothing.\n *\n * `html` above drops comments and form-control state, which is right for\n * readable assertions and wrong for proving two render strategies agree:\n * a missing anchor pair or an unwritten `input.value` would compare equal.\n * This one shows both.\n */\nfunction serialize(node) {\n  if (node.kind === \'text\') return node.nodeValue;\n  if (node.kind === \'comment\') return `<!--${node.nodeValue}-->`;\n  const inner = node.childNodes.map(serialize).join(\'\');\n  if (node.kind === \'fragment\') return inner;\n\n  const attrs = Object.entries(node.attributes)\n    .map(([k, v]) => (v === \'\' ? ` ${k}` : ` ${k}=\"${v}\"`))\n    .join(\'\');\n  let state = \'\';\n  if (\'value\' in node) state += ` .value=\"${node.value}\"`;\n  if (\'checked\' in node && node.checked) state += \' .checked\';\n  return `<${node.tagName}${attrs}${state}>${inner}</${node.tagName}>`;\n}\n\n/** Every element in a subtree, in document order. */\nfunction walk(node, out = []) {\n  if (node.kind === \'element\') out.push(node);\n  for (const child of node.childNodes) walk(child, out);\n  return out;\n}\n\n/** The first element whose tag matches, or null. */\nfunction findTag(node, tagName) {\n  return walk(node).find((n) => n.tagName === tagName) ?? null;\n}\n\n// --- the uncaught-error channel -------------------------------------------\n//\n// `dom.js` reports a throwing handler through `reportError` (#139), which\n// in a browser fires `window.onerror` and the `error` event. There is no\n// such channel here, so this one records: a test can then assert what a\n// page would have been told, which is the part of the decision that would\n// otherwise only be checkable in a browser.\n//\n// `var` rather than `const`, so a test can replace it for one case and put\n// it back \u{2014} which is what the browser lets a page do too.\nvar reported = [];\nvar reportError = function (error) {\n  reported.push(error);\n};\n";
Expand description

The minimal DOM the runtime and everything downstream of it run against when there is no browser.

Exposed from here because four crates were reaching for it and only one of them owns it. They used to reach across the workspace with ../../zdc-runtime/tests/dom-shim.js, which works in a workspace build and does not survive cargo package: a crate may only embed files inside its own directory. One copy, one owner, and a published zdc-runtime that compiles.