import { PublisherProxy, PublisherManager } from "../../utils/PublisherProxy"; export function autoSubscribe() { return function ( target: any, propertyKey: string, descriptor: PropertyDescriptor ) { let renderId = 0; const originalMethod = descriptor.value; const originalDisconnectedCallback = target.constructor.prototype.disconnectedCallback; target.constructor.prototype.disconnectedCallback = function () { originalDisconnectedCallback?.apply(this); this.__removeAutoSubscribe__(); }; const originalConnectedCallback = target.connectedCallback; target.connectedCallback = function (this: any) { originalConnectedCallback?.call(this); this[propertyKey](); }; descriptor.value = function (...args: unknown[]) { let publishers: Set = new Set(); const onAssign = () => { renderId++; const id = renderId; window.queueMicrotask(() => { if (id !== renderId) return; (this as any)[propertyKey](); }); }; publishers.forEach((publisher: PublisherProxy) => { publisher.offAssign(onAssign); }); PublisherManager.collectModifiedPublisher(); const result = originalMethod.apply(this, args); publishers = PublisherManager.getModifiedPublishers() || new Set(); publishers.forEach((publisher: PublisherProxy) => { publisher.onAssign(onAssign, false); }); ( this as typeof target.constructor.prototype.disconnectedCallback ).__removeAutoSubscribe__ = () => { publishers.forEach((publisher: PublisherProxy) => { publisher.offAssign(onAssign); }); }; return result; }; }; }