new·The score now tells you which way it movedA brain's exam only ever grows: its own material writes questions, and so does every question a real caller asked and did not get answered. The score is a percentage over that growing set, so a brain that learned more could post a smaller number — and this week three did. One of them answered two MORE questions than the week before and showed eighteen points less. Printed as a single percentage, that reads as decline to a reader and as punishment to anyone who contributes material.all news →
mozg.beta
Sign in

Svelte · Language · all subjects

core/template-syntax

188 notes in this subject, read out of this brain and free to use. This is page 2 of 4.

{@const ...} is legacy syntax

The {@const ...} syntax for declaration tags is considered legacy in Svelte 5. The modern approach is to use the {const ...} syntax instead.

Declaration tag reactivity with $state and $derived

Declaration tags can be reactive by using $state and $derived runes. You can create a reactive local variable with {let name = $state(initialValue)} and a derived reactive variable with {const greeting = $derived(expression)}.

Declaration tags with const and let

Declaration tags define local variables inside markup using either const or let syntax. They are written as {const variableName = value} or {let variableName = value} and are available since Svelte 5.56.

Declaration tags in each blocks

Declaration tags can be used inside {#each} blocks to create local computed values for each iteration. For example, you can use {const area = box.width * box.height} to compute a value based on the current iteration variable.

Action function signature with $effect

An action function receives the mounted DOM node as its first parameter. Inside the action, use $effect to set up initialization logic. Return a function from the $effect callback to run teardown logic when the element unmounts.

use: directive for actions

Actions are functions called when an element is mounted to the DOM. They are added to elements with the use: directive syntax. Actions are only called once and do not run again if the argument changes.

Legacy action update and destroy methods

Prior to the $effect rune, actions could return an object with update and destroy methods. The update method would be called when the argument changed, and destroy would run on cleanup. This pattern is now legacy; using $effect is the preferred approach.

Action not called during server-side rendering

Actions are only invoked on the client side. They do not run during server-side rendering.

Action type interface with custom events

The Action interface from 'svelte/action' accepts three optional type arguments: the node type (e.g., HTMLDivElement or Element), an optional parameter type, and an object defining custom event handlers. Custom events dispatched by the action appear as typed handlers on the element, such as onswipeleft and onswiperight.

Attachments as alternative to use: directive

In Svelte 5.29 and newer, attachments should be considered as an alternative to the use: directive. Attachments are more flexible and composable than actions.

Actions with parameters

An action function can accept a second parameter for data. This is passed using the syntax use:actionName={data} on the element. The action receives both the node and the data parameter.

bind:value on input elements

A bind:value directive on an input element binds the input's value property. For numeric inputs (type="number" or type="range"), the value will be coerced to a number. If the input is empty or invalid (in the case of type="number"), the value is undefined.

bind: directive general syntax

The bind: directive allows data to flow from child to parent. The general syntax is bind:property={expression}, where expression is an lvalue (a variable or object property). When the expression is an identifier with the same name as the property, the expression can be omitted, so bind:value={value} and bind:value are equivalent.

bind: event listener behavior

Svelte creates an event listener that updates the bound value. If an element already has a listener for the same event, that listener will be fired before the bound value is updated.

Two-way and readonly bindings

Most bindings are two-way, meaning that changes to the value will affect the element and vice versa. A few bindings are readonly, meaning that changing their value will have no effect on the element.

Function bindings syntax

Function bindings use the syntax bind:property={get, set}, where get and set are functions, allowing you to perform validation and transformation. For readonly bindings like dimension bindings, the get value should be null. Function bindings are available in Svelte 5.9.0 and newer.

Input defaultValue behavior since 5.6.0

Since 5.6.0, if an input has a defaultValue attribute and is part of a form, it will revert to that value instead of the empty string when the form is reset. For the initial render the value of the binding takes precedence unless it is null or undefined.

bind:checked for checkbox inputs

Checkbox inputs can be bound with bind:checked. Since 5.6.0, if an input has a defaultChecked attribute and is part of a form, it will revert to that value instead of false when the form is reset. For the initial render the value of the binding takes precedence unless it is null or undefined.

bind:indeterminate for checkboxes

Checkboxes can be in an indeterminate state, independently of whether they are checked or unchecked. This can be bound using bind:indeterminate.

bind:group for input grouping

Inputs that work together can use bind:group. Grouped radio inputs are mutually exclusive. Grouped checkbox inputs populate an array. bind:group only works if the inputs are in the same Svelte component.

bind:files on file input elements

On input elements with type="file", you can use bind:files to get the FileList of selected files. When you want to update the files programmatically, you always need to use a FileList object. Currently FileList objects cannot be constructed directly, so you need to create a new DataTransfer object and get files from there. FileList objects also cannot be modified, so if you want to delete a single file from the list, you need to create a new DataTransfer object and add the files you want to keep. DataTransfer may not be available in server-side JS runtimes.

bind:value on select elements

A select value binding corresponds to the value property on the selected option, which can be any value (not just strings, as is normally the case in the DOM). A select multiple element behaves similarly to a checkbox group. The bound variable is an array with an entry corresponding to the value property of each selected option. When the value of an option matches its text content, the attribute can be omitted. You can give the select a default value by adding a selected attribute to the option(s) that should be initially selected. If the select is part of a form, it will revert to that selection when the form is reset. For the initial render the value of the binding takes precedence if it's not undefined.

Audio element bindings

Audio elements have five two-way bindings: currentTime, playbackRate, paused, volume, muted. Audio elements have six readonly bindings: duration, buffered, seekable, seeking, ended, readyState, played.

Video element bindings

Video elements have all the same bindings as audio elements, plus readonly videoWidth and videoHeight bindings.

Image element bindings

img elements have two readonly bindings: naturalWidth and naturalHeight.

bind:open on details elements

details elements support binding to the open property using bind:open.

Contenteditable element bindings

Elements with the contenteditable attribute support the following bindings: innerHTML, innerText, textContent. There are subtle differences between innerText and textContent.

Dimension bindings on visible elements

All visible elements have the following readonly bindings, measured with a ResizeObserver: clientWidth, clientHeight, offsetWidth, offsetHeight, contentRect, contentBoxSize, borderBoxSize, devicePixelContentBoxSize. display: inline elements do not have a width or height (except for elements with 'intrinsic' dimensions, like img and canvas), and cannot be observed with a ResizeObserver. You will need to change the display style of these elements to something else, such as inline-block. CSS transformations do not trigger ResizeObserver callbacks.

bind:this for DOM node references

To get a reference to a DOM node, use bind:this={dom_node}. The value will be undefined until the component is mounted. You should read it inside an effect or an event handler, but not during component initialisation. When using function bindings, the getter is required to ensure that the correct value is nullified on component or element destruction.

bind:this for component instances

Components also support bind:this, allowing you to interact with component instances programmatically. All instance exports are available on the instance object.

bind:property for component props

You can bind to component props using the same syntax as for elements: bind:property={variable}. While Svelte props are reactive without binding, that reactivity only flows downward into the component by default. Using bind:property allows changes to the property from within the component to flow back up out of the component.

$bindable rune for component properties

To mark a property as bindable, use the $bindable() rune. Declaring a property as bindable means it can be used using bind:, not that it must be used using bind:. Bindable properties can have a fallback value. This fallback value only applies when the property is not bound. When the property is bound and a fallback value is present, the parent is expected to provide a value other than undefined, else a runtime error is thrown. This prevents hard-to-reason-about situations where it's unclear which value should apply.

in: transition example

The in: directive can be applied to elements to specify a transition that plays when the element enters the DOM. For example, in:fly={{ y: 200 }} applies a fly transition with a y offset of 200.

out: transition example

The out: directive can be applied to elements to specify a transition that plays when the element exits the DOM. For example, out:fade applies a fade transition.

in: and out: directives vs transition:

The in: and out: directives are identical to transition:, except that the resulting transitions 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.

Transitions keep elements in DOM until completion

When a block (such as {#if ...}) is transitioning out, all elements inside it, including those without their own transitions, are kept in the DOM until every transition in the block has been completed.

Built-in transitions module

A selection of built-in transitions can be imported from the svelte/transition module. Transitions like fade are available as named exports.

transition: parameters syntax

Transitions can have parameters passed using an object literal inside the directive. Example: transition:fade={{ duration: 2000 }} passes a duration parameter. The double curly braces are an object literal inside an expression tag, not special syntax.

Custom transition function signature

A custom transition function has the signature: 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 }. The function receives the DOM node, parameters, and options including direction.

transition css function t and u parameters

The t argument passed to the css function 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, where 1 represents the element's natural state. The u argument equals 1 - t. The function is called repeatedly before the transition begins with different t and u arguments.

transition css function for web animations

If a transition function returns an object with a css function, Svelte will generate keyframes for a web animation. Web animations can run off the main thread, preventing jank on slower devices.

transition tick function

A custom transition function can return a tick function, which is called during the transition with the same t and u arguments. Use css instead of tick when possible, as web animations can run off the main thread.

transition function returning deferred function

If a transition function returns a function instead of a transition object, that function will be called in the next microtask. This allows multiple transitions to coordinate, making crossfade effects possible.

transition options third argument

Transition functions receive a third argument called options, which contains information about the transition. Available values include direction, which is one of 'in', 'out', or 'both' depending on the type of transition.

transition: directive basic syntax

The transition: directive indicates a bidirectional transition that can be smoothly reversed while in progress. It is triggered when an element enters or leaves the DOM as a result of a state change. Example: transition:fade applied to an element.

transition: local vs global modifier

Transitions are local by default, playing only when the block they belong to is created or destroyed, not when parent blocks change. Use the |global modifier to make a transition play when any parent block is created or destroyed. Example: transition:fade|global

Tick method in animation return object

A custom animation function can return a tick method instead of or in addition to css. The tick method is called during the animation with the same t and u arguments as css. Using css instead of tick is preferred because web animations can run off the main thread, preventing jank on slower devices.

Animation function example with tick for color change

A custom animation using tick can modify element styles during the animation. Example: tick: (t, u) => Object.assign(node.style, { color: t > 0.5 ? 'Pink' : 'Blue' }) changes the element's color based on animation progress.

animate: directive triggers on keyed each block reordering

Animations triggered by the animate: directive run when contents of a keyed each block 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: must be on immediate child of keyed each block

Animate directives must be placed on an element that is an immediate child of a keyed each block.

Built-in animation functions in Svelte

Svelte provides built-in animation functions that can be used with the animate: directive, such as animate:flip for reordering animations.

animate: directive syntax with parameters

Animation directives accept parameters passed as an object literal. Example: animate:flip={{ delay: 500 }} passes a delay parameter to the flip animation function.

Custom animation function signature

A custom animation function receives three arguments: the HTMLElement node, an animation object containing from and to properties (each a DOMRect), and any parameters object. The function should return an object with optional properties: delay (number), duration (number), easing (function), css (function), or tick (function).

DOMRect in animation object describes element geometry

The animation object passed to custom animation functions contains from and to properties. The from property is a DOMRect describing the element's geometry at its starting position. The to property is a DOMRect describing the element's geometry at its final position after the list has been reordered and the DOM updated.

CSS method in animation return object

If a custom animation function's returned object has a css method, Svelte will create a web animation that plays on the element. The css method receives two arguments: t (a value from 0 to 1 after easing is applied) and u (equal to 1 - t). The function is called repeatedly before the animation begins with different t and u arguments.

Animation function example with translate and rotate

A custom animation using css can calculate the distance between start and end positions and return a css string with transforms. Example: css: (t, u) => `transform: translate(${u * dx}px, ${u * dy}px) rotate(${t * 360}deg);` translates the element using u and rotates it using t.

style: directive precedence over style attribute

When style: directives are combined with style attributes on the same element, the directives take precedence. This applies even when the style attribute contains !important properties. For example, style:color="red" style="color: blue !important" will result in the element being red.

style: directive basic syntax

The style: directive provides a shorthand for setting styles on an element. style:color="red" is equivalent to style="color: red;".

style: directive with arbitrary expressions

The value in a style: directive can contain arbitrary expressions. For example, style:color={myColor} will bind the color style to the myColor variable.

style: directive shorthand form

When the style property name matches a variable name, the shorthand form style:color can be used instead of style:color={color}. This sets the color style to the value of the color variable.

Give your agent this brain