@es-joy/jsoe 0.29.0 → 0.31.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (88) hide show
  1. package/.claude/scheduled_tasks.lock +1 -0
  2. package/CHANGES.md +11 -0
  3. package/README.md +3 -0
  4. package/dist/fundamentalTypes/dateType.d.ts +8 -3
  5. package/dist/fundamentalTypes/dateType.d.ts.map +1 -1
  6. package/dist/index.js +2 -2
  7. package/dist/index.js.map +1 -1
  8. package/dist/search/fundamentalTypes/arraySearchType.d.ts +11 -4
  9. package/dist/search/fundamentalTypes/arraySearchType.d.ts.map +1 -1
  10. package/dist/search/fundamentalTypes/bigintSearchType.d.ts.map +1 -1
  11. package/dist/search/fundamentalTypes/blobSearchType.d.ts.map +1 -1
  12. package/dist/search/fundamentalTypes/dateSearchType.d.ts +8 -3
  13. package/dist/search/fundamentalTypes/dateSearchType.d.ts.map +1 -1
  14. package/dist/search/fundamentalTypes/domexceptionSearchType.d.ts +5 -5
  15. package/dist/search/fundamentalTypes/domexceptionSearchType.d.ts.map +1 -1
  16. package/dist/search/fundamentalTypes/enumSearchType.d.ts +4 -0
  17. package/dist/search/fundamentalTypes/enumSearchType.d.ts.map +1 -1
  18. package/dist/search/fundamentalTypes/fileSearchType.d.ts +19 -10
  19. package/dist/search/fundamentalTypes/fileSearchType.d.ts.map +1 -1
  20. package/dist/search/fundamentalTypes/filelistSearchType.d.ts +4 -12
  21. package/dist/search/fundamentalTypes/filelistSearchType.d.ts.map +1 -1
  22. package/dist/search/fundamentalTypes/functionSearchType.d.ts +4 -4
  23. package/dist/search/fundamentalTypes/functionSearchType.d.ts.map +1 -1
  24. package/dist/search/fundamentalTypes/mapSearchType.d.ts +8 -4
  25. package/dist/search/fundamentalTypes/mapSearchType.d.ts.map +1 -1
  26. package/dist/search/fundamentalTypes/numberSearchType.d.ts.map +1 -1
  27. package/dist/search/fundamentalTypes/objectSearchType.d.ts +10 -4
  28. package/dist/search/fundamentalTypes/objectSearchType.d.ts.map +1 -1
  29. package/dist/search/fundamentalTypes/regexpSearchType.d.ts +7 -1
  30. package/dist/search/fundamentalTypes/regexpSearchType.d.ts.map +1 -1
  31. package/dist/search/fundamentalTypes/setSearchType.d.ts +5 -4
  32. package/dist/search/fundamentalTypes/setSearchType.d.ts.map +1 -1
  33. package/dist/search/fundamentalTypes/stringSearchType.d.ts +9 -1
  34. package/dist/search/fundamentalTypes/stringSearchType.d.ts.map +1 -1
  35. package/dist/search/fundamentalTypes/symbolSearchType.d.ts.map +1 -1
  36. package/dist/search/index.d.ts +18 -8
  37. package/dist/search/index.d.ts.map +1 -1
  38. package/dist/search/queryTree.d.ts +15 -1
  39. package/dist/search/queryTree.d.ts.map +1 -1
  40. package/dist/search/queryTreeBuilders.d.ts +8 -1
  41. package/dist/search/queryTreeBuilders.d.ts.map +1 -1
  42. package/dist/search/searchElementUtils.d.ts +17 -8
  43. package/dist/search/searchElementUtils.d.ts.map +1 -1
  44. package/dist/search/searchUtils.d.ts +350 -18
  45. package/dist/search/searchUtils.d.ts.map +1 -1
  46. package/dist/search/subTypes/blobHTMLSearchType.d.ts +32 -5
  47. package/dist/search/subTypes/blobHTMLSearchType.d.ts.map +1 -1
  48. package/dist/search/subTypes/recordSearchType.d.ts +4 -4
  49. package/dist/search/subTypes/recordSearchType.d.ts.map +1 -1
  50. package/dist/search/subTypes/tupleSearchType.d.ts +3 -3
  51. package/dist/search/subTypes/tupleSearchType.d.ts.map +1 -1
  52. package/dist/search/superTypes/buffersourceSearchType.d.ts.map +1 -1
  53. package/dist/search/unions/unionFamilySearchType.d.ts.map +1 -1
  54. package/package.json +3 -3
  55. package/pnpm-workspace.yaml +26 -26
  56. package/src/fundamentalTypes/dateType.js +9 -4
  57. package/src/fundamentalTypes/regexpType.js +1 -1
  58. package/src/jsoe.css +204 -0
  59. package/src/search/fundamentalTypes/arraySearchType.js +42 -7
  60. package/src/search/fundamentalTypes/bigintSearchType.js +7 -1
  61. package/src/search/fundamentalTypes/blobSearchType.js +2 -1
  62. package/src/search/fundamentalTypes/booleanSearchType.js +1 -1
  63. package/src/search/fundamentalTypes/dateSearchType.js +113 -20
  64. package/src/search/fundamentalTypes/domexceptionSearchType.js +39 -10
  65. package/src/search/fundamentalTypes/enumSearchType.js +5 -1
  66. package/src/search/fundamentalTypes/fileSearchType.js +64 -11
  67. package/src/search/fundamentalTypes/filelistSearchType.js +32 -7
  68. package/src/search/fundamentalTypes/functionSearchType.js +36 -12
  69. package/src/search/fundamentalTypes/mapSearchType.js +43 -13
  70. package/src/search/fundamentalTypes/numberSearchType.js +8 -1
  71. package/src/search/fundamentalTypes/objectSearchType.js +236 -17
  72. package/src/search/fundamentalTypes/regexpSearchType.js +29 -5
  73. package/src/search/fundamentalTypes/setSearchType.js +33 -7
  74. package/src/search/fundamentalTypes/stringSearchType.js +11 -2
  75. package/src/search/fundamentalTypes/symbolSearchType.js +2 -1
  76. package/src/search/index.js +26 -9
  77. package/src/search/queryTree.js +14 -2
  78. package/src/search/queryTreeBuilders.js +12 -2
  79. package/src/search/searchElementUtils.js +108 -24
  80. package/src/search/searchUtils.js +576 -24
  81. package/src/search/subTypes/blobHTMLSearchType.js +202 -9
  82. package/src/search/subTypes/recordSearchType.js +34 -13
  83. package/src/search/subTypes/tupleSearchType.js +51 -10
  84. package/src/search/superTypes/SpecialRealNumberSearchType.js +1 -1
  85. package/src/search/superTypes/buffersourceSearchType.js +7 -1
  86. package/src/search/unions/unionFamilySearchType.js +8 -0
  87. package/vendor/zod/classic/schemas.d.ts +3 -1
  88. package/vendor/zod/core/versions.js +1 -1
@@ -42,7 +42,7 @@ export function buildPathLabel (schemaObject, path) {
42
42
  * `typeNamespace` closed over inside a `$define` mixin, which is installed
43
43
  * once on the shared custom-element prototype the first time a tag is
44
44
  * defined - nothing here depends on a per-instance closure at all.
45
- * @param {HTMLElement} root
45
+ * @param {Element} root
46
46
  * @param {string} selector
47
47
  * @returns {HTMLElement|undefined}
48
48
  */
@@ -52,6 +52,113 @@ export function findOwnControl (root, selector) {
52
52
  ).find((el) => el.closest('[data-search-path]') === root);
53
53
  }
54
54
 
55
+ /**
56
+ * Whether `el` sits inside an `objectSearchType.js` has-property row whose
57
+ * own "Has"/"Doesn't have" tri-state is *already* explicitly chosen (not
58
+ * "(any)") - if so, that existence assertion alone is already a complete
59
+ * constraint for the row, so a per-field "no absent values" requirement
60
+ * inside it (a range's own "at least one bound", `buildRangeInputsPair`'s
61
+ * doc) should be relaxed. `setDescendantsRequired` handles this for plain
62
+ * `required`-attribute controls, but a range pair's requirement is
63
+ * re-asserted imperatively on every `input`/`change` via `setCustomValidity`
64
+ * (`syncRangeValidity`, `dateSearchType.js`'s own equivalent) - clearing it
65
+ * once wouldn't stick past the next keystroke, so those call this directly,
66
+ * live, instead.
67
+ *
68
+ * Returns `false` (not exempted) when `el` also sits inside a
69
+ * `buildOptInFieldset` fieldset (`jsoeSearchOptInFieldset--*`), for the same
70
+ * reason `setDescendantsRequired` skips those controls: a dimension range
71
+ * nested in `makeDomShapeSearchType`'s per-dimension opt-in gate (say,
72
+ * DOMRect's "Width") is only reachable at all once its own checkbox is
73
+ * checked, and checking it is itself the user's explicit request to
74
+ * constrain *that* facet - an enclosing "Has property" shouldn't then let
75
+ * its "From"/"To" sit blank and still read as valid, any more than
76
+ * `fileSearchType.js`'s "Name" facet should once opted into.
77
+ * @param {Element} el
78
+ * @returns {boolean}
79
+ */
80
+ export function isExemptedByAncestorHasProperty (el) {
81
+ if (el.closest('fieldset[class^="jsoeSearchOptInFieldset--"]')) {
82
+ return false;
83
+ }
84
+ const row = el.closest('jsoe-search-has-property');
85
+ if (!row) {
86
+ return false;
87
+ }
88
+ const select = /** @type {HTMLSelectElement|undefined} */ (
89
+ findOwnControl(row, 'select.jsoeSearchTriState--')
90
+ );
91
+ return select !== undefined && select.value !== '';
92
+ }
93
+
94
+ /**
95
+ * Re-runs every `input`/`change`-driven validator within `root` by
96
+ * re-dispatching those events on each descendant form control -
97
+ * `objectSearchType.js`'s `buildHasPropertyRow` calls this when its own
98
+ * "Has"/"Doesn't have" tri-state changes, since a range pair (or anything
99
+ * else reactive) nested anywhere inside the child widget needs to
100
+ * re-evaluate `isExemptedByAncestorHasProperty` against the *new* tri-state
101
+ * value - nothing else would otherwise prompt it to run again until the
102
+ * user happens to interact with that specific field themselves.
103
+ * @param {Element} root
104
+ * @returns {void}
105
+ */
106
+ export function revalidateDescendants (root) {
107
+ [...root.querySelectorAll('input, select, textarea')].forEach((el) => {
108
+ el.dispatchEvent(new Event('input'));
109
+ el.dispatchEvent(new Event('change'));
110
+ });
111
+ }
112
+
113
+ /**
114
+ * The `buildRangeInputsPair` cross-validation check, factored out so a
115
+ * consuming widget's own `$define.connectedCallback` (custom elements,
116
+ * search plan §8) can also call it - the `input`/`change` events
117
+ * `buildRangeInputsPair` wires below only fire from the user's *first*
118
+ * interaction, so a freshly-built pair with both ends still empty would
119
+ * otherwise stay "valid" by the browser's reckoning (no `setCustomValidity`
120
+ * call has ever run yet) until then, contradicting the "leaving both blank
121
+ * is invalid" rule documented below. `connectedCallback` is a native
122
+ * Custom Elements lifecycle method (invoked once per instance the moment it
123
+ * connects to the document), so calling this from there closes that gap
124
+ * without needing any build-time live element reference.
125
+ *
126
+ * "Leaving both blank is invalid" is itself relaxed when
127
+ * `isExemptedByAncestorHasProperty` says so - a range nested as a has-
128
+ * property row's own child widget (e.g. a `date`/`number` property) needs
129
+ * the same "'Has property X' is already a complete constraint" relief
130
+ * `setDescendantsRequired` gives `required`-attribute controls, just
131
+ * re-checked live on every call rather than toggled once, since this runs
132
+ * imperatively on every keystroke regardless.
133
+ * @param {Element} root
134
+ * @param {string} [key]
135
+ * @returns {void}
136
+ */
137
+ export function syncRangeValidity (root, key = '') {
138
+ const gteEl = /** @type {HTMLInputElement|undefined} */ (
139
+ findOwnControl(root, `input.jsoeSearchRangeGte--${key}`)
140
+ );
141
+ const lteEl = /** @type {HTMLInputElement|undefined} */ (
142
+ findOwnControl(root, `input.jsoeSearchRangeLte--${key}`)
143
+ );
144
+ if (!gteEl || !lteEl) {
145
+ return;
146
+ }
147
+ const bothEmpty = gteEl.value === '' && lteEl.value === '' &&
148
+ !isExemptedByAncestorHasProperty(gteEl);
149
+ const outOfOrder = gteEl.value !== '' && lteEl.value !== '' &&
150
+ Number(lteEl.value) < Number(gteEl.value);
151
+ const emptyMessage = 'Enter at least one bound (From or To).';
152
+ gteEl.setCustomValidity(bothEmpty ? emptyMessage : '');
153
+ let lteMessage = '';
154
+ if (bothEmpty) {
155
+ lteMessage = emptyMessage;
156
+ } else if (outOfOrder) {
157
+ lteMessage = 'End of range must not be less than the start of the range.';
158
+ }
159
+ lteEl.setCustomValidity(lteMessage);
160
+ }
161
+
55
162
  /**
56
163
  * A "from"/"to" pair of native inputs sharing one `type`, for the OR-range/
57
164
  * Is-Not-Range README affordance (number/bigint/buffersource; `date` uses
@@ -65,6 +172,25 @@ export function findOwnControl (root, selector) {
65
172
  * apart two same-class controls belonging to the *same* widget, so those
66
173
  * need distinct classes. Leave it at the default `''` for the common case
67
174
  * of a widget with only one range pair.
175
+ *
176
+ * Cross-validates the pair via the native Constraint Validation API,
177
+ * surfaced by `jsoe.css`'s `input:invalid` styling and a real `<form>`'s
178
+ * `reportValidity`/`checkValidity` (`src/search/index.js`): leaving *both*
179
+ * ends blank is invalid - the same "no absent values" reasoning
180
+ * `buildLiteralRegexControls`'s Value input documents, an added range row
181
+ * needs at least one bound to mean anything - and if both ends are filled
182
+ * with "To" less than "From", that's invalid too. An open-ended range (only
183
+ * one end filled) stays valid. A row nested under an
184
+ * `objectSearchType.js` required-property's opt-in `<fieldset disabled>`
185
+ * (or, for `dateSearchType.js`'s own equivalent pair, its own
186
+ * "Invalid date" fieldset) is unaffected either way, since a disabled field
187
+ * is excluded from constraint validation entirely. Every caller must also
188
+ * call `syncRangeValidity` from its own `connectedCallback` (see that
189
+ * function's doc) so the initial both-blank state is actually invalid from
190
+ * the moment the widget exists, not just after the user's first keystroke.
191
+ * `dateSearchType.js`'s own `datetime-local` pair needs the same two checks
192
+ * but isn't built through this helper (`buildDateInputControl` handles its
193
+ * own ISO-slicing), so it wires an equivalent handler itself.
68
194
  * @param {{
69
195
  * name: string,
70
196
  * key?: string,
@@ -78,14 +204,34 @@ export function findOwnControl (root, selector) {
78
204
  export function buildRangeInputsPair ({
79
205
  name, key = '', type = 'number', min, max, step
80
206
  }) {
207
+ /**
208
+ * `this` is whichever of the pair fired the event - `syncRangeValidity`
209
+ * looks up both fresh via `findOwnControl` rather than closing over
210
+ * either, so it stays correct however many `buildRangeInputsPair` pairs
211
+ * (of possibly-differing `key`s) end up sharing the same widget.
212
+ * @this {HTMLElement}
213
+ * @returns {void}
214
+ */
215
+ function validateRange () {
216
+ const root = this.closest('[data-search-path]');
217
+ if (root) {
218
+ syncRangeValidity(root, key);
219
+ }
220
+ }
81
221
  return [
82
222
  ['label', [
83
223
  'From: ',
84
- ['input', {name: `${name}-gte`, class: `jsoeSearchRangeGte--${key}`, type, min, max, step}]
224
+ ['input', {
225
+ name: `${name}-gte`, class: `jsoeSearchRangeGte--${key}`, type, min, max, step,
226
+ $on: {input: validateRange, change: validateRange}
227
+ }]
85
228
  ]],
86
229
  ['label', [
87
230
  'To: ',
88
- ['input', {name: `${name}-lte`, class: `jsoeSearchRangeLte--${key}`, type, min, max, step}]
231
+ ['input', {
232
+ name: `${name}-lte`, class: `jsoeSearchRangeLte--${key}`, type, min, max, step,
233
+ $on: {input: validateRange, change: validateRange}
234
+ }]
89
235
  ]]
90
236
  ];
91
237
  }
@@ -111,14 +257,27 @@ export function readRangeInputsPair (el, key = '') {
111
257
  * A `<select multiple>` populated from a fixed candidate list - used by
112
258
  * `enum`/`multiSelect`/`literalSet` leaf controls (README: "multiple
113
259
  * select").
260
+ *
261
+ * `required`, when set, makes leaving *every* option unselected invalid -
262
+ * `<select multiple required>` is natively satisfied by one or more
263
+ * selections, no custom validity code needed. `enumSearchType.js` passes
264
+ * this (an enum widget has nothing else to constrain, so an empty selection
265
+ * is never a meaningful "no constraint" state - same "no absent values"
266
+ * reasoning as `buildLiteralRegexControls`'s Value input); other callers
267
+ * (`regexpSearchType.js`'s Flags, `SpecialRealNumberSearchType.js`) leave it
268
+ * at the default `false`, since an empty selection there legitimately means
269
+ * "no constraint on this facet" alongside a widget that has other facets.
114
270
  * @param {{
115
271
  * name: string,
116
- * options: (string|[value: string, title: string])[]
272
+ * options: (string|[value: string, title: string])[],
273
+ * required?: boolean
117
274
  * }} cfg
118
275
  * @returns {JamilihArray}
119
276
  */
120
- export function buildMultiSelect ({name, options}) {
121
- return ['select', {name, multiple: true, class: 'jsoeSearchMultiSelect'}, options.map((opt) => {
277
+ export function buildMultiSelect ({name, options, required = false}) {
278
+ return ['select', {
279
+ name, multiple: true, required, class: 'jsoeSearchMultiSelect'
280
+ }, options.map((opt) => {
122
281
  const [value, title] = Array.isArray(opt) ? opt : [opt, opt];
123
282
  return ['option', {value}, [title]];
124
283
  })];
@@ -126,7 +285,7 @@ export function buildMultiSelect ({name, options}) {
126
285
 
127
286
  /**
128
287
  * Reads back a `buildMultiSelect` into the selected values, `[]` if none.
129
- * @param {HTMLElement} el
288
+ * @param {Element} el
130
289
  * @returns {string[]}
131
290
  */
132
291
  export function readMultiSelect (el) {
@@ -172,11 +331,36 @@ export function buildHasPropertyToggle ({name, propertyName}) {
172
331
  * `dommatrixSearchType.js`'s "Is/Is not Readonly" and "Is/Is not 3d" side
173
332
  * by side); see `buildRangeInputsPair`'s doc for why. Leave it at the
174
333
  * default `''` for the common case of a widget with only one tri-state.
175
- * @param {{name: string, key?: string, trueLabel: string, falseLabel: string}} cfg
334
+ * `onChange`, when given, wires the select's own `change` event too (in
335
+ * addition to whatever the caller reads back via `readTriStateSelect` at
336
+ * `getQuery` time) - `dateSearchType.js`'s "Is valid/invalid date" tri-state
337
+ * uses it to disable the (otherwise irrelevant) From/To range while
338
+ * "Invalid date" is selected.
339
+ *
340
+ * `required`, when set, makes leaving the select at "(any)" invalid - the
341
+ * "(any)" option's `value: ''` below is exactly what native `required`
342
+ * treats as "nothing selected", the same trick `unionFamilySearchType.js`'s
343
+ * "Has type" select and `buildMultiSelect`'s `required` use.
344
+ * `booleanSearchType.js` passes this (a boolean widget has nothing else to
345
+ * constrain, so "(any)" is never a meaningful "no constraint" state - same
346
+ * "no absent values" reasoning as `buildLiteralRegexControls`'s Value
347
+ * input); other callers (`numberSearchType.js`'s "Is/Is Not Integer",
348
+ * `dommatrixSearchType.js`'s readonly/3d) leave it at the default `false`,
349
+ * since those are one of *several* facets in their own widget, where
350
+ * "(any)" legitimately means "no constraint on this facet".
351
+ * @param {{
352
+ * name: string, key?: string, trueLabel: string, falseLabel: string,
353
+ * onChange?: (this: HTMLElement) => void, required?: boolean
354
+ * }} cfg
176
355
  * @returns {JamilihArray}
177
356
  */
178
- export function buildTriStateSelect ({name, key = '', trueLabel, falseLabel}) {
179
- return ['select', {name, class: `jsoeSearchTriState--${key}`}, [
357
+ export function buildTriStateSelect ({
358
+ name, key = '', trueLabel, falseLabel, onChange, required = false
359
+ }) {
360
+ return ['select', {
361
+ name, class: `jsoeSearchTriState--${key}`, required,
362
+ $on: onChange ? {change: onChange} : undefined
363
+ }, [
180
364
  ['option', {value: ''}, ['(any)']],
181
365
  ['option', {value: 'true'}, [trueLabel]],
182
366
  ['option', {value: 'false'}, [falseLabel]]
@@ -186,7 +370,7 @@ export function buildTriStateSelect ({name, key = '', trueLabel, falseLabel}) {
186
370
  /**
187
371
  * Reads back a `buildTriStateSelect`/`buildHasPropertyToggle` - pass the
188
372
  * same `key` it was built with. `''` (any) maps to `undefined`.
189
- * @param {HTMLElement} el
373
+ * @param {Element} el
190
374
  * @param {string} [key]
191
375
  * @returns {boolean|undefined}
192
376
  */
@@ -205,14 +389,26 @@ export function readTriStateSelect (el, key = '') {
205
389
  * `undefined`/`void`/`null`/`NaN` ("Require present"; they have "no
206
390
  * variants to allow for distinct search", since existence only becomes a
207
391
  * meaningful question once the path is optional or nested in a union), and
208
- * also used by `recordSearchType.js` for its "require same entry" toggle.
209
- * @param {{name: string, label: string}} cfg
392
+ * also used by `recordSearchType.js`/`mapSearchType.js` for their "require
393
+ * same entry" toggle.
394
+ *
395
+ * `checked`, when set, pre-checks the checkbox; `disabled` locks it there,
396
+ * non-interactive. `makePresenceOnlySearchType` passes both: the checkbox
397
+ * is that leaf's *only* possible constraint, and its whole schema type has
398
+ * exactly one value ("no variants to allow for distinct search" above) -
399
+ * there is no second state worth offering a choice between, so this simply
400
+ * asserts the one meaningful thing outright rather than making the user
401
+ * pointlessly check a box that could only ever mean one thing. "require
402
+ * same entry" leaves both at their `false` defaults (interactive,
403
+ * unchecked), since that's one optional facet alongside a map/record's own
404
+ * key/value matches, not the whole widget's sole, single-valued constraint.
405
+ * @param {{name: string, label: string, checked?: boolean, disabled?: boolean}} cfg
210
406
  * @returns {JamilihArray}
211
407
  */
212
- export function buildCheckbox ({name, label}) {
408
+ export function buildCheckbox ({name, label, checked = false, disabled = false}) {
213
409
  return ['label', [
214
410
  `${label}: `,
215
- ['input', {type: 'checkbox', name, class: 'jsoeSearchCheckbox'}]
411
+ ['input', {type: 'checkbox', name, class: 'jsoeSearchCheckbox', checked, disabled}]
216
412
  ]];
217
413
  }
218
414
 
@@ -239,14 +435,126 @@ export function readCheckbox (el) {
239
435
  * (e.g. `errorSearchType.js`'s `message`/`name`/`fileName`/`stack`); see
240
436
  * `buildRangeInputsPair`'s doc for why. Leave it at the default `''` for
241
437
  * the common case of a widget with only one such control.
242
- * @param {{name: string, key?: string}} cfg
438
+ *
439
+ * The Value input is `required`: unlike an untouched range/checkbox/select
440
+ * (whose empty/default state unambiguously means "no constraint"), a mode
441
+ * is always selected here (there is no "(any)" option), so an empty Value
442
+ * next to it is never a meaningful "no constraint" state - it just means
443
+ * the row was added and never finished. That leaves the whole form invalid
444
+ * from the moment such a row exists (`buildSearchChoices`'s `<form>`,
445
+ * `src/search/index.js`) until either a value is entered or (for an
446
+ * `objectSearchType.js` has-property row) the row is removed via its own
447
+ * "Remove" button.
448
+ *
449
+ * `onModeChange`, when given, wires the mode select's own `change` event
450
+ * too (in addition to whatever the caller reads back via
451
+ * `readLiteralRegexQuery` at `getQuery` time) - `regexpSearchType.js` uses
452
+ * it to show/hide its Flags multi-select, which only makes sense while
453
+ * "Matches regex" is the chosen mode.
454
+ *
455
+ * `flagOptions`, when given, adds a Flags multi-select (options passed in
456
+ * by the caller - most callers pass `regexpType.js`'s own `allowedFlags`,
457
+ * the same list `regexpSearchType.js` uses for the actual regexp's own
458
+ * flags - kept out of this generic module to avoid it depending on a
459
+ * specific fundamental type), shown only while "Matches regex" is the
460
+ * chosen mode, the same `$options` a Mongo-flavored `$regex` accepts
461
+ * alongside it - a plain literal/substring match has no regex to apply
462
+ * flags to, so it stays hidden otherwise. `regexpSearchType.js`'s own call
463
+ * (matching against the regexp's `.source` text, not to be confused with
464
+ * its separate, bespoke Flags control for the regexp's *actual* flags)
465
+ * leaves this unset, since a flag there would have no real regex of its own
466
+ * to apply to.
467
+ *
468
+ * While "Matches regex" is chosen, the Value input is also live syntax-
469
+ * checked (`syncLiteralRegexValidity`, below) against
470
+ * `new RegExp(value, flags)` - an unparsable pattern (or one only invalid
471
+ * for the currently-selected flags, e.g. `u`/`v`'s stricter escape rules)
472
+ * sets a custom validity message rather than silently accepting it.
473
+ * @param {{
474
+ * name: string, key?: string, onModeChange?: (this: HTMLElement) => void,
475
+ * flagOptions?: string[]
476
+ * }} cfg
243
477
  * @returns {JamilihArray}
244
478
  */
245
- export function buildLiteralRegexControls ({name, key = ''}) {
479
+ export function buildLiteralRegexControls ({name, key = '', onModeChange, flagOptions}) {
480
+ /**
481
+ * Live syntax-checks the Value input against `new RegExp(value, flags)`
482
+ * whenever the current Mode is "Matches regex" - a literal/does-not-
483
+ * contain Value is a plain string with no format to violate, so this only
484
+ * has anything to say once "regex" is chosen, and clears back to valid
485
+ * the moment it isn't. Flags are folded in (read fresh off the Flags
486
+ * multi-select, when this call has one) because they can themselves flip
487
+ * a pattern between valid and invalid - the `u`/`v` flags' stricter escape
488
+ * rules being the main example - so a Flags `change` needs to re-run this
489
+ * exactly like a Value `input` or a Mode `change` does.
490
+ * @param {HTMLElement} el - any one of the Mode/Value/Flags controls
491
+ * @returns {void}
492
+ */
493
+ function syncLiteralRegexValidity (el) {
494
+ const root = el.closest('[data-search-path]');
495
+ const modeEl = /** @type {HTMLSelectElement|undefined} */ (
496
+ root ? findOwnControl(root, `select.jsoeSearchMode--${key}`) : undefined
497
+ );
498
+ const valueEl = /** @type {HTMLInputElement|undefined} */ (
499
+ root ? findOwnControl(root, `input.jsoeSearchValue--${key}`) : undefined
500
+ );
501
+ if (!modeEl || !valueEl) {
502
+ return;
503
+ }
504
+ if (modeEl.value !== 'regex' || !valueEl.value) {
505
+ valueEl.setCustomValidity('');
506
+ return;
507
+ }
508
+ const flagsEl = /** @type {HTMLSelectElement|undefined} */ (
509
+ root ? findOwnControl(root, `select.jsoeSearchRegexFlags--${key}`) : undefined
510
+ );
511
+ const flags = [...(flagsEl?.selectedOptions ?? [])].map((opt) => opt.value).join('');
512
+ try {
513
+ // eslint-disable-next-line no-new -- Testing
514
+ new RegExp(valueEl.value, flags);
515
+ valueEl.setCustomValidity('');
516
+ } catch {
517
+ valueEl.setCustomValidity('Enter a valid regular expression.');
518
+ }
519
+ }
520
+ /**
521
+ * @this {HTMLElement}
522
+ * @returns {void}
523
+ */
524
+ function handleModeChange () {
525
+ const flagsLabel = this.closest('[data-search-path]')?.querySelector(
526
+ `.jsoeSearchRegexFlagsLabel--${key}`
527
+ );
528
+ if (flagsLabel) {
529
+ /** @type {HTMLElement} */ (flagsLabel).hidden =
530
+ /** @type {HTMLSelectElement} */ (this).value !== 'regex';
531
+ }
532
+ syncLiteralRegexValidity(this);
533
+ onModeChange?.call(this);
534
+ }
535
+ /** @type {JamilihArray[]} */
536
+ const flagsChildren = [];
537
+ if (flagOptions) {
538
+ flagsChildren.push(['label', {class: `jsoeSearchRegexFlagsLabel--${key}`, hidden: true}, [
539
+ 'Flags: ',
540
+ ['select', {
541
+ name: `${name}-flags`, multiple: true, class: `jsoeSearchRegexFlags--${key}`,
542
+ $on: {
543
+ /** @this {HTMLElement} */
544
+ change () {
545
+ syncLiteralRegexValidity(this);
546
+ }
547
+ }
548
+ }, flagOptions.map((flag) => ['option', {value: flag}, [flag]])]
549
+ ]]);
550
+ }
246
551
  return ['span', [
247
552
  ['label', [
248
553
  'Mode: ',
249
- ['select', {name: `${name}-mode`, class: `jsoeSearchMode--${key}`}, [
554
+ ['select', {
555
+ name: `${name}-mode`, class: `jsoeSearchMode--${key}`,
556
+ $on: {change: handleModeChange}
557
+ }, [
250
558
  ['option', {value: 'literal'}, ['One of (comma-separated)']],
251
559
  ['option', {value: 'regex'}, ['Matches regex']],
252
560
  ['option', {value: 'notContains'}, ['Does not contain']]
@@ -254,15 +562,27 @@ export function buildLiteralRegexControls ({name, key = ''}) {
254
562
  ]],
255
563
  ['label', [
256
564
  'Value: ',
257
- ['input', {type: 'text', name: `${name}-value`, class: `jsoeSearchValue--${key}`}]
258
- ]]
565
+ ['input', {
566
+ type: 'text', name: `${name}-value`, class: `jsoeSearchValue--${key}`,
567
+ required: true,
568
+ $on: {
569
+ /** @this {HTMLElement} */
570
+ input () {
571
+ syncLiteralRegexValidity(this);
572
+ }
573
+ }
574
+ }]
575
+ ]],
576
+ ...flagsChildren
259
577
  ]];
260
578
  }
261
579
 
262
580
  /**
263
581
  * Reads back `buildLiteralRegexControls` into the corresponding
264
582
  * `literalSet`/`regex`/`notContains` leaf - pass the same `key` it was
265
- * built with.
583
+ * built with. A `regex` leaf's `$options` is only ever populated when the
584
+ * caller built this with `flagOptions` (see that function's doc) and at
585
+ * least one flag is currently selected.
266
586
  * @param {HTMLElement} el
267
587
  * @param {string} path
268
588
  * @param {string} [key]
@@ -281,7 +601,11 @@ export function readLiteralRegexQuery (el, path, key = '') {
281
601
  return undefined;
282
602
  }
283
603
  if (mode === 'regex') {
284
- return {kind: 'regex', path, $regex: value};
604
+ const flagsSelect = /** @type {HTMLSelectElement|undefined} */ (
605
+ findOwnControl(el, `select.jsoeSearchRegexFlags--${key}`)
606
+ );
607
+ const flags = [...(flagsSelect?.selectedOptions ?? [])].map((opt) => opt.value);
608
+ return {kind: 'regex', path, $regex: value, ...(flags.length ? {$options: flags.join('')} : {})};
285
609
  }
286
610
  if (mode === 'notContains') {
287
611
  return {kind: 'notContains', path, value};
@@ -316,7 +640,11 @@ export function buildLengthSizeControls ({name, min, max, includeSparse}) {
316
640
  'Has length/size of: ',
317
641
  ['input', {
318
642
  type: 'number', name: `${name}-size`, class: 'jsoeSearchSize',
319
- min, max, step: 1
643
+ // A length/size is never negative, regardless of whether the
644
+ // schema itself declares a (necessarily non-negative) `min` -
645
+ // floor at 0 rather than leaving the input unbounded below when it
646
+ // doesn't.
647
+ min: min === undefined ? 0 : Math.max(min, 0), max, step: 1
320
648
  }]
321
649
  ]]);
322
650
  }
@@ -334,7 +662,7 @@ export function buildLengthSizeControls ({name, min, max, includeSparse}) {
334
662
  /**
335
663
  * Reads back `buildLengthSizeControls` into one `lengthSize` leaf, or
336
664
  * `undefined` if neither the size nor the sparse control was set.
337
- * @param {HTMLElement} el
665
+ * @param {Element} el
338
666
  * @param {string} path
339
667
  * @returns {import('./queryTree.js').QueryLengthSizeLeaf|undefined}
340
668
  */
@@ -353,3 +681,227 @@ export function readLengthSizeQuery (el, path) {
353
681
  ...(sparseCheck === undefined ? {} : {sparseCheck})
354
682
  };
355
683
  }
684
+
685
+ /**
686
+ * Wraps arbitrary markup - a recursed child search widget's array, or a
687
+ * fixed facet's own controls (`buildLiteralRegexControls`'s output, say) -
688
+ * in an opt-in "Search on this" checkbox around a disabled `<fieldset>`.
689
+ * For a facet that's one of *several* independent, individually-optional
690
+ * constraints within a parent widget (array/set/tuple/filelist's element
691
+ * match(es); map/record's key/value; `fileSearchType.js`'s name/content-
692
+ * type), this keeps that facet's own `required` controls (if it has any)
693
+ * from forcing the *whole* form invalid just by the facet existing -
694
+ * generalizes `objectSearchType.js`'s original required-property row (see
695
+ * that file's history) into a shared helper once enough call sites needed
696
+ * the identical checkbox+fieldset shape.
697
+ *
698
+ * `key` distinguishes multiple opt-in fieldsets *within one widget* (e.g.
699
+ * `mapSearchType.js`'s "key" and "value"); see `buildRangeInputsPair`'s doc
700
+ * for why. Leave it at the default `''` for a widget with only one.
701
+ *
702
+ * The checkbox's own `name` attribute is `${name}-optIn`, not the bare
703
+ * `name` passed in: a caller's `name` is typically shared with (a prefix
704
+ * of) the wrapped content's own field names (`mapSearchType.js`'s "value"
705
+ * facet, say, names its checkbox from the same `name` its inner value
706
+ * widget builds its own `-value`-suffixed `<input>` from), and callers
707
+ * cannot always predict what suffix a given recursed `SearchTypeObject`
708
+ * will pick - the fixed `-optIn` suffix here guarantees no collision
709
+ * regardless, without every caller needing to reason about it.
710
+ *
711
+ * Call `wireOptInFieldset` once, right after this is built into real DOM
712
+ * (e.g. inside a `jml(...)` caller, same as `objectSearchType.js`'s rows
713
+ * do), to actually connect the checkbox to the fieldset's `disabled` state -
714
+ * this function only builds the static markup (default unchecked/disabled).
715
+ * @param {{
716
+ * name: string, key?: string, label: string, children: JamilihArray[]
717
+ * }} cfg
718
+ * @returns {JamilihArray[]}
719
+ */
720
+ export function buildOptInFieldset ({name, key = '', label, children}) {
721
+ return [
722
+ ['label', {class: 'jsoeSearchOptInLabel'}, [
723
+ `${label}: `,
724
+ ['input', {type: 'checkbox', name: `${name}-optIn`, class: `jsoeSearchOptIn--${key}`}]
725
+ ]],
726
+ ['fieldset', {disabled: true, class: `jsoeSearchOptInFieldset--${key}`}, children]
727
+ ];
728
+ }
729
+
730
+ /**
731
+ * Reads back a `buildOptInFieldset`'s checkbox - pass the same `key` it was
732
+ * built with.
733
+ * @param {Element} root
734
+ * @param {string} [key]
735
+ * @returns {boolean}
736
+ */
737
+ export function readOptInChecked (root, key = '') {
738
+ return Boolean(/** @type {HTMLInputElement|undefined} */ (
739
+ findOwnControl(root, `input.jsoeSearchOptIn--${key}`)
740
+ )?.checked);
741
+ }
742
+
743
+ /**
744
+ * Connects a `buildOptInFieldset`'s checkbox to toggle its own fieldset's
745
+ * `disabled` state - call once, synchronously, right after both are live
746
+ * DOM nodes (see that function's doc). Pass the same `key` it was built
747
+ * with.
748
+ *
749
+ * `onToggle`, when given, is called after each toggle (with the checkbox as
750
+ * `this`) - `mapSearchType.js`/`recordSearchType.js`/`fileSearchType.js`
751
+ * use it to re-run their own `syncAtLeastOneCheck` whenever one of their
752
+ * (exactly two) opt-in facets changes, since checking/unchecking either one
753
+ * can change whether "at least one" is satisfied.
754
+ * @param {Element} root
755
+ * @param {string} [key]
756
+ * @param {((this: HTMLInputElement) => void)} [onToggle]
757
+ * @returns {void}
758
+ */
759
+ export function wireOptInFieldset (root, key = '', onToggle = undefined) {
760
+ const checkbox = /** @type {HTMLInputElement|undefined} */ (
761
+ findOwnControl(root, `input.jsoeSearchOptIn--${key}`)
762
+ );
763
+ const fieldset = /** @type {HTMLFieldSetElement|undefined} */ (
764
+ findOwnControl(root, `fieldset.jsoeSearchOptInFieldset--${key}`)
765
+ );
766
+ checkbox?.addEventListener('change', () => {
767
+ if (fieldset) {
768
+ fieldset.disabled = !checkbox.checked;
769
+ }
770
+ onToggle?.call(checkbox);
771
+ });
772
+ }
773
+
774
+ /**
775
+ * A visually-hidden but still-rendered (and so still constraint-validation-
776
+ * eligible - see `jsoe.css`'s `.searchAtLeastOneSentinel`, the same
777
+ * "visually-hidden" pattern used for accessibility, which keeps an element
778
+ * off-screen without `display: none`/`hidden` triggering the Constraint
779
+ * Validation API's own "not rendered" exemption) sentinel control, for a
780
+ * widget with several independent optional facets where leaving *every one*
781
+ * unconfigured should be invalid even though no single facet is itself
782
+ * always required (`mapSearchType.js`/`recordSearchType.js`'s key/value,
783
+ * `fileSearchType.js`'s name/content-type). Pair with `syncAtLeastOneCheck`.
784
+ * @returns {JamilihArray}
785
+ */
786
+ export function buildAtLeastOneSentinel () {
787
+ return ['input', {
788
+ type: 'text', class: 'searchAtLeastOneSentinel', tabindex: -1,
789
+ 'aria-hidden': 'true'
790
+ }];
791
+ }
792
+
793
+ /**
794
+ * @type {WeakMap<Element, () => void>}
795
+ */
796
+ const atLeastOneResyncs = new WeakMap();
797
+
798
+ /**
799
+ * Sets a `buildAtLeastOneSentinel`'s custom validity from a live check -
800
+ * call once at `connectedCallback` time for the initial state (a freshly-
801
+ * built widget has satisfied none of its facets yet) and again whenever a
802
+ * facet that could change the answer does (an opt-in checkbox toggling, a
803
+ * recursed child's own `input`/`change`).
804
+ *
805
+ * Also relaxed, independently of `isSatisfied`, while
806
+ * `isExemptedByAncestorHasProperty` says an enclosing
807
+ * `objectSearchType.js` has-property row's own "Has"/"Doesn't have"
808
+ * already provides a complete constraint - the same relief
809
+ * `syncRangeValidity` and `dateSearchType.js`'s own range validator give
810
+ * their "at least one bound" rule, needed here too since a has-property
811
+ * row's own child could just as easily be an `array`/`map`/`file`/etc.
812
+ * whose *own* sole constraint is this same "at least one facet" sentinel
813
+ * rather than a plain `required` attribute or a range pair.
814
+ *
815
+ * Every call re-registers `isSatisfied` (keyed by `root` in a `WeakMap`, so
816
+ * it never leaks past the element's own lifetime) for `resyncAtLeastOne` to
817
+ * call later. This exists because not every "at least one" widget's own
818
+ * answer changes via a plain `input`/`change` event - `objectSearchType.js`
819
+ * itself is the reason: its sentinel changes when a row is added/removed
820
+ * (a button click, and a structural DOM change, not a value change on any
821
+ * control), which `revalidateDescendants`' blanket event-redispatch can
822
+ * never reach, unlike `array`/`map`/etc.'s own opt-in checkboxes and size
823
+ * inputs. `objectSearchType.js`'s `buildHasPropertyRow` calls
824
+ * `resyncAtLeastOne` directly instead, precisely because it can't rely on
825
+ * redispatched events reaching every possible child type.
826
+ * @param {Element} root
827
+ * @param {() => boolean} isSatisfied
828
+ * @returns {void}
829
+ */
830
+ export function syncAtLeastOneCheck (root, isSatisfied) {
831
+ atLeastOneResyncs.set(root, () => syncAtLeastOneCheck(root, isSatisfied));
832
+ const sentinel = /** @type {HTMLInputElement|undefined} */ (
833
+ findOwnControl(root, 'input.searchAtLeastOneSentinel')
834
+ );
835
+ sentinel?.setCustomValidity(
836
+ isSatisfied() || isExemptedByAncestorHasProperty(root)
837
+ ? ''
838
+ : 'Configure at least one of this widget’s facets.'
839
+ );
840
+ }
841
+
842
+ /**
843
+ * Re-runs every `syncAtLeastOneCheck` registered anywhere within `root`
844
+ * (itself included) - see that function's doc for why this exists
845
+ * alongside `revalidateDescendants` rather than relying on it alone.
846
+ * @param {Element} root
847
+ * @returns {void}
848
+ */
849
+ export function resyncAtLeastOne (root) {
850
+ atLeastOneResyncs.get(root)?.();
851
+ [...root.querySelectorAll('[data-search-path]')].forEach((el) => {
852
+ atLeastOneResyncs.get(el)?.();
853
+ });
854
+ }
855
+
856
+ /**
857
+ * Toggles the native `required` attribute on every originally-`required`
858
+ * control inside `root`, leaving everything else (visibility, `disabled`)
859
+ * alone - unlike `buildOptInFieldset`'s `<fieldset disabled>`, this keeps
860
+ * the whole subtree fully interactive, for a case where an ancestor's own
861
+ * choice already provides a complete constraint on its own, but should
862
+ * still let the recursed child *optionally* add a further constraint on
863
+ * top rather than blocking interaction with it entirely.
864
+ * `objectSearchType.js`'s `buildHasPropertyRow` uses this for its "Has"/
865
+ * "Doesn't have" tri-state: once existence is explicitly asserted either
866
+ * way, the child's own required inputs (whatever type it turns out to be)
867
+ * should stop forcing it to be filled in, while a user who still wants to
868
+ * combine "Has property X" with "X matches Y" can keep typing into it -
869
+ * `dateSearchType.js`'s "Valid"/"Invalid date" tri-state needs the
870
+ * equivalent relaxation for its own (structurally different, so not built
871
+ * through this helper) range pair.
872
+ *
873
+ * Relaxing (`required: false`) marks each control it touches with
874
+ * `data-jsoe-was-required` before clearing the IDL `required` property -
875
+ * setting that property to `false` reflects back to *removing* the
876
+ * `required` content attribute entirely (standard boolean-attribute
877
+ * reflection), so a later call to restore it can't rely on `[required]`
878
+ * still matching that element; it looks for the marker instead.
879
+ *
880
+ * Skips any control inside a `buildOptInFieldset` fieldset
881
+ * (`jsoeSearchOptInFieldset--*`): that facet already has its own gate on
882
+ * whether it applies at all (the checkbox's `disabled` toggle exempts it
883
+ * from constraint validation while unchecked), so an enclosing "Has
884
+ * property" shouldn't also strip its `required` - a user who explicitly
885
+ * opts into e.g. `fileSearchType.js`'s "Name" facet under a "Has property"
886
+ * ancestor still needs to fill in the Value it requires, or uncheck "Name"
887
+ * again; only the widget's own `buildAtLeastOneSentinel` (which *is*
888
+ * exempted, via `isExemptedByAncestorHasProperty`) should be satisfied by
889
+ * "Has property" alone.
890
+ * @param {Element} root
891
+ * @param {boolean} required
892
+ * @returns {void}
893
+ */
894
+ export function setDescendantsRequired (root, required) {
895
+ const selector = required ? '[data-jsoe-was-required]' : '[required]';
896
+ [...root.querySelectorAll(selector)].forEach((el) => {
897
+ if (el.closest('fieldset[class^="jsoeSearchOptInFieldset--"]')) {
898
+ return;
899
+ }
900
+ if (!required) {
901
+ /** @type {HTMLElement} */ (el).dataset.jsoeWasRequired = 'true';
902
+ }
903
+ /** @type {HTMLInputElement|HTMLSelectElement|HTMLTextAreaElement} */ (
904
+ el
905
+ ).required = required;
906
+ });
907
+ }