Fix storage decorator timing (#25199)

This commit is contained in:
Bram Kragten 2025-04-28 07:46:13 +02:00 committed by GitHub
parent e1899836bf
commit 672fbc6007
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194

View File

@ -6,6 +6,7 @@ type Callback = (oldValue: any, newValue: any) => void;
type ReactiveStorageElement = ReactiveElement & { type ReactiveStorageElement = ReactiveElement & {
__unbsubLocalStorage: UnsubscribeFunc | undefined; __unbsubLocalStorage: UnsubscribeFunc | undefined;
__initialized: boolean;
}; };
class StorageClass { class StorageClass {
@ -165,6 +166,14 @@ export function storage(options: {
} }
}; };
// @ts-ignore
const performUpdate = proto.performUpdate;
// @ts-ignore
proto.performUpdate = function () {
(this as unknown as ReactiveStorageElement).__initialized = true;
performUpdate.call(this);
};
if (options.state && options.subscribe) { if (options.state && options.subscribe) {
const connectedCallback = proto.connectedCallback; const connectedCallback = proto.connectedCallback;
const disconnectedCallback = proto.disconnectedCallback; const disconnectedCallback = proto.disconnectedCallback;
@ -194,15 +203,15 @@ export function storage(options: {
let newDescriptor: PropertyDescriptor; let newDescriptor: PropertyDescriptor;
if (descriptor === undefined) { if (descriptor === undefined) {
newDescriptor = { newDescriptor = {
get(this: ReactiveElement) { get(this: ReactiveStorageElement) {
return getValue(); return getValue();
}, },
set(this: ReactiveElement, value) { set(this: ReactiveStorageElement, value) {
// Don't set the initial value if we have a value in localStorage // Don't set the initial value if we have a value in localStorage
if (this.hasUpdated || getValue() === undefined) { if (this.__initialized || getValue() === undefined) {
setValue(this, value); setValue(this, value);
this.requestUpdate(propertyKey, undefined);
} }
this.requestUpdate(propertyKey, undefined);
}, },
configurable: true, configurable: true,
enumerable: true, enumerable: true,
@ -211,8 +220,12 @@ export function storage(options: {
const oldSetter = descriptor.set; const oldSetter = descriptor.set;
newDescriptor = { newDescriptor = {
...descriptor, ...descriptor,
set(this: ReactiveElement, value) { set(this: ReactiveStorageElement, value) {
setValue(this, value); // Don't set the initial value if we have a value in localStorage
if (this.__initialized || getValue() === undefined) {
setValue(this, value);
this.requestUpdate(propertyKey, undefined);
}
oldSetter?.call(this, value); oldSetter?.call(this, value);
}, },
}; };