gitoria

jukebox

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Main branchmain10f8a8c8Merge branch 'code-order' into mainJukeboxmain/plugins/web/client.hl

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

Only the first lines are shown.

Branches

Latest commits

  • 10f8a8c8Merge branch 'code-order' into mainJukebox
  • 204fc828Merge branch 'day72' into mainJukebox
  • 95f5faae|||PR jukebox#7 Drop needless let declarationsmre
  • 33072bb5|||PR Record day72 gates and Chrome proofmre
  • 95f2cd73|||PR Use typed parent methods for screen playback and local server facesmre
  • 6422a020Sync media-player at 51c3818mre
  • b582ba1cVendor complete Hybriel day72 plugin setmre
  • 02dccbc9Merge branch 'records-1119' into mainJukebox
  • a39e1c23|||PR Records: missions 013-015, reconnect fix livemre
  • fc7db075Merge branch 'reconnect-retry' into mainJukebox
  • ac6f4c6fL2: plain declaration for a in pickedNextmre
  • 2f335086Review round 2: only an explicit queue pick drops pend (not the automatic advance); jb23 records every source changemre
  • 3eb6695fReview fixes: action generation, queue pick clears pend, Previous/Next retry the decided request, typed handlersmre
  • 7a53c0c2|||PR A tap lost to a dead socket plays after reconnect (mission 015)mre
  • 1f0cd77bMerge branch 'records-day41' into mainJukebox
  • 67be229f|||PR Records: day41 live (PR #4), mission 012, statusmre
  • 0bb027daconductor: caramboleyo is the user, not owner/creatorApollo
  • 04f5d9d5Merge branch 'day41' into mainJukebox
  • 8ed6da45|||PR README: media-player pin df9e7dfmre
  • d5d45fc3|||PR media-player df9e7df (repeat-one fix), sync pin and SOURCEmre