@jsenv/navi 0.29.404 → 0.29.407

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.
@@ -2,9 +2,8 @@
2
2
  * AI reading this file: read ../docs/AI_INSTRUCTIONS.md for context on
3
3
  * using @jsenv/navi as intended.
4
4
  */
5
- import { installImportMetaCssBuild, isSignal, getSignalType, findControlProxy, findControlRoot, isControl, findControlHost, isNumberInput, findControlProxyTargetController, findNearestControlHost, dispatchRequestSetUIState, getUIStateFromElement, getUIStateControllerById, windowHeightSignal, windowWidthSignal, visualViewportHeightSignal, visualViewportWidthSignal, getAppHeight, getAppWidth, PSEUDO_STATE_DEFAULT, PSEUDO_NAMED_STYLES_DEFAULT, initPseudoStyles, applyStyle, getParentControl, isControlRoot, readControlValue, dispatchRequestClearUIState, dispatchRequestResetUIState, findClosestControlWithAction, isEditableTarget, coarsePointerSignal, isKeyboardModality, onUIStateControllerDestroyed, getRadioSiblings, findProxyControllers, addInputEffect, findControlProxyTarget, isMatchingFocusVisible, onUIStateControllerCreated, toDomValue, PSEUDO_CLASSES, subscribeToPseudoState, resolveInputProps, smallTouchScreenSignal, timeStringToSeconds, parseTimeParts, formatTimeParts, seedDefaultValueFromSignal, minutesFromTime as minutesFromTime$1, timeFromMinutes } from "./jsenv_navi_side_effects.js";
6
- export { disableVirtualKeyboardOverlay, getNowHours, getNowHoursRoundedToStep, isToday } from "./jsenv_navi_side_effects.js";
7
- import { createPubSub, elementIsFocusable, createIterableWeakSet, getVisuallyVisibleInfo, getFirstVisuallyVisibleAncestor, getElementSignature, findEvent, createValueEffect, findFocusDelegateTarget, findFocusable, scrollIntoViewThroughScrollables, allowWheelThrough, dispatchPublicCustomEvent, resolveCSSColor, getScrollContainerSet, ELEMENT_SIZE_CHANGE, dispatchCustomEvent, findSelfOrAncestorFixedPosition, visibleRectEffect, pickPositionRelativeTo, getBorderSizes, getPaddingSizes, applyNewPosition, measureLongestVisualLineWidth, dispatchInternalCustomEvent, chainEvent, keepTouchRefusable, isPressDrivenClick, waitForTap, waitForPressHeld, suppressClickAfterGesture, startDragToTravel, dragSourceThatStoodDown, markDragSource, refuseDragTo, startDragTo, installPanZoom, createInternalCustomEvent, getKeyboardEventDefaultAction, activeElementSignal, normalizeStyle, mergeOneStyle, getPositionedParent, normalizeStyles, createGroupTransitionController, getBorderRadius, preventIntermediateScrollbar, createOpacityTransition, getScrollContainer, watchWheelTravel, scrollRoomTowards, isTouchDrivenEvent, scrollIntoViewScoped, closestOpenableAncestor, isAncestorOpen, isDisplayedDespiteClosedAncestor, observeAncestorOpenState, getAncestorOpenType, findBefore, findAfter, resolveCSSSize, hasCSSSizeUnit, releaseWheelGesture, getScrollIntoViewScopedOffsets, wheelGestureIsTakenFrom, claimWheelGesture, initFocusGroup, stringifyStyle as stringifyStyle$1, isScrollable, resolveOklchLightness, contrastColor, trapScrollInside, parsePositionArea, snapToPixel, trapFocusInside, onAncestorReopen, isPressDisputedByDrag, canScroll, measureWidestChildRow, performTabNavigation, dragAfterIntent, stickyAsRelativeCoords, createDragToMoveGestureController, getDropTargetInfo, setStyles, useActiveElement } from "@jsenv/dom";
5
+ import { installImportMetaCssBuild, windowHeightSignal, windowWidthSignal, visualViewportHeightSignal, visualViewportWidthSignal, getAppHeight, getAppWidth, coarsePointerSignal, smallTouchScreenSignal } from "./jsenv_navi_side_effects.js";
6
+ import { createPubSub, elementIsFocusable, createIterableWeakSet, dispatchInternalCustomEvent, dispatchCustomEvent, getVisuallyVisibleInfo, getFirstVisuallyVisibleAncestor, getElementSignature, findEvent, createValueEffect, findFocusDelegateTarget, findFocusable, scrollIntoViewThroughScrollables, allowWheelThrough, dispatchPublicCustomEvent, resolveCSSColor, getScrollContainerSet, ELEMENT_SIZE_CHANGE, findSelfOrAncestorFixedPosition, visibleRectEffect, pickPositionRelativeTo, getBorderSizes, getPaddingSizes, applyNewPosition, measureLongestVisualLineWidth, chainEvent, keepTouchRefusable, isPressDrivenClick, waitForTap, waitForPressHeld, suppressClickAfterGesture, startDragToTravel, dragSourceThatStoodDown, markDragSource, refuseDragTo, startDragTo, installPanZoom, createInternalCustomEvent, getKeyboardEventDefaultAction, activeElementSignal, normalizeStyle, mergeOneStyle, getPositionedParent, normalizeStyles, createGroupTransitionController, getBorderRadius, preventIntermediateScrollbar, createOpacityTransition, getScrollContainer, watchWheelTravel, scrollRoomTowards, isTouchDrivenEvent, scrollIntoViewScoped, closestOpenableAncestor, isAncestorOpen, isDisplayedDespiteClosedAncestor, observeAncestorOpenState, getAncestorOpenType, findBefore, findAfter, resolveCSSSize, hasCSSSizeUnit, releaseWheelGesture, getScrollIntoViewScopedOffsets, wheelGestureIsTakenFrom, claimWheelGesture, initFocusGroup, stringifyStyle as stringifyStyle$1, isScrollable, resolveOklchLightness, contrastColor, trapScrollInside, parsePositionArea, snapToPixel, trapFocusInside, onAncestorReopen, isPressDisputedByDrag, canScroll, measureWidestChildRow, performTabNavigation, dragAfterIntent, stickyAsRelativeCoords, createDragToMoveGestureController, getDropTargetInfo, setStyles, useActiveElement, setVirtualKeyboardOverlaysContent, subscribeVirtualKeyboardGeometryChange, getVirtualKeyboardOverlayHeight } from "@jsenv/dom";
8
7
  export { chainEvent, clickIsSuppressed, contrastColor, createDragGestureController, dragAfterIntent, findEvent, markDragSource, startDragTo } from "@jsenv/dom";
9
8
  import { signal, computed, effect, untracked, batch, useComputed, useSignal } from "@preact/signals";
10
9
  import { options, isValidElement, createContext, render, h, toChildArray, cloneElement, createElement, Fragment as Fragment$1 } from "preact";
@@ -12,7 +11,7 @@ import { useErrorBoundary, useLayoutEffect, useContext, useCallback, useRef, use
12
11
  import { humanizeI18n, setRuntimeLangSource, formatDuration, formatMonth, formatDay, resolveTimeRangePrecision, formatDatePlaceholder, toDate, getRelativeDay, formatDayRelative, formatMonthPlaceholder, formatWeekPlaceholder, formatDatetimePlaceholder, formatDatetime, toTimeOfDay, formatTimeOfDay, formatTime, formatMinuteDuration, formatSecondDuration, formatHourDuration, formatTimeRelative, formatNumber, interpolateText, installInterpolateJsx } from "@jsenv/humanize";
13
12
  export { createI18n, formatDatetime, formatDay, formatDayRelative, formatDuration, formatHourDuration, formatMinuteDuration, formatMonth, formatNumber, formatSecondDuration, formatTime, formatTimeOfDay, formatTimeRange, formatTimeRelative, interpolateText } from "@jsenv/humanize";
14
13
  import { jsxs, jsx, Fragment } from "preact/jsx-runtime";
15
- import { TYPE_RULE, durationContainsNaN, compareTwoDurations, durationToSeconds, DISPLAYABLE_RULE, MAX_LINE_BREAKS_RULE, NO_EMOJI_RULE, SINGLE_SPACE_RULE, createValidity, resolveCharClass, getCharClassMessageKey, compileCharClassAnchored, compileCharClass, parseDuration, durationToISOString } from "@jsenv/validity";
14
+ import { CHAR_CLASS_PRESETS, TYPE_RULE, durationContainsNaN, compareTwoDurations, durationToSeconds, DISPLAYABLE_RULE, MAX_LINE_BREAKS_RULE, NO_EMOJI_RULE, SINGLE_SPACE_RULE, createValidity, resolveCharClass, getCharClassMessageKey, compileCharClassAnchored, compileCharClass, parseDuration, durationToISOString } from "@jsenv/validity";
16
15
  export { compareTwoDurations, durationContainsNaN, durationToHours, durationToISOString, durationToMinutes, durationToNumber, durationToSeconds, durationToString, parseDuration } from "@jsenv/validity";
17
16
  import { Suspense, createPortal, forwardRef } from "preact/compat";
18
17
 
@@ -1577,6 +1576,27 @@ naviI18n.addAll({
1577
1576
  },
1578
1577
  });
1579
1578
 
1579
+ const isSignal = (value) => {
1580
+ return getSignalType(value) !== null;
1581
+ };
1582
+
1583
+ const BRAND_SYMBOL = Symbol.for("preact-signals");
1584
+ const getSignalType = (value) => {
1585
+ if (!value || typeof value !== "object") {
1586
+ return null;
1587
+ }
1588
+
1589
+ if (value.brand !== BRAND_SYMBOL) {
1590
+ return null;
1591
+ }
1592
+
1593
+ if (typeof value._fn === "function") {
1594
+ return "computed";
1595
+ }
1596
+
1597
+ return "signal";
1598
+ };
1599
+
1580
1600
  /*
1581
1601
  * The network policy: one declaration saying whether a request may go out,
1582
1602
  * read by the action layer rather than by every callback.
@@ -4736,6 +4756,1118 @@ const actionRunEffect = (
4736
4756
  return actionRunnedByThisEffect;
4737
4757
  };
4738
4758
 
4759
+ /**
4760
+ * DOM utilities for navigating the control element hierarchy.
4761
+ *
4762
+ * A control is a self-contained interactive widget. Its DOM structure can be
4763
+ * either flat (host only) or layered (wrapper + host):
4764
+ *
4765
+ * Flat — the element is both the root and the host:
4766
+ * ```html
4767
+ * <button navi-control navi-control-host>Click me</button>
4768
+ * ```
4769
+ *
4770
+ * Layered — a visual wrapper surrounds a native input that is the real host:
4771
+ * ```html
4772
+ * <span navi-control> ← wrapper: root of the control's DOM subtree
4773
+ * <input navi-control-host /> ← host: holds controlProps, value, UI state, constraints
4774
+ * </span>
4775
+ * ```
4776
+ *
4777
+ * Attribute roles:
4778
+ * - `navi-control` boolean, on the wrapper/root; marks the control boundary
4779
+ * - `navi-control-host` boolean, on the host; set automatically by `useInteractiveProps`
4780
+ *
4781
+ * See control_proxy.js for the `navi-control-proxy-for` pattern.
4782
+ */
4783
+
4784
+ /**
4785
+ * Returns the host element inside `el` — the element that holds the control's
4786
+ * value, UI state, and constraints (i.e. the element onto which
4787
+ * `useInteractiveProps` spreads `controlProps` and its event handlers).
4788
+ *
4789
+ * Returns `null` when `el` is itself the host (no separate wrapper).
4790
+ */
4791
+ const findControlHost = (el) => {
4792
+ if (el.hasAttribute("navi-control-host")) {
4793
+ return el;
4794
+ }
4795
+ return el.querySelector("[navi-control-host]");
4796
+ };
4797
+ /**
4798
+ * The control this element belongs to, wherever it sits relative to it.
4799
+ *
4800
+ * `findControlHost` above answers for a control's own DOM (itself, or the native
4801
+ * element it wraps). This one is for something that is not part of a control but
4802
+ * has to reach one — an interaction declared on a box (see
4803
+ * interaction/interactions.js), which may be the control, may sit inside it, or
4804
+ * may be a wrapper around exactly one. Nearest wins in that order, and the answer
4805
+ * is null when there is no control the box belongs to: not every box lives in
4806
+ * one, and a box laying out several controls (a row of badges, a toolbar) is
4807
+ * held by none of them — its interactions are its own, and a press on its empty
4808
+ * part is not a press on the first control it happens to contain.
4809
+ */
4810
+ const findNearestControlHost = (el) => {
4811
+ // Itself, then upwards — the box is inside a button, or is one.
4812
+ const selfOrAncestor = el.closest("[navi-control-host]");
4813
+ if (selfOrAncestor) {
4814
+ return selfOrAncestor;
4815
+ }
4816
+ // …then downwards, only when the box wraps a single control. Counted by
4817
+ // control, not by host: a picker holds the hosts of its popup content, and a
4818
+ // box around that one picker is still around one control.
4819
+ let single = null;
4820
+ for (const host of el.querySelectorAll("[navi-control-host]")) {
4821
+ const controlRoot = host.closest("[navi-control]") || host;
4822
+ const controlAbove = controlRoot.parentElement.closest("[navi-control]");
4823
+ if (controlAbove && el.contains(controlAbove)) {
4824
+ continue;
4825
+ }
4826
+ if (single && single !== controlRoot) {
4827
+ return null;
4828
+ }
4829
+ single = controlRoot;
4830
+ }
4831
+ return single ? findControlHost(single) : null;
4832
+ };
4833
+ const isControlRoot = (el) => {
4834
+ return el.hasAttribute("navi-control");
4835
+ };
4836
+ const isControlHost = (el) => {
4837
+ return el.hasAttribute("navi-control-host");
4838
+ };
4839
+ const isControl = (el) => {
4840
+ return isControlRoot(el) || isControlHost(el);
4841
+ };
4842
+
4843
+ /**
4844
+ * Returns the nearest ancestor of `el` (exclusive of `el`'s own control) that
4845
+ * has a `[data-action]` attribute.
4846
+ *
4847
+ * The search walks up `parentElement` manually (rather than using `.closest()`)
4848
+ * so it can stop at hard boundaries.
4849
+ *
4850
+ * **`[navi-control="picker"]` boundary**: a picker is a hard stop for what is
4851
+ * inside its popup. Elements in there can reach the picker itself, but nothing
4852
+ * above it — an input inside a picker must not submit the form around it. The
4853
+ * picker's own trigger is not inside it: a picker pressed as a whole (a confirm
4854
+ * picker sending the form around it, see picker_confirm.jsx) stands in that
4855
+ * form like any control there, and reaches it.
4856
+ *
4857
+ * ```html
4858
+ * <form data-action="outer"> ← found from the picker's own input,
4859
+ * <button navi-control="picker" data-action="p"> NOT from inside its popup
4860
+ * <input navi-control-host /> ← el (the picker's own input)
4861
+ * <div popover data-picker-content>
4862
+ * <input navi-control-host /> ← el (in picker popover): stops at the picker
4863
+ * </div>
4864
+ * </button>
4865
+ * </form>
4866
+ * ```
4867
+ */
4868
+ const findClosestControlWithAction = (el) => {
4869
+ let current = el;
4870
+ while (current) {
4871
+ if (current.hasAttribute("data-action")) {
4872
+ return current;
4873
+ }
4874
+ if (isPickerBoundaryFor(current, el)) {
4875
+ return undefined;
4876
+ }
4877
+ current = current.parentElement;
4878
+ }
4879
+ return undefined;
4880
+ };
4881
+ const isPickerBoundaryFor = (candidate, el) => {
4882
+ if (candidate.getAttribute("navi-control") !== "picker") {
4883
+ return false;
4884
+ }
4885
+ const content = el.closest("[data-picker-content]");
4886
+ return Boolean(content) && candidate.contains(content);
4887
+ };
4888
+
4889
+ /**
4890
+ * Returns the closest ancestor control element of `el` — i.e. the nearest
4891
+ * `[navi-control]` element that is not the control `el` belongs to.
4892
+ *
4893
+ * `navi-control` is only on wrapper elements, never on hosts. So
4894
+ * `el.closest("[navi-control]")` from a host returns that host's own wrapper,
4895
+ * and one more `.parentNode.closest("[navi-control]")` reaches a true ancestor:
4896
+ *
4897
+ * ```html
4898
+ * <button navi-control> ← outer control (returned)
4899
+ * <span navi-control> ← inner wrapper (skipped via parentNode)
4900
+ * <input navi-control-host /> ← el
4901
+ * </span>
4902
+ * </button>
4903
+ * ```
4904
+ */
4905
+ const getParentControl = (el) => {
4906
+ const ownControlRoot = el.closest("[navi-control]");
4907
+ const parentControlRoot = ownControlRoot.parentNode.closest("[navi-control]");
4908
+ return parentControlRoot;
4909
+ };
4910
+
4911
+ /**
4912
+ * Returns the root element of the control that `el` belongs to, or `null` if
4913
+ * `el` is not part of a control.
4914
+ *
4915
+ * Use this when you have an element that may be a host (inner input) and need
4916
+ * the visual boundary of its control — e.g. to anchor a callout, track
4917
+ * mousedown interactions, or measure the control's bounding box.
4918
+ */
4919
+ const findControlRoot = (el) => {
4920
+ if (el.hasAttribute("navi-control")) {
4921
+ return el;
4922
+ }
4923
+ if (el.hasAttribute("navi-control-host")) {
4924
+ return el.closest("[navi-control]");
4925
+ }
4926
+ return null;
4927
+ };
4928
+
4929
+ /**
4930
+ * Parses a time string into seconds.
4931
+ * Accepts:
4932
+ * - number: returned as-is (already in seconds)
4933
+ * - "HH:MM" string: converted to seconds (e.g. "00:30" → 1800, "01:00" → 3600)
4934
+ * - undefined/null: returned as-is
4935
+ */
4936
+ const timeStringToSeconds = (timeString) => {
4937
+ if (typeof timeString !== "string") {
4938
+ return timeString;
4939
+ }
4940
+ const colonIndex = timeString.indexOf(":");
4941
+ if (colonIndex === -1) {
4942
+ return Number(timeString);
4943
+ }
4944
+ const hours = parseInt(timeString.slice(0, colonIndex), 10);
4945
+ const minutes = parseInt(timeString.slice(colonIndex + 1), 10);
4946
+ return (hours * 60 + minutes) * 60;
4947
+ };
4948
+
4949
+ const isToday = (value) => {
4950
+ if (!value) {
4951
+ return false;
4952
+ }
4953
+ const now = new Date();
4954
+ const todayStr = `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, "0")}-${String(now.getDate()).padStart(2, "0")}`;
4955
+ if (typeof value === "string") {
4956
+ return value === todayStr;
4957
+ }
4958
+ if (typeof value === "number") {
4959
+ const d = new Date(value);
4960
+ const s = `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, "0")}-${String(d.getDate()).padStart(2, "0")}`;
4961
+ return s === todayStr;
4962
+ }
4963
+ if (value instanceof Date) {
4964
+ const s = `${value.getFullYear()}-${String(value.getMonth() + 1).padStart(2, "0")}-${String(value.getDate()).padStart(2, "0")}`;
4965
+ return s === todayStr;
4966
+ }
4967
+ return false;
4968
+ };
4969
+
4970
+ /**
4971
+ * Returns the current time as "HH:MM", with an optional minute offset.
4972
+ *
4973
+ * @param {number} [offsetMinutes=0] - Minutes to add (negative = subtract).
4974
+ * E.g. getNowHours(-5) returns "now minus 5 minutes".
4975
+ *
4976
+ * @example
4977
+ * getNowHours() // "14:30"
4978
+ * getNowHours(-5) // "14:25"
4979
+ */
4980
+ const getNowHours = (offsetMinutes = 0) => {
4981
+ const now = new Date();
4982
+ const totalMinutes = now.getHours() * 60 + now.getMinutes() + offsetMinutes;
4983
+ const clamped =
4984
+ totalMinutes < 0
4985
+ ? 0
4986
+ : totalMinutes > 23 * 60 + 59
4987
+ ? 23 * 60 + 59
4988
+ : totalMinutes;
4989
+ const h = Math.floor(clamped / 60);
4990
+ const m = clamped % 60;
4991
+ return `${String(h).padStart(2, "0")}:${String(m).padStart(2, "0")}`;
4992
+ };
4993
+
4994
+ /**
4995
+ * Returns the current time rounded up to the nearest step boundary,
4996
+ * with an optional minute offset applied first.
4997
+ *
4998
+ * This is useful to compute a step-aligned `min` for a time picker:
4999
+ * passing it ensures the first available slot is always on a step boundary.
5000
+ *
5001
+ * @param {number} stepMinutes - Step size in minutes (e.g. 30).
5002
+ * @param {number} [offsetMinutes=0] - Minutes to add before rounding (negative = subtract).
5003
+ *
5004
+ * @example
5005
+ * // At 9:32, step 30, offset -5 → raw = 9:27 → ceil to 30 → "09:30"
5006
+ * // At 9:38, step 30, offset -5 → raw = 9:33 → ceil to 30 → "10:00"
5007
+ * getNowHoursRoundedToStep(30, -5)
5008
+ */
5009
+ const getNowHoursRoundedToStep = (stepMinutes, offsetMinutes = 0) => {
5010
+ const now = new Date();
5011
+ const totalMinutes = now.getHours() * 60 + now.getMinutes() + offsetMinutes;
5012
+ const aligned = Math.ceil(totalMinutes / stepMinutes) * stepMinutes;
5013
+ const clamped =
5014
+ aligned < 0 ? 0 : aligned > 23 * 60 + 59 ? 23 * 60 + 59 : aligned;
5015
+ const h = Math.floor(clamped / 60);
5016
+ const m = clamped % 60;
5017
+ return `${String(h).padStart(2, "0")}:${String(m).padStart(2, "0")}`;
5018
+ };
5019
+
5020
+ /**
5021
+ * "HH:MM" and its two numbers, in both directions — what any control made of an
5022
+ * hour beside a minute (fields, wheels) aggregates to and is placed from. Held
5023
+ * as numbers, written on two digits: how they are shown is each control's own
5024
+ * business.
5025
+ */
5026
+ const parseTimeParts = (time) => {
5027
+ if (typeof time !== "string") {
5028
+ return null;
5029
+ }
5030
+ const match = /^(\d{1,2}):(\d{1,2})/.exec(time);
5031
+ if (!match) {
5032
+ return null;
5033
+ }
5034
+ return { hour: Number(match[1]), minute: Number(match[2]) };
5035
+ };
5036
+
5037
+ // Half a time is not a time: a control holding one of the two and nothing in
5038
+ // the other has no value at all, and a form has nothing to send about it.
5039
+ const formatTimeParts = (hour, minute) => {
5040
+ if (
5041
+ hour === "" ||
5042
+ hour === undefined ||
5043
+ minute === "" ||
5044
+ minute === undefined
5045
+ ) {
5046
+ return undefined;
5047
+ }
5048
+ return `${padTwo$1(hour)}:${padTwo$1(minute)}`;
5049
+ };
5050
+
5051
+ const minutesFromTime$1 = (time) => {
5052
+ const parts = parseTimeParts(time);
5053
+ if (!parts) {
5054
+ return null;
5055
+ }
5056
+ return parts.hour * 60 + parts.minute;
5057
+ };
5058
+
5059
+ // Not folded back into the day: 1440 is "24:00", the end of the day a span can
5060
+ // run into.
5061
+ const timeFromMinutes = (minutes) => {
5062
+ return `${padTwo$1(Math.floor(minutes / 60))}:${padTwo$1(minutes % 60)}`;
5063
+ };
5064
+
5065
+ const padTwo$1 = (value) => String(value).padStart(2, "0");
5066
+
5067
+ // What a bound signal's type says is what its VALUE is (a validity type);
5068
+ // what a control's `type` says is what the control IS. This table is the whole
5069
+ // bridge between the two vocabularies: a value type with a row here asks for
5070
+ // that control, one without a row asks for nothing and the control keeps its
5071
+ // own default. "string" has no row on purpose — it is the value every typeless
5072
+ // control already holds — and a name only one side knows must never cross as
5073
+ // is: a control type nobody implements is a plain text field that writes an
5074
+ // object as "[object Object]" (see warnOnUnknownPickerType in picker.jsx).
5075
+ // Numeric value types map to navi_number rather than the native type="number"
5076
+ // (spinner buttons, poor UX).
5077
+ const CONTROL_TYPE_BY_SIGNAL_TYPE = {
5078
+ boolean: "checkbox",
5079
+ number: "navi_number",
5080
+ integer: "navi_number",
5081
+ float: "navi_number",
5082
+ ratio: "navi_number",
5083
+ longitude: "navi_number",
5084
+ latitude: "navi_number",
5085
+ second: "navi_number",
5086
+ minute: "navi_number",
5087
+ hour: "navi_number",
5088
+ year: "navi_number",
5089
+ percentage: "navi_percentage",
5090
+ date: "date",
5091
+ month: "month",
5092
+ week: "week",
5093
+ time: "time",
5094
+ datetime: "datetime",
5095
+ duration: "duration",
5096
+ color: "color",
5097
+ email: "email",
5098
+ url: "url",
5099
+ array: "array",
5100
+ object: "object",
5101
+ };
5102
+
5103
+ // Conceptual navi types: defaults, plus the host type they resolve to.
5104
+ // `navi-input-type` keeps the type the caller asked for once the host has
5105
+ // become something plainer — it is what says the value is a number (see
5106
+ // isNumberInput), and what lets constraint messages use domain-specific
5107
+ // wording instead of the generic "Ce nombre doit être...".
5108
+ // A type a picker preset draws (navi_time, navi_minute: see picker_preset.jsx)
5109
+ // has no row: resolveInputProps runs before the preset resolver, and a row
5110
+ // would turn the type into its host before the preset resolver reads it. The
5111
+ // preset hands the host type on itself.
5112
+ const NAVI_TYPE_DEFAULTS = {
5113
+ navi_percentage: {
5114
+ "type": "navi_number",
5115
+ "navi-input-type": "percentage",
5116
+ "min": 0,
5117
+ "max": 100,
5118
+ "step": 1,
5119
+ },
5120
+ navi_number: {
5121
+ "type": "text",
5122
+ "navi-input-type": "number",
5123
+ "autoCorrect": "off",
5124
+ "spellcheck": false,
5125
+ "autoComplete": "off",
5126
+ },
5127
+ };
5128
+
5129
+ // The navi input types whose value IS a number.
5130
+ const NUMBER_NAVI_INPUT_TYPE_SET = new Set([
5131
+ "number",
5132
+ "percentage",
5133
+ "hour",
5134
+ "minute",
5135
+ "second",
5136
+ ]);
5137
+
5138
+ /**
5139
+ * Whether the control holds a number — asked of what the control IS, never of
5140
+ * `inputMode`. In HTML `inputmode` picks the on-screen keyboard and says
5141
+ * nothing about the value: a licence number, a postal code or a card number
5142
+ * with a check letter all want the digit keypad while staying strings. What a
5143
+ * number field is spelled `type="number"`, or a navi type that resolves to a
5144
+ * text host and leaves `navi-input-type` behind to say what it was.
5145
+ */
5146
+ const isNumberInput = (type, naviInputType) => {
5147
+ if (type === "number") {
5148
+ return true;
5149
+ }
5150
+ return NUMBER_NAVI_INPUT_TYPE_SET.has(naviInputType);
5151
+ };
5152
+
5153
+ /**
5154
+ * resolveInputProps — normalizes input-related props that are shared across
5155
+ * `<Picker>`, `<Input>` (textual) and `<Range>`. Mutates the props object in place.
5156
+ *
5157
+ * Normalization is applied recursively: a navi type may resolve to another navi
5158
+ * type (e.g. `navi_percentage` → `navi_number` → `text`), and each step applies its
5159
+ * own formatters and defaults before moving to the next.
5160
+ *
5161
+ * Steps applied for each type:
5162
+ * 1. Record the original navi type in `props["navi-input-type"]` (first call only).
5163
+ * 2. Apply defaults for the current type (min, max, step, and any other props),
5164
+ * only when the prop is not already set.
5165
+ * 3. Apply min/max formatters (e.g. HH:MM string → number for duration types,
5166
+ * Date → formatted string for date/time types).
5167
+ * 4. Apply step formatter (same conversion rules).
5168
+ * 5. Remap `props.type` to the target type defined by the current type's defaults,
5169
+ * then recurse.
5170
+ *
5171
+ * Supported navi types and their targets:
5172
+ * - `navi_percentage` → `navi_number` (0–100, step 1)
5173
+ * - `navi_number` → `text` (inputMode="numeric", no spin buttons implied)
5174
+ *
5175
+ * Standard HTML input types with formatters:
5176
+ * - `date`, `month`, `week`, `time`, `datetime-local`, `datetime`:
5177
+ * min/max accept `Date` instances or timestamps and are converted to the
5178
+ * string format expected by the native input.
5179
+ * - `time`, `datetime-local`, `datetime`:
5180
+ * step accepts `"HH:MM"` and is converted to seconds.
5181
+ */
5182
+ /**
5183
+ * A bound signal that carries a default of its own says the same thing on every
5184
+ * control: the control starts there, uncontrolled, and a reset goes back to it.
5185
+ * Uncontrolled here is about where the control starts, not about whether it
5186
+ * follows the signal — the binding stays two-way either way (see
5187
+ * stateFromSignal in control_hooks.jsx) — nor about what a form counts as
5188
+ * held: that is the signal's content (isUIStateHeld in held_ui_state.js), and a
5189
+ * stateSignal holds its default. Written once and used by everything
5190
+ * that takes a `signal`, so one signal cannot mean two different things
5191
+ * depending on which control it was handed to.
5192
+ */
5193
+ const seedDefaultValueFromSignal = (props) => {
5194
+ const signalOptions = props.signal?.options;
5195
+ if (!signalOptions) {
5196
+ return;
5197
+ }
5198
+ if (Object.hasOwn(props, "defaultValue")) {
5199
+ // explicit defaultValue prop prevails
5200
+ return;
5201
+ }
5202
+ // Snapshot the signal's current default so that resetUIState restores to the
5203
+ // original default — not the value the signal had at the time of the last
5204
+ // re-render.
5205
+ const defaultValue = signalOptions.getDefaultValue(false);
5206
+ if (defaultValue !== undefined) {
5207
+ props.defaultValue = defaultValue;
5208
+ }
5209
+ };
5210
+
5211
+ const resolveInputProps = (props, { controlType = "input" } = {}) => {
5212
+ // `signal` carries a bound state signal. It is left on `props` on purpose:
5213
+ // `createControlInfo` (control_hooks.jsx) reads it to seed the state and to
5214
+ // follow it, and `onUIAction` (ui_state_controller.js) writes user
5215
+ // interactions back into it. Here we only derive input defaults (type/min/max,
5216
+ // defaultValue/defaultChecked) from the signal's `options`, so the control
5217
+ // ends up uncontrolled-with-default while still bound to the signal.
5218
+ const signal = props.signal;
5219
+ if (signal) {
5220
+ const signalOptions = signal.options;
5221
+ if (signalOptions) {
5222
+ for (const key of ["min", "max", "step"]) {
5223
+ if (props[key] === undefined && signalOptions[key] !== undefined) {
5224
+ props[key] = signalOptions[key];
5225
+ }
5226
+ }
5227
+ if (props.type === undefined && signalOptions.type !== undefined) {
5228
+ const typeFromSignal = CONTROL_TYPE_BY_SIGNAL_TYPE[signalOptions.type];
5229
+ // A value type and the control for it usually agree — a date-typed
5230
+ // signal wants a date field — but a boolean one maps to a checkbox, and
5231
+ // a picker made into a checkbox is not a picker with a different look:
5232
+ // it is another control, with no popup to open. A picker asked to hold
5233
+ // a yes/no keeps its two rows and stays itself.
5234
+ const wouldChangeWhatTheControlIs =
5235
+ controlType === "picker" &&
5236
+ (typeFromSignal === "checkbox" || typeFromSignal === "radio");
5237
+ if (typeFromSignal !== undefined && !wouldChangeWhatTheControlIs) {
5238
+ props.type = typeFromSignal;
5239
+ }
5240
+ }
5241
+ }
5242
+
5243
+ const isCheckable = props.type === "checkbox" || props.type === "radio";
5244
+ if (isCheckable) {
5245
+ if (Object.hasOwn(props, "defaultChecked")) ; else {
5246
+ // If no explicit defaultChecked, derive it from the signal's default
5247
+ // value so that resetUIState restores to the original default.
5248
+ // Only a stateSignal carries a default of its own; a plain signal has
5249
+ // no `options` at all, hence the optional read.
5250
+ const defaultVal = signalOptions?.getDefaultValue(false);
5251
+ if (defaultVal === undefined) ; else if (props.type === "radio") {
5252
+ if (defaultVal === true) {
5253
+ props.defaultChecked = true;
5254
+ } else if (
5255
+ Object.hasOwn(props, "value") &&
5256
+ defaultVal === props.value
5257
+ ) {
5258
+ props.defaultChecked = true;
5259
+ }
5260
+ } else if (typeof defaultVal === "boolean") {
5261
+ // Standalone checkbox bound to a boolean signal.
5262
+ props.defaultChecked = defaultVal;
5263
+ } else {
5264
+ // Checkbox is a group member: defaultVal is the array of
5265
+ // selected item values.
5266
+ const checkboxValue = props.value;
5267
+ props.defaultChecked =
5268
+ Array.isArray(defaultVal) && defaultVal.includes(checkboxValue);
5269
+ }
5270
+ }
5271
+ return;
5272
+ }
5273
+
5274
+ seedDefaultValueFromSignal(props);
5275
+ }
5276
+
5277
+ const currentType = props.type;
5278
+ // Apply min/max/step formatters before anything else — this must run even for
5279
+ // standard HTML types (date, time, etc.) that have no NAVI_TYPE_DEFAULTS entry.
5280
+ const currentTypeMinMaxFormatter = MIN_MAX_FORMATTER_BY_TYPE[currentType];
5281
+ const currentTypeStepFormatter = STEP_FORMATTER_BY_TYPE[currentType];
5282
+ if (currentTypeMinMaxFormatter) {
5283
+ props.min = currentTypeMinMaxFormatter(props.min);
5284
+ props.max = currentTypeMinMaxFormatter(props.max);
5285
+ }
5286
+ if (currentTypeStepFormatter) {
5287
+ props.step = currentTypeStepFormatter(props.step);
5288
+ }
5289
+
5290
+ // For navi_number: choose inputMode based on whether step/min/max suggest decimals.
5291
+ // inputMode="numeric" (integer keyboard) vs "decimal" (keyboard with decimal separator).
5292
+ if (currentType === "navi_number") {
5293
+ if (props.inputMode === undefined) {
5294
+ props.inputMode =
5295
+ hasDecimalPlaces(props.step) ||
5296
+ hasDecimalPlaces(props.min) ||
5297
+ hasDecimalPlaces(props.max)
5298
+ ? "decimal"
5299
+ : "numeric";
5300
+ }
5301
+ }
5302
+
5303
+ const { charGuard } = props;
5304
+ if (charGuard) {
5305
+ if (charGuard === true || charGuard === "auto") {
5306
+ // Auto-resolve charGuard from context.
5307
+ let charGuardResolved;
5308
+ const inputMode = props.inputMode;
5309
+ if (inputMode === "numeric") {
5310
+ charGuardResolved = "numeric";
5311
+ } else if (inputMode === "decimal") {
5312
+ charGuardResolved = "decimal";
5313
+ } else if (currentType === "tel") {
5314
+ charGuardResolved = "tel";
5315
+ } else if (currentType === "email") {
5316
+ charGuardResolved = "email";
5317
+ }
5318
+ if (charGuardResolved !== undefined) {
5319
+ props.charGuard = charGuardResolved;
5320
+ }
5321
+ }
5322
+ // charGuard is now resolved: derive inputMode from it if not already set.
5323
+ if (props.inputMode === undefined && props.charGuard) {
5324
+ const autoMode = INPUT_MODE_FROM_CHAR_GUARD[props.charGuard];
5325
+ if (autoMode) {
5326
+ props.inputMode = autoMode;
5327
+ }
5328
+ }
5329
+ // Build pattern from the resolved charGuard (preset name → class, or raw class passthrough).
5330
+ if (props.pattern === undefined && props.charGuard) {
5331
+ const charClass = CHAR_CLASS_PRESETS[props.charGuard] ?? props.charGuard;
5332
+ props.pattern = `${charClass}*`;
5333
+ }
5334
+ }
5335
+
5336
+ // Compute maxLength from max when inputMode is numeric/decimal.
5337
+ // Done here (after inputMode is set) so controller.props has the resolved value.
5338
+ if (props.maxLength === undefined) {
5339
+ if (props.inputMode === "numeric") {
5340
+ const { min, max } = props;
5341
+ if (max === undefined) ; else {
5342
+ const canBeNegative = min === undefined ? max < 0 : min < 0;
5343
+ const signCharCount = canBeNegative ? 1 : 0;
5344
+ const integerDigitCount = String(Math.floor(Math.abs(max))).length;
5345
+ props.maxLength = signCharCount + integerDigitCount;
5346
+ }
5347
+ } else if (props.inputMode === "decimal") {
5348
+ const { min, max, step } = props;
5349
+ if (max === undefined) ; else if (step === undefined) ; else {
5350
+ const canBeNegative = min === undefined ? max < 0 : min < 0;
5351
+ const signCharCount = canBeNegative ? 1 : 0;
5352
+ const integerDigitCount = String(Math.floor(Math.abs(max))).length;
5353
+ const stepStr = String(step);
5354
+ const dotIndex = stepStr.indexOf(".");
5355
+ // integer step + decimal inputMode is an unusual combo, but we stay consistent:
5356
+ // no decimal part in maxLength since valid values are whole numbers anyway
5357
+ const isIntegerStep = dotIndex === -1;
5358
+ const decimalSignCharCount = isIntegerStep ? 0 : 1;
5359
+ const decimalDigitCount = isIntegerStep
5360
+ ? 0
5361
+ : stepStr.length - dotIndex - 1;
5362
+ props.maxLength =
5363
+ signCharCount +
5364
+ integerDigitCount +
5365
+ decimalSignCharCount +
5366
+ decimalDigitCount;
5367
+ }
5368
+ }
5369
+ }
5370
+
5371
+ // Resolve maxLengthGuard boolean/auto → the computed maxLength number.
5372
+ if (props.maxLengthGuard === true || props.maxLengthGuard === "auto") {
5373
+ props.maxLengthGuard =
5374
+ typeof props.maxLength === "number" ? props.maxLength : undefined;
5375
+ }
5376
+
5377
+ const currentTypeDefaults = NAVI_TYPE_DEFAULTS[currentType];
5378
+ if (!currentTypeDefaults) {
5379
+ return;
5380
+ }
5381
+
5382
+ for (const key of Object.keys(currentTypeDefaults)) {
5383
+ if (props[key] === undefined) {
5384
+ props[key] = currentTypeDefaults[key];
5385
+ }
5386
+ }
5387
+ const targetType = currentTypeDefaults.type;
5388
+ props.type = targetType;
5389
+ resolveInputProps(props);
5390
+ };
5391
+
5392
+ // Presets that imply a specific mobile keyboard inputMode.
5393
+ const INPUT_MODE_FROM_CHAR_GUARD = {
5394
+ numeric: "numeric",
5395
+ pin: "numeric",
5396
+ card: "numeric",
5397
+ tel: "tel",
5398
+ decimal: "decimal",
5399
+ };
5400
+
5401
+ const normalizeToDate = (value) => {
5402
+ if (value === undefined || value === null) {
5403
+ return null;
5404
+ }
5405
+ if (typeof value === "number") {
5406
+ return new Date(value);
5407
+ }
5408
+ if (value instanceof Date) {
5409
+ return value;
5410
+ }
5411
+ return null;
5412
+ };
5413
+
5414
+ const toInputDate = (value) => {
5415
+ const date = normalizeToDate(value);
5416
+ if (!date) {
5417
+ return value;
5418
+ }
5419
+ const yyyy = date.getFullYear();
5420
+ const mm = String(date.getMonth() + 1).padStart(2, "0");
5421
+ const dd = String(date.getDate()).padStart(2, "0");
5422
+ return `${yyyy}-${mm}-${dd}`;
5423
+ };
5424
+ const toInputMonth = (value) => {
5425
+ const date = normalizeToDate(value);
5426
+ if (!date) {
5427
+ return value;
5428
+ }
5429
+ const yyyy = date.getFullYear();
5430
+ const mm = String(date.getMonth() + 1).padStart(2, "0");
5431
+ return `${yyyy}-${mm}`;
5432
+ };
5433
+ const toInputWeek = (value) => {
5434
+ const date = normalizeToDate(value);
5435
+ if (!date) {
5436
+ return value;
5437
+ }
5438
+ // ISO week number
5439
+ const d = new Date(date);
5440
+ d.setHours(0, 0, 0, 0);
5441
+ d.setDate(d.getDate() + 3 - ((d.getDay() + 6) % 7));
5442
+ const yearStart = new Date(d.getFullYear(), 0, 4);
5443
+ const week =
5444
+ Math.round(
5445
+ ((d - yearStart) / 86400000 - 3 + ((yearStart.getDay() + 6) % 7)) / 7,
5446
+ ) + 1;
5447
+ return `${d.getFullYear()}-W${String(week).padStart(2, "0")}`;
5448
+ };
5449
+ const toInputTime = (value) => {
5450
+ const date = normalizeToDate(value);
5451
+ if (!date) {
5452
+ return value;
5453
+ }
5454
+ const hh = String(date.getHours()).padStart(2, "0");
5455
+ const mm = String(date.getMinutes()).padStart(2, "0");
5456
+ return `${hh}:${mm}`;
5457
+ };
5458
+ const toInputDatetime = (value) => {
5459
+ const date = normalizeToDate(value);
5460
+ if (!date) {
5461
+ return value;
5462
+ }
5463
+ const yyyy = date.getFullYear();
5464
+ const mm = String(date.getMonth() + 1).padStart(2, "0");
5465
+ const dd = String(date.getDate()).padStart(2, "0");
5466
+ const hh = String(date.getHours()).padStart(2, "0");
5467
+ const min = String(date.getMinutes()).padStart(2, "0");
5468
+ return `${yyyy}-${mm}-${dd}T${hh}:${min}`;
5469
+ };
5470
+
5471
+ const MIN_MAX_FORMATTER_BY_TYPE = {
5472
+ "date": toInputDate,
5473
+ "month": toInputMonth,
5474
+ "week": toInputWeek,
5475
+ "time": toInputTime,
5476
+ "datetime-local": toInputDatetime,
5477
+ "datetime": toInputDatetime,
5478
+ };
5479
+ const STEP_FORMATTER_BY_TYPE = {
5480
+ "time": timeStringToSeconds,
5481
+ "datetime-local": timeStringToSeconds,
5482
+ "datetime": timeStringToSeconds,
5483
+ };
5484
+
5485
+ const hasDecimalPlaces = (value) => {
5486
+ if (value === undefined || value === null) {
5487
+ return false;
5488
+ }
5489
+ const num = Number(value);
5490
+ return !isNaN(num) && !Number.isInteger(num);
5491
+ };
5492
+
5493
+ const dispatchRequestSetUIState = (element, value, detail) => {
5494
+ const controlHost = findControlHost(element) || element;
5495
+ return dispatchInternalCustomEvent(controlHost, "navi_set_ui_state", {
5496
+ ...detail,
5497
+ value,
5498
+ });
5499
+ };
5500
+ const dispatchRequestClearUIState = (element, e) => {
5501
+ const controlHost = findControlHost(element) || element;
5502
+ return dispatchInternalCustomEvent(controlHost, "navi_clear_ui_state", {
5503
+ event: e,
5504
+ });
5505
+ };
5506
+ const dispatchRequestResetUIState = (element, e) => {
5507
+ const controlHost = findControlHost(element) || element;
5508
+ return dispatchInternalCustomEvent(controlHost, "navi_reset_ui_state", {
5509
+ event: e,
5510
+ });
5511
+ };
5512
+ /**
5513
+ * @param {Element} el
5514
+ * @param {{ own?: boolean }} [options] `own`: what the element holds BY ITSELF.
5515
+ * Only a button ever answers differently — one with no value of its own
5516
+ * inherits the value of the control around it, which is what makes
5517
+ * `--navi-send` on a form's button be about that form. Something asking what
5518
+ * THIS element says (a travel command reading what the travel is about) wants
5519
+ * the own value and would otherwise be handed the surrounding control's.
5520
+ */
5521
+ const getUIStateFromElement = (el, { own } = {}) => {
5522
+ let uiState;
5523
+ dispatchInternalCustomEvent(el, "navi_get_ui_state", {
5524
+ own,
5525
+ respondWith: (v) => {
5526
+ uiState = v;
5527
+ },
5528
+ });
5529
+ return uiState;
5530
+ };
5531
+
5532
+ /**
5533
+ * Converts a JS value into the form expected by the browser DOM property for a
5534
+ * given control type/input type combination.
5535
+ *
5536
+ * For example:
5537
+ * - `datetime-local` inputs expect a local datetime string without timezone
5538
+ * - `number`/`range` inputs expect a numeric string or number
5539
+ * - `color` inputs require a non-empty hex string (falls back to `#000000`)
5540
+ * - All other inputs receive the value as-is (undefined → "")
5541
+ *
5542
+ * Returns either the converted value directly, or a converter function when the
5543
+ * conversion depends on the runtime value (e.g. plain inputs return `asInputValue`).
5544
+ *
5545
+ * @param {any} value - The JS value to convert.
5546
+ * @param {{ controlType: string, type: string }} options
5547
+ * @returns {any} The DOM-compatible value or a converter function.
5548
+ */
5549
+ const asControlHostValue = (
5550
+ jsValue,
5551
+ { controlType, type, naviInputType, pad },
5552
+ ) => {
5553
+ if (controlType === "select") {
5554
+ // A select holds one of its options, always a string; holding nothing is
5555
+ // the empty option, which the element spells "".
5556
+ return asInputValue(jsValue);
5557
+ }
5558
+ if (controlType === "input" || controlType === "picker") {
5559
+ if (type === "datetime-local") {
5560
+ return asDatetimeLocalString(jsValue);
5561
+ }
5562
+ if (type === "range" || isNumberInput(type, naviInputType)) {
5563
+ return asNumberString(jsValue, pad);
5564
+ }
5565
+ if (type === "color") {
5566
+ return asColorString(jsValue);
5567
+ }
5568
+ return asInputValue(jsValue);
5569
+ }
5570
+ return jsValue;
5571
+ };
5572
+ // As explained in https://developer.mozilla.org/en-US/docs/Web/HTML/Reference/Elements/input/datetime-local#setting_timezones
5573
+ // datetime-local does not support timezones
5574
+ const asDatetimeLocalString = (dateTimeString) => {
5575
+ const date = new Date(dateTimeString);
5576
+ if (isNaN(date.getTime())) {
5577
+ return dateTimeString;
5578
+ }
5579
+ const year = date.getFullYear();
5580
+ const month = String(date.getMonth() + 1).padStart(2, "0");
5581
+ const day = String(date.getDate()).padStart(2, "0");
5582
+ const hours = String(date.getHours()).padStart(2, "0");
5583
+ const minutes = String(date.getMinutes()).padStart(2, "0");
5584
+ const seconds = String(date.getSeconds()).padStart(2, "0");
5585
+ return `${year}-${month}-${day}T${hours}:${minutes}:${seconds}`;
5586
+ };
5587
+ // `pad` is how many digits the number is WRITTEN on — an hour is held as 7 and
5588
+ // shown as "07". Held and shown are two things here, the way they are for a
5589
+ // datetime-local above: what the field says is derived from what the control
5590
+ // holds, and reading it back (readNumberFromInput) gives the number again.
5591
+ const asNumberString = (jsValue, pad) => {
5592
+ if (jsValue === undefined) {
5593
+ return "";
5594
+ }
5595
+ if (!pad || jsValue === "" || jsValue === null) {
5596
+ return jsValue;
5597
+ }
5598
+ const number = Number(jsValue);
5599
+ if (Number.isNaN(number)) {
5600
+ return jsValue;
5601
+ }
5602
+ const negative = number < 0;
5603
+ const digits = String(negative ? -number : number).padStart(Number(pad), "0");
5604
+ return negative ? `-${digits}` : digits;
5605
+ };
5606
+ // Browser requires a non-empty value for <input type="color">.
5607
+ // When our logical value is empty we give it #000000 so it doesn't choke.
5608
+ // The UI uses the original (possibly empty) value to show the checkerboard.
5609
+ const asColorString = (jsValue) => {
5610
+ return jsValue || "#000000";
5611
+ };
5612
+ const asInputValue = (jsValue) => {
5613
+ if (jsValue === undefined) {
5614
+ return "";
5615
+ }
5616
+ return jsValue;
5617
+ };
5618
+
5619
+ /**
5620
+ * Reads the current logical JS value from a control host DOM element.
5621
+ *
5622
+ * Handles all navi control host element types:
5623
+ * - `<button>` — reads via `navi_get_value` custom event, falls back to `button.value`
5624
+ * - `<input type="number|range">` — parses as a number, returns `undefined` when empty
5625
+ * - `<input type="checkbox|radio">` — returns `undefined` when unchecked, otherwise reads
5626
+ * via `navi_get_value` custom event (to preserve the original JS type of the value prop)
5627
+ * - `<input type="datetime-local">` — converts the local datetime string to an ISO 8601 string
5628
+ * - `<input type="navi_picker">` — delegates to the controller via `navi_get_ui_state`
5629
+ * - All other inputs — returns `input.value` as a string
5630
+ *
5631
+ * @param {HTMLElement} controlHost - The control host DOM element to read from.
5632
+ * @returns {any} The current logical value of the control.
5633
+ */
5634
+ const readControlValue = (controlHost) => {
5635
+ if (
5636
+ controlHost.tagName === "BUTTON" ||
5637
+ controlHost.getAttribute("role") === "button"
5638
+ ) {
5639
+ return readValueFromButton(controlHost);
5640
+ }
5641
+ if (controlHost.tagName === "INPUT") {
5642
+ // important: input.type = "navi_js"; followed by input.type; returns "text"
5643
+ // so use getAttribute
5644
+ const type = controlHost.getAttribute("type");
5645
+
5646
+ if (
5647
+ type === "range" ||
5648
+ isNumberInput(type, controlHost.getAttribute("navi-input-type"))
5649
+ ) {
5650
+ return readNumberFromInput(controlHost);
5651
+ }
5652
+ if (type === "color") {
5653
+ return readValueFromControlHost(controlHost);
5654
+ }
5655
+ if (type === "checkbox" || type === "radio") {
5656
+ return readValueFromCheckableInput(controlHost);
5657
+ }
5658
+ if (type === "datetime-local") {
5659
+ return readDatetimeLocalFromInput(controlHost);
5660
+ }
5661
+ if (type === "navi_js") {
5662
+ return getUIStateFromElement(controlHost);
5663
+ }
5664
+ return readValueFromInput(controlHost);
5665
+ }
5666
+ if (controlHost.hasAttribute("navi-control-host")) {
5667
+ // Non-button, non-input navi controls (e.g. Badge.Button rendered as span)
5668
+ return readValueFromControlHost(controlHost);
5669
+ }
5670
+ return readValueFromElement(controlHost);
5671
+ };
5672
+ const readValueFromControlHost = (controlHost) => {
5673
+ return readValueFromNaviCustomEvent(controlHost, controlHost.value);
5674
+ };
5675
+ const readValueFromButton = (button) => {
5676
+ return readValueFromControlHost(button);
5677
+ };
5678
+ const readDatetimeLocalFromInput = (input) => {
5679
+ const localDateTimeString = input.value;
5680
+ if (localDateTimeString === "") {
5681
+ return "";
5682
+ }
5683
+ const localDate = new Date(localDateTimeString);
5684
+ if (isNaN(localDate.getTime())) {
5685
+ return localDateTimeString;
5686
+ }
5687
+ return localDate.toISOString();
5688
+ };
5689
+ const readNumberFromInput = (input) => {
5690
+ const numberString = input.value;
5691
+ if (numberString === "") {
5692
+ return "";
5693
+ }
5694
+ const asNumber = Number(numberString);
5695
+ if (isNaN(asNumber)) {
5696
+ return numberString;
5697
+ }
5698
+ return asNumber;
5699
+ };
5700
+ const readValueFromCheckableInput = (input) => {
5701
+ const checked = input.checked;
5702
+ if (!checked) {
5703
+ return undefined;
5704
+ }
5705
+ return readValueFromControlHost(input);
5706
+ };
5707
+ const readValueFromInput = (input) => {
5708
+ const value = input.value;
5709
+ return value;
5710
+ };
5711
+ const readValueFromElement = (element) => {
5712
+ const value = element.value;
5713
+ return value;
5714
+ };
5715
+ const readValueFromNaviCustomEvent = (field, fallback) => {
5716
+ // prefer the value given as prop (respect original type, browser would convert to string)
5717
+ let responded;
5718
+ let value;
5719
+ dispatchCustomEvent(field, "navi_get_value", {
5720
+ respondWith: (jsValue) => {
5721
+ responded = true;
5722
+ value = jsValue;
5723
+ },
5724
+ });
5725
+ if (responded) {
5726
+ return value;
5727
+ }
5728
+ return fallback;
5729
+ };
5730
+
5731
+ // In-memory registry of all mounted ui state controllers keyed by their id.
5732
+ // Allows direct controller access without dispatching DOM events — used by external
5733
+ // callers (e.g. selectable_list) to call setUIState by id instead of via the DOM.
5734
+ const controllersById = new Map();
5735
+
5736
+ // In-memory registry for radio controllers, keyed by input name.
5737
+ // Allows radio sibling unchecking without querying the DOM — necessary when
5738
+ // items are virtualized and their DOM element may not exist at the time.
5739
+ // Form scoping is reproduced by comparing parentUIStateController references.
5740
+ const radioControllersByName = new Map();
5741
+
5742
+ // Registry for non-serializable JS values that cannot be written to DOM attributes as-is.
5743
+ // When a value is an object/array, we store it here and write a reference string to the DOM
5744
+ // instead of "[object Object]". Console-inspectable via window.__navi_js('id').
5745
+ // The controller id is used as key — if the controller has no id, the value is not registered.
5746
+ const naviJsRegistry = new Map();
5747
+
5748
+ const getUIStateControllerById = (id) => controllersById.get(id);
5749
+ const getRadioSiblings = (radioUIStateController) => {
5750
+ const siblings = radioControllersByName.get(radioUIStateController.name);
5751
+ return siblings;
5752
+ };
5753
+
5754
+ const toDomValue = (
5755
+ jsValue,
5756
+ { controlType, id, type, naviInputType, pad },
5757
+ ) => {
5758
+ const domValue = asControlHostValue(jsValue, {
5759
+ controlType,
5760
+ type,
5761
+ naviInputType,
5762
+ pad,
5763
+ });
5764
+ if (isSerializableAsDomValue(domValue)) {
5765
+ return domValue;
5766
+ }
5767
+ naviJsRegistry.set(id, domValue);
5768
+ return `window.__navi_js('${id}')`;
5769
+ };
5770
+
5771
+ window.__navi_js = (id) => naviJsRegistry.get(id);
5772
+ const isSerializableAsDomValue = (value) => {
5773
+ if (value === null || value === undefined) {
5774
+ return true;
5775
+ }
5776
+ const type = typeof value;
5777
+ return type === "string" || type === "number" || type === "boolean";
5778
+ };
5779
+
5780
+ const onUIStateControllerCreated = (uiStateController) => {
5781
+ const { id, name, controlType } = uiStateController;
5782
+ if (id) {
5783
+ controllersById.set(id, uiStateController);
5784
+ }
5785
+ const proxyFor = uiStateController.props["navi-control-proxy-for"];
5786
+ if (proxyFor) {
5787
+ let proxySet = proxyControllersByRealInputId.get(proxyFor);
5788
+ if (!proxySet) {
5789
+ proxySet = new Set();
5790
+ proxyControllersByRealInputId.set(proxyFor, proxySet);
5791
+ }
5792
+ proxySet.add(uiStateController);
5793
+ }
5794
+ if (
5795
+ controlType === "input" &&
5796
+ uiStateController.props.type === "radio" &&
5797
+ name
5798
+ ) {
5799
+ let set = radioControllersByName.get(name);
5800
+ if (!set) {
5801
+ set = new Set();
5802
+ radioControllersByName.set(name, set);
5803
+ }
5804
+ set.add(uiStateController);
5805
+ }
5806
+ };
5807
+ const onUIStateControllerDestroyed = (uiStateController) => {
5808
+ const { id, name, controlType } = uiStateController;
5809
+ if (id) {
5810
+ // Only the controller the id currently points at may take the entry away:
5811
+ // when two controls share an id, the one leaving would otherwise unregister
5812
+ // the one staying (see the warning in onUIStateControllerCreated), and the
5813
+ // same holds while a control is being replaced by its successor, which
5814
+ // registers during its render, before this cleanup runs.
5815
+ if (controllersById.get(id) === uiStateController) {
5816
+ controllersById.delete(id);
5817
+ naviJsRegistry.delete(id);
5818
+ }
5819
+ }
5820
+ const proxyFor = uiStateController.props["navi-control-proxy-for"];
5821
+ if (proxyFor) {
5822
+ const proxySet = proxyControllersByRealInputId.get(proxyFor);
5823
+ if (proxySet) {
5824
+ proxySet.delete(uiStateController);
5825
+ if (proxySet.size === 0) {
5826
+ proxyControllersByRealInputId.delete(proxyFor);
5827
+ }
5828
+ }
5829
+ }
5830
+ if (
5831
+ controlType === "input" &&
5832
+ uiStateController.controlHostProps.type === "radio" &&
5833
+ name
5834
+ ) {
5835
+ const set = radioControllersByName.get(name);
5836
+ if (set) {
5837
+ set.delete(uiStateController);
5838
+ if (set.size === 0) {
5839
+ radioControllersByName.delete(name);
5840
+ }
5841
+ }
5842
+ }
5843
+ };
5844
+
5845
+ /**
5846
+ * Controller-based equivalent of findControlProxyTarget.
5847
+ * Given a proxy controller, returns the real control's controller.
5848
+ * Finds the target by walking the parent controller's children — no DOM queries.
5849
+ * Returns `null` when the controller is not a proxy or the target is not found.
5850
+ */
5851
+ const findControlProxyTargetController = (controller) => {
5852
+ const proxyFor = controller.controlHostProps["navi-control-proxy-for"];
5853
+ if (!proxyFor) {
5854
+ return null;
5855
+ }
5856
+ return getUIStateControllerById(proxyFor) ?? null;
5857
+ };
5858
+
5859
+ // Reverse-lookup map: real-input id → the proxy controllers that reference it
5860
+ // via `navi-control-proxy-for`. A single control can be represented by several
5861
+ // proxies (an "enable"/"disable" button pair for one radio, for instance), so
5862
+ // each id holds a set. Maintained on create/destroy so lookup is O(1).
5863
+ const proxyControllersByRealInputId = new Map();
5864
+ const findProxyControllers = (realInputId) => {
5865
+ if (!realInputId) {
5866
+ return null;
5867
+ }
5868
+ return proxyControllersByRealInputId.get(realInputId) ?? null;
5869
+ };
5870
+
4739
5871
  /**
4740
5872
  * The attributes constraints read, filled by each constraint module as it
4741
5873
  * evaluates. A constraint declares the attribute it wants (`"data-no-emoji"`)
@@ -5364,6 +6496,113 @@ const isInertOnClick = (element) => {
5364
6496
  return true;
5365
6497
  };
5366
6498
 
6499
+ /**
6500
+ * DOM utilities for the proxy control pattern.
6501
+ *
6502
+ * Some components need a native `<input>` internally — for form submission,
6503
+ * constraint validation, or browser autofill — but the user may not want to
6504
+ * display that input at all. In those cases the input is hidden and a separate
6505
+ * visible element (the proxy) takes over the visual and interactive role.
6506
+ *
6507
+ * The typical use case is `SelectableList`: each list item acts as a styled
6508
+ * radio button, but an actual `<input type="radio">` lives hidden in the DOM
6509
+ * so form submission and validation work natively. When users DO want to
6510
+ * display the input they want full control over its appearance, so they render
6511
+ * their own element and link it to the real input via `navi-control-proxy-for`:
6512
+ *
6513
+ * ```html
6514
+ * <div>
6515
+ * <input id="color_red" type="radio" name="color" value="red" /> ← real control (hidden, drives form/validation)
6516
+ * <input type="radio" name="proxy" value="red" /> ← proxy (visible, delegates interactions to real input)
6517
+ * </div>
6518
+ * ```
6519
+ *
6520
+ * A press on a checkable proxy is dealt to the real control, and so is the
6521
+ * focus: state management, validation and form submission then all happen
6522
+ * where the value lives. A proxy that says what its press does — a button
6523
+ * carrying `command="--navi-check"` — answers the press itself instead.
6524
+ *
6525
+ * Note: an alternative design would be to require users to always instantiate
6526
+ * the input explicitly — e.g. `<Selectable.Input headless />` when they don't
6527
+ * want to display it. That would remove the need for the proxy mechanism
6528
+ * entirely. For now we keep the proxy pattern.
6529
+ */
6530
+
6531
+
6532
+ /**
6533
+ * Given a proxy element, returns the real control it represents.
6534
+ * Returns `null` when `el` is not a proxy.
6535
+ */
6536
+ const findControlProxyTarget = (el) => {
6537
+ const proxyFor = el.getAttribute("navi-control-proxy-for");
6538
+ if (!proxyFor) {
6539
+ return null;
6540
+ }
6541
+ return document.getElementById(proxyFor);
6542
+ };
6543
+
6544
+ // Shared: asked on every pseudo state change of every box, and almost always
6545
+ // empty.
6546
+ const NO_PROXIES = Object.freeze([]);
6547
+ /**
6548
+ * Given a real control element, returns every proxy that visually represents
6549
+ * it — a control can have more than one (an "enable"/"disable" button pair for
6550
+ * one radio, for instance).
6551
+ *
6552
+ * Answered from the controller registry rather than the document: every proxy
6553
+ * declares itself through the `navi-control-proxy-for` prop, so the registry
6554
+ * knows them all, while asking the document means walking it in full for each
6555
+ * of the (overwhelmingly many) controls that have no proxy at all.
6556
+ *
6557
+ * Returns an empty array when no proxy exists for `el`.
6558
+ */
6559
+ const findControlProxies = (el) => {
6560
+ if (!el.id) {
6561
+ return NO_PROXIES;
6562
+ }
6563
+ const proxyControllerSet = findProxyControllers(el.id);
6564
+ if (!proxyControllerSet) {
6565
+ return NO_PROXIES;
6566
+ }
6567
+ const proxyElements = [];
6568
+ for (const proxyController of proxyControllerSet) {
6569
+ const proxyElement = proxyController.ref.current;
6570
+ if (proxyElement) {
6571
+ proxyElements.push(proxyElement);
6572
+ }
6573
+ }
6574
+ return proxyElements;
6575
+ };
6576
+
6577
+ /**
6578
+ * Given a real control element, returns the proxy a gesture on the control
6579
+ * lands on — the one thing said about the control is drawn on.
6580
+ *
6581
+ * Use when you need a single visible stand-in for the real control — anchoring
6582
+ * a callout, for instance. Anything notifying proxies of a state change wants
6583
+ * `findControlProxies` instead, so a control represented by several of them
6584
+ * updates all of them.
6585
+ *
6586
+ * A proxy the pointer cannot reach is drawn for the control without standing
6587
+ * for it: the surface around it takes the presses for everything it holds, so
6588
+ * that surface is where a refusal about the control belongs — not a box inside
6589
+ * it the finger never has to find. A selectable list row whose whole area is
6590
+ * the click target is exactly that arrangement (see `selectableArea`), and it
6591
+ * is read from the arrangement itself rather than from a flag repeating it:
6592
+ * where a gesture can land IS pointer-events.
6593
+ *
6594
+ * Returns `null` when no proxy stands for `el`.
6595
+ */
6596
+ const findControlProxy = (el) => {
6597
+ for (const proxyElement of findControlProxies(el)) {
6598
+ if (getComputedStyle(proxyElement).pointerEvents === "none") {
6599
+ continue;
6600
+ }
6601
+ return proxyElement;
6602
+ }
6603
+ return null;
6604
+ };
6605
+
5367
6606
  /**
5368
6607
  * Typography reset shared by the surfaces a control opens: callout, popover,
5369
6608
  * dialog.
@@ -19411,6 +20650,1453 @@ const getDefaultDisplay = (tagName) => {
19411
20650
  return TAG_NAME_TO_DEFAULT_DISPLAY.get(normalizedTagName) || "inline";
19412
20651
  };
19413
20652
 
20653
+ const addInputEffect = (
20654
+ input,
20655
+ callback,
20656
+ { waitForChange = false, debounce = 0, debugInteraction = () => {} } = {},
20657
+ ) => {
20658
+ const getState =
20659
+ input.type === "checkbox" || input.type === "radio"
20660
+ ? () => input.checked
20661
+ : () => input.value;
20662
+
20663
+ if (waitForChange) {
20664
+ return listenInputStateChange(input, callback, { getState });
20665
+ }
20666
+
20667
+ const [teardown, addTeardown] = createPubSub();
20668
+ let currentState = getState();
20669
+ let timeout;
20670
+ let debounceTimeout;
20671
+ let onEvent;
20672
+ if (debounce) {
20673
+ onEvent = (e, { skipDebounce } = {}) => {
20674
+ clearTimeout(timeout);
20675
+ clearTimeout(debounceTimeout);
20676
+ const state = getState();
20677
+ if (state === currentState) {
20678
+ debugInteraction(
20679
+ e,
20680
+ `interaction ignored (state unchanged: "${state}")`,
20681
+ );
20682
+ return;
20683
+ }
20684
+
20685
+ if (skipDebounce) {
20686
+ debugInteraction(e, `skip debounce, callback called with "${state}"`);
20687
+ if (callback(e) !== false) {
20688
+ currentState = state;
20689
+ }
20690
+ } else {
20691
+ debugInteraction(
20692
+ e,
20693
+ `debounced ${debounce}ms, pending callback with "${state}"`,
20694
+ );
20695
+ debounceTimeout = setTimeout(() => {
20696
+ debugInteraction(
20697
+ e,
20698
+ `debounce elapsed, callback called with "${state}"`,
20699
+ );
20700
+ if (callback(e) !== false) {
20701
+ currentState = state;
20702
+ }
20703
+ }, debounce);
20704
+ }
20705
+ };
20706
+ // no need to wait for change events (blur, enter key)
20707
+ // we consider this as strong interactions requesting an immediate response
20708
+ const stop = listenInputStateChange(
20709
+ input,
20710
+ (e) => {
20711
+ onEvent(e, { skipDebounce: true });
20712
+ },
20713
+ { getState, changeOnEnter: true },
20714
+ );
20715
+ addTeardown(() => {
20716
+ stop();
20717
+ });
20718
+ } else {
20719
+ onEvent = (e) => {
20720
+ clearTimeout(timeout);
20721
+ const state = getState();
20722
+ if (state === currentState) {
20723
+ debugInteraction(
20724
+ e,
20725
+ `interaction ignored (state unchanged: "${state}")`,
20726
+ );
20727
+ return;
20728
+ }
20729
+ debugInteraction(e, `callback called with "${state}"`);
20730
+ if (callback(e) !== false) {
20731
+ currentState = state;
20732
+ }
20733
+ };
20734
+ // Autocomplete, programmatic changes, form restoration
20735
+ input.addEventListener("change", onEvent);
20736
+ addTeardown(() => {
20737
+ input.removeEventListener("change", onEvent);
20738
+ });
20739
+ }
20740
+
20741
+ const onAsyncEvent = (e, options) => {
20742
+ debugInteraction(e, `async event, scheduling callback`);
20743
+ timeout = setTimeout(() => {
20744
+ onEvent(e, options);
20745
+ }, 0);
20746
+ };
20747
+
20748
+ // Standard user input (typing)
20749
+ const onInput = (e) => {
20750
+ onEvent(e);
20751
+ };
20752
+ input.addEventListener("input", onInput);
20753
+ addTeardown(() => {
20754
+ input.removeEventListener("input", onInput);
20755
+ });
20756
+
20757
+ // Form reset - need to check the form
20758
+ const form = input.form;
20759
+ if (form) {
20760
+ // Form reset happens asynchronously, check value after reset completes
20761
+ form.addEventListener("reset", onAsyncEvent);
20762
+ addTeardown(() => {
20763
+ form.removeEventListener("reset", onAsyncEvent);
20764
+ });
20765
+ }
20766
+
20767
+ // Paste events (some browsers need special handling)
20768
+ input.addEventListener("paste", onEvent);
20769
+ addTeardown(() => {
20770
+ input.removeEventListener("paste", onEvent);
20771
+ });
20772
+
20773
+ input.addEventListener("navi_ui_state_change", (e) => {
20774
+ // radios are unchecked by an internal setUIState call when another radio is checked.
20775
+ // navi_ui_state_change is dispatched whenever setUIState changes state, so we
20776
+ // listen here to keep currentState in sync — otherwise input_effect thinks the
20777
+ // radio is still checked and ignores the next user click as "state unchanged".
20778
+ if (input.type === "radio") {
20779
+ currentState = e.detail.value;
20780
+ }
20781
+ const clearEvent = findEvent(
20782
+ e,
20783
+ (eInChain) =>
20784
+ eInChain.type === "navi_set_ui_state" && eInChain.detail.isClear,
20785
+ );
20786
+ const isClear = Boolean(clearEvent);
20787
+ if (isClear) {
20788
+ // "navi_clear" behaves like an async event
20789
+ // a bit like form reset because
20790
+ // our action will be updated async after the component re-renders
20791
+ // and we need to wait that to happen to properly call action with the right value
20792
+ debugInteraction(e, `navi_clear received, scheduling callback`);
20793
+ onAsyncEvent(e, { skipDebounce: true });
20794
+ }
20795
+ });
20796
+
20797
+ return teardown;
20798
+ };
20799
+
20800
+ const listenInputStateChange = (
20801
+ input,
20802
+ callback,
20803
+ { getState, changeOnEnter },
20804
+ ) => {
20805
+ const [teardown, addTeardown] = createPubSub();
20806
+
20807
+ let stateAtInteraction;
20808
+ const oninput = () => {
20809
+ stateAtInteraction = undefined;
20810
+ };
20811
+ const onkeydown = (e) => {
20812
+ if (e.key === "Enter") {
20813
+ /**
20814
+ * Browser trigger a "change" event right after the enter is pressed
20815
+ * if the input value has changed.
20816
+ * We need to prevent the next change event otherwise we would request action twice
20817
+ */
20818
+ stateAtInteraction = getState();
20819
+ if (changeOnEnter) {
20820
+ onchange(e);
20821
+ }
20822
+ }
20823
+ if (e.key === "Escape") {
20824
+ /**
20825
+ * Browser trigger a "change" event right after the escape is pressed
20826
+ * if the input value has changed.
20827
+ * We need to prevent the next change event otherwise we would request action when
20828
+ * we actually want to cancel
20829
+ */
20830
+ stateAtInteraction = getState();
20831
+ }
20832
+ };
20833
+ const onchange = (e) => {
20834
+ if (stateAtInteraction !== undefined && getState() === stateAtInteraction) {
20835
+ stateAtInteraction = undefined;
20836
+ return;
20837
+ }
20838
+ callback(e);
20839
+ };
20840
+ input.addEventListener("input", oninput);
20841
+ input.addEventListener("keydown", onkeydown);
20842
+ input.addEventListener("change", onchange);
20843
+ addTeardown(() => {
20844
+ input.removeEventListener("input", oninput);
20845
+ input.removeEventListener("keydown", onkeydown);
20846
+ input.removeEventListener("change", onchange);
20847
+ });
20848
+
20849
+ {
20850
+ // Handle programmatic value changes that don't trigger browser change events
20851
+ //
20852
+ // Problem: When input values are set programmatically (not by user typing),
20853
+ // browsers don't fire the 'change' event. However, our application logic
20854
+ // still needs to detect these changes.
20855
+ //
20856
+ // Example scenario:
20857
+ // 1. User starts editing (letter key pressed, value set programmatically)
20858
+ // 2. User doesn't type anything additional (this is the key part)
20859
+ // 3. User clicks outside to finish editing
20860
+ // 4. Without this code, no change event would fire despite the fact that the input value did change from its original state
20861
+ //
20862
+ // This distinction is crucial because:
20863
+ //
20864
+ // - If the user typed additional text after the initial programmatic value,
20865
+ // the browser would fire change events normally
20866
+ // - But when they don't type anything else, the browser considers it as "no user interaction"
20867
+ // even though the programmatic initial value represents a meaningful change
20868
+ //
20869
+ // We achieve this by checking if the input value has changed between focus and blur without any user interaction
20870
+ // if yes we fire the callback because input value did change
20871
+ let stateAtStart = getState();
20872
+ let interacted = false;
20873
+
20874
+ const onfocus = () => {
20875
+ interacted = false;
20876
+ stateAtStart = getState();
20877
+ };
20878
+ const oninput = (e) => {
20879
+ if (!e.isTrusted) {
20880
+ // non trusted "input" events will be ignored by the browser when deciding to fire "change" event
20881
+ // we ignore them too
20882
+ return;
20883
+ }
20884
+ interacted = true;
20885
+ };
20886
+ const onblur = (e) => {
20887
+ if (interacted) {
20888
+ return;
20889
+ }
20890
+ if (stateAtStart === getState()) {
20891
+ return;
20892
+ }
20893
+ callback(e);
20894
+ };
20895
+
20896
+ input.addEventListener("focus", onfocus);
20897
+ input.addEventListener("input", oninput);
20898
+ input.addEventListener("blur", onblur);
20899
+ addTeardown(() => {
20900
+ input.removeEventListener("focus", onfocus);
20901
+ input.removeEventListener("input", oninput);
20902
+ input.removeEventListener("blur", onblur);
20903
+ });
20904
+ }
20905
+
20906
+ return teardown;
20907
+ };
20908
+
20909
+ const requestPseudoStateCheck = (element, detail) => {
20910
+ dispatchInternalCustomEvent(
20911
+ element,
20912
+ "navi_pseudo_state_request_check",
20913
+ detail,
20914
+ );
20915
+ // When a control has visible proxies mirroring its state (e.g. selectable
20916
+ // radio with `navi-control-proxy-for`), re-check them too so they stay in
20917
+ // sync with the real control.
20918
+ for (const proxy of findControlProxies(element)) {
20919
+ dispatchInternalCustomEvent(
20920
+ proxy,
20921
+ "navi_pseudo_state_request_check",
20922
+ detail,
20923
+ );
20924
+ }
20925
+ };
20926
+ /**
20927
+ * Called back whenever `element`'s pseudo state changes.
20928
+ *
20929
+ * Kept beside the element rather than announced to the DOM: an element that
20930
+ * changes state has at most one or two interested parties, each known by name
20931
+ * (the box drawing it, the accent color reading its computed style), and a
20932
+ * CustomEvent costs its allocation and its capture/bubble walk whether anyone
20933
+ * listens or not — paid on every element, on every state change. A lookup that
20934
+ * finds nothing costs nothing.
20935
+ *
20936
+ * @param {Element} element
20937
+ * @param {(pseudoState: object, oldPseudoState: object) => void} callback
20938
+ * @returns {() => void} teardown
20939
+ */
20940
+ const subscribeToPseudoState = (element, callback) => {
20941
+ let subscriberSet = pseudoStateSubscriberSetWeakMap.get(element);
20942
+ if (!subscriberSet) {
20943
+ subscriberSet = new Set();
20944
+ pseudoStateSubscriberSetWeakMap.set(element, subscriberSet);
20945
+ }
20946
+ subscriberSet.add(callback);
20947
+ return () => {
20948
+ subscriberSet.delete(callback);
20949
+ };
20950
+ };
20951
+ const pseudoStateSubscriberSetWeakMap = new WeakMap();
20952
+ const notifyPseudoStateSubscribers = (element, value, oldValue) => {
20953
+ const subscriberSet = pseudoStateSubscriberSetWeakMap.get(element);
20954
+ if (!subscriberSet) {
20955
+ return;
20956
+ }
20957
+ for (const subscriber of subscriberSet) {
20958
+ subscriber(value, oldValue);
20959
+ }
20960
+ };
20961
+
20962
+ const PSEUDO_CLASSES = {};
20963
+ Object.assign(PSEUDO_CLASSES, {
20964
+ ":valid": {
20965
+ attribute: "data-valid",
20966
+ test: (el) => el.matches(":valid"),
20967
+ },
20968
+ ":invalid": {
20969
+ attribute: "data-invalid",
20970
+ test: (el) => el.matches(":invalid"),
20971
+ },
20972
+ ":visited": {
20973
+ attribute: "data-visited",
20974
+ },
20975
+ // Written by whoever knows the current url — a Link from its href, a Button
20976
+ // from its route — so it lives here rather than with one of them.
20977
+ ":-navi-href-current": {
20978
+ attribute: "data-href-current",
20979
+ },
20980
+ });
20981
+ const definePseudoClass = (pseudoClass, definition) => {
20982
+ PSEUDO_CLASSES[pseudoClass] = definition;
20983
+ };
20984
+
20985
+ // On touch devices (hover: none), browsers synthesize mouseenter/mouseleave
20986
+ // from touch events but never fire mouseleave when the finger lifts, leaving
20987
+ // el.matches(":hover") stuck at true. This causes hover styles (e.g. input
20988
+ // background highlight) to remain visible long after the user has stopped
20989
+ // touching the element. Checking (hover: hover) lets us skip hover tracking
20990
+ // entirely on touch-only devices where persistent hover makes no sense.
20991
+ const hoverSupported = window.matchMedia("(hover: hover)").matches;
20992
+ definePseudoClass(":hover", {
20993
+ attribute: "data-hover",
20994
+ setup: (el, callback) => {
20995
+ if (!hoverSupported) {
20996
+ return () => {};
20997
+ }
20998
+ const recheckProxy = (e) => {
20999
+ for (const proxy of findControlProxies(el)) {
21000
+ requestPseudoStateCheck(proxy, { event: e });
21001
+ }
21002
+ };
21003
+ const recheckProxyTarget = (e) => {
21004
+ const proxyTarget = findControlProxyTarget(el);
21005
+ if (proxyTarget) {
21006
+ requestPseudoStateCheck(proxyTarget, { event: e });
21007
+ }
21008
+ };
21009
+ let onmouseenter = (e) => {
21010
+ callback();
21011
+ recheckProxy(e);
21012
+ recheckProxyTarget(e);
21013
+ };
21014
+ let onmouseleave = (e) => {
21015
+ callback();
21016
+ recheckProxy(e);
21017
+ recheckProxyTarget(e);
21018
+ };
21019
+
21020
+ if (el.tagName === "LABEL") {
21021
+ // input.matches(":hover") is true when hovering the label
21022
+ // so when label is hovered/not hovered we need to recheck the input too
21023
+ const recheckInput = (e) => {
21024
+ if (el.htmlFor) {
21025
+ const input = document.getElementById(el.htmlFor);
21026
+ if (!input) {
21027
+ // cannot find the input for this label in the DOM
21028
+ return;
21029
+ }
21030
+ requestPseudoStateCheck(input, { event: e });
21031
+ return;
21032
+ }
21033
+ const input = el.querySelector("input, textarea, select");
21034
+ if (!input) {
21035
+ // label does not contain an input
21036
+ return;
21037
+ }
21038
+ requestPseudoStateCheck(input, { event: e });
21039
+ };
21040
+ const _onmouseenter = onmouseenter;
21041
+ onmouseenter = (e) => {
21042
+ recheckInput(e);
21043
+ _onmouseenter(e);
21044
+ };
21045
+ const _onmouseleave = onmouseleave;
21046
+ onmouseleave = (e) => {
21047
+ recheckInput(e);
21048
+ _onmouseleave(e);
21049
+ };
21050
+ }
21051
+
21052
+ el.addEventListener("mouseenter", onmouseenter);
21053
+ el.addEventListener("mouseleave", onmouseleave);
21054
+ return () => {
21055
+ el.removeEventListener("mouseenter", onmouseenter);
21056
+ el.removeEventListener("mouseleave", onmouseleave);
21057
+ };
21058
+ },
21059
+ test: (el) => {
21060
+ if (!hoverSupported) {
21061
+ return false;
21062
+ }
21063
+ if (el.matches(":hover")) {
21064
+ return true;
21065
+ }
21066
+ for (const proxy of findControlProxies(el)) {
21067
+ if (proxy.matches(":hover")) {
21068
+ return true;
21069
+ }
21070
+ }
21071
+ return false;
21072
+ },
21073
+ });
21074
+ definePseudoClass(":disabled", {
21075
+ attribute: "data-disabled",
21076
+ add: (el) => {
21077
+ if (
21078
+ el.tagName === "BUTTON" ||
21079
+ el.tagName === "INPUT" ||
21080
+ el.tagName === "SELECT" ||
21081
+ el.tagName === "TEXTAREA"
21082
+ ) {
21083
+ el.disabled = true;
21084
+ }
21085
+ },
21086
+ remove: (el) => {
21087
+ if (
21088
+ el.tagName === "BUTTON" ||
21089
+ el.tagName === "INPUT" ||
21090
+ el.tagName === "SELECT" ||
21091
+ el.tagName === "TEXTAREA"
21092
+ ) {
21093
+ el.disabled = false;
21094
+ }
21095
+ },
21096
+ });
21097
+ definePseudoClass(":read-only", {
21098
+ attribute: "data-readonly",
21099
+ add: (el) => {
21100
+ if (
21101
+ el.tagName === "INPUT" ||
21102
+ el.tagName === "SELECT" ||
21103
+ el.tagName === "TEXTAREA"
21104
+ ) {
21105
+ if (el.type === "checkbox" || el.type === "radio") {
21106
+ // there is no readOnly for checkboxes/radios
21107
+ return;
21108
+ }
21109
+ // el.readOnly = true;
21110
+ }
21111
+ },
21112
+ remove: (el) => {
21113
+ if (
21114
+ el.tagName === "INPUT" ||
21115
+ el.tagName === "SELECT" ||
21116
+ el.tagName === "TEXTAREA"
21117
+ ) {
21118
+ if (el.type === "checkbox" || el.type === "radio") {
21119
+ // there is no readOnly for checkboxes/radios
21120
+ return;
21121
+ }
21122
+ // el.readOnly = false;
21123
+ }
21124
+ },
21125
+ });
21126
+ definePseudoClass(":checked", {
21127
+ attribute: "data-checked",
21128
+ setup: (el, callback) => {
21129
+ if (el.type === "checkbox") {
21130
+ // Listen to user interactions
21131
+ el.addEventListener("input", callback);
21132
+ // Intercept programmatic changes to .checked property
21133
+ const originalDescriptor = Object.getOwnPropertyDescriptor(
21134
+ HTMLInputElement.prototype,
21135
+ "checked",
21136
+ );
21137
+ Object.defineProperty(el, "checked", {
21138
+ get: originalDescriptor.get,
21139
+ set(value) {
21140
+ originalDescriptor.set.call(this, value);
21141
+ callback();
21142
+ },
21143
+ configurable: true,
21144
+ });
21145
+ return () => {
21146
+ // Restore original property descriptor
21147
+ Object.defineProperty(el, "checked", originalDescriptor);
21148
+ el.removeEventListener("input", callback);
21149
+ };
21150
+ }
21151
+ if (el.type === "radio") {
21152
+ // Listen to changes on the radio
21153
+ el.addEventListener("input", callback);
21154
+ // Intercept programmatic changes to .checked property
21155
+ const originalDescriptor = Object.getOwnPropertyDescriptor(
21156
+ HTMLInputElement.prototype,
21157
+ "checked",
21158
+ );
21159
+ Object.defineProperty(el, "checked", {
21160
+ get: originalDescriptor.get,
21161
+ set(value) {
21162
+ originalDescriptor.set.call(this, value);
21163
+ callback();
21164
+ },
21165
+ configurable: true,
21166
+ });
21167
+ return () => {
21168
+ el.removeEventListener("input", callback);
21169
+ // Restore original property descriptor
21170
+ Object.defineProperty(el, "checked", originalDescriptor);
21171
+ };
21172
+ }
21173
+ if (el.tagName === "INPUT") {
21174
+ el.addEventListener("input", callback);
21175
+ return () => {
21176
+ el.removeEventListener("input", callback);
21177
+ };
21178
+ }
21179
+ return () => {};
21180
+ },
21181
+ test: (el) => el.matches(":checked"),
21182
+ });
21183
+ definePseudoClass(":active", {
21184
+ attribute: "data-active",
21185
+ setup: (el, callback) => {
21186
+ // I'ts recommended to use :-navi-pressed over :active for interactive elements.
21187
+ const onPointerDown = () => {
21188
+ const onRelease = () => {
21189
+ document.removeEventListener("pointercancel", onRelease, true);
21190
+ document.removeEventListener("pointerup", onRelease, true);
21191
+ callback();
21192
+ };
21193
+ document.addEventListener("pointercancel", onRelease, true);
21194
+ document.addEventListener("pointerup", onRelease, true);
21195
+ callback();
21196
+ };
21197
+ el.addEventListener("pointerdown", onPointerDown);
21198
+ return () => {
21199
+ el.removeEventListener("pointerdown", onPointerDown);
21200
+ };
21201
+ },
21202
+ test: (el) => el.matches(":active"),
21203
+ });
21204
+
21205
+ // The current input modality: true after a keyboard navigation key (arrow keys,
21206
+ // Escape, Enter, Ctrl, Alt, Shift, Space — Space ignored on editable fields),
21207
+ // false after a pointer interaction. Updated by the listeners in the
21208
+ // focus_classes block below. At module scope so isMatchingFocusVisible (used
21209
+ // here and in control_hooks.jsx) can read it.
21210
+ let keyboardNavigationUsed = false;
21211
+
21212
+ // HOW FOCUS-VISIBLE IS DECIDED (the details behind isMatchingFocusVisible)
21213
+ //
21214
+ // Two rules, depending on what `el` is:
21215
+ //
21216
+ // 1. An EDITABLE target (text-ish input, textarea, contenteditable — anything
21217
+ // whose whole point is keyboard input, see isEditableTarget) shows its ring
21218
+ // whenever it holds the focus, however the focus arrived — mouse,
21219
+ // programmatic, even a focus({ focusVisible: false }). Being focused, for
21220
+ // such a field, means being about to type, and that is what the ring
21221
+ // announces. Its check is on :focus rather than :focus-visible on purpose:
21222
+ // the native :focus-visible obeys the focusVisible option, which callers
21223
+ // set from the modality without knowing what they are focusing.
21224
+ //
21225
+ // 2. Anything else needs BOTH the native :focus-visible match AND the current
21226
+ // modality being keyboard (`keyboardNavigationUsed`).
21227
+ //
21228
+ // The native match alone cannot be trusted, because we routinely take the
21229
+ // pointer out of the browser's hands: a picker opens on mousedown and calls
21230
+ // preventDefault() so the browser does not move focus itself (see
21231
+ // picker_custom.jsx). The browser therefore never registers that a pointer
21232
+ // was what moved focus, and whatever focus-visible state the previous
21233
+ // keyboard interaction left behind stays true — even across the
21234
+ // programmatic focus({ focusVisible: false }) that follows. Close a picker
21235
+ // with Escape (ring on the trigger, rightly) and click it open again: the
21236
+ // popup's own focusable would come up ringed, from a mouse press.
21237
+ //
21238
+ // `keyboardNavigationUsed` has no such blind spot — it is set by navigation
21239
+ // keydowns and cleared by pointerdown, whatever anyone prevents afterwards
21240
+ // — so it is the authority for everything rule 1 does not cover.
21241
+ //
21242
+ // Ring INHERITANCE (a controlled element ringing because its aria-controls
21243
+ // controller is focused) stays gated on the keyboard modality even for an
21244
+ // editable controller — see hasIndirectFocus: propagating a ring promises
21245
+ // keyboard shortcuts will drive the controlled element, a promise that only
21246
+ // holds once a physical keyboard has actually been used.
21247
+ /**
21248
+ * Whether `el` should currently show a focus ring — the enriched
21249
+ * :focus-visible behind every [data-focus-visible] navi renders.
21250
+ * Use this instead of a bare el.matches(":focus-visible") wherever
21251
+ * focus-visible is evaluated; the comment above details the rules.
21252
+ * @param {Element} el
21253
+ * @returns {boolean}
21254
+ */
21255
+ const isMatchingFocusVisible = (el) => {
21256
+ if (isEditableTarget(el)) {
21257
+ return el.matches(":focus");
21258
+ }
21259
+ if (!el.matches(":focus-visible")) {
21260
+ return false;
21261
+ }
21262
+ if (!keyboardNavigationUsed) {
21263
+ return false;
21264
+ }
21265
+ return true;
21266
+ };
21267
+
21268
+ // Elements that invite keyboard input: focusing one — even with the mouse —
21269
+ // means the user is about to type, so they always warrant a visible focus.
21270
+ // Also used to ignore the Space key as a navigation key while typing, and by
21271
+ // programmatic focus (focus_transfer.js) to pass focusVisible: true so the
21272
+ // native :focus-visible agrees with the ring rule 1 above draws.
21273
+ const EDITABLE_INPUT_TYPE_SET = new Set([
21274
+ "text",
21275
+ "search",
21276
+ "url",
21277
+ "email",
21278
+ "password",
21279
+ "tel",
21280
+ "number",
21281
+ "date",
21282
+ "time",
21283
+ "datetime-local",
21284
+ "month",
21285
+ "week",
21286
+ ]);
21287
+ const isEditableTarget = (target) => {
21288
+ if (!target) {
21289
+ return false;
21290
+ }
21291
+ const tag = target.tagName;
21292
+ if (tag === "TEXTAREA") {
21293
+ return !target.readOnly;
21294
+ }
21295
+ if (tag === "INPUT") {
21296
+ if (!target.type || EDITABLE_INPUT_TYPE_SET.has(target.type)) {
21297
+ return !target.readOnly;
21298
+ }
21299
+ }
21300
+ if (target.isContentEditable) {
21301
+ return true;
21302
+ }
21303
+ return false;
21304
+ };
21305
+
21306
+ // The current modality, for code deciding whether something it is about to
21307
+ // focus should show a ring — a slide arriving, a popup opening. The question is
21308
+ // "was the user on the keyboard when this was asked for", which is what this
21309
+ // flag says; the element that happens to hold the focus right now says nothing
21310
+ // about it (it may have been focused programmatically, ring or no ring, by the
21311
+ // travel before this one).
21312
+ const isKeyboardModality = () => keyboardNavigationUsed;
21313
+
21314
+ {
21315
+ // We implement :focus and :focus-visible with enriched semantics:
21316
+ // an element is considered focused not only when it natively has focus, but also
21317
+ // when a "focus proxy" element has focus (e.g. a read-only range input delegates
21318
+ // focus to a sibling span) or when a controlling element has focus (e.g. a combobox
21319
+ // input with aria-controls pointing to a listbox — the listbox should appear focused
21320
+ // while the input is focused).
21321
+ //
21322
+ // We intentionally reuse the native :focus / :focus-visible names rather than
21323
+ // introducing new navi-specific pseudo-classes (e.g. :-navi-focus). This is a
21324
+ // deliberate exception: all existing CSS and code written as [data-focus] or
21325
+ // [data-focus-visible] automatically benefits from the enriched behavior without
21326
+ // any changes. A separate navi-specific class would require updating every
21327
+ // component.
21328
+ //
21329
+ // When a controller element (e.g. combobox input) gains or loses focus,
21330
+ // notify the elements it controls via aria-controls so they re-check their
21331
+ // focus state. `requestPseudoStateCheck` also re-checks the controlled
21332
+ // element's proxy (if any), so the visible proxy mirrors the hidden real
21333
+ // input's inherited focus.
21334
+ const notifyAriaControlled = (el, e) => {
21335
+ const controlledIds = el.getAttribute("aria-controls");
21336
+ if (!controlledIds) {
21337
+ return;
21338
+ }
21339
+ for (const id of controlledIds.split(" ")) {
21340
+ const controlled = document.getElementById(id);
21341
+ if (controlled) {
21342
+ requestPseudoStateCheck(controlled, { event: e });
21343
+ }
21344
+ }
21345
+ };
21346
+ // Tracks whether the user has pressed a keyboard navigation key (arrow keys,
21347
+ // Escape, Enter, Ctrl, Alt, Shift, Space) since the last pointer interaction.
21348
+ // Space is ignored when the target is an editable field.
21349
+ // This flag is used to gate focus-visible inheritance via aria-controls:
21350
+ // on mobile (or when the user hasn't used keyboard nav yet) an input that
21351
+ // controls a radio should not cause the radio to show a focus ring.
21352
+ // (Declared at module scope — see keyboardNavigationUsed above.)
21353
+ const NAVIGATION_KEY_SET = new Set([
21354
+ "ArrowUp",
21355
+ "ArrowDown",
21356
+ "ArrowLeft",
21357
+ "ArrowRight",
21358
+ "Escape",
21359
+ "Enter",
21360
+ "Control",
21361
+ "Alt",
21362
+ "Shift",
21363
+ " ",
21364
+ "Tab",
21365
+ ]);
21366
+ document.addEventListener(
21367
+ "keydown",
21368
+ (e) => {
21369
+ if (!NAVIGATION_KEY_SET.has(e.key)) {
21370
+ return;
21371
+ }
21372
+ if (e.key === " " && isEditableTarget(e.target)) {
21373
+ return;
21374
+ }
21375
+ keyboardNavigationUsed = true;
21376
+ },
21377
+ { capture: true },
21378
+ );
21379
+ document.addEventListener(
21380
+ "pointerdown",
21381
+ () => {
21382
+ keyboardNavigationUsed = false;
21383
+ },
21384
+ { capture: true },
21385
+ );
21386
+
21387
+ // A keystroke flips keyboardNavigationUsed, which can turn :focus-visible on —
21388
+ // but only for the element that holds focus, directly or through aria-controls
21389
+ // / a proxy. Pressing a key cannot reveal a focus ring on an unfocused element.
21390
+ // So a single shared handler re-checks just that focus chain (the active
21391
+ // element, what it controls, and its proxy — the last two via
21392
+ // requestPseudoStateCheck / notifyAriaControlled). This runs in the bubble
21393
+ // phase, after the capture-phase listener above has updated the flag.
21394
+ //
21395
+ // The alternative — each registered :focus-visible element adding its own
21396
+ // document keydown listener that re-tests itself — makes one keypress cost
21397
+ // O(number-of-boxes) full-document [aria-controls] / proxy queries, since every
21398
+ // unfocused element falls through matches(":focus-visible") into hasIndirectFocus.
21399
+ const recheckFocusChainOnKey = (e) => {
21400
+ const active = document.activeElement;
21401
+ if (!active || active === document.body) {
21402
+ return;
21403
+ }
21404
+ requestPseudoStateCheck(active, { event: e });
21405
+ notifyAriaControlled(active, e);
21406
+ };
21407
+ document.addEventListener("keydown", recheckFocusChainOnKey);
21408
+ document.addEventListener("keyup", recheckFocusChainOnKey);
21409
+
21410
+ // Returns true when el holds focus indirectly — either because a controlling
21411
+ // element (aria-controls) has focus, or because el is a proxy whose target
21412
+ // is itself controlled by a focused element.
21413
+ const hasIndirectFocus = (el, { requireFocusVisible = false } = {}) => {
21414
+ // No ring inheritance without a keyboard: an editable target draws its own
21415
+ // ring on any focus (see isMatchingFocusVisible), but propagating that ring
21416
+ // to a controlled element (aria-controls) is a promise that keyboard
21417
+ // shortcuts will drive it — a promise that holds only once a physical
21418
+ // keyboard has actually been used. On touch devices the flag stays false
21419
+ // and a focused search input keeps its ring to itself.
21420
+ if (requireFocusVisible && !keyboardNavigationUsed) {
21421
+ return false;
21422
+ }
21423
+ // A controller/proxy counts as focused for inheritance via the same rule
21424
+ // used everywhere: :focus for plain inheritance, isMatchingFocusVisible for
21425
+ // the focus-visible variant (so a mouse-focused controller doesn't propagate
21426
+ // a ring).
21427
+ const isFocusedTarget = (target) =>
21428
+ requireFocusVisible
21429
+ ? isMatchingFocusVisible(target)
21430
+ : target.matches(":focus");
21431
+ // Both branches of isFocusedTarget rest on :focus / :focus-visible, and only
21432
+ // one element in the document can match those: document.activeElement. So
21433
+ // the single controller worth testing is known upfront — asking the document
21434
+ // for every [aria-controls] would collect candidates that cannot qualify,
21435
+ // once per element and again on every re-check, on a document each new
21436
+ // element makes bigger.
21437
+ const isControlledBy = (target) => {
21438
+ const id = target.id;
21439
+ if (!id) {
21440
+ return false;
21441
+ }
21442
+ const activeElement = document.activeElement;
21443
+ if (!activeElement || activeElement === document.body) {
21444
+ return false;
21445
+ }
21446
+ if (!activeElement.matches(`[aria-controls~="${id}"]`)) {
21447
+ return false;
21448
+ }
21449
+ // A controller inside the element it controls means focus is already
21450
+ // native (:focus-within) — nothing to inherit.
21451
+ if (target.contains(activeElement)) {
21452
+ return false;
21453
+ }
21454
+ return isFocusedTarget(activeElement);
21455
+ };
21456
+ if (isControlledBy(el)) {
21457
+ return true;
21458
+ }
21459
+ const proxyTarget = findControlProxyTarget(el);
21460
+ if (proxyTarget) {
21461
+ if (isFocusedTarget(proxyTarget)) {
21462
+ return true;
21463
+ }
21464
+ if (isControlledBy(proxyTarget)) {
21465
+ return true;
21466
+ }
21467
+ }
21468
+ return false;
21469
+ };
21470
+
21471
+ // One registration per element for everything focus-related, shared by
21472
+ // :focus, :focus-visible and :focus-within: they all react to the same
21473
+ // focusin/focusout, and they all re-check through the same callback (see
21474
+ // initPseudoStyles), which the Set turns into one call.
21475
+ const focusTrackingWeakMap = new WeakMap();
21476
+ const trackFocus = (el, callback) => {
21477
+ let tracking = focusTrackingWeakMap.get(el);
21478
+ if (!tracking) {
21479
+ const callbackSet = new Set();
21480
+ const onFocusChange = (e) => {
21481
+ for (const trackedCallback of callbackSet) {
21482
+ trackedCallback();
21483
+ }
21484
+ notifyAriaControlled(el, e);
21485
+ };
21486
+ el.addEventListener("focusin", onFocusChange);
21487
+ el.addEventListener("focusout", onFocusChange);
21488
+ tracking = {
21489
+ callbackSet,
21490
+ teardown: () => {
21491
+ el.removeEventListener("focusin", onFocusChange);
21492
+ el.removeEventListener("focusout", onFocusChange);
21493
+ focusTrackingWeakMap.delete(el);
21494
+ },
21495
+ };
21496
+ focusTrackingWeakMap.set(el, tracking);
21497
+ observeAriaControls();
21498
+ }
21499
+ tracking.callbackSet.add(callback);
21500
+ return () => {
21501
+ tracking.callbackSet.delete(callback);
21502
+ if (tracking.callbackSet.size === 0) {
21503
+ tracking.teardown();
21504
+ }
21505
+ };
21506
+ };
21507
+ // When aria-controls changes on a focused element, what it used to control
21508
+ // and what it controls now both re-check their inherited focus. One observer
21509
+ // on the document rather than one per tracked element: the attribute changes
21510
+ // rarely, on few elements, while thousands are tracked — and it can be set
21511
+ // after the element was, so "has it at setup" would miss it.
21512
+ let ariaControlsObserver = null;
21513
+ const observeAriaControls = () => {
21514
+ if (ariaControlsObserver) {
21515
+ return;
21516
+ }
21517
+ ariaControlsObserver = new MutationObserver((mutations) => {
21518
+ for (const mutation of mutations) {
21519
+ const el = mutation.target;
21520
+ if (!focusTrackingWeakMap.has(el)) {
21521
+ continue;
21522
+ }
21523
+ if (!el.matches(":focus-within")) {
21524
+ continue;
21525
+ }
21526
+ const oldIds = (mutation.oldValue || "").split(" ").filter(Boolean);
21527
+ for (const id of oldIds) {
21528
+ const controlled = document.getElementById(id);
21529
+ if (controlled) {
21530
+ requestPseudoStateCheck(controlled, {});
21531
+ }
21532
+ }
21533
+ notifyAriaControlled(el, {});
21534
+ }
21535
+ });
21536
+ ariaControlsObserver.observe(document.documentElement, {
21537
+ subtree: true,
21538
+ attributes: true,
21539
+ attributeFilter: ["aria-controls"],
21540
+ attributeOldValue: true,
21541
+ });
21542
+ };
21543
+
21544
+ definePseudoClass(":focus", {
21545
+ attribute: "data-focus",
21546
+ setup: trackFocus,
21547
+ test: (el) => {
21548
+ if (el.matches(":focus")) {
21549
+ return true;
21550
+ }
21551
+ if (hasIndirectFocus(el)) {
21552
+ return true;
21553
+ }
21554
+ return false;
21555
+ },
21556
+ });
21557
+ definePseudoClass(":focus-visible", {
21558
+ attribute: "data-focus-visible",
21559
+ // No per-element keydown/keyup listener: the shared recheckFocusChainOnKey
21560
+ // handler re-checks the focused element (the only one a keystroke can turn
21561
+ // focus-visible) so a keypress stays O(1), not O(number-of-boxes).
21562
+ setup: trackFocus,
21563
+ test: (el) => {
21564
+ if (isMatchingFocusVisible(el)) {
21565
+ return true;
21566
+ }
21567
+ if (hasIndirectFocus(el, { requireFocusVisible: true })) {
21568
+ return true;
21569
+ }
21570
+ return false;
21571
+ },
21572
+ });
21573
+ definePseudoClass(":focus-within", {
21574
+ attribute: "data-focus-within",
21575
+ setup: trackFocus,
21576
+ test: (el) => {
21577
+ if (el.matches(":focus-within")) {
21578
+ return true;
21579
+ }
21580
+ if (hasIndirectFocus(el)) {
21581
+ return true;
21582
+ }
21583
+ if (el.contains(document.activeElement)) {
21584
+ // for some reason :focus-within sometimes is false while focus is within...
21585
+ // (popover with chrome for some reason)
21586
+ return true;
21587
+ }
21588
+ return false;
21589
+ },
21590
+ });
21591
+ }
21592
+
21593
+ Object.assign(PSEUDO_CLASSES, {
21594
+ ":-navi-pointed": {
21595
+ attribute: "data-pointed",
21596
+ },
21597
+ ":-navi-pointed-by-mouse": {
21598
+ attribute: "data-pointed-by-mouse",
21599
+ },
21600
+ ":-navi-pointed-by-keyboard": {
21601
+ attribute: "data-pointed-by-keyboard",
21602
+ },
21603
+ ":-navi-pointed-by-proxy": {
21604
+ attribute: "data-pointed-by-proxy",
21605
+ },
21606
+ ":-navi-selected": {
21607
+ attribute: "data-selected",
21608
+ },
21609
+ ":-navi-loading": {
21610
+ attribute: "data-loading",
21611
+ },
21612
+ ":-navi-status-info": {
21613
+ attribute: "data-status-info",
21614
+ },
21615
+ ":-navi-status-success": {
21616
+ attribute: "data-status-success",
21617
+ },
21618
+ ":-navi-status-warning": {
21619
+ attribute: "data-status-warning",
21620
+ },
21621
+ ":-navi-status-error": {
21622
+ attribute: "data-status-error",
21623
+ },
21624
+ ":-navi-expanded": {
21625
+ attribute: "data-expanded",
21626
+ },
21627
+ ":-navi-void": {
21628
+ attribute: "data-void",
21629
+ },
21630
+ "::highlight": {},
21631
+ });
21632
+ definePseudoClass(":-navi-has-value", {
21633
+ attribute: "data-has-value",
21634
+ setup: (el, callback) => {
21635
+ const controlHost = findControlHost(el) || el;
21636
+ return addInputEffect(controlHost, callback);
21637
+ },
21638
+ test: (el) => {
21639
+ if (isControlHost(el)) {
21640
+ const uiState = getUIStateFromElement(el);
21641
+ if (uiState === undefined || uiState === "") {
21642
+ return false;
21643
+ }
21644
+ return true;
21645
+ }
21646
+ if (el.value === "") {
21647
+ return false;
21648
+ }
21649
+ return true;
21650
+ },
21651
+ });
21652
+ {
21653
+ const pressedElements = new WeakSet();
21654
+ definePseudoClass(":-navi-pressed", {
21655
+ attribute: "data-pressed",
21656
+ setup: (el, callback) => {
21657
+ // Prefer :-navi-pressed over :active for interactive elements because:
21658
+ // - :active only tracks the primary (left) button; right-click and touch
21659
+ // long-press do not trigger :active reliably across browsers.
21660
+ // - :-navi-pressed explicitly ignores non-primary buttons (e.g. right-click)
21661
+ // and correctly clears pressed state when a context menu opens on long-press,
21662
+ // which would otherwise leave the element stuck in a pressed appearance.
21663
+
21664
+ // Note: it might be tempting to use el.setPointerCapture() here so that pointerup
21665
+ // always fires on el regardless of where the pointer is released. However,
21666
+ // pointer capture routes all subsequent pointer events to the capturing element,
21667
+ // which means any other element in the tree that expects to receive pointerup,
21668
+ // mouseup, click, etc. after a pointerdown will silently not get them.
21669
+ // For example a <label> that reacts to mousedown + click, or a third-party
21670
+ // library that attaches its own listeners, would break because an ancestor
21671
+ // grabbed the pointer out from under them.
21672
+ // To avoid forcing every such element to declare an opt-out attribute
21673
+ // (e.g. navi-own-pointer-capture) we simply listen on document instead,
21674
+ // which is safe and does not interfere with anyone else's event flow.
21675
+ const onPointerDown = (e) => {
21676
+ if (e.button !== 0) {
21677
+ // only left pointer (mouse left click, touch, pen)
21678
+ return;
21679
+ }
21680
+ pressedElements.add(el);
21681
+ const onRelease = () => {
21682
+ pressedElements.delete(el);
21683
+ document.removeEventListener("pointercancel", onRelease, true);
21684
+ document.removeEventListener("pointerup", onRelease, true);
21685
+ document.removeEventListener("contextmenu", onContextMenu, true);
21686
+ callback();
21687
+ };
21688
+ const onContextMenu = (e) => {
21689
+ // On touch devices, a long-press triggers the context menu.
21690
+ // If the context menu is not prevented, it means it will open and the
21691
+ // pointer events (pointerup, lostpointercapture) won't fire normally,
21692
+ // leaving the element stuck in pressed state. We clear it manually.
21693
+ // e.button === -1 means the event was synthesized from a long-press (not a real mouse click).
21694
+ if (e.button === -1 && !e.defaultPrevented) {
21695
+ pressedElements.delete(el);
21696
+ document.removeEventListener("pointercancel", onRelease, true);
21697
+ document.removeEventListener("pointerup", onRelease, true);
21698
+ document.removeEventListener("contextmenu", onContextMenu, true);
21699
+ callback();
21700
+ }
21701
+ };
21702
+ document.addEventListener("pointercancel", onRelease, true);
21703
+ document.addEventListener("pointerup", onRelease, true);
21704
+ document.addEventListener("contextmenu", onContextMenu, true);
21705
+ callback();
21706
+ };
21707
+ el.addEventListener("pointerdown", onPointerDown);
21708
+ return () => {
21709
+ el.removeEventListener("pointerdown", onPointerDown);
21710
+ pressedElements.delete(el);
21711
+ };
21712
+ },
21713
+ test: (el) => pressedElements.has(el),
21714
+ });
21715
+ }
21716
+
21717
+ {
21718
+ definePseudoClass(":-navi-drag-grabbed", {
21719
+ attribute: "navi-drag-grabbed",
21720
+ setup: (el, callback) => {
21721
+ const onGrab = () => {
21722
+ callback();
21723
+ const onRelease = () => {
21724
+ el.removeEventListener("navi_drag_release", onRelease);
21725
+ callback();
21726
+ };
21727
+ el.addEventListener("navi_drag_release", onRelease);
21728
+ };
21729
+ el.addEventListener("navi_drag_grab", onGrab);
21730
+ return () => {
21731
+ el.removeEventListener("navi_drag_grab", onGrab);
21732
+ };
21733
+ },
21734
+ test: (el) => el.hasAttribute("data-drag-grabbed"),
21735
+ });
21736
+ definePseudoClass(":-navi-dragging", {
21737
+ attribute: "navi-dragging",
21738
+ setup: (el, callback) => {
21739
+ const onStart = () => {
21740
+ callback();
21741
+ const onRelease = () => {
21742
+ el.removeEventListener("navi_drag_release", onRelease);
21743
+ callback();
21744
+ };
21745
+ el.addEventListener("navi_drag_release", onRelease);
21746
+ };
21747
+ el.addEventListener("navi_drag_start", onStart);
21748
+ return () => {
21749
+ el.removeEventListener("navi_drag_start", onStart);
21750
+ };
21751
+ },
21752
+ test: (el) => el.hasAttribute("data-dragging"),
21753
+ });
21754
+ }
21755
+
21756
+ const EMPTY_STATE = {};
21757
+ const elementToImpactWeakMap = new WeakMap();
21758
+ const initPseudoStyles = (
21759
+ element,
21760
+ {
21761
+ pseudoClasses,
21762
+ pseudoState, // ":disabled", ":read-only", ":-navi-loading", etc...
21763
+ effect,
21764
+ elementToImpact = element,
21765
+ elementListeningPseudoState,
21766
+ },
21767
+ ) => {
21768
+ elementToImpactWeakMap.set(element, elementToImpact);
21769
+ if (elementListeningPseudoState === element) {
21770
+ console.warn(
21771
+ `elementListeningPseudoState should not be the same as element to avoid infinite loop`,
21772
+ );
21773
+ elementListeningPseudoState = null;
21774
+ }
21775
+
21776
+ const proxyTarget = findControlProxyTarget(element);
21777
+
21778
+ const onStateChange = (value, oldValue) => {
21779
+ effect?.(value, oldValue);
21780
+ if (elementListeningPseudoState) {
21781
+ notifyPseudoStateSubscribers(
21782
+ elementListeningPseudoState,
21783
+ value,
21784
+ oldValue,
21785
+ );
21786
+ }
21787
+ // When this element's state changes, notify any proxy element that mirrors it
21788
+ // so it can re-check and visually reflect the new state.
21789
+ for (const proxy of findControlProxies(element)) {
21790
+ requestPseudoStateCheck(proxy, {});
21791
+ }
21792
+ };
21793
+
21794
+ if (!pseudoClasses || pseudoClasses.length === 0) {
21795
+ onStateChange(EMPTY_STATE);
21796
+ return () => {};
21797
+ }
21798
+
21799
+ const [teardown, addTeardown] = createPubSub();
21800
+
21801
+ let state;
21802
+ const checkPseudoClasses = () => {
21803
+ let someChange = false;
21804
+ const currentState = {};
21805
+ for (const pseudoClass of pseudoClasses) {
21806
+ const pseudoClassDefinition = PSEUDO_CLASSES[pseudoClass];
21807
+ if (!pseudoClassDefinition) {
21808
+ console.warn(`Unknown pseudo class: ${pseudoClass}`);
21809
+ continue;
21810
+ }
21811
+ let currentValue;
21812
+ if (
21813
+ pseudoState &&
21814
+ Object.hasOwn(pseudoState, pseudoClass) &&
21815
+ pseudoState[pseudoClass] !== undefined
21816
+ ) {
21817
+ currentValue = pseudoState[pseudoClass];
21818
+ } else {
21819
+ const { test } = pseudoClassDefinition;
21820
+ if (test) {
21821
+ currentValue = test(element, pseudoState);
21822
+ }
21823
+ }
21824
+ // If this element is a proxy for another (navi-control-proxy-for="targetId"),
21825
+ // inherit the target's active pseudo-state when the element itself isn't in that state.
21826
+ // We check the target's elementToImpact (not the target itself) because the
21827
+ // data-* attribute may be set on a different element (e.g. pseudoStateSelector).
21828
+ if (!currentValue && proxyTarget) {
21829
+ const { attribute } = pseudoClassDefinition;
21830
+ if (attribute) {
21831
+ const targetElementToImpact =
21832
+ elementToImpactWeakMap.get(proxyTarget) || proxyTarget;
21833
+ if (targetElementToImpact.hasAttribute(attribute)) {
21834
+ currentValue = true;
21835
+ }
21836
+ }
21837
+ }
21838
+ currentState[pseudoClass] = currentValue;
21839
+ const oldValue = state ? state[pseudoClass] : undefined;
21840
+ if (oldValue !== currentValue || !state) {
21841
+ someChange = true;
21842
+ const { attribute, add, remove } = pseudoClassDefinition;
21843
+ if (currentValue) {
21844
+ if (attribute) {
21845
+ elementToImpact.setAttribute(attribute, "");
21846
+ }
21847
+ add?.(element);
21848
+ } else {
21849
+ if (attribute) {
21850
+ elementToImpact.removeAttribute(attribute);
21851
+ }
21852
+ remove?.(element);
21853
+ }
21854
+ }
21855
+ }
21856
+ if (!someChange) {
21857
+ return;
21858
+ }
21859
+ const oldState = state;
21860
+ state = currentState;
21861
+ onStateChange(state, oldState);
21862
+ };
21863
+
21864
+ addTeardown(
21865
+ subscribeToPseudoState(element, (pseudoState, oldPseudoState) => {
21866
+ state = pseudoState;
21867
+ onStateChange(state, oldPseudoState);
21868
+ }),
21869
+ );
21870
+ // One function for every way a re-check can be asked, so that setups
21871
+ // registering it side by side (the focus tracking, for one) hold the same
21872
+ // callback and call it once.
21873
+ const requestCheck = () => {
21874
+ checkPseudoClasses();
21875
+ };
21876
+ element.addEventListener("navi_pseudo_state_request_check", requestCheck);
21877
+ addTeardown(() => {
21878
+ element.removeEventListener(
21879
+ "navi_pseudo_state_request_check",
21880
+ requestCheck,
21881
+ );
21882
+ });
21883
+
21884
+ for (const pseudoClass of pseudoClasses) {
21885
+ const pseudoClassDefinition = PSEUDO_CLASSES[pseudoClass];
21886
+ if (!pseudoClassDefinition) {
21887
+ console.warn(`Unknown pseudo class: ${pseudoClass}`);
21888
+ continue;
21889
+ }
21890
+ const { setup } = pseudoClassDefinition;
21891
+ if (setup) {
21892
+ const cleanup = setup(element, requestCheck);
21893
+ addTeardown(cleanup);
21894
+ }
21895
+ }
21896
+ checkPseudoClasses();
21897
+
21898
+ return teardown;
21899
+ };
21900
+
21901
+ const applyStyle = (
21902
+ element,
21903
+ style,
21904
+ pseudoState,
21905
+ pseudoNamedStyles,
21906
+ preventInitialTransition,
21907
+ ) => {
21908
+ if (!element) {
21909
+ return;
21910
+ }
21911
+ const styleToApply = getStyleToApply(style, pseudoState, pseudoNamedStyles);
21912
+ // The same object comes back for every state change of a box whose inline
21913
+ // style has no pseudo entry: nothing to write.
21914
+ if (appliedStyleWeakMap.get(element) === styleToApply) {
21915
+ return;
21916
+ }
21917
+ updateStyle(element, styleToApply, preventInitialTransition);
21918
+ };
21919
+
21920
+ const PSEUDO_STATE_DEFAULT = {};
21921
+ const PSEUDO_NAMED_STYLES_DEFAULT = {};
21922
+ const getStyleToApply = (styles, pseudoState, pseudoNamedStyles) => {
21923
+ if (
21924
+ !pseudoState ||
21925
+ pseudoState === PSEUDO_STATE_DEFAULT ||
21926
+ !pseudoNamedStyles ||
21927
+ pseudoNamedStyles === PSEUDO_NAMED_STYLES_DEFAULT
21928
+ ) {
21929
+ return styles;
21930
+ }
21931
+ let style = styles;
21932
+ for (const pseudoKey of Object.keys(pseudoNamedStyles)) {
21933
+ if (!hasEveryState(pseudoState, getPseudoKeyRequiredStates(pseudoKey))) {
21934
+ continue;
21935
+ }
21936
+ if (style === styles) {
21937
+ style = { ...styles };
21938
+ }
21939
+ // Both sides are already normalized for CSS by the box; only the
21940
+ // properties that compose (a press scale on top of a translate) go through
21941
+ // a merge, the rest is a plain override.
21942
+ const styleToAdd = pseudoNamedStyles[pseudoKey];
21943
+ for (const key of Object.keys(styleToAdd)) {
21944
+ const value = styleToAdd[key];
21945
+ if (value === undefined) {
21946
+ continue;
21947
+ }
21948
+ if (key === "transform" || key === "willChange") {
21949
+ style[key] = mergeOneStyle(style[key], value, key, "css");
21950
+ } else {
21951
+ style[key] = value;
21952
+ }
21953
+ }
21954
+ }
21955
+ return style;
21956
+ };
21957
+
21958
+ // The state names a pseudo key asks for, parsed once: the same few keys come
21959
+ // back on every state change of every box that has them. "::x" alone always
21960
+ // matches; "::x:a:b" and ":a:b" ask for ":a" and ":b" — the state keys as
21961
+ // checkPseudoClasses writes them, colon included.
21962
+ const pseudoKeyRequiredStatesMap = new Map();
21963
+ const getPseudoKeyRequiredStates = (pseudoKey) => {
21964
+ const cached = pseudoKeyRequiredStatesMap.get(pseudoKey);
21965
+ if (cached) {
21966
+ return cached;
21967
+ }
21968
+ let requiredStates;
21969
+ if (pseudoKey.startsWith("::")) {
21970
+ const nextColonIndex = pseudoKey.indexOf(":", 2);
21971
+ requiredStates =
21972
+ nextColonIndex === -1
21973
+ ? []
21974
+ : getPseudoKeyRequiredStates(pseudoKey.slice(nextColonIndex));
21975
+ } else {
21976
+ const nextColonIndex = pseudoKey.indexOf(":", 1);
21977
+ requiredStates =
21978
+ nextColonIndex === -1
21979
+ ? [pseudoKey]
21980
+ : pseudoKey
21981
+ .slice(1)
21982
+ .split(":")
21983
+ .map((state) => `:${state}`);
21984
+ }
21985
+ pseudoKeyRequiredStatesMap.set(pseudoKey, requiredStates);
21986
+ return requiredStates;
21987
+ };
21988
+ const hasEveryState = (pseudoState, states) => {
21989
+ for (const state of states) {
21990
+ if (!pseudoState[state]) {
21991
+ return false;
21992
+ }
21993
+ }
21994
+ return true;
21995
+ };
21996
+
21997
+ // element → the style object last written to it, so the next one is written
21998
+ // as a difference: the values that changed, the keys it no longer has.
21999
+ const appliedStyleWeakMap = new WeakMap();
22000
+ const elementTransitionWeakMap = new WeakMap();
22001
+ const elementRenderedWeakSet = new WeakSet();
22002
+ const NO_STYLE = {};
22003
+ const updateStyle = (element, style, preventInitialTransition) => {
22004
+ const styleToApply = style || NO_STYLE;
22005
+ const styleApplied = appliedStyleWeakMap.get(element) || NO_STYLE;
22006
+ // TRANSITION ANTI-FLICKER STRATEGY:
22007
+ // Problem: When setting both transition and styled properties simultaneously
22008
+ // (e.g., el.style.transition = "border-radius 0.3s ease"; el.style.borderRadius = "20px"),
22009
+ // the browser will immediately perform a transition even if no transition existed before.
22010
+ //
22011
+ // Solution: Temporarily disable transitions during initial style application by setting
22012
+ // transition to "none", then restore the intended transition after the frame completes.
22013
+ // We handle multiple updateStyle calls in the same frame gracefully - only one
22014
+ // requestAnimationFrame is scheduled per element, and the final transition value wins.
22015
+ let skipTransition = false;
22016
+ if (!elementRenderedWeakSet.has(element)) {
22017
+ const hasTransition = Object.hasOwn(styleToApply, "transition");
22018
+ if (hasTransition || preventInitialTransition) {
22019
+ if (!elementTransitionWeakMap.has(element)) {
22020
+ element.style.transition = "none";
22021
+ }
22022
+ elementTransitionWeakMap.set(element, styleToApply.transition);
22023
+ // Stays "none" until the first frame puts the intended value back
22024
+ skipTransition = true;
22025
+ }
22026
+ afterFirstFrame(element);
22027
+ }
22028
+
22029
+ for (const key of Object.keys(styleToApply)) {
22030
+ const value = styleToApply[key];
22031
+ if (value === undefined || value === null) {
22032
+ // a removal: handled below with the keys this style no longer has
22033
+ continue;
22034
+ }
22035
+ if (skipTransition && key === "transition") {
22036
+ continue;
22037
+ }
22038
+ if (styleApplied[key] === value) {
22039
+ continue;
22040
+ }
22041
+ if (key.startsWith("--")) {
22042
+ element.style.setProperty(key, value);
22043
+ } else {
22044
+ element.style[key] = value;
22045
+ }
22046
+ }
22047
+
22048
+ for (const key of Object.keys(styleApplied)) {
22049
+ const previousValue = styleApplied[key];
22050
+ if (previousValue === undefined || previousValue === null) {
22051
+ continue;
22052
+ }
22053
+ const value = styleToApply[key];
22054
+ if (value !== undefined && value !== null) {
22055
+ continue;
22056
+ }
22057
+ if (key.startsWith("--")) {
22058
+ element.style.removeProperty(key);
22059
+ } else {
22060
+ element.style[key] = "";
22061
+ }
22062
+ }
22063
+
22064
+ appliedStyleWeakMap.set(element, styleToApply);
22065
+ };
22066
+
22067
+ // One frame for every element waiting for its first one, not one frame each.
22068
+ // What this owes each element — put back the transition suppressed above, and
22069
+ // remember it has now been painted once — is a few microseconds, while asking
22070
+ // the browser for a frame costs more than that, and a page mounting thousands of
22071
+ // boxes asks thousands of times in the same tick. A Set, so an element styled
22072
+ // twice before the frame arrives is still one entry.
22073
+ let elementSetWaitingFirstFrame = new Set();
22074
+ let firstFrameScheduled = false;
22075
+ const afterFirstFrame = (element) => {
22076
+ elementSetWaitingFirstFrame.add(element);
22077
+ if (firstFrameScheduled) {
22078
+ return;
22079
+ }
22080
+ firstFrameScheduled = true;
22081
+ requestAnimationFrame(() => {
22082
+ firstFrameScheduled = false;
22083
+ const elements = elementSetWaitingFirstFrame;
22084
+ elementSetWaitingFirstFrame = new Set();
22085
+ for (const element of elements) {
22086
+ if (elementTransitionWeakMap.has(element)) {
22087
+ const transitionToRestore = elementTransitionWeakMap.get(element);
22088
+ if (transitionToRestore === undefined) {
22089
+ element.style.transition = "";
22090
+ } else {
22091
+ element.style.transition = transitionToRestore;
22092
+ }
22093
+ elementTransitionWeakMap.delete(element);
22094
+ }
22095
+ elementRenderedWeakSet.add(element);
22096
+ }
22097
+ });
22098
+ };
22099
+
19414
22100
  /**
19415
22101
  * Keeps a DOM element in sync with `syncElement(el)` whenever syncElement changes.
19416
22102
  * - If element is already mounted: runs syncElement immediately during render.
@@ -86628,6 +89314,105 @@ const createSlot = (SlotRenderer = Box) => {
86628
89314
  return [Slot, SlotFill];
86629
89315
  };
86630
89316
 
89317
+ /**
89318
+ * The on-screen keyboard overlaying the app rather than resizing the viewport,
89319
+ * for an app that asks for it (the VirtualKeyboard API — Chromium only). See
89320
+ * virtual_keyboard.js in @jsenv/dom for what that trades away and what it
89321
+ * gives back.
89322
+ *
89323
+ * Offered, never taken by default. Overlaying means redoing by hand what the
89324
+ * browser does for a viewport that shrinks, and on a phone every piece of it
89325
+ * hid a Chrome behavior nothing reports: the focused field left under the
89326
+ * keyboard, a suggestion strip painted above the keyboard outside its
89327
+ * geometry, geometrychange firing while the page is merely scrolled. Firefox
89328
+ * and Safari shrink the viewport whatever the app wants, and navi follows that
89329
+ * already (--navi-vvh), so the default is the path every browser shares.
89330
+ *
89331
+ * What the overlay buys: no reflow of the page underneath — a resizing
89332
+ * viewport is a resize of everything, fired transiently every time focus goes
89333
+ * from one input to the next — while navi still sizes what escapes normal flow
89334
+ * against a rectangle the keyboard is subtracted from
89335
+ * (--navi-keyboard-inset-bottom, safe_area.js).
89336
+ *
89337
+ * Taking the deal means taking over what the browser stops doing under it:
89338
+ * bringing the focused field out from under the keyboard. A viewport that
89339
+ * shrinks makes the browser scroll to the field; a keyboard that merely paints
89340
+ * over the page leaves whatever is under it under it. So enabling the overlay
89341
+ * also installs that scroll, with two things safe_area.js provides: a
89342
+ * scroll-padding-bottom that counts the keyboard in, plus an allowance for the
89343
+ * strip Chrome paints above it without reporting it
89344
+ * (--navi-keyboard-strip-allowance), which bounds the band the field is brought
89345
+ * into; and room at the end of the scroller, so a field near the end of the
89346
+ * page has somewhere to go. All of it reads 0 while the keyboard does not
89347
+ * overlay.
89348
+ *
89349
+ * Only the arrival is navi's: once the field is in view, Chrome keeps the caret
89350
+ * there itself as typing grows a textarea, against that same
89351
+ * scroll-padding-bottom.
89352
+ */
89353
+
89354
+
89355
+ /**
89356
+ * Makes the on-screen keyboard overlay the app instead of shrinking the
89357
+ * viewport, and brings the focused field out from under it. A no-op on
89358
+ * Firefox/Safari, which have no VirtualKeyboard API.
89359
+ *
89360
+ * @returns {() => void} Goes back to the viewport shrinking.
89361
+ */
89362
+ const enableVirtualKeyboardOverlay = () => {
89363
+ if (!setVirtualKeyboardOverlaysContent(true)) {
89364
+ return () => {};
89365
+ }
89366
+ // The keyboard rising, or changing height (suggestion strip, emoji panel).
89367
+ const unsubscribeGeometryChange =
89368
+ subscribeVirtualKeyboardGeometryChange(revealFocusedField);
89369
+ // From one field to the next with the keyboard up: when both want the same
89370
+ // keyboard it does not move, and no geometrychange fires.
89371
+ document.addEventListener("focusin", revealFocusedField, { capture: true });
89372
+ return () => {
89373
+ unsubscribeGeometryChange();
89374
+ document.removeEventListener("focusin", revealFocusedField, {
89375
+ capture: true,
89376
+ });
89377
+ setVirtualKeyboardOverlaysContent(false);
89378
+ };
89379
+ };
89380
+
89381
+ const revealFocusedField = () => {
89382
+ if (getVirtualKeyboardOverlayHeight() === 0) {
89383
+ return;
89384
+ }
89385
+ const field = document.activeElement;
89386
+ if (!isEditableTarget(field)) {
89387
+ return;
89388
+ }
89389
+ if (isInDocumentBand(field)) {
89390
+ return;
89391
+ }
89392
+ // "center" rather than "nearest": nearest stops the field on the band's
89393
+ // edge, clear of the strip only by the allowance. The middle of the band
89394
+ // clears a strip taller than guessed too — and centering what is not fully
89395
+ // visible is what Chrome does itself when the viewport shrinks.
89396
+ scrollIntoViewThroughScrollables(field, {
89397
+ block: "center",
89398
+ behavior: "instant",
89399
+ });
89400
+ };
89401
+ // The band the document leaves visible: inside its scroll-padding (the bars,
89402
+ // the keyboard and its strip, see safe_area.js). Against the window rather
89403
+ // than each scroller's own band: the keyboard covers the window, and a field
89404
+ // hidden inside its own scroller is what the browser's focus already scrolls
89405
+ // to.
89406
+ const isInDocumentBand = (field) => {
89407
+ const documentElement = document.documentElement;
89408
+ const style = getComputedStyle(documentElement);
89409
+ const bandTop = parseFloat(style.scrollPaddingTop) || 0;
89410
+ const bandBottom =
89411
+ documentElement.clientHeight - (parseFloat(style.scrollPaddingBottom) || 0);
89412
+ const { top, bottom } = field.getBoundingClientRect();
89413
+ return top >= bandTop && bottom <= bandBottom;
89414
+ };
89415
+
86631
89416
  /*
86632
89417
  * - Usage
86633
89418
  * useEffect(() => {
@@ -86791,5 +89576,5 @@ const UserSvg = () => jsx("svg", {
86791
89576
  })
86792
89577
  });
86793
89578
 
86794
- export { ActionRenderer, ActiveKeyboardShortcuts, Address, Badge, BadgeCount, BadgeList, Binder, Box, Button, ButtonCopyToClipboard, CalloutStatusIcon, Caption, CardLayout, CheckSvg, CheckboxGroup, CloseSvg, Code, Col, Colgroup, Color, ConstructionSvg, ControlGroup, ControlSwap, DaySpin, Details, Dialog, Editable, ErrorBoundary, ErrorBoundaryContext, ExclamationSvg, Expandable, EyeClosedSvg, EyeSvg, Field, FixedBar, Form, Group, Head, HeartSvg, HomeSvg, Icon, Image, InfoSvg, Input, InputDuration, Interpolate, Label, Link, LinkAnchorSvg, LinkBlankTargetSvg, LinkCurrentSvg, List, ListItem, ListItemGroup, ListItems, Loading, LoadingDotsSvg, LoadingIndicator, LoadingIndicatorFluid, LoadingOutline, MessageBox, Meter, Nav, NaviDebug, NetworkPolicyError, NumberSpin, Paragraph, Picker, Popover, Popup, Quantity, RadioGroup, Route, RouteTransitionArea, RouteTravel, RowNumberCol, RowNumberTableCell, SVGMaskOverlay, SearchSvg, Select, SelectableInput, SelectionContext, Separator, SettingsSvg, SidePanel, Slide, SlideContainer, Spin, SpinGroup, SplitButton, StarSvg, Step, StepList, SummaryMarker, Svg, Table, TableCell, Tbody, Text, TextBox, Textarea, TextareaCharCount, Thead, Time, TimeRange, TimeRangeSpin, TimeRangeWheel, TimeSpin, TimeWheel, Title, Tr, UITransition, Unit, UserSvg, ViewportLayout, Wheel, WheelGroup, WheelItem, actionRunEffect, anyMatchingRouteSignal, applySearch, arraySignalMembership, canNavBackSignal, canNavForwardSignal, coarsePointerSignal, compareTwoJsValues, constraintFromValidityRule, createAction, createAvailableConstraint, createRequestCanceller, createSearch, createSelectionKeyboardShortcuts, createSlot, defineInteractionDetector, defineRouteDefaultTransition, defineRouteTransition, detectHorizontalOverflow, dispatchRequestSetUIState, enableDebugActions, enableDebugOnDocumentLoading, ensureDocumentStartViewTransition, errorIsDisplayed, filterTableSelection, isCellSelected, isColumnSelected, isNetworkPolicyError, isRowSelected, isScrolling, languagesSignal, localStorageSignal, markAsOutsideTextFlow, markErrorAsDisplayedBy, moveArrayItemByIndex, moveFocusTo, navBack, navForward, navIntegratedVia, navTo, naviI18n, openCallout, preloadUrl, rawUrlPart, registerGlobalConstraint, reload, rerunActions, resource, route, routeAction, routeFallback, scrollActivitySignal, setBaseUrl, setNetworkPolicy, setPreferredLanguage, setSupportedLanguages, setUrlTargetOptions, setupRoutes, smallTouchScreenSignal, stateSignal, stopLoad, stringifyTableSelectionValue, swapArrayItemByIndex, syncOwnedResourceToSignals, syncResourceToSignals, triggerNaviCommand, updateActions, useActionStatus, useArraySignalMembership, useAsyncData, useCalloutElement, useCalloutRequestClose, useCanNavBack, useCanNavForward, useCancelPrevious, useCellGridFromRows, useConstraintValidityState, useDependenciesDiff, useDisplayedLayoutEffect, useDocumentResource, useDocumentState, useDocumentUrl, useEditionController, useFocusGroup, useInputGroup, useKeyboardShortcuts, useNavState, useNetworkPolicyReason, useOrderedColumns, usePickerState, usePopupMode, useRouteStatus, useSearchText, useSelectableElement, useSelectionController, useSignalSync, useSlideContainer, useSlideValue, useStateArray, useTitleLevel, useTransitionCover, useUrlSearchParam, useUrlTargetId, valueInLocalStorage, windowWidthSignal };
89579
+ export { ActionRenderer, ActiveKeyboardShortcuts, Address, Badge, BadgeCount, BadgeList, Binder, Box, Button, ButtonCopyToClipboard, CalloutStatusIcon, Caption, CardLayout, CheckSvg, CheckboxGroup, CloseSvg, Code, Col, Colgroup, Color, ConstructionSvg, ControlGroup, ControlSwap, DaySpin, Details, Dialog, Editable, ErrorBoundary, ErrorBoundaryContext, ExclamationSvg, Expandable, EyeClosedSvg, EyeSvg, Field, FixedBar, Form, Group, Head, HeartSvg, HomeSvg, Icon, Image, InfoSvg, Input, InputDuration, Interpolate, Label, Link, LinkAnchorSvg, LinkBlankTargetSvg, LinkCurrentSvg, List, ListItem, ListItemGroup, ListItems, Loading, LoadingDotsSvg, LoadingIndicator, LoadingIndicatorFluid, LoadingOutline, MessageBox, Meter, Nav, NaviDebug, NetworkPolicyError, NumberSpin, Paragraph, Picker, Popover, Popup, Quantity, RadioGroup, Route, RouteTransitionArea, RouteTravel, RowNumberCol, RowNumberTableCell, SVGMaskOverlay, SearchSvg, Select, SelectableInput, SelectionContext, Separator, SettingsSvg, SidePanel, Slide, SlideContainer, Spin, SpinGroup, SplitButton, StarSvg, Step, StepList, SummaryMarker, Svg, Table, TableCell, Tbody, Text, TextBox, Textarea, TextareaCharCount, Thead, Time, TimeRange, TimeRangeSpin, TimeRangeWheel, TimeSpin, TimeWheel, Title, Tr, UITransition, Unit, UserSvg, ViewportLayout, Wheel, WheelGroup, WheelItem, actionRunEffect, anyMatchingRouteSignal, applySearch, arraySignalMembership, canNavBackSignal, canNavForwardSignal, coarsePointerSignal, compareTwoJsValues, constraintFromValidityRule, createAction, createAvailableConstraint, createRequestCanceller, createSearch, createSelectionKeyboardShortcuts, createSlot, defineInteractionDetector, defineRouteDefaultTransition, defineRouteTransition, detectHorizontalOverflow, dispatchRequestSetUIState, enableDebugActions, enableDebugOnDocumentLoading, enableVirtualKeyboardOverlay, ensureDocumentStartViewTransition, errorIsDisplayed, filterTableSelection, getNowHours, getNowHoursRoundedToStep, isCellSelected, isColumnSelected, isNetworkPolicyError, isRowSelected, isScrolling, isToday, languagesSignal, localStorageSignal, markAsOutsideTextFlow, markErrorAsDisplayedBy, moveArrayItemByIndex, moveFocusTo, navBack, navForward, navIntegratedVia, navTo, naviI18n, openCallout, preloadUrl, rawUrlPart, registerGlobalConstraint, reload, rerunActions, resource, route, routeAction, routeFallback, scrollActivitySignal, setBaseUrl, setNetworkPolicy, setPreferredLanguage, setSupportedLanguages, setUrlTargetOptions, setupRoutes, smallTouchScreenSignal, stateSignal, stopLoad, stringifyTableSelectionValue, swapArrayItemByIndex, syncOwnedResourceToSignals, syncResourceToSignals, triggerNaviCommand, updateActions, useActionStatus, useArraySignalMembership, useAsyncData, useCalloutElement, useCalloutRequestClose, useCanNavBack, useCanNavForward, useCancelPrevious, useCellGridFromRows, useConstraintValidityState, useDependenciesDiff, useDisplayedLayoutEffect, useDocumentResource, useDocumentState, useDocumentUrl, useEditionController, useFocusGroup, useInputGroup, useKeyboardShortcuts, useNavState, useNetworkPolicyReason, useOrderedColumns, usePickerState, usePopupMode, useRouteStatus, useSearchText, useSelectableElement, useSelectionController, useSignalSync, useSlideContainer, useSlideValue, useStateArray, useTitleLevel, useTransitionCover, useUrlSearchParam, useUrlTargetId, valueInLocalStorage, windowWidthSignal };
86795
89580
  //# sourceMappingURL=jsenv_navi.js.map