mirror of https://github.com/sveltejs/svelte
parent
8d4e514f68
commit
bb41b8626f
@ -0,0 +1,5 @@
|
||||
.DS_Store
|
||||
node_modules
|
||||
yarn-error.log
|
||||
/cypress/screenshots/
|
||||
/__sapper__/
|
@ -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,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,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 `&#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...<br>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,130 @@
|
||||
<!--
|
||||
https://github.com/eugenkiss/7guis/wiki#circle-drawer
|
||||
|
||||
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.
|
||||
-->
|
||||
|
||||
<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(event)' on:contextmenu='adjust(event)'>
|
||||
{#each circles as circle}
|
||||
<circle cx='{circle.cx}' cy='{circle.cy}' r='{circle.r}'
|
||||
on:click='select(circle, event)'
|
||||
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' bind:value='selected.r' on:input='set({ adjusted: true })'>
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
<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.5);
|
||||
}
|
||||
|
||||
input[type='range'] {
|
||||
width: 100%;
|
||||
}
|
||||
</style>
|
||||
|
||||
<script>
|
||||
export default {
|
||||
data() {
|
||||
return {
|
||||
i: 0,
|
||||
undoStack: [[]],
|
||||
adjusting: false,
|
||||
adjusted: false,
|
||||
circles: []
|
||||
};
|
||||
},
|
||||
|
||||
methods: {
|
||||
handleClick(event) {
|
||||
if (this.get().adjusting) {
|
||||
this.set({ adjusting: false });
|
||||
|
||||
// if nothing changed, rewind
|
||||
if (this.get().adjusted) this.push();
|
||||
return;
|
||||
}
|
||||
|
||||
const circle = {
|
||||
cx: event.clientX,
|
||||
cy: event.clientY,
|
||||
r: 50
|
||||
};
|
||||
|
||||
const circles = this.get().circles;
|
||||
circles.push(circle);
|
||||
this.set({ circles, selected: circle });
|
||||
|
||||
this.push();
|
||||
},
|
||||
|
||||
adjust(event) {
|
||||
event.preventDefault();
|
||||
if (!this.get().selected) return;
|
||||
this.set({ adjusting: true, adjusted: false });
|
||||
},
|
||||
|
||||
select(circle, event) {
|
||||
if (!this.get().adjusting) {
|
||||
event.stopPropagation();
|
||||
this.set({ selected: circle });
|
||||
}
|
||||
},
|
||||
|
||||
// undo stack management
|
||||
push() {
|
||||
let { i, undoStack, circles } = this.get();
|
||||
undoStack.splice(++i);
|
||||
undoStack.push(clone(circles));
|
||||
this.set({ i, undoStack });
|
||||
},
|
||||
|
||||
travel(d) {
|
||||
let { i, undoStack } = this.get();
|
||||
const circles = clone(undoStack[i += d]);
|
||||
this.set({ circles, i, adjusting: false });
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
function clone(circles) {
|
||||
return circles.map(({ cx, cy, r }) => ({ cx, cy, r }));
|
||||
}
|
||||
</script>
|
@ -0,0 +1 @@
|
||||
{}
|
@ -0,0 +1,3 @@
|
||||
<!-- https://github.com/eugenkiss/7guis/wiki#counter -->
|
||||
<input type='number' bind:value='count'>
|
||||
<button on:click='set({ count: count + 1 })'>count</button>
|
@ -0,0 +1,3 @@
|
||||
{
|
||||
"count": 0
|
||||
}
|
@ -0,0 +1,112 @@
|
||||
<!-- https://github.com/eugenkiss/7guis/wiki#crud -->
|
||||
<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>
|
||||
|
||||
<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>
|
||||
|
||||
<script>
|
||||
export default {
|
||||
data() {
|
||||
return {
|
||||
prefix: '',
|
||||
first: '',
|
||||
last: '',
|
||||
people: [],
|
||||
selected: null
|
||||
};
|
||||
},
|
||||
|
||||
computed: {
|
||||
selected: ({ filteredPeople, i }) => {
|
||||
return filteredPeople[i];
|
||||
},
|
||||
|
||||
filteredPeople({ people, prefix }) {
|
||||
if (!prefix) return people;
|
||||
|
||||
prefix = prefix.toLowerCase();
|
||||
return people.filter(person => {
|
||||
const name = `${person.last}, ${person.first}`;
|
||||
return name.toLowerCase().startsWith(prefix);
|
||||
});
|
||||
}
|
||||
},
|
||||
|
||||
onstate({ changed, current }) {
|
||||
if (changed.selected && current.selected) {
|
||||
this.set(current.selected);
|
||||
}
|
||||
},
|
||||
|
||||
methods: {
|
||||
create() {
|
||||
const { first, last, people } = this.get();
|
||||
|
||||
people.push({ first, last });
|
||||
|
||||
this.set({
|
||||
people,
|
||||
first: '',
|
||||
last: '',
|
||||
i: people.length - 1
|
||||
});
|
||||
},
|
||||
|
||||
update() {
|
||||
const { first, last, selected, people } = this.get();
|
||||
|
||||
selected.first = first;
|
||||
selected.last = last;
|
||||
|
||||
this.set({ people });
|
||||
},
|
||||
|
||||
remove() {
|
||||
const { people, selected, i } = this.get();
|
||||
const index = people.indexOf(selected);
|
||||
people.splice(index, 1);
|
||||
|
||||
this.set({
|
||||
people,
|
||||
first: '',
|
||||
last: '',
|
||||
i: Math.min(i, people.length - 1)
|
||||
});
|
||||
}
|
||||
}
|
||||
};
|
||||
</script>
|
@ -0,0 +1,16 @@
|
||||
{
|
||||
"people": [
|
||||
{
|
||||
"first": "Hans",
|
||||
"last": "Emil"
|
||||
},
|
||||
{
|
||||
"first": "Max",
|
||||
"last": "Mustermann"
|
||||
},
|
||||
{
|
||||
"first": "Roman",
|
||||
"last": "Tisch"
|
||||
}
|
||||
]
|
||||
}
|
@ -0,0 +1,71 @@
|
||||
<!-- 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>
|
||||
|
||||
<style>
|
||||
select, input, button {
|
||||
display: block;
|
||||
margin: 0.5em 0;
|
||||
font-size: inherit;
|
||||
}
|
||||
</style>
|
||||
|
||||
<script>
|
||||
export default {
|
||||
data() {
|
||||
const tomorrow = new Date(Date.now() + 86400000);
|
||||
|
||||
const tomorrowAsString = [
|
||||
tomorrow.getFullYear(),
|
||||
pad(tomorrow.getMonth() + 1, 2),
|
||||
pad(tomorrow.getDate(), 2)
|
||||
].join('-');
|
||||
|
||||
return {
|
||||
start: tomorrowAsString,
|
||||
end: tomorrowAsString,
|
||||
type: 'oneway'
|
||||
};
|
||||
},
|
||||
|
||||
computed: {
|
||||
startDate: ({ start }) => convertToDate(start),
|
||||
endDate: ({ end }) => convertToDate(end)
|
||||
},
|
||||
|
||||
methods: {
|
||||
bookFlight() {
|
||||
const { startDate, endDate, isReturn } = this.get();
|
||||
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>
|
@ -0,0 +1 @@
|
||||
{}
|
@ -0,0 +1,26 @@
|
||||
<!-- https://github.com/eugenkiss/7guis/wiki#temperature-converter -->
|
||||
<input bind:value='celsius' type='number'> °c =
|
||||
<input bind:value='fahrenheit' type='number'> °f
|
||||
|
||||
<style>
|
||||
input {
|
||||
width: 5em;
|
||||
}
|
||||
</style>
|
||||
|
||||
<script>
|
||||
export default {
|
||||
onstate: function ({ changed, current }) {
|
||||
if (changed.celsius) {
|
||||
this.set({
|
||||
fahrenheit: +(32 + (9 / 5 * current.celsius)).toFixed(1)
|
||||
});
|
||||
}
|
||||
if (changed.fahrenheit) {
|
||||
this.set({
|
||||
celsius: +(5 / 9 * (current.fahrenheit - 32)).toFixed(1)
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
</script>
|
@ -0,0 +1,3 @@
|
||||
{
|
||||
"celsius": 0
|
||||
}
|
@ -0,0 +1,53 @@
|
||||
<!-- https://github.com/eugenkiss/7guis/wiki#timer -->
|
||||
<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='reset()'>reset</button>
|
||||
|
||||
<script>
|
||||
export default {
|
||||
data() {
|
||||
return { elapsed: 0, duration: 5000 };
|
||||
},
|
||||
|
||||
oncreate() {
|
||||
this.reset();
|
||||
|
||||
const update = () => {
|
||||
this.frame = requestAnimationFrame(update);
|
||||
|
||||
const { start, duration } = this.get();
|
||||
const elapsed = window.performance.now() - start;
|
||||
|
||||
if (elapsed > duration) return;
|
||||
|
||||
this.set({ elapsed });
|
||||
};
|
||||
|
||||
update();
|
||||
},
|
||||
|
||||
ondestroy() {
|
||||
if (this.frame) {
|
||||
cancelAnimationFrame(this.frame);
|
||||
}
|
||||
},
|
||||
|
||||
methods: {
|
||||
reset() {
|
||||
this.set({
|
||||
start: window.performance.now()
|
||||
});
|
||||
}
|
||||
}
|
||||
};
|
||||
</script>
|
@ -0,0 +1 @@
|
||||
{}
|
@ -0,0 +1,26 @@
|
||||
<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}
|
||||
|
||||
<script>
|
||||
export default {
|
||||
methods: {
|
||||
findAnswer() {
|
||||
this.set({
|
||||
promise: new Promise(fulfil => {
|
||||
const delay = 1000 + Math.random() * 3000;
|
||||
setTimeout(() => fulfil(42), delay);
|
||||
})
|
||||
});
|
||||
}
|
||||
}
|
||||
};
|
||||
</script>
|
@ -0,0 +1 @@
|
||||
{}
|
@ -0,0 +1,132 @@
|
||||
<svelte:window on:resize='resize()'/>
|
||||
|
||||
<div class='chart'>
|
||||
<h2>US birthrate by year</h2>
|
||||
<svg ref: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 === 20 ? ' per 1,000 population' : ''}</text>
|
||||
</g>
|
||||
{/each}
|
||||
</g>
|
||||
|
||||
<!-- x axis -->
|
||||
<g class='axis x-axis'>
|
||||
{#each points as point, i}
|
||||
<g class='tick tick-{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>
|
||||
|
||||
<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>
|
||||
|
||||
<script>
|
||||
import { scaleLinear } from 'd3-scale';
|
||||
|
||||
var xScale = scaleLinear();
|
||||
var yScale = scaleLinear();
|
||||
|
||||
export default {
|
||||
data: function () {
|
||||
return {
|
||||
padding: { top: 20, right: 15, bottom: 20, left: 25 },
|
||||
height: 200,
|
||||
width: 500,
|
||||
xTicks: [1990, 1995, 2000, 2005, 2010, 2015],
|
||||
yTicks: [0, 5, 10, 15, 20]
|
||||
};
|
||||
},
|
||||
|
||||
helpers: {
|
||||
formatMobile: function (tick) {
|
||||
return "'" + tick % 100;
|
||||
}
|
||||
},
|
||||
|
||||
computed: {
|
||||
barWidth: function ({ xTicks, width, padding }) {
|
||||
var innerWidth = width - (padding.left + padding.right);
|
||||
return innerWidth / xTicks.length;
|
||||
},
|
||||
|
||||
xScale: function ({ padding, width, xTicks }) {
|
||||
return xScale
|
||||
.domain([0, xTicks.length])
|
||||
.range([padding.left, width - padding.right]);
|
||||
},
|
||||
|
||||
yScale: function ({ padding, height, yTicks }) {
|
||||
return yScale
|
||||
.domain([0, Math.max.apply(null, yTicks)])
|
||||
.range([height - padding.bottom, padding.top]);
|
||||
}
|
||||
},
|
||||
|
||||
oncreate() {
|
||||
this.resize();
|
||||
},
|
||||
|
||||
methods: {
|
||||
resize: function () {
|
||||
var bcr = this.refs.svg.getBoundingClientRect();
|
||||
|
||||
this.set({
|
||||
width: bcr.right - bcr.left,
|
||||
height: bcr.bottom - bcr.top
|
||||
});
|
||||
}
|
||||
}
|
||||
};
|
||||
</script>
|
@ -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,3 @@
|
||||
{
|
||||
"selected": ["blue"]
|
||||
}
|
@ -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,4 @@
|
||||
{
|
||||
"a": 5,
|
||||
"b": 5
|
||||
}
|
@ -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,3 @@
|
||||
{
|
||||
"selected": "blue"
|
||||
}
|
@ -0,0 +1,2 @@
|
||||
<input bind:value='name' placeholder='enter your name'>
|
||||
<p>Hello {name || 'stranger'}!</p>
|
@ -0,0 +1,3 @@
|
||||
{
|
||||
"name": ""
|
||||
}
|
@ -0,0 +1,104 @@
|
||||
<svelte:window on:click='seek(event)' on:mousemove='seek(event)'/>
|
||||
|
||||
<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.stopPropagation()'>
|
||||
<img alt='play/pause button' on:click='set({ 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.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>
|
||||
|
||||
<script>
|
||||
function pad(num) {
|
||||
return num < 10 ? '0' + num : num;
|
||||
}
|
||||
|
||||
export default {
|
||||
data() {
|
||||
return { paused: true, t: 0 };
|
||||
},
|
||||
|
||||
computed: {
|
||||
icon: ({ paused }) => {
|
||||
return `https://icon.now.sh/${paused ? 'play' : 'pause'}_circle_filled`;
|
||||
},
|
||||
|
||||
bg: ({ t, d }) => {
|
||||
var p = d ? t / d : 0;
|
||||
var h = 90 + 90 * p;
|
||||
var l = 10 + p * 30;
|
||||
return `hsl(${h},50%,${l}%)`;
|
||||
}
|
||||
},
|
||||
|
||||
helpers: {
|
||||
format: time => {
|
||||
if (isNaN(time)) return '--:--.-';
|
||||
var minutes = Math.floor(time / 60);
|
||||
var seconds = (time % 60).toFixed(1);
|
||||
|
||||
return minutes + ':' + pad(seconds)
|
||||
}
|
||||
},
|
||||
|
||||
methods: {
|
||||
seek(event) {
|
||||
if (event.buttons === 1) {
|
||||
event.preventDefault();
|
||||
var p = event.clientX / window.innerWidth;
|
||||
this.set({ t: p * this.get().d });
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
</script>
|
@ -0,0 +1 @@
|
||||
{}
|
@ -0,0 +1,19 @@
|
||||
<textarea bind:value='markdown' resize='none'></textarea>
|
||||
<div class='output'>{@html marked(markdown)}</div>
|
||||
|
||||
<style>
|
||||
textarea {
|
||||
width: 100%;
|
||||
height: 50%;
|
||||
}
|
||||
</style>
|
||||
|
||||
<script>
|
||||
import marked from 'marked';
|
||||
|
||||
export default {
|
||||
helpers: {
|
||||
marked
|
||||
}
|
||||
};
|
||||
</script>
|
@ -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,66 @@
|
||||
<svelte:window on:hashchange='hashchange()'/>
|
||||
|
||||
<main>
|
||||
{#if item}
|
||||
<Item {item}/>
|
||||
{:elseif page}
|
||||
<List {page}/>
|
||||
{/if}
|
||||
</main>
|
||||
|
||||
<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>
|
||||
|
||||
<script>
|
||||
import List from './List.html';
|
||||
import Item from './Item.html';
|
||||
|
||||
export default {
|
||||
components: { List, Item },
|
||||
|
||||
oncreate() {
|
||||
this.hashchange();
|
||||
},
|
||||
|
||||
methods: {
|
||||
async hashchange() {
|
||||
// the poor man's router!
|
||||
const path = window.location.hash.slice(1);
|
||||
|
||||
if (path.startsWith('/item')) {
|
||||
const id = path.slice(6);
|
||||
const item = await fetch(`https://node-hnapi.herokuapp.com/item/${id}`).then(r => r.json());
|
||||
|
||||
this.set({ item });
|
||||
|
||||
window.scrollTo(0,0);
|
||||
} else if (path.startsWith('/top')) {
|
||||
const page = +path.slice(5);
|
||||
this.set({
|
||||
item: null,
|
||||
page
|
||||
});
|
||||
} else {
|
||||
window.location.hash = '/top/1';
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
</script>
|
@ -0,0 +1,28 @@
|
||||
<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>
|
||||
|
||||
<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>
|
@ -0,0 +1,47 @@
|
||||
<a href='#/top/1' on:click='back(event)'>« 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>
|
||||
|
||||
<style>
|
||||
article {
|
||||
margin: 0 0 1em 0;
|
||||
}
|
||||
|
||||
a {
|
||||
display: block;
|
||||
margin: 0 0 1em 0;
|
||||
}
|
||||
|
||||
h1 {
|
||||
font-size: 1.4em;
|
||||
margin: 0;
|
||||
}
|
||||
</style>
|
||||
|
||||
<script>
|
||||
import Comment from './Comment.html';
|
||||
|
||||
export default {
|
||||
components: { Comment },
|
||||
|
||||
methods: {
|
||||
back(event) {
|
||||
event.preventDefault();
|
||||
window.history.back();
|
||||
}
|
||||
}
|
||||
};
|
||||
</script>
|
@ -0,0 +1,52 @@
|
||||
{#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}
|
||||
|
||||
<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>
|
||||
|
||||
<script>
|
||||
import Summary from './Summary.html';
|
||||
|
||||
const PAGE_SIZE = 20;
|
||||
|
||||
export default {
|
||||
async onstate({ changed, current }) {
|
||||
if (changed.page) {
|
||||
const { page } = current;
|
||||
const items = await fetch(`https://node-hnapi.herokuapp.com/news?page=${page}`).then(r => r.json());
|
||||
|
||||
this.set({
|
||||
items,
|
||||
offset: PAGE_SIZE * (page - 1)
|
||||
});
|
||||
|
||||
window.scrollTo(0,0);
|
||||
}
|
||||
},
|
||||
|
||||
components: {
|
||||
Summary
|
||||
}
|
||||
};
|
||||
</script>
|
@ -0,0 +1,38 @@
|
||||
<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>
|
||||
|
||||
<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>
|
||||
|
||||
<script>
|
||||
export default {
|
||||
computed: {
|
||||
comment_text({ item }) {
|
||||
const c = item.comments_count;
|
||||
return `${c} ${c === 1 ? 'comment' : 'comments'}`;
|
||||
}
|
||||
}
|
||||
};
|
||||
</script>
|
@ -0,0 +1 @@
|
||||
{}
|
@ -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.set({ name: 'everybody' });
|
||||
|
||||
You can also update the data via the JSON
|
||||
editor on this page.
|
||||
-->
|
@ -0,0 +1,3 @@
|
||||
{
|
||||
"name": "world"
|
||||
}
|
@ -0,0 +1,5 @@
|
||||
{#if foo}
|
||||
<p>foo!</p>
|
||||
{:else}
|
||||
<p>not foo!</p>
|
||||
{/if}
|
@ -0,0 +1,3 @@
|
||||
{
|
||||
"foo": true
|
||||
}
|
@ -0,0 +1,48 @@
|
||||
<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}
|
||||
|
||||
<script>
|
||||
import ImmutableTodo from './ImmutableTodo.html';
|
||||
import MutableTodo from './MutableTodo.html';
|
||||
|
||||
export default {
|
||||
immutable: true,
|
||||
|
||||
methods: {
|
||||
toggle(id) {
|
||||
const { todos } = this.get();
|
||||
|
||||
this.set({
|
||||
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;
|
||||
})
|
||||
});
|
||||
}
|
||||
},
|
||||
|
||||
components: { ImmutableTodo, MutableTodo }
|
||||
}
|
||||
</script>
|
@ -0,0 +1,17 @@
|
||||
<!-- the text will flash red whenever
|
||||
the `todo` object changes -->
|
||||
<span ref:span>{todo.text}</span>
|
||||
|
||||
<script>
|
||||
export default {
|
||||
// try commenting this out
|
||||
immutable: true,
|
||||
|
||||
onupdate({ changed, current, previous }) {
|
||||
this.refs.span.style.color = 'red';
|
||||
setTimeout(() => {
|
||||
this.refs.span.style.color = 'black';
|
||||
}, 400);
|
||||
}
|
||||
};
|
||||
</script>
|
@ -0,0 +1,14 @@
|
||||
<span ref:span>{todo.text}</span>
|
||||
|
||||
<script>
|
||||
export default {
|
||||
immutable: false,
|
||||
|
||||
onupdate({ changed, current, previous }) {
|
||||
this.refs.span.style.color = 'red';
|
||||
setTimeout(() => {
|
||||
this.refs.span.style.color = 'black';
|
||||
}, 400);
|
||||
}
|
||||
};
|
||||
</script>
|
@ -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,153 @@
|
||||
<svelte:window on:resize='resize()'/>
|
||||
|
||||
<div class='chart'>
|
||||
<h2>Arctic sea ice minimum</h2>
|
||||
|
||||
<svg ref: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>
|
||||
|
||||
<script>
|
||||
import { scaleLinear } from 'd3-scale';
|
||||
|
||||
const xScale = scaleLinear();
|
||||
const yScale = scaleLinear();
|
||||
|
||||
export default {
|
||||
data() {
|
||||
return {
|
||||
padding: { top: 20, right: 15, bottom: 20, left: 25 },
|
||||
height: 200,
|
||||
width: 500,
|
||||
xTicks: [1980, 1990, 2000, 2010],
|
||||
yTicks: [0, 2, 4, 6, 8],
|
||||
formatMobile(tick) {
|
||||
return "'" + tick % 100;
|
||||
}
|
||||
};
|
||||
},
|
||||
|
||||
computed: {
|
||||
minX: ({ points }) => {
|
||||
return points[0].x;
|
||||
},
|
||||
|
||||
maxX: ({ points }) => {
|
||||
return points[points.length - 1].x;
|
||||
},
|
||||
|
||||
xScale: ({ padding, width, minX, maxX }) => {
|
||||
return xScale
|
||||
.domain([minX, maxX])
|
||||
.range([padding.left, width - padding.right]);
|
||||
},
|
||||
|
||||
yScale: ({ padding, height, yTicks }) => {
|
||||
return yScale
|
||||
.domain([Math.min.apply(null, yTicks), Math.max.apply(null, yTicks)])
|
||||
.range([height - padding.bottom, padding.top]);
|
||||
},
|
||||
|
||||
path: ({ points, xScale, yScale }) => {
|
||||
return 'M' + points
|
||||
.map(function (point, i) {
|
||||
return xScale(point.x) + ',' + yScale(point.y);
|
||||
})
|
||||
.join('L');
|
||||
},
|
||||
|
||||
area: ({ points, xScale, yScale, minX, maxX, path }) => {
|
||||
return path + (
|
||||
'L' + xScale(maxX) + ',' + yScale(0) +
|
||||
'L' + xScale(minX) + ',' + yScale(0) +
|
||||
'Z'
|
||||
);
|
||||
}
|
||||
},
|
||||
|
||||
oncreate() {
|
||||
this.resize();
|
||||
},
|
||||
|
||||
methods: {
|
||||
resize: function () {
|
||||
const { width, height } = this.refs.svg.getBoundingClientRect();
|
||||
this.set({ width, height });
|
||||
}
|
||||
}
|
||||
};
|
||||
</script>
|
@ -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,39 @@
|
||||
<div class='modal-background' on:click='fire("close")'></div>
|
||||
|
||||
<div class='modal'>
|
||||
<slot name='header'></slot>
|
||||
<hr>
|
||||
<slot></slot>
|
||||
<hr>
|
||||
|
||||
<button on:click='fire("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,3 @@
|
||||
{
|
||||
"showModal": true
|
||||
}
|
@ -0,0 +1,12 @@
|
||||
<p>This is a top-level element.</p>
|
||||
<Nested/>
|
||||
|
||||
<script>
|
||||
import Nested from './Nested.html';
|
||||
|
||||
export default {
|
||||
components: {
|
||||
Nested
|
||||
}
|
||||
};
|
||||
</script>
|
@ -0,0 +1 @@
|
||||
<p>And this is a nested component.</p>
|
@ -0,0 +1 @@
|
||||
{}
|
@ -0,0 +1,72 @@
|
||||
<!-- 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 @@
|
||||
{}
|
@ -0,0 +1,29 @@
|
||||
<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>
|
||||
|
||||
<script>
|
||||
import Scatterplot from './Scatterplot.html';
|
||||
|
||||
export default {
|
||||
components: {
|
||||
Scatterplot
|
||||
}
|
||||
};
|
||||
</script>
|
@ -0,0 +1,116 @@
|
||||
<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>
|
||||
|
||||
<script>
|
||||
import { scaleLinear } from 'd3-scale';
|
||||
|
||||
const xScale = scaleLinear();
|
||||
const yScale = scaleLinear();
|
||||
|
||||
export default {
|
||||
data() {
|
||||
return {
|
||||
padding: { top: 20, right: 40, bottom: 40, left: 25 },
|
||||
height: 200,
|
||||
width: 500,
|
||||
xTicks: [0, 4, 8, 12, 16, 20],
|
||||
yTicks: [0, 2, 4, 6, 8, 10, 12]
|
||||
};
|
||||
},
|
||||
|
||||
computed: {
|
||||
xTicks: ({ width }) => {
|
||||
return width > 180 ?
|
||||
[0, 4, 8, 12, 16, 20] :
|
||||
[0, 10, 20];
|
||||
},
|
||||
|
||||
yTicks: ({ height }) => {
|
||||
return height > 180 ?
|
||||
[0, 2, 4, 6, 8, 10, 12] :
|
||||
[0, 4, 8, 12];
|
||||
},
|
||||
|
||||
xScale: ({ padding, width }) => {
|
||||
return xScale
|
||||
.domain([0, 20])
|
||||
.range([padding.left, width - padding.right]);
|
||||
},
|
||||
|
||||
yScale: ({ padding, height }) => {
|
||||
return yScale
|
||||
.domain([0, 12])
|
||||
.range([height - padding.bottom, padding.top]);
|
||||
}
|
||||
},
|
||||
|
||||
oncreate() {
|
||||
this.resize();
|
||||
},
|
||||
|
||||
methods: {
|
||||
resize() {
|
||||
const { width, height } = this.refs.svg.getBoundingClientRect();
|
||||
this.set({ width, height });
|
||||
}
|
||||
}
|
||||
};
|
||||
</script>
|
@ -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 @@
|
||||
{}
|
@ -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"
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
After Width: | Height: | Size: 1.6 KiB |
@ -0,0 +1 @@
|
||||
{}
|
@ -0,0 +1,50 @@
|
||||
<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>
|
||||
|
||||
<script>
|
||||
import * as eases from 'eases-jsnext';
|
||||
import { fade } from 'svelte-transitions';
|
||||
|
||||
export default {
|
||||
transitions: {
|
||||
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)}%
|
||||
);`
|
||||
}
|
||||
};
|
||||
},
|
||||
|
||||
fade
|
||||
}
|
||||
};
|
||||
</script>
|
@ -0,0 +1 @@
|
||||
{}
|
@ -0,0 +1,13 @@
|
||||
<input type='checkbox' bind:checked=visible> visible
|
||||
|
||||
{#if visible}
|
||||
<p transition:fade>fades in and out</p>
|
||||
{/if}
|
||||
|
||||
<script>
|
||||
import { fade } from 'svelte-transitions';
|
||||
|
||||
export default {
|
||||
transitions: { fade }
|
||||
};
|
||||
</script>
|
@ -0,0 +1 @@
|
||||
{}
|
@ -0,0 +1,13 @@
|
||||
<input type='checkbox' bind:checked=visible> visible
|
||||
|
||||
{#if visible}
|
||||
<p transition:fly='{y: 200, duration: 1000}'>flies 200 pixels up, slowly</p>
|
||||
{/if}
|
||||
|
||||
<script>
|
||||
import { fly } from 'svelte-transitions';
|
||||
|
||||
export default {
|
||||
transitions: { fly }
|
||||
};
|
||||
</script>
|
@ -0,0 +1 @@
|
||||
{}
|
@ -0,0 +1,13 @@
|
||||
<input type='checkbox' bind:checked=visible> visible
|
||||
|
||||
{#if visible}
|
||||
<p in:fly='{y: 50}' out:fade>flies up, fades out</p>
|
||||
{/if}
|
||||
|
||||
<script>
|
||||
import { fade, fly } from 'svelte-transitions';
|
||||
|
||||
export default {
|
||||
transitions: { fade, fly }
|
||||
};
|
||||
</script>
|
@ -0,0 +1 @@
|
||||
{}
|
@ -0,0 +1,224 @@
|
||||
---
|
||||
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' } -->
|
||||
<div class='widget-container'>
|
||||
<Widget/>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
import Widget from './Widget.html';
|
||||
|
||||
export default {
|
||||
components: {
|
||||
Widget
|
||||
}
|
||||
};
|
||||
</script>
|
||||
```
|
||||
|
||||
```html
|
||||
<!--{ filename: 'Widget.html' }-->
|
||||
<p>I am a nested component</p>
|
||||
```
|
||||
|
||||
That's similar to doing this...
|
||||
|
||||
```js
|
||||
import Widget from './Widget.html';
|
||||
|
||||
const widget = new Widget({
|
||||
target: document.querySelector('.widget-container')
|
||||
});
|
||||
```
|
||||
|
||||
...except that Svelte takes care of destroying the child component when the parent is destroyed, and keeps the two components in sync with *props*.
|
||||
|
||||
> Component names must be capitalised, following the widely-used JavaScript convention of capitalising constructor names. It's also an easy way to distinguish components from elements in your template.
|
||||
|
||||
|
||||
### Props
|
||||
|
||||
Props, short for 'properties', are the means by which you pass data down from a parent to a child component — in other words, they're just like attributes on an element:
|
||||
|
||||
```html
|
||||
<!--{ title: 'Props' }-->
|
||||
<div class='widget-container'>
|
||||
<Widget foo bar="static" baz={dynamic}/>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
import Widget from './Widget.html';
|
||||
|
||||
export default {
|
||||
components: {
|
||||
Widget
|
||||
}
|
||||
};
|
||||
</script>
|
||||
```
|
||||
|
||||
```html
|
||||
<!--{ filename: 'Widget.html' }-->
|
||||
<p>foo: {foo}</p>
|
||||
<p>bar: {bar}</p>
|
||||
<p>baz: {baz}</p>
|
||||
```
|
||||
|
||||
```json
|
||||
/* { hidden: true } */
|
||||
{
|
||||
dynamic: 'try changing this text'
|
||||
}
|
||||
```
|
||||
|
||||
As with element attributes, prop values can contain any valid JavaScript expression.
|
||||
|
||||
Often, the name of the property will be the same as the value, in which case we can use a shorthand:
|
||||
|
||||
```html
|
||||
<!-- { 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>' } -->
|
||||
<Box>
|
||||
<h2>Hello!</h2>
|
||||
<p>This is a box. It can contain anything.</p>
|
||||
</Box>
|
||||
|
||||
<script>
|
||||
import Box from './Box.html';
|
||||
|
||||
export default {
|
||||
components: { Box }
|
||||
};
|
||||
</script>
|
||||
```
|
||||
|
||||
```html
|
||||
<!--{ filename: 'Box.html' }-->
|
||||
<div class="box">
|
||||
<slot><!-- content is injected here --></slot>
|
||||
</div>
|
||||
|
||||
<style>
|
||||
.box {
|
||||
border: 2px solid black;
|
||||
padding: 0.5em;
|
||||
}
|
||||
</style>
|
||||
```
|
||||
|
||||
The `<slot>` element can contain 'fallback content', which will be used if no children are provided for the component:
|
||||
|
||||
```html
|
||||
<!-- { title: 'Default slot content' } -->
|
||||
<Box></Box>
|
||||
|
||||
<script>
|
||||
import Box from './Box.html';
|
||||
|
||||
export default {
|
||||
components: { Box }
|
||||
};
|
||||
</script>
|
||||
```
|
||||
|
||||
```html
|
||||
<!--{ filename: 'Box.html' }-->
|
||||
<div class="box">
|
||||
<slot>
|
||||
<p class="fallback">the box is empty!</p>
|
||||
</slot>
|
||||
</div>
|
||||
|
||||
<style>
|
||||
.box {
|
||||
border: 2px solid black;
|
||||
padding: 0.5em;
|
||||
}
|
||||
|
||||
.fallback {
|
||||
color: #999;
|
||||
}
|
||||
</style>
|
||||
```
|
||||
|
||||
You can also have *named* slots. Any elements with a corresponding `slot` attribute will fill these slots:
|
||||
|
||||
```html
|
||||
<!-- { title: 'Named slots' } -->
|
||||
<ContactCard>
|
||||
<span slot="name">P. Sherman</span>
|
||||
<span slot="address">42 Wallaby Way, Sydney</span>
|
||||
</ContactCard>
|
||||
|
||||
<script>
|
||||
import ContactCard from './ContactCard.html';
|
||||
|
||||
export default {
|
||||
components: { ContactCard }
|
||||
};
|
||||
</script>
|
||||
```
|
||||
|
||||
```html
|
||||
<!--{ filename: 'ContactCard.html' }-->
|
||||
<div class="contact-card">
|
||||
<h2><slot name="name"></slot></h2>
|
||||
<slot name="address">Unknown address</slot>
|
||||
<br>
|
||||
<slot name="email">Unknown email</slot>
|
||||
</div>
|
||||
|
||||
<style>
|
||||
.contact-card {
|
||||
border: 2px solid black;
|
||||
padding: 0.5em;
|
||||
}
|
||||
</style>
|
||||
```
|
||||
|
||||
|
||||
### Shorthand imports
|
||||
|
||||
As an alternative to using an `import` declaration...
|
||||
|
||||
```html
|
||||
<!-- { repl: false } -->
|
||||
<script>
|
||||
import Widget from './Widget.html';
|
||||
|
||||
export default {
|
||||
components: { Widget }
|
||||
};
|
||||
</script>
|
||||
```
|
||||
|
||||
...you can write this:
|
||||
|
||||
```html
|
||||
<!-- { repl: false } -->
|
||||
<script>
|
||||
export default {
|
||||
components: {
|
||||
Widget: './Widget.html'
|
||||
}
|
||||
};
|
||||
</script>
|
||||
```
|
@ -0,0 +1,621 @@
|
||||
---
|
||||
title: Directives
|
||||
---
|
||||
|
||||
Directives are element or component-level instructions to Svelte. They look like attributes, except with a `:` character.
|
||||
|
||||
### Event handlers
|
||||
|
||||
In most applications, you'll need to respond to the user's actions. In Svelte, this is done with the `on:[event]` directive.
|
||||
|
||||
```html
|
||||
<!-- { title: 'Event handlers' } -->
|
||||
<p>Count: {count}</p>
|
||||
<button on:click="set({ count: count + 1 })">+1</button>
|
||||
```
|
||||
|
||||
```json
|
||||
/* { hidden: true } */
|
||||
{
|
||||
count: 0
|
||||
}
|
||||
```
|
||||
|
||||
When the user clicks the button, Svelte calls `component.set(...)` with the provided arguments. You can call any method belonging to the component (whether [built-in](guide#component-api) or [custom](guide#custom-methods)), and any data property (or computed property) that's in scope:
|
||||
|
||||
```html
|
||||
<!-- { title: 'Calling custom methods' } -->
|
||||
<p>Select a category:</p>
|
||||
|
||||
{#each categories as category}
|
||||
<button on:click="select(category)">select {category}</button>
|
||||
{/each}
|
||||
|
||||
<script>
|
||||
export default {
|
||||
data() {
|
||||
return {
|
||||
categories: [
|
||||
'animal',
|
||||
'vegetable',
|
||||
'mineral'
|
||||
]
|
||||
}
|
||||
},
|
||||
|
||||
methods: {
|
||||
select(name) {
|
||||
alert(`selected ${name}`); // seriously, please don't do this
|
||||
}
|
||||
}
|
||||
};
|
||||
</script>
|
||||
```
|
||||
|
||||
You can also access the `event` object in the method call:
|
||||
|
||||
```html
|
||||
<!-- { title: 'Accessing `event`' } -->
|
||||
<div on:mousemove="set({ x: event.clientX, y: event.clientY })">
|
||||
coords: {x},{y}
|
||||
</div>
|
||||
|
||||
<style>
|
||||
div {
|
||||
border: 1px solid purple;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
}
|
||||
</style>
|
||||
```
|
||||
|
||||
The target node can be referenced as `this`, meaning you can do this sort of thing:
|
||||
|
||||
```html
|
||||
<!-- { title: 'Calling node methods' } -->
|
||||
<input on:focus="this.select()" value="click to select">
|
||||
```
|
||||
|
||||
### Custom events
|
||||
|
||||
You can define your own custom events to handle complex user interactions like dragging and swiping. See the earlier section on [custom event handlers](guide#custom-event-handlers) for more information.
|
||||
|
||||
### Component events
|
||||
|
||||
Events are an excellent way for [nested components](guide#nested-components) to communicate with their parents. Let's revisit our earlier example, but turn it into a `<CategoryChooser>` component:
|
||||
|
||||
```html
|
||||
<!-- { 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)"`).
|
||||
|
||||
### Refs
|
||||
|
||||
Refs are a convenient way to store a reference to particular DOM nodes or components. Declare a ref with `ref:[name]`, and access it inside your component's methods with `this.refs.[name]`:
|
||||
|
||||
```html
|
||||
<!-- { title: 'Refs' } -->
|
||||
<canvas ref:canvas width=200 height=200></canvas>
|
||||
|
||||
<script>
|
||||
import createRenderer from './createRenderer.js';
|
||||
|
||||
export default {
|
||||
oncreate() {
|
||||
const canvas = this.refs.canvas;
|
||||
const ctx = canvas.getContext('2d');
|
||||
|
||||
const renderer = createRenderer(canvas, ctx);
|
||||
this.on('destroy', renderer.stop);
|
||||
}
|
||||
}
|
||||
</script>
|
||||
```
|
||||
|
||||
```js
|
||||
/* { filename: 'createRenderer.js', hidden: true } */
|
||||
export default function createRenderer(canvas, ctx) {
|
||||
let running = true;
|
||||
loop();
|
||||
|
||||
return {
|
||||
stop: () => {
|
||||
running = false;
|
||||
}
|
||||
};
|
||||
|
||||
function loop() {
|
||||
if (!running) return;
|
||||
requestAnimationFrame(loop);
|
||||
|
||||
const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
|
||||
|
||||
for (let p = 0; p < imageData.data.length; p += 4) {
|
||||
const i = p / 4;
|
||||
const x = i % canvas.width;
|
||||
const y = i / canvas.height >>> 0;
|
||||
|
||||
const t = window.performance.now();
|
||||
|
||||
const r = 64 + (128 * x / canvas.width) + (64 * Math.sin(t / 1000));
|
||||
const g = 64 + (128 * y / canvas.height) + (64 * Math.cos(t / 1000));
|
||||
const b = 128;
|
||||
|
||||
imageData.data[p + 0] = r;
|
||||
imageData.data[p + 1] = g;
|
||||
imageData.data[p + 2] = b;
|
||||
imageData.data[p + 3] = 255;
|
||||
}
|
||||
|
||||
ctx.putImageData(imageData, 0, 0);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
> Since only one element or component can occupy a given `ref`, don't use them in `{#each ...}` blocks. It's fine to use them in `{#if ...}` blocks however.
|
||||
|
||||
Note that you can use refs in your `<style>` blocks — see [Special selectors](guide#special-selectors).
|
||||
|
||||
|
||||
### Transitions
|
||||
|
||||
Transitions allow elements to enter and leave the DOM gracefully, rather than suddenly appearing and disappearing.
|
||||
|
||||
```html
|
||||
<!-- { title: 'Transitions' } -->
|
||||
<input type=checkbox bind:checked=visible> visible
|
||||
|
||||
{#if visible}
|
||||
<p transition:fade>fades in and out</p>
|
||||
{/if}
|
||||
|
||||
<script>
|
||||
import { fade } from 'svelte-transitions';
|
||||
|
||||
export default {
|
||||
transitions: { fade }
|
||||
};
|
||||
</script>
|
||||
```
|
||||
|
||||
Transitions can have parameters — typically `delay` and `duration`, but often others, depending on the transition in question. For example, here's the `fly` transition from the [svelte-transitions](https://github.com/sveltejs/svelte-transitions) package:
|
||||
|
||||
```html
|
||||
<!-- { title: 'Transition with parameters' } -->
|
||||
<input type=checkbox bind:checked=visible> visible
|
||||
|
||||
{#if visible}
|
||||
<p transition:fly="{y: 200, duration: 1000}">flies 200 pixels up, slowly</p>
|
||||
{/if}
|
||||
|
||||
<script>
|
||||
import { fly } from 'svelte-transitions';
|
||||
|
||||
export default {
|
||||
transitions: { fly }
|
||||
};
|
||||
</script>
|
||||
```
|
||||
|
||||
An element can have separate `in` and `out` transitions:
|
||||
|
||||
```html
|
||||
<!-- { title: 'Transition in/out' } -->
|
||||
<input type=checkbox bind:checked=visible> visible
|
||||
|
||||
{#if visible}
|
||||
<p in:fly="{y: 50}" out:fade>flies up, fades out</p>
|
||||
{/if}
|
||||
|
||||
<script>
|
||||
import { fade, fly } from 'svelte-transitions';
|
||||
|
||||
export default {
|
||||
transitions: { fade, fly }
|
||||
};
|
||||
</script>
|
||||
```
|
||||
|
||||
Transitions are simple functions that take a `node` and any provided `parameters` and return an object with the following properties:
|
||||
|
||||
* `duration` — how long the transition takes in milliseconds
|
||||
* `delay` — milliseconds before the transition starts
|
||||
* `easing` — an [easing function](https://github.com/rollup/eases-jsnext)
|
||||
* `css` — a function that accepts an argument `t` between 0 and 1 and returns the styles that should be applied at that moment
|
||||
* `tick` — a function that will be called on every frame, with the same `t` argument, while the transition is in progress
|
||||
|
||||
Of these, `duration` is required, as is *either* `css` or `tick`. The rest are optional. Here's how the `fade` transition is implemented, for example:
|
||||
|
||||
```html
|
||||
<!-- { title: 'Fade transition' } -->
|
||||
<input type=checkbox bind:checked=visible> visible
|
||||
|
||||
{#if visible}
|
||||
<p transition:fade>fades in and out</p>
|
||||
{/if}
|
||||
|
||||
<script>
|
||||
export default {
|
||||
transitions: {
|
||||
fade(node, { delay = 0, duration = 400 }) {
|
||||
const o = +getComputedStyle(node).opacity;
|
||||
|
||||
return {
|
||||
delay,
|
||||
duration,
|
||||
css: t => `opacity: ${t * o}`
|
||||
};
|
||||
}
|
||||
}
|
||||
};
|
||||
</script>
|
||||
```
|
||||
|
||||
> If the `css` option is used, Svelte will create a CSS animation that runs efficiently off the main thread. Therefore if you can achieve an effect using `css` rather than `tick`, you should.
|
||||
|
||||
|
||||
### Bindings
|
||||
|
||||
As we've seen, data can be passed down to elements and components with attributes and [props](guide#props). Occasionally, you need to get data back up; for that we use bindings.
|
||||
|
||||
|
||||
#### Component bindings
|
||||
|
||||
Component bindings keep values in sync between a parent and a child:
|
||||
|
||||
```html
|
||||
<!-- { 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` | `<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"
|
||||
}
|
||||
```
|
||||
|
||||
### 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",
|
||||
},
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Classes
|
||||
|
||||
Classes let you toggle element classes on and off. To use classes add the directive `class` followed by a colon and the class name you want toggled (`class:the-class-name="anExpression"`). The expression inside the directive's quotes will be evaluated and toggle the class on and off depending on the truthiness of the expression's result. You can only add class directives to elements.
|
||||
|
||||
This example adds the class `active` to `<li>` elements when the `url` property matches the path their links target.
|
||||
|
||||
```html
|
||||
<!-- { title: 'Classes' } -->
|
||||
<ul class="links">
|
||||
<li class:active="url === '/'"><a href="/" on:click="goto(event)">Home</a></li>
|
||||
<li class:active="url.startsWith('/blog')"><a href="/blog/" on:click="goto(event)">Blog</a></li>
|
||||
<li class:active="url.startsWith('/about')"><a href="/about/" on:click="goto(event)">About</a></li>
|
||||
</ul>
|
||||
|
||||
<script>
|
||||
export default {
|
||||
methods: {
|
||||
goto(event) {
|
||||
event.preventDefault();
|
||||
this.set({ url: event.target.pathname });
|
||||
}
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<style>
|
||||
.links {
|
||||
list-style: none;
|
||||
}
|
||||
.links li {
|
||||
float: left;
|
||||
padding: 10px;
|
||||
}
|
||||
/* classes added this way are processed with encapsulated styles, no need for :global() */
|
||||
.active {
|
||||
background: #eee;
|
||||
}
|
||||
</style>
|
||||
```
|
||||
|
||||
```json
|
||||
/* { hidden: true } */
|
||||
{
|
||||
"url": "/"
|
||||
}
|
||||
```
|
||||
|
||||
Classes will work with an existing class attribute on your element. If you find yourself adding multiple ternary statements inside a class attribute, classes can simplify your component. Classes are recognized by the compiler and <a href="guide#scoped-styles">scoped correctly</a>.
|
||||
|
||||
If your class name is the same as a property in your component's state, you can use the shorthand of a class binding which drops the expression (`class:myProp`).
|
||||
|
||||
Note that class names with dashes in them do not usually make good shorthand classes since the property will also need a dash in it. The example below uses a computed property to make working with this easier, but it may be easier to not use the shorthand in cases like this.
|
||||
|
||||
```html
|
||||
<!-- { title: 'Classes shorthand' } -->
|
||||
<div class:active class:is-selected class:isAdmin>
|
||||
<p>Active? {active}</p>
|
||||
<p>Selected? {isSelected}</p>
|
||||
</div>
|
||||
<button on:click="set({ active: !active })">Toggle Active</button>
|
||||
<button on:click="set({ isSelected: !isSelected })">Toggle Selected</button>
|
||||
<button on:click="set({ isAdmin: !isAdmin })">Toggle Admin</button>
|
||||
|
||||
<script>
|
||||
export default {
|
||||
computed: {
|
||||
// Because shorthand relfects the var name, you must use component.set({ "is-selected": true }) or use a computed
|
||||
// property like this. It might be better to avoid shorthand for class names which are not valid variable names.
|
||||
"is-selected": ({ isSelected }) => isSelected
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<style>
|
||||
div {
|
||||
width: 300px;
|
||||
border: 1px solid #ccc;
|
||||
background: #eee;
|
||||
margin-bottom: 10px;
|
||||
}
|
||||
.active {
|
||||
background: #fff;
|
||||
}
|
||||
.is-selected {
|
||||
border-color: #99bbff;
|
||||
box-shadow: 0 0 6px #99bbff;
|
||||
}
|
||||
.isAdmin {
|
||||
outline: 2px solid red;
|
||||
}
|
||||
</style>
|
||||
```
|
||||
|
||||
```json
|
||||
/* { hidden: true } */
|
||||
{
|
||||
"active": true,
|
||||
"isSelected": false,
|
||||
"isAdmin": false,
|
||||
}
|
||||
```
|
@ -0,0 +1,99 @@
|
||||
---
|
||||
title: Plugins
|
||||
---
|
||||
|
||||
Svelte can be extended with plugins and extra methods.
|
||||
|
||||
### Transition plugins
|
||||
|
||||
The [svelte-transitions](https://github.com/sveltejs/svelte-transitions) package includes a selection of officially supported transition plugins, such as [fade](https://github.com/sveltejs/svelte-transitions-fade), [fly](https://github.com/sveltejs/svelte-transitions-fly) and [slide](https://github.com/sveltejs/svelte-transitions-slide). You can include them in a component like so:
|
||||
|
||||
```html
|
||||
<!-- { title: 'svelte-transitions' } -->
|
||||
<label>
|
||||
<input type=checkbox bind:checked=visible> visible
|
||||
</label>
|
||||
|
||||
{#if visible}
|
||||
<!-- use `in`, `out`, or `transition` (bidirectional) -->
|
||||
<div transition:fly="{y:20}">hello!</div>
|
||||
{/if}
|
||||
|
||||
<script>
|
||||
import { fly } from 'svelte-transitions';
|
||||
|
||||
export default {
|
||||
transitions: { fly }
|
||||
};
|
||||
</script>
|
||||
```
|
||||
|
||||
```json
|
||||
/* { hidden: true } */
|
||||
{
|
||||
visible: true
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
### Extra methods
|
||||
|
||||
The [svelte-extras](https://github.com/sveltejs/svelte-extras) package includes a handful of methods for tweening (animating), manipulating arrays and so on.
|
||||
|
||||
```html
|
||||
<!-- { title: 'svelte-extras' } -->
|
||||
<input bind:value=newTodo placeholder="buy milk">
|
||||
<button on:click="push('todos', newTodo)">add todo</button>
|
||||
|
||||
<ul>
|
||||
{#each todos as todo, i}
|
||||
<li>
|
||||
<button on:click="splice('todos', i, 1)">x</button>
|
||||
{todo}
|
||||
</li>
|
||||
{/each}
|
||||
</ul>
|
||||
|
||||
<style>
|
||||
ul {
|
||||
list-style: none;
|
||||
padding: 0;
|
||||
}
|
||||
|
||||
li button {
|
||||
color: rgb(200,0,0);
|
||||
background: rgba(200,0,0,0.1);
|
||||
border-color: rgba(200,0,0,0.2);
|
||||
padding: 0.2em 0.5em;
|
||||
}
|
||||
</style>
|
||||
|
||||
<script>
|
||||
import { push, splice } from 'svelte-extras';
|
||||
|
||||
export default {
|
||||
data() {
|
||||
return {
|
||||
newTodo: '',
|
||||
todos: []
|
||||
};
|
||||
},
|
||||
|
||||
methods: {
|
||||
push,
|
||||
splice
|
||||
}
|
||||
};
|
||||
</script>
|
||||
```
|
||||
|
||||
```json
|
||||
/* { hidden: true } */
|
||||
{
|
||||
todos: [
|
||||
"wash the car",
|
||||
"take the dog for a walk",
|
||||
"mow the lawn"
|
||||
]
|
||||
}
|
||||
```
|
@ -0,0 +1,37 @@
|
||||
---
|
||||
title: Static properties
|
||||
---
|
||||
|
||||
|
||||
### Setup
|
||||
|
||||
In some situations, you might want to add static properties to your component constructor. For that, we use the `setup` property:
|
||||
|
||||
```html
|
||||
<!-- { title: 'Component setup' } -->
|
||||
<p>check the console!</p>
|
||||
|
||||
<script>
|
||||
export default {
|
||||
setup(MyComponent) {
|
||||
// someone importing this component will be able
|
||||
// to access any properties or methods defined here:
|
||||
//
|
||||
// import MyComponent from './MyComponent.html';
|
||||
// console.log(MyComponent.ANSWER); // 42
|
||||
MyComponent.ANSWER = 42;
|
||||
},
|
||||
|
||||
oncreate() {
|
||||
console.log('the answer is', this.constructor.ANSWER);
|
||||
console.dir(this.constructor);
|
||||
}
|
||||
};
|
||||
</script>
|
||||
```
|
||||
|
||||
### preload
|
||||
|
||||
If your component definition includes a `preload` function, it will be attached to the component constructor as a static method. It doesn't change the behaviour of your component in any way — instead, it's a convention that allows systems like [Sapper](https://sapper.svelte.technology) to delay rendering of a component until its data is ready.
|
||||
|
||||
See the section on [preloading](https://sapper.svelte.technology/guide#preloading) in the Sapper docs for more information.
|
@ -0,0 +1,304 @@
|
||||
---
|
||||
title: State management
|
||||
---
|
||||
|
||||
Svelte components have built-in state management via the `get` and `set` methods. But as your application grows beyond a certain size, you may find that passing data between components becomes laborious.
|
||||
|
||||
For example, you might have an `<Options>` component inside a `<Sidebar>` component that allows the user to control the behaviour of a `<MainView>` component. You could use bindings or events to 'send' information up from `<Options>` through `<Sidebar>` to a common ancestor — say `<App>` — which would then have the responsibility of sending it back down to `<MainView>`. But that's cumbersome, especially if you decide you want to break `<MainView>` up into a set of smaller components.
|
||||
|
||||
Instead, a popular solution to this problem is to use a *global store* of data that cuts across your component hierarchy. React has [Redux](https://redux.js.org/) and [MobX](https://mobx.js.org/index.html) (though these libraries can be used anywhere, including with Svelte), and Vue has [Vuex](https://vuex.vuejs.org/en/).
|
||||
|
||||
Svelte has `Store`. `Store` can be used in any JavaScript app, but it's particularly well-suited to Svelte apps.
|
||||
|
||||
|
||||
### The basics
|
||||
|
||||
Import `Store` from `svelte/store.js` (remember to include the curly braces, as it's a *named import*), then create a new store with some (optional) data:
|
||||
|
||||
```js
|
||||
import { Store } from 'svelte/store.js';
|
||||
|
||||
const store = new Store({
|
||||
name: 'world'
|
||||
});
|
||||
```
|
||||
|
||||
Each instance of `Store` has `get`, `set`, `on` and `fire` methods that behave identically to their counterparts on a Svelte component:
|
||||
|
||||
```js
|
||||
const { name } = store.get(); // 'world'
|
||||
|
||||
store.on('state', ({ current }) => {
|
||||
console.log(`hello ${current.name}`);
|
||||
});
|
||||
|
||||
store.set({ name: 'everybody' }); // 'hello everybody'
|
||||
```
|
||||
|
||||
|
||||
|
||||
### Creating components with stores
|
||||
|
||||
Let's adapt our [very first example](guide#understanding-svelte-components):
|
||||
|
||||
```html
|
||||
<!-- { repl: false } -->
|
||||
<h1>Hello {$name}!</h1>
|
||||
<Greeting/>
|
||||
|
||||
<script>
|
||||
import Greeting from './Greeting.html';
|
||||
|
||||
export default {
|
||||
components: { Greeting }
|
||||
};
|
||||
</script>
|
||||
```
|
||||
|
||||
```html
|
||||
<!--{ filename: 'Greeting.html' }-->
|
||||
<p>It's nice to see you, {$name}</p>
|
||||
```
|
||||
|
||||
```js
|
||||
/* { filename: 'main.js' } */
|
||||
import App from './App.html';
|
||||
import { Store } from 'svelte/store.js';
|
||||
|
||||
const store = new Store({
|
||||
name: 'world'
|
||||
});
|
||||
|
||||
const app = new App({
|
||||
target: document.querySelector('main'),
|
||||
store
|
||||
});
|
||||
|
||||
window.store = store; // useful for debugging!
|
||||
```
|
||||
|
||||
There are three important things to notice:
|
||||
|
||||
* We're passing `store` to `new App(...)` instead of `data`
|
||||
* The template refers to `$name` instead of `name`. The `$` prefix tells Svelte that `name` is a *store property*
|
||||
* Because `<Greeting>` is a child of `<App>`, it also has access to the store. Without it, `<App>` would have to pass the `name` property down as a component property (`<Greeting name={name}/>`)
|
||||
|
||||
Components that depend on store properties will re-render whenever they change.
|
||||
|
||||
|
||||
### Declarative stores
|
||||
|
||||
As an alternative to adding the `store` option when instantiating, the component itself can declare a dependency on a store:
|
||||
|
||||
```html
|
||||
<!-- { title: 'Declarative stores' } -->
|
||||
<h1>Hello {$name}!</h1>
|
||||
<Greeting/>
|
||||
|
||||
<script>
|
||||
import Greeting from './Greeting.html';
|
||||
import store from './store.js';
|
||||
|
||||
export default {
|
||||
store: () => store,
|
||||
components: { Greeting }
|
||||
};
|
||||
</script>
|
||||
```
|
||||
|
||||
```html
|
||||
<!--{ filename: 'Greeting.html' }-->
|
||||
<p>It's nice to see you, {$name}</p>
|
||||
```
|
||||
|
||||
```js
|
||||
/* { filename: 'store.js' } */
|
||||
import { Store } from 'svelte/store.js';
|
||||
export default new Store({ name: 'world' });
|
||||
```
|
||||
|
||||
Note that the `store` option is a function that *returns* a store, rather than the store itself — this provides greater flexibility.
|
||||
|
||||
|
||||
### Computed store properties
|
||||
|
||||
Just like components, stores can have computed properties:
|
||||
|
||||
```js
|
||||
store = new Store({
|
||||
width: 10,
|
||||
height: 10,
|
||||
depth: 10,
|
||||
density: 3
|
||||
});
|
||||
|
||||
store.compute(
|
||||
'volume',
|
||||
['width', 'height', 'depth'],
|
||||
(width, height, depth) => width * height * depth
|
||||
);
|
||||
|
||||
store.get().volume; // 1000
|
||||
|
||||
store.set({ width: 20 });
|
||||
store.get().volume; // 2000
|
||||
|
||||
store.compute(
|
||||
'mass',
|
||||
['volume', 'density'],
|
||||
(volume, density) => volume * density
|
||||
);
|
||||
|
||||
store.get().mass; // 6000
|
||||
```
|
||||
|
||||
The first argument is the name of the computed property. The second is an array of *dependencies* — these can be data properties or other computed properties. The third argument is a function that recomputes the value whenever the dependencies change.
|
||||
|
||||
A component that was connected to this store could reference `{$volume}` and `{$mass}`, just like any other store property.
|
||||
|
||||
|
||||
### Accessing the store inside components
|
||||
|
||||
Each component gets a reference to `this.store`. This allows you to attach behaviours in `oncreate`...
|
||||
|
||||
```html
|
||||
<!-- { repl: false } -->
|
||||
<script>
|
||||
export default {
|
||||
oncreate() {
|
||||
const listener = this.store.on('state', ({ current }) => {
|
||||
// ...
|
||||
});
|
||||
|
||||
// listeners are not automatically removed — cancel
|
||||
// them to prevent memory leaks
|
||||
this.on('destroy', listener.cancel);
|
||||
}
|
||||
};
|
||||
</script>
|
||||
```
|
||||
|
||||
...or call store methods in your event handlers, using the same `$` prefix as data properties:
|
||||
|
||||
```html
|
||||
<!-- { repl: false } -->
|
||||
<button on:click="$set({ muted: true })">
|
||||
Mute audio
|
||||
</button>
|
||||
```
|
||||
|
||||
|
||||
### Custom store methods
|
||||
|
||||
`Store` doesn't have a concept of *actions* or *commits*, like Redux and Vuex. Instead, state is always updated with `store.set(...)`.
|
||||
|
||||
You can implement custom logic by subclassing `Store`:
|
||||
|
||||
```js
|
||||
class TodoStore extends Store {
|
||||
addTodo(description) {
|
||||
const todo = {
|
||||
id: generateUniqueId(),
|
||||
done: false,
|
||||
description
|
||||
};
|
||||
|
||||
const todos = this.get().todos.concat(todo);
|
||||
this.set({ todos });
|
||||
}
|
||||
|
||||
toggleTodo(id) {
|
||||
const todos = this.get().todos.map(todo => {
|
||||
if (todo.id === id) {
|
||||
return {
|
||||
id,
|
||||
done: !todo.done,
|
||||
description: todo.description
|
||||
};
|
||||
}
|
||||
|
||||
return todo;
|
||||
});
|
||||
|
||||
this.set({ todos });
|
||||
}
|
||||
}
|
||||
|
||||
const store = new TodoStore({
|
||||
todos: []
|
||||
});
|
||||
|
||||
store.addTodo('Finish writing this documentation');
|
||||
```
|
||||
|
||||
Methods can update the store asynchronously:
|
||||
|
||||
```js
|
||||
class NasdaqTracker extends Store {
|
||||
async fetchStockPrices(ticker) {
|
||||
const token = this.token = {};
|
||||
const prices = await fetch(`/api/prices/${ticker}`).then(r => r.json());
|
||||
if (token !== this.token) return; // invalidated by subsequent request
|
||||
|
||||
this.set({ prices });
|
||||
}
|
||||
}
|
||||
|
||||
const store = new NasdaqTracker();
|
||||
store.fetchStockPrices('AMZN');
|
||||
```
|
||||
|
||||
You can call these methods in your components, just like the built-in methods:
|
||||
|
||||
|
||||
```html
|
||||
<!-- { repl: false } -->
|
||||
<input
|
||||
placeholder="Enter a stock ticker"
|
||||
on:change="$fetchStockPrices(this.value)"
|
||||
>
|
||||
```
|
||||
|
||||
### Store bindings
|
||||
|
||||
You can bind to store values just like you bind to component values — just add the `$` prefix:
|
||||
|
||||
```html
|
||||
<!-- { repl: false } -->
|
||||
<!-- global audio volume control -->
|
||||
<input bind:value=$volume type=range min=0 max=1 step=0.01>
|
||||
```
|
||||
|
||||
|
||||
### Using store properties in computed properties
|
||||
|
||||
Just as in templates, you can access store properties in component computed properties by prefixing them with `$`:
|
||||
|
||||
```html
|
||||
<!-- { repl: false } -->
|
||||
{#if isVisible}
|
||||
<div class="todo {todo.done ? 'done': ''}">
|
||||
{todo.description}
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
<script>
|
||||
export default {
|
||||
computed: {
|
||||
// `todo` is a component property, `$filter` is
|
||||
// a store property
|
||||
isVisible: ({ todo, $filter }) => {
|
||||
if ($filter === 'all') return true;
|
||||
if ($filter === 'done') return todo.done;
|
||||
if ($filter === 'pending') return !todo.done;
|
||||
}
|
||||
}
|
||||
};
|
||||
</script>
|
||||
```
|
||||
|
||||
|
||||
### Built-in optimisations
|
||||
|
||||
The Svelte compiler knows which store properties your components are interested in (because of the `$` prefix), and writes code that only listens for changes to those properties. Because of that, you needn't worry about having many properties on your store, even ones that update frequently — components that don't use them will be unaffected.
|
||||
|
@ -0,0 +1,61 @@
|
||||
---
|
||||
title: Preprocessing
|
||||
---
|
||||
|
||||
Some developers like to use non-standard languages such as [Pug](https://pugjs.org/api/getting-started.html), [Sass](http://sass-lang.com/) or [CoffeeScript](http://coffeescript.org/).
|
||||
|
||||
It's possible to use these languages, or anything else that can be converted to HTML, CSS and JavaScript, using *preprocessors*.
|
||||
|
||||
|
||||
### svelte.preprocess
|
||||
|
||||
Svelte exports a `preprocess` function that takes some input source code and returns a Promise for a standard Svelte component, ready to be used with `svelte.compile`:
|
||||
|
||||
```js
|
||||
const svelte = require('svelte');
|
||||
|
||||
const input = fs.readFileSync('App.html', 'utf-8');
|
||||
|
||||
svelte.preprocess(input, {
|
||||
filename: 'App.html', // this is passed to each preprocessor
|
||||
|
||||
markup: ({ content, filename }) => {
|
||||
return {
|
||||
code: '<!-- some HTML -->',
|
||||
map: {...}
|
||||
};
|
||||
},
|
||||
|
||||
style: ({ content, attributes, filename }) => {
|
||||
return {
|
||||
code: '/* some CSS */',
|
||||
map: {...}
|
||||
};
|
||||
},
|
||||
|
||||
script: ({ content, attributes, filename }) => {
|
||||
return {
|
||||
code: '// some JavaScript',
|
||||
map: {...}
|
||||
};
|
||||
}
|
||||
}).then(preprocessed => {
|
||||
fs.writeFileSync('preprocessed/App.html', preprocessed.toString());
|
||||
|
||||
const { js } = svelte.compile(preprocessed);
|
||||
fs.writeFileSync('compiled/App.js', js.code);
|
||||
});
|
||||
```
|
||||
|
||||
The `markup` preprocessor, if specified, runs first. The `content` property represents the entire input string.
|
||||
|
||||
The `style` and `script` preprocessors receive the contents of the `<style>` and `<script>` elements respectively, along with any `attributes` on those elements (e.g. `<style lang='scss'>`).
|
||||
|
||||
All three preprocessors are optional. Each should return a `{ code, map }` object or a Promise that resolves to a `{ code, map }` object, where `code` is the resulting string and `map` is a sourcemap representing the transformation.
|
||||
|
||||
> The returned `map` objects are not currently used by Svelte, but will be in future versions
|
||||
|
||||
|
||||
### Using build tools
|
||||
|
||||
Many build tool plugins, such as [rollup-plugin-svelte](https://github.com/rollup/rollup-plugin-svelte) and [svelte-loader](https://github.com/sveltejs/svelte-loader), allow you to specify `preprocess` options, in which case the build tool will do the grunt work.
|
@ -0,0 +1,109 @@
|
||||
---
|
||||
title: Custom elements
|
||||
---
|
||||
|
||||
[Custom elements](https://developer.mozilla.org/en-US/docs/Web/Web_Components/Custom_Elements) are an emerging web standard for creating DOM elements that encapsulate styles and behaviours, much like Svelte components. They are part of the [web components](https://developer.mozilla.org/en-US/docs/Web/Web_Components) family of specifications.
|
||||
|
||||
> Most browsers need [polyfills](https://www.webcomponents.org/polyfills) for custom elements. See [caniuse](https://caniuse.com/#feat=custom-elementsv1) for more details
|
||||
|
||||
Svelte components can be used as custom elements by doing the following:
|
||||
|
||||
1. Declaring a `tag` name. The value must contain a hyphen (`hello-world` in the example below)
|
||||
2. Specifying `customElement: true` in the compiler configuration
|
||||
|
||||
```html
|
||||
<!-- { filename: 'HelloWorld.html', repl: false } -->
|
||||
<h1>Hello {name}!</h1>
|
||||
|
||||
<script>
|
||||
export default {
|
||||
tag: 'hello-world'
|
||||
};
|
||||
</script>
|
||||
```
|
||||
|
||||
Importing this file will now register a globally-available `<hello-world>` custom element that accepts a `name` property:
|
||||
|
||||
```js
|
||||
import './HelloWorld.html';
|
||||
document.body.innerHTML = `<hello-world name="world"/>`;
|
||||
|
||||
const el = document.querySelector('hello-world');
|
||||
el.name = 'everybody';
|
||||
```
|
||||
|
||||
See [svelte-custom-elements.surge.sh](http://svelte-custom-elements.surge.sh/) ([source here](https://github.com/sveltejs/template-custom-element)) for a larger example.
|
||||
|
||||
The compiled custom elements are still full-fledged Svelte components and can be used as such:
|
||||
|
||||
```js
|
||||
el.get().name === el.name; // true
|
||||
el.set({ name: 'folks' }); // equivalent to el.name = 'folks'
|
||||
```
|
||||
|
||||
One crucial difference is that styles are *fully encapsulated* — whereas Svelte will prevent component styles from leaking *out*, custom elements use [shadow DOM](https://developer.mozilla.org/en-US/docs/Web/Web_Components/Shadow_DOM) which also prevents styles from leaking *in*.
|
||||
|
||||
### Using `<slot>`
|
||||
|
||||
Custom elements can use [slots](guide#composing-with-slot) to place child elements, just like regular Svelte components.
|
||||
|
||||
### Firing events
|
||||
|
||||
You can dispatch events inside custom elements to pass data out:
|
||||
|
||||
```js
|
||||
// inside a component method
|
||||
const event = new CustomEvent('message', {
|
||||
detail: 'Hello parent!',
|
||||
bubbles: true,
|
||||
cancelable: true,
|
||||
composed: true // makes the event jump shadow DOM boundary
|
||||
});
|
||||
|
||||
this.dispatchEvent(event);
|
||||
```
|
||||
|
||||
Other parts of the application can listen for these events with `addEventListener`:
|
||||
|
||||
```js
|
||||
const el = document.querySelector('hello-world');
|
||||
el.addEventListener('message', event => {
|
||||
alert(event.detail);
|
||||
});
|
||||
```
|
||||
|
||||
> Note the `composed: true` attribute of the custom event. It enables the custom DOM event to cross the shadow DOM boundary and enter into main DOM tree.
|
||||
|
||||
### Observing properties
|
||||
|
||||
Svelte will determine, from the template and `computed` values, which properties the custom element has — for example, `name` in our `<hello-world>` example. You can specify this list of properties manually, for example to restrict which properties are 'visible' to the rest of your app:
|
||||
|
||||
```js
|
||||
export default {
|
||||
tag: 'my-thing',
|
||||
props: ['foo', 'bar']
|
||||
};
|
||||
```
|
||||
|
||||
### Compiler options
|
||||
|
||||
Earlier, we saw the use of `customElement: true` to instruct the Svelte compiler to generate a custom element using the `tag` and (optional) `props` declared inside the component file.
|
||||
|
||||
Alternatively, you can pass `tag` and `props` direct to the compiler:
|
||||
|
||||
```js
|
||||
const { js } = svelte.compile(source, {
|
||||
customElement: {
|
||||
tag: 'overridden-tag-name',
|
||||
props: ['yar', 'boo']
|
||||
}
|
||||
});
|
||||
```
|
||||
|
||||
These options will override the component's own settings, if any.
|
||||
|
||||
### Transpiling
|
||||
|
||||
* Custom elements use ES2015 classes (`MyThing extends HTMLElement`). Make sure you don't transpile the custom element code to ES5, and use a ES2015-aware minifier such as [uglify-es](https://www.npmjs.com/package/uglify-es).
|
||||
|
||||
* If you do need ES5 support, make sure to use `Reflect.construct` aware transpiler plugin such as [babel-plugin-transform-builtin-classes](https://github.com/WebReflection/babel-plugin-transform-builtin-classes) and a polyfill like [custom-elements-es5-adapterjs](https://github.com/webcomponents/webcomponentsjs#custom-elements-es5-adapterjs).
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in new issue