portico/Sources/Portico/Extensions/StyleClass.swift

49 lines
2 KiB
Swift

import Gtk
extension WidgetView {
/// Adds `name` to the mounted widget when `enabled` is true; a false value
/// appends no configuration step at all.
func styleClass(_ name: String, _ enabled: Bool) -> Self {
guard enabled else { return self }
return appending { w, _ in w.addCssClass(cssClass: name) }
}
/// Adds `name` at mount when the binding is true, then adds/removes it on the
/// live widget on every change. The subscription is registered with the mount
/// context's registry, so unmount cancels it.
func styleClass(_ name: String, _ enabled: Binding<Bool>) -> Self {
appending { w, ctx in
if enabled.untrackedValue { w.addCssClass(cssClass: name) }
ctx.registry.add(enabled.subscribe { [w] on in
if on { w.addCssClass(cssClass: name) } else { w.removeCssClass(cssClass: name) }
})
}
}
}
extension View {
/// `AnyView`-returning counterpart for views that are not ``WidgetView``
/// (`HStack`, `VStack`, `AnyView`, raw `Gtk.Widget`).
func styleClass(_ name: String, _ enabled: Bool) -> AnyView {
guard enabled else { return AnyView(self) }
return AnyView(makeWidget: { ctx in
let w = AnyView(self).makeWidget(ctx)
w.addCssClass(cssClass: name)
return w
})
}
/// `AnyView`-returning counterpart for views that are not ``WidgetView``
/// (`HStack`, `VStack`, `AnyView`, raw `Gtk.Widget`). The subscription is
/// registered with the mount context's registry, so unmount cancels it.
func styleClass(_ name: String, _ enabled: Binding<Bool>) -> AnyView {
AnyView(makeWidget: { ctx in
let w = AnyView(self).makeWidget(ctx)
if enabled.untrackedValue { w.addCssClass(cssClass: name) }
ctx.registry.add(enabled.subscribe { [w] on in
if on { w.addCssClass(cssClass: name) } else { w.removeCssClass(cssClass: name) }
})
return w
})
}
}