Merge branch 'version-4' into tanhauhau/claim-static-html-tag-without-recreating-nested-nodes

pull/7426/head
Simon H 3 years ago committed by GitHub
commit 5a1fb9000a
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

@ -6,72 +6,29 @@ on:
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:
matrix:
node-version: [8, 10, 12, 14, 16, 18]
os: [ubuntu-latest, windows-latest, macOS-latest]
include:
- node-version: 14
os: ubuntu-latest
- node-version: 14
os: windows-latest
- node-version: 14
os: macOS-latest
- node-version: 16
os: ubuntu-latest
- node-version: 18
os: ubuntu-latest
steps:
- 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
- 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
- run: npm run test:integration
env:
CI: true
@ -89,7 +46,17 @@ jobs:
timeout-minutes: 10
strategy:
matrix:
os: [ubuntu-latest, windows-latest, macOS-latest]
include:
- node-version: 14
os: ubuntu-latest
- node-version: 14
os: windows-latest
- node-version: 14
os: macOS-latest
- node-version: 16
os: ubuntu-latest
- node-version: 18
os: ubuntu-latest
steps:
- uses: actions/checkout@v3
- uses: actions/setup-node@v3

@ -1,6 +1,17 @@
# Svelte changelog
## Unreleased
## Unreleased (4.0)
* **breaking** Minimum supported Node version is now Node 14
* **breaking** Minimum supported TypeScript version is now 5 (it will likely work with lower versions, but we make no guarantess about that)
* **breaking** Stricter types for `createEventDispatcher` (see PR for migration instructions) ([#7224](https://github.com/sveltejs/svelte/pull/7224))
* **breaking** Stricter types for `Action` and `ActionReturn` (see PR for migration instructions) ([#7224](https://github.com/sveltejs/svelte/pull/7224))
* **breaking** Stricter types for `onMount` - now throws a type error when returning a function asynchronously to catch potential mistakes around callback functions (see PR for migration instructions) ([#8136](https://github.com/sveltejs/svelte/pull/8136))
* Add `a11y no-noninteractive-element-interactions` rule ([#8391](https://github.com/sveltejs/svelte/pull/8391))
* Add `a11y-no-static-element-interactions`rule ([#8251](https://github.com/sveltejs/svelte/pull/8251))
* Bind `null` option and input values consistently ([#8312](https://github.com/sveltejs/svelte/issues/8312))
## Unreleased (3.0)
* Handle `width`/`height` attributes when spreading ([#6752](https://github.com/sveltejs/svelte/issues/6752))
* Add support for resize observer bindings (`<div bind:contentRect|contentBoxSize|borderBoxSize|devicePixelContentBoxSize>`) ([#8022](https://github.com/sveltejs/svelte/pull/8022))

@ -1,23 +0,0 @@
// This script generates the TypeScript definitions
const { execSync } = require('child_process');
const { readFileSync, writeFileSync } = require('fs');
execSync('tsc -p src/compiler --emitDeclarationOnly && tsc -p src/runtime --emitDeclarationOnly', { stdio: 'inherit' });
// 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.
function modify(path, modifyFn) {
const content = readFileSync(path, 'utf8');
writeFileSync(path, modifyFn(content));
}
modify(
'types/runtime/index.d.ts',
content => content.replace('SvelteComponentTyped', 'SvelteComponentTyped, ComponentType, ComponentConstructorOptions, ComponentProps, ComponentEvents')
);
modify(
'types/compiler/index.d.ts',
content => content + '\nexport { CompileOptions, ModuleFormat, EnableSourcemap, CssHashGetter } from "./interfaces"'
);

5829
package-lock.json generated

File diff suppressed because it is too large Load Diff

@ -86,20 +86,20 @@
}
},
"engines": {
"node": ">= 8"
"node": ">= 14"
},
"types": "types/runtime/index.d.ts",
"scripts": {
"test": "npm run test:unit && npm run test:integration",
"test": "npm run test:unit && npm run test:integration && echo \"manually check that there are no type errors in test/types by opening the files in there\"",
"test:integration": "mocha --exit",
"test:unit": "mocha --config .mocharc.unit.js --exit",
"quicktest": "mocha --exit",
"build": "rollup -c && npm run tsd",
"prepare": "node scripts/skip_in_ci.js npm run build",
"prepare": "npm run build",
"dev": "rollup -cw",
"posttest": "agadoo internal/index.mjs",
"prepublishOnly": "node check_publish_env.js && npm run lint && npm run build && npm test",
"tsd": "node ./generate-type-definitions.js",
"tsd": "tsc -p src/compiler --emitDeclarationOnly && tsc -p src/runtime --emitDeclarationOnly",
"lint": "eslint \"{src,test}/**/*.{ts,js}\" --cache"
},
"repository": {
@ -119,45 +119,45 @@
},
"homepage": "https://svelte.dev",
"devDependencies": {
"@ampproject/remapping": "^0.3.0",
"@ampproject/remapping": "^2.2.1",
"@jridgewell/sourcemap-codec": "^1.4.15",
"@rollup/plugin-commonjs": "^11.0.0",
"@rollup/plugin-commonjs": "^24.1.0",
"@rollup/plugin-json": "^6.0.0",
"@rollup/plugin-node-resolve": "^11.2.1",
"@rollup/plugin-node-resolve": "^15.0.2",
"@rollup/plugin-replace": "^5.0.2",
"@rollup/plugin-sucrase": "^3.1.0",
"@rollup/plugin-typescript": "^2.0.1",
"@rollup/plugin-sucrase": "^5.0.1",
"@rollup/plugin-typescript": "^11.1.0",
"@rollup/plugin-virtual": "^3.0.1",
"@sveltejs/eslint-config": "github:sveltejs/eslint-config#v5.8.0",
"@types/aria-query": "^5.0.1",
"@types/mocha": "^7.0.0",
"@types/node": "^8.10.53",
"@typescript-eslint/eslint-plugin": "^5.29.0",
"@typescript-eslint/parser": "^5.29.0",
"acorn": "^8.8.1",
"@types/mocha": "^10.0.1",
"@types/node": "^14.14.31",
"@typescript-eslint/eslint-plugin": "^5.58.0",
"@typescript-eslint/parser": "^5.58.0",
"acorn": "^8.8.2",
"agadoo": "^3.0.0",
"aria-query": "^5.1.3",
"axobject-query": "^3.1.1",
"code-red": "^1.0.0",
"css-tree": "^2.3.1",
"eslint": "^8.35.0",
"eslint-plugin-import": "^2.27.0",
"eslint-plugin-import": "^2.27.5",
"eslint-plugin-svelte3": "^4.0.0",
"estree-walker": "^3.0.3",
"is-reference": "^3.0.1",
"jsdom": "^15.2.1",
"jsdom": "^21.1.1",
"kleur": "^4.1.5",
"locate-character": "^2.0.5",
"magic-string": "^0.30.0",
"mocha": "^7.0.0",
"mocha": "^10.2.0",
"periscopic": "^3.1.0",
"puppeteer": "^2.0.0",
"rollup": "^1.27.14",
"puppeteer": "^19.8.5",
"rollup": "^3.20.2",
"source-map": "^0.7.4",
"source-map-support": "^0.5.21",
"tiny-glob": "^0.2.9",
"tslib": "^2.5.0",
"typescript": "^3.7.5",
"typescript": "^5.0.4",
"util": "^0.12.5"
}
}

@ -1,148 +0,0 @@
import fs from 'fs';
import replace from '@rollup/plugin-replace';
import resolve from '@rollup/plugin-node-resolve';
import commonjs from '@rollup/plugin-commonjs';
import json from '@rollup/plugin-json';
import sucrase from '@rollup/plugin-sucrase';
import typescript from '@rollup/plugin-typescript';
import pkg from './package.json';
const is_publish = !!process.env.PUBLISH;
const ts_plugin = is_publish
? typescript({
include: 'src/**',
typescript: require('typescript')
})
: sucrase({
transforms: ['typescript']
});
const external = id => id.startsWith('svelte/');
fs.writeFileSync(`./compiler.d.ts`, `export { compile, parse, preprocess, walk, VERSION } from './types/compiler/index';`);
export default [
/* runtime */
{
input: `src/runtime/index.ts`,
output: [
{
file: `index.mjs`,
format: 'esm',
paths: id => id.startsWith('svelte/') && `${id.replace('svelte', '.')}/index.mjs`
},
{
file: `index.js`,
format: 'cjs',
paths: id => id.startsWith('svelte/') && `${id.replace('svelte', '.')}/index.js`
}
],
external,
plugins: [ts_plugin]
},
{
input: `src/runtime/ssr.ts`,
output: [
{
file: `ssr.mjs`,
format: 'esm',
paths: id => id.startsWith('svelte/') && `${id.replace('svelte', '.')}/index.mjs`
},
{
file: `ssr.js`,
format: 'cjs',
paths: id => id.startsWith('svelte/') && `${id.replace('svelte', '.')}/index.js`
}
],
external,
plugins: [ts_plugin]
},
...fs.readdirSync('src/runtime')
.filter(dir => fs.statSync(`src/runtime/${dir}`).isDirectory())
.map(dir => ({
input: `src/runtime/${dir}/index.ts`,
output: [
{
file: `${dir}/index.mjs`,
format: 'esm',
paths: id => id.startsWith('svelte/') && `${id.replace('svelte', '..')}/index.mjs`
},
{
file: `${dir}/index.js`,
format: 'cjs',
paths: id => id.startsWith('svelte/') && `${id.replace('svelte', '..')}/index.js`
}
],
external,
plugins: [
replace({
__VERSION__: pkg.version
}),
ts_plugin,
{
writeBundle(bundle) {
if (dir === 'internal') {
const mod = bundle['index.mjs'];
if (mod) {
fs.writeFileSync('src/compiler/compile/internal_exports.ts', `// This file is automatically generated\nexport default new Set(${JSON.stringify(mod.exports)});`);
}
}
fs.writeFileSync(`${dir}/package.json`, JSON.stringify({
main: './index',
module: './index.mjs',
types: './index.d.ts'
}, null, ' '));
fs.writeFileSync(`${dir}/index.d.ts`, `export * from '../types/runtime/${dir}/index';`);
}
}
]
})),
/* compiler.js */
{
input: 'src/compiler/index.ts',
plugins: [
replace({
__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/**']
}),
json(),
ts_plugin
],
output: [
{
file: 'compiler.js',
format: is_publish ? 'umd' : 'cjs',
name: 'svelte',
sourcemap: true,
},
{
file: 'compiler.mjs',
format: 'esm',
name: 'svelte',
sourcemap: true,
}
],
external: is_publish
? []
: id => id === 'acorn' || id === 'magic-string' || id.startsWith('css-tree')
}
];

@ -0,0 +1,160 @@
import fs from 'node:fs';
import { createRequire } from 'node:module';
import replace from '@rollup/plugin-replace';
import resolve from '@rollup/plugin-node-resolve';
import commonjs from '@rollup/plugin-commonjs';
import json from '@rollup/plugin-json';
import sucrase from '@rollup/plugin-sucrase';
import typescript from '@rollup/plugin-typescript';
const require = createRequire(import.meta.url);
const pkg = JSON.parse(fs.readFileSync('package.json', 'utf-8'));
const is_publish = !!process.env.PUBLISH;
const ts_plugin = is_publish
? typescript({
typescript: require('typescript'),
})
: sucrase({
transforms: ['typescript'],
});
fs.writeFileSync(
`./compiler.d.ts`,
`export { compile, parse, preprocess, walk, VERSION } from './types/compiler/index.js';`
);
const runtime_entrypoints = Object.fromEntries(
fs
.readdirSync('src/runtime', { withFileTypes: true })
.filter((dirent) => dirent.isDirectory())
.map((dirent) => [dirent.name, `src/runtime/${dirent.name}/index.ts`])
);
/**
* @type {import("rollup").RollupOptions[]}
*/
export default [
{
input: {
...runtime_entrypoints,
index: 'src/runtime/index.ts',
ssr: 'src/runtime/ssr.ts'
},
output: ['es', 'cjs'].map(
/** @returns {import('rollup').OutputOptions} */
(format) => {
const ext = format === 'es' ? 'mjs' : 'js';
return {
entryFileNames: (entry) => {
if (entry.isEntry) {
if (entry.name === 'index') return `index.${ext}`;
else if (entry.name === 'ssr') return `ssr.${ext}`;
return `${entry.name}/index.${ext}`;
}
},
chunkFileNames: `internal/[name]-[hash].${ext}`,
format,
minifyInternalExports: false,
dir: '.',
};
}
),
plugins: [
replace({
preventAssignment: true,
values: {
__VERSION__: pkg.version,
},
}),
ts_plugin,
{
writeBundle(options, bundle) {
if (options.format !== 'es') return;
for (const entry of Object.values(bundle)) {
const dir = entry.name;
if (!entry.isEntry || !runtime_entrypoints[dir]) continue;
if (dir === 'internal') {
const mod = bundle[`internal/index.mjs`];
if (mod) {
fs.writeFileSync(
'src/compiler/compile/internal_exports.ts',
`// This file is automatically generated\n` +
`export default new Set(${JSON.stringify(mod.exports)});`
);
}
}
fs.writeFileSync(
`${dir}/package.json`,
JSON.stringify(
{
main: './index.js',
module: './index.mjs',
types: './index.d.ts',
},
null,
' '
)
);
fs.writeFileSync(
`${dir}/index.d.ts`,
`export * from '../types/runtime/${dir}/index.js';`
);
}
}
}
]
},
/* compiler.js */
{
input: 'src/compiler/index.ts',
plugins: [
replace({
preventAssignment: true,
values: {
__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/**']
}),
json(),
ts_plugin
],
output: [
{
file: 'compiler.js',
format: is_publish ? 'umd' : 'cjs',
name: 'svelte',
sourcemap: true,
},
{
file: 'compiler.mjs',
format: 'esm',
name: 'svelte',
sourcemap: true,
}
],
external: is_publish
? []
: (id) =>
id === 'acorn' || id === 'magic-string' || id.startsWith('css-tree')
}
];

@ -1,7 +0,0 @@
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" });
}

@ -286,7 +286,7 @@ You cannot `export default`, since the default export is the component itself.
<script context="module">
let totalComponents = 0;
// this allows an importer to do e.g.
// the export keyword allows this function to imported with e.g.
// `import Example, { alertTotal } from './Example.svelte'`
export function alertTotal() {
alert(totalComponents);

@ -288,6 +288,20 @@ Some HTML elements have default ARIA roles. Giving these elements an ARIA role t
---
### `a11y-no-noninteractive-element-interactions`
A non-interactive element does not support event handlers (mouse and key handlers). Non-interactive elements include `<main>`, `<area>`, `<h1>` (,`<h2>`, etc), `<p>`, `<img>`, `<li>`, `<ul>` and `<ol>`. Non-interactive [WAI-ARIA roles](https://www.w3.org/TR/wai-aria-1.1/#usage_intro) include `article`, `banner`, `complementary`, `img`, `listitem`, `main`, `region` and `tooltip`.
```sv
<!-- `A11y: Non-interactive element <li> should not be assigned mouse or keyboard event listeners.` -->
<li on:click={() => {}} />
<!-- `A11y: Non-interactive element <div> should not be assigned mouse or keyboard event listeners.` -->
<div role="listitem" on:click={() => {}} />
```
---
### `a11y-no-noninteractive-element-to-interactive-role`
[WAI-ARIA](https://www.w3.org/TR/wai-aria-1.1/#usage_intro) roles should not be used to convert a non-interactive element to an interactive element. Interactive ARIA roles include `button`, `link`, `checkbox`, `menuitem`, `menuitemcheckbox`, `menuitemradio`, `option`, `radio`, `searchbox`, `switch` and `textbox`.

@ -1,3 +1,4 @@
import type { DecodedSourceMap, RawSourceMap } from '@ampproject/remapping';
import { walk } from 'estree-walker';
import { getLocator } from 'locate-character';
import Stats from '../Stats';
@ -32,7 +33,6 @@ import { print, b } from 'code-red';
import { is_reserved_keyword } from './utils/reserved_keywords';
import { apply_preprocessor_sourcemap } from '../utils/mapped_code';
import Element from './nodes/Element';
import { DecodedSourceMap, RawSourceMap } from '@ampproject/remapping/dist/types/types';
import { clone } from '../utils/clone';
import compiler_warnings from './compiler_warnings';
import compiler_errors from './compiler_errors';

@ -115,10 +115,18 @@ export default {
code: 'a11y-no-redundant-roles',
message: `A11y: Redundant role '${role}'`
}),
a11y_no_static_element_interactions: (element: string, handlers: string[]) => ({
code: 'a11y-no-static-element-interactions',
message: `A11y: <${element}> with ${handlers.join(', ')} ${handlers.length === 1 ? 'handler' : 'handlers'} must have an ARIA role`
}),
a11y_no_interactive_element_to_noninteractive_role: (role: string | boolean, element: string) => ({
code: 'a11y-no-interactive-element-to-noninteractive-role',
message: `A11y: <${element}> cannot have role '${role}'`
}),
a11y_no_noninteractive_element_interactions: (element: string) => ({
code: 'a11y-no-noninteractive-element-interactions',
message: `A11y: Non-interactive element <${element}> should not be assigned mouse or keyboard event listeners.`
}),
a11y_no_noninteractive_element_to_interactive_role: (role: string | boolean, element: string) => ({
code: 'a11y-no-noninteractive-element-to-interactive-role',
message: `A11y: Non-interactive element <${element}> cannot have interactive role '${role}'`

@ -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 { is_name_contenteditable, get_contenteditable_attr } from '../utils/contenteditable';
import { is_name_contenteditable, get_contenteditable_attr, has_contenteditable_attr } from '../utils/contenteditable';
import { regex_dimensions, regex_starts_with_newline, regex_non_whitespace_character, regex_box_size } from '../../utils/patterns';
import fuzzymatch from '../../utils/fuzzymatch';
import list from '../../utils/list';
@ -103,6 +103,15 @@ const a11y_interactive_handlers = new Set([
'mouseup'
]);
const a11y_recommended_interactive_handlers = new Set([
'click',
'mousedown',
'mouseup',
'keypress',
'keydown',
'keyup'
]);
const a11y_nested_implicit_semantics = new Map([
['header', 'banner'],
['footer', 'contentinfo']
@ -758,8 +767,12 @@ export default class Element extends Node {
}
}
const role = attribute_map.get('role');
const role_static_value = role?.get_static_value() as ARIARoleDefinitionKey;
const role_value = (role ? role_static_value : get_implicit_role(this.name, attribute_map)) as ARIARoleDefinitionKey;
// no-noninteractive-tabindex
if (!this.is_dynamic_element && !is_interactive_element(this.name, attribute_map) && !is_interactive_roles(attribute_map.get('role')?.get_static_value() as ARIARoleDefinitionKey)) {
if (!this.is_dynamic_element && !is_interactive_element(this.name, attribute_map) && !is_interactive_roles(role_static_value)) {
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);
@ -767,8 +780,6 @@ export default class Element extends Node {
}
// role-supports-aria-props
const role = attribute_map.get('role');
const role_value = (role ? role.get_static_value() : get_implicit_role(this.name, attribute_map)) as ARIARoleDefinitionKey;
if (typeof role_value === 'string' && roles.has(role_value)) {
const { props } = roles.get(role_value);
const invalid_aria_props = new Set(aria.keys().filter(attribute => !(attribute in props)));
@ -782,6 +793,45 @@ export default class Element extends Node {
}
});
}
// no-noninteractive-element-interactions
if (
!has_contenteditable_attr(this) &&
!is_hidden_from_screen_reader(this.name, attribute_map) &&
!is_presentation_role(role_static_value) &&
((!is_interactive_element(this.name, attribute_map) &&
is_non_interactive_roles(role_static_value)) ||
(is_non_interactive_element(this.name, attribute_map) && !role))
) {
const has_interactive_handlers = handlers.some((handler) => a11y_recommended_interactive_handlers.has(handler.name));
if (has_interactive_handlers) {
component.warn(this, compiler_warnings.a11y_no_noninteractive_element_interactions(this.name));
}
}
const has_dynamic_role = attribute_map.get('role') && !attribute_map.get('role').is_static;
// no-static-element-interactions
if (
!has_dynamic_role &&
!is_hidden_from_screen_reader(this.name, attribute_map) &&
!is_presentation_role(role_static_value) &&
!is_interactive_element(this.name, attribute_map) &&
!is_interactive_roles(role_static_value) &&
!is_non_interactive_element(this.name, attribute_map) &&
!is_non_interactive_roles(role_static_value) &&
!is_abstract_role(role_static_value)
) {
const interactive_handlers = handlers
.map((handler) => handler.name)
.filter((handlerName) => a11y_interactive_handlers.has(handlerName));
if (interactive_handlers.length > 0) {
component.warn(
this,
compiler_warnings.a11y_no_static_element_interactions(this.name, interactive_handlers)
);
}
}
}
validate_special_cases() {

@ -24,7 +24,7 @@ type Owner = INode;
const regex_contains_term_function_expression = /FunctionExpression/;
export default class Expression {
type: 'Expression' = 'Expression';
type: 'Expression' = 'Expression' as const;
component: Component;
owner: Owner;
node: Node;

@ -1,3 +1,4 @@
import type { RawSourceMap, DecodedSourceMap } from '@ampproject/remapping';
import { b, x, p } from 'code-red';
import Component from '../Component';
import Renderer from './Renderer';
@ -8,7 +9,6 @@ import { invalidate } from './invalidate';
import Block from './Block';
import { ImportDeclaration, ClassDeclaration, FunctionExpression, Node, Statement, ObjectExpression, Expression } from 'estree';
import { apply_preprocessor_sourcemap } from '../../utils/mapped_code';
import { RawSourceMap, DecodedSourceMap } from '@ampproject/remapping/dist/types/types';
import { flatten } from '../../utils/flatten';
import check_enable_sourcemap from '../utils/check_enable_sourcemap';
import { push_array } from '../../utils/push_array';

@ -169,7 +169,7 @@ export default class AttributeWrapper extends BaseAttributeWrapper {
}
if (is_indirectly_bound_value) {
const update_value = b`${element.var}.value = ${element.var}.__value;`;
const update_value = b`@set_input_value(${element.var}, ${element.var}.__value);`;
block.chunks.hydrate.push(update_value);
updater = b`

@ -765,20 +765,33 @@ export default class ElementWrapper extends Wrapper {
`);
binding_group.events.forEach(name => {
const resizeListenerFunctions = {
elementresize: 'add_iframe_resize_listener',
elementresizecontentbox: 'resize_observer_content_box.observe',
elementresizeborderbox: 'resize_observer_border_box.observe',
elementresizedevicepixelcontentbox: 'resize_observer_device_pixel_content_box.observe'
};
if (name in resizeListenerFunctions) {
if (['elementresize', 'elementresizecontentbox', 'elementresizeborderbox', 'elementresizedevicepixelcontentbox'].indexOf(name) !== -1) {
const resize_listener = block.get_unique_name(`${this.var.name}_resize_listener`);
block.add_variable(resize_listener);
block.chunks.mount.push(
b`${resize_listener} = @${resizeListenerFunctions[name]}(${this.var}, ${callee}.bind(${this.var}));`
);
// Can't dynamically do `@fn[name]`, code-red doesn't know how to resolve it
switch (name) {
case 'elementresize':
block.chunks.mount.push(
b`${resize_listener} = @add_iframe_resize_listener(${this.var}, ${callee}.bind(${this.var}));`
);
break;
case 'elementresizecontentbox':
block.chunks.mount.push(
b`${resize_listener} = @resize_observer_content_box.observe(${this.var}, ${callee}.bind(${this.var}));`
);
break;
case 'elementresizeborderbox':
block.chunks.mount.push(
b`${resize_listener} = @resize_observer_border_box.observe(${this.var}, ${callee}.bind(${this.var}));`
);
break;
case 'elementresizedevicepixelcontentbox':
block.chunks.mount.push(
b`${resize_listener} = @resize_observer_device_pixel_content_box.observe(${this.var}, ${callee}.bind(${this.var}));`
);
break;
}
block.chunks.destroy.push(
b`${resize_listener}();`

@ -19,7 +19,8 @@ const non_interactive_roles = new Set(
// 'toolbar' does not descend from widget, but it does support
// aria-activedescendant, thus in practice we treat it as a widget.
// focusable tabpanel elements are recommended if any panels in a set contain content where the first element in the panel is not focusable.
!['toolbar', 'tabpanel'].includes(name) &&
// 'generic' is meant to have no semantic meaning.
!['toolbar', 'tabpanel', 'generic'].includes(name) &&
!role.superClass.some((classes) => classes.includes('widget'))
);
})
@ -31,7 +32,11 @@ const non_interactive_roles = new Set(
);
const interactive_roles = new Set(
non_abstract_roles.filter((name) => !non_interactive_roles.has(name))
non_abstract_roles.filter((name) =>
!non_interactive_roles.has(name) &&
// 'generic' is meant to have no semantic meaning.
name !== 'generic'
)
);
export function is_non_interactive_roles(role: ARIARoleDefinitionKey) {

@ -2,6 +2,6 @@ export { default as compile } from './compile/index';
export { default as parse } from './parse/index';
export { default as preprocess } from './preprocess/index';
export { walk } from 'estree-walker';
export type { CompileOptions, ModuleFormat, EnableSourcemap, CssHashGetter } from './interfaces';
export const VERSION = '__VERSION__';
// additional exports added through generate-type-definitions.js
export const VERSION: string = '__VERSION__';

@ -1,4 +1,4 @@
import { RawSourceMap, DecodedSourceMap } from '@ampproject/remapping/dist/types/types';
import type { RawSourceMap, DecodedSourceMap } from '@ampproject/remapping';
import { getLocator } from 'locate-character';
import { MappedCode, SourceLocation, parse_attached_sourcemap, sourcemap_add_offset, combine_sourcemaps } from '../utils/mapped_code';
import { decode_map } from './decode_sourcemap';
@ -57,7 +57,7 @@ class PreprocessResult implements Source {
to_processed(): Processed {
// Combine all the source maps for each preprocessor function into one
const map: RawSourceMap = combine_sourcemaps(this.file_basename, this.sourcemap_list);
const map = combine_sourcemaps(this.file_basename, this.sourcemap_list);
return {
// TODO return separated output, in future version where svelte.compile supports it:

@ -1,4 +1,4 @@
import { DecodedSourceMap, RawSourceMap, SourceMapLoader } from '@ampproject/remapping/dist/types/types';
import type { DecodedSourceMap, RawSourceMap, SourceMapLoader } from '@ampproject/remapping';
import remapping from '@ampproject/remapping';
import { SourceMap } from 'magic-string';
import { Source, Processed } from '../preprocess/types';
@ -216,11 +216,11 @@ export class MappedCode {
export function combine_sourcemaps(
filename: string,
sourcemap_list: Array<DecodedSourceMap | RawSourceMap>
): RawSourceMap {
) {
if (sourcemap_list.length == 0) return null;
let map_idx = 1;
const map: RawSourceMap =
const map =
sourcemap_list.slice(0, -1)
.find(m => m.sources.length !== 1) === undefined

@ -4,7 +4,7 @@ export const regex_starts_with_whitespace = /^\s/;
export const regex_starts_with_whitespaces = /^[ \t\r\n]*/;
export const regex_ends_with_whitespace = /\s$/;
export const regex_ends_with_whitespaces = /[ \t\r\n]*$/;
export const regex_only_whitespaces = /^\s+$/;
export const regex_only_whitespaces = /^[ \t\n\r\f]+$/;
export const regex_whitespace_characters = /\s/g;
export const regex_non_whitespace_character = /\S/;

@ -1,7 +1,8 @@
/**
* Actions can return an object containing the two properties defined in this interface. Both are optional.
* - update: An action can have a parameter. This method will be called whenever that parameter changes,
* immediately after Svelte has applied updates to the markup.
* immediately after Svelte has applied updates to the markup. `ActionReturn` and `ActionReturn<never>` both
* mean that the action accepts no parameters, which makes it illegal to set the `update` method.
* - destroy: Method that is called after the element is unmounted
*
* Additionally, you can specify which additional attributes and events the action enables on the applied element.
@ -25,8 +26,8 @@
*
* Docs: https://svelte.dev/docs#template-syntax-element-directives-use-action
*/
export interface ActionReturn<Parameter = any, Attributes extends Record<string, any> = Record<never, any>> {
update?: (parameter: Parameter) => void;
export interface ActionReturn<Parameter = never, Attributes extends Record<string, any> = Record<never, any>> {
update?: [Parameter] extends [never] ? never : (parameter: Parameter) => void;
destroy?: () => void;
/**
* ### DO NOT USE THIS
@ -42,15 +43,21 @@ export interface ActionReturn<Parameter = any, Attributes extends Record<string,
* The following example defines an action that only works on `<div>` elements
* and optionally accepts a parameter which it has a default value for:
* ```ts
* export const myAction: Action<HTMLDivElement, { someProperty: boolean }> = (node, param = { someProperty: true }) => {
* export const myAction: Action<HTMLDivElement, { someProperty: boolean } | undefined> = (node, param = { someProperty: true }) => {
* // ...
* }
* ```
* `Action<HTMLDivElement>` and `Action<HTMLDiveElement, never>` both signal that the action accepts no parameters.
*
* You can return an object with methods `update` and `destroy` from the function and type which additional attributes and events it has.
* See interface `ActionReturn` for more details.
*
* Docs: https://svelte.dev/docs#template-syntax-element-directives-use-action
*/
export interface Action<Element = HTMLElement, Parameter = any, Attributes extends Record<string, any> = Record<never, any>> {
<Node extends Element>(node: Node, parameter?: Parameter): void | ActionReturn<Parameter, Attributes>;
export interface Action<Element = HTMLElement, Parameter = never, Attributes extends Record<string, any> = Record<never, any>> {
<Node extends Element>(...args: [Parameter] extends [never] ? [node: Node] : undefined extends Parameter ? [node: Node, parameter?: Parameter] : [node: Node, parameter: Parameter]): void | ActionReturn<Parameter, Attributes>;
}
// Implementation notes:
// - undefined extends X instead of X extends undefined makes this work better with both strict and nonstrict mode
// - [X] extends [never] is needed, X extends never would reduce the whole resulting type to never and not to one of the condition outcomes

@ -1,5 +1,5 @@
import { cubicOut } from 'svelte/easing';
import { is_function } from 'svelte/internal';
import { cubicOut } from '../easing';
import { is_function } from '../internal';
// todo: same as Transition, should it be shared?
export interface AnimationConfig {

@ -3,7 +3,7 @@ Adapted from https://github.com/mattdesl
Distributed under MIT License https://github.com/mattdesl/eases/blob/master/LICENSE.md
*/
export { identity as linear } from 'svelte/internal';
export { identity as linear } from '../internal';
export function backInOut(t: number) {
const s = 1.70158 * 1.525;

@ -13,5 +13,5 @@ export {
createEventDispatcher,
SvelteComponentDev as SvelteComponent,
SvelteComponentTyped
// additional exports added through generate-type-definitions.js
} from 'svelte/internal';
} from './internal';
export type { ComponentType, ComponentConstructorOptions, ComponentProps, ComponentEvents } from './internal';

@ -1,3 +1,5 @@
import { globals } from './globals';
/**
* Resize observer singleton.
* One listener per element only!
@ -15,19 +17,19 @@ export class ResizeObserverSingleton {
};
}
static readonly entries: WeakMap<Element, ResizeObserverEntry> = 'WeakMap' in globalThis ? new WeakMap() : undefined;
private readonly _listeners: WeakMap<Element, Listener> = 'WeakMap' in globalThis ? new WeakMap() : undefined;
private readonly _listeners: WeakMap<Element, Listener> = 'WeakMap' in globals ? new WeakMap() : undefined;
private _observer?: ResizeObserver;
private _getObserver() {
return this._observer ?? (this._observer = new ResizeObserver((entries) => {
for (const entry of entries) {
ResizeObserverSingleton.entries.set(entry.target, entry);
(ResizeObserverSingleton as any).entries.set(entry.target, entry);
this._listeners.get(entry.target)?.(entry);
}
}));
}
}
// Needs to be written like this to pass the tree-shake-test
(ResizeObserverSingleton as any).entries = 'WeakMap' in globals ? new WeakMap() : undefined;
type Listener = (entry: ResizeObserverEntry)=>any;

@ -751,9 +751,9 @@ export function add_iframe_resize_listener(node: HTMLElement, fn: () => void) {
};
}
export const resize_observer_content_box = new ResizeObserverSingleton({ box: 'content-box' });
export const resize_observer_border_box = new ResizeObserverSingleton({ box: 'border-box' });
export const resize_observer_device_pixel_content_box = new ResizeObserverSingleton({ box: 'device-pixel-content-box' });
export const resize_observer_content_box = /* @__PURE__ */ new ResizeObserverSingleton({ box: 'content-box' });
export const resize_observer_border_box = /* @__PURE__ */ new ResizeObserverSingleton({ box: 'border-box' });
export const resize_observer_device_pixel_content_box = /* @__PURE__ */ new ResizeObserverSingleton({ box: 'device-pixel-content-box' });
export { ResizeObserverSingleton };
export function toggle_class(element, name, toggle) {

@ -108,12 +108,18 @@ export function update_keyed_each(old_blocks, dirty, get_key, dynamic, ctx, list
}
export function validate_each_keys(ctx, list, get_context, get_key) {
const keys = new Set();
const keys = new Map();
for (let i = 0; i < list.length; i++) {
const key = get_key(get_context(ctx, list, i));
if (keys.has(key)) {
throw new Error('Cannot have duplicate keys in a keyed each');
let value = '';
try {
value = `with value '${String(key)}' `;
} catch (e) {
// can't stringify
}
throw new Error(`Cannot have duplicate keys in a keyed each: Keys at index ${keys.get(key)} and ${i} ${value}are duplicates`);
}
keys.add(key);
keys.set(key, i);
}
}

@ -27,11 +27,13 @@ export function beforeUpdate(fn: () => any) {
* It must be called during the component's initialisation (but doesn't need to live *inside* the component;
* it can be called from an external module).
*
* If a function is returned _synchronously_ from `onMount`, it will be called when the component is unmounted.
*
* `onMount` does not run inside a [server-side component](/docs#run-time-server-side-component-api).
*
* https://svelte.dev/docs#run-time-svelte-onmount
*/
export function onMount(fn: () => any) {
export function onMount<T>(fn: () => T extends Promise<() => any> ? "Returning a function asynchronously from onMount won't call that function on destroy" : T): void {
get_current_component().$$.on_mount.push(fn);
}
@ -56,6 +58,17 @@ export function onDestroy(fn: () => any) {
get_current_component().$$.on_destroy.push(fn);
}
export interface EventDispatcher<EventMap extends Record<string, any>> {
// Implementation notes:
// - undefined extends X instead of X extends undefined makes this work better with both strict and nonstrict mode
// - [X] extends [never] is needed, X extends never would reduce the whole resulting type to never and not to one of the condition outcomes
<Type extends keyof EventMap>(
...args: [EventMap[Type]] extends [never] ? [type: Type, parameter?: null | undefined, options?: DispatchOptions] :
null extends EventMap[Type] ? [type: Type, parameter?: EventMap[Type], options?: DispatchOptions] :
undefined extends EventMap[Type] ? [type: Type, parameter?: EventMap[Type], options?: DispatchOptions] :
[type: Type, parameter: EventMap[Type], options?: DispatchOptions]): boolean;
}
export interface DispatchOptions {
cancelable?: boolean;
}
@ -68,20 +81,23 @@ export interface DispatchOptions {
* [CustomEvent](https://developer.mozilla.org/en-US/docs/Web/API/CustomEvent).
* These events do not [bubble](https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Building_blocks/Events#Event_bubbling_and_capture).
* The `detail` argument corresponds to the [CustomEvent.detail](https://developer.mozilla.org/en-US/docs/Web/API/CustomEvent/detail)
* property and can contain any type of data.
* property and can contain any type of data.
*
* The event dispatcher can be typed to narrow the allowed event names and the type of the `detail` argument:
* ```ts
* const dispatch = createEventDispatcher<{
* loaded: never; // does not take a detail argument
* change: string; // takes a detail argument of type string, which is required
* optional: number | null; // takes an optional detail argument of type number
* }>();
* ```
*
* https://svelte.dev/docs#run-time-svelte-createeventdispatcher
*/
export function createEventDispatcher<EventMap extends {} = any>(): <
EventKey extends Extract<keyof EventMap, string>
>(
type: EventKey,
detail?: EventMap[EventKey],
options?: DispatchOptions
) => boolean {
export function createEventDispatcher<EventMap extends Record<string, any> = any>(): EventDispatcher<EventMap> {
const component = get_current_component();
return (type: string, detail?: any, { cancelable = false } = {}): boolean => {
return ((type: string, detail?: any, { cancelable = false } = {}): boolean => {
const callbacks = component.$$.callbacks[type];
if (callbacks) {
@ -95,7 +111,7 @@ export function createEventDispatcher<EventMap extends {} = any>(): <
}
return true;
};
}) as EventDispatcher<EventMap>;
}
/**

@ -376,8 +376,10 @@ export function create_bidirectional_transition(node: Element & ElementCSSInline
run(b: INTRO | OUTRO) {
if (is_function(config)) {
wait().then(() => {
const opts: TransitionOptions = { direction: b ? 'in' : 'out' };
// @ts-ignore
config = config(options);
config = config(opts);
go(b);
});
} else {

@ -1,4 +1,4 @@
import { Readable } from 'svelte/store';
import type { Readable } from '../store';
export function noop() {}

@ -1,5 +1,5 @@
import { Readable, writable } from 'svelte/store';
import { loop, now, Task } from 'svelte/internal';
import { Readable, writable } from '../store';
import { loop, now, Task } from '../internal';
import { is_date } from './utils';
interface TickContext<T> {

@ -1,6 +1,6 @@
import { Readable, writable } from 'svelte/store';
import { assign, loop, now, Task } from 'svelte/internal';
import { linear } from 'svelte/easing';
import { Readable, writable } from '../store';
import { assign, loop, now, Task } from '../internal';
import { linear } from '../easing';
import { is_date } from './utils';
function get_interpolator(a, b) {
@ -122,7 +122,7 @@ export function tweened<T>(value?: T, defaults: Options<T> = {}): Tweened<T> {
const elapsed = now - start;
if (elapsed > duration) {
if (elapsed > <number> duration) {
store.set(value = new_value);
return false;
}

@ -1,4 +1,4 @@
import { run_all, subscribe, noop, safe_not_equal, is_function, get_store_value } from 'svelte/internal';
import { run_all, subscribe, noop, safe_not_equal, is_function, get_store_value } from '../internal';
/** Callback to inform of a value updates. */
export type Subscriber<T> = (value: T) => void;
@ -12,8 +12,15 @@ export type Updater<T> = (value: T) => T;
/** Cleanup logic callback. */
type Invalidator<T> = (value?: T) => void;
/** Start and stop notification callbacks. */
export type StartStopNotifier<T> = (set: Subscriber<T>) => Unsubscriber | void;
/**
* Start and stop notification callbacks.
* This function is called when the first subscriber subscribes.
*
* @param {(value: T) => void} set Function that sets the value of the store.
* @returns {void | (() => void)} Optionally, a cleanup function that is called when the last remaining
* subscriber unsubscribes.
*/
export type StartStopNotifier<T> = (set: (value: T) => void) => void | (() => void);
/** Readable interface for subscribing. */
export interface Readable<T> {
@ -48,7 +55,7 @@ const subscriber_queue = [];
/**
* Creates a `Readable` store that allows reading by subscription.
* @param value initial value
* @param {StartStopNotifier}start start and stop notifications for subscriptions
* @param {StartStopNotifier} [start]
*/
export function readable<T>(value?: T, start?: StartStopNotifier<T>): Readable<T> {
return {
@ -59,7 +66,7 @@ export function readable<T>(value?: T, start?: StartStopNotifier<T>): Readable<T
/**
* Create a `Writable` store that allows both updating and reading by subscription.
* @param {*=}value initial value
* @param {StartStopNotifier=}start start and stop notifications for subscriptions
* @param {StartStopNotifier=} start
*/
export function writable<T>(value?: T, start: StartStopNotifier<T> = noop): Writable<T> {
let stop: Unsubscriber;

@ -1,5 +1,5 @@
import { cubicOut, cubicInOut, linear } from 'svelte/easing';
import { assign, split_css_unit, is_function } from 'svelte/internal';
import { cubicOut, cubicInOut, linear } from '../easing';
import { assign, split_css_unit, is_function } from '../internal';
export type EasingFunction = (t: number) => number;

@ -109,11 +109,11 @@ function cleanChildren(node) {
node.removeChild(child);
}
child.data = child.data.replace(/\s+/g, '\n');
child.data = child.data.replace(/[ \t\n\r\f]+/g, '\n');
if (previous && previous.nodeType === 3) {
previous.data += child.data;
previous.data = previous.data.replace(/\s+/g, '\n');
previous.data = previous.data.replace(/[ \t\n\r\f]+/g, '\n');
node.removeChild(child);
child = previous;
@ -130,13 +130,13 @@ function cleanChildren(node) {
// collapse whitespace
if (node.firstChild && node.firstChild.nodeType === 3) {
node.firstChild.data = node.firstChild.data.replace(/^\s+/, '');
if (!node.firstChild.data) node.removeChild(node.firstChild);
node.firstChild.data = node.firstChild.data.replace(/^[ \t\n\r\f]+/, '');
if (!node.firstChild.data.length) node.removeChild(node.firstChild);
}
if (node.lastChild && node.lastChild.nodeType === 3) {
node.lastChild.data = node.lastChild.data.replace(/\s+$/, '');
if (!node.lastChild.data) node.removeChild(node.lastChild);
node.lastChild.data = node.lastChild.data.replace(/[ \t\n\r\f]+$/, '');
if (!node.lastChild.data.length) node.removeChild(node.lastChild);
}
}
@ -146,7 +146,7 @@ export function normalizeHtml(window, html, { removeDataSvelte = false, preserve
node.innerHTML = html
.replace(/(<!--.*?-->)/g, preserveComments ? '$1' : '')
.replace(/(data-svelte-h="[^"]+")/g, removeDataSvelte ? '' : '$1')
.replace(/>[\s\r\n]+</g, '><')
.replace(/>[ \t\n\r\f]+</g, '><')
.trim();
cleanChildren(node);
return node.innerHTML.replace(/<\/?noscript\/?>/g, '');

@ -1,8 +1,8 @@
/* generated by Svelte vX.Y.Z */
import {
SvelteComponent,
add_iframe_resize_listener,
add_render_callback,
add_resize_listener,
detach,
element,
init,
@ -23,7 +23,7 @@ function create_fragment(ctx) {
},
m(target, anchor) {
insert(target, div, anchor);
div_resize_listener = add_resize_listener(div, /*div_elementresize_handler*/ ctx[2].bind(div));
div_resize_listener = add_iframe_resize_listener(div, /*div_elementresize_handler*/ ctx[2].bind(div));
},
p: noop,
i: noop,

@ -8,7 +8,8 @@ import {
insert,
noop,
safe_not_equal,
select_option
select_option,
set_input_value
} from "svelte/internal";
function create_fragment(ctx) {
@ -24,9 +25,9 @@ function create_fragment(ctx) {
option1 = element("option");
option1.textContent = "2";
option0.__value = "1";
option0.value = option0.__value;
set_input_value(option0, option0.__value);
option1.__value = "2";
option1.value = option1.__value;
set_input_value(option1, option1.__value);
},
m(target, anchor) {
insert(target, select, anchor);

@ -1,8 +1,8 @@
/* generated by Svelte vX.Y.Z */
import {
SvelteComponent,
add_iframe_resize_listener,
add_render_callback,
add_resize_listener,
detach,
element,
init,
@ -42,7 +42,7 @@ function create_fragment(ctx) {
},
m(target, anchor) {
insert(target, video, anchor);
video_resize_listener = add_resize_listener(video, /*video_elementresize_handler*/ ctx[7].bind(video));
video_resize_listener = add_iframe_resize_listener(video, /*video_elementresize_handler*/ ctx[7].bind(video));
if (!mounted) {
dispose = [

@ -75,9 +75,6 @@ describe('runtime (puppeteer)', () => {
function runTest(dir, hydrate, is_first_run) {
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,28 @@
const items = [ { id: 'a' }, { id: 'b' } ];
export default {
props: {
foo: null,
items
},
test({ assert, component, target }) {
const select = target.querySelector( 'select' );
const options = target.querySelectorAll( 'option' );
assert.equal( options[0].selected, true );
assert.equal( options[0].disabled, true );
assert.equal( options[1].selected, false );
assert.equal( options[1].disabled, false );
// placeholder option value must be blank string for native required field validation
assert.equal( options[0].value, '' );
assert.equal( select.checkValidity(), false );
component.foo = items[0];
assert.equal( options[0].selected, false );
assert.equal( options[1].selected, true );
assert.equal( select.checkValidity(), true );
}
};

@ -0,0 +1,11 @@
<script>
export let foo;
export let items;
</script>
<select bind:value={foo} required>
<option value={null} disabled>Select an option</option>
{#each items as item}
<option value={item}>{item.id}</option>
{/each}
</select>

@ -0,0 +1,11 @@
export default {
html: `
<div>&nbsp;</div>
<div>
<span>&nbsp;</span>
</div>
<div>&nbsp;</div>
`
};

@ -0,0 +1,13 @@
<script>
import Component from './Component.svelte'
</script>
<Component>&nbsp;</Component>
<Component>
<span>&nbsp;</span>
</Component>
<Component>
{@html "&nbsp;"}
</Component>

@ -3,5 +3,5 @@ export default {
dev: true
},
error: 'Cannot have duplicate keys in a keyed each'
error: 'Cannot have duplicate keys in a keyed each: Keys at index 0 and 3 with value \'1\' are duplicates'
};

@ -4,16 +4,19 @@ export default {
const div_in = target.querySelector('#in');
const div_out = target.querySelector('#out');
const div_both = target.querySelector('#both');
const div_bothin = target.querySelector('#both-in');
const div_bothout = target.querySelector('#both-out');
assert.equal(div_in.initial, 'in');
assert.equal(div_out.initial, 'out');
assert.equal(div_both.initial, 'both');
assert.equal(div_in.directions, 'in,in');
assert.equal(div_out.directions, 'out');
assert.equal(div_bothin.directions, 'both');
assert.equal(div_bothout.directions, 'both');
return Promise.resolve().then(() => {
assert.equal(div_in.later, 'in');
assert.equal(div_out.later, 'out');
assert.equal(div_both.later, 'both');
assert.equal(div_in.directions, 'in,in');
assert.equal(div_out.directions, 'out,out');
assert.equal(div_bothin.directions, 'both,in');
assert.equal(div_bothout.directions, 'both,out');
});
}
};

@ -2,10 +2,10 @@
export let visible;
function foo(node, _params, options) {
node.initial = options.direction;
node.directions = options.direction;
return (opts) => {
node.later = opts.direction;
node.directions += "," + opts.direction;
return {
duration: 10
@ -15,10 +15,11 @@
</script>
{#if visible}
<div id="both" transition:foo></div>
<div id="in" in:foo></div>
<div id="both-in" transition:foo />
<div id="in" in:foo />
{/if}
{#if !visible}
<div id="out" out:foo></div>
<div id="out" out:foo />
<div id="both-out" transition:foo={{ duration: 500 }} />
{/if}

@ -0,0 +1,153 @@
import type { Action, ActionReturn } from '$runtime/action';
// ---------------- Action
const href: Action<HTMLAnchorElement> = (node) => {
node.href = '';
// @ts-expect-error
node.href = 1;
};
href;
const required: Action<HTMLElement, boolean> = (node, param) => {
node;
param;
};
required(null as any, true);
// @ts-expect-error (only in strict mode) boolean missing
required(null as any);
// @ts-expect-error no boolean
required(null as any, 'string');
const required1: Action<HTMLElement, boolean> = (node, param) => {
node;
param;
return {
update: (p) => p === true,
destroy: () => {}
};
};
required1;
const required2: Action<HTMLElement, boolean> = (node) => {
node;
};
required2;
const required3: Action<HTMLElement, boolean> = (node, param) => {
node;
param;
return {
// @ts-expect-error comparison always resolves to false
update: (p) => p === 'd',
destroy: () => {}
};
};
required3;
const optional: Action<HTMLElement, boolean | undefined> = (node, param?) => {
node;
param;
};
optional(null as any, true);
optional(null as any);
// @ts-expect-error no boolean
optional(null as any, 'string');
const optional1: Action<HTMLElement, boolean | undefined> = (node, param?) => {
node;
param;
return {
update: (p) => p === true,
destroy: () => {}
};
};
optional1;
const optional2: Action<HTMLElement, boolean | undefined> = (node) => {
node;
};
optional2;
const optional3: Action<HTMLElement, boolean | undefined> = (node, param) => {
node;
param;
};
optional3;
const optional4: Action<HTMLElement, boolean | undefined> = (node, param?) => {
node;
param;
return {
// @ts-expect-error comparison always resolves to false
update: (p) => p === 'd',
destroy: () => {}
};
};
optional4;
const no: Action<HTMLElement, never> = (node) => {
node;
};
// @ts-expect-error second param
no(null as any, true);
no(null as any);
// @ts-expect-error second param
no(null as any, 'string');
const no1: Action<HTMLElement, never> = (node) => {
node;
return {
destroy: () => {}
};
};
no1;
// @ts-expect-error param given
const no2: Action<HTMLElement, never> = (node, param?) => {};
no2;
// @ts-expect-error param given
const no3: Action<HTMLElement, never> = (node, param) => {};
no3;
// @ts-expect-error update method given
const no4: Action<HTMLElement, never> = (node) => {
return {
update: () => {},
destroy: () => {}
};
};
no4;
// ---------------- ActionReturn
const requiredReturn: ActionReturn<string> = {
update: (p) => p.toString()
};
requiredReturn;
const optionalReturn: ActionReturn<boolean | undefined> = {
update: (p) => {
p === true;
// @ts-expect-error could be undefined
p.toString();
}
};
optionalReturn;
const invalidProperty: ActionReturn = {
// @ts-expect-error invalid property
invalid: () => {}
};
invalidProperty;
type Attributes = ActionReturn<never, { a: string; }>['$$_attributes'];
const attributes: Attributes = { a: 'a' };
attributes;
// @ts-expect-error wrong type
const invalidAttributes1: Attributes = { a: 1 };
invalidAttributes1;
// @ts-expect-error missing prop
const invalidAttributes2: Attributes = {};
invalidAttributes2;

@ -0,0 +1,43 @@
import { createEventDispatcher } from '$runtime/internal/lifecycle';
const dispatch = createEventDispatcher<{
loaded: never
change: string
valid: boolean
optional: number | null
}>();
// @ts-expect-error: dispatch invalid event
dispatch('some-event');
dispatch('loaded');
dispatch('loaded', null);
dispatch('loaded', undefined);
dispatch('loaded', undefined, { cancelable: true });
// @ts-expect-error: no detail accepted
dispatch('loaded', 123);
// @ts-expect-error: detail not provided
dispatch('change');
dispatch('change', 'string');
dispatch('change', 'string', { cancelable: true });
// @ts-expect-error: wrong type of detail
dispatch('change', 123);
// @ts-expect-error: wrong type of detail
dispatch('change', undefined);
dispatch('valid', true);
dispatch('valid', true, { cancelable: true });
// @ts-expect-error: wrong type of detail
dispatch('valid', 'string');
dispatch('optional');
dispatch('optional', 123);
dispatch('optional', 123, { cancelable: true });
dispatch('optional', null);
dispatch('optional', undefined);
dispatch('optional', undefined, { cancelable: true });
// @ts-expect-error: wrong type of optional detail
dispatch('optional', 'string');
// @ts-expect-error: wrong type of option
dispatch('optional', undefined, { cancelabled: true });

@ -0,0 +1,58 @@
import { onMount } from '$runtime/index';
// sync and no return
onMount(() => {
console.log('mounted');
});
// sync and return value
onMount(() => {
return 'done';
});
// sync and return sync
onMount(() => {
return () => {
return 'done';
};
});
// sync and return async
onMount(() => {
return async () => {
const res = await fetch('');
return res;
};
});
// async and no return
onMount(async () => {
await fetch('');
});
// async and return value
onMount(async () => {
const res = await fetch('');
return res;
});
// @ts-expect-error async and return sync
onMount(async () => {
return () => {
return 'done';
};
});
// @ts-expect-error async and return async
onMount(async () => {
return async () => {
const res = await fetch('');
return res;
};
});
// @ts-expect-error async and return any
onMount(async () => {
const a: any = null as any;
return a;
});

@ -0,0 +1,16 @@
{
"extends": "../../tsconfig.json",
"compilerOptions": {
"rootDir": "../..",
"baseUrl": "../../",
"paths": {
"$runtime/*": ["src/runtime/*"]
},
// enable strictest options
"allowUnreachableCode": false,
"noFallthroughCasesInSwitch": true,
"noImplicitReturns": true,
"strict": true,
},
"include": ["."]
}

@ -9,13 +9,20 @@
</script>
<!-- should warn -->
<!-- svelte-ignore a11y-no-static-element-interactions -->
<div on:click={noop} />
<!-- svelte-ignore a11y-no-static-element-interactions -->
<div on:click={noop} aria-hidden="false" />
<!-- svelte-ignore a11y-no-static-element-interactions -->
<section on:click={noop} />
<!-- svelte-ignore a11y-no-noninteractive-element-interactions -->
<main on:click={noop} />
<!-- svelte-ignore a11y-no-noninteractive-element-interactions -->
<article on:click={noop} />
<!-- svelte-ignore a11y-no-static-element-interactions -->
<header on:click={noop} />
<!-- svelte-ignore a11y-no-noninteractive-element-interactions -->
<footer on:click={noop} />
<!-- should not warn -->
@ -28,24 +35,37 @@
<input type="button" on:click={noop} />
<input type={dynamicTypeValue} on:click={noop} />
<!-- svelte-ignore a11y-no-static-element-interactions -->
<div on:click={noop} {...props} />
<!-- svelte-ignore a11y-no-static-element-interactions -->
<div on:click={noop} on:keydown={noop} />
<!-- svelte-ignore a11y-no-static-element-interactions -->
<div on:click={noop} on:keyup={noop} />
<!-- svelte-ignore a11y-no-static-element-interactions -->
<div on:click={noop} on:keypress={noop} />
<!-- svelte-ignore a11y-no-static-element-interactions -->
<div on:click={noop} on:keydown={noop} on:keyup={noop} />
<!-- svelte-ignore a11y-no-static-element-interactions -->
<div on:click={noop} on:keyup={noop} on:keypress={noop} />
<!-- svelte-ignore a11y-no-static-element-interactions -->
<div on:click={noop} on:keypress={noop} on:keydown={noop} />
<!-- svelte-ignore a11y-no-static-element-interactions -->
<div on:click={noop} on:keydown={noop} on:keyup={noop} on:keypress={noop} />
<input on:click={noop} type="hidden" />
<!-- svelte-ignore a11y-no-static-element-interactions -->
<div on:click={noop} aria-hidden />
<!-- svelte-ignore a11y-no-static-element-interactions -->
<div on:click={noop} aria-hidden="true" />
<!-- svelte-ignore a11y-no-static-element-interactions -->
<div on:click={noop} aria-hidden="false" on:keydown={noop} />
<!-- svelte-ignore a11y-no-static-element-interactions -->
<div on:click={noop} aria-hidden={dynamicAriaHiddenValue} />
<div on:click={noop} role="presentation" />
<div on:click={noop} role="none" />
<div on:click={noop} role={dynamicRole} />
<!-- svelte-ignore a11y-no-static-element-interactions -->
<svelte:element this={Math.random() ? 'button' : 'div'} on:click={noop} />

@ -3,11 +3,11 @@
"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.",
"start": {
"line": 12,
"line": 13,
"column": 0
},
"end": {
"line": 12,
"line": 13,
"column": 23
}
},
@ -15,11 +15,11 @@
"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.",
"start": {
"line": 13,
"line": 15,
"column": 0
},
"end": {
"line": 13,
"line": 15,
"column": 43
}
},
@ -27,11 +27,11 @@
"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.",
"start": {
"line": 15,
"line": 18,
"column": 0
},
"end": {
"line": 15,
"line": 18,
"column": 27
}
},
@ -39,11 +39,11 @@
"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.",
"start": {
"line": 16,
"line": 20,
"column": 0
},
"end": {
"line": 16,
"line": 20,
"column": 24
}
},
@ -51,11 +51,11 @@
"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.",
"start": {
"line": 17,
"line": 22,
"column": 0
},
"end": {
"line": 17,
"line": 22,
"column": 27
}
},
@ -63,11 +63,11 @@
"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.",
"start": {
"line": 18,
"line": 24,
"column": 0
},
"end": {
"line": 18,
"line": 24,
"column": 26
}
},
@ -75,11 +75,11 @@
"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.",
"start": {
"line": 19,
"line": 26,
"column": 0
},
"end": {
"line": 19,
"line": 26,
"column": 26
}
}

@ -7,9 +7,15 @@
};
</script>
<!-- svelte-ignore a11y-no-static-element-interactions -->
<div on:mouseover={() => void 0} />
<!-- svelte-ignore a11y-no-static-element-interactions -->
<div on:mouseover={() => void 0} on:focus={() => void 0} />
<!-- svelte-ignore a11y-no-static-element-interactions -->
<div on:mouseover={() => void 0} {...otherProps} />
<!-- svelte-ignore a11y-no-static-element-interactions -->
<div on:mouseout={() => void 0} />
<!-- svelte-ignore a11y-no-static-element-interactions -->
<div on:mouseout={() => void 0} on:blur={() => void 0} />
<!-- svelte-ignore a11y-no-static-element-interactions -->
<div on:mouseout={() => void 0} {...otherProps} />

@ -3,48 +3,48 @@
"code": "a11y-mouse-events-have-key-events",
"end": {
"column": 35,
"line": 10
"line": 11
},
"message": "A11y: on:mouseover must be accompanied by on:focus",
"start": {
"column": 0,
"line": 10
"line": 11
}
},
{
"code": "a11y-mouse-events-have-key-events",
"end": {
"column": 51,
"line": 12
"line": 15
},
"message": "A11y: on:mouseover must be accompanied by on:focus",
"start": {
"column": 0,
"line": 12
"line": 15
}
},
{
"code": "a11y-mouse-events-have-key-events",
"end": {
"column": 34,
"line": 13
"line": 17
},
"message": "A11y: on:mouseout must be accompanied by on:blur",
"start": {
"column": 0,
"line": 13
"line": 17
}
},
{
"code": "a11y-mouse-events-have-key-events",
"end": {
"column": 50,
"line": 15
"line": 21
},
"message": "A11y: on:mouseout must be accompanied by on:blur",
"start": {
"column": 0,
"line": 15
"line": 21
}
}
]

@ -0,0 +1,14 @@
<!-- VALID -->
<div role="presentation" on:mouseup={() => {}} />
<div role="button" tabindex="-1" on:click={() => {}} on:keypress={() => {}} />
<div role="listitem" aria-hidden on:click={() => {}} on:keypress={() => {}} />
<button on:click={() => {}} />
<h1 contenteditable="true" on:keydown={() => {}}>Heading</h1>
<h1>Heading</h1>
<!-- INVALID -->
<div role="listitem" on:mousedown={() => {}} />
<h1 on:click={() => {}} on:keydown={() => {}}>Heading</h1>
<h1 role="banner" on:keyup={() => {}}>Heading</h1>
<p on:keypress={() => {}} />
<div role="paragraph" on:mouseup={() => {}} />

@ -0,0 +1,62 @@
[
{
"code": "a11y-no-noninteractive-element-interactions",
"end": {
"column": 47,
"line": 10
},
"message": "A11y: Non-interactive element <div> should not be assigned mouse or keyboard event listeners.",
"start": {
"column": 0,
"line": 10
}
},
{
"code": "a11y-no-noninteractive-element-interactions",
"end": {
"column": 58,
"line": 11
},
"message": "A11y: Non-interactive element <h1> should not be assigned mouse or keyboard event listeners.",
"start": {
"column": 0,
"line": 11
}
},
{
"code": "a11y-no-noninteractive-element-interactions",
"end": {
"column": 50,
"line": 12
},
"message": "A11y: Non-interactive element <h1> should not be assigned mouse or keyboard event listeners.",
"start": {
"column": 0,
"line": 12
}
},
{
"code": "a11y-no-noninteractive-element-interactions",
"end": {
"column": 28,
"line": 13
},
"message": "A11y: Non-interactive element <p> should not be assigned mouse or keyboard event listeners.",
"start": {
"column": 0,
"line": 13
}
},
{
"code": "a11y-no-noninteractive-element-interactions",
"end": {
"column": 46,
"line": 14
},
"message": "A11y: Non-interactive element <div> should not be assigned mouse or keyboard event listeners.",
"start": {
"column": 0,
"line": 14
}
}
]

@ -0,0 +1,19 @@
<script>
const dynamicRole = "button";
</script>
<!-- valid -->
<button on:click={() => {}} />
<!-- svelte-ignore a11y-interactive-supports-focus -->
<div on:keydown={() => {}} role="button" />
<input type="text" on:click={() => {}} />
<div on:copy={() => {}} />
<a href="/foo" on:click={() => {}}>link</a>
<div role={dynamicRole} on:click={() => {}} />
<!-- svelte-ignore a11y-no-noninteractive-element-interactions -->
<footer on:keydown={() => {}} />
<!-- invalid -->
<div on:keydown={() => {}} />
<!-- svelte-ignore a11y-missing-attribute -->
<a on:mousedown={() => {}} on:mouseup={() => {}} on:copy={() => {}}>link</a>

@ -0,0 +1,26 @@
[
{
"code": "a11y-no-static-element-interactions",
"end": {
"column": 29,
"line": 17
},
"message": "A11y: <div> with keydown handler must have an ARIA role",
"start": {
"column": 0,
"line": 17
}
},
{
"code": "a11y-no-static-element-interactions",
"end": {
"column": 76,
"line": 19
},
"message": "A11y: <a> with mousedown, mouseup handlers must have an ARIA role",
"start": {
"column": 0,
"line": 19
}
}
]

@ -4,5 +4,6 @@
<Component>
<!-- svelte-ignore a11y-click-events-have-key-events -->
<!-- svelte-ignore a11y-no-static-element-interactions -->
<div slot='foo' on:click>hi!</div>
</Component>

@ -3,5 +3,6 @@
</script>
<Component>
<!-- svelte-ignore a11y-no-static-element-interactions -->
<div slot='foo' on:click>hi!</div>
</Component>

@ -4,11 +4,11 @@
"message": "A11y: visible, non-interactive elements with an on:click event must be accompanied by an on:keydown, on:keyup, or on:keypress event.",
"start": {
"column": 1,
"line": 6
"line": 7
},
"end": {
"column": 35,
"line": 6
"line": 7
}
}
]

@ -4,5 +4,6 @@
<Component>
<!-- svelte-ignore unrelated-warning -->
<!-- svelte-ignore a11y-no-static-element-interactions -->
<div slot='foo' on:click>hi!</div>
</Component>

@ -4,11 +4,11 @@
"message": "A11y: visible, non-interactive elements with an on:click event must be accompanied by an on:keydown, on:keyup, or on:keypress event.",
"start": {
"column": 1,
"line": 7
"line": 8
},
"end": {
"column": 35,
"line": 7
"line": 8
}
}
]

@ -1,12 +1,12 @@
{
"include": [],
"include": ["src/**/*"],
"compilerOptions": {
"rootDir": "src",
// target node v8+ (https://node.green/)
// the only missing feature is Array.prototype.values
"lib": ["es2017"],
"lib": ["es2017", "DOM", "DOM.Iterable"],
"target": "es2017",
"declaration": true,

Loading…
Cancel
Save