{"action":"created","issue":{"url":"https://api.github.com/repos/whatwg/dom/issues/270","repository_url":"https://api.github.com/repos/whatwg/dom","labels_url":"https://api.github.com/repos/whatwg/dom/issues/270/labels{/name}","comments_url":"https://api.github.com/repos/whatwg/dom/issues/270/comments","events_url":"https://api.github.com/repos/whatwg/dom/issues/270/events","html_url":"https://github.com/whatwg/dom/issues/270","id":161112784,"number":270,"title":"Proposal: DOMChangeList","user":{"login":"wycats","id":4,"avatar_url":"https://avatars.githubusercontent.com/u/4?v=3","gravatar_id":"","url":"https://api.github.com/users/wycats","html_url":"https://github.com/wycats","followers_url":"https://api.github.com/users/wycats/followers","following_url":"https://api.github.com/users/wycats/following{/other_user}","gists_url":"https://api.github.com/users/wycats/gists{/gist_id}","starred_url":"https://api.github.com/users/wycats/starred{/owner}{/repo}","subscriptions_url":"https://api.github.com/users/wycats/subscriptions","organizations_url":"https://api.github.com/users/wycats/orgs","repos_url":"https://api.github.com/users/wycats/repos","events_url":"https://api.github.com/users/wycats/events{/privacy}","received_events_url":"https://api.github.com/users/wycats/received_events","type":"User","site_admin":false},"labels":[],"state":"open","locked":false,"assignee":null,"milestone":null,"comments":21,"created_at":"2016-06-20T03:54:43Z","updated_at":"2016-06-21T00:20:57Z","closed_at":null,"body":"# `DOMChangeList` and `DOMTreeConstruction`\r\n\r\n## Motivation\r\n\r\nThere are three high-level motivations for this API:\r\n\r\n1. To make it clearer and less error prone to apply a sequence of DOM operations at once, that can support the full gamut of mutations to `Element`s and `Node`s.\r\n2. For efficiency, to provide an API for constructing a sequence of DOM operations that can be:\r\n  1. constructed in a worker and transferred to the UI thread\r\n  2. constructed with a minimum of allocations\r\n  3. applied in one shot without interleaved user code\r\n3. To support, in one API, the superset of trees that can be produced using the HTML parser and using the DOM API (the HTML parser supports more tag names, while the DOM API supports more trees, such as custom elements nested inside a table).\r\n\r\n> This is an initial, minimal version of this API, which could be expanded over time with more capabilities. It should always maintain its goals of predictable, allocation-lite performance, focusing on giving user-space abstractions the capabilities they need for maximum performance.\r\n\r\n# Concepts\r\n\r\n## NodeToken\r\n\r\nA `NodeToken` is an opaque value that represents a `Node`. It can be efficiently transferred from one worker to another.\r\n\r\nIt serves two purposes:\r\n\r\n* To represent a `Node` that already exists in another worker, and can serve as the starting point of a series of mutations expressed in a `DOMChangeList`.\r\n* To represent an intermediate `Node` that was produced as part of the process of building a `DOMChangeList`.\r\n\r\n## Applying a Change\r\n\r\nThe intent of this API is to have these performance characteristics:\r\n\r\n* Creating a change list (`DOMTreeConstruction` or `DOMChangeList`) significantly reduces GC-managed allocations compared to the current DOM APIs.\r\n* Applying a change list should not create intermediate JavaScript wrappers for the DOM objects it creates, which should reduce costs.\r\n* It is possible to run the JavaScript code necessary to construct a change list in a worker, and apply it on the UI thread with minimal additional work or allocations in JavaScript.\r\n* The API creates a single immutable blob of instructions to pass to the engine, which is intended to avoid JavaScript side effects while the application proceeds. (as [Boris Zbarsky said](https://news.ycombinator.com/item?id=11780060) in his comment about proposals in this space, \"that would simplify both specification and implementation (in the sense of not having to spell out a specific processing algorithm, allowing parallelized implementation, etc).\")\r\n* It is reasonable to assume that the builder APIs could be exposed to WebAssembly.\r\n\r\nIf there is some reason that a concrete implementation of this design might not be able to accomplish these goals, it's almost certainly something we should discuss.\r\n\r\n# Details\r\n\r\n## DOMTreeConstruction\r\n\r\n> Note: Use of TypeScript generics notation in the details of this proposal does not intend to imply any additional type checking. It is simply a way to annotate which kinds of node a particular node tokens is intended to produce for clarity. This proposal expects checking at the point of application (e.g. appending a node to a non-element node doesn't make sense and would be an error at the time of application). At present, this proposal does not assume that errors in the change list cause previously applied operations to be rolled back; that is listed as an open question below.\r\n\r\n```typescript\r\n// you can create a NodeToken in the UI thread and transfer it into\r\n// a worker that constructs the DOMChangeList or DOMTreeConstruction.\r\npartial interface Node {\r\n  getToken(): NodeToken<this>;  \r\n}\r\n\r\ninterface Bounds {\r\n  firstNode: NodeToken<Node>;\r\n  lastNode: NodeToken<Node>;\r\n}\r\n\r\npartial interface Element {\r\n  // this has the same semantics as insertBefore, but takes a `DOMTreeConstruction`\r\n  insertTreeBefore(element: Element, tree: DOMTreeConstruction, reference: Node): Promise<AppliedChanges>;\r\n}\r\n\r\n// The intent of this object is to allow engines to clean up any bookkeeping maps they\r\n// need to track `NodeToken`s once the `AppliedChanges` is GCed.\r\ninterface AppliedChanges {\r\n  // this allows code that created a ChangeList to get the actual\r\n  // node they were creating so they can add listeners or change\r\n  // the node later.\r\n  getNode<T extends Node>(t: NodeToken<T>): T;\r\n}\r\n\r\n// DOMTreeConstruction is transferrable, and is backed by raw bytes. This\r\n// allows trees to be constructed in workers.\r\ninterface DOMTreeConstruction {\r\n  openElement(name: string, ns: string = \"html\"): NodeToken<Element>;\r\n  closeElement();\r\n\r\n  setAttribute(name: string, value: string = \"\", ns: string = \"\"): void;\r\n  appendText(text: string): NodeToken<Text>;\r\n  appendComment(text: string): NodeToken<Comment>;\r\n  appendHTML(html: string): Bounds;\r\n}\r\n```\r\n\r\n## DOMChangeList\r\n\r\n```typescript\r\npartial interface Document {\r\n  applyChanges(changes: DOMChangeList): Promise<AppliedChangeList>;\r\n}\r\n\r\n// DOMChangeList is transferrable, and is backed by raw bytes. This\r\n// allows change lists to be constructed in workers.\r\ninterface DOMChangeList {\r\n  /// traverse\r\n  nextSibling(n: NodeToken<Node>): NodeToken<Node | null>;\r\n  previousSibling(n: NodeToken<Node>): NodeToken<Node | null>;\r\n  firstChild(n: NodeToken<Node>): NodeToken<Node | null>;\r\n  lastChild(n: NodeToken<Node>): NodeToken<Node | null>;\r\n  parentNode(n: NodeToken<Node>): NodeToken<Element | null>;\r\n\r\n  /// create\r\n  createElement(name: string, ns: string = 'html'): NodeToken<Element>;\r\n  createText(text: string): NodeToken<Text>;\r\n  createComment(text: string): NodeToken<Comment>;\r\n\r\n  /// update\r\n  setAttribute(el: NodeToken<Element>, name: string, value: string = '', ns: string = ''): void;\r\n  updateTextData(n: NodeToken<Text>, text: string): void;\r\n  updateCommentData(n: NodeToken<Comment>, text: string): void;\r\n  remove(n: NodeToken<Node>): void;\r\n\r\n  /// append\r\n  appendChild(el: NodeToken<Element>, node: NodeToken<Node>): void;\r\n  appendTree(el: NodeToken<Element>, tree: DOMTreeConstruction): void;\r\n\r\n  // this unifies the various HTML-based APIs in the DOM; the return value is\r\n  // a token corresponding to the start and a token corresponding to the end of\r\n  // the inserted tree which can be reified after application.\r\n  //\r\n  // IMPORTANT NOTE: The HTML is parsed during application, not when\r\n  // it is added to the change list.\r\n  insertHTMLBefore(node: NodeToken<Node>, html: string): [NodeToken, NodeToken];\r\n}\r\n```\r\n\r\n# Example\r\n\r\nUsing the usual DOM API:\r\n\r\n```javascript\r\nlet article = document.getElementById('main-article');\r\nlet text = node.firstChild;\r\ntext.textValue = \"Hello world\";\r\nnode.setAttribute(\"data-active\", \"yes\");\r\nnode.removeAttribute(\"data-pending\");\r\n```\r\n\r\nUsing the ChangeList API:\r\n\r\n```javascript\r\nlet articleToken = document.getToken(document.getElementById('main-article'));\r\n\r\nlet changes = new DOMChangeList();\r\nlet textToken = changes.firstChild(token);\r\nchanges.updateTextData(textToken, \"Hello world\");\r\nchanges.setAttribute(articleToken, \"data-active\", \"yes\");\r\nchanges.removeAttribute(articleToken, \"data-pending\");\r\n\r\ndocument.applyChanges(changes);\r\n```\r\n\r\n# FAQ\r\n\r\n### Is this actually faster?\r\n\r\n1. Don't you still have to create all of the DOM nodes anyway? If so, why is it cheaper?\r\n2. Isn't DOM pretty fast in modern browsers already?\r\n\r\nThe intent of this API is to create a low-level interface that is as close as possible to the underlying implementations. It attempts to avoid introducing new costs while reducing a number of paper-cuts that exist in today's usage.\r\n\r\n1. This API creates DOM nodes in the engine, but it does not need to create JavaScript wrappers. Experiments with deep `cloneNode` show that skipping those wrappers provides a performance benefit, but `cloneNode()` can't satisfy as many use-cases as this API.\r\n2. It allows the construction of the set of mutations to occur separately from the application (or even in a worker), keeping the sensitive work that limits 60fps to a minimum.\r\n3. Since applying changes is asynchronous, the full change list can be applied in batches that avoid blocking interaction (especially scroll). If the browser reaches its budget, it can interleave some work to keep the UI interactive and pick up the mutation process afterward. In short, the API should allow browsers to experiment with more scheduling strategies.\r\n4. It encourages good staging practices, eliminating some of the major causes of layout thrash (see the next section).\r\n\r\n### Isn't the real issue that people are interleaving DOM manipulation and layout?\r\n\r\nThat is certainly a major issue, and this API puts developers on the path to success by encouraging them to stage DOM manipulation work separately from APIs that can trigger painting or layout.\r\n\r\nBecause the API guarantees that no user script can interleave during the application of changes, there is no way to \"mess up\" and trigger an immediate flush of any deferred work.\r\n\r\n# Unresolved Questions\r\n\r\n1. The current state of this API allows failures to occur during the processing of a change list, and does not require engines to roll back earlier changes (rolling back changes like \"remove an iframe\" may not be trivial to implement). Would engines prefer to roll back changes?\r\n2. Should we support APIs like `ClassList` and the `style` property through this API? It may be difficult to represent these kinds of changes with the operations already proposed (since this API does not allow direct imperative access to the DOM), and a few additional APIs probably wouldn't do damage to the constraints.\r\n3. Are there other optimizations that could be performed by engines? For example, Luke Wagner suggested that a parameterized version of this API could work like \"prepared statements\" in SQL, allowing engines to do up-front work to optimize the access and mutation patterns for application. What can we do to make this API more hospitable to hypothetical optimizations like those?"},"comment":{"url":"https://api.github.com/repos/whatwg/dom/issues/comments/227307839","html_url":"https://github.com/whatwg/dom/issues/270#issuecomment-227307839","issue_url":"https://api.github.com/repos/whatwg/dom/issues/270","id":227307839,"user":{"login":"wycats","id":4,"avatar_url":"https://avatars.githubusercontent.com/u/4?v=3","gravatar_id":"","url":"https://api.github.com/users/wycats","html_url":"https://github.com/wycats","followers_url":"https://api.github.com/users/wycats/followers","following_url":"https://api.github.com/users/wycats/following{/other_user}","gists_url":"https://api.github.com/users/wycats/gists{/gist_id}","starred_url":"https://api.github.com/users/wycats/starred{/owner}{/repo}","subscriptions_url":"https://api.github.com/users/wycats/subscriptions","organizations_url":"https://api.github.com/users/wycats/orgs","repos_url":"https://api.github.com/users/wycats/repos","events_url":"https://api.github.com/users/wycats/events{/privacy}","received_events_url":"https://api.github.com/users/wycats/received_events","type":"User","site_admin":false},"created_at":"2016-06-21T00:20:57Z","updated_at":"2016-06-21T00:20:57Z","body":"> But looking at the improvements you mentioned, it seems like they would also be received from any general WorkerNode + asyncAppend API. Can you point to any additional benefits this proposal might have?\r\n\r\nBefore I do that, I'd be very interested to read a detailed `WorkerNode` proposal. Can you give me a pointer so I can do a fair analysis?"}}
{"actor":{"display_login":"wycats"}}