Code Monkey home page Code Monkey logo

resize-observer's People

Contributors

dependabot[bot] avatar jayakrishnanamburu avatar lexszentmiklosy avatar tremaynechrist avatar vanishcode avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

resize-observer's Issues

Writing modes are not handled

When writing mode changes, the box algorithm should use the correct value for both inlineSize and blockSize. Chrome currently has the same bug which can be found here.

Demo: https://jsfiddle.net/dholbert/ce094nxj/

<style>
.outer {
  display: inline-block;
}
.outer:hover {
  writing-mode: vertical-rl;
}

#divA {
  width: 300px;
  height: 200px;
  border: 1px solid black;
  background: yellow;
}

#divB {
  inline-size: 300px;
  block-size: 200px;
  border: 1px solid black;
  background: pink
}
</style>
<div class="outer">
  <div id="divA">My physical dimensions never change (which means my inline-size/block-size get swapped on hover)</div>
</div>
<div class="outer">
  <div id="divB">My logical dimensions never change</div>
</div>

Support latest box option: device-pixel-content-box

Add support for observing a new box size option, device-pixel-content-box.

const canvasEl = document.querySelector('canvas');
const ro = new ResizeObserver((entries, observer) => {
  ...
});

// Observes the actual device pixel dimensions of the element
ro.observe(canvasEl, { box: 'device-pixel-content-box' });

w3c/csswg-drafts#3554

nrwl nx and jest causes SyntaxError: Cannot use import statement outside a module

Describe the bug
I'm using nrwl/nx and jest to build my angular app.
I want to use @juggle/resize-observer in the project.
It works great when developing and in production,
but jest doesn't seem to like the library.

When running my tests I get

Test suite failed to run

    /Users/leon/Projects/myproject/node_modules/@juggle/resize-observer/lib/ResizeObserver.js:1
    ({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){import { ResizeObserverController } from './ResizeObserverController';
                                                                                             ^^^^^^

    SyntaxError: Cannot use import statement outside a module

      1 | import { Observable } from 'rxjs'
    > 2 | import { ResizeObserver } from '@juggle/resize-observer'
        | ^
      3 | 
      4 | /**
      5 |  * Create an observable which will emit every time the passed in elements get resized

      at ScriptTransformer._transformAndBuildScript (../../../node_modules/@jest/transform/build/ScriptTransformer.js:537:17)
      at ScriptTransformer.transform (../../../node_modules/@jest/transform/build/ScriptTransformer.js:579:25)
      at Object.<anonymous> (../../view/ui/src/lib/resize-observable.ts:2:1)

I know this isn't your problem, it's a jest problem, but I thought that I won't be the only one getting this error, so I thought we could try to find a solution together.

To Reproduce
create a nx workspace with an angular app
add a component
import @juggle/resize-observer in the component
then run npm test

Expected behavior
That the library should work when testing using jest.

Frameworks/Libraries used
Angular
Jest

Desktop (please complete the following information):

  • OS: mac catalina
  • Browser chrome
  • Version 78

Additional context
It has something to do with how the library is packaged and that it has es2015 imports.
maybe we need to have a both a "main" field in the package.json which points to a commonjs version, and a "module" version which points to a es2015 version?

If parent does not have display, size is returned as NaN.

Describe the bug
Size returned is NaN

To Reproduce
Steps to reproduce the behavior:

  1. Create a div with display:none
  2. Append and observe a new element, inside of the div
  3. The first observation returns NaN

Expected behavior
There should be no observation as the element has no display.

Use MicroTask to fire ResizeObserver callbacks

Currently this library modifys the native RAF to make sure that ResizeObserver callbacks are executed at the very end of the frame. Instead of this, it would be good to use a MicroTask to schedule the last RAF in the chain. This will prevent merging all callbacks into one RAF and will keep it inline with the native implementation.

A side effect of this, is that any other RAF which is also scheduled in a MicroTask could cause ResizeObserver callbacks to be executed before the final RAF. This is extremely unlikely though, as it doesn't exactly make sense to do this when using RAF normally.

IE9 IE10 support?

This is here to gather feedback on the need for this. Please comment below ๐Ÿ‘‡

Fails to detect transition start

As there is limited support for transitionstart events, we need another way to detect when a transition has started.

I think we can catch most transitions, which do not have a delayed start time, by always checking next render.

`SyntaxError: Unexpected token {` on SSR (Next.js)

Describe the bug
react-three-fiber is using this lib and I'm trying to use it with next.js.
I'm getting this error

Unexpected token {
./node_modules/@juggle/resize-observer/lib/ResizeObserver.js:1
(function (exports, require, module, __filename, __dirname) { import { ResizeObserverController } from './ResizeObserverController';
                                                                     ^

SyntaxError: Unexpected token {
    at new Script (vm.js:79:7)
    at createScript (vm.js:251:10)
    at Object.runInThisContext (vm.js:303:10)
    at Module._compile (internal/modules/cjs/loader.js:656:28)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:699:10)
    at Module.load (internal/modules/cjs/loader.js:598:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:537:12)
    at Function.Module._load (internal/modules/cjs/loader.js:529:3)
    at Module.require (internal/modules/cjs/loader.js:636:17)
    at require (internal/modules/cjs/helpers.js:20:18)
    at Object.<anonymous> (./node_modules/react-three-fiber/web.cjs.js:17:22)
    at Module._compile (internal/modules/cjs/loader.js:688:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:699:10)
    at Module.load (internal/modules/cjs/loader.js:598:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:537:12)
    at Function.Module._load (internal/modules/cjs/loader.js:529:3)

which you can see in the code sandbox example below.

To Reproduce
Here is code sandbox reproduction https://codesandbox.io/s/resize-observer-issue-98jp2

Expected behavior
Should work without error.

Frameworks/Libraries used
Next.js, React, react-three-fiber

Desktop (please complete the following information):

  • OS: Mac OS
  • Browser: chrome
  • Version: 79.0.3945.88

Source Key in package.json

I've never seen a "source" key in a package.json before.

What is the intent behind that, given that sources aren't being distributed in the npm package?

devicePixelBorderBoxSize should return null on non-canvas elements

Describe the bug
devicePixelBorderBoxSize gets reported, even on non-canvas elements.

To Reproduce
Steps to reproduce the behavior:

  1. Observe a HTMLDivElement
  2. Resize the div to fire the observer callback
  3. devicePixelBorderBoxSize gets reported

Expected behavior
devicePixelBorderBoxSize should return null, as it's currently only for canvas elements.

wpt fail: writing-modes

Currently failing web platform tests:
https://github.com/web-platform-tests/wpt/blob/master/resize-observer/observe.html#L424
https://github.com/web-platform-tests/wpt/blob/master/resize-observer/observe.html#L482
https://github.com/web-platform-tests/wpt/blob/master/resize-observer/observe.html#L523

When writing mode changes, the box algorithm should use the correct value for both inlineSize and blockSize. Chrome currently has the same bug which can be found here.

Demo: https://jsfiddle.net/dholbert/ce094nxj/

<style>
.outer {
  display: inline-block;
}
.outer:hover {
  writing-mode: vertical-rl;
}

#divA {
  width: 300px;
  height: 200px;
  border: 1px solid black;
  background: yellow;
}

#divB {
  inline-size: 300px;
  block-size: 200px;
  border: 1px solid black;
  background: pink
}
</style>
<div class="outer">
  <div id="divA">My physical dimensions never change (which means my inline-size/block-size get swapped on hover)</div>
</div>
<div class="outer">
  <div id="divB">My logical dimensions never change</div>
</div>

Improve Shadow DOM support for Web Components

Currently the library only listens to mutations on the main document level. This means that any non-user actioned DOM changes inside a shadow root will not be noticed.

Most of the time this will not be an issue, as user interaction is usually the main cause for resizing to take place. That being said, there are some circumstances where this will cause issues.

RAF polyfill interferes with Angular Zone

Describe the bug
I'm using this package as a polyfill for window.ResizeObserver when the native one is not available. However, this package will unconditionally override the global RAF callback, which may conflict with the RAF override provided in Angular zone.js package, causing the loss of zone information.

The underlying requestAnimationFrame is called only for the first RAF call during a frame, and all the queued RAF callbacks are executed in the same "zone" (i.e. the "zone" of first RAF callback.)

// Override requestAnimationFrame to make sure
// calculations are performed after any changes may occur.
// * Is there another way to schedule without modifying the whole function?
global.requestAnimationFrame = function (callback): number {
if (typeof callback !== 'function') {
throw new Error('requestAnimationFrame expects 1 callback argument of type function.');
}

I understand working with multiple polyfills can be tricky. However, I think it would be better if you do not apply the RAF polyfill when importing the module, but when the first ResizeObserver instance from this library is created. In this case, at least I can ensure RAF is not replaced when I'm using Browser's native ResizeObserver (e.g. on Chrome).

To Reproduce
See https://angular-cqmqgl.stackblitz.io/ . Open the console to see the error. See the Expected behavior part for full project.

image

Basically, what I have done is:

  • Start an Angular application.
  • Import the @juggle/resize-observer module.
  • Call requestAnimationFrame both inside and outside NgZone, in a way that the RAF callbacks are executed in the same frame. Check if we are inside Angular zone in the RAF callbacks with NgZone.assertInAngularZone and NgZone.assertNotInAngularZone().
  • Sample code to reproduce the bug is like this
import { Component, NgZone } from '@angular/core';
import { ResizeObserver as ResizeObserverPolyfill } from '@juggle/resize-observer';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  name = 'Angular';
  myText = String(ResizeObserverPolyfill);
  constructor(private _zone: NgZone) {
  }
  ngOnInit() {
    // RAF callback inside NgZone
    rafCallback(this._zone, true, true);
    // RAF callback outside NgZone
    rafCallback(this._zone, false, true);
  }
}

function rafCallback(zone: NgZone, isInZone: boolean, suppressAssertion?: boolean) {
  if (isInZone) {
    suppressAssertion || NgZone.assertInAngularZone();
    zone.run(() => window.requestAnimationFrame(() => rafCallback(zone, isInZone)));
  } else {
    suppressAssertion || NgZone.assertNotInAngularZone();
    zone.runOutsideAngular(() => window.requestAnimationFrame(() => rafCallback(zone, isInZone)));
  }
}

Expected behavior
The assertNotInAngularZone call should pass.

Sample Code
See https://stackblitz.com/edit/angular-cqmqgl .

Desktop (please complete the following information):

  • OS: Windows 10
  • Browser: Chromium Edge
  • Version: 79.0.287.3

Smartphone (please complete the following information):

  • Device:
  • OS:
  • Browser:
  • Version:

Additional context

Too many change detection triggered when we use ResizeObserver inside a polymer webcomponent placed in an Angular application

Describe the bug
Too many change detection triggered when we use ResizeObserver inside a polymer webcomponent placed in an Angular application. At the same time if we are not using ResizeObserver Angular change detection's number is very few.

To Reproduce
Steps to reproduce the behavior:

  1. Create an Angular application
  2. Add a polymer webcomponent dropdown
  3. Add a ResizeObserve instance inside 'ready()' call which will observe the webcomponent

this.resizeObserver = new ResizeObserver((entries, observer) => { self.handleChange(); });

  1. Enable resizeObserver only when dropdown is active (clicked and items shown)

Expected behavior
Change detection gets triggered only once for resize or UI modification.

Sample Code

if(this.active === true) {
        console.log("observing");
        this.resizeObserver.observe(_this);
      } else {
        console.log("unobserved");
        this.resizeObserver.unobserve(_this);
      }

Desktop (please complete the following information):

  • OS: Windows 10
  • Browser: IE11
  • Version: 11

Additional context
Why a webcomponent inside Angular is triggering too many change detections, when observe(element) is on.
Note: The resize observer correctly notifies about the size change and we could respond to it. Only thing is the Angular change detection getting triggered more number of times (in IE11) when observe is ON.

Regards
Basanth

No resize observations fired if animation loop is created, using requestAnimationFrame

Describe the bug
No resize observations are fired

To Reproduce
Steps to reproduce the behavior:

  1. Create an animation loop, using raf
function loop () {
  requestAnimationFrame(loop);
}
loop();

Expected behavior
Resize observation should still work and notifications should be sent.

Additional context
This is happening because the scheduled task is always being pushed to the next frame, so no calculations will take place until the animation loop has stopped.

Transitions are not causing notifications to be fired in some instances

Describe the bug
On occasions, notifications are not being sent when a transition starts to change an elements dimensions.

To Reproduce
Steps to reproduce the behavior:

  1. Have an element which transitions its width on active state
  2. Click on element with transition
  3. Depending on how quickly the transition changes the dimensions, depend on whether notifications are sent or not.

Expected behavior
Notifications should be sent if possible.

Additional context
There is code in the library to help with this however this seems to being skipped after some performance improvements were added.

Resize loop error is fired when element is removed from DOM

Describe the bug
Resize loop error is fired when element is removed from the DOM

To Reproduce
Steps to reproduce the behavior:

  1. Observe an element
  2. Remove the element from the document

Expected behavior
An observation should be reported and no resize loop error should be fired

Stop listening to events if already scheduled, listen again afterwards.

If many events happen at the same time, it can impair performance. Most events do not require this additional logic, as they are from user interaction, however, animation events can me fired multiple times in the same frame and this should be handled and improved.

Potential Fix:

  • Listen to all events.
  • If any one event schedules a recalc, stop listening to all other events.
  • After resize notifications have been sent, start listening to all events again.

"TypeError: Invalid calling object" in IE11

Describe the bug
In IE11 I have a problem with "TypeError: Invalid calling object" in the console. In other browsers (Chrome, Firefox, Safari) everything works correctly.

Error in mounted hook: "TypeError: Invalid calling object"
  found in
    ---> <App> at src/App.vue
      <Root>

Sample Code
Please fork this Debug Template and help identify the issue.

Desktop (please complete the following information):

  • OS: Windows 10
  • Browser IE11
  • Version 11.737.17763.0

Additional context
My script:

    const ro = new ResizeObserver((entries, observer) => {
      for (var entry of entries) {
        this.$store.dispatch('changeScreenSize', entry.contentRect.width);
        this.$emit('embedResized');
      }
    });
    ro.observe(wrapperEl);

Server side rendering support

Describe the bug

The package causes the build system to crash when used in server-side rendering app

To Reproduce

Cannot be reproduced in an online platform, but try to include the package in any server-side rendering environment

Expected behavior

Should support server-side rendering


The error thrown by the compiler:

var requestAnimationFrame = window.requestAnimationFrame;
ReferenceError: window is not defined

ResizeObserver.min.js

It would be great to have a .min.js file in every release, so that it can be used in the extremely simple way of doing nothing but <script src="ResizeObserver.min.js"></script>.

v1

Initial checklist for v1.0.0 release!

Required:

  • Support #1 (Partially Supported)
  • Fix #11 #12 #13
  • Setup ESLint (or alike)
  • Add license information
  • Clean release output (remove source).
  • Comment and document code where necessary.
  • Give feedback to users when observer is not used correctly.
  • Test more use cases and update tests to check all box sizes.
  • Make sure the polyfill is inline with the latest draft spec, watching out for changes to box options (w3c/csswg-drafts#3329).
  • Tidy code / Final review.

Nice to have:

  • Add more samples to README.
  • Compare performance - polyfill vs native.
  • Update demo playground / Create new chat demo.
  • Add contribution model and guidelines

Add compiled dist version to npm package?

Wondering whether to add a compiled ES5 version of the library which polyfills the global ResizeObserver on the window.

This makes it easier to integrate into older projects.

Would this be helpful?

Missing lib in release 2.0.1

Describe the bug
The latest release 2.0.1 has no lib folder with build artifacts (https://unpkg.com/@juggle/[email protected]/lib/ResizeObserver.js).

The previous 2.0.0 release works correctly (https://unpkg.com/@juggle/[email protected]/lib/ResizeObserver.js).

To Reproduce
Steps to reproduce the behavior:

  1. npm i @juggle/resize-observer
  2. import ResizeObserver from '@juggle/resize-observer'
  3. The file /lib/ResizeObserver.js cannot be found.

Expected behavior
The release has the lib folder with build artifacts.

Additional context
Thank you for developing this great polyfill :)

Improve device-pixel-content-box notifications when switching resolutions

When a window is dragged across screens with different resolutions, no notification is fired when observing device-pixel-content-box. To improve this, use matchMedia API to watch for resolution changes.

matchMedia(`(resolution: ${window.devicePixelRatio}dppx)`)
.addEventListener('change', schedule);

v2

This major version upgrade will update the library to cover the new shape of the ResizeObserverEntry.

entry = {
  target: <element>,
  contentRect: { /* v1 backwards compat */ },
  borderBox: null,
  contentBox: {
    inline: 300,
    block: 200
  }
}

Confirmed changes:

  • Remove scrollBox support.
  • Remove devicePixelBorderBox support.
  • Return null for unobserved boxes.
  • Rename borderBoxSize to borderBox.
  • Rename contentSize to contentBox.
  • Rename inlineSize to inline.
  • Rename blockSize to block.
  • Update internal names for box sizes.
  • Remove canvas checks for device-pixel-border-box.

Needs confirmation:

  • Create new key based on element and options?
  • Observing the same element multiple times, with different options, is supported?

Additional updates:

  • Update readme examples and link to v1 version of readme
  • Updated all demos to use v2

Potential upcoming changes:

  • Fragmentation of element boxes (unlikely to be anytime soon).
  • Add offset information to entry.

Doesn't work on percentage-sized svg elements

On an svg with percentage width it wont trigger after normal resize by the resize of the surrounding elements. I didnt test if it works on other kinds of css width or height definition.

I imagine the svg elements are taken into account on the api but im not sure if im missing something.

wpt fail: observer methods should be enumerable

Currently the methods on the object are not set to be enumerable and the following code will print nothing.

const ro = new ResizeObserver(() => {});

for (let key in ro) {
  console.log(ro);
}

// observe
// unobserve
// disconnect

NaN is returned on some dimensions

NaN can be returned in some entries entries. This happens when auto is returned from cs.width or cs.height, due to an element's display style being set to none.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.