16
import { getObservableTarget } from "@koalaui/compat"
21
export interface Observable {
29
export class ObservableHandler implements Observable {
30
private static handlers: WeakMap<Object, ObservableHandler> | undefined = undefined
32
private observables = new Set<Observable>()
33
private _modified = false
36
if (this.observables.size > 0) {
37
const it = this.observables.keys()
39
const result = it.next()
40
if (result.done) break
41
result.value?.onAccess()
48
if (this.observables.size > 0) {
49
const it = this.observables.keys()
51
const result = it.next()
52
if (result.done) break
53
result.value?.onModify()
58
static dropModified<Value>(value: Value): boolean {
59
const handler = ObservableHandler.findIfObject(value)
60
if (handler === undefined) return false
61
const result = handler._modified
62
handler._modified = false
67
static attach<Value>(value: Value, observable: Observable): void {
68
const handler = ObservableHandler.findIfObject(value)
69
if (handler !== undefined) handler.observables.add(observable)
73
static detach<Value>(value: Value, observable: Observable): void {
74
const handler = ObservableHandler.findIfObject(value)
75
if (handler !== undefined) handler.observables.delete(observable)
79
private static findIfObject<Value>(value: Value): ObservableHandler | undefined {
80
const handlers = ObservableHandler.handlers
81
return handlers !== undefined && value instanceof Object ? getObservableHandler(handlers, value as Object) : undefined
88
static find(value: Object): ObservableHandler | undefined {
89
const handlers = ObservableHandler.handlers
90
return handlers !== undefined ? getObservableHandler(handlers, value) : undefined
98
static installOn(value: Object, observable?: ObservableHandler): void {
99
let handlers = ObservableHandler.handlers
100
if (handlers === undefined) {
101
handlers = new WeakMap<Object, ObservableHandler>()
102
ObservableHandler.handlers = handlers
105
? handlers.set(getObservableTarget(value), observable)
106
: handlers.delete(getObservableTarget(value))
110
function getObservableHandler(handlers: WeakMap<Object, ObservableHandler>, value: Object): ObservableHandler | undefined {
111
const handler = handlers.get(getObservableTarget(value))
112
return handler === null ? undefined : handler