kopular 1.1.0 → 1.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "kopular",
3
- "version": "1.1.0",
3
+ "version": "1.1.1",
4
4
  "description": "Kopular: a small component framework for KopScript — components, reactive state, constructor-injected services, routing, real compiled templates, and HTTP, with no DI container",
5
5
  "type": "module",
6
6
  "license": "MIT",
package/src/vdom.js CHANGED
@@ -142,11 +142,18 @@ export function Patch(parent, old, updated) {
142
142
  if ((updated.RawHtml !== oldTree.RawHtml)) {
143
143
  realNode.innerHTML = updated.RawHtml;
144
144
  }
145
+ } else if ((updated.Children.length > 0)) {
146
+ if ((oldTree.Children.length === 0)) {
147
+ realNode.textContent = "";
148
+ }
149
+ PatchChildren(realNode, oldTree.Children, updated.Children);
145
150
  } else {
151
+ if ((oldTree.Children.length > 0)) {
152
+ PatchChildren(realNode, oldTree.Children, []);
153
+ }
146
154
  if ((updated.TextContent !== oldTree.TextContent)) {
147
155
  realNode.textContent = updated.TextContent;
148
156
  }
149
- PatchChildren(realNode, oldTree.Children, updated.Children);
150
157
  }
151
158
  if ((updated.ClassName !== oldTree.ClassName)) {
152
159
  realNode.className = updated.ClassName;
package/src/vdom.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"vdom.js","sources":["vdom.ks"],"sourcesContent":["using \"./dom\";\nusing \"./velement\";\n\n// The diff/patch engine behind real vdom diffing: Component.Update() (see\n// component.ks) calls Patch() with the PREVIOUS render's VElement tree\n// (which carries each node's real, live DOM counterpart via its own\n// RealNode field) and the NEW tree Render() just produced, and gets back\n// real DOM mutated/reused in place wherever possible instead of a full\n// subtree rebuild.\n//\n// Deliberately never reads the live DOM back to rediscover structure (no\n// \"get current children\"/\"get current tag\" API exists, or is needed) —\n// the retained *previous* VElement tree already records everything Patch()\n// needs to know about what's currently there. This is what makes the whole\n// approach work without a generic children/attributes read-back API that\n// KopScript's narrow, curated DOM binding doesn't have.\n\n// A component-like thing Batching (below) can flush once every DOM-event-\n// triggered Update() call inside one batch has registered itself. Declared\n// HERE, not in component.ks, specifically so THIS file's own Materialize/\n// Patch — which need to start/stop a batch around every real event\n// dispatch — never have to `using \"./component\"`: component.ks already\n// `using`s this file for Materialize/Patch themselves, and KopScript\n// rejects a circular `using` outright. Component (component.ks) is the\n// one real implementer, via `class Component : Flushable`.\ninterface Flushable {\n void FlushUpdate();\n}\n\n// Coalesces every Update() call made while a real DOM event handler\n// Kopular itself attached (see Materialize/Patch below, both of which wrap\n// each listener in Batching.Run before attaching it) into one flush per\n// affected component, applied once that handler returns — not one flush\n// per state<T> write inside it. See Component.Update()'s own comment\n// (component.ks) for the full rationale; this is just the mechanism.\n//\n// Deliberately class-level, shared across every batch/component rather\n// than per-instance — a single click can trigger Update() on more than one\n// component (e.g. a shared service's state<T> notifying two sibling\n// pages), and all of them need to flush together, once, when that one\n// handler finishes.\nclass Batching {\n private static number Depth = 0;\n private static Flushable[] Pending = [];\n\n public static bool IsActive() {\n return Batching.Depth > 0;\n }\n\n public static void Defer(Flushable f) {\n if (!Batching.Pending.Includes(f)) {\n Batching.Pending = Batching.Pending.Push(f);\n }\n }\n\n // `try`/`finally`, not a bare sequence: a handler that throws must still\n // decrement Depth and flush whatever already-triggered renders are\n // pending, or one uncaught exception would wedge every future click/\n // input on the page into \"always batching, never rendering.\" The\n // exception itself still propagates unchanged — this never catches it,\n // only guarantees the cleanup runs.\n public static void Run(() => void action) {\n Batching.Depth = Batching.Depth + 1;\n try {\n action();\n } finally {\n Batching.Depth = Batching.Depth - 1;\n if (Batching.Depth == 0) {\n Flushable[] toFlush = Batching.Pending;\n Batching.Pending = [];\n foreach (Flushable f in toFlush) {\n f.FlushUpdate();\n }\n }\n }\n }\n}\n\n// The runtime half of kopscript's `styles from \"<path>.css\";` (see its own\n// README/LLM.md \"Templates\" section) — the compiler rewrites a class's own\n// stylesheet at compile time (every selector scoped to that class's\n// `data-kop-scope=\"<id>\"` attribute) and splices exactly one\n// `ScopedStyles.Inject(id, css);` call into its constructor. Same\n// static-array-registry-with-Includes-dedup shape as Batching above,\n// deliberately: dedup here is per component TYPE, not per instance — every\n// instance's constructor calls Inject with the same `id`/`css` (both\n// compile-time constants for that class), so only the first one actually\n// creates a <style> tag; the rest are no-ops. Never removed once injected\n// — a scoped stylesheet is global infrastructure for as long as the page\n// lives, not per-instance content Teardown() would ever need to clean up.\nclass ScopedStyles {\n private static string[] Injected = [];\n\n public static void Inject(string scopeId, string css) {\n if (!ScopedStyles.Injected.Includes(scopeId)) {\n ScopedStyles.Injected = ScopedStyles.Injected.Push(scopeId);\n Element style = document.createElement(\"style\");\n style.setAttribute(\"data-kop-scope-sheet\", scopeId);\n style.textContent = css;\n document.head.appendChild(style);\n }\n }\n}\n\n// Builds a brand-new, fully real DOM subtree from a VElement tree with no\n// diffing at all — first mount, or whenever Patch() decides a subtree must\n// be replaced outright (no previous node to reuse, or the tag changed).\n// Mutates `tree.RealNode` (and recursively every descendant's) as a side\n// effect, so the tree this was called on becomes the new \"previous tree\"\n// the next Patch() call diffs against. Takes `parent` — every call site\n// already knows it (either Patch's own `parent` parameter, or the real\n// element a recursive child call is about to be appendChild'd into) —\n// solely to hand to a Mounted slot's own MountAsChild, which needs to\n// remember its real parent for THAT component's own future self-triggered\n// re-renders; an ordinary (non-Mounted) VElement never uses it.\nElement Materialize(VElement tree, Element parent) {\n Mountable? maybeMounted = tree.Mounted;\n if (maybeMounted != null) {\n Mountable m = maybeMounted;\n Element mountedRoot = m.MountAsChild(parent);\n tree.RealNode = mountedRoot;\n return mountedRoot;\n }\n\n Element el = document.createElement(tree.Tag);\n\n if (tree.RawHtml.Length > 0) {\n el.innerHTML = tree.RawHtml;\n } else if (tree.Children.Length > 0) {\n foreach (VElement child in tree.Children) {\n el.appendChild(Materialize(child, el));\n }\n } else {\n el.textContent = tree.TextContent;\n }\n\n el.className = tree.ClassName;\n el.id = tree.Id;\n el.value = tree.Value;\n\n for (number i = 0; i < tree.ExtraNames.Length; i = i + 1) {\n el.setAttribute(tree.ExtraNames[i], tree.ExtraValues[i]);\n }\n if (tree.Disabled) {\n el.disabled = true;\n }\n if (tree.Checked) {\n el.checked = true;\n }\n\n // Skip attaching VElement's own shared no-op (see velement.ks) — it does\n // nothing when invoked, so registering it costs real work (a listener\n // list entry, held onto for nothing) for zero benefit. A real handler\n // (never equal to the shared no-op) always gets attached as before —\n // wrapped in Batching.Run so every Update() it triggers coalesces with\n // any others from the same dispatch (see Component.Update()'s own\n // comment). The wrapper itself, not tree.OnClick, is what actually gets\n // registered — recorded on tree.AttachedOnClick (velement.ks) so a later\n // Patch() can remove this exact reference, not the handler value itself.\n if (tree.OnClick != NoOpEventHandler) {\n (Event) => void wrapped = (Event e) => Batching.Run(() => tree.OnClick(e));\n tree.AttachedOnClick = wrapped;\n el.addEventListener(\"click\", wrapped);\n }\n if (tree.OnInput != NoOpEventHandler) {\n (Event) => void wrapped = (Event e) => Batching.Run(() => tree.OnInput(e));\n tree.AttachedOnInput = wrapped;\n el.addEventListener(\"input\", wrapped);\n }\n if (tree.OnBlur != NoOpEventHandler) {\n (Event) => void wrapped = (Event e) => Batching.Run(() => tree.OnBlur(e));\n tree.AttachedOnBlur = wrapped;\n el.addEventListener(\"blur\", wrapped);\n }\n if (tree.OnChange != NoOpEventHandler) {\n (Event) => void wrapped = (Event e) => Batching.Run(() => tree.OnChange(e));\n tree.AttachedOnChange = wrapped;\n el.addEventListener(\"change\", wrapped);\n }\n\n tree.RealNode = el;\n return el;\n}\n\n// Diffs `updated` against `old` (the previous render's tree for this exact\n// position, or null if there is none — first mount) and returns the real\n// DOM node now representing `updated`, reusing `old`'s real node in place\n// whenever the tag matches. `parent` is only used to attach/replace at the\n// top of whatever subtree Patch() is called on — child-level attach/replace\n// happens inside PatchChildren.\n//\n// Deliberately all positive-branch `if (x != null) { ... } else { ... }`,\n// never an early-return guard clause — KopScript's nullable narrowing is\n// scope-based, not reachability-based, so `if (x == null) { return; }\n// use(x);` would NOT narrow `x` afterward (see KopScript's own LLM.md \"Common\n// mistakes\"). Every nullable member-access path (`oldTree.RealNode`,\n// never narrows directly either) is read into a local first for the same\n// reason.\nElement Patch(Element parent, VElement? old, VElement updated) {\n Mountable? newMounted = updated.Mounted;\n Mountable? oldMounted = null;\n if (old != null) {\n VElement oldTreeForMount = old;\n oldMounted = oldTreeForMount.Mounted;\n }\n\n // A live child slot (VElement.Mounted — see velement.ks) is handled\n // entirely separately from the ordinary Tag-based logic below: it's not\n // Kopular's own DOM element to create/reuse at all, and its \"same node\n // or replace\" decision is instance identity (== on the Mountable itself,\n // real reference equality — interfaces erase to the underlying object),\n // not Tag equality.\n if (newMounted != null) {\n Mountable nm = newMounted;\n if (oldMounted != null) {\n Mountable om = oldMounted;\n if (om == nm) {\n // Same instance still in this slot: patch it in place, don't touch\n // the DOM position at all (its own real node, reused or not, is\n // already exactly where it needs to be).\n Element reused = nm.PatchAsChild();\n updated.RealNode = reused;\n return reused;\n }\n }\n // First time this slot has anything mounted, or a DIFFERENT instance\n // took over the slot: release whatever was here, then mount fresh.\n UnmountPrevious(parent, old, oldMounted);\n Element created = nm.MountAsChild(parent);\n parent.appendChild(created);\n updated.RealNode = created;\n return created;\n }\n\n if (oldMounted != null) {\n // Slot reverted from a live component back to plain content: release\n // the old one, then fall through to an ordinary fresh materialize.\n UnmountPrevious(parent, old, oldMounted);\n Element created = Materialize(updated, parent);\n parent.appendChild(created);\n return created;\n }\n\n if (old != null) {\n VElement oldTree = old;\n Element? maybeOldNode = oldTree.RealNode;\n if (maybeOldNode != null) {\n Element realNode = maybeOldNode;\n if (oldTree.Tag != updated.Tag) {\n Element created = Materialize(updated, parent);\n parent.replaceChild(created, realNode);\n return created;\n } else {\n updated.RealNode = realNode;\n\n if (updated.RawHtml.Length > 0 || oldTree.RawHtml.Length > 0) {\n if (updated.RawHtml != oldTree.RawHtml) {\n realNode.innerHTML = updated.RawHtml;\n }\n } else {\n if (updated.TextContent != oldTree.TextContent) {\n realNode.textContent = updated.TextContent;\n }\n PatchChildren(realNode, oldTree.Children, updated.Children);\n }\n\n if (updated.ClassName != oldTree.ClassName) {\n realNode.className = updated.ClassName;\n }\n if (updated.Id != oldTree.Id) {\n realNode.id = updated.Id;\n }\n // Always assigned, never conditionally on updated.Value != oldTree.Value\n // — unlike TextContent/ClassName/Id, an <input>/<select>'s live value\n // can diverge from the last-recorded VElement.Value purely through\n // user interaction (typing, picking an option) with no Update() ever\n // running in between (a real, deliberate pattern — see KopularDemo's\n // dogs_page.ks, which never Update()s on input/change). The recorded\n // oldTree.Value only reflects the tree as of the last actual render,\n // so comparing against it can't tell \"genuinely unchanged\" apart from\n // \"changed live in the DOM since then, framework never told\" — the\n // same reason a real \"controlled input\" (React's own term for this)\n // always writes value on every render rather than diffing it.\n realNode.value = updated.Value;\n\n // Same-length is the overwhelmingly common case (the same Render()\n // code path calls SetAttr the same number of times, in the same\n // order, on every call) — compare aligned by index and only touch\n // the real DOM for an entry that actually changed, rather than\n // reapplying every extra attribute on every patch regardless. A\n // length mismatch (the rarer case: a SetAttr call was added,\n // removed, or made conditional between renders) falls back to\n // reapplying everything, since index-aligned comparison isn't\n // meaningful once the two arrays don't correspond entry-for-entry.\n if (updated.ExtraNames.Length == oldTree.ExtraNames.Length) {\n for (number i = 0; i < updated.ExtraNames.Length; i = i + 1) {\n if (updated.ExtraNames[i] != oldTree.ExtraNames[i] || updated.ExtraValues[i] != oldTree.ExtraValues[i]) {\n realNode.setAttribute(updated.ExtraNames[i], updated.ExtraValues[i]);\n }\n }\n } else {\n for (number i = 0; i < updated.ExtraNames.Length; i = i + 1) {\n realNode.setAttribute(updated.ExtraNames[i], updated.ExtraValues[i]);\n }\n }\n foreach (string oldName in oldTree.ExtraNames) {\n if (!updated.ExtraNames.Includes(oldName)) {\n realNode.removeAttribute(oldName);\n }\n }\n\n if (updated.Disabled != oldTree.Disabled) {\n realNode.disabled = updated.Disabled;\n }\n // Like Value above, a checkbox's live checked state changes on click\n // with no render in between, so a checked one is re-asserted every\n // patch rather than diffed against the previous tree.\n if (updated.Checked || oldTree.Checked) {\n realNode.checked = updated.Checked;\n }\n\n // Swap a listener only when the handler reference actually changed.\n // A node that never sets a real OnClick/OnInput/OnBlur/OnChange\n // keeps VElement's own shared NoOpEventHandler reference on both\n // sides (see velement.ks) — comparing by `!=` costs nothing and\n // skips two real DOM API calls per event per node for the (common)\n // case of \"this node has no handler of this kind either time,\"\n // which matters a lot on a list with hundreds/thousands of rows\n // most of which set at most one or two of the four. A node WITH a\n // real handler still gets a fresh closure every render (it\n // captures per-render values, like a loop's own item), so it still\n // swaps every time — correctly, since the old closure really is\n // stale.\n //\n // The actually-attached listener is always a Batching.Run wrapper\n // (see Materialize above), never `oldTree.OnClick`/`updated.OnClick`\n // themselves — removeEventListener only works when passed the exact\n // reference addEventListener received, so removal always goes\n // through `oldTree.AttachedOnClick` (the wrapper Materialize/a\n // previous Patch actually registered), and a real swap builds a\n // fresh wrapper the same way Materialize does. When nothing swaps,\n // `updated.AttachedOnClick` still needs to carry `oldTree`'s\n // forward — `updated` is a brand-new VElement whose own\n // AttachedOnClick starts back at the shared no-op (velement.ks's\n // constructor), and it becomes the retained \"old tree\" the very\n // next Patch() call diffs against.\n if (updated.OnClick != oldTree.OnClick) {\n realNode.removeEventListener(\"click\", oldTree.AttachedOnClick);\n (Event) => void wrappedClick = (Event e) => Batching.Run(() => updated.OnClick(e));\n updated.AttachedOnClick = wrappedClick;\n realNode.addEventListener(\"click\", wrappedClick);\n } else {\n updated.AttachedOnClick = oldTree.AttachedOnClick;\n }\n if (updated.OnInput != oldTree.OnInput) {\n realNode.removeEventListener(\"input\", oldTree.AttachedOnInput);\n (Event) => void wrappedInput = (Event e) => Batching.Run(() => updated.OnInput(e));\n updated.AttachedOnInput = wrappedInput;\n realNode.addEventListener(\"input\", wrappedInput);\n } else {\n updated.AttachedOnInput = oldTree.AttachedOnInput;\n }\n if (updated.OnBlur != oldTree.OnBlur) {\n realNode.removeEventListener(\"blur\", oldTree.AttachedOnBlur);\n (Event) => void wrappedBlur = (Event e) => Batching.Run(() => updated.OnBlur(e));\n updated.AttachedOnBlur = wrappedBlur;\n realNode.addEventListener(\"blur\", wrappedBlur);\n } else {\n updated.AttachedOnBlur = oldTree.AttachedOnBlur;\n }\n if (updated.OnChange != oldTree.OnChange) {\n realNode.removeEventListener(\"change\", oldTree.AttachedOnChange);\n (Event) => void wrappedChange = (Event e) => Batching.Run(() => updated.OnChange(e));\n updated.AttachedOnChange = wrappedChange;\n realNode.addEventListener(\"change\", wrappedChange);\n } else {\n updated.AttachedOnChange = oldTree.AttachedOnChange;\n }\n\n return realNode;\n }\n } else {\n // Shouldn't happen in practice (every previously-rendered tree has a\n // real node by the time a second render diffs against it) — treated\n // as \"nothing to reuse\" rather than a crash, same defensive spirit\n // as Component's own IsMounted guard.\n Element created = Materialize(updated, parent);\n parent.appendChild(created);\n return created;\n }\n } else {\n Element created = Materialize(updated, parent);\n parent.appendChild(created);\n return created;\n }\n}\n\n// Releases whatever was previously mounted in a slot (calling its\n// Teardown, which — for a Component — cascades into anything IT mounted\n// too, however many levels deep, before its own app-facing OnUnmount runs)\n// and removes its real node from the DOM, before a different Mountable (or\n// plain content) takes over that slot. A no-op when there was nothing\n// mounted here before — the common \"first render of this slot\" case.\nvoid UnmountPrevious(Element parent, VElement? old, Mountable? oldMounted) {\n // Teardown() only applies when there really was a Mounted instance here\n // before (nothing to tear down for plain content) — but the real node\n // itself needs removing whenever `old` had one, Mounted or not: a plain\n // VElement's slot turning into a Mounted one is exactly as much a\n // wholesale replacement as the reverse direction (handled by falling\n // through to Materialize below in Patch), and both need the OLD node\n // gone before the NEW one is appended, not left behind as a stray\n // sibling.\n if (oldMounted != null) {\n Mountable m = oldMounted;\n m.Teardown();\n }\n if (old != null) {\n VElement oldTree = old;\n Element? maybeOldNode = oldTree.RealNode;\n if (maybeOldNode != null) {\n Element oldNode = maybeOldNode;\n parent.removeChild(oldNode);\n }\n }\n}\n\n// Keyed reconciliation: each VElement's own Id is its key when non-empty —\n// a real, existing DOM convention, needing no new API or syntax. A new\n// child whose Id matches an old child's Id is patched against that old\n// child (reusing its real node) regardless of position; a new child with\n// no Id, or an Id not present among the old children, falls back to\n// pairing positionally against whatever old children are still unconsumed,\n// in order. DOCUMENTED, REAL LIMITATION: without stable Ids, a reordered\n// list still produces the correct final output, but a given item's real\n// DOM node (and anything stateful attached to it, like focus) isn't\n// guaranteed to follow its data across the reorder — give list items a\n// stable Id for that guarantee.\nvoid PatchChildren(Element parent, VElement[] oldChildren, VElement[] newChildren) {\n // Map, not a Push loop — Push is deliberately non-mutating (a real\n // spread-copy every call, see KopScript's own README), so building an\n // n-length array by Push-ing once per element in a loop is an\n // accidental O(n^2) on every single PatchChildren call, however small\n // the actual diff. Map is a real, single O(n) pass straight to\n // Array.prototype.map.\n bool[] oldConsumed = oldChildren.Map((VElement c) => false);\n number[] matchedOldIndex = newChildren.Map((VElement c) => -1);\n\n // Pass 1: keyed matches, by Id.\n for (number i = 0; i < newChildren.Length; i = i + 1) {\n if (newChildren[i].Id.Length == 0) { continue; }\n for (number j = 0; j < oldChildren.Length; j = j + 1) {\n if (!oldConsumed[j] && oldChildren[j].Id == newChildren[i].Id) {\n matchedOldIndex[i] = j;\n oldConsumed[j] = true;\n break;\n }\n }\n }\n\n // Pass 2: positional fallback for everything Pass 1 didn't match —\n // pair each remaining new child against the next still-unconsumed old\n // child, in order.\n number nextOld = 0;\n for (number i = 0; i < newChildren.Length; i = i + 1) {\n if (matchedOldIndex[i] >= 0) { continue; }\n while (nextOld < oldChildren.Length && oldConsumed[nextOld]) {\n nextOld = nextOld + 1;\n }\n if (nextOld < oldChildren.Length) {\n matchedOldIndex[i] = nextOld;\n oldConsumed[nextOld] = true;\n nextOld = nextOld + 1;\n }\n }\n\n // Whether anything is actually moving at all — same length, and every\n // new position matched the *same* old position. The extremely common\n // case for a list that's only had some of its rows' own content change\n // (e.g. \"update every 10th row\"), where reconciliation still has real\n // work to do (see Pass 1/2 above and Patch() itself) but nothing needs\n // to physically move in the DOM at all.\n bool needsReorder = oldChildren.Length != newChildren.Length;\n for (number i = 0; i < newChildren.Length; i = i + 1) {\n if (matchedOldIndex[i] != i) {\n needsReorder = true;\n break;\n }\n }\n\n // Pass 3: patch/create each new child in order, then — only if the list\n // actually needs reordering — move it into its correct final position.\n // appendChild on a node already attached elsewhere in the DOM MOVES it\n // (real DOM semantics), so processing new children in their final\n // desired order and always appending naturally builds up the correct\n // sequence, no separate insertBefore/reference-node bookkeeping needed.\n // Safe because VElement.Children is always the COMPLETE list of a\n // node's children — nothing else ever shares `parent`. Skipping the\n // move entirely when `needsReorder` is false avoids a real DOM API call\n // per child for the common no-reorder case — Patch() itself already\n // updates or replaces a reused/changed node exactly in place either way.\n for (number i = 0; i < newChildren.Length; i = i + 1) {\n VElement? matchedOld = null;\n if (matchedOldIndex[i] >= 0) {\n matchedOld = oldChildren[matchedOldIndex[i]];\n }\n Element childNode = Patch(parent, matchedOld, newChildren[i]);\n if (needsReorder) {\n parent.appendChild(childNode);\n }\n }\n\n // Pass 4: remove whatever old children never got reused — releasing\n // anything Mounted first (see velement.ks) so a child genuinely dropped\n // from a list (not replaced in the same slot by a different one, which\n // Patch() itself already handles via UnmountPrevious — removed outright)\n // still gets torn down. This is the one place THAT case is reachable\n // from, since Patch() only ever sees one slot at a time, never a slot\n // disappearing entirely.\n for (number j = 0; j < oldChildren.Length; j = j + 1) {\n if (oldConsumed[j]) { continue; }\n Mountable? maybeOldMounted = oldChildren[j].Mounted;\n if (maybeOldMounted != null) {\n Mountable m = maybeOldMounted;\n m.Teardown();\n }\n Element? maybeOldNode = oldChildren[j].RealNode;\n if (maybeOldNode != null) {\n Element oldNode = maybeOldNode;\n parent.removeChild(oldNode);\n }\n }\n}\n\n// Recursively finds and tears down every Mounted node within `tree` (tree\n// itself included) — used by Component's own Teardown (see component.ks)\n// so removing ONE component transitively releases everything IT rendered,\n// however many Mounted levels deep, not only the outermost one. A pure\n// data walk over the retained VElement tree; never touches the real DOM\n// itself (the caller already owns removing whatever real node is actually\n// attached).\nvoid UnmountTree(VElement tree) {\n Mountable? maybeMounted = tree.Mounted;\n if (maybeMounted != null) {\n Mountable m = maybeMounted;\n m.Teardown();\n }\n foreach (VElement child in tree.Children) {\n UnmountTree(child);\n }\n}\n"],"names":[],"mappings":";;;AAyCA;EACiB;;EACA;;EAED;IACZ;;;EAGY;IACZ;MACmB;;;;EAUP;IACG;IACf;MACQ;;MAES;MACf;QACE;QACiB;QACjB;UACe;;;;;;AAmBvB;EACiB;;EAED;IACZ;MACwB;MACtB;MACkB;MACA;MACO;;;;AAgB/B;EACE;EACA;IACE;IACA;IACc;IACd;;EAGF;EAEA;IACe;;IAEb;MACgB;;;IAGD;;EAGJ;EACP;EACG;EAET;IACiB;;EAEjB;IACc;;EAEd;IACa;;EAYb;IACE;IACqB;IACF;;EAErB;IACE;IACqB;IACF;;EAErB;IACE;IACoB;IACD;;EAErB;IACE;IACsB;IACH;;EAGP;EACd;;AAiBF;EACE;EACA;EACA;IACE;IACW;;EASb;IACE;IACA;MACE;MACA;QAIE;QACiB;QACjB;;;IAKW;IACf;IACkB;IACD;IACjB;;EAGF;IAGiB;IACf;IACkB;IAClB;;EAGF;IACE;IACA;IACA;MACE;MACA;QACE;QACmB;QACnB;;QAEiB;QAEjB;UACE;YACqB;;;UAGrB;YACuB;;UAEV;;QAGf;UACqB;;QAErB;UACc;;QAaC;QAWf;UACE;YACE;cACuB;;;;UAIzB;YACuB;;;QAGzB;UACE;YAC0B;;;QAI5B;UACoB;;QAKpB;UACmB;;QA4BnB;UAC8B;UAC5B;UACwB;UACC;;UAED;;QAE1B;UAC8B;UAC5B;UACwB;UACC;;UAED;;QAE1B;UAC8B;UAC5B;UACuB;UACE;;UAEF;;QAEzB;UAC8B;UAC5B;UACyB;UACA;;UAEA;;QAG3B;;;MAOF;MACkB;MAClB;;;IAGF;IACkB;IAClB;;;AAUJ;EASE;IACE;IACU;;EAEZ;IACE;IACA;IACA;MACE;MACkB;;;;AAgBxB;EAOE;EACA;EAGA;IACE;MAAqC;;IACrC;MACE;QACqB;QACJ;QACf;;;;EAQN;EACA;IACE;MAA+B;;IAC/B;MACU;;IAEV;MACqB;MACE;MACb;;;EAUZ;EACA;IACE;MACe;MACb;;;EAeJ;IACE;IACA;MACa;;IAEb;IACA;MACoB;;;EAWtB;IACE;MAAsB;;IACtB;IACA;MACE;MACU;;IAEZ;IACA;MACE;MACkB;;;;AAYxB;EACE;EACA;IACE;IACU;;EAEZ;IACa"}
1
+ {"version":3,"file":"vdom.js","sources":["vdom.ks"],"sourcesContent":["using \"./dom\";\nusing \"./velement\";\n\n// The diff/patch engine behind real vdom diffing: Component.Update() (see\n// component.ks) calls Patch() with the PREVIOUS render's VElement tree\n// (which carries each node's real, live DOM counterpart via its own\n// RealNode field) and the NEW tree Render() just produced, and gets back\n// real DOM mutated/reused in place wherever possible instead of a full\n// subtree rebuild.\n//\n// Deliberately never reads the live DOM back to rediscover structure (no\n// \"get current children\"/\"get current tag\" API exists, or is needed) —\n// the retained *previous* VElement tree already records everything Patch()\n// needs to know about what's currently there. This is what makes the whole\n// approach work without a generic children/attributes read-back API that\n// KopScript's narrow, curated DOM binding doesn't have.\n\n// A component-like thing Batching (below) can flush once every DOM-event-\n// triggered Update() call inside one batch has registered itself. Declared\n// HERE, not in component.ks, specifically so THIS file's own Materialize/\n// Patch — which need to start/stop a batch around every real event\n// dispatch — never have to `using \"./component\"`: component.ks already\n// `using`s this file for Materialize/Patch themselves, and KopScript\n// rejects a circular `using` outright. Component (component.ks) is the\n// one real implementer, via `class Component : Flushable`.\ninterface Flushable {\n void FlushUpdate();\n}\n\n// Coalesces every Update() call made while a real DOM event handler\n// Kopular itself attached (see Materialize/Patch below, both of which wrap\n// each listener in Batching.Run before attaching it) into one flush per\n// affected component, applied once that handler returns — not one flush\n// per state<T> write inside it. See Component.Update()'s own comment\n// (component.ks) for the full rationale; this is just the mechanism.\n//\n// Deliberately class-level, shared across every batch/component rather\n// than per-instance — a single click can trigger Update() on more than one\n// component (e.g. a shared service's state<T> notifying two sibling\n// pages), and all of them need to flush together, once, when that one\n// handler finishes.\nclass Batching {\n private static number Depth = 0;\n private static Flushable[] Pending = [];\n\n public static bool IsActive() {\n return Batching.Depth > 0;\n }\n\n public static void Defer(Flushable f) {\n if (!Batching.Pending.Includes(f)) {\n Batching.Pending = Batching.Pending.Push(f);\n }\n }\n\n // `try`/`finally`, not a bare sequence: a handler that throws must still\n // decrement Depth and flush whatever already-triggered renders are\n // pending, or one uncaught exception would wedge every future click/\n // input on the page into \"always batching, never rendering.\" The\n // exception itself still propagates unchanged — this never catches it,\n // only guarantees the cleanup runs.\n public static void Run(() => void action) {\n Batching.Depth = Batching.Depth + 1;\n try {\n action();\n } finally {\n Batching.Depth = Batching.Depth - 1;\n if (Batching.Depth == 0) {\n Flushable[] toFlush = Batching.Pending;\n Batching.Pending = [];\n foreach (Flushable f in toFlush) {\n f.FlushUpdate();\n }\n }\n }\n }\n}\n\n// The runtime half of kopscript's `styles from \"<path>.css\";` (see its own\n// README/LLM.md \"Templates\" section) — the compiler rewrites a class's own\n// stylesheet at compile time (every selector scoped to that class's\n// `data-kop-scope=\"<id>\"` attribute) and splices exactly one\n// `ScopedStyles.Inject(id, css);` call into its constructor. Same\n// static-array-registry-with-Includes-dedup shape as Batching above,\n// deliberately: dedup here is per component TYPE, not per instance — every\n// instance's constructor calls Inject with the same `id`/`css` (both\n// compile-time constants for that class), so only the first one actually\n// creates a <style> tag; the rest are no-ops. Never removed once injected\n// — a scoped stylesheet is global infrastructure for as long as the page\n// lives, not per-instance content Teardown() would ever need to clean up.\nclass ScopedStyles {\n private static string[] Injected = [];\n\n public static void Inject(string scopeId, string css) {\n if (!ScopedStyles.Injected.Includes(scopeId)) {\n ScopedStyles.Injected = ScopedStyles.Injected.Push(scopeId);\n Element style = document.createElement(\"style\");\n style.setAttribute(\"data-kop-scope-sheet\", scopeId);\n style.textContent = css;\n document.head.appendChild(style);\n }\n }\n}\n\n// Builds a brand-new, fully real DOM subtree from a VElement tree with no\n// diffing at all — first mount, or whenever Patch() decides a subtree must\n// be replaced outright (no previous node to reuse, or the tag changed).\n// Mutates `tree.RealNode` (and recursively every descendant's) as a side\n// effect, so the tree this was called on becomes the new \"previous tree\"\n// the next Patch() call diffs against. Takes `parent` — every call site\n// already knows it (either Patch's own `parent` parameter, or the real\n// element a recursive child call is about to be appendChild'd into) —\n// solely to hand to a Mounted slot's own MountAsChild, which needs to\n// remember its real parent for THAT component's own future self-triggered\n// re-renders; an ordinary (non-Mounted) VElement never uses it.\nElement Materialize(VElement tree, Element parent) {\n Mountable? maybeMounted = tree.Mounted;\n if (maybeMounted != null) {\n Mountable m = maybeMounted;\n Element mountedRoot = m.MountAsChild(parent);\n tree.RealNode = mountedRoot;\n return mountedRoot;\n }\n\n Element el = document.createElement(tree.Tag);\n\n if (tree.RawHtml.Length > 0) {\n el.innerHTML = tree.RawHtml;\n } else if (tree.Children.Length > 0) {\n foreach (VElement child in tree.Children) {\n el.appendChild(Materialize(child, el));\n }\n } else {\n el.textContent = tree.TextContent;\n }\n\n el.className = tree.ClassName;\n el.id = tree.Id;\n el.value = tree.Value;\n\n for (number i = 0; i < tree.ExtraNames.Length; i = i + 1) {\n el.setAttribute(tree.ExtraNames[i], tree.ExtraValues[i]);\n }\n if (tree.Disabled) {\n el.disabled = true;\n }\n if (tree.Checked) {\n el.checked = true;\n }\n\n // Skip attaching VElement's own shared no-op (see velement.ks) — it does\n // nothing when invoked, so registering it costs real work (a listener\n // list entry, held onto for nothing) for zero benefit. A real handler\n // (never equal to the shared no-op) always gets attached as before —\n // wrapped in Batching.Run so every Update() it triggers coalesces with\n // any others from the same dispatch (see Component.Update()'s own\n // comment). The wrapper itself, not tree.OnClick, is what actually gets\n // registered — recorded on tree.AttachedOnClick (velement.ks) so a later\n // Patch() can remove this exact reference, not the handler value itself.\n if (tree.OnClick != NoOpEventHandler) {\n (Event) => void wrapped = (Event e) => Batching.Run(() => tree.OnClick(e));\n tree.AttachedOnClick = wrapped;\n el.addEventListener(\"click\", wrapped);\n }\n if (tree.OnInput != NoOpEventHandler) {\n (Event) => void wrapped = (Event e) => Batching.Run(() => tree.OnInput(e));\n tree.AttachedOnInput = wrapped;\n el.addEventListener(\"input\", wrapped);\n }\n if (tree.OnBlur != NoOpEventHandler) {\n (Event) => void wrapped = (Event e) => Batching.Run(() => tree.OnBlur(e));\n tree.AttachedOnBlur = wrapped;\n el.addEventListener(\"blur\", wrapped);\n }\n if (tree.OnChange != NoOpEventHandler) {\n (Event) => void wrapped = (Event e) => Batching.Run(() => tree.OnChange(e));\n tree.AttachedOnChange = wrapped;\n el.addEventListener(\"change\", wrapped);\n }\n\n tree.RealNode = el;\n return el;\n}\n\n// Diffs `updated` against `old` (the previous render's tree for this exact\n// position, or null if there is none — first mount) and returns the real\n// DOM node now representing `updated`, reusing `old`'s real node in place\n// whenever the tag matches. `parent` is only used to attach/replace at the\n// top of whatever subtree Patch() is called on — child-level attach/replace\n// happens inside PatchChildren.\n//\n// Deliberately all positive-branch `if (x != null) { ... } else { ... }`,\n// never an early-return guard clause — KopScript's nullable narrowing is\n// scope-based, not reachability-based, so `if (x == null) { return; }\n// use(x);` would NOT narrow `x` afterward (see KopScript's own LLM.md \"Common\n// mistakes\"). Every nullable member-access path (`oldTree.RealNode`,\n// never narrows directly either) is read into a local first for the same\n// reason.\nElement Patch(Element parent, VElement? old, VElement updated) {\n Mountable? newMounted = updated.Mounted;\n Mountable? oldMounted = null;\n if (old != null) {\n VElement oldTreeForMount = old;\n oldMounted = oldTreeForMount.Mounted;\n }\n\n // A live child slot (VElement.Mounted — see velement.ks) is handled\n // entirely separately from the ordinary Tag-based logic below: it's not\n // Kopular's own DOM element to create/reuse at all, and its \"same node\n // or replace\" decision is instance identity (== on the Mountable itself,\n // real reference equality — interfaces erase to the underlying object),\n // not Tag equality.\n if (newMounted != null) {\n Mountable nm = newMounted;\n if (oldMounted != null) {\n Mountable om = oldMounted;\n if (om == nm) {\n // Same instance still in this slot: patch it in place, don't touch\n // the DOM position at all (its own real node, reused or not, is\n // already exactly where it needs to be).\n Element reused = nm.PatchAsChild();\n updated.RealNode = reused;\n return reused;\n }\n }\n // First time this slot has anything mounted, or a DIFFERENT instance\n // took over the slot: release whatever was here, then mount fresh.\n UnmountPrevious(parent, old, oldMounted);\n Element created = nm.MountAsChild(parent);\n parent.appendChild(created);\n updated.RealNode = created;\n return created;\n }\n\n if (oldMounted != null) {\n // Slot reverted from a live component back to plain content: release\n // the old one, then fall through to an ordinary fresh materialize.\n UnmountPrevious(parent, old, oldMounted);\n Element created = Materialize(updated, parent);\n parent.appendChild(created);\n return created;\n }\n\n if (old != null) {\n VElement oldTree = old;\n Element? maybeOldNode = oldTree.RealNode;\n if (maybeOldNode != null) {\n Element realNode = maybeOldNode;\n if (oldTree.Tag != updated.Tag) {\n Element created = Materialize(updated, parent);\n parent.replaceChild(created, realNode);\n return created;\n } else {\n updated.RealNode = realNode;\n\n if (updated.RawHtml.Length > 0 || oldTree.RawHtml.Length > 0) {\n if (updated.RawHtml != oldTree.RawHtml) {\n realNode.innerHTML = updated.RawHtml;\n }\n } else if (updated.Children.Length > 0) {\n // Children own this node's content now. If the old tree was a\n // plain text leaf (no tracked children of its own), any raw text\n // Materialize/a previous Patch left directly in the real node is\n // untracked by PatchChildren (which only knows about VElement-\n // backed children) — clear it first, or the new children would\n // just be appended alongside stray leftover text.\n if (oldTree.Children.Length == 0) {\n realNode.textContent = \"\";\n }\n PatchChildren(realNode, oldTree.Children, updated.Children);\n } else {\n // updated is a plain text leaf (or empty). Any of oldTree's own\n // real children need tearing down/removing properly first\n // (nested Mounted components included, via PatchChildren's own\n // Pass 4) — textContent's native browser side effect would\n // otherwise silently detach them without running their own\n // OnUnmount(), and a later PatchChildren call against those now-\n // orphaned nodes would throw trying to remove an already-detached\n // child.\n if (oldTree.Children.Length > 0) {\n PatchChildren(realNode, oldTree.Children, []);\n }\n if (updated.TextContent != oldTree.TextContent) {\n realNode.textContent = updated.TextContent;\n }\n }\n\n if (updated.ClassName != oldTree.ClassName) {\n realNode.className = updated.ClassName;\n }\n if (updated.Id != oldTree.Id) {\n realNode.id = updated.Id;\n }\n // Always assigned, never conditionally on updated.Value != oldTree.Value\n // — unlike TextContent/ClassName/Id, an <input>/<select>'s live value\n // can diverge from the last-recorded VElement.Value purely through\n // user interaction (typing, picking an option) with no Update() ever\n // running in between (a real, deliberate pattern — see KopularDemo's\n // dogs_page.ks, which never Update()s on input/change). The recorded\n // oldTree.Value only reflects the tree as of the last actual render,\n // so comparing against it can't tell \"genuinely unchanged\" apart from\n // \"changed live in the DOM since then, framework never told\" — the\n // same reason a real \"controlled input\" (React's own term for this)\n // always writes value on every render rather than diffing it.\n realNode.value = updated.Value;\n\n // Same-length is the overwhelmingly common case (the same Render()\n // code path calls SetAttr the same number of times, in the same\n // order, on every call) — compare aligned by index and only touch\n // the real DOM for an entry that actually changed, rather than\n // reapplying every extra attribute on every patch regardless. A\n // length mismatch (the rarer case: a SetAttr call was added,\n // removed, or made conditional between renders) falls back to\n // reapplying everything, since index-aligned comparison isn't\n // meaningful once the two arrays don't correspond entry-for-entry.\n if (updated.ExtraNames.Length == oldTree.ExtraNames.Length) {\n for (number i = 0; i < updated.ExtraNames.Length; i = i + 1) {\n if (updated.ExtraNames[i] != oldTree.ExtraNames[i] || updated.ExtraValues[i] != oldTree.ExtraValues[i]) {\n realNode.setAttribute(updated.ExtraNames[i], updated.ExtraValues[i]);\n }\n }\n } else {\n for (number i = 0; i < updated.ExtraNames.Length; i = i + 1) {\n realNode.setAttribute(updated.ExtraNames[i], updated.ExtraValues[i]);\n }\n }\n foreach (string oldName in oldTree.ExtraNames) {\n if (!updated.ExtraNames.Includes(oldName)) {\n realNode.removeAttribute(oldName);\n }\n }\n\n if (updated.Disabled != oldTree.Disabled) {\n realNode.disabled = updated.Disabled;\n }\n // Like Value above, a checkbox's live checked state changes on click\n // with no render in between, so a checked one is re-asserted every\n // patch rather than diffed against the previous tree.\n if (updated.Checked || oldTree.Checked) {\n realNode.checked = updated.Checked;\n }\n\n // Swap a listener only when the handler reference actually changed.\n // A node that never sets a real OnClick/OnInput/OnBlur/OnChange\n // keeps VElement's own shared NoOpEventHandler reference on both\n // sides (see velement.ks) — comparing by `!=` costs nothing and\n // skips two real DOM API calls per event per node for the (common)\n // case of \"this node has no handler of this kind either time,\"\n // which matters a lot on a list with hundreds/thousands of rows\n // most of which set at most one or two of the four. A node WITH a\n // real handler still gets a fresh closure every render (it\n // captures per-render values, like a loop's own item), so it still\n // swaps every time — correctly, since the old closure really is\n // stale.\n //\n // The actually-attached listener is always a Batching.Run wrapper\n // (see Materialize above), never `oldTree.OnClick`/`updated.OnClick`\n // themselves — removeEventListener only works when passed the exact\n // reference addEventListener received, so removal always goes\n // through `oldTree.AttachedOnClick` (the wrapper Materialize/a\n // previous Patch actually registered), and a real swap builds a\n // fresh wrapper the same way Materialize does. When nothing swaps,\n // `updated.AttachedOnClick` still needs to carry `oldTree`'s\n // forward — `updated` is a brand-new VElement whose own\n // AttachedOnClick starts back at the shared no-op (velement.ks's\n // constructor), and it becomes the retained \"old tree\" the very\n // next Patch() call diffs against.\n if (updated.OnClick != oldTree.OnClick) {\n realNode.removeEventListener(\"click\", oldTree.AttachedOnClick);\n (Event) => void wrappedClick = (Event e) => Batching.Run(() => updated.OnClick(e));\n updated.AttachedOnClick = wrappedClick;\n realNode.addEventListener(\"click\", wrappedClick);\n } else {\n updated.AttachedOnClick = oldTree.AttachedOnClick;\n }\n if (updated.OnInput != oldTree.OnInput) {\n realNode.removeEventListener(\"input\", oldTree.AttachedOnInput);\n (Event) => void wrappedInput = (Event e) => Batching.Run(() => updated.OnInput(e));\n updated.AttachedOnInput = wrappedInput;\n realNode.addEventListener(\"input\", wrappedInput);\n } else {\n updated.AttachedOnInput = oldTree.AttachedOnInput;\n }\n if (updated.OnBlur != oldTree.OnBlur) {\n realNode.removeEventListener(\"blur\", oldTree.AttachedOnBlur);\n (Event) => void wrappedBlur = (Event e) => Batching.Run(() => updated.OnBlur(e));\n updated.AttachedOnBlur = wrappedBlur;\n realNode.addEventListener(\"blur\", wrappedBlur);\n } else {\n updated.AttachedOnBlur = oldTree.AttachedOnBlur;\n }\n if (updated.OnChange != oldTree.OnChange) {\n realNode.removeEventListener(\"change\", oldTree.AttachedOnChange);\n (Event) => void wrappedChange = (Event e) => Batching.Run(() => updated.OnChange(e));\n updated.AttachedOnChange = wrappedChange;\n realNode.addEventListener(\"change\", wrappedChange);\n } else {\n updated.AttachedOnChange = oldTree.AttachedOnChange;\n }\n\n return realNode;\n }\n } else {\n // Shouldn't happen in practice (every previously-rendered tree has a\n // real node by the time a second render diffs against it) — treated\n // as \"nothing to reuse\" rather than a crash, same defensive spirit\n // as Component's own IsMounted guard.\n Element created = Materialize(updated, parent);\n parent.appendChild(created);\n return created;\n }\n } else {\n Element created = Materialize(updated, parent);\n parent.appendChild(created);\n return created;\n }\n}\n\n// Releases whatever was previously mounted in a slot (calling its\n// Teardown, which — for a Component — cascades into anything IT mounted\n// too, however many levels deep, before its own app-facing OnUnmount runs)\n// and removes its real node from the DOM, before a different Mountable (or\n// plain content) takes over that slot. A no-op when there was nothing\n// mounted here before — the common \"first render of this slot\" case.\nvoid UnmountPrevious(Element parent, VElement? old, Mountable? oldMounted) {\n // Teardown() only applies when there really was a Mounted instance here\n // before (nothing to tear down for plain content) — but the real node\n // itself needs removing whenever `old` had one, Mounted or not: a plain\n // VElement's slot turning into a Mounted one is exactly as much a\n // wholesale replacement as the reverse direction (handled by falling\n // through to Materialize below in Patch), and both need the OLD node\n // gone before the NEW one is appended, not left behind as a stray\n // sibling.\n if (oldMounted != null) {\n Mountable m = oldMounted;\n m.Teardown();\n }\n if (old != null) {\n VElement oldTree = old;\n Element? maybeOldNode = oldTree.RealNode;\n if (maybeOldNode != null) {\n Element oldNode = maybeOldNode;\n parent.removeChild(oldNode);\n }\n }\n}\n\n// Keyed reconciliation: each VElement's own Id is its key when non-empty —\n// a real, existing DOM convention, needing no new API or syntax. A new\n// child whose Id matches an old child's Id is patched against that old\n// child (reusing its real node) regardless of position; a new child with\n// no Id, or an Id not present among the old children, falls back to\n// pairing positionally against whatever old children are still unconsumed,\n// in order. DOCUMENTED, REAL LIMITATION: without stable Ids, a reordered\n// list still produces the correct final output, but a given item's real\n// DOM node (and anything stateful attached to it, like focus) isn't\n// guaranteed to follow its data across the reorder — give list items a\n// stable Id for that guarantee.\nvoid PatchChildren(Element parent, VElement[] oldChildren, VElement[] newChildren) {\n // Map, not a Push loop — Push is deliberately non-mutating (a real\n // spread-copy every call, see KopScript's own README), so building an\n // n-length array by Push-ing once per element in a loop is an\n // accidental O(n^2) on every single PatchChildren call, however small\n // the actual diff. Map is a real, single O(n) pass straight to\n // Array.prototype.map.\n bool[] oldConsumed = oldChildren.Map((VElement c) => false);\n number[] matchedOldIndex = newChildren.Map((VElement c) => -1);\n\n // Pass 1: keyed matches, by Id.\n for (number i = 0; i < newChildren.Length; i = i + 1) {\n if (newChildren[i].Id.Length == 0) { continue; }\n for (number j = 0; j < oldChildren.Length; j = j + 1) {\n if (!oldConsumed[j] && oldChildren[j].Id == newChildren[i].Id) {\n matchedOldIndex[i] = j;\n oldConsumed[j] = true;\n break;\n }\n }\n }\n\n // Pass 2: positional fallback for everything Pass 1 didn't match —\n // pair each remaining new child against the next still-unconsumed old\n // child, in order.\n number nextOld = 0;\n for (number i = 0; i < newChildren.Length; i = i + 1) {\n if (matchedOldIndex[i] >= 0) { continue; }\n while (nextOld < oldChildren.Length && oldConsumed[nextOld]) {\n nextOld = nextOld + 1;\n }\n if (nextOld < oldChildren.Length) {\n matchedOldIndex[i] = nextOld;\n oldConsumed[nextOld] = true;\n nextOld = nextOld + 1;\n }\n }\n\n // Whether anything is actually moving at all — same length, and every\n // new position matched the *same* old position. The extremely common\n // case for a list that's only had some of its rows' own content change\n // (e.g. \"update every 10th row\"), where reconciliation still has real\n // work to do (see Pass 1/2 above and Patch() itself) but nothing needs\n // to physically move in the DOM at all.\n bool needsReorder = oldChildren.Length != newChildren.Length;\n for (number i = 0; i < newChildren.Length; i = i + 1) {\n if (matchedOldIndex[i] != i) {\n needsReorder = true;\n break;\n }\n }\n\n // Pass 3: patch/create each new child in order, then — only if the list\n // actually needs reordering — move it into its correct final position.\n // appendChild on a node already attached elsewhere in the DOM MOVES it\n // (real DOM semantics), so processing new children in their final\n // desired order and always appending naturally builds up the correct\n // sequence, no separate insertBefore/reference-node bookkeeping needed.\n // Safe because VElement.Children is always the COMPLETE list of a\n // node's children — nothing else ever shares `parent`. Skipping the\n // move entirely when `needsReorder` is false avoids a real DOM API call\n // per child for the common no-reorder case — Patch() itself already\n // updates or replaces a reused/changed node exactly in place either way.\n for (number i = 0; i < newChildren.Length; i = i + 1) {\n VElement? matchedOld = null;\n if (matchedOldIndex[i] >= 0) {\n matchedOld = oldChildren[matchedOldIndex[i]];\n }\n Element childNode = Patch(parent, matchedOld, newChildren[i]);\n if (needsReorder) {\n parent.appendChild(childNode);\n }\n }\n\n // Pass 4: remove whatever old children never got reused — releasing\n // anything Mounted first (see velement.ks) so a child genuinely dropped\n // from a list (not replaced in the same slot by a different one, which\n // Patch() itself already handles via UnmountPrevious — removed outright)\n // still gets torn down. This is the one place THAT case is reachable\n // from, since Patch() only ever sees one slot at a time, never a slot\n // disappearing entirely.\n for (number j = 0; j < oldChildren.Length; j = j + 1) {\n if (oldConsumed[j]) { continue; }\n Mountable? maybeOldMounted = oldChildren[j].Mounted;\n if (maybeOldMounted != null) {\n Mountable m = maybeOldMounted;\n m.Teardown();\n }\n Element? maybeOldNode = oldChildren[j].RealNode;\n if (maybeOldNode != null) {\n Element oldNode = maybeOldNode;\n parent.removeChild(oldNode);\n }\n }\n}\n\n// Recursively finds and tears down every Mounted node within `tree` (tree\n// itself included) — used by Component's own Teardown (see component.ks)\n// so removing ONE component transitively releases everything IT rendered,\n// however many Mounted levels deep, not only the outermost one. A pure\n// data walk over the retained VElement tree; never touches the real DOM\n// itself (the caller already owns removing whatever real node is actually\n// attached).\nvoid UnmountTree(VElement tree) {\n Mountable? maybeMounted = tree.Mounted;\n if (maybeMounted != null) {\n Mountable m = maybeMounted;\n m.Teardown();\n }\n foreach (VElement child in tree.Children) {\n UnmountTree(child);\n }\n}\n"],"names":[],"mappings":";;;AAyCA;EACiB;;EACA;;EAED;IACZ;;;EAGY;IACZ;MACmB;;;;EAUP;IACG;IACf;MACQ;;MAES;MACf;QACE;QACiB;QACjB;UACe;;;;;;AAmBvB;EACiB;;EAED;IACZ;MACwB;MACtB;MACkB;MACA;MACO;;;;AAgB/B;EACE;EACA;IACE;IACA;IACc;IACd;;EAGF;EAEA;IACe;;IAEb;MACgB;;;IAGD;;EAGJ;EACP;EACG;EAET;IACiB;;EAEjB;IACc;;EAEd;IACa;;EAYb;IACE;IACqB;IACF;;EAErB;IACE;IACqB;IACF;;EAErB;IACE;IACoB;IACD;;EAErB;IACE;IACsB;IACH;;EAGP;EACd;;AAiBF;EACE;EACA;EACA;IACE;IACW;;EASb;IACE;IACA;MACE;MACA;QAIE;QACiB;QACjB;;;IAKW;IACf;IACkB;IACD;IACjB;;EAGF;IAGiB;IACf;IACkB;IAClB;;EAGF;IACE;IACA;IACA;MACE;MACA;QACE;QACmB;QACnB;;QAEiB;QAEjB;UACE;YACqB;;;UASrB;YACuB;;UAEV;;UAUb;YACe;;UAEf;YACuB;;;QAIzB;UACqB;;QAErB;UACc;;QAaC;QAWf;UACE;YACE;cACuB;;;;UAIzB;YACuB;;;QAGzB;UACE;YAC0B;;;QAI5B;UACoB;;QAKpB;UACmB;;QA4BnB;UAC8B;UAC5B;UACwB;UACC;;UAED;;QAE1B;UAC8B;UAC5B;UACwB;UACC;;UAED;;QAE1B;UAC8B;UAC5B;UACuB;UACE;;UAEF;;QAEzB;UAC8B;UAC5B;UACyB;UACA;;UAEA;;QAG3B;;;MAOF;MACkB;MAClB;;;IAGF;IACkB;IAClB;;;AAUJ;EASE;IACE;IACU;;EAEZ;IACE;IACA;IACA;MACE;MACkB;;;;AAgBxB;EAOE;EACA;EAGA;IACE;MAAqC;;IACrC;MACE;QACqB;QACJ;QACf;;;;EAQN;EACA;IACE;MAA+B;;IAC/B;MACU;;IAEV;MACqB;MACE;MACb;;;EAUZ;EACA;IACE;MACe;MACb;;;EAeJ;IACE;IACA;MACa;;IAEb;IACA;MACoB;;;EAWtB;IACE;MAAsB;;IACtB;IACA;MACE;MACU;;IAEZ;IACA;MACE;MACkB;;;;AAYxB;EACE;EACA;IACE;IACU;;EAEZ;IACa"}
package/src/vdom.ks CHANGED
@@ -257,11 +257,32 @@ Element Patch(Element parent, VElement? old, VElement updated) {
257
257
  if (updated.RawHtml != oldTree.RawHtml) {
258
258
  realNode.innerHTML = updated.RawHtml;
259
259
  }
260
+ } else if (updated.Children.Length > 0) {
261
+ // Children own this node's content now. If the old tree was a
262
+ // plain text leaf (no tracked children of its own), any raw text
263
+ // Materialize/a previous Patch left directly in the real node is
264
+ // untracked by PatchChildren (which only knows about VElement-
265
+ // backed children) — clear it first, or the new children would
266
+ // just be appended alongside stray leftover text.
267
+ if (oldTree.Children.Length == 0) {
268
+ realNode.textContent = "";
269
+ }
270
+ PatchChildren(realNode, oldTree.Children, updated.Children);
260
271
  } else {
272
+ // updated is a plain text leaf (or empty). Any of oldTree's own
273
+ // real children need tearing down/removing properly first
274
+ // (nested Mounted components included, via PatchChildren's own
275
+ // Pass 4) — textContent's native browser side effect would
276
+ // otherwise silently detach them without running their own
277
+ // OnUnmount(), and a later PatchChildren call against those now-
278
+ // orphaned nodes would throw trying to remove an already-detached
279
+ // child.
280
+ if (oldTree.Children.Length > 0) {
281
+ PatchChildren(realNode, oldTree.Children, []);
282
+ }
261
283
  if (updated.TextContent != oldTree.TextContent) {
262
284
  realNode.textContent = updated.TextContent;
263
285
  }
264
- PatchChildren(realNode, oldTree.Children, updated.Children);
265
286
  }
266
287
 
267
288
  if (updated.ClassName != oldTree.ClassName) {