@sparkwire/mcp 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/data/docs.json +4963 -0
- package/data/r/accordion.json +26 -0
- package/data/r/alert.json +26 -0
- package/data/r/avatar.json +26 -0
- package/data/r/base.json +55 -0
- package/data/r/button.json +33 -0
- package/data/r/card.json +26 -0
- package/data/r/charts.json +40 -0
- package/data/r/checkbox.json +27 -0
- package/data/r/combobox.json +30 -0
- package/data/r/command-palette.json +29 -0
- package/data/r/dashboard.json +34 -0
- package/data/r/data-table.json +39 -0
- package/data/r/date-picker.json +56 -0
- package/data/r/drawer.json +29 -0
- package/data/r/dropdown.json +30 -0
- package/data/r/field.json +26 -0
- package/data/r/file-upload.json +28 -0
- package/data/r/headless.json +27 -0
- package/data/r/indicators.json +26 -0
- package/data/r/input-base.json +21 -0
- package/data/r/menu.json +32 -0
- package/data/r/modal.json +29 -0
- package/data/r/navigation.json +26 -0
- package/data/r/number-field.json +30 -0
- package/data/r/provider.json +47 -0
- package/data/r/radio-group.json +26 -0
- package/data/r/select.json +21 -0
- package/data/r/settings.json +37 -0
- package/data/r/sidebar.json +30 -0
- package/data/r/sign-in.json +31 -0
- package/data/r/slider.json +29 -0
- package/data/r/spark.json +26 -0
- package/data/r/stepper.json +26 -0
- package/data/r/styles.json +17 -0
- package/data/r/switch.json +26 -0
- package/data/r/tabs.json +29 -0
- package/data/r/textarea.json +28 -0
- package/data/r/textfield.json +57 -0
- package/data/r/time-picker.json +32 -0
- package/data/r/toast.json +26 -0
- package/data/r/toggle-group.json +29 -0
- package/data/r/tooltip.json +29 -0
- package/data/r/utils.json +63 -0
- package/data/registry.json +1219 -0
- package/package.json +40 -4
- package/src/server.mjs +179 -0
- package/README.md +0 -3
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
{
|
|
2
|
+
"$schema": "https://ui.shadcn.com/schema/registry-item.json",
|
|
3
|
+
"name": "dashboard",
|
|
4
|
+
"type": "registry:block",
|
|
5
|
+
"title": "Dashboard",
|
|
6
|
+
"description": "Sidebar, KPI tiles with sparklines, revenue and channel charts, and a recent-orders table.",
|
|
7
|
+
"dependencies": [],
|
|
8
|
+
"registryDependencies": [
|
|
9
|
+
"@sparkwire/avatar",
|
|
10
|
+
"@sparkwire/button",
|
|
11
|
+
"@sparkwire/card",
|
|
12
|
+
"@sparkwire/charts",
|
|
13
|
+
"@sparkwire/data-table",
|
|
14
|
+
"@sparkwire/indicators",
|
|
15
|
+
"@sparkwire/sidebar",
|
|
16
|
+
"@sparkwire/styles",
|
|
17
|
+
"@sparkwire/toggle-group",
|
|
18
|
+
"@sparkwire/utils"
|
|
19
|
+
],
|
|
20
|
+
"files": [
|
|
21
|
+
{
|
|
22
|
+
"path": "components/spark-ui/blocks/Dashboard/Dashboard.tsx",
|
|
23
|
+
"type": "registry:component",
|
|
24
|
+
"target": "components/spark-ui/blocks/Dashboard/Dashboard.tsx",
|
|
25
|
+
"content": "import React, { useState } from 'react';\nimport { Sidebar } from '../../Sidebar';\nimport { Card } from '../../Card';\nimport { Badge } from '../../Indicators';\nimport { Avatar } from '../../Avatar';\nimport { Button } from '../../Button';\nimport { ToggleGroup } from '../../ToggleGroup';\nimport { LineChart, BarChart, Sparkline } from '../../Charts';\nimport { DataTable } from '../../DataTable';\nimport type { DataTableColumn } from '../../DataTable';\n\n/**\n * Dashboard block: sidebar, KPI tiles with sparklines, a revenue chart, a\n * channel breakdown and a recent-orders table. Copy it with\n * `npx sparkwire add dashboard`, then replace the sample data with yours.\n */\nconst icon = (d: string) => (\n <svg width=\"18\" height=\"18\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"2\" strokeLinecap=\"round\" strokeLinejoin=\"round\" aria-hidden=\"true\">\n <path d={d} />\n </svg>\n);\n\nconst months = ['Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov'];\nconst revenue = months.map((month, i) => ({ month, online: 18 + i * 3 + (i % 2) * 2, stores: 12 + i * 1.5 }));\nconst channels = [\n { channel: 'Search', orders: 1840 },\n { channel: 'Direct', orders: 1210 },\n { channel: 'Social', orders: 860 },\n { channel: 'Email', orders: 430 },\n];\ntype Order = { id: string; customer: string; city: string; amount: number; status: 'Paid' | 'Pending' | 'Refunded' };\nconst orders: Order[] = [\n { id: 'ORD-2041', customer: 'Aarav Shah', city: 'Ahmedabad', amount: 4999, status: 'Paid' },\n { id: 'ORD-2040', customer: 'Diya Patel', city: 'Surat', amount: 1299, status: 'Pending' },\n { id: 'ORD-2039', customer: 'Kabir Mehta', city: 'Rajkot', amount: 8450, status: 'Paid' },\n { id: 'ORD-2038', customer: 'Ananya Iyer', city: 'Chennai', amount: 2150, status: 'Refunded' },\n { id: 'ORD-2037', customer: 'Vihaan Rao', city: 'Bengaluru', amount: 3620, status: 'Paid' },\n];\nconst inr = new Intl.NumberFormat('en-IN', { style: 'currency', currency: 'INR', maximumFractionDigits: 0 });\nconst tone = { Paid: 'success', Pending: 'warning', Refunded: 'error' } as const;\nconst columns: DataTableColumn<Order>[] = [\n { key: 'id', header: 'Order', sortable: true },\n { key: 'customer', header: 'Customer', sortable: true, searchable: true, cell: (r) => <span style={{ display: 'inline-flex', alignItems: 'center', gap: 8 }}><Avatar name={r.customer} size=\"small\" />{r.customer}</span> },\n { key: 'city', header: 'City', sortable: true },\n { key: 'amount', header: 'Amount', sortable: true, cell: (r) => inr.format(r.amount) },\n { key: 'status', header: 'Status', cell: (r) => <Badge tone={tone[r.status]}>{r.status}</Badge> },\n];\n\nconst kpis = [\n { label: 'Revenue', value: '₹38.4L', delta: '+12.4%', up: true, trend: [22, 24, 23, 27, 29, 31, 34] },\n { label: 'Orders', value: '4,340', delta: '+8.1%', up: true, trend: [510, 560, 590, 640, 680, 700, 720] },\n { label: 'Avg. order', value: '₹885', delta: '+3.9%', up: true, trend: [820, 830, 845, 840, 860, 870, 885] },\n { label: 'Refund rate', value: '1.8%', delta: '−0.4 pts', up: false, trend: [2.6, 2.4, 2.3, 2.2, 2.0, 1.9, 1.8] },\n];\n\nexport function Dashboard() {\n const [range, setRange] = useState<string | null>('6m');\n const [menuOpen, setMenuOpen] = useState(false);\n return (\n <div className=\"sp-block-dashboard\">\n <Sidebar\n aria-label=\"Dashboard\"\n defaultValue=\"overview\"\n mobileOpen={menuOpen}\n onMobileOpenChange={setMenuOpen}\n header={(collapsed) => <strong className=\"sp-block-brand\">{collapsed ? 'S' : 'Sparkwire'}</strong>}\n items={[\n { id: 'overview', label: 'Overview', icon: icon('M3 12l9-9 9 9M5 10v10h14V10') },\n { id: 'orders', label: 'Orders', icon: icon('M6 2h12l1 6H5zM5 8h14v13H5z'), badge: '12' },\n { id: 'customers', label: 'Customers', icon: icon('M16 21v-2a4 4 0 0 0-8 0v2M12 11a4 4 0 1 0 0-8 4 4 0 0 0 0 8') },\n { heading: 'Reports', items: [\n { id: 'sales', label: 'Sales', icon: icon('M3 3v18h18M7 14l4-4 4 4 5-6') },\n { id: 'settings', label: 'Settings', icon: icon('M12 15a3 3 0 1 0 0-6 3 3 0 0 0 0 6zM19.4 15a1.7 1.7 0 0 0 .3 1.8l.1.1a2 2 0 1 1-2.8 2.8l-.1-.1a1.7 1.7 0 0 0-1.8-.3 1.7 1.7 0 0 0-1 1.5V21a2 2 0 1 1-4 0v-.1a1.7 1.7 0 0 0-1.1-1.5 1.7 1.7 0 0 0-1.8.3l-.1.1a2 2 0 1 1-2.8-2.8l.1-.1a1.7 1.7 0 0 0 .3-1.8 1.7 1.7 0 0 0-1.5-1H3a2 2 0 1 1 0-4h.1a1.7 1.7 0 0 0 1.5-1.1 1.7 1.7 0 0 0-.3-1.8l-.1-.1a2 2 0 1 1 2.8-2.8l.1.1a1.7 1.7 0 0 0 1.8.3H9a1.7 1.7 0 0 0 1-1.5V3a2 2 0 1 1 4 0v.1a1.7 1.7 0 0 0 1 1.5 1.7 1.7 0 0 0 1.8-.3l.1-.1a2 2 0 1 1 2.8 2.8l-.1.1a1.7 1.7 0 0 0-.3 1.8V9a1.7 1.7 0 0 0 1.5 1H21a2 2 0 1 1 0 4h-.1a1.7 1.7 0 0 0-1.5 1z') },\n ] },\n ]}\n footer={(collapsed) => <span className=\"sp-block-user\"><Avatar name=\"Anmol Mehta\" size=\"small\" status=\"online\" />{!collapsed && 'Anmol Mehta'}</span>}\n />\n <main className=\"sp-block-main\">\n <header className=\"sp-block-header\">\n <button type=\"button\" className=\"sp-block-menu\" aria-label=\"Open menu\" aria-expanded={menuOpen} onClick={() => setMenuOpen(true)}>\n {icon('M4 6h16M4 12h16M4 18h16')}\n </button>\n <div className=\"sp-block-title\">\n <h1>Overview</h1>\n <p>Sales across all channels</p>\n </div>\n <div className=\"sp-block-actions\">\n <ToggleGroup aria-label=\"Range\" value={range} onChange={setRange} size=\"small\">\n <ToggleGroup.Item value=\"30d\">30 days</ToggleGroup.Item>\n <ToggleGroup.Item value=\"6m\">6 months</ToggleGroup.Item>\n <ToggleGroup.Item value=\"1y\">1 year</ToggleGroup.Item>\n </ToggleGroup>\n <Button size=\"small\">Export</Button>\n </div>\n </header>\n\n <section className=\"sp-block-kpis\" aria-label=\"Key figures\">\n {kpis.map((k) => (\n <Card key={k.label} padding=\"medium\">\n <div className=\"sp-block-kpi\">\n <span className=\"sp-block-kpi__label\">{k.label}</span>\n <span className=\"sp-block-kpi__value\">{k.value}</span>\n <span className=\"sp-block-kpi__row\">\n <Badge tone={k.up === (k.label !== 'Refund rate') ? 'success' : 'error'} led={false}>{k.delta}</Badge>\n <Sparkline aria-label={`${k.label}, last 7 periods`} data={k.trend} area />\n </span>\n </div>\n </Card>\n ))}\n </section>\n\n <section className=\"sp-block-charts\">\n <Card padding=\"medium\">\n <LineChart title=\"Revenue (₹ lakh)\" data={revenue} x=\"month\" series={[{ key: 'online', label: 'Online' }, { key: 'stores', label: 'Stores' }]} area height={240} />\n </Card>\n <Card padding=\"medium\">\n <BarChart title=\"Orders by channel\" data={channels} x=\"channel\" series={[{ key: 'orders', label: 'Orders' }]} horizontal height={240} tableView={false} />\n </Card>\n </section>\n\n <Card padding=\"medium\">\n <DataTable aria-label=\"Recent orders\" data={orders} columns={columns} searchable density=\"compact\" pageSizeOptions={[5, 10]} />\n </Card>\n </main>\n </div>\n );\n}\n"
|
|
26
|
+
},
|
|
27
|
+
{
|
|
28
|
+
"path": "components/spark-ui/blocks/Dashboard/index.ts",
|
|
29
|
+
"type": "registry:component",
|
|
30
|
+
"target": "components/spark-ui/blocks/Dashboard/index.ts",
|
|
31
|
+
"content": "export { Dashboard } from './Dashboard';\n"
|
|
32
|
+
}
|
|
33
|
+
]
|
|
34
|
+
}
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
{
|
|
2
|
+
"$schema": "https://ui.shadcn.com/schema/registry-item.json",
|
|
3
|
+
"name": "data-table",
|
|
4
|
+
"type": "registry:ui",
|
|
5
|
+
"title": "DataTable",
|
|
6
|
+
"description": "Sort, search, filter, page and select rows; responsive div grid, no table library.",
|
|
7
|
+
"dependencies": [
|
|
8
|
+
"@react-types/shared@^3.37.0",
|
|
9
|
+
"react-aria@^3.53.1",
|
|
10
|
+
"react-stately@^3.51.0"
|
|
11
|
+
],
|
|
12
|
+
"registryDependencies": [
|
|
13
|
+
"@sparkwire/base",
|
|
14
|
+
"@sparkwire/checkbox",
|
|
15
|
+
"@sparkwire/dropdown",
|
|
16
|
+
"@sparkwire/styles",
|
|
17
|
+
"@sparkwire/utils"
|
|
18
|
+
],
|
|
19
|
+
"files": [
|
|
20
|
+
{
|
|
21
|
+
"path": "components/spark-ui/DataTable/DataTable.tsx",
|
|
22
|
+
"type": "registry:ui",
|
|
23
|
+
"target": "components/spark-ui/DataTable/DataTable.tsx",
|
|
24
|
+
"content": "import React, { useRef } from 'react';\nimport { useMessages } from '../internal/messages';\nimport {\n useLocale,\n useTable,\n useTableCell,\n useTableColumnHeader,\n useTableHeaderRow,\n useTableRow,\n useTableRowGroup,\n useTableSelectAllCheckbox,\n useTableSelectionCheckbox,\n} from 'react-aria';\nimport { Cell, Column, Row, TableBody, TableHeader, useTableState, TableState } from 'react-stately';\nimport type { Node } from '@react-types/shared';\ntype GridNode<T> = Node<T>;\nimport type { Key, Selection, SortDescriptor } from '@react-types/shared';\nimport { Checkbox } from '../Checkbox';\nimport { Dropdown } from '../Dropdown';\nimport { InputBase } from '../base/InputBase';\nimport { useDefaults, slot, ClassNames } from '../internal/defaults';\nimport { cx } from '../internal/cx';\nimport { DataTableColumn, UseDataTableOptions, useDataTable, DataTableModel } from './useDataTable';\n\nexport interface DataTableProps<RowT> extends UseDataTableOptions<RowT> {\n /** Accessible name; describe what the table lists. */\n 'aria-label'?: string;\n 'aria-labelledby'?: string;\n /** `multiple` adds checkboxes; `single` selects one row. Default `none`. */\n selectionMode?: 'none' | 'single' | 'multiple';\n /** Called when a row is activated (click, or Enter on the row). */\n onRowAction?: (row: RowT, key: string) => void;\n /** Show a search box over the table. */\n searchable?: boolean;\n /** Placeholder for the search box. */\n searchPlaceholder?: string;\n /** Extra content in the toolbar, e.g. filter dropdowns or an export button. */\n toolbar?: React.ReactNode;\n /** Actions shown when rows are selected, e.g. a delete button. Receives the selected rows. */\n bulkActions?: (rows: RowT[]) => React.ReactNode;\n /** Page sizes to offer. Default `[10, 25, 50]`. Pass `[]` to hide the picker. */\n pageSizeOptions?: number[];\n /** Row height. Default `normal`. */\n density?: 'compact' | 'normal' | 'comfortable';\n /** Shade every other row. */\n striped?: boolean;\n /** Fix the height and scroll the body under a sticky header, e.g. `400`. */\n maxHeight?: number | string;\n /**\n * In a narrow container: `stack` (default) turns rows into labelled cards;\n * `scroll` keeps the grid and scrolls sideways.\n */\n responsive?: 'stack' | 'scroll';\n /** Container width (px) below which rows stack. Default 640. */\n stackBelow?: number;\n /** Show placeholder rows while data loads. */\n loading?: boolean;\n /** Shown when there are no rows. Default \"No results\". */\n emptyState?: React.ReactNode;\n className?: string;\n /** Extra classes for each part. */\n classNames?: ClassNames<'root' | 'toolbar' | 'grid' | 'header' | 'columnHeader' | 'row' | 'cell' | 'footer'>;\n}\n\nconst width = (w?: number | string) => (w === undefined ? 'minmax(8rem, 1fr)' : typeof w === 'number' ? `${w}px` : w);\nconst isNumberish = (v: unknown) => typeof v === 'number' || typeof v === 'bigint';\nconst textOf = (node: React.ReactNode): string => (typeof node === 'string' || typeof node === 'number' ? String(node) : '');\n\n/**\n * DataTable: sort, search, filter, page and select rows. Built from divs on a\n * CSS grid (like MUI's Data Grid), so it adapts to its container: in narrow\n * spaces rows become labelled cards. The table logic is Spark UI's own\n * (`useDataTable`); React Aria supplies grid keyboard navigation and\n * screen-reader semantics. Sorted headers and selected rows light up.\n *\n * Keyboard: arrows move between cells, Home/End and Page Up/Down jump,\n * Space selects a row, Enter activates it, Shift+click sorts by more than\n * one column.\n *\n * Style hooks: `.sp-data-table[data-density][data-striped][data-responsive]`,\n * `__toolbar`, `__grid[aria-busy]`, `__header`, `__column[data-sorted][data-sortable]`,\n * `__row[data-selected][data-focus-visible]`, `__cell[data-align]`, `__footer`.\n */\nexport function DataTable<RowT>(inProps: DataTableProps<RowT>) {\n const props = useDefaults('DataTable', inProps) as DataTableProps<RowT>;\n const m = useMessages();\n const {\n 'aria-label': ariaLabel,\n 'aria-labelledby': ariaLabelledby,\n selectionMode = 'none',\n onRowAction,\n searchable,\n searchPlaceholder = m.search,\n toolbar,\n bulkActions,\n pageSizeOptions = [10, 25, 50],\n density = 'normal',\n striped,\n maxHeight,\n responsive = 'stack',\n stackBelow = 640,\n loading,\n emptyState = m.noResults,\n className,\n classNames,\n } = props;\n const table = useDataTable<RowT>(props);\n const { locale } = useLocale();\n const numberFormat = new Intl.NumberFormat(locale);\n const dateFormat = new Intl.DateTimeFormat(locale, { dateStyle: 'medium' });\n\n const columns = table.columns;\n const selectedCount = table.selectedKeys.size;\n const template = [selectionMode === 'multiple' ? '3rem' : null, ...columns.map((c) => width(c.width))].filter(Boolean).join(' ');\n\n const display = (row: RowT, col: DataTableColumn<RowT>) => {\n const v = table.valueOf(row, col);\n if (col.cell) return col.cell(row, v);\n if (isNumberish(v)) return numberFormat.format(v as number);\n if (v instanceof Date) return dateFormat.format(v);\n return v === null || v === undefined ? '' : String(v);\n };\n const alignOf = (col: DataTableColumn<RowT>) =>\n col.align ?? (table.rows.length && isNumberish(table.valueOf(table.rows[0].row, col)) ? 'end' : 'start');\n\n return (\n <div\n className={slot('sp-data-table', classNames, 'root', className)}\n data-density={density}\n data-striped={striped || undefined}\n data-responsive={responsive}\n style={{ '--sp-cols': template, '--sp-stack-below': `${stackBelow}px` } as React.CSSProperties}\n >\n {(searchable || toolbar || (bulkActions && selectedCount > 0)) && (\n <div className={slot('sp-data-table__toolbar', classNames, 'toolbar')}>\n {bulkActions && selectedCount > 0 ? (\n <div className=\"sp-data-table__bulk\" role=\"status\">\n <span className=\"sp-data-table__count\">{numberFormat.format(selectedCount)} selected</span>\n {bulkActions(table.selectedRows)}\n <button type=\"button\" className=\"sp-data-table__link\" onClick={table.clearSelection}>\n Clear\n </button>\n </div>\n ) : (\n searchable && (\n <InputBase\n type=\"search\"\n size=\"small\"\n aria-label={ariaLabel ? m.searchNamed(ariaLabel) : m.search.replace('…', '')}\n placeholder={searchPlaceholder}\n value={table.search}\n onChange={(e) => table.setSearch(e.target.value)}\n classNames={{ root: 'sp-data-table__search' }}\n startAdornment={\n <svg width=\"16\" height=\"16\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"2\" strokeLinecap=\"round\" aria-hidden=\"true\">\n <circle cx=\"11\" cy=\"11\" r=\"7\" />\n <path d=\"M20 20l-3.5-3.5\" />\n </svg>\n }\n />\n )\n )}\n {toolbar && <div className=\"sp-data-table__tools\">{toolbar}</div>}\n </div>\n )}\n\n <Grid\n table={table}\n columns={columns}\n display={display}\n alignOf={alignOf}\n selectionMode={selectionMode}\n onRowAction={onRowAction}\n ariaLabel={ariaLabel}\n ariaLabelledby={ariaLabelledby}\n loading={loading}\n emptyState={emptyState}\n maxHeight={maxHeight}\n classNames={classNames}\n />\n\n {table.pageSize > 0 && (\n <div className={slot('sp-data-table__footer', classNames, 'footer')}>\n <span className=\"sp-data-table__range\" aria-live=\"polite\">\n {numberFormat.format(table.range.from)}–{numberFormat.format(table.range.to)} of {numberFormat.format(table.filteredCount)}\n </span>\n {pageSizeOptions.length > 0 && (\n <Dropdown\n aria-label={m.rowsPerPage}\n size=\"small\"\n className=\"sp-data-table__page-size\"\n value={table.pageSize}\n onChange={(v) => table.setPageSize(Number(v))}\n options={pageSizeOptions.map((n) => ({ value: n, label: `${n} / page` }))}\n />\n )}\n <div className=\"sp-data-table__pager\">\n <button type=\"button\" className=\"sp-field-button\" aria-label={m.previousPage} disabled={!table.canPrev} onClick={() => table.setPage(table.page - 1)}>\n <svg width=\"16\" height=\"16\" viewBox=\"0 0 16 16\" aria-hidden=\"true\">\n <path d=\"M10 3L5 8l5 5\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"2\" strokeLinecap=\"round\" strokeLinejoin=\"round\" />\n </svg>\n </button>\n <span className=\"sp-data-table__page\">\n {numberFormat.format(table.page + 1)} / {numberFormat.format(table.pageCount)}\n </span>\n <button type=\"button\" className=\"sp-field-button\" aria-label={m.nextPage} disabled={!table.canNext} onClick={() => table.setPage(table.page + 1)}>\n <svg width=\"16\" height=\"16\" viewBox=\"0 0 16 16\" aria-hidden=\"true\">\n <path d=\"M6 3l5 5-5 5\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"2\" strokeLinecap=\"round\" strokeLinejoin=\"round\" />\n </svg>\n </button>\n </div>\n </div>\n )}\n </div>\n );\n}\n\n/* ---------------------------------------------------------------- grid */\n\ninterface GridProps<RowT> {\n table: DataTableModel<RowT>;\n columns: DataTableColumn<RowT>[];\n display: (row: RowT, col: DataTableColumn<RowT>) => React.ReactNode;\n alignOf: (col: DataTableColumn<RowT>) => 'start' | 'center' | 'end';\n selectionMode: 'none' | 'single' | 'multiple';\n onRowAction?: (row: RowT, key: string) => void;\n ariaLabel?: string;\n ariaLabelledby?: string;\n loading?: boolean;\n emptyState: React.ReactNode;\n maxHeight?: number | string;\n classNames?: DataTableProps<RowT>['classNames'];\n}\n\nfunction Grid<RowT>({ table, columns, display, alignOf, selectionMode, onRowAction, ariaLabel, ariaLabelledby, loading, emptyState, maxHeight, classNames }: GridProps<RowT>) {\n const ref = useRef<HTMLDivElement>(null);\n const multiSort = useRef(false);\n const rowsByKey = new Map(table.rows.map((r) => [r.key, r.row]));\n const pageKeys = table.rows.map((r) => r.key);\n const first = table.sort[0];\n\n const ariaProps = {\n 'aria-label': ariaLabel,\n 'aria-labelledby': ariaLabelledby,\n selectionMode,\n selectionBehavior: 'toggle' as const,\n showSelectionCheckboxes: selectionMode === 'multiple',\n selectedKeys: new Set(pageKeys.filter((k) => table.isSelected(k))),\n onSelectionChange: (sel: Selection) => {\n const onPage = sel === 'all' ? new Set(pageKeys) : new Set(Array.from(sel, String));\n const next = new Set(Array.from(table.selectedKeys).filter((k) => !pageKeys.includes(k)));\n if (selectionMode === 'single') next.clear();\n onPage.forEach((k) => next.add(k));\n table.setSelectedKeys(next);\n },\n sortDescriptor: first ? { column: first.column, direction: first.direction } : undefined,\n onSortChange: (d: SortDescriptor) => {\n table.toggleSort(String(d.column), multiSort.current);\n multiSort.current = false;\n },\n onRowAction: onRowAction ? (key: Key) => onRowAction(rowsByKey.get(String(key)) as RowT, String(key)) : undefined,\n children: [\n <TableHeader key=\"header\" columns={columns}>\n {(col: DataTableColumn<RowT>) => (\n <Column key={col.key} allowsSorting={col.sortable} textValue={textOf(col.header) || col['aria-label'] || col.key}>\n {col.header}\n </Column>\n )}\n </TableHeader>,\n <TableBody key=\"body\" items={table.rows}>\n {(item: { row: RowT; key: string }) => (\n <Row key={item.key}>\n {(columnKey) => {\n const col = columns.find((c) => c.key === columnKey)!;\n const content = display(item.row, col);\n return <Cell textValue={typeof content === 'string' ? content : undefined}>{content}</Cell>;\n }}\n </Row>\n )}\n </TableBody>,\n ],\n };\n const state = useTableState<object>(ariaProps as never);\n const { gridProps } = useTable(ariaProps, state, ref);\n const headerRows = state.collection.headerRows;\n const bodyRows = Array.from(state.collection.body.childNodes) as GridNode<object>[];\n const colCount = state.collection.columnCount;\n\n return (\n <div\n {...gridProps}\n ref={ref}\n className={slot('sp-data-table__grid', classNames, 'grid')}\n aria-busy={loading || undefined}\n style={maxHeight !== undefined ? { maxHeight, overflow: 'auto' } : undefined}\n data-scroll={maxHeight !== undefined || undefined}\n >\n <RowGroup className={slot('sp-data-table__header', classNames, 'header')} type=\"thead\">\n {headerRows.map((headerRow) => (\n <HeaderRow key={headerRow.key} item={headerRow} state={state}>\n {Array.from(state.collection.getChildren!(headerRow.key) as Iterable<GridNode<object>>).map((column) =>\n column.props?.isSelectionCell ? (\n <SelectAllCell key={column.key} column={column} state={state} />\n ) : (\n <ColumnHeader\n key={column.key}\n column={column}\n state={state}\n table={table}\n align={alignOf(columns.find((c) => c.key === column.key)!)}\n className={classNames?.columnHeader}\n onShift={(shift) => (multiSort.current = shift)}\n />\n ),\n )}\n </HeaderRow>\n ))}\n </RowGroup>\n <RowGroup className=\"sp-data-table__body\" type=\"tbody\">\n {loading && bodyRows.length === 0 ? (\n Array.from({ length: Math.min(table.pageSize || 5, 5) }, (_, i) => (\n <div key={i} role=\"row\" className=\"sp-data-table__row sp-data-table__row--loading\">\n {Array.from({ length: colCount }, (_, j) => (\n <div key={j} role=\"gridcell\" className=\"sp-data-table__cell\">\n <span className=\"sp-data-table__shimmer\" />\n </div>\n ))}\n </div>\n ))\n ) : bodyRows.length === 0 ? (\n <div role=\"row\" className=\"sp-data-table__row sp-data-table__row--empty\">\n <div role=\"gridcell\" aria-colspan={colCount} className=\"sp-data-table__empty\">\n {emptyState}\n </div>\n </div>\n ) : (\n bodyRows.map((row) => (\n <TableRow key={row.key} item={row} state={state} className={classNames?.row} interactive={Boolean(onRowAction) || selectionMode !== 'none'}>\n {Array.from(state.collection.getChildren!(row.key) as Iterable<GridNode<object>>).map((cell) => {\n const column = state.collection.columns[cell.index!];\n if (column?.props?.isSelectionCell) return <SelectionCell key={cell.key} cell={cell} state={state} />;\n const col = columns.find((c) => c.key === column?.key);\n return (\n <TableCell\n key={cell.key}\n cell={cell}\n state={state}\n label={col ? textOf(col.header) || col['aria-label'] || '' : ''}\n align={col ? alignOf(col) : 'start'}\n className={classNames?.cell}\n />\n );\n })}\n </TableRow>\n ))\n )}\n </RowGroup>\n </div>\n );\n}\n\nfunction RowGroup({ type, className, children }: { type: 'thead' | 'tbody'; className: string; children: React.ReactNode }) {\n const { rowGroupProps } = useTableRowGroup();\n return (\n <div {...rowGroupProps} className={className} data-group={type}>\n {children}\n </div>\n );\n}\n\nfunction HeaderRow({ item, state, children }: { item: GridNode<object>; state: TableState<object>; children: React.ReactNode }) {\n const ref = useRef<HTMLDivElement>(null);\n const { rowProps } = useTableHeaderRow({ node: item }, state, ref);\n return (\n <div {...rowProps} ref={ref} className=\"sp-data-table__header-row\">\n {children}\n </div>\n );\n}\n\nfunction ColumnHeader<RowT>({\n column,\n state,\n table,\n align,\n className,\n onShift,\n}: {\n column: GridNode<object>;\n state: TableState<object>;\n table: DataTableModel<RowT>;\n align: string;\n className?: string;\n onShift: (shift: boolean) => void;\n}) {\n const ref = useRef<HTMLDivElement>(null);\n const { columnHeaderProps } = useTableColumnHeader({ node: column }, state, ref);\n const sortable = Boolean(column.props?.allowsSorting);\n const direction = table.sortOf(String(column.key));\n const order = table.sortIndex(String(column.key));\n // React Aria marks only the first rule; announce every sorted column.\n const ariaSort = direction ?? (sortable ? 'none' : undefined);\n return (\n <div\n {...columnHeaderProps}\n ref={ref}\n aria-sort={ariaSort}\n className={cx('sp-data-table__column', className)}\n data-sortable={sortable || undefined}\n data-sorted={direction}\n data-align={align}\n onPointerDownCapture={(e) => onShift(e.shiftKey)}\n onKeyDownCapture={(e) => onShift(e.shiftKey)}\n >\n <span className=\"sp-data-table__column-label\">{column.rendered}</span>\n {sortable && (\n <span className=\"sp-data-table__sort\" aria-hidden=\"true\">\n <svg width=\"12\" height=\"12\" viewBox=\"0 0 12 12\">\n <path d={direction === 'descending' ? 'M3 4.5L6 8l3-3.5' : 'M3 7.5L6 4l3 3.5'} fill=\"none\" stroke=\"currentColor\" strokeWidth=\"1.8\" strokeLinecap=\"round\" strokeLinejoin=\"round\" />\n </svg>\n {order >= 0 && <span className=\"sp-data-table__sort-order\">{order + 1}</span>}\n </span>\n )}\n </div>\n );\n}\n\n/** Keep clicks on a checkbox from also reaching the row's press handler. */\nconst stop = { onPointerDown: (e: React.SyntheticEvent) => e.stopPropagation(), onClick: (e: React.SyntheticEvent) => e.stopPropagation() };\n\nfunction SelectAllCell({ column, state }: { column: GridNode<object>; state: TableState<object> }) {\n const ref = useRef<HTMLDivElement>(null);\n const { columnHeaderProps } = useTableColumnHeader({ node: column }, state, ref);\n const { checkboxProps } = useTableSelectAllCheckbox(state);\n return (\n <div {...columnHeaderProps} ref={ref} className=\"sp-data-table__column sp-data-table__select\">\n {state.selectionManager.selectionMode === 'multiple' && (\n <span {...stop}>\n <Checkbox\n size=\"small\"\n aria-label={checkboxProps['aria-label']}\n checked={Boolean(checkboxProps.isSelected)}\n indeterminate={checkboxProps.isIndeterminate}\n disabled={checkboxProps.isDisabled}\n onChange={() => checkboxProps.onChange?.(!checkboxProps.isSelected)}\n />\n </span>\n )}\n </div>\n );\n}\n\nfunction TableRow({ item, state, className, interactive, children }: { item: GridNode<object>; state: TableState<object>; className?: string; interactive: boolean; children: React.ReactNode }) {\n const ref = useRef<HTMLDivElement>(null);\n const { rowProps, isSelected, isPressed } = useTableRow({ node: item }, state, ref);\n const focused = state.selectionManager.isFocused && state.selectionManager.focusedKey === item.key;\n return (\n <div\n {...rowProps}\n ref={ref}\n className={cx('sp-data-table__row', className)}\n data-selected={isSelected || undefined}\n data-pressed={isPressed || undefined}\n data-focused={focused || undefined}\n data-interactive={interactive || undefined}\n >\n {children}\n </div>\n );\n}\n\nfunction TableCell({ cell, state, label, align, className }: { cell: GridNode<object>; state: TableState<object>; label: string; align: string; className?: string }) {\n const ref = useRef<HTMLDivElement>(null);\n const { gridCellProps } = useTableCell({ node: cell }, state, ref);\n return (\n <div {...gridCellProps} ref={ref} className={cx('sp-data-table__cell', className)} data-align={align} data-label={label || undefined}>\n <span className=\"sp-data-table__cell-content\">{cell.rendered}</span>\n </div>\n );\n}\n\nfunction SelectionCell({ cell, state }: { cell: GridNode<object>; state: TableState<object> }) {\n const ref = useRef<HTMLDivElement>(null);\n const { gridCellProps } = useTableCell({ node: cell }, state, ref);\n const { checkboxProps } = useTableSelectionCheckbox({ key: cell.parentKey! }, state);\n return (\n <div {...gridCellProps} ref={ref} className=\"sp-data-table__cell sp-data-table__select\">\n <span {...stop}>\n <Checkbox\n size=\"small\"\n aria-label={checkboxProps['aria-label']}\n checked={Boolean(checkboxProps.isSelected)}\n disabled={checkboxProps.isDisabled}\n onChange={() => checkboxProps.onChange?.(!checkboxProps.isSelected)}\n />\n </span>\n </div>\n );\n}\n\nexport default DataTable;\n"
|
|
25
|
+
},
|
|
26
|
+
{
|
|
27
|
+
"path": "components/spark-ui/DataTable/index.ts",
|
|
28
|
+
"type": "registry:ui",
|
|
29
|
+
"target": "components/spark-ui/DataTable/index.ts",
|
|
30
|
+
"content": "export { DataTable } from './DataTable';\nexport type { DataTableProps } from './DataTable';\nexport { useDataTable, defaultCompare, defaultFilter } from './useDataTable';\nexport type { DataTableColumn, SortRule, SortDirection, UseDataTableOptions, DataTableModel } from './useDataTable';\n"
|
|
31
|
+
},
|
|
32
|
+
{
|
|
33
|
+
"path": "components/spark-ui/DataTable/useDataTable.ts",
|
|
34
|
+
"type": "registry:ui",
|
|
35
|
+
"target": "components/spark-ui/DataTable/useDataTable.ts",
|
|
36
|
+
"content": "import { useMemo, useState } from 'react';\n\nexport type SortDirection = 'ascending' | 'descending';\nexport interface SortRule {\n /** Column key. */\n column: string;\n direction: SortDirection;\n}\n\nexport interface DataTableColumn<Row> {\n /** Unique key; also the row field read by default. */\n key: string;\n /** Header content. */\n header: React.ReactNode;\n /** Value used for sorting, filtering and default display. Default: `row[key]`. */\n accessor?: (row: Row) => unknown;\n /** Render the cell. Default: the accessor's value as text. */\n cell?: (row: Row, value: unknown) => React.ReactNode;\n /** Allow sorting by this column. Default `false`. */\n sortable?: boolean;\n /** Custom sort order (return <0, 0, >0). Default: numbers, dates, then text in the user's locale. */\n compare?: (a: unknown, b: unknown, rowA: Row, rowB: Row) => number;\n /** Include in the search box. Default `true` for text and numbers. */\n searchable?: boolean;\n /** Custom filter for this column's filter value. Default: case- and accent-insensitive \"contains\". */\n filter?: (value: unknown, filterValue: unknown, row: Row) => boolean;\n /** Text alignment. Numbers default to `end`. */\n align?: 'start' | 'center' | 'end';\n /** CSS width, e.g. `120` or `'20%'`. */\n width?: number | string;\n /** Hide the column (it still counts for search). */\n hidden?: boolean;\n /** Screen-reader text for headers without visible text (e.g. an actions column). */\n 'aria-label'?: string;\n}\n\nexport interface UseDataTableOptions<Row> {\n data: Row[];\n columns: DataTableColumn<Row>[];\n /** Stable id for each row. Default: `row.id`, then the index. */\n getRowKey?: (row: Row, index: number) => string;\n\n /** Controlled sort rules (first wins). */\n sort?: SortRule[];\n defaultSort?: SortRule[];\n onSortChange?: (sort: SortRule[]) => void;\n\n /** Controlled search text (matches any searchable column). */\n search?: string;\n defaultSearch?: string;\n onSearchChange?: (search: string) => void;\n\n /** Controlled per-column filter values, keyed by column. */\n filters?: Record<string, unknown>;\n defaultFilters?: Record<string, unknown>;\n onFiltersChange?: (filters: Record<string, unknown>) => void;\n\n /** Controlled page (0-based). */\n page?: number;\n defaultPage?: number;\n onPageChange?: (page: number) => void;\n /** Rows per page; `0` turns paging off. Default 10. */\n pageSize?: number;\n defaultPageSize?: number;\n onPageSizeChange?: (size: number) => void;\n\n /** Controlled selected row keys. */\n selectedKeys?: Set<string>;\n defaultSelectedKeys?: Iterable<string>;\n onSelectionChange?: (keys: Set<string>) => void;\n\n /**\n * Server-side mode: you sort, filter and page the data yourself (e.g. in an\n * API call) and pass the current page as `data` with the total `rowCount`.\n */\n manual?: boolean;\n /** Total rows on the server, for paging in `manual` mode. */\n rowCount?: number;\n}\n\n/** Controlled-or-uncontrolled state, like React's own inputs. */\nfunction useControllable<T>(value: T | undefined, defaultValue: T, onChange?: (v: T) => void) {\n const [inner, setInner] = useState(defaultValue);\n const current = value !== undefined ? value : inner;\n const set = (next: T) => {\n if (value === undefined) setInner(next);\n onChange?.(next);\n };\n return [current, set] as const;\n}\n\nconst collator = typeof Intl !== 'undefined' ? new Intl.Collator(undefined, { numeric: true, sensitivity: 'base' }) : null;\nconst fold = (s: string) => s.normalize('NFD').replace(/[\\u0300-\\u036f]/g, '').toLowerCase();\n\n/** Numbers and dates by value; everything else as text in the user's locale (10 after 9; \"é\" with \"e\"). Empty values last. */\nexport function defaultCompare(a: unknown, b: unknown): number {\n const empty = (v: unknown) => v === null || v === undefined || v === '';\n if (empty(a) || empty(b)) return empty(a) === empty(b) ? 0 : empty(a) ? 1 : -1;\n if (typeof a === 'number' && typeof b === 'number') return a - b;\n if (a instanceof Date && b instanceof Date) return a.getTime() - b.getTime();\n if (typeof a === 'boolean' && typeof b === 'boolean') return Number(a) - Number(b);\n return collator ? collator.compare(String(a), String(b)) : String(a).localeCompare(String(b));\n}\n\n/** Case- and accent-insensitive \"contains\"; arrays match any item. */\nexport function defaultFilter(value: unknown, filterValue: unknown): boolean {\n if (filterValue === undefined || filterValue === null || filterValue === '') return true;\n if (Array.isArray(filterValue)) return filterValue.length === 0 || filterValue.some((f) => defaultFilter(value, f));\n if (typeof filterValue !== 'string') return value === filterValue;\n return fold(String(value ?? '')).includes(fold(filterValue));\n}\n\n/**\n * The data logic of DataTable, with no markup: sorting (multi-column),\n * search, per-column filters, paging and row selection. Each piece of state\n * can be controlled or left to the hook. Use it alone for a fully custom\n * table, or let <DataTable> render it.\n */\nexport function useDataTable<Row>(options: UseDataTableOptions<Row>) {\n const { data, columns, manual = false } = options;\n const getRowKey =\n options.getRowKey ?? ((row: Row, i: number) => String((row as { id?: unknown })?.id ?? i));\n\n const [sort, setSort] = useControllable(options.sort, options.defaultSort ?? [], options.onSortChange);\n const [search, setSearchRaw] = useControllable(options.search, options.defaultSearch ?? '', options.onSearchChange);\n const [filters, setFiltersRaw] = useControllable(options.filters, options.defaultFilters ?? {}, options.onFiltersChange);\n const [page, setPage] = useControllable(options.page, options.defaultPage ?? 0, options.onPageChange);\n const [pageSize, setPageSizeRaw] = useControllable(options.pageSize, options.defaultPageSize ?? 10, options.onPageSizeChange);\n const [selectedKeys, setSelectedKeys] = useControllable(\n options.selectedKeys,\n new Set(options.defaultSelectedKeys ?? []),\n options.onSelectionChange,\n );\n\n const byKey = useMemo(() => new Map(columns.map((c) => [c.key, c])), [columns]);\n const valueOf = (row: Row, col: DataTableColumn<Row>) => (col.accessor ? col.accessor(row) : (row as Record<string, unknown>)[col.key]);\n\n const keyed = useMemo(() => data.map((row, i) => ({ row, key: getRowKey(row, i) })), [data, getRowKey]);\n\n const filtered = useMemo(() => {\n if (manual) return keyed;\n const searchCols = columns.filter((c) => c.searchable !== false);\n const activeFilters = Object.entries(filters).filter(([, v]) => !(v === undefined || v === '' || (Array.isArray(v) && !v.length)));\n return keyed.filter(({ row }) => {\n if (search) {\n const hit = searchCols.some((c) => {\n const v = valueOf(row, c);\n return (typeof v === 'string' || typeof v === 'number') && defaultFilter(v, search);\n });\n if (!hit) return false;\n }\n return activeFilters.every(([key, fv]) => {\n const col = byKey.get(key);\n if (!col) return true;\n const v = valueOf(row, col);\n return col.filter ? col.filter(v, fv, row) : defaultFilter(v, fv);\n });\n });\n // valueOf is stable for given columns\n }, [keyed, columns, byKey, search, filters, manual]);\n\n const sorted = useMemo(() => {\n if (manual || !sort.length) return filtered;\n const rules = sort.map((r) => ({ col: byKey.get(r.column), dir: r.direction === 'descending' ? -1 : 1 })).filter((r) => r.col);\n // Array.prototype.sort is stable, so equal rows keep their original order.\n return [...filtered].sort((a, b) => {\n for (const { col, dir } of rules) {\n const cmp = (col!.compare ?? defaultCompare)(valueOf(a.row, col!), valueOf(b.row, col!), a.row, b.row);\n if (cmp !== 0) return cmp * dir;\n }\n return 0;\n });\n }, [filtered, sort, byKey, manual]);\n\n const total = manual ? options.rowCount ?? data.length : sorted.length;\n const pageCount = pageSize > 0 ? Math.max(1, Math.ceil(total / pageSize)) : 1;\n const safePage = Math.min(page, pageCount - 1);\n const rows = manual || pageSize <= 0 ? sorted : sorted.slice(safePage * pageSize, safePage * pageSize + pageSize);\n\n /** Click a header: ascending → descending → off. With `multi` (Shift+click), add to the existing rules. */\n const toggleSort = (column: string, multi = false) => {\n const current = sort.find((r) => r.column === column);\n const next: SortRule | null = !current ? { column, direction: 'ascending' } : current.direction === 'ascending' ? { column, direction: 'descending' } : null;\n const others = multi ? sort.filter((r) => r.column !== column) : [];\n setSort(next ? (multi ? [...others, next] : [next]) : others);\n setPage(0);\n };\n\n const setSearch = (s: string) => {\n setSearchRaw(s);\n setPage(0);\n };\n const setFilter = (column: string, value: unknown) => {\n setFiltersRaw({ ...filters, [column]: value });\n setPage(0);\n };\n const setPageSize = (size: number) => {\n setPageSizeRaw(size);\n setPage(0);\n };\n\n const pageKeys = rows.map((r) => r.key);\n const allOnPageSelected = pageKeys.length > 0 && pageKeys.every((k) => selectedKeys.has(k));\n const someOnPageSelected = pageKeys.some((k) => selectedKeys.has(k));\n\n return {\n /** Rows to show now: filtered, sorted and paged, each with its key. */\n rows,\n /** Visible columns. */\n columns: columns.filter((c) => !c.hidden),\n valueOf,\n /** Rows after filtering (all pages). */\n filteredCount: manual ? total : filtered.length,\n totalCount: manual ? total : data.length,\n\n sort,\n setSort,\n toggleSort,\n sortOf: (column: string) => sort.find((r) => r.column === column)?.direction,\n sortIndex: (column: string) => (sort.length > 1 ? sort.findIndex((r) => r.column === column) : -1),\n\n search,\n setSearch,\n filters,\n setFilter,\n setFilters: setFiltersRaw,\n\n page: safePage,\n setPage,\n pageSize,\n setPageSize,\n pageCount,\n canPrev: safePage > 0,\n canNext: safePage < pageCount - 1,\n /** 1-based range shown, e.g. 11–20. */\n range: { from: total === 0 ? 0 : safePage * Math.max(pageSize, 0) + 1, to: pageSize > 0 ? Math.min(total, (safePage + 1) * pageSize) : total },\n\n selectedKeys,\n setSelectedKeys,\n isSelected: (key: string) => selectedKeys.has(key),\n toggleRow: (key: string) => {\n const next = new Set(selectedKeys);\n next.has(key) ? next.delete(key) : next.add(key);\n setSelectedKeys(next);\n },\n allOnPageSelected,\n someOnPageSelected,\n togglePage: () => {\n const next = new Set(selectedKeys);\n if (allOnPageSelected) pageKeys.forEach((k) => next.delete(k));\n else pageKeys.forEach((k) => next.add(k));\n setSelectedKeys(next);\n },\n clearSelection: () => setSelectedKeys(new Set()),\n /** The selected rows' data (across pages, from the current data). */\n selectedRows: keyed.filter((r) => selectedKeys.has(r.key)).map((r) => r.row),\n };\n}\n\nexport type DataTableModel<Row> = ReturnType<typeof useDataTable<Row>>;\n"
|
|
37
|
+
}
|
|
38
|
+
]
|
|
39
|
+
}
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
{
|
|
2
|
+
"$schema": "https://ui.shadcn.com/schema/registry-item.json",
|
|
3
|
+
"name": "date-picker",
|
|
4
|
+
"type": "registry:ui",
|
|
5
|
+
"title": "DatePicker",
|
|
6
|
+
"description": "DatePicker, DateRangePicker, Calendar and RangeCalendar: typed entry, presets, date rules, locales and calendar systems.",
|
|
7
|
+
"dependencies": [
|
|
8
|
+
"@internationalized/date@^3.12.4",
|
|
9
|
+
"react-aria@^3.53.1",
|
|
10
|
+
"react-stately@^3.51.0"
|
|
11
|
+
],
|
|
12
|
+
"registryDependencies": [
|
|
13
|
+
"@sparkwire/base",
|
|
14
|
+
"@sparkwire/spark",
|
|
15
|
+
"@sparkwire/styles",
|
|
16
|
+
"@sparkwire/utils"
|
|
17
|
+
],
|
|
18
|
+
"files": [
|
|
19
|
+
{
|
|
20
|
+
"path": "components/spark-ui/DatePicker/Calendar.tsx",
|
|
21
|
+
"type": "registry:ui",
|
|
22
|
+
"target": "components/spark-ui/DatePicker/Calendar.tsx",
|
|
23
|
+
"content": "import React, { useRef } from 'react';\nimport { useMessages } from '../internal/messages';\nimport { I18nProvider, useButton, useCalendar, useCalendarCell, useCalendarGrid, useDateFormatter, useLocale, useRangeCalendar } from 'react-aria';\nimport { useCalendarState, useRangeCalendarState, CalendarState, RangeCalendarState } from 'react-stately';\nimport { CalendarDate, DateValue, createCalendar, getLocalTimeZone, isSameDay, isToday, today } from '@internationalized/date';\nimport type { AriaCalendarProps, AriaRangeCalendarProps, AriaButtonProps } from 'react-aria';\nimport { Spark, SparkHandle } from '../Spark';\nimport { useDefaults, slot, ClassNames } from '../internal/defaults';\nimport { CalendarSystem, FirstDayOfWeek, fromDateValue, toDateValue, toFirstDay, withCalendar } from './dateAdapters';\nimport { DatePreset, DatePresetName, DateRange, RangePreset, RangePresetName, resolvePreset, toDatePreset, toRangePreset } from './presets';\n\nexport type CalendarSlot = 'root' | 'header' | 'title' | 'nav' | 'months' | 'grid' | 'weekday' | 'cell' | 'day' | 'footer' | 'preset';\n\n/** What `renderDay` gets for each day. */\nexport interface DayRenderInfo {\n /** The day number as the locale writes it (e.g. \"१५\" in Hindi digits). */\n formatted: string;\n selected: boolean;\n today: boolean;\n /** Can't be picked: outside min/max, disabled, or not in `enabledDates`. */\n unavailable: boolean;\n /** Belongs to the previous or next month. */\n outside: boolean;\n /** Range calendars: inside the selected (or hovered) range. */\n inRange: boolean;\n rangeStart: boolean;\n rangeEnd: boolean;\n}\n\n/** Props shared by Calendar and RangeCalendar. */\nexport interface CalendarBaseProps {\n /** Earliest selectable day. */\n min?: Date;\n /** Latest selectable day. */\n max?: Date;\n /** Days that can't be picked, e.g. holidays or booked days. */\n disabledDates?: Date[];\n /** If set, only these days can be picked, e.g. open appointment slots. */\n enabledDates?: Date[];\n /** Return `true` for days that can't be picked, e.g. weekends. Combines with the lists above. */\n isDateDisabled?: (date: Date) => boolean;\n /** First day of the week. Defaults to the locale's convention. */\n firstDayOfWeek?: FirstDayOfWeek;\n /** @deprecated Use `firstDayOfWeek`. 0 = Sunday, 1 = Monday. */\n weekStartsOn?: 0 | 1 | 2 | 3 | 4 | 5 | 6;\n /** BCP 47 locale for names, digits and direction. Defaults to SparkProvider's or the browser's. */\n locale?: string;\n /** Calendar system to display, e.g. `indian` (Saka), `islamic-umalqura`, `buddhist`. Values stay JS Dates. */\n calendar?: CalendarSystem;\n /** Months shown side by side. Default 1. */\n visibleMonths?: number;\n /** Custom content for a day cell, e.g. a price or an event dot under the number. */\n renderDay?: (date: Date, info: DayRenderInfo) => React.ReactNode;\n /** Show the Today button. Default `true` for Calendar, `false` for RangeCalendar. Ignored when `presets` is set. */\n showToday?: boolean;\n /** Label for the Today button, for other languages. */\n todayLabel?: string;\n /** Move keyboard focus into the grid when the calendar mounts. */\n autoFocus?: boolean;\n /** Called on Escape, so a custom popover can close. */\n onEscape?: () => void;\n /** Accessible name for the calendar. */\n 'aria-label'?: string;\n className?: string;\n /** Extra classes for each part. */\n classNames?: ClassNames<CalendarSlot>;\n}\n\nexport interface CalendarProps extends CalendarBaseProps {\n /** The selected day. */\n value?: Date | null;\n /** Initial selected day when uncontrolled. */\n defaultValue?: Date | null;\n /** Called with the picked day. */\n onChange?: (date: Date) => void;\n /**\n * Shortcut buttons under the calendar, replacing the Today button. Short\n * names (`'today'`, `'tomorrow'`, `'+7d'`, `'+1m'`, `'-1y'`) or your own\n * `{ label, value }` where value is a Date or a function returning one.\n */\n presets?: Array<DatePreset | DatePresetName>;\n}\n\nexport interface RangeCalendarProps extends CalendarBaseProps {\n /** The selected range. */\n value?: DateRange | null;\n /** Initial range when uncontrolled. */\n defaultValue?: DateRange | null;\n /** Called with the picked range once both ends are chosen. */\n onChange?: (range: DateRange) => void;\n /**\n * Shortcut buttons under the calendar. Short names (`'+7d'` next 7 days,\n * `'-30d'` last 30 days, `'thisWeek'`, `'thisMonth'`, `'thisYear'`,\n * `'today'`) or your own `{ label, value }`.\n */\n presets?: Array<RangePreset | RangePresetName>;\n /** Allow ranges that cross unavailable days. Default `false`. */\n allowsNonContiguousRanges?: boolean;\n}\n\n/* -------------------------------------------------------- availability */\n\nconst dayKey = (d: Date) => `${d.getFullYear()}-${d.getMonth()}-${d.getDate()}`;\n\n/** One check for min/max-free availability: allow-list, block-list and rule. */\nexport function makeUnavailable({ disabledDates, enabledDates, isDateDisabled }: CalendarBaseProps) {\n if (!disabledDates && !enabledDates && !isDateDisabled) return undefined;\n const blocked = new Set((disabledDates ?? []).map(dayKey));\n const allowed = enabledDates ? new Set(enabledDates.map(dayKey)) : null;\n return (value: DateValue) => {\n const d = fromDateValue(value)!;\n const key = dayKey(d);\n return (allowed !== null && !allowed.has(key)) || blocked.has(key) || Boolean(isDateDisabled?.(d));\n };\n}\n\n/* ------------------------------------------------------------ Calendar */\n\n/**\n * Calendar: a month grid. The selected day is a lit node, today is a ring,\n * and picking a day throws a spark. Shortcut buttons (`presets`) sit under\n * the grid. Behaviour comes from React Aria: arrows, Page Up/Down (Shift for\n * years), Home/End, right-to-left mirroring, localized names and digits,\n * other calendar systems, and announcements when the month changes.\n *\n * Style hooks: `.sp-calendar`, `__header`, `__title`, `__nav`, `__months`,\n * `__grid`, `__weekday`, `__day` with `[data-selected]`, `[data-today]`,\n * `[data-unavailable]`, `[data-outside]`, `[data-focus-visible]`,\n * `__footer`, `__preset[data-active]`. Add classes with `classNames`.\n */\nexport function Calendar(inProps: CalendarProps) {\n const props = useDefaults('Calendar', inProps);\n const { value, defaultValue, onChange, min, max, firstDayOfWeek, weekStartsOn, locale, calendar, presets, showToday = true, todayLabel, ...ui } = props;\n const { locale: inherited } = useLocale();\n const m = useMessages();\n const isDateUnavailable = makeUnavailable(props);\n const resolved = presets?.map((p) => toDatePreset(p, m)) ?? (showToday ? [{ label: todayLabel ?? m.today, value: () => fromDateValue(today(getLocalTimeZone()))! }] : []);\n return (\n <I18nProvider locale={withCalendar(locale ?? inherited, calendar)}>\n <CalendarCore\n {...ui}\n value={value === undefined ? undefined : toDateValue(value)}\n defaultValue={toDateValue(defaultValue)}\n onChange={(v) => v && onChange?.(fromDateValue(v)!)}\n minValue={toDateValue(min) ?? undefined}\n maxValue={toDateValue(max) ?? undefined}\n isDateUnavailable={isDateUnavailable}\n firstDayOfWeek={firstDayOfWeek ?? toFirstDay(weekStartsOn)}\n presets={resolved}\n />\n </I18nProvider>\n );\n}\n\ntype SharedUI = Pick<CalendarBaseProps, 'visibleMonths' | 'renderDay' | 'onEscape' | 'className' | 'classNames' | 'firstDayOfWeek'>;\n\nexport interface CalendarCoreProps extends AriaCalendarProps<DateValue>, SharedUI {\n presets?: DatePreset[];\n /** @deprecated Use presets. Kept for DatePicker's popover. */\n todayLabel?: string;\n}\n\n/** React Aria-level calendar, also used inside DatePicker's popover. */\nexport function CalendarCore({ presets, todayLabel, visibleMonths = 1, renderDay, onEscape, className, classNames, firstDayOfWeek, ...props }: CalendarCoreProps) {\n const { locale } = useLocale();\n const sparkRef = useRef<SparkHandle>(null);\n const pointer = useRef<{ clientX: number; clientY: number } | null>(null);\n const onChange = (v: DateValue) => {\n sparkRef.current?.burst((pointer.current ?? undefined) as unknown as React.MouseEvent<HTMLElement>);\n pointer.current = null;\n props.onChange?.(v as never);\n };\n const ariaProps = { ...props, onChange, visibleDuration: { months: visibleMonths } };\n const state = useCalendarState({ ...ariaProps, firstDayOfWeek, locale, createCalendar });\n const ref = useRef<HTMLDivElement>(null);\n const { calendarProps, prevButtonProps, nextButtonProps } = useCalendar(ariaProps, state);\n const list = presets ?? [{ label: todayLabel ?? 'Today', value: () => fromDateValue(today(getLocalTimeZone()))! }];\n\n const choose = (preset: DatePreset) => {\n const d = toDateValue(resolvePreset(preset.value))!;\n state.setFocusedDate(d);\n state.selectDate(d);\n };\n const usable = (preset: DatePreset) => {\n const d = toDateValue(resolvePreset(preset.value))!;\n return !state.isDisabled && !state.isInvalid(d) && !state.isCellUnavailable(d);\n };\n const active = (preset: DatePreset) => Boolean(state.value && isSameDay(state.value, toDateValue(resolvePreset(preset.value))!));\n\n return (\n <CalendarShell\n calendarProps={calendarProps}\n calRef={ref}\n state={state}\n prevButtonProps={prevButtonProps}\n nextButtonProps={nextButtonProps}\n visibleMonths={visibleMonths}\n firstDayOfWeek={firstDayOfWeek}\n renderDay={renderDay}\n onEscape={onEscape}\n className={className}\n classNames={classNames}\n onPointer={(p) => (pointer.current = p)}\n presets={list.map((p) => ({ label: p.label, onPress: () => choose(p), disabled: !usable(p), active: active(p) }))}\n spark={<Spark ref={sparkRef} count={8} spread={40} />}\n />\n );\n}\n\n/* ------------------------------------------------------- RangeCalendar */\n\n/**\n * RangeCalendar: pick a start and an end day; current flows between them.\n * Hovering after the first click previews the range. Shows two months with\n * `visibleMonths={2}`. Shortcut buttons (`presets`) sit under the grid.\n *\n * Style hooks: as Calendar, plus `__day[data-range-start][data-range-end][data-in-range]`.\n */\nexport function RangeCalendar(inProps: RangeCalendarProps) {\n const props = useDefaults('RangeCalendar', inProps);\n const { value, defaultValue, onChange, min, max, firstDayOfWeek, weekStartsOn, locale, calendar, presets, showToday = false, todayLabel, ...ui } = props;\n const { locale: inherited } = useLocale();\n const m = useMessages();\n const isDateUnavailable = makeUnavailable(props);\n const toRange = (r?: DateRange | null) => (r === undefined ? undefined : r === null ? null : { start: toDateValue(r.start)!, end: toDateValue(r.end)! });\n const resolved = presets?.map((p) => toRangePreset(p, m)) ?? (showToday ? [toRangePreset('today', m)] : []);\n if (resolved[0] && todayLabel && !presets) resolved[0] = { ...resolved[0], label: todayLabel };\n return (\n <I18nProvider locale={withCalendar(locale ?? inherited, calendar)}>\n <RangeCalendarCore\n {...ui}\n value={toRange(value)}\n defaultValue={toRange(defaultValue)}\n onChange={(r) => r && onChange?.({ start: fromDateValue(r.start)!, end: fromDateValue(r.end)! })}\n minValue={toDateValue(min) ?? undefined}\n maxValue={toDateValue(max) ?? undefined}\n isDateUnavailable={isDateUnavailable}\n firstDayOfWeek={firstDayOfWeek ?? toFirstDay(weekStartsOn)}\n presets={resolved}\n />\n </I18nProvider>\n );\n}\n\nexport interface RangeCalendarCoreProps extends AriaRangeCalendarProps<DateValue>, SharedUI {\n presets?: RangePreset[];\n}\n\n/** React Aria-level range calendar, also used inside DateRangePicker's popover. */\nexport function RangeCalendarCore({ presets = [], visibleMonths = 1, renderDay, onEscape, className, classNames, firstDayOfWeek, ...props }: RangeCalendarCoreProps) {\n const { locale } = useLocale();\n const sparkRef = useRef<SparkHandle>(null);\n const pointer = useRef<{ clientX: number; clientY: number } | null>(null);\n const onChange = (v: { start: DateValue; end: DateValue }) => {\n sparkRef.current?.burst((pointer.current ?? undefined) as unknown as React.MouseEvent<HTMLElement>);\n pointer.current = null;\n props.onChange?.(v as never);\n };\n const ariaProps = { ...props, onChange, visibleDuration: { months: visibleMonths } };\n const state = useRangeCalendarState({ ...ariaProps, firstDayOfWeek, locale, createCalendar });\n const ref = useRef<HTMLDivElement>(null);\n const { calendarProps, prevButtonProps, nextButtonProps } = useRangeCalendar(ariaProps, state, ref);\n\n const resolve = (p: RangePreset) => {\n const r = resolvePreset(p.value);\n return { start: toDateValue(r.start)!, end: toDateValue(r.end)! };\n };\n const choose = (p: RangePreset) => {\n const r = resolve(p);\n state.setFocusedDate(r.start);\n state.setValue(r);\n onChange(r);\n };\n const usable = (p: RangePreset) => {\n const r = resolve(p);\n if (state.isDisabled || state.isInvalid(r.start) || state.isInvalid(r.end)) return false;\n if (props.allowsNonContiguousRanges) return !state.isCellUnavailable(r.start) && !state.isCellUnavailable(r.end);\n for (let d = r.start; d.compare(r.end) <= 0; d = d.add({ days: 1 })) if (state.isCellUnavailable(d)) return false;\n return true;\n };\n const active = (p: RangePreset) => {\n if (!state.value) return false;\n const r = resolve(p);\n return isSameDay(state.value.start, r.start) && isSameDay(state.value.end, r.end);\n };\n\n return (\n <CalendarShell\n calendarProps={calendarProps}\n calRef={ref}\n state={state}\n prevButtonProps={prevButtonProps}\n nextButtonProps={nextButtonProps}\n visibleMonths={visibleMonths}\n firstDayOfWeek={firstDayOfWeek}\n renderDay={renderDay}\n onEscape={onEscape}\n className={className}\n classNames={classNames}\n onPointer={(p) => (pointer.current = p)}\n range\n presets={presets.map((p) => ({ label: p.label, onPress: () => choose(p), disabled: !usable(p), active: active(p) }))}\n spark={<Spark ref={sparkRef} count={10} spread={50} />}\n />\n );\n}\n\n/* --------------------------------------------------------------- shell */\n\ninterface ShellProps {\n calendarProps: React.HTMLAttributes<HTMLElement>;\n calRef: React.RefObject<HTMLDivElement>;\n state: CalendarState | RangeCalendarState;\n prevButtonProps: AriaButtonProps;\n nextButtonProps: AriaButtonProps;\n visibleMonths: number;\n firstDayOfWeek?: FirstDayOfWeek;\n renderDay?: CalendarBaseProps['renderDay'];\n onEscape?: () => void;\n className?: string;\n classNames?: ClassNames<CalendarSlot>;\n onPointer: (p: { clientX: number; clientY: number }) => void;\n presets: Array<{ label: string; onPress: () => void; disabled: boolean; active: boolean }>;\n range?: boolean;\n spark: React.ReactNode;\n}\n\nfunction CalendarShell({ calendarProps, calRef, state, prevButtonProps, nextButtonProps, visibleMonths, firstDayOfWeek, renderDay, onEscape, className, classNames, onPointer, presets, range, spark }: ShellProps) {\n const { direction } = useLocale();\n const monthFormat = useDateFormatter({ month: 'long', year: 'numeric', calendar: state.visibleRange.start.calendar.identifier, timeZone: state.timeZone });\n const months = Array.from({ length: visibleMonths }, (_, i) => state.visibleRange.start.add({ months: i }));\n return (\n <div\n {...calendarProps}\n ref={calRef}\n dir={direction}\n className={slot('sp-calendar', classNames, 'root', className)}\n data-range={range || undefined}\n data-months={visibleMonths > 1 ? visibleMonths : undefined}\n onPointerDown={(e) => onPointer({ clientX: e.clientX, clientY: e.clientY })}\n onKeyDown={(e) => {\n if (e.key === 'Escape' && onEscape) onEscape();\n }}\n >\n <div className={slot('sp-calendar__months', classNames, 'months')}>\n {months.map((month, i) => (\n <div key={month.toString()} className=\"sp-calendar__month\">\n <div className={slot('sp-calendar__header', classNames, 'header')}>\n {i === 0 ? <NavButton {...prevButtonProps} direction={direction} kind=\"prev\" className={classNames?.nav} /> : <span className=\"sp-calendar__nav-spacer\" />}\n <h2 className={slot('sp-calendar__title', classNames, 'title')}>{monthFormat.format(month.toDate(state.timeZone))}</h2>\n {i === months.length - 1 ? <NavButton {...nextButtonProps} direction={direction} kind=\"next\" className={classNames?.nav} /> : <span className=\"sp-calendar__nav-spacer\" />}\n </div>\n <CalendarGrid state={state} startDate={month} firstDayOfWeek={firstDayOfWeek} renderDay={renderDay} classNames={classNames} />\n </div>\n ))}\n </div>\n {presets.length > 0 && (\n <div className={slot('sp-calendar__footer', classNames, 'footer')}>\n {presets.map((p) => (\n <button\n key={p.label}\n type=\"button\"\n className={slot('sp-calendar__preset sp-calendar__today', classNames, 'preset')}\n data-active={p.active || undefined}\n aria-pressed={p.active}\n disabled={p.disabled}\n onClick={(e) => {\n onPointer({ clientX: e.clientX, clientY: e.clientY });\n p.onPress();\n }}\n >\n {p.label}\n </button>\n ))}\n </div>\n )}\n {spark}\n </div>\n );\n}\n\nfunction NavButton({ kind, direction, className, ...props }: AriaButtonProps & { kind: 'prev' | 'next'; direction: 'ltr' | 'rtl'; className?: string }) {\n const ref = useRef<HTMLButtonElement>(null);\n const { buttonProps } = useButton(props, ref);\n // Arrows point the way time moves, so they swap in right-to-left languages.\n const pointsLeft = (kind === 'prev') === (direction === 'ltr');\n return (\n <button {...buttonProps} ref={ref} className={slot('sp-calendar__nav', { nav: className }, 'nav')}>\n <svg width=\"16\" height=\"16\" viewBox=\"0 0 16 16\" aria-hidden=\"true\">\n <path d={pointsLeft ? 'M10 3L5 8l5 5' : 'M6 3l5 5-5 5'} fill=\"none\" stroke=\"currentColor\" strokeWidth=\"2\" strokeLinecap=\"round\" strokeLinejoin=\"round\" />\n </svg>\n </button>\n );\n}\n\nfunction CalendarGrid({\n state,\n startDate,\n firstDayOfWeek,\n renderDay,\n classNames,\n}: {\n state: CalendarState | RangeCalendarState;\n startDate: CalendarDate;\n firstDayOfWeek?: FirstDayOfWeek;\n renderDay?: CalendarBaseProps['renderDay'];\n classNames?: ClassNames<CalendarSlot>;\n}) {\n const { gridProps, headerProps, weekDays, weeksInMonth } = useCalendarGrid({ startDate, endDate: startDate.add({ months: 1 }).subtract({ days: 1 }), firstDayOfWeek, weekdayStyle: 'short' }, state);\n return (\n <table {...gridProps} className={slot('sp-calendar__grid', classNames, 'grid')}>\n <thead {...headerProps}>\n <tr>\n {weekDays.map((day, i) => (\n <th key={i} className={slot('sp-calendar__weekday', classNames, 'weekday')}>\n {day}\n </th>\n ))}\n </tr>\n </thead>\n <tbody>\n {Array.from({ length: weeksInMonth }, (_, week) => (\n <tr key={week}>\n {state.getDatesInWeek(week, startDate).map((date, i) =>\n date ? (\n <CalendarCell key={i} state={state} date={date} month={startDate} renderDay={renderDay} classNames={classNames} />\n ) : (\n <td key={i} className={slot('sp-calendar__cell', classNames, 'cell')} />\n ),\n )}\n </tr>\n ))}\n </tbody>\n </table>\n );\n}\n\nfunction CalendarCell({\n state,\n date,\n month,\n renderDay,\n classNames,\n}: {\n state: CalendarState | RangeCalendarState;\n date: CalendarDate;\n month: CalendarDate;\n renderDay?: CalendarBaseProps['renderDay'];\n classNames?: ClassNames<CalendarSlot>;\n}) {\n const ref = useRef<HTMLDivElement>(null);\n const { cellProps, buttonProps, isSelected, isDisabled, isUnavailable, isFocused, formattedDate } = useCalendarCell({ date }, state, ref);\n const outside = date.month !== month.month;\n const range = 'highlightedRange' in state ? state.highlightedRange : null;\n const rangeStart = Boolean(range && isSameDay(date, range.start));\n const rangeEnd = Boolean(range && isSameDay(date, range.end));\n const inRange = Boolean(range && date.compare(range.start) >= 0 && date.compare(range.end) <= 0);\n const todayFlag = isToday(date, getLocalTimeZone());\n const info: DayRenderInfo = { formatted: formattedDate, selected: isSelected, today: todayFlag, unavailable: isUnavailable || isDisabled, outside, inRange, rangeStart, rangeEnd };\n return (\n <td {...cellProps} className={slot('sp-calendar__cell', classNames, 'cell')} data-in-range={(inRange && !outside) || undefined} data-range-start={(rangeStart && !outside) || undefined} data-range-end={(rangeEnd && !outside) || undefined}>\n <div\n {...buttonProps}\n ref={ref}\n className={slot('sp-calendar__day', classNames, 'day')}\n data-selected={(isSelected && !outside) || undefined}\n data-today={todayFlag || undefined}\n data-outside={outside || undefined}\n data-disabled={isDisabled || undefined}\n data-unavailable={isUnavailable || undefined}\n data-focused={isFocused || undefined}\n data-range-start={(rangeStart && !outside) || undefined}\n data-range-end={(rangeEnd && !outside) || undefined}\n data-in-range={(inRange && !outside) || undefined}\n data-custom={renderDay ? true : undefined}\n >\n {renderDay ? renderDay(fromDateValue(date)!, info) : formattedDate}\n </div>\n </td>\n );\n}\n\nexport default Calendar;\n"
|
|
24
|
+
},
|
|
25
|
+
{
|
|
26
|
+
"path": "components/spark-ui/DatePicker/DatePicker.tsx",
|
|
27
|
+
"type": "registry:ui",
|
|
28
|
+
"target": "components/spark-ui/DatePicker/DatePicker.tsx",
|
|
29
|
+
"content": "import React, { useRef } from 'react';\nimport { useMessages } from '../internal/messages';\nimport { I18nProvider, useButton, useDateField, useDatePicker, useDateSegment, useDialog, useLocale } from 'react-aria';\nimport { useDateFieldState, useDatePickerState, DateFieldState, DateSegment } from 'react-stately';\nimport { DateValue, createCalendar } from '@internationalized/date';\nimport type { AriaDateFieldProps, AriaDialogProps } from 'react-aria';\nimport { CalendarCore, CalendarProps, CalendarSlot, makeUnavailable } from './Calendar';\nimport { toDatePreset } from './presets';\nimport { getLocalTimeZone, today } from '@internationalized/date';\nimport { Popover } from '../base/Popover';\nimport { useDefaults, slot, ClassNames } from '../internal/defaults';\nimport { CalendarSystem, FirstDayOfWeek, fromDateValue, toDateValue, toFirstDay, toISO, withCalendar } from './dateAdapters';\n\nexport interface DatePickerProps\n extends Pick<\n CalendarProps,\n | 'min' | 'max' | 'isDateDisabled' | 'disabledDates' | 'enabledDates' | 'firstDayOfWeek' | 'weekStartsOn' | 'locale' | 'calendar'\n | 'todayLabel' | 'showToday' | 'presets' | 'renderDay' | 'visibleMonths'\n > {\n /** Extra classes for the calendar's parts (header, day, preset…). */\n calendarClassNames?: ClassNames<CalendarSlot>;\n /** Visible label above the field. */\n label?: React.ReactNode;\n /** Accessible name when there is no visible label. */\n 'aria-label'?: string;\n /** Controlled value; `null` for no date. */\n value?: Date | null;\n /** Initial value when uncontrolled. */\n defaultValue?: Date | null;\n /** Called with the picked or typed date, or `null` when cleared. */\n onChange?: (date: Date | null) => void;\n /** Help text under the field (or the error message when `error` is set). */\n helperText?: React.ReactNode;\n /** Marks the field invalid. */\n error?: boolean;\n disabled?: boolean;\n required?: boolean;\n /** Show a clear button when a date is set. Default `true`. */\n clearable?: boolean;\n /** Name for a hidden input carrying the ISO date (YYYY-MM-DD), for plain forms. */\n name?: string;\n /** Default `medium`. */\n size?: 'small' | 'medium' | 'large';\n /** @deprecated The field now shows editable segments in the locale's order. */\n placeholder?: string;\n /** @deprecated The field now shows editable segments in the locale's order. */\n format?: Intl.DateTimeFormatOptions;\n className?: string;\n /** Extra classes for each part: root, label, control, field, trigger, popover, helper. */\n classNames?: ClassNames<'root' | 'label' | 'control' | 'field' | 'trigger' | 'popover' | 'helper'>;\n}\n\n/**\n * DatePicker: type a date or pick it from a calendar. The field lights up\n * while the calendar is open, and the picked day is a lit node with a spark.\n * Behaviour comes from React Aria: segment-by-segment typing in the\n * locale's order (DD/MM/YYYY in India, MM/DD/YYYY in the US), arrow keys to\n * adjust a segment, right-to-left layouts, other calendar systems, and a\n * dialog popover that restores focus.\n *\n * Style hooks: `.sp-date-picker[data-open][data-invalid][data-disabled]`,\n * `__label`, `__control`, `.sp-date-field`, `__segment[data-placeholder]`,\n * `__trigger`, `__clear`, `__helper`, `__popover`.\n */\nexport function DatePicker(inProps: DatePickerProps) {\n const props = useDefaults('DatePicker', inProps);\n const { locale: inherited } = useLocale();\n return (\n <I18nProvider locale={withCalendar(props.locale ?? inherited, props.calendar)}>\n <DatePickerInner {...props} />\n </I18nProvider>\n );\n}\n\nfunction DatePickerInner({\n label,\n 'aria-label': ariaLabel,\n value,\n defaultValue,\n onChange,\n min,\n max,\n isDateDisabled,\n disabledDates,\n enabledDates,\n showToday = true,\n presets,\n renderDay,\n visibleMonths,\n calendarClassNames,\n firstDayOfWeek,\n weekStartsOn,\n todayLabel,\n helperText,\n error,\n disabled,\n required,\n clearable = true,\n name,\n size = 'medium',\n className,\n classNames,\n}: DatePickerProps) {\n const { direction } = useLocale();\n const m = useMessages();\n const firstDay = firstDayOfWeek ?? toFirstDay(weekStartsOn);\n const ariaProps = {\n label,\n 'aria-label': ariaLabel,\n value: value === undefined ? undefined : toDateValue(value),\n defaultValue: toDateValue(defaultValue),\n onChange: (v: DateValue | null) => onChange?.(fromDateValue(v)),\n minValue: toDateValue(min) ?? undefined,\n maxValue: toDateValue(max) ?? undefined,\n isDateUnavailable: makeUnavailable({ isDateDisabled, disabledDates, enabledDates }),\n isDisabled: disabled,\n isRequired: required,\n isInvalid: error,\n validationBehavior: 'aria' as const,\n description: !error && helperText ? helperText : undefined,\n errorMessage: error && helperText ? helperText : undefined,\n granularity: 'day' as const,\n firstDayOfWeek: firstDay,\n shouldCloseOnSelect: true,\n };\n const state = useDatePickerState(ariaProps);\n const groupRef = useRef<HTMLDivElement>(null);\n const triggerRef = useRef<HTMLButtonElement>(null);\n const { groupProps, labelProps, fieldProps, buttonProps, dialogProps, calendarProps, descriptionProps, errorMessageProps } = useDatePicker(\n ariaProps,\n state,\n groupRef,\n );\n const { buttonProps: triggerButtonProps } = useButton(buttonProps, triggerRef);\n\n return (\n <div\n className={slot('sp-date-picker', classNames, 'root', className)}\n dir={direction}\n data-tone={error ? 'error' : 'brand'}\n data-size={size}\n data-open={state.isOpen || undefined}\n data-invalid={error || undefined}\n data-disabled={disabled || undefined}\n data-empty={!state.value || undefined}\n >\n {label && (\n <span {...labelProps} className={slot('sp-date-picker__label', classNames, 'label')}>\n {label}\n {required && (\n <span className=\"sp-field__required\" aria-hidden=\"true\">\n {' '}*\n </span>\n )}\n </span>\n )}\n <div {...groupProps} ref={groupRef} className={slot('sp-date-picker__control', classNames, 'control')}>\n <DateField {...fieldProps} className={slot('sp-date-field', classNames, 'field')} />\n {clearable && state.value && !disabled && (\n <button type=\"button\" aria-label={m.clearDate} className=\"sp-date-picker__clear\" onClick={() => state.setValue(null)}>\n <svg width=\"14\" height=\"14\" viewBox=\"0 0 16 16\" aria-hidden=\"true\">\n <path d=\"M3 3l10 10M13 3L3 13\" stroke=\"currentColor\" strokeWidth=\"2\" strokeLinecap=\"round\" />\n </svg>\n </button>\n )}\n <button {...triggerButtonProps} ref={triggerRef} className={slot('sp-date-picker__trigger', classNames, 'trigger')}>\n <svg className=\"sp-date-picker__icon\" width=\"18\" height=\"18\" viewBox=\"0 0 24 24\" aria-hidden=\"true\">\n <rect x=\"3\" y=\"5\" width=\"18\" height=\"16\" rx=\"2\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"2\" />\n <path d=\"M3 10h18M8 3v4M16 3v4\" stroke=\"currentColor\" strokeWidth=\"2\" strokeLinecap=\"round\" />\n </svg>\n </button>\n </div>\n {helperText && (\n <p {...(error ? errorMessageProps : descriptionProps)} className={slot('sp-date-picker__helper', classNames, 'helper')}>\n {helperText}\n </p>\n )}\n {name && <input type=\"hidden\" name={name} value={toISO(state.value)} />}\n {state.isOpen && (\n <Popover state={state} triggerRef={groupRef} offset={8} className={slot('sp-date-picker__popover', classNames, 'popover')}>\n <Dialog {...dialogProps}>\n <CalendarCore\n {...calendarProps}\n firstDayOfWeek={firstDay}\n presets={presets?.map((p) => toDatePreset(p, m)) ?? (showToday ? [{ label: todayLabel ?? m.today, value: () => today(getLocalTimeZone()).toDate(getLocalTimeZone()) }] : [])}\n renderDay={renderDay}\n visibleMonths={visibleMonths}\n classNames={calendarClassNames}\n />\n </Dialog>\n </Popover>\n )}\n </div>\n );\n}\n\nexport function DateField({ className, ...props }: AriaDateFieldProps<DateValue> & { className: string }) {\n const { locale } = useLocale();\n const state = useDateFieldState({ ...props, locale, createCalendar });\n const ref = useRef<HTMLDivElement>(null);\n const { fieldProps } = useDateField(props, state, ref);\n return (\n <div {...fieldProps} ref={ref} className={className}>\n {state.segments.map((segment, i) => (\n <Segment key={i} segment={segment} state={state} />\n ))}\n </div>\n );\n}\n\nexport function Segment({ segment, state }: { segment: DateSegment; state: DateFieldState }) {\n const ref = useRef<HTMLSpanElement>(null);\n const { segmentProps } = useDateSegment(segment, state, ref);\n return (\n <span\n {...segmentProps}\n ref={ref}\n className=\"sp-date-field__segment\"\n data-type={segment.type}\n data-placeholder={segment.isPlaceholder || undefined}\n data-literal={segment.type === 'literal' || undefined}\n >\n {segment.text}\n </span>\n );\n}\n\nexport function Dialog({ children, ...props }: AriaDialogProps & { children: React.ReactNode }) {\n const ref = useRef<HTMLDivElement>(null);\n const { dialogProps } = useDialog(props, ref);\n return (\n <div {...dialogProps} ref={ref} className=\"sp-date-picker__dialog\">\n {children}\n </div>\n );\n}\n\nexport type { FirstDayOfWeek, CalendarSystem };\nexport default DatePicker;\n"
|
|
30
|
+
},
|
|
31
|
+
{
|
|
32
|
+
"path": "components/spark-ui/DatePicker/DateRangePicker.tsx",
|
|
33
|
+
"type": "registry:ui",
|
|
34
|
+
"target": "components/spark-ui/DatePicker/DateRangePicker.tsx",
|
|
35
|
+
"content": "import React, { useRef } from 'react';\nimport { useMessages } from '../internal/messages';\nimport { I18nProvider, useButton, useDateRangePicker, useLocale } from 'react-aria';\nimport { useDateRangePickerState } from 'react-stately';\nimport type { DateValue } from '@internationalized/date';\nimport { Popover } from '../base/Popover';\nimport { useDefaults, slot, ClassNames } from '../internal/defaults';\nimport { CalendarSlot, RangeCalendarCore, RangeCalendarProps, makeUnavailable } from './Calendar';\nimport { DateField, Dialog } from './DatePicker';\nimport { fromDateValue, toDateValue, toFirstDay, toISO, withCalendar } from './dateAdapters';\nimport { DateRange, toRangePreset } from './presets';\n\nexport interface DateRangePickerProps\n extends Pick<\n RangeCalendarProps,\n | 'min' | 'max' | 'isDateDisabled' | 'disabledDates' | 'enabledDates' | 'firstDayOfWeek' | 'weekStartsOn' | 'locale' | 'calendar'\n | 'presets' | 'renderDay' | 'allowsNonContiguousRanges'\n > {\n /** Visible label above the field. */\n label?: React.ReactNode;\n /** Accessible name when there is no visible label. */\n 'aria-label'?: string;\n /** Controlled range; `null` for none. */\n value?: DateRange | null;\n /** Initial range when uncontrolled. */\n defaultValue?: DateRange | null;\n /** Called with the picked or typed range, or `null` when cleared. */\n onChange?: (range: DateRange | null) => void;\n /** Months shown in the popover. Default 2. */\n visibleMonths?: number;\n /** Help text under the field (or the error message when `error` is set). */\n helperText?: React.ReactNode;\n error?: boolean;\n disabled?: boolean;\n required?: boolean;\n /** Show a clear button when a range is set. Default `true`. */\n clearable?: boolean;\n /** One hidden input with an ISO interval, e.g. `2026-12-01/2026-12-07`. */\n name?: string;\n /** Hidden input with the start date (ISO), e.g. `checkIn`. */\n startName?: string;\n /** Hidden input with the end date (ISO), e.g. `checkOut`. */\n endName?: string;\n /** Default `medium`. */\n size?: 'small' | 'medium' | 'large';\n className?: string;\n /** Extra classes for each part: root, label, control, field, trigger, popover, helper. */\n classNames?: ClassNames<'root' | 'label' | 'control' | 'field' | 'trigger' | 'popover' | 'helper'>;\n /** Extra classes for the calendar's parts. */\n calendarClassNames?: ClassNames<CalendarSlot>;\n}\n\n/**\n * DateRangePicker: type or pick a start and an end date; current flows\n * between them in the calendar. Two months side by side, shortcut buttons\n * (`presets`) under the calendar, and full control over which days can be\n * picked. Behaviour comes from React Aria: typed entry in the locale's order,\n * hover preview of the range, right-to-left, calendar systems.\n *\n * Style hooks: `.sp-date-picker.sp-date-range-picker[data-open][data-invalid]`,\n * `__control`, `.sp-date-field`, `__dash`, `__trigger`, `__clear`, `__popover`.\n */\nexport function DateRangePicker(inProps: DateRangePickerProps) {\n const props = useDefaults('DateRangePicker', inProps);\n const { locale: inherited } = useLocale();\n return (\n <I18nProvider locale={withCalendar(props.locale ?? inherited, props.calendar)}>\n <Inner {...props} />\n </I18nProvider>\n );\n}\n\nfunction Inner({\n label,\n 'aria-label': ariaLabel,\n value,\n defaultValue,\n onChange,\n min,\n max,\n isDateDisabled,\n disabledDates,\n enabledDates,\n firstDayOfWeek,\n weekStartsOn,\n presets,\n renderDay,\n allowsNonContiguousRanges,\n visibleMonths = 2,\n helperText,\n error,\n disabled,\n required,\n clearable = true,\n name,\n startName,\n endName,\n size = 'medium',\n className,\n classNames,\n calendarClassNames,\n}: DateRangePickerProps) {\n const { direction } = useLocale();\n const m = useMessages();\n const firstDay = firstDayOfWeek ?? toFirstDay(weekStartsOn);\n const toRange = (r?: DateRange | null) => (r === undefined ? undefined : r === null ? null : { start: toDateValue(r.start)!, end: toDateValue(r.end)! });\n const ariaProps = {\n label,\n 'aria-label': ariaLabel,\n value: toRange(value),\n defaultValue: toRange(defaultValue),\n onChange: (r: { start: DateValue; end: DateValue } | null) => onChange?.(r ? { start: fromDateValue(r.start)!, end: fromDateValue(r.end)! } : null),\n minValue: toDateValue(min) ?? undefined,\n maxValue: toDateValue(max) ?? undefined,\n isDateUnavailable: makeUnavailable({ isDateDisabled, disabledDates, enabledDates }),\n allowsNonContiguousRanges,\n isDisabled: disabled,\n isRequired: required,\n isInvalid: error,\n validationBehavior: 'aria' as const,\n description: !error && helperText ? helperText : undefined,\n errorMessage: error && helperText ? helperText : undefined,\n granularity: 'day' as const,\n firstDayOfWeek: firstDay,\n shouldCloseOnSelect: true,\n };\n const state = useDateRangePickerState(ariaProps);\n const groupRef = useRef<HTMLDivElement>(null);\n const triggerRef = useRef<HTMLButtonElement>(null);\n const { groupProps, labelProps, startFieldProps, endFieldProps, buttonProps, dialogProps, calendarProps, descriptionProps, errorMessageProps } = useDateRangePicker(\n ariaProps,\n state,\n groupRef,\n );\n const { buttonProps: triggerButtonProps } = useButton(buttonProps, triggerRef);\n const hasValue = Boolean(state.value?.start || state.value?.end);\n\n return (\n <div\n className={slot('sp-date-picker sp-date-range-picker', classNames, 'root', className)}\n dir={direction}\n data-tone={error ? 'error' : 'brand'}\n data-size={size}\n data-open={state.isOpen || undefined}\n data-invalid={error || undefined}\n data-disabled={disabled || undefined}\n data-empty={!hasValue || undefined}\n >\n {label && (\n <span {...labelProps} className={slot('sp-date-picker__label', classNames, 'label')}>\n {label}\n {required && (\n <span className=\"sp-field__required\" aria-hidden=\"true\">\n {' '}*\n </span>\n )}\n </span>\n )}\n <div {...groupProps} ref={groupRef} className={slot('sp-date-picker__control', classNames, 'control')}>\n <DateField {...startFieldProps} className={slot('sp-date-field', classNames, 'field')} />\n <span className=\"sp-date-range-picker__dash\" aria-hidden=\"true\">\n →\n </span>\n <DateField {...endFieldProps} className={slot('sp-date-field', classNames, 'field')} />\n {clearable && hasValue && !disabled && (\n <button type=\"button\" aria-label={m.clearDates} className=\"sp-date-picker__clear\" onClick={() => state.setValue(null)}>\n <svg width=\"14\" height=\"14\" viewBox=\"0 0 16 16\" aria-hidden=\"true\">\n <path d=\"M3 3l10 10M13 3L3 13\" stroke=\"currentColor\" strokeWidth=\"2\" strokeLinecap=\"round\" />\n </svg>\n </button>\n )}\n <button {...triggerButtonProps} ref={triggerRef} className={slot('sp-date-picker__trigger', classNames, 'trigger')}>\n <svg className=\"sp-date-picker__icon\" width=\"18\" height=\"18\" viewBox=\"0 0 24 24\" aria-hidden=\"true\">\n <rect x=\"3\" y=\"5\" width=\"18\" height=\"16\" rx=\"2\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"2\" />\n <path d=\"M3 10h18M8 3v4M16 3v4\" stroke=\"currentColor\" strokeWidth=\"2\" strokeLinecap=\"round\" />\n </svg>\n </button>\n </div>\n {helperText && (\n <p {...(error ? errorMessageProps : descriptionProps)} className={slot('sp-date-picker__helper', classNames, 'helper')}>\n {helperText}\n </p>\n )}\n {name && <input type=\"hidden\" name={name} value={state.value?.start && state.value?.end ? `${toISO(state.value.start)}/${toISO(state.value.end)}` : ''} />}\n {startName && <input type=\"hidden\" name={startName} value={toISO(state.value?.start ?? null)} />}\n {endName && <input type=\"hidden\" name={endName} value={toISO(state.value?.end ?? null)} />}\n {state.isOpen && (\n <Popover state={state} triggerRef={groupRef} offset={8} className={slot('sp-date-picker__popover', classNames, 'popover')}>\n <Dialog {...dialogProps}>\n <RangeCalendarCore\n {...calendarProps}\n firstDayOfWeek={firstDay}\n visibleMonths={visibleMonths}\n renderDay={renderDay}\n presets={presets?.map((p) => toRangePreset(p, m)) ?? []}\n classNames={calendarClassNames}\n />\n </Dialog>\n </Popover>\n )}\n </div>\n );\n}\n\nexport default DateRangePicker;\n"
|
|
36
|
+
},
|
|
37
|
+
{
|
|
38
|
+
"path": "components/spark-ui/DatePicker/dateAdapters.ts",
|
|
39
|
+
"type": "registry:ui",
|
|
40
|
+
"target": "components/spark-ui/DatePicker/dateAdapters.ts",
|
|
41
|
+
"content": "import { CalendarDate, DateValue, GregorianCalendar, fromDate, getLocalTimeZone, toCalendar, toCalendarDate } from '@internationalized/date';\n\n/**\n * Spark UI's public date props use plain JS `Date`s; React Aria works with\n * `@internationalized/date` values. These helpers convert at the boundary.\n */\nexport const toDateValue = (d: Date | null | undefined): CalendarDate | null | undefined =>\n d === undefined ? undefined : d === null ? null : toCalendarDate(fromDate(d, getLocalTimeZone()));\n\nexport const fromDateValue = (v: DateValue | null | undefined): Date | null => (v ? v.toDate(getLocalTimeZone()) : null);\n\n/** ISO `YYYY-MM-DD` in the Gregorian calendar, whatever calendar is displayed. */\nexport const toISO = (v: DateValue | null | undefined) => (v ? toCalendar(toCalendarDate(v), new GregorianCalendar()).toString() : '');\n\n/** Calendar systems Intl understands, e.g. `indian`, `islamic-umalqura`, `buddhist`, `persian`, `japanese`. */\nexport type CalendarSystem =\n | 'gregory'\n | 'indian'\n | 'islamic-umalqura'\n | 'islamic-civil'\n | 'islamic-tbla'\n | 'buddhist'\n | 'persian'\n | 'japanese'\n | 'hebrew'\n | 'ethiopic'\n | 'coptic'\n | 'roc';\n\n/** Add a calendar system to a locale: ('hi-IN', 'indian') → 'hi-IN-u-ca-indian'. */\nexport const withCalendar = (locale: string, calendar?: CalendarSystem) =>\n calendar ? `${locale.replace(/-u-ca-[a-z-]+$/, '')}-u-ca-${calendar}` : locale;\n\nconst days = ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'] as const;\nexport type FirstDayOfWeek = (typeof days)[number];\n/** Old numeric `weekStartsOn` (0 = Sunday) to React Aria's `firstDayOfWeek`. */\nexport const toFirstDay = (n?: number): FirstDayOfWeek | undefined => (n === undefined ? undefined : days[((n % 7) + 7) % 7]);\n"
|
|
42
|
+
},
|
|
43
|
+
{
|
|
44
|
+
"path": "components/spark-ui/DatePicker/index.ts",
|
|
45
|
+
"type": "registry:ui",
|
|
46
|
+
"target": "components/spark-ui/DatePicker/index.ts",
|
|
47
|
+
"content": "export { DatePicker } from './DatePicker';\nexport type { DatePickerProps } from './DatePicker';\nexport { DateRangePicker } from './DateRangePicker';\nexport type { DateRangePickerProps } from './DateRangePicker';\nexport { Calendar, RangeCalendar } from './Calendar';\nexport type { CalendarProps, RangeCalendarProps, CalendarBaseProps, CalendarSlot, DayRenderInfo } from './Calendar';\nexport { datePresets, rangePresets, addTime } from './presets';\nexport type { DatePreset, RangePreset, DateRange, DatePresetName, RangePresetName, PresetUnit } from './presets';\nexport type { CalendarSystem, FirstDayOfWeek } from './dateAdapters';\n"
|
|
48
|
+
},
|
|
49
|
+
{
|
|
50
|
+
"path": "components/spark-ui/DatePicker/presets.ts",
|
|
51
|
+
"type": "registry:ui",
|
|
52
|
+
"target": "components/spark-ui/DatePicker/presets.ts",
|
|
53
|
+
"content": "import type { SparkMessages } from '../internal/messages';\n/**\n * Ready-made shortcuts for Calendar, DatePicker, RangeCalendar and\n * DateRangePicker. Each preset's value is a function, so \"Tomorrow\" is\n * worked out when it's clicked, not when the page loaded. Labels are\n * English by default; pass your own for other languages.\n *\n * presets={[datePresets.today(), datePresets.tomorrow(), datePresets.inDays(7, 'In a week')]}\n * presets={[rangePresets.next(7, 'days'), rangePresets.last(1, 'months'), rangePresets.thisYear()]}\n */\n\nexport interface DatePreset {\n label: string;\n /** A date, or a function returning one when the preset is used. */\n value: Date | (() => Date);\n}\n\nexport interface DateRange {\n start: Date;\n end: Date;\n}\n\nexport interface RangePreset {\n label: string;\n /** A range, or a function returning one when the preset is used. */\n value: DateRange | (() => DateRange);\n}\n\nexport type PresetUnit = 'days' | 'weeks' | 'months' | 'years';\n\nconst day = (d: Date) => new Date(d.getFullYear(), d.getMonth(), d.getDate());\nconst today = () => day(new Date());\n\n/** Add whole days, weeks, months or years (month ends clamp: 31 Jan + 1 month = 28/29 Feb). */\nexport function addTime(date: Date, amount: number, unit: PresetUnit): Date {\n const d = day(date);\n if (unit === 'days') return new Date(d.getFullYear(), d.getMonth(), d.getDate() + amount);\n if (unit === 'weeks') return new Date(d.getFullYear(), d.getMonth(), d.getDate() + amount * 7);\n const months = unit === 'months' ? amount : amount * 12;\n const target = new Date(d.getFullYear(), d.getMonth() + months, 1);\n const lastDay = new Date(target.getFullYear(), target.getMonth() + 1, 0).getDate();\n return new Date(target.getFullYear(), target.getMonth(), Math.min(d.getDate(), lastDay));\n}\n\nconst plural = (n: number, unit: PresetUnit) => `${n} ${n === 1 ? unit.slice(0, -1) : unit}`;\n\nexport const datePresets = {\n today: (label = 'Today'): DatePreset => ({ label, value: today }),\n tomorrow: (label = 'Tomorrow'): DatePreset => ({ label, value: () => addTime(today(), 1, 'days') }),\n yesterday: (label = 'Yesterday'): DatePreset => ({ label, value: () => addTime(today(), -1, 'days') }),\n /** `n` units from today; negative goes back. E.g. inDays(7), in(1, 'months', 'Next month'). */\n in: (n: number, unit: PresetUnit, label = n === 1 ? `In a ${unit.slice(0, -1)}` : n === -1 ? `A ${unit.slice(0, -1)} ago` : n >= 0 ? `In ${plural(n, unit)}` : `${plural(-n, unit)} ago`): DatePreset => ({\n label,\n value: () => addTime(today(), n, unit),\n }),\n inDays: (n: number, label?: string): DatePreset => datePresets.in(n, 'days', label),\n};\n\nexport const rangePresets = {\n /** Today plus the next n units, e.g. next(7, 'days') → today … today + 6. */\n next: (n: number, unit: PresetUnit, label = n === 1 ? `Next ${unit.slice(0, -1)}` : `Next ${plural(n, unit)}`): RangePreset => ({\n label,\n value: () => ({ start: today(), end: addTime(addTime(today(), n, unit), -1, 'days') }),\n }),\n /** The last n units up to today, e.g. last(30, 'days') → today − 29 … today. */\n last: (n: number, unit: PresetUnit, label = n === 1 ? `Last ${unit.slice(0, -1)}` : `Last ${plural(n, unit)}`): RangePreset => ({\n label,\n value: () => ({ start: addTime(addTime(today(), -n, unit), 1, 'days'), end: today() }),\n }),\n thisWeek: (label = 'This week', firstDay = 1): RangePreset => ({\n label,\n value: () => {\n const t = today();\n const start = addTime(t, -((t.getDay() - firstDay + 7) % 7), 'days');\n return { start, end: addTime(start, 6, 'days') };\n },\n }),\n thisMonth: (label = 'This month'): RangePreset => ({\n label,\n value: () => {\n const t = today();\n return { start: new Date(t.getFullYear(), t.getMonth(), 1), end: new Date(t.getFullYear(), t.getMonth() + 1, 0) };\n },\n }),\n thisYear: (label = 'This year'): RangePreset => ({\n label,\n value: () => {\n const y = today().getFullYear();\n return { start: new Date(y, 0, 1), end: new Date(y, 11, 31) };\n },\n }),\n};\n\nexport const resolvePreset = <T,>(value: T | (() => T)): T => (typeof value === 'function' ? (value as () => T)() : value);\n\n/**\n * Short names for presets, so most apps need no code:\n * 'today' | 'tomorrow' | 'yesterday' (dates)\n * 'thisWeek' | 'thisMonth' | 'thisYear' (ranges)\n * '+7d' '+2w' '+1m' '+1y' forward from today\n * '-30d' '-1m' back from today\n */\nexport type DatePresetName = 'today' | 'tomorrow' | 'yesterday' | `${'+' | '-'}${number}${'d' | 'w' | 'm' | 'y'}`;\nexport type RangePresetName = 'today' | 'thisWeek' | 'thisMonth' | 'thisYear' | `${'+' | '-'}${number}${'d' | 'w' | 'm' | 'y'}`;\n\nconst UNITS: Record<string, PresetUnit> = { d: 'days', w: 'weeks', m: 'months', y: 'years' };\nconst parseOffset = (s: string) => {\n const m = /^([+-])(\\d+)([dwmy])$/.exec(s);\n return m ? { n: Number(m[2]) * (m[1] === '-' ? -1 : 1), unit: UNITS[m[3]] } : null;\n};\n\n/** What preset labels need from the message table (see `useMessages`). */\nexport type PresetText = Pick<SparkMessages, 'today' | 'thisWeek' | 'thisMonth' | 'thisYear' | 'nextAmount' | 'lastAmount'> & { locale: string };\n\nconst SINGULAR: Record<PresetUnit, Intl.RelativeTimeFormatUnit> = { days: 'day', weeks: 'week', months: 'month', years: 'year' };\nconst cap = (s: string, locale: string) => s.charAt(0).toLocaleUpperCase(locale) + s.slice(1);\n/** \"Tomorrow\", \"In 7 days\", \"2 weeks ago\", in the locale's own words. */\nfunction relativeLabel(n: number, unit: PresetUnit, t: PresetText) {\n return cap(new Intl.RelativeTimeFormat(t.locale, { numeric: 'auto' }).format(n, SINGULAR[unit]), t.locale);\n}\n/** \"7 days\", \"1 month\", in the locale's own words. */\nfunction amount(n: number, unit: PresetUnit, t: PresetText) {\n return new Intl.NumberFormat(t.locale, { style: 'unit', unit: SINGULAR[unit], unitDisplay: 'long' }).format(n);\n}\n\n/** Turn a short name into a preset. With `text`, labels follow the locale; without it, English. */\nexport function toDatePreset(p: DatePreset | DatePresetName, text?: PresetText): DatePreset {\n if (typeof p !== 'string') return p;\n if (p === 'today') return datePresets.today(text?.today);\n if (p === 'tomorrow' || p === 'yesterday') return text ? datePresets.in(p === 'tomorrow' ? 1 : -1, 'days', relativeLabel(p === 'tomorrow' ? 1 : -1, 'days', text)) : datePresets[p]();\n const o = parseOffset(p);\n if (!o) throw new Error(`Unknown date preset \"${p}\"`);\n return datePresets.in(o.n, o.unit, text ? relativeLabel(o.n, o.unit, text) : undefined);\n}\n\nexport function toRangePreset(p: RangePreset | RangePresetName, text?: PresetText): RangePreset {\n if (typeof p !== 'string') return p;\n if (p === 'today') return { label: text?.today ?? 'Today', value: () => ({ start: today(), end: today() }) };\n if (p === 'thisWeek' || p === 'thisMonth' || p === 'thisYear') return rangePresets[p](text?.[p]);\n const o = parseOffset(p);\n if (!o) throw new Error(`Unknown range preset \"${p}\"`);\n return o.n >= 0\n ? rangePresets.next(o.n, o.unit, text ? text.nextAmount(amount(o.n, o.unit, text)) : undefined)\n : rangePresets.last(-o.n, o.unit, text ? text.lastAmount(amount(-o.n, o.unit, text)) : undefined);\n}\n"
|
|
54
|
+
}
|
|
55
|
+
]
|
|
56
|
+
}
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
{
|
|
2
|
+
"$schema": "https://ui.shadcn.com/schema/registry-item.json",
|
|
3
|
+
"name": "drawer",
|
|
4
|
+
"type": "registry:ui",
|
|
5
|
+
"title": "Drawer",
|
|
6
|
+
"description": "A panel that slides in from an edge, with focus trapping.",
|
|
7
|
+
"dependencies": [
|
|
8
|
+
"react-aria@^3.53.1"
|
|
9
|
+
],
|
|
10
|
+
"registryDependencies": [
|
|
11
|
+
"@sparkwire/base",
|
|
12
|
+
"@sparkwire/styles",
|
|
13
|
+
"@sparkwire/utils"
|
|
14
|
+
],
|
|
15
|
+
"files": [
|
|
16
|
+
{
|
|
17
|
+
"path": "components/spark-ui/Drawer/Drawer.tsx",
|
|
18
|
+
"type": "registry:ui",
|
|
19
|
+
"target": "components/spark-ui/Drawer/Drawer.tsx",
|
|
20
|
+
"content": "import React, { useId } from 'react';\nimport { useMessages } from '../internal/messages';\nimport { useDialog } from 'react-aria';\nimport { Overlay } from '../base/Overlay';\nimport { useDefaults, slot, ClassNames } from '../internal/defaults';\n\nexport interface DrawerProps {\n /** Whether the drawer is open. */\n open: boolean;\n /** Called on Escape, the close button or (when `dismissable`) a click on the backdrop. */\n onClose: () => void;\n /**\n * Edge it slides from. `start`/`end` follow reading direction (`end` is the\n * right in English, the left in Arabic). Default `end`.\n */\n placement?: 'start' | 'end' | 'top' | 'bottom';\n /** `small` (20rem), `medium` (28rem, default), `large` (40rem), `full`, or any CSS length. */\n size?: 'small' | 'medium' | 'large' | 'full' | (string & {});\n /** Heading; also the dialog's accessible name. */\n title?: React.ReactNode;\n /** Accessible name when there is no visible title. */\n 'aria-label'?: string;\n /** Text under the title. */\n description?: React.ReactNode;\n children?: React.ReactNode;\n /** Footer content, e.g. Cancel and Save buttons. */\n actions?: React.ReactNode;\n /** Close on a click on the backdrop. Default `true`. */\n dismissable?: boolean;\n /** Show the × button. Default `true`. */\n closeButton?: boolean;\n className?: string;\n /** Extra classes for each part: root, backdrop, panel, header, title, description, body, actions, close. */\n classNames?: ClassNames<'root' | 'backdrop' | 'panel' | 'header' | 'title' | 'description' | 'body' | 'actions' | 'close'>;\n}\n\nconst SIZES: Record<string, string> = { small: '20rem', medium: '28rem', large: '40rem', full: '100%' };\n\n/**\n * Drawer: a panel that slides in from an edge, for filters, details, forms\n * or navigation on small screens. Current runs along its inner edge as it\n * powers on. Built on the Overlay base: focus is trapped and returned,\n * the page behind is hidden from screen readers and doesn't scroll, and\n * Escape or a backdrop click closes it.\n *\n * Style hooks: `.sp-drawer[data-placement]`, `__backdrop`, `__panel`,\n * `__header`, `__title`, `__description`, `__body`, `__actions`, `__close`.\n * Variable: `--sp-drawer-size`.\n */\nexport function Drawer(inProps: DrawerProps) {\n const { open, onClose, dismissable = true, placement = 'end', classNames, ...rest } = useDefaults('Drawer', inProps);\n return (\n <Overlay\n open={open}\n onClose={onClose}\n dismissable={dismissable}\n className={slot('sp-drawer', classNames, 'root')}\n backdropClassName={slot('sp-drawer__backdrop', classNames, 'backdrop')}\n >\n {({ panelProps, panelRef }) => (\n <Panel {...rest} placement={placement} onClose={onClose} classNames={classNames} panelProps={panelProps} panelRef={panelRef} />\n )}\n </Overlay>\n );\n}\n\nfunction Panel({\n placement,\n size = 'medium',\n title,\n 'aria-label': ariaLabel,\n description,\n children,\n actions,\n closeButton = true,\n onClose,\n className,\n classNames,\n panelProps,\n panelRef,\n}: Omit<DrawerProps, 'open' | 'dismissable'> & { panelProps: React.HTMLAttributes<HTMLElement>; panelRef: React.RefObject<HTMLDivElement> }) {\n const m = useMessages();\n const { dialogProps, titleProps } = useDialog({ 'aria-label': title ? undefined : ariaLabel }, panelRef);\n const descId = useId();\n return (\n <div\n {...panelProps}\n {...dialogProps}\n ref={panelRef}\n aria-describedby={description ? descId : undefined}\n className={slot('sp-drawer__panel', classNames, 'panel', className)}\n data-placement={placement}\n style={{ '--sp-drawer-size': SIZES[size] ?? size } as React.CSSProperties}\n >\n <span aria-hidden=\"true\" className=\"sp-drawer__current sp-current\" />\n {(title || closeButton) && (\n <div className={slot('sp-drawer__header', classNames, 'header')}>\n <div className=\"sp-drawer__heading\">\n {title && (\n <h2 {...titleProps} className={slot('sp-drawer__title', classNames, 'title')}>\n {title}\n </h2>\n )}\n {description && (\n <p id={descId} className={slot('sp-drawer__description', classNames, 'description')}>\n {description}\n </p>\n )}\n </div>\n {closeButton && (\n <button type=\"button\" aria-label={m.close} onClick={onClose} className={slot('sp-drawer__close sp-modal__close', classNames, 'close')}>\n <svg width=\"16\" height=\"16\" viewBox=\"0 0 16 16\" aria-hidden=\"true\">\n <path d=\"M3 3l10 10M13 3L3 13\" stroke=\"currentColor\" strokeWidth=\"2\" strokeLinecap=\"round\" />\n </svg>\n </button>\n )}\n </div>\n )}\n <div className={slot('sp-drawer__body', classNames, 'body')}>{children}</div>\n {actions && <div className={slot('sp-drawer__actions', classNames, 'actions')}>{actions}</div>}\n </div>\n );\n}\n\nexport default Drawer;\n"
|
|
21
|
+
},
|
|
22
|
+
{
|
|
23
|
+
"path": "components/spark-ui/Drawer/index.ts",
|
|
24
|
+
"type": "registry:ui",
|
|
25
|
+
"target": "components/spark-ui/Drawer/index.ts",
|
|
26
|
+
"content": "export { Drawer } from './Drawer';\nexport type { DrawerProps } from './Drawer';\n"
|
|
27
|
+
}
|
|
28
|
+
]
|
|
29
|
+
}
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
{
|
|
2
|
+
"$schema": "https://ui.shadcn.com/schema/registry-item.json",
|
|
3
|
+
"name": "dropdown",
|
|
4
|
+
"type": "registry:ui",
|
|
5
|
+
"title": "Dropdown",
|
|
6
|
+
"description": "Pick one value from a list.",
|
|
7
|
+
"dependencies": [
|
|
8
|
+
"react-aria@^3.53.1",
|
|
9
|
+
"react-stately@^3.51.0"
|
|
10
|
+
],
|
|
11
|
+
"registryDependencies": [
|
|
12
|
+
"@sparkwire/base",
|
|
13
|
+
"@sparkwire/styles",
|
|
14
|
+
"@sparkwire/utils"
|
|
15
|
+
],
|
|
16
|
+
"files": [
|
|
17
|
+
{
|
|
18
|
+
"path": "components/spark-ui/Dropdown/Dropdown.tsx",
|
|
19
|
+
"type": "registry:ui",
|
|
20
|
+
"target": "components/spark-ui/Dropdown/Dropdown.tsx",
|
|
21
|
+
"content": "import React, { useRef } from 'react';\nimport { useMessages } from '../internal/messages';\nimport { HiddenSelect, useButton, useSelect } from 'react-aria';\nimport { useSelectState } from 'react-stately';\nimport { Popover } from '../base/Popover';\nimport { ListBox, ListItems, ListOption, findOption, renderListItems, isGroup } from '../base/ListBox';\nimport { useDefaults, slot, ClassNames } from '../internal/defaults';\n\n/** Person icon for the deprecated `forTeams` prop (inlined so the component needs no icon package). */\nconst User = () => (\n <svg width=\"16\" height=\"16\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"2\" strokeLinecap=\"round\" strokeLinejoin=\"round\" aria-hidden=\"true\">\n <path d=\"M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2\" />\n <circle cx=\"12\" cy=\"7\" r=\"4\" />\n </svg>\n);\n\nexport type DropdownOption<V extends string | number = string | number> = ListOption<V>;\nexport type DropdownOptionGroup<V extends string | number = string | number> = { label: string; options: DropdownOption<V>[] };\n\nexport interface DropdownProps<V extends string | number = string | number> {\n /** Visible label. Use `aria-label` instead if there is no visible label. */\n label?: string;\n /** Accessible name when there is no visible label. */\n 'aria-label'?: string;\n /** Options, or groups of options with a heading: `{ label: 'Asia', options: [...] }`. */\n options: Array<DropdownOption<V> | DropdownOptionGroup<V>>;\n /** Controlled value (`null` for none). */\n value?: V | null;\n /** Initial value when uncontrolled. */\n defaultValue?: V;\n /** Called with the chosen option's value; its type follows the options (numbers stay numbers). */\n onChange?: (value: V) => void;\n /** Called when the list opens or closes. */\n onOpenChange?: (open: boolean) => void;\n /** Shown when nothing is selected. Default \"Select an option\". */\n placeholder?: string;\n /** Help text under the field (shown in the error colour when `error` is `true`). */\n helperText?: React.ReactNode;\n /** An error message, or `true` to mark the field invalid and show `helperText` as the error. */\n error?: React.ReactNode | boolean;\n required?: boolean;\n disabled?: boolean;\n /** Form field name; a hidden native select submits the value. */\n name?: string;\n /** Height 36, 46 or 54px. Default `medium`. */\n size?: 'small' | 'medium' | 'large';\n /** Icon at the start of the field. */\n startIcon?: React.ReactNode;\n /** Shown when there are no options. Default \"No options\". */\n emptyState?: React.ReactNode;\n onFocus?: (event: React.FocusEvent) => void;\n onBlur?: (event: React.FocusEvent) => void;\n className?: string;\n /** Extra classes for each part: root, label, trigger, value, popover, option, helper. */\n classNames?: ClassNames<'root' | 'label' | 'trigger' | 'value' | 'popover' | 'option' | 'helper'>;\n\n /** @deprecated Use `startIcon`. */\n prependIcon?: React.ReactNode;\n /** @deprecated Put an `icon` on each option instead. */\n appendIcon?: React.ReactNode;\n /** @deprecated Use `classNames` or CSS on `.sp-dropdown__trigger`. */\n showBorder?: boolean;\n /** @deprecated Put `icon: <User />` on each option. */\n forTeams?: boolean;\n /** @deprecated Use `classNames.root` or `className`. */\n containerStyle?: React.CSSProperties;\n /** @deprecated Use `classNames.trigger`. */\n inputStyle?: React.CSSProperties;\n /** @deprecated Use `classNames.option`. */\n itemStyle?: React.CSSProperties;\n /** @deprecated Use `classNames.popover`. */\n listContainerStyle?: React.CSSProperties;\n}\n\n/**\n * Dropdown: pick one value from a list. The chosen option's node lights up.\n * Built on the Popover and ListBox base components with React Aria:\n * typeahead on the closed and open list, arrow keys, Home/End, Escape,\n * groups with headings, screen-reader announcements, and a hidden native\n * select so plain forms and autofill work. `Select` is the same component.\n *\n * Style hooks: `.sp-dropdown[data-open][data-invalid][data-disabled]`,\n * `__label`, `__trigger`, `__value[data-placeholder]`, `__chevron`,\n * `__helper`; the list uses `.sp-popover`, `.sp-listbox` and `.sp-list-item`.\n */\nexport function Dropdown<V extends string | number = string | number>(inProps: DropdownProps<V>) {\n const props = useDefaults('Dropdown', useDefaults('Select', inProps));\n const m = useMessages();\n const {\n label,\n 'aria-label': ariaLabel,\n options: rawOptions,\n value,\n defaultValue,\n onChange,\n onOpenChange,\n placeholder = m.selectPlaceholder,\n helperText,\n error,\n required,\n disabled,\n name,\n size = 'medium',\n startIcon,\n emptyState = m.noOptions,\n onFocus,\n onBlur,\n className,\n classNames,\n prependIcon,\n showBorder = true,\n forTeams,\n containerStyle,\n inputStyle,\n itemStyle,\n listContainerStyle,\n appendIcon,\n } = props;\n\n // Legacy `forTeams` puts a person icon on every option.\n const options: ListItems<ListOption<V>> = forTeams\n ? rawOptions.map((o) =>\n isGroup(o) ? { ...o, options: o.options.map((x) => ({ icon: <User />, ...x })) } : { icon: <User />, ...o },\n )\n : rawOptions;\n\n const invalid = Boolean(error);\n const message = typeof error === 'boolean' ? (error ? helperText : undefined) : error;\n const help = typeof error === 'boolean' || !error ? helperText : undefined;\n const disabledKeys = options.flatMap((o) => (isGroup(o) ? o.options : [o])).filter((o) => o.disabled).map((o) => String(o.value));\n\n const ariaProps = {\n label,\n 'aria-label': ariaLabel,\n children: renderListItems(options),\n selectedKey: value === undefined ? undefined : value === null ? null : String(value),\n defaultSelectedKey: defaultValue === undefined ? undefined : String(defaultValue),\n onSelectionChange: (key: React.Key | null) => {\n const option = findOption(options, key);\n if (option) onChange?.(option.value);\n },\n onOpenChange,\n disabledKeys,\n isDisabled: disabled,\n isRequired: required,\n isInvalid: invalid,\n description: help ? 'description' : undefined,\n errorMessage: invalid && message ? 'error' : undefined,\n name,\n onFocus,\n onBlur,\n };\n const state = useSelectState(ariaProps);\n const triggerRef = useRef<HTMLButtonElement>(null);\n const { labelProps, triggerProps, valueProps, menuProps, descriptionProps, errorMessageProps } = useSelect(ariaProps, state, triggerRef);\n const { buttonProps } = useButton(triggerProps, triggerRef);\n const selected = findOption(options, state.selectedKey);\n const icon = startIcon ?? prependIcon ?? selected?.icon;\n\n return (\n <div\n className={slot('sp-dropdown', classNames, 'root', className)}\n style={containerStyle}\n data-tone={invalid ? 'error' : 'brand'}\n data-size={size}\n data-open={state.isOpen || undefined}\n data-invalid={invalid || undefined}\n data-disabled={disabled || undefined}\n data-borderless={showBorder ? undefined : true}\n >\n {label && (\n <span {...labelProps} className={slot('sp-dropdown__label', classNames, 'label')}>\n {label}\n {required && (\n <span className=\"sp-field__required\" aria-hidden=\"true\">\n {' '}*\n </span>\n )}\n </span>\n )}\n <HiddenSelect state={state} triggerRef={triggerRef} label={label ?? ariaLabel} name={name} isDisabled={disabled} />\n <button {...buttonProps} ref={triggerRef} style={inputStyle} className={slot('sp-dropdown__trigger', classNames, 'trigger')}>\n {icon && (\n <span className=\"sp-dropdown__icon\" aria-hidden=\"true\">\n {icon}\n </span>\n )}\n <span {...valueProps} className={slot('sp-dropdown__value', classNames, 'value')} data-placeholder={selected ? undefined : true}>\n {selected ? selected.label : placeholder}\n </span>\n {appendIcon && (\n <span className=\"sp-dropdown__icon\" aria-hidden=\"true\">\n {appendIcon}\n </span>\n )}\n <svg className=\"sp-dropdown__chevron\" width=\"16\" height=\"16\" viewBox=\"0 0 16 16\" aria-hidden=\"true\">\n <path d=\"M4 6l4 4 4-4\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"2\" strokeLinecap=\"round\" strokeLinejoin=\"round\" />\n </svg>\n </button>\n {invalid && message ? (\n <p {...errorMessageProps} className={slot('sp-dropdown__helper', classNames, 'helper')}>\n {message}\n </p>\n ) : (\n help && (\n <p {...descriptionProps} className={slot('sp-dropdown__helper', classNames, 'helper')}>\n {help}\n </p>\n )\n )}\n {state.isOpen && (\n <Popover\n state={state}\n triggerRef={triggerRef}\n matchTriggerWidth\n className={slot('sp-dropdown__popover', classNames, 'popover')}\n style={listContainerStyle}\n >\n <ListBox\n {...menuProps}\n state={state}\n optionClassName={classNames?.option}\n emptyState={emptyState}\n optionStyle={itemStyle}\n />\n </Popover>\n )}\n </div>\n );\n}\n\nexport default Dropdown;\n"
|
|
22
|
+
},
|
|
23
|
+
{
|
|
24
|
+
"path": "components/spark-ui/Dropdown/index.ts",
|
|
25
|
+
"type": "registry:ui",
|
|
26
|
+
"target": "components/spark-ui/Dropdown/index.ts",
|
|
27
|
+
"content": "export { Dropdown } from './Dropdown';\nexport type { DropdownProps, DropdownOption, DropdownOptionGroup } from './Dropdown';\n"
|
|
28
|
+
}
|
|
29
|
+
]
|
|
30
|
+
}
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
{
|
|
2
|
+
"$schema": "https://ui.shadcn.com/schema/registry-item.json",
|
|
3
|
+
"name": "field",
|
|
4
|
+
"type": "registry:ui",
|
|
5
|
+
"title": "Field",
|
|
6
|
+
"description": "Label, help text and error wiring for any control.",
|
|
7
|
+
"dependencies": [],
|
|
8
|
+
"registryDependencies": [
|
|
9
|
+
"@sparkwire/styles",
|
|
10
|
+
"@sparkwire/utils"
|
|
11
|
+
],
|
|
12
|
+
"files": [
|
|
13
|
+
{
|
|
14
|
+
"path": "components/spark-ui/Field/Field.tsx",
|
|
15
|
+
"type": "registry:ui",
|
|
16
|
+
"target": "components/spark-ui/Field/Field.tsx",
|
|
17
|
+
"content": "import React, { cloneElement, createContext, isValidElement, useContext, useId } from 'react';\nimport { useDefaults, slot, ClassNames } from '../internal/defaults';\n\nexport interface FieldControlProps {\n id: string;\n 'aria-describedby'?: string;\n 'aria-invalid'?: true;\n 'aria-required'?: true;\n required?: boolean;\n disabled?: boolean;\n}\n\ninterface FieldContextValue {\n controlProps: FieldControlProps;\n labelId: string;\n}\n\nconst FieldContext = createContext<FieldContextValue | null>(null);\n\n/** Inside a <Field>, returns the props to spread on your own input. */\nexport const useFieldControl = () => useContext(FieldContext);\n\nexport interface FieldProps {\n /** Visible label, linked to the control. */\n label: React.ReactNode;\n /** Help text under the control. */\n description?: React.ReactNode;\n /** Error message. Replaces the description and marks the control invalid. */\n error?: React.ReactNode;\n /** Adds a required marker and `required` on the control. */\n required?: boolean;\n disabled?: boolean;\n /** Control id. Generated when omitted. */\n id?: string;\n /**\n * One element (ids and aria props are added to it), or a function that\n * receives the props to spread: `{(p) => <textarea {...p} />}`.\n */\n children: React.ReactElement | ((props: FieldControlProps) => React.ReactNode);\n className?: string;\n /** Extra classes for each part: root, label, description, error. */\n classNames?: ClassNames<'root' | 'label' | 'description' | 'error'>;\n}\n\n/**\n * Field: label, help text and error for any control, wired for screen readers.\n * Use it to give your own inputs (a textarea, a third-party editor) the same\n * labelling and error handling as Spark UI's built-in fields.\n *\n * Style hooks: `.sp-field[data-invalid][data-disabled]`, `__label`,\n * `__required`, `__description`, `__error`.\n */\nexport function Field(inProps: FieldProps) {\n const { label, description, error, required, disabled, id, children, className, classNames } = useDefaults('Field', inProps);\n const autoId = useId();\n const controlId = id ?? `${autoId}-control`;\n const labelId = `${controlId}-label`;\n const descId = `${controlId}-description`;\n const errorId = `${controlId}-error`;\n const invalid = Boolean(error);\n\n const controlProps: FieldControlProps = {\n id: controlId,\n 'aria-describedby': invalid ? errorId : description ? descId : undefined,\n 'aria-invalid': invalid || undefined,\n 'aria-required': required || undefined,\n required: required || undefined,\n disabled: disabled || undefined,\n };\n\n const control =\n typeof children === 'function'\n ? children(controlProps)\n : isValidElement(children)\n ? cloneElement(children as React.ReactElement<Record<string, unknown>>, controlProps as unknown as Record<string, unknown>)\n : children;\n\n return (\n <FieldContext.Provider value={{ controlProps, labelId }}>\n <div className={slot('sp-field', classNames, 'root', className)} data-invalid={invalid || undefined} data-disabled={disabled || undefined}>\n <label id={labelId} htmlFor={controlId} className={slot('sp-field__label', classNames, 'label')}>\n {label}\n {required && (\n <span className=\"sp-field__required\" aria-hidden=\"true\">\n {' '}*\n </span>\n )}\n </label>\n {control}\n {invalid ? (\n <p id={errorId} className={slot('sp-field__error', classNames, 'error')}>\n {error}\n </p>\n ) : (\n description && (\n <p id={descId} className={slot('sp-field__description', classNames, 'description')}>\n {description}\n </p>\n )\n )}\n </div>\n </FieldContext.Provider>\n );\n}\n\nexport default Field;\n"
|
|
18
|
+
},
|
|
19
|
+
{
|
|
20
|
+
"path": "components/spark-ui/Field/index.ts",
|
|
21
|
+
"type": "registry:ui",
|
|
22
|
+
"target": "components/spark-ui/Field/index.ts",
|
|
23
|
+
"content": "export { Field, useFieldControl } from './Field';\nexport type { FieldProps, FieldControlProps } from './Field';\n"
|
|
24
|
+
}
|
|
25
|
+
]
|
|
26
|
+
}
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
{
|
|
2
|
+
"$schema": "https://ui.shadcn.com/schema/registry-item.json",
|
|
3
|
+
"name": "file-upload",
|
|
4
|
+
"type": "registry:ui",
|
|
5
|
+
"title": "FileUpload",
|
|
6
|
+
"description": "Drop zone and file list with type/size/count checks, thumbnails, progress and errors.",
|
|
7
|
+
"dependencies": [
|
|
8
|
+
"react-aria@^3.53.1"
|
|
9
|
+
],
|
|
10
|
+
"registryDependencies": [
|
|
11
|
+
"@sparkwire/styles",
|
|
12
|
+
"@sparkwire/utils"
|
|
13
|
+
],
|
|
14
|
+
"files": [
|
|
15
|
+
{
|
|
16
|
+
"path": "components/spark-ui/FileUpload/FileUpload.tsx",
|
|
17
|
+
"type": "registry:ui",
|
|
18
|
+
"target": "components/spark-ui/FileUpload/FileUpload.tsx",
|
|
19
|
+
"content": "import React, { useId, useRef, useState } from 'react';\nimport { useMessages } from '../internal/messages';\nimport { useDrop } from 'react-aria';\nimport { useDefaults, slot, ClassNames } from '../internal/defaults';\n\nexport interface UploadFile {\n /** Stable id for keys and updates. */\n id: string;\n file: File;\n /** 0–100 while uploading. Leave undefined when you don't track progress. */\n progress?: number;\n status?: 'queued' | 'uploading' | 'done' | 'error';\n /** Shown under the name when status is `error`. */\n error?: string;\n}\n\nexport interface FileRejection {\n file: File;\n reason: 'type' | 'size' | 'count';\n message: string;\n}\n\nexport interface FileUploadProps {\n label?: React.ReactNode;\n /** Files in the list (controlled). Update `progress` / `status` as uploads run. */\n files?: UploadFile[];\n defaultFiles?: UploadFile[];\n /** Whole list after adding or removing. */\n onChange?: (files: UploadFile[]) => void;\n /** Just the newly accepted files: start uploads here. */\n onAdd?: (added: UploadFile[]) => void;\n onRemove?: (file: UploadFile) => void;\n /** Files that failed `accept`, `maxSize` or `maxFiles`. Default messages are shown under the zone. */\n onReject?: (rejected: FileRejection[]) => void;\n /** Like the input attribute: \"image/*,.pdf\". */\n accept?: string;\n multiple?: boolean;\n /** Bytes. */\n maxSize?: number;\n maxFiles?: number;\n /** Line under the main prompt. Default lists accepted types and size. */\n hint?: React.ReactNode;\n /** Main prompt. Default \"Drop files here or browse\". */\n prompt?: React.ReactNode;\n /** Image thumbnails in the list. Default `true`. */\n previews?: boolean;\n disabled?: boolean;\n /** Submit the files with a regular form. */\n name?: string;\n className?: string;\n classNames?: ClassNames<'root' | 'label' | 'zone' | 'list' | 'item' | 'errors'>;\n}\n\n/** 1536 → \"1.5 KB\". */\nexport function formatBytes(n: number) {\n if (n < 1024) return `${n} B`;\n const u = ['KB', 'MB', 'GB'];\n let i = -1;\n do {\n n /= 1024;\n i++;\n } while (n >= 1024 && i < u.length - 1);\n return `${n < 10 ? n.toFixed(1) : Math.round(n)} ${u[i]}`;\n}\n\nfunction matchesAccept(file: File, accept?: string) {\n if (!accept) return true;\n const name = file.name.toLowerCase();\n const type = (file.type || '').toLowerCase();\n return accept.split(',').some((raw) => {\n const a = raw.trim().toLowerCase();\n if (!a) return false;\n if (a.startsWith('.')) return name.endsWith(a);\n if (a.endsWith('/*')) return type.startsWith(a.slice(0, -1));\n return type === a;\n });\n}\n\nlet seq = 0;\nconst makeId = () => `f${Date.now().toString(36)}${(seq++).toString(36)}`;\n\nfunction Thumb({ file }: { file: File }) {\n const [url, setUrl] = useState<string | null>(null);\n React.useEffect(() => {\n if (!file.type.startsWith('image/') || typeof URL.createObjectURL !== 'function') return;\n const u = URL.createObjectURL(file);\n setUrl(u);\n return () => URL.revokeObjectURL(u);\n }, [file]);\n return url ? (\n <img className=\"sp-file-upload__thumb\" src={url} alt=\"\" onError={() => setUrl(null)} />\n ) : (\n <span className=\"sp-file-upload__thumb\" data-ext={file.name.split('.').pop()?.slice(0, 4).toUpperCase()} aria-hidden=\"true\" />\n );\n}\n\n/**\n * FileUpload: drop files on the zone or browse. Checks type, size and count\n * before accepting, lists files with thumbnails, progress and errors, and\n * lets people remove them. Uploading is yours: start it in `onAdd`, then\n * feed `progress` / `status` back through `files`.\n *\n * The zone is a real button (keyboard and screen readers), and drag-and-drop\n * uses React Aria's `useDrop`, which also accepts keyboard and screen-reader drops.\n *\n * Style hooks: `.sp-file-upload`, `__zone[data-drop-target][data-invalid]`, `__item[data-status]`, `__progress`.\n */\nexport function FileUpload(inProps: FileUploadProps) {\n const props = useDefaults('FileUpload', inProps) as FileUploadProps;\n const m = useMessages();\n const { label, accept, multiple = true, maxSize, maxFiles, previews = true, disabled, name, className, classNames } = props;\n const [inner, setInner] = useState<UploadFile[]>(props.defaultFiles ?? []);\n const files = props.files ?? inner;\n const [rejected, setRejected] = useState<FileRejection[]>([]);\n const inputRef = useRef<HTMLInputElement>(null);\n const zoneRef = useRef<HTMLButtonElement>(null);\n const id = useId();\n\n const setFiles = (next: UploadFile[]) => {\n if (props.files === undefined) setInner(next);\n props.onChange?.(next);\n };\n\n const add = (list: File[]) => {\n const ok: UploadFile[] = [];\n const bad: FileRejection[] = [];\n const room = maxFiles !== undefined ? Math.max(0, maxFiles - files.length) : Infinity;\n for (const f of multiple ? list : list.slice(0, 1)) {\n if (!matchesAccept(f, accept)) bad.push({ file: f, reason: 'type', message: m.fileTypeRejected(f.name) });\n else if (maxSize !== undefined && f.size > maxSize) bad.push({ file: f, reason: 'size', message: m.fileTooLarge(f.name, formatBytes(maxSize)) });\n else if (ok.length >= room) bad.push({ file: f, reason: 'count', message: m.tooManyFiles(f.name, m.num(maxFiles!)) });\n else ok.push({ id: makeId(), file: f, status: 'queued' });\n }\n setRejected(bad);\n if (bad.length) props.onReject?.(bad);\n if (ok.length) {\n setFiles(multiple ? [...files, ...ok] : ok);\n props.onAdd?.(ok);\n }\n };\n\n const { dropProps, isDropTarget } = useDrop({\n ref: zoneRef,\n isDisabled: disabled,\n async onDrop(e) {\n const got: File[] = [];\n for (const item of e.items) if (item.kind === 'file') got.push(await item.getFile());\n add(got);\n },\n });\n\n const hint =\n props.hint ??\n [accept && accept.split(',').map((a) => a.trim().replace(/^\\./, '').replace('/*', '').toUpperCase()).join(', '), maxSize !== undefined && m.upTo(formatBytes(maxSize)), maxFiles !== undefined && m.maxFiles(m.num(maxFiles))]\n .filter(Boolean)\n .join(' · ');\n\n return (\n <div className={slot('sp-file-upload', classNames, 'root', className)} data-disabled={disabled || undefined}>\n {label && (\n <span id={`${id}-label`} className={slot('sp-file-upload__label', classNames, 'label')}>\n {label}\n </span>\n )}\n <button\n {...dropProps}\n ref={zoneRef}\n type=\"button\"\n disabled={disabled}\n aria-labelledby={label ? `${id}-label ${id}-prompt` : `${id}-prompt`}\n aria-describedby={hint ? `${id}-hint` : undefined}\n className={slot('sp-file-upload__zone', classNames, 'zone')}\n data-drop-target={isDropTarget || undefined}\n data-invalid={rejected.length > 0 || undefined}\n onClick={() => inputRef.current?.click()}\n >\n <svg className=\"sp-file-upload__icon\" width=\"28\" height=\"28\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"1.75\" strokeLinecap=\"round\" strokeLinejoin=\"round\" aria-hidden=\"true\">\n <path d=\"M12 15V4M7.5 8.5 12 4l4.5 4.5\" />\n <path d=\"M4 14v4a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-4\" />\n </svg>\n <span id={`${id}-prompt`} className=\"sp-file-upload__prompt\">\n {props.prompt ?? (\n <>\n {m.dropFiles(multiple)} <u>{m.browse}</u>\n </>\n )}\n </span>\n {hint && (\n <span id={`${id}-hint`} className=\"sp-file-upload__hint\">\n {hint}\n </span>\n )}\n </button>\n <input\n ref={inputRef}\n type=\"file\"\n hidden\n name={name}\n accept={accept}\n multiple={multiple}\n disabled={disabled}\n onChange={(e) => {\n add(Array.from(e.target.files ?? []));\n if (!name) e.target.value = '';\n }}\n />\n {rejected.length > 0 && (\n <ul className={slot('sp-file-upload__errors', classNames, 'errors')} role=\"alert\">\n {rejected.map((r, i) => (\n <li key={i}>{r.message}</li>\n ))}\n </ul>\n )}\n {files.length > 0 && (\n <ul className={slot('sp-file-upload__list', classNames, 'list')} aria-label={m.files}>\n {files.map((f) => (\n <li key={f.id} className={slot('sp-file-upload__item', classNames, 'item')} data-status={f.status}>\n {previews && <Thumb file={f.file} />}\n <div className=\"sp-file-upload__meta\">\n <span className=\"sp-file-upload__name\" title={f.file.name}>\n {f.file.name}\n </span>\n <span className=\"sp-file-upload__detail\">\n {f.status === 'error' ? f.error ?? m.uploadFailed : f.status === 'uploading' && f.progress !== undefined ? `${Math.round(f.progress)}% · ${formatBytes(f.file.size)}` : formatBytes(f.file.size)}\n </span>\n {f.status === 'uploading' && (\n <span\n className=\"sp-file-upload__progress\"\n role=\"progressbar\"\n aria-label={m.uploading(f.file.name)}\n aria-valuemin={0}\n aria-valuemax={100}\n aria-valuenow={f.progress !== undefined ? Math.round(f.progress) : undefined}\n style={{ '--sp-progress': `${f.progress ?? 30}%` } as React.CSSProperties}\n data-indeterminate={f.progress === undefined || undefined}\n />\n )}\n </div>\n {f.status === 'done' && (\n <svg className=\"sp-file-upload__done\" width=\"18\" height=\"18\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"2.5\" strokeLinecap=\"round\" strokeLinejoin=\"round\" aria-label={m.uploaded} role=\"img\">\n <path d=\"M5 12.5l4.5 4.5L19 7.5\" />\n </svg>\n )}\n <button\n type=\"button\"\n className=\"sp-file-upload__remove\"\n aria-label={m.remove(f.file.name)}\n disabled={disabled}\n onClick={() => {\n setFiles(files.filter((x) => x.id !== f.id));\n props.onRemove?.(f);\n }}\n >\n <svg width=\"14\" height=\"14\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"2\" strokeLinecap=\"round\" aria-hidden=\"true\">\n <path d=\"M6 6l12 12M18 6 6 18\" />\n </svg>\n </button>\n </li>\n ))}\n </ul>\n )}\n </div>\n );\n}\n"
|
|
20
|
+
},
|
|
21
|
+
{
|
|
22
|
+
"path": "components/spark-ui/FileUpload/index.ts",
|
|
23
|
+
"type": "registry:ui",
|
|
24
|
+
"target": "components/spark-ui/FileUpload/index.ts",
|
|
25
|
+
"content": "export { FileUpload, formatBytes } from './FileUpload';\nexport type { FileUploadProps, UploadFile, FileRejection } from './FileUpload';\n"
|
|
26
|
+
}
|
|
27
|
+
]
|
|
28
|
+
}
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
{
|
|
2
|
+
"$schema": "https://ui.shadcn.com/schema/registry-item.json",
|
|
3
|
+
"name": "headless",
|
|
4
|
+
"type": "registry:ui",
|
|
5
|
+
"title": "Headless hooks",
|
|
6
|
+
"description": "useSwitch, useCheckbox, useSlider, useDatePicker and useSpark: behaviour without markup.",
|
|
7
|
+
"dependencies": [
|
|
8
|
+
"@internationalized/date@^3.12.4",
|
|
9
|
+
"react-aria@^3.53.1",
|
|
10
|
+
"react-stately@^3.51.0"
|
|
11
|
+
],
|
|
12
|
+
"registryDependencies": [
|
|
13
|
+
"@sparkwire/data-table",
|
|
14
|
+
"@sparkwire/date-picker",
|
|
15
|
+
"@sparkwire/spark",
|
|
16
|
+
"@sparkwire/styles",
|
|
17
|
+
"@sparkwire/utils"
|
|
18
|
+
],
|
|
19
|
+
"files": [
|
|
20
|
+
{
|
|
21
|
+
"path": "components/spark-ui/headless/index.tsx",
|
|
22
|
+
"type": "registry:ui",
|
|
23
|
+
"target": "components/spark-ui/headless/index.tsx",
|
|
24
|
+
"content": "/**\n * Spark UI headless hooks: the behaviour of Spark components without their\n * markup. Same prop names as the components, plain JS Dates, and `dataProps`\n * with the `data-*` attributes Spark's CSS uses, so your own markup can\n * still pick up the Live Wire look (or none at all).\n *\n * Built on React Aria; for anything not here, use react-aria directly.\n * Unstable until 1.0.\n */\nimport React, { useRef } from 'react';\nimport { haptic, powerCut, readEnergy, type HapticKind } from '../internal/energy';\nimport { useCheckbox as useAriaCheckbox, useDatePicker as useAriaDatePicker, useFocusRing, useNumberFormatter, useSlider as useAriaSlider, useSwitch as useAriaSwitch, mergeProps } from 'react-aria';\nimport { useDatePickerState, useSliderState, useToggleState } from 'react-stately';\nimport type { DateValue } from '@internationalized/date';\nimport { Spark, SparkHandle } from '../Spark';\nimport { FirstDayOfWeek, fromDateValue, toDateValue, toFirstDay, toISO } from '../DatePicker/dateAdapters';\n\nexport { useSliderThumb } from 'react-aria';\nexport { useDataTable } from '../DataTable/useDataTable';\nexport { toDateValue, fromDateValue, toISO, withCalendar } from '../DatePicker/dateAdapters';\n\ntype DataProps = Record<`data-${string}`, string | true | undefined>;\n\n/* --------------------------------------------------------------- switch */\n\nexport interface UseSwitchProps {\n checked?: boolean;\n defaultChecked?: boolean;\n onChange?: (checked: boolean) => void;\n disabled?: boolean;\n name?: string;\n value?: string;\n 'aria-label'?: string;\n 'aria-labelledby'?: string;\n}\n\n/**\n * Switch behaviour: a native checkbox input with `role=\"switch\"`, keyboard\n * and form support. Spread `inputProps` on a (visually hidden) input and\n * `dataProps` on your root to get `data-state=\"on\" | \"off\"`.\n */\nexport function useSwitch(props: UseSwitchProps, ref: React.RefObject<HTMLInputElement>) {\n const ariaProps = {\n isSelected: props.checked,\n defaultSelected: props.defaultChecked,\n onChange: props.onChange,\n isDisabled: props.disabled,\n name: props.name,\n value: props.value,\n 'aria-label': props['aria-label'],\n 'aria-labelledby': props['aria-labelledby'],\n };\n const state = useToggleState(ariaProps);\n const { inputProps, isSelected, isDisabled } = useAriaSwitch(ariaProps, state, ref);\n const { focusProps, isFocusVisible } = useFocusRing();\n const dataProps: DataProps = {\n 'data-state': isSelected ? 'on' : 'off',\n 'data-disabled': isDisabled || undefined,\n 'data-focus-visible': isFocusVisible || undefined,\n };\n return { inputProps: mergeProps(inputProps, focusProps), dataProps, checked: isSelected, disabled: isDisabled, focusVisible: isFocusVisible, setChecked: state.setSelected, toggle: state.toggle };\n}\n\n/* ------------------------------------------------------------- checkbox */\n\nexport interface UseCheckboxProps extends UseSwitchProps {\n /** Shown as a dash; announced as \"mixed\". */\n indeterminate?: boolean;\n required?: boolean;\n invalid?: boolean;\n}\n\n/** Checkbox behaviour. `dataProps` gives `data-state=\"checked\" | \"unchecked\" | \"indeterminate\"`. */\nexport function useCheckbox(props: UseCheckboxProps, ref: React.RefObject<HTMLInputElement>) {\n const ariaProps = {\n isSelected: props.checked,\n defaultSelected: props.defaultChecked,\n onChange: props.onChange,\n isDisabled: props.disabled,\n isIndeterminate: props.indeterminate,\n isRequired: props.required,\n isInvalid: props.invalid,\n validationBehavior: 'aria' as const,\n name: props.name,\n value: props.value,\n 'aria-label': props['aria-label'],\n 'aria-labelledby': props['aria-labelledby'],\n };\n const state = useToggleState(ariaProps);\n const { inputProps, isSelected, isDisabled, isInvalid } = useAriaCheckbox(ariaProps, state, ref);\n const { focusProps, isFocusVisible } = useFocusRing();\n const dataProps: DataProps = {\n 'data-state': props.indeterminate ? 'indeterminate' : isSelected ? 'checked' : 'unchecked',\n 'data-disabled': isDisabled || undefined,\n 'data-invalid': isInvalid || undefined,\n 'data-focus-visible': isFocusVisible || undefined,\n };\n return { inputProps: mergeProps(inputProps, focusProps), dataProps, checked: isSelected, disabled: isDisabled, focusVisible: isFocusVisible, setChecked: state.setSelected, toggle: state.toggle };\n}\n\n/* --------------------------------------------------------------- slider */\n\ntype SliderValue = number | [number, number];\n\nexport interface UseSliderProps<T extends SliderValue = SliderValue> {\n label?: React.ReactNode;\n 'aria-label'?: string;\n /** A number, or `[start, end]` for a range. */\n value?: T;\n defaultValue?: T;\n min?: number;\n max?: number;\n step?: number;\n onChange?: (value: T) => void;\n onChangeEnd?: (value: T) => void;\n disabled?: boolean;\n formatOptions?: Intl.NumberFormatOptions;\n}\n\n/**\n * Slider behaviour for one value or a two-knob range. Render one thumb per\n * entry in `values` with `useSliderThumb({ index, trackRef, inputRef }, state)`.\n * `cssVars` sets `--sp-start`, `--sp-end` and `--sp-pct` (0–100) for the fill.\n */\nexport function useSlider<T extends SliderValue = number>(props: UseSliderProps<T>, trackRef: React.RefObject<HTMLElement>) {\n const { min = 0, max = 100, step = 1 } = props;\n const isRange = Array.isArray(props.value ?? props.defaultValue);\n const toArray = (v?: SliderValue) => (v === undefined ? undefined : Array.isArray(v) ? v : [v]);\n const fromArray = (v: number | number[]) => {\n const a = Array.isArray(v) ? v : [v];\n return (isRange ? [a[0], a[1]] : a[0]) as T;\n };\n const numberFormatter = useNumberFormatter(props.formatOptions);\n const ariaProps = {\n label: props.label,\n 'aria-label': props['aria-label'],\n value: toArray(props.value),\n defaultValue: toArray(props.defaultValue) ?? (isRange ? [min, max] : [min]),\n minValue: min,\n maxValue: max,\n step,\n isDisabled: props.disabled,\n numberFormatter,\n onChange: (v: number | number[]) => props.onChange?.(fromArray(v)),\n onChangeEnd: (v: number | number[]) => props.onChangeEnd?.(fromArray(v)),\n };\n const state = useSliderState(ariaProps);\n const aria = useAriaSlider(ariaProps, state, trackRef);\n const pct = (i: number) => state.getThumbPercent(i) * 100;\n const start = isRange ? pct(0) : 0;\n const end = isRange ? pct(1) : pct(0);\n return {\n ...aria,\n state,\n isRange,\n value: fromArray(state.values),\n cssVars: { '--sp-start': start, '--sp-end': end, '--sp-pct': end } as React.CSSProperties,\n dataProps: { 'data-range': isRange || undefined, 'data-disabled': props.disabled || undefined } as DataProps,\n format: (n: number) => numberFormatter.format(n),\n };\n}\n\n/* ---------------------------------------------------------- date picker */\n\nexport interface UseDatePickerProps {\n label?: React.ReactNode;\n 'aria-label'?: string;\n value?: Date | null;\n defaultValue?: Date | null;\n onChange?: (date: Date | null) => void;\n min?: Date;\n max?: Date;\n isDateDisabled?: (date: Date) => boolean;\n firstDayOfWeek?: FirstDayOfWeek;\n /** @deprecated Use `firstDayOfWeek`. */\n weekStartsOn?: 0 | 1 | 2 | 3 | 4 | 5 | 6;\n disabled?: boolean;\n required?: boolean;\n invalid?: boolean;\n}\n\n/**\n * DatePicker behaviour with plain JS Dates. Returns React Aria's props for\n * the group, field, button, dialog and calendar (render them with\n * `useDateField`/`useCalendar` from react-aria), plus `value` as a Date and\n * `isoValue` for forms. Set the locale with `<SparkProvider locale>` or\n * React Aria's `I18nProvider`.\n */\nexport function useDatePicker(props: UseDatePickerProps, groupRef: React.RefObject<HTMLElement>) {\n const ariaProps = {\n label: props.label,\n 'aria-label': props['aria-label'],\n value: props.value === undefined ? undefined : toDateValue(props.value),\n defaultValue: toDateValue(props.defaultValue),\n onChange: (v: DateValue | null) => props.onChange?.(fromDateValue(v)),\n minValue: toDateValue(props.min) ?? undefined,\n maxValue: toDateValue(props.max) ?? undefined,\n isDateUnavailable: props.isDateDisabled ? (d: DateValue) => props.isDateDisabled!(fromDateValue(d)!) : undefined,\n firstDayOfWeek: props.firstDayOfWeek ?? toFirstDay(props.weekStartsOn),\n isDisabled: props.disabled,\n isRequired: props.required,\n isInvalid: props.invalid,\n validationBehavior: 'aria' as const,\n granularity: 'day' as const,\n };\n const state = useDatePickerState(ariaProps);\n const aria = useAriaDatePicker(ariaProps, state, groupRef);\n return {\n ...aria,\n state,\n value: fromDateValue(state.value),\n isoValue: toISO(state.value),\n dataProps: { 'data-open': state.isOpen || undefined, 'data-invalid': props.invalid || undefined, 'data-disabled': props.disabled || undefined, 'data-empty': !state.value || undefined } as DataProps,\n };\n}\n\n/* ---------------------------------------------------------------- spark */\n\n/**\n * The spark burst for any element. Render `sparks` inside a positioned\n * element and call `burst(event)` from a click handler (or with no event to\n * burst from the centre). Respects reduced motion.\n */\nexport interface UseSparkOptions {\n /** Particles per burst at default energy. Default 10. */\n count?: number;\n /** Burst radius in px at default energy. Default 70. */\n spread?: number;\n colors?: string[];\n}\n\n/**\n * Spark UI's motion on your own elements. Every effect follows the energy\n * dial (`SparkProvider energy` / `data-spark-energy`) and switches off for\n * reduced motion.\n *\n * ```tsx\n * const spark = useSpark();\n * <button className=\"sp-spark-host\" onClick={spark.burst}>{spark.sparks}Launch</button>\n * <div {...spark.current()} style={{ height: 2 }} /> // flowing current line\n * spark.powerCut(panelRef.current); // flicker an element\n * spark.haptic('toggle'); // short vibration (if enabled)\n * ```\n */\nexport function useSpark(options: UseSparkOptions = {}) {\n const ref = useRef<SparkHandle>(null);\n const sparks = <Spark ref={ref} count={options.count} spread={options.spread} colors={options.colors} />;\n return {\n /** Render inside a `position: relative` element; bursts appear here. */\n sparks,\n /** Fire a burst from the pointer (or the centre for keyboard clicks). */\n burst: (event?: React.MouseEvent<HTMLElement> | React.PointerEvent<HTMLElement>) => ref.current?.burst(event as React.MouseEvent<HTMLElement> | undefined),\n /** Props for a flowing current line. Give the element a height (or width when `down`). */\n current: (opts: { direction?: 'right' | 'down'; color?: string } = {}) => ({\n className: opts.direction === 'down' ? 'sp-current sp-current--down' : 'sp-current',\n style: (opts.color ? { '--sp-line': opts.color } : {}) as React.CSSProperties,\n }),\n /** Glow ring sized by the energy dial. */\n glow: () => ({ className: 'sp-glow' }),\n /** Flicker an element like a power cut. Resolves when it ends. */\n powerCut,\n /** Short vibration on supporting phones when haptics are on. */\n haptic: (kind?: HapticKind, el?: Element | null) => haptic(kind, el),\n /** Energy in effect at an element (or the page): off, calm, default or electric. */\n energy: (el?: Element | null) => readEnergy(el),\n };\n}\n\nexport { readEnergy, haptic, powerCut, ENERGY_SCALE } from '../internal/energy';\nexport type { Energy, HapticKind } from '../internal/energy';\n"
|
|
25
|
+
}
|
|
26
|
+
]
|
|
27
|
+
}
|