import { createSignal, For, Show } from "solid-js"; import preview from "../../../.storybook/preview.js"; import { Key, Entries, SetValues, Rerun } from "@solid-primitives/keyed"; import readme from "../README.md?raw"; import { Card, ButtonRow, Button, Container } from "../../../.storybook/ui/index.js"; const meta = preview.meta({ title: "Control Flow/Keyed", tags: ["autodocs"], parameters: { layout: "centered", docs: { description: { component: readme, }, }, }, }); export default meta; type Item = { id: number; name: string; color: string }; const COLORS = ["#6366f1", "#10b981", "#f59e0b", "#ef4444", "#8b5cf6"]; let _nextId = 1; const makeItem = (name: string): Item => ({ id: _nextId++, name, color: COLORS[(_nextId - 1) % COLORS.length]!, }); export const KeyComponent = meta.story({ name: "Key — identity-preserving mapping", parameters: { docs: { description: { story: "`` identifies items by a key rather than by position. When you click-count an item then shuffle the list, the counter stays with that item's key — it is the **same component instance**. With Solid's ``, shuffling reassigns values to position-based instances and the counts move with the slots, not the items.", }, }, }, render: () => { const [items, setItems] = createSignal([ makeItem("Alpha"), makeItem("Beta"), makeItem("Gamma"), makeItem("Delta"), ]); const shuffle = () => setItems(prev => { const copy = [...prev]; for (let i = copy.length - 1; i > 0; i--) { const j = Math.floor(Math.random() * (i + 1)); [copy[i], copy[j]] = [copy[j]!, copy[i]!]; } return copy; }); const reverse = () => setItems(prev => [...prev].reverse()); const addItem = () => setItems(prev => [...prev, makeItem(`Item ${_nextId}`)]); const removeFirst = () => setItems(prev => prev.slice(1)); return (

{''}

No items

}> {item => { const [clicks, setClicks] = createSignal(0); return (
{item().name} id:{item().id} {/* Color changes based on item color — not a generic action button */}
); }}

Click-count any item, then shuffle or reverse — the count stays with that item's{" "} id, not its position.

); }, }); export const EntriesComponent = meta.story({ name: "Entries — reactive object iteration", parameters: { docs: { description: { story: "`` iterates `Object.entries(of)` reactively. The render function receives the static key and a **value signal** — no remount when only the value changes.", }, }, }, render: () => { const [scores, setScores] = createSignal>({ Alice: 87, Bob: 42, Carol: 95, Dave: 61, }); const addPlayer = () => { const names = ["Eve", "Frank", "Grace", "Heidi", "Ivan"]; const existing = Object.keys(scores()); const name = names.find(n => !existing.includes(n)); if (name) setScores(s => ({ ...s, [name]: Math.floor(Math.random() * 100) })); }; const removeLast = () => setScores(s => { const keys = Object.keys(s); if (keys.length === 0) return s; const { [keys[keys.length - 1]!]: _, ...rest } = s; return rest as Record; }); const randomize = () => setScores(s => Object.fromEntries(Object.keys(s).map(k => [k, Math.floor(Math.random() * 100)])), ); return (

{""}

No players

}> {(name, score) => (
{name}
{score()}
)}

The bar widths are driven by a value signal — only the bars update when scores change, no row remount.

); }, }); export const SetValuesComponent = meta.story({ name: "SetValues — reactive Set iteration", parameters: { docs: { description: { story: "`` iterates a `Set` reactively, respecting insertion order. Items are identified by value — adding a duplicate is a no-op.", }, }, }, render: () => { const TAGS = ["solid-js", "typescript", "vite", "vitest", "storybook", "pnpm", "monorepo"]; const [selected, setSelected] = createSignal(new Set(["solid-js", "typescript"])); const toggle = (tag: string) => setSelected(s => { const next = new Set(s); next.has(tag) ? next.delete(tag) : next.add(tag); return next; }); const clear = () => setSelected(new Set()); return (

{""}

{tag => ( )}
Selected tags ({selected().size}):
none} > {value => ( {value} )}

Tags render in insertion order. Adding a tag that already exists is a no-op.

); }, }); export const RerunComponent = meta.story({ name: "Rerun — forced remount on key change", parameters: { docs: { description: { story: "`` destroys and recreates its children whenever the `on` key changes — equivalent to Vue's `v-key` and Svelte's `{#key}`. The children function receives the current and previous key values.", }, }, }, render: () => { const TABS = ["Overview", "Details", "Settings"] as const; type Tab = (typeof TABS)[number]; const [tab, setTab] = createSignal("Overview"); return (

{""}

{/* Tab navigation — custom underline styling, kept as )}
{(currentTab, prevTab) => { const [localCount, setLocalCount] = createSignal(0); const mountedAt = new Date().toLocaleTimeString(); return (
{currentTab}
Previous tab: {prevTab as string}
Mounted at: {mountedAt}
Local counter: {localCount()}
); }}

Increment the counter, then switch tabs — the count resets because the child is fully remounted. The mount timestamp confirms a fresh instance.

); }, });