Mixins / foldkit-mixins-ui

Menus and overlays

Panels that stay where they are drawn go in the browser's top layer (see The top layer). Dialogs, sheets, tours and floating panels return focus by focusReturn; the popups enter and leave as Exits and reduced motion describes.

WidgetWhat it doesState
MenuDropdown, context menu, or long-press menuSmall Model / Bundle
MenubarHorizontal bar of menus with arrow-key switchingSmall Model / Bundle
DialogModal dialog adapter over @foldkit/uiAdapter / Bundle
SheetDraggable modal drawer sheetSmall Model / Bundle
DrawerNon-modal bottom sheet peeking beside the pageSmall Model / Bundle
PopoverAnchored popover adapter in the top layerAdapter / Bundle
TooltipAnchored tooltip adapter in the top layerAdapter / Bundle
HoverIntentDelayed hover card adapter (Recipes.HoverCard)Adapter / Bundle
AnchorTop-layer floating positioning (behavior, topLayer)Behavior / Mount
FloatingPanelDraggable, resizable non-modal windowSmall Model / Bundle
TourGuided spotlight steps anchored to page targetsSmall Model / Bundle

Menubar renders a row of Menu panels (Recipes.MenubarMenu flattens triggers); one trigger holds the tab stop, ArrowLeft/ArrowRight moves between menus (or opens the next when one is open), and hovering another trigger switches menus while open. Anchor.behavior positions a floating slot against a trigger by id, and Anchor.topLayer shows an in-place panel in the browser's top layer.

anchor is merged over the default { placement: 'bottom-start', gap: 4, padding: 8, portal: false } (no gap at a point): { placement: 'top-end' }. header and footer are Html drawn in the panel above and below the rows, in the header and footer slots, and are no row. A row's content Html is drawn in place of its words; label stays its name and typeahead key.

A row is an ItemRow ({ value, label }: the value names the row, unique among the menu's rows and their submenus' items, and is what isRowDisabled, Selected and Menu.checkChosen use; the label is what is drawn and what typeahead matches, so two rows may read alike; type the values by a union with Row<'a' | 'b'>), a CheckRow (check: 'checkbox' | 'radio', checked: menuitemcheckbox or menuitemradio with aria-checked; choosing it sends Selected and leaves the menu open, the application keeping checked, a radio row's group being the rows of its group), or a SubmenuRow (items, each an ItemRow, one level deep, and isItemDisabled? asked of their values). Any row may name a group (rows next to each other with one group stand under its heading, a separator between groups), a shortcut (keys drawn at the row's end as Kbd with the view's kbd, named in aria-keyshortcuts; the menu binds nothing), an icon (an Html drawn before the label in the icon slot, hidden from assistive technology), a hint (a quiet note at the end of the row, before the shortcut, in the hint slot) and tone: 'destructive' (data-tone). A submenu's items take the same parts.

A submenu's row is a menuitem with aria-haspopup="menu" and aria-expanded; ArrowRight, Enter or Space opens it on its first row, ArrowLeft or Escape closes it back to the row (under direction: 'rtl' the submenu opens on the left and the arrows swap), a pointer resting 150ms opens it, and choosing a leaf closes everything. Selected names the row's value and the value of the submenu's row it came from. isAnimated gives the panels upstream's transition marks, for the recipe's fade; isModal makes the rest of the page inert while the menu is open. Pass Menu.fluid beside the style (in submenuMixins, not mixins, where rows open submenus).

opensAt: 'point', with Menu.target(onMessage, h) on the area, is a context menu: a right press records its point and the contextmenu after it opens the menu there; a finger or a pen held there Menu.HOLD_MS (500ms) opens it too, as iOS fires no contextmenu, while one that moves 10px is a scroll. Give the area -webkit-touch-callout: none and user-select: none, or iOS shows its own callout over it. A @foldkit/ui Menu the application folds itself, for typed items or groups, is drawn through the panel adapter instead, and opens at a point with Menu.drawAtPoint and Menu.pointTarget (see Why some components needed a fork).

Dialog

Slots beyond upstream's are this package's: handle (the Sheet's grabber, aria-hidden unless the Sheet has more than one point, when it is a separator), body, scroll, scrollBar, scrollThumb and footer. Draw scroll and its bar inside body and the answers in footer, and a body taller than the screen scrolls under the title while the footer stays (Dialog.overlayBars beside the style draws the overlay bar).

  • Context. attributes adds to a bundle before the mixins resolve. covered: true marks the panel data-covered, for a dialog another was opened from (draw the second inside the first's dialog, beside its panel), and the recipe steps it back. isLeaving: Dialog.isLeaving(model) draws the panel inert for the rest of its exit, so no press or key acts on it (upstream takes the backdrop and close button out of a leaving dialog but leaves the application's own controls live); the Sheet does this itself.
  • Alert dialog. role: 'alertdialog' in the context (Dialog.toView(mixins, { h, role: 'alertdialog' }, draw)) puts role="alertdialog" on the dialog bundle. Draw no close button, and drop the Messages Dialog.isDismissal names (Escape, the backdrop, the close button) in update, so only its own buttons, closing with @foldkit/ui's close, answer it.
  • Focus. Dialog.focusReturn among the mixins gives focus a place to go when the opener is gone as the dialog closes (see Focus after removal). Dialog.update(model, message) and Dialog.open(model) are @foldkit/ui's update and open plus one repair: an open that meets the exit (the dialog opened again while it leaves) puts focus back inside it, on the focusSelector, the initial-focus mark, else the first control, which a bare upstream open does not.
  • On-screen keyboard. Dialog.keyboard among the mixins of a dialog or sheet that holds a field measures the keyboard on the panel, and the recipes keep the panel above it (a Dialog shrinks, a bottom Sheet stands on it): iOS Safari and Chrome on Android otherwise leave it under the keys.
  • Recipe. title: 'hidden' leaves the heading to a screen reader alone (it still names the dialog, as display: none would not). close: 'none' leaves the closeButton Slot unstyled for an application whose own buttons carry it (the Slot is still the Dialog's, with its RequestedClose). motion: 'none' opens, closes and steps back at once, backdrop and panel alike, whatever the motion knob (reduced motion is as it was). The backdrop is the overlay.scrim token.
ts
import * as UiDialog from '@foldkit/ui/dialog'
import { Dialog, DialogSlots } from 'foldkit-mixins-ui'

const DialogStyle = Recipes.Dialog.style({ size: 'sm' })

// The dialog's Model and Messages are @foldkit/ui's: the application folds them
// with `Dialog.update`, and opens it with `Dialog.open`.
const confirmDialog = (
  model: UiDialog.Model,
  toMessage: (message: UiDialog.Message) => Message,
  h: HtmlBuilder<Message>,
) =>
  h.submodel({
    slotId: model.id,
    model,
    view: UiDialog.view,
    viewInputs: {
      toView: Dialog.toView(
        [DialogStyle.mixin, ...Dialog.focusReturn],
        { h, isLeaving: Dialog.isLeaving(model) },
        dialog =>
          h.dialog(
            dialog.dialog,
            dialog.isVisible
              ? [
                  h.div(dialog.backdrop),
                  h.div(dialog.panel, [
                    h.h2(dialog.title, ['Discard changes?']),
                    h.div(dialog.footer, [h.button(dialog.closeButton, ['Cancel'])]),
                  ]),
                ]
              : [],
          ),
      ),
    },
    toParentMessage: toMessage,
  })

Sheet and Drawer

Sheet. draw lays out DialogSlots' bundles with h.div(sheet.handle) in the panel. The panel stands on side's edge (data-side); a drag follows the pointer and settles at the nearest of points (the share of the panel shown, ascending; a top or bottom sheet with a point below 1 takes its size's full height, and below its highest point its content holds still, so a swipe up raises it), or, flicked or dragged far enough past the first, closes it, unless dismissible: false. The Dialog keeps focus, Escape and scroll lock. With more than one point the handle is a focusable separator named by words.handle (default Resize sheet), its aria-valuenow the percent shown: the arrow keys along the edge (the one toward the page raises it: ArrowUp on a bottom sheet, ArrowDown on a top one, ArrowLeft on a right one, ArrowRight on a left one), Home and End step between the points through Message.SnappedTo { at } (an index into points) and stop at the ends, and Escape still closes; an opened sheet with points takes focus on the handle unless the panel has an initial-focus element. With one point the handle stays decoration, aria-hidden; with handle: 'none' an application moves the sheet with SnappedTo from a control of its own. A leaving Sheet's panel is inert until it is gone, and Sheet.open is Dialog.open's, so a Sheet opened again while it leaves takes focus back; one whose opener is gone as it closes returns focus through Dialog.focusReturn among its mixins. scalesPage with Recipes.sheetPage on the page beside the sheet, never around it, steps the page back while it is open. The slide and its exit run on Theme.tokens.motion.sheet and sheet-exit, which default to the slow tier and its exit and are multiplied by travel: an application that keeps another timing sets them in its tokens (Theme.define({ motion: { sheet: '500ms', 'sheet-exit': '500ms' } })), and sheetPage follows sheet. The panel's padding keeps clear of the safe areas (Theme.tokens.safe) on the sides it touches.

Swiping (Sheet and Drawer). swipe: { from?, flickSpeed?, closeShare? } says how it is swiped: a finger drags it from anywhere on the panel (from: 'panel', the default), yielding to content that can still scroll its way, so a long one scrolls back to its top and then goes, and a field or data-no-swipe starts no drag; a mouse drags it by the handle, and from: 'handle' keeps every pointer there. A release faster than flickSpeed (0.4px/ms) is a flick, and a slow one goes once dragged closeShare (a quarter) of the panel.

Drawer. draw lays out panel, handle, body (the body may sit below what else peeks with the handle) and, optionally, grip, more to drag it by (a row of tabs: vertical swipes drag it, sideways ones still scroll). A drag follows the finger and lets go open or down by its speed, then by how far it came. A click or Enter on the handle toggles it, and the click a browser sends after a drag does not. label names the handle once, and its aria-expanded says whether the panel is open, so the name does not change with the state. The body is hidden (visibility: hidden) when the slide ends, not as it starts. Drawer.keepFocus beside the style moves focus to the handle when the drawer closes with focus in its body, which the hidden body would otherwise drop to the page. The panel's inline style is the drag's: set --fk-drawer-peek (default 5rem) and --fk-drawer-height (default 70dvh) on an ancestor or in a style. The handle is a 44px target drawn tight to its bar, and the peek stays above the home indicator.

FloatingPanel

The drag trigger (role="button", named Move <title>) moves the panel and eight edges resize it, kept within the viewport; the arrows move it from the drag trigger and resize it from the bottom-end corner; minimize, maximize, restore and close. A press or focus inside returns the Raised OutMessage, which the application folds into the order its panels stack by with FloatingPanel.raise(order, id). routes are application key routes beside Escape (unless closeOnEscape is false); the arrows on the drag trigger and the corner are the panel's own, and a press they handled still reaches the panel. FloatingPanel.focusReturn is opt-in and is the one way focus returns.

The limits (min, max, grid, overflow) are init's options and live in the Model, so FloatingPanel.update() reads the one copy; update(limits) still overrides them for a call. Bundles.FloatingPanel places the window with init's options as its args and reports Raised in onOut; its helpers are open, close, openBeside(openerId, { side?, gap? }) and dock(edge, thickness). openBeside (also a function of the module) reads the opener's box in a Command and answers Placed, which puts the panel there within the limits and the viewport; rectBeside(anchor, size, options) is the pure rule, for a place of your own. Docked { edge, thickness } lays the panel along an edge of the viewport as measured when it lands; it stays a window and drags away. controls names the header's buttons (default all three; restore appears with whichever stage was reached), words their names and the drag trigger's and corner's (Move {title}, Resize {title}), and FloatingPanel.configure({ base, presets }) fixes the look, words, controls and mixins once.

ts
import { Schema } from 'effect'
import { Bundle } from 'foldkit-bundle'
import { Bundles, FloatingPanel } from 'foldkit-mixins-ui'

const Windows = Bundle.compose({ order: Schema.Array(Schema.String) }).pipe(
  Bundle.withChild('notes', Bundles.FloatingPanel, {
    args: { id: 'notes', rect: { x: 80, y: 120, width: 320, height: 220 }, grid: 20 },
    onOut: out => model => ({
      model: { ...model, order: FloatingPanel.raise(model.order, out.id) },
    }),
  }),
)

Tour

The target scrolls into view; Next, Back and the arrows move on, Escape and Skip end it, and update returns Ended { completed }. A step without a target, or whose target is missing, stands in the middle. routes are application key routes on a step, such as a digit jumping to that step, beside the arrows and, unless closeOnEscape is false, Escape. Tour.focusReturn is opt-in and is the one way focus returns: ending the tour gives focus back to what had it before it started.

The steps are data in the Model (init's steps), so update(), start(model) and the view read one copy; update(config), start(model, config) and the view's config override it for a call. Bundles.Tour places it with { id, steps? } as its args, reports Ended in onOut, and helpers.start starts it. content(step, index) draws a step's words as Html in their place (a key to press, a list), still describing the step's dialog. advanceOnClick: Tour.advanceOnClick moves the tour on when the reader presses the step's target through the cutout (not with interactive: false); it is a value in a file of its own, so a tour without it loads no listener. words (Tour.words) are the buttons' names and the step's place, {step} of {count}; Tour.configure({ base, presets }) fixes the look, words and mixins once.

Popover, Tooltip and Hover Card

Popover, Tooltip and Hover Card are drawn by upstream views whose Mounts this package cannot wrap, so their panels go in the top layer by an element of their own (see The top layer). A Popover's layer Slot, Popover.anchor() and Tooltip.anchor() give portal: false and the placement: 12px and 8px off the trigger, 8px inside the viewport, flipping and shifting. Each draws an arrow slot in its panel that points at the trigger.

State as Bundles. Every overlay's state is a Bundle, one file apiece: Bundles.Dialog.with({ id, isAnimated?, focusSelector?, dismissible? }), Bundles.Sheet, Bundles.Drawer, Bundles.Popover, Bundles.Tooltip (showDelay in milliseconds) and Bundles.HoverIntent (openDelay, closeDelay). The upstream ones report Opened and Closed (a Tooltip Shown and Hidden) for onOut, and helpers.open and helpers.close are for a control of the application's. A Dialog that is not dismissible drops the RequestedClose that Escape, the backdrop and its close button send, so only an answer closes it, through helpers.close: an alert dialog is that, with role: 'alertdialog' in Dialog.toView's context. A Sheet opened by the Dialog's own RequestedOpen rests at its opensAt point, as helpers.open does. Pass isAnimated: true and the panel stays drawn while it leaves, so the recipe's fade runs on the way out as on the way in. The drawing stays the adapter's: what a dialog or a popover holds is the application's content, so the examples compose it rather than pass it as options. Dialog's overlayBars, keyboard and focusReturn, Drawer.keepFocus and Toast.keepFocus are files of their own, so a page that never names one keeps neither its Mount nor the primitive it runs. A Drawer imports no Sheet and no Dialog (swipe.ts holds what the two share).