@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.
Files changed (48) hide show
  1. package/data/docs.json +4963 -0
  2. package/data/r/accordion.json +26 -0
  3. package/data/r/alert.json +26 -0
  4. package/data/r/avatar.json +26 -0
  5. package/data/r/base.json +55 -0
  6. package/data/r/button.json +33 -0
  7. package/data/r/card.json +26 -0
  8. package/data/r/charts.json +40 -0
  9. package/data/r/checkbox.json +27 -0
  10. package/data/r/combobox.json +30 -0
  11. package/data/r/command-palette.json +29 -0
  12. package/data/r/dashboard.json +34 -0
  13. package/data/r/data-table.json +39 -0
  14. package/data/r/date-picker.json +56 -0
  15. package/data/r/drawer.json +29 -0
  16. package/data/r/dropdown.json +30 -0
  17. package/data/r/field.json +26 -0
  18. package/data/r/file-upload.json +28 -0
  19. package/data/r/headless.json +27 -0
  20. package/data/r/indicators.json +26 -0
  21. package/data/r/input-base.json +21 -0
  22. package/data/r/menu.json +32 -0
  23. package/data/r/modal.json +29 -0
  24. package/data/r/navigation.json +26 -0
  25. package/data/r/number-field.json +30 -0
  26. package/data/r/provider.json +47 -0
  27. package/data/r/radio-group.json +26 -0
  28. package/data/r/select.json +21 -0
  29. package/data/r/settings.json +37 -0
  30. package/data/r/sidebar.json +30 -0
  31. package/data/r/sign-in.json +31 -0
  32. package/data/r/slider.json +29 -0
  33. package/data/r/spark.json +26 -0
  34. package/data/r/stepper.json +26 -0
  35. package/data/r/styles.json +17 -0
  36. package/data/r/switch.json +26 -0
  37. package/data/r/tabs.json +29 -0
  38. package/data/r/textarea.json +28 -0
  39. package/data/r/textfield.json +57 -0
  40. package/data/r/time-picker.json +32 -0
  41. package/data/r/toast.json +26 -0
  42. package/data/r/toggle-group.json +29 -0
  43. package/data/r/tooltip.json +29 -0
  44. package/data/r/utils.json +63 -0
  45. package/data/registry.json +1219 -0
  46. package/package.json +40 -4
  47. package/src/server.mjs +179 -0
  48. package/README.md +0 -3
@@ -0,0 +1,26 @@
1
+ {
2
+ "$schema": "https://ui.shadcn.com/schema/registry-item.json",
3
+ "name": "accordion",
4
+ "type": "registry:ui",
5
+ "title": "Accordion",
6
+ "description": "Sections that power on as they open.",
7
+ "dependencies": [],
8
+ "registryDependencies": [
9
+ "@sparkwire/styles",
10
+ "@sparkwire/utils"
11
+ ],
12
+ "files": [
13
+ {
14
+ "path": "components/spark-ui/Accordion/Accordion.tsx",
15
+ "type": "registry:ui",
16
+ "target": "components/spark-ui/Accordion/Accordion.tsx",
17
+ "content": "import React, { createContext, useContext, useId, useState } from 'react';\nimport { cx } from '../internal/cx';\nimport { useDefaults } from '../internal/defaults';\n\ninterface AccordionCtx {\n open: string[];\n toggle: (value: string) => void;\n}\nconst Ctx = createContext<AccordionCtx | null>(null);\n\nexport interface AccordionProps {\n /** Allow several sections open at once. Default `false`. */\n multiple?: boolean;\n /** Sections open at first, by `value`. */\n defaultOpen?: string[];\n children: React.ReactNode;\n className?: string;\n}\n\n/**\n * Accordion: a stack of circuits. Opening a section closes its circuit: the\n * wire beside it lights up and current runs down it.\n *\n * Style hooks: `.sp-accordion`, `__item[data-state=\"open\"|\"closed\"]`, `__wire`,\n * `__trigger`, `__chevron`, `__panel`.\n */\nexport function Accordion(inProps: AccordionProps) {\n const { multiple = false, defaultOpen = [], children, className } = useDefaults('Accordion', inProps);\n const [open, setOpen] = useState<string[]>(defaultOpen);\n const toggle = (v: string) =>\n setOpen((cur) => (cur.includes(v) ? cur.filter((x) => x !== v) : multiple ? [...cur, v] : [v]));\n\n return (\n <Ctx.Provider value={{ open, toggle }}>\n <div className={cx('sp-accordion', className)}>{children}</div>\n </Ctx.Provider>\n );\n}\n\nexport interface AccordionItemProps {\n /** Unique key for this section. */\n value: string;\n /** Text of the header button. */\n title: React.ReactNode;\n children: React.ReactNode;\n disabled?: boolean;\n}\n\nexport function AccordionItem({ value, title, children, disabled }: AccordionItemProps) {\n const ctx = useContext(Ctx);\n if (!ctx) throw new Error('AccordionItem must be used inside <Accordion>');\n const isOpen = ctx.open.includes(value);\n const id = useId();\n\n return (\n <div className=\"sp-accordion__item\" data-state={isOpen ? 'open' : 'closed'} data-disabled={disabled || undefined}>\n <span aria-hidden=\"true\" className=\"sp-accordion__wire sp-current sp-current--down\" />\n <h3 className=\"sp-accordion__heading\">\n <button\n type=\"button\"\n id={`${id}-trigger`}\n aria-expanded={isOpen}\n aria-controls={`${id}-panel`}\n disabled={disabled}\n onClick={() => ctx.toggle(value)}\n className=\"sp-accordion__trigger\"\n >\n {title}\n <svg className=\"sp-accordion__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 </h3>\n <div id={`${id}-panel`} role=\"region\" aria-labelledby={`${id}-trigger`} hidden={!isOpen} className=\"sp-accordion__panel\">\n {children}\n </div>\n </div>\n );\n}\n"
18
+ },
19
+ {
20
+ "path": "components/spark-ui/Accordion/index.ts",
21
+ "type": "registry:ui",
22
+ "target": "components/spark-ui/Accordion/index.ts",
23
+ "content": "export { Accordion, AccordionItem } from './Accordion';\nexport type { AccordionProps, AccordionItemProps } from './Accordion';\n"
24
+ }
25
+ ]
26
+ }
@@ -0,0 +1,26 @@
1
+ {
2
+ "$schema": "https://ui.shadcn.com/schema/registry-item.json",
3
+ "name": "alert",
4
+ "type": "registry:ui",
5
+ "title": "Alert",
6
+ "description": "Info, success, warning and error messages, with actions, dismiss and a banner variant.",
7
+ "dependencies": [],
8
+ "registryDependencies": [
9
+ "@sparkwire/styles",
10
+ "@sparkwire/utils"
11
+ ],
12
+ "files": [
13
+ {
14
+ "path": "components/spark-ui/Alert/Alert.tsx",
15
+ "type": "registry:ui",
16
+ "target": "components/spark-ui/Alert/Alert.tsx",
17
+ "content": "import React, { useState } from 'react';\nimport { useMessages } from '../internal/messages';\nimport { useDefaults, slot, ClassNames } from '../internal/defaults';\n\nexport type AlertTone = 'info' | 'success' | 'warning' | 'error';\n\nexport interface AlertProps extends Omit<React.HTMLAttributes<HTMLDivElement>, 'title'> {\n /** Default `info`. Each tone ships with its own icon, so meaning is never colour alone. */\n tone?: AlertTone;\n title?: React.ReactNode;\n children?: React.ReactNode;\n /** Replace the tone icon, or `false` to hide it. */\n icon?: React.ReactNode | false;\n /** Buttons or links on the right (or below on narrow screens). */\n action?: React.ReactNode;\n /** Show a close button. Called after it hides. */\n onDismiss?: () => void;\n /** `soft` (default), `outlined`, or `banner` (full-width, square, for the top of a page). */\n variant?: 'soft' | 'outlined' | 'banner';\n /**\n * `polite` announces it when it appears, `assertive` interrupts (errors).\n * Default: `assertive` for error, otherwise none (static content).\n */\n live?: 'polite' | 'assertive' | 'off';\n dismissLabel?: string;\n classNames?: ClassNames<'root' | 'icon' | 'title' | 'body' | 'action' | 'dismiss'>;\n}\n\nconst paths: Record<AlertTone, string> = {\n info: 'M12 8h.01M11 12h1v4h1',\n success: 'M8 12.5l2.5 2.5L16 9.5',\n warning: 'M12 8v5M12 16h.01',\n error: 'M9 9l6 6M15 9l-6 6',\n};\n\nfunction ToneIcon({ tone }: { tone: AlertTone }) {\n return (\n <svg width=\"20\" height=\"20\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"2\" strokeLinecap=\"round\" strokeLinejoin=\"round\" aria-hidden=\"true\">\n {tone === 'warning' ? <path d=\"M10.3 3.9 1.8 18a2 2 0 0 0 1.7 3h17a2 2 0 0 0 1.7-3L13.7 3.9a2 2 0 0 0-3.4 0z\" /> : <circle cx=\"12\" cy=\"12\" r=\"9\" />}\n <path d={paths[tone]} />\n </svg>\n );\n}\n\n/**\n * Alert: a message about the page or a task — info, success, warning or\n * error — with an icon, optional title, actions and a dismiss button. Use\n * `variant=\"banner\"` for a site-wide strip. Errors are announced at once;\n * others are static unless you set `live`.\n *\n * Style hooks: `.sp-alert[data-tone][data-variant]`, `__icon`, `__title`, `__body`, `__action`, `__dismiss`.\n */\nexport function Alert(inProps: AlertProps) {\n const m = useMessages();\n const { tone = 'info', title, children, icon, action, onDismiss, variant = 'soft', live, dismissLabel = m.dismiss, className, classNames, ...rest } = useDefaults(\n 'Alert',\n inProps,\n ) as AlertProps;\n const [open, setOpen] = useState(true);\n if (!open) return null;\n const mode = live ?? (tone === 'error' ? 'assertive' : 'off');\n const role = mode === 'assertive' ? 'alert' : mode === 'polite' ? 'status' : undefined;\n return (\n <div {...rest} role={role} className={slot('sp-alert', classNames, 'root', className)} data-tone={tone === 'info' ? 'brand' : tone} data-kind={tone} data-variant={variant}>\n {icon !== false && <span className={slot('sp-alert__icon', classNames, 'icon')}>{icon ?? <ToneIcon tone={tone} />}</span>}\n <div className=\"sp-alert__content\">\n {title && <div className={slot('sp-alert__title', classNames, 'title')}>{title}</div>}\n {children && <div className={slot('sp-alert__body', classNames, 'body')}>{children}</div>}\n </div>\n {action && <div className={slot('sp-alert__action', classNames, 'action')}>{action}</div>}\n {onDismiss && (\n <button\n type=\"button\"\n className={slot('sp-alert__dismiss', classNames, 'dismiss')}\n aria-label={dismissLabel}\n onClick={() => {\n setOpen(false);\n onDismiss();\n }}\n >\n <svg width=\"16\" height=\"16\" 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 )}\n </div>\n );\n}\n"
18
+ },
19
+ {
20
+ "path": "components/spark-ui/Alert/index.ts",
21
+ "type": "registry:ui",
22
+ "target": "components/spark-ui/Alert/index.ts",
23
+ "content": "export { Alert } from './Alert';\nexport type { AlertProps, AlertTone } from './Alert';\n"
24
+ }
25
+ ]
26
+ }
@@ -0,0 +1,26 @@
1
+ {
2
+ "$schema": "https://ui.shadcn.com/schema/registry-item.json",
3
+ "name": "avatar",
4
+ "type": "registry:ui",
5
+ "title": "Avatar",
6
+ "description": "Avatar and AvatarGroup.",
7
+ "dependencies": [],
8
+ "registryDependencies": [
9
+ "@sparkwire/styles",
10
+ "@sparkwire/utils"
11
+ ],
12
+ "files": [
13
+ {
14
+ "path": "components/spark-ui/Avatar/Avatar.tsx",
15
+ "type": "registry:ui",
16
+ "target": "components/spark-ui/Avatar/Avatar.tsx",
17
+ "content": "import React, { useState } from 'react';\nimport { useDefaults } from '../internal/defaults';\n\nexport type AvatarStatus = 'online' | 'busy' | 'away' | 'offline';\n\nexport interface AvatarProps {\n /** Full name: used for initials and the accessible label. */\n name: string;\n /** Photo URL. Falls back to initials if missing or broken. */\n src?: string;\n /** Default `medium` (40px). */\n size?: 'small' | 'medium' | 'large' | 'xlarge';\n /** Status LED. `online` pulses. */\n status?: AvatarStatus;\n}\n\nconst initials = (name: string) =>\n name\n .trim()\n .split(/\\s+/)\n .slice(0, 2)\n .map((p) => p[0]?.toUpperCase() ?? '')\n .join('');\n\n/**\n * Avatar: a photo or initials, with an optional status LED. An online user's\n * LED pulses with current.\n * Style hooks: `.sp-avatar[data-size][data-status]`, `__face`, `__led`.\n */\nexport function Avatar(inProps: AvatarProps) {\n const { name, src, size = 'medium', status } = useDefaults('Avatar', inProps);\n const [broken, setBroken] = useState(false);\n return (\n <span role=\"img\" aria-label={status ? `${name} (${status})` : name} className=\"sp-avatar\" data-size={size} data-status={status}>\n <span aria-hidden=\"true\" className=\"sp-avatar__face\">\n {src && !broken ? <img src={src} alt=\"\" onError={() => setBroken(true)} /> : initials(name)}\n </span>\n {status && <span aria-hidden=\"true\" className=\"sp-avatar__led\" />}\n </span>\n );\n}\n\nexport interface AvatarGroupProps {\n people: AvatarProps[];\n /** Show at most this many; the rest become a \"+N\" chip. Default 4. */\n max?: number;\n size?: AvatarProps['size'];\n}\n\n/** AvatarGroup: overlapping avatars wired together, with a \"+N\" overflow. */\nexport function AvatarGroup({ people, max = 4, size = 'medium' }: AvatarGroupProps) {\n const shown = people.slice(0, max);\n const extra = people.length - shown.length;\n return (\n <span role=\"group\" aria-label={`${people.length} people`} className=\"sp-avatar-group\" data-size={size}>\n {shown.map((p) => (\n <Avatar key={p.name} {...p} size={size} />\n ))}\n {extra > 0 && (\n <span aria-label={`${extra} more`} className=\"sp-avatar-group__more\">\n +{extra}\n </span>\n )}\n </span>\n );\n}\n"
18
+ },
19
+ {
20
+ "path": "components/spark-ui/Avatar/index.ts",
21
+ "type": "registry:ui",
22
+ "target": "components/spark-ui/Avatar/index.ts",
23
+ "content": "export { Avatar, AvatarGroup } from './Avatar';\nexport type { AvatarProps, AvatarGroupProps, AvatarStatus } from './Avatar';\n"
24
+ }
25
+ ]
26
+ }
@@ -0,0 +1,55 @@
1
+ {
2
+ "$schema": "https://ui.shadcn.com/schema/registry-item.json",
3
+ "name": "base",
4
+ "type": "registry:ui",
5
+ "title": "Base components",
6
+ "description": "ButtonBase, InputBase, Popover, ListBox and Overlay: the building blocks under the other components.",
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/spark",
14
+ "@sparkwire/styles",
15
+ "@sparkwire/utils"
16
+ ],
17
+ "files": [
18
+ {
19
+ "path": "components/spark-ui/base/ButtonBase.tsx",
20
+ "type": "registry:ui",
21
+ "target": "components/spark-ui/base/ButtonBase.tsx",
22
+ "content": "import React, { ElementType, forwardRef, useRef } from 'react';\nimport { Spark, SparkHandle } from '../Spark';\nimport { cx } from '../internal/cx';\n\nexport interface ButtonBaseProps extends React.ButtonHTMLAttributes<HTMLElement> {\n /** Render as another element or component, e.g. `\"a\"` or a router Link. */\n as?: ElementType;\n /** Dead circuit: no clicks, no sparks. Uses `disabled` on buttons, `aria-disabled` otherwise. */\n disabled?: boolean;\n /** Throw sparks from the press point on click. Default `true`. */\n spark?: boolean;\n /** Spark colours. Default: the theme's spark colours. */\n sparkColors?: string[];\n /** Link target when rendered as an anchor. */\n href?: string;\n [key: `data-${string}`]: unknown;\n}\n\n/**\n * ButtonBase: the pressable foundation under Button, IconButton and menu\n * triggers. Handles disabled state for any element, `type=\"button\"` by\n * default, and the spark burst. No visual style of its own beyond\n * `.sp-button-base`; build your own buttons on it.\n */\nexport const ButtonBase = forwardRef<HTMLElement, ButtonBaseProps>(function ButtonBase(\n { as: Component = 'button', disabled = false, spark = true, sparkColors, onClick, className, children, type, ...rest },\n ref,\n) {\n const sparkRef = useRef<SparkHandle>(null);\n const isButton = Component === 'button';\n return (\n <Component\n ref={ref}\n className={cx('sp-button-base', className)}\n data-disabled={disabled || undefined}\n disabled={isButton ? disabled : undefined}\n aria-disabled={!isButton && disabled ? true : undefined}\n type={isButton ? type ?? 'button' : type}\n onClick={(event: React.MouseEvent<HTMLElement>) => {\n if (disabled) {\n event.preventDefault();\n return;\n }\n if (spark) sparkRef.current?.burst(event);\n onClick?.(event as React.MouseEvent<HTMLButtonElement>);\n }}\n {...rest}\n >\n {children}\n {spark && <Spark ref={sparkRef} colors={sparkColors} />}\n </Component>\n );\n});\n\nexport default ButtonBase;\n"
23
+ },
24
+ {
25
+ "path": "components/spark-ui/base/InputBase.tsx",
26
+ "type": "registry:ui",
27
+ "target": "components/spark-ui/base/InputBase.tsx",
28
+ "content": "import React, { forwardRef, useRef } from 'react';\nimport { mergeRefs } from 'react-aria';\nimport { slot, ClassNames } from '../internal/defaults';\n\nexport interface InputBaseProps extends Omit<React.InputHTMLAttributes<HTMLInputElement>, 'size'> {\n /** `outlined` (default), `filled` or `standard` (underline only). */\n variant?: 'outlined' | 'filled' | 'standard';\n /** Marks the field invalid. */\n error?: boolean;\n disabled?: boolean;\n /** Height 36, 46 or 54px. Default `medium`. */\n size?: 'small' | 'medium' | 'large';\n /** Shown before the input, e.g. an icon or a currency sign. */\n startAdornment?: React.ReactNode;\n /** Shown after the input, e.g. a clear button or a chevron. */\n endAdornment?: React.ReactNode;\n /** Props for the outer shell (data attributes, handlers, style). */\n rootProps?: React.HTMLAttributes<HTMLDivElement> & { [key: `data-${string}`]: unknown };\n /** Ref for the outer shell, e.g. to anchor a popover. */\n rootRef?: React.Ref<HTMLDivElement>;\n /** Extra classes for each part: root, input, adornment. */\n classNames?: ClassNames<'root' | 'input' | 'adornment'>;\n}\n\n/**\n * InputBase: the field shell under Textfield and Combobox. One bordered box\n * holds the input and its adornments, lights up on focus, dashes when\n * disabled, and focuses the input when you click anywhere in it. Build your\n * own fields on it; label and help text are up to you (see Field).\n *\n * Style hooks: `.sp-input-base[data-variant][data-size][data-invalid][data-disabled]`,\n * `__input`, `__adornment`. Focus uses `:focus-within`.\n */\nexport const InputBase = forwardRef<HTMLInputElement, InputBaseProps>(function InputBase(\n { variant = 'outlined', error = false, disabled = false, size = 'medium', startAdornment, endAdornment, rootProps, rootRef, className, classNames, ...props },\n ref,\n) {\n const inputRef = useRef<HTMLInputElement>(null);\n return (\n <div\n {...rootProps}\n ref={rootRef}\n className={slot('sp-input-base', classNames, 'root', rootProps?.className)}\n data-variant={variant}\n data-size={size}\n data-tone={error ? 'error' : (rootProps?.['data-tone'] as string | undefined) ?? 'brand'}\n data-invalid={error || undefined}\n data-disabled={disabled || undefined}\n onMouseDown={(e) => {\n rootProps?.onMouseDown?.(e);\n // Clicking the shell's padding focuses the input, like a native field.\n if (e.target === e.currentTarget && !disabled) {\n e.preventDefault();\n inputRef.current?.focus();\n }\n }}\n >\n {startAdornment && <div className={slot('sp-input-base__adornment', classNames, 'adornment')}>{startAdornment}</div>}\n <input\n ref={mergeRefs(inputRef, ref) as React.Ref<HTMLInputElement>}\n className={slot('sp-input-base__input', classNames, 'input', className)}\n disabled={disabled}\n aria-invalid={error || undefined}\n {...props}\n />\n {endAdornment && <div className={slot('sp-input-base__adornment', classNames, 'adornment')}>{endAdornment}</div>}\n </div>\n );\n});\n\nexport default InputBase;\n"
29
+ },
30
+ {
31
+ "path": "components/spark-ui/base/ListBox.tsx",
32
+ "type": "registry:ui",
33
+ "target": "components/spark-ui/base/ListBox.tsx",
34
+ "content": "import React, { useRef } from 'react';\nimport { mergeRefs, useListBox, useListBoxSection, useOption } from 'react-aria';\nimport type { AriaListBoxOptions } from 'react-aria';\nimport { Item, Section, ListState } from 'react-stately';\nimport type { Node } from '@react-types/shared';\nimport { cx } from '../internal/cx';\n\n/** A section's items. Some React Aria collections lack getChildren(); every node has childNodes. */\nfunction sectionChildren<T>(collection: object, section: Node<T>): Iterable<Node<T>> {\n const c = collection as { getChildren?: (key: Node<T>[\"key\"]) => Iterable<Node<T>> };\n return typeof c.getChildren === \"function\" ? c.getChildren(section.key) : section.childNodes;\n}\n\n\n/* ------------------------------------------------------------ items */\n\nexport interface ListOption<V extends string | number = string | number> {\n /** Submitted and passed to `onChange`. Numbers come back as numbers. */\n value: V;\n /** Visible text; also used for typeahead and filtering. */\n label: string;\n /** Secondary line under the label. */\n description?: React.ReactNode;\n /** Icon before the label. */\n icon?: React.ReactNode;\n disabled?: boolean;\n}\n\nexport interface ListOptionGroup<O extends ListOption = ListOption> {\n /** Heading for the group. */\n label: string;\n options: O[];\n}\n\nexport type ListItems<O extends ListOption = ListOption> = Array<O | ListOptionGroup<O>>;\n\nexport const isGroup = <O extends ListOption>(o: O | ListOptionGroup<O>): o is ListOptionGroup<O> =>\n Array.isArray((o as ListOptionGroup<O>).options);\n\n/** Every option, groups flattened. */\nexport const flattenOptions = <O extends ListOption>(items: ListItems<O>): O[] =>\n items.flatMap((o) => (isGroup(o) ? o.options : [o]));\n\n/** Option values are React Aria keys; keep numbers as numbers when reading them back. */\nexport const findOption = <O extends ListOption>(items: ListItems<O>, key: React.Key | null | undefined) =>\n key == null ? undefined : flattenOptions(items).find((o) => String(o.value) === String(key));\n\n/** Turn plain option objects into a React Aria collection (Items and Sections). */\nexport function renderListItems<O extends ListOption>(items: ListItems<O>) {\n return items.map((o, i) =>\n isGroup(o) ? (\n <Section key={`group-${i}-${o.label}`} title={o.label}>\n {o.options.map(renderOne)}\n </Section>\n ) : (\n renderOne(o)\n ),\n );\n}\n\nfunction renderOne<O extends ListOption>(o: O) {\n return (\n <Item key={String(o.value)} textValue={o.label}>\n <ListItemContent icon={o.icon} label={o.label} description={o.description} />\n </Item>\n );\n}\n\nexport interface ListItemContentProps {\n icon?: React.ReactNode;\n label: React.ReactNode;\n description?: React.ReactNode;\n /** Shown at the end, e.g. a keyboard shortcut. */\n end?: React.ReactNode;\n}\n\n/** The inside of a list row: icon, label, description and an end slot. Shared by options and menu items. */\nexport function ListItemContent({ icon, label, description, end }: ListItemContentProps) {\n return (\n <>\n {icon && (\n <span className=\"sp-list-item__icon\" aria-hidden=\"true\">\n {icon}\n </span>\n )}\n <span className=\"sp-list-item__text\">\n <span className=\"sp-list-item__label\">{label}</span>\n {description && <span className=\"sp-list-item__description\">{description}</span>}\n </span>\n {end && <span className=\"sp-list-item__end\">{end}</span>}\n </>\n );\n}\n\n/* ---------------------------------------------------------- listbox */\n\nexport interface ListBoxProps<T> extends AriaListBoxOptions<T> {\n /** List state from `useListState`, `useSelectState` or `useComboBoxState`. */\n state: ListState<T>;\n listBoxRef?: React.Ref<HTMLUListElement>;\n className?: string;\n /** Extra class for every option row. */\n optionClassName?: string;\n /** Inline style for every option row. */\n optionStyle?: React.CSSProperties;\n /** Shown when there are no options. */\n emptyState?: React.ReactNode;\n}\n\n/**\n * ListBox: a list of options to choose from, under Dropdown and Combobox.\n * Each option is a node on a wire: the selected one lights up. Supports\n * groups with headings, icons, descriptions, disabled options and\n * screen-reader announcements.\n *\n * Style hooks: `.sp-listbox`, `.sp-list-section`, `__heading`,\n * `.sp-list-item[data-focused][data-selected][data-disabled]`, `__icon`,\n * `__label`, `__description`, `__check`, `.sp-listbox__empty`.\n */\nexport function ListBox<T>({ state, listBoxRef, className, optionClassName, optionStyle, emptyState, ...props }: ListBoxProps<T>) {\n const ref = useRef<HTMLUListElement>(null);\n const { listBoxProps } = useListBox(props, state, ref);\n const nodes = Array.from(state.collection);\n return (\n <ul {...listBoxProps} ref={mergeRefs(ref, listBoxRef ?? null) as React.Ref<HTMLUListElement>} className={cx('sp-listbox', className)}>\n {nodes.length === 0 && emptyState ? (\n <li className=\"sp-listbox__empty\" role=\"presentation\">\n {emptyState}\n </li>\n ) : (\n nodes.map((node) =>\n node.type === 'section' ? (\n <ListBoxSection key={node.key} section={node} state={state} optionClassName={optionClassName} optionStyle={optionStyle} />\n ) : (\n <ListBoxOption key={node.key} item={node} state={state} className={optionClassName} style={optionStyle} />\n ),\n )\n )}\n </ul>\n );\n}\n\nfunction ListBoxSection<T>({ section, state, optionClassName, optionStyle }: { section: Node<T>; state: ListState<T>; optionClassName?: string; optionStyle?: React.CSSProperties }) {\n const { itemProps, headingProps, groupProps } = useListBoxSection({ heading: section.rendered, 'aria-label': section['aria-label'] });\n return (\n <li {...itemProps} className=\"sp-list-section\">\n {section.rendered && (\n <span {...headingProps} className=\"sp-list-section__heading\">\n {section.rendered}\n </span>\n )}\n <ul {...groupProps} className=\"sp-list-section__group\">\n {Array.from(sectionChildren(state.collection, section)).map((item) => (\n <ListBoxOption key={item.key} item={item} state={state} className={optionClassName} style={optionStyle} />\n ))}\n </ul>\n </li>\n );\n}\n\nfunction ListBoxOption<T>({ item, state, className, style }: { item: Node<T>; state: ListState<T>; className?: string; style?: React.CSSProperties }) {\n const ref = useRef<HTMLLIElement>(null);\n const { optionProps, isSelected, isFocused, isDisabled } = useOption({ key: item.key }, state, ref);\n return (\n <li\n {...optionProps}\n ref={ref}\n className={cx('sp-list-item', className)}\n style={style}\n data-selected={isSelected || undefined}\n data-focused={isFocused || undefined}\n data-disabled={isDisabled || undefined}\n >\n {item.rendered}\n {isSelected && (\n <svg className=\"sp-list-item__check\" width=\"16\" height=\"16\" viewBox=\"0 0 16 16\" aria-hidden=\"true\">\n <path d=\"M3 8.5l3 3 7-7\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"2\" strokeLinecap=\"round\" strokeLinejoin=\"round\" />\n </svg>\n )}\n </li>\n );\n}\n\nexport default ListBox;\n"
35
+ },
36
+ {
37
+ "path": "components/spark-ui/base/Overlay.tsx",
38
+ "type": "registry:ui",
39
+ "target": "components/spark-ui/base/Overlay.tsx",
40
+ "content": "import React, { useRef } from 'react';\nimport { createPortal } from 'react-dom';\nimport { FocusScope, useModalOverlay } from 'react-aria';\nimport { useOverlayTriggerState } from 'react-stately';\nimport { usePortalTheme } from '../internal/usePortalTheme';\nimport { cx } from '../internal/cx';\n\nexport interface OverlayProps {\n /** Whether the overlay is shown. */\n open: boolean;\n /** Called on Escape or (when `dismissable`) a click outside the panel. */\n onClose: () => void;\n /** Close on a click outside the panel. Default `true`. */\n dismissable?: boolean;\n /** Ignore Escape. Default `false`. */\n keyboardDismissDisabled?: boolean;\n /** Class for the full-screen root. */\n className?: string;\n /** Class for the dimmed backdrop. */\n backdropClassName?: string;\n /**\n * Render the panel. Spread `panelProps` on it and attach `panelRef`.\n * Use a component here if you need hooks (e.g. `useDialog`).\n */\n children: (panel: { panelProps: React.HTMLAttributes<HTMLElement>; panelRef: React.RefObject<HTMLDivElement> }) => React.ReactNode;\n}\n\n/**\n * Overlay: the full-screen layer under Modal (and future Drawer and\n * Sheet). Renders in a portal that keeps the current theme, dims the page,\n * traps and restores focus, hides the page from screen readers, blocks\n * scrolling, and closes on Escape or an outside click.\n *\n * Style hooks: `.sp-overlay`, `.sp-overlay__backdrop`.\n */\nexport function Overlay({ open, ...rest }: OverlayProps) {\n const { anchorRef, themeProps } = usePortalTheme(open);\n const anchor = <span ref={anchorRef} hidden />;\n if (!open || typeof document === 'undefined') return anchor;\n return (\n <>\n {anchor}\n {createPortal(<OverlaySurface {...rest} themeProps={themeProps} />, document.body)}\n </>\n );\n}\n\nfunction OverlaySurface({\n onClose,\n dismissable = true,\n keyboardDismissDisabled = false,\n className,\n backdropClassName,\n children,\n themeProps,\n}: Omit<OverlayProps, 'open'> & { themeProps: ReturnType<typeof usePortalTheme>['themeProps'] }) {\n const panelRef = useRef<HTMLDivElement>(null);\n const state = useOverlayTriggerState({ isOpen: true, onOpenChange: (isOpen) => !isOpen && onClose() });\n const { modalProps, underlayProps } = useModalOverlay(\n { isDismissable: dismissable, isKeyboardDismissDisabled: keyboardDismissDisabled },\n state,\n panelRef,\n );\n return (\n <div className={cx('sp-overlay', className)} data-state=\"open\" {...themeProps} {...underlayProps}>\n <div aria-hidden=\"true\" className={cx('sp-overlay__backdrop', backdropClassName)} />\n <FocusScope contain restoreFocus autoFocus>\n {children({ panelProps: modalProps, panelRef })}\n </FocusScope>\n </div>\n );\n}\n\nexport default Overlay;\n"
41
+ },
42
+ {
43
+ "path": "components/spark-ui/base/Popover.tsx",
44
+ "type": "registry:ui",
45
+ "target": "components/spark-ui/base/Popover.tsx",
46
+ "content": "import React, { forwardRef, useRef } from 'react';\nimport { DismissButton, Overlay as AriaOverlay, mergeRefs, usePopover } from 'react-aria';\nimport type { AriaPopoverProps } from 'react-aria';\nimport type { OverlayTriggerState } from 'react-stately';\nimport { usePortalTheme } from '../internal/usePortalTheme';\nimport { cx } from '../internal/cx';\n\nexport interface PopoverProps extends Omit<AriaPopoverProps, 'popoverRef' | 'triggerRef'> {\n /** Open state, from `useOverlayTriggerState` or a component state (select, combobox, menu). */\n state: OverlayTriggerState;\n /** The element the popover is attached to. Its theme is copied to the popover. */\n triggerRef: React.RefObject<Element | null>;\n /** Make the popover at least as wide as the trigger. */\n matchTriggerWidth?: boolean;\n /** Leave focus handling to the content (used by submenus). */\n disableFocusManagement?: boolean;\n className?: string;\n style?: React.CSSProperties;\n children: React.ReactNode;\n}\n\n/**\n * Popover: a floating panel attached to a trigger, under Dropdown, Combobox,\n * Menu and DatePicker. Positions itself and flips to stay on screen, renders\n * in a portal that keeps the current theme, closes on outside click and\n * Escape, and has hidden dismiss buttons for screen readers.\n *\n * Style hooks: `.sp-popover[data-placement]`.\n */\nexport const Popover = forwardRef<HTMLDivElement, PopoverProps>(function Popover(\n { state, triggerRef, matchTriggerWidth, disableFocusManagement, className, style, children, placement = 'bottom start', offset = 6, isNonModal, ...rest },\n ref,\n) {\n const popoverRef = useRef<HTMLDivElement>(null);\n const { popoverProps, underlayProps, placement: actual } = usePopover(\n { ...rest, placement, offset, isNonModal, popoverRef, triggerRef: triggerRef as React.RefObject<Element> },\n state,\n );\n const { themeProps } = usePortalTheme(true, triggerRef);\n const width = matchTriggerWidth ? (triggerRef.current as HTMLElement | null)?.offsetWidth : undefined;\n return (\n <AriaOverlay disableFocusManagement={disableFocusManagement}>\n <div {...themeProps} style={{ ...themeProps.style, display: 'contents' }}>\n {!isNonModal && <div {...underlayProps} style={{ position: 'fixed', inset: 0 }} />}\n <div\n {...popoverProps}\n ref={mergeRefs(popoverRef, ref) as React.Ref<HTMLDivElement>}\n className={cx('sp-popover', className)}\n data-placement={actual ?? undefined}\n style={{ ...popoverProps.style, minWidth: width, ...style }}\n >\n {!isNonModal && <DismissButton onDismiss={state.close} />}\n {children}\n <DismissButton onDismiss={state.close} />\n </div>\n </div>\n </AriaOverlay>\n );\n});\n\nexport default Popover;\n"
47
+ },
48
+ {
49
+ "path": "components/spark-ui/base/index.ts",
50
+ "type": "registry:ui",
51
+ "target": "components/spark-ui/base/index.ts",
52
+ "content": "/**\n * Spark UI base components: the building blocks under the advanced\n * components. Use them to build your own components that match the rest of\n * the library.\n *\n * Unstable until 1.0: names and props may still change in minor versions.\n */\nexport { ButtonBase } from './ButtonBase';\nexport type { ButtonBaseProps } from './ButtonBase';\nexport { InputBase } from './InputBase';\nexport type { InputBaseProps } from './InputBase';\nexport { Popover } from './Popover';\nexport type { PopoverProps } from './Popover';\nexport { ListBox, ListItemContent, renderListItems, flattenOptions, findOption, isGroup } from './ListBox';\nexport type { ListBoxProps, ListItemContentProps, ListOption, ListOptionGroup, ListItems } from './ListBox';\nexport { Overlay } from './Overlay';\nexport type { OverlayProps } from './Overlay';\n"
53
+ }
54
+ ]
55
+ }
@@ -0,0 +1,33 @@
1
+ {
2
+ "$schema": "https://ui.shadcn.com/schema/registry-item.json",
3
+ "name": "button",
4
+ "type": "registry:ui",
5
+ "title": "Button",
6
+ "description": "Throws sparks from the press point; current runs along outlined buttons on hover.",
7
+ "dependencies": [],
8
+ "registryDependencies": [
9
+ "@sparkwire/base",
10
+ "@sparkwire/styles",
11
+ "@sparkwire/utils"
12
+ ],
13
+ "files": [
14
+ {
15
+ "path": "components/spark-ui/Button/Button.tsx",
16
+ "type": "registry:ui",
17
+ "target": "components/spark-ui/Button/Button.tsx",
18
+ "content": "import React, { ElementType, forwardRef } from 'react';\nimport { PolymorphicButtonProps } from './Button.types';\nimport { ButtonBase } from '../base/ButtonBase';\nimport { useDefaults, slot, ClassNames } from '../internal/defaults';\n\n/**\n * Button: throws sparks from the press point. Outlined and text buttons show\n * current flowing along a wire on hover; a disabled button is a dead circuit.\n * Built on ButtonBase; forwards `ref` to the rendered element.\n */\nconst ButtonInner = (inProps: PolymorphicButtonProps<ElementType>, ref: React.ForwardedRef<HTMLElement>) => {\n const {\n as,\n variant = 'contained',\n color = 'brand',\n size = 'medium',\n disabled = false,\n className,\n startIcon,\n endIcon,\n children,\n fullWidth = false,\n disableElevation = false,\n spark,\n ripple,\n classNames,\n ...rest\n } = useDefaults('Button', inProps);\n const slots = classNames as ClassNames<'root' | 'icon'> | undefined;\n\n return (\n <ButtonBase\n ref={ref}\n as={as}\n disabled={disabled}\n spark={spark ?? ripple ?? true}\n sparkColors={color === 'brand' ? undefined : ['var(--sp-fill)', 'var(--spark-energy-hot)', 'var(--sp-hover)']}\n className={slot('sp-button', slots, 'root', className)}\n data-variant={variant}\n data-tone={color}\n data-size={size}\n data-full-width={fullWidth || undefined}\n data-flat={disableElevation || undefined}\n {...(rest as React.ButtonHTMLAttributes<HTMLElement>)}\n >\n {startIcon && <span className={slot('sp-button__icon slot-startIcon', slots, 'icon')}>{startIcon}</span>}\n {children}\n {endIcon && <span className={slot('sp-button__icon slot-endIcon', slots, 'icon')}>{endIcon}</span>}\n </ButtonBase>\n );\n};\n\nconst Button = forwardRef(ButtonInner) as <C extends ElementType = 'button'>(\n props: PolymorphicButtonProps<C> & { ref?: React.Ref<HTMLElement> },\n) => React.ReactElement | null;\n\nexport default Button;\n"
19
+ },
20
+ {
21
+ "path": "components/spark-ui/Button/Button.types.ts",
22
+ "type": "registry:ui",
23
+ "target": "components/spark-ui/Button/Button.types.ts",
24
+ "content": "import { ReactNode, ElementType } from 'react';\nimport { OverrideProps } from '../internal/spark-utils';\n\nexport type ButtonVariant = 'text' | 'outlined' | 'contained';\nexport type ButtonSize = 'small' | 'medium' | 'large';\nexport type ButtonColor = 'brand' | 'error' | 'success' | 'warning';\n\n// Base interface for Button props\nexport interface ButtonPropsBase {\n children?: ReactNode;\n className?: string;\n /** Dead circuit: no clicks, no sparks, dashed outline. */\n disabled?: boolean;\n /** Icon before the label. Coloured with the text. */\n startIcon?: ReactNode;\n /** Icon after the label. Coloured with the text. */\n endIcon?: ReactNode;\n /** Stretch to the container's width. */\n fullWidth?: boolean;\n /** Throw sparks from the press point on click. Default `true`. */\n spark?: boolean;\n /** @deprecated Use `spark`. Kept so existing code keeps working. */\n ripple?: boolean;\n /** Extra classes for each part: root, icon. */\n classNames?: Partial<Record<'root' | 'icon', string>>;\n}\n\n// Type map for Button with default component and props\nexport type ButtonTypeMap<P = {}, D extends ElementType = 'button'> = {\n props: P &\n ButtonPropsBase & {\n /** `contained` (filled, default), `outlined` or `text`. */\n variant?: ButtonVariant;\n /** Tone of the current. Default `brand`. */\n color?: ButtonColor;\n /** Height 36, 44 or 52px. Default `medium`. */\n size?: ButtonSize;\n /** Use with `as=\"a\"` to render a link that looks like a button. */\n href?: string;\n /** Remove the glow around contained buttons. */\n disableElevation?: boolean;\n };\n defaultComponent: D;\n};\n\n// Utility type for polymorphic Button props\nexport type PolymorphicButtonProps<\n D extends ElementType = ButtonTypeMap['defaultComponent'],\n P = {}\n> = OverrideProps<ButtonTypeMap<P, D>, D> & {\n /** Render as another element or component, e.g. `as=\"a\"`. */\n as?: ElementType;\n};\n\n// Slot props for Button (if applicable)\nexport type ButtonSlotProps = {\n root?: PolymorphicButtonProps;\n startIcon?: ReactNode;\n endIcon?: ReactNode;\n};\n\n\nexport type { ElementType, ReactNode };\n"
25
+ },
26
+ {
27
+ "path": "components/spark-ui/Button/index.ts",
28
+ "type": "registry:ui",
29
+ "target": "components/spark-ui/Button/index.ts",
30
+ "content": "export {default as Button} from './Button';"
31
+ }
32
+ ]
33
+ }
@@ -0,0 +1,26 @@
1
+ {
2
+ "$schema": "https://ui.shadcn.com/schema/registry-item.json",
3
+ "name": "card",
4
+ "type": "registry:ui",
5
+ "title": "Card",
6
+ "description": "Card, CardHeader, CardFooter and Skeleton.",
7
+ "dependencies": [],
8
+ "registryDependencies": [
9
+ "@sparkwire/styles",
10
+ "@sparkwire/utils"
11
+ ],
12
+ "files": [
13
+ {
14
+ "path": "components/spark-ui/Card/Card.tsx",
15
+ "type": "registry:ui",
16
+ "target": "components/spark-ui/Card/Card.tsx",
17
+ "content": "import React from 'react';\nimport { useMessages } from '../internal/messages';\nimport { cx } from '../internal/cx';\nimport { useDefaults } from '../internal/defaults';\n\n/* ------------------------------------------------------------------- Card */\n\nexport interface CardProps extends React.HTMLAttributes<HTMLElement> {\n /** A live card has current running along its top edge. */\n live?: boolean;\n /** Hover lift and glow, for clickable cards. Put the link or button inside. */\n interactive?: boolean;\n /** Render as another element, e.g. `article` or `section`. */\n as?: 'div' | 'article' | 'section' | 'li';\n /** Inner spacing. Default `medium`. */\n padding?: 'none' | 'small' | 'medium' | 'large';\n}\n\n/**\n * Card: a raised panel. `live` cards carry current; `interactive` cards glow on hover.\n * Style hooks: `.sp-card[data-live][data-interactive][data-padding]`, `__current`.\n */\nexport function Card(inProps: CardProps) {\n const { live = false, interactive = false, as: Tag = 'div', padding = 'medium', className, children, ...rest } = useDefaults('Card', inProps);\n return (\n <Tag\n className={cx('sp-card', className)}\n data-live={live || undefined}\n data-interactive={interactive || undefined}\n data-padding={padding}\n {...rest}\n >\n {live && <span aria-hidden=\"true\" className=\"sp-card__current sp-current\" />}\n {children}\n </Tag>\n );\n}\n\nexport interface CardHeaderProps {\n title: React.ReactNode;\n subtitle?: React.ReactNode;\n /** Shown on the left, e.g. an Avatar or icon. */\n media?: React.ReactNode;\n /** Shown on the right, e.g. a Badge or menu button. */\n action?: React.ReactNode;\n}\n\nexport function CardHeader({ title, subtitle, media, action }: CardHeaderProps) {\n return (\n <div className=\"sp-card__header\">\n {media}\n <div className=\"sp-card__heading\">\n <h3 className=\"sp-card__title\">{title}</h3>\n {subtitle && <p className=\"sp-card__subtitle\">{subtitle}</p>}\n </div>\n {action}\n </div>\n );\n}\n\nexport function CardFooter({ children }: { children: React.ReactNode }) {\n return <div className=\"sp-card__footer\">{children}</div>;\n}\n\n/* --------------------------------------------------------------- Skeleton */\n\nexport interface SkeletonProps {\n /** Number (px) or any CSS length. Defaults to 100%. */\n width?: number | string;\n /** Number (px) or any CSS length. */\n height?: number | string;\n /** `circle` for avatars, `text` for lines of copy. */\n shape?: 'rect' | 'circle' | 'text';\n /** For `text`: number of lines. The last line is shorter. */\n lines?: number;\n}\n\nconst len = (v: number | string | undefined, fallback: string) => (typeof v === 'number' ? `${v}px` : v ?? fallback);\n\n/** Skeleton: a placeholder that shimmers like a line charging up. */\nexport function Skeleton({ width, height, shape = 'rect', lines = 1 }: SkeletonProps) {\n const m = useMessages();\n if (shape === 'text') {\n return (\n <span role=\"status\" aria-label={m.loading} className=\"sp-skeleton-text\" style={{ width: len(width, '100%') }}>\n {Array.from({ length: lines }, (_, i) => (\n <span\n key={i}\n aria-hidden=\"true\"\n className=\"sp-skeleton\"\n style={{ width: i === lines - 1 && lines > 1 ? '60%' : '100%', height: len(height, '0.8rem') }}\n />\n ))}\n </span>\n );\n }\n const size = shape === 'circle' ? width ?? height ?? 40 : undefined;\n const w = len(size ?? width, '100%');\n return (\n <span role=\"status\" aria-label={m.loading} className=\"sp-skeleton-wrap\" style={{ width: w }}>\n <span aria-hidden=\"true\" className=\"sp-skeleton\" data-shape={shape} style={{ width: w, height: len(size ?? height, '1rem') }} />\n </span>\n );\n}\n"
18
+ },
19
+ {
20
+ "path": "components/spark-ui/Card/index.ts",
21
+ "type": "registry:ui",
22
+ "target": "components/spark-ui/Card/index.ts",
23
+ "content": "export { Card, CardHeader, CardFooter, Skeleton } from './Card';\nexport type { CardProps, CardHeaderProps, SkeletonProps } from './Card';\n"
24
+ }
25
+ ]
26
+ }
@@ -0,0 +1,40 @@
1
+ {
2
+ "$schema": "https://ui.shadcn.com/schema/registry-item.json",
3
+ "name": "charts",
4
+ "type": "registry:ui",
5
+ "title": "Charts",
6
+ "description": "Our own SVG charts: Line/Area, Bar (grouped, stacked, horizontal), Donut, Sparkline. Validated colour-blind-safe palette, tooltips, keyboard, data-table view.",
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/Charts/CartesianChart.tsx",
17
+ "type": "registry:ui",
18
+ "target": "components/spark-ui/Charts/CartesianChart.tsx",
19
+ "content": "import React, { useState } from 'react';\nimport { useMessages } from '../internal/messages';\nimport { ChartBaseProps, ChartFrame, MARGIN, TooltipBody, linear, niceTicks, seriesColor, useFormatters, useHiddenSeries } from './core';\nimport { useDefaults } from '../internal/defaults';\n\nexport interface LineChartProps<Row> extends ChartBaseProps<Row> {\n /** Fill under each line. */\n area?: boolean;\n /** Stack the series (implies `area`). */\n stacked?: boolean;\n /** Smooth the lines. Default `true`. */\n curved?: boolean;\n /** Show a dot on every point (default: only the hovered one). */\n showPoints?: boolean;\n /** Start the y axis at zero. Default `true` for areas, `false` for lines. */\n zeroBaseline?: boolean;\n}\n\nexport interface BarChartProps<Row> extends ChartBaseProps<Row> {\n /** Stack the series in one bar instead of side by side. */\n stacked?: boolean;\n /** Bars run left to right (good for long category names). */\n horizontal?: boolean;\n}\n\n/* ------------------------------------------------------------ geometry */\n\n/** Monotone cubic path: smooth without overshooting the data. */\nfunction monotonePath(pts: Array<[number, number]>) {\n if (pts.length < 3) return pts.map((p, i) => `${i ? 'L' : 'M'}${p[0]},${p[1]}`).join('');\n const n = pts.length;\n const dx = pts.slice(1).map((p, i) => p[0] - pts[i][0]);\n const slope = pts.slice(1).map((p, i) => (p[1] - pts[i][1]) / (dx[i] || 1));\n const m = pts.map((_, i) => (i === 0 ? slope[0] : i === n - 1 ? slope[n - 2] : slope[i - 1] * slope[i] <= 0 ? 0 : (slope[i - 1] + slope[i]) / 2));\n let d = `M${pts[0][0]},${pts[0][1]}`;\n for (let i = 0; i < n - 1; i++) {\n const h = dx[i] / 3;\n d += `C${pts[i][0] + h},${pts[i][1] + m[i] * h} ${pts[i + 1][0] - h},${pts[i + 1][1] - m[i + 1] * h} ${pts[i + 1][0]},${pts[i + 1][1]}`;\n }\n return d;\n}\nconst straightPath = (pts: Array<[number, number]>) => pts.map((p, i) => `${i ? 'L' : 'M'}${p[0]},${p[1]}`).join('');\n\n/** A bar with 4px rounded corners on its data end only, anchored square to the baseline. */\nfunction barPath(x: number, y: number, w: number, h: number, end: 'top' | 'right' | 'bottom' | 'left', r = 4) {\n r = Math.max(0, Math.min(r, w / 2, h / 2));\n if (end === 'top') return `M${x},${y + h}V${y + r}Q${x},${y} ${x + r},${y}H${x + w - r}Q${x + w},${y} ${x + w},${y + r}V${y + h}Z`;\n if (end === 'bottom') return `M${x},${y}V${y + h - r}Q${x},${y + h} ${x + r},${y + h}H${x + w - r}Q${x + w},${y + h} ${x + w},${y + h - r}V${y}Z`;\n if (end === 'right') return `M${x},${y}H${x + w - r}Q${x + w},${y} ${x + w},${y + r}V${y + h - r}Q${x + w},${y + h} ${x + w - r},${y + h}H${x}Z`;\n return `M${x + w},${y}H${x + r}Q${x},${y} ${x},${y + r}V${y + h - r}Q${x},${y + h} ${x + r},${y + h}H${x + w}Z`;\n}\n\nconst num = (v: unknown) => (typeof v === 'number' && Number.isFinite(v) ? v : 0);\n\n/* ------------------------------------------------------------ LineChart */\n\n/**\n * LineChart (and AreaChart with `area` / `stacked`): change over time or an\n * ordered axis. Thin 2px lines that draw in like current, a crosshair and\n * tooltip that follow the pointer, keyboard stepping (focus the chart, then\n * ← →), legend toggles, and a data-table view. One y axis only.\n *\n * Style hooks: `.sp-chart[data-kind=\"line\"|\"area\"]`, `__line`, `__area`,\n * `__crosshair`, `__point`, `__grid`, `__axis`. Colours: `--spark-chart-1…8`.\n */\nexport function LineChart<Row>(inProps: LineChartProps<Row>) {\n const props = useDefaults('LineChart', inProps) as LineChartProps<Row>;\n const { data, x, series, height = 280, stacked = false, curved = true, showPoints = false } = props;\n const area = props.area || stacked;\n const zero = props.zeroBaseline ?? area;\n const [hidden, toggle] = useHiddenSeries();\n const [active, setActive] = useState<number | null>(null);\n const [tipX, setTipX] = useState(0);\n const f = useFormatters<Row>(props);\n const msg = useMessages();\n const visible = series.map((s, i) => ({ s, i })).filter(({ s }) => !hidden.has(s.key));\n\n // Stacked totals per row, bottom-up in series order.\n const stacks = data.map((row) => {\n let acc = 0;\n return visible.map(({ s }) => {\n const lo = stacked ? acc : 0;\n acc = stacked ? acc + num((row as Record<string, unknown>)[s.key]) : num((row as Record<string, unknown>)[s.key]);\n return [lo, acc] as [number, number];\n });\n });\n const values = stacks.flat().flat();\n const lo = zero ? Math.min(0, ...values) : Math.min(...values);\n const hi = Math.max(...values, lo + 1);\n const ticks = niceTicks(lo, hi);\n\n const render = (width: number) => {\n const iw = width - MARGIN.left - MARGIN.right;\n const ih = height - MARGIN.top - MARGIN.bottom;\n const sx = (i: number) => MARGIN.left + (data.length < 2 ? iw / 2 : (i / (data.length - 1)) * iw);\n const sy = linear(ticks[0], ticks[ticks.length - 1], MARGIN.top + ih, MARGIN.top);\n const path = curved ? monotonePath : straightPath;\n const xLabelEvery = Math.max(1, Math.ceil(data.length / Math.max(2, Math.floor(iw / 80))));\n\n const go = (i: number) => {\n setActive(i);\n setTipX(sx(i));\n };\n const pick = (clientX: number, rect: DOMRect) => {\n const rel = ((clientX - rect.left - MARGIN.left) / iw) * (data.length - 1);\n go(Math.max(0, Math.min(data.length - 1, Math.round(rel))));\n };\n\n return (\n <svg\n width={width}\n height={height}\n className=\"sp-chart__svg\"\n role=\"img\"\n aria-label={`${typeof props.title === 'string' ? props.title : props['aria-label'] ?? msg.chart}: ${visible.map(({ s }) => s.label).join(', ')}`}\n tabIndex={0}\n onPointerMove={(e) => pick(e.clientX, e.currentTarget.getBoundingClientRect())}\n onPointerLeave={() => setActive(null)}\n onBlur={() => setActive(null)}\n onKeyDown={(e) => {\n if (e.key === 'ArrowRight') go(Math.min(data.length - 1, (active ?? -1) + 1));\n else if (e.key === 'ArrowLeft') go(Math.max(0, (active ?? data.length) - 1));\n else if (e.key === 'Home') go(0);\n else if (e.key === 'End') go(data.length - 1);\n else if (e.key === 'Escape') setActive(null);\n else return;\n e.preventDefault();\n }}\n >\n <g className=\"sp-chart__grid\" aria-hidden=\"true\">\n {ticks.map((t) => (\n <g key={t}>\n <line x1={MARGIN.left} x2={MARGIN.left + iw} y1={sy(t)} y2={sy(t)} data-zero={t === 0 || undefined} />\n <text x={MARGIN.left - 8} y={sy(t)} dy=\"0.32em\" textAnchor=\"end\" className=\"sp-chart__axis\">\n {f.axis(t)}\n </text>\n </g>\n ))}\n {data.map((row, i) =>\n i % xLabelEvery === 0 ? (\n <text key={i} x={sx(i)} y={height - 8} textAnchor=\"middle\" className=\"sp-chart__axis\">\n {f.x((row as Record<string, unknown>)[x])}\n </text>\n ) : null,\n )}\n </g>\n {visible.map(({ s, i }, vi) => {\n const top = data.map((_, r) => [sx(r), sy(stacks[r][vi][1])] as [number, number]);\n const base = data.map((_, r) => [sx(r), sy(stacks[r][vi][0])] as [number, number]);\n const color = seriesColor(series, i);\n const areaD = area ? `${path(top)}L${base[base.length - 1][0]},${base[base.length - 1][1]}${path([...base].reverse()).replace(/^M/, 'L')}Z` : '';\n return (\n <g key={s.key} aria-hidden=\"true\">\n {area && <path d={areaD} className=\"sp-chart__area\" style={{ fill: color }} />}\n <path d={path(top)} className=\"sp-chart__line\" pathLength={1} style={{ stroke: color }} />\n {showPoints && top.map(([px, py], r) => <circle key={r} cx={px} cy={py} r={3} className=\"sp-chart__dot\" style={{ fill: color }} />)}\n </g>\n );\n })}\n {active !== null && (\n <g aria-hidden=\"true\">\n <line className=\"sp-chart__crosshair\" x1={sx(active)} x2={sx(active)} y1={MARGIN.top} y2={MARGIN.top + ih} />\n {visible.map(({ s, i }, vi) => (\n <circle key={s.key} cx={sx(active)} cy={sy(stacks[active][vi][1])} r={4.5} className=\"sp-chart__point\" style={{ fill: seriesColor(series, i) }} />\n ))}\n </g>\n )}\n </svg>\n );\n };\n\n const activeRow = active !== null ? (data[active] as Record<string, unknown>) : null;\n return (\n <ChartFrame\n {...props}\n kind={area ? 'area' : 'line'}\n hidden={hidden}\n onToggle={toggle}\n tooltipPos={active !== null ? { x: tipX, y: (props.height ?? 280) / 2 } : null}\n tooltip={\n activeRow && (\n <TooltipBody\n heading={f.x(activeRow[x])}\n rows={visible.map(({ s, i }) => ({ label: s.label, value: f.value(num(activeRow[s.key])), color: seriesColor(series, i) })).reverse()}\n />\n )\n }\n children={render}\n />\n );\n}\n\n/* ------------------------------------------------------------- BarChart */\n\n/**\n * BarChart: compare amounts across categories. Grouped or `stacked`,\n * vertical or `horizontal`. Thin bars with 4px rounded data ends, square to\n * the baseline, a 2px gap between neighbours; a per-group tooltip on hover\n * or keyboard (focus the chart, then arrow keys), legend toggles and a\n * data-table view.\n *\n * Style hooks: `.sp-chart[data-kind=\"bar\"]`, `__bar[data-active]`, `__band`.\n */\nexport function BarChart<Row>(inProps: BarChartProps<Row>) {\n const props = useDefaults('BarChart', inProps) as BarChartProps<Row>;\n const { data, x, series, height = 280, stacked = false, horizontal = false } = props;\n const [hidden, toggle] = useHiddenSeries();\n const [active, setActive] = useState<number | null>(null);\n const [tip, setTip] = useState<{ x: number; y: number } | null>(null);\n const f = useFormatters<Row>(props);\n const msg = useMessages();\n const visible = series.map((s, i) => ({ s, i })).filter(({ s }) => !hidden.has(s.key));\n const totals = data.map((row) => visible.reduce((a, { s }) => a + num((row as Record<string, unknown>)[s.key]), 0));\n const maxV = stacked ? Math.max(1, ...totals) : Math.max(1, ...data.flatMap((row) => visible.map(({ s }) => num((row as Record<string, unknown>)[s.key]))));\n const ticks = niceTicks(0, maxV);\n const labelW = horizontal ? Math.min(140, 12 + Math.max(...data.map((r) => f.x((r as Record<string, unknown>)[x]).length)) * 7) : 0;\n\n const render = (width: number) => {\n const m = { ...MARGIN, left: horizontal ? labelW : MARGIN.left, bottom: horizontal ? 24 : MARGIN.bottom };\n const iw = width - m.left - m.right;\n const ih = height - m.top - m.bottom;\n const n = data.length;\n const band = (horizontal ? ih : iw) / Math.max(n, 1);\n const groupPad = band * 0.22;\n const inner = band - groupPad * 2;\n const per = stacked ? inner : inner / Math.max(visible.length, 1);\n const val = linear(0, ticks[ticks.length - 1], 0, horizontal ? iw : ih);\n const gap = 2;\n\n const at = (clientX: number, clientY: number, rect: DOMRect) => {\n const pos = horizontal ? clientY - rect.top - m.top : clientX - rect.left - m.left;\n const i = Math.floor(pos / band);\n if (i < 0 || i >= n) return setActive(null);\n setActive(i);\n setTip(horizontal ? { x: Math.min(width - 40, m.left + val(totalsOrMax(i)) + 8), y: m.top + band * i + band / 2 } : { x: m.left + band * i + band / 2, y: m.top + ih - val(totalsOrMax(i)) });\n };\n const totalsOrMax = (i: number) => (stacked ? totals[i] : Math.max(0, ...visible.map(({ s }) => num((data[i] as Record<string, unknown>)[s.key]))));\n const xLabelEvery = horizontal ? 1 : Math.max(1, Math.ceil(n / Math.max(2, Math.floor(iw / 70))));\n\n return (\n <svg\n width={width}\n height={height}\n className=\"sp-chart__svg\"\n role=\"img\"\n aria-label={`${typeof props.title === 'string' ? props.title : props['aria-label'] ?? msg.chart}: ${visible.map(({ s }) => s.label).join(', ')}`}\n tabIndex={0}\n onPointerMove={(e) => at(e.clientX, e.clientY, e.currentTarget.getBoundingClientRect())}\n onPointerLeave={() => setActive(null)}\n onBlur={() => setActive(null)}\n onKeyDown={(e) => {\n const next = e.key === 'ArrowRight' || e.key === 'ArrowDown' ? 1 : e.key === 'ArrowLeft' || e.key === 'ArrowUp' ? -1 : 0;\n if (e.key === 'Escape') setActive(null);\n else if (next) {\n const i = Math.max(0, Math.min(n - 1, (active ?? (next > 0 ? -1 : n)) + next));\n setActive(i);\n setTip(horizontal ? { x: Math.min(width - 40, m.left + val(totalsOrMax(i)) + 8), y: m.top + band * i + band / 2 } : { x: m.left + band * i + band / 2, y: m.top + ih - val(totalsOrMax(i)) });\n } else return;\n e.preventDefault();\n }}\n >\n <g className=\"sp-chart__grid\" aria-hidden=\"true\">\n {ticks.map((t) =>\n horizontal ? (\n <g key={t}>\n <line x1={m.left + val(t)} x2={m.left + val(t)} y1={m.top} y2={m.top + ih} data-zero={t === 0 || undefined} />\n <text x={m.left + val(t)} y={height - 6} textAnchor=\"middle\" className=\"sp-chart__axis\">\n {f.axis(t)}\n </text>\n </g>\n ) : (\n <g key={t}>\n <line x1={m.left} x2={m.left + iw} y1={m.top + ih - val(t)} y2={m.top + ih - val(t)} data-zero={t === 0 || undefined} />\n <text x={m.left - 8} y={m.top + ih - val(t)} dy=\"0.32em\" textAnchor=\"end\" className=\"sp-chart__axis\">\n {f.axis(t)}\n </text>\n </g>\n ),\n )}\n {data.map((row, i) =>\n i % xLabelEvery === 0 ? (\n horizontal ? (\n <text key={i} x={m.left - 8} y={m.top + band * i + band / 2} dy=\"0.32em\" textAnchor=\"end\" className=\"sp-chart__axis sp-chart__category\">\n {f.x((row as Record<string, unknown>)[x])}\n </text>\n ) : (\n <text key={i} x={m.left + band * i + band / 2} y={height - 8} textAnchor=\"middle\" className=\"sp-chart__axis\">\n {f.x((row as Record<string, unknown>)[x])}\n </text>\n )\n ) : null,\n )}\n </g>\n {active !== null && (\n <rect\n className=\"sp-chart__band\"\n aria-hidden=\"true\"\n x={horizontal ? m.left : m.left + band * active}\n y={horizontal ? m.top + band * active : m.top}\n width={horizontal ? iw : band}\n height={horizontal ? band : ih}\n />\n )}\n <g aria-hidden=\"true\">\n {data.map((row, r) => {\n let acc = 0;\n return visible.map(({ s, i }, vi) => {\n const v = Math.max(0, num((row as Record<string, unknown>)[s.key]));\n const len = val(v);\n const start = stacked ? val(acc) : 0;\n acc += v;\n const isTop = !stacked || vi === visible.length - 1 || visible.slice(vi + 1).every(({ s: s2 }) => num((row as Record<string, unknown>)[s2.key]) <= 0);\n const offset = groupPad + (stacked ? 0 : per * vi);\n const thick = Math.max(1, per - (stacked ? 0 : gap));\n // In stacks, each segment gives up 2px at its far end so neighbours are separated by the surface.\n const segLen = stacked && !isTop ? Math.max(0, len - gap) : len;\n if (segLen <= 0) return null;\n const d = horizontal\n ? barPath(m.left + start, m.top + band * r + offset, segLen, thick, 'right', isTop ? 4 : 0)\n : barPath(m.left + band * r + offset, m.top + ih - start - segLen, thick, segLen, 'top', isTop ? 4 : 0);\n return <path key={s.key} d={d} className=\"sp-chart__bar\" data-active={active === r || undefined} style={{ fill: seriesColor(series, i) }} />;\n });\n })}\n </g>\n </svg>\n );\n };\n\n const row = active !== null ? (data[active] as Record<string, unknown>) : null;\n return (\n <ChartFrame\n {...props}\n kind=\"bar\"\n hidden={hidden}\n onToggle={toggle}\n tooltipPos={active !== null ? tip : null}\n tooltip={\n row && (\n <TooltipBody\n heading={f.x(row[x]) + (stacked && visible.length > 1 ? ` · ${f.value(totals[active!])}` : '')}\n rows={visible.map(({ s, i }) => ({ label: s.label, value: f.value(num(row[s.key])), color: seriesColor(series, i) }))}\n />\n )\n }\n children={render}\n />\n );\n}\n"
20
+ },
21
+ {
22
+ "path": "components/spark-ui/Charts/DonutChart.tsx",
23
+ "type": "registry:ui",
24
+ "target": "components/spark-ui/Charts/DonutChart.tsx",
25
+ "content": "import React, { useId, useState } from 'react';\nimport { useMessages } from '../internal/messages';\nimport { ClassNames, slot, useDefaults } from '../internal/defaults';\nimport { useFormatters } from './core';\n\nexport interface DonutSlice {\n label: string;\n value: number;\n /** Default: the next categorical slot, in order. */\n color?: string;\n}\n\nexport interface DonutChartProps {\n /** Parts of one whole. Keep it to 6 or fewer; fold the rest into \"Other\". */\n data: DonutSlice[];\n title?: React.ReactNode;\n 'aria-label'?: string;\n /** Headline in the hole. Default: the total. */\n centerLabel?: React.ReactNode;\n /** Small caption under the headline. Default \"Total\". */\n centerCaption?: React.ReactNode;\n /** Diameter in px. Default 200. */\n size?: number;\n /** Ring thickness in px. Default 28. */\n thickness?: number;\n valueFormat?: Intl.NumberFormatOptions;\n className?: string;\n classNames?: ClassNames<'root' | 'title' | 'legend' | 'plot'>;\n}\n\nconst TAU = Math.PI * 2;\nfunction arc(cx: number, cy: number, r0: number, r1: number, a0: number, a1: number) {\n const p = (r: number, a: number) => `${cx + r * Math.sin(a)},${cy - r * Math.cos(a)}`;\n const big = a1 - a0 > Math.PI ? 1 : 0;\n return `M${p(r1, a0)}A${r1},${r1} 0 ${big} 1 ${p(r1, a1)}L${p(r0, a1)}A${r0},${r0} 0 ${big} 0 ${p(r0, a0)}Z`;\n}\n\n/**\n * DonutChart: share of a whole. Slices start at 12 o'clock in data order,\n * separated by a 2px surface gap; the legend lists every slice with its\n * value and percentage so identity never depends on colour alone. Hover or\n * focus a slice (Tab, then ← →) for its tooltip.\n *\n * Style hooks: `.sp-chart[data-kind=\"donut\"]`, `__slice[data-active]`, `__center`.\n */\nexport function DonutChart(inProps: DonutChartProps) {\n const props = useDefaults('DonutChart', inProps) as DonutChartProps;\n const m = useMessages();\n const { data, title, size = 200, thickness = 28, centerCaption = m.total, className, classNames } = props;\n const [active, setActive] = useState<number | null>(null);\n const f = useFormatters({ valueFormat: props.valueFormat });\n const titleId = useId();\n const total = data.reduce((a, d) => a + Math.max(0, d.value), 0) || 1;\n const r1 = size / 2;\n const r0 = r1 - thickness;\n const gap = 2 / r1; // 2px of surface between slices, measured on the outer edge\n const pct = (v: number) => `${Math.round((v / total) * 1000) / 10}%`;\n const color = (i: number) => data[i].color ?? `var(--spark-chart-${(i % 8) + 1})`;\n\n let a = 0;\n const slices = data.map((d, i) => {\n const sweep = (Math.max(0, d.value) / total) * TAU;\n const s = { a0: a + (data.length > 1 ? gap / 2 : 0), a1: a + sweep - (data.length > 1 ? gap / 2 : 0) };\n a += sweep;\n return s;\n });\n\n return (\n <figure className={slot('sp-chart', classNames, 'root', className)} data-kind=\"donut\" aria-labelledby={title ? titleId : undefined} aria-label={title ? undefined : props['aria-label']}>\n {title && (\n <figcaption id={titleId} className={slot('sp-chart__title', classNames, 'title')}>\n {title}\n </figcaption>\n )}\n <div className={slot('sp-chart__donut', classNames, 'plot')}>\n <div className=\"sp-chart__donut-ring\" style={{ width: size, height: size }}>\n <svg width={size} height={size} viewBox={`0 0 ${size} ${size}`} role=\"group\" aria-label={typeof title === 'string' ? title : props['aria-label'] ?? m.chart}>\n {data.map((d, i) =>\n slices[i].a1 > slices[i].a0 ? (\n <path\n key={d.label}\n d={data.length === 1 ? arc(r1, r1, r0, r1, 0, TAU - 0.0001) : arc(r1, r1, active === i ? r0 - 2 : r0, active === i ? r1 : r1 - 2, slices[i].a0, slices[i].a1)}\n className=\"sp-chart__slice\"\n data-active={active === i || undefined}\n style={{ fill: color(i) }}\n tabIndex={0}\n role=\"img\"\n aria-label={`${d.label}: ${f.value(d.value)}, ${pct(d.value)}`}\n onPointerEnter={() => setActive(i)}\n onPointerLeave={() => setActive(null)}\n onFocus={() => setActive(i)}\n onBlur={() => setActive(null)}\n onKeyDown={(e) => {\n const step = e.key === 'ArrowRight' || e.key === 'ArrowDown' ? 1 : e.key === 'ArrowLeft' || e.key === 'ArrowUp' ? -1 : 0;\n if (!step) return;\n e.preventDefault();\n const paths = (e.currentTarget.parentNode as SVGElement).querySelectorAll<SVGPathElement>('.sp-chart__slice');\n paths[(Array.from(paths).indexOf(e.currentTarget) + step + paths.length) % paths.length]?.focus();\n }}\n />\n ) : null,\n )}\n </svg>\n {/* Hover/focus readout lives in the hole; the legend row highlights too. */}\n <div className=\"sp-chart__center\" aria-live=\"polite\">\n {active !== null ? (\n <>\n <strong>{pct(data[active].value)}</strong>\n <span>\n {data[active].label} · {f.value(data[active].value)}\n </span>\n </>\n ) : (\n <>\n <strong>{props.centerLabel ?? f.axis(total)}</strong>\n <span>{centerCaption}</span>\n </>\n )}\n </div>\n </div>\n <ul className={slot('sp-chart__legend sp-chart__legend--list', classNames, 'legend')}>\n {data.map((d, i) => (\n <li key={d.label} data-active={active === i || undefined}>\n <span className=\"sp-chart__swatch\" style={{ background: color(i) }} aria-hidden=\"true\" />\n <span className=\"sp-chart__legend-label\">{d.label}</span>\n <span className=\"sp-chart__legend-value\">{f.value(d.value)}</span>\n <span className=\"sp-chart__legend-pct\">{pct(d.value)}</span>\n </li>\n ))}\n </ul>\n </div>\n </figure>\n );\n}\n\nexport interface SparklineProps {\n /** Values in order (oldest first). */\n data: number[];\n /** What the line shows, for screen readers, e.g. \"Sign-ups, last 30 days\". */\n 'aria-label': string;\n width?: number;\n height?: number;\n /** Fill under the line. */\n area?: boolean;\n /** Line colour. Default `--spark-chart-1`. */\n color?: string;\n /** Mark the last value with a dot. Default `true`. */\n showLast?: boolean;\n className?: string;\n}\n\n/**\n * Sparkline: a word-sized trend for tables, stat tiles and cards. No axes;\n * the last point is marked so the current value is easy to find. Its\n * accessible name states the first, last and range.\n */\nexport function Sparkline(inProps: SparklineProps) {\n const { data, width = 96, height = 28, area = false, color = 'var(--spark-chart-1)', showLast = true, className, ...rest } = useDefaults('Sparkline', inProps) as SparklineProps;\n const id = useId().replace(/:/g, '');\n if (!data.length) return null;\n const lo = Math.min(...data);\n const hi = Math.max(...data);\n const pad = 3;\n const sx = (i: number) => pad + (data.length < 2 ? (width - pad * 2) / 2 : (i / (data.length - 1)) * (width - pad * 2));\n const sy = (v: number) => (hi === lo ? height / 2 : pad + (1 - (v - lo) / (hi - lo)) * (height - pad * 2));\n const line = data.map((v, i) => `${i ? 'L' : 'M'}${sx(i).toFixed(1)},${sy(v).toFixed(1)}`).join('');\n const last = data[data.length - 1];\n return (\n <svg\n className={['sp-sparkline', className].filter(Boolean).join(' ')}\n width={width}\n height={height}\n viewBox={`0 0 ${width} ${height}`}\n role=\"img\"\n aria-label={`${rest['aria-label']}: from ${data[0]} to ${last}, low ${lo}, high ${hi}`}\n >\n {area && (\n <>\n <defs>\n <linearGradient id={`sp-spark-${id}`} x1=\"0\" x2=\"0\" y1=\"0\" y2=\"1\">\n <stop offset=\"0\" stopColor={color} stopOpacity=\"0.28\" />\n <stop offset=\"1\" stopColor={color} stopOpacity=\"0\" />\n </linearGradient>\n </defs>\n <path d={`${line}L${sx(data.length - 1)},${height}L${sx(0)},${height}Z`} fill={`url(#sp-spark-${id})`} />\n </>\n )}\n <path d={line} fill=\"none\" stroke={color} strokeWidth={1.5} strokeLinejoin=\"round\" strokeLinecap=\"round\" />\n {showLast && <circle cx={sx(data.length - 1)} cy={sy(last)} r={2.5} fill={color} stroke=\"var(--spark-surface-base)\" strokeWidth={1.5} />}\n </svg>\n );\n}\n"
26
+ },
27
+ {
28
+ "path": "components/spark-ui/Charts/core.tsx",
29
+ "type": "registry:ui",
30
+ "target": "components/spark-ui/Charts/core.tsx",
31
+ "content": "import React, { useEffect, useId, useMemo, useRef, useState } from 'react';\nimport { useMessages } from '../internal/messages';\nimport { useLocale } from 'react-aria';\nimport { slot, ClassNames } from '../internal/defaults';\n\n/* ------------------------------------------------------------------ types */\n\nexport interface ChartSeries<Row> {\n /** Field of each row holding this series' value. */\n key: keyof Row & string;\n /** Name in the legend, tooltip and table. */\n label: string;\n /**\n * Colour. Default: the next slot of the validated categorical palette\n * (`--spark-chart-1` … `-8`), assigned in fixed order. Colour follows the\n * series, not its position, so hiding one never repaints the others.\n */\n color?: string;\n}\n\nexport interface ChartBaseProps<Row> {\n data: Row[];\n /** Field used for the category / x axis. */\n x: keyof Row & string;\n /** One or more series (up to 8; fold the rest into \"Other\"). */\n series: ChartSeries<Row>[];\n /** Title shown above the chart; also its accessible name. */\n title?: React.ReactNode;\n /** Accessible name when there is no visible title. */\n 'aria-label'?: string;\n /** One-line summary for screen readers, e.g. \"Revenue rose 40% in Q3\". */\n description?: string;\n /** Height in px. Width follows the container. Default 280. */\n height?: number;\n /** Intl options for values, e.g. `{ style: 'currency', currency: 'INR', notation: 'compact' }`. */\n valueFormat?: Intl.NumberFormatOptions;\n /** Format x values for axis, tooltip and table. Default: dates by locale, others as text. */\n formatX?: (value: unknown) => string;\n /** Show the legend (default: when there are 2+ series). */\n legend?: boolean;\n /** Show a \"Data table\" toggle under the chart. Default `true`. */\n tableView?: boolean;\n className?: string;\n classNames?: ClassNames<'root' | 'title' | 'legend' | 'plot' | 'tooltip' | 'table'>;\n}\n\n/* ---------------------------------------------------------------- scales */\n\n/** Rounded ticks covering [min, max]: 0, 250, 500… or 0, 0.2, 0.4… */\nexport function niceTicks(min: number, max: number, count = 5): number[] {\n if (min === max) max = min + 1;\n const span = max - min;\n const raw = span / count;\n const mag = 10 ** Math.floor(Math.log10(raw));\n const step = [1, 2, 2.5, 5, 10].map((m) => m * mag).find((s) => span / s <= count) ?? 10 * mag;\n const start = Math.floor(min / step) * step;\n const end = Math.ceil(max / step) * step;\n const ticks: number[] = [];\n for (let v = start; v <= end + step / 2; v += step) ticks.push(Number(v.toFixed(10)));\n return ticks;\n}\n\nexport const linear = (d0: number, d1: number, r0: number, r1: number) => (v: number) => (d1 === d0 ? r0 : r0 + ((v - d0) / (d1 - d0)) * (r1 - r0));\n\n/* ------------------------------------------------------------------ size */\n\n/** Width of the container, kept up to date. Starts at 600 for server rendering. */\nexport function useWidth<T extends HTMLElement>() {\n const ref = useRef<T>(null);\n const [width, setWidth] = useState(600);\n useEffect(() => {\n const el = ref.current;\n if (!el || typeof ResizeObserver === 'undefined') return;\n const ro = new ResizeObserver(([entry]) => setWidth(Math.max(120, Math.round(entry.contentRect.width))));\n ro.observe(el);\n return () => ro.disconnect();\n }, []);\n return [ref, width] as const;\n}\n\n/* ------------------------------------------------------------ formatting */\n\nexport function useFormatters<Row>(props: Pick<ChartBaseProps<Row>, 'valueFormat' | 'formatX'>) {\n const { locale } = useLocale();\n return useMemo(() => {\n const num = new Intl.NumberFormat(locale, props.valueFormat);\n const axisNum = new Intl.NumberFormat(locale, { notation: 'compact', maximumFractionDigits: 1, ...props.valueFormat });\n const date = new Intl.DateTimeFormat(locale, { day: 'numeric', month: 'short' });\n const fx = props.formatX ?? ((v: unknown) => (v instanceof Date ? date.format(v) : String(v ?? '')));\n return { value: (v: number) => num.format(v), axis: (v: number) => axisNum.format(v), x: fx };\n }, [locale, props.valueFormat, props.formatX]);\n}\n\n/** Series colours in fixed palette order; a series keeps its colour wherever it appears. */\nexport const seriesColor = <Row,>(series: ChartSeries<Row>[], i: number) => series[i].color ?? `var(--spark-chart-${(i % 8) + 1})`;\n\n/* ----------------------------------------------------------------- frame */\n\nexport interface FrameProps<Row> extends ChartBaseProps<Row> {\n kind: string;\n /** Series hidden via the legend. */\n hidden: Set<string>;\n onToggle: (key: string) => void;\n tooltip: React.ReactNode;\n tooltipPos: { x: number; y: number } | null;\n children: (width: number) => React.ReactNode;\n /** Rows/series for the table view. */\n tableColumns?: Array<{ key: string; label: string }>;\n}\n\n/**\n * Shared chart shell: title, legend (click to hide a series), responsive\n * plot, a tooltip layer and an accessible data-table view. Every chart\n * type renders inside it.\n */\nexport function ChartFrame<Row>({\n kind,\n data,\n x,\n series,\n title,\n 'aria-label': ariaLabel,\n description,\n legend,\n tableView = true,\n valueFormat,\n formatX,\n className,\n classNames,\n hidden,\n onToggle,\n tooltip,\n tooltipPos,\n children,\n tableColumns,\n}: FrameProps<Row>) {\n const [ref, width] = useWidth<HTMLDivElement>();\n const titleId = useId();\n const f = useFormatters<Row>({ valueFormat, formatX });\n const m = useMessages();\n const showLegend = legend ?? series.length > 1;\n const cols = tableColumns ?? series.map((s) => ({ key: s.key, label: s.label }));\n return (\n <figure className={slot('sp-chart', classNames, 'root', className)} data-kind={kind} aria-labelledby={title ? titleId : undefined} aria-label={title ? undefined : ariaLabel}>\n {title && (\n <figcaption id={titleId} className={slot('sp-chart__title', classNames, 'title')}>\n {title}\n </figcaption>\n )}\n {showLegend && (\n <ul className={slot('sp-chart__legend', classNames, 'legend')} aria-label={m.series}>\n {series.map((s, i) => (\n <li key={s.key}>\n <button type=\"button\" className=\"sp-chart__key\" aria-pressed={!hidden.has(s.key)} onClick={() => onToggle(s.key)}>\n <span className=\"sp-chart__swatch\" style={{ background: seriesColor(series, i) }} aria-hidden=\"true\" />\n {s.label}\n </button>\n </li>\n ))}\n </ul>\n )}\n <div ref={ref} className={slot('sp-chart__plot', classNames, 'plot')}>\n {description && <p className=\"sp-visually-hidden\">{description}</p>}\n {children(width)}\n {tooltip && tooltipPos && (\n <div\n className={slot('sp-chart__tooltip', classNames, 'tooltip')}\n role=\"status\"\n style={{ left: tooltipPos.x, top: tooltipPos.y, transform: `translate(${tooltipPos.x > width / 2 ? 'calc(-100% - 12px)' : '12px'}, -50%)` }}\n >\n {tooltip}\n </div>\n )}\n </div>\n {tableView && (\n <details className={slot('sp-chart__table', classNames, 'table')}>\n <summary>{m.dataTable}</summary>\n <div className=\"sp-chart__table-scroll\">\n <table>\n <thead>\n <tr>\n <th scope=\"col\">{String(x)}</th>\n {cols.map((c) => (\n <th key={c.key} scope=\"col\">\n {c.label}\n </th>\n ))}\n </tr>\n </thead>\n <tbody>\n {data.map((row, i) => (\n <tr key={i}>\n <th scope=\"row\">{f.x((row as Record<string, unknown>)[x])}</th>\n {cols.map((c) => {\n const v = (row as Record<string, unknown>)[c.key];\n return <td key={c.key}>{typeof v === 'number' ? f.value(v) : String(v ?? '')}</td>;\n })}\n </tr>\n ))}\n </tbody>\n </table>\n </div>\n </details>\n )}\n </figure>\n );\n}\n\n/** Legend toggling: hidden series keep their colour slot. */\nexport function useHiddenSeries() {\n const [hidden, setHidden] = useState<Set<string>>(new Set());\n const toggle = (key: string) =>\n setHidden((prev) => {\n const next = new Set(prev);\n next.has(key) ? next.delete(key) : next.add(key);\n return next;\n });\n return [hidden, toggle] as const;\n}\n\n/** Tooltip body: heading plus a row per series with its colour key. */\nexport function TooltipBody({ heading, rows }: { heading: string; rows: Array<{ label: string; value: string; color: string }> }) {\n return (\n <>\n <div className=\"sp-chart__tooltip-heading\">{heading}</div>\n {rows.map((r) => (\n <div key={r.label} className=\"sp-chart__tooltip-row\">\n <span className=\"sp-chart__swatch\" style={{ background: r.color }} aria-hidden=\"true\" />\n <span className=\"sp-chart__tooltip-label\">{r.label}</span>\n <span className=\"sp-chart__tooltip-value\">{r.value}</span>\n </div>\n ))}\n </>\n );\n}\n\nexport const MARGIN = { top: 12, right: 16, bottom: 28, left: 52 };\n"
32
+ },
33
+ {
34
+ "path": "components/spark-ui/Charts/index.ts",
35
+ "type": "registry:ui",
36
+ "target": "components/spark-ui/Charts/index.ts",
37
+ "content": "export { LineChart, BarChart } from './CartesianChart';\nexport type { LineChartProps, BarChartProps } from './CartesianChart';\nexport { DonutChart, Sparkline } from './DonutChart';\nexport type { DonutChartProps, DonutSlice, SparklineProps } from './DonutChart';\nexport { niceTicks } from './core';\nexport type { ChartSeries, ChartBaseProps } from './core';\n"
38
+ }
39
+ ]
40
+ }
@@ -0,0 +1,27 @@
1
+ {
2
+ "$schema": "https://ui.shadcn.com/schema/registry-item.json",
3
+ "name": "checkbox",
4
+ "type": "registry:ui",
5
+ "title": "Checkbox",
6
+ "description": "A checkbox that closes a circuit.",
7
+ "dependencies": [],
8
+ "registryDependencies": [
9
+ "@sparkwire/styles",
10
+ "@sparkwire/textfield",
11
+ "@sparkwire/utils"
12
+ ],
13
+ "files": [
14
+ {
15
+ "path": "components/spark-ui/Checkbox/Checkbox.tsx",
16
+ "type": "registry:ui",
17
+ "target": "components/spark-ui/Checkbox/Checkbox.tsx",
18
+ "content": "import React, { forwardRef, useEffect, useId, useRef } from 'react';\nimport { haptic } from '../internal/energy';\nimport { Tone } from '../internal/tone';\nimport { cx } from '../internal/cx';\nimport { useForkRef } from '../Textfield/useForkRef';\nimport { useDefaults, slot, ClassNames } from '../internal/defaults';\n\nexport interface CheckboxProps extends Omit<React.InputHTMLAttributes<HTMLInputElement>, 'size' | 'type'> {\n /** Text next to the box. */\n label?: React.ReactNode;\n /** Shows a dash: some, but not all, of a group is selected. */\n indeterminate?: boolean;\n /** Colour when checked. Default `brand`. */\n color?: Tone;\n /** Default `medium`. */\n size?: 'small' | 'medium' | 'large';\n /** Help or error text under the label. */\n helperText?: React.ReactNode;\n /** Marks the checkbox invalid and colours it with the error tone. */\n error?: boolean;\n /** Extra classes for each part: root, box, label, helper. */\n classNames?: ClassNames<'root' | 'box' | 'label' | 'helper'>;\n}\n\n/**\n * Checkbox: a terminal. Checking it powers the terminal: it fills with current\n * and the tick is drawn in. Built on a native checkbox, so forms and keyboards work.\n *\n * Style hooks: `.sp-checkbox`, `__box`, `__label`, `__helper`; the native input\n * drives `:checked`, `:indeterminate` and `:disabled`.\n */\nexport const Checkbox = forwardRef<HTMLInputElement, CheckboxProps>(function Checkbox(inProps, ref) {\n const { label, indeterminate = false, color = 'brand', size = 'medium', helperText, error, disabled, id, className, classNames, ...rest } = useDefaults('Checkbox', inProps);\n const innerRef = useRef<HTMLInputElement>(null);\n const handleRef = useForkRef(ref, innerRef);\n const autoId = useId();\n const inputId = id ?? autoId;\n const helperId = `${inputId}-helper`;\n\n useEffect(() => {\n if (innerRef.current) innerRef.current.indeterminate = indeterminate;\n }, [indeterminate]);\n\n return (\n <div\n className={slot('sp-checkbox', classNames, 'root', className)}\n data-tone={error ? 'error' : color}\n data-size={size}\n data-invalid={error || undefined}\n data-disabled={disabled || undefined}\n >\n <label htmlFor={inputId} className=\"sp-checkbox__row\">\n <input\n onChangeCapture={(e) => haptic('toggle', e.currentTarget)}\n ref={handleRef}\n id={inputId}\n type=\"checkbox\"\n disabled={disabled}\n aria-invalid={error || undefined}\n aria-describedby={helperText ? helperId : undefined}\n className=\"sp-checkbox__input\"\n {...rest}\n />\n <span className={slot('sp-checkbox__box', classNames, 'box')} aria-hidden=\"true\">\n <svg className=\"sp-checkbox__tick\" viewBox=\"0 0 14 14\" fill=\"none\">\n <path d=\"M2.5 7.5l3 3 6-7\" strokeWidth=\"2.4\" strokeLinecap=\"round\" strokeLinejoin=\"round\" strokeDasharray=\"18\" />\n </svg>\n <svg className=\"sp-checkbox__dash\" viewBox=\"0 0 14 14\" fill=\"none\">\n <path d=\"M3 7h8\" strokeWidth=\"2.4\" strokeLinecap=\"round\" />\n </svg>\n </span>\n {label && <span className={slot('sp-checkbox__label', classNames, 'label')}>{label}</span>}\n </label>\n {helperText && (\n <span id={helperId} className={slot('sp-checkbox__helper', classNames, 'helper')}>\n {helperText}\n </span>\n )}\n </div>\n );\n});\n\nCheckbox.displayName = 'Checkbox';\nexport default Checkbox;\n"
19
+ },
20
+ {
21
+ "path": "components/spark-ui/Checkbox/index.ts",
22
+ "type": "registry:ui",
23
+ "target": "components/spark-ui/Checkbox/index.ts",
24
+ "content": "export * from './Checkbox';\n"
25
+ }
26
+ ]
27
+ }
@@ -0,0 +1,30 @@
1
+ {
2
+ "$schema": "https://ui.shadcn.com/schema/registry-item.json",
3
+ "name": "combobox",
4
+ "type": "registry:ui",
5
+ "title": "Combobox",
6
+ "description": "Type to search, then pick.",
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/Combobox/Combobox.tsx",
19
+ "type": "registry:ui",
20
+ "target": "components/spark-ui/Combobox/Combobox.tsx",
21
+ "content": "import React, { useRef } from 'react';\nimport { useMessages } from '../internal/messages';\nimport { useButton, useComboBox, useFilter } from 'react-aria';\nimport { useComboBoxState } from 'react-stately';\nimport { InputBase } from '../base/InputBase';\nimport { Popover } from '../base/Popover';\nimport { ListBox, ListItems, ListOption, findOption, isGroup, renderListItems } from '../base/ListBox';\nimport { useDefaults, slot, ClassNames } from '../internal/defaults';\n\nexport type ComboboxOption<V extends string | number = string | number> = ListOption<V>;\nexport type ComboboxOptionGroup<V extends string | number = string | number> = { label: string; options: ComboboxOption<V>[] };\n\nexport interface ComboboxProps<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. */\n options: Array<ComboboxOption<V> | ComboboxOptionGroup<V>>;\n /** Controlled selected value (`null` for none). */\n value?: V | null;\n /** Initial selected value when uncontrolled. */\n defaultValue?: V;\n /** Called with the chosen option's value, or `null` when cleared. */\n onChange?: (value: V | null) => void;\n /** Controlled text in the input. */\n inputValue?: string;\n /** Initial text in the input when uncontrolled. */\n defaultInputValue?: string;\n /** Called as the user types; use it to fetch options from a server (with `filter={false}`). */\n onInputChange?: (text: string) => void;\n /**\n * How options are matched to the typed text: `contains` (default),\n * `startsWith`, or `false` when you filter yourself (e.g. server search).\n * Matching ignores case and accents.\n */\n filter?: 'contains' | 'startsWith' | false;\n /** Keep typed text that matches no option (free entry, e.g. tags or a new city). */\n allowsCustomValue?: boolean;\n /** When the list opens: on typing (`input`, default), on focus, or only with the button or arrow keys (`manual`). */\n menuTrigger?: 'input' | 'focus' | 'manual';\n /** Show a loading indicator, e.g. while fetching options. */\n loading?: boolean;\n /** Show a clear button when there is text. Default `true`. */\n clearable?: boolean;\n /** Placeholder text in the input. */\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. Submits the selected value (or the typed text with `allowsCustomValue`). */\n name?: string;\n /** Height 36, 46 or 54px. Default `medium`. */\n size?: 'small' | 'medium' | 'large';\n /** Icon at the start of the field, e.g. a search icon. */\n startIcon?: React.ReactNode;\n /** Shown when nothing matches. Default \"No results\". */\n emptyState?: React.ReactNode;\n /** Text shown in the list while `loading`. Default \"Loading…\". */\n loadingText?: React.ReactNode;\n className?: string;\n /** Extra classes for each part: root, label, field, input, popover, option, helper. */\n classNames?: ClassNames<'root' | 'label' | 'field' | 'input' | 'popover' | 'option' | 'helper'>;\n}\n\n/**\n * Combobox: type to search a list, then pick. The field charges as you type\n * and the matching option lights up. Built on the InputBase, Popover and\n * ListBox base components with React Aria: filtering that ignores case and\n * accents, arrow keys, Enter to pick, Escape to close or clear, groups,\n * free entry, server-side search, and screen-reader announcements of\n * result counts.\n *\n * Style hooks: `.sp-combobox[data-open][data-invalid][data-disabled][data-loading]`,\n * `__label`, `__helper`, `__spinner`; the field is `.sp-input-base`, the\n * list `.sp-popover`, `.sp-listbox` and `.sp-list-item`.\n */\nexport function Combobox<V extends string | number = string | number>(inProps: ComboboxProps<V>) {\n const m = useMessages();\n const {\n label,\n 'aria-label': ariaLabel,\n options,\n value,\n defaultValue,\n onChange,\n inputValue,\n defaultInputValue,\n onInputChange,\n filter = 'contains',\n allowsCustomValue,\n menuTrigger = 'input',\n loading = false,\n clearable = true,\n placeholder,\n helperText,\n error,\n required,\n disabled,\n name,\n size = 'medium',\n startIcon,\n emptyState = m.noResults,\n loadingText = `${m.loading}…`,\n className,\n classNames,\n } = useDefaults('Combobox', inProps);\n\n const { contains, startsWith } = useFilter({ sensitivity: 'base' });\n const items = options as ListItems<ListOption<V>>;\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 = items.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 placeholder,\n children: renderListItems(items),\n selectedKey: value === undefined ? undefined : value === null ? null : String(value),\n defaultSelectedKey: defaultValue === undefined ? undefined : String(defaultValue),\n onSelectionChange: (key: React.Key | null) => onChange?.(findOption(items, key)?.value ?? null),\n inputValue,\n defaultInputValue,\n onInputChange,\n defaultFilter: filter === false ? undefined : filter === 'startsWith' ? startsWith : contains,\n allowsCustomValue,\n allowsEmptyCollection: true,\n menuTrigger,\n disabledKeys,\n isDisabled: disabled,\n isRequired: required,\n isInvalid: invalid,\n description: help ? 'description' : undefined,\n errorMessage: invalid && message ? 'error' : undefined,\n };\n const state = useComboBoxState(ariaProps);\n\n const inputRef = useRef<HTMLInputElement>(null);\n const fieldRef = useRef<HTMLDivElement>(null);\n const buttonRef = useRef<HTMLButtonElement>(null);\n const listBoxRef = useRef<HTMLUListElement>(null);\n const popoverRef = useRef<HTMLDivElement>(null);\n const { buttonProps, inputProps, listBoxProps, labelProps, descriptionProps, errorMessageProps } = useComboBox(\n { ...ariaProps, inputRef, buttonRef, listBoxRef, popoverRef },\n state,\n );\n const { buttonProps: chevronProps } = useButton(buttonProps, buttonRef);\n\n const submitted = allowsCustomValue ? state.inputValue : state.selectedKey == null ? '' : String(state.selectedKey);\n const showClear = clearable && !disabled && state.inputValue !== '';\n\n return (\n <div\n className={slot('sp-combobox', classNames, 'root', className)}\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-loading={loading || undefined}\n >\n {label && (\n <label {...labelProps} className={slot('sp-combobox__label', classNames, 'label')}>\n {label}\n {required && (\n <span className=\"sp-field__required\" aria-hidden=\"true\">\n {' '}*\n </span>\n )}\n </label>\n )}\n <InputBase\n {...(inputProps as React.InputHTMLAttributes<HTMLInputElement>)}\n ref={inputRef}\n rootRef={fieldRef}\n size={size}\n error={invalid}\n disabled={disabled}\n rootProps={{ 'data-active': state.isOpen || undefined }}\n classNames={{ root: slot('sp-combobox__field', classNames, 'field'), input: classNames?.input }}\n startAdornment={startIcon}\n endAdornment={\n <>\n {loading && <span className=\"sp-combobox__spinner\" aria-hidden=\"true\" />}\n {showClear && (\n <button\n type=\"button\"\n tabIndex={-1}\n aria-label={m.clear}\n className=\"sp-field-button\"\n onClick={() => {\n state.setSelectedKey(null);\n state.setInputValue('');\n inputRef.current?.focus();\n }}\n >\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 {...chevronProps} ref={buttonRef} className=\"sp-field-button\" data-chevron>\n <svg 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 </>\n }\n />\n {name && <input type=\"hidden\" name={name} value={submitted} />}\n {invalid && message ? (\n <p {...errorMessageProps} className={slot('sp-combobox__helper', classNames, 'helper')}>\n {message}\n </p>\n ) : (\n help && (\n <p {...descriptionProps} className={slot('sp-combobox__helper', classNames, 'helper')}>\n {help}\n </p>\n )\n )}\n {state.isOpen && (\n <Popover\n ref={popoverRef}\n state={state}\n triggerRef={fieldRef}\n isNonModal\n matchTriggerWidth\n className={slot('sp-combobox__popover', classNames, 'popover')}\n >\n <ListBox\n {...listBoxProps}\n listBoxRef={listBoxRef}\n state={state}\n optionClassName={classNames?.option}\n emptyState={loading ? loadingText : emptyState}\n />\n </Popover>\n )}\n </div>\n );\n}\n\nexport default Combobox;\n"
22
+ },
23
+ {
24
+ "path": "components/spark-ui/Combobox/index.ts",
25
+ "type": "registry:ui",
26
+ "target": "components/spark-ui/Combobox/index.ts",
27
+ "content": "export { Combobox } from './Combobox';\nexport type { ComboboxProps, ComboboxOption, ComboboxOptionGroup } from './Combobox';\n"
28
+ }
29
+ ]
30
+ }
@@ -0,0 +1,29 @@
1
+ {
2
+ "$schema": "https://ui.shadcn.com/schema/registry-item.json",
3
+ "name": "command-palette",
4
+ "type": "registry:ui",
5
+ "title": "CommandPalette",
6
+ "description": "A ⌘K launcher: search commands and pages, run with the keyboard.",
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/CommandPalette/CommandPalette.tsx",
18
+ "type": "registry:ui",
19
+ "target": "components/spark-ui/CommandPalette/CommandPalette.tsx",
20
+ "content": "import React, { useEffect, useId, useMemo, useRef, useState } from 'react';\nimport { useMessages } from '../internal/messages';\nimport { useDialog } from 'react-aria';\nimport { Overlay } from '../base/Overlay';\nimport { InputBase } from '../base/InputBase';\nimport { ListItemContent } from '../base/ListBox';\nimport { useDefaults, slot, ClassNames } from '../internal/defaults';\n\nexport interface Command {\n /** Unique id. */\n id: string;\n label: string;\n /** Extra words that should find this command, e.g. ['preferences'] for \"Settings\". */\n keywords?: string[];\n icon?: React.ReactNode;\n /** Secondary line under the label. */\n description?: React.ReactNode;\n /** Shortcut hint shown at the end, e.g. \"⌘S\". Display only. */\n shortcut?: string;\n disabled?: boolean;\n /** Run when chosen. */\n onSelect?: () => void;\n /** Navigate when chosen (rendered as a link). */\n href?: string;\n}\n\nexport interface CommandGroup {\n /** Heading for the group. */\n heading: string;\n items: Command[];\n}\n\nexport interface CommandPaletteProps {\n /** Commands, or groups of commands with a heading. */\n items: Array<Command | CommandGroup>;\n /** Controlled open state. */\n open?: boolean;\n defaultOpen?: boolean;\n onOpenChange?: (open: boolean) => void;\n /** Keyboard shortcut that opens and closes the palette. Default `mod+k` (⌘K on Mac, Ctrl+K elsewhere). `false` to turn off. */\n hotkey?: string | false;\n /** Called with the search text, e.g. to fetch results from a server (with `filter={false}`). */\n onSearchChange?: (search: string) => void;\n /** Match commands to the search yourself. Default `true` (case- and accent-insensitive, best matches first). */\n filter?: boolean;\n /** Called with the chosen command, after its own `onSelect`. */\n onSelect?: (command: Command) => void;\n /** Close after a command runs. Default `true`. */\n closeOnSelect?: boolean;\n placeholder?: string;\n /** Shown when nothing matches. Default \"No results\". */\n emptyState?: React.ReactNode;\n /** Show a loading line, e.g. while fetching. */\n loading?: boolean;\n /** Accessible name for the dialog. Default \"Command palette\". */\n 'aria-label'?: string;\n /** Hide the keyboard hints at the bottom. */\n hideFooter?: boolean;\n className?: string;\n /** Extra classes for each part: panel, input, list, group, item, footer. */\n classNames?: ClassNames<'panel' | 'input' | 'list' | 'group' | 'item' | 'footer'>;\n}\n\nconst isGroup = (x: Command | CommandGroup): x is CommandGroup => Array.isArray((x as CommandGroup).items);\nconst fold = (s: string) => s.normalize('NFD').replace(/[̀-ͯ]/g, '').toLowerCase();\n\n/** 3 = label starts with the search, 2 = a word starts with it, 1 = contains it (label or keywords), 0 = no match. */\nfunction score(cmd: Command, q: string) {\n if (!q) return 1;\n const label = fold(cmd.label);\n if (label.startsWith(q)) return 3;\n if (label.split(/[\\s\\-_/]+/).some((w) => w.startsWith(q))) return 2;\n if (label.includes(q) || cmd.keywords?.some((k) => fold(k).includes(q))) return 1;\n return 0;\n}\n\n/** Matches \"mod+k\", \"ctrl+shift+p\", \"/\" against a key event. `mod` is ⌘ on Mac, Ctrl elsewhere. */\nfunction matchesHotkey(e: KeyboardEvent, hotkey: string) {\n const parts = hotkey.toLowerCase().split('+');\n const key = parts.pop();\n const mac = typeof navigator !== 'undefined' && /mac|iphone|ipad/i.test(navigator.platform || navigator.userAgent);\n const want = { meta: parts.includes('meta') || (mac && parts.includes('mod')), ctrl: parts.includes('ctrl') || (!mac && parts.includes('mod')), shift: parts.includes('shift'), alt: parts.includes('alt') };\n return e.key.toLowerCase() === key && e.metaKey === want.meta && e.ctrlKey === want.ctrl && e.shiftKey === want.shift && e.altKey === want.alt;\n}\n\n/**\n * CommandPalette: a ⌘K launcher. Type to find a command or page; arrows move\n * the lit node, Enter runs it, Escape closes. Focus stays in the search box\n * (ARIA combobox with an active option), the dialog traps focus and returns\n * it when closed. Groups, keywords, icons, shortcuts, links and async\n * results. Built on the Overlay and InputBase base components and the\n * shared list-item look.\n *\n * Style hooks: `.sp-command`, `__panel`, `__input`, `__list`, `__group`,\n * `__heading`, `.sp-list-item[data-focused]`, `__empty`, `__footer`.\n */\nexport function CommandPalette(inProps: CommandPaletteProps) {\n const props = useDefaults('CommandPalette', inProps);\n const { open, defaultOpen = false, onOpenChange, hotkey = 'mod+k' } = props;\n const [inner, setInner] = useState(defaultOpen);\n const isOpen = open ?? inner;\n const setOpen = (v: boolean) => {\n if (open === undefined) setInner(v);\n onOpenChange?.(v);\n };\n const openRef = useRef(isOpen);\n openRef.current = isOpen;\n\n useEffect(() => {\n if (!hotkey) return;\n const onKey = (e: KeyboardEvent) => {\n if (matchesHotkey(e, hotkey)) {\n e.preventDefault();\n setOpen(!openRef.current);\n }\n };\n window.addEventListener('keydown', onKey);\n return () => window.removeEventListener('keydown', onKey);\n // setOpen is recreated each render; the ref keeps the latest state.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [hotkey, open]);\n\n return (\n <Overlay open={isOpen} onClose={() => setOpen(false)} className={slot('sp-command', undefined, 'root', props.className)} backdropClassName=\"sp-command__backdrop\">\n {({ panelProps, panelRef }) => <Panel {...props} panelProps={panelProps} panelRef={panelRef} close={() => setOpen(false)} />}\n </Overlay>\n );\n}\n\nfunction Panel({\n items,\n onSearchChange,\n filter = true,\n onSelect,\n closeOnSelect = true,\n placeholder: placeholderProp,\n emptyState: emptyStateProp,\n loading,\n 'aria-label': ariaLabelProp,\n hideFooter,\n classNames,\n panelProps,\n panelRef,\n close,\n}: CommandPaletteProps & { panelProps: React.HTMLAttributes<HTMLElement>; panelRef: React.RefObject<HTMLDivElement>; close: () => void }) {\n const m = useMessages();\n const placeholder = placeholderProp ?? m.commandPlaceholder;\n const emptyState = emptyStateProp ?? m.noResults;\n const ariaLabel = ariaLabelProp ?? m.commandPalette;\n const { dialogProps } = useDialog({ 'aria-label': ariaLabel }, panelRef);\n const [search, setSearch] = useState('');\n const [active, setActive] = useState(0);\n const listId = useId();\n const listRef = useRef<HTMLDivElement>(null);\n\n // Filter and rank within each group; groups keep their order.\n const groups = useMemo(() => {\n const q = fold(search.trim());\n const raw = items.map((x) => (isGroup(x) ? x : { heading: '', items: [x] }));\n // Merge consecutive loose commands into one heading-less group.\n const merged: CommandGroup[] = [];\n for (const g of raw) {\n const last = merged[merged.length - 1];\n if (!g.heading && last && !last.heading) last.items = [...last.items, ...g.items];\n else merged.push({ heading: g.heading, items: [...g.items] });\n }\n return merged\n .map((g) => ({\n heading: g.heading,\n items: filter\n ? g.items\n .map((c, i) => ({ c, s: score(c, q), i }))\n .filter((x) => x.s > 0)\n .sort((a, b) => b.s - a.s || a.i - b.i)\n .map((x) => x.c)\n : g.items,\n }))\n .filter((g) => g.items.length);\n }, [items, search, filter]);\n\n const flat = groups.flatMap((g) => g.items);\n const enabled = flat.map((c, i) => (c.disabled ? -1 : i)).filter((i) => i >= 0);\n const current = flat[active];\n const optionId = (i: number) => `${listId}-opt-${i}`;\n\n useEffect(() => setActive(enabled[0] ?? 0), [search, items]); // eslint-disable-line react-hooks/exhaustive-deps\n useEffect(() => {\n listRef.current?.querySelector(`#${CSS.escape(optionId(active))}`)?.scrollIntoView?.({ block: 'nearest' });\n }, [active]); // eslint-disable-line react-hooks/exhaustive-deps\n\n const run = (cmd?: Command) => {\n if (!cmd || cmd.disabled) return;\n cmd.onSelect?.();\n onSelect?.(cmd);\n if (cmd.href) window.location.assign(cmd.href);\n if (closeOnSelect) close();\n };\n\n const move = (delta: number) => {\n if (!enabled.length) return;\n const pos = enabled.indexOf(active);\n setActive(enabled[(pos + delta + enabled.length) % enabled.length]);\n };\n\n const onKeyDown = (e: React.KeyboardEvent) => {\n if (e.key === 'ArrowDown') move(1);\n else if (e.key === 'ArrowUp') move(-1);\n else if (e.key === 'Home' && e.ctrlKey) setActive(enabled[0] ?? 0);\n else if (e.key === 'End' && e.ctrlKey) setActive(enabled[enabled.length - 1] ?? 0);\n else if (e.key === 'PageDown') move(5);\n else if (e.key === 'PageUp') move(-5);\n else if (e.key === 'Enter') run(current);\n else return;\n e.preventDefault();\n };\n\n let index = -1;\n return (\n <div {...panelProps} {...dialogProps} ref={panelRef} className={slot('sp-command__panel', classNames, 'panel')}>\n <div aria-hidden=\"true\" className=\"sp-command__current sp-current\" data-live={search ? true : undefined} />\n <InputBase\n role=\"combobox\"\n aria-label={m.searchCommands}\n aria-expanded={flat.length > 0}\n aria-controls={listId}\n aria-autocomplete=\"list\"\n aria-activedescendant={current && !current.disabled ? optionId(active) : undefined}\n autoFocus\n variant=\"standard\"\n size=\"large\"\n placeholder={placeholder}\n value={search}\n onChange={(e) => {\n setSearch(e.target.value);\n onSearchChange?.(e.target.value);\n }}\n onKeyDown={onKeyDown}\n classNames={{ root: slot('sp-command__input', classNames, 'input') }}\n startAdornment={\n <svg width=\"18\" height=\"18\" 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 endAdornment={<kbd className=\"sp-command__esc\">esc</kbd>}\n />\n <div ref={listRef} id={listId} role=\"listbox\" aria-label={m.commands} className={slot('sp-command__list', classNames, 'list')}>\n {loading && (\n <div className=\"sp-command__status\" role=\"status\">\n <span className=\"sp-combobox__spinner\" aria-hidden=\"true\" /> Loading…\n </div>\n )}\n {!loading && flat.length === 0 && (\n <div className=\"sp-command__status sp-command__empty\" role=\"status\">\n {emptyState}\n </div>\n )}\n {groups.map((g, gi) => (\n <div key={`${g.heading}-${gi}`} role=\"group\" aria-label={g.heading || undefined} className={slot('sp-command__group', classNames, 'group')}>\n {g.heading && (\n <div className=\"sp-command__heading sp-list-section__heading\" aria-hidden=\"true\">\n {g.heading}\n </div>\n )}\n {g.items.map((cmd) => {\n index += 1;\n const i = index;\n const Tag = (cmd.href ? 'a' : 'div') as 'div';\n return (\n <Tag\n key={cmd.id}\n id={optionId(i)}\n role=\"option\"\n aria-selected={i === active}\n aria-disabled={cmd.disabled || undefined}\n {...(cmd.href ? { href: cmd.href, tabIndex: -1 } : {})}\n className={slot('sp-list-item sp-command__item', classNames, 'item')}\n data-focused={i === active || undefined}\n data-disabled={cmd.disabled || undefined}\n onMouseMove={() => !cmd.disabled && i !== active && setActive(i)}\n onMouseDown={(e) => e.preventDefault()}\n onClick={(e) => {\n if (cmd.href) e.preventDefault();\n run(cmd);\n }}\n >\n <ListItemContent icon={cmd.icon} label={cmd.label} description={cmd.description} end={cmd.shortcut ? <kbd>{cmd.shortcut}</kbd> : undefined} />\n </Tag>\n );\n })}\n </div>\n ))}\n </div>\n {!hideFooter && (\n <div className={slot('sp-command__footer', classNames, 'footer')} aria-hidden=\"true\">\n <span><kbd>↑</kbd><kbd>↓</kbd> move</span>\n <span><kbd>↵</kbd> run</span>\n <span><kbd>esc</kbd> close</span>\n </div>\n )}\n <div className=\"sp-visually-hidden\" role=\"status\" aria-live=\"polite\">\n {search ? `${flat.length} result${flat.length === 1 ? '' : 's'}` : ''}\n </div>\n </div>\n );\n}\n\nexport default CommandPalette;\n"
21
+ },
22
+ {
23
+ "path": "components/spark-ui/CommandPalette/index.ts",
24
+ "type": "registry:ui",
25
+ "target": "components/spark-ui/CommandPalette/index.ts",
26
+ "content": "export { CommandPalette } from './CommandPalette';\nexport type { CommandPaletteProps, Command, CommandGroup } from './CommandPalette';\n"
27
+ }
28
+ ]
29
+ }