gitoriaLog in with ident

calendar

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Commit99c7334699c73346antcolony#40: history (LOG.md), worker briefs (missions/) and reports moved here from antcolony, numbered per project; old numbers in antcolony docs/mission-map.mdmre99c73346/plugins/web/client.hl

139.7 KB

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

Only the first lines are shown.

Branches

Latest commits

  • 99c73346antcolony#40: history (LOG.md), worker briefs (missions/) and reports moved here from antcolony, numbered per project; old numbers in antcolony docs/mission-map.mdmre
  • 76edaa62calendar: Hybriel master ff51cf46 (re-vendor round, static workaround removed)mre
  • 90a3fc2cdeploy.sh: back up live storage/.sessions/.env before every deploy (newest 5 kept)mre
  • 6722b72ddeploy.sh: never send .git or .gitignore to Byrodinmre
  • be099807State of 2026-09-27, before the move to gitoriamre