brumate 0.3.0 → 0.4.1
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 +2 -2
- package/check.d.ts +49 -0
- package/dist/{boot-C25Sa6vq.d.ts → boot-SCWYwuUd.d.ts} +8 -10
- package/dist/cli.js +275 -15
- package/dist/cli.js.map +1 -1
- package/dist/client-BBtVTOIt.js +3506 -0
- package/dist/client-BBtVTOIt.js.map +1 -0
- package/dist/{client-D0CqSxoO.d.ts → client-Cs3o4key.d.ts} +390 -181
- package/dist/{client-routes-JTbGtukf.js → client-routes-BtGpYCef.js} +60 -30
- package/dist/client-routes-BtGpYCef.js.map +1 -0
- package/dist/{cookies-BzllthiF.js → cookies-Cnbf4w-S.js} +14 -7
- package/dist/cookies-Cnbf4w-S.js.map +1 -0
- package/dist/{defer-BbD7JQhj.js → defer-BLJjxqVc.js} +4 -4
- package/dist/defer-BLJjxqVc.js.map +1 -0
- package/dist/{devtools-CQgD7NPB.js → devtools-DTpsVFbn.js} +56 -82
- package/dist/devtools-DTpsVFbn.js.map +1 -0
- package/dist/{devtools-panel-BVB-W5q4.js → devtools-panel-C1Dfv6nq.js} +397 -333
- package/dist/devtools-panel-C1Dfv6nq.js.map +1 -0
- package/dist/{events-CSs7OwIC.js → events-LgLdp1R7.js} +34 -5
- package/dist/events-LgLdp1R7.js.map +1 -0
- package/dist/features-CHY5Ekku.js +30 -0
- package/dist/features-CHY5Ekku.js.map +1 -0
- package/dist/files-DZIiMDnS.js +506 -0
- package/dist/files-DZIiMDnS.js.map +1 -0
- package/dist/{forms-Cl21hkHt.d.ts → forms-j1xPAR14.d.ts} +3 -3
- package/dist/{forms-Bg-CwGqX.js → forms-nXK7-Lv_.js} +78 -44
- package/dist/forms-nXK7-Lv_.js.map +1 -0
- package/dist/highlight.js +31 -22
- package/dist/highlight.js.map +1 -1
- package/dist/{html-mNTKzaDD.js → html-DS9B1H-M.js} +92 -22
- package/dist/html-DS9B1H-M.js.map +1 -0
- package/dist/{html-Bq1rFxX_.d.ts → html-Gggepsf-.d.ts} +22 -5
- package/dist/index.d.ts +98 -10
- package/dist/index.js +639 -104
- package/dist/index.js.map +1 -1
- package/dist/{inspect-BHpOw1LF.js → inspect-DomFHy5O.js} +3832 -695
- package/dist/inspect-DomFHy5O.js.map +1 -0
- package/dist/{loader-Dos_3NP0.js → loader-D62komKu.js} +20 -14
- package/dist/loader-D62komKu.js.map +1 -0
- package/dist/logo-DQ_OYhBi.js +10 -0
- package/dist/logo-DQ_OYhBi.js.map +1 -0
- package/dist/{navigate-O78d_zGN.js → navigate-CfOr-TRF.js} +94 -31
- package/dist/navigate-CfOr-TRF.js.map +1 -0
- package/dist/nesting-DA5vJw9X.js +265 -0
- package/dist/nesting-DA5vJw9X.js.map +1 -0
- package/dist/{produce-Doc91GkX.js → produce-BNIpmZq2.js} +138 -9
- package/dist/produce-BNIpmZq2.js.map +1 -0
- package/dist/{produce-D0V0ICkz.d.ts → produce-CRfouraC.d.ts} +44 -5
- package/dist/{rpc-ygMRPmN4.js → rpc-BTMb8jap.js} +11 -6
- package/dist/rpc-BTMb8jap.js.map +1 -0
- package/dist/runtime/batch.js +9 -7
- package/dist/runtime/batch.js.map +1 -1
- package/dist/runtime/client.d.ts +4 -4
- package/dist/runtime/client.js +4 -4
- package/dist/runtime/devtools.d.ts +11 -29
- package/dist/runtime/devtools.js +3 -1
- package/dist/runtime/env.js +14 -2
- package/dist/runtime/env.js.map +1 -1
- package/dist/runtime/events.d.ts +23 -1
- package/dist/runtime/events.js +1 -1
- package/dist/runtime/forms.d.ts +2 -2
- package/dist/runtime/forms.js +1 -1
- package/dist/runtime/hot.d.ts +1 -1
- package/dist/runtime/hot.js +5 -2
- package/dist/runtime/hot.js.map +1 -1
- package/dist/runtime/html.d.ts +2 -2
- package/dist/runtime/html.js +1 -1
- package/dist/runtime/loader.d.ts +2 -2
- package/dist/runtime/loader.js +2 -2
- package/dist/runtime/routes.js +4 -1
- package/dist/runtime/routes.js.map +1 -1
- package/dist/runtime/server.d.ts +5 -5
- package/dist/runtime/server.js +5 -5
- package/dist/runtime/signals.d.ts +38 -1
- package/dist/runtime/signals.js +33 -1
- package/dist/runtime/signals.js.map +1 -1
- package/dist/runtime/static-loader.d.ts +2 -2
- package/dist/runtime/static-loader.js +1 -1
- package/dist/runtime/testing.d.ts +18 -3
- package/dist/runtime/testing.js +150 -33
- package/dist/runtime/testing.js.map +1 -1
- package/dist/{server-CxVDYE_V.js → server-BTtsQFFw.js} +633 -163
- package/dist/server-BTtsQFFw.js.map +1 -0
- package/dist/{server-DuFYRXrd.d.ts → server-CYw15Dsg.d.ts} +103 -22
- package/dist/{static-loader-nZssh66R.js → static-loader-C_GYIFtt.js} +79 -99
- package/dist/static-loader-C_GYIFtt.js.map +1 -0
- package/dist/{static-loader-Drpr0AzI.d.ts → static-loader-DVuLmXeu.d.ts} +2 -2
- package/dist/{stream-DCYZO4IF.js → stream-r4V5zBKm.js} +102 -16
- package/dist/stream-r4V5zBKm.js.map +1 -0
- package/dist/vite.d.ts +13 -20
- package/dist/vite.js +1956 -554
- package/dist/vite.js.map +1 -1
- package/elements.d.ts +951 -0
- package/forms/forms.brm.ts +3 -3
- package/package.json +12 -3
- package/skills/brumate/SKILL.md +58 -0
- package/skills/brumate/references/errors.md +2078 -0
- package/skills/brumate/references/events.md +117 -0
- package/skills/brumate/references/signals.md +61 -0
- package/skills/brumate/references/state.md +235 -0
- package/skills/brumate/references/syntax.md +250 -0
- package/types.d.ts +4 -4
- package/dist/client-BD6XT-s5.js +0 -1968
- package/dist/client-BD6XT-s5.js.map +0 -1
- package/dist/client-routes-JTbGtukf.js.map +0 -1
- package/dist/cookies-BzllthiF.js.map +0 -1
- package/dist/defer-BbD7JQhj.js.map +0 -1
- package/dist/devtools-CQgD7NPB.js.map +0 -1
- package/dist/devtools-panel-BVB-W5q4.js.map +0 -1
- package/dist/events-CSs7OwIC.js.map +0 -1
- package/dist/files-BXSSrQgc.js +0 -205
- package/dist/files-BXSSrQgc.js.map +0 -1
- package/dist/forms-Bg-CwGqX.js.map +0 -1
- package/dist/html-mNTKzaDD.js.map +0 -1
- package/dist/inspect-BHpOw1LF.js.map +0 -1
- package/dist/loader-Dos_3NP0.js.map +0 -1
- package/dist/navigate-O78d_zGN.js.map +0 -1
- package/dist/produce-Doc91GkX.js.map +0 -1
- package/dist/rpc-ygMRPmN4.js.map +0 -1
- package/dist/server-CxVDYE_V.js.map +0 -1
- package/dist/static-loader-nZssh66R.js.map +0 -1
- package/dist/stream-DCYZO4IF.js.map +0 -1
|
@@ -148,15 +148,27 @@ async function validateForm(schema, form) {
|
|
|
148
148
|
}
|
|
149
149
|
/** Validates the values of a form in the browser, and groups the errors as `reply` does. */
|
|
150
150
|
async function validateValues(schema, value) {
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
151
|
+
const result = await schema["~standard"].validate(value);
|
|
152
|
+
const issues = [];
|
|
153
|
+
for (const issue of result.issues ?? []) {
|
|
154
|
+
let path;
|
|
155
|
+
if (issue.path) {
|
|
156
|
+
path = [];
|
|
157
|
+
for (const segment of issue.path) {
|
|
158
|
+
const key = typeof segment === "object" ? segment.key : segment;
|
|
159
|
+
path.push(typeof key === "number" ? key : String(key));
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
issues.push({
|
|
163
|
+
message: String(issue.message),
|
|
164
|
+
path
|
|
165
|
+
});
|
|
166
|
+
}
|
|
167
|
+
return groupIssues(issues);
|
|
168
|
+
}
|
|
169
|
+
function isIndex(value) {
|
|
170
|
+
return Number.isInteger(value) && value >= 0 && value <= 999;
|
|
158
171
|
}
|
|
159
|
-
const isIndex = (value) => Number.isInteger(value) && value >= 0 && value <= 999;
|
|
160
172
|
/**
|
|
161
173
|
* Reads the intent that a submit button posted, as JSON. Undefined for a
|
|
162
174
|
* value that is not an intent, such as one with a name that is not a path.
|
|
@@ -212,8 +224,12 @@ function applyIntent(value, intent) {
|
|
|
212
224
|
list: intent.name
|
|
213
225
|
};
|
|
214
226
|
}
|
|
215
|
-
|
|
216
|
-
|
|
227
|
+
function isFile(value) {
|
|
228
|
+
return typeof Blob !== "undefined" && value instanceof Blob;
|
|
229
|
+
}
|
|
230
|
+
function isPlainObject(value) {
|
|
231
|
+
return typeof value === "object" && value !== null && !Array.isArray(value) && !isFile(value) && !(value instanceof Date);
|
|
232
|
+
}
|
|
217
233
|
/** The attributes of a submit button that posts an intent. */
|
|
218
234
|
function intentButton(intent, press) {
|
|
219
235
|
const attrs = {
|
|
@@ -245,7 +261,12 @@ function applyLocalIntent(form, intent, local, result) {
|
|
|
245
261
|
const current = localSince(local, result);
|
|
246
262
|
const before = getAt(values.value, parsePath(intent.name));
|
|
247
263
|
const length = Array.isArray(before) ? before.length : 0;
|
|
248
|
-
|
|
264
|
+
let known = current?.keys[intent.name] ?? (result && !result.reset ? result.keys[intent.name] : void 0);
|
|
265
|
+
if (!known) {
|
|
266
|
+
known = [];
|
|
267
|
+
for (let index = 0; index < length; index++) known.push(String(index));
|
|
268
|
+
}
|
|
269
|
+
const keys = [...known];
|
|
249
270
|
if (intent.type === "insert") keys.splice(intent.index ?? keys.length, 0, `n${nextKey++}`);
|
|
250
271
|
else if (intent.type === "remove") keys.splice(intent.index, 1);
|
|
251
272
|
else keys.splice(intent.to, 0, ...keys.splice(intent.from, 1));
|
|
@@ -274,18 +295,27 @@ function formFields(id, defaultValue, result, { checked, local, press } = {}) {
|
|
|
274
295
|
...changes?.keys
|
|
275
296
|
};
|
|
276
297
|
const replied = {};
|
|
277
|
-
for (const [name, messages] of Object.entries(result && !result.reset ? result.errors : {}))
|
|
298
|
+
for (const [name, messages] of Object.entries(result && !result.reset ? result.errors : {})) {
|
|
299
|
+
let changed = false;
|
|
300
|
+
for (const list of Object.keys(changes?.keys ?? {})) if (name.startsWith(`${list}[`)) {
|
|
301
|
+
changed = true;
|
|
302
|
+
break;
|
|
303
|
+
}
|
|
304
|
+
if (!changed) replied[name] = messages;
|
|
305
|
+
}
|
|
278
306
|
const current = checkedSince(checked, result);
|
|
279
|
-
|
|
280
|
-
|
|
307
|
+
function shows(name) {
|
|
308
|
+
return current !== void 0 && (current.all || current.touched.includes(name));
|
|
309
|
+
}
|
|
310
|
+
function getErrors(name) {
|
|
281
311
|
const source = shows(name) ? current.errors : replied;
|
|
282
312
|
return Object.hasOwn(source, name) ? source[name] : void 0;
|
|
283
|
-
}
|
|
284
|
-
|
|
313
|
+
}
|
|
314
|
+
function state(path, shown) {
|
|
285
315
|
const name = formatPath(path);
|
|
286
316
|
const fieldId = `${id}-${name}`;
|
|
287
317
|
const errorId = `${fieldId}-error`;
|
|
288
|
-
const messages =
|
|
318
|
+
const messages = getErrors(name);
|
|
289
319
|
const attrs = {
|
|
290
320
|
name,
|
|
291
321
|
id: fieldId
|
|
@@ -307,9 +337,9 @@ function formFields(id, defaultValue, result, { checked, local, press } = {}) {
|
|
|
307
337
|
role: "alert"
|
|
308
338
|
} : { id: errorId }
|
|
309
339
|
};
|
|
310
|
-
}
|
|
340
|
+
}
|
|
311
341
|
const posted = value !== void 0;
|
|
312
|
-
|
|
342
|
+
function field(path, fallback, sent) {
|
|
313
343
|
const shown = posted ? sent : fallback;
|
|
314
344
|
const own = state(path, shown);
|
|
315
345
|
if (Array.isArray(shown) || Array.isArray(fallback)) {
|
|
@@ -317,27 +347,31 @@ function formFields(id, defaultValue, result, { checked, local, press } = {}) {
|
|
|
317
347
|
const name = own.name;
|
|
318
348
|
const itemKeys = Object.hasOwn(keys, name) ? keys[name] : void 0;
|
|
319
349
|
const defaults = Array.isArray(fallback) ? fallback : [];
|
|
320
|
-
const list = items.
|
|
321
|
-
|
|
322
|
-
index
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
350
|
+
const list = new Array(items.length);
|
|
351
|
+
for (const [index, item] of items.entries()) {
|
|
352
|
+
if (!(index in items)) continue;
|
|
353
|
+
list[index] = Object.assign(field([...path, index], defaults[index] ?? defaults[0], item), {
|
|
354
|
+
key: itemKeys?.[index] ?? String(index),
|
|
355
|
+
index,
|
|
356
|
+
remove: intentButton({
|
|
357
|
+
type: "remove",
|
|
358
|
+
name,
|
|
359
|
+
index
|
|
360
|
+
}, press),
|
|
361
|
+
moveUp: intentButton({
|
|
362
|
+
type: "reorder",
|
|
363
|
+
name,
|
|
364
|
+
from: index,
|
|
365
|
+
to: Math.max(index - 1, 0)
|
|
366
|
+
}, press),
|
|
367
|
+
moveDown: intentButton({
|
|
368
|
+
type: "reorder",
|
|
369
|
+
name,
|
|
370
|
+
from: index,
|
|
371
|
+
to: Math.min(index + 1, items.length - 1)
|
|
372
|
+
}, press)
|
|
373
|
+
});
|
|
374
|
+
}
|
|
341
375
|
return Object.assign(own, {
|
|
342
376
|
list,
|
|
343
377
|
insert: intentButton({
|
|
@@ -354,7 +388,7 @@ function formFields(id, defaultValue, result, { checked, local, press } = {}) {
|
|
|
354
388
|
return path.length === 0 ? fields : Object.assign(own, { fields });
|
|
355
389
|
}
|
|
356
390
|
return own;
|
|
357
|
-
}
|
|
391
|
+
}
|
|
358
392
|
return field([], defaultValue, value);
|
|
359
393
|
}
|
|
360
394
|
/** The check of the browser when it came after the last reply, or undefined when a reply came after it. */
|
|
@@ -365,7 +399,7 @@ function checkedSince(checked, result) {
|
|
|
365
399
|
* The errors of the whole form: those that the browser found, when it
|
|
366
400
|
* checked every field since the last reply, or else those of the reply.
|
|
367
401
|
*/
|
|
368
|
-
function
|
|
402
|
+
function getFormErrors(result, checked) {
|
|
369
403
|
const current = checkedSince(checked, result);
|
|
370
404
|
const errors = current?.all ? current.formErrors : result?.formErrors;
|
|
371
405
|
return errors && errors.length > 0 ? errors : void 0;
|
|
@@ -401,6 +435,6 @@ const DEFAULT_SUBMIT = {
|
|
|
401
435
|
style: "position:absolute;width:1px;height:1px;overflow:hidden;clip-path:inset(50%);white-space:nowrap;border:0;padding:0;margin:-1px"
|
|
402
436
|
};
|
|
403
437
|
//#endregion
|
|
404
|
-
export { validateValues as S, localSince as _, applyIntent as a, setAt as b, checkedSince as c,
|
|
438
|
+
export { validateValues as S, localSince as _, applyIntent as a, setAt as b, checkedSince as c, formatPath as d, getAt as f, intentValue as g, intentButton as h, MAX_INDEX as i, formFields as l, groupIssues as m, FORBIDDEN as n, applyLocalIntent as o, getFormErrors as p, INTENT as r, checkField as s, DEFAULT_SUBMIT as t, formValues as u, parseIntent as v, validateForm as x, parsePath as y };
|
|
405
439
|
|
|
406
|
-
//# sourceMappingURL=forms-
|
|
440
|
+
//# sourceMappingURL=forms-nXK7-Lv_.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"forms-nXK7-Lv_.js","names":[],"sources":["../src/runtime/forms.ts"],"sourcesContent":["// The parts of progressive forms that the server and the browser share: the\n// paths of field names, intents, the reply of a submission, and the state of\n// the fields that `createForm` shows. Nothing here reads the server, so the\n// code of `brumate/forms` can run it in the browser.\n\n/** A part of the path of a field: a key of an object, or an index of a list. */\nexport type PathSegment = string | number;\n\n/** The name of the submit button that holds an intent. */\nexport const INTENT = '__intent';\n\n/** The largest index of a list item in a field name, so a form cannot make a huge array. */\nexport const MAX_INDEX = 999;\n\n/** Names that would change the prototype of an object, or reach the one of its constructor. */\nexport const FORBIDDEN: ReadonlySet<string> = new Set(['__proto__', 'constructor', 'prototype']);\n\n/**\n * The path of a field name: `items[0].name` is `['items', 0, 'name']`.\n * Dots separate keys, and `[n]` is the index of a list item. A number\n * between dots stays a key. Undefined for a name that is not a path, such\n * as one with an empty key, an index above `MAX_INDEX`, or a key such as\n * `__proto__`.\n */\nexport function parsePath(name: string): PathSegment[] | undefined {\n const path: PathSegment[] = [];\n for (const part of name.split('.')) {\n const match = /^([^[\\]]+)((?:\\[\\d+\\])*)$/.exec(part);\n if (!match || FORBIDDEN.has(match[1]!)) {\n return undefined;\n }\n path.push(match[1]!);\n for (const index of match[2]!.matchAll(/\\[(\\d+)\\]/g)) {\n const value = Number(index[1]);\n if (value > MAX_INDEX || (index[1]!.length > 1 && index[1]!.startsWith('0'))) {\n return undefined;\n }\n path.push(value);\n }\n }\n return path;\n}\n\n/** The field name of a path: `['items', 0, 'name']` is `items[0].name`. */\nexport function formatPath(path: readonly PathSegment[]): string {\n let name = '';\n for (const segment of path) {\n if (typeof segment === 'number') {\n name += `[${segment}]`;\n } else {\n name += name ? `.${segment}` : segment;\n }\n }\n return name;\n}\n\n/** The value at a path, or undefined when a part of the path is missing. */\nexport function getAt(value: unknown, path: readonly PathSegment[]): unknown {\n let current = value;\n for (const segment of path) {\n if (typeof current !== 'object' || current === null || !Object.hasOwn(current, segment)) {\n return undefined;\n }\n current = (current as Record<PathSegment, unknown>)[segment];\n }\n return current;\n}\n\n/**\n * A copy of `value` with `next` at the path. The objects and lists along the\n * path are copied, and the others are shared. A missing part becomes a list\n * for an index and an object for a key.\n */\nexport function setAt(value: unknown, path: readonly PathSegment[], next: unknown): unknown {\n if (path.length === 0) {\n return next;\n }\n const [segment, ...rest] = path as [PathSegment, ...PathSegment[]];\n let copy: Record<PathSegment, unknown> | unknown[];\n if (Array.isArray(value)) {\n copy = [...(value as unknown[])];\n } else if (typeof value === 'object' && value !== null) {\n copy = { ...value };\n } else {\n copy = typeof segment === 'number' ? [] : {};\n }\n const child = Object.hasOwn(copy, segment)\n ? (copy as Record<PathSegment, unknown>)[segment]\n : undefined;\n (copy as Record<PathSegment, unknown>)[segment] = setAt(child, rest, next);\n return copy;\n}\n\n/** A problem that a schema found in the values of a form. */\nexport interface FormIssue {\n message: string;\n path?: PathSegment[];\n}\n\n/** The errors of a form: those of each field by field name, and those of the whole form. */\nexport interface FormErrors {\n errors: Record<string, string[]>;\n formErrors: string[];\n}\n\n/**\n * Turns the entries of a form into a plain object:\n *\n * - A name that appears once holds its value.\n * - A name that appears more than once holds an array of its values.\n * - A name that ends with `[]` always holds an array, under the name without `[]`.\n * - Dots nest objects: `address.city` is `{ address: { city } }`.\n * - An index in brackets makes a list: `items[0].name` is `{ items: [{ name }] }`.\n * - Values stay strings and files.\n *\n * A name with an empty part, a part such as `__proto__`, an index above\n * 999, or one that needs an object where another field holds a value, is\n * an issue, and the schema does not run.\n */\nexport function formValues(\n form: FormData,\n skip?: (name: string) => boolean,\n):\n | { value: Record<string, unknown>; issues?: undefined }\n | { value?: undefined; issues: FormIssue[] } {\n const root: Record<string, unknown> = {};\n // The objects and lists of items that this function made, so a field value is never taken for one.\n const containers = new Set<unknown>([root]);\n // The arrays of the values of a repeated name.\n const repeated = new Set<unknown>();\n const issues: FormIssue[] = [];\n for (const [name, value] of form) {\n if (skip?.(name)) {\n continue;\n }\n const list = name.endsWith('[]');\n const parts = parsePath(list ? name.slice(0, -2) : name);\n if (!parts) {\n issues.push({ message: 'The form has a field name that is not allowed' });\n continue;\n }\n let target = root as Record<PathSegment, unknown>;\n let conflict = false;\n for (const [index, part] of parts.slice(0, -1).entries()) {\n const next = Object.hasOwn(target, part) ? target[part] : undefined;\n // A list takes only indexes, and an object only keys.\n if (Array.isArray(target) !== (typeof part === 'number')) {\n conflict = true;\n break;\n }\n if (next === undefined) {\n const child = typeof parts[index + 1] === 'number' ? [] : {};\n containers.add(child);\n target[part] = child;\n target = child as Record<PathSegment, unknown>;\n } else if (containers.has(next)) {\n target = next as Record<PathSegment, unknown>;\n } else {\n conflict = true;\n break;\n }\n }\n const last = parts.at(-1)!;\n const current = Object.hasOwn(target, last) ? target[last] : undefined;\n if (\n conflict ||\n containers.has(current) ||\n Array.isArray(target) !== (typeof last === 'number')\n ) {\n issues.push({ message: `Field \"${name}\" conflicts with another field`, path: parts });\n } else if (repeated.has(current)) {\n (current as unknown[]).push(value);\n } else if (current !== undefined || list) {\n const values = current === undefined ? [value] : [current, value];\n repeated.add(values);\n target[last] = values;\n } else {\n target[last] = value;\n }\n }\n return issues.length > 0 ? { issues } : { value: root };\n}\n\n/** The errors of issues by field name, such as `items[0].name`, and those of the whole form. */\nexport function groupIssues(issues: readonly FormIssue[]): FormErrors {\n const errors: Record<string, string[]> = {};\n const formErrors: string[] = [];\n for (const issue of issues) {\n const path = issue.path ?? [];\n const name = path.length > 0 && typeof path[0] === 'string' ? formatPath(path) : '';\n if (name === '' || !parsePath(name)) {\n formErrors.push(issue.message);\n } else {\n (Object.hasOwn(errors, name) ? errors[name]! : (errors[name] = [])).push(issue.message);\n }\n }\n return { errors, formErrors };\n}\n\n/** The schema of a form, as `createForm` reads it: a Standard Schema of version 1. */\ninterface FormSchema {\n readonly '~standard': {\n readonly validate: (value: unknown) => unknown;\n };\n}\n\n/**\n * Validates the fields of a form in the browser, with the schema that the\n * server uses, and groups the errors as `reply` does.\n */\nexport async function validateForm(schema: FormSchema, form: FormData): Promise<FormErrors> {\n const values = formValues(form, (name) => name === INTENT);\n return values.issues ? groupIssues(values.issues) : validateValues(schema, values.value);\n}\n\n/** Validates the values of a form in the browser, and groups the errors as `reply` does. */\nexport async function validateValues(schema: FormSchema, value: unknown): Promise<FormErrors> {\n const result = (await schema['~standard'].validate(value)) as {\n issues?: readonly { message: string; path?: readonly (PathSegment | { key: PropertyKey })[] }[];\n };\n const issues: FormIssue[] = [];\n for (const issue of result.issues ?? []) {\n let path: (string | number)[] | undefined;\n if (issue.path) {\n path = [];\n for (const segment of issue.path) {\n const key = typeof segment === 'object' ? segment.key : segment;\n path.push(typeof key === 'number' ? key : String(key));\n }\n }\n issues.push({ message: String(issue.message), path });\n }\n return groupIssues(issues);\n}\n\n/**\n * The errors that the browser found since the last reply: the fields that\n * the user left or changed, and the errors of the form at that time.\n */\nexport interface CheckedErrors extends FormErrors {\n /** The ID of the reply that the check came after, or undefined before the first submit. */\n reply: string | undefined;\n /** The names of the fields that the user left, whose errors show. */\n touched: string[];\n /** True when the errors of every field show, as after a submit. */\n all: boolean;\n}\n\n/**\n * A change that a submit button asks for, instead of a submit. The server\n * applies it to the posted values, and answers with them.\n *\n * - `insert` adds an item to a list, at `index` or at its end.\n * - `remove` removes the item at `index`.\n * - `reorder` moves the item at `from` to `to`.\n * - `reset` sets a field, or the whole form, back to its default value.\n * - `validate` answers with the errors of one field.\n */\nexport type Intent =\n | { type: 'insert'; name: string; index?: number; defaultValue?: unknown }\n | { type: 'remove'; name: string; index: number }\n | { type: 'reorder'; name: string; from: number; to: number }\n | { type: 'reset'; name?: string }\n | { type: 'validate'; name: string };\n\nfunction isIndex(value: unknown): value is number {\n return Number.isInteger(value) && (value as number) >= 0 && (value as number) <= MAX_INDEX;\n}\n\n/**\n * Reads the intent that a submit button posted, as JSON. Undefined for a\n * value that is not an intent, such as one with a name that is not a path.\n */\nexport function parseIntent(text: string): Intent | undefined {\n let intent: unknown;\n try {\n intent = JSON.parse(text);\n } catch {\n return undefined;\n }\n if (typeof intent !== 'object' || intent === null) {\n return undefined;\n }\n const { type, name, index, from, to } = intent as Record<string, unknown>;\n if (name !== undefined && (typeof name !== 'string' || !parsePath(name))) {\n return undefined;\n }\n switch (type) {\n case 'insert':\n return name !== undefined && (index === undefined || isIndex(index))\n ? (intent as Intent)\n : undefined;\n case 'remove':\n return name !== undefined && isIndex(index) ? (intent as Intent) : undefined;\n case 'reorder':\n return name !== undefined && isIndex(from) && isIndex(to) ? (intent as Intent) : undefined;\n case 'reset':\n return intent as Intent;\n case 'validate':\n return name !== undefined ? (intent as Intent) : undefined;\n default:\n return undefined;\n }\n}\n\n/** The value of a submit button that posts an intent. */\nexport function intentValue(intent: Intent): string {\n return JSON.stringify(intent);\n}\n\n/**\n * Applies an intent to the posted values. Returns the new values, and the\n * name of the list that it changed. Undefined when the intent does not fit\n * the values, such as an index past the end of the list.\n */\nexport function applyIntent(\n value: unknown,\n intent: Intent,\n): { value: unknown; list?: string } | undefined {\n if (intent.type === 'validate') {\n return { value };\n }\n if (intent.type === 'reset') {\n return {\n value:\n intent.name === undefined ? undefined : setAt(value, parsePath(intent.name)!, undefined),\n };\n }\n const path = parsePath(intent.name)!;\n const current = getAt(value, path) ?? [];\n if (!Array.isArray(current)) {\n return undefined;\n }\n const items = [...current];\n if (intent.type === 'insert') {\n const index = intent.index ?? items.length;\n if (index > items.length || items.length > MAX_INDEX) {\n return undefined;\n }\n items.splice(index, 0, intent.defaultValue);\n } else if (intent.type === 'remove') {\n if (intent.index >= items.length) {\n return undefined;\n }\n items.splice(intent.index, 1);\n } else {\n if (intent.from >= items.length || intent.to >= items.length) {\n return undefined;\n }\n items.splice(intent.to, 0, ...items.splice(intent.from, 1));\n }\n return { value: setAt(value, path, items), list: intent.name };\n}\n\n/**\n * What a server function of a form answers, for `createForm` to show. It is\n * plain data, so it goes through `$action` and the state of the page.\n */\nexport interface SubmissionResult {\n /** `success` when the values passed the schema, `error` when not, and `intent` for an intent. */\n status: 'success' | 'error' | 'intent';\n /**\n * The values as posted, after the intent, for the fields to show again.\n * Files and hidden fields are left out. Undefined after a reset, so the\n * fields show their default values.\n */\n value?: unknown;\n /** The errors of each field, by field name, such as `items[0].name`. */\n errors: Record<string, string[]>;\n /** The errors of the whole form. */\n formErrors: string[];\n /**\n * The keys of the items of a list that an intent changed, by field name.\n * They are new, so `#for … by` renders the items again, and an element\n * never shows another item. Other lists keep the index as the key.\n */\n keys: Record<string, string[]>;\n /** True when the form goes back to its default values, such as after a save. */\n reset?: boolean;\n /** A new ID for each reply, which keys of new items start with. */\n id: string;\n}\n\n/** The attributes of a submit button that posts an intent. They work without scripts. */\nexport interface IntentAttributes {\n type: 'submit';\n name: typeof INTENT;\n value: string;\n formnovalidate: true;\n /** With scripts, applies the intent in the browser instead of posting the form. */\n onClick?: (event: MouseEvent) => unknown;\n}\n\n/**\n * The changes of lists that the browser made since the last reply: the\n * values of the form after them, and the keys of the items of each list.\n */\nexport interface LocalChanges {\n /** The ID of the reply that the changes came after, or undefined before the first submit. */\n reply: string | undefined;\n value: unknown;\n /** The keys of the items of each list that changed, by field name. */\n keys: Record<string, string[]>;\n}\n\n/** What `formFields` reads besides the reply: the state of the browser, and the handler of intents. */\nexport interface FormState {\n checked?: CheckedErrors;\n local?: LocalChanges;\n /** The click handler of an intent button. */\n press?: (intent: Intent) => (event: MouseEvent) => unknown;\n}\n\n/** The attributes of a field that `createForm` gives. */\nexport interface FieldAttributes {\n name: string;\n id: string;\n 'aria-invalid'?: 'true';\n 'aria-describedby'?: string;\n value?: string;\n checked?: boolean;\n}\n\n/** The state of a field: its name, its value and its errors. */\nexport interface FieldState<T = unknown> {\n /** The field name, such as `items[0].name`. */\n name: string;\n /** The ID of the input, for a `<label for>`. */\n id: string;\n /** The value that the field shows: the posted value after a submit, or the default value. */\n value: T | undefined;\n /** The errors of the field, or undefined when it has none. */\n errors: string[] | undefined;\n /** The attributes of the input: `name`, `id`, the ARIA state of its errors and its value. */\n attrs: FieldAttributes;\n /** The attributes of the element that shows the errors: its ID, and `role=\"alert\"` after a submit. */\n errorAttrs: { id: string; role?: 'alert' };\n}\n\n/** An item of a list field. */\nexport type ListItem<T> = Field<T> & {\n /** A key that stays with the item when others are added or removed, for `#for … by`. */\n key: string;\n index: number;\n /** The attributes of a button that removes the item. */\n remove: IntentAttributes;\n /** The attributes of a button that moves the item up, or down. */\n moveUp: IntentAttributes;\n moveDown: IntentAttributes;\n};\n\n/** A field, typed by its value: a list has its items, and an object its fields. */\nexport type Field<T> = FieldState<T> &\n (NonNullable<T> extends readonly (infer Item)[]\n ? {\n list: ListItem<Item>[];\n /** The attributes of a button that adds an item at the end of the list. */\n insert: IntentAttributes;\n }\n : NonNullable<T> extends Date | File | Blob\n ? unknown\n : NonNullable<T> extends object\n ? { fields: Fields<NonNullable<T>> }\n : unknown);\n\n/** The fields of an object, by key. */\nexport type Fields<T> = { [K in keyof T]-?: Field<T[K]> };\n\nfunction isFile(value: unknown): boolean {\n return typeof Blob !== 'undefined' && value instanceof Blob;\n}\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n return (\n typeof value === 'object' &&\n value !== null &&\n !Array.isArray(value) &&\n !isFile(value) &&\n !(value instanceof Date)\n );\n}\n\n/** The attributes of a submit button that posts an intent. */\nexport function intentButton(\n intent: Intent,\n press?: (intent: Intent) => (event: MouseEvent) => unknown,\n): IntentAttributes {\n const attrs: IntentAttributes = {\n type: 'submit',\n name: INTENT,\n value: intentValue(intent),\n formnovalidate: true,\n };\n if (press) {\n attrs.onClick = press(intent);\n }\n return attrs;\n}\n\n/** The changes of the browser when they came after the last reply. */\nexport function localSince(\n local: LocalChanges | undefined,\n result: SubmissionResult | undefined,\n): LocalChanges | undefined {\n return local && local.reply === result?.id ? local : undefined;\n}\n\n/** A key for a new item, which no other item of the page has. */\nlet nextKey = 0;\n\n/**\n * Applies an intent in the browser to the values that the form holds now.\n * The items of the list keep their keys, so their elements and what was\n * typed in them stay, and a new item gets a new key. Undefined when the\n * intent does not fit the values.\n */\nexport function applyLocalIntent(\n form: HTMLFormElement | null,\n intent: Intent,\n local: LocalChanges | undefined,\n result: SubmissionResult | undefined,\n): LocalChanges | undefined {\n if (!form || intent.type === 'reset' || intent.type === 'validate') {\n return undefined;\n }\n const values = formValues(new FormData(form), (name) => name === INTENT);\n const applied = values.value && applyIntent(values.value, intent);\n if (!applied) {\n return undefined;\n }\n const current = localSince(local, result);\n const before = getAt(values.value, parsePath(intent.name)!);\n const length = Array.isArray(before) ? before.length : 0;\n let known =\n current?.keys[intent.name] ?? (result && !result.reset ? result.keys[intent.name] : undefined);\n if (!known) {\n known = [];\n for (let index = 0; index < length; index++) {\n known.push(String(index));\n }\n }\n const keys = [...known];\n if (intent.type === 'insert') {\n keys.splice(intent.index ?? keys.length, 0, `n${nextKey++}`);\n } else if (intent.type === 'remove') {\n keys.splice(intent.index, 1);\n } else {\n keys.splice(intent.to, 0, ...keys.splice(intent.from, 1));\n }\n return {\n reply: result?.id,\n value: applied.value,\n keys: { ...current?.keys, [intent.name]: keys },\n };\n}\n\n/**\n * The fields of a form, from its default value and the reply of its last\n * submit. A field exists for each key of the default value or of the posted\n * value, so the default value names every field that the form shows.\n */\nexport function formFields<T>(\n id: string,\n defaultValue: T | undefined,\n result: SubmissionResult | undefined,\n { checked, local, press }: FormState = {},\n): Fields<T> {\n const changes = localSince(local, result);\n let value: unknown;\n if (changes) {\n value = changes.value;\n } else if (result && !result.reset) {\n value = result.value;\n }\n const submitted = result !== undefined;\n const keys = { ...(result && !result.reset ? result.keys : {}), ...changes?.keys };\n // The errors of the reply for the items of a list that the browser changed are of other items.\n const replied: Record<string, string[]> = {};\n for (const [name, messages] of Object.entries(result && !result.reset ? result.errors : {})) {\n let changed = false;\n for (const list of Object.keys(changes?.keys ?? {})) {\n if (name.startsWith(`${list}[`)) {\n changed = true;\n break;\n }\n }\n if (!changed) {\n replied[name] = messages;\n }\n }\n // The errors that the browser found replace those of the reply, for the fields that it checked.\n const current = checkedSince(checked, result);\n function shows(name: string): boolean {\n return current !== undefined && (current.all || current.touched.includes(name));\n }\n function getErrors(name: string): string[] | undefined {\n const source = shows(name) ? current!.errors : replied;\n return Object.hasOwn(source, name) ? source[name] : undefined;\n }\n\n function state(path: PathSegment[], shown: unknown): FieldState {\n const name = formatPath(path);\n const fieldId = `${id}-${name}`;\n const errorId = `${fieldId}-error`;\n const messages = getErrors(name);\n const attrs: FieldAttributes = { name, id: fieldId };\n if (messages) {\n attrs['aria-invalid'] = 'true';\n attrs['aria-describedby'] = errorId;\n }\n if (typeof shown === 'string' || typeof shown === 'number') {\n attrs.value = String(shown);\n } else if (typeof shown === 'boolean') {\n attrs.checked = shown;\n }\n return {\n name,\n id: fieldId,\n value: shown,\n errors: messages,\n attrs,\n errorAttrs: submitted ? { id: errorId, role: 'alert' } : { id: errorId },\n };\n }\n\n // After a submit, the fields show what was posted, and a field that was not posted, such as a\n // checkbox that was not checked, is empty. The default value still gives the shape.\n const posted = value !== undefined;\n function field(path: PathSegment[], fallback: unknown, sent: unknown): unknown {\n const shown = posted ? sent : fallback;\n const own = state(path, shown);\n // A list stays a list when nothing of it was posted, such as a list with no items.\n if (Array.isArray(shown) || Array.isArray(fallback)) {\n const items = Array.isArray(shown) ? shown : [];\n const name = own.name;\n const itemKeys = Object.hasOwn(keys, name) ? keys[name] : undefined;\n const defaults: unknown[] = Array.isArray(fallback) ? fallback : [];\n // oxlint-disable-next-line unicorn/no-new-array -- A list posted with gaps keeps them.\n const list: unknown[] = new Array(items.length);\n for (const [index, item] of items.entries()) {\n if (!(index in items)) {\n continue;\n }\n list[index] = Object.assign(\n // A new item takes the shape of the first default item.\n field([...path, index], defaults[index] ?? defaults[0], item) as object,\n {\n key: itemKeys?.[index] ?? String(index),\n index,\n remove: intentButton({ type: 'remove', name, index }, press),\n moveUp: intentButton(\n {\n type: 'reorder',\n name,\n from: index,\n to: Math.max(index - 1, 0),\n },\n press,\n ),\n moveDown: intentButton(\n {\n type: 'reorder',\n name,\n from: index,\n to: Math.min(index + 1, items.length - 1),\n },\n press,\n ),\n },\n );\n }\n return Object.assign(own, { list, insert: intentButton({ type: 'insert', name }, press) });\n }\n if (isPlainObject(shown) || isPlainObject(fallback)) {\n const defaults = isPlainObject(fallback) ? fallback : {};\n const values = isPlainObject(sent) ? sent : {};\n const fields: Record<string, unknown> = {};\n for (const key of new Set([...Object.keys(defaults), ...Object.keys(posted ? values : {})])) {\n fields[key] = field(\n [...path, key],\n Object.hasOwn(defaults, key) ? defaults[key] : undefined,\n Object.hasOwn(values, key) ? values[key] : undefined,\n );\n }\n return path.length === 0 ? fields : Object.assign(own, { fields });\n }\n return own;\n }\n\n return field([], defaultValue, value) as Fields<T>;\n}\n\n/** The check of the browser when it came after the last reply, or undefined when a reply came after it. */\nexport function checkedSince(\n checked: CheckedErrors | undefined,\n result: SubmissionResult | undefined,\n): CheckedErrors | undefined {\n return checked && checked.reply === result?.id ? checked : undefined;\n}\n\n/**\n * The errors of the whole form: those that the browser found, when it\n * checked every field since the last reply, or else those of the reply.\n */\nexport function getFormErrors(\n result: SubmissionResult | undefined,\n checked: CheckedErrors | undefined,\n): string[] | undefined {\n const current = checkedSince(checked, result);\n const errors = current?.all ? current.formErrors : result?.formErrors;\n return errors && errors.length > 0 ? errors : undefined;\n}\n\n/**\n * The next check of the browser, after the user leaves or changes a field.\n * A field counts once the user leaves it. After a submit, every field counts.\n * Undefined when the event changes nothing, such as typing in a field that\n * the user has not left yet.\n */\nexport async function checkField(\n schema: FormSchema,\n form: HTMLFormElement | null,\n name: string,\n left: boolean,\n checked: CheckedErrors | undefined,\n result: SubmissionResult | undefined,\n): Promise<CheckedErrors | undefined> {\n const current = checkedSince(checked, result);\n const all = result !== undefined && !result.reset;\n const touched = current?.touched ?? [];\n if (!form || !name || name === INTENT || (!left && !all && !touched.includes(name))) {\n return undefined;\n }\n const report = await validateForm(schema, new FormData(form));\n return {\n ...report,\n reply: result?.id,\n touched: touched.includes(name) ? touched : [...touched, name],\n all,\n };\n}\n\n/**\n * The attributes of a submit button that the form presses on Enter. Without\n * it, Enter in a field presses the first submit button of the form, which\n * can be an intent button, such as \"Remove\". It is hidden from sight and\n * from assistive technology, and cannot take focus.\n */\nexport const DEFAULT_SUBMIT = {\n type: 'submit',\n tabindex: -1,\n 'aria-hidden': 'true',\n style:\n 'position:absolute;width:1px;height:1px;overflow:hidden;clip-path:inset(50%);white-space:nowrap;border:0;padding:0;margin:-1px',\n} as const;\n"],"mappings":";;AASA,MAAa,SAAS;;AAGtB,MAAa,YAAY;;AAGzB,MAAa,4BAAiC,IAAI,IAAI;CAAC;CAAa;CAAe;AAAW,CAAC;;;;;;;;AAS/F,SAAgB,UAAU,MAAyC;CACjE,MAAM,OAAsB,CAAC;CAC7B,KAAK,MAAM,QAAQ,KAAK,MAAM,GAAG,GAAG;EAClC,MAAM,QAAQ,4BAA4B,KAAK,IAAI;EACnD,IAAI,CAAC,SAAS,UAAU,IAAI,MAAM,EAAG,GACnC;EAEF,KAAK,KAAK,MAAM,EAAG;EACnB,KAAK,MAA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KAAA,CAC7C;GAEF,OAAO,KAAK,WAAW,IAAI,SAAS,OAAO,OAAO,KAAK,EAAE,OAAO,CAAC;EACnE;EACA,OAAO;CACT;CAEA,OAAO,MAAM,CAAC,GAAG,cAAc,KAAK;AACtC;;AAGA,SAAgB,aACd,SACA,QAC2B;CAC3B,OAAO,WAAW,QAAQ,UAAU,QAAQ,KAAK,UAAU,KAAA;AAC7D;;;;;AAMA,SAAgB,cACd,QACA,SACsB;CACtB,MAAM,UAAU,aAAa,SAAS,MAAM;CAC5C,MAAM,SAAS,SAAS,MAAM,QAAQ,aAAa,QAAQ;CAC3D,OAAO,UAAU,OAAO,SAAS,IAAI,SAAS,KAAA;AAChD;;;;;;;AAQA,eAAsB,WACpB,QACA,MACA,MACA,MACA,SACA,QACoC;CACpC,MAAM,UAAU,aAAa,SAAS,MAAM;CAC5C,MAAM,MAAM,WAAW,KAAA,KAAa,CAAC,OAAO;CAC5C,MAAM,UAAU,SAAS,WAAW,CAAC;CACrC,IAAI,CAAC,QAAQ,CAAC,QAAQ,SAAA,cAAoB,CAAC,QAAQ,CAAC,OAAO,CAAC,QAAQ,SAAS,IAAI,GAC/E;CAGF,OAAO;EACL,GAAG,MAFgB,aAAa,QAAQ,IAAI,SAAS,IAAI,CAAC;EAG1D,OAAO,QAAQ;EACf,SAAS,QAAQ,SAAS,IAAI,IAAI,UAAU,CAAC,GAAG,SAAS,IAAI;EAC7D;CACF;AACF;;;;;;;AAQA,MAAa,iBAAiB;CAC5B,MAAM;CACN,UAAU;CACV,eAAe;CACf,OACE;AACJ"}
|
package/dist/highlight.js
CHANGED
|
@@ -4,9 +4,32 @@ import * as TOKENS from "@twinkleplop/core/tokens";
|
|
|
4
4
|
import { tokenize as tokenize$1 } from "@twinkleplop/css";
|
|
5
5
|
import { tokenize as tokenize$2 } from "@twinkleplop/tsx";
|
|
6
6
|
import { dark, light } from "@twinkleplop/theme-github/tokens";
|
|
7
|
+
//#region src/highlight-keywords.ts
|
|
8
|
+
const BLOCK_KEYWORDS = [
|
|
9
|
+
"if",
|
|
10
|
+
"else if",
|
|
11
|
+
"else",
|
|
12
|
+
"for",
|
|
13
|
+
"repeat",
|
|
14
|
+
"switch",
|
|
15
|
+
"case",
|
|
16
|
+
"default",
|
|
17
|
+
"try",
|
|
18
|
+
"catch",
|
|
19
|
+
"loading",
|
|
20
|
+
"portal",
|
|
21
|
+
"head",
|
|
22
|
+
"client",
|
|
23
|
+
"offscreen",
|
|
24
|
+
"reveal",
|
|
25
|
+
"defer",
|
|
26
|
+
"key",
|
|
27
|
+
"template"
|
|
28
|
+
];
|
|
29
|
+
//#endregion
|
|
7
30
|
//#region src/highlight.ts
|
|
8
31
|
/**
|
|
9
|
-
* A twinkleplop
|
|
32
|
+
* A language of the twinkleplop highlighter (`@twinkleplop/core`) for `.brm` files, for the devtools and the website: HTML-like markup with `{…}`
|
|
10
33
|
* expressions, attribute values without quotes, control flow blocks such as
|
|
11
34
|
* `#if (a) { … }`, dynamic tags `<{tag}>`, and `<script>` and `<style>`
|
|
12
35
|
* blocks. Scripts and expressions are highlighted as TSX, styles as CSS.
|
|
@@ -55,25 +78,6 @@ const BARE_VALUE_CHARS = range([
|
|
|
55
78
|
["\\", "\\"],
|
|
56
79
|
["^", "~"]
|
|
57
80
|
]);
|
|
58
|
-
const BLOCK_KEYWORDS = [
|
|
59
|
-
"if",
|
|
60
|
-
"else if",
|
|
61
|
-
"else",
|
|
62
|
-
"for",
|
|
63
|
-
"repeat",
|
|
64
|
-
"switch",
|
|
65
|
-
"case",
|
|
66
|
-
"default",
|
|
67
|
-
"try",
|
|
68
|
-
"catch",
|
|
69
|
-
"loading",
|
|
70
|
-
"portal",
|
|
71
|
-
"head",
|
|
72
|
-
"client",
|
|
73
|
-
"offscreen",
|
|
74
|
-
"key",
|
|
75
|
-
"template"
|
|
76
|
-
];
|
|
77
81
|
const RAW = TOKENS.raw_svelte_expression;
|
|
78
82
|
const rawSkips = [
|
|
79
83
|
within("\"", "\"", RAW, {
|
|
@@ -234,7 +238,9 @@ const rawGrammar = define_grammar({
|
|
|
234
238
|
});
|
|
235
239
|
let tsxLanguage;
|
|
236
240
|
let cssLanguage;
|
|
237
|
-
|
|
241
|
+
function embedTsx(input) {
|
|
242
|
+
return (tsxLanguage ??= tokenize$2())(input);
|
|
243
|
+
}
|
|
238
244
|
const tokenize = create_language(compile(rawGrammar), [always(embed_grammars({
|
|
239
245
|
[TOKENS.raw_script]: embedTsx,
|
|
240
246
|
[TOKENS.raw_svelte_expression]: embedTsx,
|
|
@@ -251,7 +257,10 @@ function language(options) {
|
|
|
251
257
|
* the stylesheets of the page do not reach.
|
|
252
258
|
*/
|
|
253
259
|
function themeCSS(theme = "dark") {
|
|
254
|
-
|
|
260
|
+
const palette = theme === "dark" ? dark : light;
|
|
261
|
+
const rules = [];
|
|
262
|
+
for (const [token, color] of Object.entries(palette)) if (token !== "background_color") rules.push(`.twinkleplop .${token} { color: ${color}; }`);
|
|
263
|
+
return rules.join("\n");
|
|
255
264
|
}
|
|
256
265
|
/** Highlights code of a file by its extension: `.brm`, `.css`, or TypeScript and the rest. */
|
|
257
266
|
function highlightFile(file, code, render) {
|
package/dist/highlight.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"highlight.js","names":["tsx","css"],"sources":["../src/highlight.ts"],"sourcesContent":["/**\n * A twinkleplop language for `.brm` files, for the devtools and the website: HTML-like markup with `{…}`\n * expressions, attribute values without quotes, control flow blocks such as\n * `#if (a) { … }`, dynamic tags `<{tag}>`, and `<script>` and `<style>`\n * blocks. Scripts and expressions are highlighted as TSX, styles as CSS.\n *\n * Like the Svelte grammar of twinkleplop, it marks the raw text of scripts,\n * styles and expressions, and a reclassifier hands each one to its language.\n */\nimport {\n always,\n create_language,\n embed_grammars,\n enter,\n fallback,\n goto,\n keyword,\n leave,\n match,\n on,\n range,\n to_html,\n within,\n} from '@twinkleplop/core';\nimport type { LanguageFactory, LanguageOptions, RenderOptions } from '@twinkleplop/core';\nimport type { Grammar } from '@twinkleplop/core/compile';\nimport { compile, define_grammar } from '@twinkleplop/core/compile';\nimport * as TOKENS from '@twinkleplop/core/tokens';\nimport { tokenize as css } from '@twinkleplop/css';\nimport { tokenize as tsx } from '@twinkleplop/tsx';\nimport { dark, light } from '@twinkleplop/theme-github/tokens';\n\nconst WHITESPACE = [' ', '\\t', '\\n', '\\r'];\n\nconst TAG_NAME_CHARS = range([\n ['a', 'z'],\n ['A', 'Z'],\n ['0', '9'],\n ['-', '-'],\n ['_', '_'],\n [':', ':'],\n ['.', '.'],\n ['$', '$'],\n]);\n\nconst WORD_CHARS = range([\n ['a', 'z'],\n ['A', 'Z'],\n ['0', '9'],\n ['_', '_'],\n ['$', '$'],\n]);\n\nconst ASCII_ALPHA = range([\n ['a', 'z'],\n ['A', 'Z'],\n]);\n\nconst ATTR_NAME_CHARS = range([\n ['a', 'z'],\n ['A', 'Z'],\n ['0', '9'],\n ['-', '-'],\n ['_', '_'],\n ['$', '$'],\n]);\n\n// The characters of an attribute value without quotes, such as\n// `props.items[0]`. Whitespace, `>` and `/` end it.\nconst BARE_VALUE_CHARS = range([\n ['!', '!'],\n ['#', '&'],\n ['*', '.'],\n ['0', '='],\n ['?', 'Z'],\n ['\\\\', '\\\\'],\n ['^', '~'],\n]);\n\n// Sorted longest first by the compiler, so `else if` beats `else`.\nconst BLOCK_KEYWORDS = [\n 'if',\n 'else if',\n 'else',\n 'for',\n 'repeat',\n 'switch',\n 'case',\n 'default',\n 'try',\n 'catch',\n 'loading',\n 'portal',\n 'head',\n 'client',\n 'offscreen',\n 'key',\n 'template',\n];\n\nconst RAW = TOKENS.raw_svelte_expression;\n\n// Strings and comments in raw code, so their brackets do not count.\nconst rawSkips = [\n within('\"', '\"', RAW, { escape: '\\\\', multiline: true }),\n within(\"'\", \"'\", RAW, { escape: '\\\\', multiline: true }),\n within('`', '`', RAW, { escape: '\\\\', multiline: true }),\n within('/*', '*/', RAW, { multiline: true }),\n within('//', '\\n', RAW),\n];\n\n// Inside `{…}`, nested braces are tracked until the brace that closes it.\nconst expressionRules = [\n ...rawSkips,\n match('{', RAW, enter('expression_brace')),\n fallback({ token: RAW }),\n];\n\nconst tagRules = [\n on(WHITESPACE),\n match('=', TOKENS.operator, enter('attr_value')),\n match('{', TOKENS.expression, enter('expression_body')),\n match('[', RAW, enter('raw_group')),\n match(ATTR_NAME_CHARS, TOKENS.attr_name),\n match(':', TOKENS.attr_name),\n];\n\n/** Raw code between `start` and `end` that ends the state, as in `</script>`. */\nfunction rawBlock(name: 'script' | 'style', token: string) {\n return {\n [`${name}_attrs`]: {\n rules: [\n match('>', TOKENS.punctuation, goto(`${name}_content`)),\n on(WHITESPACE),\n match('=', TOKENS.operator),\n within('\"', '\"', TOKENS.string),\n within(\"'\", \"'\", TOKENS.string),\n match(ATTR_NAME_CHARS, TOKENS.attr_name),\n ],\n },\n [`${name}_content`]: {\n rules: [on('</', enter(`${name}_close_probe`)), fallback({ token })],\n },\n [`${name}_close_probe`]: {\n mode: 'probe' as const,\n fallback: `${name}_close_fail`,\n rules: [on(`${name}>`, goto(`${name}_close`)), fallback(goto(`${name}_close_fail`))],\n },\n [`${name}_close_fail`]: { rules: [match('<', token, leave())] },\n [`${name}_close`]: {\n rules: [\n match('</', TOKENS.punctuation),\n match(name, TOKENS.tag_name),\n match('>', TOKENS.punctuation, goto('content')),\n ],\n },\n };\n}\n\nexport const rawGrammar: Grammar = define_grammar({\n name: 'brm',\n states: {\n content: {\n rules: [\n within('<!--', '-->', TOKENS.comment),\n match('</', TOKENS.punctuation, enter('close_tag')),\n on('<', enter('lt_probe')),\n on('#', enter('hash_probe')),\n match('{', TOKENS.expression, enter('expression_body')),\n // The brace that closes a block body.\n match('}', TOKENS.punctuation),\n fallback({}),\n ],\n },\n\n // `#` starts a block only before a known keyword, so `#1` stays text.\n hash_probe: {\n mode: 'probe',\n fallback: 'hash_text',\n rules: [\n on(BLOCK_KEYWORDS, { boundary: true, ...enter('block_start') }),\n fallback(enter('hash_text')),\n ],\n },\n hash_text: { rules: [on('#'), fallback(leave())] },\n block_start: {\n rules: [match('#', TOKENS.svelte_block, goto('block_keyword'))],\n },\n block_keyword: {\n rules: [\n keyword(['template'], goto('template_name'), TOKENS.svelte_block),\n match(BLOCK_KEYWORDS, TOKENS.svelte_block, goto('block_header')),\n ],\n },\n // A range matches one character, so the name continues in its own state.\n template_name: {\n rules: [\n on(WHITESPACE),\n match(ATTR_NAME_CHARS, TOKENS.function, goto('template_name_rest')),\n fallback(goto('block_header')),\n ],\n },\n template_name_rest: {\n rules: [match(ATTR_NAME_CHARS, TOKENS.function), fallback(goto('block_header'))],\n },\n // An optional header in parentheses, then the `{` of the body.\n block_header: {\n rules: [\n on(WHITESPACE),\n match('(', TOKENS.punctuation, goto('block_header_body')),\n match('{', TOKENS.punctuation, leave()),\n fallback(leave()),\n ],\n },\n // `by` in `#for (item of list by item.id)` is a keyword of the block.\n // Words are read whole, so `by` only matches on its own.\n block_header_body: {\n rules: [\n ...rawSkips,\n match(['(', '['], RAW, enter('raw_group')),\n match(')', TOKENS.punctuation, goto('block_header')),\n keyword(['by'], {}, TOKENS.keyword),\n match(WORD_CHARS, RAW, enter('raw_word')),\n fallback({ token: RAW }),\n ],\n },\n raw_word: {\n rules: [match(WORD_CHARS, RAW), fallback(leave())],\n },\n\n // `<` opens a tag before a letter, `>` (a fragment) or `{` (a dynamic tag).\n lt_probe: {\n mode: 'probe',\n fallback: 'lt_text',\n rules: [\n on(ASCII_ALPHA, enter('lt_tag')),\n on(['>', '{'], enter('lt_tag')),\n fallback(enter('lt_text')),\n ],\n },\n lt_tag: { rules: [match('<', TOKENS.punctuation, goto('tag_start'))] },\n lt_text: { rules: [on('<'), fallback(leave())] },\n\n tag_start: {\n rules: [\n keyword(['script'], goto('script_attrs'), TOKENS.tag_name),\n keyword(['style'], goto('style_attrs'), TOKENS.tag_name),\n match('>', TOKENS.punctuation, leave()),\n match('{', TOKENS.expression, goto('dynamic_tag')),\n match(TAG_NAME_CHARS, TOKENS.tag_name, goto('tag_open')),\n ],\n },\n dynamic_tag: {\n rules: [match('}', TOKENS.expression, goto('tag_attrs')), ...expressionRules],\n },\n tag_open: {\n rules: [\n match('/>', TOKENS.punctuation, leave()),\n match('>', TOKENS.punctuation, leave()),\n on(WHITESPACE, goto('tag_attrs')),\n match(TAG_NAME_CHARS, TOKENS.tag_name),\n ],\n },\n tag_attrs: {\n rules: [\n match('/>', TOKENS.punctuation, leave()),\n match('>', TOKENS.punctuation, leave()),\n ...tagRules,\n ],\n },\n close_tag: {\n rules: [\n match('>', TOKENS.punctuation, leave()),\n on(WHITESPACE),\n match(TAG_NAME_CHARS, TOKENS.tag_name),\n ],\n },\n\n // The value after `=`: a string, an object in braces, or code without quotes.\n attr_value: {\n rules: [\n within('\"', '\"', TOKENS.string, { multiline: true }),\n within(\"'\", \"'\", TOKENS.string, { multiline: true }),\n match('{', TOKENS.expression, goto('expression_body')),\n fallback(goto('bare_value')),\n ],\n },\n bare_value: {\n rules: [\n ...rawSkips,\n match(['(', '['], RAW, enter('raw_group')),\n match(BARE_VALUE_CHARS, RAW),\n fallback(leave()),\n ],\n },\n raw_group: {\n rules: [\n ...rawSkips,\n match(['(', '['], RAW, enter('raw_group')),\n match([')', ']'], RAW, leave()),\n fallback({ token: RAW }),\n ],\n },\n\n expression_body: {\n rules: [match('}', TOKENS.expression, leave()), ...expressionRules],\n },\n expression_brace: {\n rules: [match('}', RAW, leave()), ...expressionRules],\n },\n\n ...rawBlock('script', TOKENS.raw_script),\n ...rawBlock('style', TOKENS.raw_style),\n },\n});\n\nlet tsxLanguage: ReturnType<typeof tsx> | undefined;\nlet cssLanguage: ReturnType<typeof css> | undefined;\nconst embedTsx = (input: string) => (tsxLanguage ??= tsx())(input);\n\nexport const tokenize: LanguageFactory = create_language(compile(rawGrammar), [\n always(\n embed_grammars({\n [TOKENS.raw_script]: embedTsx,\n [TOKENS.raw_svelte_expression]: embedTsx,\n [TOKENS.raw_style]: (input: string) => (cssLanguage ??= css())(input),\n }),\n 'embed',\n ),\n]);\n\n/** Returns a function that highlights `.brm` code as HTML. */\nexport function language(options?: LanguageOptions) {\n const run = tokenize(options);\n return (input: string, render?: RenderOptions): string => to_html(input, run(input), render);\n}\n\n/**\n * The colours of the GitHub theme of twinkleplop as CSS, for code under a\n * `.twinkleplop` element. The devtools put it in their shadow root, where\n * the stylesheets of the page do not reach.\n */\nexport function themeCSS(theme: 'dark' | 'light' = 'dark'): string {\n const palette = theme === 'dark' ? dark : light;\n return Object.entries(palette)\n .filter(([token]) => token !== 'background_color')\n .map(([token, color]) => `.twinkleplop .${token} { color: ${color}; }`)\n .join('\\n');\n}\n\n/** Highlights code of a file by its extension: `.brm`, `.css`, or TypeScript and the rest. */\nexport function highlightFile(file: string, code: string, render?: RenderOptions): string {\n const extension = /\\.(\\w+)(?:\\?.*)?$/.exec(file)?.[1] ?? '';\n let run: ReturnType<LanguageFactory>;\n if (extension === 'brm') {\n run = brmLanguage ??= tokenize();\n } else if (extension === 'css') {\n run = cssLanguage ??= css();\n } else {\n run = tsxLanguage ??= tsx();\n }\n return to_html(code, run(code), render);\n}\n\nlet brmLanguage: ReturnType<LanguageFactory> | undefined;\n"],"mappings":";;;;;;;;;;;;;;;;AAgCA,MAAM,aAAa;CAAC;CAAK;CAAM;CAAM;AAAI;AAEzC,MAAM,iBAAiB,MAAM;CAC3B,CAAC,KAAK,GAAG;CACT,CAAC,KAAK,GAAG;CACT,CAAC,KAAK,GAAG;CACT,CAAC,KAAK,GAAG;CACT,CAAC,KAAK,GAAG;CACT,CAAC,KAAK,GAAG;CACT,CAAC,KAAK,GAAG;CACT,CAAC,KAAK,GAAG;AACX,CAAC;AAED,MAAM,aAAa,MAAM;CACvB,CAAC,KAAK,GAAG;CACT,CAAC,KAAK,GAAG;CACT,CAAC,KAAK,GAAG;CACT,CAAC,KAAK,GAAG;CACT,CAAC,KAAK,GAAG;AACX,CAAC;AAED,MAAM,cAAc,MAAM,CACxB,CAAC,KAAK,GAAG,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AAU,SAAS,OAAO,KACb,CAAC,CAC3B,QAAQ,CAAC,WAAW,UAAU,kBAAkB,CAAC,CACjD,KAAK,CAAC,OAAO,WAAW,iBAAiB,MAAM,YAAY,MAAM,IAAI,CAAC,CACtE,KAAK,IAAI;AACd;;AAGA,SAAgB,cAAc,MAAc,MAAc,QAAgC;CACxF,MAAM,YAAY,oBAAoB,KAAK,IAAI,CAAC,GAAG,MAAM;CACzD,IAAI;CACJ,IAAI,cAAc,OAChB,MAAM,gBAAgB,SAAS;MAC1B,IAAI,cAAc,OACvB,MAAM,gBAAgBA,WAAI;MAE1B,MAAM,gBAAgBD,WAAI;CAE5B,OAAO,QAAQ,MAAM,IAAI,IAAI,GAAG,MAAM;AACxC;AAEA,IAAI"}
|
|
1
|
+
{"version":3,"file":"highlight.js","names":["tsx","css"],"sources":["../src/highlight-keywords.ts","../src/highlight.ts"],"sourcesContent":["// Sorted longest first by the compiler, so `else if` beats `else`.\n// It lives in its own file, so the public entry does not export it. A test checks\n// the list against the keywords of the parser.\nexport const BLOCK_KEYWORDS: string[] = [\n 'if',\n 'else if',\n 'else',\n 'for',\n 'repeat',\n 'switch',\n 'case',\n 'default',\n 'try',\n 'catch',\n 'loading',\n 'portal',\n 'head',\n 'client',\n 'offscreen',\n 'reveal',\n 'defer',\n 'key',\n 'template',\n];\n","/**\n * A language of the twinkleplop highlighter (`@twinkleplop/core`) for `.brm` files, for the devtools and the website: HTML-like markup with `{…}`\n * expressions, attribute values without quotes, control flow blocks such as\n * `#if (a) { … }`, dynamic tags `<{tag}>`, and `<script>` and `<style>`\n * blocks. Scripts and expressions are highlighted as TSX, styles as CSS.\n *\n * Like the Svelte grammar of twinkleplop, it marks the raw text of scripts,\n * styles and expressions, and a reclassifier hands each one to its language.\n */\nimport {\n always,\n create_language,\n embed_grammars,\n enter,\n fallback,\n goto,\n keyword,\n leave,\n match,\n on,\n range,\n to_html,\n within,\n} from '@twinkleplop/core';\nimport type { LanguageFactory, LanguageOptions, RenderOptions } from '@twinkleplop/core';\nimport type { Grammar } from '@twinkleplop/core/compile';\nimport { compile, define_grammar } from '@twinkleplop/core/compile';\nimport * as TOKENS from '@twinkleplop/core/tokens';\nimport { tokenize as css } from '@twinkleplop/css';\nimport { tokenize as tsx } from '@twinkleplop/tsx';\nimport { dark, light } from '@twinkleplop/theme-github/tokens';\nimport { BLOCK_KEYWORDS } from './highlight-keywords.ts';\n\nconst WHITESPACE = [' ', '\\t', '\\n', '\\r'];\n\nconst TAG_NAME_CHARS = range([\n ['a', 'z'],\n ['A', 'Z'],\n ['0', '9'],\n ['-', '-'],\n ['_', '_'],\n [':', ':'],\n ['.', '.'],\n ['$', '$'],\n]);\n\nconst WORD_CHARS = range([\n ['a', 'z'],\n ['A', 'Z'],\n ['0', '9'],\n ['_', '_'],\n ['$', '$'],\n]);\n\nconst ASCII_ALPHA = range([\n ['a', 'z'],\n ['A', 'Z'],\n]);\n\nconst ATTR_NAME_CHARS = range([\n ['a', 'z'],\n ['A', 'Z'],\n ['0', '9'],\n ['-', '-'],\n ['_', '_'],\n ['$', '$'],\n]);\n\n// The characters of an attribute value without quotes, such as\n// `props.items[0]`. Whitespace, `>` and `/` end it.\nconst BARE_VALUE_CHARS = range([\n ['!', '!'],\n ['#', '&'],\n ['*', '.'],\n ['0', '='],\n ['?', 'Z'],\n ['\\\\', '\\\\'],\n ['^', '~'],\n]);\n\nconst RAW = TOKENS.raw_svelte_expression;\n\n// Strings and comments in raw code, so their brackets do not count.\nconst rawSkips = [\n within('\"', '\"', RAW, { escape: '\\\\', multiline: true }),\n within(\"'\", \"'\", RAW, { escape: '\\\\', multiline: true }),\n within('`', '`', RAW, { escape: '\\\\', multiline: true }),\n within('/*', '*/', RAW, { multiline: true }),\n within('//', '\\n', RAW),\n];\n\n// Inside `{…}`, nested braces are tracked until the brace that closes it.\nconst expressionRules = [\n ...rawSkips,\n match('{', RAW, enter('expression_brace')),\n fallback({ token: RAW }),\n];\n\nconst tagRules = [\n on(WHITESPACE),\n match('=', TOKENS.operator, enter('attr_value')),\n match('{', TOKENS.expression, enter('expression_body')),\n match('[', RAW, enter('raw_group')),\n match(ATTR_NAME_CHARS, TOKENS.attr_name),\n match(':', TOKENS.attr_name),\n];\n\n/** Raw code between `start` and `end` that ends the state, as in `</script>`. */\nfunction rawBlock(name: 'script' | 'style', token: string) {\n return {\n [`${name}_attrs`]: {\n rules: [\n match('>', TOKENS.punctuation, goto(`${name}_content`)),\n on(WHITESPACE),\n match('=', TOKENS.operator),\n within('\"', '\"', TOKENS.string),\n within(\"'\", \"'\", TOKENS.string),\n match(ATTR_NAME_CHARS, TOKENS.attr_name),\n ],\n },\n [`${name}_content`]: {\n rules: [on('</', enter(`${name}_close_probe`)), fallback({ token })],\n },\n [`${name}_close_probe`]: {\n mode: 'probe' as const,\n fallback: `${name}_close_fail`,\n rules: [on(`${name}>`, goto(`${name}_close`)), fallback(goto(`${name}_close_fail`))],\n },\n [`${name}_close_fail`]: { rules: [match('<', token, leave())] },\n [`${name}_close`]: {\n rules: [\n match('</', TOKENS.punctuation),\n match(name, TOKENS.tag_name),\n match('>', TOKENS.punctuation, goto('content')),\n ],\n },\n };\n}\n\nexport const rawGrammar: Grammar = define_grammar({\n name: 'brm',\n states: {\n content: {\n rules: [\n within('<!--', '-->', TOKENS.comment),\n match('</', TOKENS.punctuation, enter('close_tag')),\n on('<', enter('lt_probe')),\n on('#', enter('hash_probe')),\n match('{', TOKENS.expression, enter('expression_body')),\n // The brace that closes a block body.\n match('}', TOKENS.punctuation),\n fallback({}),\n ],\n },\n\n // `#` starts a block only before a known keyword, so `#1` stays text.\n hash_probe: {\n mode: 'probe',\n fallback: 'hash_text',\n rules: [\n on(BLOCK_KEYWORDS, { boundary: true, ...enter('block_start') }),\n fallback(enter('hash_text')),\n ],\n },\n hash_text: { rules: [on('#'), fallback(leave())] },\n block_start: {\n rules: [match('#', TOKENS.svelte_block, goto('block_keyword'))],\n },\n block_keyword: {\n rules: [\n keyword(['template'], goto('template_name'), TOKENS.svelte_block),\n match(BLOCK_KEYWORDS, TOKENS.svelte_block, goto('block_header')),\n ],\n },\n // A range matches one character, so the name continues in its own state.\n template_name: {\n rules: [\n on(WHITESPACE),\n match(ATTR_NAME_CHARS, TOKENS.function, goto('template_name_rest')),\n fallback(goto('block_header')),\n ],\n },\n template_name_rest: {\n rules: [match(ATTR_NAME_CHARS, TOKENS.function), fallback(goto('block_header'))],\n },\n // An optional header in parentheses, then the `{` of the body.\n block_header: {\n rules: [\n on(WHITESPACE),\n match('(', TOKENS.punctuation, goto('block_header_body')),\n match('{', TOKENS.punctuation, leave()),\n fallback(leave()),\n ],\n },\n // `by` in `#for (item of list by item.id)` is a keyword of the block.\n // Words are read whole, so `by` only matches on its own.\n block_header_body: {\n rules: [\n ...rawSkips,\n match(['(', '['], RAW, enter('raw_group')),\n match(')', TOKENS.punctuation, goto('block_header')),\n keyword(['by'], {}, TOKENS.keyword),\n match(WORD_CHARS, RAW, enter('raw_word')),\n fallback({ token: RAW }),\n ],\n },\n raw_word: {\n rules: [match(WORD_CHARS, RAW), fallback(leave())],\n },\n\n // `<` opens a tag before a letter, `>` (a fragment) or `{` (a dynamic tag).\n lt_probe: {\n mode: 'probe',\n fallback: 'lt_text',\n rules: [\n on(ASCII_ALPHA, enter('lt_tag')),\n on(['>', '{'], enter('lt_tag')),\n fallback(enter('lt_text')),\n ],\n },\n lt_tag: { rules: [match('<', TOKENS.punctuation, goto('tag_start'))] },\n lt_text: { rules: [on('<'), fallback(leave())] },\n\n tag_start: {\n rules: [\n keyword(['script'], goto('script_attrs'), TOKENS.tag_name),\n keyword(['style'], goto('style_attrs'), TOKENS.tag_name),\n match('>', TOKENS.punctuation, leave()),\n match('{', TOKENS.expression, goto('dynamic_tag')),\n match(TAG_NAME_CHARS, TOKENS.tag_name, goto('tag_open')),\n ],\n },\n dynamic_tag: {\n rules: [match('}', TOKENS.expression, goto('tag_attrs')), ...expressionRules],\n },\n tag_open: {\n rules: [\n match('/>', TOKENS.punctuation, leave()),\n match('>', TOKENS.punctuation, leave()),\n on(WHITESPACE, goto('tag_attrs')),\n match(TAG_NAME_CHARS, TOKENS.tag_name),\n ],\n },\n tag_attrs: {\n rules: [\n match('/>', TOKENS.punctuation, leave()),\n match('>', TOKENS.punctuation, leave()),\n ...tagRules,\n ],\n },\n close_tag: {\n rules: [\n match('>', TOKENS.punctuation, leave()),\n on(WHITESPACE),\n match(TAG_NAME_CHARS, TOKENS.tag_name),\n ],\n },\n\n // The value after `=`: a string, an object in braces, or code without quotes.\n attr_value: {\n rules: [\n within('\"', '\"', TOKENS.string, { multiline: true }),\n within(\"'\", \"'\", TOKENS.string, { multiline: true }),\n match('{', TOKENS.expression, goto('expression_body')),\n fallback(goto('bare_value')),\n ],\n },\n bare_value: {\n rules: [\n ...rawSkips,\n match(['(', '['], RAW, enter('raw_group')),\n match(BARE_VALUE_CHARS, RAW),\n fallback(leave()),\n ],\n },\n raw_group: {\n rules: [\n ...rawSkips,\n match(['(', '['], RAW, enter('raw_group')),\n match([')', ']'], RAW, leave()),\n fallback({ token: RAW }),\n ],\n },\n\n expression_body: {\n rules: [match('}', TOKENS.expression, leave()), ...expressionRules],\n },\n expression_brace: {\n rules: [match('}', RAW, leave()), ...expressionRules],\n },\n\n ...rawBlock('script', TOKENS.raw_script),\n ...rawBlock('style', TOKENS.raw_style),\n },\n});\n\nlet tsxLanguage: ReturnType<typeof tsx> | undefined;\nlet cssLanguage: ReturnType<typeof css> | undefined;\nfunction embedTsx(input: string) {\n return (tsxLanguage ??= tsx())(input);\n}\n\nexport const tokenize: LanguageFactory = create_language(compile(rawGrammar), [\n always(\n embed_grammars({\n [TOKENS.raw_script]: embedTsx,\n [TOKENS.raw_svelte_expression]: embedTsx,\n [TOKENS.raw_style]: (input: string) => (cssLanguage ??= css())(input),\n }),\n 'embed',\n ),\n]);\n\n/** Returns a function that highlights `.brm` code as HTML. */\nexport function language(options?: LanguageOptions) {\n const run = tokenize(options);\n return (input: string, render?: RenderOptions): string => to_html(input, run(input), render);\n}\n\n/**\n * The colours of the GitHub theme of twinkleplop as CSS, for code under a\n * `.twinkleplop` element. The devtools put it in their shadow root, where\n * the stylesheets of the page do not reach.\n */\nexport function themeCSS(theme: 'dark' | 'light' = 'dark'): string {\n const palette = theme === 'dark' ? dark : light;\n const rules: string[] = [];\n for (const [token, color] of Object.entries(palette)) {\n if (token !== 'background_color') {\n rules.push(`.twinkleplop .${token} { color: ${color}; }`);\n }\n }\n return rules.join('\\n');\n}\n\n/** Highlights code of a file by its extension: `.brm`, `.css`, or TypeScript and the rest. */\nexport function highlightFile(file: string, code: string, render?: RenderOptions): string {\n const extension = /\\.(\\w+)(?:\\?.*)?$/.exec(file)?.[1] ?? '';\n let run: ReturnType<LanguageFactory>;\n if (extension === 'brm') {\n run = brmLanguage ??= tokenize();\n } else if (extension === 'css') {\n run = cssLanguage ??= css();\n } else {\n run = tsxLanguage ??= tsx();\n }\n return to_html(code, run(code), render);\n}\n\nlet brmLanguage: ReturnType<LanguageFactory> | undefined;\n"],"mappings":";;;;;;;AAGA,MAAa,iBAA2B;CACtC;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF;;;;;;;;;;;;ACUA,MAAM,aAAa;CAAC;CAAK;CAAM;CAAM;AAAI;AAEzC,MAAM,iBAAiB,MAAM;CAC3B,CAAC,KAAK,GAAG;CACT,CAAC,KAAK,GAAG;CACT,CAAC,KAAK,GAAG;CACT,CAAC,KAAK,GAAG;CACT,CAAC,KAAK,GAAG;CACT,CAAC,KAAK,GAAG;CACT,CAAC,KAAK,GAAG;CACT,CAAC,KAAK,GAAG;AACX,CAAC;AAED,MAAM,aAAa,MAAM;CACvB,CAAC,KAAK,GAAG;CACT,CAAC,KAAK,GAAG;CACT,CAAC,KAAK,GAAG;CACT,CAAC,KAAK,GAAG;CACT,CAAC,KAAK,GAAG;AACX,CAAC;AAED,MAAM,cAAc,MAAM,CACxB,CAAC,KA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AQ,OAAO,GACjD,IAAI,UAAU,oBACZ,MAAM,KAAK,iBAAiB,MAAM,YAAY,MAAM,IAAI;CAG5D,OAAO,MAAM,KAAK,IAAI;AACxB;;AAGA,SAAgB,cAAc,MAAc,MAAc,QAAgC;CACxF,MAAM,YAAY,oBAAoB,KAAK,IAAI,CAAC,GAAG,MAAM;CACzD,IAAI;CACJ,IAAI,cAAc,OAChB,MAAM,gBAAgB,SAAS;MAC1B,IAAI,cAAc,OACvB,MAAM,gBAAgBA,WAAI;MAE1B,MAAM,gBAAgBD,WAAI;CAE5B,OAAO,QAAQ,MAAM,IAAI,IAAI,GAAG,MAAM;AACxC;AAEA,IAAI"}
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
//#region src/runtime/html.ts
|
|
2
2
|
const RAW = Symbol.for("brumate.raw");
|
|
3
|
+
const INTERNAL = Symbol.for("brumate.internal");
|
|
3
4
|
var RawHTML = class {
|
|
4
5
|
[RAW];
|
|
5
6
|
constructor(html) {
|
|
@@ -21,18 +22,28 @@ const ESCAPES = {
|
|
|
21
22
|
">": ">",
|
|
22
23
|
"\"": """
|
|
23
24
|
};
|
|
24
|
-
|
|
25
|
+
function toEscape(char) {
|
|
26
|
+
return ESCAPES[char];
|
|
27
|
+
}
|
|
25
28
|
function escape(value) {
|
|
26
29
|
return /[&<>]/.test(value) ? value.replace(/[&<>]/g, toEscape) : value;
|
|
27
30
|
}
|
|
28
31
|
function escapeAttribute(value) {
|
|
29
32
|
return /[&<"]/.test(value) ? value.replace(/[&<"]/g, toEscape) : value;
|
|
30
33
|
}
|
|
31
|
-
/**
|
|
34
|
+
/** True for a promise, or any object with a `then` function, as the server awaits it. */
|
|
35
|
+
function isThenable(value) {
|
|
36
|
+
return value !== null && (typeof value === "object" || typeof value === "function") && typeof value.then === "function";
|
|
37
|
+
}
|
|
38
|
+
/** Renders a value inserted in markup. A promise is not awaited: it renders empty. */
|
|
32
39
|
function insertValue(value) {
|
|
33
40
|
if (isRaw(value)) return value[RAW];
|
|
34
|
-
if (value === null || value === void 0 || typeof value === "boolean") return "";
|
|
35
|
-
if (Array.isArray(value))
|
|
41
|
+
if (value === null || value === void 0 || typeof value === "boolean" || isThenable(value)) return "";
|
|
42
|
+
if (Array.isArray(value)) {
|
|
43
|
+
let result = "";
|
|
44
|
+
for (const item of value) result += insertValue(item);
|
|
45
|
+
return result;
|
|
46
|
+
}
|
|
36
47
|
return escape(String(value));
|
|
37
48
|
}
|
|
38
49
|
/**
|
|
@@ -41,8 +52,12 @@ function insertValue(value) {
|
|
|
41
52
|
*/
|
|
42
53
|
function textValue(value) {
|
|
43
54
|
if (isRaw(value)) return value[RAW];
|
|
44
|
-
if (value === null || value === void 0 || typeof value === "boolean") return "";
|
|
45
|
-
if (Array.isArray(value))
|
|
55
|
+
if (value === null || value === void 0 || typeof value === "boolean" || isThenable(value)) return "";
|
|
56
|
+
if (Array.isArray(value)) {
|
|
57
|
+
let result = "";
|
|
58
|
+
for (const item of value) result += textValue(item);
|
|
59
|
+
return result;
|
|
60
|
+
}
|
|
46
61
|
return String(value);
|
|
47
62
|
}
|
|
48
63
|
function toKebabCase(name) {
|
|
@@ -74,7 +89,11 @@ function classAttribute(classes) {
|
|
|
74
89
|
return classes === "" ? "" : ` class="${classes.slice(1)}"`;
|
|
75
90
|
}
|
|
76
91
|
function styleValue(value) {
|
|
77
|
-
if (typeof value === "object" && value !== null)
|
|
92
|
+
if (typeof value === "object" && value !== null) {
|
|
93
|
+
const declarations = [];
|
|
94
|
+
for (const [name, item] of Object.entries(value)) if (item !== null && item !== void 0 && item !== false) declarations.push(`${toKebabCase(name)}:${String(item)}`);
|
|
95
|
+
return declarations.join(";");
|
|
96
|
+
}
|
|
78
97
|
return String(value);
|
|
79
98
|
}
|
|
80
99
|
/** The brand of a binding of `$bind`, under the key of the registry. See `Binding`. */
|
|
@@ -115,8 +134,11 @@ function switchWords(name) {
|
|
|
115
134
|
* without a value, and `false` leaves it out.
|
|
116
135
|
*/
|
|
117
136
|
function attributeText(name, value) {
|
|
118
|
-
if (typeof value === "object" && value !== null && BOUND in value)
|
|
119
|
-
|
|
137
|
+
if (typeof value === "object" && value !== null && BOUND in value) {
|
|
138
|
+
if (name === "ref") return;
|
|
139
|
+
value = value.value;
|
|
140
|
+
}
|
|
141
|
+
if (value === null || value === void 0 || typeof value === "function" || isThenable(value)) return;
|
|
120
142
|
if (typeof value === "boolean") {
|
|
121
143
|
const words = switchWords(name);
|
|
122
144
|
if (words) return value ? words[0] : words[1];
|
|
@@ -163,9 +185,38 @@ function styleElement(id, css) {
|
|
|
163
185
|
* Merges the attributes of an element that has spreads, in their order: a
|
|
164
186
|
* later value wins, except `class`, whose values all apply.
|
|
165
187
|
*/
|
|
166
|
-
|
|
188
|
+
/**
|
|
189
|
+
* A value of an attribute that brumate writes, such as the `b-on` of a dynamic tag, which the
|
|
190
|
+
* compiler wraps. An object of attributes, such as a spread, writes a `b-` attribute only with
|
|
191
|
+
* one, so data from outside the app cannot name handlers or scopes.
|
|
192
|
+
*/
|
|
193
|
+
var Internal = class {
|
|
194
|
+
value;
|
|
195
|
+
constructor(value) {
|
|
196
|
+
this.value = value;
|
|
197
|
+
}
|
|
198
|
+
};
|
|
199
|
+
Internal.prototype[INTERNAL] = true;
|
|
200
|
+
/** True for an `Internal`, also one that another copy of the runtime made. */
|
|
201
|
+
function isInternal(value) {
|
|
202
|
+
return typeof value === "object" && value !== null && INTERNAL in value;
|
|
203
|
+
}
|
|
204
|
+
/** Wraps the value of an attribute that brumate writes. See `Internal`. */
|
|
205
|
+
function internal(value) {
|
|
206
|
+
return new Internal(value);
|
|
207
|
+
}
|
|
208
|
+
/** The value of an attribute of an object, or undefined for a `b-` attribute from outside. */
|
|
209
|
+
function ownValue(name, value) {
|
|
210
|
+
if (isInternal(value)) return value.value;
|
|
211
|
+
return name.startsWith("b-") ? void 0 : value;
|
|
212
|
+
}
|
|
213
|
+
function mergeAttributes(parts, variables) {
|
|
167
214
|
const result = {};
|
|
168
|
-
for (const part of parts) for (const [name, value] of Object.entries(part ?? {}))
|
|
215
|
+
for (const part of parts) for (const [name, value] of Object.entries(part ?? {})) {
|
|
216
|
+
if (name.startsWith("b-") && !isInternal(value)) continue;
|
|
217
|
+
result[name] = name === "class" && result.class !== void 0 && value !== void 0 ? [result.class, value] : value;
|
|
218
|
+
}
|
|
219
|
+
if (variables) result.style = vars(variables, result.style);
|
|
169
220
|
return result;
|
|
170
221
|
}
|
|
171
222
|
/**
|
|
@@ -193,19 +244,35 @@ function bindEntry(name, ref, setter) {
|
|
|
193
244
|
* those of its spreads.
|
|
194
245
|
*/
|
|
195
246
|
function onAttribute(on, own) {
|
|
196
|
-
const
|
|
197
|
-
|
|
247
|
+
const value = onValue(on, own);
|
|
248
|
+
return value ? ` b-on="${escapeAttribute(value)}"` : "";
|
|
249
|
+
}
|
|
250
|
+
/** The value of `b-on`, in the order of `onAttribute`. */
|
|
251
|
+
function onValue(on, own) {
|
|
252
|
+
const bindings = [];
|
|
253
|
+
const rest = [];
|
|
254
|
+
for (const entry of on) if (/=\$(bind#|set:)/.test(entry)) bindings.push(entry);
|
|
255
|
+
else rest.push(entry);
|
|
256
|
+
const parts = [];
|
|
257
|
+
for (const part of [
|
|
198
258
|
...bindings,
|
|
199
259
|
own,
|
|
200
|
-
...
|
|
201
|
-
]
|
|
202
|
-
return
|
|
260
|
+
...rest
|
|
261
|
+
]) if (part) parts.push(part);
|
|
262
|
+
return parts.join(" ");
|
|
203
263
|
}
|
|
204
264
|
/** Renders an object of attributes. */
|
|
205
|
-
function spread(attributes) {
|
|
265
|
+
function spread(attributes, names = false) {
|
|
206
266
|
let result = "";
|
|
207
|
-
|
|
208
|
-
|
|
267
|
+
const written = [];
|
|
268
|
+
for (const [name, value] of Object.entries(attributes)) if (name !== "children" && !/^on[A-Z]/.test(name)) {
|
|
269
|
+
const text = attribute(name, ownValue(name, value));
|
|
270
|
+
if (text) {
|
|
271
|
+
result += text;
|
|
272
|
+
written.push(name);
|
|
273
|
+
}
|
|
274
|
+
}
|
|
275
|
+
return names ? `${result} b-s="${written.join(" ")}"` : result;
|
|
209
276
|
}
|
|
210
277
|
const VOID_ELEMENTS = /* @__PURE__ */ new Set([
|
|
211
278
|
"area",
|
|
@@ -231,11 +298,14 @@ const VOID_ELEMENTS = /* @__PURE__ */ new Set([
|
|
|
231
298
|
*/
|
|
232
299
|
function actionAttributes(prefix, name, id, method, result, build, key) {
|
|
233
300
|
const methodText = method ? ` ${method}="post"` : "";
|
|
234
|
-
const
|
|
301
|
+
const params = [];
|
|
302
|
+
if (build !== void 0) params.push(`__build=${encodeURIComponent(build)}`);
|
|
303
|
+
if (key !== void 0) params.push(`__key=${key}`);
|
|
304
|
+
const query = params.join("&");
|
|
235
305
|
if (result !== void 0) return ` ${name}="${escapeAttribute(`?__action=${encodeURIComponent(id)}${query ? `&${query}` : ""}`)}"${methodText} b-action="${escapeAttribute(id)}" b-result="${escapeAttribute(result)}"`;
|
|
236
306
|
return ` ${name}="${escapeAttribute(`${prefix}/${encodeURIComponent(id)}${query ? `?${query}` : ""}`)}"${methodText}`;
|
|
237
307
|
}
|
|
238
308
|
//#endregion
|
|
239
|
-
export { rawHTML as _,
|
|
309
|
+
export { spread as C, vars as E, rawHTML as S, textValue as T, mergeAttributes as _, attribute as a, ownValue as b, classAttribute as c, escapeAttribute as d, handlerEntry as f, isRaw as g, isInternal as h, affix as i, classValue as l, internal as m, VOID_ELEMENTS as n, attributeText as o, insertValue as p, actionAttributes as r, bindEntry as s, Internal as t, escape as u, onAttribute as v, styleElement as w, raw as x, onValue as y };
|
|
240
310
|
|
|
241
|
-
//# sourceMappingURL=html-
|
|
311
|
+
//# sourceMappingURL=html-DS9B1H-M.js.map
|