UNPKG

@llselect/core

Version:

Low-level select: a minimal, flexible, framework-agnostic replacement for the native HTML select element.

7,731 lines • 373 kB
// Positioner: places `floating` (popup) relative to `anchor` (trigger).
// Pure math is split into `computePosition` so it can be tested without layout.
/**
 * Package-internal: the default of `PositionInput.distanceFromAnchor`, and of
 * the `popupDistanceFromTriggerWrapper` setting.
 */
const DEFAULT_DISTANCE_FROM_ANCHOR = 4;
/**
 * Package-internal: the default of `PositionInput.distanceFromViewportEdge`,
 * and of the `popupDistanceFromViewportEdge` setting.
 */
const DEFAULT_DISTANCE_FROM_VIEWPORT_EDGE = 8;
/**
 * Compute where to place the floating element relative to the anchor.
 * - The window here is the visible window, in layout-viewport coordinates,
 *   those of `position: fixed`.
 * - The anchor rect and the result use the same coordinates.
 * - Across, it spans `[viewportLeft, viewportLeft + viewportWidth]`.
 * - Down, it spans `[viewportTop, viewportTop + viewportHeight]`.
 * - Both offsets are 0 unless the visual viewport is panned. See
 *   {@link PositionInput.viewportLeft}.
 * - Vertically, the floating element goes below the anchor if it fits there.
 * - Otherwise it goes above the anchor, if it fits there.
 * - If it fits on neither side, it takes the side with more room.
 * - `maxHeight` limits it to the room on its side.
 * - A `currentPlacement` that still fits is kept.
 * - Keeping it means that a list that shrinks and regrows does not make the
 *   popup jump sides.
 * - The floating element keeps a gap of `distanceFromAnchor` from the anchor.
 * - Below the anchor, its room ends `distanceFromViewportEdge` above the
 *   bottom of the window.
 * - Above the anchor, its room starts the same distance below the top of the
 *   window.
 * - A negative value of either distance counts as 0.
 * - It also stays inside the window vertically when the anchor is outside it:
 *   - If the anchor's top lies below the window, the bottom of the window
 *     stands in for that top.
 *   - An anchor under the on-screen keyboard is such a case.
 *   - If the anchor's bottom lies above the window, the top of the window
 *     stands in for that bottom.
 *   - The floating element then no longer touches the anchor.
 * - While the anchor's edge next to the floating element is inside the
 *   window, the placement is exactly the one without the rule above.
 * - If the chosen side has no room at all, `maxHeight` is 0.
 * - If, in addition, the anchor's edge next to the floating element lies
 *   outside the window, `top` is kept inside the window.
 * - Horizontally, `widthPolicy === 'fit-content'`, the default, makes `width`
 *   the larger of the anchor's width and `floatingNaturalWidth`.
 * - That width is at most the window's width minus two side margins.
 * - A side margin is `distanceFromViewportEdge`, and at most half the
 *   window's width, so the two margins never cross.
 * - In ltr, the floating element starts at the anchor's left edge.
 * - In ltr, it grows rightward.
 * - In rtl, it starts at the anchor's right edge.
 * - In rtl, it grows leftward.
 * - If it then crosses a side margin, it shifts back inside the margins.
 * - `widthPolicy === 'match-trigger-wrapper'` copies the anchor's `width`.
 * - That policy also copies the anchor's `left`.
 * - That policy ignores `direction`.
 * - That policy has no horizontal clamp.
 */
function computePosition(input) {
    const { anchorRect, viewportWidth, viewportHeight, viewportLeft = 0, viewportTop = 0, floatingHeight, widthPolicy = 'fit-content', floatingNaturalWidth = 0, direction = 'ltr', currentPlacement, } = input;
    // Neither distance may be negative: the rules below rest on a floating
    // element that starts beyond the anchor and ends inside its margin.
    const distanceFromAnchor = Math.max(0, input.distanceFromAnchor ?? DEFAULT_DISTANCE_FROM_ANCHOR);
    const distanceFromViewportEdge = Math.max(0, input.distanceFromViewportEdge ?? DEFAULT_DISTANCE_FROM_VIEWPORT_EDGE);
    const viewportBottom = viewportTop + viewportHeight;
    // A visible edge stands in for an anchor edge beyond it: an anchor under the
    // on-screen keyboard still counts as visible, since the hidden check reads
    // the layout viewport.
    const belowStart = Math.max(anchorRect.bottom, viewportTop) + distanceFromAnchor;
    const aboveEnd = Math.min(anchorRect.top, viewportBottom) - distanceFromAnchor;
    const spaceBelow = viewportBottom - distanceFromViewportEdge - belowStart;
    const spaceAbove = aboveEnd - viewportTop - distanceFromViewportEdge;
    const fitsBelow = floatingHeight <= spaceBelow;
    const fitsAbove = floatingHeight <= spaceAbove;
    const currentStillFits = (currentPlacement === 'below' && fitsBelow) ||
        (currentPlacement === 'above' && fitsAbove);
    let placement;
    if (currentStillFits && currentPlacement !== undefined) {
        placement = currentPlacement;
    }
    else if (fitsBelow) {
        placement = 'below';
    }
    else if (fitsAbove) {
        placement = 'above';
    }
    else {
        placement = spaceAbove > spaceBelow ? 'above' : 'below';
    }
    let top;
    let maxHeight;
    if (placement === 'below') {
        top = belowStart;
        maxHeight = Math.max(0, spaceBelow);
    }
    else {
        maxHeight = Math.max(0, spaceAbove);
        top = aboveEnd - Math.min(floatingHeight, maxHeight);
    }
    // Only a side with no room at all can put `top` outside the visible window.
    // The clamp spares an anchor whose edge next to the popup is visible, which
    // keeps exactly the placement it had before the visible edge stood in.
    const anchorEdge = placement === 'below' ? anchorRect.bottom : anchorRect.top;
    if (anchorEdge < viewportTop || anchorEdge > viewportBottom) {
        top = Math.min(Math.max(top, viewportTop), viewportBottom);
    }
    let width;
    let left;
    if (widthPolicy === 'match-trigger-wrapper') {
        width = anchorRect.width;
        left = anchorRect.left;
    }
    else {
        const desiredWidth = Math.max(anchorRect.width, floatingNaturalWidth);
        // Each side margin is at most half the window, so the two never cross.
        const sideMargin = Math.min(distanceFromViewportEdge, viewportWidth / 2);
        const maxAvailable = viewportWidth - 2 * sideMargin;
        width = Math.min(desiredWidth, Math.max(0, maxAvailable));
        const leftEdge = viewportLeft + sideMargin;
        const rightEdge = viewportLeft + viewportWidth - sideMargin;
        if (direction === 'rtl') {
            // Mirror of ltr: right edges aligned, growth goes leftward; push back
            // inside the LEFT margin first, then clamp at the right one.
            left = anchorRect.right - width;
            if (left < leftEdge) {
                left = leftEdge;
            }
            if (left + width > rightEdge) {
                left = rightEdge - width;
            }
        }
        else {
            left = anchorRect.left;
            if (left + width > rightEdge) {
                left = rightEdge - width;
            }
            if (left < leftEdge) {
                left = leftEdge;
            }
        }
    }
    return { top, left, width, maxHeight, placement };
}
// The hidden-trigger check (DESIGN.md "Hidden-trigger check"): is the anchor
// fully outside an ancestor's overflow clip that applies to it? The rect alone
// misses this, since getBoundingClientRect reports viewport coordinates
// whatever the ancestors clip.
const CLIPPING_OVERFLOW = new Set(['hidden', 'auto', 'scroll', 'clip']);
function containingBlockScheme(position) {
    if (position === 'fixed') {
        return 'fixed';
    }
    if (position === 'absolute') {
        return 'absolute';
    }
    return 'flow';
}
// A property the browser does not support reads as ''.
function isSet(value) {
    return value !== '' && value !== 'none';
}
// jsdom reads a property that no rule sets as '', where a browser reports the
// initial value.
function orDefault(value, initial) {
    return value === '' ? initial : value;
}
/**
 * Package-internal (tests): whether the element has containment of any kind,
 * from `contain` or from what `content-visibility` and `container-type` apply.
 */
function hasContainment(s) {
    const visibility = s.getPropertyValue('content-visibility');
    return isSet(s.getPropertyValue('contain')) || visibility === 'auto' || visibility === 'hidden' ||
        /\b(size|inline-size)\b/.test(s.getPropertyValue('container-type'));
}
// WebKit 18.4 does not let `filter` hold fixed-position descendants, while
// WebKit 26.5, Chromium 156 and Firefox 153 do (measured). A probe inside the
// anchor answers, the first time the walk meets a filter: a fixed child of a
// filtered box lands on that box only where the filter holds it. A conclusive
// answer is kept for the page.
let filterHoldsFixed;
function probeFilterHoldsFixed(anchor) {
    if (filterHoldsFixed !== undefined) {
        return filterHoldsFixed;
    }
    const doc = anchor.ownerDocument;
    // `all: initial !important` first, so no page rule can change the position
    // or size of either element, whether it sets a margin, a translate or
    // `display: none`. `all` spares only `direction`, `unicode-bidi` and custom
    // properties: the probe uses no `var()`, and the other two do not move a
    // box placed by `left` and `top`. Every later declaration needs
    // `!important`, or the reset wins over it.
    const box = doc.createElement('div');
    box.style.cssText = 'all: initial !important; display: block !important; position: absolute !important; left: 17px !important; top: 13px !important; width: 0 !important; height: 0 !important; visibility: hidden !important; filter: blur(0px) !important';
    const child = doc.createElement('div');
    child.style.cssText = 'all: initial !important; display: block !important; position: fixed !important; left: 0 !important; top: 0 !important; width: 0 !important; height: 0 !important; visibility: hidden !important';
    box.appendChild(child);
    anchor.appendChild(box);
    // A user style marked `!important` outranks these. The guard catches one
    // that makes the box a creator through another property, where the filter
    // is not what holds the child. One that changes the position or size of
    // either element, such as moving the child, removing the child's layout box
    // with `display: none`, or putting a border on the box, can still decide
    // the answer (DESIGN.md "Hidden-trigger check", its known limits).
    const heldOtherwise = createsContainingBlock(window.getComputedStyle(box), () => false);
    const outer = box.getBoundingClientRect();
    const inner = child.getBoundingClientRect();
    box.remove();
    // The box at the viewport origin decides nothing: it has no layout box (a
    // `display: none` subtree), or a scroll cancels its offset. Answer "does
    // not hold", which can only miss a clip, and probe again next time.
    if (heldOtherwise || (outer.left === 0 && outer.top === 0)) {
        return false;
    }
    filterHoldsFixed = inner.left === outer.left && inner.top === outer.top;
    return filterHoldsFixed;
}
// The `will-change` names that make a containing block, matched whole:
// `transform-origin` names no transform.
const WILL_CHANGE_CONTAINING_BLOCK = new Set(['transform', 'translate', 'rotate', 'scale', 'perspective', 'filter', 'backdrop-filter', 'contain', 'offset-path']);
/**
 * Package-internal (tests): whether an element with this computed style is
 * the containing block of its fixed-position descendants, and so of its
 * absolute ones as well. The list is the one DESIGN.md "Hidden-trigger check"
 * keeps. `filterHoldsFixedFn` answers for `filter`, the one counted property
 * whose answer differs between engines; it runs only when `filter` is set.
 */
function createsContainingBlock(s, filterHoldsFixedFn) {
    // A non-replaced inline box takes no transform and no containment; measured,
    // `backdrop-filter` and the probed `filter` hold a fixed child there. This
    // can miss a clip in two cases: an inline `<svg>`, which is replaced and
    // takes a transform, and `will-change: filter` or
    // `will-change: backdrop-filter`, which hold there in Chromium and Firefox
    // only.
    if (orDefault(s.display, 'inline') === 'inline') {
        return isSet(s.getPropertyValue('backdrop-filter')) || (isSet(s.getPropertyValue('filter')) && filterHoldsFixedFn());
    }
    for (const name of ['transform', 'translate', 'rotate', 'scale', 'perspective', 'backdrop-filter']) {
        if (isSet(s.getPropertyValue(name))) {
            return true;
        }
    }
    const visibility = s.getPropertyValue('content-visibility');
    if (s.getPropertyValue('transform-style') === 'preserve-3d' ||
        /\b(layout|paint|strict|content)\b/.test(s.getPropertyValue('contain')) || visibility === 'auto' || visibility === 'hidden' ||
        s.getPropertyValue('will-change').split(',').some((name) => WILL_CHANGE_CONTAINING_BLOCK.has(name.trim()))) {
        return true;
    }
    return isSet(s.getPropertyValue('filter')) && filterHoldsFixedFn();
}
// A browser older than the selector throws, which reads as no match.
function matchesSafely(el, selector) {
    try {
        return el.matches(selector);
    }
    catch {
        return false;
    }
}
// The top layer, which no ancestor clips: a modal dialog, a showing popover or
// a fullscreen element. A fullscreen element is the one
// `document.fullscreenElement` names, or, since that property names the
// shadow host of an element fullscreened inside a shadow tree, one that
// matches `:fullscreen` while the property is set. Where the selectors are
// missing, the fixed rule of the walk still covers a modal dialog, which the
// UA style makes fixed.
function isInTopLayer(el) {
    const fullscreen = el.ownerDocument.fullscreenElement;
    if (fullscreen !== null && fullscreen !== undefined && (fullscreen === el || matchesSafely(el, ':fullscreen'))) {
        return true;
    }
    if (el.localName === 'dialog' && matchesSafely(el, ':modal')) {
        return true;
    }
    return el.hasAttribute('popover') && matchesSafely(el, ':popover-open');
}
// The body's overflow applies to the viewport, not to the body's own box,
// while the root's overflow is `visible` in both axes and neither element has
// containment (CSS Overflow 3 "Overflow Viewport Propagation"; CSS
// Containment 2, the `contain` property).
function isBodyOverflowPropagated(doc, bodyStyle) {
    const root = window.getComputedStyle(doc.documentElement);
    return orDefault(root.overflowX, 'visible') === 'visible' && orDefault(root.overflowY, 'visible') === 'visible' &&
        !hasContainment(root) && !hasContainment(bodyStyle);
}
// Overflow applies to block, flex and grid containers, never to an inline box
// or a table track (measured: an `overflow: hidden` span or table row clips
// nothing).
const NO_OVERFLOW_DISPLAY = new Set(['inline', 'table-row', 'table-row-group', 'table-header-group', 'table-footer-group', 'table-column', 'table-column-group']);
// Each axis is tested only where its own overflow clips: `overflow-x: clip`
// leaves `overflow-y: visible`.
function clipsRect(el, s, rect) {
    if (NO_OVERFLOW_DISPLAY.has(orDefault(s.display, 'inline'))) {
        return false;
    }
    const clipsX = CLIPPING_OVERFLOW.has(s.overflowX);
    const clipsY = CLIPPING_OVERFLOW.has(s.overflowY);
    if (!clipsX && !clipsY) {
        return false;
    }
    const box = el.getBoundingClientRect();
    return (clipsY && (rect.bottom < box.top || rect.top > box.bottom)) ||
        (clipsX && (rect.right < box.left || rect.left > box.right));
}
// By shape, so a shadow root from another realm counts too.
function isShadowRoot(node) {
    return node.nodeType === 11 && 'host' in node;
}
// The parent in the flat tree, the tree CSS lays out: the slot the element is
// assigned to, else its parent element, else the host of its shadow root. A
// slot inside a closed shadow root is not exposed, so a light-DOM child of
// that host falls back to its light-DOM parent.
function flatTreeParent(el) {
    if (el.assignedSlot !== null) {
        return el.assignedSlot;
    }
    if (el.parentElement !== null) {
        return el.parentElement;
    }
    const parent = el.parentNode;
    return parent !== null && isShadowRoot(parent) ? parent.host : null;
}
// Walks up the anchor's containing-block chain in the flat tree: an
// ancestor's overflow clips only the descendants whose containing block lies
// inside it (CSS 2.1 "overflow").
function isClippedByAncestor(anchor, anchorRect) {
    const doc = anchor.ownerDocument;
    let scheme = containingBlockScheme(window.getComputedStyle(anchor).position);
    for (let el = flatTreeParent(anchor); el !== null; el = flatTreeParent(el)) {
        // The root's overflow clips the viewport, which the caller tests, and
        // never the root's own box.
        if (el === doc.documentElement) {
            return false;
        }
        const s = window.getComputedStyle(el);
        // No box: it neither clips nor holds a containing block.
        if (s.display === 'contents') {
            continue;
        }
        const holdsContainingBlock = scheme === 'flow' || createsContainingBlock(s, () => probeFilterHoldsFixed(anchor)) ||
            (scheme === 'absolute' && orDefault(s.position, 'static') !== 'static');
        if (holdsContainingBlock) {
            const overflowGoesToViewport = el === doc.body && isBodyOverflowPropagated(doc, s);
            if (!overflowGoesToViewport && clipsRect(el, s, anchorRect)) {
                return true;
            }
            scheme = containingBlockScheme(s.position);
        }
        if (isInTopLayer(el)) {
            return false;
        }
    }
    return false;
}
// The shadow roots that the anchor's flat-tree path passes through. The set is
// read once per open cycle; a slot assignment that changes while the popup is
// open is not followed.
function shadowRootsOnPath(anchor) {
    const roots = [];
    for (let el = anchor; el !== null; el = flatTreeParent(el)) {
        const root = el.getRootNode();
        if (isShadowRoot(root) && !roots.includes(root)) {
            roots.push(root);
        }
    }
    return roots;
}
// The size of the layout viewport: the client box of the element that CSSOM
// View makes report it, `<html>`, or `<body>` in quirks mode. A pinch zoom
// leaves it alone, while WebKit shrinks innerWidth/Height to the visual
// viewport (HIGH-943). An element without layout, as in jsdom, reports 0, so
// the window's inner size stands in.
function getLayoutViewportSize() {
    const el = document.compatMode === 'BackCompat' && document.body !== null ? document.body : document.documentElement;
    return { width: el.clientWidth || window.innerWidth, height: el.clientHeight || window.innerHeight };
}
// Anchor fully outside the LAYOUT viewport (not the visual viewport - see
// reposition) or clipped away by an ancestor. `origin` is the layout
// viewport's corner in client coordinates, from getLayoutViewportClientOrigin;
// the ancestors' clips compare client rects.
// Strict comparisons so an unsized anchor at (0,0,0,0) - common in jsdom or
// before first layout - reads as "in viewport, no rect yet", not "off-screen".
function isAnchorHiddenForRect(anchor, rect, origin) {
    const layout = getLayoutViewportSize();
    const outOfViewport = rect.bottom - origin.y < 0 ||
        rect.top - origin.y > layout.height ||
        rect.right - origin.x < 0 ||
        rect.left - origin.x > layout.width;
    return outOfViewport || isClippedByAncestor(anchor, rect);
}
/**
 * Whether `anchor` is currently hidden: fully outside the layout viewport, or
 * fully outside an ancestor's overflow clip that applies to it (DESIGN.md
 * "Hidden-trigger check").
 * - Exposed so a caller can refuse to open a popup against an off-screen
 *   trigger BEFORE building a positioner, rather than opening and then
 *   hiding re-entrantly.
 * - The layout viewport here is the client box of `<html>`, or of `<body>`
 *   in quirks mode, which leaves out the scrollbars.
 */
function isAnchorHidden(anchor) {
    return isAnchorHiddenForRect(anchor, anchor.getBoundingClientRect(), getLayoutViewportClientOrigin());
}
/**
 * Measure the floating element's max-content (natural) width by briefly
 * setting `width: max-content`, then restore the prior inline width. Used only
 * in `'fit-content'` mode.
 * - Reads the computed `width`: the fractional border-box width (the popup is
 *   forced to `box-sizing: border-box` at construction), unaffected by
 *   transforms, rounded up so the box is never short of its content.
 * - The guard against `offsetWidth` catches an engine that reports the
 *   content box, a non-numeric value, or a pixel-snap mismatch: each falls
 *   back to the integer plus one, never short either. Not caught: an engine
 *   that reports an integer computed width, or the content box under less
 *   than half a pixel of border and padding (no shipped theme). `offsetWidth`
 *   alone rounds to the nearest pixel (`docs/llm/popup-width-committee.md`).
 */
function measureNaturalWidth(el) {
    const prev = el.style.width;
    el.style.width = 'max-content';
    const used = parseFloat(window.getComputedStyle(el).width);
    const offset = el.offsetWidth;
    const w = Number.isFinite(used) && Math.round(used) === offset ? Math.ceil(used) : offset + 1;
    el.style.width = prev;
    return w;
}
/**
 * Return the origin and the size of the currently visible viewport.
 * - The layout viewport is often larger than the visible area while a URL
 *   bar or the on-screen keyboard takes part of the screen, or while the
 *   page is pinch-zoomed.
 * - `visualViewport`, when present, gives the visible area, so the popup's
 *   `maxHeight` clamps to what the user can actually see.
 */
function getVisibleViewport() {
    const vv = window.visualViewport;
    // The offsets matter whenever the visual viewport pans inside the layout
    // viewport, under pinch zoom or while the on-screen keyboard shrinks it.
    // The result is in layout-viewport coordinates, those of `position: fixed`;
    // reposition brings the anchor rect into them. Both offsets are 0 otherwise.
    if (vv) {
        return { left: vv.offsetLeft, top: vv.offsetTop, width: vv.width, height: vv.height };
    }
    return { left: 0, top: 0, width: window.innerWidth, height: window.innerHeight };
}
/**
 * Return where the layout viewport's top-left corner sits in client
 * coordinates, the coordinates that `getBoundingClientRect` reports.
 * - `position: fixed` places an element against the layout viewport, so the
 *   positioner subtracts this point from the anchor rect before it places
 *   the popup.
 * - In Chromium and Firefox, client coordinates start at the layout viewport,
 *   so the point is (0, 0).
 * - In WebKit, client coordinates start at the visual viewport, the area the
 *   user sees. While the page is pinch-zoomed, the point is then
 *   (-visualViewport.offsetLeft, -visualViewport.offsetTop) (HIGH-942).
 * - The point is measured, not picked by engine.
 * - The layout viewport's corner in document coordinates is
 *   `pageLeft - offsetLeft` and `pageTop - offsetTop`.
 * - The client origin in document coordinates is `window.scrollX` and
 *   `scrollY`: each engine reports its scroll position from the corner that
 *   its client rects start at (MEDIUM-955).
 * - No element takes part, so a margin, a position or a transform on
 *   `<html>` changes nothing.
 * - WebKit returns `scrollX` and `scrollY` as whole numbers, so the point
 *   can be off by less than one pixel there.
 * - One known exception: WebKit's site-specific quirk
 *   `ShouldUseLayoutViewportForClientRectsQuirk` starts client rects at the
 *   layout viewport, while `scrollX` stays at the visual viewport
 *   (MEDIUM-959).
 * - That quirk exists on the iOS family only.
 * - It applies to `*.chatgpt.com` and `*.discord.com`.
 * - There, the point comes out wrong.
 */
function getLayoutViewportClientOrigin() {
    const vv = window.visualViewport;
    // Without an offset, both viewports share their corner in every engine.
    if (!vv || (!vv.offsetLeft && !vv.offsetTop)) {
        return { x: 0, y: 0 };
    }
    return {
        x: vv.pageLeft - vv.offsetLeft - window.scrollX,
        y: vv.pageTop - vv.offsetTop - window.scrollY,
    };
}
/**
 * Attach a positioner that keeps `floating` placed relative to `anchor`.
 *
 * - Sets `floating` to `position: fixed`.
 * - Listens for `scroll` in the capture phase, on `window` and on every
 *   shadow root of the anchor's flat-tree path. The shadow roots are read
 *   once, at attach.
 * - Listens for `resize` on `window` and on `visualViewport`, for `scroll`
 *   on `visualViewport`, and watches both elements with a `ResizeObserver`.
 * - Ignores a scroll inside `floating`, which cannot move the anchor.
 * - At the first placement and after every `scroll` event outside
 *   `floating` that the capture listeners see, checks whether the anchor is
 *   hidden (`isAnchorHidden`). If it is and `onHide` is provided, calls
 *   `onHide` and skips the style updates.
 * - The first placement runs before any listener or observer is registered.
 *   If `onHide` throws there, the positioner leaves nothing behind.
 * - Otherwise, and on every resize and every pan of the visual viewport,
 *   applies the coordinates from {@link computePosition} and sets
 *   `data-placement` on `floating` for CSS hooks.
 * - A pan of the visual viewport never runs the hidden check.
 *
 * Caller is responsible for calling `detach()` when the floating element is
 * dismissed; otherwise listeners leak.
 */
function createPositioner(anchor, floating, options) {
    let attached = true;
    const widthPolicy = options?.widthPolicy ?? 'fit-content';
    const distanceFromAnchor = options?.distanceFromAnchor ?? DEFAULT_DISTANCE_FROM_ANCHOR;
    const distanceFromViewportEdge = options?.distanceFromViewportEdge ?? DEFAULT_DISTANCE_FROM_VIEWPORT_EDGE;
    // Snapshot at attach (= once per open cycle): direction changes are rare
    // and the next open re-reads it. Only fit-content consults it.
    const direction = window.getComputedStyle(anchor).direction === 'rtl' ? 'rtl' : 'ltr';
    // Placement chosen by the previous reposition, fed back for stickiness.
    // Positioner lifetime = one open cycle, so the next open picks fresh.
    let lastPlacement;
    // `allowHide`: whether this reposition may invoke `onHide` (auto-close).
    // Only repositions driven by a document or element scroll (and the initial
    // placement) close the popup when the anchor leaves view; those driven by a
    // resize or a pan of the visual viewport never do - see onResize.
    function reposition(allowHide) {
        if (!attached) {
            return;
        }
        const clientRect = anchor.getBoundingClientRect();
        // The anchor rect in layout-viewport coordinates, those of `position: fixed`.
        const origin = getLayoutViewportClientOrigin();
        const rect = {
            top: clientRect.top - origin.y,
            left: clientRect.left - origin.x,
            right: clientRect.right - origin.x,
            bottom: clientRect.bottom - origin.y,
            width: clientRect.width,
            height: clientRect.height,
        };
        const { left: viewportLeft, top: viewportTop, width: viewportWidth, height: viewportHeight } = getVisibleViewport();
        // Visibility test uses the LAYOUT viewport (see getLayoutViewportSize), NOT
        // the visual viewport. A virtual keyboard / URL bar shrinks the visual
        // viewport from the bottom without scrolling the anchor away - comparing
        // the anchor with the visual viewport would treat a lower-screen anchor as
        // "scrolled out" and close the popup the instant the keyboard opens. The
        // visual viewport still drives computePosition below (maxHeight clamps to
        // the actually-visible area).
        if (allowHide && isAnchorHiddenForRect(anchor, clientRect, origin) && options?.onHide) {
            options.onHide();
            return;
        }
        const floatingNaturalWidth = widthPolicy === 'fit-content'
            ? measureNaturalWidth(floating)
            : 0;
        // Natural (unclamped) height, measured by reads only. offsetHeight under
        // an active maxHeight clamp feeds the clamp back into the fits test -
        // after a flip to the smaller side the popup could then never measure
        // taller than that side and stayed stuck there even when the list grew
        // back (regrown filter results kept a bottom-flipped popup squeezed at
        // the viewport edge). The clamp swallows exactly the inner scroller's
        // overflow, so adding it back reconstructs the natural height; see
        // `PositionerOptions.innerScrollEl` for why the clamp must not be lifted
        // to re-measure instead.
        const inner = options?.innerScrollEl;
        const clampedOverflow = inner ? Math.max(0, inner.scrollHeight - inner.clientHeight) : 0;
        const floatingHeight = floating.offsetHeight + clampedOverflow;
        const result = computePosition({
            anchorRect: rect,
            viewportWidth,
            viewportHeight,
            viewportLeft,
            viewportTop,
            floatingHeight,
            widthPolicy,
            floatingNaturalWidth,
            direction,
            currentPlacement: lastPlacement,
            distanceFromAnchor,
            distanceFromViewportEdge,
        });
        lastPlacement = result.placement;
        floating.style.position = 'fixed';
        floating.style.top = `${result.top}px`;
        floating.style.left = `${result.left}px`;
        floating.style.width = `${result.width}px`;
        floating.style.maxHeight = `${result.maxHeight}px`;
        floating.setAttribute('data-placement', result.placement);
    }
    // A scroll outside the floating element may move the anchor, so it honors
    // onHide: a popup whose trigger scrolled away is dismissed. A scroll inside
    // the floating element (its list, a scroller in a slot) cannot move the
    // anchor, so it needs neither a reposition nor the hidden check.
    const onScroll = (ev) => {
        if (ev.target instanceof Node && floating.contains(ev.target)) {
            return;
        }
        reposition(true);
    };
    // A resize of the window, of the visual viewport or of an element, and a pan
    // of the visual viewport, re-place the popup without the hidden check: none
    // of them means that the user scrolled the trigger away. Closing here would
    // dismiss the popup the instant the on-screen keyboard opens.
    const onResize = () => reposition(false);
    // The first placement comes before every registration below. It can run
    // app code, through `onHide` and the close notifications, and if that code
    // throws, the caller never gets the handle: nothing may be registered yet
    // that only `detach()` could remove.
    reposition(true);
    // Capture phase catches scrolls inside any ancestor scrollable container. A
    // scroll event never leaves its shadow root, so every shadow root on the
    // anchor's flat-tree path listens too.
    const scrollTargets = [window, ...shadowRootsOnPath(anchor)];
    for (const target of scrollTargets) {
        target.addEventListener('scroll', onScroll, { passive: true, capture: true });
    }
    window.addEventListener('resize', onResize);
    // Mobile: the URL bar and the on-screen keyboard resize the visual viewport
    // without a window resize, and a swipe can then pan the visual viewport
    // without a document scroll. Both move the visible edges that clamp
    // maxHeight and pick the side, so both re-place the popup, never closing it.
    // Skipping the pan left the clamp stale while the keyboard was up
    // (MEDIUM-902); listening to it was once seen to bounce the popup during the
    // URL-bar animation on Firefox Android, which the device pass rechecks.
    const vv = window.visualViewport;
    vv?.addEventListener('resize', onResize);
    vv?.addEventListener('scroll', onResize);
    let ro;
    if (typeof ResizeObserver !== 'undefined') {
        ro = new ResizeObserver(() => reposition(false));
        ro.observe(anchor);
        ro.observe(floating);
    }
    return {
        // Public re-place: never auto-closes. Called after list re-renders (incl.
        // every filter keystroke), where dismissing would be wrong - especially on
        // mobile with the keyboard open. Only the first placement and document
        // and element scrolls may dismiss.
        reposition: () => reposition(false),
        detach() {
            attached = false;
            for (const target of scrollTargets) {
                target.removeEventListener('scroll', onScroll, true);
            }
            window.removeEventListener('resize', onResize);
            vv?.removeEventListener('resize', onResize);
            vv?.removeEventListener('scroll', onResize);
            ro?.disconnect();
            floating.style.position = '';
            floating.style.top = '';
            floating.style.left = '';
            floating.style.width = '';
            floating.style.maxHeight = '';
            floating.removeAttribute('data-placement');
        },
    };
}

// Pure grouping helper, used by LLSelectBase (the `gatherGroups` setting) and
// exported for callers who pre-gather their own data.
/**
 * Stable-bucket `items` so that every group is contiguous, without touching
 * the caller's array.
 *
 * - Groups appear in order of each key's FIRST appearance.
 * - Within a group, items keep their relative order.
 * - Items whose key is `null` (ungrouped) form their own single-item segment
 *   at their walk position; they never merge.
 * - Already-contiguous input is detected in one scan and returned AS-IS (the
 *   input array itself, no copy); otherwise a new array is returned.
 *
 * This is exactly what `LLSelectBase` runs internally while the
 * `gatherGroups` setting is on (the default). Exported for callers who switch
 * `gatherGroups` off and gather once themselves (e.g. ahead of many
 * `setItems` calls on the same data).
 *
 * @param items - the item list to gather
 * @param itemToGroupKeyFn - item to group key; `null` = the item is in no group
 * @param groupKeyCompareFn - key equality; `null` / omitted = identity (`===`,
 *   plus `NaN` equals `NaN` - the rule the internal `Map` uses; same contract
 *   as the `groupKeyCompareFn` setting)
 * @group Grouping
 */
function gatherItemsByGroupKey(items, itemToGroupKeyFn, groupKeyCompareFn) {
    const eq = groupKeyCompareFn ?? null;
    // Seen-key lookup: Map for the default identity (O(1) per item), linear
    // scan over first-seen keys for a custom predicate (a Map cannot key by
    // predicate).
    const seenMap = eq === null ? new Map() : null;
    const seenList = [];
    const hasSeen = (k) => (seenMap !== null ? seenMap.has(k) : seenList.some(s => eq(s, k)));
    const keyEquals = (a, b) => (eq !== null ? eq(a, b) : a === b || (a !== a && b !== b));
    // Pass 1, detect only (no per-item allocation): contiguous means every
    // non-null key either equals the previous item's key or was never seen.
    let contiguous = true;
    let prevKey = null;
    for (const item of items) {
        const key = itemToGroupKeyFn(item);
        if (key === null) {
            prevKey = null;
            continue;
        }
        if (prevKey !== null && keyEquals(prevKey, key)) {
            continue;
        }
        if (hasSeen(key)) {
            contiguous = false;
            break;
        }
        if (seenMap !== null) {
            seenMap.set(key, true);
        }
        else {
            seenList.push(key);
        }
        prevKey = key;
    }
    if (contiguous) {
        return items;
    }
    // Pass 2, rebuild: one bucket per key in first-appearance order; null-key
    // items are their own single-item segment.
    const segments = [];
    const bucketMap = eq === null ? new Map() : null;
    const keyedBuckets = [];
    for (const item of items) {
        const key = itemToGroupKeyFn(item);
        if (key === null) {
            segments.push([item]);
            continue;
        }
        let bucket = bucketMap !== null ? bucketMap.get(key) : keyedBuckets.find(b => eq(b.key, key))?.bucket;
        if (bucket === undefined) {
            bucket = [];
            segments.push(bucket);
            if (bucketMap !== null) {
                bucketMap.set(key, bucket);
            }
            else {
                keyedBuckets.push({ key, bucket });
            }
        }
        bucket.push(item);
    }
    const out = [];
    for (const bucket of segments) {
        out.push(...bucket);
    }
    return out;
}

// KeyboardEvent -> action mapping for the trigger element.
// Pure logic so it can be tested without a DOM.
/**
 * Logical actions a keyboard interaction can map to. Numeric values are
 * implementation detail; never serialise them.
 */
var LLSelectKeyboardAction;
(function (LLSelectKeyboardAction) {
    /** Open the popup (no item activation). */
    LLSelectKeyboardAction[LLSelectKeyboardAction["Open"] = 0] = "Open";
    /** Close the popup (no item activation). */
    LLSelectKeyboardAction[LLSelectKeyboardAction["Close"] = 1] = "Close";
    /** Activate the currently focused option (select + maybe close). */
    LLSelectKeyboardAction[LLSelectKeyboardAction["Select"] = 2] = "Select";
    /** Move focus to the next option (clamps at last). */
    LLSelectKeyboardAction[LLSelectKeyboardAction["Next"] = 3] = "Next";
    /** Move focus to the previous option (clamps at first). */
    LLSelectKeyboardAction[LLSelectKeyboardAction["Previous"] = 4] = "Previous";
    /** Move focus to the first option. */
    LLSelectKeyboardAction[LLSelectKeyboardAction["GotoFirst"] = 5] = "GotoFirst";
    /** Move focus to the last option. */
    LLSelectKeyboardAction[LLSelectKeyboardAction["GotoLast"] = 6] = "GotoLast";
    /** Jump focus down by a fixed page size. */
    LLSelectKeyboardAction[LLSelectKeyboardAction["PageDown"] = 7] = "PageDown";
    /** Jump focus up by a fixed page size. */
    LLSelectKeyboardAction[LLSelectKeyboardAction["PageUp"] = 8] = "PageUp";
})(LLSelectKeyboardAction || (LLSelectKeyboardAction = {}));
const PAGE_SIZE = 10;
/**
 * Whether a keydown belongs to an IME composition, so the library leaves it
 * to the IME.
 * - `isComposing` covers the keys typed while a composition is open.
 * - `keyCode` 229 covers the key that ends a composition when Safari sends it
 *   after `compositionend`, with `isComposing` already false.
 * - That key is typically the Enter that confirms a candidate.
 * - `keyCode` is deprecated, but nothing else marks that key.
 * - Sources: MDN "keydown events with IME", WebKit bug 165004.
 */
function isImeKeydown(ev) {
    return ev.isComposing || ev.keyCode === 229;
}
/**
 * Map a keydown event to a logical {@link LLSelectKeyboardAction}, given whether the
 * popup is currently open.
 * - Returns `undefined` if the key should be left alone (no preventDefault,
 *   no library reaction).
 * - Maps the action keys of the ARIA APG combobox pattern.
 * - The pattern's printable-character typeahead is not mapped here - it needs
 *   the character, which an action enum cannot carry. The keydown handler
 *   runs {@link findTypeaheadIndex} before this mapping.
 *
 * @param inTextInput - true when focus is in the editable filter input. There,
 *   Space must type a space and Home/End must move the text caret, so those
 *   keys are NOT mapped to selection / first-last navigation. Selection is
 *   Enter only; option navigation is the arrow / page keys.
 */
function getActionFromKey(ev, isOpened, inTextInput = false) {
    const { key, altKey } = ev;
    if (!isOpened) {
        if (key === 'ArrowDown' || key === 'ArrowUp' || key === 'Enter' || key === ' ') {
            return LLSelectKeyboardAction.Open;
        }
        return undefined;
    }
    if (key === 'Escape') {
        return LLSelectKeyboardAction.Close;
    }
    if (key === 'ArrowUp' && altKey) {
        return LLSelectKeyboardAction.Close;
    }
    if (key === 'Enter') {
        return LLSelectKeyboardAction.Select;
    }
    if (key === ' ' && !inTextInput) {
        return LLSelectKeyboardAction.Select;
    }
    if (key === 'ArrowDown') {
        return LLSelectKeyboardAction.Next;
    }
    if (key === 'ArrowUp') {
        return LLSelectKeyboardAction.Previous;
    }
    if (key === 'Home' && !inTextInput) {
        return LLSelectKeyboardAction.GotoFirst;
    }
    if (key === 'End' && !inTextInput) {
        return LLSelectKeyboardAction.GotoLast;
    }
    if (key === 'PageDown') {
        return LLSelectKeyboardAction.PageDown;
    }
    if (key === 'PageUp') {
        return LLSelectKeyboardAction.PageUp;
    }
    return undefined;
}
/**
 * Compute a new focused-option index after applying a navigation action.
 * Clamps to `[0, maxIndex]` (no wrap-around). Returns `-1` if there are no
 * options (`maxIndex < 0`). The page size for PageUp/PageDown is a fixed
 * constant.
 *
 * @param currentIndex - current focused index (`-1` for "none")
 * @param maxIndex - largest valid index (`options.length - 1`)
 */
function getUpdatedIndex(currentIndex, maxIndex, action) {
    if (maxIndex < 0) {
        return -1;
    }
    switch (action) {
        case LLSelectKeyboardAction.GotoFirst: return 0;
        case LLSelectKeyboardAction.GotoLast: return maxIndex;
        case LLSelectKeyboardAction.Next: return Math.min(currentIndex + 1, maxIndex);
        case LLSelectKeyboardAction.Previous: return Math.max(currentIndex - 1, 0);
        case LLSelectKeyboardAction.PageDown: return Math.min(currentIndex + PAGE_SIZE, maxIndex);
        case LLSelectKeyboardAction.PageUp: return Math.max(currentIndex - PAGE_SIZE, 0);
        default: return currentIndex;
    }
}
/**
 * Pause (in ms) after which the next typed character starts a new typeahead
 * buffer instead of extending the old one. Native `<select>` implementations
 * use 1 s (Blink / WebKit).
 */
const TYPEAHEAD_TIMEOUT_MS = 1000;
/**
 * Compute the typeahead buffer after a newly typed character.
 * - If `elapsedMs` since the previous character exceeds
 *   {@link TYPEAHEAD_TIMEOUT_MS}, the character starts a fresh buffer.
 */
function getUpdatedTypeaheadBuffer(buffer, char, elapsedMs) {
    return elapsedMs > TYPEAHEAD_TIMEOUT_MS ? char : buffer + char;
}
/**
 * Resolve where prefix typeahead moves the active option; `-1` = no match.
 * Mirrors native `<select>` typeahead:
 * - An option matches when its text starts with `buffer`, case-insensitive.
 * - A one-character buffer searches from the option AFTER `currentIndex`, so
 *   repeated presses of one initial cycle through the options sharing it.
 * - A buffer of one repeated character (e.g. `"aa"`) behaves exactly like its
 *   single character - it keeps cycling. It is never matched literally (the
 *   W3C APG example tries the literal `"aa"` prefix first; native does not,
 *   and a text really starting `"aa"` is still reached by the cycle).
 * - Any other longer buffer searches from `currentIndex` itself, so extending
 *   the buffer stays on the current option while it still matches.
 * - The search wraps around the whole list - deliberately, unlike the clamped
 *   arrow navigation (see `docs/llm/A11Y.md`): a search means "anywhere", and
 *   cycling needs the wrap.
 * - Indexes where `textAt` returns `undefined` (disabled options) never match.
 * - `currentIndex` `-1` means no option is active; the search starts at 0.
 *
 * The repeated-character test compares CODE POINTS, each lower-cased on its
 * own: a key whose lower-case form expands to two code units (the Turkish
 * dotted capital I) still counts, astral-plane characters compare whole, and
 * a mid-repeat Shift ("aA") still cycles.
 *
 * @param textAt - match text of the option at an index, or `undefined` when
 *   that option must never match.
 */
function findTypeaheadIndex(buffer, count, currentIndex, textAt) {
    if (count <= 0 || buffer === '') {
        return -1;
    }
    // Both operands fold through foldForTypeahead. Its final-sigma map is what
    // makes the two sides agree: whole-string `toLowerCase` applies the Greek
    // Final_Sigma rule, folding a trailing sigma in the buffer differently from
    // the same sigma mid-word in the option text. The per-code-point split is
    // the backstop, in case another context-sensitive mapping ever lands.
    const chars = [...buffer].map(foldForTypeahead);
    const sameChar = chars.every((c) => c === chars[0]);
    const needle = sameChar ? chars[0] : chars.join('');
    const start = sameChar ? currentIndex + 1 : Math.max(currentIndex, 0);
    const from = ((start % count) + count) % count;
    for (let i = 0; i < count; i++) {
        const idx = (from + i) % count;
        const text = textAt(idx);
        if (text !== undefined && foldForTypeahead(text).startsWith(needle)) {
            return idx;
        }
    }
    return -1;
}
/**
 * Case-fold text for typeahead comparison, context-free per code point.
 * - Lower-cases each code point on its own (never the whole string - see
 *   `findTypeaheadIndex`).
 * - Maps the Greek final sigma (U+03C2, its own key on Greek keyboards) to
 *   sigma (U+03C3), so a typed final sigma matches upper-case text and a typed
 *   capital sigma matches lower-case text ending in the final form.
 */
function foldForTypeahead(text) {
    return [...text].map((c) => c.toLowerCase()).join('').replace(/\u03c2/g, '\u03c3');
}
/**
 * Scroll `scrollParent` just enough so `child` is fully visible. No-op if
 * `child` is already in view. Adjusts `scrollTop` directly rather than using
 * `scrollIntoView`, so the page (window) does not scroll alongside.
 * - `topInset` / `bottomInset` are the heights of anything stuck to the
 *   scroll container's edges (the pinned row blocks); the child is brought
 *   into the part of the scrollport those do not cover. When the insets leave
 *   no room, they are ignored (best-effort).
 * - Uses viewport-rect deltas, NOT `offsetTop`: `offsetTop` is relative to the
 *   offset parent, which a theme could change by making a group container
 *   `position: relative` (optgroup), silently breaking the math. Rect deltas
 *   are correct regardless of nesting / theme CSS. `clientTop` /
 *   `clientHeight` exclude the parent's border so a bordered list stays
 *   exact. Measured to cost the same as the old `offsetTop` path (see
 *   docs/llm/DESIGN.md "Optgroup").
 */
function ensureVisibleInScroll(child, scrollParent, topInset = 0, bottomInset = 0) {
    const c = child.getBoundingClientRect();
    const p = scrollParent.getBoundingClientRect();
    const edgeTop = p.top + scrollParent.clientTop;
    const edgeBottom = edgeTop + scrollParent.clientHeight;
    let viewTop = edgeTop + topInset;
    let viewBottom = edgeBottom - bottomInset;
    if (viewBottom <= viewTop) {
        // The pinned blocks cover the whole scrollport: best-effort, ignore them.
        viewTop = edgeTop;
        viewBottom = edgeBottom;
    }
    if (c.top < viewTop) {
        scrollParent.scrollTop -= viewTop - c.top;
    }
    else if (c.bottom > viewBottom) {
        scrollParent.scrollTop += c.bottom - viewBottom;
    }
}

/**
 * The built-in English pack - the library default.
 * @group Language packs
 */
const en = {
    triggerPlaceholder: 'Please select',
    filterInputAriaLabel: 'Search',
    filterInputPlaceholder: 'Filter (Esc to clear)',
    popupListNoResults: 'No results found',
    triggerButtonsAriaLabel: 'Selection actions',
    triggerClearButtonAriaLabel: 'Clear selection',
    tagRemoveButtonAriaLabel: (itemText) => `Remove ${itemText}`,
    triggerContentCountText: (chosenCount, totalCount) => chosenCount === totalCount ? `All ${chosenCount} selected` : `${chosenCount} / ${totalCount} selected`,
    triggerScreenReaderCountText: (chosenCount, totalCount) => chosenCount === totalCount ? `All ${chosenCount} selected` : `${chosenCount} of ${totalCount} selected`,
    triggerScreenReaderItemsText: (itemTexts) => itemTexts.join(', '),
    chooseAllRowText: (chosenCount, totalCount) => `Select all (${chosenCount} of ${totalCount})`,
};

/**
 * The mark that `defaultBehaviorOfScrollGesture` carries. The main bundle and
 * the presets bundle each hold a copy of that function, so the library tests
 * for the mark, not for the identity.
 * @internal
 */
const DEFAULT_BEHAVIOR_OF_SCROLL_GESTURE_MARK = Symbol.for('llselect.defaultBehaviorOfScrollGesture');
/**
 * The mark that `defaultBehaviorOfZoomGesture` carries, for the reason of
 * {@link DEFAULT_BEHAVIOR_OF_SCROLL_GESTURE_MARK}.
 * @internal
 */
const DEFAULT_BEHAVIOR_OF_ZOOM_GESTURE_MARK = Symbol.for('llselect.defaultBehaviorOfZoomGesture');
// A touch that moves farther than this from its touch-down, in CSS pixels, is
// taken for a drag that gives no click. Chosen to stay above the browsers' own
// tap limits, which the real-device pass in docs/llm/TODO.md checks.
const TAP_SLOP = 16;
/**
 * A tap's click may land at most this far from its touch-down, in CSS pixels.
 * - `base.ts` binds the click swallow of a blocked outside press with it too.
 * @internal
 */
const TAP_CLICK_RADIUS = 2 * TAP_SLOP;
/**
 * A tap's click may still come this long after the touch lifts, in
 * milliseconds.
 * - Browsers can hold the click back by about 300 ms on a page without a
 *   mobile viewport.
 * - `base.ts` waits as long in the click swallow of a blocked outside press.
 * @internal
 */
const CLICK_WAIT_MS = 1000;
const PASSIVE = { passive: true };
const NON_PASSIVE = { passive: false };
const CAPTURE_PASSIVE = { capture: true, passive: true };
const CAPTURE_NON_PASSIVE = { capture: true, passive: false };
function closes(behavior) {
    return behavior === 'close-popup-and-allow-page-scroll' || behavior === 'close-popup-and-block-page-scroll';
}
function blocks(behavior) {
    return behavior === 'leave-popup-open-and-block-page-scroll' || behavior === 'close-popup-and-block-page-scroll';
}
function zoomCloses(behavior) {
    return behavior === 'close-popup-and-allow-page-zoom' || behavior === 'close-popup-and-block-page-zoom';
}
function zoomBlocks(behavior) {
    return behavior === 'leave-popup-open-and-block-page-zoom' || behavior === 'close-popup-and-block-page-zoom';
}
// The touch target of a hold can be any node, an SVG element included, so its
// listeners take a plain `Event`.
function isTouchEvent(ev) {
    return 'changedTouches' in ev;
}
function findTouch(list, id) {
    for (let i = 0; i < list.length; i++) {
        const t = list.item(i);
        if (t !== null && t.identifier === id) {
            return t;
        }
    }
    return null;
}
// Whether `el` can still scroll by the sign of (dx, dy). `scrollLeft` counts
// from the start edge, negative in a right-to-left box.
function canScroll(el, dx, dy) {
    const style = window.getComputedStyle(el);
    if (dy !== 0 && /auto|scroll|overlay/.test(style.overflowY)) {
        const max = el.scrollHeight - el.clientHeight;
        if (dy > 0 ? el.scrollTop < max - 1 : el.scrollTop > 0) {
            return true;
        }
    }
    if (dx !== 0 && /auto|scroll|overlay/.test(style.overflowX)) {
        const max = el.scrollWidth - el.clientWidth;
        const fromStart = Math.abs(el.scrollLeft);
        const towardEnd = style.direction === 'rtl' ? dx < 0 : dx > 0;
        if (towardEnd ? fromStart < max - 1 : fromStart > 0) {
            return true;
        }
    }
    return false;
}
// Whether an element on the event's composed path, up to `boundary`, can
// still take the scroll. The composed path crosses into open shadow roots.
function canScrollWithin(path, boundary, dx, dy) {
    for (const node of path) {
        if (node instanceof Element && canScroll(node, dx, dy)) {
            return true;
        }
        if (node === boundary) {
            return false;
        }
    }
    return false;
}
/**
 * Holds the rest of a touch whose touch-down closed the popup.
 * - Returns the function that ends the hold early.
 * - The listeners of the touch sit on its own target, which gets every later
 *   event of the touch, even after the close removed that node from the
 *   document.
 * - In a closed shadow root around the select component, the document's
 *   listeners see no deeper than the shadow host:
 *   - A hold that the document's listeners start sits on the shadow host,
 *     not on the touch's own target.
 *   - If the close removed the node that the touch started on, the shadow
 *     host may miss the rest of the touch, as inferred from the code.
 * - Its moves scroll nothing while `block` is set.
 * - When `swallowClick` is set, the hold swallows the touch's click, the first
 *   click that satisfies all of the following:
 *   - it lands near the touch-down;
 *   - it comes within one second of the lift;
 *   - a pointer made it.
 * - The hold ends at the first of these moments:
 *   - the touch is over, and its click came or cannot come;
 *   - a later touch-down;
 *   - a move with two touches;
 *   - the press of a mouse or a pen.
 * - A second finger makes a pinch, which most likely gives no click.
 * - A later touch-down or press is a new press, whose click must not be taken
 *   for the click of the held touch.
 */
function holdRestOfTouch(target, start, options) {
    const { block, swallowClick, mousedown } = options;
    let moved = false;
    let timer;
    let touchDone = false;
    let clickDone = !swallowClick;
    let ended = false;
    const moveOptions = { passive: !block };
    const near = (x, y, limit) => Math.hypot(x - start.clientX, y - start.clientY) <= limit;
    const onMove = (ev) => {
        if (!isTouchEvent(ev)) {
            return;
        }
        // A second finger whose touch-down no listener saw.
        if (ev.touches.length > 1) {
            release();
            return;
        }
        const t = findTouch(ev.changedTouches, start.identifier);
        if (t === null) {
            return;
        }
        if (!near(t.clientX, t.clientY, TAP_SLOP)) {
            moved = true;
        }
        if (block && ev.cancelable) {
            ev.preventDefault();
        }
    };
    const onEnd = (ev) => {
        if (!isTouchEvent(ev) || findTouch(ev.changedTouches, start.identifier) === null) {
            return;
        }
        endTouch();
        if (moved || ev.type === 'touchcancel') {
            endClick();
            return;
        }
        if (!clickDone) {
            timer = setTimeout(endClick, CLICK_WAIT_MS);
        }
    };
    const onNextTouchStart = () => { release(); };
    // The press of a mouse or a pen is a new press too. A later touch ends the
    // hold at its touchstart, so its pointerdown is left alone, wherever a
    // browser sends it.
    const onNextPointerDown = (ev) => {
        if (ev.pointerType === 'touch') {
            return;
        }
        release();
    };
    // A click far from the touch-down came from something else, such as a mouse.
    const isTapClick = (ev) => near(ev.clientX, ev.clientY, TAP_CLICK_RADIUS);
    const onMousedown = (ev) => {
        if (!isTapClick(ev)) {
            return;
        }
        ev.preventDefault();
        if (mousedown === 'swallow') {
            ev.stopPropagation();
        }
    };
    const onClick = (ev) => {
        // A click from the keyboard or from click() has a detail of 0, so it is
        // not the tap's, whatever its place; the wait goes on.
        if (ev.detail === 0 || !isTapClick(ev)) {
            return;
        }
        ev.preventDefault();
        ev.stopPropagation();
        endClick();
    };
    const finish = () => {
        if (!touchDone || !clickDone || ended) {
            return;
        }
        ended = true;
        document.removeEventListener('touchstart', onNextTouchStart, CAPTURE_PASSIVE);
        document.removeEventListener('pointerdown', onNextPointerDown, CAPTURE_PASSIVE);
        options.ended();
    };
    const endTouch = () => {
        if (touchDone) {
            return;
        }
        touchDone = true;
        target.removeEventListener('touchmove', onMove, moveOptions);
        target.removeEventListener('touchend', onEnd, PASSIVE);
        target.removeEventListener('touchcancel', onEnd, PASSIVE);
        finish();
    };
    const endClick = () => {
        if (clickDone) {
            return;
        }
        clickDone = true;
        if (timer !== undefined) {
            clearTimeout(timer);
        }
        document.removeEventListener('mousedown', onMousedown, true);
        document.removeEventListener('click', onClick, true);
        finish();
    };
    const release = () => {
        endTouch();
        endClick();
    };
    target.addEventListener('touchmove', onMove, moveOptions);
    target.addEventListener('touchend', onEnd, PASSIVE);
    target.addEventListener('touchcancel', onEnd, PASSIVE);
    document.addEventListener('touchstart', onNextTouchStart, CAPTURE_PASSIVE);
    document.addEventListener('pointerdown', onNextPointerDown, CAPTURE_PASSIVE);
    if (swallowClick) {
        if (mousedown !== 'leave') {
            document.addEventListener('mousedown', onMousedown, true);
        }
        document.addEventListener('click', onClick, true);
    }
    return release;
}
/**
 * Blocks the rest of a touchscreen zoom whose answer closed the popup and
 * blocks the zoom, until every finger lifts.
 * - Returns the function that ends the hold early.
 * - `initialTargets` are the targets of the fingers that touch when the hold
 *   starts.
 * - A target keeps getting the events of every finger that started on it
 *   after the close, even when the close removed it from the document, as it
 *   removes the rows of the list.
 * - Also listens on the document, for a finger that lands later.
 * - Such a finger's target joins the hold at its touch-down, in the capture
 *   phase, before a later close can remove it.
 * - The document sees the target of a finger inside a shadow root as the
 *   shadow host.
 * - So the original dispatch target, `composedPath()[0]`, joins too.
 * - In an open shadow root, that target is the finger's real one.
 * - Blocks the touch-down of a further finger, and every move with two or
 *   more touches.
 * - A finger left alone after the others lifted pans as usual.
 */
function holdZoomTouch(initialTargets, ended) {
    let done = false;
    const targets = new Set();
    const onMove = (ev) => {
        if (isTouchEvent(ev) && ev.touches.length > 1 && ev.cancelable) {
            ev.preventDefault();
        }
    };
    const onEnd = (ev) => {
        if (isTouchEvent(ev) && ev.touches.length === 0) {
            release();
        }
    };
    const track = (target) => {
        if (targets.has(target)) {
            return;
        }
        targets.add(target);
        target.addEventListener('touchmove', onMove, NON_PASSIVE);
        target.addEventListener('touchend', onEnd, PASSIVE);
        target.addEventListener('touchcancel', onEnd, PASSIVE);
    };
    const onStart = (ev) => {
        if (!isTouchEvent(ev)) {
            return;
        }
        const own = ev.composedPath()[0];
        if (own !== undefined) {
            track(own);
        }
        for (let i = 0; i < ev.changedTouches.length; i++) {
            const t = ev.changedTouches.item(i);
            if (t !== null) {
                track(t.target);
            }
        }
        if (ev.touches.length > 1 && ev.cancelable) {
            ev.preventDefault();
        }
    };
    const release = () => {
        if (done) {
            return;
        }
        done = true;
        for (const target of targets) {
            target.removeEventListener('touchmove', onMove, NON_PASSIVE);
            target.removeEventListener('touchend', onEnd, PASSIVE);
            target.removeEventListener('touchcancel', onEnd, PASSIVE);
        }
        document.removeEventListener('touchstart', onStart, CAPTURE_NON_PASSIVE);
        document.removeEventListener('touchmove', onMove, CAPTURE_NON_PASSIVE);
        document.removeEventListener('touchend', onEnd, CAPTURE_PASSIVE);
        document.removeEventListener('touchcancel', onEnd, CAPTURE_PASSIVE);
        ended();
    };
    for (const target of initialTargets) {
        track(target);
    }
    document.addEventListener('touchstart', onStart, CAPTURE_NON_PASSIVE);
    document.addEventListener('touchmove', onMove, CAPTURE_NON_PASSIVE);
    document.addEventListener('touchend', onEnd, CAPTURE_PASSIVE);
    document.addEventListener('touchcancel', onEnd, CAPTURE_PASSIVE);
    return release;
}
// The parent that the composed path follows: a shadow root leads to its host.
function composedParent(node) {
    if (node.parentNode !== null) {
        return node.parentNode;
    }
    return 'host' in node && node.host instanceof Node ? node.host : null;
}
/**
 * Attaches the scroll-gesture and zoom-gesture listeners for one open cycle;
 * the returned function detaches them.
 * - On the popup: a `wheel` listener and the touch listeners, which see the
 *   zone `'popup'`. Chromium 156 makes a wheel over the top-layer popup
 *   cancelable only for a non-passive listener on the popup itself, not on
 *   an ancestor such as the root element.
 * - On the root element: the same listeners, which see the zone `'trigger'`
 *   and skip the gestures of the popup.
 * - On the document, only while `host.scrollOutside` or `host.zoomOutside`
 *   is set: the same listeners in the capture phase, which see the zone
 *   `'outside'` and pass each group only the gestures it listens for there.
 *   - A non-passive `wheel` or `touchmove` listener there makes every scroll
 *     of the page wait for script, so the default behaviors, which leave the
 *     outside alone, do not attach them.
 *   - The `touchstart` listener there is non-passive only while
 *     `host.zoomOutside` is set, since only a zoom cancels a touch-down.
 * - A wheel or a drag inside the popup that something in the popup can still
 *   scroll is left to the browser and does not reach `behaviorFor`. A
 *   touch-down always reaches it, since it has no direction yet.
 * - A `wheel` with `ctrlKey` reaches `zoomBehaviorFor` instead of
 *   `behaviorFor`, and so does a touch from the moment a second finger lands
 *   until every finger lifts. The touch asks once, and its answer holds for
 *   the rest of it.
 * - A pinch-zoomed page gets the same calls as a page that is not zoomed.
 * - The hold of a zoom that closed the popup and blocks the zoom lasts until
 *   every finger lifts, or until `destroy()`; see `holdZoomTouch`.
 * - In a closed shadow root around the select component, the document sees
 *   no deeper than the shadow host:
 *   - The document's listeners read every gesture there as `'outside'`,
 *     before the listeners inside see it.
 *   - The hold of a one-finger close that the document's listeners start
 *     sits on the shadow host.
 *   - If the close removed the node that the touch started on, the shadow
 *     host may miss the rest of the touch, as inferred from the code.
 *   - The next touch-down still ends that hold.
 * @internal
 */
function attachGestureListeners(host) {
    // The touch that is going on, from its touch-down to its lift.
    let touch = null;
    // True from a second finger's touch-down until every finger lifts.
    let multiTouch = false;
    // The answer to the zoom that the touch became, kept until every finger lifts.
    let zoomAnswer = null;
    // The composed path crosses into open shadow roots, which `contains` does not.
    const zoneOf = (path) => {
        if (path.includes(host.popupEl)) {
            return 'popup';
        }
        if (path.includes(host.rootEl)) {
            return 'trigger';
        }
        return 'outside';
    };
    const zoneOfTarget = (target) => {
        for (let node = target instanceof Node ? target : null; node !== null; node = composedParent(node)) {
            if (node === host.popupEl) {
                return 'popup';
            }
            if (node === host.rootEl) {
                return 'trigger';
            }
        }
        return 'outside';
    };
    // The zone of the first finger of a zoom. A touch keeps its target, so a
    // finger whose touch-down no listener saw, such as one outside while the
    // library does not listen there, still shows where it landed. The state of
    // one open cycle is all there is: a finger that touched down before the
    // popup opened gets the zone where its target sits now, `'outside'` once a
    // close removed it, and among several such fingers the first in `touches`
    // stands in for the first to land (MEDIUM-954).
    const firstFingerZone = (ev) => {
        if (touch !== null) {
            return touch.zone;
        }
        for (let i = 0; i < ev.touches.length; i++) {
            const t = ev.touches.item(i);
            if (t !== null && findTouch(ev.changedTouches, t.identifier) === null) {
                return zoneOfTarget(t.target);
            }
        }
        return zoneOf(ev.composedPath());
    };
    const carryOut = (gesture, ev) => {
        if (gesture.zone === 'outside' && !host.scrollOutside) {
            return;
        }
        const behavior = host.behaviorFor(gesture);
        if (blocks(behavior) && ev.cancelable) {
            ev.preventDefault();
        }
        if (closes(behavior)) {
            host.closeFor(gesture);
        }
    };
    // Asks about one zoom gesture and carries out the answer on `ev`.
    const carryOutZoom = (zone, ev) => {
        if (zone === 'outside' && !host.zoomOutside) {
            return 'leave-popup-open-and-allow-page-zoom';
        }
        const gesture = { zone };
        const behavior = host.zoomBehaviorFor(gesture);
        if (zoomBlocks(behavior) && ev.cancelable) {
            ev.preventDefault();
        }
        if (zoomCloses(behavior)) {
            // The close removes these listeners, so a hold blocks the rest of the touch.
            if (zoomBlocks(behavior) && isTouchEvent(ev)) {
                const targets = new Set();
                const own = ev.composedPath()[0];
                if (own !== undefined) {
                    targets.add(own);
                }
                for (let i = 0; i < ev.touches.length; i++) {
                    const t = ev.touches.item(i);
                    if (t !== null) {
                        targets.add(t.target);
                    }
                }
                const release = holdZoomTouch(targets, () => { host.holdEnded(release); });
                host.holdStarted(release);
            }
            host.closeForZoom(gesture);
        }
        return behavior;
    };
    // A touch becomes a zoom when a second finger lands, seen at its touch-down
    // or, where no listener saw that, at the next move with two touches.
    const onMultiTouch = (ev) => {
        if (multiTouch) {
            if (zoomAnswer !== null && zoomBlocks(zoomAnswer) && ev.cancelable) {
                ev.preventDefault();
            }
            return;
        }
        const zone = firstFingerZone(ev);
        touch = null;
        multiTouch = true;
        zoomAnswer = carryOutZoom(zone, ev);
    };
    const onWheel = (ev) => {
        const path = ev.composedPath();
        const zone = zoneOf(path);
        if (ev.ctrlKey) {
            carryOutZoom(zone, ev);
            return;
        }
        if (zone === 'popup' && canScrollWithin(path, host.popupEl, Math.sign(ev.deltaX), Math.sign(ev.deltaY))) {
            return;
        }
        carryOut({ kind: 'wheel', zone }, ev);
    };
    const onTouchStart = (ev) => {
        if (ev.touches.length > 1) {
            onMultiTouch(ev);
            return;
        }
        multiTouch = false;
        zoomAnswer = null;
        touch = null;
        const t = ev.touches.item(0);
        const path = ev.composedPath();
        const target = path[0];
        if (t === null || target === undefined) {
            return;
        }
        const zone = zoneOf(path);
        // Kept even where no scroll gesture is asked for: a zoom takes its zone.
        touch = { id: t.identifier, x: t.clientX, y: t.clientY, zone, path };
        if (zone === 'outside' && !host.scrollOutside) {
            return;
        }
        const gesture = { kind: 'touch-start', zone };
        const behavior = host.behaviorFor(gesture);
        if (!closes(behavior)) {
            return;
        }
        touch = null;
        // The click of the tap would reopen the popup on the trigger, and reach
        // the page under the closed popup inside it. A button of the trigger
        // buttons strip keeps its click: those buttons toggle nothing.
        const swallowClick = zone === 'popup' || (zone === 'trigger' && host.clickToggles(path)) || (zone === 'outside' && host.swallowsOutsideClick);
        const block = blocks(behavior);
        if (block || swallowClick) {
            const release = holdRestOfTouch(target, t, {
                block,
                swallowClick,
                mousedown: zone === 'trigger' ? 'leave' : zone === 'outside' ? 'prevent-default' : 'swallow',
                ended: () => { host.holdEnded(release); },
            });
            host.holdStarted(release);
        }
        host.closeFor(gesture);
    };
    const onTouchMove = (ev) => {
        if (ev.touches.length > 1) {
            onMultiTouch(ev);
            return;
        }
        if (touch === null || multiTouch) {
            return;
        }
        const t = findTouch(ev.touches, touch.id);
        if (t === null) {
            return;
        }
        // The content scrolls against the finger.
        const dx = touch.x - t.clientX;
        const dy = touch.y - t.clientY;
        touch.x = t.clientX;
        touch.y = t.clientY;
        if (dx === 0 && dy === 0) {
            return;
        }
        if (touch.zone === 'popup' && canScrollWithin(touch.path, host.popupEl, Math.sign(dx), Math.sign(dy))) {
            return;
        }
        carryOut({ kind: 'touch-drag', zone: touch.zone }, ev);
    };
    const onTouchEnd = (ev) => {
        if (ev.touches.length > 0) {
            return;
        }
        touch = null;
        multiTouch = false;
        zoomAnswer = null;
    };
    // Attaches the five listeners to `target`, each passing over the events
    // that `skip` names, and returns the function that removes them. The
    // `touchstart` listener is non-passive when `startBlocks` is set, so that
    // a zoom can cancel the touch-down of a second finger.
    const listen = (target, skip, capture, startBlocks) => {
        const blocking = capture ? CAPTURE_NON_PASSIVE : NON_PASSIVE;
        const passive = capture ? CAPTURE_PASSIVE : PASSIVE;
        const startOptions = startBlocks ? blocking : passive;
        const wheel = (ev) => { if (!skip(ev)) {
            onWheel(ev);
        } };
        const start = (ev) => { if (!skip(ev)) {
            onTouchStart(ev);
        } };
        const move = (ev) => { if (!skip(ev)) {
            onTouchMove(ev);
        } };
        const end = (ev) => { if (!skip(ev)) {
            onTouchEnd(ev);
        } };
        target.addEventListener('wheel', wheel, blocking);
        target.addEventListener('touchstart', start, startOptions);
        target.addEventListener('touchmove', move, blocking);
        target.addEventListener('touchend', end, passive);
        target.addEventListener('touchcancel', end, passive);
        return () => {
            target.removeEventListener('wheel', wheel, blocking);
            target.removeEventListener('touchstart', start, startOptions);
            target.removeEventListener('touchmove', move, blocking);
            target.removeEventListener('touchend', end, passive);
            target.removeEventListener('touchcancel', end, passive);
        };
    };
    const detachers = [
        listen(host.popupEl, () => false, false, true),
        // The popup's own listeners handle its gestures.
        listen(host.rootEl, (ev) => ev.composedPath().includes(host.popupEl), false, true),
    ];
    if (host.scrollOutside || host.zoomOutside) {
        // The document sees an inside gesture first, in the capture phase; the
        // listeners above handle those.
        detachers.push(listen(document, (ev) => ev.composedPath().includes(host.rootEl), true, host.zoomOutside));
    }
    return () => {
        for (const detach of detachers) {
            detach();
        }
    };
}

/**
 * Behavior presets: sets of behavior settings, spread into the settings of a
 * select component, such as
 * `new LLSelectSingle(el, { ...behaviorPresetsOfFirefoxOnWindows })`.
 * - `behaviorPresetsOfOriginalLLSelect` is what a select component does when
 *   no preset is passed.
 * - The other presets follow the native `<select>` of one browser on one
 *   operating system, as recorded by hand tests in
 *   `docs/llm/native-select-scrolling.md`.
 * - The `behaviorOfOutsideClick` of the Chromium and Firefox presets comes from
 *   the source code of those browsers instead, as `docs/llm/DESIGN.md`
 *   records.
 * - The `behaviorOfOutsideClick` of the Safari preset is inferred from the
 *   macOS menu that Safari shows.
 * - No hand test has checked these values yet.
 * - Nothing here detects the browser: the app picks the preset.
 * @module @llselect/core/behavior-presets
 */
/**
 * llselect's own behavior for a scroll gesture while the popup is open: the
 * default of `behaviorOfScrollGestureFn`.
 * - Inside the popup, a wheel or a drag that the popup cannot scroll any
 *   further scrolls nothing, so the page behind stays where it is.
 * - Everywhere else, the page scrolls, and the popup stays open. When the
 *   trigger leaves the view, the popup closes with the close reason
 *   `'hidden'`.
 * - A touch-down changes nothing anywhere.
 * - `@llselect/core` and `@llselect/core/behavior-presets` each export a
 *   copy of this function. Either copy counts as the default, so neither
 *   makes the library listen outside the select component.
 * @group Behaviors
 */
function defaultBehaviorOfScrollGesture(gesture) {
    if (gesture.zone === 'popup' && gesture.kind !== 'touch-start') {
        return 'leave-popup-open-and-block-page-scroll';
    }
    return 'leave-popup-open-and-allow-page-scroll';
}
Object.defineProperty(defaultBehaviorOfScrollGesture, DEFAULT_BEHAVIOR_OF_SCROLL_GESTURE_MARK, { value: true });
/**
 * llselect's own behavior for a zoom gesture while the popup is open: the
 * default of `behaviorOfZoomGestureFn`.
 * - Every zoom zooms the page, inside the popup too, and the popup stays
 *   open.
 * - `@llselect/core` and `@llselect/core/behavior-presets` each export a
 *   copy of this function. Either copy counts as the default, so neither
 *   makes the library listen outside the select component.
 * @group Behaviors
 */
function defaultBehaviorOfZoomGesture(_gesture) {
    return 'leave-popup-open-and-allow-page-zoom';
}
Object.defineProperty(defaultBehaviorOfZoomGesture, DEFAULT_BEHAVIOR_OF_ZOOM_GESTURE_MARK, { value: true });
/**
 * llselect's own behavior, the one a select component has when no preset is
 * passed. See {@link defaultBehaviorOfScrollGesture} and
 * {@link defaultBehaviorOfZoomGesture}.
 * - A click outside the select component while the popup is open closes the
 *   popup and does nothing else: `behaviorOfOutsideClick: 'block'`.
 * @group Behaviors
 */
const behaviorPresetsOfOriginalLLSelect = {
    behaviorOfOutsideClick: 'block',
    behaviorOfScrollGestureFn: defaultBehaviorOfScrollGesture,
    behaviorOfZoomGestureFn: defaultBehaviorOfZoomGesture,
};

// Color scheme (light / dark) resolution for the themes. Contract: DESIGN.md
// "Color scheme (light / dark) in the themes". The themes key their dark values
// on the attribute written here; hosts never write it.
/** The attribute the resolver writes on the root element. The themes key their dark values on it. */
const COLOR_SCHEME_ATTRIBUTE = 'data-llselect-color-scheme';
/** The CSS variable a host page or a built-in mark sets on any ancestor: `light`, `dark` or `auto`. */
const COLOR_SCHEME_VARIABLE = '--llselect-color-scheme';
const DARK_QUERY = '(prefers-color-scheme: dark)';
/**
 * The decision, as a pure function of its inputs (DESIGN.md "How the resolver decides").
 * Order: the forced setting; the variable (`auto` = the OS preference); the
 * declared `color-scheme` combined with the OS preference; otherwise light.
 */
function resolveColorScheme(inputs) {
    if (inputs.setting !== 'auto') {
        return inputs.setting;
    }
    const variable = inputs.variable.trim();
    if (variable === 'light' || variable === 'dark') {
        return variable;
    }
    if (variable === 'auto') {
        return inputs.osPrefersDark ? 'dark' : 'light';
    }
    const keywords = inputs.declared.trim().split(/\s+/);
    if (keywords.includes('dark') && (!keywords.includes('light') || inputs.osPrefersDark)) {
        return 'dark';
    }
    return 'light';
}
function prefersDark(view) {
    return view !== null && typeof view.matchMedia === 'function' && view.matchMedia(DARK_QUERY).matches;
}
/** Reads the inputs for a root element: one getComputedStyle call when the setting is `'auto'`. */
function readColorSchemeInputs(rootEl, setting) {
    if (setting !== 'auto') {
        return { setting, variable: '', declared: '', osPrefersDark: false };
    }
    const view = rootEl.ownerDocument.defaultView;
    if (view === null) {
        return { setting, variable: '', declared: '', osPrefersDark: false };
    }
    const style = view.getComputedStyle(rootEl);
    return {
        setting,
        variable: style.getPropertyValue(COLOR_SCHEME_VARIABLE),
        declared: style.getPropertyValue('color-scheme'),
        osPrefersDark: prefersDark(view),
    };
}
// Shared by the first decision and the page listeners' pass. The roots that
// no other select component contains decide in the two phases. A root inside
// another select component's trigger or popup inherits that select component's
// color-scheme (the themes set it there from the attribute), which those
// writes may just have changed, so it decides after them, one root at a time,
// in document order, after every root around it (the first batch comes in
// construction order, which can put an inner root first). A decision writes,
// and a nested root reads, only while its instance still owns the root: a
// custom element's attribute callback runs inside a write and may destroy or
// replace a select component.
function decideBatch(batch) {
    const outer = [];
    const nested = [];
    for (const entry of batch) {
        if (entry[0].parentElement?.closest(`[${COLOR_SCHEME_ATTRIBUTE}]`)) {
            nested.push(entry);
        }
        else {
            outer.push(entry);
        }
    }
    for (const [, d] of outer) {
        d.read();
    }
    for (const [root, d] of outer) {
        if (subscribersByRoot.get(root) === d) {
            d.apply();
        }
    }
    nested.sort(([a], [b]) => ((a.compareDocumentPosition(b) & Node.DOCUMENT_POSITION_FOLLOWING) !== 0 ? -1 : 1));
    for (const [root, d] of nested) {
        if (subscribersByRoot.get(root) === d) {
            d.read();
            d.apply();
        }
    }
}
// The attribute goes on the root at construction, before the subtree exists,
// with a provisional value: the document's last 'auto' decision on a
// connected root, light until one is made. The themes key rules on the attribute, so a write after the subtree
// was styled restyles the whole subtree; a provisional value the batch then
// confirms costs nothing, a wrong guess costs that select component one
// restyle (OPTIMIZE.md: before this, restyling every subtree cost 38 to 43 ms
// per 1100 select components).
const lastSchemeByDocument = new WeakMap();
/** The value a new `'auto'` select component writes before its first decision: the document's last `'auto'` decision on a connected root, or light. */
function provisionalColorScheme(doc) {
    return lastSchemeByDocument.get(doc) ?? 'light';
}
/** Records an `'auto'` decision made on a connected root as the document's latest, the next select component's provisional value. */
function rememberColorScheme(doc, scheme) {
    lastSchemeByDocument.set(doc, scheme);
}
// Keyed by the root element: a newer instance built on the same element
// replaces an older one's pending decision, so the older one can never write
// the attribute after the newer one did.
const pendingDecisions = new Map();
let flushScheduled = false;
function queueFirstDecision(rootEl, decision) {
    pendingDecisions.set(rootEl, decision);
    if (flushScheduled) {
        return;
    }
    flushScheduled = true;
    void Promise.resolve().then(() => {
        flushScheduled = false;
        const batch = [...pendingDecisions.entries()];
        pendingDecisions.clear();
        decideBatch(batch);
    });
}
/** Drops the pending decision only when it is still this one (a newer instance may own the element now). */
function cancelFirstDecision(rootEl, decision) {
    if (pendingDecisions.get(rootEl) === decision) {
        pendingDecisions.delete(rootEl);
    }
}
/**
 * Called by every constructor: the new instance owns the element from now on.
 * An older instance on the same element loses its pending decision and its
 * subscription, so it can neither overwrite the attribute nor keep deciding.
 */
function claimColorSchemeRoot(rootEl) {
    pendingDecisions.delete(rootEl);
    subscribersByRoot.delete(rootEl);
}
// --- shared page listeners --------------------------------------------------
// One media-query listener and one attribute observer per document re-decide
// every subscribed select component. Subscribers are keyed by their root element in a
// WeakMap, and the listeners find live roots through the document, so nothing
// here retains an instance: a closed instance stays reachable only through its
// own elements (the root, and labelEl when set), as it already does through
// its DOM listeners (the lifecycle promise of destroy() holds).
const subscribersByRoot = new WeakMap();
const wiredDocuments = new WeakSet();
function subscribeColorScheme(rootEl, subscriber) {
    subscribersByRoot.set(rootEl, subscriber);
    wireDocument(rootEl.ownerDocument);
}
function unsubscribeColorScheme(rootEl) {
    subscribersByRoot.delete(rootEl);
}
// The listeners stay for the document's life: a pass is one query of the
// document, holds no instance, and an idle document sees few attribute
// changes on <html> or <body>.
function wireDocument(doc) {
    const view = doc.defaultView;
    if (view === null || wiredDocuments.has(doc)) {
        return;
    }
    wiredDocuments.add(doc);
    let scheduled = false;
    // Batched: one pass per task, however many attributes changed, decided like
    // the first decision (decideBatch). Only roots present in the document are
    // reached (a shadow root's select components re-decide on open() or
    // refreshColorScheme()).
    const refreshAll = () => {
        if (scheduled) {
            return;
        }
        scheduled = true;
        void Promise.resolve().then(() => {
            scheduled = false;
            const batch = [];
            for (const el of doc.querySelectorAll(`[${COLOR_SCHEME_ATTRIBUTE}]`)) {
                const d = subscribersByRoot.get(el);
                if (d !== undefined) {
                    batch.push([el, d]);
                }
            }
            decideBatch(batch);
        });
    };
    if (typeof view.matchMedia === 'function') {
        const query = view.matchMedia(DARK_QUERY);
        if (typeof query.addEventListener === 'function') {
            query.addEventListener('change', refreshAll);
        }
    }
    if (typeof view.MutationObserver === 'function') {
        // A select component mounted on <html> or <body> writes its own attribute on an
        // observed element; those records must not start another pass. The child
        // list of <html> is watched too, so a <body> that appears later (a select component
        // built from a script in <head>) or gets replaced is observed as well.
        // undefined until the first registration (<body> is an element or null)
        let observedBody;
        const observer = new view.MutationObserver((records) => {
            observeBody();
            if (records.every((r) => r.attributeName === COLOR_SCHEME_ATTRIBUTE)) {
                return;
            }
            refreshAll();
        });
        // The only registration path. On a <body> identity change the observer
        // re-registers from scratch, so a removed <body> is neither observed nor
        // referenced any longer.
        const observeBody = () => {
            if (doc.body === observedBody) {
                return;
            }
            observedBody = doc.body;
            observer.disconnect();
            // typed non-null, but null while <html> itself is detached
            const html = doc.documentElement;
            if (html !== null) {
                observer.observe(html, { attributes: true, childList: true });
            }
            if (observedBody !== null) {
                observer.observe(observedBody, { attributes: true });
            }
        };
        observeBody();
    }
}

// LLSelectBase: DOM scaffold, ARIA wiring, open/close state, item storage,
// keyboard navigation, and shared rendering primitives for LLSelectSingle and
// LLSelectMultiple. Subclasses own chosen-state and decide what happens on
// item click.
const DEFAULT_PREFIX = 'llselect';
let instanceCounter = 0;
/**
 * Package-internal (not re-exported): subclasses detect it to pick fast paths.
 * SameValueZero (`===` plus `NaN` equals `NaN`), matching the `Set` those fast
 * paths use - `===` alone let a `NaN` item be chosen twice (QUALITY-92).
 * Second job: the reference-swap check in both `onItemsChanged` ("same value?",
 * a different question from item identity). Keep it SameValueZero for that too.
 */
function defaultCompareFn(a, b) {
    return a === b || (a !== a && b !== b);
}
/**
 * Blank and whitespace-only name settings count as UNSET: the accessible-name
 * computation skips an empty `aria-label` and moves on, so the ladder (and
 * the unnamed warn) must do the same instead of treating `''` as "named".
 */
function blankToNull(value) {
    return value == null || value.trim() === '' ? null : value;
}
/** Once-per-page guard for the unnamed-accessible-name warning. */
let warnedUnnamedName = false;
/** Once-per-page guard for the duplicate-items warning. */
let warnedDuplicateItems = false;
/** Once-per-page guard for the focusable-before-the-filter-input warning. */
let warnedFocusableBeforeFilterInput = false;
/** Once-per-page guard for the warning when `open()` refuses a hidden trigger. */
let warnedHiddenTrigger = false;
/** Elements that are Tab stops without a `tabindex` (`canBeTabStop`). */
const NATIVE_TAB_STOP_SELECTOR = 'a[href], area[href], button, input:not([type="hidden"]), select, textarea, iframe, summary, [contenteditable]:not([contenteditable="false"])';
/** Elements that are, or can become, Tab stops (`canBeTabStop`). */
const TAB_STOP_SELECTOR = `${NATIVE_TAB_STOP_SELECTOR}, [tabindex]`;
/**
 * Whether Tab reaches `el` now, or once it is shown, enabled, made non-inert
 * or rendered.
 * - A control counts while it carries the `hidden` attribute, is disabled,
 *   is inert, or is not rendered by CSS.
 * - `input type="hidden"` never counts, whatever its `tabindex`: it can never
 *   be shown.
 * - Only a negative `tabindex` opts an element out.
 * - A `tabindex` that is no integer counts as absent, as browsers treat it.
 * - The check is structural, so it needs no layout.
 */
function canBeTabStop(el) {
    if (!el.matches(TAB_STOP_SELECTOR) || el.matches('input[type="hidden"]')) {
        return false;
    }
    const tabindex = Number.parseInt(el.getAttribute('tabindex') ?? '', 10);
    return Number.isNaN(tabindex) ? el.matches(NATIVE_TAB_STOP_SELECTOR) : tabindex >= 0;
}
/** The span that `createVisuallyHiddenSpan` clones, built on its first call in a document. */
let visuallyHiddenSpanTemplate;
/**
 * Create the span for the screen-reader text of the trigger.
 * - While the filter is inactive, the trigger is a `combobox`, and WAI-ARIA
 *   1.2 gives a combobox that is not a text field the value of its
 *   descendant content.
 * - `hidden` or `aria-hidden` would drop the span's text from that value, so
 *   the span is hidden from the screen only.
 * - While the filter is active, the trigger is a `button`, whose
 *   `aria-labelledby` chain ends at this span.
 * - The span holds the screen-reader text, which the library writes apart
 *   from the visible content, from `computeTriggerScreenReaderText`.
 * - The common visually-hidden recipe hides the span.
 * - The recipe is written inline, so an unthemed select component hides the
 *   span too.
 * - The first call in a document builds one template span with the recipe.
 * - Every call returns a clone of that template.
 * - A clone costs less than writing the recipe on every span (OPTIMIZE.md
 *   "Mass instantiation slowed between the README's run and the 0.0.15
 *   candidate").
 * - The template takes the recipe through property writes, never through
 *   `setAttribute('style', ...)`.
 * - A Content-Security-Policy such as `style-src 'self'` refuses a style that
 *   `setAttribute` sets, and allows property writes (FIXME MEDIUM-1046).
 */
function createVisuallyHiddenSpan() {
    if (visuallyHiddenSpanTemplate === undefined || visuallyHiddenSpanTemplate.ownerDocument !== document) {
        const template = document.createElement('span');
        const s = template.style;
        s.position = 'absolute';
        s.width = '1px';
        s.height = '1px';
        s.margin = '-1px';
        s.padding = '0';
        s.border = '0';
        s.overflow = 'hidden';
        s.whiteSpace = 'nowrap';
        s.clip = 'rect(0 0 0 0)';
        s.clipPath = 'inset(50%)';
        visuallyHiddenSpanTemplate = template;
    }
    return visuallyHiddenSpanTemplate.cloneNode(false);
}
/** Write an attribute only when its value changes, so an unchanged value queues no mutation record; `null` removes it. */
function setAttributeIfChanged(el, name, value) {
    if (el.getAttribute(name) === value) {
        return;
    }
    if (value === null) {
        el.removeAttribute(name);
    }
    else {
        el.setAttribute(name, value);
    }
}
/** Copy the row position a full list render wrote onto the row that replaces `from` in place. */
function copyRowPosition(from, to) {
    for (const name of ['aria-posinset', 'aria-setsize']) {
        const value = from.getAttribute(name);
        if (value !== null) {
            to.setAttribute(name, value);
        }
    }
}
function createClassIdMap(prefix) {
    const uniq = `${prefix}${++instanceCounter}`;
    return {
        rootClass: `${prefix}-root`,
        triggerWrapperClass: `${prefix}-trigger-wrapper`,
        triggerClass: `${prefix}-trigger`,
        triggerContentClass: `${prefix}-trigger-content`,
        triggerScreenReaderTextClass: `${prefix}-trigger-screen-reader-text`,
        triggerArrowClass: `${prefix}-trigger-arrow`,
        triggerButtonsClass: `${prefix}-trigger-buttons`,
        triggerClearButtonClass: `${prefix}-trigger-clear-button`,
        popupClass: `${prefix}-popup`,
        popupListClass: `${prefix}-popup-list`,
        popupListNoResultsClass: `${prefix}-popup-list-no-results`,
        popupHeaderClass: `${prefix}-popup-header`,
        popupFooterClass: `${prefix}-popup-footer`,
        popupListActionRowClass: `${prefix}-popup-list-action-row`,
        popupListPinnedLeadingRowsClass: `${prefix}-popup-list-pinned-leading-rows`,
        popupListPinnedTrailingRowsClass: `${prefix}-popup-list-pinned-trailing-rows`,
        chooseAllRowClass: `${prefix}-choose-all-row`,
        popupListRowClass: `${prefix}-popup-list-row`,
        popupListRowFocusedClass: `${prefix}-popup-list-row-focused`,
        popupListRowDisabledClass: `${prefix}-popup-list-row-disabled`,
        groupClass: `${prefix}-group`,
        groupLabelClass: `${prefix}-group-label`,
        tagsClass: `${prefix}-tags`,
        tagClass: `${prefix}-tag`,
        tagRemoveButtonClass: `${prefix}-tag-remove-button`,
        tagTextClass: `${prefix}-tag-text`,
        tagDisabledClass: `${prefix}-tag-disabled`,
        openClass: `${prefix}-open`,
        triggerId: `${uniq}-trigger`,
        labelId: `${uniq}-label`,
        triggerContentId: `${uniq}-trigger-content`,
        triggerScreenReaderTextId: `${uniq}-trigger-screen-reader-text`,
        popupId: `${uniq}-popup`,
        popupListId: `${uniq}-popup-list`,
        filterInputClass: `${prefix}-filter-input`,
        filterInputId: `${uniq}-filter-input`,
    };
}
/**
 * Abstract base for all select component variants. Owns DOM scaffolding, ARIA
 * wiring, positioning, keyboard navigation, lazy popup-list rendering, and
 * outside-click handling. Subclasses (`LLSelectSingle`, `LLSelectMultiple`)
 * own chosen-state, decide what happens on item click, and customise the
 * trigger text via `renderTriggerContent`.
 *
 * @typeParam T - item value type. Use `unknown` (default) only when you
 *   intend to narrow inside templates / handlers; usually pass a concrete
 *   type like `string` or your domain object.
 * @typeParam GroupKey - the group key type `itemToGroupKeyFn` returns
 *   (`null` from that fn means "this item is in no group"). Defaults to
 *   `string`. Open it to objects only together with `groupKeyCompareFn`; see
 *   DESIGN.md "Data model".
 * @typeParam S - the resolved settings type, for subclasses that EXTEND the
 *   settings bag. Plain use never passes it. A subclass declares
 *   `extends LLSelectBase<T, GroupKey, MySettings>` and `this.settings` is
 *   typed `MySettings`; the constructor's `subclassSettings` param then only
 *   accepts exactly the extra fields.
 * @group Select component classes
 */
class LLSelectBase {
    /**
     * @param targetEl - mount element. Becomes `rootEl`; its existing children
     *   are wiped and replaced with the trigger + popup structure. Pre-set
     *   classes / id / data-* attributes on this element are preserved.
     * @param settings - optional partial settings. Missing fields use defaults
     *   ({@link LLSelectBaseSettings}).
     * @param subclassSettings - for subclasses that EXTEND the settings bag: their
     *   own fields, already resolved (defaults applied). Typed by the class's
     *   `S` param, so it accepts exactly the extra fields and nothing else.
     *   Merged into `this.settings` right here, so the bag is complete before
     *   any base construction code (e.g. `createFilterInputEl` reading the
     *   pack) can read it.
     * @group Lifecycle
     */
    constructor(targetEl, settings, subclassSettings) {
        /** True when the constructor minted `classIdMap.labelId` onto `labelEl`; `destroy()` then removes it. */
        this.labelElIdMinted = false;
        /** Click handler bound to `labelEl`: focus the trigger, never open (native label parity). */
        this.handleLabelElClick = () => { this.triggerEl.focus(); };
        /**
         * Current item list. Defensive copy of what `setItems` was given.
         * @group State (protected)
         */
        this.items = [];
        /** Whether the popup is currently open; public reader {@link isOpened}. */
        this.opened = false;
        /** True while `close()` returns focus to the trigger, and while `clearOpenState()` runs; `open()` refuses during both. */
        this.closing = false;
        /** True while `open()` runs `showPopover()`, and the undo after a refused show; a nested `open()` of this select component refuses during that time, since Chromium 156, Firefox 153 and WebKit 26.5 throw on a show during another show. */
        this.opening = false;
        /** True while `open()` undoes itself through `close()` after `showPopover()` threw; that `close()` fires no `onClosed` / `onClose`, since the open fired neither of their mirrors. */
        this.undoingOpen = false;
        /**
         * Position in `getVisibleItems()` (the rendered list, not `items`) of the
         * currently keyboard-focused item, or `-1` when no item is focused.
         * - "Focused" here means the active row, the row `aria-activedescendant`
         *   points to, not DOM focus.
         * - While the popup is open, the value is `-1` in two cases:
         *   - no row is active, for example after a filter keystroke that leaves
         *     no enabled visible item, or after an open that finds no enabled
         *     visible item;
         *   - the choose-all row or an action row is the active row.
         * - `close()` sets the value to `-1`.
         * - While the popup is closed, a `setFocusedIndex` call can store another
         *   value.
         * - `open()` sets the value to `-1` again before `focusInitial` places the
         *   initial row.
         * @group State (protected)
         */
        this.focusedIndex = -1;
        /** Control-level disabled state (whole select component); toggled via `setDisabled`. */
        this.disabled = false;
        /**
         * Becomes true in `destroy()` and stays true.
         * - The clear button's and the chip remove button's clicks check it after
         *   their focus step, since an `onFocus` listener may destroy the select component
         *   there.
         * - `open()` checks it, since a listener that `destroy()` runs, such as
         *   `onClose`, may call `open()`.
         * @internal
         */
        this.destroyed = false;
        /** The latest decision, or the provisional value before the first one; see `getColorScheme()`. */
        this.resolvedColorScheme = 'light';
        /** True from construction until the first decision ran (batched into a microtask, see color-scheme.ts). */
        this.colorSchemeDecisionPending = false;
        this.colorSchemeDecision = { read: () => { this.readColorScheme(); }, apply: () => { this.applyColorScheme(); } };
        /**
         * Who the change being applied right now is attributed to; the variants'
         * `onChange` firing reads it. Set to `'user'` by `withUserChangeSource`
         * and consumed (reset to `'api'`) by the first chosen-state change, before
         * `onChosenChanged` runs, so a nested api-driven change inside an
         * `onChange` handler reports `'api'`.
         * @group State (protected)
         */
        this.changeSource = 'api';
        /**
         * Bumped by every chosen-state change and every `setItems`. The
         * before-change gate drops a pending change when it moved during the
         * handlers, so a setter called inside them wins, even one that restores
         * the previous value.
         * @internal
         */
        this.changeRevision = 0;
        /** The clear button once a trigger render has built it (`clearable` only), else `null`; every later trigger render swaps it through `createTriggerClearButtonEl` (or keeps it, if that override returns the same element). */
        this.triggerClearButtonEl = null;
        /** The tag-list container in the trigger buttons strip, or `null` while no chip shows; see `commitTagsElToDom`. */
        this.tagsEl = null;
        /** The strip's last Tab stop, kept while it stays in the strip, so Tab returns to the button that last held focus. */
        this.triggerButtonsTabStopEl = null;
        /** Counts full trigger renders, so `setItems` writes the screen-reader text once even when `onItemsChanged` ran `renderTrigger`. */
        this.triggerRenderCount = 0;
        this.itemEls = [];
        /**
         * The non-item ring entry that holds the active option (the choose-all
         * row today), or `null` when an item does, or nothing does.
         * Mutually exclusive with `focusedIndex >= 0`.
         */
        this.focusedRow = null;
        /** The last item reported to `onActiveItemChange`, or none; see `reportActiveItem`. */
        this.reportedActiveItem = { active: false };
        /** Above zero while `open()` renders and places the initial row; its tail reports once instead. A depth, so a nested open inside a content function cannot end the outer suspension early. */
        this.activeItemReportSuspendDepth = 0;
        /**
         * Bumped by `open`, `close`, `rerender` and `destroy`. With `changeRevision`
         * it forms the stamp a row click takes before its active-row move
         * (`captureStateStamp`); the click activates nothing when a listener moved
         * either counter, since a close, a reopen, a rebuild or a value change
         * under it leaves the row it meant in a popup state that is gone
         * (DESIGN.md "Active item change").
         */
        this.transitionGeneration = 0;
        /**
         * Counts the open cycles: `open()` bumps it when it marks the popup open.
         * - An `open()` call compares it with the value it took, to learn whether
         *   a function it ran closed the select component and opened it again.
         */
        this.openCycle = 0;
        /** The rendered action rows of the current render, in array order; empty while closed. Never part of `itemEls`. */
        this.leadingActionRowEls = [];
        this.trailingActionRowEls = [];
        /**
         * The reason the next `open()` / `close()` reports. An internal path sets
         * it right before the call (`openWithReason` / `closeWithReason`); the
         * method reads and resets it first thing, so a call from outside reports
         * `'api'` and a refused call leaves nothing behind.
         */
        this.pendingOpenReason = 'api';
        this.pendingCloseReason = 'api';
        /** The gesture of a `'scroll-gesture'` close, for `meta.scrollGesture`; see `pendingCloseReason`. */
        this.pendingScrollGesture = undefined;
        /** The gesture of a `'zoom-gesture'` close, for `meta.zoomGesture`; see `pendingCloseReason`. */
        this.pendingZoomGesture = undefined;
        /** Detaches the scroll-gesture and zoom-gesture listeners of the open cycle; set while the popup is open. */
        this.detachGestures = undefined;
        // The functions that end the touch holds still going on: the rest of a touch
        // whose touch-down closed the popup, and the rest of a zoom that closed it
        // and blocks. A touch outlives the close, not the instance, and a popup
        // reopened during a touch can start a second hold.
        this.touchHoldReleases = new Set();
        /** Ends the swallow that an outside press armed under `'block'`; `null` while none is armed. */
        this.disarmOutsidePressClickSwallow = null;
        /** The pointer type of the press whose swallow is armed; `null` while none is armed. */
        this.outsidePressPointerType = null;
        /**
         * Text last written into the no-results region, or `null` while it is hidden.
         * Guards a re-announcement: `role="status"` speaks on every content change, so
         * a keystroke that keeps the list empty must not rewrite identical text (A11Y.md:
         * announced once per appearance). Reset to `null` when the region hides, so the
         * next appearance announces again.
         */
        this.lastNoResultsText = null;
        this.query = '';
        // Prefix-typeahead state. Expiry is a timestamp delta checked on the next
        // character (getUpdatedTypeaheadBuffer) - no timer to clean up. Reset by close()
        // and by any mapped action key.
        this.typeaheadBuffer = '';
        this.typeaheadLastTime = 0;
        this.composing = false;
        // classIdMap first: labelEl id minting below needs labelId.
        this.classIdMap = createClassIdMap(settings?.cssClassPrefix ?? DEFAULT_PREFIX);
        // The pack resolves first: the placeholder's library default is localized
        // chrome (uiTranslationPack.triggerPlaceholder), while an explicit `placeholder` is
        // app copy and wins. The raw input placeholder is kept so
        // setUiTranslationPack can re-run this exact resolution.
        this.explicitPlaceholder = settings?.placeholder ?? null;
        const uiTranslationPack = { ...en, ...settings?.uiTranslationPack };
        // Copied: the settings bag is frozen, and a caller's later array edits must not leak in.
        const leadingActionRows = settings?.popupListLeadingActionRows ? [...settings.popupListLeadingActionRows] : [];
        const trailingActionRows = settings?.popupListTrailingActionRows ? [...settings.popupListTrailingActionRows] : [];
        // labelEl resolves before the name ladder: with neither `ariaLabelledBy`
        // nor `ariaLabel` given, the label's id becomes the resolved
        // `ariaLabelledBy`, and every downstream consumer (trigger chain, filter
        // input, listbox) works unchanged.
        const labelEl = settings?.labelEl ?? null;
        if (labelEl !== null && labelEl.id === '') {
            labelEl.id = this.classIdMap.labelId;
            this.labelElIdMinted = true;
        }
        this.settings = {
            cssClassPrefix: settings?.cssClassPrefix ?? DEFAULT_PREFIX,
            placeholder: this.explicitPlaceholder ?? uiTranslationPack.triggerPlaceholder,
            ariaLabel: blankToNull(settings?.ariaLabel),
            ariaLabelledBy: blankToNull(settings?.ariaLabelledBy) ?? (blankToNull(settings?.ariaLabel) === null && labelEl !== null ? labelEl.id : null),
            labelEl,
            compareFn: settings?.compareFn ?? defaultCompareFn,
            behaviorOfOutsideClick: settings?.behaviorOfOutsideClick ?? behaviorPresetsOfOriginalLLSelect.behaviorOfOutsideClick,
            behaviorOfScrollGestureFn: settings?.behaviorOfScrollGestureFn ?? behaviorPresetsOfOriginalLLSelect.behaviorOfScrollGestureFn,
            behaviorOfZoomGestureFn: settings?.behaviorOfZoomGestureFn ?? behaviorPresetsOfOriginalLLSelect.behaviorOfZoomGestureFn,
            colorScheme: settings?.colorScheme ?? 'auto',
            createTriggerArrowContentElFn: settings?.createTriggerArrowContentElFn ?? null,
            clearable: settings?.clearable ?? false,
            createTriggerClearButtonContentElFn: settings?.createTriggerClearButtonContentElFn ?? null,
            filterable: settings?.filterable ?? false,
            uiTranslationPack,
            filterFn: settings?.filterFn ?? null,
            createPopupListNoResultsContentElFn: settings?.createPopupListNoResultsContentElFn ?? null,
            createPopupHeaderContentElFn: settings?.createPopupHeaderContentElFn ?? null,
            createPopupFooterContentElFn: settings?.createPopupFooterContentElFn ?? null,
            popupListLeadingActionRows: leadingActionRows,
            popupListTrailingActionRows: trailingActionRows,
            popupListLeadingRowsPinned: settings?.popupListLeadingRowsPinned ?? false,
            popupListTrailingRowsPinned: settings?.popupListTrailingRowsPinned ?? false,
            popupWidthPolicy: settings?.popupWidthPolicy ?? 'fit-content',
            popupDistanceFromTriggerWrapper: settings?.popupDistanceFromTriggerWrapper ?? DEFAULT_DISTANCE_FROM_ANCHOR,
            popupDistanceFromViewportEdge: settings?.popupDistanceFromViewportEdge ?? DEFAULT_DISTANCE_FROM_VIEWPORT_EDGE,
            itemDisabledFn: settings?.itemDisabledFn ?? null,
            focusableWhenDisabled: settings?.focusableWhenDisabled ?? false,
            itemToStringFn: settings?.itemToStringFn ?? null,
            itemToLangFn: settings?.itemToLangFn ?? null,
            createPopupListItemContentElFn: settings?.createPopupListItemContentElFn ?? null,
            itemToGroupKeyFn: settings?.itemToGroupKeyFn ?? null,
            gatherGroups: settings?.gatherGroups ?? true,
            groupKeyCompareFn: settings?.groupKeyCompareFn ?? null,
            groupKeyToStringFn: settings?.groupKeyToStringFn ?? null,
            groupKeyToLangFn: settings?.groupKeyToLangFn ?? null,
            groupDisabledFn: settings?.groupDisabledFn ?? null,
            createGroupLabelContentElFn: settings?.createGroupLabelContentElFn ?? null,
            onOpen: settings?.onOpen ?? null,
            onClose: settings?.onClose ?? null,
            onFocus: settings?.onFocus ?? null,
            onBlur: settings?.onBlur ?? null,
            onActiveItemChange: settings?.onActiveItemChange ?? null,
            onFilterQueryChange: settings?.onFilterQueryChange ?? null,
            // Settings cast (one per constructor, see single / multiple): TS
            // cannot prove "base fields + Omit<S, base keys>" reassembles a generic
            // S. The channel itself is typed: the subclassSettings param accepts
            // exactly the extra fields.
            ...subclassSettings,
        };
        // Loud failure over a silent a11y violation, like the group-order warn:
        // an unnamed combobox violates WAI-ARIA 1.2 (A11Y.md, name ladder).
        // Once per page, not per instance - a page full of unnamed select components (a
        // benchmark, a sandbox) must not flood the console nor pay a per-build
        // cost; one nudge carries the rule.
        if (!warnedUnnamedName && this.settings.ariaLabel === null && this.settings.ariaLabelledBy === null) {
            warnedUnnamedName = true;
            // The element rides along so DevTools can jump straight to the first
            // offender instead of leaving the developer to hunt.
            console.warn('llselect: this select component has no accessible name - pass ariaLabelledBy, ariaLabel, or labelEl. An unnamed combobox violates WAI-ARIA 1.2. (warned once per page; first offender:)', targetEl);
        }
        // Label click focuses the trigger (native <select> label behavior: focus
        // only, never open). The one listener destroy() must undo outside the root.
        if (labelEl !== null) {
            labelEl.addEventListener('click', this.handleLabelElClick);
        }
        // Initial evaluation runs against the empty item list (setItems has not
        // happened yet); every open() re-evaluates.
        this.filterActive = this.computeFilterActive();
        // Caller-passed element becomes root (preserves its id / external refs).
        this.rootEl = targetEl;
        this.rootEl.classList.add(this.classIdMap.rootClass);
        // Opt the select component's subtree out of browser scroll-anchoring.
        // Without this, showing/hiding the popup on first open after a page load
        // can trigger a window scroll as the browser tries to keep an anchor
        // element in place. The property excludes this element and all descendants
        // from being eligible anchor nodes.
        this.rootEl.style.overflowAnchor = 'none';
        this.rootEl.replaceChildren();
        // This instance owns the element from now on (an older instance on it
        // loses its pending decision and its subscription). A forced scheme is
        // written now; an 'auto' instance writes a provisional value now, before
        // its subtree exists, decides in a microtask before the first paint
        // (decideBatch: one style flush for the roots outside other
        // select components, a nested root after them) and re-decides on the
        // shared page listeners.
        claimColorSchemeRoot(this.rootEl);
        if (this.settings.colorScheme === 'auto') {
            this.resolvedColorScheme = provisionalColorScheme(this.rootEl.ownerDocument);
            this.rootEl.setAttribute(COLOR_SCHEME_ATTRIBUTE, this.resolvedColorScheme);
            this.colorSchemeDecisionPending = true;
            queueFirstDecision(this.rootEl, this.colorSchemeDecision);
            subscribeColorScheme(this.rootEl, this.colorSchemeDecision);
        }
        else {
            this.syncColorScheme();
        }
        // [wrapper: trigger (screen-reader text, content) | buttons strip | arrow]. The
        // strip sits outside the trigger: inside a combobox a control's name
        // would enter the value (triggerEl TSDoc).
        this.triggerWrapperEl = this.createTriggerWrapperEl();
        const trigger = this.createTriggerEl();
        this.triggerEl = trigger.el;
        this.triggerScreenReaderTextEl = trigger.screenReaderTextEl;
        this.triggerContentEl = trigger.contentEl;
        this.triggerButtonsEl = this.settings.clearable || this.isTriggerDisplayTags() ? this.createTriggerButtonsEl() : null;
        this.triggerArrowEl = document.createElement('span');
        this.triggerArrowEl.className = this.classIdMap.triggerArrowClass;
        this.triggerWrapperEl.append(this.triggerEl);
        if (this.triggerButtonsEl !== null) {
            this.triggerWrapperEl.append(this.triggerButtonsEl);
            this.syncTriggerButtonsNameToDom();
        }
        this.triggerWrapperEl.append(this.triggerArrowEl);
        this.popupEl = this.createPopupEl();
        this.popupListEl = this.createPopupListEl();
        // Pinned blocks: one presentational sticky wrapper per pinned block, built
        // once; commitPopupSegmentsToDom puts it in the listbox only while the
        // block has rows.
        this.popupListPinnedLeadingRowsEl = this.settings.popupListLeadingRowsPinned
            ? this.createPopupListPinnedRowsEl(this.classIdMap.popupListPinnedLeadingRowsClass, 'top')
            : null;
        this.popupListPinnedTrailingRowsEl = this.settings.popupListTrailingRowsPinned
            ? this.createPopupListPinnedRowsEl(this.classIdMap.popupListPinnedTrailingRowsClass, 'bottom')
            : null;
        this.filterInputEl = this.createFilterInputEl();
        // input always built; non-filterable keeps it `hidden`. The filter box must
        // sit above the listbox, outside it: the listbox holds only option rows,
        // group containers and pinned-block wrappers (popupListEl TSDoc).
        this.popupListNoResultsEl = this.createPopupListNoResultsEl();
        this.popupEl.append(this.filterInputEl, this.popupListEl, this.popupListNoResultsEl);
        // Pinned slots: built once, only when their content method returns an
        // element, and never rebuilt (DESIGN.md "Popup header / footer slots").
        // Order: [filter input, header, list, no-results, footer].
        this.popupHeaderEl = this.createPopupHeaderEl();
        if (this.popupHeaderEl !== null) {
            this.popupListEl.before(this.popupHeaderEl);
        }
        this.popupFooterEl = this.createPopupFooterEl();
        if (this.popupFooterEl !== null) {
            this.popupEl.append(this.popupFooterEl);
        }
        // Esc from a focusable control the app placed in a slot closes the popup
        // like Esc on the combobox host. Attached only when a slot exists: without
        // one, nothing inside the popup can hold DOM focus except the filter
        // input, whose own handler already covers Esc (A11Y.md "Focus").
        if (this.popupHeaderEl !== null || this.popupFooterEl !== null) {
            this.popupEl.addEventListener('keydown', (ev) => this.handleSlotKeydown(ev));
        }
        this.popupEl.hidden = true;
        this.syncFilterModeToDom();
        // Force border-box on the popup elements so the positioner's max-height
        // calculation stays correct regardless of the host page's box-sizing
        // setting. Without this, themes with non-zero padding/border on the
        // popup would render past the maxHeight set by the positioner and get
        // clipped by the viewport edge.
        this.popupEl.style.boxSizing = 'border-box';
        this.popupListEl.style.boxSizing = 'border-box';
        // popup-list takes the remaining vertical space inside popup and scrolls
        // when items overflow. `min-height: 0` lets flex actually shrink it.
        // These are safe to set in the constructor because they have no effect
        // while the parent is `display: none`.
        this.popupListEl.style.flex = '1';
        this.popupListEl.style.minHeight = '0';
        this.popupListEl.style.overflowY = 'auto';
        // For a touch scroll that reaches the end of the list: once the list has
        // started to scroll, its `touchmove` can no longer be canceled.
        this.popupListEl.style.overscrollBehavior = 'contain';
        // Top layer via the Popover API where it exists: while open the popup
        // paints above every stacking context and ignores containing-block
        // -creating ancestors (transform / filter / contain), WITHOUT moving in
        // the DOM - so the rootEl.contains checks, inheritance, ARIA wiring and
        // destroy() hold verbatim. 'manual' on purpose: it disables the
        // browser's light dismiss, keeping this library's own outside-click /
        // Esc logic the sole authority. Browsers without the API run the plain
        // position:fixed path unchanged. See DESIGN.md "In-place popup".
        this.popoverSupported = typeof this.popupEl.showPopover === 'function';
        if (this.popoverSupported) {
            this.popupEl.setAttribute('popover', 'manual');
        }
        this.rootEl.append(this.triggerWrapperEl, this.popupEl);
        // A press anywhere in the box toggles the popup; the strip's buttons stop
        // their own clicks.
        this.triggerWrapperEl.addEventListener('click', () => this.toggle());
        this.triggerWrapperEl.addEventListener('mousedown', (ev) => this.handleTriggerWrapperMousedown(ev));
        this.triggerEl.addEventListener('keydown', (ev) => this.handleKeydown(ev));
        this.attachFocusListeners();
        // Hold DOM focus where it is, normally the combobox host: a mousedown anywhere in the popup - an
        // option, the no-results message, a header / footer slot, popup padding, or
        // the list element itself (tabindex="-1", so click-focusable) - would move DOM focus off the
        // focused element and silently kill keyboard input (e.g. multi + filterable: mouse-toggle an
        // item, then typing goes nowhere; or a padding/no-results mousedown blurs the focused element
        // and focusout closes the popup). preventDefault keeps focus put; `click` still fires
        // (it does not depend on the mousedown default), so selection is unaffected. The
        // listener is on popupEl (not popupListEl) so it also covers the no-results
        // element and padding. Exception: the filter input MUST take focus, so its
        // subtree is let through. Native scrollbar dragging on the list is unaffected -
        // a scrollbar mousedown is not a cancelable content event (verified in a real
        // browser; see TODO.md).
        this.popupEl.addEventListener('mousedown', (ev) => {
            const t = this.eventTargetNode(ev);
            if (t instanceof Node && this.filterInputEl.contains(t)) {
                return;
            }
            ev.preventDefault();
        });
        // Always wired, regardless of the current filter mode: a `hidden` input
        // receives no events, and the predicate form of `filterable` can activate
        // the filter on any later open().
        this.filterInputEl.addEventListener('keydown', (ev) => this.handleKeydown(ev));
        this.filterInputEl.addEventListener('input', () => this.handleSearchInputEvent());
        this.filterInputEl.addEventListener('compositionstart', () => { this.composing = true; });
        this.filterInputEl.addEventListener('compositionend', () => { this.composing = false; this.handleSearchInputEvent(); });
    }
    /**
     * Evaluate the `filterable` setting against the current items: booleans
     * pass through, the predicate form is called with the full item list.
     */
    computeFilterActive() {
        const filterable = this.settings.filterable;
        return typeof filterable === 'function' ? filterable(this.items) : filterable;
    }
    /**
     * Mirror `filterActive` onto the DOM + wiring it decides: the trigger's
     * role (`button` while active, `combobox` while not), its `aria-haspopup`
     * and `aria-controls`, the popup wrapper's role, the filter input's
     * `hidden` flag, and which element `comboboxEl` points at (the
     * `aria-activedescendant` / focus host). Called from the constructor and
     * from `open()` after re-evaluation.
     */
    syncFilterModeToDom() {
        const { popupId, popupListId } = this.classIdMap;
        // Active: the popup holds a text field besides the listbox, so it is a
        // dialog, and aria-haspopup must match the role of the popup container
        // (WAI-ARIA 1.2). Inactive: the trigger is the combobox, and the active
        // row must be an owned element of the element its aria-controls names
        // (WAI-ARIA 1.2 aria-activedescendant), so that element is the listbox;
        // a dialog does not support aria-activedescendant. Each attribute is
        // written only when its value changes, so an open that keeps the mode
        // queues no mutation record.
        setAttributeIfChanged(this.triggerEl, 'role', this.filterActive ? 'button' : 'combobox');
        setAttributeIfChanged(this.triggerEl, 'aria-haspopup', this.filterActive ? 'dialog' : 'listbox');
        setAttributeIfChanged(this.triggerEl, 'aria-controls', this.filterActive ? popupId : popupListId);
        setAttributeIfChanged(this.popupEl, 'role', this.filterActive ? 'dialog' : null);
        this.filterInputEl.hidden = !this.filterActive;
        this.comboboxEl = this.filterActive ? this.filterInputEl : this.triggerEl;
        this.syncFieldNameToDom();
        this.syncTriggerTabindex();
    }
    /**
     * Reflect the field's accessible name (`ariaLabel` / `ariaLabelledBy`) onto
     * the elements that carry it. Runs with `syncFilterModeToDom` (constructor +
     * every open) because the trigger's wiring depends on the mode:
     * - Trigger, filter inactive (`role="combobox"`): the name directly; the
     *   combobox VALUE already comes from the screen-reader text inside it.
     * - Trigger, filter active (`role="button"`): a button's name would
     *   otherwise be its content (the current value) with no field name, so
     *   `aria-labelledby` chains label + screen-reader text. With only `ariaLabel`
     *   there is no label element to reference, so the chain starts at the
     *   trigger itself - the accname algorithm substitutes its `aria-label`.
     * - Filter input: the field name replaces the `uiTranslationPack.filterInputAriaLabel`
     *   fallback (while the filter is active the input IS the field's combobox).
     * - Listbox: the field name, both modes.
     * - Popup wrapper: the field name while the filter is active (a dialog
     *   needs a name), nothing while it is inactive (no role).
     */
    syncFieldNameToDom() {
        const apply = (el, labelledBy, label) => {
            if (labelledBy !== null) {
                el.setAttribute('aria-labelledby', labelledBy);
            }
            else {
                el.removeAttribute('aria-labelledby');
            }
            if (label !== null) {
                el.setAttribute('aria-label', label);
            }
            else {
                el.removeAttribute('aria-label');
            }
        };
        const { ariaLabel, ariaLabelledBy } = this.settings;
        const { triggerId, triggerScreenReaderTextId } = this.classIdMap;
        if (ariaLabelledBy !== null) {
            apply(this.triggerEl, this.filterActive ? `${ariaLabelledBy} ${triggerScreenReaderTextId}` : ariaLabelledBy, null);
            apply(this.filterInputEl, ariaLabelledBy, null);
            apply(this.popupListEl, ariaLabelledBy, null);
            apply(this.popupEl, this.filterActive ? ariaLabelledBy : null, null);
        }
        else if (ariaLabel !== null) {
            apply(this.triggerEl, this.filterActive ? `${triggerId} ${triggerScreenReaderTextId}` : null, ariaLabel);
            apply(this.filterInputEl, null, ariaLabel);
            apply(this.popupListEl, null, ariaLabel);
            apply(this.popupEl, null, this.filterActive ? ariaLabel : null);
        }
        else {
            apply(this.triggerEl, null, null);
            apply(this.filterInputEl, null, this.settings.uiTranslationPack.filterInputAriaLabel);
            apply(this.popupListEl, null, null);
            apply(this.popupEl, null, null);
        }
    }
    /**
     * Warns once per page that `open()` refused a hidden trigger, naming the
     * trigger wrapper. A refusal is otherwise silent: the click or the key does
     * nothing (`FIXME.md` QUALITY-798).
     */
    warnHiddenTriggerOnce() {
        if (warnedHiddenTrigger) {
            return;
        }
        warnedHiddenTrigger = true;
        console.warn('llselect: open() did nothing, because the trigger is outside the viewport or clipped away by an ancestor, so the popup would have nowhere to show. Scroll the trigger into view, then open again. (warned once per page; the trigger wrapper:)', this.triggerWrapperEl);
    }
    /**
     * Warn once per page when a control sits before the filter input in the
     * popup, which the prepend recipe of the header slot can cause (DESIGN.md
     * "Popup header / footer slots"): while the filter is active, Tab from the
     * input skips that control, and Shift+Tab enters it instead of leaving the
     * select component.
     * - Runs at the end of each `open()` while the filter is active, after
     *   `onOpen`, which may add or enable a header control. Never at
     *   construction: the recipe moves the header in a subclass constructor,
     *   after `super()`.
     * - A control counts when it is, or can become, a Tab stop (`canBeTabStop`).
     * - Walks only the popup children before the input, so the default order
     *   costs one sibling read.
     */
    warnIfFocusableBeforeFilterInput() {
        if (warnedFocusableBeforeFilterInput) {
            return;
        }
        for (let el = this.filterInputEl.previousElementSibling; el !== null; el = el.previousElementSibling) {
            const offender = canBeTabStop(el) ? el : Array.from(el.querySelectorAll(TAB_STOP_SELECTOR)).find(canBeTabStop);
            if (offender === undefined) {
                continue;
            }
            warnedFocusableBeforeFilterInput = true;
            console.warn('llselect: a control sits before the filter input in the popup. While the filter is active, Tab from the filter input skips it, and Shift+Tab enters it instead of leaving the select component. Keep the header after the filter input, move the control to the footer, or give it tabindex="-1". (warned once per page; first offender:)', offender);
            return;
        }
    }
    /**
     * Open the popup.
     * - Does nothing in each of these cases:
     *   - the popup is already open;
     *   - the select component is disabled;
     *   - `destroy()` has started, so an `open()` call from a listener that
     *     `destroy()` runs is ignored, such as an `onClose` that reopens the
     *     popup;
     *   - `close()` is returning focus to the trigger, so a focus handler that
     *     calls `open()` there is ignored;
     *   - the select component is putting its closed state back, in `close()`
     *     or in `destroy()`, so an `open()` call from code that the browser
     *     runs there is ignored, such as a `beforetoggle` listener of the
     *     popup or the reaction of a root that is a custom element;
     *   - this select component's own `showPopover()` is running, so an
     *     `open()` call from a listener there is ignored, for example after
     *     the listener closed the select component;
     *   - `open()` is undoing a show that the browser refused, so an `open()`
     *     call from a listener that the undo runs is ignored;
     *   - the trigger is hidden: fully outside the viewport, or fully clipped
     *     away by an ancestor.
     * - The first refusal for a hidden trigger on a page logs a console
     *   warning.
     * - Sets an initial active row, if an enabled item row exists.
     * - An action row is never the initial active row.
     * - While the filter is active, DOM focus moves to the filter input.
     * - In a browser with the Popover API, the popup shows through
     *   `showPopover()`.
     *   - The browser then focuses a control in a header or footer slot that
     *     has the `autofocus` attribute.
     *   - While the filter is active, the filter input takes DOM focus after
     *     that.
     * - If a listener closes the select component while `showPopover()` runs,
     *   such as an `onFocus` that the `autofocus` move fires, or a
     *   `beforetoggle` listener of the popup, the open stops there.
     *   - It attaches no positioner, no outside-click handler and no
     *     scroll-gesture listener.
     *   - It fires no `onOpen`.
     *   - A reopen from that listener is ignored, as the list above says.
     *   - A listener that only re-renders does not stop the open.
     * - If a function that `open()` calls closes or destroys the select
     *   component, the open stops there too.
     *   - Such functions are the `filterable` predicate, the group functions,
     *     the content functions of the arrow and of the list, and the
     *     overridable methods that `open()` runs: `isEmpty`, the two
     *     `shouldListenFor...` predicates, `focusInitial` and `onOpened`.
     *     `onOpen` is one too.
     *   - The open attaches nothing more, and what it had attached is detached.
     *   - Of `onOpened` and `onOpen`, the ones that have not run yet do not
     *     run. `onClose` has fired for that close.
     *   - If the function also opens the select component again, that newer
     *     open is the one that counts. The first call adds nothing to it.
     *   - Only the notifications among those functions are meant to do this.
     *     A function that builds or decides must not change the select
     *     component: the popup may then show outdated rows.
     * - If another popover of the same document is in the middle of its show
     *   or hide, `showPopover()` can throw an `InvalidStateError`, as
     *   Chromium 156, Firefox 153 and WebKit 26.5 do.
     *   - `open()` then undoes itself through `close()`, so the select
     *     component stays closed.
     *   - A `close()` override that throws before it calls `super.close()`
     *     leaves the select component marked open, with no list shown.
     *   - Neither `onOpen` nor `onClose` fires.
     *   - `open()` passes the browser's error on to its caller.
     *   - An error raised during that undo is dropped, for example an error
     *     of `createTriggerArrowContentElFn`, of an `onActiveItemChange`
     *     listener or of a `close()` override.
     *   - An error inside that `close()` skips the rest of it, such as the
     *     active-item report.
     *   - To open from a listener that runs during such a show or hide, call
     *     `open()` inside a `setTimeout` callback.
     *   - A `queueMicrotask` callback is not enough: when the browser itself
     *     started the show, as a `popovertarget` button does, that callback
     *     still runs inside it.
     * - The positioner closes the popup again, with the close reason
     *   `'hidden'`, when a scroll outside the popup finds the trigger hidden.
     * - Builds the item elements, which exist only while the popup is open.
     * - Attaches the positioner.
     * - Attaches the outside-click handler.
     * - Attaches the scroll-gesture and zoom-gesture listeners; see
     *   `behaviorOfScrollGestureFn` and `behaviorOfZoomGestureFn`.
     * - The initial active row comes from `focusInitial`, which a subclass can
     *   override.
     * @group Open & close
     */
    open() {
        const reason = this.pendingOpenReason;
        this.pendingOpenReason = 'api';
        const refused = () => this.opened || this.disabled || this.destroyed || this.closing || this.opening;
        if (refused()) {
            return;
        }
        // A trigger already scrolled out of view / clipped by an ancestor when
        // open() runs cannot host a visible popup, so opening is a no-op (mirrors
        // the disabled guard). It also spares an open that the positioner's first
        // placement would close at once, through onHide.
        if (isAnchorHidden(this.triggerWrapperEl)) {
            this.warnHiddenTriggerOnce();
            return;
        }
        const cycleBefore = this.openCycle;
        this.syncColorScheme();
        // The scheme write can change an attribute of the root element. A root
        // that is a custom element may observe that attribute, and its reaction
        // runs inside the write: it may destroy or disable the select component,
        // or open it. So the tests of the top are asked again. A reaction that
        // opened the popup and closed it again has had the last word as well:
        // the cycle number tells.
        if (refused() || this.openCycle !== cycleBefore) {
            return;
        }
        const restoreWindowScroll = this.captureWindowScroll();
        this.opened = true;
        this.transitionGeneration++;
        // This call runs app and subclass code: predicates, content functions,
        // hooks. Such a function may close or destroy the select component, and
        // may open it again. The cycle that this call started is then over, and
        // the rest of the call must attach nothing and fire no open notification
        // that is still due (FIXME MEDIUM-969). Each check below follows a step
        // that runs such code.
        const cycle = ++this.openCycle;
        // A destroyed select component is closed as well: `destroy()` leaves none
        // open, whatever its `close()` call did, and the tests above mark none
        // open.
        const superseded = () => !this.opened || this.openCycle !== cycle;
        // Ends the call. A destroyed select component is left alone: nothing of
        // it is written again, and the scroll restore does nothing for it. A
        // closed one gets its closed state again, since the step that ran the
        // function may have written after the close. One that is open again
        // belongs to the newer cycle: nothing of it is touched. Either way the
        // active item is reported last: the close, or the newer open, may have
        // tried to report while this call still held the report back.
        const abandon = () => {
            if (this.destroyed) {
                return;
            }
            if (!this.opened) {
                this.clearOpenState();
            }
            restoreWindowScroll();
            this.reportActiveItem();
        };
        // Filter mode is (re)evaluated once per open cycle, before anything that
        // depends on it (role, focus host, filtering).
        const filterActive = this.computeFilterActive();
        if (superseded()) {
            abandon();
            return;
        }
        this.filterActive = filterActive;
        this.syncFilterModeToDom();
        this.syncTriggerButtonsToDom();
        if (superseded()) {
            abandon();
            return;
        }
        this.triggerEl.setAttribute('aria-expanded', 'true');
        this.triggerWrapperEl.setAttribute('data-state', 'open');
        this.rootEl.classList.add(this.classIdMap.openClass);
        // A root that is a custom element may observe its class as well.
        if (superseded()) {
            abandon();
            return;
        }
        if (this.filterActive) {
            this.query = '';
            this.filterInputEl.value = '';
            this.filterInputEl.setAttribute('aria-expanded', 'true');
            this.recomputeFilteredItems();
            if (superseded()) {
                abandon();
                return;
            }
        }
        // Start from no active row, before `showPopover()` can run a listener
        // that re-renders: a `setFocusedIndex` made while closed must not be
        // reported as the initial row before `focusInitial` places it; the
        // report itself waits for the tail of this method.
        this.focusedRow = null;
        this.focusedIndex = -1;
        // `position: fixed` MUST be set before `hidden = false`. Otherwise the
        // popup is briefly an in-flow `display: flex` block while `renderPopupList`
        // appends its items, which inflates document height by the popup's
        // natural height; browsers can then run scroll-anchoring / URL-bar
        // resize before the positioner takes over and shift window scroll, even
        // though captureWindowScroll restores it at the end.
        // (Layout / display can only be set while open: setting them in the
        // constructor would override the `[hidden]` UA rule and leak the popup
        // before first open.)
        this.popupEl.style.position = 'fixed';
        this.popupEl.style.display = 'flex';
        this.popupEl.style.flexDirection = 'column';
        this.popupEl.hidden = false;
        if (this.popoverSupported && this.popupEl.isConnected) {
            // Enter the top layer BEFORE anything measures: only there is the
            // viewport the popup's containing block, whatever its ancestors. The UA
            // rule that hides a popover outside its showing state carries no
            // `!important`, so the inline `display: flex` above wins over it: a
            // show that an app's `beforetoggle` listener cancels leaves the popup
            // rendered in place, outside the top layer, which is unsupported
            // (FIXME MEDIUM-862). UA `[popover]` also sets `inset: 0`;
            // the positioner's inline top/left override two edges, but the
            // remaining `right/bottom: 0` over-constrain the box - and in an RTL
            // containing block an over-constrained `left` LOSES to `right: 0` -
            // so neutralize both. UA `[popover]` also sets `height: fit-content`:
            // WebKit 18 resolves that to 0 for this column flex box under its
            // `max-height` with a `flex-basis: 0%` list, so the popup showed as
            // its two borders (Safari 18, GNOME Web; FIXME HIGH-705); `auto` gave
            // the same shrink-to-fit box in every engine tested, WebKit 18 and 26,
            // Chromium and Firefox. (isConnected: showPopover()
            // throws on a disconnected element; a detached select component is invisible
            // either way.)
            this.opening = true;
            try {
                this.popupEl.showPopover();
            }
            catch (error) {
                // The browser refused the show, as Chromium 156, Firefox 153 and
                // WebKit 26.5 do while another popover of the document is in the
                // middle of its show or hide. `close()` puts back the closed state
                // that a completed open and close leaves, as it must anyway; the
                // filter mode and the color scheme stay, as after any close.
                this.undoingOpen = true;
                try {
                    this.close();
                }
                catch {
                    // Dropped, so that the caller gets the browser's error.
                }
                finally {
                    this.undoingOpen = false;
                }
                try {
                    restoreWindowScroll();
                }
                catch {
                    // Dropped for the same reason.
                }
                throw error;
            }
            finally {
                this.opening = false;
            }
            // A listener that the browser runs inside the show may close the
            // select component: a focus listener, since the popover focusing steps
            // can focus an `autofocus` slot control, or a `beforetoggle` listener.
            // The second runs before the popover shows, so the `hidePopover()` of
            // its close has nothing to hide, and the show then completes: the
            // stopped call puts the closed state back once more.
            if (superseded()) {
                abandon();
                return;
            }
            this.popupEl.style.right = 'auto';
            this.popupEl.style.bottom = 'auto';
            this.popupEl.style.height = 'auto';
        }
        this.renderTriggerArrow();
        if (superseded()) {
            // The render above has committed the arrow of the open state. If its
            // content function closed the select component, that commit came after
            // the arrow that `close()` rendered.
            if (!this.destroyed && !this.opened) {
                this.renderTriggerArrow();
            }
            abandon();
            return;
        }
        // The active-item report waits while the steps of `attachOpenPopup` run.
        // A stopped call ends only after that wait is over, so that `abandon`
        // can report for a newer cycle.
        this.activeItemReportSuspendDepth++;
        let attached;
        try {
            attached = this.attachOpenPopup(superseded);
        }
        finally {
            this.activeItemReportSuspendDepth--;
        }
        if (!attached) {
            abandon();
            return;
        }
        this.onOpened();
        if (superseded()) {
            abandon();
            return;
        }
        const onOpen = this.settings.onOpen;
        onOpen?.({ reason });
        // A hook above may have closed the popup, and may have opened it again:
        // nothing below is left to do for this call.
        if (superseded()) {
            abandon();
            return;
        }
        if (this.filterActive) {
            this.warnIfFocusableBeforeFilterInput();
            this.filterInputEl.focus({ preventScroll: true });
        }
        restoreWindowScroll();
        // Last, so a listener that closes the select component does so after this open
        // completed, with no step above left to run on a closed popup.
        this.reportActiveItem();
    }
    /**
     * The steps of `open()` that run while the active-item report waits.
     * - They are the list render, the positioner, the outside-click handler,
     *   the gesture listeners and the initial active row.
     * - `superseded` is the test of `open()`: whether a function that the call
     *   ran has closed or destroyed the select component, or opened it again.
     * - Returns `false` as soon as a step finds the call superseded. Nothing
     *   that this call created is attached then.
     */
    attachOpenPopup(superseded) {
        this.renderPopupList();
        if (superseded()) {
            return false;
        }
        // The first placement can find the trigger hidden and close the popup
        // through `onHide`, before `this.positioner` is set. That close cannot
        // detach this positioner, so this method does. If a listener opened the
        // popup again, the newer positioner places the popup once more, since
        // the detach cleared the inline styles they share.
        const positioner = createPositioner(this.triggerWrapperEl, this.popupEl, {
            onHide: () => this.closeWithReason('hidden'),
            widthPolicy: this.settings.popupWidthPolicy,
            distanceFromAnchor: this.settings.popupDistanceFromTriggerWrapper,
            distanceFromViewportEdge: this.settings.popupDistanceFromViewportEdge,
            innerScrollEl: this.popupListEl,
        });
        if (superseded()) {
            positioner.detach();
            this.positioner?.reposition();
            return false;
        }
        this.positioner = positioner;
        this.attachOutsideClick();
        const scrollOutside = this.shouldListenForScrollGesturesOutside();
        if (superseded()) {
            return false;
        }
        const zoomOutside = this.shouldListenForZoomGesturesOutside();
        if (superseded()) {
            return false;
        }
        this.attachGestures(scrollOutside, zoomOutside);
        this.focusInitial();
        return !superseded();
    }
    /**
     * Close the popup.
     * - If the popup is already closed, does nothing.
     * - Detaches the positioner, the outside-click listener and the
     *   scroll-gesture and zoom-gesture listeners.
     * - If the library blocks the moves of a touch whose touch-down closed
     *   the popup, or swallows its click, that touch keeps its own listeners.
     *   - They go when the touch and its click are over, or when a second
     *     finger or a new touch lands.
     * - If a zoom closed the popup and blocks the zoom, the zoom keeps its own
     *   listeners, on its fingers and on the document.
     *   - They go when every finger has lifted.
     * - Clears the item DOM.
     * - Resets the focused-item state.
     *
     * Focus return is decided automatically: when DOM focus is still inside
     * the popup at the moment of close - the filter input (Esc on an empty
     * filter, a single-select pick, an outside press on a non-focusable area)
     * or a focusable control the app placed in a header / footer slot (Esc
     * there, or `close()` called from its own click) - focus is returned to
     * the trigger. Tab-away and outside clicks on focusable elements have
     * already moved focus elsewhere, so we leave it alone.
     * - The return happens before the popup is hidden and before `onClose`:
     *   hiding a focused element first would let the browser drop focus to
     *   `<body>`, a blur and focus pair the select component never meant.
     * - `open()` also calls `close()` to undo itself when the browser refuses
     *   its `showPopover()`.
     *   - That close fires neither `onClosed` nor `onClose`.
     *   - `open()` drops an error that this close raises, so that its caller
     *     gets the browser's error.
     * @group Open & close
     */
    close() {
        const reason = this.pendingCloseReason;
        this.pendingCloseReason = 'api';
        const scrollGesture = this.pendingScrollGesture;
        this.pendingScrollGesture = undefined;
        const zoomGesture = this.pendingZoomGesture;
        this.pendingZoomGesture = undefined;
        if (!this.opened) {
            return;
        }
        const shouldReturnFocus = this.isFocused(this.popupEl);
        this.opened = false;
        this.transitionGeneration++;
        this.triggerEl.setAttribute('aria-expanded', 'false');
        this.triggerWrapperEl.setAttribute('data-state', 'closed');
        this.syncTriggerTabindex();
        this.syncTriggerButtonsToDom();
        if (shouldReturnFocus) {
            // A focus handler on the trigger may call open(); refuse it until the
            // teardown below is done, or it would set up a popup this close()
            // then hides and strips of its listeners.
            this.closing = true;
            try {
                this.triggerEl.focus({ preventScroll: true });
            }
            finally {
                this.closing = false;
            }
        }
        this.clearOpenState();
        this.renderTriggerArrow();
        // An open undone after `showPopover()` threw fired no `onOpened` /
        // `onOpen`, so its close fires neither mirror.
        if (!this.undoingOpen) {
            this.onClosed();
            const onClose = this.settings.onClose;
            onClose?.(scrollGesture !== undefined ? { reason, scrollGesture } : zoomGesture !== undefined ? { reason, zoomGesture } : { reason });
        }
        // Last, so a listener that reopens the select component does so after this close
        // completed, with no step above left to run on an open popup.
        this.reportActiveItem();
    }
    /**
     * Puts the popup and its list into the closed state.
     * - Detaches the positioner and the listeners of the open popup.
     * - Empties the list and hides the popup.
     * - Resets the active row and the filter query.
     * - It calls no content function, no predicate and no overridable method,
     *   and it fires none of the library's callbacks.
     * - The arrow of the closed state is not its work: `close()` renders that
     *   arrow right after it.
     * - The browser can still run app code inside its writes: the reaction of
     *   a root that is a custom element, a `beforetoggle` listener of the
     *   popup, and the reactions of custom elements in the rows it removes.
     * - `open()` does nothing while it runs.
     * - `close()` runs it, after the focus return.
     * - `open()` runs it when a function it called closed the select
     *   component, since that call may have written over the closed state
     *   afterwards.
     * - `destroy()` always runs it after its `close()` call, whatever that
     *   call did.
     * - A second run on a closed popup writes the same values again.
     */
    clearOpenState() {
        // The writes below can run app code: a root that is a custom element may
        // observe its class, `hidePopover()` fires `beforetoggle`, and removing
        // the rows disconnects custom elements in their content. `open()` is
        // refused until the closed state is whole, since the rest of this method
        // would take the new popup's positioner, listeners and rows away.
        const closing = this.closing;
        this.closing = true;
        try {
            this.rootEl.classList.remove(this.classIdMap.openClass);
            if (this.filterActive) {
                this.filterInputEl.setAttribute('aria-expanded', 'false');
                this.filterInputEl.value = '';
                this.query = '';
                this.filteredItems = undefined;
            }
            this.positioner?.detach();
            this.positioner = undefined;
            this.detachOutsideClick();
            this.detachGestures?.();
            this.detachGestures = undefined;
            if (this.popoverSupported) {
                try {
                    this.popupEl.hidePopover();
                }
                catch {
                    // The popup may not be showing: never shown, after a refused show, or
                    // hidden without us, as dialog.showModal() may do (TODO.md
                    // "Modal-over-popup real-browser pass" asks whether it does). A
                    // never-shown popup's hidePopover() returned without effect in
                    // Chromium 156, Firefox 153, WebKit 26.5 and WebKit 18.4; one that
                    // dialog.showModal() hid may throw InvalidStateError (unmeasured).
                    // State resyncs right here.
                }
                this.popupEl.style.right = '';
                this.popupEl.style.bottom = '';
                this.popupEl.style.height = '';
            }
            // After the hide: a `beforetoggle` listener of the hide may render rows
            // again, and this removal takes them away too.
            this.popupListEl.replaceChildren();
            // The no-results region hides with the popup; reset so a reopen with a
            // still-empty list counts as a fresh appearance and re-announces.
            this.lastNoResultsText = null;
            this.popupEl.hidden = true;
            // Clear inline display + position so the `[hidden]` UA rule can hide the
            // popup cleanly. (Position was set in open() to keep the popup out of
            // flow before the positioner attached; positioner.detach() also clears
            // it, but be explicit and symmetric with what open() set.)
            this.popupEl.style.position = '';
            this.popupEl.style.display = '';
            this.popupEl.style.flexDirection = '';
            this.itemEls = [];
            this.focusedEl = undefined;
            this.focusedIndex = -1;
            this.typeaheadBuffer = '';
            this.chooseAllRowEl = undefined;
            this.leadingActionRowEls = [];
            this.trailingActionRowEls = [];
            this.focusedRow = null;
            this.comboboxEl.removeAttribute('aria-activedescendant');
        }
        finally {
            this.closing = closing;
        }
    }
    /** `open()` with a stated reason; see `pendingOpenReason`. */
    openWithReason(reason) {
        this.pendingOpenReason = reason;
        this.open();
    }
    /**
     * `close()` with a stated reason; see `pendingCloseReason`. Protected for
     * the single select component's pick, which closes with `'choose'`.
     * @internal
     */
    closeWithReason(reason) {
        this.pendingCloseReason = reason;
        this.close();
    }
    /**
     * Picks what the select component does with one scroll gesture while the
     * popup is open.
     * - The library's scroll-gesture listeners call this method on every
     *   gesture that the docstring of `behaviorOfScrollGestureFn` lists.
     * - The listeners fill `gesture`: what the gesture is and where it
     *   happens. See {@link LLSelectScrollGesture}.
     * - The default returns `behaviorOfScrollGestureFn(gesture)`.
     * - Configure via `behaviorOfScrollGestureFn` (no subclass needed).
     * - An override replaces the setting, and
     *   `super.behaviorOfScrollGesture(gesture)` still reaches the setting.
     * - An override that answers gestures outside the select component also
     *   overrides {@link shouldListenForScrollGesturesOutside}. By default the
     *   library listens there only while the setting is not
     *   `defaultBehaviorOfScrollGesture`.
     * @group Subclassing: semantics
     */
    behaviorOfScrollGesture(gesture) {
        return this.settings.behaviorOfScrollGestureFn(gesture);
    }
    /**
     * Whether the select component listens for scroll gestures outside
     * itself, on the document, while the popup is open.
     * - `open()` calls this method once per open, right after it attaches the
     *   outside-click listeners.
     * - The default returns `true` when `behaviorOfScrollGestureFn` is not
     *   `defaultBehaviorOfScrollGesture`.
     *   - The default function leaves every gesture outside the select
     *     component alone, so the library does not listen there for it.
     *   - `@llselect/core` and `@llselect/core/behavior-presets` each export a
     *     copy of the default function, and either copy counts as the default.
     * - A subclass whose `behaviorOfScrollGesture` answers gestures outside
     *   the select component overrides this method to return `true`.
     * - Listening there has a cost. A non-passive `wheel` or `touchmove`
     *   listener on the document makes every scroll of the page wait for
     *   script while the popup is open.
     * @group Subclassing: semantics
     */
    shouldListenForScrollGesturesOutside() {
        return !(DEFAULT_BEHAVIOR_OF_SCROLL_GESTURE_MARK in this.settings.behaviorOfScrollGestureFn);
    }
    /**
     * Picks what the select component does with one zoom gesture while the
     * popup is open.
     * - The library's gesture listeners call this method on every zoom
     *   gesture that the docstring of `behaviorOfZoomGestureFn` lists.
     * - The listeners fill `gesture`: where the zoom happens. See
     *   {@link LLSelectZoomGesture}.
     * - The default returns `behaviorOfZoomGestureFn(gesture)`.
     * - Configure via `behaviorOfZoomGestureFn` (no subclass needed).
     * - An override replaces the setting, and
     *   `super.behaviorOfZoomGesture(gesture)` still reaches the setting.
     * - An override that may block or close a zoom also overrides
     *   {@link shouldListenForZoomGesturesOutside}, since a finger of a pinch
     *   may land outside the select component.
     * - By default the library listens there only while the setting is not
     *   `defaultBehaviorOfZoomGesture`.
     * @group Subclassing: semantics
     */
    behaviorOfZoomGesture(gesture) {
        return this.settings.behaviorOfZoomGestureFn(gesture);
    }
    /**
     * Whether the select component listens for zoom gestures outside itself,
     * on the document, while the popup is open.
     * - `open()` calls this method once per open, right after it attaches the
     *   outside-click listeners.
     * - The default returns `true` when `behaviorOfZoomGestureFn` is not
     *   `defaultBehaviorOfZoomGesture`.
     *   - The default function leaves every zoom alone, so the library does
     *     not listen outside the select component for it.
     *   - `@llselect/core` and `@llselect/core/behavior-presets` each export a
     *     copy of the default function, and either copy counts as the default.
     * - A subclass whose `behaviorOfZoomGesture` may block or close a zoom
     *   overrides this method to return `true`: a finger of a pinch may land
     *   outside the select component, where only the document's listeners see
     *   its events and can cancel them.
     * - Listening there has a cost. Non-passive `wheel`, `touchstart` and
     *   `touchmove` listeners on the document make every scroll of the page
     *   wait for script while the popup is open.
     * @group Subclassing: semantics
     */
    shouldListenForZoomGesturesOutside() {
        return !(DEFAULT_BEHAVIOR_OF_ZOOM_GESTURE_MARK in this.settings.behaviorOfZoomGestureFn);
    }
    /** Attaches the scroll-gesture and zoom-gesture listeners for this open cycle; `close()` detaches them. */
    attachGestures(scrollOutside, zoomOutside) {
        this.detachGestures = attachGestureListeners({
            rootEl: this.rootEl,
            popupEl: this.popupEl,
            scrollOutside,
            zoomOutside,
            behaviorFor: (gesture) => this.behaviorOfScrollGesture(gesture),
            closeFor: (gesture) => {
                this.pendingScrollGesture = gesture;
                this.closeWithReason('scroll-gesture');
            },
            zoomBehaviorFor: (gesture) => this.behaviorOfZoomGesture(gesture),
            closeForZoom: (gesture) => {
                this.pendingZoomGesture = gesture;
                this.closeWithReason('zoom-gesture');
            },
            // A chip's text and the padding of the strip toggle like the rest of
            // the wrapper; only the strip's buttons stop their own clicks.
            clickToggles: (path) => path.includes(this.triggerWrapperEl) && !this.getTriggerButtonEls().some((button) => path.includes(button)),
            swallowsOutsideClick: this.settings.behaviorOfOutsideClick === 'block',
            holdStarted: (release) => { this.touchHoldReleases.add(release); },
            holdEnded: (release) => { this.touchHoldReleases.delete(release); },
        });
    }
    /**
     * Rebuild the trigger and (while open) the popup list from current state.
     * - Use it after mutating item OBJECTS in place (e.g.
     *   `users[0].name = 'X'`). The library cannot detect that on its own.
     * - Use it too when a function it reruns reads state that changed outside
     *   the items, such as the page language.
     * - It reruns `itemToStringFn` and every content function of the trigger
     *   and the popup list.
     * - It does not rerun the header and footer content functions.
     * - It cannot reach the pack-owned attributes of the filter input, its
     *   placeholder and fallback `aria-label`; `setUiTranslationPack` does.
     * - It re-derives the display order (the `gatherGroups` gather).
     * - While the filter is active, it re-runs the filter against the current
     *   item text.
     * - The refresh is purely visual: it does NOT fire `onChange` and does NOT
     *   run `onItemsChanged`.
     * - Orchestrator: composes `renderTrigger` + `renderPopupList`; touches no
     *   DOM directly.
     * @group Lifecycle
     */
    rerender() {
        this.transitionGeneration++;
        this.gatheredItems = undefined;
        if (this.filterActive) {
            this.recomputeFilteredItems();
        }
        this.renderTrigger();
        if (this.opened) {
            this.renderPopupList();
        }
    }
    /**
     * Tear down the instance.
     * - Closes the popup, which removes the document and window listeners of
     *   the open popup and stops the popup positioning.
     * - If a `close()` override does not close the popup, `destroy()` removes
     *   those listeners and stops the positioning itself. `onClose` does not
     *   fire then.
     * - If that close throws, in a `close()` override or in an `onClose`
     *   listener, `destroy()` still finishes every step below, and then passes
     *   the error on to its caller.
     * - Once `destroy()` has started, `open()` does nothing. So a listener
     *   that this close runs, such as an `onClose` that reopens the popup,
     *   cannot open it again.
     * - Removes the click listener from `labelEl`, and removes an id the
     *   library minted on it.
     * - Removes the library's class, its inline styles and the
     *   `data-llselect-color-scheme` attribute from the mount element, ends the
     *   automatic color-scheme checks, and empties the element.
     * - After `destroy()`, call no method except `destroy()` itself. Each
     *   `destroy()` call repeats the cleanup and empties the mount element. Do
     *   not call it again once the mount element has been reused, for other
     *   content or for a second instance.
     * - REQUIRED before discarding an instance whose popup might be open; a
     *   framework wrapper calls it on unmount. Skipping it there leaks the
     *   outside-click, scroll-gesture, zoom-gesture, focusout, scroll and
     *   resize listeners.
     * - Ends the library's handling of a touch whose touch-down closed the
     *   popup.
     *   - That handling blocks the moves of the touch or swallows its click.
     *   - Without `destroy()`, the handling lasts until the finger lifts, a
     *     second finger lands or a new touch starts, and the wait for the
     *     click up to a second after the lift.
     * - Ends the library's handling of a zoom that closed the popup and blocks
     *   the zoom.
     *   - That handling blocks the moves of the zoom and the touch-down of a
     *     further finger.
     *   - Without `destroy()`, the handling lasts until every finger has
     *     lifted.
     * - Once those handlings are over, discarding a CLOSED instance without
     *   `destroy()` leaks nothing: only
     *   its mount element and `labelEl` retain it, through its own DOM
     *   listeners. Once those elements leave the document and the application
     *   holds no reference to them, the instance is collectable. The root
     *   class, the `overflow-anchor` style and the
     *   `data-llselect-color-scheme` attribute stay on the mount. If the mount
     *   stays in the document outside a shadow root, the automatic checks
     *   continue for an `'auto'` instance: it decides again when the operating
     *   system's color preference changes, and when an attribute of `<html>`
     *   or `<body>` changes.
     * - Building a second instance on the same element replaces the first. The
     *   library drops the first instance's queued scheme decision and its
     *   automatic checks. Call `destroy()` on the first instance BEFORE
     *   building the second. After the rebuild, call no method of the first
     *   instance; its `destroy()` would empty the element under the new select component.
     * @group Lifecycle
     */
    destroy() {
        // First: the close() below and the replaceChildren() at the end can move
        // focus, and no parting focusout may reach onBlur (A11Y.md "Focus").
        this.detachFocusListeners();
        this.destroyed = true;
        this.transitionGeneration++;
        try {
            this.closeWithReason('destroy');
        }
        finally {
            // The teardown does not depend on that `close()`: an override may not
            // have closed the popup, and the call may have thrown at any point, in
            // an override or in an `onClose` listener, also after it had marked the
            // popup closed. Nothing of an open popup may outlive the instance, so
            // the closed state is put back whatever `opened` says. No step below
            // calls a function of the settings or an overridable method, so an
            // error of the `close()` above still reaches the caller.
            this.opened = false;
            this.clearOpenState();
            for (const release of [...this.touchHoldReleases]) {
                release();
            }
            this.touchHoldReleases.clear();
            this.disarmOutsidePressClickSwallow?.();
            if (this.settings.labelEl !== null) {
                this.settings.labelEl.removeEventListener('click', this.handleLabelElClick);
                if (this.labelElIdMinted) {
                    this.settings.labelEl.removeAttribute('id');
                }
            }
            this.rootEl.classList.remove(this.classIdMap.rootClass, this.classIdMap.openClass);
            this.rootEl.style.overflowAnchor = '';
            unsubscribeColorScheme(this.rootEl);
            cancelFirstDecision(this.rootEl, this.colorSchemeDecision);
            this.colorSchemeDecisionPending = false;
            this.rootEl.removeAttribute(COLOR_SCHEME_ATTRIBUTE);
            this.rootEl.replaceChildren();
        }
    }
    /**
     * Open if closed, close if open.
     * @group Open & close
     */
    toggle() {
        if (this.opened) {
            this.closeWithReason('toggle');
        }
        else {
            this.openWithReason('toggle');
        }
    }
    /**
     * Whether the popup is currently open.
     * - Read through a method, like `isDisabled()`.
     * - The same state is mirrored on the DOM as CSS hooks:
     *   `data-state="open|closed"` on the trigger wrapper,
     *   `classIdMap.openClass` on the root.
     * @group Open & close
     */
    isOpened() {
        return this.opened;
    }
    /**
     * Return the full list the user chooses from, in data order (as passed to `setItems`).
     * - The chosen items are a subset of it.
     * - The rendered list may differ in order and content: see `getVisibleItems`.
     * - Returns the LIVE internal array, typed read-only. Do not mutate it
     *   (TS blocks it; plain-JS callers must treat it as frozen).
     * - Structural mutation would silently bypass chosen-state reconciliation,
     *   re-filtering, and re-render. Replace the list via `setItems` instead.
     * - Mutating item OBJECTS + `rerender()` is the supported in-place path.
     * @group Items
     */
    getItems() {
        return this.items;
    }
    /**
     * Return the resolved UI strings: the built-in English defaults merged
     * with the `uiTranslationPack` setting.
     * - Reuse these in your own UI instead of keeping a second translation
     *   source. For example, a tag remove button tooltip:
     *   `sel.getUiTranslationPack().tagRemoveButtonAriaLabel(label)`.
     * - Returns the LIVE object. Treat it as immutable, like `getItems`.
     * @group i18n
     */
    getUiTranslationPack() {
        return this.settings.uiTranslationPack;
    }
    /**
     * Replace the UI-translation pack at runtime, so switching language needs
     * no re-`new`.
     * - One of the two settings with a runtime setter (the other is
     *   `setPlaceholder`); both are copy. The rule: {@link LLSelectBaseSettings}.
     * - The pack is resolved exactly like the constructor's: merged over the
     *   built-in English pack, NOT over the previously set pack.
     * - An explicit constructor `placeholder` keeps winning over the new pack's
     *   `triggerPlaceholder`.
     * - Re-renders the trigger and the open popup.
     * - Also re-applies the pack-owned attributes `rerender()` cannot reach:
     *   the filter input placeholder and its fallback `aria-label`.
     * - The clear button needs no such step: `rerender()` rebuilds it, and the
     *   rebuild reads the new pack - unless a `createTriggerClearButtonEl`
     *   override returns the previous element, which then owns the label.
     * @group i18n
     */
    setUiTranslationPack(uiTranslationPack) {
        const pack = { ...en, ...uiTranslationPack };
        this.settings.uiTranslationPack = pack;
        this.settings.placeholder = this.explicitPlaceholder ?? pack.triggerPlaceholder;
        // Pack-owned attributes rerender() cannot reach:
        this.syncFieldNameToDom();
        this.syncTriggerButtonsNameToDom();
        if (pack.filterInputPlaceholder !== null) {
            this.filterInputEl.placeholder = pack.filterInputPlaceholder;
        }
        else {
            this.filterInputEl.removeAttribute('placeholder');
        }
        this.rerender();
    }
    /**
     * Replace the trigger placeholder text at runtime. It is one of the two
     * settings with a runtime setter (the other is `setUiTranslationPack`);
     * both are copy. The rule: {@link LLSelectBaseSettings}.
     * - `null` = fall back to the pack default (`uiTranslationPack.triggerPlaceholder`),
     *   mirroring an unset constructor `placeholder`. An explicit value keeps
     *   winning over later `setUiTranslationPack` calls, exactly like the
     *   constructor input.
     * - Takes effect immediately. Visible only while nothing is chosen - the
     *   placeholder never renders otherwise (the trigger is still re-rendered,
     *   which also refreshes the screen-reader text).
     * @group Trigger
     */
    setPlaceholder(placeholder) {
        if (this.explicitPlaceholder === placeholder) {
            return;
        }
        this.explicitPlaceholder = placeholder;
        this.settings.placeholder = placeholder ?? this.settings.uiTranslationPack.triggerPlaceholder;
        this.renderTrigger();
    }
    /**
     * Replace the full list the user chooses from.
     * - A chosen item the new list does not hold is dropped.
     * - The input is shallow-copied; later external mutation does not affect
     *   the select component.
     * - Items MUST be unique under `compareFn` (it defines item identity, and the
     *   selection is a set). Duplicates render stale selection DOM; the default
     *   compareFn warns once per page, a custom compareFn is the caller's
     *   responsibility (not scanned, to keep large lists cheap).
     * - If the popup is open, it re-renders now. While closed, the DOM is
     *   built lazily on the next `open()`.
     * - `LLSelectMultiple` renders an open popup once more when this call
     *   drops or reorders chosen items, so rows see the final chosen list.
     * - Both shipped variants re-render the trigger content from `onItemsChanged`
     *   (the multiple count total, custom content that reads `items`).
     * - `LLSelectMultiple`'s `triggerDisplay: 'tags'` mode is opt-in; `'count'` is
     *   the default.
     * - When `triggerDisplay` is `'tags'`, that content render is one chip per
     *   chosen item, unless `createTriggerContentElFn` replaces the content.
     * - Subclasses may reconcile chosen-state via {@link onItemsChanged}
     *   (e.g. single mode drops a chosen value that is no longer in the list).
     * @group Items
     */
    setItems(items) {
        this.items = items.slice();
        this.changeRevision++;
        this.warnOnDuplicateItems();
        this.gatheredItems = undefined;
        if (this.filterActive) {
            this.recomputeFilteredItems();
        }
        if (this.opened) {
            this.renderPopupList();
        }
        const triggerRenderCount = this.triggerRenderCount;
        this.onItemsChanged();
        // The variants' onItemsChanged renders the trigger content alone, unless
        // the chosen state changed, which runs renderTrigger whole.
        if (this.triggerRenderCount === triggerRenderCount) {
            this.syncTriggerButtonsToDom();
            this.renderTriggerScreenReaderText();
        }
        // The rows rendered above may have read chosen objects that the variant's
        // reconciliation just swapped for compare-equal reloads (no change fires).
        this.replacePopupListActionRowElsInDom();
    }
    /**
     * Warn (once per page, never throw) when the item list has duplicates under
     * the DEFAULT compareFn - an O(n) Set check. A custom compareFn is documented
     * only: an O(n^2) scan would tax large lists (see PERFORMANCE-31), and keeping
     * its identity unique is the caller's responsibility.
     * - The Set is SameValueZero, and so is the default compareFn, so a repeated
     *   `NaN` item counts as a duplicate on both sides.
     */
    warnOnDuplicateItems() {
        if (warnedDuplicateItems || this.settings.compareFn !== defaultCompareFn) {
            return;
        }
        if (new Set(this.items).size === this.items.length) {
            return;
        }
        warnedDuplicateItems = true;
        console.warn('llselect: duplicate items passed to setItems - items must be unique under compareFn (it defines item identity, and the selection is a set). Duplicates render stale selection state. (warned once per page)');
    }
    /**
     * Enable or disable the whole control. Disabled: the trigger gets
     * `aria-disabled` and the trigger wrapper `data-disabled` (never the native
     * `disabled` attribute, which would suppress the hover / focus events a
     * tooltip needs), opening is blocked, an open popup closes, the trigger
     * leaves the tab order unless `focusableWhenDisabled` is set, and no button
     * of the trigger buttons strip is a Tab stop. Stored as state, mirroring `setItems` /
     * `setChosenItems` (this design keeps mutable state out of settings).
     * @group Disabling
     */
    setDisabled(value) {
        if (this.disabled === value) {
            return;
        }
        this.disabled = value;
        if (value && this.opened) {
            this.closeWithReason('disabled');
        }
        this.syncDisabledStateToDom();
    }
    /**
     * Whether the whole control is disabled.
     * @group Disabling
     */
    isDisabled() {
        return this.disabled;
    }
    /**
     * The color scheme the select component currently shows.
     * - Returns the result of the latest decision, `'light'` or `'dark'`. If the library has not decided for this select component yet, the method decides now and returns that result.
     * - A decision this early does not cancel the first queued decision.
     * - For a select component inside another select component's trigger or popup, the first queued decision can still change the result.
     * - Never `'auto'`. The `colorScheme` setting explains how `'auto'` resolves.
     * @group Color scheme
     */
    getColorScheme() {
        if (this.colorSchemeDecisionPending) {
            this.syncColorScheme();
        }
        return this.resolvedColorScheme;
    }
    /**
     * Decide the color scheme again, now.
     * - Call it after replacing a stylesheet that affects the scheme.
     * - Call it after a class or attribute that selects the scheme changes on the root element or on an ancestor below `<body>`. The same holds for the variable `--llselect-color-scheme` set there.
     * - If you build the select component before inserting its element into the document, call it after the insertion. A detached element has no computed style, so an `'auto'` select component decided light.
     * - The library checks by itself when the popup opens. Outside a shadow root, it also checks when the operating system's color preference changes, and when an attribute of `<html>` or `<body>` changes.
     * - A select component inside a shadow root misses those two automatic checks. Call it after such a change.
     * - Changes nothing when the `colorScheme` setting is `'light'` or `'dark'`.
     * @group Color scheme
     */
    refreshColorScheme() {
        this.syncColorScheme();
    }
    /** Run the decision and reflect it on the root attribute: the read step, then the write step. */
    syncColorScheme() {
        this.readColorScheme();
        this.applyColorScheme();
    }
    /** The read step: resolve the scheme from the page. In a batch, the roots outside other select components all read before any writes, so one style flush serves them (`decideBatch` in color-scheme.ts). */
    readColorScheme() {
        // An early decision leaves the queued one in place: a root inside another
        // select component may have read that select component's provisional
        // value, and the batch decides it again after the outer root has written.
        this.colorSchemeDecisionPending = false;
        this.resolvedColorScheme = resolveColorScheme(readColorSchemeInputs(this.rootEl, this.settings.colorScheme));
        // A forced value says nothing about the page, and a detached root does
        // not reflect the page: neither is the document's decision.
        if (this.settings.colorScheme === 'auto' && this.rootEl.isConnected) {
            rememberColorScheme(this.rootEl.ownerDocument, this.resolvedColorScheme);
        }
    }
    /** The write step: the root attribute, only when it changed (the root may itself be an observed element). */
    applyColorScheme() {
        const scheme = this.resolvedColorScheme;
        if (this.rootEl.getAttribute(COLOR_SCHEME_ATTRIBUTE) !== scheme) {
            this.rootEl.setAttribute(COLOR_SCHEME_ATTRIBUTE, scheme);
        }
    }
    /** Reflect `this.disabled` onto the trigger's ARIA and tabindex, the wrapper's `data-disabled` and the strip's Tab stop. */
    syncDisabledStateToDom() {
        if (this.disabled) {
            this.triggerEl.setAttribute('aria-disabled', 'true');
            this.triggerWrapperEl.setAttribute('data-disabled', 'true');
        }
        else {
            this.triggerEl.removeAttribute('aria-disabled');
            this.triggerWrapperEl.setAttribute('data-disabled', 'false');
        }
        this.syncTriggerTabindex();
        this.syncTriggerButtonsToDom();
    }
    /**
     * Recompute the trigger's tabindex from every input that owns it: disabled
     * state (with `focusableWhenDisabled`), and the filterable open cycle -
     * while the filter input is the focus host the trigger leaves the tab
     * order, so the open select component stays a single tab stop and Shift+Tab exits
     * instead of landing on the trigger with the popup still open
     * (`docs/llm/A11Y.md` "Focus").
     */
    syncTriggerTabindex() {
        const disabledAndUnfocusable = this.disabled && !this.settings.focusableWhenDisabled;
        const filterOwnsFocus = this.opened && this.filterActive;
        this.triggerEl.setAttribute('tabindex', disabledAndUnfocusable || filterOwnsFocus ? '-1' : '0');
    }
    /**
     * Subclass hook: called once **after** the popup finishes opening.
     *
     * > No **before** counterpart: there is no `onOpening`.
     *
     * - Default no-op.
     * - The `onOpen` setting fires right **after** this.
     * - The hook is for subclass logic, and the setting for consumer
     *   notification.
     * - If an override of this closes or destroys the select component, or
     *   opens it again, the `onOpen` setting does not fire for this `open()`
     *   call.
     * - If a listener closes the select component while `open()` runs
     *   `showPopover()`, this does not run, while {@link onClosed} does.
     * - If a function that `open()` calls **before** this closes the select
     *   component, such as a content function of the list, this does not run
     *   either.
     * - If the browser refuses the `showPopover()` of `open()`, neither this
     *   nor {@link onClosed} runs.
     * @group Subclassing: reactions
     */
    onOpened() { }
    /**
     * Subclass hook: called once **after** the popup finishes closing.
     *
     * > No **before** counterpart: there is no `onClosing`.
     *
     * - The `onClose` setting fires right **after** this, and both run.
     * - If a listener closes the select component while `open()` runs
     *   `showPopover()`, this runs with no {@link onOpened} **before** it.
     * - If a function that `open()` calls **before** {@link onOpened} closes
     *   the select component, such as a content function of the list, this
     *   runs with no {@link onOpened} **before** it as well.
     * - If the browser refuses the `showPopover()` of `open()`, the close that
     *   undoes the open does not run this.
     * @group Subclassing: reactions
     */
    onClosed() { }
    /**
     * Subclass hook: called **after** the chosen state actually changed, right
     * **before** the variant's `onChange` setting fires (the hook runs first and both run,
     * as with `onClosed`). Default no-op.
     *
     * > Pairs with the variant's `onChosenChanging`, which runs **before** a user change and can stop it.
     * @group Subclassing: reactions
     */
    onChosenChanged() { }
    /**
     * Called inside `setItems`, **after** the new list is installed and an open
     * popup list re-rendered, and **before** the final action-row rebuild at the
     * end of the call. Override to reconcile state that depends on the item list
     * (e.g. clear a chosen value that disappeared). Default no-op.
     *
     * > No **before** counterpart: there is no `onItemsChanging`.
     * @group Subclassing: reactions
     */
    onItemsChanged() { }
    /**
     * Orchestrator: composes the clear-button rebuild + `renderTriggerContent` +
     * `renderTriggerArrow` to (re)build the whole trigger from state, then
     * brings the trigger buttons strip in line (its `hidden` flag and its Tab
     * stop) and writes the screen-reader text from
     * {@link computeTriggerScreenReaderText}; touches no DOM directly.
     * Subclasses normally override {@link renderTriggerContent}, not this.
     * - Runs on every change of the chosen value, the placeholder or the pack.
     * - `rerender()` runs it too.
     * - While `clearable` is on, the first run builds the clear button and every
     *   later run swaps it for whatever `createTriggerClearButtonEl` returns: a
     *   fresh button from the base implementation, like the arrow. An override
     *   may return the previous element; it is then kept in place.
     * - If the button is rebuilt and the old one held focus - on it or inside
     *   its icon - the rebuilt BUTTON gets it.
     * - If the builder returned the same element, nothing was rebuilt, and focus
     *   goes back to the node that held it, if that node is still inside the
     *   button and can take focus; otherwise focus stays on the button.
     * - `setItems` runs `renderTriggerContent` alone, because only the content
     *   reads the list (the multiple count total, a custom
     *   `createTriggerContentElFn`'s `items`).
     * - A `setItems` that drops the chosen entry runs the whole trigger.
     * - Runs once from the `LLSelectSingle` / `LLSelectMultiple` constructor, right
     *   after `super()`.
     * - On that first run a FURTHER subclass's own fields are still `undefined`:
     *   JS runs a subclass's field initializers only after its super constructor
     *   returns (virtual-call-in-constructor). An override of a trigger method
     *   (`renderTriggerContent`, or a `create*El` it calls) that reads such a
     *   field sees `undefined` there.
     * - The recipe: put construction-time configuration in the typed
     *   `subclassSettings` constructor param. `this.settings` is complete before
     *   any construction code runs.
     * - For genuine instance state, tolerate defaults during construction, or call
     *   `rerender()` at the end of your own constructor.
     * - The popup-list methods do NOT run here; they wait for `open()`. See
     *   DESIGN.md "Customization model".
     * @group Subclassing: rendering
     */
    renderTrigger() {
        this.replaceTriggerClearButtonElInDom();
        this.renderTriggerContent();
        this.renderTriggerArrow();
        this.syncTriggerButtonsToDom();
        this.renderTriggerScreenReaderText();
        this.triggerRenderCount++;
    }
    /**
     * Write the trigger's content slot (`triggerContentEl`), replacing whatever
     * was there. The single DOM-writing primitive behind every
     * `renderTriggerContent` path.
     * - Called by `renderTriggerContent`: the base default and the
     *   `LLSelectSingle` / `LLSelectMultiple` overrides.
     * - `string` -> set as `textContent` (plain text, NOT parsed as HTML). Used
     *   for the default placeholder / `itemToString` text / count text.
     * - `HTMLElement` -> inserted as-is via `replaceChildren`; caller owns the
     *   node. Used for whatever the `createTriggerContentElFn` setting returned.
     * - It writes what the screen shows only. Assistive technology reads the
     *   screen-reader text, which the library writes after the content render
     *   from {@link computeTriggerScreenReaderText}.
     * @group Subclassing: rendering
     */
    commitTriggerContentToDom(content) {
        if (typeof content === 'string') {
            this.triggerContentEl.textContent = content;
        }
        else {
            this.triggerContentEl.replaceChildren(content);
        }
    }
    /**
     * The screen-reader text: the value assistive technology reads for the
     * trigger, never shown.
     * - The library calls it after every trigger content render: every full
     *   trigger render (`renderTrigger`), plus every `setItems`. It writes the
     *   result as plain text into a visually hidden span inside the trigger.
     * - The span exists for screen readers. The trigger is a `combobox` while
     *   the filter is inactive, and WAI-ARIA 1.2 gives a combobox that is not
     *   a text field the value of its descendant content. The visible
     *   `triggerContentEl` carries `aria-hidden="true"`, so this text is the
     *   value.
     * - While the filter is active, the trigger is a `button`, named through
     *   `aria-labelledby`. The chain ends at the span, so the name carries
     *   this text.
     * - The usual override calls `super` and edits the returned string, or
     *   returns its own plain text.
     * - Base default: the placeholder. `LLSelectSingle` and `LLSelectMultiple`
     *   first try their `triggerContextToScreenReaderTextFn` setting, then
     *   read out the information the screen shows.
     * @group Subclassing: semantics
     */
    computeTriggerScreenReaderText() {
        return this.settings.placeholder;
    }
    /**
     * The `lang` of the screen-reader text, given the text
     * `computeTriggerScreenReaderText` returned: an item's code while the text
     * is exactly that item's text, else `null`, which writes none. Base: `null`.
     * @internal
     */
    computeTriggerScreenReaderTextLang(_text) {
        return null;
    }
    /**
     * Write the screen-reader text and its `lang`. The base runs it after
     * every trigger content render, so a `renderTriggerContent` override never
     * has to.
     */
    renderTriggerScreenReaderText() {
        const text = this.computeTriggerScreenReaderText();
        this.commitTriggerScreenReaderTextToDom(text, this.computeTriggerScreenReaderTextLang(text));
    }
    commitTriggerScreenReaderTextToDom(text, lang) {
        this.triggerScreenReaderTextEl.textContent = text;
        this.commitLangToDom(this.triggerScreenReaderTextEl, lang);
    }
    /**
     * Mirror the empty/filled state onto the trigger wrapper's `data-empty`
     * attribute (`"true"` when `isEmpty()`, else `"false"`). A CSS styling
     * hook, independent of the rendered content. Called by the subclass
     * `renderTriggerContent` overrides.
     * @group Subclassing: rendering
     */
    syncEmptyStateToDom() {
        this.triggerWrapperEl.setAttribute('data-empty', this.isEmpty() ? 'true' : 'false');
    }
    /**
     * Whether the control currently has no selection (drives `data-empty`).
     * Base default is always `true` (the base trigger only shows the
     * placeholder); `LLSelectSingle` / `LLSelectMultiple` override it.
     * @group Subclassing: semantics
     */
    isEmpty() {
        return true;
    }
    /**
     * Orchestrator: composes the `*ToDom` primitives to (re)build the trigger's
     * content slot from state; touches no DOM directly. Override in subclasses to
     * display the chosen value(s); this base default commits the placeholder and
     * the empty flag. Always write via `commitTriggerContentToDom` (content) and
     * `syncEmptyStateToDom` (the `data-empty` flag), never `triggerContentEl`
     * directly.
     * @group Subclassing: rendering
     */
    renderTriggerContent() {
        this.syncEmptyStateToDom();
        this.commitTriggerContentToDom(this.settings.placeholder);
    }
    /**
     * Orchestrator: composes the `*ToDom` / `*El` primitives to (re)build the
     * trigger's arrow slot from state; touches no DOM directly. Calls
     * `createTriggerArrowContentEl` with the current `isOpened` and commits whatever it returns
     * (including `null` -> no arrow for this state).
     */
    renderTriggerArrow() {
        this.commitTriggerArrowContentElToDom(this.createTriggerArrowContentEl({ isOpened: this.opened }));
    }
    /**
     * Trigger arrow element for the given open state.
     * - Default reads `createTriggerArrowContentElFn`; `null` (setting unset, or returned for
     *   a state) = no arrow for that state.
     * - Override only when extending; for one-off arrows pass the setting.
     *   Mirrors `createTriggerClearButtonEl` / `createPopupListItemContentEl`.
     * @group Subclassing: rendering
     */
    createTriggerArrowContentEl(state) {
        const fn = this.settings.createTriggerArrowContentElFn;
        return fn ? fn(state) : null;
    }
    /**
     * Write the trigger's arrow slot: clear it, then append `el` if non-null.
     * - `el = null`: clear only, leaving the slot empty (no arrow this state).
     * The sole mutator of the arrow slot; called by `renderTriggerArrow`.
     */
    commitTriggerArrowContentElToDom(el) {
        this.triggerArrowEl.replaceChildren();
        if (el) {
            this.triggerArrowEl.appendChild(el);
        }
    }
    /**
     * Orchestrator: composes `createPopupListItemEl` (build) + `computePopupSegments` +
     * `commitPopupSegmentsToDom` (write) to rebuild the popup list from
     * `getVisibleItems()`; touches no DOM directly. Called by `open()` and by
     * `setItems()` while open. Also clamps `focusedIndex` if the list shrank and
     * re-applies focus visuals.
     * - Extend it by wrapping: override, do your work before or after, then
     *   call `super.renderPopupList()`. The ui-select bridge frees its row
     *   scopes this way. Or override one of the methods it calls through `this`:
     *   `createPopupListItemEl`, `createPopupListChooseAllRowEl`,
     *   `createPopupListLeadingActionRowEl` /
     *   `createPopupListTrailingActionRowEl`, `itemToGroupKey`,
     *   `getVisibleItems`.
     * - Its other internals stay private on purpose. They re-establish the
     *   `itemEls[i] <-> getVisibleItems()[i]` alignment as one unit, so no
     *   subclass can leave keyboard nav or `aria-activedescendant` half-synced.
     * @group Subclassing: rendering
     */
    renderPopupList() {
        const list = this.getVisibleItems();
        const els = list.map((item, i) => this.createPopupListItemEl(item, i));
        this.itemEls = els;
        this.focusedEl = undefined;
        this.chooseAllRowEl = this.createPopupListChooseAllRowEl() ?? undefined;
        if (!this.chooseAllRowEl && this.focusedRow?.kind === 'choose-all') {
            this.focusedRow = null;
        }
        this.leadingActionRowEls = this.settings.popupListLeadingActionRows.map((row, i) => this.createPopupListLeadingActionRowEl(row, i));
        this.trailingActionRowEls = this.settings.popupListTrailingActionRows.map((row, i) => this.createPopupListTrailingActionRowEl(row, i));
        this.commitPopupSegmentsToDom(this.computePopupSegments(list, els));
        this.syncPopupListNoResultsToDom();
        this.positioner?.reposition();
        // Clamp focused index if the visible list shrank, then re-apply visuals.
        // The clamp seeks BACKWARD to an enabled row: landing focus on a
        // disabled one would break the disabled-skip contract (A11Y.md).
        if (this.focusedIndex >= list.length) {
            this.focusedIndex = list.length === 0 ? -1 : this.findNextEnabledIndex(list.length - 1, -1, list);
        }
        else if (this.focusedIndex >= 0 && this.isItemEffectivelyDisabled(list[this.focusedIndex])) {
            // Same contract when the row at the focused index BECAME disabled
            // (setItems swapped the item in place): seek backward - the option
            // above the first item is the choose-all row when present
            // (A11Y.md ring order) - else forward.
            const back = this.findNextEnabledIndex(this.focusedIndex, -1, list);
            if (back >= 0) {
                this.focusedIndex = back;
            }
            else if (!this.focusChooseAllRow()) {
                this.focusedIndex = this.findNextEnabledIndex(this.focusedIndex, 1, list);
            }
        }
        this.syncFocusedIndexToDom();
    }
    /**
     * Split the flat visible list into render segments: ungrouped item elements
     * and contiguous same-key groups. Pure computation - resolves keys via
     * `itemToGroupKey` (the overridable method; all-`null` keys = flat list) and key
     * equality via `groupKeyCompareFn`, touches no DOM. Group labels are NOT
     * added to `itemEls`, so `itemEls[i]`
     * stays aligned with `getVisibleItems()[i]` and keyboard nav skips labels for
     * free. `console.warn`s once per non-contiguous key reappearance (unsorted
     * data would otherwise emit a duplicate label for the same group) -
     * reachable with `gatherGroups: false`; the default gather feeds this an
     * already-contiguous list.
     */
    computePopupSegments(list, els) {
        const keyEq = this.settings.groupKeyCompareFn ?? defaultCompareFn;
        const segments = [];
        const closedKeys = [];
        let groupIndex = 0;
        let i = 0;
        while (i < list.length) {
            const key = this.itemToGroupKey(list[i]);
            if (key === null) {
                segments.push({ group: false, el: els[i] });
                i += 1;
                continue;
            }
            const groupItems = [list[i]];
            const groupEls = [els[i]];
            let j = i + 1;
            while (j < list.length) {
                const next = this.itemToGroupKey(list[j]);
                if (next === null || !keyEq(key, next)) {
                    break;
                }
                groupItems.push(list[j]);
                groupEls.push(els[j]);
                j += 1;
            }
            if (closedKeys.some(k => keyEq(k, key))) {
                console.warn('llselect: group key reappears non-contiguously; sort items by group to avoid a duplicate label.', key);
            }
            closedKeys.push(key);
            segments.push({ group: true, key, index: groupIndex, items: groupItems, els: groupEls });
            groupIndex += 1;
            i = j;
        }
        return segments;
    }
    /**
     * Replace every popup-list child with the leading rows, the rendered
     * segments and the trailing rows. A pinned block goes inside its sticky
     * wrapper, and the wrapper is left out while the block has no rows.
     */
    commitPopupSegmentsToDom(segments) {
        const children = segments.map(seg => seg.group ? this.createGroupEl(seg.key, seg.index, seg.items, seg.els) : seg.el);
        const leading = this.chooseAllRowEl ? [this.chooseAllRowEl, ...this.leadingActionRowEls] : this.leadingActionRowEls;
        const trailing = this.trailingActionRowEls;
        if (leading.length > 0 || trailing.length > 0) {
            this.commitPopupListRowPositionsToDom(segments, leading, trailing);
        }
        const leadingWrap = this.popupListPinnedLeadingRowsEl;
        const trailingWrap = this.popupListPinnedTrailingRowsEl;
        // A wrapper's inner edge line belongs only where items follow / precede
        // it; the themes read this attribute, so two adjacent blocks draw none.
        const hasItems = children.length > 0;
        if (leadingWrap) {
            leadingWrap.replaceChildren(...leading);
            leadingWrap.setAttribute('data-edge-to-items', String(hasItems));
            if (leading.length > 0) {
                children.unshift(leadingWrap);
            }
        }
        else {
            children.unshift(...leading);
        }
        if (trailingWrap) {
            trailingWrap.replaceChildren(...trailing);
            trailingWrap.setAttribute('data-edge-to-items', String(hasItems));
            if (trailing.length > 0) {
                children.push(trailingWrap);
            }
        }
        else {
            children.push(...trailing);
        }
        this.popupListEl.replaceChildren(...children);
    }
    /**
     * Write `aria-posinset` / `aria-setsize` while the list holds a non-item
     * row, so the position a screen reader announces ("3 of 16") does not count
     * the choose-all row or the action rows. The browser's own count would.
     * - An item row outside a group counts among the item rows outside groups.
     * - An item row inside a group gets nothing: the browser counts the rows of
     *   its group, which holds item rows only.
     * - A row of the leading block (the choose-all row, then the leading action
     *   rows) or of the trailing block counts within its block.
     * Without a non-item row nothing is written, so such lists pay nothing. An
     * in-place row rebuild copies the two attributes from the row it replaces
     * (`copyRowPosition`).
     */
    commitPopupListRowPositionsToDom(segments, leading, trailing) {
        const write = (els) => {
            const size = String(els.length);
            els.forEach((el, i) => {
                el.setAttribute('aria-posinset', String(i + 1));
                el.setAttribute('aria-setsize', size);
            });
        };
        const ungrouped = [];
        for (const seg of segments) {
            if (!seg.group) {
                ungrouped.push(seg.el);
            }
        }
        write(leading);
        write(ungrouped);
        write(trailing);
    }
    /**
     * Build the whole group container of the popup list: the label element followed by the group's item rows.
     * - The library calls it, once per group of the current render, on every
     *   list render. You never call it yourself.
     * - All four params come from the library. Forward them to `super` unchanged.
     * - `index` is the group's position among this render's groups, counted
     *   from 0. It only mints the group id. It is not an identity: it changes
     *   whenever the visible list changes.
     * - To change only the label's content, do not override this. Pass the
     *   `createGroupLabelContentElFn` setting instead.
     * - To change the element itself, override it, call `super.createGroupEl(...)`,
     *   and edit the returned element. Keep the `role` and `aria-label` the base set.
     * - Internals: the base sets the id, `role="group"` named by `groupKeyToString`
     *   (`aria-label`), `lang` from {@link groupKeyToLang} (none for `null`), an
     *   `aria-hidden` visible label element filled from
     *   {@link createGroupLabelContentEl} (else the plain label text), then the
     *   group's item elements; `aria-disabled` + `data-disabled` when the group
     *   is disabled.
     *
     * @param key - the group's key, supplied by the library
     * @param index - the group's position among this render's groups, supplied by the library
     * @param itemsInGroup - the group's items, supplied by the library (for counts / rich content)
     * @param itemEls - the group's already-built option elements, supplied by the library
     * @group Subclassing: rendering
     */
    createGroupEl(key, index, itemsInGroup, itemEls) {
        const text = this.groupKeyToString(key);
        const group = document.createElement('div');
        group.id = `${this.classIdMap.popupListId}-group${index}`;
        group.className = this.classIdMap.groupClass;
        group.setAttribute('role', 'group');
        group.setAttribute('aria-label', text);
        this.commitLangToDom(group, this.groupKeyToLang(key));
        if (this.isGroupDisabled(key)) {
            group.setAttribute('aria-disabled', 'true');
            group.setAttribute('data-disabled', 'true');
        }
        const labelEl = document.createElement('div');
        labelEl.className = this.classIdMap.groupLabelClass;
        labelEl.setAttribute('aria-hidden', 'true');
        const content = this.createGroupLabelContentEl(key, itemsInGroup);
        if (content === null) {
            labelEl.textContent = text;
        }
        else {
            labelEl.appendChild(content);
        }
        group.append(labelEl, ...itemEls);
        return group;
    }
    /**
     * Group label -> its visible content element (icon / count badge / rich
     * markup). Mirrors `createPopupListItemContentEl`.
     * - Default reads `createGroupLabelContentElFn`, else `null` so `createGroupEl`
     *   uses plain text from `groupKeyToString`.
     * - The group's accessible name stays `groupKeyToString` (container `aria-label`);
     *   this fills only the visible, `aria-hidden` label content.
     * - Override only when extending; for one-off rich labels pass the setting.
     * @group Subclassing: rendering
     */
    createGroupLabelContentEl(key, itemsInGroup) {
        const fn = this.settings.createGroupLabelContentElFn;
        return fn ? fn(key, itemsInGroup) : null;
    }
    /**
     * Re-render a single item's element in place instead of rebuilding the
     * whole popup list. The DOM work is O(1) regardless of list size, so
     * flipping one selection in a 10k-item list does not recreate 10k nodes
     * (the lookup to find the item is O(n), but that is a cheap comparison
     * loop next to DOM mutation). No-op if the popup is closed or the item is
     * not in the current list. Used by multi-select toggle.
     * @group Subclassing: rendering
     */
    replacePopupListItemElInDom(item) {
        if (!this.opened) {
            return;
        }
        const list = this.getVisibleItems();
        const compareFn = this.settings.compareFn;
        const index = list.findIndex(i => compareFn(i, item));
        if (index < 0) {
            return;
        }
        const oldEl = this.itemEls[index];
        if (oldEl === undefined) {
            return;
        }
        const newEl = this.createPopupListItemEl(list[index], index);
        copyRowPosition(oldEl, newEl);
        oldEl.replaceWith(newEl);
        this.itemEls[index] = newEl;
        // Preserve focus visuals if the replaced element was the focused one.
        if (this.focusedEl === oldEl) {
            newEl.classList.add(this.classIdMap.popupListRowFocusedClass);
            this.comboboxEl.setAttribute('aria-activedescendant', newEl.id);
            this.focusedEl = newEl;
        }
    }
    /**
     * Build the whole DOM element for one item row of the popup list.
     * - The library calls it, once per row of `getVisibleItems()`, on every
     *   list render. You never call it yourself.
     * - Both params come from the library. Forward them to `super` unchanged.
     * - `item` is the row's item.
     * - `index` is the row's position in `getVisibleItems()`, counted from 0.
     *   That is the list as rendered: grouped, filtered, minus hidden chosen
     *   rows. It is NOT the position in `items`.
     * - `index` is not an identity. It changes whenever the visible list
     *   changes. Item identity is `compareFn`. Never store it.
     * - To change only what a row shows, do not override this. Pass the
     *   `createPopupListItemContentElFn` setting instead.
     * - To change the element itself, override it, call
     *   `super.createPopupListItemEl(item, index)`, and edit the returned element: add a
     *   class, a `title`, a wrapper. Demo sections 9.1, 13.1 and 13.2 do this.
     * - Keep the `id` and `role` the base set. Do not put focusable controls
     *   inside the row. The row itself is the control.
     * - The element is rebuilt on every render. Do not keep a reference to it.
     * - After this returns, the library adds `aria-posinset` and `aria-setsize`
     *   to a row outside a group while the list holds a non-item row
     *   (`docs/llm/A11Y.md` "Action rows").
     * - Internals: the base sets `id` (`<listbox id>-item<index>`, the target of
     *   `aria-activedescendant`), `role="option"`, the visible content from
     *   {@link createPopupListItemContentEl} (else `textContent` from {@link itemToString}),
     *   `aria-label` = `itemToString` when the content is custom, `lang` from
     *   {@link itemToLang} when it returns one, `aria-disabled`
     *   plus the disabled class when {@link isItemEffectivelyDisabled}, and a
     *   click handler that focuses the row by `index`, then runs `onPopupListItemActivated`.
     *
     * @param item - the row's item, supplied by the library
     * @param index - the row's position in `getVisibleItems()`, supplied by the library
     * @group Subclassing: rendering
     */
    createPopupListItemEl(item, index) {
        const el = document.createElement('div');
        // Ids hang off the listbox id: options belong to the listbox, not the trigger.
        el.id = `${this.classIdMap.popupListId}-item${index}`;
        el.className = this.classIdMap.popupListRowClass;
        el.setAttribute('role', 'option');
        const content = this.createPopupListItemContentEl(item);
        if (content === null) {
            el.textContent = this.itemToString(item);
        }
        else {
            // Custom content fills the visuals only. The accessible name + match
            // text always come from itemToString, so pin aria-label to it: stays
            // consistent with the plain-text branch (textContent === itemToString)
            // and the caller never touches aria-* themselves.
            el.setAttribute('aria-label', this.itemToString(item));
            el.appendChild(content);
        }
        this.commitLangToDom(el, this.itemToLang(item));
        // No `title` attribute by default: items wrap (themes default), so the
        // full text is already visible and a tooltip is redundant. Adding
        // `title` would also fight third-party tooltip libraries (Tippy etc.).
        // Users who opt into ellipsis-on-items pick their own tooltip mechanism.
        if (this.isItemEffectivelyDisabled(item)) {
            // `aria-disabled` (never native `disabled`) keeps the item perceivable and
            // hoverable for a "why disabled" tooltip. No click handler -> not
            // selectable; keyboard nav skips it too.
            el.setAttribute('aria-disabled', 'true');
            el.classList.add(this.classIdMap.popupListRowDisabledClass);
        }
        else {
            el.addEventListener('click', () => {
                // Move focus to the clicked item before activating it. Without this,
                // multi mode (which keeps the popup open) leaves the focused styling
                // on the previous keyboard-focused item while a different one was
                // just clicked.
                const stamp = this.captureStateStamp();
                this.setFocusedIndex(index);
                // The move reports the active item; a listener that closed, rebuilt
                // or changed the select component leaves nothing for this click to activate.
                if (this.stateMovedSince(stamp)) {
                    return;
                }
                this.withUserChangeSource(() => this.onPopupListItemActivated(item));
            });
        }
        return el;
    }
    /**
     * Map an item to its display string. The library calls this everywhere it
     * needs an item's text: list rows, the single trigger text, default filter.
     * - Default reads the `itemToStringFn` setting, else `String(item)`.
     * - Configure via `itemToStringFn` (no subclass needed).
     * - Override only when extending (a new kind of select component); your
     *   override replaces the default. For HTML content in a row, pass the
     *   `createPopupListItemContentElFn` setting.
     * @group Subclassing: semantics
     */
    itemToString(item) {
        const fn = this.settings.itemToStringFn;
        return fn ? fn(item) : String(item);
    }
    /**
     * Map an item to the value of its `lang` attribute, or `null` for none.
     * - Default reads the `itemToLangFn` setting; `null` while it is unset.
     * - The library writes the result where it shows that item's text; the
     *   `itemToLangFn` docstring lists the places.
     * - Configure via `itemToLangFn` (no subclass needed); override only when
     *   extending.
     * @group Subclassing: semantics
     */
    itemToLang(item) {
        const fn = this.settings.itemToLangFn;
        return fn ? fn(item) : null;
    }
    /**
     * Set or remove an element's `lang` attribute. `null` removes it; an empty
     * string sets `lang=""`, HTML's "language unknown".
     * @internal
     */
    commitLangToDom(el, lang) {
        if (lang === null) {
            el.removeAttribute('lang');
        }
        else {
            el.setAttribute('lang', lang);
        }
    }
    /**
     * Item -> the visible content of its popup list row (icon + text etc.).
     * - Default reads `createPopupListItemContentElFn`, else `null` so `createPopupListItemEl` uses
     *   the plain-text default from `itemToString`.
     * - Override only when extending; for one-off rich content pass the setting.
     * @group Subclassing: rendering
     */
    createPopupListItemContentEl(item) {
        const fn = this.settings.createPopupListItemContentElFn;
        return fn ? fn(item) : null;
    }
    /**
     * Whether `item` is effectively disabled - by `itemDisabledFn`, or because
     * its group is disabled (`groupDisabledFn`). Group-disabled layers on top,
     * so every item-disabled behavior (no selection, keyboard skip, aria)
     * covers grouped items with no extra code. False when neither applies.
     * The whole-control disabled state (`isDisabled()`) is a separate layer,
     * not part of this answer.
     * @group Subclassing: semantics
     */
    isItemEffectivelyDisabled(item) {
        const itemDisabledFn = this.settings.itemDisabledFn;
        if (itemDisabledFn && itemDisabledFn(item)) {
            return true;
        }
        const key = this.itemToGroupKey(item);
        return key !== null && this.isGroupDisabled(key);
    }
    /**
     * Map an item to its group key, or `null` when it belongs to no group.
     * The authoritative method: rendering, the `gatherGroups` gather, and the
     * disabled layer all resolve keys through this method, so an override
     * drives them all - returning keys turns grouping on even with the setting
     * unset (all-`null` keys = flat list). An override reading external state
     * must call `rerender()` after that state changes (same contract as
     * mutating item objects).
     * - Default reads `itemToGroupKeyFn`, else `null` (grouping off).
     * - Override only when extending; configure via the setting.
     * @group Subclassing: semantics
     */
    itemToGroupKey(item) {
        const fn = this.settings.itemToGroupKeyFn;
        return fn ? fn(item) : null;
    }
    /**
     * Map a group key to its label display text.
     * - Default reads `groupKeyToStringFn`, else `String(key)`.
     * @group Subclassing: semantics
     */
    groupKeyToString(key) {
        const fn = this.settings.groupKeyToStringFn;
        return fn ? fn(key) : String(key);
    }
    /**
     * Map a group key to the value of the group's `lang` attribute, or `null`
     * for none.
     * - Default reads the `groupKeyToLangFn` setting; `null` while it is unset.
     * - `createGroupEl` writes the result on the group container.
     * - Configure via `groupKeyToLangFn` (no subclass needed); override only
     *   when extending. Mirrors `itemToLang`.
     * @group Subclassing: semantics
     */
    groupKeyToLang(key) {
        const fn = this.settings.groupKeyToLangFn;
        return fn ? fn(key) : null;
    }
    /**
     * Whether the whole group `key` is disabled per `groupDisabledFn` (false when unset).
     * @group Subclassing: semantics
     */
    isGroupDisabled(key) {
        const fn = this.settings.groupDisabledFn;
        return fn ? fn(key) : false;
    }
    /**
     * First enabled index scanning from `start` (inclusive) by `step` (+1 / -1).
     * Returns -1 if no enabled item lies in that direction. Used to skip disabled
     * items during keyboard nav and initial focus.
     * @group Subclassing: focus
     */
    findNextEnabledIndex(start, step, list) {
        for (let i = start; i >= 0 && i < list.length; i += step) {
            if (!this.isItemEffectivelyDisabled(list[i])) {
                return i;
            }
        }
        return -1;
    }
    /** Number of entries in the arrow-key ring for the current render. */
    ringLength() {
        return (this.chooseAllRowEl ? 1 : 0) + this.leadingActionRowEls.length + this.getVisibleItems().length + this.trailingActionRowEls.length;
    }
    /** Ring position of the active option, or -1 when nothing holds it. */
    ringPosition() {
        const lead = this.chooseAllRowEl ? 1 : 0;
        const r = this.focusedRow;
        if (r !== null) {
            if (r.kind === 'choose-all') {
                return 0;
            }
            if (r.kind === 'leading') {
                return lead + r.index;
            }
            return lead + this.leadingActionRowEls.length + this.getVisibleItems().length + r.index;
        }
        return this.focusedIndex >= 0 ? lead + this.leadingActionRowEls.length + this.focusedIndex : -1;
    }
    /** The ring entry at a position (caller keeps `0 <= position < ringLength()`). */
    ringEntryAt(position) {
        let p = position;
        if (this.chooseAllRowEl) {
            if (p === 0) {
                return { kind: 'choose-all' };
            }
            p -= 1;
        }
        const nLeading = this.leadingActionRowEls.length;
        if (p < nLeading) {
            return { kind: 'leading', index: p };
        }
        p -= nLeading;
        const nItems = this.getVisibleItems().length;
        if (p < nItems) {
            return { kind: 'item', index: p };
        }
        return { kind: 'trailing', index: p - nItems };
    }
    isRingPositionEnabled(position) {
        const e = this.ringEntryAt(position);
        switch (e.kind) {
            case 'choose-all': return true;
            case 'item': return !this.isItemEffectivelyDisabled(this.getVisibleItems()[e.index]);
            case 'leading': return this.leadingActionRowEls[e.index]?.getAttribute('aria-disabled') !== 'true';
            case 'trailing': return this.trailingActionRowEls[e.index]?.getAttribute('aria-disabled') !== 'true';
        }
    }
    /** First enabled ring position from `start` walking in `direction`, or -1. */
    findNextEnabledRingPosition(start, direction, total) {
        for (let p = start; p >= 0 && p < total; p += direction) {
            if (this.isRingPositionEnabled(p)) {
                return p;
            }
        }
        return -1;
    }
    /** Ring twin of `findEnabledIndexForAction`: search in the travel direction, Page keys fall back the other way. */
    findEnabledRingPositionForKeyboardAction(target, action, total) {
        const forward = action === LLSelectKeyboardAction.Next
            || action === LLSelectKeyboardAction.GotoFirst
            || action === LLSelectKeyboardAction.PageDown;
        const primary = this.findNextEnabledRingPosition(target, forward ? 1 : -1, total);
        if (primary >= 0) {
            return primary;
        }
        if (action === LLSelectKeyboardAction.PageDown) {
            return this.findNextEnabledRingPosition(target, -1, total);
        }
        if (action === LLSelectKeyboardAction.PageUp) {
            return this.findNextEnabledRingPosition(target, 1, total);
        }
        return -1;
    }
    /** Move the active option to a ring position through the entry's own focus method. */
    focusRingPosition(position) {
        const e = this.ringEntryAt(position);
        switch (e.kind) {
            case 'choose-all':
                this.focusChooseAllRow();
                return;
            case 'item':
                this.setFocusedIndex(e.index);
                return;
            default: this.focusActionRow(e.kind, e.index);
        }
    }
    /** Move the active option onto an action row (mirrors `focusChooseAllRow`). */
    focusActionRow(kind, index) {
        const r = this.focusedRow;
        if (r !== null && r.kind === kind && r.index === index) {
            return;
        }
        this.focusedRow = { kind, index };
        this.focusedIndex = -1;
        this.syncFocusedIndexToDom();
    }
    /** The element of the action row holding the active option, if one does. */
    focusedActionRowEl() {
        const r = this.focusedRow;
        if (r === null || r.kind === 'choose-all') {
            return undefined;
        }
        return (r.kind === 'leading' ? this.leadingActionRowEls : this.trailingActionRowEls)[r.index];
    }
    /** The descriptor of the action row holding the active option, if one does. */
    focusedActionRow() {
        const r = this.focusedRow;
        if (r === null || r.kind === 'choose-all') {
            return undefined;
        }
        return (r.kind === 'leading' ? this.settings.popupListLeadingActionRows : this.settings.popupListTrailingActionRows)[r.index];
    }
    /** Enter / click on an action row: re-check disabled, then run the hook as a user change. */
    activatePopupListActionRow(row) {
        if (this.isPopupListActionRowDisabled(row)) {
            return;
        }
        this.withUserChangeSource(() => this.onPopupListActionRowActivated(row));
    }
    /**
     * Called **after** the user's Enter on the active item row, Space on it while
     * the filter is inactive, or click on the row, as the library's response to
     * that input. Default no-op; subclasses implement their selection behaviour (single mode picks
     * and closes, multiple mode toggles and keeps the popup open).
     *
     * > No **before** counterpart: there is no `onPopupListItemActivating`.
     * @group Subclassing: reactions
     */
    onPopupListItemActivated(_item) { }
    /**
     * Build the whole DOM element for one leading action row (above the items).
     * - The library calls it, once per entry of `popupListLeadingActionRows`,
     *   on every list render and after every chosen change. You never call it.
     * - Both params come from the library. Forward them to `super` unchanged.
     *   `row` is the entry; `index` is its position in that array, counted from
     *   0, used to mint the id. It is not an identity.
     * - To change only what the row shows, do not override this: give the entry
     *   a `createContentElFn`.
     * - To change the element itself, override it, call
     *   `super.createPopupListLeadingActionRowEl(row, index)`, and edit the
     *   returned element. Keep the `id` and `role`; put no focusable control
     *   inside.
     * - After this returns, the library adds `aria-posinset` and
     *   `aria-setsize`, since a list with an action row always gets them.
     * - Internals: a `div` with `role="option"`, the id
     *   `<listbox id>-action-row-leading<index>`, `popupListRowClass` plus
     *   `popupListActionRowClass`, the visible content from
     *   {@link createPopupListActionRowContentEl} (else `textContent` from
     *   `textFn`), `aria-label` = `textFn()` when the content is custom, and
     *   either `aria-disabled` plus the disabled class
     *   ({@link isPopupListActionRowDisabled}) or a click handler that focuses
     *   the row, then runs {@link onPopupListActionRowActivated}.
     *   `aria-selected="false"`: every option needs the attribute, and a
     *   command is never selected.
     * @param row - the entry, supplied by the library
     * @param index - the entry's position in `popupListLeadingActionRows`, supplied by the library
     * @group Subclassing: rendering
     */
    createPopupListLeadingActionRowEl(row, index) {
        return this.createPopupListActionRowEl(row, 'leading', index);
    }
    /**
     * Build the whole DOM element for one trailing action row (below the items).
     * - The library calls it, once per entry of `popupListTrailingActionRows`,
     *   on every list render and after every chosen change. You never call it.
     * - Both params come from the library. Forward them to `super` unchanged.
     *   `row` is the entry; `index` is its position in that array, counted from
     *   0, used to mint the id. It is not an identity.
     * - To change only what the row shows, do not override this: give the entry
     *   a `createContentElFn`.
     * - To change the element itself, override it, call
     *   `super.createPopupListTrailingActionRowEl(row, index)`, and edit the
     *   returned element. Keep the `id` and `role`; put no focusable control
     *   inside.
     * - After this returns, the library adds `aria-posinset` and
     *   `aria-setsize`, since a list with an action row always gets them.
     * - Internals: identical to {@link createPopupListLeadingActionRowEl}
     *   except the id, `<listbox id>-action-row-trailing<index>`.
     * @param row - the entry, supplied by the library
     * @param index - the entry's position in `popupListTrailingActionRows`, supplied by the library
     * @group Subclassing: rendering
     */
    createPopupListTrailingActionRowEl(row, index) {
        return this.createPopupListActionRowEl(row, 'trailing', index);
    }
    /** Shared body of the two action-row builders. */
    createPopupListActionRowEl(row, position, index) {
        const el = document.createElement('div');
        el.id = `${this.classIdMap.popupListId}-action-row-${position}${index}`;
        el.className = `${this.classIdMap.popupListRowClass} ${this.classIdMap.popupListActionRowClass}`;
        el.setAttribute('role', 'option');
        // Required on every option (WAI-ARIA 1.2); a command is never selected.
        el.setAttribute('aria-selected', 'false');
        const textFn = row.textFn;
        const text = textFn();
        const content = this.createPopupListActionRowContentEl(row);
        if (content === null) {
            el.textContent = text;
        }
        else {
            // Custom content fills the visuals only; the accessible name stays textFn.
            el.setAttribute('aria-label', text);
            el.appendChild(content);
        }
        if (this.isPopupListActionRowDisabled(row)) {
            el.setAttribute('aria-disabled', 'true');
            el.classList.add(this.classIdMap.popupListRowDisabledClass);
        }
        else {
            el.addEventListener('click', () => {
                // Focus-then-activate, mirroring the item click wiring, guard included.
                const stamp = this.captureStateStamp();
                this.focusActionRow(position, index);
                if (this.stateMovedSince(stamp)) {
                    return;
                }
                this.activatePopupListActionRow(row);
            });
        }
        return el;
    }
    /**
     * An action row's visible content element.
     * - The library calls it from the row builders, once per row render. You
     *   never call it. `row` comes from the library.
     * - Default reads the entry's `createContentElFn`; `null` (unset, or
     *   returned) = plain text from `textFn`.
     * - Override only when extending; for one-off content give the entry a
     *   `createContentElFn`.
     * @group Subclassing: rendering
     */
    createPopupListActionRowContentEl(row) {
        const fn = row.createContentElFn;
        return fn ? fn() : null;
    }
    /**
     * Whether an action row is disabled right now.
     * - The library calls it from the row builders (once per row render) and
     *   again at activation. You never call it. `row` comes from the library.
     * - Default reads the entry's `disabledFn`; `null` / omitted = never disabled.
     * @group Subclassing: semantics
     */
    isPopupListActionRowDisabled(row) {
        const fn = row.disabledFn;
        return fn ? fn() : false;
    }
    /**
     * Subclass hook: runs **after** Enter on the active action row, Space on it
     * while the filter is inactive, or a click on it, as the library's response
     * to that input.
     *
     * > No **before** counterpart: there is no `onPopupListActionRowActivating`.
     *
     * - The library calls it on Enter, on Space while the filter is inactive,
     *   and on click, **after** the disabled re-check, as a user change. You never
     *   call it. `row` comes from the library: the activated entry.
     * - Default calls the entry's `onActivate`. The library changes nothing
     *   else: choosing and closing are the entry's job.
     * - Override to react before the entry's `onActivate`: do your work, then
     *   call `super.onPopupListActionRowActivated(row)`. To react after it, call
     *   `super` first, then do your work. Without that call the entry's
     *   `onActivate` never runs.
     * @group Subclassing: reactions
     */
    onPopupListActionRowActivated(row) {
        const onActivate = row.onActivate;
        onActivate();
    }
    /**
     * Rebuild every rendered action row in place, so `textFn` / `disabledFn`
     * reflect the current state; the row holding the active option keeps it.
     * - The library calls it after every chosen change, right after `onChange`
     *   fired (a row's text may read what the handler wrote). Subclasses may
     *   call it after a state change of their own.
     * - No-op while closed, or when both row arrays are empty - instances
     *   without rows pay nothing.
     * - O(rows) DOM work; the item rows are untouched.
     * @group Subclassing: rendering
     */
    replacePopupListActionRowElsInDom() {
        if (!this.opened) {
            return;
        }
        const leading = this.settings.popupListLeadingActionRows;
        const trailing = this.settings.popupListTrailingActionRows;
        if (leading.length === 0 && trailing.length === 0) {
            return;
        }
        this.leadingActionRowEls = this.replaceActionRowElsInDom(this.leadingActionRowEls, leading, (row, i) => this.createPopupListLeadingActionRowEl(row, i));
        this.trailingActionRowEls = this.replaceActionRowElsInDom(this.trailingActionRowEls, trailing, (row, i) => this.createPopupListTrailingActionRowEl(row, i));
    }
    replaceActionRowElsInDom(olds, rows, build) {
        return olds.map((old, i) => {
            const next = build(rows[i], i);
            copyRowPosition(old, next);
            old.replaceWith(next);
            if (this.focusedEl === old) {
                next.classList.add(this.classIdMap.popupListRowFocusedClass);
                this.comboboxEl.setAttribute('aria-activedescendant', next.id);
                this.focusedEl = next;
            }
            return next;
        });
    }
    /**
     * Optional non-item `role="option"` row placed first, at the TOP of the listbox:
     * inside the arrow-key ring (ArrowUp from the first item reaches it, Home
     * lands on it, up-actions clamp there) but never inside `itemEls`, so the
     * `itemEls[i] <-> getVisibleItems()[i]` alignment is untouched. Rebuilt on
     * every `renderPopupList`, and in place by `replaceChooseAllRowElInDom`.
     * Base default: `null` = no choose-all row.
     * `LLSelectMultiple` builds its choose-all row here (`chooseAllRow` setting).
     * @group Subclassing: rendering
     */
    createPopupListChooseAllRowEl() { return null; }
    /**
     * Dispatch the before-change event of one user change and report whether
     * the change may proceed. The variants call it from their gate with a
     * closure that runs `onChosenChanging` and the `onBeforeChange` setting.
     * - `preventDefault()` counts only inside `dispatch`; the event is sealed
     *   afterwards.
     * @internal
     */
    dispatchBeforeChange(facts, dispatch) {
        let prevented = false;
        let open = true;
        const preventDefault = () => { if (open) {
            prevented = true;
        } };
        const event = 'item' in facts
            ? { source: 'user', reason: facts.reason, item: facts.item, get defaultPrevented() { return prevented; }, preventDefault }
            : { source: 'user', reason: facts.reason, get defaultPrevented() { return prevented; }, preventDefault };
        try {
            dispatch(event);
        }
        finally {
            open = false;
        }
        return !prevented;
    }
    /**
     * Run `fn` with chosen-state changes attributed to the user.
     * - The library wraps exactly its pointer / keyboard entry points with it:
     *   option activation, the tag remove button, the clear button, the
     *   choose-all row, and an action row's `onActivate`.
     * - A change outside such a call reports `'api'`.
     * - The attribution is consumed by the first chosen-state change inside
     *   `fn`, before `onChosenChanged` runs.
     * - A second change inside the same `fn` reports `'api'`.
     * @group Subclassing: reactions
     */
    withUserChangeSource(fn) {
        const previous = this.changeSource;
        this.changeSource = 'user';
        try {
            return fn();
        }
        finally {
            this.changeSource = previous;
        }
    }
    /**
     * Subclass hook: runs **after** Enter on the active choose-all row, or Space
     * on it while the filter is inactive, as the library's response to that
     * input. Default no-op. `LLSelectMultiple`, which supplies the row, also
     * wires its click handler to this.
     *
     * > No **before** counterpart: there is no `onChooseAllRowActivating`.
     * @group Subclassing: reactions
     */
    onChooseAllRowActivated() { }
    /**
     * Decide which row is active when the popup opens.
     * - The library calls it inside `open()`, once per open, after the rows
     *   are built. You never call it.
     * - To pick another row, such as the row of the chosen item or of the
     *   last-used item, override it and set the row with `setFocusedIndex` or
     *   `focusChooseAllRow`.
     * - To fall back to the default, call `super.focusInitial()`, but only when
     *   the override set no row.
     * - The active row is the `role="option"` row that `aria-activedescendant`
     *   names on the `role="combobox"` element: the trigger, or the filter
     *   input while the filter is active.
     * - "Focus" in the names `focusInitial`, `setFocusedIndex` and
     *   `focusChooseAllRow` means the active row, not DOM focus.
     * - DOM focus never moves to the active row. While the filter is active,
     *   the open moves DOM focus to the filter input.
     * - `open()` clears the active row before the call, so the popup opens
     *   with no active row unless this method sets one.
     * - Visible items are the items in `getVisibleItems()`, the items that
     *   have a row in the list.
     * - The default makes the first enabled visible item the active row,
     *   replacing any row set before it runs.
     * - The default does nothing when no visible item is enabled.
     * @group Subclassing: focus
     */
    focusInitial() {
        const first = this.findNextEnabledIndex(0, 1, this.getVisibleItems());
        if (first >= 0) {
            this.setFocusedIndex(first);
        }
    }
    /**
     * Move keyboard focus to the item at `index`. The value is clamped to
     * `[-1, getVisibleItems().length - 1]`; pass `-1` to clear focus. Updates the focused
     * class, `aria-activedescendant`, and scrolls the item into view. No-op
     * if the clamped value equals the current focused index while no
     * choose-all row or action row is active. "Keyboard focus" here means the
     * active row; this method never moves DOM focus.
     * @group Subclassing: focus
     */
    setFocusedIndex(index) {
        const max = this.getVisibleItems().length - 1;
        const clamped = Math.max(-1, Math.min(max, index));
        if (clamped === this.focusedIndex && this.focusedRow === null) {
            return;
        }
        this.focusedRow = null;
        this.focusedIndex = clamped;
        this.syncFocusedIndexToDom();
    }
    /**
     * Move keyboard focus onto the choose-all row. Returns whether the row is now
     * focused (`false` = none is rendered, nothing changed). The item focus is
     * cleared (`focusedIndex` becomes -1). "Keyboard focus" here means the
     * active row; this method never moves DOM focus. Protected so a subclass can wire its
     * choose-all row's click to focus-then-activate (mirroring how item clicks
     * call `setFocusedIndex` before `onPopupListItemActivated`) and use it in
     * `focusInitial` (the choose-all row is the listbox's FIRST option).
     * @group Subclassing: focus
     */
    focusChooseAllRow() {
        if (!this.chooseAllRowEl) {
            return false;
        }
        if (this.focusedRow?.kind === 'choose-all') {
            return true;
        }
        this.focusedRow = { kind: 'choose-all' };
        this.focusedIndex = -1;
        this.syncFocusedIndexToDom();
        return true;
    }
    /**
     * Rebuild the choose-all row in place (tri-state / text refresh) without
     * touching the item elements - O(1) DOM work, mirroring
     * `replacePopupListItemElInDom`. Falls back to a full `renderPopupList`
     * when the row becomes inapplicable (builder returns `null`). No-op while
     * closed or when no choose-all row is rendered.
     * @group Subclassing: rendering
     */
    replaceChooseAllRowElInDom() {
        if (!this.opened || !this.chooseAllRowEl) {
            return;
        }
        const next = this.createPopupListChooseAllRowEl();
        if (next === null) {
            this.renderPopupList();
            return;
        }
        const old = this.chooseAllRowEl;
        copyRowPosition(old, next);
        old.replaceWith(next);
        this.chooseAllRowEl = next;
        if (this.focusedEl === old) {
            next.classList.add(this.classIdMap.popupListRowFocusedClass);
            this.comboboxEl.setAttribute('aria-activedescendant', next.id);
            this.focusedEl = next;
        }
    }
    /**
     * Make the DOM reflect the active row, `focusedRow`, else `focusedIndex`.
     * - With an active row, it moves the focused class onto the row's element,
     *   points `aria-activedescendant` at it, and scrolls it into view.
     * - With no active row, it clears the class and the attribute.
     * - Then it reports the active item (`reportActiveItem`).
     * - It reads the row elements that the select component currently stores.
     * - Called after every active-row change (`setFocusedIndex`,
     *   `focusChooseAllRow`, `focusActionRow`).
     * - Called after the list is rebuilt (`renderPopupList`, whose clamp
     *   assigns `focusedIndex` directly).
     */
    syncFocusedIndexToDom() {
        if (this.focusedEl) {
            this.focusedEl.classList.remove(this.classIdMap.popupListRowFocusedClass);
            this.focusedEl = undefined;
        }
        const el = this.resolveActiveRowEl();
        if (el === undefined) {
            this.comboboxEl.removeAttribute('aria-activedescendant');
        }
        else {
            el.classList.add(this.classIdMap.popupListRowFocusedClass);
            this.comboboxEl.setAttribute('aria-activedescendant', el.id);
            this.focusedEl = el;
            this.scrollRingEntryIntoView(el);
        }
        this.reportActiveItem();
    }
    /**
     * The element of the active row, or `undefined` when no rendered row is
     * active. An action row whose element is gone drops `focusedRow` to `null`
     * and falls through to the item at `focusedIndex`.
     */
    resolveActiveRowEl() {
        if (this.focusedRow !== null && this.focusedRow.kind !== 'choose-all') {
            const rowEl = this.focusedActionRowEl();
            if (rowEl !== undefined) {
                return rowEl;
            }
            this.focusedRow = null;
        }
        if (this.focusedRow?.kind === 'choose-all' && this.chooseAllRowEl) {
            return this.chooseAllRowEl;
        }
        const i = this.focusedIndex;
        return i >= 0 && i < this.itemEls.length ? this.itemEls[i] : undefined;
    }
    /**
     * Fire `onActiveItemChange` when the active item differs from the last
     * report. The tail of `syncFocusedIndexToDom`, which every active-row move
     * ends in, plus `close()`, which resets the row by assignment. Items are
     * compared with `compareFn`, never by index or element, so an in-place row
     * rebuild stays silent. The report is stored before the listener runs, so a
     * listener that closes or re-renders the select component re-enters with the right
     * baseline.
     */
    reportActiveItem() {
        if (this.activeItemReportSuspendDepth > 0) {
            return;
        }
        const next = this.resolveActiveItem();
        const last = this.reportedActiveItem;
        if (!next.active && !last.active) {
            return;
        }
        if (next.active && last.active && this.settings.compareFn(next.item, last.item)) {
            return;
        }
        this.reportedActiveItem = next;
        const onActiveItemChange = this.settings.onActiveItemChange;
        onActiveItemChange?.(next.active ? next.item : undefined);
    }
    /** The item of the active row; none while closed, on a non-item row, or with no row. */
    resolveActiveItem() {
        if (!this.opened || this.focusedRow !== null) {
            return { active: false };
        }
        const list = this.getVisibleItems();
        const i = this.focusedIndex;
        return i >= 0 && i < list.length ? { active: true, item: list[i] } : { active: false };
    }
    /**
     * Snapshot the window scroll position and return a function that restores
     * it. Opening the popup must never move the page, but Firefox auto-scrolls
     * the active option of a multiselectable listbox into view at the document
     * level when the popup is shown - even though the popup is `position: fixed`.
     * The returned restore runs synchronously and once more on the next frame,
     * since that accessibility scroll can land after the current layout flush.
     * No-op when nothing actually scrolled, so it never fights real user
     * scrolling (and stays silent under jsdom, which has no `window.scrollTo`).
     * Restores with `behavior: 'instant'`: the two-arg `scrollTo` obeys the
     * page's CSS `scroll-behavior`, so under `scroll-behavior: smooth` the
     * correction would render as a visible glide instead of a revert.
     * - The restore does nothing once the select component is destroyed, the
     *   one that waits for the next frame included: whoever destroyed it has
     *   taken over the page, a route change for one, and may have set a scroll
     *   position of its own.
     */
    captureWindowScroll() {
        const { scrollX, scrollY } = window;
        const restore = () => {
            if (this.destroyed) {
                return;
            }
            if (window.scrollX !== scrollX || window.scrollY !== scrollY) {
                window.scrollTo({ left: scrollX, top: scrollY, behavior: 'instant' });
            }
        };
        return () => {
            restore();
            if (typeof requestAnimationFrame === 'function') {
                requestAnimationFrame(restore);
            }
        };
    }
    /**
     * The element a pointer event actually hit. `ev.target` retargets to the shadow
     * host when llselect is hosted inside an app's shadow root, so an inside click
     * would read as outside and close the popup; `composedPath()[0]` pierces the
     * boundary. With no shadow tree (llselect uses none itself) this equals `ev.target`.
     * - Limitation: a CLOSED host shadow root truncates `composedPath()` at the root,
     *   so `[0]` is only the host and an inside click still reads as outside. A
     *   document-level listener cannot see into a closed root; hosting in an OPEN
     *   shadow root avoids it.
     */
    eventTargetNode(ev) {
        return ev.composedPath?.()?.[0] ?? ev.target;
    }
    attachOutsideClick() {
        const mode = this.settings.behaviorOfOutsideClick;
        if (mode === 'pass-through') {
            // mousedown fires before mouseup/click - feels snappier; we do not
            // preventDefault, so the outside click still triggers its own action.
            this.outsideHandler = (ev) => {
                const t = this.eventTargetNode(ev);
                if (t instanceof Node && !this.rootEl.contains(t)) {
                    this.closeWithReason('outside');
                }
            };
            document.addEventListener('mousedown', this.outsideHandler);
        }
        else {
            // 'block' cannot rely on the click capture alone, because of an
            // event-ordering race with the focusout-close path:
            //   mousedown outside -> browser shifts focus to the clicked target ->
            //   focusout fires on trigger -> focusOutHandler closes the popup ->
            //   detachOutsideClick removes the click capture below -> click then
            //   reaches the target and fires its own handler (regression).
            // The mousedown capture below preventDefaults the focus shift on
            // outside mousedowns, so no focusout fires and the click capture stays
            // attached long enough to swallow the click.
            // A handler of the page can still move focus during the press, such as
            // a mousedown handler that calls focus(); the focusout then closes the
            // popup before the click. So each outside press also arms a swallow
            // that outlives the close (armOutsidePressClickSwallow).
            this.blockPointerDownHandler = (ev) => {
                const t = this.eventTargetNode(ev);
                if (t instanceof Node && !this.rootEl.contains(t)) {
                    const press = ev;
                    this.armOutsidePressClickSwallow(press.pointerType || 'mouse', press.clientX, press.clientY);
                }
            };
            document.addEventListener('pointerdown', this.blockPointerDownHandler, true);
            this.blockMouseDownHandler = (ev) => {
                const t = this.eventTargetNode(ev);
                if (t instanceof Node && !this.rootEl.contains(t)) {
                    ev.preventDefault();
                    // A mouse press arms again here, which also covers a browser that
                    // sends no pointerdown. The mousedown of a tap leaves the tap's
                    // swallow and its longer wait, wherever the browser sends that
                    // mousedown among the tap's events.
                    if (this.outsidePressPointerType === null || this.outsidePressPointerType === 'mouse') {
                        const press = ev;
                        this.armOutsidePressClickSwallow('mouse', press.clientX, press.clientY);
                    }
                }
            };
            document.addEventListener('mousedown', this.blockMouseDownHandler, true);
            // capture phase so we run before the target's own listeners; swallow
            // the click so the underlying button/link/etc. does not fire.
            this.outsideHandler = (ev) => {
                const t = this.eventTargetNode(ev);
                if (t instanceof Node && !this.rootEl.contains(t)) {
                    ev.stopPropagation();
                    ev.preventDefault();
                    this.closeWithReason('outside');
                }
            };
            document.addEventListener('click', this.outsideHandler, true);
        }
    }
    detachOutsideClick() {
        if (this.outsideHandler) {
            if (this.settings.behaviorOfOutsideClick === 'pass-through') {
                document.removeEventListener('mousedown', this.outsideHandler);
            }
            else {
                document.removeEventListener('click', this.outsideHandler, true);
            }
            this.outsideHandler = undefined;
        }
        if (this.blockMouseDownHandler) {
            document.removeEventListener('mousedown', this.blockMouseDownHandler, true);
            this.blockMouseDownHandler = undefined;
        }
        if (this.blockPointerDownHandler) {
            document.removeEventListener('pointerdown', this.blockPointerDownHandler, true);
            this.blockPointerDownHandler = undefined;
        }
        // The swallow of a press under way stays armed: the close may come from
        // that press, before its click.
    }
    /**
     * Swallows the click of an outside press under `'block'`, even when the
     * popup closed during that press.
     * - Called by the `pointerdown` and `mousedown` capture listeners of
     *   `'block'` for a press outside the select component, with the pointer
     *   type of the press and the place where it went down.
     * - The `mousedown` listener arms again as a mouse press, unless a press
     *   that is not a mouse press armed the swallow.
     * - While armed, the swallow also prevents the default of an outside
     *   `mousedown`, so the browser moves no focus, even after the popup
     *   closed at the `pointerdown`.
     * - Only the press's own click counts. The swallow lets every other click
     *   through and stays armed:
     *   - a pointer made the press's click, so its `detail` is not `0`, while
     *     a click from the keyboard or from `click()` has a `detail` of `0`;
     *   - after a press that is not a mouse press, such as a tap, the click
     *     lands within `TAP_CLICK_RADIUS` of the place where the press went
     *     down.
     * - The click of the press ends the swallow.
     * - After a mouse press, the task after its `pointerup` or `mouseup` ends
     *   the swallow too, since a browser dispatches the click of a mouse press
     *   in the same task as its release.
     * - After a tap, `CLICK_WAIT_MS` after its `pointerup` ends the swallow,
     *   since a browser can hold a tap's click back by about 300 ms.
     * - A `pointercancel`, the `pointerdown` of a new press, a new arm and
     *   `destroy()` end the swallow as well, so a press without a click leaves
     *   nothing armed for a later click.
     */
    armOutsidePressClickSwallow(pointerType, x, y) {
        this.disarmOutsidePressClickSwallow?.();
        const mouse = pointerType === 'mouse';
        let timer;
        const keepFocus = (ev) => {
            const t = this.eventTargetNode(ev);
            if (t instanceof Node && !this.rootEl.contains(t)) {
                ev.preventDefault();
            }
        };
        const isPressClick = (click) => {
            if (click.detail === 0) {
                return false;
            }
            return mouse || Math.hypot(click.clientX - x, click.clientY - y) <= TAP_CLICK_RADIUS;
        };
        const swallow = (ev) => {
            if (!isPressClick(ev)) {
                return;
            }
            const t = this.eventTargetNode(ev);
            if (t instanceof Node && !this.rootEl.contains(t)) {
                ev.stopPropagation();
                ev.preventDefault();
            }
            disarm();
        };
        const released = () => {
            if (timer === undefined) {
                timer = setTimeout(disarm, mouse ? 0 : CLICK_WAIT_MS);
            }
        };
        const disarm = () => {
            if (timer !== undefined) {
                clearTimeout(timer);
            }
            document.removeEventListener('click', swallow, true);
            document.removeEventListener('pointerup', released, true);
            document.removeEventListener('mouseup', released, true);
            document.removeEventListener('pointercancel', disarm, true);
            document.removeEventListener('pointerdown', disarm, true);
            document.removeEventListener('mousedown', keepFocus, true);
            if (this.disarmOutsidePressClickSwallow === disarm) {
                this.disarmOutsidePressClickSwallow = null;
                this.outsidePressPointerType = null;
            }
        };
        document.addEventListener('mousedown', keepFocus, true);
        document.addEventListener('click', swallow, true);
        document.addEventListener('pointerup', released, true);
        document.addEventListener('mouseup', released, true);
        document.addEventListener('pointercancel', disarm, true);
        // Added during this press, while or after its pointerdown runs, so only
        // the pointerdown of a later press reaches it.
        document.addEventListener('pointerdown', disarm, true);
        this.disarmOutsidePressClickSwallow = disarm;
        this.outsidePressPointerType = pointerType;
    }
    /**
     * The whole-life `focusin` / `focusout` pair on `rootEl`. Both bubble from
     * every descendant, so one listener each sees focus entering or leaving any
     * part of the select component. `relatedTarget` - the element focus comes from or goes
     * to - tells an outside move from an inside one; `null` counts as outside
     * (a click on a non-focusable area, focus from nowhere). The inside test is
     * `rootEl.contains`, not "the trigger", so the filter input and slot
     * controls keep the popup open while they hold focus.
     * - `focusout` is always attached: it closes an open popup when focus leaves
     *   (A11Y.md "Focus"), then fires `onBlur`, in that order.
     * - `focusin` is attached only when `onFocus` is set.
     * - `destroy()` detaches both before its own `close()` and
     *   `replaceChildren()`, so a parting event cannot reach a listener.
     */
    attachFocusListeners() {
        this.focusOutHandler = (ev) => {
            if (this.isInsideRoot(ev.relatedTarget)) {
                return;
            }
            if (this.opened) {
                this.closeWithReason('blur');
            }
            const onBlur = this.settings.onBlur;
            onBlur?.();
        };
        this.rootEl.addEventListener('focusout', this.focusOutHandler);
        if (this.settings.onFocus === null) {
            return;
        }
        this.focusInHandler = (ev) => {
            if (this.isInsideRoot(ev.relatedTarget)) {
                return;
            }
            const onFocus = this.settings.onFocus;
            onFocus?.();
        };
        this.rootEl.addEventListener('focusin', this.focusInHandler);
    }
    detachFocusListeners() {
        if (this.focusOutHandler) {
            this.rootEl.removeEventListener('focusout', this.focusOutHandler);
            this.focusOutHandler = undefined;
        }
        if (this.focusInHandler) {
            this.rootEl.removeEventListener('focusin', this.focusInHandler);
            this.focusInHandler = undefined;
        }
    }
    /** Whether `target` is a node inside `rootEl`; `null` counts as outside. */
    isInsideRoot(target) {
        return target instanceof Node && this.rootEl.contains(target);
    }
    /**
     * Esc pressed while DOM focus sits on app content inside a popup slot
     * (`popupHeaderEl` / `popupFooterEl`): close, and `close()` returns focus to
     * the trigger. Escape only; ignores IME composition, an event the app
     * already handled (`defaultPrevented` - a text field that owns Esc), and
     * the filter input's own events (its `handleKeydown` ran first and prevented
     * the default). `preventDefault` so an enclosing modal `<dialog>` does not
     * also close on the same key.
     */
    handleSlotKeydown(ev) {
        if (ev.key !== 'Escape' || isImeKeydown(ev) || this.composing || ev.defaultPrevented) {
            return;
        }
        const t = this.eventTargetNode(ev);
        if (t instanceof Node && this.filterInputEl.contains(t)) {
            return;
        }
        ev.preventDefault();
        this.closeWithReason('escape');
    }
    handleKeydown(ev) {
        // Leave the keys to the IME while composing.
        if (isImeKeydown(ev) || this.composing) {
            return;
        }
        if (this.disabled) {
            return;
        }
        const inText = ev.currentTarget === this.filterInputEl;
        if (!inText && this.handleTypeaheadKeydown(ev)) {
            return;
        }
        const action = getActionFromKey(ev, this.opened, inText);
        if (action === undefined) {
            return;
        }
        ev.preventDefault();
        // Any action key ends the typed prefix (Enter/Space activate, Escape
        // closes, arrows move on).
        this.typeaheadBuffer = '';
        switch (action) {
            case LLSelectKeyboardAction.Open:
                this.openWithReason('keyboard');
                return;
            case LLSelectKeyboardAction.Close:
                // Esc two-stage while the filter is active: clear the filter first; only
                // close when the filter is already empty. Alt+ArrowUp maps to Close
                // too but always closes. Closing returns focus to the trigger.
                if (ev.key === 'Escape' && this.filterActive && this.query !== '') {
                    this.filterInputEl.value = '';
                    this.handleSearchInputEvent();
                    return;
                }
                this.closeWithReason('escape');
                return;
            case LLSelectKeyboardAction.Select: {
                if (this.focusedRow?.kind === 'choose-all') {
                    this.withUserChangeSource(() => this.onChooseAllRowActivated());
                    return;
                }
                if (this.focusedRow !== null) {
                    const row = this.focusedActionRow();
                    if (row !== undefined) {
                        this.activatePopupListActionRow(row);
                    }
                    return;
                }
                const list = this.getVisibleItems();
                if (this.focusedIndex >= 0 && this.focusedIndex < list.length) {
                    const item = list[this.focusedIndex];
                    // Defensive: nav never lands on a disabled item, but guard anyway.
                    if (!this.isItemEffectivelyDisabled(item)) {
                        this.withUserChangeSource(() => this.onPopupListItemActivated(item));
                    }
                }
                return;
            }
            case LLSelectKeyboardAction.Next:
            case LLSelectKeyboardAction.Previous:
            case LLSelectKeyboardAction.GotoFirst:
            case LLSelectKeyboardAction.GotoLast:
            case LLSelectKeyboardAction.PageDown:
            case LLSelectKeyboardAction.PageUp: {
                // One walk over the whole ring: choose-all row, leading action rows,
                // items, trailing action rows. Disabled entries are skipped
                // in the travel direction (Page keys fall back the other way).
                const total = this.ringLength();
                if (total === 0) {
                    return;
                }
                const target = getUpdatedIndex(this.ringPosition(), total - 1, action);
                const found = this.findEnabledRingPositionForKeyboardAction(target, action, total);
                if (found >= 0) {
                    this.focusRingPosition(found);
                }
                return;
            }
        }
    }
    /**
     * Native-`<select>`-style prefix typeahead for a printable-character
     * keydown on the trigger.
     * - Returns `true` when the event was consumed.
     * - Runs only while the filter is inactive. With the popup open the filter
     *   input owns typing; while closed, a would-be-filterable open cycle
     *   leaves the keys alone (the `filterable` predicate is evaluated fresh -
     *   the cached `filterActive` can be stale between opens).
     * - Space never joins the buffer; it stays the activate/open key (A11Y.md).
     * - While closed: opens the popup first, then searches relative to
     *   {@link computeTypeaheadClosedStartIndex} - NOT to the convenience focus
     *   `focusInitial` parked, which would skip the first match.
     * - Typing itself never changes the value and never fires `onChange`;
     *   activation stays Enter / Space / click.
     * - Match rule, cycling, and wrap: {@link findTypeaheadIndex}. No match
     *   leaves the active option and the buffer as they are.
     */
    handleTypeaheadKeydown(ev) {
        // Printable = exactly one code point ('Dead' / 'Process' fail, astral
        // pairs pass). Meta and Ctrl-only chords are commands.
        if (ev.key === ' ' || [...ev.key].length !== 1 || ev.metaKey || (ev.ctrlKey && !ev.altKey)) {
            return false;
        }
        // Alt-carrying chords (AltGraph, macOS Option) PRODUCE characters and the
        // produced character arrives as ev.key ("@", "a-ring", ...). A chord
        // still delivering a bare ASCII letter / digit produced nothing - that is
        // a shortcut (Windows Alt menus, accesskey, VoiceOver's Ctrl+Option), so
        // it passes through.
        if (ev.altKey && /^[a-zA-Z0-9]$/.test(ev.key)) {
            return false;
        }
        if (this.opened ? this.filterActive : this.computeFilterActive()) {
            return false;
        }
        ev.preventDefault();
        const now = Date.now();
        this.typeaheadBuffer = getUpdatedTypeaheadBuffer(this.typeaheadBuffer, ev.key, now - this.typeaheadLastTime);
        this.typeaheadLastTime = now;
        const openedByThisKey = !this.opened;
        if (openedByThisKey) {
            this.openWithReason('typeahead');
            // open() can refuse (hidden trigger): nothing to move focus in, and the
            // buffer must not survive into a later successful open.
            if (!this.opened) {
                this.typeaheadBuffer = '';
                return true;
            }
        }
        const list = this.getVisibleItems();
        const current = openedByThisKey
            ? this.computeTypeaheadClosedStartIndex(list)
            : (this.focusedRow !== null ? -1 : this.focusedIndex);
        const found = findTypeaheadIndex(this.typeaheadBuffer, list.length, current, (i) => this.isItemEffectivelyDisabled(list[i]) ? undefined : this.itemToString(list[i]));
        if (found >= 0) {
            this.setFocusedIndex(found);
        }
        return true;
    }
    /**
     * The option the closed-state typeahead treats as current, as an index into
     * `list`, when the typed character is the keystroke that opens the popup.
     * - The search starts AFTER this option: the opening keystroke is always a
     *   one-character buffer, because `close()` and a refused `open()` both
     *   empty the buffer.
     * - Default `-1`: no current option, so the first match from the top wins.
     * - The focus `focusInitial` parks on open is a convenience, not a
     *   selection - it must not shift this search.
     * - Single mode overrides this with the chosen item's index, so a typed
     *   initial cycles past the current selection like a native `<select>`.
     * - Search internals: `findTypeaheadIndex` in `keyboard.ts`.
     * @group Subclassing: focus
     */
    computeTypeaheadClosedStartIndex(_list) {
        return -1;
    }
    createTriggerWrapperEl() {
        const el = document.createElement('div');
        el.className = this.classIdMap.triggerWrapperClass;
        el.setAttribute('data-state', 'closed');
        el.setAttribute('data-disabled', 'false');
        return el;
    }
    createTriggerEl() {
        const el = document.createElement('div');
        el.id = this.classIdMap.triggerId;
        el.className = this.classIdMap.triggerClass;
        // Filter active: trigger is a button that opens a popup containing a
        // combobox+listbox. Inactive: trigger is itself the combobox.
        el.setAttribute('role', this.filterActive ? 'button' : 'combobox');
        el.setAttribute('tabindex', '0');
        // aria-controls and aria-haspopup follow the filter mode:
        // syncFilterModeToDom, which the constructor runs after building the
        // trigger.
        el.setAttribute('aria-expanded', 'false');
        const screenReaderTextEl = createVisuallyHiddenSpan();
        screenReaderTextEl.id = this.classIdMap.triggerScreenReaderTextId;
        screenReaderTextEl.className = this.classIdMap.triggerScreenReaderTextClass;
        const contentEl = document.createElement('span');
        contentEl.id = this.classIdMap.triggerContentId;
        contentEl.className = this.classIdMap.triggerContentClass;
        contentEl.setAttribute('aria-hidden', 'true');
        el.append(screenReaderTextEl, contentEl);
        return { el, screenReaderTextEl, contentEl };
    }
    /**
     * The trigger buttons strip, empty: the first trigger render builds the
     * clear button (`replaceTriggerClearButtonElInDom`), and each trigger
     * content render of tags mode builds the chips (`commitTagsElToDom`).
     */
    createTriggerButtonsEl() {
        const el = document.createElement('div');
        el.className = this.classIdMap.triggerButtonsClass;
        // Tags mode only: a lone clear button needs no toolbar. Static, since
        // triggerDisplay is frozen; a role swap at runtime confuses assistive
        // technology.
        if (this.isTriggerDisplayTags()) {
            el.setAttribute('role', 'toolbar');
        }
        el.hidden = true;
        el.addEventListener('keydown', (ev) => this.handleTriggerButtonsKeydown(ev));
        // The focused button becomes the Tab stop. While the popup is open no
        // button is a Tab stop, so focus arrives here only by script or a screen
        // reader's cursor, from inside the root or outside it. The root's
        // focusout guard closes the popup in neither case: a move from inside
        // passes its inside test and returns early, and a move from outside fires
        // no focusout on the root. The popup belongs to the combobox, so close it
        // here. close() re-syncs the stop.
        el.addEventListener('focusin', () => {
            if (this.opened) {
                this.closeWithReason('trigger-buttons');
            }
            else {
                this.syncTriggerButtonsToDom();
            }
        });
        return el;
    }
    /** The strip's `aria-label`, while it is a toolbar. Pack text: the constructor and `setUiTranslationPack` run it. */
    syncTriggerButtonsNameToDom() {
        const el = this.triggerButtonsEl;
        if (el === null || !this.isTriggerDisplayTags()) {
            return;
        }
        el.setAttribute('aria-label', this.settings.uiTranslationPack.triggerButtonsAriaLabel);
    }
    /**
     * Whether the trigger shows one chip per chosen item: the multiple select
     * component's `triggerDisplay: 'tags'`.
     * - The base constructor calls it to decide whether the trigger buttons
     *   strip exists and whether it is a toolbar.
     * - Base default `false`; `LLSelectMultiple` reads its setting.
     * @internal
     */
    isTriggerDisplayTags() {
        return false;
    }
    /** The buttons of the trigger buttons strip, in DOM order: the chips' remove buttons, then the clear button. */
    getTriggerButtonEls() {
        return this.triggerButtonsEl === null ? [] : Array.from(this.triggerButtonsEl.querySelectorAll('button'));
    }
    /**
     * Bring the trigger buttons strip in line with the state, after each change
     * of its buttons, of the chosen state, of the disabled state, and on open
     * and close.
     * - It carries `hidden` while nothing is chosen or it is empty.
     *   Before hiding it, focus inside it moves to the trigger: hiding a
     *   focused element drops focus to `<body>`.
     * - One button is the Tab stop: the one holding focus, else the previous
     *   stop while it is still in the strip, else the first that is not
     *   `aria-disabled`, else the first.
     * - None is while the strip is hidden, while the select component is
     *   disabled, or while the popup is open. The strip precedes the popup in
     *   DOM order, so a stop there would take Tab from the open popup's host
     *   before the slot controls, and focus entering the strip closes the
     *   popup (A11Y.md "Trigger buttons strip").
     */
    syncTriggerButtonsToDom() {
        const strip = this.triggerButtonsEl;
        if (strip === null) {
            return;
        }
        const buttons = this.getTriggerButtonEls();
        const hide = this.isEmpty() || strip.childElementCount === 0;
        if (hide && this.isFocused(strip)) {
            this.triggerEl.focus({ preventScroll: true });
        }
        strip.hidden = hide;
        const focused = this.focusedElementIn(strip);
        const previous = this.triggerButtonsTabStopEl;
        const stop = buttons.find((b) => focused !== null && b.contains(focused))
            ?? buttons.find((b) => b === previous)
            ?? buttons.find((b) => b.getAttribute('aria-disabled') !== 'true')
            ?? buttons[0];
        this.triggerButtonsTabStopEl = stop ?? null;
        const tabbable = !hide && !this.disabled && !this.opened;
        for (const b of buttons) {
            b.tabIndex = tabbable && b === stop ? 0 : -1;
        }
    }
    /**
     * Left / Right Arrow, Home and End inside the trigger buttons strip: move
     * focus to the previous, next, first or last button and make it the Tab
     * stop. Clamps at both ends. Left and Right swap in right-to-left text.
     * Keys with Alt, Ctrl or Meta stay with the browser.
     */
    handleTriggerButtonsKeydown(ev) {
        if (isImeKeydown(ev) || ev.altKey || ev.ctrlKey || ev.metaKey || this.disabled) {
            return;
        }
        const buttons = this.getTriggerButtonEls();
        const t = this.eventTargetNode(ev);
        const at = buttons.findIndex((b) => t instanceof Node && b.contains(t));
        if (at < 0) {
            return;
        }
        const rtl = window.getComputedStyle(this.triggerButtonsEl).direction === 'rtl';
        let next;
        switch (ev.key) {
            case 'ArrowLeft':
                next = rtl ? at + 1 : at - 1;
                break;
            case 'ArrowRight':
                next = rtl ? at - 1 : at + 1;
                break;
            case 'Home':
                next = 0;
                break;
            case 'End':
                next = buttons.length - 1;
                break;
            default: return;
        }
        ev.preventDefault();
        const target = buttons[Math.max(0, Math.min(buttons.length - 1, next))];
        this.triggerButtonsTabStopEl = target;
        for (const b of buttons) {
            b.tabIndex = b === target ? 0 : -1;
        }
        target.focus({ preventScroll: true });
    }
    /**
     * Focus the trigger for a mousedown in the trigger wrapper outside the
     * trigger: the wrapper is not focusable, so the press would move focus to
     * `<body>`, and the focusout guard would close an open popup.
     * - A press on the trigger itself takes focus natively.
     * - A mousedown already prevented is left alone. The strip's buttons
     *   prevent theirs to keep focus where it is.
     */
    handleTriggerWrapperMousedown(ev) {
        const t = this.eventTargetNode(ev);
        if (ev.defaultPrevented || !(t instanceof Node) || this.triggerEl.contains(t)) {
            return;
        }
        ev.preventDefault();
        this.triggerEl.focus({ preventScroll: true });
    }
    /**
     * Put the tag-list container into the trigger buttons strip, before the
     * clear button, in place of the previous one; `null` removes it.
     * - Called by `LLSelectMultiple`'s `renderTriggerContent` on every trigger
     *   content render.
     * - If a remove button of the previous container held focus, the remove
     *   button at the same position in the new one gets it, else the last one,
     *   else the trigger. So removing a chip by keyboard focuses the next
     *   chip's button, and removing the last chip focuses the trigger.
     * - If focus sat elsewhere in the previous container, the trigger gets it.
     * - Focus moves before the previous container leaves the DOM: removing a
     *   focused element first drops focus to `<body>`, which the focusout
     *   guard reads as focus leaving the select component.
     * @internal
     */
    commitTagsElToDom(el) {
        const strip = this.triggerButtonsEl;
        if (strip === null) {
            return;
        }
        const old = this.tagsEl;
        const focused = old === null ? null : this.focusedElementIn(old);
        if (el !== null) {
            if (old !== null) {
                old.before(el);
            }
            else {
                strip.prepend(el);
            }
        }
        this.tagsEl = el;
        if (old !== null && focused !== null) {
            const at = Array.from(old.querySelectorAll('button')).findIndex((b) => b.contains(focused));
            const buttons = el === null ? [] : Array.from(el.querySelectorAll('button'));
            const target = (at < 0 ? undefined : buttons[Math.min(at, buttons.length - 1)]) ?? this.triggerEl;
            target.focus({ preventScroll: true });
        }
        old?.remove();
    }
    /**
     * Build the clear (x) button, the last button of the trigger buttons strip
     * (`clearable`).
     * - The library owns the button, its click (stops propagation so it never
     *   toggles the popup, then `clearSelection`; a no-op while the control is
     *   disabled) and its `aria-label` (text from
     *   `uiTranslationPack.triggerClearButtonAriaLabel`).
     * - A click while focus is in the strip moves focus to the trigger first,
     *   so a clear by keyboard leaves focus on the trigger.
     * - The strip owns its `tabindex`: one button of the strip is the Tab stop.
     * - An override returns a `button` element: the strip's Tab stop and arrow
     *   keys reach `button` elements only.
     * - `createTriggerClearButtonContentElFn` optionally fills the icon; else the
     *   theme's CSS glyph draws it.
     * - The library hides the strip, and with it the button, while nothing is
     *   chosen.
     * - It runs on every trigger render (`renderTrigger`).
     * - The first run builds the button.
     * - For `LLSelectSingle` / `LLSelectMultiple` and their subclasses, that
     *   first run is the variant constructor's render, right after `super()`,
     *   so it happens before a FURTHER subclass's field initializers.
     * - A direct `LLSelectBase` subclass gets the button on its first trigger
     *   render (its own `renderTrigger()` call, or `rerender()` /
     *   `setPlaceholder`); until then the trigger is unrendered and there is no
     *   button.
     * - Every later run (a value change, `setPlaceholder`,
     *   `setUiTranslationPack`, `rerender()`) swaps the button in place, unless
     *   this method returns the previous element - then it stays in place.
     * - The base implementation returns a fresh element each run, so, like the
     *   arrow, nothing put on it from outside survives a render; customize it
     *   here.
     * - An override that returns the same element every time owns everything
     *   the rebuild would otherwise refresh on it, including its `aria-label`
     *   after `setUiTranslationPack`.
     * - An override that reads subclass fields calls `rerender()` at the end of
     *   its constructor, like every other trigger method.
     * @group Subclassing: rendering
     */
    createTriggerClearButtonEl() {
        const btn = document.createElement('button');
        btn.type = 'button';
        btn.className = this.classIdMap.triggerClearButtonClass;
        btn.tabIndex = -1;
        btn.setAttribute('aria-label', this.settings.uiTranslationPack.triggerClearButtonAriaLabel);
        const icon = this.createTriggerClearButtonContentEl();
        if (icon !== null) {
            btn.appendChild(icon);
        }
        // Keep DOM focus where it is, as the chip's remove button does: a pointer
        // press leaves focus on the trigger or the filter input. A mousedown would
        // focus the button, and focus entering the trigger buttons strip closes an
        // open popup.
        btn.addEventListener('mousedown', (ev) => { ev.preventDefault(); });
        btn.addEventListener('click', (ev) => {
            ev.stopPropagation();
            // Disabled blocks every USER path to a value change (programmatic
            // setters still work), and the clear button is
            // reachable while closed - open() and keydown are already guarded.
            if (this.isDisabled()) {
                return;
            }
            if (this.triggerButtonsEl !== null && this.isFocused(this.triggerButtonsEl)) {
                this.triggerEl.focus({ preventScroll: true });
            }
            else {
                this.focusTriggerIfUnfocused();
            }
            // The focus may run onFocus; a listener that disabled or destroyed the
            // control leaves nothing for this click to clear. One that opened the
            // popup or loaded items does not change what a clear means.
            if (this.destroyed || this.isDisabled()) {
                return;
            }
            this.withUserChangeSource(() => this.clearSelection());
        });
        return btn;
    }
    /**
     * The element holding DOM focus if that is `el` or a descendant, else `null`.
     * - Read from `el`'s own root: inside a shadow root `document.activeElement`
     *   is the shadow HOST, so the answer must come from the `ShadowRoot`'s
     *   `activeElement` (the `Document`'s otherwise).
     * - The result can sit inside an open shadow root under `el`, so
     *   `el.contains()` may reject it; use `containsComposed` for that check.
     * - A CLOSED shadow root is opaque, so its host is returned.
     */
    focusedElementIn(el) {
        const active = el.getRootNode().activeElement ?? null;
        if (active === null || !el.contains(active)) {
            return null;
        }
        // Descend through open shadow roots to the element that really holds
        // focus: `activeElement` stops at a shadow host.
        let deepest = active;
        while (deepest.shadowRoot !== null && deepest.shadowRoot.activeElement !== null) {
            deepest = deepest.shadowRoot.activeElement;
        }
        return deepest;
    }
    /** Whether `node` is `el` or inside it, walking up through open shadow hosts. */
    containsComposed(el, node) {
        let cursor = node;
        while (cursor !== null) {
            if (el.contains(cursor)) {
                return true;
            }
            // Only a ShadowRoot (a DocumentFragment, nodeType 11) has a host worth
            // climbing to. A detached element is its own root, and an `<a>` /
            // `<area>` root carries a STRING `host` (its URL host) - never follow
            // that. nodeType, not instanceof, so a foreign-realm root still counts.
            const root = cursor.getRootNode();
            cursor = root.nodeType === 11 ? root.host ?? null : null;
        }
        return false;
    }
    /** Whether DOM focus is on `el` or inside it (see `focusedElementIn`). */
    isFocused(el) {
        return this.focusedElementIn(el) !== null;
    }
    /**
     * Give the trigger DOM focus when no element inside the select component holds it.
     * - For the click of the clear button and of a chip's remove button: their
     *   `mousedown` keeps focus where it is, so a click on an unfocused select component
     *   would otherwise leave it unfocused, with no `onFocus` and no later
     *   `onBlur` for a form's touched state. A native control takes focus on a
     *   click inside it.
     * - While the trigger, the filter input or a slot control holds focus,
     *   nothing moves.
     * @internal
     */
    focusTriggerIfUnfocused() {
        if (this.isFocused(this.rootEl)) {
            return;
        }
        this.triggerEl.focus({ preventScroll: true });
    }
    /**
     * Take the stamp a row click compares after its active-row move.
     * - The three row clicks call it: the item row, the choose-all row, the
     *   action row.
     * - They call it right before `setFocusedIndex`, `focusChooseAllRow` or
     *   `focusActionRow`, whose report runs the app's `onActiveItemChange`.
     * - Returns the transition generation and the change revision as they
     *   stand.
     * - {@link stateMovedSince} reads them back.
     * @internal
     */
    captureStateStamp() {
        return { generation: this.transitionGeneration, revision: this.changeRevision };
    }
    /**
     * Returns whether a listener moved the select component since `stamp` was taken.
     * - The three row clicks call it after their active-row move.
     * - `stamp` is what {@link captureStateStamp} returned before that move.
     * - True after an open, a close, a `rerender()`, a `destroy()`, a
     *   `setItems()` or a chosen-state change.
     * - The click then activates nothing: the row it meant belongs to a popup
     *   state that is gone.
     * - The other user paths re-check what they need instead:
     *   - the filter keystroke: the popup is open and its query still stands;
     *   - the clear button: the control is enabled and not destroyed;
     *   - the chip remove button checks all of the following:
     *     - the control is enabled and not destroyed;
     *     - the item is still chosen, read from the chosen entry as it stands
     *       now;
     *     - that entry is enabled.
     * @internal
     */
    stateMovedSince(stamp) {
        return stamp.generation !== this.transitionGeneration || stamp.revision !== this.changeRevision;
    }
    /**
     * Build the clear button on the first trigger render, and swap it for a fresh
     * one on every later render, always through `createTriggerClearButtonEl` (the
     * overridable builder) - so `rerender()` repairs an override that reads
     * subclass fields. Keeps DOM focus on the new button when the old one held it.
     * No-op without `clearable`.
     * The order of the steps is load-bearing:
     * 1. Read which node holds focus, if it is the old button or inside it.
     * 2. If one does, park focus on the old button itself. A content fn that
     *    hands back the same icon element each time reparents that icon into
     *    the new button, and the reparenting must not move the focused node.
     * 3. Build the new button.
     * 4. Insert it.
     * 5. If step 1 found focus, move focus to the new button - or, if that
     *    element cannot take focus, to the trigger.
     * 6. Only then remove the old one.
     * Why this order:
     * - Removing the old button first drops DOM focus to `<body>` in every
     *   engine.
     * - Where the engine also fires `focusout` on that removal, its
     *   `relatedTarget` is `null`. The open popup's focus-out guard reads that
     *   as focus leaving the select component.
     * - Moving focus first makes the new button the `relatedTarget`, inside the
     *   root.
     * A builder override that returns the SAME element every time is allowed:
     * the element is kept in place, and focus goes back to the node step 1
     * found, because nothing was rebuilt - unless the override detached that
     * node or moved it out of the button, in which case focus stays on the
     * button.
     */
    replaceTriggerClearButtonElInDom() {
        if (!this.settings.clearable) {
            return;
        }
        const old = this.triggerClearButtonEl;
        const focused = old === null ? null : this.focusedElementIn(old);
        if (old !== null && focused !== null) {
            old.focus({ preventScroll: true });
        }
        const next = this.createTriggerClearButtonEl();
        this.triggerClearButtonEl = next;
        if (old === null) {
            // clearable guarantees the strip.
            this.triggerButtonsEl.append(next);
            return;
        }
        if (next === old) {
            // Nothing was rebuilt: hand focus back to the node that held it - but
            // only while it is still inside the button. The override may have
            // detached it or moved it elsewhere; then focus stays on the button.
            const holder = focused;
            if (holder !== null && holder !== old && this.containsComposed(old, holder) && typeof holder.focus === 'function') {
                holder.focus({ preventScroll: true });
            }
            return;
        }
        old.before(next);
        if (focused !== null) {
            next.focus({ preventScroll: true });
            // An override may return a non-focusable element; then the old button
            // still holds focus and removing it would drop focus to <body>. Keep it
            // in the select component instead.
            if (this.focusedElementIn(next) === null) {
                this.triggerEl.focus({ preventScroll: true });
            }
        }
        old.remove();
    }
    /**
     * Clear button's visible content (its x icon).
     * - Default reads `createTriggerClearButtonContentElFn`; `null` (setting
     *   unset, or returned) = no icon - the theme's CSS glyph draws the x.
     * - Override only when extending; for one-off icons pass the setting.
     * @group Subclassing: rendering
     */
    createTriggerClearButtonContentEl() {
        const fn = this.settings.createTriggerClearButtonContentElFn;
        return fn ? fn() : null;
    }
    /**
     * Empty the selection (invoked by the clear button). Base is a no-op; single
     * clears to `undefined`, multiple to `[]`. Goes through the normal setters, so
     * `onChange` fires with the empty value. The wipe is total - chosen disabled
     * items are cleared too (native `<select>` parity; `unchooseAll` is the
     * enabled-only bulk op).
     * @group Subclassing: semantics
     */
    clearSelection() { }
    /**
     * The filter input lives inside the popup, above the listbox. Always built
     * (`hidden` when `filterable: false`) so a future runtime toggle is a CSS
     * flip rather than a DOM rebuild. See `docs/llm/DESIGN.md`.
     */
    createFilterInputEl() {
        const el = document.createElement('input');
        el.type = 'text';
        el.id = this.classIdMap.filterInputId;
        el.className = this.classIdMap.filterInputClass;
        el.setAttribute('role', 'combobox');
        el.setAttribute('aria-controls', this.classIdMap.popupListId);
        el.setAttribute('aria-expanded', 'false');
        el.setAttribute('aria-autocomplete', 'list');
        el.setAttribute('autocomplete', 'off');
        el.setAttribute('autocapitalize', 'off');
        el.setAttribute('spellcheck', 'false');
        // Accessible name (aria-label / aria-labelledby) is owned by
        // syncFieldNameToDom, which runs right after construction.
        if (this.settings.uiTranslationPack.filterInputPlaceholder !== null) {
            el.placeholder = this.settings.uiTranslationPack.filterInputPlaceholder;
        }
        return el;
    }
    /**
     * Return the items the popup list renders, in display order.
     *
     * ```text
     * items                (setItems)
     *   |  gather          (only with grouping on; result cached until setItems)
     *   v
     * display base list
     *   |  filter query    (only while a query is active)
     *   v
     * visible items        (this method's return value)
     *   |  render
     *   v
     * DOM rows
     * ```
     *
     * - If no filter query is active (including while closed), it returns the
     *   full list, gathered per `gatherGroups` when grouping is on.
     * - If a filter query is active, it returns the matching subset.
     * - Disabled items are included. They render (grayed); only actions skip
     *   them (keyboard focus, the choose-all row's subset).
     * - Returns the LIVE internal array, typed read-only. Never mutate it
     *   (see `getItems`).
     * - Subclasses use it too (e.g. for selection-by-index), and may override
     *   it to add a step: `LLSelectMultiple` does for `hideChosenRows`.
     * @group Items
     */
    getVisibleItems() {
        return this.filteredItems ?? this.getDisplayBaseItems();
    }
    /**
     * The base list in DISPLAY order: `items` gathered per `gatherGroups`
     * (memoized until the next `setItems`), or `items` as-is while grouping is
     * off or `gatherGroups` is false. Filtering and rendering read this, never
     * `items` directly - so the gather runs lazily, at first need after a
     * `setItems`.
     */
    getDisplayBaseItems() {
        if (!this.settings.gatherGroups) {
            return this.items;
        }
        if (this.gatheredItems === undefined) {
            // Keys resolve via the protected overridable method itemToGroupKey, so
            // an override drives the gather exactly like the render. All-null keys
            // (grouping off) detect as contiguous and return `items` itself.
            this.gatheredItems = gatherItemsByGroupKey(this.items, (item) => this.itemToGroupKey(item), this.settings.groupKeyCompareFn);
        }
        return this.gatheredItems;
    }
    /**
     * Return the filter input's current query, exactly the string passed to
     * `filterFn`.
     * - It is `''` while the popup is closed, the filter is inactive, or the
     *   input is empty.
     * - It resets on close: each open cycle starts empty.
     * @group Filtering
     */
    getFilterQuery() {
        return this.query;
    }
    /**
     * Per-item match predicate for the filter input.
     * - Default reads `filterFn`; else case-insensitive substring on
     *   `itemToString`.
     * - Override only when extending (subclass-wide custom matching); for a
     *   one-off match rule pass the setting.
     * @group Subclassing: semantics
     */
    matchesQuery(item, query) {
        const fn = this.settings.filterFn;
        if (fn) {
            return fn(item, query);
        }
        return this.itemToString(item).toLowerCase().includes(query.toLowerCase());
    }
    /**
     * Recompute `filteredItems` from the current `items` and `query`. Pure state
     * update: does NOT touch the DOM (the caller re-renders the list separately).
     * No-op when `filterable: false`; an empty query keeps every item. Called from
     * `open()`, from `setItems()`, and on each filter-input event.
     */
    recomputeFilteredItems() {
        if (!this.filterActive) {
            return;
        }
        const q = this.query;
        // Filter over the display base (gathered order): filtering preserves
        // contiguity, so a group's position cannot jump while typing.
        const base = this.getDisplayBaseItems();
        this.filteredItems = q === '' ? base.slice() : base.filter(it => this.matchesQuery(it, q));
    }
    /**
     * Input event on the filter field: re-filter, re-render the list, move the
     * active option to the first match, then fire `onFilterQueryChange` when
     * the text actually changed. IME composition is guarded - we wait for
     * `compositionend` and filter once with the composed text. The Esc-clear
     * path comes through here too, so it fires the event as well.
     */
    handleSearchInputEvent() {
        if (this.composing) {
            return;
        }
        const next = this.filterInputEl.value;
        const changed = next !== this.query;
        this.query = next;
        this.recomputeFilteredItems();
        // First ENABLED match, not blindly index 0: disabled items are skipped
        // by keyboard navigation (A11Y.md "Disabled"), and the active option a
        // keystroke lands on is keyboard state. Set before the render, so the
        // one sync inside it reports the landing once, with no transient
        // "no item" between the rebuild and the landing.
        this.focusedRow = null;
        this.focusedIndex = this.findNextEnabledIndex(0, 1, this.getVisibleItems());
        this.renderPopupList();
        // The render reports the active item; a listener that closed the select component
        // reset the query, so no change of this keystroke is left to report: the
        // popup is closed, or the reset text differs from the typed one. A
        // rebuild or a value change under it keeps the query, which the app must
        // still hear.
        if (!this.opened || this.query !== next) {
            return;
        }
        if (changed) {
            const onFilterQueryChange = this.settings.onFilterQueryChange;
            onFilterQueryChange?.(next);
        }
    }
    /** Outer popup wrapper. Its role follows the filter mode (`syncFilterModeToDom`). */
    createPopupEl() {
        const el = document.createElement('div');
        el.id = this.classIdMap.popupId;
        el.className = this.classIdMap.popupClass;
        return el;
    }
    /**
     * Build the no-results message element.
     * - `role="status"` announces its appearance politely.
     * - It lives OUTSIDE the listbox, which holds only option rows, group
     *   containers and pinned-block wrappers.
     * - Its text comes from `uiTranslationPack.popupListNoResults`.
     */
    createPopupListNoResultsEl() {
        const el = document.createElement('div');
        el.className = this.classIdMap.popupListNoResultsClass;
        el.setAttribute('role', 'status');
        el.hidden = true;
        return el;
    }
    /**
     * The no-results message's visible content (rich empty-state).
     * - Default reads `createPopupListNoResultsContentElFn`; `null` (setting
     *   unset, or returned) = plain text from `uiTranslationPack.popupListNoResults`.
     * - Override only when extending; for one-off content pass the setting.
     * @group Subclassing: rendering
     */
    createPopupListNoResultsContentEl(query) {
        const fn = this.settings.createPopupListNoResultsContentElFn;
        return fn ? fn(query) : null;
    }
    /**
     * Build the pinned header container between the filter input and the listbox.
     * - The library calls it once, inside the constructor. You never call it.
     * - It takes no params. The default asks {@link createPopupHeaderContentEl}
     *   for content; `null` content = no container, and `popupHeaderEl` stays `null`.
     * - To supply content without subclassing, pass `createPopupHeaderContentElFn`.
     * - To change the container itself, override it: call
     *   `super.createPopupHeaderEl()` and edit the returned element, or return
     *   your own `div`. Returning non-null builds the slot even without the
     *   setting. Keep it role-free: it is not part of the listbox.
     * - Internals: the base builds a `div` with `classIdMap.popupHeaderClass`
     *   and inline `flex: none` (the popup is a flex column and only the listbox
     *   may flex), then appends the content.
     * @group Subclassing: rendering
     */
    createPopupHeaderEl() {
        return this.createPopupSlotEl(this.classIdMap.popupHeaderClass, this.createPopupHeaderContentEl());
    }
    /**
     * The pinned header's content element.
     * - The library calls it once, from {@link createPopupHeaderEl}, inside the
     *   constructor. You never call it.
     * - Default calls `createPopupHeaderContentElFn` with a
     *   {@link LLSelectConstructionContext}; `null` (setting unset, or
     *   returned) = no header at all.
     * - Override only when extending; for one-off content pass the setting.
     * @group Subclassing: rendering
     */
    createPopupHeaderContentEl() {
        const fn = this.settings.createPopupHeaderContentElFn;
        return fn ? fn(this.createConstructionContext()) : null;
    }
    /**
     * Build the pinned footer container at the bottom of the popup.
     * - The library calls it once, inside the constructor. You never call it.
     * - It takes no params. The default asks {@link createPopupFooterContentEl}
     *   for content; `null` content = no container, and `popupFooterEl` stays `null`.
     * - To supply content without subclassing, pass `createPopupFooterContentElFn`.
     * - To change the container itself, override it: call
     *   `super.createPopupFooterEl()` and edit the returned element, or return
     *   your own `div`. Returning non-null builds the slot even without the
     *   setting. Keep it role-free: it is not part of the listbox.
     * - Internals: the base builds a `div` with `classIdMap.popupFooterClass`
     *   and inline `flex: none` (only the listbox may flex), then appends the
     *   content.
     * @group Subclassing: rendering
     */
    createPopupFooterEl() {
        return this.createPopupSlotEl(this.classIdMap.popupFooterClass, this.createPopupFooterContentEl());
    }
    /**
     * The pinned footer's content element.
     * - The library calls it once, from {@link createPopupFooterEl}, inside the
     *   constructor. You never call it.
     * - Default calls `createPopupFooterContentElFn` with a
     *   {@link LLSelectConstructionContext}; `null` (setting unset, or
     *   returned) = no footer at all.
     * - Override only when extending; for one-off content pass the setting.
     * @group Subclassing: rendering
     */
    createPopupFooterContentEl() {
        const fn = this.settings.createPopupFooterContentElFn;
        return fn ? fn(this.createConstructionContext()) : null;
    }
    /** The read-only view a construction-time settings function receives. */
    createConstructionContext() {
        return { classIdMap: this.classIdMap, uiTranslationPack: this.settings.uiTranslationPack };
    }
    /**
     * Scroll a ring entry into view. A row inside a pinned wrapper is always in
     * view, so it is left alone. Every other entry, an item inside a group
     * container included, scrolls under the pinned blocks, so their measured
     * heights are handed to the scroll math as insets.
     */
    scrollRingEntryIntoView(el) {
        const leading = this.popupListPinnedLeadingRowsEl;
        const trailing = this.popupListPinnedTrailingRowsEl;
        if ((leading !== null && leading.contains(el)) || (trailing !== null && trailing.contains(el))) {
            return;
        }
        ensureVisibleInScroll(el, this.popupListEl, this.pinnedWrapperHeight(leading), this.pinnedWrapperHeight(trailing));
    }
    /** The height a pinned wrapper covers at its listbox edge; 0 when it is not in the listbox. */
    pinnedWrapperHeight(wrapper) {
        if (!wrapper || wrapper.parentElement !== this.popupListEl) {
            return 0;
        }
        return wrapper.getBoundingClientRect().height;
    }
    /**
     * The sticky wrapper of a pinned block: presentational (the accessibility
     * tree sees only the rows inside), stuck to one edge of the listbox by
     * inline style so the setting works without theme support. Themes paint
     * its background and edge line.
     */
    createPopupListPinnedRowsEl(className, edge) {
        const el = document.createElement('div');
        el.className = className;
        el.setAttribute('role', 'presentation');
        el.style.position = 'sticky';
        if (edge === 'top') {
            el.style.top = '0';
        }
        else {
            el.style.bottom = '0';
        }
        return el;
    }
    /** Shared body of the two slot builders: `null` content = no container. */
    createPopupSlotEl(className, content) {
        if (content === null) {
            return null;
        }
        const el = document.createElement('div');
        el.className = className;
        // The popup is a flex column; only the listbox may grow or shrink.
        el.style.flex = 'none';
        el.appendChild(content);
        return el;
    }
    /**
     * Mirror the visible-list-empty state onto the no-results message element:
     * `hidden` while there is at least one visible item; when shown, fill its
     * content - `createPopupListNoResultsContentEl(query)` first, else the plain
     * text from `uiTranslationPack.popupListNoResults`. Same null-branch shape as
     * `createPopupListItemEl` / `createGroupEl`.
     * - The write is SKIPPED when the resolved text matches what is already shown,
     *   so a still-empty next keystroke does not re-announce (see `lastNoResultsText`).
     */
    syncPopupListNoResultsToDom() {
        const empty = this.getVisibleItems().length === 0;
        this.popupListNoResultsEl.hidden = !empty;
        if (!empty) {
            this.lastNoResultsText = null;
            return;
        }
        const content = this.createPopupListNoResultsContentEl(this.query);
        const nextText = content === null
            ? this.settings.uiTranslationPack.popupListNoResults
            : content.textContent ?? '';
        if (nextText === this.lastNoResultsText) {
            return;
        }
        this.lastNoResultsText = nextText;
        if (content === null) {
            this.popupListNoResultsEl.textContent = this.settings.uiTranslationPack.popupListNoResults;
        }
        else {
            this.popupListNoResultsEl.replaceChildren(content);
        }
    }
    /** Inner element with `role="listbox"`. Holds item children. */
    createPopupListEl() {
        const el = document.createElement('div');
        el.id = this.classIdMap.popupListId;
        el.className = this.classIdMap.popupListClass;
        el.setAttribute('role', 'listbox');
        el.setAttribute('tabindex', '-1');
        return el;
    }
}

/**
 * Single-selection select component.
 * Picking an item replaces any prior chosen item and closes the popup.
 * Use `setChosenItem(undefined)` to clear the selection.
 *
 * @typeParam T - item type. Supply your own `compareFn` for non-primitive `T`.
 * @typeParam GroupKey - group key type of `itemToGroupKeyFn`; see
 *   {@link LLSelectBase}.
 * @typeParam S - resolved settings type, for subclasses extending the
 *   settings bag; see {@link LLSelectBase}.
 * @group Select component classes
 */
class LLSelectSingle extends LLSelectBase {
    constructor(targetEl, settings, subclassSettings) {
        const ownExtras = {
            onChange: settings?.onChange ?? null,
            onBeforeChange: settings?.onBeforeChange ?? null,
            createTriggerContentElFn: settings?.createTriggerContentElFn ?? null,
            triggerContextToScreenReaderTextFn: settings?.triggerContextToScreenReaderTextFn ?? null,
        };
        // Cast mirrored from the base constructor: TS cannot prove "own extras +
        // Omit<S, own keys>" reassembles a generic S's extras. Own extras stay
        // satisfies-checked above; incoming extras are param-typed.
        super(targetEl, settings, { ...ownExtras, ...subclassSettings });
        /**
         * Currently chosen item, or `undefined` if none.
         * @group State (protected)
         */
        this.chosenItem = undefined;
        /** The item whose text the default screen-reader text is, for its `lang`; set by `computeTriggerScreenReaderText`, read once by `computeTriggerScreenReaderTextLang`. */
        this.screenReaderTextSource = null;
        this.renderTrigger();
    }
    /**
     * Return the currently chosen item, or `undefined` if none.
     * @group Selection
     */
    getChosenItem() {
        return this.chosenItem;
    }
    /**
     * Set the chosen item programmatically.
     * - `undefined` clears the choice.
     * - Fires `onChange` only when the item actually differs from the current
     *   one (compared via `compareFn`).
     * - Accepts an item that is not (yet) in the items list, for async data
     *   flows. If a later `setItems` does not include it, it is dropped
     *   automatically.
     * - It does not check disabled state: a disabled item can be chosen
     *   programmatically. Native `<select>` behaves the same.
     * @group Selection
     */
    setChosenItem(item) {
        if (this.areEqual(item, this.chosenItem)) {
            return;
        }
        const previous = this.chosenItem;
        this.chosenItem = item;
        this.renderTrigger();
        // Popup open: refresh only the two affected options so their
        // aria-selected stays true to state (O(1); no-op while closed).
        if (previous !== undefined) {
            this.replacePopupListItemElInDom(previous);
        }
        if (item !== undefined) {
            this.replacePopupListItemElInDom(item);
        }
        if (item === undefined) {
            this.fireChange(previous, 'clear');
        }
        else {
            this.fireChange(previous, 'choose', item);
        }
    }
    /**
     * Orchestrator: composes `syncEmptyStateToDom` + `commitTriggerContentToDom`
     * to (re)build the trigger from state; touches no DOM directly.
     * - `createTriggerContentElFn` is tried first; if it returns `null` or is
     *   unset, the default applies.
     * - The default is the chosen item's string, or the placeholder when
     *   nothing is chosen.
     * @group Subclassing: rendering
     */
    renderTriggerContent() {
        this.syncEmptyStateToDom();
        // The chosen item's language rides on the content slot, custom content
        // included, and an app's own lang on its element wins, being nearer. The
        // placeholder is interface text, so an empty selection carries none.
        const lang = this.chosenItem === undefined ? null : this.itemToLang(this.chosenItem);
        this.commitLangToDom(this.triggerContentEl, lang);
        const fn = this.settings.createTriggerContentElFn;
        const custom = fn?.({ chosenItem: this.chosenItem, items: this.getItems() }) ?? null;
        if (custom !== null) {
            this.commitTriggerContentToDom(custom);
            return;
        }
        this.commitTriggerContentToDom(this.chosenItem === undefined ? this.settings.placeholder : this.itemToString(this.chosenItem));
    }
    /**
     * The screen-reader text: the value assistive technology reads for the
     * trigger, never shown. See the base method for why it exists.
     * - The library calls it after every trigger content render.
     * - Default: the text of `triggerContextToScreenReaderTextFn`; when that
     *   gives `null` or a blank string, the chosen item's `itemToString`, or
     *   the placeholder while nothing is chosen.
     * @group Subclassing: semantics
     */
    computeTriggerScreenReaderText() {
        this.screenReaderTextSource = null;
        const fn = this.settings.triggerContextToScreenReaderTextFn;
        const custom = fn?.({ chosenItem: this.chosenItem, items: this.getItems() }) ?? null;
        if (custom !== null && custom.trim() !== '') {
            return custom;
        }
        if (this.chosenItem === undefined) {
            return this.settings.placeholder;
        }
        const text = this.itemToString(this.chosenItem);
        this.screenReaderTextSource = { text, item: this.chosenItem };
        return text;
    }
    /**
     * The chosen item's `lang` while the screen-reader text is that item's text.
     * @internal
     */
    computeTriggerScreenReaderTextLang(text) {
        // Read once: an override that skips super must not inherit a stale item.
        const source = this.screenReaderTextSource;
        this.screenReaderTextSource = null;
        return source !== null && source.text === text ? this.itemToLang(source.item) : null;
    }
    /**
     * No selection iff `chosenItem` is unset. Drives the trigger wrapper's `data-empty`.
     * @group Subclassing: semantics
     */
    isEmpty() {
        return this.chosenItem === undefined;
    }
    /**
     * Mark the chosen option `aria-selected="true"`, the rest `"false"` (APG select-only).
     * @group Subclassing: rendering
     */
    createPopupListItemEl(item, index) {
        const el = super.createPopupListItemEl(item, index);
        el.setAttribute('aria-selected', String(this.areEqual(item, this.chosenItem)));
        return el;
    }
    /**
     * Set this item as the chosen item **after** Enter on its row while it is the
     * active row, Space on it while the filter is inactive, or a click on it,
     * then close the popup.
     *
     * > No **before** counterpart: there is no `onPopupListItemActivating`.
     *
     * - Asks `onChosenChanging` and `onBeforeChange` first; a veto keeps the
     *   current value.
     * - Closes the popup either way, unless a handler threw.
     * @group Subclassing: reactions
     */
    onPopupListItemActivated(item) {
        if (this.requestUserChange(item, 'choose', item)) {
            this.setChosenItem(item);
        }
        this.closeWithReason('choose');
    }
    /**
     * Clear button empties the single selection to `undefined`, after asking
     * `onChosenChanging` and `onBeforeChange`.
     * @group Subclassing: semantics
     */
    clearSelection() {
        if (this.requestUserChange(undefined, 'clear')) {
            this.setChosenItem(undefined);
        }
    }
    /**
     * Subclass hook: called **before** a user interaction changes the chosen item,
     * with the way to stop it. Default no-op.
     *
     * > Pairs with `onChosenChanged`, which runs **after** the change was written.
     *
     * - Runs **before** the `onBeforeChange` setting. Both run, either may call
     *   `event.preventDefault()`.
     * - The parameters are the setting's: the value about to be set, the
     *   current one, the event.
     * @group Subclassing: reactions
     */
    onChosenChanging(_nextChosenItem, _previousChosenItem, _event) { }
    requestUserChange(next, reason, item) {
        const previous = this.chosenItem;
        if (this.areEqual(next, previous)) {
            return false;
        }
        const revision = this.changeRevision;
        const allowed = this.dispatchBeforeChange(reason === 'choose' ? { reason, item: item } : { reason }, (event) => {
            this.onChosenChanging(next, previous, event);
            const fn = this.settings.onBeforeChange;
            fn?.(next, previous, event);
        });
        // A setter called inside the handlers wins, setItems included: the pending
        // change is dropped, even when the handler restored the previous value.
        return allowed && this.changeRevision === revision;
    }
    /**
     * Decide which row is active when the popup opens.
     * - The library calls it inside `open()`, once per open, after the rows
     *   are built. You never call it.
     * - To pick another row, override it and set the row with
     *   `setFocusedIndex`.
     * - `setFocusedIndex` takes an index into `getVisibleItems()`, which
     *   counts item rows only; action rows have no index.
     * - To fall back to this method's choice, call `super.focusInitial()`, but
     *   only when the override set no row.
     * - The active row is the `role="option"` row that `aria-activedescendant`
     *   names on the `role="combobox"` element: the trigger, or the filter
     *   input while the filter is active.
     * - "Focus" in the names `focusInitial` and `setFocusedIndex` means the
     *   active row, not DOM focus.
     * - DOM focus never moves to the active row. While the filter is active,
     *   the open moves DOM focus to the filter input.
     * - `open()` clears the active row before the call, so the popup opens
     *   with no active row unless this method sets one.
     * - Visible items are the items in `getVisibleItems()`, the items that
     *   have a row in the list.
     * - Makes the row of the chosen item active, if the chosen item is visible
     *   and enabled.
     * - Otherwise makes the first enabled visible item the active row.
     * - Either step replaces any row set before this method runs.
     * - Does nothing when no visible item is enabled.
     * @group Subclassing: focus
     */
    focusInitial() {
        const list = this.getVisibleItems();
        const c = this.chosenItem;
        if (c !== undefined) {
            const compareFn = this.settings.compareFn;
            const idx = list.findIndex(o => compareFn(o, c));
            if (idx >= 0 && !this.isItemEffectivelyDisabled(list[idx])) {
                this.setFocusedIndex(idx);
                return;
            }
        }
        const first = this.findNextEnabledIndex(0, 1, list);
        if (first >= 0) {
            this.setFocusedIndex(first);
        }
    }
    /**
     * Closed-state typeahead searches relative to the CHOSEN item, like a
     * native `<select>`: typing its initial cycles to the next match.
     * - Returns `-1` when nothing is chosen, or the chosen item left the list;
     *   the search then starts from the top.
     * @group Subclassing: focus
     */
    computeTypeaheadClosedStartIndex(list) {
        const c = this.chosenItem;
        if (c === undefined) {
            return -1;
        }
        const compareFn = this.settings.compareFn;
        return list.findIndex((o) => compareFn(o, c));
    }
    /**
     * Re-match the chosen item against the new list **after** `setItems` installs it.
     *
     * > No **before** counterpart: there is no `onItemsChanging`.
     *
     * - If the list no longer holds it (by `compareFn`), it is dropped and
     *   `onChange` fires.
     * - If the list holds a compareFn-equal but DIFFERENT object (`track by`
     *   style reload: same key, fresh fields), the stored reference is swapped
     *   to the list's object. The logical value did not change, so `onChange`
     *   does not fire.
     * - The trigger content re-renders after every `setItems`, because a custom
     *   `createTriggerContentElFn` receives `items`.
     * - The arrow re-renders only when the chosen item is dropped, because that
     *   runs the whole trigger.
     * @group Subclassing: reactions
     */
    onItemsChanged() {
        const previous = this.chosenItem;
        if (previous !== undefined) {
            const compareFn = this.settings.compareFn;
            const idx = this.items.findIndex(o => compareFn(o, previous));
            if (idx < 0) {
                this.chosenItem = undefined;
                this.renderTrigger();
                this.fireChange(previous, 'items');
                return;
            }
            const matched = this.items[idx];
            // Reference swap = a different VALUE under SameValueZero, so a NaN item
            // matching itself is not a swap.
            if (!defaultCompareFn(matched, previous)) {
                this.chosenItem = matched;
            }
        }
        // A custom trigger receives `items`, so every list change refreshes the
        // content; the arrow does not depend on the list.
        this.renderTriggerContent();
    }
    areEqual(a, b) {
        if (a === undefined && b === undefined) {
            return true;
        }
        if (a === undefined || b === undefined) {
            return false;
        }
        const compareFn = this.settings.compareFn;
        return compareFn(a, b);
    }
    fireChange(previousChosenItem, reason, item) {
        this.changeRevision++;
        // Consume the source before any observer runs: a programmatic setter
        // called from inside onChange (or a subclass reaction) must report
        // 'api', not inherit the outer interaction's 'user' attribution.
        const source = this.changeSource;
        this.changeSource = 'api';
        // The item shape for the two single-item reasons, even when T admits undefined.
        const meta = reason === 'choose' || reason === 'unchoose'
            ? { source, reason, item: item }
            : { source, reason };
        this.onChosenChanged();
        const onChange = this.settings.onChange;
        onChange?.(this.chosenItem, previousChosenItem, meta);
        // Action rows read live state; after the handler ran, so a row's text may show what it wrote.
        this.replacePopupListActionRowElsInDom();
    }
}

/**
 * Multi-selection select component. Clicking an item toggles its membership in
 * the chosen-items set and keeps the popup open. Each item DOM gets
 * `aria-selected="true|false"`; the popup list gets
 * `aria-multiselectable="true"`.
 *
 * Default trigger display is a count text ("3 / 10 selected" / "All N
 * selected" / placeholder when empty). Set `triggerDisplay: 'tags'` for chips,
 * or pass `createTriggerContentElFn` (or subclass `renderTriggerContent`) for
 * custom markup.
 *
 * @typeParam T - item type.
 * @typeParam GroupKey - group key type of `itemToGroupKeyFn`; see
 *   {@link LLSelectBase}.
 * @typeParam S - resolved settings type, for subclasses extending the
 *   settings bag; see {@link LLSelectBase}.
 * @group Select component classes
 */
class LLSelectMultiple extends LLSelectBase {
    constructor(targetEl, settings, subclassSettings) {
        const ownExtras = {
            onChange: settings?.onChange ?? null,
            onBeforeChange: settings?.onBeforeChange ?? null,
            createTriggerContentElFn: settings?.createTriggerContentElFn ?? null,
            triggerContextToScreenReaderTextFn: settings?.triggerContextToScreenReaderTextFn ?? null,
            triggerDisplay: settings?.triggerDisplay ?? 'count',
            createTagContentElFn: settings?.createTagContentElFn ?? null,
            createTagRemoveButtonContentElFn: settings?.createTagRemoveButtonContentElFn ?? null,
            hideChosenRows: settings?.hideChosenRows ?? false,
            chosenItemsOrder: settings?.chosenItemsOrder ?? 'as-chosen',
            chooseAllRow: settings?.chooseAllRow ?? false,
            createChooseAllRowContentElFn: settings?.createChooseAllRowContentElFn ?? null,
        };
        // Cast mirrored from the base constructor: TS cannot prove "own extras +
        // Omit<S, own keys>" reassembles a generic S's extras. Own extras stay
        // satisfies-checked above; incoming extras are param-typed.
        super(targetEl, settings, { ...ownExtras, ...subclassSettings });
        /**
         * Currently chosen items, in `chosenItemsOrder` order (chosen order by default).
         * @group State (protected)
         */
        // `readonly` so a subclass cannot `push`/`splice` it: every mutation must
        // REPLACE the array (the invariant both `chosenSetCache` and `visibleItemsCache`
        // rely on - a reference change is how they invalidate).
        this.chosenItems = [];
        /** The item whose text the default screen-reader text is, for its `lang`; set by `computeTriggerScreenReaderText`, read once by `computeTriggerScreenReaderTextLang`. */
        this.screenReaderTextSource = null;
        this.chosenSetCache = null;
        /**
         * hideChosenRows subtraction cache. Every layer above (items, gather,
         * filter) and the chosen set REPLACE their arrays on change, never mutate
         * in place - so two reference checks are a complete validity test and no
         * invalidation wiring is needed.
         */
        this.visibleItemsCache = null;
        /** Position of each item in the current list; built once per item list (default `compareFn` only). */
        this.itemPositionCache = null;
        this.popupListEl.setAttribute('aria-multiselectable', 'true');
        this.renderTrigger();
    }
    /**
     * Return the currently chosen items, in `chosenItemsOrder` order (chosen order by default).
     * @group Selection
     */
    getChosenItems() {
        return this.chosenItems;
    }
    /**
     * Replace the entire chosen-items list.
     * - The input is copied, and duplicates (per `compareFn`) collapse to
     *   their first occurrence: the chosen items are a set.
     * - Fires `onChange` only when the new list differs from the current one.
     *   The comparison is order-sensitive: chosen order is visible state
     *   (tags render in it).
     * - When `chosenItemsOrder` is `'as-listed'`, the input is first put in list
     *   order, so a write of the same set in another order is no change for
     *   items the list holds.
     * - When `chosenItemsOrder` is `'as-listed'`, unlisted items go last,
     *   keeping their order relative to each other.
     * - It ignores disabled state: it can add and drop disabled items, unlike
     *   the `choose*` bulk ops. Assigning to a native `<select>` behaves the
     *   same.
     * @group Selection
     */
    setChosenItems(chosenItems) {
        const next = this.normalizeChosen(chosenItems);
        if (this.arraysEqual(next, this.chosenItems)) {
            return;
        }
        const previous = this.chosenItems;
        this.chosenItems = next;
        this.rerender();
        this.fireChange(previous, next.length === 0 ? 'clear' : 'set');
    }
    /**
     * Whether the given item is currently chosen (via `compareFn`).
     * @group Selection
     */
    isChosen(item) {
        // Default (identity) compareFn: O(1) Set membership instead of a linear scan,
        // so a multi popup render is O(visible), not O(visible x chosen). The Set is
        // memoized and invalidated by the chosenItems array reference - every mutation
        // replaces the array, never mutates in place (mirrors visibleItemsCache). A
        // custom compareFn cannot hash, so it stays linear. The Set is SameValueZero,
        // and so is defaultCompareFn, so NaN behaves the same on both paths.
        if (this.settings.compareFn === defaultCompareFn) {
            return this.chosenSet().has(item);
        }
        const compareFn = this.settings.compareFn;
        return this.chosenItems.some(c => compareFn(c, item));
    }
    /** Memoized Set of `chosenItems` for the default-compareFn `isChosen` fast path. */
    chosenSet() {
        const cache = this.chosenSetCache;
        if (cache !== null && cache.chosen === this.chosenItems) {
            return cache.set;
        }
        const set = new Set(this.chosenItems);
        this.chosenSetCache = { chosen: this.chosenItems, set };
        return set;
    }
    /**
     * Toggle the membership of `item` in the chosen-items set. Fires `onChange`.
     * - If the item is not chosen, it is added at the end.
     * - When `chosenItemsOrder` is `'as-listed'`, it is added at its list
     *   position instead.
     * - If the item is chosen, it is removed.
     * - While `hideChosenRows` is on, the popup list is rebuilt so the row
     *   leaves or re-enters it.
     * @group Selection
     */
    toggleItem(item) {
        const previous = this.chosenItems;
        const { next, removed, changedItem } = this.nextAfterToggle(item);
        this.chosenItems = next;
        // Only one item's selection changed, so the popup list replaces just that
        // one row (plus the choose-all tri-state) instead of rebuilding every row -
        // O(1) in list size. Exceptions: hideChosenRows moves the row in or out of
        // the list and shifts the indexes, so it rebuilds the list instead;
        // chosenItemsOrder 'as-listed' sorts the chosen items on every add. The
        // trigger is refreshed too; its cost depends on triggerDisplay (count =
        // constant, tags = one chip per chosen item, custom = caller-defined), so
        // the whole update is not unconditionally O(1).
        this.renderTrigger();
        if (this.settings.hideChosenRows) {
            if (this.isOpened()) {
                this.renderPopupList();
            }
        }
        else {
            this.replacePopupListItemElInDom(item);
            this.replaceChooseAllRowElInDom();
        }
        this.fireChange(previous, removed ? 'unchoose' : 'choose', changedItem);
    }
    /**
     * Choose every enabled item.
     * - It chooses only enabled items from the current item list, like every
     *   `choose*` bulk op. Bulk ops mirror clicking, and clicking cannot reach
     *   disabled items.
     * - Already-chosen disabled items in the current item list are preserved.
     *   To change disabled items too, use `setChosenItems`.
     * - `setChosenItems()` and `toggleItem()` accept items outside the current
     *   item list. If a chosen item is outside that list, this method drops it
     *   when it rebuilds the selection, disabled or not.
     * - Fires `onChange` only when the chosen items actually change.
     * @group Selection
     */
    chooseAll() {
        this.setChosenItems(this.items.filter(it => !this.isItemEffectivelyDisabled(it) || this.isChosen(it)));
    }
    /**
     * Unchoose every enabled item.
     * - It filters the chosen set: every enabled chosen item leaves the
     *   selection, even if the item is outside the current item list.
     * - Every disabled chosen item stays chosen, even if the item is outside
     *   the current item list.
     * - Clicking a disabled item does not change its selection state, and this
     *   method follows that rule.
     * - The paths that DO drop them:
     *   - the clear button, when `clearable` is on and the control is enabled;
     *   - `toggleItem()` with the item;
     *   - `setChosenItems()` with a selection that excludes the item;
     *   - `setItems()` with a list that no longer contains the item;
     *   - `chooseAll()`, if the item is outside the current item list: it
     *     rebuilds the selection from that list, which drops the item
     *     (`setChosenItems()` and `toggleItem()` can select items outside
     *     the list);
     *   - `toggleAll()`, if the item is outside the current item list, in the
     *     two cases where it calls `chooseAll()`: the list has no enabled item,
     *     or an enabled item in the list is unchosen.
     * - Fires `onChange` only when the chosen items actually change.
     * @group Selection
     */
    unchooseAll() {
        this.setChosenItems(this.chosenItems.filter(c => this.isItemEffectivelyDisabled(c)));
    }
    /**
     * Toggle between "all enabled chosen" and "all enabled unchosen".
     * - If the current item list holds at least one enabled item and every
     *   enabled item is chosen:
     *   - It calls `unchooseAll()`.
     *   - Every enabled chosen item leaves the selection, even if the item is
     *     outside the current item list.
     *   - Every disabled chosen item stays chosen, even if the item is outside
     *     the current item list.
     * - Otherwise:
     *   - It calls `chooseAll()`.
     *   - Every enabled item in the current item list becomes chosen.
     *   - Disabled chosen items in the current item list stay chosen.
     *   - Chosen items outside the current item list leave the selection,
     *     disabled or not.
     * - Disabled items in the current item list keep their selection state,
     *   like with every `choose*` bulk op.
     * - This is NOT the in-popup choose-all row's action. The row acts on the
     *   visible enabled subset only: see {@link toggleAllVisible}.
     * @group Selection
     */
    toggleAll() {
        const enabled = this.items.filter(it => !this.isItemEffectivelyDisabled(it));
        const allChosen = enabled.length > 0 && enabled.every(it => this.isChosen(it));
        if (allChosen) {
            this.unchooseAll();
        }
        else {
            this.chooseAll();
        }
    }
    /**
     * Toggle the visible enabled items between all-chosen and all-unchosen.
     * - This is the choose-all row's action (the `chooseAllRow` setting) as a
     *   public method. The row computes the same next value and commits it
     *   through the before-change gate, so an override here does not change
     *   the row.
     * - Acts on exactly the items that satisfy all of the following:
     *   - Visible: the item is in `getVisibleItems()`. It matches the active
     *     filter query, and with `hideChosenRows` it is not chosen. With no
     *     query and without `hideChosenRows`, every item is visible.
     *   - Enabled: not disabled via `itemDisabledFn`, and not in a disabled
     *     group.
     * - If all of them are already chosen, it unchooses exactly those.
     * - Otherwise, it chooses the ones still missing.
     * - When `hideChosenRows` is on, a chosen item is not visible, so this
     *   method only chooses.
     * - If this method does not act on a chosen item, that item stays chosen.
     *   This covers:
     *   - items hidden by the active filter query;
     *   - items hidden by `hideChosenRows`;
     *   - disabled items;
     *   - chosen items outside the current item list (`setChosenItems()` and
     *     `toggleItem()` accept such items).
     * - When there is no filter query and `hideChosenRows` is off, this method
     *   acts on every enabled item of the current item list.
     * - `toggleAll` can drop chosen items outside the current item list:
     *   - If the current item list has no enabled item, or an enabled item in
     *     that list is unchosen, `toggleAll` calls `chooseAll()`. That call
     *     drops every chosen item outside the list, disabled or not.
     *   - Otherwise `toggleAll` calls `unchooseAll()`. That call clears every
     *     enabled chosen item outside the list and keeps the disabled ones.
     * - Fires `onChange` only when the chosen items actually change.
     * - The acted-on set is computed by the overridable method `getVisibleEnabledItems`,
     *   shared with the choose-all row.
     * @group Selection
     */
    toggleAllVisible() {
        const next = this.nextAfterToggleAllVisible();
        if (next !== null) {
            this.setChosenItems(next);
        }
    }
    /**
     * What the choose-all row would commit: the normalized next chosen array,
     * or `null` when nothing is actionable. Shared by `toggleAllVisible` and
     * the before-change gate, so the hook sees exactly what the setter commits.
     */
    nextAfterToggleAllVisible() {
        const actionable = this.getVisibleEnabledItems();
        if (actionable.length === 0) {
            return null;
        }
        const allChosen = actionable.every(i => this.isChosen(i));
        if (allChosen) {
            const compareFn = this.settings.compareFn;
            return this.normalizeChosen(this.chosenItems.filter(c => !actionable.some(v => compareFn(v, c))));
        }
        const additions = actionable.filter(v => !this.isChosen(v));
        return this.normalizeChosen([...this.chosenItems, ...additions]);
    }
    /**
     * Dedupe and order a raw chosen array: set semantics, as compareFn's
     * contract promises. The choose* bulk ops filter through isChosen and never
     * produce duplicates; setChosenItems is the one door raw arrays (framework
     * model write-back included) come in through, so the dedup lives here.
     */
    normalizeChosen(chosenItems) {
        let next;
        if (this.settings.compareFn === defaultCompareFn) {
            next = [...new Set(chosenItems)];
        }
        else {
            next = [];
            const compareFn = this.settings.compareFn;
            for (const item of chosenItems) {
                if (!next.some(c => compareFn(c, item))) {
                    next.push(item);
                }
            }
        }
        return this.orderChosen(next);
    }
    /**
     * What a toggle of `item` would do: the next chosen array, whether the item
     * leaves, and the entry that changes. Shared by `toggleItem` and the
     * before-change gate, so the hook sees exactly what the setter commits.
     * - The removed entry is the STORED one: with a key-based compareFn the
     *   caller's `item` may be a different, equal object, and meta.item must
     *   name what left the selection.
     */
    nextAfterToggle(item) {
        const previous = this.chosenItems;
        const compareFn = this.settings.compareFn;
        const idx = previous.findIndex(c => compareFn(c, item));
        const removed = idx >= 0;
        const changedItem = removed ? previous[idx] : item;
        const next = removed
            ? [...previous.slice(0, idx), ...previous.slice(idx + 1)]
            : this.orderChosen([...previous, item]);
        return { next, removed, changedItem };
    }
    /**
     * Return the items a "select all" acts on: the visible, enabled ones.
     * - Visible: the item is in `getVisibleItems()`. It matches the active
     *   filter query, and with `hideChosenRows` it is not chosen. With no
     *   query and without `hideChosenRows`, every item is visible.
     * - Enabled: not disabled via `itemDisabledFn`, and not in a disabled group.
     * - The choose-all row (its counts, its tri-state, its click) and
     *   `toggleAllVisible()` both read this method.
     * - Use it to build your own select-all as an action row, for example in
     *   the trailing rows: count the chosen items with `isChosen`, write the
     *   text with `getUiTranslationPack().chooseAllRowText(chosen, total)`, and
     *   call `toggleAllVisible()` from `onActivate`.
     * - Such a row is a command, not the built-in row:
     *   - its `aria-selected` is always `false`;
     *   - it has no `data-chosen-state`, so the themes give it no tri-state look;
     *   - it is never the active option when the popup opens;
     *   - it stays rendered when this list is empty.
     * - For a row that follows the selection, looks tri-state, can be the
     *   initial active option and hides itself, use `chooseAllRow`.
     * - Override it to change the subset. The tree-select demo narrows it to
     *   leaf nodes; the choose-all row and `toggleAllVisible()` follow the
     *   override.
     * @group Selection
     */
    getVisibleEnabledItems() {
        return this.getVisibleItems().filter(i => !this.isItemEffectivelyDisabled(i));
    }
    /**
     * Return the items the popup list renders, in display order.
     *
     * ```text
     * base visible items   (LLSelectBase.getVisibleItems: gather + filter)
     *   |  minus chosen    (only while hideChosenRows is on; result cached)
     *   v
     * visible items        (this method's return value)
     * ```
     *
     * - Identical to the base behavior, minus the chosen items while
     *   `hideChosenRows` is on.
     * - While `hideChosenRows` is on and something is chosen, it returns a
     *   cached fresh array, not the live internal one.
     * - The subtraction recomputes only when the base list or the chosen set
     *   changed. Calls in between return the same cached array.
     * @group Items
     */
    getVisibleItems() {
        const list = super.getVisibleItems();
        if (!this.settings.hideChosenRows || this.chosenItems.length === 0) {
            return list;
        }
        const cache = this.visibleItemsCache;
        if (cache !== null && cache.base === list && cache.chosen === this.chosenItems) {
            return cache.result;
        }
        let result;
        if (this.settings.compareFn === defaultCompareFn) {
            const chosen = new Set(this.chosenItems);
            result = list.filter(it => !chosen.has(it));
        }
        else {
            result = list.filter(it => !this.isChosen(it));
        }
        this.visibleItemsCache = { base: list, chosen: this.chosenItems, result };
        return result;
    }
    /**
     * Orchestrator: composes `syncEmptyStateToDom` + `commitTriggerContentToDom`
     * + `commitTagsElToDom` to (re)build the trigger from state; touches no DOM
     * directly. Default text is a count text; override (or pass the
     * `createTriggerContentElFn` setting) to display custom markup.
     *
     * - If 0 items are chosen, the text is `placeholder`.
     * - If n > 0, the text is `uiTranslationPack.triggerContentCountText(n, total)`
     *   (English default: `"n / total selected"`, or `"All n selected"` when
     *   all are chosen).
     * - In `'tags'` mode the chips from `createTagsEl` go into the trigger
     *   buttons strip, and the content slot stays empty while they show.
     * - What a screen reader reads comes from `computeTriggerScreenReaderText`,
     *   which the library calls after this render.
     * @group Subclassing: rendering
     */
    renderTriggerContent() {
        this.syncEmptyStateToDom();
        const chosenCount = this.chosenItems.length;
        const fn = this.settings.createTriggerContentElFn;
        const custom = fn?.({ chosenItems: this.getChosenItems(), items: this.getItems() }) ?? null;
        if (custom !== null) {
            this.commitTagsElToDom(null);
            this.commitTriggerContentToDom(custom);
            return;
        }
        if (this.settings.triggerDisplay === 'tags' && chosenCount > 0) {
            this.commitTagsElToDom(this.createTagsEl());
            this.commitTriggerContentToDom('');
            return;
        }
        this.commitTagsElToDom(null);
        this.commitTriggerContentToDom(chosenCount === 0
            ? this.settings.placeholder
            : this.settings.uiTranslationPack.triggerContentCountText(chosenCount, this.items.length));
    }
    /**
     * The screen-reader text: the value assistive technology reads for the
     * trigger, never shown. See the base method for why it exists.
     * - The library calls it after every trigger content render.
     * - Default: the text of `triggerContextToScreenReaderTextFn`; when that
     *   gives `null` or a blank string, the text of the current mode, the same
     *   with custom trigger content:
     *   - in `'count'` mode, `uiTranslationPack.triggerScreenReaderCountText`;
     *   - in `'tags'` mode, `uiTranslationPack.triggerScreenReaderItemsText`
     *     with the chosen items' `itemToString` texts, in the chosen order;
     *   - the placeholder while nothing is chosen.
     * @group Subclassing: semantics
     */
    computeTriggerScreenReaderText() {
        this.screenReaderTextSource = null;
        const fn = this.settings.triggerContextToScreenReaderTextFn;
        const custom = fn?.({ chosenItems: this.getChosenItems(), items: this.getItems() }) ?? null;
        if (custom !== null && custom.trim() !== '') {
            return custom;
        }
        const chosenCount = this.chosenItems.length;
        if (chosenCount === 0) {
            return this.settings.placeholder;
        }
        const pack = this.settings.uiTranslationPack;
        if (this.settings.triggerDisplay !== 'tags') {
            return pack.triggerScreenReaderCountText(chosenCount, this.items.length);
        }
        const texts = this.chosenItems.map((item) => this.itemToString(item));
        const text = pack.triggerScreenReaderItemsText(texts);
        // One item whose text the pack passed through unchanged: its lang applies.
        if (chosenCount === 1 && text === texts[0]) {
            this.screenReaderTextSource = { text, item: this.chosenItems[0] };
        }
        return text;
    }
    /**
     * The chosen item's `lang` while the screen-reader text is exactly that
     * item's text: one chip; joined texts and the count text carry none.
     * @internal
     */
    computeTriggerScreenReaderTextLang(text) {
        // Read once: an override that skips super must not inherit a stale item.
        const source = this.screenReaderTextSource;
        this.screenReaderTextSource = null;
        return source !== null && source.text === text ? this.itemToLang(source.item) : null;
    }
    /**
     * Whether the trigger shows chips: `triggerDisplay: 'tags'`.
     * @internal
     */
    isTriggerDisplayTags() {
        return this.settings.triggerDisplay === 'tags';
    }
    /**
     * Build the tag-list element for `'tags'` mode: one chip per chosen item.
     * - The library puts it into the trigger buttons strip, before the clear
     *   button.
     * - The arrow keys of the strip move between its `button` elements.
     * - Override for full control of the chip list (the trigger-level
     *   equivalent of overriding `createPopupListItemEl`).
     * @group Subclassing: rendering
     */
    createTagsEl() {
        const wrap = document.createElement('span');
        wrap.className = this.classIdMap.tagsClass;
        for (const item of this.chosenItems) {
            wrap.appendChild(this.createTagEl(item));
        }
        return wrap;
    }
    /**
     * Build one removable tag chip: its content (from `createTagContentEl`, else
     * plain `itemToString` in a span of its own) plus its remove (x) button (from
     * `createTagRemoveButtonEl`). The content element carries the item's `lang`
     * from `itemToLang` when it returns one; the button never does.
     * - The content element gets `aria-hidden="true"`. The chip sits in the
     *   trigger buttons strip, a toolbar, where only the buttons speak: the
     *   item text already reaches assistive technology through the trigger's
     *   value and through the remove button's name.
     * - A chip whose item is effectively disabled gets `aria-disabled="true"` +
     *   `tagDisabledClass`, and its x turns inert - mirroring a disabled option
     *   row.
     * - Override for full control of the chip container; override the two
     *   sub-parts for content-only / remove-button-only changes.
     * @group Subclassing: rendering
     */
    createTagEl(item) {
        const tag = document.createElement('span');
        tag.className = this.classIdMap.tagClass;
        // Same null-branch shape as createPopupListItemEl / createGroupEl: null = plain-text
        // default. The text sits in its own span so the item's `lang` covers the
        // text and not the remove button, whose name mixes pack and item text.
        const content = this.createTagContentEl(item);
        const lang = this.itemToLang(item);
        if (content === null) {
            const text = document.createElement('span');
            text.className = this.classIdMap.tagTextClass;
            text.textContent = this.itemToString(item);
            text.setAttribute('aria-hidden', 'true');
            this.commitLangToDom(text, lang);
            tag.appendChild(text);
        }
        else {
            // App-owned content: the library sets or overwrites the attribute when the
            // function returns a code, and never removes it.
            if (lang !== null) {
                this.commitLangToDom(content, lang);
            }
            content.setAttribute('aria-hidden', 'true');
            tag.appendChild(content);
        }
        if (this.isItemEffectivelyDisabled(item)) {
            // Mirror createPopupListItemEl's disabled marking: aria-disabled + the class grey the
            // chip so its inert x reads as disabled, not broken (A11Y.md Tags).
            tag.setAttribute('aria-disabled', 'true');
            tag.classList.add(this.classIdMap.tagDisabledClass);
        }
        tag.appendChild(this.createTagRemoveButtonEl(item));
        return tag;
    }
    /**
     * Build one chip's remove (x) button. The library owns the button + its click
     * (`stopPropagation` so it never toggles the popup, then the gated toggle,
     * which `onChosenChanging` and `onBeforeChange` may stop, else `toggleItem`; a no-op
     * while the whole control OR the item itself is disabled) +
     * `aria-label` (from `itemToTagRemoveButtonAriaLabel`). An effectively-disabled
     * item's button also gets `aria-disabled="true"`.
     * - The trigger buttons strip owns its `tabindex`: one button of the strip
     *   is the Tab stop.
     * - An override returns a `button` element: the strip's Tab stop and arrow
     *   keys reach `button` elements only.
     * - After a removal by keyboard, focus moves to the next chip's button, else
     *   to the previous one, else to the trigger when no chip is left
     *   (`commitTagsElToDom`).
     * - `createTagRemoveButtonContentElFn` optionally fills the icon, else the
     *   theme's CSS glyph.
     * - Mirrors the clear button's `createTriggerClearButtonEl`. Override for
     *   full control of the button element.
     * @group Subclassing: rendering
     */
    createTagRemoveButtonEl(item) {
        const btn = document.createElement('button');
        btn.type = 'button';
        btn.className = this.classIdMap.tagRemoveButtonClass;
        btn.tabIndex = -1;
        btn.setAttribute('aria-label', this.itemToTagRemoveButtonAriaLabel(item));
        if (this.isItemEffectivelyDisabled(item)) {
            btn.setAttribute('aria-disabled', 'true');
        }
        const icon = this.createTagRemoveButtonContentEl(item);
        if (icon !== null) {
            btn.appendChild(icon);
        }
        // Keep DOM focus where it is: a pointer press leaves focus on the trigger
        // or the filter input. A mousedown would focus the button, and focus
        // entering the trigger buttons strip closes an open popup, so the click
        // would close the popup it was used beside. Same rule as the popup's
        // mousedown (A11Y.md).
        btn.addEventListener('mousedown', (ev) => { ev.preventDefault(); });
        btn.addEventListener('click', (ev) => {
            ev.stopPropagation();
            // Tag chips sit in the trigger buttons strip, reachable while the whole
            // control or the item itself is disabled. Both block removal (A11Y.md: only user
            // re-toggling is blocked; the item stays chosen). toggleItem stays
            // disabled-blind so the programmatic channel matches native <select>.
            if (this.isDisabled()) {
                return;
            }
            if (this.isItemEffectivelyDisabled(item)) {
                return;
            }
            this.focusTriggerIfUnfocused();
            // The focus may run onFocus; a listener that disabled or destroyed the
            // control, removed the item, or reloaded it as a disabled object leaves
            // nothing for this click to remove, and a toggle would add a removed
            // item back. The checks read the chosen entry as it stands now, since a
            // reload swaps the stored object for a compare-equal one. A listener
            // that opened the popup or loaded enabled items does not stop the
            // removal.
            if (this.destroyed || this.isDisabled()) {
                return;
            }
            const compareFn = this.settings.compareFn;
            // By index: an item may itself be `undefined`, which `find` could not tell from no entry.
            const at = this.chosenItems.findIndex(c => compareFn(c, item));
            if (at < 0) {
                return;
            }
            const current = this.chosenItems[at];
            if (this.isItemEffectivelyDisabled(current)) {
                return;
            }
            this.withUserChangeSource(() => this.requestAndToggle(current));
        });
        return btn;
    }
    /**
     * One chip's remove-button visible content (its x icon). Mirrors
     * `createTriggerClearButtonContentEl`.
     * - Default reads `createTagRemoveButtonContentElFn`; `null` (setting unset,
     *   or returned) = no icon - the theme's CSS glyph draws the x.
     * - Override only when extending; for one-off icons pass the setting.
     * @group Subclassing: rendering
     */
    createTagRemoveButtonContentEl(item) {
        const fn = this.settings.createTagRemoveButtonContentElFn;
        return fn ? fn(item) : null;
    }
    /**
     * Per-chip visible content in `'tags'` mode. Mirrors `createPopupListItemContentEl`.
     * Default reads `createTagContentElFn`, else `null` so `createTagEl` falls
     * back to plain text from `itemToString`.
     * @group Subclassing: rendering
     */
    createTagContentEl(item) {
        const fn = this.settings.createTagContentElFn;
        return fn ? fn(item) : null;
    }
    /**
     * Item -> its remove button's accessible name in `'tags'` mode.
     * - Default: `uiTranslationPack.tagRemoveButtonAriaLabel(itemToString(item))`.
     * - Override only when extending (e.g. a name from another item field);
     *   per-locale text goes through the `uiTranslationPack` setting.
     * @group Subclassing: semantics
     */
    itemToTagRemoveButtonAriaLabel(item) {
        return this.settings.uiTranslationPack.tagRemoveButtonAriaLabel(this.itemToString(item));
    }
    /**
     * No selection iff the chosen set is empty. Drives the trigger wrapper's `data-empty`.
     * @group Subclassing: semantics
     */
    isEmpty() {
        return this.chosenItems.length === 0;
    }
    /**
     * Toggle the item **after** Enter on its row while it is the active row, Space
     * on it while the filter is inactive, or a click on it, once `onChosenChanging`
     * and `onBeforeChange` allowed it. Multi mode keeps the popup open either way.
     *
     * > No **before** counterpart: there is no `onPopupListItemActivating`.
     * @group Subclassing: reactions
     */
    onPopupListItemActivated(item) {
        this.requestAndToggle(item);
    }
    /** The gated toggle shared by the row activation and the tag remove button. */
    requestAndToggle(item) {
        const { next, removed, changedItem } = this.nextAfterToggle(item);
        if (this.requestUserChange(next, removed ? 'unchoose' : 'choose', changedItem)) {
            this.toggleItem(item);
        }
    }
    /**
     * Clear button empties the chosen-items set to `[]`, after asking
     * `onChosenChanging` and `onBeforeChange`.
     * @group Subclassing: semantics
     */
    clearSelection() {
        if (this.requestUserChange([], 'clear')) {
            this.setChosenItems([]);
        }
    }
    /**
     * Subclass hook: called **before** a user interaction changes the chosen items,
     * with the way to stop it. Default no-op.
     *
     * > Pairs with `onChosenChanged`, which runs **after** the change was written.
     *
     * - Runs **before** the `onBeforeChange` setting. Both run, either may call
     *   `event.preventDefault()`.
     * - The parameters are the setting's: the list about to be set, the
     *   current one, the event.
     * @group Subclassing: reactions
     */
    onChosenChanging(_nextChosenItems, _previousChosenItems, _event) { }
    requestUserChange(next, reason, item) {
        const previous = this.chosenItems;
        if (this.arraysEqual(next, previous)) {
            return false;
        }
        const revision = this.changeRevision;
        const allowed = this.dispatchBeforeChange(reason === 'choose' || reason === 'unchoose' ? { reason, item: item } : { reason }, (event) => {
            this.onChosenChanging(next, previous, event);
            const fn = this.settings.onBeforeChange;
            fn?.(next, previous, event);
        });
        // A setter called inside the handlers wins, setItems included: the pending
        // change is dropped, even when the handler restored the previous value.
        return allowed && this.changeRevision === revision;
    }
    /**
     * Build the choose-all row (`chooseAllRow` setting), the listbox's leading
     * `role="option"` row.
     * - The library calls it on every full list render (`renderPopupList`), and
     *   when a toggle rebuilds the row in place (`replaceChooseAllRowElInDom`).
     *   You never call it.
     * - To change only what the row shows, do not override this: pass the
     *   `createChooseAllRowContentElFn` setting.
     * - To change the element itself, override it, call
     *   `super.createPopupListChooseAllRowEl()`, and edit the returned element.
     *   Keep the `id`, the `role` and `aria-selected`; put no focusable control
     *   inside.
     *   - `super` returns `null` in two cases; return `null` then too:
     *     - the `chooseAllRow` setting is off;
     *     - no visible item is enabled, so nothing is actionable.
     * - `data-chosen-state` is `none`, `some` or `all`: a CSS styling hook.
     * - `aria-selected` is `"true"` when every visible enabled item is chosen,
     *   and `"false"` otherwise.
     * - The accessible name and the visible text come from
     *   `uiTranslationPack.chooseAllRowText(chosenCount, totalCount)`, counted
     *   over the visible enabled subset.
     * - `null` means no row.
     * - After this returns, the library adds `aria-posinset` and
     *   `aria-setsize`: the row is a non-item row, so its list always gets them.
     * @group Subclassing: rendering
     */
    createPopupListChooseAllRowEl() {
        if (!this.settings.chooseAllRow) {
            return null;
        }
        const actionable = this.getVisibleEnabledItems();
        if (actionable.length === 0) {
            return null;
        }
        const chosenCount = actionable.filter(i => this.isChosen(i)).length;
        const state = chosenCount === 0 ? 'none' : chosenCount === actionable.length ? 'all' : 'some';
        const el = document.createElement('div');
        el.id = `${this.classIdMap.popupListId}-choose-all`;
        el.className = `${this.classIdMap.popupListRowClass} ${this.classIdMap.chooseAllRowClass}`;
        el.setAttribute('role', 'option');
        el.setAttribute('data-chosen-state', state);
        // aria-selected has no `mixed`, and aria-checked, which has one, must not
        // join aria-selected in one listbox (APG listbox pattern): the
        // indeterminate state is conveyed by the visual (data-chosen-state) + the
        // counting accessible name only.
        el.setAttribute('aria-selected', String(state === 'all'));
        const text = this.settings.uiTranslationPack.chooseAllRowText(chosenCount, actionable.length);
        const content = this.createChooseAllRowContentEl(state, chosenCount, actionable.length);
        if (content === null) {
            // Default content: just the counting text - its numbers already carry
            // the tri-state, and the library ships no default indicator anywhere
            // (DESIGN.md "Choose-all default: plain counting text").
            el.textContent = text;
        }
        else {
            // Custom content fills the visuals only; the accessible name stays the
            // counting text (same pinning as createPopupListItemEl's custom content).
            el.setAttribute('aria-label', text);
            el.appendChild(content);
        }
        el.addEventListener('click', () => {
            // Focus-then-activate, mirroring the item click wiring, guard included.
            const stamp = this.captureStateStamp();
            this.focusChooseAllRow();
            if (this.stateMovedSince(stamp)) {
                return;
            }
            this.withUserChangeSource(() => this.onChooseAllRowActivated());
        });
        return el;
    }
    /**
     * The choose-all row's visible content (rich tri-state). Mirrors
     * `createPopupListItemContentEl`.
     * - Default reads `createChooseAllRowContentElFn`; `null` (setting unset,
     *   or returned) = the default content: plain text from
     *   `uiTranslationPack.chooseAllRowText`.
     * - Override only when extending; for one-off content pass the setting.
     * @group Subclassing: rendering
     */
    createChooseAllRowContentEl(chosenState, chosenCount, totalCount) {
        const fn = this.settings.createChooseAllRowContentElFn;
        return fn ? fn(chosenState, chosenCount, totalCount) : null;
    }
    /**
     * Runs **after** Enter on the active choose-all row, Space on it while the
     * filter is inactive, or a click on it, as the library's response to that
     * input.
     *
     * > No **before** counterpart: there is no `onChooseAllRowActivating`.
     *
     * - Computes what {@link toggleAllVisible} would commit.
     * - Asks `onChosenChanging` and `onBeforeChange` with that value.
     * - Then commits exactly that value, even if a handler changed which items
     *   are enabled.
     * @group Subclassing: reactions
     */
    onChooseAllRowActivated() {
        const next = this.nextAfterToggleAllVisible();
        if (next === null) {
            return;
        }
        if (this.requestUserChange(next, next.length === 0 ? 'clear' : 'set')) {
            this.setChosenItems(next);
        }
    }
    /**
     * Mark each item with `aria-selected` reflecting its chosen state.
     * @group Subclassing: rendering
     */
    createPopupListItemEl(item, index) {
        const el = super.createPopupListItemEl(item, index);
        el.setAttribute('aria-selected', String(this.isChosen(item)));
        return el;
    }
    /**
     * Re-match the chosen entries against the new list **after** `setItems` installs it.
     *
     * > No **before** counterpart: there is no `onItemsChanging`.
     *
     * - Entries the list no longer holds (by `compareFn`) are dropped and
     *   `onChange` fires for the drop.
     * - When the list holds a compareFn-equal but DIFFERENT object (`track by`
     *   style reload: same key, fresh fields), the stored reference is swapped
     *   to the list's object. A reference swap is not a logical change, so it
     *   does not fire `onChange`.
     * - The trigger content re-renders after every `setItems`, swap or not.
     * - Why: the count text shows the list total, and a custom
     *   `createTriggerContentElFn` receives `items`.
     * - The arrow re-renders only when a chosen entry is dropped, because that
     *   runs the whole trigger.
     * - `triggerDisplay: 'tags'` is opt-in; `'count'` is the default.
     * - When `triggerDisplay` is `'tags'`, that render is one chip per chosen
     *   item per `setItems`, unless `createTriggerContentElFn` replaces the
     *   content.
     * - That cost is acceptable: `setItems` is a bulk call.
     * @group Subclassing: reactions
     */
    onItemsChanged() {
        this.itemPositionCache = null;
        const previous = this.chosenItems;
        let swapped = false;
        const nextChosen = [];
        const compareFn = this.settings.compareFn;
        for (const c of previous) {
            const idx = this.items.findIndex(item => compareFn(item, c));
            if (idx < 0) {
                continue;
            }
            const matched = this.items[idx];
            // SameValueZero, so a NaN item matching itself is not a swap.
            if (!defaultCompareFn(matched, c)) {
                swapped = true;
            }
            nextChosen.push(matched);
        }
        const ordered = this.orderChosen(nextChosen);
        // A dropped entry or a new order is visible state: the trigger re-renders
        // and onChange fires, like the order-sensitive setChosenItems.
        if (!this.arraysEqual(ordered, previous)) {
            this.chosenItems = ordered;
            this.renderTrigger();
            // setItems rendered the open popup before this reconciliation, so rows
            // whose content read the chosen list must be rebuilt from the final one.
            if (this.isOpened()) {
                this.renderPopupList();
            }
            this.fireChange(previous, 'items');
            return;
        }
        if (swapped) {
            this.chosenItems = ordered;
        }
        // The count text reads the list total and a custom trigger receives
        // `items`, so every list change refreshes the content; the arrow does not
        // depend on the list.
        this.renderTriggerContent();
    }
    /**
     * Decide which row is active when the popup opens.
     * - The library calls it inside `open()`, once per open, after the rows
     *   are built. You never call it.
     * - To pick another row, override it and set the row with
     *   `setFocusedIndex` or `focusChooseAllRow`.
     * - `setFocusedIndex` takes an index into `getVisibleItems()`, which
     *   counts item rows only; the choose-all row and the action rows have no
     *   index.
     * - To fall back to this method's choice, call `super.focusInitial()`, but
     *   only when the override set no row.
     * - The active row is the `role="option"` row that `aria-activedescendant`
     *   names on the `role="combobox"` element: the trigger, or the filter
     *   input while the filter is active.
     * - "Focus" in the names `focusInitial`, `setFocusedIndex` and
     *   `focusChooseAllRow` means the active row, not DOM focus.
     * - DOM focus never moves to the active row. While the filter is active,
     *   the open moves DOM focus to the filter input.
     * - `open()` clears the active row before the call, so the popup opens
     *   with no active row unless this method sets one.
     * - Visible items are the items in `getVisibleItems()`, the items that
     *   have a row in the list.
     *   - While `hideChosenRows` is on, a chosen item is not visible.
     * - Makes the row of the first entry of `getChosenItems()` active, if that
     *   item is visible and enabled.
     *   - `getChosenItems()` follows `chosenItemsOrder`, not the order of the
     *     rows, so its first entry need not be the topmost chosen row.
     * - Otherwise makes the choose-all row active, when it is rendered.
     *   - The choose-all row is the first `role="option"` row of the listbox,
     *     so making it active at open lets a keyboard user find it without
     *     pressing an arrow key.
     * - Otherwise makes the first enabled visible item the active row.
     * - This order is the one `docs/llm/A11Y.md` rules, and an action row is
     *   never the active row at open.
     * - Each step replaces any row set before this method runs.
     * - Does nothing when no visible item is enabled.
     *   - The choose-all row is rendered only while a visible item is enabled.
     * @group Subclassing: focus
     */
    focusInitial() {
        const list = this.getVisibleItems();
        // By length: a chosen item may itself be `undefined`.
        if (this.chosenItems.length > 0) {
            const firstChosen = this.chosenItems[0];
            const compareFn = this.settings.compareFn;
            const idx = list.findIndex(i => compareFn(i, firstChosen));
            if (idx >= 0 && !this.isItemEffectivelyDisabled(list[idx])) {
                this.setFocusedIndex(idx);
                return;
            }
        }
        if (this.focusChooseAllRow()) {
            return;
        }
        const first = this.findNextEnabledIndex(0, 1, list);
        if (first >= 0) {
            this.setFocusedIndex(first);
        }
    }
    itemPositions() {
        const cache = this.itemPositionCache;
        if (cache !== null && cache.items === this.items) {
            return cache.positions;
        }
        const positions = new Map();
        this.items.forEach((item, i) => { if (!positions.has(item)) {
            positions.set(item, i);
        } });
        this.itemPositionCache = { items: this.items, positions };
        return positions;
    }
    /**
     * Apply `chosenItemsOrder`. `'as-chosen'` returns the array as is;
     * `'as-listed'` sorts by position in the item list, unlisted entries last
     * in their given order.
     */
    orderChosen(chosen) {
        if (this.settings.chosenItemsOrder !== 'as-listed' || chosen.length < 2) {
            return chosen;
        }
        const items = this.items;
        const compareFn = this.settings.compareFn;
        let positionOf;
        if (compareFn === defaultCompareFn) {
            const positions = this.itemPositions();
            positionOf = (c) => positions.get(c) ?? items.length;
        }
        else {
            positionOf = (c) => { const i = items.findIndex(item => compareFn(item, c)); return i < 0 ? items.length : i; };
        }
        return chosen
            .map((c, i) => ({ c, pos: positionOf(c), i }))
            .sort((a, b) => a.pos - b.pos || a.i - b.i)
            .map(e => e.c);
    }
    arraysEqual(a, b) {
        if (a.length !== b.length) {
            return false;
        }
        const eq = this.settings.compareFn;
        for (let i = 0; i < a.length; i++) {
            if (!eq(a[i], b[i])) {
                return false;
            }
        }
        return true;
    }
    fireChange(previousChosenItems, reason, item) {
        this.changeRevision++;
        // Consume the source before any observer runs: a programmatic setter
        // called from inside onChange (or a subclass reaction) must report
        // 'api', not inherit the outer interaction's 'user' attribution.
        const source = this.changeSource;
        this.changeSource = 'api';
        // The item shape for the two single-item reasons, even when T admits undefined.
        const meta = reason === 'choose' || reason === 'unchoose'
            ? { source, reason, item: item }
            : { source, reason };
        this.onChosenChanged();
        const onChange = this.settings.onChange;
        onChange?.(this.chosenItems, previousChosenItems, meta);
        // Action rows read live state; after the handler ran, so a row's text may show what it wrote.
        this.replacePopupListActionRowElsInDom();
    }
}

// Query-match highlighting for item content, exported like the grouping
// gather: pure (text, query) -> detached DOM, no instance state.
/**
 * Build a detached `<span>` of `text` with every `query` match wrapped for
 * highlighting.
 * - Each case-insensitive occurrence of `query` becomes a `<mark>` element;
 *   everything else stays plain text nodes.
 * - Matching mirrors the built-in filter exactly: `toLowerCase` on both
 *   sides, no trimming, scanned left to right without overlap.
 * - If `query` is `''`, the span holds the plain text and no `<mark>`.
 * - `createMatchElFn` replaces the default `<mark>` builder. It receives the
 *   matched text and must return a fully built element: the helper inserts
 *   it as-is and does not put the text inside for you.
 * - If a custom `filterFn` drives your matching, the helper cannot know its
 *   match ranges: it always marks plain substring occurrences.
 * - Intended for `createPopupListItemContentElFn` / `createPopupListItemContentEl`: they re-run
 *   on every filter keystroke, so the marks stay in sync with the query. The
 *   option's accessible name is unaffected (it comes from `itemToString`).
 * - Rare edge: if lower-casing changes the string's length (a Unicode
 *   expansion, e.g. dotted capital I, U+0130), the span degrades to plain
 *   unmarked text instead of marking wrong ranges.
 * @group Filtering
 */
function createHighlightedTextEl(text, query, createMatchElFn) {
    const span = document.createElement('span');
    const lowerText = text.toLowerCase();
    const lowerQuery = query.toLowerCase();
    // Offsets found in lowerText are applied to text; valid only while
    // lower-casing kept both lengths (lowercase mappings only ever expand).
    if (query === '' || lowerText.length !== text.length || lowerQuery.length !== query.length) {
        span.textContent = text;
        return span;
    }
    let pos = 0;
    while (true) {
        const idx = lowerText.indexOf(lowerQuery, pos);
        if (idx === -1) {
            break;
        }
        if (idx > pos) {
            span.append(text.slice(pos, idx));
        }
        const matchedText = text.slice(idx, idx + query.length);
        if (createMatchElFn) {
            span.append(createMatchElFn(matchedText));
        }
        else {
            const mark = document.createElement('mark');
            mark.textContent = matchedText;
            span.append(mark);
        }
        pos = idx + query.length;
    }
    if (pos < text.length) {
        span.append(text.slice(pos));
    }
    return span;
}

// Opt-in icon helpers. None of these is used by the library by default; pass
// the arrow ones via `settings.createTriggerArrowContentElFn`, or use the checkmark / checkbox
// ones inside a custom item renderer (override `createPopupListItemEl` / `itemToString`)
// so people who do not want to pull in mdi / FontAwesome still get sensible
// built-ins. All paths use fill="currentColor" so they inherit the
// surrounding text color (light / dark color schemes "just work"). Paths are from
// Material Design Icons (MIT). The up-down arrows are drawn here from the shapes
// of the down arrows.
const SVG_NS = 'http://www.w3.org/2000/svg';
function createSvgEl(viewBox, pathD, size) {
    const svg = document.createElementNS(SVG_NS, 'svg');
    svg.setAttribute('width', String(size));
    svg.setAttribute('height', String(size));
    svg.setAttribute('viewBox', viewBox);
    svg.setAttribute('aria-hidden', 'true');
    svg.setAttribute('focusable', 'false');
    const path = document.createElementNS(SVG_NS, 'path');
    path.setAttribute('d', pathD);
    path.setAttribute('fill', 'currentColor');
    svg.appendChild(path);
    return svg;
}
// The shipped themes turn the arrow half a turn while the popup is open,
// except an arrow that carries this attribute.
const NO_ROTATE_ATTRIBUTE = 'data-llselect-no-rotate';
/**
 * Solid filled triangle pointing down. Sized to roughly match the chevron's
 * visual weight (MDI's `arrow_drop_down` path occupies a small portion of
 * its 24x24 viewBox and looks too small next to other icons).
 * @group Icons
 * @category Arrows
 */
function createTriangleDownSvgEl(opts = {}) {
    return createSvgEl('0 0 24 24', 'M4 8l8 10 8-10z', opts.size ?? 16);
}
/**
 * Two solid filled triangles, the upper one pointing up and the lower one pointing down.
 * - Each triangle is the {@link createTriangleDownSvgEl} triangle at three quarters of its size.
 * - The element carries the attribute `data-llselect-no-rotate`, so the shipped themes do not turn it while the popup is open.
 * - The icon looks the same after a half turn, so a browser that still turns it shows the same icon once the turn ends.
 * @group Icons
 * @category Arrows
 */
function createTriangleUpDownSvgEl(opts = {}) {
    const svg = createSvgEl('0 0 24 24', 'M6 11l6-7.5 6 7.5zM6 13l6 7.5 6-7.5z', opts.size ?? 16);
    svg.setAttribute(NO_ROTATE_ATTRIBUTE, '');
    return svg;
}
/**
 * Material Design `expand_more` chevron pointing down (filled outline).
 * @group Icons
 * @category Arrows
 */
function createChevronDownSvgEl(opts = {}) {
    return createSvgEl('0 0 24 24', 'M16.59 8.59 12 13.17 7.41 8.59 6 10l6 6 6-6z', opts.size ?? 16);
}
/**
 * Two chevrons, the upper one pointing up and the lower one pointing down.
 * - Each chevron is the {@link createChevronDownSvgEl} chevron at its full size.
 * - The element carries the attribute `data-llselect-no-rotate`, so the shipped themes do not turn it while the popup is open.
 * - The icon looks the same after a half turn, so a browser that still turns it shows the same icon once the turn ends.
 * @group Icons
 * @category Arrows
 */
function createChevronUpDownSvgEl(opts = {}) {
    const svg = createSvgEl('0 0 24 24', 'M16.59 10.41 12 5.83 7.41 10.41 6 9l6-6 6 6zM16.59 13.59 12 18.17 7.41 13.59 6 15l6 6 6-6z', opts.size ?? 16);
    svg.setAttribute(NO_ROTATE_ATTRIBUTE, '');
    return svg;
}
/**
 * Standalone checkmark (no box). Useful as a "selected" indicator in single
 * mode, or as a lightweight chosen marker in multi mode.
 * @group Icons
 * @category Checkmarks & checkboxes
 */
function createCheckmarkSvgEl(opts = {}) {
    return createSvgEl('0 0 24 24', 'M21,7L9,19L3.5,13.5L4.91,12.09L9,16.17L19.59,5.59L21,7Z', opts.size ?? 16);
}
const OUTLINED_CHECKBOX_PATHS = {
    // mdi checkbox-blank-outline
    unchecked: 'M19,3H5C3.89,3 3,3.89 3,5V19A2,2 0 0,0 5,21H19A2,2 0 0,0 21,19V5C21,3.89 20.1,3 19,3M19,5V19H5V5H19Z',
    // mdi checkbox-outline (box + tick)
    checked: 'M19,3H5A2,2 0 0,0 3,5V19A2,2 0 0,0 5,21H19A2,2 0 0,0 21,19V5A2,2 0 0,0 19,3M19,5V19H5V5H19M10,17L6,13L7.41,11.58L10,14.17L16.59,7.58L18,9',
    // mdi minus-box-outline (box + dash)
    indeterminate: 'M19,19V5H5V19H19M19,3A2,2 0 0,1 21,5V19A2,2 0 0,1 19,21H5A2,2 0 0,1 3,19V5C3,3.89 3.9,3 5,3H19M17,11V13H7V11H17Z',
};
/** Map the choose-all row's chosen-state vocabulary onto the icon vocabulary. */
function resolveCheckboxState(raw) {
    return raw === 'none' ? 'unchecked' : raw === 'some' ? 'indeterminate' : raw === 'all' ? 'checked' : raw;
}
/**
 * Outlined checkbox icon: box border with the tick (`checked`) / dash
 * (`indeterminate`) drawn inside, all in `currentColor`; the filled twin is
 * {@link createFilledCheckboxSvgEl}. Intended for multi-select item rows and
 * the choose-all control. Decorative only (`aria-hidden`); the real state is
 * carried by `aria-selected` on the item or `aria-checked` on the control.
 * @group Icons
 * @category Checkmarks & checkboxes
 */
function createOutlinedCheckboxSvgEl(opts = {}) {
    const state = resolveCheckboxState(opts.state ?? 'unchecked');
    return createSvgEl('0 0 24 24', OUTLINED_CHECKBOX_PATHS[state], opts.size ?? 16);
}
const FILLED_CHECKBOX_PATHS = {
    // Material's unchecked is the same outline box in both looks.
    unchecked: OUTLINED_CHECKBOX_PATHS.unchecked,
    // mdi checkbox-marked (solid box, tick cut out)
    checked: 'M10,17L5,12L6.41,10.58L10,14.17L17.59,6.58L19,8M19,3H5C3.89,3 3,3.89 3,5V19A2,2 0 0,0 5,21H19A2,2 0 0,0 21,19V5C21,3.89 20.1,3 19,3Z',
    // mdi minus-box (solid box, dash cut out)
    indeterminate: 'M17,13H7V11H17M19,3H5C3.89,3 3,3.89 3,5V19A2,2 0 0,0 5,21H19A2,2 0 0,0 21,19V5C21,3.89 20.1,3 19,3Z',
};
/**
 * Material-look checkbox icon: a solid rounded box with the tick (`checked`)
 * / dash (`indeterminate`) cut out; `unchecked` draws the same outline box as
 * {@link createOutlinedCheckboxSvgEl}. Same options, including the chosen-state
 * vocabulary. Decorative only (`aria-hidden`); the real state is carried by
 * `aria-selected` on the item or `aria-checked` on the control.
 * @group Icons
 * @category Checkmarks & checkboxes
 */
function createFilledCheckboxSvgEl(opts = {}) {
    const state = resolveCheckboxState(opts.state ?? 'unchecked');
    return createSvgEl('0 0 24 24', FILLED_CHECKBOX_PATHS[state], opts.size ?? 16);
}

/**
 * The package entry: the two select component classes, their settings types,
 * and the SVG icon builders. Language packs live in `@llselect/core/i18n`, and
 * behavior presets in `@llselect/core/behavior-presets`.
 * @module @llselect/core
 */
/**
 * Library version. Mirrors package.json `version` (smoke-test guarded).
 * @group Metadata
 */
const version = '0.0.15';

export { LLSelectBase, LLSelectMultiple, LLSelectSingle, createCheckmarkSvgEl, createChevronDownSvgEl, createChevronUpDownSvgEl, createFilledCheckboxSvgEl, createHighlightedTextEl, createOutlinedCheckboxSvgEl, createTriangleDownSvgEl, createTriangleUpDownSvgEl, defaultBehaviorOfScrollGesture, defaultBehaviorOfZoomGesture, gatherItemsByGroupKey, version };
//# sourceMappingURL=index.mjs.map