@yuneta/gobj-ui 7.26.5 → 7.26.7

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.
@@ -0,0 +1,137 @@
1
+ /***********************************************************************
2
+ * form_json_field.wiring.test.js
3
+ *
4
+ * A C_YUI_FORM json field (a jsoneditor) whose TEXT does not parse
5
+ * was saved as `{}` or `[]`: validate_form() asked the browser
6
+ * (checkValidity) and the tables, and a jsoneditor is neither; the
7
+ * conversion then caught the parse error and stored the empty
8
+ * value. Driven through the real gclass on a document double, with
9
+ * the editor replaced by a double that answers what the real one
10
+ * answers in text mode.
11
+ *
12
+ * Copyright (c) 2026, ArtGins.
13
+ * All Rights Reserved.
14
+ ***********************************************************************/
15
+ import {describe, test, expect, beforeAll, beforeEach, vi} from "vitest";
16
+ import {install_dom_double} from "../test/dom_double.js";
17
+
18
+ install_dom_double();
19
+
20
+ if(typeof globalThis.ResizeObserver === "undefined") {
21
+ globalThis.ResizeObserver = class {
22
+ observe() {}
23
+ unobserve() {}
24
+ disconnect() {}
25
+ };
26
+ }
27
+
28
+ /* The editor: what the reader typed, in text mode. */
29
+ const editors = vi.hoisted(() => []);
30
+ vi.mock("vanilla-jsoneditor", () => ({
31
+ createJSONEditor: (opts) => {
32
+ const ed = {
33
+ content: {text: ""},
34
+ props: opts.props,
35
+ get() {
36
+ return this.content;
37
+ },
38
+ set(content) {
39
+ this.content = content;
40
+ },
41
+ destroy() {},
42
+ };
43
+ editors.push(ed);
44
+ return ed;
45
+ },
46
+ }));
47
+
48
+ const {
49
+ SDATA_END, gclass_create,
50
+ gobj_start_up, gobj_create_yuno, gobj_create_pure_child,
51
+ gobj_start, gobj_send_event, gobj_read_attr,
52
+ set_log_callback,
53
+ } = await import("@yuneta/gobj-js");
54
+ const {register_c_yui_form} = await import("./c_yui_form.js");
55
+
56
+ const saved = [];
57
+ const logged = [];
58
+ let yuno = null;
59
+
60
+ beforeAll(async () => {
61
+ const i18next = (await import("i18next")).default;
62
+ await i18next.init({lng: "en", resources: {}});
63
+ gobj_start_up(null, null, null, null, null, null, null);
64
+ set_log_callback((level, msg) => {
65
+ logged.push({level: String(level), msg: String(msg)});
66
+ });
67
+ gclass_create("C_TEST_FORM_HOST", [], [["ST_IDLE", []]], {}, 0, [SDATA_END()], {}, 0, 0, 0, 0);
68
+ gclass_create(
69
+ "C_TEST_FORM_APP",
70
+ [["EV_SAVE_RECORD", 0], ["EV_RECORD_CHANGED", 0]],
71
+ [["ST_IDLE", [
72
+ ["EV_SAVE_RECORD", (gobj, event, kw) => {
73
+ saved.push(kw);
74
+ return 0;
75
+ }, null],
76
+ ["EV_RECORD_CHANGED", () => 0, null],
77
+ ]]],
78
+ {}, 0, [SDATA_END()], {}, 0, 0, 0, 0
79
+ );
80
+ register_c_yui_form();
81
+ yuno = gobj_create_yuno("form_json_yuno", "C_TEST_FORM_HOST", {});
82
+ gobj_start(yuno);
83
+ });
84
+
85
+ beforeEach(() => {
86
+ saved.length = 0;
87
+ logged.length = 0;
88
+ editors.length = 0;
89
+ });
90
+
91
+ let seq = 0;
92
+
93
+ function build()
94
+ {
95
+ const app = gobj_create_pure_child(`fapp${++seq}`, "C_TEST_FORM_APP", {}, yuno);
96
+ gobj_start(app);
97
+ const form = gobj_create_pure_child(`form${seq}`, "C_YUI_FORM", {
98
+ template: [
99
+ {id: "id", header: "id", type: "string", flag: ["persistent", "required"]},
100
+ {id: "settings", header: "settings", type: "dict", flag: ["persistent", "writable"]},
101
+ ],
102
+ record: {id: "a", settings: {}},
103
+ render_mode: "edit",
104
+ editable: true,
105
+ }, app);
106
+ gobj_start(form);
107
+ const $c = gobj_read_attr(form, "$container");
108
+ const $editor = $c.querySelector(".jsoneditor");
109
+ expect($editor).toBeTruthy();
110
+ expect(editors.length).toBe(1);
111
+ return {form, $editor, editor: editors[0]};
112
+ }
113
+
114
+ describe("a json field that does not parse", () => {
115
+ test("is refused, marked, and nothing is saved", () => {
116
+ const {form, $editor, editor} = build();
117
+ editor.content = {text: '{"a": 1,}'};
118
+ gobj_send_event(form, "EV_SAVE_RECORD", {}, form);
119
+ expect(saved).toEqual([]);
120
+ expect($editor.classList.contains("is-danger")).toBe(true);
121
+ expect($editor.yui_json_error).toBe("invalid json");
122
+ });
123
+
124
+ test("is saved once it holds json again", () => {
125
+ const {form, $editor, editor} = build();
126
+ editor.content = {text: '[1]'};
127
+ gobj_send_event(form, "EV_SAVE_RECORD", {}, form);
128
+ expect(saved).toEqual([]);
129
+
130
+ editor.content = {text: '{"a": 1}'};
131
+ editor.props.onChange();
132
+ expect($editor.classList.contains("is-danger")).toBe(false);
133
+ gobj_send_event(form, "EV_SAVE_RECORD", {}, form);
134
+ expect(saved.length).toBe(1);
135
+ expect(saved[0].settings).toBe('{"a": 1}');
136
+ });
137
+ });
package/src/lib_icons.js CHANGED
@@ -21,10 +21,20 @@
21
21
  * disableElements, …) work on toolbar icons exactly like on
22
22
  * regular Bulma/FA buttons — no icon-specific helpers needed.
23
23
  *
24
+ * 3. User icons: the icons a user adds as DATA, one node of the
25
+ * treedb system topic `__icons__` each (id = name, svg = drawing).
26
+ * They join system 1 at run time: each becomes a rule
27
+ * `.yi-u-<id>::before` in a stylesheet of their own, so every
28
+ * component that draws an icon by class name draws them too.
29
+ * `yi-u-` is the user's namespace, and the reason a user icon can
30
+ * never replace an icon of the library.
31
+ *
24
32
  * Copyright (c) 2025-2026, ArtGins.
25
33
  * All Rights Reserved.
26
34
  *********************************************************/
27
35
 
36
+ import {log_error, log_warning} from "@yuneta/gobj-js";
37
+
28
38
  const CUSTOM_SVG_ICONS_ID = 'g6-custom-svgicons';
29
39
 
30
40
  /*
@@ -219,3 +229,388 @@ export function yui_icon_is_defined(name)
219
229
  __icon_defined__[name] = defined;
220
230
  return defined;
221
231
  }
232
+
233
+ /************************************************************
234
+ *
235
+ * User icons
236
+ *
237
+ ************************************************************/
238
+
239
+ /*
240
+ * The treedb system topic that holds them (TREEDB_ICONS_TOPIC in
241
+ * tr_treedb.h) and its drawing column. The schema of the topic is the
242
+ * SDK's, fixed, which is why the GUI may know a column of it by name.
243
+ */
244
+ export const ICONS_TOPIC = "__icons__";
245
+ const ICONS_SVG_COL = "svg";
246
+
247
+ /*
248
+ * The class of a user icon is `yi-u-<id>`: a namespace no icon of the
249
+ * library uses, so a user icon can never replace one of them -- not
250
+ * today, and not when the library adds an icon of the same name.
251
+ */
252
+ export const USER_ICON_PREFIX = "yi-u-";
253
+ const USER_ICON_ID_RE = /^[a-z0-9]+(-[a-z0-9]+)*$/;
254
+
255
+ /*
256
+ * An icon is a few hundred bytes; this is a drawing, not an icon, and it
257
+ * would be carried in the stylesheet of every page.
258
+ */
259
+ const USER_ICON_MAX_SVG = 32768;
260
+
261
+ const USER_ICONS_STYLE_ID = "yui-user-icons";
262
+
263
+ const SVG_NS = "http://www.w3.org/2000/svg";
264
+
265
+ /*
266
+ * What an icon may be made of: shapes. Everything else -- script,
267
+ * foreignObject, image, use, style, text, gradients, filters -- is
268
+ * dropped with its subtree. The svg is written by whoever can write a
269
+ * node, and it is drawn on every page of the app.
270
+ */
271
+ const SVG_ELEMENTS = [
272
+ "svg", "g", "path", "circle", "ellipse", "rect", "line", "polyline", "polygon"
273
+ ];
274
+ const SVG_ATTRIBUTES = [
275
+ "d", "cx", "cy", "r", "rx", "ry", "x", "y", "x1", "y1", "x2", "y2",
276
+ "width", "height", "points", "transform",
277
+ "fill", "fill-rule", "fill-opacity", "clip-rule", "opacity",
278
+ "stroke", "stroke-width", "stroke-linecap", "stroke-linejoin",
279
+ "stroke-miterlimit", "stroke-opacity", "stroke-dasharray"
280
+ ];
281
+ /* Numbers, path commands, colours, transforms. No quotes, no `<`, no `&`,
282
+ * no `:` -- so no url, no javascript, no entity, and nothing that can
283
+ * close the attribute it is written into. */
284
+ const SVG_VALUE_RE = /^[a-zA-Z0-9\s.,#%()+-]*$/;
285
+
286
+ const __user_icons__ = new Map(); // id -> {svg, mask}
287
+
288
+ /************************************************************
289
+ * Is this field the drawing of an icon of __icons__?
290
+ * The form edits it as a text area with a preview, and the
291
+ * table shows the icon instead of the svg source.
292
+ ************************************************************/
293
+ export function yui_icons_is_svg_field(topic_name, field_name)
294
+ {
295
+ return topic_name === ICONS_TOPIC && field_name === ICONS_SVG_COL;
296
+ }
297
+
298
+ /************************************************************
299
+ * The class of the user icon named `id`.
300
+ ************************************************************/
301
+ export function yui_user_icon_class(id)
302
+ {
303
+ return USER_ICON_PREFIX + id;
304
+ }
305
+
306
+ /************************************************************
307
+ * Rebuild an svg from its SHAPES only.
308
+ *
309
+ * Return {svg, dropped} -- svg is the clean markup, dropped the
310
+ * names of what was left out -- or {error} when there is
311
+ * nothing to draw. The error is one of a FIXED set, so a GUI
312
+ * can translate it: "empty svg", "svg too big", "not an svg
313
+ * document", "svg without size", "svg without shapes". The markup is never inserted anywhere as
314
+ * it came: it is parsed, and a new one is written from the
315
+ * elements and attributes allowed above.
316
+ ************************************************************/
317
+ export function yui_svg_sanitize(svg_text)
318
+ {
319
+ if(typeof svg_text !== "string" || !svg_text.trim()) {
320
+ return {error: "empty svg"};
321
+ }
322
+ if(svg_text.length > USER_ICON_MAX_SVG) {
323
+ return {error: "svg too big"};
324
+ }
325
+
326
+ let doc;
327
+ try {
328
+ doc = new DOMParser().parseFromString(svg_text, "image/svg+xml");
329
+ } catch(e) {
330
+ return {error: "not an svg document"};
331
+ }
332
+ let root = doc && doc.documentElement;
333
+ if(!root || root.getElementsByTagName("parsererror").length > 0) {
334
+ return {error: "not an svg document"};
335
+ }
336
+ return rebuild_svg_from_shapes(root);
337
+ }
338
+
339
+ /************************************************************
340
+ * The second half of yui_svg_sanitize(), on a PARSED tree:
341
+ * anything with `localName`, `attributes` ({name, localName,
342
+ * prefix, value}), `children` and `getAttribute()` -- a DOM
343
+ * element, or the plain objects a test builds.
344
+ ************************************************************/
345
+ export function rebuild_svg_from_shapes(root)
346
+ {
347
+ if(!root || root.localName !== "svg") {
348
+ return {error: "not an svg document"};
349
+ }
350
+
351
+ let dropped = new Set();
352
+ let shapes = 0;
353
+
354
+ function value_is_safe(value)
355
+ {
356
+ return SVG_VALUE_RE.test(value) && !/url\s*\(/i.test(value);
357
+ }
358
+
359
+ function clean_attrs(el, allowed)
360
+ {
361
+ let out = "";
362
+ for(const attr of Array.from(el.attributes || [])) {
363
+ let name = attr.localName || attr.name;
364
+ if(attr.prefix || !allowed.includes(name)) {
365
+ if(name !== "xmlns" && attr.prefix !== "xmlns") {
366
+ dropped.add(`@${attr.name}`);
367
+ }
368
+ continue;
369
+ }
370
+ let value = String(attr.value).trim();
371
+ if(!value_is_safe(value)) {
372
+ dropped.add(`@${attr.name}`);
373
+ continue;
374
+ }
375
+ out += ` ${name}="${value}"`;
376
+ }
377
+ return out;
378
+ }
379
+
380
+ function clean_node(el)
381
+ {
382
+ let name = el.localName;
383
+ if(!SVG_ELEMENTS.includes(name) || name === "svg") {
384
+ dropped.add(name);
385
+ return "";
386
+ }
387
+ if(name !== "g") {
388
+ shapes++;
389
+ }
390
+ let inner = "";
391
+ for(const child of Array.from(el.children || [])) {
392
+ inner += clean_node(child);
393
+ }
394
+ return `<${name}${clean_attrs(el, SVG_ATTRIBUTES)}>${inner}</${name}>`;
395
+ }
396
+
397
+ /*
398
+ * The viewBox is what scales the drawing into the 1em box of an
399
+ * icon. Without one, the width and height of the root say the size
400
+ * it was drawn at, and that is the box.
401
+ */
402
+ let view_box = (root.getAttribute("viewBox") || "").trim();
403
+ if(!/^-?[\d.]+([\s,]+-?[\d.]+){3}$/.test(view_box)) {
404
+ let w = parseFloat(root.getAttribute("width"));
405
+ let h = parseFloat(root.getAttribute("height"));
406
+ if(!(w > 0 && h > 0)) {
407
+ return {error: "svg without size"};
408
+ }
409
+ view_box = `0 0 ${w} ${h}`;
410
+ }
411
+
412
+ /* What the root says for every shape: an icon drawn with strokes
413
+ * (fill="none" stroke=...) is all in these. */
414
+ const ROOT_ATTRIBUTES = ["fill", "fill-rule", "stroke", "stroke-width",
415
+ "stroke-linecap", "stroke-linejoin"];
416
+ let root_attrs = "";
417
+ for(const name of ROOT_ATTRIBUTES) {
418
+ let value = (root.getAttribute(name) || "").trim();
419
+ if(value && value_is_safe(value)) {
420
+ root_attrs += ` ${name}="${value}"`;
421
+ } else if(value) {
422
+ dropped.add(`@${name}`);
423
+ }
424
+ }
425
+ for(const attr of Array.from(root.attributes || [])) {
426
+ let name = attr.localName || attr.name;
427
+ if(attr.prefix === "xmlns" || name === "xmlns" ||
428
+ ["viewBox", "width", "height", "version"].includes(name) ||
429
+ (!attr.prefix && ROOT_ATTRIBUTES.includes(name))) {
430
+ continue;
431
+ }
432
+ dropped.add(`@${attr.name}`);
433
+ }
434
+
435
+ let inner = "";
436
+ for(const child of Array.from(root.children || [])) {
437
+ inner += clean_node(child);
438
+ }
439
+ if(shapes === 0) {
440
+ return {error: "svg without shapes"};
441
+ }
442
+
443
+ return {
444
+ svg: `<svg xmlns="${SVG_NS}" viewBox="${view_box}"${root_attrs}>${inner}</svg>`,
445
+ dropped: Array.from(dropped)
446
+ };
447
+ }
448
+
449
+ /************************************************************
450
+ * The CSS `url(...)` of an svg, to be used as a mask.
451
+ * Every character that could end the string or the url is
452
+ * percent-encoded.
453
+ ************************************************************/
454
+ export function svg_mask_url(svg)
455
+ {
456
+ return `url("data:image/svg+xml,${encodeURIComponent(svg)}")`;
457
+ }
458
+
459
+ /************************************************************
460
+ * An element that shows an svg as an icon, before it is
461
+ * registered (a form preview, a cell of __icons__ itself).
462
+ * Return {element} or {error}.
463
+ ************************************************************/
464
+ export function yui_svg_icon_element(svg_text)
465
+ {
466
+ let clean = yui_svg_sanitize(svg_text);
467
+ if(clean.error) {
468
+ return {error: clean.error};
469
+ }
470
+ let el = document.createElement("span");
471
+ el.className = "USER_ICON_PREVIEW";
472
+ let mask = svg_mask_url(clean.svg);
473
+ el.style.setProperty("-webkit-mask-image", mask);
474
+ el.style.setProperty("mask-image", mask);
475
+ return {element: el, dropped: clean.dropped};
476
+ }
477
+
478
+ /************************************************************
479
+ * Write the stylesheet of the user icons again, from the map.
480
+ ************************************************************/
481
+ function rebuild_user_icons_stylesheet()
482
+ {
483
+ let css = "";
484
+ for(const [id, icon] of __user_icons__) {
485
+ css += `.${yui_user_icon_class(id)}::before {` +
486
+ `-webkit-mask-image: ${icon.mask}; mask-image: ${icon.mask};}\n`;
487
+ }
488
+
489
+ try {
490
+ let el = document.getElementById(USER_ICONS_STYLE_ID);
491
+ if(!el) {
492
+ el = document.createElement("style");
493
+ el.id = USER_ICONS_STYLE_ID;
494
+ document.head.appendChild(el);
495
+ }
496
+ el.textContent = css;
497
+ } catch(e) {
498
+ log_error(`user icons: cannot write the stylesheet: ${e}`);
499
+ }
500
+
501
+ /* The answer of yui_icon_is_defined() about a user icon has changed. */
502
+ for(const name of Object.keys(__icon_defined__)) {
503
+ if(name.startsWith(USER_ICON_PREFIX)) {
504
+ delete __icon_defined__[name];
505
+ }
506
+ }
507
+ }
508
+
509
+ /************************************************************
510
+ * Validate one node of __icons__.
511
+ * Return the entry to keep, or null (warning logged).
512
+ ************************************************************/
513
+ function user_icon_entry(node)
514
+ {
515
+ let id = node && node.id;
516
+ if(typeof id !== "string" || !USER_ICON_ID_RE.test(id)) {
517
+ log_warning(`user icons: bad icon name '${id}': lowercase letters, digits and '-' only`);
518
+ return null;
519
+ }
520
+ let clean = yui_svg_sanitize(node.svg);
521
+ if(clean.error) {
522
+ log_warning(`user icons: icon '${id}' not drawn: ${clean.error}`);
523
+ return null;
524
+ }
525
+ return {svg: clean.svg, mask: svg_mask_url(clean.svg)};
526
+ }
527
+
528
+ /************************************************************
529
+ * Replace every user icon with the nodes of __icons__.
530
+ * Return the number of icons registered.
531
+ ************************************************************/
532
+ export function yui_icons_set_user(nodes)
533
+ {
534
+ __user_icons__.clear();
535
+ if(Array.isArray(nodes)) {
536
+ for(const node of nodes) {
537
+ let entry = user_icon_entry(node);
538
+ if(entry) {
539
+ __user_icons__.set(node.id, entry);
540
+ }
541
+ }
542
+ } else if(nodes) {
543
+ log_error(`user icons: the nodes of ${ICONS_TOPIC} must be a list`);
544
+ }
545
+ rebuild_user_icons_stylesheet();
546
+ return __user_icons__.size;
547
+ }
548
+
549
+ /************************************************************
550
+ * A node of __icons__ was created or updated.
551
+ * Return true if the icon is drawn.
552
+ ************************************************************/
553
+ export function yui_icons_put_user(node)
554
+ {
555
+ let entry = user_icon_entry(node);
556
+ if(entry) {
557
+ __user_icons__.set(node.id, entry);
558
+ } else if(node && typeof node.id === "string") {
559
+ /* An update that broke the drawing takes the old one away: the
560
+ * store holds the new svg, and showing the old one would say the
561
+ * edit had not landed. */
562
+ __user_icons__.delete(node.id);
563
+ }
564
+ rebuild_user_icons_stylesheet();
565
+ return !!entry;
566
+ }
567
+
568
+ /************************************************************
569
+ * A node of __icons__ was deleted.
570
+ ************************************************************/
571
+ export function yui_icons_remove_user(id)
572
+ {
573
+ __user_icons__.delete(id);
574
+ rebuild_user_icons_stylesheet();
575
+ }
576
+
577
+ /************************************************************
578
+ * Every icon a user can choose: the library's, read from the
579
+ * loaded stylesheets (an app may extend yui_icons.css, so it
580
+ * is asked, not listed), then the user's.
581
+ * Return [{name, user}], each half sorted by name.
582
+ ************************************************************/
583
+ export function yui_icons_list()
584
+ {
585
+ let library = new Set();
586
+ try {
587
+ for(const sheet of Array.from(document.styleSheets || [])) {
588
+ if(sheet.ownerNode && sheet.ownerNode.id === USER_ICONS_STYLE_ID) {
589
+ continue;
590
+ }
591
+ let rules;
592
+ try {
593
+ rules = sheet.cssRules;
594
+ } catch(e) {
595
+ continue; /* a cross-origin sheet cannot be read, and holds no yi- icon */
596
+ }
597
+ for(const rule of Array.from(rules || [])) {
598
+ let selector = rule.selectorText || "";
599
+ for(const m of selector.matchAll(/\.(yi-[a-z0-9-]+)::?before/g)) {
600
+ if(!m[1].startsWith(USER_ICON_PREFIX)) {
601
+ library.add(m[1]);
602
+ }
603
+ }
604
+ }
605
+ }
606
+ } catch(e) {
607
+ log_error(`user icons: cannot read the stylesheets: ${e}`);
608
+ }
609
+
610
+ let list = Array.from(library).sort().map(name => ({name, user: false}));
611
+ let users = Array.from(__user_icons__.keys()).sort();
612
+ for(const id of users) {
613
+ list.push({name: yui_user_icon_class(id), user: true});
614
+ }
615
+ return list;
616
+ }