[whatwg/dom] `MutationObserver` flag to observe mutations in (open) shadow trees to facilitate polyfills of HTML syntax (Issue #1287)

### What problem are you trying to solve?

It is currently exceedingly difficult (and slow) to implement polyfills of certain features that affect HTML syntax across both light and shadow DOM because it requires observing mutations in shadow trees as well, which is currently incredibly difficult, and all solutions have prohibitive performance.

Some examples:
- Any of the custom attributes proposals ([example](https://github.com/WICG/webcomponents/issues/1029))
- Any new HTML element or attribute

### What solutions exist today?

The current options are:
1. 🤷🏽‍♀️ **The shrug method:** Use a regular document-wide mutation observer and simply accept that the polyfill will not work correctly when shadow trees are involved
2. 🤕 **The painful method**: When the mutation observer detects new elements, check if they have a `shadowRoot` and call `observe()` on that too. Loop over all existing elements and attach mutation observers to the shadow roots of those with one.
3. 🩹 **The monkey patch method**: Wrap `HTMLElement.prototype.attachShadow()` with code that calls `mutationObserver.observe()` on it, like so:
```js
let originalAttachShadow = HTMLElement.prototype.attachShadow;
HTMLElement.prototype.attachShadow = function(...args) {
 let node = originalAttachShadow.call(this, ...args);
 mutationObserver.observe(node, options);
 return node;
}
```

As you can see, all of these are _pretty terrible_.

### How would you solve it?

#### Option 1 

This is the most straightforward, lowest effort option: Simply add a new option to [`MutationObserverInit`](https://dom.spec.whatwg.org/#interface-mutationobserver) to observe (open) shadow trees. Name TBB, some ideas might be `shadow`, `shadowRoots`.

The MVP could be a boolean option, which could later be extended to more granularity (e.g. how many levels deep? What types of shadow trees (`open`, `open-stylable` etc)).

#### Option 2

It could be argued that `MutationObserver.prototype.observe()` is the wrong tool for the job. It was designed to observe mutations under a specific root, and has been since contorted to cater to these types of use cases. Perhaps a different method could be used to signal "observe this everywhere you can", e.g. `MutationObserver.prototype.globalObserve()`.

### Anything else?

_No response_

-- 
Reply to this email directly or view it on GitHub:
https://github.com/whatwg/dom/issues/1287
You are receiving this because you are subscribed to this thread.

Message ID: <whatwg/dom/issues/1287@github.com>

Received on Wednesday, 8 May 2024 15:03:31 UTC