gitoria
All repositories: gitoria
76.7 KB
// The framework's client half — a file-class constructed ONCE in the browser by// the page's module script, with the seed the server rendered from. The// components are NOT preloaded: each mount carries the url its module is served// at and `hlLoad` fetches it when the mount happens. This file is the client// realm's entrypoint, and the page script sets that realm before constructing// it.//// Its whole job: CLAIM the DOM the server rendered for the mounted instances,// remember which elements read which member (the SITES), repaint a site when a// member is written, and turn a same-origin link into a navigation that fetches// the next route's tree and state and swaps the slot — the shell stays.import View from './view.hl'import Router from './router.hl'seedText = '' // the server's seed, as JSON text (the one construction argument)seed = null // { page: { key module params state view }, shell: … | null }view = new Viewrouter = null // the client's route table, from the seedshell = null // { key, instance, view, sites, root }page = nullappHead = null // the app's manifest head defaults, off the seed: what a page// member that is null falls back to (title, description, image,// favicon, and the app's own meta list)slotEl = null // the shell element whose children are the route componentdetachedSlot = null // the slot element a shell region's rebuild took out of the DOM (see paint)socket = null // the websocket carrier, while it is opennextId = 0 // the pairing id an emit's ack comes back onpending = {} // 'k<i>' → the resolver waiting for that ack// AN ANSWER THAT ARRIVES BEFORE ITS PAGE IS MOUNTED (ticket #80). A component's root// runs while `instantiate` constructs it, and an `emit server` there goes out at once// (over REST: the socket opens after boot). What the face raised for this tab comes// back in the ack, before `page` — or, on a navigation, the NEXT page — is the mount// that holds the listener; delivered then, it reached the old mounts or none and was// lost. While a mount is being built the frames wait here, and go out in arrival// order once it stands.mounting = falseheld = []blueprints = {} // component key → { module, view }: every tree the page can// build, taken from each seed and never dropped (takeBlueprints)pendingFills = [] // fills a region rebuild anchored but could not build in place:// the host is named by address and re-entered in settle() below// THE EVENTS A REFERENCE OVERWROTE ON THE COMPOSITION'S ROOT, while the walk is inside// that composition and has not yet reached an element. A composed child's View may be a// bare reference to another component (routger's dialog-form.hl is one), so the element// that FINALLY stands as the child's root can be any number of references deeper — this// rides down through them and is spent on the first elements the walk claims or builds,// which are exactly those roots.rootOverwrites = null// IS THE PAGE ON THE DOCUMENT? A shell decides per request whether its render contains// a `slot` (COMPONENTS §7, "THE PARENT IS THE GATE"): `if (loggedIn) { main { slot } }`// standing false renders no page at all, and there is then nothing to claim. False here// means the page is constructed and seeded but has no DOM — it arrives when the region// holding the slot turns true, and leaves again when it turns false.pageShown = false// ---- THE PACKAGE'S BROWSER SURFACE: what `import { … } from 'hl:web'` binds ------//// A file's STATICS are what a braced import may take (the language's one rule for// `import { db } from './store.hl'`, and the same rule across a package's url),// so everything this half offers an app's component is declared here and nowhere// else. A static belongs to the CLASS, which is why these two reach each other// and why they are the SAME pair for every component module the page imports —// the browser loads this file once.//// `live` IS THE PAGE'S ONE CLIENT, written by the root below. The statics cannot// see an instance (they are evaluated at file load, before there is one), and a// static that is a FUNCTION does not need to: its body runs at the CALL, long// after the root has put the constructed client here.static live = { client = null }// PROGRAMMATIC NAVIGATION — the same act a click on a same-origin `<a>` performs,// asked for by code instead of by a pointer: a new history entry, then the next// route's tree and state over the boundary and into the shell's slot. A handler// that has just been told an id and must go to that thing's page has no link to// click, and this is what it calls instead. Everything about what a navigation IS// stays in `goTo` below; this is only the way in from outside the file.static navigate = (path) => { return live.client.goTo(path) }// ---- boot: construct the instances the server rendered, claim their DOM ----------// THE PAGE'S CLIENT, PUBLISHED TO THE FILE'S OWN CLASS, before anything else the// root does: `boot()` below constructs the components, and a component's module// may reach `navigate` from the moment it is loaded.Client.live.client = thisseed = JSON.parse(seedText)router = new Router(routes = seed.routes)boot()boot() {mounting = truetakeBlueprints(seed.blueprints)if (seed.shell != null) {shell = instantiate(seed.shell, [], 'shell')shell.isShell = true// (the BODY ELEMENT, nothing to do with `rootKind` below — a mount's `rootKind`// says which of the two roots it hangs from, 'page' or 'shell'. This field held// the DOM node under the same name until 2026-09-14, and the shell's address// therefore read as an element: every lift and every fill re-entry from a// composition IN THE SHELL resolved against the page instead, so a composed// control there wrote nothing — creator, W15.)shell.root = document.body// the body node's children are claimed against document.body, so the body// element takes the node itself here: a region hosted directly on it (an `if`// at the shell's root) rebuilds from it (measured 2026-09-13: a lone child// under `body` stayed on screen after its condition turned false)claim(&shell, document.body)}page = instantiate(seed.page, [], 'page')// no shell: the page IS the document's body contentif (shell == null) { slotEl = document.body }// THE SHELL RENDERED NO SLOT — its region stood false for this request, so the// document carries no page. Claiming one anyway walked the page's tree against the// SHELL's own elements and silently attached the page's nodes to them ("claim: no// element for … under …" as soon as the two shapes differ), and the page never// appeared when the region later turned true. It waits instead.if (slotEl != null) {claim(&page, slotEl)pageShown = true}// the head members are sites of this mount from here on. They are NOT painted// now: the server's `document()` already wrote them into this document, and a// write to one of them repaints it the way every other member's write does.appHead = seed.headheadSites(&page)release()listen()connect()}// the frames that waited for the mounts (above), now that they standrelease() {mounting = falselet frames = heldheld = []for (f of frames) { outward(f) }return null}// a mount's instance: the module LOADED (hlLoad — the loader primitive, which// on this target is the dynamic import of the url the server compiled the// component to), the class constructed, then the server's state laid over it.// The import is the browser's own cache: a second mount of the same component// fetches nothing.// The route's params and the server's state are the construction's NAMED// ARGUMENTS, pinned before the root runs — so a member the server evaluated// (a seeded one, declared without its initializer in this realm's projection)// is already there when a later line reads it, and a client-evaluable// initializer keeps the server's value instead of recomputing it.// THE BLUEPRINT TABLE, read by component key: the url the component's module is// served at and its View tree, one copy for the whole page. Every mount's tree is// read from here — the page's, the shell's, and every child's — and so is every// child the browser has to build itself.//// IT ONLY GROWS. Each seed carries the table for ITS route, and a navigation takes// the new entries WITHOUT dropping the old: a key is a component and a component is// one tree, so an entry is never wrong, and constructing a mount awaits its module —// long enough for a second navigation to have replaced the seed underneath it. A// table that was replaced left that half-built page reading the wrong route's// entries ("no blueprint for components/post.hl", on `/`, measured in the reference// gate 2026-09-13).takeBlueprints(table) {for (k of table.keys()) {if (blueprints[k] == null) { blueprints[k] = table[k] }}return null}blueprintOf(key) {return blueprints[key]}treeOf(key) {let bp = blueprintOf(key)// the table covers every component the page can reach, so this is a torn seed// and not a missing feature — say so loudly and paint nothing for that mountif (bp == null) { console.error('framework: the seed carries no blueprint for ' + key)return [] }return bp.view}// `chain` and `root` are the mount's ADDRESS: the kid keys from the page (or the// shell) down to it. A mount record is a value, so a site cannot hold the mount that// owns its fill — it holds this address, and `fillAt` re-enters the mount by// reference from the root when the fill has to be rebuilt (see settle below).instantiate(m, chain, root) {let args = {}for (k of m.state.keys()) { args[k] = m.state[k] }for (k of m.params.keys()) { args[k] = m.params[k] }let inst = hlLoad(m.module, args)// THE TREE COMES FROM THE TABLE, by this mount's key: a View belongs to the// COMPONENT, and the seed carries one copy of it however many mounts share it.let out = { key = m.key; instance = inst; view = treeOf(m.key); sites = []; isShell = false; kids = {}; bindings = []; chain = chain; rootKind = root; }// THE MIRROR: the components this one composes are instances here too, exactly// as the server stacked them — one per component node, constructed with the// bindings the server evaluated; a binding to a host MEMBER is remembered, so a// host write reaches the child's member and repaints the child's sitesfor (k of m.kids.keys()) { out.kids[k] = instantiate(m.kids[k], childChain(chain, k), root) }bindKids(&out, out.view)// A BOUND MEMBER'S VALUE IS THE HOST'S, HERE. The seed carried the server's// value, which is right for data and null for a FUNCTION (JSON has no form for// one) — and a function the host hands its child (`PostForm { onCancel = cancel// }`) is the way a child talks upward without knowing its host: it calls what it// was given, and the function writes the host's members through the instance// that wrote it. So every member binding is applied from the host instance now.for (b of out.bindings) {let kid = out.kids[b.kid]kid.instance[b.target] = bindingValue(b, &out)out.kids[b.kid] = kid}return out}bindKids(&m, nodes) {for (n of nodes) {if (n.k == 'component') {let kid = m.kids[view.kidKey(n.path)]if (kid != null) {// A BINDING IS A READ at the reference site: a member (`count = likes`)// or a field path off one (`postId = row.id`). Both follow the host's// write — the field path under the name it starts at.for (b of n.bindings) {// A MEMBER THAT ONLY FEEDS A BINDING still follows a write: `repaint`// walks the bindings after the sites, so a host member no element of the// host shows still reaches the child that was bound to it (measured// 2026-09-13 on the social app: `FollowButton { following =// authorFollowed }` stayed false). Under the digest that needed the// member to be in the compared map; under the write sets it needs// nothing but the edge itself.if (b.member != null) { m.bindings.push({ name = b.member; kid = view.kidKey(n.path); target = b.name; ref = null; }) }else if (b.ref != null) { m.bindings.push({ name = b.ref.name; kid = view.kidKey(n.path); target = b.name; ref = b.ref; }) }}}// the fill is THIS mount's fragment: a reference inside it binds against this instanceif (n.fill != null) { bindKids(&m, n.fill) }} else if (n.k == 'el') {bindKids(&m, n.children)} else if (n.k == 'if') {bindKids(&m, n.then)bindKids(&m, n.other)}}return null}// a body-rooted View's children are the body's childrenchildrenOf(nodes) {if (nodes.length == 1 && nodes[0].k == 'el' && nodes[0].tag == 'body') { return nodes[0].children }return nodes}// ---- WHAT THE COMPILE STEP ANSWERED, asked by name ---------------------------------// A local event's write set stands at its own listener and a region's names at its own// region: the compile step wrote them into the statements. These three are asked for by// NAME at run time and cannot be — an inbound frame names its event, a routine a host// handed down names the member that holds it, and a write set names the derivations// that follow it — so the component's compiled half carries them beside its walks.// Nothing here reduces a table: the answers are already the answers.eventWrites(key, event) {let comp = compiledOf(key)if (comp == null) { return [] }let names = comp.ev[event]return names == null ? [] : names}memberWrites(key, name) {let comp = compiledOf(key)if (comp == null) { return [] }let names = comp.mw[name]return names == null ? [] : names}derivationsOf(key) {let comp = compiledOf(key)if (comp == null) { return [] }return comp.dv}// ---- THE COMPILED COMPONENT: this framework's own output for this file ------------// The old hl:web walked a tree the seed carries — it pairs an element with a node, asks a table// what the element shows, and asks `view.value` what each bound spot holds. hl:web// ships the answers as the component's own code (plugins/web/compile.hl), and the// functions below are the FIXED runtime that code calls: the mount records, the keyed// region diff, the binding edges, the derivations, the socket and navigation stay here,// where they belong to the framework and not to any one component.//// EVERY CALL INTO GENERATED CODE PASSES BY REFERENCE. A plain call copies its// arguments (the language's value semantics), which for an instance holding a 2000-row// list would copy the list on every paint; `&` at the call site hands the value itself,// the way every walk in this file already hands a mount record.compiledOf(key) {let all = window.__hlCif (all == null) { return null }return all[key]}// the walk of a component's whole View, of one `for` body, of an `if` branch, of the// list an `if` stands in, or of the fragment a reference fills — each under its own sitewalkOf(key, slot, site) {let comp = compiledOf(key)if (comp == null) { return null }if (slot == 'v') { return comp.v }if (slot == 'b') { return comp.b[site] }if (slot == 't') { return comp.t[site] }if (slot == 'e') { return comp.e[site] }if (slot == 'f') { return comp.f[site] }if (slot == 'r') { return comp.r[site] }return null}// ONE ENTRY INTO GENERATED CODE. `f` is the walk, `m` the mount it runs for, `o` the// mount whose fragment a `slot` inside it would place.run(f, &m, &o, host, i, rows, rk, fill, cr, opt) {if (f == null) { return i }let c = thisreturn f(&c, &m, &o, &host, i, &rows, rk, &fill, cr, &opt)}acqFail(tag, host) {console.error('claim: no element for', tag, 'under', host == null ? null : host.tagName)return null}// the classes a reference's `#Child` rule put on the composition root, beside whatever// class the root itself carries (view.hl withRootClasses, on the build walk)rootClasses(el, opt) {if (opt == null || opt.classes == null || opt.classes.length == 0) { return null }let add = ''for (c of opt.classes) { add = add == '' ? c : add + ' ' + c }let have = el.getAttribute('class')el.setAttribute('class', have == null || have == '' ? add : have + ' ' + add)return null}// AN ELEMENT THAT SHOWS SOMETHING is a site of this mount. The names come from the// generated call — the compile step read them off the View — and the two-way `value`// bind is applied where the element is a form control the member paints.siteAt(&m, el, names, site, valueMember, isSelect, rows) {let keep = []for (name of names) {// the SHELL's `slot` is where the route component hangs: swapped by navigation,// never painted (the compile step already drops `Style`, folded at build)if (!(name == 'slot' && m.isShell)) { keep.push(name) }}if (valueMember != null && rows[valueMember] == null && el.value != null) {bindValue(&m, valueMember, el, isSelect)}if (keep.length > 0) { m.sites.push({ el = el; site = site; names = keep; region = false; rows = rows; }) }return null}applySelectAt(&m, el, v) {el.value = v == null ? '' : '' + vreturn null}// A HANDLER, WIRED AT CREATION. The literal is the element's own — its named entries// are the generated `__hlLit`, the `for` rows in scope ride on it, and the owner is the// instance BY REFERENCE (a handler writing a copy would repaint nothing).onAt(&m, el, event, site, rows, wrote, touched) {if (el.__hlLits == null) { el.__hlLits = {} }el.__hlLits[event] = literalFor(&m, el)let at = m.chainlet root = m.rootKindlet rowNames = rows == null ? [] : rows.keys()el.addEventListener(event, (ev) => {let lit = el.__hlLits[event]for (rk of rowNames) { lit[rk] = el.__hlRows[rk] }fire(&lit, event, ev)el.__hlLits[event] = litpatch(at, root, wrote, touched)})return null}// THE SHELL'S SLOT: where the route component hangs. On the build walk the re-created// element adopts the page's nodes, and a page the shell never rendered is built here.slotShell(&m, host, cr) {slotEl = hostif (!cr) { return null }if (detachedSlot != null && detachedSlot != host) {let moving = Array.from(detachedSlot.childNodes)for (node of moving) { host.appendChild(node) }}detachedSlot = nullif (!pageShown && page != null) {page.sites = []create(&page, host)headSites(&page)pageShown = true}return null}// A CHILD'S SLOT: the fragment its HOST wrote, built in the host's frame. The fill names// that frame by address, and `run` re-enters it when this walk is not it.slotFill(&m, &o, host, i, fill, cr) {if (fill == null) { return i }if (cr && fill.detached) {let anchor = document.createComment('hl:slot')host.appendChild(anchor)pendingFills[] = { key = fill.key; site = fill.site; rows = fill.rows; rowKey = fill.rowKey; outer = fill.outer; chain = fill.chain; rootKind = fill.rootKind; anchor = anchor; }return i}if (ownsFill(o, fill)) {let f = walkOf(fill.key, 'f', fill.site)return run(f, &o, &o, host, i, fill.rows, fill.rowKey, fill.outer, cr, null)}return fillFromRoot(fill, host, i, cr)}// the fill's owner, re-entered from the page or the shell by the address it carriesfillFromRoot(fill, host, at, cr) {if (fill.rootKind == 'shell') {if (shell == null) { return at }return fillInto(&shell, fill, 0, host, at, cr)}if (page == null) { return at }return fillInto(&page, fill, 0, host, at, cr)}fillInto(&m, fill, depth, host, at, cr) {if (depth >= fill.chain.length) {let f = walkOf(fill.key, 'f', fill.site)return run(f, &m, &m, host, at, fill.rows, fill.rowKey, fill.outer, cr, null)}let kid = m.kids[fill.chain[depth]]if (kid == null) { return at }let out = fillInto(&kid, fill, depth + 1, host, at, cr)m.kids[fill.chain[depth]] = kidreturn out}// the fill context a reference hands its child: the fragment's owner by address, the// host's rows and rowKey, and the fill the host itself was standing infillFor(&m, spec, rows, rowKey, fill) {if (!spec.fill) { return null }return { key = m.key; site = spec.site; rows = rows; rowKey = rowKey; outer = fill; chain = m.chain; rootKind = m.rootKind; detached = false; }}// ---- a `for`: the region, its rows, its anchor ------------------------------------forAt(&m, &o, host, i, site, rowName, listFn, rows, rk, fill, cr, names) {regionAt(&m, host, site, rows, rk, fill, true, rowName, listFn, names)startRegionAt(host, site)let inst = m.instancelet rws = rowslet entries = listFn(&inst, &rws)let body = walkOf(m.key, 'b', site)if (entries != null) {let keys = listKeys(entries)let ri = 0for (entry of entries) {let inner = rows + {}inner[rowName] = entrylet began = cr ? host.children.length : ilet out = run(body, &m, &o, host, cr ? 0 : i, inner, rk + '#' + keys[ri], fill, cr, null)if (!cr) { i = out }noteRowAt(host, site, keys[ri], entry, elementsBetween(host, began, cr ? host.children.length : i))ri = ri + 1}}endRegionAt(host, site, cr ? null : (host.children[i] == null ? null : host.children[i]))return i}ifAt(&m, &o, host, i, site, condFn, rows, rk, fill, cr, names) {regionAt(&m, host, site, rows, rk, fill, false, null, condFn, names)let inst = m.instancelet rws = rowslet branch = condFn(&inst, &rws) ? walkOf(m.key, 't', site) : walkOf(m.key, 'e', site)let start = cr ? host.childNodes.length : ilet out = run(branch, &m, &o, host, i, rows, rk, fill, cr, null)// a branch something can flip is marked, so a flip replaces THE BRANCH and nothing// else the host holds (ticket #32); a condition nothing can move needs no markif (names != null && names.length > 0) { noteIfAt(host, site, cr, start, cr ? host.childNodes.length : out) }return out}// THE NODES AN `if` PUT INTO ITS HOST, and an anchor comment standing right after them.// Built: every node the walk appended. Claimed from the server's HTML: the elements the// walk claimed and the text between them. The anchor is where a branch that is empty// now puts the next one — the same mark a `for` leaves (endRegionAt).noteIfAt(host, site, cr, start, to) {let nodes = []if (cr) {let k = startwhile (k < to) { nodes.push(host.childNodes[k]) k = k + 1 }} else {let els = elementsBetween(host, start, to)if (els.length > 0) {let last = els[els.length - 1]let n = els[0]let more = truewhile (more && n != null) {nodes.push(n)if (n == last) { more = false } else { n = n.nextSibling }}}}let anchor = document.createComment('hl:if')let next = nullif (!cr && host.children[to] != null) { next = host.children[to] }host.insertBefore(anchor, next)if (host.__hlIf == null) { host.__hlIf = {} }host.__hlIf[site] = { nodes = nodes; anchor = anchor; }return null}// A REGION SITE carries what the patch needs and nothing else: the names its list or// its condition reads (the compiler's answer, by this site), and the read itself as the// generated closure. One per element and site — a rebuild walks this node again.regionAt(&m, host, site, rows, rowKey, fill, isFor, rowName, readFn, names) {// a row-scoped read is its row's, and the language resolved it as one, so the// compile step names none here: an empty set is a region nothing can moveif (names == null || names.length == 0) { return null }for (s of m.sites) {if (s.region && s.el == host && s.site == site) { return null }}let held = nullif (fill != null) { held = fill + {} held.detached = true }m.sites.push({ el = host; site = site; names = names; region = true; rows = rows; rowKey = rowKey; fill = held; isFor = isFor; row = rowName; read = readFn; })return null}startRegionAt(host, site) {if (host.__hlFor == null) { host.__hlFor = {} }host.__hlFor[site] = { keys = []; rows = {}; anchor = null; }return null}noteRowAt(host, site, key, entry, els) {let box = host.__hlFor[site]if (box == null) { return null }box.keys.push(key)box.rows[key] = { els = els; entry = entry; }host.__hlFor[site] = boxreturn null}endRegionAt(host, site, before) {let box = host.__hlFor[site]if (box == null) { return null }let anchor = document.createComment('hl:for')host.insertBefore(anchor, before)box.anchor = anchorhost.__hlFor[site] = boxreturn null}// ---- a composed child --------------------------------------------------------------// The reference's own description is written at its use site by the compile step: what// it binds, what it overwrites, the classes it puts on the child's roots.kidAt(&m, host, i, spec, rows, rk, fill, cr, opt) {let kk = spec.kid + rklet kid = m.kids[kk]if (kid == null) { kid = mintFrom(&m, spec, rows) }if (kid == null) { return i }bindFrom(&kid, &m, spec, rows)if (cr) { kid.sites = [] }kid.chain = childChain(m.chain, kk)kid.rootKind = m.rootKindlet firstAt = cr ? host.children.length : i// WHAT A REFERENCE OVERWRITES REACHES THE FIRST ELEMENT, however deep. A child// whose View is a bare reference to another component renders no element of its// own, so the events the host overwrote travel on through it — the old hl:web kept that in// a field that the first element consumes; here it rides on the option the walk is// handed, and a reference with ons of its own replaces it.let over = []if (spec.ons != null && spec.ons.length > 0) { for (o of spec.ons) { over.push(o.event) } }else if (opt != null && opt.over != null) { over = opt.over }let kidOpt = { over = over; classes = spec.classes; }let f = walkOf(kid.key, 'v', null)let out = run(f, &kid, &m, host, cr ? 0 : i, {}, '', fillFor(&m, spec, rows, rk, fill), cr, kidOpt)if (!cr) { i = out }if (cr || kid.bindings.length == 0) { kid.bindings = [] bindKids(&kid, kid.view) }let roots = rootsBetween(host, firstAt, cr ? host.children.length : i)refOnsFrom(&m, spec, roots, rows)for (el of roots) { el.__hlKid = true }m.kids[kk] = kidreturn i}// the value a binding of this reference carries, off the host instancespecValue(b, &m, rows) {if (b.text != null) { return b.value }if (b.member != null) { return view.value({ k = 'member'; name = b.member; }, m.instance, rows) }if (b.ref != null) {let inst = m.instancelet rws = rowslet f = b.refreturn f(&inst, &rws)}return null}mintFrom(&m, spec, rows) {let bp = blueprintOf(spec.key)if (bp == null) { return null }let args = {}for (b of spec.bindings) { args[b.name] = specValue(b, &m, rows) }let inst = hlLoad(bp.module, args)return { key = spec.key; instance = inst; view = bp.view; sites = []; isShell = false; kids = {}; bindings = []; chain = []; rootKind = m.rootKind; }}bindFrom(&kid, &m, spec, rows) {for (b of spec.bindings) { kid.instance[b.name] = specValue(b, &m, rows) }return null}// A HANDLER WRITTEN ON A REFERENCE is the HOST's: its literal is minted here with the// reference's bindings as its own entries, and its write set is filed under the// reference's own `on` site in the host's table.refOnsFrom(&m, spec, els, rows) {if (spec.ons == null || spec.ons.length == 0) { return null }let named = {}for (b of spec.bindings) { named[b.name] = specValue(b, &m, rows) }for (k of rows.keys()) { named[k] = rows[k] }let inst = m.instancelet lit = hlLiteralNew(spec.site, named, &inst)for (el of els) {for (o of spec.ons) { listenRef(&m, &lit, el, o) }}return null}// ---- claim: walk the tree in lockstep with the DOM the same tree produced --------// Round one granularity: an element whose children include a member is a SITE for// each of those members; a repaint rewrites that element's children from the tree.// `i` is the running index into `host.children`; a `for` consumes one run of// elements per entry, an `if` the run of the branch that stands.claim(&m, host) {let f = walkOf(m.key, 'v', null)run(f, &m, &m, host, 0, {}, '', null, false, null)return null}// a kid's address: its host's, plus the key the host holds it underchildChain(chain, kk) {let out = chain == null ? [] : chain.slice(0)out.push(kk)return out}// the elements a walk placed under `host` between two indiceselementsBetween(host, at, to) {let out = []let i = atwhile (i < to) {if (host.children[i] != null) { out.push(host.children[i]) }i = i + 1}return out}// the keys a list has, in order: the record's id (view.rowKey), an index where the row// is no record, and a suffix where one id stands twice. THE SERVER DOES NOT DEDUPE —// its `mountKids` gives two rows of one id one mount key; a list with repeated ids is// written down here rather than answered twice.listKeys(entries) {let out = []let seen = {}let ri = 0for (entry of entries) {let k = view.rowKey(entry, ri)if (seen[k] != null) { k = k + ':' + ri }seen[k] = trueout.push(k)ri = ri + 1}return out}// ---- the patch: old keys against new ---------------------------------------------// A write to the list is answered by a DIFF and nothing else: the rows that are gone// are removed, the rows that arrived are built, the rows that stayed are MOVED where// the order changed and are left alone where it did not — and each of them is handed// the record it now stands for, which rewrites only the attributes and the text the// DOM does not already hold. The region's element is never emptied.paintFor(&m, s) {let host = s.elif (host.__hlFor == null) { return null }let box = host.__hlFor[s.site]if (box == null || box.anchor == null) { return null }// ONE PAINT OF A LIST AT A TIME. Building a row can wait (a composed child's module// loads on first use), and a second write to the list in that time — a push right// behind the handler's own write — read the box before the first paint had filed// its row, and built the row again. The first paint used to be hidden by the `if`// beside the list rebuilding the whole host; since an `if` replaces only its branch// (ticket #32) it showed as a doubled comment. A paint that arrives while one runs// is remembered, and the running one paints again from the list as it then stands.if (host.__hlForBusy == null) { host.__hlForBusy = {} }if (host.__hlForBusy[s.site] != null) { host.__hlForBusy[s.site] = 'again' return null }host.__hlForBusy[s.site] = 'busy'let inst = m.instancelet rws = s.rowslet read = s.readlet entries = read(&inst, &rws)if (entries == null) { entries = [] }// the keys this list has now, in orderlet keys = listKeys(entries)let next = []let ri = 0for (entry of entries) {next.push({ key = keys[ri]; entry = entry; })ri = ri + 1}// 1. THE ROWS THAT ARE GONE: their elements, their sites and their children's// mounts leave together.let keep = {}for (r of next) { keep[r.key] = true }for (k of box.keys) {if (keep[k] == null) { dropRow(&m, s, &box, k) }}// 2. THE ROWS IN ORDER. `at` is the node standing where the next row belongs: a// row already there advances it, a row that is not is moved or built before it.let at = box.anchorlet found = falsefor (k of box.keys) {if (!found && keep[k] != null) {let held = box.rows[k]if (held != null && held.els.length > 0) { at = held.els[0] found = true }}}let placed = []for (r of next) {let held = box.rows[r.key]if (held == null) {buildRow(&m, s, &box, r, at)} else if (held.els.length > 0 && held.els[0] == at) {// already in place: step over itat = afterRow(held, box.anchor)updateRow(&m, s, &box, r)} else {moveRow(host, held, at)updateRow(&m, s, &box, r)}placed.push(r.key)}box.keys = placedhost.__hlFor[s.site] = boxlet again = host.__hlForBusy[s.site] == 'again'host.__hlForBusy[s.site] = nullif (again) { paintFor(&m, s) }return null}// the node that follows a row's elements — where the walk goes on fromafterRow(held, anchor) {if (held.els.length == 0) { return anchor }let last = held.els[held.els.length - 1]if (last.nextSibling == null) { return anchor }return last.nextSibling}// A ROW LEAVES: its elements go off the document, the sites that were registered// inside it are dropped (they point at nodes nobody can see), and so do the mounts of// the children it held — a child of a row is keyed by that row (view.rowKey).dropRow(&m, s, &box, key) {let held = box.rows[key]if (held == null) { return null }let kept = []for (site of m.sites) {if (!insideRow(held, site.el)) { kept.push(site) }}m.sites = keptlet full = (s.rowKey == null ? '' : s.rowKey) + '#' + keyfor (kk of m.kids.keys()) {if (kk.includes(full + '#') || kk.endsWith(full)) { delete m.kids[kk] }}for (el of held.els) { el.remove() }delete box.rows[key]return null}insideRow(held, el) {if (el == null) { return false }for (top of held.els) {if (top == el) { return true }if (top.contains(el)) { return true }}return false}// A ROW MOVES: `moveBefore` where the browser has it, because it keeps the element's// state (focus, a playing video, an open dialog) across the move; `insertBefore` else.moveRow(host, held, at) {for (el of held.els) {if (host.moveBefore != null) { host.moveBefore(el, at) }else { host.insertBefore(el, at) }}return null}// A ROW ARRIVES: built detached and moved in, because `createInto` appends and the// row's place is where `at` stands — which may be in the middle of the region.buildRow(&m, s, &box, r, at) {let host = s.ellet inner = s.rows + {}inner[s.row] = r.entrylet bin = document.createElement('div')let body = walkOf(m.key, 'b', s.site)run(body, &m, &m, bin, 0, inner, (s.rowKey == null ? '' : s.rowKey) + '#' + r.key, s.fill, true, null)let els = []let moving = Array.from(bin.children)for (el of moving) { els.push(el) }let nodes = Array.from(bin.childNodes)for (node of nodes) { host.insertBefore(node, at) }box.rows[r.key] = { els = els; entry = r.entry; }return null}// A ROW STAYS, AND THE RECORD IT SHOWS MAY BE ANOTHER ONE — `upsert` hands the row a// new record under the same id, and `items[0].title = 'edited'` writes into the one it// already has. Both are answered here: the row's elements are handed the record (their// `__hlRows`, which is also what a handler on the row reads), and every attribute and// text leaf is rewritten ONLY where the DOM does not already hold the value. That is// why a push into 2000 rows costs no mutation on the 2000 that did not change.updateRow(&m, s, &box, r) {let held = box.rows[r.key]if (held == null) { return null }held.entry = r.entrybox.rows[r.key] = heldfor (el of held.els) { refreshRow(&m, el, s.row, r.entry) }rebindRow(&m, s, r)return null}// A ROW'S CHILDREN TAKE THEIR BINDINGS AGAIN. A reference inside a `for` body is not// in `m.bindings` — that list is built from the View's own walk, which does not enter a// `for` (the row is the scope, and there is one child per row) — so a host member that// feeds a row's child used to reach it only because the region REBUILT and the child// was minted again with the value of the moment (the framework gate's own case:// home.hl writes `noteOpen`, every row's RowNote takes it and hands it to RowMark, and// the grandchild's region appears). Nothing rebuilds any more, so the edge is walked// here — and only what MOVED is written and repainted, or every list write would// repaint every row's child.rebindRow(&m, s, r) {let rk = (s.rowKey == null ? '' : s.rowKey) + '#' + r.keylet inner = s.rows + {}inner[s.row] = r.entryrebindNodes(&m, rowBody(m.key, s.site), inner, rk)return null}// THE ROW'S OWN NODES, for the binding edges a row's child takes again. The tree is// still what the seed carries (it is the mount's `view`), and this is a read of it, not// a walk of the DOM: the compiled row factory builds, this re-binds.rowBody(key, site) {let bp = blueprints[key]if (bp == null) { return [] }return bodyIn(bp.view, site)}bodyIn(nodes, site) {for (n of nodes) {if (n.k == 'for' && n.site == site) { return n.body }if (n.k == 'el') { let got = bodyIn(n.children, site) if (got.length > 0) { return got } }if (n.k == 'if') {let a = bodyIn(n.then, site)if (a.length > 0) { return a }let b = bodyIn(n.other, site)if (b.length > 0) { return b }}if (n.k == 'for') { let got = bodyIn(n.body, site) if (got.length > 0) { return got } }if (n.k == 'component' && n.fill != null) { let got = bodyIn(n.fill, site) if (got.length > 0) { return got } }}return []}rebindNodes(&m, nodes, rows, rk) {for (n of nodes) {if (n.k == 'component') {let kk = view.kidKey(n.path) + rklet kid = m.kids[kk]if (kid != null) {let moved = []for (b of n.bindings) {let v = nullif (b.text != null) { v = view.refValue(b) }else if (b.member != null) { v = view.value({ k = 'member'; name = b.member; }, m.instance, rows) }else if (b.ref != null) { v = view.value(b.ref, m.instance, rows) }if (kid.instance[b.name] != v) { kid.instance[b.name] = v moved.push(b.name) }}if (moved.length > 0) { repaintAll(&kid, moved) }m.kids[kk] = kid}if (n.fill != null) { rebindNodes(&m, n.fill, rows, rk) }} else if (n.k == 'el') {rebindNodes(&m, n.children, rows, rk)} else if (n.k == 'if') {rebindNodes(&m, n.then, rows, rk)rebindNodes(&m, n.other, rows, rk)}}return null}refreshRow(&m, el, name, entry) {// A COMPOSED CHILD'S DOM IS ITS OWN MOUNT'S: its elements read the CHILD's// instance, and painting them from this one would show the wrong values. The walk// stops at the roots a reference claimed (`__hlKid`, set where they are claimed// and built).if (el.__hlKid == true) { return null }if (el.__hlRows != null) {let next = el.__hlRows + {}next[name] = entryel.__hlRows = next// (The literal a handler on this element fires takes its row entries from// `__hlRows` when it fires — see `bind` — so there is nothing to update here.// A handler written on a REFERENCE (bindRefOns) mints one literal for the// child's roots and does not: its bindings are re-applied by rebindRow, its// own entries are not.)}rowPaint(&m, el)let kids = Array.from(el.children)for (k of kids) { refreshRow(&m, k, name, entry) }return null}// ONE ELEMENT OF A ROW, REDRAWN WHERE IT IS WRONG. The guard is the DOM's own value,// not a remembered one: nothing is serialised and nothing is compared to a digest.rowPaint(&m, el) {let site = el.__hlSiteif (site == null) { return null }let comp = compiledOf(el.__hlKey == null ? m.key : el.__hlKey)if (comp == null) { return null }let entry = comp.p[site]if (entry == null) { return null }let f = entry.rif (f == null) { return null }let inst = m.instancelet rws = el.__hlRowslet e = elf(&e, &inst, &rws)return null}bindValue(&m, name, el, isSelect) {let held = m.instance[name] == null ? '' : '' + m.instance[name]// A SELECT IS PAINTED BY THE MEMBER FIRST: what it shows is one of its options,// and the member decides which. The server already marked it (view.hl `selected`),// so this is a no-op there; on a select the client built it is the paint. Only// then is the read-back right — before it, an unpainted select reports its FIRST// option and the read-back would write that back into the member.if (isSelect && held != '') { el.value = held }if (el.value != held) { m.instance[name] = el.value liftValue(m.chain, m.rootKind, name, el.value) }el.addEventListener('input', (ev) => {m.instance[name] = el.value// AND UP THROUGH THE REFERENCE THAT BOUND IT, if this control stands inside a// composed child: the host's member is what the app reads (see liftValue)liftValue(m.chain, m.rootKind, name, el.value)})return null}// ---- `value` IS TWO-WAY THROUGH A COMPOSITION TOO --------------------------------// `value = member` on a control is the framework's two-way name: the member paints the// field and the field writes the member (mission 132). A composed child is a mount of// its own, so that write landed on the CHILD's member and stopped there — `Field// { value = who }` left the host's `who` empty while the DOM held what was typed, and// routger's login submit read null (creator, W12). The host→child binding is an edge// the mount already carries; this is the SAME edge run backwards on input, and only// for the name `value`: every other binding name stays one-way.//// The child cannot name its host (a mount record is a value), so it names it by the// ADDRESS it already carries — the kid keys from the page or the shell — and the walk// below re-enters the host by reference. It carries on upward as long as the reference// it came through was itself a `value` binding, which is what makes a component whose// View is a bare reference to a field reach the page's member through both hops.liftValue(chain, root, target, value) {if (target != 'value') { return null }if (chain == null || chain.length == 0) { return null }if (root == 'shell') {if (shell == null) { return null }liftInto(&shell, chain, 0, target, value)} else {if (page == null) { return null }liftInto(&page, chain, 0, target, value)}return null}// walk the address down to the mount that HOLDS the last key — that mount is the host —// and write what its reference bound to the child's `target`, repainting its own sitesliftInto(&m, chain, at, target, value) {if (at >= chain.length - 1) {for (b of m.bindings) {// a field path (`value = row.text`) names no member to write back intoif (b.kid == chain[at] && b.target == target && b.ref == null) {if (m.instance[b.name] != value) {m.instance[b.name] = valuerepaintAll(&m, [b.name])}liftValue(m.chain, m.rootKind, b.name, value)}}return null}let kid = m.kids[chain[at]]if (kid == null) { return null }liftInto(&kid, chain, at + 1, target, value)m.kids[chain[at]] = kidreturn null}// THE ELEMENT'S LITERAL: a value of the class the module minted for the literal's// SITE (`file:line:col`, the id the JavaScript target registers at load), with the// element's own named entries — its attributes as the tree has them — and the// `for` row variables in scope as its own entries, the way the language builds a// row's literal (the row rides on the value). Built HERE and not looked up in the// instance's View: a row created after the list changed has no value there, and// a name-path cannot address ordered content. The handlers read own entries first,// then the owner's members — the owner is the component instance.literalFor(&m, el) {let rows = el.__hlRowslet inst = m.instancelet rws = rows// THE ELEMENT'S OWN ENTRIES, compiled: its attributes by name, with the reads// written in (compile.hl `litNamed`)let mk = el.__hlLitlet named = mk == null ? {} : mk(&inst, &rws)for (k of rows.keys()) { named[k] = rows[k] }// the owner by REFERENCE: a call argument is copied, and a handler writing a// copy's member would repaint nothingreturn hlLiteralNew(el.__hlSite, named, &inst)}// WHAT A HANDLER WROTE, REPAINTED — the whole of the answer to a local event.// `&m` is the mount whose instance the handler's owner is, so a write reaches this// mount's sites and, through its bindings, the children that read the member.//// AND UPWARD, THROUGH A ROUTINE THE HOST HANDED DOWN. `Badge { onHide = hideBadge }`// gives the child a FUNCTION of the host's; the child's handler calls it and the// host's member moves. The child's own table cannot say so — the member it called// has no initializer there — but the HOST's does: the binding edge names the host// member (`hideBadge`), and the host's table says what calling it writes. That is// the same table read one mount up, not a new mechanism.patch(chain, root, names, targets) {patchAt(chain, root, names)patchUp(chain, root, targets)settle()return null}// A MOUNT RECORD IS A VALUE (the rule this whole file is written around), so a// listener cannot hold the live one — the record it was bound against is a copy the// walk wrote back, and a region rebuild replaces it again. It holds the mount's// ADDRESS instead and the walk re-enters from the root, exactly as `liftInto` and// `fillAt` do. `refresh()` used to get this for free by starting at the root every// time; a write set has to say where it lands.patchAt(chain, root, names) {if (names == null || names.length == 0) { return null }if (root == 'shell') {if (shell == null) { return null }patchDown(&shell, chain, 0, names)} else {if (page == null) { return null }patchDown(&page, chain, 0, names)}return null}patchDown(&m, chain, at, names) {if (chain == null || at >= chain.length) {repaintAll(&m, names)return null}let kid = m.kids[chain[at]]if (kid == null) { return null }patchDown(&kid, chain, at + 1, names)m.kids[chain[at]] = kidreturn null}patchUp(chain, root, targets) {if (targets == null || targets.length == 0) { return null }if (chain == null || chain.length == 0) { return null }if (root == 'shell') {if (shell == null) { return null }patchInto(&shell, chain, 0, targets)} else {if (page == null) { return null }patchInto(&page, chain, 0, targets)}return null}// walk the address down to the mount that HOLDS the last key — that mount is the host// — and repaint what the routines it bound into the child write (and carry on upward,// because the host may have received them from ITS host)patchInto(&m, chain, at, targets) {if (at >= chain.length - 1) {let names = []let up = []for (b of m.bindings) {if (b.kid == chain[at] && b.ref == null && targets.includes(b.target)) {if (!up.includes(b.name)) { up.push(b.name) }for (w of memberWrites(m.key, b.name)) { if (!names.includes(w)) { names.push(w) } }}}repaintAll(&m, names)patchUp(m.chain, m.rootKind, up)return null}let kid = m.kids[chain[at]]if (kid == null) { return null }patchInto(&kid, chain, at + 1, targets)m.kids[chain[at]] = kidreturn null}// one listener, in its own frame so the event name it closes over is this one.// `&m` is the HOST — a handler written on a reference is the host's, and its write// set is filed under the reference's own `on` site in the host's table.listenRef(&m, &lit, el, o) {let wrote = o.sets[0]let touched = o.sets[1]let at = m.chainlet root = m.rootKindel.addEventListener(o.event, (ev) => {fire(&lit, o.event, ev)patch(at, root, wrote, touched)})return null}// the elements a composed child rendered directly under `host`, between two marks in// the child list — its roots, whatever its tree put thererootsBetween(host, firstAt, to) {let out = []let i = firstAtwhile (i < to) {if (host.children[i] != null) { out.push(host.children[i]) }i = i + 1}return out}fire(&lit, event, ev) {if (event == 'click') { emit lit.click(ev) return null }if (event == 'input') { emit lit.input(ev) return null }if (event == 'change') { emit lit.change(ev) return null }if (event == 'submit') { emit lit.submit(ev) return null }if (event == 'keydown') { emit lit.keydown(ev) return null }if (event == 'keyup') { emit lit.keyup(ev) return null }if (event == 'focus') { emit lit.focus(ev) return null }if (event == 'blur') { emit lit.blur(ev) return null }if (event == 'dblclick') { emit lit.dblclick(ev) return null }if (event == 'pointerdown') { emit lit.pointerdown(ev) return null }if (event == 'pointermove') { emit lit.pointermove(ev) return null }if (event == 'pointerup') { emit lit.pointerup(ev) return null }if (event == 'pointercancel') { emit lit.pointercancel(ev) return null }// EVERY OTHER STANDARD DOM EVENT, by name (ticket #31): `on mouseover()` was bound// and never ran, because only the thirteen names above were written out. The// language's own dynamic emit dispatches the same handler an `emit lit.x(ev)` does.if (domEvents.includes(event)) { hlEmitArgs(&lit, event, [ev]) return null }console.warn('framework: not a standard DOM event, so nothing handles it here:', event)return null}// THE STANDARD DOM EVENTS a View handler may name beyond the thirteen `fire` writes out.// A name outside this list — a custom event an element dispatches itself — is not bound// yet: whether a View may handle one is the creator's to rule (ticket #31).static domEvents = ['mouseover' 'mouseout' 'mouseenter' 'mouseleave' 'mousedown' 'mouseup' 'mousemove' 'contextmenu' 'wheel' 'auxclick''pointerover' 'pointerout' 'pointerenter' 'pointerleave' 'gotpointercapture' 'lostpointercapture''touchstart' 'touchmove' 'touchend' 'touchcancel''keypress' 'focusin' 'focusout' 'beforeinput' 'compositionstart' 'compositionupdate' 'compositionend''select' 'selectionchange' 'invalid' 'reset' 'search' 'toggle' 'cancel' 'close''drag' 'dragstart' 'dragend' 'dragenter' 'dragleave' 'dragover' 'drop''copy' 'cut' 'paste' 'scroll' 'scrollend' 'resize' 'load' 'error' 'abort''play' 'pause' 'ended' 'playing' 'timeupdate' 'volumechange' 'seeking' 'seeked' 'loadeddata' 'loadedmetadata' 'canplay' 'canplaythrough' 'waiting' 'ratechange' 'durationchange' 'emptied' 'stalled' 'suspend' 'progress''animationstart' 'animationend' 'animationiteration' 'animationcancel' 'transitionstart' 'transitionend' 'transitionrun' 'transitioncancel']// ---- C2: MEMBERS WITH INITIALIZERS ARE DERIVATIONS -------------------------------// "Members with initializers are derivations that re-run locally when what they read// changes" (CONCEPT §2). Everything that sentence needs is compiler output: the// module's `derivations` table says what each initializer reads, and the class// carries each initializer as a callable keyed by its own site (`__derive__`, which// the emitter writes for EVERY member of EVERY class — it knows nothing of a View and// nothing of this framework; the root itself calls it instead of carrying a second// copy of the expression).//// So a write is followed by this: every derivation that reads a member which MOVED// runs again, in declaration order, and what it changes has moved too. The sites are// repainted afterwards, once per member — which is why this answers with the whole// moved set instead of painting as it goes.//// A DERIVATION IS NOT ITS OWN INPUT. A second assignment to a member at a root IS a// second initializer of that member (`out = out + 'x'` is one the language accepts),// and re-running that on a write to `out` would accumulate rather than derive. The// member's own name is therefore not one of its inputs here. Measured 2026-09-14:// none of the four reference apps has an initializer that reads its own member.//// THE BOUND IS THE NUMBER OF DERIVATIONS. One pass answers a file written top to// bottom; the rounds are there for a file that is not, and they stop where a cycle// between two members would otherwise spin.moved(&m, names) {let out = names.slice(0)let list = derivationsOf(m.key)if (list.length == 0) { return out }// A CLASS THAT COMPUTES NOTHING HERE HAS NO CALLABLE: every member of it is a// declaration without an initializer, a static, or the other realm's (demo-blog's// post page is one — its `post` comes from the server). The table still lists// those initializers, so the method is asked for before it is used.if (m.instance.__derive__ == null) { return out }let rounds = 0let again = truewhile (again && rounds <= list.length) {again = falserounds = rounds + 1for (d of list) {// AN EXPLICIT WRITE OUTRANKS A COMPUTED DEFAULT — the language's own rule// for construction (hlNew pins the caller's values while the root runs: "a// run-body assignment is a computed DEFAULT; an explicit caller value// outranks it"), read here for the same relation between a handler and an// initializer. demo-blog's post page is the case: its `postsChanged`// handler writes `title`, `paragraphs` and the rest from what the server// answered, and those members' initializers would otherwise recompute them// from a `_post` the browser never refreshed. What the handler wrote stands;// everything DOWNSTREAM of it is derived.if (names.includes(d.name)) { }else if (feedsFrom(d, out)) {let before = m.instance[d.name]// THE CLASS'S OWN CALLABLE, by the site the table named it with.// A member this realm does not compute (a server-realm initializer,// a static, the View) has no branch there and nothing happens.m.instance.__derive__(d.site)if (m.instance[d.name] != before) {if (!out.includes(d.name)) { out.push(d.name) again = true }}}}}return out}// does this derivation read one of the members that moved — its own name aside?feedsFrom(d, names) {for (r of d.reads) {if (r != d.name && names.includes(r)) { return true }}return false}// A WRITE SET, DERIVED AND THEN PAINTED: the one way in for every caller that knows// which members moved. Painting is the last act, so a derived member's sites are// drawn once, with its final value.repaintAll(&m, names) {if (names == null || names.length == 0) { return null }for (n of moved(&m, names)) { repaint(&m, n) }return null}// ---- repaint: a member was written; every site that reads it is redrawn ---------write(&m, name, value) {m.instance[name] = valuerepaintAll(&m, [name])settle()return null}repaint(&m, name) {let sites = m.sites.slice(0) // a paint may add sites; walk what was therefor (s of sites) {if (s.names.includes(name)) { paint(&m, s, name) }}// DOWN THE BINDINGS: a child bound to this member at its reference site gets// the value as its own member and repaints its own sites — the host knows the// binding, the child knows nothingfor (b of m.bindings) {if (b.name == name) {let kid = m.kids[b.kid]kid.instance[b.target] = bindingValue(b, &m)// …and the CHILD's own derivations follow the member it was givenrepaintAll(&kid, [b.target])m.kids[b.kid] = kid}}return null}// THE DIGEST IS GONE (mission 309). `refresh()` stood here: after every DOM event and// every inbound frame it serialised every painted member of every mount to JSON and// string-compared it against the last paint, to find out what a handler had written —// a dirty-check over state, the thing FRAMEWORK_AUDIT §3 measured and named. What a// handler writes is a fact about its syntax, so the compiler now says it (`hlTablesDef`// in the component's own module) and the two callers that used to compare — a local// event's listener and an inbound frame — repaint exactly the members it names. The// `painted` map went with it: nothing compares any more.// A SITE REPAINTS WHAT THE CHANGED MEMBER FEEDS, and nothing else (FRAMEWORK_AUDIT// §5). `name` is the member that moved — the one `repaint` matched this site on.// An element can read two members in two places (`div { class = tone count }`);// writing `tone` used to set the attribute AND rewrite the element's whole text,// which swaps the text node for an identical one: a second mutation record, a lost// selection inside it, and work proportional to the site's content for a write that// never touched it (measured 2026-09-14 on the probe: `tone = 'b'` → 2 records).// A member read in BOTH places still repaints both — the two tests below are// independent, and `names` carries the member once per place it is read.// THE COMPONENT'S COMPILED PAINT (mission 313). The framework compiled this View's// bound spots into statements when it produced the module (plugins/web/compile.hl):// `p` writes what one member feeds, `r` rewrites a row's element where the DOM does not// already hold the value. A component whose View binds nothing has no entry, and an// element with no bound spot has none either — both are "nothing to paint".compiledPaint(key, site) {if (site == null) { return null }let all = window.__hlPaintif (all == null) { return null }let t = all[key]if (t == null) { return null }return t[site]}paint(&m, s, name) {// a head site writes the document's head, not an element of the pageif (s.head == true) { paintHead(&m, s.names[0]) return null }if (s.region) {// A `for` IS KEYED AND PATCHED (C3/C9): its rows are diffed by the record's id// and nothing else on the host is touched. An `if` re-runs the list it stands// in — the compile step registered that list's own walk under this site.if (s.isFor) { paintFor(&m, s) return null }rebuildIf(&m, s)return null}// THE COMPILED STATEMENTS FOR THIS SITE: one per bound spot, with the read written// in, under the member each reads. This is the walk the old hl:web did over the element's// node — its attributes, then its text leaves — decided when the component was// compiled instead of on every paint.let comp = compiledOf(m.key)if (comp == null) { return null }let entry = comp.p[s.site]if (entry == null) { return null }let f = entry.pif (f == null) { return null }let el = s.ellet inst = m.instancelet rws = s.rowsf(&el, &inst, &rws, name)return null}// AN `if` MOVED: the element it stands in is emptied and its child list walked again,// which was the old hl:web's region rebuild — the host's own handlers stay, because the element// is kept and only its children are built (the compiled list carries no `on` node).rebuildIf(&m, s) {let box = s.el.__hlIf == null ? null : s.el.__hlIf[s.site]if (box != null) { rebuildBranch(&m, s, box) return null }let walkList = walkOf(m.key, 'r', s.site)if (walkList == null) { return null }// A SHELL REGION THAT HOLDS THE SLOT: the page's DOM lives under the slot element,// and the rebuild re-creates the element around it — so the slot is kept aside and// the re-created one adopts the page's nodes (slotShell).if (m.isShell && slotEl != null && slotEl != s.el && s.el.contains(slotEl)) { detachedSlot = slotEl }s.el.replaceChildren()run(walkList, &m, &m, s.el, 0, s.rows, s.rowKey != null ? s.rowKey : '', s.fill, true, null)// THE SLOT WAS PUT ASIDE AND THE REBUILD NEVER REACHED ONE: the branch that now// stands places no slot, so the page is off the document.if (m.isShell && detachedSlot != null) {detachedSlot = nullslotEl = nullpageShown = falseif (page != null) { page.sites = [] }}return null}// AN `if` MOVED: ITS BRANCH IS REPLACED, AND NOTHING ELSE (ticket #32, #41). The whole// host used to be emptied and walked again, so every sibling of the `if` — an input// being typed into, a `script { src }` (which then ran again), a custom element with// state of its own — came back as a NEW node, and a write to the condition that did// not even change it cost the input its focus. The branch that stands now is built// into a fragment, what the walk registered on the fragment is re-homed on the host,// and the fragment takes the old branch's place — in one DOM operation when the old// branch had a first node, before the anchor when it was empty.rebuildBranch(&m, s, box) {let host = s.ellet inst = m.instancelet rws = s.rowslet f = s.readlet branch = f(&inst, &rws) ? walkOf(m.key, 't', s.site) : walkOf(m.key, 'e', s.site)let old = []for (n of box.nodes) { if (n.parentNode == host) { old.push(n) } }// A SHELL BRANCH THAT HOLDS THE SLOT: the page's DOM lives under the slot element and// is kept aside, for the rebuilt branch's slot to adopt (slotShell)if (m.isShell && slotEl != null) {for (n of old) { if (n == slotEl || (n.contains != null && n.contains(slotEl))) { detachedSlot = slotEl } }}let frag = document.createDocumentFragment()let before = m.sites.lengthrun(branch, &m, &m, frag, 0, s.rows, s.rowKey != null ? s.rowKey : '', s.fill, true, null)let fresh = Array.from(frag.childNodes)// what the walk marked on the fragment belongs to the hostif (frag.__hlFor != null) {if (host.__hlFor == null) { host.__hlFor = {} }for (k of frag.__hlFor.keys()) { host.__hlFor[k] = frag.__hlFor[k] }}if (frag.__hlIf != null) {for (k of frag.__hlIf.keys()) { host.__hlIf[k] = frag.__hlIf[k] }}// …and so do the regions it registered there; the old registrations of the same// regions on the host are dropped, so each region is registered oncelet again = []let k = beforewhile (k < m.sites.length) {let e = m.sites[k]if (e.el == frag) {e.el = hostm.sites[k] = eif (e.region) { again.push(e.site) }}k = k + 1}if (again.length > 0) {let keep = []let idx = 0for (e of m.sites) {if (!(idx < before && e.region && e.el == host && again.includes(e.site))) { keep.push(e) }idx = idx + 1}m.sites = keep}if (old.length > 0) {old[0].replaceWith(frag)let r = 1while (r < old.length) { old[r].remove() r = r + 1 }} else {host.insertBefore(frag, box.anchor)}box.nodes = freshhost.__hlIf[s.site] = box// THE SLOT WAS PUT ASIDE AND THE BRANCH THAT NOW STANDS PLACES NONE: the page is off// the documentif (m.isShell && detachedSlot != null) {detachedSlot = nullslotEl = nullpageShown = falseif (page != null) { page.sites = [] }}return null}// the tree node of an element by its key path// ---- create: DOM from a tree, for a route component that was not on the page ------create(&m, host) {let f = walkOf(m.key, 'v', null)run(f, &m, &m, host, 0, {}, '', null, true, null)return null}// the shell's View is a `body` element and the document already has one: the walk runs// against document.body, and the element itself only takes the marks a region rebuild// on it would needmarkHost(&m, host, site) {host.__hlSite = sitehost.__hlKey = m.keyif (host.__hlRows == null) { host.__hlRows = {} }return null}// ---- WHOSE FRAGMENT IS THIS? ------------------------------------------------------// A fill carries the ADDRESS of the mount that wrote it — the kid keys from the page or// the shell. While the walk is one composition deep the frame's `owner` IS that mount// and is used directly, which costs nothing and cannot go stale. Deeper — a fill passed// on through a second reference — it is not, and the mount is re-entered from the root// by that address instead.ownsFill(m, fill) {if (m == null || fill == null) { return false }if (fill.chain == null || m.chain == null) { return false }if (fill.rootKind != m.rootKind) { return false }if (fill.chain.length != m.chain.length) { return false }let i = 0while (i < fill.chain.length) {if (fill.chain[i] != m.chain[i]) { return false }i = i + 1}return true}// ---- settle: the fills a region rebuild left standing -----------------------------// A region that rebuilt inside a composed child reached the child's `slot` and left// an ANCHOR comment there: the fragment belongs to the HOST, and the frame doing the// rebuild is the child's. The entry below names the host by ADDRESS — the kid keys// from the page or the shell — because a mount record is a value and cannot be// handed over. Draining happens after the whole walk has unwound and every mount has// been written back, so re-entering the host from the root reaches the live record// and the sites the fill registers survive.settle() {if (pendingFills.length == 0) { return null }let due = pendingFills.slice(0)pendingFills = []for (f of due) { fillAt(f) }return null}// ONE PENDING FILL, built from the mount its address names. Built DETACHED and moved// in: the walk appends, and the fill's place is where the anchor stands, which may be// in the middle of the child's own content.fillAt(f) {if (f.anchor.parentNode == null) { return null }let box = document.createElement('div')fillFromRoot(f, box, 0, true)let moving = Array.from(box.childNodes)for (node of moving) { f.anchor.parentNode.insertBefore(node, f.anchor) }return null}// what a reference-site binding reads off the host instance: a member, or a field// path starting at onebindingValue(b, &m) {if (b.ref != null) { return view.value(b.ref, m.instance, {}) }return m.instance[b.name]}// ---- THE BOUNDARY, this side ----------------------------------------------------// This file is the client realm's EDGE MODULE: it taps the realm broadcast bus,// turns a crossing emit into the frame SPEC's wire protocol describes, and// dispatches an inbound one at the mounted instances. The frames are the// language's, not this framework's — what belongs to this file is only which// carrier they ride.connect() {let proto = location.protocol == 'https:' ? 'wss:' : 'ws:'socket = new WebSocket(proto + '//' + location.host + '/__hl/socket')// HELLO: what this tab has mounted, for the server's fan-out; resent after every// navigation. The session is not named here: the handshake carried the cookie.socket.addEventListener('open', () => { socket.send(JSON.stringify({ t = 'hello'; i = 0; mounts = mountedKeys(); })) })socket.addEventListener('message', (ev) => { frame(JSON.parse(ev.data)) })socket.addEventListener('close', () => { socket = null })return null}// every component key this tab has mounted: the shell, the page, their childrenmountedKeys() {let out = []if (shell != null) { for (k of keysOf(&shell)) { if (!out.includes(k)) { out.push(k) } } }if (page != null) { for (k of keysOf(&page)) { if (!out.includes(k)) { out.push(k) } } }return out}// (built from return values: a list handed down as an argument is a COPY, and a// push into it would be lost — the language's value semantics)keysOf(&m) {let out = [m.key]for (k of m.kids.keys()) {let kid = m.kids[k]for (kk of keysOf(&kid)) { out.push(kk) }}return out}announceMounts() {if (socket != null && socket.readyState == 1) { socket.send(JSON.stringify({ t = 'mounts'; i = 0; mounts = mountedKeys(); })) }return null}// THE TAP. `emit server x(…)` anywhere in this realm — in a component's View// handler, in this file — announces itself here as `hlRealm.peerEmit(transport,// event, payload)`, and what this returns is what the emit ANSWERS: a// value-form emit rides the ack (SPEC "An emit ANSWERS").//// The transport NAME is what an edge module is meant to filter on, and this one// ignores it: a compiled module carries no manifest, so the language announces// `undefined` here. Until the JS target compiles the project's transport table// in (the creator's open question), the carrier is chosen by what is OPEN — the// websocket while it is, the declared REST fallback while it is not.on hlRealm.peerEmit(transport, event, payload) {return crossing(event, payload)}crossing(event, payload) {nextId = nextId + 1let i = nextIdlet text = JSON.stringify({ t = 'emit'; i = i; event = event; payload = payload; })if (socket != null && socket.readyState == 1) {// The ACK is what resolves this: the executor registers the pairing and// puts the frame on the wire, and this line does not continue until the// answer comes back on the same `i`.return new Promise((res, rej) => {pending['k' + i] = ressocket.send(text)})}// The REST carrier — the same emit/ack pair over one POST, for a peer that// has no socket yet. IT CARRIES THE OUTWARD EMITS BACK (creator, 2026-09-14):// there is no connection for the far side to push to, so what a face raised// for this caller rides in the ack as `emits`, and they are delivered HERE,// before the value-form emit answers — the same order a socket sees (the// frames first, the ack after). The far side's fan-out to the OTHER// connections of this session is unaffected: they get theirs over their own// sockets.let res = fetch('/__hl/emit', { method = 'POST' body = text headers = { 'Content-Type' = 'application/json' } })if (!res.ok) { console.error('framework: the boundary is unreachable over REST', res.status) return null }let ack = res.json()if (ack.emits != null) { for (f of ack.emits) { outward(f) } }return answerOf(ack)}// `ok` is the whole truth: a false ack is the far realm saying it did not// handle the emit, and its message is the located one — the event, the realm// and the fact that no class there declares a handler for it.answerOf(ack) {if (!ack.ok) {console.error('framework: the boundary refused an emit — ' + ack.error)return null}return ack.value}frame(f) {if (f.t == 'ack') {let key = 'k' + f.ilet res = pending[key]pending[key] = nullif (res != null) { res(answerOf(f)) }return null}if (f.t == 'emit') { return outward(f) }if (f.t == 'pong') { return null }// `build`: the server re-analysed after a save (its dev watcher) — this page was// rendered under the old analysis, so it reloads and comes back under the new oneif (f.t == 'build') { location.reload() return null }console.warn('framework: unknown frame kind', f.t)return null}// AN EMIT FROM THE OTHER REALM, dispatched at the MOUNTED INSTANCES: the event// name is data, so it goes through the language's boundary dispatch at each// instance, and then what a handler wrote is repainted. A handler that writes a// member is the whole point of the direction — the server says something// happened and the page shows it.outward(f) {if (mounting) { held.push(f) return null }// BY REFERENCE, or the handler writes a copy: a call argument is a VALUE,// and an instance is copied like any other. `&` suppresses that — through a// local, because the ampersand reaches a bare name and not a field path.if (shell != null) { deliver(&shell, f) }if (page != null) { deliver(&page, f) }settle()return null}// at a mount and every mount composed into it: whichever declares the listener runs// it, and the members THAT mount's declared handler for this event writes are// repainted. The frame names the event; the module's table names what a handler for// that event writes (mission 309), so nothing is compared afterwards either.deliver(&m, f) {let inst = m.instancehlEmitArgs(&inst, f.event, f.payload)repaintAll(&m, eventWrites(m.key, f.event))for (k of m.kids.keys()) {let kid = m.kids[k]deliver(&kid, f)m.kids[k] = kid}return null}// ---- routing: a same-origin link is a navigation, the shell stays -----------------listen() {document.addEventListener('click', (ev) => { onClick(ev) })window.addEventListener('popstate', () => { show(location.pathname, false) })return null}// THE CLICK IS CLAIMED INSIDE THE DISPATCH. Every CALL in this language is// awaited, and an awaited `preventDefault` runs a microtask after the listener// returned — after the browser has already carried out the link's activation// when the click was DISPATCHED FROM SCRIPT (`a.click()`), which performs it// synchronously at the end of dispatch. So the page reloaded instead of// navigating: the whole document was replaced under the framework, the fresh one// was still parsing, nothing was hydrated, and the next click landed on an// element that had no handler yet (measured 2026-09-13 on the social app — the// "first click after a navigation does nothing" report; a REAL click happened to// work because Chrome performs a trusted click's navigation in a later task).//// Only a READ of a property is free of that (it compiles to no call), so the// decision to claim the click is made out of properties alone — the anchor is// found by walking up `parentElement`, and its `origin`, `pathname` and `search`// are the anchor's own URL pieces. `preventDefault` is then the FIRST call this// handler makes, and lands while the event is still being dispatched.onClick(ev) {// what this framework never claims: a click already handled, a middle or right// button, and a modified click — the browser's own tab, window and downloadif (ev.defaultPrevented || ev.button != 0 || ev.metaKey || ev.ctrlKey || ev.shiftKey || ev.altKey) { return null }let a = ev.targetwhile (a != null && a.tagName != 'A') { a = a.parentElement }if (a == null || a.href == '' || a.target != '' || a.download != '') { return null }if (a.origin != location.origin) { return null }ev.preventDefault()// only a PAGE of this app is a client-side navigation; anything else — an// asset, a function route, an unknown path — is the browser's own request,// made here because the default was already taken awaylet m = router.match(a.pathname)if (m == null || m.kind != 'component') { location.href = a.href return null }goTo(a.pathname + a.search)return null}// THE NAVIGATION ITSELF, whoever asked for it: the link interception above, or an// app's own code through the package's `navigate` static at the top of this file.// It is NOT named `navigate` because a file's statics are copied onto its// instances, so a static and a method of the same name would be one name with two// meanings and the instance's would be the static's (measured 2026-09-13).goTo(path) {history.pushState({}, '', path)show(path, true)return null}// THE NEXT ROUTE'S TREE AND STATE, over the boundary: `emit server page(path)`// is a value-form crossing emit, so the answer rides the ack back into this// assignment — the same carrier every other emit uses, chosen by what is open.// The shell stays if it is the same one.show(path, pushed) {let next = emit server page(path)if (next == null) { location.href = path return null }if (seed.shell == null || next.shell == null || next.shell.key != seed.shell.key) {location.href = path // another shell: a full documentreturn null}takeBlueprints(next.blueprints)seed = nextmounting = truepage = instantiate(next.page, [], 'page')// the shell may be showing something else: the next page has nowhere to stand and// waits, exactly as one that booted into a closed region doesif (slotEl != null) {slotEl.replaceChildren()create(&page, slotEl)pageShown = true} else {pageShown = false}// the next page's head members are the next mount's sites; the document was not// replaced, so they are painted once here the way the server's `document()` wouldheadSites(&page)wearHead(&page)release()announceMounts()return null}// ---- THE HEAD IS STATE (creator, 2026-09-13) -------------------------------------// `__title`, `__description`, `__image`, `__favicon` and `__meta` are members of the// page like any other, so they are SITES of the page mount, repainted by `paint()`// below whenever a handler's write set names one. A client handler's write, an inbound// push and a navigation therefore all reach the head on the ONE path every other// member takes; nothing here polls and nothing compares.headMembers() { return ['__title' '__description' '__image' '__favicon' '__meta'] }// the page mount's head sites. `el` is null and `node` is null: the element these// write is the document's head, found per member when it is painted.headSites(&m) {for (name of headMembers()) {m.sites.push({ el = null; node = null; names = [name]; region = false; head = true; rows = {}; })}return null}// every head member at once: a navigation's new mount, where each one may have movedwearHead(&m) {for (name of headMembers()) { paintHead(&m, name) }return null}// THE VALUE A HEAD MEMBER SHOWS: the page's own when it declares one, the app's// manifest default otherwise (`appHead`, off the seed) — the same rule the server's// `headOf` applies, so a page that clears its title gets the app's back and never// the previous page's.headValue(&m, name, fallback) {if (m.instance[name] != null) { return m.instance[name] }return fallback}// ONE HEAD MEMBER, into the document. The element is reused when the first document// carried it and created when it did not (a page that declares an image where the// app declared none).paintHead(&m, name) {if (name == '__title') {let v = headValue(&m, '__title', appHead != null ? appHead.title : null)if (v != null) { document.title = v }headMeta('property', 'og:title', v)} else if (name == '__description') {let v = headValue(&m, '__description', appHead != null ? appHead.description : null)headMeta('name', 'description', v)headMeta('property', 'og:description', v)} else if (name == '__image') {headMeta('property', 'og:image', headValue(&m, '__image', appHead != null ? appHead.image : null))} else if (name == '__favicon') {// AT ONCE, because apps swap the icon as an indicator: a new href on the// existing link is what the browser redraws the tab fromlet v = headValue(&m, '__favicon', appHead != null ? appHead.favicon : null)if (v != null) {let el = document.querySelector('link[rel="icon"]')if (el == null) {el = document.createElement('link')el.setAttribute('rel', 'icon')document.head.appendChild(el)}el.setAttribute('href', v)}} else if (name == '__meta') {// A GROUP, not a value: the page's list replaces the page's tags and leaves the// app's manifest tags alone. The server marks the ones it wrote for the page// with `data-hl-page-meta` and this writes the mark too, so the two halves// address the same set.let old = document.querySelectorAll('meta[data-hl-page-meta]')let i = 0while (i < old.length) { old.item(i).remove() i = i + 1 }let list = m.instance['__meta']if (list != null) {for (h of list) {let el = document.createElement('meta')for (k of h.keys()) { el.setAttribute(k, '' + h[k]) }el.setAttribute('data-hl-page-meta', '')document.head.appendChild(el)}}}return null}// one meta tag's content. The tag the first document carried is reused; a value// this document has no tag for yet gets one appended.headMeta(attr, name, content) {if (content == null) { return null }let el = document.querySelector('meta[' + attr + '="' + name + '"]')if (el == null) {el = document.createElement('meta')el.setAttribute(attr, name)document.head.appendChild(el)}el.setAttribute('content', content)return null}
Branches
- mainmain branch
Latest commits
- 4a2d7125initial commitmre