gitoria

gitoria

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Commit2f2725ac2f2725actests/browser.mjs: commit-row check (one row, centred date)MG2f2725ac/plugins/web/compile.hl

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

Branches

Latest commits

  • 2f2725actests/browser.mjs: commit-row check (one row, centred date)MG
  • 4df1ea01tests/browser.mjs: MG phone checks (list first, no dead strip, one branch heading, tab grid, commit rows, PR title row, ticket columns, wrapping commands)MG
  • c52424e9gitoria mobile: repo list before the forms, 3x2 tab grid, no duplicate branch heading, ordered commit rows, aligned ticket rows, pull title on its own row, wrapping clone commands, no dead strip under formsMG
  • 3a95252dG3: cache parsed README blocks by sha256 of the text (bounded LRU), reportmre
  • 570138cddeploy: security gate (tests/security.mjs)mre
  • da6b20fcgitoria SG: security audit fixes (uploadMax 0, Secure cookie on https, session rotation at login, nosniff on function routes, no identity in page data) + tests/security.mjs gate + reportmre
  • f98c981fgitoria B1: report wordingmre
  • c6364cedgitoria B1: compact Markdown blocks (one kind flag per block/span, empty and false fields omitted); same rendered HTML, page values -67%mre
  • cd99d2feWIP gitoria#22: always render the repo level's slot (missing-repo boot hang), pages render nothing without a repo; hydration diagnosis in reports/G2-hydrate.mdmre
  • e5404b9breport: commit idsmre
  • 63cfa21ereports/G2-repotabs.mdmre
  • 9b0516fdgitoria#22: mark the tab underline functional (check-theme), chain E2E: serve/measure split, bring the lisbeth tab to frontmre
  • 19bc1df8gitoria#22: all repo pages under ONE layout level (components/repo.hl, hl:web D-CHAIN): a tab click replaces only the page in the slot; head and tab nav stay the same DOM nodesmre
  • 40658417tests/browser.mjs: wait for the page to be live (hydrated) before clicking Merge — a click on the server-rendered button before the client mounted was lost (flaky 'Clashing change' under load)mre
  • 48a6154bre-vendor Hybriel 5406d146 (hl:web batches 9+10: #72 emits while the socket is closed delivered after reconnect, browser boot linear, faster list appends; contains int 6–14 + m406)mre
  • e972e8d7tests: short-id-switch (GITORIA_SWITCH_IDENT_PORT/_PORT) and ssh tunnel (GITORIA_GATE_TUNNEL_PORT) ports from env, defaults unchangedmre
  • f06f5349re-vendor Hybriel 6f8a0689 (int 6–11: streaming cursors, #203 index heal + close() fix, fd403 listDir/cursor fds, hl:time browser side, hl:web batches 5+6)mre
  • c7d3cc87docker-compose: nofile 65536 (Hybriel int 6+ boot opened >1024 files in the tracker)mre
  • f0e7ff8cdeploy: backup copies index files first and *.mpack data last (hot-copy skew, hybriel #203)mre
  • fe5f707cgitoria 010: report, mission, comment on why current = true staysmre