Merge remote-tracking branch 'upstream/master' into onMount-type-prevent-async-function-return

pull/8136/head
Yuichiro Yamashita 4 years ago
commit 5522a357b0

@ -1,6 +1,6 @@
### Before submitting the PR, please make sure you do the following
- [ ] It's really useful if your PR references an issue where it is discussed ahead of time. In many cases, features are absent for a reason. For large changes, please create an RFC: https://github.com/sveltejs/rfcs
- [ ] Prefix your PR title with `[feat]`, `[fix]`, `[chore]`, or `[docs]`.
- [ ] Prefix your PR title with `feat:`, `fix:`, `chore:`, or `docs:`.
- [ ] This message body should clearly illustrate what problems it solves.
- [ ] Ideally, include a test that fails without this PR but passes with it.

@ -46,7 +46,7 @@ jobs:
timeout-minutes: 15
strategy:
matrix:
node-version: [8, 10, 12, 14, 16]
node-version: [8, 10, 12, 14, 16, 18]
os: [ubuntu-latest, windows-latest, macOS-latest]
steps:
- uses: actions/checkout@v3
@ -59,6 +59,16 @@ jobs:
id: download-artifact
with:
name: build-assets
- name: Get Node version ${{ runner.os }}
run: echo "NODE_VERSION=`node --version`" >> $GITHUB_ENV
if: runner.os != 'Windows'
- name: Get Node version ${{ runner.os }}
run: |
chcp 65001
echo ("NODE_VERSION=$(node --version)") >> $env:GITHUB_ENV
if: runner.os == 'Windows'
- run: npm install --save-dev puppeteer@13
if: ${{ runner.os == 'Linux' && (!startsWith(env.NODE_VERSION, 'v8.') && !startsWith(env.NODE_VERSION, 'v10.')) }}
- run: npm install
env:
SKIP_PREPARE: true

@ -1,5 +1,33 @@
# Svelte changelog
## Unreleased
* Add a11y warnings:
* `aria-activedescendant-has-tabindex`: elements with `aria-activedescendant` need to have a `tabindex` ([#8172](https://github.com/sveltejs/svelte/pull/8172))
*
* Omit a11y warning on `<video>` tags with `aria-hidden="true"` ([#7874](https://github.com/sveltejs/svelte/issues/7874))
* Omit a11y "no child content" warning on elements with `aria-label` ([#8299](https://github.com/sveltejs/svelte/pull/8299))
* Make `noreferrer` warning less zealous ([#6289](https://github.com/sveltejs/svelte/issues/6289))
* `trusted-types` CSP compatibility for Web Components ([#8134](https://github.com/sveltejs/svelte/issues/8134))
* Add `data-sveltekit-replacestate` and `data-sveltekit-keepfocus` attribute typings ([#8281](https://github.com/sveltejs/svelte/issues/8281))
* Don't throw when calling `unsubscribe` twice ([#8186](https://github.com/sveltejs/svelte/pull/8186))
* Detect unused empty attribute CSS selectors ([#8042](https://github.com/sveltejs/svelte/issues/8042))
* Simpler output for reactive statements if dependencies are all static ([#7942](https://github.com/sveltejs/svelte/pull/7942))
* Flush remaining `afterUpdate` calls before `onDestroy` ([#7476](https://github.com/sveltejs/svelte/issues/7476))
## 3.55.1
* Fix `draw` transition with delay showing a dot at the beginning of the path ([#6816](https://github.com/sveltejs/svelte/issues/6816))
* Fix infinity runtime call stack when propagating bindings ([#7032](https://github.com/sveltejs/svelte/issues/7032))
* Fix static `<svelte:element>` optimization in production mode ([#7937](https://github.com/sveltejs/svelte/issues/7937))
* Fix `svelte-ignore` comment breaking named slot ([#8075](https://github.com/sveltejs/svelte/issues/8075))
* Revert change to prevent running init binding unnecessarily ([#8103](https://github.com/sveltejs/svelte/issues/8103))
* Fix adding duplicate event listeners with `<svelte:element on:event>` ([#8129](https://github.com/sveltejs/svelte/issues/8129))
* Improve detection of promises that are also functions ([#8162](https://github.com/sveltejs/svelte/pull/8162))
* Avoid mutating spread component props during SSR ([#8171](https://github.com/sveltejs/svelte/issues/8171))
* Add missing typing for global `part` attribute ([#8181](https://github.com/sveltejs/svelte/issues/8181))
* Add missing `submitter` property to `on:submit` event type
## 3.55.0
* Add `svelte/elements` for HTML/Svelte typings ([#7649](https://github.com/sveltejs/svelte/pull/7649))
@ -1025,7 +1053,7 @@ Also:
## 3.5.1
* Accommodate webpack idiosyncracies
* Accommodate webpack idiosyncrasies
## 3.5.0

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

@ -84,7 +84,7 @@ export interface DOMAttributes<T extends EventTarget> {
'on:beforeinput'?: EventHandler<InputEvent, T> | undefined | null;
'on:input'?: FormEventHandler<T> | undefined | null;
'on:reset'?: FormEventHandler<T> | undefined | null;
'on:submit'?: EventHandler<Event, T> | undefined | null; // TODO make this SubmitEvent once we require TS>=4.4
'on:submit'?: EventHandler<Event & { readonly submitter: HTMLElement | null; }, T> | undefined | null; // TODO make this SubmitEvent once we require TS>=4.4
'on:invalid'?: EventHandler<Event, T> | undefined | null;
'on:formdata'?: EventHandler<Event & { readonly formData: FormData; }, T> | undefined | null; // TODO make this FormDataEvent once we require TS>=4.4
@ -478,6 +478,7 @@ export interface HTMLAttributes<T extends EventTarget> extends AriaAttributes, D
hidden?: boolean | undefined | null;
id?: string | undefined | null;
lang?: string | undefined | null;
part?: string | undefined | null;
placeholder?: string | undefined | null;
slot?: string | undefined | null;
spellcheck?: Booleanish | undefined | null;
@ -539,10 +540,12 @@ export interface HTMLAttributes<T extends EventTarget> extends AriaAttributes, D
'bind:textContent'?: string | undefined | null;
// SvelteKit
'data-sveltekit-keepfocus'?: true | '' | 'off' | undefined | null;
'data-sveltekit-noscroll'?: true | '' | 'off' | undefined | null;
'data-sveltekit-preload-code'?: true | '' | 'eager' | 'viewport' | 'hover' | 'tap' | 'off' | undefined | null;
'data-sveltekit-preload-data'?: true | '' | 'hover' | 'tap' | 'off' | undefined | null;
'data-sveltekit-reload'?: true | '' | 'off' | undefined | null;
'data-sveltekit-replacestate'?: true | '' | 'off' | undefined | null;
}
export type HTMLAttributeAnchorTarget =

@ -3,8 +3,12 @@
const { execSync } = require('child_process');
const { readFileSync, writeFileSync } = require('fs');
try {
execSync('tsc -p src/compiler --emitDeclarationOnly && tsc -p src/runtime --emitDeclarationOnly');
} catch (err) {
console.error(err.stderr.toString());
throw err;
}
// We need to add these types to the .d.ts files here because if we add them before building, the build will fail,
// because the TS->JS transformation doesn't know these exports are types and produces code that fails at runtime.
// We can't use `export type` syntax either because the TS version we're on doesn't have this feature yet.

28
package-lock.json generated

@ -1,12 +1,12 @@
{
"name": "svelte",
"version": "3.55.0",
"version": "3.55.1",
"lockfileVersion": 2,
"requires": true,
"packages": {
"": {
"name": "svelte",
"version": "3.55.0",
"version": "3.55.1",
"license": "MIT",
"devDependencies": {
"@ampproject/remapping": "^0.3.0",
@ -3410,9 +3410,9 @@
"dev": true
},
"node_modules/json5": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/json5/-/json5-1.0.1.tgz",
"integrity": "sha512-aKS4WQjPenRxiQsC93MNfjx+nbF4PAdYzmd/1JIj8HYzqfbu86beTuNgXDzPknWk0n0uARlyewZo4s++ES36Ow==",
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/json5/-/json5-1.0.2.tgz",
"integrity": "sha512-g1MWMLBiz8FKi1e4w0UyVL3w+iJceWAFBAaBnnGKOpNa5f8TLktkbre1+s6oICydWAm+HRUGTmI+//xv2hvXYA==",
"dev": true,
"dependencies": {
"minimist": "^1.2.0"
@ -4138,9 +4138,9 @@
}
},
"node_modules/qs": {
"version": "6.5.2",
"resolved": "https://registry.npmjs.org/qs/-/qs-6.5.2.tgz",
"integrity": "sha512-N5ZAX4/LxJmF+7wN74pUD6qAh9/wnvdQcjq9TZjevvXzSUo7bfmw91saqMjzGS2xq91/odN2dW/WOl7qQHNDGA==",
"version": "6.5.3",
"resolved": "https://registry.npmjs.org/qs/-/qs-6.5.3.tgz",
"integrity": "sha512-qxXIEh4pCGfHICj1mAJQ2/2XVZkjCDTcEgfoSQxc/fYivUZxTkk7L3bDBJSoNrEzXI17oUO5Dp07ktqE5KzczA==",
"dev": true,
"engines": {
"node": ">=0.6"
@ -7854,9 +7854,9 @@
"dev": true
},
"json5": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/json5/-/json5-1.0.1.tgz",
"integrity": "sha512-aKS4WQjPenRxiQsC93MNfjx+nbF4PAdYzmd/1JIj8HYzqfbu86beTuNgXDzPknWk0n0uARlyewZo4s++ES36Ow==",
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/json5/-/json5-1.0.2.tgz",
"integrity": "sha512-g1MWMLBiz8FKi1e4w0UyVL3w+iJceWAFBAaBnnGKOpNa5f8TLktkbre1+s6oICydWAm+HRUGTmI+//xv2hvXYA==",
"dev": true,
"requires": {
"minimist": "^1.2.0"
@ -8432,9 +8432,9 @@
}
},
"qs": {
"version": "6.5.2",
"resolved": "https://registry.npmjs.org/qs/-/qs-6.5.2.tgz",
"integrity": "sha512-N5ZAX4/LxJmF+7wN74pUD6qAh9/wnvdQcjq9TZjevvXzSUo7bfmw91saqMjzGS2xq91/odN2dW/WOl7qQHNDGA==",
"version": "6.5.3",
"resolved": "https://registry.npmjs.org/qs/-/qs-6.5.3.tgz",
"integrity": "sha512-qxXIEh4pCGfHICj1mAJQ2/2XVZkjCDTcEgfoSQxc/fYivUZxTkk7L3bDBJSoNrEzXI17oUO5Dp07ktqE5KzczA==",
"dev": true
},
"queue-microtask": {

@ -1,6 +1,6 @@
{
"name": "svelte",
"version": "3.55.0",
"version": "3.55.1",
"description": "Cybernetically enhanced web apps",
"module": "index.mjs",
"main": "index",

@ -147,7 +147,7 @@ Any top-level statement (i.e. not inside a block or a function) can be made reac
```sv
<script>
export let title;
export let person
export let person;
// this will update `document.title` whenever
// the `title` prop changes

@ -206,6 +206,7 @@ Additional conditions can be added with `{:else if expression}`, optionally endi
{/if}
```
(Blocks don't have to wrap elements, they can also wrap text within elements!)
### {#each ...}
@ -663,7 +664,7 @@ A `<select>` value binding corresponds to the `value` property on the selected `
---
A `<select multiple>` element behaves similarly to a checkbox group.
A `<select multiple>` element behaves similarly to a checkbox group. The bound variable is an array with an entry corresponding to the `value` property of each selected `<option>`.
```sv
<select multiple bind:value={fillings}>
@ -1024,7 +1025,7 @@ Like actions, transitions can have parameters.
Transitions can use custom functions. If the returned object has a `css` function, Svelte will create a CSS animation that plays on the element.
The `t` argument passed to `css` is a value between `0` and `1` after the `easing` function has been applied. *In* transitions run from `0` to `1`, *out* transitions run from `1` to `0` in other words `1` is the element's natural state, as though no transition had been applied. The `u` argument is equal to `1 - t`.
The `t` argument passed to `css` is a value between `0` and `1` after the `easing` function has been applied. *In* transitions run from `0` to `1`, *out* transitions run from `1` to `0` in other words, `1` is the element's natural state, as though no transition had been applied. The `u` argument is equal to `1 - t`.
The function is called repeatedly *before* the transition begins, with different `t` and `u` arguments.
@ -1311,9 +1312,7 @@ A custom animation function can also return a `tick` function, which is called *
duration: Math.sqrt(d) * 120,
easing: cubicOut,
tick: (t, u) =>
Object.assign(node.style, {
color: t > 0.5 ? 'Pink' : 'Blue'
});
Object.assign(node.style, { color: t > 0.5 ? 'Pink' : 'Blue' })
};
}
</script>
@ -1415,7 +1414,7 @@ Svelte's CSS Variables support allows for easily themeable components:
---
So you can set a high level theme color:
So you can set a high-level theme color:
```css
/* global.css */
@ -1575,7 +1574,7 @@ Note that explicitly passing in an empty named slot will add that slot's name to
---
Slots can be rendered zero or more times, and can pass values *back* to the parent using props. The parent exposes the values to the slot template using the `let:` directive.
Slots can be rendered zero or more times and can pass values *back* to the parent using props. The parent exposes the values to the slot template using the `let:` directive.
The usual shorthand rules apply — `let:item` is equivalent to `let:item={item}`, and `<slot {item}>` is equivalent to `<slot item={item}>`.
@ -1666,11 +1665,11 @@ 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) do 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.
If `this` is the name of a void tag (e.g., `br`) and `<svelte:element>` has child elements, a runtime error will be thrown in development mode.
If `this` is the name of a [void element](https://developer.mozilla.org/en-US/docs/Glossary/Void_element) (e.g., `br`) and `<svelte:element>` has child elements, a runtime error will be thrown in development mode.
```sv
<script>
@ -1716,7 +1715,7 @@ You can also bind to the following properties:
* `outerHeight`
* `scrollX`
* `scrollY`
* `online` — an alias for window.navigator.onLine
* `online` — an alias for `window.navigator.onLine`
All except `scrollX` and `scrollY` are readonly.

@ -698,7 +698,7 @@ out:fly={params}
---
Animates the x and y positions and the opacity of an element. `in` transitions animate from an element's current (default) values to the provided values, passed as parameters. `out` transitions animate from the provided values to an element's default values.
Animates the x and y positions and the opacity of an element. `in` transitions animate from the provided values, passed as parameters to the element's default values. `out` transitions animate from the element's default values to the provided values.
`fly` accepts the following parameters:

@ -19,6 +19,18 @@ Enforce no `accesskey` on element. Access keys are HTML attributes that allow we
---
### `a11y-aria-activedescendant-has-tabindex`
An element with `aria-activedescendant` must be tabbable, so it must either have an inherent `tabindex` or declare `tabindex` as an attribute.
```sv
<!-- A11y: Elements with attribute aria-activedescendant should have tabindex value -->
<div aria-activedescendant="some-id" />
```
---
### `a11y-aria-attributes`
Certain reserved DOM elements do not support ARIA roles, states and properties. This is often because they are not visible, for example `meta`, `html`, `script`, `style`. This rule enforces that these DOM elements do not contain the `aria-*` props.
@ -268,7 +280,7 @@ Some HTML elements have default ARIA roles. Giving these elements an ARIA role t
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 -->
<!-- A11y: noninteractive element cannot have nonnegative tabIndex value -->
<div tabindex='0' />
```

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

@ -1,80 +1,62 @@
<script>
import { createEventDispatcher, onDestroy } from 'svelte';
export let showModal; // boolean
const dispatch = createEventDispatcher();
const close = () => dispatch('close');
let dialog; // HTMLDialogElement
let modal;
const handle_keydown = e => {
if (e.key === 'Escape') {
close();
return;
}
if (e.key === 'Tab') {
// trap focus
const nodes = modal.querySelectorAll('*');
const tabbable = Array.from(nodes).filter(n => n.tabIndex >= 0);
let index = tabbable.indexOf(document.activeElement);
if (index === -1 && e.shiftKey) index = 0;
index += tabbable.length + (e.shiftKey ? -1 : 1);
index %= tabbable.length;
tabbable[index].focus();
e.preventDefault();
}
};
const previously_focused = typeof document !== 'undefined' && document.activeElement;
if (previously_focused) {
onDestroy(() => {
previously_focused.focus();
});
}
$: if (dialog && showModal) dialog.showModal();
</script>
<svelte:window on:keydown={handle_keydown}/>
<div class="modal-background" on:click={close}></div>
<div class="modal" role="dialog" aria-modal="true" bind:this={modal}>
<slot name="header"></slot>
<hr>
<slot></slot>
<hr>
<!-- svelte-ignore a11y-click-events-have-key-events -->
<dialog
bind:this={dialog}
on:close={() => (showModal = false)}
on:click|self={() => dialog.close()}
>
<div on:click|stopPropagation>
<slot name="header" />
<hr />
<slot />
<hr />
<!-- svelte-ignore a11y-autofocus -->
<button autofocus on:click={close}>close modal</button>
<button autofocus on:click={() => dialog.close()}>close modal</button>
</div>
</dialog>
<style>
.modal-background {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
dialog {
max-width: 32em;
border-radius: 0.2em;
border: none;
padding: 0;
}
dialog::backdrop {
background: rgba(0, 0, 0, 0.3);
}
.modal {
position: absolute;
left: 50%;
top: 50%;
width: calc(100vw - 4em);
max-width: 32em;
max-height: calc(100vh - 4em);
overflow: auto;
transform: translate(-50%,-50%);
dialog > div {
padding: 1em;
border-radius: 0.2em;
background: white;
}
dialog[open] {
animation: zoom 0.3s cubic-bezier(0.34, 1.56, 0.64, 1);
}
@keyframes zoom {
from {
transform: scale(0.95);
}
to {
transform: scale(1);
}
}
dialog[open]::backdrop {
animation: fade 0.2s ease-out;
}
@keyframes fade {
from {
opacity: 0;
}
to {
opacity: 1;
}
}
button {
display: block;
}

@ -2,12 +2,20 @@
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.
How your application is structured and where logic is defined will determine the best way to ensure it is properly tested. It is important to note that not all logic belongs within a component - this includes concerns such as data transformation, cross-component state management, and logging, among others. Remember that the Svelte library has its own test suite, so you do not need to write tests to validate 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, WebdriverIO or Cypress.
A Svelte application will typically have three different types of tests: Unit, Component, and End-to-End (E2E).
Some resources for getting started with unit testing:
*Unit Tests*: Focus on testing business logic in isolation. Often this is validating individual functions and edge cases. By minimizing the surface area of these tests they can be kept lean and fast, and by extracting as much logic as possible from your Svelte components more of your application can be covered using them. When creating a new SvelteKit project, you will be asked whether you would like to setup [Vitest](https://vitest.dev/) for unit testing. There are a number of other test runners that could be used as well.
*Component Tests*: Validating that a Svelte component mounts and interacts as expected throughout its lifecycle requires a tool that provides a Document Object Model (DOM). Components can be compiled (since Svelte is a compiler and not a normal library) and mounted to allow asserting against element structure, listeners, state, and all the other capabilities provided by a Svelte component. Tools for component testing range from an in-memory implementation like jsdom paired with a test runner like [Vitest](https://vitest.dev/) to solutions that leverage an actual browser to provide a visual testing capability such as [Playwright](https://playwright.dev/docs/test-components) or [Cypress](https://www.cypress.io/).
*End-to-End Tests*: To ensure your users are able to interact with your application it is necessary to test it as a whole in a manner as close to production as possible. This is done by writing end-to-end (E2E) tests which load and interact with a deployed version of your application in order to simulate how the user will interact with your application. When creating a new SvelteKit project, you will be asked whether you would like to setup [Playwright](https://playwright.dev/) for end-to-end testing. There are many other E2E test libraries available for use as well.
Some resources for getting started with testing:
- [Svelte Testing Library](https://testing-library.com/docs/svelte-testing-library/example/)
- [Svelte Component Testing in Cypress](https://docs.cypress.io/guides/component-testing/svelte/overview)
- [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)
- [Test Svelte components using Vitest & Playwright](https://davipon.hashnode.dev/test-svelte-component-using-vitest-playwright)
- [Component testing with WebdriverIO](https://webdriver.io/docs/component-testing/svelte)

@ -23,7 +23,7 @@ function addNumber() {
}
```
The same rule applies to array methods such as `pop`, `shift`, and `splice` and to objects methods such as `Map.set`, `Set.add`, etc.
The same rule applies to array methods such as `pop`, `shift`, and `splice` and to object methods such as `Map.set`, `Set.add`, etc.
Assignments to *properties* of arrays and objects — e.g. `obj.foo += 1` or `array[i] = x` — work the same way as assignments to the values themselves.

@ -1,4 +1,6 @@
<script>
import { onDestroy } from 'svelte';
const emojis = {
apple: "🍎",
banana: "🍌",
@ -12,6 +14,11 @@
// ...but the "emoji" variable is fixed upon initialisation of the component
const emoji = emojis[name];
// observe in the console which entry is removed
onDestroy(() => {
console.log('thing destroyed: ' + name)
});
</script>
<p>

@ -1,4 +1,6 @@
<script>
import { onDestroy } from 'svelte';
const emojis = {
apple: "🍎",
banana: "🍌",
@ -12,6 +14,11 @@
// ...but the "emoji" variable is fixed upon initialisation of the component
const emoji = emojis[name];
// observe in the console which entry is removed
onDestroy(() => {
console.log('thing destroyed: ' + name)
});
</script>
<p>

@ -18,6 +18,7 @@ export function longpress(node, duration) {
return {
destroy() {
clearTimeout(timer);
node.removeEventListener('mousedown', handleMousedown);
node.removeEventListener('mouseup', handleMouseup);
}

@ -21,6 +21,7 @@ export function longpress(node, duration) {
duration = newDuration;
},
destroy() {
clearTimeout(timer);
node.removeEventListener('mousedown', handleMousedown);
node.removeEventListener('mouseup', handleMouseup);
}

@ -4,21 +4,23 @@
export let todo;
let div;
let button;
afterUpdate(() => {
flash(div);
flash(button);
});
</script>
<!-- the text will flash red whenever
the `todo` object changes -->
<div bind:this={div} on:click>
<button bind:this={button} type="button" on:click>
{todo.done ? '👍': ''} {todo.text}
</div>
</button>
<style>
div {
button {
all: unset;
display: block;
cursor: pointer;
line-height: 1.5;
}

@ -6,21 +6,23 @@
export let todo;
let div;
let button;
afterUpdate(() => {
flash(div);
flash(button);
});
</script>
<!-- the text will flash red whenever
the `todo` object changes -->
<div bind:this={div} on:click>
<button bind:this={button} type="button" on:click>
{todo.done ? '👍': ''} {todo.text}
</div>
</button>
<style>
div {
button {
all: unset;
display: block;
cursor: pointer;
line-height: 1.5;
}

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

@ -12,4 +12,4 @@ In Svelte, you do this with the special `{@html ...}` tag:
<p>{@html string}</p>
```
> Svelte doesn't perform any sanitization of the expression inside `{@html ...}` before it gets inserted into the DOM. In other words, if you use this feature it's critical that you manually escape HTML that comes from sources you don't trust, otherwise you risk exposing your users to XSS attacks.
> **Warning!** Svelte doesn't perform any sanitization of the expression inside `{@html ...}` before it gets inserted into the DOM. In other words, if you use this feature it's **critical** that you manually escape HTML that comes from sources you don't trust, otherwise you risk exposing your users to XSS attacks.

@ -0,0 +1,3 @@
{
"title": "Special tags"
}

@ -38,6 +38,7 @@ import compiler_warnings from './compiler_warnings';
import compiler_errors from './compiler_errors';
import { extract_ignores_above_position, extract_svelte_ignore_from_comments } from '../utils/extract_svelte_ignore';
import check_enable_sourcemap from './utils/check_enable_sourcemap';
import is_dynamic from './render_dom/wrappers/shared/is_dynamic';
interface ComponentOptions {
namespace?: string;
@ -1380,12 +1381,11 @@ export default class Component {
module_dependencies.add(name);
}
}
const is_writable_or_mutated =
variable && (variable.writable || variable.mutated);
if (
should_add_as_dependency &&
(!owner || owner === component.instance_scope) &&
(name[0] === '$' || is_writable_or_mutated)
(name[0] === '$' || variable)
) {
dependencies.add(name);
}
@ -1409,6 +1409,19 @@ export default class Component {
const { expression } = node.body as ExpressionStatement;
const declaration = expression && (expression as AssignmentExpression).left;
const is_dependency_static = Array.from(dependencies).every(
dependency => dependency !== '$$props' && dependency !== '$$restProps' && !is_dynamic(this.var_lookup.get(dependency))
);
if (is_dependency_static) {
assignees.forEach(assignee => {
const variable = component.var_lookup.get(assignee);
if (variable) {
variable.is_reactive_static = true;
}
});
}
unsorted_reactive_declarations.push({
assignees,
dependencies,

@ -44,7 +44,7 @@ export default {
code: 'invalid-binding',
message: 'Cannot bind to a variable declared with {@const ...}'
},
invalid_binding_writibale: {
invalid_binding_writable: {
code: 'invalid-binding',
message: 'Cannot bind to a variable which is not writable'
},

@ -185,7 +185,11 @@ export default {
}),
a11y_no_noninteractive_tabindex: {
code: 'a11y-no-noninteractive-tabindex',
message: 'A11y: noninteractive element cannot have positive tabIndex value'
message: 'A11y: noninteractive element cannot have nonnegative tabIndex value'
},
a11y_aria_activedescendant_has_tabindex: {
code: 'a11y-aria-activedescendant-has-tabindex',
message: 'A11y: Elements with attribute aria-activedescendant should have tabindex value'
},
redundant_event_modifier_for_touch: {
code: 'redundant-event-modifier',

@ -350,7 +350,7 @@ function attribute_matches(node: CssNode, name: string, expected_value: string,
const attr = node.attributes.find((attr: CssNode) => attr.name === name);
if (!attr) return false;
if (attr.is_true) return operator === null;
if (!expected_value) return true;
if (expected_value == null) return true;
if (attr.chunks.length === 1) {
const value = attr.chunks[0];

@ -80,7 +80,7 @@ export default class Binding extends Node {
variable[this.expression.node.type === 'MemberExpression' ? 'mutated' : 'reassigned'] = true;
if (info.expression.type === 'Identifier' && !variable.writable) {
component.error(this.expression.node as any, compiler_errors.invalid_binding_writibale);
component.error(this.expression.node as any, compiler_errors.invalid_binding_writable);
return;
}
}

@ -225,6 +225,7 @@ export default class Element extends Node {
namespace: string;
needs_manual_style_scoping: boolean;
tag_expr: Expression;
contains_a11y_label: boolean;
get is_dynamic_element() {
return this.name === 'svelte:element';
@ -239,6 +240,7 @@ export default class Element extends Node {
this.tag_expr = new Expression(component, this, scope, info.tag);
} else {
this.tag_expr = new Expression(component, this, scope, string_literal(info.tag) as Literal);
this.name = info.tag;
}
} else {
this.tag_expr = new Expression(component, this, scope, string_literal(this.name) as Literal);
@ -483,6 +485,11 @@ export default class Element extends Node {
component.warn(attribute, compiler_warnings.a11y_incorrect_attribute_type(schema, name));
}
}
// aria-activedescendant-has-tabindex
if (name === 'aria-activedescendant' && !is_interactive_element(this.name, attribute_map) && !attribute_map.has('tabindex')) {
component.warn(attribute, compiler_warnings.a11y_aria_activedescendant_has_tabindex);
}
}
// aria-role
@ -619,27 +626,36 @@ export default class Element extends Node {
const id_attribute = attribute_map.get('id');
const name_attribute = attribute_map.get('name');
const target_attribute = attribute_map.get('target');
const aria_label_attribute = attribute_map.get('aria-label');
if (target_attribute && target_attribute.get_static_value() === '_blank' && href_attribute) {
// links with target="_blank" should have noopener or noreferrer: https://developer.chrome.com/docs/lighthouse/best-practices/external-anchors-use-rel-noopener/
// modern browsers add noopener by default, so we only need to check legacy browsers
// legacy browsers don't support noopener so we only check for noreferrer there
if (component.compile_options.legacy && 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) {
if (!rel || !rel_values.includes('noreferrer')) {
component.warn(this, {
code: `security-anchor-rel-${expected_value}`,
message: `Security: Anchor with "target=_blank" should have rel attribute containing the value "${expected_value}"`
code: 'security-anchor-rel-noreferrer',
message:
'Security: Anchor with "target=_blank" should have rel attribute containing the value "noreferrer"'
});
}
});
}
}
}
if (aria_label_attribute) {
const aria_value = aria_label_attribute.get_static_value();
if (aria_value != '') {
this.contains_a11y_label = true;
}
}
if (href_attribute) {
const href_value = href_attribute.get_static_value();
@ -716,7 +732,10 @@ export default class Element extends Node {
}
if (this.name === 'video') {
if (attribute_map.has('muted')) {
const aria_hidden_attribute = attribute_map.get('aria-hidden');
const aria_hidden_exist = aria_hidden_attribute && aria_hidden_attribute.get_static_value();
if (attribute_map.has('muted') || aria_hidden_exist === 'true') {
return;
}
@ -920,6 +939,7 @@ export default class Element extends Node {
validate_content() {
if (!a11y_required_content.has(this.name)) return;
if (this.contains_a11y_label) return;
if (
this.bindings
.some((binding) => ['textContent', 'innerHTML'].includes(binding.name))
@ -1032,14 +1052,14 @@ export default class Element extends Node {
}
}
const regex_starts_with_vovel = /^[aeiou]/;
const regex_starts_with_vowel = /^[aeiou]/;
function should_have_attribute(
node,
attributes: string[],
name = node.name
) {
const article = regex_starts_with_vovel.test(attributes[0]) ? 'an' : 'a';
const article = regex_starts_with_vowel.test(attributes[0]) ? 'an' : 'a';
const sequence = attributes.length > 1 ?
attributes.slice(0, -1).join(', ') + ` or ${attributes[attributes.length - 1]}` :
attributes[0];

@ -143,6 +143,8 @@ export default class InlineComponent extends Node {
children.push(slot_template);
info.children.splice(i, 1);
} else if (child.type === 'Comment' && children.length > 0) {
children[children.length - 1].children.unshift(child);
}
}

@ -390,13 +390,13 @@ export default function dom(
const resubscribable_reactive_store_unsubscribers = reactive_stores
.filter(store => {
const variable = component.var_lookup.get(store.name.slice(1));
return variable && (variable.reassigned || variable.export_name);
return variable && (variable.reassigned || variable.export_name) && !variable.is_reactive_static;
})
.map(({ name }) => b`$$self.$$.on_destroy.push(() => ${`$$unsubscribe_${name.slice(1)}`}());`);
if (has_definition) {
const reactive_declarations: (Node | Node[]) = [];
const fixed_reactive_declarations: Node[] = []; // not really 'reactive' but whatever
const reactive_declarations: Node[] = [];
const fixed_reactive_declarations: Array<Node | Node[]> = []; // not really 'reactive' but whatever
component.reactive_declarations.forEach(d => {
const dependencies = Array.from(d.dependencies);
@ -417,6 +417,15 @@ export default function dom(
reactive_declarations.push(statement);
} else {
fixed_reactive_declarations.push(statement);
for (const assignee of d.assignees) {
const variable = component.var_lookup.get(assignee);
if (variable && variable.subscribable) {
fixed_reactive_declarations.push(b`
${component.compile_options.dev && b`@validate_store(${assignee}, '${assignee}');`}
@component_subscribe($$self, ${assignee}, $$value => $$invalidate(${renderer.context_lookup.get('$' + assignee).index}, ${'$' + assignee} = $$value));
`);
}
}
}
});
@ -430,7 +439,7 @@ export default function dom(
const name = $name.slice(1);
const store = component.var_lookup.get(name);
if (store && (store.reassigned || store.export_name)) {
if (store && (store.reassigned || store.export_name) && !store.is_reactive_static) {
const unsubscribe = `$$unsubscribe_${name}`;
const subscribe = `$$subscribe_${name}`;
const i = renderer.context_lookup.get($name).index;
@ -531,7 +540,10 @@ export default function dom(
constructor(options) {
super();
${css.code && b`this.shadowRoot.innerHTML = \`<style>${css.code.replace(regex_backslashes, '\\\\')}${css_sourcemap_enabled && options.dev ? `\n/*# sourceMappingURL=${css.map.toUrl()} */` : ''}</style>\`;`}
${css.code && b`
const style = document.createElement('style');
style.textContent = \`${css.code.replace(regex_backslashes, '\\\\')}${css_sourcemap_enabled && options.dev ? `\n/*# sourceMappingURL=${css.map.toUrl()} */` : ''}\`
this.shadowRoot.appendChild(style)`}
@init(this, { target: this.shadowRoot, props: ${init_props}, customElement: true }, ${definition}, ${has_create_fragment ? 'create_fragment' : 'null'}, ${not_equal}, ${prop_indexes}, null, ${dirty});

@ -19,6 +19,7 @@ export function invalidate(renderer: Renderer, scope: Scope, node: Node, names:
!variable.hoistable &&
!variable.global &&
!variable.module &&
!variable.is_reactive_static &&
(
variable.referenced ||
variable.subscribable ||

@ -170,6 +170,15 @@ export default class ElementWrapper extends Wrapper {
) {
super(renderer, block, parent, node);
this.var = {
type: 'Identifier',
name: node.name.replace(regex_invalid_variable_identifier_characters, '_')
};
this.void = is_void(node.name);
this.class_dependencies = [];
if (node.is_dynamic_element && block.type !== CHILD_DYNAMIC_ELEMENT_BLOCK) {
this.child_dynamic_element_block = block.child({
comment: create_debugging_comment(node, renderer.component),
@ -185,16 +194,13 @@ export default class ElementWrapper extends Wrapper {
strip_whitespace,
next_sibling
);
}
this.var = {
type: 'Identifier',
name: node.name.replace(regex_invalid_variable_identifier_characters, '_')
};
this.void = is_void(node.name);
this.class_dependencies = [];
// the original svelte:element is never used for rendering, because
// it gets assigned a child_dynamic_element which is used in all rendering logic.
// so doing all of this on the original svelte:element will just cause double
// code, because it will be done again on the child_dynamic_element.
return;
}
if (this.node.children.length) {
this.node.lets.forEach(l => {
@ -255,6 +261,7 @@ export default class ElementWrapper extends Wrapper {
node.styles.length > 0 ||
this.node.name === 'option' ||
node.tag_expr.dynamic_dependencies().length ||
node.is_dynamic_element ||
renderer.options.dev
) {
this.parent.cannot_use_innerhtml(); // need to use add_location
@ -326,8 +333,7 @@ export default class ElementWrapper extends Wrapper {
${this.var}.p(#ctx, #dirty);
}
} else if (${previous_tag}) {
${
has_transitions
${has_transitions
? b`
@group_outros();
@transition_out(${this.var}, 1, 1, () => {
@ -1176,10 +1182,12 @@ function to_html(wrappers: Array<ElementWrapper | TextWrapper | MustacheTagWrapp
} else if (wrapper.node.name === 'noscript') {
// do nothing
} else {
const nodeName = wrapper.node.name;
// element
state.quasi.value.raw += `<${wrapper.node.name}`;
state.quasi.value.raw += `<${nodeName}`;
const is_empty_textarea = wrapper.node.name === 'textarea' && wrapper.fragment.nodes.length === 0;
const is_empty_textarea = nodeName === 'textarea' && wrapper.fragment.nodes.length === 0;
(wrapper as ElementWrapper).attributes.forEach((attr: AttributeWrapper) => {
if (is_empty_textarea && attr.node.name === 'value') {
@ -1196,7 +1204,7 @@ function to_html(wrappers: Array<ElementWrapper | TextWrapper | MustacheTagWrapp
if (!wrapper.void) {
state.quasi.value.raw += '>';
if (wrapper.node.name === 'pre') {
if (nodeName === 'pre') {
// 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];
@ -1221,7 +1229,7 @@ function to_html(wrappers: Array<ElementWrapper | TextWrapper | MustacheTagWrapp
to_html(wrapper.fragment.nodes as Array<ElementWrapper | TextWrapper>, block, literal, state);
state.quasi.value.raw += `</${wrapper.node.name}>`;
state.quasi.value.raw += `</${nodeName}>`;
} else {
state.quasi.value.raw += '/>';
}

@ -393,7 +393,7 @@ export default class InlineComponentWrapper extends Wrapper {
component.partly_hoisted.push(body);
return b`@binding_callbacks.push(() => @bind(${this.var}, '${binding.name}', ${id}, ${snippet}));`;
return b`@binding_callbacks.push(() => @bind(${this.var}, '${binding.name}', ${id}));`;
});
const munged_handlers = this.node.handlers.map(handler => {

@ -1,4 +1,4 @@
import { namespaces } from './../../../utils/namespaces';
import { namespaces } from '../../../utils/namespaces';
import { b, x } from 'code-red';
import Renderer from '../Renderer';
import Block from '../Block';

@ -36,7 +36,7 @@ export default function(node: InlineComponent, renderer: Renderer, options: Rend
let props;
if (uses_spread) {
props = x`@_Object.assign(${
props = x`@_Object.assign({}, ${
node.attributes
.map(attribute => {
if (attribute.is_spread) {

@ -223,6 +223,7 @@ export interface Var {
subscribable?: boolean;
is_reactive_dependency?: boolean;
imported?: boolean;
is_reactive_static?: boolean;
}
export interface CssResult {

@ -132,6 +132,10 @@ export class Parser {
return this.template.slice(this.index, this.index + str.length) === str;
}
/**
* Match a regex at the current index
* @param pattern Should have a ^ anchor at the start so the regex doesn't search past the beginning, resulting in worse performance
*/
match_regex(pattern: RegExp) {
const match = pattern.exec(this.template.slice(this.index));
if (!match || match.index !== 0) return null;
@ -148,6 +152,10 @@ export class Parser {
}
}
/**
* Search for a regex starting at the current index and return the result if it matches
* @param pattern Should have a ^ anchor at the start so the regex doesn't search past the beginning, resulting in worse performance
*/
read(pattern: RegExp) {
const result = this.match_regex(pattern);
if (result) this.index += result.length;

@ -6,6 +6,7 @@ import parser_errors from '../errors';
import { regex_not_newline_characters } from '../../utils/patterns';
const regex_closing_script_tag = /<\/script\s*>/;
const regex_starts_with_closing_script_tag = /^<\/script\s*>/;
function get_context(parser: Parser, attributes: any[], start: number): string {
const context = attributes.find(attribute => attribute.name === 'context');
@ -32,7 +33,7 @@ export default function read_script(parser: Parser, start: number, attributes: N
}
const source = parser.template.slice(0, script_start).replace(regex_not_newline_characters, ' ') + data;
parser.read(regex_closing_script_tag);
parser.read(regex_starts_with_closing_script_tag);
let ast: Program;

@ -7,6 +7,7 @@ import { Style } from '../../interfaces';
import parser_errors from '../errors';
const regex_closing_style_tag = /<\/style\s*>/;
const regex_starts_with_closing_style_tag = /^<\/style\s*>/;
export default function read_style(parser: Parser, start: number, attributes: Node[]): Style {
const content_start = parser.index;
@ -21,7 +22,7 @@ export default function read_style(parser: Parser, start: number, attributes: No
// discard styles when css is disabled
if (parser.css_mode === 'none') {
parser.read(regex_closing_style_tag);
parser.read(regex_starts_with_closing_style_tag);
return null;
}
@ -76,7 +77,7 @@ export default function read_style(parser: Parser, start: number, attributes: No
}
});
parser.read(regex_closing_style_tag);
parser.read(regex_starts_with_closing_style_tag);
const end = parser.index;

@ -33,7 +33,7 @@ function trim_whitespace(block: TemplateNode, trim_before: boolean, trim_after:
}
}
const regex_whitespace_with_closing_curly_brace = /\s*}/;
const regex_whitespace_with_closing_curly_brace = /^\s*}/;
export default function mustache(parser: Parser) {
const start = parser.index;

@ -12,6 +12,9 @@ import { closing_tag_omitted, decode_character_references } from '../utils/html'
// eslint-disable-next-line no-useless-escape
const valid_tag_name = /^\!?[a-zA-Z]{1,}:?[a-zA-Z0-9\-]*/;
/** Invalid attribute characters if the attribute is not surrounded by quotes */
const regex_starts_with_invalid_attr_value = /^(\/>|[\s"'=<>`])/;
const meta_tags = new Map([
['svelte:head', 'Head'],
['svelte:options', 'Options'],
@ -293,7 +296,7 @@ function read_tag_name(parser: Parser) {
// eslint-disable-next-line no-useless-escape
const regex_token_ending_character = /[\s=\/>"']/;
const regex_quote_characters = /["']/;
const regex_starts_with_quote_characters = /^["']/;
function read_attribute(parser: Parser, unique_names: Set<string>) {
const start = parser.index;
@ -368,7 +371,7 @@ function read_attribute(parser: Parser, unique_names: Set<string>) {
parser.allow_whitespace();
value = read_attribute_value(parser);
end = parser.index;
} else if (parser.match_regex(regex_quote_characters)) {
} else if (parser.match_regex(regex_starts_with_quote_characters)) {
parser.error(parser_errors.unexpected_token('='), parser.index);
}
@ -475,15 +478,13 @@ function read_attribute_value(parser: Parser) {
}];
}
const regex = (
quote_mark === "'" ? /'/ :
quote_mark === '"' ? /"/ :
/(\/>|[\s"'=<>`])/
);
let value;
try {
value = read_sequence(parser, () => !!parser.match_regex(regex), 'in attribute value');
value = read_sequence(parser, () => {
// handle common case of quote marks existing outside of regex for performance reasons
if (quote_mark) return parser.match(quote_mark);
return !!parser.match_regex(regex_starts_with_invalid_attr_value);
}, 'in attribute value');
} catch (error) {
if (error.code === 'parse-error') {
// if the attribute value didn't close + self-closing tag

@ -1,19 +1,17 @@
import { add_render_callback, flush, schedule_update, dirty_components } from './scheduler';
import { add_render_callback, flush, flush_render_callbacks, schedule_update, dirty_components } from './scheduler';
import { current_component, set_current_component } from './lifecycle';
import { blank_object, is_empty, is_function, run, run_all, noop } from './utils';
import { children, detach, start_hydrating, end_hydrating } from './dom';
import { transition_in } from './transitions';
import { T$$ } from './types';
export function bind(component, name, callback, value) {
export function bind(component, name, callback) {
const index = component.$$.props[name];
if (index !== undefined) {
component.$$.bound[index] = callback;
if (value === undefined) {
callback(component.$$.ctx[index]);
}
}
}
export function create_component(block) {
block && block.c();
@ -53,6 +51,8 @@ export function mount_component(component, target, anchor, customElement) {
export function destroy_component(component, detaching) {
const $$ = component.$$;
if ($$.fragment !== null) {
flush_render_callbacks($$.after_update);
run_all($$.on_destroy);
$$.fragment && $$.fragment.d(detaching);

@ -5,7 +5,7 @@ export const dirty_components = [];
export const intros = { enabled: false };
export const binding_callbacks = [];
const render_callbacks = [];
let render_callbacks = [];
const flush_callbacks = [];
const resolved_promise = Promise.resolve();
@ -52,17 +52,32 @@ export function add_flush_callback(fn) {
const seen_callbacks = new Set();
let flushidx = 0; // Do *not* move this inside the flush() function
export function flush() {
// Do not reenter flush while dirty components are updated, as this can
// result in an infinite loop. Instead, let the inner flush handle it.
// Reentrancy is ok afterwards for bindings etc.
if (flushidx !== 0) {
return;
}
const saved_component = current_component;
do {
// first, call beforeUpdate functions
// and update components
try {
while (flushidx < dirty_components.length) {
const component = dirty_components[flushidx];
flushidx++;
set_current_component(component);
update(component.$$);
}
} catch (e) {
// reset dirty state to not end up in a deadlocked state and then rethrow
dirty_components.length = 0;
flushidx = 0;
throw e;
}
set_current_component(null);
dirty_components.length = 0;
@ -107,3 +122,14 @@ function update($$) {
$$.after_update.forEach(add_render_callback);
}
}
/**
* Useful for example to execute remaining `afterUpdate` callbacks before executing `destroy`.
*/
export function flush_render_callbacks(fns: Function[]): void {
const filtered = [];
const targets = [];
render_callbacks.forEach((c) => fns.indexOf(c) === -1 ? filtered.push(c) : targets.push(c));
targets.forEach((c) => c());
render_callbacks = filtered;
}

@ -10,8 +10,10 @@ export function assign<T, S>(tar: T, src: S): T & S {
return tar as T & S;
}
// Adapted from https://github.com/then/is-promise/blob/master/index.js
// Distributed under MIT License https://github.com/then/is-promise/blob/master/LICENSE
export function is_promise<T = any>(value: any): value is PromiseLike<T> {
return value && typeof value === 'object' && typeof value.then === 'function';
return !!value && (typeof value === 'object' || typeof value === 'function') && typeof value.then === 'function';
}
export function add_location(element, file, line, column, char) {

@ -98,7 +98,7 @@ export function writable<T>(value?: T, start: StartStopNotifier<T> = noop): Writ
return () => {
subscribers.delete(subscriber);
if (subscribers.size === 0) {
if (subscribers.size === 0 && stop) {
stop();
stop = null;
}

@ -198,7 +198,10 @@ export function draw(node: SVGElement & { getTotalLength(): number }, {
delay,
duration,
easing,
css: (t, u) => `stroke-dasharray: ${t * len} ${u * len}`
css: (_, u) => `
stroke-dasharray: ${len};
stroke-dashoffset: ${u * len};
`
};
}

@ -0,0 +1,25 @@
export default {
warnings: [{
filename: 'SvelteComponent.svelte',
code: 'css-unused-selector',
message: 'Unused CSS selector "img[alt=""]"',
start: {
character: 87,
column: 1,
line: 8
},
end: {
character: 98,
column: 12,
line: 8
},
pos: 87,
frame: `
6: }
7:
8: img[alt=""] {
^
9: border: 1px solid red;
10: }`
}]
};

@ -0,0 +1 @@
img[alt].svelte-xyz{border:1px solid green}

@ -0,0 +1 @@
<img alt="a foo" class="svelte-xyz" src="foo.jpg">

@ -0,0 +1,11 @@
<img src="foo.jpg" alt="a foo" />
<style>
img[alt] {
border: 1px solid green;
}
img[alt=""] {
border: 1px solid red;
}
</style>

@ -64,6 +64,9 @@ describe('custom-elements', function() {
fs.readdirSync(`${__dirname}/samples`).forEach(dir => {
if (dir[0] === '.') return;
// MEMO: puppeteer can not execute Chromium properly with Node8,10 on Linux at GitHub actions.
const { version } = process;
if ((version.startsWith('v8.') || version.startsWith('v10.')) && process.platform === 'linux') return;
const solo = /\.solo$/.test(dir);
const skip = /\.skip$/.test(dir);

@ -48,7 +48,7 @@ function create_fragment(ctx) {
t8 = text(/*$prop*/ ctx[2]);
t9 = space();
t10 = text(/*shadowedByModule*/ ctx[4]);
add_location(p, file, 22, 0, 430);
add_location(p, file, 22, 0, 431);
},
l: function claim(nodes) {
throw new Error("options.hydrate only works if the component was compiled with the `hydratable: true` option");
@ -91,7 +91,7 @@ function create_fragment(ctx) {
}
let moduleLiveBinding;
const moduleContantProps = 4;
const moduleConstantProps = 4;
let moduleLet;
const moduleConst = 2;
let shadowedByModule;
@ -137,7 +137,7 @@ function instance($$self, $$props, $$invalidate) {
$$self.$capture_state = () => ({
moduleLiveBinding,
moduleContantProps,
moduleConstantProps,
moduleLet,
moduleConst,
shadowedByModule,
@ -197,4 +197,4 @@ class Component extends SvelteComponentDev {
}
export default Component;
export { moduleLiveBinding, moduleContantProps };
export { moduleLiveBinding, moduleConstantProps };

@ -1,6 +1,6 @@
<script context="module">
export let moduleLiveBinding;
export const moduleContantProps = 4;
export const moduleConstantProps = 4;
let moduleLet;
const moduleConst = 2;
let shadowedByModule;

@ -34,7 +34,9 @@ function create_fragment(ctx) {
class Component extends SvelteElement {
constructor(options) {
super();
this.shadowRoot.innerHTML = `<style>div{animation:foo 1s}@keyframes foo{0%{opacity:0}100%{opacity:1}}</style>`;
const style = document.createElement('style');
style.textContent = `div{animation:foo 1s}@keyframes foo{0%{opacity:0}100%{opacity:1}}`;
this.shadowRoot.appendChild(style);
init(
this,

@ -9,7 +9,6 @@ import {
noop,
safe_not_equal,
space,
subscribe,
toggle_class
} from "svelte/internal";
@ -133,13 +132,8 @@ let reactiveModuleVar = Math.random();
function instance($$self, $$props, $$invalidate) {
let reactiveDeclaration;
let $reactiveStoreVal;
let $reactiveDeclaration,
$$unsubscribe_reactiveDeclaration = noop,
$$subscribe_reactiveDeclaration = () => ($$unsubscribe_reactiveDeclaration(), $$unsubscribe_reactiveDeclaration = subscribe(reactiveDeclaration, $$value => $$invalidate(3, $reactiveDeclaration = $$value)), reactiveDeclaration);
let $reactiveDeclaration;
component_subscribe($$self, reactiveStoreVal, $$value => $$invalidate(2, $reactiveStoreVal = $$value));
$$self.$$.on_destroy.push(() => $$unsubscribe_reactiveDeclaration());
nonReactiveGlobal = Math.random();
const reactiveConst = { x: Math.random() };
reactiveModuleVar += 1;
@ -148,7 +142,8 @@ function instance($$self, $$props, $$invalidate) {
reactiveConst.x += 1;
}
$: $$subscribe_reactiveDeclaration($$invalidate(1, reactiveDeclaration = reactiveModuleVar * 2));
$: reactiveDeclaration = reactiveModuleVar * 2;
component_subscribe($$self, reactiveDeclaration, $$value => $$invalidate(3, $reactiveDeclaration = $$value));
return [reactiveConst, reactiveDeclaration, $reactiveStoreVal, $reactiveDeclaration];
}

@ -0,0 +1,60 @@
/* generated by Svelte vX.Y.Z */
import {
SvelteComponent,
detach,
element,
init,
insert,
noop,
safe_not_equal,
set_data,
space,
text
} from "svelte/internal";
function create_fragment(ctx) {
let h1;
let t3;
let t4;
return {
c() {
h1 = element("h1");
h1.textContent = `Hello ${name}!`;
t3 = space();
t4 = text(/*foo*/ ctx[0]);
},
m(target, anchor) {
insert(target, h1, anchor);
insert(target, t3, anchor);
insert(target, t4, anchor);
},
p(ctx, [dirty]) {
if (dirty & /*foo*/ 1) set_data(t4, /*foo*/ ctx[0]);
},
i: noop,
o: noop,
d(detaching) {
if (detaching) detach(h1);
if (detaching) detach(t3);
if (detaching) detach(t4);
}
};
}
let name = 'world';
function instance($$self) {
let foo;
$: foo = name + name;
return [foo];
}
class Component extends SvelteComponent {
constructor(options) {
super();
init(this, options, instance, create_fragment, safe_not_equal, {});
}
}
export default Component;

@ -0,0 +1,7 @@
<script>
let name = 'world';
$: foo = name + name;
</script>
<h1>Hello {name}!</h1>
{foo}

@ -0,0 +1,171 @@
/* generated by Svelte vX.Y.Z */
import {
SvelteComponent,
append,
assign,
bubble,
detach,
element,
empty,
get_spread_update,
init,
insert,
listen,
noop,
run_all,
safe_not_equal,
set_attributes,
set_custom_element_data_map
} from "svelte/internal";
function create_dynamic_element(ctx) {
let svelte_element1;
let svelte_element0;
let mounted;
let dispose;
let svelte_element0_levels = [{ class: "inner" }];
let svelte_element0_data = {};
for (let i = 0; i < svelte_element0_levels.length; i += 1) {
svelte_element0_data = assign(svelte_element0_data, svelte_element0_levels[i]);
}
let svelte_element1_levels = [{ class: "outer" }];
let svelte_element1_data = {};
for (let i = 0; i < svelte_element1_levels.length; i += 1) {
svelte_element1_data = assign(svelte_element1_data, svelte_element1_levels[i]);
}
return {
c() {
svelte_element1 = element(a);
svelte_element0 = element(span);
if ((/-/).test(span)) {
set_custom_element_data_map(svelte_element0, svelte_element0_data);
} else {
set_attributes(svelte_element0, svelte_element0_data);
}
if ((/-/).test(a)) {
set_custom_element_data_map(svelte_element1, svelte_element1_data);
} else {
set_attributes(svelte_element1, svelte_element1_data);
}
},
m(target, anchor) {
insert(target, svelte_element1, anchor);
append(svelte_element1, svelte_element0);
if (!mounted) {
dispose = [
listen(svelte_element0, "keydown", /*keydown_handler_1*/ ctx[2]),
listen(svelte_element0, "keyup", /*keyup_handler_1*/ ctx[3]),
listen(svelte_element1, "keydown", /*keydown_handler*/ ctx[0]),
listen(svelte_element1, "keyup", /*keyup_handler*/ ctx[1])
];
mounted = true;
}
},
p(ctx, dirty) {
svelte_element0_data = get_spread_update(svelte_element0_levels, [{ class: "inner" }]);
if ((/-/).test(span)) {
set_custom_element_data_map(svelte_element0, svelte_element0_data);
} else {
set_attributes(svelte_element0, svelte_element0_data);
}
svelte_element1_data = get_spread_update(svelte_element1_levels, [{ class: "outer" }]);
if ((/-/).test(a)) {
set_custom_element_data_map(svelte_element1, svelte_element1_data);
} else {
set_attributes(svelte_element1, svelte_element1_data);
}
},
d(detaching) {
if (detaching) detach(svelte_element1);
mounted = false;
run_all(dispose);
}
};
}
function create_fragment(ctx) {
let previous_tag = a;
let svelte_element_anchor;
let svelte_element = a && create_dynamic_element(ctx);
return {
c() {
if (svelte_element) svelte_element.c();
svelte_element_anchor = empty();
},
m(target, anchor) {
if (svelte_element) svelte_element.m(target, anchor);
insert(target, svelte_element_anchor, anchor);
},
p(ctx, [dirty]) {
if (a) {
if (!previous_tag) {
svelte_element = create_dynamic_element(ctx);
svelte_element.c();
svelte_element.m(svelte_element_anchor.parentNode, svelte_element_anchor);
} else if (safe_not_equal(previous_tag, a)) {
svelte_element.d(1);
svelte_element = create_dynamic_element(ctx);
svelte_element.c();
svelte_element.m(svelte_element_anchor.parentNode, svelte_element_anchor);
} else {
svelte_element.p(ctx, dirty);
}
} else if (previous_tag) {
svelte_element.d(1);
svelte_element = null;
}
previous_tag = a;
},
i: noop,
o: noop,
d(detaching) {
if (detaching) detach(svelte_element_anchor);
if (svelte_element) svelte_element.d(detaching);
}
};
}
const a = 'a';
const span = 'span';
function instance($$self) {
function keydown_handler(event) {
bubble.call(this, $$self, event);
}
function keyup_handler(event) {
bubble.call(this, $$self, event);
}
function keydown_handler_1(event) {
bubble.call(this, $$self, event);
}
function keyup_handler_1(event) {
bubble.call(this, $$self, event);
}
return [keydown_handler, keyup_handler, keydown_handler_1, keyup_handler_1];
}
class Component extends SvelteComponent {
constructor(options) {
super();
init(this, options, instance, create_fragment, safe_not_equal, {});
}
}
export default Component;

@ -0,0 +1,8 @@
<script>
const a = 'a';
const span = 'span';
</script>
<svelte:element this={a} class='outer' on:keydown on:keyup>
<svelte:element this={span} class='inner' on:keydown on:keyup />
</svelte:element>

@ -0,0 +1,41 @@
/* generated by Svelte vX.Y.Z */
import {
SvelteComponent,
attr,
detach,
element,
init,
insert,
noop,
safe_not_equal
} from "svelte/internal";
function create_fragment(ctx) {
let a;
return {
c() {
a = element("a");
a.innerHTML = `<span class="inner"></span>`;
attr(a, "class", "outer");
},
m(target, anchor) {
insert(target, a, anchor);
},
p: noop,
i: noop,
o: noop,
d(detaching) {
if (detaching) detach(a);
}
};
}
class Component extends SvelteComponent {
constructor(options) {
super();
init(this, options, null, create_fragment, safe_not_equal, {});
}
}
export default Component;

@ -0,0 +1,3 @@
<svelte:element this='a' class='outer'>
<svelte:element this='span' class='inner' />
</svelte:element>

@ -14,11 +14,6 @@ import {
svg_element
} from "svelte/internal";
function create_dynamic_element_1(ctx) {
return { c: noop, m: noop, p: noop, d: noop };
}
// (1:0) <svelte:element this="svg" xmlns="http://www.w3.org/2000/svg">
function create_dynamic_element(ctx) {
let svelte_element1;
let svelte_element0;
@ -38,8 +33,8 @@ function create_dynamic_element(ctx) {
return {
c() {
svelte_element1 = svg_element("svg");
svelte_element0 = svg_element("path");
svelte_element1 = svg_element(/*tag*/ ctx[0].svg);
svelte_element0 = svg_element(/*tag*/ ctx[0].path);
set_svg_attributes(svelte_element0, svelte_element0_data);
set_svg_attributes(svelte_element1, svelte_element1_data);
},
@ -60,53 +55,58 @@ function create_dynamic_element(ctx) {
}
function create_fragment(ctx) {
let previous_tag = "svg";
let svelte_element1_anchor;
let svelte_element1 = "svg" && create_dynamic_element(ctx);
let previous_tag = /*tag*/ ctx[0].svg;
let svelte_element_anchor;
let svelte_element = /*tag*/ ctx[0].svg && create_dynamic_element(ctx);
return {
c() {
if (svelte_element1) svelte_element1.c();
svelte_element1_anchor = empty();
if (svelte_element) svelte_element.c();
svelte_element_anchor = empty();
},
m(target, anchor) {
if (svelte_element1) svelte_element1.m(target, anchor);
insert(target, svelte_element1_anchor, anchor);
if (svelte_element) svelte_element.m(target, anchor);
insert(target, svelte_element_anchor, anchor);
},
p(ctx, [dirty]) {
if ("svg") {
if (/*tag*/ ctx[0].svg) {
if (!previous_tag) {
svelte_element1 = create_dynamic_element(ctx);
svelte_element1.c();
svelte_element1.m(svelte_element1_anchor.parentNode, svelte_element1_anchor);
} else if (safe_not_equal(previous_tag, "svg")) {
svelte_element1.d(1);
svelte_element1 = create_dynamic_element(ctx);
svelte_element1.c();
svelte_element1.m(svelte_element1_anchor.parentNode, svelte_element1_anchor);
svelte_element = create_dynamic_element(ctx);
svelte_element.c();
svelte_element.m(svelte_element_anchor.parentNode, svelte_element_anchor);
} else if (safe_not_equal(previous_tag, /*tag*/ ctx[0].svg)) {
svelte_element.d(1);
svelte_element = create_dynamic_element(ctx);
svelte_element.c();
svelte_element.m(svelte_element_anchor.parentNode, svelte_element_anchor);
} else {
svelte_element1.p(ctx, dirty);
svelte_element.p(ctx, dirty);
}
} else if (previous_tag) {
svelte_element1.d(1);
svelte_element1 = null;
svelte_element.d(1);
svelte_element = null;
}
previous_tag = "svg";
previous_tag = /*tag*/ ctx[0].svg;
},
i: noop,
o: noop,
d(detaching) {
if (detaching) detach(svelte_element1_anchor);
if (svelte_element1) svelte_element1.d(detaching);
if (detaching) detach(svelte_element_anchor);
if (svelte_element) svelte_element.d(detaching);
}
};
}
function instance($$self) {
const tag = { svg: 'svg', path: 'path' };
return [tag];
}
class Component extends SvelteComponent {
constructor(options) {
super();
init(this, options, null, create_fragment, safe_not_equal, {});
init(this, options, instance, create_fragment, safe_not_equal, {});
}
}

@ -1,3 +1,7 @@
<svelte:element this="svg" xmlns="http://www.w3.org/2000/svg">
<svelte:element this="path" xmlns="http://www.w3.org/2000/svg"></svelte:element>
<script>
const tag = { svg: 'svg', path: 'path' };
</script>
<svelte:element this={tag.svg} xmlns="http://www.w3.org/2000/svg">
<svelte:element this={tag.path} xmlns="http://www.w3.org/2000/svg" />
</svelte:element>

@ -77,6 +77,9 @@ describe('runtime (puppeteer)', function() {
function runTest(dir, hydrate) {
if (dir[0] === '.') return;
// MEMO: puppeteer can not execute Chromium properly with Node8,10 on Linux at GitHub actions.
const { version } = process;
if ((version.startsWith('v8.') || version.startsWith('v10.')) && process.platform === 'linux') return;
const config = loadConfig(`${__dirname}/samples/${dir}/_config.js`);
const solo = config.solo || /\.solo/.test(dir);

@ -0,0 +1,27 @@
<script>
import { afterUpdate, onDestroy } from "svelte";
export let id;
export let items;
let item = $items[id];
let selected = true;
function onClick() {
selected = !selected;
items.set({});
}
onDestroy(() => {
console.log("onDestroy");
});
afterUpdate(() => {
console.log("afterUpdate");
});
</script>
<button on:click="{onClick}">Click Me</button>
{#if selected}
<div>{item.id}</div>
{/if}

@ -0,0 +1,16 @@
export default {
html: `
<button>Click Me</button>
<div>1</div>
`,
async test({ assert, target, window }) {
const button = target.querySelector('button');
const event = new window.MouseEvent('click');
const messages = [];
const log = console.log;
console.log = msg => messages.push(msg);
await button.dispatchEvent(event);
console.log = log;
assert.deepEqual(messages, ['afterUpdate', 'onDestroy']);
}
};

@ -0,0 +1,10 @@
<script>
import { writable } from 'svelte/store';
import Component from "./Component.svelte";
let items = writable({ 1: { id: 1 } });
</script>
{#each Object.values($items) as item (item.id)}
<Component id="{item.id}" {items} />
{/each}

@ -0,0 +1,19 @@
const realPromise = Promise.resolve(42);
const promise = () => {};
promise.then = realPromise.then.bind(realPromise);
promise.catch = realPromise.catch.bind(realPromise);
export default {
props: {
promise
},
test({ assert, target }) {
return promise.then(() => {
assert.htmlEqual(target.innerHTML, `
<p>42</p>
`);
});
}
};

@ -0,0 +1,7 @@
<script>
export let promise;
</script>
{#await promise then value}
<p>{JSON.stringify(value)}</p>
{/await}

@ -0,0 +1,6 @@
<script>
export let value;
value = "bar";
</script>
Child component "{value}"<br />

@ -1,7 +1,8 @@
export default {
async test({ assert, target }) {
assert.htmlEqual(target.innerHTML, `
<p>0</p>
Parent component "bar"<br />
Child component "bar"<br />
`);
}
};

@ -0,0 +1,8 @@
<script>
import Component from "./Component.svelte";
let value = "foo";
</script>
Parent component "{value}"<br />
<Component bind:value />

@ -0,0 +1,10 @@
// this test currently fails because the fix that made it pass broke other tests,
// see https://github.com/sveltejs/svelte/pull/8114 for more context.
export default {
skip: true,
async test({ assert, target }) {
assert.htmlEqual(target.innerHTML, `
<p>0</p>
`);
}
};

@ -0,0 +1,15 @@
const obj = {
x: 1,
y: 2,
z: 3
};
export default {
props: {
obj
},
test({ assert }) {
assert.deepEqual(obj, { x: 1, y: 2, z: 3 });
}
};

@ -0,0 +1,7 @@
<script>
import Widget from './Widget.svelte';
export let obj;
</script>
<Widget {...obj} x={2} />

@ -0,0 +1,13 @@
export default {
html: `
<div>
<p></p>
</div>
`,
test({ assert, target }) {
const p = target.querySelector('p');
assert.notEqual(p, undefined);
}
};

@ -0,0 +1,3 @@
<div>
<svelte:element this="p" />
</div>

@ -0,0 +1,13 @@
export default {
html: `
<div>
<p></p>
</div>
`,
test({ assert, target }) {
const p = target.querySelector('p');
assert.notEqual(p, undefined);
}
};

@ -0,0 +1,7 @@
<script>
const p = 'p';
</script>
<div>
<svelte:element this={p} />
</div>

@ -88,6 +88,14 @@ describe('store', () => {
unsubscribe();
});
it('no error even if unsubscribe calls twice', () => {
let num = 0;
const store = writable(num, set => set(num += 1));
const unsubscribe = store.subscribe(() => { });
unsubscribe();
assert.doesNotThrow(() => unsubscribe());
});
});
describe('readable', () => {

@ -0,0 +1,17 @@
<!-- VALID -->
<input />
<input tabindex="0" />
<input aria-activedescendant="some-id" />
<input aria-activedescendant="some-id" tabindex={0} />
<input aria-activedescendant="some-id" tabindex={1} />
<input aria-activedescendant="some-id" tabindex="0" />
<input aria-activedescendant="some-id" tabindex={-1} />
<input aria-activedescendant="some-id" tabindex="-1" />
<div />
<div aria-activedescendant="some-id" role="tablist" tabindex={-1} />
<div aria-activedescendant="some-id" role="tablist" tabindex="-1" />
<!-- INVALID -->
<div aria-activedescendant="some-id" />

@ -0,0 +1,17 @@
[
{
"code": "a11y-aria-activedescendant-has-tabindex",
"end": {
"character": 568,
"column": 36,
"line": 16
},
"message": "A11y: Elements with attribute aria-activedescendant should have tabindex value",
"pos": 537,
"start": {
"character": 537,
"column": 5,
"line": 16
}
}
]

@ -2,3 +2,6 @@
<video></video>
<video><track /></video>
<audio></audio>
<video aria-hidden></video>
<video aria-hidden="false"></video>
<video aria-hidden="true"></video>

@ -28,5 +28,35 @@
"column": 0,
"line": 3
}
},
{
"code": "a11y-media-has-caption",
"end": {
"character": 124,
"column": 27,
"line": 5
},
"message": "A11y: <video> elements must have a <track kind=\"captions\">",
"pos": 97,
"start": {
"character": 97,
"column": 0,
"line": 5
}
},
{
"code": "a11y-media-has-caption",
"end": {
"character": 160,
"column": 35,
"line": 6
},
"message": "A11y: <video> elements must have a <track kind=\"captions\">",
"pos": 125,
"start": {
"character": 125,
"column": 0,
"line": 6
}
}
]

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

Loading…
Cancel
Save