Bring svelte.technology source into main repo

pull/1900/head
Rich Harris 6 years ago committed by GitHub
parent 0770b54519
commit 29052aba7d
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

@ -1,46 +1,45 @@
{ {
"root": true, "root": true,
"rules": { "rules": {
"indent": [ 2, "tab", { "SwitchCase": 1 } ], "indent": [2, "tab", { "SwitchCase": 1 }],
"semi": [ 2, "always" ], "semi": [2, "always"],
"keyword-spacing": [ 2, { "before": true, "after": true } ], "keyword-spacing": [2, { "before": true, "after": true }],
"space-before-blocks": [ 2, "always" ], "space-before-blocks": [2, "always"],
"no-mixed-spaces-and-tabs": [ 2, "smart-tabs" ], "no-mixed-spaces-and-tabs": [2, "smart-tabs"],
"no-cond-assign": 0, "no-cond-assign": 0,
"no-unused-vars": 2, "no-unused-vars": 2,
"object-shorthand": [ 2, "always" ], "object-shorthand": [2, "always"],
"no-const-assign": 2, "no-const-assign": 2,
"no-class-assign": 2, "no-class-assign": 2,
"no-this-before-super": 2, "no-this-before-super": 2,
"no-var": 2, "no-var": 2,
"no-unreachable": 2, "no-unreachable": 2,
"valid-typeof": 2, "valid-typeof": 2,
"quote-props": [ 2, "as-needed" ], "quote-props": [2, "as-needed"],
"one-var": [ 2, "never" ], "one-var": [2, "never"],
"prefer-arrow-callback": 2, "prefer-arrow-callback": 2,
"prefer-const": [ 2, { "destructuring": "all" } ], "prefer-const": [2, { "destructuring": "all" }],
"arrow-spacing": 2, "arrow-spacing": 2,
"no-inner-declarations": 0 "no-inner-declarations": 0
}, },
"env": { "env": {
"es6": true, "es6": true,
"browser": true, "browser": true,
"node": true, "node": true,
"mocha": true "mocha": true
}, },
"extends": [ "extends": [
"eslint:recommended", "eslint:recommended",
"plugin:import/errors", "plugin:import/errors",
"plugin:import/warnings" "plugin:import/warnings"
], ],
"plugins": [ "plugins": ["svelte3"],
"html" "parserOptions": {
], "ecmaVersion": 6,
"parserOptions": { "sourceType": "module"
"ecmaVersion": 6, },
"sourceType": "module" "settings": {
}, "import/core-modules": ["svelte"],
"settings": { "svelte3/extensions": ["html"]
"import/core-modules": [ "svelte" ] }
}
} }

6
.gitignore vendored

@ -17,4 +17,8 @@ node_modules
/test/sourcemaps/samples/*/output.css.map /test/sourcemaps/samples/*/output.css.map
/yarn-error.log /yarn-error.log
_actual*.* _actual*.*
_*/
/site/cypress/screenshots/
/site/__sapper__/
/site/.env
/site/.sessions

@ -1,6 +1,6 @@
{ {
"name": "svelte", "name": "svelte",
"version": "3.0.0-alpha6", "version": "3.0.0-alpha8",
"description": "The magical disappearing UI framework", "description": "The magical disappearing UI framework",
"module": "index.mjs", "module": "index.mjs",
"main": "index.js", "main": "index.js",

@ -0,0 +1,45 @@
{
"root": true,
"rules": {
"indent": [2, "tab", { "SwitchCase": 1 }],
"semi": [2, "always"],
"keyword-spacing": [2, { "before": true, "after": true }],
"space-before-blocks": [2, "always"],
"no-mixed-spaces-and-tabs": [2, "smart-tabs"],
"no-cond-assign": 0,
"no-unused-vars": 2,
"object-shorthand": [2, "always"],
"no-const-assign": 2,
"no-class-assign": 2,
"no-this-before-super": 2,
"no-var": 2,
"no-unreachable": 2,
"valid-typeof": 2,
"quote-props": [2, "as-needed"],
"one-var": [2, "never"],
"prefer-arrow-callback": 2,
"prefer-const": [2, { "destructuring": "all" }],
"arrow-spacing": 2,
"no-inner-declarations": 0
},
"env": {
"es6": true,
"browser": true,
"node": true,
"mocha": true
},
"extends": [
"eslint:recommended",
"plugin:import/errors",
"plugin:import/warnings"
],
"plugins": ["svelte3"],
"parserOptions": {
"ecmaVersion": 6,
"sourceType": "module"
},
"settings": {
"import/core-modules": ["svelte"],
"svelte3/extensions": [".html"]
}
}

@ -0,0 +1,11 @@
sudo: false
language: node_js
node_js:
- "stable"
env:
global:
- BUILD_TIMEOUT=10000
install:
- npm install
- npm install cypress

@ -0,0 +1,75 @@
# sapper-template-rollup
A version of the default [Sapper](https://github.com/sveltejs/sapper) template that uses Rollup instead of webpack. To clone it and get started:
```bash
npx degit sveltejs/sapper-template#rollup my-app
cd my-app
npm install # or yarn!
npm run dev
```
Open up [localhost:3000](http://localhost:3000) and start clicking around.
Consult [sapper.svelte.technology](https://sapper.svelte.technology) for help getting started.
*[Click here for the webpack version of this template](https://github.com/sveltejs/sapper-template)*
## Structure
Sapper expects to find three directories in the root of your project — `app`, `assets` and `routes`.
### app
The [app](app) directory contains the entry points for your app — `client.js`, `server.js` and (optionally) a `service-worker.js` — along with a `template.html` file.
### assets
The [assets](assets) directory contains any static assets that should be available. These are served using [sirv](https://github.com/lukeed/sirv).
In your [service-worker.js](app/service-worker.js) file, you can import these as `assets` from the generated manifest...
```js
import { assets } from './manifest/service-worker.js';
```
...so that you can cache them (though you can choose not to, for example if you don't want to cache very large files).
### routes
This is the heart of your Sapper app. There are two kinds of routes — *pages*, and *server routes*.
**Pages** are Svelte components written in `.html` files. When a user first visits the application, they will be served a server-rendered version of the route in question, plus some JavaScript that 'hydrates' the page and initialises a client-side router. From that point forward, navigating to other pages is handled entirely on the client for a fast, app-like feel. (Sapper will preload and cache the code for these subsequent pages, so that navigation is instantaneous.)
**Server routes** are modules written in `.js` files, that export functions corresponding to HTTP methods. Each function receives Express `request` and `response` objects as arguments, plus a `next` function. This is useful for creating a JSON API, for example.
There are three simple rules for naming the files that define your routes:
* A file called `routes/about.html` corresponds to the `/about` route. A file called `routes/blog/[slug].html` corresponds to the `/blog/:slug` route, in which case `params.slug` is available to the route
* The file `routes/index.html` (or `routes/index.js`) corresponds to the root of your app. `routes/about/index.html` is treated the same as `routes/about.html`.
* Files and directories with a leading underscore do *not* create routes. This allows you to colocate helper modules and components with the routes that depend on them — for example you could have a file called `routes/_helpers/datetime.js` and it would *not* create a `/_helpers/datetime` route
## Rollup config
Sapper uses Rollup to provide code-splitting and dynamic imports, as well as compiling your Svelte components. As long as you don't do anything daft, you can edit the configuration files to add whatever plugins you'd like.
## Production mode and deployment
To start a production version of your app, run `npm run build && npm start`.
You can deploy your application to any environment that supports Node 8 or above. As an example, to deploy to [Now](https://zeit.co/now), run these commands:
```bash
npm install -g now
now
```
## Bugs and feedback
Sapper is in early development, and may have the odd rough edge here and there. Please be vocal over on the [Sapper issue tracker](https://github.com/sveltejs/sapper/issues).

@ -0,0 +1,18 @@
version: "{build}"
shallow_clone: true
init:
- git config --global core.autocrlf false
build: off
environment:
matrix:
# node.js
- nodejs_version: stable
install:
- ps: Install-Product node $env:nodejs_version
- npm install cypress
- npm install

@ -0,0 +1,56 @@
---
title: Frameworks without the framework: why didn't we think of this sooner?
description: You can't write serious applications in vanilla JavaScript without hitting a complexity wall. But a compiler can do it for you.
pubdate: 2016-11-26
author: Rich Harris
authorURL: https://twitter.com/Rich_Harris
---
> Wait, this new framework has a *runtime*? Ugh. Thanks, I'll pass.
> ** front end developers in 2018**
We're shipping too much code to our users. Like a lot of front end developers, I've been in denial about that fact, thinking that it was fine to serve 100kb of JavaScript on page load just use [one less .jpg!](https://twitter.com/miketaylr/status/227056824275333120) and that what *really* mattered was performance once your app was already interactive.
But I was wrong. 100kb of .js isn't equivalent to 100kb of .jpg. It's not just the network time that'll kill your app's startup performance, but the time spent parsing and evaluating your script, during which time the browser becomes completely unresponsive. On mobile, those milliseconds rack up very quickly.
If you're not convinced that this is a problem, follow [Alex Russell](https://twitter.com/slightlylate) on Twitter. Alex [hasn't been making many friends in the framework community lately](https://twitter.com/slightlylate/status/728355959022587905), but he's not wrong. But the proposed alternative to using frameworks like Angular, React and Ember [Polymer](https://www.polymer-project.org/1.0/) hasn't yet gained traction in the front end world, and it's certainly not for a lack of marketing.
Perhaps we need to rethink the whole thing.
## What problem do frameworks *really* solve?
The common view is that frameworks make it easier to manage the complexity of your code: the framework abstracts away all the fussy implementation details with techniques like virtual DOM diffing. But that's not really true. At best, frameworks *move the complexity around*, away from code that you had to write and into code you didn't.
Instead, the reason that ideas like React are so wildly and deservedly successful is that they make it easier to manage the complexity of your *concepts*. Frameworks are primarily a tool for structuring your thoughts, not your code.
Given that, what if the framework *didn't actually run in the browser*? What if, instead, it converted your application into pure vanilla JavaScript, just like Babel converts ES2016+ to ES5? You'd pay no upfront cost of shipping a hefty runtime, and your app would get seriously fast, because there'd be no layers of abstraction between your app and the browser.
## Introducing Svelte
Svelte is a new framework that does exactly that. You write your components using HTML, CSS and JavaScript (plus a few extra bits you can [learn in under 5 minutes](/guide)), and during your build process Svelte compiles them into tiny standalone JavaScript modules. By statically analysing the component template, we can make sure that the browser does as little work as possible.
The [Svelte implementation of TodoMVC](http://svelte-todomvc.surge.sh/) weighs 3.6kb zipped. For comparison, React plus ReactDOM *without any app code* weighs about 45kb zipped. It takes about 10x as long for the browser just to evaluate React as it does for Svelte to be up and running with an interactive TodoMVC.
And once your app *is* up and running, according to [js-framework-benchmark](https://github.com/krausest/js-framework-benchmark) **Svelte is fast as heck**. It's faster than React. It's faster than Vue. It's faster than Angular, or Ember, or Ractive, or Preact, or Riot, or Mithril. It's competitive with Inferno, which is probably the fastest UI framework in the world, for now, because [Dominic Gannaway](https://twitter.com/trueadm) is a wizard. (Svelte is slower at removing elements. We're [working on it](https://github.com/sveltejs/svelte/issues/26).)
It's basically as fast as vanilla JS, which makes sense because it *is* vanilla JS  just vanilla JS that you didn't have to write.
## But that's not the important thing
Well, it *is* important performance matters a great deal. What's really exciting about this approach, though, is that we can finally solve some of the thorniest problems in web development.
Consider interoperability. Want to `npm install cool-calendar-widget` and use it in your app? Previously, you could only do that if you were already using (a correct version of) the framework that the widget was designed for if `cool-calendar-widget` was built in React and you're using Angular then, well, hard cheese. But if the widget author used Svelte, apps that use it can be built using whatever technology you like. (On the TODO list: a way to convert Svelte components into web components.)
Or [code splitting](https://twitter.com/samccone/status/797528710085652480). It's a great idea (only load the code the user needs for the initial view, then get the rest later), but there's a problem even if you only initially serve one React component instead of 100, *you still have to serve React itself*. With Svelte, code splitting can be much more effective, because the framework is embedded in the component, and the component is tiny.
Finally, something I've wrestled with a great deal as an open source maintainer: your users always want *their* features prioritised, and underestimate the cost of those features to people who don't need them. A framework author must always balance the long-term health of the project with the desire to meet their users' needs. That's incredibly difficult, because it's hard to anticipate much less articulate the consequences of incremental bloat, and it takes serious soft skills to tell people (who may have been enthusiastically evangelising your tool up to that point) that their feature isn't important enough. But with an approach like Svelte's, many features can be added with absolutely no cost to people who don't use them, because the code that implements those features just doesn't get generated by the compiler if it's unnecessary.
## We're just getting started
Svelte is very new. There's a lot of work still left to do creating build tool integrations, adding a server-side renderer, hot reloading, transitions, more documentation and examples, starter kits, and so on.
But you can already build rich components with it, which is why we've gone straight to a stable 1.0.0 release. [Read the guide](/guide), [try it out in the REPL](/repl), and head over to [GitHub](https://github.com/sveltejs/svelte) to help kickstart the next era of front end development.

@ -0,0 +1,66 @@
---
title: The easiest way to get started with Svelte
description: This'll only take a minute.
pubdate: 2017-08-07
author: Rich Harris
authorURL: https://twitter.com/Rich_Harris
---
Svelte is a [new kind of framework](/blog/frameworks-without-the-framework). Rather than putting a `<script src='svelte.js'>` tag on the page, or bringing it into your app with `import` or `require`, Svelte is a compiler that works behind the scenes to turn your component files into beautifully optimised JavaScript.
Because of that, getting started with it can be a little bit confusing at first. How, you might reasonably ask, do you make a Svelte app?
## 1. Use the REPL
The [Svelte REPL](https://svelte.technology/repl) is the easiest way to begin. You can choose from a list of examples to get you started, and tweak them until they do what you want.
<aside>You'll need to have [Node.js](https://nodejs.org/) installed, and know how to use the terminal</aside>
At some point, your app will outgrow the REPL. Click the **download** button to save a `svelte-app.zip` file to your computer and uncompress it.
Open a terminal window and set the project up...
```bash
cd /path/to/svelte-app
npm install
```
...then start up a development server:
```bash
npm run dev
```
This will serve your app on [localhost:5000](http://localhost:5000) and rebuild it with [Rollup](https://rollupjs.org) every time you make a change to the files in `svelte-app/src`.
## 2. Use degit
When you download from the REPL, you're getting a customised version of the [sveltejs/template](https://github.com/sveltejs/template) repo. You can skip messing around with zip files by using [degit](https://github.com/Rich-Harris/degit), a project scaffolding tool.
In the terminal, install degit globally (you only need to do this once):
```bash
npm install -g degit
```
After that, you can instantly create a new project like so:
```bash
degit sveltejs/template my-new-project
cd my-new-project
npm install
npm run dev
```
Once you've tinkered a bit and understood how everything fits together, you can fork [sveltejs/template](https://github.com/sveltejs/template) and start doing this instead:
```bash
degit your-name/template my-new-project
```
And that's it! Do `npm run build` to create a production-ready version of your app, and check the project template's [README](https://github.com/sveltejs/template/blob/master/README.md) for instructions on how to easily deploy your app to the web with [Now](https://zeit.co/now) or [Surge](http://surge.sh/).
You're not restricted to using Rollup — there are also integrations for [webpack](https://github.com/sveltejs/svelte-loader), [Browserify](https://github.com/tehshrike/sveltify) and others, or you can use the [Svelte CLI](https://github.com/sveltejs/svelte-cli) or the [API](https://github.com/sveltejs/svelte#api) directly. If you make a project template using one of these tools, please share it with the [Svelte Gitter chatroom](https://gitter.im/sveltejs/svelte), or via [@sveltejs](https://twitter.com/sveltejs) on Twitter!

@ -0,0 +1,77 @@
---
title: The zen of Just Writing CSS
description: I would say this is the future, but we're already doing it.
pubdate: 2017-09-06
author: Rich Harris
authorURL: https://twitter.com/Rich_Harris
---
It's fashionable to dislike CSS. There are lots of reasons why that's the case, but it boils down to this: CSS is *unpredictable*. If you've never had the experience of tweaking a style rule and accidentally breaking some layout that you thought was completely unrelated — usually when you're trying to ship — then you're either new at this or you're a much better programmer than the rest of us.
So the JavaScript community rolled up its sleeves and got to work. Over the last couple of years, there's been a Cambrian explosion of libraries aimed at making CSS behave, collectively referred to as *CSS-in-JS*.
What you might not realise is that **the biggest problems with CSS can be solved without CSS-in-JS**. Without those problems, writing CSS isn't just tolerable — it's enjoyable. And you don't have to find solutions to the additional problems that CSS-in-JS introduces.
This article isn't in any way intended as criticism of the hard work the CSS-in-JS community has done. It's one of the most active corners of the JS ecosystem, and new ideas are springing up every week. Instead, my purpose is to illustrate why an alternative approach — based on Single File Components with real CSS — is so damn delightful.
## The biggest problem with CSS
Everything in CSS is global. Because of that, styles intended for one bit of markup often end up affecting another. Because of *that*, developers often resort to wild namespacing conventions (not 'rules', since they're very difficult to enforce) that mostly just increase your risk of RSI.
It gets worse when you're working on a team. No-one dares touch styles authored by someone else, because it's often unclear what they're doing, what markup they apply to, and what disasters will unfold if you remove them.
The consequence of all this is the **append-only stylesheet**. There's no way of knowing which code can safely be removed, so it's common to undo some existing style with another, more specific style — even on relatively small projects.
## Single File Components change all that
The idea behind SFCs is simple: you write your components in an HTML file that (optionally) contains a `<style>` and `<script>` attribute describing the component's styles and behaviour. Svelte, Ractive, Vue and Polymer all follow this basic pattern.
<aside>[Read the introductory blog post](https://svelte.technology/blog/frameworks-without-the-framework) if you're new to Svelte. Or [read](https://twitter.com/padolsey/status/899717303234908160) [the](https://twitter.com/sveltejs/status/901818357644701696) [testimonials](https://twitter.com/sveltejs/status/901818106309476352).</aside>
(For the rest of this article we'll be using Svelte, obviously. But if the idea of using a template language makes you shudder — your fears are misplaced, but that's a topic for another day — then just use Vue which lets you use JSX in your SFCs.)
Several wonderful things happen as a result:
* Your styles are *scoped to the component*. No more leakage, no more unpredictable cascade. And no more sesquipedalian classnames designed to prevent conflicts.
* You don't need to go spelunking through your folder structure to find the rules that are breaking your stuff.
* The compiler (in Svelte's case) can **identify and remove unused styles**. No more append-only stylesheets!
Let's see what that looks like in practice.
<figure>
<video controls poster='https://svelte-technology-assets.surge.sh/just-write-css.jpg'>
<source type='video/mp4' src='https://svelte-technology-assets.surge.sh/just-write-css.mp4'>
</video>
<figcaption>
Is this what they mean by 'use the platform'?
</figcaption>
</figure>
Every code editor already knows about CSS, so there's a good chance that you'll get autocomplete, linting, syntax highlighting and so on — all without additional JS-fatigue-inducing tools.
And because it's real CSS, rather than some camelCased quotes-everywhere impostor, we can take advantage of the 'tweak in devtools, paste back into our source code' workflow, which I personally couldn't live without. Notice that we get CSS sourcemaps out of the box, so you can instantly pinpoint the lines in question. It's hard to overstate the importance of this: when you're in WYSIWYG mode, you're not thinking in terms of your component tree, so having a robust way to figure out *where these damn styles came from* is essential. Doubly so if someone else originally wrote the component. (I promise you, this is the single biggest productivity boost to your CSS workflow. If you're writing styles without sourcemaps, you are almost certainly wasting a lot of time. I know I was.)
Svelte transforms your selectors (using an attribute that's also applied to affected elements, though the exact mechanism is unimportant and subject to change) to achieve the scoping. It warns on and removes any unused rules, then it minifies the result and lets you write it out to a `.css` file. There's also an experimental new option to compile to web components, using shadow DOM to encapsulate the styles, if that's your jam.
This is all possible because your CSS is parsed (with [css-tree](https://github.com/csstree/csstree)) and statically analysed in the context of your markup. Static analysis opens the doors to all kinds of exciting future possibilities — smarter optimisations, a11y hints — that are much harder if your styles are computed dynamically at runtime. We're just getting started.
## But we can add tools to do [x]!
If your reaction to the video was 'fine, but if we use TypeScript and write plugins for each editor then we can get all the autocomplete and syntax highlighting stuff' — in other words, if you believe that in order to achieve parity with CSS it makes sense to build, document, promote and maintain a fleet of ancillary projects — then, well, you and I may never see eye to eye!
## We don't have all the answers — yet
Having said all that, CSS-in-JS does point to answers to some lingering questions:
* How can we install styles from npm?
* How can we reuse constants that are defined in a single place?
* How can we compose declarations?
Personally, I haven't found these issues to outweigh the benefits of the approach outlined above. You may well have a different set of priorities, and they may be reason enough for you to abandon CSS.
But at the end of the day, you have to know CSS anyway. Love it or loathe it, you must at least *learn* it. As custodians of the web, we have a choice: create abstractions that steepen the web dev learning curve yet further, or work together to fix the bad parts of CSS. I know which I choose.

@ -0,0 +1,85 @@
---
title: Sapper: Towards the ideal web app framework
description: Taking the next-plus-one step
pubdate: 2017-12-31
author: Rich Harris
authorURL: https://twitter.com/Rich_Harris
---
> Quickstart for the impatient: [the Sapper docs](https://sapper.svelte.technology), and the [starter template](https://github.com/sveltejs/sapper-template)
If you had to list the characteristics of the perfect Node.js web application framework, you'd probably come up with something like this:
1. It should do server-side rendering, for fast initial loads and no caveats around SEO
2. As a corollary, your app's codebase should be universal — write once for server *and* client
3. The client-side app should *hydrate* the server-rendered HTML, attaching event listeners (and so on) to existing elements rather than re-rendering them
4. Navigating to subsequent pages should be instantaneous
5. Offline, and other Progressive Web App characteristics, must be supported out of the box
6. Only the JavaScript and CSS required for the first page should load initially. That means the framework should do automatic code-splitting at the route level, and support dynamic `import(...)` for more granular manual control
7. No compromise on performance
8. First-rate developer experience, with hot module reloading and all the trimmings
9. The resulting codebase should be easy to grok and maintain
10. It should be possible to understand and customise every aspect of the system — no webpack configs locked up in the framework, and as little hidden 'plumbing' as possible
11. Learning the entire framework in under an hour should be easy, and not just for experienced developers
[Next.js](https://github.com/zeit/next.js) is close to this ideal. If you haven't encountered it yet, I strongly recommend going through the tutorials at [learnnextjs.com](https://learnnextjs.com). Next introduced a brilliant idea: all the pages of your app are files in a `your-project/pages` directory, and each of those files is just a React component.
Everything else flows from that breakthrough design decision. Finding the code responsible for a given page is easy, because you can just look at the filesystem rather than playing 'guess the component name'. Project structure bikeshedding is a thing of the past. And the combination of SSR (server-side rendering) and code-splitting — something the React Router team [gave up on](https://reacttraining.com/react-router/web/guides/code-splitting), declaring 'Godspeed those who attempt the server-rendered, code-split apps' — is trivial.
But it's not perfect. As churlish as it might be to list the flaws in something *so, so good*, there are some:
* Next uses something called 'route masking' to create nice URLs (e.g. `/blog/hello-world` instead of `/post?slug=hello-world`). This undermines the guarantee about directory structure corresponding to app structure, and forces you to maintain configuration that translates between the two forms
* All your routes are assumed to be universal 'pages'. But it's very common to need routes that only render on the server, such as a 301 redirect or an [API endpoint](/api/blog/sapper-towards-the-ideal-web-app-framework) that serves the data for your pages, and Next doesn't have a great solution for this. You can add logic to your `server.js` file to handle these cases, but it feels at odds with the declarative approach taken for pages
* To use the client-side router, links can't be standard `<a>` tags. Instead, you have to use framework-specific `<Link>` components, which is impossible in the markdown content for a blog post such as this one, for example
The real problem, though, is that all that goodness comes for a price. The simplest possible Next app — a single 'hello world' page that renders some static text — involves 66kb of gzipped JavaScript. Unzipped, it's 204kb, which is a non-trivial amount of code for a mobile device to parse at a time when performance is a critical factor determining whether or not your users will stick around. And that's the *baseline*.
We can do better!
## The compiler-as-framework paradigm shift
[Svelte introduced a radical idea](https://svelte.technology/blog/frameworks-without-the-framework): what if your UI framework wasn't a framework at all, but a compiler that turned your components into standalone JavaScript modules? Instead of using a library like React or Vue, which knows nothing about your app and must therefore be a one-size-fits-all solution, we can ship highly-optimised vanilla JavaScript. Just the code your app needs, and without the memory and performance overhead of solutions based on a virtual DOM.
The JavaScript world is [moving towards this model](https://tomdale.net/2017/09/compilers-are-the-new-frameworks/). [Stencil](https://stenciljs.com), a Svelte-inspired framework from the Ionic team, compiles to web components. [Glimmer](https://glimmerjs.com) *doesn't* compile to standalone JavaScript (the pros and cons of which deserve a separate blog post), but the team is doing some fascinating research around compiling templates to bytecode. (React is [getting in on the action](https://twitter.com/trueadm/status/944908776896978946), though their current research focuses on optimising your JSX app code, which is arguably more similar to the ahead-of-time optimisations that Angular, Ractive and Vue have been doing for a few years.)
What happens if we use the new model as a starting point?
## Introducing Sapper
<aside>The [name comes from](https://sapper.svelte.technology/guide#why-the-name-) the term for combat engineers, and is also short for <strong>S</strong>velte <strong>app</strong> mak<strong>er</strong></aside>
[Sapper](https://sapper.svelte.technology) is the answer to that question. **Sapper is a Next.js-style framework that aims to meet the eleven criteria at the top of this article while dramatically reducing the amount of code that gets sent to the browser.** It's implemented as Express-compatible middleware, meaning it's easy to understand and customise.
The same 'hello world' app that took 204kb with React and Next weighs just 7kb with Sapper. That number is likely to fall further in the future as we explore the space of optimisation possibilities, such as not shipping any JavaScript *at all* for pages that aren't interactive, beyond the tiny Sapper runtime that handles client-side routing.
What about a more 'real world' example? Conveniently, the [RealWorld](https://github.com/gothinkster/realworld) project, which challenges frameworks to develop an implementation of a Medium clone, gives us a way to find out. The [Sapper implementation](http://svelte-realworld.now.sh/) takes 39.6kb (11.8kb zipped) to render an interactive homepage.
<aside>Code-splitting isn't free — if the reference implementation used code-splitting, it would be larger still</aside>
The entire app costs 132.7kb (39.9kb zipped), which is significantly smaller than the reference React/Redux implementation at 327kb (85.7kb), but even if was as large it would *feel* faster because of code-splitting. And that's a crucial point. We're told we need to code-split our apps, but if your app uses a traditional framework like React or Vue then there's a hard lower bound on the size of your initial code-split chunk — the framework itself, which is likely to be a significant portion of your total app size. With the Svelte approach, that's no longer the case.
But size is only part of the story. Svelte apps are also extremely performant and memory-efficient, and the framework includes powerful features that you would sacrifice if you chose a 'minimal' or 'simple' UI library.
## Trade-offs
The biggest drawback for many developers evaluating Sapper would be 'but I like React, and I already know how to use it', which is fair.
If you're in that camp, I'd invite you to at least try alternative frameworks. You might be pleasantly surprised! The [Sapper RealWorld](https://github.com/sveltejs/realworld) implementation totals 1,201 lines of source code, compared to 2,377 for the reference implementation, because you're able to express concepts very concisely using Svelte's template syntax (which [takes all of five minutes to master](https://svelte.technology/guide#template-syntax)). You get [scoped CSS](the-zen-of-just-writing-css), with unused style removal and minification built-in, and you can use preprocessors like LESS if you want. You no longer need to use Babel. SSR is ridiculously fast, because it's just string concatenation. And we recently introduced [svelte/store](https://svelte.technology/guide#state-management), a tiny global store that synchronises state across your component hierarchy with zero boilerplate. The worst that can happen is that you'll end up feeling vindicated!
But there are trade-offs nonetheless. Some people have a pathological aversion to any form of 'template language', and maybe that applies to you. JSX proponents will clobber you with the 'it's just JavaScript' mantra, and therein lies React's greatest strength, which is that it is infinitely flexible. That flexibility comes with its own set of trade-offs, but we're not here to discuss those.
And then there's *ecosystem*. The universe around React in particular — the devtools, editor integrations, ancillary libraries, tutorials, StackOverflow answers, hell, even job opportunities — is unrivalled. While it's true that citing 'ecosystem' as the main reason to choose a tool is a sign that you're stuck on a local maximum, apt to be marooned by the rising waters of progress, it's still a major point in favour of incumbents.
## Roadmap
We're not at version 1.0.0 yet, and a few things may change before we get there. Once we do (soon!), there are a lot of exciting possibilities.
I believe the next frontier of web performance is 'whole-app optimisation'. Currently, Svelte's compiler operates at the component level, but a compiler that understood the boundaries *between* those components could generate even more efficient code. The React team's [Prepack research](https://twitter.com/trueadm/status/944908776896978946) is predicated on a similar idea, and the Glimmer team is doing some interesting work in this space. Svelte and Sapper are well positioned to take advantage of these ideas.
Speaking of Glimmer, the idea of compiling components to bytecode is one that we'll probably steal in 2018. A framework like Sapper could conceivably determine which compilation mode to use based on the characteristics of your app. It could even serve JavaScript for the initial route for the fastest possible startup time, then lazily serve a bytecode interpreter for subsequent routes, resulting in the optimal combination of startup size and total app size.
Mostly, though, we want the direction of Sapper to be determined by its users. If you're the kind of developer who enjoys life on the bleeding edge and would like to help shape the future of how we build web apps, please join us on [GitHub](https://github.com/sveltejs/svelte) and [Gitter](https://gitter.im/sveltejs/svelte).

@ -0,0 +1,218 @@
---
title: Svelte v2 is out!
description: Here's what you need to know
pubdate: 2018-04-18
author: Rich Harris
authorURL: https://twitter.com/Rich_Harris
---
<aside>Our motto is 'move slowly and break things'. No, wait, that came out wrong...</aside>
Almost a year after we first started talking about version 2 on the Svelte issue tracker, it's finally time to make some breaking changes. This blog post will explain what changed, why it changed, and what you need to do to bring your apps up to date.
## tl;dr
Each of these items is described in more depth below. If you get stuck, ask for help in our friendly [Gitter chatroom](https://gitter.im/sveltejs/svelte).
<style>
ul {
position: relative;
list-style: none;
}
li input {
position: absolute;
left: -2.5em;
top: 0.3em;
}
</style>
- <input type=checkbox> Install Svelte v2 from npm
- <input type=checkbox> Upgrade your templates with [svelte-upgrade](https://github.com/sveltejs/svelte-upgrade)
- <input type=checkbox> Remove calls to `component.observe`, or add the `observe` method from [svelte-extras](https://github.com/sveltejs/svelte-extras)
- <input type=checkbox> Rewrite calls to `component.get('foo')` as `component.get().foo`
- <input type=checkbox> Return `destroy` from your custom event handlers, rather than `teardown`
- <input type=checkbox> Make sure you're not passing numeric string props to components
## New template syntax
The most visible change: we've made some improvements to the template syntax.
A common piece of feedback we heard was 'ewww, Mustache' or 'ewww, Handlebars'. A lot of people who used string-based templating systems in a previous era of web development *really* dislike them. Because Svelte adopted the `{{curlies}}` from those languages, a lot of people assumed that we somehow shared the limitations of those tools, such as weird scoping rules or an inability to use arbitrary JavaScript expressions.
<aside>If you need to show an actual `{` character, it's as easy as `&amp;#123;`</aside>
Beyond that, JSX proved that double curlies are unnecessary. So we've made our templates more... svelte, by adopting single curlies. The result feels much lighter to look at and is more pleasant to type:
```html
<h1>Hello {name}!</h1>
```
There are a few other updates. But you don't need to make them manually — just run [svelte-upgrade](https://github.com/sveltejs/svelte-upgrade) on your codebase:
```bash
npx svelte-upgrade v2 src
```
This assumes any `.html` files in `src` are Svelte components. You can specify whichever directory you like, or target a different directory — for example, you'd do `npx svelte-upgrade v2 routes` to update a [Sapper](https://sapper.svelte.technology) app.
To see the full set of changes, consult the [svelte-upgrade README](https://github.com/sveltejs/svelte-upgrade#svelte-v2-syntax-changes).
## Computed properties
Another thing that people often found confusing about Svelte is the way computed properties work. To recap, if you had a component with this...
```js
export default {
computed: {
d: (a, b, c) => a = b + c
}
};
```
...then Svelte would first look at the function arguments to see which values `d` depended on, and then it would write code that updated `d` whenever those values changed, by injecting them into the function. That's cool, because it allows you to derive complex values from your component's inputs without worrying about when they need to recomputed, but it's also... *weird*. JavaScript doesn't work that way!
In v2, we use [destructuring](http://www.jstips.co/en/javascript/use-destructuring-in-function-parameters/) instead:
```js
export default {
computed: {
d: ({ a, b, c }) => a = b + c
}
};
```
The Svelte compiler can still see which values `d` depends on, but it's no longer injecting values — it just passes the component state object into each computed property.
Again, you don't need to make this change manually — just run svelte-upgrade on your components, as shown above.
## Sorry, IE11. It's not you, it's... well actually, yeah. It's you
Svelte v1 was careful to only emit ES5 code, so that you wouldn't be forced to faff around with transpilers in order to use it. But it's 2018 now, and almost all browsers support modern JavaScript. By ditching the ES5 constraint, we can generate leaner code.
If you need to support IE11 and friends, you will need to use a transpiler like [Babel](http://babeljs.io/repl) or [Bublé](http://buble.surge.sh/).
## New lifecycle hooks
In addition to `oncreate` and `ondestroy`, Svelte v2 adds two more [lifecycle hooks](guide#lifecycle-hooks) for responding to state changes:
```js
export default {
onstate({ changed, current, previous }) {
// this fires before oncreate, and
// whenever state changes
},
onupdate({ changed, current, previous }) {
// this fires after oncreate, and
// whenever the DOM has been updated
// following a state change
}
};
```
You can also listen to those events programmatically:
```js
component.on('state', ({ changed, current, previous }) => {
// ...
});
```
## component.observe
With the new lifecycle hooks, we no longer need the `component.observe(...)` method:
```js
// before
export default {
oncreate() {
this.observe('foo', foo => {
console.log(`foo is now ${foo}`);
});
}
};
// after
export default {
onstate({ changed, current }) {
if (changed.foo) {
console.log(`foo is now ${current.foo}`);
}
}
};
```
This shrinks the amount of code Svelte needs to generate, and gives you more flexibility. For example, it's now very easy to take action when any one of *several* properties have changed, such as redrawing a canvas without debouncing several observers.
However, if you prefer to use `component.observe(...)`, then you can install it from [svelte-extras](https://github.com/sveltejs/svelte-extras):
```js
import { observe } from 'svelte-extras';
export default {
methods: {
observe
}
};
```
## component.get
This method no longer takes an optional `key` argument — instead, it always returns the entire state object:
```js
// before
const foo = this.get('foo');
const bar = this.get('bar');
// after
const { foo, bar } = this.get();
```
This change might seem annoying initially, but it's the right move: among other things, it's likely to play better with type systems as we explore that space more fully in future.
## event_handler.destroy
If your app has [custom event handlers](guide#custom-event-handlers), they must return an object with a `destroy` method, *not* a `teardown` method (this aligns event handlers with the component API).
## No more type coercion
Previously, numeric values passed to components were treated as numbers:
```html
<Counter start='1'/>
```
That causes unexpected behaviour, and has been changed: if you need to pass a literal number, do so as an expression:
```html
<Counter start={1}/>
```
## Compiler changes
In most cases you'll never need to deal with the compiler directly, so this shouldn't require any action on your part. It's worth noting anyway: the compiler API has changed. Instead of an object with a mish-mash of properties, the compiler now returns `js`, `css`, `ast` and `stats`:
```js
const { js, css, ast, stats } = svelte.compile(source, options);
```
`js` and `css` are both `{ code, map }` objects, where `code` is a string and `map` is a sourcemap. The `ast` is an abstract syntax tree of your component, and the `stats` object contains metadata about the component, and information about the compilation.
Before, there was a `svelte.validate` method which checked your component was valid. That's been removed — if you want to check a component without actually compiling it, just pass the `generate: false` option.
## My app is broken! Help!
Hopefully this covers everything, and the update should be easier for you than it was for us. But if you find bugs, or discover things that aren't mentioned here, swing by [Gitter](https://gitter.im/sveltejs/svelte) or raise an issue on the [tracker](https://github.com/sveltejs/svelte/issues).

@ -0,0 +1,125 @@
<!--
https://eugenkiss.github.io/7guis/tasks#circle
Click on the canvas to draw a circle. Click on a circle
to select it. Right-click on the canvas to adjust the
radius of the selected circle.
-->
<script>
let i = 0;
let undoStack = [[]];
let circles = [];
let selected;
let adjusting = false;
let adjusted = false;
function handleClick(event) {
if (adjusting) {
adjusting = false;
// if circle was adjusted,
// push to the stack
if (adjusted) push();
return;
}
const circle = {
cx: event.clientX,
cy: event.clientY,
r: 50
};
circles = circles.concat(circle);
selected = circle;
push();
}
function adjust(event) {
selected.r = +event.target.value;
circles = circles;
adjusted = true;
}
function select(circle, event) {
if (!adjusting) {
event.stopPropagation();
selected = circle;
}
}
function push() {
const newUndoStack = undoStack.slice(0, ++i);
newUndoStack.push(clone(circles));
undoStack = newUndoStack;
}
function travel(d) {
circles = clone(undoStack[i += d]);
adjusting = false;
}
function clone(circles) {
return circles.map(({ cx, cy, r }) => ({ cx, cy, r }));
}
</script>
<style>
.controls {
position: absolute;
width: 100%;
text-align: center;
}
svg {
background-color: #eee;
width: 100%;
height: 100%;
}
circle {
stroke: black;
}
.adjuster {
position: absolute;
width: 80%;
top: 50%;
left: 50%;
transform: translate(-50%,-50%);
padding: 1em;
text-align: center;
background-color: rgba(255,255,255,0.7);
border-radius: 4px;
}
input[type='range'] {
width: 100%;
}
</style>
<div class="controls">
<button on:click="{() => travel(-1)}" disabled="{i === 0}">undo</button>
<button on:click="{() => travel(+1)}" disabled="{i === undoStack.length -1}">redo</button>
</div>
<svg on:click={handleClick} >
{#each circles as circle}
<circle cx={circle.cx} cy={circle.cy} r={circle.r}
on:click="{event => select(circle, event)}"
on:contextmenu|stopPropagation|preventDefault="{() => {
adjusting = !adjusting;
if (adjusting) selected = circle;
}}"
fill="{circle === selected ? '#ccc': 'white'}"
/>
{/each}
</svg>
{#if adjusting}
<div class="adjuster">
<p>adjust diameter of circle at {selected.cx}, {selected.cy}</p>
<input type="range" value={selected.r} on:input={adjust}>
</div>
{/if}

@ -0,0 +1,3 @@
<!-- https://github.com/eugenkiss/7guis/wiki#counter -->
<input type=number bind:value={count}>
<button on:click="{() => count += 1}">count</button>

@ -0,0 +1,84 @@
<!-- https://eugenkiss.github.io/7guis/tasks#crud -->
<script>
import { beforeUpdate } from 'svelte';
export let people = [];
let filteredPeople;
let selected;
let prefix = '';
let first = '';
let last = '';
let i = 0;
function create() {
people = people.concat({ first, last });
i = people.length - 1;
first = last = '';
}
function update() {
people[i] = { first, last };
}
function remove() {
people = [...people.slice(0, i), ...people.slice(i + 1)];
first = last = '';
i = Math.min(i, people.length - 1);
}
$: filteredPeople = prefix
? people.filter(person => {
const name = `${person.last}, ${person.first}`;
return name.toLowerCase().startsWith(prefix.toLowerCase());
})
: people;
$: selected = filteredPeople[i];
$: if (selected) {
first = selected.first;
last = selected.last;
}
</script>
<style>
* {
font-family: inherit;
font-size: inherit;
}
input {
display: block;
margin: 0 0 0.5em 0;
}
select {
float: left;
margin: 0 1em 1em 0;
width: 14em;
}
.buttons {
clear: both;
}
</style>
<input placeholder="filter prefix" bind:value={prefix}>
<select bind:value={i} size={5}>
{#each filteredPeople as person, i}
<option value={i}>{person.last}, {person.first}</option>
{/each}
</select>
<label><input bind:value={first} placeholder="first"></label>
<label><input bind:value={last} placeholder="last"></label>
<div class='buttons'>
<button on:click={create} disabled="{!first || !last}">create</button>
<button on:click={update} disabled="{!first || !last || !selected}">update</button>
<button on:click={remove} disabled="{!selected}">delete</button>
</div>

@ -0,0 +1,16 @@
{
"people": [
{
"first": "Hans",
"last": "Emil"
},
{
"first": "Max",
"last": "Mustermann"
},
{
"first": "Roman",
"last": "Tisch"
}
]
}

@ -0,0 +1,61 @@
<script>
const tomorrow = new Date(Date.now() + 86400000);
const tomorrowAsString = [
tomorrow.getFullYear(),
pad(tomorrow.getMonth() + 1, 2),
pad(tomorrow.getDate(), 2)
].join('-');
let start = tomorrowAsString;
let end = tomorrowAsString;
let isReturn = false;
const startDate = () => convertToDate(start);
const endDate = () => convertToDate(end);
function bookFlight() {
const type = isReturn ? 'return' : 'one-way';
let message = `You have booked a ${type} flight, leaving ${startDate().toDateString()}`;
if (type === 'return') {
message += ` and returning ${endDate().toDateString()}`;
}
alert(message);
}
function convertToDate(str) {
var split = str.split('-');
return new Date(+split[0], +split[1] - 1, +split[2]);
}
function pad(x, len) {
x = String(x);
while (x.length < len) x = `0${x}`;
return x;
}
</script>
<style>
select, input, button {
display: block;
margin: 0.5em 0;
font-size: inherit;
}
</style>
<!-- https://github.com/eugenkiss/7guis/wiki#flight-booker -->
<select bind:value={isReturn}>
<option value={false}>one-way flight</option>
<option value={true}>return flight</option>
</select>
<input type=date bind:value={start}>
<input type=date bind:value={end} disabled={!isReturn}>
<button
on:click={bookFlight}
disabled="{isReturn && (startDate() >= endDate())}"
>book</button>

@ -0,0 +1,24 @@
<!-- https://github.com/eugenkiss/7guis/wiki#temperature-converter -->
<input value={c} on:input="{e => setBothFromC(e.target.value)}" type=number> °c =
<input value={f} on:input="{e => setBothFromF(e.target.value)}" type=number> °f
<style>
input {
width: 5em;
}
</style>
<script>
let c = 0;
let f = 32;
function setBothFromC(value) {
c = +value;
f = +(32 + (9 / 5 * c)).toFixed(1);
}
function setBothFromF(value) {
f = +value;
c =+(5 / 9 * (f - 32)).toFixed(1);
}
</script>

@ -0,0 +1,41 @@
<!-- https://eugenkiss.github.io/7guis/tasks#timer -->
<script>
import { onDestroy } from 'svelte';
let elapsed = 0;
let duration = 5000;
let last_time = window.performance.now();
let frame;
(function update() {
frame = requestAnimationFrame(update);
const time = window.performance.now();
elapsed += Math.min(
time - last_time,
duration - elapsed
);
last_time = time;
}());
onDestroy(() => {
cancelAnimationFrame(frame);
});
</script>
<label>
elapsed time:
<progress value="{elapsed / duration}"></progress>
</label>
<div>{(elapsed / 1000).toFixed(1)}s</div>
<label>
duration:
<input type="range" bind:value={duration} min="1" max="20000">
</label>
<button on:click="{() => elapsed = 0}">reset</button>

@ -0,0 +1,24 @@
<script>
export let promise;
// [svelte-upgrade suggestion]
// review these functions and remove unnecessary 'export' keywords
export function findAnswer() {
promise = new Promise(fulfil => {
const delay = 1000 + Math.random() * 3000;
setTimeout(() => fulfil(42), delay);
});
}
</script>
<button on:click='{findAnswer}'>find the answer</button>
{#if promise}
{#await promise}
<p>wait for it...</p>
{:then answer}
<p>the answer is {answer}!</p>
{:catch error}
<p>well that's odd</p>
{/await}
{/if}

@ -0,0 +1,112 @@
<script>
import { onMount } from 'svelte';
import { scaleLinear } from 'd3-scale';
export let points;
const xTicks = [1990, 1995, 2000, 2005, 2010, 2015];
const yTicks = [0, 5, 10, 15, 20];
const padding = { top: 20, right: 15, bottom: 20, left: 25 };
let width = 500;
let height = 200;
let barWidth;
let xScale;
let yScale;
function formatMobile(tick) {
return "'" + tick % 100;
}
$: xScale = scaleLinear()
.domain([0, xTicks.length])
.range([padding.left, width - padding.right]);
$: yScale = scaleLinear()
.domain([0, Math.max.apply(null, yTicks)])
.range([height - padding.bottom, padding.top]);
$: {
const innerWidth = width - (padding.left + padding.right);
barWidth = innerWidth / xTicks.length;
}
</script>
<style>
.chart {
width: 100%;
max-width: 500px;
margin: 0 auto;
}
svg {
position: relative;
width: 100%;
height: 200px;
}
.tick {
font-family: Helvetica, Arial;
font-size: .725em;
font-weight: 200;
}
.tick line {
stroke: #e2e2e2;
stroke-dasharray: 2;
}
.tick text {
fill: #ccc;
text-anchor: start;
}
.tick.tick-0 line {
stroke-dasharray: 0;
}
.x-axis .tick text {
text-anchor: middle;
}
.bars rect {
fill: #a11;
stroke: none;
opacity: 0.65;
}
</style>
<div class="chart">
<h2>US birthrate by year {width}/{height}</h2>
<svg bind:clientWidth={width} bind:clientHeight={height}>
<!-- y axis -->
<g class="axis y-axis" transform="translate(0,{padding.top})">
{#each yTicks as tick}
<g class="tick tick-{tick}" transform="translate(0, {yScale(tick) - padding.bottom})">
<line x2="100%"></line>
<text y="-4">{tick} {tick === 20 ? ' per 1,000 population' : ''}</text>
</g>
{/each}
</g>
<!-- x axis -->
<g class="axis x-axis">
{#each points as point, i}
<g class="tick" transform="translate({xScale(i)},{height})">
<text x="{barWidth/2}" y="-4">{width > 380 ? point.year : formatMobile(point.year)}</text>
</g>
{/each}
</g>
<g class='bars'>
{#each points as point, i}
<rect
x="{xScale(i) + 2}"
y="{yScale(point.birthrate)}"
width="{barWidth - 4}"
height="{height - padding.bottom - yScale(point.birthrate)}"
></rect>
{/each}
</g>
</svg>
</div>

@ -0,0 +1,28 @@
{
"points": [
{
"year": 1990,
"birthrate": 16.7
},
{
"year": 1995,
"birthrate": 14.6
},
{
"year": 2000,
"birthrate": 14.4
},
{
"year": 2005,
"birthrate": 14
},
{
"year": 2010,
"birthrate": 13
},
{
"year": 2015,
"birthrate": 12.4
}
]
}

@ -0,0 +1,16 @@
<label>
<input type=checkbox bind:group={selected} value="red">
red
</label>
<label>
<input type=checkbox bind:group={selected} value="green">
green
</label>
<label>
<input type=checkbox bind:group={selected} value="blue">
blue
</label>
<p>{selected.join(', ') || 'nothing'} selected</p>

@ -0,0 +1,17 @@
{#each todos as todo}
<div class="todo {todo.done ? 'done': ''}">
<input type=checkbox bind:checked={todo.done}>
<input type=text bind:value={todo.description}>
</div>
{/each}
<style>
input[type="text"] {
width: 20em;
max-width: calc(100% - 2em);
}
.done {
opacity: 0.6;
}
</style>

@ -0,0 +1,16 @@
{
"todos": [
{
"description": "Buy some milk",
"done": true
},
{
"description": "Do the laundry",
"done": true
},
{
"description": "Find life's true purpose",
"done": false
}
]
}

@ -0,0 +1,12 @@
<!-- number and range inputs are bound to numeric values -->
<input bind:value={a} type=number min=0 max=10>
<input bind:value={b} type=range min=0 max=10>
<p>{a} * {b} = {a * b}</p>
<style>
input {
display: block;
width: 10em
}
</style>

@ -0,0 +1,16 @@
<label>
<input type=radio bind:group={selected} value="red">
red
</label>
<label>
<input type=radio bind:group={selected} value="green">
green
</label>
<label>
<input type=radio bind:group={selected} value="blue">
blue
</label>
<p style="color: {selected};">selected {selected}</p>

@ -0,0 +1,2 @@
<input bind:value={name} placeholder="enter your name">
<p>Hello {name || 'stranger'}!</p>

@ -0,0 +1,96 @@
<script>
export let paused = true;
export let t = 0;
export let d;
let icon, bg;
$: icon = `https://icon.now.sh/${paused ? 'play' : 'pause'}_circle_filled`;
$: {
var p = d ? t / d : 0;
var h = 90 + 90 * p;
var l = 10 + p * 30;
bg = `hsl(${h},50%,${l}%)`;
}
function pad(num) {
return num < 10 ? '0' + num : num;
}
const format = time => {
if (isNaN(time)) return '--:--.-';
var minutes = Math.floor(time / 60);
var seconds = (time % 60).toFixed(1);
return minutes + ':' + pad(seconds)
};
function seek(event) {
if (event.buttons === 1) {
event.preventDefault();
var p = event.clientX / window.innerWidth;
t = p * d;
}
}
</script>
<svelte:window on:click={seek} on:mousemove={seek}/>
<audio bind:currentTime={t} bind:duration={d} bind:paused>
<source type="audio/mp3" src="https://deepnote.surge.sh/deepnote.mp3">
</audio>
<p>THX Deep Note</p>
<div class="status" on:click="{event => event.stopPropagation()}">
<img alt="play/pause button" on:click="{() => paused = !paused}" src="{icon}/333333">
<span class="elapsed">{format(t)}</span>
<span class="duration">{format(d)}</span>
</div>
<div class="progress" style="width: {d ? 100 * t/d : 0}%; background: {bg};">
<p>THX Deep Note</p>
<div class="status" on:click="{event => event.stopPropagation()}">
<img alt="play/pause button" src="{icon}/ffffff">
<span class="elapsed">{format(t)}</span>
<span class="duration">{format(d)}</span>
</div>
</div>
<style>
.progress {
position: absolute;
left: 0;
top: 0;
width: 100%;
height: 100%;
color: white;
overflow: hidden;
pointer-events: none;
}
p {
position: absolute;
left: 1em;
top: 1em;
width: 20em;
}
.status {
position: absolute;
bottom: 1em;
left: 1em;
width: calc(100vw - 2em);
}
img {
position: absolute;
left: 0;
bottom: 2em;
width: 3em;
cursor: pointer;
}
.elapsed { float: left; }
.duration { float: right; }
</style>

@ -0,0 +1,15 @@
<script>
import marked from 'marked';
export let markdown;
</script>
<textarea bind:value={markdown} resize="none"></textarea>
<div class="output">{@html marked(markdown)}</div>
<style>
textarea {
width: 100%;
height: 50%;
}
</style>

@ -0,0 +1,3 @@
{
"markdown": "# Markdown editor\n\nTODOs:\n\n* make a Svelte app\n* think of a third item for this list"
}

@ -0,0 +1,7 @@
<h1>Cats of YouTube</h1>
<ul>
{#each cats as cat}
<li><a target="_blank" href={cat.video}>{cat.name}</a></li>
{/each}
</ul>

@ -0,0 +1,16 @@
{
"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"
}
]
}

@ -0,0 +1,59 @@
<script>
import { onMount } from 'svelte';
import List from './List.html';
import Item from './Item.html';
let item;
let page;
onMount(() => {
hashchange();
});
async function hashchange() {
// the poor man's router!
const path = window.location.hash.slice(1);
if (path.startsWith('/item')) {
const id = path.slice(6);
item = await fetch(`https://node-hnapi.herokuapp.com/item/${id}`).then(r => r.json());
window.scrollTo(0,0);
} else if (path.startsWith('/top')) {
page = +path.slice(5);
item = null;
} else {
window.location.hash = '/top/1';
}
}
</script>
<style>
main {
position: relative;
max-width: 800px;
margin: 0 auto;
min-height: 101vh;
padding: 1em;
}
main :global(.meta) {
color: #999;
font-size: 12px;
margin: 0 0 1em 0;
}
main :global(a) {
color: rgb(0,0,150);
}
</style>
<svelte:window on:hashchange={hashchange}/>
<main>
{#if item}
<Item {item}/>
{:elseif page}
<List {page}/>
{/if}
</main>

@ -0,0 +1,28 @@
<style>
article {
border-top: 1px solid #eee;
margin: 1em 0 0 0;
padding: 1em 0 0 0;
font-size: 14px;
}
.meta {
color: #999;
}
.replies {
padding: 0 0 0 1em;
}
</style>
<article>
<p class="meta">{comment.user} {comment.time_ago}</p>
{@html comment.content}
<div class="replies">
{#each comment.comments as child}
<svelte:self comment={child}/>
{/each}
</div>
</article>

@ -0,0 +1,43 @@
<script>
import Comment from "./Comment.html";
export let item;
function back(event) {
event.preventDefault();
window.history.back();
}
</script>
<style>
article {
margin: 0 0 1em 0;
}
a {
display: block;
margin: 0 0 1em 0;
}
h1 {
font-size: 1.4em;
margin: 0;
}
</style>
<a href="#/top/1" on:click={back}>&laquo; back</a>
<article>
<a href="{item.url}">
<h1>{item.title}</h1>
<small>{item.domain}</small>
</a>
<p class="meta">submitted by {item.user} {item.time_ago}
</article>
<div class="comments">
{#each item.comments as comment}
<Comment {comment}/>
{/each}
</div>

@ -0,0 +1,49 @@
<script>
import { beforeUpdate } from "svelte";
import Summary from "./Summary.html";
const PAGE_SIZE = 20;
export let items;
export let offset;
export let page;
let previous_page;
beforeUpdate(async () => {
if (page !== previous_page) {
previous_page = page;
items = await fetch(`https://node-hnapi.herokuapp.com/news?page=${page}`).then(r => r.json())
offset = PAGE_SIZE * (page - 1);
window.scrollTo(0, 0);
}
});
</script>
<style>
a {
padding: 2em;
display: block;
}
.loading {
opacity: 0;
animation: 0.4s 0.8s forwards fade-in;
}
@keyframes fade-in {
from { opacity: 0; }
to { opacity: 1; }
}
</style>
{#if items}
{#each items as item, i}
<Summary {item} {i} {offset}/>
{/each}
<a href="#/top/{page + 1}">page {page + 1}</a>
{:else}
<p class="loading">loading...</p>
{/if}

@ -0,0 +1,38 @@
<script>
export let item;
export let i;
export let offset;
function comment_text() {
const c = item.comments_count;
return `${c} ${c === 1 ? 'comment' : 'comments'}`;
}
</script>
<style>
article {
position: relative;
padding: 0 0 0 2em;
border-bottom: 1px solid #eee;
}
h2 {
font-size: 1em;
margin: 0.5em 0;
}
span {
position: absolute;
left: 0;
}
a {
color: #333;
}
</style>
<article>
<span>{i + offset + 1}</span>
<h2><a target="_blank" href={item.url}>{item.title}</a></h2>
<p class="meta"><a href="#/item/{item.id}">{comment_text()}</a> by {item.user} {item.time_ago}</p>
</article>

@ -0,0 +1,14 @@
<h1>Hello {name}!</h1>
<!--
This is a Svelte component. Click the toggle
below right to see the generated code.
You can interact with this component via your
browser's console - try running the following:
app.name = 'everybody';
You can also update the data via the props
editor on this page.
-->

@ -0,0 +1,5 @@
{#if foo}
<p>foo!</p>
{:else}
<p>not foo!</p>
{/if}

@ -0,0 +1,40 @@
<svelte:meta immutable/>
<script>
import ImmutableTodo from './ImmutableTodo.html';
import MutableTodo from './MutableTodo.html';
export let todos;
function toggle(id) {
todos = todos.map(todo => {
if (todo.id === id) {
// return a new object
return {
id,
done: !todo.done,
text: todo.text
};
}
// return the same object
return todo;
});
}
</script>
<h2>Immutable</h2>
{#each todos as todo}
<label on:click="{() => toggle(todo.id)}">
<span>{todo.done ? "😎": "☹️"}</span>
<ImmutableTodo {todo}/>
</label>
{/each}
<h2>Mutable</h2>
{#each todos as todo}
<label on:click="{() => toggle(todo.id)}">
<span>{todo.done ? "😎": "☹️"}</span>
<MutableTodo {todo}/>
</label>
{/each}

@ -0,0 +1,15 @@
<svelte:meta immutable/>
<script>
import { afterUpdate } from 'svelte';
import flash from './flash.js';
export let todo;
let span;
flash(() => span);
</script>
<!-- the text will flash red whenever
the `todo` object changes -->
<span bind:this={span}>{todo.text}</span>

@ -0,0 +1,13 @@
<script>
import { afterUpdate } from 'svelte';
import flash from './flash.js';
export let todo;
let span;
flash(() => span);
</script>
<!-- the text will flash red whenever
the `todo` object changes -->
<span bind:this={span}>{todo.text}</span>

@ -0,0 +1,7 @@
{
todos: [
{ id: 1, done: true, text: "wash the car" },
{ id: 2, done: false, text: "take the dog for a walk" },
{ id: 3, done: false, text: "mow the lawn" }
]
}

@ -0,0 +1,13 @@
import { afterUpdate } from 'svelte';
export default function flash(fn) {
afterUpdate(() => {
const span = fn();
span.style.color = 'red';
setTimeout(() => {
span.style.color = 'black';
}, 400);
});
}

@ -0,0 +1,129 @@
<script>
import { onMount } from 'svelte';
import { scaleLinear } from 'd3-scale';
export let points;
const yTicks = [0, 2, 4, 6, 8];
const xTicks = [1980, 1990, 2000, 2010];
const padding = { top: 20, right: 15, bottom: 20, left: 25 };
let svg;
let width = 500;
let height = 200;
let xScale;
let yScale;
let minX;
let maxX;
let path;
let area;
$: xScale = scaleLinear()
.domain([minX, maxX])
.range([padding.left, width - padding.right]);
$: yScale = scaleLinear()
.domain([Math.min.apply(null, yTicks), Math.max.apply(null, yTicks)])
.range([height - padding.bottom, padding.top]);
$: minX = points[0].x;
$: maxX = points[points.length - 1].x;
$: path = `M${points.map(p => `${xScale(p.x)},${yScale(p.y)}`).join('L')}`;
$: area = `${path}L${xScale(maxX)},${yScale(0)}L${xScale(minX)},${yScale(0)}Z`;
function formatMobile (tick) {
return "'" + tick % 100;
}
function resize() {
const bcr = svg.getBoundingClientRect();
width = bcr.width;
height = bcr.height;
}
onMount(resize);
</script>
<svelte:window on:resize='{resize}'/>
<div class="chart">
<h2>Arctic sea ice minimum</h2>
<svg bind:this={svg}>
<!-- y axis -->
<g class="axis y-axis" transform="translate(0, {padding.top})">
{#each yTicks as tick}
<g class="tick tick-{tick}" transform="translate(0, {yScale(tick) - padding.bottom})">
<line x2="100%"></line>
<text y="-4">{tick} {tick === 8 ? ' million sq km' : ''}</text>
</g>
{/each}
</g>
<!-- x axis -->
<g class="axis x-axis">
{#each xTicks as tick}
<g class="tick tick-{ tick }" transform="translate({xScale(tick)},{height})">
<line y1="-{height}" y2="-{padding.bottom}" x1="0" x2="0"></line>
<text y="-2">{width > 380 ? tick : formatMobile(tick)}</text>
</g>
{/each}
</g>
<!-- data -->
<path class="path-area" d={area}></path>
<path class="path-line" d={path}></path>
</svg>
<p>Average September extent. Source: <a href='https://climate.nasa.gov/vital-signs/arctic-sea-ice/'>NSIDC/NASA</a>
</div>
<style>
.chart {
width: 100%;
max-width: 500px;
margin: 0 auto;
}
svg {
position: relative;
width: 100%;
height: 200px;
}
.tick {
font-size: .725em;
font-weight: 200;
}
.tick line {
stroke: #aaa;
stroke-dasharray: 2;
}
.tick text {
fill: #666;
text-anchor: start;
}
.tick.tick-0 line {
stroke-dasharray: 0;
}
.x-axis .tick text {
text-anchor: middle;
}
.path-line {
fill: none;
stroke: rgb(0,100,100);
stroke-linejoin: round;
stroke-linecap: round;
stroke-width: 2;
}
.path-area {
fill: rgba(0,100,100,0.2);
}
</style>

@ -0,0 +1,156 @@
{
"points": [
{
"x": 1979,
"y": 7.19
},
{
"x": 1980,
"y": 7.83
},
{
"x": 1981,
"y": 7.24
},
{
"x": 1982,
"y": 7.44
},
{
"x": 1983,
"y": 7.51
},
{
"x": 1984,
"y": 7.1
},
{
"x": 1985,
"y": 6.91
},
{
"x": 1986,
"y": 7.53
},
{
"x": 1987,
"y": 7.47
},
{
"x": 1988,
"y": 7.48
},
{
"x": 1989,
"y": 7.03
},
{
"x": 1990,
"y": 6.23
},
{
"x": 1991,
"y": 6.54
},
{
"x": 1992,
"y": 7.54
},
{
"x": 1993,
"y": 6.5
},
{
"x": 1994,
"y": 7.18
},
{
"x": 1995,
"y": 6.12
},
{
"x": 1996,
"y": 7.87
},
{
"x": 1997,
"y": 6.73
},
{
"x": 1998,
"y": 6.55
},
{
"x": 1999,
"y": 6.23
},
{
"x": 2000,
"y": 6.31
},
{
"x": 2001,
"y": 6.74
},
{
"x": 2002,
"y": 5.95
},
{
"x": 2003,
"y": 6.13
},
{
"x": 2004,
"y": 6.04
},
{
"x": 2005,
"y": 5.56
},
{
"x": 2006,
"y": 5.91
},
{
"x": 2007,
"y": 4.29
},
{
"x": 2008,
"y": 4.72
},
{
"x": 2009,
"y": 5.38
},
{
"x": 2010,
"y": 4.92
},
{
"x": 2011,
"y": 4.61
},
{
"x": 2012,
"y": 3.62
},
{
"x": 2013,
"y": 5.35
},
{
"x": 2014,
"y": 5.28
},
{
"x": 2015,
"y": 4.63
},
{
"x": 2016,
"y": 4.72
}
]
}

@ -0,0 +1,175 @@
[
{
"name": "Basics",
"examples": [
{
"slug": "hello-world",
"title": "Hello World!"
},
{
"slug": "if-blocks",
"title": "If blocks"
},
{
"slug": "each-blocks",
"title": "Each blocks"
},
{
"slug": "scoped-styles",
"title": "Scoped styles"
}
]
},
{
"name": "Two-way bindings",
"examples": [
{
"slug": "binding-input-text",
"title": "Text input"
},
{
"slug": "binding-input-numeric",
"title": "Numeric input"
},
{
"slug": "binding-textarea",
"title": "Textarea"
},
{
"slug": "binding-input-checkbox",
"title": "Checkbox input"
},
{
"slug": "binding-input-checkbox-group",
"title": "Checkbox input (grouped)"
},
{
"slug": "binding-input-radio",
"title": "Radio input"
},
{
"slug": "binding-media-elements",
"title": "Media elements"
}
]
},
{
"name": "Nested components",
"examples": [
{
"slug": "nested-components",
"title": "Nested components"
},
{
"slug": "modal-with-slot",
"title": "Modal with <slot>"
},
{
"slug": "self-references",
"title": "Self-references"
}
]
},
{
"name": "SVG and dataviz",
"examples": [
{
"slug": "svg-clock",
"title": "SVG Clock"
},
{
"slug": "line-chart",
"title": "Line/area chart"
},
{
"slug": "bar-chart",
"title": "Bar chart"
},
{
"slug": "scatterplot",
"title": "Scatterplot"
}
]
},
{
"name": "Transitions",
"examples": [
{
"slug": "transitions-fade",
"title": "Simple fade"
},
{
"slug": "transitions-fly",
"title": "Parameterised"
},
{
"slug": "transitions-in-out",
"title": "In and out"
},
{
"slug": "transitions-custom",
"title": "Custom CSS"
}
]
},
{
"name": "Async data",
"examples": [
{
"slug": "await-block",
"title": "Await block"
}
]
},
{
"name": "7guis",
"examples": [
{
"slug": "7guis-counter",
"title": "Counter"
},
{
"slug": "7guis-temperature",
"title": "Temperature converter"
},
{
"slug": "7guis-flight-booker",
"title": "Flight booker"
},
{
"slug": "7guis-timer",
"title": "Timer"
},
{
"slug": "7guis-crud",
"title": "CRUD"
},
{
"slug": "7guis-circles",
"title": "Circles"
}
]
},
{
"name": "<:Window>",
"examples": [
{
"slug": "parallax",
"title": "Parallax"
}
]
},
{
"name": "Miscellaneous",
"examples": [
{
"slug": "hacker-news",
"title": "Hacker News"
},
{
"slug": "immutable",
"title": "Immutable data"
}
]
}
]

@ -0,0 +1,29 @@
<script>
import Modal from './Modal.html';
export let showModal;
</script>
{#if showModal}
<Modal on:close="{() => showModal = false}">
<h2 slot="header">
modal
<small><em>adjective</em> mod·al \ˈmō-dəl\</small>
</h2>
<ol class="definition-list">
<li>of or relating to modality in logic</li>
<li>containing provisions as to the mode of procedure or the manner of taking effect —used of a contract or legacy</li>
<li>of or relating to a musical mode</li>
<li>of or relating to structure as opposed to substance</li>
<li>of, relating to, or constituting a grammatical form or category characteristically indicating predication</li>
<li>of or relating to a statistical mode</li>
</ol>
<a href="https://www.merriam-webster.com/dictionary/modal">merriam-webster.com</a>
</Modal>
{:else}
<button on:click="{() => showModal = true}">
show modal
</button>
{/if}

@ -0,0 +1,45 @@
<script>
import { createEventDispatcher } from 'svelte';
const dispatch = createEventDispatcher();
</script>
<div class='modal-background' on:click='{() => dispatch("close")}'></div>
<div class='modal'>
<slot name='header'></slot>
<hr>
<slot></slot>
<hr>
<button on:click='{() => dispatch("close")}'>close modal</button>
</div>
<style>
.modal-background {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background: rgba(0,0,0,0.3);
}
.modal {
position: absolute;
left: 50%;
top: 50%;
width: calc(100vw - 4em);
max-width: 32em;
max-height: calc(100vh - 4em);
overflow: auto;
transform: translate(-50%,-50%);
padding: 1em;
border-radius: 0.2em;
background: white;
}
button {
display: block;
}
</style>

@ -0,0 +1,6 @@
<script>
import Nested from './Nested.html';
</script>
<p>This is a top-level element.</p>
<Nested/>

@ -0,0 +1 @@
<p>And this is a nested component.</p>

@ -0,0 +1,76 @@
<script>
let sy;
</script>
<!-- this binds `sy` to the current value of `window.scrollY` -->
<svelte:window bind:scrollY={sy}/>
<!-- try changing the values that `sy` is multiplied by -
values closer to 0 appear further away -->
<div class="parallax-container">
<img style="transform: translate(0,{-sy * 0.2}px)" src="http://www.firewatchgame.com/images/parallax/parallax0.png">
<img style="transform: translate(0,{-sy * 0.3}px)" src="http://www.firewatchgame.com/images/parallax/parallax1.png">
<img style="transform: translate(0,{-sy * 0.4}px)" src="http://www.firewatchgame.com/images/parallax/parallax3.png">
<img style="transform: translate(0,{-sy * 0.5}px)" src="http://www.firewatchgame.com/images/parallax/parallax5.png">
<img style="transform: translate(0,{-sy * 0.6}px)" src="http://www.firewatchgame.com/images/parallax/parallax7.png">
</div>
<div class="text">
<small style="
transform: translate(0,{-sy * 1.5}px);
opacity: {1 - Math.max( 0, sy / 80 )}
">(scroll down)</small>
<span>parallax has never been this easy</span>
</div>
<style>
.parallax-container {
position: fixed;
width: 2400px;
height: 712px;
left: 50%;
transform: translate(-50%,0);
}
.parallax-container img {
position: absolute;
top: 0;
left: 0;
width: 100%;
will-change: transform;
}
.text {
position: relative;
width: 100%;
min-height: 100vh;
color: white;
text-align: center;
padding: 50vh 0.5em 0.5em 0.5em;
box-sizing: border-box;
}
.text::before {
content: '';
position: absolute;
width: 100%;
height: 100%;
top: 0;
left: 0;
background: linear-gradient(to bottom, rgba(45,10,13,0) 60vh,rgba(45,10,13,1) 712px);
}
small {
display: block;
font-size: 4vw;
will-change: transform, opacity;
}
.text span {
font-size: 20vw;
position: relative;
z-index: 2;
}
:global(body) { margin: 0; padding: 0; }
</style>

@ -0,0 +1,28 @@
<script>
import Scatterplot from './Scatterplot.html';
export let a;
export let b;
export let c;
export let d;
</script>
<div class="chart">
<h2>Anscombe's quartet</h2>
<Scatterplot points={a}/>
<Scatterplot points={b}/>
<Scatterplot points={c}/>
<Scatterplot points={d}/>
</div>
<style>
.chart {
width: 100%;
max-width: 640px;
height: calc(100% - 4em);
min-height: 280px;
max-height: 480px;
margin: 0 auto;
}
</style>

@ -0,0 +1,111 @@
<script>
// TODO this example needs updating
import { onMount } from 'svelte';
import { scaleLinear } from 'd3-scale';
export let svg;
const xScale = scaleLinear();
const yScale = scaleLinear();
export let width = 500;
export let height = 200;
export let padding = { top: 20, right: 40, bottom: 40, left: 25 };
export let points;
export let xTicks = [0, 4, 8, 12, 16, 20];
export let yTicks = [0, 2, 4, 6, 8, 10, 12];
function xTicks() {
return width > 180 ?
[0, 4, 8, 12, 16, 20] :
[0, 10, 20];
}
function yTicks() {
return height > 180 ?
[0, 2, 4, 6, 8, 10, 12] :
[0, 4, 8, 12];
}
function xScale() {
return xScale()
.domain([0, 20])
.range([padding.left, width - padding.right]);
}
function yScale() {
return yScale()
.domain([0, 12])
.range([height - padding.bottom, padding.top]);
}
onMount(() => {
resize();
});
function resize() {
const { width, height } = svg.getBoundingClientRect();
width = width, height = height;
}
</script>
<svelte:window on:resize='{resize}'/>
<svg ref:svg>
<!-- y axis -->
<g class='axis y-axis'>
{#each yTicks as tick}
<g class='tick tick-{tick}' transform='translate(0, {yScale()(tick)})'>
<line x1='{padding.left}' x2='{xScale()(22)}'/>
<text x='{padding.left - 8}' y='+4'>{tick}</text>
</g>
{/each}
</g>
<!-- x axis -->
<g class='axis x-axis'>
{#each xTicks as tick}
<g class='tick' transform='translate({xScale()(tick)},0)'>
<line y1='{yScale()(0)}' y2='{yScale()(13)}'/>
<text y='{height - padding.bottom + 16}'>{tick}</text>
</g>
{/each}
</g>
<!-- data -->
{#each points as point}
<circle cx='{xScale()(point.x)}' cy='{yScale()(point.y)}' r='5'/>
{/each}
</svg>
<style>
svg {
width: 50%;
height: 50%;
float: left;
}
circle {
fill: orange;
fill-opacity: 0.6;
stroke: rgba(0,0,0,0.5);
}
.tick line {
stroke: #ddd;
stroke-dasharray: 2;
}
text {
font-size: 12px;
fill: #999;
}
.x-axis text {
text-anchor: middle;
}
.y-axis text {
text-anchor: end;
}
</style>

@ -0,0 +1,186 @@
{
"a": [
{
"x": 10,
"y": 8.04
},
{
"x": 8,
"y": 6.95
},
{
"x": 13,
"y": 7.58
},
{
"x": 9,
"y": 8.81
},
{
"x": 11,
"y": 8.33
},
{
"x": 14,
"y": 9.96
},
{
"x": 6,
"y": 7.24
},
{
"x": 4,
"y": 4.26
},
{
"x": 12,
"y": 10.84
},
{
"x": 7,
"y": 4.82
},
{
"x": 5,
"y": 5.68
}
],
"b": [
{
"x": 10,
"y": 9.14
},
{
"x": 8,
"y": 8.14
},
{
"x": 13,
"y": 8.74
},
{
"x": 9,
"y": 8.77
},
{
"x": 11,
"y": 9.26
},
{
"x": 14,
"y": 8.1
},
{
"x": 6,
"y": 6.13
},
{
"x": 4,
"y": 3.1
},
{
"x": 12,
"y": 9.13
},
{
"x": 7,
"y": 7.26
},
{
"x": 5,
"y": 4.74
}
],
"c": [
{
"x": 10,
"y": 7.46
},
{
"x": 8,
"y": 6.77
},
{
"x": 13,
"y": 12.74
},
{
"x": 9,
"y": 7.11
},
{
"x": 11,
"y": 7.81
},
{
"x": 14,
"y": 8.84
},
{
"x": 6,
"y": 6.08
},
{
"x": 4,
"y": 5.39
},
{
"x": 12,
"y": 8.15
},
{
"x": 7,
"y": 6.42
},
{
"x": 5,
"y": 5.73
}
],
"d": [
{
"x": 8,
"y": 6.58
},
{
"x": 8,
"y": 5.76
},
{
"x": 8,
"y": 7.71
},
{
"x": 8,
"y": 8.84
},
{
"x": 8,
"y": 8.47
},
{
"x": 8,
"y": 7.04
},
{
"x": 8,
"y": 5.25
},
{
"x": 19,
"y": 12.5
},
{
"x": 8,
"y": 5.56
},
{
"x": 8,
"y": 7.91
},
{
"x": 8,
"y": 6.89
}
]
}

@ -0,0 +1,11 @@
<div class="foo">
Big red Comic Sans
</div>
<style>
.foo {
color: red;
font-size: 2em;
font-family: 'Comic Sans MS';
}
</style>

@ -0,0 +1,9 @@
<ul>
<li>{node.name}
{#if node.children}
{#each node.children as child}
<svelte:self node={child}/>
{/each}
{/if}
</li>
</ul>

@ -0,0 +1,32 @@
{
"node": {
"name": "Fruit",
"children": [
{
"name": "Red",
"children": [
{
"name": "Cherry"
},
{
"name": "Strawberry"
}
]
},
{
"name": "Green",
"children": [
{
"name": "Apple"
},
{
"name": "Pear"
},
{
"name": "Lime"
}
]
}
]
}
}

@ -0,0 +1,100 @@
<script>
import { onMount } from 'svelte';
export let time = new Date();
let hours, minutes, seconds;
$: {
// this block runs reactively, whenever
// `time` changes
hours = time.getHours();
minutes = time.getMinutes();
seconds = time.getSeconds();
}
onMount(() => {
const interval = setInterval(() => {
time = new Date();
}, 1000);
return () => {
clearInterval(interval);
};
});
</script>
<svg viewBox='-50 -50 100 100'>
<circle class='clock-face' r='48'/>
<!-- markers -->
{#each [0, 5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55] as minute}
<line
class='major'
y1='35'
y2='45'
transform='rotate({30 * minute})'
/>
{#each [1, 2, 3, 4] as offset}
<line
class='minor'
y1='42'
y2='45'
transform='rotate({6 * (minute + offset)})'
/>
{/each}
{/each}
<!-- hour hand -->
<line
class='hour'
y1='2'
y2='-20'
transform='rotate({30 * hours + minutes / 2})'
/>
<!-- minute hand -->
<line
class='minute'
y1='4'
y2='-30'
transform='rotate({6 * minutes + seconds / 10})'
/>
<!-- second hand -->
<g transform='rotate({6 * seconds})'>
<line class='second' y1='10' y2='-38'/>
<line class='second-counterweight' y1='10' y2='2'/>
</g>
</svg>
<style>
svg {
width: 100%;
height: 100%;
}
.clock-face {
stroke: #333;
fill: white;
}
.minor {
stroke: #999;
stroke-width: 0.5;
}
.major {
stroke: #333;
stroke-width: 1;
}
.hour {
stroke: #333;
}
.minute {
stroke: #666;
}
.second, .second-counterweight {
stroke: rgb(180,0,0);
}
.second-counterweight {
stroke-width: 3;
}
</style>

@ -0,0 +1,46 @@
<script>
import * as eases from 'eases-jsnext';
import { fade } from 'svelte-transitions';
export let visible;
const wheee = (node, params) => {
return {
duration: params.duration,
css: t => {
const eased = eases.elasticOut(t);
return `
transform: scale(${eased}) rotate(${eased * 1080}deg);
color: hsl(
${~~(t * 360)},
${Math.min(100, 1000 - 1000 * t)}%,
${Math.min(50, 500 - 500 * t)}%
);`
}
};
};
</script>
<input type=checkbox bind:checked={visible}> visible
{#if visible}
<div class="centered" in:wheee="{{duration: 8000}}" out:fade>
<span>wheeee!!!!!</span>
</div>
{/if}
<style>
.centered {
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%,-50%);
}
span {
position: absolute;
transform: translate(-50%,-50%);
font-size: 4em;
}
</style>

@ -0,0 +1,11 @@
<script>
import { fade } from 'svelte-transitions';
export let visible;
</script>
<input type=checkbox bind:checked={visible}> visible
{#if visible}
<p transition:fade>fades in and out</p>
{/if}

@ -0,0 +1,11 @@
<script>
import { fly } from 'svelte-transitions';
export let visible;
</script>
<input type=checkbox bind:checked={visible}> visible
{#if visible}
<p transition:fly="{{y: 200, duration: 1000}}">flies 200 pixels up, slowly</p>
{/if}

@ -0,0 +1,11 @@
<script>
import { fade, fly } from 'svelte-transitions';
export let visible;
</script>
<input type=checkbox bind:checked={visible}> visible
{#if visible}
<p in:fly="{{y: 50}}" out:fade>flies up, fades out</p>
{/if}

@ -0,0 +1,112 @@
---
title: Introduction
---
### What is Svelte?
Svelte is a tool for building fast web applications.
It is similar to JavaScript frameworks such as React and Vue, which share a goal of making it easy to build slick interactive user interfaces.
But there's a crucial difference: Svelte converts your app into ideal JavaScript at *build time*, rather than interpreting your application code at *run time*. This means you don't pay the performance cost of the framework's abstractions, and you don't incur a penalty when your app first loads.
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, written into an `.html` file. Here's a simple example:
```html
<!--{ title: 'Hello world!' }-->
<h1>Hello {name}!</h1>
```
```json
/* { hidden: true } */
{
name: 'world'
}
```
> Wherever you see <strong style="font-weight: 700; font-size: 16px; font-family: Inconsolata, monospace; color: rgba(170,30,30, 0.8)">REPL</strong> 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'),
props: { name: 'world' },
});
// change the component's "name" prop. We'll learn about props (aka properties) below
app.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, Webpack 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 -g 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 ...`

@ -0,0 +1,281 @@
---
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.
### Tags
Tags allow you to bind data to your template. Whenever your data changes (for example after `component.a = 3`), the DOM updates automatically. You can use any JavaScript expression in templates, and it will also automatically update:
```html
<!-- { title: 'Template tags' } -->
<p>{a} + {b} = {a + b}</p>
```
```json
/* { hidden: true } */
{
"a": 1,
"b": 2
}
```
You can also use tags in attributes:
```html
<!-- { title: 'Tags in attributes' } -->
<h1 style="color: {color};">{color}</h1>
<p hidden={hideParagraph}>You can hide this paragraph.</p>
```
```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
<!-- { title: 'Triple tags' } -->
<p>This HTML: {content}</p>
<p>Renders as: {@html content}</p>
```
```json
/* { hidden: true } */
{
content: "Some <b>bold</b> 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
<!-- { repl: false } -->
{#if user.loggedIn}
<a href="/logout">log out</a>
{/if}
{#if !user.loggedIn}
<a href="/login">log in</a>
{/if}
```
You can combine the two blocks above with `{:else}`:
```html
<!-- { repl: false } -->
{#if user.loggedIn}
<a href="/logout">log out</a>
{:else}
<a href="/login">log in</a>
{/if}
```
You can also use `{:elseif ...}`:
```html
<!--{ title: 'If, else and elseif' }-->
{#if x > 10}
<p>{x} is greater than 10</p>
{:elseif 5 > x}
<p>{x} is less than 5</p>
{:else}
<p>{x} is between 5 and 10</p>
{/if}
```
```json
/* { hidden: true } */
{
x: 7
}
```
### Each blocks
Iterate over lists of data:
```html
<!--{ title: 'Each blocks' }-->
<h1>Cats of YouTube</h1>
<ul>
{#each cats as cat}
<li><a target="_blank" href={cat.video}>{cat.name}</a></li>
{:else}
<li>No cats :(</li>
{/each}
</ul>
```
```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
<!--{ title: 'Each block indexes' }-->
<div class="grid">
{#each rows as row, y}
<div class="row">
{#each columns as column, x}
<code class="cell">
{x + 1},{y + 1}:
<strong>{row[column]}</strong>
</code>
{/each}
</div>
{/each}
</div>
```
```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
<!--{ title: 'Each block destructuring' }-->
<h1>It's the cats of YouTube again</h1>
<ul>
{#each cats as {name, video} }
<li><a target="_blank" href={video}>{name}</a></li>
{/each}
</ul>
```
```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"
}
]
}
```
### 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
<!--{ title: 'Await blocks' }-->
<script>
const promise = new Promise(fulfil => {
setTimeout(() => fulfil(42), 3000);
});
</script>
{#await promise}
<p>wait for it...</p>
{:then answer}
<p>the answer is {answer}!</p>
{:catch error}
<p>well that's odd</p>
{/await}
```
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), [transitions](guide#transitions) 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
<!--{ title: 'Element directives' }-->
<p>Count: {count}</p>
<button on:click="{() => count += 1}">+1</button>
```
```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
<!--{ title: 'Debug tags' }-->
<input bind:value={name}>
{@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.

@ -0,0 +1,118 @@
---
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
<!--{ title: 'Scoped styles' }-->
<style>
.foo {
color: red;
font-size: 2em;
font-family: 'Comic Sans MS';
}
</style>
<div class="foo">
Big red Comic Sans
</div>
```
### 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-css) 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:
<!-- TODO `cascade: false` in the REPL -->
```html
<!-- { repl: false } -->
<script>
import Widget from './Widget.html';
</script>
<style>
p {
/* this block will be disregarded, since
there are no <p> elements here */
color: red;
}
div :global(p) {
/* this block will be applied to any <p> elements
inside the <div>, i.e. in <Widget> */
font-weight: bold;
}
</style>
<div>
<Widget/>
</div>
```
> 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 `.bold` is unused in the following code and should be removed:
```html
<!-- { repl: false } -->
<div>
<p bind:this={paragraph}>this text is not bold</p>
</div>
<style>
.bold {
color: bold;
}
</style>
<script>
import { onMount } from 'svelte';
let paragraph;
onMount(() => {
paragraph.classList.add('bold');
});
</script>
```
Instead of manually manipulating the DOM, you should always use the `class` attribute (or the [class directive](https://svelte.technology/guide#classes)):
```html
<!-- { repl: false } -->
<div>
<p class:bold={bold}>this text is bold</p>
</div>
```
If that's impossible for some reason, you can use `:global(...)`:
```html
<!-- { repl: false } -->
<style>
div :global(.bold) {
color: bold;
}
</style>
```
The same applies to the contents of `{@html ...}` tags.

@ -0,0 +1,121 @@
---
title: Behaviours
---
As well as scoped styles and a template, components can encapsulate *behaviours*. For that, we add a `<script>` element:
```html
<!-- { title: 'Behaviours' } -->
<script>
// behaviours go here
</script>
<div>
<!-- template goes here -->
</div>
```
### Internal state
Often, it makes sense for a component to have internal state that isn't visible to the outside world.
```html
<!-- { title: 'Internal state' } -->
<script>
let count = 0;
</script>
<p>Count: {count}</p>
<button on:click="{() => count += 1}">+1</button>
```
### External properties
On the other hand, for the component to form part of a system, it needs to expose certain values so that they can be set from outside. These are called *props*, and we use the `export` keyword to differentiate them from internal state:
```html
<!-- { title: 'External properties' } -->
<script>
export let count = 0;
</script>
<p>Count: {count}</p>
<button on:click="{() => count += 1}">+1</button>
```
> Effectively, we're exporting a *contract* with the outside world. The `export` keyword normally means something different in JavaScript, so you might be surprised to see it used like this. Just roll with it for now!
The `= 0` sets a default value for `count`, if none is provided.
```js
const counter = new Counter({
target: document.body,
props: {
count: 99
}
});
counter.count; // 99
counter.count += 1; // 100
```
Props declared with `const` or `function` are *read-only* — they cannot be set from outside. This allows you to, for example, attach custom methods to your component:
```js
component.doSomethingFun();
```
### Lifecycle hooks
There are four 'hooks' provided by Svelte for adding control logic — `onMount`, `beforeUpdate`, `afterUpdate` and `onDestroy`. Import them directly from `svelte`:
```html
<!-- { title: 'Lifecycle hooks' } -->
<script>
import { onMount, beforeUpdate, afterUpdate, onDestroy } from 'svelte';
beforeUpdate(() => {
// this function is called immediately before
// the component updates to reflect new data
console.log(`beforeUpdate`);
});
afterUpdate(() => {
// this function is called immediately *after*
// the component updates to reflect new data.
// if you need to do anything that assumes the
// DOM is up-to-date — such as measuring the
// size of an element — do it here
console.log(`afterUpdate`);
});
onMount(() => {
// this function is called once, after the
// `afterUpdate` function (if there is one)
// runs for the first time
console.log(`onMount`);
return () => {
// this function runs when the
// component is destroyed
console.log(`onMount cleanup`);
};
});
onDestroy(() => {
// this function runs when the
// component is destroyed
console.log(`onDestroy`);
});
let count = 0;
</script>
<button on:click="{() => count += 1}">
Trigger an update ({count})
</button>
> Lifecycle hooks do *not* run in server-side rendering (SSR) mode, with the exception of `onDestroy`. More on SSR later.

@ -0,0 +1,147 @@
---
title: Nested components
---
As well as containing elements (and `if` blocks and `each` blocks), Svelte components can contain *other* Svelte components.
```html
<!-- { title: 'Nested components' } -->
<script>
import Widget from './Widget.html';
</script>
<div class='widget-container'>
<Widget answer={42}/>
</div>
```
```html
<!--{ filename: 'Widget.html' }-->
<p>I am a nested component. The answer is {answer}</p>
```
That's similar to doing this...
```js
import Widget from './Widget.html';
const widget = new Widget({
target: document.querySelector('.widget-container'),
props: {
answer: 42
}
});
```
...except that Svelte takes care of destroying the child component when the parent is destroyed, and keeps props in sync if they change.
> 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. 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
<!-- { repl: false } -->
<!-- these are equivalent -->
<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
<!-- { title: 'Using <slot>' } -->
<script>
import Box from './Box.html';
</script>
<Box>
<h2>Hello!</h2>
<p>This is a box. It can contain anything.</p>
</Box>
```
```html
<!--{ filename: 'Box.html' }-->
<style>
.box {
border: 2px solid black;
padding: 0.5em;
}
</style>
<div class="box">
<slot><!-- content is injected here --></slot>
</div>
```
The `<slot>` element can contain 'fallback content', which will be used if no children are provided for the component:
```html
<!-- { title: 'Default slot content' } -->
<script>
import Box from './Box.html';
</script>
<Box></Box>
```
```html
<!--{ filename: 'Box.html' }-->
<style>
.box {
border: 2px solid black;
padding: 0.5em;
}
.fallback {
color: #999;
}
</style>
<div class="box">
<slot>
<p class="fallback">the box is empty!</p>
</slot>
</div>
```
You can also have *named* slots. Any elements with a corresponding `slot` attribute will fill these slots:
```html
<!-- { title: 'Named slots' } -->
<script>
import ContactCard from './ContactCard.html';
</script>
<ContactCard>
<span slot="name">P. Sherman</span>
<span slot="address">42 Wallaby Way, Sydney</span>
</ContactCard>
```
```html
<!--{ filename: 'ContactCard.html' }-->
<style>
.contact-card {
border: 2px solid black;
padding: 0.5em;
}
</style>
<div class="contact-card">
<h2><slot name="name"></slot></h2>
<slot name="address">Unknown address</slot>
<br>
<slot name="email">Unknown email</slot>
</div>
```

@ -0,0 +1,137 @@
---
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
<!-- { title: '<svelte:self> tags' } -->
{#if countdown > 0}
<p>{countdown}</p>
<svelte:self countdown="{countdown - 1}"/>
{:else}
<p>liftoff!</p>
{/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
<!-- { title: '<svelte:component> tags' } -->
<script>
import Red from './Red.html';
import Blue from './Blue.html';
let foo = true;
</script>
<input type=checkbox bind:checked={foo}> foo
<svelte:component this="{foo ? Red : Blue}" name="thing"/>
```
```html
<!--{ hidden: true, filename: 'Red.html' }-->
<p style="color: red">Red {name}</p>
```
```html
<!--{ hidden: true, filename: 'Blue.html' }-->
<p style="color: blue">Blue {name}</p>
```
The expression inside the `this="{...}"` can be any valid JavaScript expression.
### `<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
<!-- { title: '<svelte:window> tags' } -->
<svelte:window on:keydown="{e => (key = event.key, keyCode = e.keyCode)}"/>
<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>
{#if key}
<p><kbd>{key === ' ' ? 'Space' : key}</kbd> (code {keyCode})</p>
{:else}
<p>click in this window and press any key</p>
{/if}
```
You can also bind to certain values — so far `innerWidth`, `outerWidth`, `innerHeight`, `outerHeight`, `scrollX`, `scrollY` and `online`:
```html
<!-- { title: '<svelte:window> bindings' } -->
<svelte:window bind:scrollY={y}/>
<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>
<div class="background"></div>
<p class="fixed">user has scrolled {y} pixels</p>
```
### `<svelte:document>`
TODO REPLACE THIS WITH svelte:body
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.svelte.technology) — 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
<!-- { title: '<svelte:head> tags' } -->
<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.

@ -0,0 +1,180 @@
---
title: Events
---
In most applications, you'll need to respond to the user's actions. In Svelte, this is done with the `on:[event]` directive.
### Element events
When used on an element, `on:click={handler}` is equivalent to calling `element.addEventListener('click', handler)`. When the element is removed, Svelte calls `removeEventListener` automatically.
```html
<!-- { title: 'Inline event handlers' } -->
<p>Count: {count}</p>
<button on:click="{() => count += 1}">+1</button>
```
```json
/* { hidden: true } */
{
count: 0
}
```
For more complicated behaviours, you'll probably want to declare an event handler in your `<script>` block:
```html
<!-- { title: 'Event handlers' } -->
<script>
let count = 0;
function incrementOrDecrement(event) {
const d = event.shiftKey
? -1
: +1;
count += d;
}
</script>
<p>Count: {count}</p>
<button on:click={incrementOrDecrement}>update</button>
```
```json
/* { hidden: true } */
{
count: 0
}
```
### Event handler modifiers
While you can invoke methods like `event.stopPropagation` directly...
```html
<!-- { repl: false } -->
<div on:click="{e => e.stopPropagation()}">...</div>
```
...it gets annoying if you want to combine that with some other behaviour:
```html
<!-- { repl: false } -->
<script>
let foo = false;
function toggleFoo(event) {
event.stopPropagation();
event.preventDefault();
foo = !foo;
}
</script>
<div on:click={toggleFoo}>...</div>
```
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 separate event handler:
```html
<!-- { repl: false } -->
<div on:click|stopPropagation|preventDefault="{() => foo = !foo}">...</div>
```
### 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
<!-- { filename: 'CategoryChooser.html', repl: false } -->
<p>Select a category:</p>
{#each categories as category}
<button on:click="fire('select', { category })">select {category}</button>
{/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
<!--{ title: 'Component events' }-->
<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
<!--{ filename: 'CategoryChooser.html', hidden: true }-->
<p>Select a category:</p>
{#each categories as category}
<button on:click="fire('select', { category })">select {category}</button>
{/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
<!-- { repl: false } -->
<!-- these are equivalent -->
<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)"`).

@ -0,0 +1,161 @@
---
title: Bindings
---
### 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
<!-- { repl: false } -->
<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
<!-- { repl: false } -->
<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
<!-- { title: 'Element bindings' } -->
<h1>Hello {name}!</h1>
<input bind:value=name>
```
```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` | `<input>` `<textarea>` `<select>` | <span>Two-way</span> |
| `checked` `indeterminate` | `<input type=checkbox>` | <span>Two-way</span> |
| `group` (see note) | `<input type=checkbox>` `<input type=radio>` | <span>Two-way</span> |
| `currentTime` `paused` `played` `volume` | `<audio>` `<video>` | <span>Two-way</span> |
| `buffered` `duration` `seekable` | `<audio>` `<video>` | <span>One-way</span> |
| `offsetWidth` `offsetHeight` `clientWidth` `clientHeight` | All block-level elements | <span>One-way</span> |
| `scrollX` `scrollY` | `<svelte:window>` | <span>Two-way</span> |
| `online` `innerWidth` `innerHeight` `outerWidth` `outerHeight` | `<svelte:window>` | <span>One-way</span> |
> '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
<!-- { title: 'Form bindings' } -->
<form on:submit="handleSubmit(event)">
<input bind:value=name type=text>
<button type=submit>Say hello</button>
</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).
### bind:this
There's a special binding that exists on all elements and components — `this`. It allows you to store a reference to a DOM node or component instance so that you can interact with it programmatically:
```html
<!-- { title: 'Refs' } -->
<canvas bind:this={canvas} width={200} height={200}></canvas>
<script>
import { onMount } from 'svelte';
import createRenderer from './createRenderer.js';
let canvas;
onMount(() => {
const ctx = canvas.getContext('2d');
const renderer = createRenderer(canvas, ctx);
// stop updating the canvas when
// the component is destroyed
return 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);
}
}
```

@ -0,0 +1,89 @@
---
title: Transitions
---
### Transitions
Transitions allow elements to enter and leave the DOM gracefully, rather than suddenly appearing and disappearing.
```html
<!-- { title: 'Transitions' } -->
<script>
import { fade } from 'svelte/transition.js';
let visible = false;
</script>
<input type=checkbox bind:checked={visible}> visible
{#if visible}
<p transition:fade>fades in and out</p>
{/if}
```
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
<!-- { title: 'Transition with parameters' } -->
<script>
import { fly } from 'svelte-transitions';
let visible = false;
</script>
<input type=checkbox bind:checked={visible}> visible
{#if visible}
<p transition:fly="{{y: 200, duration: 1000}}">flies 200 pixels up, slowly</p>
{/if}
```
An element can have separate `in` and `out` transitions:
```html
<!-- { title: 'Transition in/out' } -->
<script>
import { fade, fly } from 'svelte-transitions';
let visible = false;
</script>
<input type=checkbox bind:checked={visible}> visible
{#if visible}
<p in:fly="{y: 50}" out:fade>flies up, fades out</p>
{/if}
```
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
<!-- { title: 'Fade transition' } -->
<script>
function fade(node, { delay = 0, duration = 400 }) {
const o = +getComputedStyle(node).opacity;
return {
delay,
duration,
css: t => `opacity: ${t * o}`
};
}
let visible = false;
</script>
<input type=checkbox bind:checked={visible}> visible
{#if visible}
<p transition:fade>fades in and out</p>
{/if}
```
> 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.

@ -0,0 +1,103 @@
---
title: Actions
---
### 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. `<img use:lazyload data-src='giant-photo.jpg'/>`
* capturing link clicks for your client router
* adding drag and drop
```html
<!-- { title: 'Actions' } -->
<button on:click={toggleLanguage} use:tooltip={translations[language].tooltip}>
{language}
</button>
<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",
},
}
}
```

@ -0,0 +1,70 @@
---
title: Classes
---
Like any attribute, the `class` attribute can be set using regular JavaScript. Suppose we had an `active` class that we wanted to apply to an element when `isActive` is true — we could do it like this:
```html
<!-- { title: 'Dynamic classes using ternaries' } -->
<script>
let isActive = false;
</script>
<style>
.active {
color: red;
}
</style>
<h1 class="{isActive ? 'active' : ''}">red if active</h1>
<label>
<input type=checkbox bind:checked={isActive}> isActive
</label>
```
That's a little verbose though, so the `class:` directive gives you a simpler way to achieve the same thing:
```html
<!-- { title: 'Dynamic classes using directives' } -->
<script>
let isActive = false;
</script>
<style>
.active {
color: red;
}
</style>
-<h1 class="{isActive ? 'active' : ''}">red if active</h1>
+<h1 class:active={isActive}>red if active</h1>
<label>
<input type=checkbox bind:checked={isActive}> isActive
</label>
```
As with any directive, you can use any JavaScript expression. If it's a variable name that matches the class name, you can use a shorthand:
```html
<!-- { title: 'Dynamic classes using directives' } -->
<script>
- let isActive = false;
+ let active = false;
</script>
<style>
.active {
color: red;
}
</style>
-<h1 class:active={isActive}>red if active</h1>
+<h1 class:active>red if active</h1>
<label>
- <input type=checkbox bind:checked={isActive}> isActive
+ <input type=checkbox bind:checked={active}> active
</label>
```

@ -0,0 +1,67 @@
---
title: Module context
---
So far, our `<script>` tags have been running in the context of a component *instance*. In other words, if you have two components like this...
```html
<!-- { title: 'Counter' } -->
<script>
import Counter from './Counter.html';
</script>
<Counter/>
<Counter/>
```
```html
<!--{ filename: 'Counter.html' }-->
<script>
let count = 0;
</script>
<button on:click="{() => count += 1}">+1</button>
```
...each counter has its own `count` variable. The code runs once per instance.
Occasionally, you want code to run once *per module* instead. For that, we use `context="module"`:
```html
<!-- { title: 'Module context' } -->
<script context="module">
console.log(`this will run once`);
const answer = 42;
</script>
<script>
console.log(`this will run once per instance`);
console.log(`we can 'see' module-level variables like ${answer}`);
</script>
```
> Don't worry about manually hoisting functions from instance context to module context to avoid creating multiple copies of them — Svelte will do that for you
### Module exports
Any named exports from a `context="module"` script become part of the module's static exports. For example, to define a `preload` function for use with [Sapper](https://sapper.svelte.technology):
```html
<!-- { title: 'Module exports', repl: false } -->
<script context="module">
export async function preload({ params }) {
const res = await this.fetch(`/blog/${params.slug}.json`);
return {
post: await res.json()
};
}
</script>
```
```js
import BlogPost, { preload } from './BlogPost.html';
```
You can only have named exports — no `export default` — because the component *is* the default export.

@ -0,0 +1,78 @@
---
title: Server-side rendering
---
So far, we've discussed creating Svelte components *on the client*, which is to say the browser. But you can also render Svelte components in Node.js. This can result in better perceived performance as it means the application starts rendering while the page is still downloading, before any JavaScript executes. It also has SEO advantages in some cases, and can be beneficial for people running older browsers that can't or won't run your JavaScript for whatever reason.
### Using the compiler
If you're using the Svelte compiler, whether directly or via an integration like [rollup-plugin-svelte](https://github.com/rollup/rollup-plugin-svelte) or [svelte-loader](https://github.com/sveltejs/svelte-loader), you can tell it to generate a server-side component by passing the `generate: 'ssr'` option:
```js
const { js } = svelte.compile(source, {
generate: 'ssr' // as opposed to 'dom', the default
});
```
### Registering Svelte
Alternatively, an easy way to use the server-side renderer is to *register* it:
```js
require('svelte/register.js');
```
Now you can `require` your components:
```js
const Thing = require('./components/Thing.html');
```
If you prefer to use a different file extension, you can pass options like so:
```js
require('svelte/register.js')({
extensions: ['.svelte']
});
```
### Server-side API
Components have a different API in Node.js rather than being a constructor that you use with the `new` keyword, a component is an object with a `render(data, options)` method:
```js
require('svelte/register.js');
const Thing = require('./components/Thing.html');
const props = { answer: 42 };
const { html, css, head } = Thing.render(props);
```
[Lifecycle hooks](guide#lifecycle-hooks) will *not* run, with the exception of `onDestroy`, because the component is never 'mounted'.
> The SSR compiler will generate a CommonJS module for each of your components meaning that `import` and `export` statements are converted into their `require` and `module.exports` equivalents. If your components have non-component dependencies, they must also work as CommonJS modules in Node. If you're using ES2015 modules, we recommend the [`esm`](https://github.com/standard-things/esm) module for automatically converting them to CommonJS.
#### Rendering styles
You can also extract any [scoped styles](guide#scoped-styles) that are used by the component or its children:
```js
const { css } = Thing.render(data);
```
You could put the resulting `css` in a separate stylesheet, or include them in the page inside a `<style>` tag. If you do this, you will probably want to prevent the client-side compiler from including the CSS again. For the CLI, use the `--no-css` flag. In build tool integrations like `rollup-plugin-svelte`, pass the `css: false` option.
#### Rendering `<head>` contents
If your component, any of its children, use the `<svelte:head>` [component](guide#-head-tags), you can extract the contents:
```js
const { head } = Thing.render(data);
```

Some files were not shown because too many files have changed in this diff Show More

Loading…
Cancel
Save