| 29 | const reactionMap = new WeakMap<CustomElement, ReactionItem[]>(); |
| 30 | |
| 31 | function wrapClass<T extends ClassComponent>(Component: T) { |
| 32 | class ObserverComponent extends (Component as ClassComponent) implements CustomElement { |
| 33 | static observedAttributes = []; |
| 34 | |
| 35 | protected disposers: IReactionDisposer[] = []; |
| 36 | |
| 37 | get props() { |
| 38 | return getMobxData(this); |
| 39 | } |
| 40 | |
| 41 | constructor() { |
| 42 | super(); |
| 43 | |
| 44 | Promise.resolve().then(() => this.#boot()); |
| 45 | } |
| 46 | |
| 47 | update = () => { |
| 48 | const { update } = Object.getPrototypeOf(this); |
| 49 | |
| 50 | return new Promise<void>(resolve => |
| 51 | this.disposers.push(autorun(() => update.call(this).then(resolve))) |
| 52 | ); |
| 53 | }; |
| 54 | |
| 55 | #boot() { |
| 56 | const names: string[] = this.constructor['observedAttributes'] || [], |
| 57 | reactions = reactionMap.get(this) || []; |
| 58 | |
| 59 | this.disposers.push( |
| 60 | ...names.map(name => autorun(() => this.syncPropAttr(name))), |
| 61 | ...reactions.map(({ expression, effect }) => |
| 62 | watch(reaction => expression(this, reaction), effect.bind(this)) |
| 63 | ) |
| 64 | ); |
| 65 | } |
| 66 | |
| 67 | disconnectedCallback() { |
| 68 | for (const disposer of this.disposers) disposer(); |
| 69 | |
| 70 | this.disposers.length = 0; |
| 71 | |
| 72 | super['disconnectedCallback']?.(); |
| 73 | } |
| 74 | |
| 75 | setAttribute(name: string, value: string) { |
| 76 | const old = super.getAttribute(name), |
| 77 | names: string[] = this.constructor['observedAttributes']; |
| 78 | |
| 79 | super.setAttribute(name, value); |
| 80 | |
| 81 | if (names.includes(name)) this.attributeChangedCallback(name, old, value); |
| 82 | } |
| 83 | |
| 84 | attributeChangedCallback(name: string, old: string, value: string) { |
| 85 | this[toCamelCase(name)] = parseJSON(value); |
| 86 | |
| 87 | super['attributeChangedCallback']?.(name, old, value); |
| 88 | } |