Ported to new ags version

This commit is contained in:
Thomas Avé 2025-07-09 16:09:53 +02:00
parent c5712bb3d4
commit ffed9ee873
9 changed files with 451 additions and 459 deletions

View File

@ -1,11 +1,15 @@
import { App, Astal, Gdk, Gtk, Widget } from "astal/gtk3"; import { Astal, Gdk } from "ags/gtk4";
import { GLib, Variable, bind } from "astal"; import app from "ags/gtk4/app"
import Gtk from "gi://Gtk?version=4.0"
import { createBinding, createState, For, With, Accessor } from "ags"
import { createPoll } from "ags/time"
import Tray from "gi://AstalTray"; import Tray from "gi://AstalTray";
import { execAsync } from "astal/process" import { execAsync } from "ags/process"
import Hyprland from "gi://AstalHyprland"; import Hyprland from "gi://AstalHyprland";
import { getIconName } from "./utils"; import { getIconName } from "./utils";
import Wp from "gi://AstalWp" import Wp from "gi://AstalWp"
import Battery from "gi://AstalBattery" import Battery from "gi://AstalBattery"
import GLib from "gi://GLib";
const battery = Battery.get_default() const battery = Battery.get_default()
const sensorsAvailable = await execAsync(['sensors']).then(() => true).catch(() => false); const sensorsAvailable = await execAsync(['sensors']).then(() => true).catch(() => false);
@ -13,23 +17,30 @@ const wirePlumber = Wp.get_default();
function SysTray(): JSX.Element { function SysTray(): JSX.Element {
const tray = Tray.get_default(); const tray = Tray.get_default();
let items = createBinding(tray, "items");
const init = (btn: Gtk.MenuButton, item: Tray.TrayItem) => {
btn.menuModel = item.menuModel
btn.insert_action_group("dbusmenu", item.actionGroup)
item.connect("notify::action-group", () => {
btn.insert_action_group("dbusmenu", item.actionGroup)
})
}
return ( return (
<box> <box>
{bind(tray, "items").as((items) => <For each={items}>
items.map((item) => { {(item: Tray.TrayItem) => {
if (item.iconThemePath) App.add_icons(item.iconThemePath); if (item.iconThemePath) app.add_icons(item.iconThemePath);
return ( return (
<menubutton <menubutton
className="systray" $={(self) => init(self, item)}
tooltipMarkup={bind(item, "tooltipMarkup")} class="systray"
usePopover={false} tooltipMarkup={createBinding(item, "tooltipMarkup")}
actionGroup={bind(item, "actionGroup").as(ag => ["dbusmenu", ag])} menuModel={createBinding(item, "menuModel")}>
menuModel={bind(item, "menuModel")}> <image gicon={item.gicon} class="systray-item" />
<icon gicon={bind(item, "gicon")} className="systray-item" />
</menubutton> </menubutton>
); );
}), }}
)} </For>
</box> </box>
); );
} }
@ -51,85 +62,77 @@ function Center() : JSX.Element {
} }
function Date({ format = "%Y-%m-%d" }): JSX.Element { function Date({ format = "%Y-%m-%d" }): JSX.Element {
const time = Variable<string>("").poll(60000, () => const time = createPoll<string>("", 60000, () => GLib.DateTime.new_now_local().format(format)!)
GLib.DateTime.new_now_local().format(format)!)
return <button return <button
className="item" class="item"
onDestroy={() => time.drop()} label={time}
label={time()}
onClicked={() => execAsync(['gnome-calendar'])} onClicked={() => execAsync(['gnome-calendar'])}
/> />
} }
function Time({ format = "%H:%M:%S" }): JSX.Element { function Time({ format = "%H:%M:%S" }): JSX.Element {
const time = Variable<string>("").poll(1000, () => const time = createPoll<string>("", 10000, () => GLib.DateTime.new_now_local().format(format)!)
GLib.DateTime.new_now_local().format(format)!)
return <label return <label
className="item blue" class="item blue"
onDestroy={() => time.drop()} label={time}
label={time()}
/> />
} }
function Temp(): JSX.Element { function Temp(): JSX.Element {
let label = Variable<string>("N/A"); let [label, _setlabel] = createState<string>("N/A");
if (sensorsAvailable) { if (sensorsAvailable) {
label = Variable<string>("").poll(5000, 'sensors', out => { label = createPoll<string>("", 5000, 'sensors', out => {
const match = out.split('\n').find(line => line.includes('Tctl') || line.includes('Package'))?.match(/[0-9.]*°C/); const match = out.split('\n').find(line => line.includes('Tctl') || line.includes('Package'))?.match(/[0-9.]*°C/);
return match ? match[0] : "N/A"; return match ? match[0] : "N/A";
}) })
} }
return <label return <label
className="item blue" class="item blue"
onDestroy={() => label.drop()} label={label}
label={label()}
/> />
} }
function Memory(): JSX.Element { function Memory(): JSX.Element {
const memory = Variable<string>("").poll(2000, "free", out => { const memory = createPoll<string>("", 2000, "free", out => {
const line = out.split('\n').find(line => line.includes('Mem:')); const line = out.split('\n').find(line => line.includes('Mem:'));
if (!line) return "N/A"; if (!line) return "N/A";
const split = line.split(/\s+/).map(Number); const split = line.split(/\s+/).map(Number);
return (split[2] / 1000000).toFixed(2) + "GB"; return (split[2] / 1000000).toFixed(2) + "GB";
}); });
return <label return <label
className="item blue" class="item blue"
onDestroy={() => memory.drop()} label={memory}
label={memory()}
/> />
} }
function ClockSpeed(): JSX.Element { function ClockSpeed(): JSX.Element {
const command = 'bash -c "cat /proc/cpuinfo | grep \\"MHz\\" | awk \'{print \\$4}\' | sort -n | tail -1 | awk \'{printf \\"%.2fGHz\\", \\$1/1000}\'"'; const command = 'bash -c "cat /proc/cpuinfo | grep \\"MHz\\" | awk \'{print \\$4}\' | sort -n | tail -1 | awk \'{printf \\"%.2fGHz\\", \\$1/1000}\'"';
const speed = Variable<string>("").poll(5000, command) const speed = createPoll<string>("", 5000, command, out => out)
return <label return <label
className="item" class="item"
onDestroy={() => speed.drop()} label={speed}
label={speed()}
/> />
} }
function CPU(): JSX.Element { function CPU(): JSX.Element {
const usage = Variable<string>("").poll(2000, "top -b -n 1", out => { const usage = createPoll<string>("", 2000, "top -b -n 1", out => {
const line = out.split("\n").find(line => line.includes('Cpu(s)')); const line = out.split("\n").find(line => line.includes('Cpu(s)'));
if (!line) return "N/A"; if (!line) return "N/A";
return line.split(/\s+/)[1].replace(',', '.').toString() + "%"; return line.split(/\s+/)[1].replace(',', '.').toString() + "%";
}); });
return <box className="item"> return <box class="item">
<icon icon="speedometer" css="margin-right: 0.7em;" /> <image iconName="speedometer" css="margin-right: 0.7em;" />
<label <label
onDestroy={() => usage.drop()} label={usage}
label={usage()}
/> />
</box> </box>
} }
function Right() : JSX.Element { function Right() {
return ( return (
<box className="right" hexpand halign={Gtk.Align.END} spacing={6}> <box class="right" hexpand halign={Gtk.Align.END} spacing={6}>
<Icons /> <Icons />
<Volume /> <Volume />
<CPU /> <CPU />
@ -144,25 +147,26 @@ function Right() : JSX.Element {
function BatteryIcon(): JSX.Element { function BatteryIcon(): JSX.Element {
if (battery.get_state() == 0) return <box />; if (battery.get_state() == 0) return <box />;
return <button className="battery-item" onClicked={() => execAsync(['gnome-power-statistics'])}> let batteryPercentage = createBinding(battery, "percentage");
return <button class="battery-item" onClicked={() => execAsync(['gnome-power-statistics'])}>
<box> <box>
{ <With value={batteryPercentage}>
bind(battery, "percentage").as((percentage) => { {(percentage) => {
const thresholds = [...Array(11).keys()].map(i => i * 10); const thresholds = [...Array(11).keys()].map(i => i * 10);
const icon = thresholds.find(threshold => threshold >= percentage * 100) const icon = thresholds.find(threshold => threshold >= percentage * 100)
const charging_name = battery.percentage >= 0.99 ? "charged" : "charging" const charging_name = battery.percentage >= 0.99 ? "charged" : "charging"
return <icon return <image
icon={battery.charging? `battery-level-${icon}-${charging_name}-symbolic` : `battery-level-${icon}-symbolic`} iconName={battery.charging ? `battery-level-${icon}-${charging_name}-symbolic` : `battery-level-${icon}-symbolic`}
/> />
}) }}
} </With>
</box> </box>
</button> </button>
} }
function Icons() { function Icons() {
return ( return (
<box className="item icon-group"> <box class="item icon-group">
<SysTray /> <SysTray />
<BatteryIcon /> <BatteryIcon />
</box> </box>
@ -173,7 +177,7 @@ function Volume(): JSX.Element {
if (!wirePlumber) return <box />; if (!wirePlumber) return <box />;
const audio = wirePlumber.audio; const audio = wirePlumber.audio;
const icon = bind(audio.default_speaker, "volume").as((volume) => { const icon = createBinding(audio.default_speaker, "volume").as((volume) => {
const vol = volume * 100 const vol = volume * 100
const icon = [ const icon = [
[101, 'overamplified'], [101, 'overamplified'],
@ -184,24 +188,26 @@ function Volume(): JSX.Element {
].find(([threshold]) => Number(threshold) <= vol)?.[1] ].find(([threshold]) => Number(threshold) <= vol)?.[1]
return `audio-volume-${icon}-symbolic` return `audio-volume-${icon}-symbolic`
}); });
const css = bind(audio.default_speaker, "mute").as((mute) => { const css = createBinding(audio.default_speaker, "mute").as((mute) => {
return mute ? "margin-left:0;" : "margin-left: 0.7em;" return mute ? "margin-left:0;" : "margin-left: 0.7em;"
}); });
let volume = createBinding(audio.default_speaker, "volume");
let mute = createBinding(audio.default_speaker, "mute");
return ( return (
<button className="item blue" onClicked={() => audio.default_speaker.mute = !audio.default_speaker.mute}> <button class="item blue" onClicked={() => audio.default_speaker.mute = !audio.default_speaker.mute}>
<box> <box>
<icon icon={icon} /> <image iconName={icon} />
{ <With value={volume}>
bind(audio.default_speaker, "volume").as((volume) => <box> {(vol) => <box>
{ <With value={mute}>
bind(audio.default_speaker, "mute").as((mute) => <box> {(muted) => {
{ return (
<label label={mute? "": `${Math.floor(volume * 100)}%`} css={css} /> <label label={muted ? "" : `${Math.floor(vol * 100)}%`} css={css} />
} )
</box>) }}
} </With>
</box>) </box>}
} </With>
</box> </box>
</button> </button>
); );
@ -210,23 +216,35 @@ function Volume(): JSX.Element {
function Workspaces(): JSX.Element { function Workspaces(): JSX.Element {
const hyprland = Hyprland.get_default(); const hyprland = Hyprland.get_default();
let workspaces = createBinding(hyprland, "workspaces");
return ( return (
<box className="workspaces"> <box class="workspaces">
{bind(hyprland, "workspaces").as((wss) => <With value={workspaces}>
{(wss: Array<Hyprland.Workspace>) => (
<box> <box>
{bind(hyprland, "focusedMonitor").as((fm) => <With value={createBinding(hyprland, "focusedMonitor")}>
wss.sort((a, b) => a.id - b.id) {(fm: Hyprland.Monitor) => {
.filter(ws => ws && ws.get_monitor() && ws.get_monitor().get_id() === fm.get_id()) let filtered_wss = new Accessor(() => wss.sort((a, b) => a.id - b.id)
.map((ws) => ( .filter(ws => ws && ws.get_monitor() && ws.get_monitor().get_id() === fm.get_id()))
return (
<box>
<For each={filtered_wss}>
{(ws: Hyprland.Workspace, _index) => (
<button <button
className={bind(hyprland, "focusedWorkspace").as((fw) => ws === fw ? "focused" : "",)} class={createBinding(hyprland, "focusedWorkspace").as((fw) => ws === fw ? "focused" : "",)}
onClicked={() => ws.focus()} onClicked={() => ws.focus()}
> >
{`${ws.id}`.slice(-1)} {`${ws.id}`.slice(-1)}
</button> </button>
)))} )}
</For>
</box>
)
}}
</With>
</box> </box>
)} )}
</With>
</box> </box>
); );
} }
@ -237,57 +255,64 @@ function shorten(title: string) {
function Clients(): JSX.Element { function Clients(): JSX.Element {
const hyprland = Hyprland.get_default(); const hyprland = Hyprland.get_default();
let clients = createBinding(hyprland, "clients")
return ( return (
<box> <box>
{ <With value={createBinding(hyprland, "focusedWorkspace")}>
bind(hyprland, "focusedWorkspace").as(fw => ( {(fw: Hyprland.Workspace) => (
<box className="clients"> <box class="clients">
{ <With value={clients}>
bind(hyprland, "clients").as(cls => {(cls: Array<Hyprland.Client>) => {
cls let filtered_clients = new Accessor(() => cls
.sort((a, b) => a.pid - b.pid) .sort((a, b) => a.pid - b.pid)
.filter(cl => !cl.title.includes("rofi")) .filter(cl => !cl.title.includes("rofi"))
.filter(cl => fw && cl.get_workspace().get_id() === fw.get_id()) .filter(cl => fw && cl.get_workspace().get_id() === fw.get_id()))
.map(cl => (
<box
className={bind(hyprland, "focusedClient").as(a => a && a.address === cl.address ? "focused" : "unfocused")}
>
<icon
icon={getIconName(cl)}
className="app-icon"
/>
<label label={bind(cl, 'title').as(title => shorten(title))} />
</box>
)
)
)
} return (
<box>
<For each={filtered_clients}>
{(cl: Hyprland.Client, _index) => (
<box
class={createBinding(hyprland, "focusedClient").as(a => a && a.address === cl.address ? "focused" : "unfocused")}
>
<image
iconName={getIconName(cl)}
class="app-icon"
/>
<label label={createBinding(cl, 'title').as(title => shorten(title))} />
</box>
)}
</For>
</box> </box>
) )
}
}
</With>
</box>
) )
} }
</With >
</box > </box >
); );
} }
export default function Bar(gdkmonitor: Gdk.Monitor, scaleFactor: number = 1): Widget.Window { export default function Bar(gdkmonitor: Gdk.Monitor, scaleFactor: number = 1) {
return new Widget.Window({ console.log("Creating Bar on monitor:", gdkmonitor);
gdkmonitor, return (
css: "font-size: " + scaleFactor + "em;", <window
exclusivity: Astal.Exclusivity.EXCLUSIVE, visible
anchor: Astal.WindowAnchor.TOP | Astal.WindowAnchor.LEFT | Astal.WindowAnchor.RIGHT, gdkmonitor={gdkmonitor}
application: App, css={"font-size: " + scaleFactor + "em;"}
className: "Bar", exclusivity={Astal.Exclusivity.EXCLUSIVE}
name: "top-bar", anchor={Astal.WindowAnchor.TOP | Astal.WindowAnchor.LEFT | Astal.WindowAnchor.RIGHT}
setup: self => self.connect("destroy", () => { application={app}
print("Detroying bar"); class="Bar"
App.remove_window(self); name="top-bar" >
}), <centerbox class="window-box">
child: <centerbox className="window-box"> <Left $type="start" />
<Left /> <Center $type="center" />
<Center /> <Right $type="end" />
<Right />
</centerbox> </centerbox>
}) </window >
)
} }

View File

@ -1,8 +1,10 @@
import { App, Gdk, Widget } from "astal/gtk3" import app from "ags/gtk4/app"
import style from "./style.scss" import style from "./style.scss"
import Bar from "./Bar" import Bar from "./Bar"
import Hyprland from "gi://AstalHyprland"; import Hyprland from "gi://AstalHyprland";
import NotificationPopups from "./notifications/NotificationPopups" import NotificationPopups from "./notifications/NotificationPopups"
import Gtk from "gi://Gtk?version=4.0";
import { Gdk } from "ags/gtk4";
const hyprland = Hyprland.get_default(); const hyprland = Hyprland.get_default();
@ -22,21 +24,26 @@ function find_main_monitor(): Hyprland.Monitor {
} }
function register_windows(monitor: Hyprland.Monitor) { function register_windows(monitor: Hyprland.Monitor) {
let gtkMonitor = App.get_monitors()[0].get_display().get_monitor_at_point(monitor.get_x(), monitor.get_y()) let gtkMonitors = app.get_monitors()[0].get_display().get_monitors()
let gtkMonitor = gtkMonitors.get_item(0)
if (!gtkMonitor) {
console.error("No GTK monitor found for the Hyprland monitor:", monitor.get_name());
return;
}
let scale = (monitor.get_width() >= 3000) ? 1.2 : 1 let scale = (monitor.get_width() >= 3000) ? 1.2 : 1
Bar(gtkMonitor, scale) Bar(gtkMonitor, scale)
NotificationPopups(gtkMonitor) NotificationPopups()
} }
function switch_to_best_monitor() { function switch_to_best_monitor() {
let mainMonitor = find_main_monitor() let mainMonitor = find_main_monitor()
for (var wd of App.get_windows()) { for (var wd of app.get_windows()) {
wd.destroy(); wd.destroy();
} }
register_windows(mainMonitor); register_windows(mainMonitor);
} }
hyprland.connect("monitor-added", (_, monitor) => { hyprland.connect("monitor-added", (_, _monitor: Hyprland.Monitor) => {
switch_to_best_monitor() switch_to_best_monitor()
}) })
@ -44,7 +51,7 @@ hyprland.connect("monitor-removed", () => {
switch_to_best_monitor() switch_to_best_monitor()
}) })
App.start({ app.start({
css: style, css: style,
iconTheme: "Papirus", iconTheme: "Papirus",
main() { main() {

View File

@ -5,7 +5,7 @@
} }
// https://gitlab.gnome.org/GNOME/gtk/-/blob/gtk-3-24/gtk/theme/Adwaita/_colors-public.scss // https://gitlab.gnome.org/GNOME/gtk/-/blob/gtk-3-24/gtk/theme/Adwaita/_colors-public.scss
$fg-color: #{"@theme_fg_color"}; $fg-color: #{"@theme_bg_color"};
$bg-color: #1f2430; $bg-color: #1f2430;
$error: red; $error: red;
@ -13,78 +13,63 @@ window.NotificationPopups {
all: unset; all: unset;
} }
eventbox.Notification { .Notification {
&:first-child>box {
margin-top: 1rem;
}
&:last-child>box {
margin-bottom: 1rem;
}
// eventboxes can not take margins so we style its inner box instead
>box {
min-width: 400px;
border-radius: 13px; border-radius: 13px;
background-color: #1f2430; background-color: $bg-color;
margin: .5rem 1rem .5rem 1rem; margin: 0.5rem 1rem 0.5rem 1rem;
box-shadow: 2px 3px 8px 0 gtkalpha(black, .4); box-shadow: 2px 3px 8px 0 gtkalpha(black, 0.4);
border: 1pt solid gtkalpha($fg-color, .03); border: 1pt solid gtkalpha($fg-color, 0.03);
}
&.critical>box { &.critical {
border: 1pt solid gtkalpha($error, .4); border: 1pt solid gtkalpha($error, 0.4);
.header { .header {
.app-name { .app-name {
color: gtkalpha($error, .8); color: gtkalpha($error, 0.8);
} }
.app-icon { .app-icon {
color: gtkalpha($error, .6); color: gtkalpha($error, 0.6);
} }
} }
} }
.header { .header {
padding: .5rem; padding: 0.5rem;
color: gtkalpha($fg-color, 0.5); color: gtkalpha($fg-color, 0.5);
.app-icon { .app-icon {
margin: 0 .4rem; margin: 0 0.4rem;
} }
.app-name { .app-name {
margin-right: .3rem; margin-right: 0.3rem;
font-weight: bold; font-weight: bold;
&:first-child { &:first-child {
margin-left: .4rem; margin-left: 0.4rem;
} }
} }
.time { .time {
margin: 0 .4rem; margin: 0 0.4rem;
} }
button { button {
padding: .2rem; padding: 0.2rem;
min-width: 0; min-width: 0;
min-height: 0; min-height: 0;
} }
} }
separator { separator {
margin: 0 .4rem; margin: 0 0.4rem;
background-color: gtkalpha($fg-color, .1); background-color: gtkalpha($fg-color, 0.1);
} }
.content { .content {
margin: 1rem; margin: 1rem;
margin-top: .5rem; margin-top: 0.5rem;
.summary { .summary {
font-size: 1.2em; font-size: 1.2em;
@ -96,8 +81,8 @@ eventbox.Notification {
} }
.image { .image {
border: 1px solid gtkalpha($fg-color, .02); border: 1px solid gtkalpha($fg-color, 0.02);
margin-right: .5rem; margin-right: 0.5rem;
border-radius: 9px; border-radius: 9px;
min-width: 100px; min-width: 100px;
min-height: 100px; min-height: 100px;
@ -111,7 +96,7 @@ eventbox.Notification {
margin-top: 0; margin-top: 0;
button { button {
margin: 0 .3rem; margin: 0 0.3rem;
&:first-child { &:first-child {
margin-left: 0; margin-left: 0;

View File

@ -1,107 +1,120 @@
import { GLib } from "astal" import Gtk from "gi://Gtk?version=4.0"
import { Gtk, Astal } from "astal/gtk3" import Gdk from "gi://Gdk?version=4.0"
import { type EventBox } from "astal/gtk3/widget" import Adw from "gi://Adw"
import Notifd from "gi://AstalNotifd" import GLib from "gi://GLib"
import AstalNotifd from "gi://AstalNotifd"
import Pango from "gi://Pango"
const isIcon = (icon: string) => function isIcon(icon?: string | null) {
!!Astal.Icon.lookup_icon(icon) const iconTheme = Gtk.IconTheme.get_for_display(Gdk.Display.get_default()!)
return icon && iconTheme.has_icon(icon)
}
const fileExists = (path: string) => function fileExists(path: string) {
GLib.file_test(path, GLib.FileTest.EXISTS) return GLib.file_test(path, GLib.FileTest.EXISTS)
}
const time = (time: number, format = "%H:%M") => GLib.DateTime function time(time: number, format = "%H:%M") {
.new_from_unix_local(time) return GLib.DateTime.new_from_unix_local(time).format(format)!
.format(format)! }
const urgency = (n: Notifd.Notification) => { function urgency(n: AstalNotifd.Notification) {
const { LOW, NORMAL, CRITICAL } = Notifd.Urgency const { LOW, NORMAL, CRITICAL } = AstalNotifd.Urgency
// match operator when?
switch (n.urgency) { switch (n.urgency) {
case LOW: return "low" case LOW:
case CRITICAL: return "critical" return "low"
case CRITICAL:
return "critical"
case NORMAL: case NORMAL:
default: return "normal" default:
return "normal"
} }
} }
type Props = { export default function Notification({
setup(self: EventBox): void notification: n,
onHoverLost(self: EventBox): void onHoverLost,
notification: Notifd.Notification }: {
} notification: AstalNotifd.Notification
onHoverLost: () => void
export default function Notification(props: Props) { }) {
const { notification: n, onHoverLost, setup } = props return (
const { START, CENTER, END } = Gtk.Align <Adw.Clamp maximumSize={400}>
<box
return <eventbox widthRequest={400}
className={`Notification ${urgency(n)}`} class={`Notification ${urgency(n)}`}
setup={setup} orientation={Gtk.Orientation.VERTICAL}
onHoverLost={onHoverLost}> >
<box vertical> <Gtk.EventControllerMotion onLeave={onHoverLost} />
<box className="header"> <box class="header">
{(n.appIcon || n.desktopEntry) && <icon {(n.appIcon || isIcon(n.desktopEntry)) && (
className="app-icon" <image
class="app-icon"
visible={Boolean(n.appIcon || n.desktopEntry)} visible={Boolean(n.appIcon || n.desktopEntry)}
icon={n.appIcon || n.desktopEntry} iconName={n.appIcon || n.desktopEntry}
/>} />
)}
<label <label
className="app-name" class="app-name"
halign={START} halign={Gtk.Align.START}
truncate ellipsize={Pango.EllipsizeMode.END}
label={n.appName || "Unknown"} label={n.appName || "Unknown"}
/> />
<label <label
className="time" class="time"
hexpand hexpand
halign={END} halign={Gtk.Align.END}
label={time(n.time)} label={time(n.time)}
/> />
<button onClicked={() => n.dismiss()}> <button onClicked={() => n.dismiss()}>
<icon icon="window-close-symbolic" /> <image iconName="window-close-symbolic" />
</button> </button>
</box> </box>
<Gtk.Separator visible /> <Gtk.Separator visible />
<box className="content"> <box class="content">
{n.image && fileExists(n.image) && <box {n.image && fileExists(n.image) && (
valign={START} <image valign={Gtk.Align.START} class="image" file={n.image} />
className="image" )}
css={`background-image: url('${n.image}')`} {n.image && isIcon(n.image) && (
/>} <box valign={Gtk.Align.START} class="icon-image">
{n.image && isIcon(n.image) && <box <image
expand={false} iconName={n.image}
valign={START} halign={Gtk.Align.CENTER}
className="icon-image"> valign={Gtk.Align.CENTER}
<icon icon={n.image} expand halign={CENTER} valign={CENTER} /> />
</box>} </box>
<box vertical> )}
<box orientation={Gtk.Orientation.VERTICAL}>
<label <label
className="summary" class="summary"
halign={START} halign={Gtk.Align.START}
xalign={0} xalign={0}
label={n.summary} label={n.summary}
truncate ellipsize={Pango.EllipsizeMode.END}
/> />
{n.body && <label {n.body && (
className="body" <label
class="body"
wrap wrap
useMarkup useMarkup
halign={START} halign={Gtk.Align.START}
xalign={0} xalign={0}
justifyFill justify={Gtk.Justification.FILL}
label={n.body} label={n.body}
/>} />
)}
</box> </box>
</box> </box>
{n.get_actions().length > 0 && <box className="actions"> {n.actions.length > 0 && (
{n.get_actions().map(({ label, id }) => ( <box class="actions">
<button {n.actions.map(({ label, id }) => (
hexpand <button hexpand onClicked={() => n.invoke(id)}>
onClicked={() => n.invoke(id)}> <label label={label} halign={Gtk.Align.CENTER} hexpand />
<label label={label} halign={CENTER} hexpand />
</button> </button>
))} ))}
</box>}
</box> </box>
</eventbox> )}
</box>
</Adw.Clamp>
)
} }

View File

@ -1,105 +1,65 @@
import { Astal, Gtk, Gdk } from "astal/gtk3" import app from "ags/gtk4/app"
import Notifd from "gi://AstalNotifd" import { Astal, Gtk } from "ags/gtk4"
import AstalNotifd from "gi://AstalNotifd"
import Notification from "./Notification" import Notification from "./Notification"
import { type Subscribable } from "astal/binding" import { createBinding, For, createState, onCleanup } from "ags"
import { GLib, Variable, bind, timeout } from "astal"
// see comment below in constructor export default function NotificationPopups() {
const TIMEOUT_DELAY = 5000 const monitors = createBinding(app, "monitors")
// The purpose if this class is to replace Variable<Array<Widget>> const notifd = AstalNotifd.get_default()
// with a Map<number, Widget> type in order to track notification widgets
// by their id, while making it conviniently bindable as an array
class NotifiationMap implements Subscribable {
// the underlying map to keep track of id widget pairs
private map: Map<number, Gtk.Widget> = new Map()
// it makes sense to use a Variable under the hood and use its const [notifications, setNotifications] = createState(
// reactivity implementation instead of keeping track of subscribers ourselves new Array<AstalNotifd.Notification>(),
private var: Variable<Array<Gtk.Widget>> = Variable([]) )
// notify subscribers to rerender when state changes const notifiedHandler = notifd.connect("notified", (_, id, replaced) => {
private notifiy() { const notification = notifd.get_notification(id)
this.var.set([...this.map.values()].reverse())
if (replaced && notifications.get().some(n => n.id === id)) {
setNotifications((ns) => ns.map((n) => (n.id === id ? notification : n)))
} else {
setNotifications((ns) => [notification, ...ns])
} }
private constructor() {
const notifd = Notifd.get_default()
/**
* uncomment this if you want to
* ignore timeout by senders and enforce our own timeout
* note that if the notification has any actions
* they might not work, since the sender already treats them as resolved
*/
// notifd.ignoreTimeout = true
notifd.connect("notified", (_, id) => {
this.set(id, Notification({
notification: notifd.get_notification(id)!,
// once hovering over the notification is done
// destroy the widget without calling notification.dismiss()
// so that it acts as a "popup" and we can still display it
// in a notification center like widget
// but clicking on the close button will close it
onHoverLost: () => this.delete(id),
// notifd by default does not close notifications
// until user input or the timeout specified by sender
// which we set to ignore above
setup: () => timeout(TIMEOUT_DELAY, () => {
/**
* uncomment this if you want to "hide" the notifications
* after TIMEOUT_DELAY
*/
this.delete(id)
})
}))
}) })
// notifications can be closed by the outside before const resolvedHandler = notifd.connect("resolved", (_, id) => {
// any user input, which have to be handled too setNotifications((ns) => ns.filter((n) => n.id !== id))
notifd.connect("resolved", (_, id) => {
this.delete(id)
}) })
}
private set(key: number, value: Gtk.Widget) { // technically, we don't need to cleanup because in this example this is a root component
// in case of replacecment destroy previous widget // and this cleanup function is only called when the program exits, but exiting will cleanup either way
this.map.get(key)?.destroy() // but it's here to remind you that you should not forget to cleanup signal connections
this.map.set(key, value) onCleanup(() => {
this.notifiy() notifd.disconnect(notifiedHandler)
} notifd.disconnect(resolvedHandler)
})
private delete(key: number) { return (
this.map.get(key)?.destroy() <For each={monitors} cleanup={(win) => (win as Gtk.Window).destroy()}>
this.map.delete(key) {(monitor) => (
this.notifiy() <window
class="NotificationPopups"
gdkmonitor={monitor}
visible={notifications((ns) => ns.length > 0)}
anchor={Astal.WindowAnchor.TOP | Astal.WindowAnchor.RIGHT}
>
<box orientation={Gtk.Orientation.VERTICAL}>
<For each={notifications}>
{(notification) => (
<Notification
notification={notification}
onHoverLost={() =>
setNotifications((ns) =>
ns.filter((n) => n.id !== notification.id),
)
} }
/>
// needed by the Subscribable interface )}
get() { </For>
return this.var.get()
}
// needed by the Subscribable interface
subscribe(callback: (list: Array<Gtk.Widget>) => void) {
return this.var.subscribe(callback)
}
}
export default function NotificationPopups(gdkmonitor: Gdk.Monitor) {
const { TOP, RIGHT } = Astal.WindowAnchor
const notifs = new NotifiationMap()
return <window
className="NotificationPopups"
gdkmonitor={gdkmonitor}
exclusivity={Astal.Exclusivity.EXCLUSIVE}
anchor={TOP | RIGHT}>
<box vertical>
{bind(notifs)}
</box> </box>
</window> </window>
)}
</For>
)
} }

View File

@ -0,0 +1,5 @@
{
"dependencies": {
"ags": "*"
}
}

View File

@ -17,7 +17,7 @@ window.Bar {
margin-top: 0.2em; margin-top: 0.2em;
} }
.clients box { .clients box box {
margin-right: 0.3em; margin-right: 0.3em;
} }
@ -27,11 +27,13 @@ window.Bar {
border-radius: 0.3em; border-radius: 0.3em;
background: #1f2430; background: #1f2430;
} }
.battery-item:hover { .battery-item:hover {
background: #023269; background: #023269;
} }
.item, .clients box { .item,
.clients box box {
background: #1f2430; background: #1f2430;
padding-left: 0.7em; padding-left: 0.7em;
padding-right: 0.7em; padding-right: 0.7em;
@ -54,7 +56,8 @@ window.Bar {
border-radius: 0.3em; border-radius: 0.3em;
} }
.focused, .clients box.focused { .focused,
.clients box.focused {
background: #023269; background: #023269;
} }

View File

@ -1,22 +1,16 @@
{ {
"$schema": "https://json.schemastore.org/tsconfig", "$schema": "https://json.schemastore.org/tsconfig",
"compilerOptions": { "compilerOptions": {
"experimentalDecorators": true,
"strict": true, "strict": true,
"target": "ES2022",
"module": "ES2022", "module": "ES2022",
"target": "ES2020",
"lib": [
"ES2023"
],
"moduleResolution": "Bundler", "moduleResolution": "Bundler",
// "checkJs": true, // "checkJs": true,
// "allowJs": true, // "allowJs": true,
"jsx": "react-jsx", "jsx": "react-jsx",
"jsxImportSource": "/nix/store/1pd4fdq90f4vla3zghmfci9axsbvkd3w-astal-gjs/share/astal/gjs/gtk3", "jsxImportSource": "ags/gtk4"
"paths": {
"astal": [
"/nix/store/1pd4fdq90f4vla3zghmfci9axsbvkd3w-astal-gjs/share/astal/gjs"
],
"astal/*": [
"/nix/store/1pd4fdq90f4vla3zghmfci9axsbvkd3w-astal-gjs/share/astal/gjs/*"
]
},
} }
} }