goaljs 0.1.1 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +4 -2
- package/package.json +1 -1
- package/src/app.js +28 -3
- package/src/build.js +38 -8
- package/src/compiler.js +34 -8
- package/src/hmr.js +65 -0
- package/src/keyed.js +14 -2
- package/src/loader.js +2 -5
- package/src/rt.js +60 -0
- package/src/server.js +14 -4
package/README.md
CHANGED
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
<img src="https://goallabs.github.io/goal/assets/goal.svg" alt="" width="72" height="72">
|
|
2
|
+
|
|
1
3
|
# goal.js
|
|
2
4
|
|
|
3
5
|
A compiled JavaScript framework where **`var` is state** and **`let`/`const` are computed**. Pages are
|
|
@@ -37,7 +39,7 @@ export function Counter({ start }) {
|
|
|
37
39
|
|
|
38
40
|
```bash
|
|
39
41
|
npm install goaljs
|
|
40
|
-
npx goal dev . # build the app in this folder, serve it on http://localhost:3000,
|
|
42
|
+
npx goal dev . # build the app in this folder, serve it on http://localhost:3000, update live on save
|
|
41
43
|
```
|
|
42
44
|
|
|
43
45
|
[Getting started](https://goallabs.github.io/goal/getting-started) walks through a first app. The docs
|
|
@@ -52,7 +54,7 @@ also cover [routes](https://goallabs.github.io/goal/routes),
|
|
|
52
54
|
|
|
53
55
|
```bash
|
|
54
56
|
npm install
|
|
55
|
-
npm run demo # builds examples/demo, serves it on http://localhost:3000,
|
|
57
|
+
npm run demo # builds examples/demo, serves it on http://localhost:3000, updates live on save
|
|
56
58
|
npm test # the tests, with 100% coverage of src/ required
|
|
57
59
|
npm run bench:virtual # a 100,000-row virtual list in headless Chrome: speed and memory
|
|
58
60
|
```
|
package/package.json
CHANGED
package/src/app.js
CHANGED
|
@@ -165,6 +165,16 @@ function match(routes, method, segs) {
|
|
|
165
165
|
return allow.size ? { allow: [...allow] } : null;
|
|
166
166
|
}
|
|
167
167
|
|
|
168
|
+
/** The state a page kept for each component, sent with a live update; anything else counts as none. */
|
|
169
|
+
function keptState(header) {
|
|
170
|
+
try {
|
|
171
|
+
const v = JSON.parse(header);
|
|
172
|
+
return v && typeof v === 'object' ? v : {};
|
|
173
|
+
} catch {
|
|
174
|
+
return {};
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
|
|
168
178
|
/**
|
|
169
179
|
* A request handler for node:http.
|
|
170
180
|
* @param {{ method: string, path: string, handler: Function }[]} routes
|
|
@@ -198,13 +208,27 @@ export function createApp(routes, { dev = false, staticDirs = [], config = {}, l
|
|
|
198
208
|
|
|
199
209
|
let method = req.method === 'HEAD' ? 'GET' : req.method;
|
|
200
210
|
let form = {};
|
|
211
|
+
const files = {};
|
|
201
212
|
let body;
|
|
202
213
|
if (!SAFE.has(req.method)) {
|
|
203
214
|
const raw = await readBody(req, limit);
|
|
204
215
|
const type = (req.headers['content-type'] ?? '').split(';')[0].trim();
|
|
205
216
|
if (raw.length) {
|
|
206
217
|
if (type === 'application/x-www-form-urlencoded') form = Object.fromEntries(new URLSearchParams(raw.toString()));
|
|
207
|
-
else if (type === '
|
|
218
|
+
else if (type === 'multipart/form-data') {
|
|
219
|
+
// A form with files: its fields go in form, and each file input's files in files, by name.
|
|
220
|
+
// A file input left empty arrives as an empty field.
|
|
221
|
+
let data;
|
|
222
|
+
try {
|
|
223
|
+
data = await new Response(raw, { headers: { 'content-type': req.headers['content-type'] } }).formData();
|
|
224
|
+
} catch {
|
|
225
|
+
return fail(400, 'Bad request');
|
|
226
|
+
}
|
|
227
|
+
for (const [name, v] of data) {
|
|
228
|
+
if (typeof v === 'string') form[name] = v;
|
|
229
|
+
else (files[name] ??= []).push({ name: v.name, type: v.type, size: v.size, data: Buffer.from(await v.arrayBuffer()) });
|
|
230
|
+
}
|
|
231
|
+
} else if (type === 'application/json') {
|
|
208
232
|
try {
|
|
209
233
|
body = JSON.parse(raw);
|
|
210
234
|
} catch {
|
|
@@ -230,10 +254,11 @@ export function createApp(routes, { dev = false, staticDirs = [], config = {}, l
|
|
|
230
254
|
if (m.allow) return send(405, HTML, errorPage('Method not allowed'), { allow: m.allow.join(', ') });
|
|
231
255
|
|
|
232
256
|
const ctx = _$ctx(token);
|
|
233
|
-
|
|
257
|
+
if (dev && req.headers['x-goal-hmr']) ctx.hmr = keptState(req.headers['x-goal-hmr']); // goal dev: a live update (see hmr.js)
|
|
258
|
+
const request = { method, path: url.pathname, url, params: m.params, query: Object.fromEntries(url.searchParams), headers: req.headers, cookies, form, files, json: body };
|
|
234
259
|
const cookie = (name, value, opts) => setCookies.push(serializeCookie(name, value, opts));
|
|
235
260
|
const out = await m.route.handler(request, { ctx, redirect, json, notFound, cookie });
|
|
236
|
-
if (out instanceof Html) return send(200, HTML, page(out.s, [...ctx.ev], nonce, token));
|
|
261
|
+
if (out instanceof Html) return send(200, HTML, page(out.s, [...ctx.ev], nonce, token, dev));
|
|
237
262
|
if (out === undefined) return send(204);
|
|
238
263
|
if (out?.[REPLY]) return send(out.status, out.type, out.body, out.headers);
|
|
239
264
|
throw new Error('a route returns markup, redirect(), json(), notFound() or nothing');
|
package/src/build.js
CHANGED
|
@@ -88,7 +88,9 @@ export async function build(app, { out = join(app, 'dist'), dev = false, publicP
|
|
|
88
88
|
const target = posix.join(posix.dirname(rel), spec);
|
|
89
89
|
return exported.has(target) ? { base: target.slice(0, -5), names: exported.get(target) } : null;
|
|
90
90
|
};
|
|
91
|
-
|
|
91
|
+
// In dev a chunk's URL names the build, so a page updated live loads the new code.
|
|
92
|
+
const chunk = (n) => `${publicPath}c/${base}.${n}.js${dev ? `?v=${version}` : ''}`;
|
|
93
|
+
const r = compile(readFileSync(join(app, rel), 'utf8'), { file: rel, base, rt: RT, keyed: KEYED, chunk, serverFunctions, dev });
|
|
92
94
|
const server = r.server.replace(/((?:from|import)\s*["'])(\.{1,2}\/[^"']+?)(\.goal|\.m?js)(["'])/g, (_, a, p, ext, b) => `${a}${p}${ext === '.goal' ? '.js' : ext}?v=${version}${b}`);
|
|
93
95
|
write(join(out, 'server', base + '.js'), server);
|
|
94
96
|
if (r.routes.length || r.serverFunctions.length) routeFiles.push(base);
|
|
@@ -144,39 +146,67 @@ export async function build(app, { out = join(app, 'dist'), dev = false, publicP
|
|
|
144
146
|
return { version, chunks, loader: gzipSync(loaderScript()).length, routes: routes.map((r) => r.label) };
|
|
145
147
|
}
|
|
146
148
|
|
|
147
|
-
/**
|
|
148
|
-
|
|
149
|
+
/**
|
|
150
|
+
* Serves a built app. `dev` shows error details; `version` names the build to load; `hmr`, the set
|
|
151
|
+
* of pages listening at /_goal/hmr for live updates (goal dev).
|
|
152
|
+
*/
|
|
153
|
+
export async function serve(app, { out = join(app, 'dist'), port = 3000, dev = false, version = () => '', log = console.error, hmr } = {}) {
|
|
149
154
|
const configFile = join(app, 'goal.config.js');
|
|
150
155
|
const config = existsSync(configFile) ? (await import(pathToFileURL(configFile).href)).default : {};
|
|
151
156
|
const routesFile = pathToFileURL(join(out, 'server', '_routes.js')).href;
|
|
152
157
|
const server = createServer(async (req, res) => {
|
|
158
|
+
if (hmr && req.url === '/_goal/hmr') {
|
|
159
|
+
res.writeHead(200, { 'content-type': 'text/event-stream', 'cache-control': 'no-store' });
|
|
160
|
+
res.write(': goal dev\n\n');
|
|
161
|
+
hmr.add(res);
|
|
162
|
+
req.on('close', () => hmr.delete(res));
|
|
163
|
+
return;
|
|
164
|
+
}
|
|
153
165
|
const routes = (await import(`${routesFile}?v=${version()}`)).default;
|
|
154
166
|
return createApp(routes, { dev, config, log, staticDirs: [join(out, 'client'), join(out, 'public')] })(req, res);
|
|
155
167
|
});
|
|
156
168
|
return new Promise((ok) => server.listen(port, () => ok(server)));
|
|
157
169
|
}
|
|
158
170
|
|
|
159
|
-
/**
|
|
171
|
+
/**
|
|
172
|
+
* Builds, serves with error details, and builds again when a source file changes. Open pages update
|
|
173
|
+
* live (see hmr.js): after a build they're told that a stylesheet changed, that code did, or what the
|
|
174
|
+
* compile error is.
|
|
175
|
+
*/
|
|
160
176
|
export async function dev(app, { port = 3000, log = console.log } = {}) {
|
|
161
177
|
let version = '';
|
|
162
|
-
const
|
|
178
|
+
const pages = new Set();
|
|
179
|
+
const tell = (m) => {
|
|
180
|
+
for (const res of pages) res.write(`data: ${JSON.stringify(m)}\n\n`);
|
|
181
|
+
};
|
|
182
|
+
const rebuild = async (changed = []) => {
|
|
163
183
|
try {
|
|
164
184
|
const r = await build(app, { dev: true });
|
|
165
185
|
version = r.version;
|
|
166
186
|
log(`built: ${r.routes.length} route(s), ${r.chunks.length} chunk(s)`);
|
|
187
|
+
tell({ type: changed.length && changed.every((f) => f.endsWith('.css')) ? 'css' : 'update', version });
|
|
167
188
|
} catch (e) {
|
|
168
189
|
log(e.message);
|
|
190
|
+
tell({ type: 'error', message: e.message });
|
|
169
191
|
}
|
|
170
192
|
};
|
|
171
193
|
await rebuild();
|
|
172
194
|
process.setSourceMapsEnabled(true); // stack traces point at the .goal files
|
|
173
|
-
const server = await serve(app, { port, dev: true, version: () => version, log });
|
|
195
|
+
const server = await serve(app, { port, dev: true, version: () => version, log, hmr: pages });
|
|
174
196
|
let timer;
|
|
197
|
+
let changed = [];
|
|
175
198
|
const watcher = watch(app, { recursive: true }, (_, f) => {
|
|
176
199
|
if (!/\.(goal|m?js|json|css)$/.test(String(f)) || String(f).startsWith('dist')) return;
|
|
200
|
+
changed.push(String(f));
|
|
177
201
|
clearTimeout(timer);
|
|
178
|
-
timer = setTimeout(rebuild, 30);
|
|
202
|
+
timer = setTimeout(() => rebuild(changed.splice(0)), 30);
|
|
179
203
|
});
|
|
180
|
-
|
|
204
|
+
// The pages' streams stay open, so close them for the server to close.
|
|
205
|
+
const close = server.close.bind(server);
|
|
206
|
+
server.close = (done) => {
|
|
207
|
+
watcher.close();
|
|
208
|
+
for (const res of pages) res.end();
|
|
209
|
+
return close(done);
|
|
210
|
+
};
|
|
181
211
|
return server;
|
|
182
212
|
}
|
package/src/compiler.js
CHANGED
|
@@ -76,18 +76,19 @@ function emit(node) {
|
|
|
76
76
|
/**
|
|
77
77
|
* Compiles one .goal file.
|
|
78
78
|
* @param {string} source
|
|
79
|
-
* @param {{ file?: string, base?: string, rt?: string,
|
|
80
|
-
* serverFunctions?: (specifier: string) => { base: string, names: string[] } | null }} [opts]
|
|
79
|
+
* @param {{ file?: string, base?: string, rt?: string, keyed?: string, chunk?: (name: string) => string,
|
|
80
|
+
* serverFunctions?: (specifier: string) => { base: string, names: string[] } | null, dev?: boolean }} [opts]
|
|
81
81
|
* file: the name in errors and source maps; base: the file's path without .goal, which names its
|
|
82
82
|
* server functions' URLs (/_m/<base>/<name>); rt and keyed: where compiled code imports the helpers
|
|
83
83
|
* and the keyed list patcher from;
|
|
84
84
|
* chunk: the URL the browser loads a component's client module from; serverFunctions: the server
|
|
85
|
-
* functions another .goal file exports, for imports of it
|
|
85
|
+
* functions another .goal file exports, for imports of it; dev: for goal dev, where a component
|
|
86
|
+
* rendered for a live update starts from the state the page kept (see hmr.js).
|
|
86
87
|
*/
|
|
87
88
|
export function compile(source, opts = {}) {
|
|
88
89
|
const file = opts.file ?? 'input.goal';
|
|
89
90
|
const base = opts.base ?? file.replace(/\.goal$/, '');
|
|
90
|
-
const o = { file, rt: opts.rt ?? 'goaljs/rt', keyed: opts.keyed ?? 'goaljs/keyed', chunk: opts.chunk ?? ((n) => `/${n}.js`), sfns: new Map() };
|
|
91
|
+
const o = { file, rt: opts.rt ?? 'goaljs/rt', keyed: opts.keyed ?? 'goaljs/keyed', chunk: opts.chunk ?? ((n) => `/${n}.js`), dev: !!opts.dev, sfns: new Map() };
|
|
91
92
|
const d = desugar(source, file);
|
|
92
93
|
SRC = { source, file };
|
|
93
94
|
const ast = parse(d.code, { sourceType: 'module', plugins: ['jsx'] });
|
|
@@ -323,6 +324,7 @@ function component(fn, program, mode, o) {
|
|
|
323
324
|
const pre = [];
|
|
324
325
|
if (param) pre.push(t.variableDeclaration('let', [t.variableDeclarator(patternOf(param), pId)]));
|
|
325
326
|
pre.push(t.variableDeclaration('const', [t.variableDeclarator(cx.iId, t.updateExpression('++', t.memberExpression(cx.cId, t.identifier('i'))))]));
|
|
327
|
+
if (o.dev && interactive && state.length) pre.push(keptState(fn, cx, o.chunk(name).split('?')[0], state));
|
|
326
328
|
if (events.length) pre.push(t.expressionStatement(t.callExpression(t.memberExpression(cx.cId, t.identifier('e')), [t.valueToNode(events)])));
|
|
327
329
|
if (cx.dyn) {
|
|
328
330
|
// The server only numbers the handlers made while rendering; the browser keeps them.
|
|
@@ -341,6 +343,29 @@ function component(fn, program, mode, o) {
|
|
|
341
343
|
|
|
342
344
|
const patternOf = (param) => (t.isAssignmentPattern(param) ? param.left : param);
|
|
343
345
|
|
|
346
|
+
/**
|
|
347
|
+
* goal dev: a live update renders the page again with the state each component had in the browser
|
|
348
|
+
* (ctx.hmr, by instance number). When this instance is the same component, its vars start from that
|
|
349
|
+
* state instead of their initial values; a var it didn't have starts as written.
|
|
350
|
+
*/
|
|
351
|
+
function keptState(fn, cx, chunk, state) {
|
|
352
|
+
const kept = t.identifier('_$o');
|
|
353
|
+
const at = t.memberExpression(t.memberExpression(cx.cId, t.identifier('hmr')), cx.iId, true);
|
|
354
|
+
for (const name of state) {
|
|
355
|
+
const d = fn.scope.getBinding(name).path.node;
|
|
356
|
+
d.init = t.conditionalExpression(
|
|
357
|
+
t.logicalExpression('&&', kept, t.binaryExpression('in', t.stringLiteral(name), kept)),
|
|
358
|
+
t.memberExpression(kept, t.identifier(name)),
|
|
359
|
+
d.init ?? t.identifier('undefined'),
|
|
360
|
+
);
|
|
361
|
+
}
|
|
362
|
+
// _$c.hmr?.[_$i]?.c === chunk ? _$c.hmr[_$i].s : null
|
|
363
|
+
const cOf = t.optionalMemberExpression(t.optionalMemberExpression(t.memberExpression(cx.cId, t.identifier('hmr')), cx.iId, true, true), t.identifier('c'), false, true);
|
|
364
|
+
return t.variableDeclaration('const', [
|
|
365
|
+
t.variableDeclarator(kept, t.conditionalExpression(t.binaryExpression('===', cOf, t.stringLiteral(chunk)), t.memberExpression(at, t.identifier('s')), t.nullLiteral())),
|
|
366
|
+
]);
|
|
367
|
+
}
|
|
368
|
+
|
|
344
369
|
const ROOT = Symbol('root attributes');
|
|
345
370
|
|
|
346
371
|
function rootAttrs(cx, url, state, param, pId, keys) {
|
|
@@ -475,12 +500,12 @@ function element(p, cx, top, root, row) {
|
|
|
475
500
|
row.key = v.node.expression;
|
|
476
501
|
continue;
|
|
477
502
|
}
|
|
478
|
-
//
|
|
503
|
+
// A list in markup that is patched as a whole: inside an element in an {if}, or in another list's
|
|
504
|
+
// row. Its rows carry their key (m-k), and the patch finds each row by it (rt.js). A list that
|
|
505
|
+
// never changes renders once, and needs none.
|
|
479
506
|
const list = mapOf(p);
|
|
480
507
|
if (!list) fail('key goes on the outer element of a list row: items.map((x) => <li key={x.id}>...</li>)', a.node);
|
|
481
|
-
if (cx.inRow
|
|
482
|
-
if (cx.kind === 'component' && changes(list, cx))
|
|
483
|
-
fail('a keyed list that changes goes straight in the markup, or straight in an {if} or a ternary: <ul>{items.map((x) => <li key={x.id}>...</li>)}</ul>', a.node);
|
|
508
|
+
if (cx.inRow || (cx.kind === 'component' && changes(list, cx))) parts.push(t.callExpression(t.identifier('_$a'), [t.stringLiteral('m-k'), v.node.expression]));
|
|
484
509
|
continue;
|
|
485
510
|
}
|
|
486
511
|
if (/^on/i.test(name)) {
|
|
@@ -839,6 +864,7 @@ function clientModule(program, info, o) {
|
|
|
839
864
|
} else if (t.isStatement(d) && !/^_\$t\d/.test(d.declarations?.[0].id.name)) body.push(t.cloneNode(d, true)); // `export { a }` and `export default expr` are dropped
|
|
840
865
|
}
|
|
841
866
|
body.push(...info.tpls.map((x) => t.cloneNode(x, true)), ...clientComponent(comp, info)); // row templates before _$k reads them
|
|
867
|
+
if (info.binds.some((b) => b.k[0] === 0)) body.push(t.exportNamedDeclaration(null, [t.exportSpecifier(t.identifier('_$hm'), t.identifier('_$hm'))], t.stringLiteral(o.rt)));
|
|
842
868
|
if (info.binds.some((b) => b.k[0] === 2))
|
|
843
869
|
body.push(
|
|
844
870
|
t.exportNamedDeclaration(null, [t.exportSpecifier(t.identifier('_$lp'), t.identifier('_$lp'))], t.stringLiteral(o.keyed)),
|
package/src/hmr.js
ADDED
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
// goal dev's live updates, in the page. After each build the dev server says what changed (see dev()
|
|
2
|
+
// in build.js). A stylesheet is swapped in place. For code, the page asks the server for itself again,
|
|
3
|
+
// sending the state each component has now, and puts the new body in place of the old one: the
|
|
4
|
+
// components keep their state, and the loader runs the new code on the next event. A compile error
|
|
5
|
+
// shows over the page until a build works again. Only goal dev pages have this.
|
|
6
|
+
|
|
7
|
+
/** Listens for the dev server's updates. `connect` opens the stream; tests pass their own. */
|
|
8
|
+
export function hmr(d, w, connect = (url) => new w.EventSource(url)) {
|
|
9
|
+
let box; // the compile error, over the page
|
|
10
|
+
const show = (text) => {
|
|
11
|
+
box?.remove();
|
|
12
|
+
box = null;
|
|
13
|
+
if (!text) return;
|
|
14
|
+
box = d.createElement('pre');
|
|
15
|
+
box.id = 'goal-dev-error';
|
|
16
|
+
box.textContent = text;
|
|
17
|
+
Object.assign(box.style, {
|
|
18
|
+
position: 'fixed',
|
|
19
|
+
inset: '0',
|
|
20
|
+
zIndex: '2147483647',
|
|
21
|
+
margin: '0',
|
|
22
|
+
padding: '24px',
|
|
23
|
+
overflow: 'auto',
|
|
24
|
+
whiteSpace: 'pre-wrap',
|
|
25
|
+
background: '#1b1b1f',
|
|
26
|
+
color: '#ffb4ab',
|
|
27
|
+
font: '14px/1.5 ui-monospace, Menlo, monospace',
|
|
28
|
+
});
|
|
29
|
+
d.body.append(box);
|
|
30
|
+
};
|
|
31
|
+
const events = (doc) => JSON.parse(doc.querySelector('meta[name="goal-events"]')?.content || '[]');
|
|
32
|
+
|
|
33
|
+
async function update() {
|
|
34
|
+
const kept = {}; // by instance number: which component, and its state now
|
|
35
|
+
for (const el of d.querySelectorAll('[m-c]'))
|
|
36
|
+
kept[el.getAttribute('m-i')] = { c: el.getAttribute('m-c').split('?')[0], s: el.$s ?? JSON.parse(el.getAttribute('m-s') || '{}') };
|
|
37
|
+
const header = JSON.stringify(kept);
|
|
38
|
+
if (header.length > 8000) return w.location.reload(); // more than a request header should carry
|
|
39
|
+
const res = await w.fetch(w.location.href, { headers: { 'x-goal-hmr': header } });
|
|
40
|
+
const text = await res.text();
|
|
41
|
+
if (!res.ok) return show(text); // the route failed: goal dev answers with the stack
|
|
42
|
+
const next = new w.DOMParser().parseFromString(text, 'text/html');
|
|
43
|
+
const now = events(d);
|
|
44
|
+
if (events(next).some((e) => !now.includes(e))) return w.location.reload(); // the loader listens only for the events it started with
|
|
45
|
+
for (const s of next.querySelectorAll('script')) s.remove(); // this page's loader and updates keep running
|
|
46
|
+
const { scrollX: x, scrollY: y } = w;
|
|
47
|
+
const focused = d.activeElement?.id;
|
|
48
|
+
d.title = next.title;
|
|
49
|
+
d.body.replaceWith(d.adoptNode(next.body));
|
|
50
|
+
w.scrollTo(x, y);
|
|
51
|
+
if (focused) d.getElementById(focused)?.focus();
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
connect('/_goal/hmr').onmessage = (e) => {
|
|
55
|
+
const m = JSON.parse(e.data);
|
|
56
|
+
if (m.type === 'error') return show(m.message);
|
|
57
|
+
show(null);
|
|
58
|
+
if (m.type === 'update') return update();
|
|
59
|
+
for (const link of d.querySelectorAll('link[rel="stylesheet"]')) {
|
|
60
|
+
const u = new URL(link.href);
|
|
61
|
+
u.searchParams.set('v', m.version);
|
|
62
|
+
link.href = u.href;
|
|
63
|
+
}
|
|
64
|
+
};
|
|
65
|
+
}
|
package/src/keyed.js
CHANGED
|
@@ -4,6 +4,8 @@
|
|
|
4
4
|
// one batch, rows that are gone are removed, and of the kept rows only those out of order are moved
|
|
5
5
|
// (the rest are the longest run already in order).
|
|
6
6
|
|
|
7
|
+
import { into } from './rt.js';
|
|
8
|
+
|
|
7
9
|
const set = (el, name, v, off = v == null || v === false) =>
|
|
8
10
|
name === 'value' ? (el.value = off ? '' : v)
|
|
9
11
|
: name === 'checked' ? (el.checked = !off)
|
|
@@ -16,7 +18,7 @@ const put = (row, [kind, path, name], v) => {
|
|
|
16
18
|
for (const p of path) el = el.children[p];
|
|
17
19
|
const x = el.firstChild;
|
|
18
20
|
if (kind) set(el, name, v);
|
|
19
|
-
else if (/[<&]/.test(v)) el.
|
|
21
|
+
else if (/[<&]/.test(v)) into(el.ownerDocument, el, el.firstChild, null, v); // markup: into the nodes there, keyed rows by key
|
|
20
22
|
else if (x?.nodeType === 3 && !x.nextSibling) x.data = v;
|
|
21
23
|
else el.textContent = v;
|
|
22
24
|
};
|
|
@@ -53,8 +55,18 @@ export function _$lp(d, c, a, b, tpl, parts) {
|
|
|
53
55
|
for (; end.data !== '/'; end = end.nextSibling) old.push(end); // rows are all elements, up to the end marker
|
|
54
56
|
const parent = end.parentNode;
|
|
55
57
|
// Writes a kept row's changed values in place; says no when the row has to be made again.
|
|
58
|
+
// Writes a kept row's changed values in place. A row whose values have no fixed place gets its new
|
|
59
|
+
// markup put into its nodes (rt.js), so what stays the same, an input's focus too, is kept.
|
|
56
60
|
const keep = (r, o, n) => {
|
|
57
|
-
if (r !== o)
|
|
61
|
+
if (r !== o)
|
|
62
|
+
for (let k = 3; k < r.length; k++)
|
|
63
|
+
if (r[k] !== o[k]) {
|
|
64
|
+
if (!parts) {
|
|
65
|
+
into(d, n.parentNode, n, n.nextSibling, tpl(r));
|
|
66
|
+
return 1;
|
|
67
|
+
}
|
|
68
|
+
put(n, parts[k - 3], r[k]);
|
|
69
|
+
}
|
|
58
70
|
return 1;
|
|
59
71
|
};
|
|
60
72
|
// Rows that stay where they were, at the start and at the end, are patched where they are.
|
package/src/loader.js
CHANGED
|
@@ -92,10 +92,7 @@ function patch(d, r, m, a, b) {
|
|
|
92
92
|
while ((c = w.nextNode()) && c.data !== `${i}.${n}`);
|
|
93
93
|
r.$m[n] = c;
|
|
94
94
|
}
|
|
95
|
-
if (kind)
|
|
96
|
-
|
|
97
|
-
const tpl = d.createElement('template');
|
|
98
|
-
tpl.innerHTML = v;
|
|
99
|
-
c.after(tpl.content);
|
|
95
|
+
if (kind) m._$lp(d, c, a[j], v, name, parts); // a keyed list (keyed.js)
|
|
96
|
+
else m._$hm(d, c, v); // a hole's markup, into the nodes there (rt.js)
|
|
100
97
|
});
|
|
101
98
|
}
|
package/src/rt.js
CHANGED
|
@@ -94,3 +94,63 @@ export function _$lh(el, root, x, h, e) {
|
|
|
94
94
|
|
|
95
95
|
/** A keyed list in the browser: its rows, and `h(item, index)`, the handlers of one row. */
|
|
96
96
|
export const _$L = (rows, h) => ((rows.h = h), rows);
|
|
97
|
+
|
|
98
|
+
/**
|
|
99
|
+
* A `{...}` hole's new markup, put into the nodes after its start marker `c` (see into).
|
|
100
|
+
*/
|
|
101
|
+
export function _$hm(d, c, html) {
|
|
102
|
+
let end = c.nextSibling;
|
|
103
|
+
while (end.nodeType !== 8 || end.data !== '/') end = end.nextSibling;
|
|
104
|
+
into(d, c.parentNode, c.nextSibling, end, html);
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/**
|
|
108
|
+
* New markup, put into the nodes of `parent` from `at` up to `end` (null: its last). A node of the
|
|
109
|
+
* same kind as the new one in its place is kept and updated, so a focused input stays focused and
|
|
110
|
+
* keeps what was typed; a row with a key (`m-k`) is found by its key, and moved there. The others
|
|
111
|
+
* are added or removed.
|
|
112
|
+
*/
|
|
113
|
+
export function into(d, parent, at, end, html) {
|
|
114
|
+
const t = d.createElement('template');
|
|
115
|
+
t.innerHTML = html;
|
|
116
|
+
kids(parent, at, end, t.content);
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
const key = (n) => (n.nodeType === 1 ? n.getAttribute('m-k') : null);
|
|
120
|
+
|
|
121
|
+
function kids(parent, at, end, to) {
|
|
122
|
+
for (let n = to.firstChild, next; n; n = next) {
|
|
123
|
+
next = n.nextSibling;
|
|
124
|
+
const k = key(n);
|
|
125
|
+
let old = at;
|
|
126
|
+
if (k !== null) while (old !== end && key(old) !== k) old = old.nextSibling;
|
|
127
|
+
if (old !== end && old.nodeName === n.nodeName && key(old) === k) {
|
|
128
|
+
if (old === at) at = at.nextSibling;
|
|
129
|
+
else parent.insertBefore(old, at);
|
|
130
|
+
same(old, n);
|
|
131
|
+
} else parent.insertBefore(n, at);
|
|
132
|
+
}
|
|
133
|
+
while (at !== end) {
|
|
134
|
+
const x = at.nextSibling;
|
|
135
|
+
at.remove();
|
|
136
|
+
at = x;
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
function same(a, b) {
|
|
141
|
+
if (a.nodeType !== 1) {
|
|
142
|
+
if (a.data !== b.data) a.data = b.data;
|
|
143
|
+
return;
|
|
144
|
+
}
|
|
145
|
+
for (const { name } of [...a.attributes]) if (!b.hasAttribute(name)) attr(a, name, null);
|
|
146
|
+
for (const { name, value } of b.attributes) if (a.getAttribute(name) !== value) attr(a, name, value);
|
|
147
|
+
kids(a, a.firstChild, null, b);
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
/** An attribute that changed. As when the page is rendered, a form control's value and checked follow it. */
|
|
151
|
+
function attr(a, name, v) {
|
|
152
|
+
if (v === null) a.removeAttribute(name);
|
|
153
|
+
else a.setAttribute(name, v);
|
|
154
|
+
if (name === 'value') a.value = v ?? '';
|
|
155
|
+
if (name === 'checked') a.checked = v !== null;
|
|
156
|
+
}
|
package/src/server.js
CHANGED
|
@@ -12,24 +12,34 @@ export function render(Component, props = {}, ctx = _$ctx()) {
|
|
|
12
12
|
return { html, events: [...ctx.ev] };
|
|
13
13
|
}
|
|
14
14
|
|
|
15
|
+
const HERE = dirname(fileURLToPath(import.meta.url));
|
|
15
16
|
const EVENTS = '"__GOAL_EVENTS__"';
|
|
16
17
|
let loaderCode;
|
|
17
18
|
/** The loader, minified, starting itself; the page puts its events where EVENTS is. */
|
|
18
19
|
export function loaderScript() {
|
|
19
|
-
const src = readFileSync(join(
|
|
20
|
+
const src = readFileSync(join(HERE, 'loader.js'), 'utf8');
|
|
20
21
|
loaderCode ??= transformSync(`${src.replace('export function boot', 'function boot')}\nboot(document, ${EVENTS});`, { format: 'iife', minify: true }).code.trim();
|
|
21
22
|
return loaderCode;
|
|
22
23
|
}
|
|
23
24
|
|
|
25
|
+
let hmrCode;
|
|
26
|
+
/** goal dev's live updates in the page (hmr.js), minified, starting itself. */
|
|
27
|
+
export function hmrScript() {
|
|
28
|
+
hmrCode ??= transformSync(`${readFileSync(join(HERE, 'hmr.js'), 'utf8').replace('export function hmr', 'function hmr')}\nhmr(document, window);`, { format: 'iife', minify: true }).code.trim();
|
|
29
|
+
return hmrCode;
|
|
30
|
+
}
|
|
31
|
+
|
|
24
32
|
/**
|
|
25
33
|
* A whole HTML document. Markup that starts with <html> is the document itself; anything else goes
|
|
26
34
|
* in a plain one. The loader goes in only when there are events, with the request's CSP nonce, and
|
|
27
|
-
* the CSRF token that server function calls send.
|
|
35
|
+
* the CSRF token that server function calls send. In goal dev (`dev`), every page also gets the
|
|
36
|
+
* live updates, and the events it listens for, which an update compares.
|
|
28
37
|
*/
|
|
29
|
-
export function page(html, events, nonce, token = '') {
|
|
30
|
-
|
|
38
|
+
export function page(html, events, nonce, token = '', dev = false) {
|
|
39
|
+
let script = events.length
|
|
31
40
|
? `<meta name="goal-csrf" content="${_$e(token)}"><script type="module" nonce="${nonce}">${loaderScript().replace(EVENTS, JSON.stringify(events))}</script>`
|
|
32
41
|
: '';
|
|
42
|
+
if (dev) script += `<meta name="goal-events" content="${_$e(JSON.stringify(events))}"><script type="module" nonce="${nonce}">${hmrScript()}</script>`;
|
|
33
43
|
if (/^<html[\s>]/.test(html)) {
|
|
34
44
|
const i = html.lastIndexOf('</body>');
|
|
35
45
|
return '<!doctype html>' + (i < 0 ? html + script : html.slice(0, i) + script + html.slice(i));
|