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
| entry | exports |
|---|---|
@fragiola/primitives/async-list | createAsyncList, AsyncList, AsyncListOptions, AsyncListLoad, AsyncListPage, AsyncListRequest, AsyncListState, AsyncListStatus |
@fragiola/primitives/cascade | cascadeKeyAction, CascadeKeyAction, cascadeLevels, cascadePathItems, hasCascadeChildren, CascadeItem |
@fragiola/primitives/calendar-systems | buddhist, coptic, ethioaa, ethiopic, gregory, hebrew, indian, islamicCivil, islamicTbla, islamicUmalqura, japanese, persian, roc, CalendarSystem, CalendarId, CalendarDateFields, CalendarFieldsInput, CalendarYearMonth, CalendarUnit, CalendarUnits |
@fragiola/primitives/collection | scrollIntoViewWithin, 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/command | commandScore, commandItemScore, commandMatches, bestMatch, commandKeyTarget, CommandEntry, CommandFilter, CommandMatches |
@fragiola/primitives/color | Color, 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/date | PlainDate, 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-year | PlainYearMonth, PlainYear, YearMonthRange, YearRange, monthIndex, fromMonthIndex, currentYearMonth, toIsoYearMonth, toIsoYear, UNIT_PAGE_SIZE, unitPageStart, unitRows, unitKeyTarget, UnitKeyOptions, formatMonthName, formatYearMonth, formatYear, formatYearSpan |
@fragiola/primitives/direction | getDirection, Direction |
@fragiola/primitives/file | watchFileDrop, dragHasFiles, FileDropOptions, FileDropReason, openFileDialog, FileDialogOptions, acceptsFile, acceptFiles, acceptAttribute, FileAccept, FileLike, checkFiles, CheckedFile, FileCheck, FileRejection, FileRejectionReason, FileRules, formatFileSize, assignFiles, fieldFiles |
@fragiola/primitives/focus | focusInitial, trapFocus, getTabbables, nextTabbableAfter, previousTabbableBefore, isKeyboardModality, FocusTrapOptions |
@fragiola/primitives/form | bridgeForm, 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/hover | createHoverIntent, HoverIntent, createDelayGroup, DelayGroup |
@fragiola/primitives/id | createId |
@fragiola/primitives/image | watchImageStatus, ImageLoadingStatus, ImageSourceOptions |
@fragiola/primitives/inert | inertOutside, blockOutsidePointer |
@fragiola/primitives/layers | pushLayer, Layer, LayerOptions, watchFocusOutside, interceptEscape |
@fragiola/primitives/number | formatNumber, numberFormatOptions, NumberFormatOptions, parseNumber, isNumberText, stepNumber, clampNumber, NumberStepOptions, watchAutoRepeat, AutoRepeatOptions, watchScrub, ScrubOptions, ScrubPoint |
@fragiola/primitives/overlay | openOverlaySession, OverlaySession, OverlaySessionOptions, DismissReason, DismissEvent |
@fragiola/primitives/carousel | carouselPages, CarouselPagesOptions, clampCarouselPage, slidesInView, stepCarouselPage, CarouselOrientation, groupScrollPosition, nearestCarouselPage, slideScrollPosition, createRotationTimer, RotationTimer, CarouselController, CarouselWatchOptions, watchCarousel |
@fragiola/primitives/clipboard | writeClipboard, announceText |
@fragiola/primitives/pagination | paginationRange, PaginationItem, PaginationRangeOptions, pageCount, PageCountOptions, clampPage |
@fragiola/primitives/pointer | startDrag, DragSessionOptions, isInSafeArea, Point, isInHoverBridge, trackHoverBridge, HoverBridgeCallbacks, watchPointerExit, LongPressOptions, watchLongPress |
@fragiola/primitives/positioning | anchorFloating, AnchorOptions, Side, Align, toPlacement, fromPlacement, AnchorRect, VirtualAnchor, virtualAnchor |
@fragiola/primitives/presence | nextFrame, waitForAnimations, isAnimating, measurePanelSize, freezePanelSize, panelSizeVariables, PanelSize, watchBeforeMatch, BeforeMatchOptions |
@fragiola/primitives/range | snapToStep, fractionAlong, valueAtFraction, valueToPercent, nearestThumb, moveThumb, thumbBounds, RangeOptions, ThumbOptions, sliderKeyTarget, SliderKeyOptions, progressValue, ProgressOptions, ProgressStatus, ProgressValue, ratingKeyTarget, RatingKeyOptions, ratingValueAt, ratingItemState, RatingItemState |
@fragiola/primitives/scroll-area | createScrollArea, ScrollAreaController, ScrollAreaOptions, ScrollAreaOrientation, ScrollAreaPart, ScrollAreaState, ScrollAreaThreshold, ScrollAreaThresholdInput, initialScrollAreaState, normalizeScrollAreaThreshold, thumbGeometry, ThumbGeometry, ThumbGeometryInput, scrollFromStart, scrollForThumbOffset, MIN_THUMB_SIZE |
@fragiola/primitives/scroll-lock | lockScroll |
@fragiola/primitives/segments | segmentFormat, 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/selection | createListModel, ListModel, ListNode, applySelection, inModelOrder, sameSelection, SelectionBehavior, SelectionChange, SelectionMode, SelectionOptions, SelectionState, listKeyTarget, listPressSelection, ListKeyEvent, ListKeyOptions, ListKeyResult, pageTarget, rowTarget |
@fragiola/primitives/swipe | watchSwipe, SwipeOptions, SwipeDirection, SwipeMovement, SwipeEnd, SWIPE_LOCK_DISTANCE, swipeRelease, SwipeOutcome, swipeMovement, swipeProgress, swipeDisplacement, resolveSnapPoints, SnapPoint, ResolvedSnapPoint |
@fragiola/primitives/time | addDateTime, 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-zone | timeZone, TimeZone, ZonedDateTime, Disambiguation, offsetAt, fromInstant, toInstant, toZoned, toTimeZone, compareZoned, addZoned, cycleZoned, localTimeZone, toIsoZoned, toIsoOffset, fromIsoZoned, formatTimeZoneName |
@fragiola/primitives/toast | createToastManager, ToastManager, ToastManagerOptions, ToastObject, ToastOptions, ToastPriority, ToastPromiseOptions, ToastUpdate, watchToastViewport, ToastViewportWatch, ToastViewportWatchOptions, measureToastHeight |
@fragiola/primitives/virtual | createVirtualizer, 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).openOverlaySessiontakes the layer'sowner(default: itsignoreelements, the triggers),backdropsandmodal, and callsdismiss(reason, event)with the DOM event that caused it (DismissEvent: a keyboard, pointer or focus event;undefined, with the reasonnone, 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 itsowner()elements (its triggers), else the newest one containing the focused element, else none.backdropsare 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 itsignorelist) and its ancestors, and dismisses every other open layer, newest first.modal: truemarks 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, getsonOutsidePress(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 getsonParentClose(), 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): withholdOutsidePress, 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-styleanddata-ending-stylestates. - 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 withrtl; it passes over the radiosskipreturnstruefor (the disabled ones), wraps at the ends withloop, and returnsnullfor another key or an end withoutloop. 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),tagsInputInputKeyTargetandtagsInputTagKeyTarget(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, andplaceSegmentIndicator(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?), aVirtualAnchorwhoseAnchorRectis in client coordinates: a context menu's pointer; its direction is read fromcontextElement) (Floating UI), on Base UI's sides:top,bottom, the logicalinline-startandinline-end, and the physicalleftandright; a flipped side keeps the kind it was asked with. Itsdirectionoption (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 onelementthat moves 6 px (SWIPE_LOCK_DISTANCE) along the axis of itsdirectionsand reports it as a swipe (onStart,onMove(movement),onEnd(end)with the release velocity in px per ms, ornullwhen 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 markeddata-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,resolveSnapPointsmeasuring them in px).swipeMovementdamps a move past the fully open position,swipeProgressgives 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(aloadingtoast that becomessuccessorerror),toasts()newest first with what a stack needs (limitedpast the limit,index,height,offsetY,closing),subscribe; each toast's timer runs while it shows and nothingpauses 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,scrollingper axis,hovering, whether the viewport needs a tab stop).thumbGeometry,scrollFromStartandscrollForThumbOffsetare its math (ScrollArea). - Carousel:
carouselPages({ slideCount, slidesPerPage, slidesPerMove })gives each page's first slide (the last page always full), withclampCarouselPage,slidesInViewandstepCarouselPage(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);slideScrollPositionandnearestCarouselPageare 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
Colorin rgb, hsl or hsb with alpha, a plain object whosespaceis its discriminant;parseColor(hex,rgb(),hsl(),hsb();nullfor 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), theirIntltext (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 noexecCommandfallback.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.typesholds"Files") counted across its children shows thecopyeffect 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 showsnoneand 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)readsacceptas 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)writesIntl.NumberFormat's short decimal units (1.5 kB), andassignFiles(input, files)puts files into a file input through aDataTransfer, so the native form submits them, andfieldFiles(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 })andclampPage(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) callsonLongPress(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 andcontextmenuthat 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),
createFieldValidatorfor asyncvalidate(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, pastmaxor byvalidate, 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 computeddirection. - Number: a number field's text and steps (Epic #52).
formatNumber(value, { locale, format })writes a value (""fornull; 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 reads25%as0.25), an accounting negative in parentheses;nullfor a text with no digit,NaNfor one that is no number.isNumberTextsays 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 at0).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 callsonEndonce 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 atoggle, areplace, arange(from the anchor, orfroma key) orall(none when every enabled option already is), innone,singleormultiplemode,toggleorreplacebehaviour (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 throughpage, the typeahead throughtypeahead, Space, Enter, Shift, Ctrl or Meta, Ctrl+A);listPressSelectiona 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:indeterminatefornull,completeatmax, elseprogressing) and its formatted value:formatandlocaleforIntl.NumberFormat, a percentage of the range withoutformat,""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 withloop, never to0),ratingValueAt(index, fraction, allowHalf)the value a pointer chooses on a star, andratingItemState(index, value, displayed)a star'schecked,highlightedandhalf(Rating). - Image:
watchImageStatus(element, src, options, onStatus)loads an image outside the document, through the element's window (anew Image()of itsownerDocument.defaultView), with theimg'ssrcSet,sizes,crossOriginandreferrerPolicy(ImageSourceOptions), and reports its status (ImageLoadingStatus):loading, thenloadedorerror. Nosrcand nosrcSetis anerror. A cached image reports at once, synchronously and with noloading:loaded, orerrorwhen 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,overscanrows beyond each end, thepinnedrows and thestickyrow of the group in view), each{ index, start, size, spaceBefore, sticky }, with the list'stotalSize, the room after the last row (spaceAfter) and the first and last rows in view.rowStarts,rowAt,activeStickyandpageIndex(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'srow-gap;measure(index, element)measures a rendered row now and on every resize (without it, every row isestimateSize);scrollToIndex(index, align)(auto,start,center,end) scrolls to a row and updates the range at once;update(options),range(),pageIndex(from, delta);onChangeasks 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 returns1for no text or the whole text,0.9for a prefix,0.8for a word prefix (words split at spaces and-_/.:),0.7when every word of the search starts a word of the text in order,0.6for a substring, else0; a keyword's score counts at0.95.commandItemScorescores 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, andcommandKeyTargetmaps 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, andcascadeKeyAction(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 }) andPlainDateTime(aPlainDateand aPlainTimein one flat object, so the date math takes it), with no time zone:compareTimes,compareDateTimes(aPlainDatecounts 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; theirfromIso*parsers) and the clock's now (currentTime,currentDateTime). Written in-house onIntlandDate, 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 fromIntl.DateTimeFormat#formatToPartsin UTC (the order, the literals, the hour cycleh11,h12,h23orh24, the locale's digits, the day period texts, and each segment's name fromIntl.DisplayNames);dateSegments(format, values, edit)gives the segments to render (a placeholder shows one–per digit).typeSegmenttypes one character (a digit continues the segment's digits and reportsadvanceonce no further digit fits; a day period takes its first letter),eraseSegmenterases one,stepSegmentandsegmentToEdgestep with a wrap inside the segment (a 12-hour hour stays in its half of the day), andsegmentKeyDownmaps the keys to those.segmentTarget(segment, move)finds the segment a move reaches, ArrowLeft and ArrowRight measured on screen;focusOnLabelPressfocuses 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(orPlainDateTime) and submits2026-11-20;min,maxandisDateUnavailabletake 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 fromIntl.DateTimeFormat#formatToParts, so a system is only as good as the engine's ICU (Chromium and Node 24+ have all 13). ACalendarSystemalso 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 nocalendarpays 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;hideTimeZoneleaves it out. - The segments keep the wall time typed; the value resolves it with
disambiguation(compatibleby 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, orrejectfor no value). - Forms submit the zoned ISO text,
2026-11-01T01:30-05:00[America/New_York], from atype="text"hidden input:requiredstill works, out of range has no native message. - The functions:
toZoned(a wall time in a zone, with adisambiguation),toTimeZone(the same instant in another zone),fromInstant,toInstant,compareZoned,addZoned,cycleZoned,offsetAt,localTimeZone, the ISO text (toIsoZoned,fromIsoZoned) andformatTimeZoneName(the zone's short name at an instant, fromIntl). 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 itschoose(a chosen wall time,rejectread ascompatible), so a field given no zone pays only for those calls.