Skip to content
Skills Library
Programming · Building & coding

svelte-headless-component

/svelte-headless-component

Architecture and conventions for building headless (unstyled, behavior-only) UI component libraries and compound components in Svelte 5 with runes — the state-class + thin-renderer pattern with render delegation via `child` snippets, context-based composition, and full type wiring. Use this skill whenever creating or structuring a component library, adding a new component family (accordion, dialog, menu, select, tabs, popover, ...) or new parts of one, writing `.svelte.ts` state modules with classes and runes, designing headless/accessible primitives, or porting Radix/shadcn-style components t

Licence
MIT
Last repository change
30.10.2026

Assessment and security

95/ 100Class: good
Format20 / 25
Frontmatter with name and description, valid name, description up to 1,024 characters, name matching the folder.
Discoverability25 / 25
Description explains when to use the skill, has a reasonable length and uses third person.
Content35 / 35
At least 150 words and at most 500 lines, headings, step lists, examples or code.
Hygiene15 / 15
No placeholders such as TODO, no Windows paths, with a licence.
Riskno signals detected in the scan
Files in this package
9
Scripts
0
HTML comments
1
URLs in SKILL.md
0
Deprecation

No signals detected. Repository changed on 30.10.2026, without references to retired models or APIs.

Licence

MIT, open: use and modify while retaining author attribution.

What to check before installing
  • SKILL.md zawiera komentarze HTML (1). Nie widać ich w podglądzie Markdown, a model je czyta.

What it does and when to use it

Architecture and conventions for building headless (unstyled, behavior-only) UI component libraries and compound components in Svelte 5 with runes — the state-class + thin-renderer pattern with render delegation via `child` snippets, context-based composition, and full type wiring. Use this skill whenever creating or structuring a component library, adding a new component family (accordion, dialog, menu, select, tabs, popover, ...) or new parts of one, writing `.svelte.ts` state modules with classes and runes, designing headless/accessible primitives, or porting Radix/shadcn-style components t

Original author description

Architecture and conventions for building headless (unstyled, behavior-only) UI component libraries and compound components in Svelte 5 with runes — the state-class + thin-renderer pattern with render delegation via `child` snippets, context-based composition, and full type wiring. Use this skill whenever creating or structuring a component library, adding a new component family (accordion, dialog, menu, select, tabs, popover, ...) or new parts of one, writing `.svelte.ts` state modules with classes and runes, designing headless/accessible primitives, or porting Radix/shadcn-style components t

How it works

  1. Setup
  2. The anatomy
  3. The state layer in one screen
  4. The component layer in one screen
  5. Deciding structure for a new component
  6. Reviewing changes against this pattern
Original SKILL.md headings · 264 lines, 1,585 words
SKILL.md preview
---
name: svelte-headless-component
description: Architecture and conventions for building headless (unstyled, behavior-only) UI component libraries and compound components in Svelte 5 with runes — the state-class + thin-renderer pattern with render delegation via `child` snippets, context-based composition, and full type wiring. Use this skill whenever creating or structuring a component library, adding a new component family (accordion, dialog, menu, select, tabs, popover, ...) or new parts of one, writing `.svelte.ts` state modules with classes and runes, designing headless/accessible primitives, or porting Radix/shadcn-style components to Svelte. Also use it when reviewing or editing code that follows this pattern, even for small changes — the layering rules are easy to break accidentally.
---

# Headless Component Family Architecture (Svelte 5)

This skill encodes a proven architecture for headless Svelte 5 component libraries. Every
component family (a root plus its parts: trigger, content, item, ...) is built with the same
four-layer structure. The layers exist so that:

- **Logic is testable and reusable without DOM rendering.** All behavior lives in plain classes
  inside `<name>.svelte.ts`. The `.svelte` files are dumb renderers. This is what lets one
  state module power several public families (e.g. one menu state powering dropdown menus,
  context menus, and menu bars).
- **Consumers can render their own elements.** Every part accepts a `child` snippet that
  receives the computed props, making the library truly headless while still shipping sensible
  defaults.
- **The public API is stable and discoverable.** Types carry full JSDoc; exports are
  namespaced (`Accordion.Root`, `Accordion.Trigger`, ...) with short prop aliases
  (`RootProps`).

Break a layer's rule and something concrete breaks: put DOM logic in a `.svelte` file and
variant families can't reuse it; forget the SSR-safe default initialization and hydration
mismatches; return `true` instead of `""` from a boolean attr helper and consumer CSS
selectors stop matching.

## Setup

Two runtime dependencies provide the reactivity bridge this architecture is built on:

```sh
npm install svelte-toolbelt runed
```

- **svelte-toolbelt** — `boxWith`, `simpleBox`, `box`, `mergeProps`, `attachRef`, `afterTick`,
  `onDestroyEffect`, and the `Box` / `ReadableBoxedValues` / `WritableBoxedValues` types.
  Boxes are live views over component props, letting plain classes stay reactive.
- **runed** — `Context` (parent-child wiring) and `watch` / `watch.pre` (effects inside
  classes).

Suggested project layout (adjust to taste; `src/lib/components` and `src/lib/internal` are the
convention used throughout this skill):

```
src/lib/
├── components/
│   ├── <family>/
│   │   ├── <family>.svelte.ts    # ALL behavior: state classes, one per part
│   │   ├── components/           # thin renderers, one per part
│   │   ├── types.ts              # public prop types + snippet prop types, full JSDoc
│   │   ├── exports.ts            # namespaced public API (parts as Root/Trigger/...)
│   │   └── index.ts              # one line: export * as <Name> from "./exports.js"
│   └── index.ts                  # optional barrel re-exporting each family namespace
└── internal/                     # shared helpers (reference implementations provided
                                  #   in references/utilities.md — copy them in)
```

`$lib/...` import aliases work out of the box in SvelteKit; in plain Vite setups either add
the alias or use relative imports. All import specifiers must carry explicit `.js` extensions
(`./types.js`, `../accordion.svelte.js`) including for runes modules.

Reference files (read as needed while working):

- `references/state-layer.md` — the state class pattern in depth: contexts, boxed opts,
  derived props, presence, teardown guards, variant sharing. Read before writing
  `<family>.svelte.ts`.
- `references/component-layer.md` — the renderer pattern in depth: prop bridging,
  `mergeProps` semantics, the `child`/`children` duality, composing overlay behavior. Read
  before writing `components/*.svelte`.
- `references/types-and-exports.md` — prop type construction, JSDoc conventions, export
  wiring, and the new-family/new-part checklists. Read before writing `types.ts` /
  `exports.ts`.
- `references/conventions.md` — data attributes, a11y rules, keyboard handling, SSR safety,
  naming, imports. Read when deciding "how do I express X?" for any detail.
- `references/utilities.md` — copy-ready reference implementations of every shared helper
  this skill assumes: attr helpers, `createAttrs`, core types (`WithChild`, `WithRefOpts`,
  event aliases), `createId`, `noop`, `kbd`, roving focus, presence manager, portal, and a
  minimal dismissable behavior. Bootstrap `src/lib/internal/` from this file first.

## The anatomy

A family directory contains exactly these files (no more, no less):

```
components/<family>/
├── <family>.svelte.ts          # ALL behavior: state classes, one per part
├── components/
│   ├── <family>.svelte         # Root part renderer (no suffix)
│   ├── <family>-<part>.svelte  # Other parts: <family>-<part>.svelte
│   └── ...
├── types.ts                    # Public prop types + snippet prop types, full JSDoc
├── exports.ts                  # Namespaced public API (parts as Root/Trigger/...)
└── index.ts                    # One line: export * as <Name> from "./exports.js"
```

Simple single-part families (a button) skip nothing but have one component and no contexts.
A family that is a thin variant of another (an alert dialog reusing dialog behavior) may
have _no_ state file of its own — it re-exports the shared family's components and state
classes and adds only variant-specific renderers.

## The state layer in one screen

```ts
// <family>.svelte.ts — pattern skeleton (accordion example)
const accordionAttrs = createAttrs({
	component: "accordion",
	parts: ["root", "trigger", "content", "item", "header"],
});

const AccordionRootContext = new Context<AccordionRoot>("Accordion.Root");
const AccordionItemContext = new Context<AccordionItemState>("Accordion.Item");

// One NAMED interface per state class — never inline — composed from the box utilities:
interface AccordionItemStateOpts
	extends
		WithRefOpts, // id (readable) + ref (writable) — never redeclare these
		ReadableBoxedValues<{
			value: string;
			disabled: boolean;
		}> {
	rootState: AccordionRoot; // resolved dependency, not a box
}

export class AccordionItemState {
	static create(props: Omit<AccordionItemStateOpts, "rootState">): AccordionItemState {
		return AccordionItemContext.set(new AccordionItemState({ ...props, rootState: AccordionRootContext.get() }));
	}

	readonly opts: AccordionItemStateOpts;
	readonly root: AccordionRoot;
	readonly isActive = $derived.by(() => this.root.includesItem(this.opts.value.current));
	readonly attachment: RefAttachment;

	constructor(opts: AccordionItemStateOpts) {
		this.opts = opts;
		this.root = opts.rootState;
		this.attachment = attachRef(this.opts.ref);
	}

	// EVERYTHING the DOM element needs, computed reactively:
	readonly props = $derived.by(
		() =>
			({
				id: this.opts.id.current,
				"data-state": getDataOpenClosed(this.isActive),
				[accordionAttrs.item]: "",
				...this.attachment,
			}) as const,
	);
}
```

Non-negotiables, all explained in `references/state-layer.md`:

- One exported class per part, named `<Part>State` (`AccordionRootState`, `MenuContentState`).
- `static create(opts)` is the only public constructor path. It resolves parent state via
  `ParentContext.get()` and registers itself with `OwnContext.set(...)`.
- **Every state class's opts MUST be a named interface.** Declare `<Part>StateOpts`
  (`AccordionItemStateOpts`, `DialogRootStateOpts`) as a standalone `interface` — never an
  inline object type or a `type` alias — composed with `extends` over the option
  utilities: `WithRefOpts` (id + ref — never redeclare those),
  `ReadableBoxedValues<T>` for read-only props, `WritableBoxedValues<T>` for bindable
  props the state may write back to, plus any other shared option utilities. The same
  named contract types `static create`'s parameter, `readonly opts`, and the
  `constructor`.
- Props from components cross the boundary as **boxes** (`boxWith(() => prop, setter)`)
  matching that interface. Read box values with `.current` — never cache them.
- DOM-facing output is a `readonly props = $derived.by(...)` object: `id`, data attributes,
  ARIA attributes, event handlers, `tabindex`, `style`, and always `...this.attachment` last.
- Interactive handlers are bound methods (`this.onclick = this.onclick.bind(this)` in the
  constructor) that guard on disabled state and delegate mutations to the root state.
- Parts that mount/unmount expose `get shouldRender()` backed by a `PresenceManager`, plus
  `...getDataTransitionAttrs(presence.transitionStatus)` inside `props`.
- Snippets receive live values through `readonly snippetProps = $derived.by(() => ({ open }))`.
- Any deferred/async work must be guarded by a `#destroyed` flag set in `onDestroyEffect`.

## The component layer in one screen

```svelte
<!-- components/<family>-trigger.svelte — pattern skeleton -->
<script lang="ts">
	import { boxWith, mergeProps } from "svelte-toolbelt";
	import type { AccordionTriggerProps } from "../types.js";
	import { AccordionTriggerState } from "../accordion.svelte.js";
	import { createId } from "$lib/internal/create-id.js";

	const uid = $props.id();

	let {
		disabled = false,
		ref = $bindable(null),
		id = createId(uid),
		children,
		child,
		...restProps
	}: AccordionTriggerProps = $props();

	const triggerState = AccordionTriggerState.create({
		disabled: boxWith(() => disabled),
		id: boxWith(() => id),
		ref: boxWith(
			() => ref,
			(v) => (ref = v)
		),
	});

	const mergedProps = $derived(mergeProps(restProps, triggerState.props));
</script>

{#if child}
	{@render child({ props: mergedProps })}
{:else}
	<button type="button" {...mergedProps}>
		{@render children?.()}
	</button>
{/if}
```

Non-negotiables, all explained in `references/component-layer.md`:

- `const uid = $props.id();` then default `id = createId(uid)` — never invent ids another way.
- `ref = $bindable(null)` on every part; bridge it (and every bindable prop) into the state
  with `boxWith(() => ref, (v) => (ref = v))`. Bindable state props also invoke their
  `onXChange` callback in the setter.
- `mergeProps(restProps, state.props)` — restProps first, state props second: the state's
  managed values win, but user-supplied event handlers still run (they chain).
- The template is always the `child`-vs-default-element duality shown above. `child` receives
  `{ props: mergedProps, ...state.snippetProps }`; the default branch spreads onto the
  canonical element (button for triggers/actions, div for containers/content).
- Components contain **no logic** beyond prop defaults, bridging, and delegating events to
  state methods. If you're writing an `if` about component state in a `.svelte` file, it
  belongs in the state class.

## Deciding structure for a new component

- **Does it render anything on its own?** Every part is optional to render — the pattern has
  no "uncontrolled default UI". You ship behavior and attributes, never styling.
- **Polymorphic root behavior** (single vs. multiple selection): abstract base state class +
  concrete subclasses + a `type` discriminant, chosen in `static create`. The public props
  type is a discriminated union (see `references/types-and-exports.md`).
- **Variant families** (dialog/alert-dialog, menu/dropdown-menu): one state file with a
  `variant` opt and `getAttr(part)` that prefixes data attributes (`data-alert-dialog-*`).
  Variants share contexts, so context display names list all users:
  `new Context<DialogRootState>("Dialog.Root | AlertDialog.Root")`.
- **Overlays** (dialog/popover content): compose shared behaviors — portal, escape keydown,
  outside-pointer dismissal, focus containment, scroll lock — rather than hand-rolling them.
  Minimal reference implementations for portal and dismissal are in
  `references/utilities.md`; adopt a dedicated focus-trap/floating-positioning library for
  those concerns rather than reimplementing them.
- **Form-worthy parts** (checkbox, select): render a hidden `<input>` sibling carrying
  name/value/disabled so the part participates in native form submission.

## Reviewing changes against this pattern

When reviewing or editing existing families, check the seams first:

1. Logic leaking into `.svelte` files (should move to the state class).
2. `props` objects that omit `...this.attachment` or bypass the attr helpers.
3. State classes taking inline/anonymous opts instead of a named `<Part>StateOpts`
   interface `extends`-ing `WithRefOpts` / `ReadableBoxedValues` / `WritableBoxedValues`
   (or redeclaring `id` / `ref` by hand instead of inheriting them).
4. New props added to `types.ts` without `WithoutHTML` variants / JSDoc / export aliases.
5. Bindable props not bridged through `boxWith` (breaks two-way binding + onXChange).
6. Missing teardown guards for deferred work (`#destroyed` / `onDestroyEffect`).
7. Components in `exports.ts` not aliased (`XRootProps as RootProps`) or missing from the
   barrel registration.
Files in this package (9)
  • .gitignore 1 KB
  • LICENSE 1 KB
  • README.md 1 KB
  • SKILL.md 13 KB
  • references/component-layer.md 7 KB
  • references/conventions.md 7 KB
  • references/state-layer.md 10 KB
  • references/types-and-exports.md 8 KB
  • references/utilities.md 27 KB

Versions

The database has no other skills named svelte-headless-component.

Database snapshot: 13.11.2026 · package version b41f4e29440d (SHA-256 digest of the entire package)

Downloads in the last 30 days: 0 · ranking

: harmful content, incorrect descriptions or an author’s removal request.

Similar skills

  • 100radix-ui
    Radix UI unstyled accessible React components. Headless primitives. USE WHEN: user mentions "Radix", "Radix UI", "headless components", "unstyled primitives", asks about "accessible components", "Radix primitives" DO NOT USE FOR: shadcn/ui (use shadcn-ui skill), styled component…
  • 95building-compound-components
    Creates unstyled compound components that separate business logic from styles. Use when building headless UI primitives, creating component libraries, implementing Radix-style namespaced components, or when the user mentions "compound components", "headless", "unstyled",…
  • 100radix-ui-design-system
    Provides Radix UI patterns for building accessible design systems with headless components, theming, and compound component architecture. Use when building UI with Radix UI primitives or when the user mentions Radix UI, headless components, or accessible component libraries.
  • 90fe-svelte
    Writes and reviews Svelte 5 components in runes mode - $state, $derived, $effect, $props, snippets, event attributes, keyed each blocks - and moves Svelte 4 syntax forward, so components stay reactive, correct and accessible. Use when creating or editing a .svelte or .svelte.js…
  • 100svelte
    Apply Epicenter’s Svelte 5 patterns for runes, components, lifecycles, and workspace-backed state. Use when editing `.svelte`, `.svelte.ts`, or Svelte UI state.
  • 100ui-components
    UI component library patterns for shadcn/ui and Radix Primitives. Use when building accessible component libraries, customizing shadcn components, using Radix unstyled primitives, or creating design system foundations.

Feedback and reports

Your message goes to Bartosz Sokoliński. An email address is needed only for a reply. See the privacy policy.