Skip to content

Type to search the docs, API, and blog.

↑↓ navigate↵ openesc close
  • Zazz 0.14 alpha

    API

    Drawer

    A bottom sheet on the native `<dialog>`, dragged down to dismiss.

    Installation

    Source
    pnpm dlx zazz-ui add drawer
    npx zazz-ui add drawer
    yarn dlx zazz-ui add drawer
    bunx zazz-ui add drawer

    Also adds fields, kbd, button, dialog, which it depends on. Run zazz-ui init first if the project has no zazz/ folder yet.

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <!-- Paint the right theme (background, form controls, scrollbars) before CSS loads -->
    <meta name="color-scheme" content="light dark">
    <!-- Zazz styles: base layers, then fields, kbd, button, dialog, drawer in cascade order -->
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@zazz-ui/core@0.14.1/src/base/_layers.css">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@zazz-ui/core@0.14.1/src/base/_variables.css">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@zazz-ui/core@0.14.1/src/base/_shadows.css">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@zazz-ui/core@0.14.1/src/base/_breakpoints.css">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@zazz-ui/core@0.14.1/src/base/_reset.css">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@zazz-ui/core@0.14.1/src/base/_typography.css">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@zazz-ui/core@0.14.1/src/base/_view-transitions.css">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@zazz-ui/core@0.14.1/src/primitives/fields/fields.css">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@zazz-ui/core@0.14.1/src/primitives/kbd/kbd.css">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@zazz-ui/core@0.14.1/src/primitives/button/button.css">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@zazz-ui/core@0.14.1/src/primitives/dialog/dialog.css">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@zazz-ui/core@0.14.1/src/primitives/drawer/drawer.css">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@zazz-ui/core@0.14.1/src/base/_properties.css">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@zazz-ui/core@0.14.1/src/base/_properties-sm.css">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@zazz-ui/core@0.14.1/src/base/_properties-md.css">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@zazz-ui/core@0.14.1/src/base/_properties-lg.css">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@zazz-ui/core@0.14.1/src/base/_properties-xl.css">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@zazz-ui/core@0.14.1/src/base/_properties-2xl.css">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@zazz-ui/core@0.14.1/src/base/_properties-disabled.css">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@zazz-ui/core@0.14.1/src/base/_properties-active.css">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@zazz-ui/core@0.14.1/src/base/_properties-focus-visible.css">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@zazz-ui/core@0.14.1/src/base/_properties-focus-within.css">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@zazz-ui/core@0.14.1/src/base/_properties-hover.css">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@zazz-ui/core@0.14.1/src/base/_properties-checked.css">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@zazz-ui/core@0.14.1/src/base/_properties-current.css">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@zazz-ui/core@0.14.1/src/base/_properties-open.css">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@zazz-ui/core@0.14.1/src/base/_properties-stuck.css">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@zazz-ui/core@0.14.1/src/base/_properties-starting.css">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@zazz-ui/core@0.14.1/src/base/_utilities-tier-sm.css">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@zazz-ui/core@0.14.1/src/base/_utilities-tier-md.css">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@zazz-ui/core@0.14.1/src/base/_utilities-tier-lg.css">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@zazz-ui/core@0.14.1/src/base/_utilities-tier-xl.css">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@zazz-ui/core@0.14.1/src/base/_utilities-tier-2xl.css">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@zazz-ui/core@0.14.1/src/base/_utilities-tier-disabled.css">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@zazz-ui/core@0.14.1/src/base/_utilities-tier-active.css">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@zazz-ui/core@0.14.1/src/base/_utilities-tier-focus-visible.css">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@zazz-ui/core@0.14.1/src/base/_utilities-tier-focus-within.css">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@zazz-ui/core@0.14.1/src/base/_utilities-tier-hover.css">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@zazz-ui/core@0.14.1/src/base/_utilities-tier-checked.css">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@zazz-ui/core@0.14.1/src/base/_utilities-tier-current.css">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@zazz-ui/core@0.14.1/src/base/_utilities-tier-open.css">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@zazz-ui/core@0.14.1/src/base/_utilities-tier-stuck.css">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@zazz-ui/core@0.14.1/src/base/_utilities-tier-starting.css">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@zazz-ui/core@0.14.1/src/base/_utilities-flow.css">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@zazz-ui/core@0.14.1/src/base/_utilities-grid.css">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@zazz-ui/core@0.14.1/src/base/_utilities-spacing.css">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@zazz-ui/core@0.14.1/src/base/_utilities-margin.css">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@zazz-ui/core@0.14.1/src/base/_utilities-sizing.css">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@zazz-ui/core@0.14.1/src/base/_utilities-typography.css">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@zazz-ui/core@0.14.1/src/base/_utilities-color.css">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@zazz-ui/core@0.14.1/src/base/_utilities-effects.css">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@zazz-ui/core@0.14.1/src/base/_utilities-box.css">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@zazz-ui/core@0.14.1/src/base/_utilities-pseudo.css">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@zazz-ui/core@0.14.1/src/base/_defaults.css">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@zazz-ui/core@0.14.1/src/base/_utilities-sr.css">
    <!-- Import map: bare specifiers in Zazz scripts resolve to pinned, SRI-checked files -->
    <script type="importmap">
    {
      "imports": {
        "signal-polyfill": "https://cdn.jsdelivr.net/npm/signal-polyfill@0.2.2/dist/index.js"
      },
      "integrity": {
        "https://cdn.jsdelivr.net/npm/signal-polyfill@0.2.2/dist/index.js": "sha384-0OqM7OXGT6Oz1z98u/geiFn/FUyz4iWexkXHCvbIGXRRDXl6bp6IKc0j78AQ6DEK"
      }
    }
    </script>
    <!-- Polyfill: Interest Invokers (interestfor) — native in Chromium only -->
    <script type="module" src="https://cdn.jsdelivr.net/npm/invokers@2.2.2/dist/esm/production/interest.js" integrity="sha384-hR2BVNtsS7fIIMwOm+f7MY0JZfuByGhQQfevCBB6evFATKzBsTw0JzH/RxD94z2T" crossorigin="anonymous"></script>
    <!-- Zazz behavior: side-effect modules by tag; the rest via module imports -->
    <script type="module" src="https://cdn.jsdelivr.net/npm/@zazz-ui/core@0.14.1/src/base/dialog-lifecycle.js"></script>
    <script type="module" src="https://cdn.jsdelivr.net/npm/@zazz-ui/core@0.14.1/src/base/gesture.js"></script>
    <script type="module" src="https://cdn.jsdelivr.net/npm/@zazz-ui/core@0.14.1/src/primitives/drawer/drawer.js"></script>
    <!-- Theme: apply the persisted (or preferred) scheme before first paint -->
    <script>
      (() => {
        try {
          // A stored choice pins the scheme with data-theme; with no choice the
          // page follows the system scheme.
          const storedTheme = localStorage.getItem("theme");
          if (storedTheme === "dark" || storedTheme === "light") {
            document.documentElement.dataset.theme = storedTheme;
          }
        } catch {
          /* no storage access: follow the system scheme */
        }
      })();
    </script>

    A <head> that loads the base layers and drawer with its dependencies from jsDelivr, pinned to 0.14.1. To load the whole kit in two requests, see the CDN install.

    Examples

    Default

    Notification settings

    Drag the drawer down, or flick it, to dismiss it.

    Scrolling content scrolls first. Once it is at the top, pulling down moves the drawer; the handle always does.

    <button data-ui="button" type="button" command="show-modal" commandfor="drawer-example-1">
      Open drawer
    </button>
    <dialog id="drawer-example-1" data-ui="drawer" closedby="any">
      <div data-drawer-slot="handle"></div>
      <div data-drawer-slot="content">
        <header data-drawer-slot="header">
          <h2
            style="
              --font-size: var(--font-size-lg);
              --font-weight: strong;
              --font-family: var(--font-family-heading);
            "
          >
            Notification settings
          </h2>
          <p style="--text: var(--color-muted-foreground)">
            Drag the drawer down, or flick it, to dismiss it.
          </p>
        </header>
        <div data-drawer-slot="body">
          <p>
            Scrolling content scrolls first. Once it is at the top, pulling down moves the drawer; the
            handle always does.
          </p>
        </div>
        <footer data-drawer-slot="footer">
          <button data-ui="button" type="button" commandfor="drawer-example-1" command="close">
            Cancel
          </button>
          <button
            data-ui="button"
            data-button-variant="primary"
            type="button"
            commandfor="drawer-example-1"
            command="close"
          >
            Save
          </button>
        </footer>
      </div>
    </dialog>
    /**
     * drawer.css: Drawer ([data-ui~="drawer"] on native <dialog>; slots
     *             data-drawer-slot="handle | content | header | body | footer | close";
     *             <ui-drawer-indent> / [data-ui~="drawer-indent"], the page wrapper that
     *             scales back behind an open drawer)
     *
     * A bottom sheet: a modal dialog that rises from the bottom edge and is dragged
     * back down to dismiss. Alone (`data-ui="drawer"`) it is a drawer everywhere;
     * on a dialog (`data-ui="dialog drawer"`) it is a drawer below the sm band on a
     * touch screen and the plain dialog otherwise. `data-drawer-snap` gives it
     * resting heights; a drawer opened over another pushes that one back.
     *
     * @layer      variables, components
     * @requires   _layers.css, _variables.css, dialog.css (the native <dialog> motion, backdrop, and
     *             scroll lock in its reset layer; the surface and slots in the combined form)
     * @uses       Overrides --ui-dialog-* motion tokens: the dialog's open/close transition becomes a
     *             rise from the bottom edge, with the backdrop on the same duration and curve
     * @uses       translate — drawer.js writes the inline translate while a pointer drags the drawer
     *             (state `dragging`, transitions off); the dialog's transitions finish the release
     * @uses       Web Animations on ::backdrop — drawer.js scrubs a paused opacity animation so the
     *             backdrop fades with the drag without restyling the drawer's content on every move
     * @uses       @property (inherits: false) + `inherit` on ::backdrop — the same link in CSS, for
     *             an engine that cannot animate ::backdrop from script; where neither works the
     *             backdrop stays opaque until release
     * @uses       @media (width < 40rem) and (not (hover: hover)) — the combined form's drawer mode,
     *             the same phone test as dialog.css
     * @uses       scale, translate — the only properties the stack and the indent animate; the
     *             indent's corner radius is two corner pieces that scale up, so no border-radius or
     *             clip is animated and the page is never repainted for it
     * @uses       clip-path: inset() — a fixed rectangle while the page is indented, so the part of
     *             the page above and below the viewport stays out of the gaps the scale opens
     * @uses       :has() — the body takes the backing color while its page wrapper is indented
     * @uses       @starting-style — the corner pieces grow from nothing when they are generated
     * @uses       corner-shape — the corner pieces follow --radius-corner-shape where it is
     *             supported and are round elsewhere
     * @uses       env(safe-area-inset-top) — the indented page clears the status bar
     * @uses       env(safe-area-inset-bottom) — content clears the home indicator
     * @uses       visualViewport — drawer.js writes --_drawer-keyboard (the software
     *             keyboard's height) on the front drawer, and the sheet's bottom padding takes it,
     *             so content ends at the keyboard's top edge while the surface runs on under it
     * @uses       --_touch-min — the handle's hit area on touch screens
     * @tokens     --ui-drawer-* (@layer variables)
     */
    
    @layer variables {
      :root {
        /* surface */
        --ui-drawer-bg: var(--ui-dialog-bg);
        --ui-drawer-text: var(--ui-dialog-text);
        --ui-drawer-radius: var(--radius-xl);
        --ui-drawer-corner-shape: var(--ui-dialog-corner-shape);
        --ui-drawer-shadow: var(--shadow-lg);
    
        /* metrics: edge to edge, the layout-bleed band; cap it with a band to float a
           narrower sheet, e.g. min(var(--layout-sm), 100%) */
        --ui-drawer-w: 100%;
        --ui-drawer-max-h: calc(100dvb - var(--space-lg));
    
        /* stack: how much each drawer in front shrinks and lifts the one behind */
        --ui-drawer-stack-scale: 0.05;
        --ui-drawer-stack-lift: var(--space-sm);
        /* the page is already dimmed by the first drawer's backdrop */
        --ui-drawer-nested-backdrop-color: transparent;
    
        /* indent: how far each side of the page pulls in, how far it drops, the radius of
           its top corners, and the color behind it. Set these on :root: the body reads the
           backing color too. */
        --ui-drawer-indent-inset: calc(var(--spacing) * 3);
        --ui-drawer-indent-offset: calc(env(safe-area-inset-top, 0px) + var(--space-sm));
        --ui-drawer-indent-radius: var(--ui-drawer-radius);
        --ui-drawer-indent-bg: var(--color-background);
        --ui-drawer-indent-backing: var(--color-black);
    
        /* handle */
        --ui-drawer-handle-w: calc(var(--spacing) * 12);
        --ui-drawer-handle-h: calc(var(--spacing) * 1.25);
        --ui-drawer-handle-bg: var(--color-muted);
        --ui-drawer-handle-bg--hover: var(--color-muted-foreground);
        --ui-drawer-handle-bg--active: var(--color-muted-foreground);
        --ui-drawer-handle-bg--dragging: var(--color-foreground);
    
        /* motion: the iOS sheet curve, steep at the start so twice the default
           duration still reads as quick; 0s under reduced motion like the default */
        --ui-drawer-transition-duration: calc(var(--default-transition-duration) * 2);
        --ui-drawer-transition-timing-function: cubic-bezier(0.32, 0.72, 0, 1);
      }
    }
    
    /* Drawer mode flag, read by drawer.js; and the backdrop's drag opacity, written by it.
       Non-inheriting, so neither restyles the drawer's content. */
    @property --_drawer-mode {
      syntax: "*";
      inherits: false;
    }
    
    @property --_drawer-backdrop {
      syntax: "*";
      inherits: false;
    }
    
    /* Where a drawer with snap points rests, and how many drawers sit in front of it:
       both written by drawer.js when they change (the depth also while the front drawer
       is dragged), and non-inheriting, so neither restyles the drawer's content. */
    @property --_drawer-snap {
      syntax: "*";
      inherits: false;
    }
    
    @property --_drawer-depth {
      syntax: "*";
      inherits: false;
    }
    
    /* The software keyboard's height while the drawer is the front one, written by
       drawer.js from the visual viewport; the sheet's bottom padding takes it. */
    @property --_drawer-keyboard {
      syntax: "*";
      inherits: false;
    }
    
    /* The indent's measurements, written by drawer.js when a drawer opens, and how
       indented the page is (0 to 1): 1 from the `active` state, or the drag's own
       value while the last drawer is dragged. The corner pieces take them by explicit
       inheritance. The inset is typed so the script reads the hook in px. */
    @property --_drawer-indent-amount {
      syntax: "*";
      inherits: false;
    }
    
    @property --_drawer-indent-scale {
      syntax: "*";
      inherits: false;
    }
    
    @property --_drawer-indent-top {
      syntax: "*";
      inherits: false;
    }
    
    @property --_drawer-indent-bottom {
      syntax: "*";
      inherits: false;
    }
    
    @property --_drawer-indent-inset {
      syntax: "<length>";
      inherits: false;
      initial-value: 0px;
    }
    
    @layer ui.components {
      /* ===========================================================================
      DRAWER MODE: the declarations that make a dialog a bottom sheet. Written
      twice, because the two forms enter it under different conditions: the
      standalone form always, the combined form on a phone. Keep the two blocks
      identical apart from the --_dialog-* lines, which feed the dialog's own
      read chain in the combined form.
    
      The sheet extends --_bleed past the bottom edge (padding inside,
      an equal negative margin outside), so pulling it up against its resistance
      never opens a gap under it.
      =========================================================================== */
    
      :where([data-ui~="drawer"]:not([data-ui~="dialog"])) {
        --_drawer-mode: 1;
        --_bleed: calc(var(--spacing) * 12);
        --_handle-display: block;
        --_content-row: 2;
        --_header-select: none;
    
        --ui-dialog-transition-duration: var(--ui-drawer-transition-duration);
        --ui-dialog-transition-timing-function: var(--ui-drawer-transition-timing-function);
        --ui-dialog-backdrop-transition-duration: var(--ui-dialog-transition-duration);
        --ui-dialog-backdrop-transition-timing-function: var(--ui-drawer-transition-timing-function);
        --ui-dialog-transition-delay--end: 0ms;
        --ui-dialog-opacity--start: 1;
        --ui-dialog-scale--start: 1;
        --ui-dialog-translate--start: 0, 100%, 0;
    
        margin-block: auto calc(var(--_bleed) * -1);
        margin-inline: auto;
        /* the keyboard covers the home indicator: the larger of the two, not both */
        padding-block-end: calc(
          var(--_bleed) + max(env(safe-area-inset-bottom, 0px), var(--_drawer-keyboard, 0px))
        );
        max-inline-size: 100%;
        max-block-size: calc(var(--ui-drawer-max-h) + var(--_bleed));
        grid-template-rows: auto minmax(0, 1fr);
        border-block-end-width: 0;
        border-end-start-radius: 0;
        border-end-end-radius: 0;
        /* a stacked drawer shrinks toward its top edge, the part that stays in view */
        transform-origin: 50% 0;
      }
    
      @media (width < 40rem) and (not (hover: hover)) {
        :where([data-ui~="dialog"][data-ui~="drawer"]) {
          --_drawer-mode: 1;
          --_bleed: calc(var(--spacing) * 12);
          --_handle-display: block;
          --_content-row: 2;
          --_header-select: none;
    
          --_dialog-w: var(--ui-drawer-w);
          --_dialog-radius: var(--ui-drawer-radius);
          --_dialog-shadow: var(--ui-drawer-shadow);
    
          --ui-dialog-transition-duration: var(--ui-drawer-transition-duration);
          --ui-dialog-transition-timing-function: var(--ui-drawer-transition-timing-function);
          --ui-dialog-backdrop-transition-duration: var(--ui-dialog-transition-duration);
          --ui-dialog-backdrop-transition-timing-function: var(--ui-drawer-transition-timing-function);
          --ui-dialog-transition-delay--end: 0ms;
          --ui-dialog-opacity--start: 1;
          --ui-dialog-scale--start: 1;
          --ui-dialog-translate--start: 0, 100%, 0;
    
          margin-block: auto calc(var(--_bleed) * -1);
          margin-inline: auto;
          /* the keyboard covers the home indicator: the larger of the two, not both */
          padding-block-end: calc(
            var(--_bleed) + max(env(safe-area-inset-bottom, 0px), var(--_drawer-keyboard, 0px))
          );
          max-inline-size: 100%;
          max-block-size: calc(var(--ui-drawer-max-h) + var(--_bleed));
          grid-template-rows: auto minmax(0, 1fr);
          border-block-end-width: 0;
          border-end-start-radius: 0;
          border-end-end-radius: 0;
          transform-origin: 50% 0;
        }
      }
    
      /* ===========================================================================
      STANDALONE SURFACE: without the dialog identity the drawer paints itself.
      The combined form takes all of this from dialog.css.
      =========================================================================== */
    
      :where([data-ui~="drawer"]:not([data-ui~="dialog"])) {
        inline-size: var(--ui-drawer-w);
        block-size: fit-content;
        background-color: var(--_bg-resolved, var(--ui-drawer-bg));
        color: var(--_text-resolved, var(--ui-drawer-text));
        box-shadow: var(--_shadow-resolved, var(--ui-drawer-shadow));
        /* the top corners only: the bottom edge sits past the viewport */
        border-start-start-radius: var(--ui-drawer-radius);
        border-start-end-radius: var(--ui-drawer-radius);
        corner-shape: var(--_corner-shape-resolved, var(--ui-drawer-corner-shape));
        font-size: var(--font-size-md);
        overflow: hidden;
        overscroll-behavior: contain;
      }
    
      :where([data-ui~="drawer"]:not([data-ui~="dialog"])[open]) {
        display: grid;
        min-block-size: 0;
      }
    
      /* ===========================================================================
      SNAP POINTS: a drawer with data-drawer-snap is as tall as a drawer may be and
      rests pushed down by --_drawer-snap, which drawer.js writes when the stop
      changes. The height is set per form, like drawer mode itself.
      =========================================================================== */
    
      :where([data-ui~="drawer"]:not([data-ui~="dialog"])[data-drawer-snap]) {
        block-size: calc(var(--ui-drawer-max-h) + var(--_bleed));
      }
    
      @media (width < 40rem) and (not (hover: hover)) {
        :where([data-ui~="dialog"][data-ui~="drawer"][data-drawer-snap]) {
          --_dialog-h: calc(var(--ui-drawer-max-h) + var(--_bleed));
        }
      }
    
      :where([data-ui~="drawer"][data-drawer-snap]) {
        translate: 0 var(--_drawer-snap, 0px);
      }
    
      /* ===========================================================================
      STACK: a drawer with others open in front of it shrinks toward its top edge
      and lifts, once per drawer in front. drawer.js writes the count, and while
      the front drawer is dragged a fraction of it (state `following`, transitions
      off). A drawer opened over another dims nothing more.
      =========================================================================== */
    
      :where([data-ui~="drawer"][data-drawer-state~="stacked"]) {
        scale: calc(1 - var(--_drawer-depth, 0) * var(--ui-drawer-stack-scale));
        translate: 0
          calc(var(--_drawer-snap, 0px) - var(--_drawer-depth, 0) * var(--ui-drawer-stack-lift));
      }
    
      :where([data-ui~="drawer"][data-drawer-state~="following"]) {
        transition: none;
      }
    
      :where([data-ui~="drawer"][data-drawer-state~="nested"])::backdrop {
        background-color: var(--ui-drawer-nested-backdrop-color);
        backdrop-filter: none;
      }
    
      /* Each slot owns a row, as in the dialog: the body is the part that scrolls */
      :where([data-ui~="drawer"]) [data-drawer-slot~="content"] {
        display: grid;
        grid-template-rows: auto minmax(0, 1fr) auto;
        position: relative;
        min-block-size: 0;
        max-block-size: 100%;
      }
    
      :where([data-ui~="drawer"]) [data-drawer-slot~="header"] {
        grid-row: 1;
        display: flex;
        flex-direction: column;
        padding-inline: var(--space-sm);
        padding-block-start: var(--space-sm);
      }
    
      :where([data-ui~="drawer"]) [data-drawer-slot~="body"] {
        grid-row: 2;
        display: grid;
        align-content: start;
        padding-inline: var(--space-sm);
        padding-block: var(--space-md);
        min-block-size: 0;
        overflow-y: auto;
        overscroll-behavior: contain;
      }
    
      :where([data-ui~="drawer"]) [data-drawer-slot~="footer"] {
        grid-row: 3;
        display: flex;
        justify-content: flex-end;
        gap: var(--space-xs);
        padding: var(--space-sm);
        border-block-start: 1px solid var(--color-border);
      }
    
      :where([data-ui~="drawer"]) [data-drawer-slot~="close"] {
        position: absolute;
        inset-block-start: var(--space-xs);
        inset-inline-end: var(--space-xs);
        z-index: 50;
      }
    
      /* ===========================================================================
      PARTS IN DRAWER MODE: the handle shows and takes the first row; the content
      slot (the drawer's own or the dialog's) takes the flexible second row, with
      or without a handle before it. Both read the mode privates set above, so
      neither rule is repeated per form.
      =========================================================================== */
    
      :where([data-ui~="drawer"]) :where([data-drawer-slot~="content"], [data-dialog-slot~="content"]) {
        grid-row: var(--_content-row, auto);
      }
    
      /* The header is where a mouse grabs the drawer: a press on its text drags
         instead of selecting. Body text stays selectable. */
      :where([data-ui~="drawer"]) :where([data-drawer-slot~="header"], [data-dialog-slot~="header"]) {
        -webkit-user-select: var(--_header-select, auto);
        user-select: var(--_header-select, auto);
      }
    
      /* A pill, with a hit area that reaches the touch-target height. It always
         drags, even over a scrolled body, so it opts out of native panning. */
      :where([data-ui~="drawer"]) [data-drawer-slot~="handle"] {
        display: var(--_handle-display, none);
        grid-row: 1;
        justify-self: center;
        position: relative;
        inline-size: var(--ui-drawer-handle-w);
        block-size: var(--ui-drawer-handle-h);
        margin-block: calc(var(--spacing) * 2.5) calc(var(--spacing) * 1);
        border-radius: var(--radius-full);
        background-color: var(--ui-drawer-handle-bg);
        cursor: grab;
        touch-action: none;
        -webkit-user-select: none;
        user-select: none;
        transition: background-color var(--default-transition-duration)
          var(--default-transition-timing-function);
      }
    
      :where([data-ui~="drawer"]) [data-drawer-slot~="handle"]:hover {
        background-color: var(--ui-drawer-handle-bg--hover);
      }
    
      :where([data-ui~="drawer"]) [data-drawer-slot~="handle"]:active {
        background-color: var(--ui-drawer-handle-bg--active);
        cursor: grabbing;
      }
    
      :where([data-ui~="drawer"]) [data-drawer-slot~="handle"]::before {
        content: "";
        position: absolute;
        inset-inline: calc(var(--ui-drawer-handle-w) * -1);
        inset-block: min(calc(var(--spacing) * -2), calc((100% - var(--_touch-min, 0px)) / 2));
      }
    
      /* Below its largest snap point a drawer's content does not scroll: the drawer
         moves first. After the slot rules, which it has to beat. */
      :where([data-ui~="drawer"][data-drawer-state~="partial"])
        :is([data-drawer-slot~="body"], [data-dialog-slot~="body"]) {
        overflow-y: hidden;
      }
    
      /* ===========================================================================
      DRAG: while a pointer drags the drawer, drawer.js writes its inline
      translate and nothing may ease it: the drawer is the pointer. The backdrop
      fades with the drag: drawer.js scrubs an animation on it, or, where
      ::backdrop cannot be animated from script, writes --_drawer-backdrop, which
      the backdrop takes from the dialog by explicit inheritance. On release the state drops and the dialog's
      own transitions finish the motion, to closed or back to rest.
      =========================================================================== */
    
      :where([data-ui~="drawer"][data-drawer-state~="dragging"]) [data-drawer-slot~="handle"] {
        background-color: var(--ui-drawer-handle-bg--dragging);
      }
    
      :where([data-ui~="drawer"][data-drawer-state~="dragging"]) {
        transition: none;
        cursor: grabbing;
        /* a mouse drag that began beside text must not start selecting it */
        -webkit-user-select: none;
        user-select: none;
      }
    
      :where([data-ui~="drawer"][data-drawer-state~="dragging"])::backdrop {
        --_drawer-backdrop: inherit;
        opacity: var(--_drawer-backdrop, 1);
        transition: none;
      }
    
      /* ===========================================================================
      INDENT: the page wrapper scales back behind an open drawer. drawer.js sets the
      state (`on` while the machinery is engaged, `active` while a drawer is open,
      `dragging` while the last drawer is dragged) and measures, once, the scale and
      where the viewport sits inside the wrapper.
    
      Only scale and translate animate. The wrapper is clipped to the viewport's
      rectangle, a fixed clip, so the page above and below it stays out of the gaps;
      the body paints the backing color there. The rounded top corners are two
      corner pieces that grow from the corners, not a border-radius: nothing is
      repainted while the page moves.
    
      While `on` the wrapper is transformed, so it is the containing block of its
      fixed and absolute descendants.
      =========================================================================== */
    
      :where(ui-drawer-indent, [data-ui~="drawer-indent"]) {
        --_drawer-indent-inset: var(--ui-drawer-indent-inset);
        display: block;
        background-color: var(--ui-drawer-indent-bg);
        transition:
          scale var(--ui-drawer-transition-duration) var(--ui-drawer-transition-timing-function),
          translate var(--ui-drawer-transition-duration) var(--ui-drawer-transition-timing-function);
      }
    
      :where(ui-drawer-indent, [data-ui~="drawer-indent"])[data-drawer-indent-state~="on"] {
        position: relative;
        transform-origin: 50% var(--_drawer-indent-top, 0px);
        scale: calc(1 - (1 - var(--_drawer-indent-scale, 1)) * var(--_drawer-indent-amount, 0));
        translate: 0 calc(var(--ui-drawer-indent-offset) * var(--_drawer-indent-amount, 0));
        clip-path: inset(var(--_drawer-indent-top, 0px) 0 var(--_drawer-indent-bottom, 0px) 0);
        will-change: scale, translate;
      }
    
      :where(ui-drawer-indent, [data-ui~="drawer-indent"])[data-drawer-indent-state~="active"] {
        --_drawer-indent-amount: 1;
      }
    
      /* The backing shows in the gaps around the indented page. Important, because a
         page's own <body style="--bg: …"> is a utility and would otherwise win; it holds
         only while the wrapper is `on`. */
      :where(body):has(
        :is(ui-drawer-indent, [data-ui~="drawer-indent"])[data-drawer-indent-state~="on"]
      ) {
        background-color: var(--ui-drawer-indent-backing) !important;
      }
    
      /* A corner piece: a square the size of the radius whose outer corner is rounded
         and whose spread shadow, cut off at the square, paints only the notch outside
         the curve. Scaling it from that corner is the radius growing. */
      :where(ui-drawer-indent, [data-ui~="drawer-indent"])[data-drawer-indent-state~="on"]::before,
      :where(ui-drawer-indent, [data-ui~="drawer-indent"])[data-drawer-indent-state~="on"]::after {
        --_drawer-indent-amount: inherit;
        --_drawer-indent-top: inherit;
        content: "";
        position: absolute;
        z-index: 2147483647;
        inset-block-start: var(--_drawer-indent-top, 0px);
        inline-size: var(--ui-drawer-indent-radius);
        block-size: var(--ui-drawer-indent-radius);
        box-shadow: 0 0 0 var(--ui-drawer-indent-radius) var(--ui-drawer-indent-backing);
        clip-path: inset(0);
        corner-shape: var(--radius-corner-shape);
        scale: var(--_drawer-indent-amount, 0);
        pointer-events: none;
        transition: scale var(--ui-drawer-transition-duration)
          var(--ui-drawer-transition-timing-function);
    
        @starting-style {
          scale: 0;
        }
      }
    
      :where(ui-drawer-indent, [data-ui~="drawer-indent"])[data-drawer-indent-state~="on"]::before {
        left: 0;
        border-top-left-radius: 100%;
        transform-origin: 0 0;
      }
    
      :where(ui-drawer-indent, [data-ui~="drawer-indent"])[data-drawer-indent-state~="on"]::after {
        right: 0;
        border-top-right-radius: 100%;
        transform-origin: 100% 0;
      }
    
      :where(ui-drawer-indent, [data-ui~="drawer-indent"])[data-drawer-indent-state~="dragging"],
      :where(
          ui-drawer-indent,
          [data-ui~="drawer-indent"]
        )[data-drawer-indent-state~="dragging"]::before,
      :where(
          ui-drawer-indent,
          [data-ui~="drawer-indent"]
        )[data-drawer-indent-state~="dragging"]::after {
        transition: none;
      }
    }
    // primitives/drawer/drawer.js
    "use strict";
    /**
     * @fileoverview Drawer: drag-to-dismiss for `<dialog data-ui="drawer">` bottom sheets.
     * @description A drawer is a native modal `<dialog>`, opened and closed like
     * any other (`command="show-modal"`, `command="close"`, Esc, the backdrop with
     * `closedby="any"`). This script adds the gesture: drag the drawer down and
     * let go to dismiss it.
     *
     * - `data-ui="drawer"` is a drawer on every device.
     * - `data-ui="dialog drawer"` is a drawer below the `sm` band on a touch
     *   screen, and a plain dialog (no dragging) everywhere else.
     *
     * While the pointer is down the drawer follows it 1:1 and the backdrop fades
     * with it. Letting go past a quarter of the drawer's height, or with a quick
     * downward flick, slides it off the bottom edge and then closes it through
     * `requestClose()`, so `cancel` and `close` fire as they do for Esc; anything
     * less returns it to rest. Until it has slid out it can be caught again. Pulling it up
     * past its resting place meets resistance.
     *
     * A drag starts anywhere on the drawer except on form fields, selected text,
     * and anything inside `[data-ui-no-drag]`. Inside scrolling content it starts
     * only once that content is scrolled to the top and the pointer moves down,
     * so the body scrolls first and the drawer follows; the handle
     * (`data-drawer-slot="handle"`) always drags. There is no custom element and
     * nothing to initialize: the script binds a drawer when it opens.
     *
     * **Snap points.** `data-drawer-snap="148px 0.5 1"` gives the drawer resting
     * heights, smallest first: a number up to 1 is a share of the drawer's full
     * height, a `px` or `rem` length is a visible height. It opens at the first.
     * Letting go settles on the nearest; a flick moves one stop in its direction,
     * a very fast one goes all the way (or one stop, with
     * `data-drawer-snap-sequential`), and from the lowest stop a flick or enough
     * travel downward closes the drawer. Below the largest stop the drawer takes
     * every vertical drag and its content does not scroll. A click on the handle
     * steps to the next stop; make the handle a `<button>` to give the keyboard
     * the same. Each change fires `zazz:drawer-snap` (`detail.index`,
     * `detail.value` in px), `data-drawer-state` carries `expanded` at the largest
     * stop, and `snapDrawer(dialog, index)` moves it from script.
     *
     * **The software keyboard.** A phone lays a drawer out against the full
     * screen, which the keyboard does not shrink. While a field in the front
     * drawer has the keyboard up, the drawer's content ends at the keyboard's top
     * edge (its surface runs on underneath), the focused field scrolls into what
     * is still visible, and the page behind stays where it was. Nothing to author.
     *
     * **Stacked drawers.** A drawer opened over another scales the one behind back
     * and lifts it, and that one follows as the front drawer is dragged. Nothing
     * to author: the script counts the open drawers.
     *
     * **Indent.** Wrap the page in `<ui-drawer-indent>` (or put
     * `data-ui="drawer-indent"` on its wrapper) and it scales back behind any open
     * drawer, with rounded top corners, and follows the drag of the last one. Only
     * transforms animate. While indented the wrapper is transformed, so a
     * `position: fixed` element inside it moves with the page; `position: sticky`
     * is unaffected.
     *
     * @example
     * <button data-ui="button" command="show-modal" commandfor="filters">Filters</button>
     * <dialog id="filters" data-ui="drawer" closedby="any">
     *   <div data-drawer-slot="handle"></div>
     *   <div data-drawer-slot="content">
     *     <header data-drawer-slot="header">…</header>
     *     <div data-drawer-slot="body">…</div>
     *   </div>
     * </dialog>
     */
    import { currentTranslate, maxTransitionMs, pickSnap, rubberBand, trackDrag, } from "../../base/gesture.js";
    // --- Tuning ---
    /** Share of the drawer's visible height, at its lowest stop, that dismisses on its own. */
    const CLOSE_RATIO = 0.25;
    /** Speed that moves the drawer one stop, or dismisses it from the lowest, in px/ms. */
    const FLICK_VELOCITY = 0.4;
    /** Speed that skips every stop: all the way open, or closed, in px/ms. */
    const FLING_VELOCITY = 2;
    /**
     * After inner content scrolls, how long before the drawer may be dragged, in
     * ms. A fast scroll that reaches the top would otherwise carry straight on
     * into dragging the drawer away.
     */
    const SCROLL_GUARD_MS = 100;
    /** Length of the backdrop's scrub animation: its timeline is drag progress, not time. */
    const SCRUB_MS = 1000;
    const DRAWER = 'dialog[data-ui~="drawer"]';
    const HANDLE = '[data-drawer-slot~="handle"]';
    const INDENT = 'ui-drawer-indent, [data-ui~="drawer-indent"]';
    const INDENT_STATE = "data-drawer-indent-state";
    // --- Helpers ---
    /** Adds or removes one token of a space-separated state attribute; an empty attribute is removed. */
    function setToken(element, attribute, token, on) {
        const tokens = new Set((element.getAttribute(attribute) ?? "").split(/\s+/).filter(Boolean));
        if (tokens.has(token) === on)
            return;
        if (on)
            tokens.add(token);
        else
            tokens.delete(token);
        if (tokens.size)
            element.setAttribute(attribute, [...tokens].join(" "));
        else
            element.removeAttribute(attribute);
    }
    /** Adds or removes a token of a drawer's `data-drawer-state`. */
    function setState(dialog, token, on) {
        setToken(dialog, "data-drawer-state", token, on);
    }
    /** Adds or removes the `dragging` token of a drawer's `data-drawer-state`. */
    function setDragging(dialog, on) {
        setState(dialog, "dragging", on);
    }
    /** Clears everything a drag wrote on the drawer. */
    function reset(dialog) {
        setDragging(dialog, false);
        dialog.style.removeProperty("translate");
        dialog.style.removeProperty("--_drawer-backdrop");
    }
    /**
     * @description Reads a drawer's snap points as resting positions: px the
     * drawer is pushed down at each, the smallest visible height first.
     *
     * @param dialog - The drawer.
     * @param height - The drawer's full visible height in px.
     * @returns The positions, descending; `[0]` without usable snap points.
     * @private
     */
    function readStops(dialog, height) {
        const raw = dialog.getAttribute("data-drawer-snap")?.trim();
        if (!raw)
            return [0];
        const rem = Number.parseFloat(getComputedStyle(document.documentElement).fontSize) || 16;
        const positions = new Set();
        for (const token of raw.split(/\s+/)) {
            const value = Number.parseFloat(token);
            if (!Number.isFinite(value) || value <= 0)
                continue;
            let visible = value * height;
            if (token.endsWith("rem"))
                visible = value * rem;
            else if (token.endsWith("px") || value > 1)
                visible = value;
            positions.add(Math.round(height - Math.min(height, Math.max(1, visible))));
        }
        return positions.size ? [...positions].sort((a, b) => b - a) : [0];
    }
    /**
     * @description Starts a paused opacity animation on the drawer's backdrop, to
     * be scrubbed with the drag. An animation, not a style write: it reaches the
     * pseudo-element without restyling the drawer's content, in engines that do
     * not re-resolve `::backdrop` when a non-inherited property changes on its
     * dialog (WebKit).
     *
     * @param dialog - The drawer.
     * @returns The animation, or null where `::backdrop` cannot be animated; the
     * caller then writes `--_drawer-backdrop`, which drawer.css reads.
     * @private
     */
    function scrubBackdrop(dialog) {
        try {
            const animation = dialog.animate([{ opacity: 1 }, { opacity: 0 }], {
                pseudoElement: "::backdrop",
                duration: SCRUB_MS,
                fill: "both",
            });
            animation.pause();
            return animation;
        }
        catch {
            return null;
        }
    }
    /** Whether drawer.css has the dialog in drawer mode right now. */
    function inDrawerMode(dialog) {
        return getComputedStyle(dialog).getPropertyValue("--_drawer-mode").trim() === "1";
    }
    /** Whether an element scrolls its content on the block axis. */
    function scrolls(element) {
        if (element.scrollHeight <= element.clientHeight)
            return false;
        const overflow = getComputedStyle(element).overflowY;
        return overflow === "auto" || overflow === "scroll";
    }
    /**
     * @description Whether a press may drag the drawer, given what it landed on
     * and which way it is moving.
     *
     * @param dialog - The drawer.
     * @param drag - The drag about to start; `offset` carries its direction.
     * @param lastScroll - When content inside the drawer last scrolled.
     * @param partial - Whether the drawer rests below its largest snap point.
     * @returns Whether the drawer takes the gesture.
     * @private
     */
    function claims(dialog, drag, lastScroll, partial) {
        if (!inDrawerMode(dialog))
            return false;
        // a press on the backdrop targets the dialog, outside its box
        const box = dialog.getBoundingClientRect();
        if (drag.startY < box.top || drag.startX < box.left || drag.startX > box.right)
            return false;
        if (drag.target.closest(HANDLE))
            return true;
        // below its largest stop the drawer moves before anything inside it scrolls
        if (partial)
            return true;
        // scrolling content goes first: it must be at the top, and the pull downward
        const down = drag.offset > 0;
        for (let node = drag.target; node && dialog.contains(node); node = node.parentElement) {
            if (scrolls(node) && (node.scrollTop > 0 || !down))
                return false;
        }
        return performance.now() - lastScroll >= SCROLL_GUARD_MS;
    }
    // --- Stack ---
    /** The open drawers in drawer mode, the front one last. */
    const stack = [];
    /**
     * @description Writes each open drawer's place in the stack: how many drawers
     * sit in front of it (`--_drawer-depth`, `stacked`) and whether it opened over
     * another (`nested`). Runs when a drawer opens or closes, never per frame.
     * @private
     */
    function restack() {
        // a drawer removed from the page while open never reports its close
        for (let index = stack.length - 1; index >= 0; index--) {
            const dialog = stack[index];
            if (!dialog.isConnected || !dialog.open)
                stack.splice(index, 1);
        }
        stack.forEach((dialog, index) => {
            const depth = stack.length - 1 - index;
            setState(dialog, "following", false);
            setState(dialog, "stacked", depth > 0);
            setState(dialog, "nested", index > 0);
            if (depth > 0)
                dialog.style.setProperty("--_drawer-depth", String(depth));
            else
                dialog.style.removeProperty("--_drawer-depth");
        });
        indentPose(stack.length > 0);
    }
    /**
     * @description Moves the drawers behind `front` with its drag: at progress 1
     * each sits where it will once `front` is gone. The depth is a non-inheriting
     * property, so the write restyles those drawers and not their content.
     *
     * @param front - The drawer being dragged or released.
     * @param progress - How far `front` is toward closed, 0 to 1.
     * @param live - Whether a pointer is driving it (transitions off).
     * @private
     */
    function follow(front, progress, live) {
        const index = stack.indexOf(front);
        for (let behind = 0; behind < index; behind++) {
            const dialog = stack[behind];
            dialog.style.setProperty("--_drawer-depth", String(index - behind - progress));
            setState(dialog, "following", live);
        }
    }
    // --- Indent ---
    /** The page wrapper that is indented right now, and what ends its return to rest. */
    let indented = null;
    let cancelOutdent = null;
    /**
     * @description Measures what the indent needs, once per activation and on
     * resize: the scale that pulls each side in by the inset hook, and where the
     * viewport sits inside the wrapper (the transform's origin, the clip, and the
     * corner pieces all hang off its top edge).
     * @private
     */
    function measureIndent(wrapper) {
        const box = wrapper.getBoundingClientRect();
        const width = wrapper.offsetWidth || 1;
        const inset = Number.parseFloat(getComputedStyle(wrapper).getPropertyValue("--_drawer-indent-inset")) || 0;
        const top = Math.max(0, -box.top);
        const bottom = Math.max(0, wrapper.offsetHeight - top - window.innerHeight);
        wrapper.style.setProperty("--_drawer-indent-scale", String(Math.max(0, 1 - (inset * 2) / width)));
        wrapper.style.setProperty("--_drawer-indent-top", `${top}px`);
        wrapper.style.setProperty("--_drawer-indent-bottom", `${bottom}px`);
    }
    /**
     * @description Indents the page wrapper or sends it back to rest. The pose is
     * a state token and the motion a CSS transition; the `on` token (clip,
     * corners, backing) outlasts the pose until the return has finished.
     *
     * @param active - Whether a drawer is open.
     * @private
     */
    function indentPose(active) {
        // a wrapper that left the page takes its state with it
        if (indented && !indented.isConnected) {
            cancelOutdent?.();
            indented = null;
        }
        const wrapper = indented ?? document.querySelector(INDENT);
        if (!wrapper)
            return;
        if (active) {
            cancelOutdent?.();
            if (indented !== wrapper) {
                measureIndent(wrapper);
                indented = wrapper;
            }
            setToken(wrapper, INDENT_STATE, "on", true);
            setToken(wrapper, INDENT_STATE, "active", true);
            return;
        }
        if (!indented || cancelOutdent)
            return;
        setToken(wrapper, INDENT_STATE, "dragging", false);
        wrapper.style.removeProperty("--_drawer-indent-amount");
        setToken(wrapper, INDENT_STATE, "active", false);
        const off = () => {
            cancelOutdent?.();
            wrapper.removeAttribute(INDENT_STATE);
            for (const name of ["scale", "top", "bottom"]) {
                wrapper.style.removeProperty(`--_drawer-indent-${name}`);
            }
            indented = null;
        };
        const ms = maxTransitionMs(wrapper);
        if (ms <= 0) {
            off();
            return;
        }
        const onReturned = (event) => {
            if (event.target === wrapper && event.propertyName === "scale")
                off();
        };
        const timer = window.setTimeout(off, ms + 100);
        wrapper.addEventListener("transitionend", onReturned);
        cancelOutdent = () => {
            window.clearTimeout(timer);
            wrapper.removeEventListener("transitionend", onReturned);
            cancelOutdent = null;
        };
    }
    /**
     * @description Links the indent to the last open drawer's drag.
     *
     * @param progress - How far the drawer is toward closed, 0 to 1.
     * @param live - Whether a pointer is driving it (transitions off).
     * @private
     */
    function indentProgress(progress, live) {
        if (!indented)
            return;
        setToken(indented, INDENT_STATE, "dragging", live);
        if (live)
            indented.style.setProperty("--_drawer-indent-amount", String(1 - progress));
        else
            indented.style.removeProperty("--_drawer-indent-amount");
    }
    // --- Keyboard ---
    /** The keyboard's height on the front drawer, which drawer.css adds to its bottom padding. */
    const KEYBOARD_INSET = "--_drawer-keyboard";
    /** Space kept between a revealed field and the keyboard's top edge, in px. */
    const REVEAL_GAP = 16;
    /** Inputs that open a picker or nothing rather than the software keyboard. */
    const NO_KEYBOARD = /^(?:button|checkbox|color|file|hidden|image|radio|range|reset|submit|date|datetime-local|month|time|week)$/;
    /** Whether focus on this element opens the software keyboard. */
    function typesText(element) {
        if (element instanceof HTMLTextAreaElement)
            return !element.readOnly;
        if (element instanceof HTMLInputElement)
            return !element.readOnly && !NO_KEYBOARD.test(element.type);
        return element instanceof HTMLElement && element.isContentEditable;
    }
    /**
     * @description How much of the layout viewport the software keyboard covers,
     * from the bottom: the part below the visual viewport. 0 while the page is
     * pinch-zoomed, when the visual viewport is smaller for another reason.
     * @private
     */
    function keyboardInset() {
        const viewport = window.visualViewport;
        if (!viewport || Math.abs(viewport.scale - 1) > 0.01)
            return 0;
        const bottom = Math.max(0, viewport.offsetTop) + viewport.height;
        return Math.max(0, Math.round(window.innerHeight - Math.min(window.innerHeight, bottom)));
    }
    /**
     * @description Keeps an open drawer usable with the software keyboard up.
     * iOS lays out the top layer against the layout viewport, which the keyboard
     * does not shrink, and scrolls the page behind a modal to reveal a focused
     * field. While the drawer is the front one this writes the keyboard's height
     * to `--_drawer-keyboard` (drawer.css pads the sheet by it, so its
     * content ends at the keyboard's top edge), holds the page at its scroll
     * position, and scrolls a focused field into the part of its scrolling slot
     * that is still visible.
     *
     * @param dialog - The drawer.
     * @param signal - Aborts when the drawer closes.
     * @param onChange - Runs after the inset changes, once the new padding is in place.
     * @private
     */
    function trackKeyboard(dialog, signal, onChange) {
        const viewport = window.visualViewport;
        if (!viewport)
            return;
        const front = () => stack[stack.length - 1] === dialog;
        const pageX = window.scrollX;
        const pageY = window.scrollY;
        let frame = 0;
        let current = 0;
        const update = () => {
            frame = 0;
            const inset = front() ? keyboardInset() : 0;
            if (inset === current)
                return;
            current = inset;
            if (inset > 0)
                dialog.style.setProperty(KEYBOARD_INSET, `${inset}px`);
            else
                dialog.style.removeProperty(KEYBOARD_INSET);
            onChange();
        };
        const schedule = () => {
            if (!frame)
                frame = requestAnimationFrame(update);
        };
        /** Scrolls the field's scrolling slot so the field sits above the keyboard and below the slot's top. */
        const reveal = (field) => {
            if (!dialog.contains(field) || document.activeElement !== field)
                return;
            let container = field.parentElement;
            while (container && dialog.contains(container) && !scrolls(container)) {
                container = container.parentElement;
            }
            if (!container || !dialog.contains(container))
                return;
            const box = container.getBoundingClientRect();
            const target = field.getBoundingClientRect();
            const visibleBottom = Math.min(box.bottom, viewport.offsetTop + viewport.height) - REVEAL_GAP;
            const visibleTop = Math.max(box.top, viewport.offsetTop) + REVEAL_GAP;
            let by = 0;
            if (target.bottom > visibleBottom)
                by = target.bottom - visibleBottom;
            if (target.top - by < visibleTop)
                by = target.top - visibleTop;
            if (Math.abs(by) < 1)
                return;
            const still = matchMedia("(prefers-reduced-motion: reduce)").matches;
            container.scrollBy({ top: by, behavior: still ? "instant" : "smooth" });
        };
        viewport.addEventListener("resize", schedule, { signal });
        viewport.addEventListener("scroll", schedule, { signal });
        // the page behind a modal stays where it was, whatever iOS scrolls to show the field
        window.addEventListener("scroll", () => {
            if (!front() || (window.scrollX === pageX && window.scrollY === pageY))
                return;
            window.scrollTo({ left: pageX, top: pageY, behavior: "instant" });
        }, { passive: true, signal });
        // the keyboard settles over a few frames: reveal after it has, and again once it is up
        dialog.addEventListener("focusin", (event) => {
            const field = event.target;
            if (!(field instanceof Element) || !typesText(field) || !front())
                return;
            for (const ms of [100, 350]) {
                const timer = window.setTimeout(() => {
                    update();
                    reveal(field);
                }, ms);
                signal.addEventListener("abort", () => window.clearTimeout(timer), { once: true });
            }
        }, { signal });
        signal.addEventListener("abort", () => {
            cancelAnimationFrame(frame);
            dialog.style.removeProperty(KEYBOARD_INSET);
        });
        update();
    }
    /** Open drawers and what unbinds or moves each. */
    const bound = new WeakMap();
    /** Each drawer's backdrop animation, kept past its close so the next open can drop it. */
    const fades = new WeakMap();
    /**
     * @description Binds drag-to-dismiss to an open drawer until it closes.
     *
     * @param dialog - The drawer.
     */
    function bindDrawer(dialog) {
        if (bound.has(dialog))
            return;
        const controller = new AbortController();
        const { signal } = controller;
        // what the last dismissal left in place: the slid-out translate, the cleared backdrop
        fades.get(dialog)?.cancel();
        fades.delete(dialog);
        reset(dialog);
        const snaps = dialog.hasAttribute("data-drawer-snap");
        let lastScroll = 0;
        // where the drawer was when the drag caught it (mid snap-back, usually its stop)
        let base = 0;
        let height = 1;
        // the sheet's bleed past the bottom edge: the most it may be pulled up
        let lift = 0;
        // resting positions, px pushed down, the lowest snap point first; and the one it rests at
        let stops = [0];
        let active = 0;
        let fade = null;
        // undoes a dismissal still sliding out, so a new drag can catch the drawer
        let cancelClose = null;
        const measure = () => {
            lift = Math.max(0, -Number.parseFloat(getComputedStyle(dialog).marginBlockEnd) || 0);
            // the layout height: a stacked drawer's scale must not shrink it
            height = Math.max(1, dialog.offsetHeight - lift);
            stops = snaps ? readStops(dialog, height) : [0];
            active = Math.min(active, stops.length - 1);
        };
        /** Writes where the drawer rests: drawer.css turns `--_drawer-snap` into its `translate`. */
        const place = () => {
            if (!snaps)
                return;
            const largest = active === stops.length - 1;
            dialog.style.setProperty("--_drawer-snap", `${stops[active] ?? 0}px`);
            setState(dialog, "expanded", largest);
            setState(dialog, "partial", !largest);
        };
        /** Everything that moves with the drawer's progress toward closed, besides its backdrop. */
        const link = (progress, live) => {
            follow(dialog, progress, live);
            if (stack.length === 1 && stack[0] === dialog)
                indentProgress(progress, live);
        };
        /**
         * Runs the backdrop from where the drag left it to clear or back to full,
         * in `ms`. Back at full the animation is dropped; clear, it holds until the
         * drawer next opens, over whatever the closed dialog's own backdrop does.
         */
        const settle = (closing, ms) => {
            dialog.style.removeProperty("--_drawer-backdrop");
            const animation = fade;
            if (!animation)
                return;
            const done = () => {
                if (closing || fade !== animation || animation.playState !== "finished")
                    return;
                animation.cancel();
                fades.delete(dialog);
                fade = null;
            };
            const at = Number(animation.currentTime) || 0;
            const left = closing ? SCRUB_MS - at : at;
            if (ms <= 0 || left <= 0) {
                animation.playbackRate = closing ? 1 : -1;
                animation.finish();
                done();
                return;
            }
            animation.playbackRate = ((closing ? 1 : -1) * left) / ms;
            animation.play();
            animation.finished.then(done, () => { });
        };
        /** Settles the drawer on a stop; the dialog's `translate` transition carries it there. */
        const snapTo = (index) => {
            const next = Math.min(Math.max(index, 0), stops.length - 1);
            const changed = next !== active;
            active = next;
            place();
            setDragging(dialog, false);
            settle(false, maxTransitionMs(dialog));
            dialog.style.removeProperty("translate");
            link(0, false);
            if (!changed)
                return;
            dialog.dispatchEvent(new CustomEvent("zazz:drawer-snap", {
                bubbles: true,
                detail: { index: active, value: height - (stops[active] ?? 0) },
            }));
        };
        const rest = () => snapTo(active);
        /** Closes the dialog; a `cancel` listener that keeps it open sends it back to rest. */
        const close = () => {
            if (!dialog.open)
                return;
            if (typeof dialog.requestClose === "function")
                dialog.requestClose();
            else
                dialog.close();
            if (!dialog.open)
                return;
            if (stack.length === 1)
                indentPose(true);
            rest();
        };
        /**
         * Slides the drawer off the bottom edge while it is still open, then closes
         * it. The slide is the drawer's own `translate` transition, so it does not
         * depend on the engine animating a dialog's exit (WebKit removes a closed
         * dialog at once), and until it ends the drawer can be caught again.
         * Whatever is linked to the drawer leaves with it.
         */
        const slideOutAndClose = (ms) => {
            dialog.style.translate = `0 ${height + lift}px`;
            settle(true, ms);
            follow(dialog, 1, false);
            if (stack.length === 1 && stack[0] === dialog)
                indentPose(false);
            if (ms <= 0) {
                close();
                return;
            }
            const onSlid = (event) => {
                if (event.target === dialog && event.propertyName === "translate")
                    finish();
            };
            const finish = () => {
                cancelClose?.();
                close();
            };
            // the timer covers a transition that never reports its end
            const timer = window.setTimeout(finish, ms + 100);
            dialog.addEventListener("transitionend", onSlid);
            cancelClose = () => {
                window.clearTimeout(timer);
                dialog.removeEventListener("transitionend", onSlid);
                cancelClose = null;
            };
        };
        bound.set(dialog, { controller, snapTo });
        if (inDrawerMode(dialog)) {
            measure();
            place();
            stack.push(dialog);
            restack();
            trackKeyboard(dialog, signal, () => {
                measure();
                place();
            });
        }
        signal.addEventListener("abort", () => {
            cancelClose?.();
            // a drawer closed some other way mid-drag: nothing may hold the backdrop
            if (fade?.playState === "paused") {
                fade.cancel();
                fades.delete(dialog);
            }
        });
        dialog.addEventListener("scroll", () => {
            lastScroll = performance.now();
        }, { capture: true, passive: true, signal });
        // the handle steps through the snap points: a click, so a button handle works from the keyboard
        dialog.addEventListener("click", (event) => {
            if (stops.length < 2 || !(event.target instanceof Element))
                return;
            if (event.target.closest(HANDLE))
                snapTo((active + 1) % stops.length);
        }, { signal });
        window.addEventListener("resize", () => {
            if (!stack.includes(dialog))
                return;
            measure();
            place();
        }, { signal });
        trackDrag(dialog, {
            axis: "y",
            signal,
            canStart: (drag) => claims(dialog, drag, lastScroll, active < stops.length - 1),
            onStart: () => {
                // a drawer caught on its way out: what left with it comes back
                if (cancelClose && stack.length === 1)
                    indentPose(true);
                cancelClose?.();
                base = currentTranslate(dialog).y;
                measure();
                if (!fade) {
                    fade = scrubBackdrop(dialog);
                    if (fade)
                        fades.set(dialog, fade);
                }
                fade?.pause();
                setDragging(dialog, true);
            },
            onMove: ({ offset }) => {
                const travel = base + offset;
                const top = stops[stops.length - 1] ?? 0;
                const y = travel >= top ? travel : top + rubberBand(travel - top, lift + top);
                dialog.style.translate = `0 ${y}px`;
                // progress runs from the lowest stop to gone: above it nothing fades
                const lowest = stops[0] ?? 0;
                const progress = Math.min(1, Math.max(0, (y - lowest) / Math.max(1, height - lowest)));
                if (fade)
                    fade.currentTime = progress * SCRUB_MS;
                else
                    dialog.style.setProperty("--_drawer-backdrop", String(1 - progress));
                link(progress, true);
            },
            onEnd: ({ offset, velocity }) => {
                const target = pickSnap({
                    stops,
                    position: base + offset,
                    velocity,
                    active,
                    size: height,
                    closeRatio: CLOSE_RATIO,
                    flick: FLICK_VELOCITY,
                    fling: FLING_VELOCITY,
                    sequential: dialog.hasAttribute("data-drawer-snap-sequential"),
                });
                // transitions back on: the inline translate now eases to wherever it is set
                setDragging(dialog, false);
                if (target < 0)
                    slideOutAndClose(maxTransitionMs(dialog));
                else
                    snapTo(target);
            },
            onCancel: rest,
        });
    }
    /** Unbinds a drawer that closed. */
    function unbindDrawer(dialog) {
        bound.get(dialog)?.controller.abort();
        bound.delete(dialog);
        dialog.removeAttribute("data-drawer-state");
        dialog.style.removeProperty("--_drawer-depth");
        const index = stack.indexOf(dialog);
        if (index < 0)
            return;
        stack.splice(index, 1);
        restack();
    }
    /**
     * @description Moves an open drawer to one of its snap points.
     *
     * @param dialog - The drawer.
     * @param index - The snap point, counted from the smallest; clamped to the ones it has.
     */
    function snapDrawer(dialog, index) {
        bound.get(dialog)?.snapTo(index);
    }
    /**
     * @description Starts drawer binding for the page: every drawer is bound when
     * the dialog lifecycle reports it open and unbound when it closes. Idempotent.
     */
    const initDrawers = function () {
        if (initDrawers._bound)
            return;
        initDrawers._bound = true;
        document.addEventListener("zazz:dialog-open", (event) => {
            if (event.target instanceof HTMLDialogElement && event.target.matches(DRAWER)) {
                bindDrawer(event.target);
            }
        });
        document.addEventListener("zazz:dialog-close", (event) => {
            if (event.target instanceof HTMLDialogElement)
                unbindDrawer(event.target);
        });
        window.addEventListener("resize", () => {
            if (indented)
                measureIndent(indented);
        });
        // drawers that were already open when the script loaded
        for (const dialog of document.querySelectorAll(`${DRAWER}[open]`)) {
            bindDrawer(dialog);
        }
    };
    // Auto-initialize when DOM is ready (only in browser environment)
    if (typeof window !== "undefined" && typeof document !== "undefined") {
        if (document.readyState === "loading") {
            document.addEventListener("DOMContentLoaded", initDrawers);
        }
        else {
            initDrawers();
        }
    }
    export { bindDrawer, initDrawers, snapDrawer };

    Responsive dialog

    Confirm your order

    A dialog on a desktop, and a drawer you can swipe away on a phone.

    The markup is a dialog with its usual slots, plus the drawer identity and a handle.

    <button data-ui="button" type="button" command="show-modal" commandfor="drawer-responsive-dialog-1">
      Open dialog
    </button>
    <dialog id="drawer-responsive-dialog-1" data-ui="dialog drawer" closedby="any">
      <div data-drawer-slot="handle"></div>
      <div data-dialog-slot="content">
        <header data-dialog-slot="header">
          <h2
            style="
              --font-size: var(--font-size-lg);
              --font-weight: strong;
              --font-family: var(--font-family-heading);
            "
          >
            Confirm your order
          </h2>
          <p style="--text: var(--color-muted-foreground)">
            A dialog on a desktop, and a drawer you can swipe away on a phone.
          </p>
        </header>
        <div data-dialog-slot="body">
          <p>The markup is a dialog with its usual slots, plus the drawer identity and a handle.</p>
        </div>
        <footer data-dialog-slot="footer">
          <button
            data-ui="button"
            type="button"
            commandfor="drawer-responsive-dialog-1"
            command="close"
          >
            Cancel
          </button>
          <button
            data-ui="button"
            data-button-variant="primary"
            type="button"
            commandfor="drawer-responsive-dialog-1"
            command="close"
          >
            Confirm
          </button>
        </footer>
      </div>
    </dialog>
    /**
     * drawer.css: Drawer ([data-ui~="drawer"] on native <dialog>; slots
     *             data-drawer-slot="handle | content | header | body | footer | close";
     *             <ui-drawer-indent> / [data-ui~="drawer-indent"], the page wrapper that
     *             scales back behind an open drawer)
     *
     * A bottom sheet: a modal dialog that rises from the bottom edge and is dragged
     * back down to dismiss. Alone (`data-ui="drawer"`) it is a drawer everywhere;
     * on a dialog (`data-ui="dialog drawer"`) it is a drawer below the sm band on a
     * touch screen and the plain dialog otherwise. `data-drawer-snap` gives it
     * resting heights; a drawer opened over another pushes that one back.
     *
     * @layer      variables, components
     * @requires   _layers.css, _variables.css, dialog.css (the native <dialog> motion, backdrop, and
     *             scroll lock in its reset layer; the surface and slots in the combined form)
     * @uses       Overrides --ui-dialog-* motion tokens: the dialog's open/close transition becomes a
     *             rise from the bottom edge, with the backdrop on the same duration and curve
     * @uses       translate — drawer.js writes the inline translate while a pointer drags the drawer
     *             (state `dragging`, transitions off); the dialog's transitions finish the release
     * @uses       Web Animations on ::backdrop — drawer.js scrubs a paused opacity animation so the
     *             backdrop fades with the drag without restyling the drawer's content on every move
     * @uses       @property (inherits: false) + `inherit` on ::backdrop — the same link in CSS, for
     *             an engine that cannot animate ::backdrop from script; where neither works the
     *             backdrop stays opaque until release
     * @uses       @media (width < 40rem) and (not (hover: hover)) — the combined form's drawer mode,
     *             the same phone test as dialog.css
     * @uses       scale, translate — the only properties the stack and the indent animate; the
     *             indent's corner radius is two corner pieces that scale up, so no border-radius or
     *             clip is animated and the page is never repainted for it
     * @uses       clip-path: inset() — a fixed rectangle while the page is indented, so the part of
     *             the page above and below the viewport stays out of the gaps the scale opens
     * @uses       :has() — the body takes the backing color while its page wrapper is indented
     * @uses       @starting-style — the corner pieces grow from nothing when they are generated
     * @uses       corner-shape — the corner pieces follow --radius-corner-shape where it is
     *             supported and are round elsewhere
     * @uses       env(safe-area-inset-top) — the indented page clears the status bar
     * @uses       env(safe-area-inset-bottom) — content clears the home indicator
     * @uses       visualViewport — drawer.js writes --_drawer-keyboard (the software
     *             keyboard's height) on the front drawer, and the sheet's bottom padding takes it,
     *             so content ends at the keyboard's top edge while the surface runs on under it
     * @uses       --_touch-min — the handle's hit area on touch screens
     * @tokens     --ui-drawer-* (@layer variables)
     */
    
    @layer variables {
      :root {
        /* surface */
        --ui-drawer-bg: var(--ui-dialog-bg);
        --ui-drawer-text: var(--ui-dialog-text);
        --ui-drawer-radius: var(--radius-xl);
        --ui-drawer-corner-shape: var(--ui-dialog-corner-shape);
        --ui-drawer-shadow: var(--shadow-lg);
    
        /* metrics: edge to edge, the layout-bleed band; cap it with a band to float a
           narrower sheet, e.g. min(var(--layout-sm), 100%) */
        --ui-drawer-w: 100%;
        --ui-drawer-max-h: calc(100dvb - var(--space-lg));
    
        /* stack: how much each drawer in front shrinks and lifts the one behind */
        --ui-drawer-stack-scale: 0.05;
        --ui-drawer-stack-lift: var(--space-sm);
        /* the page is already dimmed by the first drawer's backdrop */
        --ui-drawer-nested-backdrop-color: transparent;
    
        /* indent: how far each side of the page pulls in, how far it drops, the radius of
           its top corners, and the color behind it. Set these on :root: the body reads the
           backing color too. */
        --ui-drawer-indent-inset: calc(var(--spacing) * 3);
        --ui-drawer-indent-offset: calc(env(safe-area-inset-top, 0px) + var(--space-sm));
        --ui-drawer-indent-radius: var(--ui-drawer-radius);
        --ui-drawer-indent-bg: var(--color-background);
        --ui-drawer-indent-backing: var(--color-black);
    
        /* handle */
        --ui-drawer-handle-w: calc(var(--spacing) * 12);
        --ui-drawer-handle-h: calc(var(--spacing) * 1.25);
        --ui-drawer-handle-bg: var(--color-muted);
        --ui-drawer-handle-bg--hover: var(--color-muted-foreground);
        --ui-drawer-handle-bg--active: var(--color-muted-foreground);
        --ui-drawer-handle-bg--dragging: var(--color-foreground);
    
        /* motion: the iOS sheet curve, steep at the start so twice the default
           duration still reads as quick; 0s under reduced motion like the default */
        --ui-drawer-transition-duration: calc(var(--default-transition-duration) * 2);
        --ui-drawer-transition-timing-function: cubic-bezier(0.32, 0.72, 0, 1);
      }
    }
    
    /* Drawer mode flag, read by drawer.js; and the backdrop's drag opacity, written by it.
       Non-inheriting, so neither restyles the drawer's content. */
    @property --_drawer-mode {
      syntax: "*";
      inherits: false;
    }
    
    @property --_drawer-backdrop {
      syntax: "*";
      inherits: false;
    }
    
    /* Where a drawer with snap points rests, and how many drawers sit in front of it:
       both written by drawer.js when they change (the depth also while the front drawer
       is dragged), and non-inheriting, so neither restyles the drawer's content. */
    @property --_drawer-snap {
      syntax: "*";
      inherits: false;
    }
    
    @property --_drawer-depth {
      syntax: "*";
      inherits: false;
    }
    
    /* The software keyboard's height while the drawer is the front one, written by
       drawer.js from the visual viewport; the sheet's bottom padding takes it. */
    @property --_drawer-keyboard {
      syntax: "*";
      inherits: false;
    }
    
    /* The indent's measurements, written by drawer.js when a drawer opens, and how
       indented the page is (0 to 1): 1 from the `active` state, or the drag's own
       value while the last drawer is dragged. The corner pieces take them by explicit
       inheritance. The inset is typed so the script reads the hook in px. */
    @property --_drawer-indent-amount {
      syntax: "*";
      inherits: false;
    }
    
    @property --_drawer-indent-scale {
      syntax: "*";
      inherits: false;
    }
    
    @property --_drawer-indent-top {
      syntax: "*";
      inherits: false;
    }
    
    @property --_drawer-indent-bottom {
      syntax: "*";
      inherits: false;
    }
    
    @property --_drawer-indent-inset {
      syntax: "<length>";
      inherits: false;
      initial-value: 0px;
    }
    
    @layer ui.components {
      /* ===========================================================================
      DRAWER MODE: the declarations that make a dialog a bottom sheet. Written
      twice, because the two forms enter it under different conditions: the
      standalone form always, the combined form on a phone. Keep the two blocks
      identical apart from the --_dialog-* lines, which feed the dialog's own
      read chain in the combined form.
    
      The sheet extends --_bleed past the bottom edge (padding inside,
      an equal negative margin outside), so pulling it up against its resistance
      never opens a gap under it.
      =========================================================================== */
    
      :where([data-ui~="drawer"]:not([data-ui~="dialog"])) {
        --_drawer-mode: 1;
        --_bleed: calc(var(--spacing) * 12);
        --_handle-display: block;
        --_content-row: 2;
        --_header-select: none;
    
        --ui-dialog-transition-duration: var(--ui-drawer-transition-duration);
        --ui-dialog-transition-timing-function: var(--ui-drawer-transition-timing-function);
        --ui-dialog-backdrop-transition-duration: var(--ui-dialog-transition-duration);
        --ui-dialog-backdrop-transition-timing-function: var(--ui-drawer-transition-timing-function);
        --ui-dialog-transition-delay--end: 0ms;
        --ui-dialog-opacity--start: 1;
        --ui-dialog-scale--start: 1;
        --ui-dialog-translate--start: 0, 100%, 0;
    
        margin-block: auto calc(var(--_bleed) * -1);
        margin-inline: auto;
        /* the keyboard covers the home indicator: the larger of the two, not both */
        padding-block-end: calc(
          var(--_bleed) + max(env(safe-area-inset-bottom, 0px), var(--_drawer-keyboard, 0px))
        );
        max-inline-size: 100%;
        max-block-size: calc(var(--ui-drawer-max-h) + var(--_bleed));
        grid-template-rows: auto minmax(0, 1fr);
        border-block-end-width: 0;
        border-end-start-radius: 0;
        border-end-end-radius: 0;
        /* a stacked drawer shrinks toward its top edge, the part that stays in view */
        transform-origin: 50% 0;
      }
    
      @media (width < 40rem) and (not (hover: hover)) {
        :where([data-ui~="dialog"][data-ui~="drawer"]) {
          --_drawer-mode: 1;
          --_bleed: calc(var(--spacing) * 12);
          --_handle-display: block;
          --_content-row: 2;
          --_header-select: none;
    
          --_dialog-w: var(--ui-drawer-w);
          --_dialog-radius: var(--ui-drawer-radius);
          --_dialog-shadow: var(--ui-drawer-shadow);
    
          --ui-dialog-transition-duration: var(--ui-drawer-transition-duration);
          --ui-dialog-transition-timing-function: var(--ui-drawer-transition-timing-function);
          --ui-dialog-backdrop-transition-duration: var(--ui-dialog-transition-duration);
          --ui-dialog-backdrop-transition-timing-function: var(--ui-drawer-transition-timing-function);
          --ui-dialog-transition-delay--end: 0ms;
          --ui-dialog-opacity--start: 1;
          --ui-dialog-scale--start: 1;
          --ui-dialog-translate--start: 0, 100%, 0;
    
          margin-block: auto calc(var(--_bleed) * -1);
          margin-inline: auto;
          /* the keyboard covers the home indicator: the larger of the two, not both */
          padding-block-end: calc(
            var(--_bleed) + max(env(safe-area-inset-bottom, 0px), var(--_drawer-keyboard, 0px))
          );
          max-inline-size: 100%;
          max-block-size: calc(var(--ui-drawer-max-h) + var(--_bleed));
          grid-template-rows: auto minmax(0, 1fr);
          border-block-end-width: 0;
          border-end-start-radius: 0;
          border-end-end-radius: 0;
          transform-origin: 50% 0;
        }
      }
    
      /* ===========================================================================
      STANDALONE SURFACE: without the dialog identity the drawer paints itself.
      The combined form takes all of this from dialog.css.
      =========================================================================== */
    
      :where([data-ui~="drawer"]:not([data-ui~="dialog"])) {
        inline-size: var(--ui-drawer-w);
        block-size: fit-content;
        background-color: var(--_bg-resolved, var(--ui-drawer-bg));
        color: var(--_text-resolved, var(--ui-drawer-text));
        box-shadow: var(--_shadow-resolved, var(--ui-drawer-shadow));
        /* the top corners only: the bottom edge sits past the viewport */
        border-start-start-radius: var(--ui-drawer-radius);
        border-start-end-radius: var(--ui-drawer-radius);
        corner-shape: var(--_corner-shape-resolved, var(--ui-drawer-corner-shape));
        font-size: var(--font-size-md);
        overflow: hidden;
        overscroll-behavior: contain;
      }
    
      :where([data-ui~="drawer"]:not([data-ui~="dialog"])[open]) {
        display: grid;
        min-block-size: 0;
      }
    
      /* ===========================================================================
      SNAP POINTS: a drawer with data-drawer-snap is as tall as a drawer may be and
      rests pushed down by --_drawer-snap, which drawer.js writes when the stop
      changes. The height is set per form, like drawer mode itself.
      =========================================================================== */
    
      :where([data-ui~="drawer"]:not([data-ui~="dialog"])[data-drawer-snap]) {
        block-size: calc(var(--ui-drawer-max-h) + var(--_bleed));
      }
    
      @media (width < 40rem) and (not (hover: hover)) {
        :where([data-ui~="dialog"][data-ui~="drawer"][data-drawer-snap]) {
          --_dialog-h: calc(var(--ui-drawer-max-h) + var(--_bleed));
        }
      }
    
      :where([data-ui~="drawer"][data-drawer-snap]) {
        translate: 0 var(--_drawer-snap, 0px);
      }
    
      /* ===========================================================================
      STACK: a drawer with others open in front of it shrinks toward its top edge
      and lifts, once per drawer in front. drawer.js writes the count, and while
      the front drawer is dragged a fraction of it (state `following`, transitions
      off). A drawer opened over another dims nothing more.
      =========================================================================== */
    
      :where([data-ui~="drawer"][data-drawer-state~="stacked"]) {
        scale: calc(1 - var(--_drawer-depth, 0) * var(--ui-drawer-stack-scale));
        translate: 0
          calc(var(--_drawer-snap, 0px) - var(--_drawer-depth, 0) * var(--ui-drawer-stack-lift));
      }
    
      :where([data-ui~="drawer"][data-drawer-state~="following"]) {
        transition: none;
      }
    
      :where([data-ui~="drawer"][data-drawer-state~="nested"])::backdrop {
        background-color: var(--ui-drawer-nested-backdrop-color);
        backdrop-filter: none;
      }
    
      /* Each slot owns a row, as in the dialog: the body is the part that scrolls */
      :where([data-ui~="drawer"]) [data-drawer-slot~="content"] {
        display: grid;
        grid-template-rows: auto minmax(0, 1fr) auto;
        position: relative;
        min-block-size: 0;
        max-block-size: 100%;
      }
    
      :where([data-ui~="drawer"]) [data-drawer-slot~="header"] {
        grid-row: 1;
        display: flex;
        flex-direction: column;
        padding-inline: var(--space-sm);
        padding-block-start: var(--space-sm);
      }
    
      :where([data-ui~="drawer"]) [data-drawer-slot~="body"] {
        grid-row: 2;
        display: grid;
        align-content: start;
        padding-inline: var(--space-sm);
        padding-block: var(--space-md);
        min-block-size: 0;
        overflow-y: auto;
        overscroll-behavior: contain;
      }
    
      :where([data-ui~="drawer"]) [data-drawer-slot~="footer"] {
        grid-row: 3;
        display: flex;
        justify-content: flex-end;
        gap: var(--space-xs);
        padding: var(--space-sm);
        border-block-start: 1px solid var(--color-border);
      }
    
      :where([data-ui~="drawer"]) [data-drawer-slot~="close"] {
        position: absolute;
        inset-block-start: var(--space-xs);
        inset-inline-end: var(--space-xs);
        z-index: 50;
      }
    
      /* ===========================================================================
      PARTS IN DRAWER MODE: the handle shows and takes the first row; the content
      slot (the drawer's own or the dialog's) takes the flexible second row, with
      or without a handle before it. Both read the mode privates set above, so
      neither rule is repeated per form.
      =========================================================================== */
    
      :where([data-ui~="drawer"]) :where([data-drawer-slot~="content"], [data-dialog-slot~="content"]) {
        grid-row: var(--_content-row, auto);
      }
    
      /* The header is where a mouse grabs the drawer: a press on its text drags
         instead of selecting. Body text stays selectable. */
      :where([data-ui~="drawer"]) :where([data-drawer-slot~="header"], [data-dialog-slot~="header"]) {
        -webkit-user-select: var(--_header-select, auto);
        user-select: var(--_header-select, auto);
      }
    
      /* A pill, with a hit area that reaches the touch-target height. It always
         drags, even over a scrolled body, so it opts out of native panning. */
      :where([data-ui~="drawer"]) [data-drawer-slot~="handle"] {
        display: var(--_handle-display, none);
        grid-row: 1;
        justify-self: center;
        position: relative;
        inline-size: var(--ui-drawer-handle-w);
        block-size: var(--ui-drawer-handle-h);
        margin-block: calc(var(--spacing) * 2.5) calc(var(--spacing) * 1);
        border-radius: var(--radius-full);
        background-color: var(--ui-drawer-handle-bg);
        cursor: grab;
        touch-action: none;
        -webkit-user-select: none;
        user-select: none;
        transition: background-color var(--default-transition-duration)
          var(--default-transition-timing-function);
      }
    
      :where([data-ui~="drawer"]) [data-drawer-slot~="handle"]:hover {
        background-color: var(--ui-drawer-handle-bg--hover);
      }
    
      :where([data-ui~="drawer"]) [data-drawer-slot~="handle"]:active {
        background-color: var(--ui-drawer-handle-bg--active);
        cursor: grabbing;
      }
    
      :where([data-ui~="drawer"]) [data-drawer-slot~="handle"]::before {
        content: "";
        position: absolute;
        inset-inline: calc(var(--ui-drawer-handle-w) * -1);
        inset-block: min(calc(var(--spacing) * -2), calc((100% - var(--_touch-min, 0px)) / 2));
      }
    
      /* Below its largest snap point a drawer's content does not scroll: the drawer
         moves first. After the slot rules, which it has to beat. */
      :where([data-ui~="drawer"][data-drawer-state~="partial"])
        :is([data-drawer-slot~="body"], [data-dialog-slot~="body"]) {
        overflow-y: hidden;
      }
    
      /* ===========================================================================
      DRAG: while a pointer drags the drawer, drawer.js writes its inline
      translate and nothing may ease it: the drawer is the pointer. The backdrop
      fades with the drag: drawer.js scrubs an animation on it, or, where
      ::backdrop cannot be animated from script, writes --_drawer-backdrop, which
      the backdrop takes from the dialog by explicit inheritance. On release the state drops and the dialog's
      own transitions finish the motion, to closed or back to rest.
      =========================================================================== */
    
      :where([data-ui~="drawer"][data-drawer-state~="dragging"]) [data-drawer-slot~="handle"] {
        background-color: var(--ui-drawer-handle-bg--dragging);
      }
    
      :where([data-ui~="drawer"][data-drawer-state~="dragging"]) {
        transition: none;
        cursor: grabbing;
        /* a mouse drag that began beside text must not start selecting it */
        -webkit-user-select: none;
        user-select: none;
      }
    
      :where([data-ui~="drawer"][data-drawer-state~="dragging"])::backdrop {
        --_drawer-backdrop: inherit;
        opacity: var(--_drawer-backdrop, 1);
        transition: none;
      }
    
      /* ===========================================================================
      INDENT: the page wrapper scales back behind an open drawer. drawer.js sets the
      state (`on` while the machinery is engaged, `active` while a drawer is open,
      `dragging` while the last drawer is dragged) and measures, once, the scale and
      where the viewport sits inside the wrapper.
    
      Only scale and translate animate. The wrapper is clipped to the viewport's
      rectangle, a fixed clip, so the page above and below it stays out of the gaps;
      the body paints the backing color there. The rounded top corners are two
      corner pieces that grow from the corners, not a border-radius: nothing is
      repainted while the page moves.
    
      While `on` the wrapper is transformed, so it is the containing block of its
      fixed and absolute descendants.
      =========================================================================== */
    
      :where(ui-drawer-indent, [data-ui~="drawer-indent"]) {
        --_drawer-indent-inset: var(--ui-drawer-indent-inset);
        display: block;
        background-color: var(--ui-drawer-indent-bg);
        transition:
          scale var(--ui-drawer-transition-duration) var(--ui-drawer-transition-timing-function),
          translate var(--ui-drawer-transition-duration) var(--ui-drawer-transition-timing-function);
      }
    
      :where(ui-drawer-indent, [data-ui~="drawer-indent"])[data-drawer-indent-state~="on"] {
        position: relative;
        transform-origin: 50% var(--_drawer-indent-top, 0px);
        scale: calc(1 - (1 - var(--_drawer-indent-scale, 1)) * var(--_drawer-indent-amount, 0));
        translate: 0 calc(var(--ui-drawer-indent-offset) * var(--_drawer-indent-amount, 0));
        clip-path: inset(var(--_drawer-indent-top, 0px) 0 var(--_drawer-indent-bottom, 0px) 0);
        will-change: scale, translate;
      }
    
      :where(ui-drawer-indent, [data-ui~="drawer-indent"])[data-drawer-indent-state~="active"] {
        --_drawer-indent-amount: 1;
      }
    
      /* The backing shows in the gaps around the indented page. Important, because a
         page's own <body style="--bg: …"> is a utility and would otherwise win; it holds
         only while the wrapper is `on`. */
      :where(body):has(
        :is(ui-drawer-indent, [data-ui~="drawer-indent"])[data-drawer-indent-state~="on"]
      ) {
        background-color: var(--ui-drawer-indent-backing) !important;
      }
    
      /* A corner piece: a square the size of the radius whose outer corner is rounded
         and whose spread shadow, cut off at the square, paints only the notch outside
         the curve. Scaling it from that corner is the radius growing. */
      :where(ui-drawer-indent, [data-ui~="drawer-indent"])[data-drawer-indent-state~="on"]::before,
      :where(ui-drawer-indent, [data-ui~="drawer-indent"])[data-drawer-indent-state~="on"]::after {
        --_drawer-indent-amount: inherit;
        --_drawer-indent-top: inherit;
        content: "";
        position: absolute;
        z-index: 2147483647;
        inset-block-start: var(--_drawer-indent-top, 0px);
        inline-size: var(--ui-drawer-indent-radius);
        block-size: var(--ui-drawer-indent-radius);
        box-shadow: 0 0 0 var(--ui-drawer-indent-radius) var(--ui-drawer-indent-backing);
        clip-path: inset(0);
        corner-shape: var(--radius-corner-shape);
        scale: var(--_drawer-indent-amount, 0);
        pointer-events: none;
        transition: scale var(--ui-drawer-transition-duration)
          var(--ui-drawer-transition-timing-function);
    
        @starting-style {
          scale: 0;
        }
      }
    
      :where(ui-drawer-indent, [data-ui~="drawer-indent"])[data-drawer-indent-state~="on"]::before {
        left: 0;
        border-top-left-radius: 100%;
        transform-origin: 0 0;
      }
    
      :where(ui-drawer-indent, [data-ui~="drawer-indent"])[data-drawer-indent-state~="on"]::after {
        right: 0;
        border-top-right-radius: 100%;
        transform-origin: 100% 0;
      }
    
      :where(ui-drawer-indent, [data-ui~="drawer-indent"])[data-drawer-indent-state~="dragging"],
      :where(
          ui-drawer-indent,
          [data-ui~="drawer-indent"]
        )[data-drawer-indent-state~="dragging"]::before,
      :where(
          ui-drawer-indent,
          [data-ui~="drawer-indent"]
        )[data-drawer-indent-state~="dragging"]::after {
        transition: none;
      }
    }
    // primitives/drawer/drawer.js
    "use strict";
    /**
     * @fileoverview Drawer: drag-to-dismiss for `<dialog data-ui="drawer">` bottom sheets.
     * @description A drawer is a native modal `<dialog>`, opened and closed like
     * any other (`command="show-modal"`, `command="close"`, Esc, the backdrop with
     * `closedby="any"`). This script adds the gesture: drag the drawer down and
     * let go to dismiss it.
     *
     * - `data-ui="drawer"` is a drawer on every device.
     * - `data-ui="dialog drawer"` is a drawer below the `sm` band on a touch
     *   screen, and a plain dialog (no dragging) everywhere else.
     *
     * While the pointer is down the drawer follows it 1:1 and the backdrop fades
     * with it. Letting go past a quarter of the drawer's height, or with a quick
     * downward flick, slides it off the bottom edge and then closes it through
     * `requestClose()`, so `cancel` and `close` fire as they do for Esc; anything
     * less returns it to rest. Until it has slid out it can be caught again. Pulling it up
     * past its resting place meets resistance.
     *
     * A drag starts anywhere on the drawer except on form fields, selected text,
     * and anything inside `[data-ui-no-drag]`. Inside scrolling content it starts
     * only once that content is scrolled to the top and the pointer moves down,
     * so the body scrolls first and the drawer follows; the handle
     * (`data-drawer-slot="handle"`) always drags. There is no custom element and
     * nothing to initialize: the script binds a drawer when it opens.
     *
     * **Snap points.** `data-drawer-snap="148px 0.5 1"` gives the drawer resting
     * heights, smallest first: a number up to 1 is a share of the drawer's full
     * height, a `px` or `rem` length is a visible height. It opens at the first.
     * Letting go settles on the nearest; a flick moves one stop in its direction,
     * a very fast one goes all the way (or one stop, with
     * `data-drawer-snap-sequential`), and from the lowest stop a flick or enough
     * travel downward closes the drawer. Below the largest stop the drawer takes
     * every vertical drag and its content does not scroll. A click on the handle
     * steps to the next stop; make the handle a `<button>` to give the keyboard
     * the same. Each change fires `zazz:drawer-snap` (`detail.index`,
     * `detail.value` in px), `data-drawer-state` carries `expanded` at the largest
     * stop, and `snapDrawer(dialog, index)` moves it from script.
     *
     * **The software keyboard.** A phone lays a drawer out against the full
     * screen, which the keyboard does not shrink. While a field in the front
     * drawer has the keyboard up, the drawer's content ends at the keyboard's top
     * edge (its surface runs on underneath), the focused field scrolls into what
     * is still visible, and the page behind stays where it was. Nothing to author.
     *
     * **Stacked drawers.** A drawer opened over another scales the one behind back
     * and lifts it, and that one follows as the front drawer is dragged. Nothing
     * to author: the script counts the open drawers.
     *
     * **Indent.** Wrap the page in `<ui-drawer-indent>` (or put
     * `data-ui="drawer-indent"` on its wrapper) and it scales back behind any open
     * drawer, with rounded top corners, and follows the drag of the last one. Only
     * transforms animate. While indented the wrapper is transformed, so a
     * `position: fixed` element inside it moves with the page; `position: sticky`
     * is unaffected.
     *
     * @example
     * <button data-ui="button" command="show-modal" commandfor="filters">Filters</button>
     * <dialog id="filters" data-ui="drawer" closedby="any">
     *   <div data-drawer-slot="handle"></div>
     *   <div data-drawer-slot="content">
     *     <header data-drawer-slot="header">…</header>
     *     <div data-drawer-slot="body">…</div>
     *   </div>
     * </dialog>
     */
    import { currentTranslate, maxTransitionMs, pickSnap, rubberBand, trackDrag, } from "../../base/gesture.js";
    // --- Tuning ---
    /** Share of the drawer's visible height, at its lowest stop, that dismisses on its own. */
    const CLOSE_RATIO = 0.25;
    /** Speed that moves the drawer one stop, or dismisses it from the lowest, in px/ms. */
    const FLICK_VELOCITY = 0.4;
    /** Speed that skips every stop: all the way open, or closed, in px/ms. */
    const FLING_VELOCITY = 2;
    /**
     * After inner content scrolls, how long before the drawer may be dragged, in
     * ms. A fast scroll that reaches the top would otherwise carry straight on
     * into dragging the drawer away.
     */
    const SCROLL_GUARD_MS = 100;
    /** Length of the backdrop's scrub animation: its timeline is drag progress, not time. */
    const SCRUB_MS = 1000;
    const DRAWER = 'dialog[data-ui~="drawer"]';
    const HANDLE = '[data-drawer-slot~="handle"]';
    const INDENT = 'ui-drawer-indent, [data-ui~="drawer-indent"]';
    const INDENT_STATE = "data-drawer-indent-state";
    // --- Helpers ---
    /** Adds or removes one token of a space-separated state attribute; an empty attribute is removed. */
    function setToken(element, attribute, token, on) {
        const tokens = new Set((element.getAttribute(attribute) ?? "").split(/\s+/).filter(Boolean));
        if (tokens.has(token) === on)
            return;
        if (on)
            tokens.add(token);
        else
            tokens.delete(token);
        if (tokens.size)
            element.setAttribute(attribute, [...tokens].join(" "));
        else
            element.removeAttribute(attribute);
    }
    /** Adds or removes a token of a drawer's `data-drawer-state`. */
    function setState(dialog, token, on) {
        setToken(dialog, "data-drawer-state", token, on);
    }
    /** Adds or removes the `dragging` token of a drawer's `data-drawer-state`. */
    function setDragging(dialog, on) {
        setState(dialog, "dragging", on);
    }
    /** Clears everything a drag wrote on the drawer. */
    function reset(dialog) {
        setDragging(dialog, false);
        dialog.style.removeProperty("translate");
        dialog.style.removeProperty("--_drawer-backdrop");
    }
    /**
     * @description Reads a drawer's snap points as resting positions: px the
     * drawer is pushed down at each, the smallest visible height first.
     *
     * @param dialog - The drawer.
     * @param height - The drawer's full visible height in px.
     * @returns The positions, descending; `[0]` without usable snap points.
     * @private
     */
    function readStops(dialog, height) {
        const raw = dialog.getAttribute("data-drawer-snap")?.trim();
        if (!raw)
            return [0];
        const rem = Number.parseFloat(getComputedStyle(document.documentElement).fontSize) || 16;
        const positions = new Set();
        for (const token of raw.split(/\s+/)) {
            const value = Number.parseFloat(token);
            if (!Number.isFinite(value) || value <= 0)
                continue;
            let visible = value * height;
            if (token.endsWith("rem"))
                visible = value * rem;
            else if (token.endsWith("px") || value > 1)
                visible = value;
            positions.add(Math.round(height - Math.min(height, Math.max(1, visible))));
        }
        return positions.size ? [...positions].sort((a, b) => b - a) : [0];
    }
    /**
     * @description Starts a paused opacity animation on the drawer's backdrop, to
     * be scrubbed with the drag. An animation, not a style write: it reaches the
     * pseudo-element without restyling the drawer's content, in engines that do
     * not re-resolve `::backdrop` when a non-inherited property changes on its
     * dialog (WebKit).
     *
     * @param dialog - The drawer.
     * @returns The animation, or null where `::backdrop` cannot be animated; the
     * caller then writes `--_drawer-backdrop`, which drawer.css reads.
     * @private
     */
    function scrubBackdrop(dialog) {
        try {
            const animation = dialog.animate([{ opacity: 1 }, { opacity: 0 }], {
                pseudoElement: "::backdrop",
                duration: SCRUB_MS,
                fill: "both",
            });
            animation.pause();
            return animation;
        }
        catch {
            return null;
        }
    }
    /** Whether drawer.css has the dialog in drawer mode right now. */
    function inDrawerMode(dialog) {
        return getComputedStyle(dialog).getPropertyValue("--_drawer-mode").trim() === "1";
    }
    /** Whether an element scrolls its content on the block axis. */
    function scrolls(element) {
        if (element.scrollHeight <= element.clientHeight)
            return false;
        const overflow = getComputedStyle(element).overflowY;
        return overflow === "auto" || overflow === "scroll";
    }
    /**
     * @description Whether a press may drag the drawer, given what it landed on
     * and which way it is moving.
     *
     * @param dialog - The drawer.
     * @param drag - The drag about to start; `offset` carries its direction.
     * @param lastScroll - When content inside the drawer last scrolled.
     * @param partial - Whether the drawer rests below its largest snap point.
     * @returns Whether the drawer takes the gesture.
     * @private
     */
    function claims(dialog, drag, lastScroll, partial) {
        if (!inDrawerMode(dialog))
            return false;
        // a press on the backdrop targets the dialog, outside its box
        const box = dialog.getBoundingClientRect();
        if (drag.startY < box.top || drag.startX < box.left || drag.startX > box.right)
            return false;
        if (drag.target.closest(HANDLE))
            return true;
        // below its largest stop the drawer moves before anything inside it scrolls
        if (partial)
            return true;
        // scrolling content goes first: it must be at the top, and the pull downward
        const down = drag.offset > 0;
        for (let node = drag.target; node && dialog.contains(node); node = node.parentElement) {
            if (scrolls(node) && (node.scrollTop > 0 || !down))
                return false;
        }
        return performance.now() - lastScroll >= SCROLL_GUARD_MS;
    }
    // --- Stack ---
    /** The open drawers in drawer mode, the front one last. */
    const stack = [];
    /**
     * @description Writes each open drawer's place in the stack: how many drawers
     * sit in front of it (`--_drawer-depth`, `stacked`) and whether it opened over
     * another (`nested`). Runs when a drawer opens or closes, never per frame.
     * @private
     */
    function restack() {
        // a drawer removed from the page while open never reports its close
        for (let index = stack.length - 1; index >= 0; index--) {
            const dialog = stack[index];
            if (!dialog.isConnected || !dialog.open)
                stack.splice(index, 1);
        }
        stack.forEach((dialog, index) => {
            const depth = stack.length - 1 - index;
            setState(dialog, "following", false);
            setState(dialog, "stacked", depth > 0);
            setState(dialog, "nested", index > 0);
            if (depth > 0)
                dialog.style.setProperty("--_drawer-depth", String(depth));
            else
                dialog.style.removeProperty("--_drawer-depth");
        });
        indentPose(stack.length > 0);
    }
    /**
     * @description Moves the drawers behind `front` with its drag: at progress 1
     * each sits where it will once `front` is gone. The depth is a non-inheriting
     * property, so the write restyles those drawers and not their content.
     *
     * @param front - The drawer being dragged or released.
     * @param progress - How far `front` is toward closed, 0 to 1.
     * @param live - Whether a pointer is driving it (transitions off).
     * @private
     */
    function follow(front, progress, live) {
        const index = stack.indexOf(front);
        for (let behind = 0; behind < index; behind++) {
            const dialog = stack[behind];
            dialog.style.setProperty("--_drawer-depth", String(index - behind - progress));
            setState(dialog, "following", live);
        }
    }
    // --- Indent ---
    /** The page wrapper that is indented right now, and what ends its return to rest. */
    let indented = null;
    let cancelOutdent = null;
    /**
     * @description Measures what the indent needs, once per activation and on
     * resize: the scale that pulls each side in by the inset hook, and where the
     * viewport sits inside the wrapper (the transform's origin, the clip, and the
     * corner pieces all hang off its top edge).
     * @private
     */
    function measureIndent(wrapper) {
        const box = wrapper.getBoundingClientRect();
        const width = wrapper.offsetWidth || 1;
        const inset = Number.parseFloat(getComputedStyle(wrapper).getPropertyValue("--_drawer-indent-inset")) || 0;
        const top = Math.max(0, -box.top);
        const bottom = Math.max(0, wrapper.offsetHeight - top - window.innerHeight);
        wrapper.style.setProperty("--_drawer-indent-scale", String(Math.max(0, 1 - (inset * 2) / width)));
        wrapper.style.setProperty("--_drawer-indent-top", `${top}px`);
        wrapper.style.setProperty("--_drawer-indent-bottom", `${bottom}px`);
    }
    /**
     * @description Indents the page wrapper or sends it back to rest. The pose is
     * a state token and the motion a CSS transition; the `on` token (clip,
     * corners, backing) outlasts the pose until the return has finished.
     *
     * @param active - Whether a drawer is open.
     * @private
     */
    function indentPose(active) {
        // a wrapper that left the page takes its state with it
        if (indented && !indented.isConnected) {
            cancelOutdent?.();
            indented = null;
        }
        const wrapper = indented ?? document.querySelector(INDENT);
        if (!wrapper)
            return;
        if (active) {
            cancelOutdent?.();
            if (indented !== wrapper) {
                measureIndent(wrapper);
                indented = wrapper;
            }
            setToken(wrapper, INDENT_STATE, "on", true);
            setToken(wrapper, INDENT_STATE, "active", true);
            return;
        }
        if (!indented || cancelOutdent)
            return;
        setToken(wrapper, INDENT_STATE, "dragging", false);
        wrapper.style.removeProperty("--_drawer-indent-amount");
        setToken(wrapper, INDENT_STATE, "active", false);
        const off = () => {
            cancelOutdent?.();
            wrapper.removeAttribute(INDENT_STATE);
            for (const name of ["scale", "top", "bottom"]) {
                wrapper.style.removeProperty(`--_drawer-indent-${name}`);
            }
            indented = null;
        };
        const ms = maxTransitionMs(wrapper);
        if (ms <= 0) {
            off();
            return;
        }
        const onReturned = (event) => {
            if (event.target === wrapper && event.propertyName === "scale")
                off();
        };
        const timer = window.setTimeout(off, ms + 100);
        wrapper.addEventListener("transitionend", onReturned);
        cancelOutdent = () => {
            window.clearTimeout(timer);
            wrapper.removeEventListener("transitionend", onReturned);
            cancelOutdent = null;
        };
    }
    /**
     * @description Links the indent to the last open drawer's drag.
     *
     * @param progress - How far the drawer is toward closed, 0 to 1.
     * @param live - Whether a pointer is driving it (transitions off).
     * @private
     */
    function indentProgress(progress, live) {
        if (!indented)
            return;
        setToken(indented, INDENT_STATE, "dragging", live);
        if (live)
            indented.style.setProperty("--_drawer-indent-amount", String(1 - progress));
        else
            indented.style.removeProperty("--_drawer-indent-amount");
    }
    // --- Keyboard ---
    /** The keyboard's height on the front drawer, which drawer.css adds to its bottom padding. */
    const KEYBOARD_INSET = "--_drawer-keyboard";
    /** Space kept between a revealed field and the keyboard's top edge, in px. */
    const REVEAL_GAP = 16;
    /** Inputs that open a picker or nothing rather than the software keyboard. */
    const NO_KEYBOARD = /^(?:button|checkbox|color|file|hidden|image|radio|range|reset|submit|date|datetime-local|month|time|week)$/;
    /** Whether focus on this element opens the software keyboard. */
    function typesText(element) {
        if (element instanceof HTMLTextAreaElement)
            return !element.readOnly;
        if (element instanceof HTMLInputElement)
            return !element.readOnly && !NO_KEYBOARD.test(element.type);
        return element instanceof HTMLElement && element.isContentEditable;
    }
    /**
     * @description How much of the layout viewport the software keyboard covers,
     * from the bottom: the part below the visual viewport. 0 while the page is
     * pinch-zoomed, when the visual viewport is smaller for another reason.
     * @private
     */
    function keyboardInset() {
        const viewport = window.visualViewport;
        if (!viewport || Math.abs(viewport.scale - 1) > 0.01)
            return 0;
        const bottom = Math.max(0, viewport.offsetTop) + viewport.height;
        return Math.max(0, Math.round(window.innerHeight - Math.min(window.innerHeight, bottom)));
    }
    /**
     * @description Keeps an open drawer usable with the software keyboard up.
     * iOS lays out the top layer against the layout viewport, which the keyboard
     * does not shrink, and scrolls the page behind a modal to reveal a focused
     * field. While the drawer is the front one this writes the keyboard's height
     * to `--_drawer-keyboard` (drawer.css pads the sheet by it, so its
     * content ends at the keyboard's top edge), holds the page at its scroll
     * position, and scrolls a focused field into the part of its scrolling slot
     * that is still visible.
     *
     * @param dialog - The drawer.
     * @param signal - Aborts when the drawer closes.
     * @param onChange - Runs after the inset changes, once the new padding is in place.
     * @private
     */
    function trackKeyboard(dialog, signal, onChange) {
        const viewport = window.visualViewport;
        if (!viewport)
            return;
        const front = () => stack[stack.length - 1] === dialog;
        const pageX = window.scrollX;
        const pageY = window.scrollY;
        let frame = 0;
        let current = 0;
        const update = () => {
            frame = 0;
            const inset = front() ? keyboardInset() : 0;
            if (inset === current)
                return;
            current = inset;
            if (inset > 0)
                dialog.style.setProperty(KEYBOARD_INSET, `${inset}px`);
            else
                dialog.style.removeProperty(KEYBOARD_INSET);
            onChange();
        };
        const schedule = () => {
            if (!frame)
                frame = requestAnimationFrame(update);
        };
        /** Scrolls the field's scrolling slot so the field sits above the keyboard and below the slot's top. */
        const reveal = (field) => {
            if (!dialog.contains(field) || document.activeElement !== field)
                return;
            let container = field.parentElement;
            while (container && dialog.contains(container) && !scrolls(container)) {
                container = container.parentElement;
            }
            if (!container || !dialog.contains(container))
                return;
            const box = container.getBoundingClientRect();
            const target = field.getBoundingClientRect();
            const visibleBottom = Math.min(box.bottom, viewport.offsetTop + viewport.height) - REVEAL_GAP;
            const visibleTop = Math.max(box.top, viewport.offsetTop) + REVEAL_GAP;
            let by = 0;
            if (target.bottom > visibleBottom)
                by = target.bottom - visibleBottom;
            if (target.top - by < visibleTop)
                by = target.top - visibleTop;
            if (Math.abs(by) < 1)
                return;
            const still = matchMedia("(prefers-reduced-motion: reduce)").matches;
            container.scrollBy({ top: by, behavior: still ? "instant" : "smooth" });
        };
        viewport.addEventListener("resize", schedule, { signal });
        viewport.addEventListener("scroll", schedule, { signal });
        // the page behind a modal stays where it was, whatever iOS scrolls to show the field
        window.addEventListener("scroll", () => {
            if (!front() || (window.scrollX === pageX && window.scrollY === pageY))
                return;
            window.scrollTo({ left: pageX, top: pageY, behavior: "instant" });
        }, { passive: true, signal });
        // the keyboard settles over a few frames: reveal after it has, and again once it is up
        dialog.addEventListener("focusin", (event) => {
            const field = event.target;
            if (!(field instanceof Element) || !typesText(field) || !front())
                return;
            for (const ms of [100, 350]) {
                const timer = window.setTimeout(() => {
                    update();
                    reveal(field);
                }, ms);
                signal.addEventListener("abort", () => window.clearTimeout(timer), { once: true });
            }
        }, { signal });
        signal.addEventListener("abort", () => {
            cancelAnimationFrame(frame);
            dialog.style.removeProperty(KEYBOARD_INSET);
        });
        update();
    }
    /** Open drawers and what unbinds or moves each. */
    const bound = new WeakMap();
    /** Each drawer's backdrop animation, kept past its close so the next open can drop it. */
    const fades = new WeakMap();
    /**
     * @description Binds drag-to-dismiss to an open drawer until it closes.
     *
     * @param dialog - The drawer.
     */
    function bindDrawer(dialog) {
        if (bound.has(dialog))
            return;
        const controller = new AbortController();
        const { signal } = controller;
        // what the last dismissal left in place: the slid-out translate, the cleared backdrop
        fades.get(dialog)?.cancel();
        fades.delete(dialog);
        reset(dialog);
        const snaps = dialog.hasAttribute("data-drawer-snap");
        let lastScroll = 0;
        // where the drawer was when the drag caught it (mid snap-back, usually its stop)
        let base = 0;
        let height = 1;
        // the sheet's bleed past the bottom edge: the most it may be pulled up
        let lift = 0;
        // resting positions, px pushed down, the lowest snap point first; and the one it rests at
        let stops = [0];
        let active = 0;
        let fade = null;
        // undoes a dismissal still sliding out, so a new drag can catch the drawer
        let cancelClose = null;
        const measure = () => {
            lift = Math.max(0, -Number.parseFloat(getComputedStyle(dialog).marginBlockEnd) || 0);
            // the layout height: a stacked drawer's scale must not shrink it
            height = Math.max(1, dialog.offsetHeight - lift);
            stops = snaps ? readStops(dialog, height) : [0];
            active = Math.min(active, stops.length - 1);
        };
        /** Writes where the drawer rests: drawer.css turns `--_drawer-snap` into its `translate`. */
        const place = () => {
            if (!snaps)
                return;
            const largest = active === stops.length - 1;
            dialog.style.setProperty("--_drawer-snap", `${stops[active] ?? 0}px`);
            setState(dialog, "expanded", largest);
            setState(dialog, "partial", !largest);
        };
        /** Everything that moves with the drawer's progress toward closed, besides its backdrop. */
        const link = (progress, live) => {
            follow(dialog, progress, live);
            if (stack.length === 1 && stack[0] === dialog)
                indentProgress(progress, live);
        };
        /**
         * Runs the backdrop from where the drag left it to clear or back to full,
         * in `ms`. Back at full the animation is dropped; clear, it holds until the
         * drawer next opens, over whatever the closed dialog's own backdrop does.
         */
        const settle = (closing, ms) => {
            dialog.style.removeProperty("--_drawer-backdrop");
            const animation = fade;
            if (!animation)
                return;
            const done = () => {
                if (closing || fade !== animation || animation.playState !== "finished")
                    return;
                animation.cancel();
                fades.delete(dialog);
                fade = null;
            };
            const at = Number(animation.currentTime) || 0;
            const left = closing ? SCRUB_MS - at : at;
            if (ms <= 0 || left <= 0) {
                animation.playbackRate = closing ? 1 : -1;
                animation.finish();
                done();
                return;
            }
            animation.playbackRate = ((closing ? 1 : -1) * left) / ms;
            animation.play();
            animation.finished.then(done, () => { });
        };
        /** Settles the drawer on a stop; the dialog's `translate` transition carries it there. */
        const snapTo = (index) => {
            const next = Math.min(Math.max(index, 0), stops.length - 1);
            const changed = next !== active;
            active = next;
            place();
            setDragging(dialog, false);
            settle(false, maxTransitionMs(dialog));
            dialog.style.removeProperty("translate");
            link(0, false);
            if (!changed)
                return;
            dialog.dispatchEvent(new CustomEvent("zazz:drawer-snap", {
                bubbles: true,
                detail: { index: active, value: height - (stops[active] ?? 0) },
            }));
        };
        const rest = () => snapTo(active);
        /** Closes the dialog; a `cancel` listener that keeps it open sends it back to rest. */
        const close = () => {
            if (!dialog.open)
                return;
            if (typeof dialog.requestClose === "function")
                dialog.requestClose();
            else
                dialog.close();
            if (!dialog.open)
                return;
            if (stack.length === 1)
                indentPose(true);
            rest();
        };
        /**
         * Slides the drawer off the bottom edge while it is still open, then closes
         * it. The slide is the drawer's own `translate` transition, so it does not
         * depend on the engine animating a dialog's exit (WebKit removes a closed
         * dialog at once), and until it ends the drawer can be caught again.
         * Whatever is linked to the drawer leaves with it.
         */
        const slideOutAndClose = (ms) => {
            dialog.style.translate = `0 ${height + lift}px`;
            settle(true, ms);
            follow(dialog, 1, false);
            if (stack.length === 1 && stack[0] === dialog)
                indentPose(false);
            if (ms <= 0) {
                close();
                return;
            }
            const onSlid = (event) => {
                if (event.target === dialog && event.propertyName === "translate")
                    finish();
            };
            const finish = () => {
                cancelClose?.();
                close();
            };
            // the timer covers a transition that never reports its end
            const timer = window.setTimeout(finish, ms + 100);
            dialog.addEventListener("transitionend", onSlid);
            cancelClose = () => {
                window.clearTimeout(timer);
                dialog.removeEventListener("transitionend", onSlid);
                cancelClose = null;
            };
        };
        bound.set(dialog, { controller, snapTo });
        if (inDrawerMode(dialog)) {
            measure();
            place();
            stack.push(dialog);
            restack();
            trackKeyboard(dialog, signal, () => {
                measure();
                place();
            });
        }
        signal.addEventListener("abort", () => {
            cancelClose?.();
            // a drawer closed some other way mid-drag: nothing may hold the backdrop
            if (fade?.playState === "paused") {
                fade.cancel();
                fades.delete(dialog);
            }
        });
        dialog.addEventListener("scroll", () => {
            lastScroll = performance.now();
        }, { capture: true, passive: true, signal });
        // the handle steps through the snap points: a click, so a button handle works from the keyboard
        dialog.addEventListener("click", (event) => {
            if (stops.length < 2 || !(event.target instanceof Element))
                return;
            if (event.target.closest(HANDLE))
                snapTo((active + 1) % stops.length);
        }, { signal });
        window.addEventListener("resize", () => {
            if (!stack.includes(dialog))
                return;
            measure();
            place();
        }, { signal });
        trackDrag(dialog, {
            axis: "y",
            signal,
            canStart: (drag) => claims(dialog, drag, lastScroll, active < stops.length - 1),
            onStart: () => {
                // a drawer caught on its way out: what left with it comes back
                if (cancelClose && stack.length === 1)
                    indentPose(true);
                cancelClose?.();
                base = currentTranslate(dialog).y;
                measure();
                if (!fade) {
                    fade = scrubBackdrop(dialog);
                    if (fade)
                        fades.set(dialog, fade);
                }
                fade?.pause();
                setDragging(dialog, true);
            },
            onMove: ({ offset }) => {
                const travel = base + offset;
                const top = stops[stops.length - 1] ?? 0;
                const y = travel >= top ? travel : top + rubberBand(travel - top, lift + top);
                dialog.style.translate = `0 ${y}px`;
                // progress runs from the lowest stop to gone: above it nothing fades
                const lowest = stops[0] ?? 0;
                const progress = Math.min(1, Math.max(0, (y - lowest) / Math.max(1, height - lowest)));
                if (fade)
                    fade.currentTime = progress * SCRUB_MS;
                else
                    dialog.style.setProperty("--_drawer-backdrop", String(1 - progress));
                link(progress, true);
            },
            onEnd: ({ offset, velocity }) => {
                const target = pickSnap({
                    stops,
                    position: base + offset,
                    velocity,
                    active,
                    size: height,
                    closeRatio: CLOSE_RATIO,
                    flick: FLICK_VELOCITY,
                    fling: FLING_VELOCITY,
                    sequential: dialog.hasAttribute("data-drawer-snap-sequential"),
                });
                // transitions back on: the inline translate now eases to wherever it is set
                setDragging(dialog, false);
                if (target < 0)
                    slideOutAndClose(maxTransitionMs(dialog));
                else
                    snapTo(target);
            },
            onCancel: rest,
        });
    }
    /** Unbinds a drawer that closed. */
    function unbindDrawer(dialog) {
        bound.get(dialog)?.controller.abort();
        bound.delete(dialog);
        dialog.removeAttribute("data-drawer-state");
        dialog.style.removeProperty("--_drawer-depth");
        const index = stack.indexOf(dialog);
        if (index < 0)
            return;
        stack.splice(index, 1);
        restack();
    }
    /**
     * @description Moves an open drawer to one of its snap points.
     *
     * @param dialog - The drawer.
     * @param index - The snap point, counted from the smallest; clamped to the ones it has.
     */
    function snapDrawer(dialog, index) {
        bound.get(dialog)?.snapTo(index);
    }
    /**
     * @description Starts drawer binding for the page: every drawer is bound when
     * the dialog lifecycle reports it open and unbound when it closes. Idempotent.
     */
    const initDrawers = function () {
        if (initDrawers._bound)
            return;
        initDrawers._bound = true;
        document.addEventListener("zazz:dialog-open", (event) => {
            if (event.target instanceof HTMLDialogElement && event.target.matches(DRAWER)) {
                bindDrawer(event.target);
            }
        });
        document.addEventListener("zazz:dialog-close", (event) => {
            if (event.target instanceof HTMLDialogElement)
                unbindDrawer(event.target);
        });
        window.addEventListener("resize", () => {
            if (indented)
                measureIndent(indented);
        });
        // drawers that were already open when the script loaded
        for (const dialog of document.querySelectorAll(`${DRAWER}[open]`)) {
            bindDrawer(dialog);
        }
    };
    // Auto-initialize when DOM is ready (only in browser environment)
    if (typeof window !== "undefined" && typeof document !== "undefined") {
        if (document.readyState === "loading") {
            document.addEventListener("DOMContentLoaded", initDrawers);
        }
        else {
            initDrawers();
        }
    }
    export { bindDrawer, initDrawers, snapDrawer };

    Snap

    Nearby places

    Drag up for more, or press the handle to step through the sizes.

    The drawer rests at three heights. Its content scrolls once it is fully open.

    Flick down from the smallest height to close it.

    <button data-ui="button" type="button" command="show-modal" commandfor="drawer-snap-1">
      Open drawer
    </button>
    <dialog id="drawer-snap-1" data-ui="drawer" data-drawer-snap="12rem 0.5 1" closedby="any">
      <button type="button" data-drawer-slot="handle" aria-label="Resize drawer"></button>
      <div data-drawer-slot="content">
        <header data-drawer-slot="header">
          <h2
            style="
              --font-size: var(--font-size-lg);
              --font-weight: strong;
              --font-family: var(--font-family-heading);
            "
          >
            Nearby places
          </h2>
          <p style="--text: var(--color-muted-foreground)">
            Drag up for more, or press the handle to step through the sizes.
          </p>
        </header>
        <div data-drawer-slot="body">
          <p>The drawer rests at three heights. Its content scrolls once it is fully open.</p>
          <p>Flick down from the smallest height to close it.</p>
        </div>
      </div>
    </dialog>
    /**
     * drawer.css: Drawer ([data-ui~="drawer"] on native <dialog>; slots
     *             data-drawer-slot="handle | content | header | body | footer | close";
     *             <ui-drawer-indent> / [data-ui~="drawer-indent"], the page wrapper that
     *             scales back behind an open drawer)
     *
     * A bottom sheet: a modal dialog that rises from the bottom edge and is dragged
     * back down to dismiss. Alone (`data-ui="drawer"`) it is a drawer everywhere;
     * on a dialog (`data-ui="dialog drawer"`) it is a drawer below the sm band on a
     * touch screen and the plain dialog otherwise. `data-drawer-snap` gives it
     * resting heights; a drawer opened over another pushes that one back.
     *
     * @layer      variables, components
     * @requires   _layers.css, _variables.css, dialog.css (the native <dialog> motion, backdrop, and
     *             scroll lock in its reset layer; the surface and slots in the combined form)
     * @uses       Overrides --ui-dialog-* motion tokens: the dialog's open/close transition becomes a
     *             rise from the bottom edge, with the backdrop on the same duration and curve
     * @uses       translate — drawer.js writes the inline translate while a pointer drags the drawer
     *             (state `dragging`, transitions off); the dialog's transitions finish the release
     * @uses       Web Animations on ::backdrop — drawer.js scrubs a paused opacity animation so the
     *             backdrop fades with the drag without restyling the drawer's content on every move
     * @uses       @property (inherits: false) + `inherit` on ::backdrop — the same link in CSS, for
     *             an engine that cannot animate ::backdrop from script; where neither works the
     *             backdrop stays opaque until release
     * @uses       @media (width < 40rem) and (not (hover: hover)) — the combined form's drawer mode,
     *             the same phone test as dialog.css
     * @uses       scale, translate — the only properties the stack and the indent animate; the
     *             indent's corner radius is two corner pieces that scale up, so no border-radius or
     *             clip is animated and the page is never repainted for it
     * @uses       clip-path: inset() — a fixed rectangle while the page is indented, so the part of
     *             the page above and below the viewport stays out of the gaps the scale opens
     * @uses       :has() — the body takes the backing color while its page wrapper is indented
     * @uses       @starting-style — the corner pieces grow from nothing when they are generated
     * @uses       corner-shape — the corner pieces follow --radius-corner-shape where it is
     *             supported and are round elsewhere
     * @uses       env(safe-area-inset-top) — the indented page clears the status bar
     * @uses       env(safe-area-inset-bottom) — content clears the home indicator
     * @uses       visualViewport — drawer.js writes --_drawer-keyboard (the software
     *             keyboard's height) on the front drawer, and the sheet's bottom padding takes it,
     *             so content ends at the keyboard's top edge while the surface runs on under it
     * @uses       --_touch-min — the handle's hit area on touch screens
     * @tokens     --ui-drawer-* (@layer variables)
     */
    
    @layer variables {
      :root {
        /* surface */
        --ui-drawer-bg: var(--ui-dialog-bg);
        --ui-drawer-text: var(--ui-dialog-text);
        --ui-drawer-radius: var(--radius-xl);
        --ui-drawer-corner-shape: var(--ui-dialog-corner-shape);
        --ui-drawer-shadow: var(--shadow-lg);
    
        /* metrics: edge to edge, the layout-bleed band; cap it with a band to float a
           narrower sheet, e.g. min(var(--layout-sm), 100%) */
        --ui-drawer-w: 100%;
        --ui-drawer-max-h: calc(100dvb - var(--space-lg));
    
        /* stack: how much each drawer in front shrinks and lifts the one behind */
        --ui-drawer-stack-scale: 0.05;
        --ui-drawer-stack-lift: var(--space-sm);
        /* the page is already dimmed by the first drawer's backdrop */
        --ui-drawer-nested-backdrop-color: transparent;
    
        /* indent: how far each side of the page pulls in, how far it drops, the radius of
           its top corners, and the color behind it. Set these on :root: the body reads the
           backing color too. */
        --ui-drawer-indent-inset: calc(var(--spacing) * 3);
        --ui-drawer-indent-offset: calc(env(safe-area-inset-top, 0px) + var(--space-sm));
        --ui-drawer-indent-radius: var(--ui-drawer-radius);
        --ui-drawer-indent-bg: var(--color-background);
        --ui-drawer-indent-backing: var(--color-black);
    
        /* handle */
        --ui-drawer-handle-w: calc(var(--spacing) * 12);
        --ui-drawer-handle-h: calc(var(--spacing) * 1.25);
        --ui-drawer-handle-bg: var(--color-muted);
        --ui-drawer-handle-bg--hover: var(--color-muted-foreground);
        --ui-drawer-handle-bg--active: var(--color-muted-foreground);
        --ui-drawer-handle-bg--dragging: var(--color-foreground);
    
        /* motion: the iOS sheet curve, steep at the start so twice the default
           duration still reads as quick; 0s under reduced motion like the default */
        --ui-drawer-transition-duration: calc(var(--default-transition-duration) * 2);
        --ui-drawer-transition-timing-function: cubic-bezier(0.32, 0.72, 0, 1);
      }
    }
    
    /* Drawer mode flag, read by drawer.js; and the backdrop's drag opacity, written by it.
       Non-inheriting, so neither restyles the drawer's content. */
    @property --_drawer-mode {
      syntax: "*";
      inherits: false;
    }
    
    @property --_drawer-backdrop {
      syntax: "*";
      inherits: false;
    }
    
    /* Where a drawer with snap points rests, and how many drawers sit in front of it:
       both written by drawer.js when they change (the depth also while the front drawer
       is dragged), and non-inheriting, so neither restyles the drawer's content. */
    @property --_drawer-snap {
      syntax: "*";
      inherits: false;
    }
    
    @property --_drawer-depth {
      syntax: "*";
      inherits: false;
    }
    
    /* The software keyboard's height while the drawer is the front one, written by
       drawer.js from the visual viewport; the sheet's bottom padding takes it. */
    @property --_drawer-keyboard {
      syntax: "*";
      inherits: false;
    }
    
    /* The indent's measurements, written by drawer.js when a drawer opens, and how
       indented the page is (0 to 1): 1 from the `active` state, or the drag's own
       value while the last drawer is dragged. The corner pieces take them by explicit
       inheritance. The inset is typed so the script reads the hook in px. */
    @property --_drawer-indent-amount {
      syntax: "*";
      inherits: false;
    }
    
    @property --_drawer-indent-scale {
      syntax: "*";
      inherits: false;
    }
    
    @property --_drawer-indent-top {
      syntax: "*";
      inherits: false;
    }
    
    @property --_drawer-indent-bottom {
      syntax: "*";
      inherits: false;
    }
    
    @property --_drawer-indent-inset {
      syntax: "<length>";
      inherits: false;
      initial-value: 0px;
    }
    
    @layer ui.components {
      /* ===========================================================================
      DRAWER MODE: the declarations that make a dialog a bottom sheet. Written
      twice, because the two forms enter it under different conditions: the
      standalone form always, the combined form on a phone. Keep the two blocks
      identical apart from the --_dialog-* lines, which feed the dialog's own
      read chain in the combined form.
    
      The sheet extends --_bleed past the bottom edge (padding inside,
      an equal negative margin outside), so pulling it up against its resistance
      never opens a gap under it.
      =========================================================================== */
    
      :where([data-ui~="drawer"]:not([data-ui~="dialog"])) {
        --_drawer-mode: 1;
        --_bleed: calc(var(--spacing) * 12);
        --_handle-display: block;
        --_content-row: 2;
        --_header-select: none;
    
        --ui-dialog-transition-duration: var(--ui-drawer-transition-duration);
        --ui-dialog-transition-timing-function: var(--ui-drawer-transition-timing-function);
        --ui-dialog-backdrop-transition-duration: var(--ui-dialog-transition-duration);
        --ui-dialog-backdrop-transition-timing-function: var(--ui-drawer-transition-timing-function);
        --ui-dialog-transition-delay--end: 0ms;
        --ui-dialog-opacity--start: 1;
        --ui-dialog-scale--start: 1;
        --ui-dialog-translate--start: 0, 100%, 0;
    
        margin-block: auto calc(var(--_bleed) * -1);
        margin-inline: auto;
        /* the keyboard covers the home indicator: the larger of the two, not both */
        padding-block-end: calc(
          var(--_bleed) + max(env(safe-area-inset-bottom, 0px), var(--_drawer-keyboard, 0px))
        );
        max-inline-size: 100%;
        max-block-size: calc(var(--ui-drawer-max-h) + var(--_bleed));
        grid-template-rows: auto minmax(0, 1fr);
        border-block-end-width: 0;
        border-end-start-radius: 0;
        border-end-end-radius: 0;
        /* a stacked drawer shrinks toward its top edge, the part that stays in view */
        transform-origin: 50% 0;
      }
    
      @media (width < 40rem) and (not (hover: hover)) {
        :where([data-ui~="dialog"][data-ui~="drawer"]) {
          --_drawer-mode: 1;
          --_bleed: calc(var(--spacing) * 12);
          --_handle-display: block;
          --_content-row: 2;
          --_header-select: none;
    
          --_dialog-w: var(--ui-drawer-w);
          --_dialog-radius: var(--ui-drawer-radius);
          --_dialog-shadow: var(--ui-drawer-shadow);
    
          --ui-dialog-transition-duration: var(--ui-drawer-transition-duration);
          --ui-dialog-transition-timing-function: var(--ui-drawer-transition-timing-function);
          --ui-dialog-backdrop-transition-duration: var(--ui-dialog-transition-duration);
          --ui-dialog-backdrop-transition-timing-function: var(--ui-drawer-transition-timing-function);
          --ui-dialog-transition-delay--end: 0ms;
          --ui-dialog-opacity--start: 1;
          --ui-dialog-scale--start: 1;
          --ui-dialog-translate--start: 0, 100%, 0;
    
          margin-block: auto calc(var(--_bleed) * -1);
          margin-inline: auto;
          /* the keyboard covers the home indicator: the larger of the two, not both */
          padding-block-end: calc(
            var(--_bleed) + max(env(safe-area-inset-bottom, 0px), var(--_drawer-keyboard, 0px))
          );
          max-inline-size: 100%;
          max-block-size: calc(var(--ui-drawer-max-h) + var(--_bleed));
          grid-template-rows: auto minmax(0, 1fr);
          border-block-end-width: 0;
          border-end-start-radius: 0;
          border-end-end-radius: 0;
          transform-origin: 50% 0;
        }
      }
    
      /* ===========================================================================
      STANDALONE SURFACE: without the dialog identity the drawer paints itself.
      The combined form takes all of this from dialog.css.
      =========================================================================== */
    
      :where([data-ui~="drawer"]:not([data-ui~="dialog"])) {
        inline-size: var(--ui-drawer-w);
        block-size: fit-content;
        background-color: var(--_bg-resolved, var(--ui-drawer-bg));
        color: var(--_text-resolved, var(--ui-drawer-text));
        box-shadow: var(--_shadow-resolved, var(--ui-drawer-shadow));
        /* the top corners only: the bottom edge sits past the viewport */
        border-start-start-radius: var(--ui-drawer-radius);
        border-start-end-radius: var(--ui-drawer-radius);
        corner-shape: var(--_corner-shape-resolved, var(--ui-drawer-corner-shape));
        font-size: var(--font-size-md);
        overflow: hidden;
        overscroll-behavior: contain;
      }
    
      :where([data-ui~="drawer"]:not([data-ui~="dialog"])[open]) {
        display: grid;
        min-block-size: 0;
      }
    
      /* ===========================================================================
      SNAP POINTS: a drawer with data-drawer-snap is as tall as a drawer may be and
      rests pushed down by --_drawer-snap, which drawer.js writes when the stop
      changes. The height is set per form, like drawer mode itself.
      =========================================================================== */
    
      :where([data-ui~="drawer"]:not([data-ui~="dialog"])[data-drawer-snap]) {
        block-size: calc(var(--ui-drawer-max-h) + var(--_bleed));
      }
    
      @media (width < 40rem) and (not (hover: hover)) {
        :where([data-ui~="dialog"][data-ui~="drawer"][data-drawer-snap]) {
          --_dialog-h: calc(var(--ui-drawer-max-h) + var(--_bleed));
        }
      }
    
      :where([data-ui~="drawer"][data-drawer-snap]) {
        translate: 0 var(--_drawer-snap, 0px);
      }
    
      /* ===========================================================================
      STACK: a drawer with others open in front of it shrinks toward its top edge
      and lifts, once per drawer in front. drawer.js writes the count, and while
      the front drawer is dragged a fraction of it (state `following`, transitions
      off). A drawer opened over another dims nothing more.
      =========================================================================== */
    
      :where([data-ui~="drawer"][data-drawer-state~="stacked"]) {
        scale: calc(1 - var(--_drawer-depth, 0) * var(--ui-drawer-stack-scale));
        translate: 0
          calc(var(--_drawer-snap, 0px) - var(--_drawer-depth, 0) * var(--ui-drawer-stack-lift));
      }
    
      :where([data-ui~="drawer"][data-drawer-state~="following"]) {
        transition: none;
      }
    
      :where([data-ui~="drawer"][data-drawer-state~="nested"])::backdrop {
        background-color: var(--ui-drawer-nested-backdrop-color);
        backdrop-filter: none;
      }
    
      /* Each slot owns a row, as in the dialog: the body is the part that scrolls */
      :where([data-ui~="drawer"]) [data-drawer-slot~="content"] {
        display: grid;
        grid-template-rows: auto minmax(0, 1fr) auto;
        position: relative;
        min-block-size: 0;
        max-block-size: 100%;
      }
    
      :where([data-ui~="drawer"]) [data-drawer-slot~="header"] {
        grid-row: 1;
        display: flex;
        flex-direction: column;
        padding-inline: var(--space-sm);
        padding-block-start: var(--space-sm);
      }
    
      :where([data-ui~="drawer"]) [data-drawer-slot~="body"] {
        grid-row: 2;
        display: grid;
        align-content: start;
        padding-inline: var(--space-sm);
        padding-block: var(--space-md);
        min-block-size: 0;
        overflow-y: auto;
        overscroll-behavior: contain;
      }
    
      :where([data-ui~="drawer"]) [data-drawer-slot~="footer"] {
        grid-row: 3;
        display: flex;
        justify-content: flex-end;
        gap: var(--space-xs);
        padding: var(--space-sm);
        border-block-start: 1px solid var(--color-border);
      }
    
      :where([data-ui~="drawer"]) [data-drawer-slot~="close"] {
        position: absolute;
        inset-block-start: var(--space-xs);
        inset-inline-end: var(--space-xs);
        z-index: 50;
      }
    
      /* ===========================================================================
      PARTS IN DRAWER MODE: the handle shows and takes the first row; the content
      slot (the drawer's own or the dialog's) takes the flexible second row, with
      or without a handle before it. Both read the mode privates set above, so
      neither rule is repeated per form.
      =========================================================================== */
    
      :where([data-ui~="drawer"]) :where([data-drawer-slot~="content"], [data-dialog-slot~="content"]) {
        grid-row: var(--_content-row, auto);
      }
    
      /* The header is where a mouse grabs the drawer: a press on its text drags
         instead of selecting. Body text stays selectable. */
      :where([data-ui~="drawer"]) :where([data-drawer-slot~="header"], [data-dialog-slot~="header"]) {
        -webkit-user-select: var(--_header-select, auto);
        user-select: var(--_header-select, auto);
      }
    
      /* A pill, with a hit area that reaches the touch-target height. It always
         drags, even over a scrolled body, so it opts out of native panning. */
      :where([data-ui~="drawer"]) [data-drawer-slot~="handle"] {
        display: var(--_handle-display, none);
        grid-row: 1;
        justify-self: center;
        position: relative;
        inline-size: var(--ui-drawer-handle-w);
        block-size: var(--ui-drawer-handle-h);
        margin-block: calc(var(--spacing) * 2.5) calc(var(--spacing) * 1);
        border-radius: var(--radius-full);
        background-color: var(--ui-drawer-handle-bg);
        cursor: grab;
        touch-action: none;
        -webkit-user-select: none;
        user-select: none;
        transition: background-color var(--default-transition-duration)
          var(--default-transition-timing-function);
      }
    
      :where([data-ui~="drawer"]) [data-drawer-slot~="handle"]:hover {
        background-color: var(--ui-drawer-handle-bg--hover);
      }
    
      :where([data-ui~="drawer"]) [data-drawer-slot~="handle"]:active {
        background-color: var(--ui-drawer-handle-bg--active);
        cursor: grabbing;
      }
    
      :where([data-ui~="drawer"]) [data-drawer-slot~="handle"]::before {
        content: "";
        position: absolute;
        inset-inline: calc(var(--ui-drawer-handle-w) * -1);
        inset-block: min(calc(var(--spacing) * -2), calc((100% - var(--_touch-min, 0px)) / 2));
      }
    
      /* Below its largest snap point a drawer's content does not scroll: the drawer
         moves first. After the slot rules, which it has to beat. */
      :where([data-ui~="drawer"][data-drawer-state~="partial"])
        :is([data-drawer-slot~="body"], [data-dialog-slot~="body"]) {
        overflow-y: hidden;
      }
    
      /* ===========================================================================
      DRAG: while a pointer drags the drawer, drawer.js writes its inline
      translate and nothing may ease it: the drawer is the pointer. The backdrop
      fades with the drag: drawer.js scrubs an animation on it, or, where
      ::backdrop cannot be animated from script, writes --_drawer-backdrop, which
      the backdrop takes from the dialog by explicit inheritance. On release the state drops and the dialog's
      own transitions finish the motion, to closed or back to rest.
      =========================================================================== */
    
      :where([data-ui~="drawer"][data-drawer-state~="dragging"]) [data-drawer-slot~="handle"] {
        background-color: var(--ui-drawer-handle-bg--dragging);
      }
    
      :where([data-ui~="drawer"][data-drawer-state~="dragging"]) {
        transition: none;
        cursor: grabbing;
        /* a mouse drag that began beside text must not start selecting it */
        -webkit-user-select: none;
        user-select: none;
      }
    
      :where([data-ui~="drawer"][data-drawer-state~="dragging"])::backdrop {
        --_drawer-backdrop: inherit;
        opacity: var(--_drawer-backdrop, 1);
        transition: none;
      }
    
      /* ===========================================================================
      INDENT: the page wrapper scales back behind an open drawer. drawer.js sets the
      state (`on` while the machinery is engaged, `active` while a drawer is open,
      `dragging` while the last drawer is dragged) and measures, once, the scale and
      where the viewport sits inside the wrapper.
    
      Only scale and translate animate. The wrapper is clipped to the viewport's
      rectangle, a fixed clip, so the page above and below it stays out of the gaps;
      the body paints the backing color there. The rounded top corners are two
      corner pieces that grow from the corners, not a border-radius: nothing is
      repainted while the page moves.
    
      While `on` the wrapper is transformed, so it is the containing block of its
      fixed and absolute descendants.
      =========================================================================== */
    
      :where(ui-drawer-indent, [data-ui~="drawer-indent"]) {
        --_drawer-indent-inset: var(--ui-drawer-indent-inset);
        display: block;
        background-color: var(--ui-drawer-indent-bg);
        transition:
          scale var(--ui-drawer-transition-duration) var(--ui-drawer-transition-timing-function),
          translate var(--ui-drawer-transition-duration) var(--ui-drawer-transition-timing-function);
      }
    
      :where(ui-drawer-indent, [data-ui~="drawer-indent"])[data-drawer-indent-state~="on"] {
        position: relative;
        transform-origin: 50% var(--_drawer-indent-top, 0px);
        scale: calc(1 - (1 - var(--_drawer-indent-scale, 1)) * var(--_drawer-indent-amount, 0));
        translate: 0 calc(var(--ui-drawer-indent-offset) * var(--_drawer-indent-amount, 0));
        clip-path: inset(var(--_drawer-indent-top, 0px) 0 var(--_drawer-indent-bottom, 0px) 0);
        will-change: scale, translate;
      }
    
      :where(ui-drawer-indent, [data-ui~="drawer-indent"])[data-drawer-indent-state~="active"] {
        --_drawer-indent-amount: 1;
      }
    
      /* The backing shows in the gaps around the indented page. Important, because a
         page's own <body style="--bg: …"> is a utility and would otherwise win; it holds
         only while the wrapper is `on`. */
      :where(body):has(
        :is(ui-drawer-indent, [data-ui~="drawer-indent"])[data-drawer-indent-state~="on"]
      ) {
        background-color: var(--ui-drawer-indent-backing) !important;
      }
    
      /* A corner piece: a square the size of the radius whose outer corner is rounded
         and whose spread shadow, cut off at the square, paints only the notch outside
         the curve. Scaling it from that corner is the radius growing. */
      :where(ui-drawer-indent, [data-ui~="drawer-indent"])[data-drawer-indent-state~="on"]::before,
      :where(ui-drawer-indent, [data-ui~="drawer-indent"])[data-drawer-indent-state~="on"]::after {
        --_drawer-indent-amount: inherit;
        --_drawer-indent-top: inherit;
        content: "";
        position: absolute;
        z-index: 2147483647;
        inset-block-start: var(--_drawer-indent-top, 0px);
        inline-size: var(--ui-drawer-indent-radius);
        block-size: var(--ui-drawer-indent-radius);
        box-shadow: 0 0 0 var(--ui-drawer-indent-radius) var(--ui-drawer-indent-backing);
        clip-path: inset(0);
        corner-shape: var(--radius-corner-shape);
        scale: var(--_drawer-indent-amount, 0);
        pointer-events: none;
        transition: scale var(--ui-drawer-transition-duration)
          var(--ui-drawer-transition-timing-function);
    
        @starting-style {
          scale: 0;
        }
      }
    
      :where(ui-drawer-indent, [data-ui~="drawer-indent"])[data-drawer-indent-state~="on"]::before {
        left: 0;
        border-top-left-radius: 100%;
        transform-origin: 0 0;
      }
    
      :where(ui-drawer-indent, [data-ui~="drawer-indent"])[data-drawer-indent-state~="on"]::after {
        right: 0;
        border-top-right-radius: 100%;
        transform-origin: 100% 0;
      }
    
      :where(ui-drawer-indent, [data-ui~="drawer-indent"])[data-drawer-indent-state~="dragging"],
      :where(
          ui-drawer-indent,
          [data-ui~="drawer-indent"]
        )[data-drawer-indent-state~="dragging"]::before,
      :where(
          ui-drawer-indent,
          [data-ui~="drawer-indent"]
        )[data-drawer-indent-state~="dragging"]::after {
        transition: none;
      }
    }
    // primitives/drawer/drawer.js
    "use strict";
    /**
     * @fileoverview Drawer: drag-to-dismiss for `<dialog data-ui="drawer">` bottom sheets.
     * @description A drawer is a native modal `<dialog>`, opened and closed like
     * any other (`command="show-modal"`, `command="close"`, Esc, the backdrop with
     * `closedby="any"`). This script adds the gesture: drag the drawer down and
     * let go to dismiss it.
     *
     * - `data-ui="drawer"` is a drawer on every device.
     * - `data-ui="dialog drawer"` is a drawer below the `sm` band on a touch
     *   screen, and a plain dialog (no dragging) everywhere else.
     *
     * While the pointer is down the drawer follows it 1:1 and the backdrop fades
     * with it. Letting go past a quarter of the drawer's height, or with a quick
     * downward flick, slides it off the bottom edge and then closes it through
     * `requestClose()`, so `cancel` and `close` fire as they do for Esc; anything
     * less returns it to rest. Until it has slid out it can be caught again. Pulling it up
     * past its resting place meets resistance.
     *
     * A drag starts anywhere on the drawer except on form fields, selected text,
     * and anything inside `[data-ui-no-drag]`. Inside scrolling content it starts
     * only once that content is scrolled to the top and the pointer moves down,
     * so the body scrolls first and the drawer follows; the handle
     * (`data-drawer-slot="handle"`) always drags. There is no custom element and
     * nothing to initialize: the script binds a drawer when it opens.
     *
     * **Snap points.** `data-drawer-snap="148px 0.5 1"` gives the drawer resting
     * heights, smallest first: a number up to 1 is a share of the drawer's full
     * height, a `px` or `rem` length is a visible height. It opens at the first.
     * Letting go settles on the nearest; a flick moves one stop in its direction,
     * a very fast one goes all the way (or one stop, with
     * `data-drawer-snap-sequential`), and from the lowest stop a flick or enough
     * travel downward closes the drawer. Below the largest stop the drawer takes
     * every vertical drag and its content does not scroll. A click on the handle
     * steps to the next stop; make the handle a `<button>` to give the keyboard
     * the same. Each change fires `zazz:drawer-snap` (`detail.index`,
     * `detail.value` in px), `data-drawer-state` carries `expanded` at the largest
     * stop, and `snapDrawer(dialog, index)` moves it from script.
     *
     * **The software keyboard.** A phone lays a drawer out against the full
     * screen, which the keyboard does not shrink. While a field in the front
     * drawer has the keyboard up, the drawer's content ends at the keyboard's top
     * edge (its surface runs on underneath), the focused field scrolls into what
     * is still visible, and the page behind stays where it was. Nothing to author.
     *
     * **Stacked drawers.** A drawer opened over another scales the one behind back
     * and lifts it, and that one follows as the front drawer is dragged. Nothing
     * to author: the script counts the open drawers.
     *
     * **Indent.** Wrap the page in `<ui-drawer-indent>` (or put
     * `data-ui="drawer-indent"` on its wrapper) and it scales back behind any open
     * drawer, with rounded top corners, and follows the drag of the last one. Only
     * transforms animate. While indented the wrapper is transformed, so a
     * `position: fixed` element inside it moves with the page; `position: sticky`
     * is unaffected.
     *
     * @example
     * <button data-ui="button" command="show-modal" commandfor="filters">Filters</button>
     * <dialog id="filters" data-ui="drawer" closedby="any">
     *   <div data-drawer-slot="handle"></div>
     *   <div data-drawer-slot="content">
     *     <header data-drawer-slot="header">…</header>
     *     <div data-drawer-slot="body">…</div>
     *   </div>
     * </dialog>
     */
    import { currentTranslate, maxTransitionMs, pickSnap, rubberBand, trackDrag, } from "../../base/gesture.js";
    // --- Tuning ---
    /** Share of the drawer's visible height, at its lowest stop, that dismisses on its own. */
    const CLOSE_RATIO = 0.25;
    /** Speed that moves the drawer one stop, or dismisses it from the lowest, in px/ms. */
    const FLICK_VELOCITY = 0.4;
    /** Speed that skips every stop: all the way open, or closed, in px/ms. */
    const FLING_VELOCITY = 2;
    /**
     * After inner content scrolls, how long before the drawer may be dragged, in
     * ms. A fast scroll that reaches the top would otherwise carry straight on
     * into dragging the drawer away.
     */
    const SCROLL_GUARD_MS = 100;
    /** Length of the backdrop's scrub animation: its timeline is drag progress, not time. */
    const SCRUB_MS = 1000;
    const DRAWER = 'dialog[data-ui~="drawer"]';
    const HANDLE = '[data-drawer-slot~="handle"]';
    const INDENT = 'ui-drawer-indent, [data-ui~="drawer-indent"]';
    const INDENT_STATE = "data-drawer-indent-state";
    // --- Helpers ---
    /** Adds or removes one token of a space-separated state attribute; an empty attribute is removed. */
    function setToken(element, attribute, token, on) {
        const tokens = new Set((element.getAttribute(attribute) ?? "").split(/\s+/).filter(Boolean));
        if (tokens.has(token) === on)
            return;
        if (on)
            tokens.add(token);
        else
            tokens.delete(token);
        if (tokens.size)
            element.setAttribute(attribute, [...tokens].join(" "));
        else
            element.removeAttribute(attribute);
    }
    /** Adds or removes a token of a drawer's `data-drawer-state`. */
    function setState(dialog, token, on) {
        setToken(dialog, "data-drawer-state", token, on);
    }
    /** Adds or removes the `dragging` token of a drawer's `data-drawer-state`. */
    function setDragging(dialog, on) {
        setState(dialog, "dragging", on);
    }
    /** Clears everything a drag wrote on the drawer. */
    function reset(dialog) {
        setDragging(dialog, false);
        dialog.style.removeProperty("translate");
        dialog.style.removeProperty("--_drawer-backdrop");
    }
    /**
     * @description Reads a drawer's snap points as resting positions: px the
     * drawer is pushed down at each, the smallest visible height first.
     *
     * @param dialog - The drawer.
     * @param height - The drawer's full visible height in px.
     * @returns The positions, descending; `[0]` without usable snap points.
     * @private
     */
    function readStops(dialog, height) {
        const raw = dialog.getAttribute("data-drawer-snap")?.trim();
        if (!raw)
            return [0];
        const rem = Number.parseFloat(getComputedStyle(document.documentElement).fontSize) || 16;
        const positions = new Set();
        for (const token of raw.split(/\s+/)) {
            const value = Number.parseFloat(token);
            if (!Number.isFinite(value) || value <= 0)
                continue;
            let visible = value * height;
            if (token.endsWith("rem"))
                visible = value * rem;
            else if (token.endsWith("px") || value > 1)
                visible = value;
            positions.add(Math.round(height - Math.min(height, Math.max(1, visible))));
        }
        return positions.size ? [...positions].sort((a, b) => b - a) : [0];
    }
    /**
     * @description Starts a paused opacity animation on the drawer's backdrop, to
     * be scrubbed with the drag. An animation, not a style write: it reaches the
     * pseudo-element without restyling the drawer's content, in engines that do
     * not re-resolve `::backdrop` when a non-inherited property changes on its
     * dialog (WebKit).
     *
     * @param dialog - The drawer.
     * @returns The animation, or null where `::backdrop` cannot be animated; the
     * caller then writes `--_drawer-backdrop`, which drawer.css reads.
     * @private
     */
    function scrubBackdrop(dialog) {
        try {
            const animation = dialog.animate([{ opacity: 1 }, { opacity: 0 }], {
                pseudoElement: "::backdrop",
                duration: SCRUB_MS,
                fill: "both",
            });
            animation.pause();
            return animation;
        }
        catch {
            return null;
        }
    }
    /** Whether drawer.css has the dialog in drawer mode right now. */
    function inDrawerMode(dialog) {
        return getComputedStyle(dialog).getPropertyValue("--_drawer-mode").trim() === "1";
    }
    /** Whether an element scrolls its content on the block axis. */
    function scrolls(element) {
        if (element.scrollHeight <= element.clientHeight)
            return false;
        const overflow = getComputedStyle(element).overflowY;
        return overflow === "auto" || overflow === "scroll";
    }
    /**
     * @description Whether a press may drag the drawer, given what it landed on
     * and which way it is moving.
     *
     * @param dialog - The drawer.
     * @param drag - The drag about to start; `offset` carries its direction.
     * @param lastScroll - When content inside the drawer last scrolled.
     * @param partial - Whether the drawer rests below its largest snap point.
     * @returns Whether the drawer takes the gesture.
     * @private
     */
    function claims(dialog, drag, lastScroll, partial) {
        if (!inDrawerMode(dialog))
            return false;
        // a press on the backdrop targets the dialog, outside its box
        const box = dialog.getBoundingClientRect();
        if (drag.startY < box.top || drag.startX < box.left || drag.startX > box.right)
            return false;
        if (drag.target.closest(HANDLE))
            return true;
        // below its largest stop the drawer moves before anything inside it scrolls
        if (partial)
            return true;
        // scrolling content goes first: it must be at the top, and the pull downward
        const down = drag.offset > 0;
        for (let node = drag.target; node && dialog.contains(node); node = node.parentElement) {
            if (scrolls(node) && (node.scrollTop > 0 || !down))
                return false;
        }
        return performance.now() - lastScroll >= SCROLL_GUARD_MS;
    }
    // --- Stack ---
    /** The open drawers in drawer mode, the front one last. */
    const stack = [];
    /**
     * @description Writes each open drawer's place in the stack: how many drawers
     * sit in front of it (`--_drawer-depth`, `stacked`) and whether it opened over
     * another (`nested`). Runs when a drawer opens or closes, never per frame.
     * @private
     */
    function restack() {
        // a drawer removed from the page while open never reports its close
        for (let index = stack.length - 1; index >= 0; index--) {
            const dialog = stack[index];
            if (!dialog.isConnected || !dialog.open)
                stack.splice(index, 1);
        }
        stack.forEach((dialog, index) => {
            const depth = stack.length - 1 - index;
            setState(dialog, "following", false);
            setState(dialog, "stacked", depth > 0);
            setState(dialog, "nested", index > 0);
            if (depth > 0)
                dialog.style.setProperty("--_drawer-depth", String(depth));
            else
                dialog.style.removeProperty("--_drawer-depth");
        });
        indentPose(stack.length > 0);
    }
    /**
     * @description Moves the drawers behind `front` with its drag: at progress 1
     * each sits where it will once `front` is gone. The depth is a non-inheriting
     * property, so the write restyles those drawers and not their content.
     *
     * @param front - The drawer being dragged or released.
     * @param progress - How far `front` is toward closed, 0 to 1.
     * @param live - Whether a pointer is driving it (transitions off).
     * @private
     */
    function follow(front, progress, live) {
        const index = stack.indexOf(front);
        for (let behind = 0; behind < index; behind++) {
            const dialog = stack[behind];
            dialog.style.setProperty("--_drawer-depth", String(index - behind - progress));
            setState(dialog, "following", live);
        }
    }
    // --- Indent ---
    /** The page wrapper that is indented right now, and what ends its return to rest. */
    let indented = null;
    let cancelOutdent = null;
    /**
     * @description Measures what the indent needs, once per activation and on
     * resize: the scale that pulls each side in by the inset hook, and where the
     * viewport sits inside the wrapper (the transform's origin, the clip, and the
     * corner pieces all hang off its top edge).
     * @private
     */
    function measureIndent(wrapper) {
        const box = wrapper.getBoundingClientRect();
        const width = wrapper.offsetWidth || 1;
        const inset = Number.parseFloat(getComputedStyle(wrapper).getPropertyValue("--_drawer-indent-inset")) || 0;
        const top = Math.max(0, -box.top);
        const bottom = Math.max(0, wrapper.offsetHeight - top - window.innerHeight);
        wrapper.style.setProperty("--_drawer-indent-scale", String(Math.max(0, 1 - (inset * 2) / width)));
        wrapper.style.setProperty("--_drawer-indent-top", `${top}px`);
        wrapper.style.setProperty("--_drawer-indent-bottom", `${bottom}px`);
    }
    /**
     * @description Indents the page wrapper or sends it back to rest. The pose is
     * a state token and the motion a CSS transition; the `on` token (clip,
     * corners, backing) outlasts the pose until the return has finished.
     *
     * @param active - Whether a drawer is open.
     * @private
     */
    function indentPose(active) {
        // a wrapper that left the page takes its state with it
        if (indented && !indented.isConnected) {
            cancelOutdent?.();
            indented = null;
        }
        const wrapper = indented ?? document.querySelector(INDENT);
        if (!wrapper)
            return;
        if (active) {
            cancelOutdent?.();
            if (indented !== wrapper) {
                measureIndent(wrapper);
                indented = wrapper;
            }
            setToken(wrapper, INDENT_STATE, "on", true);
            setToken(wrapper, INDENT_STATE, "active", true);
            return;
        }
        if (!indented || cancelOutdent)
            return;
        setToken(wrapper, INDENT_STATE, "dragging", false);
        wrapper.style.removeProperty("--_drawer-indent-amount");
        setToken(wrapper, INDENT_STATE, "active", false);
        const off = () => {
            cancelOutdent?.();
            wrapper.removeAttribute(INDENT_STATE);
            for (const name of ["scale", "top", "bottom"]) {
                wrapper.style.removeProperty(`--_drawer-indent-${name}`);
            }
            indented = null;
        };
        const ms = maxTransitionMs(wrapper);
        if (ms <= 0) {
            off();
            return;
        }
        const onReturned = (event) => {
            if (event.target === wrapper && event.propertyName === "scale")
                off();
        };
        const timer = window.setTimeout(off, ms + 100);
        wrapper.addEventListener("transitionend", onReturned);
        cancelOutdent = () => {
            window.clearTimeout(timer);
            wrapper.removeEventListener("transitionend", onReturned);
            cancelOutdent = null;
        };
    }
    /**
     * @description Links the indent to the last open drawer's drag.
     *
     * @param progress - How far the drawer is toward closed, 0 to 1.
     * @param live - Whether a pointer is driving it (transitions off).
     * @private
     */
    function indentProgress(progress, live) {
        if (!indented)
            return;
        setToken(indented, INDENT_STATE, "dragging", live);
        if (live)
            indented.style.setProperty("--_drawer-indent-amount", String(1 - progress));
        else
            indented.style.removeProperty("--_drawer-indent-amount");
    }
    // --- Keyboard ---
    /** The keyboard's height on the front drawer, which drawer.css adds to its bottom padding. */
    const KEYBOARD_INSET = "--_drawer-keyboard";
    /** Space kept between a revealed field and the keyboard's top edge, in px. */
    const REVEAL_GAP = 16;
    /** Inputs that open a picker or nothing rather than the software keyboard. */
    const NO_KEYBOARD = /^(?:button|checkbox|color|file|hidden|image|radio|range|reset|submit|date|datetime-local|month|time|week)$/;
    /** Whether focus on this element opens the software keyboard. */
    function typesText(element) {
        if (element instanceof HTMLTextAreaElement)
            return !element.readOnly;
        if (element instanceof HTMLInputElement)
            return !element.readOnly && !NO_KEYBOARD.test(element.type);
        return element instanceof HTMLElement && element.isContentEditable;
    }
    /**
     * @description How much of the layout viewport the software keyboard covers,
     * from the bottom: the part below the visual viewport. 0 while the page is
     * pinch-zoomed, when the visual viewport is smaller for another reason.
     * @private
     */
    function keyboardInset() {
        const viewport = window.visualViewport;
        if (!viewport || Math.abs(viewport.scale - 1) > 0.01)
            return 0;
        const bottom = Math.max(0, viewport.offsetTop) + viewport.height;
        return Math.max(0, Math.round(window.innerHeight - Math.min(window.innerHeight, bottom)));
    }
    /**
     * @description Keeps an open drawer usable with the software keyboard up.
     * iOS lays out the top layer against the layout viewport, which the keyboard
     * does not shrink, and scrolls the page behind a modal to reveal a focused
     * field. While the drawer is the front one this writes the keyboard's height
     * to `--_drawer-keyboard` (drawer.css pads the sheet by it, so its
     * content ends at the keyboard's top edge), holds the page at its scroll
     * position, and scrolls a focused field into the part of its scrolling slot
     * that is still visible.
     *
     * @param dialog - The drawer.
     * @param signal - Aborts when the drawer closes.
     * @param onChange - Runs after the inset changes, once the new padding is in place.
     * @private
     */
    function trackKeyboard(dialog, signal, onChange) {
        const viewport = window.visualViewport;
        if (!viewport)
            return;
        const front = () => stack[stack.length - 1] === dialog;
        const pageX = window.scrollX;
        const pageY = window.scrollY;
        let frame = 0;
        let current = 0;
        const update = () => {
            frame = 0;
            const inset = front() ? keyboardInset() : 0;
            if (inset === current)
                return;
            current = inset;
            if (inset > 0)
                dialog.style.setProperty(KEYBOARD_INSET, `${inset}px`);
            else
                dialog.style.removeProperty(KEYBOARD_INSET);
            onChange();
        };
        const schedule = () => {
            if (!frame)
                frame = requestAnimationFrame(update);
        };
        /** Scrolls the field's scrolling slot so the field sits above the keyboard and below the slot's top. */
        const reveal = (field) => {
            if (!dialog.contains(field) || document.activeElement !== field)
                return;
            let container = field.parentElement;
            while (container && dialog.contains(container) && !scrolls(container)) {
                container = container.parentElement;
            }
            if (!container || !dialog.contains(container))
                return;
            const box = container.getBoundingClientRect();
            const target = field.getBoundingClientRect();
            const visibleBottom = Math.min(box.bottom, viewport.offsetTop + viewport.height) - REVEAL_GAP;
            const visibleTop = Math.max(box.top, viewport.offsetTop) + REVEAL_GAP;
            let by = 0;
            if (target.bottom > visibleBottom)
                by = target.bottom - visibleBottom;
            if (target.top - by < visibleTop)
                by = target.top - visibleTop;
            if (Math.abs(by) < 1)
                return;
            const still = matchMedia("(prefers-reduced-motion: reduce)").matches;
            container.scrollBy({ top: by, behavior: still ? "instant" : "smooth" });
        };
        viewport.addEventListener("resize", schedule, { signal });
        viewport.addEventListener("scroll", schedule, { signal });
        // the page behind a modal stays where it was, whatever iOS scrolls to show the field
        window.addEventListener("scroll", () => {
            if (!front() || (window.scrollX === pageX && window.scrollY === pageY))
                return;
            window.scrollTo({ left: pageX, top: pageY, behavior: "instant" });
        }, { passive: true, signal });
        // the keyboard settles over a few frames: reveal after it has, and again once it is up
        dialog.addEventListener("focusin", (event) => {
            const field = event.target;
            if (!(field instanceof Element) || !typesText(field) || !front())
                return;
            for (const ms of [100, 350]) {
                const timer = window.setTimeout(() => {
                    update();
                    reveal(field);
                }, ms);
                signal.addEventListener("abort", () => window.clearTimeout(timer), { once: true });
            }
        }, { signal });
        signal.addEventListener("abort", () => {
            cancelAnimationFrame(frame);
            dialog.style.removeProperty(KEYBOARD_INSET);
        });
        update();
    }
    /** Open drawers and what unbinds or moves each. */
    const bound = new WeakMap();
    /** Each drawer's backdrop animation, kept past its close so the next open can drop it. */
    const fades = new WeakMap();
    /**
     * @description Binds drag-to-dismiss to an open drawer until it closes.
     *
     * @param dialog - The drawer.
     */
    function bindDrawer(dialog) {
        if (bound.has(dialog))
            return;
        const controller = new AbortController();
        const { signal } = controller;
        // what the last dismissal left in place: the slid-out translate, the cleared backdrop
        fades.get(dialog)?.cancel();
        fades.delete(dialog);
        reset(dialog);
        const snaps = dialog.hasAttribute("data-drawer-snap");
        let lastScroll = 0;
        // where the drawer was when the drag caught it (mid snap-back, usually its stop)
        let base = 0;
        let height = 1;
        // the sheet's bleed past the bottom edge: the most it may be pulled up
        let lift = 0;
        // resting positions, px pushed down, the lowest snap point first; and the one it rests at
        let stops = [0];
        let active = 0;
        let fade = null;
        // undoes a dismissal still sliding out, so a new drag can catch the drawer
        let cancelClose = null;
        const measure = () => {
            lift = Math.max(0, -Number.parseFloat(getComputedStyle(dialog).marginBlockEnd) || 0);
            // the layout height: a stacked drawer's scale must not shrink it
            height = Math.max(1, dialog.offsetHeight - lift);
            stops = snaps ? readStops(dialog, height) : [0];
            active = Math.min(active, stops.length - 1);
        };
        /** Writes where the drawer rests: drawer.css turns `--_drawer-snap` into its `translate`. */
        const place = () => {
            if (!snaps)
                return;
            const largest = active === stops.length - 1;
            dialog.style.setProperty("--_drawer-snap", `${stops[active] ?? 0}px`);
            setState(dialog, "expanded", largest);
            setState(dialog, "partial", !largest);
        };
        /** Everything that moves with the drawer's progress toward closed, besides its backdrop. */
        const link = (progress, live) => {
            follow(dialog, progress, live);
            if (stack.length === 1 && stack[0] === dialog)
                indentProgress(progress, live);
        };
        /**
         * Runs the backdrop from where the drag left it to clear or back to full,
         * in `ms`. Back at full the animation is dropped; clear, it holds until the
         * drawer next opens, over whatever the closed dialog's own backdrop does.
         */
        const settle = (closing, ms) => {
            dialog.style.removeProperty("--_drawer-backdrop");
            const animation = fade;
            if (!animation)
                return;
            const done = () => {
                if (closing || fade !== animation || animation.playState !== "finished")
                    return;
                animation.cancel();
                fades.delete(dialog);
                fade = null;
            };
            const at = Number(animation.currentTime) || 0;
            const left = closing ? SCRUB_MS - at : at;
            if (ms <= 0 || left <= 0) {
                animation.playbackRate = closing ? 1 : -1;
                animation.finish();
                done();
                return;
            }
            animation.playbackRate = ((closing ? 1 : -1) * left) / ms;
            animation.play();
            animation.finished.then(done, () => { });
        };
        /** Settles the drawer on a stop; the dialog's `translate` transition carries it there. */
        const snapTo = (index) => {
            const next = Math.min(Math.max(index, 0), stops.length - 1);
            const changed = next !== active;
            active = next;
            place();
            setDragging(dialog, false);
            settle(false, maxTransitionMs(dialog));
            dialog.style.removeProperty("translate");
            link(0, false);
            if (!changed)
                return;
            dialog.dispatchEvent(new CustomEvent("zazz:drawer-snap", {
                bubbles: true,
                detail: { index: active, value: height - (stops[active] ?? 0) },
            }));
        };
        const rest = () => snapTo(active);
        /** Closes the dialog; a `cancel` listener that keeps it open sends it back to rest. */
        const close = () => {
            if (!dialog.open)
                return;
            if (typeof dialog.requestClose === "function")
                dialog.requestClose();
            else
                dialog.close();
            if (!dialog.open)
                return;
            if (stack.length === 1)
                indentPose(true);
            rest();
        };
        /**
         * Slides the drawer off the bottom edge while it is still open, then closes
         * it. The slide is the drawer's own `translate` transition, so it does not
         * depend on the engine animating a dialog's exit (WebKit removes a closed
         * dialog at once), and until it ends the drawer can be caught again.
         * Whatever is linked to the drawer leaves with it.
         */
        const slideOutAndClose = (ms) => {
            dialog.style.translate = `0 ${height + lift}px`;
            settle(true, ms);
            follow(dialog, 1, false);
            if (stack.length === 1 && stack[0] === dialog)
                indentPose(false);
            if (ms <= 0) {
                close();
                return;
            }
            const onSlid = (event) => {
                if (event.target === dialog && event.propertyName === "translate")
                    finish();
            };
            const finish = () => {
                cancelClose?.();
                close();
            };
            // the timer covers a transition that never reports its end
            const timer = window.setTimeout(finish, ms + 100);
            dialog.addEventListener("transitionend", onSlid);
            cancelClose = () => {
                window.clearTimeout(timer);
                dialog.removeEventListener("transitionend", onSlid);
                cancelClose = null;
            };
        };
        bound.set(dialog, { controller, snapTo });
        if (inDrawerMode(dialog)) {
            measure();
            place();
            stack.push(dialog);
            restack();
            trackKeyboard(dialog, signal, () => {
                measure();
                place();
            });
        }
        signal.addEventListener("abort", () => {
            cancelClose?.();
            // a drawer closed some other way mid-drag: nothing may hold the backdrop
            if (fade?.playState === "paused") {
                fade.cancel();
                fades.delete(dialog);
            }
        });
        dialog.addEventListener("scroll", () => {
            lastScroll = performance.now();
        }, { capture: true, passive: true, signal });
        // the handle steps through the snap points: a click, so a button handle works from the keyboard
        dialog.addEventListener("click", (event) => {
            if (stops.length < 2 || !(event.target instanceof Element))
                return;
            if (event.target.closest(HANDLE))
                snapTo((active + 1) % stops.length);
        }, { signal });
        window.addEventListener("resize", () => {
            if (!stack.includes(dialog))
                return;
            measure();
            place();
        }, { signal });
        trackDrag(dialog, {
            axis: "y",
            signal,
            canStart: (drag) => claims(dialog, drag, lastScroll, active < stops.length - 1),
            onStart: () => {
                // a drawer caught on its way out: what left with it comes back
                if (cancelClose && stack.length === 1)
                    indentPose(true);
                cancelClose?.();
                base = currentTranslate(dialog).y;
                measure();
                if (!fade) {
                    fade = scrubBackdrop(dialog);
                    if (fade)
                        fades.set(dialog, fade);
                }
                fade?.pause();
                setDragging(dialog, true);
            },
            onMove: ({ offset }) => {
                const travel = base + offset;
                const top = stops[stops.length - 1] ?? 0;
                const y = travel >= top ? travel : top + rubberBand(travel - top, lift + top);
                dialog.style.translate = `0 ${y}px`;
                // progress runs from the lowest stop to gone: above it nothing fades
                const lowest = stops[0] ?? 0;
                const progress = Math.min(1, Math.max(0, (y - lowest) / Math.max(1, height - lowest)));
                if (fade)
                    fade.currentTime = progress * SCRUB_MS;
                else
                    dialog.style.setProperty("--_drawer-backdrop", String(1 - progress));
                link(progress, true);
            },
            onEnd: ({ offset, velocity }) => {
                const target = pickSnap({
                    stops,
                    position: base + offset,
                    velocity,
                    active,
                    size: height,
                    closeRatio: CLOSE_RATIO,
                    flick: FLICK_VELOCITY,
                    fling: FLING_VELOCITY,
                    sequential: dialog.hasAttribute("data-drawer-snap-sequential"),
                });
                // transitions back on: the inline translate now eases to wherever it is set
                setDragging(dialog, false);
                if (target < 0)
                    slideOutAndClose(maxTransitionMs(dialog));
                else
                    snapTo(target);
            },
            onCancel: rest,
        });
    }
    /** Unbinds a drawer that closed. */
    function unbindDrawer(dialog) {
        bound.get(dialog)?.controller.abort();
        bound.delete(dialog);
        dialog.removeAttribute("data-drawer-state");
        dialog.style.removeProperty("--_drawer-depth");
        const index = stack.indexOf(dialog);
        if (index < 0)
            return;
        stack.splice(index, 1);
        restack();
    }
    /**
     * @description Moves an open drawer to one of its snap points.
     *
     * @param dialog - The drawer.
     * @param index - The snap point, counted from the smallest; clamped to the ones it has.
     */
    function snapDrawer(dialog, index) {
        bound.get(dialog)?.snapTo(index);
    }
    /**
     * @description Starts drawer binding for the page: every drawer is bound when
     * the dialog lifecycle reports it open and unbound when it closes. Idempotent.
     */
    const initDrawers = function () {
        if (initDrawers._bound)
            return;
        initDrawers._bound = true;
        document.addEventListener("zazz:dialog-open", (event) => {
            if (event.target instanceof HTMLDialogElement && event.target.matches(DRAWER)) {
                bindDrawer(event.target);
            }
        });
        document.addEventListener("zazz:dialog-close", (event) => {
            if (event.target instanceof HTMLDialogElement)
                unbindDrawer(event.target);
        });
        window.addEventListener("resize", () => {
            if (indented)
                measureIndent(indented);
        });
        // drawers that were already open when the script loaded
        for (const dialog of document.querySelectorAll(`${DRAWER}[open]`)) {
            bindDrawer(dialog);
        }
    };
    // Auto-initialize when DOM is ready (only in browser environment)
    if (typeof window !== "undefined" && typeof document !== "undefined") {
        if (document.readyState === "loading") {
            document.addEventListener("DOMContentLoaded", initDrawers);
        }
        else {
            initDrawers();
        }
    }
    export { bindDrawer, initDrawers, snapDrawer };

    Nested

    Your order

    Open the second drawer: this one steps back behind it.

    Two items, arriving Thursday.

    Delivery address

    Drag this drawer down and the one behind follows it back.

    14 Harbour Street, Flat 3.

    <button data-ui="button" type="button" command="show-modal" commandfor="drawer-nested-1">
      Open drawer
    </button>
    <dialog id="drawer-nested-1" data-ui="drawer" closedby="any">
      <div data-drawer-slot="handle"></div>
      <div data-drawer-slot="content">
        <header data-drawer-slot="header">
          <h2
            style="
              --font-size: var(--font-size-lg);
              --font-weight: strong;
              --font-family: var(--font-family-heading);
            "
          >
            Your order
          </h2>
          <p style="--text: var(--color-muted-foreground)">
            Open the second drawer: this one steps back behind it.
          </p>
        </header>
        <div data-drawer-slot="body">
          <p>Two items, arriving Thursday.</p>
        </div>
        <footer data-drawer-slot="footer">
          <button data-ui="button" type="button" commandfor="drawer-nested-1" command="close">
            Close
          </button>
          <button
            data-ui="button"
            data-button-variant="primary"
            type="button"
            command="show-modal"
            commandfor="drawer-nested-2"
          >
            Change address
          </button>
        </footer>
      </div>
    </dialog>
    <dialog id="drawer-nested-2" data-ui="drawer" closedby="any">
      <div data-drawer-slot="handle"></div>
      <div data-drawer-slot="content">
        <header data-drawer-slot="header">
          <h2
            style="
              --font-size: var(--font-size-lg);
              --font-weight: strong;
              --font-family: var(--font-family-heading);
            "
          >
            Delivery address
          </h2>
          <p style="--text: var(--color-muted-foreground)">
            Drag this drawer down and the one behind follows it back.
          </p>
        </header>
        <div data-drawer-slot="body">
          <p>14 Harbour Street, Flat 3.</p>
        </div>
        <footer data-drawer-slot="footer">
          <button
            data-ui="button"
            data-button-variant="primary"
            type="button"
            commandfor="drawer-nested-2"
            command="close"
          >
            Done
          </button>
        </footer>
      </div>
    </dialog>
    /**
     * drawer.css: Drawer ([data-ui~="drawer"] on native <dialog>; slots
     *             data-drawer-slot="handle | content | header | body | footer | close";
     *             <ui-drawer-indent> / [data-ui~="drawer-indent"], the page wrapper that
     *             scales back behind an open drawer)
     *
     * A bottom sheet: a modal dialog that rises from the bottom edge and is dragged
     * back down to dismiss. Alone (`data-ui="drawer"`) it is a drawer everywhere;
     * on a dialog (`data-ui="dialog drawer"`) it is a drawer below the sm band on a
     * touch screen and the plain dialog otherwise. `data-drawer-snap` gives it
     * resting heights; a drawer opened over another pushes that one back.
     *
     * @layer      variables, components
     * @requires   _layers.css, _variables.css, dialog.css (the native <dialog> motion, backdrop, and
     *             scroll lock in its reset layer; the surface and slots in the combined form)
     * @uses       Overrides --ui-dialog-* motion tokens: the dialog's open/close transition becomes a
     *             rise from the bottom edge, with the backdrop on the same duration and curve
     * @uses       translate — drawer.js writes the inline translate while a pointer drags the drawer
     *             (state `dragging`, transitions off); the dialog's transitions finish the release
     * @uses       Web Animations on ::backdrop — drawer.js scrubs a paused opacity animation so the
     *             backdrop fades with the drag without restyling the drawer's content on every move
     * @uses       @property (inherits: false) + `inherit` on ::backdrop — the same link in CSS, for
     *             an engine that cannot animate ::backdrop from script; where neither works the
     *             backdrop stays opaque until release
     * @uses       @media (width < 40rem) and (not (hover: hover)) — the combined form's drawer mode,
     *             the same phone test as dialog.css
     * @uses       scale, translate — the only properties the stack and the indent animate; the
     *             indent's corner radius is two corner pieces that scale up, so no border-radius or
     *             clip is animated and the page is never repainted for it
     * @uses       clip-path: inset() — a fixed rectangle while the page is indented, so the part of
     *             the page above and below the viewport stays out of the gaps the scale opens
     * @uses       :has() — the body takes the backing color while its page wrapper is indented
     * @uses       @starting-style — the corner pieces grow from nothing when they are generated
     * @uses       corner-shape — the corner pieces follow --radius-corner-shape where it is
     *             supported and are round elsewhere
     * @uses       env(safe-area-inset-top) — the indented page clears the status bar
     * @uses       env(safe-area-inset-bottom) — content clears the home indicator
     * @uses       visualViewport — drawer.js writes --_drawer-keyboard (the software
     *             keyboard's height) on the front drawer, and the sheet's bottom padding takes it,
     *             so content ends at the keyboard's top edge while the surface runs on under it
     * @uses       --_touch-min — the handle's hit area on touch screens
     * @tokens     --ui-drawer-* (@layer variables)
     */
    
    @layer variables {
      :root {
        /* surface */
        --ui-drawer-bg: var(--ui-dialog-bg);
        --ui-drawer-text: var(--ui-dialog-text);
        --ui-drawer-radius: var(--radius-xl);
        --ui-drawer-corner-shape: var(--ui-dialog-corner-shape);
        --ui-drawer-shadow: var(--shadow-lg);
    
        /* metrics: edge to edge, the layout-bleed band; cap it with a band to float a
           narrower sheet, e.g. min(var(--layout-sm), 100%) */
        --ui-drawer-w: 100%;
        --ui-drawer-max-h: calc(100dvb - var(--space-lg));
    
        /* stack: how much each drawer in front shrinks and lifts the one behind */
        --ui-drawer-stack-scale: 0.05;
        --ui-drawer-stack-lift: var(--space-sm);
        /* the page is already dimmed by the first drawer's backdrop */
        --ui-drawer-nested-backdrop-color: transparent;
    
        /* indent: how far each side of the page pulls in, how far it drops, the radius of
           its top corners, and the color behind it. Set these on :root: the body reads the
           backing color too. */
        --ui-drawer-indent-inset: calc(var(--spacing) * 3);
        --ui-drawer-indent-offset: calc(env(safe-area-inset-top, 0px) + var(--space-sm));
        --ui-drawer-indent-radius: var(--ui-drawer-radius);
        --ui-drawer-indent-bg: var(--color-background);
        --ui-drawer-indent-backing: var(--color-black);
    
        /* handle */
        --ui-drawer-handle-w: calc(var(--spacing) * 12);
        --ui-drawer-handle-h: calc(var(--spacing) * 1.25);
        --ui-drawer-handle-bg: var(--color-muted);
        --ui-drawer-handle-bg--hover: var(--color-muted-foreground);
        --ui-drawer-handle-bg--active: var(--color-muted-foreground);
        --ui-drawer-handle-bg--dragging: var(--color-foreground);
    
        /* motion: the iOS sheet curve, steep at the start so twice the default
           duration still reads as quick; 0s under reduced motion like the default */
        --ui-drawer-transition-duration: calc(var(--default-transition-duration) * 2);
        --ui-drawer-transition-timing-function: cubic-bezier(0.32, 0.72, 0, 1);
      }
    }
    
    /* Drawer mode flag, read by drawer.js; and the backdrop's drag opacity, written by it.
       Non-inheriting, so neither restyles the drawer's content. */
    @property --_drawer-mode {
      syntax: "*";
      inherits: false;
    }
    
    @property --_drawer-backdrop {
      syntax: "*";
      inherits: false;
    }
    
    /* Where a drawer with snap points rests, and how many drawers sit in front of it:
       both written by drawer.js when they change (the depth also while the front drawer
       is dragged), and non-inheriting, so neither restyles the drawer's content. */
    @property --_drawer-snap {
      syntax: "*";
      inherits: false;
    }
    
    @property --_drawer-depth {
      syntax: "*";
      inherits: false;
    }
    
    /* The software keyboard's height while the drawer is the front one, written by
       drawer.js from the visual viewport; the sheet's bottom padding takes it. */
    @property --_drawer-keyboard {
      syntax: "*";
      inherits: false;
    }
    
    /* The indent's measurements, written by drawer.js when a drawer opens, and how
       indented the page is (0 to 1): 1 from the `active` state, or the drag's own
       value while the last drawer is dragged. The corner pieces take them by explicit
       inheritance. The inset is typed so the script reads the hook in px. */
    @property --_drawer-indent-amount {
      syntax: "*";
      inherits: false;
    }
    
    @property --_drawer-indent-scale {
      syntax: "*";
      inherits: false;
    }
    
    @property --_drawer-indent-top {
      syntax: "*";
      inherits: false;
    }
    
    @property --_drawer-indent-bottom {
      syntax: "*";
      inherits: false;
    }
    
    @property --_drawer-indent-inset {
      syntax: "<length>";
      inherits: false;
      initial-value: 0px;
    }
    
    @layer ui.components {
      /* ===========================================================================
      DRAWER MODE: the declarations that make a dialog a bottom sheet. Written
      twice, because the two forms enter it under different conditions: the
      standalone form always, the combined form on a phone. Keep the two blocks
      identical apart from the --_dialog-* lines, which feed the dialog's own
      read chain in the combined form.
    
      The sheet extends --_bleed past the bottom edge (padding inside,
      an equal negative margin outside), so pulling it up against its resistance
      never opens a gap under it.
      =========================================================================== */
    
      :where([data-ui~="drawer"]:not([data-ui~="dialog"])) {
        --_drawer-mode: 1;
        --_bleed: calc(var(--spacing) * 12);
        --_handle-display: block;
        --_content-row: 2;
        --_header-select: none;
    
        --ui-dialog-transition-duration: var(--ui-drawer-transition-duration);
        --ui-dialog-transition-timing-function: var(--ui-drawer-transition-timing-function);
        --ui-dialog-backdrop-transition-duration: var(--ui-dialog-transition-duration);
        --ui-dialog-backdrop-transition-timing-function: var(--ui-drawer-transition-timing-function);
        --ui-dialog-transition-delay--end: 0ms;
        --ui-dialog-opacity--start: 1;
        --ui-dialog-scale--start: 1;
        --ui-dialog-translate--start: 0, 100%, 0;
    
        margin-block: auto calc(var(--_bleed) * -1);
        margin-inline: auto;
        /* the keyboard covers the home indicator: the larger of the two, not both */
        padding-block-end: calc(
          var(--_bleed) + max(env(safe-area-inset-bottom, 0px), var(--_drawer-keyboard, 0px))
        );
        max-inline-size: 100%;
        max-block-size: calc(var(--ui-drawer-max-h) + var(--_bleed));
        grid-template-rows: auto minmax(0, 1fr);
        border-block-end-width: 0;
        border-end-start-radius: 0;
        border-end-end-radius: 0;
        /* a stacked drawer shrinks toward its top edge, the part that stays in view */
        transform-origin: 50% 0;
      }
    
      @media (width < 40rem) and (not (hover: hover)) {
        :where([data-ui~="dialog"][data-ui~="drawer"]) {
          --_drawer-mode: 1;
          --_bleed: calc(var(--spacing) * 12);
          --_handle-display: block;
          --_content-row: 2;
          --_header-select: none;
    
          --_dialog-w: var(--ui-drawer-w);
          --_dialog-radius: var(--ui-drawer-radius);
          --_dialog-shadow: var(--ui-drawer-shadow);
    
          --ui-dialog-transition-duration: var(--ui-drawer-transition-duration);
          --ui-dialog-transition-timing-function: var(--ui-drawer-transition-timing-function);
          --ui-dialog-backdrop-transition-duration: var(--ui-dialog-transition-duration);
          --ui-dialog-backdrop-transition-timing-function: var(--ui-drawer-transition-timing-function);
          --ui-dialog-transition-delay--end: 0ms;
          --ui-dialog-opacity--start: 1;
          --ui-dialog-scale--start: 1;
          --ui-dialog-translate--start: 0, 100%, 0;
    
          margin-block: auto calc(var(--_bleed) * -1);
          margin-inline: auto;
          /* the keyboard covers the home indicator: the larger of the two, not both */
          padding-block-end: calc(
            var(--_bleed) + max(env(safe-area-inset-bottom, 0px), var(--_drawer-keyboard, 0px))
          );
          max-inline-size: 100%;
          max-block-size: calc(var(--ui-drawer-max-h) + var(--_bleed));
          grid-template-rows: auto minmax(0, 1fr);
          border-block-end-width: 0;
          border-end-start-radius: 0;
          border-end-end-radius: 0;
          transform-origin: 50% 0;
        }
      }
    
      /* ===========================================================================
      STANDALONE SURFACE: without the dialog identity the drawer paints itself.
      The combined form takes all of this from dialog.css.
      =========================================================================== */
    
      :where([data-ui~="drawer"]:not([data-ui~="dialog"])) {
        inline-size: var(--ui-drawer-w);
        block-size: fit-content;
        background-color: var(--_bg-resolved, var(--ui-drawer-bg));
        color: var(--_text-resolved, var(--ui-drawer-text));
        box-shadow: var(--_shadow-resolved, var(--ui-drawer-shadow));
        /* the top corners only: the bottom edge sits past the viewport */
        border-start-start-radius: var(--ui-drawer-radius);
        border-start-end-radius: var(--ui-drawer-radius);
        corner-shape: var(--_corner-shape-resolved, var(--ui-drawer-corner-shape));
        font-size: var(--font-size-md);
        overflow: hidden;
        overscroll-behavior: contain;
      }
    
      :where([data-ui~="drawer"]:not([data-ui~="dialog"])[open]) {
        display: grid;
        min-block-size: 0;
      }
    
      /* ===========================================================================
      SNAP POINTS: a drawer with data-drawer-snap is as tall as a drawer may be and
      rests pushed down by --_drawer-snap, which drawer.js writes when the stop
      changes. The height is set per form, like drawer mode itself.
      =========================================================================== */
    
      :where([data-ui~="drawer"]:not([data-ui~="dialog"])[data-drawer-snap]) {
        block-size: calc(var(--ui-drawer-max-h) + var(--_bleed));
      }
    
      @media (width < 40rem) and (not (hover: hover)) {
        :where([data-ui~="dialog"][data-ui~="drawer"][data-drawer-snap]) {
          --_dialog-h: calc(var(--ui-drawer-max-h) + var(--_bleed));
        }
      }
    
      :where([data-ui~="drawer"][data-drawer-snap]) {
        translate: 0 var(--_drawer-snap, 0px);
      }
    
      /* ===========================================================================
      STACK: a drawer with others open in front of it shrinks toward its top edge
      and lifts, once per drawer in front. drawer.js writes the count, and while
      the front drawer is dragged a fraction of it (state `following`, transitions
      off). A drawer opened over another dims nothing more.
      =========================================================================== */
    
      :where([data-ui~="drawer"][data-drawer-state~="stacked"]) {
        scale: calc(1 - var(--_drawer-depth, 0) * var(--ui-drawer-stack-scale));
        translate: 0
          calc(var(--_drawer-snap, 0px) - var(--_drawer-depth, 0) * var(--ui-drawer-stack-lift));
      }
    
      :where([data-ui~="drawer"][data-drawer-state~="following"]) {
        transition: none;
      }
    
      :where([data-ui~="drawer"][data-drawer-state~="nested"])::backdrop {
        background-color: var(--ui-drawer-nested-backdrop-color);
        backdrop-filter: none;
      }
    
      /* Each slot owns a row, as in the dialog: the body is the part that scrolls */
      :where([data-ui~="drawer"]) [data-drawer-slot~="content"] {
        display: grid;
        grid-template-rows: auto minmax(0, 1fr) auto;
        position: relative;
        min-block-size: 0;
        max-block-size: 100%;
      }
    
      :where([data-ui~="drawer"]) [data-drawer-slot~="header"] {
        grid-row: 1;
        display: flex;
        flex-direction: column;
        padding-inline: var(--space-sm);
        padding-block-start: var(--space-sm);
      }
    
      :where([data-ui~="drawer"]) [data-drawer-slot~="body"] {
        grid-row: 2;
        display: grid;
        align-content: start;
        padding-inline: var(--space-sm);
        padding-block: var(--space-md);
        min-block-size: 0;
        overflow-y: auto;
        overscroll-behavior: contain;
      }
    
      :where([data-ui~="drawer"]) [data-drawer-slot~="footer"] {
        grid-row: 3;
        display: flex;
        justify-content: flex-end;
        gap: var(--space-xs);
        padding: var(--space-sm);
        border-block-start: 1px solid var(--color-border);
      }
    
      :where([data-ui~="drawer"]) [data-drawer-slot~="close"] {
        position: absolute;
        inset-block-start: var(--space-xs);
        inset-inline-end: var(--space-xs);
        z-index: 50;
      }
    
      /* ===========================================================================
      PARTS IN DRAWER MODE: the handle shows and takes the first row; the content
      slot (the drawer's own or the dialog's) takes the flexible second row, with
      or without a handle before it. Both read the mode privates set above, so
      neither rule is repeated per form.
      =========================================================================== */
    
      :where([data-ui~="drawer"]) :where([data-drawer-slot~="content"], [data-dialog-slot~="content"]) {
        grid-row: var(--_content-row, auto);
      }
    
      /* The header is where a mouse grabs the drawer: a press on its text drags
         instead of selecting. Body text stays selectable. */
      :where([data-ui~="drawer"]) :where([data-drawer-slot~="header"], [data-dialog-slot~="header"]) {
        -webkit-user-select: var(--_header-select, auto);
        user-select: var(--_header-select, auto);
      }
    
      /* A pill, with a hit area that reaches the touch-target height. It always
         drags, even over a scrolled body, so it opts out of native panning. */
      :where([data-ui~="drawer"]) [data-drawer-slot~="handle"] {
        display: var(--_handle-display, none);
        grid-row: 1;
        justify-self: center;
        position: relative;
        inline-size: var(--ui-drawer-handle-w);
        block-size: var(--ui-drawer-handle-h);
        margin-block: calc(var(--spacing) * 2.5) calc(var(--spacing) * 1);
        border-radius: var(--radius-full);
        background-color: var(--ui-drawer-handle-bg);
        cursor: grab;
        touch-action: none;
        -webkit-user-select: none;
        user-select: none;
        transition: background-color var(--default-transition-duration)
          var(--default-transition-timing-function);
      }
    
      :where([data-ui~="drawer"]) [data-drawer-slot~="handle"]:hover {
        background-color: var(--ui-drawer-handle-bg--hover);
      }
    
      :where([data-ui~="drawer"]) [data-drawer-slot~="handle"]:active {
        background-color: var(--ui-drawer-handle-bg--active);
        cursor: grabbing;
      }
    
      :where([data-ui~="drawer"]) [data-drawer-slot~="handle"]::before {
        content: "";
        position: absolute;
        inset-inline: calc(var(--ui-drawer-handle-w) * -1);
        inset-block: min(calc(var(--spacing) * -2), calc((100% - var(--_touch-min, 0px)) / 2));
      }
    
      /* Below its largest snap point a drawer's content does not scroll: the drawer
         moves first. After the slot rules, which it has to beat. */
      :where([data-ui~="drawer"][data-drawer-state~="partial"])
        :is([data-drawer-slot~="body"], [data-dialog-slot~="body"]) {
        overflow-y: hidden;
      }
    
      /* ===========================================================================
      DRAG: while a pointer drags the drawer, drawer.js writes its inline
      translate and nothing may ease it: the drawer is the pointer. The backdrop
      fades with the drag: drawer.js scrubs an animation on it, or, where
      ::backdrop cannot be animated from script, writes --_drawer-backdrop, which
      the backdrop takes from the dialog by explicit inheritance. On release the state drops and the dialog's
      own transitions finish the motion, to closed or back to rest.
      =========================================================================== */
    
      :where([data-ui~="drawer"][data-drawer-state~="dragging"]) [data-drawer-slot~="handle"] {
        background-color: var(--ui-drawer-handle-bg--dragging);
      }
    
      :where([data-ui~="drawer"][data-drawer-state~="dragging"]) {
        transition: none;
        cursor: grabbing;
        /* a mouse drag that began beside text must not start selecting it */
        -webkit-user-select: none;
        user-select: none;
      }
    
      :where([data-ui~="drawer"][data-drawer-state~="dragging"])::backdrop {
        --_drawer-backdrop: inherit;
        opacity: var(--_drawer-backdrop, 1);
        transition: none;
      }
    
      /* ===========================================================================
      INDENT: the page wrapper scales back behind an open drawer. drawer.js sets the
      state (`on` while the machinery is engaged, `active` while a drawer is open,
      `dragging` while the last drawer is dragged) and measures, once, the scale and
      where the viewport sits inside the wrapper.
    
      Only scale and translate animate. The wrapper is clipped to the viewport's
      rectangle, a fixed clip, so the page above and below it stays out of the gaps;
      the body paints the backing color there. The rounded top corners are two
      corner pieces that grow from the corners, not a border-radius: nothing is
      repainted while the page moves.
    
      While `on` the wrapper is transformed, so it is the containing block of its
      fixed and absolute descendants.
      =========================================================================== */
    
      :where(ui-drawer-indent, [data-ui~="drawer-indent"]) {
        --_drawer-indent-inset: var(--ui-drawer-indent-inset);
        display: block;
        background-color: var(--ui-drawer-indent-bg);
        transition:
          scale var(--ui-drawer-transition-duration) var(--ui-drawer-transition-timing-function),
          translate var(--ui-drawer-transition-duration) var(--ui-drawer-transition-timing-function);
      }
    
      :where(ui-drawer-indent, [data-ui~="drawer-indent"])[data-drawer-indent-state~="on"] {
        position: relative;
        transform-origin: 50% var(--_drawer-indent-top, 0px);
        scale: calc(1 - (1 - var(--_drawer-indent-scale, 1)) * var(--_drawer-indent-amount, 0));
        translate: 0 calc(var(--ui-drawer-indent-offset) * var(--_drawer-indent-amount, 0));
        clip-path: inset(var(--_drawer-indent-top, 0px) 0 var(--_drawer-indent-bottom, 0px) 0);
        will-change: scale, translate;
      }
    
      :where(ui-drawer-indent, [data-ui~="drawer-indent"])[data-drawer-indent-state~="active"] {
        --_drawer-indent-amount: 1;
      }
    
      /* The backing shows in the gaps around the indented page. Important, because a
         page's own <body style="--bg: …"> is a utility and would otherwise win; it holds
         only while the wrapper is `on`. */
      :where(body):has(
        :is(ui-drawer-indent, [data-ui~="drawer-indent"])[data-drawer-indent-state~="on"]
      ) {
        background-color: var(--ui-drawer-indent-backing) !important;
      }
    
      /* A corner piece: a square the size of the radius whose outer corner is rounded
         and whose spread shadow, cut off at the square, paints only the notch outside
         the curve. Scaling it from that corner is the radius growing. */
      :where(ui-drawer-indent, [data-ui~="drawer-indent"])[data-drawer-indent-state~="on"]::before,
      :where(ui-drawer-indent, [data-ui~="drawer-indent"])[data-drawer-indent-state~="on"]::after {
        --_drawer-indent-amount: inherit;
        --_drawer-indent-top: inherit;
        content: "";
        position: absolute;
        z-index: 2147483647;
        inset-block-start: var(--_drawer-indent-top, 0px);
        inline-size: var(--ui-drawer-indent-radius);
        block-size: var(--ui-drawer-indent-radius);
        box-shadow: 0 0 0 var(--ui-drawer-indent-radius) var(--ui-drawer-indent-backing);
        clip-path: inset(0);
        corner-shape: var(--radius-corner-shape);
        scale: var(--_drawer-indent-amount, 0);
        pointer-events: none;
        transition: scale var(--ui-drawer-transition-duration)
          var(--ui-drawer-transition-timing-function);
    
        @starting-style {
          scale: 0;
        }
      }
    
      :where(ui-drawer-indent, [data-ui~="drawer-indent"])[data-drawer-indent-state~="on"]::before {
        left: 0;
        border-top-left-radius: 100%;
        transform-origin: 0 0;
      }
    
      :where(ui-drawer-indent, [data-ui~="drawer-indent"])[data-drawer-indent-state~="on"]::after {
        right: 0;
        border-top-right-radius: 100%;
        transform-origin: 100% 0;
      }
    
      :where(ui-drawer-indent, [data-ui~="drawer-indent"])[data-drawer-indent-state~="dragging"],
      :where(
          ui-drawer-indent,
          [data-ui~="drawer-indent"]
        )[data-drawer-indent-state~="dragging"]::before,
      :where(
          ui-drawer-indent,
          [data-ui~="drawer-indent"]
        )[data-drawer-indent-state~="dragging"]::after {
        transition: none;
      }
    }
    // primitives/drawer/drawer.js
    "use strict";
    /**
     * @fileoverview Drawer: drag-to-dismiss for `<dialog data-ui="drawer">` bottom sheets.
     * @description A drawer is a native modal `<dialog>`, opened and closed like
     * any other (`command="show-modal"`, `command="close"`, Esc, the backdrop with
     * `closedby="any"`). This script adds the gesture: drag the drawer down and
     * let go to dismiss it.
     *
     * - `data-ui="drawer"` is a drawer on every device.
     * - `data-ui="dialog drawer"` is a drawer below the `sm` band on a touch
     *   screen, and a plain dialog (no dragging) everywhere else.
     *
     * While the pointer is down the drawer follows it 1:1 and the backdrop fades
     * with it. Letting go past a quarter of the drawer's height, or with a quick
     * downward flick, slides it off the bottom edge and then closes it through
     * `requestClose()`, so `cancel` and `close` fire as they do for Esc; anything
     * less returns it to rest. Until it has slid out it can be caught again. Pulling it up
     * past its resting place meets resistance.
     *
     * A drag starts anywhere on the drawer except on form fields, selected text,
     * and anything inside `[data-ui-no-drag]`. Inside scrolling content it starts
     * only once that content is scrolled to the top and the pointer moves down,
     * so the body scrolls first and the drawer follows; the handle
     * (`data-drawer-slot="handle"`) always drags. There is no custom element and
     * nothing to initialize: the script binds a drawer when it opens.
     *
     * **Snap points.** `data-drawer-snap="148px 0.5 1"` gives the drawer resting
     * heights, smallest first: a number up to 1 is a share of the drawer's full
     * height, a `px` or `rem` length is a visible height. It opens at the first.
     * Letting go settles on the nearest; a flick moves one stop in its direction,
     * a very fast one goes all the way (or one stop, with
     * `data-drawer-snap-sequential`), and from the lowest stop a flick or enough
     * travel downward closes the drawer. Below the largest stop the drawer takes
     * every vertical drag and its content does not scroll. A click on the handle
     * steps to the next stop; make the handle a `<button>` to give the keyboard
     * the same. Each change fires `zazz:drawer-snap` (`detail.index`,
     * `detail.value` in px), `data-drawer-state` carries `expanded` at the largest
     * stop, and `snapDrawer(dialog, index)` moves it from script.
     *
     * **The software keyboard.** A phone lays a drawer out against the full
     * screen, which the keyboard does not shrink. While a field in the front
     * drawer has the keyboard up, the drawer's content ends at the keyboard's top
     * edge (its surface runs on underneath), the focused field scrolls into what
     * is still visible, and the page behind stays where it was. Nothing to author.
     *
     * **Stacked drawers.** A drawer opened over another scales the one behind back
     * and lifts it, and that one follows as the front drawer is dragged. Nothing
     * to author: the script counts the open drawers.
     *
     * **Indent.** Wrap the page in `<ui-drawer-indent>` (or put
     * `data-ui="drawer-indent"` on its wrapper) and it scales back behind any open
     * drawer, with rounded top corners, and follows the drag of the last one. Only
     * transforms animate. While indented the wrapper is transformed, so a
     * `position: fixed` element inside it moves with the page; `position: sticky`
     * is unaffected.
     *
     * @example
     * <button data-ui="button" command="show-modal" commandfor="filters">Filters</button>
     * <dialog id="filters" data-ui="drawer" closedby="any">
     *   <div data-drawer-slot="handle"></div>
     *   <div data-drawer-slot="content">
     *     <header data-drawer-slot="header">…</header>
     *     <div data-drawer-slot="body">…</div>
     *   </div>
     * </dialog>
     */
    import { currentTranslate, maxTransitionMs, pickSnap, rubberBand, trackDrag, } from "../../base/gesture.js";
    // --- Tuning ---
    /** Share of the drawer's visible height, at its lowest stop, that dismisses on its own. */
    const CLOSE_RATIO = 0.25;
    /** Speed that moves the drawer one stop, or dismisses it from the lowest, in px/ms. */
    const FLICK_VELOCITY = 0.4;
    /** Speed that skips every stop: all the way open, or closed, in px/ms. */
    const FLING_VELOCITY = 2;
    /**
     * After inner content scrolls, how long before the drawer may be dragged, in
     * ms. A fast scroll that reaches the top would otherwise carry straight on
     * into dragging the drawer away.
     */
    const SCROLL_GUARD_MS = 100;
    /** Length of the backdrop's scrub animation: its timeline is drag progress, not time. */
    const SCRUB_MS = 1000;
    const DRAWER = 'dialog[data-ui~="drawer"]';
    const HANDLE = '[data-drawer-slot~="handle"]';
    const INDENT = 'ui-drawer-indent, [data-ui~="drawer-indent"]';
    const INDENT_STATE = "data-drawer-indent-state";
    // --- Helpers ---
    /** Adds or removes one token of a space-separated state attribute; an empty attribute is removed. */
    function setToken(element, attribute, token, on) {
        const tokens = new Set((element.getAttribute(attribute) ?? "").split(/\s+/).filter(Boolean));
        if (tokens.has(token) === on)
            return;
        if (on)
            tokens.add(token);
        else
            tokens.delete(token);
        if (tokens.size)
            element.setAttribute(attribute, [...tokens].join(" "));
        else
            element.removeAttribute(attribute);
    }
    /** Adds or removes a token of a drawer's `data-drawer-state`. */
    function setState(dialog, token, on) {
        setToken(dialog, "data-drawer-state", token, on);
    }
    /** Adds or removes the `dragging` token of a drawer's `data-drawer-state`. */
    function setDragging(dialog, on) {
        setState(dialog, "dragging", on);
    }
    /** Clears everything a drag wrote on the drawer. */
    function reset(dialog) {
        setDragging(dialog, false);
        dialog.style.removeProperty("translate");
        dialog.style.removeProperty("--_drawer-backdrop");
    }
    /**
     * @description Reads a drawer's snap points as resting positions: px the
     * drawer is pushed down at each, the smallest visible height first.
     *
     * @param dialog - The drawer.
     * @param height - The drawer's full visible height in px.
     * @returns The positions, descending; `[0]` without usable snap points.
     * @private
     */
    function readStops(dialog, height) {
        const raw = dialog.getAttribute("data-drawer-snap")?.trim();
        if (!raw)
            return [0];
        const rem = Number.parseFloat(getComputedStyle(document.documentElement).fontSize) || 16;
        const positions = new Set();
        for (const token of raw.split(/\s+/)) {
            const value = Number.parseFloat(token);
            if (!Number.isFinite(value) || value <= 0)
                continue;
            let visible = value * height;
            if (token.endsWith("rem"))
                visible = value * rem;
            else if (token.endsWith("px") || value > 1)
                visible = value;
            positions.add(Math.round(height - Math.min(height, Math.max(1, visible))));
        }
        return positions.size ? [...positions].sort((a, b) => b - a) : [0];
    }
    /**
     * @description Starts a paused opacity animation on the drawer's backdrop, to
     * be scrubbed with the drag. An animation, not a style write: it reaches the
     * pseudo-element without restyling the drawer's content, in engines that do
     * not re-resolve `::backdrop` when a non-inherited property changes on its
     * dialog (WebKit).
     *
     * @param dialog - The drawer.
     * @returns The animation, or null where `::backdrop` cannot be animated; the
     * caller then writes `--_drawer-backdrop`, which drawer.css reads.
     * @private
     */
    function scrubBackdrop(dialog) {
        try {
            const animation = dialog.animate([{ opacity: 1 }, { opacity: 0 }], {
                pseudoElement: "::backdrop",
                duration: SCRUB_MS,
                fill: "both",
            });
            animation.pause();
            return animation;
        }
        catch {
            return null;
        }
    }
    /** Whether drawer.css has the dialog in drawer mode right now. */
    function inDrawerMode(dialog) {
        return getComputedStyle(dialog).getPropertyValue("--_drawer-mode").trim() === "1";
    }
    /** Whether an element scrolls its content on the block axis. */
    function scrolls(element) {
        if (element.scrollHeight <= element.clientHeight)
            return false;
        const overflow = getComputedStyle(element).overflowY;
        return overflow === "auto" || overflow === "scroll";
    }
    /**
     * @description Whether a press may drag the drawer, given what it landed on
     * and which way it is moving.
     *
     * @param dialog - The drawer.
     * @param drag - The drag about to start; `offset` carries its direction.
     * @param lastScroll - When content inside the drawer last scrolled.
     * @param partial - Whether the drawer rests below its largest snap point.
     * @returns Whether the drawer takes the gesture.
     * @private
     */
    function claims(dialog, drag, lastScroll, partial) {
        if (!inDrawerMode(dialog))
            return false;
        // a press on the backdrop targets the dialog, outside its box
        const box = dialog.getBoundingClientRect();
        if (drag.startY < box.top || drag.startX < box.left || drag.startX > box.right)
            return false;
        if (drag.target.closest(HANDLE))
            return true;
        // below its largest stop the drawer moves before anything inside it scrolls
        if (partial)
            return true;
        // scrolling content goes first: it must be at the top, and the pull downward
        const down = drag.offset > 0;
        for (let node = drag.target; node && dialog.contains(node); node = node.parentElement) {
            if (scrolls(node) && (node.scrollTop > 0 || !down))
                return false;
        }
        return performance.now() - lastScroll >= SCROLL_GUARD_MS;
    }
    // --- Stack ---
    /** The open drawers in drawer mode, the front one last. */
    const stack = [];
    /**
     * @description Writes each open drawer's place in the stack: how many drawers
     * sit in front of it (`--_drawer-depth`, `stacked`) and whether it opened over
     * another (`nested`). Runs when a drawer opens or closes, never per frame.
     * @private
     */
    function restack() {
        // a drawer removed from the page while open never reports its close
        for (let index = stack.length - 1; index >= 0; index--) {
            const dialog = stack[index];
            if (!dialog.isConnected || !dialog.open)
                stack.splice(index, 1);
        }
        stack.forEach((dialog, index) => {
            const depth = stack.length - 1 - index;
            setState(dialog, "following", false);
            setState(dialog, "stacked", depth > 0);
            setState(dialog, "nested", index > 0);
            if (depth > 0)
                dialog.style.setProperty("--_drawer-depth", String(depth));
            else
                dialog.style.removeProperty("--_drawer-depth");
        });
        indentPose(stack.length > 0);
    }
    /**
     * @description Moves the drawers behind `front` with its drag: at progress 1
     * each sits where it will once `front` is gone. The depth is a non-inheriting
     * property, so the write restyles those drawers and not their content.
     *
     * @param front - The drawer being dragged or released.
     * @param progress - How far `front` is toward closed, 0 to 1.
     * @param live - Whether a pointer is driving it (transitions off).
     * @private
     */
    function follow(front, progress, live) {
        const index = stack.indexOf(front);
        for (let behind = 0; behind < index; behind++) {
            const dialog = stack[behind];
            dialog.style.setProperty("--_drawer-depth", String(index - behind - progress));
            setState(dialog, "following", live);
        }
    }
    // --- Indent ---
    /** The page wrapper that is indented right now, and what ends its return to rest. */
    let indented = null;
    let cancelOutdent = null;
    /**
     * @description Measures what the indent needs, once per activation and on
     * resize: the scale that pulls each side in by the inset hook, and where the
     * viewport sits inside the wrapper (the transform's origin, the clip, and the
     * corner pieces all hang off its top edge).
     * @private
     */
    function measureIndent(wrapper) {
        const box = wrapper.getBoundingClientRect();
        const width = wrapper.offsetWidth || 1;
        const inset = Number.parseFloat(getComputedStyle(wrapper).getPropertyValue("--_drawer-indent-inset")) || 0;
        const top = Math.max(0, -box.top);
        const bottom = Math.max(0, wrapper.offsetHeight - top - window.innerHeight);
        wrapper.style.setProperty("--_drawer-indent-scale", String(Math.max(0, 1 - (inset * 2) / width)));
        wrapper.style.setProperty("--_drawer-indent-top", `${top}px`);
        wrapper.style.setProperty("--_drawer-indent-bottom", `${bottom}px`);
    }
    /**
     * @description Indents the page wrapper or sends it back to rest. The pose is
     * a state token and the motion a CSS transition; the `on` token (clip,
     * corners, backing) outlasts the pose until the return has finished.
     *
     * @param active - Whether a drawer is open.
     * @private
     */
    function indentPose(active) {
        // a wrapper that left the page takes its state with it
        if (indented && !indented.isConnected) {
            cancelOutdent?.();
            indented = null;
        }
        const wrapper = indented ?? document.querySelector(INDENT);
        if (!wrapper)
            return;
        if (active) {
            cancelOutdent?.();
            if (indented !== wrapper) {
                measureIndent(wrapper);
                indented = wrapper;
            }
            setToken(wrapper, INDENT_STATE, "on", true);
            setToken(wrapper, INDENT_STATE, "active", true);
            return;
        }
        if (!indented || cancelOutdent)
            return;
        setToken(wrapper, INDENT_STATE, "dragging", false);
        wrapper.style.removeProperty("--_drawer-indent-amount");
        setToken(wrapper, INDENT_STATE, "active", false);
        const off = () => {
            cancelOutdent?.();
            wrapper.removeAttribute(INDENT_STATE);
            for (const name of ["scale", "top", "bottom"]) {
                wrapper.style.removeProperty(`--_drawer-indent-${name}`);
            }
            indented = null;
        };
        const ms = maxTransitionMs(wrapper);
        if (ms <= 0) {
            off();
            return;
        }
        const onReturned = (event) => {
            if (event.target === wrapper && event.propertyName === "scale")
                off();
        };
        const timer = window.setTimeout(off, ms + 100);
        wrapper.addEventListener("transitionend", onReturned);
        cancelOutdent = () => {
            window.clearTimeout(timer);
            wrapper.removeEventListener("transitionend", onReturned);
            cancelOutdent = null;
        };
    }
    /**
     * @description Links the indent to the last open drawer's drag.
     *
     * @param progress - How far the drawer is toward closed, 0 to 1.
     * @param live - Whether a pointer is driving it (transitions off).
     * @private
     */
    function indentProgress(progress, live) {
        if (!indented)
            return;
        setToken(indented, INDENT_STATE, "dragging", live);
        if (live)
            indented.style.setProperty("--_drawer-indent-amount", String(1 - progress));
        else
            indented.style.removeProperty("--_drawer-indent-amount");
    }
    // --- Keyboard ---
    /** The keyboard's height on the front drawer, which drawer.css adds to its bottom padding. */
    const KEYBOARD_INSET = "--_drawer-keyboard";
    /** Space kept between a revealed field and the keyboard's top edge, in px. */
    const REVEAL_GAP = 16;
    /** Inputs that open a picker or nothing rather than the software keyboard. */
    const NO_KEYBOARD = /^(?:button|checkbox|color|file|hidden|image|radio|range|reset|submit|date|datetime-local|month|time|week)$/;
    /** Whether focus on this element opens the software keyboard. */
    function typesText(element) {
        if (element instanceof HTMLTextAreaElement)
            return !element.readOnly;
        if (element instanceof HTMLInputElement)
            return !element.readOnly && !NO_KEYBOARD.test(element.type);
        return element instanceof HTMLElement && element.isContentEditable;
    }
    /**
     * @description How much of the layout viewport the software keyboard covers,
     * from the bottom: the part below the visual viewport. 0 while the page is
     * pinch-zoomed, when the visual viewport is smaller for another reason.
     * @private
     */
    function keyboardInset() {
        const viewport = window.visualViewport;
        if (!viewport || Math.abs(viewport.scale - 1) > 0.01)
            return 0;
        const bottom = Math.max(0, viewport.offsetTop) + viewport.height;
        return Math.max(0, Math.round(window.innerHeight - Math.min(window.innerHeight, bottom)));
    }
    /**
     * @description Keeps an open drawer usable with the software keyboard up.
     * iOS lays out the top layer against the layout viewport, which the keyboard
     * does not shrink, and scrolls the page behind a modal to reveal a focused
     * field. While the drawer is the front one this writes the keyboard's height
     * to `--_drawer-keyboard` (drawer.css pads the sheet by it, so its
     * content ends at the keyboard's top edge), holds the page at its scroll
     * position, and scrolls a focused field into the part of its scrolling slot
     * that is still visible.
     *
     * @param dialog - The drawer.
     * @param signal - Aborts when the drawer closes.
     * @param onChange - Runs after the inset changes, once the new padding is in place.
     * @private
     */
    function trackKeyboard(dialog, signal, onChange) {
        const viewport = window.visualViewport;
        if (!viewport)
            return;
        const front = () => stack[stack.length - 1] === dialog;
        const pageX = window.scrollX;
        const pageY = window.scrollY;
        let frame = 0;
        let current = 0;
        const update = () => {
            frame = 0;
            const inset = front() ? keyboardInset() : 0;
            if (inset === current)
                return;
            current = inset;
            if (inset > 0)
                dialog.style.setProperty(KEYBOARD_INSET, `${inset}px`);
            else
                dialog.style.removeProperty(KEYBOARD_INSET);
            onChange();
        };
        const schedule = () => {
            if (!frame)
                frame = requestAnimationFrame(update);
        };
        /** Scrolls the field's scrolling slot so the field sits above the keyboard and below the slot's top. */
        const reveal = (field) => {
            if (!dialog.contains(field) || document.activeElement !== field)
                return;
            let container = field.parentElement;
            while (container && dialog.contains(container) && !scrolls(container)) {
                container = container.parentElement;
            }
            if (!container || !dialog.contains(container))
                return;
            const box = container.getBoundingClientRect();
            const target = field.getBoundingClientRect();
            const visibleBottom = Math.min(box.bottom, viewport.offsetTop + viewport.height) - REVEAL_GAP;
            const visibleTop = Math.max(box.top, viewport.offsetTop) + REVEAL_GAP;
            let by = 0;
            if (target.bottom > visibleBottom)
                by = target.bottom - visibleBottom;
            if (target.top - by < visibleTop)
                by = target.top - visibleTop;
            if (Math.abs(by) < 1)
                return;
            const still = matchMedia("(prefers-reduced-motion: reduce)").matches;
            container.scrollBy({ top: by, behavior: still ? "instant" : "smooth" });
        };
        viewport.addEventListener("resize", schedule, { signal });
        viewport.addEventListener("scroll", schedule, { signal });
        // the page behind a modal stays where it was, whatever iOS scrolls to show the field
        window.addEventListener("scroll", () => {
            if (!front() || (window.scrollX === pageX && window.scrollY === pageY))
                return;
            window.scrollTo({ left: pageX, top: pageY, behavior: "instant" });
        }, { passive: true, signal });
        // the keyboard settles over a few frames: reveal after it has, and again once it is up
        dialog.addEventListener("focusin", (event) => {
            const field = event.target;
            if (!(field instanceof Element) || !typesText(field) || !front())
                return;
            for (const ms of [100, 350]) {
                const timer = window.setTimeout(() => {
                    update();
                    reveal(field);
                }, ms);
                signal.addEventListener("abort", () => window.clearTimeout(timer), { once: true });
            }
        }, { signal });
        signal.addEventListener("abort", () => {
            cancelAnimationFrame(frame);
            dialog.style.removeProperty(KEYBOARD_INSET);
        });
        update();
    }
    /** Open drawers and what unbinds or moves each. */
    const bound = new WeakMap();
    /** Each drawer's backdrop animation, kept past its close so the next open can drop it. */
    const fades = new WeakMap();
    /**
     * @description Binds drag-to-dismiss to an open drawer until it closes.
     *
     * @param dialog - The drawer.
     */
    function bindDrawer(dialog) {
        if (bound.has(dialog))
            return;
        const controller = new AbortController();
        const { signal } = controller;
        // what the last dismissal left in place: the slid-out translate, the cleared backdrop
        fades.get(dialog)?.cancel();
        fades.delete(dialog);
        reset(dialog);
        const snaps = dialog.hasAttribute("data-drawer-snap");
        let lastScroll = 0;
        // where the drawer was when the drag caught it (mid snap-back, usually its stop)
        let base = 0;
        let height = 1;
        // the sheet's bleed past the bottom edge: the most it may be pulled up
        let lift = 0;
        // resting positions, px pushed down, the lowest snap point first; and the one it rests at
        let stops = [0];
        let active = 0;
        let fade = null;
        // undoes a dismissal still sliding out, so a new drag can catch the drawer
        let cancelClose = null;
        const measure = () => {
            lift = Math.max(0, -Number.parseFloat(getComputedStyle(dialog).marginBlockEnd) || 0);
            // the layout height: a stacked drawer's scale must not shrink it
            height = Math.max(1, dialog.offsetHeight - lift);
            stops = snaps ? readStops(dialog, height) : [0];
            active = Math.min(active, stops.length - 1);
        };
        /** Writes where the drawer rests: drawer.css turns `--_drawer-snap` into its `translate`. */
        const place = () => {
            if (!snaps)
                return;
            const largest = active === stops.length - 1;
            dialog.style.setProperty("--_drawer-snap", `${stops[active] ?? 0}px`);
            setState(dialog, "expanded", largest);
            setState(dialog, "partial", !largest);
        };
        /** Everything that moves with the drawer's progress toward closed, besides its backdrop. */
        const link = (progress, live) => {
            follow(dialog, progress, live);
            if (stack.length === 1 && stack[0] === dialog)
                indentProgress(progress, live);
        };
        /**
         * Runs the backdrop from where the drag left it to clear or back to full,
         * in `ms`. Back at full the animation is dropped; clear, it holds until the
         * drawer next opens, over whatever the closed dialog's own backdrop does.
         */
        const settle = (closing, ms) => {
            dialog.style.removeProperty("--_drawer-backdrop");
            const animation = fade;
            if (!animation)
                return;
            const done = () => {
                if (closing || fade !== animation || animation.playState !== "finished")
                    return;
                animation.cancel();
                fades.delete(dialog);
                fade = null;
            };
            const at = Number(animation.currentTime) || 0;
            const left = closing ? SCRUB_MS - at : at;
            if (ms <= 0 || left <= 0) {
                animation.playbackRate = closing ? 1 : -1;
                animation.finish();
                done();
                return;
            }
            animation.playbackRate = ((closing ? 1 : -1) * left) / ms;
            animation.play();
            animation.finished.then(done, () => { });
        };
        /** Settles the drawer on a stop; the dialog's `translate` transition carries it there. */
        const snapTo = (index) => {
            const next = Math.min(Math.max(index, 0), stops.length - 1);
            const changed = next !== active;
            active = next;
            place();
            setDragging(dialog, false);
            settle(false, maxTransitionMs(dialog));
            dialog.style.removeProperty("translate");
            link(0, false);
            if (!changed)
                return;
            dialog.dispatchEvent(new CustomEvent("zazz:drawer-snap", {
                bubbles: true,
                detail: { index: active, value: height - (stops[active] ?? 0) },
            }));
        };
        const rest = () => snapTo(active);
        /** Closes the dialog; a `cancel` listener that keeps it open sends it back to rest. */
        const close = () => {
            if (!dialog.open)
                return;
            if (typeof dialog.requestClose === "function")
                dialog.requestClose();
            else
                dialog.close();
            if (!dialog.open)
                return;
            if (stack.length === 1)
                indentPose(true);
            rest();
        };
        /**
         * Slides the drawer off the bottom edge while it is still open, then closes
         * it. The slide is the drawer's own `translate` transition, so it does not
         * depend on the engine animating a dialog's exit (WebKit removes a closed
         * dialog at once), and until it ends the drawer can be caught again.
         * Whatever is linked to the drawer leaves with it.
         */
        const slideOutAndClose = (ms) => {
            dialog.style.translate = `0 ${height + lift}px`;
            settle(true, ms);
            follow(dialog, 1, false);
            if (stack.length === 1 && stack[0] === dialog)
                indentPose(false);
            if (ms <= 0) {
                close();
                return;
            }
            const onSlid = (event) => {
                if (event.target === dialog && event.propertyName === "translate")
                    finish();
            };
            const finish = () => {
                cancelClose?.();
                close();
            };
            // the timer covers a transition that never reports its end
            const timer = window.setTimeout(finish, ms + 100);
            dialog.addEventListener("transitionend", onSlid);
            cancelClose = () => {
                window.clearTimeout(timer);
                dialog.removeEventListener("transitionend", onSlid);
                cancelClose = null;
            };
        };
        bound.set(dialog, { controller, snapTo });
        if (inDrawerMode(dialog)) {
            measure();
            place();
            stack.push(dialog);
            restack();
            trackKeyboard(dialog, signal, () => {
                measure();
                place();
            });
        }
        signal.addEventListener("abort", () => {
            cancelClose?.();
            // a drawer closed some other way mid-drag: nothing may hold the backdrop
            if (fade?.playState === "paused") {
                fade.cancel();
                fades.delete(dialog);
            }
        });
        dialog.addEventListener("scroll", () => {
            lastScroll = performance.now();
        }, { capture: true, passive: true, signal });
        // the handle steps through the snap points: a click, so a button handle works from the keyboard
        dialog.addEventListener("click", (event) => {
            if (stops.length < 2 || !(event.target instanceof Element))
                return;
            if (event.target.closest(HANDLE))
                snapTo((active + 1) % stops.length);
        }, { signal });
        window.addEventListener("resize", () => {
            if (!stack.includes(dialog))
                return;
            measure();
            place();
        }, { signal });
        trackDrag(dialog, {
            axis: "y",
            signal,
            canStart: (drag) => claims(dialog, drag, lastScroll, active < stops.length - 1),
            onStart: () => {
                // a drawer caught on its way out: what left with it comes back
                if (cancelClose && stack.length === 1)
                    indentPose(true);
                cancelClose?.();
                base = currentTranslate(dialog).y;
                measure();
                if (!fade) {
                    fade = scrubBackdrop(dialog);
                    if (fade)
                        fades.set(dialog, fade);
                }
                fade?.pause();
                setDragging(dialog, true);
            },
            onMove: ({ offset }) => {
                const travel = base + offset;
                const top = stops[stops.length - 1] ?? 0;
                const y = travel >= top ? travel : top + rubberBand(travel - top, lift + top);
                dialog.style.translate = `0 ${y}px`;
                // progress runs from the lowest stop to gone: above it nothing fades
                const lowest = stops[0] ?? 0;
                const progress = Math.min(1, Math.max(0, (y - lowest) / Math.max(1, height - lowest)));
                if (fade)
                    fade.currentTime = progress * SCRUB_MS;
                else
                    dialog.style.setProperty("--_drawer-backdrop", String(1 - progress));
                link(progress, true);
            },
            onEnd: ({ offset, velocity }) => {
                const target = pickSnap({
                    stops,
                    position: base + offset,
                    velocity,
                    active,
                    size: height,
                    closeRatio: CLOSE_RATIO,
                    flick: FLICK_VELOCITY,
                    fling: FLING_VELOCITY,
                    sequential: dialog.hasAttribute("data-drawer-snap-sequential"),
                });
                // transitions back on: the inline translate now eases to wherever it is set
                setDragging(dialog, false);
                if (target < 0)
                    slideOutAndClose(maxTransitionMs(dialog));
                else
                    snapTo(target);
            },
            onCancel: rest,
        });
    }
    /** Unbinds a drawer that closed. */
    function unbindDrawer(dialog) {
        bound.get(dialog)?.controller.abort();
        bound.delete(dialog);
        dialog.removeAttribute("data-drawer-state");
        dialog.style.removeProperty("--_drawer-depth");
        const index = stack.indexOf(dialog);
        if (index < 0)
            return;
        stack.splice(index, 1);
        restack();
    }
    /**
     * @description Moves an open drawer to one of its snap points.
     *
     * @param dialog - The drawer.
     * @param index - The snap point, counted from the smallest; clamped to the ones it has.
     */
    function snapDrawer(dialog, index) {
        bound.get(dialog)?.snapTo(index);
    }
    /**
     * @description Starts drawer binding for the page: every drawer is bound when
     * the dialog lifecycle reports it open and unbound when it closes. Idempotent.
     */
    const initDrawers = function () {
        if (initDrawers._bound)
            return;
        initDrawers._bound = true;
        document.addEventListener("zazz:dialog-open", (event) => {
            if (event.target instanceof HTMLDialogElement && event.target.matches(DRAWER)) {
                bindDrawer(event.target);
            }
        });
        document.addEventListener("zazz:dialog-close", (event) => {
            if (event.target instanceof HTMLDialogElement)
                unbindDrawer(event.target);
        });
        window.addEventListener("resize", () => {
            if (indented)
                measureIndent(indented);
        });
        // drawers that were already open when the script loaded
        for (const dialog of document.querySelectorAll(`${DRAWER}[open]`)) {
            bindDrawer(dialog);
        }
    };
    // Auto-initialize when DOM is ready (only in browser environment)
    if (typeof window !== "undefined" && typeof document !== "undefined") {
        if (document.readyState === "loading") {
            document.addEventListener("DOMContentLoaded", initDrawers);
        }
        else {
            initDrawers();
        }
    }
    export { bindDrawer, initDrawers, snapDrawer };

    Indent

    Share this page

    The page behind steps back while the drawer is open, and follows as you drag it down.

    Wrap the page in the indent element once; every drawer on the page uses it.

    <ui-drawer-indent style="--p: 6">
      <button data-ui="button" type="button" command="show-modal" commandfor="drawer-indent-1">
        Open drawer
      </button>
    </ui-drawer-indent>
    <dialog id="drawer-indent-1" data-ui="drawer" closedby="any">
      <div data-drawer-slot="handle"></div>
      <div data-drawer-slot="content">
        <header data-drawer-slot="header">
          <h2
            style="
              --font-size: var(--font-size-lg);
              --font-weight: strong;
              --font-family: var(--font-family-heading);
            "
          >
            Share this page
          </h2>
          <p style="--text: var(--color-muted-foreground)">
            The page behind steps back while the drawer is open, and follows as you drag it down.
          </p>
        </header>
        <div data-drawer-slot="body">
          <p>Wrap the page in the indent element once; every drawer on the page uses it.</p>
        </div>
      </div>
    </dialog>
    /**
     * drawer.css: Drawer ([data-ui~="drawer"] on native <dialog>; slots
     *             data-drawer-slot="handle | content | header | body | footer | close";
     *             <ui-drawer-indent> / [data-ui~="drawer-indent"], the page wrapper that
     *             scales back behind an open drawer)
     *
     * A bottom sheet: a modal dialog that rises from the bottom edge and is dragged
     * back down to dismiss. Alone (`data-ui="drawer"`) it is a drawer everywhere;
     * on a dialog (`data-ui="dialog drawer"`) it is a drawer below the sm band on a
     * touch screen and the plain dialog otherwise. `data-drawer-snap` gives it
     * resting heights; a drawer opened over another pushes that one back.
     *
     * @layer      variables, components
     * @requires   _layers.css, _variables.css, dialog.css (the native <dialog> motion, backdrop, and
     *             scroll lock in its reset layer; the surface and slots in the combined form)
     * @uses       Overrides --ui-dialog-* motion tokens: the dialog's open/close transition becomes a
     *             rise from the bottom edge, with the backdrop on the same duration and curve
     * @uses       translate — drawer.js writes the inline translate while a pointer drags the drawer
     *             (state `dragging`, transitions off); the dialog's transitions finish the release
     * @uses       Web Animations on ::backdrop — drawer.js scrubs a paused opacity animation so the
     *             backdrop fades with the drag without restyling the drawer's content on every move
     * @uses       @property (inherits: false) + `inherit` on ::backdrop — the same link in CSS, for
     *             an engine that cannot animate ::backdrop from script; where neither works the
     *             backdrop stays opaque until release
     * @uses       @media (width < 40rem) and (not (hover: hover)) — the combined form's drawer mode,
     *             the same phone test as dialog.css
     * @uses       scale, translate — the only properties the stack and the indent animate; the
     *             indent's corner radius is two corner pieces that scale up, so no border-radius or
     *             clip is animated and the page is never repainted for it
     * @uses       clip-path: inset() — a fixed rectangle while the page is indented, so the part of
     *             the page above and below the viewport stays out of the gaps the scale opens
     * @uses       :has() — the body takes the backing color while its page wrapper is indented
     * @uses       @starting-style — the corner pieces grow from nothing when they are generated
     * @uses       corner-shape — the corner pieces follow --radius-corner-shape where it is
     *             supported and are round elsewhere
     * @uses       env(safe-area-inset-top) — the indented page clears the status bar
     * @uses       env(safe-area-inset-bottom) — content clears the home indicator
     * @uses       visualViewport — drawer.js writes --_drawer-keyboard (the software
     *             keyboard's height) on the front drawer, and the sheet's bottom padding takes it,
     *             so content ends at the keyboard's top edge while the surface runs on under it
     * @uses       --_touch-min — the handle's hit area on touch screens
     * @tokens     --ui-drawer-* (@layer variables)
     */
    
    @layer variables {
      :root {
        /* surface */
        --ui-drawer-bg: var(--ui-dialog-bg);
        --ui-drawer-text: var(--ui-dialog-text);
        --ui-drawer-radius: var(--radius-xl);
        --ui-drawer-corner-shape: var(--ui-dialog-corner-shape);
        --ui-drawer-shadow: var(--shadow-lg);
    
        /* metrics: edge to edge, the layout-bleed band; cap it with a band to float a
           narrower sheet, e.g. min(var(--layout-sm), 100%) */
        --ui-drawer-w: 100%;
        --ui-drawer-max-h: calc(100dvb - var(--space-lg));
    
        /* stack: how much each drawer in front shrinks and lifts the one behind */
        --ui-drawer-stack-scale: 0.05;
        --ui-drawer-stack-lift: var(--space-sm);
        /* the page is already dimmed by the first drawer's backdrop */
        --ui-drawer-nested-backdrop-color: transparent;
    
        /* indent: how far each side of the page pulls in, how far it drops, the radius of
           its top corners, and the color behind it. Set these on :root: the body reads the
           backing color too. */
        --ui-drawer-indent-inset: calc(var(--spacing) * 3);
        --ui-drawer-indent-offset: calc(env(safe-area-inset-top, 0px) + var(--space-sm));
        --ui-drawer-indent-radius: var(--ui-drawer-radius);
        --ui-drawer-indent-bg: var(--color-background);
        --ui-drawer-indent-backing: var(--color-black);
    
        /* handle */
        --ui-drawer-handle-w: calc(var(--spacing) * 12);
        --ui-drawer-handle-h: calc(var(--spacing) * 1.25);
        --ui-drawer-handle-bg: var(--color-muted);
        --ui-drawer-handle-bg--hover: var(--color-muted-foreground);
        --ui-drawer-handle-bg--active: var(--color-muted-foreground);
        --ui-drawer-handle-bg--dragging: var(--color-foreground);
    
        /* motion: the iOS sheet curve, steep at the start so twice the default
           duration still reads as quick; 0s under reduced motion like the default */
        --ui-drawer-transition-duration: calc(var(--default-transition-duration) * 2);
        --ui-drawer-transition-timing-function: cubic-bezier(0.32, 0.72, 0, 1);
      }
    }
    
    /* Drawer mode flag, read by drawer.js; and the backdrop's drag opacity, written by it.
       Non-inheriting, so neither restyles the drawer's content. */
    @property --_drawer-mode {
      syntax: "*";
      inherits: false;
    }
    
    @property --_drawer-backdrop {
      syntax: "*";
      inherits: false;
    }
    
    /* Where a drawer with snap points rests, and how many drawers sit in front of it:
       both written by drawer.js when they change (the depth also while the front drawer
       is dragged), and non-inheriting, so neither restyles the drawer's content. */
    @property --_drawer-snap {
      syntax: "*";
      inherits: false;
    }
    
    @property --_drawer-depth {
      syntax: "*";
      inherits: false;
    }
    
    /* The software keyboard's height while the drawer is the front one, written by
       drawer.js from the visual viewport; the sheet's bottom padding takes it. */
    @property --_drawer-keyboard {
      syntax: "*";
      inherits: false;
    }
    
    /* The indent's measurements, written by drawer.js when a drawer opens, and how
       indented the page is (0 to 1): 1 from the `active` state, or the drag's own
       value while the last drawer is dragged. The corner pieces take them by explicit
       inheritance. The inset is typed so the script reads the hook in px. */
    @property --_drawer-indent-amount {
      syntax: "*";
      inherits: false;
    }
    
    @property --_drawer-indent-scale {
      syntax: "*";
      inherits: false;
    }
    
    @property --_drawer-indent-top {
      syntax: "*";
      inherits: false;
    }
    
    @property --_drawer-indent-bottom {
      syntax: "*";
      inherits: false;
    }
    
    @property --_drawer-indent-inset {
      syntax: "<length>";
      inherits: false;
      initial-value: 0px;
    }
    
    @layer ui.components {
      /* ===========================================================================
      DRAWER MODE: the declarations that make a dialog a bottom sheet. Written
      twice, because the two forms enter it under different conditions: the
      standalone form always, the combined form on a phone. Keep the two blocks
      identical apart from the --_dialog-* lines, which feed the dialog's own
      read chain in the combined form.
    
      The sheet extends --_bleed past the bottom edge (padding inside,
      an equal negative margin outside), so pulling it up against its resistance
      never opens a gap under it.
      =========================================================================== */
    
      :where([data-ui~="drawer"]:not([data-ui~="dialog"])) {
        --_drawer-mode: 1;
        --_bleed: calc(var(--spacing) * 12);
        --_handle-display: block;
        --_content-row: 2;
        --_header-select: none;
    
        --ui-dialog-transition-duration: var(--ui-drawer-transition-duration);
        --ui-dialog-transition-timing-function: var(--ui-drawer-transition-timing-function);
        --ui-dialog-backdrop-transition-duration: var(--ui-dialog-transition-duration);
        --ui-dialog-backdrop-transition-timing-function: var(--ui-drawer-transition-timing-function);
        --ui-dialog-transition-delay--end: 0ms;
        --ui-dialog-opacity--start: 1;
        --ui-dialog-scale--start: 1;
        --ui-dialog-translate--start: 0, 100%, 0;
    
        margin-block: auto calc(var(--_bleed) * -1);
        margin-inline: auto;
        /* the keyboard covers the home indicator: the larger of the two, not both */
        padding-block-end: calc(
          var(--_bleed) + max(env(safe-area-inset-bottom, 0px), var(--_drawer-keyboard, 0px))
        );
        max-inline-size: 100%;
        max-block-size: calc(var(--ui-drawer-max-h) + var(--_bleed));
        grid-template-rows: auto minmax(0, 1fr);
        border-block-end-width: 0;
        border-end-start-radius: 0;
        border-end-end-radius: 0;
        /* a stacked drawer shrinks toward its top edge, the part that stays in view */
        transform-origin: 50% 0;
      }
    
      @media (width < 40rem) and (not (hover: hover)) {
        :where([data-ui~="dialog"][data-ui~="drawer"]) {
          --_drawer-mode: 1;
          --_bleed: calc(var(--spacing) * 12);
          --_handle-display: block;
          --_content-row: 2;
          --_header-select: none;
    
          --_dialog-w: var(--ui-drawer-w);
          --_dialog-radius: var(--ui-drawer-radius);
          --_dialog-shadow: var(--ui-drawer-shadow);
    
          --ui-dialog-transition-duration: var(--ui-drawer-transition-duration);
          --ui-dialog-transition-timing-function: var(--ui-drawer-transition-timing-function);
          --ui-dialog-backdrop-transition-duration: var(--ui-dialog-transition-duration);
          --ui-dialog-backdrop-transition-timing-function: var(--ui-drawer-transition-timing-function);
          --ui-dialog-transition-delay--end: 0ms;
          --ui-dialog-opacity--start: 1;
          --ui-dialog-scale--start: 1;
          --ui-dialog-translate--start: 0, 100%, 0;
    
          margin-block: auto calc(var(--_bleed) * -1);
          margin-inline: auto;
          /* the keyboard covers the home indicator: the larger of the two, not both */
          padding-block-end: calc(
            var(--_bleed) + max(env(safe-area-inset-bottom, 0px), var(--_drawer-keyboard, 0px))
          );
          max-inline-size: 100%;
          max-block-size: calc(var(--ui-drawer-max-h) + var(--_bleed));
          grid-template-rows: auto minmax(0, 1fr);
          border-block-end-width: 0;
          border-end-start-radius: 0;
          border-end-end-radius: 0;
          transform-origin: 50% 0;
        }
      }
    
      /* ===========================================================================
      STANDALONE SURFACE: without the dialog identity the drawer paints itself.
      The combined form takes all of this from dialog.css.
      =========================================================================== */
    
      :where([data-ui~="drawer"]:not([data-ui~="dialog"])) {
        inline-size: var(--ui-drawer-w);
        block-size: fit-content;
        background-color: var(--_bg-resolved, var(--ui-drawer-bg));
        color: var(--_text-resolved, var(--ui-drawer-text));
        box-shadow: var(--_shadow-resolved, var(--ui-drawer-shadow));
        /* the top corners only: the bottom edge sits past the viewport */
        border-start-start-radius: var(--ui-drawer-radius);
        border-start-end-radius: var(--ui-drawer-radius);
        corner-shape: var(--_corner-shape-resolved, var(--ui-drawer-corner-shape));
        font-size: var(--font-size-md);
        overflow: hidden;
        overscroll-behavior: contain;
      }
    
      :where([data-ui~="drawer"]:not([data-ui~="dialog"])[open]) {
        display: grid;
        min-block-size: 0;
      }
    
      /* ===========================================================================
      SNAP POINTS: a drawer with data-drawer-snap is as tall as a drawer may be and
      rests pushed down by --_drawer-snap, which drawer.js writes when the stop
      changes. The height is set per form, like drawer mode itself.
      =========================================================================== */
    
      :where([data-ui~="drawer"]:not([data-ui~="dialog"])[data-drawer-snap]) {
        block-size: calc(var(--ui-drawer-max-h) + var(--_bleed));
      }
    
      @media (width < 40rem) and (not (hover: hover)) {
        :where([data-ui~="dialog"][data-ui~="drawer"][data-drawer-snap]) {
          --_dialog-h: calc(var(--ui-drawer-max-h) + var(--_bleed));
        }
      }
    
      :where([data-ui~="drawer"][data-drawer-snap]) {
        translate: 0 var(--_drawer-snap, 0px);
      }
    
      /* ===========================================================================
      STACK: a drawer with others open in front of it shrinks toward its top edge
      and lifts, once per drawer in front. drawer.js writes the count, and while
      the front drawer is dragged a fraction of it (state `following`, transitions
      off). A drawer opened over another dims nothing more.
      =========================================================================== */
    
      :where([data-ui~="drawer"][data-drawer-state~="stacked"]) {
        scale: calc(1 - var(--_drawer-depth, 0) * var(--ui-drawer-stack-scale));
        translate: 0
          calc(var(--_drawer-snap, 0px) - var(--_drawer-depth, 0) * var(--ui-drawer-stack-lift));
      }
    
      :where([data-ui~="drawer"][data-drawer-state~="following"]) {
        transition: none;
      }
    
      :where([data-ui~="drawer"][data-drawer-state~="nested"])::backdrop {
        background-color: var(--ui-drawer-nested-backdrop-color);
        backdrop-filter: none;
      }
    
      /* Each slot owns a row, as in the dialog: the body is the part that scrolls */
      :where([data-ui~="drawer"]) [data-drawer-slot~="content"] {
        display: grid;
        grid-template-rows: auto minmax(0, 1fr) auto;
        position: relative;
        min-block-size: 0;
        max-block-size: 100%;
      }
    
      :where([data-ui~="drawer"]) [data-drawer-slot~="header"] {
        grid-row: 1;
        display: flex;
        flex-direction: column;
        padding-inline: var(--space-sm);
        padding-block-start: var(--space-sm);
      }
    
      :where([data-ui~="drawer"]) [data-drawer-slot~="body"] {
        grid-row: 2;
        display: grid;
        align-content: start;
        padding-inline: var(--space-sm);
        padding-block: var(--space-md);
        min-block-size: 0;
        overflow-y: auto;
        overscroll-behavior: contain;
      }
    
      :where([data-ui~="drawer"]) [data-drawer-slot~="footer"] {
        grid-row: 3;
        display: flex;
        justify-content: flex-end;
        gap: var(--space-xs);
        padding: var(--space-sm);
        border-block-start: 1px solid var(--color-border);
      }
    
      :where([data-ui~="drawer"]) [data-drawer-slot~="close"] {
        position: absolute;
        inset-block-start: var(--space-xs);
        inset-inline-end: var(--space-xs);
        z-index: 50;
      }
    
      /* ===========================================================================
      PARTS IN DRAWER MODE: the handle shows and takes the first row; the content
      slot (the drawer's own or the dialog's) takes the flexible second row, with
      or without a handle before it. Both read the mode privates set above, so
      neither rule is repeated per form.
      =========================================================================== */
    
      :where([data-ui~="drawer"]) :where([data-drawer-slot~="content"], [data-dialog-slot~="content"]) {
        grid-row: var(--_content-row, auto);
      }
    
      /* The header is where a mouse grabs the drawer: a press on its text drags
         instead of selecting. Body text stays selectable. */
      :where([data-ui~="drawer"]) :where([data-drawer-slot~="header"], [data-dialog-slot~="header"]) {
        -webkit-user-select: var(--_header-select, auto);
        user-select: var(--_header-select, auto);
      }
    
      /* A pill, with a hit area that reaches the touch-target height. It always
         drags, even over a scrolled body, so it opts out of native panning. */
      :where([data-ui~="drawer"]) [data-drawer-slot~="handle"] {
        display: var(--_handle-display, none);
        grid-row: 1;
        justify-self: center;
        position: relative;
        inline-size: var(--ui-drawer-handle-w);
        block-size: var(--ui-drawer-handle-h);
        margin-block: calc(var(--spacing) * 2.5) calc(var(--spacing) * 1);
        border-radius: var(--radius-full);
        background-color: var(--ui-drawer-handle-bg);
        cursor: grab;
        touch-action: none;
        -webkit-user-select: none;
        user-select: none;
        transition: background-color var(--default-transition-duration)
          var(--default-transition-timing-function);
      }
    
      :where([data-ui~="drawer"]) [data-drawer-slot~="handle"]:hover {
        background-color: var(--ui-drawer-handle-bg--hover);
      }
    
      :where([data-ui~="drawer"]) [data-drawer-slot~="handle"]:active {
        background-color: var(--ui-drawer-handle-bg--active);
        cursor: grabbing;
      }
    
      :where([data-ui~="drawer"]) [data-drawer-slot~="handle"]::before {
        content: "";
        position: absolute;
        inset-inline: calc(var(--ui-drawer-handle-w) * -1);
        inset-block: min(calc(var(--spacing) * -2), calc((100% - var(--_touch-min, 0px)) / 2));
      }
    
      /* Below its largest snap point a drawer's content does not scroll: the drawer
         moves first. After the slot rules, which it has to beat. */
      :where([data-ui~="drawer"][data-drawer-state~="partial"])
        :is([data-drawer-slot~="body"], [data-dialog-slot~="body"]) {
        overflow-y: hidden;
      }
    
      /* ===========================================================================
      DRAG: while a pointer drags the drawer, drawer.js writes its inline
      translate and nothing may ease it: the drawer is the pointer. The backdrop
      fades with the drag: drawer.js scrubs an animation on it, or, where
      ::backdrop cannot be animated from script, writes --_drawer-backdrop, which
      the backdrop takes from the dialog by explicit inheritance. On release the state drops and the dialog's
      own transitions finish the motion, to closed or back to rest.
      =========================================================================== */
    
      :where([data-ui~="drawer"][data-drawer-state~="dragging"]) [data-drawer-slot~="handle"] {
        background-color: var(--ui-drawer-handle-bg--dragging);
      }
    
      :where([data-ui~="drawer"][data-drawer-state~="dragging"]) {
        transition: none;
        cursor: grabbing;
        /* a mouse drag that began beside text must not start selecting it */
        -webkit-user-select: none;
        user-select: none;
      }
    
      :where([data-ui~="drawer"][data-drawer-state~="dragging"])::backdrop {
        --_drawer-backdrop: inherit;
        opacity: var(--_drawer-backdrop, 1);
        transition: none;
      }
    
      /* ===========================================================================
      INDENT: the page wrapper scales back behind an open drawer. drawer.js sets the
      state (`on` while the machinery is engaged, `active` while a drawer is open,
      `dragging` while the last drawer is dragged) and measures, once, the scale and
      where the viewport sits inside the wrapper.
    
      Only scale and translate animate. The wrapper is clipped to the viewport's
      rectangle, a fixed clip, so the page above and below it stays out of the gaps;
      the body paints the backing color there. The rounded top corners are two
      corner pieces that grow from the corners, not a border-radius: nothing is
      repainted while the page moves.
    
      While `on` the wrapper is transformed, so it is the containing block of its
      fixed and absolute descendants.
      =========================================================================== */
    
      :where(ui-drawer-indent, [data-ui~="drawer-indent"]) {
        --_drawer-indent-inset: var(--ui-drawer-indent-inset);
        display: block;
        background-color: var(--ui-drawer-indent-bg);
        transition:
          scale var(--ui-drawer-transition-duration) var(--ui-drawer-transition-timing-function),
          translate var(--ui-drawer-transition-duration) var(--ui-drawer-transition-timing-function);
      }
    
      :where(ui-drawer-indent, [data-ui~="drawer-indent"])[data-drawer-indent-state~="on"] {
        position: relative;
        transform-origin: 50% var(--_drawer-indent-top, 0px);
        scale: calc(1 - (1 - var(--_drawer-indent-scale, 1)) * var(--_drawer-indent-amount, 0));
        translate: 0 calc(var(--ui-drawer-indent-offset) * var(--_drawer-indent-amount, 0));
        clip-path: inset(var(--_drawer-indent-top, 0px) 0 var(--_drawer-indent-bottom, 0px) 0);
        will-change: scale, translate;
      }
    
      :where(ui-drawer-indent, [data-ui~="drawer-indent"])[data-drawer-indent-state~="active"] {
        --_drawer-indent-amount: 1;
      }
    
      /* The backing shows in the gaps around the indented page. Important, because a
         page's own <body style="--bg: …"> is a utility and would otherwise win; it holds
         only while the wrapper is `on`. */
      :where(body):has(
        :is(ui-drawer-indent, [data-ui~="drawer-indent"])[data-drawer-indent-state~="on"]
      ) {
        background-color: var(--ui-drawer-indent-backing) !important;
      }
    
      /* A corner piece: a square the size of the radius whose outer corner is rounded
         and whose spread shadow, cut off at the square, paints only the notch outside
         the curve. Scaling it from that corner is the radius growing. */
      :where(ui-drawer-indent, [data-ui~="drawer-indent"])[data-drawer-indent-state~="on"]::before,
      :where(ui-drawer-indent, [data-ui~="drawer-indent"])[data-drawer-indent-state~="on"]::after {
        --_drawer-indent-amount: inherit;
        --_drawer-indent-top: inherit;
        content: "";
        position: absolute;
        z-index: 2147483647;
        inset-block-start: var(--_drawer-indent-top, 0px);
        inline-size: var(--ui-drawer-indent-radius);
        block-size: var(--ui-drawer-indent-radius);
        box-shadow: 0 0 0 var(--ui-drawer-indent-radius) var(--ui-drawer-indent-backing);
        clip-path: inset(0);
        corner-shape: var(--radius-corner-shape);
        scale: var(--_drawer-indent-amount, 0);
        pointer-events: none;
        transition: scale var(--ui-drawer-transition-duration)
          var(--ui-drawer-transition-timing-function);
    
        @starting-style {
          scale: 0;
        }
      }
    
      :where(ui-drawer-indent, [data-ui~="drawer-indent"])[data-drawer-indent-state~="on"]::before {
        left: 0;
        border-top-left-radius: 100%;
        transform-origin: 0 0;
      }
    
      :where(ui-drawer-indent, [data-ui~="drawer-indent"])[data-drawer-indent-state~="on"]::after {
        right: 0;
        border-top-right-radius: 100%;
        transform-origin: 100% 0;
      }
    
      :where(ui-drawer-indent, [data-ui~="drawer-indent"])[data-drawer-indent-state~="dragging"],
      :where(
          ui-drawer-indent,
          [data-ui~="drawer-indent"]
        )[data-drawer-indent-state~="dragging"]::before,
      :where(
          ui-drawer-indent,
          [data-ui~="drawer-indent"]
        )[data-drawer-indent-state~="dragging"]::after {
        transition: none;
      }
    }
    // primitives/drawer/drawer.js
    "use strict";
    /**
     * @fileoverview Drawer: drag-to-dismiss for `<dialog data-ui="drawer">` bottom sheets.
     * @description A drawer is a native modal `<dialog>`, opened and closed like
     * any other (`command="show-modal"`, `command="close"`, Esc, the backdrop with
     * `closedby="any"`). This script adds the gesture: drag the drawer down and
     * let go to dismiss it.
     *
     * - `data-ui="drawer"` is a drawer on every device.
     * - `data-ui="dialog drawer"` is a drawer below the `sm` band on a touch
     *   screen, and a plain dialog (no dragging) everywhere else.
     *
     * While the pointer is down the drawer follows it 1:1 and the backdrop fades
     * with it. Letting go past a quarter of the drawer's height, or with a quick
     * downward flick, slides it off the bottom edge and then closes it through
     * `requestClose()`, so `cancel` and `close` fire as they do for Esc; anything
     * less returns it to rest. Until it has slid out it can be caught again. Pulling it up
     * past its resting place meets resistance.
     *
     * A drag starts anywhere on the drawer except on form fields, selected text,
     * and anything inside `[data-ui-no-drag]`. Inside scrolling content it starts
     * only once that content is scrolled to the top and the pointer moves down,
     * so the body scrolls first and the drawer follows; the handle
     * (`data-drawer-slot="handle"`) always drags. There is no custom element and
     * nothing to initialize: the script binds a drawer when it opens.
     *
     * **Snap points.** `data-drawer-snap="148px 0.5 1"` gives the drawer resting
     * heights, smallest first: a number up to 1 is a share of the drawer's full
     * height, a `px` or `rem` length is a visible height. It opens at the first.
     * Letting go settles on the nearest; a flick moves one stop in its direction,
     * a very fast one goes all the way (or one stop, with
     * `data-drawer-snap-sequential`), and from the lowest stop a flick or enough
     * travel downward closes the drawer. Below the largest stop the drawer takes
     * every vertical drag and its content does not scroll. A click on the handle
     * steps to the next stop; make the handle a `<button>` to give the keyboard
     * the same. Each change fires `zazz:drawer-snap` (`detail.index`,
     * `detail.value` in px), `data-drawer-state` carries `expanded` at the largest
     * stop, and `snapDrawer(dialog, index)` moves it from script.
     *
     * **The software keyboard.** A phone lays a drawer out against the full
     * screen, which the keyboard does not shrink. While a field in the front
     * drawer has the keyboard up, the drawer's content ends at the keyboard's top
     * edge (its surface runs on underneath), the focused field scrolls into what
     * is still visible, and the page behind stays where it was. Nothing to author.
     *
     * **Stacked drawers.** A drawer opened over another scales the one behind back
     * and lifts it, and that one follows as the front drawer is dragged. Nothing
     * to author: the script counts the open drawers.
     *
     * **Indent.** Wrap the page in `<ui-drawer-indent>` (or put
     * `data-ui="drawer-indent"` on its wrapper) and it scales back behind any open
     * drawer, with rounded top corners, and follows the drag of the last one. Only
     * transforms animate. While indented the wrapper is transformed, so a
     * `position: fixed` element inside it moves with the page; `position: sticky`
     * is unaffected.
     *
     * @example
     * <button data-ui="button" command="show-modal" commandfor="filters">Filters</button>
     * <dialog id="filters" data-ui="drawer" closedby="any">
     *   <div data-drawer-slot="handle"></div>
     *   <div data-drawer-slot="content">
     *     <header data-drawer-slot="header">…</header>
     *     <div data-drawer-slot="body">…</div>
     *   </div>
     * </dialog>
     */
    import { currentTranslate, maxTransitionMs, pickSnap, rubberBand, trackDrag, } from "../../base/gesture.js";
    // --- Tuning ---
    /** Share of the drawer's visible height, at its lowest stop, that dismisses on its own. */
    const CLOSE_RATIO = 0.25;
    /** Speed that moves the drawer one stop, or dismisses it from the lowest, in px/ms. */
    const FLICK_VELOCITY = 0.4;
    /** Speed that skips every stop: all the way open, or closed, in px/ms. */
    const FLING_VELOCITY = 2;
    /**
     * After inner content scrolls, how long before the drawer may be dragged, in
     * ms. A fast scroll that reaches the top would otherwise carry straight on
     * into dragging the drawer away.
     */
    const SCROLL_GUARD_MS = 100;
    /** Length of the backdrop's scrub animation: its timeline is drag progress, not time. */
    const SCRUB_MS = 1000;
    const DRAWER = 'dialog[data-ui~="drawer"]';
    const HANDLE = '[data-drawer-slot~="handle"]';
    const INDENT = 'ui-drawer-indent, [data-ui~="drawer-indent"]';
    const INDENT_STATE = "data-drawer-indent-state";
    // --- Helpers ---
    /** Adds or removes one token of a space-separated state attribute; an empty attribute is removed. */
    function setToken(element, attribute, token, on) {
        const tokens = new Set((element.getAttribute(attribute) ?? "").split(/\s+/).filter(Boolean));
        if (tokens.has(token) === on)
            return;
        if (on)
            tokens.add(token);
        else
            tokens.delete(token);
        if (tokens.size)
            element.setAttribute(attribute, [...tokens].join(" "));
        else
            element.removeAttribute(attribute);
    }
    /** Adds or removes a token of a drawer's `data-drawer-state`. */
    function setState(dialog, token, on) {
        setToken(dialog, "data-drawer-state", token, on);
    }
    /** Adds or removes the `dragging` token of a drawer's `data-drawer-state`. */
    function setDragging(dialog, on) {
        setState(dialog, "dragging", on);
    }
    /** Clears everything a drag wrote on the drawer. */
    function reset(dialog) {
        setDragging(dialog, false);
        dialog.style.removeProperty("translate");
        dialog.style.removeProperty("--_drawer-backdrop");
    }
    /**
     * @description Reads a drawer's snap points as resting positions: px the
     * drawer is pushed down at each, the smallest visible height first.
     *
     * @param dialog - The drawer.
     * @param height - The drawer's full visible height in px.
     * @returns The positions, descending; `[0]` without usable snap points.
     * @private
     */
    function readStops(dialog, height) {
        const raw = dialog.getAttribute("data-drawer-snap")?.trim();
        if (!raw)
            return [0];
        const rem = Number.parseFloat(getComputedStyle(document.documentElement).fontSize) || 16;
        const positions = new Set();
        for (const token of raw.split(/\s+/)) {
            const value = Number.parseFloat(token);
            if (!Number.isFinite(value) || value <= 0)
                continue;
            let visible = value * height;
            if (token.endsWith("rem"))
                visible = value * rem;
            else if (token.endsWith("px") || value > 1)
                visible = value;
            positions.add(Math.round(height - Math.min(height, Math.max(1, visible))));
        }
        return positions.size ? [...positions].sort((a, b) => b - a) : [0];
    }
    /**
     * @description Starts a paused opacity animation on the drawer's backdrop, to
     * be scrubbed with the drag. An animation, not a style write: it reaches the
     * pseudo-element without restyling the drawer's content, in engines that do
     * not re-resolve `::backdrop` when a non-inherited property changes on its
     * dialog (WebKit).
     *
     * @param dialog - The drawer.
     * @returns The animation, or null where `::backdrop` cannot be animated; the
     * caller then writes `--_drawer-backdrop`, which drawer.css reads.
     * @private
     */
    function scrubBackdrop(dialog) {
        try {
            const animation = dialog.animate([{ opacity: 1 }, { opacity: 0 }], {
                pseudoElement: "::backdrop",
                duration: SCRUB_MS,
                fill: "both",
            });
            animation.pause();
            return animation;
        }
        catch {
            return null;
        }
    }
    /** Whether drawer.css has the dialog in drawer mode right now. */
    function inDrawerMode(dialog) {
        return getComputedStyle(dialog).getPropertyValue("--_drawer-mode").trim() === "1";
    }
    /** Whether an element scrolls its content on the block axis. */
    function scrolls(element) {
        if (element.scrollHeight <= element.clientHeight)
            return false;
        const overflow = getComputedStyle(element).overflowY;
        return overflow === "auto" || overflow === "scroll";
    }
    /**
     * @description Whether a press may drag the drawer, given what it landed on
     * and which way it is moving.
     *
     * @param dialog - The drawer.
     * @param drag - The drag about to start; `offset` carries its direction.
     * @param lastScroll - When content inside the drawer last scrolled.
     * @param partial - Whether the drawer rests below its largest snap point.
     * @returns Whether the drawer takes the gesture.
     * @private
     */
    function claims(dialog, drag, lastScroll, partial) {
        if (!inDrawerMode(dialog))
            return false;
        // a press on the backdrop targets the dialog, outside its box
        const box = dialog.getBoundingClientRect();
        if (drag.startY < box.top || drag.startX < box.left || drag.startX > box.right)
            return false;
        if (drag.target.closest(HANDLE))
            return true;
        // below its largest stop the drawer moves before anything inside it scrolls
        if (partial)
            return true;
        // scrolling content goes first: it must be at the top, and the pull downward
        const down = drag.offset > 0;
        for (let node = drag.target; node && dialog.contains(node); node = node.parentElement) {
            if (scrolls(node) && (node.scrollTop > 0 || !down))
                return false;
        }
        return performance.now() - lastScroll >= SCROLL_GUARD_MS;
    }
    // --- Stack ---
    /** The open drawers in drawer mode, the front one last. */
    const stack = [];
    /**
     * @description Writes each open drawer's place in the stack: how many drawers
     * sit in front of it (`--_drawer-depth`, `stacked`) and whether it opened over
     * another (`nested`). Runs when a drawer opens or closes, never per frame.
     * @private
     */
    function restack() {
        // a drawer removed from the page while open never reports its close
        for (let index = stack.length - 1; index >= 0; index--) {
            const dialog = stack[index];
            if (!dialog.isConnected || !dialog.open)
                stack.splice(index, 1);
        }
        stack.forEach((dialog, index) => {
            const depth = stack.length - 1 - index;
            setState(dialog, "following", false);
            setState(dialog, "stacked", depth > 0);
            setState(dialog, "nested", index > 0);
            if (depth > 0)
                dialog.style.setProperty("--_drawer-depth", String(depth));
            else
                dialog.style.removeProperty("--_drawer-depth");
        });
        indentPose(stack.length > 0);
    }
    /**
     * @description Moves the drawers behind `front` with its drag: at progress 1
     * each sits where it will once `front` is gone. The depth is a non-inheriting
     * property, so the write restyles those drawers and not their content.
     *
     * @param front - The drawer being dragged or released.
     * @param progress - How far `front` is toward closed, 0 to 1.
     * @param live - Whether a pointer is driving it (transitions off).
     * @private
     */
    function follow(front, progress, live) {
        const index = stack.indexOf(front);
        for (let behind = 0; behind < index; behind++) {
            const dialog = stack[behind];
            dialog.style.setProperty("--_drawer-depth", String(index - behind - progress));
            setState(dialog, "following", live);
        }
    }
    // --- Indent ---
    /** The page wrapper that is indented right now, and what ends its return to rest. */
    let indented = null;
    let cancelOutdent = null;
    /**
     * @description Measures what the indent needs, once per activation and on
     * resize: the scale that pulls each side in by the inset hook, and where the
     * viewport sits inside the wrapper (the transform's origin, the clip, and the
     * corner pieces all hang off its top edge).
     * @private
     */
    function measureIndent(wrapper) {
        const box = wrapper.getBoundingClientRect();
        const width = wrapper.offsetWidth || 1;
        const inset = Number.parseFloat(getComputedStyle(wrapper).getPropertyValue("--_drawer-indent-inset")) || 0;
        const top = Math.max(0, -box.top);
        const bottom = Math.max(0, wrapper.offsetHeight - top - window.innerHeight);
        wrapper.style.setProperty("--_drawer-indent-scale", String(Math.max(0, 1 - (inset * 2) / width)));
        wrapper.style.setProperty("--_drawer-indent-top", `${top}px`);
        wrapper.style.setProperty("--_drawer-indent-bottom", `${bottom}px`);
    }
    /**
     * @description Indents the page wrapper or sends it back to rest. The pose is
     * a state token and the motion a CSS transition; the `on` token (clip,
     * corners, backing) outlasts the pose until the return has finished.
     *
     * @param active - Whether a drawer is open.
     * @private
     */
    function indentPose(active) {
        // a wrapper that left the page takes its state with it
        if (indented && !indented.isConnected) {
            cancelOutdent?.();
            indented = null;
        }
        const wrapper = indented ?? document.querySelector(INDENT);
        if (!wrapper)
            return;
        if (active) {
            cancelOutdent?.();
            if (indented !== wrapper) {
                measureIndent(wrapper);
                indented = wrapper;
            }
            setToken(wrapper, INDENT_STATE, "on", true);
            setToken(wrapper, INDENT_STATE, "active", true);
            return;
        }
        if (!indented || cancelOutdent)
            return;
        setToken(wrapper, INDENT_STATE, "dragging", false);
        wrapper.style.removeProperty("--_drawer-indent-amount");
        setToken(wrapper, INDENT_STATE, "active", false);
        const off = () => {
            cancelOutdent?.();
            wrapper.removeAttribute(INDENT_STATE);
            for (const name of ["scale", "top", "bottom"]) {
                wrapper.style.removeProperty(`--_drawer-indent-${name}`);
            }
            indented = null;
        };
        const ms = maxTransitionMs(wrapper);
        if (ms <= 0) {
            off();
            return;
        }
        const onReturned = (event) => {
            if (event.target === wrapper && event.propertyName === "scale")
                off();
        };
        const timer = window.setTimeout(off, ms + 100);
        wrapper.addEventListener("transitionend", onReturned);
        cancelOutdent = () => {
            window.clearTimeout(timer);
            wrapper.removeEventListener("transitionend", onReturned);
            cancelOutdent = null;
        };
    }
    /**
     * @description Links the indent to the last open drawer's drag.
     *
     * @param progress - How far the drawer is toward closed, 0 to 1.
     * @param live - Whether a pointer is driving it (transitions off).
     * @private
     */
    function indentProgress(progress, live) {
        if (!indented)
            return;
        setToken(indented, INDENT_STATE, "dragging", live);
        if (live)
            indented.style.setProperty("--_drawer-indent-amount", String(1 - progress));
        else
            indented.style.removeProperty("--_drawer-indent-amount");
    }
    // --- Keyboard ---
    /** The keyboard's height on the front drawer, which drawer.css adds to its bottom padding. */
    const KEYBOARD_INSET = "--_drawer-keyboard";
    /** Space kept between a revealed field and the keyboard's top edge, in px. */
    const REVEAL_GAP = 16;
    /** Inputs that open a picker or nothing rather than the software keyboard. */
    const NO_KEYBOARD = /^(?:button|checkbox|color|file|hidden|image|radio|range|reset|submit|date|datetime-local|month|time|week)$/;
    /** Whether focus on this element opens the software keyboard. */
    function typesText(element) {
        if (element instanceof HTMLTextAreaElement)
            return !element.readOnly;
        if (element instanceof HTMLInputElement)
            return !element.readOnly && !NO_KEYBOARD.test(element.type);
        return element instanceof HTMLElement && element.isContentEditable;
    }
    /**
     * @description How much of the layout viewport the software keyboard covers,
     * from the bottom: the part below the visual viewport. 0 while the page is
     * pinch-zoomed, when the visual viewport is smaller for another reason.
     * @private
     */
    function keyboardInset() {
        const viewport = window.visualViewport;
        if (!viewport || Math.abs(viewport.scale - 1) > 0.01)
            return 0;
        const bottom = Math.max(0, viewport.offsetTop) + viewport.height;
        return Math.max(0, Math.round(window.innerHeight - Math.min(window.innerHeight, bottom)));
    }
    /**
     * @description Keeps an open drawer usable with the software keyboard up.
     * iOS lays out the top layer against the layout viewport, which the keyboard
     * does not shrink, and scrolls the page behind a modal to reveal a focused
     * field. While the drawer is the front one this writes the keyboard's height
     * to `--_drawer-keyboard` (drawer.css pads the sheet by it, so its
     * content ends at the keyboard's top edge), holds the page at its scroll
     * position, and scrolls a focused field into the part of its scrolling slot
     * that is still visible.
     *
     * @param dialog - The drawer.
     * @param signal - Aborts when the drawer closes.
     * @param onChange - Runs after the inset changes, once the new padding is in place.
     * @private
     */
    function trackKeyboard(dialog, signal, onChange) {
        const viewport = window.visualViewport;
        if (!viewport)
            return;
        const front = () => stack[stack.length - 1] === dialog;
        const pageX = window.scrollX;
        const pageY = window.scrollY;
        let frame = 0;
        let current = 0;
        const update = () => {
            frame = 0;
            const inset = front() ? keyboardInset() : 0;
            if (inset === current)
                return;
            current = inset;
            if (inset > 0)
                dialog.style.setProperty(KEYBOARD_INSET, `${inset}px`);
            else
                dialog.style.removeProperty(KEYBOARD_INSET);
            onChange();
        };
        const schedule = () => {
            if (!frame)
                frame = requestAnimationFrame(update);
        };
        /** Scrolls the field's scrolling slot so the field sits above the keyboard and below the slot's top. */
        const reveal = (field) => {
            if (!dialog.contains(field) || document.activeElement !== field)
                return;
            let container = field.parentElement;
            while (container && dialog.contains(container) && !scrolls(container)) {
                container = container.parentElement;
            }
            if (!container || !dialog.contains(container))
                return;
            const box = container.getBoundingClientRect();
            const target = field.getBoundingClientRect();
            const visibleBottom = Math.min(box.bottom, viewport.offsetTop + viewport.height) - REVEAL_GAP;
            const visibleTop = Math.max(box.top, viewport.offsetTop) + REVEAL_GAP;
            let by = 0;
            if (target.bottom > visibleBottom)
                by = target.bottom - visibleBottom;
            if (target.top - by < visibleTop)
                by = target.top - visibleTop;
            if (Math.abs(by) < 1)
                return;
            const still = matchMedia("(prefers-reduced-motion: reduce)").matches;
            container.scrollBy({ top: by, behavior: still ? "instant" : "smooth" });
        };
        viewport.addEventListener("resize", schedule, { signal });
        viewport.addEventListener("scroll", schedule, { signal });
        // the page behind a modal stays where it was, whatever iOS scrolls to show the field
        window.addEventListener("scroll", () => {
            if (!front() || (window.scrollX === pageX && window.scrollY === pageY))
                return;
            window.scrollTo({ left: pageX, top: pageY, behavior: "instant" });
        }, { passive: true, signal });
        // the keyboard settles over a few frames: reveal after it has, and again once it is up
        dialog.addEventListener("focusin", (event) => {
            const field = event.target;
            if (!(field instanceof Element) || !typesText(field) || !front())
                return;
            for (const ms of [100, 350]) {
                const timer = window.setTimeout(() => {
                    update();
                    reveal(field);
                }, ms);
                signal.addEventListener("abort", () => window.clearTimeout(timer), { once: true });
            }
        }, { signal });
        signal.addEventListener("abort", () => {
            cancelAnimationFrame(frame);
            dialog.style.removeProperty(KEYBOARD_INSET);
        });
        update();
    }
    /** Open drawers and what unbinds or moves each. */
    const bound = new WeakMap();
    /** Each drawer's backdrop animation, kept past its close so the next open can drop it. */
    const fades = new WeakMap();
    /**
     * @description Binds drag-to-dismiss to an open drawer until it closes.
     *
     * @param dialog - The drawer.
     */
    function bindDrawer(dialog) {
        if (bound.has(dialog))
            return;
        const controller = new AbortController();
        const { signal } = controller;
        // what the last dismissal left in place: the slid-out translate, the cleared backdrop
        fades.get(dialog)?.cancel();
        fades.delete(dialog);
        reset(dialog);
        const snaps = dialog.hasAttribute("data-drawer-snap");
        let lastScroll = 0;
        // where the drawer was when the drag caught it (mid snap-back, usually its stop)
        let base = 0;
        let height = 1;
        // the sheet's bleed past the bottom edge: the most it may be pulled up
        let lift = 0;
        // resting positions, px pushed down, the lowest snap point first; and the one it rests at
        let stops = [0];
        let active = 0;
        let fade = null;
        // undoes a dismissal still sliding out, so a new drag can catch the drawer
        let cancelClose = null;
        const measure = () => {
            lift = Math.max(0, -Number.parseFloat(getComputedStyle(dialog).marginBlockEnd) || 0);
            // the layout height: a stacked drawer's scale must not shrink it
            height = Math.max(1, dialog.offsetHeight - lift);
            stops = snaps ? readStops(dialog, height) : [0];
            active = Math.min(active, stops.length - 1);
        };
        /** Writes where the drawer rests: drawer.css turns `--_drawer-snap` into its `translate`. */
        const place = () => {
            if (!snaps)
                return;
            const largest = active === stops.length - 1;
            dialog.style.setProperty("--_drawer-snap", `${stops[active] ?? 0}px`);
            setState(dialog, "expanded", largest);
            setState(dialog, "partial", !largest);
        };
        /** Everything that moves with the drawer's progress toward closed, besides its backdrop. */
        const link = (progress, live) => {
            follow(dialog, progress, live);
            if (stack.length === 1 && stack[0] === dialog)
                indentProgress(progress, live);
        };
        /**
         * Runs the backdrop from where the drag left it to clear or back to full,
         * in `ms`. Back at full the animation is dropped; clear, it holds until the
         * drawer next opens, over whatever the closed dialog's own backdrop does.
         */
        const settle = (closing, ms) => {
            dialog.style.removeProperty("--_drawer-backdrop");
            const animation = fade;
            if (!animation)
                return;
            const done = () => {
                if (closing || fade !== animation || animation.playState !== "finished")
                    return;
                animation.cancel();
                fades.delete(dialog);
                fade = null;
            };
            const at = Number(animation.currentTime) || 0;
            const left = closing ? SCRUB_MS - at : at;
            if (ms <= 0 || left <= 0) {
                animation.playbackRate = closing ? 1 : -1;
                animation.finish();
                done();
                return;
            }
            animation.playbackRate = ((closing ? 1 : -1) * left) / ms;
            animation.play();
            animation.finished.then(done, () => { });
        };
        /** Settles the drawer on a stop; the dialog's `translate` transition carries it there. */
        const snapTo = (index) => {
            const next = Math.min(Math.max(index, 0), stops.length - 1);
            const changed = next !== active;
            active = next;
            place();
            setDragging(dialog, false);
            settle(false, maxTransitionMs(dialog));
            dialog.style.removeProperty("translate");
            link(0, false);
            if (!changed)
                return;
            dialog.dispatchEvent(new CustomEvent("zazz:drawer-snap", {
                bubbles: true,
                detail: { index: active, value: height - (stops[active] ?? 0) },
            }));
        };
        const rest = () => snapTo(active);
        /** Closes the dialog; a `cancel` listener that keeps it open sends it back to rest. */
        const close = () => {
            if (!dialog.open)
                return;
            if (typeof dialog.requestClose === "function")
                dialog.requestClose();
            else
                dialog.close();
            if (!dialog.open)
                return;
            if (stack.length === 1)
                indentPose(true);
            rest();
        };
        /**
         * Slides the drawer off the bottom edge while it is still open, then closes
         * it. The slide is the drawer's own `translate` transition, so it does not
         * depend on the engine animating a dialog's exit (WebKit removes a closed
         * dialog at once), and until it ends the drawer can be caught again.
         * Whatever is linked to the drawer leaves with it.
         */
        const slideOutAndClose = (ms) => {
            dialog.style.translate = `0 ${height + lift}px`;
            settle(true, ms);
            follow(dialog, 1, false);
            if (stack.length === 1 && stack[0] === dialog)
                indentPose(false);
            if (ms <= 0) {
                close();
                return;
            }
            const onSlid = (event) => {
                if (event.target === dialog && event.propertyName === "translate")
                    finish();
            };
            const finish = () => {
                cancelClose?.();
                close();
            };
            // the timer covers a transition that never reports its end
            const timer = window.setTimeout(finish, ms + 100);
            dialog.addEventListener("transitionend", onSlid);
            cancelClose = () => {
                window.clearTimeout(timer);
                dialog.removeEventListener("transitionend", onSlid);
                cancelClose = null;
            };
        };
        bound.set(dialog, { controller, snapTo });
        if (inDrawerMode(dialog)) {
            measure();
            place();
            stack.push(dialog);
            restack();
            trackKeyboard(dialog, signal, () => {
                measure();
                place();
            });
        }
        signal.addEventListener("abort", () => {
            cancelClose?.();
            // a drawer closed some other way mid-drag: nothing may hold the backdrop
            if (fade?.playState === "paused") {
                fade.cancel();
                fades.delete(dialog);
            }
        });
        dialog.addEventListener("scroll", () => {
            lastScroll = performance.now();
        }, { capture: true, passive: true, signal });
        // the handle steps through the snap points: a click, so a button handle works from the keyboard
        dialog.addEventListener("click", (event) => {
            if (stops.length < 2 || !(event.target instanceof Element))
                return;
            if (event.target.closest(HANDLE))
                snapTo((active + 1) % stops.length);
        }, { signal });
        window.addEventListener("resize", () => {
            if (!stack.includes(dialog))
                return;
            measure();
            place();
        }, { signal });
        trackDrag(dialog, {
            axis: "y",
            signal,
            canStart: (drag) => claims(dialog, drag, lastScroll, active < stops.length - 1),
            onStart: () => {
                // a drawer caught on its way out: what left with it comes back
                if (cancelClose && stack.length === 1)
                    indentPose(true);
                cancelClose?.();
                base = currentTranslate(dialog).y;
                measure();
                if (!fade) {
                    fade = scrubBackdrop(dialog);
                    if (fade)
                        fades.set(dialog, fade);
                }
                fade?.pause();
                setDragging(dialog, true);
            },
            onMove: ({ offset }) => {
                const travel = base + offset;
                const top = stops[stops.length - 1] ?? 0;
                const y = travel >= top ? travel : top + rubberBand(travel - top, lift + top);
                dialog.style.translate = `0 ${y}px`;
                // progress runs from the lowest stop to gone: above it nothing fades
                const lowest = stops[0] ?? 0;
                const progress = Math.min(1, Math.max(0, (y - lowest) / Math.max(1, height - lowest)));
                if (fade)
                    fade.currentTime = progress * SCRUB_MS;
                else
                    dialog.style.setProperty("--_drawer-backdrop", String(1 - progress));
                link(progress, true);
            },
            onEnd: ({ offset, velocity }) => {
                const target = pickSnap({
                    stops,
                    position: base + offset,
                    velocity,
                    active,
                    size: height,
                    closeRatio: CLOSE_RATIO,
                    flick: FLICK_VELOCITY,
                    fling: FLING_VELOCITY,
                    sequential: dialog.hasAttribute("data-drawer-snap-sequential"),
                });
                // transitions back on: the inline translate now eases to wherever it is set
                setDragging(dialog, false);
                if (target < 0)
                    slideOutAndClose(maxTransitionMs(dialog));
                else
                    snapTo(target);
            },
            onCancel: rest,
        });
    }
    /** Unbinds a drawer that closed. */
    function unbindDrawer(dialog) {
        bound.get(dialog)?.controller.abort();
        bound.delete(dialog);
        dialog.removeAttribute("data-drawer-state");
        dialog.style.removeProperty("--_drawer-depth");
        const index = stack.indexOf(dialog);
        if (index < 0)
            return;
        stack.splice(index, 1);
        restack();
    }
    /**
     * @description Moves an open drawer to one of its snap points.
     *
     * @param dialog - The drawer.
     * @param index - The snap point, counted from the smallest; clamped to the ones it has.
     */
    function snapDrawer(dialog, index) {
        bound.get(dialog)?.snapTo(index);
    }
    /**
     * @description Starts drawer binding for the page: every drawer is bound when
     * the dialog lifecycle reports it open and unbound when it closes. Idempotent.
     */
    const initDrawers = function () {
        if (initDrawers._bound)
            return;
        initDrawers._bound = true;
        document.addEventListener("zazz:dialog-open", (event) => {
            if (event.target instanceof HTMLDialogElement && event.target.matches(DRAWER)) {
                bindDrawer(event.target);
            }
        });
        document.addEventListener("zazz:dialog-close", (event) => {
            if (event.target instanceof HTMLDialogElement)
                unbindDrawer(event.target);
        });
        window.addEventListener("resize", () => {
            if (indented)
                measureIndent(indented);
        });
        // drawers that were already open when the script loaded
        for (const dialog of document.querySelectorAll(`${DRAWER}[open]`)) {
            bindDrawer(dialog);
        }
    };
    // Auto-initialize when DOM is ready (only in browser environment)
    if (typeof window !== "undefined" && typeof document !== "undefined") {
        if (document.readyState === "loading") {
            document.addEventListener("DOMContentLoaded", initDrawers);
        }
        else {
            initDrawers();
        }
    }
    export { bindDrawer, initDrawers, snapDrawer };

    Behavior

    primitives/drawer/drawer.js

    Drawer: drag-to-dismiss for <dialog data-ui="drawer"> bottom sheets. A drawer is a native modal <dialog>, opened and closed like any other (command="show-modal", command="close", Esc, the backdrop with closedby="any"). This script adds the gesture: drag the drawer down and let go to dismiss it.

    • data-ui="drawer" is a drawer on every device.
    • data-ui="dialog drawer" is a drawer below the sm band on a touch screen, and a plain dialog (no dragging) everywhere else.

    While the pointer is down the drawer follows it 1:1 and the backdrop fades with it. Letting go past a quarter of the drawer's height, or with a quick downward flick, slides it off the bottom edge and then closes it through requestClose(), so cancel and close fire as they do for Esc; anything less returns it to rest. Until it has slid out it can be caught again. Pulling it up past its resting place meets resistance.

    A drag starts anywhere on the drawer except on form fields, selected text, and anything inside [data-ui-no-drag]. Inside scrolling content it starts only once that content is scrolled to the top and the pointer moves down, so the body scrolls first and the drawer follows; the handle (data-drawer-slot="handle") always drags. There is no custom element and nothing to initialize: the script binds a drawer when it opens.

    Snap points. data-drawer-snap="148px 0.5 1" gives the drawer resting heights, smallest first: a number up to 1 is a share of the drawer's full height, a px or rem length is a visible height. It opens at the first. Letting go settles on the nearest; a flick moves one stop in its direction, a very fast one goes all the way (or one stop, with data-drawer-snap-sequential), and from the lowest stop a flick or enough travel downward closes the drawer. Below the largest stop the drawer takes every vertical drag and its content does not scroll. A click on the handle steps to the next stop; make the handle a <button> to give the keyboard the same. Each change fires zazz:drawer-snap (detail.index, detail.value in px), data-drawer-state carries expanded at the largest stop, and snapDrawer(dialog, index) moves it from script.

    The software keyboard. A phone lays a drawer out against the full screen, which the keyboard does not shrink. While a field in the front drawer has the keyboard up, the drawer's content ends at the keyboard's top edge (its surface runs on underneath), the focused field scrolls into what is still visible, and the page behind stays where it was. Nothing to author.

    Stacked drawers. A drawer opened over another scales the one behind back and lifts it, and that one follows as the front drawer is dragged. Nothing to author: the script counts the open drawers.

    Indent. Wrap the page in <ui-drawer-indent> (or put data-ui="drawer-indent" on its wrapper) and it scales back behind any open drawer, with rounded top corners, and follows the drag of the last one. Only transforms animate. While indented the wrapper is transformed, so a position: fixed element inside it moves with the page; position: sticky is unaffected.

    Events: zazz:dialog-close, zazz:dialog-open, zazz:drawer-snap

    Drawer everywhere, or only on a phone

    data-ui="drawer" on a <dialog> is a drawer on every device: it rises from the bottom edge, spans the full width of the screen, and can be dragged with a mouse as well as a finger. It has its own slots, data-drawer-slot="content", header, body, footer, and close, which lay out as the dialog's do.

    data-ui="dialog drawer" is a dialog that turns into a drawer below the sm band on a touch screen, the same test the dialog uses for its phone size. Everywhere else it is the plain dialog at the width its data-dialog-size gives it, and it does not drag. Keep the dialog's slots (data-dialog-slot), and add the handle:

    <dialog id="confirm" data-ui="dialog drawer" closedby="any">
      <div data-drawer-slot="handle"></div>
      <div data-dialog-slot="content">…</div>
    </dialog>

    In drawer mode both forms run edge to edge. To float a narrower sheet, cap --ui-drawer-w with a layout band: --ui-drawer-w: min(var(--layout-sm), 100%).

    A drawer takes the place of the dialog's phone size, so --ui-dialog-mobile-size does not apply to it. The handle is optional and shows only in drawer mode.

    Dragging and scrolling

    The whole drawer is the drag surface. Letting go past a quarter of its height closes it, and so does a quick downward flick over any distance; less than that and it returns to rest. Closing goes through requestClose(), so a cancel listener can keep the drawer open, as it can for Esc.

    Content that scrolls takes the gesture first. A pull moves the drawer only once the content under the finger is scrolled to the top, and only downward; the handle drags the drawer wherever the content is. Form fields and selected text never start a drag. To keep the drawer still under something else that needs the pointer (a map, a slider, a canvas), mark it:

    <div data-ui-no-drag>…</div>

    The open and close motion is the dialog's transition with the drawer's own timing: --ui-drawer-transition-duration (twice the default duration) and --ui-drawer-transition-timing-function. With prefers-reduced-motion the duration is zero, as it is for every dialog; the drawer still follows the pointer while it is dragged.

    Forms and the on-screen keyboard

    On a phone, the keyboard covers the bottom of the screen without making the page any shorter, so a drawer would sit partly under it. While a field in the front drawer has the keyboard up, the drawer's content ends at the keyboard's top edge, with its surface carrying on underneath, and the focused field scrolls into the part that is still visible. The page behind keeps its scroll position. There is nothing to author.

    Snap points

    data-drawer-snap gives a drawer more than one resting height. List them smallest first, separated by spaces: a number up to 1 is a share of the drawer's full height, and a px or rem length is a visible height.

    <dialog id="places" data-ui="drawer" data-drawer-snap="12rem 0.5 1" closedby="any">
      <button type="button" data-drawer-slot="handle" aria-label="Resize drawer"></button>
      <div data-drawer-slot="content">…</div>
    </dialog>

    The drawer opens at the first stop. Letting go settles it on the nearest one; a flick moves it one stop in the flick's direction, and a very fast flick goes all the way open or closed. Add data-drawer-snap-sequential to make a fast flick move one stop as well. From the smallest stop, a downward flick or enough travel closes the drawer.

    Below its largest stop the drawer takes every vertical drag and its content does not scroll; at the largest stop content scrolls first, as it does without snap points. A click on the handle steps to the next stop and wraps to the first. Make the handle a <button> with an aria-label, as above, so the keyboard can do the same.

    The backdrop stays full at every stop, because the drawer is a modal dialog and the page behind it is inert. It fades only as the drawer is dragged below the smallest stop.

    Read or writeHow
    The drawer reached a stopzazz:drawer-snap on the dialog, bubbling; event.detail.index and event.detail.value (visible height in px)
    It is at the largest stopdata-drawer-state~="expanded" (otherwise partial)
    Move it from scriptimport { snapDrawer } from "@zazz-ui/core/primitives/drawer/drawer.js", then snapDrawer(dialog, index)

    Stacked drawers

    A drawer opened while another is open sits in front of it. The one behind scales back and lifts so its top edge shows, and it follows as the front drawer is dragged down. Esc and the backdrop close the front drawer first. There is nothing to author: open the second drawer from the first with the usual command="show-modal".

    --ui-drawer-stack-scale (default 0.05) is how much each drawer in front shrinks the one behind, and --ui-drawer-stack-lift how far it lifts. The second drawer adds no dimming of its own; set --ui-drawer-nested-backdrop-color to give it some.

    Indenting the page

    Wrap the page in <ui-drawer-indent> (or put data-ui="drawer-indent" on the element that already wraps it), and the page scales back behind any open drawer, with rounded top corners, and follows the last drawer as it is dragged down.

    <body>
      <ui-drawer-indent>
        <header>…</header>
        <main>…</main>
      </ui-drawer-indent>
    
      <dialog id="share" data-ui="drawer" closedby="any">…</dialog>
    </body>

    Drawers can sit inside the wrapper or beside it. The wrapper paints the page background (--ui-drawer-indent-bg), and the <body> takes the backing color (--ui-drawer-indent-backing, black by default) while the page is indented. Set the indent hooks on :root, since the body reads the backing color too.

    HookWhat it setsDefault
    --ui-drawer-indent-insetHow far each side of the page pulls in3 spacing units
    --ui-drawer-indent-offsetHow far the page drops from the topthe top safe-area inset plus --space-sm
    --ui-drawer-indent-radiusThe radius of the page's top corners--ui-drawer-radius

    Only scale and translate animate. The corner radius is two small corner pieces that grow from the corners, so no border-radius or clip is animated and the page is not repainted as it moves. The corners follow --radius-corner-shape in browsers that support corner-shape and are round elsewhere.

    Two limits come with scaling the page:

    • While a drawer is open the wrapper is transformed, so a position: fixed element inside it is positioned against the wrapper and moves with the page. Use position: sticky for headers, or keep fixed elements outside the wrapper.
    • A dialog drawer indents the page only in drawer mode, never as a desktop dialog.

    Attributes

    drawer attributes
    AttributeKindValuesNotes
    data-ui="drawer-indent"Identityfree valueIdentity token in data-ui.
    data-ui="drawer"Identityfree valueIdentity token in data-ui.
    <ui-drawer-indent>Tag formfree valueTag form; styled and, when scripted, registered under this name.
    data-drawer-slotSlotbody close content footer handle headerSlot: a part inside the primitive.
    data-drawer-indent-stateStateactive dragging onState the kit's script writes; read it in selectors, never author it.
    data-drawer-stateStatedragging following nested partial stackedState the kit's script writes; read it in selectors, never author it.
    data-drawer-snapConfigfree valueConfiguration the kit's script reads.
    data-drawer-snap-sequentialConfigfree valueConfiguration the kit's script reads.

    Requires: dialog, button.

    Hooks

    Set a hook on :root, on a subtree, or inline on one element. A state hook (--…--hover) themes that state only; the primitive keeps its other states.

    drawer hooks
    HookDefaultState
    --ui-drawer-bgvar(--ui-dialog-bg)—
    --ui-drawer-corner-shapevar(--ui-dialog-corner-shape)—
    --ui-drawer-handle-bgvar(--color-muted)—
    --ui-drawer-handle-bg--activevar(--color-muted-foreground)active
    --ui-drawer-handle-bg--draggingvar(--color-foreground)dragging
    --ui-drawer-handle-bg--hovervar(--color-muted-foreground)hover
    --ui-drawer-handle-hcalc(var(--spacing) * 1.25)—
    --ui-drawer-handle-wcalc(var(--spacing) * 12)—
    --ui-drawer-indent-backingvar(--color-black)—
    --ui-drawer-indent-bgvar(--color-background)—
    --ui-drawer-indent-insetcalc(var(--spacing) * 3)—
    --ui-drawer-indent-offsetcalc(env(safe-area-inset-top, 0px) + var(--space-sm))—
    --ui-drawer-indent-radiusvar(--ui-drawer-radius)—
    --ui-drawer-max-hcalc(100dvb - var(--space-lg))—
    --ui-drawer-nested-backdrop-colortransparent—
    --ui-drawer-radiusvar(--radius-xl)—
    --ui-drawer-shadowvar(--shadow-lg)—
    --ui-drawer-stack-liftvar(--space-sm)—
    --ui-drawer-stack-scale0.05—
    --ui-drawer-textvar(--ui-dialog-text)—
    --ui-drawer-transition-durationcalc(var(--default-transition-duration) * 2)—
    --ui-drawer-transition-timing-functioncubic-bezier(0.32, 0.72, 0, 1)—
    --ui-drawer-w100%—

    API