@ -7,7 +7,6 @@ Components are the building blocks of Svelte applications. They are written into
All three sections — script, styles and markup — are optional.
```svelte
<!--- file: App.svelte --->
<script>
// logic goes here
</script>
@ -28,7 +27,6 @@ A `<script>` block contains JavaScript that runs when a component instance is cr
Svelte uses the `export` keyword to mark a variable declaration as a _property_ or _prop_, which means it becomes accessible to consumers of the component (see the section on [attributes and props](/docs/basic-markup#attributes-and-props) for more information).
```svelte
<!--- file: App.svelte --->
<script>
export let foo;
@ -43,7 +41,6 @@ You can specify a default initial value for a prop. It will be used if the compo
In development mode (see the [compiler options](/docs/svelte-compiler#compile)), a warning will be printed if no default initial value is provided and the consumer does not specify a value. To squelch this warning, ensure that a default initial value is specified, even if it is `undefined`.
```svelte
<!--- file: App.svelte --->
<script>
export let bar = 'optional default initial value';
export let baz = undefined;
@ -91,7 +88,6 @@ To change component state and trigger a re-render, just assign to a locally decl
Update expressions (`count += 1`) and property assignments (`obj.x = y`) have the same effect.
```svelte
<!--- file: App.svelte --->
<script>
let count = 0;
@ -106,7 +102,6 @@ Update expressions (`count += 1`) and property assignments (`obj.x = y`) have th
Because Svelte's reactivity is based on assignments, using array methods like `.push()` and `.splice()` won't automatically trigger updates. A subsequent assignment is required to trigger the update. This and more details can also be found in the [tutorial](https://learn.svelte.dev/tutorial/updating-arrays-and-objects).
```svelte
<!--- file: App.svelte --->
<script>
let arr = [0, 1];
@ -123,7 +118,6 @@ Because Svelte's reactivity is based on assignments, using array methods like `.
Svelte's `<script>` blocks are run only when the component is created, so assignments within a `<script>` block are not automatically run again when a prop updates. If you'd like to track changes to a prop, see the next example in the following section.
```svelte
<!--- file: App.svelte --->
<script>
export let person;
// this will only set `name` on component creation
@ -137,7 +131,6 @@ Svelte's `<script>` blocks are run only when the component is created, so assign
Any top-level statement (i.e. not inside a block or a function) can be made reactive by prefixing it with the `$:` [JS label syntax](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/label). Reactive statements run after other script code and before the component markup is rendered, whenever the values that they depend on have changed.
```svelte
<!--- file: App.svelte --->
<script>
export let title;
export let person;
@ -184,7 +177,6 @@ Total: {total}
It is important to note that the reactive blocks are ordered via simple static analysis at compile time, and all the compiler looks at are the variables that are assigned to and used within the block itself, not in any functions called by them. This means that `yDependent` will not be updated when `x` is updated in the following example:
```svelte
<!--- file: App.svelte --->
<script>
let x = 0;
let y = 0;
@ -229,7 +221,6 @@ Note that the store must be declared at the top level of the component — not i
Local variables (that do not represent store values) must _not_ have a `$` prefix.
```svelte
<!--- file: App.svelte --->
<script>
import { writable } from 'svelte/store';
@ -270,7 +261,6 @@ You cannot `export default`, since the default export is the component itself.
> Variables defined in `module` scripts are not reactive — reassigning them will not trigger a rerender even though the variable itself will update. For values shared between multiple components, consider using a [store](/docs/svelte-store).
```svelte
<!--- file: App.svelte --->
<scriptcontext="module">
let totalComponents = 0;
@ -294,7 +284,6 @@ CSS inside a `<style>` block will be scoped to that component.
This works by adding a class to affected elements, which is based on a hash of the component styles (e.g. `svelte-123xyz`).
```svelte
<!--- file: App.svelte --->
<style>
p {
/* this will only affect <p> elements in this component */
@ -306,7 +295,6 @@ This works by adding a class to affected elements, which is based on a hash of t
To apply styles to a selector globally, use the `:global(...)` modifier.
```svelte
<!--- file: App.svelte --->
<style>
:global(body) {
/* this will apply to <body> */
@ -336,7 +324,6 @@ If you want to make @keyframes that are accessible globally, you need to prepend
The `-global-` part will be removed when compiled, and the keyframe then be referenced using just `my-animation-name` elsewhere in your code.
```svelte
<!--- file: App.svelte --->
<style>
@keyframes -global-my-animation-name {
/* code goes here */
@ -351,7 +338,6 @@ However, it is possible to have `<style>` tag nested inside other elements or lo
In that case, the `<style>` tag will be inserted as-is into the DOM, no scoping or processing will be done on the `<style>` tag.
Content that is conditionally rendered can be wrapped in an if block.
```svelte
<!--- file: App.svelte --->
{#if answer === 42}
<p>what was the question?</p>
{/if}
@ -28,7 +30,6 @@ Content that is conditionally rendered can be wrapped in an if block.
Additional conditions can be added with `{:else if expression}`, optionally ending in an `{:else}` clause.
```svelte
<!--- file: App.svelte --->
{#if porridge.temperature > 100}
<p>too hot!</p>
{:else if 80 > porridge.temperature}
@ -43,29 +44,33 @@ Additional conditions can be added with `{:else if expression}`, optionally endi
## {#each ...}
```svelte
<!--- copy: false --->
{#each expression as name}...{/each}
```
```svelte
<!--- copy: false --->
{#each expression as name, index}...{/each}
```
```svelte
<!--- copy: false --->
{#each expression as name (key)}...{/each}
```
```svelte
<!--- copy: false --->
{#each expression as name, index (key)}...{/each}
```
```svelte
<!--- copy: false --->
{#each expression as name}...{:else}...{/each}
```
Iterating over lists of values can be done with an each block.
```svelte
<!--- file: App.svelte --->
<h1>Shopping list</h1>
<ul>
{#each items as item}
@ -79,7 +84,6 @@ You can use each blocks to iterate over any array or array-like value — that i
An each block can also specify an _index_, equivalent to the second argument in an `array.map(...)` callback:
```svelte
<!--- file: App.svelte --->
{#each items as item, i}
<li>{i + 1}: {item.name} x {item.qty}</li>
{/each}
@ -88,7 +92,6 @@ An each block can also specify an _index_, equivalent to the second argument in
If a _key_ expression is provided — which must uniquely identify each list item — Svelte will use it to diff the list when data changes, rather than adding or removing items at the end. The key can be any object, but strings and numbers are recommended since they allow identity to persist when the objects themselves change.
```svelte
<!--- file: App.svelte --->
{#each items as item (item.id)}
<li>{item.name} x {item.qty}</li>
{/each}
@ -102,7 +105,6 @@ If a _key_ expression is provided — which must uniquely identify each list ite
You can freely use destructuring and rest patterns in each blocks.
```svelte
<!--- file: App.svelte --->
{#each items as { id, name, qty }, i (id)}
<li>{i + 1}: {name} x {qty}</li>
{/each}
@ -119,7 +121,6 @@ You can freely use destructuring and rest patterns in each blocks.
An each block can also have an `{:else}` clause, which is rendered if the list is empty.
```svelte
<!--- file: App.svelte --->
{#each todos as todo}
<p>{todo.text}</p>
{:else}
@ -132,25 +133,28 @@ Since Svelte 4 it is possible to iterate over iterables like `Map` or `Set`. Ite
Await blocks allow you to branch on the three possible states of a Promise — pending, fulfilled or rejected. In SSR mode, only the pending state will be rendered on the server.
```svelte
<!--- file: App.svelte --->
{#await promise}
<!-- promise is pending -->
<p>waiting for the promise to resolve...</p>
@ -166,7 +170,6 @@ Await blocks allow you to branch on the three possible states of a Promise — p
The `catch` block can be omitted if you don't need to render anything when the promise rejects (or no error is possible).
```svelte
<!--- file: App.svelte --->
{#await promise}
<!-- promise is pending -->
<p>waiting for the promise to resolve...</p>
@ -179,7 +182,6 @@ The `catch` block can be omitted if you don't need to render anything when the p
If you don't care about the pending state, you can also omit the initial block.
```svelte
<!--- file: App.svelte --->
{#await promise then value}
<p>The value is {value}</p>
{/await}
@ -188,7 +190,6 @@ If you don't care about the pending state, you can also omit the initial block.
Similarly, if you only want to show the error state, you can omit the `then` block.
```svelte
<!--- file: App.svelte --->
{#await promise catch error}
<p>The error is {error}</p>
{/await}
@ -197,6 +198,7 @@ Similarly, if you only want to show the error state, you can omit the `then` blo
## {#key ...}
```svelte
<!--- copy: false --->
{#key expression}...{/key}
```
@ -205,7 +207,6 @@ Key blocks destroy and recreate their contents when the value of an expression c
This is useful if you want an element to play its transition whenever a value changes.
```svelte
<!--- file: App.svelte --->
{#key value}
<divtransition:fade>{value}</div>
{/key}
@ -214,7 +215,6 @@ This is useful if you want an element to play its transition whenever a value ch
When used around components, this will cause them to be reinstantiated and reinitialised.
@ -15,7 +16,6 @@ The expression should be valid standalone HTML — `{@html "<div>"}content{@html
> Svelte does not sanitize expressions before injecting HTML. If the data comes from an untrusted source, you must sanitize it, or you are exposing your users to an XSS vulnerability.
```svelte
<!--- file: App.svelte --->
<divclass="blog-post">
<h1>{post.title}</h1>
{@html post.content}
@ -25,17 +25,18 @@ The expression should be valid standalone HTML — `{@html "<div>"}content{@html
## {@debug ...}
```svelte
<!--- copy: false --->
{@debug}
```
```svelte
<!--- copy: false --->
{@debug var1, var2, ..., varN}
```
The `{@debug ...}` tag offers an alternative to `console.log(...)`. It logs the values of specific variables whenever they change, and pauses code execution if you have devtools open.
```svelte
<!--- file: App.svelte --->
<script>
let user = {
firstname: 'Ada',
@ -51,7 +52,6 @@ The `{@debug ...}` tag offers an alternative to `console.log(...)`. It logs the
`{@debug ...}` accepts a comma-separated list of variable names (not arbitrary expressions).
```svelte
<!--- file: App.svelte --->
<!-- Compiles -->
{@debug user}
{@debug user1, user2, user3}
@ -68,13 +68,13 @@ The `{@debug}` tag without any arguments will insert a `debugger` statement that
@ -7,10 +7,12 @@ As well as attributes, elements can have _directives_, which control the element
## on:_eventname_
```svelte
<!--- copy: false --->
on:eventname={handler}
```
```svelte
<!--- copy: false --->
on:eventname|modifiers={handler}
```
@ -35,7 +37,6 @@ Use the `on:` directive to listen to DOM events.
Handlers can be declared inline with no performance penalty. As with attributes, directive values may be quoted for the sake of syntax highlighters.
```svelte
<!--- file: App.svelte --->
<buttonon:click={()=> (count += 1)}>
count: {count}
</button>
@ -44,7 +45,6 @@ Handlers can be declared inline with no performance penalty. As with attributes,
Add _modifiers_ to DOM events with the `|` character.
```svelte
<!--- file: App.svelte --->
<formon:submit|preventDefault={handleSubmit}>
<!-- the `submit` event's default is prevented,
so the page won't reload -->
@ -74,7 +74,6 @@ If the `on:` directive is used without a value, the component will _forward_ the
It's possible to have multiple event listeners for the same event:
```svelte
<!--- file: App.svelte --->
<script>
let counter = 0;
function increment() {
@ -93,6 +92,7 @@ It's possible to have multiple event listeners for the same event:
## bind:_property_
```svelte
<!--- copy: false --->
bind:property={variable}
```
@ -101,7 +101,6 @@ Data ordinarily flows down, from parent to child. The `bind:` directive allows d
The simplest bindings reflect the value of a property, such as `input.value`.
```svelte
<!--- file: App.svelte --->
<inputbind:value={name}/>
<textareabind:value={text}/>
@ -111,7 +110,6 @@ The simplest bindings reflect the value of a property, such as `input.value`.
If the name matches the value, you can use a shorthand.
```svelte
<!--- file: App.svelte --->
<inputbind:value/>
<!-- equivalent to
<inputbind:value={value}/>
@ -121,7 +119,6 @@ If the name matches the value, you can use a shorthand.
Numeric input values are coerced; even though `input.value` is a string as far as the DOM is concerned, Svelte will treat it as a number. If the input is empty or invalid (in the case of `type="number"`), the value is `undefined`.
```svelte
<!--- file: App.svelte --->
<inputtype="number"bind:value={num}/>
<inputtype="range"bind:value={num}/>
```
@ -129,7 +126,6 @@ Numeric input values are coerced; even though `input.value` is a string as far a
On `<input>` elements with `type="file"`, you can use `bind:files` to get the [`FileList` of selected files](https://developer.mozilla.org/en-US/docs/Web/API/FileList). It is readonly.
@ -137,7 +133,6 @@ On `<input>` elements with `type="file"`, you can use `bind:files` to get the [`
If you're using `bind:` directives together with `on:` directives, the order that they're defined in affects the value of the bound variable when the event handler is called.
```svelte
<!--- file: App.svelte --->
<script>
let value = 'Hello World';
</script>
@ -156,7 +151,6 @@ Here we were binding to the value of a text input, which uses the `input` event.
A `<select>` value binding corresponds to the `value` property on the selected `<option>`, which can be any value (not just strings, as is normally the case in the DOM).
```svelte
<!--- file: App.svelte --->
<selectbind:value={selected}>
<optionvalue={a}>a</option>
<optionvalue={b}>b</option>
@ -167,7 +161,6 @@ A `<select>` value binding corresponds to the `value` property on the selected `
A `<select multiple>` element behaves similarly to a checkbox group. The bound variable is an array with an entry corresponding to the `value` property of each selected `<option>`.
```svelte
<!--- file: App.svelte --->
<selectmultiplebind:value={fillings}>
<optionvalue="Rice">Rice</option>
<optionvalue="Beans">Beans</option>
@ -179,7 +172,6 @@ A `<select multiple>` element behaves similarly to a checkbox group. The bound v
When the value of an `<option>` matches its text content, the attribute can be omitted.
```svelte
<!--- file: App.svelte --->
<selectmultiplebind:value={fillings}>
<option>Rice</option>
<option>Beans</option>
@ -199,14 +191,12 @@ There are slight differences between each of these, read more about them [here](
<!-- for some reason puts the comment and html on same line -->
<!-- prettier-ignore -->
```svelte
<!--- file: App.svelte --->
<divcontenteditable="true"bind:innerHTML={html}/>
```
`<details>` elements support binding to the `open` property.
```svelte
<!--- file: App.svelte --->
<detailsbind:open={isOpen}>
<summary>Details</summary>
<p>Something small enough to escape casual notice.</p>
@ -263,7 +253,6 @@ Image elements (`<img>`) have two readonly bindings:
- `naturalHeight` (readonly) — the original height of the image, available after the image has loaded
```svelte
<!--- file: App.svelte --->
<img
bind:naturalWidth
bind:naturalHeight
@ -280,7 +269,6 @@ Block-level elements have 4 read-only bindings, measured using a technique simil
Actions are functions that are called when an element is created. They can return an object with a `destroy` method that is called after the element is unmounted:
```svelte
<!--- file: App.svelte --->
<script>
/** @type {import('svelte/action').Action} */
function foo(node) {
@ -451,7 +441,6 @@ An action can have a parameter. If the returned value has an `update` method, it
> Don't worry about the fact that we're redeclaring the `foo` function for every component instance — Svelte will hoist any functions that don't depend on local state out of the component definition.
```svelte
<!--- file: App.svelte --->
<script>
export let bar;
@ -479,30 +468,37 @@ Read more in the [`svelte/action`](/docs/svelte-action) page.
@ -520,7 +516,6 @@ When a block is transitioning out, all elements inside the block, including thos
The `transition:` directive indicates a _bidirectional_ transition, which means it can be smoothly reversed while the transition is in progress.
```svelte
<!--- file: App.svelte --->
{#if visible}
<divtransition:fade>fades in and out</div>
{/if}
@ -529,7 +524,6 @@ The `transition:` directive indicates a _bidirectional_ transition, which means
Transitions are local by default (in Svelte 3, they were global by default). Local transitions only play when the block they belong to is created or destroyed, _not_ when parent blocks are created or destroyed.
```svelte
<!--- file: App.svelte --->
{#if x}
{#if y}
<!-- Svelte 3: <p transition:fade|local> -->
@ -550,7 +544,6 @@ Like actions, transitions can have parameters.
(The double `{{curlies}}` aren't a special syntax; this is an object literal inside an expression tag.)
```svelte
<!--- file: App.svelte --->
{#if visible}
<divtransition:fade={{duration:2000}}>fades in and out over two seconds</div>
{/if}
@ -565,7 +558,6 @@ The `t` argument passed to `css` is a value between `0` and `1` after the `easin
The function is called repeatedly _before_ the transition begins, with different `t` and `u` arguments.
```svelte
<!--- file: App.svelte --->
<script>
import { elasticOut } from 'svelte/easing';
@ -649,7 +641,6 @@ An element with transitions will dispatch the following events in addition to an
- `outroend`
```svelte
<!--- file: App.svelte --->
{#if visible}
<p
transition:fly={{ y: 200, duration: 2000 }}
@ -666,50 +657,62 @@ An element with transitions will dispatch the following events in addition to an
## in:_fn_/out:_fn_
```svelte
<!--- copy: false --->
in:fn
```
```svelte
<!--- copy: false --->
in:fn={params}
```
```svelte
<!--- copy: false --->
in:fn|global
```
```svelte
<!--- copy: false --->
in:fn|global={params}
```
```svelte
<!--- copy: false --->
in:fn|local
```
```svelte
<!--- copy: false --->
in:fn|local={params}
```
```svelte
<!--- copy: false --->
out:fn
```
```svelte
<!--- copy: false --->
out:fn={params}
```
```svelte
<!--- copy: false --->
out:fn|global
```
```svelte
<!--- copy: false --->
out:fn|global={params}
```
```svelte
<!--- copy: false --->
out:fn|local
```
```svelte
<!--- copy: false --->
out:fn|local={params}
```
@ -718,7 +721,6 @@ Similar to `transition:`, but only applies to elements entering (`in:`) or leavi
Unlike with `transition:`, transitions applied with `in:` and `out:` are not bidirectional — an in transition will continue to 'play' alongside the out transition, rather than reversing, if the block is outroed while the transition is in progress. If an out transition is aborted, transitions will restart from scratch.
```svelte
<!--- file: App.svelte --->
{#if visible}
<divin:flyout:fade>flies in, fades out</div>
{/if}
@ -727,14 +729,17 @@ Unlike with `transition:`, transitions applied with `in:` and `out:` are not bid
@ -764,7 +770,6 @@ An animation is triggered when the contents of a [keyed each block](/docs/logic-
Animations can be used with Svelte's [built-in animation functions](/docs/svelte-animate) or [custom animation functions](/docs/element-directives#custom-animation-functions).
```svelte
<!--- file: App.svelte --->
<!-- When `list` is reordered the animation will run-->
{#each list as item, index (item)}
<lianimate:flip>{item}</li>
@ -778,7 +783,6 @@ As with actions and transitions, animations can have parameters.
(The double `{{curlies}}` aren't a special syntax; this is an object literal inside an expression tag.)
```svelte
<!--- file: App.svelte --->
{#each list as item, index (item)}
<lianimate:flip={{delay:500}}>{item}</li>
{/each}
@ -797,7 +801,6 @@ The function is called repeatedly _before_ the animation begins, with different
<!-- TODO: Types -->
```svelte
<!--- file: App.svelte --->
<script>
import { cubicOut } from 'svelte/easing';
@ -831,7 +834,6 @@ A custom animation function can also return a `tick` function, which is called _
> If it's possible to use `css` instead of `tick`, do so — CSS animations can run off the main thread, preventing jank on slower devices.
@ -196,7 +195,6 @@ If `this` has a nullish value, the element and its children will not be rendered
If `this` is the name of a [void element](https://developer.mozilla.org/en-US/docs/Glossary/Void_element) (e.g., `br`) and `<svelte:element>` has child elements, a runtime error will be thrown in development mode.
```svelte
<!--- file: App.svelte --->
<script>
let tag = 'div';
@ -221,7 +219,6 @@ The `<svelte:window>` element allows you to add event listeners to the `window`
Unlike `<svelte:self>`, this element may only appear at the top level of your component and must never be inside a block or element.
```svelte
<!--- file: App.svelte --->
<script>
/** @param {KeyboardEvent} event */
function handleKeydown(event) {
@ -301,7 +298,6 @@ This element makes it possible to insert elements into `document.head`. During s
As with `<svelte:window>`, `<svelte:document>` and `<svelte:body>`, this element may only appear at the top level of your component and must never be inside a block or element.
```svelte
<!--- file: App.svelte --->
<svelte:head>
<title>Hello world!</title>
<metaname="description"content="This is where the description goes for SEO"/>
@ -13,7 +13,6 @@ The `onMount` function schedules a callback to run as soon as the component has
`onMount` does not run inside a [server-side component](/docs/server-side-component-api).
```svelte
<!--- file: App.svelte --->
<script>
import { onMount } from 'svelte';
@ -26,7 +25,6 @@ The `onMount` function schedules a callback to run as soon as the component has
If a function is returned from `onMount`, it will be called when the component is unmounted.
```svelte
<!--- file: App.svelte --->
<script>
import { onMount } from 'svelte';
@ -51,7 +49,6 @@ Schedules a callback to run immediately before the component is updated after an
> The first time the callback runs will be before the initial `onMount`
```svelte
<!--- file: App.svelte --->
<script>
import { beforeUpdate } from 'svelte';
@ -70,7 +67,6 @@ Schedules a callback to run immediately after the component has been updated.
> The first time the callback runs will be after the initial `onMount`
```svelte
<!--- file: App.svelte --->
<script>
import { afterUpdate } from 'svelte';
@ -89,7 +85,6 @@ Schedules a callback to run immediately before the component is unmounted.
Out of `onMount`, `beforeUpdate`, `afterUpdate` and `onDestroy`, this is the only one that runs inside a server-side component.
```svelte
<!--- file: App.svelte --->
<script>
import { onDestroy } from 'svelte';
@ -106,7 +101,6 @@ Out of `onMount`, `beforeUpdate`, `afterUpdate` and `onDestroy`, this is the onl
Returns a promise that resolves once any pending state changes have been applied, or in the next microtask if there are none.
```svelte
<!--- file: App.svelte --->
<script>
import { beforeUpdate, tick } from 'svelte';
@ -127,7 +121,6 @@ Associates an arbitrary `context` object with the current component and the spec
Like lifecycle functions, this must be called during component initialisation.
```svelte
<!--- file: App.svelte --->
<script>
import { setContext } from 'svelte';
@ -144,7 +137,6 @@ Like lifecycle functions, this must be called during component initialisation.
Retrieves the context that belongs to the closest parent component with the specified `key`. Must be called during component initialisation.
```svelte
<!--- file: App.svelte --->
<script>
import { getContext } from 'svelte';
@ -159,7 +151,6 @@ Retrieves the context that belongs to the closest parent component with the spec
Checks whether a given `key` has been set in the context of a parent component. Must be called during component initialisation.
```svelte
<!--- file: App.svelte --->
<script>
import { hasContext } from 'svelte';
@ -176,7 +167,6 @@ Checks whether a given `key` has been set in the context of a parent component.
Retrieves the whole context map that belongs to the closest parent component. Must be called during component initialisation. Useful, for example, if you programmatically create a component and want to pass the existing context to it.
```svelte
<!--- file: App.svelte --->
<script>
import { getAllContexts } from 'svelte';
@ -193,7 +183,6 @@ Creates an event dispatcher that can be used to dispatch [component events](/doc
Component events created with `createEventDispatcher` create a [CustomEvent](https://developer.mozilla.org/en-US/docs/Web/API/CustomEvent). These events do not [bubble](https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Building_blocks/Events#Event_bubbling_and_capture). The `detail` argument corresponds to the [CustomEvent.detail](https://developer.mozilla.org/en-US/docs/Web/API/CustomEvent/detail) property and can contain any type of data.
```svelte
<!--- file: App.svelte --->
<script>
import { createEventDispatcher } from 'svelte';
@ -206,7 +195,6 @@ Component events created with `createEventDispatcher` create a [CustomEvent](htt
Events dispatched from child components can be listened to in their parent. Any data provided when the event was dispatched is available on the `detail` property of the event object.
@ -219,7 +207,6 @@ Events dispatched from child components can be listened to in their parent. Any
Events can be cancelable by passing a third parameter to the dispatch function. The function returns `false` if the event is cancelled with `event.preventDefault()`, otherwise it returns `true`.
@ -62,8 +62,6 @@ Note that the value of a `writable` is lost when it is destroyed, for example wh
Creates a store whose value cannot be set from 'outside', the first argument is the store's initial value, and the second argument to `readable` is the same as the second argument to `writable`.
```ts
/// file: store.js
// ---cut---
import { readable } from 'svelte/store';
const time = readable(new Date(), (set) => {
@ -94,7 +92,6 @@ Derives a store from one or more other stores. The callback runs initially when
In the simplest version, `derived` takes a single store, and the callback returns a derived value.
```ts
/// file: store.js
// @filename: ambient.d.ts
import { type Writable } from 'svelte/store';
@ -115,8 +112,7 @@ The callback can set a value asynchronously by accepting a second argument, `set
In this case, you can also pass a third argument to `derived` — the initial value of the derived store before `set` or `update` is first called. If no initial value is specified, the store's initial value will be `undefined`.
@ -22,7 +22,6 @@ Both functions return a Promise that resolves when the tween completes. If the t
Out of the box, Svelte will interpolate between two numbers, two arrays or two objects (as long as the arrays and objects are the same 'shape', and their 'leaf' properties are also numbers).
```svelte
<!--- file: App.svelte --->
<script>
import { tweened } from 'svelte/motion';
import { cubicOut } from 'svelte/easing';
@ -46,7 +45,6 @@ Out of the box, Svelte will interpolate between two numbers, two arrays or two o
If the initial value is `undefined` or `null`, the first value change will take effect immediately. This is useful when you have tweened values that are based on props, and don't want any motion when the component first renders.
```ts
/// file: motion.js
// @filename: ambient.d.ts
declare global {
var $size: number;
@ -70,7 +68,6 @@ $: $size = big ? 100 : 10;
The `interpolate` option allows you to tween between _any_ arbitrary values. It must be an `(a, b) => t => value` function, where `a` is the starting value, `b` is the target value, `t` is a number between 0 and 1, and `value` is the result. For example, we can use the [d3-interpolate](https://github.com/d3/d3-interpolate) package to smoothly interpolate between two colours.
```svelte
<!--- file: App.svelte --->
<script>
import { interpolateLab } from 'd3-interpolate';
import { tweened } from 'svelte/motion';
@ -105,7 +102,6 @@ A `spring` store gradually changes to its target value based on its `stiffness`
All of the options above can be changed while the spring is in motion, and will take immediate effect.
```js
/// file: motion.js
import { spring } from 'svelte/motion';
const size = spring(100);
@ -119,7 +115,6 @@ As with [`tweened`](/docs/svelte-motion#tweened) stores, `set` and `update` retu
Both `set` and `update` can take a second argument — an object with `hard` or `soft` properties. `{ hard: true }` sets the target value immediately; `{ soft: n }` preserves existing momentum for `n` seconds before settling. `{ soft: true }` is equivalent to `{ soft: 0.5 }`.
```js
/// file: motion.js
import { spring } from 'svelte/motion';
const coords = spring({ x: 50, y: 50 });
@ -137,7 +132,6 @@ coords.update(
[See a full example on the spring tutorial.](https://learn.svelte.dev/tutorial/springs)
```svelte
<!--- file: App.svelte --->
<script>
import { spring } from 'svelte/motion';
@ -154,7 +148,6 @@ coords.update(
If the initial value is `undefined` or `null`, the first value change will take effect immediately, just as with `tweened` values (see above).
@ -31,7 +34,6 @@ Animates the opacity of an element from 0 to the current opacity for `in` transi
You can see the `fade` transition in action in the [transition tutorial](https://learn.svelte.dev/tutorial/transition).
```svelte
<!--- file: App.svelte --->
<script>
import { fade } from 'svelte/transition';
</script>
@ -46,14 +48,17 @@ You can see the `fade` transition in action in the [transition tutorial](https:/
> EXPORT_SNIPPET: svelte/transition#blur
```svelte
<!--- copy: false --->
transition:blur={params}
```
```svelte
<!--- copy: false --->
in:blur={params}
```
```svelte
<!--- copy: false --->
out:blur={params}
```
@ -68,7 +73,6 @@ Animates a `blur` filter alongside an element's opacity.
- `amount` (`number | string`, default 5) - the size of the blur. Supports css units (for example: `"4rem"`). The default unit is `px`
```svelte
<!--- file: App.svelte --->
<script>
import { blur } from 'svelte/transition';
</script>
@ -83,14 +87,17 @@ Animates a `blur` filter alongside an element's opacity.
> EXPORT_SNIPPET: svelte/transition#fly
```svelte
<!--- copy: false --->
transition:fly={params}
```
```svelte
<!--- copy: false --->
in:fly={params}
```
```svelte
<!--- copy: false --->
out:fly={params}
```
@ -109,7 +116,6 @@ x and y use `px` by default but support css units, for example `x: '100vw'` or `
You can see the `fly` transition in action in the [transition tutorial](https://learn.svelte.dev/tutorial/adding-parameters-to-transitions).
```svelte
<!--- file: App.svelte --->
<script>
import { fly } from 'svelte/transition';
import { quintOut } from 'svelte/easing';
@ -129,14 +135,17 @@ You can see the `fly` transition in action in the [transition tutorial](https://
> EXPORT_SNIPPET: svelte/transition#slide
```svelte
<!--- copy: false --->
transition:slide={params}
```
```svelte
<!--- copy: false --->
in:slide={params}
```
```svelte
<!--- copy: false --->
out:slide={params}
```
@ -151,7 +160,6 @@ Slides an element in and out.
* `axis` (`x` | `y`, default `y`) — the axis of motion along which the transition occurs
```svelte
<!--- file: App.svelte --->
<script>
import { slide } from 'svelte/transition';
import { quintOut } from 'svelte/easing';
@ -169,14 +177,17 @@ Slides an element in and out.
> EXPORT_SNIPPET: svelte/transition#scale
```svelte
<!--- copy: false --->
transition:scale={params}
```
```svelte
<!--- copy: false --->
in:scale={params}
```
```svelte
<!--- copy: false --->
out:scale={params}
```
@ -191,7 +202,6 @@ Animates the opacity and scale of an element. `in` transitions animate from an e
- `opacity` (`number`, default 0) - the opacity value to animate out to and in from
```svelte
<!--- file: App.svelte --->
<script>
import { scale } from 'svelte/transition';
import { quintOut } from 'svelte/easing';
@ -209,14 +219,17 @@ Animates the opacity and scale of an element. `in` transitions animate from an e
> EXPORT_SNIPPET: svelte/transition#draw
```svelte
<!--- copy: false --->
transition:draw={params}
```
```svelte
<!--- copy: false --->
in:draw={params}
```
```svelte
<!--- copy: false --->
out:draw={params}
```
@ -232,7 +245,6 @@ Animates the stroke of an SVG element, like a snake in a tube. `in` transitions
The `speed` parameter is a means of setting the duration of the transition relative to the path's length. It is a modifier that is applied to the length of the path: `duration = length / speed`. A path that is 1000 pixels with a speed of 1 will have a duration of `1000ms`, setting the speed to `0.5` will double that duration and setting it to `2` will halve it.
```svelte
<!--- file: App.svelte --->
<script>
import { draw } from 'svelte/transition';
import { quintOut } from 'svelte/easing';
@ -266,7 +278,6 @@ The `crossfade` function creates a pair of [transitions](/docs/element-directive
- `fallback` (`function`) — A fallback [transition](/docs/element-directives#transition-fn) to use for send when there is no matching element being received, and for receive when there is no element being sent.
Actions are functions that are called when an element is created. They can return an object with a `destroy` method that is called after the element is unmounted:
```svelte
<!--- copy: true --->
<script>
/** @type {import('svelte/action').Action} */
function foo(node) {
@ -27,7 +26,6 @@ An action can have a parameter. If the returned value has an `update` method, it
> Don't worry that we're redeclaring the `foo` function for every component instance — Svelte will hoist any functions that don't depend on local state out of the component definition.
```svelte
<!--- file: App.svelte --->
<script>
/** @type {string} */
export let bar;
@ -56,7 +54,6 @@ An action can have a parameter. If the returned value has an `update` method, it
Sometimes actions emit custom events and apply custom attributes to the element they are applied to. To support this, actions typed with `Action` or `ActionReturn` type can have a last parameter, `Attributes`:
@ -90,8 +90,7 @@ Each `markup`, `script` or `style` function must return an object (or a Promise
> Preprocessor functions should return a `map` object whenever possible or else debugging becomes harder as stack traces can't link to the original code correctly.
@ -79,7 +79,6 @@ When constructing a custom element, you can tailor several aspects by defining `
- `extend`: an optional property which expects a function as its argument. It is passed the custom element class generated by Svelte and expects you to return a custom element class. This comes in handy if you have very specific requirements to the life cycle of the custom element or want to enhance the class to for example use [ElementInternals](https://developer.mozilla.org/en-US/docs/Web/API/ElementInternals#examples) for better HTML form integration.