feat: make AGS colorshell configuration fully declarative

- Add complete colorshell v2.0.3 configuration to home/ags-config/
- Disable runner plugin and NightLight tile (incompatible with NixOS)
- Customize SCSS with full opacity (no transparency)
- Add dark pale blue color scheme in home/pywal-colors/
- Configure Papirus-Dark icon theme via home-manager
- Make ~/.config/ags/ immutable and managed by Nix store
- Auto-deploy pywal colors to ~/.cache/wal/colors.json

All AGS configuration is now reproducible and version controlled.
This commit is contained in:
2025-11-04 21:36:38 +00:00
parent 593735370a
commit b2ae32a078
240 changed files with 1024921 additions and 3 deletions

View File

@@ -0,0 +1,383 @@
import { Astal, Gdk, Gtk } from "ags/gtk4";
import { CCProps } from "ags";
import { getPopupWindowContainer, PopupWindow } from "../widget/PopupWindow";
import { updateApps } from "../modules/apps";
import { ResultWidget, ResultWidgetProps } from "./widgets/ResultWidget";
import { Windows } from "../windows";
import AstalHyprland from "gi://AstalHyprland";
import GLib from "gi://GLib?version=2.0";
export namespace Runner {
export type RunnerProps = {
halign?: Gtk.Align;
valign?: Gtk.Align;
width?: number;
height?: number;
entryPlaceHolder?: string;
initialText?: string;
resultsLimit?: number;
showResultsPlaceHolderOnStartup?: boolean;
};
export type Result = CCProps<ResultWidget, ResultWidgetProps>;
export interface Plugin {
/** prefix to call the plugin. if undefined, will be triggered like applications plugin */
readonly prefix?: string;
/** name of the plugin. e.g.: websearch, shell */
readonly name?: string;
/** runs when runner opens */
readonly init?: () => void;
/** handle the user input to return results (does not include plugin's prefix) */
readonly handle: (inputText: string, limit?: number) => Promise<Result|Array<Result>|null|undefined>|Result|Array<Result>|null|undefined;
/** runs when runner closes */
readonly onClose?: () => void;
/** prioritize this plugin's results over other results.
* (hides other results that aren't from this plugin on list) */
prioritize?: boolean;
/** show a specific icon when the plugin is prioritized/only
* has results from this plugin
* @todo actually implement the plugin icon feature
* @default "system-search-symbolic" */
iconName?: string;
}
export let instance: (Astal.Window|null) = null;
let gtkEntry: (Gtk.Entry|null) = null;
const plugins = new Set<Runner.Plugin>();
const ignoredKeys = [
Gdk.KEY_space,
Gdk.KEY_Shift_L,
Gdk.KEY_Shift_R,
Gdk.KEY_Shift_Lock,
Gdk.KEY_Return,
Gdk.KEY_Tab,
Gdk.KEY_Control_L,
Gdk.KEY_Control_R,
Gdk.KEY_Alt_L,
Gdk.KEY_Alt_R,
Gdk.KEY_Option,
Gdk.KEY_Super_L,
Gdk.KEY_Super_R,,
Gdk.KEY_F5,
Gdk.KEY_Up,
Gdk.KEY_Down,
Gdk.KEY_Left,
Gdk.KEY_Right
];
export function close() { instance?.close(); }
export function regExMatch(search: string, item: (string|number)): boolean {
search = search.replace(/[\\^$.*?()[\]{}|]/g, "\\$&");
if(typeof item === "number")
return new RegExp(`${search.split('').map(c =>
`[${c}]`).join('')}`,
"g").test(item.toString());
return new RegExp(`${search.split('').map(c =>
`${c}`).join('')}`,
"gi").test(item);
}
export function addPlugin(plugin: Runner.Plugin, force?: boolean) {
if(!force && plugin.prefix && plugins.has(plugin))
throw new Error(`Runner plugin with prefix ${plugin.prefix} already exists`);
plugins.delete(plugin);
plugins.add(plugin);
}
export function getPlugins(): Array<Runner.Plugin> {
return [...plugins.values()];
}
/** Removes a plugin from the runner plugins list
* @returns true if plugin was removed or false if plugin wasn't found
*/
export function removePlugin(plugin: Plugin): boolean {
return plugins.delete(plugin);
}
export function setEntryText(text: string): void {
gtkEntry?.set_text(text);
gtkEntry?.set_position(gtkEntry.text.length);
gtkEntry?.grab_focus();
}
export function openDefault(initialText?: string) {
return Runner.openRunner({
entryPlaceHolder: "Start typing...",
initialText,
showResultsPlaceHolderOnStartup: false,
resultsLimit: 24
} as Runner.RunnerProps, [
{
icon: "application-x-executable-symbolic",
title: "Use your applications",
description: "Search for any app installed in your computer",
closeOnClick: false,
actionClick: () => gtkEntry?.grab_focus()
},
{
icon: "edit-paste-symbolic",
title: "See your clipboard history",
description: "Start your search with '>' to go through your clipboard history",
closeOnClick: false,
actionClick: () => setEntryText('>')
},
{
icon: "image-x-generic-symbolic",
title: "Change your wallpaper",
description: "Add '#' at the start to search through the wallpapers folder!",
closeOnClick: false,
actionClick: () => setEntryText('#'),
},
{
icon: "utilities-terminal-symbolic",
title: "Run shell commands",
description: "Add '!' before your command to run it (tip: add another '!' to notify command output)",
closeOnClick: false,
actionClick: () => setEntryText('!')
},
{
icon: "media-playback-start-symbolic",
title: "Control media",
description: "Type ':' to control playing media",
closeOnClick: false,
actionClick: () => setEntryText(':')
},
{
icon: "applications-internet-symbolic",
title: "Search the Web",
description: "Start typing with '?' prefix to search the web",
closeOnClick: false,
actionClick: () => setEntryText('?')
}
]);
}
async function getPluginResults(input: string, limit?: number): Promise<Array<Result>> {
let calledPlugins: Array<Plugin> = getPlugins().filter((plugin) =>
plugin.prefix ? (input.startsWith(plugin.prefix) ? true : false) : true
).sort((plugin) => plugin.prefix != null ? 0 : 1);
for(const plugin of calledPlugins) {
if(plugin.prioritize) {
calledPlugins = [ plugin ];
plugin.iconName !== undefined &&
gtkEntry
break;
}
}
let results: Array<Result> = [];
function push(result: Result|null|undefined|void|Array<Result|null|undefined|void>) {
if(Array.isArray(result)) {
results.push(...result.filter(r => r != null));
return;
}
result && results.push(result);
}
for(const plugin of calledPlugins) {
const res = plugin.handle(plugin.prefix ?
input.replace(plugin.prefix, "")
: input, limit);
res instanceof Promise ?
await res.then(push)
: push(res);
}
return limit !== undefined && limit > 0 && limit !== Infinity ?
results.splice(0, limit)
: results;
}
async function updateResultsList(listbox: Gtk.ListBox, input: string, limit?: number, placeholders?: Array<Result>) {
const newResults: Array<Result> = [],
scrolledWindow = listbox.parent.parent as Gtk.ScrolledWindow;
const results = await getPluginResults(input, limit).catch((e: Error) => {
console.error(`Couldn't get results because of an error: ${e.message}\n${e.stack}`);
listbox.insert(<ResultWidget title={`Error: ${e.message}`}
description={"Try changing your search a little..."}
icon={"window-close-symbolic"}
actionClick={() => gtkEntry?.select_region(0, gtkEntry?.text.length - 1)}
/> as ResultWidget, -1);
return [] as Array<Result>;
});
listbox.remove_all();
results.forEach((result) => {
listbox.insert(<ResultWidget {...result} /> as ResultWidget, -1);
newResults.push(result);
});
// Insert placeholder if there are no results
if(placeholders && newResults.length < 1)
placeholders.forEach(phdlr => listbox.insert(
<ResultWidget {...phdlr} /> as ResultWidget, -1
));
newResults.length > 0 ?
(!scrolledWindow.visible && scrolledWindow.show())
: scrolledWindow.hide();
}
function selectPreviousItem(listbox: Gtk.ListBox) {
const selectedRow = listbox.get_selected_row();
const prevRow = selectedRow?.get_prev_sibling();
if(!prevRow || selectedRow === listbox.get_first_child())
return;
const viewport = listbox.parent as Gtk.Viewport;
const vadjustment = (viewport.parent as Gtk.ScrolledWindow).get_vadjustment();
const [, , prevRowY] = prevRow.translate_coordinates(viewport,
prevRow.get_allocation().x, prevRow.get_allocation().y);
listbox.select_row(prevRow as Gtk.ListBoxRow);
if(prevRowY < vadjustment.get_value())
vadjustment.set_value(prevRowY);
}
function selectNextItem(listbox: Gtk.ListBox) {
const selectedRow = listbox.get_selected_row();
const nextRow = selectedRow?.get_next_sibling();
if(!nextRow || selectedRow === listbox.get_last_child())
return;
const viewport = listbox.parent as Gtk.Viewport;
const vadjustment = (viewport.parent as Gtk.ScrolledWindow).get_vadjustment();
const nextRowVAllocation = (nextRow.get_allocation().y + nextRow.get_allocation().height);
listbox.select_row(nextRow as Gtk.ListBoxRow);
if(nextRowVAllocation > viewport.get_allocation().height)
vadjustment.set_value(nextRow.get_allocation().y - viewport.get_allocation().height + nextRow.get_allocation().height);}
export function openRunner(props: RunnerProps, placeholders?: Array<Result>): Astal.Window {
props.width ??= 780;
props.height ??= 420;
let clickTimeout: GLib.Source|undefined;
if(!instance)
instance = Windows.getDefault().createWindowForFocusedMonitor((mon, root) =>
<PopupWindow namespace={"runner"} monitor={mon} widthRequest={props.width}
heightRequest={props.height} exclusivity={Astal.Exclusivity.IGNORE} halign={Gtk.Align.CENTER}
marginTop={(AstalHyprland.get_default().get_monitor(mon)?.height / 2) - (props.height! / 2)}
valign={Gtk.Align.START} hexpand orientation={Gtk.Orientation.VERTICAL}
$={() => {
plugins.forEach(plugin =>
plugin.init?.());
props.initialText &&
Runner.setEntryText(props.initialText);
}} actionKeyPressed={(self, keyval) => {
const listbox = ((getPopupWindowContainer(self).get_last_child() as Gtk.ScrolledWindow)
.get_child() as Gtk.Viewport).get_child() as Gtk.ListBox;
switch(keyval) {
case Gdk.KEY_F5:
updateApps();
return;
case Gdk.KEY_Left:
case Gdk.KEY_Up:
selectPreviousItem(listbox);
gtkEntry?.grab_focus();
return;
case Gdk.KEY_Right:
case Gdk.KEY_Down:
selectNextItem(listbox);
gtkEntry?.grab_focus();
return;
}
for(const key of ignoredKeys) {
if(keyval === key)
return;
}
if(!gtkEntry?.hasFocus) {
gtkEntry?.grab_focus();
listbox.grab_focus();
}
}} actionClosed={() => {
[...plugins.values()].forEach(plugin => plugin?.onClose?.());
root.dispose();
instance = null;
gtkEntry = null;
}}>
<Gtk.Entry class={"search"} placeholderText={props.entryPlaceHolder ?? ""}
$={(self) => gtkEntry = self} onNotifyText={(self) => {
const listbox = ((self.get_next_sibling()! as Gtk.ScrolledWindow)
.get_child() as Gtk.Viewport).get_child() as Gtk.ListBox;
updateResultsList(listbox, self.text, props.resultsLimit, placeholders).then(() =>
listbox.get_row_at_index(0) &&
listbox.select_row(listbox.get_row_at_index(0))
);
}} primaryIconName={"system-search-symbolic"}
primaryIconTooltipText={"Search"}
secondaryIconName={"edit-clear-symbolic"}
secondaryIconTooltipText={"Clear search"}
onIconRelease={(self, iconPos) => {
if(iconPos === Gtk.EntryIconPosition.PRIMARY) {
self.notify("text"); // emit notify::text, so it will force-search again
return;
}
self.set_text("");
}} onActivate={(self) => {
const listbox = ((self.get_next_sibling() as Gtk.ScrolledWindow)
.get_child() as Gtk.Viewport).get_child() as Gtk.ListBox;
const resultWidget = listbox.get_selected_row()?.get_child();
if(resultWidget instanceof ResultWidget && !clickTimeout) {
clickTimeout = setTimeout(() => clickTimeout = undefined, 250);
resultWidget.actionClick();
resultWidget.closeOnClick &&
Runner.close();
}
}} onUnrealize={() => Runner.close()}
/>
<Gtk.ScrolledWindow class={"results-scrollable"} vscrollbarPolicy={Gtk.PolicyType.AUTOMATIC}
hscrollbarPolicy={Gtk.PolicyType.NEVER} hexpand vexpand propagateNaturalHeight visible={false}
maxContentHeight={props.height} focusable={false}>
<Gtk.ListBox hexpand activateOnSingleClick selectionMode={Gtk.SelectionMode.SINGLE}
onRowActivated={(_, row) => {
const child = row.get_child()!;
if(child instanceof ResultWidget && !clickTimeout) {
clickTimeout = setTimeout(() => clickTimeout = undefined, 250);
child.actionClick?.();
child.closeOnClick &&
Runner.close();
}
}}
/>
</Gtk.ScrolledWindow>
</PopupWindow> as Astal.Window
)();
return instance!;
}
}

View File

@@ -0,0 +1,18 @@
import { execApp, getAstalApps, lookupIcon, updateApps } from "../../modules/apps";
import { Runner } from "../Runner";
export const PluginApps = {
// Do not provide prefix, so it always runs.
name: "Apps",
// asynchronously-refresh apps list on init
init: async () => updateApps(),
handle: (text: string) => {
return getAstalApps().fuzzy_query(text).map(app => ({
title: app.get_name(),
description: app.get_description(),
icon: lookupIcon(app.iconName) ? app.iconName : "application-x-executable-symbolic",
actionClick: () => execApp(app)
})
);
}
} as Runner.Plugin;

View File

@@ -0,0 +1,62 @@
import { Gtk } from "ags/gtk4";
import { Clipboard, ClipboardItem } from "../../modules/clipboard";
import { Runner } from "../Runner";
import { jsx } from "ags/gtk4/jsx-runtime";
import Fuse from "fuse.js";
class _PluginClipboard implements Runner.Plugin {
#fuse!: Fuse<unknown>;
prefix = '>';
prioritize = true;
init() {
const items: ReadonlyArray<ClipboardItem> = [...Clipboard.getDefault().history];
this.#fuse = new Fuse(
items,
{
keys: [ "id", "preview" ] satisfies Array<keyof ClipboardItem>,
ignoreDiacritics: false,
isCaseSensitive: false,
shouldSort: true,
useExtendedSearch: false
}
);
}
private clipboardResult(item: ClipboardItem): Runner.Result {
return {
icon: jsx(Gtk.Label, {
label: `${item.id}`,
css: "font-size: 16px; margin-right: 8px; font-weight: 600;"
}),
title: item.preview,
actionClick: () => Clipboard.getDefault().selectItem(item).catch((err: Error) => {
console.error(`Runner(Plugin/Clipboard): An error occurred while selecting clipboard item. Stderr:\n${
err.message ? `${err.message}\n` : ""}Stack: ${err.stack}`
);
})
};
}
async handle(search: string, limit?: number) {
if(Clipboard.getDefault().history.length < 1)
return {
icon: "edit-paste-symbolic",
title: "Clipboard is empty",
description: "Copy something and it will be shown right here!"
};
if(search.trim().length === 0)
return Clipboard.getDefault().history.map(item =>
this.clipboardResult(item)
);
return this.#fuse.search(search, {
limit: limit ?? Infinity
}).map(result => this.clipboardResult(result.item as ClipboardItem))
}
}
export const PluginClipboard = new _PluginClipboard();

View File

@@ -0,0 +1,18 @@
import { PluginApps } from "./apps"
import { PluginClipboard } from "./clipboard"
import { PluginMedia } from "./media"
import { PluginShell } from "./shell"
import { PluginWallpapers } from "./wallpapers"
import { PluginWebSearch } from "./websearch"
import { PluginKill } from "./kill"
export {
PluginApps,
PluginWebSearch,
PluginClipboard,
PluginShell,
PluginMedia,
PluginWallpapers,
PluginKill
};

View File

@@ -0,0 +1,18 @@
import { execAsync } from "ags/process";
import { Runner } from "../Runner";
import { Notifications } from "../../modules/notifications";
export const PluginKill = {
prefix: ":k",
handle: () => ({
title: "Select a client to kill",
closeOnClick: true,
icon: "window-close-symbolic",
actionClick: () => execAsync("hyprctl kill").catch((e) =>
Notifications.getDefault().sendNotification({
summary: "Couldn't kill client",
body: `An error occurred while trying to kill a client! Stderr: ${e}`
})
)
} satisfies Runner.Result)
} satisfies Runner.Plugin;

View File

@@ -0,0 +1,99 @@
import { createBinding, createComputed } from "ags";
import { Runner } from "../Runner";
import { secureBaseBinding } from "../../modules/utils";
import { tr } from "../../i18n/intl";
import Media from "../../modules/media";
import AstalMpris from "gi://AstalMpris";
export const PluginMedia = {
prefix: ":",
handle: () => !Media.getDefault().player.available ? {
icon: "folder-music-symbolic",
title: "Couldn't find any players",
closeOnClick: false,
description: "No media / player found with mpris"
} : [
{
icon: secureBaseBinding<AstalMpris.Player>(
createBinding(Media.getDefault(), "player"),
"playbackStatus",
AstalMpris.PlaybackStatus.PAUSED
).as((status) => status === AstalMpris.PlaybackStatus.PLAYING ?
"media-playback-pause-symbolic"
: "media-playback-start-symbolic"),
closeOnClick: false,
title: createComputed([
secureBaseBinding<AstalMpris.Player>(
createBinding(Media.getDefault(), "player"),
"title",
null
).as(t => t ?? tr("media.no_title")),
secureBaseBinding<AstalMpris.Player>(
createBinding(Media.getDefault(), "player"),
"artist",
null
).as(t => t ?? tr("media.no_artist")),
secureBaseBinding<AstalMpris.Player>(
createBinding(Media.getDefault(), "player"),
"playbackStatus",
AstalMpris.PlaybackStatus.PAUSED
)
], (title, artist, status) => `${status === AstalMpris.PlaybackStatus.PLAYING ?
"Pause" : "Play"
} ${title} | ${artist}`),
actionClick: () => Media.getDefault().player.play_pause()
},
{
icon: "media-skip-backward-symbolic",
closeOnClick: false,
title: createComputed([
secureBaseBinding<AstalMpris.Player>(
createBinding(Media.getDefault(), "player"),
"title",
null
).as(t => t ?? tr("media.no_title")),
secureBaseBinding<AstalMpris.Player>(
createBinding(Media.getDefault(), "player"),
"artist",
null
).as(t => t ?? tr("media.no_artist")),
secureBaseBinding<AstalMpris.Player>(
createBinding(Media.getDefault(), "player"),
"identity",
"Music Player"
)
], (title, artist, identity) =>
`Go Previous ${title ? title : identity}${artist ? ` | ${artist}` : ""}`
),
actionClick: () => Media.getDefault().player.canGoPrevious &&
Media.getDefault().player.previous()
},
{
icon: "media-skip-forward-symbolic",
closeOnClick: false,
title: createComputed([
secureBaseBinding<AstalMpris.Player>(
createBinding(Media.getDefault(), "player"),
"title",
null
).as(t => t ?? tr("media.no_title")),
secureBaseBinding<AstalMpris.Player>(
createBinding(Media.getDefault(), "player"),
"artist",
null
).as(t => t ?? tr("media.no_artist")),
secureBaseBinding<AstalMpris.Player>(
createBinding(Media.getDefault(), "player"),
"identity",
"Music Player"
)
], (title, artist, identity) =>
`Go Next ${title ? title : identity}${artist ? ` | ${artist}` : ""}`
),
actionClick: () => Media.getDefault().player.canGoNext &&
Media.getDefault().player.next()
}
]
} as Runner.Plugin;

View File

@@ -0,0 +1,65 @@
import { Runner } from "../Runner";
import { Notifications } from "../../modules/notifications";
import GLib from "gi://GLib?version=2.0";
import Gio from "gi://Gio?version=2.0";
export const PluginShell = (() => {
const shell = GLib.getenv("SHELL") ?? "/bin/sh";
const procLauncher = Gio.SubprocessLauncher.new(
Gio.SubprocessFlags.STDOUT_PIPE | Gio.SubprocessFlags.STDERR_PIPE);
procLauncher.set_cwd(GLib.get_home_dir());
return {
prefix: '!',
prioritize: true,
handle: (input) => {
let showOutputNotif: boolean = false;
if(input.startsWith('!')) {
input = input.replace('!', "");
showOutputNotif = true;
}
const command = input ? GLib.shell_parse_argv(input) : undefined;
const shellSplit = shell.split('/'),
shellName = shellSplit[shellSplit.length-1];
return {
actionClick: () => {
if(!command?.[0] || !command[1]) return;
const proc = procLauncher.spawnv([ shell, "-c", `${input}` ]);
proc.communicate_utf8_async(null, null, (_, asyncResult) => {
const [ success, stdout, stderr ] = proc.communicate_utf8_finish(asyncResult);
if(!success || stderr) {
Notifications.getDefault().sendNotification({
appName: shell,
summary: "Command error",
body: `An error occurred on \`${input}\`. Stderr: ${stderr}`
});
return;
}
if(!showOutputNotif) return;
Notifications.getDefault().sendNotification({
appName: shell,
summary: "Command output",
body: stdout
});
});
},
title: `Run ${input ? ` \`${input}\`` : `with ${shellName}`}`,
description: input || showOutputNotif ? `${input ? `${shell}\t` : ""}${
showOutputNotif ? "(showing output on notification)" : "" }`
: "",
icon: "utilities-terminal-symbolic"
};
}
} as Runner.Plugin
})();

View File

@@ -0,0 +1,63 @@
import Fuse from "fuse.js";
import { Wallpaper } from "../../modules/wallpaper";
import { Runner } from "../Runner";
import Gio from "gi://Gio?version=2.0";
class _PluginWallpapers implements Runner.Plugin {
prefix = "#";
prioritize = true;
#fuse!: Fuse<string>;
#files!: Array<string>;
init() {
this.#files = [];
const dir = Gio.File.new_for_path(Wallpaper.getDefault().wallpapersPath);
if(dir.query_file_type(null, null) === Gio.FileType.DIRECTORY) {
for(const file of dir.enumerate_children(
"standard::*",
Gio.FileQueryInfoFlags.NOFOLLOW_SYMLINKS,
null
)) {
this.#files.push(`${dir.get_path()}/${file.get_name()}`);
}
}
this.#fuse = new Fuse<string>(
this.#files as ReadonlyArray<string>,
{
useExtendedSearch: false,
shouldSort: true,
isCaseSensitive: false
}
);
}
private wallpaperResult(path: string): Runner.Result {
return {
title: path.split('/')[path.split('/').length-1].replace(/\..*$/, ""),
actionClick: () => Wallpaper.getDefault().setWallpaper(path)
};
}
handle(search: string, limit?: number) {
if(search.trim().length === 0)
return this.#files.map(path =>
this.wallpaperResult(path)
);
if(this.#files.length > 0)
return this.#fuse.search(search, {
limit: limit ?? Infinity
}).map(result => this.wallpaperResult(result.item));
return {
title: "No wallpapers found!",
description: "Define the $WALLPAPERS variable on Hyprland or create a ~/wallpapers directory",
icon: "image-missing-symbolic"
};
}
}
export const PluginWallpapers = new _PluginWallpapers();

View File

@@ -0,0 +1,27 @@
import AstalHyprland from "gi://AstalHyprland";
import { Runner } from "../Runner";
const searchEngines = {
duckduckgo: "https://duckduckgo.com/?q=",
google: "https://google.com/search?q=",
yahoo: "https://search.yahoo.com/search?p="
};
let engine: string = searchEngines.google;
export const PluginWebSearch = {
prefix: '?',
name: "Web Search",
prioritize: true,
handle: (search) => ({
icon: "system-search-symbolic",
title: search || "Type your search...",
description: `Search the Web`,
actionClick: () => AstalHyprland.get_default().dispatch(
"exec",
`xdg-open \"${engine + search}\"`
)
})
} as Runner.Plugin;

View File

@@ -0,0 +1,119 @@
import { getter, gtype, property, register, setter } from "ags/gobject";
import { Gtk } from "ags/gtk4";
import { variableToBoolean } from "../../modules/utils";
import Pango from "gi://Pango?version=1.0";
import GdkPixbuf from "gi://GdkPixbuf?version=2.0";
export type ResultWidgetProps = {
icon?: string | GdkPixbuf.Pixbuf | Gtk.Widget | JSX.Element;
title: string;
description?: string;
closeOnClick?: boolean;
setup?: () => void;
actionClick?: () => void;
visible?: boolean;
};
@register({ GTypeName: "ResultWidget" })
export class ResultWidget extends Gtk.Box {
#icon: string|Gtk.Widget|GdkPixbuf.Pixbuf|null = null;
public readonly actionClick: () => void;
public readonly setup?: () => void;
@property(Boolean)
closeOnClick: boolean = true;
@getter(gtype<string|Gtk.Widget|GdkPixbuf.Pixbuf|null>(Object))
get icon() { return this.#icon; }
@setter(gtype<string|Gtk.Widget|GdkPixbuf.Pixbuf|null>(Object))
set icon(newIcon: string|Gtk.Widget|GdkPixbuf.Pixbuf|null) {
this.set_icon(newIcon);
}
constructor(props: ResultWidgetProps & Partial<Gtk.Box.ConstructorProps>) {
super();
this.add_css_class("result");
this.visible = props.visible ?? true;
this.hexpand = true;
this.setup = props.setup;
this.closeOnClick = props.closeOnClick ?? true;
this.actionClick = () => props.actionClick?.();
this.append(<Gtk.Box orientation={Gtk.Orientation.VERTICAL} valign={Gtk.Align.CENTER}>
<Gtk.Label class={"title"} xalign={0} ellipsize={Pango.EllipsizeMode.END}
label={props.title} />
<Gtk.Label class={"description"} visible={variableToBoolean(props.description)}
ellipsize={Pango.EllipsizeMode.END} xalign={0} label={props.description ?? ""} />
</Gtk.Box> as Gtk.Box);
if(props.icon !== undefined)
this.set_icon(props.icon as Gtk.Widget|string|GdkPixbuf.Pixbuf);
}
/** it is recommended to not change the custom widget's name. */
set_icon(icon: string|Gtk.Widget|GdkPixbuf.Pixbuf|null): void {
const firstChild = this.get_first_child();
if(icon === null && firstChild?.name !== undefined &&
/^(custom\-)?icon\-widget$/.test(firstChild?.name)) {
this.remove(firstChild);
return;
}
if(firstChild && firstChild.name === "icon-widget" &&
firstChild instanceof Gtk.Image) {
if(typeof icon === "string") {
firstChild.set_from_icon_name(icon);
this.#icon = icon;
this.notify("icon");
return;
}
if(icon instanceof GdkPixbuf.Pixbuf) {
firstChild.set_from_pixbuf(icon);
this.#icon = icon;
this.notify("icon");
return;
}
// remove if we're not going to use it
this.remove(firstChild);
}
if(icon instanceof Gtk.Widget) {
if(firstChild?.name === "custom-icon-widget")
this.remove(firstChild);
this.prepend(icon);
this.#icon = this.get_first_child();
this.notify("icon");
return;
}
this.prepend(
<Gtk.Image name={"icon-widget"} $={(self) => {
if(typeof icon === "string") {
self.set_from_icon_name(icon);
this.#icon = icon;
this.notify("icon");
return;
}
self.set_from_pixbuf(icon);
this.#icon = icon;
this.notify("icon");
}} /> as Gtk.Image
);
}
}