diff --git a/apps/svelte.dev/content/docs/svelte/01-introduction/01-overview.md b/apps/svelte.dev/content/docs/svelte/01-introduction/01-overview.md index e5d8f5603..a0901b951 100644 --- a/apps/svelte.dev/content/docs/svelte/01-introduction/01-overview.md +++ b/apps/svelte.dev/content/docs/svelte/01-introduction/01-overview.md @@ -6,10 +6,25 @@ title: Overview - A few code examples to have a very rough understanding of how Svelte code looks like - Jump off points to tutorial, SvelteKit etc -## One +Svelte is a web UI framework that uses a compiler to turn declarative component code like this... -TODO +```svelte + + -TODO + +``` + +...into tightly optimized JavaScript that updates the document when state like count changes. Because the compiler can 'see' where count is referenced, the generated code is highly efficient, and because we're hijacking syntax like `$state(...)` and `=` instead of using cumbersome APIs, you can write less code. + +Besides being fun to work with, Svelte offers a lot of features built-in, such as animations and transitions. Once you've written your first components you can reach for our batteries included metaframework [SvelteKit](/docs/kit) which provides you with an opinionated router, data loading and more. + +If you're new to Svelte, visit the [interactive tutorial](/tutorial) before consulting this documentation. You can try Svelte online using the [REPL](/repl). Alternatively, if you'd like a more fully-featured environment, you can try Svelte on [StackBlitz](https://sveltekit.new). diff --git a/apps/svelte.dev/content/docs/svelte/01-introduction/02-getting-started.md b/apps/svelte.dev/content/docs/svelte/01-introduction/02-getting-started.md index 2ec873317..0f896abe1 100644 --- a/apps/svelte.dev/content/docs/svelte/01-introduction/02-getting-started.md +++ b/apps/svelte.dev/content/docs/svelte/01-introduction/02-getting-started.md @@ -6,3 +6,34 @@ title: Getting started - `npm create vite@latest`, describe that it scaffolds Svelte SPA powered by Vite - mention `svelte-add` - Jump off points to tutorial, SvelteKit etc + +## Start a new project + +We recommend using [SvelteKit](https://kit.svelte.dev/), the official application framework from the Svelte team: + +``` +npm create svelte@latest myapp +cd myapp +npm install +npm run dev +``` + +SvelteKit will handle calling [the Svelte compiler](https://www.npmjs.com/package/svelte) to convert your `.svelte` files into `.js` files that create the DOM and `.css` files that style it. It also provides all the other pieces you need to build a web application such as a development server, routing, deployment, and SSR support. [SvelteKit](https://kit.svelte.dev/) uses [Vite](https://vitejs.dev/) to build your code. + +Don't worry if you don't know Svelte yet! You can ignore all the nice features SvelteKit brings on top for now and dive into it later. + +### Alternatives to SvelteKit + +If you don't want to use SvelteKit for some reason, you can also use Svelte with Vite (but without SvelteKit) by running `npm create vite@latest` and selecting the `svelte` option. With this, `npm run build` will generate HTML, JS and CSS files inside the `dist` directory thanks using [vite-plugin-svelte](https://github.com/sveltejs/vite-plugin-svelte). In most cases, you will probably need to [choose a routing library](faq#is-there-a-router) as well. + +Alternatively, there are plugins for [Rollup](https://github.com/sveltejs/rollup-plugin-svelte), [Webpack](https://github.com/sveltejs/svelte-loader) [and a few others](https://sveltesociety.dev/packages?category=build-plugins) to handle Svelte compilation — which will output `.js` and `.css` that you can insert into your HTML — but setting up SSR with them requires more manual work. + +## Editor tooling + +The Svelte team maintains a [VS Code extension](https://marketplace.visualstudio.com/items?itemName=svelte.svelte-vscode) and there are integrations with various other [editors](https://sveltesociety.dev/resources#editor-support) and tools as well. + +You can also check your code from the command line using [svelte-check](https://www.npmjs.com/package/svelte-check) (using the Svelte or Vite CLI setup will install this for you). + +## Getting help + +Don't be shy about asking for help in the [Discord chatroom](https://svelte.dev/chat)! You can also find answers on [Stack Overflow](https://stackoverflow.com/questions/tagged/svelte). diff --git a/apps/svelte.dev/content/docs/svelte/01-introduction/03-reactivity-fundamentals.md b/apps/svelte.dev/content/docs/svelte/01-introduction/03-reactivity-fundamentals.md new file mode 100644 index 000000000..0f1c8e079 --- /dev/null +++ b/apps/svelte.dev/content/docs/svelte/01-introduction/03-reactivity-fundamentals.md @@ -0,0 +1,88 @@ +--- +title: Reactivity fundamentals +--- + +Reactivity is at the heart of interactive UIs. When you click a button, you expect some kind of response. It's your job as a developer to make this happen. It's Svelte's job to make your job as intuitive as possible, by providing a good API to express reactive systems. + +## Runes + +Svelte 5 uses _runes_, a powerful set of primitives for controlling reactivity inside your Svelte components and inside `.svelte.js` and `.svelte.ts` modules. + +Runes are function-like symbols that provide instructions to the Svelte compiler. You don't need to import them from anywhere — when you use Svelte, they're part of the language. + +The following sections introduce the most important runes for declare state, derived state and side effects at a high level. For more details refer to the later sections on [state](/docs/svelte/runes/state) and [side effects](/docs/svelte/runes/side-effects). + +## `$state` + +Reactive state is declared with the `$state` rune: + +```svelte + + + +``` + +You can also use `$state` in class fields (whether public or private): + +```js +// @errors: 7006 2554 +class Todo { + done = $state(false); + text = $state(); + + constructor(text) { + this.text = text; + } +} +``` + +## `$derived` + +Derived state is declared with the `$derived` rune: + +```svelte + + + + +

{count} doubled is {doubled}

+``` + +The expression inside `$derived(...)` should be free of side-effects. Svelte will disallow state changes (e.g. `count++`) inside derived expressions. + +As with `$state`, you can mark class fields as `$derived`. + +## `$effect` + +To run _side-effects_ when the component is mounted to the DOM, and when values change, we can use the `$effect` rune ([demo](/#H4sIAAAAAAAAE31T24rbMBD9lUG7kAQ2sbdlX7xOYNk_aB_rQhRpbAsU2UiTW0P-vbrYubSlYGzmzMzROTPymdVKo2PFjzMzfIusYB99z14YnfoQuD1qQh-7bmdFQEonrOppVZmKNBI49QthCc-OOOH0LZ-9jxnR6c7eUpOnuv6KeT5JFdcqbvbcBcgDz1jXKGg6ncFyBedYR6IzLrAZwiN5vtSxaJA-EzadfJEjKw11C6GR22-BLH8B_wxdByWpvUYtqqal2XB6RVkG1CoHB6U1WJzbnYFDiwb3aGEdDa3Bm1oH12sQLTcNPp7r56m_00mHocSG97_zd7ICUXonA5fwKbPbkE2ZtMJGGVkEdctzQi4QzSwr9prnFYNk5hpmqVuqPQjNnfOJoMF22lUsrq_UfIN6lfSVyvQ7grB3X2mjMZYO3XO9w-U5iLx42qg29md3BP_ni5P4gy9ikTBlHxjLzAtPDlyYZmRdjAbGq7HprEQ7p64v4LU_guu0kvAkhBim3nMplWl8FreQD-CW20aZR0wq12t-KqDWeBywhvexKC3memmDwlHAv9q4Vo2ZK8KtK0CgX7u9J8wXbzdKv-nRnfF_2baTqlYoWUF2h5efl9-n0O6koAMAAA==)): + +```svelte + + + +``` + +The function passed to `$effect` will run when the component mounts, and will re-run after any changes to the values it reads that were declared with `$state` or `$derived` (including those passed in with `$props`). Re-runs are batched (i.e. changing `color` and `size` in the same moment won't cause two separate runs), and happen after any DOM updates have been applied. diff --git a/apps/svelte.dev/content/docs/svelte/02-template-syntax/01-component-fundamentals.md b/apps/svelte.dev/content/docs/svelte/02-template-syntax/01-component-fundamentals.md index 049ad6386..0e0a38342 100644 --- a/apps/svelte.dev/content/docs/svelte/02-template-syntax/01-component-fundamentals.md +++ b/apps/svelte.dev/content/docs/svelte/02-template-syntax/01-component-fundamentals.md @@ -4,3 +4,181 @@ title: Component fundamentals - script (module) / template / style (rough overview) - `$props` / `$state` (in the context of components) + +Components are the building blocks of Svelte applications. They are written into `.svelte` files, using a superset of HTML. + +All three sections — script, styles and markup — are optional. + +```svelte + + + + + +``` + +## <script> + +A ` +``` + +You can specify a fallback value for a prop. It will be used if the component's consumer doesn't specify the prop on the component when instantiating the component, or if the passed value is `undefined` at some point. + +```svelte + +``` + +To get all properties, use rest syntax: + +```svelte + +``` + +You can use reserved words as prop names. + +```svelte + +``` + +If you're using TypeScript, you can declare the prop types: + +```svelte + +``` + +If you export a `const`, `class` or `function`, it is readonly from outside the component. + +```svelte + +``` + +Readonly props can be accessed as properties on the element, tied to the component using [`bind:this` syntax](/docs/component-directives#bind-this). + +### Reactive variables + +To change component state and trigger a re-render, just assign to a locally declared variable that was declared using the `$state` rune. + +Update expressions (`count += 1`) and property assignments (`obj.x = y`) have the same effect. + +```svelte + +``` + +Svelte's ` +``` + +If you'd like to react to changes to a prop, use the `$derived` or `$effect` runes instead. + +```svelte + +``` + +For more information on reactivity, read the documentation around runes. + +## <script context="module"> + +A ` + + +``` + +## <style> + +CSS inside a ` +``` + +For more information regarding styling, read the documentation around [styles and classes](styles-and-classes). diff --git a/apps/svelte.dev/content/docs/svelte/02-template-syntax/02-basic-markup.md b/apps/svelte.dev/content/docs/svelte/02-template-syntax/02-basic-markup.md index 012eb4ea3..36436849a 100644 --- a/apps/svelte.dev/content/docs/svelte/02-template-syntax/02-basic-markup.md +++ b/apps/svelte.dev/content/docs/svelte/02-template-syntax/02-basic-markup.md @@ -3,3 +3,209 @@ title: Basic markup --- - [basically what we have in the Svelte docs today](https://svelte.dev/docs/basic-markup) + +## Tags + +A lowercase tag, like `
`, denotes a regular HTML element. A capitalised tag, such as `` or ``, indicates a _component_. + +```svelte + + +
+ +
+``` + +## Attributes and props + +By default, attributes work exactly like their HTML counterparts. + +```svelte +
+ +
+``` + +As in HTML, values may be unquoted. + + +```svelte + +``` + +Attribute values can contain JavaScript expressions. + +```svelte +page {p} +``` + +Or they can _be_ JavaScript expressions. + +```svelte + +``` + +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`). + +```svelte + +
This div has no title attribute
+``` + +Quoting a singular expression does not affect how the value is parsed yet, but in Svelte 6 it will: + + +```svelte + +``` + +When the attribute name and value match (`name={name}`), they can be replaced with `{name}`. + +```svelte + + +``` + +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. + +```svelte + +``` + +_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. + +```svelte + +``` + +> 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, ``, 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 ``. + +> Another example is ``. Svelte will set the img `src` before making the img element `loading="lazy"`, which is probably too late. Change this to `` to make the image lazily loaded. + +## Events + +Listening to DOM events is possible by adding attributes to the element that start with `on`. For example, to listen to the `click` event, add the `onclick` attribute to a button: + +```svelte + +``` + +Event attributes are case sensitive. `onclick` listens to the `click` event, `onClick` listens to the `Click` event, which is different. This ensures you can listen to custom events that have uppercase characters in them. + +Because events are just attributes, the same rules as for attributes apply: + +- you can use the shorthand form: `` +- you can spread them: `` +- component events are just (callback) properties and don't need a separate concept + +### Event delegation + +To reduce the memory footprint and increase performance, Svelte uses a technique called event delegation. This means that certain events are only listened to once at the application root, invoking a handler that then traverses the event call path and invokes listeners along the way. + +There are a few gotchas you need to be aware of when it comes to event delegation: + +- when you dispatch events manually, make sure to set the `{ bubbles: true }` option +- when listening to events programmatically (i.e. not through ` +``` + +> Note that you cannot have a prop called `children` if you also have content inside the component — for this reason, you should avoid having props with that name + +You can declare snippet props as being optional. You can either use optional chaining to not render anything if the snippet isn't set... + +```svelte + + +{@render children?.()} +``` + +...or use an `#if` block to render fallback content: + +```svelte + + +{#if children} + {@render children()} +{:else} + fallback content +{/if} +``` + +## Typing snippets + +Snippets implement the `Snippet` interface imported from `'svelte'`: + +```svelte + +``` + +With this change, red squigglies will appear if you try and use the component without providing a `data` prop and a `row` snippet. Notice that the type argument provided to `Snippet` is a tuple, since snippets can have multiple parameters. + +We can tighten things up further by declaring a generic, so that `data` and `row` refer to the same type: + +```svelte + +``` + +## Snippets and slots + +In Svelte 4, content can be passed to components using [slots](https://svelte.dev/docs/special-elements#slot). Snippets are more powerful and flexible, and as such slots are deprecated in Svelte 5. diff --git a/apps/svelte.dev/content/docs/svelte/02-template-syntax/05-styles-and-classes.md b/apps/svelte.dev/content/docs/svelte/02-template-syntax/05-styles-and-classes.md index c483cc3c8..48cdeabce 100644 --- a/apps/svelte.dev/content/docs/svelte/02-template-syntax/05-styles-and-classes.md +++ b/apps/svelte.dev/content/docs/svelte/02-template-syntax/05-styles-and-classes.md @@ -7,3 +7,208 @@ title: Styles & Classes - `style:` - `class:` - `--css` props + +Styling is a fundamental part of UI components. Svelte helps you style your components with ease, providing useful features out of the box. + +## Scoped by default + +By default CSS inside a ` +``` + +## :global + +To apply styles to a selector globally, use the `:global(...)` modifier. + +```svelte + +``` + +If you want to make @keyframes that are accessible globally, you need to prepend your keyframe names with `-global-`. + +The `-global-` part will be removed when compiled, and the keyframe will then be referenced using just `my-animation-name` elsewhere in your code. + +```svelte + +``` + +## Nested style tags + +There should only be 1 top-level ` +
+``` + +## class:_name_ + +```svelte + +class:name={value} +``` + +```svelte + +class:name +``` + +A `class:` directive provides a shorter way of toggling a class on an element. + +```svelte + +
...
+
...
+ + +
...
+ + +
...
+``` + +## style:_property_ + +```svelte + +style:property={value} +``` + +```svelte + +style:property="value" +``` + +```svelte + +style:property +``` + +The `style:` directive provides a shorthand for setting multiple styles on an element. + +```svelte + +
...
+
...
+ + +
...
+ + +
...
+ + +
...
+ + +
...
+``` + +When `style:` directives are combined with `style` attributes, the directives will take precedence: + +```svelte +
This will be red
+``` + +## --style-props + +```svelte + +--style-props="anycssvalue" +``` + +You can also pass styles as props to components for the purposes of theming, using CSS custom properties. + +Svelte's implementation is essentially syntactic sugar for adding a wrapper element. This example: + +```svelte + +``` + +Desugars to this: + +```svelte +
+ +
+``` + +For SVG namespace, the example above desugars into using `` instead: + +```svelte + + + +``` + +> Since this is an extra `
` (or ``), beware that your CSS structure might accidentally target this. Be mindful of this added wrapper element when using this feature. + +Svelte's CSS Variables support allows for easily themeable components: + +```svelte + +``` + +So you can set a high-level theme color: + +```css +/* global.css */ +html { + --theme-color: black; +} +``` + +Or override it at the consumer level: + +```svelte + +``` diff --git a/apps/svelte.dev/content/docs/svelte/02-template-syntax/06-transitions-and-animations.md b/apps/svelte.dev/content/docs/svelte/02-template-syntax/06-transitions-and-animations.md index 8479ad871..8163d96a6 100644 --- a/apps/svelte.dev/content/docs/svelte/02-template-syntax/06-transitions-and-animations.md +++ b/apps/svelte.dev/content/docs/svelte/02-template-syntax/06-transitions-and-animations.md @@ -8,3 +8,425 @@ title: Transitions & Animations - easing & motion - mention imports - key block + +Svelte provides different techniques and syntax for incorporating motion into your Svelte projects. + +## transition:_fn_ + +```svelte + +transition:fn +``` + +```svelte + +transition:fn={params} +``` + +```svelte + +transition:fn|global +``` + +```svelte + +transition:fn|global={params} +``` + +```svelte + +transition:fn|local +``` + +```svelte + +transition:fn|local={params} +``` + +```js +/// copy: false +// @noErrors +transition = (node: HTMLElement, params: any, options: { direction: 'in' | 'out' | 'both' }) => { + delay?: number, + duration?: number, + easing?: (t: number) => number, + css?: (t: number, u: number) => string, + tick?: (t: number, u: number) => void +} +``` + +A transition is triggered by an element entering or leaving the DOM as a result of a state change. + +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. + +```svelte +{#if visible} +
fades in and out
+{/if} +``` + +Transitions are local by default. Local transitions only play when the block they belong to is created or destroyed, _not_ when parent blocks are created or destroyed. + +```svelte +{#if x} + {#if y} +

fades in and out only when y changes

+ +

fades in and out when x or y change

+ {/if} +{/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/runtime/imperative-component-api) and marking the transition as `global`. + +## Transition parameters + +Transitions can have parameters. + +(The double `{{curlies}}` aren't a special syntax; this is an object literal inside an expression tag.) + +```svelte +{#if visible} +
fades in and out over two seconds
+{/if} +``` + +## Custom transition functions + +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 function is called repeatedly _before_ the transition begins, with different `t` and `u` arguments. + +```svelte + + +{#if visible} +
whooshes in
+{/if} +``` + +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. + +```svelte + + + +{#if visible} +

The quick brown fox jumps over the lazy dog

+{/if} +``` + +If a transition returns a function instead of a transition object, the function will be called in the next microtask. This allows multiple transitions to coordinate, making [crossfade effects](/tutorial/deferred-transitions) possible. + +Transition functions also receive a third argument, `options`, which contains information about the transition. + +Available values in the `options` object are: + +- `direction` - one of `in`, `out`, or `both` depending on the type of transition + +## Transition events + +An element with transitions will dispatch the following events in addition to any standard DOM events: + +- `introstart` +- `introend` +- `outrostart` +- `outroend` + +```svelte +{#if visible} +

(status = 'intro started')} + on:outrostart={() => (status = 'outro started')} + on:introend={() => (status = 'intro ended')} + on:outroend={() => (status = 'outro ended')} + > + Flies in and out +

+{/if} +``` + +## in:_fn_/out:_fn_ + +```svelte + +in:fn +``` + +```svelte + +in:fn={params} +``` + +```svelte + +in:fn|global +``` + +```svelte + +in:fn|global={params} +``` + +```svelte + +in:fn|local +``` + +```svelte + +in:fn|local={params} +``` + +```svelte + +out:fn +``` + +```svelte + +out:fn={params} +``` + +```svelte + +out:fn|global +``` + +```svelte + +out:fn|global={params} +``` + +```svelte + +out:fn|local +``` + +```svelte + +out:fn|local={params} +``` + +Similar to `transition:`, but only applies to elements entering (`in:`) or leaving (`out:`) the DOM. + +Unlike with `transition:`, transitions applied with `in:` and `out:` are not bidirectional — an in transition will continue to 'play' alongside the out transition, rather than reversing, if the block is outroed while the transition is in progress. If an out transition is aborted, transitions will restart from scratch. + +```svelte +{#if visible} +
flies in, fades out
+{/if} +``` + +## animate:_fn_ + +```svelte + +animate:name +``` + +```svelte + +animate:name={params} +``` + +```js +/// copy: false +// @noErrors +animation = (node: HTMLElement, { from: DOMRect, to: DOMRect } , params: any) => { + delay?: number, + duration?: number, + easing?: (t: number) => number, + css?: (t: number, u: number) => string, + tick?: (t: number, u: number) => void +} +``` + +```ts +/// copy: false +// @noErrors +DOMRect { + bottom: number, + height: number, + ​​left: number, + right: number, + ​top: number, + width: number, + x: number, + y: number +} +``` + +An animation is triggered when the contents of a [keyed each block](control-flow#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/svelte/reference/svelte-animate) or [custom animation functions](#custom-animation-functions). + +```svelte + +{#each list as item, index (item)} +
  • {item}
  • +{/each} +``` + +## Animation Parameters + +As with actions and transitions, animations can have parameters. + +(The double `{{curlies}}` aren't a special syntax; this is an object literal inside an expression tag.) + +```svelte +{#each list as item, index (item)} +
  • {item}
  • +{/each} +``` + +## Custom animation functions + +Animations can use custom functions that provide the `node`, an `animation` object and any `parameters` as arguments. The `animation` parameter is an object containing `from` and `to` properties each containing a [DOMRect](https://developer.mozilla.org/en-US/docs/Web/API/DOMRect#Properties) describing the geometry of the element in its `start` and `end` positions. The `from` property is the DOMRect of the element in its starting position, and the `to` property is the DOMRect of the element in its final position after the list has been reordered and the DOM updated. + +If the returned object has a `css` method, Svelte will create a CSS animation that plays on the element. + +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. + + + +```svelte + + +{#each list as item, index (item)} +
    {item}
    +{/each} +``` + +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. + +```svelte + + +{#each list as item, index (item)} +
    {item}
    +{/each} +``` + +## {#key ...} + +```svelte + +{#key expression}...{/key} +``` + +Key blocks destroy and recreate their contents when the value of an expression changes. + +This is useful if you want an element to play its transition whenever a value changes. + +```svelte +{#key value} +
    {value}
    +{/key} +``` + +When used around components, this will cause them to be reinstantiated and reinitialised. + +```svelte +{#key value} + +{/key} +``` diff --git a/apps/svelte.dev/content/docs/svelte/02-template-syntax/07-actions.md b/apps/svelte.dev/content/docs/svelte/02-template-syntax/07-actions.md index 3f237b5ce..5752b039f 100644 --- a/apps/svelte.dev/content/docs/svelte/02-template-syntax/07-actions.md +++ b/apps/svelte.dev/content/docs/svelte/02-template-syntax/07-actions.md @@ -5,3 +5,99 @@ title: Actions - template syntax - how to write - typings +- adjust so that `$effect` is used instead of update/destroy? + +```svelte + +use:action +``` + +```svelte + +use:action={parameters} +``` + +```ts +/// copy: false +// @noErrors +action = (node: HTMLElement, parameters: any) => { + update?: (parameters: any) => void, + destroy?: () => void +} +``` + +Actions are functions that are called when an element is created. They can return an object with a `destroy` method that is called after the element is unmounted: + +```svelte + + + +
    +``` + +An action can have a parameter. If the returned value has an `update` method, it will be called immediately after Svelte has applied updates to the markup whenever that parameter changes. + +> Don't worry that we're redeclaring the `foo` function for every component instance — Svelte will hoist any functions that don't depend on local state out of the component definition. + +```svelte + + + +
    +``` + +## Attributes + +Sometimes actions emit custom events and apply custom attributes to the element they are applied to. To support this, actions typed with `Action` or `ActionReturn` type can have a last parameter, `Attributes`: + +```svelte + + + +
    +``` diff --git a/apps/svelte.dev/content/docs/svelte/02-template-syntax/08-bindings.md b/apps/svelte.dev/content/docs/svelte/02-template-syntax/08-bindings.md index 6af0b7e99..64fb63690 100644 --- a/apps/svelte.dev/content/docs/svelte/02-template-syntax/08-bindings.md +++ b/apps/svelte.dev/content/docs/svelte/02-template-syntax/08-bindings.md @@ -5,3 +5,301 @@ title: Bindings - how for dom elements - list of all bindings - how for components + +Most of the time a clear separation between data flowing down and events going up is worthwhile and results in more robust apps. But in some cases - especially when interacting with form elements - it's more ergonomic to declare a two way binding. Svelte provides many element bindings out of the box, and also allows component bindings. + +## bind:_property_ for elements + +```svelte + +bind:property={variable} +``` + +Data ordinarily flows down, from parent to child. The `bind:` directive allows data to flow the other way, from child to parent. Most bindings are specific to particular elements. + +The simplest bindings reflect the value of a property, such as `input.value`. + +```svelte + +