tickets
All repositories: gitoria
185.4 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 module params state view }, shell: … | null }view = new HlwViewrouter = 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 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 = nullregionTable = {} // 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 openprobing = 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 opened// 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 = 0seenAbove = {} // 'n<n>' → true for a push dispatched past lastSeq (one a POST's ack carried)everOpened = falsenavigating = false // a navigation is running (show); navNext is the one asked for meanwhilenavNext = nullpinging = false // the ping interval is started once, with the first socketpongDue = null // the timer that takes the socket for dead when its pong is latenextId = 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 silentlateInner = 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 thenblueprints = {} // component key → { module, view }: every tree the page can// build, taken from each seed and never dropped (takeBlueprints)strict = 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 = []sidNext = 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 = false// 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 = 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'squeueRetryTimer = 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) => { return live.client.goTo(path) }// 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() }// ---- 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)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 }let table = s.valuess.values = nullif (s.page != null) { s.page = unshare(&table, s.page) }if (s.shell != null) { s.shell = unshare(&table, s.shell) }return 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 == 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 = 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()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}for (n of between(slotStart)) { 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}// 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) {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}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}instantiateNode(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 = chain.length > 0 && chain[chain.length - 1] == '^'; kids = {}; bindings = []; chain = chain; rootKind = root; }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) }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}// 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 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 }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) { 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] }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) {inner.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['^'] = innerreturn 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)slotStart.__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) {page.sites = []create(&page, host)headSites(&page)wearHead(&page)pageShown = trueplaceRegions(false)}}start.__hlEnd = markAt(host, true, false)slotStart = 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 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 }takeBlueprints(next.blueprints)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)if (m.kids['^'] != null) {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['^'] }}slotEl = 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 }for (n of nodes) { n.__hlGone = true }let kept = []let dropped = 0for (site of m.sites) {let n = (site.region && site.el == host && site.start != null) ? site.start : site.ellet gone = falsewhile (n != null && n != host && !gone) {if (n.__hlGone == true) { gone = true }n = n.parentNode}if (gone) { dropped = dropped + 1 } else { kept[] = site }}if (dropped > 0) {m.sites = keptdropGen = dropGen + 1}for (n of nodes) { n.__hlGone = null }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 = []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)) { disposeAt(&m, c, base.length) }else { others.push(c) }}}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)for (c of d.kids) { if (c.length > depth) { disposeAt(&m, c, depth) } }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) {purgeMounts(chain, m.rootKind)delete m.kids[chain[depth]]}return null}if (m.kids[chain[depth]] == null) { return null }disposeAt(&m.kids[chain[depth]], chain, depth + 1)return null}// 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}liveSids(&m) {let out = {}for (e of m.sites) { out[e.sid] = true }return out}// 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 inst = m.instancelet t = leafNode(host, cr, readFn(&inst, &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)let box = { keys = []; rows = {}; }let entries = listFn(&m.instance, &rows)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] = 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)box.keys.push(keys[ri])box.rows[keys[ri]] = { start = rs; entry = entry; }ri = ri + 1}}start.__hlEnd = markAt(host, cr, false)start.__hlBox = boxreturn 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)for (el of roots) { el.__hlKid = true }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 = blueprintOf(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 }}let inst = hlLoad(bp.module, args)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. 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 = {}for (let ri = 0; ri < entries.length; ri = ri + 1) {let k = view.rowKey(&entries[ri], ri)if (seen[k] != null) { k = k + ':' + ri }seen[k] = trueout.push(k)}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. 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 (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 }for (k of start.__hlBox.keys) {if (keep[k] == null) { dropRow(&m, &s, &start.__hlBox, 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.// A DELTA COSTS WHAT CHANGED (#181): each row carries the JSON of the record it was// painted from (`sig`), 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].startlet sig = JSON.stringify(entries[r.i])if (start.__hlBox.rows[r.key] == null) {buildRow(&m, &s, &start.__hlBox, r.key, &entries[r.i], at)if (start.__hlBox.rows[r.key] != null) { start.__hlBox.rows[r.key].sig = sig }} else if (hstart == at) {// already in place: step over itat = hstart.__hlEnd.nextSiblingif (!(lean == true && start.__hlBox.rows[r.key].sig == sig)) {if (updateRow(&m, &s, &start.__hlBox, r.key, &entries[r.i], sig)) { 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], sig)) { 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}// 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.buildRow(&m, &s, &box, key, &entry, at) {let host = s.ellet inner = s.rows + {}inner[s.row] = shareOf(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; }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, sig) {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 = box.rows[key].sig != sigbox.rows[key].entry = entrybox.rows[key].sig = sig// 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)for (held of changed) {for (n of between(held.start)) { n.__hlReseat = held.share }}// (#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 : 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] = hit.__hlReseatif (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}}}}for (held of changed) { for (n of between(held.start)) { n.__hlReseat = null } }for (t of txts) {let at = sitePos(&m, t, -1)if (at >= 0) { paintText(&m, &m.sites[at]) }}for (r of regs) {// read again from the mount: a region an outer one already patched away is gonelet at = sitePos(&m, r, -1)if (at >= 0) {if (m.sites[at].isFor) { paintFor(&m, &m.sites[at], false) } else { rebuildIf(&m, &m.sites[at], kidsMoved && ifBranchHasKid(m.key, m.sites[at].site, m.sites[at].start.__hlSide)) }}}return null}// the index of the site numbered `want` in m.sites, or -1: sids only grow along m.sites, so it is bisected (#71)sitePos(&m, want, hint) {// the sites of one row were registered one after the other: the one after the last found is tried firstif (hint >= 0 && hint < m.sites.length && m.sites[hint].sid == want) { return hint }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) { return mid }if (sid < want) { lo = mid + 1 } else { hi = mid - 1 }}return -1}// ONE HANDLE TO A RECORD: hlShared (core, #198/mission 383) gives a read-only shared handle the language's copy rules// pass as is, so storing it in the `rows` of a hundred sites copies nothing; the sites read it in place, a write through// it is a located 'read-only shared value' error. Scalars come back as themselves; on native it is the identity.shareOf(entry) {return hlShared(entry)}// 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, key, &entry) {// a row body with no composed child has nothing to take again: decided once per bodylet bk = m.key + '|' + s.siteif (rowKidless[bk] == true) { return null }if (rowKidless[bk] == null) { rowKidless[bk] = !rowHasKid(m.key, s.site) }if (rowKidless[bk] == true) { return null }let rk = (s.rowKey == null ? '' : s.rowKey) + '#' + keylet inner = s.rows + {}inner[s.row] = entry// (the seed's tree is read in place: a copy of it, or of the instance, per row per delta// is what froze a streaming chat — #181)if (blueprints[m.key] != null) { rebindIn(&m, &blueprints[m.key].view, s.site, &inner, rk) }return null}// the host members the composed children of the `for` at `site` are bound to (read in place, once per body)rowKidReads(key, site) {let bk = key + '|' + siteif (rowKidBound[bk] != null) { return rowKidBound[bk] }let out = []if (blueprints[key] != null) { kidReadsIn(&blueprints[key].view, site, out) }rowKidBound[bk] = outreturn out}kidReadsIn(&nodes, site, &out) {for (let i = 0; i < nodes.length; i = i + 1) {if (nodes[i].k == 'for' && nodes[i].site == site) { bodyReads(&nodes[i].body, out) }else if (nodes[i].k == 'el') { kidReadsIn(&nodes[i].children, site, out) }else if (nodes[i].k == 'if') { kidReadsIn(&nodes[i].then, site, out) kidReadsIn(&nodes[i].other, site, out) }else if (nodes[i].k == 'for') { kidReadsIn(&nodes[i].body, site, out) }else if (nodes[i].k == 'component' && nodes[i].fill != null) { kidReadsIn(&nodes[i].fill, site, out) }}return null}// every name a composed child's binding reads, anywhere in these nodesbodyReads(&nodes, &out) {for (let i = 0; i < nodes.length; i = i + 1) {if (nodes[i].k == 'component') {for (let j = 0; j < nodes[i].bindings.length; j = j + 1) {if (nodes[i].bindings[j].member != null) { out.push(nodes[i].bindings[j].member) }else if (nodes[i].bindings[j].ref != null) { exprReads(&nodes[i].bindings[j].ref, out) }}if (nodes[i].fill != null) { bodyReads(&nodes[i].fill, out) }} else if (nodes[i].k == 'el') { bodyReads(&nodes[i].children, out) }else if (nodes[i].k == 'if') { bodyReads(&nodes[i].then, out) bodyReads(&nodes[i].other, out) }else if (nodes[i].k == 'for') { bodyReads(&nodes[i].body, out) }}return null}exprReads(&x, &out) {if (x == null) { return null }if (x.k == 'member' || x.k == 'field') { out.push(x.name) return null }if (x.k == 'expr') { exprReads(&x.x, out) return null }if (x.k == 'bin') { exprReads(&x.l, out) exprReads(&x.r, out) return null }if (x.k == 'un') { exprReads(&x.x, out) return null }if (x.k == 'cond') { exprReads(&x.c, out) exprReads(&x.a, out) exprReads(&x.b, out) return null }return null}// whether the body of the `for` at `site` holds a composed child — read in place, nothing copiedrowHasKid(key, site) {if (blueprints[key] == null) { return false }return kidIn(&blueprints[key].view, site, false)}// walks the tree by address to the `for` at `site`; asks (find false) or re-binds (find true) its bodykidIn(&nodes, site, inside) {for (let i = 0; i < nodes.length; i = i + 1) {if (nodes[i].k == 'for' && nodes[i].site == site) { if (bodyHasKid(&nodes[i].body)) { return true } }else if (nodes[i].k == 'el') { if (kidIn(&nodes[i].children, site, inside)) { return true } }else if (nodes[i].k == 'if') { if (kidIn(&nodes[i].then, site, inside) || kidIn(&nodes[i].other, site, inside)) { return true } }else if (nodes[i].k == 'for') { if (kidIn(&nodes[i].body, site, inside)) { return true } }else if (nodes[i].k == 'component' && nodes[i].fill != null) { if (kidIn(&nodes[i].fill, site, inside)) { return true } }}return false}// the row body of the `for` at `site`, bound again — found and walked by address (rebindNodes)rebindIn(&m, &nodes, site, &rows, rk) {for (let i = 0; i < nodes.length; i = i + 1) {if (nodes[i].k == 'for' && nodes[i].site == site) { rebindNodes(&m, &nodes[i].body, &rows, rk) return true }let got = falseif (nodes[i].k == 'el') { got = rebindIn(&m, &nodes[i].children, site, &rows, rk) }else if (nodes[i].k == 'if') { got = rebindIn(&m, &nodes[i].then, site, &rows, rk) || rebindIn(&m, &nodes[i].other, site, &rows, rk) }else if (nodes[i].k == 'for') { got = rebindIn(&m, &nodes[i].body, site, &rows, rk) }else if (nodes[i].k == 'component' && nodes[i].fill != null) { got = rebindIn(&m, &nodes[i].fill, site, &rows, rk) }if (got) { return true }}return false}bodyHasKid(&nodes) {for (let i = 0; i < nodes.length; i = i + 1) {if (nodes[i].k == 'component') { return true }if (nodes[i].k == 'el' && bodyHasKid(&nodes[i].children)) { return true }if (nodes[i].k == 'if' && (bodyHasKid(&nodes[i].then) || bodyHasKid(&nodes[i].other))) { return true }if (nodes[i].k == 'for' && bodyHasKid(&nodes[i].body)) { return true }}return false}// whether the branch of the `if` at `site` that stands (side 't' / 'e') holds a composed child — by address, nothing copiedifBranchHasKid(key, site, side) {if (blueprints[key] == null) { return false }return ifKidIn(&blueprints[key].view, site, side)}ifKidIn(&nodes, site, side) {for (let i = 0; i < nodes.length; i = i + 1) {if (nodes[i].k == 'if' && nodes[i].site == site) { return side == 't' ? bodyHasKid(&nodes[i].then) : bodyHasKid(&nodes[i].other) }let got = falseif (nodes[i].k == 'el') { got = ifKidIn(&nodes[i].children, site, side) }else if (nodes[i].k == 'if') { got = ifKidIn(&nodes[i].then, site, side) || ifKidIn(&nodes[i].other, site, side) }else if (nodes[i].k == 'for') { got = ifKidIn(&nodes[i].body, site, side) }else if (nodes[i].k == 'component' && nodes[i].fill != null) { got = ifKidIn(&nodes[i].fill, site, side) }if (got) { return true }}return false}// (#200) whether every member that moved holds a plain value (text, number, flag): a child handed one may draw it once// (MdEditor's mount hook), so its branch is composed anew; a list or record is drawn by the child's own `for`s and sites,// which repaintAll patches — rebuilding them is the cost #198 removed
Only the first lines are shown.
Branches
Latest commits
- e9f428e7tools: reown-authors (tracker#36: every author that is not Caramboleyo or Apollo becomes the project's conductor; antcolony, miserit-anthar, hybrilior, termuplex stay) and a read-only author surveymre
- f51029abMerge branch 'sy-sync'mre
- eae6e8c7sync components.hybriel 4922f9c: comments like / Edit / Delete / 'edited' are 44 px targets; gate: 'edited' hit-area padding, thread targets check (SY)mre
- 0de4750btheme: sync from layouts 4994037 (list rows stack, td word-keep, heading code, edited tap target)mre
- 4eeb7bfeST2 report wordingmre
- 2558f56cst2-sec: keep the hlsid session cookie name (no one is signed out), Secure flag only; gate: a cookie issued by main stays signed in; ident stub serves selector.js; security.mjs in deploy GATESmre
- ea2e440esecurity audit (ST): JSON body cap, relation rights, login session rotation, __Host- Secure cookie, API security headers, CSP+referrer meta, /connect cap, one-line subjects, tests/security.mjs, reportmre
- 7c8c2282sessions last 99 years (creator 2026-10-23: logins never expire; only sign out ends them)mre
- b6277497report MT-mobile, LOGmre
- 6709398blist paging: the newest rows come first (the sorted array was not used); filter rows hide their scrollbar; gate checks the ordermre
- 31736a80gate: member-name check fails on the old row layout toomre
- e03ae537gate: the phone checks run on without the Show more button (so old code reports every failed check)mre
- adf7f132gate: 390 px checks for the mobile audit fixes (row number, filters, field widths, Edit, member names, relation taps, paging)mre
- 28e9c938ticket list: draw the newest 50 rows and a Show more button (500 rows were a 2-4 s first paint, 740 KB, a 90 000 px phone page)mre
- ccebb0c7mobile: ticket number stays on one line, filter chips one scrolling row, fields full width under their caption, Edit/action buttons, member names whole, 44 px relation linksmre
- f2dc7741gate: the phone toolbar is two even rows (E2)mre
- 20f7c33async components.hybriel 214c318: MdEditor on a phone, two even toolbar rows of 44 px targets, label 15 px, table head 16 px (E2)mre
- d74a5482sync components.hybriel 134b4e3: MdEditor builds an editor put into the page at once, redraws a surface put in anew (F5, hybriel#211)mre
- 9d02c540sync components.hybriel 6b0936a: the 'edited' foldable drops the theme's border and marginmre
- 22751914sync components.hybriel 8d79ff7: bubble hugs its content, quiet 'edited' label; gate checksmre