Skip to content

Commit

Permalink
fix(resize): uses ResizeObserver if possible
Browse files Browse the repository at this point in the history
As discussed in sveltejs#4233, ResizeObserver is now widely available (>90% as
of 15/01/2021) so we can use it instead of a custom-built solution to
listen to resizes.

I also needed to add @types/resize-observer-browser because the type
definition for `ResizeObserver` hasn't landed in TS yet (see
microsoft/TypeScript#28502).

Closes sveltejs#4233.
  • Loading branch information
iamricard committed Jan 15, 2021
1 parent 8180c5d commit 34bb17c
Show file tree
Hide file tree
Showing 5 changed files with 23 additions and 3 deletions.
6 changes: 6 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions package.json
Expand Up @@ -105,6 +105,7 @@
"@sveltejs/eslint-config": "github:sveltejs/eslint-config#v5.6.0",
"@types/mocha": "^7.0.0",
"@types/node": "^8.10.53",
"@types/resize-observer-browser": "^0.1.5",
"@typescript-eslint/eslint-plugin": "^4.9.0",
"@typescript-eslint/parser": "^4.9.0",
"acorn": "^7.4.0",
Expand Down
4 changes: 2 additions & 2 deletions src/compiler/tsconfig.json
Expand Up @@ -3,9 +3,9 @@
"include": ["."],

"compilerOptions": {
"lib": ["es2017", "webworker"]
"lib": ["es2017", "webworker"],

// TODO: remove mocha types from the whole project
// "types": ["node", "estree"]
"types": ["node", "estree", "mocha"]
}
}
13 changes: 13 additions & 0 deletions src/runtime/internal/dom.ts
Expand Up @@ -260,6 +260,19 @@ export function is_crossorigin() {
}

export function add_resize_listener(node: HTMLElement, fn: () => void) {
if (window.ResizeObserver) {
const observer = new ResizeObserver(entries => {
for (const entry of entries) {
if (entry.target === node) {
fn();
break;
}
}
});
observer.observe(node);
return observer.disconnect;
}

const computed_style = getComputedStyle(node);

if (computed_style.position === 'static') {
Expand Down
2 changes: 1 addition & 1 deletion src/runtime/tsconfig.json
Expand Up @@ -5,7 +5,7 @@
"compilerOptions": {
"lib": ["es2015", "dom", "dom.iterable"],
"target": "es2015",
"types": [],
"types": ["resize-observer-browser"],

"baseUrl": ".",
"paths": {
Expand Down

0 comments on commit 34bb17c

Please sign in to comment.