@ibobbyts/svelte-ui-utils
v0.5.15
Published
Reusable Svelte 5 UI utilities for dialogs, toast notifications, dropdowns, and data tables.
Readme
svelte-ui-utils
Reusable Svelte 5 UI utilities published to the npm registry as
@ibobbyts/svelte-ui-utils.
Install
Install from the public npm registry. No GitHub Packages token is required.
With Bun:
bun add @ibobbyts/[email protected]Canonical Bun pull address:
@ibobbyts/[email protected]With npm:
npm install @ibobbyts/[email protected]The repository does not track dist/; releases and local integration builds run
npm run package to generate the published files.
Import the stylesheet once in your app entry:
import '@ibobbyts/svelte-ui-utils/style.css';Module imports
<script lang="ts">
import { ToastManager, toast } from '@ibobbyts/svelte-ui-utils/toast';
import { Dropdown } from '@ibobbyts/svelte-ui-utils/dropdown';
import { Dialog, ConfirmDialog, InputDialog, CsvUploadDialog, ImagePreviewDialog, PasswordCopyDialog } from '@ibobbyts/svelte-ui-utils/dialog';
import { DataTable, DateRangeFilter, FilterTable, NumberRangeFilter } from '@ibobbyts/svelte-ui-utils/table';
</script>The package root also re-exports the public modules:
import { ToastManager, Dropdown, Dialog, DataTable } from '@ibobbyts/svelte-ui-utils';Toast
<script lang="ts">
import { ToastManager, toast } from '@ibobbyts/svelte-ui-utils/toast';
import '@ibobbyts/svelte-ui-utils/style.css';
function save() {
toast.success({
title: 'Saved',
message: 'The record was updated.',
duration: 4000,
position: 'top-right'
});
}
</script>
<ToastManager language="en_us" closeLabel="Close" />
<button on:click={save}>Save</button>Supported positions are top-left, top-center, top-right, right-center,
bottom-right, bottom-center, bottom-left, and left-center.
Dropdown
Dropdown menus default to placement="auto" and open toward whichever side of
the trigger has more available viewport space. The direction is recalculated
while the menu is open when the viewport is resized or a scroll container
moves. Set placement="up" or placement="down" to force a direction. Use
fitViewport={false} to disable the default panel-height constraint for the
chosen side.
SortableList
SortableList provides controlled vertical HTML5 drag-and-drop ordering. Each
item has a string id (and may contain any additional fields); getId can
project a different string key while retaining that typed item contract. The
caller owns the item array and receives the reordered array through
onReorder. Use the third snippet argument to attach drag bindings to a
dedicated handle. listTag and itemTag can be changed when the list must
render valid table markup such as direct <tr> children under <tbody>.
<script lang="ts">
import { SortableList } from '@ibobbyts/svelte-ui-utils/sortable-list';
let items = [{ id: 'a', label: 'First' }, { id: 'b', label: 'Second' }];
</script>
<SortableList {items} onReorder={(next) => (items = next)}>
{#snippet children(item, _index, handle)}
<div {...handle} aria-label={`Drag ${item.label}`}>⠿</div>
<span>{item.label}</span>
{/snippet}
</SortableList>Dragging over the target item's upper or lower half displays a before/after
insertion indicator. Dropping on the same item or while disabled={true} is a
no-op. The component does not persist order or perform rollback; those remain
the responsibility of the controlled parent.
OrderedListEditor
OrderedListEditor is the shared editor for ordered fields. It renders the
provided content first, an optional current/select action next, and a trash-icon
remove action at the far right. Reorder arrows are intentionally not rendered;
use SortableList when drag-and-drop ordering is needed. Set
allowRemoveLast={true} when an empty list is valid.
<script lang="ts">
import { OrderedListEditor } from '@ibobbyts/svelte-ui-utils/ordered-list';
</script>
<OrderedListEditor items={rows} onremove={(id) => remove(id)}>
{#snippet children(item)}
<input value={item.value ?? ''} />
{/snippet}
</OrderedListEditor>SortableTable
SortableTable is the table-level ordering primitive. It owns the table rows,
the left drag-handle column, and the right trash-icon delete column. Callers
provide only the header cells and the middle row cells through snippets.
Use getDragLabel(item, index) and getRemoveLabel(item, index) when the
controls need caller-owned accessible labels. Each label is applied to both
aria-label and title; defaults remain Drag ${getId(item)} and
Remove ${getId(item)}.
<SortableTable items={rows} onReorder={reorder} onRemove={remove}>
{#snippet header()}<th>Name</th><th>Protocol</th>{/snippet}
{#snippet children(row)}<td>{row.name}</td><td>{row.protocol}</td>{/snippet}
</SortableTable>Set verticalSeparators={true} to show vertical lines between the drag,
content, and remove columns. The option is disabled by default. Override
--suu-sortable-table-border and --suu-sortable-table-separator to tune
light-mode borders. For dark mode, optionally override
--suu-sortable-table-border-dark and
--suu-sortable-table-separator-dark; both default to a higher-contrast
blue-gray color.
SortableTableEnhanced composes the same table and adds a controlled current
radio immediately after each drag handle. currentId is read-only input;
onCurrentChange asks the caller to persist a new current item. Use
showCurrentControl={false} to omit the radios while retaining the table's
drag, remove, reorder, and row-color behavior. Use
getCurrentDisabled for per-row eligibility and getRowColorPreset to select
the package-owned red, yellow, or green background. The presets include
light and dark defaults and expose --suu-sortable-table-row-*-light and
--suu-sortable-table-row-*-dark override variables.
<SortableTableEnhanced
items={rows}
currentId={currentRowId}
getDragLabel={(row) => `Reorder ${row.name}`}
getRemoveLabel={(row) => `Remove ${row.name}`}
onCurrentChange={(row) => selectCurrent(row.id)}
getCurrentDisabled={(row) => row.exhausted}
getRowColorPreset={(row) => row.exhausted ? 'red' : row.cooling ? 'yellow' : 'green'}
onReorder={reorder}
onRemove={remove}
verticalSeparators={true}
>
{#snippet header()}<th>Name</th><th>Protocol</th>{/snippet}
{#snippet children(row)}<td>{row.name}</td><td>{row.protocol}</td>{/snippet}
</SortableTableEnhanced>Dialogs
<script lang="ts">
import { ConfirmDialog, Dialog, InputDialog } from '@ibobbyts/svelte-ui-utils/dialog';
let dialogOpen = false;
let confirmOpen = false;
let inputOpen = false;
let passwordOpen = false;
let name = '';
</script>
<button type="button" on:click={() => (dialogOpen = true)}>Open dialog</button>
<Dialog
open={dialogOpen}
title="Edit record"
description="Update the shared fields."
padding="12px 16px"
closeLabel="Close dialog"
blurBackdrop={true}
showCountdown={true}
countdownDurationMs={30000}
restoreFocusSelector="#edit-record-trigger"
onClose={() => (dialogOpen = false)}
>
<p>Dialog body content goes here.</p>
<svelte:fragment slot="footer">
<button type="button" class="suu-dialog__button" on:click={() => (dialogOpen = false)}>Cancel</button>
<button type="button" class="suu-dialog__button suu-dialog__button--primary">Save</button>
</svelte:fragment>
</Dialog>
<ConfirmDialog
open={confirmOpen}
title="Delete file"
message="This cannot be undone."
confirmLabel="Delete"
cancelLabel="Cancel"
intent="danger"
onClose={() => (confirmOpen = false)}
onConfirm={() => {
confirmOpen = false;
}}
/>
<InputDialog
open={inputOpen}
title="Rename"
inputLabel="Name"
bind:inputValue={name}
onClose={() => (inputOpen = false)}
onConfirm={(value) => {
name = value;
inputOpen = false;
}}
/>
<PasswordCopyDialog
open={passwordOpen}
title="Temporary password"
message="This value is shown only once."
value="Abc123xy"
valueLabel="Password"
copyLabel="Copy password"
copiedLabel="Copied"
doneLabel="Done"
onClose={() => (passwordOpen = false)}
/>Dialog components are controlled by the consuming app. Dialog renders a
native <dialog> element and opens it with the browser top layer, so dialogs
nest: with several dialogs open at once, Escape, Tab, and backdrop clicks only
affect the topmost dialog and parent dialogs stay open. Dialog calls
onClose from the close button, backdrop, or Escape key when dismissible; it
does not mutate open internally. Set dimBackdrop={false} to disable
background darkening, blurBackdrop={true} to blur content behind the dialog,
and showCountdown={true} with countdownDurationMs to show a toast-style top
countdown bar. The optional padding prop accepts a CSS padding shorthand and
applies it consistently to the dialog header, body, and footer. The default
section-specific spacing is preserved when padding is omitted, and the same
prop is available on all dialog wrapper components. Set restoreFocusSelector
when the opening control may be replaced while the dialog is open; after
closing, Dialog focuses the latest matching element and otherwise falls back
to the original connected element. ConfirmDialog renders its message once
in the dialog body and forwards this prop, along with the dismiss, backdrop,
countdown, and focus-restore lifecycle props, to Dialog.
Dropdown
<script lang="ts">
import {
Dropdown,
DropdownMultiSelect,
type DropdownOption,
type DropdownValue
} from '@ibobbyts/svelte-ui-utils/dropdown';
const pageSizeOptions: DropdownOption[] = [
{ label: '10', value: '10' },
{ label: '20', value: '20' },
{ label: '50', value: '50' }
];
let pageSize: DropdownValue = '20';
</script>
<Dropdown
value={pageSize}
options={pageSizeOptions}
ariaLabel="Rows"
placement="down"
onChange={(next) => {
pageSize = next;
}}
/>Dropdown is a controlled select-like component for simple option lists.
Every option submits a string value while label stays the display text;
callers with numeric domain state convert with String/Number at the
boundary (the bundled Pagination does this for its numeric page size). Use
placement="up" when the menu should open above the trigger, such as bottom
pagination bars. The expanded menu shares the trigger's left edge by default;
use menuAlign="right" to align their right edges instead. fitContent sizes
the menu to its longest option while keeping the selected edge aligned.
DataTable uses this same component for its page-size picker. A trigger
stretched taller than its content (for example filling a tall table cell)
centers its collapsed label by default; verticalAlign="start" or "end"
pins the label and chevron to the top or bottom edge instead, keeping a
minimal vertical padding so the content never touches the button border.
Set search={true} with loadOptions to load remote options as the user
types. The default inputStyle="dropdown" keeps the search field inside the
expanded menu. Set inputStyle="input" to render a directly editable input;
results appear while it is focused and hide on blur. In input style, the
optional getItemLabel callback controls the displayed label while value
and onChange continue to represent submitted option values. The input style
is ignored when search is disabled.
For keyboard typeahead, an option may provide searchText separately from its
display label. Typeahead matches the beginning of searchText or label,
while the label remains the only text shown in the trigger and menu:
<Dropdown
value="cn"
options={[{ label: '中国', searchText: 'China', value: 'cn' }]}
ariaLabel="Country"
/>Set multiselect={true} to control the component with a DropdownValue[].
Each option then shows a checkbox, selecting or deselecting an option keeps the
menu open, and onChange receives the complete selected-value array in option
display order. DropdownMultiSelect is the convenience wrapper for this mode:
<script lang="ts">
import { DropdownMultiSelect, type DropdownMultiValue } from '@ibobbyts/svelte-ui-utils/dropdown';
let selectedRoles: DropdownMultiValue = ['editor'];
</script>
<DropdownMultiSelect
value={selectedRoles}
options={[
{ label: 'Editor', value: 'editor' },
{ label: 'Reviewer', value: 'reviewer' }
]}
ariaLabel="Roles"
maxWidth="18rem"
onChange={(next) => {
selectedRoles = next;
}}
/>The collapsed trigger joins selected labels with ", " and truncates the
single line when it exceeds the existing width or maxWidth constraint.
Pass triggerText to replace that joined text with a caller-computed summary
(e.g. "3 selected"); it also applies to single-select triggers, and a blank
value keeps the default label behavior. Grouped and disabled options retain
the same behavior as single-select mode.
The dropdown panel is constrained by default to the space available above or
below the trigger and remains scrollable when its contents exceed that height.
Set fitViewport={false} to fall back to the stylesheet's viewport-height
limit (100vh).
Allowing a Dropdown menu to extend outside a modal
fitViewport chooses the opening direction and limits the panel height against
the browser viewport. It does not portal the menu to document.body, so an
ancestor with overflow: auto or overflow: hidden can still clip the menu or
include it in the ancestor's scrollable overflow area.
For a modal whose content otherwise fits without scrolling, use a full-width positioning boundary around the Dropdown and release the modal overflow only while the menu exists:
<div class="app-modal">
<div class="app-modal__body">
<div class="dropdown-overflow-boundary">
<Dropdown
value={selectedValue}
options={options}
onChange={(next) => {
selectedValue = next;
}}
/>
</div>
</div>
</div>.dropdown-overflow-boundary {
position: relative;
}
/* Position the absolute menu against the full-width boundary, not the
intrinsic-width Dropdown trigger. */
.dropdown-overflow-boundary .suu-dropdown {
position: static;
}
.dropdown-overflow-boundary .suu-dropdown__menu {
width: max-content;
min-width: 0;
max-width: 100%;
}
.dropdown-overflow-boundary .suu-dropdown__option {
white-space: normal;
overflow-wrap: anywhere;
}
/* :has() scopes the overflow exception to the time the menu is open. */
.app-modal:has(.dropdown-overflow-boundary .suu-dropdown__menu),
.app-modal:has(.dropdown-overflow-boundary .suu-dropdown__menu) .app-modal__body {
overflow: visible;
}This keeps the trigger at its intrinsic width, lets the menu grow toward its
aligned edge up to the modal content width, wraps longer options, and allows
the menu to paint outside the modal. The default fitViewport={true} still
sets the panel's upper or lower limit from the browser viewport and keeps an
oversized option list scrollable.
This CSS pattern intentionally does not implement a portal. If the modal body
must remain independently scrollable while the menu is open, use a portal or
floating-layer component instead; releasing overflow would change that
scrolling contract. :has() also requires a browser that supports the CSS
relational pseudo-class.
The original flat options API remains available. New callers may opt into
grouped options with optionGroups; each group can have an
optional accessible label and its options keep the same keyboard and disabled
semantics. Set groupsCollapsedByDefault to "true" to initially collapse
all groups, or to "auto" to initially expand only groups containing a
selected option; "false" is the default. The initial state is evaluated each
time the menu opens, and selecting options while it remains open does not
change the current collapsed state. Group headings can always be toggled
manually. width, minWidth, maxWidth, and className are optional styling
hooks. onTriggerClick runs before the dropdown toggles, so a nested control
can stop event propagation without preventing the dropdown from opening.
Async search mode
Set search={true} and pass loadOptions to turn the menu into an async
search dropdown. The trigger stays a dropdown button; expanding it opens a menu
with an always-visible search input:
<script lang="ts">
import { Dropdown, type DropdownLoadOptions } from '@ibobbyts/svelte-ui-utils';
let country = '';
const loadOptions: DropdownLoadOptions = async (query, { limit, signal }) => {
const params = new URLSearchParams({ q: query, limit: String(limit) });
const response = await fetch(`/api/countries?${params}`, { signal });
return response.json();
};
</script>
<Dropdown
value={country}
search
searchPlaceholder="Search countries"
{loadOptions}
ariaLabel="Country"
onChange={(next) => {
country = next;
}}
/>loadOptions(query, { limit, signal }) returns { options?, optionGroups? }
whose options use label/value only. The empty query fires immediately on
every expand; typed queries are debounced with searchDebounceMs (default
300) and receive searchLimit (default 50, floored to at least 1; pass a
larger value when the source list is longer). When a
response contains optionGroups, the groups are the sole render source and any
flat options on the same response are ignored; empty groups stay hidden, and
an empty result renders the no-results row. Stale responses are discarded by
request order, closing the menu aborts the in-flight request, and a rejected
load shows the error row (override the text with errorText). The empty-query
response is the browsing list and follows the same groupsCollapsedByDefault
states as static groups; with "auto" its collapse state is seeded once per
open session and manual toggles survive later empty-query refreshes. A
non-empty query renders every matched group expanded regardless of that
setting (filtered results drop groups, so browsing indexes would point at the
wrong groups); toggles made during a query apply to that query text only, and
clearing the query restores the browsing state.
A single-select pick closes the menu; a multiselect pick keeps it open and
emits the complete selected array. Values picked during earlier queries stay
selected across new results. Search mode never falls back to the static
options/optionGroups props; without search, those props remain the only
render source and loadOptions is never called. Type the loader with
DropdownLoadOptions/DropdownLoadOptionsResult, exported from the package
root.
loadOptions factories
Most loadOptions implementations only differ in the item source: filter a
local array, or POST one JSON endpoint. The factories exported from
@ibobbyts/svelte-ui-utils/dropdown (and the package root) build loaders that
fit both the root Dropdown search mode and the data-table
filter.dropdownSearch control:
import { createFetchLoadOptions, createLocalLoadOptions } from '@ibobbyts/svelte-ui-utils';
// Local list: filter, map to options, slice to the limit.
const loadFromRoster = createLocalLoadOptions(
() => rosterUsers,
{
toOption: (user) => ({ value: String(user.id), label: user.displayName }),
matches: (user, query) => matchesPinyin(user.displayName, query),
limit: 5
}
);
// JSON endpoint: URL, body builder, payload decoding, abort and error policy.
const loadFromApi = createFetchLoadOptions({
url: '/api/members/search',
buildBody: (query, limit) => ({ groupId, query, limit }),
mapOptions: (payload) => (payload as { options: MemberOption[] }).options ?? [],
throwOnError: true
});createLocalLoadOptions(source, config?) accepts a static array or a getter
re-evaluated on every search. toOption converts domain items (omit it when
the items already satisfy the { label, value } contract); matches receives
the raw item and the trimmed query, and defaults to a case-insensitive
substring match over the converted option's label/searchText, where an
empty query matches everything. limit caps the context limit.
createFetchLoadOptions(config) skips the request for a blank query, posts
JSON (default body { query, limit }), passes context.signal through, and
decodes the payload with mapOptions before slicing to the limit. HTTP and
network failures resolve with no options by default; throwOnError: true
rethrows them (aborted requests always resolve with no options) so wrappers
that surface errors keep working. fetchImpl swaps the transport for tests.
The filter.dropdownSearch control reports selections through onChange and
every raw keystroke through onQueryChange (undebounced there; wrap your own
debounce). Pages whose table follows the free text itself — not a selected
item — use onQueryChange to apply it, and keep value/selectedItem for
the committed selection so typing is never clobbered.
Multiselect handlers can also stop repeating the string | string[] narrowing:
toMultiSelection(selection) and toSingleSelection(selection) normalize a
Dropdown onChange argument to the shape the handler needs.
DataTable
<script lang="ts">
import {
DataTable,
type PaginationState,
type SortState
} from '@ibobbyts/svelte-ui-utils/table';
type UserRow = {
name: string;
createdAt: string;
};
const columns = [
{ key: 'name', header: 'Name', sortable: true },
{
key: 'createdAt',
header: 'Created',
sortable: true,
headerHorizontalAlign: 'center',
headerVerticalAlign: 'middle',
cellHorizontalAlign: 'right',
cellVerticalAlign: 'top'
}
];
let rows: UserRow[] = [];
let totalRows = 0;
let searchTerm = '';
let sort: SortState | null = null;
async function loadRows({ page, pageSize }: PaginationState) {
const params = new URLSearchParams({
page: String(page),
pageSize: String(pageSize),
search: searchTerm
});
const response = await fetch(`/api/users?${params}`);
if (!response.ok) {
throw new Error('Failed to load users');
}
const result = (await response.json()) as { rows: UserRow[]; totalRows: number };
rows = result.rows;
totalRows = result.totalRows;
}
</script>
<DataTable
language="en_us"
rows={rows}
{columns}
{sort}
pagination={{
tableId: 'admin-users',
totalRows,
defaultPageSize: 20,
pageSizeOptions: [10, 20, 50, 100],
persistPageSize: true,
queryKey: searchTerm,
onRequest: loadRows
}}
tableLayout="auto"
stickyHeader={true}
onSortChange={(next) => {
sort = next;
}}
/>DataTable only supports server pagination. Pass the current page rows in
rows, the server count in pagination.totalRows, and load each requested page
through pagination.onRequest. The component owns page and page-size state,
resets to page 1 when the primitive queryKey changes, disables both
pagination bars while a request is pending, and rolls back its controls if that
request rejects. The callback remains responsible for presenting request errors.
Set persistPageSize: true and provide a stable, non-empty tableId to retain
the selected page size in browser localStorage. The generated key is
svelte-ui-utils:data-table:<tableId>:page-size; callers do not construct it.
Stored values are accepted only when present in the normalized
pageSizeOptions. Storage failures are ignored. Options default to
[10, 20, 50, 100], and defaultPageSize falls back to the first unique
positive integer option when omitted or invalid.
DataTable renders page-number pagination above and below the data table by
default, including a page-size selector. Use language for package-owned
defaults such as empty state, pagination label, and page-size label; use
pagination.pageSizeLabel or emptyText when a specific app needs to override
them.
Pass pagination={false} for static tables. Use showHeader={false} for
tables that should render body rows without a header section. Sortable headers
preserve the current window scroll position by default and wait for an async
onSortChange before restoring scroll position.
Body rows change background on pointer hover by default. Set
hoverable={false} to disable that behavior. When zebra={false}, the body
uses var(--suu-color-bg) as its explicit background instead of alternating
row colors.
Column alignment is configured separately for headers and body cells.
Horizontal alignment accepts left, center, or right; vertical alignment
accepts top, middle, or bottom. Header alignment defaults to
left/middle; cell alignment defaults to left/top.
Use headerHorizontalAlign, headerVerticalAlign, cellHorizontalAlign, and
cellVerticalAlign instead of the older combined align field.
Pagination is also available as a standalone module when an app needs
pagination outside DataTable:
<script lang="ts">
import { Pagination, type PaginationState } from '@ibobbyts/svelte-ui-utils/pagination';
let pagination: PaginationState = { page: 1, pageSize: 20 };
</script>
<Pagination
{pagination}
totalRows={totalRows}
pageSizeOptions={[10, 20, 50, 100]}
pageSizeDropdownPlacement="down"
onPaginationChange={(next) => {
pagination = next;
}}
/>Render two synchronized standalone pagination bars by passing both instances
the same controlled pagination value and the same onPaginationChange
handler. Standalone Pagination remains controlled; DataTable owns its own
server-pagination state.
FilterTable is filter-only. It accepts rows, where each row has a title
for the left column and a controlled filter created with the filter helper:
<script lang="ts">
import { FilterTable, filter } from '@ibobbyts/svelte-ui-utils/table';
const filterRows = [
{
key: 'status',
title: 'Status',
filter: filter.checkbox({
value: selectedStatuses,
options: [
{ label: 'Active', value: 'active' },
{ label: 'Archived', value: 'archived' }
],
onChange: (value) => (selectedStatuses = value)
})
},
{
key: 'search',
title: 'Search',
filter: filter.container([
filter.dropdownSearch({
value: searchValue,
selectedItem,
width: '24rem',
maxWidth: '100%',
loadOptions,
onChange: (detail) => updateSearch(detail)
}),
filter.button({ icon: 'search', label: 'Find', onClick: submitSearch })
])
}
];
</script>
<FilterTable rows={filterRows} language="en_us" />FilterTable uses the same 1px solid var(--suu-color-border) outer border
and var(--suu-radius) corner radius as a bordered DataTable. Set
bordered={false} to remove both the border and outer corner radius.
The left title column fits its content by default (max-content plus
white-space: nowrap, with the control column claiming all remaining width).
Set the --suu-filter-table-title-width CSS variable on the FilterTable or
any ancestor when a page needs a fixed width instead:
.my-filters {
--suu-filter-table-title-width: 10rem;
}filter.text renders a free-text search input for keyword contains-style
filtering. Unlike filter.dropdownSearch it has no selection semantics: the
value is the raw input text, and matching stays in the consuming app:
{
key: 'location',
title: 'Location',
filter: filter.text({
value: locationQuery,
placeholder: 'Search location',
ariaLabel: 'Location filter',
onChange: (value) => (locationQuery = value)
})
}Every keystroke reports by default; pass debounceMs to batch changes (Enter
flushes the pending draft immediately). The input stays a controlled input:
applying the new value from onChange keeps typing intact, and resetting
value clears the field. Width follows the width/minWidth/maxWidth
props when the full-row default is not what you want.
filter.select uses the shared Dropdown component, so select filters keep the
same menu, keyboard, and visual behavior as standalone dropdowns.
filter.dropdown maps a filter row onto the unified Dropdown API with
label/value options: pass static options or optionGroups (with
groupsCollapsedByDefault), set multiselect to collect an array, or set
search with loadOptions to run the async search flow inside the filter row:
{
key: 'assignee',
title: 'Assignee',
filter: filter.dropdown({
value: assignee,
search: true,
loadOptions: searchUsers,
ariaLabel: 'Assignee',
width: '18rem',
onChange: (next) => {
assignee = next;
}
})
}dateRange renders two browser date inputs, preset buttons, and quick month/year
selects. The presets are last 24 hours, last 7 days, last 30 days,
today, this week, this month, and this year. Manual changes and quick
month/year changes emit { startDate, endDate, preset: null }. When the month is
selected first, the year select fills with the most recent matching year. For
example, in July 2026, July resolves to 2026 and August resolves to 2025. Pass
defaultPreset to apply a preset on mount when the current value is empty.
Clicking the currently active preset clears both date inputs and emits an empty
range. thisWeek, thisMonth, and thisYear cover the complete calendar
period, including days after today. The last24Hours preset also emits
startDateTime and endDateTime so
a consuming app can run an exact timestamp query while still showing the covered
dates in the inputs.
Pass presets to fully control the preset row. Each entry is one of:
- a built-in preset key:
'last24Hours','last7Days','last30Days','today','thisWeek','thisMonth','thisYear'; - a custom preset object
{ key, label?, resolve }, whereresolvereceives{ now, weekStartsOn }and returns{ startDate, endDate }dates that the component formats into the value; - a consumer-controlled select object
{ type: 'select', key, value, options, ariaLabel?, onChange }, rendered as a dropdown inside the preset row (for example a year picker whose selection feeds custom preset resolvers); the component only reports selection changes, the consumer owns the value; 'quickMonth'or'quickYear'for the quick month/year selects;'divider'for a visual separator between entries.
When presets is omitted the default row is used: the seven built-in buttons
with dividers after last 30 days and this year, then both quick selects.
Custom preset keys are stored in value.preset as plain strings, so
defaultPreset and the active-button highlight work with them too. Custom
labels resolve from label, then presetLabels[key], then the key itself.
Preset and select keys must be unique within one presets list; duplicate
keys make the active-state highlight and the defaultPreset lookup ambiguous.
numberRange renders min/max number inputs and supports prefixLabel, for
example $ for currency filters.
Localization
Components that render package-owned text accept language="en_us",
language="zh_cn", or language="zh_tw". This affects only built-in defaults:
toast close labels, dropdown loading/empty/clear labels, table empty and
pagination labels, date range labels and presets, and number range labels.
Business labels such as column headers, filter row titles, button labels, and
placeholders should still be passed by the consuming app. Explicit props such
as closeLabel, clearLabel, noResultsText, emptyText, startLabel, and
minLabel, plus nested settings such as pagination.pageSizeLabel, always
override the language defaults.
Pass pagination={false} for a non-paginated data table:
<DataTable
rows={rows}
{columns}
pagination={false}
rowKey="id"
tableLayout="fixed"
stickyHeader={true}
stickyHeaderOffset="4rem"
verticalSeparators={true}
preserveScrollOnSort={true}
rowAttributes={(row) => ({ 'data-row-id': row.id })}
onSortChange={(sort) => updateUrl(sort)}
>
<svelte:fragment slot="cell" let:row let:column let:value>
{#if column.key === 'actions'}
<button type="button">Open</button>
{:else}
{value}
{/if}
</svelte:fragment>
</DataTable>Set preserveScrollOnSort={false} when a page should intentionally return to
the top after sorting. DataTable headers are sticky by default. Use
stickyHeader={false} to disable this, or set stickyHeaderOffset when an app
has a fixed or sticky navbar. The offset accepts any browser CSS length such as
64px, 4rem, or calc(...), and it is used both for the fixed header
position and for the scroll threshold. When the original header top reaches the
offset, a synchronized fixed header takes over while the original header keeps
its layout space. The older stickyHeaderTop prop and
--suu-table-sticky-top CSS variable remain supported.
Theme variables
The package ships plain CSS and CSS variables. Override variables globally or inside a theme root:
:root {
--suu-color-bg: #ffffff;
--suu-color-text: #111827;
--suu-color-border: #d1d5db;
--suu-color-accent: #2563eb;
}
[data-theme='dark'] {
--suu-color-bg: #111827;
--suu-color-text: #f9fafb;
--suu-color-border: #374151;
--suu-color-accent: #60a5fa;
}Overlay surface tokens
Dropdown menus render as floating overlays: they step the page background up
(--suu-color-elevated, derived from the surface/bg palette) and lift off the
page with --suu-shadow-overlay (a deep shadow plus a hairline ring so the
outline stays readable over host grid lines). Both resolve against the current
theme palette automatically.
Inside the menu, row semantics come from --suu-dropdown-* tokens declared on
.suu-dropdown: --suu-dropdown-option-separator (faint line between
options), --suu-dropdown-group-border / --suu-dropdown-group-bg /
--suu-dropdown-group-text (the section header band), and
--suu-dropdown-option-hover-bg / --suu-dropdown-option-selected-bg /
--suu-dropdown-option-selected-hover-bg. They are palette-derived color
mixes, so light and dark themes keep the same hierarchy: panel frame > group
band boundary > option separator, and selected > hover. Only override them for
a deliberately different overlay treatment.
下拉选项默认最小行高为 36px,分组标题为 32px;长文本仍可撑高。 分组通过中性底色、加粗标题和组内选项缩进区分,未分组的选项不缩进。
Corner-radius tokens
All non-zero component corner radii come from the token definitions in
src/lib/style.css. Reuse an existing token before adding another radius; when
a confirmed design requirement needs a new size, define it in that token block
first and reference it from components.
| Token | Default | Intended use |
| --- | ---: | --- |
| --suu-radius-xs | 4px | compact checks and small indicators |
| --suu-radius-sm | 6px | compact controls |
| --suu-radius-md | 8px | standard controls and surfaces |
| --suu-radius-lg | standard radius plus 2px | dialogs and prominent surfaces |
| --suu-radius-pill | 999px | pills and circular controls |
| --suu-radius | --suu-radius-md | backward-compatible standard radius override |
| --suu-radius-inner | standard radius minus 1px | inner fill inside a standard 1px border |
Use 0 directly when a component intentionally has square corners. Component
styles must not introduce other numeric border-radius values or ad hoc radius
calculations.
Release
Do not publish this package as part of consumer-app local integration work. Publish only when a release is explicitly requested.
Releases publish from CI via npm Trusted Publishing (OIDC): bump the version
in package.json, commit, then push a vX.Y.Z tag. That runs
.github/workflows/npm-publish.yml, which
installs from the committed lockfile, runs svelte-check and vitest, and
publishes with no npm token in the environment — the runner's OIDC identity is
the credential (id-token: write). The tag must match package.json's
version. The trusted publisher is linked on npmjs.com (user iBobbyTS, repo
svelte-ui-utils, workflow npm-publish.yml); the workflow filename is part
of that link and must not be renamed. prepublishOnly builds dist/ before
the tarball is packed, so no publish path can ship stale output.
Bun install verification
The repository includes a Bun Consumer Check workflow. It creates a temporary
consumer project and installs the released npm version without registry-specific
tokens:
bun add @ibobbyts/[email protected] svelteUse it after each release when a Bun-based project will consume the package.
分段日期输入(本地新增,尚未发布)
<script lang="ts">
import { SegmentedDateInput } from '@ibobbyts/svelte-ui-utils/segmented-date';
let dob = $state('');
</script>
<SegmentedDateInput name="dob" bind:value={dob} ariaLabel="生日"
yearLabel="年" monthLabel="月" dayLabel="日" autocomplete="bday" />支持 precision="year" | "month" | "day"(默认 day)、数字输入、全角数字归一化、完整日期粘贴及月日失焦补零。value 可双向绑定;onvalueinput 接收用户输入后的组合值。日历有效性和业务范围由调用方校验。
默认用隐藏字段提交组合值;submitParts={true} 改为提交 ${name}Year、${name}Month、${name}Day(按精度决定字段)。支持 required、readonly、disabled、id(关联年输入框)和生日自动填充。ariaLabel、各段标签及占位符由调用方提供,以接入应用本地化。
引入公共 style.css 后可独立使用,无需 Tailwind 或 DaisyUI。class 定制容器;inputClass 替换默认输入框装饰样式,布局仍由组件负责。MMS 通过该参数保留 DaisyUI 外观。
纯函数和类型可从 @ibobbyts/svelte-ui-utils/segmented-date/state 引入:splitSegmentedDate、composeSegmentedDate、parsePastedSegmentedDate、SegmentedDateParts、SegmentedDatePrecision;此入口不加载 Svelte,适用于服务端和 Node。
