## 1. Project Overview & Quickstart (sveltejs/LICENSE)

# LICENSE

Open-source repository sveltejs/LICENSE

### Repository Details
- **Repository:** [sveltejs/LICENSE](https://github.com/sveltejs/LICENSE)
- **Primary Language:** Code

*Note: High-volume repository documentation is actively indexed and synchronized by YakaAI.*

## 2. Official Technical Reference & Guides (sveltejs/sveltejs.github.io)

## File: README.md

# [v2.svelte.dev](https://v2.svelte.dev)

The website for Svelte v2.

## Note

**This is the repo for the Svelte v2 site.** The Svelte v3 site lives in [the `site` directory of the main Svelte repo](https://github.com/sveltejs/svelte/tree/master/site).

## Running locally

This project uses [yarn](https://yarnpkg.com) to manage dependencies.

Set up the project:

```bash
git clone git@github.com:sveltejs/v2.svelte.dev.git
cd v2.svelte.dev
yarn
```

Start the server with `yarn run dev`, and navigate to [localhost:3000](http://localhost:3000).

## Using a local copy of Svelte

By default, the REPL will fetch the most recent version of Svelte from https://unpkg.com/svelte. If you need to test a local version of Svelte, you can do so by linking it and navigating to [localhost:3000/repl?version=local](http://localhost:3000/repl?version=local):

```bash
cd /path/to/svelte
yarn link
yarn dev # rebuild Svelte on changes

cd /path/to/v2.svelte.dev
yarn link svelte
yarn dev
```

## REPL GitHub integration

In order for the REPL's GitHub integration to work properly when running locally, you will need to create a GitHub OAuth app. Set its authorization callback URL to `http://localhost:3000/auth/callback`, and in the root of this project, create a file `.env` containing:

```
GITHUB_CLIENT_ID=[your app's client id]
GITHUB_CLIENT_SECRET=[your app's client secret]
BASEURL=http://localhost:3000
```

## License

[MIT](LICENSE)

---

## File: content/guide/00-introduction.md

---
title: Introduction
---

### What is Svelte?

Svelte is a tool for building fast web applications.

It is similar to JavaScript frameworks such as React, Angular, Vue, and Ractive, which all 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.

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.

[Read the introductory blog post](/blog/frameworks-without-the-framework) to learn more about Svelte's goals and philosophy.


### Understanding Svelte components

In Svelte, an application is composed from one or more *components*. A component is a reusable self-contained block of code that encapsulates markup, styles and behaviours that belong together.

Like Ractive and Vue, Svelte promotes the concept of *single-file components*: a component is just an `.html` file. Here's a simple example:

```html

<h1>Hello {name}!</h1>
```

```json
/* { hidden: true } */
{
	name: 'world'
}
```

> Wherever you see REPL links, click through for an interactive example

Svelte turns this into a JavaScript module that you can import into your app:

```js
/* { filename: 'main.js' } */
import App from './App.html';

const app = new App({
	target: document.querySelector('main'),
	data: { name: 'world' }
});

// change the data associated with the template
app.set({ name: 'everybody' });

// detach the component and clean everything up
app.destroy();
```

Congratulations, you've just learned about half of Svelte's API!


### Getting started

Normally, this is the part where the instructions might tell you to add the framework to your page as a `<script>` tag. But because Svelte runs at build time, it works a little bit differently.

The best way to use Svelte is to integrate it into your build system – there are plugins for Rollup, Browserify, Gulp and others, with more on the way. See [here](https://github.com/sveltejs/svelte/#svelte) for an up-to-date list.

> You will need to have [Node.js](https://nodejs.org/en/) installed, and have some familiarity with the command line

#### Getting started using the REPL

Going to the [REPL](/repl) and pressing the *download* button on any of the examples will give you a .zip file containing everything you need to run that example locally. Just unzip it, `cd` to the directory, and run `npm install` and `npm run dev`. See [this blog post](/blog/the-easiest-way-to-get-started) for more information.

#### Getting started using degit

[degit](https://github.com/Rich-Harris/degit) is a tool for creating projects from templates stored in git repos. Install it globally...

```bash
npm install degit
```

...then you can use it to spin up a new project:

```bash
degit sveltejs/template my-new-project
cd my-new-project
npm install
npm run dev
```

You can use any git repo you like — these are the 'official' templates:

* [sveltejs/template](https://github.com/sveltejs/template) — this is what you get by downloading from the REPL
* [sveltejs/template-webpack](https://github.com/sveltejs/template-webpack) — similar, but uses [webpack](https://webpack.js.org/) instead of [Rollup](https://rollupjs.org/guide/en)

#### Getting started using the CLI

Svelte also provides a Command Line Interface, but it's not recommended for production use. The CLI will compile your components to standalone JavaScript files, but won't automatically recompile them when they change, and won't deduplicate code shared between your components. Use one of the above methods instead.

If you've installed `svelte` globally, you can use `svelte --help` for a complete list of options. Some examples of the more common operations are:

```bash
# Generate a JavaScript module from MyComponent.html
svelte compile MyComponent.html > MyComponent.js
svelte compile -i MyComponent.html -o MyComponent.js

# Generate a UMD module from MyComponent.html, inferring its name from the filename ('MyComponent')
svelte compile -f umd MyComponent.html > MyComponent.js

# Generate a UMD module, specifying the name
svelte compile -f umd -n CustomName MyComponent.html > MyComponent.js

# Compile all .html files in a directory
svelte compile -i src/components -o build/components
```

> You can also use [npx](https://medium.com/@maybekatz/introducing-npx-an-npm-package-runner-55f7d4bd282b) to use the CLI without installing Svelte globally — just prefix your command with `npx`: `npx svelte compile ...`

---

## File: content/guide/01-component-api.md

---
title: Component API
---

As we saw above, you create a component instance with the `new` keyword:

```js
/* { filename: 'main.js' } */
import MyComponent from './MyComponent.html';

const component = new MyComponent({
	// `target` is the only required option. This is the
	// DOM element your component will be appended to
	target: document.querySelector('main'),

	// `anchor` is optional.
	// The component is inserted immediately before this
	// DOM element, which must be a child of `target`
	anchor: document.querySelector('main #child'),

	// `data` is optional.
	// A component can have default data – we'll learn about that later.
	data: {
		questions: [
			'life',
			'the universe',
			'everything'
		],
		answer: 42
	}
});
```

Every Svelte component instance has a small number of methods you can use to control it, in addition to any [custom methods](guide#custom-methods) you add.


### component.set(state)

This updates the component's state with the new values provided and causes the DOM to update. `state` must be a plain old JavaScript object (POJO). Any properties *not* included in `state` will remain as they were.

```js
component.set({
	questions: [
		'why is the sky blue?',
		'how do planes fly?',
		'where do babies come from?'
	],
	answer: 'ask your mother'
});
```


### component.get()

Returns the component's current state:

```js
const { questions, answer } = component.get();
console.log(answer); // 'ask your mother'
```

This will also retrieve the value of [computed properties](guide#computed-properties).

> Previous versions of Svelte allowed you to specify a key to retrieve a specific value — this was removed in version 2.

### component.on(eventName, callback)

Allows you to respond to *events*:

```js
const listener = component.on('thingHappened', event => {
	console.log(`A thing happened: ${event.thing}`);
});

// some time later...
listener.cancel();
```

Each component has three built-in events, corresponding to their [lifecycle hooks](guide#lifecycle-hooks):

```js
component.on('state', ({ changed, current, previous }) => {
	console.log('state changed', current);
});

component.on('update', ({ changed, current, previous }) => {
	console.log('DOM updated after state change', current);
});

component.on('destroy', () => {
	console.log('this component is being destroyed');
});
```


### component.fire(eventName, event)

The companion to `component.on(...)`:

```js
component.fire('thingHappened', {
	thing: 'this event was fired'
});
```

At first glance `component.on(...)` and `component.fire(...)` aren't particularly useful, but it'll become more so when we learn about [nested components](guide#nested-components) and [component events](guide#component-events).


### component.destroy()

Removes the component from the DOM and removes any event listeners that were created. This will also fire a `destroy` event:

```js
component.on('destroy', () => {
	alert('goodbye!'); // please don't do this
});

component.destroy();
```


### component.options

The options used to instantiate the component are available in `component.options`.

```html

Check the console.

<script>
	export default {
		oncreate() {
			console.log(this.options);
		}
	};
</script>
```

This gives you access to standard options like `target` and `data`, but can also be used to access any other custom options you may choose to implement for your component.


### component.root

In [nested components](guide#nested-components), each component has a `root` property pointing to the top-level root component – that is, the one instantiated with `new MyComponent({...})`.

> Earlier versions of Svelte had a `component.observe(...)` method. This was removed in version 2, in favour of the `onstate` [lifecycle hook](guide#lifecycle-hooks), but is still available via [svelte-extras](https://github.com/sveltejs/svelte-extras).

---

## File: content/guide/02-template-syntax.md

---
title: Template syntax
---

Rather than reinventing the wheel, Svelte templates are built on foundations that have stood the test of time: HTML, CSS and JavaScript. There's very little extra stuff to learn.

> Svelte version 1 had a slightly different template syntax. You can upgrade older components automatically using [svelte-upgrade](https://github.com/sveltejs/svelte-upgrade).


### Tags

Tags allow you to bind data to your template. Whenever your data changes (for example after `component.set(...)`), the DOM updates automatically. You can use any JavaScript expression in templates, and it will also automatically update:

```html

{a} + {b} = {a + b}
```

```json
/* { hidden: true } */
{
	"a": 1,
	"b": 2
}
```

You can also use tags in attributes:

```html

<h1 style="color: {color};">{color}</h1>
You can hide this paragraph.
```

```json
/* { hidden: true } */
{
	color: "steelblue",
	hideParagraph: false
}
```
[Boolean attributes](https://www.w3.org/TR/html5/infrastructure.html#sec-boolean-attributes) like `hidden` will be omitted if the tag expression evaluates to false. Attributes will be removed from the element if their value is `undefined` or `null`.

### HTML

Ordinary tags render expressions as plain text. If you need your expression interpreted as HTML, wrap it in a special `@html` tag:

```html

This HTML: {content}
Renders as: {@html content}
```

```json
/* { hidden: true } */
{
	content: "Some **bold** text."
}
```

As with regular tags, you can use any JavaScript expression in HTML tags, and it will automatically update the document when your data changes.

> HTML is **not** sanitized before it is rendered! If you are displaying user input, you are responsible for first sanitizing it. Not doing so potentially opens you up to XSS attacks.


### If blocks

Control whether or not part of your template is rendered by wrapping it in an if block.

```html

{#if user.loggedIn}
	[log out](/logout)
{/if}

{#if !user.loggedIn}
	[log in](/login)
{/if}
```

You can combine the two blocks above with `{:else}`:

```html

{#if user.loggedIn}
	[log out](/logout)
{:else}
	[log in](/login)
{/if}
```

You can also use `{:elseif ...}`:

```html

{#if x > 10}
	{x} is greater than 10
{:elseif 5 > x}
	{x} is less than 5
{:else}
	{x} is between 5 and 10
{/if}
```

```json
/* { hidden: true } */
{
	x: 7
}
```

### Each blocks

Iterate over lists of data:

```html

<h1>Cats of YouTube</h1>


	{#each cats as cat}
		<li><a target="_blank" href={cat.video}>{cat.name}</a></li>
	{:else}
		<li>No cats :(</li>
	{/each}

```

```json
/* { hidden: true } */
{
	cats: [
		{
			name: "Keyboard Cat",
			video: "https://www.youtube.com/watch?v=J---aiyznGQ"
		},
		{
			name: "Maru",
			video: "https://www.youtube.com/watch?v=z_AbfPXTKms"
		},
		{
			name: "Henri The Existential Cat",
			video: "https://www.youtube.com/watch?v=OUtn3pvWmpg"
		}
	]
}
```

Else is triggered when the list is empty.

You can access the index of the current element with *expression* as *name*, *index*:

```html


	{#each rows as row, y}
		
			{#each columns as column, x}
				<code class="cell">
					{x + 1},{y + 1}:
					**{row[column]}**
				</code>
			{/each}
		
	{/each}

```

```json
/* { hidden: true } */
{
	columns: ["foo", "bar", "baz"],
	rows: [
		{ foo: "a", bar: "b", baz: "c" },
		{ foo: "d", bar: "e", baz: "f" },
		{ foo: "g", bar: "h", baz: "i" }
	]
}
```

> By default, if the list `a, b, c` becomes `a, c`, Svelte will *remove* the third block and *change* the second from `b` to `c`, rather than removing `b`. If that's not what you want, use a [keyed each block](guide#keyed-each-blocks).

You can use destructuring patterns on the elements of the array:

```html

<h1>It's the cats of YouTube again</h1>


	{#each cats as {name, video} }
		<li><a target="_blank" href={video}>{name}</a></li>
	{/each}

```

```json
/* { hidden: true } */
{
	cats: [
		{
			name: "Keyboard Cat",
			video: "https://www.youtube.com/watch?v=J---aiyznGQ"
		},
		{
			name: "Maru",
			video: "https://www.youtube.com/watch?v=z_AbfPXTKms"
		},
		{
			name: "Henri The Existential Cat",
			video: "https://www.youtube.com/watch?v=OUtn3pvWmpg"
		}
	]
}
```

If you want to iterate over an object you can use `Object.entries(object)` which returns the object's properties as `[key, value]` pairs:

```html

<h1>Cats and Dogs</h1>

{#each Object.entries(animals) as [animal, names]}
	{animal}: {names.join(" and ")}
{/each}
```

```json
/* { hidden: true } */
{
	animals: {
		Cats: ["Buzz", "Stella"],
		Dogs: ["Hector", "Victoria"]
	}
}
```

### Await blocks

You can represent the three states of a [Promise](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) — pending, fulfilled and rejected — with an `await` block:

```html

{#await promise}
	wait for it...
{:then answer}
	the answer is {answer}!
{:catch error}
	well that's odd
{/await}

<script>
	export default {
		data() {
			return {
				promise: new Promise(fulfil => {
					setTimeout(() => fulfil(42), 3000);
				})
			};
		}
	};
</script>
```

If the expression in `{#await expression}` *isn't* a promise, Svelte skips ahead to the `then` section.


### Directives

Directives allow you to add special instructions for adding [event handlers](guide#event-handlers), [bindings](guide#bindings), [referencing elements](guide#refs) and so on. We'll cover each of those in later stages of this guide – for now, all you need to know is that directives can be identified by the `:` character:

```html

Count: {count}
+1
```

```json
/* { hidden: true } */
{
	count: 0
}
```

> Technically, the `:` character is used to denote namespaced attributes in HTML. These will *not* be treated as directives, if encountered.


### Debug tags

To inspect data as it changes and flows through your app, use a `{@debug ...}` tag:

```html



{@debug name}
<h1>Hello {name}!</h1>
```

```json
/* { hidden: true } */
{
	name: 'world'
}
```

This will log the value of `name` whenever it changes. If your devtools are open, changing `name` will pause execution and open the debugger.

You can debug multiple values simultaneously (`{@debug foo, bar, baz}`), or use `{@debug}` to pause execution whenever the surrounding markup is updated.

> Debug tags only have an effect when compiling with the `dev: true` compiler option.

---

## File: content/guide/03-scoped-styles.md

---
title: Scoped styles
---

One of Svelte's key tenets is that components should be self-contained and reusable in different contexts. Because of that, it has a mechanism for *scoping* your CSS, so that you don't accidentally clobber other selectors on the page.

### Adding styles

Your component template can have a `<style>` tag, like so:

```html


	Big red Comic Sans


<style>
	.foo {
		color: red;
		font-size: 2em;
		font-family: 'Comic Sans MS';
	}
</style>
```


### How it works

Open the example above in the REPL and inspect the element to see what has happened – Svelte has added a `svelte-[uniqueid]` class to the element, and transformed the CSS selector accordingly. Since no other element on the page can share that selector, anything else on the page with `class="foo"` will be unaffected by our styles.

This is vastly simpler than achieving the same effect via [Shadow DOM](http://caniuse.com/#search=shadow%20dom) and works everywhere without polyfills.

> Svelte will add a `<style>` tag to the page containing your scoped styles. Dynamically adding styles may be impossible if your site has a [Content Security Policy](https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP). If that's the case, you can use scoped styles by [server-rendering your CSS](guide#rendering-styles) and using the `css: false` compiler option (or `--no-css` with the CLI).


### Cascading rules

Styles will *only* apply to the current component, unless you opt in to cascading with the `:global(...)` modifier:



```html


	<Widget/>


<style>
	p {
		/* this block will be disregarded, since
		   there are no  elements here */
		color: red;
	}

	div :global(p) {
		/* this block will be applied to any  elements
		   inside the , i.e. in <Widget> */
		font-weight: bold;
	}
</style>

<script>
	import Widget from './Widget.html';

	export default {
		components: { Widget }
	};
</script>
```

> Scoped styles are *not* dynamic – they are shared between all instances of a component. In other words you can't use `{tags}` inside your CSS.


### Unused style removal

Svelte will identify and remove styles that are not being used in your app. It will also emit a warning so that you can remove them from the source.

For rules *not* to be removed, they must apply to the component's markup. As far as Svelte is concerned `.active` is unused in the following code and should be removed:

```html


	this text is not bold


<style>
	.active {
		color: bold;
	}
</style>

<script>
	export default {
		oncreate() {
			const { active } = this.get();
			if (active) this.refs.paragraph.classList.add('active');
		}
	};
</script>
```

Instead of manually manipulating the DOM, you should always use the `class` attribute (or the [class directive](guide#classes)):

```html


	this text is bold

```

If that's impossible for some reason, you can use `:global(...)`:

```html

<style>
	div :global(.active) {
		color: bold;
	}
</style>
```

The same applies to the contents of `{@html ...}` tags.


### Special selectors

If you have a [ref](guide#refs) on an element, you can use it as a CSS selector. The `ref:*` selector has the same specificity as a class or attribute selector.


```html


	yeah!


<style>
	ref:foo {
		color: magenta;
		font-size: 5em;
	}
</style>
```

---

## File: content/guide/04-behaviour.md

---
title: Behaviours
---

As well as scoped styles and a template, components can encapsulate *behaviours*. For that, we add a `<script>` element and export an object:

```html


	


<script>
	export default {
		// behaviours go here
	};
</script>
```


### Default data

Often, it makes sense for a component to have default data. This should be expressed as a function that returns a plain JavaScript object:

```html

Count: {count}
+1

<script>
	export default {
		data() {
			return {
				count: 0
			};
		}
	};
</script>
```

Data supplied at instantiation takes priority over defaults. In other words, if we instantiated the component above like so...

```js
const counter = new Counter({
	data: {
		count: 99
	}
});
```

...then `{count}`, or `counter.get().count`, would initially be 99 rather than 0.


### Computed properties

Often, your program will use values that depend on other values – for example, you might have a filtered list, which depends on both the list *and* the filter. Normally in JavaScript you'd have to add logic to update the dependent property when *any* of the dependencies change. This is a frequent source of bugs, and it gets worse as your application grows.

Svelte allows you to express these dependencies in computed properties, which are recalculated whenever those dependencies change:

```html


	The time is
	**{hours}:{minutes}:{seconds}**


<script>
	export default {
		data() {
			return {
				time: new Date()
			};
		},

		computed: {
			hours:   ({ time }) => time.getHours(),
			minutes: ({ time }) => time.getMinutes(),
			seconds: ({ time }) => time.getSeconds()
		}
	};
</script>
```

Each function is passed the component's current state object. Because we're using destructuring syntax, the compiler knows that `hours`, `minutes` and `seconds` only need to re-run when `time` changes, and not when any other values change. There's no costly dependency tracking involved – the dependency graph is resolved at compile time.

> `computed` must be an object literal, and the properties must be function expressions or arrow function expressions. Any external functions used in computed must be wrapped _here_:

```js
import externalFunc from '_external_file';
export default {
	computed: {
		externalFunc: ({ dep1, dep2 }) => externalFunc(dep1, dep2);
	}
}
```

Computed properties can of course return functions. For example, we could dynamically generate a filter function for a list of items:

```html



{#each items.filter(predicate) as word}
	**{word.slice(0, search.length)}**{word.slice(search.length)}
{:else}
	no matches!
{/each}

<script>
	export default {
		computed: {
			predicate: ({ search }) => {
				search = search.toLowerCase();
				return word => word.startsWith(search);
			}
		}
	};
</script>
```

```
/* Detailed source-code truncated for AI context efficiency. */
```


### Lifecycle hooks

There are four 'hooks' provided by Svelte for adding control logic — `oncreate`, `ondestroy`, `onstate` and `onupdate`:

```html


	The time is
	**{hours}:{minutes}:{seconds}**


<script>
	export default {
		onstate({ changed, current, previous }) {
			// this fires before oncreate, and on every state change.
			// the first time it runs, `previous` is undefined
			if (changed.time) {
				console.log(`time changed: ${previous && previous.time} -> ${current.time}`);
			}
		},

		oncreate() {
			// this fires when the component has been
			// rendered to the DOM
			console.log('in oncreate');

			this.interval = setInterval(() => {
				this.set({ time: new Date() });
			}, 1000);
		},

		onupdate({ changed, current, previous }) {
			// this fires after oncreate, and after every state change
			// once the DOM is synchronised with the data
			console.log(`The DOM has been updated`);
		},

		ondestroy() {
			// this fires when the component is
			// removed from the DOM
			console.log('in ondestroy');

			clearInterval(this.interval);
		},

		data() {
			return {
				time: new Date()
			};
		},

		computed: {
			hours:   ({ time }) => time.getHours(),
			minutes: ({ time }) => time.getMinutes(),
			seconds: ({ time }) => time.getSeconds()
		}
	};
</script>
```

> You can add event listeners corresponding to `onstate`, `onupdate` and `ondestroy` programmatically — see [component.on](guide#component-on-eventname-callback-)


### Helpers

Helpers are simple functions that are used in your template. In the example above, we want to ensure that `minutes` and `seconds` are preceded with a `0` if they only have one digit, so we add a `leftPad` helper:

```html


	The time is
	**{hours}:{leftPad(minutes, 2, '0')}:{leftPad(seconds, 2, '0')}**


<script>
	import leftPad from 'left-pad';

	export default {
		helpers: {
			leftPad
		},

		oncreate() {
			this.interval = setInterval(() => {
				this.set({ time: new Date() });
			}, 1000);
		},

		ondestroy() {
			clearInterval(this.interval);
		},

		data() {
			return {
				time: new Date()
			};
		},

		computed: {
			hours:   ({ time }) => time.getHours(),
			minutes: ({ time }) => time.getMinutes(),
			seconds: ({ time }) => time.getSeconds()
		}
	};
</script>
```

Of course, you could use `leftPad` inside the computed properties instead of in the template. There's no hard and fast rule about when you should use expressions with helpers versus when you should use computed properties – do whatever makes your component easier for the next developer to understand.

> Helper functions should be *pure* – in other words, they should not have side-effects, and their returned value should only depend on their arguments.


### Custom methods

In addition to the [built-in methods](guide#component-api), you can add methods of your own:

```html

Try calling `app.say('hello!')` from the console

<script>
	export default {
		methods: {
			say(message) {
				alert(message); // again, please don't do this
			}
		}
	};
</script>
```

These become part of the component's API:

```js
import MyComponent from './MyComponent.html';

var component = new MyComponent({
	target: document.querySelector('main')
});

component.say('👋');
```

Methods (whether built-in or custom) can also be called inside [event handlers](guide#event-handlers):

```html

say hello!
```


### Custom event handlers

Soon, we'll learn about [event handlers](guide#event-handlers) – if you want, skip ahead to that section first then come back here!

Most of the time you can make do with the standard DOM events (the sort you'd add via `element.addEventListener`, such as `click`) but sometimes you might need custom events to handle gestures, for example.

Custom events are just functions that take a node and a callback as their argument, and return an object with a `destroy` method that gets called when the element is removed from the page:

```html

click and hold

{#if done}
	clicked and held
{/if}

<script>
	export default {
		events: {
			longpress(node, callback) {
				function onmousedown(event) {
					const timeout = setTimeout(() => callback(event), 1000);

					function cancel() {
						clearTimeout(timeout);
						node.removeEventListener('mouseup', cancel, false);
					}

					node.addEventListener('mouseup', cancel, false);
				}

				node.addEventListener('mousedown', onmousedown, false);

				return {
					destroy() {
						node.removeEventListener('mousedown', onmousedown, false);
					}
				};
			}
		}
	};
</script>
```


### Namespaces

Components are assumed to be in the HTML namespace. If your component is designed to be used inside an `<svg>` element, you need to specify the namespace:

```html

<svg viewBox="0 0 1000 1000" style="width: 100%; height: 100%;">
	<SmileyFace x=70 y=280 size=100 fill="#f4d9c7"/>
	<SmileyFace x=800 y=250 size=150 fill="#40250f"/>
	<SmileyFace x=150 y=700 size=110 fill="#d2aa7a"/>
	<SmileyFace x=875 y=730 size=130 fill="#824e2e"/>
	<SmileyFace x=450 y=500 size=240 fill="#d2b198"/>
</svg>

<script>
	import SmileyFace from './SmileyFace.html';

	export default {
		components: { SmileyFace }
	};
</script>
```

```html


<g transform="translate({x},{y}) scale({size / 366.5})">
	<circle r=366.5/>
	<circle r=336.5 fill={fill}/>
	
	
	
	
	
	
	
</g>

<script>
	export default {
		// you can either use the shorthand 'svg', or the full
		// namespace: 'http://www.w3.org/2000/svg'. (I know
		// which one I prefer.)
		namespace: 'svg',

		data() {
			return {
				x: 100,
				y: 100,
				size: 100
			};
		}
	};
</script>
```

---

## File: content/guide/05-nested-components.md

---
title: Nested components
---

As well as containing elements (and `if` blocks and `each` blocks), Svelte components can contain *other* Svelte components.

```html


	<Widget/>


<script>
	import Widget from './Widget.html';

	export default {
		components: {
			Widget
		}
	};
</script>
```

```html

I am a nested component
```

That's similar to doing this...

```js
import Widget from './Widget.html';

const widget = new Widget({
	target: document.querySelector('.widget-container')
});
```

...except that Svelte takes care of destroying the child component when the parent is destroyed, and keeps the two components in sync with *props*.

> Component names must be capitalised, following the widely-used JavaScript convention of capitalising constructor names. It's also an easy way to distinguish components from elements in your template.


### Props

Props, short for 'properties', are the means by which you pass data down from a parent to a child component — in other words, they're just like attributes on an element:

```html


	<Widget foo bar="static" baz={dynamic}/>


<script>
	import Widget from './Widget.html';

	export default {
		components: {
			Widget
		}
	};
</script>
```

```html

foo: {foo}
bar: {bar}
baz: {baz}
```

```json
/* { hidden: true } */
{
	dynamic: 'try changing this text'
}
```

As with element attributes, prop values can contain any valid JavaScript expression.

Often, the name of the property will be the same as the value, in which case we can use a shorthand:

```html


<Widget foo={foo}/>
<Widget {foo}/>
```

> Note that props are *one-way* — to get data from a child component into a parent component, use [bindings](guide#bindings).


### Composing with `<slot>`

A component can contain a `<slot></slot>` element, which allows the parent component to inject content:

```html


	<h2>Hello!</h2>
	This is a box. It can contain anything.


<script>
	import Box from './Box.html';

	export default {
		components: { Box }
	};
</script>
```

```html


	<slot></slot>


<style>
	.box {
		border: 2px solid black;
		padding: 0.5em;
	}
</style>
```

The `<slot>` element can contain 'fallback content', which will be used if no children are provided for the component:

```html



<script>
	import Box from './Box.html';

	export default {
		components: { Box }
	};
</script>
```

```html


	<slot>
		the box is empty!
	</slot>


<style>
	.box {
		border: 2px solid black;
		padding: 0.5em;
	}

	.fallback {
		color: #999;
	}
</style>
```

You can also have *named* slots. Any elements with a corresponding `slot` attribute will fill these slots:

```html

<ContactCard>
	P. Sherman
	42 Wallaby Way, Sydney
</ContactCard>

<script>
	import ContactCard from './ContactCard.html';

	export default {
		components: { ContactCard }
	};
</script>
```

```html


	<h2><slot name="name"></slot></h2>
	<slot name="address">Unknown address</slot>
	
	<slot name="email">Unknown email</slot>


<style>
	.contact-card {
		border: 2px solid black;
		padding: 0.5em;
	}
</style>
```


### Shorthand imports

As an alternative to using an `import` declaration...

```html

<script>
	import Widget from './Widget.html';

	export default {
		components: { Widget }
	};
</script>
```

...you can write this:

```html

<script>
	export default {
		components: {
			Widget: './Widget.html'
		}
	};
</script>
```

---

## File: content/guide/06-special-components.md

---
title: Special elements
---

Svelte includes a handful of built-in elements with special behaviour.


### `<svelte:self>`

Sometimes, a component needs to embed itself recursively — for example if you have a tree-like data structure. In Svelte, that's accomplished with the `<svelte:self>` tag:

```html

{#if countdown > 0}
	{countdown}
	<svelte:self countdown="{countdown - 1}"/>
{:else}
	liftoff!
{/if}
```

```json
/* { hidden: true } */
{
	countdown: 5
}
```


### `<svelte:component>`

If you don't know what kind of component to render until the app runs — in other words, it's driven by state (aka a dynamic component) — you can use `<svelte:component>`:

```html

 foo
<svelte:component this="{foo ? Red : Blue}" name="thing"/>

<script>
	import Red from './Red.html';
	import Blue from './Blue.html';

	export default {
		data() {
			return { Red, Blue }
		}
	};
</script>
```

```html

Red {name}
```

```html

Blue {name}
```

> Note that `Red` and `Blue` are items in `data`, *not* `components`, unlike if we were doing `<Red>` or ``.

The expression inside the `this="{...}"` can be any valid JavaScript expression. For example, it could be a [computed property](guide#computed-properties):

```html

<label> small</label>
<label> medium</label>
<label> large</label>

<svelte:component this={Size}/>

<script>
	import Small from './Small.html';
	import Medium from './Medium.html';
	import Large from './Large.html';

	export default {
		computed: {
			Size: ({size}) => {
				if (size === 'small') return Small;
				if (size === 'medium') return Medium;
				return Large;
			}
		}
	};
</script>
```

```html

small
```

```html

medium
```

```html

LARGE
```

```json
/* { hidden: true } */
{
	size: "medium"
}
```


### `<svelte:window>`

The `<svelte:window>` tag gives you a convenient way to declaratively add event listeners to `window`. Event listeners are automatically removed when the component is destroyed.

```html

<svelte:window on:keydown="set({ key: event.key, keyCode: event.keyCode })"/>

{#if key}
	<kbd>{key === ' ' ? 'Space' : key}</kbd> (code {keyCode})
{:else}
	click in this window and press any key
{/if}

<style>
	kbd {
		background-color: #eee;
		border: 2px solid #f4f4f4;
		border-right-color: #ddd;
		border-bottom-color: #ddd;
		font-size: 2em;
		margin: 0 0.5em 0 0;
		padding: 0.5em 0.8em;
		font-family: Inconsolata;
	}
</style>
```

You can also bind to certain values — so far `innerWidth`, `outerWidth`, `innerHeight`, `outerHeight`, `scrollX`, `scrollY` and `online`:

```html

<svelte:window bind:scrollY=y/>


user has scrolled {y} pixels

<style>
	.background {
		position: absolute;
		left: 0;
		top: 0;
		width: 100%;
		height: 9999px;
		background: linear-gradient(to bottom, #7db9e8 0%,#0a1d33 100%);
	}

	.fixed {
		position: fixed;
		top: 1em;
		left: 1em;
		color: white;
	}
</style>
```


### `<svelte:document>`

The `<svelte:document>` tag, just like `<svelte:window>`, gives you a convenient way to declaratively add event listeners to the `document` object. This is useful for listening to events that don't fire on `window`, such as `mouseenter` and `mouseleave`.


### `<svelte:head>`

If you're building an application with Svelte — particularly if you're using [Sapper](https://sapper-legacy.svelte.dev) — then it's likely you'll need to add some content to the `<head>` of your page, such as adding a `<title>` element.

You can do that with the `<svelte:head>` tag:

```html

<svelte:head>
	<title>{post.title} • My blog</title>
</svelte:head>
```

When [server rendering](guide#server-side-rendering), the `<head>` contents can be extracted separately to the rest of the markup.

---

## File: content/guide/07-element-directives.md

---
title: Directives
---

Directives are element or component-level instructions to Svelte. They look like attributes, except with a `:` character.

### Event handlers

In most applications, you'll need to respond to the user's actions. In Svelte, this is done with the `on:[event]` directive.

```html

Count: {count}
+1
```

```json
/* { hidden: true } */
{
	count: 0
}
```

When the user clicks the button, Svelte calls `component.set(...)` with the provided arguments. You can call any method belonging to the component (whether [built-in](guide#component-api) or [custom](guide#custom-methods)), and any data property (or computed property) that's in scope:

```html

Select a category:

{#each categories as category}
	select {category}
{/each}

<script>
	export default {
		data() {
			return {
				categories: [
					'animal',
					'vegetable',
					'mineral'
				]
			}
		},

		methods: {
			select(name) {
				alert(`selected ${name}`); // seriously, please don't do this
			}
		}
	};
</script>
```

You can also access the `event` object in the method call:

```html


	coords: {x},{y}


<style>
	div {
		border: 1px solid purple;
		width: 100%;
		height: 100%;
	}
</style>
```

The target node can be referenced as `this`, meaning you can do this sort of thing:

```html


```

### Event handler modifiers

While you can invoke methods like `event.stopPropagation` directly...

```html

...
```

...it gets annoying if you want to combine that with some other behaviour:

```html

...

<script>
	export default {
		methods: {
			setFoo(event) {
				event.stopPropagation();
				event.preventDefault();
				this.set({ foo: true });
			}
		}
	};
</script>
```

For that reason, Svelte lets you use *event modifiers*:

- [`preventDefault`](https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
- [`stopPropagation`](https://developer.mozilla.org/en-US/docs/Web/API/Event/stopPropagation)
- [`passive`](https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener#Parameters) — improves scrolling performance on touch/wheel events (Svelte will add it automatically where it's safe to do so)
- [`once`](https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener#Parameters) — removes the listener after the first invocation
- [`capture`](https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener#Parameter)

> `passive` and `once` are not implemented in `legacy` mode

The example above can be achieved with modifiers — no need for a custom method:

```html

...
```

### Custom events

You can define your own custom events to handle complex user interactions like dragging and swiping. See the earlier section on [custom event handlers](guide#custom-event-handlers) for more information.

### Component events

Events are an excellent way for [nested components](guide#nested-components) to communicate with their parents. Let's revisit our earlier example, but turn it into a `<CategoryChooser>` component:

```html

Select a category:

{#each categories as category}
	select {category}
{/each}

<script>
	export default {
		data() {
			return {
				categories: [
					'animal',
					'vegetable',
					'mineral'
				]
			}
		}
	};
</script>
```

When the user clicks a button, the component will fire a `select` event, where the `event` object has a `category` property. Any component that nests `<CategoryChooser>` can listen for events like so:

```html

<CategoryChooser on:select="playTwentyQuestions(event.category)"/>

<script>
	import CategoryChooser from './CategoryChooser.html';

	export default {
		components: {
			CategoryChooser
		},

		methods: {
			playTwentyQuestions(category) {
				alert(`ok! you chose ${category}`);
			}
		}
	};
</script>
```

```html

Select a category:

{#each categories as category}
	select {category}
{/each}

<script>
	export default {
		data() {
			return {
				categories: [
					'animal',
					'vegetable',
					'mineral'
				]
			}
		}
	};
</script>
```

Just as `this` in an element's event handler refers to the element itself, in a component event handler `this` refers to the component firing the event.

There is also a shorthand for listening for and re-firing an event unchanged.

```html


<Widget on:foo="fire('foo', event)"/>
<Widget on:foo/>
```

Since component events do not propagate as DOM events do, this can be used to pass events through intermediate components. This shorthand technique also applies to element events (`on:click` is equivalent to `on:click="fire('click', event)"`).

### Refs

Refs are a convenient way to store a reference to particular DOM nodes or components. Declare a ref with `ref:[name]`, and access it inside your component's methods with `this.refs.[name]`:

```html

<canvas ref:canvas width=200 height=200></canvas>

<script>
	import createRenderer from './createRenderer.js';

	export default {
		oncreate() {
			const canvas = this.refs.canvas;
			const ctx = canvas.getContext('2d');

			const renderer = createRenderer(canvas, ctx);
			this.on('destroy', renderer.stop);
		}
	}
</script>
```

```js
/* { filename: 'createRenderer.js', hidden: true } */
export default function createRenderer(canvas, ctx) {
	let running = true;
	loop();

	return {
		stop: () => {
			running = false;
		}
	};

	function loop() {
		if (!running) return;
		requestAnimationFrame(loop);

		const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);

		for (let p = 0; p < imageData.data.length; p += 4) {
			const i = p / 4;
			const x = i % canvas.width;
			const y = i / canvas.height >>> 0;

			const t = window.performance.now();

			const r = 64 + (128 * x / canvas.width) + (64 * Math.sin(t / 1000));
			const g = 64 + (128 * y / canvas.height) + (64 * Math.cos(t / 1000));
			const b = 128;

			imageData.data[p + 0] = r;
			imageData.data[p + 1] = g;
			imageData.data[p + 2] = b;
			imageData.data[p + 3] = 255;
		}

		ctx.putImageData(imageData, 0, 0);
	}
}
```

> Since only one element or component can occupy a given `ref`, don't use them in `{#each ...}` blocks. It's fine to use them in `{#if ...}` blocks however.

Note that you can use refs in your `<style>` blocks — see [Special selectors](guide#special-selectors).


### Transitions

Transitions allow elements to enter and leave the DOM gracefully, rather than suddenly appearing and disappearing.

```html

 visible

{#if visible}
	fades in and out
{/if}

<script>
	import { fade } from 'svelte-transitions';

	export default {
		transitions: { fade }
	};
</script>
```

Transitions can have parameters — typically `delay` and `duration`, but often others, depending on the transition in question. For example, here's the `fly` transition from the [svelte-transitions](https://github.com/sveltejs/svelte-transitions) package:

```html

 visible

{#if visible}
	flies 200 pixels up, slowly
{/if}

<script>
	import { fly } from 'svelte-transitions';

	export default {
		transitions: { fly }
	};
</script>
```

An element can have separate `in` and `out` transitions:

```html

 visible

{#if visible}
	flies up, fades out
{/if}

<script>
	import { fade, fly } from 'svelte-transitions';

	export default {
		transitions: { fade, fly }
	};
</script>
```

Transitions are simple functions that take a `node` and any provided `parameters` and return an object with the following properties:

* `duration` — how long the transition takes in milliseconds
* `delay` — milliseconds before the transition starts
* `easing` — an [easing function](https://github.com/rollup/eases-jsnext)
* `css` — a function that accepts an argument `t` between 0 and 1 and returns the styles that should be applied at that moment
* `tick` — a function that will be called on every frame, with the same `t` argument, while the transition is in progress

Of these, `duration` is required, as is *either* `css` or `tick`. The rest are optional. Here's how the `fade` transition is implemented, for example:

```html

 visible

{#if visible}
	fades in and out
{/if}

<script>
	export default {
		transitions: {
			fade(node, { delay = 0, duration = 400 }) {
				const o = +getComputedStyle(node).opacity;

				return {
					delay,
					duration,
					css: t => `opacity: ${t * o}`
				};
			}
		}
	};
</script>
```

> If the `css` option is used, Svelte will create a CSS animation that runs efficiently off the main thread. Therefore if you can achieve an effect using `css` rather than `tick`, you should.


### Bindings

As we've seen, data can be passed down to elements and components with attributes and [props](guide#props). Occasionally, you need to get data back up; for that we use bindings.


#### Component bindings

Component bindings keep values in sync between a parent and a child:

```html

<Widget bind:childValue=parentValue/>
```

Whenever `childValue` changes in the child component, `parentValue` will be updated in the parent component and vice versa.

If the names are the same, you can shorten the declaration:

```html

<Widget bind:value/>
```

> Use component bindings judiciously. They can save you a lot of boilerplate, but will make it harder to reason about data flow within your application if you overuse them.


#### Element bindings

Element bindings make it easy to respond to user interactions:

```html

<h1>Hello {name}!</h1>

```

```json
/* { hidden: true } */
{
	name: 'world'
}
```

Some bindings are *one-way*, meaning that the values are read-only. Most are *two-way* — changing the data programmatically will update the DOM. The following bindings are available:

| Name                                                            | Applies to                                   | Kind                 |
|-----------------------------------------------------------------|----------------------------------------------|----------------------|
| `value`                                                         | `` `<textarea>` `<select>`            | Two-way |
| `checked` `indeterminate`                                       | ``                      | Two-way |
| `group` (see note)                                              | `` `` | Two-way |
| `currentTime` `paused` `played` `volume`                        | `<audio>` `<video>`                          | Two-way |
| `buffered` `duration` `seekable`                                | `<audio>` `<video>`                          | One-way |
| `offsetWidth` `offsetHeight` `clientWidth` `clientHeight`       | All block-level elements                     | One-way |
| `scrollX` `scrollY`                                             | `<svelte:window>`                            | Two-way |
| `online` `innerWidth` `innerHeight` `outerWidth` `outerHeight`  | `<svelte:window>`                            | One-way |

> 'group' bindings allow you to capture the current value of a [set of radio inputs](repl?demo=binding-input-radio), or all the selected values of a [set of checkbox inputs](repl?demo=binding-input-checkbox-group).

Here is a complete example of using two way bindings with a form:

```html

<form on:submit="handleSubmit(event)">
	
	Say hello
</form>

<script>
	export default {
		methods: {
			handleSubmit(event) {
				// prevent the page from reloading
				event.preventDefault();

				const { name } = this.get();
				alert(`Hello ${name}!`);
			}
		}
	};
</script>
```

```json
/* { hidden: true } */
{
	name: "world"
}
```

> 'two way' bindings allow you to update a value in a nested property as seen in [checkbox input](repl?demo=binding-input-checkbox).

### Actions

Actions let you decorate elements with additional functionality. Actions are functions which may return an object with lifecycle methods, `update` and `destroy`. The action will be called when its element is added to the DOM.

Use actions for things like:
* tooltips
* lazy loading images as the page is scrolled, e.g. ``
* capturing link clicks for your client router
* adding drag and drop

```html


	{language}


<script>
	export default {
		actions: {
			tooltip(node, text) {
				const tooltip = document.createElement('div');
				tooltip.textContent = text;

				Object.assign(tooltip.style, {
					position: 'absolute',
					background: 'black',
					color: 'white',
					padding: '0.5em 1em',
					fontSize: '12px',
					pointerEvents: 'none',
					transform: 'translate(5px, -50%)',
					borderRadius: '2px',
					transition: 'opacity 0.4s'
				});

				function position() {
					const { top, right, bottom } = node.getBoundingClientRect();
					tooltip.style.top = `${(top + bottom) / 2}px`;
					tooltip.style.left = `${right}px`;
				}

				function append() {
					document.body.appendChild(tooltip);
					tooltip.style.opacity = 0;
					setTimeout(() => tooltip.style.opacity = 1);
					position();
				}

				function remove() {
					tooltip.remove();
				}

				node.addEventListener('mouseenter', append);
				node.addEventListener('mouseleave', remove);

				return {
					update(text) {
						tooltip.textContent = text;
						position();
					},

					destroy() {
						tooltip.remove();
						node.removeEventListener('mouseenter', append);
						node.removeEventListener('mouseleave', remove);
					}
				}
			}
		},

		methods: {
			toggleLanguage() {
				const { language } = this.get();

				this.set({
					language: language === 'english' ? 'latin' : 'english'
				});
			}
		}
	};
</script>
```

```json
/* { hidden: true } */
{
	language: "english",
	translations: {
		english: {
			tooltip: "Switch Languages",
		},
		latin: {
			tooltip: "Itchsway Anguageslay",
		},
	}
}
```

### Classes

Classes let you toggle element classes on and off. To use classes add the directive `class` followed by a colon and the class name you want toggled (`class:the-class-name="anExpression"`). The expression inside the directive's quotes will be evaluated and toggle the class on and off depending on the truthiness of the expression's result. You can only add class directives to elements.

This example adds the class `active` to `<li>` elements when the `url` property matches the path their links target.

```html


	<li class:active="url === '/'">[Home](/)</li>
	<li class:active="url.startsWith('/blog')">[Blog](/blog/)</li>
	<li class:active="url.startsWith('/about')">[About](/about/)</li>


<script>
	export default {
		methods: {
			goto(event) {
				event.preventDefault();
				this.set({ url: event.target.pathname });
			}
		}
	}
</script>

<style>
	.links {
		list-style: none;
	}
	.links li {
		float: left;
		padding: 10px;
	}
	/* classes added this way are processed with encapsulated styles, no need for :global() */
	.active {
		background: #eee;
	}
</style>
```

```json
/* { hidden: true } */
{
	"url": "/"
}
```

Classes will work with an existing class attribute on your element. If you find yourself adding multiple ternary statements inside a class attribute, classes can simplify your component. Classes are recognized by the compiler and [scoped correctly](guide#scoped-styles).

If your class name is the same as a property in your component's state, you can use the shorthand of a class binding which drops the expression (`class:myProp`).

Note that class names with dashes in them do not usually make good shorthand classes since the property will also need a dash in it. The example below uses a computed property to make working with this easier, but it may be easier to not use the shorthand in cases like this.

```html


	Active? {active}
	Selected? {isSelected}

Toggle Active
Toggle Selected
Toggle Admin

<script>
export default {
	computed: {
		// Because shorthand reflects the var name, you must use component.set({ "is-selected": true }) or use a computed
		// property like this. It might be better to avoid shorthand for class names which are not valid variable names.
		"is-selected": ({ isSelected }) => isSelected
	}
}
</script>

<style>
	div {
		width: 300px;
		border: 1px solid #ccc;
		background: #eee;
		margin-bottom: 10px;
	}
	.active {
		background: #fff;
	}
	.is-selected {
		border-color: #99bbff;
		box-shadow: 0 0 6px #99bbff;
	}
	.isAdmin {
		outline: 2px solid red;
	}
</style>
```

```json
/* { hidden: true } */
{
	"active": true,
	"isSelected": false,
	"isAdmin": false,
}
```

---

## File: content/guide/08-plugins.md

---
title: Plugins
---

Svelte can be extended with plugins and extra methods.

### Transition plugins

The [svelte-transitions](https://github.com/sveltejs/svelte-transitions) package includes a selection of officially supported transition plugins, such as [fade](https://github.com/sveltejs/svelte-transitions-fade), [fly](https://github.com/sveltejs/svelte-transitions-fly) and [slide](https://github.com/sveltejs/svelte-transitions-slide). You can include them in a component like so:

```html

<label>
	 visible
</label>

{#if visible}
	
	hello!
{/if}

<script>
	import { fly } from 'svelte-transitions';

	export default {
		transitions: { fly }
	};
</script>
```

```json
/* { hidden: true } */
{
	visible: true
}
```


### Extra methods

The [svelte-extras](https://github.com/sveltejs/svelte-extras) package includes a handful of methods for tweening (animating), manipulating arrays and so on.

```html


add todo


	{#each todos as todo, i}
		<li>
			x
			{todo}
		</li>
	{/each}


<style>
	ul {
		list-style: none;
		padding: 0;
	}

	li button {
		color: rgb(200,0,0);
		background: rgba(200,0,0,0.1);
		border-color: rgba(200,0,0,0.2);
		padding: 0.2em 0.5em;
	}
</style>

<script>
	import { push, splice } from 'svelte-extras';

	export default {
		data() {
			return {
				newTodo: '',
				todos: []
			};
		},

		methods: {
			push,
			splice
		}
	};
</script>
```

```json
/* { hidden: true } */
{
	todos: [
		"wash the car",
		"take the dog for a walk",
		"mow the lawn"
	]
}
```