gitoria

jukebox

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Main branchmain10f8a8c8Merge branch 'code-order' into mainJukeboxmain/plugins/web/compile.hl

64.5 KB

  1. // plugins/web/compile.hl — THE FRAMEWORK COMPILES EACH COMPONENT.
  2. //
  3. // Mission 313 (the creator, 15 Sep 14:30: "clientside interpreter + table against
  4. // component code per component, no tables needed"). The old hl:web ships ONE generic client
  5. // that walks a tree the seed carries: it pairs elements with nodes, asks a table which
  6. // members each element shows, asks `view.value` what each bound spot holds, and does it
  7. // again on every paint. hl:web ships the ANSWERS instead — this file writes each
  8. // component's own code, once, where the old hl:web would have walked.
  9. //
  10. // WHAT IS EMITTED, per component, beside the class `hlJs` compiled:
  11. //
  12. // v(c,m,o,host,i,rows,rk,fill,cr,opt) the component's View, unrolled: one
  13. // statement per element, per handler, per
  14. // bound spot. `cr` false CLAIMS the server's
  15. // DOM (take host.children[i], step on), `cr`
  16. // true CREATES it — the two walks the old hl:web
  17. // spells out separately, which differ only in
  18. // where an element comes from.
  19. // b["<for site>"] one `for` body — the row factory the keyed
  20. // region builds a row with.
  21. // t/e["<if site>"] an `if`'s two branches.
  22. // f["<reference site>"] the fragment this component writes into a
  23. // child's `slot` — built in THIS frame, which
  24. // is why it is this component's code.
  25. // p["<element site>"] the paint statements: `p` writes what one
  26. // member feeds (the old hl:web's paint(&m,s,name)),
  27. // `r` rewrites a row's element where the DOM
  28. // does not already hold it (rowPaint).
  29. //
  30. // The generated code calls a FIXED runtime (client.hl) for everything that is not this
  31. // component: the mount records, the keyed region diff, the binding edges, the
  32. // derivations, the socket, navigation. It never looks anything up in a table — the
  33. // names, the sites and the write sets are written into the statements.
  34. //
  35. // It is TEXT the framework produces, served from memory beside the module (WebFramework
  36. // `module`), never a JavaScript file under plugins/.
  37. import { newline, tab } from './view.hl'
  38. import HlwView from './view.hl'
  39. import HlwViewServer from './viewserver.hl'
  40. // The framework supplies its one graph-key → browser-key mapping. Reflection and
  41. // SSR keep the original key; only emitted component identities use this function.
  42. browserKeyOf = null
  43. // ---- the emitted half --------------------------------------------------------------
  44. module(gen, key, nodes, fnTable, fills) {
  45. literalFns = []
  46. fns = [] // the sub-walks: row bodies, if branches, fills
  47. done = {}
  48. rowVars = []
  49. tbl = tableOf(gen, key) // what the language says about this file, read once
  50. regions = regionIndex(tbl) // a `for`'s list reads, an `if`'s condition reads
  51. publicKey = browserKeyOf(key)
  52. root = walkTop(publicKey, nodes)
  53. // THE NAMED-REGION FILLS this View's root writes (`side { … }`): each is a sub-walk of THIS
  54. // component (its members, its handlers), run by the browser into the region a level above holds
  55. let fillNames = '{'
  56. let fillConds = '{'
  57. if (fills != null) {
  58. for (fl of fills) {
  59. sub(publicKey, fl.children, 'R', fl.site)
  60. fillNames = fillNames + (fillNames == '{' ? '' : ',') + str(fl.name) + ':' + str(fl.site)
  61. // a conditional fill (`if (x) { side { … } }`): the condition, read off the filling instance
  62. if (fl.cond != null) { fillConds = fillConds + (fillConds == '{' ? '' : ',') + str(fl.name) + ':async function(inst,r){return ' + rawRead(fl.cond) + ';}' }
  63. }
  64. }
  65. fillNames = fillNames + '}'
  66. fillConds = fillConds + '}'
  67. let src = ';(function(){var g=(typeof globalThis!=="undefined"?globalThis:window);'
  68. src = src + 'var C=(g.__hlC=g.__hlC||{});'
  69. // the element a claim takes or a create makes — the one shape both walks share; a create
  70. // inside an svg (or an svg itself) is made in the SVG namespace, as the parser makes it
  71. // THE PRELUDE, one per module: the element a claim takes or a create makes, and the
  72. // two reads. A read written out in full — `(r["title"]!=null?r["title"]:inst["title"])`
  73. // — is 45 bytes and a component's View holds dozens of them; named, it is 16. The
  74. // rule is the same rule (a `for` row variable in scope wins over a member of the
  75. // same name, and a field path walks into it), spelled once.
  76. // A claim also moves the host's CURSOR — the last node the walk took there — which is
  77. // where a text leaf and a region's mark are looked for next (client.hl `leafNode`,
  78. // `markAt`).
  79. // MISSION 505: the five helpers (A, S, X, RV, RF) are bound off the runtime text (`paintHelpers` below) instead of written
  80. // into every module
  81. src = src + 'var A=g.__hlP.A,S=g.__hlP.S,X=g.__hlP.X,RV=g.__hlP.RV,RF=g.__hlP.RF,N=g.__hlP.N,TX=g.__hlP.TX;'
  82. src = src + 'var B={},T={},E={},F={},P={},D={},R={};'
  83. src = src + 'var L=[' + literalFns.join(',') + '];'
  84. // ONE FUNCTION PER LIST, however many sites reach it: a nested walk is written once
  85. // and named — emitting it per site made the reference app's home page 215 KB of the
  86. // same code over and over.
  87. let wi = 0
  88. for (f of fns) {
  89. wi = wi + 1
  90. let name = 'w' + wi
  91. src = src + 'var ' + name + '=' + f.src + ';'
  92. for (site of f.sites) { src = src + f.slot + '[' + str(site) + ']=' + name + ';' }
  93. }
  94. let paints = []
  95. collectPaints(&paints, nodes)
  96. for (e of paints) { src = src + 'P[' + str(e.site) + ']={p:' + e.paint + ',r:' + e.row + ',reads:' + e.reads + '};' }
  97. src = src + 'C[' + str(publicKey) + ']={v:' + root + ',b:B,t:T,e:E,f:F,p:P,d:D,r:R,rn:' + fillNames + ',rc:' + fillConds
  98. // THE ANSWERS A LOOKUP STILL NEEDS, and only those. A local event's write set stands
  99. // at its own listener and a region's names at its own region — written into the
  100. // call. These three are asked for by NAME at run time and cannot be: an inbound
  101. // frame names its event, a routine handed down names the member that holds it, and
  102. // a write set names the derivations that follow it. `on` is the one thing run FROM the
  103. // module's own scope: the language's instance-scoped handler (`on page.ev`, the instance's
  104. // own bus: runtime `hlInstanceBus`) with the event named at run time, which client.hl
  105. // `wireUp` registers for a page (#193). The bus class is read off the instance's own class
  106. // (`static __events__`): a module imports no `hlScopedBus` unless it writes an `on x.y`, and
  107. // a minified module renames `EventBus`.
  108. src = src + ',ev:' + eventMap() + ',mw:' + memberMap() + ',hf:' + handlerFeeds() + ',mt:' + methodMap() + ',dv:' + derivList() + ',fn:' + fnMap(fnTable) + ',on:g.__hlP.O};'
  109. return src + '})();' + newline
  110. }
  111. // MISSION 505: THE SHARED PRELUDE, once per page. The five helpers every module's paint text calls — the element a claim
  112. // takes or a create makes (A), the text of a value (S), a region's sub-walk (X), the two reads (RV, RF) — were written
  113. // into every module: 699 bytes, 25 times on the reference app's start page. They are appended to the runtime text the
  114. // framework serves (WebFramework `runtime`), as `globalThis.__hlP`, and a module binds them by name (`module` above):
  115. // every module imports the runtime first, so they are there when its paint text runs. The two texts must agree on the
  116. // names; this is the only place the helpers are written.
  117. paintHelpers() {
  118. let s = ';(function(){var g=(typeof globalThis!=="undefined"?globalThis:window);var P=(g.__hlP=g.__hlP||{});'
  119. s = s + 'P.A=function(cr,host,i,tag){if(cr){if(tag==="svg"||(host.namespaceURI==="http://www.w3.org/2000/svg"&&host.localName.toLowerCase()!=="foreignobject")){return document.createElementNS("http://www.w3.org/2000/svg",tag);}return document.createElement(tag);}var e=host.children[i];if(e!=null){host.__hlCur=e;}return e;};'
  120. s = s + 'P.S=function(v){return v==null?"":""+v;};'
  121. s = s + 'P.X=async function(t,r,q){return await g.__hlX(t,q,r);};'
  122. s = s + 'P.RV=function(r,q,n){return r[n]!=null?r[n]:q[n];};'
  123. s = s + 'P.RF=function(r,q,n,p){var v=P.RV(r,q,n);for(var k=0;k<p.length;k++){if(v==null)return null;v=v[p[k]];}return v;};'
  124. // W200: the element idiom's fixed part (claim or create, the failed-claim report, the row/site/key stamp and the literal), a
  125. // build walk's text node, and the instance-scoped handler every module's `on:` names (client.hl `wireUp`)
  126. s = s + 'P.N=function(c,cr,host,i,tag,rows,site,key,lit){var el=P.A(cr,host,i,tag);if(el==null){c.acqFail(tag,host);return null;}el.__hlRows=rows;el.__hlSite=site;el.__hlKey=key;el.__hlLit=lit;return el;};'
  127. s = s + 'P.TX=function(h,t){h.appendChild(document.createTextNode(t));};'
  128. s = s + 'P.O=function(i,e,f){if(!Object.prototype.hasOwnProperty.call(i,"__instanceEvents__")){Object.defineProperty(i,"__instanceEvents__",{value:new (i.constructor.__events__.constructor)()});}i.__instanceEvents__.on(e,f);};'
  129. // Ordinary methods have no fnReturned announcement. Preserve synchronous returns and
  130. // callable metadata while notifying the mount of the method's compiled write set.
  131. s = s + 'P.M=function(i,t,done){if(i.__hlMethodPaint)return;Object.defineProperty(i,"__hlMethodPaint",{value:true});for(const n of Object.keys(t)){const f=i[n];if(typeof f!=="function")continue;const w=function(...a){const r=f.apply(this,a);if(r instanceof Promise)return r.then(v=>{done(n);return v;});done(n);return r;};Object.assign(w,f);w.__hlBound=f;Object.defineProperty(i,n,{value:w,writable:true,configurable:true});}};'
  132. s = s + 'P.L=function(u){return import(u);};'
  133. return s + '})();'
  134. }
  135. tbl = null
  136. regions = {}
  137. // WHAT A FUNCTION VALUE WRITES, by the site it was made at (tickets #98, #99): the
  138. // module announces a function's return with its site, and the browser repaints this
  139. // set — the members it writes, closed over the methods it calls and the events it
  140. // emits, the same closure a handler's set gets. A function that writes nothing has
  141. // no entry.
  142. fnMap(fns) {
  143. let bySite = {}
  144. if (fns != null) {
  145. for (f of fns) {
  146. let names = closeWrites(&tbl, f.writes, f.reads)
  147. if (names.length > 0) { bySite[f.site] = names }
  148. }
  149. }
  150. return mapOf(bySite)
  151. }
  152. // what a DECLARED handler writes, by event: one entry per event name, unioned
  153. eventMap() {
  154. let byEvent = {}
  155. for (h of tbl.handlers) {
  156. if (!h.nested) {
  157. let have = byEvent[h.event] == null ? [] : byEvent[h.event]
  158. for (w of closeWrites(&tbl, h.writes, h.reads)) { if (!have.includes(w)) { have.push(w) } }
  159. byEvent[h.event] = have
  160. }
  161. }
  162. return mapOf(byEvent)
  163. }
  164. // WHAT A DECLARED HANDLER'S OWN WRITES ARE FED BY (#404): per member a declared `on` handler writes
  165. // in its own body, the members that same body reads DIRECTLY. The offline store files a member under
  166. // the url when a route parameter feeds it; a feed a handler fills from what it was told about THIS page
  167. // (`if (pageId == id) { rows = fresh }`) is as much the url's as a derivation is. Nothing is closed
  168. // over the methods the handler calls: a handler that writes a shared list and then calls a method
  169. // which reads a route-fed member (notes.worldapi.org: `notes = list settle(list)`) leaves the list
  170. // the component's (#123). The reflection gives one read set per handler, not one per statement.
  171. handlerFeeds() {
  172. let byName = {}
  173. for (h of tbl.handlers) {
  174. if (!h.nested) {
  175. let reads = memberNames(h.reads)
  176. for (w of memberNames(h.writes)) {
  177. let have = byName[w] == null ? [] : byName[w]
  178. for (r of reads) { if (r != w && !have.includes(r)) { have.push(r) } }
  179. byName[w] = have
  180. }
  181. }
  182. }
  183. return mapOf(byName)
  184. }
  185. // A MEMBER HOLDING A ROUTINE: what calling it writes is what its initializer writes
  186. memberMap() {
  187. let byName = {}
  188. for (m of tbl.members) {
  189. if (m.nodes != null) { byName[m.name] = memberNames(m.nodes.writes) }
  190. }
  191. return mapOf(byName)
  192. }
  193. // Method calls can come from another mounted file through $parent. Their writes
  194. // belong to the receiver's mount, just as a function member's fnMap writes do.
  195. methodMap() {
  196. byName = {}
  197. for (mm of tbl.methods) {
  198. names = closeWrites(&tbl, mm.writes, mm.reads)
  199. if (names.length > 0) { byName[mm.name] = names }
  200. }
  201. return mapOf(byName)
  202. }
  203. // EVERY INITIALIZER, IN DECLARATION ORDER, with the members it reads — the whole of
  204. // what a derivation needs; the class carries the computation itself as `__derive__`.
  205. // `srv` (written only when true, same rule as `isStatic` on a read — every byte here
  206. // ships to the browser) marks a SERVER REFERENCE SITE (COMPONENTS.md §9.1/§9.3): an
  207. // initializer that calls an imported class (`import Store from './store.hl'`, then
  208. // `Store.chatsOf(…)` — `hlDenotes`'s own `kind: 'class'`, not a second resolution).
  209. // It is evaluated per request, on the SERVER, and its value ships into the page as
  210. // state; `client.hl`'s `moved()` must never call it locally — routger's `conversations
  211. // = … ? store.chatsOf(session.user.id) : []` reached `hl:time`, which ships no client
  212. // half, the moment a session sync (0b17f65b) made `session` move in the browser and
  213. // `moved()` re-ran every derivation that reads it. A fresh value for a server
  214. // reference site ships in `sync` instead (WebFramework.hl `serverSyncNames`).
  215. derivList() {
  216. let src = '['
  217. let first = true
  218. let own = []
  219. for (m of tbl.members) { if (!m.isStatic) { own.push(m.name) } }
  220. for (d of tbl.derivations) {
  221. if (!first) { src = src + ',' }
  222. first = false
  223. src = src + '{name:' + str(d.name) + ',site:' + str(d.site) + ',reads:' + list(derivedReads(d, own))
  224. if (d.serverSite) { src = src + ',srv:true' }
  225. src = src + '}'
  226. }
  227. return src + ']'
  228. }
  229. // A derivation re-runs when any member it needs moves: the initializer's own reads plus
  230. // the compiler's transitive `inputs` (members read through methods and helpers it calls,
  231. // SPEC "Reflection builtins for frameworks"), kept to this class's instance members.
  232. derivedReads(d, own) {
  233. let out = memberNames(d.reads)
  234. if (d.inputs != null) {
  235. for (i of d.inputs) { if (own.includes(i) && !out.includes(i)) { out.push(i) } }
  236. }
  237. return out
  238. }
  239. mapOf(byName) {
  240. let src = '{'
  241. let first = true
  242. for (k of byName.keys()) {
  243. if (!first) { src = src + ',' }
  244. first = false
  245. src = src + str(k) + ':' + list(byName[k])
  246. }
  247. return src + '}'
  248. }
  249. // the write set and the read set of the handler at this site, closed over the methods
  250. // it calls and the handlers it emits to — computed here, written into the listener
  251. handlerSets(site) {
  252. for (h of tbl.handlers) {
  253. if (h.nested && h.site == site) {
  254. return list(closeWrites(&tbl, h.writes, h.reads)) + ',' + list(closeReads(&tbl, h.reads))
  255. }
  256. }
  257. return '[],[]'
  258. }
  259. // the named regions an `if`'s branch fills (`if (x) { side { … } }`), as a JS list, `null` for none: the
  260. // browser places those regions again when the condition changes
  261. fillNamesIn(nodes) {
  262. let out = ''
  263. for (c of nodes) {
  264. if (c.k == 'if' && c.regionfill != null) { out = out + (out == '' ? '' : ',') + str(c.regionfill) }
  265. }
  266. return out == '' ? 'null' : '[' + out + ']'
  267. }
  268. regionNamesAt(site) {
  269. let names = regions[site]
  270. return list(names == null ? [] : names)
  271. }
  272. fns = []
  273. literalFns = []
  274. // ---- the walk, unrolled ------------------------------------------------------------
  275. // `top` marks the View's own root list: an element there is a COMPOSITION ROOT — a
  276. // reference above may have overwritten some of its events and put classes on it, which
  277. // is what `opt` carries (the old hl:web's rootOverwrites and withRootClasses).
  278. walk(key, nodes) {
  279. return plain(key, nodes)
  280. }
  281. // a list's walk
  282. plain(key, nodes) {
  283. let body = ''
  284. for (n of nodes) { body = body + node(key, n, false, false) }
  285. return 'async function(c,m,o,host,i,rows,rk,fill,cr,opt){let inst=m.instance;let r=rows;' + body + 'return i;}'
  286. }
  287. // the View's own root list, whose elements are composition roots
  288. walkTop(key, nodes) {
  289. let body = ''
  290. for (n of nodes) {
  291. if (n.k == 'el' && n.tag == 'body') { body = body + elNode(key, n, true, true) }
  292. else { body = body + node(key, n, true, false) }
  293. }
  294. return 'async function(c,m,o,host,i,rows,rk,fill,cr,opt){let inst=m.instance;let r=rows;' + body + 'return i;}'
  295. }
  296. // W200: a text leaf made on the build walk, or taken on the claim walk (the server's text node), the fixed part in `TX`
  297. textLeaf(t) { return 'if(cr){TX(host,' + t + ');}else{await c.leafAt(host,false,i,null,' + t + ');}' }
  298. // a sub-walk, registered under its own site so the runtime can reach it by name
  299. // A SUB-WALK IS WRITTEN ONCE, however often the compile reaches its list.
  300. sub(key, nodes, slot, site) {
  301. if (done[slot + ' ' + site] != null) { return null }
  302. done[slot + ' ' + site] = true
  303. fns.push({ slot = slot; sites = [site]; src = walk(key, nodes); })
  304. return null
  305. }
  306. done = {}
  307. node(key, n, top, filterOns) {
  308. if (n.k == 'el') { return elNode(key, n, top) }
  309. if (n.k == 'text') { return textLeaf(str(n.text)) }
  310. if (n.k == 'on') {
  311. // A REFERENCE ABOVE MAY HAVE OVERWRITTEN THIS EVENT on the composition root:
  312. // the root's own handler for it is dropped and the reference's stands instead
  313. // (the old hl:web's withoutOns, which applies to the root element's direct children).
  314. let guard = filterOns ? 'if(!(opt&&opt.over&&opt.over.indexOf(' + str(n.event) + ')>=0)){' : '{'
  315. return guard + 'await c.onAt(m,host,' + str(n.event) + ',' + str(n.site) + ',rows,' + handlerSets(n.site) + ');}'
  316. }
  317. if (n.k == 'member' && n.name == 'slot') {
  318. // the SHELL's slot is where the route component hangs; a child's slot is the
  319. // fragment its host wrote, and the host's frame builds it
  320. return 'if(m.isShell){i=await c.slotShell(m,host,i,cr);}else if(fill!=null){i=await c.slotFill(m,o,host,i,fill,cr);}'
  321. }
  322. // A TEXT LEAF STANDING IN A LIST — an `if` branch, a `for` body — beside elements or
  323. // alone: its own text node, and a site of the member it reads (or of the row it
  324. // stands in), painted by rewriting that node.
  325. if (n.k == 'member' || n.k == 'field' || n.k == 'expr') {
  326. let names = readNames(n)
  327. return 'await c.textAt(m,host,cr,async function(inst,r){return ' + textRead(n) + ';},' + list(names) + ',rows,rk,' + pathReads(n) + ');'
  328. }
  329. if (n.k == 'for') {
  330. // THE ROW VARIABLE IS IN SCOPE INSIDE THE BODY, and a read of it is the ROW's,
  331. // not a member of the instance — the language resolves it that way and the site
  332. // sets must say the same, or a member of the same name would paint the row.
  333. rowVars.push(n.row)
  334. sub(key, n.body, 'B', n.site)
  335. rowVars.pop()
  336. return 'i=await c.forAt(m,o,host,i,' + str(n.site) + ',' + str(n.row) + ',function(inst,r){return ' + rawRead(n.list) + ';},rows,rk,fill,cr,' + regionNamesAt(n.site) + ',' + pathReads(n.list) + ');'
  337. }
  338. if (n.k == 'if' && n.regionfill != null) { return '' }
  339. if (n.k == 'if' && n.region != null) {
  340. // A NAMED REGION: the default is this component's own sub-walk; what stands between the
  341. // region's marks is the default, or the fill a lower level wrote (client.hl `regionAt`)
  342. sub(key, n.then, 'D', n.site)
  343. return 'i=await c.namedRegionAt(m,o,host,i,' + str(n.site) + ',' + str(n.region) + ',rows,rk,fill,cr);'
  344. }
  345. if (n.k == 'if') {
  346. sub(key, n.then, 'T', n.site)
  347. sub(key, n.other, 'E', n.site)
  348. return 'i=await c.ifAt(m,o,host,i,' + str(n.site) + ',async function(inst,r){return ' + rawRead(n.cond) + ';},rows,rk,fill,cr,' + regionNamesAt(n.site) + ',' + fillNamesIn(n.then) + ',' + pathReads(n.cond) + ');'
  349. }
  350. if (n.k == 'component') {
  351. if (n.fill != null && n.fill.length > 0) { sub(key, n.fill, 'F', n.site) }
  352. return 'i=await c.kidAt(m,host,i,' + kidSpec(n) + ',rows,rk,fill,cr,opt);'
  353. }
  354. return ''
  355. }
  356. // ---- an element --------------------------------------------------------------------
  357. elNode(key, n, top, Boolean documentRoot = false) {
  358. // W200: the element, its claim-or-create, the failed-claim report and the row/site/key/literal stamp are the shared `N`
  359. // A literal reads only its arguments. Create it once at module scope instead of
  360. // allocating a function on every claim/create walk (#107 detached-node regression).
  361. literalIndex = literalFns.length
  362. literalFns.push('function(inst,r){return ' + litNamed(n) + ';}')
  363. let src = ''
  364. if (documentRoot) {
  365. attrNames = []
  366. for (a of n.attrs) { if (a.name != 'follow' && !isTop(n, a)) { attrNames.push(a.name) } }
  367. src = '{let el=host;await c.bodyHost(m,host,' + str(n.site) + ',' + list(attrNames) + ');'
  368. } else {
  369. src = '{let el=N(c,cr,host,i,' + str(n.tag) + ',rows,' + str(n.site) + ',' + str(key) + ',L[' + literalIndex + ']);if(!cr){i=i+1;}'
  370. }
  371. src = src + 'if(el!=null){'
  372. src = src + 'if(cr){' + createAttrs(n)
  373. if (!documentRoot) { src = src + (top ? 'await c.rootClasses(el,opt);' : '') + 'host.appendChild(el);' }
  374. src = src + '}'
  375. // `follow` is no attribute: it is read here, built or claimed, and the client keeps the element at its end (#396)
  376. if (!documentRoot) {
  377. for (a of n.attrs) {
  378. if (a.name == 'follow') { src = src + 'await c.follow(el,' + (a.member != null ? readOf({ k = 'member'; name = a.member; }) : (a.ref != null ? readOf(a.ref) : str(a.text))) + ');' }
  379. if (isTop(n, a)) { src = src + 'await c.topAt(m,el,' + str(a.name) + ',' + (a.member != null ? str(a.member) : 'null') + ',' + (a.member != null ? readOf({ k = 'member'; name = a.member; }) : (a.ref != null ? readOf(a.ref) : str(a.text))) + ',rows);' }
  380. }
  381. }
  382. let names = siteNames(n)
  383. let valueMember = 'null'
  384. for (a of n.attrs) { if (a.member != null && a.name == 'value') { valueMember = str(a.member) } }
  385. let sited = ''
  386. if (names.length > 0 || valueMember != 'null') {
  387. sited = 'await c.siteAt(m,el,' + list(names) + ',' + str(n.site) + ',' + valueMember + ',' + (n.tag == 'select' ? 'true' : 'false') + ',rows);'
  388. }
  389. let kids = ''
  390. // AN ELEMENT THAT HOLDS ONLY TEXT is painted whole (`textContent`, see the paints):
  391. // built, it gets that text as one node; claimed, the server's is taken as it stands
  392. let whole = textOf(n)
  393. if (whole != null) {
  394. kids = 'if(cr){TX(host,' + whole + ');}'
  395. for (c of n.children) { if (c.k == 'on') { kids = kids + node(key, c, false, top) } }
  396. }
  397. else if (mixed(n)) { kids = mixedKids(key, n, top) }
  398. else { for (c of n.children) { kids = kids + node(key, c, false, top) } }
  399. let inner = '{let host=el;let i=0;' + kids + '}'
  400. // A SELECT IS SITED AFTER ITS OPTIONS: the member decides which option stands, and
  401. // the read-back that `siteAt` does reports nothing before they exist.
  402. if (n.tag == 'select') { src = src + inner + (selectValue(n) == 'null' ? '' : 'if(cr){await c.applySelectAt(m,el,' + selectValue(n) + ');}') + sited }
  403. else { src = src + sited + inner }
  404. return src + '}}'
  405. }
  406. // A TEXT LEAF BESIDE AN ELEMENT OR A REGION (ticket #86 follow-up): `td { d.n if (…) {…} }`
  407. // cannot be painted through `textContent`, which would wipe the branch. Each RUN of
  408. // adjacent leaves is one text node, held on the element (`__hlLeaves`, by the run's
  409. // index) where the walk builds or claims it, and the paints rewrite that node alone.
  410. mixed(n) {
  411. if (textOf(n) != null) { return false }
  412. for (c of n.children) { if (isReadNode(c)) { return true } }
  413. return false
  414. }
  415. isLeaf(c) { return c.k == 'text' || isReadNode(c) }
  416. // a node that shows a value read at render time: a member, a field path, or an expression
  417. isReadNode(c) { return (c.k == 'member' || c.k == 'field' || c.k == 'expr') && c.name != 'slot' }
  418. // the members whose move repaints a read (`Style` and a `for` row variable are not members
  419. // of the instance), and the guard a paint writes for them
  420. readNames(c) {
  421. let out = []
  422. for (nm of (c.k == 'expr' ? c.names : [c.name])) {
  423. if (nm != 'Style' && !rowVars.includes(nm) && !out.includes(nm)) { out.push(nm) }
  424. }
  425. return out
  426. }
  427. guardOf(c) {
  428. let g = ''
  429. for (nm of readNames(c)) { g = g + (g == '' ? '' : '||') + 'n===' + str(nm) }
  430. return g
  431. }
  432. // the runs of adjacent leaves, in order; an `on` renders nothing and splits none
  433. runsOf(n) {
  434. let out = []
  435. let run = []
  436. for (c of n.children) {
  437. if (isLeaf(c)) { run.push(c) }
  438. else if (c.k != 'on') {
  439. if (run.length > 0) { out.push(run) }
  440. run = []
  441. }
  442. }
  443. if (run.length > 0) { out.push(run) }
  444. return out
  445. }
  446. runText(run) {
  447. let src = '""'
  448. for (c of run) { src = src + '+(' + (c.k == 'text' ? str(c.text) : textRead(c)) + ')' }
  449. return src
  450. }
  451. runFeeds(run) {
  452. for (c of run) { if (c.k != 'text') { return true } }
  453. return false
  454. }
  455. mixedKids(key, n, top) {
  456. let kids = ''
  457. let run = []
  458. let k = 0
  459. for (c of n.children) {
  460. if (isLeaf(c)) { run.push(c) }
  461. else {
  462. if (c.k != 'on' && run.length > 0) { kids = kids + leafRun(run, k) k = k + 1 run = [] }
  463. kids = kids + node(key, c, false, top)
  464. }
  465. }
  466. if (run.length > 0) { kids = kids + leafRun(run, k) }
  467. return kids
  468. }
  469. // EVERY CALL INTO THE CLIENT IS AWAITED: its methods are async in the browser, and one
  470. // not awaited runs its DOM work after the walk has gone on — a built leaf then lands
  471. // after the elements that follow it (ticket #104).
  472. leafRun(run, k) {
  473. if (!runFeeds(run)) { return textLeaf(runText(run)) }
  474. return 'await c.leafAt(host,cr,i,' + k + ',' + runText(run) + ');'
  475. }
  476. // the attributes an element is BUILT with — a bound one written in, a literal one as it
  477. // stands. `value` is a property once the page is live and an attribute as the control's
  478. // default; a textarea has no value attribute at all and a select's value is an option.
  479. createAttrs(n) {
  480. let src = ''
  481. for (a of n.attrs) {
  482. if ((a.name == 'follow' || isTop(n, a))) { src = src }
  483. else if (isBool(a)) {
  484. src = src + '{' + boolWrite(a, rawRead(a.member != null ? { k = 'member'; name = a.member; } : a.ref)) + '}'
  485. } else if (nullable(a)) {
  486. src = src + '{let v=' + rawRead(a.member != null ? { k = 'member'; name = a.member; } : a.ref) + ';if(v!=null){el.setAttribute(' + str(a.name) + ',""+v);}}'
  487. } else {
  488. let rd = a.member != null ? readOf({ k = 'member'; name = a.member; }) : (a.ref != null ? readOf(a.ref) : str(a.text))
  489. src = src + '{let v=' + rd + ';'
  490. if (a.extra != null) { src = src + 'v=v+" "+' + str(a.extra) + ';' }
  491. if (n.tag == 'select' && a.name == 'value') { src = src + '}' }
  492. else if (a.name == 'value') {
  493. src = src + 'if(el.value!=null){el.value=v;' + (n.tag == 'textarea' ? '' : 'el.setAttribute("value",v);') + '}else{el.setAttribute("value",v);}}'
  494. } else { src = src + 'el.setAttribute(' + str(a.name) + ',v);}' }
  495. }
  496. }
  497. if (boundValue(n)) { src = src + 'el.setAttribute("autocomplete","off");' }
  498. return src
  499. }
  500. // `modal = flag` on a dialog and `popoverOpen = flag` on any element: the member drives the browser's top layer
  501. // (showModal / showPopover) and is no HTML attribute (#329, #389)
  502. isTop(n, a) {
  503. return (a.name == 'modal' && n.tag == 'dialog') || a.name == 'popoverOpen'
  504. }
  505. // a bound attribute whose null read is NO attribute (#177): not `value` (a control's
  506. // value has its own rules), and not one carrying extra classes
  507. nullable(a) {
  508. return (a.member != null || a.ref != null) && a.name != 'value' && a.extra == null && !v.isBoolAttr(a.name)
  509. }
  510. // a BOUND boolean attribute — a literal one was decided at build (WebFramework `element`)
  511. isBool(a) {
  512. return (a.member != null || a.ref != null) && v.isBoolAttr(a.name)
  513. }
  514. // A BOUND BOOLEAN ATTRIBUTE, WRITTEN (ticket #33): set when the value is on, REMOVED when
  515. // it is off — the markup's rule (viewserver.boolAttrs) — and the DOM property with it, because
  516. // once the page is live `checked` is the property and the attribute only its default.
  517. boolWrite(a, raw) {
  518. props = { allowfullscreen = 'allowFullscreen'; formnovalidate = 'formNoValidate'; ismap = 'isMap'; itemscope = 'itemScope'; nomodule = 'noModule'; novalidate = 'noValidate'; playsinline = 'playsInline'; readonly = 'readOnly'; }
  519. prop = props[a.name] != null ? props[a.name] : a.name
  520. return 'let on=!!' + raw + ';if(on){el.setAttribute(' + str(a.name) + ',"");}else if(el.removeAttribute){el.removeAttribute(' + str(a.name) + ');}if(' + str(prop) + ' in el&&el[' + str(prop) + ']!==on){el[' + str(prop) + ']=on;}'
  521. }
  522. // view.hl's `boundValue`, to the letter: a FORM CONTROL whose `value` reads a member or
  523. // a field, and not one the author gave an `autocomplete` of its own
  524. boundValue(n) {
  525. if (n.tag != 'input' && n.tag != 'textarea' && n.tag != 'select') { return false }
  526. let bound = false
  527. for (a of n.attrs) {
  528. if (a.name == 'autocomplete') { return false }
  529. if (a.name == 'value' && (a.member != null || a.ref != null)) { bound = true }
  530. }
  531. return bound
  532. }
  533. selectValue(n) {
  534. for (a of n.attrs) {
  535. if (a.name == 'value') {
  536. if (a.member != null) { return readOf({ k = 'member'; name = a.member; }) }
  537. if (a.ref != null) { return readOf(a.ref) }
  538. return str(a.text)
  539. }
  540. }
  541. return 'null'
  542. }
  543. // the element's own entries as the literal sees them — its attributes by name, then the
  544. // `for` row variables in scope (the row rides on the value)
  545. litNamed(n) {
  546. let src = '{'
  547. let first = true
  548. for (a of n.attrs) {
  549. if (!first) { src = src + ',' }
  550. first = false
  551. let v = a.member != null ? rawRead({ k = 'member'; name = a.member; }) : (a.ref != null ? rawRead(a.ref) : str(a.text))
  552. src = src + str(a.name) + ':' + v
  553. }
  554. return src + '}'
  555. }
  556. // the reference's own description, written at its use site: what it binds, what it
  557. // overwrites, the classes the host's `#Child` rule puts on it
  558. kidSpec(n) {
  559. let src = '{key:' + str(browserKeyOf(n.key)) + ',kid:' + str(kidKeyOf(n)) + ',site:' + str(n.site) + ',fill:' + ((n.fill != null && n.fill.length > 0) ? 'true' : 'false')
  560. src = src + ',bindings:['
  561. let first = true
  562. for (b of n.bindings) {
  563. if (!first) { src = src + ',' }
  564. first = false
  565. src = src + '{name:' + str(b.name) + ',member:' + (b.member == null ? 'null' : str(b.member))
  566. src = src + ',ref:' + (b.ref == null ? 'null' : 'function(inst,r){return ' + rawRead(b.ref) + ';}')
  567. src = src + ',refName:' + (b.ref == null ? 'null' : str(b.ref.name))
  568. src = src + ',text:' + (b.text == null ? 'null' : 'true') + ',value:' + (b.text == null ? 'null' : refLiteral(b)) + '}'
  569. }
  570. src = src + '],ons:['
  571. first = true
  572. for (o of n.ons) {
  573. if (!first) { src = src + ',' }
  574. first = false
  575. src = src + '{event:' + str(o.event) + ',site:' + str(o.site) + ',sets:[' + handlerSets(o.site) + ']}'
  576. }
  577. src = src + '],classes:' + list(n.classes == null ? [] : n.classes) + '}'
  578. return src
  579. }
  580. // view.hl's kidKey: the reference's path, joined — the key the server mounted it under
  581. kidKeyOf(n) {
  582. let out = ''
  583. for (p of n.path) { out = out + '/' + p }
  584. return out
  585. }
  586. // the value a literal binding carries — view.refValue, folded at compile time
  587. refLiteral(b) {
  588. if (b.kind == 'folded') { return jsValue(b.value) }
  589. if (b.kind == 'number') { return '' + b.text }
  590. if (b.kind == 'boolean') { return b.text == 'true' ? 'true' : 'false' }
  591. if (b.kind == 'null_literal') { return 'null' }
  592. return str(b.text)
  593. }
  594. jsValue(v) {
  595. if (v == null) { return 'null' }
  596. if (hlTypeName(v) == 'String') { return str(v) }
  597. if (hlTypeName(v) == 'Boolean') { return v ? 'true' : 'false' }
  598. if (hlTypeName(v) == 'Number') { return '' + v }
  599. return JSON.stringify(v)
  600. }
  601. // ---- the site set: what this element SHOWS ------------------------------------------
  602. // The old hl:web asked the module's table which members the element at this site reads. The
  603. // answer is a fact about the View, so it is written in: the members its bound
  604. // attributes and its text leaves name. `Style` is folded into a class name at build and
  605. // the shell's `slot` is swapped by navigation — neither is ever painted, and neither is
  606. // a member read that reaches here (a `for` row variable resolves to its row).
  607. siteNames(n) {
  608. let out = []
  609. for (a of n.attrs) {
  610. if (a.member != null && a.member != 'Style' && !rowVars.includes(a.member) && !out.includes(a.member)) { out.push(a.member) }
  611. // A FIELD OF A MEMBER (`value = f.title`, ticket #93) is a read of the member:
  612. // a write to `f.title`, or a new `f`, moves `f`, and this element repaints
  613. if (a.ref != null && a.ref.name != 'Style' && !rowVars.includes(a.ref.name) && !out.includes(a.ref.name)) { out.push(a.ref.name) }
  614. }
  615. for (c of n.children) {
  616. if (isReadNode(c)) {
  617. for (nm of readNames(c)) { if (!out.includes(nm)) { out.push(nm) } }
  618. }
  619. }
  620. return out
  621. }
  622. rowVars = []
  623. // ---- the paints ---------------------------------------------------------------------
  624. collectPaints(&out, nodes) {
  625. for (n of nodes) {
  626. if (n.k == 'el') {
  627. let paint = paintFn(n)
  628. let row = rowFn(n)
  629. if (paint != null || row != 'null') {
  630. out.push({ site = n.site; paint = paint == null ? 'null' : paint; row = row; reads = rowReadList(n); })
  631. }
  632. collectPaints(&out, n.children)
  633. } else if (n.k == 'for') { collectPaints(&out, n.body) }
  634. else if (n.k == 'if') { collectPaints(&out, n.then) collectPaints(&out, n.other) }
  635. else if (n.k == 'component') { if (n.fill != null) { collectPaints(&out, n.fill) } }
  636. }
  637. return null
  638. }
  639. // Preserve exact field paths for row delta selection; expression operands contribute
  640. // their own paths. A whole-record read has an empty path and overlaps every delta.
  641. pathReads(Hybrid n) {
  642. out = []
  643. readPaths(&n, &out)
  644. return JSON.stringify(out)
  645. }
  646. readPaths(&n, &out) {
  647. if (n == null) { return null }
  648. if (n.k == 'member' || n.k == 'field') {
  649. out.push({ name = n.name; path = n.path == null ? [] : n.path; })
  650. } else if (n.k == 'expr') { readPaths(&n.x, &out) }
  651. else if (n.k == 'bin') { readPaths(&n.l, &out) readPaths(&n.r, &out) }
  652. else if (n.k == 'un') { readPaths(&n.x, &out) }
  653. else if (n.k == 'cond') { readPaths(&n.c, &out) readPaths(&n.a, &out) readPaths(&n.b, &out) }
  654. return null
  655. }
  656. rowReadList(Hybrid n) {
  657. out = []
  658. for (a of n.attrs) {
  659. if (a.member != null) { out.push({ name = a.member; path = []; }) }
  660. if (a.ref != null) { readPaths(&a.ref, &out) }
  661. }
  662. for (c of n.children) { if (isReadNode(c)) { readPaths(&c, &out) } }
  663. return JSON.stringify(out)
  664. }
  665. // `paint(&m, s, name)`, compiled: the bound attributes under the member each reads, and
  666. // the text where the member that moved stands among the leaves.
  667. paintFn(n) {
  668. let body = ''
  669. for (a of n.attrs) {
  670. if (a.member != null) {
  671. body = body + 'if(n===' + str(a.member) + '){' + attrWrite(n, a, readOf({ k = 'member'; name = a.member; })) + '}'
  672. } else if (a.ref != null) {
  673. // a field of a member paints when the MEMBER moves (ticket #93)
  674. body = body + 'if(n===' + str(a.ref.name) + '){' + attrWrite(n, a, readOf(a.ref)) + '}'
  675. }
  676. }
  677. let text = textOf(n)
  678. if (text != null) {
  679. let guard = ''
  680. for (c of n.children) {
  681. if (isReadNode(c)) {
  682. let g = guardOf(c)
  683. if (g != '') {
  684. if (guard != '') { guard = guard + '||' }
  685. guard = guard + g
  686. }
  687. }
  688. }
  689. if (guard != '') { body = body + 'if(' + guard + '){el.textContent=' + text + ';}' }
  690. } else if (mixed(n)) {
  691. let k = 0
  692. for (run of runsOf(n)) {
  693. let guard = ''
  694. for (c of run) {
  695. if (c.k != 'text') {
  696. let g = guardOf(c)
  697. if (g != '') {
  698. if (guard != '') { guard = guard + '||' }
  699. guard = guard + g
  700. }
  701. }
  702. }
  703. if (guard != '') { body = body + 'if((' + guard + ')&&el.__hlLeaves&&el.__hlLeaves[' + k + ']){el.__hlLeaves[' + k + '].data=' + runText(run) + ';}' }
  704. k = k + 1
  705. }
  706. }
  707. if (body == '') { return null }
  708. return 'async function(el,inst,r,n,keepInput){' + body + '}'
  709. }
  710. // `rowPaint(&m, el)`, compiled: every bound spot, written only where the DOM does not
  711. // already hold it — which is why a push into 2000 rows costs the 1999 nothing.
  712. rowFn(n) {
  713. let body = ''
  714. for (a of n.attrs) {
  715. if ((a.name == 'follow' || isTop(n, a))) {
  716. if (a.member != null || a.ref != null) { body = body + '{' + attrWrite(n, a, '') + '}' }
  717. } else if (isBool(a)) {
  718. body = body + '{' + boolWrite(a, rawRead(a.member != null ? { k = 'member'; name = a.member; } : a.ref)) + '}'
  719. } else if (nullable(a)) {
  720. body = body + '{let v=' + rawRead(a.member != null ? { k = 'member'; name = a.member; } : a.ref) + ';if(v==null){if(el.hasAttribute(' + str(a.name) + ')){el.removeAttribute(' + str(a.name) + ');}}else{v=""+v;if(el.getAttribute(' + str(a.name) + ')!==v){el.setAttribute(' + str(a.name) + ',v);}}}'
  721. } else if (a.member != null || a.ref != null) {
  722. let one = 'let v=' + readOf(a.member != null ? { k = 'member'; name = a.member; } : a.ref) + ';'
  723. if (a.extra != null) { one = one + 'v=v+" "+' + str(a.extra) + ';' }
  724. if (n.tag == 'select' && a.name == 'value') { one = one + 'if(el.value!==v){el.value=v;}' }
  725. else {
  726. one = one + 'if(el.getAttribute(' + str(a.name) + ')!==v){el.setAttribute(' + str(a.name) + ',v);}'
  727. if (a.name == 'value') { one = one + 'if(el.value!=null&&el.value!==v){el.value=v;}' }
  728. }
  729. if (a.name == 'value') { one = 'if(el!==keepInput||el!==document.activeElement){' + one + '}' }
  730. body = body + '{' + one + '}'
  731. }
  732. }
  733. let text = textOf(n)
  734. let feeds = false
  735. for (c of n.children) { if (isReadNode(c)) { feeds = true } }
  736. if (text != null && feeds) { body = body + '{let t=' + text + ';if(el.textContent!==t){el.textContent=t;}}' }
  737. if (text == null && feeds) {
  738. let k = 0
  739. for (run of runsOf(n)) {
  740. if (runFeeds(run)) { body = body + '{let x=el.__hlLeaves&&el.__hlLeaves[' + k + '];let t=' + runText(run) + ';if(x&&x.data!==t){x.data=t;}}' }
  741. k = k + 1
  742. }
  743. }
  744. if (body == '') { return 'null' }
  745. return 'async function(el,inst,r,keepInput){' + body + '}'
  746. }
  747. attrWrite(n, a, v) {
  748. if (a.name == 'follow') { return 'el.__hlFollow=!!' + rawRead(a.member != null ? { k = 'member'; name = a.member; } : a.ref) + ';' }
  749. if (isTop(n, a)) { return 'el.__hlTop=!!' + rawRead(a.member != null ? { k = 'member'; name = a.member; } : a.ref) + ';if(el.__hlTopSync){el.__hlTopSync();}' }
  750. if (isBool(a)) { return boolWrite(a, rawRead(a.member != null ? { k = 'member'; name = a.member; } : a.ref)) }
  751. if (nullable(a)) { return 'let v=' + rawRead(a.member != null ? { k = 'member'; name = a.member; } : a.ref) + ';if(v==null){if(el.hasAttribute(' + str(a.name) + ')){el.removeAttribute(' + str(a.name) + ');}}else{v=""+v;if(el.getAttribute(' + str(a.name) + ')!==v){el.setAttribute(' + str(a.name) + ',v);}}' }
  752. let src = 'let v=' + v + ';'
  753. if (a.extra != null) { src = src + 'v=v+" "+' + str(a.extra) + ';' }
  754. if (n.tag == 'select' && a.name == 'value') { return src + 'if(el!==keepInput||el!==document.activeElement){el.value=v;}' }
  755. // Setting an unchanged src can reload media; compare plain attributes before writing.
  756. if (a.name == 'value') { src = src + 'if(el!==keepInput||el!==document.activeElement){el.setAttribute(' + str(a.name) + ',v);if(el.value!=null&&el.value!==v){el.value=v;}}' }
  757. else { src = src + 'if(el.getAttribute(' + str(a.name) + ')!==v){el.setAttribute(' + str(a.name) + ',v);}' }
  758. return src
  759. }
  760. textOf(n) {
  761. let parts = []
  762. let content = 0
  763. let feeds = false
  764. for (c of n.children) {
  765. if (c.k != 'on') {
  766. content = content + 1
  767. if (c.k == 'text') { parts.push(str(c.text)) }
  768. else if (isReadNode(c)) { parts.push(textRead(c)) feeds = true }
  769. }
  770. }
  771. if (!feeds) { return null }
  772. if (parts.length != content) { return null }
  773. let src = '""'
  774. for (p of parts) { src = src + '+(' + p + ')' }
  775. return src
  776. }
  777. // ---- a read, written in ---------------------------------------------------------------
  778. // `view.value`'s own rule as an expression: a `for` row variable in scope wins over a
  779. // member of the same name, and a field path walks into it. `readOf` answers the STRING
  780. // the DOM takes; `rawRead` the value itself (a binding, a list, a condition).
  781. // A null bound value is empty, matching the server attribute writer.
  782. readOf(node) { return 'S(' + rawRead(node) + ')' }
  783. // A READ SHOWN AS TEXT: null is no text, as the server writes it (view.hl `escape`)
  784. textRead(node) { return 'S(' + rawRead(node) + ')' }
  785. rawRead(node) {
  786. if (node == null) { return 'null' }
  787. if (node.k == 'text') { return node.kind == 'folded' && hlTypeName(node.value) == 'Hybrid' ? JSON.stringify(node.value) : str(node.text) }
  788. if (node.k == 'expr') { return '(await X(' + JSON.stringify(node.x) + ',r,inst))' }
  789. if (node.k != 'field') { return 'RV(r,inst,' + str(node.name) + ')' }
  790. return 'RF(r,inst,' + str(node.name) + ',' + list(node.path) + ')'
  791. }
  792. list(names) {
  793. let src = '['
  794. let first = true
  795. for (n of names) {
  796. if (!first) { src = src + ',' }
  797. first = false
  798. src = src + str(n)
  799. }
  800. return src + ']'
  801. }
  802. // a JavaScript string literal — JSON's escaping is a subset of JavaScript's, so a
  803. // source text's quotes, newlines and backslashes survive into the statement unchanged
  804. str(s) {
  805. if (s == null) { return '""' }
  806. return JSON.stringify('' + s)
  807. }
  808. // ---- WHAT THE LANGUAGE SAYS ABOUT THIS FILE, read HERE and written into the code ----
  809. // The old hl:web shipped the language's answers to the browser as data: `hlJs` writes each file's
  810. // members, handlers and methods — every node of every initializer, with the names it
  811. // reads — into the module, and the client reduces that table on every boot. The answers
  812. // are facts about the source, so this file asks for them once, at compile time, and
  813. // writes the RESULT into the statements: a handler's write set stands at the listener
  814. // that needs it, a region's names at the region, the derivations as a list of what to
  815. // re-run. The module carries no table at all (WebFramework `module` drops the one the
  816. // emitter writes).
  817. //
  818. // The reflection is the framework's own analysis generation — the same `gen` the View
  819. // trees come from. Nothing starts a second one: a handle is only valid inside the
  820. // generation that made it.
  821. tableOf(gen, key) {
  822. let members = []
  823. let derivations = []
  824. let handlers = []
  825. let methods = []
  826. for (m of hlMembers(gen, key)) {
  827. let entry = { name = m.name; nodes = null; isStatic = m.isStatic == true; }
  828. if (m.hasValue) {
  829. let n = syntaxTree(gen, key, m.node)
  830. entry.nodes = n
  831. derivations.push({ name = m.name; site = n.site; reads = n.reads; serverSite = m.serverSite == true; pure = m.pure == true; writtenElsewhere = m.writtenElsewhere == true; inputs = m.inputs; })
  832. nestedHandlers(&handlers, n)
  833. }
  834. members.push(entry)
  835. }
  836. for (h of hlEvents(gen, key).handles) {
  837. let n = syntaxTree(gen, key, h.node)
  838. // `on window.x()` / `on viewport.x()` / `on document.x()` (SPEC "Reserved browser targets"): filed under 'window.x', so
  839. // the write set never mixes with an own handler of the same event name
  840. let evName = (h.scope == 'window' || h.scope == 'viewport' || h.scope == 'document') ? h.scope + '.' + h.event : h.event
  841. handlers.push({ event = evName; site = n.site; reads = n.reads; writes = n.writes; nested = false; })
  842. }
  843. for (mm of hlMethods(gen, key)) {
  844. if (!mm.inlineHandler) {
  845. let n = syntaxTree(gen, key, mm.node)
  846. methods.push({ name = mm.name; reads = n.reads; writes = n.writes; })
  847. }
  848. }
  849. return { members = members; derivations = derivations; handlers = handlers; methods = methods; }
  850. }
  851. // A NESTED `on` IS A DOM HANDLER, filed under its own site — the id the View node
  852. // carries. Its body is not the literal's syntax, so the node answers for it and the
  853. // walk stops there.
  854. nestedHandlers(&into, n) {
  855. if (n == null) { return null }
  856. if (n.tag == 'on_statement') {
  857. into.push({ event = n.event; site = n.site; reads = n.reads; writes = n.writes; nested = true; })
  858. return null
  859. }
  860. for (c of [n.value, n.list, n.body, n.condition, n.consequent, n.alternate, n.object, n.property, n.callee, n.left, n.right, n.operand]) {
  861. if (c != null) { nestedHandlers(&into, c) }
  862. }
  863. for (l of [n.entries, n.args, n.elements]) {
  864. if (l != null) { for (c of l) { nestedHandlers(&into, c) } }
  865. }
  866. return null
  867. }
  868. // the site with its file's base name: everything after the last '/'. The path part
  869. // is not "up to the first ':'" — a package key has a colon of its own
  870. // ('hl:markdown/Markdown.hl:24:3'), and that reading left a package component's
  871. // sites unshortened, so its regions found no reads and never repainted (#111)
  872. shortSite(site) {
  873. if (site == null) { return null }
  874. let cut = site.lastIndexOf('/')
  875. if (cut < 0) { return site }
  876. return site.slice(cut + 1)
  877. }
  878. // the syntax of one node, recursively — hl:core/AST's `tree`, read off the framework's
  879. // own generation instead of starting one of its own
  880. syntaxTree(gen, key, node) {
  881. let n = hlSyntax(gen, key, node)
  882. if (n == null) { return null }
  883. // A SITE IS NAMED BY THE FILE'S BASE NAME. The reflection answers with the project
  884. // key ('components/sort_list.hl:77:26'); the View tree, the emitter's own
  885. // `__derive__` branches and every site this framework writes use the base name
  886. // ('sort_list.hl:77:26'). One spelling, or a lookup by site finds nothing.
  887. let out = { tag = n.tag; site = shortSite(n.site); reads = n.reads; writes = n.writes; }
  888. if (n.tag == 'object_expression') {
  889. let kids = []
  890. for (h of n.entries) { kids.push(syntaxTree(gen, key, h)) }
  891. out.entries = kids
  892. } else if (n.tag == 'object_property') {
  893. out.key = n.key
  894. out.value = syntaxTree(gen, key, n.value)
  895. } else if (n.tag == 'view_for') {
  896. out.list = syntaxTree(gen, key, n.list)
  897. out.body = syntaxTree(gen, key, n.body)
  898. } else if (n.tag == 'view_if') {
  899. out.condition = syntaxTree(gen, key, n.condition)
  900. out.consequent = syntaxTree(gen, key, n.consequent)
  901. out.alternate = syntaxTree(gen, key, n.alternate)
  902. } else if (n.tag == 'on_statement') {
  903. out.event = n.event
  904. } else if (n.tag == 'member_expression') {
  905. out.object = syntaxTree(gen, key, n.object)
  906. out.property = syntaxTree(gen, key, n.property)
  907. out.computed = n.computed
  908. } else if (n.tag == 'identifier') {
  909. out.name = n.name
  910. } else if (n.tag == 'call_expression') {
  911. out.callee = syntaxTree(gen, key, n.callee)
  912. let args = []
  913. for (h of n.args) { args.push(syntaxTree(gen, key, h)) }
  914. out.args = args
  915. } else if (n.tag == 'binary_expression') {
  916. out.left = syntaxTree(gen, key, n.left)
  917. out.right = syntaxTree(gen, key, n.right)
  918. } else if (n.tag == 'unary_expression') {
  919. out.operand = syntaxTree(gen, key, n.operand)
  920. } else if (n.tag == 'conditional_expression') {
  921. out.condition = syntaxTree(gen, key, n.condition)
  922. out.consequent = syntaxTree(gen, key, n.consequent)
  923. out.alternate = syntaxTree(gen, key, n.alternate)
  924. } else if (n.tag == 'array_expression') {
  925. let els = []
  926. for (h of n.elements) { els.push(syntaxTree(gen, key, h)) }
  927. out.elements = els
  928. }
  929. return out
  930. }
  931. // ---- the reductions the browser used to make on every boot --------------------------
  932. // A `for`'s names are what its list reads, an `if`'s what its condition reads — filed
  933. // under the region's own site.
  934. regionIndex(t) {
  935. let idx = {}
  936. for (m of t.members) { if (m.nodes != null) { indexRegions(&idx, m.nodes) } }
  937. return idx
  938. }
  939. indexRegions(&idx, n) {
  940. if (n == null) { return null }
  941. if (n.tag == 'view_for') {
  942. idx[n.site] = memberNames(nodeReads(n.list))
  943. indexRegions(&idx, n.body)
  944. return null
  945. }
  946. if (n.tag == 'view_if') {
  947. idx[n.site] = memberNames(nodeReads(n.condition))
  948. indexRegions(&idx, n.consequent)
  949. indexRegions(&idx, n.alternate)
  950. return null
  951. }
  952. if (n.tag == 'on_statement') { return null }
  953. for (c of [n.value, n.list, n.body, n.condition, n.consequent, n.alternate, n.object, n.property, n.callee, n.left, n.right, n.operand]) {
  954. if (c != null) { indexRegions(&idx, c) }
  955. }
  956. for (l of [n.entries, n.args, n.elements]) {
  957. if (l != null) { for (c of l) { indexRegions(&idx, c) } }
  958. }
  959. return null
  960. }
  961. // the member reads of a read list — the language resolved every name, so this is a
  962. // filter and not a second resolution
  963. memberNames(reads) {
  964. let out = []
  965. if (reads == null) { return out }
  966. for (r of reads) {
  967. if (r.kind == 'member' && r.isStatic != true && !out.includes(r.name)) { out.push(r.name) }
  968. }
  969. return out
  970. }
  971. nodeReads(n) {
  972. if (n == null) { return [] }
  973. if (n.reads != null) { return n.reads }
  974. let out = []
  975. for (c of [n.value, n.list, n.body, n.condition, n.consequent, n.alternate, n.object, n.property, n.callee, n.left, n.right, n.operand]) {
  976. if (c != null) { for (r of nodeReads(c)) { out.push(r) } }
  977. }
  978. for (l of [n.entries, n.args, n.elements]) {
  979. if (l != null) { for (c of l) { for (r of nodeReads(c)) { out.push(r) } } }
  980. }
  981. return out
  982. }
  983. // A ROUTINE'S WRITES, PLUS THE WRITES OF EVERYTHING IT REACHES — the method it calls
  984. // and the handler it emits to, transitively. Both are READS the language resolved, so
  985. // this is a walk of its answer and never a guess.
  986. closeWrites(&t, writes, reads) {
  987. let out = memberNames(writes)
  988. let queue = []
  989. reached(&queue, reads)
  990. let seen = {}
  991. while (queue.length > 0) {
  992. let at = queue.shift()
  993. if (seen[at] == null) {
  994. seen[at] = true
  995. let sp = at.indexOf(' ')
  996. let kind = at.slice(0, sp)
  997. let name = at.slice(sp + 1)
  998. for (mm of t.methods) {
  999. if (kind == 'method' && mm.name == name) {
  1000. for (w of memberNames(mm.writes)) { if (!out.includes(w)) { out.push(w) } }
  1001. reached(&queue, mm.reads)
  1002. }
  1003. }
  1004. for (h of t.handlers) {
  1005. if (kind == 'handler' && !h.nested && h.event == name) {
  1006. for (w of memberNames(h.writes)) { if (!out.includes(w)) { out.push(w) } }
  1007. reached(&queue, h.reads)
  1008. }
  1009. }
  1010. for (mb of t.members) {
  1011. if (kind == 'member' && mb.name == name && mb.nodes != null) {
  1012. for (w of memberNames(mb.nodes.writes)) { if (!out.includes(w)) { out.push(w) } }
  1013. reached(&queue, nodeReads(mb.nodes))
  1014. }
  1015. }
  1016. }
  1017. }
  1018. return out
  1019. }
  1020. // the mirror: a handler's reads plus the reads of everything it reaches — the
  1021. // candidates for a routine a host handed down, whose writes only the host's table names
  1022. closeReads(&t, reads) {
  1023. let out = memberNames(reads)
  1024. let queue = []
  1025. reached(&queue, reads)
  1026. let seen = {}
  1027. while (queue.length > 0) {
  1028. let at = queue.shift()
  1029. if (seen[at] == null) {
  1030. seen[at] = true
  1031. let sp = at.indexOf(' ')
  1032. let kind = at.slice(0, sp)
  1033. let name = at.slice(sp + 1)
  1034. for (mm of t.methods) {
  1035. if (kind == 'method' && mm.name == name) {
  1036. for (r of memberNames(mm.reads)) { if (!out.includes(r)) { out.push(r) } }
  1037. reached(&queue, mm.reads)
  1038. }
  1039. }
  1040. for (h of t.handlers) {
  1041. if (kind == 'handler' && !h.nested && h.event == name) {
  1042. for (r of memberNames(h.reads)) { if (!out.includes(r)) { out.push(r) } }
  1043. reached(&queue, h.reads)
  1044. }
  1045. }
  1046. for (mb of t.members) {
  1047. if (kind == 'member' && mb.name == name && mb.nodes != null) {
  1048. for (r of memberNames(nodeReads(mb.nodes))) { if (!out.includes(r)) { out.push(r) } }
  1049. reached(&queue, nodeReads(mb.nodes))
  1050. }
  1051. }
  1052. }
  1053. }
  1054. return out
  1055. }
  1056. reached(&queue, reads) {
  1057. if (reads == null) { return null }
  1058. for (r of reads) {
  1059. if (r.kind == 'method' || r.kind == 'handler' || (r.kind == 'member' && r.isStatic != true)) { queue.push(r.kind + ' ' + r.name) }
  1060. }
  1061. return null
  1062. }
  1063. // ---- THE SERVER RENDER, COMPILED --------------------------------------------------
  1064. // The old hl:web rendered a page by WALKING the View tree per request: for every node it asks
  1065. // what kind it is, for every element it builds the attribute string, and it decides the
  1066. // indentation of every line again, on every request, for every one of the 121 mounts a
  1067. // page may hold. Every one of those decisions is a fact about the View.
  1068. //
  1069. // So a component's render is compiled ONCE into a list of STEPS — constant text, and a
  1070. // read with its own closure — and a request is a concatenation. The structure (tags,
  1071. // static attributes, the readable form's line breaks, which element is a block) is
  1072. // decided at compile time; only the values are asked for per request.
  1073. //
  1074. // KEYED BY THE INDENT IT IS RENDERED AT, because that is the only thing about a
  1075. // component's HTML that its caller decides: the shell renders at one tab, the page at
  1076. // the depth the slot stands, a fill compactly (null). An app has a handful of those.
  1077. // the framework's `(key) => View tree`, for a kid whose steps are not built yet (set after the trees are)
  1078. treeOf = null
  1079. // the steps of a kid mount: the memo when it holds them, else built from the key's tree (read once, when they are built)
  1080. kidSteps(key, indent, classes, slotted) {
  1081. let ck = key + '|' + (indent == null ? '~' : indent) + '|' + joinList(classes) + '|' + (slotted ? '1' : '0')
  1082. if (steps[ck] == null) { return serverSteps(key, treeOf(key), indent, classes, slotted) }
  1083. return steps[ck]
  1084. }
  1085. bodySteps = {}
  1086. documentBody(String key, &nodes, &inst, &mounts) {
  1087. if (nodes.length != 1 || nodes[0].k != 'el' || nodes[0].tag != 'body') { return '<body>' }
  1088. if (bodySteps[key] == null) {
  1089. let root = nodes[0]
  1090. root.children = []
  1091. bodySteps[key] = blockSteps([root], null, false)
  1092. }
  1093. rows = {}
  1094. ctx = { slot = null }
  1095. html = runSteps(&bodySteps[key], &inst, &rows, &ctx, &mounts)
  1096. return html.slice(0, html.indexOf('>') + 1)
  1097. }
  1098. serverSteps(key, &nodes, indent, classes, slotted) {
  1099. let ck = key + '|' + (indent == null ? '~' : indent) + '|' + joinList(classes) + '|' + (slotted ? '1' : '0')
  1100. if (steps[ck] == null) {
  1101. steps[ck] = blockSteps(classes == null || classes.length == 0 ? nodes : v.withRootClasses(&nodes, &classes), indent, slotted)
  1102. }
  1103. return steps[ck]
  1104. }
  1105. // A `slot` THE HOST FILLED COUNTS AS CONTENT, and an empty one does not — the one
  1106. // thing about a component's shape its caller decides, so it is part of the key.
  1107. staticVoid = [ 'area' 'base' 'br' 'col' 'embed' 'hr' 'img' 'input' 'link' 'meta' 'source' 'track' 'wbr' ]
  1108. staticVerbatim = [ 'textarea' 'pre' 'script' 'style' ]
  1109. blocky(n, slotted) {
  1110. if (staticVerbatim.includes(n.tag)) { return false }
  1111. if (n.children.length == 0) { return false }
  1112. for (c of n.children) {
  1113. if (c.k == 'text' || c.k == 'field' || c.k == 'expr') { return false }
  1114. if (c.k == 'member' && !(c.name == 'slot' && slotted)) { return false }
  1115. }
  1116. return true
  1117. }
  1118. steps = {}
  1119. v = new HlwViewServer
  1120. viewRead = new HlwView
  1121. joinList(l) {
  1122. if (l == null) { return '' }
  1123. let out = ''
  1124. for (c of l) { out = out + ',' + c }
  1125. return out
  1126. }
  1127. // `render(nodes, …, indent)`: the readable form puts each element on its own line at
  1128. // `indent`, the compact one writes them end to end.
  1129. blockSteps(nodes, indent, slotted) {
  1130. let out = []
  1131. for (n of nodes) {
  1132. if (indent != null) {
  1133. if (n.k == 'el') { push(&out, { k = 's'; v = newline + indent; }) nodeSteps(&out, n, indent, slotted) }
  1134. else if (n.k == 'component') { nodeSteps(&out, n, indent, slotted) }
  1135. else if (n.k == 'for') { forSteps(&out, n, indent, slotted) }
  1136. else if (n.k == 'if') { ifSteps(&out, n, indent, slotted) }
  1137. else if (n.k == 'member' && n.name == 'slot') { push(&out, { k = 'slotline'; v = newline + indent; }) }
  1138. else if (n.k != 'on') { nodeSteps(&out, n, indent, slotted) }
  1139. } else {
  1140. nodeSteps(&out, n, null, slotted)
  1141. }
  1142. }
  1143. return out
  1144. }
  1145. forSteps(&out, n, indent, slotted) {
  1146. out.push({ k = 'for'; row = n.row; read = readFn(n.list); body = blockSteps(n.body, indent, slotted); })
  1147. return null
  1148. }
  1149. ifSteps(&out, n, indent, slotted) {
  1150. if (n.regionfill != null) { return null }
  1151. if (n.region != null) {
  1152. out.push({ k = 'region'; name = n.region; ind = indent; late = n.deferred == true; body = n.deferred == true ? [] : blockSteps(n.then, indent, slotted); })
  1153. return null
  1154. }
  1155. out.push({ k = 'if'; read = readFn(n.cond); then = blockSteps(n.then, indent, slotted); other = blockSteps(n.other, indent, slotted); })
  1156. return null
  1157. }
  1158. // a script's children: text and values written as they are (`view.rawText`)
  1159. rawSteps(nodes, slotted) {
  1160. let out = []
  1161. for (n of nodes) {
  1162. if (n.k == 'text') { push(&out, { k = 's'; v = v.rawText(n.text); }) }
  1163. else if (n.k == 'member' || n.k == 'field' || n.k == 'expr') { out.push({ k = 'raw'; read = readFn(n); }) }
  1164. else { nodeSteps(&out, n, null, slotted) }
  1165. }
  1166. return out
  1167. }
  1168. // one node's steps — `html(node, …)`, decided once
  1169. nodeSteps(&out, n, indent, slotted) {
  1170. if (n.k == 'text') { push(&out, { k = 's'; v = v.escape(n.text); }) return null }
  1171. if (n.k == 'on') { return null }
  1172. if (n.k == 'member' && n.name == 'slot') { out.push({ k = 'slot'; }) return null }
  1173. if (n.k == 'member' || n.k == 'field' || n.k == 'expr') { out.push({ k = 'r'; read = readFn(n); }) return null }
  1174. if (n.k == 'for') { forSteps(&out, n, indent, slotted) return null }
  1175. if (n.k == 'if') { ifSteps(&out, n, indent, slotted) return null }
  1176. if (n.k == 'component') {
  1177. out.push({ k = 'kid'; path = n.path; cls = n.cls; key = n.key; classes = n.classes; indent = indent;
  1178. fill = (n.fill == null || n.fill.length == 0) ? null : blockSteps(n.fill, null, slotted); })
  1179. return null
  1180. }
  1181. if (n.k == 'el') { elSteps(&out, n, indent, slotted) return null }
  1182. push(&out, { k = 's'; v = '<!-- ' + n.tag + ' not rendered yet -->'; })
  1183. return null
  1184. }
  1185. elSteps(&out, n, indent, slotted) {
  1186. let attrs = []
  1187. let valueRead = null // a textarea's value is its content
  1188. let selRead = null // a select's value selects an option
  1189. for (a of n.attrs) {
  1190. if ((a.name == 'follow' || isTop(n, a))) { valueRead = valueRead }
  1191. else if (n.tag == 'textarea' && a.name == 'value') { valueRead = attrRead(a) }
  1192. else if (n.tag == 'select' && a.name == 'value') { selRead = attrRead(a) }
  1193. // a bound BOOLEAN attribute is its presence (ticket #33): ` checked=""` or nothing
  1194. else if ((a.member != null || a.ref != null) && v.isBoolAttr(a.name)) { attrs.push({ k = 'b'; name = a.name; read = attrRead(a); }) }
  1195. // a null read is no attribute (#177)
  1196. else if (nullable(a)) { attrs.push({ k = 'a'; name = a.name; read = attrRead(a); }) }
  1197. else if (a.member != null || a.ref != null) {
  1198. push(&attrs, { k = 's'; v = ' ' + a.name + '="'; })
  1199. attrs.push({ k = 'r'; read = attrRead(a); })
  1200. push(&attrs, { k = 's'; v = v.extraOf(a) + '"'; })
  1201. } else {
  1202. push(&attrs, { k = 's'; v = ' ' + a.name + '="' + v.escape(a.text) + '"'; })
  1203. }
  1204. }
  1205. if (v.boundValue(&n)) { push(&attrs, { k = 's'; v = ' autocomplete="off"'; }) }
  1206. // Only handled forms opt into the document's preboot submit capture (#349).
  1207. if (n.tag == 'form') {
  1208. for (c of n.children) {
  1209. if (c.k == 'on' && c.event == 'submit') {
  1210. push(&attrs, { k = 's'; v = ' data-hl-submit'; })
  1211. break
  1212. }
  1213. }
  1214. }
  1215. // the children, in the form this element takes: a block puts them one per line
  1216. let kids = []
  1217. // a script's and a style's content is raw text (#140, view.rawKids says why)
  1218. if (n.tag == 'script' || n.tag == 'style') { kids = rawSteps(n.children, slotted) }
  1219. else if (indent != null && blocky(n, slotted)) {
  1220. kids = blockSteps(n.children, indent + tab, slotted)
  1221. push(&kids, { k = 's'; v = newline + indent; })
  1222. } else {
  1223. kids = blockSteps(n.children, null, slotted)
  1224. }
  1225. if (valueRead != null) { kids = [{ k = 'r'; read = valueRead; }] }
  1226. // AN OPTION IS THE ONE ELEMENT WHOSE OWN TAG DEPENDS ON THE VALUE ABOVE IT: it
  1227. // carries `selected` when its value is the select's. Everything else is settled.
  1228. if (n.tag == 'option') {
  1229. out.push({ k = 'opt'; attrs = attrs; body = kids; ov = optionRead(n); })
  1230. return null
  1231. }
  1232. push(&out, { k = 's'; v = '<' + n.tag; })
  1233. for (a of attrs) { push(&out, a) }
  1234. if (staticVoid.includes(n.tag)) { push(&out, { k = 's'; v = '>'; }) return null }
  1235. push(&out, { k = 's'; v = '>'; })
  1236. // A SELECT HANDS ITS VALUE TO ITS OPTIONS, however deep they stand: its children
  1237. // run under it, and it is the only element that changes anything for them.
  1238. if (n.tag == 'select') { out.push({ k = 'sel'; read = selRead; body = kids; }) }
  1239. else { for (kk of kids) { push(&out, kk) } }
  1240. push(&out, { k = 's'; v = '</' + n.tag + '>'; })
  1241. return null
  1242. }
  1243. // CONSTANT TEXT MERGES. Two literal steps in a row are one string decided at compile
  1244. // time — which is what makes a request a concatenation of a handful of pieces instead
  1245. // of one per node.
  1246. push(&out, step) {
  1247. if (step.k == 's' && out.length > 0 && out[out.length - 1].k == 's') {
  1248. let last = out[out.length - 1]
  1249. last.v = last.v + step.v
  1250. out[out.length - 1] = last
  1251. return null
  1252. }
  1253. out.push(step)
  1254. return null
  1255. }
  1256. // ---- the reads, each with its own closure ------------------------------------------
  1257. // `view.value`'s rule, split once: a `for` row variable in scope wins over a member of
  1258. // the same name, and a field path walks into it. The closure holds the name — there is
  1259. // no node to look at per request.
  1260. readFn(node) {
  1261. if (node == null) { return (inst, rows) => { return null } }
  1262. if (node.k == 'text') { let t = viewRead.refValue(node) return (inst, rows) => { return t } }
  1263. if (node.k == 'expr') { let x = node.x return (inst, rows) => { return viewRead.evalExpr(&x, &inst, &rows) } }
  1264. let name = node.name
  1265. if (node.k != 'field') {
  1266. return (inst, rows) => { return rows[name] != null ? rows[name] : inst[name] }
  1267. }
  1268. let path = node.path
  1269. return (inst, rows) => {
  1270. let val = rows[name] != null ? rows[name] : inst[name]
  1271. for (f of path) {
  1272. if (val == null) { return null }
  1273. val = val[f]
  1274. }
  1275. return val
  1276. }
  1277. }
  1278. attrRead(a) {
  1279. if (a.member != null) { return readFn({ k = 'member'; name = a.member; }) }
  1280. if (a.ref != null) { return readFn(a.ref) }
  1281. let t = a.text
  1282. return (inst, rows) => { return t }
  1283. }
  1284. // an option's own value: its `value` attribute, or null when it has none (the browser
  1285. // then reports its text, and the run compares against what it rendered)
  1286. optionRead(n) {
  1287. for (a of n.attrs) {
  1288. if (a.name == 'value') { return attrRead(a) }
  1289. }
  1290. return null
  1291. }
  1292. // ---- the run: a concatenation ------------------------------------------------------
  1293. // EVERY REGION IS WRITTEN BETWEEN TWO MARKS (tickets #103, #104): an `if` around the
  1294. // branch that stands, a `for` around its rows and each row around its own nodes. The
  1295. // client claims them as they are and builds the same ones, and a region's nodes are
  1296. // exactly what stands between its two marks — nothing it holds has to be remembered
  1297. // node by node, and text beside a region can never run into the region's text.
  1298. regionOpen = '<!--hl:rg:'
  1299. regionClose = '<!--hl:/rg:'
  1300. markOpen = '<!--[-->'
  1301. markClose = '<!--]-->'
  1302. // THE PIECES ARE JOINED ONCE, AT THE END (ticket #127). `out = out + piece` copied
  1303. // the whole page so far for every piece: a 3.5 MB page of 2000 rows allocated 2.3 GB
  1304. // in growing copies, 7 GB per render all told — 12 s a load once the collector ran
  1305. // by bytes (#126), where the joined pieces take 2.5 s.
  1306. runSteps(&list, &inst, &rows, &ctx, &mounts) {
  1307. let out = []
  1308. runInto(&out, &list, &inst, &rows, &ctx, &mounts)
  1309. return out.join('')
  1310. }
  1311. // the same run, its pieces pushed onto the ONE list the caller joins: a nested region used to be
  1312. // joined into a string and then concatenated into its parent's list, so every piece was copied once
  1313. // per level it sat in (a README's blocks sit several levels deep)
  1314. runInto(&out, &list, &inst, &rows, &ctx, &mounts) {
  1315. for (s of list) {
  1316. if (s.k == 's') { out.push(s.v) }
  1317. else if (s.k == 'r') { let f = s.read out.push(v.escape(f(&inst, &rows))) }
  1318. else if (s.k == 'raw') { let f = s.read out.push(v.rawText(f(&inst, &rows))) }
  1319. else if (s.k == 'a') { let f = s.read let av = f(&inst, &rows) if (av != null) { out.push(' ' + s.name + '="' + v.escape(av) + '"') } }
  1320. else if (s.k == 'b') { let f = s.read if (v.boolOn(f(&inst, &rows))) { out.push(' ' + s.name + '=""') } }
  1321. else if (s.k == 'slot') { if (ctx.slot != null) { out.push(ctx.slot) } }
  1322. else if (s.k == 'slotline') { if (ctx.slot != null) { out.push(s.v + ctx.slot) } }
  1323. else if (s.k == 'for') {
  1324. let f = s.read
  1325. let list2 = f(&inst, &rows)
  1326. out.push(markOpen)
  1327. if (list2 != null) {
  1328. // THE ROW IS SET IN PLACE, and the name it shadows put back after the loop:
  1329. // `rows + {}` copied every enclosing row per iteration, and an outer row holds the
  1330. // whole list its inner `for` walks (a list block holding its N items): N rows of N items
  1331. let held = rows[s.row]
  1332. let ri = 0
  1333. let keys = viewRead.listKeys(&list2)
  1334. for (entry of list2) {
  1335. rows[s.row] = entry
  1336. let rc = v.rowCtx(&ctx, keys[ri])
  1337. out.push(markOpen)
  1338. runInto(&out, &s.body, &inst, &rows, &rc, &mounts)
  1339. out.push(markClose)
  1340. ri = ri + 1
  1341. }
  1342. rows[s.row] = held
  1343. }
  1344. out.push(markClose)
  1345. }
  1346. else if (s.k == 'region') {
  1347. // the region's default, between PLACEHOLDERS the document replaces once the page is known
  1348. // (a level above is rendered before the page below it is constructed): WebFramework `regions`
  1349. out.push(regionOpen + s.name + ':' + (s.ind == null ? '-' : '' + s.ind.length) + (s.late == true ? '!' : '') + '-->')
  1350. runInto(&out, &s.body, &inst, &rows, &ctx, &mounts)
  1351. out.push(regionClose + s.name + '-->')
  1352. }
  1353. else if (s.k == 'if') {
  1354. let f = s.read
  1355. out.push(markOpen)
  1356. if (f(&inst, &rows)) { runInto(&out, &s.then, &inst, &rows, &ctx, &mounts) }
  1357. else { runInto(&out, &s.other, &inst, &rows, &ctx, &mounts) }
  1358. out.push(markClose)
  1359. }
  1360. else if (s.k == 'opt') {
  1361. let head = runSteps(&s.attrs, &inst, &rows, &ctx, &mounts)
  1362. let body = runSteps(&s.body, &inst, &rows, &ctx, &mounts)
  1363. let mark = ''
  1364. if (ctx.sel != null) {
  1365. let ov = body
  1366. if (s.ov != null) { let f = s.ov ov = '' + f(&inst, &rows) }
  1367. if (ov == ctx.sel) { mark = ' selected' }
  1368. }
  1369. out.push('<option' + head + mark + '>' + body + '</option>')
  1370. }
  1371. else if (s.k == 'sel') {
  1372. let f = s.read
  1373. let inner = ctx + {}
  1374. inner.sel = f == null ? null : '' + f(&inst, &rows)
  1375. runInto(&out, &s.body, &inst, &rows, &inner, &mounts)
  1376. }
  1377. else if (s.k == 'kid') {
  1378. // THE KID IS READ IN PLACE: `let kid = ctx.kids[…]` copied the whole mount (its tree, its
  1379. // params, its state, its own kids) once per mount rendered. And the mounts a level holds
  1380. // travel as their own reference (`mounts`), not inside `ctx`: every `for` row copies the
  1381. // ctx, and a ctx holding the kids copied ALL of them per row (N rows of N mounts).
  1382. let kk = v.kidKeyIn(&s.path, &ctx)
  1383. if (mounts[kk] == null) { out.push('<!-- ' + s.cls + ' not mounted -->') }
  1384. else {
  1385. let fillText = s.fill == null ? null : runSteps(&s.fill, &inst, &rows, &ctx, &mounts)
  1386. let kidCtx = { slot = fillText; }
  1387. let empty = {}
  1388. let ksteps = kidSteps(s.key, s.indent, s.classes, fillText != null)
  1389. runInto(&out, &ksteps, &mounts[kk].page, &empty, &kidCtx, &mounts[kk].kids)
  1390. }
  1391. }
  1392. }
  1393. }

Branches

Latest commits

  • 10f8a8c8Merge branch 'code-order' into mainJukebox
  • 204fc828Merge branch 'day72' into mainJukebox
  • 95f5faae|||PR jukebox#7 Drop needless let declarationsmre
  • 33072bb5|||PR Record day72 gates and Chrome proofmre
  • 95f2cd73|||PR Use typed parent methods for screen playback and local server facesmre
  • 6422a020Sync media-player at 51c3818mre
  • b582ba1cVendor complete Hybriel day72 plugin setmre
  • 02dccbc9Merge branch 'records-1119' into mainJukebox
  • a39e1c23|||PR Records: missions 013-015, reconnect fix livemre
  • fc7db075Merge branch 'reconnect-retry' into mainJukebox
  • ac6f4c6fL2: plain declaration for a in pickedNextmre
  • 2f335086Review round 2: only an explicit queue pick drops pend (not the automatic advance); jb23 records every source changemre
  • 3eb6695fReview fixes: action generation, queue pick clears pend, Previous/Next retry the decided request, typed handlersmre
  • 7a53c0c2|||PR A tap lost to a dead socket plays after reconnect (mission 015)mre
  • 1f0cd77bMerge branch 'records-day41' into mainJukebox
  • 67be229f|||PR Records: day41 live (PR #4), mission 012, statusmre
  • 0bb027daconductor: caramboleyo is the user, not owner/creatorApollo
  • 04f5d9d5Merge branch 'day41' into mainJukebox
  • 8ed6da45|||PR README: media-player pin df9e7dfmre
  • d5d45fc3|||PR media-player df9e7df (repeat-one fix), sync pin and SOURCEmre