Merge pull request #1 from sveltejs/master

keep up to date
pull/4957/head
swyx 6 years ago committed by GitHub
commit 3de0e4bca4
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

@ -1,7 +1,18 @@
src/shared
shared.js
store.js
test/test.js
test/setup.js
**/_actual.js
**/expected.js
_output
test/*/samples/*/output.js
node_modules
# automatically generated
internal_exports.ts
# output files
animate/*.js
esing/*.js
internal/*.js
motion/*.js
store/*.js
transition/*.js
index.js
compiler.js

@ -0,0 +1,88 @@
module.exports = {
root: true,
rules: {
indent: 'off',
'no-unused-vars': 'off',
semi: [2, 'always'],
'keyword-spacing': [2, { before: true, after: true }],
'space-before-blocks': [2, 'always'],
'no-mixed-spaces-and-tabs': [2, 'smart-tabs'],
'no-cond-assign': 0,
'object-shorthand': [2, 'always'],
'no-const-assign': 2,
'no-class-assign': 2,
'no-this-before-super': 2,
'no-var': 2,
'no-unreachable': 2,
'valid-typeof': 2,
'quote-props': [2, 'as-needed'],
'one-var': [2, 'never'],
'prefer-arrow-callback': 2,
'prefer-const': [2, { destructuring: 'all' }],
'arrow-spacing': 2,
'no-inner-declarations': 0,
'require-atomic-updates': 'off',
'@typescript-eslint/indent': 'off',
'@typescript-eslint/camelcase': 'off',
'@typescript-eslint/no-use-before-define': 'off',
'@typescript-eslint/array-type': ['error', 'array-simple'],
'@typescript-eslint/explicit-function-return-type': 'off',
'@typescript-eslint/no-explicit-any': 'off',
'@typescript-eslint/explicit-member-accessibility': 'off',
'@typescript-eslint/no-unused-vars': [
'error',
{
argsIgnorePattern: '^_'
}
],
'@typescript-eslint/no-object-literal-type-assertion': 'off',
'@typescript-eslint/no-unused-vars': 'off',
'@typescript-eslint/prefer-interface': 'off'
},
globals: {
globalThis: false
},
env: {
es6: true,
browser: true,
node: true,
mocha: true
},
extends: [
'eslint:recommended',
'plugin:import/errors',
'plugin:import/warnings',
'plugin:import/typescript',
'plugin:@typescript-eslint/recommended'
],
parserOptions: {
ecmaVersion: 9,
sourceType: 'module'
},
plugins: ['svelte3'],
settings: {
'import/core-modules': [
'svelte',
'svelte/internal',
'svelte/store',
'svelte/easing',
'estree'
],
'svelte3/compiler': require('./compiler')
},
overrides: [
{
files: ['*.js'],
rules: {
'@typescript-eslint/no-var-requires': 'off'
}
},
{
files: ['*.svelte'],
processor: 'svelte3/svelte3',
rules: {
'@typescript-eslint/indent': 'off'
}
}
]
};

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

@ -1,9 +0,0 @@
[ignore]
<PROJECT_ROOT>/dist/.*
[include]
[libs]
[options]
strip_root=true

@ -1,21 +1,26 @@
<!--
Thanks for raising an issue! (For *questions*, we recommend instead using https://stackoverflow.com and adding the 'svelte' tag.)
------
Before filing an issue we'd appreciate it if you could take a moment to ensure
there isn't already an open issue or pull-request.
-----
To help us help you, if you've found a bug please consider the following:
If there's an existing issue, please add a :+1: reaction to the description of
the issue. One way we prioritize issues is by the number of :+1: reactions on
their descriptions. Please DO NOT add `+1` or :+1: comments.
* If you can demonstrate the bug using https://svelte.dev/repl, please do.
* If that's not possible, we recommend creating a small repo that illustrates the problem.
* Make sure you include information about the browser, and which version of Svelte you're using
### Feature requests and proposals
We're excited to hear how we can make Svelte better. Please add as much detail
as you can on your use case.
Reproductions should be small, self-contained, correct examples http://sscce.org.
### Bugs
If you're filing an issue about a bug please include as much information
as you can including the following.
Occasionally, this won't be possible, and that's fine we still appreciate you raising the issue. But please understand that Svelte is run by unpaid volunteers in their free time, and issues that follow these instructions will get fixed faster.
- Your browser and the version: (e.x. Chrome 52.1, Firefox 48.0, IE 10)
- Your operating system: (e.x. OS X 10, Windows XP, etc)
- Svelte version (Please check you can reproduce the issue with the latest release!)
- Whether your project uses Webpack or Rollup
If you have a stack trace to include, we recommend putting inside a `<details>` block for the sake of the thread's readability:
- *Repeatable steps to reproduce the issue*
<details>
<summary>Stack trace</summary>
Stack trace goes here...
</details>
-->
Thanks for being part of Svelte!
-------

@ -0,0 +1,52 @@
---
name: Bug report
about: Create a report to help us improve
title: ''
labels: 'Bug'
assignees: ''
---
**Describe the bug**
A clear and concise description of what the bug is.
**Logs**
Please include browser console and server logs around the time this bug occurred.
**To Reproduce**
To help us help you, if you've found a bug please consider the following:
* If you can demonstrate the bug using https://svelte.dev/repl, please do.
* If that's not possible, we recommend creating a small repo that illustrates the problem.
* Reproductions should be small, self-contained, correct examples http://sscce.org.
Occasionally, this won't be possible, and that's fine we still appreciate you raising the issue. But please understand that Svelte is run by unpaid volunteers in their free time, and issues that follow these instructions will get fixed faster.
**Expected behavior**
A clear and concise description of what you expected to happen.
**Stacktraces**
If you have a stack trace to include, we recommend putting inside a `<details>` block for the sake of the thread's readability:
<details>
<summary>Stack trace</summary>
Stack trace goes here...
</details>
**Information about your Svelte project:**
- Your browser and the version: (e.x. Chrome 52.1, Firefox 48.0, IE 10)
- Your operating system: (e.x. OS X 10, Ubuntu Linux 19.10, Windows XP, etc)
- Svelte version (Please check you can reproduce the issue with the latest release!)
- Whether your project uses Webpack or Rollup
**Severity**
How severe an issue is this bug to you? Is this annoying, blocking some users, blocking an upgrade or blocking your usage of Svelte entirely?
Note: the more honest and specific you are here the more we will take you seriously.
**Additional context**
Add any other context about the problem here.

@ -0,0 +1,23 @@
---
name: Feature request
about: Suggest an idea for this project
title: ''
labels: 'New Feature'
assignees: ''
---
**Is your feature request related to a problem? Please describe.**
A clear and concise description of what the problem is. For example: I'm always frustrated when [...]
**Describe the solution you'd like**
A clear and concise description of what you want to happen.
**Describe alternatives you've considered**
A clear and concise description of any alternative solutions or features you've considered.
**How important is this feature to you?**
Note: the more honest and specific you are here the more we will take you seriously.
**Additional context**
Add any other context or screenshots about the feature request here.

@ -0,0 +1,12 @@
---
name: Questions and help
about: If you think you need help with something related to Svelte
title: ''
labels: 'Question'
assignees: ''
---
This issue tracker is intended to collect bug reports and feature requests.
For help with installation, information on how features work, or questions about specific features of Svelte, please come and join us in the [Svelte Discord](https://svelte.dev/chat), or ask your question on [Stack Overflow](https://stackoverflow.com/questions/tagged/svelte). Any issues open for help requests will be closed to keep from clogging up the issue tracker.

@ -1,7 +1,8 @@
<!--
Thank you for creating a pull request. Before submitting, please note the following:
* If your pull request implements a new feature, please raise an issue to discuss it before sending code. In many cases features are absent for a reason.
* This message body should clearly illustrate what problems it solves. If there are related issues, remember to reference them.
* Ideally, include a test that fails without this PR but passes with it. PRs will only be merged once they pass CI. (Remember to `npm run lint`!)
-->
### Before submitting the PR, please make sure you do the following
- [ ] It's really useful if your PR relates to an outstanding issue, so please reference it in your PR, or create an explanatory one for discussion. In many cases features are absent for a reason.
- [ ] This message body should clearly illustrate what problems it solves. If there are related issues, remember to reference them.
- [ ] Ideally, include a test that fails without this PR but passes with it. PRs will only be merged once they pass CI. (Remember to `npm run lint`!)
### Tests
- [ ] Run the tests tests with `npm test` or `yarn test`)

@ -0,0 +1,31 @@
name: CI
on: [push, pull_request]
jobs:
Tests:
runs-on: ${{ matrix.os }}
strategy:
matrix:
node-version: [8, 10, 12]
os: [ubuntu-latest, windows-latest, macOS-latest]
steps:
- run: git config --global core.autocrlf false
- uses: actions/checkout@v1
- uses: actions/setup-node@v1
with:
node-version: ${{ matrix.node-version }}
- run: npm install
- run: npm test
env:
CI: true
Lint:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v1
- uses: actions/setup-node@v1
- run: 'npm i && npm run lint'
Unit:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v1
- uses: actions/setup-node@v1
- run: 'npm i && npm run test:unit'

29
.gitignore vendored

@ -1,25 +1,30 @@
.idea
.DS_Store
.nyc_output
node_modules
*.map
/src/compile/internal-exports.ts
/compiler.js
/index.js
/internal.*
/store.js
/easing.js
/motion.*
/transition.js
/animate.js
/src/compiler/compile/internal_exports.ts
/compiler.d.ts
/compiler.*js
/index.*js
/internal
/store
/easing
/motion
/transition
/animate
/scratch/
/coverage/
/coverage.lcov/
/coverage.lcov
/test/*/samples/_
/test/sourcemaps/samples/*/output.js
/test/sourcemaps/samples/*/output.js.map
/test/sourcemaps/samples/*/output.css
/test/sourcemaps/samples/*/output.css.map
/yarn-error.log
_actual*.*
_output
/types
/site/cypress/screenshots/
/site/__sapper__/
@ -27,5 +32,9 @@ _actual*.*
/site/.sessions
/site/static/svelte-app.json
/site/static/contributors.jpg
/site/static/workers
/site/static/organisations
/site/scripts/svelte-app
/site/scripts/community
/site/src/routes/_contributors.js
/site/src/routes/_components/WhosUsingSvelte.svelte

@ -1,3 +0,0 @@
useTabs: true
singleQuote: true
trailingComma: es5

@ -1,19 +0,0 @@
language: node_js
node_js:
- "node"
env:
global:
- BUILD_TIMEOUT=20000
addons:
apt:
packages:
- xvfb
install:
- export DISPLAY=':99.0'
- Xvfb :99 -screen 0 1024x768x24 > /dev/null 2>&1 &
- npm ci || npm install
after_success: npm run codecov

@ -1,5 +1,474 @@
# Svelte changelog
## Unreleased
* Fix indirect bindings involving elements with spreads ([#3680](https://github.com/sveltejs/svelte/issues/3680))
* Fix unneeded updating of keyed each blocks ([#4373](https://github.com/sveltejs/svelte/issues/4373))
## 3.18.2
* Fix binding to module-level variables ([#4086](https://github.com/sveltejs/svelte/issues/4086))
* Improve parsing error messages when there is a pending unclosed tag ([#4131](https://github.com/sveltejs/svelte/issues/4131))
* Disallow attribute/prop names from matching two-way-bound names or `{shorthand}` attribute/prop names ([#4325](https://github.com/sveltejs/svelte/issues/4325))
* Improve performance of `flush()` by not using `.shift()` ([#4356](https://github.com/sveltejs/svelte/pull/4356))
* Permit reserved keywords as destructuring keys in `{#each}` ([#4372](https://github.com/sveltejs/svelte/issues/4372))
* Disallow reserved keywords in `{expressions}` ([#4372](https://github.com/sveltejs/svelte/issues/4372))
* Fix code generation error with precedence of arrow functions ([#4384](https://github.com/sveltejs/svelte/issues/4384))
* Fix event handlers that are dynamic via reactive declarations or stores ([#4388](https://github.com/sveltejs/svelte/issues/4388))
* Fix invalidation in expressions like `++foo.bar` ([#4393](https://github.com/sveltejs/svelte/issues/4393))
## 3.18.1
* Fix code generation error with adjacent inline and block comments ([#4312](https://github.com/sveltejs/svelte/issues/4312))
* Fix detection of unused CSS selectors that begin with a `:global()` but contain a scoped portion ([#4314](https://github.com/sveltejs/svelte/issues/4314))
## 3.18.0
* Fix infinite loop when instantiating another component during `onMount` ([#3218](https://github.com/sveltejs/svelte/issues/3218))
* Make autosubscribing to a nullish store a no-op ([#2181](https://github.com/sveltejs/svelte/issues/2181))
## 3.17.3
* Fix updating a `<slot>` inside an `{#if}` or other block ([#4292](https://github.com/sveltejs/svelte/issues/4292))
* Fix using RxJS observables in `derived` stores ([#4298](https://github.com/sveltejs/svelte/issues/4298))
* Add dev mode check to disallow duplicate keys in a keyed `{#each}` ([#4301](https://github.com/sveltejs/svelte/issues/4301))
* Fix hydration of `<title>` when starting from SSR-generated code with `hydratable: true` ([#4310](https://github.com/sveltejs/svelte/issues/4310))
## 3.17.2
* Fix removing attributes during hydration ([#1733](https://github.com/sveltejs/svelte/issues/1733))
* Disallow two-way binding to a variable declared by an `{#await}` block ([#4012](https://github.com/sveltejs/svelte/issues/4012))
* Allow access to `let:` variables in sibling attributes on slot root ([#4173](https://github.com/sveltejs/svelte/issues/4173))
* Fix `~=` and class selector matching against values separated by any whitespace characters ([#4242](https://github.com/sveltejs/svelte/issues/4242))
* Fix code generation for `await`ed expressions that need parentheses ([#4267](https://github.com/sveltejs/svelte/issues/4267))
* Preserve JavaScript comments from the original component source where possible ([#4268](https://github.com/sveltejs/svelte/issues/4268))
* Add some more known globals ([#4276](https://github.com/sveltejs/svelte/pull/4276))
* Correctly apply event modifiers to `<svelte:body>` events ([#4278](https://github.com/sveltejs/svelte/issues/4278))
## 3.17.1
* Only attach SSR mode markers to a component's `<head>` elements when compiling with `hydratable: true` ([#4258](https://github.com/sveltejs/svelte/issues/4258))
## 3.17.0
* Remove old `<head>` elements during hydration so they aren't duplicated ([#1607](https://github.com/sveltejs/svelte/issues/1607))
* Prevent text input cursor jumping in Safari with one-way binding ([#3449](https://github.com/sveltejs/svelte/issues/3449))
* Expose compiler version in dev events ([#4047](https://github.com/sveltejs/svelte/issues/4047))
* Don't run actions before their element is in the document ([#4166](https://github.com/sveltejs/svelte/issues/4166))
* Fix reactive assignments with destructuring and stores where the destructured value should be undefined ([#4170](https://github.com/sveltejs/svelte/issues/4170))
* Fix hydrating `{:else}` in `{#each}` ([#4202](https://github.com/sveltejs/svelte/issues/4202))
* Do not automatically declare variables in reactive declarations when assigning to a member expression ([#4212](https://github.com/sveltejs/svelte/issues/4212))
* Fix stringifying of attributes in SSR mode when there are spread attributes ([#4240](https://github.com/sveltejs/svelte/issues/4240))
* Only render one `<title>` in SSR mode when multiple components provide one ([#4250](https://github.com/sveltejs/svelte/pull/4250))
## 3.16.7
* Also apply actions in the order they're given along with other directives ([#2446](https://github.com/sveltejs/svelte/issues/2446), [#4156](https://github.com/sveltejs/svelte/pull/4156))
* Check whether a dynamic event handler is a function before calling it ([#4090](https://github.com/sveltejs/svelte/issues/4090))
* Correctly mark event handlers as dynamic when they involve an expression used in a `bind:` elsewhere ([#4155](https://github.com/sveltejs/svelte/pull/4155))
## 3.16.6
* Fix CSS specificity bug when encapsulating styles ([#1277](https://github.com/sveltejs/svelte/issues/1277))
* Apply directives in the order they're given ([#2446](https://github.com/sveltejs/svelte/issues/2446))
* Fix destructuring in `let:` directives ([#2751](https://github.com/sveltejs/svelte/issues/2751))
* Preserve whitespace around `<tspan>`s in `<svg>`s ([#3998](https://github.com/sveltejs/svelte/issues/3998))
## 3.16.5
* Better fix for cascading invalidations and fix some regressions ([#4098](https://github.com/sveltejs/svelte/issues/4098), [#4114](https://github.com/sveltejs/svelte/issues/4114), [#4120](https://github.com/sveltejs/svelte/issues/4120))
## 3.16.4
* Fix slots with props not propagating through to inner slots ([#4061](https://github.com/sveltejs/svelte/issues/4061))
* Fix noting autosubscribed stores as `referenced` in `vars` for tooling ([#4081](https://github.com/sveltejs/svelte/issues/4081))
* Fix cascading invalidations in certain situations ([#4094](https://github.com/sveltejs/svelte/issues/4094))
## 3.16.3
* Fix bitmask overflow when using slotted components ([#4077](https://github.com/sveltejs/svelte/issues/4077))
* Remove unnecessary `$$invalidate` calls from init block ([#4018](https://github.com/sveltejs/svelte/issues/4018))
## 3.16.2
* Handle slot updates when parent component has a bitmask overflow ([#4078](https://github.com/sveltejs/svelte/pull/4078))
## 3.16.1
* Fix unused export warning for props used as stores ([#4021](https://github.com/sveltejs/svelte/issues/4021))
* Fix `{:then}` without resolved value containing `{#each}` ([#4022](https://github.com/sveltejs/svelte/issues/4022))
* Fix incorrect code generated with `loopGuardTimeout` ([#4034](https://github.com/sveltejs/svelte/issues/4034))
* Fix handling of bitmask overflow and globals ([#4037](https://github.com/sveltejs/svelte/issues/4037))
* Fix `{:then}` containing `{#if}` ([#4044](https://github.com/sveltejs/svelte/issues/4044))
* Fix bare `import`s in `format: 'cjs'` output mode ([#4055](https://github.com/sveltejs/svelte/issues/4050))
* Warn when using a known global as a component name ([#4070](https://github.com/sveltejs/svelte/issues/4070))
## 3.16.0
* Use bitmasks to track changes ([#3945](https://github.com/sveltejs/svelte/pull/3945))
* Fix heisenbug with component styles ([#3977](https://github.com/sveltejs/svelte/issues/3977))
* Do not warn about missing expected props for `export function foo() {}` ([#3954](https://github.com/sveltejs/svelte/issues/3954))
* Fix `context="module"` exports with the same name as an instance variable ([#3983](https://github.com/sveltejs/svelte/issues/3983))
* Fix binding to contextual values from `{#each}` blocks referring to global variables ([#3992](https://github.com/sveltejs/svelte/issues/3992))
* Use `requestAnimationFrame` callback argument for smoother transitions ([#4014](https://github.com/sveltejs/svelte/pull/4014))
* Fix `listen_dev` argument order ([#4016](https://github.com/sveltejs/svelte/pull/4016))
## 3.15.0
* Hide commented sections from preprocessors ([#3894](https://github.com/sveltejs/svelte/pull/3894))
* Add `seeking` and `ended` bindings to media elements ([#3650](https://github.com/sveltejs/svelte/pull/3650))
* Add `videoWidth` and `videoHeight` bindings to video elements ([#3927](https://github.com/sveltejs/svelte/pull/3927))
* Fix for dynamic event handlers ([#3934](https://github.com/sveltejs/svelte/pull/3934))
* Handle scale transforms when using the `flip` animation ([#3555](https://github.com/sveltejs/svelte/issues/3555))
* Fix some code generation bugs ([#3929](https://github.com/sveltejs/svelte/issues/3929), [#3939](https://github.com/sveltejs/svelte/issues/3939))
* Add `aria-hidden="true"` to objects generated when adding resize-listeners, to improve accessibility ([#3948](https://github.com/sveltejs/svelte/issues/3948))
## 3.14.1
* Deconflict block method names with other variables ([#3900](https://github.com/sveltejs/svelte/issues/3900))
* Fix entity encoding issue in text nodes with constant expressions ([#3911](https://github.com/sveltejs/svelte/issues/3911))
* Make code for unknown prop warnings compatible with older js engines ([#3914](https://github.com/sveltejs/svelte/issues/3914))
## 3.14.0
* Add `loopGuardTimeout` option that augments `for`/`while` loops to prevent infinite loops, primarily for use in the REPL ([#3887](https://github.com/sveltejs/svelte/pull/3887))
* Keep component bindings in sync when changed in reactive statements ([#3382](https://github.com/sveltejs/svelte/issues/3382))
* Update attributes before bindings ([#3857](https://github.com/sveltejs/svelte/issues/3857))
* Prevent variable naming conflict ([#3899](https://github.com/sveltejs/svelte/issues/3899))
## 3.13.0
* New structured code generation, which eliminates a number of edge cases and obscure bugs ([#3539](https://github.com/sveltejs/svelte/pull/3539))
Also:
* Fix `{#each}` context not shadowing outer scope when using `bind:` ([#1565](https://github.com/sveltejs/svelte/issues/1565))
* Fix edge cases in matching selectors against elements ([#1710](https://github.com/sveltejs/svelte/issues/1710))
* Fix several bugs related to interaction of `{...spread}` attributes with other features ([#2721](https://github.com/sveltejs/svelte/issues/2721), [#2916](https://github.com/sveltejs/svelte/issues/2916), [#3421](https://github.com/sveltejs/svelte/issues/3421), [#3681](https://github.com/sveltejs/svelte/issues/3681), [#3764](https://github.com/sveltejs/svelte/issues/3764), [#3790](https://github.com/sveltejs/svelte/issues/3790))
* Allow exiting a reactive block early with `break $` ([#2828](https://github.com/sveltejs/svelte/issues/2828))
* Fix binding to props that have been renamed with `export { ... as ... }` ([#3508](https://github.com/sveltejs/svelte/issues/3508))
* Fix application of style scoping class in cases of ambiguity ([#3544](https://github.com/sveltejs/svelte/issues/3544))
* Check attributes have changed before setting them to avoid image flicker ([#3579](https://github.com/sveltejs/svelte/pull/3579))
* Fix generating malformed code for `{@debug}` tags with no dependencies ([#3588](https://github.com/sveltejs/svelte/issues/3588))
* Fix generated code in specific case involving compound ifs and child components ([#3595](https://github.com/sveltejs/svelte/issues/3595))
* Fix `bind:this` binding to a store ([#3591](https://github.com/sveltejs/svelte/issues/3591))
* Use safer `HTMLElement` check before extending class ([#3608](https://github.com/sveltejs/svelte/issues/3608))
* Add `location` as a known global ([#3619](https://github.com/sveltejs/svelte/pull/3619))
* Support `{#await}` with `{:catch}` but no `{:then}` ([#3623](https://github.com/sveltejs/svelte/issues/3623))
* Clean up dead code emitted for `<slot/>`s ([#3631](https://github.com/sveltejs/svelte/issues/3631))
* Fix tracking of dependencies of compound assignments in reactive statements ([#3634](https://github.com/sveltejs/svelte/issues/3634))
* Flush changes in newly attached block when using `{#await}` ([#3660](https://github.com/sveltejs/svelte/issues/3660))
* Throw exception immediately when calling `createEventDispatcher()` after component instantiation ([#3667](https://github.com/sveltejs/svelte/pull/3667))
* Fix globals shadowing contextual template scope ([#3674](https://github.com/sveltejs/svelte/issues/3674))
* Fix `<svelte:window>` bindings to stores ([#3832](https://github.com/sveltejs/svelte/issues/3832))
* Deconflict generated var names with builtins ([#3724](https://github.com/sveltejs/svelte/issues/3724))
* Allow spring/tweened values to be initially undefined ([#3761](https://github.com/sveltejs/svelte/issues/3761))
* Warn if using `<svelte:options tag="...">` without `customElement: true` option ([#3782](https://github.com/sveltejs/svelte/pull/3782))
* Add `Event` to list of known globals ([#3810](https://github.com/sveltejs/svelte/pull/3810))
* Throw helpful error on empty CSS declaration ([#3801](https://github.com/sveltejs/svelte/issues/3801))
* Support `easing` param on `fade` transition ([#3823](https://github.com/sveltejs/svelte/pull/3823))
* Generate valid names from filenames with unicode characters ([#3845](https://github.com/sveltejs/svelte/issues/3845))
* Don't generate any code for markup-less components ([#2200](https://github.com/sveltejs/svelte/issues/2200))
* Deconflict with internal name `block` ([#3854](https://github.com/sveltejs/svelte/issues/3854))
* Set attributes before bindings, to prevent erroneous assignments to `input.files` ([#3828](https://github.com/sveltejs/svelte/issues/3828))
* Smarter unused CSS detection ([#3825](https://github.com/sveltejs/svelte/pull/3825))
* Allow dynamic event handlers ([#3040](https://github.com/sveltejs/svelte/issues/3040))
* Prevent erroneous `"undefined"` class name ([#3876](https://github.com/sveltejs/svelte/pull/3876))
* Prevent resetting of `src` attribute unless changed ([#3579](https://github.com/sveltejs/svelte/pull/3579))
* Prevent hydration of void element 'children' ([#3882](https://github.com/sveltejs/svelte/issues/3882))
* Hoist globals even if mentioned in `<script>` block ([#3745](https://github.com/sveltejs/svelte/pull/3745))
## 3.12.1
* Escape `@` symbols in props, again ([#3545](https://github.com/sveltejs/svelte/issues/3545))
## 3.12.0
* Fire events on `document` in development to facilitate dev tooling ([#3005](https://github.com/sveltejs/svelte/pull/3005))
* Remove old props when the keys in spread props are removed ([#2282](https://github.com/sveltejs/svelte/issues/2282))
## 3.11.0
* `$capture_state` and `$inject_state` HMR hooks in dev mode ([#3148](https://github.com/sveltejs/svelte/pull/3148))
* Allow unclosed tags inside if/each/etc blocks ([#2807](https://github.com/sveltejs/svelte/issues/2807))
* Invalidate unreferenced store values inside `<script>` ([#3537](https://github.com/sveltejs/svelte/issues/3537))
* Print `null` text when hydrating ([#3379](https://github.com/sveltejs/svelte/pull/3379))
## 3.10.1
* Preserve reactivity inside if block heads etc ([#3512](https://github.com/sveltejs/svelte/issues/3512))
* Fix store bindings inside each blocks ([#3455](https://github.com/sveltejs/svelte/issues/3455))
* Generate correct code for if-else blocks with static conditions ([#3505](https://github.com/sveltejs/svelte/issues/3505))
* Avoid generating unnecessary component update code ([#3526](https://github.com/sveltejs/svelte/issues/3526))
* Make `bind:currentTime` more reliable ([#3524](https://github.com/sveltejs/svelte/issues/3524))
* Prevent errors when setting spread props on SVG elements ([#3522](https://github.com/sveltejs/svelte/issues/3522))
## 3.10.0
* Add `blur` transition ([#3477](https://github.com/sveltejs/svelte/pull/3477))
* Prevent `<input type="number">` edge case with spread props ([#3426](https://github.com/sveltejs/svelte/issues/3426))
* Robustify cyclical dependency detection, improve errors ([#3459](https://github.com/sveltejs/svelte/issues/3459))
## 3.9.2
* Fix handling of additional @-rules in style blocks ([#2995](https://github.com/sveltejs/svelte/pull/2995))
* Fix if blocks with complex but static conditions ([#3447](https://github.com/sveltejs/svelte/issues/3447))
## 3.9.1
* Only update style properties if necessary ([#3433](https://github.com/sveltejs/svelte/issues/3433))
* Only update if/await blocks if necessary ([#2355](https://github.com/sveltejs/svelte/issues/2355))
* Set context correctly inside await blocks ([#2443](https://github.com/sveltejs/svelte/issues/2443))
* Handle `!important` inline styles ([#1834](https://github.com/sveltejs/svelte/issues/1834))
* Make index references reactive in event handlers inside keyed each blocks ([#2569](https://github.com/sveltejs/svelte/issues/2569))
## 3.9.0
* Support `is` attribute on elements, with a warning ([#3182](https://github.com/sveltejs/svelte/issues/3182))
* Handle missing slot prop ([#3322](https://github.com/sveltejs/svelte/issues/3322))
* Don't set undefined/null input values, unless previous value exists ([#1233](https://github.com/sveltejs/svelte/issues/1233))
* Fix style attribute optimisation bailout ([#1830](https://github.com/sveltejs/svelte/issues/1830))
## 3.8.1
* Set SVG namespace for slotted elements ([#3321](https://github.com/sveltejs/svelte/issues/3321))
## 3.8.0
* Add `self` event modifier ([#3372](https://github.com/sveltejs/svelte/issues/3372))
* Generate valid code when spreading literal ([#3185](https://github.com/sveltejs/svelte/issues/3185))
* Coerce tag values to string before checking equality ([#2290](https://github.com/sveltejs/svelte/issues/2290))
## 3.7.1
* Assume `let` variables are dynamic for slots ([#3354](https://github.com/sveltejs/svelte/issues/3354))
* Allow transition functions to return nothing ([#2246](https://github.com/sveltejs/svelte/pull/2246))
## 3.7.0
* Disable warnings via `svelte-ignore` comments ([#3351](https://github.com/sveltejs/svelte/pull/3351))
* Throw if `$` or `$$...` is referenced as global ([#3272](https://github.com/sveltejs/svelte/issues/3272))
* Remount HTML tags correctly ([#3329](https://github.com/sveltejs/svelte/pull/3329))
* Treat data attributes like other attributes ([#3337](https://github.com/sveltejs/svelte/issues/3337))
## 3.6.11
* Handle reassigned RxJS observables ([#3304](https://github.com/sveltejs/svelte/issues/3304))
* Remove commas from HTMLified attributes with multiple chunks ([#3341](https://github.com/sveltejs/svelte/issues/3341))
* Prevent `class` on element with scoped styles from rendering as `undefined` ([#3283](https://github.com/sveltejs/svelte/issues/3283))
* Allow references to index in key expression ([#3274](https://github.com/sveltejs/svelte/issues/3274))
* Mark attribute selectors as used if corresponding binding exists ([#3281](https://github.com/sveltejs/svelte/issues/3281))
* Preserve `async`/`*` when hoisting functions ([#3179](https://github.com/sveltejs/svelte/issues/3179))
* Make `raf` a noop on server ([#3324](https://github.com/sveltejs/svelte/issues/3324))
* Prevent erroneous a11y warning for image input with alt attribute ([#3331](https://github.com/sveltejs/svelte/issues/3331))
* Add several well-known globals ([#3316](https://github.com/sveltejs/svelte/pull/3316))
## 3.6.10
* Use `change` event for file inputs ([#3226](https://github.com/sveltejs/svelte/issues/3226))
* Always fire reactive declarations with `$$props` ([#3286](https://github.com/sveltejs/svelte/issues/3286))
* More conservative spread prop updates ([#3289](https://github.com/sveltejs/svelte/issues/3289))
* Quote props if necessary in SSR mode ([#3312](https://github.com/sveltejs/svelte/issues/3312))
## 3.6.9
* Always update derived stores with a derived input whose value does not change ([#3191](https://github.com/sveltejs/svelte/issues/3191))
## 3.6.8
* Preserve global keyframes that don't match local elements ([#3228](https://github.com/sveltejs/svelte/issues/3228))
* Fix spread/`class:` combination ([#3242](https://github.com/sveltejs/svelte/pull/3242))
* Never scope `:root` selector ([#3250](https://github.com/sveltejs/svelte/pull/3250))
* Prevent trailing commas in function arguments ([#3255](https://github.com/sveltejs/svelte/pull/3260))
## 3.6.7
* Prevent corruption of outro callbacks with nested keyed each blocks ([#3209](https://github.com/sveltejs/svelte/pull/3209))
* Prevent cursor jumping in bound input in Safari ([#3199](https://github.com/sveltejs/svelte/issues/3199))
* Make resize listener object unfocusable ([#3206](https://github.com/sveltejs/svelte/issues/3206))
## 3.6.6
* Prevent dynamic components being detached twice ([#3113](https://github.com/sveltejs/svelte/issues/3113), [#2086](https://github.com/sveltejs/svelte/issues/2086))
## 3.6.5
* Handle RxJS-style observables with `get` ([#3153](https://github.com/sveltejs/svelte/issues/3153))
* Pass `let` values to bindings ([#3140](https://github.com/sveltejs/svelte/issues/3140))
* Escape `@` symbols in props ([#3173](https://github.com/sveltejs/svelte/issues/3173))
* Scale crossfaded elements ([#3175](https://github.com/sveltejs/svelte/pull/3175))
## 3.6.4
* Run `onMount` functions in correct order, and before initial `afterUpdate` functions ([#2281](https://github.com/sveltejs/svelte/issues/2281))
* Fix code transformation for shorthand methods ([#2906](https://github.com/sveltejs/svelte/issues/2906))
* Fix assignments in inline functions ([#3038](https://github.com/sveltejs/svelte/issues/3038))
## 3.6.3
* Fix await block mounting inside removed if block ([#1496](https://github.com/sveltejs/svelte/issues/1496))
* Update when element references are removed ([#2034](https://github.com/sveltejs/svelte/issues/2034))
* Don't attempt to serialize non-string values in server-rendered bindings ([#2135](https://github.com/sveltejs/svelte/issues/2135))
* Recognise dependencies in function expressions ([#2693](https://github.com/sveltejs/svelte/issues/2693))
* Scope pseudo-class selectors without class/type ([#1705](https://github.com/sveltejs/svelte/issues/1705))
* Allow nested at-rules ([#3135](https://github.com/sveltejs/svelte/issues/3135))
* Allow attributes to contain `=` characters ([#3149](https://github.com/sveltejs/svelte/pull/3149))
## 3.6.2
* Fix placement of each-else block ([#2917](https://github.com/sveltejs/svelte/issues/2917))
* Make context accessible to `bind:this` ([#2806](https://github.com/sveltejs/svelte/issues/2806))
* Pass hoisted values to slots ([#2586](https://github.com/sveltejs/svelte/issues/2586))
## 3.6.1
* Fix escaping of `@` in dev mode debug filename ([#3114](https://github.com/sveltejs/svelte/pull/3114))
## 3.6.0
* Add `innerHTML` and `textContent` bindings for `contenteditable` elements ([#2996](https://github.com/sveltejs/svelte/pull/2996))
* Fix destructuring assignments where targets are member expressions ([#3092](https://github.com/sveltejs/svelte/issues/3092))
* Deconflict with used globals ([#2963](https://github.com/sveltejs/svelte/pull/2963))
* Always run `onDestroy` functions, not just for detaching components ([#3058](https://github.com/sveltejs/svelte/issues/3058))
* Fix scope analysis around catch clauses ([#3064](https://github.com/sveltejs/svelte/issues/3064))
* Add error constructors to known globals ([#3064](https://github.com/sveltejs/svelte/issues/3064))
* Always bail out of hoisting on encountering local state in function definition ([#3044](https://github.com/sveltejs/svelte/issues/3044))
* Fix incorrect merging of top-level text nodes ([#3027](https://github.com/sveltejs/svelte/issues/3027))
* Handle removal of components in each blocks without props ([#3035](https://github.com/sveltejs/svelte/issues/3035))
* Only call subscriber once when resubscribing to a store ([#3022](https://github.com/sveltejs/svelte/issues/3022))
* Check for existence of dynamic component before introing ([#3054](https://github.com/sveltejs/svelte/issues/3054))
* Sanitize names of bubbled event handlers ([#2923](https://github.com/sveltejs/svelte/issues/2923))
## 3.5.4
* Preserve whitespace at the boundaries of `{#each}` blocks ([#713](https://github.com/sveltejs/svelte/issues/713))
* Fix dynamic `bind:this` on components ([#2333](https://github.com/sveltejs/svelte/issues/2333))
* Fix binding to values in a component when it uses `$$props` ([#2725](https://github.com/sveltejs/svelte/issues/2725))
* Fix parsing ambiguous HTML entities ([#3071](https://github.com/sveltejs/svelte/pull/3071))
## 3.5.3
* Don't double-destroy keyed each blocks with outros ([#3055](https://github.com/sveltejs/svelte/issues/3055))
## 3.5.2
* Prevent duplicated outros causing errors ([#3001](https://github.com/sveltejs/svelte/issues/3001))
* Fix automatic name generation ([#2843](https://github.com/sveltejs/svelte/issues/2843))
* Fix .d.ts stubs ([#3009](https://github.com/sveltejs/svelte/pull/3009))
* Don't strip non-breaking spaces ([#3014](https://github.com/sveltejs/svelte/issues/3014))
* Fix `requestAnimationFrame` context ([#2933](https://github.com/sveltejs/svelte/issues/2933))
* Allow space before attribute value ([#3026](https://github.com/sveltejs/svelte/issues/3026))
* Remove null/undefined attributes ([#1434](https://github.com/sveltejs/svelte/issues/1434))
* Fix whitespace in static markup ([#3030](https://github.com/sveltejs/svelte/pull/3030))
## 3.5.1
* Accommodate webpack idiosyncracies
## 3.5.0
* Update package folder structure ([#2887](https://github.com/sveltejs/svelte/pull/2887))
* Support `once` modifier on component events ([#2654](https://github.com/sveltejs/svelte/issues/2654))
* Allow empty `<title>` tags ([#2980](https://github.com/sveltejs/svelte/issues/2980))
* Render textarea binding values inside element ([#2975](https://github.com/sveltejs/svelte/pull/2975))
* Fix delayed animation glitch ([#2871](https://github.com/sveltejs/svelte/issues/2871))
* Solve diamond dependencies problem with stores ([#2660](https://github.com/sveltejs/svelte/issues/2660))
* Fix missing outros inside each blocks ([#2689](https://github.com/sveltejs/svelte/issues/2689))
* Support animations without transitions ([#2908](https://github.com/sveltejs/svelte/issues/2908))
* Add missing transition events ([#2912](https://github.com/sveltejs/svelte/pull/2912))
## 3.4.4
* Publish type declaration files ([#2874](https://github.com/sveltejs/svelte/issues/2874))
* Don't trigger updates for unreferenced values ([#2865](https://github.com/sveltejs/svelte/pull/2865))
* Omit readonly bindings from SSR output ([#2339](https://github.com/sveltejs/svelte/issues/2339))
* Prevent outdated animation CSS ([#2871](https://github.com/sveltejs/svelte/issues/2871))
* Repair dynamic `{@html ...}` in head ([#2880](https://github.com/sveltejs/svelte/pull/2880))
* Don't create unknown prop warnings for internal props, or if component has `$$props` ([#2881](https://github.com/sveltejs/svelte/pull/2881))
## 3.4.3
* Add type declaration files for everything ([#2842](https://github.com/sveltejs/svelte/pull/2842))
* Prevent `svelte/store` being bundled ([#2786](https://github.com/sveltejs/svelte/issues/2786))
* Warn on unknown props in dev mode ([#2840](https://github.com/sveltejs/svelte/pull/2840))
* Treat `requestAnimationFrame` as a no-op on the server ([#2856](https://github.com/sveltejs/svelte/pull/2856))
* Add `raw` property to AST's `Text` nodes ([#2714](https://github.com/sveltejs/svelte/issues/2714))
* Add `<details bind:open>` ([#2854](https://github.com/sveltejs/svelte/issues/2854))
## 3.4.2
* Use empty string for empty data attributes ([#2804](https://github.com/sveltejs/svelte/pull/2804))
* Support `customElement: true` with no `<svelte:options>` ([#2821](https://github.com/sveltejs/svelte/issues/2821))
* Add docstrings to `svelte/store` ([#2795](https://github.com/sveltejs/svelte/pull/2795))
## 3.4.1
* Handle non-falsy non-function return values from derivers ([#2780](https://github.com/sveltejs/svelte/issues/2780))
* Allow `spring` to work server-side ([#2773](https://github.com/sveltejs/svelte/issues/2773))
## 3.4.0
* Allow custom element to be defined without a `tag` ([#2417](https://github.com/sveltejs/svelte/issues/2417))
* Fix parsing of quote marks inside attribute values ([#2715](https://github.com/sveltejs/svelte/pull/2754))
* Convert `svelte/store` to TypeScript ([#2733](https://github.com/sveltejs/svelte/pull/2733))
* Allow `debug` tags to include hoisted values ([#2764](https://github.com/sveltejs/svelte/issues/2764))
* Parse error if attribute name is missing `=` ([#1513](https://github.com/sveltejs/svelte/pull/2770))
* Allow reactive declarations to depend on mutated `const` values ([#2728](https://github.com/sveltejs/svelte/issues/2728))
## 3.3.0
* Allow multiple event listeners on a single node ([#2688](https://github.com/sveltejs/svelte/issues/2688))
* Allow derivers to return a cleanup function ([#2553](https://github.com/sveltejs/svelte/issues/2553))
* Support namespaced components (`<Foo.Bar/>`) ([#2743](https://github.com/sveltejs/svelte/pull/2743))
## 3.2.2
* Add `window` and `document` to expected globals ([#2722](https://github.com/sveltejs/svelte/pull/2722))
* Prevent hoisting of functions that depend on reactive state ([#2703](https://github.com/sveltejs/svelte/pull/2703))
* Generate correct code when slot has no changes ([#2697](https://github.com/sveltejs/svelte/issues/2697))
* Prevent `Object.prototype`-related bugs ([#2696](https://github.com/sveltejs/svelte/pull/2696))
## 3.2.1
* Use same comparison logic for `derived` as for other stores ([#2644](https://github.com/sveltejs/svelte/issues/2644))
* Invalidate dependencies of reactive declarations ([#2444](https://github.com/sveltejs/svelte/issues/2444))
* Fix instrumentation of auto-subscription self-assignments ([#2681](https://github.com/sveltejs/svelte/issues/2681))
* Warn on non-top-level or module-context statements labeled with `$:` ([#2176](https://github.com/sveltejs/svelte/issues/2176))
## 3.2.0
* Improve `spring` animations, and add `hard`/`soft` options ([#2627](https://github.com/sveltejs/svelte/pull/2627))
* Expose `parse` and `walk` functions ([#2661](https://github.com/sveltejs/svelte/issues/2661), [#2534](https://github.com/sveltejs/svelte/pull/2534))
* Support array/object rest in `each` block destructuring patterns ([#2647](https://github.com/sveltejs/svelte/issues/2647), [#2658](https://github.com/sveltejs/svelte/pull/2658))
* Use `setAttribute` to change `form` property on form elements ([#1742](https://github.com/sveltejs/svelte/issues/1742))
* Fix a11y warning when `<figcaption>` is non-direct descendant of `<figure>` ([#2582](https://github.com/sveltejs/svelte/issues/2582))
* Squelch erroneous 'empty block' warnings ([#1716](https://github.com/sveltejs/svelte/issues/1716))
* Fix IE9/10 error with `insertBefore` ([#2573](https://github.com/sveltejs/svelte/issues/2573))
* Prevent `$$scope` from being spread onto an element ([#2520](https://github.com/sveltejs/svelte/issues/2520))
* Resubscribe to stores that are assigned to in `<script>` ([#2435](https://github.com/sveltejs/svelte/issues/2435))
* Allow reactive declarations to depend on `const` variables ([#2285](https://github.com/sveltejs/svelte/issues/2285))
* Trigger store changes on UpdateExpression ([#2625](https://github.com/sveltejs/svelte/issues/2625))
* Squelch missing prop warning if variable is initialised ([#2635](https://github.com/sveltejs/svelte/issues/2635))
* Add `alert`, `confirm` and `prompt` to known globals ([#2648](https://github.com/sveltejs/svelte/issues/2648))
## 3.1.0
* Allow store subscribe functions to return an object with an `unsubscribe` method, providing native RxJS support ([#2549](https://github.com/sveltejs/svelte/issues/2549))
## 3.0.1
* Prevent text input cursor jumping in Safari ([#2506](https://github.com/sveltejs/svelte/issues/2506))
* Allow assignments to member expressions ([#2510](https://github.com/sveltejs/svelte/issues/2510))
* Prevent mutually dependent functions causing an infinite during hoisting ([#2542](https://github.com/sveltejs/svelte/issues/2542))
* Reuse scheduler promise instead of creating new one each time ([#2555](https://github.com/sveltejs/svelte/pull/2555))
* Various site/docs fixes
## 3.0.0
* Everything

@ -0,0 +1,138 @@
# Contributing to Svelte
Svelte is a new way to build web applications. It's a compiler that takes your declarative components and converts them into efficient JavaScript that surgically updates the DOM.
The [Open Source Guides](https://opensource.guide/) website has a collection of resources for individuals, communities, and companies. These resources help people who want to learn how to run and contribute to open source projects. Contributors and people new to open source alike will find the following guides especially useful:
* [How to Contribute to Open Source](https://opensource.guide/how-to-contribute/)
* [Building Welcoming Communities](https://opensource.guide/building-community/)
## Get involved
There are many ways to contribute to Svelte, and many of them do not involve writing any code. Here's a few ideas to get started:
- Simply start using Svelte. Go through the [Getting Started](https://svelte.dev/blog/the-easiest-way-to-get-started) guide. Does everything work as expected? If not, we're always looking for improvements. Let us know by [opening an issue](#reporting-new-issues).
- Look through the [open issues](https://github.com/sveltejs/svelte/issues). Provide workarounds, ask for clarification, or suggest labels. Help [triage issues](#triaging-issues-and-pull-requests).
- If you find an issue you would like to fix, [open a pull request](#your-first-pull-request).
- Read through our [tutorials](https://svelte.dev/tutorial/basics). If you find anything that is confusing or can be improved, you can make edits by clicking "Edit this chapter" at the bottom left of the tutorial page.
- Take a look at the [features requested](https://github.com/sveltejs/svelte/labels/enhancement) by others in the community and consider opening a pull request if you see something you want to work on.
Contributions are very welcome. If you think you need help planning your contribution, please ping us on Discord at [svelte.dev/chat](https://svelte.dev/chat) and let us know you are looking for a bit of help.
### Triaging issues and pull requests
One great way you can contribute to the project without writing any code is to help triage issues and pull requests as they come in.
- Ask for more information if you believe the issue does not provide all the details required to solve it.
- Suggest [labels](https://github.com/sveltejs/svelte/labels) that can help categorize issues.
- Flag issues that are stale or that should be closed.
- Ask for test plans and review code.
## Bugs
We use [GitHub issues](https://github.com/sveltejs/svelte/issues) for our public bugs. If you would like to report a problem, take a look around and see if someone already opened an issue about it. If you are certain this is a new unreported bug, you can submit a [bug report](#reporting-new-issues).
If you have questions about using Svelte, contact us on Discord at [svelte.dev/chat](https://svelte.dev/chat), and we will do our best to answer your questions.
If you see anything you'd like to be implemented, create a [feature request issue](https://github.com/sveltejs/svelte/issues/new?template=feature_request.md)
## Reporting new issues
When [opening a new issue](https://github.com/sveltejs/svelte/issues/new/choose), always make sure to fill out the issue template. **This step is very important!** Not doing so may result in your issue not being managed in a timely fashion. Don't take this personally if this happens, and feel free to open a new issue once you've gathered all the information required by the template.
- **One issue, one bug:** Please report a single bug per issue.
- **Provide reproduction steps:** List all the steps necessary to reproduce the issue. The person reading your bug report should be able to follow these steps to reproduce your issue with minimal effort. If possible, use the [REPL](https://svelte.dev/repl) to create your reproduction.
## Installation
1. Ensure you have [npm](https://www.npmjs.com/get-npm) installed.
1. After cloning the repository, run `npm install` in the root of the repository.
1. To start a development server, run `npm run dev`.
## Pull requests
### Your first pull request
So you have decided to contribute code back to upstream by opening a pull request. You've invested a good chunk of time, and we appreciate it. We will do our best to work with you and get the PR looked at.
Working on your first Pull Request? You can learn how from this free video series:
[**How to Contribute to an Open Source Project on GitHub**](https://egghead.io/courses/how-to-contribute-to-an-open-source-project-on-github)
### Proposing a change
If you would like to request a new feature or enhancement but are not yet thinking about opening a pull request, you can also file an issue with [feature template](https://github.com/sveltejs/svelte/issues/new?template=feature_request.md).
If you're only fixing a bug, it's fine to submit a pull request right away but we still recommend that you file an issue detailing what you're fixing. This is helpful in case we don't accept that specific fix but want to keep track of the issue.
### Sending a pull request
Small pull requests are much easier to review and more likely to get merged. Make sure the PR does only one thing, otherwise please split it.
Please make sure the following is done when submitting a pull request:
1. Fork [the repository](https://github.com/sveltejs/svelte) and create your branch from `master`.
1. Describe your **test plan** in your pull request description. Make sure to test your changes.
1. Make sure your code lints (`npm run lint`).
1. Make sure your tests pass (`npm run test`).
All pull requests should be opened against the `master` branch.
#### Test plan
A good test plan has the exact commands you ran and their output, provides screenshots or videos if the pull request changes UI.
- If you've changed APIs, update the documentation.
#### Writing tests
All tests are located in `/test` folder.
Test samples are kept in `/test/xxx/samples` folder.
#### Running tests
1. To run test, run `npm run test`
1. To run test for a specific feature, you can use the `-g` (aka `--grep`) option. For example, to only run test involving transitions, run `npm run test -- -g transition`.
##### Running solo test
1. To run only one test, rename the test sample folder to end with `.solo`. For example, to run the `test/js/samples/action` only, rename it to `test/js/samples/action.solo`.
1. To run only one test suite, rename the test suite folder to end with `.solo`. For example, to run the `test/js` test suite only, rename it to `test/js.solo`.
1. Remember to rename the test folder back. The CI will fail if there's a solo test.
##### Updating `.expected` files
1. Tests suites like `css`, `js`, `server-side-rendering` asserts that the generated output has to match the content in the `.expected` file. For example, in the `js` test suites, the generated js code is compared against the content in `expected.js`.
1. To update the content of the `.expected` file, run the test with `--update` flag. (`npm run test --update`)
#### Breaking changes
When adding a new breaking change, follow this template in your pull request:
```md
### New breaking change here
- **Who does this affect**:
- **How to migrate**:
- **Why make this breaking change**:
- **Severity (number of people affected x effort)**:
```
### What happens next?
The core Svelte team will be monitoring for pull requests. Do help us by making your pull request easy to review by following the guidelines above.
## Style guide
[Eslint](https://eslint.org) will catch most styling issues that may exist in your code. You can check the status of your code styling by simply running `npm run lint`.
### Code conventions
- `snake_case` for internal variable names and methods
- `camelCase` for public variable names and methods.
## License
By contributing to Svelte, you agree that your contributions will be licensed under its [MIT license](https://github.com/sveltejs/svelte/blob/master/LICENSE).

@ -1,4 +1,4 @@
Copyright (c) 2016 [these people](https://github.com/sveltejs/svelte/graphs/contributors)
Copyright (c) 2016-20 [these people](https://github.com/sveltejs/svelte/graphs/contributors)
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

@ -1,6 +1,19 @@
<p align="center">
<p>
<a href="https://svelte.dev">
<img alt="Cybernetically enhanced web apps: Svelte" src="https://svelte-assets.surge.sh/banner.png">
<img alt="Cybernetically enhanced web apps: Svelte" src="https://sveltejs.github.io/assets/banner.png">
</a>
<a href="https://www.npmjs.com/package/svelte">
<img src="https://img.shields.io/npm/v/svelte.svg" alt="npm version">
</a>
<a href="https://github.com/sveltejs/svelte/actions">
<img src="https://github.com/sveltejs/svelte/workflows/CI/badge.svg?branch=master"
alt="build status">
</a>
<a href="https://github.com/sveltejs/svelte/blob/master/LICENSE">
<img src="https://img.shields.io/npm/l/svelte.svg" alt="license">
</a>
</p>
@ -9,7 +22,7 @@
Svelte is a new way to build web applications. It's a compiler that takes your declarative components and converts them into efficient JavaScript that surgically updates the DOM.
Learn more at the [Svelte website](https://svelte.dev), or stop by the [Discord chatroom](https://discord.gg/yy75DKs).
Learn more at the [Svelte website](https://svelte.dev), or stop by the [Discord chatroom](https://svelte.dev/chat).
## Development
@ -19,11 +32,16 @@ Pull requests are encouraged and always welcome. [Pick an issue](https://github.
To install and work on Svelte locally:
```bash
git clone git@github.com:sveltejs/svelte.git
git clone https://github.com/sveltejs/svelte.git
cd svelte
npm install
```
> Many tests depend on newlines being preserved as `<LF>`. On Windows, you can ensure this by cloning with:
> ```bash
> git -c core.autocrlf=false clone https://github.com/sveltejs/svelte.git
> ```
To build the compiler, and all the other modules included in the package:
```bash
@ -36,7 +54,7 @@ To watch for changes and continually rebuild the package (this is useful if you'
npm run dev
```
The compiler is written in [TypeScript](https://www.typescriptlang.org/), but don't let that put you off — it's basically just JavaScript with type annotations. You'll pick it up in no time. If you're using an editor other than [VSCode](https://code.visualstudio.com/) you may need to install a plugin in order to get syntax highlighting and code hints etc.
The compiler is written in [TypeScript](https://www.typescriptlang.org/), but don't let that put you off — it's basically just JavaScript with type annotations. You'll pick it up in no time. If you're using an editor other than [Visual Studio Code](https://code.visualstudio.com/) you may need to install a plugin in order to get syntax highlighting and code hints etc.
### Running Tests
@ -54,11 +72,11 @@ npm run test -- -g transition
## svelte.dev
The source code for https://svelte.dev, including all the documentation, lives in the [site](site) directory. The site is built with [Sapper](https://sapper.svelte.technology) To develop locally:
The source code for https://svelte.dev, including all the documentation, lives in the [site](site) directory. The site is built with [Sapper](https://sapper.svelte.dev). To develop locally:
```bash
cd site
npm install
npm install && npm run update
npm run dev
```

@ -1,25 +0,0 @@
import { cubicOut } from './easing';
import { is_function } from './internal';
export function flip(node, animation, params) {
const style = getComputedStyle(node);
const transform = style.transform === 'none' ? '' : style.transform;
const dx = animation.from.left - animation.to.left;
const dy = animation.from.top - animation.to.top;
const d = Math.sqrt(dx * dx + dy * dy);
const {
delay = 0,
duration = d => Math.sqrt(d) * 120,
easing = cubicOut
} = params;
return {
delay,
duration: is_function(duration) ? duration(d) : duration,
easing,
css: (t, u) => `transform: ${transform} translate(${u * dx}px, ${u * dy}px);`
};
}

@ -1,30 +0,0 @@
# http://www.appveyor.com/docs/appveyor-yml
version: "{build}"
clone_depth: 10
init:
- git config --global core.autocrlf false
environment:
matrix:
# node.js
- nodejs_version: 10
install:
- ps: Install-Product node $env:nodejs_version
- npm install
build: off
test_script:
- node --version && npm --version
- npm test
matrix:
fast_finish: false
# cache:
# - C:\Users\appveyor\AppData\Roaming\npm-cache -> package.json # npm cache
# - node_modules -> package.json # local npm modules

@ -1,10 +0,0 @@
export {
onMount,
onDestroy,
beforeUpdate,
afterUpdate,
setContext,
getContext,
tick,
createEventDispatcher
} from './internal';

@ -1,4 +1,3 @@
--compilers ts-node/register
--require source-map-support/register
--full-trace
--recursive

4011
package-lock.json generated

File diff suppressed because it is too large Load Diff

@ -1,37 +1,43 @@
{
"name": "svelte",
"version": "3.0.0",
"version": "3.18.2",
"description": "Cybernetically enhanced web apps",
"module": "index.mjs",
"main": "index",
"files": [
"compiler.js",
"types",
"compiler.*",
"register.js",
"index.*",
"internal.*",
"store.*",
"animate.*",
"transition.*",
"easing.*",
"motion.*",
"internal",
"store",
"animate",
"transition",
"easing",
"motion",
"svelte",
"README.md"
],
"engines": {
"node": ">= 8"
},
"types": "types/runtime/index.d.ts",
"scripts": {
"test": "mocha --opts mocha.opts",
"test:unit": "mocha --require sucrase/register --recursive ./**/__test__.ts",
"test:unit": "mocha --require sucrase/register --recursive src/**/__test__.ts",
"quicktest": "mocha --opts mocha.opts",
"precoverage": "c8 mocha --opts mocha.coverage.opts",
"coverage": "c8 report --reporter=text-lcov > coverage.lcov && c8 report --reporter=html",
"codecov": "codecov",
"precodecov": "npm run coverage",
"lint": "eslint src test/*.js",
"build": "rollup -c",
"build": "rollup -c && npm run tsd",
"prepare": "npm run build",
"dev": "rollup -cw",
"pretest": "npm run build",
"posttest": "agadoo src/internal/index.js",
"prepublishOnly": "export PUBLISH=true && npm run lint && npm test"
"posttest": "agadoo internal/index.mjs",
"prepublishOnly": "npm run lint && PUBLISH=true npm test",
"tsd": "tsc -p src/compiler --emitDeclarationOnly && tsc -p src/runtime --emitDeclarationOnly",
"lint": "eslint \"{src,test}/**/*.{ts,js}\""
},
"repository": {
"type": "git",
@ -50,40 +56,41 @@
},
"homepage": "https://github.com/sveltejs/svelte#README",
"devDependencies": {
"@sveltejs/svelte-repl": "0.0.5",
"@types/mocha": "^5.2.0",
"@types/node": "^10.5.5",
"acorn": "^6.1.1",
"acorn-dynamic-import": "^4.0.0",
"agadoo": "^1.0.1",
"c8": "^3.4.0",
"codecov": "^3.0.0",
"@rollup/plugin-commonjs": "^11.0.0",
"@rollup/plugin-json": "^4.0.1",
"@rollup/plugin-node-resolve": "^6.0.0",
"@rollup/plugin-replace": "^2.3.0",
"@rollup/plugin-sucrase": "^3.0.0",
"@rollup/plugin-typescript": "^2.0.1",
"@rollup/plugin-virtual": "^2.0.0",
"@types/mocha": "^5.2.7",
"@types/node": "^8.10.53",
"@typescript-eslint/eslint-plugin": "^1.13.0",
"@typescript-eslint/parser": "^2.1.0",
"acorn": "^7.1.0",
"agadoo": "^1.1.0",
"c8": "^5.0.1",
"code-red": "0.1.1",
"codecov": "^3.5.0",
"css-tree": "1.0.0-alpha22",
"eslint": "^5.3.0",
"eslint-plugin-html": "^5.0.0",
"eslint-plugin-import": "^2.11.0",
"estree-walker": "^0.6.0",
"is-reference": "^1.1.1",
"jsdom": "^12.2.0",
"kleur": "^3.0.0",
"eslint": "^6.3.0",
"eslint-plugin-import": "^2.18.2",
"eslint-plugin-svelte3": "^2.7.3",
"estree-walker": "^1.0.0",
"is-reference": "^1.1.4",
"jsdom": "^15.1.1",
"kleur": "^3.0.3",
"locate-character": "^2.0.5",
"magic-string": "^0.25.2",
"mocha": "^5.2.0",
"puppeteer": "^1.13.0",
"rollup": "^1.1.2",
"rollup-plugin-commonjs": "^9.1.0",
"rollup-plugin-json": "^3.0.0",
"rollup-plugin-node-resolve": "^4.0.0",
"rollup-plugin-replace": "^2.0.0",
"rollup-plugin-sucrase": "^2.1.0",
"rollup-plugin-typescript": "^1.0.0",
"rollup-plugin-virtual": "^1.0.1",
"source-map": "0.6",
"source-map-support": "^0.5.4",
"tiny-glob": "^0.2.1",
"ts-node": "^8.0.2",
"tslib": "^1.8.0",
"typescript": "^3.0.1"
"magic-string": "^0.25.3",
"mocha": "^6.2.0",
"periscopic": "^2.0.1",
"puppeteer": "^1.19.0",
"rollup": "^1.27.14",
"source-map": "^0.7.3",
"source-map-support": "^0.5.13",
"tiny-glob": "^0.2.6",
"tslib": "^1.10.0",
"typescript": "^3.5.3"
},
"nyc": {
"include": [

@ -2,7 +2,7 @@ const fs = require('fs');
const path = require('path');
const { compile } = require('./compiler.js');
let extensions = ['.svelte', '.html'];
const extensions = ['.svelte', '.html'];
let compileOptions = {};
function capitalise(name) {
@ -25,8 +25,7 @@ function deregisterExtension(extension) {
function registerExtension(extension) {
require.extensions[extension] = function(module, filename) {
const name = path.basename(filename)
.slice(0, -path.extname(filename).length)
const name = path.parse(filename).name
.replace(/^\d/, '_$&')
.replace(/[^a-zA-Z0-9_$]/g, '');

@ -1,44 +1,93 @@
import fs from 'fs';
import replace from 'rollup-plugin-replace';
import resolve from 'rollup-plugin-node-resolve';
import commonjs from 'rollup-plugin-commonjs';
import json from 'rollup-plugin-json';
import sucrase from 'rollup-plugin-sucrase';
import typescript from 'rollup-plugin-typescript';
import replace from '@rollup/plugin-replace';
import resolve from '@rollup/plugin-node-resolve';
import commonjs from '@rollup/plugin-commonjs';
import json from '@rollup/plugin-json';
import sucrase from '@rollup/plugin-sucrase';
import typescript from '@rollup/plugin-typescript';
import pkg from './package.json';
const is_publish = !!process.env.PUBLISH;
const ts_plugin = is_publish
? typescript({
include: 'src/**',
typescript: require('typescript')
})
: sucrase({
transforms: ['typescript']
});
const external = id => id.startsWith('svelte/');
fs.writeFileSync(`./compiler.d.ts`, `export { compile, parse, preprocess, VERSION } from './types/compiler/index';`);
export default [
/* internal.[m]js */
/* runtime */
{
input: `src/internal/index.js`,
input: `src/runtime/index.ts`,
output: [
{
file: `internal.mjs`,
file: `index.mjs`,
format: 'esm',
paths: id => id.startsWith('svelte/') && id.replace('svelte', '.')
paths: id => id.startsWith('svelte/') && `${id.replace('svelte', '.')}`
},
{
file: `internal.js`,
file: `index.js`,
format: 'cjs',
paths: id => id.startsWith('svelte/') && id.replace('svelte', '.')
paths: id => id.startsWith('svelte/') && `${id.replace('svelte', '.')}`
}
],
external: id => id.startsWith('svelte/'),
plugins: [{
generateBundle(options, bundle) {
const mod = bundle['internal.mjs'];
if (mod) {
fs.writeFileSync('src/compile/internal-exports.ts', `// This file is automatically generated\nexport default new Set(${JSON.stringify(mod.exports)});`);
}
}
}]
external,
plugins: [ts_plugin]
},
...fs.readdirSync('src/runtime')
.filter(dir => fs.statSync(`src/runtime/${dir}`).isDirectory())
.map(dir => ({
input: `src/runtime/${dir}/index.ts`,
output: [
{
file: `${dir}/index.mjs`,
format: 'esm',
paths: id => id.startsWith('svelte/') && `${id.replace('svelte', '..')}`
},
{
file: `${dir}/index.js`,
format: 'cjs',
paths: id => id.startsWith('svelte/') && `${id.replace('svelte', '..')}`
}
],
external,
plugins: [
replace({
__VERSION__: pkg.version
}),
ts_plugin,
{
writeBundle(bundle) {
if (dir === 'internal') {
const mod = bundle['index.mjs'];
if (mod) {
fs.writeFileSync('src/compiler/compile/internal_exports.ts', `// This file is automatically generated\nexport default new Set(${JSON.stringify(mod.exports)});`);
}
}
fs.writeFileSync(`${dir}/package.json`, JSON.stringify({
main: './index',
module: './index.mjs',
types: './index.d.ts'
}, null, ' '));
fs.writeFileSync(`${dir}/index.d.ts`, `export * from '../types/runtime/${dir}/index';`);
}
}
]
})),
/* compiler.js */
{
input: 'src/index.ts',
input: 'src/compiler/index.ts',
plugins: [
replace({
__VERSION__: pkg.version
@ -48,15 +97,7 @@ export default [
include: ['node_modules/**']
}),
json(),
is_publish
? typescript({
include: 'src/**',
exclude: 'src/internal/**',
typescript: require('typescript')
})
: sucrase({
transforms: ['typescript']
})
ts_plugin
],
output: {
file: 'compiler.js',
@ -67,34 +108,5 @@ export default [
external: is_publish
? []
: id => id === 'acorn' || id === 'magic-string' || id.startsWith('css-tree')
},
/* motion.mjs */
{
input: `src/motion/index.js`,
output: [
{
file: `motion.mjs`,
format: 'esm',
paths: id => id.startsWith('svelte/') && id.replace('svelte', '.')
},
{
file: `motion.js`,
format: 'cjs',
paths: id => id.startsWith('svelte/') && id.replace('svelte', '.')
}
],
external: id => id.startsWith('svelte/')
},
// everything else
...['index', 'store', 'easing', 'transition', 'animate'].map(name => ({
input: `${name}.mjs`,
output: {
file: `${name}.js`,
format: 'cjs',
paths: id => id.startsWith('svelte/') && id.replace('svelte', '.')
},
external: id => id !== `${name}.mjs`
}))
}
];

@ -0,0 +1,13 @@
NODE_ENV=
PORT=
BASEURL=
GITHUB_CLIENT_ID=
GITHUB_CLIENT_SECRET=
MAPBOX_ACCESS_TOKEN=
PGHOST=hostname
PGPORT=port
PGUSER=username
PGPASSWORD=password
PGDATABASE=database_name

@ -0,0 +1,58 @@
module.exports = {
root: true,
rules: {
indent: [2, 'tab', { SwitchCase: 1 }],
semi: [2, 'always'],
'keyword-spacing': [2, { before: true, after: true }],
'space-before-blocks': [2, 'always'],
'no-mixed-spaces-and-tabs': [2, 'smart-tabs'],
'no-cond-assign': 0,
'no-unused-vars': 2,
'object-shorthand': [2, 'always'],
'no-const-assign': 2,
'no-class-assign': 2,
'no-this-before-super': 2,
'no-var': 2,
'no-unreachable': 2,
'valid-typeof': 2,
'quote-props': [2, 'as-needed'],
'one-var': [2, 'never'],
'prefer-arrow-callback': 2,
'prefer-const': [2, { destructuring: 'all' }],
'arrow-spacing': 2,
'no-inner-declarations': 0,
'require-atomic-updates': 0
},
env: {
es6: true,
browser: true,
node: true,
mocha: true
},
extends: [
'eslint:recommended',
'plugin:import/errors',
'plugin:import/warnings'
],
plugins: ['svelte3'],
overrides: [
{
files: ['*.svelte'],
processor: 'svelte3/svelte3'
}
],
parserOptions: {
ecmaVersion: 9,
sourceType: 'module'
},
settings: {
'import/core-modules': ['svelte'],
'svelte3/compiler': (() => {
try {
return require('svelte/compiler');
} catch (e) {
return null;
}
})()
}
};

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

@ -1,4 +1,7 @@
FROM mhart/alpine-node:11.14
# IMPORTANT: Don't use this Dockerfile in your own Sapper projects without also looking at the .dockerignore file.
# Without an appropriate .dockerignore, this Dockerfile will copy a large number of unneeded files into your image.
FROM mhart/alpine-node:12
# install dependencies
WORKDIR /app
@ -9,7 +12,7 @@ RUN npm ci --production
# Only copy over the Node pieces we need
# ~> Saves 35MB
###
FROM mhart/alpine-node:base-11.14
FROM mhart/alpine-node:slim-12
WORKDIR /app
COPY --from=0 /app .

@ -14,9 +14,9 @@ sapper:
docker:
@echo "\n~> building docker image"
@gcloud builds submit -t $(IMAGE)
@gcloud builds submit --project $(PROJECT) -t $(IMAGE)
deploy: sapper docker
@echo "\n~> deploying $(SERVICE) to Cloud Run servers"
@gcloud beta run deploy $(SERVICE) --allow-unauthenticated --region us-central1 --image $(IMAGE) --memory=512Mi
@gcloud run deploy $(SERVICE) --project $(PROJECT) --allow-unauthenticated --platform managed --region us-central1 --image $(IMAGE) --memory=512Mi

@ -4,7 +4,10 @@ Set up the project:
```bash
git clone https://github.com/sveltejs/svelte.git
cd svelte/site
cd svelte
npm ci
PUBLISH=1 npm run build
cd site
npm ci
npm run update
```
@ -13,20 +16,35 @@ Start the server with `npm run dev`, and navigate to [localhost:3000](http://loc
## Using a local copy of Svelte
By default, the REPL will fetch the most recent version of Svelte from https://unpkg.com/svelte. To use the local copy of the compiler and runtime from this repo, you can navigate to [localhost:3000/repl?version=local](http://localhost:3000/repl?version=local). To produce the proper browser-compatible UMD build, you will need to run `npm run build` with the `PUBLISH` environment variable set (to any non-empty string).
By default, the REPL will fetch the most recent version of Svelte from https://unpkg.com/svelte. When running the site locally, you can also use your local copy of Svelte.
To produce the proper browser-compatible UMD build of the compiler, you will need to run `npm run build` (or `npm run dev`) in the root of this repository with the `PUBLISH` environment variable set to any non-empty string.
Then visit the REPL at [localhost:3000/repl?version=local](http://localhost:3000/repl?version=local). Please note that the local REPL only works with `npm run dev` and not when building the site for production usage.
## REPL GitHub integration
In order for the REPL's GitHub integration to work properly when running locally, you will need to create a GitHub OAuth app. Set its authorization callback URL to `http://localhost:3000/auth/callback`, and in this project, create `site/.env` containing:
In order for the REPL's GitHub integration to work properly when running locally, you will need to:
- [create a GitHub OAuth app](https://github.com/settings/developers):
- set `Authorization callback URL` to `http://localhost:3000/auth/callback`;
- set `Application name` as you like, and `Homepage URL` as `http://localhost:3000/`;
- create the app and take note of `Client ID` and `Client Secret`
- in this repo, create `site/.env` containing:
```
GITHUB_CLIENT_ID=[your app's Client ID]
GITHUB_CLIENT_SECRET=[your app's Client Secret]
BASEURL=http://localhost:3000
```
## Building the site
```
GITHUB_CLIENT_ID=[your app's client id]
GITHUB_CLIENT_SECRET=[your app's client secret]
BASEURL=http://localhost:3000
```
To build the website, run `npm run sapper`. The output can be found in `__sapper__/build`.
## Testing
Tests can be run using `npm run test`.
## Translating the API docs
Anchors are automatically generated using headings in the documentation and by default (for the english language) they are latinised to make sure the URL is always conforming to RFC3986.
If we need to translate the API documentation to a language using unicode chars, we can setup this app to export the correct anchors by setting up `SLUG_PRESERVE_UNICODE` to `true` and `SLUG_LANG` to the ISO 639-1 two-letter language code of your choice in `config.js`.
If we need to translate the API documentation to a language using unicode chars, we can setup this app to export the correct anchors by setting up `SLUG_PRESERVE_UNICODE` to `true` in `config.js`.

@ -1,3 +1,2 @@
export const SLUG_PRESERVE_UNICODE = false;
export const SLUG_SEPARATOR = '_';
export const SLUG_LANG = 'en';

@ -38,28 +38,23 @@ This will serve your app on [localhost:5000](http://localhost:5000) and rebuild
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):
In the terminal, you can instantly create a new project like so:
```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
npx degit sveltejs/template my-svelte-project
cd my-svelte-project
npm install
npm run dev
```
This will create a new project in the `my-svelte-project` directory, install its dependencies, and start a server on http://localhost:5000.
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
npx 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/tree/v2#api) directly. If you make a project template using one of these tools, please share it with the [Svelte Discord chatroom](https://discord.gg/yy75DKs), or via [@sveltejs](https://twitter.com/sveltejs) on Twitter!
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) (Update from 2019: with Svelte 3 the CLI was deprecated and we now use [sirv-cli](https://www.npmjs.com/package/sirv-cli) in our template. Feel free to use whatever tool you like!) or the [API](https://github.com/sveltejs/svelte/tree/v2#api) directly. If you make a project template using one of these tools, please share it with the [Svelte Discord chatroom](chat), or via [@sveltejs](https://twitter.com/sveltejs) on Twitter!

@ -53,7 +53,7 @@ What happens if we use the new model as a starting point?
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.
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](https://github.com/sveltejs/realworld) takes 39.6kb (11.8kb zipped) to render an interactive homepage.
<aside><p>Code-splitting isn't free — if the reference implementation used code-splitting, it would be larger still</p></aside>
@ -81,4 +81,4 @@ I believe the next frontier of web performance is 'whole-app optimisation'. Curr
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 [Discord](https://discord.gg/yy75DKs).
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 [Discord](chat).

@ -12,7 +12,7 @@ Almost a year after we first started talking about version 2 on the Svelte issue
## tl;dr
Each of these items is described in more depth below. If you get stuck, ask for help in our friendly [Discord chatroom](https://discord.gg/yy75DKs).
Each of these items is described in more depth below. If you get stuck, ask for help in our friendly [Discord chatroom](chat).
- Install Svelte v2 from npm
- Upgrade your templates with [svelte-upgrade](https://github.com/sveltejs/svelte-upgrade)
@ -201,4 +201,4 @@ Before, there was a `svelte.validate` method which checked your component was va
## 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 [Discord chatroom](https://discord.gg/yy75DKs) or raise an issue on the [tracker](https://github.com/sveltejs/svelte/issues).
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 [Discord chatroom](chat) or raise an issue on the [tracker](https://github.com/sveltejs/svelte/issues).

@ -19,7 +19,7 @@ Here, we're using [Emotion](https://emotion.sh) to generate scoped class names t
<div class="max">
<iframe
title="Aphrodite example"
src="/repl/embed?gist=ad495ff5ba9ceefe5984fe62c1f15e19"
src="/repl/embed?example=blog-svelte-css-in-js"
scrolling="no"
></iframe>
</div>
@ -27,4 +27,3 @@ Here, we're using [Emotion](https://emotion.sh) to generate scoped class names t
It's important to note that most CSS-in-JS libraries have a runtime library, and many don't support statically extracting styles out into a separate <code>.css</code> file at build time (which is essential for the best performance). You should therefore only use CSS-in-JS if it's necessary for your application!
Note that you can mix-and-match — you can still use Svelte's built-in CSS handling alongside a CSS-in-JS library.

@ -14,9 +14,8 @@ Earlier this month, I had the privilege of appearing on [The Changelog](https://
...and, most importantly, Svelte 3.
Unless you hang out in our [Discord server](https://discord.gg/yy75DKs) or follow [@sveltejs](https://twitter.com/sveltejs) on Twitter, you might not know that Svelte 3 is just around the corner, and it's going to be a huge release. We've rethought the developer experience from the ground up, and while it *will* be a nuisance if you need to upgrade a Svelte 2 app (more on that soon) we think you're going to love it.
Unless you hang out in our [Discord server](chat) or follow [@sveltejs](https://twitter.com/sveltejs) on Twitter, you might not know that Svelte 3 is just around the corner, and it's going to be a huge release. We've rethought the developer experience from the ground up, and while it *will* be a nuisance if you need to upgrade a Svelte 2 app (more on that soon) we think you're going to love it.
On the podcast [Adam](https://twitter.com/adamstac), [Jerod](https://twitter.com/jerodsanto) and I talk about some of the changes and why we're making them. You can listen here or on the [podcast page](https://changelog.com/podcast/332).
<audio data-theme="night" style="width: 100%" data-src="https://changelog.com/podcast/332/embed" src="https://cdn.changelog.com/uploads/podcast/332/the-changelog-332.mp3" preload="none" class="changelog-episode" controls></audio><p><a href="https://changelog.com/podcast/332">The Changelog 332: A UI framework without the framework</a> Listen on <a href="https://changelog.com/">Changelog.com</a></p><script async src="//cdn.changelog.com/embed.js"></script>

@ -6,8 +6,64 @@ authorURL: https://twitter.com/Rich_Harris
draft: true
---
*Coming soon* This post will walk you through setting up your editor so that recognises Svelte files:
*__Coming soon__*
This post will walk you through setting up your editor so that recognises Svelte files:
* eslint-plugin-svelte3
* svelte-vscode
* associating .svelte files with HTML in VSCode, Sublime, Atom, etc etc etc
* associating .svelte files with HTML in VSCode, Sublime, etc.
## Atom
To treat `*.svelte` files as HTML, open *__Edit → Config...__* and add the following lines to your `core` section:
```cson
"*":
core:
customFileTypes:
"text.html.basic": [
"svelte"
]
```
## Vim/Neovim
To treat all `*.svelte` files as HTML, add the following line to your `init.vim`:
```
au! BufNewFile,BufRead *.svelte set ft=html
```
To temporarily turn on HTML syntax highlighting for the current buffer, use:
```
:set ft=html
```
To set the filetype for a single file, use a [modeline](https://vim.fandom.com/wiki/Modeline_magic):
```
<!-- vim: set ft=html :-->
```
## Visual Studio Code
To treat `*.svelte` files as HTML, add the following lines to your `settings.json` file:
```cson
"files.associations": {
"*.svelte": "html"
}
```
## JetBrains WebStorm
The [Svelte Framework Integration](https://plugins.jetbrains.com/plugin/12375-svelte/) can be used to add support for Svelte to WebStorm, or other Jetbrains IDEs. Consult the [WebStorm plugin installation guide](https://www.jetbrains.com/help/webstorm/managing-plugins.html) on the JetBrains website for more details.
## Sublime Text 3
Open any `.svelte` file.
Go to *__View → Syntax → Open all with current extension as... → HTML__*.

@ -3,7 +3,109 @@ title: Svelte for new developers
description: Never used Node.js or the command line? No problem
author: Rich Harris
authorURL: https://twitter.com/Rich_Harris
draft: true
---
*Coming soon* This blog post will walk you through installing Node.js and git and using Terminal.app to clone a project template and start developing with Svelte
This short guide is designed to help you — someone who has looked at the [tutorial](/tutorial) and wants to start creating Svelte apps, but doesn't have a ton of experience using JavaScript build tooling — get up and running.
If there are things that don't make sense, or that we're glossing over, feel free to [raise an issue](https://github.com/sveltejs/svelte/issues) or [suggest edits to this page](https://github.com/sveltejs/svelte/blob/master/site/content/blog/2019-04-16-svelte-for-new-developers.md) that will help us help more people.
If you get stuck at any point following this guide, the best place to ask for help is in the [chatroom](https://svelte.dev/chat).
## First things first
You'll be using the *command line*, also known as the terminal. On Windows, you can access it by running **Command Prompt** from the Start menu; on a Mac, hit `Cmd` and `Space` together to bring up **Spotlight**, then start typing `Terminal.app`. On most Linux systems, `Ctrl-Alt-T` brings up the command line.
The command line is a way to interact with your computer (or another computer! but that's a topic for another time) with more power and control than the GUI (graphical user interface) that most people use day-to-day.
Once on the command line, you can navigate the filesystem using `ls` to list the contents of your current directory, and `cd` to change the current directory. For example, if you had a `Development` directory of your projects inside your home directory, you would type
```bash
cd Development
```
to go to it. From there, you could create a new project directory with the `mkdir` command:
```bash
mkdir svelte-projects
cd svelte-projects
```
A full introduction to the command line is out of the scope of this guide, but here are a few more useful commands:
* `cd ..` — navigates to the parent of the current directory
* `cat my-file.txt` — on Mac/Linux, lists the contents of `my-file.txt`
* `open .` (or `start .` on Windows) — opens the current directory in Finder or File Explorer
## Installing Node.js
[Node](https://nodejs.org/en/) is a way to run JavaScript on the command line. It's used by many tools, including Svelte. If you don't yet have it installed, the easiest way is to download the latest version straight from the [website](https://nodejs.org/en/).
Once installed, you'll have access to three new commands:
* `node my-file.js` — runs the JavaScript in `my-file.js`
* `npm [subcommand]` — [npm](https://www.npmjs.com/) is a way to install 'packages' that your application depends on, such as the [svelte](https://www.npmjs.com/) package
* `npx [subcommand]` — a convenient way to run programs available on npm without permanently installing them
## Installing a text editor
To write code, you need a good editor. The most popular choice is [Visual Studio Code](https://code.visualstudio.com/) or VSCode, and justifiably so — it's well-designed and fully-featured, and has a wealth of extensions ([including one for Svelte](https://marketplace.visualstudio.com/items?itemName=JamesBirtles.svelte-vscode), which provides syntax highlighting and diagnostic messages when you're writing components).
## Creating a project
We're going to follow the instructions in part two of [The easiest way to get started with Svelte](/blog/the-easiest-way-to-get-started).
First, we'll use npx to run [degit](https://github.com/Rich-Harris/degit), a program for cloning project templates from [GitHub](https://github.com) and other code storage websites. You don't have to use a project template, but it means you have to do a lot less setup work.
(Eventually you'll probably have to learn [git](https://git-scm.com/), which most programmers use to manage their projects. But you don't need to worry about it just yet.)
On the command line, navigate to where you want to create a new project, then type the following lines (you can paste the whole lot, but you'll develop better muscle memory if you get into the habit of writing each line out one at a time then running it):
```bash
npx degit sveltejs/template my-svelte-project
cd my-svelte-project
npm install
```
This creates a new directory, `my-svelte-project`, adds files from the [sveltejs/template](https://github.com/sveltejs/template) code repository, and installs a number of packages from npm. Open the directory in your text editor and take a look around. The app's 'source code' lives in the `src` directory, while the files your app can load are in `public`.
In the `package.json` file, there is a section called `"scripts"`. These scripts define shortcuts for working with your application — `dev`, `build` and `start`. To launch your app in development mode, type the following:
> TODO update the template, it needs... some work
```bash
npm run dev
```
Running the `dev` script starts a program called [Rollup](https://rollupjs.org/guide/en/). Rollup's job is to take your application's source files (so far, just `src/main.js` and `src/App.svelte`), pass them to other programs (including Svelte, in our case) and convert them into the code that will actually run when you open the application in a browser.
Speaking of which, open a browser and navigate to http://localhost:5000. This is your application running on a local *web server* (hence 'localhost') on port 5000.
Try changing `src/App.svelte` and saving it. The application will reload with your changes.
## Building your app
In the last step, we were running the app in 'development mode'. In dev mode, Svelte adds extra code that helps with debugging, and Rollup skips the final step where your app's JavaScript is compressed using [Terser](https://terser.org/).
When you share your app with the world, you want to build it in 'production mode', so that it's as small and efficient as possible for end users. To do that, use the `build` command:
```bash
npm run build
```
Your `public` directory now contains a compressed `bundle.js` file containing your app's JavaScript. You can run it like so:
```bash
npm run start
```
This will run the app on http://localhost:5000.
## Next steps
To share your app with the world you'll need to *deploy* it. There are many ways to do so — some are listed in the `README.md` file inside your project.

@ -42,7 +42,7 @@ Reducing the amount of code you have to write is an explicit goal of Svelte. To
<div class="max">
<iframe
title="Simple component example"
src="/repl/embed?gist=6b573f1819d12defc441098236fb9abe"
src="/repl/embed?example=blog-write-less-code"
scrolling="no"
></iframe>
</div>
@ -159,6 +159,6 @@ In Vue, meanwhile, we have a default export with a `data` function that returns
## Death to boilerplate
These are just some of the ways that Svelte helps you build user interfaces with a minimum of fuss. There are plenty of others — for example, [reactive declarations](https://svelte.dev/tutorial/reactive-declarations) essentially do the work of React's `useMemo`, `useCallback` and `useEffect` without the boilerplate (or indeed the garbage collection overhead of creating inline functions and arrays on each state change).
These are just some of the ways that Svelte helps you build user interfaces with a minimum of fuss. There are plenty of others — for example, [reactive declarations](tutorial/reactive-declarations) essentially do the work of React's `useMemo`, `useCallback` and `useEffect` without the boilerplate (or indeed the garbage collection overhead of creating inline functions and arrays on each state change).
How? By choosing a different set of constraints. Because [Svelte is a compiler](blog/frameworks-without-the-framework), we're not bound to the peculiarities of JavaScript: we can *design* a component authoring experience, rather than having to fit it around the semantics of the language. Paradoxically, this results in *more* idiomatic code — for example using variables naturally rather than via proxies or hooks — while delivering significantly more performant apps.

@ -92,6 +92,6 @@ We don't take this lightly: hopefully once you've experienced Svelte 3 you'll un
## Still to come
As grueling as this release has been, we're nowhere near finished. We have a ton of ideas for generating smarter, more compact code, and a long feature wish-list. [Sapper](https://sapper.svelte.technology), our Next.js-style app framework, is still in the middle of being updated to use Svelte 3. The [Svelte Native](https://svelte-native.technology/) community project, which allows you to write Android and iOS apps in Svelte, is making solid progress but deserves more complete support from core. We don't yet have the bounty of editor extensions, syntax highlighters, component kits, devtools and so on that other frameworks have, and we should fix that. We *really* want to add first-class TypeScript support.
As grueling as this release has been, we're nowhere near finished. We have a ton of ideas for generating smarter, more compact code, and a long feature wish-list. [Sapper](https://sapper.svelte.dev), our Next.js-style app framework, is still in the middle of being updated to use Svelte 3. The [Svelte Native](https://svelte-native.technology/) community project, which allows you to write Android and iOS apps in Svelte, is making solid progress but deserves more complete support from core. We don't yet have the bounty of editor extensions, syntax highlighters, component kits, devtools and so on that other frameworks have, and we should fix that. We *really* want to add first-class TypeScript support.
But in the meantime we think Svelte 3 is the best way to build web apps yet. Take an hour to go through the [tutorial](tutorial) and we hope to convince you of the same. Either way, we'd love to see you in our [Discord chatroom](https://discord.gg/yy75DKs) and on [GitHub](https://github.com/sveltejs/svelte) — everyone is welcome, especially you.
But in the meantime we think Svelte 3 is the best way to build web apps yet. Take an hour to go through the [tutorial](tutorial) and we hope to convince you of the same. Either way, we'd love to see you in our [Discord chatroom](chat) and on [GitHub](https://github.com/sveltejs/svelte) — everyone is welcome, especially you.

@ -2,8 +2,8 @@
title: Before we begin
---
> Temporary note: This document is a work-in-progress. Please forgive any missing or misleading parts, and don't be shy about asking for help in the [Discord chatroom](https://discord.gg/yy75DKs). The [tutorial](tutorial) is more complete; start there.
This page contains detailed API reference documentation. It's intended to be a resource for people who already have some familiarity with Svelte.
If that's not you (yet), you may prefer to visit the [interactive tutorial](tutorial) or the [examples](examples) before consulting this reference.
Don't be shy about asking for help in the [Discord chatroom](chat).

@ -28,23 +28,60 @@ A `<script>` block contains JavaScript that runs when a component instance is cr
---
Svelte uses the `export` keyword to mark a variable declaration as a *property* or *prop*, which means it becomes accessible to consumers of the component:
Svelte uses the `export` keyword to mark a variable declaration as a *property* or *prop*, which means it becomes accessible to consumers of the component (see the section on [attributes and props](docs#Attributes_and_props) for more information).
```html
<script>
// these properties can be set externally
export let foo;
export let bar = 'optional default value';
// Values that are passed in as props
// are immediately available
console.log(foo, bar);
console.log({ foo });
</script>
```
---
You can specify a default value, which will be used if the component's consumer doesn't specify a prop.
In development mode (see the [compiler options](docs#svelte_compile)), a warning will be printed if no default is provided and the consumer does not specify a value. To squelch this warning, ensure that a default is specified, even if it is `undefined`.
```html
<script>
export let bar = 'optional default value';
export let baz = undefined;
</script>
```
// function declarations cannot be set externally,
// but can be accessed from outside
export function instanceMethod() {
alert(foo);
---
If you export a `const`, `class` or `function`, it is readonly from outside the component. Function *expressions* are valid props, however.
```html
<script>
// these are readonly
export const thisIs = 'readonly';
export function greet(name) {
alert(`hello ${name}!`);
}
// this is a prop
export let format = n => n.toFixed(2);
</script>
```
---
You can use reserved words as prop names.
```html
<script>
let className;
// creates a `class` property, even
// though it is a reserved word
export { className as class };
</script>
```
@ -56,13 +93,15 @@ To change component state and trigger a re-render, just assign to a locally decl
Update expressions (`count += 1`) and property assignments (`obj.x = y`) have the same effect.
Because Svelte's reactivity is based on assignments, using array methods like `.push()` and `.splice()` won't automatically trigger updates. Options for getting around this can be found in the [tutorial](tutorial/updating-arrays-and-objects).
```html
<script>
let count = 0;
function handleClick () {
// calling this function will trigger a re-render
// if the markup references `count`
// calling this function will trigger an
// update if the markup references `count`
count = count + 1;
}
</script>
@ -72,7 +111,7 @@ Update expressions (`count += 1`) and property assignments (`obj.x = y`) have th
---
Any top-level statement (i.e. not inside a block or a function) can be made reactive by prefixing it with the `$:` label. Reactive statements run immediately before the component updates, whenever the values that they depend on have changed.
Any top-level statement (i.e. not inside a block or a function) can be made reactive by prefixing it with the `$:` [JS label syntax](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/label). Reactive statements run immediately before the component updates, whenever the values that they depend on have changed.
```html
<script>
@ -108,8 +147,12 @@ If a statement consists entirely of an assignment to an undeclared variable, Sve
---
A *store* is an object that allows reactive access to a value via a simple *store contract*. The [`svelte/store` module](docs#svelte_store) contains minimal store implementations which fulfil this contract.
Any time you have a reference to a store, you can access its value inside a component by prefixing it with the `$` character. This causes Svelte to declare the prefixed variable, and set up a store subscription that will be unsubscribed when appropriate.
Assignments to `$`-prefixed variables require that the variable be a writable store, and will result in a call to the store's `.set` method.
Note that the store must be declared at the top level of the component — not inside an `if` block or a function, for example.
Local variables (that do not represent store values) must *not* have a `$` prefix.
@ -123,9 +166,26 @@ Local variables (that do not represent store values) must *not* have a `$` prefi
count.set(1);
console.log($count); // logs 1
$count = 2;
console.log($count); // logs 2
</script>
```
##### Store contract
```js
store = { subscribe: (subscription: (value: any) => void) => () => void, set?: (value: any) => void }
```
You can create your own stores without relying on [`svelte/store`](docs#svelte_store), by implementing the *store contract*:
1. A store must contain a `.subscribe` method, which must accept as its argument a subscription function. This subscription function must be immediately and synchronously called with the store's current value upon calling `.subscribe`. All of a store's active subscription functions must later be synchronously called whenever the store's value changes.
2. The `.subscribe` method must return an unsubscribe function. Calling an unsubscribe function must stop its subscription, and its corresponding subscription function must not be called again by the store.
3. A store may *optionally* contain a `.set` method, which must accept as its argument a new value for the store, and which synchronously calls all of the store's active subscription functions. Such a store is called a *writable store*.
For interoperability with RxJS Observables, the `.subscribe` method is also allowed to return an object with an `.unsubscribe` method, rather than return the unsubscription function directly. Note however that unless `.subscribe` synchronously calls the subscription (which is not required by the Observable spec), Svelte will see the value of the store as `undefined` until it does.
### &lt;script context="module"&gt;
@ -137,6 +197,8 @@ You can `export` bindings from this block, and they will become exports of the c
You cannot `export default`, since the default export is the component itself.
> Variables defined in `module` scripts are not reactive — reassigning them will not trigger a rerender even though the variable itself will update. For values shared between multiple components, consider using a [store](docs#svelte_store).
```html
<script context="module">
let totalComponents = 0;
@ -191,3 +253,15 @@ To apply styles to a selector globally, use the `:global(...)` modifier.
}
</style>
```
---
If you want to make @keyframes that are accessible globally, you need to prepend your keyframe names with `-global-`.
The `-global-` part will be removed when compiled, and the keyframe then be referenced using just `my-animation-name` elsewhere in your code.
```html
<style>
@keyframes -global-my-animation-name {...}
</style>
```

@ -7,7 +7,7 @@ title: Template syntax
---
A lowercase tag, like `<div>`, denotes a regular HTML element. A capitalised tag, such as `<Widget>`, indicates a *component*.
A lowercase tag, like `<div>`, denotes a regular HTML element. A capitalised tag, such as `<Widget>` or `<Namespace.Widget>`, indicates a *component*.
```html
<script>
@ -20,7 +20,7 @@ A lowercase tag, like `<div>`, denotes a regular HTML element. A capitalised tag
```
### Attributes
### Attributes and props
---
@ -76,6 +76,16 @@ When the attribute name and value match (`name={name}`), they can be replaced wi
---
By convention, values passed to components are referred to as *properties* or *props* rather than *attributes*, which are a feature of the DOM.
As with elements, `name={name}` can be replaced with the `{name}` shorthand.
```html
<Widget foo={bar} answer={42} text="hello"/>
```
---
*Spread attributes* allow many attributes or properties to be passed to an element or component at once.
An element or component can have multiple spread attributes, interspersed with regular ones.
@ -84,6 +94,14 @@ An element or component can have multiple spread attributes, interspersed with r
<Widget {...things}/>
```
---
*`$$props`* references all props that are passed to a component including ones that are not declared with `export`. It is useful in rare cases, but not generally recommended, as it is difficult for Svelte to optimise.
```html
<Widget {...$$props}/>
```
### Text expressions
@ -101,27 +119,28 @@ Text can also contain JavaScript expressions:
```
### HTML expressions
### Comments
```sv
{@html expression}
---
You can use HTML comments inside components.
```html
<!-- this is a comment! -->
<h1>Hello world</h1>
```
---
In a text expression, characters like `<` and `>` are escaped. With HTML expressions, they're not.
> Svelte does not sanitize expressions before injecting HTML. If the data comes from an untrusted source, you must sanitize it, or you are exposing your users to an XSS vulnerability.
Comments beginning with `svelte-ignore` disable warnings for the next block of markup. Usually these are accessibility warnings; make sure that you're disabling them for a good reason.
```html
<div class="blog-post">
<h1>{post.title}</h1>
{@html post.content}
</div>
<!-- svelte-ignore a11y-autofocus -->
<input bind:value={name} autofocus>
```
### If blocks
### {#if ...}
```sv
{#if expression}...{/if}
@ -158,7 +177,7 @@ Additional conditions can be added with `{:else if expression}`, optionally endi
```
### Each blocks
### {#each ...}
```sv
{#each expression as name}...{/each}
@ -186,6 +205,8 @@ Iterating over lists of values can be done with an each block.
</ul>
```
You can use each blocks to iterate over any array or array-like value — that is, any object with a `length` property.
---
An each block can also specify an *index*, equivalent to the second argument in an `array.map(...)` callback:
@ -208,12 +229,20 @@ If a *key* expression is provided — which must uniquely identify each list ite
---
You can freely use destructuring patterns in each blocks.
You can freely use destructuring and rest patterns in each blocks.
```html
{#each items as { id, name, qty }, i (id)}
<li>{i + 1}: {name} x {qty}</li>
{/each}
{#each objects as { id, ...rest }}
<li><span>{id}</span><MyComponent {...rest}/></li>
{/each}
{#each items as [id, ...rest]}
<li><span>{id}</span><MyComponent values={rest}/></li>
{/each}
```
---
@ -229,7 +258,7 @@ An each block can also have an `{:else}` clause, which is rendered if the list i
```
### Await blocks
### {#await ...}
```sv
{#await expression}...{:then name}...{:catch name}...{/await}
@ -283,7 +312,82 @@ If you don't care about the pending state, you can also omit the initial block.
```
### DOM events
### {@html ...}
```sv
{@html expression}
```
---
In a text expression, characters like `<` and `>` are escaped; however, with HTML expressions, they're not.
The expression should be valid standalone HTML — `{@html "<div>"}content{@html "</div>"}` will *not* work, because `</div>` is not valid HTML.
> Svelte does not sanitize expressions before injecting HTML. If the data comes from an untrusted source, you must sanitize it, or you are exposing your users to an XSS vulnerability.
```html
<div class="blog-post">
<h1>{post.title}</h1>
{@html post.content}
</div>
```
### {@debug ...}
```sv
{@debug}
```
```sv
{@debug var1, var2, ..., varN}
```
---
The `{@debug ...}` tag offers an alternative to `console.log(...)`. It logs the values of specific variables whenever they change, and pauses code execution if you have devtools open.
It accepts a comma-separated list of variable names (not arbitrary expressions).
```html
<script>
let user = {
firstname: 'Ada',
lastname: 'Lovelace'
};
</script>
{@debug user}
<h1>Hello {user.firstname}!</h1>
```
---
`{@debug ...}` accepts a comma-separated list of variable names (not arbitrary expressions).
```html
<!-- Compiles -->
{@debug user}
{@debug user1, user2, user3}
<!-- WON'T compile -->
{@debug user.firstname}
{@debug myArray[0]}
{@debug !isReady}
{@debug typeof user === 'object'}
```
The `{@debug}` tag without any arguments will insert a `debugger` statement that gets triggered when *any* state changes, as opposed to the specified variables.
### Element directives
As well as attributes, elements can have *directives*, which control the element's behaviour in some way.
#### [on:*eventname*](on_element_event)
```sv
on:eventname={handler}
@ -324,6 +428,13 @@ Handlers can be declared inline with no performance penalty. As with attributes,
Add *modifiers* to DOM events with the `|` character.
```html
<form on:submit|preventDefault={handleSubmit}>
<!-- the `submit` event's default is prevented,
so the page won't reload -->
</form>
```
The following modifiers are available:
* `preventDefault` — calls `event.preventDefault()` before running the handler
@ -334,13 +445,6 @@ The following modifiers are available:
Modifiers can be chained together, e.g. `on:click|once|capture={...}`.
```html
<form on:submit|preventDefault={handleSubmit}>
<!-- the `submit` event's default is prevented,
so the page won't reload -->
</form>
```
---
If the `on:` directive is used without a value, the component will *forward* the event, meaning that a consumer of the component can listen for it.
@ -351,34 +455,30 @@ If the `on:` directive is used without a value, the component will *forward* the
</button>
```
### Component events
```sv
on:eventname={handler}
```
---
Components can emit events using [createEventDispatcher](docs#createEventDispatcher), or by forwarding DOM events. Listening for component events looks the same as listening for DOM events:
It's possible to have multiple event listeners for the same event:
```html
<SomeComponent on:whatever={handler}/>
```
<script>
let counter = 0;
function increment() {
counter = counter + 1;
}
function track(event) {
trackEvent(event)
}
</script>
<button on:click={increment} on:click={track}>Click me!</button>
```
### Element bindings
#### [bind:*property*](bind_element_property)
```sv
bind:property={variable}
```
```sv
bind:group={variable}
```
```sv
bind:this={dom_node}
```
---
@ -412,31 +512,8 @@ Numeric input values are coerced; even though `input.value` is a string as far a
<input type="range" bind:value={num}>
```
#### Binding related elements
---
Inputs that work together can use `bind:group`.
```html
<script>
let tortilla = 'Plain';
let fillings = [];
</script>
<!-- grouped radio inputs are mutually exclusive -->
<input type="radio" bind:group={tortilla} value="Plain">
<input type="radio" bind:group={tortilla} value="Whole wheat">
<input type="radio" bind:group={tortilla} value="Spinach">
<!-- grouped checkbox inputs populate an array -->
<input type="checkbox" bind:group={fillings} value="Rice">
<input type="checkbox" bind:group={fillings} value="Beans">
<input type="checkbox" bind:group={fillings} value="Cheese">
<input type="checkbox" bind:group={fillings} value="Guac (extra)">
```
#### Binding `<select>` value
##### Binding `<select>` value
---
@ -476,37 +553,54 @@ When the value of an `<option>` matches its text content, the attribute can be o
</select>
```
#### Media element bindings
---
Elements with the `contenteditable` attribute support `innerHTML` and `textContent` bindings.
```html
<div contenteditable="true" bind:innerHTML={html}></div>
```
##### Media element bindings
---
Media elements (`<audio>` and `<video>`) have their own set of bindings — four *readonly* ones...
Media elements (`<audio>` and `<video>`) have their own set of bindings — six *readonly* ones...
* `duration` (readonly) — the total duration of the video, in seconds
* `buffered` (readonly) — an array of `{start, end}` objects
* `seekable` (readonly) — ditto
* `played` (readonly) — ditto
* `seeking` (readonly) — boolean
* `ended` (readonly) — boolean
...and three *two-way* bindings:
...and four *two-way* bindings:
* `currentTime` — the current point in the video, in seconds
* `playbackRate` — how fast to play the video, where 1 is 'normal'
* `paused` — this one should be self-explanatory
* `volume` — a value between 0 and 1
Videos additionally have readonly `videoWidth` and `videoHeight` bindings.
```html
<video
src={clip}
bind:duration
bind:buffered
bind:seekable
bind:seeking
bind:played
bind:ended
bind:currentTime
bind:paused
bind:volume
bind:videoWidth
bind:videoHeight
></video>
```
#### Block-level element bindings
##### Block-level element bindings
---
@ -526,61 +620,61 @@ Block-level elements have 4 readonly bindings, measured using a technique simila
</div>
```
#### Binding a DOM node
#### bind:group
```sv
bind:group={variable}
```
---
To get a reference to a DOM node, use `bind:this`.
Inputs that work together can use `bind:group`.
```html
<script>
import { onMount } from 'svelte';
let canvasElement;
onMount(() => {
const ctx = canvasElement.getContext('2d');
drawStuff(ctx);
});
let tortilla = 'Plain';
let fillings = [];
</script>
<canvas bind:this={canvasElement}></canvas>
```
<!-- grouped radio inputs are mutually exclusive -->
<input type="radio" bind:group={tortilla} value="Plain">
<input type="radio" bind:group={tortilla} value="Whole wheat">
<input type="radio" bind:group={tortilla} value="Spinach">
<!-- grouped checkbox inputs populate an array -->
<input type="checkbox" bind:group={fillings} value="Rice">
<input type="checkbox" bind:group={fillings} value="Beans">
<input type="checkbox" bind:group={fillings} value="Cheese">
<input type="checkbox" bind:group={fillings} value="Guac (extra)">
```
### Component bindings
#### [bind:this](bind_element)
```sv
bind:property={variable}
```
```sv
bind:this={component_instance}
bind:this={dom_node}
```
---
You can bind to component props using the same mechanism.
To get a reference to a DOM node, use `bind:this`.
```html
<Keypad bind:value={pin}/>
```
---
Components also support `bind:this`, allowing you to interact with component instances programmatically.
<script>
import { onMount } from 'svelte';
> Note that we can do `{cart.empty}` rather than `{() => cart.empty()}`, since component methods are closures. You don't need to worry about the value of `this` when calling them.
let canvasElement;
```html
<ShoppingCart bind:this={cart}/>
onMount(() => {
const ctx = canvasElement.getContext('2d');
drawStuff(ctx);
});
</script>
<button on:click={cart.empty}>
Empty shopping cart
</button>
<canvas bind:this={canvasElement}></canvas>
```
### Classes
#### class:*name*
```sv
class:name={value}
@ -600,10 +694,13 @@ A `class:` directive provides a shorter way of toggling a class on an element.
<!-- Shorthand, for when name and value match -->
<div class:active>...</div>
<!-- Multiple class toggles can be included -->
<div class:active class:inactive={!active} class:isAdmin>...</div>
```
### Actions
#### use:*action*
```sv
use:action
@ -668,43 +765,19 @@ An action can have parameters. If the returned value has an `update` method, it
```
### Transitions
#### transition:*fn*
```sv
transition:name
```
```sv
transition:name={params}
transition:fn
```
```sv
transition:name|local
transition:fn={params}
```
```sv
transition:name|local={params}
transition:fn|local
```
```sv
in:name
```
```sv
in:name={params}
```
```sv
in:name|local
```
```sv
in:name|local={params}
```
```sv
out:name
```
```sv
out:name={params}
```
```sv
out:name|local
```
```sv
out:name|local={params}
transition:fn|local={params}
```
@ -720,7 +793,7 @@ transition = (node: HTMLElement, params: any) => {
---
A transition is triggered by an element entering or leaving the DOM as a result of a state change. Transitions do not run when a component is first mounted, but only on subsequent updates.
A transition is triggered by an element entering or leaving the DOM as a result of a state change.
Elements inside an *outroing* block are kept in the DOM until all current transitions have completed.
@ -734,19 +807,9 @@ The `transition:` directive indicates a *bidirectional* transition, which means
{/if}
```
---
> By default intro transitions will not play on first render. You can modify this behaviour by setting `intro: true` when you [create a component](docs#Client-side_component_API).
The `in:` and `out:` directives are not bidirectional. An in transition will continue to 'play' alongside the out transition, if the block is outroed while the transition is in progress. If an out transition is aborted, transitions will restart from scratch.
```html
{#if visible}
<div in:fly out:fade>
flies in, fades out
</div>
{/if}
```
#### Transition parameters
##### Transition parameters
---
@ -762,7 +825,7 @@ Like actions, transitions can have parameters.
{/if}
```
#### Custom transition functions
##### Custom transition functions
---
@ -838,7 +901,7 @@ A custom transition function can also return a `tick` function, which is called
If a transition returns a function instead of a transition object, the function will be called in the next microtask. This allows multiple transitions to coordinate, making [crossfade effects](tutorial/deferred-transitions) possible.
#### Transition events
##### Transition events
---
@ -882,12 +945,246 @@ Local transitions only play when the block they belong to is created or destroye
```
### Animations
#### in:*fn*/out:*fn*
```sv
in:fn
```
```sv
in:fn={params}
```
```sv
in:fn|local
```
```sv
in:fn|local={params}
```
```sv
out:fn
```
```sv
out:fn={params}
```
```sv
out:fn|local
```
```sv
out:fn|local={params}
```
TODO i can't remember how any of this works
---
Similar to `transition:`, but only applies to elements entering (`in:`) or leaving (`out:`) the DOM.
### Slots
Unlike with `transition:`, transitions applied with `in:` and `out:` are not bidirectional — an in transition will continue to 'play' alongside the out transition, rather than reversing, if the block is outroed while the transition is in progress. If an out transition is aborted, transitions will restart from scratch.
```html
{#if visible}
<div in:fly out:fade>
flies in, fades out
</div>
{/if}
```
#### animate:*fn*
```sv
animate:name
```
```sv
animate:name={params}
```
```js
animation = (node: HTMLElement, { from: DOMRect, to: DOMRect } , params: any) => {
delay?: number,
duration?: number,
easing?: (t: number) => number,
css?: (t: number, u: number) => string,
tick?: (t: number, u: number) => void
}
```
```js
DOMRect {
bottom: number,
height: number,
left: number,
right: number,
top: number,
width: number,
x: number,
y: number
}
```
---
An animation is triggered when the contents of a [keyed each block](docs#each) are re-ordered. Animations do not run when an element is removed, only when the each block's data is reordered. Animate directives must be on an element that is an *immediate* child of a keyed each block.
Animations can be used with Svelte's [built-in animation functions](docs#svelte_animate) or [custom animation functions](docs#Custom_animation_functions).
```html
<!-- When `list` is reordered the animation will run-->
{#each list as item, index (item)}
<li animate:flip>{item}</li>
{/each}
```
##### Animation Parameters
---
As with actions and transitions, animations can have parameters.
(The double `{{curlies}}` aren't a special syntax; this is an object literal inside an expression tag.)
```html
{#each list as item, index (item)}
<li animate:flip="{{ delay: 500 }}">{item}</li>
{/each}
```
##### Custom animation functions
---
Animations can use custom functions that provide the `node`, an `animation` object and any `paramaters` as arguments. The `animation` parameter is an object containing `from` and `to` properties each containing a [DOMRect](https://developer.mozilla.org/en-US/docs/Web/API/DOMRect#Properties) describing the geometry of the element in its `start` and `end` positions. The `from` property is the DOMRect of the element in its starting position, the `to` property is the DOMRect of the element in its final position after the list has been reordered and the DOM updated.
If the returned object has a `css` method, Svelte will create a CSS animation that plays on the element.
The `t` argument passed to `css` is a value that goes from `0` and `1` after the `easing` function has been applied. The `u` argument is equal to `1 - t`.
The function is called repeatedly *before* the animation begins, with different `t` and `u` arguments.
```html
<script>
import { cubicOut } from 'svelte/easing';
function whizz(node, { from, to }, params) {
const dx = from.left - to.left;
const dy = from.top - to.top;
const d = Math.sqrt(dx * dx + dy * dy);
return {
delay: 0,
duration: Math.sqrt(d) * 120,
easing: cubicOut,
css: (t, u) =>
`transform: translate(${u * dx}px, ${u * dy}px) rotate(${t*360}deg);`
};
}
</script>
{#each list as item, index (item)}
<div animate:whizz>{item}</div>
{/each}
```
---
A custom animation function can also return a `tick` function, which is called *during* the animation with the same `t` and `u` arguments.
> If it's possible to use `css` instead of `tick`, do so — CSS animations can run off the main thread, preventing jank on slower devices.
```html
<script>
import { cubicOut } from 'svelte/easing';
function whizz(node, { from, to }, params) {
const dx = from.left - to.left;
const dy = from.top - to.top;
const d = Math.sqrt(dx * dx + dy * dy);
return {
delay: 0,
duration: Math.sqrt(d) * 120,
easing: cubicOut,
tick: (t, u) =>
Object.assign(node.style, {
color: t > 0.5 ? 'Pink' : 'Blue'
});
};
}
</script>
{#each list as item, index (item)}
<div animate:whizz>{item}</div>
{/each}
```
### Component directives
#### [on:*eventname*](on_component_event)
```sv
on:eventname={handler}
```
---
Components can emit events using [createEventDispatcher](docs#createEventDispatcher), or by forwarding DOM events. Listening for component events looks the same as listening for DOM events:
```html
<SomeComponent on:whatever={handler}/>
```
---
As with DOM events, if the `on:` directive is used without a value, the component will *forward* the event, meaning that a consumer of the component can listen for it.
```html
<SomeComponent on:whatever/>
```
#### [bind:*property*](bind_component_property)
```sv
bind:property={variable}
```
---
You can bind to component props using the same syntax as for elements.
```html
<Keypad bind:value={pin}/>
```
#### [bind:this](bind_component)
```sv
bind:this={component_instance}
```
---
Components also support `bind:this`, allowing you to interact with component instances programmatically.
> Note that we can't do `{cart.empty}` since `cart` is `undefined` when the button is first rendered and throws an error.
```html
<ShoppingCart bind:this={cart}/>
<button on:click={() => cart.empty()}>
Empty shopping cart
</button>
```
### `<slot>`
```sv
<slot><!-- optional fallback --></slot>
@ -907,18 +1204,22 @@ The content is exposed in the child component using the `<slot>` element, which
```html
<!-- App.svelte -->
<Widget></Widget>
<Widget>
<p>this is some child content</p>
<p>this is some child content that will overwrite the default slot content</p>
</Widget>
<!-- Widget.svelte -->
<div>
<slot>
this will be rendered if someone does <Widget/>
this fallback content will be rendered when no content is provided, like in the first example
</slot>
</div>
```
#### [`<slot name="`*name*`">`](slot_name)
---
Named slots allow consumers to target specific areas. They can also have fallback content.
@ -934,10 +1235,12 @@ Named slots allow consumers to target specific areas. They can also have fallbac
<div>
<slot name="header">No header was provided</slot>
<p>Some content between header and footer</p>
</slot name="footer"></slot>
<slot name="footer"></slot>
</div>
```
#### [`<slot let:`*name*`={`*value*`}>`](slot_let)
---
Slots can be rendered zero or more times, and can pass values *back* to the parent using props. The parent exposes the values to the slot template using the `let:` directive.
@ -980,11 +1283,11 @@ Named slots can also expose values. The `let:` directive goes on the element wit
{/each}
</ul>
</slot name="footer"></slot>
<slot name="footer"></slot>
```
### &lt;svelte:self&gt;
### `<svelte:self>`
---
@ -1005,10 +1308,10 @@ It cannot appear at the top level of your markup; it must be inside an if or eac
{/if}
```
### &lt;svelte:component&gt;
### `<svelte:component>`
```sv
<svelte:component this={expression}>
<svelte:component this={expression}/>
```
---
@ -1022,7 +1325,7 @@ If `this` is falsy, no component is rendered.
```
### &lt;svelte:window&gt;
### `<svelte:window>`
```sv
<svelte:window on:event={handler}/>
@ -1064,7 +1367,7 @@ All except `scrollX` and `scrollY` are readonly.
```
### &lt;svelte:body&gt;
### `<svelte:body>`
```sv
<svelte:body on:event={handler}/>
@ -1082,15 +1385,15 @@ As with `<svelte:window>`, this element allows you to add listeners to events on
```
### &lt;svelte:head&gt;
### `<svelte:head>`
```sv
<svelte:head>
<svelte:head>...</svelte:head>
```
---
This element makes it possible to insert elements into `document.head`. During server-side rendering, `head` content exposed separately to the main `html` content.
This element makes it possible to insert elements into `document.head`. During server-side rendering, `head` content is exposed separately to the main `html` content.
```html
<svelte:head>
@ -1099,10 +1402,10 @@ This element makes it possible to insert elements into `document.head`. During s
```
### &lt;svelte:options&gt;
### `<svelte:options>`
```sv
<svelte:options option={value}>
<svelte:options option={value}/>
```
---

@ -156,6 +156,8 @@ Like lifecycle functions, this must be called during component initialisation.
</script>
```
> Context is not inherently reactive. If you need reactive values in context then you can pass a store into context, which *will* be reactive.
#### `getContext`
```js
@ -176,45 +178,48 @@ Retrieves the context that belongs to the closest parent component with the spec
#### `createEventDispatcher`
TODO
```js
dispatch: ((name: string, detail?: any) => void) = createEventDispatcher();
```
### `svelte/store`
---
The `svelte/store` module exports functions for creating [stores](tutorial/writable-stores).
Creates an event dispatcher that can be used to dispatch [component events](docs#on_component_event). Event dispatchers are functions that can take two arguments: `name` and `detail`.
---
Component events created with `createEventDispatcher` create a [CustomEvent](https://developer.mozilla.org/en-US/docs/Web/API/CustomEvent). These events do not [bubble](https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Building_blocks/Events#Event_bubbling_and_capture) and are not cancellable with `event.preventDefault()`. The `detail` argument corresponds to the [CustomEvent.detail](https://developer.mozilla.org/en-US/docs/Web/API/CustomEvent/detail) property and can contain any type of data.
To be considered a store, an object must have a `subscribe` method that returns an `unsubscribe` function.
```html
<script>
import { createEventDispatcher } from 'svelte';
```js
const unsubscribe = store.subscribe(value => {
console.log(value);
}); // logs `value`
const dispatch = createEventDispatcher();
</script>
// later...
unsubscribe();
<button on:click="{() => dispatch('notify', 'detail value')}">Fire Event</button>
```
---
Stores have special significance inside Svelte components. Their values can be read by prefixing the store's name with the `$` character, which causes Svelte to set up subscriptions and unsubscriptions automatically during the component's lifecycle.
Events dispatched from child components can be listened to in their parent. Any data provided when the event was dispatched is available on the `detail` property of the event object.
```html
<script>
import { count } from './stores.js';
function handleClick() {
// this is equivalent to count.update(n => n + 1)
$count += 1;
function callbackFunction(event) {
console.log(`Notify fired! Detail: ${event.detail}`)
}
</script>
<button on:click={handleClick}>
Clicks: {$count}
</button>
<Child on:notify="{callbackFunction}"/>
```
### `svelte/store`
The `svelte/store` module exports functions for creating [readable](docs#readable), [writable](docs#writable) and [derived](docs#derived) stores.
Keep in mind that you don't *have* to use these functions to enjoy the [reactive `$store` syntax](docs#4_Prefix_stores_with_$_to_access_their_values) in your components. Any object that correctly implements `.subscribe`, unsubscribe, and (optionally) `.set` is a valid store, and will work both with the special syntax, and with Svelte's built-in [`derived` stores](docs#derived).
This makes it possible to wrap almost any other reactive state handling library for use in Svelte. Read more about the [store contract](docs#Store_contract) to see what a correct implementation looks like.
#### `writable`
```js
@ -226,7 +231,11 @@ store = writable(value: any, (set: (value: any) => void) => () => void)
---
Creates a store with additional `set` and `update` methods.
Function that creates a store which has values that can be set from 'outside' components. It gets created as an object with additional `set` and `update` methods.
`set` is a method that takes one argument which is the value to be set. The store value gets set to the value of the argument if the store value is not already equal to it.
`update` is a method that takes one argument which is a callback. The callback takes the existing store value as its argument and returns the new value to be set to the store.
```js
import { writable } from 'svelte/store';
@ -293,13 +302,13 @@ const time = readable(new Date(), set => {
store = derived(a, callback: (a: any) => any)
```
```js
store = derived(a, callback: (a: any, set: (value: any) => void) => void, initial_value: any)
store = derived(a, callback: (a: any, set: (value: any) => void) => void | () => void, initial_value: any)
```
```js
store = derived([a, ...b], callback: ([a: any, ...b: any[]]) => any)
```
```js
store = derived([a, ...b], callback: ([a: any, ...b: any[]], set: (value: any) => void) => void, initial_value: any)
store = derived([a, ...b], callback: ([a: any, ...b: any[]], set: (value: any) => void) => void | () => void, initial_value: any)
```
---
@ -330,6 +339,24 @@ const delayed = derived(a, ($a, set) => {
---
If you return a function from the callback, it will be called when a) the callback runs again, or b) the last subscriber unsubscribes.
```js
import { derived } from 'svelte/store';
const tick = derived(frequency, ($frequency, set) => {
const interval = setInterval(() => {
set(Date.now());
}, 1000 / $frequency);
return () => {
clearInterval(interval);
};
}, 'one moment...');
```
---
In both cases, an array of arguments can be passed as the first argument instead of a single store.
```js
@ -376,7 +403,7 @@ Tweened stores update their values over a fixed duration. The following options
* `delay` (`number`, default 0) — milliseconds before starting
* `duration` (`number`, default 400) — milliseconds the tween lasts
* `easing` (`function`, default `t => t`) — an [easing function](docs#svelte_easing)
* `interpolator` (`function`) — see below
* `interpolate` (`function`) — see below
`store.set` and `store.update` can accept a second `options` argument that will override the options passed in upon instantiation.
@ -410,7 +437,20 @@ Out of the box, Svelte will interpolate between two numbers, two arrays or two o
---
The `interpolator` option allows you to tween between *any* arbitrary values. It must be an `(a, b) => t => value` function, where `a` is the starting value, `b` is the target value, `t` is a number between 0 and 1, and `value` is the result. For example, we can use the [d3-interpolate](https://github.com/d3/d3-interpolate) package to smoothly interpolate between two colours.
If the initial value is `undefined` or `null`, the first value change will take effect immediately. This is useful when you have tweened values that are based on props, and don't want any motion when the component first renders.
```js
const size = tweened(undefined, {
duration: 300,
easing: cubicOut
});
$: $size = big ? 100 : 10;
```
---
The `interpolate` option allows you to tween between *any* arbitrary values. It must be an `(a, b) => t => value` function, where `a` is the starting value, `b` is the target value, `t` is a number between 0 and 1, and `value` is the result. For example, we can use the [d3-interpolate](https://github.com/d3/d3-interpolate) package to smoothly interpolate between two colours.
```html
<script>
@ -453,7 +493,9 @@ A `spring` store gradually changes to its target value based on its `stiffness`
---
As with [`tweened`](#tweened) stores, `set` and `update` return a Promise that resolves if the spring settles. The `store.stiffness` and `store.damping` properties can be changed while the spring is in motion, and will take immediate effect.
As with [`tweened`](docs#tweened) stores, `set` and `update` return a Promise that resolves if the spring settles. The `store.stiffness` and `store.damping` properties can be changed while the spring is in motion, and will take immediate effect.
Both `set` and `update` can take a second argument — an object with `hard` or `soft` properties. `{ hard: true }` sets the target value immediately; `{ soft: n }` preserves existing momentum for `n` seconds before settling. `{ soft: true }` is equivalent to `{ soft: 0.5 }`.
[See a full example on the spring tutorial.](tutorial/spring)
@ -468,28 +510,343 @@ As with [`tweened`](#tweened) stores, `set` and `update` return a Promise that r
</script>
```
---
If the initial value is `undefined` or `null`, the first value change will take effect immediately, just as with `tweened` values (see above).
```js
const size = spring();
$: $size = big ? 100 : 10;
```
### `svelte/transition`
TODO
The `svelte/transition` module exports six functions: `fade`, `fly`, `slide`, `scale`, `draw` and `crossfade`. They are for use with svelte [`transitions`](docs#Transitions).
#### `fade`
```sv
transition:fade={params}
```
```sv
in:fade={params}
```
```sv
out:fade={params}
```
---
Animates the opacity of an element from 0 to the current opacity for `in` transitions and from the current opacity to 0 for `out` transitions.
`fade` accepts the following parameters:
* `delay` (`number`, default 0) — milliseconds before starting
* `duration` (`number`, default 400) — milliseconds the transition lasts
You can see the `fade` transition in action in the [transition tutorial](tutorial/transition).
```html
<script>
import { fade } from 'svelte/transition';
</script>
{#if condition}
<div transition:fade="{{delay: 250, duration: 300}}">
fades in and out
</div>
{/if}
```
#### `blur`
```sv
transition:blur={params}
```
```sv
in:blur={params}
```
```sv
out:blur={params}
```
---
Animates a `blur` filter alongside an element's opacity.
`blur` accepts the following parameters:
* `delay` (`number`, default 0) — milliseconds before starting
* `duration` (`number`, default 400) — milliseconds the transition lasts
* `easing` (`function`, default `cubicInOut`) — an [easing function](docs#svelte_easing)
* `opacity` (`number`, default 0) - the opacity value to animate out to and in from
* `amount` (`number`, default 5) - the size of the blur in pixels
```html
<script>
import { blur } from 'svelte/transition';
</script>
{#if condition}
<div transition:blur="{{amount: 10}}">
fades in and out
</div>
{/if}
```
#### `fly`
```sv
transition:fly={params}
```
```sv
in:fly={params}
```
```sv
out:fly={params}
```
---
Animates the x and y positions and the opacity of an element. `in` transitions animate from an element's current (default) values to the provided values, passed as parameters. `out` transitions animate from the provided values to an element's default values.
`fly` accepts the following parameters:
* `delay` (`number`, default 0) — milliseconds before starting
* `duration` (`number`, default 400) — milliseconds the transition lasts
* `easing` (`function`, default `cubicOut`) — an [easing function](docs#svelte_easing)
* `x` (`number`, default 0) - the x offset to animate out to and in from
* `y` (`number`, default 0) - the y offset to animate out to and in from
* `opacity` (`number`, default 0) - the opacity value to animate out to and in from
You can see the `fly` transition in action in the [transition tutorial](tutorial/adding-parameters-to-transitions).
```html
<script>
import { fly } from 'svelte/transition';
import { quintOut } from 'svelte/easing';
</script>
{#if condition}
<div transition:fly="{{delay: 250, duration: 300, x: 100, y: 500, opacity: 0.5, easing: quintOut}}">
flies in and out
</div>
{/if}
```
#### `slide`
```sv
transition:slide={params}
```
```sv
in:slide={params}
```
```sv
out:slide={params}
```
---
Slides an element in and out.
`slide` accepts the following parameters:
* `delay` (`number`, default 0) — milliseconds before starting
* `duration` (`number`, default 400) — milliseconds the transition lasts
* `easing` (`function`, default `cubicOut`) — an [easing function](docs#svelte_easing)
```html
<script>
import { slide } from 'svelte/transition';
import { quintOut } from 'svelte/easing';
</script>
{#if condition}
<div transition:slide="{{delay: 250, duration: 300, easing: quintOut }}">
slides in and out
</div>
{/if}
```
#### `scale`
```sv
transition:scale={params}
```
```sv
in:scale={params}
```
```sv
out:scale={params}
```
---
Animates the opacity and scale of an element. `in` transitions animate from an element's current (default) values to the provided values, passed as parameters. `out` transitions animate from the provided values to an element's default values.
`scale` accepts the following parameters:
* `delay` (`number`, default 0) — milliseconds before starting
* `duration` (`number`, default 400) — milliseconds the transition lasts
* `easing` (`function`, default `cubicOut`) — an [easing function](docs#svelte_easing)
* `start` (`number`, default 0) - the scale value to animate out to and in from
* `opacity` (`number`, default 0) - the opacity value to animate out to and in from
```html
<script>
import { scale } from 'svelte/transition';
import { quintOut } from 'svelte/easing';
</script>
{#if condition}
<div transition:scale="{{duration: 500, delay: 500, opacity: 0.5, start: 0.5, easing: quintOut}}">
scales in and out
</div>
{/if}
```
#### `draw`
```sv
transition:draw={params}
```
```sv
in:draw={params}
```
```sv
out:draw={params}
```
* fade, fly, slide, scale, draw
* crossfade...
---
### `svelte/animation`
Animates the stroke of an SVG element, like a snake in a tube. `in` transitions begin with the path invisible and draw the path to the screen over time. `out` transitions start in a visible state and gradually erase the path. `draw` only works with elements that have a `getTotalLength` method, like `<path>` and `<polyline>`.
TODO
`draw` accepts the following parameters:
* `delay` (`number`, default 0) — milliseconds before starting
* `speed` (`number`, default undefined) - the speed of the animation, see below.
* `duration` (`number` | `function`, default 800) — milliseconds the transition lasts
* `easing` (`function`, default `cubicInOut`) — an [easing function](docs#svelte_easing)
The `speed` parameter is a means of setting the duration of the transition relative to the path's length. It is modifier that is applied to the length of the path: `duration = length / speed`. A path that is 1000 pixels with a speed of 1 will have a duration of `1000ms`, setting the speed to `0.5` will double that duration and setting it to `2` will halve it.
```html
<script>
import { draw } from 'svelte/transition';
import { quintOut } from 'svelte/easing';
</script>
<svg viewBox="0 0 5 5" xmlns="http://www.w3.org/2000/svg">
{#if condition}
<path transition:draw="{{duration: 5000, delay: 500, easing: quintOut}}"
d="M2 1 h1 v1 h1 v1 h-1 v1 h-1 v-1 h-1 v-1 h1 z"
fill="none"
stroke="cornflowerblue"
stroke-width="0.1px"
stroke-linejoin="round"
/>
{/if}
</svg>
```
<!-- Crossfade is coming soon... -->
### `svelte/animate`
The `svelte/animate` module exports one function for use with svelte [animations](docs#Animations).
#### `flip`
```sv
animate:flip={params}
```
The `flip` function calculates the start and end position of an element and animates between them, translating the `x` and `y` values. `flip` stands for [First, Last, Invert, Play](https://aerotwist.com/blog/flip-your-animations/).
`flip` accepts the following parameters:
* `delay` (`number`, default 0) — milliseconds before starting
* `duration` (`number` | `function`, default `d => Math.sqrt(d) * 120`) — see below
* `easing` (`function`, default [`cubicOut`](docs#cubicOut)) — an [easing function](docs#svelte_easing)
`duration` can be be provided as either:
- a `number`, in milliseconds.
- a function, `distance: number => duration: number`, receiving the distance the element will travel in pixels and returning the duration in milliseconds. This allows you to assign a duration that is relative to the distance travelled by each element.
---
You can see a full example on the [animations tutorial](tutorial/animate)
```html
<script>
import { flip } from 'svelte/animate';
import { quintOut } from 'svelte/easing';
let list = [1, 2, 3];
</script>
{#each list as n (n)}
<div animate:flip="{{delay: 250, duration: 250, easing: quintOut}}">
{n}
</div>
{/each}
```
* TODO this doesn't even exist yet
TODO
### `svelte/easing`
* TODO could have nice little interactive widgets showing the different functions, maybe
Easing functions specificy the rate of change over time and are useful when working with Svelte's built-in transitions and animations as well as the tweened and spring utilities. `svelte/easing` contains 31 named exports, a `linear` ease and 3 variants of 10 different easing functions: `in`, `out` and `inOut`.
You can explore the various eases using the [ease visualiser](examples#easing) in the [examples section](examples).
| ease | in | out | inOut |
| --- | --- | --- | --- |
| **back** | `backIn` | `backOut` | `backInOut` |
| **bounce** | `bounceIn` | `bounceOut` | `bounceInOut` |
| **circ** | `circIn` | `circOut` | `circInOut` |
| **cubic** | `cubicIn` | `cubicOut` | `cubicInOut` |
| **elastic** | `elasticIn` | `elasticOut` | `elasticInOut` |
| **expo** | `expoIn` | `expoOut` | `expoInOut` |
| **quad** | `quadIn` | `quadOut` | `quadInOut` |
| **quart** | `quartIn` | `quartOut` | `quartInOut` |
| **quint** | `quintIn` | `quintOut` | `quintInOut` |
| **sine** | `sineIn` | `sineOut` | `sineInOut` |
### `svelte/register`
TODO
To render Svelte components in Node.js without bundling, use `require('svelte/register')`. After that, you can use `require` to include any `.svelte` file.
```js
require('svelte/register');
const App = require('./App.svelte').default;
...
const { html, css, head } = App.render({ answer: 42 });
```
> The `.default` is necessary because we're converting from native JavaScript modules to the CommonJS modules recognised by Node. Note that if your component imports JavaScript modules, they will fail to load in Node and you will need to use a bundler instead.
To set compile options, or to use a custom file extension, call the `register` hook as a function:
```js
require('svelte/register')({
extensions: ['.customextension'], // defaults to ['.html', '.svelte']
preserveComments: true
});
```
### Client-side component API
@ -500,8 +857,6 @@ TODO
const component = new Component(options)
```
---
A client-side component — that is, a component compiled with `generate: 'dom'` (or the `generate` option left unspecified) is a JavaScript class.
```js
@ -532,7 +887,7 @@ Existing children of `target` are left where they are.
---
The `hydrate` option instructs Svelte to upgrade existing DOM (usually from server-side rendering) rather than creating new elements. It will only work if the component was compiled with the [`hydratable: true` option](docs#svelte_compile).
The `hydrate` option instructs Svelte to upgrade existing DOM (usually from server-side rendering) rather than creating new elements. It will only work if the component was compiled with the [`hydratable: true` option](docs#svelte_compile). Hydration of `<head>` elements only works properly if the server-side rendering code was also compiled with `hydratable: true`, which adds a marker to each element in the `<head>` so that the component knows which elements it's responsible for removing during hydration.
Whereas children of `target` are normally left alone, `hydrate: true` will cause any children to be removed. For that reason, the `anchor` option cannot be used alongside `hydrate: true`.
@ -573,10 +928,14 @@ component.$on(event, callback)
Causes the `callback` function to be called whenever the component dispatches an `event`.
A function is returned that will remove the event listener when called.
```js
app.$on('selected', event => {
const off = app.$on('selected', event => {
console.log(event.detail.selection);
});
off();
```
#### `$destroy`
@ -610,7 +969,68 @@ app.count += 1;
### Custom element API
* TODO
---
Svelte components can also be compiled to custom elements (aka web components) using the `customElement: true` compiler option. You should specify a tag name for the component using the `<svelte:options>` [element](docs#svelte_options).
```html
<svelte:options tag="my-element">
<script>
export let name = 'world';
</script>
<h1>Hello {name}!</h1>
<slot></slot>
```
---
Alternatively, use `tag={null}` to indicate that the consumer of the custom element should name it.
```js
import MyElement from './MyElement.svelte';
customElements.define('my-element', MyElement);
```
---
Once a custom element has been defined, it can be used as a regular DOM element:
```js
document.body.innerHTML = `
<my-element>
<p>This is some slotted content</p>
</my-element>
`;
```
---
By default, custom elements are compiled with `accessors: true`, which means that any [props](docs#Attributes_and_props) are exposed as properties of the DOM element (as well as being readable/writable as attributes, where possible).
To prevent this, add `accessors={false}` to `<svelte:options>`.
```js
const el = document.querySelector('my-element');
// get the current value of the 'name' prop
console.log(el.name);
// set a new value, updating the shadow DOM
el.name = 'everybody';
```
Custom elements can be a useful way to package components for consumption in a non-Svelte app, as they will work with vanilla HTML and JavaScript as well as [most frameworks](https://custom-elements-everywhere.com/). There are, however, some important differences to be aware of:
* Styles are *encapsulated*, rather than merely *scoped*. This means that any non-component styles (such as you might have in a `global.css` file) will not apply to the custom element, including styles with the `:global(...)` modifier
* Instead of being extracted out as a separate .css file, styles are inlined into the component as a JavaScript string
* Custom elements are not generally suitable for server-side rendering, as the shadow DOM is invisible until JavaScript loads
* In Svelte, slotted content renders *lazily*. In the DOM, it renders *eagerly*. In other words, it will always be created even if the component's `<slot>` element is inside an `{#if ...}` block. Similarly, including a `<slot>` in an `{#each ...}` block will not cause the slotted content to be rendered multiple times
* The `let:` directive has no effect
* Polyfills are required to support older browsers
### Server-side component API
@ -625,8 +1045,12 @@ Unlike client-side components, server-side components don't have a lifespan afte
A server-side component exposes a `render` method that can be called with optional props. It returns an object with `head`, `html`, and `css` properties, where `head` contains the contents of any `<svelte:head>` elements encountered.
You can import a Svelte component directly into Node using [`svelte/register`](docs#svelte_register).
```js
const App = require('./App.svelte');
require('svelte/register');
const App = require('./App.svelte').default;
const { head, html, css } = App.render({
answer: 42

@ -4,9 +4,9 @@ title: Compile time
Typically, you won't interact with the Svelte compiler directly, but will instead integrate it into your build system using a bundler plugin:
* [rollup-plugin-svelte](https://github.com/rollup/rollup-plugin-svelte) for users of [Rollup](https://rollupjs.org)
* [rollup-plugin-svelte](https://github.com/sveltejs/rollup-plugin-svelte) for users of [Rollup](https://rollupjs.org)
* [svelte-loader](https://github.com/sveltejs/svelte-loader) for users of [webpack](https://webpack.js.org)
* [parcel-plugin-svelte](https://github.com/DeMoorJasper/parcel-plugin-svelte) for users of [Parcel](https://parceljs.org/)
* or one of the [community-maintained plugins](https://github.com/sveltejs/integrations#bundler-plugins)
Nonetheless, it's useful to understand how to use the compiler, since bundler plugins generally expose compiler options to you.
@ -53,6 +53,7 @@ The following options can be passed to the compiler. None are required:
| `tag` | string | null
| `accessors` | boolean | `false`
| `css` | boolean | `true`
| `loopGuardTimeout` | number | 0
| `preserveComments` | boolean | `false`
| `preserveWhitespace` | boolean | `false`
| `outputFilename` | string | `null`
@ -67,14 +68,15 @@ The following options can be passed to the compiler. None are required:
| `generate` | `"dom"` | If `"dom"`, Svelte emits a JavaScript class for mounting to the DOM. If `"ssr"`, Svelte emits an object with a `render` method suitable for server-side rendering. If `false`, no JavaScript or CSS is returned; just metadata.
| `dev` | `false` | If `true`, causes extra code to be added to components that will perform runtime checks and provide debugging information during development.
| `immutable` | `false` | If `true`, tells the compiler that you promise not to mutate any objects. This allows it to be less conservative about checking whether values have changed.
| `hydratable` | `false` | If `true`, enables the `hydrate: true` runtime option, which allows a component to upgrade existing DOM rather than creating new DOM from scratch.
| `hydratable` | `false` | If `true` when generating DOM code, enables the `hydrate: true` runtime option, which allows a component to upgrade existing DOM rather than creating new DOM from scratch. When generating SSR code, this adds markers to `<head>` elements so that hydration knows which to replace.
| `legacy` | `false` | If `true`, generates code that will work in IE9 and IE10, which don't support things like `element.dataset`.
| `accessors` | `false` | If `true`, getters and setters will be created for the component's props. If `false`, they will only be created for readonly exported values (i.e. those declared with `const`, `class` and `function`). If compiling with `customElement: true` this option defaults to `true`.
| `customElement` | `false` | If `true`, tells the compiler to generate a custom element constructor instead of a regular Svelte component.
| `tag` | `null` | A `string` that tells Svelte what tag name to register the custom element with. It must be a lowercase alphanumeric string with at least one hyphen, e.g. `"my-element"`.
| `css` | `true` | If `true`, styles will be included in the JavaScript class and injected at runtime. It's recommended that you set this to `false` and use the CSS that is statically generated, as it will result in smaller JavaScript bundles and better performance.
| `loopGuardTimeout` | 0 | A `number` that tells Svelte to break the loop if it blocks the thread for more than `loopGuardTimeout` ms. This is useful to prevent infinite loops. **Only available when `dev: true`**
| `preserveComments` | `false` | If `true`, your HTML comments will be preserved during server-side rendering. By default, they are stripped out.
| `preserveWhitespace` | `false` | If `true`, whitespace inside and between elements is kept as you typed it, rather than optimised by Svelte.
| `preserveWhitespace` | `false` | If `true`, whitespace inside and between elements is kept as you typed it, rather than removed or collapsed to a single space where possible.
| `outputFilename` | `null` | A `string` used for your JavaScript sourcemap.
| `cssOutputFilename` | `null` | A `string` used for your CSS sourcemap.
| `sveltePath` | `"svelte"` | The location of the `svelte` package. Any imports from `svelte` or `svelte/[module]` will be modified accordingly.
@ -153,24 +155,48 @@ compiled: {
-->
### `svelte.parse`
```js
ast: object = svelte.parse(
source: string,
options?: {
filename?: string,
customElement?: boolean
}
)
```
---
The `parse` function parses a component, returning only its abstract syntax tree. Unlike compiling with the `generate: false` option, this will not perform any validation or other analysis of the component beyond parsing it.
```js
const svelte = require('svelte/compiler');
const ast = svelte.parse(source, { filename: 'App.svelte' });
```
### `svelte.preprocess`
```js
result: {
code: string,
dependencies: Array<string>
} = svelte.preprocess(
} = await svelte.preprocess(
source: string,
preprocessors: Array<{
markup?: (input: { source: string, filename: string }) => Promise<{
markup?: (input: { content: string, filename: string }) => Promise<{
code: string,
dependencies?: Array<string>
}>,
script?: (input: { source: string, attributes: Record<string, string>, filename: string }) => Promise<{
script?: (input: { content: string, attributes: Record<string, string>, filename: string }) => Promise<{
code: string,
dependencies?: Array<string>
}>,
style?: (input: { source: string, attributes: Record<string, string>, filename: string }) => Promise<{
style?: (input: { content: string, attributes: Record<string, string>, filename: string }) => Promise<{
code: string,
dependencies?: Array<string>
}>
@ -196,7 +222,7 @@ The `markup` function receives the entire component source text, along with the
```js
const svelte = require('svelte/compiler');
const { code } = svelte.preprocess(source, {
const { code } = await svelte.preprocess(source, {
markup: ({ content, filename }) => {
return {
code: content.replace(/foo/g, 'bar')
@ -211,14 +237,14 @@ const { code } = svelte.preprocess(source, {
The `script` and `style` functions receive the contents of `<script>` and `<style>` elements respectively. In addition to `filename`, they get an object of the element's attributes.
If a `dependencies` array is returned, it will be included in the result object. This is used by packages like [rollup-plugin-svelte](https://github.com/rollup/rollup-plugin-svelte) to watch additional files for changes, in the case where your `<style>` tag has an `@import` (for example).
If a `dependencies` array is returned, it will be included in the result object. This is used by packages like [rollup-plugin-svelte](https://github.com/sveltejs/rollup-plugin-svelte) to watch additional files for changes, in the case where your `<style>` tag has an `@import` (for example).
```js
const svelte = require('svelte/compiler');
const sass = require('node-sass');
const { dirname } = require('path');
const { code, dependencies } = svelte.preprocess(source, {
const { code, dependencies } = await svelte.preprocess(source, {
style: async ({ content, attributes, filename }) => {
// only process <style lang="sass">
if (attributes.lang !== 'sass') return;
@ -251,7 +277,7 @@ Multiple preprocessors can be used together. The output of the first becomes the
```js
const svelte = require('svelte/compiler');
const { code } = svelte.preprocess(source, [
const { code } = await svelte.preprocess(source, [
{
markup: () => {
console.log('this runs first');
@ -280,6 +306,38 @@ const { code } = svelte.preprocess(source, [
```
### `svelte.walk`
```js
walk(ast: Node, {
enter(node: Node, parent: Node, prop: string, index: number)?: void,
leave(node: Node, parent: Node, prop: string, index: number)?: void
})
```
---
The `walk` function provides a way to walk the abstract syntax trees generated by the parser, using the compiler's own built-in instance of [estree-walker](https://github.com/Rich-Harris/estree-walker).
The walker takes an abstract syntax tree to walk and an object with two optional methods: `enter` and `leave`. For each node, `enter` is called (if present). Then, unless `this.skip()` is called during `enter`, each of the children are traversed, and then `leave` is called on the node.
```js
const svelte = require('svelte/compiler');
svelte.walk(ast, {
enter(node, parent, prop, index) {
do_something(node);
if (should_skip_children(node)) {
this.skip();
}
},
leave(node, parent, prop, index) {
do_something_else(node);
}
});
```
### `svelte.VERSION`
---

@ -1,7 +1,7 @@
<style>
p {
color: purple;
font-family: 'Comic Sans MS';
font-family: 'Comic Sans MS', cursive;
font-size: 2em;
}
</style>

@ -5,7 +5,7 @@
<style>
p {
color: purple;
font-family: 'Comic Sans MS';
font-family: 'Comic Sans MS', cursive;
font-size: 2em;
}
</style>

@ -2,11 +2,11 @@
import Thing from './Thing.svelte';
let things = [
{ id: 1, value: 'a' },
{ id: 2, value: 'b' },
{ id: 3, value: 'c' },
{ id: 4, value: 'd' },
{ id: 5, value: 'e' }
{ id: 1, color: '#0d0887' },
{ id: 2, color: '#6a00a8' },
{ id: 3, color: '#b12a90' },
{ id: 4, color: '#e16462' },
{ id: 5, color: '#fca636' }
];
function handleClick() {
@ -22,14 +22,14 @@
<div>
<h2>Keyed</h2>
{#each things as thing (thing.id)}
<Thing value={thing.value}/>
<Thing current={thing.color}/>
{/each}
</div>
<div>
<h2>Unkeyed</h2>
{#each things as thing}
<Thing value={thing.value}/>
<Thing current={thing.color}/>
{/each}
</div>
</div>

@ -1,9 +1,24 @@
<script>
// `value` is updated whenever the prop value changes...
export let value;
// `current` is updated whenever the prop value changes...
export let current;
// ...but `valueAtStart` is fixed upon initialisation
const valueAtStart = value;
// ...but `initial` is fixed upon initialisation
const initial = current;
</script>
<p>{valueAtStart} / {value}</p>
<p>
<span style="background-color: {initial}">initial</span>
<span style="background-color: {current}">current</span>
</p>
<style>
span {
display: inline-block;
padding: 0.2em 0.5em;
margin: 0 0.2em 0.2em 0;
width: 4em;
text-align: center;
border-radius: 0.2em;
color: white;
}
</style>

@ -1,6 +1,6 @@
<style>
button {
font-family: 'Comic Sans MS';
font-family: 'Comic Sans MS', cursive;
font-size: 2em;
padding: 0.5em 1em;
color: royalblue;

@ -1,12 +1,12 @@
<script>
import marked from 'marked';
let value = `Some words are *italic*, some are **bold**`;
let text = `Some words are *italic*, some are **bold**`;
</script>
<style>
textarea { width: 100%; height: 200px; }
</style>
<textarea bind:value></textarea>
<textarea bind:value={text}></textarea>
{@html marked(value)}
{@html marked(text)}

@ -14,7 +14,7 @@
showControlsTimeout = setTimeout(() => showControls = false, 2500);
showControls = true;
if (e.which !== 1) return; // mouse not down
if (!(e.buttons & 1)) return; // mouse not down
if (!duration) return; // video not loaded yet
const { left, right } = this.getBoundingClientRect();
@ -109,8 +109,8 @@
<div>
<video
poster="http://svelte-assets.surge.sh/caminandes-llamigos.jpg"
src="http://svelte-assets.surge.sh/caminandes-llamigos.mp4"
poster="http://sveltejs.github.io/assets/caminandes-llamigos.jpg"
src="http://sveltejs.github.io/assets/caminandes-llamigos.mp4"
on:mousemove={handleMousemove}
on:mousedown={handleMousedown}
bind:currentTime={time}

@ -2,10 +2,6 @@
import { onMount } from 'svelte';
let canvas;
let ctx;
let running = false;
const r = Math.random();
onMount(() => {
const ctx = canvas.getContext('2d');
@ -47,8 +43,8 @@
width: 100%;
height: 100%;
background-color: #666;
-webkit-mask: url(logo-mask.svg) 50% 50% no-repeat;
mask: url(logo-mask.svg) 50% 50% no-repeat;
-webkit-mask: url(svelte-logo-mask.svg) 50% 50% no-repeat;
mask: url(svelte-logo-mask.svg) 50% 50% no-repeat;
}
</style>

@ -1,5 +1,5 @@
<script>
import Eliza from 'elizanode';
import Eliza from 'elizabot';
import { beforeUpdate, afterUpdate } from 'svelte';
let div;

@ -1,140 +1,153 @@
<script>
import { quintOut } from 'svelte/easing';
import crossfade from './crossfade.js'; // TODO put this in svelte/transition!
const { send, receive } = crossfade({
fallback(node, params) {
const style = getComputedStyle(node);
const transform = style.transform === 'none' ? '' : style.transform;
return {
duration: 600,
easing: quintOut,
css: t => `
transform: ${transform} scale(${t});
opacity: ${t}
`
};
}
import { crossfade, scale } from 'svelte/transition';
import images from './images.js';
const [send, receive] = crossfade({
duration: 200,
fallback: scale
});
let todos = [
{ id: 1, done: false, description: 'write some docs' },
{ id: 2, done: false, description: 'start writing JSConf talk' },
{ id: 3, done: true, description: 'buy some milk' },
{ id: 4, done: false, description: 'mow the lawn' },
{ id: 5, done: false, description: 'feed the turtle' },
{ id: 6, done: false, description: 'fix some bugs' },
];
let uid = todos.length + 1;
function add(input) {
const todo = {
id: uid++,
done: false,
description: input.value
};
let selected = null;
let loading = null;
todos = [todo, ...todos];
input.value = '';
}
const ASSETS = `https://sveltejs.github.io/assets/crossfade`;
function remove(todo) {
todos = todos.filter(t => t !== todo);
}
const load = image => {
const timeout = setTimeout(() => loading = image, 100);
const img = new Image();
img.onload = () => {
selected = image;
clearTimeout(timeout);
loading = null;
};
img.src = `${ASSETS}/${image.id}.jpg`;
};
</script>
<div class="container">
<div class="phone">
<h1>Photo gallery</h1>
<div class="grid">
{#each images as image}
<div class="square">
{#if selected !== image}
<button
style="background-color: {image.color};"
on:click="{() => load(image)}"
in:receive={{key:image.id}}
out:send={{key:image.id}}
>{loading === image ? '...' : image.id}</button>
{/if}
</div>
{/each}
</div>
{#if selected}
{#await selected then d}
<div class="photo" in:receive={{key:d.id}} out:send={{key:d.id}}>
<img
alt={d.alt}
src="{ASSETS}/{d.id}.jpg"
on:click="{() => selected = null}"
>
<p class='credit'>
<a target="_blank" href="https://www.flickr.com/photos/{d.path}">via Flickr</a> &ndash;
<a target="_blank" href={d.license.url}>{d.license.name}</a>
</p>
</div>
{/await}
{/if}
</div>
</div>
<style>
.new-todo {
font-size: 1.4em;
.container {
position: absolute;
display: flex;
align-items: center;
justify-content: center;
width: 100%;
margin: 2em 0 1em 0;
height: 100%;
top: 0;
left: 0;
}
.board {
max-width: 36em;
margin: 0 auto;
.phone {
position: relative;
display: flex;
flex-direction: column;
width: 52vmin;
height: 76vmin;
border: 2vmin solid #ccc;
border-bottom-width: 10vmin;
padding: 3vmin;
border-radius: 2vmin;
}
.left, .right {
float: left;
width: 50%;
padding: 0 1em 0 0;
box-sizing: border-box;
h1 {
font-weight: 300;
text-transform: uppercase;
font-size: 5vmin;
margin: 0.2em 0 0.5em 0;
}
h2 {
font-size: 2em;
font-weight: 200;
user-select: none;
.grid {
display: grid;
flex: 1;
grid-template-columns: repeat(3, 1fr);
grid-template-rows: repeat(4, 1fr);
grid-gap: 2vmin;
}
label {
button {
width: 100%;
height: 100%;
color: white;
font-size: 5vmin;
border: none;
margin: 0;
will-change: transform;
}
.photo, img {
position: absolute;
top: 0;
left: 0;
display: block;
font-size: 1em;
line-height: 1;
padding: 0.5em;
margin: 0 auto 0.5em auto;
border-radius: 2px;
background-color: #eee;
user-select: none;
width: 100%;
height: 100%;
overflow: hidden;
}
input { margin: 0 }
.photo {
display: flex;
align-items: stretch;
justify-content: flex-end;
flex-direction: column;
will-change: transform;
}
.right label {
background-color: rgb(180,240,100);
img {
object-fit: cover;
cursor: pointer;
}
button {
float: right;
height: 1em;
box-sizing: border-box;
padding: 0 0.5em;
line-height: 1;
background-color: transparent;
border: none;
color: rgb(170,30,30);
opacity: 0;
transition: opacity 0.2s;
.credit {
text-align: right;
font-size: 2.5vmin;
padding: 1em;
margin: 0;
color: white;
font-weight: bold;
opacity: 0.6;
background: rgba(0,0,0,0.4);
}
label:hover button {
opacity: 1;
.credit a, .credit a:visited {
color: white;
}
</style>
<div class='board'>
<input class="new-todo" placeholder="what needs to be done?" on:keydown="{event => event.which === 13 && add(event.target)}">
<div class='left'>
<h2>todo</h2>
{#each todos.filter(t => !t.done) as todo (todo.id)}
<label
in:receive="{{key: todo.id}}"
out:send="{{key: todo.id}}"
>
<input type=checkbox bind:checked={todo.done}>
{todo.description}
<button on:click="{() => remove(todo)}">x</button>
</label>
{/each}
</div>
<div class='right'>
<h2>done</h2>
{#each todos.filter(t => t.done) as todo (todo.id)}
<label
in:receive="{{key: todo.id}}"
out:send="{{key: todo.id}}"
>
<input type=checkbox bind:checked={todo.done}>
{todo.description}
<button on:click="{() => remove(todo)}">x</button>
</label>
{/each}
</div>
</div>

@ -1,65 +0,0 @@
import { quintOut } from 'svelte/easing';
export default function crossfade({ send, receive, fallback }) {
let requested = new Map();
let provided = new Map();
function crossfade(from, node) {
const to = node.getBoundingClientRect();
const dx = from.left - to.left;
const dy = from.top - to.top;
const style = getComputedStyle(node);
const transform = style.transform === 'none' ? '' : style.transform;
return {
duration: 400,
easing: quintOut,
css: (t, u) => `
opacity: ${t};
transform: ${transform} translate(${u * dx}px,${u * dy}px);
`
};
}
return {
send(node, params) {
provided.set(params.key, {
rect: node.getBoundingClientRect()
});
return () => {
if (requested.has(params.key)) {
const { rect } = requested.get(params.key);
requested.delete(params.key);
return crossfade(rect, node);
}
// if the node is disappearing altogether
// (i.e. wasn't claimed by the other list)
// then we need to supply an outro
provided.delete(params.key);
return fallback(node, params);
};
},
receive(node, params) {
requested.set(params.key, {
rect: node.getBoundingClientRect()
});
return () => {
if (provided.has(params.key)) {
const { rect } = provided.get(params.key);
provided.delete(params.key);
return crossfade(rect, node);
}
requested.delete(params.key);
return fallback(node, params);
};
}
};
}

@ -0,0 +1,102 @@
const BY = {
name: 'CC BY 2.0',
url: 'https://creativecommons.org/licenses/by/2.0/'
};
const BY_SA = {
name: 'CC BY-SA 2.0',
url: 'https://creativecommons.org/licenses/by-sa/2.0/'
};
const BY_ND = {
name: 'CC BY-ND 2.0',
url: 'https://creativecommons.org/licenses/by-nd/2.0/'
};
// via http://labs.tineye.com/multicolr
export default [
{
color: '#001f3f',
id: '1',
alt: 'Crepuscular rays',
path: '43428526@N03/7863279376',
license: BY
},
{
color: '#0074D9',
id: '2',
alt: 'Lapland winter scene',
path: '25507134@N00/6527537485',
license: BY
},
{
color: '#7FDBFF',
id: '3',
alt: 'Jellyfish',
path: '37707866@N00/3354331318',
license: BY
},
{
color: '#39CCCC',
id: '4',
alt: 'A man scuba diving',
path: '32751486@N00/4608886209',
license: BY_SA
},
{
color: '#3D9970',
id: '5',
alt: 'Underwater scene',
path: '25483059@N08/5548569010',
license: BY
},
{
color: '#2ECC40',
id: '6',
alt: 'Ferns',
path: '8404611@N06/2447470760',
license: BY
},
{
color: '#01FF70',
id: '7',
alt: 'Posters in a bar',
path: '33917831@N00/114428206',
license: BY_SA
},
{
color: '#FFDC00',
id: '8',
alt: 'Daffodil',
path: '46417125@N04/4818617089',
license: BY_ND
},
{
color: '#FF851B',
id: '9',
alt: 'Dust storm in Sydney',
path: '56068058@N00/3945496657',
license: BY
},
{
color: '#FF4136',
id: '10',
alt: 'Postbox',
path: '31883499@N05/4216820032',
license: BY
},
{
color: '#85144b',
id: '11',
alt: 'Fireworks',
path: '8484971@N07/2625506561',
license: BY_ND
},
{
color: '#B10DC9',
id: '12',
alt: 'The Stereophonics',
path: '58028312@N00/5385464371',
license: BY_ND
}
];

@ -1,8 +1,9 @@
<script>
import { quintOut } from 'svelte/easing';
import crossfade from './crossfade.js'; // TODO put this in svelte/transition!
import { crossfade } from 'svelte/transition';
import { flip } from 'svelte/animate';
const { send, receive } = crossfade({
const [send, receive] = crossfade({
fallback(node, params) {
const style = getComputedStyle(node);
const transform = style.transform === 'none' ? '' : style.transform;
@ -43,12 +44,6 @@
function remove(todo) {
todos = todos.filter(t => t !== todo);
}
function handleKeydown(event) {
if (event.which === 13) {
addTodo(event.target);
}
}
</script>
<style>
@ -114,7 +109,11 @@
</style>
<div class='board'>
<input class="new-todo" placeholder="what needs to be done?" on:enter={add}>
<input
class="new-todo"
placeholder="what needs to be done?"
on:keydown="{event => event.which === 13 && add(event.target)}"
>
<div class='left'>
<h2>todo</h2>
@ -122,6 +121,7 @@
<label
in:receive="{{key: todo.id}}"
out:send="{{key: todo.id}}"
animate:flip
>
<input type=checkbox bind:checked={todo.done}>
{todo.description}
@ -136,6 +136,7 @@
<label
in:receive="{{key: todo.id}}"
out:send="{{key: todo.id}}"
animate:flip
>
<input type=checkbox bind:checked={todo.done}>
{todo.description}

@ -1,65 +0,0 @@
import { quintOut } from 'svelte/easing';
export default function crossfade({ send, receive, fallback }) {
let requested = new Map();
let provided = new Map();
function crossfade(from, node) {
const to = node.getBoundingClientRect();
const dx = from.left - to.left;
const dy = from.top - to.top;
const style = getComputedStyle(node);
const transform = style.transform === 'none' ? '' : style.transform;
return {
duration: 400,
easing: quintOut,
css: (t, u) => `
opacity: ${t};
transform: ${transform} translate(${u * dx}px,${u * dy}px);
`
};
}
return {
send(node, params) {
provided.set(params.key, {
rect: node.getBoundingClientRect()
});
return () => {
if (requested.has(params.key)) {
const { rect } = requested.get(params.key);
requested.delete(params.key);
return crossfade(rect, node);
}
// if the node is disappearing altogether
// (i.e. wasn't claimed by the other list)
// then we need to supply an outro
provided.delete(params.key);
return fallback(node, params);
};
},
receive(node, params) {
requested.set(params.key, {
rect: node.getBoundingClientRect()
});
return () => {
if (provided.has(params.key)) {
const { rect } = provided.get(params.key);
provided.delete(params.key);
return crossfade(rect, node);
}
requested.delete(params.key);
return fallback(node, params);
};
}
};
}

@ -0,0 +1,106 @@
<script>
import { interpolateString as interpolate } from 'd3-interpolate';
import { tweened } from 'svelte/motion';
import Grid from './Grid.svelte';
import Controls from './Controls.svelte';
import { eases, types } from './eases.js';
let current_type = 'In';
let current_ease = 'sine';
let duration = 2000;
let current = eases.get(current_ease)[current_type];
let playing = false;
let width;
const ease_path = tweened(current.shape, { interpolate });
const time = tweened(0);
const value = tweened(1000);
async function runAnimations() {
playing = true;
value.set(1000, {duration: 0});
time.set(0, {duration: 0});
await ease_path.set(current.shape);
await Promise.all([
time.set(1000, {duration, easing: x => x}),
value.set(0, {duration, easing: current.fn})
]);
playing = false;
}
$: current = eases.get(current_ease)[current_type];
$: current && runAnimations();
</script>
<style>
.easing-vis {
display: flex;
max-height: 95%;
max-width: 800px;
margin: auto;
padding: 10px;
border: 1px solid #333;
border-radius: 2px;
padding: 20px;
}
svg {
width: 100%;
margin: 0 20px 0 0;
}
.graph {
transform: translate(200px,400px)
}
@media (max-width:600px) {
.easing-vis {
flex-direction: column;
max-height: calc(100% - 3rem);
}
}
</style>
<div bind:offsetWidth={width} class="easing-vis">
<svg viewBox="0 0 1400 1802">
<g class="canvas">
<Grid x={$time} y={$value}/>
<g class="graph">
<path
d={$ease_path}
stroke="#333"
stroke-width="2"
fill="none"
/>
<path d="M0,23.647C0,22.41 27.014,0.407 28.496,0.025C29.978,-0.357 69.188,3.744 70.104,4.744C71.02,5.745 71.02,41.499 70.104,42.5C69.188,43.501 29.978,47.601 28.496,47.219C27.014,46.837 0,24.884 0,23.647Z"
fill="#ff3e00"
style="transform: translate(1060px, {($value - 24)}px)"
/>
<circle
cx="{$time}"
cy="{$value}"
r="15"
fill="#ff3e00"
/>
</g>
</g>
</svg>
<Controls
{eases}
{types}
{playing}
{width}
bind:duration
bind:current_ease
bind:current_type
on:play={runAnimations}
/>
</div>

@ -0,0 +1,186 @@
<script>
import { createEventDispatcher } from 'svelte';
export let current_ease;
export let current_type;
export let eases;
export let types;
export let duration;
export let playing;
export let width;
const dispatch = createEventDispatcher();
$: mobile = width && width < 600;
</script>
<style>
.easing-sidebar {
width: 11em;
}
ul {
list-style: none;
padding: 0;
display: flex;
flex-direction: column;
align-items: flex-start;
font-size: 18px;
}
li {
padding: 5px 10px;
background: #eee;
border-radius: 2px;
margin: 3px 0;
cursor:pointer;
}
li:hover {
background: #676778;
color: white;
}
.selected {
background: #ff3e00;
color: white;
}
h3 {
margin: 0 10px 0 0;
}
h4 {
margin-bottom: 0;
}
select {
display: inline;
padding: 0.2em;
margin: 0;
}
.duration {
width: 100%;
display: flex;
align-items: center;
flex-wrap: wrap;
}
.duration span {
display: flex;
}
.duration input {
width: 80px;
margin: 10px 10px 10px 0 ;
}
.duration button {
margin: 10px 5px;
}
.duration .number {
width: 30px;
}
.duration .play {
margin: 0 5px 0 auto;
width: 100%;
}
@media (max-width:600px) {
.easing-types {
display: flex;
align-items: center;
margin-top: 10px;
}
.easing-sidebar {
width: 100%;
}
.duration .play {
margin-left: auto;
width: unset;
}
h3 {
font-size: 0.9em;
display: inline;
}
h3:nth-of-type(2) {
margin-left: auto;
}
ul li {
margin-right: 10px;
}
}
</style>
<div class="easing-sidebar">
<div class="easing-types">
<h3>Ease</h3>
{#if mobile}
<select bind:value={current_ease}>
{#each [...eases] as [name]}
<option
value={name}
class:selected={name === current_ease}
>
{name}
</option>
{/each}
</select>
{:else}
<ul>
{#each [...eases] as [name]}
<li
class:selected={name === current_ease}
on:click={() => current_ease = name}
>
{name}
</li>
{/each}
</ul>
{/if}
<h3>Type</h3>
{#if mobile }
<select bind:value={current_type}>
{#each types as [name, type]}
<option
value={type}
>
{name}
</option>
{/each}
</select>
{:else}
<ul>
{#each types as [name, type]}
<li
class:selected={type === current_type}
on:click={() => current_type = type}
>
{name}
</li>
{/each}
</ul>
{/if}
</div>
<h4>
Duration
</h4>
<div class="duration">
<span>
<input type="number" bind:value={duration} min="0" step="100"/>
<button class="number" on:click={() => duration -= 100}>-</button>
<button class="number" on:click={() => duration += 100}>+</button>
</span>
<button class="play" on:click={() => dispatch('play')}>
{playing ? 'Restart' : 'Play'}
</button>
</div>
</div>

@ -0,0 +1,62 @@
<script>
export let x, y;
</script>
<style>
.grid-line {
stroke:#ccc;
opacity: 0.5;
stroke-width: 2;
}
.grid-line-xy {
stroke: tomato;
stroke-width: 2;
}
</style>
<svelte:options namespace="svg" />
<rect
x=0
y=0
width=1400
height=1800
stroke=#ccc
style="opacity: 0.5"
fill=none
stroke-width=2
/>
{#each { length: 8 } as _, i}
{#if i < 6}
<path
d="M{(i+1) * 200} 0 L{(i+1)*200} 1802"
class="grid-line"
/>
{/if}
<path
d="M0 {(i+1) * 200} L1400 {(i+1)*200} "
class="grid-line"
/>
{/each}
<path
style="transform: translateX({x+200}px)"
d="M0 0 L0 1800"
class="grid-line-xy"
/>
<path
style="transform: translateY({y}px)"
d="M0 400 L1400 400"
class="grid-line-xy"
/>
<rect
x=200
y=400
width=1000
height=1000
stroke=#999
fill=none
stroke-width=2
/>

@ -0,0 +1,43 @@
import * as eases from 'svelte/easing';
const processed_eases = {};
for (const ease in eases) {
if (ease === "linear") {
processed_eases.linear = eases.linear;
} else {
const name = ease.replace(/In$|InOut$|Out$/, '');
const type = ease.match(/In$|InOut$|Out$/)[0];
if (!(name in processed_eases)) processed_eases[name] = {};
processed_eases[name][type] = {};
processed_eases[name][type].fn = eases[ease];
let shape = 'M0 1000';
for (let i = 1; i <= 1000; i++) {
shape = `${shape} L${(i / 1000) * 1000} ${1000 - eases[ease](i / 1000) * 1000} `;
processed_eases[name][type].shape = shape;
}
}
}
const sorted_eases = new Map([
['sine', processed_eases.sine],
['quad', processed_eases.quad],
['cubic', processed_eases.cubic],
['quart', processed_eases.quart],
['quint', processed_eases.quint],
['expo', processed_eases.expo],
['circ', processed_eases.circ],
['back', processed_eases.back],
['elastic', processed_eases.elastic],
['bounce', processed_eases.bounce],
]);
export const types = [
['Ease In', 'In'],
['Ease Out', 'Out'],
['Ease In Out', 'InOut']
];
export { sorted_eases as eases };

@ -0,0 +1,3 @@
{
"title": "Ease Visualiser"
}

@ -1,70 +0,0 @@
<script>
let language = "english";
const translations = {
english: {
tooltip: "Switch Languages",
},
latin: {
tooltip: "Itchsway Anguageslay",
}
};
function 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);
}
};
}
function toggleLanguage() {
language = language === 'english' ? 'latin' : 'english'
}
</script>
<button on:click={toggleLanguage} use:tooltip={translations[language].tooltip}>
{language}
</button>

@ -33,7 +33,7 @@
font-family: 'Overpass';
letter-spacing: 0.12em;
color: #676778;
font-weight: 100;
font-weight: 400;
}
.centered span {
@ -71,4 +71,4 @@
toggle me
</label>
<link href="https://fonts.googleapis.com/css?family=Overpass:100" rel="stylesheet">
<link href="https://fonts.googleapis.com/css?family=Overpass:100,400" rel="stylesheet">

@ -0,0 +1,20 @@
<script>
import { longpress } from './longpress.js';
let pressed = false;
let duration = 2000;
</script>
<label>
<input type=range bind:value={duration} max={2000} step={100}>
{duration}ms
</label>
<button use:longpress={duration}
on:longpress="{() => pressed = true}"
on:mouseenter="{() => pressed = false}"
>press and hold</button>
{#if pressed}
<p>congratulations, you pressed and held for {duration}ms</p>
{/if}

@ -0,0 +1,28 @@
export function longpress(node, duration) {
let timer;
const handleMousedown = () => {
timer = setTimeout(() => {
node.dispatchEvent(
new CustomEvent('longpress')
);
}, duration);
};
const handleMouseup = () => {
clearTimeout(timer)
};
node.addEventListener('mousedown', handleMousedown);
node.addEventListener('mouseup', handleMouseup);
return {
update(newDuration) {
duration = newDuration;
},
destroy() {
node.removeEventListener('mousedown', handleMousedown);
node.removeEventListener('mouseup', handleMouseup);
}
};
}

@ -1,45 +0,0 @@
<script>
import { createEventDispatcher } from 'svelte';
const dispatch = createEventDispatcher();
</script>
<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>
<div class='modal-background' on:click='{() => dispatch("close")}'></div>
<div class='modal'>
<slot name='header'></slot>
<hr>
<slot></slot>
<hr>
<button on:click='{() => dispatch("close")}'>close modal</button>
</div>

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

Loading…
Cancel
Save