gitoria

kunibert

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Commit56e70dcb56e70dcbrecords: review time limit 1800 s (routger 132)mre56e70dcb/plugins/web/client.hl

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

Only the first lines are shown.

Branches

Latest commits

  • 56e70dcbrecords: review time limit 1800 s (routger 132)mre
  • c3a304c5Merge branch 'job-timeout' into mainKunibert
  • 402bfeb0|||PR runner: the model run uses the job's time limit (jobTimeoutSeconds), not a fixed 900 smre
  • 8d34ca33records: repo rename (gitoria#53)mre
  • 1e05cb3fMerge branch 'repo-rename' into mainKunibert
  • 6ee0d2e9|||PR intake: match a delivery by repo.id and signature, not URLs (gitoria#53 rename)mre
  • 900ffcd4status: routgermre
  • 59b0b793log: routger merge waitmre
  • e52f094alog: routger intake check (hycon#122)mre
  • f979027frecords: design rule livemre
  • 71efaf84Merge branch 'design-guard' into mainKunibert
  • c0656581|||PR Flag removal of a documented design as major unless his recorded yes is linked; rules version 5mre
  • 901cdd75records: L10 update 2 livemre
  • 4a68016bMerge branch 'hl-standard-l10b' into mainKunibert
  • 246d0f30|||PR HL-STANDARD L10 update (hybriel ab293e5a), rules version 4mre
  • 1aa4d64crecords: HL-STANDARD L10 update livemre
  • 2b04c240Merge branch 'hl-standard-l10' into mainKunibert
  • 88c7b09d|||PR HL-STANDARD L10 update (hybriel 5885d688), rules version 3mre
  • 00869ecbrecords: gitoria#50 step 3 livemre
  • f97a0e5fMerge branch 'hl-standard' into mainKunibert