Fragiola

API: DOM toolkit (@fragiola/primitives)

The DOM toolkit

@fragiola/primitives: the framework-free DOM behaviours every component is built on, one entry per mechanism, from the focus trap to the date math.

@fragiola/primitives is the framework-free toolkit the three framework packages build their components on. Each framework package depends on it at the exact same version: you rarely import it yourself, but you can, to build a primitive of your own.

What it is, and what it is not

It holds DOM behaviours and pure math: functions and small classes that take elements and options and return values or a cleanup. It never holds a component's open, selected or value state, its lifecycle or its API, and it never imports a framework. It never touches the global document or window, only an element's own document, so it works inside iframes and popup windows. Its only runtime dependency is @floating-ui/dom, in the positioning entry.

One entry per mechanism

Each mechanism is its own entry, so a component pulls in only the ones it uses: Dialog uses /overlay, /focus, /inert, /scroll-lock and /presence (AlertDialog, built on Dialog's parts, the same, with the focus trap's holdOutsidePress); Tabs uses /collection and /direction (and /presence for its panels' enter and exit); Collapsible uses /presence alone (its panel size and find-in-page match), Accordion /presence, /collection and /direction; Popover adds /positioning; Tooltip uses /hover, /pointer and /positioning; Menu uses /collection, /pointer, /positioning and, for its modal option, /inert and /scroll-lock; ContextMenu, built on Menu's parts, adds the long press of /pointer and the virtual anchor of /positioning (each in its own module, so Menu and Dialog do not pull them); Drawer, built on Dialog's parts, adds /swipe; ScrollArea uses /scroll-area alone (its measurement, its scrollbars' pointer and its hover, which no other component imports) and Pagination /pagination alone (its range, pure math); Carousel /carousel (its pages, its scrolling and mouse drag, its hover and focus watch and its rotation delay, which no other component imports) with /collection and /direction (the tabbed Indicators' keys); Link and Breadcrumbs use none; Steps uses none; AspectRatio uses none; Clipboard uses /clipboard alone (its copy and its announcement); DropZone and FileUpload use /file (their drop target, file dialog, accept matching, checks, sizes and the files assigned to an input, which no other component imports) and /clipboard's announceText, FileUpload /form too; Toast uses /toast (the queue, which no other component imports), /swipe and /presence; HoverCard uses Tooltip's /hover and /pointer, with /overlay and /positioning; NavigationMenu uses /overlay, /positioning, /hover, /pointer (the hover bridge), /focus, /collection, /direction and /presence. The form controls use /form (the hidden inputs, the form bridges and the Field layer), so Field's form code reaches only the components that import it: Field (and Fieldset and Form, built on it), Checkbox, Switch and Radio use it alone; RadioGroup uses /collection and /direction for its arrow keys; Slider adds /range, /pointer and /direction; Select and Combobox add /collection, /overlay and /positioning (Select's modal option /inert and /scroll-lock); the date pickers add /date to the Popover's mechanisms; DateField and TimeField add /segments (the segment editing) and /time (the plain times and date-times) to /date and /form, as do the range fields and the pickers' opt-in typed input (DatePickerInput, DateRangePickerInput, in entries of their own), and no other component imports those two: a DatePicker without the typed input stays on /date. The month and year calendars, their pickers and a calendar's views (CalendarView) add /month-year (the month and year values, their 12-item page and its keys, their names), which no day calendar imports. No component imports /calendar-systems or /time-zone: a date component takes a calendar system as its calendar, a date field or typed picker a zone as its timeZone, so an app that passes none bundles none of their code (calendar systems, time zones). Progress uses /range alone, Avatar /image alone; Button and Separator use none. Toolbar and ToggleGroup use the roving focus of /collection and /direction (a Toggle alone imports neither: its composite's root handles the keys). NumberField adds /number to /form (its parsing and formatting of localized text, its stepping, the auto repeat of its buttons and its scrub; no other component imports it), OTPField uses /form (its value rules), /collection and /direction; Meter uses /range alone, Label /form alone (its press). Listbox adds /selection, the collections mechanism (its list model, selection rules and key map; no other component imports it yet), to /collection (typeahead), /direction and /form; Autocomplete uses Combobox's mechanisms (/collection, /overlay, /positioning, /form). TagGroup uses /collection (its key map and removal focus), /selection (its selection rules), /direction and /form (the Field binding); TagsInput /collection (its keys), /form (the rules that add and edit a tag, the form bridge) and /direction. SegmentedControl uses /collection (the radio key map and its Indicator's measurement), /direction and /form; Rating /range (its steps, the value under the pointer and a star's state), /direction and /form. The virtual lists (ListboxVirtual and the others) add /virtual to their component's mechanisms, and the async list utility uses /async-list alone: a list that does not opt in imports neither. Command uses /command (its scorer and keys; no other component imports it) and /collection; CascadeSelect uses /cascade (its levels and keys; no other component imports it) with Select's mechanisms (/collection, /overlay, /positioning, /form, /direction) and /pointer (Menu's safe area). The root entry, @fragiola/primitives, only re-exports them.

Exports

entryexports
@fragiola/primitives/async-listcreateAsyncList, AsyncList, AsyncListOptions, AsyncListLoad, AsyncListPage, AsyncListRequest, AsyncListState, AsyncListStatus
@fragiola/primitives/cascadecascadeKeyAction, CascadeKeyAction, cascadeLevels, cascadePathItems, hasCascadeChildren, CascadeItem
@fragiola/primitives/calendar-systemsbuddhist, coptic, ethioaa, ethiopic, gregory, hebrew, indian, islamicCivil, islamicTbla, islamicUmalqura, japanese, persian, roc, CalendarSystem, CalendarId, CalendarDateFields, CalendarFieldsInput, CalendarYearMonth, CalendarUnit, CalendarUnits
@fragiola/primitives/collectionscrollIntoViewWithin, placeTabsIndicator, tabsIndicatorBox, TabsIndicatorBox, placeSegmentIndicator, segmentIndicatorBox, SegmentIndicatorBox, activationDirection, ActivationDirection, tabsKeyTarget, TabsKeyOptions, accordionKeyTarget, AccordionKeyOptions, menuKeyTarget, submenuKeys, radioKeyTarget, RadioKeyOptions, rovingKeyTarget, rovingKeys, rovingTabStop, textFieldKeepsKey, inDocumentOrder, RovingKeyOptions, RovingKeys, RovingOrientation, stepIndex, edgeIndex, stepThroughNone, NavigationOptions, createTypeahead, filterItems, flattenItems, containsFilter, textContains, queryIsLabel, isItemGroup, itemLabel, itemFormValue, itemsEqual, includesItem, toggleItem, chipKeyTarget, chipArrows, ChipKeyAction, tagGroupKeyTarget, removalFocusIndex, tagsInputInputKeyTarget, tagsInputTagKeyTarget, TagGroupKeyAction, TagGroupKeyOptions, TagKeyEvent, TagsInputInputKeyAction, TagsInputTagKeyAction, FilterItemsOptions, ItemEquality, ItemFilter, ItemGroup
@fragiola/primitives/commandcommandScore, commandItemScore, commandMatches, bestMatch, commandKeyTarget, CommandEntry, CommandFilter, CommandMatches
@fragiola/primitives/colorColor, ColorSpace, ColorChannel, RgbColor, HslColor, HsbColor, ColorChannelRange, colorChannelRange, colorChannels, hasColorChannel, colorSpaceFor, getColorChannel, setColorChannel, clampColorChannel, isSameColor, ColorAreaChannels, colorAreaChannels, parseColor, formatColor, ColorFormat, colorChannelFormat, formatColorChannel, convertColor, colorChannelGradient, ColorGradientDirection, colorAreaBackground, ColorAreaBackground, colorWheelGradient, colorAreaKeyTarget, ColorAreaKeyOptions, colorWheelKeyTarget, wrapHue, hueAtPoint, isOnColorWheel, colorWheelThumbOffset, openEyeDropper, supportsEyeDropper
@fragiola/primitives/datePlainDate, DateRange, Weekday, plainDate, today, fromIsoDate, toIsoDate, toLocalDate, addDays, addMonths, addYears, clampDate, compareDates, isSameDate, isSameMonth, isBetween, isWithinBounds, dayOfWeek, daysInMonth, startOfMonth, endOfMonth, startOfWeek, endOfWeek, monthsBetween, firstDayOfWeek, weekdays, monthGrid, calendarKeyTarget, CalendarKeyOptions, formatDayNumber, formatFullDate, formatMonthYear, watchDocumentLanguage
@fragiola/primitives/month-yearPlainYearMonth, PlainYear, YearMonthRange, YearRange, monthIndex, fromMonthIndex, currentYearMonth, toIsoYearMonth, toIsoYear, UNIT_PAGE_SIZE, unitPageStart, unitRows, unitKeyTarget, UnitKeyOptions, formatMonthName, formatYearMonth, formatYear, formatYearSpan
@fragiola/primitives/directiongetDirection, Direction
@fragiola/primitives/filewatchFileDrop, dragHasFiles, FileDropOptions, FileDropReason, openFileDialog, FileDialogOptions, acceptsFile, acceptFiles, acceptAttribute, FileAccept, FileLike, checkFiles, CheckedFile, FileCheck, FileRejection, FileRejectionReason, FileRules, formatFileSize, assignFiles, fieldFiles
@fragiola/primitives/focusfocusInitial, trapFocus, getTabbables, nextTabbableAfter, previousTabbableBefore, isKeyboardModality, FocusTrapOptions
@fragiola/primitives/formbridgeForm, FormBridgeOptions, validateField, ValidateFieldOptions, createFieldValidator, FieldValidator, validatesOnChange, shownAfterChange, fieldErrorShown, fieldErrorMessages, fieldDescribedBy, fieldStateAttributes, onSubmitAttempt, guardFormSubmit, firstInDocumentOrder, focusFieldControl, formErrorsFor, withoutFormErrors, CLEARED, UNVALIDATED, VALIDITY_KEYS, VISUALLY_HIDDEN_INPUT_STYLE, FieldErrorMatch, FieldState, FieldValidate, FieldValidateResult, FieldValidation, FieldValidationMode, FieldValidity, FormErrors, ValidityKey, preventLabelSelection, labelFocusTarget, normalizeOtp, replaceOtp, removeOtpCharacter, otpAccepts, otpInputMode, otpPattern, OtpValidationType, takeTags, typesDelimiter, editTag, TagRules, TakenTags, RefusedTag, TagRefusal, EditedTag
@fragiola/primitives/hovercreateHoverIntent, HoverIntent, createDelayGroup, DelayGroup
@fragiola/primitives/idcreateId
@fragiola/primitives/imagewatchImageStatus, ImageLoadingStatus, ImageSourceOptions
@fragiola/primitives/inertinertOutside, blockOutsidePointer
@fragiola/primitives/layerspushLayer, Layer, LayerOptions, watchFocusOutside, interceptEscape
@fragiola/primitives/numberformatNumber, numberFormatOptions, NumberFormatOptions, parseNumber, isNumberText, stepNumber, clampNumber, NumberStepOptions, watchAutoRepeat, AutoRepeatOptions, watchScrub, ScrubOptions, ScrubPoint
@fragiola/primitives/overlayopenOverlaySession, OverlaySession, OverlaySessionOptions, DismissReason, DismissEvent
@fragiola/primitives/carouselcarouselPages, CarouselPagesOptions, clampCarouselPage, slidesInView, stepCarouselPage, CarouselOrientation, groupScrollPosition, nearestCarouselPage, slideScrollPosition, createRotationTimer, RotationTimer, CarouselController, CarouselWatchOptions, watchCarousel
@fragiola/primitives/clipboardwriteClipboard, announceText
@fragiola/primitives/paginationpaginationRange, PaginationItem, PaginationRangeOptions, pageCount, PageCountOptions, clampPage
@fragiola/primitives/pointerstartDrag, DragSessionOptions, isInSafeArea, Point, isInHoverBridge, trackHoverBridge, HoverBridgeCallbacks, watchPointerExit, LongPressOptions, watchLongPress
@fragiola/primitives/positioninganchorFloating, AnchorOptions, Side, Align, toPlacement, fromPlacement, AnchorRect, VirtualAnchor, virtualAnchor
@fragiola/primitives/presencenextFrame, waitForAnimations, isAnimating, measurePanelSize, freezePanelSize, panelSizeVariables, PanelSize, watchBeforeMatch, BeforeMatchOptions
@fragiola/primitives/rangesnapToStep, fractionAlong, valueAtFraction, valueToPercent, nearestThumb, moveThumb, thumbBounds, RangeOptions, ThumbOptions, sliderKeyTarget, SliderKeyOptions, progressValue, ProgressOptions, ProgressStatus, ProgressValue, ratingKeyTarget, RatingKeyOptions, ratingValueAt, ratingItemState, RatingItemState
@fragiola/primitives/scroll-areacreateScrollArea, ScrollAreaController, ScrollAreaOptions, ScrollAreaOrientation, ScrollAreaPart, ScrollAreaState, ScrollAreaThreshold, ScrollAreaThresholdInput, initialScrollAreaState, normalizeScrollAreaThreshold, thumbGeometry, ThumbGeometry, ThumbGeometryInput, scrollFromStart, scrollForThumbOffset, MIN_THUMB_SIZE
@fragiola/primitives/scroll-locklockScroll
@fragiola/primitives/segmentssegmentFormat, SegmentFormat, SegmentFormatOptions, SegmentGranularity, SegmentKind, SegmentPart, SegmentType, EditableSegmentType, HourCycle, dateSegments, DateSegment, SEGMENT_PLACEHOLDER, SegmentValues, SegmentRange, segmentRange, SEGMENT_PAGE_STEPS, setSegment, stepSegment, segmentToEdge, shownValue, displayHour, isSegmentsComplete, segmentValuesOf, segmentsToDate, segmentsToTime, segmentsToDateTime, typeSegment, eraseSegment, segmentDigit, SegmentEdit, SegmentTypeResult, SegmentEraseResult, segmentKeyDown, SegmentKeyResult, segmentTarget, SegmentMove, focusOnLabelPress
@fragiola/primitives/selectioncreateListModel, ListModel, ListNode, applySelection, inModelOrder, sameSelection, SelectionBehavior, SelectionChange, SelectionMode, SelectionOptions, SelectionState, listKeyTarget, listPressSelection, ListKeyEvent, ListKeyOptions, ListKeyResult, pageTarget, rowTarget
@fragiola/primitives/swipewatchSwipe, SwipeOptions, SwipeDirection, SwipeMovement, SwipeEnd, SWIPE_LOCK_DISTANCE, swipeRelease, SwipeOutcome, swipeMovement, swipeProgress, swipeDisplacement, resolveSnapPoints, SnapPoint, ResolvedSnapPoint
@fragiola/primitives/timeaddDateTime, addTime, compareDateTimes, compareTimes, currentDateTime, currentTime, cycleTime, DateTimeDuration, fromIsoDateTime, fromIsoTime, IsoTimePrecision, isSameDateTime, isSameTime, PlainDateTime, plainDateTime, PlainTime, plainTime, TimeDuration, TimeField, TimeRange, toIsoDateTime, toIsoTime, toPlainDate, toPlainTime
@fragiola/primitives/time-zonetimeZone, TimeZone, ZonedDateTime, Disambiguation, offsetAt, fromInstant, toInstant, toZoned, toTimeZone, compareZoned, addZoned, cycleZoned, localTimeZone, toIsoZoned, toIsoOffset, fromIsoZoned, formatTimeZoneName
@fragiola/primitives/toastcreateToastManager, ToastManager, ToastManagerOptions, ToastObject, ToastOptions, ToastPriority, ToastPromiseOptions, ToastUpdate, watchToastViewport, ToastViewportWatch, ToastViewportWatchOptions, measureToastHeight
@fragiola/primitives/virtualcreateVirtualizer, Virtualizer, VirtualizerOptions, VirtualAlign, scrollContainer, virtualLayout, VirtualLayoutOptions, VirtualRange, VirtualRow, rowStarts, rowAt, activeSticky, pageIndex

The mechanisms

  • Overlay: an overlay session ties a layer, the focus-out watch and the focus return of one open overlay together, and ends them with one call. After an outside press, a popover's focus returns only once the press has ended, and only when the press focused nothing (returnFocus.whenUnfocused). openOverlaySession takes the layer's owner (default: its ignore elements, the triggers), backdrops and modal, and calls dismiss(reason, event) with the DOM event that caused it (DismissEvent: a keyboard, pointer or focus event; undefined, with the reason none, when a parent overlay closed).
  • Layers: the tree of a document's open overlays (nested overlays). pushLayer(doc, options) resolves the layer's parent when it opens: the newest open layer whose elements contain one of its owner() elements (its triggers), else the newest one containing the focused element, else none. backdrops are the elements that cover the page under the layer (a dialog's backdrop and viewport): a press on them is outside the layer and inside its parent. Escape goes to the newest layer only. An outside press keeps the deepest layer containing the press (its elements, or its ignore list) and its ancestors, and dismisses every other open layer, newest first. modal: true marks a layer that makes the page under it inert (a dialog): while it is the newest modal layer open, a press that is neither in it nor in one of its descendants counts as a press in its parent, so the layers it was opened from stay open and it, with the layers above them that are not its ancestors, gets onOutsidePress (a press on the inert page reaches no layer, and would otherwise dismiss them all). Layer.elementsAbove() gives the elements of the layer's descendants only (what a focus trap and a focus-out watch accept). When a layer is removed, its children move to its parent and each descendant still open gets onParentClose(), newest first. A tooltip, which is no layer, takes Escape before them (interceptEscape), so an enclosing dialog stays open.
  • Focus: the tabbable elements of a container, the focus trap, the initial focus, and whether the last interaction was the keyboard. trapFocus(container, allow, { holdOutsidePress }) (FocusTrapOptions): with holdOutsidePress, a press outside the trap and its child layers keeps focus where it is (its default focus change is prevented): an alert dialog's.
  • Inert and scroll lock: everything outside some elements made inert, the pointer blocked outside a modal menu (the body stops taking pointer events), and the document's scroll locked (counted, so nested locks release in order), keeping the scrollbar gutter.
  • Presence: the next frame and the end of an element's animations, for the data-starting-style and data-ending-style states.
  • Collection: the key maps of tabs, menus, radio groups and chips, list navigation, typeahead and the combobox's item helpers. radioKeyTarget(key, index, count, options) gives the radio an arrow key moves the focus and the check to: ArrowDown and ArrowRight the next, ArrowUp and ArrowLeft the previous, whatever the orientation, ArrowLeft and ArrowRight swapped with rtl; it passes over the radios skip returns true for (the disabled ones), wraps at the ends with loop, and returns null for another key or an end without loop. The tags' keys (Epic #91): tagGroupKeyTarget(event, index, count, options) (a TagGroup's: both axes' arrows, Home, End, select, remove), removalFocusIndex(count, removed, skip) (the next item after a removal, else the previous one), tagsInputInputKeyTarget and tagsInputTagKeyTarget (a TagsInput's Input and tags: Enter adds, Backspace at the start reaches the last tag, a tag's arrows, removals and edit) (TagGroup, TagsInput). A segmented control's Indicator (Epic #91): segmentIndicatorBox(root, item, rtl) gives the checked Item's box from the Root's padding box as the ten --segment-indicator-* variables, and placeSegmentIndicator(script), self-contained, writes them before hydration (SegmentedControl).
  • Positioning: a floating element anchored to its trigger, or to a point (virtualAnchor({ x, y, width?, height? }, contextElement?), a VirtualAnchor whose AnchorRect is in client coordinates: a context menu's pointer; its direction is read from contextElement) (Floating UI), on Base UI's sides: top, bottom, the logical inline-start and inline-end, and the physical left and right; a flipped side keeps the kind it was asked with. Its direction option (a direction, or a getter read at every placement) is a DirectionProvider's: the logical sides follow it. Without it, the anchor's computed direction, read at every placement.
  • Swipe: watchSwipe(element, options) follows a press on element that moves 6 px (SWIPE_LOCK_DISTANCE) along the axis of its directions and reports it as a swipe (onStart, onMove(movement), onEnd(end) with the release velocity in px per ms, or null when canceled): a move along the other axis, or one a scrollable element under the pointer takes (scroll containment), is let go; a touch that may be a swipe does not scroll the page; no swipe starts on a text control or an element marked data-swipe-ignore, nor, with the mouse, on an interactive element. swipeRelease(direction, end, size, snap?) decides the release: dismiss past half the size or on a flick (0.5 px per ms), or settle (on the closest snap point, resolveSnapPoints measuring them in px). swipeMovement damps a move past the fully open position, swipeProgress gives the share of the way to closed. A drawer's swipe (Drawer) and a toast's (Toast).
  • Toast queue: createToastManager({ limit, timeout }) holds an app's notifications outside every framework, so a plain module can import it: add, update, close, promise (a loading toast that becomes success or error), toasts() newest first with what a stack needs (limited past the limit, index, height, offsetY, closing), subscribe; each toast's timer runs while it shows and nothing pauses the queue. watchToastViewport(viewport, manager, { onExpandedChange }) is a Viewport's DOM side (the F6 landmark, the hover, focus and hidden-page pauses, two live regions that announce each shown toast by its priority, the focus off a closing toast); measureToastHeight(element) a toast's natural height (Toast).
  • Scroll area: createScrollArea(root, { direction, threshold, onStateChange }) is a ScrollArea's DOM side: the parts register as they mount (setPart("viewport" | "content" | "scrollbar-y" | ..., element)), and it measures them on mount, on scroll and on resize (ResizeObserver), writes the CSS variables (--scroll-area-overflow-* on the viewport, --scroll-area-thumb-* on the scrollbars, --scroll-area-corner-* on the root) and each thumb's transform, runs the scrollbars' thumb drag, track press and wheel, and reports the state (ScrollAreaState: the overflow and its edges, scrolling per axis, hovering, whether the viewport needs a tab stop). thumbGeometry, scrollFromStart and scrollForThumbOffset are its math (ScrollArea).
  • Carousel: carouselPages({ slideCount, slidesPerPage, slidesPerMove }) gives each page's first slide (the last page always full), with clampCarouselPage, slidesInView and stepCarouselPage (pure math). watchCarousel(root, group, options) is a carousel's DOM side, all native listeners: it scrolls the group to a page (scrollToPage, smooth unless reduced motion), reports the page a scroll the user made settled on (swipe) or a mouse drag released on (drag, over /pointer's drag session, snapping off while it runs), the hover (but over the AutoplayTrigger) and focus entering, and whether the group needs a tab stop (needsTabStop); slideScrollPosition and nearestCarouselPage are its geometry, RTL included. createRotationTimer(element) is the rotation's delay, paused with the time it had left (Carousel).
  • Color: the color model (color, below). An immutable Color in rgb, hsl or hsb with alpha, a plain object whose space is its discriminant; parseColor (hex, rgb(), hsl(), hsb(); null for anything else), formatColor (hex, hexa, the functions, css), convertColor (hsl and hsb directly, the others through rgb; rgb in whole numbers, hue, saturation, lightness and brightness to 2 decimals, alpha to 4), the channels' ranges and steps (colorChannelRange), their Intl text (formatColorChannel: "120°", "50%"), and the CSS gradients of a track (colorChannelGradient), an area (colorAreaBackground, exact layers) and a wheel (colorWheelGradient); the keys and geometry of an area and a wheel. Only the color components import it (ColorSlider, ColorArea, ColorWheel, ColorField).
  • Clipboard: writeClipboard(element, text) writes the text with the asynchronous Clipboard API of the element's window (navigator.clipboard.writeText) and returns its promise, which rejects where the API is missing (an insecure context) or the browser refuses the write: there is no execCommand fallback. announceText(region, text) replaces a live region's content with a new text node, so the same text said twice is announced twice ("" empties it) (Clipboard).
  • Files (Epic #106): a drop target for files and a FileUpload's rules. watchFileDrop(element, { disabled, onDropTargetChange, onFiles, onActivate }) makes an element a target: a drag of files (dragHasFiles: dataTransfer.types holds "Files") counted across its children shows the copy effect and its drop hands the files over, a paste hands the clipboard's files over, a click, Enter or Space is a press; while disabled a drag shows none and its drop is canceled. openFileDialog(element, { accept, multiple, capture }, onFiles) opens the browser's dialog through a file input created for the press and never put in the document. acceptsFile(file, accept) reads accept as a file input does (MIME types, type/*, .ext), acceptFiles(files, accept, multiple) splits a drop, acceptAttribute(accept) writes the attribute. checkFiles(value, files, rules) checks a pick (accept, maxFiles, minFileSize, maxFileSize, validate) into the new value, the accepted and the rejected files with their reasons (invalid-type, too-large, too-small, the app's, too-many). formatFileSize(bytes, locale) writes Intl.NumberFormat's short decimal units (1.5 kB), and assignFiles(input, files) puts files into a file input through a DataTransfer, so the native form submits them, and fieldFiles(files) gives a Field files it can compare (by name, size, type and date) (DropZone, FileUpload).
  • Pagination range: paginationRange({ page, count, siblingCount, boundaryCount }) gives the pages and ellipses in order (every page while they fit, else a constant number of items with the window kept whole near the ends, no ellipsis for a single page); pageCount({ count, total, pageSize }) and clampPage(page, count) (Pagination).
  • Pointer and hover: pointer drags, a submenu's safe area and hover bridge, hover intent and delay groups. watchLongPress(element, { delay, moveTolerance, pointerTypes, onLongPress }) (LongPressOptions; defaults 500 ms, 10 px, touch only) calls onLongPress(point, event) once a press is held still that long; a move beyond the tolerance, a release or a cancel stops it, and the click and contextmenu that follow a long press are swallowed. It returns the cleanup.
  • Form: the hidden inputs' form bridge (a reset, and focus on the primitive when its input is the form's first invalid control), the field's validity and its rules (the required rule, the modes), createFieldValidator for async validate (the latest run wins, a value already validated is reused), the Error's matching and messages, and a Form's pieces: guardFormSubmit (a capture listener that blocks a submission before any other listener), firstInDocumentOrder, focusFieldControl, and the server errors (formErrorsFor, withoutFormErrors). A tags input's rules (Epic #91): takeTags(value, text, rules, whole) offers a text as tags (split by the delimiter, trimmed, refused as a duplicate, past max or by validate, the refused texts and the typed rest left for the input), typesDelimiter(previous, next, delimiter, inserted) tells whether an input typed the delimiter (only then is a typed text offered), editTag(value, index, text, rules) ends a tag's edit (TagsInput).
  • Direction: getDirection(element, provided), the direction a provider gives, else the element's computed direction.
  • Number: a number field's text and steps (Epic #52). formatNumber(value, { locale, format }) writes a value ("" for null; every decimal kept without a format); parseNumber(text, options) reads the locale's writing back: its digits (Arabic-Indic, Extended Arabic-Indic and ASCII in every locale), its group and decimal separators (. or , also read as the decimal point where the locale groups with neither), any minus or plus sign and the bidirectional marks around it, the currency, unit and percent text (a percent format reads 25% as 0.25), an accounting negative in parentheses; null for a text with no digit, NaN for one that is no number. isNumberText says whether a text holds only those characters (a field refuses the others as they are typed). stepNumber(value, amount, { min, max, snapOnStep }) steps and clamps with no floating-point noise (an empty field starts at 0). watchAutoRepeat(button, { onStep, onEnd, delay, interval }) steps at a press, then every 60 ms after 400 ms (a click no press started steps once; a mouse press keeps the focus), and calls onEnd once the press is over. watchScrub(element, { direction, pixelSensitivity, onStart, onScrub, onEnd, onCursor }) reports steps per pixels moved, under the pointer lock for a mouse, with the virtual cursor's point wrapped around the viewport.
  • Selection: the collections mechanism (Epic #55), pure functions over a list's options; the framework holds the value, the focus and the anchor. createListModel(nodes) orders the options ({ key, textValue, disabled }) and indexes them. applySelection(model, state, change, { mode, behavior }) gives the next { selected, anchor } for a toggle, a replace, a range (from the anchor, or from a key) or all (none when every enabled option already is), in none, single or multiple mode, toggle or replace behaviour (the APG's two models): a disabled option is never selected and a range passes over it; the selection is in the list's order. listKeyTarget(event, model, index, options) gives the option a key focuses and the selection change it makes (the arrows of the orientation, mirrored in RTL, Home, End, PageUp and PageDown through page, the typeahead through typeahead, Space, Enter, Shift, Ctrl or Meta, Ctrl+A); listPressSelection a press's; pageTarget(elements, index, delta, container, orientation) the option a visible page away.
  • Range: slider math and keys, and a progress bar's value. progressValue(value, options) clamps the value to [min, max] and returns it with its percent (0 to 100), its status (ProgressStatus: indeterminate for null, complete at max, else progressing) and its formatted value: format and locale for Intl.NumberFormat, a percentage of the range without format, "" when indeterminate. A rating's steps (Epic #91): ratingKeyTarget(key, value, { count, allowHalf, rtl, loop }) gives the value an arrow, Home or End moves to (steps of 1 or 0.5, wrapping with loop, never to 0), ratingValueAt(index, fraction, allowHalf) the value a pointer chooses on a star, and ratingItemState(index, value, displayed) a star's checked, highlighted and half (Rating).
  • Image: watchImageStatus(element, src, options, onStatus) loads an image outside the document, through the element's window (a new Image() of its ownerDocument.defaultView), with the img's srcSet, sizes, crossOrigin and referrerPolicy (ImageSourceOptions), and reports its status (ImageLoadingStatus): loading, then loaded or error. No src and no srcSet is an error. A cached image reports at once, synchronously and with no loading: loaded, or error when it has no size. It returns the cleanup, after which no status is reported. Avatar's Image is built on it.
  • Virtual: the virtualizer of the virtual lists, written in-house. virtualLayout({ count, size, gap, offset, viewport, overscan, pinned, sticky }) is pure: the rows to render for a scroll position (the rows in view, overscan rows beyond each end, the pinned rows and the sticky row of the group in view), each { index, start, size, spaceBefore, sticky }, with the list's totalSize, the room after the last row (spaceAfter) and the first and last rows in view. rowStarts, rowAt, activeSticky and pageIndex (the row a page away, by the sizes) are its pieces. createVirtualizer(options) runs it over the DOM: attach(list, scroller?) watches the scroll container (the list when it scrolls, else its nearest scrolling ancestor, scrollContainer), its size and the list's row-gap; measure(index, element) measures a rendered row now and on every resize (without it, every row is estimateSize); scrollToIndex(index, align) (auto, start, center, end) scrolls to a row and updates the range at once; update(options), range(), pageIndex(from, delta); onChange asks for a new render only when the rows or their room change. A measured row above the view that changes size moves the scroll position by the change, so the rows in view stay still. Sizes are layout sizes (offsetHeight), which a popup's opening scale never changes.
  • Async list: createAsyncList({ load, filterText, onChange }), framework-free: reload() loads the first page, loadMore() the next one (with the cursor the previous page returned; nothing while one loads or when there is none), setFilterText(text) the first page for a new text, abort() the load in flight; state() is { items, filterText, status, error, hasMore }. The loader gets { signal, filterText, cursor } and returns { items, cursor? }; a new load aborts the one in flight and a stale page is never used. Each framework wraps it in its own state (async list).
  • Command (Epic #104): the command palette's scorer and keys. commandScore(value, search, keywords) compares case- and accent-insensitively and returns 1 for no text or the whole text, 0.9 for a prefix, 0.8 for a word prefix (words split at spaces and -_/.:), 0.7 when every word of the search starts a word of the text in order, 0.6 for a substring, else 0; a keyword's score counts at 0.95. commandItemScore scores one Item with a filter, commandMatches(entries, search, filter) gives a list's matching entries and their scores (the virtual list's), bestMatch(scores, disabled) the best-scoring enabled index, the first among equals, and commandKeyTarget maps the Input's keys (the arrows, Home, End) to the next highlight.
  • Cascade (Epic #104): a cascade select's tree, pure functions. cascadeLevels(items, path) gives the items of each open level along a path, cascadePathItems(items, path) the items of a path (its labels), hasCascadeChildren(item) whether an item is a parent, and cascadeKeyAction(event, rtl) maps a key to its action (the inline-end and inline-start keys swapped in RTL).
  • Id, date: document-unique ids, and plain dates with their math and locale data from Intl (imported only by the calendar and picker entries).
  • Time (Epic #73): PlainTime ({ hour, minute, second, millisecond }) and PlainDateTime (a PlainDate and a PlainTime in one flat object, so the date math takes it), with no time zone: compareTimes, compareDateTimes (a PlainDate counts as its midnight), addTime (carrying, wrapping around midnight), cycleTime (one field, wrapping, carrying nothing), addDateTime, the ISO text (toIsoTime: 14:30, the shortest exact form unless a precision is given; toIsoDateTime; their fromIso* parsers) and the clock's now (currentTime, currentDateTime). Written in-house on Intl and Date, no date library.
  • Segments (Epic #73): the segment editing of the date and time fields, pure functions. segmentFormat({ locale, kind, granularity, hourCycle }) reads a field's format from Intl.DateTimeFormat#formatToParts in UTC (the order, the literals, the hour cycle h11, h12, h23 or h24, the locale's digits, the day period texts, and each segment's name from Intl.DisplayNames); dateSegments(format, values, edit) gives the segments to render (a placeholder shows one – per digit). typeSegment types one character (a digit continues the segment's digits and reports advance once no further digit fits; a day period takes its first letter), eraseSegment erases one, stepSegment and segmentToEdge step with a wrap inside the segment (a 12-hour hour stays in its half of the day), and segmentKeyDown maps the keys to those. segmentTarget(segment, move) finds the segment a move reaches, ArrowLeft and ArrowRight measured on screen; focusOnLabelPress focuses the first segment from a Field's label.

Color

@fragiola/primitives/color holds the value the color components share, so an app (or a color picker built of several controls) keeps one color and hands it to each of them:

import { convertColor, formatColor, parseColor, setColorChannel } from "@fragiola/primitives/color";

const color = parseColor("#336699"); // { space: "rgb", red: 51, green: 102, blue: 153, alpha: 1 }
const hsl = convertColor(color, "hsl"); // { space: "hsl", hue: 210, saturation: 50, lightness: 40, alpha: 1 }
formatColor(setColorChannel(hsl, "lightness", 60), "hex"); // "#6699cc"

A control takes Color | string and reports a Color in the space it edits. The precision of a conversion is fixed per channel and unit-tested on round trips: every rgb color goes through hsl and hsb and back unchanged. The channel names are not provided (no text): name each control. openEyeDropper(element) opens the browser's eyedropper (Chromium's EyeDropper) and resolves with the picked color, or null when it is cancelled or missing (supportsEyeDropper(element) tells which): a ColorPicker's EyeDropperTrigger uses them.

Calendar systems

@fragiola/primitives/calendar-systems exports one object per system, each importable alone: gregory, buddhist, japanese, roc, persian, indian, islamicCivil, islamicTbla, islamicUmalqura, hebrew (13 months in a leap year), coptic, ethiopic and ethioaa (13 months). Every date component takes one as its calendar and injects it: no component imports the entry, so the systems you do not pass are not in your bundle, and a component never maps a locale's -u-ca- keyword to a system (it would bundle every system).

import { persian } from "@fragiola/primitives/calendar-systems";
import { Calendar } from "@fragiola/primitives-react/calendar";

<Calendar.Root calendar={persian} locale="fa-IR" />;
  • Values stay ISO. A day calendar, picker or field still holds a PlainDate (or PlainDateTime) and submits 2026-11-20; min, max and isDateUnavailable take ISO dates. The system is how the dates are shown, typed and moved through: the grid's months, the heading and cell names, Page Up and Page Down, the segments' year, month (up to 13) and day, and an editable era where the system has several (Japanese, ROC, Gregorian).
  • Month and year calendars and pickers hold the system's months and years ({ year: 1405, month: 8 } is Aban 1405); a page is one of its years, 12 or 13 months. A form submits the ISO date of the first day with the system's annotation (RFC 9557): 2026-10-23[u-ca=persian].
  • Computed on Intl, no data table: the systems read their months from Intl.DateTimeFormat#formatToParts, so a system is only as good as the engine's ICU (Chromium and Node 24+ have all 13). A CalendarSystem also exposes the math (fields, fromFields, monthsInYear, daysInMonth, addMonths, monthGrid, ...) for a primitive of your own.
  • The system carries what it changes: the components call it through one hook per concern (its month math, its units(kind), the segments' segment* hooks), so an app that passes no calendar pays only for those calls (bundle size).

Time zones

@fragiola/primitives/time-zone holds zoned dates and times with Temporal's DST rules, on Intl. A ZonedDateTime is a PlainDateTime (the wall-clock time) with its IANA timeZone and its offset from UTC in milliseconds. DateField, DateRangeField, DatePickerInput and DateRangePickerInput take a zone as their timeZone, from timeZone(id), and inject it like a calendar system:

import { timeZone } from "@fragiola/primitives/time-zone";
import { DateField } from "@fragiola/primitives-react/date-field";

const newYork = timeZone("America/New_York");
<DateField.Root granularity="minute" timeZone={newYork} />;
  • Values are ZonedDateTimes in the field's zone; a value from another zone is shown at the same instant. A time granularity shows the zone's name ("EST", then "EDT" across the change) as a segment that is read but not edited; hideTimeZone leaves it out.
  • The segments keep the wall time typed; the value resolves it with disambiguation (compatible by default: 2:30 AM on a spring-forward night is 3:30 AM, 1:30 AM on a fall-back night the first one; earlier, later, or reject for no value).
  • Forms submit the zoned ISO text, 2026-11-01T01:30-05:00[America/New_York], from a type="text" hidden input: required still works, out of range has no native message.
  • The functions: toZoned (a wall time in a zone, with a disambiguation), toTimeZone (the same instant in another zone), fromInstant, toInstant, compareZoned, addZoned, cycleZoned, offsetAt, localTimeZone, the ISO text (toIsoZoned, fromIsoZoned) and formatTimeZoneName (the zone's short name at an instant, from Intl). Zone names come from each engine's ICU: a server's may differ from the browser's (server rendering).
  • The zone carries what it changes: a field calls its hooks (segmentOptions, segmentText, wallTime, segmentsToDateTime) and a picker its choose (a chosen wall time, reject read as compatible), so a field given no zone pays only for those calls.