pull/8995/head
Puru 3 years ago
parent e5db07c1c1
commit 2a4437c0c6

@ -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 --->
<script context="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.
```svelte
<!--- file: App.svelte --->
<div>
<style>
/* this style tag will be inserted as-is */

@ -116,7 +116,6 @@ Text can also contain JavaScript expressions:
<!-- prettier-ignore -->
```svelte
<!--- file: App.svelte --->
<h1>Hello {name}!</h1>
<p>{a} + {b} = {a + b}.</p>

@ -5,21 +5,23 @@ title: Logic blocks
## {#if ...}
```svelte
<!--- copy: false --->
{#if expression}...{/if}
```
```svelte
<!--- copy: false --->
{#if expression}...{:else if expression}...{/if}
```
```svelte
<!--- copy: false --->
{#if expression}...{:else}...{/if}
```
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 ...}
```svelte
<!--- copy: false --->
{#await expression}...{:then name}...{:catch name}...{/await}
```
```svelte
<!--- copy: false --->
{#await expression}...{:then name}...{/await}
```
```svelte
<!--- copy: false --->
{#await expression then name}...{/await}
```
```svelte
<!--- copy: false --->
{#await expression catch name}...{/await}
```
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}
<div transition: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.
```svelte
<!--- file: App.svelte --->
{#key value}
<Component />
{/key}

@ -5,6 +5,7 @@ title: Special tags
## {@html ...}
```svelte
<!--- copy: false --->
{@html expression}
```
@ -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 --->
<div class="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
## {@const ...}
```svelte
<!--- copy: false --->
{@const assignment}
```
The `{@const ...}` tag defines a local constant.
```svelte
<!--- file: App.svelte --->
<script>
export let boxes;
</script>

@ -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 --->
<button on: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 --->
<form on: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 --->
<input bind:value={name} />
<textarea bind: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 --->
<input bind:value />
<!-- equivalent to
<input bind: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 --->
<input type="number" bind:value={num} />
<input type="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.
```svelte
<!--- file: App.svelte --->
<label for="avatar">Upload a picture:</label>
<input accept="image/png, image/jpeg" bind:files id="avatar" name="avatar" type="file" />
```
@ -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 --->
<select bind:value={selected}>
<option value={a}>a</option>
<option value={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 --->
<select multiple bind:value={fillings}>
<option value="Rice">Rice</option>
<option value="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 --->
<select multiple bind: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 --->
<div contenteditable="true" bind:innerHTML={html} />
```
`<details>` elements support binding to the `open` property.
```svelte
<!--- file: App.svelte --->
<details bind: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
- `offsetHeight`
```svelte
<!--- file: App.svelte --->
<div bind:offsetWidth={width} bind:offsetHeight={height}>
<Chart {width} {height} />
</div>
@ -289,13 +277,13 @@ Block-level elements have 4 read-only bindings, measured using a technique simil
## bind:group
```svelte
<!--- copy: false --->
bind:group={variable}
```
Inputs that work together can use `bind:group`.
```svelte
<!--- file: App.svelte --->
<script>
let tortilla = 'Plain';
@ -320,13 +308,13 @@ Inputs that work together can use `bind:group`.
## bind:this
```svelte
<!--- copy: false --->
bind:this={dom_node}
```
To get a reference to a DOM node, use `bind:this`.
```svelte
<!--- file: App.svelte --->
<script>
import { onMount } from 'svelte';
@ -345,17 +333,18 @@ To get a reference to a DOM node, use `bind:this`.
## class:_name_
```svelte
<!--- copy: false --->
class:name={value}
```
```svelte
<!--- copy: false --->
class:name
```
A `class:` directive provides a shorter way of toggling a class on an element.
```svelte
<!--- file: App.svelte --->
<!-- These are equivalent -->
<div class={isActive ? 'active' : ''}>...</div>
<div class:active={isActive}>...</div>
@ -384,7 +373,6 @@ style:property
The `style:` directive provides a shorthand for setting multiple styles on an element.
```svelte
<!--- file: App.svelte --->
<!-- These are equivalent -->
<div style:color="red">...</div>
<div style="color: red;">...</div>
@ -411,14 +399,17 @@ When `style:` directives are combined with `style` attributes, the directives wi
## use:_action_
```svelte
<!--- copy: false --->
use:action
```
```svelte
<!--- copy: false --->
use:action={parameters}
```
```ts
/// copy: false
// @noErrors
action = (node: HTMLElement, parameters: any) => {
update?: (parameters: any) => void,
@ -429,7 +420,6 @@ action = (node: HTMLElement, parameters: any) => {
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.
## transition:_fn_
```svelte
<!--- copy: false --->
transition:fn
```
```svelte
<!--- copy: false --->
transition:fn={params}
```
```svelte
<!--- copy: false --->
transition:fn|global
```
```svelte
<!--- copy: false --->
transition:fn|global={params}
```
```svelte
<!--- copy: false --->
transition:fn|local
```
```svelte
<!--- copy: false --->
transition:fn|local={params}
```
```js
/// copy: false
// @noErrors
transition = (node: HTMLElement, params: any, options: { direction: 'in' | 'out' | 'both' }) => {
delay?: number,
@ -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}
<div transition: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}
<div transition: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}
<div in:fly out:fade>flies in, fades out</div>
{/if}
@ -727,14 +729,17 @@ Unlike with `transition:`, transitions applied with `in:` and `out:` are not bid
## animate:_fn_
```svelte
<!--- copy: false --->
animate:name
```
```svelte
<!--- copy: false --->
animate:name={params}
```
```js
/// copy: false
// @noErrors
animation = (node: HTMLElement, { from: DOMRect, to: DOMRect } , params: any) => {
delay?: number,
@ -746,6 +751,7 @@ animation = (node: HTMLElement, { from: DOMRect, to: DOMRect } , params: any) =>
```
```ts
/// copy: false
// @noErrors
DOMRect {
bottom: number,
@ -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)}
<li animate: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)}
<li animate: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.
```svelte
<!--- file: App.svelte --->
<script>
import { cubicOut } from 'svelte/easing';

@ -5,13 +5,13 @@ title: Component directives
## on:_eventname_
```svelte
<!--- copy: false --->
on:eventname={handler}
```
Components can emit events using [`createEventDispatcher`](/docs/svelte#createeventdispatcher) or by forwarding DOM events.
```svelte
<!--- file: SomeComponent.svelte --->
<script>
import { createEventDispatcher } from 'svelte';
@ -28,20 +28,19 @@ Components can emit events using [`createEventDispatcher`](/docs/svelte#createev
Listening for component events looks the same as listening for DOM events:
```svelte
<!--- file: App.svelte --->
<SomeComponent on:whatever={handler} />
```
As with DOM events, if the `on:` directive is used without a value, the event will be forwarded, meaning that a consumer can listen for it.
```svelte
<!--- file: App.svelte --->
<SomeComponent on:whatever />
```
## --style-props
```svelte
<!--- copy: false --->
--style-props="anycssvalue"
```
@ -50,14 +49,12 @@ You can also pass styles as props to components for the purposes of theming, usi
Svelte's implementation is essentially syntactic sugar for adding a wrapper element. This example:
```svelte
<!--- file: App.svelte --->
<Slider bind:value min={0} --rail-color="black" --track-color="rgb(0, 0, 255)" />
```
Desugars to this:
```svelte
<!--- file: App.svelte --->
<div style="display: contents; --rail-color: black; --track-color: rgb(0, 0, 255)">
<Slider bind:value min={0} max={100} />
</div>
@ -68,7 +65,6 @@ Desugars to this:
For SVG namespace, the example above desugars into using `<g>` instead:
```svelte
<!--- file: App.svelte --->
<g style="--rail-color: black; --track-color: rgb(0, 0, 255)">
<Slider bind:value min={0} max={100} />
</g>
@ -79,7 +75,6 @@ For SVG namespace, the example above desugars into using `<g>` instead:
Svelte's CSS Variables support allows for easily themeable components:
```svelte
<!--- file: Slider.svelte --->
<style>
.potato-slider-rail {
background-color: var(--rail-color, var(--theme-color, 'purple'));
@ -99,7 +94,6 @@ html {
Or override it at the consumer level:
```svelte
<!--- file: App.svelte --->
<Slider --rail-color="goldenrod" />
```
@ -112,7 +106,6 @@ bind:property={variable}
You can bind to component props using the same syntax as for elements.
```svelte
<!--- file: App.svelte --->
<Keypad bind:value={pin} />
```
@ -121,13 +114,13 @@ While Svelte props are reactive without binding, that reactivity only flows down
## bind:this
```svelte
<!--- copy: false --->
bind:this={component_instance}
```
Components also support `bind:this`, allowing you to interact with component instances programmatically.
```svelte
<!--- file: App.svelte --->
<ShoppingCart bind:this={cart} />
<button on:click={() => cart.empty()}> Empty shopping cart </button>

@ -177,7 +177,6 @@ The `<svelte:component>` element renders a component dynamically, using the comp
If `this` is falsy, no component is rendered.
```svelte
<!--- file: App.svelte --->
<svelte:component this={currentSelection.component} foo={bar} />
```
@ -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>
<meta name="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.
```svelte
<!--- file: App.svelte --->
<script>
function callbackFunction(event) {
console.log(`Notify fired! Detail: ${event.detail}`);
@ -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`.
```svelte
<!--- file: App.svelte --->
<script>
import { createEventDispatcher } from 'svelte';

@ -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`.
```js
/// file: store.js
```ts
// @filename: ambient.d.ts
import { type Writable } from 'svelte/store';
@ -131,13 +127,17 @@ export {};
// ---cut---
import { derived } from 'svelte/store';
const delayed = derived(a, ($a, set) => {
const delayed = derived(
a,
($a, set) => {
setTimeout(() => set($a), 1000);
}, 2000);
},
2000
);
const delayedIncrement = derived(a, ($a, set, update) => {
set($a);
setTimeout(() => update(x => x + 1), 1000);
setTimeout(() => update((x) => x + 1), 1000);
// every time $a produces a value, this produces two
// values, $a immediately and then $a + 1 a second later
});
@ -145,8 +145,7 @@ const delayedIncrement = derived(a, ($a, set, update) => {
If you return a function from the callback, it will be called when a) the callback runs again, or b) the last subscriber unsubscribes.
```js
/// file: store.js
```ts
// @filename: ambient.d.ts
import { type Writable } from 'svelte/store';
@ -178,7 +177,6 @@ const tick = derived(
In both cases, an array of arguments can be passed as the first argument instead of a single store.
```ts
/// file: store.js
// @filename: ambient.d.ts
import { type Writable } from 'svelte/store';
@ -208,7 +206,6 @@ const delayed = derived([a, b], ([$a, $b], set) => {
This simple helper function makes a store readonly. You can still subscribe to the changes from the original one using this new readable store.
```js
/// file: store.js
import { readonly, writable } from 'svelte/store';
const writableStore = writable(1);
@ -229,8 +226,7 @@ Generally, you should read the value of a store by subscribing to it and using t
> This works by creating a subscription, reading the value, then unsubscribing. It's therefore not recommended in hot code paths.
```js
/// file: store.js
```ts
// @filename: ambient.d.ts
import { type Writable } from 'svelte/store';

@ -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).
```ts
/// file: motion.js
// @filename: ambient.d.ts
declare global {
var $size: number;

@ -9,14 +9,17 @@ The `svelte/transition` module exports seven functions: `fade`, `blur`, `fly`, `
> EXPORT_SNIPPET: svelte/transition#fade
```svelte
<!--- copy: false --->
transition:fade={params}
```
```svelte
<!--- copy: false --->
in:fade={params}
```
```svelte
<!--- copy: false --->
out:fade={params}
```
@ -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.
```svelte
<!--- file: App.svelte --->
<script>
import { crossfade } from 'svelte/transition';
import { quintOut } from 'svelte/easing';

@ -9,6 +9,7 @@ The `svelte/animate` module exports one function for use with Svelte [animations
> EXPORT_SNIPPET: svelte/animate#flip
```svelte
<!--- copy: false --->
animate:flip={params}
```
@ -28,7 +29,6 @@ The `flip` function calculates the start and end position of an element and anim
You can see a full example on the [animations tutorial](https://learn.svelte.dev/tutorial/animate).
```svelte
<!--- file: App.svelte --->
<script>
import { flip } from 'svelte/animate';
import { quintOut } from 'svelte/easing';

@ -5,7 +5,6 @@ title: svelte/action
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`:
```svelte
<!--- file: App.svelte --->
<script>
/**
* @type {import('svelte/action').Action<HTMLDivElement, { prop: any }, { 'on:emit': (e: CustomEvent<string>) => void }>}

@ -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.
```js
/// file: preprocess-example.js
```ts
// @filename: ambient.d.ts
declare global {
var source: string;

@ -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.
```svelte
<!--- file: App.svelte --->
<svelte:options
customElement={{
tag: 'custom-element',

@ -33,7 +33,6 @@ You can use prettier with the [prettier-plugin-svelte](https://www.npmjs.com/pac
In editors which use the Svelte Language Server you can document Components, functions and exports using specially formatted comments.
````svelte
<!--- file: App.svelte --->
<script>
/** What should we call the user? */
export let name = 'world';

@ -50,7 +50,6 @@ If you're using tools like Rollup or Webpack instead, install their respective S
To use TypeScript inside your Svelte components, add `lang="ts"` to your `script` tags:
```svelte
<!--- file: App.svelte --->
<script lang="ts">
let name: string = 'world';
@ -75,7 +74,6 @@ Props can be typed directly on the `export let` statement:
Slot and slot prop types are inferred from the types of the slot props passed to them:
```svelte
<!--- file: App.svelte --->
<script lang="ts">
export let name: string;
</script>
@ -94,7 +92,6 @@ Slot and slot prop types are inferred from the types of the slot props passed to
Events can be typed with `createEventDispatcher`:
```svelte
<!--- file: App.svelte --->
<script lang="ts">
import { createEventDispatcher } from 'svelte';
@ -147,7 +144,7 @@ Since Svelte version 4.2 / `svelte-check` version 3.5 / VS Code extension versio
```ts
/// file: additional-svelte-typings.d.ts
import { HTMLButtonAttributes } from 'svelte/elements'
import { HTMLButtonAttributes } from 'svelte/elements';
declare module 'svelte/elements' {
export interface SvelteHTMLElements {
@ -156,7 +153,7 @@ declare module 'svelte/elements' {
// allows for more granular control over what element to add the typings to
export interface HTMLButtonAttributes {
'veryexperimentalattribute'?: string;
veryexperimentalattribute?: string;
}
}
@ -176,7 +173,6 @@ A few features are missing from taking full advantage of TypeScript in more adva
You cannot use TypeScript in your template's markup. For example, the following does not work:
```svelte
<!--- file: App.svelte --->
<script lang="ts">
let count = 10;
</script>
@ -193,7 +189,6 @@ You cannot use TypeScript in your template's markup. For example, the following
You cannot type your reactive declarations with TypeScript in the way you type a variable. For example, the following does not work:
```svelte
<!--- file: App.svelte --->
<script lang="ts">
let count = 0;
@ -204,7 +199,6 @@ You cannot type your reactive declarations with TypeScript in the way you type a
You cannot add a `: TYPE` because it's invalid syntax in this position. Instead, you can move the definition to a `let` statement just above:
```svelte
<!--- file: App.svelte --->
<script lang="ts">
let count = 0;

File diff suppressed because it is too large Load Diff

@ -18,7 +18,7 @@
},
"dependencies": {
"@jridgewell/sourcemap-codec": "^1.4.15",
"@supabase/supabase-js": "^2.33.1",
"@supabase/supabase-js": "^2.33.2",
"@sveltejs/repl": "0.6.0",
"cookie": "^0.5.0",
"devalue": "^4.3.2",
@ -30,20 +30,20 @@
"@resvg/resvg-js": "^2.4.1",
"@sveltejs/adapter-vercel": "^3.0.3",
"@sveltejs/kit": "^1.24.1",
"@sveltejs/site-kit": "6.0.0-next.40",
"@sveltejs/vite-plugin-svelte": "^2.4.5",
"@sveltejs/site-kit": "6.0.0-next.44",
"@sveltejs/vite-plugin-svelte": "^2.4.6",
"@types/cookie": "^0.5.2",
"@types/node": "^20.5.9",
"browserslist": "^4.21.10",
"degit": "^2.8.4",
"dotenv": "^16.3.1",
"jimp": "^0.22.10",
"lightningcss": "^1.21.7",
"lightningcss": "^1.21.8",
"magic-string": "^0.30.3",
"marked": "^8.0.1",
"marked": "^9.0.0",
"prettier": "^3.0.3",
"prettier-plugin-svelte": "^3.0.3",
"sass": "^1.66.1",
"sass": "^1.67.0",
"satori": "^0.10.4",
"satori-html": "^0.3.2",
"shelljs": "^0.8.5",

@ -8,7 +8,7 @@ import { renderContentMarkdown, slugify } from '@sveltejs/site-kit/markdown';
*/
export const render_content = (filename, body) =>
renderContentMarkdown(filename, body, {
cacheCodeSnippets: true,
cacheCodeSnippets: false,
modules,
resolveTypeLinks: (module_name, type_name) => {

Loading…
Cancel
Save