@jsenv/navi 0.29.402 → 0.29.404

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