gitoria

jukebox

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Commit05c3578c05c3578c|||PR Keep each playing row bound to the shell song on day76mre05c3578c/plugins/web/client.hl

289.2 KB

  1. // The framework's client half — a file-class constructed ONCE in the browser by
  2. // the page's module script, with the seed the server rendered from. The
  3. // components are NOT preloaded: each mount carries the url its module is served
  4. // at and `hlLoad` fetches it when the mount happens. This file is the client
  5. // realm's entrypoint, and the page script sets that realm before constructing
  6. // it.
  7. //
  8. // Its whole job: CLAIM the DOM the server rendered for the mounted instances,
  9. // remember which elements read which member (the SITES), repaint a site when a
  10. // member is written, and turn a same-origin link into a navigation that fetches
  11. // the next route's tree and state and swaps the slot — the shell stays.
  12. import HlwView from './view.hl'
  13. import HlwRouter from './router.hl'
  14. seedText = '' // the server's seed, as JSON text (the one construction argument)
  15. coalesced = {}
  16. coalesceSerial = 0
  17. seed = null // { page: { key params state view }, shell: … | null }
  18. view = new HlwView
  19. router = null // the client's route table, from the seed
  20. plainRoutes = {} // the paths of the routes that are not pages and have no :param or * (a click on them is left to the browser)
  21. shell = null // { key, instance, view, sites, root }
  22. page = null
  23. appHead = null // the app's manifest head defaults, off the seed: what a page
  24. // member that is null falls back to (title, description, image,
  25. // favicon, and the app's own meta list)
  26. bodyAttrs = [] // root body attributes; initialized before boot() claims the page
  27. slotEl = null // the shell element whose children are the route component
  28. // WHERE IN IT (ticket #81's finding): the shell's slot may stand beside other elements
  29. // of the shell — `body { header { … } slot }` — and the page's nodes are then not all
  30. // of slotEl's children. `slotAt` is the index of the page's first element among them,
  31. // and `slotStart` the open mark of the region the page is (a page in a shell stands
  32. // between two marks like every region), so the page is claimed from the right element
  33. // and a navigation replaces what stands between the marks and nothing of the shell's.
  34. slotAt = 0
  35. rowKidBound = {} // component key | for site → the host members its row children are bound to
  36. reseatGen = 0 // (#71) the number of the running reseat: a node a nested changed row shares with its outer one is read once
  37. kidMoved = 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 child
  38. rowDropSpecs = {} // component key | for site → own child specs in the row body
  39. rowKidless = {} // component key | for site → true when its row body composes no child
  40. slotStart = null
  41. // THE PAGES LEFT BY A NAVIGATION, KEPT FOR BACK AND FORWARD (W147, D5 on hybriel#206). A page replaced by another under
  42. // the same chain of levels is not thrown away: its DOM nodes (detached), its mount record and its index entries wait here,
  43. // keyed by the history entry it belonged to (`hid`, written into history.state). Back or forward to such an entry puts the
  44. // page back with its state and scroll; any other entry is a miss and builds the page as before. `keptMax` is five: a page
  45. // holds its whole DOM and live instances, and five is the few pages one walks back through, without a long session
  46. // growing without end; the oldest one left goes first.
  47. kept = []
  48. keptMax = 5
  49. // PERSISTENT PAGES (hybriel#411): a page that declares `persistent = true` is kept by its ADDRESS (pathname + search), not by
  50. // the history entry, with no count cap: a link, navigate(), Back and Forward to that address attach the same DOM and
  51. // instances again, scrolled where they were left, and ask the server for nothing. While it is detached it hears no push: the
  52. // pushes its components listen to are queued on its record (in order, `persistBytes` at most, the bound of the server's
  53. // pushKeptBytes) and run before it is shown. Past the bound, after a resync, or past `persistFor` seconds (an optional
  54. // member), the copy is dropped and the page is built as any page. A sweep of the expired ones runs at each navigation.
  55. persistBytes = 1048576
  56. keptUid = 0
  57. hidNext = 1
  58. shownHid = null // the history entry the page on the screen belongs to
  59. shownPath = null
  60. scrollNow = 0
  61. regionTable = {} // NAMED REGIONS (`slot { name = 'side' … }`) the shell's levels hold: name → { host start at desc kind }
  62. detachedSlot = null // the slot element a shell region's rebuild took out of the DOM (see paint)
  63. socket = null // the websocket carrier, while it is open
  64. static connectWithin = 5000 // handshake deadline in ms, independent of the OPEN socket's ping settings
  65. static connectCap = 60000 // the handshake deadline never grows past this (ms)
  66. connectLimit = 5000 // THE CURRENT UPGRADE's deadline: connectWithin, doubled by every upgrade that expired in a row, reset when a socket opens (#403)
  67. connectingAt = 0 // monotonic start of the current upgrade
  68. connectDue = null // the current upgrade's deadline timer
  69. socketOpened = false // it has opened (a socket that closes without opening is a failed reconnect)
  70. retryMs = 500 // the wait before the next reconnect: doubles per failure up to 4 s, reset on open
  71. hasSession = true // the server said at the last hello whether this tab has a session (W136, sessionKnown)
  72. sessionChannel = null // the BroadcastChannel to the other tabs of this app in this browser
  73. sessionCookieName = null // the app's session cookie name and Domain, as the server said at the hello
  74. sessionCookieDomain = null
  75. newsWaiting = false // news of a login came while the socket was still connecting
  76. sessionHello = false // this socket has reported whether its upgrade carried a session
  77. cookieWatch = null // the cookieStore listener for a login in a tab of another origin of the same site is bound
  78. emitPosts = 0 // the offline emits' fallback POSTs in flight (crossing())
  79. emitGateN = 0 // how many emits wait in emitGate
  80. emitGate = {} // (keyed by number) resolvers of the emits waiting for the one fallback POST in flight to settle (crossing(): they follow it, in order)
  81. 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()
  82. 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)
  83. probing = false // the probe of `/__hl/up` runs while a reconnect waits (ticket #153, probe())
  84. probeFailed = false // a probe found no server since the last socket opened
  85. reach = 'connecting' // WHETHER THE SERVER ANSWERS (setReach): 'connecting' until the first socket opens, then 'up' or 'down'
  86. // THE TAB ACROSS ITS SOCKETS (ticket #143): this document's id, the `n` of the last push it
  87. // dispatched, and whether a socket opened before — all three ride every `hello`, and the
  88. // server answers a reopened socket with what it missed
  89. tabId = null
  90. lastSeq = 0
  91. appliedN = {} // W117: 'm<mount key>.<member>' → the highest sync `n` applied to it (a snapshot older than that is not laid over)
  92. gapHeld = {} // W117: 'n<n>' → a push above a gap, held until the replay fills it
  93. gapTimer = null
  94. syncN = null // the `n` of the numbered `sync` being applied (applySync reads it)
  95. everOpened = false
  96. gotFrame = false // the current socket has been answered at least once (W123: the backoff resets here, not on open)
  97. shutStreak = 0 // sockets in a row the server shut right after the handshake, with no frame
  98. warnedOrigin = false // the cross-origin warning is logged once
  99. navigating = false // a navigation is running (show); navNext is the one asked for meanwhile
  100. navNext = null
  101. navTurn = 0 // changes on every requested navigation, including Back/Forward
  102. navLate = null // a timed crossing and the local instance it may refresh
  103. navResync = null // the same answer supplies newly minted children during its patch
  104. navFlight = null // the framework page crossing, cancellable when a newer route wins
  105. busyN = 0 // #434: navigations and emit answers open now; <html data-hl-busy> stands while it is above 0
  106. emitOrigin = null // #435: the button whose handler is running (set for the run of one event; its emits mark it)
  107. navWake = null // a failed page answer waits for the next carrier, or a newer route
  108. lateFrames = [] // the pushes a page answer carries (`ack.late`, hybriel#410): applied once the page stands, in order
  109. navNextKeep = false // the navigation asked for meanwhile was a replace (goTo(path, true)): its page may stay
  110. pinging = false // the ping interval is started once, with the first socket
  111. pongDue = null // the timer that takes the socket for dead when its pong is late
  112. srvAt = null // the SERVER's clock as last heard (the hello's clock frame, a pong), in the server's own ms…
  113. srvMono = 0 // …and this page's monotonic clock at that moment: only DURATIONS ever cross (see `horizon`)
  114. nextId = 0 // the pairing id an emit's ack comes back on
  115. pending = {} // 'k<i>' → the resolver waiting for that ack
  116. // AN ANSWER THAT ARRIVES BEFORE ITS PAGE IS MOUNTED (ticket #80). A component's root
  117. // runs while `instantiate` constructs it, and an `emit server` there goes out at once
  118. // (over REST: the socket opens after boot). What the face raised for this tab comes
  119. // back in the ack, before `page` — or, on a navigation, the NEXT page — is the mount
  120. // that holds the listener; delivered then, it reached the old mounts or none and was
  121. // lost. While a mount is being built the frames wait here, and go out in arrival
  122. // order once it stands.
  123. mounting = false
  124. targetRegs = [] // the handlers `on window.x()` / `on viewport.x()` / `on document.x()` registered: { id, target, event, fn } (see registerTargets)
  125. targetHooks = {} // 'window.resize' -> true: the one DOM listener per target and event, installed at the first registration
  126. heldPrompt = null // a beforeinstallprompt nobody listened to yet: handed to the first component that does, once
  127. seenObserver = null // the page's one IntersectionObserver for `on seen()` (#412), made at the first element
  128. seenRuns = [] // the elements it still watches
  129. seenWaiting = [] // seen while the tab was hidden: they fire when it shows
  130. held = []
  131. heldDom = [] // DOM events received while claim still reads the rendered state (#399)
  132. forwarding = 0 // upward() is dispatching at the levels above a sender: their own listeners stay silent
  133. levelMarks = [] // 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 marks
  134. pushRuns = null // WeakMap: instance -> one-element array holding its latest delivery Promise
  135. delivering = 0 // outward() is dispatching a frame at the mounts: a page's forwarder (wireUp) stays silent then
  136. strict = false // the gates' client: a repaint that finds a stale site throws (staleSite)
  137. paintInput = null // focused control protected by this same-page replace patch only (#328)
  138. 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)
  139. painting = 0 // repaints running: 0 when the page stands still (the gates wait for it)
  140. mountQueue = [] // kids minted after the page stood (a row added): their `on mount()` runs once the patch that built them is painted (#236)
  141. turning = false // a patch is running (patch): the ones asked for meanwhile wait in patchQueue
  142. patchQueue = []
  143. scrollPending = [] // #445 writes to apply once the patch has placed its rows
  144. followers = [] // the elements that carry `follow` (follow): scroll containers kept at their end
  145. followSeen = null // the ResizeObserver that keeps them there when something inside grows after a patch
  146. placing = 0 // pages being placed (showOne): no patch runs meanwhile; counted, so two overlapping ones and a turn that ends meanwhile cannot leave the queue stopped
  147. sidNext = 0 // every site's own number, so a repaint can tell one that has left
  148. dropGen = 0 // counts the drops of sites (dropSitesIn): a repaint's list is checked again after one
  149. pendingDrops = [] // ranges that left holding a host's fill: that host's sites and children in them
  150. // go in settle(), once every mount on the walk has been written back
  151. pendingFills = [] // fills a region rebuild anchored but could not build in place:
  152. // the host is named by address and re-entered in settle() below
  153. // ownerId -> { key, chain, root } of the mount that owns that instance, and the reverse
  154. // (address -> ownerId, the check that an entry still names a live mount). A MOUNT RECORD
  155. // IS A VALUE, so finding a mount by walking the tree with `let kid = m.kids[k]` deep-copies
  156. // every subtree on every handler event; the index is filled where a mount is made
  157. // (`instantiateNode`, `mintFrom`) and emptied where one is replaced or removed
  158. // (`purgeMounts`), so a lookup is O(1) at any depth.
  159. mountIndex = {}
  160. mountAddr = {}
  161. lateJobs = [] // late patches (#98, #99): see latePatch
  162. lateDue = false
  163. domListener = null // the DOM listener just dispatched {event, chain, root, wrote}: see handlerWaiting (W185)
  164. // THE EVENTS A REFERENCE OVERWROTE ON THE COMPOSITION'S ROOT, while the walk is inside
  165. // that composition and has not yet reached an element. A composed child's View may be a
  166. // bare reference to another component (routger's dialog-form.hl is one), so the element
  167. // that FINALLY stands as the child's root can be any number of references deeper — this
  168. // rides down through them and is spent on the first elements the walk claims or builds,
  169. // which are exactly those roots.
  170. rootOverwrites = null
  171. // IS THE PAGE ON THE DOCUMENT? A shell decides per request whether its render contains
  172. // a `slot` (COMPONENTS §7, "THE PARENT IS THE GATE"): `if (loggedIn) { main { slot } }`
  173. // standing false renders no page at all, and there is then nothing to claim. False here
  174. // means there IS no page: the server did not construct it and the seed carries none
  175. // (creator, 2026-08-26 — the parent is the gate). It is asked for and constructed when
  176. // the region holding the slot turns true, and dropped again when it turns false.
  177. pageShown = false
  178. dropped = null // the page of a region that closed (snapLeft's record): put back when the region opens again, never asked for
  179. restored = false
  180. pageArrived = false // a region's rebuild constructed the page: its held frames go out after it
  181. // AN EMIT IN FLIGHT OUTLIVES ITS SOCKET (ticket #107). Every emit that went out on the
  182. // socket is here until its ack, as the frame it was: a socket that closes under it
  183. // hands it on to the POST fallback or the next socket, with the same `q`, and the
  184. // server's exactly-once path answers the repeat instead of running the face again.
  185. // `post` is true while the POST fallback carries it, `lost` once a POST failed.
  186. inflight = {} // 'k<i>' → { text; event; post; lost; }
  187. // A PAGE BEING LEFT starts nothing. Firefox closes the page's socket the moment a
  188. // document navigation starts, right after `beforeunload` and long before `pagehide`;
  189. // a reconnect or a POST made then, and an answer that loads a document, would cancel
  190. // the navigation the user started. `beforeunload` is only a maybe (a download, a
  191. // navigation the server answers with 204), so after it the page takes itself for
  192. // staying once `stayMs` have passed and it is still here.
  193. leaving = false
  194. stayTimer = null
  195. static stayMs = 3000
  196. retryTimer = null
  197. pendingNotices = new Map()
  198. notifyPermissionBound = false
  199. onlineBound = false // the online/offline listeners are on the window (syncOnline)
  200. // ---- THE PACKAGE'S BROWSER SURFACE: what `import { … } from 'hl:web'` binds ------
  201. //
  202. // A file's STATICS are what a braced import may take (the language's one rule for
  203. // `import { db } from './store.hl'`, and the same rule across a package's url),
  204. // so everything this half offers an app's component is declared here and nowhere
  205. // else. A static belongs to the CLASS, which is why these two reach each other
  206. // and why they are the SAME pair for every component module the page imports —
  207. // the browser loads this file once.
  208. //
  209. // `live` IS THE PAGE'S ONE CLIENT, written by the root below. The statics cannot
  210. // see an instance (they are evaluated at file load, before there is one), and a
  211. // static that is a FUNCTION does not need to: its body runs at the CALL, long
  212. // after the root has put the constructed client here.
  213. static live = { client = null }
  214. // Features register during module evaluation, before this page constructs its Client.
  215. static features = {}
  216. static registerFeature = (String name, Function feature) => { if (feature != null) { features[name] = feature } return features[name] }
  217. offline = null
  218. uploads = null
  219. // PROGRAMMATIC NAVIGATION — the same act a click on a same-origin `<a>` performs,
  220. // asked for by code instead of by a pointer: a new history entry, then the next
  221. // route's tree and state over the boundary and into the shell's slot. A handler
  222. // that has just been told an id and must go to that thing's page has no link to
  223. // click, and this is what it calls instead. Everything about what a navigation IS
  224. // stays in `goTo` below; this is only the way in from outside the file.
  225. static navigate = (String path, Boolean replace = false) => { return live.client.goTo(path, replace) }
  226. // A NOTIFICATION, now or at a set time (COMPONENTS §10, ticket #95). `at` is epoch
  227. // milliseconds. The browser is asked for permission the first time. It is shown by
  228. // the service worker when the app has one (so an installed app shows it as the app),
  229. // else by the page. A notification AT A SET TIME is a timer of this page: it fires
  230. // while the page is open — a browser offers no way to wake a closed app at a time
  231. // without a server push, and this does not pretend otherwise.
  232. static notify = (String title, Hybrid options) => { return live.client.showNotice(title, options) }
  233. static cancelNotify = (String tag) => { return live.client.cancelNotice(tag) }
  234. static notifyAt = (Number at, String title, Hybrid options) => { return live.client.noticeAt(at, title, options) }
  235. // …or after `ms` milliseconds
  236. static notifyIn = (Number ms, String title, Hybrid options) => { return live.client.noticeIn(ms, title, options) }
  237. // FORGET WHAT THIS BROWSER KEPT OFFLINE (ticket #125): the kept state, the queue and the
  238. // worker's kept documents. hl:web does it itself when the session's user changes (a log-out
  239. // included) at the next page it is told about; an app that logs out in place calls this.
  240. // WEB PUSH (ticket #173): ask for permission, subscribe with the app's `pushKey`, and answer the
  241. // subscription as `{ endpoint, expirationTime, keys = { p256dh, auth } }` — or null when the browser
  242. // has no push, the key is not set or permission is refused. The app hands it on:
  243. // `let s = subscribePush() emit server savePush(s)`.
  244. static subscribePush = () => { return live.client.pushSubscribe() }
  245. // …and the server's half (hl:web's server.hl): a component that imports `sendPush` from 'hl:web' binds this
  246. // name in the browser, so the module loads; the call belongs in an `on server` handler, and here it only says so.
  247. 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 }
  248. static forgetOffline = () => { if (live.client.offline != null) { return live.client.offline.forgetOffline() } live.client.dropKept() return null }
  249. // TAKE BACK A QUEUED EMIT (W215): `import { takeBack } from 'hl:web'`, `took = takeBack(r.q)` with the `q` of a `__hlQueue` row.
  250. // true: it was still waiting, is never sent, and its caller got null. false: unknown, taken back before, or already sent.
  251. static takeBack = (String q) => { return live.client.takeBack(q) }
  252. // ---- boot: construct the instances the server rendered, claim their DOM ----------
  253. // THE PAGE'S CLIENT, PUBLISHED TO THE FILE'S OWN CLASS, before anything else the
  254. // root does: `boot()` below constructs the components, and a component's module
  255. // may reach `navigate` from the moment it is loaded.
  256. parentEdges = {}
  257. parentOwners = {}
  258. Client.live.client = this
  259. // A VIEW EXPRESSION in a module's code is evaluated by view.hl's one `evalExpr`, so the
  260. // language's own operators answer in the browser as they do on the server
  261. view.parentOf = (Hybrid inst) => { return window.__hlP.H(inst) }
  262. window.__hlX = (Hybrid x, Hybrid inst, Hybrid rows) => { return view.evalExpr(&x, &inst, &rows) }
  263. seed = resolveValues(JSON.parse(seedText))
  264. if (seed.offline != null && Client.features.offline != null) { feature = Client.features.offline offline = new feature(client = this) }
  265. router = new HlwRouter(routes = seed.routes)
  266. for (r of seed.routes) {
  267. if (r.component == null && r.pattern.indexOf(':') < 0 && r.pattern.indexOf('*') < 0) { plainRoutes[r.pattern] = true }
  268. }
  269. // A `beforeinstallprompt` can fire before any component stands: this listener (installed at module load) keeps the event, and the first
  270. // component with `on window.beforeinstallprompt(e)` gets it when it mounts (registerTargets). Nothing is prevented here.
  271. targetHooks['window.beforeinstallprompt'] = true
  272. window.addEventListener('beforeinstallprompt', (Hybrid ev) => {
  273. let n = dispatchTarget('window', 'beforeinstallprompt', ev)
  274. if (n == 0) { heldPrompt = ev }
  275. })
  276. boot()
  277. // THE VALUES TABLE (#180): the server writes a large value that stands in several places once,
  278. // in `seed.values[id]`, and a place holds `{ "$hlv": id }`. Every reference is resolved HERE,
  279. // as the seed is read (a navigation's answer too, in showOne) and each place gets a copy of its
  280. // own, built fresh: a child that changes its `items` does not change the page's `home`.
  281. resolveValues(&s) {
  282. if (s == null || s.values == null) { return s }
  283. // (the table is read in place and the answer is the caller's own temporary: `let table = s.values` copied the whole table, W110)
  284. if (s.page != null) { s.page = unshare(&s.values, &s.page) }
  285. if (s.shell != null) { s.shell = unshare(&s.values, &s.shell) }
  286. s.values = null
  287. return s
  288. }
  289. unshare(&table, &v) {
  290. if (hlTypeName(&v) != 'Hybrid') { return v }
  291. if (v['$hlv'] != null) { return unshare(&table, &table[v['$hlv']]) }
  292. let out = null
  293. if (Array.isArray(&v)) {
  294. out = []
  295. for (x of v) { out.push(unshare(&table, &x)) }
  296. } else { out = {} }
  297. for (k of v.keys()) { out[k] = unshare(&table, &v[k]) }
  298. return out
  299. }
  300. boot() {
  301. mounting = true
  302. strict = seed.strict == true
  303. if (seed.shell != null) {
  304. shell = instantiate(seed.shell, [], 'shell')
  305. shell.isShell = true
  306. // (the BODY ELEMENT, nothing to do with `rootKind` below — a mount's `rootKind`
  307. // says which of the two roots it hangs from, 'page' or 'shell'. This field held
  308. // the DOM node under the same name until 2026-09-14, and the shell's address
  309. // therefore read as an element: every lift and every fill re-entry from a
  310. // composition IN THE SHELL resolved against the page instead, so a composed
  311. // control there wrote nothing — creator, W15.)
  312. shell.root = document.body
  313. // the body node's children are claimed against document.body, so the body
  314. // element takes the node itself here: a region hosted directly on it (an `if`
  315. // at the shell's root) rebuilds from it (measured 2026-09-13: a lone child
  316. // under `body` stayed on screen after its condition turned false)
  317. claim(&shell, document.body)
  318. }
  319. // The donor seed is used only to locate the slot during the shell's claim (#350).
  320. if (seed.offlineNotice != null) { offlineNotice() return null }
  321. page = seed.page != null ? instantiate(seed.page, [], 'page', layoutHost(shell)) : null
  322. // no shell: the page IS the document's body content
  323. if (shell == null) { slotEl = document.body }
  324. // THE SHELL RENDERED NO SLOT — its region stood false for this request, so the
  325. // document carries no page. Claiming one anyway walked the page's tree against the
  326. // SHELL's own elements and silently attached the page's nodes to them ("claim: no
  327. // element for … under …" as soon as the two shapes differ), and the page never
  328. // appeared when the region later turned true. It waits instead.
  329. if (slotEl != null && page != null) {
  330. slotEl.__hlCur = slotStart
  331. claim(&page, slotEl, slotAt)
  332. pageShown = true
  333. }
  334. // the shell's named regions take their content: the filling level's, or their own default
  335. if (shell != null) { placeRegions(true) }
  336. // the head members are sites of this mount from here on. They are NOT painted
  337. // now: the server's `document()` already wrote them into this document, and a
  338. // write to one of them repaints it the way every other member's write does.
  339. appHead = seed.head
  340. if (page != null) { headSites(&page) }
  341. release()
  342. sweepAll()
  343. listen()
  344. syncOnline()
  345. syncNotifyPermission()
  346. syncReach()
  347. if (offline != null) { offline.standIn() }
  348. if (offline != null) { offline.offlineBoot() }
  349. connect()
  350. }
  351. // A FRAMEWORK NOTICE IN A KEPT SHELL (#350). No donor page is instantiated or
  352. // claimed, and no offline state is started for the unavailable URL.
  353. // The carrier follows reachability for the shell without mounting a page (#381).
  354. // The worker has already replaced the page HTML, so the first paint is the notice.
  355. offlineNotice() {
  356. seed.page = null
  357. document.title = seed.head != null && seed.head.title != null ? seed.head.title : ''
  358. // R67 / #423: links use the normal navigation path; the notice itself
  359. // still starts no offline store and mounts no donor page (#381).
  360. appHead = seed.head
  361. listen()
  362. setReach('down')
  363. release()
  364. syncOnline()
  365. syncNotifyPermission()
  366. connect()
  367. return null
  368. }
  369. // THE NEXT PAGE INTO THE SLOT, and nothing else of the shell's: the slot's element may
  370. // hold the shell's own elements beside the page (`body { header { … } slot }`), which
  371. // emptying it took with the old page. The new page is built where the old one stood.
  372. placePage(&m) {
  373. if (!standing(slotEl, slotStart)) {
  374. // the page is all the slot's element holds: empty it, as it always was
  375. slotEl.replaceChildren()
  376. create(&m, slotEl)
  377. return null
  378. }
  379. // the page's own nodes go; the readable form's line breaks the server wrote between the marks
  380. // (whitespace text no site, leaf or walk owns) stay, so a swap touches nothing else of the container
  381. for (n of between(slotStart)) { if (!formatting(n)) { n.remove() } }
  382. let frag = document.createDocumentFragment()
  383. let before = sidNext
  384. create(&m, frag)
  385. slotEl.insertBefore(frag, slotStart.__hlEnd)
  386. // the sites the walk registered on the fragment (a region at the page's root, a composed
  387. // child's) belong to the slot's element it landed in (#191: they stayed on the empty fragment,
  388. // and the first click on a child's button after a navigation did nothing)
  389. rehome(&m, frag, slotEl, before)
  390. return null
  391. }
  392. // a whitespace-only text node nothing of the page owns: no site, and not a leaf the host keeps
  393. formatting(Hybrid n) {
  394. if (n.nodeType != 3 || n.data.trim() != '' || n.__hlSid != null) { return false }
  395. if (n.parentNode.__hlLeaves != null) {
  396. for (k of n.parentNode.__hlLeaves.keys()) { if (n.parentNode.__hlLeaves[k] == n) { return false } }
  397. }
  398. return true
  399. }
  400. // the frames that waited for the mounts (above), now that they stand
  401. release() {
  402. mounting = false
  403. // App writes must wait too: claim still reads the server-rendered list (#399).
  404. events = heldDom
  405. heldDom = []
  406. // ONE FAILING HANDLER DOES NOT COST THE OTHERS THEIR RUN (#422): each is attempted, a failure is logged
  407. for (dispatch of events) {
  408. let r = window.__hlAttempt(() => { return dispatch() })
  409. if (!r.ok) { console.error('framework: a handler held while mounting failed — ' + r.error) }
  410. }
  411. let frames = held
  412. held = []
  413. for (f of frames) { outward(f) }
  414. return null
  415. }
  416. // a mount's instance: the module LOADED (hlLoad — the loader primitive, which
  417. // on this target is the dynamic import of the url the server compiled the
  418. // component to), the class constructed, then the server's state laid over it.
  419. // The import is the browser's own cache: a second mount of the same component
  420. // fetches nothing.
  421. // The route's params and the server's state are the construction's NAMED
  422. // ARGUMENTS, pinned before the root runs — so a member the server evaluated
  423. // (a seeded one, declared without its initializer in this realm's projection)
  424. // is already there when a later line reads it, and a client-evaluable
  425. // initializer keeps the server's value instead of recomputing it.
  426. // A COMPONENT'S BLUEPRINT (its View tree, whether it takes the route, the members the server computes) COMES WITH ITS
  427. // MODULE (W195): the module registers it under `__hlB[key]` when it runs, so a page carries the plans of the
  428. // components it uses and no others, and the browser's cache keeps them. A mount has its module loaded before its tree is
  429. // read; a child the browser mints itself has its module fetched first (`planOf`).
  430. blueprintOf(String key) {
  431. if (window.__hlB == null) { return null }
  432. return window.__hlB[key]
  433. }
  434. // A browser key IS the module path without its leading slash (the server's
  435. // graphModuleKey). No disk path or separate URL mapping reaches the client.
  436. // does this component declare a setter for the member? (its blueprint names them — hybriel#301): a parameter the host binds
  437. // into such a member goes through the setter and is not a construction argument or a plain write here
  438. hasSetter(String key, String name) {
  439. let bp = blueprintOf(key)
  440. return bp != null && bp.setters != null && bp.setters.includes(name)
  441. }
  442. // A PARAMETER THE HOST BINDS INTO A CHILD'S SETTER (hybriel#301) is written through the setter, once for each change of the
  443. // host's value. The member may never hold the value (the setter decides), so the last value given is kept on the mount record
  444. // and compared with. Answers the member names to repaint — the parameter and what the setter writes — or null when this is
  445. // the value already given.
  446. giveSetter(&kid, String name, Hybrid | String | Number | Boolean | Bytes | Function v) {
  447. if (kid.given == null) { kid.given = {} }
  448. if (kid.given.keys().includes(name)) {
  449. let last = kid.given[name]
  450. if (hlSame(&last, &v)) { return null }
  451. }
  452. kid.given[name] = v
  453. kid.instance[name] = v
  454. let names = [name]
  455. let wrote = compiledEntry(kid.key, 'mt', name)
  456. if (wrote != null) { for (w of wrote) { if (!names.includes(w)) { names.push(w) } } }
  457. return names
  458. }
  459. moduleUrlOf(String key) {
  460. return '/' + key + seed.build
  461. }
  462. // the blueprint of a component whose module may not be loaded yet: the module is imported (once, the browser's module map)
  463. planOf(String key) {
  464. if (blueprintOf(key) == null) { window.__hlP.L(moduleUrlOf(key)) }
  465. return blueprintOf(key)
  466. }
  467. treeOf(String key) {
  468. let bp = blueprintOf(key)
  469. // the table covers every component the page can reach, so this is a torn seed
  470. // and not a missing feature — say so loudly and paint nothing for that mount
  471. if (bp == null) { console.error('framework: the module carries no blueprint for ' + key)
  472. return [] }
  473. return bp.view
  474. }
  475. // `chain` and `root` are the mount's ADDRESS: the kid keys from the page (or the
  476. // shell) down to it. A mount record is a value, so a site cannot hold the mount that
  477. // owns its fill — it holds this address, and `fillAt` re-enters the mount by
  478. // reference from the root when the fill has to be rebuilt (see settle below).
  479. instantiate(Hybrid m, Hybrid chain, String root, Hybrid host = null) {
  480. purgeMounts(chain, root)
  481. return instantiateNode(m, chain, root, host)
  482. }
  483. // The innermost layout owns the page in its slot; the top shell itself has no host.
  484. layoutHost(Hybrid m) {
  485. let at = m
  486. if (at == null) { return null }
  487. while (at.kids['^'] != null) { at = at.kids['^'] }
  488. return at.instance
  489. }
  490. // a mount made at (chain, root) replaces whatever was there: forget it and everything under it
  491. purgeMounts(Hybrid chain, String root) {
  492. let base = addressOf(chain, root)
  493. let sep = chain.length == 0 ? '' : '/'
  494. let gone = []
  495. for (a of mountAddr.keys()) {
  496. if (a == base || a.startsWith(base + sep)) { gone.push(a) }
  497. }
  498. for (a of gone) {
  499. unparent(mountAddr[a])
  500. delete mountIndex['' + mountAddr[a]]
  501. delete mountAddr[a]
  502. }
  503. return null
  504. }
  505. // Borrow the chain list read-only: copying every nested address at the call dominated bulk disposal.
  506. // the same for many addresses in ONE scan of the index (`keys()` sorts the names: a purge per dropped child sorted
  507. // them per child, ~145 ms at 800 rows): an address goes when it is one of the bases or stands under one
  508. purgeMany(&chains, String root) {
  509. if (chains.length == 0) { return null }
  510. let bases = {}
  511. for (c of chains) { bases[addressOf(c, root)] = true }
  512. let gone = []
  513. // keys() orders descendants together. Reuse a confirmed purged base for the
  514. // following descendants instead of slicing every prefix of every address.
  515. // The full prefix test remains the fallback, including for another root.
  516. let previous = ''
  517. for (a of mountAddr.keys()) {
  518. let hit = previous != '' && (a == previous || a.startsWith(previous + '/'))
  519. if (!hit && bases[a] == true) { hit = true previous = a }
  520. let at = hit ? -1 : a.indexOf('/')
  521. while (!hit && at >= 0) {
  522. prefix = a.slice(0, at)
  523. if (bases[prefix] == true) { hit = true previous = prefix }
  524. at = a.indexOf('/', at + 1)
  525. }
  526. if (hit) { gone.push(a) }
  527. }
  528. for (a of gone) {
  529. unparent(mountAddr[a])
  530. delete mountIndex['' + mountAddr[a]]
  531. delete mountAddr[a]
  532. }
  533. return null
  534. }
  535. registerMount(Hybrid inst, String key, Hybrid chain, String root) {
  536. let addr = addressOf(chain, root)
  537. if (mountAddr[addr] != null) { purgeMounts(chain, root) }
  538. let id = inst.__hlOwnerId
  539. if (id == null) { return null }
  540. mountIndex['' + id] = { key = key; chain = chain; root = root; }
  541. mountAddr[addr] = id
  542. parentEdge(inst, key)
  543. window.__hlP.M(inst, window.__hlC[key].mt, (String name) => { methodReturned(id, name) })
  544. if (root == 'page' && chain.length == 0) { wireUp(inst, key, levelCount() + 1) }
  545. if (root == 'shell' && chain.length > 0 && chain[chain.length - 1] == '^') { wireUp(inst, key, chain.length) }
  546. return null
  547. }
  548. // A PAGE'S EMIT REACHES ITS PARENT SHELL'S `on` (ticket #193). The levels stand in the
  549. // browser, so the page is its own instance and `emit shellSession(x)` in its View finds
  550. // no handler on it: the handler is the shell's. Every event the shell declares gets a
  551. // listener on the PAGE INSTANCE's own bus (the language's instance-scoped handler, the one
  552. // `on page.ev` registers, which every dispatch at that instance fires last) that hands the
  553. // emit to the shell's instance through the dispatch `outward` uses (`hlEmitArgs`) and
  554. // repaints what the shell's handler wrote. Server cost: none, nothing leaves the browser.
  555. wireUp(Hybrid inst, String key, Number depth) {
  556. if (seed.shell == null || window.__hlC == null) { return null }
  557. if (window.__hlC[key] == null || window.__hlC[key].on == null) { return null }
  558. // every event any level above this mount declares (a level's table is its own compiled `ev`)
  559. let seen = {}
  560. let at = seed.shell
  561. let i = 0
  562. while (at != null && i < depth) {
  563. let tbl = window.__hlC[at.key]
  564. if (tbl != null && tbl.ev != null) {
  565. for (ev of tbl.ev.keys()) {
  566. if (seen[ev] == null) { seen[ev] = true wireEvent(&inst, key, ev, depth) }
  567. }
  568. }
  569. at = at.kids['^']
  570. i = i + 1
  571. }
  572. return null
  573. }
  574. // how many parent levels stand above the page: the shell and every '^' kid below it
  575. levelCount() {
  576. let n = 0
  577. let at = shell
  578. while (at != null) { n = n + 1 at = at.kids['^'] }
  579. return n
  580. }
  581. wireEvent(&inst, String key, String ev, Number depth) {
  582. 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) })
  583. return null
  584. }
  585. // The emit goes to the `depth` levels above its sender, nearest first, each level's handlers
  586. // once. `forwarding` keeps the dispatch AT a level (the levels' own listeners) silent.
  587. upward(String ev, Hybrid args, Number depth) {
  588. // a frame the server pushed reaches the shell on its own (outward), not through the page
  589. if (shell == null || delivering > 0 || forwarding > 0) { return null }
  590. let payload = args
  591. while (payload.length > 0 && payload[payload.length - 1] == null) { payload = payload.slice(0, payload.length - 1) }
  592. let lv = []
  593. let at = shell
  594. while (at != null && lv.length < depth) { lv.push(at) at = at.kids['^'] }
  595. forwarding = forwarding + 1
  596. let j = lv.length - 1
  597. while (j >= 0) {
  598. let m = lv[j]
  599. let tbl = window.__hlC[m.key]
  600. if (tbl != null && tbl.ev != null && tbl.ev[ev] != null) {
  601. let inst = m.instance
  602. hlEmitArgs(&inst, ev, payload)
  603. patch(m.chain, m.rootKind, eventWrites(m.key, ev), [])
  604. }
  605. j = j - 1
  606. }
  607. forwarding = forwarding - 1
  608. return null
  609. }
  610. // `host` is the instance whose View placed this component: the live host instance, handed to the
  611. // loader as the builder, which is what `$parent` reads (hybriel#63, #361). A page or
  612. // layout uses its wrapping layout; only a top shell or a standalone page has none.
  613. instantiateNode(Hybrid m, Hybrid chain, String root, Hybrid host, Hybrid given) {
  614. let args = {}
  615. // a member the seed left out (`m.skipped`) is the server's: given as null so the browser never runs its initializer
  616. // (it may call a package with no client code, `readFile`); the first value that arrives replaces it
  617. if (m.skipped != null) { for (k of m.skipped) { args[k] = null } }
  618. for (k of m.state.keys()) { args[k] = m.state[k] }
  619. for (k of m.params.keys()) { args[k] = m.params[k] }
  620. // THE PARAMS THE HOST BINDS ARE NOT IN THE SEED (hybriel#276; `m.bound`): `given` holds what the host's binding reads now;
  621. // a name it cannot give yet (a binding inside a `for` row, which the row's claim binds) is null, never its initializer
  622. if (m.bound != null) {
  623. // (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)
  624. for (k of m.bound) { if (!hasSetter(m.key, k)) { args[k] = null } }
  625. if (given != null) { for (k of given.keys()) { if (!hasSetter(m.key, k)) { args[k] = given[k] } } }
  626. }
  627. // #413: the server already evaluated these members and found them equal to a bound argument.
  628. // Copy that argument into the construction pins; this does not re-run an initializer or create a live alias.
  629. if (m.copies != null) { for (name of m.copies.keys()) { args[name] = args[m.copies[name]] } }
  630. // A row's bindings arrive during claim, after this mirror is built (#307).
  631. // Pin omitted members now; bound kids derive in bindFrom, before their View is walked.
  632. pendingDerived = m.bound != null && m.bound.length > 0 ? m.derived : null
  633. if (m.derived != null) { for (name of m.derived) { args[name] = null } }
  634. blueprint = planOf(m.key)
  635. if (blueprint != null && blueprint.styleHandles != null) { args.Style = blueprint.styleHandles }
  636. let inst = hlLoad(moduleUrlOf(m.key), args, host)
  637. if (m.derived != null && pendingDerived == null) {
  638. for (name of m.derived) { inst.__derive__(inst.constructor.__memberSites__[name]) }
  639. }
  640. // THE TREE COMES FROM THE TABLE, by this mount's key: a View belongs to the
  641. // COMPONENT, and the seed carries one copy of it however many mounts share it.
  642. inputs = m.params.keys()
  643. if (m.bound != null) { for (name of m.bound) { inputs.push(name) } }
  644. let out = { inputs = inputs; 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 = {}; }
  645. if (root == 'shell' && (chain.length == 0 || chain[chain.length - 1] == '^')) { langSite(&out) }
  646. registerMount(inst, m.key, chain, root)
  647. // THE MIRROR: the components this one composes are instances here too, exactly
  648. // as the server stacked them — one per component node, constructed with the
  649. // bindings the server evaluated; a binding to a host MEMBER is remembered, so a
  650. // host write reaches the child's member and repaints the child's sites
  651. // the edges first: a kid's bound params are read off this instance while the kid is built, top down
  652. bindKids(&out, out.view)
  653. for (k of m.kids.keys()) {
  654. let given = null
  655. if (m.kids[k].bound != null) {
  656. given = {}
  657. for (b of out.bindings) { if (b.kid == k && m.kids[k].bound.includes(b.target)) { given[b.target] = bindingValue(b, &out) } }
  658. }
  659. out.kids[k] = instantiateNode(m.kids[k], childChain(chain, k), root, inst, given)
  660. }
  661. // A BOUND MEMBER'S VALUE IS THE HOST'S, HERE. The seed carried the server's
  662. // value, which is right for data and null for a FUNCTION (JSON has no form for
  663. // one) — and a function the host hands its child (`PostForm { onCancel = cancel
  664. // }`) is the way a child talks upward without knowing its host: it calls what it
  665. // was given, and the function writes the host's members through the instance
  666. // that wrote it. So every member binding is applied from the host instance now.
  667. for (b of out.bindings) {
  668. // A PARAMETER THE CHILD'S SETTER TAKES IS NOT WRITTEN HERE (hybriel#301): the server ran the setter at the mount, once,
  669. // and what it did is in the seed's state; a second run here would count the mount twice
  670. if (out.kids[b.kid] != null && hasSetter(out.kids[b.kid].key, b.target)) {
  671. out.kids[b.kid].given[b.target] = bindingValue(b, &out)
  672. } else if (out.kids[b.kid] != null) {
  673. out.kids[b.kid].instance[b.target] = bindingValue(b, &out)
  674. }
  675. }
  676. return out
  677. }
  678. bindKids(&m, Hybrid nodes) {
  679. for (n of nodes) {
  680. if (n.k == 'component') {
  681. // THE EDGE STANDS WHETHER OR NOT THE SERVER MOUNTED THE CHILD: a branch that does
  682. // not stand is not mounted, and the browser builds the child when it comes to
  683. // stand — which must then follow the host's member (every reader of `m.bindings`
  684. // passes over an edge whose child is not there)
  685. {
  686. // A BINDING IS A READ at the reference site: a member (`count = likes`)
  687. // or a field path off one (`postId = row.id`). Both follow the host's
  688. // write — the field path under the name it starts at.
  689. for (b of n.bindings) {
  690. // A MEMBER THAT ONLY FEEDS A BINDING still follows a write: `repaint`
  691. // walks the bindings after the sites, so a host member no element of the
  692. // host shows still reaches the child that was bound to it (measured
  693. // 2026-09-13 on the social app: `FollowButton { following =
  694. // authorFollowed }` stayed false). Under the digest that needed the
  695. // member to be in the compared map; under the write sets it needs
  696. // nothing but the edge itself.
  697. if (b.member != null) { m.bindings.push({ name = b.member; kid = view.kidKey(&n.path); target = b.name; ref = null; }) }
  698. else if (b.ref != null) { m.bindings.push({ name = b.ref.name; kid = view.kidKey(&n.path); target = b.name; ref = b.ref; }) }
  699. }
  700. }
  701. // the fill is THIS mount's fragment: a reference inside it binds against this instance
  702. if (n.fill != null) { bindKids(&m, n.fill) }
  703. } else if (n.k == 'el') {
  704. bindKids(&m, n.children)
  705. } else if (n.k == 'if') {
  706. bindKids(&m, n.then)
  707. bindKids(&m, n.other)
  708. }
  709. }
  710. return null
  711. }
  712. // ---- WHAT THE COMPILE STEP ANSWERED, asked by name ---------------------------------
  713. // A local event's write set stands at its own listener and a region's names at its own
  714. // region: the compile step wrote them into the statements. These three are asked for by
  715. // NAME at run time and cannot be — an inbound frame names its event, a routine a host
  716. // handed down names the member that holds it, and a write set names the derivations
  717. // that follow it — so the component's compiled half carries them beside its walks.
  718. // Nothing here reduces a table: the answers are already the answers.
  719. eventWrites(String key, String event) {
  720. let names = compiledEntry(key, 'ev', event)
  721. return names == null ? [] : names
  722. }
  723. memberWrites(String key, String name) {
  724. let names = compiledEntry(key, 'mw', name)
  725. return names == null ? [] : names
  726. }
  727. // the members the declared handlers that write `name` read (compile.hl handlerFeeds); [] for none
  728. handlerFeedsOf(String key, String name) {
  729. let reads = compiledEntry(key, 'hf', name)
  730. return reads == null ? [] : reads
  731. }
  732. // the members some declared handler writes (compile.hl handlerFeeds)
  733. handlerFed(String key) {
  734. if (window.__hlC == null || window.__hlC[key] == null || window.__hlC[key].hf == null) { return [] }
  735. return window.__hlC[key].hf.keys()
  736. }
  737. derivationsOf(String key) {
  738. if (window.__hlC == null || window.__hlC[key] == null) { return [] }
  739. return window.__hlC[key].dv
  740. }
  741. // one entry of one table of a compiled component, read in place: `compiledOf` hands a
  742. // copy of the whole compiled half, which a push to every mount cannot afford (#138)
  743. compiledEntry(String key, String table, String name) {
  744. if (window.__hlC == null || window.__hlC[key] == null || window.__hlC[key][table] == null) { return null }
  745. return window.__hlC[key][table][name]
  746. }
  747. // ---- THE COMPILED COMPONENT: this framework's own output for this file ------------
  748. // The old hl:web walked a tree the seed carries — it pairs an element with a node, asks a table
  749. // what the element shows, and asks `view.value` what each bound spot holds. hl:web
  750. // ships the answers as the component's own code (plugins/web/compile.hl), and the
  751. // functions below are the FIXED runtime that code calls: the mount records, the keyed
  752. // region diff, the binding edges, the derivations, the socket and navigation stay here,
  753. // where they belong to the framework and not to any one component.
  754. //
  755. // EVERY CALL INTO GENERATED CODE PASSES BY REFERENCE. A plain call copies its
  756. // arguments (the language's value semantics), which for an instance holding a 2000-row
  757. // list would copy the list on every paint; `&` at the call site hands the value itself,
  758. // the way every walk in this file already hands a mount record.
  759. compiledOf(String key) {
  760. let all = window.__hlC
  761. if (all == null) { return null }
  762. return all[key]
  763. }
  764. // one paint entry of a compiled component, read in place (compiledOf hands a copy of
  765. // the whole table, which a row repaint cannot afford per element)
  766. paintEntry(String key, String site) {
  767. if (window.__hlC == null || window.__hlC[key] == null) { return null }
  768. return window.__hlC[key].p[site]
  769. }
  770. // the walk of a component's whole View, of one `for` body, of an `if` branch, or of
  771. // the fragment a reference fills — each under its own site
  772. walkOf(String key, String slot, String site) {
  773. // each slot is read in place off the global table (the `paintEntry` way): `compiledOf`
  774. // would copy the whole compiled component for every `if` site and every `for` row
  775. if (window.__hlC == null || window.__hlC[key] == null) { return null }
  776. if (slot == 'v') { return window.__hlC[key].v }
  777. if (slot == 'b') { return window.__hlC[key].b[site] }
  778. if (slot == 't') { return window.__hlC[key].t[site] }
  779. if (slot == 'e') { return window.__hlC[key].e[site] }
  780. if (slot == 'f') { return window.__hlC[key].f[site] }
  781. if (slot == 'd') { return window.__hlC[key].d[site] }
  782. if (slot == 'r') { return window.__hlC[key].r[site] }
  783. return null
  784. }
  785. // ONE ENTRY INTO GENERATED CODE. `f` is the walk, `m` the mount it runs for, `o` the
  786. // mount whose fragment a `slot` inside it would place.
  787. run(Function f, &m, &o, &host, Number i, &rows, String rk, &fill, Boolean cr, &opt) {
  788. if (f == null) { return i }
  789. return f(&this, &m, &o, &host, i, &rows, rk, &fill, cr, &opt)
  790. }
  791. acqFail(String tag, Hybrid host) {
  792. console.error('claim: no element for', tag, 'under', host == null ? null : host.tagName)
  793. return null
  794. }
  795. // the classes a reference's `#Child` rule put on the composition root, beside whatever
  796. // class the root itself carries (view.hl withRootClasses, on the build walk)
  797. rootClasses(Hybrid el, Hybrid opt) {
  798. if (opt == null || opt.classes == null || opt.classes.length == 0) { return null }
  799. let add = ''
  800. for (c of opt.classes) { add = add == '' ? c : add + ' ' + c }
  801. let have = el.getAttribute('class')
  802. el.setAttribute('class', have == null || have == '' ? add : have + ' ' + add)
  803. return null
  804. }
  805. // #445: write-only positions. Keep every requested write, even if its value is unchanged.
  806. scrollAt(Hybrid el, String axis, Number value) {
  807. el.__hlScroll = (String name, Number offset) => { scrollPending[] = { el = el; axis = name; value = offset; } }
  808. if (value != 0 && value != null) {
  809. scrollPending[] = { el = el; axis = axis; value = value; }
  810. window.requestAnimationFrame(() => { scrollApply() })
  811. }
  812. return null
  813. }
  814. scrollApply() {
  815. jobs = scrollPending
  816. scrollPending = []
  817. for (job of jobs) { if (job.el.isConnected) { job.el[job.axis] = job.value } }
  818. return null
  819. }
  820. // ---- `follow = flag` (ticket #396) ------------------------------------------------------
  821. // A scroll container that follows stays at its end while it was at its end: a patch that adds or grows
  822. // content inside it scrolls it on only if it stood at its end (within a few pixels) before the patch, so a
  823. // user who scrolled up stays where they are. What grows later (an image loads, a row's text wraps) is
  824. // the same: the container's tracked state says whether it was at its end. `follow` is no HTML attribute.
  825. atEnd(Hybrid el) {
  826. return el.scrollHeight - el.scrollTop - el.clientHeight <= 4
  827. }
  828. // the generated walk calls this for every element with a `follow`, built or claimed, and a member's
  829. // repaint writes `__hlFollow` itself
  830. follow(Hybrid el, Hybrid | String | Number | Boolean | Bytes | Function flag) {
  831. el.__hlFollow = flag != null && flag != false && flag != "" && flag != "false"
  832. if (el.__hlFollowed == true) { return null }
  833. el.__hlFollowed = true
  834. el.__hlEnd = true
  835. el.__hlWas = true
  836. followers.push(el)
  837. el.addEventListener('scroll', () => { el.__hlEnd = atEnd(el) })
  838. // a container built or claimed with its content stands at its end once it is laid out
  839. window.requestAnimationFrame(() => { followKeep() })
  840. return null
  841. }
  842. // before a patch: which followers stand at their end now
  843. followMark() {
  844. for (el of followers) { el.__hlWas = el.__hlFollow == true && atEnd(el) }
  845. return null
  846. }
  847. // after a patch (and when a child resizes): the followers that stood at their end stand there again
  848. followKeep() {
  849. let live = []
  850. for (el of followers) {
  851. if (el.isConnected) { live.push(el) }
  852. }
  853. followers = live
  854. for (el of followers) {
  855. if (el.__hlFollow == true && el.__hlWas == true) {
  856. if (!atEnd(el)) { el.scrollTop = el.scrollHeight }
  857. el.__hlEnd = true
  858. } else { el.__hlEnd = atEnd(el) }
  859. el.__hlWas = el.__hlFollow == true && el.__hlEnd == true
  860. followWatch(el)
  861. }
  862. return null
  863. }
  864. // a container and its children are watched: a child that grows after the patch (an image, wrapped text) moves the end
  865. followWatch(Hybrid el) {
  866. if (followSeen == null) {
  867. followSeen = new ResizeObserver(() => { followResized() })
  868. }
  869. followSeen.observe(el)
  870. for (kid of Array.from(el.children)) { followSeen.observe(kid) }
  871. return null
  872. }
  873. followResized() {
  874. for (el of followers) {
  875. if (el.isConnected && el.__hlFollow == true && el.__hlEnd == true && !atEnd(el)) { el.scrollTop = el.scrollHeight }
  876. }
  877. return null
  878. }
  879. // ---- `modal = flag` on a dialog, `popoverOpen = flag` on a popover (tickets #329, #389) ----------
  880. // The member drives the browser's top layer: true shows the dialog with showModal() (the popover with
  881. // showPopover()), false closes it. A native close (Escape, a form method=dialog, a light dismiss) writes the
  882. // member back to false, so the View and the member agree. Neither name is an HTML attribute.
  883. // The generated walk calls this for each such element, built or claimed; a member's repaint sets `__hlTop`
  884. // and calls `__hlTopSync` itself.
  885. topAt(&m, Hybrid el, String name, String member, Hybrid | String | Number | Boolean | Bytes | Function flag, Hybrid rows) {
  886. el.__hlTop = flag != null && flag != false && flag != "" && flag != "false"
  887. if (el.__hlTopWired == true) { el.__hlTopSync() return null }
  888. el.__hlTopWired = true
  889. let isDialog = name == 'modal'
  890. let tries = 0
  891. el.__hlTopSync = () => {
  892. // not in the document yet (a page built off-screen): the next frame
  893. if (!el.isConnected) {
  894. tries = tries + 1
  895. if (tries < 20) { window.requestAnimationFrame(() => { el.__hlTopSync() }) }
  896. return null
  897. }
  898. let shown = isDialog ? el.matches(':modal') : el.matches(':popover-open')
  899. if (el.__hlTop == true && !shown) {
  900. if (isDialog) {
  901. if (el.open) { el.close() }
  902. el.showModal()
  903. } else { el.showPopover() }
  904. } else if (el.__hlTop != true && shown) {
  905. if (isDialog) { el.close() } else { el.hidePopover() }
  906. }
  907. return null
  908. }
  909. // a native close writes the member back (a member that is already false, or a row variable, is left alone)
  910. let back = () => {
  911. let shown = isDialog ? el.matches(':modal') : el.matches(':popover-open')
  912. if (shown || member == null || rows[member] != null) { return null }
  913. el.__hlTop = false
  914. if (m.instance[member] == null || m.instance[member] == false) { return null }
  915. m.instance[member] = false
  916. patch(m.chain, m.rootKind, [member], [])
  917. return null
  918. }
  919. if (isDialog) { el.addEventListener('close', () => { back() }) }
  920. else { el.addEventListener('toggle', () => { back() }) }
  921. el.__hlTopSync()
  922. return null
  923. }
  924. // AN ELEMENT THAT SHOWS SOMETHING is a site of this mount. The names come from the
  925. // generated call — the compile step read them off the View — and the two-way `value`
  926. // bind is applied where the element is a form control the member paints.
  927. siteAt(&m, Hybrid el, Hybrid names, String site, String valueMember, Boolean isSelect, Hybrid rows) {
  928. let keep = []
  929. for (name of names) {
  930. // the SHELL's `slot` is where the route component hangs: swapped by navigation,
  931. // never painted (the compile step already drops `Style`, folded at build)
  932. if (!(name == 'slot' && m.isShell)) { keep.push(name) }
  933. }
  934. if (valueMember != null && rows[valueMember] == null && el.value != null) {
  935. bindValue(&m, valueMember, el, isSelect)
  936. }
  937. 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 + ',' } }
  938. return null
  939. }
  940. // (#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
  941. // 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
  942. // on its open mark, the node the reseat walk starts from.
  943. applySelectAt(&m, Hybrid el, Hybrid | String | Number | Boolean | Bytes | Function v) {
  944. el.value = v == null ? '' : '' + v
  945. return null
  946. }
  947. // A HANDLER, WIRED AT CREATION. The literal is the element's own — its named entries
  948. // are the generated `__hlLit`, the `for` rows in scope ride on it, and the owner is the
  949. // instance BY REFERENCE (a handler writing a copy would repaint nothing).
  950. onAt(&m, Hybrid el, String event, String site, Hybrid rows, Hybrid wrote, Hybrid touched) {
  951. if (el.__hlLits == null) { el.__hlLits = {} }
  952. el.__hlLits[event] = literalFor(&m, el)
  953. let at = m.chain
  954. let root = m.rootKind
  955. let rowNames = rows == null ? [] : rows.keys()
  956. runEvent = (Hybrid ev) => {
  957. let lit = el.__hlLits[event]
  958. for (rk of rowNames) { lit[rk] = el.__hlRows[rk] }
  959. domListener = { event = event; chain = at; root = root; wrote = wrote; }
  960. if (event == 'submit') { flushCoalesced() }
  961. originFor(el, event, ev)
  962. // A host timer returns immediately; keep it here so originFor stays synchronous.
  963. mine = emitOrigin
  964. if (mine != null) { window.setTimeout(() => { if (emitOrigin == mine) { emitOrigin = null } }, 0) }
  965. fire(&lit, event, ev)
  966. el.__hlLits[event] = lit
  967. patch(at, root, wrote, touched)
  968. }
  969. if (event == 'seen') { watchSeen(el, runEvent) return null }
  970. el.addEventListener(event, (Hybrid ev) => {
  971. // Capture dispatch-only fields before the first awaited call. If dispatch
  972. // waits for claim, preserve native defaults except the framework-owned submit.
  973. current = ev.currentTarget
  974. target = ev.target
  975. phase = ev.eventPhase
  976. waiting = mounting
  977. if (event == 'submit') { ev.preventDefault() }
  978. if (waiting) { deferDom(ev, current, target, phase, runEvent) return null }
  979. runEvent(ev)
  980. })
  981. return null
  982. }
  983. // `on seen()` (#412): fires ONCE per element, when the element is at least partly in the viewport while the tab is
  984. // visible. ONE IntersectionObserver serves the page. An element that came into view while the tab was hidden waits in
  985. // `seenWaiting` and fires when the tab becomes visible (`seenFlush`). A fired element is unobserved, and so is one that
  986. // left the DOM unseen (swept at every report). `seenRuns` is the array of the elements still watched, each carrying its
  987. // handler's run in `__hlSeen`.
  988. watchSeen(Hybrid el, Function go) {
  989. if (seenObserver == null) { seenObserver = new IntersectionObserver((Hybrid entries) => { seenReport(entries) }) }
  990. el.__hlSeen = go
  991. seenRuns.push(el)
  992. seenObserver.observe(el)
  993. return null
  994. }
  995. seenReport(Hybrid entries) {
  996. for (en of entries) {
  997. if (en.isIntersecting && en.target.__hlSeen != null && !seenWaiting.includes(en.target)) { seenWaiting.push(en.target) }
  998. }
  999. // 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
  1000. // 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 s
  1001. let keep = []
  1002. for (el of seenRuns) {
  1003. if (el.__hlSeen == null) { continue }
  1004. if (el.isConnected) { el.__hlSeenOff = null keep.push(el) }
  1005. else if (el.__hlSeenOff == null) { el.__hlSeenOff = Date.now() keep.push(el) }
  1006. else if (mounting || Date.now() - el.__hlSeenOff < 3000) { keep.push(el) }
  1007. else { seenObserver.unobserve(el) el.__hlSeen = null }
  1008. }
  1009. seenRuns = keep
  1010. seenFlush()
  1011. return null
  1012. }
  1013. seenFlush() {
  1014. if (document.visibilityState != 'visible') { return null }
  1015. let due = seenWaiting
  1016. seenWaiting = []
  1017. for (el of due) {
  1018. let go = el.__hlSeen
  1019. if (go == null || !el.isConnected) { continue }
  1020. el.__hlSeen = null
  1021. seenObserver.unobserve(el)
  1022. if (mounting) { heldDom[] = () => { runSeen(go) } } else { runSeen(go) }
  1023. }
  1024. return null
  1025. }
  1026. // one `on seen()` handler's run: a handler that fails is logged and does not cost the elements after it theirs (#422)
  1027. runSeen(Function go) {
  1028. let r = window.__hlAttempt(() => { return go({ type = 'seen'; }) })
  1029. if (!r.ok) { console.error('framework: an on seen() handler failed — ' + r.error) }
  1030. return null
  1031. }
  1032. // THE SHELL'S SLOT: where the route component hangs. On the build walk the re-created
  1033. // element adopts the page's nodes, and a page the shell never rendered is built here.
  1034. slotShell(&m, Hybrid host, Number i, Boolean cr) {
  1035. // A PARENT LEVEL BELOW THE SHELL (#194): this level's slot holds the next parent level,
  1036. // kid '^' (the page stands in the innermost level's slot). It leaves no mark of its own.
  1037. let inner = m.kids['^']
  1038. // A SLOT THAT OPENS LATER (#194): the levels below this one were never built (the shell's
  1039. // slot stood closed when the document was made). The answer for the route brings the
  1040. // page AND every level between, so the level below this one is built from it now
  1041. if (inner == null && cr && !pageShown && page == null) {
  1042. page = arrive(&m)
  1043. inner = m.kids['^']
  1044. }
  1045. if (inner != null) {
  1046. // THE REGION OF THE LEVEL BELOW (mission 343): the server writes the same two marks around a parent level as around
  1047. // the page, so a navigation that changes only the levels from here down can replace what stands between them
  1048. let rs = markAt(&host, cr, true)
  1049. levelMarks[m.chain.length] = rs
  1050. inner.chain = childChain(m.chain, '^')
  1051. inner.rootKind = m.rootKind
  1052. if (cr) { inner.sites = [] if (m.rootKind == 'shell') { langSite(&inner) } }
  1053. let f = walkOf(inner.key, 'v', null)
  1054. let out = run(f, &inner, &m, &host, cr ? 0 : i, {}, '', null, cr, null)
  1055. if (!cr) { i = out }
  1056. if (cr || inner.bindings.length == 0) { inner.bindings = [] bindKids(&inner, inner.view) }
  1057. m.kids['^'] = inner
  1058. if (cr) { rs.__hlEnd = markAt(&host, true, false) }
  1059. else {
  1060. rs.__hlEnd = closeOf(rs)
  1061. host.__hlCur = rs.__hlEnd
  1062. }
  1063. return i
  1064. }
  1065. slotEl = host
  1066. if (!cr) {
  1067. // claiming: the page's elements stand here, and the shell's own elements after
  1068. // the slot come after them
  1069. slotAt = i
  1070. if (seed.page == null) { return i }
  1071. // the page's region: its marks, and the elements between them the shell steps over
  1072. slotStart = markAt(&host, false, true)
  1073. levelMarks[m.chain.length] = slotStart
  1074. slotStart.__hlEnd = closeOf(slotStart)
  1075. host.__hlCur = slotStart.__hlEnd
  1076. let span = 0
  1077. for (n of between(slotStart)) { if (n.nodeType == 1) { span = span + 1 } }
  1078. return i + span
  1079. }
  1080. slotAt = host.children.length
  1081. let start = markAt(&host, true, true)
  1082. if (detachedSlot != null && detachedSlot != host) {
  1083. // the page's own nodes: what stood between its marks, or all of the old host's
  1084. let moving = standing(detachedSlot, slotStart) ? between(slotStart) : Array.from(detachedSlot.childNodes)
  1085. for (node of moving) { host.appendChild(node) }
  1086. }
  1087. detachedSlot = null
  1088. if (!pageShown) {
  1089. // THE PAGE ARRIVES WITH ITS SLOT: it was never constructed while the shell
  1090. // placed none, so it is asked for now — the route's state, from the server
  1091. if (page == null) { page = arrive(&m) }
  1092. if (page != null && restored) {
  1093. // THE PAGE THE CLOSED REGION HELD comes back with its DOM and instances, no server round trip (W161)
  1094. restored = false
  1095. for (n of dropped.nodes) { host.appendChild(n) }
  1096. for (a of dropped.addrs.keys()) { mountAddr[a] = dropped.addrs[a] }
  1097. for (i of dropped.ids.keys()) { mountIndex[i] = dropped.ids[i] }
  1098. let back = dropped
  1099. dropped = null
  1100. wearHead(&page)
  1101. pageShown = true
  1102. placeRegions(false)
  1103. pageArrived = true
  1104. repaintAway(back)
  1105. } else if (page != null) {
  1106. page.sites = []
  1107. create(&page, host)
  1108. headSites(&page)
  1109. wearHead(&page)
  1110. pageShown = true
  1111. placeRegions(false)
  1112. }
  1113. }
  1114. start.__hlEnd = markAt(&host, true, false)
  1115. slotStart = start
  1116. levelMarks[m.chain.length] = start
  1117. return i
  1118. }
  1119. // THE ROUTE'S PAGE, for a slot that just opened: the navigation face answers it for
  1120. // this path, told the slot stands here, and the mount is constructed from that. The
  1121. // frames it raises wait until the rebuild that placed it is done (pageArrived).
  1122. arrive(&m) {
  1123. if (seed.offlineNotice != null) { return null }
  1124. // the page this slot held when it closed, if it is the route's still and stands under the same levels
  1125. if (dropped != null && dropped.path == location.pathname + location.search && dropped.keys == JSON.stringify(chainKeys(seed.shell)) && dropped.params == chainParams() && dropped.who == whoNow()) {
  1126. restored = true
  1127. seed.page = JSON.parse(dropped.seedPage)
  1128. dropped.page.instance.__hlParent = layoutHost(m)
  1129. return dropped.page
  1130. }
  1131. dropped = null
  1132. // the answer carries the values table (#180) like a navigation's: resolved before anything reads it
  1133. let next = resolveValues(emit server page(location.pathname + location.search, true, [], []))
  1134. if (next == null || next.page == null) { return null }
  1135. seed.page = next.page
  1136. mounting = true
  1137. // Build any newly opened layout levels before their page, with the standing level as host.
  1138. let level = next.shell
  1139. let depth = 0
  1140. while (level != null && depth < m.chain.length) { level = level.kids['^'] depth = depth + 1 }
  1141. if (level != null && level.kids['^'] != null) {
  1142. m.kids['^'] = instantiate(level.kids['^'], childChain(m.chain, '^'), m.rootKind, m.instance)
  1143. let saved = seed.shell
  1144. depth = 0
  1145. while (depth < m.chain.length) { saved = saved.kids['^'] depth = depth + 1 }
  1146. saved.kids['^'] = level.kids['^']
  1147. }
  1148. pageArrived = true
  1149. return instantiate(next.page, [], 'page', layoutHost(m))
  1150. }
  1151. // THE SLOT CLOSED: the page is dropped, not kept aside — the next time the slot opens
  1152. // it is constructed again. The head falls back to the app's own.
  1153. dropPage(&m) {
  1154. // THE LEVELS BELOW THE CLOSED SLOT GO WITH THE PAGE (#194): the level this slot belonged to held
  1155. // the next parent level as kid '^' — its sites, listeners and record are dropped, not left stale;
  1156. // the slot's next opening builds them again (arrive)
  1157. let hadInner = m.kids['^'] != null
  1158. if (hadInner) {
  1159. purgeMounts(childChain(m.chain, '^'), m.rootKind)
  1160. delete m.kids['^']
  1161. if (m.chain.length == 0 && seed.shell != null && seed.shell.kids != null) { delete seed.shell.kids['^'] }
  1162. }
  1163. // (kept for the slot's next opening when no parent level hangs below it)
  1164. dropped = page != null && slotStart != null && !hadInner && shownPath != null ? snapLeft() : null
  1165. slotEl = null
  1166. pageShown = false
  1167. page = null
  1168. purgeMounts([], 'page')
  1169. slotStart = null
  1170. seed.page = null
  1171. let none = { instance = {}; }
  1172. wearHead(&none)
  1173. announceMounts()
  1174. return null
  1175. }
  1176. // a rebuild that constructed the page: what waited for it goes out, and the server
  1177. // learns the tab mounts it
  1178. arrived() {
  1179. if (!pageArrived) { return null }
  1180. pageArrived = false
  1181. release()
  1182. announceMounts()
  1183. return null
  1184. }
  1185. // A CHILD'S SLOT: the fragment its HOST wrote, built in the host's frame. The fill names
  1186. // that frame by address, and `run` re-enters it when this walk is not it.
  1187. slotFill(&m, &o, Hybrid host, Number i, Hybrid fill, Boolean cr) {
  1188. if (fill == null) { return i }
  1189. if (cr && fill.detached) {
  1190. let anchor = document.createComment('hl:slot')
  1191. host.appendChild(anchor)
  1192. pendingFills[] = { key = fill.key; site = fill.site; rows = fill.rows; rowKey = fill.rowKey; outer = fill.outer; chain = fill.chain; rootKind = fill.rootKind; anchor = anchor; }
  1193. return i
  1194. }
  1195. if (ownsFill(o, fill)) {
  1196. let f = walkOf(fill.key, 'f', fill.site)
  1197. return run(f, &o, &o, &host, i, &fill.rows, fill.rowKey, &fill.outer, cr, null)
  1198. }
  1199. return fillFromRoot(fill, host, i, cr)
  1200. }
  1201. // ---- NAMED REGIONS (D-CHAIN addendum) -------------------------------------------------
  1202. // A level above declares `slot { name = 'side' … }`: a region between two marks, holding its
  1203. // default (built in the declaring level's frame, walk 'd') or the fill a lower level wrote at its
  1204. // View root (`side { … }`, built in THAT level's frame, walk 'r'). The region element stands; a
  1205. // navigation rebuilds only what stands between the marks.
  1206. namedRegionAt(&m, &o, Hybrid host, Number i, String site, String name, Hybrid rows, String rk, Hybrid fill, Boolean cr) {
  1207. let desc = { key = m.key; site = site; rows = rows; rowKey = rk; outer = fill; chain = m.chain; rootKind = m.rootKind; slot = 'd'; }
  1208. if (!cr) {
  1209. // claiming: the region's marks are taken and its content is claimed once the page is (boot)
  1210. let start = markAt(&host, false, true)
  1211. start.__hlEnd = closeOf(start)
  1212. host.__hlCur = start.__hlEnd
  1213. let span = 0
  1214. for (n of between(start)) { if (n.nodeType == 1) { span = span + 1 } }
  1215. regionTable[name] = { host = host; start = start; at = i; base = desc; desc = desc; kind = null; }
  1216. return i + span
  1217. }
  1218. let start = markAt(&host, true, true)
  1219. start.__hlEnd = mark(false)
  1220. host.appendChild(start.__hlEnd)
  1221. let fd = fillerOf(name)
  1222. // (a hybrid read off a table is a copy: the entry is written whole, never through a read of it)
  1223. regionTable[name] = { host = host; start = start; at = 0; base = desc; desc = fd == null ? desc : fd; kind = fd == null ? 'd' : 'r'; }
  1224. if (fd != null) {
  1225. fillFromRoot(fd, host, 0, true)
  1226. } else {
  1227. run(walkOf(m.key, 'd', site), &m, &o, &host, 0, &rows, rk, &fill, true, null)
  1228. }
  1229. // built in place before the close mark (the walk appended after it)
  1230. host.appendChild(start.__hlEnd)
  1231. return i
  1232. }
  1233. // the level below the declaring one that fills region `name`: the page first, then the levels
  1234. // from the innermost out. A descriptor naming the filler's frame, or null (the default stands).
  1235. fillerOf(String name) {
  1236. let cands = []
  1237. if (page != null) { cands.push(page) }
  1238. let lv = []
  1239. let x = shell
  1240. while (x != null && lv.length < 64) { lv.push(x) x = x.kids == null ? null : x.kids['^'] }
  1241. let k = lv.length - 1
  1242. while (k > 0) { cands.push(lv[k]) k = k - 1 }
  1243. for (c of cands) {
  1244. let site = regionFillSite(c.key, name)
  1245. // a conditional fill holds while its condition does (read off the filling instance)
  1246. if (site != null && window.__hlC[c.key].rc != null && window.__hlC[c.key].rc[name] != null) {
  1247. let cf = window.__hlC[c.key].rc[name]
  1248. let nr = {}
  1249. if (!cf(&c.instance, &nr)) { site = null }
  1250. }
  1251. if (site != null) { return { key = c.key; site = site; rows = {}; rowKey = ''; outer = null; chain = c.chain; rootKind = c.rootKind; slot = 'r'; } }
  1252. }
  1253. return null
  1254. }
  1255. regionFillSite(String key, String name) {
  1256. if (window.__hlC == null || window.__hlC[key] == null || window.__hlC[key].rn == null) { return null }
  1257. return window.__hlC[key].rn[name]
  1258. }
  1259. // every named region takes what its level or the filler below it holds: after a page is claimed
  1260. // (boot, `claim` true: the server's nodes are taken) or placed (navigation: rebuilt)
  1261. placeRegions(Boolean claimIt) {
  1262. if (!claimIt) {
  1263. for (name of regionTable.keys()) { placeRegion(name, false) }
  1264. return null
  1265. }
  1266. // claiming a region's default may claim regions inside it (their marks are taken on the way and
  1267. // their content waits): pass again until every one that stands has its content
  1268. let pass = 0
  1269. let pending = true
  1270. while (pending && pass < 16) {
  1271. pending = false
  1272. pass = pass + 1
  1273. for (name of regionTable.keys()) {
  1274. let r = regionTable[name]
  1275. if (r.kind == null && standing(r.host, r.start)) { pending = true placeRegion(name, true) }
  1276. }
  1277. }
  1278. return null
  1279. }
  1280. placeRegion(String name, Boolean claimIt) {
  1281. let r = regionTable[name]
  1282. if (r == null || !standing(r.host, r.start)) { return null }
  1283. let fd = fillerOf(name)
  1284. let want = fd == null ? 'd' : 'r'
  1285. if (claimIt) {
  1286. let d = fd == null ? r.base : fd
  1287. regionTable[name].kind = want
  1288. regionTable[name].desc = d
  1289. r.host.__hlCur = r.start
  1290. regionClaim(d, r.host, r.at)
  1291. return null
  1292. }
  1293. // the default stands and stays the default: its state and its nodes are not rebuilt
  1294. if (want == 'd' && r.kind == 'd') { return null }
  1295. let old = between(r.start)
  1296. let owner = r.desc
  1297. if (owner.rootKind == 'shell' || owner.slot == 'd') { regionDrop(owner, r.host, old) }
  1298. for (n of old) { n.remove() }
  1299. let d = fd == null ? r.base : fd
  1300. regionTable[name].desc = d
  1301. regionTable[name].kind = want
  1302. regionBuild(d, r.host, r.start.__hlEnd)
  1303. return null
  1304. }
  1305. // claims the server's nodes of a region's content, in the frame its descriptor names
  1306. regionClaim(Hybrid d, Hybrid host, Number at) {
  1307. fillFromRoot(d, host, at, false)
  1308. return null
  1309. }
  1310. // builds a region's content in a fragment and puts it before the close mark; the sites the walk
  1311. // registered on the fragment belong to the region's host (as `placePage` does)
  1312. regionBuild(Hybrid d, Hybrid host, Hybrid closeMark) {
  1313. let frag = document.createDocumentFragment()
  1314. let before = sidNext
  1315. fillFromRoot(d, frag, 0, true)
  1316. host.insertBefore(frag, closeMark)
  1317. regionRehome(d, frag, host, before)
  1318. return null
  1319. }
  1320. regionRehome(Hybrid d, Hybrid frag, Hybrid host, Number before) {
  1321. if (d.rootKind == 'shell') { if (shell != null) { regionRehomeAt(&shell, d, 0, frag, host, before) } }
  1322. else if (page != null) { regionRehomeAt(&page, d, 0, frag, host, before) }
  1323. return null
  1324. }
  1325. regionRehomeAt(&m, Hybrid d, Number depth, Hybrid frag, Hybrid host, Number before) {
  1326. if (depth >= d.chain.length) { rehome(&m, frag, host, before) return null }
  1327. if (m.kids[d.chain[depth]] == null) { return null }
  1328. regionRehomeAt(&m.kids[d.chain[depth]], d, depth + 1, frag, host, before)
  1329. return null
  1330. }
  1331. // the sites of the nodes that leave belong to the frame that built them
  1332. regionDrop(Hybrid d, Hybrid host, Hybrid nodes) {
  1333. if (d.rootKind == 'shell') { if (shell != null) { regionDropAt(&shell, d, 0, host, nodes) } }
  1334. else if (page != null) { regionDropAt(&page, d, 0, host, nodes) }
  1335. return null
  1336. }
  1337. regionDropAt(&m, Hybrid d, Number depth, Hybrid host, Hybrid nodes) {
  1338. if (depth >= d.chain.length) { dropSitesIn(&m, host, nodes) return null }
  1339. if (m.kids[d.chain[depth]] == null) { return null }
  1340. regionDropAt(&m.kids[d.chain[depth]], d, depth + 1, host, nodes)
  1341. return null
  1342. }
  1343. // the fill's owner, re-entered from the page or the shell by the address it carries
  1344. fillFromRoot(Hybrid fill, Hybrid host, Number at, Boolean cr) {
  1345. if (fill.rootKind == 'shell') {
  1346. if (shell == null) { return at }
  1347. return fillInto(&shell, fill, 0, host, at, cr)
  1348. }
  1349. if (page == null) { return at }
  1350. return fillInto(&page, fill, 0, host, at, cr)
  1351. }
  1352. fillInto(&m, Hybrid fill, Number depth, Hybrid host, Number at, Boolean cr) {
  1353. if (depth >= fill.chain.length) {
  1354. let f = walkOf(fill.key, fill.slot == null ? 'f' : fill.slot, fill.site)
  1355. return run(f, &m, &m, &host, at, &fill.rows, fill.rowKey, &fill.outer, cr, null)
  1356. }
  1357. if (m.kids[fill.chain[depth]] == null) { return at }
  1358. return fillInto(&m.kids[fill.chain[depth]], fill, depth + 1, host, at, cr)
  1359. }
  1360. // the fill context a reference hands its child: the fragment's owner by address, the
  1361. // host's rows and rowKey, and the fill the host itself was standing in
  1362. fillFor(&m, Hybrid spec, Hybrid rows, String rowKey, Hybrid fill) {
  1363. if (!spec.fill) { return null }
  1364. return { key = m.key; site = spec.site; rows = rows; rowKey = rowKey; outer = fill; chain = m.chain; rootKind = m.rootKind; detached = false; }
  1365. }
  1366. // ---- THE MARKS: every region stands between two comments ---------------------------
  1367. // THE INVARIANT (tickets #103, #104). Every region — an `if`, a `for`, each row of a
  1368. // `for`, the shell's page — stands on its host between an OPEN mark (a comment `[`)
  1369. // and a CLOSE mark (`]`), and ITS NODES ARE EXACTLY THE NODES BETWEEN THEM. A region
  1370. // inside another one on the same host stands between the outer one's marks. So:
  1371. // - a region's nodes are never remembered, they are read off the DOM between its
  1372. // marks when they are needed — whatever a region inside it did since, they are
  1373. // right (a list taken when the branch was built went stale, #103);
  1374. // - a region is replaced by removing what stands between its marks and putting the
  1375. // new nodes before its close mark; a row moves and leaves WITH its marks, so a row
  1376. // is always whole and in its list;
  1377. // - nothing outside a region is touched by it, and nothing inside it outlives it: the
  1378. // sites registered in the nodes it drops are dropped with them, and a region whose
  1379. // marks have left its host has nothing to paint.
  1380. // The server writes the same marks (compile.hl `markOpen`), the claim walk takes them in
  1381. // document order and the build walk makes them, so a region looks the same however it
  1382. // came to stand — and text beside a region never runs into the region's own text.
  1383. mark(Boolean open) { return document.createComment(open ? '[' : ']') }
  1384. isMark(Hybrid n) { return n != null && n.nodeType == 8 && (n.data == '[' || n.data == ']' || n.data == '[hl:page' || n.data == ']hl:page') }
  1385. // the nodes strictly between a region's marks
  1386. between(Hybrid start) {
  1387. let out = []
  1388. let end = start.__hlEnd
  1389. let n = start.nextSibling
  1390. while (n != null && n != end) { out.push(n) n = n.nextSibling }
  1391. return out
  1392. }
  1393. // …and with the marks themselves: a row as it moves or leaves
  1394. spanOf(Hybrid start) {
  1395. let out = [start]
  1396. for (n of between(start)) { out.push(n) }
  1397. out.push(start.__hlEnd)
  1398. return out
  1399. }
  1400. // a region stands while both its marks are on its host
  1401. standing(Hybrid host, Hybrid start) {
  1402. return start != null && start.parentNode == host && start.__hlEnd != null && start.__hlEnd.parentNode == host
  1403. }
  1404. // A REGION'S MARK, made (building) or taken (claiming). The claim takes the next mark
  1405. // after the host's cursor: the walk meets the regions in document order, so it is this
  1406. // region's. A page whose marks do not match its tree is said so, and gets a mark where
  1407. // the walk stands.
  1408. markAt(&host, Boolean cr, Boolean open) {
  1409. if (cr) {
  1410. let made = mark(open)
  1411. host.appendChild(&made)
  1412. return made
  1413. }
  1414. let n = host.__hlCur == null ? host.firstChild : host.__hlCur.nextSibling
  1415. while (n != null && !isMark(&n)) { n = n.nextSibling }
  1416. let mk = null
  1417. if (n != null && (n.data == (open ? '[' : ']') || n.data == (open ? '[hl:page' : ']hl:page'))) { mk = n }
  1418. else {
  1419. console.error('claim: no region mark under', host.tagName)
  1420. mk = mark(open)
  1421. host.insertBefore(mk, host.__hlCur == null ? host.firstChild : host.__hlCur.nextSibling)
  1422. }
  1423. host.__hlCur = mk
  1424. return mk
  1425. }
  1426. // the close mark that pairs with an open one, past the regions inside it
  1427. closeOf(Hybrid start) {
  1428. let depth = 0
  1429. let n = start.nextSibling
  1430. while (n != null) {
  1431. if (isMark(n)) {
  1432. if (n.data == '[' || n.data == '[hl:page') { depth = depth + 1 }
  1433. else if (depth == 0) { return n }
  1434. else { depth = depth - 1 }
  1435. }
  1436. n = n.nextSibling
  1437. }
  1438. let made = mark(false)
  1439. start.parentNode.appendChild(made)
  1440. return made
  1441. }
  1442. // THE SITES IN NODES THAT LEAVE go with them: an element's, a text leaf's, and a
  1443. // region's whose open mark is among them. Marked and walked up once per site.
  1444. //
  1445. // NO CALL BETWEEN READING THE LIST AND WRITING IT BACK. Every call in this language is
  1446. // awaited, and an await lets another repaint run — one that registers sites of its
  1447. // own, which a list read before it and written after it would lose. The loops that
  1448. // read `m.sites` and write it back hold property reads, index writes and `[] =` only.
  1449. dropSitesIn(&m, Hybrid host, Hybrid nodes) {
  1450. if (nodes.length == 0) { return null }
  1451. // MARK THE LEAVING NODES AND EVERY NODE UNDER THEM once (a tree walk), then READ EACH SITE BY INDEX and remove the
  1452. // gone ones in place: `for (site of m.sites)` / `kept[] = site` / `m.sites = kept` copied every site and the
  1453. // whole list per drop, and `n = n.parentNode` copied a node per step: hlCopyFast ~205 ms for one fold of 60
  1454. // rows (w77)
  1455. for (n of nodes) {
  1456. n.__hlGone = true
  1457. if (n.nodeType == 1) {
  1458. let w = document.createTreeWalker(n, 4294967295)
  1459. let c = w.nextNode()
  1460. while (c != null) { c.__hlGone = true c = w.nextNode() }
  1461. }
  1462. }
  1463. let k = m.sites.length - 1
  1464. let dropped = 0
  1465. while (k >= 0) {
  1466. if (m.sites[k].region && m.sites[k].el == host && m.sites[k].start != null) {
  1467. if (m.sites[k].start.__hlGone == true) { m.sites.splice(k, 1) dropped = dropped + 1 }
  1468. } else if (m.sites[k].el != null && m.sites[k].el.__hlGone == true) { m.sites.splice(k, 1) dropped = dropped + 1 }
  1469. k = k - 1
  1470. }
  1471. if (dropped > 0) { dropGen = dropGen + 1 }
  1472. for (n of nodes) {
  1473. n.__hlGone = null
  1474. if (n.nodeType == 1) {
  1475. let w = document.createTreeWalker(n, 4294967295)
  1476. let c = w.nextNode()
  1477. while (c != null) { c.__hlGone = null c = w.nextNode() }
  1478. }
  1479. }
  1480. return null
  1481. }
  1482. // THE SITES A WALK REGISTERED ON THE FRAGMENT IT BUILT INTO belong to the host it lands
  1483. // in — this mount's, and those of the children composed straight onto the fragment,
  1484. // whose own regions (a child's View may begin with an `if`) stand on the same host.
  1485. // Those children are named by address on the fragment as the walk composes them
  1486. // (kidAt, `__hlOnFrag`), so only they are re-entered.
  1487. rehome(&m, Hybrid src, Hybrid dst, Number before) {
  1488. sitesOnto(&m, src, dst, before)
  1489. let due = src.__hlOnFrag == null ? [] : src.__hlOnFrag
  1490. src.__hlOnFrag = null
  1491. let base = m.chain == null ? 0 : m.chain.length
  1492. for (chain of due) {
  1493. if (chain.length > base) { rehomeAt(&m, chain, base, src, dst) }
  1494. }
  1495. return null
  1496. }
  1497. // (`after`: the sites numbered after it are the walk's — an index would move when
  1498. // another repaint drops sites in the meantime)
  1499. sitesOnto(&m, Hybrid src, Hybrid dst, Number after) {
  1500. // sids only grow along m.sites, so the walk's sites are its tail: read it from the end
  1501. // and stop at the first older one (a scan of every site per row built was O(rows x sites))
  1502. let k = m.sites.length - 1
  1503. while (k >= 0 && m.sites[k].sid > after) {
  1504. if (m.sites[k].el == src) { m.sites[k].el = dst }
  1505. k = k - 1
  1506. }
  1507. return null
  1508. }
  1509. rehomeAt(&m, Hybrid chain, Number depth, Hybrid src, Hybrid dst) {
  1510. if (depth >= chain.length) { sitesOnto(&m, src, dst, 0) return null }
  1511. if (m.kids[chain[depth]] == null) { return null }
  1512. rehomeAt(&m.kids[chain[depth]], chain, depth + 1, src, dst)
  1513. return null
  1514. }
  1515. // A RANGE LEAVES THE PAGE — a branch, a row: every site registered in it goes (at any
  1516. // depth: an element's, a text's, a region's whose marks are in it), and so does every
  1517. // child composed in it (its nodes carry its address), with its own sites, its children
  1518. // and its handlers.
  1519. // A range can hold a FILL — a host's fragment placed at this component's `slot` — whose
  1520. // sites and children are the host's: `fill` names that host (and the one it was filled
  1521. // by in turn), and those go in settle(), where a host is re-entered by its address after
  1522. // every mount on this walk has been written back.
  1523. dropRange(&m, Hybrid host, Hybrid nodes, Hybrid fill) {
  1524. dropSitesIn(&m, host, nodes)
  1525. let others = disposeIn(&m, nodes)
  1526. let f = fill
  1527. while (f != null) {
  1528. pendingDrops.push({ chain = f.chain; rootKind = f.rootKind; host = host; nodes = nodes; kids = others; })
  1529. others = []
  1530. f = f.outer
  1531. }
  1532. return null
  1533. }
  1534. // THE CHILDREN COMPOSED IN NODES go: those of this mount at once, and the others (a
  1535. // host's, composed in its fill) are answered for the caller to hand on
  1536. disposeIn(&m, Hybrid nodes) {
  1537. let chains = []
  1538. for (n of nodes) { kidsFiledIn(n, &chains) }
  1539. base = m.chain == null ? [] : m.chain
  1540. let others = []
  1541. let purged = []
  1542. for (c of chains) {
  1543. // Addresses are lists of string kid keys. Compare their common prefix once;
  1544. // slicing and serialising both prefixes per child copies and encodes them.
  1545. // Keep the original chain order, ancestor exclusion and fill-host handoff.
  1546. let common = 0
  1547. while (common < base.length && common < c.length && base[common] == c[common]) { common = common + 1 }
  1548. above = c.length <= base.length && common == c.length
  1549. if (!above) {
  1550. if (c.length > base.length && common == base.length) { if (disposeAt(&m, &c, base.length)) { purged.push(c) } }
  1551. else { others.push(c) }
  1552. }
  1553. }
  1554. purgeMany(&purged, m.rootKind)
  1555. return others
  1556. }
  1557. // the ranges a fill's host still has to let go of (see dropRange)
  1558. dropPending() {
  1559. if (pendingDrops.length == 0) { return null }
  1560. let due = pendingDrops.slice(0)
  1561. pendingDrops = []
  1562. for (d of due) {
  1563. if (d.rootKind == 'shell') {
  1564. if (shell != null) { dropAt(&shell, d, 0) }
  1565. } else if (page != null) { dropAt(&page, d, 0) }
  1566. }
  1567. return null
  1568. }
  1569. dropAt(&m, Hybrid d, Number depth) {
  1570. if (depth >= d.chain.length) {
  1571. dropSitesIn(&m, d.host, d.nodes)
  1572. let purged = []
  1573. for (c of d.kids) { if (c.length > depth) { if (disposeAt(&m, &c, depth)) { purged.push(c) } } }
  1574. purgeMany(&purged, m.rootKind)
  1575. return null
  1576. }
  1577. if (m.kids[d.chain[depth]] == null) { return null }
  1578. dropAt(&m.kids[d.chain[depth]], d, depth + 1)
  1579. return null
  1580. }
  1581. // a node in a range whose host's sites are still to go (dropPending)
  1582. dropDue(Hybrid n) {
  1583. let top = n.getRootNode()
  1584. for (d of pendingDrops) { if (d.nodes.includes(top)) { return true } }
  1585. return false
  1586. }
  1587. // the children whose nodes are this node or stand under it (kidAt files them there)
  1588. kidsFiledIn(Hybrid n, &out) {
  1589. if (n.__hlKidChains != null) { for (c of n.__hlKidChains) { out.push(c) } }
  1590. if (n.nodeType != 1) { return null }
  1591. let w = document.createTreeWalker(n, 4294967295)
  1592. let c = w.nextNode()
  1593. while (c != null) {
  1594. if (c.__hlKidChains != null) { for (k of c.__hlKidChains) { out.push(k) } }
  1595. c = w.nextNode()
  1596. }
  1597. return null
  1598. }
  1599. // Borrow the address read-only through recursion; only m.kids is changed.
  1600. disposeAt(&m, &chain, Number depth) {
  1601. if (depth == chain.length - 1) {
  1602. if (m.kids[chain[depth]] != null) {
  1603. delete m.kids[chain[depth]]
  1604. return true
  1605. }
  1606. return false
  1607. }
  1608. if (m.kids[chain[depth]] == null) { return false }
  1609. return disposeAt(&m.kids[chain[depth]], &chain, depth + 1)
  1610. }
  1611. // a node no longer on the page: not in the document, not in a fragment a walk is
  1612. // still building, not in the slot a shell's rebuild holds aside
  1613. placedOff(Hybrid n) {
  1614. if (n.isConnected) { return false }
  1615. if (n.getRootNode().nodeType == 11) { return false }
  1616. if (detachedSlot != null && detachedSlot.contains(n)) { return false }
  1617. return true
  1618. }
  1619. nextSid() {
  1620. sidNext = sidNext + 1
  1621. return sidNext
  1622. }
  1623. isLive(&m, Hybrid s) {
  1624. for (e of m.sites) { if (e.sid == s.sid) { return true } }
  1625. return false
  1626. }
  1627. // A SITE WHOSE NODES LEFT THE PAGE, found by a repaint. Every range that leaves takes
  1628. // its sites with it (dropRange), so this is a bug: the gates' client raises it as an
  1629. // uncaught exception (the page's error event, what every gate fails on), a page in the
  1630. // field says so on the console; neither paints it.
  1631. staleSite(Hybrid s) {
  1632. let msg = 'hl:web: a repaint found a site whose nodes have left the page (site ' + s.site + ')'
  1633. if (strict) { window.reportError(window.Reflect.construct(window.Error, [msg])) }
  1634. else { console.error(msg) }
  1635. return null
  1636. }
  1637. // A RUN OF TEXT LEAVES BESIDE ELEMENTS OR REGIONS (compile.hl `mixed`): one text node,
  1638. // kept on the element under the run's index so a paint rewrites it and nothing else.
  1639. // `k` null is a text the walk only has to step over (literal, or painted as a site of
  1640. // its own by `textAt`). Built, it is appended. Claimed, it is the text node right
  1641. // after the host's cursor — the last node the walk took there — which the server may
  1642. // have run together with the readable form's line break after it, so it is split off
  1643. // by the value it has now. A run that rendered empty has no node and gets one.
  1644. leafAt(Hybrid host, Boolean cr, Number i, Number k, String text) {
  1645. let t = leafNode(&host, cr, text)
  1646. if (k != null) {
  1647. if (host.__hlLeaves == null) { host.__hlLeaves = {} }
  1648. host.__hlLeaves[k] = t
  1649. }
  1650. return null
  1651. }
  1652. leafNode(&host, Boolean cr, String text) {
  1653. let t = null
  1654. if (cr) {
  1655. t = document.createTextNode(text)
  1656. host.appendChild(&t)
  1657. return t
  1658. }
  1659. let at = host.__hlCur == null ? host.firstChild : host.__hlCur.nextSibling
  1660. if (at != null && at.nodeType == 3 && text != '') {
  1661. if (at.data == text) { t = at }
  1662. else if (at.data.startsWith(text)) { at.splitText(text.length) t = at }
  1663. else {
  1664. // a line break of the readable form in front of it (a filled slot's line)
  1665. let lead = at.data.length - at.data.trimStart().length
  1666. if (lead > 0 && at.data.startsWith(View.newline) && at.data.slice(lead).startsWith(text)) {
  1667. t = at.splitText(lead)
  1668. if (t.data != text) { t.splitText(text.length) }
  1669. }
  1670. }
  1671. }
  1672. if (t == null) {
  1673. t = document.createTextNode(text)
  1674. host.insertBefore(t, at)
  1675. }
  1676. host.__hlCur = t
  1677. return t
  1678. }
  1679. // A TEXT LEAF STANDING IN A LIST (an `if` branch, a `for` body): its own text node, and
  1680. // a site of the member it reads — or of the row it stands in — painted by rewriting it.
  1681. textAt(&m, &host, Boolean cr, Function readFn, &names, &rows, String rk, &reads) {
  1682. let t = leafNode(&host, cr, readFn(&m.instance, &rows))
  1683. if (names.length > 0 || (rk != null && rk != '')) {
  1684. let sid = nextSid()
  1685. m.sites.push({ sid = sid; el = t; site = null; names = names; region = false; text = true; reads = reads; rows = rows; rowKey = rk; read = readFn; })
  1686. if (t.__hlSid == null) { t.__hlSid = sid } else { t.__hlSidMore = (t.__hlSidMore == null ? '' : t.__hlSidMore) + sid + ',' }
  1687. }
  1688. return null
  1689. }
  1690. paintText(&m, &s) {
  1691. let f = s.read
  1692. let v = f(&m.instance, &s.rows)
  1693. let t = s.el
  1694. if (t.data != v) { t.data = v }
  1695. return null
  1696. }
  1697. // ---- a `for`: the region, its rows, each between its marks -------------------------
  1698. forAt(&m, &o, &host, Number i, String site, String rowName, Function listFn, &rows, String rk, &fill, Boolean cr, &names, &reads) {
  1699. let start = markAt(&host, cr, true)
  1700. regionAt(&m, &host, site, &rows, rk, &fill, true, rowName, listFn, &names, &start, null, &reads)
  1701. // (the box lives on the open mark from the start and every row is written through it in place: `let box = ...` / `start.__hlBox = box`
  1702. // each copied the box with every row's entry and snapshot, W110)
  1703. start.__hlBox = { keys = []; rows = {}; }
  1704. let entries = listFn(&m.instance, &rows)
  1705. let body = walkOf(m.key, 'b', site)
  1706. // SHIP LESS (W173): the list is a server-only member the first load's seed left out (`m.skipped`). The server's rows
  1707. // stand between the marks and are taken as they are; the first value that arrives builds them (paintFor clears them first)
  1708. if (!cr && entries == null && m.skipped != null && names != null && names.length > 0) {
  1709. let left = false
  1710. for (nm of names) { if (m.skipped.includes(nm)) { left = true } }
  1711. if (left) {
  1712. start.__hlBox.unclaimed = true
  1713. start.__hlEnd = closeOf(start)
  1714. host.__hlCur = start.__hlEnd
  1715. let span = 0
  1716. for (n of between(start)) { if (n.nodeType == 1) { span = span + 1 } }
  1717. return i + span
  1718. }
  1719. }
  1720. if (entries != null) {
  1721. let keys = listKeys(&entries)
  1722. let ri = 0
  1723. for (entry of entries) {
  1724. let inner = rows + {}
  1725. inner[rowName] = shareOf(&entry)
  1726. let rs = markAt(&host, cr, true)
  1727. let out = run(body, &m, &o, &host, cr ? 0 : i, &inner, rk + '#' + keys[ri], &fill, cr, null)
  1728. if (!cr) { i = out }
  1729. rs.__hlEnd = markAt(&host, cr, false)
  1730. start.__hlBox.keys.push(keys[ri])
  1731. // (the row carries a private copy of the record it was built from (`snap`), as buildRow's rows do: without it the FIRST paint
  1732. // after a load — the page's rows are built here, or claimed from the server's — took every row for changed
  1733. // and updated, rebound and reseated all of them: ~100 ms for the first append to a chat of 250 rows, w78)
  1734. start.__hlBox.rows[keys[ri]] = { start = rs; entry = entry; snap = snapOf(&entry); }
  1735. ri = ri + 1
  1736. }
  1737. }
  1738. start.__hlEnd = markAt(&host, cr, false)
  1739. return i
  1740. }
  1741. // an `if`: the branch that stands, between its marks
  1742. ifAt(&m, &o, &host, Number i, String site, Function condFn, &rows, String rk, &fill, Boolean cr, &names, &fnames, &reads) {
  1743. let start = markAt(&host, cr, true)
  1744. regionAt(&m, &host, site, &rows, rk, &fill, false, null, condFn, &names, &start, &fnames, &reads)
  1745. let side = condFn(&m.instance, &rows) ? 't' : 'e'
  1746. start.__hlSide = side
  1747. let out = run(walkOf(m.key, side, site), &m, &o, &host, i, &rows, rk, &fill, cr, null)
  1748. start.__hlEnd = markAt(&host, cr, false)
  1749. return out
  1750. }
  1751. // A REGION SITE carries what the patch needs and nothing else: the names its list or
  1752. // its condition reads (the compiler's answer, by this site), the read itself as the
  1753. // generated closure, and its open mark — the region itself, one per row it stands in.
  1754. regionAt(&m, &host, String site, &rows, String rowKey, &fill, Boolean isFor, String rowName, Function readFn, &names, &start, &fnames, &reads) {
  1755. // a row-scoped read is its row's, and the language resolved it as one, so the
  1756. // compile step names none here: an empty set is a region no member can move. INSIDE
  1757. // A ROW it is still registered, with no names: the row's new record moves it
  1758. // (reseatRows, ticket #86). Outside one nothing ever can.
  1759. if (names == null) { names = [] }
  1760. if (names.length == 0 && (rowKey == null || rowKey == '')) { return null }
  1761. let held = null
  1762. if (fill != null) { held = fill + {} held.detached = true }
  1763. let sid = nextSid()
  1764. 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; })
  1765. if (start != null) { if (start.__hlSid == null) { start.__hlSid = sid } else { start.__hlSidMore = (start.__hlSidMore == null ? '' : start.__hlSidMore) + sid + ',' } }
  1766. return null
  1767. }
  1768. // ---- a composed child --------------------------------------------------------------
  1769. // The reference's own description is written at its use site by the compile step: what
  1770. // it binds, what it overwrites, the classes it puts on the child's roots.
  1771. kidAt(&m, Hybrid host, Number i, Hybrid spec, Hybrid rows, String rk, Hybrid fill, Boolean cr, Hybrid opt) {
  1772. let kk = spec.kid + rk
  1773. if (m.kids[kk] == null) {
  1774. let minted = mintFrom(&m, spec, rows, childChain(m.chain, kk))
  1775. if (minted == null) { return i }
  1776. m.kids[kk] = minted
  1777. mountQueue[] = { chain = minted.chain; root = m.rootKind; }
  1778. }
  1779. bindFrom(&m.kids[kk], &m, spec, rows)
  1780. if (cr) { m.kids[kk].sites = [] }
  1781. m.kids[kk].chain = childChain(m.chain, kk)
  1782. m.kids[kk].rootKind = m.rootKind
  1783. let firstAt = cr ? host.children.length : i
  1784. // WHAT A REFERENCE OVERWRITES REACHES THE FIRST ELEMENT, however deep. A child
  1785. // whose View is a bare reference to another component renders no element of its
  1786. // own, so the events the host overwrote travel on through it — the old hl:web kept that in
  1787. // a field that the first element consumes; here it rides on the option the walk is
  1788. // handed, and a reference with ons of its own replaces it.
  1789. let over = []
  1790. if (spec.ons != null && spec.ons.length > 0) { for (o of spec.ons) { over.push(o.event) } }
  1791. else if (opt != null && opt.over != null) { over = opt.over }
  1792. let kidOpt = { over = over; classes = spec.classes; }
  1793. let f = walkOf(m.kids[kk].key, 'v', null)
  1794. // a child composed straight onto a fragment has its regions on the host the fragment
  1795. // lands in: the fragment names it, for the re-homing (rehome)
  1796. if (cr && host.nodeType == 11) {
  1797. let onFrag = host.__hlOnFrag == null ? [] : host.__hlOnFrag
  1798. onFrag.push(m.kids[kk].chain)
  1799. host.__hlOnFrag = onFrag
  1800. }
  1801. let nodesBefore = host.childNodes.length
  1802. let curBefore = host.__hlCur
  1803. let out = run(f, &m.kids[kk], &m, &host, cr ? 0 : i, {}, '', fillFor(&m, spec, rows, rk, fill), cr, &kidOpt)
  1804. if (!cr) { i = out }
  1805. // THE NODES THE CHILD PUT ON ITS HOST CARRY ITS ADDRESS: when a range holding them
  1806. // leaves the page, the child goes with it (dropRange)
  1807. let made = []
  1808. if (cr) {
  1809. let k = nodesBefore
  1810. while (k < host.childNodes.length) { made.push(host.childNodes[k]) k = k + 1 }
  1811. } else {
  1812. let n = curBefore == null ? host.firstChild : curBefore.nextSibling
  1813. let stop = host.__hlCur == null ? null : host.__hlCur.nextSibling
  1814. while (n != null && n != stop) { made.push(n) n = n.nextSibling }
  1815. }
  1816. for (n of made) {
  1817. let filed = n.__hlKidChains == null ? [] : n.__hlKidChains
  1818. filed.push(m.kids[kk].chain)
  1819. n.__hlKidChains = filed
  1820. }
  1821. if (cr || m.kids[kk].bindings.length == 0) { m.kids[kk].bindings = [] bindKids(&m.kids[kk], m.kids[kk].view) }
  1822. let roots = rootsBetween(host, firstAt, cr ? host.children.length : i)
  1823. refOnsFrom(&m, spec, roots, rows)
  1824. // (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)
  1825. for (el of roots) { el.__hlKid = m.key }
  1826. return i
  1827. }
  1828. // the value a binding of this reference carries, off the host instance
  1829. specValue(Hybrid b, &m, Hybrid rows) {
  1830. if (b.text != null) { return b.value }
  1831. if (b.member != null) { return view.value({ k = 'member'; name = b.member; }, &m.instance, &rows) }
  1832. if (b.ref != null) {
  1833. let inst = m.instance
  1834. let f = b.ref
  1835. return f(&inst, &rows)
  1836. }
  1837. return null
  1838. }
  1839. // A CHILD A REGION BUILDS is born with its address: the host's chain and its own key.
  1840. // Every patch, and every late patch a function or a waiting handler of it asks for, is
  1841. // filed and cancelled by that address (tickets #98, #99).
  1842. mintFrom(&m, Hybrid spec, Hybrid rows, Hybrid chain) {
  1843. let bp = planOf(spec.key)
  1844. if (bp == null) { return null }
  1845. let args = {}
  1846. for (b of spec.bindings) { if (!hasSetter(spec.key, b.name)) { args[b.name] = specValue(b, &m, rows) } }
  1847. // A CHILD MINTED LATE takes the current route like one built at boot (#197), by the
  1848. // same `{ path, params, pattern, query }` the server hands construction
  1849. if (bp.route == true) {
  1850. let cur = currentRoute()
  1851. if (cur != null) { args.route = cur }
  1852. }
  1853. // the host's own instance, not a copy: this child's `$parent` is the instance whose View placed it
  1854. let host = m.instance
  1855. // THE SERVER VALUES of a kid with server-realm members (D1): asked for with the arguments it was bound
  1856. let supplied = navigationReply(chain, m.rootKind)
  1857. if (supplied != null) {
  1858. for (k of supplied.state.keys()) { if (!args.keys().includes(k)) { args[k] = supplied.state[k] } }
  1859. } else if (offline != null && offline.localRoute(location.pathname) != null && (reach == 'down' || seed.local == true || (navLate != null && navLate.local == true))) {
  1860. boundInputs = args
  1861. for (b of spec.bindings) { boundInputs[b.name] = null }
  1862. localState = offline.mountState(spec.key, boundInputs, chain, m.rootKind, location.pathname + location.search)
  1863. for (k of localState.keys()) { if (!args.keys().includes(k)) { args[k] = localState[k] } }
  1864. } else if (bp.srv != null) {
  1865. let sv = emit server values(spec.key, askArgs(args, args.keys()), location.pathname + location.search)
  1866. if (sv != null) { for (k of sv.keys()) { args[k] = sv[k] } }
  1867. }
  1868. if (bp.styleHandles != null) { args.Style = bp.styleHandles }
  1869. let inst = hlLoad(moduleUrlOf(spec.key), args, host)
  1870. registerMount(inst, spec.key, chain, m.rootKind)
  1871. inputs = []
  1872. for (b of spec.bindings) { inputs.push(b.name) }
  1873. return { inputs = inputs; key = spec.key; instance = inst; view = bp.view; sites = []; isShell = false; kids = {}; bindings = []; chain = chain; rootKind = m.rootKind; given = {}; }
  1874. }

Only the first lines are shown.

Branches

Latest commits

  • 05c3578c|||PR Keep each playing row bound to the shell song on day76mre
  • eaa7e6d6Vendor Hybriel day76 for live parent member readsmre
  • 0923398bMerge branch 'records-1124d' into mainJukebox
  • 78f0cc86|||PR records 2026-11-24: inbox-thread rule, "Not playing" confirmed and closedmre
  • c1b153c4Merge branch 'records-1124c' into mainJukebox
  • d7b5e780|||PR Records 2026-11-24 (2): live day72, PR #19 merge, #10 newsmre
  • 43b564dbMerge branch 'records-1124b' into mainJukebox
  • fa86b08c|||PR Records 2026-11-24: LOG, STATUS, missions 020-023mre
  • 0a2ae3daMerge remote-tracking branch 'origin/records-1123' into records-1124mre
  • 9a48cfcaMerge branch 'vendor-theme' into mainJukebox
  • 170d3735Merge branch 'code-order-2' into mainJukebox
  • 3f1918a7|||PR Re-sync layouts theme 4099e64 with Segoe UI firstmre
  • 2e7f6a43Vendor virtual-list 489afcf from components.hybrielmre
  • 0ba85799Merge branch 'reset-classes' into mainJukebox
  • 502eeed5jukebox#20: vendor virtual-list initial resetKey baseline fixmre
  • 6d5ce287|||PR jukebox#9 Centralize songs table reads and writes in db.hlmre
  • dcca21abjukebox#8 Move copies and queue logic into their topicsmre
  • 3b76651cjukebox#20: update virtual-list README pin and resetKey optionsmre
  • bc09e1e8|||PR jukebox#20: reset virtual lists through resetKey (partial validation)mre
  • a3796dc5Records: live step waits for idlemre