gitoriaLog in with ident

ident

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Commit81b15b7b81b15b7bState of 2026-09-27, before the move to gitoriamre81b15b7b/plugins/web/client.hl

109.6 KB

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

Only the first lines are shown.

Branches

Latest commits

  • 81b15b7bState of 2026-09-27, before the move to gitoriamre