## docs/svelte/01-introduction/01-overview.md # Svelte 5 Reference ## Overview Svelte is a compiler-based framework for building web UIs. It turns declarative components into optimized JavaScript. ```svelte ``` Components contain HTML, CSS, and JavaScript. Use with SvelteKit for full-stack apps. ## docs/svelte/01-introduction/02-getting-started.md # Getting started ## Quick start with SvelteKit (recommended) ```bash npx sv create myapp cd myapp npm install npm run dev ``` ## Alternatives **Vite standalone:** ```bash npm create vite@latest # Select 'svelte' option npm run build # Generates files in dist/ ``` **Other build tools:** Rollup, Webpack plugins available but Vite recommended. ## Editor tooling - VS Code extension available - Command line checking: `sv check` ## Getting help - Discord chatroom - Stack Overflow (svelte tag) ## docs/svelte/01-introduction/03-svelte-files.md # .svelte files Components are written in `.svelte` files using a superset of HTML. All sections are optional. ```svelte ``` ## ` ``` Can `export` bindings (becomes module exports). Cannot `export default` - component is default export. ## ` ``` ## docs/svelte/01-introduction/04-svelte-js-files.md # .svelte.js and .svelte.ts files `.svelte.js` and `.svelte.ts` files behave like regular JS/TS modules but can use runes. Useful for reusable reactive logic and sharing reactive state across your app. > Note: You cannot export reassigned state. > New in Svelte 5 ## docs/svelte/02-runes/01-what-are-runes.md # Runes Runes are symbols with `$` prefix that control the Svelte compiler. They're keywords, not functions. ```js let message = $state('hello'); ``` Key differences from functions: - No import needed - they're globals - Not values - can't assign to variables or pass as arguments - Only valid in specific positions (compiler enforces this) ## docs/svelte/02-runes/02-$state.md # $state Creates reactive state that triggers UI updates when changed. ```svelte ``` State values are plain JavaScript - no special API needed for updates. ## Deep state Arrays and objects become deeply reactive proxies: ```js let todos = $state([ { done: false, text: 'add more todos' } ]); ``` Granular updates work: ```js todos[0].done = !todos[0].done; // triggers updates todos.push({ done: false, text: 'eat lunch' }); // also reactive ``` **Gotcha:** Destructuring breaks reactivity: ```js let { done, text } = todos[0]; // `done` won't update when todos[0].done changes ``` ## Classes Use `$state` in class fields or constructor assignments: ```js class Todo { done = $state(false); constructor(text) { this.text = $state(text); } reset() { this.text = ''; this.done = false; } } ``` **Method binding gotcha:** Use arrow functions or inline functions: ```svelte ``` Or use arrow functions in class: ```js class Todo { reset = () => { this.text = ''; this.done = false; } } ``` ## $state.raw Non-reactive state - can only be reassigned, not mutated: ```js let person = $state.raw({ name: 'Heraclitus', age: 49 }); person.age += 1; // no effect person = { name: 'Heraclitus', age: 50 }; // works ``` Better performance for large objects you won't mutate. ## $state.snapshot Get static snapshot of reactive state: ```svelte ``` Useful for external libraries that don't expect proxies. ## Sharing state across modules **Can't directly export reassignable state:** ```js // โŒ Won't work export let count = $state(0); ``` **Solutions:** Export object properties: ```js export const counter = $state({ count: 0 }); export function increment() { counter.count += 1; } ``` Or use getter functions: ```js let count = $state(0); export function getCount() { return count; } export function increment() { count += 1; } ``` ## docs/svelte/02-runes/03-$derived.md # $derived Derived state is declared with the `$derived` rune: ```svelte

{count} doubled is {doubled}

``` The expression inside `$derived(...)` should be free of side-effects. Svelte will disallow state changes (e.g. `count++`) inside derived expressions. Code in Svelte components is only executed once at creation. Without the `$derived` rune, `doubled` would maintain its original value even when `count` changes. ## `$derived.by` For complex derivations that don't fit inside a short expression, use `$derived.by` which accepts a function: ```svelte ``` `$derived(expression)` is equivalent to `$derived.by(() => expression)`. ## Dependencies Anything read synchronously inside the `$derived` expression is considered a dependency. When state changes, the derived is marked as dirty and recalculated when next read. To exempt state from being a dependency, use `untrack`. ## Overriding derived values You can temporarily override derived values by reassigning them (unless declared with `const`). Useful for optimistic UI: ```svelte ``` ## Deriveds and reactivity Unlike `$state`, `$derived` values are left as-is (not converted to deeply reactive proxies): ```svelte let items = $state([...]); let index = $state(0); let selected = $derived(items[index]); ``` You can change properties of `selected` and it will affect the underlying `items` array. ## Update propagation Svelte uses push-pull reactivity โ€” when state updates, everything that depends on it is immediately notified (push), but derived values aren't re-evaluated until read (pull). If a derived's new value is referentially identical to its previous value, downstream updates are skipped: ```svelte ``` The button only updates when `large` changes, not when `count` changes. ## docs/svelte/02-runes/04-$effect.md # $effect Effects run when state updates. Used for third-party libraries, canvas drawing, network requests. Only run in browser, not SSR. **Don't update state inside effects** - leads to infinite loops. Use alternatives below. ## Basic Usage ```svelte ``` ## Lifecycle & Teardown Effects run after mount in microtasks. Re-runs are batched. Can return teardown function: ```svelte

{count}

``` ## Dependencies Auto-tracks reactive values read **synchronously**. Async reads (after `await`, `setTimeout`) not tracked: ```ts $effect(() => { const context = canvas.getContext('2d'); context.clearRect(0, 0, canvas.width, canvas.height); // this will re-run whenever `color` changes... context.fillStyle = color; setTimeout(() => { // ...but not when `size` changes context.fillRect(0, 0, size, size); }, 0); }); ``` **Object vs property tracking:** ```svelte

{state.value} doubled is {derived.value}

``` **Conditional dependencies:** Only tracks values read in last run. ## $effect.pre Runs **before** DOM updates: ```svelte
{#each messages as message}

{message}

{/each}
``` ## $effect.tracking Returns if code runs in tracking context: ```svelte

in template: {$effect.tracking()}

``` ## $effect.root Creates non-tracked scope with manual cleanup: ```js const destroy = $effect.root(() => { $effect(() => { // setup }); return () => { // cleanup }; }); // later... destroy(); ``` ## When NOT to use $effect **โŒ Don't sync state:** ```svelte ``` **โœ… Use $derived:** ```svelte ``` **โŒ Don't link values with effects:** ```svelte ``` **โœ… Use derived + callbacks:** ```svelte ``` Use `untrack()` if you must read/write same state in effect to avoid loops. ## docs/svelte/02-runes/05-$props.md # $props Pass props to components like attributes: ```svelte ``` Receive props with `$props` rune: ```svelte

this component is {props.adjective}

``` More commonly, destructure props: ```svelte

this component is {adjective}

``` ## Fallback values ```js let { adjective = 'happy' } = $props(); ``` > Fallback values are not turned into reactive state proxies ## Renaming props ```js let { super: trouper = 'lights are gonna find me' } = $props(); ``` ## Rest props ```js let { a, b, c, ...others } = $props(); ``` ## Updating props Props update when parent changes. Child can temporarily override prop values: ```svelte ``` ```svelte ``` **Don't mutate props** unless they are `$bindable`. Mutating regular objects has no effect. Mutating reactive state proxies causes `ownership_invalid_mutation` warning. ## Type safety TypeScript: ```svelte ``` JSDoc: ```svelte ``` Interface: ```svelte ``` ## `$props.id()` Generates unique ID per component instance, consistent between server/client: ```svelte
``` ## docs/svelte/02-runes/06-$bindable.md # $bindable Props normally flow one-way from parent to child. `$bindable` allows two-way data flow and state mutation in the child component. ## Basic Usage Mark a prop as bindable with `$bindable()`: ```svelte /// file: FancyInput.svelte ``` Parent can bind to it with `bind:`: ```svelte /// file: App.svelte

{message}

``` ## Fallback Values Provide fallback when no prop is passed: ```js /// file: FancyInput.svelte let { value = $bindable('fallback'), ...props } = $props(); ``` **Note:** Parent can still pass normal props without `bind:` - binding is optional. ## docs/svelte/02-runes/07-$inspect.md # $inspect > [!NOTE] `$inspect` only works during development. In a production build it becomes a noop. The `$inspect` rune is equivalent to `console.log` but re-runs when its arguments change. Tracks reactive state deeply. ```svelte ``` ## $inspect(...).with Use custom callback instead of `console.log`. First argument is `"init"` or `"update"`: ```svelte ``` Find origin of changes: ```js // @errors: 2304 $inspect(stuff).with(console.trace); ``` ## $inspect.trace(...) Traces function re-runs in effects/derived. Must be first statement in function body: ```svelte ``` Takes optional label as first argument. ## docs/svelte/02-runes/08-$host.md # $host The `$host` rune provides access to the host element when compiling a component as a custom element. Commonly used to dispatch custom events. ```svelte /// file: Stepper.svelte ``` ```svelte /// file: App.svelte count -= 1} onincrement={() => count += 1} >

count: {count}

``` ## docs/svelte/03-template-syntax/01-basic-markup.md # Basic markup Markup inside Svelte components is HTML++. ## Tags - Lowercase tags (`
`) = HTML elements - Capitalized/dot notation (``, ``) = components ```svelte
``` ## Element attributes Work like HTML. Values can contain or be JavaScript expressions: ```svelte
``` ```svelte ``` ```svelte page {p} ``` ```svelte ``` **Attribute rules:** - Boolean attributes: included if truthy, excluded if falsy - Other attributes: included unless nullish (`null`/`undefined`) - Shorthand: `{name}` instead of `name={name}` ```svelte
This div has no title attribute
``` ```svelte ``` ## Component props Same rules as attributes. Use `{name}` shorthand: ```svelte ``` ## Spread attributes Pass multiple attributes at once. Order matters: ```svelte ``` ## Events Use `on` prefix (case sensitive). No colon syntax in Svelte 5: ```svelte ``` Event attributes support: - Shorthand: `` - Spreading: `` **Event delegation:** These events are delegated for performance: `beforeinput`, `click`, `change`, `dblclick`, `contextmenu`, `focusin`, `focusout`, `input`, `keydown`, `keyup`, `mousedown`, `mousemove`, `mouseout`, `mouseover`, `mouseup`, `pointerdown`, `pointermove`, `pointerout`, `pointerover`, `pointerup`, `touchend`, `touchmove`, `touchstart` **Gotchas:** - Manual events need `{ bubbles: true }` - Avoid `stopPropagation` with `addEventListener` - Use `on` from `svelte/events` instead of `addEventListener` ## Text expressions JavaScript expressions in curly braces. `null`/`undefined` omitted, others stringified: ```svelte

Hello {name}!

{a} + {b} = {a + b}.

{(/^[A-Za-z ]+$/).test(value) ? x : y}
``` Render HTML (dangerous): ```svelte {@html potentiallyUnsafeHtmlString} ``` ## Comments HTML comments work. Use `svelte-ignore` to disable warnings: ```svelte

Hello world

``` ```svelte ``` Component documentation with `@component`: ````svelte

Hello, {name}

```` ## docs/svelte/03-template-syntax/02-if.md # {#if ...} Conditionally render content using if blocks. ## Syntax ```svelte {#if expression}...{/if} {#if expression}...{:else if expression}...{/if} {#if expression}...{:else}...{/if} ``` ## Examples Basic conditional: ```svelte {#if answer === 42}

what was the question?

{/if} ``` Multiple conditions: ```svelte {#if porridge.temperature > 100}

too hot!

{:else if 80 > porridge.temperature}

too cold!

{:else}

just right!

{/if} ``` Blocks can wrap elements or text within elements. ## docs/svelte/03-template-syntax/03-each.md # {#each ...} ## Basic syntax ```svelte {#each expression as name}...{/each} {#each expression as name, index}...{/each} ``` Works with arrays, array-like objects (with `length` property), or iterables like `Map` and `Set`. ```svelte

Shopping list

    {#each items as item}
  • {item.name} x {item.qty}
  • {/each}
``` With index: ```svelte {#each items as item, i}
  • {i + 1}: {item.name} x {item.qty}
  • {/each} ``` ## Keyed each blocks ```svelte {#each expression as name (key)}...{/each} {#each expression as name, index (key)}...{/each} ``` Keys enable intelligent updates (insert/move/delete) instead of updating all items. Use strings/numbers for persistent identity. ```svelte {#each items as item (item.id)}
  • {item.name} x {item.qty}
  • {/each} {#each items as item, i (item.id)}
  • {i + 1}: {item.name} x {item.qty}
  • {/each} ``` ## Destructuring ```svelte {#each items as { id, name, qty }, i (id)}
  • {i + 1}: {name} x {qty}
  • {/each} {#each objects as { id, ...rest }}
  • {id}
  • {/each} {#each items as [id, ...rest]}
  • {id}
  • {/each} ``` ## Without item variable ```svelte {#each expression}...{/each} {#each expression, index}...{/each} ``` For rendering something `n` times: ```svelte
    {#each { length: 8 }, rank} {#each { length: 8 }, file}
    {/each} {/each}
    ``` ## Else blocks ```svelte {#each expression as name}...{:else}...{/each} ``` Renders when list is empty: ```svelte {#each todos as todo}

    {todo.text}

    {:else}

    No tasks today!

    {/each} ``` ## docs/svelte/03-template-syntax/04-key.md # {#key ...} ```svelte {#key expression}...{/key} ``` Destroys and recreates contents when expression changes. **Component reinstantiation:** ```svelte {#key value} {/key} ``` **Trigger transitions on value change:** ```svelte {#key value}
    {value}
    {/key} ``` ## docs/svelte/03-template-syntax/05-await.md # {#await ...} Await blocks handle Promise states: pending, fulfilled, rejected. ## Syntax ```svelte {#await expression}...{:then name}...{:catch name}...{/await} {#await expression}...{:then name}...{/await} {#await expression then name}...{/await} {#await expression catch name}...{/await} ``` ## Basic Usage ```svelte {#await promise}

    waiting for the promise to resolve...

    {:then value}

    The value is {value}

    {:catch error}

    Something went wrong: {error.message}

    {/await} ``` ## Shortened Forms Omit catch block: ```svelte {#await promise}

    waiting for the promise to resolve...

    {:then value}

    The value is {value}

    {/await} ``` Omit pending state: ```svelte {#await promise then value}

    The value is {value}

    {/await} ``` Error only: ```svelte {#await promise catch error}

    The error is {error}

    {/await} ``` ## Lazy Component Loading ```svelte {#await import('./Component.svelte') then { default: Component }} {/await} ``` ## Important Notes - SSR only renders pending branch - Non-Promise expressions only render `:then` branch - Catch block is optional if no error handling needed ## docs/svelte/03-template-syntax/06-snippet.md # {#snippet ...} Create reusable chunks of markup inside components. ## Syntax ```svelte {#snippet name()}...{/snippet} ``` ```svelte {#snippet name(param1, param2, paramN)}...{/snippet} ``` ## Basic Usage Instead of duplicating markup: ```svelte {#each images as image} {#if image.href}
    {image.caption}
    {image.caption}
    {:else}
    {image.caption}
    {image.caption}
    {/if} {/each} ``` Use snippets: ```svelte {#snippet figure(image)}
    {image.caption}
    {image.caption}
    {/snippet} {#each images as image} {#if image.href} {@render figure(image)} {:else} {@render figure(image)} {/if} {/each} ``` ## Snippet Scope Snippets can reference values from ` {#snippet hello(name)}

    hello {name}! {message}!

    {/snippet} {@render hello('alice')} {@render hello('bob')} ``` Snippets can reference themselves and each other: ```svelte {#snippet blastoff()} ๐Ÿš€ {/snippet} {#snippet countdown(n)} {#if n > 0} {n}... {@render countdown(n - 1)} {:else} {@render blastoff()} {/if} {/snippet} {@render countdown(10)} ``` ## Passing Snippets to Components ### Explicit Props ```svelte {#snippet header()} fruit qty price total {/snippet} {#snippet row(d)} {d.name} {d.qty} {d.price} {d.qty * d.price} {/snippet} ``` ### Implicit Props Snippets declared inside a component become props: ```svelte
    {#snippet header()} {/snippet} {#snippet row(d)} {/snippet}
    fruit qty price total{d.name} {d.qty} {d.price} {d.qty * d.price}
    ``` ### Implicit `children` Snippet Content inside component tags becomes the `children` snippet: ```svelte ``` ```svelte ``` ### Optional Snippets Use optional chaining: ```svelte {@render children?.()} ``` Or `#if` with fallback: ```svelte {#if children} {@render children()} {:else} fallback content {/if} ``` ## TypeScript Use the `Snippet` interface: ```svelte ``` With generics: ```svelte ``` ## Exporting Snippets Export from ` {#snippet add(a, b)} {a} + {b} = {a + b} {/snippet} ``` ## Notes - Parameters can have default values and be destructured - No rest parameters allowed - Snippets replace deprecated slots from Svelte 4 - Use `createRawSnippet` API for programmatic creation ## docs/svelte/03-template-syntax/07-@render.md # {@render ...} Render [snippets](snippet) using `{@render ...}` tags. ```svelte {#snippet sum(a, b)}

    {a} + {b} = {a + b}

    {/snippet} {@render sum(1, 2)} {@render sum(3, 4)} {@render sum(5, 6)} ``` Expression can be identifier or JavaScript expression: ```svelte {@render (cool ? coolSnippet : lameSnippet)()} ``` ## Optional snippets Use optional chaining for potentially undefined snippets: ```svelte {@render children?.()} ``` Or `{#if}` with fallback: ```svelte {#if children} {@render children()} {:else}

    fallback content

    {/if} ``` ## docs/svelte/03-template-syntax/08-@html.md # {@html ...} Inject raw HTML into components: ```svelte
    {@html content}
    ``` **Security**: Always escape or control content to prevent XSS attacks. Never render unsanitized content. **Requirements**: - Expression must be valid standalone HTML - Cannot split HTML tags across multiple `{@html}` blocks - Does not compile Svelte code ## Styling `{@html}` content is invisible to Svelte scoped styles. Use `:global` modifier: ```svelte ``` ## docs/svelte/03-template-syntax/09-@attach.md # {@attach ...} Attachments are functions that run in an effect when an element mounts or when state updates. They can return a cleanup function. ```svelte
    ...
    ``` ## Attachment factories Functions can return attachments for reusability: ```svelte ``` Attachments recreate when dependencies change. ## Inline attachments ```svelte { const context = canvas.getContext('2d'); $effect(() => { context.fillStyle = color; context.fillRect(0, 0, canvas.width, canvas.height); }); }} > ``` ## Component attachments Attachments on components become props that spread to elements: ```svelte ``` ```svelte ``` ## Controlling re-runs Attachments are fully reactive. To prevent expensive re-runs, pass data in a function: ```js function foo(getBar) { return (node) => { veryExpensiveSetupWork(node); $effect(() => { update(node, getBar()); }); } } ``` ## Utilities - `createAttachmentKey` - Add attachments to objects programmatically - `fromAction` - Convert actions to attachments ## docs/svelte/03-template-syntax/10-@const.md # {@const ...} The `{@const ...}` tag defines a local constant within blocks. ```svelte {#each boxes as box} {@const area = box.width * box.height} {box.width} * {box.height} = {area} {/each} ``` **Usage**: Only allowed as immediate child of blocks (`{#if}`, `{#each}`, `{#snippet}`), components (``), or ``. ## docs/svelte/03-template-syntax/11-@debug.md # {@debug ...} The `{@debug ...}` tag logs variable values when they change and pauses execution if devtools are open. ```svelte {@debug user}

    Hello {user.firstname}!

    ``` **Usage patterns:** - Single variable: `{@debug user}` - Multiple variables: `{@debug user1, user2, user3}` - No arguments: `{@debug}` - triggers on any state change **Important:** Only accepts variable names, not arbitrary expressions like `{@debug !isReady}` or `{@debug typeof user === 'object'}`. ## docs/svelte/03-template-syntax/12-bind.md # bind: Data flows down by default. `bind:` allows data to flow from child to parent. Syntax: `bind:property={expression}` or `bind:property` (shorthand when names match) ```svelte ``` Most bindings are two-way. Some are readonly. ## Function bindings Use `bind:property={get, set}` for validation/transformation: ```svelte value, (v) => value = v.toLowerCase()} /> ``` For readonly bindings, set `get` to `null`: ```svelte
    ...
    ``` ## Input bindings ### `bind:value` ```svelte

    {message}

    ``` Numeric inputs coerce to numbers: ```svelte

    {a} + {b} = {a + b}

    ``` Empty/invalid numeric inputs return `undefined`. ### `bind:checked` ```svelte ``` ### `bind:indeterminate` ```svelte
    {#if indeterminate} waiting... {:else if checked} checked {:else} unchecked {/if}
    ``` ### `bind:group` For radio buttons and checkbox groups: ```svelte ``` ### `bind:files` ```svelte ``` ## Select bindings Single select: ```svelte ``` Multiple select: ```svelte ``` ## Media bindings ### `
    {/if} ``` ## Local vs Global Local (default): only play when their block is created/destroyed Global: play when any parent block changes ```svelte {#if x} {#if y}

    fades in and out only when y changes

    fades in and out when x or y change

    {/if} {/if} ``` ## Built-in Transitions Import from `svelte/transition` module. ## Parameters ```svelte {#if visible}
    fades in and out over two seconds
    {/if} ``` ## Custom Functions ```js transition = (node: HTMLElement, params: any, options: { direction: 'in' | 'out' | 'both' }) => { delay?: number, duration?: number, easing?: (t: number) => number, css?: (t: number, u: number) => string, tick?: (t: number, u: number) => void } ``` `t`: 0-1 after easing (1 = natural state) `u`: 1-t ### CSS-based (preferred - runs off main thread): ```svelte {#if visible}
    whooshes in
    {/if} ``` ### Tick-based: ```svelte {#if visible}

    The quick brown fox jumps over the lazy dog

    {/if} ``` ## Events Elements dispatch transition events: - `introstart` - `introend` - `outrostart` - `outroend` ```svelte {#if visible}

    (status = 'intro started')} onoutrostart={() => (status = 'outro started')} onintroend={() => (status = 'intro ended')} onoutroend={() => (status = 'outro ended')} > Flies in and out

    {/if} ``` ## docs/svelte/03-template-syntax/15-in-and-out.md # in: and out: The `in:` and `out:` directives work like [`transition:`](transition) but are unidirectional. Unlike bidirectional transitions, `in` transitions don't reverse when interrupted - they continue playing alongside `out` transitions. ```svelte {#if visible}
    flies in, fades out
    {/if} ``` **Key difference**: If an out transition is aborted, transitions restart from scratch rather than reversing. ## docs/svelte/03-template-syntax/16-animate.md # animate: Animations trigger when keyed each block contents are re-ordered. Only runs when existing item index changes, not on add/remove. Must be on immediate child of keyed each block. ```svelte {#each list as item, index (item)}
  • {item}
  • {/each} ``` ## Animation Parameters ```svelte {#each list as item, index (item)}
  • {item}
  • {/each} ``` ## Custom Animation Functions ```js animation = (node: HTMLElement, { from: DOMRect, to: DOMRect } , params: any) => { delay?: number, duration?: number, easing?: (t: number) => number, css?: (t: number, u: number) => string, tick?: (t: number, u: number) => void } ``` Function receives `node`, `animation` object with `from`/`to` DOMRect properties, and `parameters`. `from` is starting position, `to` is final position after reorder. If returned object has `css` method, Svelte creates web animation. `t` goes from 0 to 1 after easing, `u` equals `1 - t`. ```svelte {#each list as item, index (item)}
    {item}
    {/each} ``` Can also return `tick` function called during animation with same `t`/`u` arguments. > Use `css` over `tick` when possible - web animations run off main thread, preventing jank. ```svelte {#each list as item, index (item)}
    {item}
    {/each} ``` ## docs/svelte/03-template-syntax/17-style.md # style: The `style:` directive provides shorthand for setting multiple styles on an element. ## Basic Usage ```svelte
    ...
    ...
    ``` ## Dynamic Values ```svelte
    ...
    ``` ## Shorthand Form ```svelte
    ...
    ``` ## Multiple Styles ```svelte
    ...
    ``` ## Important Modifier ```svelte
    ...
    ``` ## Precedence `style:` directives take precedence over `style` attributes: ```svelte
    This will be red
    ``` ## docs/svelte/03-template-syntax/18-class.md # class Two ways to set classes: `class` attribute and `class:` directive. ## Attributes Basic usage: ```svelte
    ...
    ``` > Falsy values stringify (`class="false"`), except `undefined`/`null` which omit the attribute. ### Objects and arrays Since Svelte 5.16, `class` accepts objects/arrays using [clsx](https://github.com/lukeed/clsx). **Objects** - truthy keys are added: ```svelte
    ...
    ``` **Arrays** - truthy values combined: ```svelte
    ...
    ``` **Nested arrays/objects** for combining local classes with props: ```svelte ``` Usage: ```svelte ``` **TypeScript** - use `ClassValue` type: ```svelte
    ...
    ``` ## The `class:` directive Legacy conditional class setting: ```svelte
    ...
    ...
    ``` Shorthand when class name matches value: ```svelte
    ...
    ``` > Consider using `class` attribute instead - more powerful and composable. ## docs/svelte/04-styling/01-scoped-styles.md # Scoped styles Svelte components include ` ``` ## Specificity Scoped selectors get +0-1-0 specificity from the scoping class, so component styles override global styles even if global stylesheet loads later. Multiple scoping classes use `:where(.svelte-xyz123)` to avoid further specificity increases. ## Scoped keyframes `@keyframes` names are scoped to components. Animation rules adjust automatically: ```svelte ``` ## docs/svelte/04-styling/02-global-styles.md # Global styles ## :global(...) Apply styles to a single selector globally: ```svelte ``` For global keyframes, prepend with `-global-`: ```svelte ``` ## :global Apply styles to multiple selectors globally using blocks: ```svelte ``` ## docs/svelte/04-styling/03-custom-properties.md # Custom Properties Pass CSS custom properties (static and dynamic) to components: ```svelte ``` This desugars to a wrapper element: ```svelte ``` For SVG elements, uses ``: ```svelte ``` Inside components, use `var()` with fallbacks: ```svelte ``` Custom properties inherit from parent elements. Define on `:root` for global access. > **Note:** Wrapper element won't affect layout but may affect CSS selectors using `>` combinator. ## docs/svelte/04-styling/04-nested-style-elements.md # Nested ` ``` ## docs/svelte/05-special-elements/01-svelte-boundary.md # `` ```svelte ... ``` Guards against errors in part of your app from breaking the whole app. Catches errors during rendering/updating children and `$effect` functions. **Does NOT catch**: Event handlers, `setTimeout`, async work outside rendering. ## Properties ### `failed` Renders when error occurs. Receives `error` and `reset` function: ```svelte {#snippet failed(error, reset)} {/snippet} ``` Can be passed explicitly: `...` ### `onerror` Called with `error` and `reset` arguments. Useful for error reporting: ```svelte report(e)}> ... ``` Or managing error state externally: ```svelte {#if error} {/if} ``` Errors in `onerror` bubble to parent boundary if it exists. ## docs/svelte/05-special-elements/02-svelte-window.md # `` ```svelte ``` Adds event listeners to `window` object. Auto-removes on component destroy. SSR-safe. Must be at component top level, not inside blocks/elements. ## Event Listeners ```svelte ``` ## Bindable Properties ```svelte ``` **Readonly:** `innerWidth`, `innerHeight`, `outerWidth`, `outerHeight`, `online`, `devicePixelRatio` **Writable:** `scrollX`, `scrollY` > **Note:** Page won't scroll to initial bound values. Only subsequent changes trigger scrolling. Use `scrollTo()` in `$effect` if needed. ## docs/svelte/05-special-elements/03-svelte-document.md # `` Adds event listeners and actions to the `document` object. Must be at component top level, never inside blocks or elements. ## Syntax ```svelte ``` ## Usage ```svelte ``` ## Bindable Properties (readonly) - `activeElement` - `fullscreenElement` - `pointerLockElement` - `visibilityState` ## docs/svelte/05-special-elements/04-svelte-body.md # `` ```svelte ``` Adds event listeners to `document.body` for events that don't fire on `window` (like `mouseenter`/`mouseleave`). Also allows [actions](use) on ``. **Requirements:** - Must be at top level of component - Cannot be inside blocks or elements ```svelte ``` ## docs/svelte/05-special-elements/05-svelte-head.md # `` Inserts elements into `document.head`. Must be at component top level, never inside blocks or elements. ```svelte Hello world! ``` During SSR, head content is exposed separately from body content. ## docs/svelte/05-special-elements/06-svelte-element.md # `` ```svelte ``` Renders dynamic elements unknown at author time (e.g., from CMS). ## Basic Usage ```svelte This text cannot appear inside an hr element ``` ## Key Points - Properties and event listeners are applied to the element - Only `bind:this` binding supported - If `this` is nullish, element and children won't render - Void elements (br, hr) with children throw runtime error in dev - `this` must be valid DOM element tag ## Namespace Control ```svelte ``` Use `xmlns` when Svelte can't infer correct namespace. ## docs/svelte/05-special-elements/07-svelte-options.md # `` ```svelte ``` Specifies per-component compiler options. ## Options - `runes={true}` โ€” forces runes mode - `runes={false}` โ€” forces legacy mode - `namespace="..."` โ€” "html" (default), "svg", or "mathml" - `customElement={...}` โ€” custom element options, or string for tag name - `css="injected"` โ€” injects styles inline (`