Skip to content

svelte-atoms/core

Repository files navigation

βš›οΈ @svelte-atoms/core

A modern, modular, and accessible Svelte 5 UI component library built with composability at its core.

@svelte-atoms/core is a comprehensive Svelte component library that provides fundamental building blocks ("atoms") for creating sophisticated, interactive design systems. Each component is designed with accessibility, type safety, and developer experience in mind. Built with Svelte 5 runes for optimal reactivity and performance.

npm version Ask DeepWiki license


✨ Features

🧱 Bond Architecture

Built around the concept of "Bonds" - self-contained, reusable state management classes that encapsulate component state and DOM interactions. Each component uses the Bond pattern for consistent, predictable behavior across complex interactions. Simple components like Button don't require the Bond pattern as they have minimal state management needs.

πŸ”— Context-Driven Communication

Components seamlessly communicate through Svelte's context API using standardized static methods (Bond.get() / Bond.set()) of the Bond class, enabling powerful parent-child relationships without prop drilling.

β™Ώ Accessibility First

Every component includes proper ARIA attributes, keyboard navigation, and focus management out of the box.

πŸ”§ Highly Extensible

Easily extend components with custom behaviors, animations, and styling while maintaining the core functionality.

🎯 Type Safety

Fully written in TypeScript with comprehensive type definitions for a robust development experience.

⚑ Reactive by Design

Leverages Svelte's fine-grained reactivity system for optimal performance and smooth user interactions.

🎨 Headless & Stylable

Components are headless by default, giving you complete control over styling while providing sensible defaults.

🧩 Composable

Build complex UIs by combining simple, reusable components. Each component is designed to work seamlessly with others through the Bond pattern and context API. Create sophisticated features like multi-level dropdowns, nested accordions, or custom form controls by composing atomic components together.


πŸ“¦ Available Components

Our comprehensive collection of UI components with implementation status:

Layout & Navigation

Component Description Status
Accordion Collapsible content sections βœ…
Breadcrumb Navigation hierarchy βœ…
Sidebar Collapsible side navigation βœ…
Tabs Tabbed interfaces βœ…
Tree Hierarchical data structures βœ…
Stepper Multi-step process indicator ❌
Pagination Page navigation controls ❌

Forms & Input

Component Description Status
Button Interactive buttons with variants βœ…
Checkbox Multi-select inputs βœ…
Combobox Searchable select inputs βœ…
Input Text input fields βœ…
Radio Single-select inputs βœ…
Slider Range input controls ❌
Switch Toggle controls ❌
Textarea Multi-line text inputs βœ…
Form Form validation and state management βœ…
DatePicker Date selection component βœ…
TimePicker Time selection component ❌
FileUpload File upload component ❌
ColorPicker Color selection component ❌
Rating Star rating component ❌

Data Display

Component Description Status
Avatar User profile images βœ…
Badge Status indicators βœ…
DataGrid Advanced data tables βœ…
Divider Content separators βœ…
Icon Scalable icons βœ…
Label Form labels βœ…
Link Navigation links βœ…
List Structured lists βœ…
Card Content containers βœ…
Table Simple data tables ❌
Chip Compact information display ❌
Progress Progress indicators ❌
Skeleton Loading placeholders ❌
Timeline Event timeline display ❌
Calendar Date display component βœ…
QRCode QR code generator βœ…

Overlays & Feedback

Component Description Status
Dialog Modal dialogs βœ…
Dropdown Contextual menus βœ…
Popover Contextual information βœ…
Toast Notification messages βœ…
Tooltip Contextual hints βœ…
ContextMenu Right-click menus βœ…
Drawer Slide-out panels βœ…
Alert Alert messages βœ…
Banner Full-width notifications ❌
Spotlight Feature highlighting ❌

Utilities & Layout

Component Description Status
Portal Declare a portal anywhere in DOM βœ…
Teleport Render content in a specific portal βœ…
Root Application root container βœ…
Layer Layer management utility βœ…
Collapsible Generic collapsible wrapper βœ…
Container Layout container βœ…
Scrollable Custom scrollbar component βœ…
Stack Flexible layout stacking component βœ…
Spacer Space management utility ❌
VirtualList Virtual scrolling list ❌

πŸ—οΈ Architecture

The library is organized into distinct layers for maximum maintainability and extensibility:

src/lib/
β”œβ”€β”€ components/          # 30+ Core UI components
β”œβ”€β”€ shared/         # Base classes (Bond, BondState) and utilities
β”œβ”€β”€ helpers/        # Helper functions and components
β”œβ”€β”€ attachments/    # DOM attachment utilities
β”œβ”€β”€ runes/          # Reactive utilities (Svelte 5 runes)
β”œβ”€β”€ types/          # TypeScript type definitions
└── utils/          # General utility functions

Bond Pattern

Each component follows a consistent Bond pattern:

  • Bond Class: Manages component state and DOM interactions
  • BondState Class: Holds reactive component state using Svelte 5 runes
  • Context Methods: Static CONTEXT_KEY, get(), and set() methods for component communication
  • Component Files: Svelte components that use the Bond for behavior
class MyComponentBond extends Bond<MyComponentBondState> {
	static CONTEXT_KEY = '@atoms/context/my-component';

	static get(): MyComponentBond | undefined {
		return getContext(MyComponentBond.CONTEXT_KEY);
	}

	static set(bond: MyComponentBond): MyComponentBond {
		return setContext(MyComponentBond.CONTEXT_KEY, bond);
	}
}

πŸš€ Quick Start

Installation

# npm
npm install @svelte-atoms/core

# yarn
yarn install @svelte-atoms/core

# pnpm
pnpm add @svelte-atoms/core

# bun
bun add @svelte-atoms/core

Basic Usage

<script lang="ts">
	import { Button, Dialog, Input } from '@svelte-atoms/core';

	let dialogOpen = $state(false);
	let inputValue = '';
</script>

<!-- Simple Button -->
<Button onclick={() => (dialogOpen = true)}>Open Dialog</Button>

<!-- Dialog with Input -->
<Dialog.Root bind:open={dialogOpen}>
	<Dialog.Content>
		<Dialog.Header>
			<Dialog.Title>Enter your name</Dialog.Title>
		</Dialog.Header>
		<Dialog.Body>
			<Input.Root>
				<Input.Value bind:value={inputValue} placeholder="Your name...">
			</Input.Root>
		</Dialog.Body>
		<Dialog.Footer>
			<Button.Root onclick={() => (dialogOpen = false)}>Cancel</Button.Root>
			<Button.Root variant="primary" onclick={() => (dialogOpen = false)}>Confirm</Button.Root>
		</Dialog.Footer>
	</Dialog.Content>
</Dialog.Root>

Advanced Usage with Bonds

For more control, you can use the Bond system directly:

<script lang="ts">
	import { DialogBond, DialogBondState } from '@svelte-atoms/core/dialog';

	const { open = false, disable = false } = $props();

	const bondProps = defineState(
		[
			defineProperty(
				'open',
				() => open,
				(v) => (open = v)
			),
			defineProperty('disable', () => disable)
		],
		{
			// Other props
		}
	);

	// Create dialog state
	const dialogState = new DialogBondState(() => bondProps);

	// Create dialog bond
	// Make available via context
	const dialogBond = new DialogBond(dialogState).share();
</script>

<div {...dialogBond.root()}>
	<button {...dialogBond.trigger()} onclick={() => dialogBond.state.toggle()}>
		Toggle Dialog
	</button>

	{#if open}
		<div {...dialogBond.overlay()}>
			<div {...dialogBond.content()}>
				<h2 {...dialogBond.title()}>Dialog Title</h2>
				<p>Dialog content goes here...</p>
				<button onclick={() => dialogBond.state.close()}>Close</button>
			</div>
		</div>
	{/if}
</div>

Advanced Usage With Composition

This example demonstrates the power of component composition by combining Dropdown, Input, and animation capabilities to create a searchable multi-select dropdown with smooth transitions:

<script lang="ts">
	import { Dropdown, Input, Root, filter } from '@svelte-atoms/core';
	import { flip } from 'svelte/animate';

	// Sample data
	let data = [
		{ id: 1, value: 'apple', text: 'Apple' },
		{ id: 2, value: 'banana', text: 'Banana' },
		{ id: 3, value: 'cherry', text: 'Cherry' },
		{ id: 4, value: 'date', text: 'Date' },
		{ id: 5, value: 'elderberry', text: 'Elderberry' }
	];

	let open = $state(false);
	// Filter items based on search query
	const dd = filter(
		() => data,
		(query, item) => item.text.toLowerCase().includes(query.toLowerCase())
	);
</script>

<Root class="items-center justify-center p-4">
	<!-- Multi-select dropdown with search functionality -->
	<Dropdown.Root
		bind:open
		multiple
		keys={data.map((item) => item.value)}
		onquerychange={(q) => (dd.query = q)}
	>
		{#snippet children({ dropdown })}
			<!-- Compose Dropdown.Trigger with Input.Root for a custom trigger -->
			<Dropdown.Trigger
				base={Input.Root}
				class="h-auto min-h-12 max-w-sm min-w-sm items-center gap-2 rounded-sm px-4 transition-colors duration-200"
				onclick={(ev) => {
					ev.preventDefault();

					dropdown.state.open();
				}}
			>
				<!-- Display selected values with animation -->
				{#each dropdown?.state?.selectedItems ?? [] as item (item.id)}
					<div animate:flip={{ duration: 200 }}>
						<ADropdown.Value value={item.value} class="text-foreground/80">
							{item.text}
						</ADropdown.Value>
					</div>
				{/each}

				<!-- Inline search input within the trigger -->
				<Dropdown.Query class="flex-1 px-1" placeholder="Search for fruits..." />
			</Dropdown.Trigger>

			<!-- Dropdown list with filtered items -->
			<Dropdown.List>
				{#each dd.current as item (item.id)}
					<div animate:flip={{ duration: 200 }}>
						<Dropdown.Item value={item.value}>{item.text}</Dropdown.Item>
					</div>
				{/each}
			</Dropdown.List>
		{/snippet}
	</Dropdown.Root>
</Root>

Key composition features demonstrated:

  • Component Fusion: Using base={Input.Root} to compose Dropdown.Trigger with Input styling and behavior
  • Snippet Patterns: Accessing internal state through snippets for custom rendering
  • Reactive Filtering: Combining search query state with reactive effects for real-time filtering
  • Smooth Animations: Using Svelte's flip animation for seamless list transitions
  • Multi-Select State: Managing complex selection state through the Bond pattern

Creating Custom Variants

@svelte-atoms/core provides a powerful variant system using defineVariants() that allows you to create type-safe, reusable component variations with support for compound variants, defaults, and bond state integration.

Basic Variant Definition

import { defineVariants, type VariantPropsType } from '@svelte-atoms/core/utils';

const buttonVariants = defineVariants({
	class: 'inline-flex items-center justify-center rounded-md font-medium transition-colors',
	variants: {
		variant: {
			primary: 'bg-blue-500 text-white hover:bg-blue-600',
			secondary: 'bg-gray-200 text-gray-900 hover:bg-gray-300',
			ghost: 'hover:bg-gray-100'
		},
		size: {
			sm: 'h-8 px-3 text-sm',
			md: 'h-10 px-4',
			lg: 'h-12 px-6 text-lg'
		}
	},
	compounds: [
		{
			variant: 'primary',
			size: 'lg',
			class: 'shadow-md font-semibold'
		}
	],
	defaults: {
		variant: 'primary',
		size: 'md'
	}
});

// Extract type-safe props
type ButtonVariantProps = VariantPropsType<typeof buttonVariants>;

Local vs Global Variants

Local Variants - Define variants directly in your component:

<script lang="ts">
	import { HtmlAtom } from '@svelte-atoms/core';
	import { defineVariants, type VariantPropsType } from '@svelte-atoms/core/utils';

	const buttonVariants = defineVariants({
		class: 'rounded-md font-medium',
		variants: {
			variant: {
				primary: 'bg-blue-500 text-white',
				secondary: 'bg-gray-500 text-white'
			},
			size: {
				sm: 'px-2 py-1 text-sm',
				md: 'px-4 py-2 text-base'
			}
		},
		defaults: {
			variant: 'primary',
			size: 'md'
		}
	});

	type ButtonProps = VariantPropsType<typeof buttonVariants> & {
		disabled?: boolean;
		class?: string;
	};

	let { variant, size, disabled = false, class: klass = '', ...props }: ButtonProps = $props();

	const variantProps = $derived(buttonVariants(null, { variant, size }));
</script>

<HtmlAtom
	as="button"
	variants={variantProps}
	{disabled}
	class={[variantProps.class, klass]}
	{...props}
>
	{@render children?.()}
</HtmlAtom>

Global Variants - Define variants in your theme/preset configuration:

// +layout.svelte or theme configuration
import { setPreset } from '@svelte-atoms/core/context';

setPreset({
	button: () => ({
		class: 'inline-flex items-center justify-center rounded-md font-medium transition-colors',
		variants: {
			variant: {
				default: {
					class: 'bg-primary text-primary-foreground hover:bg-primary/90'
				},
				destructive: {
					class: 'bg-destructive text-destructive-foreground hover:bg-destructive/90'
				},
				outline: {
					class: 'border border-input bg-background hover:bg-accent'
				}
			},
			size: {
				default: 'h-10 px-4 py-2',
				sm: 'h-9 px-3',
				lg: 'h-11 px-8'
			}
		},
		compounds: [
			{
				variant: 'default',
				size: 'lg',
				class: 'text-base font-semibold'
			}
		],
		defaults: {
			variant: 'default',
			size: 'default'
		}
	})
});

Extending Global Variants

Combine global presets with local extensions:

<script lang="ts">
	import { HtmlAtom } from '@svelte-atoms/core';
	import { defineVariants } from '@svelte-atoms/core/utils';

	// Extend preset variants with local additions
	const extendedVariants = defineVariants({
		variants: {
			variant: {
				// Add new variants not in preset
				gradient: {
					class: 'bg-gradient-to-r from-purple-500 to-pink-500 text-white'
				},
				neon: {
					class: 'bg-black text-green-400 border-2 border-green-400'
				}
			},
			// Add new variant dimension
			animated: {
				true: 'animate-pulse',
				false: ''
			}
		},
		defaults: {
			animated: false
		}
	});

	let { variant, size, animated, ...props } = $props();
</script>

<HtmlAtom
	preset="button"
	variants={extendedVariants}
	as="button"
	{variant}
	{size}
	{animated}
	{...props}
>
	{@render children?.()}
</HtmlAtom>

Bond-Reactive Variants

Variants can react to component state through the Bond pattern:

const accordionVariants = defineVariants({
	class: 'border rounded-md transition-all',
	variants: {
		state: {
			open: (bond) => ({
				class: bond?.state?.isOpen ? 'bg-blue-50 border-blue-200' : 'bg-white',
				'aria-expanded': bond?.state?.isOpen,
				'data-state': bond?.state?.isOpen ? 'open' : 'closed'
			})
		}
	}
});

// Usage with bond
const bond = AccordionBond.get();
const variantProps = $derived(accordionVariants(bond, { state: 'open' }));

Variant Features:

  • βœ… Type Safety - Automatic TypeScript inference
  • βœ… Compound Variants - Apply styles when multiple conditions match
  • βœ… Default Values - Specify fallback variant values
  • βœ… Bond Integration - Access component state for reactive styling
  • βœ… Return Attributes - Not just classes, any HTML attributes
  • βœ… Extensible - Combine global presets with local variants

πŸ“– Documentation

Component Examples

Dropdown with Multiple Selection

<script lang="ts">
	import { Dropdown } from '@svelte-atoms/core';

	let selectedValues = ['option1'];
	const options = [
		{ value: 'option1', label: 'Option 1' },
		{ value: 'option2', label: 'Option 2' },
		{ value: 'option3', label: 'Option 3' }
	];
</script>

<Dropdown.Root multiple bind:values={selectedValues}>
	<!-- Access internal bond -->
	{#snippet children({ dropdown })}
		<Dropdown.Trigger>
			Select options ({selectedValues.length} selected)
		</Dropdown.Trigger>

		<Dropdown.Content>
			{#each options as option}
				<Dropdown.Item value={option.value}>
					{option.label}
				</Dropdown.Item>
			{/each}
		</Dropdown.Content>
	{/snippet}
</Dropdown.Root>

Form with Validation

<script lang="ts">
	import { Form, Input, Button } from '@svelte-atoms/core';
	import { z } from 'zod';

	const schema = z.object({
		email: z.string().email('Invalid email address'),
		password: z.string().min(8, 'Password must be at least 8 characters')
	});

	let formData = { email: '', password: '' };
	let errors = {};
</script>

<Form {schema} bind:value={formData} bind:errors>
	<Field name="email">
		<Field.Label>Email</Field.Label>
		<Field.Control>
			<Input.Root type="email" placeholder="Enter your email" bind:value={formData.email} />
		</Field.Control>
		{#if errors.email}
			<Form.Error>{errors.email}</Form.Error>
		{/if}
	</.Field>

	<Field name="password">
		<Field.Label>Password</Field.Label>
		<Field.Control>
			<Input.Root
				type="password"
				placeholder="Enter your password"
				bind:value={formData.password}
			/>
		</Field.Control>
		{#if errors.password}
			<Field.Error>{errors.password}</Field.Error>
		{/if}
	</.Field>

	<Button type="submit">Submit</Button>
</Form>

Data Grid with Sorting and Selection

<script lang="ts">
	import { DataGrid, Checkbox } from '@svelte-atoms/core';

	let data = [
		{ id: 1, name: 'John Doe', email: 'john@example.com', role: 'Admin' },
		{ id: 2, name: 'Jane Smith', email: 'jane@example.com', role: 'User' },
		{ id: 3, name: 'Bob Johnson', email: 'bob@example.com', role: 'Editor' }
	];

	let selectedRows = [];
</script>

<DataGrid.Root {data} bind:selectedRows multiple>
	<DataGrid.Header>
		<DataGrid.Tr>
			<DataGrid.Th>
				<Checkbox />
			</DataGrid.Th>
			<DataGrid.Th sortable="name">Name</DataGrid.Th>
			<DataGrid.Th sortable="email">Email</DataGrid.Th>
			<DataGrid.Th>Role</DataGrid.Th>
		</DataGrid.Tr>
	</DataGrid.Header>

	<DataGrid.Body>
		{#each data as row}
			<DataGrid.Tr value={row.id}>
				<DataGrid.Td>
					<Checkbox.Root value={row.id} />
				</DataGrid.Td>
				<DataGrid.Td>{row.name}</DataGrid.Td>
				<DataGrid.Td>{row.email}</DataGrid.Td>
				<DataGrid.Td>{row.role}</DataGrid.Td>
			</DataGrid.Tr>
		{/each}
	</DataGrid.Body>
</DataGrid.Root>

🎨 Styling

@svelte-atoms/core is completely headless, giving you full control over styling. Here are some approaches:

Using Vanilla CSS

/* Default button styles */
.btn {
	@apply rounded-md px-4 py-2 font-medium transition-colors;
}

.btn-primary {
	@apply bg-blue-600 text-white hover:bg-blue-700;
}

.btn-secondary {
	@apply bg-gray-200 text-gray-900 hover:bg-gray-300;
}

Using Tailwind CSS

<Button class="rounded-md bg-blue-600 px-4 py-2 text-white hover:bg-blue-700">Styled Button</Button>

πŸ§ͺ Development

Setup

  1. Clone the repository:

    git clone https://github.com/ryu-man/svelte-atoms.git
    cd svelte-atoms
  2. Install dependencies:

    bun install
  3. Start development server:

    bun dev
  4. Run Storybook:

    bun run storybook:dev

Building

# Build library
bun run build

# Build Storybook
bun run storybook:build

Creating New Components

When adding new components, follow these guidelines:

  1. Create the bond structure:

    src/lib/atoms/my-component/
    β”œβ”€β”€ bond.svelte.ts          		# Core bond logic (Bond + BondState classes)
    β”œβ”€β”€ index.ts                		# Public exports
    β”œβ”€β”€ atoms.ts          			# Component exports
    β”œβ”€β”€ my-component-root.svelte		# Use namespace pattern when building complex component
    β”œβ”€β”€ my-component-content.svelte
    └── README.md              		# Component documentation
    
  2. Implement accessibility features:

    • ARIA attributes
    • Keyboard navigation
    • Focus management
    • Screen reader support
  3. Add comprehensive tests:

    • Unit tests for bond logic
    • Component integration tests
    • Accessibility tests
  4. Create Storybook stories:

    • Basic usage examples
    • Advanced configurations
    • Interactive demos

πŸ“š Resources


πŸ—ΊοΈ Roadmap

v1.0.0 (Current - Alpha)

  • βœ… Bond architecture with Svelte 5 runes
  • βœ… 35+ essential components
  • βœ… TypeScript support
  • βœ… Accessibility features
  • βœ… Storybook documentation
  • βœ… Standardized context pattern

πŸ“„ License

MIT License - see the LICENSE file for details.


πŸ™ Acknowledgements

  • Svelte - The amazing framework that powers this library
  • Motion - For handling internal default animations
  • Floating UI - For advanced positioning logic
  • Tailwind CSS - For styling
  • Storybook - For component documentation and testing
  • Vitest - For fast and reliable testing
  • Playwright - For end-to-end testing

Built with ❀️ by the Svelte Atoms team

About

It's not just a UI library - it's a composable rendering system for complex Svelte design systems and applications!

Topics

Resources

Stars

Watchers

Forks

Packages

No packages published

Contributors 2

  •  
  •