jukebox
All repositories: gitoria
232.5 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 HlwView from './view.hl'import HlwRouter from './router.hl'seedText = '' // the server's seed, as JSON text (the one construction argument)seed = null // { page: { key params state view }, shell: … | null }view = new HlwViewrouter = null // the client's route table, from the seedplainRoutes = {} // the paths of the routes that are not pages and have no :param or * (a click on them is left to the browser)shell = 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 component// WHERE IN IT (ticket #81's finding): the shell's slot may stand beside other elements// of the shell — `body { header { … } slot }` — and the page's nodes are then not all// of slotEl's children. `slotAt` is the index of the page's first element among them,// and `slotStart` the open mark of the region the page is (a page in a shell stands// between two marks like every region), so the page is claimed from the right element// and a navigation replaces what stands between the marks and nothing of the shell's.slotAt = 0rowKidBound = {} // component key | for site → the host members its row children are bound toreseatGen = 0 // (#71) the number of the running reseat: a node a nested changed row shares with its outer one is read oncekidMoved = false // (#200) a row's composed child took a new bound value in this paint's rebinding: reseatRows rebuilds the row's `if`s that hold a childrowKidless = {} // component key | for site → true when its row body composes no childslotStart = null// THE PAGES LEFT BY A NAVIGATION, KEPT FOR BACK AND FORWARD (W147, D5 on hybriel#206). A page replaced by another under// the same chain of levels is not thrown away: its DOM nodes (detached), its mount record and its index entries wait here,// keyed by the history entry it belonged to (`hid`, written into history.state). Back or forward to such an entry puts the// page back with its state and scroll; any other entry is a miss and builds the page as before. `keptMax` is five: a page// holds its whole DOM and live instances, and five is the few pages one walks back through, without a long session// growing without end; the oldest one left goes first.kept = []keptMax = 5hidNext = 1shownHid = null // the history entry the page on the screen belongs toshownPath = nullscrollNow = 0regionTable = {} // NAMED REGIONS (`slot { name = 'side' … }`) the shell's levels hold: name → { host start at desc kind }detachedSlot = null // the slot element a shell region's rebuild took out of the DOM (see paint)socket = null // the websocket carrier, while it is opensocketOpened = false // it has opened (a socket that closes without opening is a failed reconnect)retryMs = 500 // the wait before the next reconnect: doubles per failure up to 4 s, reset on openhasSession = true // the server said at the last hello whether this tab has a session (W136, sessionKnown)sessionChannel = null // the BroadcastChannel to the other tabs of this app in this browsersessionCookieName = null // the app's session cookie name and Domain, as the server said at the hellosessionCookieDomain = nullnewsWaiting = false // news of a login came while the socket was still connectingcookieWatch = null // the cookieStore listener for a login in a tab of another origin of the same site is boundprobing = false // the probe of `/__hl/up` runs while a reconnect waits (ticket #153, probe())probeFailed = false // a probe found no server since the last socket openedreach = 'connecting' // WHETHER THE SERVER ANSWERS (setReach): 'connecting' until the first socket opens, then 'up' or 'down'replayingQ = null // the `q` of the queued entry whose frame is out and not acked (it cannot be taken back)// THE TAB ACROSS ITS SOCKETS (ticket #143): this document's id, the `n` of the last push it// dispatched, and whether a socket opened before — all three ride every `hello`, and the// server answers a reopened socket with what it missedtabId = nulllastSeq = 0appliedN = {} // W117: 'm<mount key>.<member>' → the highest sync `n` applied to it (a snapshot older than that is not laid over)gapHeld = {} // W117: 'n<n>' → a push above a gap, held until the replay fills itgapTimer = nullsyncN = null // the `n` of the numbered `sync` being applied (applySync reads it)everOpened = falsegotFrame = false // the current socket has been answered at least once (W123: the backoff resets here, not on open)shutStreak = 0 // sockets in a row the server shut right after the handshake, with no framewarnedOrigin = false // the cross-origin warning is logged oncenavigating = false // a navigation is running (show); navNext is the one asked for meanwhilenavNext = nullnavNextKeep = false // the navigation asked for meanwhile was a replace (goTo(path, true)): its page may staypinging = false // the ping interval is started once, with the first socketpongDue = null // the timer that takes the socket for dead when its pong is latesrvAt = null // the SERVER's clock as last heard (the hello's clock frame, a pong), in the server's own ms…srvMono = 0 // …and this page's monotonic clock at that moment: only DURATIONS ever cross (see `horizon`)nextId = 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 = []forwarding = 0 // upward() is dispatching at the levels above a sender: their own listeners stay silentlevelMarks = [] // per level depth: the open mark of the region its slot holds (the next parent level, or the page); a navigation replaces what stands between a level's markslateInner = null // the parent levels an arriving page brought below the shell (arrive), taken by the slot that openeddelivering = 0 // outward() is dispatching a frame at the mounts: a page's forwarder (wireUp) stays silent thenstrict = false // the gates' client: a repaint that finds a stale site throws (staleSite)paintSet = null // the members the running repaintAll moved (a `for` over a row with a child steps over unchanged rows only if all are its own)painting = 0 // repaints running: 0 when the page stands still (the gates wait for it)turning = false // a patch is running (patch): the ones asked for meanwhile wait in patchQueuepatchQueue = []placing = 0 // pages being placed (showOne): no patch runs meanwhile; counted, so two overlapping ones and a turn that ends meanwhile cannot leave the queue stoppedsidNext = 0 // every site's own number, so a repaint can tell one that has leftdropGen = 0 // counts the drops of sites (dropSitesIn): a repaint's list is checked again after onependingDrops = [] // ranges that left holding a host's fill: that host's sites and children in them// go in settle(), once every mount on the walk has been written backpendingFills = [] // fills a region rebuild anchored but could not build in place:// the host is named by address and re-entered in settle() below// ownerId -> { key, chain, root } of the mount that owns that instance, and the reverse// (address -> ownerId, the check that an entry still names a live mount). A MOUNT RECORD// IS A VALUE, so finding a mount by walking the tree with `let kid = m.kids[k]` deep-copies// every subtree on every handler event; the index is filled where a mount is made// (`instantiateNode`, `mintFrom`) and emptied where one is replaced or removed// (`purgeMounts`), so a lookup is O(1) at any depth.mountIndex = {}mountAddr = {}lateJobs = [] // late patches (#98, #99): see latePatchlateDue = falsedomListener = null // the DOM listener just dispatched {event, chain, root, wrote}: see handlerWaiting (W185)// 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 there IS no page: the server did not construct it and the seed carries none// (creator, 2026-08-26 — the parent is the gate). It is asked for and constructed when// the region holding the slot turns true, and dropped again when it turns false.pageShown = falsedropped = null // the page of a region that closed (snapLeft's record): put back when the region opens again, never asked forrestored = falsepageArrived = false // a region's rebuild constructed the page: its held frames go out after it// THE OFFLINE LAYER (COMPONENTS §10), live only when the seed says the app keeps pages// offline. `store` is the IndexedDB database, opened at boot; `unacked` holds what a// queueable emit sent on the socket carried until its ack, so a socket that closes// under it queues the emit instead of losing it; `flushing` is true while the queue// is replayed; `retryTimer` is the reconnect that is waiting.store = nullunacked = {}replays = {} // 'k<i>' → what ends a replayed entry's wait when its socket closes// AN EMIT IN FLIGHT OUTLIVES ITS SOCKET (ticket #107). Every emit that went out on the// socket is here until its ack, as the frame it was: a socket that closes under it// hands it on to the POST fallback or the next socket, with the same `q`, and the// server's exactly-once path answers the repeat instead of running the face again.// `post` is true while the POST fallback carries it, `lost` once a POST failed.inflight = {} // 'k<i>' → { text; event; post; lost; }// A PAGE BEING LEFT starts nothing. Firefox closes the page's socket the moment a// document navigation starts, right after `beforeunload` and long before `pagehide`;// a reconnect or a POST made then, and an answer that loads a document, would cancel// the navigation the user started. `beforeunload` is only a maybe (a download, a// navigation the server answers with 204), so after it the page takes itself for// staying once `stayMs` have passed and it is still here.leaving = falsestayTimer = nullstatic stayMs = 3000flushing = falseretryTimer = nullowner = '' // whose the kept copy is (settleWho): the last user logged inonlineBound = false // the online/offline listeners are on the window (syncOnline)holding = false // an anonymous page over a user's copy: nothing is kept or laid over itheldBack = false // the server said a queued entry is for another user than the session'sflushAgain = false // an entry was queued while a round ran: the round goes over the queue once morequeueRetryTimer = null // a round that did not fully drain tries again after queueRetryWait// ---- 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, replace = false) => { return live.client.goTo(path, replace) }// A NOTIFICATION, now or at a set time (COMPONENTS §10, ticket #95). `at` is epoch// milliseconds. The browser is asked for permission the first time. It is shown by// the service worker when the app has one (so an installed app shows it as the app),// else by the page. A notification AT A SET TIME is a timer of this page: it fires// while the page is open — a browser offers no way to wake a closed app at a time// without a server push, and this does not pretend otherwise.static notify = (title, options) => { return live.client.showNotice(title, options) }static notifyAt = (at, title, options) => { return live.client.noticeAt(at, title, options) }// …or after `ms` millisecondsstatic notifyIn = (ms, title, options) => { return live.client.noticeIn(ms, title, options) }// FORGET WHAT THIS BROWSER KEPT OFFLINE (ticket #125): the kept state, the queue and the// worker's kept documents. hl:web does it itself when the session's user changes (a log-out// included) at the next page it is told about; an app that logs out in place calls this.// WEB PUSH (ticket #173): ask for permission, subscribe with the app's `pushKey`, and answer the// subscription as `{ endpoint, expirationTime, keys = { p256dh, auth } }` — or null when the browser// has no push, the key is not set or permission is refused. The app hands it on:// `let s = subscribePush() emit server savePush(s)`.static subscribePush = () => { return live.client.pushSubscribe() }// …and the server's half (hl:web's server.hl): a component that imports `sendPush` from 'hl:web' binds this// name in the browser, so the module loads; the call belongs in an `on server` handler, and here it only says so.static sendPush = (subscription, payload, opts) => { console.error('hl:web: sendPush sends from the server — call it in an `on server` handler or a route function') return null }static forgetOffline = () => { return live.client.forgetOffline() }// TAKE BACK A QUEUED EMIT (W215): `import { takeBack } from 'hl:web'`, `took = takeBack(r.q)` with the `q` of a `__hlQueue` row.// true: it was still waiting, is never sent, and its caller got null. false: unknown, taken back before, or already sent.static takeBack = (q) => { return live.client.takeBack(q) }// ---- 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 = this// A VIEW EXPRESSION in a module's code is evaluated by view.hl's one `evalExpr`, so the// language's own operators answer in the browser as they do on the serverwindow.__hlX = (x, inst, rows) => { return view.evalExpr(&x, &inst, &rows) }seed = resolveValues(JSON.parse(seedText))router = new HlwRouter(routes = seed.routes)for (r of seed.routes) {if (r.component != true && r.pattern.indexOf(':') < 0 && r.pattern.indexOf('*') < 0) { plainRoutes[r.pattern] = true }}boot()// THE VALUES TABLE (#180): the server writes a large value that stands in several places once,// in `seed.values[id]`, and a place holds `{ "$hlv": id }`. Every reference is resolved HERE,// as the seed is read (a navigation's answer too, in showOne) and each place gets a copy of its// own, built fresh: a child that changes its `items` does not change the page's `home`.resolveValues(&s) {if (s == null || s.values == null) { return s }// (the table is read in place and the answer is the caller's own temporary: `let table = s.values` copied the whole table, W110)if (s.page != null) { s.page = unshare(&s.values, &s.page) }if (s.shell != null) { s.shell = unshare(&s.values, &s.shell) }s.values = nullreturn s}unshare(&table, &v) {if (hlTypeName(&v) != 'Hybrid') { return v }if (v['$hlv'] != null) { return unshare(&table, &table[v['$hlv']]) }let out = nullif (Array.isArray(&v)) {out = []for (x of v) { out.push(unshare(&table, &x)) }} else {out = {}for (k of v.keys()) { out[k] = unshare(&table, &v[k]) }}return out}boot() {mounting = truestrict = seed.strict == trueif (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 = seed.page != null ? instantiate(seed.page, [], 'page') : null// 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 && page != null) {slotEl.__hlCur = slotStartclaim(&page, slotEl, slotAt)pageShown = true}// the shell's named regions take their content: the filling level's, or their own defaultif (shell != null) { placeRegions(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.headif (page != null) { headSites(&page) }release()listen()syncOnline()syncReach()if (seed.offline != null) { standIn() }if (seed.offline != null) { offlineBoot() }connect()}// A DOCUMENT THAT STANDS IN FOR THIS URL (#124): the worker answered an unvisited param page// with a kept document of the same component, so the seed's parameters are another url's.// This url's are the truth: they go into the instance, and what they feed is derived again// here (what only the server can derive stays as that document had it, until a push).standIn() {if (page == null || seed.page == null) { return null }let m = router.match(location.pathname)if (m == null || m.route.component != true) { return null }let mine = JSON.stringify(m.params)if (mine == JSON.stringify(seed.page.params)) { return null }for (k of m.params.keys()) { page.instance[k] = m.params[k] }seed.page.params = m.paramspatch(page.chain, 'page', moved(&page, m.params.keys()), [])return null}// THE NEXT PAGE INTO THE SLOT, and nothing else of the shell's: the slot's element may// hold the shell's own elements beside the page (`body { header { … } slot }`), which// emptying it took with the old page. The new page is built where the old one stood.placePage(&m) {if (!standing(slotEl, slotStart)) {// the page is all the slot's element holds: empty it, as it always wasslotEl.replaceChildren()create(&m, slotEl)return null}// the page's own nodes go; the readable form's line breaks the server wrote between the marks// (whitespace text no site, leaf or walk owns) stay, so a swap touches nothing else of the containerfor (n of between(slotStart)) { if (!formatting(n)) { n.remove() } }let frag = document.createDocumentFragment()let before = sidNextcreate(&m, frag)slotEl.insertBefore(frag, slotStart.__hlEnd)// the sites the walk registered on the fragment (a region at the page's root, a composed// child's) belong to the slot's element it landed in (#191: they stayed on the empty fragment,// and the first click on a child's button after a navigation did nothing)rehome(&m, frag, slotEl, before)return null}// a whitespace-only text node nothing of the page owns: no site, and not a leaf the host keepsformatting(n) {if (n.nodeType != 3 || n.data.trim() != '' || n.__hlSid != null) { return false }if (n.parentNode.__hlLeaves != null) {for (k of n.parentNode.__hlLeaves.keys()) { if (n.parentNode.__hlLeaves[k] == n) { return false } }}return true}// 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.// A COMPONENT'S BLUEPRINT (its View tree, whether it takes the route, the members the server computes) COMES WITH ITS// MODULE (W195): the module registers it under `__hlB[key]` when it runs, so a page carries the plans of the// components it uses and no others, and the browser's cache keeps them. A mount has its module loaded before its tree is// read; a child the browser mints itself has its module fetched first (`planOf`).blueprintOf(key) {if (window.__hlB == null) { return null }return window.__hlB[key]}// the url a component's module is served at (the server's `moduleUrl`)moduleUrlOf(key) {return '/' + key + seed.build}// the blueprint of a component whose module may not be loaded yet: the module is imported (once, the browser's module map)planOf(key) {if (blueprintOf(key) == null) { window.__hlP.L(moduleUrlOf(key)) }return blueprintOf(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 module 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) {purgeMounts(chain, root)return instantiateNode(m, chain, root)}// a mount made at (chain, root) replaces whatever was there: forget it and everything under itpurgeMounts(chain, root) {let base = addressOf(chain, root)let sep = chain.length == 0 ? '' : '/'let gone = []for (a of mountAddr.keys()) {if (a == base || a.startsWith(base + sep)) { gone.push(a) }}for (a of gone) {delete mountIndex['' + mountAddr[a]]delete mountAddr[a]}return null}// the same for many addresses in ONE scan of the index (`keys()` sorts the names: a purge per dropped child sorted// them per child, ~145 ms at 800 rows): an address goes when it is one of the bases or stands under onepurgeMany(chains, root) {if (chains.length == 0) { return null }let bases = {}for (c of chains) { bases[addressOf(c, root)] = true }let gone = []for (a of mountAddr.keys()) {let hit = bases[a] == truelet at = a.indexOf('/')while (!hit && at >= 0) {if (bases[a.slice(0, at)] == true) { hit = true }at = a.indexOf('/', at + 1)}if (hit) { gone.push(a) }}for (a of gone) {delete mountIndex['' + mountAddr[a]]delete mountAddr[a]}return null}registerMount(inst, key, chain, root) {let addr = addressOf(chain, root)if (mountAddr[addr] != null) { purgeMounts(chain, root) }let id = inst.__hlOwnerIdif (id == null) { return null }mountIndex['' + id] = { key = key; chain = chain; root = root; }mountAddr[addr] = idif (root == 'page' && chain.length == 0) { wireUp(inst, key, levelCount() + 1) }if (root == 'shell' && chain.length > 0 && chain[chain.length - 1] == '^') { wireUp(inst, key, chain.length) }return null}// A PAGE'S EMIT REACHES ITS PARENT SHELL'S `on` (ticket #193). The levels stand in the// browser, so the page is its own instance and `emit shellSession(x)` in its View finds// no handler on it: the handler is the shell's. Every event the shell declares gets a// listener on the PAGE INSTANCE's own bus (the language's instance-scoped handler, the one// `on page.ev` registers, which every dispatch at that instance fires last) that hands the// emit to the shell's instance through the dispatch `outward` uses (`hlEmitArgs`) and// repaints what the shell's handler wrote. Server cost: none, nothing leaves the browser.wireUp(inst, key, depth) {if (seed.shell == null || window.__hlC == null) { return null }if (window.__hlC[key] == null || window.__hlC[key].on == null) { return null }// every event any level above this mount declares (a level's table is its own compiled `ev`)let seen = {}let at = seed.shelllet i = 0while (at != null && i < depth) {let tbl = window.__hlC[at.key]if (tbl != null && tbl.ev != null) {for (ev of tbl.ev.keys()) {if (seen[ev] == null) { seen[ev] = true wireEvent(&inst, key, ev, depth) }}}at = at.kids['^']i = i + 1}return null}// how many parent levels stand above the page: the shell and every '^' kid below itlevelCount() {let n = 0let at = shellwhile (at != null) { n = n + 1 at = at.kids['^'] }return n}wireEvent(&inst, key, ev, depth) {window.__hlC[key].on(&inst, ev, (a, b, c, d, e) => { return upward(ev, [a, b, c, d, e], depth) })return null}// The emit goes to the `depth` levels above its sender, nearest first, each level's handlers// once. `forwarding` keeps the dispatch AT a level (the levels' own listeners) silent.upward(ev, args, depth) {// a frame the server pushed reaches the shell on its own (outward), not through the pageif (shell == null || delivering > 0 || forwarding > 0) { return null }let payload = argswhile (payload.length > 0 && payload[payload.length - 1] == null) { payload = payload.slice(0, payload.length - 1) }let lv = []let at = shellwhile (at != null && lv.length < depth) { lv.push(at) at = at.kids['^'] }forwarding = forwarding + 1let j = lv.length - 1while (j >= 0) {let m = lv[j]let tbl = window.__hlC[m.key]if (tbl != null && tbl.ev != null && tbl.ev[ev] != null) {let inst = m.instancehlEmitArgs(&inst, ev, payload)patch(m.chain, m.rootKind, eventWrites(m.key, ev), [])}j = j - 1}forwarding = forwarding - 1return null}// `host` is the instance whose View placed this component: the live host instance, handed to the// loader as the builder, which is what `$parent` reads in the component (hybriel#63). A root (the// shell, a page) has none.instantiateNode(m, chain, root, host) {let args = {}// a member the seed left out (`m.skipped`) is the server's: given as null so the browser never runs its initializer// (it may call a package with no client code, `readFile`); the first value that arrives replaces itif (m.skipped != null) { for (k of m.skipped) { args[k] = null } }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(moduleUrlOf(m.key), args, host)// 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 = chain.length > 0 && chain[chain.length - 1] == '^'; kids = {}; bindings = []; chain = chain; rootKind = root; skipped = m.skipped; }registerMount(inst, m.key, chain, 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] = instantiateNode(m.kids[k], childChain(chain, k), root, inst) }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) {if (out.kids[b.kid] != null) {out.kids[b.kid].instance[b.target] = bindingValue(b, &out)}}return out}bindKids(&m, nodes) {for (n of nodes) {if (n.k == 'component') {// THE EDGE STANDS WHETHER OR NOT THE SERVER MOUNTED THE CHILD: a branch that does// not stand is not mounted, and the browser builds the child when it comes to// stand — which must then follow the host's member (every reader of `m.bindings`// passes over an edge whose child is not there){// 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}// ---- 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 names = compiledEntry(key, 'ev', event)return names == null ? [] : names}memberWrites(key, name) {let names = compiledEntry(key, 'mw', name)return names == null ? [] : names}derivationsOf(key) {if (window.__hlC == null || window.__hlC[key] == null) { return [] }return window.__hlC[key].dv}// one entry of one table of a compiled component, read in place: `compiledOf` hands a// copy of the whole compiled half, which a push to every mount cannot afford (#138)compiledEntry(key, table, name) {if (window.__hlC == null || window.__hlC[key] == null || window.__hlC[key][table] == null) { return null }return window.__hlC[key][table][name]}// ---- 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]}// one paint entry of a compiled component, read in place (compiledOf hands a copy of// the whole table, which a row repaint cannot afford per element)paintEntry(key, site) {if (window.__hlC == null || window.__hlC[key] == null) { return null }return window.__hlC[key].p[site]}// the walk of a component's whole View, of one `for` body, of an `if` branch, or of// the fragment a reference fills — each under its own sitewalkOf(key, slot, site) {// each slot is read in place off the global table (the `paintEntry` way): `compiledOf`// would copy the whole compiled component for every `if` site and every `for` rowif (window.__hlC == null || window.__hlC[key] == null) { return null }if (slot == 'v') { return window.__hlC[key].v }if (slot == 'b') { return window.__hlC[key].b[site] }if (slot == 't') { return window.__hlC[key].t[site] }if (slot == 'e') { return window.__hlC[key].e[site] }if (slot == 'f') { return window.__hlC[key].f[site] }if (slot == 'd') { return window.__hlC[key].d[site] }if (slot == 'r') { return window.__hlC[key].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 }return f(&this, &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) { let sid = nextSid() m.sites.push({ sid = sid; el = el; site = site; names = keep; region = false; rows = rows; }) if (el.__hlSid == null) { el.__hlSid = sid } else { el.__hlSidMore = (el.__hlSidMore == null ? '' : el.__hlSidMore) + sid + ',' } }return null}// (#71) a site's node carries the site's number (`__hlSid`, the first, and `__hlSidMore`, set inline where the site registers: a call with the node// as argument is a copy per site), so a reseat finds the sites of the rows it touches from their nodes. A region is tagged// on its open mark, the node the reseat walk starts from.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) => {// THE DEFAULT ACTION OF `submit` IS A PAGE NAVIGATION (COMPONENTS.md §6b), so the// framework suppresses it itself — a handler declared with no parameter has no// `ev` to call `preventDefault()` on, and one declared with it may call it again,// harmlessly. This is the FIRST statement, unawaited, for the same reason `onClick`// claims a link before anything else: called after an `await`, it lands a// microtask late, once the browser already navigated (mission 132 / ticket submit).if (event == 'submit') { ev.preventDefault() }let lit = el.__hlLits[event]for (rk of rowNames) { lit[rk] = el.__hlRows[rk] }// a plain write, not a call: a call is awaited and the handler must run inside the dispatch (#620)domListener = { event = event; chain = at; root = root; wrote = wrote; }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, i, cr) {// A PARENT LEVEL BELOW THE SHELL (#194): this level's slot holds the next parent level,// kid '^' (the page stands in the innermost level's slot). It leaves no mark of its own.let inner = m.kids['^']// A SLOT THAT OPENS LATER (#194): the levels below this one were never built (the shell's// slot stood closed when the document was made). The answer for the route brings the// page AND every level between, so the level below this one is built from it nowif (inner == null && cr && !pageShown && page == null) {page = arrive()if (lateInner != null) {m.kids['^'] = instantiate(lateInner, childChain(m.chain, '^'), m.rootKind)if (m.chain.length == 0 && seed.shell != null) { seed.shell.kids['^'] = lateInner }lateInner = nullinner = m.kids['^']}}if (inner != null) {// THE REGION OF THE LEVEL BELOW (mission 343): the server writes the same two marks around a parent level as around// the page, so a navigation that changes only the levels from here down can replace what stands between themlet rs = markAt(&host, cr, true)levelMarks[m.chain.length] = rsinner.chain = childChain(m.chain, '^')inner.rootKind = m.rootKindif (cr) { inner.sites = [] }let f = walkOf(inner.key, 'v', null)let out = run(f, &inner, &m, &host, cr ? 0 : i, {}, '', null, cr, null)if (!cr) { i = out }if (cr || inner.bindings.length == 0) { inner.bindings = [] bindKids(&inner, inner.view) }m.kids['^'] = innerif (cr) { rs.__hlEnd = markAt(&host, true, false) }else {rs.__hlEnd = closeOf(rs)host.__hlCur = rs.__hlEnd}return i}slotEl = hostif (!cr) {// claiming: the page's elements stand here, and the shell's own elements after// the slot come after themslotAt = iif (seed.page == null) { return i }// the page's region: its marks, and the elements between them the shell steps overslotStart = markAt(&host, false, true)levelMarks[m.chain.length] = slotStartslotStart.__hlEnd = closeOf(slotStart)host.__hlCur = slotStart.__hlEndlet span = 0for (n of between(slotStart)) { if (n.nodeType == 1) { span = span + 1 } }return i + span}slotAt = host.children.lengthlet start = markAt(&host, true, true)if (detachedSlot != null && detachedSlot != host) {// the page's own nodes: what stood between its marks, or all of the old host'slet moving = standing(detachedSlot, slotStart) ? between(slotStart) : Array.from(detachedSlot.childNodes)for (node of moving) { host.appendChild(node) }}detachedSlot = nullif (!pageShown) {// THE PAGE ARRIVES WITH ITS SLOT: it was never constructed while the shell// placed none, so it is asked for now — the route's state, from the serverif (page == null) { page = arrive() }if (page != null && restored) {// THE PAGE THE CLOSED REGION HELD comes back with its DOM and instances, no server round trip (W161)restored = falsefor (n of dropped.nodes) { host.appendChild(n) }for (a of dropped.addrs.keys()) { mountAddr[a] = dropped.addrs[a] }for (i of dropped.ids.keys()) { mountIndex[i] = dropped.ids[i] }let back = droppeddropped = nullwearHead(&page)pageShown = trueplaceRegions(false)pageArrived = truerepaintAway(back)} else if (page != null) {page.sites = []create(&page, host)headSites(&page)wearHead(&page)pageShown = trueplaceRegions(false)}}start.__hlEnd = markAt(&host, true, false)slotStart = startlevelMarks[m.chain.length] = startreturn i}// THE ROUTE'S PAGE, for a slot that just opened: the navigation face answers it for// this path, told the slot stands here, and the mount is constructed from that. The// frames it raises wait until the rebuild that placed it is done (pageArrived).arrive() {// the page this slot held when it closed, if it is the route's still and stands under the same levelsif (dropped != null && dropped.path == location.pathname + location.search && dropped.keys == JSON.stringify(chainKeys(seed.shell)) && dropped.params == chainParams() && dropped.who == whoNow()) {restored = trueseed.page = JSON.parse(dropped.seedPage)return dropped.page}dropped = null// the answer carries the values table (#180) like a navigation's: resolved before anything reads itlet next = resolveValues(emit server page(location.pathname + location.search, true, [], []))if (next == null || next.page == null) { return null }seed.page = next.pagelateInner = next.shell != null ? next.shell.kids['^'] : nullmounting = truepageArrived = truereturn instantiate(next.page, [], 'page')}// THE SLOT CLOSED: the page is dropped, not kept aside — the next time the slot opens// it is constructed again. The head falls back to the app's own.dropPage(&m) {// THE LEVELS BELOW THE CLOSED SLOT GO WITH THE PAGE (#194): the level this slot belonged to held// the next parent level as kid '^' — its sites, listeners and record are dropped, not left stale;// the slot's next opening builds them again (lateInner)let hadInner = m.kids['^'] != nullif (hadInner) {purgeMounts(childChain(m.chain, '^'), m.rootKind)delete m.kids['^']if (m.chain.length == 0 && seed.shell != null && seed.shell.kids != null) { delete seed.shell.kids['^'] }}// (kept for the slot's next opening when no parent level hangs below it)dropped = page != null && slotStart != null && !hadInner && shownPath != null ? snapLeft() : nullslotEl = nullpageShown = falsepage = nullpurgeMounts([], 'page')slotStart = nullseed.page = nulllet none = { instance = {}; }wearHead(&none)announceMounts()return null}// a rebuild that constructed the page: what waited for it goes out, and the server// learns the tab mounts itarrived() {if (!pageArrived) { return null }pageArrived = falserelease()announceMounts()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)}// ---- NAMED REGIONS (D-CHAIN addendum) -------------------------------------------------// A level above declares `slot { name = 'side' … }`: a region between two marks, holding its// default (built in the declaring level's frame, walk 'd') or the fill a lower level wrote at its// View root (`side { … }`, built in THAT level's frame, walk 'r'). The region element stands; a// navigation rebuilds only what stands between the marks.namedRegionAt(&m, &o, host, i, site, name, rows, rk, fill, cr) {let desc = { key = m.key; site = site; rows = rows; rowKey = rk; outer = fill; chain = m.chain; rootKind = m.rootKind; slot = 'd'; }if (!cr) {// claiming: the region's marks are taken and its content is claimed once the page is (boot)let start = markAt(&host, false, true)start.__hlEnd = closeOf(start)host.__hlCur = start.__hlEndlet span = 0for (n of between(start)) { if (n.nodeType == 1) { span = span + 1 } }regionTable[name] = { host = host; start = start; at = i; base = desc; desc = desc; kind = null; }return i + span}let start = markAt(&host, true, true)start.__hlEnd = mark(false)host.appendChild(start.__hlEnd)let fd = fillerOf(name)// (a hybrid read off a table is a copy: the entry is written whole, never through a read of it)regionTable[name] = { host = host; start = start; at = 0; base = desc; desc = fd == null ? desc : fd; kind = fd == null ? 'd' : 'r'; }if (fd != null) {fillFromRoot(fd, host, 0, true)} else {run(walkOf(m.key, 'd', site), &m, &o, &host, 0, &rows, rk, &fill, true, null)}// built in place before the close mark (the walk appended after it)host.appendChild(start.__hlEnd)return i}// the level below the declaring one that fills region `name`: the page first, then the levels// from the innermost out. A descriptor naming the filler's frame, or null (the default stands).fillerOf(name) {let cands = []if (page != null) { cands.push(page) }let lv = []let x = shellwhile (x != null && lv.length < 64) { lv.push(x) x = x.kids == null ? null : x.kids['^'] }let k = lv.length - 1while (k > 0) { cands.push(lv[k]) k = k - 1 }for (c of cands) {let site = regionFillSite(c.key, name)// a conditional fill holds while its condition does (read off the filling instance)if (site != null && window.__hlC[c.key].rc != null && window.__hlC[c.key].rc[name] != null) {let cf = window.__hlC[c.key].rc[name]let nr = {}if (!cf(&c.instance, &nr)) { site = null }}if (site != null) { return { key = c.key; site = site; rows = {}; rowKey = ''; outer = null; chain = c.chain; rootKind = c.rootKind; slot = 'r'; } }}return null}regionFillSite(key, name) {if (window.__hlC == null || window.__hlC[key] == null || window.__hlC[key].rn == null) { return null }return window.__hlC[key].rn[name]}// every named region takes what its level or the filler below it holds: after a page is claimed// (boot, `claim` true: the server's nodes are taken) or placed (navigation: rebuilt)placeRegions(claimIt) {if (!claimIt) {for (name of regionTable.keys()) { placeRegion(name, false) }return null}// claiming a region's default may claim regions inside it (their marks are taken on the way and// their content waits): pass again until every one that stands has its contentlet pass = 0let pending = truewhile (pending && pass < 16) {pending = falsepass = pass + 1for (name of regionTable.keys()) {let r = regionTable[name]if (r.kind == null && standing(r.host, r.start)) { pending = true placeRegion(name, true) }}}return null}placeRegion(name, claimIt) {let r = regionTable[name]if (r == null || !standing(r.host, r.start)) { return null }let fd = fillerOf(name)let want = fd == null ? 'd' : 'r'if (claimIt) {let d = fd == null ? r.base : fdregionTable[name].kind = wantregionTable[name].desc = dr.host.__hlCur = r.startregionClaim(d, r.host, r.at)return null}// the default stands and stays the default: its state and its nodes are not rebuiltif (want == 'd' && r.kind == 'd') { return null }let old = between(r.start)let owner = r.descif (owner.rootKind == 'shell' || owner.slot == 'd') { regionDrop(owner, r.host, old) }for (n of old) { n.remove() }let d = fd == null ? r.base : fdregionTable[name].desc = dregionTable[name].kind = wantregionBuild(d, r.host, r.start.__hlEnd)return null}// claims the server's nodes of a region's content, in the frame its descriptor namesregionClaim(d, host, at) {fillFromRoot(d, host, at, false)return null}// builds a region's content in a fragment and puts it before the close mark; the sites the walk// registered on the fragment belong to the region's host (as `placePage` does)regionBuild(d, host, closeMark) {let frag = document.createDocumentFragment()let before = sidNextfillFromRoot(d, frag, 0, true)host.insertBefore(frag, closeMark)regionRehome(d, frag, host, before)return null}regionRehome(d, frag, host, before) {if (d.rootKind == 'shell') { if (shell != null) { regionRehomeAt(&shell, d, 0, frag, host, before) } }else if (page != null) { regionRehomeAt(&page, d, 0, frag, host, before) }return null}regionRehomeAt(&m, d, depth, frag, host, before) {if (depth >= d.chain.length) { rehome(&m, frag, host, before) return null }if (m.kids[d.chain[depth]] == null) { return null }regionRehomeAt(&m.kids[d.chain[depth]], d, depth + 1, frag, host, before)return null}// the sites of the nodes that leave belong to the frame that built themregionDrop(d, host, nodes) {if (d.rootKind == 'shell') { if (shell != null) { regionDropAt(&shell, d, 0, host, nodes) } }else if (page != null) { regionDropAt(&page, d, 0, host, nodes) }return null}regionDropAt(&m, d, depth, host, nodes) {if (depth >= d.chain.length) { dropSitesIn(&m, host, nodes) return null }if (m.kids[d.chain[depth]] == null) { return null }regionDropAt(&m.kids[d.chain[depth]], d, depth + 1, host, nodes)return null}// 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, fill.slot == null ? 'f' : fill.slot, fill.site)return run(f, &m, &m, &host, at, &fill.rows, fill.rowKey, &fill.outer, cr, null)}if (m.kids[fill.chain[depth]] == null) { return at }return fillInto(&m.kids[fill.chain[depth]], fill, depth + 1, host, at, cr)}// 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; }}// ---- THE MARKS: every region stands between two comments ---------------------------// THE INVARIANT (tickets #103, #104). Every region — an `if`, a `for`, each row of a// `for`, the shell's page — stands on its host between an OPEN mark (a comment `[`)// and a CLOSE mark (`]`), and ITS NODES ARE EXACTLY THE NODES BETWEEN THEM. A region// inside another one on the same host stands between the outer one's marks. So:// - a region's nodes are never remembered, they are read off the DOM between its// marks when they are needed — whatever a region inside it did since, they are// right (a list taken when the branch was built went stale, #103);// - a region is replaced by removing what stands between its marks and putting the// new nodes before its close mark; a row moves and leaves WITH its marks, so a row// is always whole and in its list;// - nothing outside a region is touched by it, and nothing inside it outlives it: the// sites registered in the nodes it drops are dropped with them, and a region whose// marks have left its host has nothing to paint.// The server writes the same marks (compile.hl `markOpen`), the claim walk takes them in// document order and the build walk makes them, so a region looks the same however it// came to stand — and text beside a region never runs into the region's own text.mark(open) { return document.createComment(open ? '[' : ']') }isMark(n) { return n != null && n.nodeType == 8 && (n.data == '[' || n.data == ']') }// the nodes strictly between a region's marksbetween(start) {let out = []let end = start.__hlEndlet n = start.nextSiblingwhile (n != null && n != end) { out.push(n) n = n.nextSibling }return out}// …and with the marks themselves: a row as it moves or leavesspanOf(start) {let out = [start]for (n of between(start)) { out.push(n) }out.push(start.__hlEnd)return out}// a region stands while both its marks are on its hoststanding(host, start) {return start != null && start.parentNode == host && start.__hlEnd != null && start.__hlEnd.parentNode == host}// A REGION'S MARK, made (building) or taken (claiming). The claim takes the next mark// after the host's cursor: the walk meets the regions in document order, so it is this// region's. A page whose marks do not match its tree is said so, and gets a mark where// the walk stands.markAt(&host, cr, open) {if (cr) {let made = mark(open)host.appendChild(&made)return made}let n = host.__hlCur == null ? host.firstChild : host.__hlCur.nextSiblingwhile (n != null && !isMark(&n)) { n = n.nextSibling }let mk = nullif (n != null && n.data == (open ? '[' : ']')) { mk = n }else {console.error('claim: no region mark under', host.tagName)mk = mark(open)host.insertBefore(mk, host.__hlCur == null ? host.firstChild : host.__hlCur.nextSibling)}host.__hlCur = mkreturn mk}// the close mark that pairs with an open one, past the regions inside itcloseOf(start) {let depth = 0let n = start.nextSiblingwhile (n != null) {if (isMark(n)) {if (n.data == '[') { depth = depth + 1 }else if (depth == 0) { return n }else { depth = depth - 1 }}n = n.nextSibling}let made = mark(false)start.parentNode.appendChild(made)return made}// THE SITES IN NODES THAT LEAVE go with them: an element's, a text leaf's, and a// region's whose open mark is among them. Marked and walked up once per site.//// NO CALL BETWEEN READING THE LIST AND WRITING IT BACK. Every call in this language is// awaited, and an await lets another repaint run — one that registers sites of its// own, which a list read before it and written after it would lose. The loops that// read `m.sites` and write it back hold property reads, index writes and `[] =` only.dropSitesIn(&m, host, nodes) {if (nodes.length == 0) { return null }// MARK THE LEAVING NODES AND EVERY NODE UNDER THEM once (a tree walk), then READ EACH SITE BY INDEX and remove the// gone ones in place: `for (site of m.sites)` / `kept[] = site` / `m.sites = kept` copied every site and the// whole list per drop, and `n = n.parentNode` copied a node per step: hlCopyFast ~205 ms for one fold of 60// rows (w77)for (n of nodes) {n.__hlGone = trueif (n.nodeType == 1) {let w = document.createTreeWalker(n, 4294967295)let c = w.nextNode()while (c != null) { c.__hlGone = true c = w.nextNode() }}}let k = m.sites.length - 1let dropped = 0while (k >= 0) {if (m.sites[k].region && m.sites[k].el == host && m.sites[k].start != null) {if (m.sites[k].start.__hlGone == true) { m.sites.splice(k, 1) dropped = dropped + 1 }} else if (m.sites[k].el != null && m.sites[k].el.__hlGone == true) { m.sites.splice(k, 1) dropped = dropped + 1 }k = k - 1}if (dropped > 0) { dropGen = dropGen + 1 }for (n of nodes) {n.__hlGone = nullif (n.nodeType == 1) {let w = document.createTreeWalker(n, 4294967295)let c = w.nextNode()while (c != null) { c.__hlGone = null c = w.nextNode() }}}return null}// THE SITES A WALK REGISTERED ON THE FRAGMENT IT BUILT INTO belong to the host it lands// in — this mount's, and those of the children composed straight onto the fragment,// whose own regions (a child's View may begin with an `if`) stand on the same host.// Those children are named by address on the fragment as the walk composes them// (kidAt, `__hlOnFrag`), so only they are re-entered.rehome(&m, src, dst, before) {sitesOnto(&m, src, dst, before)let due = src.__hlOnFrag == null ? [] : src.__hlOnFragsrc.__hlOnFrag = nulllet base = m.chain == null ? 0 : m.chain.lengthfor (chain of due) {if (chain.length > base) { rehomeAt(&m, chain, base, src, dst) }}return null}// (`after`: the sites numbered after it are the walk's — an index would move when// another repaint drops sites in the meantime)sitesOnto(&m, src, dst, after) {// sids only grow along m.sites, so the walk's sites are its tail: read it from the end// and stop at the first older one (a scan of every site per row built was O(rows x sites))let k = m.sites.length - 1while (k >= 0 && m.sites[k].sid > after) {if (m.sites[k].el == src) { m.sites[k].el = dst }k = k - 1}return null}rehomeAt(&m, chain, depth, src, dst) {if (depth >= chain.length) { sitesOnto(&m, src, dst, 0) return null }if (m.kids[chain[depth]] == null) { return null }rehomeAt(&m.kids[chain[depth]], chain, depth + 1, src, dst)return null}// A RANGE LEAVES THE PAGE — a branch, a row: every site registered in it goes (at any// depth: an element's, a text's, a region's whose marks are in it), and so does every// child composed in it (its nodes carry its address), with its own sites, its children// and its handlers.// A range can hold a FILL — a host's fragment placed at this component's `slot` — whose// sites and children are the host's: `fill` names that host (and the one it was filled// by in turn), and those go in settle(), where a host is re-entered by its address after// every mount on this walk has been written back.dropRange(&m, host, nodes, fill) {dropSitesIn(&m, host, nodes)let others = disposeIn(&m, nodes)let f = fillwhile (f != null) {pendingDrops.push({ chain = f.chain; rootKind = f.rootKind; host = host; nodes = nodes; kids = others; })others = []f = f.outer}return null}// THE CHILDREN COMPOSED IN NODES go: those of this mount at once, and the others (a// host's, composed in its fill) are answered for the caller to hand ondisposeIn(&m, nodes) {let chains = []for (n of nodes) { kidsFiledIn(n, &chains) }let base = m.chain == null ? [] : m.chainlet others = []let purged = []for (c of chains) {// (a range inside a child never takes the child itself, nor a mount above it: the// child's own nodes carry its address, a region of its own among them)let above = c.length <= base.length && JSON.stringify(base.slice(0, c.length)) == JSON.stringify(c)if (!above) {if (c.length > base.length && JSON.stringify(c.slice(0, base.length)) == JSON.stringify(base)) { if (disposeAt(&m, c, base.length)) { purged.push(c) } }else { others.push(c) }}}purgeMany(purged, m.rootKind)return others}// the ranges a fill's host still has to let go of (see dropRange)dropPending() {if (pendingDrops.length == 0) { return null }let due = pendingDrops.slice(0)pendingDrops = []for (d of due) {if (d.rootKind == 'shell') {if (shell != null) { dropAt(&shell, d, 0) }} else if (page != null) { dropAt(&page, d, 0) }}return null}dropAt(&m, d, depth) {if (depth >= d.chain.length) {dropSitesIn(&m, d.host, d.nodes)let purged = []for (c of d.kids) { if (c.length > depth) { if (disposeAt(&m, c, depth)) { purged.push(c) } } }purgeMany(purged, m.rootKind)return null}if (m.kids[d.chain[depth]] == null) { return null }dropAt(&m.kids[d.chain[depth]], d, depth + 1)return null}// a node in a range whose host's sites are still to go (dropPending)dropDue(n) {let top = n.getRootNode()for (d of pendingDrops) { if (d.nodes.includes(top)) { return true } }return false}// the children whose nodes are this node or stand under it (kidAt files them there)kidsFiledIn(n, &out) {if (n.__hlKidChains != null) { for (c of n.__hlKidChains) { out.push(c) } }if (n.nodeType != 1) { return null }let w = document.createTreeWalker(n, 4294967295)let c = w.nextNode()while (c != null) {if (c.__hlKidChains != null) { for (k of c.__hlKidChains) { out.push(k) } }c = w.nextNode()}return null}disposeAt(&m, chain, depth) {if (depth == chain.length - 1) {if (m.kids[chain[depth]] != null) {delete m.kids[chain[depth]]return true}return false}if (m.kids[chain[depth]] == null) { return false }return disposeAt(&m.kids[chain[depth]], chain, depth + 1)}// a node no longer on the page: not in the document, not in a fragment a walk is// still building, not in the slot a shell's rebuild holds asideplacedOff(n) {if (n.isConnected) { return false }if (n.getRootNode().nodeType == 11) { return false }if (detachedSlot != null && detachedSlot.contains(n)) { return false }return true}nextSid() {sidNext = sidNext + 1return sidNext}isLive(&m, s) {for (e of m.sites) { if (e.sid == s.sid) { return true } }return false}// A SITE WHOSE NODES LEFT THE PAGE, found by a repaint. Every range that leaves takes// its sites with it (dropRange), so this is a bug: the gates' client raises it as an// uncaught exception (the page's error event, what every gate fails on), a page in the// field says so on the console; neither paints it.staleSite(s) {let msg = 'hl:web: a repaint found a site whose nodes have left the page (site ' + s.site + ')'if (strict) { window.reportError(window.Reflect.construct(window.Error, [msg])) }else { console.error(msg) }return null}// A RUN OF TEXT LEAVES BESIDE ELEMENTS OR REGIONS (compile.hl `mixed`): one text node,// kept on the element under the run's index so a paint rewrites it and nothing else.// `k` null is a text the walk only has to step over (literal, or painted as a site of// its own by `textAt`). Built, it is appended. Claimed, it is the text node right// after the host's cursor — the last node the walk took there — which the server may// have run together with the readable form's line break after it, so it is split off// by the value it has now. A run that rendered empty has no node and gets one.leafAt(host, cr, i, k, text) {let t = leafNode(&host, cr, text)if (k != null) {if (host.__hlLeaves == null) { host.__hlLeaves = {} }host.__hlLeaves[k] = t}return null}leafNode(&host, cr, text) {let t = nullif (cr) {t = document.createTextNode(text)host.appendChild(&t)return t}let at = host.__hlCur == null ? host.firstChild : host.__hlCur.nextSiblingif (at != null && at.nodeType == 3 && text != '') {if (at.data == text) { t = at }else if (at.data.startsWith(text)) { at.splitText(text.length) t = at }else {// a line break of the readable form in front of it (a filled slot's line)let lead = at.data.length - at.data.trimStart().lengthif (lead > 0 && at.data.startsWith(View.newline) && at.data.slice(lead).startsWith(text)) {t = at.splitText(lead)if (t.data != text) { t.splitText(text.length) }}}}if (t == null) {t = document.createTextNode(text)host.insertBefore(t, at)}host.__hlCur = treturn t}// A TEXT LEAF STANDING IN A LIST (an `if` branch, a `for` body): its own text node, and// a site of the member it reads — or of the row it stands in — painted by rewriting it.textAt(&m, &host, cr, readFn, &names, &rows, rk) {let t = leafNode(&host, cr, readFn(&m.instance, &rows))if (names.length > 0 || (rk != null && rk != '')) {let sid = nextSid()m.sites.push({ sid = sid; el = t; site = null; names = names; region = false; text = true; rows = rows; rowKey = rk; read = readFn; })if (t.__hlSid == null) { t.__hlSid = sid } else { t.__hlSidMore = (t.__hlSidMore == null ? '' : t.__hlSidMore) + sid + ',' }}return null}paintText(&m, &s) {let f = s.readlet v = f(&m.instance, &s.rows)let t = s.elif (t.data != v) { t.data = v }return null}// ---- a `for`: the region, its rows, each between its marks -------------------------forAt(&m, &o, &host, i, site, rowName, listFn, &rows, rk, &fill, cr, &names) {let start = markAt(&host, cr, true)regionAt(&m, &host, site, &rows, rk, &fill, true, rowName, listFn, &names, &start, null)// (the box lives on the open mark from the start and every row is written through it in place: `let box = ...` / `start.__hlBox = box`// each copied the box with every row's entry and snapshot, W110)start.__hlBox = { keys = []; rows = {}; }let entries = listFn(&m.instance, &rows)let body = walkOf(m.key, 'b', site)// SHIP LESS (W173): the list is a server-only member the first load's seed left out (`m.skipped`). The server's rows// stand between the marks and are taken as they are; the first value that arrives builds them (paintFor clears them first)if (!cr && entries == null && m.skipped != null && names != null && names.length > 0) {let left = falsefor (nm of names) { if (m.skipped.includes(nm)) { left = true } }if (left) {start.__hlBox.unclaimed = truestart.__hlEnd = closeOf(start)host.__hlCur = start.__hlEndlet span = 0for (n of between(start)) { if (n.nodeType == 1) { span = span + 1 } }return i + span}}if (entries != null) {let keys = listKeys(&entries)let ri = 0for (entry of entries) {let inner = rows + {}inner[rowName] = shareOf(&entry)let rs = markAt(&host, cr, true)let out = run(body, &m, &o, &host, cr ? 0 : i, &inner, rk + '#' + keys[ri], &fill, cr, null)if (!cr) { i = out }rs.__hlEnd = markAt(&host, cr, false)start.__hlBox.keys.push(keys[ri])// (the row carries a private copy of the record it was built from (`snap`), as buildRow's rows do: without it the FIRST paint// after a load — the page's rows are built here, or claimed from the server's — took every row for changed// and updated, rebound and reseated all of them: ~100 ms for the first append to a chat of 250 rows, w78)start.__hlBox.rows[keys[ri]] = { start = rs; entry = entry; snap = snapOf(&entry); }ri = ri + 1}}start.__hlEnd = markAt(&host, cr, false)return i}// an `if`: the branch that stands, between its marksifAt(&m, &o, &host, i, site, condFn, &rows, rk, &fill, cr, &names, &fnames) {let start = markAt(&host, cr, true)regionAt(&m, &host, site, &rows, rk, &fill, false, null, condFn, &names, &start, &fnames)let side = condFn(&m.instance, &rows) ? 't' : 'e'start.__hlSide = sidelet out = run(walkOf(m.key, side, site), &m, &o, &host, i, &rows, rk, &fill, cr, null)start.__hlEnd = markAt(&host, cr, false)return out}// 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), the read itself as the// generated closure, and its open mark — the region itself, one per row it stands in.regionAt(&m, &host, site, &rows, rowKey, &fill, isFor, rowName, readFn, &names, &start, &fnames) {// 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 no member can move. INSIDE// A ROW it is still registered, with no names: the row's new record moves it// (reseatRows, ticket #86). Outside one nothing ever can.if (names == null) { names = [] }if (names.length == 0 && (rowKey == null || rowKey == '')) { return null }let held = nullif (fill != null) { held = fill + {} held.detached = true }let sid = nextSid()m.sites.push({ sid = sid; el = host; site = site; names = names; region = true; rows = rows; rowKey = rowKey; fill = held; isFor = isFor; row = rowName; read = readFn; start = start; fills = fnames; })if (start != null) { if (start.__hlSid == null) { start.__hlSid = sid } else { start.__hlSidMore = (start.__hlSidMore == null ? '' : start.__hlSidMore) + sid + ',' } }return 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 + rkif (m.kids[kk] == null) {let minted = mintFrom(&m, spec, rows, childChain(m.chain, kk))if (minted == null) { return i }m.kids[kk] = minted}bindFrom(&m.kids[kk], &m, spec, rows)if (cr) { m.kids[kk].sites = [] }m.kids[kk].chain = childChain(m.chain, kk)m.kids[kk].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(m.kids[kk].key, 'v', null)// a child composed straight onto a fragment has its regions on the host the fragment// lands in: the fragment names it, for the re-homing (rehome)if (cr && host.nodeType == 11) {let onFrag = host.__hlOnFrag == null ? [] : host.__hlOnFragonFrag.push(m.kids[kk].chain)host.__hlOnFrag = onFrag}let nodesBefore = host.childNodes.lengthlet curBefore = host.__hlCurlet out = run(f, &m.kids[kk], &m, &host, cr ? 0 : i, {}, '', fillFor(&m, spec, rows, rk, fill), cr, &kidOpt)if (!cr) { i = out }// THE NODES THE CHILD PUT ON ITS HOST CARRY ITS ADDRESS: when a range holding them// leaves the page, the child goes with it (dropRange)let made = []if (cr) {let k = nodesBeforewhile (k < host.childNodes.length) { made.push(host.childNodes[k]) k = k + 1 }} else {let n = curBefore == null ? host.firstChild : curBefore.nextSiblinglet stop = host.__hlCur == null ? null : host.__hlCur.nextSiblingwhile (n != null && n != stop) { made.push(n) n = n.nextSibling }}for (n of made) {let filed = n.__hlKidChains == null ? [] : n.__hlKidChainsfiled.push(m.kids[kk].chain)n.__hlKidChains = filed}if (cr || m.kids[kk].bindings.length == 0) { m.kids[kk].bindings = [] bindKids(&m.kids[kk], m.kids[kk].view) }let roots = rootsBetween(host, firstAt, cr ? host.children.length : i)refOnsFrom(&m, spec, roots, rows)// (the mark names the host that claimed the root: that host's own walk steps over it, the child's own walk — its rows at its top level are roots too — does not)for (el of roots) { el.__hlKid = m.key }return 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 f = b.refreturn f(&inst, &rows)}return null}// A CHILD A REGION BUILDS is born with its address: the host's chain and its own key.// Every patch, and every late patch a function or a waiting handler of it asks for, is// filed and cancelled by that address (tickets #98, #99).mintFrom(&m, spec, rows, chain) {let bp = planOf(spec.key)if (bp == null) { return null }let args = {}for (b of spec.bindings) { args[b.name] = specValue(b, &m, rows) }// A CHILD MINTED LATE takes the current route like one built at boot (#197), by the// same `{ path, params, pattern }` the server hands constructionif (bp.route == true) {let cur = currentRoute()if (cur != null) { args.route = cur }}// the host's own instance, not a copy: this child's `$parent` is the instance whose View placed itlet host = m.instance// THE SERVER VALUES of a kid with server-realm members (D1): asked for with the arguments it was boundif (bp.srv != null) {let sv = emit server values(spec.key, askArgs(args, args.keys()))if (sv != null) { for (k of sv.keys()) { args[k] = sv[k] } }}let inst = hlLoad(moduleUrlOf(spec.key), args, host)registerMount(inst, spec.key, chain, m.rootKind)return { key = spec.key; instance = inst; view = bp.view; sites = []; isShell = false; kids = {}; bindings = []; chain = chain; rootKind = m.rootKind; }}// the route the address bar names, as the server hands it to construction: `{ path, params, pattern }`currentRoute() {let rm = router.match(location.pathname)if (rm == null) { return null }return { path = rm.path; params = rm.params; pattern = rm.route.pattern; }}// every mount a navigation did not rebuild that declares `route` (a child minted late, #197)// takes the new route, by the sync the levels above took theirs throughrouteSync(&m, &sync, cur) {let bp = blueprintOf(m.key)if (bp != null && bp.route == true) {if (sync[m.key] == null) { sync[m.key] = {} }sync[m.key].route = cur}for (k of m.kids.keys()) { routeSync(&m.kids[k], &sync, cur) }return null}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, Number at = 0) {let f = walkOf(m.key, 'v', null)return run(f, &m, &m, &host, at, {}, '', null, false, 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 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. view.listKeys is the one rule: the server's HTML walk and// its `mountKids` key a list the same way (#119: they once gave two rows of one id one mount key).listKeys(&entries) {return view.listKeys(&entries)}// ---- 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. Each row is the// span between its own marks, and every row stands between the list's marks.paintFor(&m, &s, lean) {let host = s.ellet start = s.startif (!standing(host, start)) {// dropped while this paint was on its way (a paint that was running when the// range holding it left, and comes back for another round): it is gone, and// nothing is painted — a site still REGISTERED here is the bugif (!isLive(&m, s)) { return null }if (start != null && dropDue(start)) { return null }return staleSite(s)}if (start.__hlBox == 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 start.__hlBox before the first paint had filed// its row, and built the row again. A paint that arrives while one runs is// remembered, and the running one paints again from the list as it then stands.if (start.__hlBusy != null) { start.__hlBusy = 'again' return null }start.__hlBusy = 'busy'// A ROW WITH A COMPOSED CHILD IS STEPPED OVER only when the write moved no member the child is// bound to (#181): its bound values (`lit = b3`) are host members, not the record, and a write// that moved `L` (derived) may have moved them too — only rebindRow hands them down againif (lean == true && rowHasKid(m.key, s.site)) {if (paintSet == null) { lean = false }else {let bound = rowKidReads(m.key, s.site)for (n of paintSet) { if (bound.includes(n)) { lean = false } }}}let read = s.readlet entries = read(&m.instance, &s.rows)if (start.__hlBox.unclaimed == true) {// SHIP LESS (W173): the server's rows were claimed without the list. No value yet: they stay. The value: they go, the rows are builtif (entries == null) { start.__hlBusy = null return null }for (n of between(start)) { n.remove() }start.__hlBox.unclaimed = false}if (entries == null) { entries = [] }// the keys this list has now, in orderlet keys = listKeys(&entries)let next = []let ri = 0while (ri < entries.length) {next.push({ key = keys[ri]; i = ri; })ri = ri + 1}// 1. THE ROWS THAT ARE GONE: their nodes, their sites and their children's// mounts leave together.let keep = {}for (r of next) { keep[r.key] = true }let goneKeys = []for (k of start.__hlBox.keys) {if (keep[k] == null) { goneKeys.push(k) }}if (goneKeys.length == 1) { dropRow(&m, &s, &start.__hlBox, goneKeys[0]) }else if (goneKeys.length > 1) { dropRows(&m, &s, &start.__hlBox, goneKeys) }// 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.// A DELTA COSTS WHAT CHANGED (#181): each row carries the JSON of the record it was// painted from (`snap`, compared by hlSame), and a row that stands in place with the same record, on a paint// the list's own member started (`lean`), is stepped over — no copy of its record, no// refresh, no rebind. A row is read by address (`entries[r.i]`), never put in a local.let at = start.__hlEndlet found = falsefor (k of start.__hlBox.keys) {if (!found && keep[k] != null && start.__hlBox.rows[k] != null) { at = start.__hlBox.rows[k].start found = true }}let placed = []let changed = []kidMoved = falsefor (r of next) {let hstart = start.__hlBox.rows[r.key] == null ? null : start.__hlBox.rows[r.key].start// the test is Anton's hlSame (JS runtime, #210): the live record against the private copy `snap` taken when the// row was painted — no copy, no stringify; never against the record itself (always equal). A row painted// without a `snap` counts as changed.let same = start.__hlBox.rows[r.key] != null && start.__hlBox.rows[r.key].snap != null && hlSame(&entries[r.i], &start.__hlBox.rows[r.key].snap)if (start.__hlBox.rows[r.key] == null) {buildRow(&m, &s, &start.__hlBox, r.key, &entries[r.i], at)} else if (hstart == at) {// already in place: step over itat = hstart.__hlEnd.nextSiblingif (!(lean == true && same)) {if (updateRow(&m, &s, &start.__hlBox, r.key, &entries[r.i], same)) { changed.push(start.__hlBox.rows[r.key]) }}} else {moveRow(host, &start.__hlBox.rows[r.key], at)if (updateRow(&m, &s, &start.__hlBox, r.key, &entries[r.i], same)) { changed.push(start.__hlBox.rows[r.key]) }}placed.push(r.key)}start.__hlBox.keys = placedif (changed.length > 0) { reseatRows(&m, &s, changed) }let again = start.__hlBusy == 'again'start.__hlBusy = nullif (again) { paintFor(&m, &s, false) }return null}// a row's own elements: the ones between its marksrowEls(&held) {let out = []for (n of between(held.start)) { if (n.nodeType == 1) { out.push(n) } }return out}// A ROW LEAVES: its span goes 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 host = s.ellet nodes = spanOf(held.start)dropRange(&m, host, nodes, s.fill)for (n of nodes) { n.remove() }delete box.rows[key]return null}// SEVERAL ROWS LEAVE IN ONE PAINT (a fold): their nodes are dropped as ONE range, so the sites are swept once// for all of them and the children's mounts purged once (a sweep per row was rows x sites)dropRows(&m, &s, &box, keys) {let host = s.ellet nodes = []for (key of keys) {if (box.rows[key] != null) { for (n of spanOf(box.rows[key].start)) { nodes.push(n) } }}dropRange(&m, host, nodes, s.fill)for (n of nodes) { n.remove() }for (key of keys) { delete box.rows[key] }return null}// A ROW MOVES, marks and all: `moveBefore` where the browser has it, because it keeps// an element's state (focus, a playing video, an open dialog) across the move;// `insertBefore` else.moveRow(host, held, at) {for (n of spanOf(held.start)) {if (host.moveBefore != null) { host.moveBefore(n, at) }else { host.insertBefore(n, at) }}return null}// A ROW ARRIVES: built into a fragment between its marks and put in with one insertion,// because the walk appends and the row's place is where `at` stands — which may be in// the middle of the region. What the walk registered on the fragment belongs to the host.// THE PRIVATE COPY A ROW IS COMPARED WITH (#210): what the record said when the row was painted, as plain JSON data (the// record is mutated in place by the host, so the record itself can never be the thing compared against). A record that// has no JSON text (an undefined value) gives null: the row then counts as changed, never as unchanged.snapOf(&entry) {let text = JSON.stringify(entry)if (text == null) { return null }return JSON.parse(text)}buildRow(&m, &s, &box, key, &entry, at) {let host = s.ellet inner = s.rows + {}inner[s.row] = shareOf(&entry)// (#118) THE RECORD AS THE WALK STARTS: building can wait (a composed child's module loads), and a write to the// record in that time (the next chunk of a live answer) is read by the sites built after it but not by those built// before it. A snap taken after the wait would call the record unchanged for the paint that comes back for that// write, and the row would keep what the early sites read.let snap = snapOf(&entry)let bin = document.createDocumentFragment()let body = walkOf(m.key, 'b', s.site)let before = sidNextlet rs = markAt(&bin, true, true)run(body, &m, &m, &bin, 0, &inner, (s.rowKey == null ? '' : s.rowKey) + '#' + key, &s.fill, true, null)rs.__hlEnd = markAt(&bin, true, false)rehome(&m, bin, host, before)// THE LIST LEFT WHILE THE ROW WAS BEING BUILT (a module to load is a wait, and a// branch around the list can be replaced in it): the row never stands, and what// its walk registered goes with itif (!standing(host, s.start)) {dropRange(&m, host, Array.from(bin.childNodes), s.fill)return null}host.insertBefore(bin, at)box.rows[key] = { start = rs; entry = entry; snap = snap; }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, key, &entry, same) {if (box.rows[key] == null) { return false }// the row holds its own copy of the record, so the two are compared by what they say// (read and written in place: a row held in a local, and put back, is a copy of its record twice per delta — #181)let changed = same != truebox.rows[key].entry = entryif (changed) { box.rows[key].snap = snapOf(&entry) }// ONE shared handle to the record for every element and site of the row (see shareOf): an element or site that took// its own copy would be a copy per element, N^2 for a long list inside the row (#198)let share = shareOf(&entry)box.rows[key].share = sharefor (el of rowEls(&box.rows[key])) { refreshRow(&m, el, s.row, &share) }rebindRow(&m, &s, key, &entry)return changed}// A ROW THAT NOW SHOWS ANOTHER RECORD HANDS IT TO THE SITES INSIDE IT (ticket #86). A// row without an id is keyed by its place, so a new list of the same shape keeps every// row — and refreshRow repaints only the row's own elements. The sites registered in// the row still hold the rows of the moment they were built: a nested `for` read the// old record's list, and a `td` inside it the old inner record. Each site whose element// stands in a changed row takes the new record, and the regions among them are patched// again, outermost first — a nested row that changed in turn does the same for its own.// One pass over the sites, marked rows and an ancestor walk, not a scan per row.reseatRows(&m, &s, changed) {let host = s.el// (#200) a child of these rows took a new bound value: the row's `if`s with a child in their standing branch rebuildlet kidsMoved = kidMoved// every node of a changed row carries its record for the walk up — its text and// its regions' marks as well as its elements, so a text leaf or an `if` standing// in the row directly on the host takes the record too// (the record rides as the row's ONE shared handle, made by updateRow: a site that took a copy of it would be a// copy per site, sites x record size — N^2 for a long list inside the row: #198)// (w79: a node carries only the NUMBER of its row's record in `shares` — a node property holding the record, or the// node of the row standing over it, made a CDP by-value return of a row node fail: "Object reference chain is too long")let shares = []for (held of changed) {let at = shares.lengthshares.push(held.share)for (n of between(held.start)) { n.__hlReseat = at }}// (#71) THE SITES OF THE CHANGED ROWS ARE FOUND FROM THEIR NODES, not by walking every site of the mount up to the// host: an append of one row to a chat of 150 rows scanned and ancestor-walked every site of every row. The nodes of a// changed row carry their sites' numbers (`__hlSids`); the numbers grow along m.sites, so each is found by bisection.// (sites are read and written in place, by index: a site held in a local and put back is a copy of its// rows — every record of every enclosing row — twice per site, and a row with a long list inside has a site per item: #198)// (the record is handed to the site while the rows are still marked; the regions are repainted in the document order the// walk met them in: an outer region's mark comes before the ones inside it)reseatGen = reseatGen + 1let gen = reseatGenlet regs = []let txts = []let last = -1for (held of changed) {for (top of between(held.start)) {// every node under the row's top node, by hand: a call per node is what a reseat of a long row cost (#198)let c = topwhile (c != null) {// the record this node stands under: its own mark, else its parent's (the walk reaches a parent first)c.__hlHit = c.__hlReseat != null ? c.__hlReseat : c.parentNode.__hlHitif (c.__hlSid != null && c.__hlSeen != gen) {c.__hlSeen = genlet hit = c.__hlHitif (hit != null) {let wants = [c.__hlSid]if (c.__hlSidMore != null) { for (id of c.__hlSidMore.split(',')) { if (id != '') { wants.push(JSON.parse(id)) } } }for (want of wants) {// the sites of one row were registered one after the other: the one after the last found is tried first, else bisectedlet k = -1if (last >= -1 && last + 1 < m.sites.length && m.sites[last + 1].sid == want) { k = last + 1 }else {let lo = 0let hi = m.sites.length - 1while (lo <= hi) {let sum = lo + hilet mid = (sum - (sum % 2)) / 2let sid = m.sites[mid].sidif (sid == want) { k = mid lo = hi + 1 } else if (sid < want) { lo = mid + 1 } else { hi = mid - 1 }}}if (k >= 0) { last = k }if (k >= 0 && m.sites[k].el != null && m.sites[k].rows != null && !(m.sites[k].region && m.sites[k].start == s.start)) {m.sites[k].rows[s.row] = shares[hit]if (m.sites[k].region) { regs.push(want) } else if (m.sites[k].text == true) { txts.push(want) }}}}}if (c.firstChild != null) { c = c.firstChild }else {while (c != top && c.nextSibling == null) { c = c.parentNode }c = c == top ? null : c.nextSibling}}
Only the first lines are shown.
Branches
Latest commits
- f2b5db98styles: format styles with nested rules and bare queriesmre
- f036bab4search: format styles with nested rules and bare queriesmre
- ef9a9d4asongs: format styles with nested rules and bare queriesmre
- f22f9aacmain: format styles with nested rules and bare queriesmre
- f56cd7c7Sync icons from 8176eb1 and verify mixed component sourcesmre
- d56e5054Sync theme and shared tokens from layouts 17e0f03mre
- b1362547Re-vendor to Hybriel set day35mre
- 89e10f08Records: mission 002 rollback wordingmre
- 9485dee7Records: mission 002 brief (live step)mre
- 9ba68fe7Records: S1b reviewedmre
- 193dfff1Records: S1 result, S1b startedmre
- 028ed776Records: mission 001 continuation S1bmre
- 1838d7e8Records: S1 startedmre
- a43fca3fRecords: mission 001 decided pointsmre
- 41773828Records: statusmre
- a82c0805Records: mission 001 brief (Style form)mre
- a4bce6d1Records: ticket push subscriptionmre
- 14abde3bjukebox: records: Atlas's records moved to worldapi-conductor/archivemre
- 0433e9a8jukebox: records: gitoria remote added and pushedmre
- 1722d707jukebox: records: repo creation handed to Gitoriamre