gitoriaLog in with ident

components

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Commit317bd09f317bd09fdeploy.sh: back up live storage/.sessions/.env before every deploy (newest 5 kept)mre317bd09f/plugins/web/client.hl

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

Only the first lines are shown.

Branches

Latest commits

  • 317bd09fdeploy.sh: back up live storage/.sessions/.env before every deploy (newest 5 kept)mre
  • becbd59bcomponents#13: modal dialog (<dialog> based, focus wrap, backdrop/Esc/x close with reason, scroll lock, footer buttons)mre
  • 367dd19adeploy.sh: never send .git or .gitignore to Byrodinmre
  • 4b4dabe5State of 2026-09-27, before the move to gitoriamre