Skip to content

Latest commit

 

History

History
948 lines (766 loc) · 48.2 KB

ui-usage.md

File metadata and controls

948 lines (766 loc) · 48.2 KB

@pathscale/ui — Usage Reference

This is the source of truth for @pathscale/ui usage conventions, for humans and agents alike, and for every consuming application. Those apps link here rather than keeping their own copy — one library, one set of conventions, no drift.

SolidJS component library, HeroUI-parity API, daisyUI-style theming. 103 public component families.

This file is how to USE the library (as a consumer, or when writing demos and examples). For modifying the library itself, read ../CLAUDE-INTERNALS.md. Repo analysis: ../ANALYSIS.md.

Install & setup

bun add @pathscale/ui solid-layouts
bun add -d rsbuild-plugin-solid-layouts
import { Button, Flex, Dialog, toast } from "@pathscale/ui";   // everything is in the root barrel
import "@pathscale/ui/index.css";                              // tokens + themes + base + icons

Subpath exports also exist: ./components/*, ./primitives/*, ./hooks/*, ./motion, ./styles/*.

componentFamilies is the canonical public visual-family inventory. Documentation and showcase applications can import it with ComponentFamily and ComponentFamilyId from the root barrel, then fail their own build when a newly shipped family has no page or example.

Layout components require the application compiler before the normal Solid transform. See Layouts for the Rsbuild configuration, exact failure behavior, and porting report.

Theming

  • Two themes: light (default when no attribute) and dark. Switch: document.documentElement.setAttribute("data-theme", "dark").
  • Tokens are CSS vars: --color-primary(/-content), --color-secondary, --color-accent, --color-neutral, --color-info/success/warning/error, --color-danger, surfaces --color-base-100/200/300, --color-base-content, HeroUI-style --color-default(/-foreground/-hover), --color-background/foreground, daisy short aliases --b1/--b2/--b3/--bc, radii --radius-selector/-field/-box, and the --glass-* set: six colours the theme owns, plus the rest derived from three numbers by applyGlassTokens (see Glass).
  • src/index.css has a Tailwind v4 @theme block, so in a Tailwind v4 app bg-primary, text-base-content, bg-base-100 etc. work.
  • Any component accepts dataTheme prop → rendered as data-theme attr (scoped theming).

Glass

material="glass" makes a surface out of what is behind it rather than a fill. It is on Card, Dialog.Content, Drawer.Content, Popover.Content, Menu and Navbar; solid is the default everywhere, so nothing changes until it is asked for.

The look is driven by the --glass-* custom properties, and you do not set those by hand — applyGlassTokens derives all twenty-five from three numbers:

import { applyGlassTokens, GLASS_DEFAULTS, GLASS_LIMITS } from "@pathscale/ui";

applyGlassTokens({ blur: 9, refraction: 0.31, depth: 24 }, "dark");
  • blur (0–50px) how far the backdrop is smeared
  • refraction (0–0.4) how much the surface asserts its own tint, border and highlight
  • depth (0–30) how far off the page it sits: glow, sheen, shadow

GLASS_LIMITS carries those ranges and GLASS_DEFAULTS the per-mode defaults, so a settings panel should read both from here rather than restating them. resolveGlassTokens returns the same set as an object, and glassTokensToCss as a declaration block for a theme that wants them baked in.

Pass a complete tuning. Three of the derived tokens are read without a CSS fallback, and an undefined custom property makes CSS drop the whole declaration rather than fall back — so a partial set renders a surface with no background at all rather than a plainer one.

Nested glass is flattened to one pane on purpose, and both prefers-reduced-transparency and a browser without backdrop-filter fall back to a more opaque fill.

Components require solid-layouts >=0.2.4 so caller styles reach their root elements reactively.

Component conventions (consumer-facing)

  • Booleans are HeroUI-style is* where they exist: isDisabled, isInvalid, isIconOnly, isInteractive. Native disabled is also honored.

    Not every is* name in older guidance is real. Overlays take open, not isOpen -- isOpen is the context accessor a compound part reads, not a prop you pass. Button has no isPending; a pending button is state="loading", from the shared State vocabulary.

  • Sizes and colour-ish props are per-component, not a shared union in practice. ComponentSize and ComponentColor are declared in src/components/types.ts with the full unions, but they are not re-exported from the root barrel, so consumers cannot import them, and individual components narrow them.

    Button separates shape from intent, and the two are different props: variant is solid | soft | outline | ghost | plain, flavor is neutral | primary | secondary | accent | destructive | success | warning | info, and state is the shared State. So the call to action is flavor="primary", not variant="primary" — this line previously listed primary | secondary | tertiary | outline | ghost | danger | danger-soft as the variants, which mixed the two vocabularies and named four values that do not exist.

    Badge, Chip, Avatar, Spinner, Switch, Meter and the progress components take color. Read the component's own props before assuming.

  • class is the escape hatch. className is gone: every component takes UIBaseProps, which carries class only, so a className you pass is an unknown prop and the class is silently dropped. Prefer semantic component parameters over either; solid-layouts-lint --porting --layouts @pathscale/ui reports overrides that should move into recipes.

  • Controlled/uncontrolled triples: open/defaultOpen/onOpenChange, value/defaultValue/onChange, selectedKey/defaultSelectedKey/onSelectionChange. Event callbacks pass values, not events.

  • Breaking in 3.1 — Switch, Checkbox and PasswordField. The rule above was already the documented contract, and three controls did not follow it. Switch.onChange and Checkbox.onChange were the input's native onChange and handed you an Event, while Slider, RadioGroup and CheckboxGroup handed you a value under the same name; PasswordField delivered a string from a prop called onInput, matching neither. Swapping one field for another therefore changed what your handler received, silently.

    control was now
    Switch onChange(Event) onChange(checked: boolean)
    Checkbox onChange(Event) onChange(checked: boolean)
    PasswordField onInput(value) onChange(value: string)

    The native event is still available on Switch and Checkbox as onNativeChange, and it is still where preventDefault() vetoes the toggle — which now also suppresses onChange. A Checkbox inside a CheckboxGroup now fires its own onChange as well; previously that path reported nothing to the box's own caller.

  • Breaking in 3.1 — Select rejects competing control sources. Passing both value and selectedKeys (or both defaultValue and defaultSelectedKeys) throws. It used to prefer selectedKeys and silently ignore the other, so a stale prop could win with nothing to say which had been dropped.

  • Breaking in 3.1 — Card.state. Typed as the shared State (default | loading | error | invalid | disabled | hidden) while the recipe implements info | success | warning | danger. The two had no member in common: every accepted value did nothing, every implemented value was a type error. Now CardState, which is what it renders. A card is not a form control; interactivity is isInteractive.

  • Behaviour change — an interactive Card is a button only when it has something to press. isInteractive gave every card role="button" and tabindex="0", so the ordinary way to make a whole card navigate, <a href><Card isInteractive /></a>, produced a button inside a link with the same name and the same box: invalid HTML, announced twice, and a press by coordinate landing on whichever was on top. Measured on one site as every card on it. isInteractive now means what it looks like it means, the hover and press affordance; the button role and the keyboard activation arrive with an onClick.

    So a card inside a link is fixed where it stands, with nothing to edit. A card that carried a handler is unchanged. What does change is a card whose click was handled by an ancestor rather than by the card: it keeps the affordance and loses the role and the tab stop, so move the handler onto the Card.

    Better still, if the card navigates, give it the href and drop the wrapper:

    <Card href="/pricing" isInteractive>…</Card>

    Card then renders a real anchor, so middle-click, open-in-new-tab and copy link address work, and there is nothing left to nest it inside. role is also honoured properly now: role="presentation" no longer leaves tabindex="0" behind.

  • Slider.onChange reports continuous values. Optional Slider.onChangeEnd reports the final changed value once on pointer release, pointer cancellation, keyboard release, or blur fallback. Its visible label is also copied to the semantic slider's aria-label, because not every renderer resolves aria-labelledby across a visually hidden label.

  • FirefoxPWABanner waits 2000ms before appearing by default. Pass showDelayMs when the surrounding onboarding flow needs a different delay; the same option is available as ImmersiveLanding.firefoxPWAConfig.showDelayMs. The banner still applies its Firefox, standalone-mode, and dismissal checks before starting that delay. Give it an id to derive stable IDs for its banner and actions; ImmersiveLanding derives this base from its own id unless firefoxPWAConfig.id overrides it.

  • Give PWAInstallPrompt an id to derive stable IDs for its dialog and actions. ImmersiveLanding derives this base from its own id unless pwaConfig.id overrides it.

  • ImmersiveLanding.id is placed on the component root. Its page viewport, arrows, navigation, optional PWA prompts, and cookie controls remain inside that ownership subtree and derive their control IDs from the same base.

  • Give CookieConsent an id when its controls need stable authored IDs. Its banner, dialog, preference inputs, and actions derive unique IDs from that base. ImmersiveLanding forwards cookieConfig.id and otherwise derives the cookie family from the landing's own id.

  • Collapsible.Content retains closed content by default. Set keepMounted={false} to mount it only while expanded; the check is reactive, so it mounts and unmounts as the state changes.

  • Popover accepts anchorRect as a rectangle or rectangle accessor when content must be positioned without a trigger element.

  • Compound components: Dialog.Trigger, Tabs.List, Select.Option, etc. (Object.assign statics; also exported flat: AccordionRoot, AlertTitle, …). Parts are styleable/testable via data-slot="..." and state attrs (data-open, data-selected, data-invalid).

  • Tabs does not require ResizeObserver. When it is unavailable, selection and keyboard behavior remain active and the indicator is measured on selection, mount, and window resize.

  • Flex, Grid, Navbar and Text take a polymorphic as, and Card and Button take an href that makes them anchors. Nothing else is polymorphic; reach for the component that renders the element you want rather than repointing one that does not.

  • When a Button or Card link opens with target="_blank", it keeps caller rel tokens and adds noopener noreferrer.

<Flex direction="col" gap="sm">
  <Button flavor="primary" size="md" state={saving() ? "loading" : "default"}>
    Save
  </Button>
</Flex>

This example used to read variant="primary" isPending={saving()}, and none of it was real: variant is solid | soft | outline | ghost | plain, so primary is a flavor; there is no isPending, because pending is state="loading"; and the same page said there was no as prop while three components shipped one. The shortest documented path did not compile.

Typography presentation belongs on Text parameters rather than consumer utility classes:

<Text size="xs" variant="muted" weight="semibold" transform="uppercase" tracking="wide">
  Appearance
</Text>

Omitted parameters do not reset inherited font family, weight, transform, tracking, or leading.

Font selection uses semantic roles rather than coupling UI to a particular font package:

import "@pathscale/fonts-metroclean";
:root {
  --font-display: "metroclean", sans-serif;
}
<Text family="display">Chuzz</Text>

The available roles are body, heading, display, and mono. They resolve through --font-body, --font-heading, --font-display, and --font-mono, with --font-sans as the shared fallback. This works with PathScale Fonts and application-owned font faces.

family="heading" is a typeface, not a heading. It says which face to set the text in and nothing about the document. Say which element the text is with as:

<Text as="h1" family="heading" size="xl">Pricing</Text>
<Text as="h2" family="heading">What you get</Text>
<Text as="p">Every plan includes the same engine.</Text>

as defaults to span, which is right for a run of text inside a sentence and is what Text has always rendered. It accepts span, p, div, h1 through h6, strong and em.

Reach for it on every title. Sites read family="heading" as making a heading, and the result was pages, landing pages among them, with no heading of any role anywhere on them: a reader using headings to move through the page found nothing to move between. If a page has a title, that title is an h1.

Naming a Switch, Radio or Checkbox

All three render a visually hidden 1x1 input with a styled, aria-hidden sibling beside it. That is the ordinary pattern and it is correct, and it means the control has whatever name you give it and no name at all otherwise. There is nothing visible for a name to be inferred from: the thing a reader sees is the decoration.

Give it children, which become the visible label and the name through the wrapping <label>:

<Switch onChange={setDark}>Dark mode</Switch>

Or, when the row around it already carries the words, aria-label:

<Switch aria-label="Dark mode" onChange={setDark} />

One or the other, always. A toggle with neither is a 1x1 target with an empty name: nothing can address it, and no assistive technology can reach it. Four sites reported exactly that, and a sweep of the showcase measured 13 unnamed switches on one page and 8 unnamed radios of 10 on another.

Triggers that are given a control

Popover.Trigger and Drawer.Trigger render a button. That is right when the trigger is a word or a glyph, and wrong when you hand one a control:

<Popover.Trigger><Button>Filters</Button></Popover.Trigger>   {/* two buttons */}

produces a second, anonymous button wrapping the named one at identical coordinates. Nested interactive content is invalid HTML, the control is announced twice, and a press by coordinate lands on the outer wrapper rather than on the button you wrote. Measured on three sites for Popover and on Drawer besides.

Make the control be the trigger with as:

<Popover.Trigger as={Button} flavor="primary">Filters</Popover.Trigger>
<Drawer.Trigger as={Button} variant="ghost">Menu</Drawer.Trigger>

One element carries the name, the box and the wiring. Everything else you pass goes to the delegate, so flavor, size and the rest work as they always do. Two things do not travel: the trigger's own class, which is a button reset that a real control must not be given, and data-slot="popover-trigger" / data-slot="drawer-trigger", because the delegate's own recipe owns that attribute. Select on the delegate's slot, or on [aria-haspopup="dialog"].

A trigger given plain text is unchanged and needs nothing.

Component inventory (by family)

  • Layout/primitives: Flex, Grid, Join, Card, Separator, ScrollArea, ScrollHorizontal, Skeleton, Empty, Footer, Header, Navbar, Toolbar, Dock
  • Typography/misc: Text, Link, Kbd, Badge, Chip, Tag/TagGroup, Avatar, Icon, Tooltip, Breadcrumb, Pagination, Meter, Progress, RadialProgress, Spinner (alias: Loading)
  • Inputs: Input, InputGroup, InputOTP, TextField, Textarea, NumberField, SearchField, PasswordField (+ password-requirements/rules, passwordRules.ts), ColorField, Checkbox(+Group), Radio(+Group), Switch, Slider, Select, ComboBox, ListBox, SizePicker, Form pieces (Label, Description, ErrorMessage, FieldError, Fieldset)

For Honey signup and password changes, import isPrintableAsciiPassword and PASSWORD_CHARSET_MESSAGE from @pathscale/ui/passwordRules. The validator allows only U+0020 through U+007E, preserves spaces, and leaves length and confirmation to the form's existing rules. Show the message inline when validation fails. Never use this validator for sign-in or reauthentication: existing passwords remain accepted.

  • Dates: Calendar, RangeCalendar, DatePicker, DateRangePicker (internal date engine); DateField, TimeField (separate segmented editors)
  • Color: ColorPicker, ColorArea, ColorSlider, ColorSwatch(+Picker), ColorWheel, ComplexColorWheel, ColorWheelFlower, ThemeColorPicker
  • Overlays: Dialog, Drawer, Popover, Dropdown, Menu, Toast, Collapsible(+Group), Accordion
  • Data: DataGrid (assembled, createDataGrid model), FlexGrid (incremental reveal, createFlexGrid model), Table (headless compound, bring your own model), plus primitives useStreamingBuffer, useStreamingSubscription
  • Auth kit: AuthForm, AuthCard, AuthFieldGroup, AuthSubmitButton, AuthFooterLinks, AuthPoweredBy, AuthErrorMessage, AuthSuccessMessage — Layouts composing Button/Card/fields. Their spacing, alignment and tone are recipe parameters (gap, align, variant), so a consumer asks for the presentation it wants rather than restating utility classes. AuthCard exposes header, headings, title, description, branding, body and footer as data-slot targets.
  • Connection settings: ConnectionSettings (the panel) with createConnectionSettings (the store). See below.
  • Visual FX: MetalBorder (WebGL liquid-metal border; presets chromatic|silver|gold, kind="pill"|"circle", glow, strength 0-100, theme="dark"|"light"|"auto"), GlowCard (mouse-tracking glow), NoiseBackground (animated gradient blobs), QrCode, ImmersiveLanding (full mini-app w/ PWA widgets), VideoPreview, LiveChat, ChatBubble, LanguageSwitcher

ScrollHorizontal

Use ScrollHorizontal for a gallery whose cards move horizontally as the page scrolls vertically. Intro and outro sections remain regular consumer content. Children can be existing Layouts such as Card:

import { Card, ScrollHorizontal } from "@pathscale/ui";

<section aria-labelledby="gallery-intro">
  <h2 id="gallery-intro">Stories</h2>
  <p>Introductory copy stays outside the gallery.</p>
</section>

<ScrollHorizontal
  aria-label="Featured stories"
  itemWidth={400}
  mobileItemWidth={280}
  gap={30}
  mobileGap={15}
  height="auto"
>
  <Card>First story</Card>
  <Card>Second story</Card>
  <Card>Third story</Card>
</ScrollHorizontal>

<section>Outro content follows the gallery.</section>

itemWidth and mobileItemWidth set card widths; gap and mobileGap set spacing. Defaults are 400px and 280px for widths, and 30px and 15px for gaps. The default height="auto" measures the row and creates enough vertical travel to reach the last card. Pass a number for a pixel height or a CSS length string to choose a different section height.

The gallery exposes a labelled region with a keyboard-focusable horizontal viewport. Supply aria-label or aria-labelledby with a useful name. Focus entering an offscreen card moves the page to reveal it without changing DOM or focus order. Reduced motion disables sticky translation and leaves a normal horizontal scroller. After hydration, supported browsers use a CSS view timeline; other browsers use a passive scroll listener with frame-scheduled progress. The component also accepts class, style and dataTheme props. ScrollArea remains the component for an ordinary scrollable region.

Renames from old versions: Loading→Spinner, DropdownSelect→Select, RangeSlider→Slider, Callout→Alert, EmptyState→Empty, Toggle→Switch, Modal→Dialog, TextArea→Textarea, Disclosure→Collapsible, FloatingDock→Dock, ProgressBar→Progress, ProgressCircle→RadialProgress, ScrollShadow→ScrollArea, Breadcrumbs→Breadcrumb. ~40 components removed outright (Carousel, Rating, Steps, Stats, FileInput, …).

docs/component-migration-map.md describes the earlier 2.x HeroUI migration and contradicts this list on three of them: it maps RadialProgress to ProgressCircle and splits Progress into ProgressBar/ProgressCircle, which is the reverse of what shipped, and it lists Dock as removed. Its removed-component list is still useful; its rename table is not. api-contract.md is the file that cannot be wrong, because bun run check:api fails the build when it disagrees with the code.

ColorWheelFlower follows the root data-theme by default. Its built-in light and dark palettes share hue positions, while dark mode uses genuinely darker values. Pass mode="light"|"dark" to make the mode explicit, or palette={colors} to render a custom 31-color literal palette (12 outer, 12 middle, 6 inner, 1 center). A picked swatch emits the same normalized hex that it displays. Surface strength, softness and accent mixing remain consumer theme concerns; use the literal selected hex as their input rather than making the wheel silently transform it.

Use ColorWheel for the ordinary controlled surface: it owns the picker context and accepts value, onChange, mode, and an optional literal 31-colour palette. ColorWheelFlower is the low-level context consumer and normally stays an implementation detail.

ComplexColorWheel puts standard, accessible slider axes beside the controlled wheel on a glass card. Supply explicit adjustments for the application's strength, softness, blur, refraction, depth, or other numeric theme controls:

<ComplexColorWheel
  aria-label="Surface colour"
  value={theme.surface}
  onChange={setSurface}
  palette={surfacePalette}
  adjustments={[
    { id: "strength", label: "Strength", value: theme.strength, min: 0, max: 100, onChange: setStrength },
    { id: "softness", label: "Softness", value: theme.softness, min: 0, max: 10, onChange: setSoftness },
    { id: "glass-blur", label: "Glass blur", value: glass.blur, min: 0, max: 50, onChange: setBlur },
  ]}
/>

The composition standardizes layout, glass, labels, semantic slider values, and keyboard interaction. The application still owns its colour math: an adjustment may provide preview(value, selectedColour) without hiding a token transformation inside the wheel. Pass stops for a curated discrete axis; it renders named, pressed-state choices instead of approximating a non-uniform palette with a continuous slider. ink adds a foreground sample for a text-brightness axis.

Forms (built in, plus Standard Schema)

import { createForm, Form, FormField, FormSubmitButton } from "@pathscale/ui";

const form = createForm({
  defaultValues: { email: "", password: "" },
  schema: loginSchema,                    // any Standard Schema: Zod v4 / Valibot / ArkType
  onSubmit: async (values) => { await login(values); },
});

<Form form={form} class="space-y-4">
  <FormField name="email" label="Email" />
  <FormField name="password" label="Password" inputProps={{ type: "password" }} />
  <FormSubmitButton>Log in</FormSubmitButton>
</Form>
  • Form without a form prop = plain styled <form> (FormRoot). With form = context provider + wired submit.
  • Inside a <Form>: useField(name) → {value, error, touched, invalid, handleChange, handleBlur}. Errors are touch-gated — error() is undefined until the field blurs. FormSubmitButton disables on !form.isValid() (not touch-gated), so the button can be disabled with no visible error. A failed submit() touches every field, so the errors it refused on all become visible at once.
  • The form API is the library's own: values(), getFieldValue, getFieldMeta, setFieldValue, validateField, submit(), isSubmitting(), isValid(). There is no longer a _tsForm escape hatch, because there is no longer a wrapped library to escape to.
  • Synchronous schema validation runs on change, blur, and submit; touched errors clear when valid. Submit also awaits asynchronous Standard Schemas.
  • defaultValues and field accessors retain the input type. onSubmit receives the schema’s validated output, including coercions, transforms, and defaults. Validation runs once for each submit.

DataGrid (assembled)

Reach for this first. Table below is the headless path, fifteen parts you assemble yourself; DataGrid is one tag over a model that owns the state.

import { createDataGrid, DataGrid } from "@pathscale/ui";

const grid = createDataGrid({ pageSize: 10, selection: "multiple" });
grid.addColumn("id", "ID", "number");
grid.addColumn("firstName", "First Name", "string", { searchable: true });
grid.addColumn("status", "Status", "custom", {
  render: ({ value }) => <Chip flavor="success">{String(value)}</Chip>,
});
grid.addRow({ id: 1, firstName: "John", status: "active" });

<DataGrid model={grid} borders="rows" striping="rows" interactive />

model is the only required prop. There is no sortable, searchable, checkable, pagination or expandable flag: each of those is already a fact about the model, and a second copy on the tag could disagree with the thing beside it. A column sorts because it was added sortable; the grid pages because it was given a pageSize; it selects because it was given a selection mode.

What is left on the tag is presentation: borders (none|rows|cols|both), striping, sticky (none|header|columns|both), interactive, size, width, flavor, caption, empty, renderExpanded. onSortChange, onPageChange and onSelectionChange are mirrors for an app keeping state in a URL; the model stays the source, so read the URL and call grid.setSort().

Model API: addColumn(name, label, dataType?, options?), addRow(row, index?), deleteRow, setRows, toggleColumn, sortByColumn, setSort, searchColumn, resetFilters, filterRows, switchPage, setPageSize, toggleCheck, toggleCheckAll, setGroupBy, groups(name). Accessors: columns, visibleColumns, columnsByName, rows, filteredRows, sortedRows, pageRows, sort, queries, page, pageSize, pageCount, total, selectedIds, selectedRows, groupBy, groupedRows.

Porting from vue3-ui's DataGrid

The verbs and their positional shapes carry over, so grid.addColumn("id", "ID", "number") moves unchanged. Five differences:

vue3 here why
caption on a column label caption collides with <caption>
dataType: string closed union a typo used to typecheck and render nothing
sortByColumn(col, ascendant) sortByColumn(col, direction?) true meaning "ascending" is what 2.2 removed
switchPage() reading a field switchPage(page) explicit
getColumns() visibleColumns() it always returned only the visible ones

And one behavioural difference worth knowing: in vue3, searchColumn, sortByColumn and switchPage each rewrote the same rows array from originalRows, so any two of them composed by destroying each other — paging after a search silently restored the rows the search removed. Here rows is the source and the rest is derived, so a search survives a page change and searches accumulate across columns instead of replacing the last one. resetFilters() clears them all.

Drag reordering is not ported. Cell editing is deferred.

FlexGrid (a long list, a page at a time)

Not a smaller DataGrid. That one is discrete pagination — page 3 of 12, the reader moving between fixed windows. This is the other shape: one continuous list that starts short and grows, which is what a feed, a task log or an item list wants. Neither can be spelled as the other without lying about where the reader is.

import { FlexGrid } from "@pathscale/ui";

<FlexGrid
  rows={entries()}
  pageSize={20}
  fromEnd
  more={({ count, reveal }) => (
    <Button onClick={reveal}>Show {count} earlier</Button>
  )}
>
  {(entry) => <LogRow entry={entry} />}
</FlexGrid>

The cost it removes is construction, not data. A list of 700 rows where 20 are visible still builds 700 subtrees, and a row made of library components is a handful of instances rather than one element. The application this came from measured a 40-row log at 122-178ms of a 203-339ms panel build for exactly that reason, and had seven separate hand-rolled versions of the same limit signal and "show more" button — the lists that had not been given one were the slow ones.

fromEnd is for anything read newest-first: the first page is the tail, "more" means earlier, and the control moves above the rows so it does not sit under the reader's eye. autoLoad (on by default) reveals as they scroll; more adds an explicit control, and you can have either or both.

It listens for scroll, not IntersectionObserver. That is deliberate, not dated: not every consumer runs in an engine that has observers. One renders through Blitz, where IntersectionObserver, ResizeObserver and MutationObserver are all absent, so a sentinel would never intersect and the list would silently stop at its first page with no error to explain it. One consequence for you: the list slot owns the scrollbar, so do not put overflow: auto on an ancestor and expect reveals to fire.

createFlexGrid is the same logic without the markup, for a list that wants its own container: visible, total, remaining, hasMore, nextCount, revealMore, revealAll, reset, onScroll.

InlineEdit (a value edited where it is read)

A name, a title, a label: something shown as text until someone chooses to change it, without a dialog or a separate form. The trigger swaps the value for a field holding a draft of it.

import { InlineEdit } from "@pathscale/ui";

<InlineEdit
  value={project.name}
  onCommit={(name) => rename(project.id, name)}
  label={`Rename ${project.name}`}
  trigger={<Icon name="pencil" />}
/>

onCommit receives the trimmed draft and is not called when it is empty or unchanged. Enter commits, Escape abandons, and moving focus away commits, so the mode has an exit for a reader who never touches the keyboard. Pass children to render the value as something other than plain text, such as a link that opens what it names.

Two things it does that a hand-rolled version usually gets wrong, both of which shipped as bugs in the application this came from:

Only the active row is mounted. When the field mounts, it receives the draft and takes focus. This keeps the focus request tied to the field that will actually be on screen.

The field ignores the blur that arrives before it has focus. Revealing the field moves focus, and that first blur reaches the field's own handler while the mode is still opening; committing on it closes the editor inside the click that opened it. Same symptom, and it survives a tab switch because the state belongs to the component rather than the surface.

Every part is a declared slot - inline-edit-trigger, inline-edit-field, inline-edit-read, inline-edit-edit, inline-edit-value - so a test harness can address the trigger and the field by name instead of guessing at the markup.

Table (headless assembly)

Table is the compound for markup you write yourself. It has no model of its own: the row model hooks -- useTableModel, useTableSorting, useTablePagination, useTableFiltering, useTableExpansion, useTableSelection -- went out with TanStack, and nothing replaced them in that shape. Reach for Table only when you need markup DataGrid cannot draw, such as an animated expanded row or a bespoke row component, and drive it from createDataGrid:

import { createDataGrid, Table, TableSortIcon } from "@pathscale/ui";

const grid = createDataGrid<Row>({ columns, rows: props.rows, pageSize: 10 });

// grid.visibleColumns() for the header, grid.pageRows() for the body,
// grid.sort() / grid.setSort for <Table.Content sortDescriptor= onSortChange=>,
// grid.page() / grid.pageCount() / grid.switchPage() for pagination.

If you do not need your own markup, use DataGrid instead: it draws the header, rows, pagination and empty state from the same model.

  • The grid model owns sorting, filtering, paging, selection and grouping. What it deliberately does not own is presentation state, such as which filter popover is open, or which rows a bespoke table has expanded. A consumer keeping its own markup owns that too, and should key expansion by row id rather than index so sorting or paging does not leave the wrong row open.
  • Parts: TableRoot/ScrollContainer/Content/Header/Column/Body/Row/Cell/ExpandedRow/Footer/PageSize/ResizableContainer/ColumnResizer/LoadMore(+Content), plus SortIcon, ExpandToggle, InlineConfirm, MobileListView (responsive card fallback), VirtualSpacerRow.
  • Virtualization is not built in. useVirtualRows was a thin wrapper over @tanstack/solid-virtual that nothing in the library used; it was removed with the rest of TanStack. For a long unpaged list use createFlexGrid, which reveals incrementally and removes the construction cost windowing was there to avoid. VirtualSpacerRow is still here for a caller that brings its own windowing.

Motion

import { enablePopmotion } from "@pathscale/ui";
import { animate } from "popmotion";
enablePopmotion((opts) => animate({ ...opts }));   // ⚠️ WITHOUT this, all JS animations SNAP to end state
  • runMotion(el, from, to, transition?, onComplete?) — animates opacity/x/y/scale; durations in seconds.
  • Presets via getPreset/resolvePreset (route, routeAuth, authSwap, fade, fadeUp, scaleIn, toast, routeDashboard); registerPreset mutates the global set; createMotionSystem() for isolated instances; createRouteTransitionResolver({rules, fallback}) for route rules.
  • Solid components: <Presence when={open()}>{(isExiting, onExitComplete) => <MotionDiv initial animate exit isExiting={isExiting()} onExitComplete={onExitComplete}>… — Presence force-unmounts after 800ms if onExitComplete never fires. <AnimatedCollapse open duration=0.24> for height collapse.
  • resolvePreset(name, {reduceMotion}) returns the noMotion preset under prefers-reduced-motion. Note Dialog/Toast/Drawer animate via CSS, not this system.

The root barrel and @pathscale/ui/motion subpath also export small browser motion helpers:

import {
  animateElement,
  createInView,
  createScrollProgress,
  springKeyframes,
  stagger,
} from "@pathscale/ui/motion";

const visible = createInView(() => observedElement, { once: true });
const progress = createScrollProgress(() => section, {
  range: "start-start/end-end",
});
const delay = stagger(index, 50); // milliseconds

const samples = springKeyframes({ stiffness: 180, damping: 20, mass: 1 });
const animation = animateElement(element, { opacity: samples }, {
  duration: ((samples.length - 1) / 60) * 1000,
});

createInView and createScrollProgress return Solid accessors and attach browser listeners only after mount. Visibility starts as true if the observer is unavailable. Scroll progress starts at zero, samples scroll updates at most once per animation frame, and also writes --scroll-progress to its target for CSS. Its supported range tracks the target from viewport top to its bottom at viewport bottom; the target's previous inline custom property is restored on cleanup. supportsViewTimeline() checks the CSS timeline and attachment range used by ScrollHorizontal.

animateElement uses WAAPI when available, defaults to the library's base duration and motionEasings.out, and applies the final keyframe immediately when WAAPI is unavailable. Its options follow WAAPI timing fields in milliseconds; the returned finished promise resolves on completion or cancellation, and cancel() stops the animation. Live reduced-motion changes finish an active animation by default. springKeyframes returns normalized 60 Hz samples for a WAAPI property; use (samples.length - 1) / 60 * 1000 milliseconds as the duration to preserve that sample rate.

Streaming

const buf = useStreamingBuffer<Row>({ strategy: "upsert", maxSize: 500, getKey: r => r.id });
useStreamingSubscription<Row>({
  subscribe: (o) => { const es = new EventSource(url); es.onmessage = e => o.next(JSON.parse(e.data)); return () => es.close(); },
  onData: buf.add,
});
// buf.rows() is the reactive, capped, deduped array

Strategies: append (ignore duplicate keys) | upsert (replace in place) | replace. Subscription returns {isLive, isConnecting, error, eventCount, start, stop}; auto-starts unless enabled is false.

Toast (imperative singleton)

import { toast, ToastProvider } from "@pathscale/ui";
// mount <ToastProvider/> once, then anywhere:
toast.success("Saved"); toast.danger("Failed"); toast.promise(p, {loading, success, error});

Icons

Icon's main prop is src, and which source it is, is the type: a string is a preload token ("lucide--copy", or the wrapped "icon-[lucide--copy]"), an element is inline SVG you own.

<Icon src="lucide--copy" />
<Icon src={<svg viewBox="0 0 24 24">…</svg>} />

An icon is hidden from the accessibility tree by default, which is right for the common case: it sits next to text that already says what it means, and announcing it says the same thing twice. When the icon is the label, name it with label, which swaps aria-hidden for role="img" and that name.

<Button width="square" aria-label="Copy"><Icon src="lucide--copy" /></Button>
<Icon src="lucide--trending-up" label="Rising" />

Reach for label only when nothing else names the thing. A square Button with its own aria-label is already named, so labelling the icon inside it makes the control announce twice.

The library ships no glyphs. Your app generates the CSS that resolves a token, with @plugin "@iconify/tailwind4" under Tailwind v4 or @pathscale/rsbuild-plugin-iconify under rsbuild, scanning your source rather than ours. Both sources inherit colour through currentColor, so flavor works the same either way.

QR codes

QrCode encodes value into one inline SVG. Its required title is both the SVG title and its accessible name. Encoding is synchronous, so a changed value updates the matrix immediately. level accepts L, M, Q or H and defaults to M; size accepts a number of CSS pixels or another CSS length.

import { QrCode } from "@pathscale/ui";

<QrCode value={otpauthUri} title="Authenticator setup QR code" size={192} />

For non-Solid use, qrMatrix(value, level?) returns the dark modules as a boolean[][].

Dates

Calendar/DatePicker/RangeCalendar/DateRangePicker use the internal engine (native Date, a built-in name table, no Intl and no date lib). Values are Date objects; ranges are {start: Date, end: Date}. Controlled via value/defaultValue/onChange. DateField/TimeField are separate segmented text editors, not calendar-backed.

Language

The name table is en-US only, and it is the whole of the locale data the library carries. Intl is not used at all: it is undefined in the chuzz browser, ICU data is deliberately not shipped, and the resulting ReferenceError does not produce a wrong date, it halts Solid's reactive system for the rest of the page's life.

So locale on its own changes nothing. Pass dateNames to render another language:

import { Calendar, type DateNames } from "@pathscale/ui";

const de: DateNames = {
  monthsLong: ["Januar", "Februar", /* ...12 */],
  monthsShort: ["Jan", "Feb", /* ...12 */],
  weekdaysNarrow: ["S", "M", "D", "M", "D", "F", "S"], // Sunday first
  weekdaysShort: ["So", "Mo", "Di", "Mi", "Do", "Fr", "Sa"],
  weekdaysLong: ["Sonntag", "Montag", /* ...7 */],
};

<Calendar locale="de-DE" dateNames={de} />;

All five arrays are required, months indexed by Date#getMonth and weekdays by Date#getDay from Sunday. A site with its own i18n already has these strings. The same props exist on RangeCalendar, DatePicker and DateRangePicker.

Two things to know:

  • A locale with no dateNames renders English, and says so. The root element carries lang set to the language actually on screen, so <Calendar locale="de-DE" /> renders lang="en-US". It does not throw and it does not label English text as German.
  • The assembly order stays en-US. dateNames replaces the words, not the grammar, so a German calendar reads "Sonntag, Juni 15, 2025" rather than "Sonntag, 15. Juni 2025". Per-locale patterns are what ICU is for, and ICU is what was ruled out. Raise it if a site needs the ordering.

Mirroring to the public showcase (js.software)

Decision (2026-07-26): hand-port this to TSX in js.software. It has no markdown pipeline — docs pages are hand-written TSX under src/pages/docs/ — and adding one was judged not worth it.

Entry point: a third homepage button, "Usage Cheatsheet". src/pages/Home.tsx currently has two (Start Building Today → ROUTES.DOCS_INSTALLATION, Explore Components → ROUTES.SHOWCASES). A third is right rather than folding this into Installation, because the three serve different intents: get started (first five minutes), browse (visual), look something up while working (this document). Burying a reference inside a getting-started flow hides it from the people who need it most. Style it subordinate to the existing two — btn-ghost, not a third btn-primary — so the hero stays a hero and not a menu.

Build it with @pathscale/ui components, not raw markup — the showcase should be built from the library it documents. Follow the existing page conventions in src/pages/docs/Installation.tsx: ContentContainer, CodeBlock, Callout, and Flex from @pathscale/ui.

Drift control — this matters. This file stays the source of truth. Port the stable narrative sections (Install, Component conventions, Forms, Table, Toast, Icons, Dates) and have Theming tokens and the Component inventory link back here rather than duplicating them: those two change whenever the library changes, and a TSX copy has nothing keeping it honest. The inventory alone is ~40 lines that go stale the moment a component is added.

Connection settings

Where an application points itself, and how that survives a reload. Every property in this family ships this page: a switch, one or more backend URLs, an app id, and a save that reconfigures the transport. Six of them had written it separately, in two shapes and with different bugs.

Two pieces. createConnectionSettings owns the state and the persistence; <ConnectionSettings> is the panel over it. They are separate because the transport needs the addresses at module scope, long before any settings page is rendered.

import { createConnectionSettings } from "@pathscale/ui/hooks/connection";
import { ConnectionSettings } from "@pathscale/ui/components/connection-settings";

// Module scope, so the transport and the page read the same instance.
export const connection = createConnectionSettings({
  storageKey: "acme.connection",          // namespace it; two apps on one origin collide
  endpoints: [
    { name: "api", fallback: "wss://api.acme.com" },
    { name: "auth", fallback: "wss://auth.example.com" },
  ],
  appPublicId: DEFAULT_APP_ID,
  onApply: async ({ urls, appPublicId }) => {
    reconfigure({ apiUrl: urls.api, authUrl: urls.auth, appPublicId });
    await reconnect();
  },
});

<ConnectionSettings
  id="acme-connection"
  store={connection}
  endpoints={[{ name: "api", label: "API URL", hint: "leave empty for production" }]}
  labels={{
    useCustom: "Use a custom backend",
    appPublicId: "Application ID",
    save: "Save",
    reset: "Reset",
  }}
  showAppPublicId
  validateAppPublicId={(id) =>
    /^[0-9A-Za-z]{16}$/.test(id)
      ? undefined
      : "Application ID must be 16 letters or numbers"
  }
/>

The default endpoint validator accepts absolute HTTP, HTTPS, WS, and WSS URLs. It does not determine which transport an endpoint supports; provide that endpoint's validate callback when it needs a narrower scheme or origin rule.

When showAppPublicId, labels.appPublicId, and validateAppPublicId are all present, Save validates the visible application ID before changing persisted settings or running onApply. Return undefined to accept it or a message to show the failure and call onSaveFailed.

Read connection.urls.api from the transport. It resolves overrides and never returns an empty string.

It is not memoised: every read folds over the endpoints and rebuilds the record. That is deliberate — the store is created at module scope, where a memo sits in a detached root and can go stale rather than merely slow, and a stale URL is worse than a rebuilt one. Reading it per request is fine at the scale these panels have. Reading it in a loop is not: hoist it, or wrap it in a createMemo inside your component, where there is an owner to keep it live.

What the store guarantees

  • Per endpoint, not global. Pointing the API at a local instance while auth stays on production is the ordinary case. setUseCustom flips them all together for a page that wants one switch; the panel does not use it, because it would also mark endpoints the page never showed.

  • An override means a value that differs from the fallback. An endpoint storing today's default is not overridden, so when that default moves the application moves with it.

  • Nothing customised means nothing stored. At defaults the key is removed rather than written, for the same reason.

  • Stored values are checked on read. A key written by an older version, or edited by hand, falls back field by field rather than throwing. A settings page that cannot open is a settings page that cannot be corrected. An address that does not validate is dropped along with its override, so a corrupted key cannot activate an address nobody typed.

  • Addresses are validated before they are saved, by validate on the endpoint, defaulting to "parses as a URL". Give an endpoint its own when it knows more: a WebSocket transport handed http:// fails at connect time, far from the page that could have explained it.

    The store enforces this, not just the panel: setUrl returns the reason it refused a value and stores nothing, because every write there becomes an active, persisted override. Keep an address a person is still typing as a draft in your own state and call setUrl when it validates — which is what ConnectionSettings does.

  • apply() persists first, then reconnects. onApply receives the settings that were just written, and storage already holds them when it runs, so a callback that reloads or navigates reads back what it was handed.

  • apply() is awaited and isApplying covers the reconnect, not just the write. A failure propagates; the panel shows it and calls onSaveFailed.

  • Overlapping applies run in order. Two saves in quick succession reconnect in the order they were made, so the transport ends on the newer one. A queued apply waits for the one in front; onApply reconfigures a transport this store does not own, so a superseded reconnect cannot be undone after the fact and is not started out of turn.

What the panel guarantees

Everything is a draft until Save, the switch included. Opening the panel, looking, and navigating away changes nothing. Save validates, commits, applies, and reports a failure where the person who pressed it is looking. Reset drops the overrides and applies the defaults.

It renders a <form>, so Enter in a field saves, and its actions are the library's Button.

Migrating a site off its own copy

Replace the site's store with a thin adapter over this one rather than changing every call site at once:

export const connectionStore = {
  get wsUrl() { return connection.urls.api; },
  get useCustomUrl() { return connection.isOverridden("api"); },
  applySettings() { return connection.apply(); },
};