Update links

pull/8289/head
Puru Vijay 4 years ago
parent df2bb23af4
commit 92830b077b

@ -28,7 +28,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#template-syntax-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/template-syntax#attributes-and-props) for more information).
```sv
<script>
@ -44,7 +44,7 @@ Svelte uses the `export` keyword to mark a variable declaration as a *property*
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#compile-time-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`.
In development mode (see the [compiler options](/docs/compile-time#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`.
```sv
<script>
@ -71,7 +71,7 @@ If you export a `const`, `class` or `function`, it is readonly from outside the
</script>
```
Readonly props can be accessed as properties on the element, tied to the component using [`bind:this` syntax](/docs#template-syntax-component-directives-bind-this).
Readonly props can be accessed as properties on the element, tied to the component using [`bind:this` syntax](/docs/template-syntax#component-directives-bind-this).
---
@ -174,11 +174,11 @@ Only values which directly appear within the `$:` block will become dependencies
<script>
let x = 0;
let y = 0;
function yPlusAValue(value) {
return value + y;
}
$: total = yPlusAValue(x);
</script>
@ -193,17 +193,18 @@ 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:
```sv
<script>
let x = 0;
let y = 0;
const setY = (value) => {
y = value;
}
$: yDependent = y;
$: setY(x);
</script>
@ -230,7 +231,7 @@ If a statement consists entirely of an assignment to an undeclared variable, Sve
---
A *store* is an object that allows reactive access to a value via a simple *store contract*. The [`svelte/store` module](/docs#run-time-svelte-store) contains minimal store implementations which fulfil this contract.
A _store_ is an object that allows reactive access to a value via a simple _store contract_. The [`svelte/store` module](/docs/run-time#svelte-store) contains minimal store implementations which fulfil this contract.
Any time you have a reference to a store, you can access its value inside a component by prefixing it with the `$` character. This causes Svelte to declare the prefixed variable, subscribe to the store at component initialization and unsubscribe when appropriate.
@ -238,7 +239,7 @@ Assignments to `$`-prefixed variables require that the variable be a writable st
Note that the store must be declared at the top level of the component — not inside an `if` block or a function, for example.
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.
```sv
<script>
@ -261,15 +262,14 @@ Local variables (that do not represent store values) must *not* have a `$` prefi
store = { subscribe: (subscription: (value: any) => void) => (() => void), set?: (value: any) => void }
```
You can create your own stores without relying on [`svelte/store`](/docs#run-time-svelte-store), by implementing the *store contract*:
You can create your own stores without relying on [`svelte/store`](/docs/run-time#svelte-store), by implementing the _store contract_:
1. A store must contain a `.subscribe` method, which must accept as its argument a subscription function. This subscription function must be immediately and synchronously called with the store's current value upon calling `.subscribe`. All of a store's active subscription functions must later be synchronously called whenever the store's value changes.
2. The `.subscribe` method must return an unsubscribe function. Calling an unsubscribe function must stop its subscription, and its corresponding subscription function must not be called again by the store.
3. A store may *optionally* contain a `.set` method, which must accept as its argument a new value for the store, and which synchronously calls all of the store's active subscription functions. Such a store is called a *writable store*.
3. A store may _optionally_ contain a `.set` method, which must accept as its argument a new value for the store, and which synchronously calls all of the store's active subscription functions. Such a store is called a _writable store_.
For interoperability with RxJS Observables, the `.subscribe` method is also allowed to return an object with an `.unsubscribe` method, rather than return the unsubscription function directly. Note however that unless `.subscribe` synchronously calls the subscription (which is not required by the Observable spec), Svelte will see the value of the store as `undefined` until it does.
### &lt;script context="module"&gt;
---
@ -280,7 +280,7 @@ You can `export` bindings from this block, and they will become exports of the c
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#run-time-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/run-time#svelte-store).
```sv
<script context="module">
@ -299,7 +299,6 @@ You cannot `export default`, since the default export is the component itself.
</script>
```
### &lt;style&gt;
---
@ -336,11 +335,11 @@ To apply styles to a selector globally, use the `:global(...)` modifier.
}
p:global(.red) {
/* this will apply to all <p> elements belonging to this
/* this will apply to all <p> elements belonging to this
component with a class of red, even if class="red" does
not initially appear in the markup, and is instead
added at runtime. This is useful when the class
of the element is dynamically applied, for instance
not initially appear in the markup, and is instead
added at runtime. This is useful when the class
of the element is dynamically applied, for instance
when updating the element's classList property directly. */
}
</style>
@ -354,7 +353,9 @@ The `-global-` part will be removed when compiled, and the keyframe then be refe
```html
<style>
@keyframes -global-my-animation-name {...}
@keyframes -global-my-animation-name {
...;
}
</style>
```

@ -2,12 +2,11 @@
title: Template syntax
---
### Tags
---
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_.
```sv
<script>
@ -19,7 +18,6 @@ A lowercase tag, like `<div>`, denotes a regular HTML element. A capitalised tag
</div>
```
### Attributes and props
---
@ -50,7 +48,7 @@ Attribute values can contain JavaScript expressions.
---
Or they can *be* JavaScript expressions.
Or they can _be_ JavaScript expressions.
```sv
<button disabled={!clickable}>...</button>
@ -63,8 +61,8 @@ Boolean attributes are included on the element if their value is [truthy](https:
All other attributes are included unless their value is [nullish](https://developer.mozilla.org/en-US/docs/Glossary/Nullish) (`null` or `undefined`).
```html
<input required={false} placeholder="This input field is not required">
<div title={null}>This div has no title attribute</div>
<input required="{false}" placeholder="This input field is not required" />
<div title="{null}">This div has no title attribute</div>
```
---
@ -87,7 +85,7 @@ When the attribute name and value match (`name={name}`), they can be replaced wi
---
By convention, values passed to components are referred to as *properties* or *props* rather than *attributes*, which are a feature of the DOM.
By convention, values passed to components are referred to as _properties_ or _props_ rather than _attributes_, which are a feature of the DOM.
As with elements, `name={name}` can be replaced with the `{name}` shorthand.
@ -97,7 +95,7 @@ As with elements, `name={name}` can be replaced with the `{name}` shorthand.
---
*Spread attributes* allow many attributes or properties to be passed to an element or component at once.
_Spread attributes_ allow many attributes or properties to be passed to an element or component at once.
An element or component can have multiple spread attributes, interspersed with regular ones.
@ -107,7 +105,7 @@ 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 not generally recommended, as it is difficult for Svelte to optimise. But it can be useful in rare cases for example, when you don't know at compile time what props might be passed to a component.
_`$$props`_ references all props that are passed to a component, including ones that are not declared with `export`. It is not generally recommended, as it is difficult for Svelte to optimise. But it can be useful in rare cases for example, when you don't know at compile time what props might be passed to a component.
```sv
<Widget {...$$props}/>
@ -115,13 +113,12 @@ An element or component can have multiple spread attributes, interspersed with r
---
*`$$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. It shares the same optimisation problems as *`$$props`*, and is likewise not recommended.
_`$$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. It shares the same optimisation problems as _`$$props`_, and is likewise not recommended.
```html
<input {...$$restProps}>
<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.
> Sometimes, the attribute order matters as Svelte sets attributes sequentially in JavaScript. For example, `<input type="range" min="0" max="1" value={0.5} step="0.1"/>`, Svelte will attempt to set the value to `1` (rounding up from 0.5 as the step by default is 1), and then set the step to `0.1`. To fix this, change it to `<input type="range" min="0" max="1" step="0.1" value={0.5}/>`.
@ -169,15 +166,16 @@ Comments beginning with `svelte-ignore` disable warnings for the next block of m
<input bind:value={name} autofocus>
```
### {#if ...}
```sv
{#if expression}...{/if}
```
```sv
{#if expression}...{:else if expression}...{/if}
```
```sv
{#if expression}...{:else}...{/if}
```
@ -206,21 +204,24 @@ Additional conditions can be added with `{:else if expression}`, optionally endi
{/if}
```
### {#each ...}
```sv
{#each expression as name}...{/each}
```
```sv
{#each expression as name, index}...{/each}
```
```sv
{#each expression as name (key)}...{/each}
```
```sv
{#each expression as name, index (key)}...{/each}
```
```sv
{#each expression as name}...{:else}...{/each}
```
@ -242,7 +243,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:
```sv
{#each items as item, i}
@ -252,7 +253,7 @@ 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.
```sv
{#each items as item (item.id)}
@ -295,18 +296,20 @@ An each block can also have an `{:else}` clause, which is rendered if the list i
{/each}
```
### {#await ...}
```sv
{#await expression}...{:then name}...{:catch name}...{/await}
```
```sv
{#await expression}...{:then name}...{/await}
```
```sv
{#await expression then name}...{/await}
```
```sv
{#await expression catch name}...{/await}
```
@ -400,7 +403,7 @@ When used around components, this will cause them to be reinstantiated and reini
In a text expression, characters like `<` and `>` are escaped; however, with HTML expressions, they're not.
The expression should be valid standalone HTML — `{@html "<div>"}content{@html "</div>"}` will *not* work, because `</div>` is not valid HTML. It also will *not* compile Svelte code.
The expression should be valid standalone HTML — `{@html "<div>"}content{@html "</div>"}` will _not_ work, because `</div>` is not valid HTML. It also will _not_ compile Svelte code.
> 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.
@ -411,12 +414,12 @@ The expression should be valid standalone HTML — `{@html "<div>"}content{@html
</div>
```
### {@debug ...}
```sv
{@debug}
```
```sv
{@debug var1, var2, ..., varN}
```
@ -454,8 +457,7 @@ The `{@debug ...}` tag offers an alternative to `console.log(...)`. It logs the
{@debug typeof user === 'object'}
```
The `{@debug}` tag without any arguments will insert a `debugger` statement that gets triggered when *any* state changes, as opposed to the specified variables.
The `{@debug}` tag without any arguments will insert a `debugger` statement that gets triggered when _any_ state changes, as opposed to the specified variables.
### {@const ...}
@ -480,17 +482,16 @@ The `{@const ...}` tag defines a local constant.
`{@const}` is only allowed as direct child of `{#if}`, `{:else if}`, `{:else}`, `{#each}`, `{:then}`, `{:catch}`, `<Component />` or `<svelte:fragment />`.
### Element directives
As well as attributes, elements can have *directives*, which control the element's behaviour in some way.
As well as attributes, elements can have _directives_, which control the element's behaviour in some way.
#### on:*eventname*
#### on:_eventname_
```sv
on:eventname={handler}
```
```sv
on:eventname|modifiers={handler}
```
@ -525,7 +526,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.
```sv
<form on:submit|preventDefault={handleSubmit}>
@ -536,20 +537,20 @@ Add *modifiers* to DOM events with the `|` character.
The following modifiers are available:
* `preventDefault` — calls `event.preventDefault()` before running the handler
* `stopPropagation` — calls `event.stopPropagation()`, preventing the event reaching the next element
* `passive` — improves scrolling performance on touch/wheel events (Svelte will add it automatically where it's safe to do so)
* `nonpassive` — explicitly set `passive: false`
* `capture` — fires the handler during the *capture* phase instead of the *bubbling* phase
* `once` — remove the handler after the first time it runs
* `self` — only trigger handler if `event.target` is the element itself
* `trusted` — only trigger handler if `event.isTrusted` is `true`. I.e. if the event is triggered by a user action.
- `preventDefault` — calls `event.preventDefault()` before running the handler
- `stopPropagation` — calls `event.stopPropagation()`, preventing the event reaching the next element
- `passive` — improves scrolling performance on touch/wheel events (Svelte will add it automatically where it's safe to do so)
- `nonpassive` — explicitly set `passive: false`
- `capture` — fires the handler during the _capture_ phase instead of the _bubbling_ phase
- `once` — remove the handler after the first time it runs
- `self` — only trigger handler if `event.target` is the element itself
- `trusted` — only trigger handler if `event.isTrusted` is `true`. I.e. if the event is triggered by a user action.
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.
```sv
<button on:click>
@ -576,7 +577,7 @@ It's possible to have multiple event listeners for the same event:
<button on:click={increment} on:click={track}>Click me!</button>
```
#### bind:*property*
#### bind:_property_
```sv
bind:property={variable}
@ -712,22 +713,22 @@ Elements with the `contenteditable` attribute support `innerHTML` and `textConte
---
Media elements (`<audio>` and `<video>`) have their own set of bindings — six *readonly* ones...
Media elements (`<audio>` and `<video>`) have their own set of bindings — six _readonly_ ones...
* `duration` (readonly) — the total duration of the video, in seconds
* `buffered` (readonly) — an array of `{start, end}` objects
* `played` (readonly) — ditto
* `seekable` (readonly) — ditto
* `seeking` (readonly) — boolean
* `ended` (readonly) — boolean
- `duration` (readonly) — the total duration of the video, in seconds
- `buffered` (readonly) — an array of `{start, end}` objects
- `played` (readonly) — ditto
- `seekable` (readonly) — ditto
- `seeking` (readonly) — boolean
- `ended` (readonly) — boolean
...and five *two-way* bindings:
...and five _two-way_ bindings:
* `currentTime` — the current playback time in the video, in seconds
* `playbackRate` — how fast or slow to play the video, where 1 is 'normal'
* `paused` — this one should be self-explanatory
* `volume` — a value between 0 and 1
* `muted` — a boolean value indicating whether the player is muted
- `currentTime` — the current playback time in the video, in seconds
- `playbackRate` — how fast or slow to play the video, where 1 is 'normal'
- `paused` — this one should be self-explanatory
- `volume` — a value between 0 and 1
- `muted` — a boolean value indicating whether the player is muted
Videos additionally have readonly `videoWidth` and `videoHeight` bindings.
@ -756,10 +757,10 @@ Videos additionally have readonly `videoWidth` and `videoHeight` bindings.
Block-level elements have 4 read-only bindings, measured using a technique similar to [this one](http://www.backalleycoder.com/2013/03/18/cross-browser-event-based-element-resize-detection/):
* `clientWidth`
* `clientHeight`
* `offsetWidth`
* `offsetHeight`
- `clientWidth`
- `clientHeight`
- `offsetWidth`
- `offsetHeight`
```sv
<div
@ -823,12 +824,12 @@ To get a reference to a DOM node, use `bind:this`.
<canvas bind:this={canvasElement}></canvas>
```
#### class:*name*
#### class:_name_
```sv
class:name={value}
```
```sv
class:name
```
@ -849,14 +850,16 @@ A `class:` directive provides a shorter way of toggling a class on an element.
<div class:active class:inactive={!active} class:isAdmin>...</div>
```
#### style:*property*
#### style:_property_
```sv
style:property={value}
```
```sv
style:property="value"
```
```sv
style:property
```
@ -891,13 +894,12 @@ When `style:` directives are combined with `style` attributes, the directives wi
<div style="color: blue;" style:color="red">This will be red</div>
```
#### use:*action*
#### use:_action_
```sv
use:action
```
```sv
use:action={parameters}
```
@ -957,23 +959,24 @@ An action can have a parameter. If the returned value has an `update` method, it
<div use:foo={bar}></div>
```
#### transition:*fn*
#### transition:_fn_
```sv
transition:fn
```
```sv
transition:fn={params}
```
```sv
transition:fn|local
```
```sv
transition:fn|local={params}
```
```js
transition = (node: HTMLElement, params: any, options: { direction: 'in' | 'out' | 'both' }) => {
delay?: number,
@ -990,7 +993,7 @@ A transition is triggered by an element entering or leaving the DOM as a result
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 been 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.
```sv
{#if visible}
@ -1000,7 +1003,7 @@ The `transition:` directive indicates a *bidirectional* transition, which means
{/if}
```
> By default intro transitions will not play on first render. You can modify this behaviour by setting `intro: true` when you [create a component](/docs#run-time-client-side-component-api).
> By default intro transitions will not play on first render. You can modify this behaviour by setting `intro: true` when you [create a component](/docs/run-time#client-side-component-api).
##### Transition parameters
@ -1024,9 +1027,9 @@ Like actions, transitions can have parameters.
Transitions can use custom functions. If the returned object has a `css` function, Svelte will create a CSS animation that plays on the element.
The `t` argument passed to `css` is a value between `0` and `1` after the `easing` function has been applied. *In* transitions run from `0` to `1`, *out* transitions run from `1` to `0` in other words, `1` is the element's natural state, as though no transition had been applied. The `u` argument is equal to `1 - t`.
The `t` argument passed to `css` is a value between `0` and `1` after the `easing` function has been applied. _In_ transitions run from `0` to `1`, _out_ transitions run from `1` to `0` in other words, `1` is the element's natural state, as though no transition had been applied. The `u` argument is equal to `1 - t`.
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.
```sv
<script>
@ -1055,7 +1058,7 @@ The function is called repeatedly *before* the transition begins, with different
---
A custom transition function can also return a `tick` function, which is called *during* the transition with the same `t` and `u` arguments.
A custom transition function can also return a `tick` function, which is called _during_ the transition with the same `t` and `u` arguments.
> 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.
@ -1099,7 +1102,7 @@ Transition functions also receive a third argument, `options`, which contains in
Available values in the `options` object are:
* `direction` - one of `in`, `out`, or `both` depending on the type of transition
- `direction` - one of `in`, `out`, or `both` depending on the type of transition
##### Transition events
@ -1107,10 +1110,10 @@ Available values in the `options` object are:
An element with transitions will dispatch the following events in addition to any standard DOM events:
* `introstart`
* `introend`
* `outrostart`
* `outroend`
- `introstart`
- `introend`
- `outrostart`
- `outroend`
```sv
{#if visible}
@ -1128,7 +1131,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.
```sv
{#if x}
@ -1144,18 +1147,20 @@ Local transitions only play when the block they belong to is created or destroye
{/if}
```
#### in:*fn*/out:*fn*
#### in:_fn_/out:_fn_
```sv
in:fn
```
```sv
in:fn={params}
```
```sv
in:fn|local
```
```sv
in:fn|local={params}
```
@ -1163,12 +1168,15 @@ in:fn|local={params}
```sv
out:fn
```
```sv
out:fn={params}
```
```sv
out:fn|local
```
```sv
out:fn|local={params}
```
@ -1187,9 +1195,7 @@ Unlike with `transition:`, transitions applied with `in:` and `out:` are not bid
{/if}
```
#### animate:*fn*
#### animate:_fn_
```sv
animate:name
@ -1224,9 +1230,9 @@ DOMRect {
---
An animation is triggered when the contents of a [keyed each block](/docs#template-syntax-each) are re-ordered. Animations do not run when an element is added or removed, only when the index of an existing data item within the each block changes. Animate directives must be on an element that is an *immediate* child of a keyed each block.
An animation is triggered when the contents of a [keyed each block](/docs/template-syntax#each) are re-ordered. Animations do not run when an element is added or removed, only when the index of an existing data item within the each block changes. Animate directives must be on an element that is an _immediate_ child of a keyed each block.
Animations can be used with Svelte's [built-in animation functions](/docs#run-time-svelte-animate) or [custom animation functions](/docs#template-syntax-element-directives-animate-fn-custom-animation-functions).
Animations can be used with Svelte's [built-in animation functions](/docs/run-time#svelte-animate) or [custom animation functions](/docs/template-syntax#element-directives-animate-fn-custom-animation-functions).
```sv
<!-- When `list` is reordered the animation will run-->
@ -1259,8 +1265,7 @@ If the returned object has a `css` method, Svelte will create a CSS animation th
The `t` argument passed to `css` is a value that goes from `0` and `1` after the `easing` function has been applied. The `u` argument is equal to `1 - t`.
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.
```sv
<script>
@ -1290,8 +1295,7 @@ The function is called repeatedly *before* the animation begins, with different
---
A custom animation function can also return a `tick` function, which is called *during* the animation with the same `t` and `u` arguments.
A custom animation function can also return a `tick` function, which is called _during_ the animation with the same `t` and `u` arguments.
> 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.
@ -1323,7 +1327,7 @@ A custom animation function can also return a `tick` function, which is called *
### Component directives
#### on:*eventname*
#### on:_eventname_
```sv
on:eventname={handler}
@ -1331,7 +1335,7 @@ on:eventname={handler}
---
Components can emit events using [createEventDispatcher](/docs#run-time-svelte-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/run-time#svelte-createeventdispatcher), or by forwarding DOM events. Listening for component events looks the same as listening for DOM events:
```sv
<SomeComponent on:whatever={handler}/>
@ -1339,7 +1343,7 @@ Components can emit events using [createEventDispatcher](/docs#run-time-svelte-c
---
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.
```sv
<SomeComponent on:whatever/>
@ -1418,7 +1422,7 @@ So you can set a high-level theme color:
```css
/* global.css */
html {
--theme-color: black;
--theme-color: black;
}
```
@ -1430,7 +1434,7 @@ Or override it at the consumer level:
<Slider --rail-color="goldenrod"/>
```
#### bind:*property*
#### bind:_property_
```sv
bind:property={variable}
@ -1464,16 +1468,16 @@ Components also support `bind:this`, allowing you to interact with component ins
</button>
```
### `<slot>`
```sv
<slot><!-- optional fallback --></slot>
```
```sv
<slot name="x"><!-- optional fallback --></slot>
```
```sv
<slot prop={value}></slot>
```
@ -1500,7 +1504,7 @@ The content is exposed in the child component using the `<slot>` element, which
</Widget>
```
#### `<slot name="`*name*`">`
#### `<slot name="`_name_`">`
---
@ -1542,7 +1546,6 @@ In order to place content in a slot without using a wrapper element, you can use
</Widget>
```
#### `$$slots`
---
@ -1569,11 +1572,11 @@ Note that explicitly passing in an empty named slot will add that slot's name to
</Card>
```
#### `<slot key={`*value*`}>`
#### `<slot key={`_value_`}>`
---
Slots can be rendered zero or more times and can pass values *back* to the parent using props. The parent exposes the values to the slot template using the `let:` directive.
Slots can be rendered zero or more times and can pass values _back_ to the parent using props. The parent exposes the values to the slot template using the `let:` directive.
The usual shorthand rules apply — `let:item` is equivalent to `let:item={item}`, and `<slot {item}>` is equivalent to `<slot item={item}>`.
@ -1616,7 +1619,6 @@ Named slots can also expose values. The `let:` directive goes on the element wit
</FancyList>
```
### `<svelte:self>`
---
@ -1684,6 +1686,7 @@ If `this` is the name of a [void element](https://developer.mozilla.org/en-US/do
```sv
<svelte:window on:event={handler}/>
```
```sv
<svelte:window bind:prop={value}/>
```
@ -1708,13 +1711,13 @@ Unlike `<svelte:self>`, this element may only appear at the top level of your co
You can also bind to the following properties:
* `innerWidth`
* `innerHeight`
* `outerWidth`
* `outerHeight`
* `scrollX`
* `scrollY`
* `online` — an alias for `window.navigator.onLine`
- `innerWidth`
- `innerHeight`
- `outerWidth`
- `outerHeight`
- `scrollX`
- `scrollY`
- `online` — an alias for `window.navigator.onLine`
All except `scrollX` and `scrollY` are readonly.
@ -1732,7 +1735,7 @@ All except `scrollX` and `scrollY` are readonly.
---
Similarly to `<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`. It also lets you use [actions](/docs#template-syntax-element-directives-use-action) on the `<body>` element.
Similarly to `<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`. It also lets you use [actions](/docs/template-syntax#element-directives-use-action) on the `<body>` element.
As with `<svelte:window>`, this element may only appear the top level of your component and must never be inside a block or element.
@ -1744,7 +1747,6 @@ As with `<svelte:window>`, this element may only appear the top level of your co
/>
```
### `<svelte:head>`
```sv
@ -1763,7 +1765,6 @@ As with `<svelte:window>` and `<svelte:body>`, this element may only appear at t
</svelte:head>
```
### `<svelte:options>`
```sv
@ -1772,14 +1773,14 @@ As with `<svelte:window>` and `<svelte:body>`, this element may only appear at t
---
The `<svelte:options>` element provides a place to specify per-component compiler options, which are detailed in the [compiler section](/docs#compile-time-svelte-compile). The possible options are:
The `<svelte:options>` element provides a place to specify per-component compiler options, which are detailed in the [compiler section](/docs/compile-time#svelte-compile). The possible options are:
* `immutable={true}` — you never use mutable data, so the compiler can do simple referential equality checks to determine if values have changed
* `immutable={false}` — the default. Svelte will be more conservative about whether or not mutable objects have changed
* `accessors={true}` — adds getters and setters for the component's props
* `accessors={false}` — the default
* `namespace="..."` — the namespace where this component will be used, most commonly "svg"; use the "foreign" namespace to opt out of case-insensitive attribute names and HTML-specific warnings
* `tag="..."` — the name to use when compiling this component as a custom element
- `immutable={true}` — you never use mutable data, so the compiler can do simple referential equality checks to determine if values have changed
- `immutable={false}` — the default. Svelte will be more conservative about whether or not mutable objects have changed
- `accessors={true}` — adds getters and setters for the component's props
- `accessors={false}` — the default
- `namespace="..."` — the namespace where this component will be used, most commonly "svg"; use the "foreign" namespace to opt out of case-insensitive attribute names and HTML-specific warnings
- `tag="..."` — the name to use when compiling this component as a custom element
```sv
<svelte:options tag="my-custom-element"/>
@ -1787,7 +1788,7 @@ The `<svelte:options>` element provides a place to specify per-component compile
### `<svelte:fragment>`
The `<svelte:fragment>` element allows you to place content in a [named slot](/docs#template-syntax-slot-slot-name-name) without wrapping it in a container DOM element. This keeps the flow layout of your document intact.
The `<svelte:fragment>` element allows you to place content in a [named slot](/docs/template-syntax#slot-slot-name-name) without wrapping it in a container DOM element. This keeps the flow layout of your document intact.
```sv
<!-- Widget.svelte -->

@ -2,7 +2,6 @@
title: Run time
---
### `svelte`
The `svelte` package exposes [lifecycle functions](/tutorial/onmount) and the [context API](/tutorial/context-api).
@ -12,15 +11,16 @@ The `svelte` package exposes [lifecycle functions](/tutorial/onmount) and the [c
```js
onMount(callback: () => void)
```
```js
onMount(callback: () => () => void)
```
---
The `onMount` function schedules a callback to run as soon as the component has been mounted to the DOM. It must be called during the component's initialisation (but doesn't need to live *inside* the component; it can be called from an external module).
The `onMount` function schedules a callback to run as soon as the component has been mounted to the DOM. It must be called during the component's initialisation (but doesn't need to live _inside_ the component; it can be called from an external module).
`onMount` does not run inside a [server-side component](/docs#run-time-server-side-component-api).
`onMount` does not run inside a [server-side component](/docs/run-time#server-side-component-api).
```sv
<script>
@ -50,7 +50,7 @@ If a function is returned from `onMount`, it will be called when the component i
</script>
```
> This behaviour will only work when the function passed to `onMount` *synchronously* returns a value. `async` functions always return a `Promise`, and as such cannot *synchronously* return a function.
> This behaviour will only work when the function passed to `onMount` _synchronously_ returns a value. `async` functions always return a `Promise`, and as such cannot _synchronously_ return a function.
#### `beforeUpdate`
@ -121,7 +121,7 @@ Out of `onMount`, `beforeUpdate`, `afterUpdate` and `onDestroy`, this is the onl
#### `tick`
```js
promise: Promise = tick()
promise: Promise = tick();
```
---
@ -160,7 +160,7 @@ Like lifecycle functions, this must be called during component initialisation.
</script>
```
> Context is not inherently reactive. If you need reactive values in context then you can pass a store into context, which *will* be reactive.
> Context is not inherently reactive. If you need reactive values in context then you can pass a store into context, which _will_ be reactive.
#### `getContext`
@ -226,7 +226,7 @@ dispatch: ((name: string, detail?: any, options?: DispatchOptions) => boolean) =
---
Creates an event dispatcher that can be used to dispatch [component events](/docs#template-syntax-component-directives-on-eventname). Event dispatchers are functions that can take two arguments: `name` and `detail`.
Creates an event dispatcher that can be used to dispatch [component events](/docs/template-syntax#component-directives-on-eventname). Event dispatchers are functions that can take two arguments: `name` and `detail`.
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.
@ -277,17 +277,18 @@ Events can be cancelable by passing a third parameter to the dispatch function.
### `svelte/store`
The `svelte/store` module exports functions for creating [readable](/docs#run-time-svelte-store-readable), [writable](/docs#run-time-svelte-store-writable) and [derived](/docs#run-time-svelte-store-derived) stores.
The `svelte/store` module exports functions for creating [readable](/docs/run-time#svelte-store-readable), [writable](/docs/run-time#svelte-store-writable) and [derived](/docs/run-time#svelte-store-derived) stores.
Keep in mind that you don't *have* to use these functions to enjoy the [reactive `$store` syntax](/docs#component-format-script-4-prefix-stores-with-$-to-access-their-values) in your components. Any object that correctly implements `.subscribe`, unsubscribe, and (optionally) `.set` is a valid store, and will work both with the special syntax, and with Svelte's built-in [`derived` stores](/docs#run-time-svelte-store-derived).
Keep in mind that you don't _have_ to use these functions to enjoy the [reactive `$store` syntax](/docs/component-format#script-4-prefix-stores-with-$-to-access-their-values) in your components. Any object that correctly implements `.subscribe`, unsubscribe, and (optionally) `.set` is a valid store, and will work both with the special syntax, and with Svelte's built-in [`derived` stores](/docs/run-time#svelte-store-derived).
This makes it possible to wrap almost any other reactive state handling library for use in Svelte. Read more about the [store contract](/docs#component-format-script-4-prefix-stores-with-$-to-access-their-values-store-contract) to see what a correct implementation looks like.
This makes it possible to wrap almost any other reactive state handling library for use in Svelte. Read more about the [store contract](/docs/component-format#script-4-prefix-stores-with-$-to-access-their-values-store-contract) to see what a correct implementation looks like.
#### `writable`
```js
store = writable(value?: any)
```
```js
store = writable(value?: any, start?: (set: (value: any) => void) => () => void)
```
@ -301,17 +302,17 @@ Function that creates a store which has values that can be set from 'outside' co
`update` is a method that takes one argument which is a callback. The callback takes the existing store value as its argument and returns the new value to be set to the store.
```js
import { writable } from 'svelte/store';
import { writable } from "svelte/store";
const count = writable(0);
count.subscribe(value => {
count.subscribe((value) => {
console.log(value);
}); // logs '0'
count.set(1); // logs '1'
count.update(n => n + 1); // logs '2'
count.update((n) => n + 1); // logs '2'
```
---
@ -319,16 +320,16 @@ count.update(n => n + 1); // logs '2'
If a function is passed as the second argument, it will be called when the number of subscribers goes from zero to one (but not from one to two, etc). That function will be passed a `set` function which changes the value of the store. It must return a `stop` function that is called when the subscriber count goes from one to zero.
```js
import { writable } from 'svelte/store';
import { writable } from "svelte/store";
const count = writable(0, () => {
console.log('got a subscriber');
return () => console.log('no more subscribers');
console.log("got a subscriber");
return () => console.log("no more subscribers");
});
count.set(1); // does nothing
const unsubscribe = count.subscribe(value => {
const unsubscribe = count.subscribe((value) => {
console.log(value);
}); // logs 'got a subscriber', then '1'
@ -348,9 +349,9 @@ store = readable(value?: any, start?: (set: (value: any) => void) => () => void)
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`.
```js
import { readable } from 'svelte/store';
import { readable } from "svelte/store";
const time = readable(null, set => {
const time = readable(null, (set) => {
set(new Date());
const interval = setInterval(() => {
@ -366,12 +367,15 @@ const time = readable(null, set => {
```js
store = derived(a, callback: (a: any) => any)
```
```js
store = derived(a, callback: (a: any, set: (value: any) => void) => void | () => void, initial_value: any)
```
```js
store = derived([a, ...b], callback: ([a: any, ...b: any[]]) => any)
```
```js
store = derived([a, ...b], callback: ([a: any, ...b: any[]], set: (value: any) => void) => void | () => void, initial_value: any)
```
@ -383,9 +387,9 @@ 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.
```js
import { derived } from 'svelte/store';
import { derived } from "svelte/store";
const doubled = derived(a, $a => $a * 2);
const doubled = derived(a, ($a) => $a * 2);
```
---
@ -395,11 +399,15 @@ 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` is first called.
```js
import { derived } from 'svelte/store';
import { derived } from "svelte/store";
const delayed = derived(a, ($a, set) => {
setTimeout(() => set($a), 1000);
}, 'one moment...');
const delayed = derived(
a,
($a, set) => {
setTimeout(() => set($a), 1000);
},
"one moment..."
);
```
---
@ -407,17 +415,21 @@ const delayed = derived(a, ($a, set) => {
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
import { derived } from 'svelte/store';
import { derived } from "svelte/store";
const tick = derived(frequency, ($frequency, set) => {
const interval = setInterval(() => {
set(Date.now());
}, 1000 / $frequency);
const tick = derived(
frequency,
($frequency, set) => {
const interval = setInterval(() => {
set(Date.now());
}, 1000 / $frequency);
return () => {
clearInterval(interval);
};
}, 'one moment...');
return () => {
clearInterval(interval);
};
},
"one moment..."
);
```
---
@ -425,7 +437,7 @@ const tick = derived(frequency, ($frequency, set) => {
In both cases, an array of arguments can be passed as the first argument instead of a single store.
```js
import { derived } from 'svelte/store';
import { derived } from "svelte/store";
const summed = derived([a, b], ([$a, $b]) => $a + $b);
@ -437,7 +449,7 @@ const delayed = derived([a, b], ([$a, $b], set) => {
#### `get`
```js
value: any = get(store)
value: any = get(store);
```
---
@ -447,12 +459,11 @@ 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
import { get } from 'svelte/store';
import { get } from "svelte/store";
const value = get(store);
```
### `svelte/motion`
The `svelte/motion` module exports two functions, `tweened` and `spring`, for creating writable stores whose values change over time after `set` and `update`, rather than immediately.
@ -465,10 +476,10 @@ store = tweened(value: any, options)
Tweened stores update their values over a fixed duration. The following options are available:
* `delay` (`number`, default 0) — milliseconds before starting
* `duration` (`number` | `function`, default 400) — milliseconds the tween lasts
* `easing` (`function`, default `t => t`) — an [easing function](/docs#run-time-svelte-easing)
* `interpolate` (`function`) — see below
- `delay` (`number`, default 0) — milliseconds before starting
- `duration` (`number` | `function`, default 400) — milliseconds the tween lasts
- `easing` (`function`, default `t => t`) — an [easing function](/docs/run-time#svelte-easing)
- `interpolate` (`function`) — see below
`store.set` and `store.update` can accept a second `options` argument that will override the options passed in upon instantiation.
@ -507,7 +518,7 @@ If the initial value is `undefined` or `null`, the first value change will take
```js
const size = tweened(undefined, {
duration: 300,
easing: cubicOut
easing: cubicOut,
});
$: $size = big ? 100 : 10;
@ -515,7 +526,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.
```sv
<script>
@ -552,9 +563,9 @@ store = spring(value: any, options)
A `spring` store gradually changes to its target value based on its `stiffness` and `damping` parameters. Whereas `tweened` stores change their values over a fixed duration, `spring` stores change over a duration that is determined by their existing velocity, allowing for more natural-seeming motion in many situations. The following options are available:
* `stiffness` (`number`, default `0.15`) — a value between 0 and 1 where higher means a 'tighter' spring
* `damping` (`number`, default `0.8`) — a value between 0 and 1 where lower means a 'springier' spring
* `precision` (`number`, default `0.01`) — determines the threshold at which the spring is considered to have 'settled', where lower means more precise
- `stiffness` (`number`, default `0.15`) — a value between 0 and 1 where higher means a 'tighter' spring
- `damping` (`number`, default `0.8`) — a value between 0 and 1 where lower means a 'springier' spring
- `precision` (`number`, default `0.01`) — determines the threshold at which the spring is considered to have 'settled', where lower means more precise
---
@ -569,7 +580,7 @@ size.precision = 0.005;
---
As with [`tweened`](/docs#run-time-svelte-motion-tweened) stores, `set` and `update` return a Promise that resolves if the spring settles.
As with [`tweened`](/docs/run-time#svelte-motion-tweened) stores, `set` and `update` return a Promise that resolves if the spring settles.
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 }`.
@ -610,16 +621,18 @@ $: $size = big ? 100 : 10;
### `svelte/transition`
The `svelte/transition` module exports seven functions: `fade`, `blur`, `fly`, `slide`, `scale`, `draw` and `crossfade`. They are for use with Svelte [`transitions`](/docs#template-syntax-element-directives-transition-fn).
The `svelte/transition` module exports seven functions: `fade`, `blur`, `fly`, `slide`, `scale`, `draw` and `crossfade`. They are for use with Svelte [`transitions`](/docs/template-syntax#element-directives-transition-fn).
#### `fade`
```sv
transition:fade={params}
```
```sv
in:fade={params}
```
```sv
out:fade={params}
```
@ -630,9 +643,9 @@ Animates the opacity of an element from 0 to the current opacity for `in` transi
`fade` accepts the following parameters:
* `delay` (`number`, default 0) — milliseconds before starting
* `duration` (`number`, default 400) — milliseconds the transition lasts
* `easing` (`function`, default `linear`) — an [easing function](/docs#run-time-svelte-easing)
- `delay` (`number`, default 0) — milliseconds before starting
- `duration` (`number`, default 400) — milliseconds the transition lasts
- `easing` (`function`, default `linear`) — an [easing function](/docs/run-time#svelte-easing)
You can see the `fade` transition in action in the [transition tutorial](/tutorial/transition).
@ -653,9 +666,11 @@ You can see the `fade` transition in action in the [transition tutorial](/tutori
```sv
transition:blur={params}
```
```sv
in:blur={params}
```
```sv
out:blur={params}
```
@ -666,11 +681,11 @@ Animates a `blur` filter alongside an element's opacity.
`blur` accepts the following parameters:
* `delay` (`number`, default 0) — milliseconds before starting
* `duration` (`number`, default 400) — milliseconds the transition lasts
* `easing` (`function`, default `cubicInOut`) — an [easing function](/docs#run-time-svelte-easing)
* `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
- `delay` (`number`, default 0) — milliseconds before starting
- `duration` (`number`, default 400) — milliseconds the transition lasts
- `easing` (`function`, default `cubicInOut`) — an [easing function](/docs/run-time#svelte-easing)
- `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
```sv
<script>
@ -689,9 +704,11 @@ Animates a `blur` filter alongside an element's opacity.
```sv
transition:fly={params}
```
```sv
in:fly={params}
```
```sv
out:fly={params}
```
@ -702,12 +719,12 @@ Animates the x and y positions and the opacity of an element. `in` transitions a
`fly` accepts the following parameters:
* `delay` (`number`, default 0) — milliseconds before starting
* `duration` (`number`, default 400) — milliseconds the transition lasts
* `easing` (`function`, default `cubicOut`) — an [easing function](/docs#run-time-svelte-easing)
* `x` (`number`, default 0) - the x offset to animate out to and in from
* `y` (`number`, default 0) - the y offset to animate out to and in from
* `opacity` (`number`, default 0) - the opacity value to animate out to and in from
- `delay` (`number`, default 0) — milliseconds before starting
- `duration` (`number`, default 400) — milliseconds the transition lasts
- `easing` (`function`, default `cubicOut`) — an [easing function](/docs/run-time#svelte-easing)
- `x` (`number`, default 0) - the x offset to animate out to and in from
- `y` (`number`, default 0) - the y offset to animate out to and in from
- `opacity` (`number`, default 0) - the opacity value to animate out to and in from
You can see the `fly` transition in action in the [transition tutorial](/tutorial/adding-parameters-to-transitions).
@ -729,9 +746,11 @@ You can see the `fly` transition in action in the [transition tutorial](/tutoria
```sv
transition:slide={params}
```
```sv
in:slide={params}
```
```sv
out:slide={params}
```
@ -742,9 +761,9 @@ Slides an element in and out.
`slide` accepts the following parameters:
* `delay` (`number`, default 0) — milliseconds before starting
* `duration` (`number`, default 400) — milliseconds the transition lasts
* `easing` (`function`, default `cubicOut`) — an [easing function](/docs#run-time-svelte-easing)
- `delay` (`number`, default 0) — milliseconds before starting
- `duration` (`number`, default 400) — milliseconds the transition lasts
- `easing` (`function`, default `cubicOut`) — an [easing function](/docs/run-time#svelte-easing)
```sv
<script>
@ -764,9 +783,11 @@ Slides an element in and out.
```sv
transition:scale={params}
```
```sv
in:scale={params}
```
```sv
out:scale={params}
```
@ -777,11 +798,11 @@ Animates the opacity and scale of an element. `in` transitions animate from an e
`scale` accepts the following parameters:
* `delay` (`number`, default 0) — milliseconds before starting
* `duration` (`number`, default 400) — milliseconds the transition lasts
* `easing` (`function`, default `cubicOut`) — an [easing function](/docs#run-time-svelte-easing)
* `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
- `delay` (`number`, default 0) — milliseconds before starting
- `duration` (`number`, default 400) — milliseconds the transition lasts
- `easing` (`function`, default `cubicOut`) — an [easing function](/docs/run-time#svelte-easing)
- `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
```sv
<script>
@ -801,9 +822,11 @@ Animates the opacity and scale of an element. `in` transitions animate from an e
```sv
transition:draw={params}
```
```sv
in:draw={params}
```
```sv
out:draw={params}
```
@ -814,10 +837,10 @@ Animates the stroke of an SVG element, like a snake in a tube. `in` transitions
`draw` accepts the following parameters:
* `delay` (`number`, default 0) — milliseconds before starting
* `speed` (`number`, default undefined) - the speed of the animation, see below.
* `duration` (`number` | `function`, default 800) — milliseconds the transition lasts
* `easing` (`function`, default `cubicInOut`) — an [easing function](/docs#run-time-svelte-easing)
- `delay` (`number`, default 0) — milliseconds before starting
- `speed` (`number`, default undefined) - the speed of the animation, see below.
- `duration` (`number` | `function`, default 800) — milliseconds the transition lasts
- `easing` (`function`, default `cubicInOut`) — an [easing function](/docs/run-time#svelte-easing)
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.
@ -841,19 +864,18 @@ The `speed` parameter is a means of setting the duration of the transition relat
```
#### `crossfade`
The `crossfade` function creates a pair of [transitions](/docs#template-syntax-element-directives-transition-fn) called `send` and `receive`. When an element is 'sent', it looks for a corresponding element being 'received', and generates a transition that transforms the element to its counterpart's position and fades it out. When an element is 'received', the reverse happens. If there is no counterpart, the `fallback` transition is used.
The `crossfade` function creates a pair of [transitions](/docs/template-syntax#element-directives-transition-fn) called `send` and `receive`. When an element is 'sent', it looks for a corresponding element being 'received', and generates a transition that transforms the element to its counterpart's position and fades it out. When an element is 'received', the reverse happens. If there is no counterpart, the `fallback` transition is used.
---
`crossfade` accepts the following parameters:
* `delay` (`number`, default 0) — milliseconds before starting
* `duration` (`number` | `function`, default 800) — milliseconds the transition lasts
* `easing` (`function`, default `cubicOut`) — an [easing function](/docs#run-time-svelte-easing)
* `fallback` (`function`) — A fallback [transition](/docs#template-syntax-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.
- `delay` (`number`, default 0) — milliseconds before starting
- `duration` (`number` | `function`, default 800) — milliseconds the transition lasts
- `easing` (`function`, default `cubicOut`) — an [easing function](/docs/run-time#svelte-easing)
- `fallback` (`function`) — A fallback [transition](/docs/template-syntax#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.
```sv
<script>
@ -873,10 +895,9 @@ The `crossfade` function creates a pair of [transitions](/docs#template-syntax-e
{/if}
```
### `svelte/animate`
The `svelte/animate` module exports one function for use with Svelte [animations](/docs#template-syntax-element-directives-animate-fn).
The `svelte/animate` module exports one function for use with Svelte [animations](/docs/template-syntax#element-directives-animate-fn).
#### `flip`
@ -888,10 +909,9 @@ The `flip` function calculates the start and end position of an element and anim
`flip` accepts the following parameters:
* `delay` (`number`, default 0) — milliseconds before starting
* `duration` (`number` | `function`, default `d => Math.sqrt(d) * 120`) — see below
* `easing` (`function`, default `cubicOut`) — an [easing function](/docs#run-time-svelte-easing)
- `delay` (`number`, default 0) — milliseconds before starting
- `duration` (`number` | `function`, default `d => Math.sqrt(d) * 120`) — see below
- `easing` (`function`, default `cubicOut`) — an [easing function](/docs/run-time#svelte-easing)
`duration` can be provided as either:
@ -902,7 +922,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](/tutorial/animate)
```sv
<script>
import { flip } from 'svelte/animate';
@ -918,28 +937,24 @@ You can see a full example on the [animations tutorial](/tutorial/animate)
{/each}
```
### `svelte/easing`
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).
| ease | in | out | inOut |
| --- | --- | --- | --- |
| **back** | `backIn` | `backOut` | `backInOut` |
| **bounce** | `bounceIn` | `bounceOut` | `bounceInOut` |
| **circ** | `circIn` | `circOut` | `circInOut` |
| **cubic** | `cubicIn` | `cubicOut` | `cubicInOut` |
| ease | in | out | inOut |
| ----------- | ----------- | ------------ | -------------- |
| **back** | `backIn` | `backOut` | `backInOut` |
| **bounce** | `bounceIn` | `bounceOut` | `bounceInOut` |
| **circ** | `circIn` | `circOut` | `circInOut` |
| **cubic** | `cubicIn` | `cubicOut` | `cubicInOut` |
| **elastic** | `elasticIn` | `elasticOut` | `elasticInOut` |
| **expo** | `expoIn` | `expoOut` | `expoInOut` |
| **quad** | `quadIn` | `quadOut` | `quadInOut` |
| **quart** | `quartIn` | `quartOut` | `quartInOut` |
| **quint** | `quintIn` | `quintOut` | `quintInOut` |
| **sine** | `sineIn` | `sineOut` | `sineInOut` |
| **expo** | `expoIn` | `expoOut` | `expoInOut` |
| **quad** | `quadIn` | `quadOut` | `quadInOut` |
| **quart** | `quartIn` | `quartOut` | `quartInOut` |
| **quint** | `quintIn` | `quintOut` | `quintInOut` |
| **sine** | `sineIn` | `sineOut` | `sineInOut` |
### `svelte/register`
@ -960,78 +975,76 @@ const { html, css, head } = App.render({ answer: 42 });
To set compile options, or to use a custom file extension, call the `register` hook as a function:
```js
require('svelte/register')({
extensions: ['.customextension'], // defaults to ['.html', '.svelte']
preserveComments: true
require("svelte/register")({
extensions: [".customextension"], // defaults to ['.html', '.svelte']
preserveComments: true,
});
```
### Client-side component API
#### Creating a component
```js
const component = new Component(options)
const component = new Component(options);
```
A client-side component — that is, a component compiled with `generate: 'dom'` (or the `generate` option left unspecified) is a JavaScript class.
```js
import App from './App.svelte';
import App from "./App.svelte";
const app = new App({
target: document.body,
props: {
// assuming App.svelte contains something like
// `export let answer`:
answer: 42
}
answer: 42,
},
});
```
The following initialisation options can be provided:
| option | default | description |
| --- | --- | --- |
| `target` | **none** | An `HTMLElement` or `ShadowRoot` to render to. This option is required
| `anchor` | `null` | A child of `target` to render the component immediately before
| `props` | `{}` | An object of properties to supply to the component
| `context` | `new Map()` | A `Map` of root-level context key-value pairs to supply to the component
| `hydrate` | `false` | See below
| `intro` | `false` | If `true`, will play transitions on initial render, rather than waiting for subsequent state changes
| option | default | description |
| --------- | ----------- | ---------------------------------------------------------------------------------------------------- |
| `target` | **none** | An `HTMLElement` or `ShadowRoot` to render to. This option is required |
| `anchor` | `null` | A child of `target` to render the component immediately before |
| `props` | `{}` | An object of properties to supply to the component |
| `context` | `new Map()` | A `Map` of root-level context key-value pairs to supply to the component |
| `hydrate` | `false` | See below |
| `intro` | `false` | If `true`, will play transitions on initial render, rather than waiting for subsequent state changes |
Existing children of `target` are left where they are.
---
The `hydrate` option instructs Svelte to upgrade existing DOM (usually from server-side rendering) rather than creating new elements. It will only work if the component was compiled with the [`hydratable: true` option](/docs#compile-time-svelte-compile). Hydration of `<head>` elements only works properly if the server-side rendering code was also compiled with `hydratable: true`, which adds a marker to each element in the `<head>` so that the component knows which elements it's responsible for removing during hydration.
The `hydrate` option instructs Svelte to upgrade existing DOM (usually from server-side rendering) rather than creating new elements. It will only work if the component was compiled with the [`hydratable: true` option](/docs/compile-time#svelte-compile). Hydration of `<head>` elements only works properly if the server-side rendering code was also compiled with `hydratable: true`, which adds a marker to each element in the `<head>` so that the component knows which elements it's responsible for removing during hydration.
Whereas children of `target` are normally left alone, `hydrate: true` will cause any children to be removed. For that reason, the `anchor` option cannot be used alongside `hydrate: true`.
The existing DOM doesn't need to match the component — Svelte will 'repair' the DOM as it goes.
```js
import App from './App.svelte';
import App from "./App.svelte";
const app = new App({
target: document.querySelector('#server-rendered-html'),
hydrate: true
target: document.querySelector("#server-rendered-html"),
hydrate: true,
});
```
#### `$set`
```js
component.$set(props)
component.$set(props);
```
---
Programmatically sets props on an instance. `component.$set({ x: 1 })` is equivalent to `x = 1` inside the component's `<script>` block.
Calling this method schedules an update for the next microtask — the DOM is *not* updated synchronously.
Calling this method schedules an update for the next microtask — the DOM is _not_ updated synchronously.
```js
component.$set({ answer: 42 });
@ -1040,7 +1053,7 @@ component.$set({ answer: 42 });
#### `$on`
```js
component.$on(event, callback)
component.$on(event, callback);
```
---
@ -1050,7 +1063,7 @@ Causes the `callback` function to be called whenever the component dispatches an
A function is returned that will remove the event listener when called.
```js
const off = app.$on('selected', event => {
const off = app.$on("selected", (event) => {
console.log(event.detail.selection);
});
@ -1060,7 +1073,7 @@ off();
#### `$destroy`
```js
component.$destroy()
component.$destroy();
```
Removes a component from the DOM and triggers any `onDestroy` handlers.
@ -1068,15 +1081,16 @@ Removes a component from the DOM and triggers any `onDestroy` handlers.
#### Component props
```js
component.prop
component.prop;
```
```js
component.prop = value
component.prop = value;
```
---
If a component is compiled with `accessors: true`, each instance will have getters and setters corresponding to each of the component's props. Setting a value will cause a *synchronous* update, rather than the default async update caused by `component.$set(...)`.
If a component is compiled with `accessors: true`, each instance will have getters and setters corresponding to each of the component's props. Setting a value will cause a _synchronous_ update, rather than the default async update caused by `component.$set(...)`.
By default, `accessors` is `false`, unless you're compiling as a custom element.
@ -1085,12 +1099,11 @@ console.log(app.count);
app.count += 1;
```
### Custom element API
---
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#template-syntax-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/template-syntax#svelte-options).
```sv
<svelte:options tag="my-element" />
@ -1108,9 +1121,9 @@ Svelte components can also be compiled to custom elements (aka web components) u
Alternatively, use `tag={null}` to indicate that the consumer of the custom element should name it.
```js
import MyElement from './MyElement.svelte';
import MyElement from "./MyElement.svelte";
customElements.define('my-element', MyElement);
customElements.define("my-element", MyElement);
```
---
@ -1127,30 +1140,28 @@ document.body.innerHTML = `
---
By default, custom elements are compiled with `accessors: true`, which means that any [props](/docs#template-syntax-attributes-and-props) are exposed as properties of the DOM element (as well as being readable/writable as attributes, where possible).
By default, custom elements are compiled with `accessors: true`, which means that any [props](/docs/template-syntax#attributes-and-props) are exposed as properties of the DOM element (as well as being readable/writable as attributes, where possible).
To prevent this, add `accessors={false}` to `<svelte:options>`.
```js
const el = document.querySelector('my-element');
const el = document.querySelector("my-element");
// get the current value of the 'name' prop
console.log(el.name);
// set a new value, updating the shadow DOM
el.name = 'everybody';
el.name = "everybody";
```
Custom elements can be a useful way to package components for consumption in a non-Svelte app, as they will work with vanilla HTML and JavaScript as well as [most frameworks](https://custom-elements-everywhere.com/). There are, however, some important differences to be aware of:
* Styles are *encapsulated*, rather than merely *scoped*. This means that any non-component styles (such as you might have in a `global.css` file) will not apply to the custom element, including styles with the `:global(...)` modifier
* Instead of being extracted out as a separate .css file, styles are inlined into the component as a JavaScript string
* Custom elements are not generally suitable for server-side rendering, as the shadow DOM is invisible until JavaScript loads
* In Svelte, slotted content renders *lazily*. In the DOM, it renders *eagerly*. In other words, it will always be created even if the component's `<slot>` element is inside an `{#if ...}` block. Similarly, including a `<slot>` in an `{#each ...}` block will not cause the slotted content to be rendered multiple times
* The `let:` directive has no effect
* Polyfills are required to support older browsers
- Styles are _encapsulated_, rather than merely _scoped_. This means that any non-component styles (such as you might have in a `global.css` file) will not apply to the custom element, including styles with the `:global(...)` modifier
- Instead of being extracted out as a separate .css file, styles are inlined into the component as a JavaScript string
- Custom elements are not generally suitable for server-side rendering, as the shadow DOM is invisible until JavaScript loads
- In Svelte, slotted content renders _lazily_. In the DOM, it renders _eagerly_. In other words, it will always be created even if the component's `<slot>` element is inside an `{#if ...}` block. Similarly, including a `<slot>` in an `{#each ...}` block will not cause the slotted content to be rendered multiple times
- The `let:` directive has no effect
- Polyfills are required to support older browsers
### Server-side component API
@ -1164,15 +1175,15 @@ Unlike client-side components, server-side components don't have a lifespan afte
A server-side component exposes a `render` method that can be called with optional props. It returns an object with `head`, `html`, and `css` properties, where `head` contains the contents of any `<svelte:head>` elements encountered.
You can import a Svelte component directly into Node using [`svelte/register`](/docs#run-time-svelte-register).
You can import a Svelte component directly into Node using [`svelte/register`](/docs/run-time#svelte-register).
```js
require('svelte/register');
require("svelte/register");
const App = require('./App.svelte').default;
const App = require("./App.svelte").default;
const { head, html, css } = App.render({
answer: 42
answer: 42,
});
```
@ -1180,16 +1191,16 @@ const { head, html, css } = App.render({
The `.render()` method accepts the following parameters:
| parameter | default | description |
| --- | --- | --- |
| `props` | `{}` | An object of properties to supply to the component
| `options` | `{}` | An object of options
| parameter | default | description |
| --------- | ------- | -------------------------------------------------- |
| `props` | `{}` | An object of properties to supply to the component |
| `options` | `{}` | An object of options |
The `options` object takes in the following options:
| option | default | description |
| --- | --- | --- |
| `context` | `new Map()` | A `Map` of root-level context key-value pairs to supply to the component
| option | default | description |
| --------- | ----------- | ------------------------------------------------------------------------ |
| `context` | `new Map()` | A `Map` of root-level context key-value pairs to supply to the component |
```js
const { head, html, css } = App.render(
@ -1197,7 +1208,7 @@ const { head, html, css } = App.render(
{ answer: 42 },
// options
{
context: new Map([['context-key', 'context-value']])
context: new Map([["context-key", "context-value"]]),
}
);
```

@ -4,8 +4,7 @@ title: Basics
Welcome to the Svelte tutorial. This will teach you everything you need to know to build fast, small web applications easily.
You can also consult the [API docs](/docs) and the [examples](/examples), or — if you're impatient to start hacking on your machine locally — the [60-second quickstart](/docs#getting-started).
You can also consult the [API docs](/docs) and the [examples](/examples), or — if you're impatient to start hacking on your machine locally — the [60-second quickstart](/docs/getting-started).
## What is Svelte?
@ -13,11 +12,10 @@ Svelte is a tool for building fast web applications.
It is similar to JavaScript frameworks such as React and Vue, which share a goal of making it easy to build slick interactive user interfaces.
But there's a crucial difference: Svelte converts your app into ideal JavaScript at *build time*, rather than interpreting your application code at *run time*. This means you don't pay the performance cost of the framework's abstractions, and you don't incur a penalty when your app first loads.
But there's a crucial difference: Svelte converts your app into ideal JavaScript at _build time_, rather than interpreting your application code at _run time_. This means you don't pay the performance cost of the framework's abstractions, and you don't incur a penalty when your app first loads.
You can build your entire app with Svelte, or you can add it incrementally to an existing codebase. You can also ship components as standalone packages that work anywhere, without the overhead of a dependency on a conventional framework.
## How to use this tutorial
You'll need to have basic familiarity with HTML, CSS and JavaScript to understand Svelte.
@ -26,7 +24,6 @@ As you progress through the tutorial, you'll be presented with mini exercises de
Each tutorial chapter will have a 'Show me' button that you can click if you get stuck following the instructions. Try not to rely on it too much; you will learn faster by figuring out where to put each suggested code block and manually typing it into the editor.
## Understanding components
In Svelte, an application is composed from one or more *components*. A component is a reusable self-contained block of code that encapsulates HTML, CSS and JavaScript that belong together, written into a `.svelte` file. The 'hello world' example in the code editor is a simple component.
In Svelte, an application is composed from one or more _components_. A component is a reusable self-contained block of code that encapsulates HTML, CSS and JavaScript that belong together, written into a `.svelte` file. The 'hello world' example in the code editor is a simple component.

@ -16,22 +16,22 @@ Don't worry if you're relatively new to web development and haven't used these t
You'll also want to configure your text editor. There are [plugins](https://sveltesociety.dev/tools#editor-support) for many popular editors as well as an official [VS Code extension](https://marketplace.visualstudio.com/items?itemName=svelte.svelte-vscode).
<!--
<!--
NOTE: Removed until we have better place for setting-up-your-editor guide. See https://github.com/sveltejs/svelte/pull/7310#issuecomment-1049923609
If your editor does not have a Svelte plugin then you can follow [this guide](/blog/setting-up-your-editor) to configure your text editor to treat `.svelte` files the same as `.html` for the sake of syntax highlighting. -->
Then, once you've got your project set up, using Svelte components is easy. The compiler turns each component into a regular JavaScript class — just import it and instantiate with `new`:
```js
import App from './App.svelte';
import App from "./App.svelte";
const app = new App({
target: document.body,
props: {
// we'll learn about props later
answer: 42
}
answer: 42,
},
});
```
You can then interact with `app` using the [component API](/docs#run-time-client-side-component-api) if you need to.
You can then interact with `app` using the [component API](/docs/run-time#client-side-component-api) if you need to.

@ -2,13 +2,12 @@
title: Derived stores
---
You can create a store whose value is based on the value of one or more *other* stores with `derived`. Building on our previous example, we can create a store that derives the time the page has been open:
You can create a store whose value is based on the value of one or more _other_ stores with `derived`. Building on our previous example, we can create a store that derives the time the page has been open:
```js
export const elapsed = derived(
time,
$time => Math.round(($time - start) / 1000)
export const elapsed = derived(time, ($time) =>
Math.round(($time - start) / 1000)
);
```
> It's possible to derive a store from multiple inputs, and to explicitly `set` a value instead of returning it (which is useful for deriving values asynchronously). Consult the [API reference](/docs#run-time-svelte-store-derived) for more information.
> It's possible to derive a store from multiple inputs, and to explicitly `set` a value instead of returning it (which is useful for deriving values asynchronously). Consult the [API reference](/docs/run-time#svelte-store-derived) for more information.

@ -8,7 +8,7 @@ In this example we have two stores — one representing the circle's coordinates
```html
<script>
import { spring } from 'svelte/motion';
import { spring } from "svelte/motion";
let coords = spring({ x: 50, y: 50 });
let size = spring(10);
@ -18,12 +18,15 @@ In this example we have two stores — one representing the circle's coordinates
Both springs have default `stiffness` and `damping` values, which control the spring's, well... springiness. We can specify our own initial values:
```js
let coords = spring({ x: 50, y: 50 }, {
stiffness: 0.1,
damping: 0.25
});
let coords = spring(
{ x: 50, y: 50 },
{
stiffness: 0.1,
damping: 0.25,
}
);
```
Waggle your mouse around, and try dragging the sliders to get a feel for how they affect the spring's behaviour. Notice that you can adjust the values while the spring is still in motion.
Consult the [API reference](/docs#run-time-svelte-motion-spring) for more information.
Consult the [API reference](/docs/run-time#svelte-motion-spring) for more information.

@ -4,7 +4,7 @@ title: Congratulations!
You've now finished the Svelte tutorial and are ready to start building apps. You can refer back to individual chapters at any time (click the title above to reveal a dropdown) or continue your learning via the [API reference](/docs), [Examples](/examples) and [Blog](/blog). If you're a Twitter user, you can get updates via [@sveltejs](https://twitter.com/sveltejs).
To get set up in your local development environment, check out [the quickstart guide](/docs#getting-started).
To get set up in your local development environment, check out [the quickstart guide](/docs/getting-started).
If you're looking for a more expansive framework that includes routing, server-side rendering and everything else, take a look at [SvelteKit](https://kit.svelte.dev).

@ -4,9 +4,5 @@ import adapter from '@sveltejs/adapter-auto';
export default {
kit: {
adapter: adapter(),
prerender: {
// TODO: REMOVE
handleMissingId: 'ignore',
},
},
};

Loading…
Cancel
Save