summaryrefslogtreecommitdiff
path: root/node/src/astalify.ts
blob: 9f83e71784f057cc5e9ba9802aefc255203e6845 (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, Gtk } from "./imports.js"
import Binding, { kebabify, type Connectable, type Subscribable } from "./binding.js"

export type Widget<C extends { new(...args: any): any }> = InstanceType<C> & {
    className: string
    css: string
    cursor: Cursor
    hook(
        object: Connectable,
        signal: string,
        callback: (self: Widget<C>, ...args: any[]) => void,
    ): Widget<C>
    hook(
        object: Subscribable,
        callback: (self: Widget<C>, ...args: any[]) => void,
    ): Widget<C>
}


function setter(prop: string) {
    return `set${prop.charAt(0).toUpperCase() + prop.slice(1)}`
}

function hook(
    self: any,
    object: Connectable | Subscribable,
    signalOrCallback: string | ((self: any, ...args: any[]) => void),
    callback?: (self: any, ...args: any[]) => void,
) {
    if (typeof object.connect === "function" && callback) {
        const id = object.connect(signalOrCallback, (_: any, ...args: unknown[]) => {
            callback(self, ...args)
        })
        self.connect("destroy", () => {
            (object.disconnect as Connectable["disconnect"])(id)
        })
    }

    else if (typeof object.subscribe === "function" && typeof signalOrCallback === "function") {
        const unsub = object.subscribe((...args: unknown[]) => {
            signalOrCallback(self, ...args)
        })
        self.connect("destroy", unsub)
    }

    return self
}

function setChild(parent: any, child: any) {
    if (parent instanceof Gtk.Bin) {
        if (parent.getChild())
            parent.remove(parent.getChild()!)
    }
    if (parent instanceof Gtk.Container)
        parent.add(child)
}

function ctor(self: any, config: any, ...children: any[]) {
    const { setup, child, ...props } = config
    props.visible ??= true

    const bindings = Object.keys(props).reduce((acc: any, prop) => {
        if (props[prop] instanceof Binding) {
            const bind = [prop, props[prop]]
            prop === "child"
                ? setChild(self, props[prop].get())
                : self[setter(prop)](props[prop].get())

            delete props[prop]
            return [...acc, bind]
        }
        return acc
    }, [])

    const onHandlers = Object.keys(props).reduce((acc: any, key) => {
        if (key.startsWith("on")) {
            const sig = kebabify(key).split("-").slice(1).join("-")
            const handler = [sig, props[key]]
            delete props[key]
            return [...acc, handler]
        }
        return acc
    }, [])

    Object.assign(self, props)
    Object.assign(self, {
        hook(obj: any, sig: any, callback: any) {
            return hook(self, obj, sig, callback)
        },
    })

    if (child instanceof Binding) {
        setChild(self, child.get())
        self.connect("destroy", child.subscribe(v => {
            setChild(self, v)
        }))
    } else if (self instanceof Gtk.Container && child instanceof Gtk.Widget) {
        self.add(child)
    }

    for (const [signal, callback] of onHandlers)
        self.connect(signal, callback)

    if (self instanceof Gtk.Container && children) {
        for (const child of children)
            self.add(child)
    }

    for (const [prop, bind] of bindings) {
        self.connect("destroy", bind.subscribe((v: any) => {
            self[`${setter(prop)}`](v)
        }))
    }

    setup?.(self)
    return self
}

function proxify<
    C extends { new(...args: any[]): any },
>(klass: C) {
    Object.defineProperty(klass.prototype, "className", {
        get() { return Astal.widgetGetClassNames(this).join(" ") },
        set(v) { Astal.widgetSetClassNames(this, v.split(/\s+/)) },
    })

    Object.defineProperty(klass.prototype, "css", {
        get() { return Astal.widgetGetCss(this) },
        set(v) { Astal.widgetSetCss(this, v) },
    })

    Object.defineProperty(klass.prototype, "cursor", {
        get() { return Astal.widgetGetCursor(this) },
        set(v) { Astal.widgetSetCursor(this, v) },
    })

    const proxy = new Proxy(klass, {
        construct(_, [conf, ...children]) {
            const self = new klass
            return ctor(self, conf, ...children)
        },
        apply(_t, _a, [conf, ...children]) {
            const self = new klass
            return ctor(self, conf, ...children)
        },
    })

    return proxy
}

export default function astalify<
    C extends typeof Gtk.Widget,
    P extends Record<string, any>,
    N extends string = "Widget",
>(klass: C) {
    // eslint-disable-next-line @typescript-eslint/no-unused-vars
    type Astal<N> = Omit<C, "new"> & {
        new(props: P, ...children: InstanceType<typeof Gtk.Widget>[]): Widget<C>
        (props: P, ...children: InstanceType<typeof Gtk.Widget>[]): Widget<C>
    }

    return proxify(klass) as unknown as Astal<N>
}


type BindableProps<T> = {
    [K in keyof T]: Binding<NonNullable<T[K]>> | T[K];
}

type SigHandler<
    W extends { new(...args: any): Gtk.Widget },
    Args extends Array<unknown>,
> = ((self: Widget<W>, ...args: Args) => unknown) | string | string[]

export type ConstructProps<
    Self extends { new(...args: any[]): any },
    Props = unknown,
    Signals extends Record<`on${string}`, Array<unknown>> = Record<`on${string}`, any[]>
> = Partial<{
    [S in keyof Signals]: SigHandler<Self, Signals[S]>
}> & Partial<{
    [Key in `on${string}`]: SigHandler<Self, any[]>
}> & BindableProps<Props & {
    className?: string
    css?: string
    cursor?: string
}> & {
    onDestroy?: (self: Widget<Self>) => unknown
    onDraw?: (self: Widget<Self>) => unknown
    setup?: (self: Widget<Self>) => void
}

type Cursor =
    | "default"
    | "help"
    | "pointer"
    | "context-menu"
    | "progress"
    | "wait"
    | "cell"
    | "crosshair"
    | "text"
    | "vertical-text"
    | "alias"
    | "copy"
    | "no-drop"
    | "move"
    | "not-allowed"
    | "grab"
    | "grabbing"
    | "all-scroll"
    | "col-resize"
    | "row-resize"
    | "n-resize"
    | "e-resize"
    | "s-resize"
    | "w-resize"
    | "ne-resize"
    | "nw-resize"
    | "sw-resize"
    | "se-resize"
    | "ew-resize"
    | "ns-resize"
    | "nesw-resize"
    | "nwse-resize"
    | "zoom-in"
    | "zoom-out"