summaryrefslogtreecommitdiff
path: root/gjs/src/jsx/jsx-runtime.ts
blob: 7a90dc5b5c35018729d0de0fc9ffda7481cefe5d (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
import { Gtk } from "../imports.js"
import * as Widget from "../widgets.js"
import Binding from "../binding.js"

function w(e: any) {
    if (e instanceof Gtk.Widget || e instanceof Binding)
        return e

    return Widget.Label({ label: String(e) })
}

export function jsx(
    ctor: keyof typeof ctors | typeof Gtk.Widget,
    { children, ...props }: any,
) {
    children ??= []

    if (!Array.isArray(children))
        children = [children]
    else
        children = children.flat()

    if (ctor === "centerbox") {
        if (children[0])
            props.startWidget = w(children[0])
        if (children[1])
            props.centerWidget = w(children[1])
        if (children[2])
            props.endWidget = w(children[2])
    }

    else if (children.length === 1) {
        props.child = w(children[0])
        delete props.children
    }

    else {
        props.children = children.map(w)
    }

    return typeof ctor === "string"
        ? (ctors as any)[ctor](props)
        : new ctor(props)
}

const ctors = {
    "box": Widget.Box,
    "button": Widget.Button,
    "centerbox": Widget.CenterBox,
    "eventbox": Widget.EventBox,
    "icon": Widget.Icon,
    "label": Widget.Label,
    "window": Widget.Window,
}

// eslint-disable-next-line @typescript-eslint/no-namespace
export namespace JSX {
    export type Element = Gtk.Widget
    export interface IntrinsicElements {
        "box": Widget.BoxProps
        "button": Widget.ButtonProps
        "centerbox": Widget.CenterBoxProps
        "eventbox": Widget.EventBoxProps
        "icon": Widget.IconProps
        "label": Widget.LabelProps
        "window": Widget.WindowProps
    }
}

export const jsxs = jsx