W3C

Resize Observer 1

Editor’s Draft,

This version:
https://github.com/WICG/ResizeObserver/
Editor:
(Google)

Abstract

This specification describes an API for observing changes to Element’s size.

Status of this document

This section describes the status of this document at the time of its publication. Other documents may supersede this document. A list of current W3C publications and the latest revision of this technical report can be found in the W3C technical reports index at http://www.w3.org/TR/.

This document was published by the Web Performance Working Group as an Editors Draft. This document is intended to become a W3C Recommendation. Feedback and comments on this specification are welcome. Please use Github issues. Discussions may also be found in the public-web-perf@w3.org archives.

Publication as an Editors Draft does not imply endorsement by the W3C Membership. This is a draft document and may be updated, replaced or obsoleted by other documents at any time. It is inappropriate to cite this document as other than work in progress.

This document was produced by a group operating under the 5 February 2004 W3C Patent Policy. W3C maintains a public list of any patent disclosures made in connection with the deliverables of the group; that page also includes instructions for disclosing a patent. An individual who has actual knowledge of a patent which the individual believes contains Essential Claim(s) must disclose the information in accordance with section 6 of the W3C Patent Policy.

This document is governed by the 1 March 2017 W3C Process Document.

1. Introduction

This section is non-normative.

Responsive Web Components need to respond to content rect size changes. An example is an Element that displays a map:

Responsive Web Applications can already respond to viewport size changes. This is done with CSS media queries, or window.resize event.

The ResizeObserver API is an interface for observing changes to Element's content rect’s width and height. It is an Element's counterpart to window.resize event.

ResizeObserver’s notifications can be used to respond to changes in Element's size. Some interesting facts about these observations:

<canvas id="elipse" style="display:block"></canvas>
<div id="menu" style="display:block;width:100px">
    <img src="hamburger.jpg" style="width:24px;height:24px">
    <p class="title">menu title</p>
</div>
// In response to resize, elipse paints an elipse inside a canvas
document.querySelector('#elipse').handleResize = entry => {
    entry.target.width = entry.contentRect.width;
    entry.target.height = entry.contentRect.height;
    let rx = Math.floor(entry.contentRect.width / 2);
    let ry = Math.floor(entry.contentRect.height / 2);
    let ctx = entry.target.getContext('2d');
    ctx.beginPath();
    ctx.ellipse(rx, ry, rx, ry, 0, 0, 2 * Math.PI);
    ctx.stroke();
}
// In response to resize, change title visibility depending on width
document.querySelector('#menu').handleResize = entry => {
    let title = entry.target.querySelector(".title")
    if (entry.contentRect.width < 40)
        title.style.display = "none";
    else
        title.style.display = "inline-block";
}

var ro = new ResizeObserver( entries => {
  for (let entry of entries) {
    let cs = window.getComputedStyle(entry.target);
    console.log('watching element:', entry.target);
    console.log(entry.contentRect.width,' is ', cs.width);
    console.log(entry.contentRect.height,' is ', cs.height);
    console.log(entry.contentRect.top,' is ', cs.paddingTop);
    console.log(entry.contentRect.left,' is ', cs.paddingLeft);
    if (entry.target.handleResize)
        entry.target.handleResize(entry);
  }
});
ro.observe(document.querySelector('#elipse'));
ro.observe(document.querySelector('#menu'));

2. Resize Observer API

2.1. ResizeObserver interface

The ResizeObserver interface is used to observe changes to Element's content rect.

It is modeled after MutationObserver and IntersectionObserver.

[Constructor(ResizeObserverCallback callback),
    Exposed=Window]
interface ResizeObserver {
    void observe(Element target);
    void unobserve(Element target);
    void disconnect();
};
new ResizeObserver(callback)
  1. Let this be a new ResizeObserver object.

  2. Set this internal callback slot to callback.

  3. Add this to Document's resizeObservers slot.

observe(target)

Adds target to the list of observed elements.

  1. If target is in observationTargets slot, return.

  2. Let resizeObservation be new ResizeObservation(target).

  3. Add the resizeObservation to the observationTargets slot.

unobserve(target)

Removes target from the list of observed elements.

  1. Let observation be ResizeObservation in observationTargets whose target slot is target.

  2. If observation is not found, return.

  3. Remove observation from observationTargets

disconnect()

1) Clear the observationTargets list.

2) Clear the activeTargets list.

2.2. ResizeObserverCallback

callback ResizeObserverCallback = void (sequence<ResizeObserverEntry> entries, ResizeObserver observer)

This callback delivers ResizeObserver's notifications. It is invoked by a broadcast active observations algorithm.

2.3. ResizeObserverEntry

[Constructor(Element target)
]
interface ResizeObserverEntry {
    readonly attribute Element target;
    readonly attribute DOMRectReadOnly contentRect;
};
target, of type Element, readonly

The Element whose size has changed.

contentRect, of type DOMRectReadOnly, readonly

Element's content rect when ResizeObserverCallback is invoked.

new ResizeObserverEntry(target)
  1. Let this be a new ResizeObserverEntry.

  2. Set this target slot to target.

  3. If target is not an SVG element do these steps:

    1. Set this.contentRect.width to target.content width.

    2. Set this.contentRect.height to target.content height.

    3. Set this.contentRect.top to target.padding top.

    4. Set this.contentRect.left to target.padding left.

  4. If target is an SVG element do these steps:

    1. Set this.contentRect.top and this.contentRect.left to 0.

    2. Set this.contentRect.width to target.bounding box.width.

    3. Set this.contentRect.height to target.bounding box.height.

2.4. ResizeObservation

ResizeObservation holds observation information for a single Element. This interface is not visible to Javascript.
[Constructor(Element target)
]
interface ResizeObservation {
    readonly attribute Element target;
    readonly attribute float broadcastWidth;
    readonly attribute float broadcastHeight;
    boolean isActive();
};
target, of type Element, readonly

The observed Element.

broadcastWidth, of type float, readonly

Width of last broadcast content width.

broadcastHeight, of type float, readonly

Width of last broadcast content height.

new ResizeObservation(target)
  1. Let this be a new ResizeObservation object

  2. Set this internal target slot to target

  3. Set this broadcastWidth slot to 0.

  4. Set this broadcastHeight slot to 0.

isActive()
  1. If target is an HTML element do these steps:

    1. If target.content width != broadcastWidth return true.

    2. If target.content height != broadcastHeight return true.

  2. If target is an SVGGraphicsElement do these steps:

    1. If target.bounding box width != broadcastWidth return true.

    2. If target.bounding box height != broadcastHeight return true.

  3. return false.

3. Processing Model

3.1. Internal Slot Definitions

3.1.1. Document

Document has a resizeObservers slot that is a list of ResizeObservers in this document. It is initialized to empty.

3.1.2. ResizeObserver

ResizeObserver has a callback slot, initialized by constructor.

ResizeObserver has an observationTargets slot, which is a list of ResizeObservations. It represents all Elements being observed.

ResizeObserver has a activeTargets slot, which is a list of ResizeObservations. It represents all Elements whose size has changed since last observation broadcast that are eligible for broadcast.

ResizeObserver has a skippedTargets slot, which is a list of ResizeObservations. It represents all Elements whose size has changed since last observation broadcast that are **not** eligible for broadcast

3.2. CSS Definitions

3.2.1. content rect

DOM content rect is a rect whose:

content width spec does not mention how multi-column layout affects content box. In this spec, content width of an Element inside multi-column is the result of getComputedStyle(Element).width. This currently evaluates to width of the first column.

Having content rect position be padding-top/left is useful for absolute positioning of target’s children. Absolute position coordinate space origin is topLeft of the padding rect.

Watching content rect means that:

Web content can also contain SVG elements. SVG Elements define bounding box instead of a content box. Content rect for SVGGraphicsElements is a rect whose:

3.3. Algorithms

3.3.1. Gather active observations at depth

It computes all active observations for a document. To gather active observations at depth, run these steps:

  1. Let depth be the depth passed in.

  2. For each observer in resizeObservers run these steps:

    1. Clear observer’s activeTargets, and skippedTargets

    2. For each observation in observer.observationTargets run this step:

      1. If observation.isActive() is true

        1. Let targetDepth be result of calculate depth for node for observation.target.

        2. If targetDepth is greater than depth then add observation to activeTargets.

        3. Else add observation to skippedTargets.

3.3.2. Has active observations

To determine if Document has active observations run these steps:

  1. For each observer in resizeObservers run this step:

    1. If observer.activeTargets is not empty, return true.

  2. return false.

3.3.3. Has skipped observations

To determine if Document has skipped observations run these steps:

  1. For each observer in resizeObservers run this step:

    1. If observer.skippedTargets is not empty, return true.

  2. return false.

3.3.4. Broadcast active observations

broadcast active observations delivers all active observations in a document, and returns the depth of the shallowest broadcast target depth.

To broadcast active observations for a document, run these steps:

  1. Let shallowestTargetDepth be ∞

  2. For each observer in document.resizeObservers run these steps:

    1. If observer.activeTargets slot is empty, continue.

    2. Let entries be an empty list of ResizeObserverEntryies.

    3. For each observation in activeTargets perform these steps:

      1. Let entry be new ResizeObserverEntry(observation.target)

      2. Add entry to entries

      3. Set observation.broadcastWidth to entry.contentRect.width.

      4. Set observation.broadcastHeight to entry.contentRect.height.

      5. Set targetDepth to the result of calculate depth for node for observation.target.

      6. Set shallowestTargetDepth to targetDepth if targetDepth < shallowestTargetDepth

    4. Invoke observer.callback with entries.

    5. Clear observer.activeTargets.

  3. Return shallowestTargetDepth.

3.3.5. Deliver Resize Loop Error

To deliver resize loop error notification run these steps:

  1. Create a new ErrorEvent.

  2. Initialize event’s message slot to "ResizeObserver loop completed with undelivered notifications.".

  3. Dispach the event to document’s window.

3.3.6. Calculate depth for node

To calculate depth for node node run these steps:

  1. Let p be the parent-traversal path from node to a root Element of this element’s DOM tree.

  2. Return number of nodes in p.

3.4. ResizeObserver Lifetime

A ResizeObserver will remain alive until both of these conditions are met:

3.5. External Spec Integrations

3.5.1. HTML Processing Model: Event Loop

ResizeObserver processing happens inside the step 7.12 of the HTML Processing Model event loop.

Step 12 is currently underspecified as:

For each fully active Document in docs, update the rendering or user interface of that Document and its browsing context to reflect the current state..

Existing step 12 can be fully specified as:

For each fully active Document in docs, run the following steps for that Document and its browsing contents:

  1. recalc styles

  2. update layout

  3. paint

ResizeObserver extends step 12 with resize notifications. It tries to deliver all pending notifications by looping until no pending notifications are available. This can cause an infinite loop.

Infinite loop is prevented by shrinking the set of nodes that can notify at every iteration. In each iteration, only nodes deeper than the shallowest node in previous iteration can notify.

An error is generated if notification loop completes, and there are undelivered notifications. Elements with undelivered notifications will be considered for delivery in the next loop.

Step 12 with ResizeObserver notifications is:

For each fully active Document in docs, run the following steps for that Document and its browsing contentx:

  1. recalc styles

  2. update layout

  3. set depth to 0

  4. gather active observations at depth depth for Document

  5. repeat while (document has active observations)

    1. set depth to broadcast active observations

    2. recalc styles

    3. update layout

    4. gather active observations at depth depth for Document

  6. if Document has skipped observations then deliver resize loop error notification

  7. update the rendering or user interface of Document and its browsing context to reflect the current state.

Index

Terms defined by this specification

Terms defined by reference

References

Normative References

[CSSOM-VIEW-1]
Simon Pieters. CSSOM View Module. URL: https://www.w3.org/TR/cssom-view-1/
[DOM]
Anne van Kesteren. DOM Standard. Living Standard. URL: https://dom.spec.whatwg.org/
[GEOMETRY-1]
Simon Pieters; Dirk Schulze; Rik Cabanier. Geometry Interfaces Module Level 1. URL: https://www.w3.org/TR/geometry-1/
[HTML]
Anne van Kesteren; et al. HTML Standard. Living Standard. URL: https://html.spec.whatwg.org/multipage/
[WebIDL]
Cameron McCormack; Boris Zbarsky; Tobie Langel. Web IDL. URL: https://www.w3.org/TR/WebIDL-1/

IDL Index

[Constructor(ResizeObserverCallback callback),
    Exposed=Window]
interface ResizeObserver {
    void observe(Element target);
    void unobserve(Element target);
    void disconnect();
};

callback ResizeObserverCallback = void (sequence<ResizeObserverEntry> entries, ResizeObserver observer)

[Constructor(Element target)
]
interface ResizeObserverEntry {
    readonly attribute Element target;
    readonly attribute DOMRectReadOnly contentRect;
};

[Constructor(Element target)
]
interface ResizeObservation {
    readonly attribute Element target;
    readonly attribute float broadcastWidth;
    readonly attribute float broadcastHeight;
    boolean isActive();
};