Skip to content

Commit

Permalink
Differentiate null and undefined in Custom Elements - removing sets t…
Browse files Browse the repository at this point in the history
…o undefined (facebook#28716)

In React DOM, in general, we don't differentiate between `null` and
`undefined` because we expect to target DOM APIs. When we're setting a
property on a Custom Element, in the new heuristic, the goal is to allow
passing whatever data type instead of normalizing it. Switching between
`undefined` and `null` as an explicit value should therefore be
respected.

However, in this mode if `undefined` is used for the initial value, we
don't actually set the property at all. If passing `null` we will now
initialize it to the value `null`. Meaning `undefined` kind of
represents the default.

### Removing Properties

There is a pretty complex edge case which is what should happen when a
prop used to exist but was removed from the props object. This doesn't
have any kind of defined semantics. It really should mean - return to
"default". Because in the declarative world it means the same as if it
was just created - i.e. we can't just leave it as it was.

The closest might be `delete object.property` but that's not really the
intended way that properties on custom elements / classes are supposed
to operate. Additionally, for a property to even hit our heuristic it
must pass the `in` test and must exist to being with so the default must
have a value.

Since the point of these properties is to contain any kind of type,
there isn't really a conceptual default value. E.g. a numeric default
value might be zero `0` while a default string might be empty `""` and
default object might `null`. Additionally, the conceptual default can
really be initialized to anything. There's also varied precedence in the
ecosystem here and really no consensus. Anything we pick would be kind
of wrong, so we used to just pick `null`.

_The safest way to consume a Custom Element is to always pass the same
set of props._

JS does have a concept of a "default value" though and that is described
as the value `undefined`. That's why default argument / object property
initializers are initialized if the value is `undefined`.

The problem with using `undefined` as value is that [you shouldn't
actually ever set the value of a class property to
`undefined`](https://twitter.com/sebmarkbage/status/1774082540296388752).
A property should always be initialized to some value. It can't be left
missing and shouldn't be initialized to the value `undefined` for hidden
class optimizations. If we just mutate it to be `undefined` it would be
potentially bad for perf and shouldn't really be the value after
removing property - it should be returned to default.

Every property should really have a setter to be useful since it is what
is used to trigger reactivity when it changes. Sometimes you can just
use the properties passively when something else happens but most of the
time it should be a setter but to reach parity with DOM it should really
be always so that the active value can be normalized.

Those setters can have default argument initializers to represent what
the default value should be. Therefore Custom Element properties should
be used like this:

```js
class CustomElement extends HTMLElement {
  _textLabel = '';
  _price = 0;
  _items = null;
  
  constructor() {
    super();
  }
  set textLabel(value = '') {
    this._textLabel = value;
  }
  get textLabel() {
    return this._textLabel;
  }
  set price(value = 0) {
    this._price = value;
  }
  get price() {
    return this._price;
  }
  set items(value = null) {
    this._items = value;
  }
  get items() {
    return this._items;
  }
}
```

The default initializer can be used to initialize a value back to its
original default when `undefined` is passed to it. Therefore, we pass
`undefined`, not because we expect that to be the value of a property
but because that's the value that represents "return to default".

This fixes facebook#28203 but not really for the reason specified in the issue.
We don't expect you to actually store the `undefined` value but to use a
setter to set the property to something else that represents the
default. When we initialize the element the first time, we won't set
anything if it's the value `undefined` so we assume that the property
initializers running in the constructor is going to set the same default
value as if we set the property to `undefined`.

cc @josepharhar
  • Loading branch information
sebmarkbage authored and AndyPengc12 committed Apr 15, 2024
1 parent da90fc1 commit b2aad57
Show file tree
Hide file tree
Showing 2 changed files with 76 additions and 7 deletions.
10 changes: 5 additions & 5 deletions packages/react-dom-bindings/src/client/ReactDOMComponent.js
Original file line number Diff line number Diff line change
Expand Up @@ -1301,7 +1301,7 @@ export function setInitialProperties(
continue;
}
const propValue = props[propKey];
if (propValue == null) {
if (propValue === undefined) {
continue;
}
setPropOnCustomElement(
Expand All @@ -1310,7 +1310,7 @@ export function setInitialProperties(
propKey,
propValue,
props,
null,
undefined,
);
}
return;
Expand Down Expand Up @@ -1741,14 +1741,14 @@ export function updateProperties(
const lastProp = lastProps[propKey];
if (
lastProps.hasOwnProperty(propKey) &&
lastProp != null &&
lastProp !== undefined &&
!nextProps.hasOwnProperty(propKey)
) {
setPropOnCustomElement(
domElement,
tag,
propKey,
null,
undefined,
nextProps,
lastProp,
);
Expand All @@ -1760,7 +1760,7 @@ export function updateProperties(
if (
nextProps.hasOwnProperty(propKey) &&
nextProp !== lastProp &&
(nextProp != null || lastProp != null)
(nextProp !== undefined || lastProp !== undefined)
) {
setPropOnCustomElement(
domElement,
Expand Down
73 changes: 71 additions & 2 deletions packages/react-dom/src/__tests__/DOMPropertyOperations-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -1230,7 +1230,7 @@ describe('DOMPropertyOperations', () => {
});
customelement.dispatchEvent(new Event('customevent'));
expect(oncustomevent).toHaveBeenCalledTimes(2);
expect(customelement.oncustomevent).toBe(null);
expect(customelement.oncustomevent).toBe(undefined);
expect(customelement.getAttribute('oncustomevent')).toBe(null);
});

Expand Down Expand Up @@ -1290,12 +1290,33 @@ describe('DOMPropertyOperations', () => {
await act(() => {
root.render(<my-custom-element />);
});
expect(customElement.foo).toBe(null);
expect(customElement.foo).toBe(undefined);
await act(() => {
root.render(<my-custom-element foo={myFunction} />);
});
expect(customElement.foo).toBe(myFunction);
});

it('switching between null and undefined should update a property', async () => {
const container = document.createElement('div');
document.body.appendChild(container);
const root = ReactDOMClient.createRoot(container);
await act(() => {
root.render(<my-custom-element foo={undefined} />);
});
const customElement = container.querySelector('my-custom-element');
customElement.foo = undefined;

await act(() => {
root.render(<my-custom-element foo={null} />);
});
expect(customElement.foo).toBe(null);

await act(() => {
root.render(<my-custom-element foo={undefined} />);
});
expect(customElement.foo).toBe(undefined);
});
});

describe('deleteValueForProperty', () => {
Expand Down Expand Up @@ -1349,5 +1370,53 @@ describe('DOMPropertyOperations', () => {
});
expect(container.firstChild.getAttribute('size')).toBe('5px');
});

it('custom elements should remove by setting undefined to restore defaults', async () => {
const container = document.createElement('div');
document.body.appendChild(container);
const root = ReactDOMClient.createRoot(container);
await act(() => {
root.render(<my-custom-element />);
});
const customElement = container.querySelector('my-custom-element');

// Non-setter but existing property to active the `in` heuristic
customElement.raw = 1;

// Install a setter to activate the `in` heuristic
Object.defineProperty(customElement, 'object', {
set: function (value = null) {
this._object = value;
},
get: function () {
return this._object;
},
});

Object.defineProperty(customElement, 'string', {
set: function (value = '') {
this._string = value;
},
get: function () {
return this._string;
},
});

const obj = {};
await act(() => {
root.render(<my-custom-element raw={2} object={obj} string="hi" />);
});
expect(customElement.raw).toBe(2);
expect(customElement.object).toBe(obj);
expect(customElement.string).toBe('hi');

// Removing the properties should reset to defaults by passing undefined
await act(() => {
root.render(<my-custom-element />);
});
expect(customElement.raw).toBe(undefined);
expect(customElement.object).toBe(null);
expect(customElement.string).toBe('');
});
});
});

0 comments on commit b2aad57

Please sign in to comment.