diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 0a4d83558f..8520c04310 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -11,8 +11,17 @@ jobs: timeout-minutes: 15 strategy: matrix: - node-version: [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 @@ -37,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 diff --git a/CHANGELOG.md b/CHANGELOG.md index 44b50c6951..381d02de72 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,7 +2,14 @@ ## Unreleased (4.0) -* Minimum supported Node version is now Node 14 +* **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) diff --git a/package.json b/package.json index c5239c8b50..dc27fa2084 100644 --- a/package.json +++ b/package.json @@ -90,7 +90,7 @@ }, "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", diff --git a/rollup.config.mjs b/rollup.config.mjs index 56ebdaa755..d6a22733a4 100644 --- a/rollup.config.mjs +++ b/rollup.config.mjs @@ -14,136 +14,113 @@ const is_publish = !!process.env.PUBLISH; const ts_plugin = is_publish ? typescript({ - typescript: require('typescript') - }) + typescript: require('typescript'), + }) : sucrase({ - transforms: ['typescript'] - }); + transforms: ['typescript'], + }); -// The following external and path logic is necessary so that the bundled runtime pieces and the index file -// reference each other correctly instead of bundling their references to each other +fs.writeFileSync( + `./compiler.d.ts`, + `export { compile, parse, preprocess, walk, VERSION } from './types/compiler/index.js';` +); -/** - * Ensures that relative imports inside `src/runtime` like `./internal` and `../store` are externalized correctly - */ -const external = (id, parent_id) => { - const parent_segments = parent_id.replace(/\\/g, '/').split('/'); - // TODO needs to be adjusted when we move to JS modules - if (parent_segments[parent_segments.length - 3] === 'runtime') { - return /\.\.\/\w+$/.test(id); - } else { - return id === './internal' && parent_segments[parent_segments.length - 2] === 'runtime'; - } -} - -/** - * Transforms externalized import paths like `../store` into correct relative imports with correct index file extension import - */ -const replace_relative_svelte_imports = (id, ending) => { - id = id.replace(/\\/g, '/'); - // TODO needs to be adjusted when we move to JS modules - return /src\/runtime\/\w+$/.test(id) && `../${id.split('/').pop()}/${ending}`; -} +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`]) +); /** - * Transforms externalized `./internal` import path into correct relative import with correct index file extension import + * @type {import("rollup").RollupOptions[]} */ -const replace_relative_internal_import = (id, ending) => { - id = id.replace(/\\/g, '/'); - // TODO needs to be adjusted when we move to JS modules - return id.endsWith('src/runtime/internal') && `./internal/${ending}`; -} - -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 => replace_relative_internal_import(id, 'index.mjs') - }, - { - file: `index.js`, - format: 'cjs', - paths: id => replace_relative_internal_import(id, 'index.js') - } - ], - external, - plugins: [ts_plugin] - }, + 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}`; - { - input: `src/runtime/ssr.ts`, - output: [ - { - file: `ssr.mjs`, - format: 'esm', - paths: id => replace_relative_internal_import(id, 'index.mjs') - }, - { - file: `ssr.js`, - format: 'cjs', - paths: id => replace_relative_internal_import(id, 'index.js') + return `${entry.name}/index.${ext}`; + } + }, + chunkFileNames: `internal/[name]-[hash].${ext}`, + format, + minifyInternalExports: false, + dir: '.', + }; } - ], - 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 => replace_relative_svelte_imports(id, 'index.mjs') + ), + plugins: [ + replace({ + preventAssignment: true, + values: { + __VERSION__: pkg.version, }, - { - file: `${dir}/index.js`, - format: 'cjs', - paths: id => replace_relative_svelte_imports(id, 'index.js') - } - ], - external, - plugins: [ - replace({ - __VERSION__: pkg.version - }), - ts_plugin, - { - writeBundle(_options, bundle) { + }), + 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['index.mjs']; + const mod = bundle[`internal/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( + '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', - module: './index.mjs', - types: './index.d.ts' - }, null, ' ')); + 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';`); + fs.writeFileSync( + `${dir}/index.d.ts`, + `export * from '../types/runtime/${dir}/index.js';` + ); } } - ] - })), - + } + ] + }, /* compiler.js */ { input: 'src/compiler/index.ts', plugins: [ replace({ - __VERSION__: pkg.version, - 'process.env.NODE_DEBUG': false // appears inside the util package + preventAssignment: true, + values: { + __VERSION__: pkg.version, + 'process.env.NODE_DEBUG': false // appears inside the util package + }, }), { resolveId(id) { @@ -152,7 +129,7 @@ export default [ if (id === 'util') { return require.resolve('./node_modules/util'); // just 'utils' would resolve this to the built-in module } - } + }, }, resolve(), commonjs({ @@ -177,6 +154,7 @@ export default [ ], external: is_publish ? [] - : id => id === 'acorn' || id === 'magic-string' || id.startsWith('css-tree') + : (id) => + id === 'acorn' || id === 'magic-string' || id.startsWith('css-tree') } ]; diff --git a/site/content/docs/06-accessibility-warnings.md b/site/content/docs/06-accessibility-warnings.md index 0d025d797d..934cf638e6 100644 --- a/site/content/docs/06-accessibility-warnings.md +++ b/site/content/docs/06-accessibility-warnings.md @@ -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 `
`, ``, `

` (,`

`, etc), `

`, ``, `

  • `, `
      ` and `
        `. 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 + +
      1. {}} /> + + +
        {}} /> +``` + +--- + ### `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`. diff --git a/src/compiler/compile/compiler_warnings.ts b/src/compiler/compile/compiler_warnings.ts index a851bc24c2..2138e81213 100644 --- a/src/compiler/compile/compiler_warnings.ts +++ b/src/compiler/compile/compiler_warnings.ts @@ -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}'` diff --git a/src/compiler/compile/nodes/Element.ts b/src/compiler/compile/nodes/Element.ts index 2410904d63..ee62d3e7e8 100644 --- a/src/compiler/compile/nodes/Element.ts +++ b/src/compiler/compile/nodes/Element.ts @@ -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'; @@ -102,6 +102,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'] @@ -738,8 +747,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); @@ -747,8 +760,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))); @@ -762,6 +773,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() { diff --git a/src/compiler/compile/render_dom/wrappers/Element/Attribute.ts b/src/compiler/compile/render_dom/wrappers/Element/Attribute.ts index 64178030f6..61311fd83c 100644 --- a/src/compiler/compile/render_dom/wrappers/Element/Attribute.ts +++ b/src/compiler/compile/render_dom/wrappers/Element/Attribute.ts @@ -172,7 +172,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` diff --git a/src/compiler/compile/utils/a11y.ts b/src/compiler/compile/utils/a11y.ts index 4409f80262..bc23f5c818 100644 --- a/src/compiler/compile/utils/a11y.ts +++ b/src/compiler/compile/utils/a11y.ts @@ -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) { diff --git a/src/compiler/index.ts b/src/compiler/index.ts index 6ab256c59b..7d349cf6bb 100644 --- a/src/compiler/index.ts +++ b/src/compiler/index.ts @@ -4,4 +4,4 @@ export { default as preprocess } from './preprocess/index'; export { walk } from 'estree-walker'; export type { CompileOptions, ModuleFormat, EnableSourcemap, CssHashGetter } from './interfaces'; -export const VERSION = '__VERSION__'; +export const VERSION: string = '__VERSION__'; diff --git a/src/runtime/action/index.ts b/src/runtime/action/index.ts index 388f6f040e..a672bb7ae5 100644 --- a/src/runtime/action/index.ts +++ b/src/runtime/action/index.ts @@ -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` 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 = Record> { - update?: (parameter: Parameter) => void; +export interface ActionReturn = Record> { + update?: [Parameter] extends [never] ? never : (parameter: Parameter) => void; destroy?: () => void; /** * ### DO NOT USE THIS @@ -42,15 +43,21 @@ export interface ActionReturn` elements * and optionally accepts a parameter which it has a default value for: * ```ts - * export const myAction: Action = (node, param = { someProperty: true }) => { + * export const myAction: Action = (node, param = { someProperty: true }) => { * // ... * } * ``` + * `Action` and `Action` 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 = Record> { - (node: Node, parameter?: Parameter): void | ActionReturn; +export interface Action = Record> { + (...args: [Parameter] extends [never] ? [node: Node] : undefined extends Parameter ? [node: Node, parameter?: Parameter] : [node: Node, parameter: Parameter]): void | ActionReturn; } + +// 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 diff --git a/src/runtime/internal/lifecycle.ts b/src/runtime/internal/lifecycle.ts index e75bbdc501..1c1726c29c 100644 --- a/src/runtime/internal/lifecycle.ts +++ b/src/runtime/internal/lifecycle.ts @@ -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(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> { + // 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 + ( + ...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(): < - EventKey extends Extract ->( - type: EventKey, - detail?: EventMap[EventKey], - options?: DispatchOptions -) => boolean { +export function createEventDispatcher = any>(): EventDispatcher { 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(): < } return true; - }; + }) as EventDispatcher; } /** diff --git a/src/runtime/store/index.ts b/src/runtime/store/index.ts index 4991c05700..09e5b10bd2 100644 --- a/src/runtime/store/index.ts +++ b/src/runtime/store/index.ts @@ -12,8 +12,15 @@ export type Updater = (value: T) => T; /** Cleanup logic callback. */ type Invalidator = (value?: T) => void; -/** Start and stop notification callbacks. */ -export type StartStopNotifier = (set: Subscriber) => 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 = (set: (value: T) => void) => void | (() => void); /** Readable interface for subscribing. */ export interface Readable { @@ -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(value?: T, start?: StartStopNotifier): Readable { return { @@ -59,7 +66,7 @@ export function readable(value?: T, start?: StartStopNotifier): Readable(value?: T, start: StartStopNotifier = noop): Writable { let stop: Unsubscriber; diff --git a/test/js/samples/select-dynamic-value/expected.js b/test/js/samples/select-dynamic-value/expected.js index cd1ab1d812..1d0896d6e8 100644 --- a/test/js/samples/select-dynamic-value/expected.js +++ b/test/js/samples/select-dynamic-value/expected.js @@ -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); diff --git a/test/runtime-puppeteer/index.ts b/test/runtime-puppeteer/index.ts index efb7ac02e3..e2bcf2add1 100644 --- a/test/runtime-puppeteer/index.ts +++ b/test/runtime-puppeteer/index.ts @@ -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); diff --git a/test/runtime/samples/binding-select-null-placeholder/_config.js b/test/runtime/samples/binding-select-null-placeholder/_config.js new file mode 100644 index 0000000000..b453e6869a --- /dev/null +++ b/test/runtime/samples/binding-select-null-placeholder/_config.js @@ -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 ); + } +}; diff --git a/test/runtime/samples/binding-select-null-placeholder/main.svelte b/test/runtime/samples/binding-select-null-placeholder/main.svelte new file mode 100644 index 0000000000..65cab99495 --- /dev/null +++ b/test/runtime/samples/binding-select-null-placeholder/main.svelte @@ -0,0 +1,11 @@ + + + diff --git a/test/types/actions.ts b/test/types/actions.ts new file mode 100644 index 0000000000..7a0ca97714 --- /dev/null +++ b/test/types/actions.ts @@ -0,0 +1,153 @@ +import type { Action, ActionReturn } from '$runtime/action'; + +// ---------------- Action + +const href: Action = (node) => { + node.href = ''; + // @ts-expect-error + node.href = 1; +}; +href; + +const required: Action = (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 = (node, param) => { + node; + param; + return { + update: (p) => p === true, + destroy: () => {} + }; +}; +required1; + +const required2: Action = (node) => { + node; +}; +required2; + +const required3: Action = (node, param) => { + node; + param; + return { + // @ts-expect-error comparison always resolves to false + update: (p) => p === 'd', + destroy: () => {} + }; +}; +required3; + +const optional: Action = (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 = (node, param?) => { + node; + param; + return { + update: (p) => p === true, + destroy: () => {} + }; +}; +optional1; + +const optional2: Action = (node) => { + node; +}; +optional2; + +const optional3: Action = (node, param) => { + node; + param; +}; +optional3; + +const optional4: Action = (node, param?) => { + node; + param; + return { + // @ts-expect-error comparison always resolves to false + update: (p) => p === 'd', + destroy: () => {} + }; +}; +optional4; + +const no: Action = (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 = (node) => { + node; + return { + destroy: () => {} + }; +}; +no1; + +// @ts-expect-error param given +const no2: Action = (node, param?) => {}; +no2; + +// @ts-expect-error param given +const no3: Action = (node, param) => {}; +no3; + +// @ts-expect-error update method given +const no4: Action = (node) => { + return { + update: () => {}, + destroy: () => {} + }; +}; +no4; + +// ---------------- ActionReturn + +const requiredReturn: ActionReturn = { + update: (p) => p.toString() +}; +requiredReturn; + +const optionalReturn: ActionReturn = { + 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['$$_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; diff --git a/test/types/create-event-dispatcher.ts b/test/types/create-event-dispatcher.ts new file mode 100644 index 0000000000..37e31fd179 --- /dev/null +++ b/test/types/create-event-dispatcher.ts @@ -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 }); diff --git a/test/types/on-mount.ts b/test/types/on-mount.ts new file mode 100644 index 0000000000..47d272b8f5 --- /dev/null +++ b/test/types/on-mount.ts @@ -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; +}); diff --git a/test/types/tsconfig.json b/test/types/tsconfig.json new file mode 100644 index 0000000000..108ed2a2b2 --- /dev/null +++ b/test/types/tsconfig.json @@ -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": ["."] +} \ No newline at end of file diff --git a/test/validator/samples/a11y-click-events-have-key-events/input.svelte b/test/validator/samples/a11y-click-events-have-key-events/input.svelte index 8737f04ec5..3fb1ded53d 100644 --- a/test/validator/samples/a11y-click-events-have-key-events/input.svelte +++ b/test/validator/samples/a11y-click-events-have-key-events/input.svelte @@ -9,13 +9,20 @@ +
        +
        +
        +
        +
        +
        +