Merge branch 'master' into handle-list-of-nodes

pull/8442/head
Nguyen Tran 3 years ago
commit 3f12748788

@ -1,3 +1,7 @@
# HEADS UP: BIG RESTRUCTURING UNDERWAY
The Svelte repo is currently in the process of heavy restructuring for Svelte 4. After that, work on Svelte 5 will likely change a lot on the compiler aswell. For that reason, please don't open PRs that are large in scope, touch more than a couple of files etc. In other words, bug fixes are fine, but feature PRs will likely not be merged.
### Before submitting the PR, please make sure you do the following
- [ ] It's really useful if your PR references an issue where it is discussed ahead of time. In many cases, features are absent for a reason. For large changes, please create an RFC: https://github.com/sveltejs/rfcs
- [ ] Prefix your PR title with `feat:`, `fix:`, `chore:`, or `docs:`.

@ -1,5 +1,13 @@
# Svelte changelog
## Unreleased
* 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))
* Update interpolated style directive properly when using spread ([#8438](https://github.com/sveltejs/svelte/issues/8438))
* Remove style directive property when value is `undefined` ([#8462](https://github.com/sveltejs/svelte/issues/8462))
* Ensure version is typed as `string` instead of the literal `__VERSION__` ([#8498](https://github.com/sveltejs/svelte/issues/8498))
## 3.58.0
* Add `bind:innerText` for `contenteditable` elements ([#3311](https://github.com/sveltejs/svelte/issues/3311))

@ -62,6 +62,8 @@ When [opening a new issue](https://github.com/sveltejs/svelte/issues/new/choose)
## Pull requests
> HEADS UP: The Svelte repo is currently in the process of heavy restructuring for Svelte 4. After that, work on Svelte 5 will likely change a lot on the compiler aswell. For that reason, please don't open PRs that are large in scope, touch more than a couple of files etc. In other words, bug fixes are fine, but feature PRs will likely not be merged.
### Proposing a change
If you would like to request a new feature or enhancement but are not yet thinking about opening a pull request, you can also file an issue with [feature template](https://github.com/sveltejs/svelte/issues/new?template=feature_request.yml).

@ -546,6 +546,11 @@ export interface HTMLAttributes<T extends EventTarget> extends AriaAttributes, D
*/
'bind:innerText'?: string | undefined | null;
readonly 'bind:contentRect'?: DOMRectReadOnly | undefined | null;
readonly 'bind:contentBoxSize'?: Array<{ blockSize: number; inlineSize: number }> | undefined | null; // TODO make this ResizeObserverSize once we require TS>=4.4
readonly 'bind:borderBoxSize'?: Array<{ blockSize: number; inlineSize: number }> | undefined | null; // TODO make this ResizeObserverSize once we require TS>=4.4
readonly 'bind:devicePixelContentBoxSize'?: Array<{ blockSize: number; inlineSize: number }> | undefined | null; // TODO make this ResizeObserverSize once we require TS>=4.4
// SvelteKit
'data-sveltekit-keepfocus'?: true | '' | 'off' | undefined | null;
'data-sveltekit-noscroll'?: true | '' | 'off' | undefined | null;
@ -1073,11 +1078,17 @@ export interface SvelteMediaTimeRange {
end: number;
}
export interface SvelteDocumentAttributes extends HTMLAttributes<Document> {
readonly 'bind:fullscreenElement'?: Document['fullscreenElement'] | undefined | null;
readonly 'bind:visibilityState'?: Document['visibilityState'] | undefined | null;
}
export interface SvelteWindowAttributes extends HTMLAttributes<Window> {
readonly 'bind:innerWidth'?: Window['innerWidth'] | undefined | null;
readonly 'bind:innerHeight'?: Window['innerHeight'] | undefined | null;
readonly 'bind:outerWidth'?: Window['outerWidth'] | undefined | null;
readonly 'bind:outerHeight'?: Window['outerHeight'] | undefined | null;
readonly 'bind:devicePixelRatio'?: Window['devicePixelRatio'] | undefined | null;
'bind:scrollX'?: Window['scrollX'] | undefined | null;
'bind:scrollY'?: Window['scrollY'] | undefined | null;
readonly 'bind:online'?: Window['navigator']['onLine'] | undefined | null;
@ -1586,7 +1597,7 @@ export interface SvelteHTMLElements {
// Svelte specific
'svelte:window': SvelteWindowAttributes;
'svelte:document': HTMLAttributes<Document>;
'svelte:document': SvelteDocumentAttributes;
'svelte:body': HTMLAttributes<HTMLElement>;
'svelte:fragment': { slot?: string };
'svelte:options': { [name: string]: any };

14
package-lock.json generated

@ -10,7 +10,7 @@
"license": "MIT",
"devDependencies": {
"@ampproject/remapping": "^0.3.0",
"@jridgewell/sourcemap-codec": "^1.4.14",
"@jridgewell/sourcemap-codec": "^1.4.15",
"@rollup/plugin-commonjs": "^11.0.0",
"@rollup/plugin-json": "^6.0.0",
"@rollup/plugin-node-resolve": "^11.2.1",
@ -184,9 +184,9 @@
}
},
"node_modules/@jridgewell/sourcemap-codec": {
"version": "1.4.14",
"resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.4.14.tgz",
"integrity": "sha512-XPSJHWmi394fuUuzDnGz1wiKqWfo1yXecHQMRf2l6hztTO+nPru658AyDngaBe7isIxEkRsPR3FZh+s7iVa4Uw==",
"version": "1.4.15",
"resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.4.15.tgz",
"integrity": "sha512-eF2rxCRulEKXHTRiDrDy6erMYWqNw4LPdQ8UQA4huuxaQsVeRPFl2oM8oDGxMFhJUWZf9McpLtJasDDZb/Bpeg==",
"dev": true
},
"node_modules/@nodelib/fs.scandir": {
@ -5499,9 +5499,9 @@
"dev": true
},
"@jridgewell/sourcemap-codec": {
"version": "1.4.14",
"resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.4.14.tgz",
"integrity": "sha512-XPSJHWmi394fuUuzDnGz1wiKqWfo1yXecHQMRf2l6hztTO+nPru658AyDngaBe7isIxEkRsPR3FZh+s7iVa4Uw==",
"version": "1.4.15",
"resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.4.15.tgz",
"integrity": "sha512-eF2rxCRulEKXHTRiDrDy6erMYWqNw4LPdQ8UQA4huuxaQsVeRPFl2oM8oDGxMFhJUWZf9McpLtJasDDZb/Bpeg==",
"dev": true
},
"@nodelib/fs.scandir": {

@ -120,7 +120,7 @@
"homepage": "https://svelte.dev",
"devDependencies": {
"@ampproject/remapping": "^0.3.0",
"@jridgewell/sourcemap-codec": "^1.4.14",
"@jridgewell/sourcemap-codec": "^1.4.15",
"@rollup/plugin-commonjs": "^11.0.0",
"@rollup/plugin-json": "^6.0.0",
"@rollup/plugin-node-resolve": "^11.2.1",

@ -42,7 +42,7 @@ Svelte uses the `export` keyword to mark a variable declaration as a *property*
---
You can specify a default initial value for a prop. It will be used if the component's consumer doesn't specify the prop on the component (or if its initial value is `undefined`) when instantiating the component. Note that whenever a prop is removed by the consumer, its value is set to `undefined` rather than the initial value.
You can specify a default initial value for a prop. It will be used if the component's consumer doesn't specify the prop on the component (or if its initial value is `undefined`) when instantiating the component. Note that if the values of props are subsequently updated, then any prop whose value is not specified will be set to `undefined` (rather than its initial value).
In development mode (see the [compiler options](/docs#compile-time-svelte-compile)), a warning will be printed if no default initial value is provided and the consumer does not specify a value. To squelch this warning, ensure that a default initial value is specified, even if it is `undefined`.
@ -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);

@ -823,6 +823,8 @@ Inputs that work together can use `bind:group`.
<input type="checkbox" bind:group={fillings} value="Guac (extra)">
```
> `bind:group` only works if the inputs are in the same Svelte component.
#### bind:this
```sv
@ -1742,6 +1744,7 @@ You can also bind to the following properties:
* `scrollX`
* `scrollY`
* `online` — an alias for `window.navigator.onLine`
* `devicePixelRatio`
All except `scrollX` and `scrollY` are readonly.
@ -1756,6 +1759,9 @@ All except `scrollX` and `scrollY` are readonly.
```sv
<svelte:document on:event={handler}/>
```
```sv
<svelte:document bind:prop={value}/>
```
---
@ -1770,6 +1776,15 @@ As with `<svelte:window>`, this element may only appear the top level of your co
/>
```
---
You can also bind to the following properties:
* `fullscreenElement`
* `visibilityState`
All are readonly.
### `<svelte:body>`
```sv

@ -25,7 +25,7 @@ import TemplateScope from './nodes/shared/TemplateScope';
import fuzzymatch from '../utils/fuzzymatch';
import get_object from './utils/get_object';
import Slot from './nodes/Slot';
import { Node, ImportDeclaration, ExportNamedDeclaration, Identifier, ExpressionStatement, AssignmentExpression, Literal, Property, RestElement, ExportDefaultDeclaration, ExportAllDeclaration, FunctionDeclaration, FunctionExpression } from 'estree';
import { Node, ImportDeclaration, ExportNamedDeclaration, Identifier, ExpressionStatement, AssignmentExpression, Literal, Property, RestElement, ExportDefaultDeclaration, ExportAllDeclaration, FunctionDeclaration, FunctionExpression, Pattern, Expression } from 'estree';
import add_to_set from './utils/add_to_set';
import check_graph_for_cycles from './utils/check_graph_for_cycles';
import { print, b, x } from 'code-red';
@ -1034,7 +1034,7 @@ export default class Component {
const subscriptions = [];
const props = [];
function add_new_props(exported, local, default_value) {
function add_new_props(exported: Identifier, local: Pattern, default_value: Expression) {
props.push({
type: 'Property',
method: false,
@ -1064,7 +1064,7 @@ export default class Component {
for (let index = 0; index < node.declarations.length; index++) {
const declarator = node.declarations[index];
if (declarator.id.type !== 'Identifier') {
function get_new_name(local) {
function get_new_name(local: Identifier): Identifier {
const variable = component.var_lookup.get(local.name);
if (variable.subscribable) {
subscriptions.push(get_subscriptions(variable));
@ -1078,7 +1078,7 @@ export default class Component {
return local;
}
function rename_identifiers(param: Node) {
function rename_identifiers(param: Pattern) {
switch (param.type) {
case 'ObjectPattern': {
const handle_prop = (prop: Property | RestElement) => {
@ -1087,7 +1087,7 @@ export default class Component {
} else if (prop.value.type === 'Identifier') {
prop.value = get_new_name(prop.value);
} else {
rename_identifiers(prop.value);
rename_identifiers(prop.value as Pattern);
}
};
@ -1095,7 +1095,7 @@ export default class Component {
break;
}
case 'ArrayPattern': {
const handle_element = (element: Node, index: number, array: Node[]) => {
const handle_element = (element: Pattern | null, index: number, array: Array<Pattern | null>) => {
if (element) {
if (element.type === 'Identifier') {
array[index] = get_new_name(element);
@ -1110,7 +1110,11 @@ export default class Component {
}
case 'RestElement':
param.argument = get_new_name(param.argument);
if (param.argument.type === 'Identifier') {
param.argument = get_new_name(param.argument);
} else {
rename_identifiers(param.argument);
}
break;
case 'AssignmentPattern':

@ -220,7 +220,7 @@ export default {
},
invalid_rest_eachblock_binding: (rest_element_name: string) => ({
code: 'invalid-rest-eachblock-binding',
message: `...${rest_element_name} operator will create a new object and binding propagation with original object will not work`
message: `The rest operator (...) will create a new object and binding '${rest_element_name}' with the original object will not work`
}),
avoid_mouse_events_on_document: {
code: 'avoid-mouse-events-on-document',

@ -3,12 +3,13 @@ import get_object from '../utils/get_object';
import Expression from './shared/Expression';
import Component from '../Component';
import TemplateScope from './shared/TemplateScope';
import { regex_dimensions } from '../../utils/patterns';
import { regex_dimensions, regex_box_size } from '../../utils/patterns';
import { Node as ESTreeNode } from 'estree';
import { TemplateNode } from '../../interfaces';
import Element from './Element';
import InlineComponent from './InlineComponent';
import Window from './Window';
import Document from './Document';
import { clone } from '../../utils/clone';
import compiler_errors from '../compiler_errors';
import compiler_warnings from '../compiler_warnings';
@ -36,7 +37,7 @@ export default class Binding extends Node {
is_contextual: boolean;
is_readonly: boolean;
constructor(component: Component, parent: Element | InlineComponent | Window, scope: TemplateScope, info: TemplateNode) {
constructor(component: Component, parent: Element | InlineComponent | Window | Document, scope: TemplateScope, info: TemplateNode) {
super(component, parent, scope, info);
if (info.expression.type !== 'Identifier' && info.expression.type !== 'MemberExpression') {
@ -92,6 +93,7 @@ export default class Binding extends Node {
this.is_readonly =
regex_dimensions.test(this.name) ||
regex_box_size.test(this.name) ||
(isElement(parent) &&
((parent.is_media_node() && read_only_media_attributes.has(this.name)) ||
(parent.name === 'input' && type === 'file')) /* TODO others? */);

@ -1,14 +1,24 @@
import Node from './shared/Node';
import Binding from './Binding';
import EventHandler from './EventHandler';
import fuzzymatch from '../../utils/fuzzymatch';
import Action from './Action';
import Component from '../Component';
import list from '../../utils/list';
import TemplateScope from './shared/TemplateScope';
import { Element } from '../../interfaces';
import compiler_warnings from '../compiler_warnings';
import compiler_errors from '../compiler_errors';
const valid_bindings = [
'fullscreenElement',
'visibilityState'
];
export default class Document extends Node {
type: 'Document';
handlers: EventHandler[] = [];
bindings: Binding[] = [];
actions: Action[] = [];
constructor(component: Component, parent: Node, scope: TemplateScope, info: Element) {
@ -17,6 +27,17 @@ export default class Document extends Node {
info.attributes.forEach((node) => {
if (node.type === 'EventHandler') {
this.handlers.push(new EventHandler(component, this, scope, node));
} else if (node.type === 'Binding') {
if (!~valid_bindings.indexOf(node.name)) {
const match = fuzzymatch(node.name, valid_bindings);
if (match) {
return component.error(node, compiler_errors.invalid_binding_on(node.name, '<svelte:document>', ` (did you mean '${match}'?)`));
} else {
return component.error(node, compiler_errors.invalid_binding_on(node.name, '<svelte:document>', ` — valid bindings are ${list(valid_bindings)}`));
}
}
this.bindings.push(new Binding(component, this, scope, node));
} else if (node.type === 'Action') {
this.actions.push(new Action(component, this, scope, node));
} else {

@ -12,7 +12,7 @@ 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 { regex_dimensions, regex_starts_with_newline, regex_non_whitespace_character } from '../../utils/patterns';
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';
import Let from './Let';
@ -121,6 +121,7 @@ const a11y_implicit_semantics = new Map([
['details', 'group'],
['dt', 'term'],
['fieldset', 'group'],
['figure', 'figure'],
['form', 'form'],
['h1', 'heading'],
['h2', 'heading'],
@ -132,6 +133,7 @@ const a11y_implicit_semantics = new Map([
['img', 'img'],
['li', 'listitem'],
['link', 'link'],
['main', 'main'],
['menu', 'list'],
['meter', 'progressbar'],
['nav', 'navigation'],
@ -142,6 +144,7 @@ const a11y_implicit_semantics = new Map([
['progress', 'progressbar'],
['section', 'region'],
['summary', 'button'],
['table', 'table'],
['tbody', 'rowgroup'],
['textarea', 'textbox'],
['tfoot', 'rowgroup'],
@ -631,9 +634,7 @@ export default class Element extends Node {
}
// no-redundant-roles
const has_redundant_role = current_role === get_implicit_role(this.name, attribute_map);
if (this.name === current_role || has_redundant_role) {
if (current_role === get_implicit_role(this.name, attribute_map)) {
component.warn(attribute, compiler_warnings.a11y_no_redundant_roles(current_role));
}
@ -1090,7 +1091,10 @@ export default class Element extends Node {
} else if (contenteditable && !contenteditable.is_static) {
return component.error(contenteditable, compiler_errors.dynamic_contenteditable_attribute);
}
} else if (name !== 'this') {
} else if (
name !== 'this' &&
!regex_box_size.test(name)
) {
return component.error(binding, compiler_errors.invalid_binding(binding.name));
}
});

@ -17,6 +17,7 @@ const valid_bindings = [
'outerHeight',
'scrollX',
'scrollY',
'devicePixelRatio',
'online'
];

@ -1,5 +1,5 @@
import { x } from 'code-red';
import { Node, Identifier, Expression, PrivateIdentifier } from 'estree';
import { Node, Identifier, Expression, PrivateIdentifier, Pattern } from 'estree';
import { walk } from 'estree-walker';
import is_reference, { NodeWithPropertyDefinition } from 'is-reference';
import { clone } from '../../../utils/clone';
@ -30,15 +30,17 @@ export function unpack_destructuring({
default_modifier = (node) => node,
scope,
component,
context_rest_properties
context_rest_properties,
in_rest_element = false
}: {
contexts: Context[];
node: Node;
node: Pattern;
modifier?: DestructuredVariable['modifier'];
default_modifier?: DestructuredVariable['default_modifier'];
scope: TemplateScope;
component: Component;
context_rest_properties: Map<string, Node>;
in_rest_element?: boolean;
}) {
if (!node) return;
@ -49,28 +51,26 @@ export function unpack_destructuring({
modifier,
default_modifier
});
} else if (node.type === 'RestElement') {
contexts.push({
type: 'DestructuredVariable',
key: node.argument as Identifier,
modifier,
default_modifier
});
context_rest_properties.set((node.argument as Identifier).name, node);
if (in_rest_element) {
context_rest_properties.set(node.name, node);
}
} else if (node.type === 'ArrayPattern') {
node.elements.forEach((element, i) => {
if (element && element.type === 'RestElement') {
node.elements.forEach((element: Pattern | null, i: number) => {
if (!element) {
return;
} else if (element.type === 'RestElement') {
unpack_destructuring({
contexts,
node: element,
node: element.argument,
modifier: (node) => x`${modifier(node)}.slice(${i})` as Node,
default_modifier,
scope,
component,
context_rest_properties
context_rest_properties,
in_rest_element: true
});
context_rest_properties.set((element.argument as Identifier).name, element);
} else if (element && element.type === 'AssignmentPattern') {
} else if (element.type === 'AssignmentPattern') {
const n = contexts.length;
mark_referenced(element.right, scope, component);
@ -87,7 +87,8 @@ export function unpack_destructuring({
)}` as Node,
scope,
component,
context_rest_properties
context_rest_properties,
in_rest_element
});
} else {
unpack_destructuring({
@ -97,7 +98,8 @@ export function unpack_destructuring({
default_modifier,
scope,
component,
context_rest_properties
context_rest_properties,
in_rest_element
});
}
});
@ -116,9 +118,9 @@ export function unpack_destructuring({
default_modifier,
scope,
component,
context_rest_properties
context_rest_properties,
in_rest_element: true
});
context_rest_properties.set((property.argument as Identifier).name, property);
} else if (property.type === 'Property') {
const key = property.key;
const value = property.value;
@ -168,7 +170,8 @@ export function unpack_destructuring({
)}` as Node,
scope,
component,
context_rest_properties
context_rest_properties,
in_rest_element
});
} else {
// e.g. { property } or { property: newName }
@ -179,7 +182,8 @@ export function unpack_destructuring({
default_modifier,
scope,
component,
context_rest_properties
context_rest_properties,
in_rest_element
});
}
}

@ -1,6 +1,6 @@
import Block from '../Block';
import Wrapper from './shared/Wrapper';
import { x } from 'code-red';
import { b, x } from 'code-red';
import Document from '../../nodes/Document';
import { Identifier } from 'estree';
import EventHandler from './Element/EventHandler';
@ -9,6 +9,16 @@ import { TemplateNode } from '../../../interfaces';
import Renderer from '../Renderer';
import add_actions from './shared/add_actions';
const associated_events = {
fullscreenElement: ['fullscreenchange'],
visibilityState: ['visibilitychange']
};
const readonly = new Set([
'fullscreenElement',
'visibilityState'
]);
export default class DocumentWrapper extends Wrapper {
node: Document;
handlers: EventHandler[];
@ -19,7 +29,66 @@ export default class DocumentWrapper extends Wrapper {
}
render(block: Block, _parent_node: Identifier, _parent_nodes: Identifier) {
const { renderer } = this;
const { component } = renderer;
const events: Record<string, Array<{ name: string; value: string }>> = {};
const bindings: Record<string, string> = {};
add_event_handlers(block, x`@_document`, this.handlers);
add_actions(block, x`@_document`, this.node.actions);
this.node.bindings.forEach(binding => {
// TODO: what if it's a MemberExpression?
const binding_name = (binding.expression.node as Identifier).name;
// in dev mode, throw if read-only values are written to
if (readonly.has(binding.name)) {
renderer.readonly.add(binding_name);
}
bindings[binding.name] = binding_name;
const binding_events = associated_events[binding.name];
const property = binding.name;
binding_events.forEach(associated_event => {
if (!events[associated_event]) events[associated_event] = [];
events[associated_event].push({
name: binding_name,
value: property
});
});
});
Object.keys(events).forEach(event => {
const id = block.get_unique_name(`ondocument${event}`);
const props = events[event];
renderer.add_to_context(id.name);
const fn = renderer.reference(id.name);
props.forEach(prop => {
renderer.meta_bindings.push(
b`this._state.${prop.name} = @_document.${prop.value};`
);
});
block.event_listeners.push(x`
@listen(@_document, "${event}", ${fn})
`);
component.partly_hoisted.push(b`
function ${id}() {
${props.map(prop => renderer.invalidate(prop.name, x`${prop.name} = @_document.${prop.value}`))}
}
`);
block.chunks.init.push(b`
@add_render_callback(${fn});
`);
component.has_reactive_assignments = true;
});
}
}

@ -11,6 +11,7 @@ import { Node, Identifier } from 'estree';
import add_to_set from '../../../utils/add_to_set';
import mark_each_block_bindings from '../shared/mark_each_block_bindings';
import handle_select_value_binding from './handle_select_value_binding';
import { regex_box_size } from '../../../../utils/patterns';
export default class BindingWrapper {
node: Binding;
@ -455,7 +456,12 @@ function get_value_from_dom(
return x`$$value`;
}
// <select bind:value='selected'>
// <div bind:contentRect|contentBoxSize|borderBoxSize|devicePixelContentBoxSize>
if (regex_box_size.test(name)) {
return x`@ResizeObserverSingleton.entries.get(this)?.${name}`;
}
// <select bind:value='selected>
if (node.name === 'select') {
return node.get_static_attribute_value('multiple') === true ?
x`@select_multiple_value(this)` :

@ -12,7 +12,7 @@ import { namespaces } from '../../../../utils/namespaces';
import AttributeWrapper from './Attribute';
import StyleAttributeWrapper from './StyleAttribute';
import SpreadAttributeWrapper from './SpreadAttribute';
import { regex_dimensions, regex_starts_with_newline, regex_backslashes } from '../../../../utils/patterns';
import { regex_dimensions, regex_starts_with_newline, regex_backslashes, regex_border_box_size, regex_content_box_size, regex_device_pixel_content_box_size, regex_content_rect } from '../../../../utils/patterns';
import Binding from './Binding';
import add_to_set from '../../../utils/add_to_set';
import { add_event_handler } from '../shared/add_event_handlers';
@ -64,11 +64,29 @@ const events = [
filter: (node: Element, _name: string) =>
node.name === 'input' && node.get_static_attribute_value('type') === 'range'
},
// resize events
{
event_names: ['elementresize'],
filter: (_node: Element, name: string) =>
regex_dimensions.test(name)
},
{
event_names: ['elementresizecontentbox'],
filter: (_node: Element, name: string) =>
regex_content_rect.test(name) ?? regex_content_box_size.test(name)
},
{
event_names: ['elementresizeborderbox'],
filter: (_node: Element, name: string) =>
regex_border_box_size.test(name)
},
{
event_names: ['elementresizedevicepixelcontentbox'],
filter: (_node: Element, name: string) =>
regex_device_pixel_content_box_size.test(name)
},
// media events
{
event_names: ['timeupdate'],
@ -747,14 +765,33 @@ export default class ElementWrapper extends Wrapper {
`);
binding_group.events.forEach(name => {
if (name === 'elementresize') {
// special case
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} = @add_resize_listener(${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}();`
@ -1203,19 +1240,27 @@ export default class ElementWrapper extends Wrapper {
block.chunks.hydrate.push(updater);
const self_deps = expression.dynamic_dependencies();
const all_deps = new Set([
...self_deps,
...this.dynamic_style_dependencies
]);
let condition = block.renderer.dirty([...all_deps]);
// Assume that style has changed through the spread attribute
if (has_spread) {
if (should_cache && all_deps.size) {
// Update the cached value
block.chunks.update.push(b`
if (${condition}) {
${cached_snippet} = ${snippet};
}`
);
}
block.chunks.update.push(updater);
} else {
const self_deps = expression.dynamic_dependencies();
const all_deps = new Set([
...self_deps,
...this.dynamic_style_dependencies
]);
if (all_deps.size === 0) return;
let condition = block.renderer.dirty([...all_deps]);
if (all_deps.size === 0) return;
if (should_cache) {
condition = x`${condition} && ${cached_snippet} !== (${cached_snippet} = ${snippet})`;

@ -14,6 +14,7 @@ const associated_events = {
innerHeight: 'resize',
outerWidth: 'resize',
outerHeight: 'resize',
devicePixelRatio: 'resize',
scrollX: 'scroll',
scrollY: 'scroll'
@ -29,6 +30,7 @@ const readonly = new Set([
'innerHeight',
'outerWidth',
'outerHeight',
'devicePixelRatio',
'online'
]);

@ -3,5 +3,5 @@ export { default as parse } from './parse/index';
export { default as preprocess } from './preprocess/index';
export { walk } from 'estree-walker';
export const VERSION = '__VERSION__';
export const VERSION: string = '__VERSION__';
// additional exports added through generate-type-definitions.js

@ -22,3 +22,9 @@ export const regex_ends_with_underscore = /_$/;
export const regex_invalid_variable_identifier_characters = /[^a-zA-Z0-9_$]/g;
export const regex_dimensions = /^(?:offset|client)(?:Width|Height)$/;
export const regex_content_rect = /^(?:contentRect)$/;
export const regex_content_box_size = /^(?:contentBoxSize)$/;
export const regex_border_box_size = /^(?:borderBoxSize)$/;
export const regex_device_pixel_content_box_size = /^(?:devicePixelContentBoxSize)$/;
export const regex_box_size = /^(?:contentRect|contentBoxSize|borderBoxSize|devicePixelContentBoxSize)$/;

@ -0,0 +1,69 @@
import { globals } from './globals';
/**
* Resize observer singleton.
* One listener per element only!
* https://groups.google.com/a/chromium.org/g/blink-dev/c/z6ienONUb5A/m/F5-VcUZtBAAJ
*/
export class ResizeObserverSingleton {
constructor(readonly options?: ResizeObserverOptions) {}
observe(element: Element, listener: Listener) {
this._listeners.set(element, listener);
this._getObserver().observe(element, this.options);
return () => {
this._listeners.delete(element);
this._observer.unobserve(element); // this line can probably be removed
};
}
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 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;
// TODO: Remove this
interface ResizeObserverSize {
readonly blockSize: number;
readonly inlineSize: number;
}
interface ResizeObserverEntry {
readonly borderBoxSize: readonly ResizeObserverSize[];
readonly contentBoxSize: readonly ResizeObserverSize[];
readonly contentRect: DOMRectReadOnly;
readonly devicePixelContentBoxSize: readonly ResizeObserverSize[];
readonly target: Element;
}
type ResizeObserverBoxOptions = 'border-box' | 'content-box' | 'device-pixel-content-box';
interface ResizeObserverOptions {
box?: ResizeObserverBoxOptions;
}
interface ResizeObserver {
disconnect(): void;
observe(target: Element, options?: ResizeObserverOptions): void;
unobserve(target: Element): void;
}
interface ResizeObserverCallback {
(entries: ResizeObserverEntry[], observer: ResizeObserver): void;
}
declare let ResizeObserver: {
prototype: ResizeObserver;
new(callback: ResizeObserverCallback): ResizeObserver;
};

@ -1,3 +1,4 @@
import { ResizeObserverSingleton } from './ResizeObserverSingleton';
import { contenteditable_truthy_values, has_prop } from './utils';
// Track which nodes are claimed during hydration. Unclaimed nodes can then be removed from the DOM
@ -306,6 +307,15 @@ export function attr(node: Element, attribute: string, value?: string) {
else if (node.getAttribute(attribute) !== value) node.setAttribute(attribute, value);
}
/**
* List of attributes that should always be set through the attr method,
* because updating them through the property setter doesn't work reliably.
* In the example of `width`/`height`, the problem is that the setter only
* accepts numeric values, but the attribute can also be set to a string like `50%`.
* If this list becomes too big, rethink this approach.
*/
const always_set_through_set_attribute = ['width', 'height'];
export function set_attributes(node: Element & ElementCSSInlineStyle, attributes: { [x: string]: string }) {
// @ts-ignore
const descriptors = Object.getOwnPropertyDescriptors(node.__proto__);
@ -316,7 +326,7 @@ export function set_attributes(node: Element & ElementCSSInlineStyle, attributes
node.style.cssText = attributes[key];
} else if (key === '__value') {
(node as any).value = node[key] = attributes[key];
} else if (descriptors[key] && descriptors[key].set) {
} else if (descriptors[key] && descriptors[key].set && always_set_through_set_attribute.indexOf(key) === -1) {
node[key] = attributes[key];
} else {
attr(node, key, attributes[key]);
@ -631,7 +641,7 @@ export function set_input_type(input, type) {
}
export function set_style(node, key, value, important) {
if (value === null) {
if (value == null) {
node.style.removeProperty(key);
} else {
node.style.setProperty(key, value, important ? 'important' : '');
@ -689,7 +699,7 @@ export function is_crossorigin() {
return crossorigin;
}
export function add_resize_listener(node: HTMLElement, fn: () => void) {
export function add_iframe_resize_listener(node: HTMLElement, fn: () => void) {
const computed_style = getComputedStyle(node);
if (computed_style.position === 'static') {
@ -737,6 +747,11 @@ export function add_resize_listener(node: HTMLElement, fn: () => void) {
};
}
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) {
element.classList[toggle ? 'add' : 'remove'](name);
}

@ -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,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,

@ -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 = [

@ -0,0 +1,18 @@
export default {
html: `
<div style="background-color: rgb(255, 0, 0);"></div>
`,
test({ assert, target, window, component }) {
const div = target.querySelector('div');
const styles = window.getComputedStyle(div);
assert.equal(styles.backgroundColor, 'rgb(255, 0, 0)');
{
component.backgroundColor = 128;
const div = target.querySelector('div');
const styles = window.getComputedStyle(div);
assert.equal(styles.backgroundColor, 'rgb(128, 0, 0)');
}
}
};

@ -0,0 +1,5 @@
<script lang="ts">
export let backgroundColor = 255;
</script>
<div style:background-color="rgb({backgroundColor}, 0, 0)" {...$$restProps} />

@ -0,0 +1,12 @@
export default {
html: `
<h1>1</h1>
<h1>2</h1>
<h1>3</h1>
<h1>5</h1>
<h1>10</h1>
<h1>20</h1>
<h1>30</h1>
<h1>6</h1>
`
};

@ -0,0 +1,15 @@
<script>
let [first, second, ...[third, ...[, fifth]]] = [1, 2, 3, 4, 5];
let [one, two, ...[three, ...{ length }]] = [10, 20, 30, 40, 50, 60, 70, 80, 90];
</script>
<h1>{first}</h1>
<h1>{second}</h1>
<h1>{third}</h1>
<h1>{fifth}</h1>
<h1>{one}</h1>
<h1>{two}</h1>
<h1>{three}</h1>
<h1>{length}</h1>

@ -0,0 +1,69 @@
export default {
props: {
thePromise: new Promise(_ => {})
},
html: `
loading...
`,
async test({ assert, component, target }) {
await (component.thePromise = Promise.resolve([1, 2, 3, 4, 5, 6, 7, 8]));
assert.htmlEqual(
target.innerHTML,
`
<p>a: 1</p>
<p>b: 2</p>
<p>c: 5</p>
<p>remaining length: 3</p>
`
);
await (component.thePromise = Promise.resolve([9, 10, 11, 12, 13, 14, 15]));
assert.htmlEqual(
target.innerHTML,
`
<p>a: 9</p>
<p>b: 10</p>
<p>c: 13</p>
<p>remaining length: 2</p>
`
);
try {
await (component.thePromise = Promise.reject([16, 17, 18, 19, 20, 21, 22]));
} catch (e) {
// do nothing
}
assert.htmlEqual(
target.innerHTML,
`
<p>c: 16</p>
<p>d: 17</p>
<p>e: 18</p>
<p>f: 19</p>
<p>g: 22</p>
`
);
try {
await (component.thePromise = Promise.reject([23, 24, 25, 26, 27, 28, 29, 30, 31]));
} catch (e) {
// do nothing
}
assert.htmlEqual(
target.innerHTML,
`
<p>c: 23</p>
<p>d: 24</p>
<p>e: 25</p>
<p>f: 26</p>
<p>g: 29</p>
`
);
}
};

@ -0,0 +1,18 @@
<script>
export let thePromise;
</script>
{#await thePromise}
loading...
{:then [ a, b, ...[,, c, ...{ length } ]]}
<p>a: {a}</p>
<p>b: {b}</p>
<p>c: {c}</p>
<p>remaining length: {length}</p>
{:catch [c, ...[d, e, f, ...[,,g]]]}
<p>c: {c}</p>
<p>d: {d}</p>
<p>e: {e}</p>
<p>f: {f}</p>
<p>g: {g}</p>
{/await}

@ -0,0 +1,19 @@
export default {
html: '<div>12 120 70, 30+4=34</div>',
async test({ component, target, assert }) {
component.promise1 = Promise.resolve({width: 5, height: 6});
component.promise2 = Promise.reject({width: 6, height: 7});
await Promise.resolve();
assert.htmlEqual(target.innerHTML, `
<div>30 300 110, 50+6=56</div>
<div>42 420 130, 60+7=67</div>
`);
component.constant = 20;
assert.htmlEqual(target.innerHTML, `
<div>30 600 220, 100+6=106</div>
<div>42 840 260, 120+7=127</div>
`);
}
};

@ -0,0 +1,23 @@
<script>
export let promise1 = {width: 3, height: 4};
export let promise2 = {width: 5, height: 7};
export let constant = 10;
function calculate(width, height, constant) {
return { area: width * height, volume: width * height * constant };
}
</script>
{#await promise1 then { width, height }}
{@const {area, volume} = calculate(width, height, constant)}
{@const perimeter = (width + height) * constant}
{@const [_width, ...[_height, ...[sum]]] = [width * constant, height, width * constant + height]}
<div>{area} {volume} {perimeter}, {_width}+{_height}={sum}</div>
{/await}
{#await promise2 catch { width, height }}
{@const {area, volume} = calculate(width, height, constant)}
{@const perimeter = (width + height) * constant}
{@const [_width, ...[_height, ...[sum]]] = [width * constant, height, width * constant + height]}
<div>{area} {volume} {perimeter}, {_width}+{_height}={sum}</div>
{/await}

@ -0,0 +1,30 @@
export default {
html: `
<div>12 120 70, 30+4=34</div>
<div>35 350 120, 50+7=57</div>
<div>48 480 140, 60+8=68</div>
`,
async test({ component, target, assert }) {
component.constant = 20;
assert.htmlEqual(target.innerHTML, `
<div>12 240 140, 60+4=64</div>
<div>35 700 240, 100+7=107</div>
<div>48 960 280, 120+8=128</div>
`);
component.boxes = [
{width: 3, height: 4},
{width: 4, height: 5},
{width: 5, height: 6},
{width: 6, height: 7}
];
assert.htmlEqual(target.innerHTML, `
<div>12 240 140, 60+4=64</div>
<div>20 400 180, 80+5=85</div>
<div>30 600 220, 100+6=106</div>
<div>42 840 260, 120+7=127</div>
`);
}
};

@ -0,0 +1,19 @@
<script>
export let boxes = [
{width: 3, height: 4},
{width: 5, height: 7},
{width: 6, height: 8},
];
export let constant = 10;
function calculate(width, height, constant) {
return { area: width * height, volume: width * height * constant };
}
</script>
{#each boxes as { width, height }}
{@const {area, volume} = calculate(width, height, constant)}
{@const perimeter = (width + height) * constant}
{@const [_width, ...[_height, ...[sum]]] = [width * constant, height, width * constant + height]}
<div>{area} {volume} {perimeter}, {_width}+{_height}={sum}</div>
{/each}

@ -0,0 +1,25 @@
<script>
import { writable } from 'svelte/store';
const THING = { a: 1, b: { c: 2, d: [3, 4, writable(5), 6, 7] }, e: [6], h: 8 };
const default_g = 9;
export let { a, b: { c, d: [d_one, ...[, ...[d_three, ...{ length }]]], f }, e: [e_one], g = default_g } = THING;
export const { a: A, b: { c: C } } = THING;
</script>
<div>
a: {a},
b: {typeof b},
c: {c},
d_one: {d_one},
d_three: {$d_three},
length: {length},
f: {f},
g: {g},
e: {typeof e},
e_one: {e_one},
A: {A},
C: {C}
</div>
<div>{JSON.stringify(THING)}</div>

@ -0,0 +1,9 @@
export default {
html: `
<div>a: 1, b: undefined, c: 2, d_one: 3, d_three: 5, length: 2, f: undefined, g: 9, e: undefined, e_one: 6, A: 1, C: 2</div>
<div>{"a":1,"b":{"c":2,"d":[3,4,{},6,7]},"e":[6],"h":8}</div>
<br>
<div>a: a, b: undefined, c: 2, d_one: d_one, d_three: 5, length: 7, f: f, g: g, e: undefined, e_one: 6, A: 1, C: 2</div>
<div>{"a":1,"b":{"c":2,"d":[3,4,{},6,7]},"e":[6],"h":8}</div>
`
};

@ -0,0 +1,7 @@
<script>
import A from './A.svelte';
</script>
<A />
<br />
<A a="a" d_one="d_one" list_one="list_one" f="f" list_two_b="list_two_b" g="g" A="A" C="C" length={7} />

@ -0,0 +1,23 @@
<script>
import { writable } from "svelte/store";
let default_b = 5;
const LIST = [1, 2, 3, { a: 4 }, [5, writable(6), writable(7), 8]];
export const [
x,
,
...[, { a: list_two_a, b: list_two_b = default_b }, [, ...{ length: y }]]
] = LIST;
export let [
l,
m,
,
...[{ a: n, b: o = default_b }, [p, q, ...[r, ...{ length: s }]]]
] = LIST;
</script>
<div>
x: {x}, list_two_a: {list_two_a}, list_two_b: {list_two_b}, y: {y}, l: {l}, m: {m},
n: {n}, o: {o}, p: {p}, q: {$q}, r: {$r}, s: {s}
</div>
<div>{JSON.stringify(LIST)}</div>

@ -0,0 +1,19 @@
export default {
html: `
<div>x: 1, list_two_a: 4, list_two_b: 5, y: 3, l: 1, m: 2, n: 4, o: 5, p: 5, q: 6, r: 7, s: 1</div>
<div>[1,2,3,{"a":4},[5,{},{},8]]</div>
<br><div>x: 1, list_two_a: 4, list_two_b: 5, y: 3, l: l, m: m, n: n, o: o, p: p, q: q, r: r, s: s</div>
<div>[1,2,3,{"a":4},[5,{},{},8]]</div>
`,
async test({ component, assert, target }) {
await component.update();
assert.htmlEqual(target.innerHTML, `
<div>x: 1, list_two_a: 4, list_two_b: 5, y: 3, l: 1, m: 2, n: 4, o: 5, p: 5, q: 6, r: 7, s: 1</div>
<div>[1,2,3,{"a":4},[5,{},{},8]]</div>
<br><div>x: 1, list_two_a: 4, list_two_b: 5, y: 3, l: LL, m: MM, n: NN, o: OO, p: PP, q: QQ, r: RR, s: SS</div>
<div>[1,2,3,{"a":4},[5,{},{},8]]</div>
`);
}
};

@ -0,0 +1,36 @@
<script>
import A from "./A.svelte";
import { writable } from "svelte/store";
let x = "x",
list_two_a = "list_two_a",
list_two_b = "list_two_b",
y = writable("y"),
l = "l",
m = "m",
n = "n",
o = "o",
p = "p",
q = writable("q"),
r = writable("r"),
s = "s";
export function update() {
x = "XX";
list_two_a = "LIST_TWO_A";
list_two_b = "LIST_TWO_B";
y = writable("YY");
l = "LL";
m = "MM";
n = "NN";
o = "OO";
p = "PP";
q = writable("QQ");
r = writable("RR");
s = "SS";
}
</script>
<A />
<br />
<A {x} {list_two_a} {list_two_b} {y} {l} {m} {n} {o} {p} {q} {r} {s} />

@ -0,0 +1,31 @@
export default {
before_test() {
Object.defineProperties(window.document, {
fullscreenElement: {
value: null,
configurable: true
}
});
},
// copied from window-binding
// there's some kind of weird bug with this test... it compiles with the wrong require.extensions hook for some bizarre reason
skip_if_ssr: true,
async test({ assert, target, window, component }) {
const event = new window.Event('fullscreenchange');
const div = target.querySelector('div');
Object.defineProperties(window.document, {
fullscreenElement: {
value: div,
configurable: true
}
});
window.document.dispatchEvent(event);
assert.equal(component.fullscreen, div);
}
};

@ -0,0 +1,7 @@
<script>
export let fullscreen;
</script>
<svelte:document bind:fullscreenElement={fullscreen}/>
<div />

@ -0,0 +1,24 @@
export default {
props: {
array: [
[1, 2, 3, 4, 5],
[6, 7, 8],
[9, 10, 11, 12],
[13, 14, 15, 16, 17, 18, 19, 20, 21, 22]
]
},
html: `
<p>First: 1, Second: 2, Third: 3, Elements remaining: 2</p>
<p>First: 6, Second: 7, Third: 8, Elements remaining: 0</p>
<p>First: 9, Second: 10, Third: 11, Elements remaining: 1</p>
<p>First: 13, Second: 14, Third: 15, Elements remaining: 7</p>
`,
test({ assert, component, target }) {
component.array = [[23, 24, 25, 26, 27, 28, 29]];
assert.htmlEqual( target.innerHTML, `
<p>First: 23, Second: 24, Third: 25, Elements remaining: 4</p>
`);
}
};

@ -0,0 +1,9 @@
<script>
export let array;
</script>
{#each array as [first, second, ...[third, ...{ length }]]}
<p>
First: {first}, Second: {second}, Third: {third}, Elements remaining: {length}
</p>
{/each}

@ -0,0 +1,11 @@
export default {
async test({ assert, target, window }) {
const div = target.querySelector('div');
const click = new window.MouseEvent('click');
assert.htmlEqual(target.innerHTML, '<div style="background: red;"></div>');
await div.dispatchEvent(click);
await Promise.resolve();
assert.htmlEqual(target.innerHTML, '<div style=""></div>');
}
};

@ -0,0 +1,9 @@
<script>
let bg = "red";
const handle = () => {
bg = undefined;
};
</script>
<div style:background={bg} on:click={handle}></div>

@ -0,0 +1,4 @@
export default {
// https://github.com/sveltejs/svelte/issues/6752
html: '<img height="100%" width="100%" alt="" />'
};

@ -0,0 +1 @@
<img height="100%" width="100%" alt="" {...$$restProps} />

@ -1,5 +1,5 @@
export default {
html: '<div>1024x768</div>',
html: '<div>1024x768</div><div>1</div>',
before_test() {
Object.defineProperties(window, {
@ -10,6 +10,10 @@ export default {
innerHeight: {
value: 768,
configurable: true
},
devicePixelRatio: {
value: 1,
configurable: true
}
});
},
@ -27,13 +31,17 @@ export default {
innerHeight: {
value: 456,
configurable: true
},
devicePixelRatio: {
value: 2,
configurable: true
}
});
await window.dispatchEvent(event);
assert.htmlEqual(target.innerHTML, `
<div>567x456</div>
<div>567x456</div><div>2</div>
`);
}
};

@ -1,8 +1,10 @@
<script>
export let width;
export let height;
export let devicePixelRatio;
</script>
<svelte:window bind:innerWidth={width} bind:innerHeight={height}/>
<svelte:window bind:innerWidth={width} bind:innerHeight={height} bind:devicePixelRatio={devicePixelRatio}/>
<div>{width}x{height}</div>
<div>{width}x{height}</div>
<div>{devicePixelRatio}</div>

@ -41,4 +41,8 @@
<!-- Tested header/footer not nested in section/article -->
<header role="banner"></header>
<footer role="contentinfo"></footer>
<footer role="contentinfo"></footer>
<!-- Allowed -->
<!-- svelte-ignore a11y-no-noninteractive-element-to-interactive-role -->
<menu role="menu" />

@ -1,8 +1,8 @@
[
{
"code": "invalid-rest-eachblock-binding",
"message": "...rest operator will create a new object and binding propagation with original object will not work",
"start": { "line": 8, "column": 24 },
"message": "The rest operator (...) will create a new object and binding 'rest' with the original object will not work",
"start": { "line": 8, "column": 27 },
"end": { "line": 8, "column": 31 }
}
]

@ -1,8 +1,8 @@
[
{
"code": "invalid-rest-eachblock-binding",
"message": "...rest operator will create a new object and binding propagation with original object will not work",
"start": { "line": 5, "column": 32 },
"end": { "line": 5, "column": 39 }
"message": "The rest operator (...) will create a new object and binding 'rest' with the original object will not work",
"start": { "line": 5, "column": 35 },
"end": { "line": 5, "column": 39 }
}
]

@ -0,0 +1,9 @@
<script>
const a = [[1, 2, 3, 4, 5]];
</script>
{#each a as [first, second, ...[third, ...{ length }]]}
<p>{first}, {second}, {length}</p>
<input bind:value={third} />
<input bind:value={length} />
{/each}

@ -0,0 +1,26 @@
[
{
"code": "invalid-rest-eachblock-binding",
"end": {
"column": 37,
"line": 5
},
"message": "The rest operator (...) will create a new object and binding 'third' with the original object will not work",
"start": {
"column": 32,
"line": 5
}
},
{
"code": "invalid-rest-eachblock-binding",
"end": {
"column": 50,
"line": 5
},
"message": "The rest operator (...) will create a new object and binding 'length' with the original object will not work",
"start": {
"column": 44,
"line": 5
}
}
]

@ -1,8 +1,8 @@
[
{
"code": "invalid-rest-eachblock-binding",
"message": "...rest operator will create a new object and binding propagation with original object will not work",
"start": { "line": 5, "column": 25 },
"message": "The rest operator (...) will create a new object and binding 'rest' with the original object will not work",
"start": { "line": 5, "column": 28 },
"end": { "line": 5, "column": 32 }
}
]

@ -1,6 +1,6 @@
[{
"code": "invalid-binding",
"message": "'potato' is not a valid binding on <svelte:window> — valid bindings are innerWidth, innerHeight, outerWidth, outerHeight, scrollX, scrollY or online",
"message": "'potato' is not a valid binding on <svelte:window> — valid bindings are innerWidth, innerHeight, outerWidth, outerHeight, scrollX, scrollY, devicePixelRatio or online",
"start": {
"line": 1,
"column": 15

Loading…
Cancel
Save