@jsenv/navi 0.29.406 → 0.29.408

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.
@@ -1,5 +1,4 @@
1
- import { getVirtualKeyboardOverlayHeight, subscribeWindowResizeSettled, subscribeVisualViewportResizeSettled, dispatchInternalCustomEvent, dispatchCustomEvent, createPubSub, findEvent, mergeOneStyle, setVirtualKeyboardOverlaysContent, subscribeVirtualKeyboardGeometryChange, scrollIntoViewThroughScrollables, setPlacementViewportInsets } from "@jsenv/dom";
2
- import { CHAR_CLASS_PRESETS } from "@jsenv/validity";
1
+ import { getVirtualKeyboardOverlayHeight, subscribeWindowResizeSettled, subscribeVisualViewportResizeSettled, setPlacementViewportInsets } from "@jsenv/dom";
3
2
  import { signal, computed, effect } from "@preact/signals";
4
3
 
5
4
  const installImportMetaCssBuild = (importMeta) => {
@@ -367,2865 +366,6 @@ const SAFE_AREA_CSS = /* css */ `@property --navi-app-inset-top {
367
366
  `;
368
367
  import.meta.css = [SAFE_AREA_CSS, "@jsenv/navi/src/layout/safe_area.js"];
369
368
 
370
- /**
371
- * DOM utilities for navigating the control element hierarchy.
372
- *
373
- * A control is a self-contained interactive widget. Its DOM structure can be
374
- * either flat (host only) or layered (wrapper + host):
375
- *
376
- * Flat — the element is both the root and the host:
377
- * ```html
378
- * <button navi-control navi-control-host>Click me</button>
379
- * ```
380
- *
381
- * Layered — a visual wrapper surrounds a native input that is the real host:
382
- * ```html
383
- * <span navi-control> ← wrapper: root of the control's DOM subtree
384
- * <input navi-control-host /> ← host: holds controlProps, value, UI state, constraints
385
- * </span>
386
- * ```
387
- *
388
- * Attribute roles:
389
- * - `navi-control` boolean, on the wrapper/root; marks the control boundary
390
- * - `navi-control-host` boolean, on the host; set automatically by `useInteractiveProps`
391
- *
392
- * See control_proxy.js for the `navi-control-proxy-for` pattern.
393
- */
394
-
395
- /**
396
- * Returns the host element inside `el` — the element that holds the control's
397
- * value, UI state, and constraints (i.e. the element onto which
398
- * `useInteractiveProps` spreads `controlProps` and its event handlers).
399
- *
400
- * Returns `null` when `el` is itself the host (no separate wrapper).
401
- */
402
- const findControlHost = (el) => {
403
- if (el.hasAttribute("navi-control-host")) {
404
- return el;
405
- }
406
- return el.querySelector("[navi-control-host]");
407
- };
408
- /**
409
- * The control this element belongs to, wherever it sits relative to it.
410
- *
411
- * `findControlHost` above answers for a control's own DOM (itself, or the native
412
- * element it wraps). This one is for something that is not part of a control but
413
- * has to reach one — an interaction declared on a box (see
414
- * interaction/interactions.js), which may be the control, may sit inside it, or
415
- * may be a wrapper around exactly one. Nearest wins in that order, and the answer
416
- * is null when there is no control the box belongs to: not every box lives in
417
- * one, and a box laying out several controls (a row of badges, a toolbar) is
418
- * held by none of them — its interactions are its own, and a press on its empty
419
- * part is not a press on the first control it happens to contain.
420
- */
421
- const findNearestControlHost = (el) => {
422
- // Itself, then upwards — the box is inside a button, or is one.
423
- const selfOrAncestor = el.closest("[navi-control-host]");
424
- if (selfOrAncestor) {
425
- return selfOrAncestor;
426
- }
427
- // …then downwards, only when the box wraps a single control. Counted by
428
- // control, not by host: a picker holds the hosts of its popup content, and a
429
- // box around that one picker is still around one control.
430
- let single = null;
431
- for (const host of el.querySelectorAll("[navi-control-host]")) {
432
- const controlRoot = host.closest("[navi-control]") || host;
433
- const controlAbove = controlRoot.parentElement.closest("[navi-control]");
434
- if (controlAbove && el.contains(controlAbove)) {
435
- continue;
436
- }
437
- if (single && single !== controlRoot) {
438
- return null;
439
- }
440
- single = controlRoot;
441
- }
442
- return single ? findControlHost(single) : null;
443
- };
444
- const isControlRoot = (el) => {
445
- return el.hasAttribute("navi-control");
446
- };
447
- const isControlHost = (el) => {
448
- return el.hasAttribute("navi-control-host");
449
- };
450
- const isControl = (el) => {
451
- return isControlRoot(el) || isControlHost(el);
452
- };
453
-
454
- /**
455
- * Returns the nearest ancestor of `el` (exclusive of `el`'s own control) that
456
- * has a `[data-action]` attribute.
457
- *
458
- * The search walks up `parentElement` manually (rather than using `.closest()`)
459
- * so it can stop at hard boundaries.
460
- *
461
- * **`[navi-control="picker"]` boundary**: a picker is a hard stop for what is
462
- * inside its popup. Elements in there can reach the picker itself, but nothing
463
- * above it — an input inside a picker must not submit the form around it. The
464
- * picker's own trigger is not inside it: a picker pressed as a whole (a confirm
465
- * picker sending the form around it, see picker_confirm.jsx) stands in that
466
- * form like any control there, and reaches it.
467
- *
468
- * ```html
469
- * <form data-action="outer"> ← found from the picker's own input,
470
- * <button navi-control="picker" data-action="p"> NOT from inside its popup
471
- * <input navi-control-host /> ← el (the picker's own input)
472
- * <div popover data-picker-content>
473
- * <input navi-control-host /> ← el (in picker popover): stops at the picker
474
- * </div>
475
- * </button>
476
- * </form>
477
- * ```
478
- */
479
- const findClosestControlWithAction = (el) => {
480
- let current = el;
481
- while (current) {
482
- if (current.hasAttribute("data-action")) {
483
- return current;
484
- }
485
- if (isPickerBoundaryFor(current, el)) {
486
- return undefined;
487
- }
488
- current = current.parentElement;
489
- }
490
- return undefined;
491
- };
492
- const isPickerBoundaryFor = (candidate, el) => {
493
- if (candidate.getAttribute("navi-control") !== "picker") {
494
- return false;
495
- }
496
- const content = el.closest("[data-picker-content]");
497
- return Boolean(content) && candidate.contains(content);
498
- };
499
-
500
- /**
501
- * Returns the closest ancestor control element of `el` — i.e. the nearest
502
- * `[navi-control]` element that is not the control `el` belongs to.
503
- *
504
- * `navi-control` is only on wrapper elements, never on hosts. So
505
- * `el.closest("[navi-control]")` from a host returns that host's own wrapper,
506
- * and one more `.parentNode.closest("[navi-control]")` reaches a true ancestor:
507
- *
508
- * ```html
509
- * <button navi-control> ← outer control (returned)
510
- * <span navi-control> ← inner wrapper (skipped via parentNode)
511
- * <input navi-control-host /> ← el
512
- * </span>
513
- * </button>
514
- * ```
515
- */
516
- const getParentControl = (el) => {
517
- const ownControlRoot = el.closest("[navi-control]");
518
- const parentControlRoot = ownControlRoot.parentNode.closest("[navi-control]");
519
- return parentControlRoot;
520
- };
521
-
522
- /**
523
- * Returns the root element of the control that `el` belongs to, or `null` if
524
- * `el` is not part of a control.
525
- *
526
- * Use this when you have an element that may be a host (inner input) and need
527
- * the visual boundary of its control — e.g. to anchor a callout, track
528
- * mousedown interactions, or measure the control's bounding box.
529
- */
530
- const findControlRoot = (el) => {
531
- if (el.hasAttribute("navi-control")) {
532
- return el;
533
- }
534
- if (el.hasAttribute("navi-control-host")) {
535
- return el.closest("[navi-control]");
536
- }
537
- return null;
538
- };
539
-
540
- const isSignal = (value) => {
541
- return getSignalType(value) !== null;
542
- };
543
-
544
- const BRAND_SYMBOL = Symbol.for("preact-signals");
545
- const getSignalType = (value) => {
546
- if (!value || typeof value !== "object") {
547
- return null;
548
- }
549
-
550
- if (value.brand !== BRAND_SYMBOL) {
551
- return null;
552
- }
553
-
554
- if (typeof value._fn === "function") {
555
- return "computed";
556
- }
557
-
558
- return "signal";
559
- };
560
-
561
- /**
562
- * Parses a time string into seconds.
563
- * Accepts:
564
- * - number: returned as-is (already in seconds)
565
- * - "HH:MM" string: converted to seconds (e.g. "00:30" → 1800, "01:00" → 3600)
566
- * - undefined/null: returned as-is
567
- */
568
- const timeStringToSeconds = (timeString) => {
569
- if (typeof timeString !== "string") {
570
- return timeString;
571
- }
572
- const colonIndex = timeString.indexOf(":");
573
- if (colonIndex === -1) {
574
- return Number(timeString);
575
- }
576
- const hours = parseInt(timeString.slice(0, colonIndex), 10);
577
- const minutes = parseInt(timeString.slice(colonIndex + 1), 10);
578
- return (hours * 60 + minutes) * 60;
579
- };
580
-
581
- const isToday = (value) => {
582
- if (!value) {
583
- return false;
584
- }
585
- const now = new Date();
586
- const todayStr = `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, "0")}-${String(now.getDate()).padStart(2, "0")}`;
587
- if (typeof value === "string") {
588
- return value === todayStr;
589
- }
590
- if (typeof value === "number") {
591
- const d = new Date(value);
592
- const s = `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, "0")}-${String(d.getDate()).padStart(2, "0")}`;
593
- return s === todayStr;
594
- }
595
- if (value instanceof Date) {
596
- const s = `${value.getFullYear()}-${String(value.getMonth() + 1).padStart(2, "0")}-${String(value.getDate()).padStart(2, "0")}`;
597
- return s === todayStr;
598
- }
599
- return false;
600
- };
601
-
602
- /**
603
- * Returns the current time as "HH:MM", with an optional minute offset.
604
- *
605
- * @param {number} [offsetMinutes=0] - Minutes to add (negative = subtract).
606
- * E.g. getNowHours(-5) returns "now minus 5 minutes".
607
- *
608
- * @example
609
- * getNowHours() // "14:30"
610
- * getNowHours(-5) // "14:25"
611
- */
612
- const getNowHours = (offsetMinutes = 0) => {
613
- const now = new Date();
614
- const totalMinutes = now.getHours() * 60 + now.getMinutes() + offsetMinutes;
615
- const clamped =
616
- totalMinutes < 0
617
- ? 0
618
- : totalMinutes > 23 * 60 + 59
619
- ? 23 * 60 + 59
620
- : totalMinutes;
621
- const h = Math.floor(clamped / 60);
622
- const m = clamped % 60;
623
- return `${String(h).padStart(2, "0")}:${String(m).padStart(2, "0")}`;
624
- };
625
-
626
- /**
627
- * Returns the current time rounded up to the nearest step boundary,
628
- * with an optional minute offset applied first.
629
- *
630
- * This is useful to compute a step-aligned `min` for a time picker:
631
- * passing it ensures the first available slot is always on a step boundary.
632
- *
633
- * @param {number} stepMinutes - Step size in minutes (e.g. 30).
634
- * @param {number} [offsetMinutes=0] - Minutes to add before rounding (negative = subtract).
635
- *
636
- * @example
637
- * // At 9:32, step 30, offset -5 → raw = 9:27 → ceil to 30 → "09:30"
638
- * // At 9:38, step 30, offset -5 → raw = 9:33 → ceil to 30 → "10:00"
639
- * getNowHoursRoundedToStep(30, -5)
640
- */
641
- const getNowHoursRoundedToStep = (stepMinutes, offsetMinutes = 0) => {
642
- const now = new Date();
643
- const totalMinutes = now.getHours() * 60 + now.getMinutes() + offsetMinutes;
644
- const aligned = Math.ceil(totalMinutes / stepMinutes) * stepMinutes;
645
- const clamped =
646
- aligned < 0 ? 0 : aligned > 23 * 60 + 59 ? 23 * 60 + 59 : aligned;
647
- const h = Math.floor(clamped / 60);
648
- const m = clamped % 60;
649
- return `${String(h).padStart(2, "0")}:${String(m).padStart(2, "0")}`;
650
- };
651
-
652
- /**
653
- * "HH:MM" and its two numbers, in both directions — what any control made of an
654
- * hour beside a minute (fields, wheels) aggregates to and is placed from. Held
655
- * as numbers, written on two digits: how they are shown is each control's own
656
- * business.
657
- */
658
- const parseTimeParts = (time) => {
659
- if (typeof time !== "string") {
660
- return null;
661
- }
662
- const match = /^(\d{1,2}):(\d{1,2})/.exec(time);
663
- if (!match) {
664
- return null;
665
- }
666
- return { hour: Number(match[1]), minute: Number(match[2]) };
667
- };
668
-
669
- // Half a time is not a time: a control holding one of the two and nothing in
670
- // the other has no value at all, and a form has nothing to send about it.
671
- const formatTimeParts = (hour, minute) => {
672
- if (
673
- hour === "" ||
674
- hour === undefined ||
675
- minute === "" ||
676
- minute === undefined
677
- ) {
678
- return undefined;
679
- }
680
- return `${padTwo(hour)}:${padTwo(minute)}`;
681
- };
682
-
683
- const minutesFromTime = (time) => {
684
- const parts = parseTimeParts(time);
685
- if (!parts) {
686
- return null;
687
- }
688
- return parts.hour * 60 + parts.minute;
689
- };
690
-
691
- // Not folded back into the day: 1440 is "24:00", the end of the day a span can
692
- // run into.
693
- const timeFromMinutes = (minutes) => {
694
- return `${padTwo(Math.floor(minutes / 60))}:${padTwo(minutes % 60)}`;
695
- };
696
-
697
- const padTwo = (value) => String(value).padStart(2, "0");
698
-
699
- // What a bound signal's type says is what its VALUE is (a validity type);
700
- // what a control's `type` says is what the control IS. This table is the whole
701
- // bridge between the two vocabularies: a value type with a row here asks for
702
- // that control, one without a row asks for nothing and the control keeps its
703
- // own default. "string" has no row on purpose — it is the value every typeless
704
- // control already holds — and a name only one side knows must never cross as
705
- // is: a control type nobody implements is a plain text field that writes an
706
- // object as "[object Object]" (see warnOnUnknownPickerType in picker.jsx).
707
- // Numeric value types map to navi_number rather than the native type="number"
708
- // (spinner buttons, poor UX).
709
- const CONTROL_TYPE_BY_SIGNAL_TYPE = {
710
- boolean: "checkbox",
711
- number: "navi_number",
712
- integer: "navi_number",
713
- float: "navi_number",
714
- ratio: "navi_number",
715
- longitude: "navi_number",
716
- latitude: "navi_number",
717
- second: "navi_number",
718
- minute: "navi_number",
719
- hour: "navi_number",
720
- year: "navi_number",
721
- percentage: "navi_percentage",
722
- date: "date",
723
- month: "month",
724
- week: "week",
725
- time: "time",
726
- datetime: "datetime",
727
- duration: "duration",
728
- color: "color",
729
- email: "email",
730
- url: "url",
731
- array: "array",
732
- object: "object",
733
- };
734
-
735
- // Conceptual navi types: defaults, plus the host type they resolve to.
736
- // `navi-input-type` keeps the type the caller asked for once the host has
737
- // become something plainer — it is what says the value is a number (see
738
- // isNumberInput), and what lets constraint messages use domain-specific
739
- // wording instead of the generic "Ce nombre doit être...".
740
- // A type a picker preset draws (navi_time, navi_minute: see picker_preset.jsx)
741
- // has no row: resolveInputProps runs before the preset resolver, and a row
742
- // would turn the type into its host before the preset resolver reads it. The
743
- // preset hands the host type on itself.
744
- const NAVI_TYPE_DEFAULTS = {
745
- navi_percentage: {
746
- "type": "navi_number",
747
- "navi-input-type": "percentage",
748
- "min": 0,
749
- "max": 100,
750
- "step": 1,
751
- },
752
- navi_number: {
753
- "type": "text",
754
- "navi-input-type": "number",
755
- "autoCorrect": "off",
756
- "spellcheck": false,
757
- "autoComplete": "off",
758
- },
759
- };
760
-
761
- // The navi input types whose value IS a number.
762
- const NUMBER_NAVI_INPUT_TYPE_SET = new Set([
763
- "number",
764
- "percentage",
765
- "hour",
766
- "minute",
767
- "second",
768
- ]);
769
-
770
- /**
771
- * Whether the control holds a number — asked of what the control IS, never of
772
- * `inputMode`. In HTML `inputmode` picks the on-screen keyboard and says
773
- * nothing about the value: a licence number, a postal code or a card number
774
- * with a check letter all want the digit keypad while staying strings. What a
775
- * number field is spelled `type="number"`, or a navi type that resolves to a
776
- * text host and leaves `navi-input-type` behind to say what it was.
777
- */
778
- const isNumberInput = (type, naviInputType) => {
779
- if (type === "number") {
780
- return true;
781
- }
782
- return NUMBER_NAVI_INPUT_TYPE_SET.has(naviInputType);
783
- };
784
-
785
- /**
786
- * resolveInputProps — normalizes input-related props that are shared across
787
- * `<Picker>`, `<Input>` (textual) and `<Range>`. Mutates the props object in place.
788
- *
789
- * Normalization is applied recursively: a navi type may resolve to another navi
790
- * type (e.g. `navi_percentage` → `navi_number` → `text`), and each step applies its
791
- * own formatters and defaults before moving to the next.
792
- *
793
- * Steps applied for each type:
794
- * 1. Record the original navi type in `props["navi-input-type"]` (first call only).
795
- * 2. Apply defaults for the current type (min, max, step, and any other props),
796
- * only when the prop is not already set.
797
- * 3. Apply min/max formatters (e.g. HH:MM string → number for duration types,
798
- * Date → formatted string for date/time types).
799
- * 4. Apply step formatter (same conversion rules).
800
- * 5. Remap `props.type` to the target type defined by the current type's defaults,
801
- * then recurse.
802
- *
803
- * Supported navi types and their targets:
804
- * - `navi_percentage` → `navi_number` (0–100, step 1)
805
- * - `navi_number` → `text` (inputMode="numeric", no spin buttons implied)
806
- *
807
- * Standard HTML input types with formatters:
808
- * - `date`, `month`, `week`, `time`, `datetime-local`, `datetime`:
809
- * min/max accept `Date` instances or timestamps and are converted to the
810
- * string format expected by the native input.
811
- * - `time`, `datetime-local`, `datetime`:
812
- * step accepts `"HH:MM"` and is converted to seconds.
813
- */
814
- /**
815
- * A bound signal that carries a default of its own says the same thing on every
816
- * control: the control starts there, uncontrolled, and a reset goes back to it.
817
- * Uncontrolled here is about where the control starts, not about whether it
818
- * follows the signal — the binding stays two-way either way (see
819
- * stateFromSignal in control_hooks.jsx) — nor about what a form counts as
820
- * held: that is the signal's content (isUIStateHeld in held_ui_state.js), and a
821
- * stateSignal holds its default. Written once and used by everything
822
- * that takes a `signal`, so one signal cannot mean two different things
823
- * depending on which control it was handed to.
824
- */
825
- const seedDefaultValueFromSignal = (props) => {
826
- const signalOptions = props.signal?.options;
827
- if (!signalOptions) {
828
- return;
829
- }
830
- if (Object.hasOwn(props, "defaultValue")) {
831
- // explicit defaultValue prop prevails
832
- return;
833
- }
834
- // Snapshot the signal's current default so that resetUIState restores to the
835
- // original default — not the value the signal had at the time of the last
836
- // re-render.
837
- const defaultValue = signalOptions.getDefaultValue(false);
838
- if (defaultValue !== undefined) {
839
- props.defaultValue = defaultValue;
840
- }
841
- };
842
-
843
- const resolveInputProps = (props, { controlType = "input" } = {}) => {
844
- // `signal` carries a bound state signal. It is left on `props` on purpose:
845
- // `createControlInfo` (control_hooks.jsx) reads it to seed the state and to
846
- // follow it, and `onUIAction` (ui_state_controller.js) writes user
847
- // interactions back into it. Here we only derive input defaults (type/min/max,
848
- // defaultValue/defaultChecked) from the signal's `options`, so the control
849
- // ends up uncontrolled-with-default while still bound to the signal.
850
- const signal = props.signal;
851
- if (signal) {
852
- const signalOptions = signal.options;
853
- if (signalOptions) {
854
- for (const key of ["min", "max", "step"]) {
855
- if (props[key] === undefined && signalOptions[key] !== undefined) {
856
- props[key] = signalOptions[key];
857
- }
858
- }
859
- if (props.type === undefined && signalOptions.type !== undefined) {
860
- const typeFromSignal = CONTROL_TYPE_BY_SIGNAL_TYPE[signalOptions.type];
861
- // A value type and the control for it usually agree — a date-typed
862
- // signal wants a date field — but a boolean one maps to a checkbox, and
863
- // a picker made into a checkbox is not a picker with a different look:
864
- // it is another control, with no popup to open. A picker asked to hold
865
- // a yes/no keeps its two rows and stays itself.
866
- const wouldChangeWhatTheControlIs =
867
- controlType === "picker" &&
868
- (typeFromSignal === "checkbox" || typeFromSignal === "radio");
869
- if (typeFromSignal !== undefined && !wouldChangeWhatTheControlIs) {
870
- props.type = typeFromSignal;
871
- }
872
- }
873
- }
874
-
875
- const isCheckable = props.type === "checkbox" || props.type === "radio";
876
- if (isCheckable) {
877
- if (Object.hasOwn(props, "defaultChecked")) ; else {
878
- // If no explicit defaultChecked, derive it from the signal's default
879
- // value so that resetUIState restores to the original default.
880
- // Only a stateSignal carries a default of its own; a plain signal has
881
- // no `options` at all, hence the optional read.
882
- const defaultVal = signalOptions?.getDefaultValue(false);
883
- if (defaultVal === undefined) ; else if (props.type === "radio") {
884
- if (defaultVal === true) {
885
- props.defaultChecked = true;
886
- } else if (
887
- Object.hasOwn(props, "value") &&
888
- defaultVal === props.value
889
- ) {
890
- props.defaultChecked = true;
891
- }
892
- } else if (typeof defaultVal === "boolean") {
893
- // Standalone checkbox bound to a boolean signal.
894
- props.defaultChecked = defaultVal;
895
- } else {
896
- // Checkbox is a group member: defaultVal is the array of
897
- // selected item values.
898
- const checkboxValue = props.value;
899
- props.defaultChecked =
900
- Array.isArray(defaultVal) && defaultVal.includes(checkboxValue);
901
- }
902
- }
903
- return;
904
- }
905
-
906
- seedDefaultValueFromSignal(props);
907
- }
908
-
909
- const currentType = props.type;
910
- // Apply min/max/step formatters before anything else — this must run even for
911
- // standard HTML types (date, time, etc.) that have no NAVI_TYPE_DEFAULTS entry.
912
- const currentTypeMinMaxFormatter = MIN_MAX_FORMATTER_BY_TYPE[currentType];
913
- const currentTypeStepFormatter = STEP_FORMATTER_BY_TYPE[currentType];
914
- if (currentTypeMinMaxFormatter) {
915
- props.min = currentTypeMinMaxFormatter(props.min);
916
- props.max = currentTypeMinMaxFormatter(props.max);
917
- }
918
- if (currentTypeStepFormatter) {
919
- props.step = currentTypeStepFormatter(props.step);
920
- }
921
-
922
- // For navi_number: choose inputMode based on whether step/min/max suggest decimals.
923
- // inputMode="numeric" (integer keyboard) vs "decimal" (keyboard with decimal separator).
924
- if (currentType === "navi_number") {
925
- if (props.inputMode === undefined) {
926
- props.inputMode =
927
- hasDecimalPlaces(props.step) ||
928
- hasDecimalPlaces(props.min) ||
929
- hasDecimalPlaces(props.max)
930
- ? "decimal"
931
- : "numeric";
932
- }
933
- }
934
-
935
- const { charGuard } = props;
936
- if (charGuard) {
937
- if (charGuard === true || charGuard === "auto") {
938
- // Auto-resolve charGuard from context.
939
- let charGuardResolved;
940
- const inputMode = props.inputMode;
941
- if (inputMode === "numeric") {
942
- charGuardResolved = "numeric";
943
- } else if (inputMode === "decimal") {
944
- charGuardResolved = "decimal";
945
- } else if (currentType === "tel") {
946
- charGuardResolved = "tel";
947
- } else if (currentType === "email") {
948
- charGuardResolved = "email";
949
- }
950
- if (charGuardResolved !== undefined) {
951
- props.charGuard = charGuardResolved;
952
- }
953
- }
954
- // charGuard is now resolved: derive inputMode from it if not already set.
955
- if (props.inputMode === undefined && props.charGuard) {
956
- const autoMode = INPUT_MODE_FROM_CHAR_GUARD[props.charGuard];
957
- if (autoMode) {
958
- props.inputMode = autoMode;
959
- }
960
- }
961
- // Build pattern from the resolved charGuard (preset name → class, or raw class passthrough).
962
- if (props.pattern === undefined && props.charGuard) {
963
- const charClass = CHAR_CLASS_PRESETS[props.charGuard] ?? props.charGuard;
964
- props.pattern = `${charClass}*`;
965
- }
966
- }
967
-
968
- // Compute maxLength from max when inputMode is numeric/decimal.
969
- // Done here (after inputMode is set) so controller.props has the resolved value.
970
- if (props.maxLength === undefined) {
971
- if (props.inputMode === "numeric") {
972
- const { min, max } = props;
973
- if (max === undefined) ; else {
974
- const canBeNegative = min === undefined ? max < 0 : min < 0;
975
- const signCharCount = canBeNegative ? 1 : 0;
976
- const integerDigitCount = String(Math.floor(Math.abs(max))).length;
977
- props.maxLength = signCharCount + integerDigitCount;
978
- }
979
- } else if (props.inputMode === "decimal") {
980
- const { min, max, step } = props;
981
- if (max === undefined) ; else if (step === undefined) ; else {
982
- const canBeNegative = min === undefined ? max < 0 : min < 0;
983
- const signCharCount = canBeNegative ? 1 : 0;
984
- const integerDigitCount = String(Math.floor(Math.abs(max))).length;
985
- const stepStr = String(step);
986
- const dotIndex = stepStr.indexOf(".");
987
- // integer step + decimal inputMode is an unusual combo, but we stay consistent:
988
- // no decimal part in maxLength since valid values are whole numbers anyway
989
- const isIntegerStep = dotIndex === -1;
990
- const decimalSignCharCount = isIntegerStep ? 0 : 1;
991
- const decimalDigitCount = isIntegerStep
992
- ? 0
993
- : stepStr.length - dotIndex - 1;
994
- props.maxLength =
995
- signCharCount +
996
- integerDigitCount +
997
- decimalSignCharCount +
998
- decimalDigitCount;
999
- }
1000
- }
1001
- }
1002
-
1003
- // Resolve maxLengthGuard boolean/auto → the computed maxLength number.
1004
- if (props.maxLengthGuard === true || props.maxLengthGuard === "auto") {
1005
- props.maxLengthGuard =
1006
- typeof props.maxLength === "number" ? props.maxLength : undefined;
1007
- }
1008
-
1009
- const currentTypeDefaults = NAVI_TYPE_DEFAULTS[currentType];
1010
- if (!currentTypeDefaults) {
1011
- return;
1012
- }
1013
-
1014
- for (const key of Object.keys(currentTypeDefaults)) {
1015
- if (props[key] === undefined) {
1016
- props[key] = currentTypeDefaults[key];
1017
- }
1018
- }
1019
- const targetType = currentTypeDefaults.type;
1020
- props.type = targetType;
1021
- resolveInputProps(props);
1022
- };
1023
-
1024
- // Presets that imply a specific mobile keyboard inputMode.
1025
- const INPUT_MODE_FROM_CHAR_GUARD = {
1026
- numeric: "numeric",
1027
- pin: "numeric",
1028
- card: "numeric",
1029
- tel: "tel",
1030
- decimal: "decimal",
1031
- };
1032
-
1033
- const normalizeToDate = (value) => {
1034
- if (value === undefined || value === null) {
1035
- return null;
1036
- }
1037
- if (typeof value === "number") {
1038
- return new Date(value);
1039
- }
1040
- if (value instanceof Date) {
1041
- return value;
1042
- }
1043
- return null;
1044
- };
1045
-
1046
- const toInputDate = (value) => {
1047
- const date = normalizeToDate(value);
1048
- if (!date) {
1049
- return value;
1050
- }
1051
- const yyyy = date.getFullYear();
1052
- const mm = String(date.getMonth() + 1).padStart(2, "0");
1053
- const dd = String(date.getDate()).padStart(2, "0");
1054
- return `${yyyy}-${mm}-${dd}`;
1055
- };
1056
- const toInputMonth = (value) => {
1057
- const date = normalizeToDate(value);
1058
- if (!date) {
1059
- return value;
1060
- }
1061
- const yyyy = date.getFullYear();
1062
- const mm = String(date.getMonth() + 1).padStart(2, "0");
1063
- return `${yyyy}-${mm}`;
1064
- };
1065
- const toInputWeek = (value) => {
1066
- const date = normalizeToDate(value);
1067
- if (!date) {
1068
- return value;
1069
- }
1070
- // ISO week number
1071
- const d = new Date(date);
1072
- d.setHours(0, 0, 0, 0);
1073
- d.setDate(d.getDate() + 3 - ((d.getDay() + 6) % 7));
1074
- const yearStart = new Date(d.getFullYear(), 0, 4);
1075
- const week =
1076
- Math.round(
1077
- ((d - yearStart) / 86400000 - 3 + ((yearStart.getDay() + 6) % 7)) / 7,
1078
- ) + 1;
1079
- return `${d.getFullYear()}-W${String(week).padStart(2, "0")}`;
1080
- };
1081
- const toInputTime = (value) => {
1082
- const date = normalizeToDate(value);
1083
- if (!date) {
1084
- return value;
1085
- }
1086
- const hh = String(date.getHours()).padStart(2, "0");
1087
- const mm = String(date.getMinutes()).padStart(2, "0");
1088
- return `${hh}:${mm}`;
1089
- };
1090
- const toInputDatetime = (value) => {
1091
- const date = normalizeToDate(value);
1092
- if (!date) {
1093
- return value;
1094
- }
1095
- const yyyy = date.getFullYear();
1096
- const mm = String(date.getMonth() + 1).padStart(2, "0");
1097
- const dd = String(date.getDate()).padStart(2, "0");
1098
- const hh = String(date.getHours()).padStart(2, "0");
1099
- const min = String(date.getMinutes()).padStart(2, "0");
1100
- return `${yyyy}-${mm}-${dd}T${hh}:${min}`;
1101
- };
1102
-
1103
- const MIN_MAX_FORMATTER_BY_TYPE = {
1104
- "date": toInputDate,
1105
- "month": toInputMonth,
1106
- "week": toInputWeek,
1107
- "time": toInputTime,
1108
- "datetime-local": toInputDatetime,
1109
- "datetime": toInputDatetime,
1110
- };
1111
- const STEP_FORMATTER_BY_TYPE = {
1112
- "time": timeStringToSeconds,
1113
- "datetime-local": timeStringToSeconds,
1114
- "datetime": timeStringToSeconds,
1115
- };
1116
-
1117
- const hasDecimalPlaces = (value) => {
1118
- if (value === undefined || value === null) {
1119
- return false;
1120
- }
1121
- const num = Number(value);
1122
- return !isNaN(num) && !Number.isInteger(num);
1123
- };
1124
-
1125
- const dispatchRequestSetUIState = (element, value, detail) => {
1126
- const controlHost = findControlHost(element) || element;
1127
- return dispatchInternalCustomEvent(controlHost, "navi_set_ui_state", {
1128
- ...detail,
1129
- value,
1130
- });
1131
- };
1132
- const dispatchRequestClearUIState = (element, e) => {
1133
- const controlHost = findControlHost(element) || element;
1134
- return dispatchInternalCustomEvent(controlHost, "navi_clear_ui_state", {
1135
- event: e,
1136
- });
1137
- };
1138
- const dispatchRequestResetUIState = (element, e) => {
1139
- const controlHost = findControlHost(element) || element;
1140
- return dispatchInternalCustomEvent(controlHost, "navi_reset_ui_state", {
1141
- event: e,
1142
- });
1143
- };
1144
- /**
1145
- * @param {Element} el
1146
- * @param {{ own?: boolean }} [options] `own`: what the element holds BY ITSELF.
1147
- * Only a button ever answers differently — one with no value of its own
1148
- * inherits the value of the control around it, which is what makes
1149
- * `--navi-send` on a form's button be about that form. Something asking what
1150
- * THIS element says (a travel command reading what the travel is about) wants
1151
- * the own value and would otherwise be handed the surrounding control's.
1152
- */
1153
- const getUIStateFromElement = (el, { own } = {}) => {
1154
- let uiState;
1155
- dispatchInternalCustomEvent(el, "navi_get_ui_state", {
1156
- own,
1157
- respondWith: (v) => {
1158
- uiState = v;
1159
- },
1160
- });
1161
- return uiState;
1162
- };
1163
-
1164
- /**
1165
- * Converts a JS value into the form expected by the browser DOM property for a
1166
- * given control type/input type combination.
1167
- *
1168
- * For example:
1169
- * - `datetime-local` inputs expect a local datetime string without timezone
1170
- * - `number`/`range` inputs expect a numeric string or number
1171
- * - `color` inputs require a non-empty hex string (falls back to `#000000`)
1172
- * - All other inputs receive the value as-is (undefined → "")
1173
- *
1174
- * Returns either the converted value directly, or a converter function when the
1175
- * conversion depends on the runtime value (e.g. plain inputs return `asInputValue`).
1176
- *
1177
- * @param {any} value - The JS value to convert.
1178
- * @param {{ controlType: string, type: string }} options
1179
- * @returns {any} The DOM-compatible value or a converter function.
1180
- */
1181
- const asControlHostValue = (
1182
- jsValue,
1183
- { controlType, type, naviInputType, pad },
1184
- ) => {
1185
- if (controlType === "select") {
1186
- // A select holds one of its options, always a string; holding nothing is
1187
- // the empty option, which the element spells "".
1188
- return asInputValue(jsValue);
1189
- }
1190
- if (controlType === "input" || controlType === "picker") {
1191
- if (type === "datetime-local") {
1192
- return asDatetimeLocalString(jsValue);
1193
- }
1194
- if (type === "range" || isNumberInput(type, naviInputType)) {
1195
- return asNumberString(jsValue, pad);
1196
- }
1197
- if (type === "color") {
1198
- return asColorString(jsValue);
1199
- }
1200
- return asInputValue(jsValue);
1201
- }
1202
- return jsValue;
1203
- };
1204
- // As explained in https://developer.mozilla.org/en-US/docs/Web/HTML/Reference/Elements/input/datetime-local#setting_timezones
1205
- // datetime-local does not support timezones
1206
- const asDatetimeLocalString = (dateTimeString) => {
1207
- const date = new Date(dateTimeString);
1208
- if (isNaN(date.getTime())) {
1209
- return dateTimeString;
1210
- }
1211
- const year = date.getFullYear();
1212
- const month = String(date.getMonth() + 1).padStart(2, "0");
1213
- const day = String(date.getDate()).padStart(2, "0");
1214
- const hours = String(date.getHours()).padStart(2, "0");
1215
- const minutes = String(date.getMinutes()).padStart(2, "0");
1216
- const seconds = String(date.getSeconds()).padStart(2, "0");
1217
- return `${year}-${month}-${day}T${hours}:${minutes}:${seconds}`;
1218
- };
1219
- // `pad` is how many digits the number is WRITTEN on — an hour is held as 7 and
1220
- // shown as "07". Held and shown are two things here, the way they are for a
1221
- // datetime-local above: what the field says is derived from what the control
1222
- // holds, and reading it back (readNumberFromInput) gives the number again.
1223
- const asNumberString = (jsValue, pad) => {
1224
- if (jsValue === undefined) {
1225
- return "";
1226
- }
1227
- if (!pad || jsValue === "" || jsValue === null) {
1228
- return jsValue;
1229
- }
1230
- const number = Number(jsValue);
1231
- if (Number.isNaN(number)) {
1232
- return jsValue;
1233
- }
1234
- const negative = number < 0;
1235
- const digits = String(negative ? -number : number).padStart(Number(pad), "0");
1236
- return negative ? `-${digits}` : digits;
1237
- };
1238
- // Browser requires a non-empty value for <input type="color">.
1239
- // When our logical value is empty we give it #000000 so it doesn't choke.
1240
- // The UI uses the original (possibly empty) value to show the checkerboard.
1241
- const asColorString = (jsValue) => {
1242
- return jsValue || "#000000";
1243
- };
1244
- const asInputValue = (jsValue) => {
1245
- if (jsValue === undefined) {
1246
- return "";
1247
- }
1248
- return jsValue;
1249
- };
1250
-
1251
- /**
1252
- * Reads the current logical JS value from a control host DOM element.
1253
- *
1254
- * Handles all navi control host element types:
1255
- * - `<button>` — reads via `navi_get_value` custom event, falls back to `button.value`
1256
- * - `<input type="number|range">` — parses as a number, returns `undefined` when empty
1257
- * - `<input type="checkbox|radio">` — returns `undefined` when unchecked, otherwise reads
1258
- * via `navi_get_value` custom event (to preserve the original JS type of the value prop)
1259
- * - `<input type="datetime-local">` — converts the local datetime string to an ISO 8601 string
1260
- * - `<input type="navi_picker">` — delegates to the controller via `navi_get_ui_state`
1261
- * - All other inputs — returns `input.value` as a string
1262
- *
1263
- * @param {HTMLElement} controlHost - The control host DOM element to read from.
1264
- * @returns {any} The current logical value of the control.
1265
- */
1266
- const readControlValue = (controlHost) => {
1267
- if (
1268
- controlHost.tagName === "BUTTON" ||
1269
- controlHost.getAttribute("role") === "button"
1270
- ) {
1271
- return readValueFromButton(controlHost);
1272
- }
1273
- if (controlHost.tagName === "INPUT") {
1274
- // important: input.type = "navi_js"; followed by input.type; returns "text"
1275
- // so use getAttribute
1276
- const type = controlHost.getAttribute("type");
1277
-
1278
- if (
1279
- type === "range" ||
1280
- isNumberInput(type, controlHost.getAttribute("navi-input-type"))
1281
- ) {
1282
- return readNumberFromInput(controlHost);
1283
- }
1284
- if (type === "color") {
1285
- return readValueFromControlHost(controlHost);
1286
- }
1287
- if (type === "checkbox" || type === "radio") {
1288
- return readValueFromCheckableInput(controlHost);
1289
- }
1290
- if (type === "datetime-local") {
1291
- return readDatetimeLocalFromInput(controlHost);
1292
- }
1293
- if (type === "navi_js") {
1294
- return getUIStateFromElement(controlHost);
1295
- }
1296
- return readValueFromInput(controlHost);
1297
- }
1298
- if (controlHost.hasAttribute("navi-control-host")) {
1299
- // Non-button, non-input navi controls (e.g. Badge.Button rendered as span)
1300
- return readValueFromControlHost(controlHost);
1301
- }
1302
- return readValueFromElement(controlHost);
1303
- };
1304
- const readValueFromControlHost = (controlHost) => {
1305
- return readValueFromNaviCustomEvent(controlHost, controlHost.value);
1306
- };
1307
- const readValueFromButton = (button) => {
1308
- return readValueFromControlHost(button);
1309
- };
1310
- const readDatetimeLocalFromInput = (input) => {
1311
- const localDateTimeString = input.value;
1312
- if (localDateTimeString === "") {
1313
- return "";
1314
- }
1315
- const localDate = new Date(localDateTimeString);
1316
- if (isNaN(localDate.getTime())) {
1317
- return localDateTimeString;
1318
- }
1319
- return localDate.toISOString();
1320
- };
1321
- const readNumberFromInput = (input) => {
1322
- const numberString = input.value;
1323
- if (numberString === "") {
1324
- return "";
1325
- }
1326
- const asNumber = Number(numberString);
1327
- if (isNaN(asNumber)) {
1328
- return numberString;
1329
- }
1330
- return asNumber;
1331
- };
1332
- const readValueFromCheckableInput = (input) => {
1333
- const checked = input.checked;
1334
- if (!checked) {
1335
- return undefined;
1336
- }
1337
- return readValueFromControlHost(input);
1338
- };
1339
- const readValueFromInput = (input) => {
1340
- const value = input.value;
1341
- return value;
1342
- };
1343
- const readValueFromElement = (element) => {
1344
- const value = element.value;
1345
- return value;
1346
- };
1347
- const readValueFromNaviCustomEvent = (field, fallback) => {
1348
- // prefer the value given as prop (respect original type, browser would convert to string)
1349
- let responded;
1350
- let value;
1351
- dispatchCustomEvent(field, "navi_get_value", {
1352
- respondWith: (jsValue) => {
1353
- responded = true;
1354
- value = jsValue;
1355
- },
1356
- });
1357
- if (responded) {
1358
- return value;
1359
- }
1360
- return fallback;
1361
- };
1362
-
1363
- /**
1364
- * A control is bound to EITHER a signal (two-way) or a value/checked prop,
1365
- * never both — the two would fight over the state. The signal is the one that
1366
- * wins; this says so in dev, wherever the question is decided (a leaf control
1367
- * in control_hooks, a group in ui_state_controller).
1368
- *
1369
- * Only the controlled prop (value/checked) collides with signal — the default
1370
- * prop (defaultValue/defaultChecked) is legitimately seeded from the signal by
1371
- * resolveInputProps, so it must not warn here.
1372
- */
1373
- const warnSignalCollision = (props, controlType, stateProp) => {
1374
- if (Object.hasOwn(props, stateProp)) {
1375
- console.warn(
1376
- `[navi] "${controlType}" got both "signal" and "${stateProp}". ` +
1377
- `"signal" is the source of truth; "${stateProp}" is ignored. ` +
1378
- `Pass only "signal".`,
1379
- );
1380
- }
1381
- };
1382
-
1383
- /**
1384
- * A signal handed to a prop that holds a plain value is the `signal` binding
1385
- * written in the wrong place. Nothing throws: the signal object becomes the
1386
- * value, and a value that cannot be written to the DOM is replaced by a
1387
- * `window.__navi_js('…')` reference string — which is then what the field
1388
- * shows on screen (see toDomValue in controller_registry.js).
1389
- */
1390
- const warnSignalAsState = (props, controlType, stateProps) => {
1391
- for (const stateProp of stateProps) {
1392
- if (isSignal(props[stateProp])) {
1393
- console.warn(
1394
- `[navi] "${controlType}" got a signal as "${stateProp}". ` +
1395
- `A signal binds a control through "signal" — did you mean signal={...}? ` +
1396
- `As "${stateProp}" it is taken for the value itself.`,
1397
- );
1398
- }
1399
- }
1400
- };
1401
-
1402
- // In-memory registry of all mounted ui state controllers keyed by their id.
1403
- // Allows direct controller access without dispatching DOM events — used by external
1404
- // callers (e.g. selectable_list) to call setUIState by id instead of via the DOM.
1405
- const controllersById = new Map();
1406
-
1407
- // In-memory registry for radio controllers, keyed by input name.
1408
- // Allows radio sibling unchecking without querying the DOM — necessary when
1409
- // items are virtualized and their DOM element may not exist at the time.
1410
- // Form scoping is reproduced by comparing parentUIStateController references.
1411
- const radioControllersByName = new Map();
1412
-
1413
- // Registry for non-serializable JS values that cannot be written to DOM attributes as-is.
1414
- // When a value is an object/array, we store it here and write a reference string to the DOM
1415
- // instead of "[object Object]". Console-inspectable via window.__navi_js('id').
1416
- // The controller id is used as key — if the controller has no id, the value is not registered.
1417
- const naviJsRegistry = new Map();
1418
-
1419
- // Controllers already reported for sharing their id with another one. An id is
1420
- // stated on every render of its control, so without this the warning below
1421
- // would repeat for as long as both controls are on screen.
1422
- const controllersWarned = new WeakSet();
1423
-
1424
- const getUIStateControllerById = (id) => controllersById.get(id);
1425
- const getRadioSiblings = (radioUIStateController) => {
1426
- const siblings = radioControllersByName.get(radioUIStateController.name);
1427
- return siblings;
1428
- };
1429
-
1430
- const toDomValue = (
1431
- jsValue,
1432
- { controlType, id, type, naviInputType, pad },
1433
- ) => {
1434
- const domValue = asControlHostValue(jsValue, {
1435
- controlType,
1436
- type,
1437
- naviInputType,
1438
- pad,
1439
- });
1440
- if (isSerializableAsDomValue(domValue)) {
1441
- return domValue;
1442
- }
1443
- naviJsRegistry.set(id, domValue);
1444
- return `window.__navi_js('${id}')`;
1445
- };
1446
-
1447
- window.__navi_js = (id) => naviJsRegistry.get(id);
1448
- const isSerializableAsDomValue = (value) => {
1449
- if (value === null || value === undefined) {
1450
- return true;
1451
- }
1452
- const type = typeof value;
1453
- return type === "string" || type === "number" || type === "boolean";
1454
- };
1455
-
1456
- const onUIStateControllerCreated = (uiStateController) => {
1457
- const { id, name, controlType } = uiStateController;
1458
- if (id) {
1459
- {
1460
- const existing = controllersById.get(id);
1461
- if (
1462
- existing &&
1463
- existing !== uiStateController &&
1464
- !controllersWarned.has(uiStateController)
1465
- ) {
1466
- controllersWarned.add(uiStateController);
1467
- console.warn(
1468
- `[navi] Two controls share the same id "${id}" ("${existing.controlType}" and "${controlType}"). ` +
1469
- `The id resolves to whichever of them rendered last, so the other one is unreachable through it (undefined uiState, dead picker buttons). ` +
1470
- `Common causes: several controls inside a single <Field> (the Field provides one id via context and every control consumes it — put each control in its own <Field>, or give one an explicit id), ` +
1471
- `or the same content mounted twice (e.g. two popups sharing an id prefix while both hold their content).`,
1472
- );
1473
- }
1474
- }
1475
- controllersById.set(id, uiStateController);
1476
- }
1477
- const proxyFor = uiStateController.props["navi-control-proxy-for"];
1478
- if (proxyFor) {
1479
- let proxySet = proxyControllersByRealInputId.get(proxyFor);
1480
- if (!proxySet) {
1481
- proxySet = new Set();
1482
- proxyControllersByRealInputId.set(proxyFor, proxySet);
1483
- }
1484
- proxySet.add(uiStateController);
1485
- }
1486
- if (
1487
- controlType === "input" &&
1488
- uiStateController.props.type === "radio" &&
1489
- name
1490
- ) {
1491
- let set = radioControllersByName.get(name);
1492
- if (!set) {
1493
- set = new Set();
1494
- radioControllersByName.set(name, set);
1495
- }
1496
- set.add(uiStateController);
1497
- }
1498
- };
1499
- const onUIStateControllerDestroyed = (uiStateController) => {
1500
- const { id, name, controlType } = uiStateController;
1501
- if (id) {
1502
- // Only the controller the id currently points at may take the entry away:
1503
- // when two controls share an id, the one leaving would otherwise unregister
1504
- // the one staying (see the warning in onUIStateControllerCreated), and the
1505
- // same holds while a control is being replaced by its successor, which
1506
- // registers during its render, before this cleanup runs.
1507
- if (controllersById.get(id) === uiStateController) {
1508
- controllersById.delete(id);
1509
- naviJsRegistry.delete(id);
1510
- }
1511
- }
1512
- const proxyFor = uiStateController.props["navi-control-proxy-for"];
1513
- if (proxyFor) {
1514
- const proxySet = proxyControllersByRealInputId.get(proxyFor);
1515
- if (proxySet) {
1516
- proxySet.delete(uiStateController);
1517
- if (proxySet.size === 0) {
1518
- proxyControllersByRealInputId.delete(proxyFor);
1519
- }
1520
- }
1521
- }
1522
- if (
1523
- controlType === "input" &&
1524
- uiStateController.controlHostProps.type === "radio" &&
1525
- name
1526
- ) {
1527
- const set = radioControllersByName.get(name);
1528
- if (set) {
1529
- set.delete(uiStateController);
1530
- if (set.size === 0) {
1531
- radioControllersByName.delete(name);
1532
- }
1533
- }
1534
- }
1535
- };
1536
-
1537
- /**
1538
- * Controller-based equivalent of findControlProxyTarget.
1539
- * Given a proxy controller, returns the real control's controller.
1540
- * Finds the target by walking the parent controller's children — no DOM queries.
1541
- * Returns `null` when the controller is not a proxy or the target is not found.
1542
- */
1543
- const findControlProxyTargetController = (controller) => {
1544
- const proxyFor = controller.controlHostProps["navi-control-proxy-for"];
1545
- if (!proxyFor) {
1546
- return null;
1547
- }
1548
- return getUIStateControllerById(proxyFor) ?? null;
1549
- };
1550
-
1551
- // Reverse-lookup map: real-input id → the proxy controllers that reference it
1552
- // via `navi-control-proxy-for`. A single control can be represented by several
1553
- // proxies (an "enable"/"disable" button pair for one radio, for instance), so
1554
- // each id holds a set. Maintained on create/destroy so lookup is O(1).
1555
- const proxyControllersByRealInputId = new Map();
1556
- const findProxyControllers = (realInputId) => {
1557
- if (!realInputId) {
1558
- return null;
1559
- }
1560
- return proxyControllersByRealInputId.get(realInputId) ?? null;
1561
- };
1562
-
1563
- /**
1564
- * DOM utilities for the proxy control pattern.
1565
- *
1566
- * Some components need a native `<input>` internally — for form submission,
1567
- * constraint validation, or browser autofill — but the user may not want to
1568
- * display that input at all. In those cases the input is hidden and a separate
1569
- * visible element (the proxy) takes over the visual and interactive role.
1570
- *
1571
- * The typical use case is `SelectableList`: each list item acts as a styled
1572
- * radio button, but an actual `<input type="radio">` lives hidden in the DOM
1573
- * so form submission and validation work natively. When users DO want to
1574
- * display the input they want full control over its appearance, so they render
1575
- * their own element and link it to the real input via `navi-control-proxy-for`:
1576
- *
1577
- * ```html
1578
- * <div>
1579
- * <input id="color_red" type="radio" name="color" value="red" /> ← real control (hidden, drives form/validation)
1580
- * <input type="radio" name="proxy" value="red" /> ← proxy (visible, delegates interactions to real input)
1581
- * </div>
1582
- * ```
1583
- *
1584
- * A press on a checkable proxy is dealt to the real control, and so is the
1585
- * focus: state management, validation and form submission then all happen
1586
- * where the value lives. A proxy that says what its press does — a button
1587
- * carrying `command="--navi-check"` — answers the press itself instead.
1588
- *
1589
- * Note: an alternative design would be to require users to always instantiate
1590
- * the input explicitly — e.g. `<Selectable.Input headless />` when they don't
1591
- * want to display it. That would remove the need for the proxy mechanism
1592
- * entirely. For now we keep the proxy pattern.
1593
- */
1594
-
1595
-
1596
- /**
1597
- * Given a proxy element, returns the real control it represents.
1598
- * Returns `null` when `el` is not a proxy.
1599
- */
1600
- const findControlProxyTarget = (el) => {
1601
- const proxyFor = el.getAttribute("navi-control-proxy-for");
1602
- if (!proxyFor) {
1603
- return null;
1604
- }
1605
- return document.getElementById(proxyFor);
1606
- };
1607
-
1608
- // Shared: asked on every pseudo state change of every box, and almost always
1609
- // empty.
1610
- const NO_PROXIES = Object.freeze([]);
1611
- /**
1612
- * Given a real control element, returns every proxy that visually represents
1613
- * it — a control can have more than one (an "enable"/"disable" button pair for
1614
- * one radio, for instance).
1615
- *
1616
- * Answered from the controller registry rather than the document: every proxy
1617
- * declares itself through the `navi-control-proxy-for` prop, so the registry
1618
- * knows them all, while asking the document means walking it in full for each
1619
- * of the (overwhelmingly many) controls that have no proxy at all.
1620
- *
1621
- * Returns an empty array when no proxy exists for `el`.
1622
- */
1623
- const findControlProxies = (el) => {
1624
- if (!el.id) {
1625
- return NO_PROXIES;
1626
- }
1627
- const proxyControllerSet = findProxyControllers(el.id);
1628
- if (!proxyControllerSet) {
1629
- return NO_PROXIES;
1630
- }
1631
- const proxyElements = [];
1632
- for (const proxyController of proxyControllerSet) {
1633
- const proxyElement = proxyController.ref.current;
1634
- if (proxyElement) {
1635
- proxyElements.push(proxyElement);
1636
- }
1637
- }
1638
- return proxyElements;
1639
- };
1640
-
1641
- /**
1642
- * Given a real control element, returns the proxy a gesture on the control
1643
- * lands on — the one thing said about the control is drawn on.
1644
- *
1645
- * Use when you need a single visible stand-in for the real control — anchoring
1646
- * a callout, for instance. Anything notifying proxies of a state change wants
1647
- * `findControlProxies` instead, so a control represented by several of them
1648
- * updates all of them.
1649
- *
1650
- * A proxy the pointer cannot reach is drawn for the control without standing
1651
- * for it: the surface around it takes the presses for everything it holds, so
1652
- * that surface is where a refusal about the control belongs — not a box inside
1653
- * it the finger never has to find. A selectable list row whose whole area is
1654
- * the click target is exactly that arrangement (see `selectableArea`), and it
1655
- * is read from the arrangement itself rather than from a flag repeating it:
1656
- * where a gesture can land IS pointer-events.
1657
- *
1658
- * Returns `null` when no proxy stands for `el`.
1659
- */
1660
- const findControlProxy = (el) => {
1661
- for (const proxyElement of findControlProxies(el)) {
1662
- if (getComputedStyle(proxyElement).pointerEvents === "none") {
1663
- continue;
1664
- }
1665
- return proxyElement;
1666
- }
1667
- return null;
1668
- };
1669
-
1670
- const addInputEffect = (
1671
- input,
1672
- callback,
1673
- { waitForChange = false, debounce = 0, debugInteraction = () => {} } = {},
1674
- ) => {
1675
- const getState =
1676
- input.type === "checkbox" || input.type === "radio"
1677
- ? () => input.checked
1678
- : () => input.value;
1679
-
1680
- if (waitForChange) {
1681
- return listenInputStateChange(input, callback, { getState });
1682
- }
1683
-
1684
- const [teardown, addTeardown] = createPubSub();
1685
- let currentState = getState();
1686
- let timeout;
1687
- let debounceTimeout;
1688
- let onEvent;
1689
- if (debounce) {
1690
- onEvent = (e, { skipDebounce } = {}) => {
1691
- clearTimeout(timeout);
1692
- clearTimeout(debounceTimeout);
1693
- const state = getState();
1694
- if (state === currentState) {
1695
- debugInteraction(
1696
- e,
1697
- `interaction ignored (state unchanged: "${state}")`,
1698
- );
1699
- return;
1700
- }
1701
-
1702
- if (skipDebounce) {
1703
- debugInteraction(e, `skip debounce, callback called with "${state}"`);
1704
- if (callback(e) !== false) {
1705
- currentState = state;
1706
- }
1707
- } else {
1708
- debugInteraction(
1709
- e,
1710
- `debounced ${debounce}ms, pending callback with "${state}"`,
1711
- );
1712
- debounceTimeout = setTimeout(() => {
1713
- debugInteraction(
1714
- e,
1715
- `debounce elapsed, callback called with "${state}"`,
1716
- );
1717
- if (callback(e) !== false) {
1718
- currentState = state;
1719
- }
1720
- }, debounce);
1721
- }
1722
- };
1723
- // no need to wait for change events (blur, enter key)
1724
- // we consider this as strong interactions requesting an immediate response
1725
- const stop = listenInputStateChange(
1726
- input,
1727
- (e) => {
1728
- onEvent(e, { skipDebounce: true });
1729
- },
1730
- { getState, changeOnEnter: true },
1731
- );
1732
- addTeardown(() => {
1733
- stop();
1734
- });
1735
- } else {
1736
- onEvent = (e) => {
1737
- clearTimeout(timeout);
1738
- const state = getState();
1739
- if (state === currentState) {
1740
- debugInteraction(
1741
- e,
1742
- `interaction ignored (state unchanged: "${state}")`,
1743
- );
1744
- return;
1745
- }
1746
- debugInteraction(e, `callback called with "${state}"`);
1747
- if (callback(e) !== false) {
1748
- currentState = state;
1749
- }
1750
- };
1751
- // Autocomplete, programmatic changes, form restoration
1752
- input.addEventListener("change", onEvent);
1753
- addTeardown(() => {
1754
- input.removeEventListener("change", onEvent);
1755
- });
1756
- }
1757
-
1758
- const onAsyncEvent = (e, options) => {
1759
- debugInteraction(e, `async event, scheduling callback`);
1760
- timeout = setTimeout(() => {
1761
- onEvent(e, options);
1762
- }, 0);
1763
- };
1764
-
1765
- // Standard user input (typing)
1766
- const onInput = (e) => {
1767
- onEvent(e);
1768
- };
1769
- input.addEventListener("input", onInput);
1770
- addTeardown(() => {
1771
- input.removeEventListener("input", onInput);
1772
- });
1773
-
1774
- // Form reset - need to check the form
1775
- const form = input.form;
1776
- if (form) {
1777
- // Form reset happens asynchronously, check value after reset completes
1778
- form.addEventListener("reset", onAsyncEvent);
1779
- addTeardown(() => {
1780
- form.removeEventListener("reset", onAsyncEvent);
1781
- });
1782
- }
1783
-
1784
- // Paste events (some browsers need special handling)
1785
- input.addEventListener("paste", onEvent);
1786
- addTeardown(() => {
1787
- input.removeEventListener("paste", onEvent);
1788
- });
1789
-
1790
- input.addEventListener("navi_ui_state_change", (e) => {
1791
- // radios are unchecked by an internal setUIState call when another radio is checked.
1792
- // navi_ui_state_change is dispatched whenever setUIState changes state, so we
1793
- // listen here to keep currentState in sync — otherwise input_effect thinks the
1794
- // radio is still checked and ignores the next user click as "state unchanged".
1795
- if (input.type === "radio") {
1796
- currentState = e.detail.value;
1797
- }
1798
- const clearEvent = findEvent(
1799
- e,
1800
- (eInChain) =>
1801
- eInChain.type === "navi_set_ui_state" && eInChain.detail.isClear,
1802
- );
1803
- const isClear = Boolean(clearEvent);
1804
- if (isClear) {
1805
- // "navi_clear" behaves like an async event
1806
- // a bit like form reset because
1807
- // our action will be updated async after the component re-renders
1808
- // and we need to wait that to happen to properly call action with the right value
1809
- debugInteraction(e, `navi_clear received, scheduling callback`);
1810
- onAsyncEvent(e, { skipDebounce: true });
1811
- }
1812
- });
1813
-
1814
- return teardown;
1815
- };
1816
-
1817
- const listenInputStateChange = (
1818
- input,
1819
- callback,
1820
- { getState, changeOnEnter },
1821
- ) => {
1822
- const [teardown, addTeardown] = createPubSub();
1823
-
1824
- let stateAtInteraction;
1825
- const oninput = () => {
1826
- stateAtInteraction = undefined;
1827
- };
1828
- const onkeydown = (e) => {
1829
- if (e.key === "Enter") {
1830
- /**
1831
- * Browser trigger a "change" event right after the enter is pressed
1832
- * if the input value has changed.
1833
- * We need to prevent the next change event otherwise we would request action twice
1834
- */
1835
- stateAtInteraction = getState();
1836
- if (changeOnEnter) {
1837
- onchange(e);
1838
- }
1839
- }
1840
- if (e.key === "Escape") {
1841
- /**
1842
- * Browser trigger a "change" event right after the escape is pressed
1843
- * if the input value has changed.
1844
- * We need to prevent the next change event otherwise we would request action when
1845
- * we actually want to cancel
1846
- */
1847
- stateAtInteraction = getState();
1848
- }
1849
- };
1850
- const onchange = (e) => {
1851
- if (stateAtInteraction !== undefined && getState() === stateAtInteraction) {
1852
- stateAtInteraction = undefined;
1853
- return;
1854
- }
1855
- callback(e);
1856
- };
1857
- input.addEventListener("input", oninput);
1858
- input.addEventListener("keydown", onkeydown);
1859
- input.addEventListener("change", onchange);
1860
- addTeardown(() => {
1861
- input.removeEventListener("input", oninput);
1862
- input.removeEventListener("keydown", onkeydown);
1863
- input.removeEventListener("change", onchange);
1864
- });
1865
-
1866
- {
1867
- // Handle programmatic value changes that don't trigger browser change events
1868
- //
1869
- // Problem: When input values are set programmatically (not by user typing),
1870
- // browsers don't fire the 'change' event. However, our application logic
1871
- // still needs to detect these changes.
1872
- //
1873
- // Example scenario:
1874
- // 1. User starts editing (letter key pressed, value set programmatically)
1875
- // 2. User doesn't type anything additional (this is the key part)
1876
- // 3. User clicks outside to finish editing
1877
- // 4. Without this code, no change event would fire despite the fact that the input value did change from its original state
1878
- //
1879
- // This distinction is crucial because:
1880
- //
1881
- // - If the user typed additional text after the initial programmatic value,
1882
- // the browser would fire change events normally
1883
- // - But when they don't type anything else, the browser considers it as "no user interaction"
1884
- // even though the programmatic initial value represents a meaningful change
1885
- //
1886
- // We achieve this by checking if the input value has changed between focus and blur without any user interaction
1887
- // if yes we fire the callback because input value did change
1888
- let stateAtStart = getState();
1889
- let interacted = false;
1890
-
1891
- const onfocus = () => {
1892
- interacted = false;
1893
- stateAtStart = getState();
1894
- };
1895
- const oninput = (e) => {
1896
- if (!e.isTrusted) {
1897
- // non trusted "input" events will be ignored by the browser when deciding to fire "change" event
1898
- // we ignore them too
1899
- return;
1900
- }
1901
- interacted = true;
1902
- };
1903
- const onblur = (e) => {
1904
- if (interacted) {
1905
- return;
1906
- }
1907
- if (stateAtStart === getState()) {
1908
- return;
1909
- }
1910
- callback(e);
1911
- };
1912
-
1913
- input.addEventListener("focus", onfocus);
1914
- input.addEventListener("input", oninput);
1915
- input.addEventListener("blur", onblur);
1916
- addTeardown(() => {
1917
- input.removeEventListener("focus", onfocus);
1918
- input.removeEventListener("input", oninput);
1919
- input.removeEventListener("blur", onblur);
1920
- });
1921
- }
1922
-
1923
- return teardown;
1924
- };
1925
-
1926
- const requestPseudoStateCheck = (element, detail) => {
1927
- dispatchInternalCustomEvent(
1928
- element,
1929
- "navi_pseudo_state_request_check",
1930
- detail,
1931
- );
1932
- // When a control has visible proxies mirroring its state (e.g. selectable
1933
- // radio with `navi-control-proxy-for`), re-check them too so they stay in
1934
- // sync with the real control.
1935
- for (const proxy of findControlProxies(element)) {
1936
- dispatchInternalCustomEvent(
1937
- proxy,
1938
- "navi_pseudo_state_request_check",
1939
- detail,
1940
- );
1941
- }
1942
- };
1943
- /**
1944
- * Called back whenever `element`'s pseudo state changes.
1945
- *
1946
- * Kept beside the element rather than announced to the DOM: an element that
1947
- * changes state has at most one or two interested parties, each known by name
1948
- * (the box drawing it, the accent color reading its computed style), and a
1949
- * CustomEvent costs its allocation and its capture/bubble walk whether anyone
1950
- * listens or not — paid on every element, on every state change. A lookup that
1951
- * finds nothing costs nothing.
1952
- *
1953
- * @param {Element} element
1954
- * @param {(pseudoState: object, oldPseudoState: object) => void} callback
1955
- * @returns {() => void} teardown
1956
- */
1957
- const subscribeToPseudoState = (element, callback) => {
1958
- let subscriberSet = pseudoStateSubscriberSetWeakMap.get(element);
1959
- if (!subscriberSet) {
1960
- subscriberSet = new Set();
1961
- pseudoStateSubscriberSetWeakMap.set(element, subscriberSet);
1962
- }
1963
- subscriberSet.add(callback);
1964
- return () => {
1965
- subscriberSet.delete(callback);
1966
- };
1967
- };
1968
- const pseudoStateSubscriberSetWeakMap = new WeakMap();
1969
- const notifyPseudoStateSubscribers = (element, value, oldValue) => {
1970
- const subscriberSet = pseudoStateSubscriberSetWeakMap.get(element);
1971
- if (!subscriberSet) {
1972
- return;
1973
- }
1974
- for (const subscriber of subscriberSet) {
1975
- subscriber(value, oldValue);
1976
- }
1977
- };
1978
-
1979
- const PSEUDO_CLASSES = {};
1980
- Object.assign(PSEUDO_CLASSES, {
1981
- ":valid": {
1982
- attribute: "data-valid",
1983
- test: (el) => el.matches(":valid"),
1984
- },
1985
- ":invalid": {
1986
- attribute: "data-invalid",
1987
- test: (el) => el.matches(":invalid"),
1988
- },
1989
- ":visited": {
1990
- attribute: "data-visited",
1991
- },
1992
- // Written by whoever knows the current url — a Link from its href, a Button
1993
- // from its route — so it lives here rather than with one of them.
1994
- ":-navi-href-current": {
1995
- attribute: "data-href-current",
1996
- },
1997
- });
1998
- const definePseudoClass = (pseudoClass, definition) => {
1999
- PSEUDO_CLASSES[pseudoClass] = definition;
2000
- };
2001
-
2002
- // On touch devices (hover: none), browsers synthesize mouseenter/mouseleave
2003
- // from touch events but never fire mouseleave when the finger lifts, leaving
2004
- // el.matches(":hover") stuck at true. This causes hover styles (e.g. input
2005
- // background highlight) to remain visible long after the user has stopped
2006
- // touching the element. Checking (hover: hover) lets us skip hover tracking
2007
- // entirely on touch-only devices where persistent hover makes no sense.
2008
- const hoverSupported = window.matchMedia("(hover: hover)").matches;
2009
- definePseudoClass(":hover", {
2010
- attribute: "data-hover",
2011
- setup: (el, callback) => {
2012
- if (!hoverSupported) {
2013
- return () => {};
2014
- }
2015
- const recheckProxy = (e) => {
2016
- for (const proxy of findControlProxies(el)) {
2017
- requestPseudoStateCheck(proxy, { event: e });
2018
- }
2019
- };
2020
- const recheckProxyTarget = (e) => {
2021
- const proxyTarget = findControlProxyTarget(el);
2022
- if (proxyTarget) {
2023
- requestPseudoStateCheck(proxyTarget, { event: e });
2024
- }
2025
- };
2026
- let onmouseenter = (e) => {
2027
- callback();
2028
- recheckProxy(e);
2029
- recheckProxyTarget(e);
2030
- };
2031
- let onmouseleave = (e) => {
2032
- callback();
2033
- recheckProxy(e);
2034
- recheckProxyTarget(e);
2035
- };
2036
-
2037
- if (el.tagName === "LABEL") {
2038
- // input.matches(":hover") is true when hovering the label
2039
- // so when label is hovered/not hovered we need to recheck the input too
2040
- const recheckInput = (e) => {
2041
- if (el.htmlFor) {
2042
- const input = document.getElementById(el.htmlFor);
2043
- if (!input) {
2044
- // cannot find the input for this label in the DOM
2045
- return;
2046
- }
2047
- requestPseudoStateCheck(input, { event: e });
2048
- return;
2049
- }
2050
- const input = el.querySelector("input, textarea, select");
2051
- if (!input) {
2052
- // label does not contain an input
2053
- return;
2054
- }
2055
- requestPseudoStateCheck(input, { event: e });
2056
- };
2057
- const _onmouseenter = onmouseenter;
2058
- onmouseenter = (e) => {
2059
- recheckInput(e);
2060
- _onmouseenter(e);
2061
- };
2062
- const _onmouseleave = onmouseleave;
2063
- onmouseleave = (e) => {
2064
- recheckInput(e);
2065
- _onmouseleave(e);
2066
- };
2067
- }
2068
-
2069
- el.addEventListener("mouseenter", onmouseenter);
2070
- el.addEventListener("mouseleave", onmouseleave);
2071
- return () => {
2072
- el.removeEventListener("mouseenter", onmouseenter);
2073
- el.removeEventListener("mouseleave", onmouseleave);
2074
- };
2075
- },
2076
- test: (el) => {
2077
- if (!hoverSupported) {
2078
- return false;
2079
- }
2080
- if (el.matches(":hover")) {
2081
- return true;
2082
- }
2083
- for (const proxy of findControlProxies(el)) {
2084
- if (proxy.matches(":hover")) {
2085
- return true;
2086
- }
2087
- }
2088
- return false;
2089
- },
2090
- });
2091
- definePseudoClass(":disabled", {
2092
- attribute: "data-disabled",
2093
- add: (el) => {
2094
- if (
2095
- el.tagName === "BUTTON" ||
2096
- el.tagName === "INPUT" ||
2097
- el.tagName === "SELECT" ||
2098
- el.tagName === "TEXTAREA"
2099
- ) {
2100
- el.disabled = true;
2101
- }
2102
- },
2103
- remove: (el) => {
2104
- if (
2105
- el.tagName === "BUTTON" ||
2106
- el.tagName === "INPUT" ||
2107
- el.tagName === "SELECT" ||
2108
- el.tagName === "TEXTAREA"
2109
- ) {
2110
- el.disabled = false;
2111
- }
2112
- },
2113
- });
2114
- definePseudoClass(":read-only", {
2115
- attribute: "data-readonly",
2116
- add: (el) => {
2117
- if (
2118
- el.tagName === "INPUT" ||
2119
- el.tagName === "SELECT" ||
2120
- el.tagName === "TEXTAREA"
2121
- ) {
2122
- if (el.type === "checkbox" || el.type === "radio") {
2123
- // there is no readOnly for checkboxes/radios
2124
- return;
2125
- }
2126
- // el.readOnly = true;
2127
- }
2128
- },
2129
- remove: (el) => {
2130
- if (
2131
- el.tagName === "INPUT" ||
2132
- el.tagName === "SELECT" ||
2133
- el.tagName === "TEXTAREA"
2134
- ) {
2135
- if (el.type === "checkbox" || el.type === "radio") {
2136
- // there is no readOnly for checkboxes/radios
2137
- return;
2138
- }
2139
- // el.readOnly = false;
2140
- }
2141
- },
2142
- });
2143
- definePseudoClass(":checked", {
2144
- attribute: "data-checked",
2145
- setup: (el, callback) => {
2146
- if (el.type === "checkbox") {
2147
- // Listen to user interactions
2148
- el.addEventListener("input", callback);
2149
- // Intercept programmatic changes to .checked property
2150
- const originalDescriptor = Object.getOwnPropertyDescriptor(
2151
- HTMLInputElement.prototype,
2152
- "checked",
2153
- );
2154
- Object.defineProperty(el, "checked", {
2155
- get: originalDescriptor.get,
2156
- set(value) {
2157
- originalDescriptor.set.call(this, value);
2158
- callback();
2159
- },
2160
- configurable: true,
2161
- });
2162
- return () => {
2163
- // Restore original property descriptor
2164
- Object.defineProperty(el, "checked", originalDescriptor);
2165
- el.removeEventListener("input", callback);
2166
- };
2167
- }
2168
- if (el.type === "radio") {
2169
- // Listen to changes on the radio
2170
- el.addEventListener("input", callback);
2171
- // Intercept programmatic changes to .checked property
2172
- const originalDescriptor = Object.getOwnPropertyDescriptor(
2173
- HTMLInputElement.prototype,
2174
- "checked",
2175
- );
2176
- Object.defineProperty(el, "checked", {
2177
- get: originalDescriptor.get,
2178
- set(value) {
2179
- originalDescriptor.set.call(this, value);
2180
- callback();
2181
- },
2182
- configurable: true,
2183
- });
2184
- return () => {
2185
- el.removeEventListener("input", callback);
2186
- // Restore original property descriptor
2187
- Object.defineProperty(el, "checked", originalDescriptor);
2188
- };
2189
- }
2190
- if (el.tagName === "INPUT") {
2191
- el.addEventListener("input", callback);
2192
- return () => {
2193
- el.removeEventListener("input", callback);
2194
- };
2195
- }
2196
- return () => {};
2197
- },
2198
- test: (el) => el.matches(":checked"),
2199
- });
2200
- definePseudoClass(":active", {
2201
- attribute: "data-active",
2202
- setup: (el, callback) => {
2203
- // I'ts recommended to use :-navi-pressed over :active for interactive elements.
2204
- const onPointerDown = () => {
2205
- const onRelease = () => {
2206
- document.removeEventListener("pointercancel", onRelease, true);
2207
- document.removeEventListener("pointerup", onRelease, true);
2208
- callback();
2209
- };
2210
- document.addEventListener("pointercancel", onRelease, true);
2211
- document.addEventListener("pointerup", onRelease, true);
2212
- callback();
2213
- };
2214
- el.addEventListener("pointerdown", onPointerDown);
2215
- return () => {
2216
- el.removeEventListener("pointerdown", onPointerDown);
2217
- };
2218
- },
2219
- test: (el) => el.matches(":active"),
2220
- });
2221
-
2222
- // The current input modality: true after a keyboard navigation key (arrow keys,
2223
- // Escape, Enter, Ctrl, Alt, Shift, Space — Space ignored on editable fields),
2224
- // false after a pointer interaction. Updated by the listeners in the
2225
- // focus_classes block below. At module scope so isMatchingFocusVisible (used
2226
- // here and in control_hooks.jsx) can read it.
2227
- let keyboardNavigationUsed = false;
2228
-
2229
- // HOW FOCUS-VISIBLE IS DECIDED (the details behind isMatchingFocusVisible)
2230
- //
2231
- // Two rules, depending on what `el` is:
2232
- //
2233
- // 1. An EDITABLE target (text-ish input, textarea, contenteditable — anything
2234
- // whose whole point is keyboard input, see isEditableTarget) shows its ring
2235
- // whenever it holds the focus, however the focus arrived — mouse,
2236
- // programmatic, even a focus({ focusVisible: false }). Being focused, for
2237
- // such a field, means being about to type, and that is what the ring
2238
- // announces. Its check is on :focus rather than :focus-visible on purpose:
2239
- // the native :focus-visible obeys the focusVisible option, which callers
2240
- // set from the modality without knowing what they are focusing.
2241
- //
2242
- // 2. Anything else needs BOTH the native :focus-visible match AND the current
2243
- // modality being keyboard (`keyboardNavigationUsed`).
2244
- //
2245
- // The native match alone cannot be trusted, because we routinely take the
2246
- // pointer out of the browser's hands: a picker opens on mousedown and calls
2247
- // preventDefault() so the browser does not move focus itself (see
2248
- // picker_custom.jsx). The browser therefore never registers that a pointer
2249
- // was what moved focus, and whatever focus-visible state the previous
2250
- // keyboard interaction left behind stays true — even across the
2251
- // programmatic focus({ focusVisible: false }) that follows. Close a picker
2252
- // with Escape (ring on the trigger, rightly) and click it open again: the
2253
- // popup's own focusable would come up ringed, from a mouse press.
2254
- //
2255
- // `keyboardNavigationUsed` has no such blind spot — it is set by navigation
2256
- // keydowns and cleared by pointerdown, whatever anyone prevents afterwards
2257
- // — so it is the authority for everything rule 1 does not cover.
2258
- //
2259
- // Ring INHERITANCE (a controlled element ringing because its aria-controls
2260
- // controller is focused) stays gated on the keyboard modality even for an
2261
- // editable controller — see hasIndirectFocus: propagating a ring promises
2262
- // keyboard shortcuts will drive the controlled element, a promise that only
2263
- // holds once a physical keyboard has actually been used.
2264
- /**
2265
- * Whether `el` should currently show a focus ring — the enriched
2266
- * :focus-visible behind every [data-focus-visible] navi renders.
2267
- * Use this instead of a bare el.matches(":focus-visible") wherever
2268
- * focus-visible is evaluated; the comment above details the rules.
2269
- * @param {Element} el
2270
- * @returns {boolean}
2271
- */
2272
- const isMatchingFocusVisible = (el) => {
2273
- if (isEditableTarget(el)) {
2274
- return el.matches(":focus");
2275
- }
2276
- if (!el.matches(":focus-visible")) {
2277
- return false;
2278
- }
2279
- if (!keyboardNavigationUsed) {
2280
- return false;
2281
- }
2282
- return true;
2283
- };
2284
-
2285
- // Elements that invite keyboard input: focusing one — even with the mouse —
2286
- // means the user is about to type, so they always warrant a visible focus.
2287
- // Also used to ignore the Space key as a navigation key while typing, and by
2288
- // programmatic focus (focus_transfer.js) to pass focusVisible: true so the
2289
- // native :focus-visible agrees with the ring rule 1 above draws.
2290
- const EDITABLE_INPUT_TYPE_SET = new Set([
2291
- "text",
2292
- "search",
2293
- "url",
2294
- "email",
2295
- "password",
2296
- "tel",
2297
- "number",
2298
- "date",
2299
- "time",
2300
- "datetime-local",
2301
- "month",
2302
- "week",
2303
- ]);
2304
- const isEditableTarget = (target) => {
2305
- if (!target) {
2306
- return false;
2307
- }
2308
- const tag = target.tagName;
2309
- if (tag === "TEXTAREA") {
2310
- return !target.readOnly;
2311
- }
2312
- if (tag === "INPUT") {
2313
- if (!target.type || EDITABLE_INPUT_TYPE_SET.has(target.type)) {
2314
- return !target.readOnly;
2315
- }
2316
- }
2317
- if (target.isContentEditable) {
2318
- return true;
2319
- }
2320
- return false;
2321
- };
2322
-
2323
- // The current modality, for code deciding whether something it is about to
2324
- // focus should show a ring — a slide arriving, a popup opening. The question is
2325
- // "was the user on the keyboard when this was asked for", which is what this
2326
- // flag says; the element that happens to hold the focus right now says nothing
2327
- // about it (it may have been focused programmatically, ring or no ring, by the
2328
- // travel before this one).
2329
- const isKeyboardModality = () => keyboardNavigationUsed;
2330
-
2331
- {
2332
- // We implement :focus and :focus-visible with enriched semantics:
2333
- // an element is considered focused not only when it natively has focus, but also
2334
- // when a "focus proxy" element has focus (e.g. a read-only range input delegates
2335
- // focus to a sibling span) or when a controlling element has focus (e.g. a combobox
2336
- // input with aria-controls pointing to a listbox — the listbox should appear focused
2337
- // while the input is focused).
2338
- //
2339
- // We intentionally reuse the native :focus / :focus-visible names rather than
2340
- // introducing new navi-specific pseudo-classes (e.g. :-navi-focus). This is a
2341
- // deliberate exception: all existing CSS and code written as [data-focus] or
2342
- // [data-focus-visible] automatically benefits from the enriched behavior without
2343
- // any changes. A separate navi-specific class would require updating every
2344
- // component.
2345
- //
2346
- // When a controller element (e.g. combobox input) gains or loses focus,
2347
- // notify the elements it controls via aria-controls so they re-check their
2348
- // focus state. `requestPseudoStateCheck` also re-checks the controlled
2349
- // element's proxy (if any), so the visible proxy mirrors the hidden real
2350
- // input's inherited focus.
2351
- const notifyAriaControlled = (el, e) => {
2352
- const controlledIds = el.getAttribute("aria-controls");
2353
- if (!controlledIds) {
2354
- return;
2355
- }
2356
- for (const id of controlledIds.split(" ")) {
2357
- const controlled = document.getElementById(id);
2358
- if (controlled) {
2359
- requestPseudoStateCheck(controlled, { event: e });
2360
- }
2361
- }
2362
- };
2363
- // Tracks whether the user has pressed a keyboard navigation key (arrow keys,
2364
- // Escape, Enter, Ctrl, Alt, Shift, Space) since the last pointer interaction.
2365
- // Space is ignored when the target is an editable field.
2366
- // This flag is used to gate focus-visible inheritance via aria-controls:
2367
- // on mobile (or when the user hasn't used keyboard nav yet) an input that
2368
- // controls a radio should not cause the radio to show a focus ring.
2369
- // (Declared at module scope — see keyboardNavigationUsed above.)
2370
- const NAVIGATION_KEY_SET = new Set([
2371
- "ArrowUp",
2372
- "ArrowDown",
2373
- "ArrowLeft",
2374
- "ArrowRight",
2375
- "Escape",
2376
- "Enter",
2377
- "Control",
2378
- "Alt",
2379
- "Shift",
2380
- " ",
2381
- "Tab",
2382
- ]);
2383
- document.addEventListener(
2384
- "keydown",
2385
- (e) => {
2386
- if (!NAVIGATION_KEY_SET.has(e.key)) {
2387
- return;
2388
- }
2389
- if (e.key === " " && isEditableTarget(e.target)) {
2390
- return;
2391
- }
2392
- keyboardNavigationUsed = true;
2393
- },
2394
- { capture: true },
2395
- );
2396
- document.addEventListener(
2397
- "pointerdown",
2398
- () => {
2399
- keyboardNavigationUsed = false;
2400
- },
2401
- { capture: true },
2402
- );
2403
-
2404
- // A keystroke flips keyboardNavigationUsed, which can turn :focus-visible on —
2405
- // but only for the element that holds focus, directly or through aria-controls
2406
- // / a proxy. Pressing a key cannot reveal a focus ring on an unfocused element.
2407
- // So a single shared handler re-checks just that focus chain (the active
2408
- // element, what it controls, and its proxy — the last two via
2409
- // requestPseudoStateCheck / notifyAriaControlled). This runs in the bubble
2410
- // phase, after the capture-phase listener above has updated the flag.
2411
- //
2412
- // The alternative — each registered :focus-visible element adding its own
2413
- // document keydown listener that re-tests itself — makes one keypress cost
2414
- // O(number-of-boxes) full-document [aria-controls] / proxy queries, since every
2415
- // unfocused element falls through matches(":focus-visible") into hasIndirectFocus.
2416
- const recheckFocusChainOnKey = (e) => {
2417
- const active = document.activeElement;
2418
- if (!active || active === document.body) {
2419
- return;
2420
- }
2421
- requestPseudoStateCheck(active, { event: e });
2422
- notifyAriaControlled(active, e);
2423
- };
2424
- document.addEventListener("keydown", recheckFocusChainOnKey);
2425
- document.addEventListener("keyup", recheckFocusChainOnKey);
2426
-
2427
- // Returns true when el holds focus indirectly — either because a controlling
2428
- // element (aria-controls) has focus, or because el is a proxy whose target
2429
- // is itself controlled by a focused element.
2430
- const hasIndirectFocus = (el, { requireFocusVisible = false } = {}) => {
2431
- // No ring inheritance without a keyboard: an editable target draws its own
2432
- // ring on any focus (see isMatchingFocusVisible), but propagating that ring
2433
- // to a controlled element (aria-controls) is a promise that keyboard
2434
- // shortcuts will drive it — a promise that holds only once a physical
2435
- // keyboard has actually been used. On touch devices the flag stays false
2436
- // and a focused search input keeps its ring to itself.
2437
- if (requireFocusVisible && !keyboardNavigationUsed) {
2438
- return false;
2439
- }
2440
- // A controller/proxy counts as focused for inheritance via the same rule
2441
- // used everywhere: :focus for plain inheritance, isMatchingFocusVisible for
2442
- // the focus-visible variant (so a mouse-focused controller doesn't propagate
2443
- // a ring).
2444
- const isFocusedTarget = (target) =>
2445
- requireFocusVisible
2446
- ? isMatchingFocusVisible(target)
2447
- : target.matches(":focus");
2448
- // Both branches of isFocusedTarget rest on :focus / :focus-visible, and only
2449
- // one element in the document can match those: document.activeElement. So
2450
- // the single controller worth testing is known upfront — asking the document
2451
- // for every [aria-controls] would collect candidates that cannot qualify,
2452
- // once per element and again on every re-check, on a document each new
2453
- // element makes bigger.
2454
- const isControlledBy = (target) => {
2455
- const id = target.id;
2456
- if (!id) {
2457
- return false;
2458
- }
2459
- const activeElement = document.activeElement;
2460
- if (!activeElement || activeElement === document.body) {
2461
- return false;
2462
- }
2463
- if (!activeElement.matches(`[aria-controls~="${id}"]`)) {
2464
- return false;
2465
- }
2466
- // A controller inside the element it controls means focus is already
2467
- // native (:focus-within) — nothing to inherit.
2468
- if (target.contains(activeElement)) {
2469
- return false;
2470
- }
2471
- return isFocusedTarget(activeElement);
2472
- };
2473
- if (isControlledBy(el)) {
2474
- return true;
2475
- }
2476
- const proxyTarget = findControlProxyTarget(el);
2477
- if (proxyTarget) {
2478
- if (isFocusedTarget(proxyTarget)) {
2479
- return true;
2480
- }
2481
- if (isControlledBy(proxyTarget)) {
2482
- return true;
2483
- }
2484
- }
2485
- return false;
2486
- };
2487
-
2488
- // One registration per element for everything focus-related, shared by
2489
- // :focus, :focus-visible and :focus-within: they all react to the same
2490
- // focusin/focusout, and they all re-check through the same callback (see
2491
- // initPseudoStyles), which the Set turns into one call.
2492
- const focusTrackingWeakMap = new WeakMap();
2493
- const trackFocus = (el, callback) => {
2494
- let tracking = focusTrackingWeakMap.get(el);
2495
- if (!tracking) {
2496
- const callbackSet = new Set();
2497
- const onFocusChange = (e) => {
2498
- for (const trackedCallback of callbackSet) {
2499
- trackedCallback();
2500
- }
2501
- notifyAriaControlled(el, e);
2502
- };
2503
- el.addEventListener("focusin", onFocusChange);
2504
- el.addEventListener("focusout", onFocusChange);
2505
- tracking = {
2506
- callbackSet,
2507
- teardown: () => {
2508
- el.removeEventListener("focusin", onFocusChange);
2509
- el.removeEventListener("focusout", onFocusChange);
2510
- focusTrackingWeakMap.delete(el);
2511
- },
2512
- };
2513
- focusTrackingWeakMap.set(el, tracking);
2514
- observeAriaControls();
2515
- }
2516
- tracking.callbackSet.add(callback);
2517
- return () => {
2518
- tracking.callbackSet.delete(callback);
2519
- if (tracking.callbackSet.size === 0) {
2520
- tracking.teardown();
2521
- }
2522
- };
2523
- };
2524
- // When aria-controls changes on a focused element, what it used to control
2525
- // and what it controls now both re-check their inherited focus. One observer
2526
- // on the document rather than one per tracked element: the attribute changes
2527
- // rarely, on few elements, while thousands are tracked — and it can be set
2528
- // after the element was, so "has it at setup" would miss it.
2529
- let ariaControlsObserver = null;
2530
- const observeAriaControls = () => {
2531
- if (ariaControlsObserver) {
2532
- return;
2533
- }
2534
- ariaControlsObserver = new MutationObserver((mutations) => {
2535
- for (const mutation of mutations) {
2536
- const el = mutation.target;
2537
- if (!focusTrackingWeakMap.has(el)) {
2538
- continue;
2539
- }
2540
- if (!el.matches(":focus-within")) {
2541
- continue;
2542
- }
2543
- const oldIds = (mutation.oldValue || "").split(" ").filter(Boolean);
2544
- for (const id of oldIds) {
2545
- const controlled = document.getElementById(id);
2546
- if (controlled) {
2547
- requestPseudoStateCheck(controlled, {});
2548
- }
2549
- }
2550
- notifyAriaControlled(el, {});
2551
- }
2552
- });
2553
- ariaControlsObserver.observe(document.documentElement, {
2554
- subtree: true,
2555
- attributes: true,
2556
- attributeFilter: ["aria-controls"],
2557
- attributeOldValue: true,
2558
- });
2559
- };
2560
-
2561
- definePseudoClass(":focus", {
2562
- attribute: "data-focus",
2563
- setup: trackFocus,
2564
- test: (el) => {
2565
- if (el.matches(":focus")) {
2566
- return true;
2567
- }
2568
- if (hasIndirectFocus(el)) {
2569
- return true;
2570
- }
2571
- return false;
2572
- },
2573
- });
2574
- definePseudoClass(":focus-visible", {
2575
- attribute: "data-focus-visible",
2576
- // No per-element keydown/keyup listener: the shared recheckFocusChainOnKey
2577
- // handler re-checks the focused element (the only one a keystroke can turn
2578
- // focus-visible) so a keypress stays O(1), not O(number-of-boxes).
2579
- setup: trackFocus,
2580
- test: (el) => {
2581
- if (isMatchingFocusVisible(el)) {
2582
- return true;
2583
- }
2584
- if (hasIndirectFocus(el, { requireFocusVisible: true })) {
2585
- return true;
2586
- }
2587
- return false;
2588
- },
2589
- });
2590
- definePseudoClass(":focus-within", {
2591
- attribute: "data-focus-within",
2592
- setup: trackFocus,
2593
- test: (el) => {
2594
- if (el.matches(":focus-within")) {
2595
- return true;
2596
- }
2597
- if (hasIndirectFocus(el)) {
2598
- return true;
2599
- }
2600
- if (el.contains(document.activeElement)) {
2601
- // for some reason :focus-within sometimes is false while focus is within...
2602
- // (popover with chrome for some reason)
2603
- return true;
2604
- }
2605
- return false;
2606
- },
2607
- });
2608
- }
2609
-
2610
- Object.assign(PSEUDO_CLASSES, {
2611
- ":-navi-pointed": {
2612
- attribute: "data-pointed",
2613
- },
2614
- ":-navi-pointed-by-mouse": {
2615
- attribute: "data-pointed-by-mouse",
2616
- },
2617
- ":-navi-pointed-by-keyboard": {
2618
- attribute: "data-pointed-by-keyboard",
2619
- },
2620
- ":-navi-pointed-by-proxy": {
2621
- attribute: "data-pointed-by-proxy",
2622
- },
2623
- ":-navi-selected": {
2624
- attribute: "data-selected",
2625
- },
2626
- ":-navi-loading": {
2627
- attribute: "data-loading",
2628
- },
2629
- ":-navi-status-info": {
2630
- attribute: "data-status-info",
2631
- },
2632
- ":-navi-status-success": {
2633
- attribute: "data-status-success",
2634
- },
2635
- ":-navi-status-warning": {
2636
- attribute: "data-status-warning",
2637
- },
2638
- ":-navi-status-error": {
2639
- attribute: "data-status-error",
2640
- },
2641
- ":-navi-expanded": {
2642
- attribute: "data-expanded",
2643
- },
2644
- ":-navi-void": {
2645
- attribute: "data-void",
2646
- },
2647
- "::highlight": {},
2648
- });
2649
- definePseudoClass(":-navi-has-value", {
2650
- attribute: "data-has-value",
2651
- setup: (el, callback) => {
2652
- const controlHost = findControlHost(el) || el;
2653
- return addInputEffect(controlHost, callback);
2654
- },
2655
- test: (el) => {
2656
- if (isControlHost(el)) {
2657
- const uiState = getUIStateFromElement(el);
2658
- if (uiState === undefined || uiState === "") {
2659
- return false;
2660
- }
2661
- return true;
2662
- }
2663
- if (el.value === "") {
2664
- return false;
2665
- }
2666
- return true;
2667
- },
2668
- });
2669
- {
2670
- const pressedElements = new WeakSet();
2671
- definePseudoClass(":-navi-pressed", {
2672
- attribute: "data-pressed",
2673
- setup: (el, callback) => {
2674
- // Prefer :-navi-pressed over :active for interactive elements because:
2675
- // - :active only tracks the primary (left) button; right-click and touch
2676
- // long-press do not trigger :active reliably across browsers.
2677
- // - :-navi-pressed explicitly ignores non-primary buttons (e.g. right-click)
2678
- // and correctly clears pressed state when a context menu opens on long-press,
2679
- // which would otherwise leave the element stuck in a pressed appearance.
2680
-
2681
- // Note: it might be tempting to use el.setPointerCapture() here so that pointerup
2682
- // always fires on el regardless of where the pointer is released. However,
2683
- // pointer capture routes all subsequent pointer events to the capturing element,
2684
- // which means any other element in the tree that expects to receive pointerup,
2685
- // mouseup, click, etc. after a pointerdown will silently not get them.
2686
- // For example a <label> that reacts to mousedown + click, or a third-party
2687
- // library that attaches its own listeners, would break because an ancestor
2688
- // grabbed the pointer out from under them.
2689
- // To avoid forcing every such element to declare an opt-out attribute
2690
- // (e.g. navi-own-pointer-capture) we simply listen on document instead,
2691
- // which is safe and does not interfere with anyone else's event flow.
2692
- const onPointerDown = (e) => {
2693
- if (e.button !== 0) {
2694
- // only left pointer (mouse left click, touch, pen)
2695
- return;
2696
- }
2697
- pressedElements.add(el);
2698
- const onRelease = () => {
2699
- pressedElements.delete(el);
2700
- document.removeEventListener("pointercancel", onRelease, true);
2701
- document.removeEventListener("pointerup", onRelease, true);
2702
- document.removeEventListener("contextmenu", onContextMenu, true);
2703
- callback();
2704
- };
2705
- const onContextMenu = (e) => {
2706
- // On touch devices, a long-press triggers the context menu.
2707
- // If the context menu is not prevented, it means it will open and the
2708
- // pointer events (pointerup, lostpointercapture) won't fire normally,
2709
- // leaving the element stuck in pressed state. We clear it manually.
2710
- // e.button === -1 means the event was synthesized from a long-press (not a real mouse click).
2711
- if (e.button === -1 && !e.defaultPrevented) {
2712
- pressedElements.delete(el);
2713
- document.removeEventListener("pointercancel", onRelease, true);
2714
- document.removeEventListener("pointerup", onRelease, true);
2715
- document.removeEventListener("contextmenu", onContextMenu, true);
2716
- callback();
2717
- }
2718
- };
2719
- document.addEventListener("pointercancel", onRelease, true);
2720
- document.addEventListener("pointerup", onRelease, true);
2721
- document.addEventListener("contextmenu", onContextMenu, true);
2722
- callback();
2723
- };
2724
- el.addEventListener("pointerdown", onPointerDown);
2725
- return () => {
2726
- el.removeEventListener("pointerdown", onPointerDown);
2727
- pressedElements.delete(el);
2728
- };
2729
- },
2730
- test: (el) => pressedElements.has(el),
2731
- });
2732
- }
2733
-
2734
- {
2735
- definePseudoClass(":-navi-drag-grabbed", {
2736
- attribute: "navi-drag-grabbed",
2737
- setup: (el, callback) => {
2738
- const onGrab = () => {
2739
- callback();
2740
- const onRelease = () => {
2741
- el.removeEventListener("navi_drag_release", onRelease);
2742
- callback();
2743
- };
2744
- el.addEventListener("navi_drag_release", onRelease);
2745
- };
2746
- el.addEventListener("navi_drag_grab", onGrab);
2747
- return () => {
2748
- el.removeEventListener("navi_drag_grab", onGrab);
2749
- };
2750
- },
2751
- test: (el) => el.hasAttribute("data-drag-grabbed"),
2752
- });
2753
- definePseudoClass(":-navi-dragging", {
2754
- attribute: "navi-dragging",
2755
- setup: (el, callback) => {
2756
- const onStart = () => {
2757
- callback();
2758
- const onRelease = () => {
2759
- el.removeEventListener("navi_drag_release", onRelease);
2760
- callback();
2761
- };
2762
- el.addEventListener("navi_drag_release", onRelease);
2763
- };
2764
- el.addEventListener("navi_drag_start", onStart);
2765
- return () => {
2766
- el.removeEventListener("navi_drag_start", onStart);
2767
- };
2768
- },
2769
- test: (el) => el.hasAttribute("data-dragging"),
2770
- });
2771
- }
2772
-
2773
- const EMPTY_STATE = {};
2774
- const elementToImpactWeakMap = new WeakMap();
2775
- const initPseudoStyles = (
2776
- element,
2777
- {
2778
- pseudoClasses,
2779
- pseudoState, // ":disabled", ":read-only", ":-navi-loading", etc...
2780
- effect,
2781
- elementToImpact = element,
2782
- elementListeningPseudoState,
2783
- },
2784
- ) => {
2785
- elementToImpactWeakMap.set(element, elementToImpact);
2786
- if (elementListeningPseudoState === element) {
2787
- console.warn(
2788
- `elementListeningPseudoState should not be the same as element to avoid infinite loop`,
2789
- );
2790
- elementListeningPseudoState = null;
2791
- }
2792
-
2793
- const proxyTarget = findControlProxyTarget(element);
2794
-
2795
- const onStateChange = (value, oldValue) => {
2796
- effect?.(value, oldValue);
2797
- if (elementListeningPseudoState) {
2798
- notifyPseudoStateSubscribers(
2799
- elementListeningPseudoState,
2800
- value,
2801
- oldValue,
2802
- );
2803
- }
2804
- // When this element's state changes, notify any proxy element that mirrors it
2805
- // so it can re-check and visually reflect the new state.
2806
- for (const proxy of findControlProxies(element)) {
2807
- requestPseudoStateCheck(proxy, {});
2808
- }
2809
- };
2810
-
2811
- if (!pseudoClasses || pseudoClasses.length === 0) {
2812
- onStateChange(EMPTY_STATE);
2813
- return () => {};
2814
- }
2815
-
2816
- const [teardown, addTeardown] = createPubSub();
2817
-
2818
- let state;
2819
- const checkPseudoClasses = () => {
2820
- let someChange = false;
2821
- const currentState = {};
2822
- for (const pseudoClass of pseudoClasses) {
2823
- const pseudoClassDefinition = PSEUDO_CLASSES[pseudoClass];
2824
- if (!pseudoClassDefinition) {
2825
- console.warn(`Unknown pseudo class: ${pseudoClass}`);
2826
- continue;
2827
- }
2828
- let currentValue;
2829
- if (
2830
- pseudoState &&
2831
- Object.hasOwn(pseudoState, pseudoClass) &&
2832
- pseudoState[pseudoClass] !== undefined
2833
- ) {
2834
- currentValue = pseudoState[pseudoClass];
2835
- } else {
2836
- const { test } = pseudoClassDefinition;
2837
- if (test) {
2838
- currentValue = test(element, pseudoState);
2839
- }
2840
- }
2841
- // If this element is a proxy for another (navi-control-proxy-for="targetId"),
2842
- // inherit the target's active pseudo-state when the element itself isn't in that state.
2843
- // We check the target's elementToImpact (not the target itself) because the
2844
- // data-* attribute may be set on a different element (e.g. pseudoStateSelector).
2845
- if (!currentValue && proxyTarget) {
2846
- const { attribute } = pseudoClassDefinition;
2847
- if (attribute) {
2848
- const targetElementToImpact =
2849
- elementToImpactWeakMap.get(proxyTarget) || proxyTarget;
2850
- if (targetElementToImpact.hasAttribute(attribute)) {
2851
- currentValue = true;
2852
- }
2853
- }
2854
- }
2855
- currentState[pseudoClass] = currentValue;
2856
- const oldValue = state ? state[pseudoClass] : undefined;
2857
- if (oldValue !== currentValue || !state) {
2858
- someChange = true;
2859
- const { attribute, add, remove } = pseudoClassDefinition;
2860
- if (currentValue) {
2861
- if (attribute) {
2862
- elementToImpact.setAttribute(attribute, "");
2863
- }
2864
- add?.(element);
2865
- } else {
2866
- if (attribute) {
2867
- elementToImpact.removeAttribute(attribute);
2868
- }
2869
- remove?.(element);
2870
- }
2871
- }
2872
- }
2873
- if (!someChange) {
2874
- return;
2875
- }
2876
- const oldState = state;
2877
- state = currentState;
2878
- onStateChange(state, oldState);
2879
- };
2880
-
2881
- addTeardown(
2882
- subscribeToPseudoState(element, (pseudoState, oldPseudoState) => {
2883
- state = pseudoState;
2884
- onStateChange(state, oldPseudoState);
2885
- }),
2886
- );
2887
- // One function for every way a re-check can be asked, so that setups
2888
- // registering it side by side (the focus tracking, for one) hold the same
2889
- // callback and call it once.
2890
- const requestCheck = () => {
2891
- checkPseudoClasses();
2892
- };
2893
- element.addEventListener("navi_pseudo_state_request_check", requestCheck);
2894
- addTeardown(() => {
2895
- element.removeEventListener(
2896
- "navi_pseudo_state_request_check",
2897
- requestCheck,
2898
- );
2899
- });
2900
-
2901
- for (const pseudoClass of pseudoClasses) {
2902
- const pseudoClassDefinition = PSEUDO_CLASSES[pseudoClass];
2903
- if (!pseudoClassDefinition) {
2904
- console.warn(`Unknown pseudo class: ${pseudoClass}`);
2905
- continue;
2906
- }
2907
- const { setup } = pseudoClassDefinition;
2908
- if (setup) {
2909
- const cleanup = setup(element, requestCheck);
2910
- addTeardown(cleanup);
2911
- }
2912
- }
2913
- checkPseudoClasses();
2914
- {
2915
- // just in case + catch use forcing them in chrome devtools
2916
- addTeardown(pollInDev(requestCheck));
2917
- }
2918
-
2919
- return teardown;
2920
- };
2921
-
2922
- const applyStyle = (
2923
- element,
2924
- style,
2925
- pseudoState,
2926
- pseudoNamedStyles,
2927
- preventInitialTransition,
2928
- ) => {
2929
- if (!element) {
2930
- return;
2931
- }
2932
- const styleToApply = getStyleToApply(style, pseudoState, pseudoNamedStyles);
2933
- // The same object comes back for every state change of a box whose inline
2934
- // style has no pseudo entry: nothing to write.
2935
- if (appliedStyleWeakMap.get(element) === styleToApply) {
2936
- return;
2937
- }
2938
- updateStyle(element, styleToApply, preventInitialTransition);
2939
- };
2940
-
2941
- const PSEUDO_STATE_DEFAULT = {};
2942
- const PSEUDO_NAMED_STYLES_DEFAULT = {};
2943
- const getStyleToApply = (styles, pseudoState, pseudoNamedStyles) => {
2944
- if (
2945
- !pseudoState ||
2946
- pseudoState === PSEUDO_STATE_DEFAULT ||
2947
- !pseudoNamedStyles ||
2948
- pseudoNamedStyles === PSEUDO_NAMED_STYLES_DEFAULT
2949
- ) {
2950
- return styles;
2951
- }
2952
- let style = styles;
2953
- for (const pseudoKey of Object.keys(pseudoNamedStyles)) {
2954
- if (!hasEveryState(pseudoState, getPseudoKeyRequiredStates(pseudoKey))) {
2955
- continue;
2956
- }
2957
- if (style === styles) {
2958
- style = { ...styles };
2959
- }
2960
- // Both sides are already normalized for CSS by the box; only the
2961
- // properties that compose (a press scale on top of a translate) go through
2962
- // a merge, the rest is a plain override.
2963
- const styleToAdd = pseudoNamedStyles[pseudoKey];
2964
- for (const key of Object.keys(styleToAdd)) {
2965
- const value = styleToAdd[key];
2966
- if (value === undefined) {
2967
- continue;
2968
- }
2969
- if (key === "transform" || key === "willChange") {
2970
- style[key] = mergeOneStyle(style[key], value, key, "css");
2971
- } else {
2972
- style[key] = value;
2973
- }
2974
- }
2975
- }
2976
- return style;
2977
- };
2978
-
2979
- // The state names a pseudo key asks for, parsed once: the same few keys come
2980
- // back on every state change of every box that has them. "::x" alone always
2981
- // matches; "::x:a:b" and ":a:b" ask for ":a" and ":b" — the state keys as
2982
- // checkPseudoClasses writes them, colon included.
2983
- const pseudoKeyRequiredStatesMap = new Map();
2984
- const getPseudoKeyRequiredStates = (pseudoKey) => {
2985
- const cached = pseudoKeyRequiredStatesMap.get(pseudoKey);
2986
- if (cached) {
2987
- return cached;
2988
- }
2989
- let requiredStates;
2990
- if (pseudoKey.startsWith("::")) {
2991
- const nextColonIndex = pseudoKey.indexOf(":", 2);
2992
- requiredStates =
2993
- nextColonIndex === -1
2994
- ? []
2995
- : getPseudoKeyRequiredStates(pseudoKey.slice(nextColonIndex));
2996
- } else {
2997
- const nextColonIndex = pseudoKey.indexOf(":", 1);
2998
- requiredStates =
2999
- nextColonIndex === -1
3000
- ? [pseudoKey]
3001
- : pseudoKey
3002
- .slice(1)
3003
- .split(":")
3004
- .map((state) => `:${state}`);
3005
- }
3006
- pseudoKeyRequiredStatesMap.set(pseudoKey, requiredStates);
3007
- return requiredStates;
3008
- };
3009
- const hasEveryState = (pseudoState, states) => {
3010
- for (const state of states) {
3011
- if (!pseudoState[state]) {
3012
- return false;
3013
- }
3014
- }
3015
- return true;
3016
- };
3017
-
3018
- // element → the style object last written to it, so the next one is written
3019
- // as a difference: the values that changed, the keys it no longer has.
3020
- const appliedStyleWeakMap = new WeakMap();
3021
- const elementTransitionWeakMap = new WeakMap();
3022
- const elementRenderedWeakSet = new WeakSet();
3023
- const NO_STYLE = {};
3024
- const updateStyle = (element, style, preventInitialTransition) => {
3025
- const styleToApply = style || NO_STYLE;
3026
- const styleApplied = appliedStyleWeakMap.get(element) || NO_STYLE;
3027
- // TRANSITION ANTI-FLICKER STRATEGY:
3028
- // Problem: When setting both transition and styled properties simultaneously
3029
- // (e.g., el.style.transition = "border-radius 0.3s ease"; el.style.borderRadius = "20px"),
3030
- // the browser will immediately perform a transition even if no transition existed before.
3031
- //
3032
- // Solution: Temporarily disable transitions during initial style application by setting
3033
- // transition to "none", then restore the intended transition after the frame completes.
3034
- // We handle multiple updateStyle calls in the same frame gracefully - only one
3035
- // requestAnimationFrame is scheduled per element, and the final transition value wins.
3036
- let skipTransition = false;
3037
- if (!elementRenderedWeakSet.has(element)) {
3038
- const hasTransition = Object.hasOwn(styleToApply, "transition");
3039
- if (hasTransition || preventInitialTransition) {
3040
- if (!elementTransitionWeakMap.has(element)) {
3041
- element.style.transition = "none";
3042
- }
3043
- elementTransitionWeakMap.set(element, styleToApply.transition);
3044
- // Stays "none" until the first frame puts the intended value back
3045
- skipTransition = true;
3046
- }
3047
- afterFirstFrame(element);
3048
- }
3049
-
3050
- for (const key of Object.keys(styleToApply)) {
3051
- const value = styleToApply[key];
3052
- if (value === undefined || value === null) {
3053
- // a removal: handled below with the keys this style no longer has
3054
- continue;
3055
- }
3056
- if (skipTransition && key === "transition") {
3057
- continue;
3058
- }
3059
- if (styleApplied[key] === value) {
3060
- continue;
3061
- }
3062
- if (key.startsWith("--")) {
3063
- element.style.setProperty(key, value);
3064
- } else {
3065
- element.style[key] = value;
3066
- }
3067
- }
3068
-
3069
- for (const key of Object.keys(styleApplied)) {
3070
- const previousValue = styleApplied[key];
3071
- if (previousValue === undefined || previousValue === null) {
3072
- continue;
3073
- }
3074
- const value = styleToApply[key];
3075
- if (value !== undefined && value !== null) {
3076
- continue;
3077
- }
3078
- if (key.startsWith("--")) {
3079
- element.style.removeProperty(key);
3080
- } else {
3081
- element.style[key] = "";
3082
- }
3083
- }
3084
-
3085
- appliedStyleWeakMap.set(element, styleToApply);
3086
- };
3087
-
3088
- // One frame for every element waiting for its first one, not one frame each.
3089
- // What this owes each element — put back the transition suppressed above, and
3090
- // remember it has now been painted once — is a few microseconds, while asking
3091
- // the browser for a frame costs more than that, and a page mounting thousands of
3092
- // boxes asks thousands of times in the same tick. A Set, so an element styled
3093
- // twice before the frame arrives is still one entry.
3094
- let elementSetWaitingFirstFrame = new Set();
3095
- let firstFrameScheduled = false;
3096
- const afterFirstFrame = (element) => {
3097
- elementSetWaitingFirstFrame.add(element);
3098
- if (firstFrameScheduled) {
3099
- return;
3100
- }
3101
- firstFrameScheduled = true;
3102
- requestAnimationFrame(() => {
3103
- firstFrameScheduled = false;
3104
- const elements = elementSetWaitingFirstFrame;
3105
- elementSetWaitingFirstFrame = new Set();
3106
- for (const element of elements) {
3107
- if (elementTransitionWeakMap.has(element)) {
3108
- const transitionToRestore = elementTransitionWeakMap.get(element);
3109
- if (transitionToRestore === undefined) {
3110
- element.style.transition = "";
3111
- } else {
3112
- element.style.transition = transitionToRestore;
3113
- }
3114
- elementTransitionWeakMap.delete(element);
3115
- }
3116
- elementRenderedWeakSet.add(element);
3117
- }
3118
- });
3119
- };
3120
-
3121
- // Dev only: a periodic re-check for what nothing announces — a state forced
3122
- // from the devtools. One interval walking every registered check rather than
3123
- // one per element: a page of a thousand boxes would otherwise run a thousand
3124
- // timers a second.
3125
- const devPollCheckSet = new Set();
3126
- let devPollInterval = null;
3127
- const pollInDev = (check) => {
3128
- devPollCheckSet.add(check);
3129
- if (devPollInterval === null) {
3130
- devPollInterval = setInterval(() => {
3131
- for (const registeredCheck of devPollCheckSet) {
3132
- registeredCheck();
3133
- }
3134
- }, 1_000);
3135
- }
3136
- return () => {
3137
- devPollCheckSet.delete(check);
3138
- if (devPollCheckSet.size === 0) {
3139
- clearInterval(devPollInterval);
3140
- devPollInterval = null;
3141
- }
3142
- };
3143
- };
3144
-
3145
- /**
3146
- * navi's stance on the on-screen keyboard: it overlays the app rather than
3147
- * resizing the viewport, wherever the browser can be told so (the
3148
- * VirtualKeyboard API — Chromium only). See virtual_keyboard.js in @jsenv/dom
3149
- * for what that trades away and what it gives back.
3150
- *
3151
- * Turned on rather than offered, because navi already sizes everything that
3152
- * escapes normal flow against the app's own rectangle rather than against the
3153
- * window (--navi-app-width/height, see navi_css_vars.js), and
3154
- * --navi-keyboard-inset-bottom (safe_area.js) puts the keyboard into exactly
3155
- * that rectangle. So the two mechanisms reach the same numbers here, and the
3156
- * overlay reaches them without reflowing the page underneath — a resizing
3157
- * viewport is a resize of everything, fired transiently every time focus goes
3158
- * from one input to the next.
3159
- *
3160
- * An app that built its own layout around the viewport shrinking can say so
3161
- * with disableVirtualKeyboardOverlay(), and gets the behavior Firefox and
3162
- * Safari give it anyway.
3163
- *
3164
- * Taking the deal means taking over what the browser stops doing under it:
3165
- * bringing the focused field out from under the keyboard. A viewport that
3166
- * shrinks makes the browser scroll to the field; a keyboard that merely paints
3167
- * over the page leaves whatever is under it under it. So navi does that
3168
- * scroll here, with two things safe_area.js provides: a scroll-padding-bottom
3169
- * that counts the keyboard in, plus an allowance for the strip Chrome paints
3170
- * above it without reporting it (--navi-keyboard-strip-allowance), which
3171
- * bounds the band the field is brought into; and room at the end of the
3172
- * scroller, so a field near the end of the page has somewhere to go.
3173
- *
3174
- * Only the arrival is navi's: once the field is in view, Chrome keeps the caret
3175
- * there itself as typing grows a textarea, against that same
3176
- * scroll-padding-bottom.
3177
- */
3178
-
3179
-
3180
- setVirtualKeyboardOverlaysContent(true);
3181
-
3182
- const disableVirtualKeyboardOverlay = () => {
3183
- setVirtualKeyboardOverlaysContent(false);
3184
- };
3185
-
3186
- const revealFocusedField = () => {
3187
- // 0 as well once the overlay is disabled: the viewport shrinks and the
3188
- // browser reveals the field itself.
3189
- if (getVirtualKeyboardOverlayHeight() === 0) {
3190
- return;
3191
- }
3192
- const field = document.activeElement;
3193
- if (!isEditableTarget(field)) {
3194
- return;
3195
- }
3196
- if (isInDocumentBand(field)) {
3197
- return;
3198
- }
3199
- // "center" rather than "nearest": nearest stops the field on the band's
3200
- // edge, clear of the strip only by the allowance. The middle of the band
3201
- // clears a strip taller than guessed too — and centering what is not fully
3202
- // visible is what Chrome does itself when the viewport shrinks.
3203
- scrollIntoViewThroughScrollables(field, {
3204
- block: "center",
3205
- behavior: "instant",
3206
- });
3207
- };
3208
- // The keyboard rising, or changing height (suggestion strip, emoji panel).
3209
- subscribeVirtualKeyboardGeometryChange(revealFocusedField);
3210
- // From one field to the next with the keyboard up: when both want the same
3211
- // keyboard it does not move, and no geometrychange fires.
3212
- document.addEventListener("focusin", revealFocusedField, { capture: true });
3213
-
3214
- // The band the document leaves visible: inside its scroll-padding (the bars,
3215
- // the keyboard and its strip, see safe_area.js). Against the window rather
3216
- // than each scroller's own band: the keyboard covers the window, and a field
3217
- // hidden inside its own scroller is what the browser's focus already scrolls
3218
- // to.
3219
- const isInDocumentBand = (field) => {
3220
- const documentElement = document.documentElement;
3221
- const style = getComputedStyle(documentElement);
3222
- const bandTop = parseFloat(style.scrollPaddingTop) || 0;
3223
- const bandBottom =
3224
- documentElement.clientHeight - (parseFloat(style.scrollPaddingBottom) || 0);
3225
- const { top, bottom } = field.getBoundingClientRect();
3226
- return top >= bandTop && bottom <= bandBottom;
3227
- };
3228
-
3229
369
  installImportMetaCssBuild(import.meta);
3230
370
 
3231
371
  const button = document.createElement("button");
@@ -3397,10 +537,10 @@ effect(() => {
3397
537
  // that positions popups (pickPositionRelativeTo in @jsenv/dom) computes
3398
538
  // against the visual viewport narrowed by the app's own bands, so a dialog
3399
539
  // centers on the app column and a side panel docks flush against the app's
3400
- // edge rather than the window's. Here rather than in each component, for the
3401
- // same reason as virtual_keyboard.js above: one decision about the whole
3402
- // window.
540
+ // edge rather than the window's. Here rather than in each component: it is
541
+ // one decision about the whole window, and this is the module that makes
542
+ // those.
3403
543
  setPlacementViewportInsets(getAppInsets);
3404
544
 
3405
- export { PSEUDO_CLASSES, PSEUDO_NAMED_STYLES_DEFAULT, PSEUDO_STATE_DEFAULT, addInputEffect, applyStyle, coarsePointerSignal, disableVirtualKeyboardOverlay, dispatchRequestClearUIState, dispatchRequestResetUIState, dispatchRequestSetUIState, findClosestControlWithAction, findControlHost, findControlProxy, findControlProxyTarget, findControlProxyTargetController, findControlRoot, findNearestControlHost, findProxyControllers, formatTimeParts, getAppHeight, getAppWidth, getNowHours, getNowHoursRoundedToStep, getParentControl, getRadioSiblings, getSignalType, getUIStateControllerById, getUIStateFromElement, initPseudoStyles, installImportMetaCssBuild, isControl, isControlRoot, isEditableTarget, isKeyboardModality, isMatchingFocusVisible, isNumberInput, isSignal, isToday, minutesFromTime, onUIStateControllerCreated, onUIStateControllerDestroyed, parseTimeParts, readControlValue, resolveInputProps, seedDefaultValueFromSignal, smallTouchScreenSignal, subscribeToPseudoState, timeFromMinutes, timeStringToSeconds, toDomValue, visualViewportHeightSignal, visualViewportWidthSignal, warnSignalAsState, warnSignalCollision, windowHeightSignal, windowWidthSignal };
545
+ export { coarsePointerSignal, getAppHeight, getAppWidth, installImportMetaCssBuild, smallTouchScreenSignal, visualViewportHeightSignal, visualViewportWidthSignal, windowHeightSignal, windowWidthSignal };
3406
546
  //# sourceMappingURL=jsenv_navi_side_effects.js.map