Layout Transition Primitives

Unofficial Proposal Draft,

This version:
http://tabatkins.github.io/specs/layout-transitions/
Issue Tracking:
Inline In Spec
GitHub Issues
Editors:
(Google)
Tab Atkins Jr. (Google)
Suggest an Edit for this Spec:
GitHub Editor

Abstract

Primitive JavaScript operations to enable layout transition effects.

CSS is a language for describing the rendering of structured documents (such as HTML and XML) on screen, on paper, in speech, etc.

Status of this document

1. Introduction

[CSS3-TRANSITIONS] provide web authors with the ability to generate smooth transitioning effects when mutating the CSS of their web pages. However, the transitions that can be generated in this manner are limited in important ways, which make it difficult or impossible to use them in some cases.

In particular, CSS Transitions only operate on computed style values, such as between 100px and 200px; values that rely on layout, such as width: auto, can’t be used as the start or end of a transition.

Furthermore, CSS Transitions only work over actual CSS property values, but some of aspects of an element one might wish to transition are derived from other properties rather than being directly specified. For example, the position and size of an element positioned with Grid Layout is derived from its grid-placement properties, rather than being directly specified. An author can transition the grid-placement properties, but that will merely cause the element to "skip" from cell to cell as its grid-row-start and similar properties transition as integers; it won’t have the desired effect of making the element smoothly move between its start and end position. Relatedly, there is no reasonable way to express a transition when an element enters or leaves the document.

These shortcomings make [CSS3-TRANSITIONS] unsuitable for specifying transitions between laid out states of a web page. This specification provides a set of primitive JavaScript methods to enable transition-like graphical effects for complex layout changes.

1.1. Motivating Examples

Layout transition primitives can be used to programmatically control transitions between layout states. For example:

To transition element myDiv from an initial laid out position to a new position:
myDiv.suspendPainting();
CSS.elementSources.myDivSnapshot = myDiv.snapshot();
var div = document.createElement('div');
div.style.position = 'absolute';
div.style.left = myDiv.offsetLeft + 'px';
// ...
div.style.backgroundImage = 'element(myDivSnapshot)';
document.body.appendChild(div);
// perform layout
div.animate({left: myDiv.offsetLeft, ... }, 1).source.onEnd(function() {
  myDiv.resumePainting();
  div.remove();
});
Layout transition primitives also allow element insertions and removals to be smoothed.

In this example, afterDiv is the last div in a list. We wish to grow newDiv in-place before afterDiv, smoothly moving afterDiv down as we do so.

container.suspendPainting();
CSS.elementSources.afterDivSnapshot = afterDiv.snapshot();
// .. create and insert snapshot element (see previous example)
container.appendBefore(afterDiv, newDiv);
var bounds = newDiv.recastElement();
new ParGroup([
  bounds.animate([{height: 0}, {height: bounds.height}], 1),
  div.animate({top: afterDiv.top}, 1)
]).source.onEnd(function() {
  myDiv.resumePainting();
  div.remove();
});
When combined with [CSS4-IMAGES], layout transition primitves allow crossfade and transfade effects to be scripted. For example:
myDiv.suspendPainting();
CSS.elementSources.before = myDiv.snapshot();
// .. create and insert snapshot element (see previous example)
// perform layout
CSS.elementSources.after = myDiv.snapshot();
div.style.transition = 'background-image 1s';
div.style.backgroundImage = 'element(after)';
setTimeout(function() {
  myDiv.resumePainting();
  div.remove();
}, 1000);

2. IDL

partial interface Element {
  void suspendPainting();
  void resumePainting();
  Promise<OpaqueImageSnapshot> snapshot();
  ElementBounds recastElement();
  void cancelRecast();
};

interface OpaqueImageSnapshot {
};

interface ElementBounds {
  attribute DOMString left;
  attribute DOMString top;
  attribute DOMString width;
  attribute DOMString height;
  attribute DOMString transform;
  attribute DOMString transformOrigin;
  attribute DOMString opacity;
  attribute DOMString overflow;
};

Ensure that ElementBounds implements Animatable, assuming that this idea makes it into the Web Animations specification.

3. Suspending Painting - the suspendPainting() and resumePainting() methods

The suspendPainting() and resumePainting() methods on elements allow an author to control whether an element "paints", or is displayed on the screen. This is similar to using the visibility property, but more explicit and slightly more powerful. Like visibility and unlike other properties such as display, the element is still laid out and takes up space on the page as normal even if it’s not being painted.

Note: Suspending the painting of an element is commonly used with the other methods in this specification, to get the original element "out of the way" while script is simulating a transition of the element with snapshots and recastings.

When suspendPainting() is called on an element, the element’s painting suspended flag must be set. When resumePainting() is called on an element, the element’s painting suspended flag must be unset.

When an element’s painting suspended flag is toggled from unset to set, its subtree must be repainted.

This is actually trying to introduce the notion that suspendPainting() is an entry in the style updates queue. How should this be worded?

An element is suspended if its painting suspended flag is set, or if it has a parent element and that parent element is suspended.

Whether the painting suspended flag is set or unset must not change if the element is added or removed from the document.

When an element is suspended, its generated box is invisible (fully transparent, nothing is drawn), but still affects layout. This is similar to the effects of visibility: hidden

Note: Calling resumePainting() on an element which is suspended due to an ancestor having its painting suspended flag set will do nothing; the element’s painting suspended flag is already unset.

4. Snapshotting Elements - The snapshot() method

The snapshot() method takes a "snapshot" of an element, returning an image of the element at that time (even if the element is currently suspended) which is useful in implementing layout transitions, as described in the Examples section of this document.

When snapshot() is called on an element el, the user agent must perform the following steps:

  1. Let snapshot be a newly-created OpaqueImageSnapshot object. Return snapshot, and complete the rest of these steps asynchronously.
  2. Create a new style-dependent action action which, when executed, captures the current rendering of el, associates the rendering with snapshot, and resolves snapshot’s ready promise with undefined.
  3. Push action onto el’s style updates queue.

Rewrite this to return a promise for a snapshot, rather than sync-returning a snapshot that then has a ready promise.

When asked to capture the current rendering of an element el, the user agent must produce the image that would be represented by an element() function referencing el at that moment, with the image having the same width and height as el does at that moment. If el is currently suspended, for the purposes of generating this image it is treated as being not suspended.

Note: Only the current element’s suspended state is altered for the purposes of generating a snapshot image. If descendant elements are also marked as suspended, then those elements will remain transparent in the snapshot.

Note: The image does not necessarily have to be a raster bitmap, as the actual image data is never directly exposed to the page. For example, some user agents use an intermediate vector-like representation of an element before the rasterization step; this alternative representation may be produced instead, so that the image can be rendered accurately at any target size without scaling artifacts.

Note: Due to the way the style updates queue works, if an author generates a snapshot before creating a new element and assigning the snapshot as a background image, it’s guaranteed that there will be no FOUC (flash of unstyled content). Any other order might generate a FOUC, depending on timing and user-agent-specific behavior.

Note: Snapshots never "expire" or otherwise become unusable, even if the element they are snapshotting is removed or deleted.

4.1. Snapshots: the OpaqueImageSnapshot object

OpaqueImageSnapshot objects are returned by the snapshot() method, and represent the rendering of an element at the time that snapshot() is called.

For security reasons, the image data represented by an OpaqueImageSnapshot object is not obtainable by any means; the image can only be displayed indirectly, by using the OpaqueImageSnapshot object in conjunction with CSS’s element() function and the elementSources map.

An OpaqueImageSnapshot object might represent an image. If it does, it provides a paint source, with the width, height, and appearance of the image it represents.

When the ready() method of an OpaqueImageSnapshot snapshot is called, user agents must perform the following steps:

  1. Let ready promise be a newly-created Promise. Return it, and perform the rest of these steps asynchronously.
  2. When snapshot represents an image, resolve ready promise with undefined.

Is there any way for a snapshot to fail? Deleting the element before it’s rendered?

5. Recasting Painting - The recastElement() and cancelRecast() methods

While snapshotting elements into static images is appropriate for many layout transitions, sometimes it is necessary to continuously lay out the element and its contents as it changes size and shape. However, the actual element can’t be used for this purpose, as it’s busy occupying space in the layout. Instead, a suspended element can have its painting recasted, rendering it at an explicitly-set size and position without moving it in the layout as far as the outer page is concerned.

When the recastElement() method is called on an element el, the user agent must perform the following steps:

  1. If the element is not currently suspended, throw a ??? error and exit this algorithm.
  2. If the element already has an associated ElementBounds object, return that object and exit this algorithm.
  3. Create a new ElementBounds object bounds associated with el. Initialize the element bounds. Return bounds.

While an element has an associated ElementBounds object, it is recast.

If an element is recast, and stops being suspended for any reason, it must cancel recast, which causes its associated ElementBounds object to no longer be associated with it.

While an element is recast, it must be laid out twice. The first is as normal for a suspended element, to establish the space that the element takes up in the page.

The second treats the element as absolutely positioned with the initial containing block as its containing block, and the element’s width, height, left, top, opacity, and transform properties set to the corresponding values from the element’s associated ElementBounds object rather than the values obtained from the cascade. Additionally, the element’s right and bottom properties must be treated as auto for this layout. The element must then render as normal based on the results of this layout.

Modifying the element’s associated ElementBounds object must cause the element to perform its second layout with the new values, as if this were an ordinary style change.

Querying the style of any properties on the element must return the results of the first layout, not the second.

Note: Note that while an element is recast, any additional calls to recastElement() will return the same ElementBounds object.

When the cancelRecast() method is called on an element, the user agent must cancel recast on it.

Removing a recast element from the document causes that element to cancel recast. However, atomic moves within the same document do not cancel recast.

Note: recasting an element does not alter the suspended state of descendents of that element.

5.1. The ElementBounds Object

The ElementBounds object controls the position and size of a recast element’s rendering. It is returned by calling recastElement() on an element.

When asked to initialize the element bounds for an element el and an ElementBounds object eb, user agents must perform the following steps:

  1. Lay out the element as normal.
  2. Set the width, height, opacity, and transform attributes of eb to the used values of the corresponding properties from el.
  3. Set the left and top attributes of eb to the offsets of el’s left and top edges, respectively, relative to the top left corner of the initial containing block.

6. Appendix A: The Style Updates Queue

Note: This section probably isn’t best placed here, but I need some terms defined that aren’t currently defined.

Each element in a document is associated with a style updates queue, containing style updates and style-dependent actions. A style update is a pending currently-unapplied change made to the style of an element on the page which might have an effect on the style, layout, or rendering of the element. A style-dependent action is an operation which relies on the element’s style, layout, and/or rendering being fully up-to-date.

Whenever a change is made to the page’s style that may affect an element, a style update must be pushed onto the element’s style updates queue. The element’s style, layout, and/or rendering must not be updated unless a corresponding style update is at the front of the style updates queue. When a style update is applied, it must be popped from the queue.

Similarly, style-dependent actions must not be executed unless they are at the front of the style updates queue. When they are executed, they must be popped from the queue.

User agents may delay applying style updates as long as they consider reasonable so as to batch any work caused by updating styles, layout, and rendering. User agents should prioritize applying style updates that precede a style-dependent action when a style-dependent action is in the queue.

Conformance

Document conventions

Conformance requirements are expressed with a combination of descriptive assertions and RFC 2119 terminology. The key words “MUST”, “MUST NOT”, “REQUIRED”, “SHALL”, “SHALL NOT”, “SHOULD”, “SHOULD NOT”, “RECOMMENDED”, “MAY”, and “OPTIONAL” in the normative parts of this document are to be interpreted as described in RFC 2119. However, for readability, these words do not appear in all uppercase letters in this specification.

All of the text of this specification is normative except sections explicitly marked as non-normative, examples, and notes. [RFC2119]

Examples in this specification are introduced with the words “for example” or are set apart from the normative text with class="example", like this:

This is an example of an informative example.

Informative notes begin with the word “Note” and are set apart from the normative text with class="note", like this:

Note, this is an informative note.

Advisements are normative sections styled to evoke special attention and are set apart from other normative text with <strong class="advisement">, like this: UAs MUST provide an accessible alternative.

Conformance classes

Conformance to this specification is defined for three conformance classes:

style sheet
A CSS style sheet.
renderer
A UA that interprets the semantics of a style sheet and renders documents that use them.
authoring tool
A UA that writes a style sheet.

A style sheet is conformant to this specification if all of its statements that use syntax defined in this module are valid according to the generic CSS grammar and the individual grammars of each feature defined in this module.

A renderer is conformant to this specification if, in addition to interpreting the style sheet as defined by the appropriate specifications, it supports all the features defined by this specification by parsing them correctly and rendering the document accordingly. However, the inability of a UA to correctly render a document due to limitations of the device does not make the UA non-conformant. (For example, a UA is not required to render color on a monochrome monitor.)

An authoring tool is conformant to this specification if it writes style sheets that are syntactically correct according to the generic CSS grammar and the individual grammars of each feature in this module, and meet all other conformance requirements of style sheets as described in this module.

Requirements for Responsible Implementation of CSS

The following sections define several conformance requirements for implementing CSS responsibly, in a way that promotes interoperability in the present and future.

Partial Implementations

So that authors can exploit the forward-compatible parsing rules to assign fallback values, CSS renderers must treat as invalid (and ignore as appropriate) any at-rules, properties, property values, keywords, and other syntactic constructs for which they have no usable level of support. In particular, user agents must not selectively ignore unsupported property values and honor supported values in a single multi-value property declaration: if any value is considered invalid (as unsupported values must be), CSS requires that the entire declaration be ignored.

Implementations of Unstable and Proprietary Features

To avoid clashes with future stable CSS features, the CSSWG recommends following best practices for the implementation of unstable features and proprietary extensions to CSS.

Implementations of CR-level Features

Once a specification reaches the Candidate Recommendation stage, implementers should release an unprefixed implementation of any CR-level feature they can demonstrate to be correctly implemented according to spec, and should avoid exposing a prefixed variant of that feature.

To establish and maintain the interoperability of CSS across implementations, the CSS Working Group requests that non-experimental CSS renderers submit an implementation report (and, if necessary, the testcases used for that implementation report) to the W3C before releasing an unprefixed implementation of any CSS features. Testcases submitted to W3C are subject to review and correction by the CSS Working Group.

Further information on submitting testcases and implementation reports can be found from on the CSS Working Group’s website at http://www.w3.org/Style/CSS/Test/. Questions should be directed to the public-css-testsuite@w3.org mailing list.

Index

Terms defined by this specification

Terms defined by reference

References

Normative References

[CSS-COLOR-4]
Tab Atkins Jr.; Chris Lilley. CSS Color Module Level 4. 5 July 2016. WD. URL: https://www.w3.org/TR/css-color-4/
[CSS-DISPLAY-3]
Tab Atkins Jr.; Elika Etemad. CSS Display Module Level 3. 9 August 2018. WD. URL: https://www.w3.org/TR/css-display-3/
[CSS-FONT-LOADING-3]
Tab Atkins Jr.. CSS Font Loading Module Level 3. 22 May 2014. WD. URL: https://www.w3.org/TR/css-font-loading-3/
[CSS-GRID-1]
Tab Atkins Jr.; Elika Etemad; Rossen Atanassov. CSS Grid Layout Module Level 1. 14 December 2017. CR. URL: https://www.w3.org/TR/css-grid-1/
[CSS-POSITION-3]
Rossen Atanassov; Arron Eicholz. CSS Positioned Layout Module Level 3. 17 May 2016. WD. URL: https://www.w3.org/TR/css-position-3/
[CSS-TRANSFORMS-1]
Simon Fraser; et al. CSS Transforms Module Level 1. 30 November 2017. WD. URL: https://www.w3.org/TR/css-transforms-1/
[CSS2]
Bert Bos; et al. Cascading Style Sheets Level 2 Revision 1 (CSS 2.1) Specification. 7 June 2011. REC. URL: https://www.w3.org/TR/CSS2/
[CSS4-IMAGES]
Tab Atkins Jr.; Elika Etemad; Lea Verou. CSS Image Values and Replaced Content Module Level 4. 13 April 2017. WD. URL: https://www.w3.org/TR/css-images-4/
[DOM]
Anne van Kesteren. DOM Standard. Living Standard. URL: https://dom.spec.whatwg.org/
[RFC2119]
S. Bradner. Key words for use in RFCs to Indicate Requirement Levels. March 1997. Best Current Practice. URL: https://tools.ietf.org/html/rfc2119
[WebIDL]
Cameron McCormack; Boris Zbarsky; Tobie Langel. Web IDL. 15 December 2016. ED. URL: https://heycam.github.io/webidl/

Informative References

[CSS3-TRANSITIONS]
David Baron; Dean Jackson; Brian Birtles. CSS Transitions. 30 November 2017. WD. URL: https://www.w3.org/TR/css-transitions-1/

IDL Index

partial interface Element {
  void suspendPainting();
  void resumePainting();
  Promise<OpaqueImageSnapshot> snapshot();
  ElementBounds recastElement();
  void cancelRecast();
};

interface OpaqueImageSnapshot {
};

interface ElementBounds {
  attribute DOMString left;
  attribute DOMString top;
  attribute DOMString width;
  attribute DOMString height;
  attribute DOMString transform;
  attribute DOMString transformOrigin;
  attribute DOMString opacity;
  attribute DOMString overflow;
};

Issues Index

Ensure that ElementBounds implements Animatable, assuming that this idea makes it into the Web Animations specification.
This is actually trying to introduce the notion that suspendPainting() is an entry in the style updates queue. How should this be worded?
Rewrite this to return a promise for a snapshot, rather than sync-returning a snapshot that then has a ready promise.
Is there any way for a snapshot to fail? Deleting the element before it’s rendered?