jukebox
All repositories: gitoria
276.3 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)bodyAttrs = [] // root body attributes; initialized before boot() claims the pageslotEl = 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 = 5// PERSISTENT PAGES (hybriel#411): a page that declares `persistent = true` is kept by its ADDRESS (pathname + search), not by// the history entry, with no count cap: a link, navigate(), Back and Forward to that address attach the same DOM and// instances again, scrolled where they were left, and ask the server for nothing. While it is detached it hears no push: the// pushes its components listen to are queued on its record (in order, `persistBytes` at most, the bound of the server's// pushKeptBytes) and run before it is shown. Past the bound, after a resync, or past `persistFor` seconds (an optional// member), the copy is dropped and the page is built as any page. A sweep of the expired ones runs at each navigation.persistBytes = 1048576keptUid = 0hidNext = 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 openstatic connectWithin = 5000 // handshake deadline in ms, independent of the OPEN socket's ping settingsstatic connectCap = 60000 // the handshake deadline never grows past this (ms)connectLimit = 5000 // THE CURRENT UPGRADE's deadline: connectWithin, doubled by every upgrade that expired in a row, reset when a socket opens (#403)connectingAt = 0 // monotonic start of the current upgradeconnectDue = null // the current upgrade's deadline timersocketOpened = 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 connectingsessionHello = false // this socket has reported whether its upgrade carried a sessioncookieWatch = null // the cookieStore listener for a login in a tab of another origin of the same site is boundemitPosts = 0 // the offline emits' fallback POSTs in flight (crossing())emitGateN = 0 // how many emits wait in emitGateemitGate = {} // (keyed by number) resolvers of the emits waiting for the one fallback POST in flight to settle (crossing(): they follow it, in order)httpAt = 0 // the monotonic time an HTTP request of this page last got an answer (the document itself counts: 0 = the page load); see crossing()resumeWait = false // this socket's hello asked for a refresh (a cached document, or an offline-built page) and its answer has not come: reach is not 'up' yet (#403)probing = 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'// 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 = nullnavTurn = 0 // changes on every requested navigation, including Back/ForwardnavLate = null // a timed crossing and the local instance it may refreshnavResync = null // the same answer supplies newly minted children during its patchnavFlight = null // the framework page crossing, cancellable when a newer route winsbusyN = 0 // #434: navigations and emit answers open now; <html data-hl-busy> stands while it is above 0emitOrigin = null // #435: the button whose handler is running (set for the run of one event; its emits mark it)navWake = null // a failed page answer waits for the next carrier, or a newer routelateFrames = [] // the pushes a page answer carries (`ack.late`, hybriel#410): applied once the page stands, in ordernavNextKeep = 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 = falsetargetRegs = [] // the handlers `on window.x()` / `on viewport.x()` / `on document.x()` registered: { id, target, event, fn } (see registerTargets)targetHooks = {} // 'window.resize' -> true: the one DOM listener per target and event, installed at the first registrationheldPrompt = null // a beforeinstallprompt nobody listened to yet: handed to the first component that does, onceseenObserver = null // the page's one IntersectionObserver for `on seen()` (#412), made at the first elementseenRuns = [] // the elements it still watchesseenWaiting = [] // seen while the tab was hidden: they fire when it showsheld = []heldDom = [] // DOM events received while claim still reads the rendered state (#399)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 markspushRuns = null // WeakMap: instance -> one-element array holding its latest delivery Promisedelivering = 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)paintInput = null // focused control protected by this same-page replace patch only (#328)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)mountQueue = [] // kids minted after the page stood (a row added): their `on mount()` runs once the patch that built them is painted (#236)turning = false // a patch is running (patch): the ones asked for meanwhile wait in patchQueuepatchQueue = []followers = [] // the elements that carry `follow` (follow): scroll containers kept at their endfollowSeen = null // the ResizeObserver that keeps them there when something inside grows after a patchplacing = 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// 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 = 3000retryTimer = nullonlineBound = false // the online/offline listeners are on the window (syncOnline)// ---- 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 }// Features register during module evaluation, before this page constructs its Client.static features = {}static registerFeature = (String name, Function feature) => { if (feature != null) { features[name] = feature } return features[name] }offline = nulluploads = 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 = (String path, Boolean 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 = (String title, Hybrid options) => { return live.client.showNotice(title, options) }static notifyAt = (Number at, String title, Hybrid options) => { return live.client.noticeAt(at, title, options) }// …or after `ms` millisecondsstatic notifyIn = (Number ms, String title, Hybrid 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 = (Hybrid subscription, String | Bytes payload, Hybrid 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 = () => { if (live.client.offline != null) { return live.client.offline.forgetOffline() } live.client.dropKept() return null }// 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 = (String 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 = (Hybrid x, Hybrid inst, Hybrid rows) => { return view.evalExpr(&x, &inst, &rows) }seed = resolveValues(JSON.parse(seedText))if (seed.offline != null && Client.features.offline != null) { feature = Client.features.offline offline = new feature(client = this) }router = new HlwRouter(routes = seed.routes)for (r of seed.routes) {if (r.component == null && r.pattern.indexOf(':') < 0 && r.pattern.indexOf('*') < 0) { plainRoutes[r.pattern] = true }}// A `beforeinstallprompt` can fire before any component stands: this listener (installed at module load) keeps the event, and the first// component with `on window.beforeinstallprompt(e)` gets it when it mounts (registerTargets). Nothing is prevented here.targetHooks['window.beforeinstallprompt'] = truewindow.addEventListener('beforeinstallprompt', (Hybrid ev) => {let n = dispatchTarget('window', 'beforeinstallprompt', ev)if (n == 0) { heldPrompt = ev }})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)}// The donor seed is used only to locate the slot during the shell's claim (#350).if (seed.offlineNotice != null) { offlineNotice() return null }page = seed.page != null ? instantiate(seed.page, [], 'page', layoutHost(shell)) : 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()sweepAll()listen()syncOnline()syncReach()if (offline != null) { offline.standIn() }if (offline != null) { offline.offlineBoot() }connect()}// A FRAMEWORK NOTICE IN A KEPT SHELL (#350). No donor page is instantiated or// claimed, and no offline state is started for the unavailable URL.// The carrier follows reachability for the shell without mounting a page (#381).// The worker has already replaced the page HTML, so the first paint is the notice.offlineNotice() {seed.page = nulldocument.title = seed.head != null && seed.head.title != null ? seed.head.title : ''// R67 / #423: links use the normal navigation path; the notice itself// still starts no offline store and mounts no donor page (#381).appHead = seed.headlisten()setReach('down')release()syncOnline()connect()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(Hybrid 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 = false// App writes must wait too: claim still reads the server-rendered list (#399).events = heldDomheldDom = []// ONE FAILING HANDLER DOES NOT COST THE OTHERS THEIR RUN (#422): each is attempted, a failure is loggedfor (dispatch of events) {let r = window.__hlAttempt(() => { return dispatch() })if (!r.ok) { console.error('framework: a handler held while mounting failed — ' + r.error) }}let 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(String key) {if (window.__hlB == null) { return null }return window.__hlB[key]}// A browser key IS the module path without its leading slash (the server's// graphModuleKey). No disk path or separate URL mapping reaches the client.// does this component declare a setter for the member? (its blueprint names them — hybriel#301): a parameter the host binds// into such a member goes through the setter and is not a construction argument or a plain write herehasSetter(String key, String name) {let bp = blueprintOf(key)return bp != null && bp.setters != null && bp.setters.includes(name)}// A PARAMETER THE HOST BINDS INTO A CHILD'S SETTER (hybriel#301) is written through the setter, once for each change of the// host's value. The member may never hold the value (the setter decides), so the last value given is kept on the mount record// and compared with. Answers the member names to repaint — the parameter and what the setter writes — or null when this is// the value already given.giveSetter(&kid, String name, Hybrid | String | Number | Boolean | Bytes | Function v) {if (kid.given == null) { kid.given = {} }if (kid.given.keys().includes(name)) {let last = kid.given[name]if (hlSame(&last, &v)) { return null }}kid.given[name] = vkid.instance[name] = vlet names = [name]let wrote = compiledEntry(kid.key, 'mt', name)if (wrote != null) { for (w of wrote) { if (!names.includes(w)) { names.push(w) } } }return names}moduleUrlOf(String 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(String key) {if (blueprintOf(key) == null) { window.__hlP.L(moduleUrlOf(key)) }return blueprintOf(key)}treeOf(String 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(Hybrid m, Hybrid chain, String root, Hybrid host = null) {purgeMounts(chain, root)return instantiateNode(m, chain, root, host)}// The innermost layout owns the page in its slot; the top shell itself has no host.layoutHost(Hybrid m) {let at = mif (at == null) { return null }while (at.kids['^'] != null) { at = at.kids['^'] }return at.instance}// a mount made at (chain, root) replaces whatever was there: forget it and everything under itpurgeMounts(Hybrid chain, String 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(Hybrid chains, String 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(Hybrid inst, String key, Hybrid chain, String 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] = idwindow.__hlP.M(inst, window.__hlC[key].mt, (String name) => { methodReturned(id, name) })if (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(Hybrid inst, String key, Number 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, String key, String ev, Number depth) {window.__hlC[key].on(&inst, ev, (Hybrid | String | Number | Boolean | Bytes | Function a, Hybrid | String | Number | Boolean | Bytes | Function b, Hybrid | String | Number | Boolean | Bytes | Function c, Hybrid | String | Number | Boolean | Bytes | Function d, Hybrid | String | Number | Boolean | Bytes | Function 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(String ev, Hybrid args, Number 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 (hybriel#63, #361). A page or// layout uses its wrapping layout; only a top shell or a standalone page has none.instantiateNode(Hybrid m, Hybrid chain, String root, Hybrid host, Hybrid given) {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] }// THE PARAMS THE HOST BINDS ARE NOT IN THE SEED (hybriel#276; `m.bound`): `given` holds what the host's binding reads now;// a name it cannot give yet (a binding inside a `for` row, which the row's claim binds) is null, never its initializerif (m.bound != null) {// (a name the child's setter takes is no argument: the server ran the setter at the mount and its effects are in the state)for (k of m.bound) { if (!hasSetter(m.key, k)) { args[k] = null } }if (given != null) { for (k of given.keys()) { if (!hasSetter(m.key, k)) { args[k] = given[k] } } }}// #413: the server already evaluated these members and found them equal to a bound argument.// Copy that argument into the construction pins; this does not re-run an initializer or create a live alias.if (m.copies != null) { for (name of m.copies.keys()) { args[name] = args[m.copies[name]] } }// A row's bindings arrive during claim, after this mirror is built (#307).// Pin omitted members now; bound kids derive in bindFrom, before their View is walked.pendingDerived = m.bound != null && m.bound.length > 0 ? m.derived : nullif (m.derived != null) { for (name of m.derived) { args[name] = null } }let inst = hlLoad(moduleUrlOf(m.key), args, host)if (m.derived != null && pendingDerived == null) {for (name of m.derived) { inst.__derive__(inst.constructor.__memberSites__[name]) }}// 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; derived = m.derived; pendingDerived = pendingDerived; given = {}; }if (root == 'shell' && (chain.length == 0 || chain[chain.length - 1] == '^')) { langSite(&out) }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 sites// the edges first: a kid's bound params are read off this instance while the kid is built, top downbindKids(&out, out.view)for (k of m.kids.keys()) {let given = nullif (m.kids[k].bound != null) {given = {}for (b of out.bindings) { if (b.kid == k && m.kids[k].bound.includes(b.target)) { given[b.target] = bindingValue(b, &out) } }}out.kids[k] = instantiateNode(m.kids[k], childChain(chain, k), root, inst, given)}// 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) {// A PARAMETER THE CHILD'S SETTER TAKES IS NOT WRITTEN HERE (hybriel#301): the server ran the setter at the mount, once,// and what it did is in the seed's state; a second run here would count the mount twiceif (out.kids[b.kid] != null && hasSetter(out.kids[b.kid].key, b.target)) {out.kids[b.kid].given[b.target] = bindingValue(b, &out)} else if (out.kids[b.kid] != null) {out.kids[b.kid].instance[b.target] = bindingValue(b, &out)}}return out}bindKids(&m, Hybrid 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(String key, String event) {let names = compiledEntry(key, 'ev', event)return names == null ? [] : names}memberWrites(String key, String name) {let names = compiledEntry(key, 'mw', name)return names == null ? [] : names}// the members the declared handlers that write `name` read (compile.hl handlerFeeds); [] for nonehandlerFeedsOf(String key, String name) {let reads = compiledEntry(key, 'hf', name)return reads == null ? [] : reads}// the members some declared handler writes (compile.hl handlerFeeds)handlerFed(String key) {if (window.__hlC == null || window.__hlC[key] == null || window.__hlC[key].hf == null) { return [] }return window.__hlC[key].hf.keys()}derivationsOf(String 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(String key, String table, String 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(String 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(String key, String 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(String key, String slot, String 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(Function f, &m, &o, &host, Number i, &rows, String rk, &fill, Boolean cr, &opt) {if (f == null) { return i }return f(&this, &m, &o, &host, i, &rows, rk, &fill, cr, &opt)}acqFail(String tag, Hybrid 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(Hybrid el, Hybrid 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}// ---- `follow = flag` (ticket #396) ------------------------------------------------------// A scroll container that follows stays at its end while it was at its end: a patch that adds or grows// content inside it scrolls it on only if it stood at its end (within a few pixels) before the patch, so a// user who scrolled up stays where they are. What grows later (an image loads, a row's text wraps) is// the same: the container's tracked state says whether it was at its end. `follow` is no HTML attribute.atEnd(Hybrid el) {return el.scrollHeight - el.scrollTop - el.clientHeight <= 4}// the generated walk calls this for every element with a `follow`, built or claimed, and a member's// repaint writes `__hlFollow` itselffollow(Hybrid el, Hybrid | String | Number | Boolean | Bytes | Function flag) {el.__hlFollow = flag != null && flag != false && flag != "" && flag != "false"if (el.__hlFollowed == true) { return null }el.__hlFollowed = trueel.__hlEnd = trueel.__hlWas = truefollowers.push(el)el.addEventListener('scroll', () => { el.__hlEnd = atEnd(el) })// a container built or claimed with its content stands at its end once it is laid outwindow.requestAnimationFrame(() => { followKeep() })return null}// before a patch: which followers stand at their end nowfollowMark() {for (el of followers) { el.__hlWas = el.__hlFollow == true && atEnd(el) }return null}// after a patch (and when a child resizes): the followers that stood at their end stand there againfollowKeep() {let live = []for (el of followers) {if (el.isConnected) { live.push(el) }}followers = livefor (el of followers) {if (el.__hlFollow == true && el.__hlWas == true) {if (!atEnd(el)) { el.scrollTop = el.scrollHeight }el.__hlEnd = true} else { el.__hlEnd = atEnd(el) }el.__hlWas = el.__hlFollow == true && el.__hlEnd == truefollowWatch(el)}return null}// a container and its children are watched: a child that grows after the patch (an image, wrapped text) moves the endfollowWatch(Hybrid el) {if (followSeen == null) {followSeen = new ResizeObserver(() => { followResized() })}followSeen.observe(el)for (kid of Array.from(el.children)) { followSeen.observe(kid) }return null}followResized() {for (el of followers) {if (el.isConnected && el.__hlFollow == true && el.__hlEnd == true && !atEnd(el)) { el.scrollTop = el.scrollHeight }}return null}// ---- `modal = flag` on a dialog, `popoverOpen = flag` on a popover (tickets #329, #389) ----------// The member drives the browser's top layer: true shows the dialog with showModal() (the popover with// showPopover()), false closes it. A native close (Escape, a form method=dialog, a light dismiss) writes the// member back to false, so the View and the member agree. Neither name is an HTML attribute.// The generated walk calls this for each such element, built or claimed; a member's repaint sets `__hlTop`// and calls `__hlTopSync` itself.topAt(&m, Hybrid el, String name, String member, Hybrid | String | Number | Boolean | Bytes | Function flag, Hybrid rows) {el.__hlTop = flag != null && flag != false && flag != "" && flag != "false"if (el.__hlTopWired == true) { el.__hlTopSync() return null }el.__hlTopWired = truelet isDialog = name == 'modal'let tries = 0el.__hlTopSync = () => {// not in the document yet (a page built off-screen): the next frameif (!el.isConnected) {tries = tries + 1if (tries < 20) { window.requestAnimationFrame(() => { el.__hlTopSync() }) }return null}let shown = isDialog ? el.matches(':modal') : el.matches(':popover-open')if (el.__hlTop == true && !shown) {if (isDialog) {if (el.open) { el.close() }el.showModal()} else { el.showPopover() }} else if (el.__hlTop != true && shown) {if (isDialog) { el.close() } else { el.hidePopover() }}return null}// a native close writes the member back (a member that is already false, or a row variable, is left alone)let back = () => {let shown = isDialog ? el.matches(':modal') : el.matches(':popover-open')if (shown || member == null || rows[member] != null) { return null }el.__hlTop = falseif (m.instance[member] == null || m.instance[member] == false) { return null }m.instance[member] = falsepatch(m.chain, m.rootKind, [member], [])return null}if (isDialog) { el.addEventListener('close', () => { back() }) }else { el.addEventListener('toggle', () => { back() }) }el.__hlTopSync()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, Hybrid el, Hybrid names, String site, String valueMember, Boolean isSelect, Hybrid 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, Hybrid el, Hybrid | String | Number | Boolean | Bytes | Function 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, Hybrid el, String event, String site, Hybrid rows, Hybrid wrote, Hybrid 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()runEvent = (Hybrid ev) => {let lit = el.__hlLits[event]for (rk of rowNames) { lit[rk] = el.__hlRows[rk] }domListener = { event = event; chain = at; root = root; wrote = wrote; }originFor(el, event, ev)// A host timer returns immediately; keep it here so originFor stays synchronous.mine = emitOriginif (mine != null) { window.setTimeout(() => { if (emitOrigin == mine) { emitOrigin = null } }, 0) }fire(&lit, event, ev)el.__hlLits[event] = litpatch(at, root, wrote, touched)}if (event == 'seen') { watchSeen(el, runEvent) return null }el.addEventListener(event, (Hybrid ev) => {// Capture dispatch-only fields before the first awaited call. If dispatch// waits for claim, preserve native defaults except the framework-owned submit.current = ev.currentTargettarget = ev.targetphase = ev.eventPhasewaiting = mountingif (event == 'submit') { ev.preventDefault() }if (waiting) { deferDom(ev, current, target, phase, runEvent) return null }runEvent(ev)})return null}// `on seen()` (#412): fires ONCE per element, when the element is at least partly in the viewport while the tab is// visible. ONE IntersectionObserver serves the page. An element that came into view while the tab was hidden waits in// `seenWaiting` and fires when the tab becomes visible (`seenFlush`). A fired element is unobserved, and so is one that// left the DOM unseen (swept at every report). `seenRuns` is the array of the elements still watched, each carrying its// handler's run in `__hlSeen`.watchSeen(Hybrid el, Function go) {if (seenObserver == null) { seenObserver = new IntersectionObserver((Hybrid entries) => { seenReport(entries) }) }el.__hlSeen = goseenRuns.push(el)seenObserver.observe(el)return null}seenReport(Hybrid entries) {for (en of entries) {if (en.isIntersecting && en.target.__hlSeen != null && !seenWaiting.includes(en.target)) { seenWaiting.push(en.target) }}// the elements that left the DOM unseen are let go. One not in the DOM YET is not one that left: a mount builds its rows apart// and puts them in later, and a report in between must not take their handlers (#422); it is let go when it stays out 3 slet keep = []for (el of seenRuns) {if (el.__hlSeen == null) { continue }if (el.isConnected) { el.__hlSeenOff = null keep.push(el) }else if (el.__hlSeenOff == null) { el.__hlSeenOff = Date.now() keep.push(el) }else if (mounting || Date.now() - el.__hlSeenOff < 3000) { keep.push(el) }else { seenObserver.unobserve(el) el.__hlSeen = null }}seenRuns = keepseenFlush()return null}seenFlush() {if (document.visibilityState != 'visible') { return null }let due = seenWaitingseenWaiting = []for (el of due) {let go = el.__hlSeenif (go == null || !el.isConnected) { continue }el.__hlSeen = nullseenObserver.unobserve(el)if (mounting) { heldDom[] = () => { runSeen(go) } } else { runSeen(go) }}return null}// one `on seen()` handler's run: a handler that fails is logged and does not cost the elements after it theirs (#422)runSeen(Function go) {let r = window.__hlAttempt(() => { return go({ type = 'seen'; }) })if (!r.ok) { console.error('framework: an on seen() handler failed — ' + r.error) }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, Hybrid host, Number i, Boolean 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(&m)inner = 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 = [] if (m.rootKind == 'shell') { langSite(&inner) } }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(&m) }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(&m) {if (seed.offlineNotice != null) { return null }// 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)dropped.page.instance.__hlParent = layoutHost(m)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.pagemounting = true// Build any newly opened layout levels before their page, with the standing level as host.let level = next.shelllet depth = 0while (level != null && depth < m.chain.length) { level = level.kids['^'] depth = depth + 1 }if (level != null && level.kids['^'] != null) {m.kids['^'] = instantiate(level.kids['^'], childChain(m.chain, '^'), m.rootKind, m.instance)let saved = seed.shelldepth = 0while (depth < m.chain.length) { saved = saved.kids['^'] depth = depth + 1 }saved.kids['^'] = level.kids['^']}pageArrived = truereturn instantiate(next.page, [], 'page', layoutHost(m))}// 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 (arrive)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, Hybrid host, Number i, Hybrid fill, Boolean 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, Hybrid host, Number i, String site, String name, Hybrid rows, String rk, Hybrid fill, Boolean 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(String 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(String key, String 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(Boolean 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(String name, Boolean 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(Hybrid d, Hybrid host, Number 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(Hybrid d, Hybrid host, Hybrid closeMark) {let frag = document.createDocumentFragment()let before = sidNextfillFromRoot(d, frag, 0, true)host.insertBefore(frag, closeMark)regionRehome(d, frag, host, before)return null}regionRehome(Hybrid d, Hybrid frag, Hybrid host, Number 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, Hybrid d, Number depth, Hybrid frag, Hybrid host, Number 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(Hybrid d, Hybrid host, Hybrid 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, Hybrid d, Number depth, Hybrid host, Hybrid 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(Hybrid fill, Hybrid host, Number at, Boolean 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, Hybrid fill, Number depth, Hybrid host, Number at, Boolean 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, Hybrid spec, Hybrid rows, String rowKey, Hybrid 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(Boolean open) { return document.createComment(open ? '[' : ']') }isMark(Hybrid n) { return n != null && n.nodeType == 8 && (n.data == '[' || n.data == ']' || n.data == '[hl:page' || n.data == ']hl:page') }// the nodes strictly between a region's marksbetween(Hybrid 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(Hybrid 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(Hybrid host, Hybrid 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, Boolean cr, Boolean 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 ? '[' : ']') || n.data == (open ? '[hl:page' : ']hl:page'))) { 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(Hybrid start) {let depth = 0let n = start.nextSiblingwhile (n != null) {if (isMark(n)) {if (n.data == '[' || n.data == '[hl:page') { 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, Hybrid host, Hybrid 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, Hybrid src, Hybrid dst, Number 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, Hybrid src, Hybrid dst, Number 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, Hybrid chain, Number depth, Hybrid src, Hybrid 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, Hybrid host, Hybrid nodes, Hybrid 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, Hybrid 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, Hybrid d, Number 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(Hybrid 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(Hybrid 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, Hybrid chain, Number 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(Hybrid 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, Hybrid 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(Hybrid 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(Hybrid host, Boolean cr, Number i, Number k, String text) {let t = leafNode(&host, cr, text)if (k != null) {if (host.__hlLeaves == null) { host.__hlLeaves = {} }host.__hlLeaves[k] = t}return null}leafNode(&host, Boolean cr, String 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, Boolean cr, Function readFn, &names, &rows, String rk, &reads) {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; reads = reads; 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, Number i, String site, String rowName, Function listFn, &rows, String rk, &fill, Boolean cr, &names, &reads) {let start = markAt(&host, cr, true)regionAt(&m, &host, site, &rows, rk, &fill, true, rowName, listFn, &names, &start, null, &reads)// (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, Number i, String site, Function condFn, &rows, String rk, &fill, Boolean cr, &names, &fnames, &reads) {let start = markAt(&host, cr, true)regionAt(&m, &host, site, &rows, rk, &fill, false, null, condFn, &names, &start, &fnames, &reads)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, String site, &rows, String rowKey, &fill, Boolean isFor, String rowName, Function readFn, &names, &start, &fnames, &reads) {// 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; reads = reads; 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, Hybrid host, Number i, Hybrid spec, Hybrid rows, String rk, Hybrid fill, Boolean cr, Hybrid 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] = mintedmountQueue[] = { chain = minted.chain; root = m.rootKind; }}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(Hybrid b, &m, Hybrid 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, Hybrid spec, Hybrid rows, Hybrid chain) {let bp = planOf(spec.key)if (bp == null) { return null }let args = {}for (b of spec.bindings) { if (!hasSetter(spec.key, b.name)) { 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, query }` 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 boundlet supplied = navigationReply(chain, m.rootKind)if (supplied != null) {for (k of supplied.state.keys()) { if (!args.keys().includes(k)) { args[k] = supplied.state[k] } }} else if (offline != null && offline.localRoute(location.pathname) != null && (reach == 'down' || seed.local == true || (navLate != null && navLate.local == true))) {localState = offline.mountState(spec.key, args, chain, m.rootKind, location.pathname + location.search)for (k of localState.keys()) { if (!args.keys().includes(k)) { args[k] = localState[k] } }} else if (bp.srv != null) {let sv = emit server values(spec.key, askArgs(args, args.keys()), location.pathname + location.search)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; given = {}; }}// the route the address bar names, as the server hands it to construction: `{ path, params, pattern, query }`currentRoute() {let rm = router.match(location.pathname)if (rm == null) { return null }return { path = rm.path; params = rm.params; pattern = rm.route.pattern; query = router.queryOf(location.pathname + location.search); }}// 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, Hybrid 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, Hybrid spec, Hybrid rows) {for (b of spec.bindings) {if (hasSetter(kid.key, b.name)) { giveSetter(&kid, b.name, specValue(b, &m, rows)) }else { kid.instance[b.name] = specValue(b, &m, rows) }}if (kid.pendingDerived != null) {for (name of kid.pendingDerived) { kid.instance.__derive__(kid.instance.constructor.__memberSites__[name]) }kid.pendingDerived = null}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, Hybrid spec, Hybrid els, Hybrid 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, Hybrid host, Number at = 0) {
Only the first lines are shown.
Branches
Latest commits
- 10f8a8c8Merge branch 'code-order' into mainJukebox
- 204fc828Merge branch 'day72' into mainJukebox
- 95f5faae|||PR jukebox#7 Drop needless let declarationsmre
- 33072bb5|||PR Record day72 gates and Chrome proofmre
- 95f2cd73|||PR Use typed parent methods for screen playback and local server facesmre
- 6422a020Sync media-player at 51c3818mre
- b582ba1cVendor complete Hybriel day72 plugin setmre
- 02dccbc9Merge branch 'records-1119' into mainJukebox
- a39e1c23|||PR Records: missions 013-015, reconnect fix livemre
- fc7db075Merge branch 'reconnect-retry' into mainJukebox
- ac6f4c6fL2: plain declaration for a in pickedNextmre
- 2f335086Review round 2: only an explicit queue pick drops pend (not the automatic advance); jb23 records every source changemre
- 3eb6695fReview fixes: action generation, queue pick clears pend, Previous/Next retry the decided request, typed handlersmre
- 7a53c0c2|||PR A tap lost to a dead socket plays after reconnect (mission 015)mre
- 1f0cd77bMerge branch 'records-day41' into mainJukebox
- 67be229f|||PR Records: day41 live (PR #4), mission 012, statusmre
- 0bb027daconductor: caramboleyo is the user, not owner/creatorApollo
- 04f5d9d5Merge branch 'day41' into mainJukebox
- 8ed6da45|||PR README: media-player pin df9e7dfmre
- d5d45fc3|||PR media-player df9e7df (repeat-one fix), sync pin and SOURCEmre