@yuneta/gobj-ui 7.26.10 → 7.26.12

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,372 @@
1
+ #!/usr/bin/env node
2
+ /***********************************************************************
3
+ * check-markup-strings.mjs
4
+ *
5
+ * createElement2() reads a plain string that starts with '<' as
6
+ * html (gobj-js), so whether a string RUNS depends on its content,
7
+ * not on who wrote it. The way out is to say markup out loud --
8
+ * html_markup('<i class="yi-copy"></i>') -- and, once every
9
+ * deliberate markup does, to turn on set_strings_are_text(true),
10
+ * where a plain string is always text.
11
+ *
12
+ * This check finds, in the CONTENT of a createElement2()
13
+ * description (`[tag, attrs, content]`) and in its list of
14
+ * children:
15
+ *
16
+ * literal a string literal that starts with '<': deliberate
17
+ * markup, to be wrapped in html_markup().
18
+ * built a template with ${...} or a '+' concatenation that
19
+ * starts with '<': markup BUILT WITH VALUES. If a value
20
+ * is data, that is the hole; build the element with
21
+ * createElement2() and pass the value as text.
22
+ * in-list a string that starts with '<' inside a LIST of
23
+ * children: since gobj-js 7.26.2 a string there is
24
+ * text, so it renders as the literal tags.
25
+ * list-head a list of children whose FIRST item is a string that
26
+ * starts with '<': createElement2() reads such a list as
27
+ * one description, so the string would be its tag.
28
+ *
29
+ * A ternary or a `||`/`&&` in the content is checked branch by
30
+ * branch; `'<b>'.concat(x)` counts as built; a computed tag is
31
+ * taken when the attrs slot is an object literal.
32
+ *
33
+ * What it cannot see: a VARIABLE or a function result holding a
34
+ * string (its type is not known before running); a description
35
+ * built piece by piece (push() into an array that is later the
36
+ * content); a computed tag with an attrs slot that is not an object
37
+ * literal; markup given to innerHTML, or to a widget (Tabulator,
38
+ * G6), which are other sinks. set_strings_are_text(true) logs, once
39
+ * at run time, every string that reaches createElement2() starting
40
+ * with '<': that is the other half of the check.
41
+ *
42
+ * Usage (from the package root):
43
+ * node scripts/check-markup-strings.mjs [dir|file ...] # default: src
44
+ * Exit 1 when anything is found.
45
+ *
46
+ * Copyright (c) 2026, ArtGins.
47
+ * All Rights Reserved.
48
+ ***********************************************************************/
49
+ import {readFileSync, readdirSync, statSync, realpathSync} from "node:fs";
50
+ import {join, relative, resolve} from "node:path";
51
+ import {fileURLToPath} from "node:url";
52
+ import {parse} from "acorn";
53
+
54
+ const TAG_RE = /^[a-z][a-z0-9-]*$/i;
55
+ const SKIP_DIRS = new Set(["node_modules", "dist", ".git", "build", "_build"]);
56
+
57
+ function list_files(path, out)
58
+ {
59
+ let st = statSync(path);
60
+ if(st.isDirectory()) {
61
+ for(const name of readdirSync(path)) {
62
+ if(SKIP_DIRS.has(name)) {
63
+ continue;
64
+ }
65
+ list_files(join(path, name), out);
66
+ }
67
+ } else if(/\.(js|mjs)$/.test(path) && !/\.test\.(js|mjs)$/.test(path)) {
68
+ out.push(path);
69
+ }
70
+ return out;
71
+ }
72
+
73
+ function is_string_literal(n)
74
+ {
75
+ return n && n.type === "Literal" && typeof n.value === "string";
76
+ }
77
+
78
+ function static_string(n)
79
+ {
80
+ if(is_string_literal(n)) {
81
+ return n.value;
82
+ }
83
+ if(n && n.type === "TemplateLiteral" && n.expressions.length === 0) {
84
+ return n.quasis[0].value.cooked;
85
+ }
86
+ return null;
87
+ }
88
+
89
+ function starts_with_markup(s)
90
+ {
91
+ return typeof s === "string" && s.trim().startsWith("<");
92
+ }
93
+
94
+ /* String methods that keep the head of their receiver (a markup head
95
+ * stays a markup head through them). */
96
+ const HEAD_KEEPING_METHODS = new Set([
97
+ "trim", "trimStart", "trimEnd", "toString", "valueOf", "normalize",
98
+ "toLowerCase", "toUpperCase", "replace", "replaceAll", "padEnd", "concat"
99
+ ]);
100
+
101
+ function concat_parts(parts)
102
+ {
103
+ /* parts: [{text, complete}] in order. The leading text runs while
104
+ * the parts are static. */
105
+ let text = "";
106
+ for(const p of parts) {
107
+ if(p === null) {
108
+ return {text, complete: false};
109
+ }
110
+ text += p.text;
111
+ if(!p.complete) {
112
+ return {text, complete: false};
113
+ }
114
+ }
115
+ return {text, complete: true};
116
+ }
117
+
118
+ function template_parts(quasis, expressions, raw)
119
+ {
120
+ let parts = [];
121
+ for(let i = 0; i < quasis.length; i++) {
122
+ let q = quasis[i].value;
123
+ parts.push({text: raw ? q.raw : (q.cooked ?? ""), complete: true});
124
+ if(i < expressions.length) {
125
+ parts.push(leading(expressions[i]));
126
+ }
127
+ }
128
+ return parts;
129
+ }
130
+
131
+ /* The text an expression STARTS with, as far as it is static:
132
+ * {text, complete} (complete: the whole value is static), or null when
133
+ * it starts with something the check cannot see. */
134
+ function leading(n)
135
+ {
136
+ if(!n) {
137
+ return null;
138
+ }
139
+ if(is_string_literal(n)) {
140
+ return {text: n.value, complete: true};
141
+ }
142
+ if(n.type === "TemplateLiteral") {
143
+ return concat_parts(template_parts(n.quasis, n.expressions, false));
144
+ }
145
+ if(n.type === "TaggedTemplateExpression") {
146
+ let tag = n.tag;
147
+ if(tag.type === "MemberExpression" && !tag.computed &&
148
+ tag.object.type === "Identifier" && tag.object.name === "String" &&
149
+ tag.property.name === "raw") {
150
+ return concat_parts(template_parts(n.quasi.quasis, n.quasi.expressions, true));
151
+ }
152
+ return null;
153
+ }
154
+ if(n.type === "BinaryExpression" && n.operator === "+") {
155
+ let operands = [];
156
+ let flatten = (e) => {
157
+ if(e.type === "BinaryExpression" && e.operator === "+") {
158
+ flatten(e.left);
159
+ flatten(e.right);
160
+ } else {
161
+ operands.push(e);
162
+ }
163
+ };
164
+ flatten(n);
165
+ return concat_parts(operands.map(leading));
166
+ }
167
+ if(n.type === "SequenceExpression") {
168
+ return leading(n.expressions[n.expressions.length - 1]);
169
+ }
170
+ if(n.type === "CallExpression" && n.callee.type === "MemberExpression" &&
171
+ !n.callee.computed) {
172
+ let method = n.callee.property.name;
173
+ let receiver = n.callee.object;
174
+ if(method === "join" && receiver.type === "ArrayExpression") {
175
+ let sep = n.arguments.length ? leading(n.arguments[0]) : {text: ",", complete: true};
176
+ let parts = [];
177
+ receiver.elements.forEach((el, k) => {
178
+ if(k > 0) {
179
+ parts.push(sep);
180
+ }
181
+ parts.push(leading(el));
182
+ });
183
+ return concat_parts(parts);
184
+ }
185
+ if(HEAD_KEEPING_METHODS.has(method)) {
186
+ let head = leading(receiver);
187
+ if(head === null) {
188
+ return null;
189
+ }
190
+ if(method === "concat") {
191
+ return concat_parts([head, ...n.arguments.map(leading)]);
192
+ }
193
+ /* The head is kept; the whole is no longer known to be static. */
194
+ return {text: head.text, complete: false};
195
+ }
196
+ return null;
197
+ }
198
+ return null;
199
+ }
200
+
201
+ /* Markup BUILT with values: its static head starts with '<' and it is
202
+ * not static as a whole. */
203
+ function built_markup(n)
204
+ {
205
+ let head = leading(n);
206
+ return !!head && !head.complete && starts_with_markup(head.text);
207
+ }
208
+
209
+ /* [tag, attrs, content, events?]: a tag and an attrs slot. A literal
210
+ * tag must look like one; a computed tag (a variable, a ternary) is
211
+ * taken when the attrs slot is an object literal, which is what makes
212
+ * the array a description and not some other triple. */
213
+ function is_description(n)
214
+ {
215
+ if(!n || n.type !== "ArrayExpression" || n.elements.length < 3 || n.elements.length > 4) {
216
+ return false;
217
+ }
218
+ let tag = n.elements[0];
219
+ let attrs = n.elements[1];
220
+ if(!tag || !attrs) {
221
+ return false;
222
+ }
223
+ if(is_string_literal(tag)) {
224
+ if(!TAG_RE.test(tag.value)) {
225
+ return false;
226
+ }
227
+ return attrs.type === "ObjectExpression" || attrs.type === "Identifier" ||
228
+ attrs.type === "MemberExpression" || attrs.type === "CallExpression" ||
229
+ attrs.type === "ConditionalExpression" ||
230
+ (attrs.type === "Literal" && attrs.value === null);
231
+ }
232
+ if(tag.type === "SpreadElement" || tag.type === "ArrayExpression" ||
233
+ tag.type === "ObjectExpression" || tag.type === "Literal") {
234
+ return false;
235
+ }
236
+ return attrs.type === "ObjectExpression";
237
+ }
238
+
239
+ function walk(node, visit)
240
+ {
241
+ if(!node || typeof node.type !== "string") {
242
+ return;
243
+ }
244
+ visit(node);
245
+ for(const key of Object.keys(node)) {
246
+ if(key === "loc" || key === "start" || key === "end") {
247
+ continue;
248
+ }
249
+ let v = node[key];
250
+ if(Array.isArray(v)) {
251
+ for(const c of v) {
252
+ if(c && typeof c.type === "string") {
253
+ walk(c, visit);
254
+ }
255
+ }
256
+ } else if(v && typeof v.type === "string") {
257
+ walk(v, visit);
258
+ }
259
+ }
260
+ }
261
+
262
+ function check_content(n, findings, file, src, where)
263
+ {
264
+ if(!n) {
265
+ return;
266
+ }
267
+ if(n.type === "ConditionalExpression") {
268
+ check_content(n.consequent, findings, file, src, where);
269
+ check_content(n.alternate, findings, file, src, where);
270
+ return;
271
+ }
272
+ if(n.type === "LogicalExpression") {
273
+ check_content(n.left, findings, file, src, where);
274
+ check_content(n.right, findings, file, src, where);
275
+ return;
276
+ }
277
+ if(n.type === "SequenceExpression") {
278
+ check_content(n.expressions[n.expressions.length - 1], findings, file, src, where);
279
+ return;
280
+ }
281
+ let head = leading(n);
282
+ if(head && head.complete && starts_with_markup(head.text)) {
283
+ findings.push({file, line: n.loc.start.line, rule: where === "list" ? "in-list" : "literal",
284
+ text: src.slice(n.start, Math.min(n.end, n.start + 90))});
285
+ return;
286
+ }
287
+ if(built_markup(n)) {
288
+ findings.push({file, line: n.loc.start.line, rule: "built",
289
+ text: src.slice(n.start, Math.min(n.end, n.start + 90))});
290
+ }
291
+ }
292
+
293
+ function check_file(file, root)
294
+ {
295
+ const src = readFileSync(file, "utf8");
296
+ let ast;
297
+ try {
298
+ ast = parse(src, {ecmaVersion: "latest", sourceType: "module", locations: true,
299
+ allowHashBang: true, allowAwaitOutsideFunction: true});
300
+ } catch(e) {
301
+ console.error(`${relative(root, file)}: cannot parse: ${e.message}`);
302
+ return [{file, line: 0, rule: "parse", text: e.message}];
303
+ }
304
+ const findings = [];
305
+ const rel = relative(root, file);
306
+ walk(ast, (n) => {
307
+ if(!is_description(n)) {
308
+ return;
309
+ }
310
+ let content = n.elements[2];
311
+ if(content && content.type === "ArrayExpression" && content.elements.length > 0) {
312
+ let lead = leading(content.elements[0]);
313
+ let head = (lead && lead.complete)? lead.text : null;
314
+ if(head !== null && starts_with_markup(head)) {
315
+ /* createElement2() reads a list that starts with a string
316
+ * as ONE description: '<b>' would be its tag. */
317
+ findings.push({file: rel, line: content.loc.start.line, rule: "list-head",
318
+ text: src.slice(content.start, Math.min(content.end, content.start + 90))});
319
+ } else if(head === null) {
320
+ for(const child of content.elements) {
321
+ check_content(child, findings, rel, src, "list");
322
+ }
323
+ }
324
+ } else {
325
+ check_content(content, findings, rel, src, "slot");
326
+ }
327
+ });
328
+ return findings;
329
+ }
330
+
331
+ export {check_file};
332
+
333
+ /* Run as a command (not imported by a test). Both sides through
334
+ * realpath: argv[1] keeps a symlinked path, import.meta.url does not. */
335
+ if(process.argv[1] &&
336
+ realpathSync(fileURLToPath(import.meta.url)) === realpathSync(process.argv[1])) {
337
+ main();
338
+ }
339
+
340
+ function main()
341
+ {
342
+ const root = process.cwd();
343
+ const targets = process.argv.slice(2).length ? process.argv.slice(2) : ["src"];
344
+ let files = [];
345
+ for(const t of targets) {
346
+ const path = resolve(root, t); // an absolute path stays absolute
347
+ try {
348
+ statSync(path);
349
+ } catch(e) {
350
+ console.error(`check-markup-strings: no such file or directory: ${t}`);
351
+ process.exit(2);
352
+ }
353
+ list_files(path, files);
354
+ }
355
+
356
+ let all = [];
357
+ for(const f of files) {
358
+ all = all.concat(check_file(f, root));
359
+ }
360
+
361
+ const by_rule = {};
362
+ for(const f of all) {
363
+ by_rule[f.rule] = (by_rule[f.rule] || 0) + 1;
364
+ console.log(`${f.file}:${f.line}: ${f.rule}: ${f.text.replace(/\s+/g, " ")}`);
365
+ }
366
+ if(all.length) {
367
+ console.log(`\ncheck-markup-strings: ${all.length} found ` +
368
+ `(${Object.entries(by_rule).map(([k, v]) => `${k} ${v}`).join(", ")}) in ${files.length} files`);
369
+ process.exit(1);
370
+ }
371
+ console.log(`check-markup-strings: OK (${files.length} files)`);
372
+ }
@@ -213,14 +213,17 @@ class YuiToolbar extends Toolbar
213
213
  return `<div class="g6-toolbar-sep" aria-hidden="true"></div>`;
214
214
  }
215
215
 
216
- const extra_class = item.className ? ` ${item.className}` : '';
217
- const title = item.title ?? '';
216
+ /* Everything that goes into this markup is escaped, the
217
+ * read-out branch too: its text, title and value are values
218
+ * (a zoom figure, a translated title), never markup. */
219
+ const extra_class = item.className ? ` ${escapeHtml(String(item.className))}` : '';
220
+ const title = escapeHtml(String(item.title ?? ''));
218
221
 
219
222
  if(item.readout) {
220
223
  return (
221
224
  `<div class="g6-toolbar-readout${extra_class}"` +
222
225
  ` title="${title}" aria-label="${title}">` +
223
- `${item.text ?? ''}` +
226
+ `${escapeHtml(String(item.text ?? ''))}` +
224
227
  `</div>`
225
228
  );
226
229
  }
@@ -229,14 +232,14 @@ class YuiToolbar extends Toolbar
229
232
  const is_text = (item.text !== undefined);
230
233
  const kind_class = is_text ? ' g6-toolbar-item-text' : '';
231
234
  const body = is_text
232
- ? `<span class="g6-toolbar-text">${item.text}</span>`
235
+ ? `<span class="g6-toolbar-text">${escapeHtml(String(item.text))}</span>`
233
236
  : `<svg aria-hidden="true" focusable="false">` +
234
- `<use xlink:href="#${item.id}"></use>` +
237
+ `<use xlink:href="#${escapeHtml(String(item.id))}"></use>` +
235
238
  `</svg>`;
236
239
 
237
240
  return (
238
241
  `<div class="g6-toolbar-item${kind_class}${extra_class}"` +
239
- ` value="${item.value}" title="${title}"` +
242
+ ` value="${escapeHtml(String(item.value))}" title="${title}"` +
240
243
  ` aria-label="${title}"${disabled}>` +
241
244
  `${body}` +
242
245
  `</div>`
@@ -2301,6 +2304,10 @@ function topic_defaults_of(gobj, topic_name)
2301
2304
  * It is written into a card's html (see yui_data_color.js): a
2302
2305
  * refused value logs, and the node wears the topic's colour.
2303
2306
  ************************************************************/
2307
+ const refused_colors_logged = new Set(); // once per (gobj, value): every repaint asks again
2308
+ const REFUSED_COLORS_LOG_MAX = 200;
2309
+ let refused_colors_capped = false;
2310
+
2304
2311
  function data_color(gobj, value)
2305
2312
  {
2306
2313
  if(value === undefined || value === null || value === "") {
@@ -2308,7 +2315,23 @@ function data_color(gobj, value)
2308
2315
  }
2309
2316
  let color = css_color_or_null(value);
2310
2317
  if(!color) {
2311
- log_warning(`${gobj_short_name(gobj)}: colour refused, not a css colour: ${JSON.stringify(value)}`);
2318
+ let key = `${gobj_short_name(gobj)}\u0000${String(value)}`;
2319
+ if(refused_colors_logged.has(key)) {
2320
+ return color;
2321
+ }
2322
+ if(refused_colors_logged.size < REFUSED_COLORS_LOG_MAX) {
2323
+ refused_colors_logged.add(key);
2324
+ log_warning(`${gobj_short_name(gobj)}: colour refused, not a css colour: ${JSON.stringify(value)}`);
2325
+ } else if(!refused_colors_capped) {
2326
+ /* Bounded, but not silent: say once that the rest go unlogged.
2327
+ * An LRU would log again and again on every repaint of a
2328
+ * graph with more refused colours than it holds. */
2329
+ refused_colors_capped = true;
2330
+ log_warning(
2331
+ `${gobj_short_name(gobj)}: ${REFUSED_COLORS_LOG_MAX} refused colours ` +
2332
+ `logged; further refused colours are not logged`
2333
+ );
2334
+ }
2312
2335
  }
2313
2336
  return color;
2314
2337
  }
@@ -9017,7 +9040,7 @@ function ctx_item(icon_id, label, value)
9017
9040
  `vertical-align:-0.125em;margin-right:8px;` +
9018
9041
  `pointer-events:none;fill:currentColor">` +
9019
9042
  `<use href="#${icon_id}"></use></svg>` +
9020
- `${label}`;
9043
+ `${escapeHtml(String(label))}`; // text: G6 innerHTMLs the name
9021
9044
  return { name: name, value: value };
9022
9045
  }
9023
9046
 
package/src/c_yui_form.js CHANGED
@@ -92,7 +92,7 @@ import "./tabulator.css";
92
92
  import {is_time_field} from "./json_view_helpers.js";
93
93
  import {date_to_datetime_local, datetime_local_to_epoch} from "./form_time_value.js";
94
94
  import {parse_json_field, json_editor_value} from "./form_json_field.js";
95
- import {text_node, text_title_formatter} from "./yui_text.js";
95
+ import {text_node, text_title_formatter, text_list_item_formatter} from "./yui_text.js";
96
96
  import { TabulatorFull as Tabulator } from "tabulator-tables"; // Import Full Tabulator JS
97
97
  // import { Tabulator } from "tabulator-tables"; // Import light Tabulator JS
98
98
 
@@ -2325,6 +2325,7 @@ function template2columns(gobj, columns, template, sub_elements)
2325
2325
  case "enum":
2326
2326
  column.editor = "list";
2327
2327
  column.editorParams = {
2328
+ itemFormatter: text_list_item_formatter // schema data
2328
2329
  };
2329
2330
  switch(field_desc.real_type) {
2330
2331
  case "string": // TODO review types
@@ -462,7 +462,7 @@ function render_raw(gobj)
462
462
  if(dump.error) {
463
463
  children.push(
464
464
  ['div', {class: 'GCLASS_RAW_ERROR has-text-danger is-size-7 p-2'},
465
- dump.error]);
465
+ text_node(dump.error)]); // the backend's words
466
466
  }
467
467
 
468
468
  let $body = createElement2(['div', {class: 'GCLASS_RAW_WRAP'}, children]);
@@ -556,7 +556,7 @@ function build_head(gobj, model)
556
556
  {
557
557
  let items = [
558
558
  ['span', {class: 'GCLASS_NAME'},
559
- model.id || gobj_read_str_attr(gobj, "gclass_name") || "?"]
559
+ text_node(model.id || gobj_read_str_attr(gobj, "gclass_name") || "?")]
560
560
  ];
561
561
 
562
562
  if(model.instances !== null) {
@@ -577,7 +577,7 @@ function build_head(gobj, model)
577
577
  items.push(
578
578
  ['span', {class: 'GCLASS_CHIP GCLASS_CURRENT',
579
579
  title: t("current state"),
580
- 'data-i18n-title': 'current state'}, current]);
580
+ 'data-i18n-title': 'current state'}, text_node(current)]);
581
581
  }
582
582
 
583
583
  return ['div', {class: 'GCLASS_HEAD'}, items];
@@ -819,14 +819,14 @@ function build_methods(model)
819
819
  if(model.methods.length) {
820
820
  blocks.push(['div', {class: 'GCLASS_CHIPS'},
821
821
  model.methods.map((m) =>
822
- ['span', row_attrs(m, {class: 'GCLASS_CHIP GCLASS_METHOD'}), m])]);
822
+ ['span', row_attrs(m, {class: 'GCLASS_CHIP GCLASS_METHOD'}), text_node(m)])]);
823
823
  }
824
824
  if(model.internal_methods.length) {
825
825
  blocks.push(['div', {class: 'GCLASS_SUBTITLE', i18n: 'internal methods'},
826
826
  t("internal methods")]);
827
827
  blocks.push(['div', {class: 'GCLASS_CHIPS'},
828
828
  model.internal_methods.map((m) =>
829
- ['span', row_attrs(m, {class: 'GCLASS_CHIP GCLASS_METHOD'}), m])]);
829
+ ['span', row_attrs(m, {class: 'GCLASS_CHIP GCLASS_METHOD'}), text_node(m)])]);
830
830
  }
831
831
 
832
832
  return ['div', {class: 'GCLASS_METHODS'}, blocks];
package/src/c_yui_json.js CHANGED
@@ -905,7 +905,7 @@ function push_collapsed_row(ctx, value, segments, depth, key, rows)
905
905
  'data-i18n': err.error}, t(err.error)]);
906
906
  } else if(err) {
907
907
  children.push(['span', {class: 'JSON_STUB_ERR has-text-danger is-size-7 ml-2'},
908
- String(err.error)]);
908
+ text_node(err.error)]); // the backend's words
909
909
  }
910
910
 
911
911
  let attrs = {
@@ -1989,7 +1989,7 @@ function select_input(name, value, options)
1989
1989
  let $options = options.map((option) => {
1990
1990
  return ["option", el_attrs({value: `${option}`,
1991
1991
  selected: `${option}` === `${value}` ? "selected" : undefined}),
1992
- `${option}`];
1992
+ text_node(`${option}`)]; // names from the schema: data
1993
1993
  });
1994
1994
 
1995
1995
  return ["div", {class: "select is-fullwidth"}, [
@@ -2002,7 +2002,7 @@ function textarea_input(name, value, rows, placeholder)
2002
2002
  return ["textarea", {class: "textarea", "data-name": name,
2003
2003
  rows: `${rows || 3}`,
2004
2004
  placeholder: placeholder || ""},
2005
- value === undefined || value === null ? "" : `${value}`];
2005
+ text_node(value === undefined || value === null ? "" : `${value}`)];
2006
2006
  }
2007
2007
 
2008
2008
  /***************************************************************