* Fix `use:` actions being recreated when a keyed `{#each}` is reordered ([#4693](https://github.com/sveltejs/svelte/issues/4693))
* Fix `{@html}` when using tags that can only appear inside certain tags ([#4852](https://github.com/sveltejs/svelte/issues/4852))
* Fix reactivity when binding directly to `{#each}` context ([#4879](https://github.com/sveltejs/svelte/issues/4879))
## 3.22.3
* Support default values and trailing commas in destructuring `{#await}` ([#4560](https://github.com/sveltejs/svelte/issues/4560), [#4810](https://github.com/sveltejs/svelte/issues/4810))
* Fix handling of `tweened` store when set using `duration: 0` ([#4799](https://github.com/sveltejs/svelte/issues/4799), [#4846](https://github.com/sveltejs/svelte/issues/4846))
* Fix setting `value` attribute with `bind:group` and attribute spread ([#4803](https://github.com/sveltejs/svelte/issues/4803))
* Fix issue with compound `{#if}` block involving static condition, dynamic condition, and inline component ([#4840](https://github.com/sveltejs/svelte/issues/4840))
* Update a11y warnings per ARIA 1.2 working draft ([#4844](https://github.com/sveltejs/svelte/issues/4844))
## 3.22.2
* Fix compiler exception with `a11y-img-redundant-alt` and value-less `alt` attribute ([#4777](https://github.com/sveltejs/svelte/issues/4777))
## 3.22.1
* Fix compiler exception with `a11y-img-redundant-alt` and dynamic `alt` attribute ([#4770](https://github.com/sveltejs/svelte/issues/4770))
## 3.22.0
* Fix misaligned line numbers in source maps ([#3906](https://github.com/sveltejs/svelte/issues/3906))
* Make setting a `tweened` store using `duration: 0` instantly update the value ([#4399](https://github.com/sveltejs/svelte/issues/4399))
* Fix reactivity with imported values that are then mutated ([#4555](https://github.com/sveltejs/svelte/issues/4555))
* Fix variable name conflict with component called `<Anchor>` ([#4768](https://github.com/sveltejs/svelte/issues/4768))
## 3.21.0
* Support dimension bindings in cross-origin environments ([#2147](https://github.com/sveltejs/svelte/issues/2147))
* Fix several related outro bugs ([#3202](https://github.com/sveltejs/svelte/issues/3202), [#3410](https://github.com/sveltejs/svelte/issues/3410), [#3685](https://github.com/sveltejs/svelte/issues/3685), [#4620](https://github.com/sveltejs/svelte/issues/4620), [#4630](https://github.com/sveltejs/svelte/issues/4630))
* Try using `globalThis` rather than `globals` for the benefit of non-Node servers and web workers ([#3561](https://github.com/sveltejs/svelte/issues/3561), [#4545](https://github.com/sveltejs/svelte/issues/4545))
* Support `{#await ... catch ...}` syntax shorthand ([#3623](https://github.com/sveltejs/svelte/issues/3623))
* Fix attaching of JS debugging comments to HTML comments ([#4565](https://github.com/sveltejs/svelte/issues/4565))
* Fix `<svelte:component/>` within `<slot/>` ([#4597](https://github.com/sveltejs/svelte/issues/4597))
* Fix bug with updating simple `{#if}` blocks ([#4629](https://github.com/sveltejs/svelte/issues/4629))
* Fix issues with `<input type="number">` updates ([#4631](https://github.com/sveltejs/svelte/issues/4631), [#4687](https://github.com/sveltejs/svelte/issues/4687))
* Fix `{#if}` block directly within `<slot/>` ([#4703](https://github.com/sveltejs/svelte/issues/4703))
## 3.20.1
* Fix compiler regression with slots ([#4562](https://github.com/sveltejs/svelte/issues/4562))
## 3.20.0
* Allow destructuring in `{#await}` blocks ([#1851](https://github.com/sveltejs/svelte/issues/1851))
* Allow `<svelte:self>` to be used in a slot ([#2798](https://github.com/sveltejs/svelte/issues/2798))
* Expose object of unknown props in `$$restProps` ([#2930](https://github.com/sveltejs/svelte/issues/2930))
* Prevent passing named slots other than from the top level within a component ([#3385](https://github.com/sveltejs/svelte/issues/3385))
* Allow transitions and animations to work within iframes ([#3624](https://github.com/sveltejs/svelte/issues/3624))
* Fix initialising slot fallbacks when unnecessary ([#3763](https://github.com/sveltejs/svelte/issues/3763))
* Disallow binding directly to `const` variables ([#4479](https://github.com/sveltejs/svelte/issues/4479))
* Fix re-attaching event handlers on keyed `{#each}` blocks ([#4491](https://github.com/sveltejs/svelte/issues/4491))
* Fix updating keyed `{#each}` blocks with `{:else}` ([#4536](https://github.com/sveltejs/svelte/issues/4536), [#4549](https://github.com/sveltejs/svelte/issues/4549))
* Fix hydration of top-level content ([#4542](https://github.com/sveltejs/svelte/issues/4542))
## 3.19.2
* In `dev` mode, display a runtime warning when a component is passed an unexpected slot ([#1020](https://github.com/sveltejs/svelte/issues/1020), [#1447](https://github.com/sveltejs/svelte/issues/1447))
* In `vars` array, correctly indicate whether `module` variables are `mutated` or `reassigned` ([#3215](https://github.com/sveltejs/svelte/issues/3215))
* Fix spread props not updating in certain situations ([#3521](https://github.com/sveltejs/svelte/issues/3521), [#4480](https://github.com/sveltejs/svelte/issues/4480))
* Use the fallback content for slots if they are passed only whitespace ([#4092](https://github.com/sveltejs/svelte/issues/4092))
* Fix bitmask overflow for `{#if}` blocks ([#4263](https://github.com/sveltejs/svelte/issues/4263))
* In `dev` mode, check for unknown props even if the component has no writable props ([#4323](https://github.com/sveltejs/svelte/issues/4323))
* Exclude global variables from `$capture_state` ([#4463](https://github.com/sveltejs/svelte/issues/4463))
* Fix bitmask overflow for slots ([#4481](https://github.com/sveltejs/svelte/issues/4481))
## 3.19.1
* Do not treat modifications to `$$props` as updates to a store called `$props` ([#4368](https://github.com/sveltejs/svelte/issues/4368))
* Deconflict `value` parameter name used in contextual bindings ([#4445](https://github.com/sveltejs/svelte/issues/4445))
* Fix dev mode validation of `{#each}` blocks using strings ([#4450](https://github.com/sveltejs/svelte/issues/4450))
## 3.19.0
* Fix indirect bindings involving elements with spreads ([#3680](https://github.com/sveltejs/svelte/issues/3680))
* Fix indirect bindings involving elements with spreads ([#3680](https://github.com/sveltejs/svelte/issues/3680))
* `$capture_state`/`$inject_state` now act on the component's entire state, rather than its props ([#3822](https://github.com/sveltejs/svelte/pull/3822))
* Warn when using `<Foo/>` and `Foo` is dynamic ([#4331](https://github.com/sveltejs/svelte/issues/4331))
* Display compilation warnings in `svelte/register` in dev mode ([#4364](https://github.com/sveltejs/svelte/issues/4364))
* Fix unneeded updating of keyed each blocks ([#4373](https://github.com/sveltejs/svelte/issues/4373))
* Fix unneeded updating of keyed each blocks ([#4373](https://github.com/sveltejs/svelte/issues/4373))
* Throw runtime error in dev mode for non-array-like values in `{#each}` blocks ([#4408](https://github.com/sveltejs/svelte/issues/4408))
@ -93,7 +93,7 @@ Test samples are kept in `/test/xxx/samples` folder.
#### Running tests
#### Running tests
1. To run test, run `npm run test`
1. To run test, run `npm run test`.
1. To run test for a specific feature, you can use the `-g` (aka `--grep`) option. For example, to only run test involving transitions, run `npm run test -- -g transition`.
1. To run test for a specific feature, you can use the `-g` (aka `--grep`) option. For example, to only run test involving transitions, run `npm run test -- -g transition`.
##### Running solo test
##### Running solo test
@ -130,7 +130,7 @@ The core Svelte team will be monitoring for pull requests. Do help us by making
### Code conventions
### Code conventions
- `snake_case` for internal variable names and methods
- `snake_case` for internal variable names and methods.
- `camelCase` for public variable names and methods.
- `camelCase` for public variable names and methods.
To build the compiler, and all the other modules included in the package:
To build the compiler, and all the other modules included in the package:
@ -80,6 +72,9 @@ npm install && npm run update
npm run dev
npm run dev
```
```
### Is svelte.dev down?
Probably not, but it's possible. If you can't seem to access any `.dev` sites, check out [this SuperUser question and answer](https://superuser.com/q/1413402).
@ -18,7 +18,7 @@ You'll be using the *command line*, also known as the terminal. On Windows, you
The command line is a way to interact with your computer (or another computer! but that's a topic for another time) with more power and control than the GUI (graphical user interface) that most people use day-to-day.
The command line is a way to interact with your computer (or another computer! but that's a topic for another time) with more power and control than the GUI (graphical user interface) that most people use day-to-day.
Once on the command line, you can navigate the filesystem using `ls` to list the contents of your current directory, and `cd` to change the current directory. For example, if you had a `Development` directory of your projects inside your home directory, you would type
Once on the command line, you can navigate the filesystem using `ls`(`dir` on Windows) to list the contents of your current directory, and `cd` to change the current directory. For example, if you had a `Development` directory of your projects inside your home directory, you would type
```bash
```bash
cd Development
cd Development
@ -34,7 +34,7 @@ cd svelte-projects
A full introduction to the command line is out of the scope of this guide, but here are a few more useful commands:
A full introduction to the command line is out of the scope of this guide, but here are a few more useful commands:
* `cd ..` — navigates to the parent of the current directory
* `cd ..` — navigates to the parent of the current directory
* `cat my-file.txt` — on Mac/Linux, lists the contents of `my-file.txt`
* `cat my-file.txt` — on Mac/Linux (`type my-file.txt` on Windows), lists the contents of `my-file.txt`
* `open .` (or `start .` on Windows) — opens the current directory in Finder or File Explorer
* `open .` (or `start .` on Windows) — opens the current directory in Finder or File Explorer
@ -8,7 +8,7 @@ Components are the building blocks of Svelte applications. They are written into
All three sections — script, styles and markup — are optional.
All three sections — script, styles and markup — are optional.
```html
```sv
<script>
<script>
// logic goes here
// logic goes here
</script>
</script>
@ -30,7 +30,7 @@ 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#Attributes_and_props) for more information).
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#Attributes_and_props) for more information).
```html
```sv
<script>
<script>
export let foo;
export let foo;
@ -42,13 +42,13 @@ Svelte uses the `export` keyword to mark a variable declaration as a *property*
---
---
You can specify a default value, which will be used if the component's consumer doesn't specify a prop.
You can specify a default initial value for a prop. It will be used if the component's consumer doesn't specify the prop on the component (or if its initial value is `undefined`) when instantiating the component. Note that whenever a prop is removed by the consumer, its value is set to `undefined` rather than the initial value.
In development mode (see the [compiler options](docs#svelte_compile)), a warning will be printed if no default is provided and the consumer does not specify a value. To squelch this warning, ensure that a default is specified, even if it is `undefined`.
In development mode (see the [compiler options](docs#svelte_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`.
```html
```sv
<script>
<script>
export let bar = 'optional default value';
export let bar = 'optional default initial value';
export let baz = undefined;
export let baz = undefined;
</script>
</script>
```
```
@ -57,7 +57,7 @@ In development mode (see the [compiler options](docs#svelte_compile)), a warning
If you export a `const`, `class` or `function`, it is readonly from outside the component. Function *expressions* are valid props, however.
If you export a `const`, `class` or `function`, it is readonly from outside the component. Function *expressions* are valid props, however.
```html
```sv
<script>
<script>
// these are readonly
// these are readonly
export const thisIs = 'readonly';
export const thisIs = 'readonly';
@ -75,7 +75,7 @@ If you export a `const`, `class` or `function`, it is readonly from outside the
You can use reserved words as prop names.
You can use reserved words as prop names.
```html
```sv
<script>
<script>
let className;
let className;
@ -95,7 +95,7 @@ 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. Options for getting around this can be found in the [tutorial](tutorial/updating-arrays-and-objects).
Because Svelte's reactivity is based on assignments, using array methods like `.push()` and `.splice()` won't automatically trigger updates. Options for getting around this can be found in the [tutorial](tutorial/updating-arrays-and-objects).
```html
```sv
<script>
<script>
let count = 0;
let count = 0;
@ -113,7 +113,7 @@ Because Svelte's reactivity is based on assignments, using array methods like `.
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 immediately before the component updates, whenever the values that they depend on have changed.
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 immediately before the component updates, whenever the values that they depend on have changed.
```html
```sv
<script>
<script>
export let title;
export let title;
@ -132,7 +132,7 @@ Any top-level statement (i.e. not inside a block or a function) can be made reac
If a statement consists entirely of an assignment to an undeclared variable, Svelte will inject a `let` declaration on your behalf.
If a statement consists entirely of an assignment to an undeclared variable, Svelte will inject a `let` declaration on your behalf.
```html
```sv
<script>
<script>
export let num;
export let num;
@ -157,7 +157,7 @@ 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.
Local variables (that do not represent store values) must *not* have a `$` prefix.
```html
```sv
<script>
<script>
import { writable } from 'svelte/store';
import { writable } from 'svelte/store';
@ -175,7 +175,7 @@ Local variables (that do not represent store values) must *not* have a `$` prefi
You can create your own stores without relying on [`svelte/store`](docs#svelte_store), by implementing the *store contract*:
You can create your own stores without relying on [`svelte/store`](docs#svelte_store), by implementing the *store contract*:
@ -199,7 +199,7 @@ 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).
> 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).
```html
```sv
<scriptcontext="module">
<scriptcontext="module">
let totalComponents = 0;
let totalComponents = 0;
@ -225,7 +225,7 @@ 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`).
This works by adding a class to affected elements, which is based on a hash of the component styles (e.g. `svelte-123xyz`).
```html
```sv
<style>
<style>
p {
p {
/* this will only affect <p> elements in this component */
/* this will only affect <p> elements in this component */
@ -238,7 +238,7 @@ 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.
To apply styles to a selector globally, use the `:global(...)` modifier.
A lowercase tag, like `<div>`, denotes a regular HTML element. A capitalised tag, such as `<Widget>` or `<Namespace.Widget>`, indicates a *component*.
A lowercase tag, like `<div>`, denotes a regular HTML element. A capitalised tag, such as `<Widget>` or `<Namespace.Widget>`, indicates a *component*.
```html
```sv
<script>
<script>
import Widget from './Widget.svelte';
import Widget from './Widget.svelte';
</script>
</script>
@ -26,7 +26,7 @@ A lowercase tag, like `<div>`, denotes a regular HTML element. A capitalised tag
By default, attributes work exactly like their HTML counterparts.
By default, attributes work exactly like their HTML counterparts.
```html
```sv
<divclass="foo">
<divclass="foo">
<buttondisabled>can't touch this</button>
<buttondisabled>can't touch this</button>
</div>
</div>
@ -36,7 +36,7 @@ By default, attributes work exactly like their HTML counterparts.
As in HTML, values may be unquoted.
As in HTML, values may be unquoted.
```html
```sv
<inputtype=checkbox>
<inputtype=checkbox>
```
```
@ -44,7 +44,7 @@ As in HTML, values may be unquoted.
Attribute values can contain JavaScript expressions.
Attribute values can contain JavaScript expressions.
```html
```sv
<ahref="page/{p}">page {p}</a>
<ahref="page/{p}">page {p}</a>
```
```
@ -52,15 +52,26 @@ Attribute values can contain JavaScript expressions.
Or they can *be* JavaScript expressions.
Or they can *be* JavaScript expressions.
```html
```sv
<buttondisabled={!clickable}>...</button>
<buttondisabled={!clickable}>...</button>
```
```
---
---
An expression might include characters that would cause syntax highlighting to fail in regular HTML, so quoting the value is permitted. The quotes do not affect how the value is parsed:
Boolean attributes are included on the element if their value is [truthy](https://developer.mozilla.org/en-US/docs/Glossary/Truthy) and excluded if it's [falsy](https://developer.mozilla.org/en-US/docs/Glossary/Falsy).
All other attributes are included unless their value is [nullish](https://developer.mozilla.org/en-US/docs/Glossary/Nullish) (`null` or `undefined`).
```html
```html
<inputrequired={false}placeholder="This input field is not required">
<divtitle={null}>This div has no title attribute</div>
```
---
An expression might include characters that would cause syntax highlighting to fail in regular HTML, so quoting the value is permitted. The quotes do not affect how the value is parsed:
```sv
<buttondisabled="{number !== 42}">...</button>
<buttondisabled="{number !== 42}">...</button>
```
```
@ -68,7 +79,7 @@ An expression might include characters that would cause syntax highlighting to f
When the attribute name and value match (`name={name}`), they can be replaced with `{name}`.
When the attribute name and value match (`name={name}`), they can be replaced with `{name}`.
```html
```sv
<!-- These are equivalent -->
<!-- These are equivalent -->
<buttondisabled={disabled}>...</button>
<buttondisabled={disabled}>...</button>
<button{disabled}>...</button>
<button{disabled}>...</button>
@ -80,7 +91,7 @@ By convention, values passed to components are referred to as *properties* or *p
As with elements, `name={name}` can be replaced with the `{name}` shorthand.
As with elements, `name={name}` can be replaced with the `{name}` shorthand.
```html
```sv
<Widgetfoo={bar}answer={42}text="hello"/>
<Widgetfoo={bar}answer={42}text="hello"/>
```
```
@ -90,7 +101,7 @@ As with elements, `name={name}` can be replaced with the `{name}` shorthand.
An element or component can have multiple spread attributes, interspersed with regular ones.
An element or component can have multiple spread attributes, interspersed with regular ones.
```html
```sv
<Widget{...things}/>
<Widget{...things}/>
```
```
@ -98,10 +109,22 @@ An element or component can have multiple spread attributes, interspersed with r
*`$$props`* references all props that are passed to a component – including ones that are not declared with `export`. It is useful in rare cases, but not generally recommended, as it is difficult for Svelte to optimise.
*`$$props`* references all props that are passed to a component – including ones that are not declared with `export`. It is useful in rare cases, but not generally recommended, as it is difficult for Svelte to optimise.
```html
```sv
<Widget{...$$props}/>
<Widget{...$$props}/>
```
```
---
*`$$restProps`* contains only the props which are *not* declared with `export`. It can be used to pass down other unknown attributes to an element in a component.
```html
<input{...$$restProps}>
```
> The `value` attribute of an `input` element or its children `option` elements must not be set with spread attributes when using `bind:group` or `bind:checked`. Svelte needs to be able to see the element's `value` directly in the markup in these cases so that it can link it to the bound variable.
---
### Text expressions
### Text expressions
@ -113,7 +136,7 @@ An element or component can have multiple spread attributes, interspersed with r
Text can also contain JavaScript expressions:
Text can also contain JavaScript expressions:
```html
```sv
<h1>Hello {name}!</h1>
<h1>Hello {name}!</h1>
<p>{a} + {b} = {a + b}.</p>
<p>{a} + {b} = {a + b}.</p>
```
```
@ -125,7 +148,7 @@ Text can also contain JavaScript expressions:
You can use HTML comments inside components.
You can use HTML comments inside components.
```html
```sv
<!-- this is a comment! -->
<!-- this is a comment! -->
<h1>Hello world</h1>
<h1>Hello world</h1>
```
```
@ -134,7 +157,7 @@ You can use HTML comments inside components.
Comments beginning with `svelte-ignore` disable warnings for the next block of markup. Usually these are accessibility warnings; make sure that you're disabling them for a good reason.
Comments beginning with `svelte-ignore` disable warnings for the next block of markup. Usually these are accessibility warnings; make sure that you're disabling them for a good reason.
```html
```sv
<!-- svelte-ignore a11y-autofocus -->
<!-- svelte-ignore a11y-autofocus -->
<inputbind:value={name}autofocus>
<inputbind:value={name}autofocus>
```
```
@ -156,7 +179,7 @@ Comments beginning with `svelte-ignore` disable warnings for the next block of m
Content that is conditionally rendered can be wrapped in an if block.
Content that is conditionally rendered can be wrapped in an if block.
```html
```sv
{#if answer === 42}
{#if answer === 42}
<p>what was the question?</p>
<p>what was the question?</p>
{/if}
{/if}
@ -166,7 +189,7 @@ 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.
Additional conditions can be added with `{:else if expression}`, optionally ending in an `{:else}` clause.
```html
```sv
{#if porridge.temperature > 100}
{#if porridge.temperature > 100}
<p>too hot!</p>
<p>too hot!</p>
{:else if 80 > porridge.temperature}
{:else if 80 > porridge.temperature}
@ -186,6 +209,9 @@ Additional conditions can be added with `{:else if expression}`, optionally endi
{#each expression as name, index}...{/each}
{#each expression as name, index}...{/each}
```
```
```sv
```sv
{#each expression as name (key)}...{/each}
```
```sv
{#each expression as name, index (key)}...{/each}
{#each expression as name, index (key)}...{/each}
```
```
```sv
```sv
@ -196,7 +222,7 @@ Additional conditions can be added with `{:else if expression}`, optionally endi
Iterating over lists of values can be done with an each block.
Iterating over lists of values can be done with an each block.
```html
```sv
<h1>Shopping list</h1>
<h1>Shopping list</h1>
<ul>
<ul>
{#each items as item}
{#each items as item}
@ -211,7 +237,7 @@ 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:
An each block can also specify an *index*, equivalent to the second argument in an `array.map(...)` callback:
```html
```sv
{#each items as item, i}
{#each items as item, i}
<li>{i + 1}: {item.name} x {item.qty}</li>
<li>{i + 1}: {item.name} x {item.qty}</li>
{/each}
{/each}
@ -221,7 +247,12 @@ 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.
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.
```html
```sv
{#each items as item (item.id)}
<li>{item.name} x {item.qty}</li>
{/each}
<!-- or with additional index value -->
{#each items as item, i (item.id)}
{#each items as item, i (item.id)}
<li>{i + 1}: {item.name} x {item.qty}</li>
<li>{i + 1}: {item.name} x {item.qty}</li>
{/each}
{/each}
@ -231,7 +262,7 @@ If a *key* expression is provided — which must uniquely identify each list ite
You can freely use destructuring and rest patterns in each blocks.
You can freely use destructuring and rest patterns in each blocks.
```html
```sv
{#each items as { id, name, qty }, i (id)}
{#each items as { id, name, qty }, i (id)}
<li>{i + 1}: {name} x {qty}</li>
<li>{i + 1}: {name} x {qty}</li>
{/each}
{/each}
@ -249,7 +280,7 @@ 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.
An each block can also have an `{:else}` clause, which is rendered if the list is empty.
```html
```sv
{#each todos as todo}
{#each todos as todo}
<p>{todo.text}</p>
<p>{todo.text}</p>
{:else}
{:else}
@ -274,7 +305,7 @@ An each block can also have an `{:else}` clause, which is rendered if the list i
Await blocks allow you to branch on the three possible states of a Promise — pending, fulfilled or rejected.
Await blocks allow you to branch on the three possible states of a Promise — pending, fulfilled or rejected.
```html
```sv
{#await promise}
{#await promise}
<!-- promise is pending -->
<!-- promise is pending -->
<p>waiting for the promise to resolve...</p>
<p>waiting for the promise to resolve...</p>
@ -291,7 +322,7 @@ 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).
The `catch` block can be omitted if you don't need to render anything when the promise rejects (or no error is possible).
```html
```sv
{#await promise}
{#await promise}
<!-- promise is pending -->
<!-- promise is pending -->
<p>waiting for the promise to resolve...</p>
<p>waiting for the promise to resolve...</p>
@ -305,7 +336,7 @@ 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.
If you don't care about the pending state, you can also omit the initial block.
```html
```sv
{#await promise then value}
{#await promise then value}
<p>The value is {value}</p>
<p>The value is {value}</p>
{/await}
{/await}
@ -326,7 +357,7 @@ 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 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.
```html
```sv
<divclass="blog-post">
<divclass="blog-post">
<h1>{post.title}</h1>
<h1>{post.title}</h1>
{@html post.content}
{@html post.content}
@ -349,7 +380,7 @@ The `{@debug ...}` tag offers an alternative to `console.log(...)`. It logs the
It accepts a comma-separated list of variable names (not arbitrary expressions).
It accepts a comma-separated list of variable names (not arbitrary expressions).
```html
```sv
<script>
<script>
let user = {
let user = {
firstname: 'Ada',
firstname: 'Ada',
@ -366,7 +397,7 @@ It accepts a comma-separated list of variable names (not arbitrary expressions).
`{@debug ...}` accepts a comma-separated list of variable names (not arbitrary expressions).
`{@debug ...}` accepts a comma-separated list of variable names (not arbitrary expressions).
@ -418,7 +449,7 @@ 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.
Handlers can be declared inline with no performance penalty. As with attributes, directive values may be quoted for the sake of syntax highlighters.
```html
```sv
<buttonon:click="{() => count += 1}">
<buttonon:click="{() => count += 1}">
count: {count}
count: {count}
</button>
</button>
@ -428,7 +459,7 @@ Handlers can be declared inline with no performance penalty. As with attributes,
Add *modifiers* to DOM events with the `|` character.
Add *modifiers* to DOM events with the `|` character.
```html
```sv
<formon:submit|preventDefault={handleSubmit}>
<formon:submit|preventDefault={handleSubmit}>
<!-- the `submit` event's default is prevented,
<!-- the `submit` event's default is prevented,
so the page won't reload -->
so the page won't reload -->
@ -442,6 +473,7 @@ The following modifiers are available:
* `passive` — improves scrolling performance on touch/wheel events (Svelte will add it automatically where it's safe to do so)
* `passive` — improves scrolling performance on touch/wheel events (Svelte will add it automatically where it's safe to do so)
* `capture` — fires the handler during the *capture* phase instead of the *bubbling* phase
* `capture` — fires the handler during the *capture* phase instead of the *bubbling* phase
* `once` — remove the handler after the first time it runs
* `once` — remove the handler after the first time it runs
* `self` — only trigger handler if event.target is the element itself
Modifiers can be chained together, e.g. `on:click|once|capture={...}`.
Modifiers can be chained together, e.g. `on:click|once|capture={...}`.
@ -449,7 +481,7 @@ Modifiers can be chained together, e.g. `on:click|once|capture={...}`.
If the `on:` directive is used without a value, the component will *forward* the event, meaning that a consumer of the component can listen for it.
If the `on:` directive is used without a value, the component will *forward* the event, meaning that a consumer of the component can listen for it.
```html
```sv
<buttonon:click>
<buttonon:click>
The component itself will emit the click event
The component itself will emit the click event
</button>
</button>
@ -459,7 +491,7 @@ 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:
It's possible to have multiple event listeners for the same event:
```html
```sv
<script>
<script>
let counter = 0;
let counter = 0;
function increment() {
function increment() {
@ -486,7 +518,7 @@ 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`.
The simplest bindings reflect the value of a property, such as `input.value`.
```html
```sv
<inputbind:value={name}>
<inputbind:value={name}>
<textareabind:value={text}></textarea>
<textareabind:value={text}></textarea>
@ -497,7 +529,7 @@ The simplest bindings reflect the value of a property, such as `input.value`.
If the name matches the value, you can use a shorthand.
If the name matches the value, you can use a shorthand.
```html
```sv
<!-- These are equivalent -->
<!-- These are equivalent -->
<inputbind:value={value}>
<inputbind:value={value}>
<inputbind:value>
<inputbind:value>
@ -507,7 +539,7 @@ 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`.
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`.
```html
```sv
<inputtype="number"bind:value={num}>
<inputtype="number"bind:value={num}>
<inputtype="range"bind:value={num}>
<inputtype="range"bind:value={num}>
```
```
@ -519,7 +551,7 @@ Numeric input values are coerced; even though `input.value` is a string as far a
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).
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).
```html
```sv
<selectbind:value={selected}>
<selectbind:value={selected}>
<optionvalue={a}>a</option>
<optionvalue={a}>a</option>
<optionvalue={b}>b</option>
<optionvalue={b}>b</option>
@ -531,7 +563,7 @@ A `<select>` value binding corresponds to the `value` property on the selected `
A `<select multiple>` element behaves similarly to a checkbox group.
A `<select multiple>` element behaves similarly to a checkbox group.
```html
```sv
<selectmultiplebind:value={fillings}>
<selectmultiplebind:value={fillings}>
<optionvalue="Rice">Rice</option>
<optionvalue="Rice">Rice</option>
<optionvalue="Beans">Beans</option>
<optionvalue="Beans">Beans</option>
@ -544,7 +576,7 @@ A `<select multiple>` element behaves similarly to a checkbox group.
When the value of an `<option>` matches its text content, the attribute can be omitted.
When the value of an `<option>` matches its text content, the attribute can be omitted.
```html
```sv
<selectmultiplebind:value={fillings}>
<selectmultiplebind:value={fillings}>
<option>Rice</option>
<option>Rice</option>
<option>Beans</option>
<option>Beans</option>
@ -557,7 +589,7 @@ When the value of an `<option>` matches its text content, the attribute can be o
Elements with the `contenteditable` attribute support `innerHTML` and `textContent` bindings.
Elements with the `contenteditable` attribute support `innerHTML` and `textContent` bindings.
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:
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:
```html
```sv
<script>
<script>
function foo(node) {
function foo(node) {
// the node has been mounted in the DOM
// the node has been mounted in the DOM
@ -742,7 +776,7 @@ An action can have parameters. 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.
> 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.
A transition is triggered by an element entering or leaving the DOM as a result of a state change.
A transition is triggered by an element entering or leaving the DOM as a result of a state change.
Elements inside an *outroing* block are kept in the DOM until all current transitions have completed.
When a block is transitioning out, all elements inside the block, including those that do not have their own transitions, are kept in the DOM until every transition in the block has completed.
The `transition:` directive indicates a *bidirectional* transition, which means it can be smoothly reversed while the transition is in progress.
The `transition:` directive indicates a *bidirectional* transition, which means it can be smoothly reversed while the transition is in progress.
```html
```sv
{#if visible}
{#if visible}
<divtransition:fade>
<divtransition:fade>
fades in and out
fades in and out
@ -817,7 +851,7 @@ Like actions, transitions can have parameters.
(The double `{{curlies}}` aren't a special syntax; this is an object literal inside an expression tag.)
(The double `{{curlies}}` aren't a special syntax; this is an object literal inside an expression tag.)
```html
```sv
{#if visible}
{#if visible}
<divtransition:fade="{{ duration: 2000 }}">
<divtransition:fade="{{ duration: 2000 }}">
flies in, fades out over two seconds
flies in, fades out over two seconds
@ -835,7 +869,7 @@ 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.
The function is called repeatedly *before* the transition begins, with different `t` and `u` arguments.
```html
```sv
<script>
<script>
import { elasticOut } from 'svelte/easing';
import { elasticOut } from 'svelte/easing';
@ -866,14 +900,14 @@ A custom transition 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.
> 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.
```html
```sv
<script>
<script>
export let visible = false;
export let visible = false;
function typewriter(node, { speed = 50 }) {
function typewriter(node, { speed = 50 }) {
const valid = (
const valid = (
node.childNodes.length === 1 &&
node.childNodes.length === 1 &&
node.childNodes[0].nodeType === 3
node.childNodes[0].nodeType === Node.TEXT_NODE
);
);
if (!valid) return {};
if (!valid) return {};
@ -912,7 +946,7 @@ An element with transitions will dispatch the following events in addition to an
* `outrostart`
* `outrostart`
* `outroend`
* `outroend`
```html
```sv
{#if visible}
{#if visible}
<p
<p
transition:fly="{{ y: 200, duration: 2000 }}"
transition:fly="{{ y: 200, duration: 2000 }}"
@ -930,7 +964,7 @@ An element with transitions will dispatch the following events in addition to an
Local transitions only play when the block they belong to is created or destroyed, *not* when parent blocks are created or destroyed.
Local transitions only play when the block they belong to is created or destroyed, *not* when parent blocks are created or destroyed.
```html
```sv
{#if x}
{#if x}
{#if y}
{#if y}
<ptransition:fade>
<ptransition:fade>
@ -979,7 +1013,7 @@ 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.
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.
```html
```sv
{#if visible}
{#if visible}
<divin:flyout:fade>
<divin:flyout:fade>
flies in, fades out
flies in, fades out
@ -1028,7 +1062,7 @@ An animation is triggered when the contents of a [keyed each block](docs#each) a
Animations can be used with Svelte's [built-in animation functions](docs#svelte_animate) or [custom animation functions](docs#Custom_animation_functions).
Animations can be used with Svelte's [built-in animation functions](docs#svelte_animate) or [custom animation functions](docs#Custom_animation_functions).
```html
```sv
<!-- When `list` is reordered the animation will run-->
<!-- When `list` is reordered the animation will run-->
{#each list as item, index (item)}
{#each list as item, index (item)}
<lianimate:flip>{item}</li>
<lianimate:flip>{item}</li>
@ -1043,7 +1077,7 @@ 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.)
(The double `{{curlies}}` aren't a special syntax; this is an object literal inside an expression tag.)
```html
```sv
{#each list as item, index (item)}
{#each list as item, index (item)}
<lianimate:flip="{{ delay: 500 }}">{item}</li>
<lianimate:flip="{{ delay: 500 }}">{item}</li>
{/each}
{/each}
@ -1062,7 +1096,7 @@ The `t` argument passed to `css` is a value that goes from `0` and `1` after the
The function is called repeatedly *before* the animation begins, with different `t` and `u` arguments.
The function is called repeatedly *before* the animation begins, with different `t` and `u` arguments.
```html
```sv
<script>
<script>
import { cubicOut } from 'svelte/easing';
import { cubicOut } from 'svelte/easing';
@ -1095,7 +1129,7 @@ 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.
> 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.
```html
```sv
<script>
<script>
import { cubicOut } from 'svelte/easing';
import { cubicOut } from 'svelte/easing';
@ -1135,7 +1169,7 @@ on:eventname={handler}
Components can emit events using [createEventDispatcher](docs#createEventDispatcher), or by forwarding DOM events. Listening for component events looks the same as listening for DOM events:
Components can emit events using [createEventDispatcher](docs#createEventDispatcher), or by forwarding DOM events. Listening for component events looks the same as listening for DOM events:
```html
```sv
<SomeComponenton:whatever={handler}/>
<SomeComponenton:whatever={handler}/>
```
```
@ -1143,7 +1177,7 @@ Components can emit events using [createEventDispatcher](docs#createEventDispatc
As with DOM events, if the `on:` directive is used without a value, the component will *forward* the event, meaning that a consumer of the component can listen for it.
As with DOM events, if the `on:` directive is used without a value, the component will *forward* the event, meaning that a consumer of the component can listen for it.
```html
```sv
<SomeComponenton:whatever/>
<SomeComponenton:whatever/>
```
```
@ -1158,7 +1192,7 @@ bind:property={variable}
You can bind to component props using the same syntax as for elements.
You can bind to component props using the same syntax as for elements.
```html
```sv
<Keypadbind:value={pin}/>
<Keypadbind:value={pin}/>
```
```
@ -1174,7 +1208,7 @@ Components also support `bind:this`, allowing you to interact with component ins
> Note that we can't do `{cart.empty}` since `cart` is `undefined` when the button is first rendered and throws an error.
> Note that we can't do `{cart.empty}` since `cart` is `undefined` when the button is first rendered and throws an error.
```html
```sv
<ShoppingCartbind:this={cart}/>
<ShoppingCartbind:this={cart}/>
<buttonon:click={()=> cart.empty()}>
<buttonon:click={()=> cart.empty()}>
@ -1202,7 +1236,7 @@ Components can have child content, in the same way that elements can.
The content is exposed in the child component using the `<slot>` element, which can contain fallback content that is rendered if no children are provided.
The content is exposed in the child component using the `<slot>` element, which can contain fallback content that is rendered if no children are provided.
```html
```sv
<!-- App.svelte -->
<!-- App.svelte -->
<Widget></Widget>
<Widget></Widget>
@ -1224,7 +1258,7 @@ The content is exposed in the child component using the `<slot>` element, which
Named slots allow consumers to target specific areas. They can also have fallback content.
Named slots allow consumers to target specific areas. They can also have fallback content.
```html
```sv
<!-- App.svelte -->
<!-- App.svelte -->
<Widget>
<Widget>
<h1slot="header">Hello</h1>
<h1slot="header">Hello</h1>
@ -1247,17 +1281,17 @@ Slots can be rendered zero or more times, and can pass values *back* to the pare
The usual shorthand rules apply — `let:item` is equivalent to `let:item={item}`, and `<slot {item}>` is equivalent to `<slot item={item}>`.
The usual shorthand rules apply — `let:item` is equivalent to `let:item={item}`, and `<slot {item}>` is equivalent to `<slot item={item}>`.
```html
```sv
<!-- App.svelte -->
<!-- App.svelte -->
<FancyList{items}let:item={item}>
<FancyList{items}let:prop={thing}>
<div>{item.text}</div>
<div>{thing.text}</div>
</FancyList>
</FancyList>
<!-- FancyList.svelte -->
<!-- FancyList.svelte -->
<ul>
<ul>
{#each items as item}
{#each items as item}
<liclass="fancy">
<liclass="fancy">
<slotitem={item}></slot>
<slotprop={item}></slot>
</li>
</li>
{/each}
{/each}
</ul>
</ul>
@ -1267,10 +1301,10 @@ The usual shorthand rules apply — `let:item` is equivalent to `let:item={item}
Named slots can also expose values. The `let:` directive goes on the element with the `slot` attribute.
Named slots can also expose values. The `let:` directive goes on the element with the `slot` attribute.
@ -1338,7 +1372,7 @@ If `this` is falsy, no component is rendered.
The `<svelte:window>` element allows you to add event listeners to the `window` object without worrying about removing them when the component is destroyed, or checking for the existence of `window` when server-side rendering.
The `<svelte:window>` element allows you to add event listeners to the `window` object without worrying about removing them when the component is destroyed, or checking for the existence of `window` when server-side rendering.
```html
```sv
<script>
<script>
function handleKeydown(event) {
function handleKeydown(event) {
alert(`pressed the ${event.key} key`);
alert(`pressed the ${event.key} key`);
@ -1362,7 +1396,7 @@ You can also bind to the following properties:
All except `scrollX` and `scrollY` are readonly.
All except `scrollX` and `scrollY` are readonly.
```html
```sv
<svelte:windowbind:scrollY={y}/>
<svelte:windowbind:scrollY={y}/>
```
```
@ -1377,7 +1411,7 @@ All except `scrollX` and `scrollY` are readonly.
As with `<svelte:window>`, this element allows you to add listeners to events on `document.body`, such as `mouseenter` and `mouseleave` which don't fire on `window`.
As with `<svelte:window>`, this element allows you to add listeners to events on `document.body`, such as `mouseenter` and `mouseleave` which don't fire on `window`.
```html
```sv
<svelte:body
<svelte:body
on:mouseenter={handleMouseenter}
on:mouseenter={handleMouseenter}
on:mouseleave={handleMouseleave}
on:mouseleave={handleMouseleave}
@ -1395,7 +1429,7 @@ As with `<svelte:window>`, this element allows you to add listeners to events on
This element makes it possible to insert elements into `document.head`. During server-side rendering, `head` content is exposed separately to the main `html` content.
This element makes it possible to insert elements into `document.head`. During server-side rendering, `head` content is exposed separately to the main `html` content.
Schedules a callback to run immediately after the component has been updated.
Schedules a callback to run immediately after the component has been updated.
```html
```sv
<script>
<script>
import { afterUpdate } from 'svelte';
import { afterUpdate } from 'svelte';
@ -104,7 +104,7 @@ Schedules a callback to run once the component is unmounted.
Out of `onMount`, `beforeUpdate`, `afterUpdate` and `onDestroy`, this is the only one that runs inside a server-side component.
Out of `onMount`, `beforeUpdate`, `afterUpdate` and `onDestroy`, this is the only one that runs inside a server-side component.
```html
```sv
<script>
<script>
import { onDestroy } from 'svelte';
import { onDestroy } from 'svelte';
@ -124,7 +124,7 @@ promise: Promise = tick()
Returns a promise that resolves once any pending state changes have been applied, or in the next microtask if there are none.
Returns a promise that resolves once any pending state changes have been applied, or in the next microtask if there are none.
```html
```sv
<script>
<script>
import { beforeUpdate, tick } from 'svelte';
import { beforeUpdate, tick } from 'svelte';
@ -148,7 +148,7 @@ Associates an arbitrary `context` object with the current component and the spec
Like lifecycle functions, this must be called during component initialisation.
Like lifecycle functions, this must be called during component initialisation.
```html
```sv
<script>
<script>
import { setContext } from 'svelte';
import { setContext } from 'svelte';
@ -168,7 +168,7 @@ context: any = getContext(key: any)
Retrieves the context that belongs to the closest parent component with the specified `key`. 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.
```html
```sv
<script>
<script>
import { getContext } from 'svelte';
import { getContext } from 'svelte';
@ -188,7 +188,7 @@ Creates an event dispatcher that can be used to dispatch [component events](docs
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) and are not cancellable with `event.preventDefault()`. 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.
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) and are not cancellable with `event.preventDefault()`. 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.
```html
```sv
<script>
<script>
import { createEventDispatcher } from 'svelte';
import { createEventDispatcher } from 'svelte';
@ -202,7 +202,7 @@ 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.
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.
@ -287,7 +287,9 @@ The second argument to `readable` is the same as the second argument to `writabl
```js
```js
import { readable } from 'svelte/store';
import { readable } from 'svelte/store';
const time = readable(new Date(), set => {
const time = readable(null, set => {
set(new Date());
const interval = setInterval(() => {
const interval = setInterval(() => {
set(new Date());
set(new Date());
}, 1000);
}, 1000);
@ -413,7 +415,7 @@ 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).
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).
```html
```sv
<script>
<script>
import { tweened } from 'svelte/motion';
import { tweened } from 'svelte/motion';
import { cubicOut } from 'svelte/easing';
import { cubicOut } from 'svelte/easing';
@ -452,7 +454,7 @@ $: $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.
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.
```html
```sv
<script>
<script>
import { interpolateLab } from 'd3-interpolate';
import { interpolateLab } from 'd3-interpolate';
import { tweened } from 'svelte/motion';
import { tweened } from 'svelte/motion';
@ -499,7 +501,7 @@ Both `set` and `update` can take a second argument — an object with `hard` or
[See a full example on the spring tutorial.](tutorial/spring)
[See a full example on the spring tutorial.](tutorial/spring)
```html
```sv
<script>
<script>
import { spring } from 'svelte/motion';
import { spring } from 'svelte/motion';
@ -521,7 +523,7 @@ $: $size = big ? 100 : 10;
### `svelte/transition`
### `svelte/transition`
The `svelte/transition` module exports six functions: `fade`, `fly`, `slide`, `scale`, `draw` and `crossfade`. They are for use with svelte [`transitions`](docs#Transitions).
The `svelte/transition` module exports seven functions: `fade`, `blur`, `fly`, `slide`, `scale`, `draw` and `crossfade`. They are for use with Svelte [`transitions`](docs#transition_fn).
#### `fade`
#### `fade`
@ -546,7 +548,7 @@ 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](tutorial/transition).
You can see the `fade` transition in action in the [transition tutorial](tutorial/transition).
```html
```sv
<script>
<script>
import { fade } from 'svelte/transition';
import { fade } from 'svelte/transition';
</script>
</script>
@ -582,7 +584,7 @@ Animates a `blur` filter alongside an element's opacity.
* `opacity` (`number`, default 0) - the opacity value to animate out to and in from
* `opacity` (`number`, default 0) - the opacity value to animate out to and in from
* `amount` (`number`, default 5) - the size of the blur in pixels
* `amount` (`number`, default 5) - the size of the blur in pixels
```html
```sv
<script>
<script>
import { blur } from 'svelte/transition';
import { blur } from 'svelte/transition';
</script>
</script>
@ -621,7 +623,7 @@ Animates the x and y positions and the opacity of an element. `in` transitions a
You can see the `fly` transition in action in the [transition tutorial](tutorial/adding-parameters-to-transitions).
You can see the `fly` transition in action in the [transition tutorial](tutorial/adding-parameters-to-transitions).
```html
```sv
<script>
<script>
import { fly } from 'svelte/transition';
import { fly } from 'svelte/transition';
import { quintOut } from 'svelte/easing';
import { quintOut } from 'svelte/easing';
@ -656,7 +658,7 @@ Slides an element in and out.
* `duration` (`number`, default 400) — milliseconds the transition lasts
* `duration` (`number`, default 400) — milliseconds the transition lasts
* `easing` (`function`, default `cubicOut`) — an [easing function](docs#svelte_easing)
* `easing` (`function`, default `cubicOut`) — an [easing function](docs#svelte_easing)
```html
```sv
<script>
<script>
import { slide } from 'svelte/transition';
import { slide } from 'svelte/transition';
import { quintOut } from 'svelte/easing';
import { quintOut } from 'svelte/easing';
@ -693,7 +695,7 @@ Animates the opacity and scale of an element. `in` transitions animate from an e
* `start` (`number`, default 0) - the scale value to animate out to and in from
* `start` (`number`, default 0) - the scale value to animate out to and in from
* `opacity` (`number`, default 0) - the opacity value to animate out to and in from
* `opacity` (`number`, default 0) - the opacity value to animate out to and in from
```html
```sv
<script>
<script>
import { scale } from 'svelte/transition';
import { scale } from 'svelte/transition';
import { quintOut } from 'svelte/easing';
import { quintOut } from 'svelte/easing';
@ -731,7 +733,7 @@ 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 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.
The `speed` parameter is a means of setting the duration of the transition relative to the path's length. It is 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.
```html
```sv
<script>
<script>
import { draw } from 'svelte/transition';
import { draw } from 'svelte/transition';
import { quintOut } from 'svelte/easing';
import { quintOut } from 'svelte/easing';
@ -758,7 +760,7 @@ The `speed` parameter is a means of setting the duration of the transition relat
### `svelte/animate`
### `svelte/animate`
The `svelte/animate` module exports one function for use with svelte [animations](docs#Animations).
The `svelte/animate` module exports one function for use with Svelte [animations](docs#animate_fn).
#### `flip`
#### `flip`
@ -785,7 +787,7 @@ The `flip` function calculates the start and end position of an element and anim
You can see a full example on the [animations tutorial](tutorial/animate)
You can see a full example on the [animations tutorial](tutorial/animate)
```html
```sv
<script>
<script>
import { flip } from 'svelte/animate';
import { flip } from 'svelte/animate';
import { quintOut } from 'svelte/easing';
import { quintOut } from 'svelte/easing';
@ -804,7 +806,7 @@ You can see a full example on the [animations tutorial](tutorial/animate)
### `svelte/easing`
### `svelte/easing`
Easing functions specificy the rate of change over time and are useful when working with Svelte's built-in transitions and animations as well as the tweened and spring utilities. `svelte/easing` contains 31 named exports, a `linear` ease and 3 variants of 10 different easing functions: `in`, `out` and `inOut`.
Easing functions specify the rate of change over time and are useful when working with Svelte's built-in transitions and animations as well as the tweened and spring utilities. `svelte/easing` contains 31 named exports, a `linear` ease and 3 variants of 10 different easing functions: `in`, `out` and `inOut`.
You can explore the various eases using the [ease visualiser](examples#easing) in the [examples section](examples).
You can explore the various eases using the [ease visualiser](examples#easing) in the [examples section](examples).
@ -973,8 +975,8 @@ app.count += 1;
Svelte components can also be compiled to custom elements (aka web components) using the `customElement: true` compiler option. You should specify a tag name for the component using the `<svelte:options>` [element](docs#svelte_options).
Svelte components can also be compiled to custom elements (aka web components) using the `customElement: true` compiler option. You should specify a tag name for the component using the `<svelte:options>` [element](docs#svelte_options).
A number of [community-maintained preprocessing plugins](https://github.com/sveltejs/integrations#preprocessors) are available to allow you to use Svelte with tools like TypeScript, PostCSS, SCSS, and Less.
You can write your own preprocessor using the `svelte.preprocess` API.
question: I'm new to Svelte. Where should I start?
---
We think the best way to get started is playing through the interactive [Tutorial](https://svelte.dev/tutorial). Each step there is mainly focused on one specific aspect and is easy to follow. You'll be editing and running real Svelte components right in your browser.
Five to ten minutes should be enough to get you up and running. An hour and a half should get you through the entire tutorial.
New features aren't being added to it, and bugs will probably only be fixed if they are extremely nasty or present some sort of security vulnerability.
The documentation is still available [here](https://v2.svelte.dev/guide).
question: How can I get VSCode to syntax-highlight my .svelte files?
---
There is an [official VSCode extension for Svelte](https://marketplace.visualstudio.com/items?itemName=svelte.svelte-vscode), however it is still in the **beta** testing stage, and not all issues have been ironed out.
You need to install a [community supported preprocessor](https://github.com/sveltejs/integrations#preprocessors) such as [svelte-preprocess](https://github.com/kaisermann/svelte-preprocess). Work is ongoing to improve [IDE support](https://github.com/sveltejs/language-tools/issues/83). You can also run type checking from command line with [svelte-check](https://www.npmjs.com/package/svelte-check).
There are several UI component libraries. Find them under the [code section](https://svelte-community.netlify.com/code) of the Svelte Community website.
We don't have a good answer to this yet, but it is a priority. There are a few approaches that people take when testing, but it generally involves compiling the component and mounting it to something and then performing the tests.
You essentially need to create a bundle for each component you're testing (since svelte is a compiler and not a normal library) and then mount them. You can mount to a JSDOM instance, or you can use Puppeteer if you need a real browser, or you can use a tool like Cypress. There is an example of this in the Sapper starter template.
You can use any router lib you want. A lot of people use [page.js](https://github.com/visionmedia/page.js). There's also [navaid](https://github.com/lukeed/navaid), which is very similar.
If you prefer a declarative HTML approach, there's [svelte-routing](https://github.com/EmilTholin/svelte-routing).
If you need hash-based routing on the client side, check out [svelte-spa-router](https://github.com/ItalyPaleAle/svelte-spa-router), or [abstract-state-router](https://github.com/TehShrike/abstract-state-router/), a mature router for business software.
For filesystem-based routing, you can take a look at [Routify](https://routify.dev).
For an official solution, there's nothing that's simply a routing library. There is, however, the official [Sapper](https://sapper.svelte.dev/) framework, a Next.js-style application framework built on Svelte, which includes its own filesystem-based routing.
@ -19,4 +19,6 @@ Add a `<script>` tag that imports `Nested.svelte`...
<Nested/>
<Nested/>
```
```
Notice that even though `Nested.svelte` has a `<p>` element, the styles from `App.svelte` don't leak in.
Notice that even though `Nested.svelte` has a `<p>` element, the styles from `App.svelte` don't leak in.
Also notice that the component name `Nested` is capitalised. This convention has been adopted to allow us to differentiate between user-defined components and regular HTML tags.
We want to get notified of clicks on our `<FancyButton>` — to do that, we just need to forward `click` events on the `<button>` element in `FancyButton.svelte`:
We want to get notified of clicks on our `<CustomButton>` — to do that, we just need to forward `click` events on the `<button>` element in `CustomButton.svelte`:
The `tick` function is unlike other lifecycle functions in that you can call it any time, not just when the component first initialises. It returns a promise that resolves as soon as any pending state changes have been applied to the DOM (or immediately, if there are no pending state changes).
The `tick` function is unlike other lifecycle functions in that you can call it any time, not just when the component first initialises. It returns a promise that resolves as soon as any pending state changes have been applied to the DOM (or immediately, if there are no pending state changes).
When you invalidate component state in Svelte, it doesn't update the DOM immediately. Instead, it waits until the next *microtask* to see if there are any other changes that need to be applied, including in other components. Doing so avoids unnecessary work and allows the browser to batch things more effectively.
When you update component state in Svelte, it doesn't update the DOM immediately. Instead, it waits until the next *microtask* to see if there are any other changes that need to be applied, including in other components. Doing so avoids unnecessary work and allows the browser to batch things more effectively.
You can see that behaviour in this example. Select a range of text and hit the tab key. Because the `<textarea>` value changes, the current selection is cleared and the cursor jumps, annoyingly, to the end. We can fix this by importing `tick`...
You can see that behaviour in this example. Select a range of text and hit the tab key. Because the `<textarea>` value changes, the current selection is cleared and the cursor jumps, annoyingly, to the end. We can fix this by importing `tick`...