This skill helps you implement state-driven navigation and Motion One animations for modals, sheets, and route transitions in Composable Svelte.
npx playbooks add skill jonathanbelolo/composable-svelte --skill composable-svelte-navigation
This skill covers state-driven navigation patterns, PresentationState lifecycle animations, and URL routing integration.
---
Principle: State-driven animation uses the public motion layer. For declared motion
recipes, use useMotion or MotionElement for a recipe with exactly one target, anduseMotionGroup when one recipe coordinates its complete declared target set. These APIs
provide managed target ownership and do not imply default animation behavior for navigation
overlays. Keep an explicit PresentationState lifecycle only when application state must observe
completion or keep presentation content alive through dismissal. CSS transitions remain
unsupported for UI interactions. See guides/ANIMATION-GUIDELINES.md andspecs/frontend/application-authoring-and-motion.md; import the public APIs from@composable-svelte/core/application/motion.
Does component have animation?
├─ NO → No animation system needed
└─ YES → What kind?
├─ Infinite loop (spinner, shimmer) → CSS @keyframes ONLY
├─ Hover/focus/click → instant feedback unless application state drives the change
├─ Declared element/group state → MotionElement, useMotion, or useMotionGroup
└─ Store-observed completion/content lifetime → Motion One + PresentationState
.button {
transition: background-color 0.2s; /* ❌ REMOVED */
}
.modal {
transition: opacity 0.3s; /* ❌ Not state-driven, not testable */
}
interface ModalState {
content: Content | null;
presentation: PresentationState<Content>;
}
// Reducer manages lifecycle
case 'show':
return [
{
...state,
content,
presentation: { status: 'presenting', content, duration: 0.3 }
},
Effect.afterDelay(300, (d) => d({
type: 'presentation',
event: { type: 'presentationCompleted' }
}))
];
// Component executes animation
$effect(() => {
if (store.state.presentation.status === 'presenting') {
animateModalIn(element).then(() => {
store.dispatch({
type: 'presentation',
event: { type: 'presentationCompleted' }
});
});
}
});
WHY: State-driven animations are predictable, testable with TestStore, and composable with the navigation system.
---
Non-null state = presented, null = dismissed
This creates a navigation tree where each node can optionally present a child screen.
// Parent state
interface AppState {
items: Item[];
destination: DestinationState | null; // What to show
}
// Destination is enum of possible screens
type DestinationState =
| { type: 'addItem'; state: AddItemState }
| { type: 'editItem'; state: EditItemState; itemId: string }
| { type: 'confirmDelete'; state: ConfirmDeleteState; itemId: string };
// Child states
interface AddItemState {
name: string;
quantity: number;
}
interface EditItemState {
name: string;
quantity: number;
}
interface ConfirmDeleteState {
itemName: string;
}
type AppAction =
| { type: 'addButtonTapped' }
| { type: 'editButtonTapped'; itemId: string }
| { type: 'deleteButtonTapped'; itemId: string }
| { type: 'destination'; action: PresentationAction<DestinationAction> };
type DestinationAction =
| { type: 'addItem'; action: AddItemAction }
| { type: 'editItem'; action: EditItemAction }
| { type: 'confirmDelete'; action: ConfirmDeleteAction };
// PresentationAction wraps child actions
type PresentationAction<A> =
| { type: 'presented'; action: A }
| { type: 'dismiss' };
---
When: Maintaining reducer-only code that has not adopted managed composition. New
application presentation code should declare an optionalSlot or destinationSlot;
managed composition consumes its dismissal action and clears the slot automatically.
// Parent state
interface AppState {
items: Item[];
destination: AddItemState | null; // Optional child
}
// Parent actions
type AppAction =
| { type: 'addButtonTapped' }
| { type: 'destination'; action: PresentationAction<AddItemAction> };
// Reducer
import { ifLetPresentation } from '@composable-svelte/core';
case 'addButtonTapped':
return [
{ ...state, destination: { name: '', quantity: 0 } },
Effect.none()
];
case 'destination': {
// Handle dismiss
if (action.action.type === 'dismiss') {
return [{ ...state, destination: null }, Effect.none()];
}
// Compose child
const [newState, effect] = ifLetPresentation(
(s) => s.destination,
(s, d) => ({ ...s, destination: d }),
'destination',
(ca): AppAction => ({ type: 'destination', action: { type: 'presented', action: ca } }),
addItemReducer
)(state, action, deps);
// Parent observes child completion
if ('action' in action &&
action.action.type === 'presented' &&
action.action.action.type === 'saveButtonTapped') {
const item = newState.destination!;
return [
{
...newState,
destination: null, // Dismiss
items: [...newState.items, { id: crypto.randomUUID(), ...item }]
},
effect
];
}
return [newState, effect];
}
---
Critical Pattern: Parent can observe child actions to react to completion, cancellation, or other child events.
The manual reducer example below is a legacy reducer-only boundary. In managed
composition, observe presented child actions in the root reducer but let the declared
slot consume dismissal.
case 'destination': {
// Legacy-only dismissal handling (no managed slot owns this boundary).
if (action.action.type === 'dismiss') {
return [{ ...state, destination: null }, Effect.none()];
}
// Route to child reducer based on destination type
let newState = state;
let effect: Effect<AppAction> = Effect.none();
if (state.destination?.type === 'addItem' && 'action' in action && action.action.type === 'presented') {
const [childState, childEffect] = addItemReducer(
state.destination.state,
action.action.action,
deps
);
newState = {
...state,
destination: { type: 'addItem', state: childState }
};
// By hand there is no cancellation: a save still in flight when the
// destination is nulled below lands in the next presentation. Prefer
// `integrate(core).with('destination', Destination.reducer)`, which puts
// the child's effects in the field's cancellation group and cancels it on
// dismiss, on a parent null and on a case change — or add
// `Effect.cancelGroup('destination')` where the field is nulled and nest
// the child's effect with `Effect.inGroup(…, 'destination')`.
effect = Effect.map(childEffect, (childAction): AppAction => ({
type: 'destination',
action: { type: 'presented', action: { type: 'addItem', action: childAction } }
}));
// Observe child completion
if (action.action.action.type === 'saveButtonTapped') {
return [
{
...newState,
destination: null,
items: [...newState.items, {
id: crypto.randomUUID(),
name: childState.name,
quantity: childState.quantity
}]
},
effect
];
}
// Observe child cancellation
if (action.action.action.type === 'cancelButtonTapped') {
return [
{ ...newState, destination: null },
effect
];
}
}
// Similar for editItem and confirmDelete...
return [newState, effect];
}
---
Legacy scopeToDestination, scopeToOptional, and fluent scopeTo remain useful for
state reads and action dispatch outside presentation rendering. Their returned stores
do not carry dismissal authority and must not be passed to dismissing navigation
components.
For a rendered presentation, declare an optionalSlot or destinationSlot in the
application composition, declare its view with defineViews, and render it throughFeatureViews / FeatureOutlet. The renderer receives a nominalPresentationView<State, Action> and its surface action:
Import PresentationFeatureViewProps from @composable-svelte/core/application when
annotating a standalone declaration snippet.
<script lang="ts">
import type { PresentationFeatureViewProps } from '@composable-svelte/core/application';
</script>
{#snippet modalView({ store, surface }: PresentationFeatureViewProps<State, Action>)}
<Modal {store} ariaLabel="Edit item">
<form use:surface>
<button onclick={() => store.dispatch({ type: 'save' })}>Save</button>
<button onclick={() => store.dismiss()}>Cancel</button>
</form>
</Modal>
{/snippet}
Do not fabricate or cast a view. dismiss() is exact-owner authority: a copied or stale
view cannot dismiss a replacement.
---
idle → presenting → presented → dismissing → idle
↑ ↓ ↓ ↓ ↑
└────────┴───────────┴───────────┴─────────┘
type PresentationState<Content> =
| { status: 'idle' }
| { status: 'presenting'; content: Content; duration: number }
| { status: 'presented'; content: Content }
| { status: 'dismissing'; content: Content; duration: number };
type PresentationEvent =
| { type: 'presentationCompleted' }
| { type: 'dismissalCompleted' };
Pass the admitted PresentationView and the reducer-owned PresentationState to the
navigation component. Completion callbacks report the visual lifecycle; they do not
mint dismissal authority or synthesize raw dismiss actions.
<Modal
{store}
{presentation}
onPresentationComplete={() => dispatch({ type: 'presentationCompleted' })}
onDismissalComplete={() => dispatch({ type: 'dismissalCompleted' })}
>
<section use:surface>...</section>
</Modal>
The component owns focus, portal, dismissal boundary, scroll lock, and exit-shell
lifetime. Keep those concerns out of application reducers.
---
The current public authoring surface is MotionElement, useMotion, and useMotionGroup
from @composable-svelte/core/application/motion. Use a declared recipe for element or group
motion. The explicit helper pattern below is retained for legacy application-owned lifecycles
whose reducers must observe completion or retain content through dismissal; it is not required
for every animation.
import {
animateModalIn,
animateModalOut,
animateSheetIn,
animateSheetOut,
animateAccordionExpand,
animateAccordionCollapse
} from '@composable-svelte/core/animation';
// Usage
$effect(() => {
if ($store.presentation.status === 'presenting') {
animateModalIn(element).then(() => {
store.dispatch({
type: 'presentation',
event: { type: 'presentationCompleted' }
});
});
}
});
MotionElement or useMotion.useMotionGroup.PresentationState and completion-event pattern below.
choose and declare the motion required by that view.
import { animateModalIn, animateSheetIn, /* etc */ } from '@composable-svelte/core/animation';
// Modal (fade + scale)
animateModalIn(element), animateModalOut(element)
animateBackdropIn(element), animateBackdropOut(element)
// Sheet (slide from bottom)
animateSheetIn(element), animateSheetOut(element)
// Drawer (slide from side)
animateDrawerIn(element, side), animateDrawerOut(element, side)
// Alert (fade + scale, smaller)
animateAlertIn(element), animateAlertOut(element)
// Tooltip (fade + slight scale)
animateTooltipIn(element), animateTooltipOut(element)
// Toast (slide from edge)
animateToastIn(element), animateToastOut(element)
// Dropdown (fade + slide)
animateDropdownIn(element), animateDropdownOut(element)
// Sidebar (width expand/collapse)
animateSidebarExpand(element), animateSidebarCollapse(element)
// Popover (fade + scale)
animatePopoverIn(element), animatePopoverOut(element)
// NavigationStack (slide left/right)
animateStackPushIn(element), animateStackPushOut(element)
animateStackPopIn(element), animateStackPopOut(element)
// Accordion (height expand/collapse)
animateAccordionExpand(element), animateAccordionCollapse(element)
/* ✅ ALLOWED - Infinite loop */
@keyframes spin {
to { transform: rotate(360deg); }
}
.spinner {
animation: spin 1s linear infinite;
}
/* ✅ ALLOWED - Shimmer effect */
@keyframes shimmer {
0% { background-position: -200% 0; }
100% { background-position: 200% 0; }
}
.skeleton {
animation: shimmer 1.5s infinite;
}
CSS Animations:
---
URL routing is state synchronization, not a separate navigation system. Use the router's pure functions for serialization/parsing.
import { syncBrowserHistory } from '@composable-svelte/core/routing';
import type { Store } from '@composable-svelte/core';
// The destination type is inferred from `getDestination`'s return, which needs
// a typed store to infer *from*. Without one, `dest` in `destinationToAction`
// arrives as `{}` and `dest.state` does not compile.
interface BlogState {
selectedPostId: string | null;
}
declare const store: Store<BlogState, AppAction>;
type PostDestination = { type: 'post'; state: { postId: string } };
// In client hydration. The destination type is given explicitly: TypeScript
// cannot unify it from `getDestination`'s return and `destinationToAction`'s
// parameter at the same time, and falls back to `{}`.
syncBrowserHistory<BlogState, AppAction, PostDestination>(store, {
serializers: serializerConfig.serializers,
parsers: parserConfig.parsers,
// Map state → destination for URL serialization
getDestination: (state) => {
if (state.selectedPostId !== null) {
return { type: 'post' as const, state: { postId: state.selectedPostId } };
}
return null;
},
// Map destination → action for back/forward navigation
destinationToAction: (dest) => {
if (dest?.type === 'post') {
return { type: 'selectPost', postId: dest.state.postId };
}
return null;
}
});
import { parseDestination } from './routing';
// In server route handler
async function renderApp(request: any, reply: any) {
const posts = await loadPosts();
const path = request.url;
const requestedPostId = parsePostFromURL(path, posts[0]?.id || 1);
const store = createStore({
initialState: {
...initialState,
posts,
selectedPostId: requestedPostId,
meta: computeMetaForPost(posts.find(p => p.id === requestedPostId))
},
reducer: appReducer,
dependencies: {}
});
const html = renderToHTML(App, { store });
reply.type('text/html').send(html);
}
> There is no createRouter builder. Routing is a pair of config objects —
> parseDestination for URL → state and serializeDestination for state → URL.
import {
parseDestination,
serializeDestination,
matchPath,
type ParserConfig,
type SerializerConfig
} from '@composable-svelte/core/routing';
type Destination = { type: 'post'; state: { postId: number } };
// `parsers` is an ordered list of functions, each returning a destination or
// null. Put more specific patterns first.
const parserConfig: ParserConfig<Destination> = {
basePath: '/',
parsers: [
(path) => {
const params = matchPath('/posts/:postId', path);
return params ? { type: 'post', state: { postId: Number(params.postId) } } : null;
}
]
};
// `serializers` maps destination.type -> a function over that destination's state.
const serializerConfig: SerializerConfig<Destination> = {
basePath: '/',
serializers: {
post: (state) => `/posts/${state.postId}`
}
};
const destination = parseDestination('/posts/42', parserConfig);
const path = serializeDestination({ type: 'post', state: { postId: 42 } }, serializerConfig);
matchPath('/posts/:postId', path) returns the params (or null) for a single
pattern. Working reference: examples/url-routing/src/routing.ts.
---
Modal, Alert, Sheet, Drawer, Popover, and Sidebar are dismissing managed
presentation families. Each styled component and primitive accepts a framework-mintedPresentationView; never pass a raw store or legacy scoped store.
<Modal {store} ariaLabel="Details"><section use:surface>...</section></Modal>
<Alert {store} ariaLabel="Confirm"><section use:surface>...</section></Alert>
<Sheet {store} side="bottom"><section use:surface>...</section></Sheet>
<Drawer {store} side="right"><section use:surface>...</section></Drawer>
<Popover {store} style="top: 3rem; right: 1rem"><section use:surface>...</section></Popover>
<Sidebar {store} side="left" width="240px"><nav use:surface>...</nav></Sidebar>
Use store.dispatch() for feature actions and store.dismiss() for an owner-bound
view request. Reducers use managedDismissDependency() when dismissal must originate
from reducer logic.
Tabs, NavigationStack, and AnimatedNavigationStack are non-dismissing families
and retain their ChildView contract.
---
Keep application composition, view declaration, and component rendering separate:
ManagedIntegrationBuilder and an optional/destination slot.defineApplication.defineViews.ApplicationRoot and ApplicationHost.FeatureViews and FeatureOutlet.Inside each view snippet, pass the supplied store directly to the navigation
component and attach the supplied surface action to feature markup. Do not recreate
that plumbing inside child components and do not scope the raw application store into
a modal, sheet, drawer, alert, popover, or sidebar.
---
case 'destination': {
// Redundant with the managed slot below.
if (action.action.type === 'dismiss') {
return [{ ...state, destination: null }, Effect.none()];
}
// ...
}
const composition = new ManagedIntegrationBuilder(reducer)
.with(destinationSlot, childReducer)
.build();
// Managed boundary: the slot consumes dismissal and clears itself.
const composition = new ManagedIntegrationBuilder(reducer)
.with(destinationSlot, childReducer)
.build();
// Legacy reducer-only boundary (without ManagedIntegrationBuilder):
case 'destination': {
if (action.action.type === 'dismiss') {
return [{ ...state, destination: null }, Effect.none()];
}
const [newState, effect] = ifLetPresentation(...)(state, action, deps);
return [newState, effecWeekly roundup of top Claude Code skills, MCP servers, and AI coding tips.