Skip to content

Commit

Permalink
fix: [#1647] Fixes problem with children of created documents not bei…
Browse files Browse the repository at this point in the history
…ng considered as connected to the DOM that was introduced in v16 (#1648)

* fix: [#1647] Fixes problem with children of created documents not being considered as connected to the DOM that was introduced in v16

* chore: [#1647] Fixes attributeChangedCallback
  • Loading branch information
capricorn86 authored Dec 27, 2024
1 parent d58fc61 commit 2df1cc4
Show file tree
Hide file tree
Showing 7 changed files with 102 additions and 22 deletions.
2 changes: 1 addition & 1 deletion packages/happy-dom/src/css/rules/CSSStyleRule.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,8 @@ import CSSStyleDeclaration from '../declaration/CSSStyleDeclaration.js';
*/
export default class CSSStyleRule extends CSSRule {
public readonly type = CSSRule.STYLE_RULE;
public readonly selectorText = '';
public readonly styleMap = new Map();
public selectorText = '';
public [PropertySymbol.cssText] = '';
#style: CSSStyleDeclaration | null = null;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,11 @@ export default class CustomElementReactionStack {
return;
}

// If the element is not connected to the main document, we should not invoke the callback.
if (element[PropertySymbol.ownerDocument] !== this.window.document) {
return;
}

// According to the spec, we should use a queue for each element and then invoke the reactions in the order they were enqueued asynchronously.
// However, the browser seem to always invoke the reactions synchronously.
// TODO: Can we find an example where the reactions are invoked asynchronously? In that case we should use a queue for those cases.
Expand Down
2 changes: 1 addition & 1 deletion packages/happy-dom/src/nodes/document/Document.ts
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ export default class Document extends Node {
public [PropertySymbol.isFirstWrite] = true;
public [PropertySymbol.isFirstWriteAfterOpen] = false;
public [PropertySymbol.nodeType] = NodeTypeEnum.documentNode;
public [PropertySymbol.isConnected] = false;
public [PropertySymbol.isConnected] = true;
public [PropertySymbol.adoptedStyleSheets]: CSSStyleSheet[] = [];
public [PropertySymbol.implementation] = new DOMImplementation(this);
public [PropertySymbol.readyState] = DocumentReadyStateEnum.interactive;
Expand Down
26 changes: 18 additions & 8 deletions packages/happy-dom/src/nodes/html-element/HTMLElement.ts
Original file line number Diff line number Diff line change
Expand Up @@ -613,10 +613,15 @@ export default class HTMLElement extends Element {
public override [PropertySymbol.connectedToDocument](): void {
super[PropertySymbol.connectedToDocument]();

this[PropertySymbol.window][PropertySymbol.customElementReactionStack].enqueueReaction(
this,
'connectedCallback'
);
if (
this[PropertySymbol.ownerDocument][PropertySymbol.window].document ===
this[PropertySymbol.ownerDocument]
) {
this[PropertySymbol.window][PropertySymbol.customElementReactionStack].enqueueReaction(
this,
'connectedCallback'
);
}
}

/**
Expand All @@ -625,10 +630,15 @@ export default class HTMLElement extends Element {
public override [PropertySymbol.disconnectedFromDocument](): void {
super[PropertySymbol.disconnectedFromDocument]();

this[PropertySymbol.window][PropertySymbol.customElementReactionStack].enqueueReaction(
this,
'disconnectedCallback'
);
if (
this[PropertySymbol.ownerDocument][PropertySymbol.window].document ===
this[PropertySymbol.ownerDocument]
) {
this[PropertySymbol.window][PropertySymbol.customElementReactionStack].enqueueReaction(
this,
'disconnectedCallback'
);
}
}

/**
Expand Down
11 changes: 0 additions & 11 deletions packages/happy-dom/src/window/BrowserWindow.ts
Original file line number Diff line number Diff line change
Expand Up @@ -835,17 +835,6 @@ export default class BrowserWindow extends EventTarget implements INodeJSGlobal
// Document
this.document = new this.HTMLDocument();
this.document[PropertySymbol.defaultView] = this;
this.document[PropertySymbol.isConnected] = true;

this.document[PropertySymbol.nodeArray][0][PropertySymbol.isConnected] = true;

this.document[PropertySymbol.nodeArray][0][PropertySymbol.nodeArray][0][
PropertySymbol.isConnected
] = true;

this.document[PropertySymbol.nodeArray][0][PropertySymbol.nodeArray][1][
PropertySymbol.isConnected
] = true;

// Ready state manager
this[PropertySymbol.readyStateManager].waitUntilComplete().then(() => {
Expand Down
8 changes: 7 additions & 1 deletion packages/happy-dom/test/dom-parser/DOMParser.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -235,6 +235,7 @@ describe('DOMParser', () => {
class CustomElement extends HTMLElement {
public connectedCount = 0;
public disconnectedCount = 0;
public changedAttributes = 0;

constructor() {
super();
Expand All @@ -248,6 +249,10 @@ describe('DOMParser', () => {
public disconnectedCallback(): void {
this.disconnectedCount++;
}

public attributeChangedCallback(): void {
this.changedAttributes++;
}
}

window.customElements.define('custom-element', CustomElement);
Expand All @@ -259,13 +264,14 @@ describe('DOMParser', () => {
'text/html'
);

expect(newDocument.isConnected).toBe(false);
expect(newDocument.isConnected).toBe(true);
expect(newDocument.defaultView).toBe(window);

const customElement = <CustomElement>newDocument.querySelector('custom-element');

expect(customElement.connectedCount).toBe(0);
expect(customElement.disconnectedCount).toBe(0);
expect(customElement.changedAttributes).toBe(0);

document.body.appendChild(customElement);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@ import Document from '../../../src/nodes/document/Document.js';
import HTMLStyleElement from '../../../src/nodes/html-style-element/HTMLStyleElement.js';
import { beforeEach, describe, it, expect } from 'vitest';
import HTMLElement from '../../../src/nodes/html-element/HTMLElement.js';
import DOMImplementation from '../../../src/dom-implementation/DOMImplementation.js';
import CSSStyleRule from '../../../src/css/rules/CSSStyleRule.js';

describe('HTMLStyleElement', () => {
let window: Window;
Expand Down Expand Up @@ -185,5 +187,73 @@ describe('HTMLStyleElement', () => {

expect(documentElementComputedStyle.backgroundColor).toBe('blue');
});

it('Returns an CSSStyleSheet instance with its text content as style rules for #1647.', () => {
const StyleTagRegexp = /<style[^>]*>(?<content>.*?)<\/style>/gis;

function getScopedCssRules(html: string, scope: string, dom?: DOMImplementation): string {
const css = Array.from(html.matchAll(StyleTagRegexp))
.map(({ groups }) => groups?.content ?? '')
.join('\n');

if (!css) {
return '';
}

// Use the browser's CSSOM to parse CSS
const doc = (dom ?? document.implementation).createHTMLDocument();
const styleElement = doc.createElement('style');
styleElement.textContent = css;
doc.body.appendChild(styleElement);

return Array.from(styleElement.sheet?.cssRules ?? [])
.map((rule) => {
if (rule instanceof CSSStyleRule) {
rule.selectorText = rule.selectorText
.split(',')
.map((selector) => `${scope} ${selector}`)
.join(',');
}

return rule.cssText;
})
.join('\n');
}

function scopeCssSelectors(html: string, scope: string, dom?: DOMImplementation): string {
const scopedCss = getScopedCssRules(html, scope, dom);

return `${scopedCss ? `<style>${scopedCss}</style>` : ''}${html.replace(
StyleTagRegexp,
''
)}`;
}

const html = `
<style>
#document h1, #document h2 {
background: red;
}
</style>
<h1>I love this</h1>
<STYLE type="text/css">
h3 {
color: white;
}
</STYLE>
`;

expect(scopeCssSelectors(html, '.scope'))
.toEqual(`<style>.scope #document h1,.scope #document h2 { background: red; }
.scope h3 { color: white; }</style>
<h1>I love this</h1>
`);
});
});
});

0 comments on commit 2df1cc4

Please sign in to comment.