viewkitjs 0.24.0 → 0.25.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 (82) hide show
  1. package/CHANGELOG.md +20 -0
  2. package/fields/dist/creatable.d.ts +9 -5
  3. package/fields/dist/creatable.js +8 -1
  4. package/fields/dist/messages.d.ts +19 -1
  5. package/fields/dist/messages.js +75 -0
  6. package/fields/dist/registry.js +4 -7
  7. package/fields/dist/types.d.ts +4 -2
  8. package/fields/dist/zod.d.ts +58 -0
  9. package/fields/dist/zod.js +430 -2
  10. package/fields/docs/guides/checking-definitions.md +6 -1
  11. package/fields/docs/guides/field-types.md +5 -1
  12. package/fields/docs/reference/definitions.md +1 -2
  13. package/fields/docs/reference/types.md +2 -1
  14. package/fields/skills/viewkit/SKILL.md +2 -2
  15. package/package.json +1 -1
  16. package/views/dist/controls/avatar/avatar.d.ts +58 -0
  17. package/views/dist/controls/avatar/avatar.js +54 -0
  18. package/views/dist/controls/avatar/looks.d.ts +4 -0
  19. package/views/dist/controls/avatar/looks.js +5 -0
  20. package/views/dist/controls/avatar/tokens.d.ts +131 -0
  21. package/views/dist/controls/avatar/tokens.js +35 -0
  22. package/views/dist/controls/avatar.css +163 -0
  23. package/views/dist/controls/controls.d.ts +2 -0
  24. package/views/dist/controls/controls.js +2 -0
  25. package/views/dist/controls/index.d.ts +12 -0
  26. package/views/dist/controls/index.js +12 -0
  27. package/views/dist/controls/internal/phone.d.ts +9 -0
  28. package/views/dist/controls/internal/phone.js +15 -0
  29. package/views/dist/controls/internal/read-token.d.ts +2 -1
  30. package/views/dist/controls/internal/read-token.js +1 -1
  31. package/views/dist/controls/internal/scroll.d.ts +38 -0
  32. package/views/dist/controls/internal/scroll.js +126 -0
  33. package/views/dist/controls/list/looks.d.ts +4 -0
  34. package/views/dist/controls/list/looks.js +12 -0
  35. package/views/dist/controls/list.css +17 -13
  36. package/views/dist/controls/menu/map-menu.d.ts +11 -0
  37. package/views/dist/controls/menu/map-menu.js +47 -0
  38. package/views/dist/controls/menu/menu.d.ts +75 -0
  39. package/views/dist/controls/menu/menu.js +105 -0
  40. package/views/dist/controls/menu/tokens.d.ts +23 -0
  41. package/views/dist/controls/menu/tokens.js +8 -0
  42. package/views/dist/controls/menu-list/looks.d.ts +5 -1
  43. package/views/dist/controls/menu-list/looks.js +6 -4
  44. package/views/dist/controls/menu-list/menu-list.js +3 -1
  45. package/views/dist/controls/menu-list.css +39 -31
  46. package/views/dist/controls/menu.css +25 -0
  47. package/views/dist/controls/picker/looks.d.ts +19 -0
  48. package/views/dist/controls/picker/looks.js +32 -0
  49. package/views/dist/controls/picker/picker.d.ts +153 -0
  50. package/views/dist/controls/picker/picker.js +773 -0
  51. package/views/dist/controls/picker/rows.d.ts +129 -0
  52. package/views/dist/controls/picker/rows.js +90 -0
  53. package/views/dist/controls/picker/tokens.d.ts +147 -0
  54. package/views/dist/controls/picker/tokens.js +39 -0
  55. package/views/dist/controls/picker.css +237 -0
  56. package/views/dist/controls/popup-line/tokens.d.ts +23 -0
  57. package/views/dist/controls/popup-line/tokens.js +8 -0
  58. package/views/dist/controls/popup-line.css +44 -0
  59. package/views/dist/controls/select/filled.d.ts +7 -0
  60. package/views/dist/controls/select/filled.js +5 -0
  61. package/views/dist/controls/select/fit.d.ts +9 -0
  62. package/views/dist/controls/select/fit.js +11 -0
  63. package/views/dist/controls/select/select.d.ts +131 -0
  64. package/views/dist/controls/select/select.js +227 -0
  65. package/views/dist/controls/select/side.d.ts +3 -0
  66. package/views/dist/controls/select/side.js +4 -0
  67. package/views/dist/controls/select/tokens.d.ts +27 -0
  68. package/views/dist/controls/select/tokens.js +9 -0
  69. package/views/dist/controls/select.css +91 -0
  70. package/views/dist/controls/tokens.js +10 -0
  71. package/views/dist/looks/index.d.ts +4 -0
  72. package/views/dist/looks/index.js +4 -0
  73. package/views/dist/looks/pieces.js +6 -0
  74. package/views/dist/styles.css +586 -62
  75. package/views/dist/styles.unlayered.css +586 -62
  76. package/views/docs/controls/avatar.md +38 -0
  77. package/views/docs/controls/menu.md +11 -0
  78. package/views/docs/controls/picker.md +42 -0
  79. package/views/docs/controls/popup-line.md +11 -0
  80. package/views/docs/controls/select.md +12 -0
  81. package/views/docs/reference/controls.md +86 -0
  82. package/views/docs/reference/looks.md +8 -0
@@ -5,6 +5,7 @@ import { isCleanDomain } from "./domain.js";
5
5
  import { LOCATION_PARTS } from "./location.js";
6
6
  import { relationKinds, storesRelationRef } from "./relation.js";
7
7
  import { DEFAULT_CONVENTIONS, conventionsOr } from "./conventions.js";
8
+ import { FieldDefinitionError } from "./errors.js";
8
9
  import { optionValues } from "./options.js";
9
10
  import { isPhoneValue, readPhone } from "./phone.js";
10
11
  import { compareDecimalText, decimalFractionDigits, decimalTextOf, isDecimalText, } from "./parse-number.js";
@@ -147,8 +148,15 @@ function build(field, cv, say, kept = NO_KEPT) {
147
148
  error: () => say({ key: "validation.max-length", values: { max } }),
148
149
  });
149
150
  }
150
- if (v?.pattern)
151
- s = s.regex(new RegExp(v.pattern), { error: () => say({ key: "validation.pattern" }) });
151
+ if (v?.pattern) {
152
+ const read = readPattern(v.pattern);
153
+ if (!read.ok)
154
+ throw new FieldDefinitionError(field.key, `pattern ${read.why}`);
155
+ const limit = read.pattern.maxValueLength;
156
+ if (v.maxLength === undefined || v.maxLength > limit)
157
+ s = s.max(limit, { error: () => say({ key: "validation.max-length", values: { max: limit } }) });
158
+ s = s.regex(read.pattern, { error: () => say({ key: "validation.pattern" }) });
159
+ }
152
160
  return s;
153
161
  }
154
162
  case "number":
@@ -417,3 +425,423 @@ function build(field, cv, say, kept = NO_KEPT) {
417
425
  }
418
426
  }
419
427
  }
428
+ export const PATTERN_MAX_LENGTH = 500;
429
+ export const PATTERN_MAX_STEPS = 1000;
430
+ export const PATTERN_MAX_WORK = 20_000_000;
431
+ const CHAR = 0;
432
+ const SPLIT = 1;
433
+ const JUMP = 2;
434
+ const ASSERT = 3;
435
+ const MATCH = 4;
436
+ class Refusal extends Error {
437
+ }
438
+ const MAX_UNIT = 0xffff;
439
+ function rangesOf(pairs) {
440
+ const sorted = [];
441
+ for (let i = 0; i < pairs.length; i += 2)
442
+ sorted.push([pairs[i], pairs[i + 1]]);
443
+ sorted.sort((a, b) => a[0] - b[0]);
444
+ const merged = [];
445
+ for (const [low, high] of sorted) {
446
+ const last = merged.length - 1;
447
+ if (last > 0 && low <= merged[last] + 1)
448
+ merged[last] = Math.max(merged[last], high);
449
+ else
450
+ merged.push(low, high);
451
+ }
452
+ return Int32Array.from(merged);
453
+ }
454
+ function complement(set) {
455
+ const out = [];
456
+ let next = 0;
457
+ for (let i = 0; i < set.length; i += 2) {
458
+ if (set[i] > next)
459
+ out.push(next, set[i] - 1);
460
+ next = set[i + 1] + 1;
461
+ }
462
+ if (next <= MAX_UNIT)
463
+ out.push(next, MAX_UNIT);
464
+ return Int32Array.from(out);
465
+ }
466
+ function contains(set, code) {
467
+ let low = 0;
468
+ let high = set.length / 2 - 1;
469
+ while (low <= high) {
470
+ const mid = (low + high) >> 1;
471
+ if (code < set[2 * mid])
472
+ high = mid - 1;
473
+ else if (code > set[2 * mid + 1])
474
+ low = mid + 1;
475
+ else
476
+ return true;
477
+ }
478
+ return false;
479
+ }
480
+ const DIGIT = rangesOf([0x30, 0x39]);
481
+ const WORD = rangesOf([0x30, 0x39, 0x41, 0x5a, 0x5f, 0x5f, 0x61, 0x7a]);
482
+ const SPACE = rangesOf([
483
+ 0x09, 0x0d, 0x20, 0x20, 0xa0, 0xa0, 0x1680, 0x1680, 0x2000, 0x200a, 0x2028, 0x2029, 0x202f, 0x202f, 0x205f,
484
+ 0x205f, 0x3000, 0x3000, 0xfeff, 0xfeff,
485
+ ]);
486
+ const ANY_BUT_LINE_END = complement(rangesOf([0x0a, 0x0a, 0x0d, 0x0d, 0x2028, 0x2029]));
487
+ const SETS = {
488
+ d: DIGIT,
489
+ D: complement(DIGIT),
490
+ w: WORD,
491
+ W: complement(WORD),
492
+ s: SPACE,
493
+ S: complement(SPACE),
494
+ };
495
+ const CONTROLS = { t: 0x09, n: 0x0a, v: 0x0b, f: 0x0c, r: 0x0d };
496
+ const SYMBOL = /^[\x20-\x2f\x3a-\x40\x5b-\x60\x7b-\x7e]$/;
497
+ const BACKTRACKS = "which a field's pattern can't: it would have to backtrack";
498
+ const QUANTIFIER = /^\{(\d+)(?:(,)(\d*))?\}/;
499
+ class Parser {
500
+ s;
501
+ i = 0;
502
+ constructor(s) {
503
+ this.s = s;
504
+ }
505
+ alternation() {
506
+ const items = [this.sequence()];
507
+ while (this.s[this.i] === "|") {
508
+ this.i += 1;
509
+ items.push(this.sequence());
510
+ }
511
+ return items.length === 1 ? items[0] : { t: "alt", items };
512
+ }
513
+ sequence() {
514
+ const items = [];
515
+ while (this.i < this.s.length && this.s[this.i] !== "|" && this.s[this.i] !== ")") {
516
+ const [node, quantifiable] = this.atom();
517
+ items.push(quantifiable ? this.quantified(node) : node);
518
+ }
519
+ return { t: "cat", items };
520
+ }
521
+ quantified(node) {
522
+ const c = this.s[this.i];
523
+ let min;
524
+ let max;
525
+ if (c === "*" || c === "+" || c === "?") {
526
+ this.i += 1;
527
+ min = c === "+" ? 1 : 0;
528
+ max = c === "?" ? 1 : Infinity;
529
+ }
530
+ else if (c === "{") {
531
+ const m = QUANTIFIER.exec(this.s.slice(this.i));
532
+ if (!m)
533
+ throw new Refusal(`has a lone "{": write \\{ for the character`);
534
+ this.i += m[0].length;
535
+ min = Number(m[1]);
536
+ max = m[2] === undefined ? min : m[3] === "" ? Infinity : Number(m[3]);
537
+ }
538
+ else
539
+ return node;
540
+ if (this.s[this.i] === "?")
541
+ this.i += 1;
542
+ return { t: "repeat", node, min, max };
543
+ }
544
+ atom() {
545
+ const s = this.s;
546
+ const c = s[this.i];
547
+ switch (c) {
548
+ case "^":
549
+ this.i += 1;
550
+ return [{ t: "assert", a: "start" }, false];
551
+ case "$":
552
+ this.i += 1;
553
+ return [{ t: "assert", a: "end" }, false];
554
+ case ".":
555
+ this.i += 1;
556
+ return [{ t: "char", set: ANY_BUT_LINE_END }, true];
557
+ case "(": {
558
+ if (s.startsWith("(?=", this.i) || s.startsWith("(?!", this.i) || s.startsWith("(?<=", this.i) || s.startsWith("(?<!", this.i))
559
+ throw new Refusal(`looks ahead or behind, ${BACKTRACKS}`);
560
+ if (s.startsWith("(?:", this.i))
561
+ this.i += 3;
562
+ else if (s.startsWith("(?<", this.i))
563
+ this.i = s.indexOf(">", this.i) + 1;
564
+ else if (s.startsWith("(?", this.i))
565
+ throw new Refusal("sets flags inside a group, which a field's pattern can't");
566
+ else
567
+ this.i += 1;
568
+ const inner = this.alternation();
569
+ this.i += 1;
570
+ return [inner, true];
571
+ }
572
+ case "[":
573
+ return [this.charClass(), true];
574
+ case "\\":
575
+ return this.escape();
576
+ case "{":
577
+ case "}":
578
+ case "]":
579
+ throw new Refusal(`has a lone "${c}": write \\${c} for the character`);
580
+ default:
581
+ this.i += 1;
582
+ return [literal(c.charCodeAt(0)), true];
583
+ }
584
+ }
585
+ escape() {
586
+ const e = this.s[this.i + 1];
587
+ if (e === "b" || e === "B") {
588
+ this.i += 2;
589
+ return [{ t: "assert", a: e === "b" ? "word" : "not-word" }, false];
590
+ }
591
+ if ((e >= "1" && e <= "9") || e === "k")
592
+ throw new Refusal(`refers back to a group, ${BACKTRACKS}`);
593
+ const one = this.escapedChar(false);
594
+ return [typeof one === "number" ? literal(one) : { t: "char", set: one }, true];
595
+ }
596
+ escapedChar(inClass) {
597
+ const s = this.s;
598
+ const e = s[this.i + 1];
599
+ const unknown = () => new Refusal(`uses \\${e}, which a field's pattern doesn't know`);
600
+ const set = SETS[e];
601
+ if (set) {
602
+ this.i += 2;
603
+ return set;
604
+ }
605
+ if (e in CONTROLS) {
606
+ this.i += 2;
607
+ return CONTROLS[e];
608
+ }
609
+ if (inClass && e === "b") {
610
+ this.i += 2;
611
+ return 0x08;
612
+ }
613
+ if (e === "0") {
614
+ if (/[0-9]/.test(s[this.i + 2] ?? ""))
615
+ throw unknown();
616
+ this.i += 2;
617
+ return 0;
618
+ }
619
+ if (e === "x" || e === "u") {
620
+ const digits = e === "x" ? 2 : 4;
621
+ const hex = s.slice(this.i + 2, this.i + 2 + digits);
622
+ if (hex.length !== digits || !/^[0-9a-fA-F]+$/.test(hex))
623
+ throw unknown();
624
+ this.i += 2 + digits;
625
+ return parseInt(hex, 16);
626
+ }
627
+ if (SYMBOL.test(e)) {
628
+ this.i += 2;
629
+ return e.charCodeAt(0);
630
+ }
631
+ throw unknown();
632
+ }
633
+ charClass() {
634
+ const s = this.s;
635
+ this.i += 1;
636
+ const negate = s[this.i] === "^";
637
+ if (negate)
638
+ this.i += 1;
639
+ const pairs = [];
640
+ const item = () => {
641
+ if (s[this.i] === "\\")
642
+ return this.escapedChar(true);
643
+ const code = s.charCodeAt(this.i);
644
+ this.i += 1;
645
+ return code;
646
+ };
647
+ while (s[this.i] !== "]") {
648
+ const low = item();
649
+ if (s[this.i] === "-" && s[this.i + 1] !== "]") {
650
+ this.i += 1;
651
+ const high = item();
652
+ if (typeof low !== "number" || typeof high !== "number")
653
+ throw new Refusal("has a range that starts or ends with a set: write - first or last for the character");
654
+ pairs.push(low, high);
655
+ }
656
+ else if (typeof low === "number")
657
+ pairs.push(low, low);
658
+ else
659
+ pairs.push(...low);
660
+ }
661
+ this.i += 1;
662
+ const set = rangesOf(pairs);
663
+ return { t: "char", set: negate ? complement(set) : set };
664
+ }
665
+ }
666
+ function literal(code) {
667
+ return { t: "char", set: Int32Array.of(code, code) };
668
+ }
669
+ function isEmpty(node) {
670
+ switch (node.t) {
671
+ case "cat":
672
+ return node.items.every(isEmpty);
673
+ case "repeat":
674
+ return node.max === 0 || isEmpty(node.node);
675
+ default:
676
+ return false;
677
+ }
678
+ }
679
+ function compile(root) {
680
+ const program = [];
681
+ const push = (step) => {
682
+ if (program.length >= PATTERN_MAX_STEPS)
683
+ throw new Refusal(`grows past ${PATTERN_MAX_STEPS} steps once its repeats are counted out: repeat less`);
684
+ program.push(step);
685
+ return program.length - 1;
686
+ };
687
+ const emit = (node) => {
688
+ switch (node.t) {
689
+ case "char":
690
+ push({ op: CHAR, set: node.set });
691
+ return;
692
+ case "assert":
693
+ push({ op: ASSERT, a: node.a });
694
+ return;
695
+ case "cat":
696
+ for (const item of node.items)
697
+ emit(item);
698
+ return;
699
+ case "alt": {
700
+ const jumps = [];
701
+ node.items.forEach((item, k) => {
702
+ if (k < node.items.length - 1) {
703
+ const split = push({ op: SPLIT, x: 0, y: 0 });
704
+ emit(item);
705
+ jumps.push(push({ op: JUMP, x: 0 }));
706
+ program[split] = { op: SPLIT, x: split + 1, y: program.length };
707
+ }
708
+ else
709
+ emit(item);
710
+ });
711
+ for (const j of jumps)
712
+ program[j] = { op: JUMP, x: program.length };
713
+ return;
714
+ }
715
+ case "repeat": {
716
+ if (isEmpty(node.node))
717
+ return;
718
+ for (let k = 0; k < node.min; k += 1)
719
+ emit(node.node);
720
+ if (node.max === Infinity) {
721
+ const split = push({ op: SPLIT, x: 0, y: 0 });
722
+ emit(node.node);
723
+ push({ op: JUMP, x: split });
724
+ program[split] = { op: SPLIT, x: split + 1, y: program.length };
725
+ }
726
+ else {
727
+ for (let k = node.min; k < node.max; k += 1) {
728
+ const split = push({ op: SPLIT, x: 0, y: 0 });
729
+ emit(node.node);
730
+ program[split] = { op: SPLIT, x: split + 1, y: program.length };
731
+ }
732
+ }
733
+ return;
734
+ }
735
+ }
736
+ };
737
+ emit(root);
738
+ push({ op: MATCH });
739
+ return program;
740
+ }
741
+ function run(program, value) {
742
+ const size = program.length;
743
+ const n = value.length;
744
+ let current = new Int32Array(size);
745
+ let next = new Int32Array(size);
746
+ let currentCount = 0;
747
+ let nextCount = 0;
748
+ const seen = new Uint32Array(size);
749
+ const stack = new Int32Array(size * 2 + 2);
750
+ let generation = 1;
751
+ let matched = false;
752
+ const isWord = (at) => at >= 0 && at < n && contains(WORD, value.charCodeAt(at));
753
+ const add = (into, count, pc, pos) => {
754
+ let top = 0;
755
+ stack[top++] = pc;
756
+ while (top > 0) {
757
+ const at = stack[--top];
758
+ if (seen[at] === generation)
759
+ continue;
760
+ seen[at] = generation;
761
+ const step = program[at];
762
+ switch (step.op) {
763
+ case CHAR:
764
+ into[count++] = at;
765
+ break;
766
+ case JUMP:
767
+ stack[top++] = step.x;
768
+ break;
769
+ case SPLIT:
770
+ stack[top++] = step.y;
771
+ stack[top++] = step.x;
772
+ break;
773
+ case ASSERT: {
774
+ const holds = step.a === "start"
775
+ ? pos === 0
776
+ : step.a === "end"
777
+ ? pos === n
778
+ : (isWord(pos - 1) !== isWord(pos)) === (step.a === "word");
779
+ if (holds)
780
+ stack[top++] = at + 1;
781
+ break;
782
+ }
783
+ case MATCH:
784
+ matched = true;
785
+ break;
786
+ }
787
+ }
788
+ return count;
789
+ };
790
+ for (let pos = 0;; pos += 1) {
791
+ currentCount = add(current, currentCount, 0, pos);
792
+ if (matched)
793
+ return true;
794
+ if (pos === n)
795
+ return false;
796
+ const code = value.charCodeAt(pos);
797
+ generation += 1;
798
+ nextCount = 0;
799
+ for (let k = 0; k < currentCount; k += 1) {
800
+ const at = current[k];
801
+ const step = program[at];
802
+ if (contains(step.set, code))
803
+ nextCount = add(next, nextCount, at + 1, pos + 1);
804
+ }
805
+ if (matched)
806
+ return true;
807
+ const done = current;
808
+ current = next;
809
+ next = done;
810
+ currentCount = nextCount;
811
+ }
812
+ }
813
+ export class BoundedPattern extends RegExp {
814
+ #program;
815
+ maxValueLength;
816
+ constructor(source, program) {
817
+ super(source);
818
+ this.#program = program;
819
+ this.maxValueLength = Math.floor(PATTERN_MAX_WORK / program.length);
820
+ }
821
+ static get [Symbol.species]() {
822
+ return RegExp;
823
+ }
824
+ test(value) {
825
+ const text = String(value);
826
+ return text.length <= this.maxValueLength && run(this.#program, text);
827
+ }
828
+ }
829
+ export function readPattern(source) {
830
+ try {
831
+ new RegExp(source);
832
+ }
833
+ catch {
834
+ return { ok: false, why: "is not a valid regular expression" };
835
+ }
836
+ if (source.length > PATTERN_MAX_LENGTH)
837
+ return { ok: false, why: `is longer than ${PATTERN_MAX_LENGTH} characters` };
838
+ try {
839
+ const program = compile(new Parser(source).alternation());
840
+ return { ok: true, pattern: new BoundedPattern(source, program) };
841
+ }
842
+ catch (error) {
843
+ if (error instanceof Refusal)
844
+ return { ok: false, why: error.message };
845
+ throw error;
846
+ }
847
+ }
@@ -193,7 +193,7 @@ assert.throws(
193
193
 
194
194
  ### Values of other types
195
195
 
196
- - A text, a URL, a place, a name or rich text states a `minLength` of at least 0, a `maxLength` of at least 1, the first not above the second, and a `pattern` that compiles. An `emptiable` field states no `minLength` above 0.
196
+ - A text, a URL, a place, a name or rich text states a `minLength` of at least 0, a `maxLength` of at least 1 and the first not above the second, and a text a `pattern` in ViewKit's pattern dialect (see [Field types](field-types.md#text)). An `emptiable` field states no `minLength` above 0.
197
197
  - A phone and a domain take no validation of their own: the phone library and the domain rule are the whole check. Several of them may say how many, and nothing else.
198
198
  - Only an email, a phone, a URL or a domain holds several values. `multiple` is `true` or absent, and `validation.maxItems` sits only beside it, as a whole number of at least 1.
199
199
  - A place limited to some of its `parts` names at least one, each a real part and once, and names `countryCode` beside `regionCode`.
@@ -216,6 +216,11 @@ assert.throws(
216
216
  /pattern is not a valid regular expression/
217
217
  );
218
218
 
219
+ assert.throws(
220
+ () => checkFieldSpec("code", { type: "text", label: "Code", validation: { pattern: "(\\w)\\1" } }),
221
+ /pattern refers back to a group/
222
+ );
223
+
219
224
  assert.throws(
220
225
  () => checkFieldSpec("salary", { type: "range", of: "currency", label: "Salary" }),
221
226
  /an amount range names its currency/
@@ -77,6 +77,8 @@ assert.equal(fieldTypeLabel("rich_text"), "Long text");
77
77
 
78
78
  A `text` stores a string. Its validation is `minLength`, `maxLength` and `pattern`, a regular expression source; a pattern that does not compile fails the definition. `format: { long: true }` marks text written over several lines, such as a summary, so a surface edits it in a box larger than one line.
79
79
 
80
+ A pattern may arrive as data, typed in by a person or an agent, and every value saved to the field is tested against it, so ViewKit reads it in its own dialect and matches it without backtracking: each character of a value costs at most one pass over the pattern's steps, so a value costs time in proportion to its length, never the exponential blow-up of a backtracking engine. A value may cost at most 20,000,000 steps in all (its characters times the pattern's steps), about a fifth of a second, so a value too long for its pattern is refused as too long before the pattern reads it: up to a cap-sized pattern of 1,000 steps that is 20,000 characters, and far more for a short one. State a `maxLength` beside a pattern to say the limit yourself. The dialect is JavaScript's regular-expression syntax with no flags, and it answers as `RegExp` does, without lookahead or lookbehind and without backreferences (both need backtracking), without group flags such as `(?i:…)`, and without the legacy forms whose meaning depends on where they sit: write `\{`, `\}` and `\]` for those characters. Its escapes are `\d \w \s \b`, their capitals, `\t \n \r \f \v \0 \xHH \uHHHH` and any escaped ASCII symbol (`\.`, `\@`, `\-`); an escaped letter or digit it doesn't know is refused. A pattern is at most 500 characters and 1,000 steps once its repeats are counted out (`a{3}` is three). `checkFieldSpec`, and so `defineFields`, refuse a pattern outside it, and `zodFor` refuses it in the same words.
81
+
80
82
  ```ts
81
83
  const TASK_FIELDS = defineFields({
82
84
  entity: "task",
@@ -649,7 +651,7 @@ assert.equal(zodFor(MARGIN_FIELDS.margin).safeParse(10).success, false);
649
651
 
650
652
  An app that lets a person make a field builds its New field dialog from `creatableFieldTypes()`, from `viewkitjs/fields/definitions`: the twenty types a person may create, in the dialog's order. It never lists the actor, which the system sets, nor a lookup, rollup or formula, which are worked out from other fields. Each entry carries the type's `label` in the host's words, its `icon` (the type's own key, the glyph name a renderer draws it by), whether it may hold several values (`several`), its `settings` as data and the `spec` a new field of it starts as, which `checkFieldSpec` accepts as it stands.
651
653
 
652
- A setting names where it sits in a definition (`path`, dotted), its `kind` (`switch`, `word`, `words`, `number`, `text`, `currency`, `options`, `entity` or `value`) and, for a word, its allowed `words`. A `when` says it applies only while another setting holds a word; a `required` setting holds a value whenever it applies, starting from its `start`. A switch that is off is written by removing its key, never as `false`. A setting whose `when` stops holding is removed, and so is a block it leaves empty (`validation`, `format`, `code`): `checkFieldSpec` refuses the leftovers, such as a currency code on a range of numbers. A relation starts with no kind; the app sets one before it saves. An app leaves a type or a setting out by filtering the list; it never writes its own copy.
654
+ A setting names where it sits in a definition (`path`, dotted), its `label` in the host's words, its `kind` (`switch`, `word`, `words`, `number`, `text`, `currency`, `options`, `entity` or `value`) and, for a word, its allowed `words` and `wordLabels`, a name for each in the host's words. Both names are messages, `setting.label` ("Decimals shown") and `setting.word` ("Up is good"), each carrying the type and the path, so a host renames them in its own language as it renames a type's label. A `when` says it applies only while another setting holds a word; a `required` setting holds a value whenever it applies, starting from its `start`. A switch that is off is written by removing its key, never as `false`. A setting whose `when` stops holding is removed, and so is a block it leaves empty (`validation`, `format`, `code`): `checkFieldSpec` refuses the leftovers, such as a currency code on a range of numbers. A relation starts with no kind; the app sets one before it saves. An app leaves a type or a setting out by filtering the list; it never writes its own copy.
653
655
 
654
656
  ```ts
655
657
  import { creatableFieldTypes } from "viewkitjs/fields/definitions";
@@ -659,6 +661,8 @@ const status = creatableFieldTypes().find((entry) => entry.type === "status")!;
659
661
  assert.equal(status.label, "Status");
660
662
  assert.equal(status.icon, "status");
661
663
  assert.ok(status.settings.some((setting) => setting.path === "options"));
664
+ const number = creatableFieldTypes().find((entry) => entry.type === "number")!;
665
+ assert.equal(number.settings.find((setting) => setting.path === "format.decimals")!.label, "Decimals shown");
662
666
  checkFieldSpec("stage", status.spec);
663
667
  // A spec built from the list is data, as a row's is.
664
668
  checkFieldSpec("stage", { ...status.spec, options: [{ value: "new", label: "New", slot: "pending" }] } as FieldSpec);
@@ -6,11 +6,10 @@ This entry is for an app that lets a person make and change fields: the types a
6
6
 
7
7
  Guide: [field types](../guides/field-types.md).
8
8
 
9
- - `CreatableFieldType` — a type a person may create: every field type but `actor`, `lookup`, `rollup` and `formula`.
10
9
  - `CREATABLE_FIELD_TYPES` — the twenty types a person may create, in New field's order.
11
10
  - `creatableFieldTypes` — every type a person may create, each with its label in the host's words, its glyph's name, whether it may hold several values, its settings as data and the definition a new field of it starts as.
12
11
  - `FieldTypeEntry` — one type in that list: `type`, `label`, `icon`, `several`, `settings` and `spec`.
13
- - `FieldTypeSetting` — one setting a definition of a type takes: its dotted `path`, its `kind`, its allowed words or bounds, and whether it is `required`, what it `start`s as and `when` it applies. A switch that is off is written by removing its key.
12
+ - `FieldTypeSetting` — one setting a definition of a type takes: its dotted `path`, its `label` in the host's words (the message `setting.label`), its `kind`, its allowed words with `wordLabels` naming each (the message `setting.word`) or its bounds, and whether it is `required`, what it `start`s as and `when` it applies. A switch that is off is written by removing its key.
14
13
  - `FieldSettingWhen` — the setting a setting applies under, and the word or switch it must hold.
15
14
 
16
15
  ## When a definition changes
@@ -5,6 +5,7 @@ Import from `viewkitjs/fields/types` only for module augmentation: narrowing the
5
5
  ## Field types and definitions
6
6
 
7
7
  - `FieldType` — the twenty-four type names a field can have: `text`, `number`, `percent`, `currency`, `date`, `datetime`, `boolean`, `select`, `status`, `multiselect`, `relation`, `user`, `url`, `domain`, `email`, `phone`, `location`, `name`, `actor`, `rich_text`, `range`, `lookup`, `rollup` and `formula`. A `date` is a calendar day (`YYYY-MM-DD`, no zone); a `datetime` is an instant. A `percent` is stored from 0 to 100, so the value is the percent itself.
8
+ - `CreatableFieldType` — a type a person may create: every field type but `actor`, `lookup`, `rollup` and `formula`; the twenty `creatableFieldTypes` lists.
8
9
  - `FieldDef` — a field as a registry holds it: a union over the field types, each member carrying the shared base (`key`, `label`, `description`, `required`, `nullable`, `emptiable`, `unique`, `edit` and `provenance`) beside the members of its own type.
9
10
  - `FieldDefOf` — the member of `FieldDef` for one field type, picked by that type's name.
10
11
  - `FieldSpec` — a `FieldDef` without the keys the library stamps itself (`key`, `identity`, `subtitle`, `subtitleThrough`, `subtitleTargets`, `rename` and `entity`). It is what you write for a field.
@@ -14,7 +15,7 @@ Import from `viewkitjs/fields/types` only for module augmentation: narrowing the
14
15
 
15
16
  ## Specs of the simple types
16
17
 
17
- - `TextualValidation` — what a text-like value may be held to: a `maxLength`, and a `pattern` that is a regular expression source. `checkFieldSpec` refuses a pattern that does not compile.
18
+ - `TextualValidation` — what a text-like value may be held to: a `maxLength`, and a `pattern` that is a regular expression source. `checkFieldSpec` and `zodFor` refuse a pattern outside ViewKit's dialect, which is matched without backtracking.
18
19
  - `TextSpec` — the spec of a `text` field: optional validation (`minLength` as well) and a `long` format flag.
19
20
  - `NumberSpec` — the spec of a `number` field: its storage, its validation and its number format.
20
21
  - `PercentSpec` — the spec of a `percent` field: its storage, its validation (with `reason`, why its bounds leave 0–100, required then) and its percent format.
@@ -94,7 +94,7 @@ Four more field types, and growth in the relation, the rollup and the formula. E
94
94
 
95
95
  **A list's settings and its hold.** Two Zod schemas, from `/query`, are the one shape a browser, a server and an agent read a list's settings and its quick-filter hold by, so check what comes in by them before anything else reads it (`safeParse`, then `readListSettings` for the settings). `listSettingsSchema` checks a list's settings: its sorts, its filter tree, its group, its columns, its look and `showCounts`. It checks shape, not fields, and refuses an unknown key at any level, a fourth sort, a field sorted twice, a filter deeper than 3 levels and an operator ViewKit has no word for, each with its reason. `listHoldSchema` checks a hold (`ListHold`, a list of `{ fieldKey, values }`): it refuses anything but a list, an empty key, a field held twice and a value that isn't text. The hold sits beside the settings, never inside them or the filter: hand it to `evaluateView` as `ViewQuery.hold`, and a database translator compiles `withHold(filter, hold, fieldOf)`, the view's filter with each held field in force written as an ordinary rule.
96
96
 
97
- **The types a person may create.** `creatableFieldTypes(conventions)`, from `viewkitjs/fields/definitions`, lists the twenty a New field dialog offers (never the actor, a lookup, a rollup or a formula), each with its `label` (`fieldTypeLabel`'s, New field's words), its `icon` (the type's key), `several`, its `settings` as data (`path`, `kind`, allowed `words`, `when`, `required`, `start`; a switch that is off is a removed key) and a starting `spec` `checkFieldSpec` accepts. Filter it; never re-type it. `FIELD_TYPES`, `STATUS_SLOTS` and `CATEGORY_COLORS` are the closed words at run time.
97
+ **The types a person may create.** `creatableFieldTypes(conventions)`, from `viewkitjs/fields/definitions`, lists the twenty a New field dialog offers (never the actor, a lookup, a rollup or a formula), each with its `label` (`fieldTypeLabel`'s, New field's words), its `icon` (the type's key), `several`, its `settings` as data (`path`, `label` in the host's words, `kind`, allowed `words` with `wordLabels` naming each, `when`, `required`, `start`; a switch that is off is a removed key; the names are the messages `setting.label` and `setting.word`, so never write your own) and a starting `spec` `checkFieldSpec` accepts. Filter it; never re-type it. `FIELD_TYPES`, `STATUS_SLOTS` and `CATEGORY_COLORS` are the closed words at run time.
98
98
 
99
99
  **A definition that arrives as data.** `checkFieldSpec` takes any value: it refuses a definition of the wrong shape (a key its type does not declare, a value of the wrong kind, a blank label, nesting past 408 levels) and every closed word it does not know, the type first, naming each. `defineFields` and `contributeFields` refuse a SQL formula unless you pass `allowSql: true`. `fieldSpecChanges(before, after)` (`viewkitjs/fields/definitions`) names every change between two definitions of one field, each with `reachesValues` (cautious: any validation change says true); allow or refuse each in your own words.
100
100
 
@@ -231,7 +231,7 @@ Use `acceptStoredFieldValue(field, value, conventions?)` after a binding has pro
231
231
 
232
232
  A field states what its value may be: `text` takes `minLength`, `maxLength` and `pattern`; `phone` takes none of its own (only `maxItems` beside `multiple`, below): it is read with Google's phone library into `{ number, extension }`, the number in its international form, in the region the commit or the conventions name, from text that is the number alone (words around it or a `tel:` link are refused, `validation.phone-whole`); `domain` takes none of its own either: a commit is cleaned by `cleanDomain` (`https://www.Acme.ro/about` → `acme.ro`, subdomains kept) and a stored domain must already be clean; `url` takes `maxLength`; `email`, `phone`, `url` and `domain` take `multiple: true`, the value then a list of `{ value, label, main }` with at most one main, and `validation.maxItems`, the most it holds — the host's binding names where the list is kept, and `valueListChanges(before, after)` maps a commit onto a host that changes its rows one at a time; `name` takes `maxLength`, the ceiling on each of its parts; `location` takes `maxLength`, the ceiling on each of its parts, and `parts`, the place's parts it takes (`["city", "region", "countryCode"]` for a person's location; every part when absent) — a place is `{ line1?, line2?, city?, region?, regionCode?, postalCode?, countryCode? }`, its `countryCode` an ISO 3166-1 code, or `XK` for Kosovo, drawn by its name and its `regionCode` an ISO 3166-2 code of that country, and `countryCodeOf(text)` reads a country you hold as a name into its code. `locationLines` and `locationText` write a place in its country's order, `placeFormat(countryCode)` gives that order with the country's words and required parts, and `viewkitjs/fields/places` loads a country's regions (`loadRegions`). A rule reads a place through `part` (`{ fieldKey: "location", part: "countryCode", operator: "is_any_of", value: ["RO"] }`; `region`, `city` and `postalCode` take text's operators), a sort through `by` (`"city"`, the default, `"region"`, `"countryCode"` or `"postalCode"`) and a group through `by` (the first three), and a place is filtered or grouped no other way; `number`, `percent` and `currency` take `min`, `max`, `gt`, `lt`, and either `integer` or `decimals` — the most fraction digits a stored value may carry, where `format.decimals` only draws. State one or the other: `integer` already governs precision. A `percent` stores 0–100 — `14` is 14%, never `0.14` — and a range past it, above 100 or below 0, states why in `validation.reason`, a sentence of its own that is never the lock text.
233
233
 
234
- A definition that promises two opposite things is refused when it is defined, not at the first write: `required` with `emptiable`, `emptiable` with a `minLength`, `minLength` above `maxLength`, a `pattern` that does not compile, a `count` rollup that names an `of`, a decimal field whose default is a number, a duration stored as decimal text, `format.bands` that are empty, do not climb or name a non-finite `min`, and bands beside a positive-good sign (both would colour the figure — `signedTone: "neutral"` keeps the sign). A band is a tone by threshold on a number or a percent: the figure wears the highest band it reaches, read as drawn.
234
+ A definition that promises two opposite things is refused when it is defined, not at the first write: `required` with `emptiable`, `emptiable` with a `minLength`, `minLength` above `maxLength`, a `pattern` outside ViewKit's dialect (JavaScript's syntax without lookaround, backreferences or group flags, at most 500 characters and 1,000 steps, matched without backtracking; `zodFor` refuses it in the same words, and refuses a value too long for its pattern to read as too long), a `count` rollup that names an `of`, a decimal field whose default is a number, a duration stored as decimal text, `format.bands` that are empty, do not climb or name a non-finite `min`, and bands beside a positive-good sign (both would colour the figure — `signedTone: "neutral"` keeps the sign). A band is a tone by threshold on a number or a percent: the figure wears the highest band it reaches, read as drawn.
235
235
 
236
236
  ### Exact decimals
237
237
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "viewkitjs",
3
- "version": "0.24.0",
3
+ "version": "0.25.0",
4
4
  "description": "ViewKit — typed fields, the grid and its editors, and a list's SQL for record lists, in one package: viewkitjs/fields, viewkitjs/views and viewkitjs/postgres. By Sheaf.",
5
5
  "license": "UNLICENSED",
6
6
  "repository": {
@@ -0,0 +1,58 @@
1
+ import * as React from "react";
2
+ export type AvatarSize = 16 | 20 | 24 | 32 | 40 | 64;
3
+ /** The initials of a name: the first letters of the first and last names; a first name of two joined
4
+ * parts gives both ("Maximiliane-Theodora von Hohenberg-Lichtenstein" is MT); one name gives one ("Jo" is J). */
5
+ export declare function initials(name: string): string;
6
+ /** A person's tone, 1 to 6, from their id: the same on every screen and in every theme. */
7
+ export declare function toneOf(id: string): number;
8
+ /** Whether a person is here now: here, a green dot; away, a hollow ring (after Slack). */
9
+ export type AvatarPresence = "here" | "away";
10
+ export interface AvatarProps {
11
+ /** Whose or what's it is: its accessible name, and where the initials come from. */
12
+ name: string;
13
+ /** People are circles on their tone; things (a company, a record) are squares; the workspace is the one brand square; an agent
14
+ * (Claude, a reply agent) is a thing's square holding its own icon: its app icon as `src`, its mark as `icon`, drawn in its own
15
+ * fills, or with neither its first letter. */
16
+ kind?: "person" | "thing" | "workspace" | "agent";
17
+ /** 16 in a chip (a typed Select's), with no badge; 20 in chips and text, 24 in dense rows and stacks, 32 in list rows,
18
+ * 40 in headers, 64 on a record's own page. */
19
+ size?: AvatarSize;
20
+ /** A stable id, for a person's tone. */
21
+ id?: string;
22
+ /** The tone itself, where the app keeps it. */
23
+ tone?: 1 | 2 | 3 | 4 | 5 | 6;
24
+ /** A photo or a logo, filling the same shape. */
25
+ src?: string;
26
+ /** A record with no name: its kind's icon instead of a letter. */
27
+ icon?: React.ReactNode;
28
+ /** Whether a person is here now: here, a green dot; away, a hollow ring; offline, leave it out. Wins over a badge. */
29
+ presence?: AvatarPresence;
30
+ /** shadcn's AvatarBadge: a dot on its corner in the brand, or one holding an icon (shown from 32 up). */
31
+ badge?: true | React.ReactNode;
32
+ className?: string;
33
+ }
34
+ /** Who or what a row is about, at a glance. */
35
+ export declare function Avatar({ name, kind, size, id, tone, src, icon, presence, badge, className }: AvatarProps): import("react/jsx-runtime").JSX.Element;
36
+ /** One person on a stack. */
37
+ export type AvatarStackPerson = Omit<AvatarProps, "size" | "kind">;
38
+ export interface AvatarStackProps {
39
+ /** Who is on it, in order. */
40
+ people: AvatarStackPerson[];
41
+ /** How many to show before the rest become a count. */
42
+ max?: number;
43
+ size?: Exclude<AvatarSize, 16>;
44
+ className?: string;
45
+ /** What everyone is on ("Acme Robotics renewal"): the list's name to a screen reader. Left out, the stack's own words. */
46
+ label?: string;
47
+ /** The whole stack is one button: pressed, it opens everyone in a list (the Menu, All rows: a popup on a computer, the Sheet
48
+ * on a phone, its card rows pinned whatever the app picks for a menu's own sheet), and the person picked there is handed here. */
49
+ onPick?: (person: AvatarStackPerson) => void;
50
+ /** Someone added: "Add someone…" at the end of the list it opens; with addButton, the dashed + after it too. */
51
+ onAdd?: () => void;
52
+ /** Where adding is the main job: a dashed + after the stack, pressing onAdd; with nobody on it, the + alone. */
53
+ addButton?: boolean;
54
+ }
55
+ /** Several people on one thing: overlapping, each cut out of whatever it stands on, the rest as a count. Its accessible name
56
+ * lists them ("Ioana Vlad, Kwame Asante, Lea Brandt and 3 more"). With onPick the whole stack is one button that opens
57
+ * everyone (after Linear); with addButton a dashed + stands after it (after Asana). */
58
+ export declare function AvatarStack({ people, max, size, className, label, onPick, onAdd, addButton }: AvatarStackProps): import("react/jsx-runtime").JSX.Element | null;