gitoria

calendar

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Commit9bf3c38b9bf3c38bcalendar mission 008: re-vendor Hybriel f9833544 (gates old = new); Web Push stopped: hl:crypto half missing on mastermre9bf3c38b/plugins/web/client.hl

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

Only the first lines are shown.

Branches

Latest commits

  • 9bf3c38bcalendar mission 008: re-vendor Hybriel f9833544 (gates old = new); Web Push stopped: hl:crypto half missing on mastermre
  • 186f969bcalendar mission 007: signed-in gate for the first-pointer race (fails on 3c5604f), README theme section, reportmre
  • ba9b4955calendar mission 006: first pointer event no longer re-runs the month (stale overwrite race), gate check, e2e settings cleanup, reportmre
  • bd730759calendar mission 006: theme move (WIP): brief, report, LOG, STATUSmre
  • b117b153calendar mission 006 WIP: reminder row fields keep 44 px; e2e script flagsmre
  • 53e3b0debrowser gate: Log out through the user menu, theme colour rgb(15, 20, 25)mre
  • 90bf9e2ecalendar mission 006 WIP: theme dbe3de7, theme shell (AppHeader/MainMenu/UserMenu/Sidebar/ContentFirst), styles cut to the app's own rules, check-theme gate, e2e toolsmre
  • 3c5604f9identkit: refuse a taken ident port, cold-start deadline, abort on dead ident, clear no-code error (as notes)mre
  • 4996bbe7paths: projects moved into /media/STORAGE/projects/WorldAPI/mre
  • f5bf0803calendar mission 004: re-vendor Hybriel to the shared static build 0f396652; compose cache volume + tmpfs; notify-paths gate in deploy.sh; gate start waits 150 s; reportmre
  • eb86526fmission brief 004mre
  • 2f953b16deploy.sh: wait up to DEPLOY_URL_WAIT (120 s) for 200 after the restart, as the other apps (cold compile, hybriel#148)mre
  • 9078e1b7calendar mission 003 (2/2): report, LOG, STATUS (cause: timers only in an open, front, touched page; gate old 5/2 new 7/0; Hybriel gaps Web Push + page-shown hook, STOP)mre
  • 31ffe910calendar mission 003 (1/2): calendar#9 — missed reminders shown when the app is back, timers set again when it is shownmre
  • 26c997d3mission brief 003mre
  • c6809c76calendar mission 002: report, LOG, STATUS (test bug; fixed gate 78/0 at 00:30 05:40 12:00 19:59 20:01; 23:30 not run, quota stop)mre
  • 00f72783calendar mission 002 (2/2): TEST bug — the reminder steps get their own identity (carol): alice's all-day Vacation (20th-22nd) from the events steps added 2 reminders from the 12th 20:00 to the 19th 23:00; Tokyo check no longer skipped in the Tokyo eveningmre
  • 54fb0ce1calendar mission 002 (1/2): gate clock override GATE_CLOCK=HH:MM (this process and every page get Date shifted to that local time today)mre
  • c838ee79mission brief 002mre
  • f2bc67ecdocker-compose: init: true (hybriel#156, PID 1 ignored SIGTERM, every restart waited 10 s)mre