Merge branch 'sveltejs:master' into gh-7578

pull/7699/head
Nico Beierle 4 years ago committed by GitHub
commit bb5d6e044c
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

@ -1,7 +1,47 @@
name: CI
on: [push, pull_request]
on:
push:
branches: [ master ]
pull_request:
permissions:
contents: read # to fetch code (actions/checkout)
jobs:
Setup:
runs-on: ${{ matrix.os }}
strategy:
matrix:
os: [ubuntu-latest, windows-latest, macOS-latest]
steps:
- uses: actions/checkout@v3
- uses: actions/setup-node@v3
with:
node-version: 18
cache: npm
- run: npm install
env:
SKIP_PREPARE: true
- run: npm run build
env:
PUBLISH: true
- name: Upload build assets
id: upload-artifact
uses: actions/upload-artifact@v3
with:
name: build-assets
path: |
index.*
compiler.*
ssr.*
action/
animate/
easing/
internal/
motion/
store/
transition/
types/
Tests:
needs: Setup
runs-on: ${{ matrix.os }}
timeout-minutes: 15
strategy:
@ -9,21 +49,28 @@ jobs:
node-version: [8, 10, 12, 14, 16]
os: [ubuntu-latest, windows-latest, macOS-latest]
steps:
- uses: actions/checkout@v1
- uses: actions/setup-node@v2
- uses: actions/checkout@v3
- uses: actions/setup-node@v3
with:
node-version: ${{ matrix.node-version }}
cache: npm
- name: Download build assets
uses: actions/download-artifact@v3
id: download-artifact
with:
name: build-assets
- run: npm install
- run: npm test
env:
SKIP_PREPARE: true
- run: npm run test:integration
env:
CI: true
Lint:
runs-on: ubuntu-latest
timeout-minutes: 5
steps:
- uses: actions/checkout@v1
- uses: actions/setup-node@v2
- uses: actions/checkout@v3
- uses: actions/setup-node@v3
with:
cache: npm
- run: 'npm i && npm run lint'
@ -34,8 +81,11 @@ jobs:
matrix:
os: [ubuntu-latest, windows-latest, macOS-latest]
steps:
- uses: actions/checkout@v1
- uses: actions/setup-node@v2
- uses: actions/checkout@v3
- uses: actions/setup-node@v3
with:
cache: npm
- run: 'npm i && npm run test:unit'
- run: npm install
env:
SKIP_PREPARE: true
- run: npm run test:unit

@ -7,6 +7,8 @@ on:
paths:
- site/content/**
permissions: {}
jobs:
release:
name: Deploy docs
@ -25,4 +27,4 @@ jobs:
repo: 'svelte'
branch: 'master'
docs_path: 'site/content'
token: ${{ steps.github-app.outputs.token }}
token: ${{ steps.github-app.outputs.token }}

1
.gitignore vendored

@ -21,3 +21,4 @@ node_modules
_actual*.*
_output
/types
.eslintcache

@ -1,7 +1,7 @@
const is_unit_test = process.env.UNIT_TEST;
module.exports = {
file: [
'test/test.ts'
],
file: is_unit_test ? [] : ['test/test.ts'],
require: [
'sucrase/register'
]

@ -0,0 +1,15 @@
module.exports = {
spec: [
'src/**/__test__.ts',
],
require: [
'sucrase/register'
],
recursive: true,
};
// add coverage options when running 'npx c8 mocha'
if (process.env.NODE_V8_COVERAGE) {
module.exports.fullTrace = true;
module.exports.require.push('source-map-support/register');
}

@ -2,11 +2,82 @@
## Unreleased
* Add a11y warning `a11y-role-has-required-aria-props` which checks that elements with `role` attribute has all required attributes for that role. ([#5852](https://github.com/sveltejs/svelte/pull/5852))
* Add a11y warning `aria-proptypes` which checks ARIA state and property values ([#6978](https://github.com/sveltejs/svelte/pull/6978))
* Add a11y warning `a11y-no-abstract-role` which checks ARIA roles must be non-abstract ARIA role ([#6241](https://github.com/sveltejs/svelte/pull/6241))
* Add a11y warning `a11y-no-interactive-element-to-noninteractive-role` which checks for noninteractive roles used on interactive elements ([#5955](https://github.com/sveltejs/svelte/pull/5955))
* Remove of empty stylesheets created from transitions ([#4801](https://github.com/sveltejs/svelte/issues/4801), [#7164](https://github.com/sveltejs/svelte/issues/7164))
* Add `svelte/elements` for HTML/Svelte typings ([#7649](https://github.com/sveltejs/svelte/pull/7649))
## 3.54.0
* Pass `options.direction` argument to custom transition functions ([#3918](https://github.com/sveltejs/svelte/issues/3918))
* Support fallback a11y WAI-ARIA roles ([#8044](https://github.com/sveltejs/svelte/issues/8044))
* Prevent running init binding unnecessarily ([#5689](https://github.com/sveltejs/svelte/issues/5689), [#6298](https://github.com/sveltejs/svelte/issues/6298))
* Allow updating variables from `@const` declared function ([#7843](https://github.com/sveltejs/svelte/issues/7843))
* Do not emit `a11y-no-noninteractive-tabindex` warning if element has a `tabpanel` ([#8025](https://github.com/sveltejs/svelte/pull/8025))
* Fix escaping SSR'd values in `style:` directive ([#8085](https://github.com/sveltejs/svelte/issues/8085))
## 3.53.1
* Fix exception in `rel=` attribute check with dynamic values ([#7994](https://github.com/sveltejs/svelte/issues/7994))
* Do not emit deprecation warnings for `css` compiler options for now ([#8009](https://github.com/sveltejs/svelte/issues/8009))
* Make compiler run in browser again ([#8010](https://github.com/sveltejs/svelte/issues/8010))
* Upgrade `tslib` ([#8013](https://github.com/sveltejs/svelte/issues/8013))
## 3.53.0
* Check whether `parentNode` exists before removing child ([#6037](https://github.com/sveltejs/svelte/issues/6037))
* Upgrade various dependencies, notably `css-tree` to `2.2.1` ([#7572](https://github.com/sveltejs/svelte/pull/7572), [#7982](https://github.com/sveltejs/svelte/pull/7982))
* Extend `css` compiler option with `'external' | 'injected' | 'none'` settings and deprecate old `true | false` values ([#7914](https://github.com/sveltejs/svelte/pull/7914))
## 3.52.0
* Throw compile-time error when attempting to update `const` variable ([#4895](https://github.com/sveltejs/svelte/issues/4895))
* Warn when using `<a target="_blank">` without `rel="noreferrer"` ([#6188](https://github.com/sveltejs/svelte/issues/6188))
* Support `style:foo|important` modifier ([#7365](https://github.com/sveltejs/svelte/issues/7365))
* Fix hydration regression with `{@html}` and components in `<svelte:head>` ([#7941](https://github.com/sveltejs/svelte/pull/7941))
## 3.51.0
* Add a11y warnings:
* `a11y-click-events-have-key-events`: check if click event is accompanied by key events ([#5073](https://github.com/sveltejs/svelte/pull/5073))
* `a11y-no-noninteractive-tabindex`: check for tabindex on non-interactive elements ([#6693](https://github.com/sveltejs/svelte/pull/6693))
* Warn when two-way binding to `{...rest}` object in `{#each}` block ([#6860](https://github.com/sveltejs/svelte/issues/6860))
* Support `--style-props` on `<svelte:component>` ([#7461](https://github.com/sveltejs/svelte/issues/7461))
* Supports nullish values for component event handlers ([#7568](https://github.com/sveltejs/svelte/issues/7568))
* Supports SVG elements with `<svelte:element>`([#7613](https://github.com/sveltejs/svelte/issues/7613))
* Treat `inert` as boolean attribute ([#7785](https://github.com/sveltejs/svelte/pull/7785))
* Support `--style-props` for SVG components ([#7808](https://github.com/sveltejs/svelte/issues/7808))
* Fix false positive dev warnings about unset props when they are bound ([#4457](https://github.com/sveltejs/svelte/issues/4457))
* Fix hydration with `{@html}` and components in `<svelte:head>` ([#4533](https://github.com/sveltejs/svelte/issues/4533), [#6463](https://github.com/sveltejs/svelte/issues/6463), [#7444](https://github.com/sveltejs/svelte/issues/7444))
* Support scoped style for `<svelte:element>` ([#7443](https://github.com/sveltejs/svelte/issues/7443))
* Improve error message for invalid value for `<svelte:component this={...}>` ([#7550](https://github.com/sveltejs/svelte/issues/7550))
* Improve error message when using logic blocks or tags at invalid location ([#7552](https://github.com/sveltejs/svelte/issues/7552))
* Warn instead of throwing error if `<svelte:element>` is a void tag ([#7566](https://github.com/sveltejs/svelte/issues/7566))
* Supports custom elements in `<svelte:element>` ([#7733](https://github.com/sveltejs/svelte/issues/7733))
* Fix calling component unmount if a component is mounted and then immediately unmounted ([#7817](https://github.com/sveltejs/svelte/issues/7817))
* Do not generate `a11y-role-has-required-aria-props` warning when elements match their semantic role ([#7837](https://github.com/sveltejs/svelte/issues/7837))
* Improve performance of custom element data setting in `<svelte:element>` ([#7869](https://github.com/sveltejs/svelte/pull/7869))
## 3.50.1
* Add all global objects and functions as known globals ([#3805](https://github.com/sveltejs/svelte/issues/3805), [#7223](https://github.com/sveltejs/svelte/issues/7223))
* Fix regression with style manager ([#7828](https://github.com/sveltejs/svelte/issues/7828))
## 3.50.0
* Add a11y warnings:
* `a11y-incorrect-aria-attribute-type`: check ARIA state and property values ([#6978](https://github.com/sveltejs/svelte/pull/6978))
* `a11y-no-abstract-role`: check that ARIA roles are non-abstract ([#6241](https://github.com/sveltejs/svelte/pull/6241))
* `a11y-no-interactive-element-to-noninteractive-role`: check for non-interactive roles used on interactive elements ([#5955](https://github.com/sveltejs/svelte/pull/5955))
* `a11y-role-has-required-aria-props`: check that elements with `role` attribute have all required attributes for that role ([#5852](https://github.com/sveltejs/svelte/pull/5852))
* Add `ComponentEvents` convenience type ([#7702](https://github.com/sveltejs/svelte/pull/7702))
* Add `SveltePreprocessor` utility type ([#7742](https://github.com/sveltejs/svelte/pull/7742))
* Enhance action typings ([#7805](https://github.com/sveltejs/svelte/pull/7805))
* Remove empty stylesheets created from transitions ([#4801](https://github.com/sveltejs/svelte/issues/4801), [#7164](https://github.com/sveltejs/svelte/issues/7164))
* Make `a11y-label-has-associated-control` warning check all descendants for input control ([#5528](https://github.com/sveltejs/svelte/issues/5528))
* Only show lowercase component name warnings for non-HTML/SVG elements ([#5712](https://github.com/sveltejs/svelte/issues/5712))
* Disallow invalid CSS selectors starting with a combinator ([#7643](https://github.com/sveltejs/svelte/issues/7643))
* Use `Node.parentNode` instead of `Node.parentElement` for legacy browser support ([#7723](https://github.com/sveltejs/svelte/issues/7723))
* Handle arrow function on `<slot>` inside `<svelte:fragment>` ([#7485](https://github.com/sveltejs/svelte/issues/7485))
* Improve parsing speed when encountering large blocks of whitespace ([#7675](https://github.com/sveltejs/svelte/issues/7675))
* Fix `class:` directive updates in aborted/restarted transitions ([#7764](https://github.com/sveltejs/svelte/issues/7764))
## 3.49.0
@ -1156,7 +1227,7 @@ Also:
## 2.12.0
* Initialise actions on mount rather than hydrate ([#1653](https://github.com/sveltejs/svelte/pull/1653))
* Allow non-existent components to be destroyed ([#1677](https://github.com/sveltejs/svelte/pull/1677))
* Allow nonexistent components to be destroyed ([#1677](https://github.com/sveltejs/svelte/pull/1677))
* Pass AMD ID from CLI correctly ([#1672](https://github.com/sveltejs/svelte/pull/1672))
* Minor AST tweaks ([#1673](https://github.com/sveltejs/svelte/pull/1673), [#1674](https://github.com/sveltejs/svelte/pull/1674))
* Reduce code duplication in component initialisation ([#1670](https://github.com/sveltejs/svelte/pull/1670))

@ -11,9 +11,9 @@ The [Open Source Guides](https://opensource.guide/) website has a collection of
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).
- Simply start using Svelte. Go through the [Getting Started](https://svelte.dev/docs#getting-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). A good starting point would be issues tagged [good first issue](https://github.com/sveltejs/svelte/issues?q=is%3Aissue+is%3Aopen+label%3A%22good+first+issue%22). 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).
- If you find an issue you would like to fix, [open a pull request](#pull-requests).
- 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/feature%20request) by others in the community and consider opening a pull request if you see something you want to work on.
@ -24,65 +24,63 @@ Contributions are very welcome. If you think you need help planning your contrib
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
## Our process
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).
### RFCs
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'd like to propose an implementation for a large new feature or change then please [create an RFC](https://github.com/sveltejs/rfcs) to discuss it up front.
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)
### Roadmap
## Reporting new issues
When deciding where to contribute, you may wish to take a look at [our roadmap](https://svelte.dev/roadmap). The Svelte team generally works on a single major effort at a time. This has a couple benefits for us as maintainers. First, it allows us to focus and make noticeable progress in an area being proactive rather than reactive. Secondly, it allows us to handle related issues and PRs together. By batching issues and PRs together were able to ensure implementations and fixes holistically address the set of problems and use cases encountered by our users.
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.
### Maintainer meetings
- **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.
The maintainers meet on the final Saturday of each month. While these meetings are not open publicly, we will report back by leaving a comment on each issue discussed. We will generally discuss items aligning with our roadmap, but major PRs needing discussion amongst the maintainers can be added to the agenda for the monthly maintainers meeting. However, we typically are only able to get to a couple of items that are not aligned with our current priority.
## RFCs
### Prioritization
If you'd like to propose an implementation for a large new feature or change then please [create an RFC](https://github.com/sveltejs/rfcs) to discuss it up front.
We do our best to review PRs and RFCs as they are sent, but it is difficult to keep up. We welcome help in reviewing PRs, RFC, and issues. If an item aligns with the current priority on our [roadmap](https://svelte.dev/roadmap), it is more likely to be reviewed quickly. PRs to the most important and active ones repositories get reviewed more quickly while PRs to smaller inactive repos may sit for a bit before we periodically come by and review the pending PRs in a batch.
## Installation
## Bugs
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`.
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).
## Pull requests
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.
### Your first pull request
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)
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.
### Reporting new issues
Working on your first Pull Request? You can learn how from this free video series:
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.
[**How to Contribute to an Open Source Project on GitHub**](https://egghead.io/courses/how-to-contribute-to-an-open-source-project-on-github)
## Pull requests
### 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 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.yml).
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.
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.
### Installation
Please make sure the following is done when submitting a pull request:
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`.
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`).
### Creating a branch
All pull requests should be opened against the `master` branch.
Fork [the repository](https://github.com/sveltejs/svelte) and create your branch from `master`. If you've never sent a GitHub pull request before, you can learn how from [this free video series](https://egghead.io/courses/how-to-contribute-to-an-open-source-project-on-github).
#### Test plan
### Testing
A good test plan has the exact commands you ran and their output, provides screenshots or videos if the pull request changes UI.
@ -110,6 +108,25 @@ Test samples are kept in `/test/xxx/samples` folder.
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`)
### 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.
### Sending your pull request
Please make sure the following is done when submitting a pull request:
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. Make sure the PR does only one thing, otherwise please split it.
#### Breaking changes
When adding a new breaking change, follow this template in your pull request:
@ -123,19 +140,10 @@ When adding a new breaking change, follow this template in your pull request:
- **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).
## Questions
Feel free to ask in [#contributing](https://discord.com/channels/457912077277855764/750401468569354431) on [Discord](https://svelte.dev/chat) if you have questions about our process, how to proceed, etc.

@ -20,6 +20,11 @@ Svelte is an MIT-licensed open source project with its ongoing development made
Funds donated via Open Collective will be used for compensating expenses related to Svelte's development such as hosting costs. If sufficient donations are received, funds may also be used to support Svelte's development more directly.
## Roadmap
You may view [our roadmap](https://svelte.dev/roadmap) if you'd like to see what we're currently working on.
## Development
Pull requests are encouraged and always welcome. [Pick an issue](https://github.com/sveltejs/svelte/issues?q=is%3Aissue+is%3Aopen+sort%3Aupdated-desc) and help us out!

1581
elements/index.d.ts vendored

File diff suppressed because it is too large Load Diff

@ -0,0 +1,3 @@
{
"types": "./index.d.ts"
}

@ -16,7 +16,7 @@ function modify(path, modifyFn) {
modify(
'types/runtime/index.d.ts',
content => content.replace('SvelteComponentTyped', 'SvelteComponentTyped, ComponentType, ComponentConstructorOptions, ComponentProps')
content => content.replace('SvelteComponentTyped', 'SvelteComponentTyped, ComponentType, ComponentConstructorOptions, ComponentProps, ComponentEvents')
);
modify(
'types/compiler/index.d.ts',

1560
package-lock.json generated

File diff suppressed because it is too large Load Diff

@ -1,6 +1,6 @@
{
"name": "svelte",
"version": "3.49.0",
"version": "3.54.0",
"description": "Cybernetically enhanced web apps",
"module": "index.mjs",
"main": "index",
@ -17,6 +17,7 @@
"easing",
"motion",
"action",
"elements",
"README.md"
],
"exports": {
@ -75,6 +76,9 @@
"import": "./transition/index.mjs",
"require": "./transition/index.js"
},
"./elements": {
"types": "./elements/index.d.ts"
},
"./ssr": {
"types": "./types/runtime/index.d.ts",
"import": "./ssr.mjs",
@ -86,17 +90,17 @@
},
"types": "types/runtime/index.d.ts",
"scripts": {
"test": "mocha --exit",
"test:unit": "mocha --require sucrase/register --recursive src/**/__test__.ts --exit",
"quicktest": "mocha",
"test": "npm run test:unit && npm run test:integration",
"test:integration": "mocha --exit",
"test:unit": "mocha --config .mocharc.unit.js --exit",
"quicktest": "mocha --exit",
"build": "rollup -c && npm run tsd",
"prepare": "npm run build",
"prepare": "node scripts/skip_in_ci.js npm run build",
"dev": "rollup -cw",
"pretest": "npm run build",
"posttest": "agadoo internal/index.mjs",
"prepublishOnly": "node check_publish_env.js && npm run lint && npm test",
"prepublishOnly": "node check_publish_env.js && npm run lint && npm run build && npm test",
"tsd": "node ./generate-type-definitions.js",
"lint": "eslint \"{src,test}/**/*.{ts,js}\""
"lint": "eslint \"{src,test}/**/*.{ts,js}\" --cache"
},
"repository": {
"type": "git",
@ -118,7 +122,7 @@
"@ampproject/remapping": "^0.3.0",
"@rollup/plugin-commonjs": "^11.0.0",
"@rollup/plugin-json": "^4.0.1",
"@rollup/plugin-node-resolve": "^6.0.0",
"@rollup/plugin-node-resolve": "^11.2.1",
"@rollup/plugin-replace": "^2.3.0",
"@rollup/plugin-sucrase": "^3.1.0",
"@rollup/plugin-typescript": "^2.0.1",
@ -129,30 +133,31 @@
"@types/node": "^8.10.53",
"@typescript-eslint/eslint-plugin": "^5.22.0",
"@typescript-eslint/parser": "^5.22.0",
"acorn": "^8.4.1",
"agadoo": "^1.1.0",
"aria-query": "^5.0.0",
"axobject-query": "^3.0.1",
"acorn": "^8.8.1",
"agadoo": "^2.0.0",
"aria-query": "^5.1.1",
"axobject-query": "^3.1.1",
"code-red": "^0.2.5",
"css-tree": "^1.1.2",
"eslint": "^8.0.0",
"css-tree": "^2.2.1",
"eslint": "^8.26.0",
"eslint-plugin-import": "^2.26.0",
"eslint-plugin-svelte3": "^4.0.0",
"estree-walker": "^3.0.0",
"estree-walker": "^3.0.1",
"is-reference": "^3.0.0",
"jsdom": "^15.2.1",
"kleur": "^3.0.3",
"kleur": "^4.1.5",
"locate-character": "^2.0.5",
"magic-string": "^0.25.3",
"mocha": "^7.0.0",
"periscopic": "^3.0.4",
"puppeteer": "^2.0.0",
"rollup": "^1.27.14",
"source-map": "^0.7.3",
"source-map-support": "^0.5.13",
"source-map": "^0.7.4",
"source-map-support": "^0.5.21",
"sourcemap-codec": "^1.4.8",
"tiny-glob": "^0.2.6",
"tslib": "^2.0.3",
"typescript": "^3.7.5"
"tiny-glob": "^0.2.9",
"tslib": "^2.4.1",
"typescript": "^3.7.5",
"util": "^0.12.5"
}
}

@ -108,8 +108,18 @@ export default [
input: 'src/compiler/index.ts',
plugins: [
replace({
__VERSION__: pkg.version
__VERSION__: pkg.version,
'process.env.NODE_DEBUG': false // appears inside the util package
}),
{
resolveId(id) {
// util is a built-in module in Node.js, but we want a self-contained compiler bundle
// that also works in the browser, so we load its polyfill instead
if (id === 'util') {
return require.resolve('./node_modules/util'); // just 'utils' would resolve this to the built-in module
}
}
},
resolve(),
commonjs({
include: ['node_modules/**']

@ -0,0 +1,91 @@
/** ----------------------------------------------------------------------
This script gets a list of global objects/functions of browser.
This process is simple for now, so it is handled without AST parser.
Please run `node scripts/globals-extractor.mjs` at the project root.
see: https://github.com/microsoft/TypeScript/tree/main/lib
---------------------------------------------------------------------- */
import http from 'https';
import fs from 'fs';
const GLOBAL_TS_PATH = './src/compiler/utils/globals.ts';
// MEMO: add additional objects/functions which existed in `src/compiler/utils/names.ts`
// before this script was introduced but could not be retrieved by this process.
const SPECIALS = ['global', 'globalThis', 'InternalError', 'process', 'undefined'];
const get_url = (name) => `https://raw.githubusercontent.com/microsoft/TypeScript/main/lib/lib.${name}.d.ts`;
const extract_name = (split) => split.match(/^[a-zA-Z0-9_$]+/)[0];
const extract_functions_and_references = (name, data) => {
const functions = [];
const references = [];
data.split('\n').forEach(line => {
const trimmed = line.trim();
const split = trimmed.replace(/[\s+]/, ' ').split(' ');
if (split[0] === 'declare' && split[1] !== 'type') {
functions.push(extract_name(split[2]));
} else if (trimmed.startsWith('/// <reference')) {
const matched = trimmed.match(/ lib="(.+)"/);
const reference = matched && matched[1];
if (reference) references.push(reference);
}
});
return { functions, references };
};
const do_get = (url) => new Promise((resolve, reject) => {
http.get(url, (res) => {
let body = '';
res.setEncoding('utf8');
res.on('data', (chunk) => body += chunk);
res.on('end', () => resolve(body));
}).on('error', (e) => {
console.error(e.message);
reject(e);
});
});
const fetched_names = new Set();
const get_functions = async (name) => {
const res = [];
if (fetched_names.has(name)) return res;
fetched_names.add(name);
const body = await do_get(get_url(name));
const { functions, references } = extract_functions_and_references(name, body);
res.push(...functions);
const chile_functions = await Promise.all(references.map(get_functions));
chile_functions.forEach(i => res.push(...i));
return res;
};
const build_output = (functions) => {
const sorted = Array.from(new Set(functions.sort()));
return `\
/** ----------------------------------------------------------------------
This file is automatically generated by \`scripts/globals-extractor.mjs\`.
Generated At: ${new Date().toISOString()}
---------------------------------------------------------------------- */
export default new Set([
${sorted.map((i) => `\t'${i}'`).join(',\n')}
]);
`;
};
const get_exists_globals = () => {
const regexp = /^\s*["'](.+)["'],?\s*$/;
return fs.readFileSync(GLOBAL_TS_PATH, 'utf8')
.split('\n')
.filter(line => line.match(regexp))
.map(line => line.match(regexp)[1]);
};
(async () => {
const globals = get_exists_globals();
const new_globals = await get_functions('es2021.full');
globals.forEach((g) => new_globals.push(g));
SPECIALS.forEach((g) => new_globals.push(g));
fs.writeFileSync(GLOBAL_TS_PATH, build_output(new_globals));
})();

@ -0,0 +1,7 @@
if (process.env.SKIP_PREPARE) {
console.log('Skipped "prepare" script');
} else {
const { execSync } = require("child_process");
const command = process.argv.slice(2).join(" ");
execSync(command, { stdio: "inherit" });
}

@ -63,4 +63,4 @@ 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 [Vercel](https://vercel.com) 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) (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!
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](https://svelte.dev/chat), or via [@sveltejs](https://twitter.com/sveltejs) on Twitter!

@ -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](chat).
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://svelte.dev/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](chat).
Each of these items is described in more depth below. If you get stuck, ask for help in our friendly [Discord chatroom](https://svelte.dev/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](chat) 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](https://svelte.dev/chat) or raise an issue on the [tracker](https://github.com/sveltejs/svelte/issues).

@ -14,7 +14,7 @@ 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](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.
Unless you hang out in our [Discord server](https://svelte.dev/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).

@ -61,7 +61,7 @@ We're going to use the [Svelte + Vite](https://github.com/vitejs/vite/tree/main/
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
npm init vite my-svelte-project -- --template svelte
npm create vite@latest my-svelte-project -- --template svelte
cd my-svelte-project
npm install
```
@ -78,7 +78,7 @@ npm run dev
Running the `dev` script starts a program called [Vite](https://vitejs.dev/). Vite's job is to take your application's source files, 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:3000. This is your application running on a local *web server* (hence 'localhost') on port 3000.
Speaking of which, open a browser and navigate to http://localhost:5173. This is your application running on a local *web server* (hence 'localhost') on port 5173.
Try changing `src/App.svelte` and saving it. The application will update with your changes.

@ -12,7 +12,7 @@ Welcome to the first edition of our "What's new in Svelte" series! We'll try to
2. `_` is now supported as a "numerical separator", similar to a `.` or `,` ([Example](https://svelte.dev/repl/844c39e91d1248649fe54af839fab570?version=3.26.0), **3.26.0**)
3. `import.meta` now works in template expressions ([Example](https://svelte.dev/repl/9630de41957a4c80a4fce264360a6bc7?version=3.26.0), **3.26.0**)
4. CSS Selectors with `~` and `+` combinators are now supported ([Example](https://svelte.dev/repl/91ad9257d2d1430185a504a18cc60172?version=3.29.0), **3.27.0**, with a compiler fix in **3.29.0**)
5. The `{#key}` block is now available to key arbitrary content on an expression. Whever the expression changes, the contents inside the `{#key}` block will be destroyed and recreated. For an in-depth explanation and to find out how it's implemented, check out the [new blog post](https://lihautan.com/contributing-to-svelte-implement-key-block/) of Svelte Team member Tan Li Hau. ([More info](https://github.com/sveltejs/svelte/issues/1469), **3.29.0**)
5. The `{#key}` block is now available to key arbitrary content on an expression. Whenever the expression changes, the contents inside the `{#key}` block will be destroyed and recreated. For an in-depth explanation and to find out how it's implemented, check out the [new blog post](https://lihautan.com/contributing-to-svelte-implement-key-block/) of Svelte Team member Tan Li Hau. ([More info](https://github.com/sveltejs/svelte/issues/1469), **3.29.0**)
6. Slots can now be forwarded through child components! This used to only be possible by adding extra wrapper `<div>`s ([More info](https://github.com/sveltejs/svelte/issues/2079), **3.29.0**)
7. When using TypeScript, you can now type the `createEventDispatcher` method:
```html
@ -53,7 +53,7 @@ For all the features and bugfixes see the CHANGELOG for [Svelte](https://github.
## Svelte Showcase
- [This CustomMenu example](https://svelte.dev/repl/3a33725c3adb4f57b46b597f9dade0c1?version=3.25.0) demos how to replace the OS right-click menu
- [Github Tetris](https://svelte.dev/repl/cc1eaa7c66964fedb5e70e3ecbbaa0e1?version=3.25.1) lets you play a Tetris-like game in a git commit history
- [GitHub Tetris](https://svelte.dev/repl/cc1eaa7c66964fedb5e70e3ecbbaa0e1?version=3.25.1) lets you play a Tetris-like game in a git commit history
- [Who are my representatives?](https://whoaremyrepresentatives.us/) is a website built with Svelte to help US residents get more info on their congressional representatives
- [Pick Palette](https://github.com/bluwy/pick-palette) is a color palette manager made with Svelte!

@ -53,7 +53,7 @@ For all the features and bugfixes see the CHANGELOGs for [Svelte](https://github
**Components, Libraries & Tools**
- [svelte-crossword](https://russellgoldenberg.github.io/svelte-crossword/) is a customizable crossword puzzle component for Svelte.
- [svelte-cloudinary](https://github.com/cupcakearmy/svelte-cloudinary) makes it easy to integrate Cloudinary with Svelte (including Typescript and SSR support)
- [svelte-cloudinary](https://github.com/cupcakearmy/svelte-cloudinary) makes it easy to integrate Cloudinary with Svelte (including TypeScript and SSR support)
- [Svelte Nova](https://extensions.panic.com/extensions/sb.lao/sb.lao.svelte-nova/) extends the new Nova editor to support Svelte
- [saos](https://github.com/shiryel/saos) is a small svelte component to animate your elements on scroll.
- [Svelte-nStore](https://github.com/lacikawiz/svelte-nStore) is a general purpose store replacement that fulfills the Svelte store contract and adds getter and calculation features.

@ -66,11 +66,11 @@ New changes to the Svelte Society website include [a new cheat sheet](https://sv
- [eleventy-plugin-embed-svelte](https://github.com/shalomscott/eleventy-plugin-embed-svelte) makes it easy to embed Svelte components into an 11ty site.
- [svelte-tailwind-extension-boilerplate](https://github.com/kyrelldixon/svelte-tailwind-extension-boilerplate) is a good foundation for a Chrome extension using either JavaScript or TypeScript, Svelte for the frontend, Tailwind CSS for styling, Jest for testing, and Rollup as the build system.
- [snowpack-ui](https://github.com/rajasegar/snowpack-ui) lets you run & manage Snowpack projects from the browser instead of the terminal
- [Svelte for Appwrite](https://dev.to/torstendittmann/svelte-for-appwrite-4fkg) explains how to integrate with Appwrite, a self-hosted Firebase alternative [Github Repo](https://github.com/appwrite/sdk-for-svelte)
- [Svelte for Appwrite](https://dev.to/torstendittmann/svelte-for-appwrite-4fkg) explains how to integrate with Appwrite, a self-hosted Firebase alternative [GitHub Repo](https://github.com/appwrite/sdk-for-svelte)
- [here-maps-svelte](https://github.com/peopledrivemecrazy/here-maps-svelte) makes it easy to include HERE maps in a Svelte app
- [p5-svelte](https://github.com/tonyketcham/p5-svelte) is an absolutely dead simple way of tossing the creative coding/sketching tool, p5, into a project
- [svelte-windicss-preprocess](https://github.com/voorjaar/svelte-windicss-preprocess) is a Svelte preprocessor to compile tailwindcss at build time based on windicss compiler
- [MitzaCoder/svelte-boilerplate](https://github.com/MitzaCoder/svelte-boilerplate) features configurations for Typescript, TailwindCSS, IE11 compatibility (with Babel) and lazy loaded modules.
- [MitzaCoder/svelte-boilerplate](https://github.com/MitzaCoder/svelte-boilerplate) features configurations for TypeScript, TailwindCSS, IE11 compatibility (with Babel) and lazy loaded modules.
**Want to share your Svelte Component with the world?** Head over to the [Components](https://sveltesociety.dev/components) page on the Svelte Society site. You can contribute by making [a PR to this file](https://github.com/svelte-society/sveltesociety.dev/blob/master/src/pages/components/components.json).

@ -17,7 +17,7 @@ Let's dive into the news 🐬
* Destructured defaults are now allowed to refer to other variables (**3.33.0**, [example](https://svelte.dev/repl/0ee7227e1b45465b9b47d7a5ae2d1252?version=3.33.0))
* Custom elements will now call `onMount` functions when connecting and clean up when disconnecting (**3.33.0**, checkout [this PR](https://github.com/sveltejs/svelte/pull/4522) for an interesting conversation on how folks are using Svelte with Web Components)
* A `cssHash` option has been added to the compiler options to control the classname used for CSS scoping (**3.34.0**, [docs](https://svelte.dev/docs#compile-time-svelte-compile))
* Continued improvement to Typescript definitions
* Continued improvement to TypeScript definitions
For a complete list of changes, including bug fixes and links to PRs, check out [the CHANGELOG](https://github.com/sveltejs/svelte/blob/master/CHANGELOG.md)
@ -96,7 +96,7 @@ Haven't tried the language-tools yet? Check out [Svelte Extension for VSCode](ht
- [Using Fauna's streaming feature to build a chat with Svelte](https://dev.to/fauna/using-fauna-s-streaming-feature-to-build-a-chat-with-svelte-1gkd) demonstrates how to setup and configure Fauna to build a real-time chat interface with Svelte
- [Using TakeShape with Sapper](https://www.takeshape.io/articles/using-takeshape-with-sapper/) demonstrates how to connect the TakeShape CMS with Sapper
- [YastPack](https://github.com/rodabt/yastpack) is Yet Another Snowpack-Svelte-TailwindCss-Routify Template Pack
- [S2T2](https://ralphbliu.medium.com/s2t2-snowpack-svelte-tailwindcss-typescript-8928caa5af6c) is a Snowpack + Svelte + TailwindCSS + Typescript template
- [S2T2](https://ralphbliu.medium.com/s2t2-snowpack-svelte-tailwindcss-typescript-8928caa5af6c) is a Snowpack + Svelte + TailwindCSS + TypeScript template
- [tonyketcham/sapper-tailwind2-template](https://github.com/tonyketcham/sapper-tailwind2-template) is a Sapper Template w/ Tailwind 2.0, TypeScript, ESLint, and Prettier
## See you next month!

@ -49,7 +49,7 @@ As the northern hemisphere heats up, Svelte has stayed cool with lots of perform
**Libraries, Tools & Components**
- [svelte-pipeline](https://github.com/novacbn/svelte-pipeline) provides custom Javascript contexts and the Svelte Compiler as Svelte Stores, for REPLs, Editors, etc.
- [svelte-pipeline](https://github.com/novacbn/svelte-pipeline) provides custom JavaScript contexts and the Svelte Compiler as Svelte Stores, for REPLs, Editors, etc.
- [Sveltotron](https://github.com/Salemmous/sveltotron) is an Electron-based app made to inspect your Svelte app
- [svelte-qr-reader-writer](https://github.com/pleasemarkdarkly/svelte-qr-reader-writer) is a Svelte component that helps read and write data from QR codes
- [svelte-stack-router](https://www.npmjs.com/package/svelte-stack-router) Aims to make Svelte apps feel more native by routing with Stacks

@ -52,7 +52,7 @@ To see all updates to SvelteKit, check out the [SvelteKit changelog](https://git
- [How to Create a Blog with SvelteKit and Strapi](https://strapi.io/blog/how-to-create-a-blog-with-svelte-kit-strapi) is a step-by-step tutorial by Aarnav Pai from Strapi
- [Sveltekit Markdown Blog](https://www.youtube.com/watch?v=sKKgT0SEioI&list=PLm_Qt4aKpfKgonq1zwaCS6kOD-nbOKx7V) is a YouTube tutorial series by WebJeda.
- [Using Custom Elements in Svelte](https://css-tricks.com/using-custom-elements-in-svelte/) is a deep dive into custom elements by Geoff Rich.
- [learn / graphql / svelte](https://hasura.io/learn/graphql/svelte-apollo/introduction/) is a free 2-hour GraphQL course course from Hasura.
- [learn / graphql / svelte](https://hasura.io/learn/graphql/svelte-apollo/introduction/) is a free 2-hour GraphQL course from Hasura.
- [How to add Magic Link to a SvelteKit application](https://magic.link/posts/magic-svelte) is a guide to the popular password-less login pattern.
**Libraries, Tools & Components**

@ -44,7 +44,7 @@ To see all updates to SvelteKit, check out the [SvelteKit changelog](https://git
- [macos-web](https://github.com/PuruVJ/macos-web) by @puruvjdev has been rebuilt with Svelte from the ground up. Check out all the details in this [Twitter thread](https://twitter.com/puruvjdev/status/1426267327687847939)
- [Brave Search](https://search.brave.com/) is using Svelte
- [exatorrent](https://github.com/varbhat/exatorrent) is a self-hostable, easy-to-use, lightweight and feature-rich torrent client written in Go and Svelte
- [json2TsTypes](https://github.com/jatinhemnani01/json2TsTypes) is a simple tool which will convert your JSON to Typescript Types/Interfaces
- [json2TsTypes](https://github.com/jatinhemnani01/json2TsTypes) is a simple tool which will convert your JSON to TypeScript Types/Interfaces
- [Histogram.dev](https://histogram.dev/) generates histograms for each feature in a CSV
- [cybernetic.dev](https://cybernetic.dev/) is a collection of data-centric UI experiments made while learning Svelte
- [LunaNotes](https://chrome.google.com/webstore/detail/lunanotes-youtube-video-n/oehoffnnkgcdacmbkhmlbjedinpampak?hl=en) is a Chrome extension to help with taking YouTube video notes

@ -52,12 +52,12 @@ To see all updates to SvelteKit, check out the [SvelteKit changelog](https://git
- [hirehive](https://www.hirehive.com/) is a candidate and job tracking site
- [Microsocial](https://microsocial.xyz/) is an experimental Peer-to-Peer Social Platform
- [Dylan Ipsum](https://www.dylanlyrics.app/) is a random text generator to replace lorem ipsum with Bob Dylan lyrics
- [Chip8 Svelte](https://github.com/mikeyhogarth/chip8-svelte) is a CHIP-8 emulator frontend, built on top of CHIP8 Typescript
- [Chip8 Svelte](https://github.com/mikeyhogarth/chip8-svelte) is a CHIP-8 emulator frontend, built on top of CHIP8 TypeScript
**Looking for a Svelte project to work on? Interested in helping make Svelte's presence on the web better?** Check out [the list of open issues](https://github.com/svelte-society/sveltesociety-2021/issues) if you'd like to contribute to the Svelte Society rewrite in SvelteKit.
**Podcasts Featuring Svelte**
- [Syntax Podast: From React to SvelteKit](https://podcasts.apple.com/us/podcast/from-react-to-sveltekit/id1253186678?i=1000536276106) Scott talks with Wes about moving Level Up Tutorials from React to SvelteKit — why he did it, how, benefits, things to watch out for, and more!
- [Syntax Podcast: From React to SvelteKit](https://podcasts.apple.com/us/podcast/from-react-to-sveltekit/id1253186678?i=1000536276106) Scott talks with Wes about moving Level Up Tutorials from React to SvelteKit — why he did it, how, benefits, things to watch out for, and more!
- [Web Rush Podcast: Svelte Tools and Svelte Society](https://www.webrush.io/episodes/episode-150-svelte-tools-and-svelte-society) Kevin Åberg Kultalahti talks about what Svelte Society is, what he's excited about with Svelte, how important documentation is to any product, and much _much_ more
- [Svelte: The Compiled Future of Front End](https://www.arahansen.com/the-compiled-future-of-front-end/) details the history of component-based frontends and how a compiler changes everything
- [Svelte Radio: Contributing to Svelte with Martin 'Grygrflzr' Krisnanto Putra](https://share.transistor.fm/s/10aa305c) Grygrflzr shares his journey to becoming a maintainer and his views on React, Vite and a host of other things
@ -74,7 +74,7 @@ To see all updates to SvelteKit, check out the [SvelteKit changelog](https://git
**Libraries, Tools & Components**
- [sveltekit-netlify-cms](https://github.com/buhrmi/sveltekit-netlify-cms) is a SvelteKit skeleton app configured for use with Netlify CMS
- [SvelteFireTS](https://github.com/jacobbowdoin/sveltefirets) is a SvelteKit + Typescript + Firebase library inspired by Fireship.io
- [SvelteFireTS](https://github.com/jacobbowdoin/sveltefirets) is a SvelteKit + TypeScript + Firebase library inspired by Fireship.io
- [stores-x](https://github.com/Anyass3/stores-x) lets you use Svelte stores just like vueX
- [sveltekit-snippets](https://github.com/stordahl/sveltekit-snippets) is a VSCode extension that provides snippets for common patterns in SvelteKit & Vanilla Svelte
- [svelte-xactor](https://github.com/wobsoriano/svelte-xactor) is a middleware that allows you to easily convert your xactor machines into a global store that implements the store contract

@ -41,7 +41,7 @@ To see all updates to Svelte and SvelteKit, check out the [Svelte](https://githu
- [DottoBit](https://dottobit.com/) is a multi-color 16-bit drawing program with URL sharing built-in
- [Former Fast Document for Print](https://github.com/zummon/former) is an invoice generator with beautiful designs, abilities for international languages and auto calculation
- [Helvetikon](https://github.com/noahsalvi/helvetikon) is a community maintained dictionary for the Swiss German language
- [Palitra App](https://palitra.app/) is a search-based color pallete generator
- [Palitra App](https://palitra.app/) is a search-based color palette generator
**Podcasts Featuring Svelte**
- [Svelte Radio](https://www.svelteradio.com/episodes/svelte-summit-is-coming-up-and-svelte-is-growing) dives into the tech behind the recently released Svelte Summit website and a bunch of other fun stuff!
@ -72,7 +72,7 @@ To see all updates to Svelte and SvelteKit, check out the [Svelte](https://githu
- [date-picker-svelte](https://github.com/probablykasper/date-picker-svelte) is a date and time picker for Svelte
- [TwelveUI](https://twelveui.readme.io/reference/what-is-twelveui) is a Svelte component library with accessibility built-in
- [svelte-outclick](https://github.com/babakfp/svelte-outclick/) is a Svelte component that allows you to listen for clicks outside of an element, by providing you an outclick event
- [svelte-zero-api](https://github.com/ymzuiku/svelte-zero-api) lets you use SvelteKit APIs like client functions - with support for Typescript
- [svelte-zero-api](https://github.com/ymzuiku/svelte-zero-api) lets you use SvelteKit APIs like client functions - with support for TypeScript
- [svelte-recaptcha-v2](https://github.com/basaran/svelte-recaptcha-v2) is a Google reCAPTCHA v2 implementation for Svelte SPA, SSR and sveltekit static sites.
- [Svelte Body](https://github.com/ghostdevv/svelte-body) lets you apply styles to the body in routes - designed to work with SvelteKit and Routify.
- [svelte-debug-console](https://github.com/basaran/svelte-debug-console) is a debug.js implementation for Svelte SPA, SSR and sveltekit static sites that lets you see your debug statements in the browser.

@ -69,7 +69,7 @@ _To Read_
- [Building an iOS app with Svelte, Capacitor and Firebase](https://harryherskowitz.com/2022/01/05/tapedrop-app.html) by Harry Herskowitz
- [Mutating Query Params in SvelteKit Without Page Reloads or Navigations](https://dev.to/mohamadharith/mutating-query-params-in-sveltekit-without-page-reloads-or-navigations-2i2b) and [Workaround for Bubbling Custom Events in Svelte](https://dev.to/mohamadharith/workaround-for-bubbling-custom-events-in-svelte-3khk) by Mohamad Harith
- [How to build a full stack serverless application with Svelte and GraphQL](https://dev.to/shadid12/how-to-build-a-full-stack-serverless-application-with-svelte-graphql-and-fauna-5427) by Shadid Haque
- [How to Deploy SvelteKit Apps to Github Pages](https://sveltesaas.com/articles/sveltekit-github-pages-guide/)
- [How to Deploy SvelteKit Apps to GitHub Pages](https://sveltesaas.com/articles/sveltekit-github-pages-guide/)
- [Creating a dApp with SvelteKit](https://anthonyriley.org/2021/12/31/creating-a-dapp-with-sveltekit/) by Anthony Riley
- [Comparing Svelte Reactivity Options](https://opendirective.net/2022/01/06/comparing-svelte-reactivity-options/) by Steve Lee

@ -41,7 +41,7 @@ More on that, and what else is new in Svelte, as we dive in...
**Apps & Sites built with Svelte**
- [Launcher](https://launcher.team/) is an open-source app launcher powered by SvelteKit, Prisma, and Tailwind
- [Paaster](https://paaster.io/) is a secure by default end to end encrypted pastebin built with Svelte, Vite, Typescript, Python, Starlette, rclone & Docker.
- [Paaster](https://paaster.io/) is a secure by default end to end encrypted pastebin built with Svelte, Vite, TypeScript, Python, Starlette, rclone & Docker.
- [Simple AF Video Converter](https://github.com/berlyozzy/Simple-AF-Video-Converter) is an Electron wrapper around ffmpeg.wasm to make converting videos between formats easier
- [Streamchaser](https://github.com/streamchaser/streamchaser) seeks to simplify movie, series and documentary search through a centralized entertainment technology platform
- [Svelte Color Picker](https://github.com/V-Py/svelte-material-color-picker) is a simple color picker made with Svelte
@ -89,7 +89,7 @@ _To Watch_
**Libraries, Tools & Components**
- [SvelTable](https://sveltable.io/) is a feature rich, data table component built with Svelte
- [svelte-cyberComp](https://github.com/Cybersteam00/svelte-cyberComp) is a powerful, lightweight component library written in Svelte and Typescript
- [svelte-cyberComp](https://github.com/Cybersteam00/svelte-cyberComp) is a powerful, lightweight component library written in Svelte and TypeScript
- [Flowbite Svelte](https://github.com/shinokada/flowbite-svelte) is an unofficial Flowbite component library for Svelte
- [Svelte-Tide-Project](https://github.com/jbertovic/svelte-tide-project) is a starter template for Svelte frontend apps with Rust Tide backend server
- [Fetch Inject](https://github.com/vhscom/fetch-inject#sveltekit) implements a performance optimization technique for managing asynchronous JavaScript dependencies - now with Svelte support

@ -16,7 +16,7 @@ Let's dive in!
## What's new in SvelteKit
- Vite 2.9.9 was released as one of the last Vite 2 releases. The Svelte team has been hard at work contributing to the the Vite 3 release to make the integration between SvelteKit and Vite smoother than ever ([Vite 3.0 Milestone](https://github.com/vitejs/vite/milestone/5))
- Vite 2.9.9 was released as one of the last Vite 2 releases. The Svelte team has been hard at work contributing to the Vite 3 release to make the integration between SvelteKit and Vite smoother than ever ([Vite 3.0 Milestone](https://github.com/vitejs/vite/milestone/5))
- `config.kit.alias` lets you more easily declare a custom alias to replace values in `import` statements ([Docs](https://kit.svelte.dev/docs/configuration#alias), [PR](https://github.com/sveltejs/kit/pull/4964))
- Pages marked for prerendering will now fail during SSR at runtime ([PR](https://github.com/sveltejs/kit/pull/4812))

@ -26,7 +26,7 @@ We will also be utilizing OpenCollective funds to allow Svelte core maintainers
- Introduced `@sveltejs/kit/experimental/vite` which allows SvelteKit to interoperate with other tools in the Vite ecosystem like Vitest and Storybook ([#5094](https://github.com/sveltejs/kit/pull/5094)). Please [leave feedback](https://github.com/sveltejs/kit/issues/5184) as to whether the feature works and is helpful as we consider taking it out of experimental and making `vite.config.js` required for all users
- Streaming in endpoints is now supported ([#3419](https://github.com/sveltejs/kit/issues/3419)). This was enabled by switching to the Undici `fetch` implementation ([#5117](https://github.com/sveltejs/kit/pull/5117))
- Static assets can now be symlinked in development environments ([#5089](https://github.com/sveltejs/kit/pull/5089))
- `server` and `prod` environment variables are now available as a correlary to `browser` and `dev` ([#5251](https://github.com/sveltejs/kit/pull/5251))
- `server` and `prod` environment variables are now available as a corollary to `browser` and `dev` ([#5251](https://github.com/sveltejs/kit/pull/5251))
---
@ -63,7 +63,7 @@ _To Watch_
- [SvelteKit Page Endpoints](https://www.youtube.com/watch?v=yQRf2wmTu5w), [Named Layouts](https://www.youtube.com/watch?v=UHX9TJ0BxZY) and [Passing data from page component to layout component with $page.stuff](https://www.youtube.com/watch?v=CXaCstU5pcw) by lihautan
- [🍞 & 🧈: Magically load data with SvelteKit Endpoints](https://www.youtube.com/watch?v=f6prqYlbTE4) by Johnny Magrippis
- [Svelte for React developers](https://www.youtube.com/watch?v=7tsrwrx5HtQ) by frontendtier
- [Learn Svelte JS || Javascript Compiler for Building Front end Applications](https://www.youtube.com/watch?v=1rKRarJJFrY&list=PLIGDNOJWiL1-7zCgdR7MKuho-tPC6Ra6C&index=1) by Code with tsksharma
- [Learn Svelte JS || JavaScript Compiler for Building Front end Applications](https://www.youtube.com/watch?v=1rKRarJJFrY&list=PLIGDNOJWiL1-7zCgdR7MKuho-tPC6Ra6C&index=1) by Code with tsksharma
- [SvelteKit Authentication](https://www.youtube.com/watch?v=T935Ya4W5X0&list=PLA9WiRZ-IS_zKrDzhOhV5RGKKTHNIyTDO&index=1) by Joy of Code
- [Svelte + websockets: Build a real-time Auction app](https://www.youtube.com/watch?v=CqgsWFrwQIU) by Evgeny Maksimov
@ -85,7 +85,7 @@ _To Read_
- [Svelte Brick Gallery](https://github.com/anotherempty/svelte-brick-gallery) is a masonry-like image gallery component for Svelte
- [use-vest](https://github.com/enyo/use-vest) is a Svelte action for Vest - a library that makes it easy to validate forms and show errors when necessary
- [Svelidate](https://github.com/svelidate/svelidate) is a simple and lightweight form validation library for Svelte with no dependencies
- [Svve11](https://github.com/oslabs-beta/Svve11) is an "accessbility-first" component library for Svelte
- [Svve11](https://github.com/oslabs-beta/Svve11) is an "accessibility-first" component library for Svelte
- [Slidy](https://github.com/Valexr/Slidy) is a simple, configurable & reusable carousel sliding action script with templates & some useful plugins
- [Svelte Component Snippets](https://marketplace.visualstudio.com/items?itemName=brysonbw.svelte-component-snippets) is a VS Code extension with access to common Svelte snippets
- [Svelte Confetti](https://github.com/Mitcheljager/svelte-confetti) adds a little bit of flair to your app with some confetti 🎊

@ -0,0 +1,119 @@
---
title: "What's new in Svelte: August 2022"
description: "Changes to SvelteKit's `load` before 1.0 plus support for Vite 3 and `vite.config.js`!"
author: Daniel Sandoval
authorURL: https://desandoval.net
---
There's a lot to cover this month... big changes are coming to SvelteKit's design before 1.0 can be completed. If you haven't already, check out Rich's Discussion, [Fixing `load`, and tightening up SvelteKit's design before 1.0 #5748](https://github.com/sveltejs/kit/discussions/5748).
Also, [@dummdidumm](https://github.com/dummdidumm) (Simon H) [has joined Vercel to work on Svelte full-time](https://twitter.com/dummdidumm_/status/1549041206348222464) and [@tcc-sejohnson](https://github.com/tcc-sejohnson) has joined the group of SvelteKit maintainers! We're super excited to have additional maintainers now dedicated to working on Svelte and SvelteKit and have already been noticing their impact. July was the third largest month for SvelteKit changes since its inception!
Now onto the rest of the updates...
## What's new in SvelteKit
- Dynamically imported styles are now included during SSR ([#5138](https://github.com/sveltejs/kit/pull/5138))
- Improvements to routes and prop updates to prevent unnecessary rerendering ([#5654](https://github.com/sveltejs/kit/pull/5654), [#5671](https://github.com/sveltejs/kit/pull/5671))
- Lots of improvements to error handling ([#4665](https://github.com/sveltejs/kit/pull/4665), [#5622](https://github.com/sveltejs/kit/pull/5622), [#5619](https://github.com/sveltejs/kit/pull/5619), [#5616](https://github.com/sveltejs/kit/pull/5616))
- Custom Vite modes are now respected in SSR builds ([#5602](https://github.com/sveltejs/kit/pull/5602))
- Custom Vite config locations are now supported ([#5705](https://github.com/sveltejs/kit/pull/5705))
- Private environment variables (aka "secrets") are now much more secure. Now if you accidentally import them to client-side code, you'll see an error ([#5663](https://github.com/sveltejs/kit/pull/5663), [Docs](https://kit.svelte.dev/docs/configuration#env))
- Vercel's v3 build output API is now being used in `adapter-vercel` ([#5514](https://github.com/sveltejs/kit/pull/5514))
- `vite-plugin-svelte` has reached 1.0 and now supports Vite 3. You'll notice new default ports for `dev` (port 5173) and `preview` (port 4173) ([#5005](https://github.com/sveltejs/kit/pull/5005), [vite-plugin-svelte CHANGELOG](https://github.com/sveltejs/vite-plugin-svelte/blob/main/packages/vite-plugin-svelte/CHANGELOG.md))
**Breaking changes:**
- `mode`, `prod` and `server` are no longer available in `$app/env` ([#5602](https://github.com/sveltejs/kit/pull/5602))
- `svelte-kit` CLI commands are now run using the `vite` command and `vite.config.js` is required. This will allow first-class support with other projects in the Vite ecosystem like Vitest and Storybook ([#5332](https://github.com/sveltejs/kit/pull/5332), [Docs](https://kit.svelte.dev/docs/project-structure#project-files-vite-config-js))
- `endpointExtensions` is now `moduleExtensions` and can be used to filter param matchers ([#5085](https://github.com/sveltejs/kit/pull/5085), [Docs](https://kit.svelte.dev/docs/configuration#moduleextensions))
- Node 16.9 is now the minimum version for SvelteKit ([#5395](https://github.com/sveltejs/kit/pull/5395))
- %-encoded filenames are now allowed. If you had a `%` in your route, you must now encode it with `%25` ([#5056](https://github.com/sveltejs/kit/pull/5056))
- Endpoint method names are now uppercased to match HTTP specifications ([#5513](https://github.com/sveltejs/kit/pull/5513), [Docs](https://kit.svelte.dev/docs/routing#endpoints))
- `writeStatic` has been removed to align with Vite's config ([#5618](https://github.com/sveltejs/kit/pull/5618))
- `transformPage` is now `transformPageChunk` ([#5657](https://github.com/sveltejs/kit/pull/5657), [Docs](https://kit.svelte.dev/docs/hooks#handle))
- The `prepare` script is no longer needed in `package.json` ([#5760](https://github.com/sveltejs/kit/pull/5760))
- `adapter-node` no longer does any compression while we wait for a [bug fix in the `compression` library](https://github.com/expressjs/compression/pull/183) ([#5560](https://github.com/sveltejs/kit/pull/5506))
For a full list of changes, check out kit's [CHANGELOG](https://github.com/sveltejs/kit/blob/master/packages/kit/CHANGELOG.md).
## What's new in Svelte & Language Tools
- The `@layer` [CSS at-rule](https://developer.mozilla.org/en-US/docs/Web/CSS/@layer) is now supported in Svelte components (**3.49.0**, [PR](https://github.com/sveltejs/svelte/issues/7504))
- The `inert` [HTML attribute](https://html.spec.whatwg.org/multipage/interaction.html#the-inert-attribute) is now supported in Svelte's language tools and plugins (**105.20.0**, [PR](https://github.com/sveltejs/language-tools/pull/1565))
- The Svelte plugin will now use `SvelteComponentTyped` typings, if available (**105.19.0**, [PR](https://github.com/sveltejs/language-tools/pull/1548))
---
## Community Showcase
**Apps & Sites built with Svelte**
- [PocketBase](https://github.com/pocketbase/pocketbase) is an open source Go backend with a single file and an admin dashboard built with Svelte
- [Hondo](https://www.playhondo.com/how-to-play) is a word guessing game with multiple rounds
- [Hexapipes](https://github.com/gereleth/hexapipes) is a site for playing hexagonal pipes puzzle
- [Mail Must Move](https://www.mordon.app/) is an email made for those who want to get more done
- [Jot Down](https://github.com/brysonbw/vscode-jot-down) is a Visual Studio Code extension for quick and simple note taking
- [Kadium](https://kadium.kasper.space/) is an app for staying on top of YouTube channels' uploads
- [Samen zjin we #1metS10](https://1mets10.avrotros.nl/) is a campaign website to support S10, the dutch Eurovision finalist, by sending a drawing or a wish
- [On Writing Code](https://onwritingcode.com/) is an interactive website to learn programming design patterns
- [Svelte-In-Motion](https://github.com/novacbn/svelte-in-motion) lets you create Svelte-animated videos in your browser
- [Svelte Terminal](https://github.com/Nico-Mayer/svelte-terminal) is a terminal-like website
- [Bulletlist](https://bulletlist.com/) is a simple tool with a single purpose: making lists
- [Remind Me Again](https://github.com/probablykasper/remind-me-again) is an app for toggleable reminders on Mac, Linux and Windows
- [Heyweek](https://heyweek.com/) is a timetracking app built for freelancers craving that extra pizzazz
**Learning Resources**
_Starring the Svelte team_
- [The Svelte Documentary is out!](https://www.svelteradio.com/episodes/the-svelte-documentary-is-out) on Svelte Radio
- [Beginner SvelteKit](https://vercel.com/docs/beginner-sveltekit) by Vercel
- [Challenge: Explore Svelte by Building a Bubble Popping Game](https://prismic.io/blog/try-svelte-build-game) by Brittney Postma
- [Let's write a Client-side Routing Library with Svelte](https://www.youtube.com/watch?v=3foVDSknGEY) by lihautan
- [Svelte Sirens July Talk - Testing in Svelte with Jess Sachs](https://sveltesirens.dev/event/testing-in-svelte)
_To Watch_
- [10 Awesome Svelte UI Component Libraries](https://www.youtube.com/watch?v=RkD88ARvucM) by LevelUpTuts
- [Learn How SvelteKit Works](https://www.youtube.com/watch?v=VizuTy3uSNE) and [SvelteKit Endpoints](https://www.youtube.com/watch?v=XnVxDLTgCgo) by Joy of Code
- [SvelteKit using TS, and Storybook setup](https://www.youtube.com/watch?v=L4F5dSu0FcQ) by Jarrod Kane
- [Building Apps with Svelte!](https://www.youtube.com/watch?v=prsXVk1fdW4) by Simon Grimm
- [SvelteKit authentication, the better way - Tutorial](https://www.youtube.com/watch?v=Y98KipzwVdM) by Pilcrow
_To Read_
- [Some assorted Svelte demos](https://geoffrich.net/posts/assorted-svelte-demos/) by Geoff Rich
- [Three ways to bootstrap a Svelte project](https://maier.tech/posts/three-ways-to-bootstrap-a-svelte-project) by Thilo Maier
- [Design & build an app with Svelte](https://bootcamp.uxdesign.cc/design-build-an-app-with-svelte-ecd7ed0729da) by Hugo
- [Define routes via JS in SvelteKit](https://dev.to/maxcore/define-routes-via-js-in-sveltekit-27e9) by Max Core
- [Integrating Telegram api with SvelteKit](https://dev.to/theether0/integrating-telegram-api-with-sveltekit-5gb) by Shivam Meena
- [SvelteKit SSG: how to Prerender your SvelteKit Site](https://rodneylab.com/sveltekit-ssg/) by Rodney Lab
- [ADEO Design System: Building a Web Component library with Svelte and Rollup](https://medium.com/adeo-tech/adeo-design-system-building-a-web-component-library-with-svelte-and-rollup-72d65de50163) by Mohamed Mokhtari
- [The Svelte Handbook](https://thevalleyofcode.com/svelte/) by The Valley of Code
- [Test Svelte Component Using Vitest & Playwright](https://davipon.hashnode.dev/test-svelte-component-using-vitest-playwright) by David Peng
- [Transitional Apps with Phoenix and Svelte](https://nathancahill.com/phoenix-svelte) by Nathan Cahill
_Tech Demos_
- [Bringing the best GraphQL experience to Svelte](https://www.the-guild.dev/blog/houdini-and-kitql) by The Guild
- [Style your Svelte website faster with Stylify CSS](https://stylifycss.com/blog/style-your-svelte-website-faster-with-stylify-css/) by Stylify
- [Revamped Auth Helpers for Supabase (with SvelteKit support)](https://supabase.com/blog/2022/07/13/supabase-auth-helpers-with-sveltekit-support) by Supabase
**Libraries, Tools & Components**
- [Lucia](https://github.com/pilcrowOnPaper/lucia-sveltekit) is a simple, JWT based authentication library for SvelteKit that connects your SvelteKit app with your database
- [Skeleton](https://github.com/Brain-Bones/skeleton) is a UI component library for use with Svelte + Tailwind
- [pass-composer](https://pass-composer.vercel.app/) helps you compose your postprocessing passes for threlte scenes
- [@crikey/stores-*](https://whenderson.github.io/stores-mono/) is a collection of libraries to extend Svelte stores for common use-cases
- [Svelte Chrome Storage](https://github.com/shaun-wild/svelte-chrome-storage) is a lightweight abstraction between Svelte stores and Chrome extension storage
- [Svelte Schema Form](https://github.com/restspace/svelte-schema-form) is a form generator for JSON schema
- [svelte-gesture](https://github.com/wobsoriano/svelte-gesture) is a library that lets you bind richer mouse and touch events to any component or view
- [Snap Layout](https://github.com/ThaUnknown/snap-layout) and [universal-title-bar](https://github.com/ThaUnknown/universal-title-bar) bring Windows 11 snap layout and title features to webapps and PWAs. Both can be imported as a `.svelte` module or as a web component
- [svelte-adapter-bun](https://github.com/gornostay25/svelte-adapter-bun) is an adapter for SvelteKit apps that generates a standalone Bun server
- [json2dir](https://www.npmjs.com/package/json2dir) converts JSON objects into directory trees
- [Svelte Command Palette](https://github.com/rohitpotato/svelte-command-palette) is a drop-in command palette component
- [svelte-use-drop-outside](https://github.com/untemps/svelte-use-drop-outside) is a Svelte action to drop an element outside an area
- [PowerTable](https://github.com/muonw/powertable) is a JavaScript component that turns JSON data into an interactive HTML table
- [svelte-slides](https://github.com/rajasegar/svelte-slides) is a slide show template for Svelte using Reveal.js
- [Svelte Theme Light](https://marketplace.visualstudio.com/items?itemName=webmaek.svelte-theme-light) is a Visual Studio Code theme based on the Svelte REPL
Did we miss anything? Let us know on [Reddit](https://www.reddit.com/r/sveltejs/) or [Discord](https://discord.com/invite/yy75DKs)!
Still looking for something to do in September? Come join us at the Svelte Summit in Stockholm! [Get your tickets now](https://www.sveltesummit.com/).
See ya next month!

@ -0,0 +1,105 @@
---
title: "What's new in Svelte: September 2022"
description: "Migrating to SvelteKit's new filesystem-based router"
author: Daniel Sandoval
authorURL: https://desandoval.net
---
Still looking for something to do this month? It's your last chance to get tickets to Svelte Summit, Stockholm! [Join us on Sept 8-9th](https://www.sveltesummit.com/) 🎉
With the redesign of SvelteKit's filesystem-based router merging early last month, there's lots to cover this month - from the [migration script](https://github.com/sveltejs/kit/discussions/5774) to a number of new blog posts, videos and tutorials.
But the new routing isn't the only new feature in SvelteKit...
## What's new in SvelteKit
- `Link` is now supported as an HTTP header and works out of the box with Cloudflare's [Automatic Early Hints](https://github.com/sveltejs/kit/issues/5455) (**1.0.0-next.405**, [PR](https://github.com/sveltejs/kit/pull/5735))
- `$env/static/*` are now virtual to prevent writing sensitive values to disk (**1.0.0-next.413**, [PR](https://github.com/sveltejs/kit/pull/5825))
- `$app/stores` can now be used from anywhere on the browser (**1.0.0-next.428**, [PR](https://github.com/sveltejs/kit/pull/6100))
- `config.kit.env.dir` is a new config that sets the directory to search for `.env` files (**1.0.0-next.430**, [PR](https://github.com/sveltejs/kit/pull/6175))
**Breaking changes:**
- The filesystem-based router and `load` API improves the way routes are managed. **Before installing version `@sveltejs/kit@1.0.0-next.406` or later, [follow this migration guide](https://github.com/sveltejs/kit/discussions/5774)** ([PR](https://github.com/sveltejs/kit/pull/5778), [Issue](https://github.com/sveltejs/kit/discussions/5748))
- `event.session` has been removed from `load` along with the `session` store and `getSession`. Use `event.locals` instead (**1.0.0-next.415**, [PR](https://github.com/sveltejs/kit/pull/5946))
- Named layouts have been removed in favor of `(groups)` (**1.0.0-next.432**, [Docs](https://kit.svelte.dev/docs/advanced-routing#advanced-layouts), [PR & Migration Instructions](https://github.com/sveltejs/kit/pull/6174))
- `event.clientAddress` is now `event.getClientAddress()` (**1.0.0-next.438**, [PR](https://github.com/sveltejs/kit/pull/6237))
- `$app/env` has been renamed to `$app/environment`, to disambiguate with `$env/...` (**1.0.0-next.445**, [PR](https://github.com/sveltejs/kit/pull/6334))
For a full list of changes, check out kit's [CHANGELOG](https://github.com/sveltejs/kit/blob/master/packages/kit/CHANGELOG.md).
**Updates to language tools**
- TypeScript doesn't resolve imports to SvelteKit's $types very well, the latest version of Svelte's language tools makes it better (**105.21.0**, [#1592](https://github.com/sveltejs/language-tools/pull/1592))
---
## Community Showcase
**Apps & Sites built with Svelte**
- [canno](https://twitter.com/a_warnes/status/1556724034959818754?s=20&t=RyKWALPByqMT5A_PkLtUew) is a simple interactive 3d physics game with adjustable gravity, cannon power, and debug visualizer - made with threlte
- [straw.page](https://straw.page/) is an extremely simple website builder that lets you create unique websites straight from your phone
- [Patra](https://patra.webjeda.com/) lets you share short notes just with a link. No database. No storage
- [promptoMANIA](https://promptomania.com/) is an AI art community with an online prompt builder
- [Album by Mood](https://www.albumbymood.com/) lets you listen to music based on your mood
- [Daily Sumeiro](https://digivaux.com/sumeiro/daily/) is a daily game to test your math and logic skills
- [Lofi and Games](https://www.lofiandgames.com/) - play relaxing, casual games right from your browser
- [Pitch Pipe](https://github.com/joelgibson/pitch-pipe) is a digital pitch pipe with a frequency analyser and just-intonation intervals
- [classes.wtf](https://github.com/ekzhang/classes.wtf) is a custom, distributed search engine written in Go and Svelte to make searching for Harvard courses much quicker than the standard course catalog
- [Scrumpack](https://scrumpack.io/) is a set of tools to help agile/scrum teams with their ceremonies like Planning Poker and Retrospectives
**Learning Resources**
_Starring the Svelte team_
- [Supper Club × Rich Harris, Author of Svelte — Syntax Podcast 499](https://syntax.fm/show/499/supper-club-rich-harris-author-of-svelte)
- [Let's talk routing with Rich Harris on Svelte Radio](https://www.svelteradio.com/episodes/lets-talk-routing-with-rich-harris)
- [2.17 - Building the Future of Svelte at Vercel with Rich Harris](https://www.youtube.com/watch?v=F1sSUDVoij4)
- [1.15 - What's Up With SvelteKit with Shawn Wang (swyx)](https://www.youtube.com/watch?v=xLhuUShkYkM)
- [Adding Notion Tailwindcss and DaisyUI to Svelte App](https://www.youtube.com/watch?v=l4sbqrY0XGk)
- [Svelte 101 Session](https://www.youtube.com/watch?v=IIeBERpyxx4)
- [Astro and Svelte](https://www.youtube.com/watch?v=iYKKg-50Gm4)
- [Storyblok in Svelte](https://www.youtube.com/watch?v=xXHFRzqUxoE)
- [Svelte London August Recording](https://www.youtube.com/watch?v=ua6gE2zPulw)
_Learning the new SvelteKit routing_
- [Migrating Breaking Changes in SvelteKit](https://www.netlify.com/blog/migrating-breaking-changes-in-sveltekit/) by Brittney Postma (Netlify)
- [Major Svelte Kit API Change - Fixing `load`, and tightening up SvelteKit's design before 1.0](https://www.youtube.com/watch?v=OUGn7VifUCg) - Video by LevelUpTuts
- [SvelteKit Is Never Going To Be The Same](https://www.youtube.com/watch?v=eVFcGA-15LA) - Video by Joy of Code
- [Let's learn SvelteKit by building a static Markdown blog from scratch](https://joshcollinsworth.com/blog/build-static-sveltekit-markdown-blog) by Josh Collinsworth (updated Aug 26th to keep up with the new changes)
_To Watch_
- [Svelte Guide For React Developers](https://www.youtube.com/watch?v=uWDBEUkTRGk) and [Svelte State Management Guide](https://www.youtube.com/watch?v=4dDjQiOVrOo) by Joy of Code
- [What Is Bookit? The Svelte Kit Storybook Killer](https://www.youtube.com/watch?v=aOBGhvggsq0) and [What Is @type{import In Svelte Kit - JSDoc Syntax](https://www.youtube.com/watch?v=y0DvJTVO65M) by LevelUpTuts
- [TWF Yet another JS Framework... or not? Svelte!](https://www.youtube.com/watch?app=desktop&v=nT8QtDBIKZA) by TWF meetup
_To Read_
- [Creating a Figma Plugin with Svelte](https://www.lekoarts.de/javascript/creating-a-figma-plugin-with-svelte) by Lennart
- [Svelte Video Blog: Vlog with Mux from your own SvelteKit Site](https://plus.rodneylab.com/tutorials/svelte-video-blog) and [Svelte Shy Header: Peekaboo Sticky Header with CSS](https://rodneylab.com/svelte-shy-header/) by Rodney Lab
**Libraries, Tools & Components**
- [@svelte-plugins/tooltips](https://github.com/svelte-plugins/tooltips) is a simple tooltip action and component designed for Svelte
- [Lucia](https://github.com/pilcrowOnPaper/lucia-sveltekit) is a simple authentication library for SvelteKit that connects your SvelteKit app to your database
- [remix-router-svelte](https://github.com/brophdawg11/remix-routers/tree/main/packages/svelte) is a Svelte implementation of the `react-router-dom` API (driven by `@remix-run/router`)
- [MKRT](https://github.com/j4w8n/mkrt) is a CLI to help you create SvelteKit routes, fast
- [Histoire](https://histoire.dev/guide/) is a tool to generate stories applications - scenarios where you showcase components for specific use cases
- [sveltekit-flash-message](https://www.npmjs.com/package/sveltekit-flash-message) is a Sveltekit library that passes temporary data to the next request, usually from endpoints
- [svelte-particles](https://github.com/matteobruni/tsparticles#svelte) is a lightweight TypeScript library for creating particles
- [svelte-claps](https://github.com/bufgix/svelte-claps) adds clap button (like Medium) to any page for your SvelteKit apps
- [Neon Flicker](https://svelte.dev/repl/fd5e3b2be7da42fe8afddf89661af7d7?version=3.49.0) is a Svelte component to make your text flicker in a cyberpunk style
- [ComboBox](https://svelte.dev/repl/144f22d18c6943abb1fdd00f13e23fde?version=3.49.0) is a search input to help users select from a large list of items
- [@svelte-put](https://github.com/vnphanquang/svelte-put) is useful svelte stuff to put in your projects
- [vite-plugin-svelte-bridge](https://github.com/joshnuss/vite-plugin-svelte-bridge) lets you write Svelte components and use them from React & Vue
_UI Kits and Starters_
- [Svelte-spectre](https://github.com/basf/svelte-spectre) is a UI-kit based on spectre.css and powered by Svelte
- [Skeleton](https://skeleton.brainandbonesllc.com/) allows you to build fast and reactive web UI using the power of Svelte + Tailwind
- [iconsax-svelte](https://www.npmjs.com/package/iconsax-svelte) brings the popular icon kit to Svelte
- [laravel-vite-svelte-spa-template](https://github.com/NukeJS/laravel-vite-svelte-spa-template) is a Laravel 9, Vite, Svelte SPA, Tailwind CSS (w/ Forms Plugin & Aspect Ratio Plugin), Axios, & TypeScript starter template
- [neutralino-svelte-boilerplate-js](https://github.com/Raffaele/neutralino-svelte-boilerplate-js) is a cross platform desktop template for Neutralino and Svelte
- [figma-plugin-svelte-vite](https://github.com/candidosales/figma-plugin-svelte-vite) is a boilerplate for creating Figma plugins using Svelte, Vite and Typescript
- [Urara](https://github.com/importantimport/urara) is a sweet & powerful SvelteKit blog starter
- [SvelteKit Commerce](https://vercel.com/templates/svelte/sveltekit-commerce) is an all-in-one starter kit for high-performance e-commerce sites built with SvelteKit by Vercel
Did we miss anything? Let us know on [Reddit](https://www.reddit.com/r/sveltejs/) or [Discord](https://discord.com/invite/yy75DKs)!
See ya next month!

@ -0,0 +1,139 @@
---
title: "What's new in Svelte: October 2022"
description: "Svelte Summit, `use:enhance`, and a SvelteKit Release Candidate!"
author: Daniel Sandoval
authorURL: https://desandoval.net
---
There's a bunch of updates this month... from new features in Svelte and SvelteKit to a whole 2-day *summit*! Plus, the Svelte extension gets some helpful new tools, new accessibility (a11y) warnings, and Tan Li Hau teaches us how to build our own Svelte and a Svelte spreadsheet 😎
## What happened at Svelte Summit?
A lot! Below you can find all the talks, by timestamp, from each livestream. Bite-size videos of the event will be coming soon to the Svelte Society channel, so be sure to [Subscribe](https://www.youtube.com/c/SvelteSociety), if you haven't already!
_Day One_
- [12:31](https://www.youtube.com/watch?v=pJcbZr5VlV4&t=751s) - How to get Svelte adopted at work
- [33:21](https://www.youtube.com/watch?v=pJcbZr5VlV4&t=2001s) - Animating Data Visualization in Svelte
- [2:20:36](https://www.youtube.com/watch?v=pJcbZr5VlV4&t=8436s) - Red flags & code smells
- [2:53:42](https://www.youtube.com/watch?v=pJcbZr5VlV4&t=10422s) - Enhance your DX
- [4:42:41](https://www.youtube.com/watch?v=pJcbZr5VlV4&t=16961s) - Svelte in UBS knowledge graph
- [5:06:42](https://www.youtube.com/watch?v=pJcbZr5VlV4&t=18402s) - How to migrate react libraries to svelte
- [5:45:27](https://www.youtube.com/watch?v=pJcbZr5VlV4&t=20727s) - DX magic in the world of Svelte
- [7:25:39](https://www.youtube.com/watch?v=pJcbZr5VlV4&t=26739s) - Data visualizations powered by Svelte
- [7:59:38](https://www.youtube.com/watch?v=pJcbZr5VlV4&t=28778s) - Partial Hydration in Svelte for Increased Performance
- [8:20:49](https://www.youtube.com/watch?v=pJcbZr5VlV4&t=30049s) - Building the future, faster
_Day Two_
- [24:09](https://www.youtube.com/watch?v=A8jkJTWacow&t=1449s) - Scrollytell me why: Ain't nothing but a piece of cake
- [2:02:40](https://www.youtube.com/watch?v=A8jkJTWacow&t=7360s) - I told you my dog wouldnt run
- [2:29:43](https://www.youtube.com/watch?v=A8jkJTWacow&t=8983s) - 10Xing Svelte
- [3:04:56](https://www.youtube.com/watch?v=A8jkJTWacow&t=11096s) - Svemix? Re-svmix? Re-svelte?: Bringing Svelte to Remix Router
- [5:09:39](https://www.youtube.com/watch?v=A8jkJTWacow&t=18579s) - Having fun with stores: an interactive demo of Sveltes built in state management library
- [5:37:06](https://www.youtube.com/watch?v=A8jkJTWacow&t=20226s) - When Keeping it Svelte Goes Wrong. An Analysis of Some of the Worst Svelte I Have Ever Coded
- [7:22:05](https://www.youtube.com/watch?v=A8jkJTWacow&t=26525s) - Getting started with Hooks
- [7:38:14](https://www.youtube.com/watch?v=A8jkJTWacow&t=27494s) - Special Announcement*
*In the final talk of the summit, Rich Harris announces the first Release Candidate of SvelteKit! With no planned breaking changes left, the team is hard at work squashing bugs and adding the remaining features for 1.0...
## More SvelteKit Updates
- `use:enhance` is the easiest way to progressively enhance a form ([Docs](https://kit.svelte.dev/docs/form-actions#progressive-enhancement-use-enhance), [#6633](https://github.com/sveltejs/kit/pull/6633), [#6828](https://github.com/sveltejs/kit/pull/6828), [#7012](https://github.com/sveltejs/kit/pull/7012))
- The demo app has been updated to add the Sverdle game, which Rich demoed at Svelte Summit and demonstrates `use:enhance` ([#6979](https://github.com/sveltejs/kit/pull/6979))
- Cloudflare Pages `_routes.json` specification is now supported by `adapter-cloudflare` ([#6530](https://github.com/sveltejs/kit/pull/6530))
- Improved build performance by running asset and page compression in parallel ([#6710](https://github.com/sveltejs/kit/pull/6710))
**Breaking changes:**
- Node 16.14 is now the minimum version to run SvelteKit ([#6388](https://github.com/sveltejs/kit/pull/6388))
- `App.PrivateEnv` and `App.PublicEnv` have been removed in favour of generated types ([#6413](https://github.com/sveltejs/kit/pull/6413))
- `%sveltekit.message%` has been replaced with `%sveltekit.error.message%` ([6659](https://github.com/sveltejs/kit/pull/6659))
- `App.PageError` is now `App.Error` - check for it in your hooks ([Docs](https://kit.svelte.dev/docs/hooks#shared-hooks-handleerror), [#6963](https://github.com/sveltejs/kit/pull/6963))
- `externalFetch` is now `handleFetch` and will run for all fetch calls in `load` that run on the server ([#6565](https://github.com/sveltejs/kit/pull/6565))
For a full list of changes, check out SvelteKit's [CHANGELOG](https://github.com/sveltejs/kit/blob/master/packages/kit/CHANGELOG.md).
## Svelte Updates
- New a11y warnings for `incorrect-aria-attribute-type`, `no-abstract-role`, `interactive-element-to-noninteractive-role` and `role-has-required-aria-props`.`no-noninteractive-tabindex` and `click-events-have-key-events` coming soon! (**3.50.0**)
- New types for `ComponentEvents` and `SveltePreprocessor` (**3.50.0**)
- Improved parsing speed when encountering large blocks of whitespace (**3.50.0**)
- All global JavaScript objects and functions are now recognized as known globals (**3.50.1**)
For all the changes to the Svelte compiler, including upcoming changes, check out the [CHANGELOG](https://github.com/sveltejs/svelte/blob/master/CHANGELOG.md).
## New in Language Tools
- Better code formatting for editor suggestion (**106.0.0**, [#1598](https://github.com/sveltejs/language-tools/pull/1598))
- Easily create SvelteKit route files from the context menu or command palette (**106.1.0**, [#1620](https://github.com/sveltejs/language-tools/pull/1620))
---
## Ask Questions in the Svelte Discord
In case you missed the announcement, the Svelte Discord has an exciting new update... a forum! The new [questions channel](https://discord.com/channels/457912077277855764/1023340103071965194) utilizes Discord's new forums feature to help the community better ask, find and answer questions!
It can be used for anything you may be trying to accomplish using Svelte including using SvelteKit, community libraries, tools, etc. So ask away!
---
## Community Showcase
**Apps & Sites built with Svelte**
- [Timeflow](https://www.timeflow.site/) is a smart calendar & task manager that dynamically schedules your tasks between your events
- [GeoQuest](https://github.com/woutdp/geoquest) is an open source geography game
- [Houses Of](https://housesof.world/) is a project showcasing charismatic houses around the world
- [Greenfield Brewery](https://greenfield-brewery.vercel.app/) is a tool for quickly installing a lot of homebrew casks
- [Gram Jam](https://gramjam.app/) is a word puzzle game inspired by match three games and Scrabble
- [Beatbump](https://github.com/snuffyDev/Beatbump) is a privacy-respecting alternative frontend for YouTube Music
- [RoomOS Device Widgets](https://github.com/wxsd-sales/roomos-device-widgets) is an app for demoing RoomOS device capabilities in Kiosk/PWA mode
- [World Seed](https://store.steampowered.com/app/1870320/World_Seed/) is a full blown online multiplayer game
- [Lirify](https://lirify-tan.vercel.app/) is a song lyrics writing web app tool made in Latvia
- [Splet Tech Konferencija](https://www.splet.rs/) is a tech conference in Serbia with a *very* fancy website
- [Unbounded](https://unbounded.polkadot.network/) is an open-source variable font - funded by blockchain (and an awesome-looking website)
- [Porter's Paints](https://shop.porterspaints.com/) is an eCommerce site for (you guessed it) paints built with Svelte
- [CRAN/E](https://www.cran-e.com/) is a search engine for modern R-packages
**Learning Resources**
_Starring the Svelte team_
- [Upgrading SvelteKit](https://www.youtube.com/watch?v=vzeZskhjoeQ) by Svelte Sirens (with Brittney, Kev, and GHOST!)
- [Build your own Svelte](https://www.youtube.com/watch?v=mwvyKGw2CzU) by lihautan
- [Native Page Transitions in SvelteKit: Part 1](https://geoffrich.net/posts/page-transitions-1/) by Geoff Rich
- [Build a cross platform app with Tauri](https://ghostdev.xyz/posts/build-a-cross-platform-app-with-tauri/) by GHOST
_To Watch_
- [How To Use Future CSS In Svelte](https://www.youtube.com/watch?v=eqwtoaP-0pk) and [Master Animation With Svelte](https://www.youtube.com/watch?v=3RlBfUQCiAQ) by Joy of Code
- [Svelte Kit Form Actions 101 - New Svelte Kit API](https://www.youtube.com/watch?v=i5zdnv83mxY) and [Svelte Kit Form Actions - Real World Examples - Q&A](https://www.youtube.com/watch?v=PK2Mpt1q6K8) by LevelUpTuts
_To Read_
- [What's new in `svelte-kit, 1.0.0-next.445`: (group) layout](https://dev.to/parables/whats-new-in-svelte-kit-100-next445-group-layout-1ld5) by Parables
- [Handling breaking changes in SvelteKit pre-1.0](https://maier.tech/posts/handling-breaking-changes-in-sveltekit-pre-1-0) by Thilo Maier
- [Svelte Custom Stores Demystified](https://raqueebuddinaziz.com/blog/svelte-custom-stores-demystified/) by Raqueebuddin Aziz
- Sveltekit Changes: [Advanced Layouts](https://dev.to/theether0/sveltekit-changes-advanced-layouts-3id4), [Form Actions and Progressive Enhancement](https://dev.to/theether0/sveltekit-changes-form-actions-and-progressive-enhancement-31h9) and [Cookies and Authentication](https://dev.to/theether0/sveltekit-changes-session-and-cookies-enb) by Shivam Meena
- [How to add an Emoji Picker to Sveltekit](https://xvrc.net/) by Xavier Coiffard
- [Get Started with SvelteKit Headless WordPress](https://plus.rodneylab.com/tutorials/get-started-sveltekit-headless-wordpress) by Rodney Lab
- [Speed up SvelteKit Pages With a Redis Cache](https://www.captaincodeman.com/speed-up-sveltekit-pages-with-a-redis-cache) and [How to await Firebase Auth with SvelteKit](https://www.captaincodeman.com/how-to-await-firebase-auth-with-sveltekit) by Captain Codeman
- [Deploying SvelteKit with NodeJS to a Server Using GitLab and PM2](https://abyteofcoding.com/blog/deploying-sveltekit-with-nodejs-pm2-to-server/) by A Byte of Coding
- [Quality of Life Tips when using SvelteKit in VS Code](https://www.reddit.com/r/sveltejs/comments/xltgyp/quality_of_life_tips_when_using_sveltekit_in_vs/) by doa-doa
**Libraries, Tools & Components**
- [Svelte Fit](https://github.com/leveluptuts/svelte-fit) is an extremely simple, no dependency fit text library
- [svelte-switch-case](https://github.com/l-portet/svelte-switch-case) is a switch case syntax for your Svelte components
- [svelte-canvas-confetti](https://github.com/andreasmcdermott/svelte-canvas-confetti) uses a single canvas to render full-screen confetti
- [@slidy/svelte](https://github.com/Valexr/Slidy/tree/master/packages/svelte) is a simple, configurable & reusable carousel component built with Svelte - based on `@slidy/core`
- [svelte-currency-input](https://github.com/canutin/svelte-currency-input) is a form input that converts numbers to localized currency formats as you type
- [Adria](https://github.com/pilcrowOnPaper/adria) is a super simple form validation library, with autocomplete and value/type checking
- [Canopy](https://github.com/oslabs-beta/canopy) is a Svelte debugging app for the Chrome devtools panel
- [MenuFramework](https://github.com/MyHwu9508/altv-os-menu-framework) is a menu framework written for [alt:V](https://altv.mp/#/)
- [whyframe](https://whyframe.dev/) gives iframes superpowers, making it easy to render anything in isolation
- [@svelte-put/modal](https://github.com/vnphanquang/svelte-put/tree/main/packages/misc/modal) is a solution to async, declarative, type-safe modals in Svelte
- [Kitty](https://github.com/grottopress/kitty) is a collection of libraries and handlers for developing secure frontend apps
- [svelte-turnstile](https://github.com/ghostdevv/svelte-turnstile) is a component for Cloudflare Turnstile, the privacy focused CAPTCHA replacement
_UI Kits and Starters_
- [QWER](https://github.com/kwchang0831/svelte-QWER) is a blog starter built with SvelteKit
- [SvelteKit Zero API](https://github.com/Refzlund/sveltekit-zero-api) provides type-safety between the frontend and backend - creating a structure for easy APIs
- [sveltekit-monorepo](https://github.com/sw-yx/sveltekit-monorepo) is monorepo starter with 2022 tech
- [svelte-component-test-recipes](https://github.com/davipon/svelte-component-test-recipes) uses `vitest`, `@testing-library/svelte`, and `svelte-htm` to test Svelte components that seemed to be hard to test
Whew! That's a lot of updates. Let us know if we missed anything on [Reddit](https://www.reddit.com/r/sveltejs/) or [Discord](https://discord.com/invite/yy75DKs)!
See ya next month 👋

@ -0,0 +1,116 @@
---
title: "What's new in Svelte: November 2022"
description: "Better forms, routes and inline styles across SvelteKit and Svelte"
author: Daniel Sandoval
authorURL: https://desandoval.net
---
It's been a busy October for the Svelte community. `use:enhance` and Advanced Routes got some great improvements in SvelteKit while the Svelte compiler released a minor version to improve the day-to-day dev experience.
There's also a _huge_ showcase to cover... so let's jump in!
## What's new in SvelteKit
- The new `update` method for `use:enhance` lets you easily get back the default form behavior while augmenting it with your own logic ([docs](https://kit.svelte.dev/docs/form-actions#progressive-enhancement-use-enhance), [#7083](https://github.com/sveltejs/kit/pull/7083) and [#7326](https://github.com/sveltejs/kit/pull/7326))
- `[[optional]]` parameters are now available for routing ([docs](https://kit.svelte.dev/docs/advanced-routing#optional-parameters), [#7051](https://github.com/sveltejs/kit/pull/7051))
- `goto` now has `invalidateAll` to (re-)run all `load` functions belonging to the new active page ([docs](https://kit.svelte.dev/docs/modules#$app-navigation-goto), [#7407](https://github.com/sveltejs/kit/pull/7407))
- `config.kit.paths.base` is now used in adapters looking for static assets - fixing 404 issues across `adapter-netlify`, `adapter-vercel`, `adapter-cloudflare`, and `adapter-cloudflare-workers` ([#4448](https://github.com/sveltejs/kit/pull/4448))
**Breaking changes:**
- Errors will now be thrown when routes conflict ([#7051](https://github.com/sveltejs/kit/pull/7051))
- The global `fetch` override has been removed when prerendering ([#7318](https://github.com/sveltejs/kit/pull/7318))
- Route IDs have been prefixed with `/` ([#7338](https://github.com/sveltejs/kit/pull/7338))
## Svelte changes
- New accessibility warnings, `a11y-click-events-have-key-events` and `a11y-no-noninteractive-tabindex`, will now warn when your components lack required key events or tabindex. While `a11y-role-has-required-aria-props` will no longer warn when elements match their semantic role (**3.51.0**)
- `--style-props` are now supported on `<svelte:component>` and `<svg>` (**3.51.0**, Component Example: [Before](https://svelte.dev/repl/48984f20503f4959b70f24f4130d164b?version=3.47.0) and [After](https://svelte.dev/repl/48984f20503f4959b70f24f4130d164b?version=3.51.0), SVG Example: [Before](https://svelte.dev/repl/b7a3f94255914044b35462234ccaea43?version=3.50.0) and [After](https://svelte.dev/repl/b7a3f94255914044b35462234ccaea43?version=3.51.0))
- "nullish" values for component event handlers are now supported (**3.51.0**, [Example](https://svelte.dev/repl/9228022922af4c76af68ce42349ccbf9?version=3.51.0))
- Scoped styles can now be applied to `<svelte:element>` (**3.51.0**, [Example](https://svelte.dev/repl/23d982fc6f4f4f06a6aa227860fa2d84?version=3.51.0))
- You can now use `important` in inline style tags: `style:foo|important` (**3.52.0**, [#7365](https://github.com/sveltejs/svelte/issues/7365))
- A warning will now be thrown when using `<a target="_blank">` without `rel="noreferrer"` (**3.52.0**, [#6188](https://github.com/sveltejs/svelte/issues/6188))
Tom Smykowski also released a great summary of [all the changes in 3.52.0](https://tomaszs2.medium.com/svelte-3-52-0-improves-dev-experience-45f8c460bb96)! For all the changes to the Svelte compiler, including upcoming changes, check out the [CHANGELOG](https://github.com/sveltejs/svelte/blob/master/CHANGELOG.md).
---
## Community Showcase
**Apps & Sites built with Svelte**
- [AttendZen](https://www.attendzen.io/) is an event management and marketing platform for in-person, virtual or hybrid events
- [Gram Jam](https://gramjam.app/) is a challenging daily word game using SvelteKit
- [Collabwriting](https://collabwriting.com/) is an actionable knowledge base for your team
- [Dazzle](https://dazzlega.me/) is a Puzzle Game made with Svelte & DallE
- [Figma Autoname plugin](https://github.com/Hugo-Dz/figma_autoname_client_app) automatically names your Figma layers in one click
- [DECK](https://github.com/sfx101/deck) is powerful and high performant local web development studio for MacOS, Ubuntu and Windows
- [Asm editor](https://github.com/Specy/asm-editor) is a webapp to write and run m68k assembly code
- [Nucleus](https://github.com/mellobacon/Nucleus) is a text editor featuring a clean and easy to use user interface inspired by Visual Studio Code, Atom, Fleet, and others
- [Observer](https://github.com/diamonc/observer) is a frontend for Arth Panel, an open-source & self-hosted minecraft server panel
- [.PLAN](https://plan.lodzero.com/) is a cloud-based notetaking app with markdown and section support
- [Stablecog](https://github.com/yekta/stablecog) is a simple, free & open source AI image generator
- [FreeSpeech AAC](https://github.com/merkie/freespeech) is a free and open-source assistive communication app written in TypeScript
- [sqrdoff](https://sqrdoff.cubieverse.co/) is a dots and boxes to enjoy playing with friends
- [itty](https://launch.itty-sh.pages.dev/) is a fresh take on the traditional link-shortener
- [splits](https://splits.best/) lets you track your splits, calculate your race pace, become a better athlete
- [Weaver](https://jrende.xyz/weaver/) is an application for creating [weave drafts](https://www.gistyarn.com/blogs/how-to-weave/how-to-read-a-weaving-draft)
**Learning Resources**
_To Watch_
- [Starting With Svelte - Brittney Postma](https://www.youtube.com/watch?v=pdKJzrPA0DY) by fitcevents
- [Learn Svelte from scratch with Geoff Rich: A Svelte tutorial](https://www.youtube.com/watch?v=QoR0AZ-Rov8) by Kelvin Omereshone
- [How To Connect to MongoDB in Svelte Kit](https://www.youtube.com/watch?v=gwktlvFHLMA) by LevelUpTuts
- [SvelteKit Authentication Using Cookies](https://www.youtube.com/watch?v=E3VG-dLCRUk), [Make A Typing Game With Svelte](https://www.youtube.com/watch?v=kMz_Ba_OF2w) and [SvelteKit Tailwind CSS Setup With Automatic Class Sorting](https://www.youtube.com/watch?v=J_G_xP0chog) by Joy of Code
- [Authentication with SvelteKit & PocketBase](https://www.youtube.com/watch?v=doDKaKDvB30) and [Form Actions in SvelteKit (+page)](https://www.youtube.com/watch?v=52nXUwQWeKI) by Huntabyte
- [Sybil - Episode 1 - Rust knowledge management with SurrealDB](https://www.youtube.com/watch?v=eC7IePI5rIk) by Raphael Darley
_To Read_
- [4 things I miss from Svelte after working in React](https://geoffrich.net/posts/4-things-i-miss-svelte/) and [Create dynamic social card images with Svelte components](https://geoffrich.net/posts/svelte-social-image/) by Geoff Rich
- [First-class Vite support in Storybook 7.0](https://storybook.js.org/blog/first-class-vite-support-in-storybook/) (Svelte and SvelteKit included) by Ian VanSchooten
- [Better Svelte support is coming to WebStorm](https://blog.jetbrains.com/webstorm/2022/09/webstorm-2022-3-eap1/#information_regarding_svelte_support) from JetBrains
- [Dark Mode](https://pyronaur.com/dark-mode/) Toggle by pyronaur
- [HeadlessUI Components with Svelte](https://www.captaincodeman.com/headlessui-components-with-svelte) by Captain Codeman
- [Using Sequelize with SvelteKit](https://cherrific.io/0xedB00816FB204b4CD9bCb45FF2EF693E99723484/story/23) by MetaZebre
- [Implementing Maintenance mode on a SvelteKit site](https://blog.encodeart.dev/implementing-maintenance-mode-on-a-sveltekit-site) by Andreas Söderlund
- [ActionStore: Real-time Svelte stores for Rails](https://dev.to/buhrmi/actionstore-real-time-svelte-stores-for-rails-4jhg) by Stefan Buhrmester
- [Svelte CSS Image Slider: with Bouncy Overscroll](https://rodneylab.com/svelte-css-image-slider/) and [SvelteKit Local Edge Functions: Edge on Localhost](https://rodneylab.com/sveltekit-local-edge-functions/) by Rodney Lab
- [Creating a Svelte Tabs component with Slot props](https://blog.openreplay.com/creating-a-svelte-tabs-component-with-slot-props/) by Shinichi Okada
- [Sky Cart: An Open Source, cloud-agnostic shopping cart using Stripe Checkout](https://dev.to/stripe/sky-cart-an-open-source-cloud-agnostic-shopping-cart-using-stripe-checkout-o5k) by Mike Bifulco for Stripe
**Libraries, Tools & Components**
- [Threlte](https://threlte.xyz/) is a component library for Svelte to build and render three.js scenes declaratively and state-driven in Svelte apps. It's being featured again to highlight the new "Playground" button in its examples
- [Svelte Turnstile](https://github.com/ghostdevv/svelte-turnstile) is a library to integrate Cloudflare's Turnstile (a new CAPTCHA alternative) into a Svelte app
- [ActionStore](https://github.com/buhrmi/actionstore) allows you to push data directly into Svelte stores via ActionCable
- [SvelteKit + `<is-land>`](https://sveltekit-is-land.vercel.app/) is an experiment with partial hydration in SvelteKit using `@11ty/is-land`
- [Svelte Color Select](https://github.com/CaptainCodeman/svelte-color-select) is an Okhsv Color Selection component for Svelte using OKLab perceptual colorspace
- [svelte-awesome-color-picker](https://github.com/Ennoriel/svelte-awesome-color-picker) is a highly customizable color picker component library
- [rx-svelte-forms](https://www.npmjs.com/package/rx-svelte-forms) creates reactive Svelte forms inspired by Angular reactive forms
- [svelte-wc-bind](https://www.npmjs.com/package/svelte-wc-bind) enables two way data binding in Svelte web components
- [svelte-preprocess-style-child-component](https://github.com/valterkraemer/svelte-preprocess-style-child-component) allows you to style elements inside a child component using similar syntax as CSS Shadow Parts
- [unplugin-svelte-components](https://www.npmjs.com/package/unplugin-svelte-components) allows for on-demand components auto importing for Svelte
- [sveltekit-search-params](https://github.com/paoloricciuti/sveltekit-search-params) aims to be the fastest way to read AND WRITE from query search params in SvelteKit
- [svelte-crop-window](https://github.com/sabine/svelte-crop-window) is a crop window component for images and videos that supports touch gestures (pinch zoom, rotate, pan), as well as mousewheel zoom, mouse-dragging the image, and rotating on right mouse button
- [Open Graph Image Generation](https://github.com/etherCorps/sveltekit-og) lets you generate open graph images dynamically from HTML/CSS without a browser in SvelteKit
- [Svelte Tap Hold](https://github.com/binsarjr/svelte-taphold) is a minimalistic tap and hold component for Svelte/SvelteKit
- [svelte-copy](https://github.com/ghostdevv/svelte-copy)'s new version lets you customize the events that cause text to be copied to the clipboard
_UI Kits, Integrations and Starters_
- [SvelteKit Statiko](https://github.com/ivodolenc/sveltekit-statiko) is a multi-featured assistant for SvelteKit static projects
- [Svelte-TailwindCSS UI (STWUI)](https://github.com/N00nDay/stwui) is a Tailwind-based UI that is currently in pre-release beta
- [KitBase](https://github.com/kevmodrome/kitbase) is a starter template for SvelteKit and PocketBase
- [UnoCSS Vite Plugin (svelte-scoped)](https://github.com/unocss/unocss/tree/main/examples/sveltekit-scoped) is a scoped-CSS utility for Vite/SvelteKit
- [SvelteKit Auth App](https://github.com/fabiorodriguesroque/sveltekit_auth_app) is an example of how we can create an authentication system with SvelteKit using JsonWebToken and Prisma
- [SvelteKit Supabase Dashboard](https://github.com/xulioc/sveltekit-supabase-dashboard) is a simple dashboard inspired by Supabase UI made with SvelteKit as frontend and Supabase as backend
- [Supakit](https://github.com/j4w8n/supakit) is a Supabase auth helper for SvelteKit
- [@bun-community/sveltekit-adapter-bun](https://www.npmjs.com/package/@bun-community/sveltekit-adapter-bun) is an adapter for SvelteKit apps that generates a standalone Bun server
- [hooks-as-store](https://github.com/micha-lmxt/hooks-as-store) lets you use React custom hooks in Svelte Apps
_Fun ones_
- [svelte-typewriter-store](https://github.com/paoloricciuti/svelte-typewriter-store) is the simplest way to get a rotating typewriter effect in Svelte
- [Aksel](https://www.npmjs.com/package/aksel) is the seagull you needed on your site
- [Svelte-Dodge](https://github.com/WbaN314/svelte-dodge) makes components dodge the pointer
That's it for this month! Let us know if we missed anything on [Reddit](https://www.reddit.com/r/sveltejs/) or [Discord](https://discord.gg/svelte)
See ya next month 👋

@ -0,0 +1,102 @@
---
title: "What's new in Svelte: December 2022"
description: "Rounding the corner to SvelteKit 1.0"
author: Daniel Sandoval
authorURL: https://desandoval.net
---
SvelteKit 1.0 is just around the corner! With [99% of the milestone issues completed](https://github.com/sveltejs/kit/milestone/2), there's a lot of new changes from the last month to cover...
Let's get to it!
## What's new in SvelteKit
- Use the `willUnload` property to find out if the navigation will result the app being unloaded (full page reload/closing/leaving to another page). ([#6813](https://github.com/sveltejs/kit/pull/6813))
- `__data.json` requests now allows for caching while ensuring we cache matching responses for all invalidation scenarios ([#7532](https://github.com/sveltejs/kit/pull/7532))
- Linking to `<a name="hash">` tags is now supported ([#7596](https://github.com/sveltejs/kit/pull/7596))
- Throwing redirects in the `handle` hook is now supported ([#7612](https://github.com/sveltejs/kit/pull/7612))
- A fallback component will now be added automatically for layouts without one ([#7619](https://github.com/sveltejs/kit/pull/7619))
- The new `preload` function within the `resolve` hook determines what files should be added to the <head> tag to preload it ([Docs](https://kit.svelte.dev/docs/hooks#server-hooks-handle), [#4963](https://github.com/sveltejs/kit/pull/4963), [#7704](https://github.com/sveltejs/kit/pull/7704))
- `version` is now available via `$app/environment` ([#7689](https://github.com/sveltejs/kit/pull/7689), [#7694](https://github.com/sveltejs/kit/pull/7694))
- `handleError` can now return a promise ([#7780](https://github.com/sveltejs/kit/pull/7780))
**Breaking changes:**
- `routeId` is now `route.id` ([#7450](https://github.com/sveltejs/kit/pull/7450))
- 'load' has been renamed to 'enter' and 'unload' to 'leave' in the `beforeNavigate` and `afterNavigate` methods. `beforeNavigate` is now called once with type 'unload' on external navigation and will no longer run during redirects ([#7502](https://github.com/sveltejs/kit/pull/7502), [#7529](https://github.com/sveltejs/kit/pull/7529), [#7588](https://github.com/sveltejs/kit/pull/7588))
- The `redirect` helper will now only allow status codes between 300-308 for redirects and only `error` status codes between 400-599 are allowed ([#7767](https://github.com/sveltejs/kit/pull/7767)) ([#7615](https://github.com/sveltejs/kit/pull/7615), [#7767](https://github.com/sveltejs/kit/pull/7767))
- Special characters will now be encoded with hex/unicode escape sequences in route directory names ([#7644](https://github.com/sveltejs/kit/pull/7644))
- devalue is now used to (de)serialize action data - this is only a breaking change for everyone who fetches the actions directly and doesn't go through `use:enhance` ([#7494](https://github.com/sveltejs/kit/pull/7494))
- `trailingSlash` is now a page option, rather than configuration ([#7719](https://github.com/sveltejs/kit/pull/7719))
- The client-side router now ignores links outside `%sveltekit.body%` ([#7766](https://github.com/sveltejs/kit/pull/7766))
- `prerendering` is now named `building`, and `config.kit.prerender.enabled` has been removed ([#7762](https://github.com/sveltejs/kit/pull/7762))
- `getStaticDirectory()` has been removed from the builder API ([#7809](https://github.com/sveltejs/kit/pull/7809))
- The `format` option has been removed from `generateManifest(...)` ([#7820](https://github.com/sveltejs/kit/pull/7820))
- `data-sveltekit-prefetch` has been replaced with `-preload-code` and `-preload-data`, `prefetch` is now `preloadData` and `prefetchRoutes` is now `preloadCode` ([#7776](https://github.com/sveltejs/kit/pull/7776), [#7776](https://github.com/sveltejs/kit/pull/7776))
- `SubmitFunction` has been moved from `$app/forms` into `@sveltejs/kit` ([#7003](https://github.com/sveltejs/kit/pull/7003))
## New in Svelte
- The css compiler options of `css: false` and `css: true` have been replaced with `'external' | 'injected' | 'none'` settings to speed up compilation for `ssr` builds and improve clarity (**3.53.0**)
For all the changes to the Svelte compiler, including unreleased changes, check out the [CHANGELOG](https://github.com/sveltejs/svelte/blob/master/CHANGELOG.md).
---
## Community Showcase
**Apps & Sites built with Svelte**
- [Appwrite's new console](https://github.com/appwrite/console) makes its secure backend server for web, mobile & Flutter developers avaiable in the browser
- [RepoMagic](https://www.repomagic.com/) is a search and analytics tool for GitHub
- [Podman Desktop](https://github.com/containers/podman-desktop) is a graphical tool for developing on containers and Kubernetes
- [Ballerine](https://github.com/ballerine-io/ballerine) is a Know Your Customer (KYC) UX for any vertical or geography using modular building blocks, components, and 3rd party integrations
- [Budget Pen](https://github.com/Nico-Mayer/budget_pen) is a Codepen-like browser code editor with Tailwind included
- [doTogether](https://github.com/SarcevicAntonio/doTogether) helps you keep track of stuff you have get done via a List of recurring Tasks
- [Webscraped College Results](https://www.redditcollegeresults.com/) is a collection of visualizations for data from r/collegeresults
- [Let's premortem](https://letspremortem.com/) helps avoid lengthy, frustrating post-mortems after a project fails
- [BLKMARKET.COM](https://beta.blkmarket.com/) is an illustration library for commercial and personal use
- [Sigil](https://sigilspace.com/) is a canvas for anything with spaces organized by the most-voted content
- [corpus-activity-streams](https://github.com/ryanatkn/corpus-activity-streams) is an unofficial ActivityStreams 2.0 vocabulary data set and alternative docs
- [nodeMyAdmin](https://github.com/Andrea055/nodeMyAdmin) is an alternative to phpMyAdmin written with SvelteKit
- [Image to Pattern Conversion](https://www.thread-bare.com/convert) is a cross-stitch pattern conversion tool with [a list of pre-made patterns](https://www.thread-bare.com/store) to start with
- [Verbums](https://verbums.vdoc.dev/) is an English vocabulary trainer to improve language comprehension
- [SVGPS](https://svgps.app/) removes the burden of working with a cluster of SVG files by converting your icons into a single JSON file
- [This 3D retro-themed asteroid shooter](https://photon-alexwarnes.vercel.app/showcase/asteroids) was made with threlte
**Learning Resources**
_To Hear_
- [Catching up after Svelte Summit](https://www.svelteradio.com/episodes/catching-up) and [3D, WebGL and AI](https://www.svelteradio.com/episodes/3d-webgl-and-ai) by Svelte Radio
_To Watch_
- [Domenik Reitzner - The easy way, an introduction to Sveltekit](https://www.youtube.com/watch?v=t-LKRrNedps) from Svelte Society Vienna
- [Sirens: Form Actions](https://www.youtube.com/watch?v=2OISk5-EHek) - Kev joins the Sirens again to chat about Form actions in SvelteKit and create a new form for speaker submissions on SvelteSirens.dev
- [Introduction To 3D With Svelte (Threlte)](https://www.youtube.com/watch?v=89LYeHOncVk), [How To Use Global Styles In SvelteKit](https://www.youtube.com/watch?v=jHSwChkx3TQ) and [Progressive Form Enhancement With SvelteKit](https://www.youtube.com/watch?v=6pv70d7i-3Q) by Joy of Code
_To Read_
- [Building tic-tac-toe with Svelte](https://geoffrich.net/posts/tic-tac-toe/) by Geoff Rich
- [Speed up SvelteKit Pages With a Redis Cache](https://www.captaincodeman.com/speed-up-sveltekit-pages-with-a-redis-cache) by Captain Codeman
- [Understanding environment variables in SvelteKit](https://www.okupter.com/blog/environment-variables-in-sveltekit), [Form validation with SvelteKit and Zod](https://www.okupter.com/blog/sveltekit-form-validation-with-zod) and [Build a SvelteKit application with Docker](https://www.okupter.com/blog/build-a-sveltekit-application-with-docker) by Justin Ahinon
- [Why I failed to create the "Solid.js's store" for Svelte, and announcing svelte-store-tree v0.3.1](https://dev.to/igrep/why-i-failed-to-create-the-solidjss-store-for-svelte-and-announcing-svelte-store-tree-v031-1am2) by YAMAMOTO Yuji
- [Create an offline-first and installable PWA with SvelteKit and workbox-precaching](https://www.sarcevic.dev/offline-first-installable-pwa-sveltekit-workbox-precaching) by Antonio Sarcevic
**Libraries, Tools & Components**
- [Skeleton](https://www.skeleton.dev/) is a UI toolkit to build fast and reactive web interfaces using Svelte + Tailwind CSS
- [svelte-svg-spinners](https://github.com/luluvia/svelte-svg-spinners) is a collection of SVG Spinners components
- [Svelte Floating UI](https://github.com/fedorovvvv/svelte-floating-ui) enables floating UIs with actions - no wrapper components or component bindings required
- [at-html](https://github.com/micha-lmxt/at-html) lets you use `{@html }` tags with slots in Svelte apps
- [html-svelte-parser](https://github.com/PatrickG/html-svelte-parser) is a HTML to Svelte parser that works on both the server (Node.js) and the client (browser)
- [svelte-switcher](https://github.com/rohitpotato/svelte-switcher) is a fully customisable, touch-friendly, accessible and tiny toggle component
- [sveltkit-hook-html-minifier](https://www.npmjs.com/package/@svackages/sveltkit-hook-html-minifier) is a hook that wrapps `html-minifier`
- [sveltekit-hook-redirect](https://www.npmjs.com/package/@svackages/sveltekit-hook-redirect) is a hook that makes redirects easy
- [sveltekit-video-meet](https://github.com/harshmangalam/sveltekit-video-meet) is a video calling web app built with SvelteKit and SocketIO
- [svelte-colourpicker](https://www.npmjs.com/package/svelte-colourpicker) is a lightweight opinionated colour picker component for Svelte
- [Svelte-HeadlessUI](https://captaincodeman.github.io/svelte-headlessui/) is an unofficial implementation of Tailwind HeadlessUI for Svelte
- [svelte-lazyimage-cache](https://github.com/binsarjr/svelte-lazyimage-cache) is a Lazy Image component with IntersectionObserver and cache action
- [threlte v5.0](https://www.reddit.com/r/sveltejs/comments/ywit18/threlte_v50_is_here_a_completely_new_developer/) is a completely new developer experience that is faster, more powerful, and incredibly flexible
That's it for this month! Let us know if we missed anything on [Reddit](https://www.reddit.com/r/sveltejs/) or [Discord](https://discord.gg/svelte)
See ya next near 🎆

@ -0,0 +1,21 @@
---
title: Getting started
---
---
To try Svelte in an interactive online environment you can try [the REPL](https://svelte.dev/repl) or [StackBlitz](https://node.new/svelte).
To create a project locally we recommend using [SvelteKit](https://kit.svelte.dev/), the official application framework from the Svelte team:
```
npm create svelte@latest myapp
cd myapp
npm install
npm run dev
```
SvelteKit will handle calling [the Svelte compiler](https://www.npmjs.com/package/svelte) to convert your `.svelte` files into `.js` files that create the DOM and `.css` files that style it. It also provides all the other pieces you need to build a web application such as a development server, routing, and deployment. [SvelteKit](https://kit.svelte.dev/) utilizes [Vite](https://vitejs.dev/) to build your code and handle server-side rendering (SSR). There are [plugins for all the major web bundlers](https://sveltesociety.dev/tools#bundling) to handle Svelte compilation, which will output `.js` and `.css` that you can insert into your HTML, but most others won't handle SSR.
The Svelte team maintains a [VS Code extension](https://marketplace.visualstudio.com/items?itemName=svelte.svelte-vscode) and there are integrations with various other [editors](https://sveltesociety.dev/tools#editor-support) and tools as well.
If you're having trouble, get help on [Discord](https://svelte.dev/chat) or [StackOverflow](https://stackoverflow.com/questions/tagged/svelte).

@ -55,9 +55,7 @@ In development mode (see the [compiler options](/docs#compile-time-svelte-compil
---
If you export a `const`, `class` or `function`, it is readonly from outside the component. Function *expressions* are valid props, however.
Readonly props can be accessed as properties on the element, tied to the component using [`bind:this` syntax](/docs#template-syntax-component-directives-bind-this).
If you export a `const`, `class` or `function`, it is readonly from outside the component. Functions are valid prop values, however, as shown below.
```sv
<script>
@ -73,6 +71,8 @@ Readonly props can be accessed as properties on the element, tied to the compone
</script>
```
Readonly props can be accessed as properties on the element, tied to the component using [`bind:this` syntax](/docs#template-syntax-component-directives-bind-this).
---
You can use reserved words as prop names.
@ -125,15 +125,29 @@ Because Svelte's reactivity is based on assignments, using array methods like `.
</script>
```
---
Svelte's `<script>` blocks are run only when the component is created, so assignments within a `<script>` block are not automatically run again when a prop updates. If you'd like to track changes to a prop, see the next example in the following section.
```sv
<script>
export let person;
// this will only set `name` on component creation
// it will not update when `person` does
let { name } = person;
</script>
```
#### 3. `$:` marks a statement as reactive
---
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.
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 after other script code and before the component markup is rendered, whenever the values that they depend on have changed.
```sv
<script>
export let title;
export let person
// this will update `document.title` whenever
// the `title` prop changes
@ -143,6 +157,12 @@ Any top-level statement (i.e. not inside a block or a function) can be made reac
console.log(`multiple statements can be combined`);
console.log(`the current title is ${title}`);
}
// this will update `name` when 'person' changes
$: ({ name } = person);
// don't do this. it will run before the previous line
let name2 = name;
</script>
```
@ -172,6 +192,25 @@ Total: {total}
</button>
```
---
It is important to note that the reactive blocks are ordered via simple static analysis at compile time, and all the compiler looks at are the variables that are assigned to and used within the block itself, not in any functions called by them. This means that `yDependent` will not be updated when `x` is updated in the following example:
```sv
<script>
let x = 0;
let y = 0;
const setY = (value) => {
y = value;
}
$: yDependent = y;
$: setY(x);
</script>
```
Moving the line `$: yDependent = y` below `$: setY(x)` will cause `yDependent` to be updated when `x` is updated.
---
If a statement consists entirely of an assignment to an undeclared variable, Svelte will inject a `let` declaration on your behalf.

@ -124,6 +124,10 @@ An element or component can have multiple spread attributes, interspersed with r
> The `value` attribute of an `input` element or its children `option` elements must not be set with spread attributes when using `bind:group` or `bind:checked`. Svelte needs to be able to see the element's `value` directly in the markup in these cases so that it can link it to the bound variable.
> Sometimes, the attribute order matters as Svelte sets attributes sequentially in JavaScript. For example, `<input type="range" min="0" max="1" value={0.5} step="0.1"/>`, Svelte will attempt to set the value to `1` (rounding up from 0.5 as the step by default is 1), and then set the step to `0.1`. To fix this, change it to `<input type="range" min="0" max="1" step="0.1" value={0.5}/>`.
> Another example is `<img src="..." loading="lazy" />`. Svelte will set the img `src` before making the img element `loading="lazy"`, which is probably too late. Change this to `<img loading="lazy" src="...">` to make the image lazily loaded.
---
### Text expressions
@ -158,7 +162,7 @@ You can use HTML comments inside components.
---
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.
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.
```sv
<!-- svelte-ignore a11y-autofocus -->
@ -593,7 +597,7 @@ The simplest bindings reflect the value of a property, such as `input.value`.
---
If the name matches the value, you can use a shorthand.
If the name matches the value, you can use shorthand.
```sv
<!-- These are equivalent -->
@ -750,7 +754,7 @@ Videos additionally have readonly `videoWidth` and `videoHeight` bindings.
---
Block-level elements have 4 readonly bindings, measured using a technique similar to [this one](http://www.backalleycoder.com/2013/03/18/cross-browser-event-based-element-resize-detection/):
Block-level elements have 4 read-only bindings, measured using a technique similar to [this one](http://www.backalleycoder.com/2013/03/18/cross-browser-event-based-element-resize-detection/):
* `clientWidth`
* `clientHeight`
@ -874,6 +878,9 @@ The `style:` directive provides a shorthand for setting multiple styles on an el
<!-- Multiple styles can be included -->
<div style:color style:width="12rem" style:background-color={darkMode ? "black" : "white"}>...</div>
<!-- Styles can be marked as important -->
<div style:color|important="red">...</div>
```
---
@ -968,7 +975,7 @@ transition:fn|local={params}
```js
transition = (node: HTMLElement, params: any) => {
transition = (node: HTMLElement, params: any, options: { direction: 'in' | 'out' | 'both' }) => {
delay?: number,
duration?: number,
easing?: (t: number) => number,
@ -981,7 +988,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.
When a block is transitioning out, all elements inside the block, including those that do not have their own transitions, are kept in the DOM until every transition in the block has completed.
When a block is transitioning out, all elements inside the block, including those that do not have their own transitions, are kept in the DOM until every transition in the block has been completed.
The `transition:` directive indicates a *bidirectional* transition, which means it can be smoothly reversed while the transition is in progress.
@ -1006,7 +1013,7 @@ Like actions, transitions can have parameters.
```sv
{#if visible}
<div transition:fade="{{ duration: 2000 }}">
flies in, fades out over two seconds
fades in and out over two seconds
</div>
{/if}
```
@ -1088,6 +1095,11 @@ 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 functions also receive a third argument, `options`, which contains information about the transition.
Available values in the `options` object are:
* `direction` - one of `in`, `out`, or `bidirectional` depending on the type of transition
##### Transition events
@ -1241,7 +1253,7 @@ As with actions and transitions, animations can have parameters.
---
Animations can use custom functions that provide the `node`, an `animation` object and any `parameters` 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.
Animations can use custom functions that provide the `node`, an `animation` object and any `parameters` 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, and 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.
@ -1374,7 +1386,23 @@ Desugars to this:
---
Svelte's CSS Variables support allows for easily themable components:
For SVG namespace, the example above desugars into using `<g>` instead:
```sv
<g style="--rail-color: black; --track-color: rgb(0, 0, 255)">
<Slider
bind:value
min={0}
max={100}
/>
</g>
```
**Note**: Since this is an extra `<g>`, beware that your CSS structure might accidentally target this. Be mindful of this added wrapper element when using this feature.
---
Svelte's CSS Variables support allows for easily themeable components:
```sv
<!-- Slider.svelte -->
@ -1638,7 +1666,7 @@ If `this` is falsy, no component is rendered.
The `<svelte:element>` element lets you render an element of a dynamically specified type. This is useful for example when displaying rich text content from a CMS. Any properties and event listeners present will be applied to the element.
The only supported binding is `bind:this`, since the element type specific bindings that Svelte does at build time (e.g. `bind:value` for input elements) does not work with a dynamic tag type.
The only supported binding is `bind:this`, since the element type specific bindings that Svelte does at build time (e.g. `bind:value` for input elements) do not work with a dynamic tag type.
If `this` has a nullish value, the element and its children will not be rendered.

@ -73,7 +73,7 @@ The following options can be passed to the compiler. None are required:
| `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 for the components actually rendered. If `false`, the CSS will be returned in the `css` field of the compilation result. Most Svelte bundler plugins will set this to `false` and use the CSS that is statically generated for better performance, as it will result in smaller JavaScript bundles and the output can be served as cacheable `.css` files.
| `css` | `'injected'` | If `'injected'` (formerly `true`), styles will be included in the JavaScript class and injected at runtime for the components actually rendered. If `'external'` (formerly `false`), the CSS will be returned in the `css` field of the compilation result. Most Svelte bundler plugins will set this to `'external'` and use the CSS that is statically generated for better performance, as it will result in smaller JavaScript bundles and the output can be served as cacheable `.css` files. If `'none'`, styles are completely avoided and no CSS output is generated.
| `cssHash` | See right | A function that takes a `{ hash, css, name, filename }` argument and returns the string that is used as a classname for scoped CSS. It defaults to returning `svelte-${hash(css)}`
| `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.

@ -41,26 +41,28 @@ Enforce that `autofocus` is not used on elements. Autofocusing elements can caus
---
### `a11y-distracting-elements`
### `a11y-click-events-have-key-events`
Enforces that no distracting elements are used. Elements that can be visually distracting can cause accessibility issues with visually impaired users. Such elements are most likely deprecated, and should be avoided.
Enforce `on:click` is accompanied by at least one of the following: `onKeyUp`, `onKeyDown`, `onKeyPress`. Coding for the keyboard is important for users with physical disabilities who cannot use a mouse, AT compatibility, and screenreader users.
The following elements are visually distracting: `<marquee>` and `<blink>`.
This does not apply for interactive or hidden elements.
```sv
<!-- A11y: Avoid <marquee> elements -->
<marquee />
<!-- A11y: visible, non-interactive elements with an on:click event must be accompanied by an on:keydown, on:keyup, or on:keypress event. -->
<div on:click={() => {}} />
```
---
### `role-has-required-aria-props`
### `a11y-distracting-elements`
Elements with ARIA roles must have all required attributes for that role.
Enforces that no distracting elements are used. Elements that can be visually distracting can cause accessibility issues with visually impaired users. Such elements are most likely deprecated, and should be avoided.
The following elements are visually distracting: `<marquee>` and `<blink>`.
```sv
<!-- A11y: A11y: Elements with the ARIA role "checkbox" must have the following attributes defined: "aria-checked" -->
<span role="checkbox" aria-labelledby="foo" tabindex="0"></span>
<!-- A11y: Avoid <marquee> elements -->
<marquee />
```
---
@ -261,6 +263,17 @@ Some HTML elements have default ARIA roles. Giving these elements an ARIA role t
---
### `a11y-no-noninteractive-tabindex`
Tab key navigation should be limited to elements on the page that can be interacted with.
```sv
<!-- A11y: noninteractive element cannot have positive tabIndex value -->
<div tabindex='0' />
```
---
### `a11y-positive-tabindex`
Avoid positive `tabindex` property values. This will move elements out of the expected tab order, creating a confusing experience for keyboard users.
@ -272,6 +285,17 @@ Avoid positive `tabindex` property values. This will move elements out of the ex
---
### `a11y-role-has-required-aria-props`
Elements with ARIA roles must have all required attributes for that role.
```sv
<!-- A11y: A11y: Elements with the ARIA role "checkbox" must have the following attributes defined: "aria-checked" -->
<span role="checkbox" aria-labelledby="foo" tabindex="0"></span>
```
---
### `a11y-structure`
Enforce that certain DOM elements have the correct structure.

@ -11,7 +11,7 @@
<ul>
{#each cats as { id, name }, i}
<li>
<a target="_blank" href="https://www.youtube.com/watch?v={id}">
<a target="_blank" rel="noreferrer" href="https://www.youtube.com/watch?v={id}">
{i + 1}: {name}
</a>
</li>

@ -10,7 +10,7 @@
{#if yes}
<p>Thank you. We will bombard your inbox and sell your personal details.</p>
{:else}
<p>You must opt in to continue. If you're not paying, you're the product.</p>
<p>You must opt-in to continue. If you're not paying, you're the product.</p>
{/if}
<button disabled={!yes}>

@ -56,8 +56,8 @@
>
<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>
<a target="_blank" rel="noreferrer" href="https://www.flickr.com/photos/{d.path}">via Flickr</a> &ndash;
<a target="_blank" rel="noreferrer" href={d.license.url}>{d.license.name}</a>
</p>
</div>
{/await}

@ -43,4 +43,8 @@
background-color: #ff3e00;
color: white;
}
</style>
p {
pointer-events: none;
}
</style>

@ -13,7 +13,7 @@
<article>
<span>{i + offset + 1}</span>
<h2><a target="_blank" href={url}>{item.title}</a></h2>
<h2><a target="_blank" rel="noreferrer" href={url}>{item.title}</a></h2>
<p class="meta"><a href="#/item/{item.id}">{comment_text()}</a> by {item.user} {item.time_ago}</p>
</article>
@ -37,4 +37,4 @@
a {
color: #333;
}
</style>
</style>

@ -4,9 +4,10 @@ question: How do I test Svelte apps?
We recommend trying to separate your view logic from your business logic. Data transformation or cross component state management is best kept outside of Svelte components. You can test those parts like you would test any JavaScript functionality that way. When it comes to testing the components, it is best to test the logic of the component and remember that the Svelte library has its own tests and you do not need to test implementation details provided by Svelte.
There are a few approaches that people take when testing, but it generally involves compiling the component and mounting it to something and then performing the tests. You essentially need to create a bundle for each component you're testing (since svelte is a compiler and not a normal library) and then mount them. You can mount to a JSDOM instance. Or you can use a real browser powered by a library like Playwright, Puppeteer, or Cypress.
There are a few approaches that people take when testing, but it generally involves compiling the component and mounting it to something and then performing the tests. You essentially need to create a bundle for each component you're testing (since svelte is a compiler and not a normal library) and then mount them. You can mount to a JSDOM instance. Or you can use a real browser powered by a library like Playwright, Puppeteer, WebdriverIO or Cypress.
Some resources for getting started with unit testing:
- [Svelte Testing Library](https://testing-library.com/docs/svelte-testing-library/example/)
- [Example using vitest](https://github.com/vitest-dev/vitest/tree/main/examples/svelte)
- [Example using uvu test runner with JSDOM](https://github.com/lukeed/uvu/tree/master/examples/svelte)
- [Component testing in real browser](https://webdriver.io/docs/component-testing/svelte)

@ -2,7 +2,7 @@
question: Is there a router?
---
The official routing library is [SvelteKit](https://kit.svelte.dev/), which is currently in beta. SvelteKit provides a filesystem router, server-side rendering (SSR), and hot module reloading (HMR) in one easy-to-use package. It shares similarities with Next.js for React.
The official routing library is [SvelteKit](https://kit.svelte.dev/). SvelteKit provides a filesystem router, server-side rendering (SSR), and hot module reloading (HMR) in one easy-to-use package. It shares similarities with Next.js for React.
However, you can use any router lib you want. A lot of people use [page.js](https://github.com/visionmedia/page.js). There's also [navaid](https://github.com/lukeed/navaid), which is very similar. And [universal-router](https://github.com/kriasoft/universal-router), which is isomorphic with child routes, but without built-in history support.

@ -4,7 +4,7 @@ title: Basics
Welcome to the Svelte tutorial. This will teach you everything you need to know to build fast, small web applications easily.
You can also consult the [API docs](/docs) and the [examples](/examples), or — if you're impatient to start hacking on your machine locally — the [60-second quickstart](/blog/the-easiest-way-to-get-started).
You can also consult the [API docs](/docs) and the [examples](/examples), or — if you're impatient to start hacking on your machine locally — the [60-second quickstart](/docs#getting-started).
## What is Svelte?
@ -24,7 +24,7 @@ You'll need to have basic familiarity with HTML, CSS and JavaScript to understan
As you progress through the tutorial, you'll be presented with mini exercises designed to illustrate new features. Later chapters build on the knowledge gained in earlier ones, so it's recommended that you go from start to finish. If necessary, you can navigate via the dropdown above (click 'Introduction / Basics').
Each tutorial chapter will have a 'Show me' button that you can click if you get stuck following the instructions. Try not to rely on it too much; you will learn faster by figuring out where to put each suggested code block and manually typing it in to the editor.
Each tutorial chapter will have a 'Show me' button that you can click if you get stuck following the instructions. Try not to rely on it too much; you will learn faster by figuring out where to put each suggested code block and manually typing it into the editor.
## Understanding components

@ -10,7 +10,7 @@
<ul>
<!-- open each block -->
<li><a target="_blank" href="https://www.youtube.com/watch?v={cat.id}">
<li><a target="_blank" href="https://www.youtube.com/watch?v={cat.id}" rel="noreferrer">
{cat.name}
</a></li>
<!-- close each block -->

@ -10,7 +10,7 @@
<ul>
{#each cats as { id, name }, i}
<li><a target="_blank" href="https://www.youtube.com/watch?v={id}">
<li><a target="_blank" href="https://www.youtube.com/watch?v={id}" rel="noreferrer">
{i + 1}: {name}
</a></li>
{/each}

@ -7,7 +7,7 @@ If you need to loop over lists of data, use an `each` block:
```html
<ul>
{#each cats as cat}
<li><a target="_blank" href="https://www.youtube.com/watch?v={cat.id}">
<li><a target="_blank" href="https://www.youtube.com/watch?v={cat.id}" rel="noreferrer">
{cat.name}
</a></li>
{/each}
@ -20,10 +20,10 @@ You can get the current *index* as a second argument, like so:
```html
{#each cats as cat, i}
<li><a target="_blank" href="https://www.youtube.com/watch?v={cat.id}">
<li><a target="_blank" href="https://www.youtube.com/watch?v={cat.id}" rel="noreferrer">
{i + 1}: {cat.name}
</a></li>
{/each}
```
If you prefer, you can use destructuring — `each cats as { id, name }` — and replace `cat.id` and `cat.name` with `id` and `name`.
If you prefer, you can use destructuring — `each cats as { id, name }` — and replace `cat.id` and `cat.name` with `id` and `name`.

@ -10,7 +10,7 @@
{#if yes}
<p>Thank you. We will bombard your inbox and sell your personal details.</p>
{:else}
<p>You must opt in to continue. If you're not paying, you're the product.</p>
<p>You must opt-in to continue. If you're not paying, you're the product.</p>
{/if}
<button disabled={!yes}>

@ -10,7 +10,7 @@
{#if yes}
<p>Thank you. We will bombard your inbox and sell your personal details.</p>
{:else}
<p>You must opt in to continue. If you're not paying, you're the product.</p>
<p>You must opt-in to continue. If you're not paying, you're the product.</p>
{/if}
<button disabled={!yes}>

@ -33,6 +33,7 @@
svg {
width: 100%;
height: 100%;
margin: -8px;
}
circle {
fill: #ff3e00;

@ -10,7 +10,7 @@
<ul>
<li>
<Project
title="Add Typescript support"
title="Add TypeScript support"
tasksCompleted={25}
totalTasks={57}
>

@ -10,7 +10,7 @@
<ul>
<li>
<Project
title="Add Typescript support"
title="Add TypeScript support"
tasksCompleted={25}
totalTasks={57}
>

@ -10,7 +10,7 @@
}
</script>
<span class:expanded on:click={toggle}>{name}</span>
<button class:expanded on:click={toggle}>{name}</button>
{#if expanded}
<ul>
@ -27,12 +27,14 @@
{/if}
<style>
span {
button {
padding: 0 0 0 1.5em;
background: url(/tutorial/icons/folder.svg) 0 0.1em no-repeat;
background-size: 1em 1em;
font-weight: bold;
cursor: pointer;
border: none;
margin: 0;
}
.expanded {

@ -10,7 +10,7 @@
}
</script>
<span class:expanded on:click={toggle}>{name}</span>
<button class:expanded on:click={toggle}>{name}</button>
{#if expanded}
<ul>
@ -27,12 +27,14 @@
{/if}
<style>
span {
button {
padding: 0 0 0 1.5em;
background: url(/tutorial/icons/folder.svg) 0 0.1em no-repeat;
background-size: 1em 1em;
font-weight: bold;
cursor: pointer;
border: none;
margin: 0;
}
.expanded {

@ -1,10 +1,10 @@
<script>
let key;
let keyCode;
let code;
function handleKeydown(event) {
key = event.key;
keyCode = event.keyCode;
code = event.code;
}
</script>
@ -13,7 +13,7 @@
<div style="text-align: center">
{#if key}
<kbd>{key === ' ' ? 'Space' : key}</kbd>
<p>{keyCode}</p>
<p>{code}</p>
{:else}
<p>Focus this window and press any key</p>
{/if}
@ -39,4 +39,4 @@
border-bottom: 5px solid rgba(0, 0, 0, 0.2);
color: #555;
}
</style>
</style>

@ -1,10 +1,10 @@
<script>
let key;
let keyCode;
let code;
function handleKeydown(event) {
key = event.key;
keyCode = event.keyCode;
code = event.code;
}
</script>
@ -13,7 +13,7 @@
<div style="text-align: center">
{#if key}
<kbd>{key === ' ' ? 'Space' : key}</kbd>
<p>{keyCode}</p>
<p>{code}</p>
{:else}
<p>Focus this window and press any key</p>
{/if}

@ -4,7 +4,7 @@ title: Congratulations!
You've now finished the Svelte tutorial and are ready to start building apps. You can refer back to individual chapters at any time (click the title above to reveal a dropdown) or continue your learning via the [API reference](/docs), [Examples](/examples) and [Blog](/blog). If you're a Twitter user, you can get updates via [@sveltejs](https://twitter.com/sveltejs).
To get set up in your local development environment, check out [the quickstart guide](/blog/the-easiest-way-to-get-started).
To get set up in your local development environment, check out [the quickstart guide](/docs#getting-started).
If you're looking for a more expansive framework that includes routing, server-side rendering and everything else, take a look at [SvelteKit](https://kit.svelte.dev).

@ -1,7 +1,8 @@
import { walk } from 'estree-walker';
import { getLocator } from 'locate-character';
import Stats from '../Stats';
import { globals, reserved, is_valid } from '../utils/names';
import { reserved, is_valid } from '../utils/names';
import globals from '../utils/globals';
import { namespaces, valid_namespaces } from '../utils/namespaces';
import create_module from './create_module';
import {
@ -46,6 +47,10 @@ interface ComponentOptions {
preserveWhitespace?: boolean;
}
const regex_leading_directory_separator = /^[/\\]/;
const regex_starts_with_term_export = /^Export/;
const regex_contains_term_function = /Function/;
export default class Component {
stats: Stats;
warnings: Warning[];
@ -135,7 +140,7 @@ export default class Component {
(typeof process !== 'undefined'
? compile_options.filename
.replace(process.cwd(), '')
.replace(/^[/\\]/, '')
.replace(regex_leading_directory_separator, '')
: compile_options.filename);
this.locate = getLocator(this.source, { offsetLine: 1 });
@ -637,7 +642,7 @@ export default class Component {
body.splice(i, 1);
}
if (/^Export/.test(node.type)) {
if (regex_starts_with_term_export.test(node.type)) {
const replacement = this.extract_exports(node, true);
if (replacement) {
body[i] = replacement;
@ -787,6 +792,42 @@ export default class Component {
scope = map.get(node);
}
let deep = false;
let names: string[] | undefined;
if (node.type === 'AssignmentExpression') {
deep = node.left.type === 'MemberExpression';
names = deep
? [get_object(node.left).name]
: extract_names(node.left);
} else if (node.type === 'UpdateExpression') {
deep = node.argument.type === 'MemberExpression';
const { name } = get_object(node.argument);
names = [name];
}
if (names) {
names.forEach(name => {
let current_scope = scope;
let declaration;
while (current_scope) {
if (current_scope.declarations.has(name)) {
declaration = current_scope.declarations.get(name);
break;
}
current_scope = current_scope.parent;
}
if (declaration && declaration.kind === 'const' && !deep) {
component.error(node as any, {
code: 'assignment-to-const',
message: 'You are assigning to a const'
});
}
});
}
if (node.type === 'ImportDeclaration') {
component.extract_imports(node);
// TODO: to use actual remove
@ -794,7 +835,7 @@ export default class Component {
return this.skip();
}
if (/^Export/.test(node.type)) {
if (regex_starts_with_term_export.test(node.type)) {
const replacement = component.extract_exports(node);
if (replacement) {
this.replace(replacement);
@ -917,7 +958,7 @@ export default class Component {
}
if (name[1] !== '$' && scope.has(name.slice(1)) && scope.find_owner(name.slice(1)) !== this.instance_scope) {
if (!((/Function/.test(parent.type) && prop === 'params') || (parent.type === 'VariableDeclarator' && prop === 'id'))) {
if (!((regex_contains_term_function.test(parent.type) && prop === 'params') || (parent.type === 'VariableDeclarator' && prop === 'id'))) {
return this.error(node as any, compiler_errors.contextual_store);
}
}
@ -964,7 +1005,7 @@ export default class Component {
walk(this.ast.instance.content, {
enter(node: Node) {
if (/Function/.test(node.type)) {
if (regex_contains_term_function.test(node.type)) {
return this.skip();
}
@ -1088,7 +1129,7 @@ export default class Component {
this.replace(b`
${node.declarations.length ? node : null}
${ props.length > 0 && b`let { ${ props } } = $$props;`}
${ props.length > 0 && b`let { ${props} } = $$props;`}
${inserts}
` as any);
return this.skip();
@ -1459,6 +1500,8 @@ export default class Component {
}
}
const regex_valid_tag_name = /^[a-zA-Z][a-zA-Z0-9]*-[a-zA-Z0-9-]+$/;
function process_component_options(component: Component, nodes) {
const component_options: ComponentOptions = {
immutable: component.compile_options.immutable || false,
@ -1472,7 +1515,7 @@ function process_component_options(component: Component, nodes) {
const node = nodes.find(node => node.name === 'svelte:options');
function get_value(attribute, {code, message}) {
function get_value(attribute, { code, message }) {
const { value } = attribute;
const chunk = value[0];
@ -1504,7 +1547,7 @@ function process_component_options(component: Component, nodes) {
return component.error(attribute, compiler_errors.invalid_tag_attribute);
}
if (tag && !/^[a-zA-Z][a-zA-Z0-9]*-[a-zA-Z0-9-]+$/.test(tag)) {
if (tag && !regex_valid_tag_name.test(tag)) {
return component.error(attribute, compiler_errors.invalid_tag_property);
}

@ -234,6 +234,10 @@ export default {
code: 'css-invalid-global-selector',
message: ':global(...) must contain a single selector'
},
css_invalid_selector: (selector: string) => ({
code: 'css-invalid-selector',
message: `Invalid selector "${selector}"`
}),
duplicate_animation: {
code: 'duplicate-animation',
message: "An element can only have one 'animate' directive"
@ -277,5 +281,9 @@ export default {
invalid_component_style_directive: {
code: 'invalid-component-style-directive',
message: 'Style directives cannot be used on components'
}
},
invalid_style_directive_modifier: (valid: string) => ({
code: 'invalid-style-directive-modifier',
message: `Valid modifiers for style directives are: ${valid}`
})
};

@ -175,10 +175,18 @@ export default {
code: 'a11y-mouse-events-have-key-events',
message: `A11y: on:${event} must be accompanied by on:${accompanied_by}`
}),
a11y_click_events_have_key_events: () => ({
code: 'a11y-click-events-have-key-events',
message: 'A11y: visible, non-interactive elements with an on:click event must be accompanied by an on:keydown, on:keyup, or on:keypress event.'
}),
a11y_missing_content: (name: string) => ({
code: 'a11y-missing-content',
message: `A11y: <${name}> element should have child content`
}),
a11y_no_noninteractive_tabindex: {
code: 'a11y-no-noninteractive-tabindex',
message: 'A11y: noninteractive element cannot have positive tabIndex value'
},
redundant_event_modifier_for_touch: {
code: 'redundant-event-modifier',
message: 'Touch event handlers that don\'t use the \'event\' object are passive by default'
@ -186,5 +194,9 @@ export default {
redundant_event_modifier_passive: {
code: 'redundant-event-modifier',
message: 'The passive modifier only works with wheel and touch events'
}
},
invalid_rest_eachblock_binding: (rest_element_name: string) => ({
code: 'invalid-rest-eachblock-binding',
message: `...${rest_element_name} operator will create a new object and binding propagation with original object will not work`
})
};

@ -9,6 +9,7 @@ import EachBlock from '../nodes/EachBlock';
import IfBlock from '../nodes/IfBlock';
import AwaitBlock from '../nodes/AwaitBlock';
import compiler_errors from '../compiler_errors';
import { regex_starts_with_whitespace, regex_ends_with_whitespace } from '../../utils/patterns';
enum BlockAppliesToNode {
NotPossible,
@ -25,6 +26,8 @@ const whitelist_attribute_selector = new Map([
['dialog', new Set(['open'])]
]);
const regex_is_single_css_selector = /[^\\],(?!([^([]+[^\\]|[^([\\])[)\]])/;
export default class Selector {
node: CssNode;
stylesheet: Stylesheet;
@ -145,6 +148,7 @@ export default class Selector {
}
this.validate_global_with_multiple_selectors(component);
this.validate_invalid_combinator_without_selector(component);
}
validate_global_with_multiple_selectors(component: Component) {
@ -156,13 +160,24 @@ export default class Selector {
for (const block of this.blocks) {
for (const selector of block.selectors) {
if (selector.type === 'PseudoClassSelector' && selector.name === 'global') {
if (/[^\\],(?!([^([]+[^\\]|[^([\\])[)\]])/.test(selector.children[0].value)) {
if (regex_is_single_css_selector.test(selector.children[0].value)) {
component.error(selector, compiler_errors.css_invalid_global_selector);
}
}
}
}
}
validate_invalid_combinator_without_selector(component: Component) {
for (let i = 0; i < this.blocks.length; i++) {
const block = this.blocks[i];
if (block.combinator && block.selectors.length === 0) {
component.error(this.node, compiler_errors.css_invalid_selector(component.source.slice(this.node.start, this.node.end)));
}
if (!block.combinator && block.selectors.length === 0) {
component.error(this.node, compiler_errors.css_invalid_selector(component.source.slice(this.node.start, this.node.end)));
}
}
}
get_amount_class_specificity_increased() {
let count = 0;
@ -197,7 +212,7 @@ function apply_selector(blocks: Block[], node: Element, to_encapsulate: Array<{
}
if (block.combinator) {
if (block.combinator.type === 'WhiteSpace') {
if (block.combinator.type === 'Combinator' && block.combinator.name === ' ') {
for (const ancestor_block of blocks) {
if (ancestor_block.global) {
continue;
@ -269,12 +284,14 @@ function apply_selector(blocks: Block[], node: Element, to_encapsulate: Array<{
return true;
}
const regex_backslash_and_following_character = /\\(.)/g;
function block_might_apply_to_node(block: Block, node: Element): BlockAppliesToNode {
let i = block.selectors.length;
while (i--) {
const selector = block.selectors[i];
const name = typeof selector.name === 'string' && selector.name.replace(/\\(.)/g, '$1');
const name = typeof selector.name === 'string' && selector.name.replace(regex_backslash_and_following_character, '$1');
if (selector.type === 'PseudoClassSelector' && (name === 'host' || name === 'root')) {
return BlockAppliesToNode.NotPossible;
@ -299,7 +316,7 @@ function block_might_apply_to_node(block: Block, node: Element): BlockAppliesToN
return BlockAppliesToNode.NotPossible;
}
} else if (selector.type === 'TypeSelector') {
if (node.name.toLowerCase() !== name.toLowerCase() && name !== '*') return BlockAppliesToNode.NotPossible;
if (node.name.toLowerCase() !== name.toLowerCase() && name !== '*' && !node.is_dynamic_element) return BlockAppliesToNode.NotPossible;
} else {
return BlockAppliesToNode.UnknownSelectorType;
}
@ -359,7 +376,7 @@ function attribute_matches(node: CssNode, name: string, expected_value: string,
const start_with_space = [];
const remaining = [];
current_possible_values.forEach((current_possible_value: string) => {
if (/^\s/.test(current_possible_value)) {
if (regex_starts_with_whitespace.test(current_possible_value)) {
start_with_space.push(current_possible_value);
} else {
remaining.push(current_possible_value);
@ -380,7 +397,7 @@ function attribute_matches(node: CssNode, name: string, expected_value: string,
prev_values = combined;
start_with_space.forEach((value: string) => {
if (/\s$/.test(value)) {
if (regex_ends_with_whitespace.test(value)) {
possible_values.add(value);
} else {
prev_values.push(value);
@ -394,7 +411,7 @@ function attribute_matches(node: CssNode, name: string, expected_value: string,
}
current_possible_values.forEach((current_possible_value: string) => {
if (/\s$/.test(current_possible_value)) {
if (regex_ends_with_whitespace.test(current_possible_value)) {
possible_values.add(current_possible_value);
} else {
prev_values.push(current_possible_value);

@ -9,9 +9,12 @@ import hash from '../utils/hash';
import compiler_warnings from '../compiler_warnings';
import { extract_ignores_above_position } from '../../utils/extract_svelte_ignore';
import { push_array } from '../../utils/push_array';
import { regex_only_whitespaces, regex_whitespace } from '../../utils/patterns';
const regex_css_browser_prefix = /^-((webkit)|(moz)|(o)|(ms))-/;
function remove_css_prefix(name: string): string {
return name.replace(/^-((webkit)|(moz)|(o)|(ms))-/, '');
return name.replace(regex_css_browser_prefix, '');
}
const is_keyframes_node = (node: CssNode) =>
@ -147,10 +150,10 @@ class Declaration {
// Don't minify whitespace in custom properties, since some browsers (Chromium < 99)
// treat --foo: ; and --foo:; differently
if (first.type === 'Raw' && /^\s+$/.test(first.value)) return;
if (first.type === 'Raw' && regex_only_whitespaces.test(first.value)) return;
let start = first.start;
while (/\s/.test(code.original[start])) start += 1;
while (regex_whitespace.test(code.original[start])) start += 1;
if (start - c > 1) {
code.overwrite(c, start, ':');

@ -35,8 +35,19 @@ const valid_options = [
'cssHash'
];
const valid_css_values = [
true,
false,
'injected',
'external',
'none'
];
const regex_valid_identifier = /^[a-zA-Z_$][a-zA-Z_$0-9]*$/;
const regex_starts_with_lowercase_character = /^[a-z]/;
function validate_options(options: CompileOptions, warnings: Warning[]) {
const { name, filename, loopGuardTimeout, dev, namespace } = options;
const { name, filename, loopGuardTimeout, dev, namespace, css } = options;
Object.keys(options).forEach(key => {
if (!valid_options.includes(key)) {
@ -48,11 +59,11 @@ function validate_options(options: CompileOptions, warnings: Warning[]) {
}
});
if (name && !/^[a-zA-Z_$][a-zA-Z_$0-9]*$/.test(name)) {
if (name && !regex_valid_identifier.test(name)) {
throw new Error(`options.name must be a valid identifier (got '${name}')`);
}
if (name && /^[a-z]/.test(name)) {
if (name && regex_starts_with_lowercase_character.test(name)) {
const message = 'options.name should be capitalised';
warnings.push({
code: 'options-lowercase-name',
@ -72,6 +83,23 @@ function validate_options(options: CompileOptions, warnings: Warning[]) {
});
}
if (valid_css_values.indexOf(css) === -1) {
throw new Error(`options.css must be true, false, 'injected', 'external', or 'none' (got '${css}')`);
}
if (css === true || css === false) {
options.css = css === true ? 'injected' : 'external';
// possibly show this warning once we decided how Svelte 4 looks like
// const message = `options.css as a boolean is deprecated. Use '${options.css}' instead of ${css}.`;
// warnings.push({
// code: 'options-css-boolean-deprecated',
// message,
// filename,
// toString: () => message
// });
// }
}
if (namespace && valid_namespaces.indexOf(namespace) === -1) {
const match = fuzzymatch(namespace, valid_namespaces);
if (match) {
@ -83,7 +111,7 @@ function validate_options(options: CompileOptions, warnings: Warning[]) {
}
export default function compile(source: string, options: CompileOptions = {}) {
options = Object.assign({ generate: 'dom', dev: false, enableSourcemap: true }, options);
options = Object.assign({ generate: 'dom', dev: false, enableSourcemap: true, css: 'injected' }, options);
const stats = new Stats();
const warnings = [];

@ -23,6 +23,8 @@ export default class AwaitBlock extends Node {
then: ThenBlock;
catch: CatchBlock;
context_rest_properties: Map<string, ESTreeNode> = new Map();
constructor(component: Component, parent: Node, scope: TemplateScope, info: TemplateNode) {
super(component, parent, scope, info);
@ -33,12 +35,12 @@ export default class AwaitBlock extends Node {
if (this.then_node) {
this.then_contexts = [];
unpack_destructuring({ contexts: this.then_contexts, node: info.value, scope, component });
unpack_destructuring({ contexts: this.then_contexts, node: info.value, scope, component, context_rest_properties: this.context_rest_properties });
}
if (this.catch_node) {
this.catch_contexts = [];
unpack_destructuring({ contexts: this.catch_contexts, node: info.error, scope, component });
unpack_destructuring({ contexts: this.catch_contexts, node: info.error, scope, component, context_rest_properties: this.context_rest_properties });
}
this.pending = new PendingBlock(component, this, scope, info.pending);

@ -3,7 +3,7 @@ import get_object from '../utils/get_object';
import Expression from './shared/Expression';
import Component from '../Component';
import TemplateScope from './shared/TemplateScope';
import {dimensions} from '../../utils/patterns';
import { regex_dimensions } from '../../utils/patterns';
import { Node as ESTreeNode } from 'estree';
import { TemplateNode } from '../../interfaces';
import Element from './Element';
@ -11,6 +11,7 @@ import InlineComponent from './InlineComponent';
import Window from './Window';
import { clone } from '../../utils/clone';
import compiler_errors from '../compiler_errors';
import compiler_warnings from '../compiler_warnings';
// TODO this should live in a specific binding
const read_only_media_attributes = new Set([
@ -47,6 +48,7 @@ export default class Binding extends Node {
const { name } = get_object(this.expression.node);
this.is_contextual = Array.from(this.expression.references).some(name => scope.names.has(name));
if (this.is_contextual) this.validate_binding_rest_properties(scope);
// make sure we track this as a mutable ref
if (scope.is_let(name)) {
@ -86,7 +88,7 @@ export default class Binding extends Node {
const type = parent.get_static_attribute_value('type');
this.is_readonly =
dimensions.test(this.name) ||
regex_dimensions.test(this.name) ||
(isElement(parent) &&
((parent.is_media_node() && read_only_media_attributes.has(this.name)) ||
(parent.name === 'input' && type === 'file')) /* TODO others? */);
@ -95,6 +97,18 @@ export default class Binding extends Node {
is_readonly_media_attribute() {
return read_only_media_attributes.has(this.name);
}
validate_binding_rest_properties(scope: TemplateScope) {
this.expression.references.forEach(name => {
const each_block = scope.get_owner(name);
if (each_block && each_block.type === 'EachBlock') {
const rest_node = each_block.context_rest_properties.get(name);
if (rest_node) {
this.component.warn(rest_node as any, compiler_warnings.invalid_rest_eachblock_binding(name));
}
}
});
}
}
function isElement(node: Node): node is Element {

@ -10,6 +10,7 @@ import { extract_identifiers } from 'periscopic';
import is_reference, { NodeWithPropertyDefinition } from 'is-reference';
import get_object from '../utils/get_object';
import compiler_errors from '../compiler_errors';
import { Node as ESTreeNode } from 'estree';
const allowed_parents = new Set(['EachBlock', 'CatchBlock', 'ThenBlock', 'InlineComponent', 'SlotTemplate', 'IfBlock', 'ElseBlock']);
@ -19,6 +20,7 @@ export default class ConstTag extends Node {
contexts: Context[] = [];
node: ConstTagType;
scope: TemplateScope;
context_rest_properties: Map<string, ESTreeNode> = new Map();
assignees: Set<string> = new Set();
dependencies: Set<string> = new Set();
@ -58,7 +60,8 @@ export default class ConstTag extends Node {
contexts: this.contexts,
node: this.node.expression.left,
scope: this.scope,
component: this.component
component: this.component,
context_rest_properties: this.context_rest_properties
});
this.expression = new Expression(this.component, this, this.scope, this.node.expression.right);
this.contexts.forEach(context => {

@ -28,7 +28,7 @@ export default class EachBlock extends AbstractBlock {
has_animation: boolean;
has_binding = false;
has_index_binding = false;
context_rest_properties: Map<string, Node>;
else?: ElseBlock;
constructor(component: Component, parent: Node, scope: TemplateScope, info: TemplateNode) {
@ -40,9 +40,9 @@ export default class EachBlock extends AbstractBlock {
this.index = info.index;
this.scope = scope.child();
this.context_rest_properties = new Map();
this.contexts = [];
unpack_destructuring({ contexts: this.contexts, node: info.context, scope, component });
unpack_destructuring({ contexts: this.contexts, node: info.context, scope, component, context_rest_properties: this.context_rest_properties });
this.contexts.forEach(context => {
this.scope.add(context.key.name, this.expression.dependencies, this);

@ -1,4 +1,4 @@
import { is_void } from '../../../shared/utils/names';
import { is_html, is_svg, is_void } from '../../../shared/utils/names';
import Node from './shared/Node';
import Attribute from './Attribute';
import Binding from './Binding';
@ -11,7 +11,7 @@ import StyleDirective from './StyleDirective';
import Text from './Text';
import { namespaces } from '../../utils/namespaces';
import map_children from './shared/map_children';
import { dimensions, start_newline } from '../../utils/patterns';
import { regex_dimensions, regex_starts_with_newline, regex_non_whitespace_character } from '../../utils/patterns';
import fuzzymatch from '../../utils/fuzzymatch';
import list from '../../utils/list';
import Let from './Let';
@ -24,9 +24,7 @@ import { Literal } from 'estree';
import compiler_warnings from '../compiler_warnings';
import compiler_errors from '../compiler_errors';
import { ARIARoleDefintionKey, roles, aria, ARIAPropertyDefinition, ARIAProperty } from 'aria-query';
import { is_interactive_element, is_non_interactive_roles, is_presentation_role } from '../utils/a11y';
const svg = /^(?:altGlyph|altGlyphDef|altGlyphItem|animate|animateColor|animateMotion|animateTransform|circle|clipPath|color-profile|cursor|defs|desc|discard|ellipse|feBlend|feColorMatrix|feComponentTransfer|feComposite|feConvolveMatrix|feDiffuseLighting|feDisplacementMap|feDistantLight|feDropShadow|feFlood|feFuncA|feFuncB|feFuncG|feFuncR|feGaussianBlur|feImage|feMerge|feMergeNode|feMorphology|feOffset|fePointLight|feSpecularLighting|feSpotLight|feTile|feTurbulence|filter|font|font-face|font-face-format|font-face-name|font-face-src|font-face-uri|foreignObject|g|glyph|glyphRef|hatch|hatchpath|hkern|image|line|linearGradient|marker|mask|mesh|meshgradient|meshpatch|meshrow|metadata|missing-glyph|mpath|path|pattern|polygon|polyline|radialGradient|rect|set|solidcolor|stop|svg|switch|symbol|text|textPath|tref|tspan|unknown|use|view|vkern)$/;
import { is_interactive_element, is_non_interactive_roles, is_presentation_role, is_interactive_roles, is_hidden_from_screen_reader, is_semantic_role_element } from '../utils/a11y';
const aria_attributes = 'activedescendant atomic autocomplete busy checked colcount colindex colspan controls current describedby description details disabled dropeffect errormessage expanded flowto grabbed haspopup hidden invalid keyshortcuts label labelledby level live modal multiline multiselectable orientation owns placeholder posinset pressed readonly relevant required roledescription rowcount rowindex rowspan selected setsize sort valuemax valuemin valuenow valuetext'.split(' ');
const aria_attribute_set = new Set(aria_attributes);
@ -166,13 +164,13 @@ function get_namespace(parent: Element, element: Element, explicit_namespace: st
const parent_element = parent.find_nearest(/^Element/);
if (!parent_element) {
return explicit_namespace || (svg.test(element.name)
return explicit_namespace || (is_svg(element.name)
? namespaces.svg
: null);
}
if (parent_element.namespace !== namespaces.foreign) {
if (svg.test(element.name.toLowerCase())) return namespaces.svg;
if (is_svg(element.name.toLowerCase())) return namespaces.svg;
if (parent_element.name.toLowerCase() === 'foreignobject') return null;
}
@ -196,15 +194,19 @@ function is_valid_aria_attribute_value(schema: ARIAPropertyDefinition, value: st
.indexOf(typeof value === 'string' ? value.toLowerCase() : value) > -1;
case 'idlist': // if list of ids, split each
return typeof value === 'string'
&& value.split(' ').every((id) => typeof id === 'string');
&& value.split(regex_any_repeated_whitespaces).every((id) => typeof id === 'string');
case 'tokenlist': // if list of tokens, split each
return typeof value === 'string'
&& value.split(' ').every((token) => (schema.values || []).indexOf(token.toLowerCase()) > -1);
&& value.split(regex_any_repeated_whitespaces).every((token) => (schema.values || []).indexOf(token.toLowerCase()) > -1);
default:
return false;
}
}
const regex_any_repeated_whitespaces = /[\s]+/g;
const regex_heading_tags = /^h[1-6]$/;
const regex_illegal_attribute_character = /(^[0-9-.])|[\^$@%&#?!|()[\]{}^*+~;]/;
export default class Element extends Node {
type: 'Element';
name: string;
@ -248,14 +250,14 @@ export default class Element extends Node {
if (this.name === 'pre' || this.name === 'textarea') {
const first = info.children[0];
if (first && first.type === 'Text') {
// The leading newline character needs to be stripped because of a qirk,
// The leading newline character needs to be stripped because of a quirk,
// it is ignored by browsers if the tag and its contents are set through
// innerHTML (NOT if set through the innerHTML of the tag or dynamically).
// Therefore strip it here but add it back in the appropriate
// places if there's another newline afterwards.
// see https://html.spec.whatwg.org/multipage/syntax.html#element-restrictions
// see https://html.spec.whatwg.org/multipage/grouping-content.html#the-pre-element
first.data = first.data.replace(start_newline, '');
first.data = first.data.replace(regex_starts_with_newline, '');
}
}
@ -373,7 +375,7 @@ export default class Element extends Node {
}
validate() {
if (this.component.var_lookup.has(this.name) && this.component.var_lookup.get(this.name).imported) {
if (this.component.var_lookup.has(this.name) && this.component.var_lookup.get(this.name).imported && !is_svg(this.name) && !is_html(this.name)) {
this.component.warn(this, compiler_warnings.component_name_lowercase(this.name));
}
@ -400,7 +402,7 @@ export default class Element extends Node {
// Errors
if (/(^[0-9-.])|[\^$@%&#?!|()[\]{}^*+~;]/.test(name)) {
if (regex_illegal_attribute_character.test(name)) {
return component.error(attribute, compiler_errors.illegal_attribute(name));
}
@ -436,12 +438,17 @@ export default class Element extends Node {
}
validate_attributes_a11y() {
const { component, attributes } = this;
const { component, attributes, handlers } = this;
const attribute_map = new Map<string, Attribute>();
const handlers_map = new Map();
attributes.forEach(attribute => (
attribute_map.set(attribute.name, attribute)
));
handlers.forEach(handler => (
handlers_map.set(handler.name, handler)
));
attributes.forEach(attribute => {
if (attribute.is_spread) return;
@ -461,7 +468,7 @@ export default class Element extends Node {
component.warn(attribute, compiler_warnings.a11y_unknown_aria_attribute(type, match));
}
if (name === 'aria-hidden' && /^h[1-6]$/.test(this.name)) {
if (name === 'aria-hidden' && regex_heading_tags.test(this.name)) {
component.warn(attribute, compiler_warnings.a11y_hidden(this.name));
}
@ -485,45 +492,52 @@ export default class Element extends Node {
component.warn(attribute, compiler_warnings.a11y_misplaced_role(this.name));
}
const value = attribute.get_static_value() as ARIARoleDefintionKey;
if (value && aria_role_abstract_set.has(value)) {
component.warn(attribute, compiler_warnings.a11y_no_abstract_role(value));
} else if (value && !aria_role_set.has(value)) {
const match = fuzzymatch(value, aria_roles);
component.warn(attribute, compiler_warnings.a11y_unknown_role(value, match));
}
const value = attribute.get_static_value();
// no-redundant-roles
const has_redundant_role = value === a11y_implicit_semantics.get(this.name);
if (typeof value === 'string') {
value.split(regex_any_repeated_whitespaces).forEach((current_role: ARIARoleDefintionKey) => {
if (current_role && aria_role_abstract_set.has(current_role)) {
component.warn(attribute, compiler_warnings.a11y_no_abstract_role(current_role));
} else if (current_role && !aria_role_set.has(current_role)) {
const match = fuzzymatch(current_role, aria_roles);
component.warn(attribute, compiler_warnings.a11y_unknown_role(current_role, match));
}
if (this.name === value || has_redundant_role) {
component.warn(attribute, compiler_warnings.a11y_no_redundant_roles(value));
}
// no-redundant-roles
const has_redundant_role = current_role === a11y_implicit_semantics.get(this.name);
// Footers and headers are special cases, and should not have redundant roles unless they are the children of sections or articles.
const is_parent_section_or_article = is_parent(this.parent, ['section', 'article']);
if (!is_parent_section_or_article) {
const has_nested_redundant_role = value === a11y_nested_implicit_semantics.get(this.name);
if (has_nested_redundant_role) {
component.warn(attribute, compiler_warnings.a11y_no_redundant_roles(value));
}
}
if (this.name === current_role || has_redundant_role) {
component.warn(attribute, compiler_warnings.a11y_no_redundant_roles(current_role));
}
// role-has-required-aria-props
const role = roles.get(value);
if (role) {
const required_role_props = Object.keys(role.requiredProps);
const has_missing_props = required_role_props.some(prop => !attributes.find(a => a.name === prop));
// Footers and headers are special cases, and should not have redundant roles unless they are the children of sections or articles.
const is_parent_section_or_article = is_parent(this.parent, ['section', 'article']);
if (!is_parent_section_or_article) {
const has_nested_redundant_role = current_role === a11y_nested_implicit_semantics.get(this.name);
if (has_nested_redundant_role) {
component.warn(attribute, compiler_warnings.a11y_no_redundant_roles(current_role));
}
}
if (has_missing_props) {
component.warn(attribute, compiler_warnings.a11y_role_has_required_aria_props(value as string, required_role_props));
}
}
// role-has-required-aria-props
if (!is_semantic_role_element(current_role, this.name, attribute_map)) {
const role = roles.get(current_role);
if (role) {
const required_role_props = Object.keys(role.requiredProps);
const has_missing_props = required_role_props.some(prop => !attributes.find(a => a.name === prop));
if (has_missing_props) {
component.warn(attribute, compiler_warnings.a11y_role_has_required_aria_props(current_role, required_role_props));
}
}
}
// no-interactive-element-to-noninteractive-role
if (is_interactive_element(this.name, attribute_map) && (is_non_interactive_roles(current_role) || is_presentation_role(current_role))) {
component.warn(this, compiler_warnings.a11y_no_interactive_element_to_noninteractive_role(current_role, this.name));
}
});
// no-interactive-element-to-noninteractive-role
if (is_interactive_element(this.name, attribute_map) && (is_non_interactive_roles(value) || is_presentation_role(value))) {
component.warn(this, compiler_warnings.a11y_no_interactive_element_to_noninteractive_role(value, this.name));
}
}
@ -551,8 +565,40 @@ export default class Element extends Node {
}
}
});
}
// click-events-have-key-events
if (handlers_map.has('click')) {
const role = attribute_map.get('role');
const is_non_presentation_role = role?.is_static && !is_presentation_role(role.get_static_value() as ARIARoleDefintionKey);
if (
!is_hidden_from_screen_reader(this.name, attribute_map) &&
(!role || is_non_presentation_role) &&
!is_interactive_element(this.name, attribute_map) &&
!this.attributes.find(attr => attr.is_spread)
) {
const has_key_event =
handlers_map.has('keydown') ||
handlers_map.has('keyup') ||
handlers_map.has('keypress');
if (!has_key_event) {
component.warn(
this,
compiler_warnings.a11y_click_events_have_key_events()
);
}
}
}
// no-noninteractive-tabindex
if (!is_interactive_element(this.name, attribute_map) && !is_interactive_roles(attribute_map.get('role')?.get_static_value() as ARIARoleDefintionKey)) {
const tab_index = attribute_map.get('tabindex');
if (tab_index && (!tab_index.is_static || Number(tab_index.get_static_value()) >= 0)) {
component.warn(this, compiler_warnings.a11y_no_noninteractive_tabindex);
}
}
}
validate_special_cases() {
const { component, attributes, handlers } = this;
@ -572,6 +618,27 @@ export default class Element extends Node {
const href_attribute = attribute_map.get('href') || attribute_map.get('xlink:href');
const id_attribute = attribute_map.get('id');
const name_attribute = attribute_map.get('name');
const target_attribute = attribute_map.get('target');
if (target_attribute && target_attribute.get_static_value() === '_blank' && href_attribute) {
const href_static_value = href_attribute.get_static_value() ? href_attribute.get_static_value().toLowerCase() : null;
if (href_static_value === null || href_static_value.match(/^(https?:)?\/\//i)) {
const rel = attribute_map.get('rel');
if (rel == null || rel.is_static) {
const rel_values = rel ? rel.get_static_value().split(regex_any_repeated_whitespaces) : [];
const expected_values = ['noreferrer'];
expected_values.forEach(expected_value => {
if (!rel || rel && rel_values.indexOf(expected_value) < 0) {
component.warn(this, {
code: `security-anchor-rel-${expected_value}`,
message: `Security: Anchor with "target=_blank" should have rel attribute containing the value "${expected_value}"`
});
}
});
}
}
}
if (href_attribute) {
const href_value = href_attribute.get_static_value();
@ -626,8 +693,24 @@ export default class Element extends Node {
}
if (this.name === 'label') {
const has_input_child = this.children.some(i => (i instanceof Element && a11y_labelable.has(i.name) ));
if (!attribute_map.has('for') && !has_input_child) {
const has_input_child = (children: INode[]) => {
if (children.some(child => (child instanceof Element && (a11y_labelable.has(child.name) || child.name === 'slot')))) {
return true;
}
for (const child of children) {
if (!('children' in child) || child.children.length === 0) {
continue;
}
if (has_input_child(child.children)) {
return true;
}
}
return false;
};
if (!attribute_map.has('for') && !has_input_child(this.children)) {
component.warn(this, compiler_warnings.a11y_label_has_associated_control);
}
}
@ -676,7 +759,7 @@ export default class Element extends Node {
if (this.name === 'figure') {
const children = this.children.filter(node => {
if (node.type === 'Comment') return false;
if (node.type === 'Text') return /\S/.test(node.data);
if (node.type === 'Text') return regex_non_whitespace_character.test(node.data);
return true;
});
@ -808,10 +891,10 @@ export default class Element extends Node {
if (this.name !== 'video') {
return component.error(binding, compiler_errors.invalid_binding_element_with('<video>', name));
}
} else if (dimensions.test(name)) {
} else if (regex_dimensions.test(name)) {
if (this.name === 'svg' && (name === 'offsetWidth' || name === 'offsetHeight')) {
return component.error(binding, compiler_errors.invalid_binding_on(binding.name, `<svg>. Use '${name.replace('offset', 'client')}' instead`));
} else if (svg.test(this.name)) {
} else if (is_svg(this.name)) {
return component.error(binding, compiler_errors.invalid_binding_on(binding.name, 'SVG elements'));
} else if (is_void(this.name)) {
return component.error(binding, compiler_errors.invalid_binding_on(binding.name, `void elements like <${this.name}>. Use a wrapper element instead`));
@ -935,7 +1018,7 @@ export default class Element extends Node {
if (attribute && !attribute.is_true) {
attribute.chunks.forEach((chunk, index) => {
if (chunk.type === 'Text') {
let data = chunk.data.replace(/[\s\n\t]+/g, ' ');
let data = chunk.data.replace(regex_any_repeated_whitespaces, ' ');
if (index === 0) {
data = data.trimLeft();
} else if (index === attribute.chunks.length - 1) {
@ -949,12 +1032,14 @@ export default class Element extends Node {
}
}
const regex_starts_with_vovel = /^[aeiou]/;
function should_have_attribute(
node,
attributes: string[],
name = node.name
) {
const article = /^[aeiou]/.test(attributes[0]) ? 'an' : 'a';
const article = regex_starts_with_vovel.test(attributes[0]) ? 'an' : 'a';
const sequence = attributes.length > 1 ?
attributes.slice(0, -1).join(', ') + ` or ${attributes[attributes.length - 1]}` :
attributes[0];
@ -962,10 +1047,12 @@ function should_have_attribute(
node.component.warn(node, compiler_warnings.a11y_missing_attribute(name, article, sequence));
}
const regex_minus_sign = /-/;
function within_custom_element(parent: INode) {
while (parent) {
if (parent.type === 'InlineComponent') return false;
if (parent.type === 'Element' && /-/.test(parent.name)) return true;
if (parent.type === 'Element' && regex_minus_sign.test(parent.name)) return true;
parent = parent.parent;
}
return false;

@ -6,6 +6,8 @@ import { Identifier } from 'estree';
import TemplateScope from './shared/TemplateScope';
import { TemplateNode } from '../../interfaces';
const regex_contains_term_function_expression = /FunctionExpression/;
export default class EventHandler extends Node {
type: 'EventHandler';
name: string;
@ -25,7 +27,7 @@ export default class EventHandler extends Node {
this.expression = new Expression(component, this, template_scope, info.expression);
this.uses_context = this.expression.uses_context;
if (/FunctionExpression/.test(info.expression.type) && info.expression.params.length === 0) {
if (regex_contains_term_function_expression.test(info.expression.type) && info.expression.params.length === 0) {
// TODO make this detection more accurate — if `event.preventDefault` isn't called, and
// `event` is passed to another function, we can make it passive
this.can_make_passive = true;
@ -55,7 +57,7 @@ export default class EventHandler extends Node {
}
const node = this.expression.node;
if (/FunctionExpression/.test(node.type)) {
if (regex_contains_term_function_expression.test(node.type)) {
return false;
}

@ -5,6 +5,7 @@ import Component from '../Component';
import TemplateScope from './shared/TemplateScope';
import { TemplateNode } from '../../interfaces';
import compiler_errors from '../compiler_errors';
import { regex_non_whitespace_character } from '../../utils/patterns';
export default class Head extends Node {
type: 'Head';
@ -20,7 +21,7 @@ export default class Head extends Node {
}
this.children = map_children(component, parent, scope, info.children.filter(child => {
return (child.type !== 'Text' || /\S/.test(child.data));
return (child.type !== 'Text' || regex_non_whitespace_character.test(child.data));
}));
if (this.children.length > 0) {

@ -10,6 +10,7 @@ import TemplateScope from './shared/TemplateScope';
import { INode } from './interfaces';
import { TemplateNode } from '../../interfaces';
import compiler_errors from '../compiler_errors';
import { regex_only_whitespaces } from '../../utils/patterns';
export default class InlineComponent extends Node {
type: 'InlineComponent';
@ -22,6 +23,7 @@ export default class InlineComponent extends Node {
css_custom_properties: Attribute[] = [];
children: INode[];
scope: TemplateScope;
namespace: string;
constructor(component: Component, parent: Node, scope: TemplateScope, info: TemplateNode) {
super(component, parent, scope, info);
@ -33,6 +35,7 @@ export default class InlineComponent extends Node {
}
this.name = info.name;
this.namespace = get_namespace(parent, component.namespace);
this.expression = this.name === 'svelte:component'
? new Expression(component, this, scope, info.expression)
@ -71,10 +74,10 @@ export default class InlineComponent extends Node {
case 'Transition':
return component.error(node, compiler_errors.invalid_transition);
case 'StyleDirective':
return component.error(node, compiler_errors.invalid_component_style_directive);
default:
throw new Error(`Not implemented: ${node.type}`);
}
@ -163,5 +166,15 @@ export default class InlineComponent extends Node {
}
function not_whitespace_text(node) {
return !(node.type === 'Text' && /^\s+$/.test(node.data));
return !(node.type === 'Text' && regex_only_whitespaces.test(node.data));
}
function get_namespace(parent: Node, explicit_namespace: string) {
const parent_element = parent.find_nearest(/^Element/);
if (!parent_element) {
return explicit_namespace;
}
return parent_element.namespace;
}

@ -1,20 +1,42 @@
import { TemplateNode } from '../../interfaces';
import list from '../../utils/list';
import compiler_errors from '../compiler_errors';
import Component from '../Component';
import { nodes_to_template_literal } from '../utils/nodes_to_template_literal';
import Expression from './shared/Expression';
import Node from './shared/Node';
import TemplateScope from './shared/TemplateScope';
const valid_modifiers = new Set(['important']);
export default class StyleDirective extends Node {
type: 'StyleDirective';
name: string;
modifiers: Set<string>;
expression: Expression;
should_cache: boolean;
constructor(component: Component, parent: Node, scope: TemplateScope, info: TemplateNode) {
constructor(
component: Component,
parent: Node,
scope: TemplateScope,
info: TemplateNode
) {
super(component, parent, scope, info);
this.name = info.name;
this.modifiers = new Set(info.modifiers);
for (const modifier of this.modifiers) {
if (!valid_modifiers.has(modifier)) {
component.error(
this,
compiler_errors.invalid_style_directive_modifier(
list([...valid_modifiers])
)
);
}
}
// Convert the value array to an expression so it's easier to handle
// the StyleDirective going forward.
@ -34,6 +56,9 @@ export default class StyleDirective extends Node {
this.expression = new Expression(component, this, scope, raw_expression);
this.should_cache = raw_expression.expressions.length > 0;
}
}
get important() {
return this.modifiers.has('important');
}
}

@ -3,6 +3,7 @@ import Component from '../Component';
import TemplateScope from './shared/TemplateScope';
import { INode } from './interfaces';
import { TemplateNode } from '../../interfaces';
import { regex_non_whitespace_character } from '../../utils/patterns';
// Whitespace inside one of these elements will not result in
// a whitespace node being created in any circumstances. (This
@ -16,6 +17,8 @@ const elements_without_text = new Set([
'video'
]);
const regex_ends_with_svg = /svg$/;
export default class Text extends Node {
type: 'Text';
data: string;
@ -28,7 +31,7 @@ export default class Text extends Node {
}
should_skip() {
if (/\S/.test(this.data)) return false;
if (regex_non_whitespace_character.test(this.data)) return false;
const parent_element = this.find_nearest(/(?:Element|InlineComponent|SlotTemplate|Head)/);
if (!parent_element) return false;
@ -37,7 +40,7 @@ export default class Text extends Node {
if (parent_element.type === 'InlineComponent') return parent_element.children.length === 1 && this === parent_element.children[0];
// svg namespace exclusions
if (/svg$/.test(parent_element.namespace)) {
if (regex_ends_with_svg.test(parent_element.namespace)) {
if (this.prev && this.prev.type === 'Element' && this.prev.name === 'tspan') return false;
}

@ -4,6 +4,8 @@ import Node from './Node';
import { INode } from '../interfaces';
import compiler_warnings from '../../compiler_warnings';
const regex_non_whitespace_characters = /[^ \r\n\f\v\t]/;
export default class AbstractBlock extends Node {
block: Block;
children: INode[];
@ -17,7 +19,7 @@ export default class AbstractBlock extends Node {
const child = this.children[0];
if (!child || (child.type === 'Text' && !/[^ \r\n\f\v\t]/.test(child.data))) {
if (!child || (child.type === 'Text' && !regex_non_whitespace_characters.test(child.data))) {
this.component.warn(this, compiler_warnings.empty_block);
}
}

@ -20,7 +20,8 @@ export function unpack_destructuring({
modifier = (node) => node,
default_modifier = (node) => node,
scope,
component
component,
context_rest_properties
}: {
contexts: Context[];
node: Node;
@ -28,6 +29,7 @@ export function unpack_destructuring({
default_modifier?: Context['default_modifier'];
scope: TemplateScope;
component: Component;
context_rest_properties: Map<string, Node>;
}) {
if (!node) return;
@ -43,6 +45,7 @@ export function unpack_destructuring({
modifier,
default_modifier
});
context_rest_properties.set((node.argument as Identifier).name, node);
} else if (node.type === 'ArrayPattern') {
node.elements.forEach((element, i) => {
if (element && element.type === 'RestElement') {
@ -52,8 +55,10 @@ export function unpack_destructuring({
modifier: (node) => x`${modifier(node)}.slice(${i})` as Node,
default_modifier,
scope,
component
component,
context_rest_properties
});
context_rest_properties.set((element.argument as Identifier).name, element);
} else if (element && element.type === 'AssignmentPattern') {
const n = contexts.length;
mark_referenced(element.right, scope, component);
@ -70,7 +75,8 @@ export function unpack_destructuring({
to_ctx
)}` as Node,
scope,
component
component,
context_rest_properties
});
} else {
unpack_destructuring({
@ -79,7 +85,8 @@ export function unpack_destructuring({
modifier: (node) => x`${modifier(node)}[${i}]` as Node,
default_modifier,
scope,
component
component,
context_rest_properties
});
}
});
@ -97,8 +104,10 @@ export function unpack_destructuring({
)}, [${used_properties}])` as Node,
default_modifier,
scope,
component
component,
context_rest_properties
});
context_rest_properties.set((property.argument as Identifier).name, property);
} else {
const key = property.key as Identifier;
const value = property.value;
@ -121,7 +130,8 @@ export function unpack_destructuring({
to_ctx
)}` as Node,
scope,
component
component,
context_rest_properties
});
} else {
unpack_destructuring({
@ -130,7 +140,8 @@ export function unpack_destructuring({
modifier: (node) => x`${modifier(node)}.${key.name}` as Node,
default_modifier,
scope,
component
component,
context_rest_properties
});
}
}

@ -21,6 +21,8 @@ import compiler_errors from '../../compiler_errors';
type Owner = INode;
const regex_contains_term_function_expression = /FunctionExpression/;
export default class Expression {
type: 'Expression' = 'Expression';
component: Component;
@ -72,7 +74,7 @@ export default class Expression {
scope = map.get(node);
}
if (!function_expression && /FunctionExpression/.test(node.type)) {
if (!function_expression && regex_contains_term_function_expression.test(node.type)) {
function_expression = node;
}
@ -126,6 +128,7 @@ export default class Expression {
deep = node.left.type === 'MemberExpression';
names = extract_names(deep ? get_object(node.left) : node.left);
} else if (node.type === 'UpdateExpression') {
deep = node.argument.type === 'MemberExpression';
names = extract_names(get_object(node.argument));
}
}
@ -147,7 +150,26 @@ export default class Expression {
component.add_reference(node, name);
const variable = component.var_lookup.get(name);
if (variable) variable[deep ? 'mutated' : 'reassigned'] = true;
if (variable) {
variable[deep ? 'mutated' : 'reassigned'] = true;
}
const declaration: any = scope.find_owner(name)?.declarations.get(name);
if (declaration) {
if (declaration.kind === 'const' && !deep) {
component.error(node, {
code: 'assignment-to-const',
message: 'You are assigning to a const'
});
}
} else if (variable && variable.writable === false && !deep) {
component.error(node, {
code: 'assignment-to-const',
message: 'You are assigning to a const'
});
}
}
});
}
@ -252,41 +274,7 @@ export default class Expression {
);
const declaration = b`const ${id} = ${node}`;
if (owner.type === 'ConstTag') {
let child_scope = scope;
walk(node, {
enter(node: Node, parent: any) {
if (map.has(node)) child_scope = map.get(node);
if (node.type === 'Identifier' && is_reference(node, parent)) {
if (child_scope.has(node.name)) return;
this.replace(block.renderer.reference(node, ctx));
}
},
leave(node: Node) {
if (map.has(node)) child_scope = child_scope.parent;
}
});
} else if (dependencies.size === 0 && contextual_dependencies.size === 0) {
// we can hoist this out of the component completely
component.fully_hoisted.push(declaration);
this.replace(id as any);
component.add_var(node, {
name: id.name,
internal: true,
hoistable: true,
referenced: true
});
} else if (contextual_dependencies.size === 0) {
// function can be hoisted inside the component init
component.partly_hoisted.push(declaration);
block.renderer.add_to_context(id.name);
this.replace(block.renderer.reference(id));
} else {
// we need a combo block/init recipe
const extract_functions = () => {
const deps = Array.from(contextual_dependencies);
const function_expression = node as FunctionExpression;
@ -296,7 +284,7 @@ export default class Expression {
...function_expression.params
];
const context_args = deps.map(name => block.renderer.reference(name));
const context_args = deps.map(name => block.renderer.reference(name, ctx));
component.partly_hoisted.push(declaration);
@ -312,6 +300,50 @@ export default class Expression {
: b`function ${id}() {
return ${callee}(${context_args});
}`;
return { deps, func_declaration };
};
if (owner.type === 'ConstTag') {
// we need a combo block/init recipe
if (contextual_dependencies.size === 0) {
let child_scope = scope;
walk(node, {
enter(node: Node, parent: any) {
if (map.has(node)) child_scope = map.get(node);
if (node.type === 'Identifier' && is_reference(node, parent)) {
if (child_scope.has(node.name)) return;
this.replace(block.renderer.reference(node, ctx));
}
},
leave(node: Node) {
if (map.has(node)) child_scope = child_scope.parent;
}
});
} else {
const { func_declaration } = extract_functions();
this.replace(func_declaration[0]);
}
} else if (dependencies.size === 0 && contextual_dependencies.size === 0) {
// we can hoist this out of the component completely
component.fully_hoisted.push(declaration);
this.replace(id as any);
component.add_var(node, {
name: id.name,
internal: true,
hoistable: true,
referenced: true
});
} else if (contextual_dependencies.size === 0) {
// function can be hoisted inside the component init
component.partly_hoisted.push(declaration);
block.renderer.add_to_context(id.name);
this.replace(block.renderer.reference(id));
} else {
// we need a combo block/init recipe
const { deps, func_declaration } = extract_functions();
if (owner.type === 'Attribute' && owner.parent.name === 'slot') {
const dep_scopes = new Set<INode>(deps.map(name => template_scope.get_owner(name)));
@ -323,7 +355,7 @@ export default class Expression {
const func_expression = func_declaration[0];
if (node.type === 'InlineComponent') {
if (node.type === 'InlineComponent' || node.type === 'SlotTemplate') {
// <Comp let:data />
this.replace(func_expression);
} else {

@ -3,6 +3,7 @@ import Wrapper from './wrappers/shared/Wrapper';
import { b, x } from 'code-red';
import { Node, Identifier, ArrayPattern } from 'estree';
import { is_head } from './wrappers/shared/is_head';
import { regex_double_quotes } from '../../utils/patterns';
export interface Bindings {
object: Identifier;
@ -415,7 +416,7 @@ export default class Block {
block: ${block},
id: ${this.name || 'create_fragment'}.name,
type: "${this.type}",
source: "${this.comment ? this.comment.replace(/"/g, '\\"') : ''}",
source: "${this.comment ? this.comment.replace(regex_double_quotes, '\\"') : ''}",
ctx: #ctx
});
return ${block};`

@ -168,7 +168,7 @@ export default class Renderer {
return member;
}
invalidate(name: string, value?, main_execution_context: boolean = false) {
invalidate(name: string, value?: unknown, main_execution_context: boolean = false) {
return renderer_invalidate(this, name, value, main_execution_context);
}

@ -12,6 +12,7 @@ import { RawSourceMap, DecodedSourceMap } from '@ampproject/remapping/dist/types
import { flatten } from '../../utils/flatten';
import check_enable_sourcemap from '../utils/check_enable_sourcemap';
import { push_array } from '../../utils/push_array';
import { regex_backslashes } from '../../utils/patterns';
export default function dom(
component: Component,
@ -53,7 +54,7 @@ export default function dom(
const should_add_css = (
!options.customElement &&
!!styles &&
options.css !== false
options.css === 'injected'
);
if (should_add_css) {
@ -82,7 +83,7 @@ export default function dom(
}
const uses_slots = component.var_lookup.has('$$slots');
let compute_slots;
let compute_slots: Node[] | undefined;
if (uses_slots) {
compute_slots = b`
const $$slots = @compute_slots(#slots);
@ -121,7 +122,7 @@ export default function dom(
const accessors = [];
const not_equal = component.component_options.immutable ? x`@not_equal` : x`@safe_not_equal`;
let dev_props_check: Node[] | Node;
let missing_props_check: Node[] | Node;
let inject_state: Expression;
let capture_state: Expression;
let props_inject: Node[] | Node;
@ -227,13 +228,13 @@ export default function dom(
const expected = props.filter(prop => prop.writable && !prop.initialised);
if (expected.length) {
dev_props_check = b`
const { ctx: #ctx } = this.$$;
const props = ${options.customElement ? x`this.attributes` : x`options.props || {}`};
${expected.map(prop => b`
if (${renderer.reference(prop.name)} === undefined && !('${prop.export_name}' in props)) {
@_console.warn("<${component.tag}> was created without expected prop '${prop.export_name}'");
}`)}
missing_props_check = b`
$$self.$$.on_mount.push(function () {
${expected.map(prop => b`
if (${prop.name} === undefined && !(('${prop.export_name}' in $$props) || $$self.$$.bound[$$self.$$.props['${prop.export_name}']])) {
@_console.warn("<${component.tag}> was created without expected prop '${prop.export_name}'");
}`)}
});
`;
}
@ -395,7 +396,7 @@ export default function dom(
if (has_definition) {
const reactive_declarations: (Node | Node[]) = [];
const fixed_reactive_declarations = []; // not really 'reactive' but whatever
const fixed_reactive_declarations: Node[] = []; // not really 'reactive' but whatever
component.reactive_declarations.forEach(d => {
const dependencies = Array.from(d.dependencies);
@ -440,7 +441,7 @@ export default function dom(
return b`let ${$name};`;
});
let unknown_props_check;
let unknown_props_check: Node[] | undefined;
if (component.compile_options.dev && !(uses_props || uses_rest)) {
unknown_props_check = b`
const writable_props = [${writable_props.map(prop => x`'${prop.export_name}'`)}];
@ -476,6 +477,7 @@ export default function dom(
${instance_javascript}
${missing_props_check}
${unknown_props_check}
${renderer.binding_groups.size > 0 && b`const $$binding_groups = [${[...renderer.binding_groups.keys()].map(_ => x`[]`)}];`}
@ -529,12 +531,10 @@ export default function dom(
constructor(options) {
super();
${css.code && b`this.shadowRoot.innerHTML = \`<style>${css.code.replace(/\\/g, '\\\\')}${css_sourcemap_enabled && options.dev ? `\n/*# sourceMappingURL=${css.map.toUrl()} */` : ''}</style>\`;`}
${css.code && b`this.shadowRoot.innerHTML = \`<style>${css.code.replace(regex_backslashes, '\\\\')}${css_sourcemap_enabled && options.dev ? `\n/*# sourceMappingURL=${css.map.toUrl()} */` : ''}</style>\`;`}
@init(this, { target: this.shadowRoot, props: ${init_props}, customElement: true }, ${definition}, ${has_create_fragment ? 'create_fragment' : 'null'}, ${not_equal}, ${prop_indexes}, null, ${dirty});
${dev_props_check}
if (options) {
if (options.target) {
@insert(options.target, this, options.anchor);
@ -594,8 +594,6 @@ export default function dom(
super(${options.dev && 'options'});
@init(this, options, ${definition}, ${has_create_fragment ? 'create_fragment' : 'null'}, ${not_equal}, ${prop_indexes}, ${optional_parameters});
${options.dev && b`@dispatch_dev("SvelteRegisterComponent", { component: this, tagName: "${name.name}", options, id: create_fragment.name });`}
${dev_props_check}
}
}
`[0] as ClassDeclaration;

@ -80,7 +80,7 @@ export function invalidate(renderer: Renderer, scope: Scope, node: Node, names:
return invalidate;
}
export function renderer_invalidate(renderer: Renderer, name: string, value?, main_execution_context: boolean = false) {
export function renderer_invalidate(renderer: Renderer, name: string, value?: unknown, main_execution_context: boolean = false) {
const variable = renderer.component.var_lookup.get(name);
if (variable && (variable.subscribable && (variable.reassigned || variable.export_name))) {

@ -582,7 +582,7 @@ export default class EachBlockWrapper extends Wrapper {
const start = this.block.has_update_method ? 0 : '#old_length';
let remove_old_blocks;
let remove_old_blocks: Node[];
if (this.block.has_outros) {
const out = block.get_unique_name('out');

@ -9,6 +9,8 @@ import Text from '../../../nodes/Text';
import handle_select_value_binding from './handle_select_value_binding';
import { Identifier, Node } from 'estree';
import { namespaces } from '../../../../utils/namespaces';
import { boolean_attributes } from '../../../../../shared/boolean_attributes';
import { regex_double_quotes } from '../../../../utils/patterns';
const non_textlike_input_types = new Set([
'button',
@ -41,9 +43,12 @@ export class BaseAttributeWrapper {
}
}
render(_block: Block) {}
render(_block: Block) { }
}
const regex_minus_sign = /-/;
const regex_invalid_variable_identifier_characters = /[^a-zA-Z_$]/g;
export default class AttributeWrapper extends BaseAttributeWrapper {
node: Attribute;
parent: ElementWrapper;
@ -114,7 +119,7 @@ export default class AttributeWrapper extends BaseAttributeWrapper {
// xlink is a special case... we could maybe extend this to generic
// namespaced attributes but I'm not sure that's applicable in
// HTML5?
const method = /-/.test(element.node.name)
const method = regex_minus_sign.test(element.node.name)
? '@set_custom_element_data'
: name.slice(0, 6) === 'xlink:'
? '@xlink_attr'
@ -125,7 +130,7 @@ export default class AttributeWrapper extends BaseAttributeWrapper {
const dependencies = this.get_dependencies();
const value = this.get_value(block);
let updater;
let updater: Node[];
const init = this.get_init(block, value);
if (is_legacy_input_type) {
@ -195,7 +200,7 @@ export default class AttributeWrapper extends BaseAttributeWrapper {
get_init(block: Block, value) {
this.last = this.should_cache && block.get_unique_name(
`${this.parent.var.name}_${this.name.replace(/[^a-zA-Z_$]/g, '_')}_value`
`${this.parent.var.name}_${this.name.replace(regex_invalid_variable_identifier_characters, '_')}_value`
);
if (this.should_cache) block.add_variable(this.last);
@ -253,9 +258,9 @@ export default class AttributeWrapper extends BaseAttributeWrapper {
return metadata;
}
get_value(block) {
get_value(block: Block) {
if (this.node.is_true) {
if (this.metadata && boolean_attribute.has(this.metadata.property_name.toLowerCase())) {
if (this.metadata && boolean_attributes.has(this.metadata.property_name.toLowerCase())) {
return x`true`;
}
return x`""`;
@ -282,7 +287,7 @@ export default class AttributeWrapper extends BaseAttributeWrapper {
return value;
}
get_class_name_text(block) {
get_class_name_text(block: Block) {
const scoped_css = this.node.chunks.some((chunk: Text) => chunk.synthetic);
const rendered = this.render_chunks(block);
@ -312,7 +317,7 @@ export default class AttributeWrapper extends BaseAttributeWrapper {
return `="${value.map(chunk => {
return chunk.type === 'Text'
? chunk.data.replace(/"/g, '\\"')
? chunk.data.replace(regex_double_quotes, '\\"')
: `\${${chunk.manipulate()}}`;
}).join('')}"`;
}
@ -376,46 +381,18 @@ Object.keys(attribute_lookup).forEach(name => {
if (!metadata.property_name) metadata.property_name = name;
});
// source: https://html.spec.whatwg.org/multipage/indices.html
const boolean_attribute = new Set([
'allowfullscreen',
'allowpaymentrequest',
'async',
'autofocus',
'autoplay',
'checked',
'controls',
'default',
'defer',
'disabled',
'formnovalidate',
'hidden',
'ismap',
'itemscope',
'loop',
'multiple',
'muted',
'nomodule',
'novalidate',
'open',
'playsinline',
'readonly',
'required',
'reversed',
'selected'
]);
function should_cache(attribute: AttributeWrapper) {
return attribute.is_src || attribute.node.should_cache();
}
const regex_contains_checked_or_group = /checked|group/;
function is_indirectly_bound_value(attribute: AttributeWrapper) {
const element = attribute.parent;
return attribute.name === 'value' &&
(element.node.name === 'option' || // TODO check it's actually bound
(element.node.name === 'input' &&
element.node.bindings.some(
(binding) =>
/checked|group/.test(binding.name)
(binding) => regex_contains_checked_or_group.test(binding.name)
)));
}

@ -299,8 +299,8 @@ function get_binding_group(renderer: Renderer, value: Binding, block: Block) {
for (const dep of contextual_dependencies) {
const context = block.bindings.get(dep);
let key;
let name;
let key: string;
let name: string;
if (context) {
key = context.object.name;
name = context.property.name;
@ -364,7 +364,7 @@ function get_event_handler(
const contextual_dependencies = new Set<string>(binding.node.expression.contextual_dependencies);
const context = block.bindings.get(name);
let set_store;
let set_store: Node[] | undefined;
if (context) {
const { object, property, store, snippet } = context;

@ -26,7 +26,7 @@ export default class EventHandlerWrapper {
}
}
get_snippet(block) {
get_snippet(block: Block) {
const snippet = this.node.expression ? this.node.expression.manipulate(block) : block.renderer.reference(this.node.handler_name);
if (this.node.reassigned) {

@ -69,6 +69,8 @@ export default class StyleAttributeWrapper extends AttributeWrapper {
}
}
const regex_style_prop_key = /^\s*([\w-]+):\s*/;
function optimize_style(value: Array<Text | Expression>) {
const props: StyleProp[] = [];
let chunks = value.slice();
@ -78,7 +80,7 @@ function optimize_style(value: Array<Text | Expression>) {
if (chunk.type !== 'Text') return null;
const key_match = /^\s*([\w-]+):\s*/.exec(chunk.data);
const key_match = regex_style_prop_key.exec(chunk.data);
if (!key_match) return null;
const key = key_match[1];
@ -106,6 +108,9 @@ function optimize_style(value: Array<Text | Expression>) {
return props;
}
const regex_important_flag = /\s*!important\s*$/;
const regex_semicolon_or_whitespace = /[;\s]/;
function get_style_value(chunks: Array<Text | Expression>) {
const value: Array<Text | Expression> = [];
@ -151,7 +156,7 @@ function get_style_value(chunks: Array<Text | Expression>) {
} as Text);
}
while (/[;\s]/.test(chunk.data[c])) c += 1;
while (regex_semicolon_or_whitespace.test(chunk.data[c])) c += 1;
const remaining_data = chunk.data.slice(c);
if (remaining_data) {
@ -172,9 +177,9 @@ function get_style_value(chunks: Array<Text | Expression>) {
let important = false;
const last_chunk = value[value.length - 1];
if (last_chunk && last_chunk.type === 'Text' && /\s*!important\s*$/.test(last_chunk.data)) {
if (last_chunk && last_chunk.type === 'Text' && regex_important_flag.test(last_chunk.data)) {
important = true;
last_chunk.data = last_chunk.data.replace(/\s*!important\s*$/, '');
last_chunk.data = last_chunk.data.replace(regex_important_flag, '');
if (!last_chunk.data) value.pop();
}

@ -6,7 +6,7 @@ svg_attributes.forEach(name => {
svg_attribute_lookup.set(name.toLowerCase(), name);
});
export default function fix_attribute_casing(name) {
export default function fix_attribute_casing(name: string) {
name = name.toLowerCase();
return svg_attribute_lookup.get(name) || name;
}

@ -12,14 +12,14 @@ import { namespaces } from '../../../../utils/namespaces';
import AttributeWrapper from './Attribute';
import StyleAttributeWrapper from './StyleAttribute';
import SpreadAttributeWrapper from './SpreadAttribute';
import { dimensions, start_newline } from '../../../../utils/patterns';
import { regex_dimensions, regex_starts_with_newline, regex_backslashes } from '../../../../utils/patterns';
import Binding from './Binding';
import add_to_set from '../../../utils/add_to_set';
import { add_event_handler } from '../shared/add_event_handlers';
import { add_action } from '../shared/add_actions';
import bind_this from '../shared/bind_this';
import { is_head } from '../shared/is_head';
import { Identifier, ExpressionStatement, CallExpression } from 'estree';
import { Identifier, ExpressionStatement, CallExpression, Node } from 'estree';
import EventHandler from './EventHandler';
import { extract_names } from 'periscopic';
import Action from '../../../nodes/Action';
@ -34,12 +34,16 @@ interface BindingGroup {
bindings: Binding[];
}
const regex_contains_radio_or_checkbox_or_file = /radio|checkbox|file/;
const regex_contains_radio_or_checkbox_or_range_or_file = /radio|checkbox|range|file/;
const events = [
{
event_names: ['input'],
filter: (node: Element, _name: string) =>
node.name === 'textarea' ||
node.name === 'input' && !/radio|checkbox|range|file/.test(node.get_static_attribute_value('type') as string)
node.name === 'input' &&
!regex_contains_radio_or_checkbox_or_range_or_file.test(node.get_static_attribute_value('type') as string)
},
{
event_names: ['input'],
@ -51,7 +55,8 @@ const events = [
event_names: ['change'],
filter: (node: Element, _name: string) =>
node.name === 'select' ||
node.name === 'input' && /radio|checkbox|file/.test(node.get_static_attribute_value('type') as string)
node.name === 'input' &&
regex_contains_radio_or_checkbox_or_file.test(node.get_static_attribute_value('type') as string)
},
{
event_names: ['change', 'input'],
@ -62,7 +67,7 @@ const events = [
{
event_names: ['elementresize'],
filter: (_node: Element, name: string) =>
dimensions.test(name)
regex_dimensions.test(name)
},
// media events
@ -136,6 +141,8 @@ const events = [
];
const CHILD_DYNAMIC_ELEMENT_BLOCK = 'child_dynamic_element';
const regex_invalid_variable_identifier_characters = /[^a-zA-Z0-9_$]/g;
const regex_minus_signs = /-/g;
export default class ElementWrapper extends Wrapper {
node: Element;
@ -182,7 +189,7 @@ export default class ElementWrapper extends Wrapper {
this.var = {
type: 'Identifier',
name: node.name.replace(/[^a-zA-Z0-9_$]/g, '_')
name: node.name.replace(regex_invalid_variable_identifier_characters, '_')
};
this.void = is_void(node.name);
@ -504,9 +511,10 @@ export default class ElementWrapper extends Wrapper {
get_render_statement(block: Block) {
const { name, namespace, tag_expr } = this.node;
const reference = tag_expr.manipulate(block);
if (namespace === namespaces.svg) {
return x`@svg_element("${name}")`;
return x`@svg_element(${reference})`;
}
if (namespace) {
@ -518,7 +526,6 @@ export default class ElementWrapper extends Wrapper {
return x`@element_is("${name}", ${is.render_chunks(block).reduce((lhs, rhs) => x`${lhs} + ${rhs}`)})`;
}
const reference = tag_expr.manipulate(block);
return x`@element(${reference})`;
}
@ -527,7 +534,7 @@ export default class ElementWrapper extends Wrapper {
.filter((attr) => !(attr instanceof SpreadAttributeWrapper) && !attr.property_name)
.map((attr) => p`${(attr as StyleAttributeWrapper | AttributeWrapper).name}: true`);
let reference;
let reference: string | ReturnType<typeof x>;
if (this.node.tag_expr.node.type === 'Literal') {
if (this.node.namespace) {
reference = `"${this.node.tag_expr.node.value}"`;
@ -547,7 +554,7 @@ export default class ElementWrapper extends Wrapper {
}
}
add_directives_in_order (block: Block) {
add_directives_in_order(block: Block) {
type OrderedAttribute = EventHandler | BindingGroup | Binding | Action;
const binding_groups = events
@ -561,7 +568,7 @@ export default class ElementWrapper extends Wrapper {
const this_binding = this.bindings.find(b => b.node.name === 'this');
function getOrder (item: OrderedAttribute) {
function getOrder(item: OrderedAttribute) {
if (item instanceof EventHandler) {
return item.node.start;
} else if (item instanceof Binding) {
@ -627,7 +634,7 @@ export default class ElementWrapper extends Wrapper {
// media bindings — awkward special case. The native timeupdate events
// fire too infrequently, so we need to take matters into our
// own hands
let animation_frame;
let animation_frame: Identifier | undefined;
if (binding_group.events[0] === 'timeupdate') {
animation_frame = block.get_unique_name(`${this.var.name}_animationframe`);
block.add_variable(animation_frame);
@ -803,15 +810,33 @@ export default class ElementWrapper extends Wrapper {
const fn = this.node.namespace === namespaces.svg ? x`@set_svg_attributes` : x`@set_attributes`;
block.chunks.hydrate.push(
b`${fn}(${this.var}, ${data});`
);
if (this.node.is_dynamic_element) {
// call attribute bindings for custom element if tag is custom element
const tag = this.node.tag_expr.manipulate(block);
const attr_update = this.node.namespace === namespaces.svg
? b`${fn}(${this.var}, ${data});`
: b`
if (/-/.test(${tag})) {
@set_custom_element_data_map(${this.var}, ${data});
} else {
${fn}(${this.var}, ${data});
}`;
block.chunks.hydrate.push(attr_update);
block.chunks.update.push(b`
${data} = @get_spread_update(${levels}, [${updates}]);
${attr_update}`
);
} else {
block.chunks.hydrate.push(
b`${fn}(${this.var}, ${data});`
);
block.chunks.update.push(b`
${fn}(${this.var}, ${data} = @get_spread_update(${levels}, [
${updates}
]));
`);
block.chunks.update.push(b`
${fn}(${this.var}, ${data} = @get_spread_update(${levels}, [
${updates}
]));
`);
}
// handle edge cases for elements
if (this.node.name === 'select') {
@ -851,9 +876,7 @@ export default class ElementWrapper extends Wrapper {
}
}
add_transitions(
block: Block
) {
add_transitions(block: Block) {
const { intro, outro } = this.node;
if (!intro && !outro) return;
@ -910,7 +933,7 @@ export default class ElementWrapper extends Wrapper {
const fn = this.renderer.reference(intro.name);
let intro_block;
let intro_block: Node[];
if (outro) {
intro_block = b`
@ -1009,7 +1032,7 @@ export default class ElementWrapper extends Wrapper {
${outro && b`@add_transform(${this.var}, ${rect});`}
`);
let params;
let params: Node | ReturnType<typeof x>;
if (this.node.animation.expression) {
params = this.node.animation.expression.manipulate(block);
@ -1037,8 +1060,8 @@ export default class ElementWrapper extends Wrapper {
const has_spread = this.node.attributes.some(attr => attr.is_spread);
this.node.classes.forEach(class_directive => {
const { expression, name } = class_directive;
let snippet;
let dependencies;
let snippet: Node | string;
let dependencies: Set<string>;
if (expression) {
snippet = expression.manipulate(block);
dependencies = expression.dependencies;
@ -1054,7 +1077,10 @@ export default class ElementWrapper extends Wrapper {
block.chunks.update.push(updater);
} else if ((dependencies && dependencies.size > 0) || this.class_dependencies.length) {
const all_dependencies = this.class_dependencies.concat(...dependencies);
const condition = block.renderer.dirty(all_dependencies);
let condition = block.renderer.dirty(all_dependencies);
if (block.has_outros) {
condition = x`!#current || ${condition}`;
}
// If all of the dependencies are non-dynamic (don't get updated) then there is no reason
// to add an updater for this.
@ -1076,16 +1102,16 @@ export default class ElementWrapper extends Wrapper {
add_styles(block: Block) {
const has_spread = this.node.attributes.some(attr => attr.is_spread);
this.node.styles.forEach((style_directive) => {
const { name, expression, should_cache } = style_directive;
const { name, expression, should_cache, important } = style_directive;
const snippet = expression.manipulate(block);
let cached_snippet;
let cached_snippet: Identifier | undefined;
if (should_cache) {
cached_snippet = block.get_unique_name(`style_${name.replace(/-/g, '_')}`);
cached_snippet = block.get_unique_name(`style_${name.replace(regex_minus_signs, '_')}`);
block.add_variable(cached_snippet, snippet);
}
const updater = b`@set_style(${this.var}, "${name}", ${should_cache ? cached_snippet : snippet}, false)`;
const updater = b`@set_style(${this.var}, "${name}", ${should_cache ? cached_snippet : snippet}, ${important ? 1 : null})`;
block.chunks.hydrate.push(updater);
@ -1110,7 +1136,7 @@ export default class ElementWrapper extends Wrapper {
});
}
add_manual_style_scoping(block) {
add_manual_style_scoping(block: Block) {
if (this.node.needs_manual_style_scoping) {
const updater = b`@toggle_class(${this.var}, "${this.node.component.stylesheet.id}", true);`;
block.chunks.hydrate.push(updater);
@ -1119,10 +1145,13 @@ export default class ElementWrapper extends Wrapper {
}
}
const regex_backticks = /`/g;
const regex_dollar_signs = /\$/g;
function to_html(wrappers: Array<ElementWrapper | TextWrapper | MustacheTagWrapper | RawMustacheTagWrapper>, block: Block, literal: any, state: any, can_use_raw_text?: boolean) {
wrappers.forEach(wrapper => {
if (wrapper instanceof TextWrapper) {
// Don't add the <pre>/<textare> newline logic here because pre/textarea.innerHTML
// Don't add the <pre>/<textarea> newline logic here because pre/textarea.innerHTML
// would keep the leading newline, too, only someParent.innerHTML = '..<pre/textarea>..' won't
if ((wrapper as TextWrapper).use_space()) state.quasi.value.raw += ' ';
@ -1136,9 +1165,9 @@ function to_html(wrappers: Array<ElementWrapper | TextWrapper | MustacheTagWrapp
);
state.quasi.value.raw += (raw ? wrapper.data : escape_html(wrapper.data))
.replace(/\\/g, '\\\\')
.replace(/`/g, '\\`')
.replace(/\$/g, '\\$');
.replace(regex_backslashes, '\\\\')
.replace(regex_backticks, '\\`')
.replace(regex_dollar_signs, '\\$');
} else if (wrapper instanceof MustacheTagWrapper || wrapper instanceof RawMustacheTagWrapper) {
literal.quasis.push(state.quasi);
literal.expressions.push(wrapper.node.expression.manipulate(block));
@ -1173,7 +1202,7 @@ function to_html(wrappers: Array<ElementWrapper | TextWrapper | MustacheTagWrapp
// Two or more leading newlines are required to restore the leading newline immediately after `<pre>`.
// see https://html.spec.whatwg.org/multipage/grouping-content.html#the-pre-element
const first = wrapper.fragment.nodes[0];
if (first && first.node.type === 'Text' && start_newline.test(first.node.data)) {
if (first && first.node.type === 'Text' && regex_starts_with_newline.test(first.node.data)) {
state.quasi.value.raw += '\n';
}
}
@ -1185,7 +1214,7 @@ function to_html(wrappers: Array<ElementWrapper | TextWrapper | MustacheTagWrapp
// Two or more leading newlines are required to restore the leading newline immediately after `<textarea>`.
// see https://html.spec.whatwg.org/multipage/syntax.html#element-restrictions
const first = value_attribute.node.chunks[0];
if (first && first.type === 'Text' && start_newline.test(first.data)) {
if (first && first.type === 'Text' && regex_starts_with_newline.test(first.data)) {
state.quasi.value.raw += '\n';
}
to_html_for_attr_value(value_attribute, block, literal, state);

@ -21,6 +21,7 @@ import Block from '../Block';
import { trim_start, trim_end } from '../../../utils/trim';
import { link } from '../../../utils/link';
import { Identifier } from 'estree';
import { regex_starts_with_whitespace } from '../../../utils/patterns';
const wrappers = {
AwaitBlock,
@ -64,7 +65,7 @@ export default class FragmentWrapper {
this.nodes = [];
let last_child: Wrapper;
let window_wrapper;
let window_wrapper: Window | undefined;
let i = nodes.length;
while (i--) {
@ -92,7 +93,7 @@ export default class FragmentWrapper {
// *unless* there is no whitespace between this node and its next sibling
if (this.nodes.length === 0) {
const should_trim = (
next_sibling ? (next_sibling.node.type === 'Text' && /^\s/.test(next_sibling.node.data) && trimmable_at(child, next_sibling)) : !child.has_ancestor('EachBlock')
next_sibling ? (next_sibling.node.type === 'Text' && regex_starts_with_whitespace.test(next_sibling.node.data) && trimmable_at(child, next_sibling)) : !child.has_ancestor('EachBlock')
);
if (should_trim && !child.keep_space()) {

@ -33,10 +33,10 @@ export default class HeadWrapper extends Wrapper {
}
render(block: Block, _parent_node: Identifier, _parent_nodes: Identifier) {
let nodes;
let nodes: Identifier;
if (this.renderer.options.hydratable && this.fragment.nodes.length) {
nodes = block.get_unique_name('head_nodes');
block.chunks.claim.push(b`const ${nodes} = @query_selector_all('[data-svelte="${this.node.id}"]', @_document.head);`);
block.chunks.claim.push(b`const ${nodes} = @head_selector('${this.node.id}', @_document.head);`);
}
this.fragment.render(block, x`@_document.head` as unknown as Identifier, nodes);

@ -13,6 +13,8 @@ import { Identifier, Node } from 'estree';
import { push_array } from '../../../utils/push_array';
import { add_const_tags, add_const_tags_context } from './shared/add_const_tags';
type DetachingOrNull = 'detaching' | null;
function is_else_if(node: ElseBlock) {
return (
node && node.children.length === 1 && node.children[0].type === 'IfBlock'
@ -213,7 +215,7 @@ export default class IfBlockWrapper extends Wrapper {
const vars = { name, anchor, if_exists_condition, has_else, has_transitions };
const detaching = parent_node && !is_head(parent_node) ? null : 'detaching';
const detaching: DetachingOrNull = parent_node && !is_head(parent_node) ? null : 'detaching';
if (this.node.else) {
this.branches.forEach(branch => {
@ -275,9 +277,9 @@ export default class IfBlockWrapper extends Wrapper {
block: Block,
parent_node: Identifier,
_parent_nodes: Identifier,
dynamic,
dynamic: boolean,
{ name, anchor, has_else, if_exists_condition, has_transitions },
detaching
detaching: DetachingOrNull
) {
const select_block_type = this.renderer.component.get_unique_name('select_block_type');
const current_block_type = block.get_unique_name('current_block_type');
@ -414,9 +416,9 @@ export default class IfBlockWrapper extends Wrapper {
block: Block,
parent_node: Identifier,
_parent_nodes: Identifier,
dynamic,
dynamic: boolean,
{ name, anchor, has_else, has_transitions, if_exists_condition },
detaching
detaching: DetachingOrNull
) {
const select_block_type = this.renderer.component.get_unique_name('select_block_type');
const current_block_type_index = block.get_unique_name('current_block_type_index');
@ -428,8 +430,8 @@ export default class IfBlockWrapper extends Wrapper {
const if_ctx = select_block_ctx ? x`${select_block_ctx}(#ctx, ${current_block_type_index})` : x`#ctx`;
const if_current_block_type_index = has_else
? nodes => nodes
: nodes => b`if (~${current_block_type_index}) { ${nodes} }`;
? (nodes: Node[]) => nodes
: (nodes: Node[]) => b`if (~${current_block_type_index}) { ${nodes} }`;
block.add_variable(current_block_type_index);
block.add_variable(name);
@ -593,9 +595,9 @@ export default class IfBlockWrapper extends Wrapper {
block: Block,
parent_node: Identifier,
_parent_nodes: Identifier,
dynamic,
dynamic: boolean,
{ name, anchor, if_exists_condition, has_transitions },
detaching
detaching: DetachingOrNull
) {
const branch = this.branches[0];
const if_ctx = branch.get_ctx_name ? x`${branch.get_ctx_name}(#ctx)` : x`#ctx`;

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

Loading…
Cancel
Save