gitoria

notes

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Commita5c27cb6a5c27cb6Allow real edits back to earlier text and honor configured identAtlasa5c27cb6/plugins/web/client.hl

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

Only the first lines are shown.

Branches

Latest commits

  • a5c27cb6Allow real edits back to earlier text and honor configured identAtlas
  • 15c46ced|||PR Preserve note edits, conflict bases and visible historyAtlas
  • 4c6e0bf6Merge branch 'notes13-day61' into mainAtlas
  • eb51864f|||PR Back/Forward via navigate, server drafts, Hybriel day61Atlas
  • 3537cf7eMerge branch 'vendor-day59' into mainAtlas
  • c13d188b|||PR Vendor Hybriel day59Atlas
  • 24c95433Merge branch 'notes17-ghost-note' into mainAtlas
  • ae1075b2Preserve rejected drafts during note ID adoptionAtlas
  • 383cce23|||PR Prevent saved local edits from restoring deleted notesAtlas
  • 99ca1cf6Merge branch 'vendor-day56' into mainAtlas
  • 649cef37|||PR Vendor Hybriel day56Atlas
  • aadd0abcMerge branch 'hl-standard-2' into mainAtlas
  • 52ffac9f|||PR Keyboard and reload checks for the notes gate (HL-STANDARD F21, F5)Atlas
  • 617ee8c0Merge branch 'hl-standard' into mainAtlas
  • 452458ee|||PR Type the function parameters of notes' own .hl files (HL-STANDARD L10)Atlas
  • 23758cd6Re-vendor complete Hybriel plugins and runtime to day44mre
  • 5d7cc700Backup tar: --hard-dereference, so mpackdb sidecars are never stored as hard links (Tracker's finding)mre
  • 3e07b1cfVendor complete Hybriel day39 plugin sources and librariesmre
  • d7366702Check session cookie flags after login and assert anonymous GET stays cookielessmre
  • 16bc8fd8Re-vendor Hybriel day38b with the mpackdb store-open race fixmre