gitoria

notes

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Commitc08c655ac08c655anotes 013: theme re-copied from layouts 76f99f6 (menu marks the current page), current = true on the menu item, e2e marker checks, reportmrec08c655a/plugins/web/client.hl

154.6 KB

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

Only the first lines are shown.

Branches

Latest commits

  • c08c655anotes 013: theme re-copied from layouts 76f99f6 (menu marks the current page), current = true on the menu item, e2e marker checks, reportmre
  • f431bdf8notes mission 011: notes on the layouts theme (ListFirst shell), styles cut, check-theme gate, E2E extended; reportmre
  • 1a8603d1notes mission 011 WIP: deploy.sh gate summary also matches check-theme, browser.mjs logout via the user menumre
  • dae2e508notes mission 011 WIP: theme dbe3de7, shell on AppHeader/MainMenu/UserMenu/Sidebar + ListFirst, styles cut to the app's own, check-theme gate, e2e auditmre
  • fd36da27notes mission 010: the note editor is the Hybriel MdEditor block (components.hybriel 1442e58, verbatim); md-editor.js, its route, script tag and offlineFiles retired; gate 66/0, realdata-offline 12/0, round-trip and Chrome E2E tests; report 010mre
  • efa92170notes tests/identkit.mjs: refuse a taken ident port, cold-wait deadline, emit, identities; mission 009 reportmre
  • f3dec0f1Merge branch 'w7'mre
  • d1cf966dre-vendor hybriel 97bcf128: offlineFiles for the editor script, 44 px taps, 390 px offline checks, mission 008mre
  • 4a610a21paths: projects moved into /media/STORAGE/projects/WorldAPI/mre
  • eeaea980report 007: say which runs included the removed checkmre
  • 8a8ad9banotes mission 007: report, LOG, STATUSmre
  • 2cce9c96code order: plain declarations where never reassigned (letcount 0 never); gate: scan every IndexedDB at log-out, soft mode for old-code runs, drop a check that could not failmre
  • 7f6a4090README: offline in Hybriel (hl:web offline, continuation, known md-editor gap); gate waits report instead of crash; realdata-offline checkmre
  • 632223f2notes#4: delete notes-offline.js and sw.js (hl:web's generated worker and kept state replace them)mre
  • 52a2acadgate: offline checks on hl:web's worker/queue, Chrome offline via CDP (reload offline first), one-offline conflict, log-out forgets the kept copymre
  • e5785b03notes#4: the notes page in Hybriel — hl:web offline = [Notes], queued faces notesPut/notesDrop, push notesChanged, value-form notesPull on a tick; notes-offline.js/sw.js no longer loaded or routedmre
  • 510aff75notes#4: server continues a run of saves of one login (by + since), loser keeps writing into its copy; notesFor listmre
  • 0176c4b5mission brief 007mre
  • 06cfa870notes mission 006: re-vendor hybriel 0f396652 (static), reportmre
  • 6c07bd91mission brief w6mre