gnim-hooks
v1.0.0
Published
Gnim utilities for working with reactive values.
Readme
Gnim Hooks
Gnim utilities for working with reactive values.
Demo
import Gtk from "gi://Gtk?version=4.0"
import { $, useEffect } from "gnim-hooks"
import { cls, useStyle } from "gnim-hooks/gtk4"
import { createComputed, type Node } from "gnim"
// mark props as reactive with `$`
type BoxProps = {
class?: $<string> // Accessor<string> | string
gap?: $<number>
padding?: $<number>
vertical?: $<boolean>
children?: Node | Node[]
}
export default function Box(props: BoxProps) {
// avoid handling both reactive and static props
// by wrapping props with `$` and only worry about reactive props
const className = $(props.class)
const gap = $(props.gap, (v) => v ?? 2)
const padding = $(props.padding, (v) => v ?? 0)
const orientation = $(props.vertical, (v) =>
v ? Gtk.Orientation.VERTICAL : Gtk.Orientation.HORIZONTAL,
)
// define scoped css using `useStyle` which returns a unique className
const cn = useStyle(
// if values are reactive you can use a computed value
createComputed((get) => ({
"border-spacing": `${get(gap)}px`,
"padding": `${get(padding)}px`,
})),
)
// `useEffect` lets you handle Accessor subscriptions with ease
useEffect((get) => {
if (get(orientation) === Gtk.Orientation.VERTICAL) {
console.log(`box is vertical and has ${get(gap)} gap`)
}
})
return (
// use `cls` to pass multiple classNames
<Gtk.Box class={cls(cn, className)} orientation={orientation}>
{props.children}
</Gtk.Box>
)
}