chartjs / chartjs/Chart.js

Attach observer doesn't work when canvas is inside of Shadow DOM

Open
#10,924 4 comments 0 reactions 0 assignees View on GitHub
type: bug
Dominant language
JavaScript
Stars
67.7k
Forks
11.9k
Avg merge
7h 39m
Merged PRs (30d)
5

Description

### Expected behavior

When chart creates for a canvas node which is not connected to DOM yet, then it creates MutationObserver to handle a moment when canvas will be added. But when canvas node adds to DOM as a part of other node with Shadow DOM then attach handler should be called.

### Current behavior

Attach handler not calling when canvas node is inside of Shadow DOM and node adds later to DOM (after chart is created). This happens because Chart.JS checks if canvas is added to DOM through `justAddedNode.contains(canvas)` and it doesn't work with Shadow DOM.
This code is here: https://github.com/chartjs/Chart.js/blob/51441272a781ba575149b214933f0c5b4bafb6ab/src/platform/platform.dom.js#L130

For example MutationObserver handles following added node:
```html



#shadow-root:
// <-- it is canvas which Chart.JS waits to be added to DOM


````
With this case added node `div` will return `false` for node `canvas` when in real it contains `canvas`.

### Reproducible sample

https://jsfiddle.net/ryf837xs/1/

The same fiddle without Shadow DOM works correct: https://jsfiddle.net/q4gmfy2p/

### Optional extra steps/info to reproduce

_No response_

### Possible solution

Maybe it's enough to check just if `canvas.isConnected` in MutationObserver callback?

Here: https://github.com/chartjs/Chart.js/blob/51441272a781ba575149b214933f0c5b4bafb6ab/src/platform/platform.dom.js#L130

Like this:
```js
function createAttachObserver(chart, type, listener) {
const canvas = chart.canvas;
const observer = new MutationObserver(entries => {
if (canvas.isConnected) { // <-- here is enough just to check if canvas connected ?
listener();
}
});
...
```

### Context

_No response_

### chart.js version

4.0.1

### Browser name and version

Chrome 107

### Link to your project

_No response_

Contributor guide

No contributing guide indexed for this repository

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.