summaryrefslogtreecommitdiff
path: root/lang/gjs/src/variable.ts
blob: 016d73afde5e3d91ff672835840ca869207c00ca (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
import Astal from "gi://AstalIO"
import Binding, { type Connectable, type Subscribable } from "./binding.js"
import { interval } from "./time.js"
import { execAsync, subprocess } from "./process.js"

class VariableWrapper<T> extends Function {
    private variable!: Astal.VariableBase
    private errHandler? = console.error

    private _value: T
    private _poll?: Astal.Time
    private _watch?: Astal.Process

    private pollInterval = 1000
    private pollExec?: string[] | string
    private pollTransform?: (stdout: string, prev: T) => T
    private pollFn?: (prev: T) => T | Promise<T>

    private watchTransform?: (stdout: string, prev: T) => T
    private watchExec?: string[] | string

    constructor(init: T) {
        super()
        this._value = init
        this.variable = new Astal.VariableBase()
        this.variable.connect("dropped", () => {
            this.stopWatch()
            this.stopPoll()
        })
        this.variable.connect("error", (_, err) => this.errHandler?.(err))
        return new Proxy(this, {
            apply: (target, _, args) => target._call(args[0]),
        })
    }

    private _call<R = T>(transform?: (value: T) => R): Binding<R> {
        const b = Binding.bind(this)
        return transform ? b.as(transform) : b as unknown as Binding<R>
    }

    toString() {
        return String(`Variable<${this.get()}>`)
    }

    get(): T { return this._value }
    set(value: T) {
        if (value !== this._value) {
            this._value = value
            this.variable.emit("changed")
        }
    }

    startPoll() {
        if (this._poll)
            return

        if (this.pollFn) {
            this._poll = interval(this.pollInterval, () => {
                const v = this.pollFn!(this.get())
                if (v instanceof Promise) {
                    v.then(v => this.set(v))
                        .catch(err => this.variable.emit("error", err))
                } else {
                    this.set(v)
                }
            })
        } else if (this.pollExec) {
            this._poll = interval(this.pollInterval, () => {
                execAsync(this.pollExec!)
                    .then(v => this.set(this.pollTransform!(v, this.get())))
                    .catch(err => this.variable.emit("error", err))
            })
        }
    }

    startWatch() {
        if (this._watch)
            return

        this._watch = subprocess({
            cmd: this.watchExec!,
            out: out => this.set(this.watchTransform!(out, this.get())),
            err: err => this.variable.emit("error", err),
        })
    }

    stopPoll() {
        this._poll?.cancel()
        delete this._poll
    }

    stopWatch() {
        this._watch?.kill()
        delete this._watch
    }

    isPolling() { return !!this._poll }
    isWatching() { return !!this._watch }

    drop() {
        this.variable.emit("dropped")
    }

    onDropped(callback: () => void) {
        this.variable.connect("dropped", callback)
        return this as unknown as Variable<T>
    }

    onError(callback: (err: string) => void) {
        delete this.errHandler
        this.variable.connect("error", (_, err) => callback(err))
        return this as unknown as Variable<T>
    }

    subscribe(callback: (value: T) => void) {
        const id = this.variable.connect("changed", () => {
            callback(this.get())
        })
        return () => this.variable.disconnect(id)
    }

    poll(
        interval: number,
        exec: string | string[],
        transform?: (stdout: string, prev: T) => T
    ): Variable<T>

    poll(
        interval: number,
        callback: (prev: T) => T | Promise<T>
    ): Variable<T>

    poll(
        interval: number,
        exec: string | string[] | ((prev: T) => T | Promise<T>),
        transform: (stdout: string, prev: T) => T = out => out as T,
    ) {
        this.stopPoll()
        this.pollInterval = interval
        this.pollTransform = transform
        if (typeof exec === "function") {
            this.pollFn = exec
            delete this.pollExec
        } else {
            this.pollExec = exec
            delete this.pollFn
        }
        this.startPoll()
        return this as unknown as Variable<T>
    }

    watch(
        exec: string | string[],
        transform: (stdout: string, prev: T) => T = out => out as T,
    ) {
        this.stopWatch()
        this.watchExec = exec
        this.watchTransform = transform
        this.startWatch()
        return this as unknown as Variable<T>
    }

    observe(
        objs: Array<[obj: Connectable, signal: string]>,
        callback: (...args: any[]) => T,
    ): Variable<T>

    observe(
        obj: Connectable,
        signal: string,
        callback: (...args: any[]) => T,
    ): Variable<T>

    observe(
        objs: Connectable | Array<[obj: Connectable, signal: string]>,
        sigOrFn: string | ((obj: Connectable, ...args: any[]) => T),
        callback?: (obj: Connectable, ...args: any[]) => T,
    ) {
        const f = typeof sigOrFn === "function" ? sigOrFn : callback ?? (() => this.get())
        const set = (obj: Connectable, ...args: any[]) => this.set(f(obj, ...args))

        if (Array.isArray(objs)) {
            for (const obj of objs) {
                const [o, s] = obj
                const id = o.connect(s, set)
                this.onDropped(() => o.disconnect(id))
            }
        } else {
            if (typeof sigOrFn === "string") {
                const id = objs.connect(sigOrFn, set)
                this.onDropped(() => objs.disconnect(id))
            }
        }

        return this as unknown as Variable<T>
    }

    static derive<
        const Deps extends Array<Subscribable<any>>,
        Args extends {
            [K in keyof Deps]: Deps[K] extends Subscribable<infer T> ? T : never
        },
        V = Args,
    >(deps: Deps, fn: (...args: Args) => V = (...args) => args as unknown as V) {
        const update = () => fn(...deps.map(d => d.get()) as Args)
        const derived = new Variable(update())
        const unsubs = deps.map(dep => dep.subscribe(() => derived.set(update())))
        derived.onDropped(() => unsubs.map(unsub => unsub()))
        return derived
    }
}

export interface Variable<T> extends Omit<VariableWrapper<T>, "bind"> {
    <R>(transform: (value: T) => R): Binding<R>
    (): Binding<T>
}

export const Variable = new Proxy(VariableWrapper as any, {
    apply: (_t, _a, args) => new VariableWrapper(args[0]),
}) as {
    derive: typeof VariableWrapper["derive"]
    <T>(init: T): Variable<T>
    new<T>(init: T): Variable<T>
}

export const { derive } = Variable
export default Variable