Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(hydration): only ignore mutated host attributes #4385

Merged
merged 1 commit into from
Jul 17, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 6 additions & 3 deletions packages/@lwc/engine-core/src/framework/hydration.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ import {
APIFeature,
isAPIFeatureEnabled,
isFalse,
StringSplit,
} from '@lwc/shared';

import { logError, logWarn } from '../shared/logger';
Expand Down Expand Up @@ -165,9 +166,11 @@ function getValidationPredicate(
optOutStaticProp: string[] | true | undefined
): AttrValidationPredicate {
// `data-lwc-host-mutated` is a special attribute added by the SSR engine itself,
// which does the same thing as an explicit `static validationOptOut = true`.
if (renderer.getAttribute(elm, 'data-lwc-host-mutated') === '') {
return (_attrName: string) => false;
// which does the same thing as an explicit `static validationOptOut = ['attr1', 'attr2']`.
const hostMutatedValue = renderer.getAttribute(elm, 'data-lwc-host-mutated');
if (isString(hostMutatedValue)) {
const mutatedAttrValues = new Set(StringSplit.call(hostMutatedValue, / /));
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

/ / looks weird...

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sorry, too late. I did not see your comments before merging.

TypeScript for some weird reason complains if I use ' '. So I used / /.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Well I was too slow to review. I bet it's because of our weird re-mapping losing overloaded function signatures.

return (attrName: string) => !mutatedAttrValues.has(attrName);
}

if (isUndefined(optOutStaticProp)) {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
<x-cmp aria-label="haha" class="yolo woot" data-foo="bar" data-lwc-host-mutated="aria-label class data-foo">
<template shadowrootmode="open">
</template>
</x-cmp>
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
export const tagName = 'x-cmp';
export { default } from 'x/cmp';
export * from 'x/cmp';
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
<template>
</template>
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import { LightningElement } from 'lwc';

export default class extends LightningElement {
connectedCallback() {
// Modify this component's class and attributes at runtime
// We expect a data-lwc-host-mutated attr to be added with the mutated attribute names in unique sorted order
this.setAttribute('data-foo', 'bar')
this.classList.add('yolo')
this.classList.add('woot')
this.setAttribute('aria-label', 'haha')
}
}
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
<x-cmp aria-activedescendant="foo" aria-busy="true" data-lwc-host-mutated>
<x-cmp aria-activedescendant="foo" aria-busy="true" data-lwc-host-mutated="aria-activedescendant aria-busy">
<template shadowrootmode="open">
</template>
</x-cmp>
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
<x-cmp ARIA-LABEL="haha" DATA-FOO="bar" data-lwc-host-mutated="aria-label data-bar data-foo">
<template shadowrootmode="open">
</template>
</x-cmp>
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
export const tagName = 'x-cmp';
export { default } from 'x/cmp';
export * from 'x/cmp';
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
<template>
</template>
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import { LightningElement } from 'lwc';

export default class extends LightningElement {
connectedCallback() {
// Modify this component's attributes at runtime, using uppercase
// We expect a data-lwc-host-mutated attr to be added with the mutated attribute names in unique sorted order,
// all lowercase
this.setAttribute('DATA-FOO', 'bar')
this.setAttribute('ARIA-LABEL', 'haha')
this.removeAttribute('dAtA-BaR')
}
}
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
<x-getter-class-list class="a c d-e" data-lwc-host-mutated>
<x-getter-class-list class="a c d-e" data-lwc-host-mutated="class">
<template shadowrootmode="open">
</template>
</x-getter-class-list>
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
<x-method-remove-attribute data-a data-c data-lwc-host-mutated>
<x-method-remove-attribute data-a data-c data-lwc-host-mutated="data-a data-b data-c data-unknown">
<template shadowrootmode="open">
</template>
</x-method-remove-attribute>
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
<x-method-set-attribute data-boolean="true" data-empty-string data-lwc-host-mutated data-null="null" data-number="1" data-override="override" data-string="test">
<x-method-set-attribute data-boolean="true" data-empty-string data-lwc-host-mutated="data-boolean data-empty-string data-null data-number data-override data-string" data-null="null" data-number="1" data-override="override" data-string="test">
<template shadowrootmode="open">
</template>
</x-method-set-attribute>
8 changes: 4 additions & 4 deletions packages/@lwc/engine-server/src/renderer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -258,7 +258,7 @@ function getAttribute(element: E, name: string, namespace: string | null = null)
}

function setAttribute(element: E, name: string, value: string, namespace: string | null = null) {
reportMutation(element);
reportMutation(element, name);
const attribute = element[HostAttributesKey].find(
(attr) => attr.name === name && attr[HostNamespaceKey] === namespace
);
Expand All @@ -279,7 +279,7 @@ function setAttribute(element: E, name: string, value: string, namespace: string
}

function removeAttribute(element: E, name: string, namespace?: string | null) {
reportMutation(element);
reportMutation(element, name);
element[HostAttributesKey] = element[HostAttributesKey].filter(
(attr) => attr.name !== name && attr[HostNamespaceKey] !== namespace
);
Expand All @@ -305,15 +305,15 @@ function getClassList(element: E) {

return {
add(...names: string[]): void {
reportMutation(element);
reportMutation(element, 'class');
const classAttribute = getClassAttribute();

const tokenList = classNameToTokenList(classAttribute.value);
names.forEach((name) => tokenList.add(name));
classAttribute.value = tokenListToClassName(tokenList);
},
remove(...names: string[]): void {
reportMutation(element);
reportMutation(element, 'class');
const classAttribute = getClassAttribute();

const tokenList = classNameToTokenList(classAttribute.value);
Expand Down
17 changes: 13 additions & 4 deletions packages/@lwc/engine-server/src/utils/mutation-tracking.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,16 +10,25 @@ const elementsToTrackForMutations: WeakSet<HostElement> = new WeakSet();

const MUTATION_TRACKING_ATTRIBUTE = 'data-lwc-host-mutated';

export function reportMutation(element: HostElement) {
export function reportMutation(element: HostElement, attributeName: string) {
if (elementsToTrackForMutations.has(element)) {
const hasMutationAttribute = element[HostAttributesKey].find(
const existingMutationAttribute = element[HostAttributesKey].find(
(attr) => attr.name === MUTATION_TRACKING_ATTRIBUTE && attr[HostNamespaceKey] === null
);
if (!hasMutationAttribute) {
const attrNameValues = new Set(
existingMutationAttribute ? existingMutationAttribute.value.split(' ') : []
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
existingMutationAttribute ? existingMutationAttribute.value.split(' ') : []
existingMutationAttribute ? existingMutationAttribute.value.split(/ /) : []

.split(/ /) is faster than .split(' ') or StringSplit.call(value, delimiter) according to a quick lil jsperf comparison.

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We're less concerned about compiler perf than runtime perf, but yeah it would have been nice to use / / consistently as well.

);
attrNameValues.add(attributeName.toLowerCase());

const newMutationAttributeValue = [...attrNameValues].sort().join(' ');
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Do we need to sort here or is it just for nice?

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Consistent output formatting and to look nice, yeah.


if (existingMutationAttribute) {
existingMutationAttribute.value = newMutationAttributeValue;
} else {
element[HostAttributesKey].push({
name: MUTATION_TRACKING_ATTRIBUTE,
[HostNamespaceKey]: null,
value: '',
value: newMutationAttributeValue,
});
}
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
export default {
props: {
ssr: true,
},
clientProps: {
ssr: false,
},
snapshot(target) {
const child = target.shadowRoot.querySelector('x-child');
const div = child.shadowRoot.querySelector('div');

return {
child,
div,
};
},
test(target, snapshots, consoleCalls) {
const snapshotAfterHydration = this.snapshot(target);
expect(snapshotAfterHydration.child).not.toBe(snapshots.child);
expect(snapshotAfterHydration.div).not.toBe(snapshots.div);

const { child } = snapshotAfterHydration;
expect(child.getAttribute('data-foo')).toBe('bar');
expect(child.getAttribute('data-mutatis')).toBe('mutandis');
expect(child.getAttribute('class')).toBe('is-client');

TestUtils.expectConsoleCallsDev(consoleCalls, {
warn: [],
error: [
'Mismatch hydrating element <x-child>: attribute "class" has different values, expected "is-client" but found "is-server"',
'Hydration completed with errors.',
],
});
},
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
<template>
<div>{yolo}</div>
</template>
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import { LightningElement } from 'lwc';

export default class Child extends LightningElement {
yolo = 'woot';

connectedCallback() {
this.setAttribute('data-mutatis', 'mutandis');
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
<template>
<x-child data-foo="bar" class={mismatchingClass}></x-child>
</template>
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import { LightningElement, api } from 'lwc';

export default class Main extends LightningElement {
@api ssr;

get mismatchingClass() {
return this.ssr ? 'is-server' : 'is-client';
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
export default {
props: {
ssr: true,
},
clientProps: {
ssr: false,
},
snapshot(target) {
const child = target.shadowRoot.querySelector('x-child');
const div = child.shadowRoot.querySelector('div');

return {
child,
div,
};
},
test(target, snapshots, consoleCalls) {
const snapshotAfterHydration = this.snapshot(target);
expect(snapshotAfterHydration.child).not.toBe(snapshots.child);
expect(snapshotAfterHydration.div).not.toBe(snapshots.div);

const { child } = snapshotAfterHydration;
expect(child.getAttribute('class')).toBe('static mutatis');
expect(child.getAttribute('data-mismatched-attr')).toBe('is-client');

TestUtils.expectConsoleCallsDev(consoleCalls, {
warn: [],
error: [
'Mismatch hydrating element <x-child>: attribute "data-mismatched-attr" has different values, expected "is-client" but found "is-server"',
'Hydration completed with errors.',
],
});
},
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
<template>
<div>{yolo}</div>
</template>
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import { LightningElement } from 'lwc';

export default class Child extends LightningElement {
yolo = 'woot';

connectedCallback() {
this.classList.add('mutatis');
this.classList.add('mutandis');
this.classList.remove('mutandis');
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
<template>
<x-child class="static" data-mismatched-attr={mismatchedAttr}></x-child>
</template>
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import { LightningElement, api } from 'lwc';

export default class Main extends LightningElement {
@api ssr;

get mismatchedAttr() {
return this.ssr ? 'is-server' : 'is-client';
}
}
Loading