# GTKX 2.0 beta 14
> The React framework for Linux. Build native Adwaita and GTK apps with the workflow of modern web development.
@doc-version: 2.0
@doc-status: prerelease
GTKX 2.0 beta 14 is a pre-release. The current release is GTKX 1.6 stable, documented at https://gtkx.dev/llms.txt.
gtkx.dev documents the current release, the release it replaced, and any pre-release in progress. Promoting a pre-release retires the older of the two published releases, so no more than one superseded release is ever online.
## GTKX 2.0 beta 14 documentation
---
title: "Why GTKX"
description: "Why GTKX exists: React, Fast Refresh, native UI tests, and packaging for GTK and Adwaita apps on Linux."
---
# Why GTKX
In a typical GTK application, code creates the widget tree and then keeps each widget in step with application state by hand: every change in state means finding the affected widgets and calling their setters. Web development moved past this years ago. Declarative components, a dev server with Fast Refresh, tests that query the interface the way a user sees it, and one-command builds are standard there, along with the React and npm ecosystems built around them.
GTKX brings that workflow to native GTK and Adwaita apps. You describe the interface in JSX; GTKX renders real Adwaita and GTK widgets, and React updates them when state changes.
## Why Node.js
GTKX runs your app on Node.js. Node owns the process, and GTKX drives GLib's main loop, which GTK uses for input, drawing, and timers, from Node's event loop on the main thread. Your app is an ordinary Node program, so it can use Node's standard library and npm packages, and GTKX's development and test tooling builds on Vite and Vitest. GLib and Gio bindings cover platform APIs such as settings, actions, and notifications.
## Platform scope
GTKX targets one platform, GTK and Adwaita on Linux, rather than abstracting over several. Your app uses the native libraries' own APIs, not a cross-platform subset of them. GTKX does not provide a Windows, macOS, mobile, or browser renderer. [Comparisons](/v2/guide/comparisons) describes how GTKX differs from GJS, node-gtk, React Native, gtk4-rs and Relm4, and Electron and Tauri.
GTKX generates TypeScript bindings from the native libraries installed for your project. Those bindings describe the available classes, methods, and JSX props. Shipping an app still requires compatible native libraries; see [Deploying](/v2/guide/deploying).
Components render native widgets, so web UI libraries that expect HTML, the DOM, or browser CSS need to be replaced or adapted. React hooks and libraries that work independently of a renderer can be reused. GTK styles use [GTK CSS](/v2/guide/css), whose properties and layout differ from the web.
## Development tools
`npm run dev` opens your app, and Fast Refresh updates the open window as you save while preserving component state. [Tests](/v2/guide/testing) run in Vitest, find widgets by role and name, and click and type into the real native interface on a private headless display. `npm run deploy` builds Flatpak, Debian, RPM, and AppImage packages from your configuration; see [Deploying](/v2/guide/deploying). Coding agents can inspect and drive the running app through the [MCP server](/v2/guide/mcp).
Libraries cover common app structure: [navigation](/v2/guide/navigation) maps React Navigation to native page stacks, tabs, drawers, and split views; [components](/v2/guide/components) render collections and notifications; and [forms](/v2/guide/forms) connect native controls to React Hook Form.
## Credits
GTKX builds on [React](https://react.dev), [Vite](https://vite.dev), [Vitest](https://vitest.dev), [napi-rs](https://napi.rs), and [React Navigation](https://reactnavigation.org). Its GObject APIs follow the names and conventions of [GJS](https://gjs.guide).
---
---
title: "Comparisons"
description: "How GTKX compares with GJS, node-gtk, React Native, gtk4-rs and Relm4, and Electron and Tauri for building desktop apps."
---
# Comparisons
Several projects build GTK and Adwaita apps, or desktop apps with React and web technologies. This page describes how each one differs from GTKX in design and scope, and when it is the better fit.
## GJS
[GJS](https://gjs.guide) is GNOME's JavaScript runtime. It embeds Firefox's SpiderMonkey engine, and GNOME Shell and many GNOME apps are written with it. Your JavaScript runs inside GLib's main loop, in a runtime that implements neither the Node.js APIs nor most Web APIs. npm packages that depend on those APIs, and tools that run on Node.js such as Vitest, don't work with a GJS app.
GTKX reverses that arrangement: Node.js owns the process, and GLib's main loop runs inside it (see [Why Node.js](/v2/guide/why-gtkx#why-node-js)). The app is an ordinary Node.js program, so it can use npm packages, Vite and Vitest. GTKX's GObject APIs follow GJS's names and conventions, so knowledge of GJS carries over.
GJS is the better fit for [GNOME Shell extensions](https://gjs.guide/extensions/), which run inside GNOME Shell's own GJS, and for apps that should use the runtime GNOME already provides: a GJS app's Flatpak takes GJS from the GNOME runtime, while a GTKX package includes Node.js.
## node-gtk
[node-gtk](https://github.com/romgrk/node-gtk) also runs GTK inside a Node.js process, through GObject Introspection bindings. Its API is imperative: code creates widgets and calls their methods to keep them in step with state. It is built on Nan rather than [Node-API](https://nodejs.org/api/n-api.html), the interface that lets an addon compiled for one Node.js major version run on later ones without recompiling, and it generates TypeScript declarations on request. It also ships a project scaffolder, CSS hot reloading and Flatpak bundling.
GTKX renders declarative React components, and its native addon is written in Rust on Node-API. It is TypeScript-first: [codegen](/v2/guide/configuration-and-codegen) generates typed bindings and JSX props for the libraries your project uses.
## React Native
[React Native](https://reactnative.dev) builds native apps with React. Its core targets Android and iOS, and separately maintained [out-of-tree platforms](https://reactnative.dev/docs/out-of-tree-platforms) add others such as macOS and Windows; none of them renders GTK or Adwaita. Its components abstract over the differences between platforms, which makes it the better fit when one codebase must run on several of them.
GTKX targets one platform and exposes all of it: every GTK and Adwaita widget and API the installed libraries provide, under its native name. Readers who know React Native will recognize [navigation](/v2/guide/navigation), which maps React Navigation to Adwaita page stacks, tabs, drawers and split views.
## gtk4-rs and Relm4
[gtk4-rs](https://gtk-rs.org/gtk4-rs/) is the Rust binding for GTK 4. Code builds and updates widgets imperatively, or loads them from UI templates. [Relm4](https://relm4.org) builds on gtk4-rs with an Elm-inspired component model and a `view!` macro that declares the UI. Both suit apps written in Rust. Neither provides hot reloading, a dev server or UI test automation; gtk4-rs's `#[gtk::test]` attribute runs a test on the GTK main thread, and driving the interface is left to the test.
GTKX includes those tools along with React: a dev server with Fast Refresh, [tests](/v2/guide/testing) that find widgets by role and name and click and type into the real interface on a headless display, and [packaging](/v2/guide/deploying) for Flatpak, Debian, RPM and AppImage.
## Electron and Tauri
[Electron](https://www.electronjs.org) and [Tauri](https://tauri.app) build desktop apps whose interface is a web page written in HTML, CSS and JavaScript. Electron bundles Chromium and Node.js into each app. Tauri renders in the operating system's webview, WebKitGTK on Linux, and runs backend logic in Rust. Both build for Windows, macOS and Linux from one codebase, and Tauri also builds for Android and iOS.
GTKX renders native GTK and Adwaita widgets instead of a web page, so an app gets the platform's look, accessibility and desktop integration, on Linux only. Its React components create widgets rather than DOM elements, so UI libraries that render to the DOM don't apply.
Electron and Tauri are the better fit when one web codebase must run on several desktop platforms, or when the interface reuses DOM UI libraries.
---
---
title: "Getting Started"
description: "Install the prerequisites, create a GTKX app, and run the development loop."
---
# Getting Started
Create a Linux desktop app with React and TypeScript, then edit it while its window stays open. This guide uses the [GTKX 2.0 beta](/releases#prereleases).
## What you need
GTKX requires Linux, Node.js 26.7 or later, GTK 4.20 or later, libadwaita 1.8 or later, and GLib development files. Prebuilt GTKX binaries support x64 and arm64 Linux with glibc.
Install [Node.js](https://nodejs.org/en/download) with your preferred version manager, then check the version in the terminal you will use for development:
```bash
node --version
```
### Native libraries
Install the development packages, which supply both native libraries and the GIR files used to generate bindings:
::: code-group
```bash [Fedora 44]
sudo dnf install gtk4-devel libadwaita-devel glib2-devel \
gobject-introspection-devel pkgconf-pkg-config
```
```bash [Ubuntu 26.04]
sudo apt install libgtk-4-dev libadwaita-1-dev libglib2.0-dev \
libgirepository1.0-dev pkgconf
```
```bash [Arch Linux]
sudo pacman -S --needed gtk4 libadwaita glib2 gobject-introspection pkgconf
```
:::
Check the installed versions:
```bash
pkg-config --modversion gtk4 libadwaita-1 glib-2.0
```
Other distributions need equivalent development packages; [GTK's Linux installation guide](https://www.gtk.org/docs/installations/linux) lists their names. A runtime-only package is insufficient for code generation.
::: tip Older distributions
Debian 13 and Ubuntu 24.04 ship GTK and libadwaita releases older than the minimums. Run the Fedora command inside a [Toolbx](https://containertoolbx.org/) or [Distrobox](https://distrobox.it/) container, which shares your desktop session with the app.
:::
Run the app from a graphical desktop session. In a development container, the container also needs access to the session's display and D-Bus; installing libraries alone does not provide that connection.
## Scaffolding a new app
::: code-group
```bash [pnpm]
pnpm create gtkx@beta
```
```bash [npm]
npm create gtkx@beta
```
```bash [yarn]
yarn create gtkx@beta
```
:::
The scaffolder asks for a project directory, a display name, an application ID such as `com.example.MyApp`, and a package manager, then whether to use TypeScript and include the Vitest setup. It preselects the package manager that ran it and recommends pnpm. Keep TypeScript and Vitest for typed components and native widget tests.
The directory can be a path, such as `~/Projects/my-app`, and any name works. `Unit Converter` gets the display name Unit Converter; because it is not a valid package name, the scaffolder also asks for one and suggests `unit-converter`.
The `yarn` command needs Yarn 2 or later. Yarn 1 cannot run the prerelease scaffolder; with Yarn 1, start the project with npm or pnpm and choose Yarn as the package manager. Yarn projects get `nodeLinker: node-modules` in `.yarnrc.yml`, because GTKX generates its bindings into `node_modules` and does not support Plug'n'Play.
Start the app:
```bash
cd my-app
npm run dev
```
The starter uses an Adwaita application window with a counter. Click the button to increase the count. Change its label in `src/app.tsx` and save; the open window should update.
The starter window, captured from the src/app.tsx below with the display name My App.
::: details The starter `src/app.tsx`
```tsx [src/app.tsx]
import * as Gtk from "@gtkx/gi/gtk";
import {
AdwApplication,
AdwApplicationWindow,
AdwHeaderBar,
AdwToolbarView,
} from "@gtkx/jsx/adw";
import { GtkBox, GtkButton, GtkLabel } from "@gtkx/jsx/gtk";
import { quit } from "@gtkx/react";
import { useState } from "react";
const MainWindow = () => {
const [count, setCount] = useState(0);
return (
}>
Welcome to GTKX!
Count: {count} setCount((c) => c + 1)}
cssClasses={["suggested-action", "pill"]}
/>
);
};
export const App = () => (
);
export default App;
```
:::
For noninteractive creation and existing directories, see [Scaffold Options](/v2/guide/scaffold-options).
The [tutorial](/v2/tutorial/) follows development on `main` and may use APIs added after the published beta. Check its version prerequisites before continuing beyond this starter.
## The dev loop
`npm run dev` runs `gtkx dev`, which opens the app and watches your source files. Fast Refresh applies most edits to the open window and keeps its state; some edits [restart the app](/v2/guide/troubleshooting#the-app-restarts-instead-of-refreshing) instead.
| Command | Result |
| ---------------- | ------------------------------------------------------------------- |
| `npm run dev` | Run the app and watch source files |
| `npm run build` | Bundle the app into `dist/bundle.mjs` |
| `npm start` | Run that production bundle with Node.js |
| `npm run deploy` | Build a distributable package; see [Deploying](/v2/guide/deploying) |
With pnpm, run the last one as `pnpm run deploy`, because `pnpm deploy` is pnpm's built-in command.
The production bundle still needs the native runtime libraries. Packaging can supply a Node.js runtime and desktop integration files.
## Project structure
```text
my-app/
├─ gtkx.config.ts
├─ package.json
├─ tsconfig.json
├─ vitest.config.ts
├─ data/
│ └─ icons/
├─ src/
│ ├─ index.tsx
│ ├─ app.tsx
│ └─ gtkx-env.d.ts
└─ tests/
└─ app.test.tsx
```
`gtkx.config.ts` holds the application ID, the icon directory and packaging metadata; [Configuration and Codegen](/v2/guide/configuration-and-codegen) covers its other options. `data/icons/` holds the app icon. The component lives in `src/app.tsx`; `src/index.tsx` renders it. Without TypeScript, the source files end in `.jsx` and `.js` and there is no `tsconfig.json` or `src/gtkx-env.d.ts`; without Vitest, there is no `vitest.config.ts` or `tests/`.
## The entry point: `src/index.tsx`
Create a React root and render your application. GTKX supplies the native root container, so `createRoot()` takes no DOM element:
```tsx
import { createRoot } from "@gtkx/react";
import { App } from "./app.js";
createRoot().render();
```
The starter's `` gets its application ID from `gtkx.config.ts`. [The application element](/v2/guide/application-lifecycle#the-application-element) explains the application, its windows and when the app ends.
## Updating GTKX
Run `npx gtkx upgrade` to move every GTKX package in the project to the newest release on the dist-tag it follows. [Updating GTKX](/v2/guide/updating) describes what it changes.
## Troubleshooting
[Troubleshooting](/v2/guide/troubleshooting) covers missing GIR files, display connections, release-age gates, and edits that restart the app.
## Next
- [Tutorial](/v2/tutorial/): build Notes, a Markdown notes app with file watching, search, tests, and packaging.
- [JSX Elements](/v2/guide/jsx-elements): how elements map props, signals and child slots to the native API.
- [Examples](https://github.com/gtkx-org/gtkx/tree/main/examples): complete apps, from Hello World to the GTK and Adwaita demos, run from the GTKX repository.
- [Discussions](https://github.com/gtkx-org/gtkx/discussions): ask questions and share what you build.
---
---
title: "JSX Elements"
description: "How GTKX JSX elements map props, signals, notifications, child slots and refs to the native API."
---
# JSX Elements
Codegen generates a JSX element for each GObject class in the configured libraries, named after its GLib type, such as `` or ``. This page describes how element props map to the native API. [Components](/v2/guide/components) covers the higher-level components built on them.
## The JSX prop model
Generated elements follow the native API with GTKX naming conventions. This header bar toggles a search entry:
```tsx
import type * as Gtk from "@gtkx/gi/gtk";
import { AdwHeaderBar, AdwToolbarView } from "@gtkx/jsx/adw";
import { GtkButton, GtkSearchEntry, GtkToggleButton } from "@gtkx/jsx/gtk";
import { useRef, useState } from "react";
export const SearchPane = () => {
const [searching, setSearching] = useState(false);
const entry = useRef(null);
return (
setSearching(active)}
/>
}
end={
entry.current?.grabFocus()}
/>
}
/>
}
>
console.log(self.getText())}
/>
);
};
```
- Properties use camelCase, such as `showTitleButtons`.
- Signals use handler props, such as `onClicked`. GTKX passes the emitting object after the signal arguments.
- Property notifications use `onNotifyX`, receiving the new value and the emitting object.
- Object properties that accept elements can be expressed as JSX, with GTKX managing their lifetime. This includes construct-only ones, such as `userContentManager={}` on a `WebKitWebView`: GTKX builds the prop's element first and passes its object when it constructs the parent, so the element must stay the same while the parent is mounted.
- Elements that show one child, such as `GtkScrolledWindow`, `AdwClamp`, window content or `AdwToolbarView` content, show the last one passed. Development builds warn when such an element holds more than one visible child; wrap them in a `GtkBox`.
- Child slots that no property backs are props named after their GtkBuilder child type, such as `start` and `end` on a header bar or `top` and `bottom` on a toolbar view.
- Refs expose the corresponding GI instance for imperative APIs.
A `text` prop on an editable widget, such as `GtkEntry`, or on a text buffer is written only when it differs from the widget's current text.
Handlers don't report what GTKX writes for you. Writing a prop doesn't call that property's `onNotifyX` handler, and signal handlers such as `onChanged`, `onRowSelected` or `onClosePage` stay quiet while a commit changes props or children.
Properties the widget changes in reaction still notify. When adding or removing children changes a property, such as the selected page after the selected tab is removed, its `onNotifyX` handler runs once the commit and its layout effects have finished, with the value at that point. The handler doesn't run when:
- The commit writes that property itself, as a controlled `visibleChildName` does.
- The property ends at the value its prop asks for, as a `GtkDropDown`'s `selected={0}` does once its model is placed.
- The property ends at the value it had before the children changed.
A prop the element does not have, such as a typo, a C-style name like `margin_top` or a prop from another toolkit, throws an error that names the element and, where it can, the closest prop it does have.
Create objects and place children with JSX rather than through refs, so GTKX manages their lifetime. The [generated element reference](/v2/guide/configuration-and-codegen#generating-element-reference-docs) shows the exact props, slots, and signals for each configured library.
### Member names
Native methods keep their generated camelCase names, even when a name overlaps a GTKX signal or property helper. For example, `Gio.Socket.connect` connects the socket; use `GObject.signalConnect` to connect one of its signals. When a method has the same name as a property, read and write the property with `GObject.getProperty` and `GObject.setProperty` from `@gtkx/gi/gobject`. Both take the camelCase property name and type the value from the object's properties.
---
---
title: "Application Lifecycle"
description: "Start the application from the entry point, know when it ends, end pending work, handle termination signals and the command line, and run an application without React."
---
# Application Lifecycle
A GTKX app is a GTK application that React renders: the application element starts it, its windows keep it running, and it ends when they are gone. An app should also leave no work running when it quits, save its data when it receives `SIGTERM`, and answer when it is launched again from the command line. GTKX handles part of each; this page covers what your code does.
## The application element
The entry point renders the app into a root:
```tsx [src/index.tsx]
import { createRoot } from "@gtkx/react";
import { App } from "./app.js";
createRoot().render();
```
`createRoot()` without a container renders at the top level, where the application element goes. The application element is `AdwApplication`, or the element of any other `Gtk.Application` class, such as `GtkApplication`:
```tsx [src/app.tsx]
import { AdwApplication, AdwApplicationWindow } from "@gtkx/jsx/adw";
import { quit } from "@gtkx/react";
export const App = () => (
);
```
When it mounts, the application element creates the application and runs it with the process's command-line arguments. Its `applicationId` defaults to the one in [`gtkx.config.ts`](/v2/guide/configuration-and-codegen#the-config-file), including a `$development` override under `gtkx dev`. Its children render once the application activates, so the windows among them become the application's windows, and they unmount when it shuts down. [`useApplication()`](/v2/guide/native-state#the-application) returns the application to any component inside. When the run ends with a nonzero status, GTKX sets it as the process's exit code.
The application ID makes the app single-instance. A second launch hands its arguments to the running instance and exits without rendering, and the running instance receives `activate` again. Present its window there, or the second launch appears to do nothing:
```tsx [src/app.tsx]
import { AdwApplication, AdwApplicationWindow } from "@gtkx/jsx/adw";
import { quit } from "@gtkx/react";
export const App = () => (
application.getActiveWindow()?.present()}
>
);
```
### When the app ends
A GTK application runs while it has a window or a [`hold()`](https://docs.gtk.org/gio/method.Application.hold.html). GTKX holds the application until its first activated render commits, then releases it, so:
- Closing the last window ends the app. A window without an `onCloseRequest` handler closes when the user closes it.
- `quit()` from `@gtkx/react` unmounts every root and quits each application it unmounts, even one that holds itself. It returns `Gdk.EVENT_STOP`, so it can be the main window's `onCloseRequest` handler.
- A first render that shows no window ends the app at once, and `gtkx dev` reports `Application quit`. An app that waits for saved data before rendering anything quits before the data arrives. Render the window first and show a placeholder inside it; see [Restoring state](/v2/guide/navigation#restoring-state) for React Navigation's state persistence.
- `root.unmount()` and `root.render(null)` remove the windows. The application then ends unless something holds it.
To keep a windowless app running for background work, call `hold()` on the application and `release()` when the work finishes. Each `hold()` needs one `release()`; an extra `release()` throws a `RangeError`.
## Ending work on unmount
When the application quits, GTKX unmounts the tree, and the Node process exits once its event loop has no work left. A pending `fetch` or a running timer keeps the process alive after its window has closed. Abort requests and clear timers in the cleanup of the effect that started them, and start timers in effects rather than at module level:
```tsx
import { useEffect, useState } from "react";
export const useFeed = (url: string, intervalMs: number): string | null => {
const [body, setBody] = useState(null);
useEffect(() => {
const controller = new AbortController();
const refresh = (): void => {
fetch(url, { signal: controller.signal })
.then((response) => response.text())
.then(setBody)
.catch((error: unknown) => {
if (!controller.signal.aborted) console.error(error);
});
};
refresh();
const timer = setInterval(refresh, intervalMs);
return () => {
clearInterval(timer);
controller.abort();
};
}, [url, intervalMs]);
return body;
};
```
`gtkx dev` waits a few seconds after the application quits. If the process is still running then, it prints a warning naming the kinds of pending work, such as `Timeout` for a timer or `TCPSocketWrap` for an open connection, and stops. Run the built bundle to see the same work keep a production process alive.
## Handling termination signals
Listen for `SIGINT` and `SIGTERM` with Node's [`process.on`](https://nodejs.org/api/process.html#signal-events), not `GLibUnix.signalAdd`. GTKX quits the application on `SIGINT`, `SIGTERM` and `SIGHUP` while no other listener handles the signal. A listener you add takes over, so finish your cleanup and call `quit()`:
```tsx
import { quit } from "@gtkx/react";
import { useEffect } from "react";
export const useQuitOnSignals = (save: () => void): void => {
useEffect(() => {
const handleSignal = (): void => {
save();
quit();
};
process.on("SIGINT", handleSignal);
process.on("SIGTERM", handleSignal);
return () => {
process.off("SIGINT", handleSignal);
process.off("SIGTERM", handleSignal);
};
}, [save]);
};
```
When the last `GLibUnix.signalAdd` source for a signal is removed, for example on unmount or after a Fast Refresh, GLib resets that signal to its default action. That silently disables GTKX's exit handling and every `process.on` listener, although Node still lists them. The next `SIGTERM` then ends the process without cleanup, and a Vitest worker ends without releasing its headless display.
## Command-line apps
With `Gio.ApplicationFlags.HANDLES_COMMAND_LINE`, every launch's arguments reach the primary instance through the [`command-line`](https://docs.gtk.org/gio/signal.Application.command-line.html) signal instead of `activate`, including the first launch. GTKX renders the application's children once the application is activated or opened, so the handler calls `application.activate()` to show the window.
A second launch waits for the primary instance's reply. GLib sends it when the `Gio.ApplicationCommandLine` is finalized or its [`done()`](https://docs.gtk.org/gio/method.ApplicationCommandLine.done.html) method is called. GTKX finalizes it only after JavaScript garbage-collects the wrapper, so without `done()` the second launch can wait for minutes. Set the exit status before calling `done()`, because `done()` freezes it before GLib applies the handler's return value:
```tsx
import * as Gio from "@gtkx/gi/gio";
import { AdwApplication, AdwApplicationWindow } from "@gtkx/jsx/adw";
import { quit } from "@gtkx/react";
const handleCommandLine = (
commandLine: Gio.ApplicationCommandLine,
application: Gio.Application,
): number => {
application.activate();
commandLine.setExitStatus(0);
commandLine.done();
return 0;
};
export const App = () => (
);
```
A handler that answers after asynchronous work calls `setExitStatus` and `done()` when that work completes.
The `mainOptions` prop declares the options the application accepts. GLib parses them in the launching process and lists them in `--help`. The `onHandleLocalOptions` handler reads them there, before the launch reaches the primary instance, and returns `-1` to continue the launch or an exit status to end it. With `HANDLES_COMMAND_LINE`, the `command-line` handler reads them from `commandLine.getOptionsDict()`. The list can't change once the application has started, and a render with a different list throws, so define it outside the component:
```tsx [src/app.tsx]
import * as GLib from "@gtkx/gi/glib";
import { AdwApplication, AdwApplicationWindow } from "@gtkx/jsx/adw";
import { quit } from "@gtkx/react";
const mainOptions = [
{
longName: "list",
shortName: "l",
description: "Print the task list and exit",
},
];
const handleLocalOptions = (options: GLib.VariantDict): number => {
if (!options.contains("list")) return -1;
console.log("No tasks");
return 0;
};
export const App = () => (
);
```
An option that takes a value sets `arg`, such as `GLib.OptionArg.STRING`, and names the value in `--help` with `argDescription`. Read it with `options.lookupValue("name", null)?.getString()[0]`. GLib's [`add_main_option_entries`](https://docs.gtk.org/gio/method.Application.add_main_option_entries.html) documents the option fields and when each handler sees them.
During development, `gtkx dev` passes the arguments after `--` to the application, so `gtkx dev -- notes.txt` starts an app with `HANDLES_OPEN` on that file. pnpm and Yarn 2 or newer pass `--` on to the `dev` script, as in `pnpm dev -- notes.txt`; npm removes the first `--`, so write `npm run dev -- -- notes.txt`. An option before `--` must be one `gtkx dev` defines: `gtkx dev --verbose` stops with an error naming `--verbose` rather than starting the app, so application options always go after `--`.
A GTKX app needs a display even for `--help` and other options that exit before a window opens. The generated `@gtkx/gi/gtk` and `@gtkx/gi/adw` modules initialize GTK when they are imported, before the application parses its command line, so without a Wayland or X11 display the process prints `Failed to open display` and exits with status 1. Run command-line checks of a packaged app, such as a smoke test in a container or CI, inside a desktop session or a virtual display such as `xvfb-run`.
GTKX sets the program name to the last segment of the production application ID before the entry module runs, as GJS does before an app's code. `--help` prints it as the usage line, and GTK's X11 backend uses it as the window class, even when a library such as GStreamer initializes while the app's modules load. A development ID such as `$development: { applicationId: "com.example.Tasks.Devel" }` keeps the name `Tasks` under `gtkx dev`. To choose another name, call `GLib.setPrgname()` before the application starts.
## Running without React
An app that uses the generated bindings without React constructs its application and runs it with `runAsync()`, as a GJS app calls `run()`:
```ts [src/index.ts]
import * as Gtk from "@gtkx/gi/gtk";
import process from "node:process";
const application = new Gtk.Application({
applicationId: "com.example.Notes",
});
application.on("activate", () => {
const window =
application.getActiveWindow() ??
new Gtk.ApplicationWindow({ application, title: "Notes" });
window.present();
});
process.exitCode = await application.runAsync([
"notes",
...process.argv.slice(2),
]);
```
`runAsync()` takes the command line, starting with the program name, or `null` for none. It parses GLib's options, registers the application, and activates it or hands the launch to the running instance. Node keeps running its event loop the whole time, so timers, `fetch` and `await` work as usual. The returned promise resolves with the exit status once the run has ended, and rejects if startup or shutdown throws.
A primary instance runs while it has application windows or JavaScript `hold()` calls without a matching `release()`. Holds that native code takes don't count:
- With neither, the run ends right after the current JavaScript turn. Create the window or call `hold()` in the `activate` handler itself, not after an `await`.
- After the last window closes or the last `release()`, the run waits `inactivityTimeout` milliseconds (none by default), then ends. An application with `Gio.ApplicationFlags.IS_SERVICE` also waits up to ten seconds for its first use.
- `application.quit()` ends the run even while windows or holds remain. It doesn't release the holds: each `hold()` still needs its `release()`.
A launch that ends in the launching process, such as `--help`, and a launch handed to a running instance resolve at once. The application stays the process's default application until you call `application.quit()`.
A second `runAsync()` while a run is active rejects. GLib shuts an application down fully only once, so create a new application for each complete run.
## Keeping a helper process alive
Application elements manage the GLib lifecycle automatically. A standalone Node helper needs an explicit hold while native work is pending; see [helper processes](/v2/guide/workers#keeping-a-helper-process-alive).
---
---
title: "Modals and Portals"
description: "Render windows, Adwaita dialogs, and objects outside their surrounding container."
---
# Modals and Portals
Windows and Adwaita dialogs are JSX elements: rendering one opens it, and the app closes it by no longer rendering it. GTKX places them natively, outside the widget tree they are declared in. Use `createPortal` for other objects that belong outside their surrounding container.
## Windows
Window elements present themselves on mount and destroy the native window on unmount. Render a secondary window conditionally, and handle `onCloseRequest` by clearing the state that rendered it:
```tsx
import {
AdwApplicationWindow,
AdwHeaderBar,
AdwToolbarView,
} from "@gtkx/jsx/adw";
const MirrorWindow = ({
open,
onClose,
}: {
open: boolean;
onClose: () => void;
}) =>
open ? (
{
onClose();
return true;
}}
>
} />
) : null;
```
Returning `true` keeps the window until React unmounts it.
A window that should keep its state while hidden, such as one with `hideOnClose`, can stay mounted and pass `visible` instead, setting it to `false` from `onCloseRequest`. Mounted with `visible={false}`, it stays hidden until `visible` becomes `true`.
`AdwApplicationWindow` registers with its nearest application element, normally `AdwApplication`, and throws without one. To associate it with another window, pass `transientFor` explicitly.
Plain `AdwWindow` and `GtkWindow` elements default `transientFor` to their nearest window ancestor. An explicit value selects another parent; `null` keeps the window independent.
## Dialogs
Adwaita dialog elements present on mount over their nearest window and close on unmount. Handle `onClosed` by clearing the state that rendered the dialog:
```tsx
import { AdwDialog } from "@gtkx/jsx/adw";
import { GtkLabel } from "@gtkx/jsx/gtk";
const Notice = ({ onClose }: { onClose: () => void }) => (
Nothing to report.
);
```
Specialized dialogs keep the same lifecycle. Place their content in the supported JSX slots; for example, `AdwPreferencesDialog` takes `AdwPreferencesPage` children.
Without `onClosed`, the close button and Escape do nothing and the dialog stays open, as described in [Closing](#closing). To confirm before closing, for example when there are unsaved changes, set `canClose={false}` and handle `onCloseAttempt`, then stop rendering the dialog once the user confirms. Unmounting always closes the dialog.
`AdwAlertDialog` takes plain-text `heading` and `body` values and a `responses` array. Its `onResponse` prop receives the selected response ID and also answers the close request. Children appear between the body and the response buttons:
```tsx [src/components/rename-dialog.tsx]
import * as Adw from "@gtkx/gi/adw";
import { AdwAlertDialog } from "@gtkx/jsx/adw";
import { GtkEntry } from "@gtkx/jsx/gtk";
export function RenameDialog({
onResponse,
}: {
onResponse: (id: string) => void;
}) {
return (
);
}
```
Captured from the sample above. SUGGESTED colors the Rename response.
The tutorial builds dialogs in [Mount the dialogs](/v2/tutorial/actions-menus-shortcuts#mount-the-dialogs) and [Rename a note](/v2/tutorial/trash-and-toasts#rename-a-note).
### About dialog metadata
`AdwAboutDialog` accepts `links`, `creditSections`, `acknowledgementSections`, `legalSections`, and `otherApps` as arrays:
```tsx [src/components/about.tsx]
import * as Gtk from "@gtkx/gi/gtk";
import { AdwAboutDialog } from "@gtkx/jsx/adw";
export function About({ onClose }: { onClose: () => void }) {
return (
);
}
```
Captured from the sample above. Libadwaita puts links under Details, gives each section array its own page, and lists otherApps at the bottom.
Libadwaita cannot remove these entries. Each array becomes fixed when its first nonempty value is applied; equivalent arrays on later renders are accepted, and a different one throws. To change or remove a populated list, give the dialog a new React `key`. Legal-section copyright and custom license text accept Pango markup, so escape externally supplied plain text with `GLib.markupEscapeText`.
## Closing
The app decides what is open by what it renders. A close button, Escape, a gesture or the window manager only asks to close, and the app answers by rendering something else. Until it answers, GTKX keeps the native state matching React as far as the toolkit allows:
| Element | Answered by | When nothing answers |
| ------------------------------------------------------ | --------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------- |
| Adwaita dialogs | `onClosed` or `onCloseAttempt`; `onResponse` on `AdwAlertDialog` | The dialog stays open. |
| `AdwTabPage` in a JSX `AdwTabView` | A `close-page` handler on the view: `onClosePage` or one connected with [`useSignal`](/v2/guide/native-state#connecting-a-signal) | The tab stays. |
| `AdwBottomSheet` given `open` | `onNotifyOpen` or `onCloseAttempt` | The sheet stays open. |
| Open-state props | Rendering the new value, usually from the matching `onNotify…` handler | GTKX restores the rendered value before the next frame. |
| Windows | `onCloseRequest` | The window closes, so the user can always close it. |
| `visible` on `GtkPopover`, `active` on `GtkMenuButton` | `onClosed`, `onNotifyActive` | The popover closes. |
Returning `false` from `onClosePage` lets libadwaita close the tab without the app answering.
The open-state props are `showSidebar` on `AdwOverlaySplitView`, `showContent` on `AdwNavigationSplitView`, `open` on `AdwBottomSheet` and `AdwTabOverview`, and `searchModeEnabled` on `GtkSearchBar`. Like [`selectedIndex` on `GtkListBox`](/v2/guide/components#gtklistbox), each one is controlled when given; omitting it leaves it to the widget.
In development, GTKX warns once per element type when nothing answers, naming the handler to add. It also warns when a window other than the last one, a dialog or a popover closed while the app still renders it open, as when an `onClosed` handler only logs.
## Finding the parent window
`useParentWindow()` from `@gtkx/react` returns the nearest window once its native instance exists. It returns `null` while the instance is unavailable or when there is no window ancestor. The lookup follows component ancestry through portals, so portaled dialogs can still use their originating window.
## createPortal
`createPortal` from `@gtkx/react` renders into a native object whose child-placement rules accept the content. Capture that target with a state callback ref:
```tsx
import type * as Gtk from "@gtkx/gi/gtk";
import { GtkBox, GtkLabel } from "@gtkx/jsx/gtk";
import { createPortal } from "@gtkx/react";
import { useState } from "react";
const StatusArea = () => {
const [tray, setTray] = useState(null);
return (
<>
{tray && createPortal(Synced, tray)}
>
);
};
```
Pass `rootElement` from `@gtkx/react` as the target when the object needs React ownership without a native parent. The [async operations example](/v2/guide/async-operations#awaiting-async-operations) uses this for a file dialog.
See the [`createPortal` reference](/v2/reference/@gtkx/react/index/functions/createPortal) for GTKX's arguments, and React's [portal documentation](https://react.dev/reference/react-dom/createPortal) for context and component lifetime.
## Synchronous native callbacks
Some native signals need an object returned before their handler finishes. For example, `AdwTabOverview.onCreateTab` returns the new `Adw.TabPage`, and `AdwTabView.onCreateWindow` returns the destination `Adw.TabView`.
React commits asynchronously, so JSX rendered in response to the signal is not ready in time. Create the native object in the handler, keep it in state, and render into it with `createPortal` once React commits. For a new tab, append an `Adw.Bin` to the view and return its page; for a new window, construct the `Adw.TabView` and mount the window around it. The [tab view navigator](/v2/guide/navigation#tab-view-navigator) packages this pattern for tabs, and the list components use it for their cells.
An independent `createRoot(container)` owns its rendered children separately from the component that created the container, until you call its `unmount()`. A tab rendered into an `Adw.TabView` this way keeps its native widget and React state after libadwaita transfers it to another window and the original view unmounts. The tab view navigator remounts a transferred screen instead; see [Windows and transfers](/v2/guide/navigation#windows-and-transfers).
The exported API is in the [@gtkx/react reference](/v2/reference/@gtkx/react/).
---
---
title: "Components"
description: "Render lists, tables, dropdowns, grid cells, stack pages, tabs, menu widgets, and toast notifications from React state."
---
# Components
`@gtkx/components` renders native collections from data and render functions, managing their GTK models and factories, and shares toasts through a provider. This page also covers the JSX elements these components sit beside: `GtkListBox`, tabs, grid cells, stack pages and widgets in menus.
`@gtkx/components` is a separate install:
```bash
npm install @gtkx/components@beta
```
See the [component reference](/v2/reference/@gtkx/components/) for props. Hooks that connect GObject state to React come from [`@gtkx/react`](/v2/reference/@gtkx/react/).
## List components
### ListView
`ListView` wraps `Gtk.ListView`. Pass `items` as `{ id, value }` pairs plus a `renderItem`. Selection is controlled: update `selectedIds` from `onSelectionChanged` to retain the selection. Like a React input's `onChange`, `onSelectionChanged` reports what the user or the widget changes, not the `selectedIds` you pass in. It also reports the remaining selection when an item named by `selectedIds` is not in the list.
```tsx [src/task-list.tsx]
import { ListView } from "@gtkx/components";
import * as Gtk from "@gtkx/gi/gtk";
import { GtkLabel } from "@gtkx/jsx/gtk";
import { useState } from "react";
type Task = { id: string; title: string };
const tasks: Task[] = [
{ id: "welcome", title: "Welcome to Tasks" },
{ id: "milk", title: "Buy oat milk" },
{ id: "dentist", title: "Book the dentist" },
{ id: "passport", title: "Renew passport" },
];
export function TaskList() {
const [selectedIds, setSelectedIds] = useState(["milk", "dentist"]);
return (
items={tasks.map((task) => ({ id: task.id, value: task }))}
selectionMode={Gtk.SelectionMode.MULTIPLE}
selectedIds={selectedIds}
onSelectionChanged={setSelectedIds}
estimatedItemHeight={56}
renderItem={({ item }) => (
{item.title}
)}
/>
);
}
```
Captured from the ListView sample above, with two tasks selected.
The tutorial's [note list](/v2/tutorial/the-note-editor#select-the-open-note) derives `selectedIds` from the current route.
Nesting `ListItem.children` turns the same component into an acyclic tree, with `expandedIds` and `onExpandedChange` driving expansion the same way. Keep item IDs stable and unique across the collection, including nested items, since selection and expansion name rows by ID. Section IDs must be unique among sections.
IDs also give rows their identity. When items are inserted, removed or reordered, GTK keeps every row whose ID stays among the same siblings bound, so its component state survives, and only new rows mount. A row that moves keeps its state in a flat list, grid, table or section; a tree row that moves among its siblings remounts, because GTK rebuilds its tree node. A reorder that moves more than about a thousand rows at once updates rows in place instead, and the rows that move there remount. An ID repeated among siblings pairs rows by their order.
When every item is known to be a leaf, pass `isFlat` to `ListView` or `ColumnView`. This skips tree discovery when synchronizing large collections. Leave it out when any item has children: those items would render as plain rows that never expand.
To group rows under headers, pass `sections` in place of `items`: each `ListSection` carries its own `data` array of items, and `renderHeader` draws the header above each group. `ColumnView` and `DropDown` accept the same pair.
A row's content is not the row a screen reader announces: GTK names a list row only from its own accessible label. Pass `rowProps` to name or describe each row, or to make one unselectable, unactivatable or unfocusable. It receives the same arguments as `renderItem`; `GridView`, `ColumnView` and `ListItemFactory` accept it too.
```tsx
items={tasks.map((task) => ({ id: task.id, value: task }))}
rowProps={({ item }) => ({
accessibleLabel: item.title,
isSelectable: !item.isArchived,
})}
renderItem={({ item }) => }
/>
```
### GridView
`GridView` renders a grid with the same `items`, `renderItem`, controlled selection, and size estimates as `ListView`. A grid is always flat: it takes no `sections` and ignores `children`. Use `minColumns` and `maxColumns` to size the grid, and `singleClickActivate` and `onActivate` for activation.
### ColumnView
`ColumnView` renders a multi-column table. Columns come from the `columns` prop, each one requiring `id`, `title`, and `renderCell`. Sorting is controlled: `onSortChanged` reports the header click, and the caller sorts `items` before passing them in.
```tsx [src/employee-table.tsx]
import { ColumnView, type ColumnViewColumn } from "@gtkx/components";
import * as Gtk from "@gtkx/gi/gtk";
import { GtkLabel } from "@gtkx/jsx/gtk";
import { useState } from "react";
type Employee = { id: string; name: string; team: string };
const employees: Employee[] = [
{ id: "ada", name: "Ada Lovelace", team: "Research" },
{ id: "grace", name: "Grace Hopper", team: "Compilers" },
{ id: "radia", name: "Radia Perlman", team: "Networking" },
{ id: "alan", name: "Alan Turing", team: "Research" },
];
const columns: ColumnViewColumn[] = [
{
id: "name",
title: "Name",
isSortable: true,
expand: true,
renderCell: ({ item }) => (
{item.name}
),
},
{
id: "team",
title: "Team",
isSortable: true,
expand: true,
renderCell: ({ item }) => (
{item.team}
),
},
];
function sortEmployees(column: string | null, order: Gtk.SortType) {
if (column !== "name" && column !== "team") return employees;
const sorted = [...employees].sort((a, b) =>
a[column].localeCompare(b[column]),
);
return order === Gtk.SortType.DESCENDING ? sorted.reverse() : sorted;
}
export function EmployeeTable() {
const [sortColumn, setSortColumn] = useState("name");
const [sortOrder, setSortOrder] = useState(Gtk.SortType.ASCENDING);
return (
{
setSortColumn(column);
setSortOrder(order);
}}
items={sortEmployees(sortColumn, sortOrder).map((employee) => ({
id: employee.id,
value: employee,
}))}
columns={columns}
/>
);
}
```
Captured from the ColumnView sample above, sorted by the Name column.
`ColumnView` also supports trees through `ListItem.children`, `expandedIds`, and `onExpandedChange`. The first visible column draws the expander and indentation; the other columns stay aligned at each depth. Hiding that column with `visible: false` moves the expander to the next visible column. Set `hasExpander` on a column to draw them there instead, such as the subject column of a message list whose status icons come first.
### DropDown
`DropDown` takes `items`, or `sections` plus `renderHeader`, with single controlled selection through `selectedId` and `onSelectionChanged`. Primitive values display as labels by default; `null` and `undefined` leave the display empty. Objects and other structured values require `renderItem`, which draws both the selected value and the popup rows. Use `renderListItem` to override only the popup rows.
```tsx [src/source-type-picker.tsx]
import { DropDown } from "@gtkx/components";
import * as Gtk from "@gtkx/gi/gtk";
import { useState } from "react";
const SOURCE_TYPES = ["Book", "Article", "Podcast"];
export const SourceTypePicker = () => {
const [sourceType, setSourceType] = useState("Article");
return (
({ id: type, value: type }))}
selectedId={sourceType}
onSelectionChanged={(id) => {
if (id !== null) setSourceType(id);
}}
halign={Gtk.Align.CENTER}
valign={Gtk.Align.START}
marginTop={12}
/>
);
};
```
Captured from the sample above after clicking the drop-down.
The callback receives `null` when the model becomes empty.
GTK names a drop-down after its selected item: its template labels the drop-down by the item shown on its button, and that relation outranks `accessibleLabel`. To give it a fixed name, pass a visible label in `accessibleLabelledBy`.
`ComboRow` from `@gtkx/components` takes the same collection props and renders an `Adw.ComboRow`, the drop-down as a row for a preferences group. See the tutorial's [preferences chapter](/v2/tutorial/preferences-and-theming) for an example.
### Native models
When a native `Gio.ListModel` already holds the data, such as a `Gtk.StringList` behind a `Gtk.FilterListModel`, keep the model and use `ListItemFactory` as the view's factory. Its `renderItem` receives each model object:
```tsx
import { ListItemFactory } from "@gtkx/components";
import type * as Gtk from "@gtkx/gi/gtk";
import { GtkInscription, GtkListView, GtkNoSelection } from "@gtkx/jsx/gtk";
}
factory={
rowProps={({ item }) => ({ accessibleLabel: item.getString() })}
renderItem={({ item }) => (
)}
/>
}
/>
```
### GtkListBox
`GtkListBox` takes JSX rows directly, making it suitable for short lists such as a sidebar or settings group. Its `selectedIndex` prop controls the selected row:
```tsx [src/sidebar.tsx]
import { AdwActionRow } from "@gtkx/jsx/adw";
import { GtkListBox } from "@gtkx/jsx/gtk";
import { useState } from "react";
const views = [
{ id: "inbox", title: "Inbox" },
{ id: "today", title: "Today" },
{ id: "upcoming", title: "Upcoming" },
{ id: "done", title: "Done" },
];
export function Sidebar() {
const [activeId, setActiveId] = useState("today");
return (
view.id === activeId)}
onRowSelected={(row) => {
if (!row) return;
const view = views[row.getIndex()];
if (view) setActiveId(view.id);
}}
>
{views.map((view) => (
))}
);
}
```
Captured from the GtkListBox sample above, with Today selected.
Leave `selectedIndex` out for native selection, or set it to keep selection under application control. Use `-1` or `null` to clear it. If the desired row has not mounted yet, GTKX keeps the current selection and applies the index once that row exists.
GTKX suppresses `onRowSelected` while applying its own selection updates and while a commit adds or removes rows, so removing the selected row from your state doesn't call it with `null`. Other native selection changes still reach the handler, including changes made through native methods. Update the controlled value in that handler to keep the new selection; otherwise GTKX restores the requested row.
## Tabs
Ordinary `AdwTabView` children work for tabs that share their parent's React lifetime. For tabs the user opens, closes, reorders and drags between windows, use the [tab view navigator](/v2/guide/navigation#tab-view-navigator) from `@gtkx/navigation`, which keeps the open tabs in navigation state and follows native transfers.
A JSX tab stays open while React renders it. To let the user close tabs with their close buttons or the tab overview, handle `onClosePage`: remove the page from the state that renders it and confirm the close. Without a handler, the close does nothing and GTKX warns in development; see [Closing](/v2/guide/modals-and-portals#closing).
```tsx [src/documents.tsx]
import type * as Adw from "@gtkx/gi/adw";
import * as Gtk from "@gtkx/gi/gtk";
import { AdwTabBar, AdwTabPage, AdwTabView } from "@gtkx/jsx/adw";
import { GtkBox, GtkLabel } from "@gtkx/jsx/gtk";
import { useState } from "react";
export const Documents = () => {
const [titles, setTitles] = useState(["Notes", "Ideas"]);
const [view, setView] = useState(null);
return (
{
setTitles((current) =>
current.filter((title) => title !== page.getTitle()),
);
tabView.closePageFinish(page, true);
return true;
}}
>
{titles.map((title) => (
{title}
))}
);
};
```
Captured from the sample above. The tab bar shows a tab for each page the component renders.
`onNotifySelectedPage` reports the selection libadwaita makes: the first page once the view mounts, and the neighbour it selects after your state drops the selected page, so a window subtitle or per-tab action mirrored from that handler stays current.
### Native tab configuration
`AdwTabPage` accepts `pinned` in ordinary JSX. Updating it pins or unpins the page through its current native view. Reordering keyed JSX pages preserves the requested relative order within each pin group. Pinning a page follows libadwaita’s insertion order.
Both `AdwTabBar` and `AdwTabOverview` accept `extraDropTarget`, so supported drag actions and data types can follow React state:
```tsx
import * as Gdk from "@gtkx/gi/gdk";
import * as GObject from "@gtkx/gi/gobject";
import { AdwTabBar } from "@gtkx/jsx/adw";
{
const title = value.getString();
if (title === null) return false;
renameTab(page, title);
return true;
}}
/>
```
Here `renameTab` updates the state the page's `title` prop comes from. Removing `extraDropTarget` disables the additional drop target. Types can be GType values or generated classes. Use explicit `null` when clearing nullable object props such as a tab's `icon`.
## Grid cells
GTK places a widget in a `GtkGrid` through the layout manager's child object, which GtkBuilder writes as a `` element and C code sets with `gtk_grid_attach`. Wrap each child of the grid in `GtkGridLayoutChild` and give it the cell's `column` and `row`, plus `columnSpan` or `rowSpan` to cover several cells:
```tsx [src/name-grid.tsx]
import {
GtkButton,
GtkGrid,
GtkGridLayoutChild,
GtkLabel,
} from "@gtkx/jsx/gtk";
export function NameGrid() {
return (
);
}
```
Captured from the grid sample above.
The grid creates the layout child for the widget, and changing `column` or `row` moves it. A child without the wrapper sits in the first cell. Other layout managers' child objects work the same way, such as `GtkFixedLayoutChild` for a widget's `transform` inside a `GtkFixed`, which [Animations](/v2/guide/animations#moving-widgets) animates.
## Stack pages
`GtkStack`, `AdwViewStack` and `GtkNotebook` keep a page object for each child, which holds the child's name, title and icon, or its tab label. Wrap each child in the matching page element, `GtkStackPage`, `AdwViewStackPage` or `GtkNotebookPage`, and set those properties on it. The container creates the page object when the child is added, as a grid does for its layout children:
```tsx [src/editor.tsx]
import * as Gtk from "@gtkx/gi/gtk";
import {
GtkBox,
GtkLabel,
GtkStack,
GtkStackPage,
GtkStackSwitcher,
} from "@gtkx/jsx/gtk";
import { useState } from "react";
export const Editor = () => {
const [stack, setStack] = useState(null);
return (
Markdown sourceRendered preview
);
};
```
Captured from the sample above. The switcher takes its buttons from the page titles.
The switcher shows a button for each page `title`. To switch pages from state instead, set `visibleChildName` to a page's `name`, as the tutorial's [Markdown preview](/v2/tutorial/the-markdown-preview#switch-between-editor-and-preview) does. For a few peer sections with a view switcher in the header bar, the [tab navigator](/v2/guide/navigation#tab-navigator) renders the `AdwViewStack` for you.
## Widgets in menus
A popover menu can show a widget in place of a menu item, as GNOME Text Editor does with its style selector. Give the item a `custom` ID and pass the widget under that ID in `customChildren` on the `GtkMenuButton`, `GtkPopoverMenu` or `GtkPopoverMenuBar` showing the menu, as GtkBuilder's `` does:
```tsx [src/components/app-menu.tsx]
import * as Adw from "@gtkx/gi/adw";
import * as Gtk from "@gtkx/gi/gtk";
import { GMenu } from "@gtkx/jsx/gio";
import { GtkBox, GtkMenuButton, GtkToggleButton } from "@gtkx/jsx/gtk";
import { useState } from "react";
const COLOR_SCHEMES = [
{ label: "System", scheme: Adw.ColorScheme.DEFAULT },
{ label: "Light", scheme: Adw.ColorScheme.FORCE_LIGHT },
{ label: "Dark", scheme: Adw.ColorScheme.FORCE_DARK },
];
const ThemeSelector = () => {
const [first, setFirst] = useState(null);
return (
{COLOR_SCHEMES.map(({ label, scheme }, index) => (
Adw.StyleManager.getDefault().setColorScheme(scheme)
}
/>
))}
);
};
export const AppMenu = () => (
comma",
},
],
},
]}
/>
}
customChildren={{ theme: }}
/>
);
```
Captured from the sample above with the menu open, in a window that declares win.preferences.
The widget stays in its item when the model or its items change. An ID with no matching item leaves its widget out of the menu. [Menus](/v2/guide/actions#menus) covers the other item attributes, such as `hiddenWhen` and `accel`.
## Toasts
Wrap the window's content in `AdwToastOverlay`, then share its ref through `ToastProvider`. Descendants can call `useToast()` to show a notification:
```tsx [src/notifications.tsx]
import { ToastProvider, useToast } from "@gtkx/components";
import type * as Adw from "@gtkx/gi/adw";
import * as Gtk from "@gtkx/gi/gtk";
import { AdwToastOverlay } from "@gtkx/jsx/adw";
import { GtkButton } from "@gtkx/jsx/gtk";
import { useRef } from "react";
const NotifyButton = () => {
const toast = useToast();
return (
toast.show({ title: "Task saved", useMarkup: false })
}
/>
);
};
export const Notifications = () => {
const overlayRef = useRef(null);
return (
);
};
```
Captured from the sample above after clicking the button.
Render `Notifications` inside an application window. Clicking the button shows a toast over the content. Use `useMarkup: false` for titles that should display literally, including user text.
`show()` returns the native `Adw.Toast`. Pass `buttonLabel` and `onButtonClicked` to add an action, and `onDismissed` when cleanup depends on its dismissal. Call `dismiss()` on the returned toast to close it, or the controller's `dismissAll()` to clear the overlay.
`useToast()` requires a provider. Show toasts from events or effects after the overlay mounts; calling `show()` while its ref is empty creates a toast without displaying it. [Rename, Trash, and Undo](/v2/tutorial/trash-and-toasts#undo-from-a-toast) adds an Undo button to a trash operation.
---
---
title: "CSS"
description: "Apply widget styles and reusable classes in GTKX."
---
# CSS
GTKX provides a `style` prop for individual widgets and `@gtkx/css` for reusable styles. Use [Adwaita's style classes](https://gnome.pages.gitlab.gnome.org/libadwaita/doc/1-latest/style-classes.html) for standard widget styling. For custom rules, use [GTK's supported CSS properties](https://docs.gtk.org/gtk4/css-properties.html); layout stays in widget props.
## Style one widget
The `style` prop accepts an object with camelCase property names:
```tsx
import { GtkLabel } from "@gtkx/jsx/gtk";
;
```
Numeric lengths use pixels: `minHeight: 48` becomes `min-height: 48px`. Pass other units as strings. Setting `style` to `undefined` or `null` removes its declarations.
Nested selectors start with `&`, which refers to the styled widget. Other parts of a selector match GTK's [CSS node names](https://docs.gtk.org/gtk4/css-overview.html#css-nodes), which each widget's API documentation lists, so `& label` matches the button's label:
```tsx
import { GtkButton } from "@gtkx/jsx/gtk";
;
```
Keys starting with `--` set CSS custom properties, which the widget and its descendants read through `var()`. Overriding Adwaita's variables recolors a subtree:
```tsx [src/accent-override.tsx]
import * as Gtk from "@gtkx/gi/gtk";
import { GtkBox, GtkButton } from "@gtkx/jsx/gtk";
export function AccentOverride() {
return (
);
}
```
Captured from the sample above. Only Save, inside the box that overrides the accent variables, turns green.
A declaration in `style` takes precedence over the same declaration supplied through `cssClasses`. GTKX adds a generated class to apply the style; leave that class under GTKX's control.
Use `style` for values specific to one widget, such as a color computed from props. GTKX batches these updates through a shared style provider, but frequent changes still make GTK recalculate styles. Prefer native animated properties or CSS transitions when they express the effect. See [Animations](/v2/guide/animations) for animated styles.
## Create reusable classes
`css` accepts a tagged template or style object and returns a class name for `cssClasses`:
```tsx [src/due-label.tsx]
import { css } from "@gtkx/css";
import { GtkLabel } from "@gtkx/jsx/gtk";
const overdue = css`
color: var(--error-color);
font-weight: 700;
&:hover {
text-decoration: underline;
}
`;
export const DueLabel = () => (
);
```
Captured from the sample above. The label takes the theme's error color in each color scheme.
Identical styles reuse the same class and are inserted once. Interpolating a generated class into another `css` call includes its declarations. Use these classes for styles shared by several widgets, or for rules such as `@media` and `@keyframes` that the `style` prop does not expose. Keyframe names are global, so give them an application or component prefix.
## Combine classes
`cx` returns the array that `cssClasses` expects. It keeps nonempty class names and ignores boolean, `null`, and `undefined` arguments:
```tsx
import { css, cx } from "@gtkx/css";
import { GtkButton } from "@gtkx/jsx/gtk";
const action = css({ minWidth: 96 });
;
```
When several generated classes are combined, `cx` merges their declarations into one class. Later arguments win on conflicting declarations. As within one `css` call, nested selectors and `@media` blocks follow all plain declarations, so an earlier argument's `@media` rule still overrides a later argument's plain declaration while its query matches. Give the later class its own `@media` rule when it must win there too:
```ts
import { css, cx } from "@gtkx/css";
const chip = css`
background: alpha(var(--accent-bg-color), 0.15);
@media (prefers-color-scheme: dark) {
background: alpha(var(--accent-bg-color), 0.35);
}
`;
const warning = css`
background: alpha(var(--warning-bg-color), 0.2);
@media (prefers-color-scheme: dark) {
background: alpha(var(--warning-bg-color), 0.35);
}
`;
const unsaved = cx(chip, warning);
```
## Apply global rules
`injectGlobal` inserts selectors without a generated class:
```ts
import { injectGlobal } from "@gtkx/css";
injectGlobal`
window {
background: var(--window-bg-color);
}
`;
```
### Import a stylesheet
A plain `.css` import also works: the GTKX CLI turns it into an `injectGlobal` call. Global rules remain installed for the application's lifetime.
Relative references in the file are bundled with the app. A relative `url()`, such as `background-image: url("../data/paper.png")`, becomes a [`?resource`](/v2/guide/assets#resources) file, and a relative `@import` loads that stylesheet before the file's own rules.
Other `url()` values reach GTK unchanged. A `resource://` or `file://` URI loads, but an absolute path such as `url("/com/example/Tasks/paper.png")` draws nothing, because the installed stylesheet has no location to resolve it against; `gtkx dev` and `gtkx build` warn about it. In `css` and `style`, interpolate a `?resource` import instead:
```ts
import { css } from "@gtkx/css";
import paperPath from "../data/paper.png?resource";
const paper = css`
background-image: url("resource://${paperPath}");
`;
```
During `gtkx dev`, editing a stylesheet replaces the rules that file installed, so removed rules stop applying, and the app keeps its state. Editing a module's `injectGlobal` rules re-runs the module, which adds the edited rules after the earlier ones, as Emotion does: a changed value takes effect, but a removed rule or a selector you moved keeps applying until the app restarts.
### Load Adwaita's `style.css`
A stylesheet imported with [`?resource`](/v2/guide/assets#resources) is bundled unchanged rather than installed. Use this for the `style.css` that [Adwaita loads](https://gnome.pages.gitlab.gnome.org/libadwaita/doc/1-latest/class.Application.html#automatic-resources) from the application's resource base path, as in a ported GNOME application:
```ts
import "../data/style.css?resource=/com/example/Tasks/style.css";
import "../data/paper.png?resource=/com/example/Tasks/paper.png";
```
GTK resolves `url()` values in that file against its resource path, so `url("paper.png")` and `url("/com/example/Tasks/paper.png")` both load the image imported beside it. Import each image the stylesheet references at its matching path, since GTKX bundles only imported files. `gtkx build` warns about a `url()` or `@import` under the application's resource base path that names no bundled file.
## Follow appearance preferences
Media queries in `css`, `injectGlobal` and imported `.css` files follow the color scheme resolved by [Adw.StyleManager](https://gnome.pages.gitlab.gnome.org/libadwaita/doc/1-latest/class.StyleManager.html), including an application override. It also follows the system's contrast preference and, on GTK 4.22 or later, reduced-motion preference.
Use theme variables in custom styles so their colors follow the active appearance. When a rule needs to change by preference, place its `@media` block inside `css`:
```ts
import { css } from "@gtkx/css";
const card = css`
background: var(--card-bg-color);
box-shadow: 0 1px 3px var(--shade-color);
@media (prefers-color-scheme: dark) {
box-shadow: none;
}
`;
```
See [Add Preferences](/v2/tutorial/preferences-and-theming#read-and-bind-settings) for an application preference that switches the scheme.
## Use a bundled font
A `?font` import bundles the font and returns its family name. Pass that name directly to `fontFamily`:
```tsx
import { GtkLabel } from "@gtkx/jsx/gtk";
import bodyFont from "../data/fonts/Inter-Regular.otf?font";
;
```
To add a font for fallback coverage without selecting it, use a side-effect import such as `import "../data/fonts/NotoSansKR.otf?font";`. See [Fonts](/v2/guide/assets#fonts) for font imports.
---
---
title: "Assets"
description: "Bundle images, icons, fonts, and settings schemas with a GTKX application."
---
# Assets
Import application assets from source files so GTKX can include them in development and production builds.
## Import project data
Import each asset with a relative path and a query that says how GTKX bundles it:
```ts [src/app.tsx]
import logoPath from "../data/logo.png?resource";
import saveIcon from "./icons/scalable/actions/save.svg?icon=example-save-symbolic";
import templatePath from "../data/template.txt?url";
import bodyFont from "../data/fonts/Inter-Regular.otf?font";
import schema from "../data/com.example.Tasks.gschema.xml";
```
### Resources
`?resource` bundles a file of any type, such as an image, text, JSON or a shader, and returns its GResource path; `?resource=/org/example/exact.png` selects an exact path. Convert it to a `resource://` URI only when an API requires one.
GTKX derives resource paths from the configured application ID: `com.example.Tasks` becomes `/com/example/Tasks`. Overriding an application's `applicationId` prop alone does not move bundled resources; supply a matching `resourceBasePath` when using another resource tree. Production builds load their `gtkx.gresource` file automatically.
### Icons
`?icon` returns an icon name and registers the bundled icon with the app's private theme path. Keep icons under `icons///` or `icons/hicolor///` to preserve theme layout; other locations become unthemed fallbacks. Choose package-specific names for icons supplied by libraries.
Keep these icons outside the `applicationIcon` directory (`data/icons` in scaffolded projects): deployment installs that directory into the system icon theme in full.
A workspace package the app uses from source can import its icons the same way, and the app's declarations then include those names; see [Workspace sources](/v2/guide/workspaces#workspace-sources).
### Fonts
`?font` bundles a font and returns its family name. GTKX makes bundled fonts available automatically. Import a font for its side effect when it only supplies fallback characters; see [CSS](/v2/guide/css) for choosing a family in styles.
### Files and text
`?url` provides a real file path: the source file during `gtkx dev` and Vitest, and the copy in `dist/` after `gtkx build`. `?raw` provides a file's text, and `?inline` inlines it into the bundle: a stylesheet's text, or a data URL for any other file.
### Settings schemas
Import the application's own `.gschema.xml` without a query. GTKX compiles and bundles the schema and generates its types beside it, and the import returns the module the settings hooks read keys through; see [Your app's schema](/v2/guide/native-state#your-app-s-schema).
### Types
The scaffold's `src/gtkx-env.d.ts` types the queries above and stylesheet imports. It types only what GTKX supports, so an asset imported without a query fails `tsc`, and so does another Vite query. `gtkx dev`, `gtkx build` and Vitest also reject an image, media or font file imported without a query, and Vite's `?worker` and `?sharedworker` imports, because Node.js has no global `Worker`; start a worker from `node:worker_threads` as [Workers](/v2/guide/workers#moving-work-to-a-worker) shows.
### Development restarts
During development, changing, removing, or restoring an imported resource or icon restarts the app. Changing the imports that select those assets also restarts it, so resources from removed imports are released.
## Read system settings schemas
A schema installed on the system, such as `org.gnome.desktop.interface`, is described by hand rather than imported; see [System schemas](/v2/guide/native-state#system-schemas).
## Production build output
This section moved to [Production build output](/v2/guide/deploying#production-build-output) in Deploying.
---
---
title: "Navigation"
description: "Choose an Adwaita navigator and connect its pages, headers, and native back controls."
---
# Navigation
`@gtkx/navigation` renders [React Navigation](https://reactnavigation.org) with Adwaita widgets. Install it alongside GTKX:
```bash
npm install @gtkx/navigation@beta
```
Choose a navigator for the layout:
| Navigator | Use it for | Native widgets |
| ----------------------------------- | ---------------------------------------------- | ---------------------------------------- |
| [Stack](#stack-navigator) | Moving through a sequence of pages | `AdwNavigationView` |
| [Tabs](#tab-navigator) | Switching between a few peer sections | `AdwViewStack` and a view switcher |
| [Drawer](#drawer-navigator) | Choosing an application section from a sidebar | `AdwOverlaySplitView` |
| [Split view](#split-view-navigator) | Keeping a selection beside its detail pages | `AdwNavigationSplitView` |
| [Tab view](#tab-view-navigator) | Opening any number of documents as tabs | `AdwTabView` with a tab bar and overview |
Scaffolded applications already generate the Adwaita bindings these navigators need. The package re-exports React Navigation's core hooks, actions and types. Use its [navigation documentation](https://reactnavigation.org/docs/navigation-object/) for those shared concepts and the [GTKX reference](/v2/reference/@gtkx/navigation/) for navigator options.
## NavigationContainer
`NavigationContainer` hosts the navigation tree. Render it once, inside the window, around the root navigator:
```tsx
import { AdwApplication, AdwApplicationWindow } from "@gtkx/jsx/adw";
import { NavigationContainer } from "@gtkx/navigation";
import { quit } from "@gtkx/react";
export const App = () => (
);
```
The container's default theme follows Adwaita's current dark and high-contrast settings. Pass `theme` to override the values supplied to `useTheme` and screen options; this does not change the native color scheme.
Navigation outside the tree uses React Navigation's [container API](https://reactnavigation.org/docs/navigation-container/).
### Restoring state
Pass a saved state to `initialState` and save each new one from `onStateChange`. React Navigation's [state persistence](https://reactnavigation.org/docs/state-persistence/) example renders `null` until the saved state loads, but a GTKX application ends when its first render shows no window. Keep the window rendered and load the state inside it:
```tsx
import * as Gio from "@gtkx/gi/gio";
import * as GLib from "@gtkx/gi/glib";
import {
AdwApplication,
AdwApplicationWindow,
AdwSpinner,
} from "@gtkx/jsx/adw";
import { type InitialState, NavigationContainer } from "@gtkx/navigation";
import { quit } from "@gtkx/react";
import { useEffect, useState } from "react";
const dataDir = GLib.buildFilenamev([GLib.getUserDataDir(), "notes"]);
const stateFile = Gio.File.newForPath(
GLib.buildFilenamev([dataDir, "navigation.json"]),
);
const loadState = async (): Promise => {
try {
const [bytes] = await stateFile.loadContentsAsync(null);
return JSON.parse(new TextDecoder().decode(bytes));
} catch {
return undefined;
}
};
const saveState = (state: object | undefined) => {
GLib.mkdirWithParents(dataDir, 0o755);
const bytes = new TextEncoder().encode(JSON.stringify(state));
stateFile
.replaceContentsAsync(
bytes,
null,
false,
Gio.FileCreateFlags.NONE,
null,
)
.catch((error: unknown) => {
console.error(error);
});
};
export const App = () => {
const [restored, setRestored] = useState<{
state: InitialState | undefined;
}>();
useEffect(() => {
void loadState().then((state) => setRestored({ state }));
}, []);
return (
{restored ? (
) : (
)}
);
};
```
### Opening links
`NavigationContainer` has no `linking` prop: React Navigation's linking reads URLs through React Native, while a desktop application receives them from `GApplication`. Register the scheme with `deploy.protocols` in `gtkx.config.ts`, set `Gio.ApplicationFlags.HANDLES_OPEN`, and turn each URI into a navigation state with `getStateFromPath`.
A launch with a URI emits `open` before the window renders, so pass that state to `initialState`. A URI forwarded from a second launch reaches the running container, which `resetRoot` updates:
```tsx
import * as Gio from "@gtkx/gi/gio";
import { AdwApplication, AdwApplicationWindow } from "@gtkx/jsx/adw";
import {
createNavigationContainerRef,
getStateFromPath,
type InitialState,
NavigationContainer,
} from "@gtkx/navigation";
import { quit } from "@gtkx/react";
import { useState } from "react";
type NotesParams = { List: undefined; Note: { id: string } };
const navigationRef = createNavigationContainerRef();
const linking = {
initialRouteName: "List",
screens: { List: "", Note: "note/:id" },
} as const;
const stateFromUri = (uri: string) =>
getStateFromPath(uri.replace(/^notes:\/\//, ""), linking);
export const App = () => {
const [initialState, setInitialState] = useState();
const open = (files: Gio.File[]) => {
const uri = files.at(-1)?.getUri();
const state = uri === undefined ? undefined : stateFromUri(uri);
if (state === undefined) return;
if (navigationRef.isReady()) navigationRef.resetRoot(state);
else setInitialState(state);
};
return (
);
};
```
`initialRouteName` keeps the list beneath a linked note, so Back returns to it. `getPathFromState(state, linking)` turns a state back into a path, for example to copy a link to the visible page. During development, pass a URI after `--`, as in `pnpm dev -- notes://note/42`; see [command-line apps](/v2/guide/application-lifecycle#command-line-apps).
## Stack navigator
`createStackNavigator` renders an `AdwNavigationView`. Define the route parameters to typecheck screens, `navigate` calls, and `route.params`:
```tsx [src/notes.tsx]
import * as Gtk from "@gtkx/gi/gtk";
import { GtkBox, GtkButton, GtkLabel } from "@gtkx/jsx/gtk";
import { createStackNavigator, type StackScreenProps } from "@gtkx/navigation";
type NotesParams = { List: undefined; Note: { id: string } };
const Stack = createStackNavigator();
const List = ({ navigation }: StackScreenProps) => (
navigation.navigate("Note", { id: "42" })}
/>
);
const Note = ({ route, navigation }: StackScreenProps) => (
{`Showing note ${route.params.id}`} navigation.goBack()} />
);
export const Notes = () => (
({ title: `Note ${route.params.id}` })}
/>
);
```
Captured from the sample above. The navigator draws the header bar and its title from the screen options.
Each screen renders one root widget; wrap several widgets in a container such as `GtkBox`.
The stack uses React Navigation's routing behavior. In the example, `navigate("Note", { id })` updates the current Note screen or pushes one from another screen. Returning to an earlier route is a separate action, such as `popTo`. See the [navigation API](https://reactnavigation.org/docs/navigation-object/) for route identity and action behavior.
Pushes and pops use Adwaita transitions. Replacing or resetting the stack switches pages without a transition.
### Headers
Each page gets an `AdwHeaderBar` with a title and native back button. The title defaults to the route name.
Captured from the stack sample after clicking Open note 42. The pushed page gets the back button and the title from its options.
Add header actions through screen options:
```tsx
import { GtkButton } from "@gtkx/jsx/gtk";
({
title: `Note ${route.params.id}`,
headerEnd: ,
})}
/>;
```
Use `headerStart` and `headerEnd` for actions in the native header bar. `headerTitle` replaces its title widget, and `header` replaces the bar. Set `headerShown: false` on a screen that contains another navigator to let the inner navigator own the header.
Set shared defaults through the navigator's `screenOptions`; a screen's `options` take precedence. See the [header options reference](/v2/reference/@gtkx/navigation/type-aliases/HeaderOptions).
### Native back controls
The header back button, Escape, Alt+Left, mouse back button and swipe gestures use the native Adwaita behavior. Set `popOnEscape={false}` to disable the navigator's Escape handling, `canPop: false` to prevent native back navigation, or `animation: "none"` to skip a page's transition. `headerBackVisible: false` hides only the header button.
Native back controls dispatch `StackActions.pop()`. Use `usePreventRemove` to guard against losing edits; if it prevents removal, the page returns to its position and the callback receives the attempted action:
```tsx
import type { NavigationAction } from "@gtkx/navigation";
import * as Adw from "@gtkx/gi/adw";
import * as Gtk from "@gtkx/gi/gtk";
import { AdwAlertDialog } from "@gtkx/jsx/adw";
import { GtkBox, GtkEntry } from "@gtkx/jsx/gtk";
import { useNavigation, usePreventRemove } from "@gtkx/navigation";
import { useState } from "react";
const Compose = () => {
const navigation = useNavigation();
const [text, setText] = useState("");
const [pending, setPending] = useState(null);
usePreventRemove(text !== "", ({ data }) => {
setPending(data.action);
});
return (
setText(entry.text)}
/>
{pending && (
{
if (id === "discard") {
navigation.dispatch(pending);
}
setPending(null);
}}
/>
)}
);
};
```
React Navigation documents the rest of the [removal guard lifecycle](https://reactnavigation.org/docs/preventing-going-back/).
React Navigation 7 depends on `use-latest-callback` 0.2, which outside a browser updates the guard's callback in a passive effect. A passive effect that leaves the screen, such as `useEffect(() => { if (sent) navigation.goBack(); }, [sent])`, and runs before that update still sees the old `preventRemove` value, so the guard blocks a leave it should allow. Version 0.3 fixes this. Until React Navigation 7 accepts it, override the version: with npm, add it to `"overrides"` in `package.json`; with Yarn, to `"resolutions"`; with pnpm, to `overrides` in `pnpm-workspace.yaml`. For npm:
```json
{
"overrides": {
"use-latest-callback": "^0.3.5"
}
}
```
Otherwise, call `usePreventRemove` before the effect that leaves the screen, so its callback updates first.
### Transition events
Stack screens emit `transitionStart` and `transitionEnd` from their native page signals. Their `closing` value distinguishes a page leaving from one arriving. Screen `listeners` can observe them whether animation is enabled or disabled.
## Tab navigator
`createTabNavigator` renders an `AdwViewStack`. The switcher occupies the header title by default; `tabBarPosition="bottom"` puts an `AdwViewSwitcherBar` below the content:
```tsx [src/mail.tsx]
import { AdwStatusPage } from "@gtkx/jsx/adw";
import { createTabNavigator } from "@gtkx/navigation";
type MailParams = { Inbox: undefined; Archive: undefined };
const Tabs = createTabNavigator();
const Inbox = () => (
);
const Archive = () => (
);
export const Mail = ({ unread }: { unread: number }) => (
0,
}}
/>
);
```
Captured from the sample above with unread={3}. The bottom switcher shows each screen's icon, label and badge.
The switcher uses each screen's label, icon, badge and attention options. Tabs mount when first focused unless `lazy: false` is set. Set `animation: "fade"` for a crossfade.
Set `useUnderline: true` to read underscores in the switcher label as keyboard mnemonics: with `tabBarLabel: "_World"`, Alt+W selects the tab in either switcher position. Write `__` for a literal underscore. Header titles stay plain text, so put the mnemonic in `tabBarLabel` and keep `title` plain.
With a top switcher, leave the header's title widget available for it. To supply `headerTitle`, move the switcher to the bottom or place it explicitly through a custom `header`. Hiding the header leaves a top switcher visible on its own.
User selection emits `tabPress`, which a screen listener can prevent. Programmatic selection uses React Navigation's tab actions. The [tab options reference](/v2/reference/@gtkx/navigation/type-aliases/TabNavigationOptions) covers the remaining settings.
## Drawer navigator
`createDrawerNavigator` uses an `AdwOverlaySplitView`. Its sidebar lists the screens and marks the focused one; a button in the content header toggles the sidebar:
```tsx [src/app.tsx]
import { AdwStatusPage } from "@gtkx/jsx/adw";
import { createDrawerNavigator } from "@gtkx/navigation";
type AppParams = { Inbox: undefined; Settings: undefined };
const Drawer = createDrawerNavigator();
const Inbox = () => (
);
const Settings = () => (
);
export const App = ({ isNarrow }: { isNarrow: boolean }) => (
);
```
Captured from the sample above with isNarrow={false}. The sidebar stays beside the content and marks the focused screen.
Set `collapsed` when the layout needs an overlay sidebar; the sidebar then closes after a selection. In a wide layout it stays beside the content. `defaultStatus` controls its initial visibility, and `pinSidebar` preserves visibility across collapse changes.
`useUnderline: true` works the same way for drawer labels: with `drawerLabel: "_Settings"`, Alt+S selects the screen while the sidebar is visible.
Native opening and dismissal update the drawer's navigation state, so gestures and React Navigation's drawer actions stay in sync. See the [drawer configuration reference](/v2/reference/@gtkx/navigation/type-aliases/DrawerNavigationConfig) for sizing and placement.
`drawerContent` can wrap the default `DrawerItemList` with application-specific content:
```tsx
import * as Gtk from "@gtkx/gi/gtk";
import { AdwHeaderBar, AdwToolbarView, AdwWindowTitle } from "@gtkx/jsx/adw";
import { GtkScrolledWindow } from "@gtkx/jsx/gtk";
import { type DrawerContentProps, DrawerItemList } from "@gtkx/navigation";
const Sidebar = (props: DrawerContentProps) => (
} />}
>
);
}>
;
```
Activating a row emits `drawerItemPress`, which `preventDefault` cancels, before navigating.
## Split view navigator
`createSplitViewNavigator` keeps its first screen in the sidebar and places the other screens in a content stack. Use it when the sidebar selects data, such as a folder whose messages appear beside it:
```tsx [src/mail.tsx]
import * as Gtk from "@gtkx/gi/gtk";
import {
AdwSidebar,
AdwSidebarItem,
AdwSidebarSection,
AdwStatusPage,
} from "@gtkx/jsx/adw";
import { GtkButton, GtkLabel } from "@gtkx/jsx/gtk";
import {
createSplitViewNavigator,
type SplitViewScreenProps,
} from "@gtkx/navigation";
type MailParams = {
Folders: undefined;
Messages: { folder: string };
Message: { id: string };
};
const Split = createSplitViewNavigator();
const Folders = ({
navigation,
}: SplitViewScreenProps) => (
navigation.navigate("Messages", { folder: "Inbox" })}
>
);
const Messages = ({
navigation,
}: SplitViewScreenProps) => (
navigation.navigate("Message", { id: "1" })}
/>
);
const Message = ({ route }: SplitViewScreenProps) => (
);
export const Mail = () => (
}
>
({ title: route.params.folder })}
/>
}}
/>
);
```
Captured from the sample above. The navigator opens on the Inbox folder, which the sidebar selects first.
`AdwSidebar` selects its first item on its own, and `activated` fires only when the user activates a row. The sample therefore names a content screen in `initialRouteName`, with `initialParams`, so the pane opens on the folder the sidebar shows as selected instead of on the placeholder.
In a split view, `navigate` selects a content route: it updates that route and removes pages above it. Choosing another folder therefore replaces the selection instead of adding another folder page. Use `push` to keep multiple copies of a content page.
A content route that is not open yet is pushed above the current one, as in a stack. In a sidebar of distinct section screens, as in a settings app, `navigate("Proxy")` from Wi-Fi therefore leaves a Back button to Wi-Fi, and `popTo` replaces only the top page, which keeps the previous section beneath a section's sub-page. Reset the content instead, keeping the sidebar's own route so the sidebar is not remounted:
```tsx
import { GtkLabel, GtkListBox, GtkListBoxRow } from "@gtkx/jsx/gtk";
import type { SplitViewScreenProps } from "@gtkx/navigation";
type SettingsParams = {
Sections: undefined;
Wifi: undefined;
Proxy: undefined;
};
const sections = [
{ name: "Wifi", label: "Wi-Fi" },
{ name: "Proxy", label: "Proxy" },
] as const;
const Sections = ({
navigation,
route,
}: SplitViewScreenProps) => (
{
const section = sections[row.getIndex()];
if (section)
navigation.reset({
index: 1,
routes: [route, { name: section.name }],
});
}}
>
{sections.map((section) => (
))}
);
```
The reset switches sections without a page transition.
The sidebar stays pinned beneath the content routes. Going back from the first content page clears the selection and restores `contentPlaceholder`, which sits below an untitled header bar so the window keeps its controls.
Content pages use the stack's headers, back controls and transition events. The first selection fills an empty pane and emits no page transition. The sidebar has its own header without a back button.
`collapseCondition` collapses the panes while an [`Adw.BreakpointCondition`](https://gnome.pages.gitlab.gnome.org/libadwaita/doc/1-latest/type_func.BreakpointCondition.parse.html) holds, measured against the navigator's size. libadwaita applies it during layout, as it applies an `AdwBreakpoint` setter, so the panes change before GTK moves keyboard focus. Setting `collapsed` from a breakpoint's `onApply` and `onUnapply` handlers lands after GTK has moved focus, and widening the window can then select the focused sidebar row. Use `collapsed` when the layout depends on application state rather than size.
As with window breakpoints, give the window a minimum size the collapsed layout fits:
```tsx
import { AdwApplicationWindow } from "@gtkx/jsx/adw";
import { NavigationContainer } from "@gtkx/navigation";
export const App = () => (
);
```
`useSplitViewCollapsed()` tells the navigator's screens whether the panes are collapsed, whether `collapsed` or `collapseCondition` collapsed them. libadwaita's [`AdwSidebar`](https://gnome.pages.gitlab.gnome.org/libadwaita/doc/1-latest/class.Sidebar.html) switches to page mode with the breakpoint that collapses its split view, so a sidebar screen reads the hook instead of repeating the condition in a window breakpoint:
```tsx
import * as Adw from "@gtkx/gi/adw";
import { AdwSidebar, AdwSidebarItem, AdwSidebarSection } from "@gtkx/jsx/adw";
import {
type SplitViewScreenProps,
useSplitViewCollapsed,
} from "@gtkx/navigation";
const folders = ["Inbox", "Sent", "Archive"];
const Folders = ({
navigation,
}: SplitViewScreenProps) => {
const isCollapsed = useSplitViewCollapsed();
return (
{
const folder = folders[index];
if (folder) navigation.navigate("Messages", { folder });
}}
>
{folders.map((folder) => (
))}
);
};
```
The value changes after libadwaita has laid out the collapsed or widened panes, so use it for how a screen presents itself rather than to collapse anything.
In a collapsed split view, Back or Escape from the first content page returns directly to the sidebar. Sizing and sidebar placement are covered by the [split view configuration reference](/v2/reference/@gtkx/navigation/type-aliases/SplitViewNavigationConfig).
Focus follows the selected content route even when the sidebar remains visible. A sidebar's `useFocusEffect` therefore stops when a content page is selected; refresh sidebar data based on the data source or navigation state instead.
## Tab view navigator
`createTabViewNavigator` renders its routes as the pages of an `AdwTabView`, with an `AdwTabBar` under the header and an optional `AdwTabOverview`. Unlike the tab navigator, it opens any number of tabs from one screen, so a document or browser window declares the screen once and opens it repeatedly:
```tsx [src/documents.tsx]
import * as Gtk from "@gtkx/gi/gtk";
import { GtkBox, GtkButton, GtkLabel } from "@gtkx/jsx/gtk";
import {
createTabViewNavigator,
type TabViewScreenProps,
} from "@gtkx/navigation";
type DocumentParams = { Document: { title: string } };
const Tabs = createTabViewNavigator();
const Document = ({
route,
navigation,
}: TabViewScreenProps) => (
navigation.openTab(
"Document",
{ title: "Related" },
{ parent: route.key },
)
}
/>
);
export const Documents = () => (
({
name: "Document",
params: { title: "Untitled" },
}),
}}
screenOptions={({ route }) => ({ title: route.params.title })}
>
);
```
Captured from the sample above after clicking Open related in the first tab.
Tabs are addressed by route key. The navigation object adds [tab actions](/v2/reference/@gtkx/navigation/type-aliases/TabViewActionHelpers) such as `openTab`, `closeTab`, `selectTab` and `pinTab`, also available as `TabViewActions`. Opening with `parent` places the tab after its parent and the parent's descendants, and closing it selects that parent again. Pinned tabs stay ahead of the others; the state's `pinnedKeys` lists them.
[Screen options](/v2/reference/@gtkx/navigation/type-aliases/TabViewNavigationOptions) set the native tab page's properties, such as `title`, `icon`, `loading` and `needsAttention`. The header shows the window title unless `headerTitle` is set. Screens mount when first selected unless `lazy: false`.
`navigate` selects the last open tab of a screen and updates its params, or opens one when none is open. Give the screen a `getId` to identify tabs by their params: `navigate` and `openTab` then select the tab with the same id and open a new tab for a new id.
Native interaction flows back into the state: selecting a tab emits a cancellable `tabPress`, dragging reorders the route, and the close button dispatches `closeTab`, which `usePreventRemove` can refuse.
Closing the last tab is left unhandled, so a parent navigator or the container's `onUnhandledAction` decides whether the window closes. A tab view inside a section of the app has no window to close; set `replaceLastTab` there, and closing the last tab replaces it with a new tab of the initial route.
The overview's `open` follows the same rule as other [open-state props](/v2/guide/modals-and-portals#closing): when given, update it from `onOpenChange`, or leave it out to let the overview open and close on its own. The [tab view configuration reference](/v2/reference/@gtkx/navigation/type-aliases/TabViewNavigationConfig) lists the tab bar, overview, menu and drop target settings.
### Tab context menu
`renderMenu` declares the menu that right-clicking a tab or pressing Shift+F10 opens. It receives a ref to attach to a `GMenu` anywhere in what it returns, directly or through a component of yours that passes the ref on; the navigator renders the result outside the widget tree and uses that menu. `onSetupMenu` reports the tab the menu opens for, and `null` once it closes after the chosen action has run:
```tsx
import { GMenu, GSimpleAction } from "@gtkx/jsx/gio";
import { AdwApplicationWindow } from "@gtkx/jsx/adw";
import {
NavigationContainer,
TabViewActions,
useNavigationContainerRef,
} from "@gtkx/navigation";
import { useRef } from "react";
export const DocumentWindow = () => {
const navigation = useNavigationContainerRef();
const menuTab = useRef(null);
return (
navigation.dispatch(
TabViewActions.closeOtherTabs(
menuTab.current ?? undefined,
),
)
}
/>
}
>
(
)}
onSetupMenu={(route) => {
menuTab.current = route?.key ?? null;
}}
>
);
};
```
To reuse a menu model that already exists, such as one shared with another widget, pass it as `menuModel` instead. A navigator given both `renderMenu` and `menuModel` throws.
Without a tab from `onSetupMenu`, as when the same action runs from a shortcut, the actions act on the selected tab.
### Windows and transfers
libadwaita's `create-window` and `create-tab` signals expect an object before the handler returns, so the navigator creates native pages and views first and renders into them afterwards. Pass `onCreateWindow` to open a window for a tab dragged out: create an `Adw.TabView`, store it, and return it. Render the new window with its own `NavigationContainer` and a navigator that receives that view through the `view` prop; the transferred page becomes its initial route. A page dragged into another window is adopted by that navigator with its params, and its screen mounts again there, so keep tab state in params or an external store. `useTabView()` gives screens and header content the native view, `getPage(key)` and `transferTab(key, target)`.
The [Adwaita demo](https://github.com/gtkx-org/gtkx/tree/main/examples/adwaita-demo) shows the complete window lifecycle with menus, shortcuts and the overview.
## Nesting navigators
Use a navigator as a screen to nest it, for example a stack inside each drawer section. Set `headerShown: false` on the containing screen so only the inner navigator draws a header:
```tsx
import type { NavigatorScreenParams } from "@gtkx/navigation";
import { createDrawerNavigator, createStackNavigator } from "@gtkx/navigation";
type NotesParams = { List: undefined; Note: { id: string } };
type AppParams = {
Notes: NavigatorScreenParams;
Settings: undefined;
};
const Drawer = createDrawerNavigator();
const Stack = createStackNavigator();
const NotesStack = () => (
);
export const App = () => (
);
```
Hiding the drawer header also hides its toggle. Add a button to the inner stack's `headerStart` that dispatches `DrawerActions.toggleDrawer()`:
```tsx
import { GtkButton } from "@gtkx/jsx/gtk";
import { DrawerActions } from "@gtkx/navigation";
({
headerStart: (
navigation.dispatch(DrawerActions.toggleDrawer())
}
/>
),
})}
>
;
```
Route parameters and actions follow React Navigation's [nesting rules](https://reactnavigation.org/docs/nesting-navigators/).
## Hooks
Import React Navigation's hooks, such as [`useFocusEffect`](https://reactnavigation.org/docs/use-focus-effect/) and [`useNavigation`](https://reactnavigation.org/docs/use-navigation/), from `@gtkx/navigation`. `useTheme` returns the [container's theme](#navigationcontainer). GTKX adds [`useSplitViewCollapsed`](#split-view-navigator) for split view screens and [`useTabView`](#windows-and-transfers) for tab view screens and their header content.
## Static configuration
The navigators also accept React Navigation's [static configuration](https://reactnavigation.org/docs/static-configuration/). Import `createStaticNavigation` from `@gtkx/navigation`; the resulting component includes GTKX's `NavigationContainer`.
## Typing the root param list
Declare the root navigator once to type `useNavigation()` and navigation refs throughout the application:
```ts
import { createStackNavigator } from "@gtkx/navigation";
type RootParams = { List: undefined; Note: { id: string } };
const RootStack = createStackNavigator();
type RootStackType = typeof RootStack;
declare module "@react-navigation/core" {
interface RootNavigator extends RootStackType {}
}
```
GTKX uses the interface declared by `@react-navigation/core`, so augment that module. Install it directly with `npm install @react-navigation/core@^7`: pnpm keeps transitive dependencies out of the project's `node_modules`, and TypeScript cannot augment a module it cannot resolve. Until it resolves, `navigate` from `useNavigation()` rejects every route, typed as `never`. The same pattern works with a static navigator. See React Navigation's [TypeScript guide](https://reactnavigation.org/docs/typescript/) for nested screens and inferred route parameters.
## Testing
Drive the rendered widgets with `@gtkx/testing`. Animations are disabled by default, and queries find the visible page:
```tsx
import * as Gtk from "@gtkx/gi/gtk";
import { NavigationContainer } from "@gtkx/navigation";
import { render, screen, userEvent } from "@gtkx/testing";
import { expect, it } from "vitest";
it("opens a note and comes back", async () => {
await render(
,
);
await userEvent.click(
await screen.findByRole(Gtk.AccessibleRole.BUTTON, {
name: "Open note 42",
}),
);
await screen.findByText("Showing note 42");
await userEvent.click(
screen.getByRole(Gtk.AccessibleRole.BUTTON, { name: "Back" }),
);
expect(screen.queryByText("Showing note 42")).toBeNull();
});
```
For tab navigation, query the view switcher's `Gtk.AccessibleRole.TAB` and its label. `userEvent.keyboard(widget, "{Escape}")` exercises native back navigation. See [Testing](/v2/guide/testing) for setup and query behavior.
---
---
title: "Forms"
description: "Connect React Hook Form to native Adwaita rows, focus and validation feedback."
---
# Forms
`@gtkx/forms` connects [React Hook Form](https://react-hook-form.com) to native Adwaita rows. This page covers what is GTKX-specific: native input, focus and validation feedback. For form state, validation rules and submission, see the [React Hook Form documentation](https://react-hook-form.com/docs).
Install the package:
```bash
npm install @gtkx/forms@beta
```
The rows use the generated `@gtkx/jsx/adw` bindings included in GTKX 2 projects.
## Connect a form
Pass `control={form.control}` to infer the row's field names from your form type. GTK buttons submit through `onClicked`:
```tsx [src/preferences-form.tsx]
import { ComboRow, EntryRow, useForm } from "@gtkx/forms";
import * as Gtk from "@gtkx/gi/gtk";
import { AdwPreferencesGroup } from "@gtkx/jsx/adw";
import { GtkBox, GtkButton } from "@gtkx/jsx/gtk";
type Preferences = { displayName: string; theme: string };
const themes = [
{ id: "system", value: "Follow system" },
{ id: "light", value: "Light" },
{ id: "dark", value: "Dark" },
];
export const PreferencesForm = ({
onSave,
}: {
onSave: (values: Preferences) => void;
}) => {
const form = useForm({
defaultValues: { displayName: "", theme: "system" },
});
const submit = form.handleSubmit(onSave);
return (
{
void submit();
}}
/>
);
};
```
You can also import `FormProvider` from `@gtkx/forms` to supply the control to rows below it. When a row relies on the provider, give it the form type explicitly, such as ` name="displayName" />`, to check its field name.
## React Compiler
GTKX compiles components with the React Compiler [by default](/v2/guide/configuration-and-codegen#every-option), so read a field with `useWatch` rather than `form.watch`. As [React Hook Form documents](https://react-hook-form.com/docs/useform/watch), the compiler can cache what `watch` returns, and the component keeps showing a stale value after `setValue`:
```tsx
import { useWatch } from "@gtkx/forms";
const theme = useWatch({ control: form.control, name: "theme" });
```
React Hook Form also updates nested `formState.errors` objects in place, so the compiler can keep rendering an old result for a message read below a field array or a nested object. For example, once `errors.stops` holds an error for an empty row, a field array `validate` rule that fails on submit adds `root` to that same object, and a label showing `errors.stops?.root?.message` never appears. Add the [`"use no memo"`](https://react.dev/reference/react-compiler/directives/use-no-memo) directive at the top of a component that renders such messages:
```tsx
import { useFieldArray, useForm } from "@gtkx/forms";
import { GtkLabel } from "@gtkx/jsx/gtk";
type Trip = { stops: { city: string; nights: number }[] };
const StopsError = () => {
"use no memo";
const form = useForm({ defaultValues: { stops: [] } });
useFieldArray({
control: form.control,
name: "stops",
rules: {
validate: (stops) => stops.length <= 6 || "Plan at most six stops",
},
});
const message = form.formState.errors.stops?.root?.message;
return message ? : null;
};
```
## Choose a row
| Row | Stored value |
| ------------------------------ | ------------ |
| `EntryRow`, `PasswordEntryRow` | Text |
| `SwitchRow` | Boolean |
| `SpinRow` | Number |
| `ComboRow` | Item ID |
The rows retain their native props, children, refs and signal handlers.
Set a spin row's range with a JSX `GtkAdjustment` in its `adjustment` prop, such as `adjustment={}`. The form owns the current value, so change it with `setValue` or `reset`. The row shows those values without reporting them as edits, so the options you pass to `setValue` alone decide dirty state and validation.
If GTK clamps a value to the adjustment's range or cuts text at `maxLength`, the form keeps the stored value and submits it. The row is marked invalid, and a development build logs a warning, until an edit replaces the value.
`ComboRow` takes the same `items`, `sections` and renderers as the [collection `DropDown`](/v2/guide/components#dropdown) and stores the selected item's ID, which stays stable when items move or their labels change. Passing `control` also lets TypeScript infer item and section types for renderers.
A form `ComboRow` uses a non-nullable string field. Supply an explicit default ID that exists in its choices. An empty source preserves that ID, so asynchronously reloaded choices restore the selection without changing the form's value or dirty state. See the [React Hook Form defaults guidance](https://react-hook-form.com/docs/useform#defaultValues) for asynchronous defaults and resets.
## Native validation feedback
An invalid row gains Adwaita's `error` CSS class. The row and, for text and spin rows, the field that receives focus expose an accessible invalid state. When validation supplies a message, the row uses it as its tooltip. Correcting the field restores the caller's classes and tooltip.
Captured from the form above after clicking Save with an empty display name. The row has the error class and the focus.
The rows do not add a persistent error label. Render one beside the row when your application needs visible feedback. Native handlers such as `onNotifyText` still run after the form receives an edit.
## Focus and disabled fields
Form focus operations, including focus on the first invalid field, reach the native row through `grabFocus()`. Text and spin rows also support `setFocus(name, { shouldSelect: true })`. Forwarded refs receive the native row and preserve React callback-ref cleanup.
Leaving the row's native subtree marks the field touched and supports blur validation. Moving focus between widgets inside the same row does not. Any controllers passed through `controllers` remain attached alongside this tracking.
`disabled` makes a row insensitive and omits its value from submission. Use the native `sensitive={false}` prop when the value should remain in the submitted form. Disabling the whole form also disables its rows.
## Other GTK controls
For a control without a form row, use [`Controller`](https://react-hook-form.com/docs/usecontroller/controller) from `@gtkx/forms` and connect its `field` to the control's props and signals:
```tsx
import { Controller, useForm } from "@gtkx/forms";
import { GtkCheckButton, GtkEventControllerFocus } from "@gtkx/jsx/gtk";
type Terms = { accepted: boolean };
export const TermsForm = () => {
const form = useForm({ defaultValues: { accepted: false } });
return (
(
field.onChange(button.getActive())}
ref={(button) =>
field.ref(button && { focus: () => button.grabFocus() })
}
cssClasses={fieldState.invalid ? ["error"] : []}
controllers={
}
/>
)}
/>
);
};
```
`field.ref` needs a handle with a no-argument `focus()` method. Passing the widget directly does not work, because GTK's `focus` method expects a direction. `GtkEventControllerFocus` reports when focus leaves the control, which marks the field touched.
See the [forms reference](/v2/reference/@gtkx/forms/) for GTKX prop types and the [testing guide](/v2/guide/testing) for driving native controls.
---
---
title: "Actions and Shortcuts"
description: "Declare application and window actions, and reach them from menus, buttons, keyboard accelerators and the shortcuts dialog."
---
# Actions and Shortcuts
A command that a menu item, a button and a keyboard shortcut all run is a GTK [action](https://docs.gtk.org/gtk4/actions.html): a named `Gio.Action` that each of them activates by its prefixed name, such as `win.new`. This page declares actions in JSX and connects menus, buttons, accelerators and the shortcuts dialog to them.
## Declaring actions
Pass `GSimpleAction` elements to the `actions` prop of the application element or a window. Actions on the application are named `app.`, and those on an `AdwApplicationWindow` or `GtkApplicationWindow` are named `win.`:
```tsx [src/components/window.tsx]
import { AdwApplicationWindow } from "@gtkx/jsx/adw";
import { GSimpleAction } from "@gtkx/jsx/gio";
import { GtkLabel } from "@gtkx/jsx/gtk";
import { quit } from "@gtkx/react";
import { useState } from "react";
export const Window = () => {
const [count, setCount] = useState(0);
return (
setCount(count + 1)}
/>
0}
onActivate={() => setCount(0)}
/>
>
}
>
);
};
```
The `actions` prop belongs to every element whose class implements `Gio.ActionMap`. An action is added when its element mounts and removed when it unmounts. `enabled={false}` greys out every menu item and button that points at the action and stops its accelerators.
### Parameters and state
An action with a `parameterType` receives a `GLib.Variant` when activated. Menu items and buttons pass it as their target:
```tsx
import * as GLib from "@gtkx/gi/glib";
import { GSimpleAction } from "@gtkx/jsx/gio";
export const OpenAction = ({ onOpen }: { onOpen: (name: string) => void }) => (
{
if (parameter !== null) onOpen(parameter.getString()[0]);
}}
/>
);
```
An action with a `state` is a toggle or a choice. Render the state from React and update it in `onChangeState`, which receives the requested value. A menu item shows a boolean state as a check box:
```tsx
import * as GLib from "@gtkx/gi/glib";
import { GSimpleAction } from "@gtkx/jsx/gio";
export const PreviewAction = ({
preview,
onPreviewChange,
}: {
preview: boolean;
onPreviewChange: (preview: boolean) => void;
}) => (
{
if (value !== null) onPreviewChange(value.getBoolean());
}}
/>
);
```
Activating a boolean action without a parameter requests the opposite state, so the menu item toggles it without an `onActivate` handler. See [`Gio.SimpleAction`](https://docs.gtk.org/gio/class.SimpleAction.html) for the native rules.
### Actions for one widget
Actions that belong to part of the window, such as a tab's context menu, go in a `GSimpleActionGroup` in that widget's `actionGroups` prop. Its `prefix` names them, and they reach the widget and its descendants:
```tsx
import { GSimpleAction, GSimpleActionGroup } from "@gtkx/jsx/gio";
import { GtkBox } from "@gtkx/jsx/gtk";
export const NoteTab = ({
onPin,
onClose,
}: {
onPin: () => void;
onClose: () => void;
}) => (
>
}
/>
}
/>
);
```
## Menus
`GMenu` describes a menu as data. Pass it as the `menuModel` of a `GtkMenuButton`, or of a `GtkPopoverMenu` for a context menu, and point each item at an action:
```tsx [src/components/main-menu.tsx]
import { GMenu } from "@gtkx/jsx/gio";
import { GtkMenuButton } from "@gtkx/jsx/gtk";
export const MainMenu = () => (
}
/>
);
```
Captured from the sample above, in a window that declares its actions and their accelerators. The check mark is the state of win.preview.
`section` groups items between separators, and `submenu` opens a nested menu. An item for an action with a parameter names its target in the action string, as in `win.open('todo.md')`. The menu rebuilds when `items` changes. Items also take GTK's other [menu attributes](https://docs.gtk.org/gtk4/class.PopoverMenu.html#menu-models) in camelCase, such as `icon`, and [Widgets in menus](/v2/guide/components#widgets-in-menus) puts a widget in place of an item.
An item whose action is disabled is greyed out; `hiddenWhen: "action-disabled"` hides it instead. `primary` makes F10 open the main menu, as the [GNOME HIG](https://developer.gnome.org/hig/reference/keyboard.html) expects.
## Buttons
Any widget that implements `Gtk.Actionable`, such as `GtkButton`, `GtkToggleButton` or `GtkCheckButton`, runs an action through its `actionName`, and passes `actionTarget` as the parameter:
```tsx [src/components/toolbar.tsx]
import * as GLib from "@gtkx/gi/glib";
import { GtkButton } from "@gtkx/jsx/gtk";
export const Toolbar = () => (
<>
>
);
```
Captured from the sample above at the start of a header bar, in a window that declares win.new and win.open.
The button follows the action's `enabled` state. A toggle button for a stateful action shows the action's state.
## Keyboard accelerators
Bind keys to actions with the application element's `actionAccels` prop. Each entry takes the detailed action name and one or more accelerators in GTK's [accelerator syntax](https://docs.gtk.org/gtk4/func.accelerator_parse.html):
```tsx [src/app.tsx]
import { AdwApplication } from "@gtkx/jsx/adw";
import { GSimpleAction } from "@gtkx/jsx/gio";
import { quit } from "@gtkx/react";
import { Window } from "./components/window.js";
export const App = () => (
n"] },
{
detailedActionName: "win.shortcuts",
accels: ["question"],
},
{ detailedActionName: "app.quit", accels: ["q"] },
]}
actions={ quit()} />}
>
);
```
The keys work in every window that has the action, and menus show them beside the item. Removing an entry clears its accelerators. [Keyboard](https://developer.gnome.org/hig/guidelines/keyboard.html) in the GNOME HIG lists the standard keys.
### Shortcuts without an action
A key that runs code without an action, or that only applies in part of the window, uses a `GtkShortcutController` in a widget's `controllers` prop:
```tsx [src/components/search-shortcut.tsx]
import * as Gtk from "@gtkx/gi/gtk";
import {
GtkCallbackAction,
GtkShortcut,
GtkShortcutController,
GtkShortcutTrigger,
} from "@gtkx/jsx/gtk";
export const SearchShortcut = ({
onToggleSearch,
}: {
onToggleSearch: () => void;
}) => (
}
action={
{
onToggleSearch();
return true;
}}
/>
}
/>
}
/>
);
```
Add it as `controllers={}` on the window. `GLOBAL` scope handles the key anywhere in the window. A callback that returns `false` leaves the key unhandled, so other handlers still receive it. See [`Gtk.ShortcutController`](https://docs.gtk.org/gtk4/class.ShortcutController.html) for the other scopes.
## The shortcuts dialog
`AdwShortcutsDialog` lists the app's shortcuts. Give an item the `actionName` of an action with an accelerator, and it shows the keys from `actionAccels`; give it an `accelerator` for keys that no action owns:
```tsx [src/components/shortcuts.tsx]
import {
AdwShortcutsDialog,
AdwShortcutsItem,
AdwShortcutsSection,
} from "@gtkx/jsx/adw";
export const Shortcuts = ({ onClose }: { onClose: () => void }) => (
);
```
Captured from the sample above, in an app with the accelerators from Keyboard accelerators.
The items describe shortcuts; they do not register them. Render the dialog from state that a `win.shortcuts` action sets, and clear that state in `onClosed`, as [Dialogs](/v2/guide/modals-and-portals#dialogs) shows.
## Actions in a registered class
A [registered class](/v2/guide/subclassing) that builds its own action group, such as a widget with a context menu, adds a table of actions with `addActionEntries`, GJS's `add_action_entries` and C's `g_action_map_add_action_entries`. Every `Gio.ActionMap` has it, including `Gio.SimpleActionGroup`, `Gtk.Application`, `Adw.Application`, `Gtk.ApplicationWindow` and the classes registered from them:
```ts
import * as Gio from "@gtkx/gi/gio";
import * as Gtk from "@gtkx/gi/gtk";
import { registerClass } from "@gtkx/runtime";
class ChartBase extends Gtk.Widget {
declare private chartActions: Gio.SimpleActionGroup;
declare depth: number;
override vfuncConstructed(): void {
super.vfuncConstructed();
this.depth = 5;
this.chartActions = new Gio.SimpleActionGroup();
this.chartActions.addActionEntries([
{ name: "zoom-in", activate: () => this.setDepth(this.depth - 1) },
{ name: "zoom-out", activate: () => this.setDepth(this.depth + 1) },
{
name: "set-depth",
parameterType: "i",
activate: (_action, depth) =>
this.setDepth(depth?.getInt32() ?? 5),
},
{
name: "show-hidden",
state: "false",
changeState: (action, value) => {
if (value !== null) action.setState(value);
this.queueDraw();
},
},
]);
this.insertActionGroup("chart", this.chartActions);
}
setDepth(depth: number): void {
this.depth = Math.max(1, depth);
this.queueDraw();
}
}
export const Chart = registerClass(ChartBase, { typeName: "ExampleChart" });
```
A menu item with the action `chart.zoom-in` then activates the first entry. Each entry, typed as `Gio.ActionEntryObj`, takes GJS's fields in camelCase:
- `name`, the action's name.
- `activate(action, parameter)`, connected to the action's `activate` signal.
- `parameterType`, a GVariant type string such as `"s"` or a `GLib.VariantType`. Without it, the action takes no parameter.
- `state`, the initial state in GVariant text such as `"'large'"` or `"true"`, a boolean or a `GLib.Variant`. Without it, the action is stateless.
- `changeState(action, value)`, connected to `change-state`. Without it, a change request sets the state directly.
As in GJS and C, both callbacks receive the action first and run with `this` set to it; a handler passed to `connect` receives only the signal's arguments. An entry without a string name, an invalid `parameterType` or a `state` that does not parse throws, and the entries before it stay added. `removeActionEntries` takes the same entries and removes the actions they name.
---
---
title: "Native State"
description: "Follow GObject properties and signals from components, reach the application, and read, write and bind GSettings keys."
---
# Native State
Some state lives in native objects rather than in React: the dark style in `Adw.StyleManager`, the clipboard's contents, the user's preferences in GSettings. The hooks on this page connect a component to that state, re-render it on changes and disconnect when it unmounts. Props cover the objects JSX renders; these hooks cover everything else and the objects you hold through a ref.
## Following a property
`useProperty(object, name)` returns a GObject property's current value and re-renders when it changes. Property names are camelCase, as in props:
```tsx [src/components/theme-icon.tsx]
import * as Adw from "@gtkx/gi/adw";
import { GtkImage } from "@gtkx/jsx/gtk";
import { useProperty } from "@gtkx/react";
export const ThemeIcon = () => {
const dark = useProperty(Adw.StyleManager.getDefault(), "dark");
return (
);
};
```
`dark` is a `boolean`, typed from the property. To style by the color scheme, prefer the media queries in [CSS](/v2/guide/css#follow-appearance-preferences); follow the property when the component's output changes.
### Objects that JSX creates
For an instance created by JSX, use a state setter as its callback ref and pass the state to the hook:
```tsx
import type * as Gtk from "@gtkx/gi/gtk";
import { GtkEntry, GtkLabel } from "@gtkx/jsx/gtk";
import { useProperty } from "@gtkx/react";
import { useState } from "react";
export const EntryLength = () => {
const [entry, setEntry] = useState(null);
const length = useProperty(entry, "textLength");
return (
<>
>
);
};
```
The hook returns `undefined` while its target is absent, and its type includes `undefined` only when the target's type allows `null` or `undefined`. React state keeps the subscription aligned when the element mounts, is replaced or unmounts. `useSignal` and `useBindSetting` take instances the same way; mutable ref objects are not subscription targets. Properties that a [registered class](/v2/guide/subclassing#properties) declares work the same, with their declared types.
## Connecting a signal
`useSignal(object, signal, handler)` connects a handler for the component's lifetime and reconnects when the object changes. Each emission runs the handler from the latest render, so it can read props and state without reconnecting. `isImmediate: true` also runs it once, with no arguments, when it connects, which reads the initial state:
```tsx [src/components/paste-button.tsx]
import * as Gdk from "@gtkx/gi/gdk";
import { GtkButton } from "@gtkx/jsx/gtk";
import { useSignal } from "@gtkx/react";
import { useState } from "react";
export const PasteButton = ({ onPaste }: { onPaste: () => void }) => {
const clipboard = Gdk.Display.getDefault()?.getClipboard() ?? null;
const [hasText, setHasText] = useState(false);
useSignal(
clipboard,
"changed",
() =>
setHasText(
clipboard?.getFormats().containMimeType("text/plain") ?? false,
),
{
isImmediate: true,
},
);
return (
);
};
```
The signal name is typed from the object, and accepts a `::detail` suffix such as `notify::dark`. `isAfter: true` runs the handler after the object's default handler. For a signal of an element you render, use its `on…` prop instead.
## The application
`useApplication()` returns the `Gtk.Application` of the nearest [application element](/v2/guide/application-lifecycle#the-application-element), and throws outside one:
```tsx [src/hooks/use-notify.ts]
import * as Gio from "@gtkx/gi/gio";
import { useApplication } from "@gtkx/react";
export const useNotify = (): ((title: string) => void) => {
const application = useApplication();
return (title) => {
application.sendNotification(null, Gio.Notification.new(title));
};
};
```
Use it for the application's own methods: notifications, its D-Bus connection ([Exporting an object](/v2/guide/dbus#exporting-an-object)), its windows, or a [`hold()`](/v2/guide/application-lifecycle#when-the-app-ends) for background work.
## Settings
GSettings stores preferences outside the app, where they survive restarts and are shared by every running instance. The [GSettings reference](https://docs.gtk.org/gio/class.Settings.html) covers schemas and their native storage; GTKX compiles your schema, types its keys, and provides hooks to read, write and bind them.
### Your app's schema
Write the schema in a `.gschema.xml` file, usually `data/.gschema.xml` with the application ID as the schema ID:
```xml [data/com.example.Notes.gschema.xml]
'default'Color scheme800Window width
```
Import the file without a query wherever a hook needs it. GTKX compiles and bundles the schema, and codegen writes its types beside it as `com.example.Notes.gschema.d.xml.ts`, which TypeScript reads with `allowArbitraryExtensions`; the scaffold's `tsconfig.json` enables it, and its `.gitignore` leaves out `*.d.xml.ts`. The import's default export describes the file's first schema, and every schema in the file is also a named export (`com_example_Notes` here). The hooks use that description to check key names and value types:
```ts
import schema from "../data/com.example.Notes.gschema.xml";
```
GTKX installs schemas by file name, so imported schema files that share a name must be identical, including [copies in workspace packages](/v2/guide/workspaces#workspace-sources); otherwise GTKX stops with an error naming both.
A schema without a `path` attribute is relocatable: give `GSettings` a `path` too, and each path keeps its own values.
[Translate settings schemas](/v2/guide/internationalization#translate-settings-schemas) covers the schema text, and [Test data and settings](/v2/guide/testing#test-data-and-settings) how tests start from the defaults.
### The settings instance
The hooks take a `Gio.Settings` instance. Render `GSettings` at the top level with a portal, keep the instance in state, and share it with [React context](https://react.dev/learn/passing-data-deeply-with-context):
```tsx [src/settings.tsx]
import type * as Gio from "@gtkx/gi/gio";
import { GSettings } from "@gtkx/jsx/gio";
import { createPortal, rootElement } from "@gtkx/react";
import { createContext, type ReactNode, use, useState } from "react";
import schema from "../data/com.example.Notes.gschema.xml";
const SettingsContext = createContext(null);
export const SettingsProvider = ({ children }: { children: ReactNode }) => {
const [settings, setSettings] = useState(null);
return (
<>
{createPortal(
,
rootElement,
)}
{settings !== null && (
{children}
)}
>
);
};
export const useAppSettings = (): Gio.Settings => {
const settings = use(SettingsContext);
if (settings === null) throw new Error("SettingsProvider is required");
return settings;
};
```
Wrap the windows inside the application element in `SettingsProvider`. The provider renders its children once the instance exists, so `useAppSettings()` always returns one.
### Reading and writing a key
`useSetting(settings, schema, key)` returns the key's value and a setter, and re-renders when the value changes, including from another instance or `gsettings set`:
```tsx [src/components/dark-style-row.tsx]
import { AdwSwitchRow } from "@gtkx/jsx/adw";
import { useSetting } from "@gtkx/react";
import schema from "../../data/com.example.Notes.gschema.xml";
import { useAppSettings } from "../settings.js";
export const DarkStyleRow = () => {
const [scheme, setScheme] = useSetting(
useAppSettings(),
schema,
"color-scheme",
);
return (
setScheme(active ? "dark" : "default")}
/>
);
};
```
`scheme` is `"default" | "light" | "dark"`, from the key's ``. The schema's `values` holds those choices as a readonly tuple, so `(typeof schema.values)["color-scheme"][number]` names the type and `schema.values["color-scheme"]` lists them at runtime. Other keys read as their unpacked GVariant type, such as a `number` for `i` and a `bigint` for `x`. A key declared with `enum` or `flags` reads as a number, and `values` maps each nick to its number. A key the schema does not declare fails `tsc`, and so does a value of the wrong type.
### Binding a key to a property
`useBindSetting` keeps a key and an object's property in step, both ways by default, with no React state between them. Use it for values the widget owns, such as a window's size:
```tsx
import type * as Adw from "@gtkx/gi/adw";
import { AdwApplicationWindow } from "@gtkx/jsx/adw";
import { quit, useBindSetting } from "@gtkx/react";
import { useState } from "react";
import schema from "../../data/com.example.Notes.gschema.xml";
import { useAppSettings } from "../settings.js";
export const Window = () => {
const settings = useAppSettings();
const [window, setWindow] = useState(null);
useBindSetting({
settings,
schema,
key: "window-width",
object: window,
property: "defaultWidth",
});
return (
);
};
```
The bind waits for the mounted window, restores the saved width, and writes changes back. `flags` takes [`Gio.SettingsBindFlags`](https://docs.gtk.org/gio/flags.SettingsBindFlags.html), such as `GET` to only read the key.
### System schemas
Schema imports type only the schemas the project ships. To read a schema installed on the system, such as `org.gnome.desktop.interface` for the desktop's fonts and color scheme, describe the keys the app uses in an object that satisfies `SettingsSchema`:
```tsx [src/components/system-appearance.tsx]
import type * as Gio from "@gtkx/gi/gio";
import { AdwActionRow } from "@gtkx/jsx/adw";
import { GSettings } from "@gtkx/jsx/gio";
import {
createPortal,
rootElement,
type SettingsSchema,
useSetting,
} from "@gtkx/react";
import { useState } from "react";
const desktopInterface = {
id: "org.gnome.desktop.interface",
path: null,
keys: { "monospace-font-name": "s", "color-scheme": "enum" },
values: {
"color-scheme": { default: 0, "prefer-dark": 1, "prefer-light": 2 },
},
} as const satisfies SettingsSchema;
const AppearanceRows = ({ settings }: { settings: Gio.Settings }) => {
const [font] = useSetting(
settings,
desktopInterface,
"monospace-font-name",
);
const [scheme] = useSetting(settings, desktopInterface, "color-scheme");
const prefersDark =
scheme === desktopInterface.values["color-scheme"]["prefer-dark"];
return (
<>
>
);
};
export const SystemAppearance = () => {
const [settings, setSettings] = useState(null);
return (
<>
{createPortal(
,
rootElement,
)}
{settings !== null && }
>
);
};
```
Captured from the sample above, with its rows inside an AdwPreferencesGroup. The subtitles are the values of the two desktop keys.
`keys` maps each key to its GVariant type string, or to `enum` or `flags` for a key declared with those attributes; `values` gives the number of each enum nick, or the allowed strings of a key with choices. Copy the key types from the installed `.gschema.xml` under `/usr/share/glib-2.0/schemas`, and the enum numbers from the `.enums.xml` file that declares the enum, here `org.gnome.desktop.enums.xml`. Keep `as const satisfies SettingsSchema` so the hooks see literal types: `font` is a `string`, `scheme` is `0 | 1 | 2`, and a key the object does not list fails `tsc`.
GTKX does not bundle or compile a system schema; the app reads the copy installed on the user's machine. TypeScript cannot check the object against that copy. As in GJS, `GSettings` throws when the schema is not installed, and reading a key the installed schema does not declare throws, so an [error boundary](/v2/guide/error-handling#react-error-boundaries) can handle a missing package or a misspelled name.
---
---
title: "Animations"
description: "Animate native widget properties and GTK styles with React Spring."
---
# Animations
`@gtkx/animated` adapts [React Spring](https://www.react-spring.dev) to GTKX. Learn how to create and control springs in the React Spring docs; this guide covers how those values reach native GTKX elements. Install the package separately:
```bash
npm install @gtkx/animated@beta
```
## Animated components
`animated(Component)` wraps a GTKX element so its mutable props accept values from React Spring. Create the wrapper at module scope, then pass it the values a hook returns:
```tsx
import { animated, useSpring } from "@gtkx/animated";
import { GtkLabel } from "@gtkx/jsx/gtk";
const AnimatedLabel = animated(GtkLabel);
export const FadeIn = () => {
const styles = useSpring({ from: { opacity: 0 }, to: { opacity: 1 } });
return ;
};
```
Wrap generated elements, non-widget objects such as `GtkAdjustment`, or your own components. There is no `animated.div`-style element map as in `@react-spring/web`; pass `animated` the element you import.
For writable GObject props, each frame updates the native object through its `ref` without re-rendering the component. This includes `opacity`, margins, size requests, and adjustment values. Construct-only props remain static, and TypeScript rejects springs passed to them. A label's text children also accept animated values, alone or next to static text:
```tsx
const { count } = useSpring({ from: { count: 0 }, to: { count: 100 } });
{count.to((value) => value.toFixed(0))}
{" items"}
;
```
GTKX truncates whole-number properties, such as margins, toward zero and clamps values to the native property range. An opacity spring cannot exceed 1, and margins cannot be negative. To slide a widget using a margin, animate from a positive margin to zero.
A custom component that forwards its `ref` to the native object receives the same updates. Otherwise, and for props that are not GObject properties, such as `accessible*`, the wrapper re-renders the component with the current values on each frame.
## Animated styles
The [`style` prop](/v2/guide/css#style-one-widget) accepts springs too. GTKX writes animated declarations into its shared `Gtk.CssProvider` without re-rendering the component, and reloads the provider once for all the updates of one frame. A spring can drive the whole object or one declaration:
```tsx [src/deadline.tsx]
import { animated, useSpring } from "@gtkx/animated";
import { GtkLabel } from "@gtkx/jsx/gtk";
const AnimatedLabel = animated(GtkLabel);
const overdueColor = (value: number) => ({
color: `mix(var(--window-fg-color), var(--error-color), ${value})`,
});
export const Deadline = ({ isOverdue }: { isOverdue: boolean }) => {
const { level } = useSpring({ level: isOverdue ? 1 : 0 });
return ;
};
```
Recorded from the sample above while isOverdue turns on, then off.
The spring carries a number and the interpolation builds the declaration around it. A spring returned by `useSpring` can also be passed directly as the style object or placed on one declaration:
```tsx
const styles = useSpring({ from: { color: "red" }, to: { color: "blue" } });
;
;
```
Nested blocks work too, so `style={{ "&:hover": { color: styles.color } }}` is animated without a React render. Only `style` is read this way; a spring nested inside another object-valued prop is not tracked.
A provider reload invalidates styling across the display. Prefer a native property for effects it can express, or a CSS `transition` or `@keyframes` for a fixed state change. Use animated `style` for dynamic CSS values, and profile large trees with many animations. For custom drawing, call `queueDraw()` on a [`GtkDrawingArea`](/v2/guide/cairo#draw-in-a-widget) as values change.
## Moving widgets
To animate position, use a container that exposes it. Inside a `GtkFixed`, the `transform` of a `GtkFixedLayoutChild` is a `Gsk.Transform`, and an interpolation builds one from the spring:
```tsx [src/slide.tsx]
import { animated, useSpring } from "@gtkx/animated";
import * as Graphene from "@gtkx/gi/graphene";
import * as Gsk from "@gtkx/gi/gsk";
import { GtkButton, GtkFixed, GtkFixedLayoutChild } from "@gtkx/jsx/gtk";
const AnimatedFixedLayoutChild = animated(GtkFixedLayoutChild);
const translate = (x: number): Gsk.Transform | null =>
Gsk.Transform.new().translate(new Graphene.Point({ x, y: 0 }));
export const Slide = ({ isOpen }: { isOpen: boolean }) => {
const { x } = useSpring({ x: isOpen ? 240 : 0 });
return (
);
};
```
Recorded from the sample above while isOpen turns on, then off.
Elsewhere, animate the margins, the size requests, a `Gtk.Paned`'s `position`, or a CSS `transform` through `style`, which changes the painted position without changing layout.
## React Spring APIs
`@gtkx/animated` re-exports React Spring's platform-neutral APIs, so import hooks such as `useSpring` and `useTransition` from it rather than from `@react-spring/web`. DOM hooks such as [`useScroll`](https://www.react-spring.dev/docs/utilities/use-scroll) and [`useInView`](https://www.react-spring.dev/docs/utilities/use-in-view) have no GTK counterpart and are not exported.
## The frame clock
Frames advance during the update phase of a mapped window's GTK frame clock, before layout and painting. GTKX keeps using that window while it can supply frames, switching to another mapped window or a timer when necessary.
## Reduced motion
GTK exposes two settings with different effects:
- `gtk-enable-animations` disables motion across the toolkit. When false, GTKX springs jump to their targets while still running their lifecycle callbacks, and a `loop` stops after its current pass. GTKX applies each change of this setting to React Spring's [`Globals.skipAnimation`](https://www.react-spring.dev/docs/advanced/globals), so an in-app preference can set `skipAnimation` itself; the next change of the setting overrides it.
- `gtk-interface-reduced-motion`, available in GTK 4.22 and later, asks applications to reduce motion. It also drives GTK's `prefers-reduced-motion` media query. Springs keep running; the component chooses an alternative, such as a fade instead of a slide.
`useReducedMotion()` returns `true` when either preference calls for less motion, `false` otherwise, and `null` before a display is open. It updates when the settings change.
`@gtkx/testing` disables animations by default, so springs reach their targets on the first frame. Assert the result with `findBy*` or `waitFor`. Pass `areAnimationsEnabled: true` to `render` when the test needs to exercise motion.
---
---
title: "Internationalization"
description: "Translate GTKX applications and package metadata with gettext catalogs."
---
# Internationalization
`@gtkx/i18n` connects i18next and react-i18next to GNU gettext. Your application's production `applicationId` is its gettext domain, and the catalogs in `po/` translate both the application and its desktop metadata. GTKX manages `po/` only in projects that install `@gtkx/i18n`, so an existing gettext setup, such as a Meson project's, stays untouched until then.
Install `@gtkx/i18n@beta` and GNU gettext 0.23 or later. On Fedora 44:
```bash
npm install @gtkx/i18n@beta
sudo dnf install gettext
xgettext --version
msgfmt --version
```
Codegen, development and builds run the gettext tools (`xgettext`, `msginit`, `msgmerge`, `msgfmt` and others), so they must be on `PATH`. Some distributions package them separately, such as `gettext-tools` on openSUSE.
## Create a catalog
Add `po/LINGUAS` at the project root, with one locale per line:
```text
fr
```
Write source messages with `t`:
```tsx
import { t } from "@gtkx/i18n";
import { GtkLabel } from "@gtkx/jsx/gtk";
;
```
Run codegen:
```bash
gtkx codegen
```
GTKX creates the template `po/.pot`, a PO file for each listed locale, and translation types. Translators edit each catalog's `msgstr` values.
Run codegen again after changing messages. It updates the template and merges the changes into the catalogs. Review fuzzy entries before release; removed messages remain as obsolete entries.
When `msginit` has no plural rule for a locale, such as `ar` or `zh_CN`, its catalog starts with a placeholder `Plural-Forms` header. Replace it before translating plural messages.
Messages come from the `src` directory, or the project root without one, and from the workspace packages the application uses from source, as described in [Workspace sources](/v2/guide/workspaces#workspace-sources). Their template locations are relative to the application, such as `../../packages/ui/src/rating.tsx:18`, and the application's catalogs translate them. Messages of packages installed from a registry are not extracted.
## Plurals and context
For a plural message, provide the singular and plural source strings through `defaultValue_one` and `defaultValue_other`:
```tsx
const label = t("{{count}} file", {
count: files.length,
defaultValue_one: "{{count}} file",
defaultValue_other: "{{count}} files",
});
```
Gettext chooses the translated form using the catalog's plural rule. Counts must be non-negative safe integers. GTKX extraction requires both source forms and rejects i18next options that cannot be represented by this gettext entry, such as ordinal plurals and zero-specific defaults. Write both options out even when the English forms read the same, as in `{{count}} installed`: the message still gets a plural entry, and languages such as Italian translate it with two forms.
A `Trans` component takes the same options through `tOptions`, with the count in its `count` prop:
```tsx
```
Use `context` when the same source text has different meanings:
```tsx
const command = t("Open", { context: "menu command" });
```
A missing contextual entry falls back to the ordinary message. A missing message uses its source text or `defaultValue`.
## Comments for translators
A comment that starts with `Translators:` right before a message reaches translators as an extracted comment (`#.`) in the template and in every catalog, as xgettext's `--add-comments=Translators:` does for Meson projects:
```tsx
// Translators: {{index}} is the number of the new recording.
const name = t("Recording {{index}}", { index });
;
```
- The comment belongs to the next `t` call or `Trans` element when only whitespace and other comments come between them, so it can sit on the lines above or earlier on the same line.
- Before an element in JSX children, write it as `{/* Translators: ... */}`.
- Code between the comment and the line of the call, such as `setTitle(` on a line of its own, detaches it.
- A comment goes only to the first message after it. A message used in several places collects the comment from each place.
- Comments without the tag stay out of the catalogs.
## Use translations in components
Import `useTranslation` and `Trans` from `@gtkx/i18n`, not `react-i18next`. Importing `@gtkx/i18n` configures the gettext backend, and extraction does not follow `react-i18next` imports: their messages never reach the catalogs, and the generated declarations then reject their keys.
```tsx [src/greeting.tsx]
import { useTranslation } from "@gtkx/i18n";
import { GtkLabel } from "@gtkx/jsx/gtk";
export function Greeting({ name }: { name: string }) {
const { t } = useTranslation();
return ;
}
```
Captured from the sample above with name set to Ada, in the source language.The same component under a French locale, with a catalog that translates the message as Bonjour, {{name}} !.
See [react-i18next's documentation](https://react.i18next.com/latest/usetranslation-hook) for its React APIs and [i18next's formatting guide](https://www.i18next.com/translation-function/formatting) for interpolation and formatting. GTKX supplies the catalog integration; gettext still uses one process-wide application domain.
## Keep messages extractable
Use ESM and the original names `t`, `useTranslation`, `Trans`, or `TransWithoutContext`, imported from `@gtkx/i18n`. Keys, explicit `i18nKey` props, `context` and the `defaultValue` options must be string literals. Pass options as an inline object literal, without spreads or `as const`, and write `Trans` props out rather than spreading them: `t("Open", options)` fails extraction. A `Trans` component can derive its source from static children when `i18nKey` is omitted.
Extraction rejects aliases and member calls such as `i18n.t(...)`. CommonJS, tagged templates, and ICU MessageFormat are not extraction forms. These restrictions keep the catalog aligned with the calls that reach gettext.
Extraction follows `t` from its import or from a `useTranslation()` call in the same module. A `t` received in any other way, such as a function parameter, a prop, `withTranslation`, or the `Translation` render prop, is not extracted, and the generated declarations then reject its keys. Helpers outside components can import `t` from `@gtkx/i18n` instead, since gettext uses one language for the whole process.
[Storybook](/v2/guide/storybook) stories stay out of the catalogs. Files matched by the `stories` patterns in `.storybook/main.ts`, or by `src/**/*.stories.*` without that file, are left out of `po/POTFILES.in` and the template, so translators never see story fixture text. A `t` call in a story still type-checks and shows its source text, and the components a story renders show their translations as in the application.
Generated declarations under `node_modules/.gtkx` extend the upstream translation types. They check message keys and contexts, and the interpolation values of an options object. As in i18next, they do not require the options object itself or a plural message's `count`: `t("Hello, {{name}}!")` compiles and renders the placeholder unchanged. Run codegen after adding messages; do not edit the declarations.
## Develop and build
`gtkx dev` prepares the catalogs before loading your application. Saving source files updates the template and translation types before Fast Refresh without modifying PO files. Run codegen or a build to merge source changes into those files. Saving a PO file or `LINGUAS` restarts the application because gettext caches catalogs for the lifetime of the process.
A GNOME-style development profile gives the development build its own application ID, so it can run beside the installed app:
```ts [gtkx.config.ts]
import { defineConfig } from "@gtkx/config";
export default defineConfig({
applicationId: "com.example.Tasks",
$development: { applicationId: "com.example.Tasks.Devel" },
});
```
The gettext domain stays the production ID: `gtkx dev` registers `com.example.Tasks.Devel` but keeps using `po/com.example.Tasks.pot` and the same catalogs as tests, builds, and packages. A separate configuration selected with `--config` is a different project setup, so an application ID it changes also names its own template and domain.
`gtkx build` compiles the catalogs into `dist/locale` beside the bundle. When the entry module imports GTKX, directly or through other modules, the bundle initializes localization before the entry runs and finds that directory on its own.
Select the process locale before launch:
```bash
LANG=fr_FR.UTF-8 LANGUAGE=fr gtkx dev
```
Gettext translations follow the startup environment. Intl-based formatting uses the process's default locale. Changing i18next's language does not change libc's active gettext locale; restart the process to change the application's translation language.
## Test translations
The [Vitest plugin](/v2/guide/testing) does not compile catalogs, so tests render source text whatever the locale. To check translations, run those tests in their own configuration: gettext reads the locale when the process starts, so the configuration sets it for its workers, and `localeDir` points the plugin at catalogs that `gtkx build` compiled:
```ts [vitest.i18n.config.ts]
import gtkx from "@gtkx/cli/vitest-plugin";
import { resolve } from "node:path";
import { defineConfig } from "vitest/config";
const localeDir = resolve(import.meta.dirname, "dist/locale");
export default defineConfig({
plugins: [gtkx({ localeDir })],
test: {
include: ["tests/**/*.i18n.tsx"],
env: {
LANG: "fr_FR.UTF-8",
LANGUAGE: "fr",
LC_ALL: "fr_FR.UTF-8",
},
},
});
```
Name those test files so the main configuration's `include` pattern skips them, as `*.i18n.tsx` does for `tests/**/*.test.{ts,tsx}`, and build before running them:
```bash
gtkx build && vitest run --config vitest.i18n.config.ts
```
The locale must be installed: `locale -a` lists it, and on Fedora 44 French comes with `glibc-langpack-fr`.
## Text direction
GTK chooses the default text direction from the application's locale. Use `textDirection` on a widget when content needs an explicit direction, such as a left-to-right animation or technical value:
```tsx
import * as Gtk from "@gtkx/gi/gtk";
import { GtkLabel } from "@gtkx/jsx/gtk";
192.0.2.1;
```
Removing `textDirection`, passing `null`, or using `Gtk.TextDirection.NONE` restores GTK's default direction.
## Translate settings schemas
Codegen, development, and builds also extract the `` and `` of every [GSettings schema](/v2/guide/native-state#your-app-s-schema) your application imports, as a Meson project does by listing the schema in `po/POTFILES.in`. xgettext reads them with the ITS rules GLib installs with its development files (`glib2-devel` on Fedora), so a `` comment before an element reaches translators as well. Existing translations of those messages stay in the PO files.
GLib translates the schema text shown by tools such as `gsettings describe` and dconf Editor from the domain named by the schema list's `gettext-domain` attribute. Set it to your production `applicationId`, the application's gettext domain:
```xml [data/com.example.Tasks.gschema.xml]
trueShow completed tasks
```
Without `gettext-domain`, those tools show the source text. Installed packages put the catalogs where GLib looks for that domain, so the summaries translate once the application is installed.
## Translate package metadata
A normal `gtkx deploy` refreshes the catalog with application and metadata messages, then compiles and packages the translations. The same PO files supply desktop-entry names, AppStream text, and MIME descriptions. The AppStream metainfo also names the application's gettext domain, so AppStream catalog generators, including Flathub's, can list the languages the application is translated into.
[`gtkx deploy --skip-build`](/v2/guide/cli#gtkx-deploy) packages the existing build and recompiles existing catalogs without updating PO files. Every locale in `LINGUAS` must already have a catalog. Packaged launchers locate the installed catalogs automatically.
See [Deploying](/v2/guide/deploying) for the packaging workflow.
---
---
title: "Scaffold Options"
description: "Create projects without prompts, defer dependency installation, and replace scaffold files."
---
# Scaffold Options
For an interactive first project, follow [Getting Started](/v2/guide/getting-started). To create a project from a script, pass the directory and `--yes`:
```bash
npm create gtkx@beta -- my-app --yes --application-id com.example.MyApp \
--display-name "My App"
```
## Options
| Option | Default without prompts |
| ------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `` | Required. A name or a path, such as `apps/my-app` or `~/Projects/my-app`. |
| `--application-id` | Derived from the directory: `my-app` gets `com.myapp.app`. |
| `--display-name` | Derived from the directory: `my-app` gets My App. |
| `-p`, `--package-manager` | `pnpm`, `npm` or `yarn`. Detected from a `packageManager` field or lockfile in the current directory or a parent, then from the command running the scaffold, otherwise pnpm. |
| `--no-typescript` | TypeScript. Pass it for a JavaScript project. |
| `--no-vitest` | The Vitest setup is included. Pass it to leave it out. |
| `-y`, `--yes` | Prompts for every option not passed. Without a terminal, as in CI, the command never prompts. |
| `-f`, `--overwrite` | Refuses a directory that is not empty. See [Existing directories](#existing-directories). |
| `--skip-install` | Installs dependencies. With it, run your package manager's install command in the project afterward. |
The package name is the directory name when that is a valid npm package name. Otherwise the scaffold lowercases it, removes accents and replaces other characters with hyphens, so `Unit Converter` becomes `unit-converter` and `café` becomes `cafe`. `--no-interactive` is the same as `--yes`, and `--typescript` and `--vitest` request the defaults explicitly. `npm create gtkx@beta -- --help` prints every option.
The new project depends on the major versions this GTKX release supports, not the newest ones: React, `@types/react` and Vitest within the ranges GTKX declares as peers, the Vite range `@gtkx/cli` depends on, TypeScript 6, and the `@types/node` major of the oldest Node.js GTKX supports. When a later GTKX release supports a new major, run `gtkx upgrade` first, then move those packages with your package manager.
With Yarn 2 or newer, the new `package.json` pins the installing Yarn release in its `packageManager` field, as `yarn init -2` does, so Corepack runs that release on every machine. The installing release is the Yarn running the scaffold, as with `corepack yarn@4 create gtkx@beta`, otherwise the one Corepack runs in the target directory. An app inside a Yarn workspace gets no pin; the workspace root owns it.
## Existing directories
Without prompts, a directory that holds anything other than `.git` stops the command before it changes anything, and the error lists the scaffold files it would replace. `--overwrite` replaces those files and leaves every other file in place. Interactive runs ask before replacing them. The command refuses a destination reached through a symbolic link.
The package manager's own settings are added to rather than replaced. An existing `.yarnrc.yml` keeps its registry, authentication and other settings and gains `nodeLinker: node-modules` and the [release-age exemptions](#release-age-gates). An existing `pnpm-workspace.yaml` keeps its settings and `packages` and gains `allowBuilds` entries for the scaffold's native dependencies and the exemptions. An existing `.npmrc` keeps its lines and gains the exemptions at the end. A `packageManager` field naming the chosen package manager stays in the new `package.json`, so the project keeps its pinned version.
The scaffold initializes a Git repository with an initial commit only in a new or empty directory outside an existing repository.
## Release-age gates
Package managers can hold back versions published more recently than a set age. Yarn 4.15 and newer ([`npmMinimalAgeGate`](https://yarnpkg.com/configuration/yarnrc#npmMinimalAgeGate)) and pnpm 11 and newer ([`minimumReleaseAge`](https://pnpm.io/settings/dependency-resolution#minimumreleaseage)) hold back packages published within the last day by default; npm's [`min-release-age`](https://docs.npmjs.com/cli/v11/using-npm/config#min-release-age) applies only when set. So that a project created on the day of a GTKX release still installs it, the scaffold exempts GTKX's own packages, `@gtkx/*` and `create-gtkx`, which `@gtkx/cli` depends on, in the configuration it writes. Every other dependency keeps the gate.
::: code-group
```yaml [.yarnrc.yml]
npmPreapprovedPackages:
- "@gtkx/*"
- create-gtkx
```
```yaml [pnpm-workspace.yaml]
minimumReleaseAgeExclude:
- "@gtkx/*"
- create-gtkx
```
```ini [.npmrc]
min-release-age-exclude[]=@gtkx/*
min-release-age-exclude[]=create-gtkx
```
:::
Yarn releases before 4.10 refuse to run with a setting they do not know, so `.yarnrc.yml` gets `npmPreapprovedPackages` only when the project's Yarn is 4.10 or newer: the release its `yarnPath` or `packageManager` field selects, otherwise the Yarn running the scaffold. `gtkx upgrade` adds the same entries to a project that lacks them before it installs a new release.
## Workspaces
Inside a workspace whose root lists the target directory, in the `packages` of `pnpm-workspace.yaml` for pnpm or the `workspaces` of the root `package.json` for npm and Yarn, the scaffold adds the app to that workspace:
```bash
pnpm create gtkx@beta apps/my-app
```
The app installs through the workspace and gets no lockfile or package manager configuration of its own, so `pnpm add`, `gtkx upgrade` and other commands run from the app act on the whole workspace. Its dependencies get their own version ranges rather than `catalog:` references, so a workspace catalog that pins another major version of `react` or `vitest` neither changes nor applies to the app.
The package managers read these settings only from the workspace root. The scaffold does not edit the root; when the root lacks an entry, the command prints it, and you add it and run the workspace's install command:
| Package manager | Root settings the app needs |
| --------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| pnpm | `allowBuilds` for `@swc/core` and `esbuild`, and the `minimumReleaseAgeExclude` exemptions, in `pnpm-workspace.yaml` |
| npm | `allowScripts` for `@swc/core` and `esbuild` in `package.json`, and the `min-release-age-exclude[]` lines in `.npmrc` |
| Yarn | `nodeLinker: node-modules` and, with Yarn 4.10 or newer, the `npmPreapprovedPackages` exemptions in `.yarnrc.yml`; `dependenciesMeta` for `@swc/core` and `esbuild` in `package.json` |
Until the root has them, pnpm skips the build scripts of `@swc/core` and `esbuild`, Yarn installs the workspace with Plug'n'Play, which GTKX does not support, and a release-age gate holds back a GTKX release published that day. When the install fails, the command prints the missing entries first; [Troubleshooting](/v2/guide/troubleshooting#dependency-installation-fails-while-scaffolding) covers recovery.
The app gets its own `.mcp.json`, and the scaffold also adds a server named `gtkx` to the `.mcp.json` at the workspace root, where AI clients are usually opened. That server starts the app's MCP server through the workspace's package manager:
| Workspace | Command |
| --------------- | --------------------------------------------------- |
| pnpm | `pnpm --dir apps/my-app exec gtkx mcp` |
| npm | `npm exec --no --workspace apps/my-app -- gtkx mcp` |
| Yarn 2 or newer | `yarn workspace my-app exec gtkx mcp` |
| Yarn 1 | `yarn --silent --cwd apps/my-app gtkx mcp` |
Other servers in the file and its indentation stay. When the root `.mcp.json` already has a GTKX server, such as an earlier app's, the scaffold adds none, because [one server drives every running GTKX app](/v2/guide/mcp#several-apps). When the file is not a valid MCP configuration, the scaffold leaves it unchanged and prints the entry to add.
---
---
title: "Configuration and Codegen"
description: "Configure a GTKX project and generate its bindings."
---
# Configuration and Codegen
`gtkx.config.ts` identifies your application and selects the libraries GTKX generates bindings for. GTKX 2 includes Adwaita and GTK by default. For resource imports, see [Assets](/v2/guide/assets); for native type wrappers, see [Native Values](/v2/guide/native-values).
## The config file
Create `gtkx.config.ts` in the project root:
```ts
import { defineConfig } from "@gtkx/config";
export default defineConfig({
applicationId: "com.example.Tasks",
});
```
List additional libraries by GIR name and version, for example `libraries: ["WebKit-6.0"]`. Codegen starts from `Adw-1` and follows its GIR dependencies, including `Gtk-4.0`. Omit these two entries from `libraries`; listing them explicitly is an error.
`defineConfig` provides editor completion. The CLI validates the configuration when it loads it. An application's ID uses a reverse-DNS name such as `com.example.Tasks`; `gtkx dev`, `gtkx build` and `gtkx deploy` stop when it is missing. Only a package that is not an application, such as a [component library](/v2/guide/workspaces#component-libraries), leaves it out.
Configuration modules and their local imports use ESM. Use `.ts`, `.mts`, `.js`, or `.mjs` files with `import` and `export`; TypeScript configuration runs through Node's native type stripping and must use erasable syntax. JSON, JSONC, JSON5, YAML, and TOML configuration files are also supported.
`gtkx dev` watches the config and the local dependencies it loads, including shared config layers and imported data, and the GIR files the bindings were generated from, such as a library built alongside the app into a `girPath` directory. Changes regenerate bindings and restart the app. If a reload fails, the current app keeps running until the configuration is fixed; creating a missing imported file also triggers another attempt.
Install the corresponding GIR files before generating bindings. Use `girPath` when they live outside the standard search directories; relative paths start at the project root. Supplying a newer GIR file changes the declarations, not the library that runs your app.
At run time the dynamic linker loads each library by the `shared-library` name its GIR file records, so a library built alongside the app has to be installed or on the linker's search path. Point `LD_LIBRARY_PATH` at its build directory for `gtkx dev`, `gtkx build` output and Vitest, as `meson devenv` does; a library the linker cannot find fails with the linker's reason, such as `cannot open shared object file`.
### Other settings {#every-option}
Use the [configuration reference](/v2/reference/@gtkx/config/index/type-aliases/Config) for available settings. The React Compiler is enabled by default; `reactCompiler: false` disables it. Application icons and package metadata are covered in [Deploying](/v2/guide/deploying), and agent tool settings in [MCP](/v2/guide/mcp).
`$development` and `$production` blocks override settings in one mode. `gtkx dev` runs in development mode; `gtkx build` and `gtkx deploy` run in production mode:
```ts
export default defineConfig({
applicationId: "com.example.Tasks",
$development: { applicationId: "com.example.Tasks.Devel" },
});
```
The app reads the resolved application ID from `virtual:gtkx-config`, a module GTKX generates from the config file. Under `gtkx dev` it holds the `$development` value. The scaffold's `src/gtkx-env.d.ts` types the module:
```ts
import { applicationId } from "virtual:gtkx-config";
```
For shared configuration, `mergeConfig(base, override)` applies the override over the base; arrays concatenate with override entries first.
### Selecting another configuration
`gtkx dev`, `gtkx codegen`, `gtkx build`, `gtkx deploy` and `gtkx storybook` accept [`--config`](/v2/guide/cli#gtkx-dev):
```bash
gtkx dev --config gtkx.enterprise.config.ts
gtkx build --config gtkx.enterprise.config.ts
```
The path is relative to the project root selected by [`--cwd`](/v2/guide/cli#gtkx-dev) and must stay inside it. For tests, pass the same path as `gtkx({ configFile: "gtkx.enterprise.config.ts" })` in `vitest.config.ts`.
Builds use the selected configuration throughout generation and bundling. `gtkx deploy --skip-build --config ...` rejects a bundle created with another config file or different production settings.
### Environment files
`gtkx dev`, `gtkx build` and Vitest read [Vite's environment files](https://vite.dev/guide/env-and-mode#env-files) from the project directory: `.env`, `.env.local`, `.env.[mode]` and `.env.[mode].local`, where the mode is `development` for `gtkx dev`, `production` for `gtkx build` and `test` for Vitest. Variables whose names start with `VITE_` appear on `import.meta.env`; the others stay out of the app.
```ini [.env]
VITE_REPORT_URL=https://reports.example.com/submit
```
```ts
const endpoint = import.meta.env.VITE_REPORT_URL;
```
The scaffold's `src/gtkx-env.d.ts` types `import.meta.env`, including `MODE`, `DEV` and `PROD`. Declare your own variables there:
```ts [src/gtkx-env.d.ts]
interface ImportMetaEnv {
readonly VITE_REPORT_URL: string;
}
```
Only the project directory is read. A `.env` at the root of a workspace does not apply to the apps in it, and no setting moves the directory; keep each app's files next to its `gtkx.config.ts`. Editing them restarts the app under `gtkx dev`.
`gtkx build` writes each value into `dist/bundle.mjs` as text, so it ships in every package `gtkx deploy` makes and cannot be changed on an installed app. Never put secrets in these files: anyone with the package can read them. Read settings that differ per machine or per run from `process.env` when the app runs.
## What codegen emits
Run generation after installing dependencies or changing the configured libraries:
```bash
gtkx codegen
```
GTKX generates modules under `node_modules/.gtkx` and links them as `@gtkx/gi` and `@gtkx/jsx`. They belong to the project and are not separate npm dependencies. `gtkx dev`, `gtkx build` and the Vitest plugin also generate them when they are missing or out of date.
Both packages always describe the same libraries. A project without `@gtkx/react` gets only `@gtkx/gi`, and its `@gtkx/jsx` comes back once `@gtkx/react` is installed again. Projects that resolve the same dependency directory share their generated bindings, as described in [Shared bindings](/v2/guide/workspaces#shared-bindings).
Import classes, enums, and functions from GI modules, and elements from JSX modules:
```tsx
import * as Gtk from "@gtkx/gi/gtk";
import { AdwHeaderBar } from "@gtkx/jsx/adw";
import { GtkBox, GtkButton } from "@gtkx/jsx/gtk";
```
Both packages use namespace subpaths; neither has a bare root import. Use [`@gtkx/cairo`](/v2/guide/cairo) for Cairo.
Leave generation enabled for an ordinary application. `codegen: false` is for projects that reuse an installed binding store. If a generated store needs rebuilding, run [`gtkx codegen --force`](/v2/guide/cli#gtkx-codegen) in the project that generates it.
Concurrent generation waits up to ten minutes for each binding-store lock. Use [`gtkx codegen --lock-timeout 900000`](/v2/guide/cli#gtkx-codegen) to change that wait in milliseconds, or pass `lockTimeoutMs` to the `@gtkx/codegen` `runCodegen` API.
### Library initialization
Importing a namespace initializes its library. When its GIR declares a top-level `init` function that can be called without arguments, such as `Gtk.init()`, `Adw.init()`, `GtkSource.init()` or `Gst.init()`, the namespace calls it as it loads, before any namespace that depends on it. GStreamer apps can therefore import `@gtkx/gi/gst` and plugin namespaces such as `@gtkx/gi/gstpbutils` in any order without calling `Gst.init()` first. A later `Gst.init(argv)` call does nothing, so pass GStreamer options through environment variables such as `GST_DEBUG`. Library teardown functions such as `GtkSource.finalize()` are never called; the process releases the libraries when it exits.
### Production bindings
Production builds remove unused generated classes. Import a class as a runtime value when the app needs its type registration, including when using `GObject.typeFromName`. A side-effect-only namespace import initializes the namespace but does not retain every class. Development and tests do not bundle.
An object that first reaches JavaScript through a callback GIR types only as a `GObject.Closure` loses its class in a production build unless the app references that class as a value. A type annotation is erased, so the object arrives as its nearest retained ancestor, often a plain `GObject.Object`. For example, the `invocation` that `Gio.DBusConnection.registerObjectWithClosures2` passes to a method-call handler lacks `returnValue`, and the first D-Bus call fails, although the same code works in `gtkx dev` and tests. The handlers given to `Gio.busOwnName` and other closure-typed functions behave the same way. Check the class in the handler to keep it in the bundle:
```ts
if (!(invocation instanceof Gio.DBusMethodInvocation)) {
throw new TypeError("Expected a D-Bus method invocation");
}
```
`Gtk.ClosureExpression` callbacks follow the same rule. An `AdwComboRow` whose `expression` names the items of an `AdwEnumListModel` receives `Adw.EnumListItem` objects; without a value reference to that class, the bundle passes plain objects and `item.getValue()` throws when the row first renders:
```ts
const easingName = Gtk.ClosureExpression.new(
GObject.TYPE_STRING,
(item: unknown) => {
if (!(item instanceof Adw.EnumListItem)) {
throw new TypeError("Expected an enum list item");
}
return item.getName();
},
null,
);
```
When a production build receives such an object through a closure and has dropped its class, it prints a warning once for that class, naming the class to reference and the module to import it from:
```text
[gtkx:runtime] warn AdwEnumListItem objects reach JavaScript as GObject
because the production build dropped Adw.EnumListItem, ...
```
The object is still wrapped as its nearest retained ancestor, so the warning usually comes right before the error it explains. Objects returned from typed functions, methods and properties keep at least their declared class and never trigger it, nor do private library classes that have no generated class. Development and tests load every class and never print it.
A type assertion is erased too, so it does not keep a more derived class than the declared one. `Gst.parseLaunch` declares a `Gst.Element`, so `(pipeline as Gst.Bin).getByName("sink")` throws `getByName is not a function` in a production build unless the app references `Gst.Bin` as a value. No warning precedes these errors. Narrow with `instanceof` instead of a cast:
```ts
const pipeline = Gst.parseLaunch(
"videotestsrc ! videoconvert ! appsink name=sink",
);
if (!(pipeline instanceof Gst.Bin)) throw new TypeError("Expected a bin");
const sink = pipeline.getByName("sink");
```
## Monorepos
Running several apps and shared packages in one pnpm, npm or Yarn workspace, and how they share bindings, is described in [Workspaces](/v2/guide/workspaces#monorepos).
## Component libraries
Building, testing and publishing a package of components that apps install is described in [Workspaces](/v2/guide/workspaces#component-libraries).
## The JSX prop model
How element props, signals, notifications, child slots and refs map to the native API is described in [JSX Elements](/v2/guide/jsx-elements#the-jsx-prop-model).
### Member names
How native method names that overlap GTKX helpers are kept is described in [JSX Elements](/v2/guide/jsx-elements#member-names).
## Passing a GType
Pass a registered GI class wherever a method takes a GType. See [Native Values](/v2/guide/native-values#passing-a-gtype) for registration and returned type IDs.
## Passing a GValue
For most `GValue` inputs, pass a JavaScript value directly. See [Native Values](/v2/guide/native-values#passing-a-gvalue) for typed nulls, output values, and explicit wrappers, and [generated return values](/v2/guide/native-values#generated-return-values) for byte arrays, unpacked values, and async result shapes.
## Generating element reference docs
`gtkx docs` writes reference pages for the project's generated elements to `docs/reference`:
```bash
gtkx docs
```
[`--out`](/v2/guide/cli#gtkx-docs) chooses another directory and [`--base-path`](/v2/guide/cli#gtkx-docs) the URL root of the links between pages. The pages describe the project's configured libraries and element props, including props imported through `elements.config`. Rerun the command after changing those inputs. The [MCP](/v2/guide/mcp) reference tools read the current configuration and need no rerun.
## What agents are given
In an application, codegen also writes `.gtkx/reference` for coding agents and maintains a marked GTKX section in `AGENTS.md`. Text outside that section is preserved, and so is a section that a Markdown formatter has only rewrapped or realigned. It creates a `CLAUDE.md` import only when that file does not already exist.
Commit the rules file and ignore `.gtkx/`, as scaffolded projects do. Set `agents.rules` or `agents.reference` to `false` to disable the corresponding output. Disabling the rules removes the GTKX section from `AGENTS.md`, and deletes that file and the `CLAUDE.md` import when nothing else remains in them. Disabling the reference also removes `.gtkx/reference` and its mention from the rules.
The reference covers the project's bindings. To give an agent the GTKX guide as well, see [Point the agent to the guide](/v2/guide/mcp#point-the-agent-to-the-guide).
## Advanced: Customizing elements
Use element behaviors when a native API needs custom prop handling or child placement. Export a `defineElements` map from a module, keyed by GLib type name, and register it through `elements.behaviors`:
```ts
export default defineConfig({
applicationId: "com.example.Tasks",
elements: { behaviors: "./src/elements.ts" },
});
```
Wrap each behavior with `defineBehavior` from `@gtkx/react/config`, supplying its GI class as the type argument. A behavior on a type also covers its subclasses, and it runs before the built-in behaviors. A behavior's `update` returns the names of the props it handles; any other prop must be a native property of the element. The [ElementBehavior reference](/v2/reference/@gtkx/react/config/type-aliases/ElementBehavior) describes the hooks.
To add a prop, declare it on the props interface of the namespace module that owns the type. This module adds `cursorName` to every widget:
```ts [src/elements.ts]
import type * as Gtk from "@gtkx/gi/gtk";
import { defineBehavior, defineElements } from "@gtkx/react/config";
declare module "@gtkx/jsx/gtk" {
interface GtkWidgetProps {
cursorName?: string;
}
}
const cursor = defineBehavior({
update: (widget, prev, next) => {
const name = next.cursorName;
if (name !== prev.cursorName) {
widget.setCursorFromName(typeof name === "string" ? name : null);
}
return ["cursorName"];
},
});
export default defineElements({
GtkWidget: { behaviors: [cursor] },
});
```
Any element of a `GtkWidget` subclass then accepts it, as in ``. The `declare module` block must sit in a file with a top-level `import` or `export`; without one, it replaces `@gtkx/jsx/gtk` instead of extending it. Keep application effects and higher-level behavior in React components.
---
---
title: "CLI"
description: "The gtkx commands and their options, with links to the guides that use them."
---
# CLI
`@gtkx/cli` installs the `gtkx` command. Scaffolded projects call it from their package scripts, so `npm run dev` runs `gtkx dev`. Outside a script, run it from the project with `npx gtkx `.
`gtkx --help` lists the commands, `gtkx --help` lists a command's options, and `gtkx --version` prints the installed version. Each section below links to the guide page that explains the workflow. In the tables, an option shown with a placeholder such as `` takes a value, and one without is a boolean flag.
A command stops with an error on an option it does not define. Boolean options also take a `--no-` form, as in `--no-read-only`. Only `gtkx dev` and `gtkx storybook` pass arguments to the application; put them after `--`, as described in [Command-line apps](/v2/guide/application-lifecycle#command-line-apps).
## `gtkx create`
Creates a project, as `npm create gtkx` does, from a directory that already has `@gtkx/cli` installed, such as a [workspace](/v2/guide/workspaces) gaining another app. It takes the same arguments and options, listed with their defaults in [Scaffold Options](/v2/guide/scaffold-options#options).
## `gtkx dev`
Runs the app from source and watches the project. Fast Refresh applies most edits to the open window. See [the dev loop](/v2/guide/getting-started#the-dev-loop).
```bash
gtkx dev [entry] [options] [-- application arguments]
```
| Option | Default | Description |
| ----------------- | -------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `[entry]` | The first of `src/index.tsx`, `.jsx`, `.ts`, `.js` | Application entry module |
| `--cwd ` | Current directory | Project root |
| `--config ` | `gtkx.config.*` | Configuration file, relative to the project root. See [Selecting another configuration](/v2/guide/configuration-and-codegen#selecting-another-configuration) |
| `--headless` | `false` | Run on an isolated headless Wayland display. See [Headless development](/v2/guide/testing#headless-development) |
| `--size ` | `1024x768` | Headless display size, such as `1280x720`. Requires `--headless` |
## `gtkx build`
Bundles the app for production into `dist/bundle.mjs`. See [Production build output](/v2/guide/deploying#production-build-output).
```bash
gtkx build [entry] [options]
```
| Option | Default | Description |
| ----------------- | -------------------------------------------------- | ------------------------------------------------ |
| `[entry]` | The first of `src/index.tsx`, `.jsx`, `.ts`, `.js` | Application entry module |
| `--cwd ` | Current directory | Project root |
| `--config ` | `gtkx.config.*` | Configuration file, relative to the project root |
| `--out ` | `dist` | Output directory below the project root |
## `gtkx deploy`
Builds the app and packages it for distribution. See [Deploying](/v2/guide/deploying).
```bash
gtkx deploy [entry] [options]
```
| Option | Default | Description |
| ------------------- | -------------------------------------------------- | ----------------------------------------------------------------------- |
| `[entry]` | The first of `src/index.tsx`, `.jsx`, `.ts`, `.js` | Application entry module |
| `--cwd ` | Current directory | Project root |
| `--config ` | `gtkx.config.*` | Configuration file, relative to the project root |
| `--target ` | `deploy.targets`, otherwise `flatpak` | Comma-separated package formats: `appimage`, `deb`, `flatpak`, `rpm` |
| `--arch ` | `deploy.architectures`, otherwise the host | Comma-separated architectures: `arm64`, `x64` |
| `--out ` | `deploy.outDir`, otherwise `build` | Deployment directory below the project root |
| `--print-manifests` | `false` | Write the generated manifests and metadata, then stop without packaging |
| `--skip-build` | `false` | Package the existing `dist/` instead of building |
## `gtkx codegen`
Generates the project's bindings, translation catalogs and TypeScript declarations. `gtkx dev`, `gtkx build` and the Vitest plugin also generate them when they are missing or out of date. See [What codegen emits](/v2/guide/configuration-and-codegen#what-codegen-emits).
```bash
gtkx codegen [options]
```
| Option | Default | Description |
| --------------------- | ----------------- | ------------------------------------------------------------------------------------ |
| `--cwd ` | Current directory | Project root |
| `--config ` | `gtkx.config.*` | Configuration file, relative to the project root |
| `--force` | `false` | Delete the generated store and regenerate it, for example to recover a corrupted one |
| `--lock-timeout ` | `600000` | Longest wait for each generated-store lock, in milliseconds |
## `gtkx docs`
Writes Markdown reference pages for the JSX elements of the libraries in `gtkx.config.ts`. See [Generating element reference docs](/v2/guide/configuration-and-codegen#generating-element-reference-docs).
```bash
gtkx docs [options]
```
| Option | Default | Description |
| -------------------- | ----------------- | -------------------------------------------------------------------------------------------- |
| `--cwd ` | Current directory | Project root |
| `--out ` | `docs/reference` | Output directory below the project root. It must be empty or hold an earlier `gtkx docs` run |
| `--base-path ` | `/reference` | URL base path of the links between the generated pages |
| `--force` | `false` | Regenerate even when the pages are up to date |
## `gtkx storybook`
Opens the native Storybook explorer for the project's stories, with hot reload. See [Storybook](/v2/guide/storybook).
```bash
gtkx storybook [options] [-- application arguments]
```
| Option | Default | Description |
| --------------------------- | ------------------- | ------------------------------------------------------ |
| `--cwd ` | Current directory | Project root |
| `--config ` | `gtkx.config.*` | Configuration file, relative to the project root |
| `--storybook-config ` | `.storybook/main.*` | Story configuration file, relative to the project root |
| `--headless` | `false` | Run on an isolated headless Wayland display |
| `--size ` | `1024x768` | Headless display size. Requires `--headless` |
## `gtkx mcp`
Runs the MCP server that exposes the running app and the generated API reference to an agent. MCP clients start it. See [App Inspection (MCP)](/v2/guide/mcp).
```bash
gtkx mcp [options]
```
| Option | Default | Description |
| ---------------- | -------------------------- | -------------------------------------------------------------------------------------------------------------- |
| `--cwd ` | Current directory | Project root |
| `--tools ` | `mcp.tools`, otherwise all | Comma-separated tool name patterns. See [Choose the available tools](/v2/guide/mcp#choose-the-available-tools) |
| `--read-only` | `mcp.readOnly` | Register only the tools that read state, leaving out the ones that drive the app |
### `gtkx mcp init`
Adds the `gtkx` server to an MCP client's project configuration file. See [Setup](/v2/guide/mcp#setup).
```bash
gtkx mcp init --client [options]
```
| Option | Default | Description |
| ----------------- | ----------------- | ---------------------------------------------------------------------------- |
| `--client ` | Required | The client to configure: `claude`, `cursor`, `vscode`, `opencode` or `codex` |
| `--cwd ` | Current directory | Project root |
## `gtkx upgrade`
Moves every GTKX package in the project or its workspace to one version and installs it. See [Updating GTKX](/v2/guide/updating).
```bash
gtkx upgrade [version] [options]
```
| Option | Default | Description |
| ------------- | -------------------------------------------- | ------------------------------ |
| `[version]` | The newest release on the project's dist-tag | Version or dist-tag to move to |
| `--cwd ` | Current directory | Project root |
## `gtkx cleanup`
Removes headless runtime directories and compile caches left by interrupted runs. They belong to your user account rather than a project, so the command ignores `--cwd`. See [Headless development](/v2/guide/testing#headless-development).
```bash
gtkx cleanup [options]
```
| Option | Default | Description |
| ----------- | ------- | ------------------------------------------------ |
| `--dry-run` | `false` | List the stale directories without removing them |
---
---
title: "Async Operations"
description: "Await native operations, handle failures, and cancel work with Gio.Cancellable."
---
# Async Operations
GTKX turns compatible GIR async/finish pairs into promise-returning methods. Await the method and handle failures with `try`/`catch`.
The promise resolves to what the finish function returns: one value directly, several as a tuple. When a finish function that can fail returns a success boolean along with output values, the promise drops the boolean, because failure rejects instead. For example, `loadContentsAsync` resolves to `[contents, etag]` and `replaceContentsAsync` to the new etag. A finish function that returns only a boolean still resolves to it, and calling a finish method such as `loadContentsFinish` yourself returns its full native tuple.
Check the generated signature for the libraries your project binds. Not every method ending in `Async` returns a promise. Some GIO operations, including the closure-based `copyAsync` and `moveAsync`, retain their callback form. GIR types their progress and ready handlers only as `GObject.Closure`, so annotate the parameters with the types the C documentation gives them; 64-bit integers such as the `goffset` byte counts of a progress handler arrive as `bigint`.
## Awaiting async operations
Create the file dialog through JSX and keep its instance in a callback ref. The portal gives the non-widget object React ownership without placing it inside the button:
```tsx
import type * as Gio from "@gtkx/gi/gio";
import * as Gtk from "@gtkx/gi/gtk";
import { GCancellable } from "@gtkx/jsx/gio";
import { GtkButton, GtkFileDialog } from "@gtkx/jsx/gtk";
import { createPortal, rootElement, useParentWindow } from "@gtkx/react";
import { useState } from "react";
type OpenButtonProps = {
onFile: (file: Gio.File) => void;
onError: (error: unknown) => void;
};
const OpenButton = ({ onFile, onError }: OpenButtonProps) => {
const parentWindow = useParentWindow();
const [dialog, setDialog] = useState(null);
const [cancellable, setCancellable] = useState(
null,
);
const [cancellableGeneration, setCancellableGeneration] = useState(0);
const [isOpening, setIsOpening] = useState(false);
const open = async (
fileDialog: Gtk.FileDialog,
current: Gio.Cancellable,
) => {
setIsOpening(true);
try {
onFile(await fileDialog.open(parentWindow, current));
} catch (error) {
if (
error instanceof Gtk.DialogError &&
(error.code === Gtk.DialogError.DISMISSED ||
error.code === Gtk.DialogError.CANCELLED)
) {
return;
}
onError(error);
} finally {
setIsOpening(false);
setCancellableGeneration((generation) => generation + 1);
}
};
return (
<>
{createPortal(, rootElement)}
{createPortal(
,
rootElement,
)}
{
if (dialog && cancellable) void open(dialog, cancellable);
}}
/>
cancellable?.cancel()}
/>
>
);
};
```
Dismissing this dialog rejects with `Gtk.DialogError.DISMISSED`. Match the generated domain and code for expected outcomes, and pass other failures to the application's error handling. Outside production, the rejection's `cause` holds the stack of the call that started the operation, unless the error already has a cause.
## Cancellation with Gio.Cancellable
Promisified methods retain their `Gio.Cancellable` argument. The example renders `GCancellable` from `@gtkx/jsx/gio` in the root portal, captures it with a state callback ref, and passes that instance into `open`.
Cancellation rejects the promise. GIO operations report `Gio.IOErrorEnum.CANCELLED`; GTK dialogs use `Gtk.DialogError.CANCELLED`.
A cancelled instance stays cancelled. Before starting another operation, replace its JSX element, for example by changing its key, and wait for the callback ref to receive the fresh instance. This also applies to an instance that an effect cleanup cancelled.
## Callback-only methods and external finish owners
GTKX pairs an async method with a finish method on its own class. When GIR names a finish function on another class, codegen looks for a matching sibling or an unambiguous generic finish method on the declaring class. For example, PackageKit sack operations use the sack's `mergeGenericFinish`.
If no suitable method exists, the generated method stays callback-based and its declaration identifies the annotated finish owner. Follow that library's async contract and finish the result on its actual owning instance. See [Gio.AsyncResult](https://docs.gtk.org/gio/iface.AsyncResult.html) for the native completion model.
## D-Bus {#calling-d-bus-directly}
[D-Bus](/v2/guide/dbus) covers calling services, exporting objects, and packing GVariant values.
## Application lifecycle {#ending-work-on-unmount}
[Application Lifecycle](/v2/guide/application-lifecycle) covers [ending work on unmount](/v2/guide/application-lifecycle#ending-work-on-unmount), [termination signals](/v2/guide/application-lifecycle#handling-termination-signals), [command-line apps](/v2/guide/application-lifecycle#command-line-apps), and [helper processes](/v2/guide/application-lifecycle#keeping-a-helper-process-alive).
## Moving work to a worker
Move CPU-bound computation to a Node worker and send results to the UI thread. [Workers and Helper Processes](/v2/guide/workers) covers bundling, direct source loading in development, and native thread ownership.
---
---
title: "Error Handling"
description: "Match native errors by domain and code, and see how GLib criticals, uncaught exceptions and addon panics surface."
---
# Error Handling
GTKX turns a native `GError` into a thrown `GLib.Error`, which extends JavaScript's `Error`. Generated signatures omit the error output parameter. Promisified methods reject with the same errors; see [Async Operations](/v2/guide/async-operations).
## Matching errors by domain and code
Generated error domains support `instanceof`. The check matches the domain; compare `code` with a member of that same domain to handle a particular failure:
```ts
import * as GLib from "@gtkx/gi/glib";
const parseKeyFile = (contents: string) => {
const keyFile = GLib.KeyFile.new();
try {
keyFile.loadFromData(
contents,
Buffer.byteLength(contents),
GLib.KeyFileFlags.NONE,
);
return keyFile;
} catch (error) {
if (
error instanceof GLib.KeyFileError &&
error.code === GLib.KeyFileError.PARSE
)
return null;
throw error;
}
};
```
Checking a domain narrows the value to an error with `domain` and `code`. Check `error instanceof GLib.Error` when you need its native methods, such as `matches` or `copy`. As in GJS, `matches` accepts a generated domain in place of its quark, as in `error.matches(Gio.IOErrorEnum, Gio.IOErrorEnum.CANCELLED)`. Editor completion lists a domain's codes from the generated bindings, and the library's documentation, such as GLib's [`GKeyFileError`](https://docs.gtk.org/glib/error.KeyFileError.html), says when each one occurs.
To report a failure to native code, create an error as in GJS. Throw it from a virtual function that reports errors through `GError` (see [Reporting a vfunc error](/v2/guide/subclassing#reporting-a-vfunc-error)), or pass it to a function such as `Gio.Task.returnError()`. The domain may be a generated domain or its quark, here and in `GLib.Error.newLiteral()`:
```ts
import * as Gio from "@gtkx/gi/gio";
import * as GLib from "@gtkx/gi/glib";
const reportMissingNote = (callback: Gio.AsyncReadyCallback) => {
const task = Gio.Task.new(null, null, callback);
task.returnError(
new GLib.Error(
Gio.IOErrorEnum,
Gio.IOErrorEnum.NOT_FOUND,
"No such note",
),
);
};
```
## GLib criticals and warnings
Some native functions report misuse by logging a `CRITICAL` or `WARNING` instead of returning a `GError`. GTKX leaves these messages to GLib, as C and GJS applications do: GLib prints them to standard error, the binding call returns normally, and the application keeps running. A critical usually points at a programming error, such as an invalid argument, so fix the code that triggered it.
GLib's [`G_DEBUG`](https://docs.gtk.org/glib/running.html) environment variable can make criticals or warnings abort the process while you debug them. GLib `ERROR` messages always abort.
## Uncaught exceptions
GTKX keeps Node's contract for exceptions no JavaScript code catches. A function that native code calls, such as a signal handler, a draw function or a `GLib.timeoutAdd` callback, has no JavaScript caller to catch what it throws, so its exception becomes an uncaught exception. So does a render error no [error boundary](#react-error-boundaries) catches, and a promise rejection nothing handles. Node prints the error with its stack and ends the process with exit status 1, which closes the application and loses unsaved work. GJS logs such exceptions and keeps running; GTKX does not, so catch errors inside callbacks the application should survive, and show the failure through application state. A callback that reports errors through `GError`, such as some virtual functions, is different: GTKX hands the thrown error to its native caller.
Use Node's [`uncaughtExceptionMonitor`](https://nodejs.org/api/process.html#event-uncaughtexceptionmonitor) to report crashes without changing that exit. An application that registers its own `uncaughtException` listener replaces the exit and keeps running, as any Node program does, although Node advises against resuming normal work after an uncaught exception.
`gtkx dev` behaves like the built application: it prints the error with a stack that points at your source, ends the application and keeps the dev server running, then starts the application again on the next save. Until then, [MCP](/v2/guide/mcp) tools answer with the error that stopped it. An application's own `uncaughtException` listener keeps it running under `gtkx dev` as well. `gtkx storybook` prints the error and keeps the explorer open.
## Addon panics
A panic in the GTKX native addon while it handles a binding call throws an ordinary `Error` from that call. It has no native domain or code.
A panic while native code calls back into JavaScript, or on another thread, cannot reach the `try`/`catch` that started the work. GTKX reports it as an [uncaught exception](#uncaught-exceptions), which ends the process unless the application handles it. Native state may already be invalid, so do not resume normal application work after a panic. An unhandled panic fails the test suite as well; see [Testing](/v2/guide/testing).
## React error boundaries
An error boundary can replace a failed descendant's rendered UI with a fallback. Use it around a recoverable part of the interface, and render the fallback with GTKX elements. React's [error boundary documentation](https://react.dev/reference/react/Component#catching-rendering-errors-with-an-error-boundary) describes the component contract.
Boundaries do not catch ordinary event-handler failures or arbitrary rejected promises. Catch those failures in the signal handler or around the awaited operation, then update application state to show an error.
---
---
title: "Native Values"
description: "Pass GTypes, GValues and integers to native methods and read generated return values."
---
# Native Values
Most generated methods take and return plain JavaScript values. This page covers the cases that differ: GTypes, `GObject.Value`, integers, byte arrays and records.
## Passing a GType
GTKX accepts a registered class wherever a binding takes a GType:
```ts
import * as GObject from "@gtkx/gi/gobject";
import * as Gtk from "@gtkx/gi/gtk";
const isWidget = GObject.typeIsA(Gtk.Label, Gtk.Widget);
```
Generated classes and interfaces, and subclasses registered with `registerClass`, can be passed this way. A plain JavaScript subclass that skipped `registerClass` has no GType of its own, and passing it throws a `TypeError`. GTypes returned by bindings or passed to signal handlers remain `bigint` values.
Generated enumerations, flags and error domains whose type is registered with GObject can be passed the same way, and carry their GType as `__type__`, like classes. Reading it registers the type, so use it rather than `GObject.typeFromName`, which finds a type only once something has registered it. JSX props that take a GType accept the `__type__` value:
```tsx
import * as GObject from "@gtkx/gi/gobject";
import * as Gtk from "@gtkx/gi/gtk";
import { AdwEnumListModel } from "@gtkx/jsx/adw";
const isEnum = GObject.typeIsA(Gtk.SortType, GObject.TYPE_ENUM);
const orders = ;
```
A GType that GObject rejects for a construct property, such as the `0n` `typeFromName` returns for a type nobody registered, throws a `RangeError` instead of constructing the object without it.
## Passing a GValue
When a binding takes a `GObject.Value`, pass the JavaScript payload and GTKX infers its type: a string becomes a `gchararray`, a number a `gint` or `gdouble`, and an object its own class's type. For example, a `GtkDragSource` can use this `onPrepare` handler:
```ts
import * as Gdk from "@gtkx/gi/gdk";
const prepareDrag = () => Gdk.ContentProvider.newForValue("Copied text");
```
`onPrepare` returns its provider synchronously, so the handler creates it directly. Create long-lived GObjects through JSX.
When the operation needs a type inference cannot select, such as an enumeration or an interface, initialize a `GObject.Value` yourself. Clipboards and drop targets match content by GType, and a file passed directly is offered as its implementation class, `GLocalFile`, rather than `GFile`:
```ts
import * as Gdk from "@gtkx/gi/gdk";
import * as Gio from "@gtkx/gi/gio";
import * as GObject from "@gtkx/gi/gobject";
const fileProvider = (file: Gio.File) => {
const value = new GObject.Value();
value.init(Gio.File);
value.setObject(file);
return Gdk.ContentProvider.newForValue(value);
};
```
A binding that fills a value, such as `Gdk.ContentProvider.getValue`, takes a `GObject.Value` you create; its documentation says whether to initialize it first. Signal handlers receive the value object rather than its payload.
For nullable value parameters, `null` means no value object. To represent a typed null payload, create a value with the required type and set its payload to null.
## Generated return values
Returned byte arrays are `Uint8Array`; byte inputs accept `Uint8Array`, `Uint8ClampedArray` or `number[]`. A returned `GObject.Value` is unpacked to its payload, typed as `unknown`. Inout records and boxed values are updated in place rather than repeated in the return value. [Async Operations](/v2/guide/async-operations) covers what promisified operations resolve to.
## Records passed to callbacks
A record that a signal handler or callback receives stays valid until the handler returns. Reference-counted records, such as `WebKit.ScriptMessageReply`, are the exception: the handler may keep one and use it later, for example to answer once an asynchronous operation finishes.
## Passing integers
Integer parameters, properties and vfunc results take whole numbers within their native type's range. GTKX throws a `RangeError` for any other number, such as `Value 10922.4 is not an integer, int32 expects a whole number`, where GJS truncates a fractional number silently. Code ported from GJS that computes sizes or positions with fractional arithmetic must round each value before passing it:
```ts
import * as Pango from "@gtkx/gi/pango";
const shrinkFont = (description: Pango.FontDescription, size: number) =>
description.setSize(Math.round(size * 0.8));
```
The same applies to sizes a [vfunc returns](/v2/guide/subclassing#subclass-virtual-methods) and to fields of records such as `Gdk.Rectangle`. Use `Math.trunc` to keep GJS's behavior exactly.
## Reading embedded records
A record or union field that embeds another record by value, such as `Pango.Item.analysis` or the members of a `Poppler.Action` (`action.any.title`), reads as a view into the parent's memory, as in GJS:
```ts
import * as Pango from "@gtkx/gi/pango";
const isRightToLeft = (item: Pango.Item) => item.analysis.level % 2 === 1;
```
A view reflects later changes to the parent and keeps the parent alive while it is reachable. A view of a value lent to a callback expires with that value when the callback returns. When the embedded record holds pointers, the field is read-only, because copying a whole record would alias pointers the parent already owns.
---
---
title: "D-Bus"
description: "Call D-Bus services, export objects, and pack GVariant values with the generated Gio bindings."
---
# D-Bus
GTKX apps use D-Bus through the generated Gio bindings, as GJS apps do: `Gio.DBusProxy` and `Gio.DBusConnection` for calls, signals and properties, with `Variant` from `@gtkx/gi/glib` for the values. The [GJS D-Bus guide](https://gjs.guide/guides/gio/dbus.html) explains the D-Bus concepts; this page covers what is specific to GTKX.
## Calling D-Bus directly
Construct the variants used by `Gio.DBusProxy` with `new Variant(signature, value)` from `@gtkx/gi/glib`, as in GJS. Literal GVariant type strings determine the TypeScript input and unpacked types. For native replies, supply the expected signature as a type parameter when unpacking:
```ts
import * as Gio from "@gtkx/gi/gio";
import { Variant } from "@gtkx/gi/glib";
const getNameOwner = async (proxy: Gio.DBusProxy, name: string) => {
const reply = await proxy.call(
"GetNameOwner",
new Variant("(s)", [name]),
Gio.DBusCallFlags.NONE,
-1,
);
const [owner] = reply.deepUnpack<"(s)">();
return owner;
};
```
## GVariant packing and unpacking
Variants expose the [GJS unpacking methods](https://gjs.guide/guides/glib/gvariant.html#unpacking-variants):
| Method | Behavior |
| ------------------- | ---------------------------------------------------------------------------------------------------------- |
| `unpack()` | Opens the outer container, leaving its children as variants. Dictionary keys are unpacked. |
| `deepUnpack()` | Opens arrays, tuples, dictionaries, and maybes recursively, retaining the variants held inside `v` values. |
| `recursiveUnpack()` | Opens every container, including nested `v` values. |
Basic values unpack directly. Byte arrays (`ay`) return `Uint8Array` in every mode, and dictionaries return objects, including dictionaries with numeric keys. `deep_unpack()` aliases `deepUnpack()`, and `Variant.new(signature, value)` aliases construction for compatibility with older GJS code.
Passing a string to `new Variant("ay", text)` produces UTF-8 bytes with a trailing NUL, as in GJS; passing a byte array preserves its bytes. GTKX keeps signed and unsigned 64-bit values as `bigint` to preserve their full precision. Construction accepts `bigint` or safe integer numbers for those types.
Unpacking always reads the variant's actual runtime type. An explicit type parameter describes the signature your code expects; it does not validate that signature at runtime. Without a known constructor signature or explicit type parameter, the result is `unknown`.
## Consuming a service
`Gio.DBusProxy.newForBus` returns a promise for a proxy to one interface of a remote object. The proxy emits `g-signal` for the service's signals, and `getCachedProperty` reads its properties, which `g-properties-changed` reports when they change. `Gio.DBusObjectManagerClient` lists the objects of a service that exports an object manager, with a proxy for each of their interfaces. `Gio.busWatchName` calls its handlers when a name gains or loses its owner, so a client can create its proxy once the service is running:
```ts
import * as Gio from "@gtkx/gi/gio";
import { Variant } from "@gtkx/gi/glib";
import * as GObject from "@gtkx/gi/gobject";
export const watchCounter = (onValue: (value: number | null) => void) => {
let proxy: Gio.DBusProxy | null = null;
let disconnect = () => {};
let generation = 0;
const forget = () => {
generation += 1;
disconnect();
disconnect = () => {};
proxy = null;
};
const watcher = Gio.busWatchName(
Gio.BusType.SESSION,
"com.example.Counter",
Gio.BusNameWatcherFlags.NONE,
async (_connection: Gio.DBusConnection, name: string) => {
const current = generation;
try {
const created = await Gio.DBusProxy.newForBus(
Gio.BusType.SESSION,
Gio.DBusProxyFlags.NONE,
null,
name,
"/com/example/Counter",
"com.example.Counter",
);
if (current !== generation) return;
const handler = created.connect(
"g-signal",
(_sender, signalName, parameters) => {
if (signalName === "Changed")
onValue(parameters.deepUnpack<"(u)">()[0]);
},
);
disconnect = () =>
GObject.signalHandlerDisconnect(created, handler);
proxy = created;
onValue(
created.getCachedProperty("Value")?.unpack<"u">() ?? null,
);
} catch (error) {
if (current === generation) console.error(error);
}
},
(_connection: Gio.DBusConnection | null, _name: string) => {
forget();
onValue(null);
},
);
return {
increment: async (step: number) => {
if (!proxy) return;
const reply = await proxy.call(
"Increment",
new Variant("(u)", [step]),
Gio.DBusCallFlags.NONE,
-1,
);
onValue(reply.deepUnpack<"(u)">()[0]);
},
stop: () => {
Gio.busUnwatchName(watcher);
forget();
},
};
};
```
A proxy created after its name vanished, or after `stop`, is discarded, and each proxy's signal handler is disconnected when its name vanishes. GIR types the watcher's handlers only as `GObject.Closure`, so annotate their parameters with the types the C documentation gives them, as the example does.
## Exporting an object
`connection.registerObjectWithClosures2` exports an object at a path, given an interface description and three handlers. The method-call handler answers each call exactly once, through the `Gio.DBusMethodInvocation` it receives, with `returnValue` or `returnDbusError`, and may do so after asynchronous work. The property handlers read and write properties; pass `null` for one the interface does not need:
```ts [src/counter-service.ts]
import * as Gio from "@gtkx/gi/gio";
import { Variant } from "@gtkx/gi/glib";
const COUNTER_XML = ``;
export const exportCounter = (
connection: Gio.DBusConnection,
objectPath: string,
): (() => void) => {
const info = Gio.DBusNodeInfo.newForXml(COUNTER_XML).lookupInterface(
"com.example.Counter",
);
if (!info)
throw new Error("The interface description has no com.example.Counter");
let value = 0;
const registration = connection.registerObjectWithClosures2(
objectPath,
info,
(
_connection: Gio.DBusConnection,
_sender: string,
_path: string,
interfaceName: string,
method: string,
parameters: Variant,
invocation: Gio.DBusMethodInvocation,
) => {
if (!(invocation instanceof Gio.DBusMethodInvocation))
throw new TypeError("Expected a D-Bus method invocation");
if (method !== "Increment") {
invocation.returnDbusError(
"org.freedesktop.DBus.Error.UnknownMethod",
`Unknown method ${method}`,
);
return;
}
const [step] = parameters.deepUnpack<"(u)">();
value += step;
connection.emitSignal(
null,
objectPath,
interfaceName,
"Changed",
new Variant("(u)", [value]),
);
invocation.returnValue(new Variant("(u)", [value]));
},
(
_connection: Gio.DBusConnection,
_sender: string,
_path: string,
_interfaceName: string,
property: string,
) => (property === "Value" ? new Variant("u", value) : null),
null,
);
return () => connection.unregisterObject(registration);
};
```
The method-call handler's parameters are annotated for the same reason as the watcher's. The `instanceof` check keeps `Gio.DBusMethodInvocation` in production builds, which would otherwise pass the invocation as a plain `GObject.Object`; see [Production bindings](/v2/guide/configuration-and-codegen#production-bindings).
Export from an effect and return the cleanup. [`useApplication()`](/v2/guide/native-state#the-application) returns the application, so render this component inside the [application element](/v2/guide/application-lifecycle#the-application-element):
```tsx [src/components/counter-service.tsx]
import { useApplication } from "@gtkx/react";
import { useEffect } from "react";
import { exportCounter } from "../counter-service.js";
export const CounterService = () => {
const application = useApplication();
useEffect(() => {
const connection = application.getDbusConnection();
const objectPath = application.getDbusObjectPath();
if (!connection || !objectPath) return;
return exportCounter(connection, objectPath);
}, [application]);
return null;
};
```
The application element registers the app on the session bus under its application ID before it renders its children, so the connection is ready when the effect runs; both getters return `null` for an app without an ID. `getDbusObjectPath()` is the application's object path, which can hold the object or a path below it. With the application ID `com.example.Counter`, the object lands at `/com/example/Counter`, where the client above looks for it. To export under another name, own it with `Gio.busOwnName` and export from its bus-acquired handler, which receives the connection.
## GJS D-Bus wrappers
GTKX has no equivalent of the `Gio.DBusProxy.makeProxyWrapper` and `Gio.DBusExportedObject.wrapJSObject` helpers from the [GJS D-Bus guide](https://gjs.guide/guides/gio/dbus.html). When porting, replace a proxy wrapper's methods with `proxy.call`, its signals with `g-signal` and its properties with `getCachedProperty`, and export a wrapped object with `registerObjectWithClosures2`. Exporting objects through `Gio.DBusObjectManagerServer` is not supported: it takes `Gio.DBusInterfaceSkeleton` implementations, and JavaScript cannot supply the method table a skeleton returns, so the bindings omit `vfuncGetVtable`.
---
---
title: "Workers and Helper Processes"
description: "Run computation away from the UI thread and manage native work outside an application."
---
# Workers and Helper Processes
Move CPU-bound computation to a [Node worker](https://nodejs.org/api/worker_threads.html) so it doesn't block the interface. Native asynchronous I/O can stay on the application thread; [await it](/v2/guide/async-operations) instead.
## Moving work to a worker
Start the worker from the application and send its results back as messages:
```ts
import { Worker } from "node:worker_threads";
const worker = new Worker(new URL("./indexer.ts", import.meta.url));
worker.on("message", (rows) => setRows(rows));
```
Only one thread in a process can own GTKX's GLib integration, and in an application that is the main thread. A worker uses Node APIs and posts plain data to the main thread; it cannot import generated GI modules or make GTKX native calls.
For `gtkx build` to emit the worker, its URL must appear directly inside `new Worker(...)` and name the source file through a relative path.
During `gtkx dev` and Vitest, Node loads the worker's source directly, and `gtkx dev` restarts the app when a file the worker loaded changes. The worker's relative imports must name source files or [project files](#importing-files-in-a-worker), and its syntax must work with [Node's type stripping](https://nodejs.org/api/typescript.html#type-stripping). Exercise workers in tests as well as builds, since the production bundle can accept syntax that direct loading cannot.
For imports of TypeScript files, add `"allowImportingTsExtensions": true` to the scaffold's `compilerOptions`; it already uses `NodeNext` and `noEmit`. To have `tsc` report syntax that Node cannot strip, add `"erasableSyntaxOnly": true` as well. `tsc` then rejects parameter properties such as `constructor(private readonly path: string)`, enums, namespaces with code and other TypeScript that would otherwise typecheck and build and only fail with a `SyntaxError` when the worker starts in `gtkx dev` or Vitest. The option applies to the whole project, including code that only Vite compiles.
## Importing files in a worker
A worker imports project files with `?url`, `?raw` and `?inline`, as the main thread does; [Assets](/v2/guide/assets#files-and-text) describes what each provides:
```ts
import { readFileSync } from "node:fs";
import captionsPath from "../../data/captions.txt?url";
const captions = readFileSync(captionsPath, "utf8");
```
During `gtkx dev` and Vitest, a worker started with its own `execArgv` must include `process.execArgv` to keep this support. `?resource`, `?icon` and `?font` make assets available to GTK, so import them from the main thread.
## Standalone workers that own GTKX
In a Node helper that is not a GTKX application, a worker can own GTKX instead of the main thread. A thread starts GTKX when it first loads GTKX code, such as `@gtkx/gi`, `@gtkx/react` or `@gtkx/i18n`, and a second thread that loads GTKX code fails during bootstrap. A helper whose main thread calls `t()` from `@gtkx/i18n` therefore owns GTKX on that thread, so keep `@gtkx/*` imports out of the main thread of a helper that hands GTKX to a worker, and post plain data between them. `gtkx build` sets the program name and the locale on an entry's main thread only when that thread loads GTKX code, so building such a helper leaves GTKX to its worker:
```ts
import { Worker } from "node:worker_threads";
const [folder, output] = process.argv.slice(2);
const worker = new Worker(new URL("./thumbnailer.ts", import.meta.url), {
workerData: { folder, output },
});
worker.on("message", (message) => {
if (message === "cleanup-complete") void worker.terminate();
});
```
Before the parent terminates a worker that owns GTKX, the worker must:
1. Finish its native operations, or cancel them and await completion.
2. Disconnect signal handlers and remove other native callback registrations.
3. Call `quit()` from `@gtkx/runtime`.
4. Post a cleanup-complete message. The parent calls `worker.terminate()` only after it arrives.
`quit()` alone does not cancel pending operations or await their callbacks, and terminating a worker with live native work or registrations is unsupported.
## Callbacks from other threads
JavaScript runs only on the thread that owns GTKX, but some libraries call back from threads of their own. GStreamer emits `about-to-finish` on `playbin` and `playbin3`, and `handoff` on `identity` and `fakesink`, from its streaming threads. When native code calls a JavaScript signal handler, callback or virtual function override from another thread, GTKX skips the call, as GJS does, and logs a GLib warning that names the signal and the emitting object:
```text
Gtkx-WARNING **: The JavaScript handler for signal 'about-to-finish' on GstPlayBin3 0x55d0c2a1e0f0 was called on another thread and was skipped. …
```
The application keeps running. The library sees a call that did nothing: a skipped signal handler or callback returns zero, `false` or `null`, and a skipped virtual function override runs the implementation it replaced. The warning appears once per handler. Use signals and messages that reach the main thread instead, such as the pipeline bus.
Gapless playback is the common case. A C or Vala player sets the next track's URI inside `about-to-finish`, which a JavaScript handler cannot do. `playbin` also keeps a `uri` set while it plays and switches to it without a gap when the current track ends, so queue the next track from the bus once the current one starts:
```ts
import * as GLib from "@gtkx/gi/glib";
import * as Gst from "@gtkx/gi/gst";
const tracks = [
"file:///music/01.ogg",
"file:///music/02.ogg",
"file:///music/03.ogg",
];
const player = Gst.ElementFactory.make("playbin", "player");
if (player === null)
throw new Error("GStreamer's playbin element is not installed");
player.getBus()?.addWatch(GLib.PRIORITY_DEFAULT, (_bus, message) => {
if (message.type === Gst.MessageType.STREAM_START) {
const next = tracks.shift();
if (next !== undefined) player.setProperty("uri", next);
}
return GLib.SOURCE_CONTINUE;
});
player.setProperty("uri", tracks.shift() ?? null);
player.setState(Gst.State.PLAYING);
```
With GStreamer 1.28, `playbin3` stalls when its `uri` changes while it plays, so use `playbin` for this.
## Keeping a helper process alive
An application element, normally `AdwApplication`, keeps the Node event loop alive automatically. A plain Node helper has no application lifecycle, so pending GIO work alone does not keep the process alive. Hold the event loop around the operation with `keepAlive` from `@gtkx/runtime`:
```ts
import { keepAlive } from "@gtkx/runtime";
keepAlive(true);
try {
await runGioWork();
} finally {
keepAlive(false);
}
```
`keepAlive` is a switch for the current JavaScript environment. Coordinate overlapping operations and release it after the last one. Application components should leave this to their application element. Calling `quit()` releases the hold and prevents it from being enabled again.
---
---
title: "Subclassing GObject"
description: "Register native types in TypeScript and render them through JSX."
---
# Subclassing GObject
Use React components to compose your interface. Register a subclass when a native API needs a new type, custom properties, or a virtual-function implementation. For background on the native object system, see the [GObject documentation](https://docs.gtk.org/gobject/concepts.html).
## Register a class
Extend a generated GI class and pass the class declaration to `registerClass`. Choose an application-specific `typeName`; native type names share a process-wide namespace.
```ts
import { ParamFlags, paramSpecString } from "@gtkx/gi/gobject";
import * as Gtk from "@gtkx/gi/gtk";
import { registerClass } from "@gtkx/runtime";
class TaggedScaleBase extends Gtk.Scale {
declare tag: string;
}
const TaggedScale = registerClass(TaggedScaleBase, {
typeName: "ExampleTaggedScale",
properties: {
tag: paramSpecString("tag", null, null, "", ParamFlags.READWRITE),
},
});
type TaggedScale = InstanceType;
```
Use the returned class so TypeScript recognizes the registered properties and signals. Register once at module scope, before rendering instances. See the [`registerClass` reference](/v2/reference/@gtkx/runtime/functions/registerClass) for registration options.
## Rendering a registered class
Codegen does not emit elements for application-defined classes. Create a component with `createElementComponent`, passing the props type, the registered type name and the class, then render it through JSX:
```tsx
import { GtkAdjustment, type GtkScaleProps } from "@gtkx/jsx/gtk";
import { createElementComponent } from "@gtkx/react";
type TaggedScaleProps = GtkScaleProps & { tag?: string };
const TaggedScaleElement = createElementComponent(
"ExampleTaggedScale",
TaggedScale,
);
}
/>;
```
The element inherits its parent type's props, signals and child-placement behavior. Passing the class also keeps its registration reachable in production bundles.
Declared native properties are passed into construction. Construct-only props must remain unchanged while the element is mounted. Omitting a writable prop on a later render restores its ParamSpec default.
## Properties
Use `declare` for native properties. A JavaScript field initializer would shadow the native accessor. Write the `properties` object inline, without a wider annotation such as `Record`, so its keys stay available to `useProperty` and other typed consumers.
Property keys use camelCase; the ParamSpec uses the matching native spelling. For example, pair `displayName` with `paramSpecString("display-name", ...)`. Declare read-only and construct-only fields as `readonly`.
Typed `GObject.getProperty` and `GObject.setProperty` calls and `useProperty` infer keys from declared fields and compatible ParamSpecs. For object and boxed specs the declared field's type is trusted, so declare `color: Gdk.RGBA` for `paramSpecBoxed("color", null, null, Gdk.RGBA, ParamFlags.READWRITE)`; a field declared with another type typechecks but reads the boxed value. Use the descriptor-taking `getProperty` and `setProperty` overloads when a spec cannot preserve that inference, such as a write-only property, a `paramSpecPointer` or `paramSpecUnichar` spec, or a spec widened to plain `ParamSpec`.
### Overriding an inherited property
Use `GObject.ParamSpec.override("property-name", Source)` when explicitly redeclaring a property from a parent class or interface. `Source` can be its generated class, interface, or GType. Implemented interface properties are overridden automatically. Native reads and writes go through a getter and setter of the same camelCase name when the class defines them, as they do for declared properties.
Some interface properties are read through a virtual function, such as `Gtk.Editable`'s `text`, which reads `vfuncGetText`. A write to such a property throws unless the class defines a getter and setter for it, because the virtual function would never see the written value.
### Inspecting a ParamSpec
A ParamSpec exposes `name`, `nick`, `blurb`, `flags`, `valueType` and `ownerType` as fields, and its default through `getDefaultValue()`. To look a property up on a class, use the class-struct wrapper: `GObject.ObjectClass.peek(TaggedScale).findProperty("tag")`.
### Binding properties
`bindProperty` keeps a property of one object in step with a property of another. `bindPropertyFull` and `BindingGroup.bindFull` also convert the value on the way, as in GJS: a transform receives the binding and the value read from one end, and returns whether the conversion succeeded with the value to write to the other end. Pass `null` for a direction that should use the default conversion.
```ts
import * as GObject from "@gtkx/gi/gobject";
scale.bindPropertyFull(
"tag",
label,
"label",
GObject.BindingFlags.SYNC_CREATE | GObject.BindingFlags.BIDIRECTIONAL,
(_binding, tag) => [true, `#${tag}`],
(_binding, text) =>
text.startsWith("#") ? [true, text.slice(1)] : [false, null],
);
```
The transform's value types come from the named properties when the objects declare them, so `tag` is a `string` here. A transform that returns `[false, value]` leaves the other end unchanged. A `GObject.Closure` passed in place of a function receives GLib's closure arguments: the binding and the two `GObject.Value`s, the second of which it fills in.
### Properties and the hooks
`useProperty`, `useSignal` and `useBindSetting` accept registered classes like any other object, typed from their declared properties and signals. See [Native State](/v2/guide/native-state#objects-that-jsx-creates) for passing an instance that JSX created.
## Declaring signals
Declare custom signals with `withSignals` when the class emits or connects to them itself. It takes the base class and the signal specs, and the class extending it can use those names on `this`:
```ts
import * as GObject from "@gtkx/gi/gobject";
import { registerClass, withSignals } from "@gtkx/runtime";
class CounterBase extends withSignals(GObject.Object, {
"cycle-completed": { paramTypes: [GObject.TYPE_INT] },
}) {
complete(cycles: number): void {
this.emit("cycle-completed", cycles);
}
}
const Counter = registerClass(CounterBase, { typeName: "ExampleCounter" });
```
`registerClass` installs these signals on the new type. Its `signals` option declares signals too, typed on the returned class rather than inside the class body; a name declared in both places is an error. Each entry names its parameter GTypes and, when needed, its return GType, as GType values, generated classes, or generated enumerations and flags. Custom JSX components should include their signal handler props in their prop type.
Handlers receive the signal arguments; JSX handlers also receive the emitting object last. See the [JSX prop model](/v2/guide/jsx-elements#the-jsx-prop-model) for handler props and the [`registerClass` reference](/v2/reference/@gtkx/runtime/functions/registerClass) for signal options.
## Default handlers
A class method named `on`, such as `onCycleCompleted` for the `cycle-completed` signal above, becomes the signal's default handler. It receives the signal arguments with `this` bound to the instance. A registered subclass can replace it and chain to it with `super.onCycleCompleted()`.
The method replaces the parent type's native default handler. When an inherited signal has a generated `vfunc` member, such as `Gtk.Button`'s `vfuncClicked` for `clicked`, override that instead and chain with `super`, as in [Subclass virtual methods](#subclass-virtual-methods).
Reserve these names for default handlers when they match a signal. Use ordinary React handler props for application behavior attached to a rendered element.
## Class-level setup
Use `classInit` for native operations that must run during type registration, and `cssName` to set a widget subclass's CSS name. `classInit` receives the generated class-struct wrapper, such as `Gtk.WidgetClass`, after GTKX installs the declared properties, signals and virtual functions. Its parameter is typed as `object`; annotate it with the class struct of the class you extend:
```ts
import * as Gtk from "@gtkx/gi/gtk";
import { registerClass } from "@gtkx/runtime";
class WaveformBase extends Gtk.Widget {}
const Waveform = registerClass(WaveformBase, {
typeName: "ExampleWaveform",
cssName: "waveform",
classInit(klass: Gtk.WidgetClass) {
klass.setAccessibleRole(Gtk.AccessibleRole.IMG);
},
});
```
This is type setup, not a component mount effect. If it throws, registration fails to return, but the native type remains registered and cannot be retried under the same name.
## Overriding virtual functions
### Custom layout callbacks
A container whose only custom behavior is measurement and allocation needs no subclass. Pass a `GtkCustomLayout` through `layoutManager` instead:
```tsx
import { AdwBin } from "@gtkx/jsx/adw";
import { GtkCustomLayout, GtkLabel } from "@gtkx/jsx/gtk";
widget.getFirstChild()?.measure(orientation, forSize) ?? [
0, 0, -1, -1,
]
}
allocate={(widget, width, height, baseline) => {
widget.getFirstChild()?.allocate(width, height, baseline, null);
}}
/>
}
>
Custom layout;
```
`measure` returns `[minimum, natural, minimumBaseline, naturalBaseline]`. Both `measure` and `allocate` are required; `requestMode` is optional and defaults to constant size. Rerendering with new callbacks keeps the same native layout and invalidates its measurements, so inline callbacks can read current props.
GTKX retains these callbacks for the layout's lifetime, including when GTK owns the layout after its JavaScript reference is dropped. This also applies to `Gtk.CustomLayout.new()`; callbacks are released with their owner and can capture the layout without permanently retaining it.
### Subclass virtual methods
Implement the generated `vfunc` method with its declared signature. Use `super` to chain to the parent implementation:
```ts
import * as Gtk from "@gtkx/gi/gtk";
import { registerClass } from "@gtkx/runtime";
class PaddedLabel extends Gtk.Label {
override vfuncMeasure(
orientation: Gtk.Orientation,
forSize: number,
): [number, number, number, number] {
const [minimum, natural, minimumBaseline, naturalBaseline] =
super.vfuncMeasure(orientation, forSize);
return [minimum + 10, natural + 10, minimumBaseline, naturalBaseline];
}
}
registerClass(PaddedLabel, { typeName: "ExamplePaddedLabel" });
```
Output parameters become return values, grouped into a tuple when there are several. Follow the [native operation's contract](https://docs.gtk.org/gtk4/vfunc.Widget.measure.html) when changing those values.
Return whole numbers where the slot takes an integer, as `vfuncMeasure` does. GJS truncates a fractional result silently; GTKX rejects it with an error that names the vfunc, such as `TypeError: PaddedLabel.vfuncMeasure returned a value its native caller cannot take: Value 99.5 is not an integer, int32 expects a whole number`. Round sizes computed from fractional values, such as Pango units divided by `Pango.SCALE`, with `Math.round`, `Math.floor` or `Math.ceil` before returning them. See [Passing integers](/v2/guide/native-values#passing-integers).
### Draw with Cairo in `vfuncSnapshot`
A widget that draws with Cairo from its own `vfuncSnapshot`, as many C widgets and gtk4-demo's Paint do, gets a context from `snapshot.appendCairo(bounds)`. Declare it with `using` so it is released once the method has drawn, where C calls `cairo_destroy`:
```ts
import { type ImageSurface } from "@gtkx/cairo";
import * as Graphene from "@gtkx/gi/graphene";
import * as Gtk from "@gtkx/gi/gtk";
import { registerClass } from "@gtkx/runtime";
class CanvasBase extends Gtk.Widget {
surface: ImageSurface | null = null;
override vfuncSnapshot(snapshot: Gtk.Snapshot): void {
using cr = snapshot.appendCairo(
new Graphene.Rect().init(0, 0, this.getWidth(), this.getHeight()),
);
if (this.surface) {
cr.setSourceSurface(this.surface, 0, 0);
cr.paint();
}
}
}
const Canvas = registerClass(CanvasBase, { typeName: "ExampleCanvas" });
```
Without `using`, a widget that keeps drawing into `surface` grows in memory with every frame until garbage collection; [Release contexts you create](/v2/guide/cairo#release-contexts-you-create) explains why. A `GtkDrawingArea` `drawFunc` needs no call.
### Slots with no generated member
Use [`callParent`](/v2/reference/@gtkx/runtime/functions/callParent) when the virtual function has no generated member, including `vfuncDispose`. Pass the class whose override is running, the vfunc name, the instance, and its arguments. The same helper can chain interface slots that TypeScript cannot resolve through `super`.
### Disposal
As in GJS, `vfuncDispose` runs only while the instance's JavaScript object is alive, such as after `runDispose()` or when a window is destroyed. An object released by GTK is usually disposed after its JavaScript object has been garbage-collected; GTKX then skips the override, which could no longer reach the instance's JavaScript state, and runs the parent implementation. Stop timers and other JavaScript-driven work where it is started, such as in `vfuncUnmap` or an effect cleanup, rather than relying on `vfuncDispose`.
When the application quits, GTKX stops keeping objects alive for their JavaScript objects while JavaScript still runs. Objects that only JavaScript references are disposed then, widgets first, then instances of registered classes, then other objects, and the objects they own go with them, as in C. Their `vfuncDispose` overrides run with their JavaScript state, and vfuncs other objects call while they are torn down, such as a column view reading the size of a JavaScript list model, run as usual. Objects GTK itself still holds at that point, such as a window that was never destroyed, are not disposed, as in a C application.
## Implementing an interface
List the generated interface value in `implements` and implement its required vfunc methods. The generated `Impl` type checks their signatures:
```ts
import * as Gio from "@gtkx/gi/gio";
import { Object, TYPE_OBJECT } from "@gtkx/gi/gobject";
import { registerClass } from "@gtkx/runtime";
class LevelStoreBase extends Object implements Gio.ListModelImpl {
rows: Object[] = [];
vfuncGetItemType(): bigint {
return TYPE_OBJECT;
}
vfuncGetNItems(): number {
return this.rows.length;
}
vfuncGetItem(position: number): Object | null {
return this.rows[position] ?? null;
}
}
const LevelStore = registerClass(LevelStoreBase, {
typeName: "ExampleLevelStore",
implements: [Gio.ListModel],
});
```
Write vfuncs as prototype methods, not arrow-function fields.
Every slot of an `Impl` type is optional, so TypeScript rejects `implements` on a class that fills none of them, such as a `Gtk.Scrollable` widget that only overrides the interface's adjustment and scroll-policy properties; register that class with `implements: [Gtk.Scrollable]` and leave out the `implements` clause.
The `Impl` type checks signatures; it does not establish that every required native operation has an implementation. Follow the interface's prerequisites and behavior contract. For this example, [Gio.ListModel](https://docs.gtk.org/gio/iface.ListModel.html) also requires change notifications when items change.
Registration adds the interface's public members to instances. Inside the class, declare any added member you call, such as `declare itemsChanged: Gio.ListModel["itemsChanged"];`. Use a base class whose native state agrees with the implementation you provide.
### Delegating `Gtk.Editable`
GTK's [recipe for implementing `Gtk.Editable`](https://docs.gtk.org/gtk4/iface.Editable.html#implementing-gtkeditable) wraps an inner `Gtk.Text`: return it from `vfuncGetDelegate`, call `initDelegate()` once it exists and `finishDelegate()` in `vfuncDispose`. GTKX forwards the interface's properties (`text`, `cursorPosition`, `editable`, `widthChars`, `xalign` and the rest) to the delegate automatically, as `gtk_editable_delegate_set_property` and `gtk_editable_delegate_get_property` do in C, so skip that step of the recipe. Props such as `text` and `editable` on the class's element then reach the inner field:
```ts
import * as Gtk from "@gtkx/gi/gtk";
import { callParent, registerClass } from "@gtkx/runtime";
class SearchFieldBase extends Gtk.Widget implements Gtk.EditableImpl {
declare private delegate: Gtk.Text | null;
declare initDelegate: Gtk.Editable["initDelegate"];
declare finishDelegate: Gtk.Editable["finishDelegate"];
override vfuncConstructed(): void {
super.vfuncConstructed();
const text = new Gtk.Text({ hexpand: true });
text.setParent(this);
this.delegate = text;
this.initDelegate();
}
vfuncGetDelegate(): Gtk.Editable | null {
return this.delegate;
}
vfuncDispose(): void {
if (this.delegate !== null) {
this.finishDelegate();
this.delegate.unparent();
this.delegate = null;
}
callParent(SearchField, "vfuncDispose", this);
}
}
const SearchField = registerClass(SearchFieldBase, {
typeName: "ExampleSearchField",
implements: [Gtk.Editable],
classInit(klass: Gtk.WidgetClass) {
klass.setLayoutManagerType(Gtk.BoxLayout);
},
});
```
Create the delegate in `vfuncConstructed`: reading or writing an editable property while `vfuncGetDelegate` returns `null` throws.
### Reporting a vfunc error
Throw from a vfunc that reports errors through `GError`. GTKX preserves a thrown `GLib.Error`, such as `new GLib.Error(Gio.IOErrorEnum, Gio.IOErrorEnum.PERMISSION_DENIED, "Read-only")`, and converts other exceptions into a native error. A virtual function without an error channel cannot report failure that way; see [Error Handling](/v2/guide/error-handling).
## Adding actions
A registered class that builds its own action group adds a table of actions with `addActionEntries`; see [Actions in a registered class](/v2/guide/actions#actions-in-a-registered-class). A window or application that React renders declares its actions with the `actions` prop, as [Actions and Shortcuts](/v2/guide/actions) shows.
## Elements that cannot be children
Express native object relationships through JSX props and supported child slots. For an object that needs React ownership without native child placement, use [a portal](/v2/guide/modals-and-portals). Add native placement rules through [element configuration](/v2/guide/configuration-and-codegen#advanced-customizing-elements).
## Initialization order
`vfuncConstructed` runs after native construct properties are set, while `super()` is still executing. JavaScript field initializers and the constructor body have not run yet. Other properties passed to the constructor, including element props, are set after it returns: a binding or `notify` handler connected there receives them, but reading them directly there returns their defaults. Use declared fields or native properties for state this override needs; private fields are unavailable at that point.
Objects created by native code do not run the JavaScript constructor or its field initializers. Initialize state needed by those instances in `vfuncConstructed`, chaining to the parent. Keep ordinary component setup in React.
## GtkBuilder and `.ui` files
GTKX applications define their interface in JSX, where signal handlers are props; port a `.ui` file or a `Gtk.Template` to JSX rather than loading it. `Gtk.Builder` can still create instances of registered classes from XML, initialized in `vfuncConstructed` as above, but `` handlers in a `.ui` file are not supported. GTKX has no built-in JavaScript `Gtk.BuilderScope` like GJS's, and a scope implemented with `registerClass` cannot return a closure from `vfuncCreateClosure`, so such a file fails to load.
---
---
title: "Cairo"
description: "Use GTKX Cairo values in drawing callbacks and render images offscreen."
---
# Cairo
`@gtkx/cairo` provides the drawing objects used by GTKX's native bindings. Projects created with `create-gtkx` already depend on it; otherwise, install it:
```bash
npm install @gtkx/cairo@beta
```
This guide covers the GTKX integration. For drawing techniques, use the [Cairo manual](https://www.cairographics.org/manual/); for available methods and types, see the [GTKX Cairo reference](/v2/reference/@gtkx/cairo/).
## Draw in a widget
Add a `GtkDrawingArea` inside your application's JSX tree. Its `drawFunc` receives a managed Cairo context and the widget's current dimensions:
```tsx [src/components/circle.tsx]
import { GtkDrawingArea } from "@gtkx/jsx/gtk";
export function Circle() {
return (
{
cr.setSourceRgb(0.2, 0.4, 0.9);
cr.arc(
width / 2,
height / 2,
Math.min(width, height) / 3,
0,
2 * Math.PI,
);
cr.fill();
}}
/>
);
}
```
Captured from the sample above. The area fills the window, so the circle follows the callback's width and height rather than the requested 200 × 120.
Draw only inside this callback: do not update widget properties or React state from it. Keep the context local to the callback: GTKX releases it when the callback returns, and any later call on it throws.
Changing `drawFunc` queues a repaint, including when a render supplies a new callback. If drawing data changes without replacing the callback, call `queueDraw()` on the area obtained through its `ref`. Use the callback's dimensions when drawing; `contentWidth` and `contentHeight` request a size, which can differ from the allocated space.
## Share values with native libraries
GTK and PangoCairo return the same managed classes that you import from `@gtkx/cairo`. Pass these objects directly between APIs. For example, `PangoCairo.showLayout(cr, layout)` accepts the context from `drawFunc` without conversion.
Use Pango for application text. Inside `drawFunc`, create the layout with the widget's `createPangoLayout(text)`, which uses the widget's font, and draw it with PangoCairo:
```tsx
import * as PangoCairo from "@gtkx/gi/pangocairo";
import { GtkDrawingArea } from "@gtkx/jsx/gtk";
const Caption = () => (
{
const layout = area.createPangoLayout("Mood this week");
cr.moveTo(8, 8);
PangoCairo.showLayout(cr, layout);
}}
/>
);
```
`PangoCairo.createLayout(cr)` creates a layout with Pango's default font rather than the widget's, so text drawn with it does not match the rest of the interface. Use it for offscreen rendering, and set a font with `layout.setFontDescription()`; `widget.getPangoContext().getFontDescription()` returns the font a widget uses. The [PangoCairo documentation](https://docs.gtk.org/PangoCairo/) covers shaping, font fallback and layout; import its bindings from `@gtkx/gi/pangocairo`.
`cr.copyPath()` and `cr.copyPathFlat()` return a `Path`, which `cr.appendPath()` and bindings such as `Gsk.PathBuilder.addCairoPath()` accept as is. This turns text into a `GskPath`, for example:
```ts
import * as Gsk from "@gtkx/gi/gsk";
import * as PangoCairo from "@gtkx/gi/pangocairo";
PangoCairo.layoutPath(cr, layout);
const builder = Gsk.PathBuilder.new();
builder.addCairoPath(cr.copyPathFlat());
const textPath = builder.toPath();
```
Call `path.toData()` to read a path's segments.
Values returned by native libraries use their concrete wrapper classes. Check `surface instanceof ImageSurface` before reading image pixels from a surface returned by `cr.getTarget()`.
## Render offscreen
An `ImageSurface` lets you draw without a widget. Create a context for it, then save the result:
```ts
import {
Context,
Format,
ImageSurface,
Status,
statusToString,
} from "@gtkx/cairo";
const writeSwatch = (path: string): void => {
const surface = new ImageSurface(Format.ARGB32, 256, 256);
using cr = Context.create(surface);
cr.setSourceRgb(0.9, 0.3, 0.2);
cr.paint();
const status = surface.writeToPng(path);
if (status !== Status.SUCCESS) throw new Error(statusToString(status));
};
```
`getData()` returns a copy of the image's pixels, including row padding. Editing that array does not change the surface; draw through its context to update it. Load a saved image with `ImageSurface.createFromPng(path)`.
## Release contexts you create
A context obtained outside a draw callback holds its target surface until JavaScript garbage-collects it. This applies to the contexts from `Context.create(surface)` and from `snapshot.appendCairo(bounds)` in a widget's `vfuncSnapshot`, as well as those returned by other native calls. Declare the context with [`using`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/using) so it is released when its block exits, where C calls `cairo_destroy`; the offscreen example above does. To release it at another point, call `cr[Symbol.dispose]()`.
Releasing them matters most for contexts created on every frame. A snapshot context records the frame, and Cairo copies a backing surface into each recording that still holds it when the app draws into that surface again. Without releasing them, a widget that paints a canvas it keeps updating can grow to gigabytes before the garbage collector runs. [Subclassing](/v2/guide/subclassing#draw-with-cairo-in-vfuncsnapshot) shows the pattern.
Once released, every call on the context throws. Releasing it again does nothing. If a native call is still drawing with the context, for example when it is released in a callback that call invoked, the release throws and leaves the context usable.
## Handle errors
Creating an image with an invalid size or loading a missing PNG throws. Queries that cannot return a value also throw: for example, reading gradient stops from a solid pattern or requesting rectangles for a circular clip.
Drawing operations retain Cairo's status model. Check `cr.status()` after drawing; operations that return a `Status`, such as `writeToPng`, need their return value checked directly. Use `statusToString` when presenting an error.
---
---
title: "OpenGL"
description: "Use GTKX's OpenGL bindings inside a GtkGLArea."
---
# OpenGL
`@gtkx/gl` provides OpenGL bindings for drawing inside a `GtkGLArea`. `create-gtkx` projects don't include it; install it:
```bash
npm install @gtkx/gl@beta
```
This guide covers GTKX integration. Use the [Khronos OpenGL reference](https://registry.khronos.org/OpenGL-Refpages/gl4/) for the rendering API and the [GTKX GL reference](/v2/reference/@gtkx/gl/) for how its names and types map to the bindings.
## Draw in a widget
Place a `GtkGLArea` inside your application's JSX tree. Its `onRender` handler runs with the area's GL context and framebuffer ready for drawing:
```tsx [src/color-area.tsx]
import * as Gdk from "@gtkx/gi/gdk";
import * as gl from "@gtkx/gl";
import { GtkGLArea } from "@gtkx/jsx/gtk";
export const ColorArea = () => (
{
gl.clearColor(0.5, 0.5, 0.5, 1);
gl.clear(gl.COLOR_BUFFER_BIT);
return Gdk.EVENT_STOP;
}}
/>
);
```
Captured from the sample above. The handler clears the framebuffer to gray, and GTK draws it below the header bar.
GTK presents the result as part of the surrounding widget tree. Returning `Gdk.EVENT_STOP` marks the render signal as handled. Like every signal handler, `onRender` also receives the area as its last argument (see the [JSX prop model](/v2/guide/jsx-elements#the-jsx-prop-model)).
For complete shader and geometry setup, see the [GLArea, Gears and Shadertoy examples](https://github.com/gtkx-org/gtkx/tree/main/examples/gtk-demo/src/demos/opengl).
## Use the bindings
The bindings are generated from the OpenGL 4.6 core registry. Commands omit the `gl` prefix and start with a lowercase letter; constants omit `GL_`. For example, use `gl.compileShader` and `gl.TRIANGLES`.
Object creation and deletion also have singular helpers: `gl.genBuffer()` returns one name, while `gl.genBuffers(count)` returns an array. Pass typed-array views directly, with their byte length where the command takes a size, as in `gl.bufferData(gl.ARRAY_BUFFER, vertices.byteLength, vertices, gl.STATIC_DRAW)`. `GLint64` and `GLuint64` values are `bigint`.
Pass `null` as the lengths of `shaderSource` to read each source to its end, as `NULL` does in C:
```ts
gl.shaderSource(shader, 1, [source], null);
```
Explicit lengths count UTF-8 bytes, so `[source.length]`, which counts UTF-16 code units, truncates any source with a non-ASCII character, even one in a comment.
Generic state queries such as `getIntegerv` are not exported. Use the typed query for the object you are inspecting, such as `getShaderiv` or `getProgramiv`. `getShaderInfoLog` and `getProgramInfoLog` return the driver's diagnostics as strings.
## Manage context resources
Create GL objects in `onRealize` and delete them in `onUnrealize`, making the area's context current first in both. Realization follows the native widget's lifecycle, so it can happen after the React component mounts. Keep the object names in refs:
```tsx
import * as gl from "@gtkx/gl";
import { GtkGLArea } from "@gtkx/jsx/gtk";
import { useRef } from "react";
export const BufferArea = () => {
const buffer = useRef(null);
return (
{
area.makeCurrent();
if (area.getError()) {
return;
}
buffer.current = gl.genBuffer();
}}
onUnrealize={(area) => {
area.makeCurrent();
if (buffer.current !== null) {
gl.deleteBuffer(buffer.current);
buffer.current = null;
}
}}
/>
);
};
```
`onRender` and `onResize` already run with the context current. Call `makeCurrent()` before issuing GL commands from other handlers. GTK sets the viewport when the area resizes; use `onResize` for other size-dependent state, such as a camera's aspect ratio.
Configure the context through JSX before realization. `allowedApis` selects GL or GLES, while `hasDepthBuffer` and `hasStencilBuffer` request framebuffer attachments. Use `area.getApi()` to choose rendering code compatible with the context that was created. A realized area keeps its context: GTK rejects a later `allowedApis` change with a critical, including one made by editing the prop while `gtkx dev` runs. To switch APIs, give the area a React `key` that changes with `allowedApis`, so React replaces it with a new area. See [GTK's GLArea documentation](https://docs.gtk.org/gtk4/class.GLArea.html) for the native lifecycle and context options.
## Request another frame
Changing React state does not itself repaint the GL scene. Obtain the area through its `ref` and call `queueRender()` when the scene needs drawing again.
With the default `autoRender`, GTK emits the render signal whenever the widget draws. With `autoRender={false}`, ordinary redraws reuse the previous frame; resizing the area or calling `queueRender()` requests a new one.
For continuous animation, advance the scene and call `queueRender()` from a [tick callback](https://docs.gtk.org/gtk4/method.Widget.add_tick_callback.html), registered while the area is mounted:
```tsx
import * as Gdk from "@gtkx/gi/gdk";
import * as GLib from "@gtkx/gi/glib";
import type * as Gtk from "@gtkx/gi/gtk";
import * as gl from "@gtkx/gl";
import { GtkGLArea } from "@gtkx/jsx/gtk";
import { useLayoutEffect, useRef, useState } from "react";
export const PulsingArea = () => {
const [area, setArea] = useState(null);
const seconds = useRef(0);
useLayoutEffect(() => {
if (area === null) {
return;
}
const id = area.addTickCallback((_widget, clock) => {
seconds.current = Number(clock.getFrameTime()) / 1_000_000;
area.queueRender();
return GLib.SOURCE_CONTINUE;
});
return () => area.removeTickCallback(id);
}, [area]);
return (
{
const red = 0.5 + 0.5 * Math.sin(seconds.current);
gl.clearColor(red, 0.5, 0.5, 1);
gl.clear(gl.COLOR_BUFFER_BIT);
return Gdk.EVENT_STOP;
}}
/>
);
};
```
## Show an error
Pass a `GLib.Error` to `area.setError()` to display an error inside the widget, and pass `null` to clear it after recovery. Context initialization failures are available through `area.getError()`. See [Error Handling](/v2/guide/error-handling) for errors raised by binding calls.
---
---
title: "Testing"
description: "Test GTKX components with native widgets, accessible queries, and user interactions."
---
# Testing
`@gtkx/testing` renders GTKX components and provides queries, interactions, and assertions for native widgets. Its API follows React Testing Library conventions.
## Setup
Projects created with `npm create gtkx@beta` can include testing setup. To add it to an existing project, install the test dependencies:
```bash
npm install -D @gtkx/testing@beta vitest
```
Add a `test` script that runs `vitest run`, and create `vitest.config.ts`:
```ts
import gtkx from "@gtkx/cli/vitest-plugin";
import { defineConfig } from "vitest/config";
export default defineConfig({
plugins: [gtkx()],
test: {
include: ["tests/**/*.test.{ts,tsx}"],
},
});
```
In a JavaScript project, name the file `vitest.config.js` and include `tests/**/*.test.{js,jsx}` instead.
The plugin gives each worker a private headless display and session bus, which need Sway and `dbus-daemon`. On Fedora 44, install these with:
```bash
sudo dnf install sway dbus-daemon
```
Then run the tests:
```bash
npm test
```
If `sway` or `dbus-daemon` is missing from `PATH`, the run stops before any test starts and names each missing tool, with an install command when GTKX recognizes the distribution. See the [plugin reference](/v2/reference/@gtkx/vitest/) for the display size and other options.
With the GTKX Vitest plugin, importing `@gtkx/testing` registers widget matchers and automatic cleanup. No additional setup file is needed.
### Test environment
Each test file runs in its own worker process, with a GTK runtime and display that shut down once the file's tests finish. Vitest's `isolate: false` would reuse that worker for the next file, so the run stops before any test starts when it is set.
A package that is not an application, such as a [component library](/v2/guide/workspaces#component-libraries), runs its tests the same way without an `applicationId`, as the application `org.gtkx.Test`.
The private session bus contains GTKX's minimal notifications service. Other desktop services, such as portals and keyrings, are absent; provide any D-Bus services the component under test needs on that bus.
### Test data and settings
Tests share the user's files: `GLib.getUserDataDir()` and the other XDG directories point where the app's do. To keep test data apart, set the XDG variables in a [setup file](https://vitest.dev/config/setupfiles). GLib reads each XDG variable once, and GTK reads the data, configuration and cache directories as soon as a test file imports `@gtkx/react` or `@gtkx/testing`, so setting `process.env.XDG_DATA_HOME` in `beforeEach` or in a test has no effect.
```ts [tests/setup.ts]
import { mkdtempSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { afterAll } from "vitest";
const dataHome = mkdtempSync(join(tmpdir(), "my-app-test-"));
process.env.XDG_DATA_HOME = dataHome;
afterAll(() => {
rmSync(dataHome, { recursive: true, force: true });
});
```
List it under `test.setupFiles` in `vitest.config.ts`, and clear the app's files in `beforeEach` when tests must not see each other's data.
GSettings does not use those directories in tests: GTKX runs them with GLib's in-memory settings backend, so tests never read or change the user's settings. Each test file starts from the schema defaults, and a value one test writes stays for the following tests in the same file. Reset the keys in `beforeEach` when each test should start from the defaults:
```ts
import * as Gio from "@gtkx/gi/gio";
import { beforeEach } from "vitest";
import schema from "../data/com.example.MyApp.gschema.xml";
beforeEach(() => {
const settings = Gio.Settings.new(schema.id);
for (const key of Object.keys(schema.keys)) settings.reset(key);
});
```
### Headless development
[`gtkx dev --headless`](/v2/guide/cli#gtkx-dev) runs the app in the same environment as a test worker, with its own display, session bus and in-memory settings, so settings changed in the session are gone when it stops. `--size` sets the display size, which defaults to `1024x768`:
```bash
gtkx dev --headless --size 1280x720
```
Use Ctrl+C to stop the session and release its display. Later development or test runs reclaim sessions left by interrupted runs; [`gtkx cleanup --dry-run`](/v2/guide/cli#gtkx-cleanup) lists them and `gtkx cleanup` removes them.
### Sway in a restricted container
Fedora may install Sway with the `CAP_SYS_NICE` file capability. A rootless container that excludes that capability can fail to start Sway with exit status 126, before a test runs. Check the container capability policy. For a disposable test container, removing the capability with `sudo setcap -r "$(command -v sway)"` allows Sway to run without it. This is a container workaround, not a desktop setup step.
## Rendering a component
Await `render` before querying or interacting with widgets. This example tests an application's `SettingsPanel`:
```tsx
import * as Gtk from "@gtkx/gi/gtk";
import { render, screen, userEvent } from "@gtkx/testing";
import { expect, it } from "vitest";
import { SettingsPanel } from "../src/settings-panel.js";
it("saves the display name", async () => {
await render();
const name = screen.getByRole(Gtk.AccessibleRole.TEXT_BOX, {
name: "Display name",
});
await userEvent.type(name, "Ada");
await userEvent.click(
screen.getByRole(Gtk.AccessibleRole.BUTTON, { name: "Save" }),
);
expect(await screen.findByText("Settings saved")).toBeVisible();
});
```
Components render inside a test window by default. An application component that creates its own window needs `rootElement` instead:
```tsx
import { rootElement } from "@gtkx/react";
await render(, { container: rootElement });
```
`rootElement` expects a tree that creates a toplevel window; omit `container` for components without their own window. An application window such as `AdwApplicationWindow` must render inside an application element, so wrap a window component tested on its own in `AdwApplication`. Use the `wrapper` option for context providers.
`rerender` updates the rendered component and `unmount` removes it. Automatic cleanup unmounts rendered trees after each test. Unmounting also quits the application a render started, even one that holds itself or waits out its `inactivityTimeout`, so the next render can register the same application ID. Animations are disabled unless the `areAnimationsEnabled` render option is set. For hooks, use `renderHook` and assert on `result.current`.
### Module-level state
The GTKX plugin loads GTKX's packages through Vitest's module graph, so `vi.resetModules()` resets them along with your modules. Importing the app again afterwards would evaluate a second copy of GTKX beside the one `@gtkx/testing` uses, and GTKX throws an error naming `vi.resetModules()` instead. To give each test fresh state, create it in a function and pass it in as a prop rather than holding it at module level:
```tsx
import { rootElement } from "@gtkx/react";
import { render, screen } from "@gtkx/testing";
import { expect, it } from "vitest";
import { App } from "../src/app.js";
import { loadState } from "../src/store.js";
it("restores the saved feeds", async () => {
await render(, { container: rootElement });
expect(await screen.findByText("Planet GNOME")).toBeVisible();
});
```
The entry point does the same with `createRoot().render()`.
## Finding widgets
Prefer `screen.getByRole` with a `Gtk.AccessibleRole` enum and an accessible name. `screen` searches open toplevel windows, including dialogs and popovers. Use `within(container)` to restrict a query to a subtree.
GTKX follows [Testing Library's query conventions](https://testing-library.com/docs/queries/about/). Other query families match label text, placeholders, display values, or the widget's `name` prop; see the [query reference](/v2/reference/@gtkx/testing/).
`findBy` and `findAllBy` queries take wait options as their third argument, as in Testing Library, or with the query options, as in `screen.findByRole(Gtk.AccessibleRole.BUTTON, { name: "Save", timeout: 3000 })`.
Queries exclude widgets that are not mapped, including content on inactive stack pages. The `hidden` option on role queries only includes widgets excluded from the accessibility tree; it does not include unmapped widgets. A role query matches an Adwaita dialog only once its content is shown, which libadwaita does a frame after the dialog opens, so a dialog found with `findByRole` can be queried right away.
A text button's child label takes precedence over its `accessibleLabel` prop. Query the visible label and use `within` when several buttons share it.
Some Adwaita rows expose their inner control under the row's title as well, as they do to assistive technologies. An `AdwEntryRow` and its text field both carry the title as their label, so `getByLabelText("Message")` finds two widgets; `getByRole(Gtk.AccessibleRole.TEXT_BOX, { name: "Message" })` finds the field. An `AdwSwitchRow` and its switch both have the `switch` role and the row's title as their name. Pass the `as` option to keep one widget class, which also types the result:
```ts
import * as Adw from "@gtkx/gi/adw";
const row = screen.getByRole(Gtk.AccessibleRole.SWITCH, {
name: "Reimbursable",
as: Adw.SwitchRow,
});
await userEvent.click(row);
expect(row).toBeChecked();
```
GTK ignores `accessibleLabel` on widgets whose accessible role takes no name, such as the `generic` role of a plain `GtkBox` or a `GtkDrawingArea`, so neither assistive technologies nor queries see it. Give such a widget a role that is named, as in `` for a chart or `Gtk.AccessibleRole.GROUP` for a box of related controls.
## Interacting and waiting
Await every `userEvent` call. Helpers wait for the target to become actionable and flush React updates before resolving, and fail naming what blocks it, such as an open dialog over the target. Pointer helpers also wait until a pointer can reach the target; when an ancestor's `canTarget` is off, the error names the widget a pointer would land on instead, which the test can click.
Keyboard modifiers and pointer buttons held with `>` stay held across calls until released, and the cleanup after each test releases those the default `userEvent` still holds. `userEvent.setup()` creates an instance with its own held state, and its `delay` option waits after each action:
```ts
const user = userEvent.setup();
await user.keyboard(entry, "{Control>}a{/Control}");
await user.type(entry, "Replacement");
await user.click(saveButton);
```
### Keyboard
`type` inserts text into an editable widget one character at a time, each as its own edit, and presses the keys named in braces, as in Testing Library's [`keyboard`](https://testing-library.com/docs/user-event/keyboard) syntax, so `type(entry, "Ada{Enter}")` types "Ada" and then activates the entry. Handlers that react to single typed characters, such as GtkSourceView's interactive completion, see each one. Type a literal `{` as `{{`.
`keyboard(widget, keys)` sends the keys to the focused widget inside `widget`, or to `widget` itself. A widget that can take focus, or passes it to a child as a `GtkMenuButton` does to its button, is focused first unless the focus is already inside it, as a user would before typing. `{Space}` on a switch therefore toggles that switch, whatever had focus before. Keys go through GTK's key bindings and key controllers, including the ones GTK's own widgets add, so `{Space}` or `{Enter}` selects a swatch in a `GtkColorChooserWidget`.
`keyboard(keys)` without a widget sends the keys to the focused widget of the active window, as Testing Library does, or to the window itself while its focus widget is not on screen. Keys no widget handles reach the window's bindings, so `{Tab}`, `{Shift>}{Tab}{/Shift}` and arrow keys move focus.
Some key handlers read the real key event, which `keyboard` cannot create, so they do not receive the keys:
- GtkSourceView's own key handling, such as auto-indent and bracket completion. Keys in a `GtkSourceView` behave as in a plain `GtkTextView`, except that its completion list takes them while it shows: arrow keys move the selection, `{Enter}` chooses the selected proposal and `{Escape}` hides the list.
- The key capture of a `GtkSearchEntry` or `GtkSearchBar` that has a key capture widget.
- A file chooser's key forwarding.
- The interactive search of the deprecated `GtkTreeView`.
- A WebKit web view.
Key controllers the app adds always receive the keys. In the same way, a click reaches GTK's own pointer handling of a widget only where `@gtkx/testing` knows its outcome, as for buttons, rows and tabs. A click on a color swatch or a completion proposal does nothing, so press `{Space}` or `{Enter}` on a swatch, and choose a proposal with the arrow keys and `{Enter}`. As in Testing Library, input that nothing handles is not an error.
### Pointer buttons
`pointer` takes Testing Library's [button tokens](https://testing-library.com/docs/user-event/pointer). `[MouseLeft]` clicks the widget as `click` does, and `[MouseRight]` and `[MouseMiddle]` press and release the other buttons for the click gestures on the widget and its ancestors that listen for them, so `pointer(cell, "[MouseRight]")` opens a context menu that a `GtkGestureClick` with `button={Gdk.BUTTON_SECONDARY}` shows. Add `>` to only press a button, as in `[MouseRight>]`, and a leading `/` to release it. A gesture's handlers read the pressed button with `getCurrentButton()` and the held modifiers with `getCurrentEventState()`. No real pointer event exists, so `getCurrentEvent()` returns `null`: port upstream code that reads the button from the event, such as `event.get_button()`, to `getCurrentButton()`.
### Selection
`selectOptions` and `deselectOptions` take positions rather than option values or labels, because GTK drop-downs, lists and grids have no option values: `selectOptions(dropDown, 2)` selects the third item, and an array selects several positions in a multiple-selection list. A position past the last item, or an option label, rejects with the range of valid positions and leaves the selection unchanged.
### Sliders and drag and drop
Use `slide(range, value)` for a slider. `drag` drives application-defined drag gestures and cannot drive a range's native slider. The [interaction reference](/v2/reference/@gtkx/testing/) covers the available helpers.
Use `dragAndDrop(source, target)` to transfer a drag source's typed content to a `GtkDropTarget`. Use `drop(target, content)` when testing how a target handles a supplied value. Gesture helpers such as these, `drag` and `longPress` use the nearest controller from the given widget up through its ancestors, as GTK propagates pointer events, so you can pass the visible label of a cell whose container carries the controller.
### Signals and waiting
`fireEvent(object, signalName, ...args)` emits a GObject signal directly. Await its promise so the resulting React updates finish before asserting. Use it when testing a signal handler or a tree without a visible window. Wrap state changes made outside these helpers in `act`.
For asynchronous assertions, use `waitFor`; for a widget leaving the tree, use `waitForElementToBeRemoved`. Their timeout defaults to one second and can be changed per call or through `configure`.
### Fake timers
Vitest's [fake timers](https://vitest.dev/guide/mocking/timers) replace JavaScript timers only. GLib timeouts keep the real clock, including GTK's own, such as the `searchDelay` after which a `GtkSearchEntry` emits `search-changed`, so advancing fake time does not fire them. Under `vi.useFakeTimers()`, `waitFor` and `findBy` queries advance the fake clock by their polling interval and then wait the same interval in real time, so both kinds of timer run while they poll. Assert through them rather than right after `vi.advanceTimersByTime()`:
```ts
vi.useFakeTimers();
await user.type(screen.getByRole(Gtk.AccessibleRole.SEARCH_BOX), "mus");
await waitFor(() => expect(screen.queryByText("photos/")).toBeNull());
```
`userEvent` helpers wait between actions only when `delay` is set, so unlike Testing Library's, `userEvent.setup()` takes no `advanceTimers` option.
## Assertions and debugging
Use widget matchers such as `toHaveTextContent`, `toHaveAccessibleName`, `toBeChecked`, and `toHaveDisplayValue`. Accessible states and properties have their own matchers, `toHaveAccessibleState` and `toHaveAccessibleProperty`. See the [matcher reference](/v2/reference/@gtkx/testing/) for the complete set.
`screen.debug()` prints the widget tree, and `screen.logRoles()` groups widgets by accessible role. Capture the active window with `await screen.screenshot({ path: "test.png" })`, or pass a widget to `screenshot` to capture a subtree. The [MCP server](/v2/guide/mcp) provides the same inspection tools during development.
Snapshot assertions print a widget as its widget tree in the `screen.debug()` format, so `expect(container).toMatchSnapshot()` records the rendered widgets.
GLib prints criticals and warnings to the test output without failing the test, and a GLib `ERROR` aborts the worker. Set GLib's `G_DEBUG` environment variable, for example to `fatal-criticals`, to make criticals abort the worker instead. See [Error Handling](/v2/guide/error-handling#glib-criticals-and-warnings). A [native addon panic](/v2/guide/error-handling#addon-panics) outside a binding call fails the test as an uncaught exception.
A render error that an error boundary catches does not fail the test, so a test can assert the boundary's fallback; the `onCaughtError` render option receives it. An error no boundary catches rejects `render`, or the next `rerender`, `unmount` or cleanup, with that error.
## Next
The [tutorial's testing chapter](/v2/tutorial/testing) applies these tools to a complete application.
---
---
title: "Storybook"
description: "Browse native GTKX component stories, edit arguments, record actions, and reuse the same stories in integration tests."
---
# Storybook
`@gtkx/storybook` runs [CSF3 component stories](https://storybook.js.org/docs/api/csf) in a native Adwaita explorer. It supplies a story navigator, a preview, controls, and an action panel, using the same GTKX runtime and generated bindings as your application.
## Start the explorer
In an existing GTKX project:
```sh
npm install -D @gtkx/storybook@beta
```
Start the explorer with `npx gtkx storybook`; add [`--headless --size 1280x900`](/v2/guide/cli#gtkx-storybook) when you need a private display. It finds story files such as `src/button.stories.tsx` under `src` without configuration. To choose other files, create `.storybook/main.ts`:
```ts
import { defineConfig } from "@gtkx/storybook/config";
export default defineConfig({
stories: ["src/components/**/*.stories.tsx"],
});
```
Patterns are relative to the GTKX project root. Your `gtkx.config.ts` still defines the application settings and additional GIR libraries. [Asset imports](/v2/guide/assets) work as they do in the application.
The explorer registers under the project's application ID with a `.Storybook` suffix, so it can run alongside `gtkx dev`. A running explorer exposes the [GTKX MCP server](/v2/guide/mcp) for live widget inspection and interaction.
### Stories from a shared package
In a [monorepo](/v2/guide/workspaces#monorepos), an app's patterns can reach the stories of a shared component package, as Storybook monorepo configurations do:
```ts
export default defineConfig({
stories: ["src/**/*.stories.tsx", "../../packages/ui/src/**/*.stories.tsx"],
});
```
Every matched file must lie inside the workspace root, the directory holding `pnpm-workspace.yaml` or the `package.json` with `workspaces`; the explorer stops with an error naming any file outside it. The explorer runs with the app's `gtkx.config.ts`, so the app has to declare the libraries the shared stories import. Stories without a `title` are named by their path from the workspace root, such as `packages/ui/src/badge`.
To browse a shared package's stories on their own, set it up as a [component library](/v2/guide/workspaces#component-libraries), add `@gtkx/storybook` as a development dependency and run `gtkx storybook` in its directory. It needs no `applicationId`; its explorer registers as `org.gtkx.Library.Storybook`.
## Define stories
Keep each component in its own module so that Fast Refresh updates it in place. Write a component in `src/button.tsx`:
```tsx [src/button.tsx]
import { GtkButton } from "@gtkx/jsx/gtk";
import type { ReactNode } from "react";
type ButtonProps = {
label: string;
enabled: boolean;
onClicked?: () => void;
};
const Button = ({ label, enabled, onClicked }: ButtonProps): ReactNode => (
);
export { Button };
```
and its stories in `src/button.stories.tsx`:
```tsx [src/button.stories.tsx]
import type { Meta, StoryObj } from "@gtkx/storybook";
import { Button } from "./button.js";
const meta = {
title: "Components/Button",
component: Button,
args: { label: "Save", enabled: true },
argTypes: {
label: { control: "text" },
enabled: { control: "boolean" },
onClicked: { action: "clicked" },
},
} satisfies Meta;
type Story = StoryObj;
const Default = {} satisfies Story;
const Disabled = { args: { enabled: false } } satisfies Story;
export default meta;
export { Default, Disabled };
```
The explorer showing these stories, captured after clicking Save in the preview. The controls come from argTypes, and the click is recorded under Actions.
An argument gets a native control only when its `argTypes` entry sets [`control`](https://storybook.js.org/docs/api/arg-types#control): `boolean`, `text`, `number` or `range`, and `select`, `radio` or `inline-radio`. The explorer does not infer controls from the args, so an argument without `control` has none and needs no `control: false`. `argTypes.onClicked.action` records callback calls in the action panel; asynchronous callbacks are recorded once when they settle. You can also provide `action("clicked")` from `@gtkx/storybook` directly as an argument.
Shared preview configuration belongs in `.storybook/preview.tsx`, exported as an object satisfying `Preview` from `@gtkx/storybook`. [Decorators](https://storybook.js.org/docs/writing-stories/decorators) return ordinary GTKX JSX and receive the resolved story context.
Controls preserve absent arguments until you edit them. Choice controls display a placeholder for an unset value; selecting it clears the argument. Set `table.readonly: true` on an argument's metadata to show a disabled control, or `table.disable: true` to hide it. A [conditional](https://storybook.js.org/docs/api/arg-types#if) `if` on an argument hides its control, and leaves the argument unset, while its arg or global condition is false.
The explorer lists stories whose [tags](https://storybook.js.org/docs/writing-stories/tags) include `dev`, which every story has by default. Add `tags: ["!dev"]` to a story or its metadata to leave it out of the navigator; `composeStories` still returns it.
The navigator shows one group per story `title`. Titles that share a path, such as `Recipes/Card` and `Recipes/Grid`, stay next to each other, and the first story file under each path decides where the path appears, as in Storybook's sidebar.
## Reuse stories in native tests
With the [GTKX Vitest setup](/v2/guide/testing), import and compose the same module:
```tsx
import * as Gtk from "@gtkx/gi/gtk";
import { composeStories } from "@gtkx/storybook";
import { render, screen, userEvent } from "@gtkx/testing";
import { expect, it } from "vitest";
import * as stories from "./button.stories.js";
const { Default } = composeStories(stories);
it("invokes the button callback", async () => {
let clicks = 0;
await render( { clicks += 1; }} />);
await userEvent.click(
screen.getByRole(Gtk.AccessibleRole.BUTTON, { name: "Save" }),
);
expect(clicks).toBe(1);
});
```
Pass shared preview configuration as the second argument to `composeStories`. Render a window story as any component that creates its own window, with `{ container: rootElement }` from `@gtkx/react`; a story whose window is an `AdwApplicationWindow` also needs an `` around it, as in the [Testing guide](/v2/guide/testing#rendering-a-component).
## Lifecycle and compatibility
Control edits rerender the current story and retry previews that failed to render. Reset restores default arguments and remounts it. Switching stories unmounts the previous preview, including its windows and dialogs.
Content stories render inside the explorer window and receive its application and parent-window contexts. They get a margin; set Storybook's [`layout`](https://storybook.js.org/docs/configure/story-layout) parameter to `"centered"` or `"fullscreen"` to center the story or drop the margin. A story owning a separate window sets `parameters: { gtkx: { preview: "window" } }`.
A content story whose component has its own header bar, such as a page split out of a window, shows the explorer's window controls in it, and they act on the explorer window: its close button closes the explorer. Pass `showStartTitleButtons` and `showEndTitleButtons` through to the header bar and set them to `false` in the story's `args`, or render the whole window in a `preview: "window"` story. Give a window story a component that does not call `quit()`, such as a window without the scaffold's `onCloseRequest={quit}`. `quit()` unmounts every root in the process and quits their applications, so it stops the explorer instead of closing the story.
GTKX reuses Storybook 10's composition APIs. This is a standalone native explorer. Browser addons, a browser manager, MDX, Autodocs, `play`, loaders, Storybook preview hooks, and static interactive publishing are unsupported. The explorer skips `.mdx` files matched by `stories` patterns and prints a warning naming them, so a configuration copied from Storybook works unchanged. Configured globals are available in context; there is no global toolbar.
The [example project](https://github.com/gtkx-org/gtkx/tree/main/examples/storybook) demonstrates controls, dialog and window stories, and native integration tests.
---
---
title: "Workspaces"
description: "Run GTKX apps in pnpm, npm and Yarn workspaces, and build, test and publish component libraries."
---
# Workspaces
A workspace holds several GTKX apps and the packages of components they share. This page covers how they share generated bindings and sources, and how to package components as a library that apps install. Each app's own settings are described in [Configuration and Codegen](/v2/guide/configuration-and-codegen).
## Monorepos
GTKX apps and shared packages of components work in pnpm and npm workspaces with the package manager's default `node_modules` layout, and in Yarn workspaces whose root `.yarnrc.yml` sets `nodeLinker: node-modules`. Scaffolding into a directory the workspace lists, as in `pnpm create gtkx@beta apps/my-app`, adds the app to the workspace and prints the settings the root needs; see [Scaffold Options](/v2/guide/scaffold-options#workspaces).
### Shared bindings
Codegen writes the bindings into the `node_modules` directory the GTKX packages are installed in. In a workspace this is usually the root: pnpm keeps every package under the root `node_modules/.pnpm`, and npm and Yarn hoist them there. The bindings link `@gtkx/runtime`, `@gtkx/cairo`, `@gtkx/react`, `react` and `@types/react` from the app, so they use the same copies the app does.
Apps that resolve the same directory share one set of bindings, generated for the union of their `libraries`. Codegen stops with an error naming the other app when apps sharing bindings differ in anything else:
- `girPath` or `elements`
- whether they use `@gtkx/react`
- a version of a GIR namespace, such as `Soup-2.4` and `Soup-3.0`
- the copies of `@gtkx/runtime`, `@gtkx/cairo`, `@gtkx/react`, `react` or `@types/react` they resolve
Keep these aligned across the workspace, for example with a [pnpm catalog](https://pnpm.io/catalogs). After changing `girPath` or `elements` in every app, run [`gtkx codegen --force`](/v2/guide/cli#gtkx-codegen) in one of them; the others share its bindings again the next time they generate theirs.
### Namespaces per app
Each app still imports only the libraries it declares and their dependencies, which are also what `gtkx deploy` requires of the installed system. Codegen gives an app that shares bindings its own `@gtkx/gi` and `@gtkx/jsx` packages, which expose those namespaces and link them to the shared bindings. They live in the app's `node_modules/.gtkx`, as a single project's bindings do, so the scaffold's `tsconfig.json` paths and editors keep finding them after any package install. An app at the workspace root, where the bindings are written, sees every namespace.
Importing a namespace that only another app declared fails:
- in `gtkx dev`, `gtkx build` and Vitest, with an error naming the library to add to `libraries`
- in Node, which reports the subpath as not exported
- in `tsc`, which reports the namespace as having no exports
### Shared packages
A shared package declares `@gtkx/react` as a peer dependency and imports `@gtkx/gi` and `@gtkx/jsx` subpaths like an app. List it in the dependencies of each app that uses it, so `gtkx dev` loads it through Vite. A shared package resolves the bindings from the workspace root, so it can import any library some app declares; each app that uses it has to declare the libraries the package imports.
An app's [Storybook](/v2/guide/storybook#stories-from-a-shared-package) configuration can list a shared package's stories with a pattern such as `../../packages/ui/src/**/*.stories.tsx`. A shared package can also run its own tests and Storybook explorer without an `applicationId`, as a [component library](#component-libraries) does.
### Workspace sources
GTKX treats the sources of the workspace packages an app uses as part of the app. These are the packages that depend on `@gtkx/react` or `@gtkx/i18n` and that the app's dependencies, directly or through other such packages, link from outside `node_modules`: workspace packages and `link:` or `file:` directories. Codegen, `gtkx dev`, `gtkx build` and `gtkx deploy` read their `src` directories as they read the app's:
- Their [messages](/v2/guide/internationalization) go into the app's gettext template, `po/POTFILES.in` and translation types, at locations relative to the app such as `../../packages/ui/src/rating.tsx:18`, so the app's catalogs translate them. Their stories stay out of the catalogs.
- Their `?icon=` and `?resource=` [imports](/v2/guide/assets) are declared in the app's `node_modules/.gtkx/env.d.ts`, and their GSettings schemas get [types beside each schema](/v2/guide/native-state#your-app-s-schema), so the app's `tsc` accepts them. The app bundles and installs those schemas, and `gtkx deploy` requires a schema's file name to start with the app's ID, as for the app's own. Copies of a schema file in several packages, or reached through symlinks, are installed once; files with the same name and different contents stop with an error naming both.
- Saving one of their files in `gtkx dev` updates the app's template and declarations, as saving one of the app's does.
Packages installed from a registry stay outside: their messages are not extracted, so a published [component library](#component-libraries) takes translated text from the app, for example as props.
## Component libraries
A component library is a package of GTKX components that apps install, from their workspace or from a registry. It is not an application, so it has no `applicationId`. It needs a `gtkx.config.ts` only to list the GIR libraries its components import beyond Adwaita and GTK:
```ts [gtkx.config.ts]
import { defineConfig } from "@gtkx/config";
export default defineConfig({
libraries: ["GtkSource-5"],
});
```
`gtkx codegen`, `gtkx storybook` and the Vitest plugin work in such a package, with or without the file, while `gtkx dev`, `gtkx build` and `gtkx deploy` stop because they need an `applicationId`. Codegen writes no `AGENTS.md`, `CLAUDE.md` or `.gtkx/reference` there unless `agents.rules` or `agents.reference` is `true`.
Its `package.json` lists `@gtkx/react` and `react` as peer dependencies, with any other GTKX package its components import at runtime, such as `@gtkx/css` or `@gtkx/cairo`, so that it uses the app's copies. It does not depend on `@gtkx/gi` or `@gtkx/jsx`: each app generates those for the libraries it declares, so an app that uses the package lists in `libraries` every GIR library the package imports beyond Adwaita and GTK.
For building and testing, add the peer packages, `@gtkx/cairo`, `@gtkx/cli`, `@gtkx/config`, `@gtkx/runtime`, `@gtkx/testing`, `@types/node`, `@types/react`, `typescript` and `vitest` as development dependencies. The generated bindings import the package's own `@gtkx/runtime` and `@gtkx/cairo`, so where the package manager does not hoist them, as pnpm does not, `gtkx codegen` stops with "Cannot resolve @gtkx/runtime" without the first and the tests fail with "Cannot find package '@gtkx/cairo'" without the second.
```json [package.json]
{
"name": "@example/ui",
"version": "0.1.0",
"type": "module",
"exports": {
".": {
"types": "./dist/index.d.ts",
"default": "./dist/index.js"
}
},
"files": ["dist"],
"scripts": {
"build": "gtkx codegen && tsc -p tsconfig.build.json",
"typecheck": "gtkx codegen && tsc",
"test": "vitest run"
}
}
```
Build it with `tsc` into JavaScript and declarations. Start from a scaffolded app's `tsconfig.json`, which resolves `@gtkx/gi` and `@gtkx/jsx` to the generated bindings, and copy its `src/gtkx-env.d.ts`, which types `import.meta.env` and asset imports such as `?icon`. Then add a build configuration that emits only the sources:
```json [tsconfig.build.json]
{
"extends": "./tsconfig.json",
"compilerOptions": {
"noEmit": false,
"declaration": true,
"outDir": "dist",
"rootDir": "src"
},
"include": ["src/**/*"],
"exclude": ["src/**/*.stories.tsx"]
}
```
The output keeps its `@gtkx/gi` and `@gtkx/jsx` imports, in the JavaScript and in the declarations, so the app's own bindings resolve them when it builds and typechecks. `gtkx dev`, `gtkx build` and the Vitest plugin load an installed package that depends on `@gtkx/react` through Vite, so the app needs no extra configuration, and `gtkx build` bundles the package and lists it in `BUNDLED-NOTICES`. Publish the package with your package manager after building it, for example `npm publish`.
Test the components with `@gtkx/testing` and the Vitest plugin, as in an app:
```ts [vitest.config.ts]
import gtkx from "@gtkx/cli/vitest-plugin";
import { defineConfig } from "vitest/config";
export default defineConfig({
plugins: [gtkx()],
});
```
The tests run as the application `org.gtkx.Test`. To browse the components in the [Storybook explorer](/v2/guide/storybook), also add `@gtkx/storybook` as a development dependency and run `gtkx storybook`; the explorer registers as `org.gtkx.Library.Storybook`. In a workspace the package shares the bindings of the apps around it, under the rules described in [Monorepos](#monorepos).
---
---
title: "App Inspection (MCP)"
description: "Inspect a running GTKX app and look up its generated bindings from your coding agent."
---
# App Inspection (MCP)
`@gtkx/mcp` is a [Model Context Protocol](https://modelcontextprotocol.io/docs/learn/server-concepts) server that connects a coding agent to your running GTKX app. The agent can inspect widgets, interact with the window, take screenshots, and look up the exact bindings generated for your project.
## Setup
Install the server and the testing package its widget tools use. Scaffolded projects include both.
::: code-group
```bash [npm]
npm install -D @gtkx/mcp@beta @gtkx/testing@beta
```
```bash [pnpm]
pnpm add -D @gtkx/mcp@beta @gtkx/testing@beta
```
```bash [yarn]
yarn add -D @gtkx/mcp@beta @gtkx/testing@beta
```
:::
From the project root, register the server with your client. A scaffolded project already has the Claude configuration.
```bash
npx gtkx mcp init --client claude
```
[`--client`](/v2/guide/cli#gtkx-mcp-init) accepts `claude`, `cursor`, `vscode`, `opencode`, and `codex`. The command adds a `gtkx` entry to the client's project configuration file, replacing an older one and keeping the file's other entries and indentation. When it cannot edit the file safely, such as a JSON file with comments or a Codex file that already declares `gtkx` as an inline table, it leaves the file unchanged and prints the entry to add. For Codex it writes a `[mcp_servers.gtkx]` table to `.codex/config.toml`, which Codex reads only in a [trusted project](https://developers.openai.com/codex/mcp).
### Other clients
Configure a stdio server that runs `npx --no gtkx mcp`. Clients start servers without a terminal, where plain `npx` would install and run an unrelated `gtkx` package from the npm registry when `@gtkx/cli` is missing; `--no` makes it fail instead. The standalone `gtkx-mcp` command is also available when `@gtkx/mcp` is installed directly.
Start the server in the app's directory. It reads the configuration and generated bindings of the directory it starts in, and pnpm installs the CLI only in the app, not at a workspace root. The first app scaffolded into a workspace adds an entry to the root's `.mcp.json` that does this through the package manager, such as `pnpm --dir apps/my-app exec gtkx mcp`; see [Scaffold Options](/v2/guide/scaffold-options#workspaces).
### Start the app
```bash
npx gtkx dev
```
The app connects automatically, and either side can start first. The connection exists only during development; production builds exclude it. For a session without a display, run [`npx gtkx dev --headless`](/v2/guide/cli#gtkx-dev) and stop it with Ctrl+C. See [headless development](/v2/guide/testing#headless-development) for display options.
## Inspect and verify changes
Ask the agent to inspect the running app before changing it, then verify the result after Fast Refresh updates the window. A useful sequence is:
1. Find a widget by its role, accessible name, or text with `gtkx_query_widgets`.
2. Read its properties or subtree when more context is needed.
3. Click, type, or press keys through the interaction tools.
4. Take a screenshot to check the rendered result.
A screenshot shows the window at the moment it is taken, so one taken straight after a click can catch a transition half done, such as a stack crossfading between pages. Take another once the animation has finished.
### Tools
| Tool | Read-only | Use |
| ----------------------- | --------- | ---------------------------------------------------------------------- |
| `gtkx_list_apps` | Yes | List the connected apps and their windows |
| `gtkx_query_widgets` | Yes | Find widgets by role, text, accessible name or label |
| `gtkx_get_widget_tree` | Yes | Read the widget tree, or one subtree, to a chosen depth |
| `gtkx_get_widget_props` | Yes | Read a widget's state and the GObject properties you ask for |
| `gtkx_take_screenshot` | Yes | Capture a window as an image, a saved PNG, or both |
| `gtkx_click` | No | Click a widget |
| `gtkx_type` | No | Type text into an editable widget |
| `gtkx_press_keys` | No | Press keys and shortcuts, such as `{Enter}` or `{Control>}s{/Control}` |
| `gtkx_pointer` | No | Press, hold or release a mouse button on a widget |
| `gtkx_fire_event` | No | Emit a GObject signal on a widget |
| `gtkx_list_api` | Yes | List the namespaces and symbols of the generated bindings |
| `gtkx_search_api` | Yes | Search the generated bindings by name |
| `gtkx_get_api_docs` | Yes | Read the reference for one symbol or member |
Your client shows the agent each tool's parameters and description. Widget summaries report the GTK type as `type` and the accessible name as `name`, so an icon-only button reads as its tooltip. For a large window, request a subtree or limit the depth rather than reading the whole tree again. Widget IDs last only while their widgets are mounted, so query again after the UI they belong to is replaced.
### Simulated input
The interaction tools use the same queries and `userEvent` helpers as [`@gtkx/testing`](/v2/guide/testing#interacting-and-waiting), not a real keyboard or mouse. In practice:
- `gtkx_type` replaces selected text, as typing does. GTK selects an entry's text when focus moves into it, as when a dialog opens, so the agent passes `clear: true` with the full text to set a value.
- `gtkx_press_keys` focuses the widget first when it can take focus. A widget that cannot, such as the switch inside an `AdwSwitchRow`, leaves the focus where it is, and the result names the ancestor to press the keys on instead.
- A modifier pressed without release, such as `{Control>}`, stays held for later calls until `{/Control}`, which is how an agent Control-clicks several rows. `gtkx_type` refuses while one is held.
- `gtkx_pointer` takes one token, such as `[MouseRight]` for a right click that opens a context menu, `[MouseRight>]` to hold the button and `[/MouseRight]` to release it.
- `gtkx_click` and `gtkx_press_keys` say in their result when nothing on the widget or its ancestors handled the input. Some GTK widgets, such as the swatches of a color dialog, react only to a real pointer event, so the result suggests pressing `{Space}` or `{Enter}` on them instead. In tests, `userEvent` stays silent about unhandled input, as Testing Library does.
### Errors
An error the app raises while handling an interaction, such as a render error or an exception from a signal handler, comes back in the tool result. `gtkx dev` also handles it as it does any uncaught error: it ends the app and starts it again after a saved fix, as [Error Handling](/v2/guide/error-handling#uncaught-exceptions) describes. An error from using a tool on the wrong widget, such as typing into a button or clicking one behind an open dialog, comes back only in the tool result, which names what blocks it or the widget to target instead.
### Several apps
All GTKX MCP servers of a session listen on one socket, so run one server: it lists and drives every running GTKX app, and a second server started next to it exits with an error. Without `applicationId`, tools use the app from the server's project, or the first connected app when none comes from it. Use `gtkx_list_apps` to find the others and pass `applicationId` to target one.
The [Storybook explorer](/v2/guide/storybook) registers under the project's application ID with a `.Storybook` suffix, so `gtkx dev` and `gtkx storybook` can run together. Tools without `applicationId` use the `gtkx dev` app. While it restarts, they wait for it, up to `appTimeout` (10 seconds by default), before falling back to the explorer.
## Look up generated bindings
The reference tools document the project's `@gtkx/gi/*` and `@gtkx/jsx/*` modules. They use the same GIR files as code generation and work without a running app.
Use `gtkx_search_api` to find a symbol or member, then `gtkx_get_api_docs` to read it. Search matches the names of symbols and of their members, so `replaceContentsAsync` finds `Gio.File.replaceContentsAsync`. Results are ranked with exact names first and limited to 20 unless you pass `limit`. Include the owner to list its members, such as `Gio.File.replace`, or a JSX element's props, such as `GtkButton.icon`.
`gtkx_get_api_docs` accepts qualified names such as `Adw.Toast`, JSX names such as `AdwToast`, and member names such as `Gio.File.replaceContentsAsync` or `GtkWindow.close-request`. A member name returns only that member's section, which is much shorter than a class page, and an inherited member such as `Gtk.Button.setVisible` resolves to the ancestor that documents it. Pass `kind` when a signal and a method share a name. [`gtkx docs`](/v2/guide/configuration-and-codegen#generating-element-reference-docs) writes static reference pages from the same bindings.
The server documents the project containing its working directory, falling back to a connected app's project. Pass `projectRoot` to select another project. Clients that browse MCP resources can read the reference there too. A project with `codegen: false` has no generated bindings to document.
## Point the agent to the guide
The server documents the generated bindings, not how to build a GTKX app. For that, give the agent this version's guide and tutorial as Markdown: [https://gtkx.dev/v2/llms.txt](https://gtkx.dev/v2/llms.txt) lists every page, and [https://gtkx.dev/v2/llms-full.txt](https://gtkx.dev/v2/llms-full.txt) holds all of their text in one large file. Each page also has a Markdown copy at its own URL with `.md` added, such as [https://gtkx.dev/v2/guide/mcp.md](https://gtkx.dev/v2/guide/mcp.md). See [Machine-readable documentation](/versions#machine-readable-documentation) for the other versions.
## Choose the available tools
Set `mcp.readOnly` to expose only the read-only tools, leaving out app interactions. Use `mcp.tools` to select tools by name:
```ts
import { defineConfig } from "@gtkx/config";
export default defineConfig({
applicationId: "com.example.app",
mcp: {
tools: ["gtkx_*", "!gtkx_take_screenshot"],
readOnly: true,
},
});
```
`*` matches any text, and a leading `!` removes matches. A list containing only exclusions starts with all tools. Otherwise, patterns add and remove tools in order, starting with none.
[Command-line options](/v2/guide/cli#gtkx-mcp) override the project settings for one client:
```bash
npx --no gtkx mcp --read-only --tools "gtkx_*_api,gtkx_get_widget_tree"
```
---
---
title: "Troubleshooting"
description: "Fix common problems creating, generating, running, refreshing, and updating a GTKX app."
---
# Troubleshooting
Each heading names a symptom. For errors your app reports at runtime, see [Error Handling](/v2/guide/error-handling).
## The create command runs an older scaffolder {#the-create-command-finds-no-version}
On the day of a GTKX release, a package manager's release-age gate holds back the new `create-gtkx`, and the create command quietly runs an older one. pnpm 11 and newer gate by default and run the previous release. npm gates only when `min-release-age` is set, and then runs the newest stable release: during the 2.0 beta, that is the 1.x scaffolder, which creates a GTKX 1.x project. Yarn 4.15 and newer gate by default and stop instead, reporting that every version of a `@gtkx` dependency is quarantined. The scaffolder exempts GTKX's own packages in the project it creates (see [Scaffold Options](/v2/guide/scaffold-options#release-age-gates)), but the gate still applies to downloading the scaffolder.
Exempt GTKX for that one command. npm ignores `min-release-age-exclude` when it downloads the scaffolder, so lift its gate for the download with `--min-release-age=0`; the scaffolder's own install still applies the gate:
```bash
pnpm_config_minimum_release_age_exclude='["@gtkx/*","create-gtkx"]' \
pnpm create gtkx@beta
npm create --min-release-age=0 gtkx@beta
YARN_NPM_PREAPPROVED_PACKAGES='@gtkx/*,create-gtkx' \
yarn create gtkx@beta
```
## Dependency installation fails while scaffolding
The generated files remain in the project directory, but the scaffolder stops before initializing Git. Resolve the package manager's error, rerun its install command there, and run `git init` if you want the project under version control.
When the app was added to an existing [workspace](/v2/guide/scaffold-options#workspaces), the command first prints the root settings the app needs. Add them to the workspace root before installing again.
## Missing GIR file
Codegen reports `GIR file Adw-1.gir not found on girPath`, or that no GIR search paths are available. Install the library's development package, which supplies its GIR file, then run `npx gtkx codegen` from the project. For libraries outside the standard directories, set [`girPath`](/v2/guide/configuration-and-codegen#the-config-file).
## Native versions are too old
A call fails with `Failed to find symbol '…'`, or the generated bindings lack a widget, property or method that the docs use. Compare `pkg-config --modversion gtk4 libadwaita-1` with the [minimum versions](/v2/guide/getting-started#what-you-need), and use a distribution or development container that meets them. Installing newer npm packages does not upgrade GTK or libadwaita.
## No display connection
GTK prints `Failed to open display` and the app exits. Run the app from a terminal in a graphical desktop session. In a development container, give the container access to the session's display and D-Bus; installing the libraries alone does not provide that connection. Tests run without a desktop and have a separate [headless setup](/v2/guide/testing#setup).
## The app restarts instead of refreshing
`gtkx dev` applies most edits to the open window with Fast Refresh and keeps its state:
- Editing a module that exports only components refreshes it in place.
- Editing any other module, such as a custom hook or shared styles, refreshes the component modules that import it, directly or through other modules.
- A component whose hook calls change remounts, which resets its state and the state of the components inside it.
- Editing an imported stylesheet replaces its rules. Editing a module's `injectGlobal` rules adds the edited rules, while the earlier ones stay until the app restarts.
These changes restart the app and reset its state. The terminal usually names the cause first, such as `Module imports changed: `.
- an edit that reaches the entry module before a component module
- importing or re-exporting a module that the edited module did not import before, or no longer importing one; adding a name to an existing import, or editing type-only imports, refreshes instead
- an edit to an imported resource, icon or settings schema, a new `?font` import, or an edit to a file a [worker](/v2/guide/workers) loaded
- removing a module or stylesheet the app loaded
- an edit that changes a construct-only prop, such as the `strings` of a `GtkStringList`
- an edit to `gtkx.config.ts` or a file it loads, an [environment file](/v2/guide/configuration-and-codegen#environment-files), or a GIR file the bindings were generated from
- a saved PO file or `LINGUAS` ([Internationalization](/v2/guide/internationalization#develop-and-build))
- a lockfile change from installing or updating dependencies
- any other change that Fast Refresh cannot patch
## A new GTKX release does not install
A project created by `create-gtkx` 2.0.0-beta.12 or earlier has no release-age exemption for GTKX, so on the day of a release its package manager's gate holds back the new packages. [`gtkx upgrade`](/v2/guide/updating) adds the exemption before installing. To install on a release day without upgrading, add the [entries](/v2/guide/scaffold-options#release-age-gates) yourself, or install again a day later.
---
---
description: "Package a GTKX application as a Flatpak, Debian package, RPM, or AppImage."
---
# Deploying
`gtkx deploy` builds your application and packages it for Linux. GTKX generates the launcher, desktop entry,
AppStream metadata, and package manifests from `gtkx.config.ts`. Start with one package for your own
distribution, then add other targets or a [source Flatpak build](#publishing-on-flathub).
## Configure your application
GTKX reads the application's name, summary, version, developer, license, and homepage from the `name`,
`description`, `version`, `author`, `license`, and `homepage` fields of `package.json`, unless `deploy` sets them:
```ts
import { defineConfig } from "@gtkx/config";
export default defineConfig({
applicationId: "com.example.Tasks",
applicationIcon: "data/icons",
deploy: {
summary: "Manage your tasks and to-dos",
categories: ["Office"],
minimumLibraryVersions: { "Gtk-4.0": "4.20", "Adw-1": "1.8" },
},
});
```
Without a `deploy` block, the command stops and suggests a starter configuration. `defineConfig` provides
completion for packaging settings; the [configuration API reference](/v2/reference/@gtkx/config/) describes
its exported types.
### Application icons
The example expects an icon such as `data/icons/hicolor/scalable/apps/com.example.Tasks.svg`. A theme
directory must contain an application icon named after `applicationId` under `hicolor//apps`.
GTKX preserves the directory's other sizes and variants.
You can also point `applicationIcon` at a single SVG, PNG, or XPM file. When the option is omitted, GTKX looks
for exactly one `.svg`, `.png`, or `.xpm` in the project root. Deployment requires an icon.
Theme directories are copied in full. Keep icons imported with [`?icon`](/v2/guide/assets#icons) elsewhere,
since the app bundles them itself. Keep development icons in a separate directory and select it with a
[`$development` override](/v2/guide/configuration-and-codegen#every-option).
## Choose a target
| Target | Package | Use |
| ---------- | -------------------------------------- | -------------------------------------------- |
| `flatpak` | `.flatpak` bundle and local repository | A sandboxed application with a GNOME runtime |
| `deb` | `.deb` | Debian, Ubuntu, and derivatives |
| `rpm` | `.rpm` | Fedora and other RPM distributions |
| `appimage` | `.AppImage` | A downloadable executable file |
Flatpak is the default. Set `deploy.targets` for the project's usual formats, or override them for one run with [`--target`](/v2/guide/cli#gtkx-deploy):
```bash
gtkx deploy --target deb,rpm
```
Packages are written to `build/out`. Manifests and staged files are under `build//`. `deploy.outDir: "packages"`
or [`gtkx deploy --out packages`](/v2/guide/cli#gtkx-deploy) changes this deployment directory to `packages`, with finished artifacts in `packages/out`.
### Build tools
Every deployment needs `desktop-file-validate` and `appstreamcli`. Downloaded archives need `tar`;
applications with translation catalogs also need GNU gettext. See [Internationalization](/v2/guide/internationalization)
for the catalog workflow.
Flatpak needs `flatpak` and either `flatpak-builder` or the `org.flatpak.Builder` Flatpak. AppImage needs
`file`. GTKX downloads and verifies `nfpm` for Debian/RPM packaging and `appimagetool` for AppImage packaging.
The command reports missing tools with installation hints.
Flatpak builds install the GNOME runtime and SDK from a remote named `flathub` in your user installation; a
system-wide `flathub` remote is not used. Add it once:
```bash
flatpak remote-add --user --if-not-exists flathub \
https://dl.flathub.org/repo/flathub.flatpakrepo
```
To use a local nFPM installation, set `deploy.tools.nfpm` to an executable name such as `"nfpm"` or a path such as `"./tools/nfpm"`. Relative paths start at the project root. This skips the pinned nFPM download for Debian and RPM packages.
## Preview and build
From a scaffolded project on Fedora, preview an RPM:
```bash
npm run deploy -- --target rpm --print-manifests
```
With pnpm, run `pnpm run deploy --target rpm --print-manifests`; `pnpm deploy` is pnpm's built-in command and does not run the script.
Use `--target deb` on Debian or Ubuntu. The preview builds and stages the application, writes the generated
metadata to `build//metadata/` and the package manifests to `build//targets/`, and stops before
creating packages. It skips Node.js and packaging-tool downloads; cross-architecture addon downloads and source
Flatpak dependency preparation may still need network access.
GTKX validates the desktop entry and AppStream metadata. AppStream errors and unsupported tags fail every
target. Other AppStream warnings are fatal when source-mode Flatpak is selected, including previews.
Prebuilt Flatpak, Debian, RPM, and AppImage deployments report them and continue.
Remove [`--print-manifests`](/v2/guide/cli#gtkx-deploy) to build the package:
```bash
npm run deploy -- --target rpm
```
The finished package is under `build/out`. Install it on a compatible system and open the application from
the desktop launcher to check the packaged build. Even `--help` needs a display, so run command-line smoke tests
in a desktop session or a virtual display; see [Command-line apps](/v2/guide/application-lifecycle#command-line-apps).
Each deployment replaces its managed output directory. Choose an empty directory or an earlier GTKX deploy
directory below the project root, outside `dist/`; symlinked output paths and unrelated files are rejected.
### Production build output
`gtkx build` writes the production build to `dist/`. To package an existing build:
```bash
gtkx build
gtkx deploy --skip-build
```
[`--skip-build`](/v2/guide/cli#gtkx-deploy) always reads `dist/`; the deployment's `--out` option selects the package
directory, not the build directory. Keep `dist/gtkx-schemas.json` beside the bundle: it records the build's entry,
configuration, imported schemas, and dependency notices. Deployment rejects a build of another entry, such as a
helper built without `--out`, a different production configuration, or an older metadata format; rebuild to update
it. Changes to the `deploy` block alone do not need a rebuild.
Use [`gtkx build --out`](/v2/guide/cli#gtkx-build) for another independently runnable build, such as a
[helper command](#helper-commands):
```bash
gtkx build src/helper.ts --out dist-helper
```
Choose a directory below the project root that is empty or contains an earlier GTKX build, and add it to
`.gitignore`, which scaffolded projects set up only for `dist/` and `build/`. GTKX rejects unrelated files,
symlinked paths, output nested inside another build, and output inside the deploy output directory (`build/` unless
`deploy.outDir` says otherwise), which every deployment replaces. Generated bundles contain their JavaScript
dependencies; unresolved package imports fail the build.
### Architectures
Deployment uses the host architecture unless `deploy.architectures` or [`--arch`](/v2/guide/cli#gtkx-deploy) selects `x64`, `arm64`, or both:
```bash
gtkx deploy --target deb,rpm --arch x64,arm64
```
Only Debian and RPM packages support cross-building. Flatpak and AppImage must be built on their target
architecture. Cross-building also requires the default `deploy.node.source: "download"`; GTKX obtains the
matching Node.js runtime and native addon.
## Runtime and library requirements
For prebuilt deployments, GTKX bundles Node.js with the application. The default download is pinned to
26.8.2, verified, and cached. Use `deploy.node.version` to choose another supported version. The `host` and `path` sources use an existing
runtime; GTKX checks its version and portability. See [DeployNodeOptions](/v2/reference/@gtkx/config/index/type-aliases/DeployNodeOptions).
GTK, libadwaita, and other native libraries come from the host system or the Flatpak runtime. Generated GTKX
bindings call those libraries directly; the installed app does not need GIR files. An AppImage still needs
compatible native libraries on the host.
Debian and RPM dependencies include GTK, libadwaita, and runtime requirements detected from staged binaries.
RPM packages also require the shared library of every other library in `libraries`, such as
`libgtksourceview-5.so.0()(64bit)` for `GtkSource-5`, which RPM resolves to the right package on any distribution.
Debian has no such relation: list the packages that ship those libraries in `deploy.depends.deb`, for example
`["libgtksourceview-5-0"]`, or the package installs on a system without them and the app fails to start. While
`deploy.depends.deb` is empty, a deb deployment warns and names the shared libraries it must cover. Declare other
system packages through `deploy.depends` as well.
The opening example sets the GTKX baseline in `deploy.minimumLibraryVersions`. GTKX writes these minimums into
Debian and RPM package dependencies but does not infer them from your code, so raise them when your app uses newer
APIs, for example `{ "Gtk-4.0": "4.22", "Adw-1": "1.8" }`. Publish the same requirements alongside an AppImage, and
check prebuilt Flatpaks against the selected GNOME runtime.
### Settings schemas
Debian, RPM, and Flatpak packages install the application's GSettings schemas into `share/glib-2.0/schemas`
under their prefix, where the system compiles them: the distribution's GLib package on installation, or
`glib-compile-schemas` in the Flatpak build. Vendor `.gschema.override` files placed there by a distribution or
administrator change the application's defaults, as they do for other GNOME applications. Every schema shares that
directory, so each schema file name must start with the application ID.
The AppImage and `node dist/bundle.mjs` read the `gschemas.compiled` that `gtkx build` writes beside the bundle,
so vendor overrides do not apply to them.
### Additional native addons
Import a prebuilt `.node` file with `?url` so GTKX includes it in the package:
```ts
import { createRequire } from "node:module";
import addonPath from "../vendor/addon.node?url";
const require = createRequire(import.meta.url);
const addon = require(addonPath) as { open(path: string): unknown };
```
Choose a prebuild matching the deployment architecture and Node.js ABI. Import the `.node` file itself, not
the package that loads it: `gtkx build` cannot bundle a package whose entry point requires its `.node` file
and stops with an error naming that package, and a loader that searches its original `node_modules` directory will not find that directory after bundling.
GTKX's own addon uses the emitted asset path in the same way. For prebuilds published as one package per
platform, such as `@node-rs/xxhash-linux-x64-gnu`, add that package as a dependency and import its `.node` file.
Every package of one deployment contains the same build. When `deploy.architectures` or `--arch` selects more
than one architecture, import a prebuild for each and load the one matching `process.arch`; GTKX does not check
the architecture of imported addons.
```ts
import { createRequire } from "node:module";
import arm64Addon from
"@node-rs/xxhash-linux-arm64-gnu/xxhash.linux-arm64-gnu.node?url";
import x64Addon from
"@node-rs/xxhash-linux-x64-gnu/xxhash.linux-x64-gnu.node?url";
const require = createRequire(import.meta.url);
const addonPath = process.arch === "arm64" ? arm64Addon : x64Addon;
const addon = require(addonPath) as { xxh64(input: string): bigint };
```
Package managers treat a prebuild package for another CPU differently. pnpm installs it. Yarn skips it unless
`supportedArchitectures` in `.yarnrc.yml` lists that CPU. npm rejects it with `EBADPLATFORM`, also when a
[source Flatpak](#publishing-on-flathub) runs `npm ci` on another architecture, so npm projects copy each
prebuild into the project and import it by path, as in the first example.
## Third-party notices
Packages contain the application bundle, Node.js, GTKX's native addon, and the imported resources, schemas,
fonts, and translations. GTKX also installs desktop integration files and license notices; applications do
not need an installed `node_modules` tree.
The notices cover bundled Node.js, GTKX, and bundled JavaScript dependencies, and identify the platform
libraries used by the application. `gtkx build` records dependency names, versions, source links, and license
terms, so replacing or removing an installed dependency does not change the notices for an existing bundle.
Dependencies with neither a license declaration nor license text remain listed with a warning.
Debian packages install the notices at `/usr/share/doc//copyright`. Other targets use
`share/licenses//THIRD-PARTY-NOTICES` under their installation prefix: `/app` for Flatpak,
`/usr` for RPM, and the AppImage's embedded `usr` directory.
## Customize a package
Keep packaging adjustments in `deploy`. For example, `flatpak.finishArgs` configures sandbox permissions,
`extraFiles` includes additional files, and `metainfoExtra` adds uncommon AppStream metadata before validation.
Signing and format-specific settings also live here; use `defineConfig` completion to explore them.
Flatpak defaults permit display access and hardware rendering. Add network or filesystem access only when
your application needs it; use the [Flatpak permission documentation](https://docs.flatpak.org/en/latest/sandbox-permissions.html)
to choose the arguments for `deploy.flatpak.finishArgs`.
Extra files must exist before deployment starts. Their destinations are relative to the installation prefix;
see [DeployExtraFileOptions](/v2/reference/@gtkx/config/index/type-aliases/DeployExtraFileOptions) for explicit
file modes. A directory source installs every file below it, so a directory of man pages or a whole build output
takes one entry. Generated desktop, AppStream, and MIME metadata take precedence over extra files targeting the
same destination.
### Screenshots and releases
Software centers show the screenshots and release history from the AppStream metadata. Each
`deploy.screenshots` entry takes an absolute `url` or a `file` relative to the project root. Software centers
download screenshots over the network, so GTKX turns each `file` into a URL under `deploy.screenshotBaseUrl`.
Without that option, GTKX uses the raw file URL of the project's GitHub or GitLab `origin` remote on its default
branch, and deployment stops when there is no such remote. Push the screenshots before you publish a package.
`deploy.releases` lists the release history. It defaults to one release for the `package.json` version, dated
on the day of the build or by `SOURCE_DATE_EPOCH`.
### Desktop actions
`deploy.desktopActions` adds entries to the application's launcher menu. Choosing one runs the application with
the entry's `args`:
```ts
deploy: {
isDbusActivatable: true,
desktopActions: { today: { name: "Today", args: ["tasks://today"] } },
},
```
With `isDbusActivatable: true`, launchers ignore `args`. They start the application if needed and activate its
`app.` action, so register an application action under each ID. An action launch does not emit `activate`,
so the windows render only after the handler calls `activate()`:
```tsx
import type * as Adw from "@gtkx/gi/adw";
import { AdwApplication } from "@gtkx/jsx/adw";
import { GSimpleAction } from "@gtkx/jsx/gio";
import { useRef, useState } from "react";
import { MainWindow } from "./main-window.js";
export const App = () => {
const application = useRef(null);
const [view, setView] = useState("inbox");
const showToday = () => {
setView("today");
application.current?.activate();
};
return (
}
>
);
};
```
### Helper commands
An application can ship a command-line helper beside it, such as a `tally-report` command that prints the
application's data without opening a window. Build the helper into its own directory, as in
[Production build output](#production-build-output), before every deployment, since
`gtkx deploy` rebuilds only `dist/`:
```bash
gtkx build src/report.ts --out dist-report
gtkx deploy
```
List the whole directory in `extraFiles`, so chunk names that change between helper builds need no
configuration change, along with a launcher script and the helper's dependency notices:
```ts
deploy: {
extraFiles: {
"lib/tally-report": "dist-report",
"bin/tally-report": { source: "packaging/tally-report", mode: "0755" },
"share/licenses/tally/tally-report-NOTICES":
"dist-report/BUNDLED-NOTICES",
},
},
```
The launcher runs the helper with the bundled Node.js runtime. Every target installs it at
`lib//node` below the installation prefix, `lib/tally/node` for an application whose binary name is
`tally`, so launcher scripts can rely on that path:
```sh
#!/bin/sh
set -e
self=$(readlink -f "$0")
prefix=$(dirname "$(dirname "$self")")
exec "$prefix/lib/tally/node" "$prefix/lib/tally-report/bundle.mjs" "$@"
```
Debian, RPM, AppImage, and prebuilt Flatpak packages then contain the helper. Inside the Flatpak sandbox, run
it with `flatpak run --command=tally-report `. GTKX does not merge the helper's notices into the
application's, and a [source Flatpak](#publishing-on-flathub) builds only the application from your repository,
so building and installing the helper there is up to you.
## Source Flatpak builds {#publishing-on-flathub}
The default Flatpak mode packages the local build. Set `deploy.flatpak.mode` to `"source"` to generate a
manifest that checks out a pinned Git revision, installs dependencies offline, and runs `gtkx build` inside
the GNOME SDK:
```ts
flatpak: {
mode: "source",
source: { url: "https://github.com/you/tasks.git", tag: "v1.0.0" },
},
```
Put this inside `deploy` and use your application's public repository and release tag. Commit the sources,
lockfile, icons, license, translation catalogs, and extra files that the manifest installs. Those files must
be available inside the project checkout. Without an explicit tag or commit, GTKX pins the current checkout
commit. Source builds use Node.js from the SDK extension.
Source mode needs a standalone project, with its lockfile and `packageManager` field in the application's
directory. An app in a [workspace](/v2/guide/workspaces#monorepos) shares the lockfile and package
manager of the workspace root, so `gtkx deploy` stops with an error, including previews, when a workspace member
selects source mode. Package a workspace member as a prebuilt Flatpak, or move it into its own repository to
publish it from source.
Install [`flatpak-node-generator`](https://github.com/flatpak/flatpak-builder-tools/blob/master/node/README.md)
for dependency preparation, including previews. GTKX detects npm, pnpm, or yarn from the lockfile. A pnpm
project needs a generator with `--pnpm-store-version`. Explicit pnpm pins support major versions 10, 11
(11.3.0 or later), and 12. The `packageManager` field must include an integrity digest. For pnpm 12, which
runs as a native binary, the manifest also vendors that binary for each architecture, with checksums read from
the npm registry when the manifest is generated.
A Yarn 2 or later project, recognized by its `yarn.lock` format, installs with the release its `packageManager`
field names instead of the SDK's Yarn 1, so that field is required. The manifest vendors that release, checked
against the field's sha512 digest when it carries one, as `corepack use yarn@` writes it, or against the
checksum the npm registry publishes for `@yarnpkg/cli-dist` otherwise. The offline install follows
flatpak-node-generator's recipe for these lockfiles: its Yarn plugin turns the vendored package tarballs into
Yarn's cache before `yarn install --immutable`.
Keep the generated Flatpak manifest and `generated-sources.json` together, and regenerate them after dependency
changes. When the pinned commit is in the local checkout, `generated-sources.json` comes from the lockfile
committed there, so commit dependency changes before regenerating. Deployment stops with an error, including
previews, when that commit has no lockfile.
Source mode rebuilds the application bundle; native npm dependencies still use their packaged binaries.
Review those dependencies against [Flathub's source-build requirements](https://docs.flathub.org/docs/for-app-authors/requirements#building-from-source)
and test the final manifest before submission. A successful preview does not validate the source build or
confirm compliance with Flathub requirements. The [Flatpak tutorial](/v2/tutorial/flatpak) walks through the GTKX workflow.
## Flatpak in containers
If Flatpak stops while spawning `rofiles-fuse`, set `deploy.flatpak.shouldUseRofilesFuse: false` in `gtkx.config.ts` and retry. This applies to both prebuilt and source builds when the container cannot provide FUSE.
The failed build can leave a `rofiles-fuse` mount below `build//targets/flatpak/state/rofiles/`, so GTKX
cannot restore the output directory and reports "Device or resource busy". Unmount it with
`fusermount3 -u ` before retrying.
If a failed deployment leaves an output directory that GTKX refuses to replace, keep it for diagnosis and choose a fresh directory, for example `npm run deploy -- --target flatpak --out build-flatpak-retry`.
---
---
title: "Updating GTKX"
description: "Move a GTKX project or workspace to a newer release with gtkx upgrade."
---
# Updating GTKX
GTKX packages are released together under one version. To move a project to the newest release on the dist-tag it follows, such as `beta`, run this from the project directory:
```bash
npx gtkx upgrade
```
Pass a version or dist-tag to choose one, as in `npx gtkx upgrade 2.0.1`, and [`--cwd `](/v2/guide/cli#gtkx-upgrade) to upgrade a project outside the current directory. To move a 1.x project to 2.0, follow [Upgrading to 2.0](/v2/guide/upgrading-to-2) instead.
Read the [changelog](https://github.com/gtkx-org/gtkx/releases) before you update: it lists each release's changes, with breaking changes apart. A prerelease can remove an API that an earlier prerelease added, as [Releases](/releases#prereleases) explains, along with how to pin an exact release.
## What the command changes
The command rewrites every GTKX package version in the project, or in each package of its workspace, including pnpm catalog entries, and keeps their range operators. A `peerDependencies` range, such as a shared package's `@gtkx/react`, moves only when it does not accept the new version, so a range like `^1.6.0 || ^2.0.0` stays as written. It then installs and deduplicates with the project's package manager.
When the install leaves some GTKX packages on another version, for example through a Yarn catalog, `overrides` or `resolutions`, or a peer range it cannot rewrite still excludes the new version, the command fails and names them. Change those and install again.
`gtkx dev`, `gtkx build` and the other project commands warn when the installed GTKX packages are not all on one version.
## Release days
Before installing, the command exempts GTKX's own packages from the package manager's [release-age gate](/v2/guide/scaffold-options#release-age-gates) at the project or workspace root, so a release published that day installs. If the install still fails, it restores each `package.json`, the lockfile and those settings, so the project stays on its previous release.
## Projects on 2.0.0-beta.12 or earlier
The CLI of 2.0.0-beta.12 and earlier releases has no `upgrade` command. Run the newer one once with `npx @gtkx/cli@beta upgrade`; on a release day, [Upgrading to 2.0](/v2/guide/upgrading-to-2) shows how to run it past a release-age gate.
---
---
title: "Upgrading to 2.0"
description: "Migrate a GTKX 1.x application to GTKX 2, including configuration, imports, and native API changes."
---
# Upgrading to 2.0
GTKX 2.0 makes the behaviors previewed in 1.6 unconditional and removes their compatibility APIs. [Prepare on 1.6](/guide/upgrading-to-2#prepare-on-1-6), then move every `@gtkx/*` package to the same 2.0 version and work through this checklist. The [changelog](https://github.com/gtkx-org/gtkx/releases) lists each 2.0 prerelease's changes. Do not install `@gtkx/gi` or `@gtkx/jsx`; codegen creates them for the project. Security updates for 1.x end on 1 December 2026, as the [security policy](https://github.com/gtkx-org/gtkx/security/policy) states.
Upgrade to Node.js 26.7 or newer and set `"type": "module"` in `package.json`; GTKX packages are ESM-only and explicitly reject `require()`. Localized projects also need GNU gettext 0.23 or newer; see [Internationalization](/v2/guide/internationalization).
The 2.0 packages require React 19.3 or newer, and `@gtkx/testing` requires Vitest 5. Upgrade `react`, `@types/react`, and `vitest` first, then run the 2.0 upgrade command from the project directory:
::: code-group
```bash [npm]
npx @gtkx/cli@beta upgrade
```
```bash [pnpm]
pnpm dlx @gtkx/cli@beta upgrade
```
:::
The 1.x CLI has no `upgrade` command, so this runs the 2.0 CLI without installing it first. It moves every GTKX package in the project or its workspace to the newest 2.0 beta and installs it; [Updating GTKX](/v2/guide/updating) describes what it changes. Later releases need only `npx gtkx upgrade`.
On the day of a release, the package manager's [release-age gate](/v2/guide/scaffold-options#release-age-gates) also applies to downloading the CLI, and the command quietly runs an older one. pnpm 11 and newer gate by default and run the previous release. npm gates only when `min-release-age` is set, and then runs the newest stable release: during the 2.0 beta, that is the 1.x CLI, which has no `upgrade` command. Exempt GTKX for that one command:
::: code-group
```bash [npm]
npx --min-release-age=0 @gtkx/cli@beta upgrade
```
```bash [pnpm]
pnpm_config_minimum_release_age_exclude='["@gtkx/*","create-gtkx"]' \
pnpm dlx @gtkx/cli@beta upgrade
```
:::
Yarn's gate does not apply to `npx`.
Use ESM `import` and `export` in application code, configuration files, and their local helpers. Convert `.cjs` and `.cts` files to ESM. Configuration runs through Node's native loader, so TypeScript configuration must use erasable syntax. Storybook main configuration uses `.ts`, `.mts`, `.js`, or `.mjs`; keep JSX in previews and stories. External CommonJS dependencies remain supported through ESM imports.
Stop running apps and dev sessions before the first [`gtkx codegen --force`](/v2/guide/cli#gtkx-codegen) after upgrading. Codegen replaces older generated-store layouts with a new snapshot. GI-only generation removes obsolete JSX bindings owned by the project; installing React again regenerates them.
## Clean up the configuration
Delete the `future` block and any retired ids under `deprecations.silence`. A graduated flag left at `true` is temporarily accepted with a warning; `false` is rejected because the old behavior no longer exists.
`Adw-1` is the sole default GIR root, and its GIR include generates `Gtk-4.0` transitively. Both namespaces are always present, but neither identifier belongs in `libraries`. List only additional roots:
```ts
import { defineConfig } from "@gtkx/config";
export default defineConfig({
applicationId: "com.example.Tasks",
libraries: ["WebKit-6.0"],
});
```
The `"*"` wildcard is gone, and explicitly listing `Adw-1` or `Gtk-4.0` is rejected. Explicit additional roots keep generated bindings stable across machines.
## Check the behavior changes
Work through the changes that apply to the project, then run `tsc --noEmit`. The typechecker catches the value and tuple changes; `gtkx build` catches stale resource imports.
### Byte sequences are `Uint8Array`
GIR byte sequences are `Uint8Array`. Check code using array mutation, `Array.isArray`, or JSON serialization.
### A returned `GObject.Value` is unwrapped
A returned `GObject.Value` is unwrapped and typed `unknown`; narrow it at the call site.
### Async results drop the success boolean
Promisified methods omit a leading success boolean from multi-value finish results when failure already rejects. `loadContentsAsync` resolves to `[Uint8Array, string | null]`.
### Inout records are updated in place
Inout records and boxed values mutate the object passed in instead of repeating it in the return value.
### Assets use query imports
Assets use relative `?resource`, `?icon`, `?font`, or `?url` imports. Settings schemas use query-free relative imports, typed by files [generated beside each schema](#type-settings-schema-imports).
### Import changes restart the app
Development apps restart and reset their state when a module starts or stops importing or re-exporting a module, or when an imported resource or icon changes. Adding a name to an existing import, editing type-only imports and editing component bodies still use Fast Refresh; [The app restarts instead of refreshing](/v2/guide/troubleshooting#the-app-restarts-instead-of-refreshing) lists every cause.
### Builds keep only reached classes
Generated classes register with their own definitions, so production builds retain only reached bindings. Import a class if `GObject.typeFromName` must find it.
### An app without a window quits
An application ends when its first render shows no window and nothing holds it. An app that rendered `null` until saved data loaded, as React Navigation's state persistence example does, now quits at once and `gtkx dev` prints `Application quit`. Render the window first and show a placeholder inside it; see [When the app ends](/v2/guide/application-lifecycle#when-the-app-ends).
### Unknown construct properties throw
Constructing an object with a key that is not one of its properties throws a `TypeError`, as in GJS, instead of skipping the key: `new Gio.Notification({ title: "Done" })` fails with "No property title on GNotification". Pass such values to the type's constructor function or setters, as in `Gio.Notification.new("Done")`.
### GLib criticals are logged
GLib criticals are logged by GLib, as in C and GJS applications, instead of becoming uncaught exceptions. They no longer end the application or fail tests; see [Error Handling](/v2/guide/error-handling#glib-criticals-and-warnings).
### Unanswered closes are undone
A close the app does not answer no longer leaves React and the toolkit out of step. Adwaita dialogs without `onClosed` or `onCloseAttempt`, and JSX tab pages whose view has no `onClosePage`, stay open when the user closes them; `showSidebar`, `showContent`, `searchModeEnabled` and the `open` of bottom sheets and tab overviews are restored when the app passes them without taking the user's change. Development builds warn with the handler to add; see [Closing](/v2/guide/modals-and-portals#closing).
### Binding transforms take the GJS shape
`bindPropertyFull` and `BindingGroup.bindFull` take transforms shaped as in GJS: `(binding, value) => [success, value]` receives the value read from one property and returns the value to write to the other, and `null` selects the default conversion. Rewrite functions taking GLib's closure arguments, `(binding, fromValue, toValue) => boolean`, to return the converted value instead of filling `toValue`. A `GObject.Closure` still receives the closure arguments. See [Binding properties](/v2/guide/subclassing#binding-properties).
### `gtkx` rejects unknown options
`gtkx` commands stop with an error on an option they do not define instead of ignoring it, naming the option and listing the ones the command takes. Remove options GTKX never read from package scripts and CI, and put options meant for the application after `--`, as in `gtkx dev -- --verbose`.
### `userEvent.type` parses key names
`userEvent.type` presses keys named in braces, so `type(entry, "Ada{Enter}")` activates the entry. Text with a literal `{`, such as JSON, fails with "Unclosed key descriptor"; write it as `{{`. See [Testing](/v2/guide/testing).
## Split JSX imports by namespace
The bare `@gtkx/jsx` entry point is removed. Import each element from the subpath for the namespace that declares it:
```tsx
import { AdwHeaderBar } from "@gtkx/jsx/adw";
import { GtkBox, GtkButton } from "@gtkx/jsx/gtk";
```
Namespace subpaths are the public JSX surface and keep unrelated generated libraries out of the module graph.
## Drop the Adwaita subpaths
Adwaita is part of the core packages. `ComboRow`, `ToastProvider`, and `useToast` moved from `@gtkx/components/adw` to `@gtkx/components`, and the internal `@gtkx/react/adw` entry point is gone:
```tsx
import { ComboRow, ToastProvider, useToast } from "@gtkx/components";
```
`DropDown` and `ComboRow` now call `onSelectionChanged` with `null` when their items become empty. Check for `null` before storing the ID. `selectedId` no longer accepts `null`; pass `undefined` when no item is chosen.
Use `useToast().dismissAll()` in place of `useToastOverlay().dismissAll()`. `show()` returns the native `Adw.Toast`; call its `dismiss()` method to dismiss that toast. The forwarding `useToast().dismiss(toast)` method and `ToastOverlayController` type are removed.
## Update runtime imports
Import `createElementComponent` from `@gtkx/react` instead of `@gtkx/react/config`. The config subpath remains for renderer behavior and element registration APIs.
Direct native calls using `bigint64` or `biguint64` descriptors now require bigint values. Runtime bindings still accept exactly representable integer Number inputs within ±2⁵³ and normalize them before crossing the native boundary.
The generated wrapper-retention helper `retainWrapperClasses` now belongs to `@gtkx/runtime/internal`. Regenerate bindings with `gtkx codegen --force` after upgrading so their bootstrap imports match the runtime.
Use generated APIs instead of the removed runtime backing exports: `GObject.getProperty` and `GObject.setProperty`, ParamSpec accessors such as `spec.flags`, a `GObject.Value` instance's `getBoxed()` and `setBoxed()` methods, `GLib.Regex` matching methods, and generated class-structure methods. Replace `GObject.paramSpecOverride(name, source)` with `GObject.ParamSpec.override(name, source)`.
## Update application lifecycle code
React applications should keep rendering `AdwApplication` and `AdwApplicationWindow` through JSX; [When the app ends](/v2/guide/application-lifecycle#when-the-app-ends) describes how they end. The replacements below apply to code that manages an application lifecycle directly.
Replace `createApplication(ApplicationClass, props)` and `ApplicationClass.create(props)` with `new ApplicationClass(props)`. This works for Gio, Gtk, Adw, and custom application subclasses. Replace `getApplicationInstance(application)` and `application.getRegistrationState()` with `application.getIsRegistered()` and, once registered, `application.getIsRemote()`. Use the `activate` signal to build the primary instance's UI and the `runAsync(argv)` promise to observe completion.
The `ApplicationInstance`, `ApplicationRegistrationState`, `ApplicationClass`, and `ApplicationConstructor` helper types are removed. Use generated application classes and their constructor props directly. Use `Gio.Application` in place of the removed `CommandLineApplication` interface. Runtime shutdown remains `quit()` from `@gtkx/runtime`.
Replace `runApplication(application, argv)` with `application.runAsync(argv): Promise` and `quitApplication(application)` with `application.quit()`. Pass an array beginning with the program name, or `null` or `[]` for no arguments; omitting the argument is an error. `RunApplicationResult` is removed. [Running without React](/v2/guide/application-lifecycle#running-without-react) describes when a run ends, how holds keep it running, and what `quit()` does.
## Update Variant values
Import `Variant` from `@gtkx/gi/glib`; its `ByteArray` type is now `VariantByteArray` in that namespace.
The `toVariant` and `fromVariant` helpers are removed. Replace `toVariant(signature, value)` with `new GLib.Variant(signature, value)`, `fromVariant(value)` with `value.deepUnpack()`, and recursive `fromVariant` calls with `value.recursiveUnpack()`. For native replies, `fromVariant("(s)", reply)` becomes `reply.deepUnpack<"(s)">()`. `FromVariantOptions` and `RecursiveFromVariantOptions` are removed too.
Variant dictionaries now use objects for every key type; replace `Map` inputs and reads with object properties. GTKX continues to use exact `bigint` values for 64-bit integers. See [GVariant packing and unpacking](/v2/guide/dbus#gvariant-packing-and-unpacking) for the unpacking modes and GJS compatibility aliases.
## Move GObject ownership into JSX
The settings hooks no longer create a `Gio.Settings` instance. Render `GSettings` from `@gtkx/jsx/gio` in the root portal, capture the instance with a state callback ref, and mount its consumers once it is available. Pass that instance first to `useSetting`, and add it as the `settings` option to `useBindSetting`. [The settings instance](/v2/guide/native-state#the-settings-instance) shows the complete ownership pattern.
`useProperty`, `useSignal`, and `useBindSetting` now take a mounted instance rather than a mutable ref object. Store callback-ref values in state and pass the value to the hook so subscriptions follow replacement and unmounting. Remove imports of the deleted `RefProp` type. See [Objects that JSX creates](/v2/guide/native-state#objects-that-jsx-creates) for the pattern.
## Give form choices explicit values
A form `ComboRow` now controls a non-nullable string field. Replace `null` or `undefined` defaults with an item ID that exists in the choices. GTKX preserves that ID while an asynchronous source is empty, so reloading choices does not alter the form value or dirty state. See [Choose a row](/v2/guide/forms#choose-a-row).
## Update internationalization
GTKX now delegates extraction and resource typing to `i18next-cli`. Keep catalog declarations in ESM files and use the exact names `t`, `useTranslation`, `Trans`, or `TransWithoutContext`; replace imported aliases, `i18n.t` member calls, dynamic keys, and CommonJS declarations with those static forms. Extraction also no longer follows a `t` received through `withTranslation`, the `Translation` render prop or a function parameter, as 1.6 did: codegen leaves those messages out without an error and keeps their translations as obsolete PO entries, and `tsc` then rejects their keys. Import `t` from `@gtkx/i18n` or call `useTranslation()` in those modules; the next codegen run restores the obsolete translations.
Replace the removed positional plural overload:
```ts
t("{{count}} file", {
count,
defaultValue_one: "{{count}} file",
defaultValue_other: "{{count}} files",
});
```
Run codegen after migrating. The generated declaration now uses i18next's standard `CustomTypeOptions` resources instead of GTKX's strict translation registry, so remove imports of GTKX-specific registry types and use types exported by `i18next` or `react-i18next`.
GTKX no longer reads `GTKX_LOCALE_DIR`. A Vitest configuration that tests compiled catalogs passes their directory to the plugin instead:
```ts
plugins: [gtkx({ localeDir: resolve(import.meta.dirname, "dist/locale") })],
```
See [Test translations](/v2/guide/internationalization#test-translations).
## Type settings schema imports
Codegen, `gtkx dev` and `gtkx build` write the types of each GSettings schema beside it, as `.gschema.d.xml.ts`, instead of declaring schemas in `node_modules/.gtkx/env.d.ts`. TypeScript reads these files only with [`allowArbitraryExtensions`](https://www.typescriptlang.org/tsconfig/#allowArbitraryExtensions), so enable it and keep the generated files out of version control:
```json [tsconfig.json]
{
"compilerOptions": {
"allowArbitraryExtensions": true
}
}
```
```text [.gitignore]
*.d.xml.ts
```
A schema import with a wrong path now fails `tsc`, and schemas with the same file name in different directories get their own types. Codegen warns while a project with schemas lacks the option.
## Replace removed APIs
| Replace | With |
| ------------------------------------------- | -------------------------------------------------------------- |
| `object.addEventListener(name, handler)` | `object.on(name, handler)` |
| `object.removeEventListener(name, handler)` | `object.off(name, handler)` |
| `Gdk.RGBA.create(css)` | `new Gdk.RGBA()` followed by a checked `parse(css)` |
| `Graphene.Point.create(x, y)` | `new Graphene.Point({ x, y })` |
| `Graphene.Rect.create(x, y, width, height)` | `new Graphene.Rect().init(x, y, width, height)` |
| `Graphene.Size.create(width, height)` | `new Graphene.Size({ width, height })` |
| `GObject.buildValue(...)` | Pass the JavaScript value, or initialize `new GObject.Value()` |
| `getObjectProperty(...)` | `getProperty(...)` |
| `setObjectProperty(...)` | `setProperty(...)` |
| `@gtkx/gi/cairo` | `@gtkx/cairo` |
| `@gtkx/components/adw` | `@gtkx/components` |
| `animated.GtkLabel` | `animated(GtkLabel)` |
| `AnimatedElements` | `AnimatedElementMap` |
The cairo stub-constructor `*ConstructorProps` aliases have no replacement because their constructors no longer exist.
### Record constructors
_Only affects code that constructs records with `new` or names their `*ConstructorProps` types._
Record constructors now take a props object only when the record has public writable value fields, a supported native default constructor, or the zero-initialization contract of `GObject.Value`. For other records, `new` calls the record's native `new` constructor with the given arguments, as in GJS: `new GLib.String(text)` calls `GLib.String.new(text)`, and `new GLib.VariantType("s")` calls `GLib.VariantType.new("s")`. Records without a `new` constructor, or whose first zero-argument constructor has another name, come only from their native factories: use `GLib.Error.newLiteral(domain, code, message)` or `Graphene.Matrix.alloc().initIdentity()`. The synthetic `*ConstructorProps` types of all these records are removed. `GLib.String` exposes `str`, `len`, and `allocatedLen` as readonly; use methods such as `assign`, `append`, and `truncate` to update its buffer.
### Methods that return native addresses
_Only affects code that reads raw native memory, such as the contents of `GLib.Bytes`, `GLib.Variant` or `Gio.MemoryOutputStream`._
Generated methods that expose unmanaged native addresses are omitted. Replace `GLib.Bytes.getRegion` with `getData` or `newFromBytes`, use `GLib.Variant.getDataAsBytes` instead of `getData`, and close a `Gio.MemoryOutputStream` before calling `stealAsBytes` instead of `getData` or `stealData`.
### `sink()` on closures and param specs
_Only affects code that creates a `GObject.Closure` or `GObject.ParamSpec` and sinks it itself._
Remove calls to `GObject.Closure.sink()` and `GObject.ParamSpec.sink()`. These generated methods are removed as part of the GTKX 2 ownership model: native handles manage reference sinking and release automatically, so no replacement call is needed.
### `@gtkx/gl` debug output and sync waits
_Only affects apps that use `@gtkx/gl`._
`@gtkx/gl` no longer exposes `getDebugMessageLog` or `debugMessageCallback`, whose native contracts require caller-owned memory or callback lifetime management. Remove those calls; the shader, program, and pipeline info-log helpers remain available. Replace `clientWaitSyncLoop` with the generated `clientWaitSync`, which accepts the full timeout as a `bigint`.
### Test compositor
_Only affects test setups that chose a compositor other than the default, Sway._
Headless displays always run Sway, so the Vitest plugin no longer accepts a `compositor` option and `@gtkx/vitest` no longer exports `CompositorId`. Delete the option and any `CompositorId` imports; tests need Sway, as described in the [testing setup](/v2/guide/testing#setup).
## Rename slot props
Child slots now use their GtkBuilder child type names. Rename `topBar` and `bottomBar` on `AdwToolbarView` to `top` and `bottom`, and `overlays` on `GtkOverlay` to `overlay`. `AdwExpanderRow` takes its nested rows as children instead of the `rows` prop:
```tsx
```
The old names are no longer accepted.
## Verify the upgrade
```bash
gtkx codegen --force
tsc --noEmit
gtkx build
```
Finally run the application and inspect it. `@gtkx/react` now registers the Adwaita elements itself, so every application initializes the Adwaita stylesheet and the build depends on the Adwaita introspection and runtime libraries even when it renders no Adwaita widget.
For current configuration and binding behavior, see [Configuration and Codegen](/v2/guide/configuration-and-codegen) and the [API reference](/v2/reference/).
---
---
description: "Build a Markdown notes app for Linux with React and Adwaita, then test, translate, and package it."
---
# Build a Notes App with GTKX
Build **Notes**, a Markdown notes app that keeps each note as a plain file in a folder, from an empty directory, then test, translate, and package it as a Flatpak, deb, rpm, and AppImage. You will use npm packages, Node's file APIs and a worker thread, GtkSourceView (a library outside the default bindings), a GObject interface written in TypeScript, and Fast Refresh, Storybook and MCP, then prepare the app for Flathub.
The tutorial assumes familiarity with [React](https://react.dev/learn) and [TypeScript](https://www.typescriptlang.org/docs/handbook/2/basic-types.html). It focuses on using GTKX with libadwaita and GTK 4. You need Linux, the native development libraries, and Node.js 26.7 or later; [Getting Started](/v2/guide/getting-started) covers installation. Notes also needs GtkSourceView 5 with its GObject introspection data, and the gettext tools.
This tutorial uses the GTKX 2.0 beta. Keep GTKX packages on the same version; [`gtkx upgrade`](/v2/guide/updating) moves them together. For the stable release, use the [1.6 tutorial](/tutorial/), which builds a task manager.
## Check your setup
Confirm that Node.js is version 26.7 or later:
```bash
node --version
```
Scaffold the project:
::: code-group
```bash [npm]
npm create gtkx@beta
```
```bash [pnpm]
pnpm create gtkx@beta
```
:::
Choose `notes` as the project directory, keep the suggested package name, and enter **Notes** as the display name and `dev.gtkx.Notes` as the application ID. Choose your package manager, and enable TypeScript and the testing setup. The scaffolder installs the dependencies and makes a first Git commit.
The commands below use npm; use the equivalent commands for your package manager. If you choose another application ID, substitute it consistently throughout the tutorial.
Start the app:
```bash
cd notes
npm run dev
```
This opens an Adwaita window with a counter. The next chapter replaces it with the Notes window.
Leave `npm run dev` running as you work. It applies saved edits to the open window and relaunches the app when an edit needs a restart; saving `gtkx.config.ts` also regenerates the bindings. [Develop with Fast Refresh](/v2/tutorial/fast-refresh) shows which edits keep the app's state.
## How this tutorial works
Follow the chapters in order. Each one leaves the app runnable and ends with **Run it** checks to try in the running app.
| Stage | Chapters | What you build |
| ----------------------- | ---------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------ |
| Foundation | [Create a Window](/v2/tutorial/your-first-window) through [Develop with Fast Refresh](/v2/tutorial/fast-refresh) | A Markdown editor and preview over a folder of plain files |
| Desktop features | [Adapt the Layout](/v2/tutorial/an-adaptive-layout) through [Complete Note Links](/v2/tutorial/note-links) | An adaptive layout, search, tags, menus, dialogs, preferences, link completion |
| Develop, test, and ship | [Develop the Preview in Storybook](/v2/tutorial/storybook) through [Prepare for Flathub](/v2/tutorial/flatpak) | Stories, integration tests, MCP, translations, and installable packages |
Examples you apply are titled with their file. Most show the whole file: create it or replace yours with it, and the highlighted lines are the ones the chapter adds or changes. A short block, such as a few `package.json` fields or one `gtkx.config.ts` option, shows only what to add; keep the rest of the file. Run `npm run typecheck` after each chapter and `npm test` once [Test the App](/v2/tutorial/testing) adds the suite.
After the **Run it** checks pass, save a commit in your project so you can review the next chapter's changes with `git diff` or return to a working state. Keep the lockfile with that commit.
The [finished source](https://github.com/gtkx-org/gtkx/tree/main/tutorial) is a reference for the complete app. It includes later features, so copy only the change a chapter describes when following along.
---
---
description: "Replace the starter counter with an Adwaita window whose strings are ready for translation."
---
# Create a Window
Replace the starter counter with the Notes window: an Adwaita window with a header bar and an empty state. Its strings go through `t()` from the start, so translating the app later needs no changes to the components.
## The project
The project from [Check your setup](/v2/tutorial/#check-your-setup) has these files to start from:
- `gtkx.config.ts` holds the application ID, `dev.gtkx.Notes`, and the packaging metadata. GTKX reads it for codegen, development and builds.
- `src/index.tsx` creates a React root without a DOM container and renders `` into it. It stays the same throughout the tutorial.
- `src/app.tsx` holds the counter. This chapter replaces it.
[Project structure](/v2/guide/getting-started#project-structure) describes the other files.
The scaffold's starter test, `tests/app.test.tsx`, looks for the counter's Increment button and imports a default export that the new `src/app.tsx` doesn't have, so `npm run typecheck` would fail. Delete it; [Test the App](/v2/tutorial/testing) writes the app's tests.
```bash
rm tests/app.test.tsx
```
## Mark strings for translation
Install `@gtkx/i18n`:
```bash
npm install @gtkx/i18n@beta
```
`useTranslation()` from `@gtkx/i18n` returns `t`, which looks up the translation of its source string and falls back to the string itself. Until [Translate the App](/v2/tutorial/internationalization) adds catalogs, every `t("…")` shows its source text. Pass `t` a string literal, as every chapter does, so that GTKX can extract the message; [Keep messages extractable](/v2/guide/internationalization#keep-messages-extractable) lists the forms it reads.
## The application window
Replace `src/app.tsx`:
```tsx [src/app.tsx]
import { useTranslation } from "@gtkx/i18n";
import {
AdwApplication,
AdwApplicationWindow,
AdwHeaderBar,
AdwStatusPage,
AdwToolbarView,
} from "@gtkx/jsx/adw";
import { quit } from "@gtkx/react";
function App() {
const { t } = useTranslation();
return (
quit()}
>
}>
);
}
export { App };
```
Elements come from `@gtkx/jsx/`, one module per library, and take the native class's properties and signals as camelCase props; [JSX Elements](/v2/guide/jsx-elements) has the rules.
- `AdwApplication` creates the application with the ID from `gtkx.config.ts` and renders its children once it activates. [The application element](/v2/guide/application-lifecycle#the-application-element) explains when the app ends.
- `AdwApplicationWindow` is the main window. `widthRequest` and `heightRequest` set the smallest size it shrinks to, 360 by 294, the size the [GNOME HIG](https://developer.gnome.org/hig/guidelines/adaptive.html) asks phone-friendly apps to support. `quit()` from `@gtkx/react` unmounts the app and quits when the window closes.
- `AdwToolbarView` places bars around its content. Its `top` slot holds an `AdwHeaderBar`, which shows the window title and the close button.
- `AdwStatusPage` is the empty state, a [placeholder page](https://developer.gnome.org/hig/patterns/feedback/placeholders.html) with a symbolic icon, a title and a description. [List the Notes](/v2/tutorial/the-notes-folder) shows it only while the folder has no notes.
## Run it
Save `src/app.tsx`. Its imports changed, so `gtkx dev` restarts the app instead of refreshing it, and the window shows the empty state.
Captured from src/app.tsx above.
Run `npm run typecheck`. It passes once the starter test is gone.
---
---
description: "Read Markdown files from a folder with Node's file APIs and list them in a GTK list view."
---
# List the Notes
Read the `.md` files in the notes folder with Node's `fs/promises` and list them, newest first, in a GTK list view. Each note is a plain file, so any editor or sync tool can change it.
## Find the notes folder
Notes keeps its files in a `Notes` folder inside the user's Documents folder:
```ts [src/notes/files.ts]
import * as GLib from "@gtkx/gi/glib";
import { mkdir, readdir, readFile, stat } from "node:fs/promises";
import { join } from "node:path";
import { type Note, toNote } from "./note.js";
const EXTENSION = ".md";
const defaultFolder = (): string =>
join(
GLib.getUserSpecialDir(GLib.UserDirectory.DIRECTORY_DOCUMENTS) ??
GLib.getHomeDir(),
"Notes",
);
const noteName = (fileName: string): string | null =>
fileName.endsWith(EXTENSION) && !fileName.startsWith(".")
? fileName.slice(0, -EXTENSION.length)
: null;
const readNote = async (folder: string, name: string): Promise => {
const path = join(folder, `${name}${EXTENSION}`);
const info = await stat(path);
if (!info.isFile()) {
return null;
}
return toNote(name, await readFile(path, "utf8"), info.mtimeMs);
};
const readNotes = async (folder: string): Promise => {
await mkdir(folder, { recursive: true });
const names = (await readdir(folder))
.map(noteName)
.filter((name) => name !== null);
const notes = await Promise.all(
names.map((name) => readNote(folder, name)),
);
return notes.filter((note) => note !== null);
};
export { defaultFolder, readNotes };
```
[`GLib.getUserSpecialDir`](https://docs.gtk.org/glib/func.get_user_special_dir.html) returns the Documents folder set in `user-dirs.dirs`, which the desktop may have localized or moved, or `null` when there is none; Notes then uses the home folder. `@gtkx/gi/glib` holds the GLib bindings, generated like the elements in `@gtkx/jsx`.
The rest is ordinary Node.js code, since a GTKX app is a Node.js program ([Why Node.js](/v2/guide/why-gtkx#why-node-js)). `readNotes` creates the folder on first launch, keeps the visible `.md` files, and reads them in parallel. `readNote` calls `stat` before reading a file, which gives its modification time and skips anything that isn't a file, such as a folder named `something.md`.
## Read the notes
A `Note` is the file's name without `.md`, its text, its modification time in milliseconds, and an excerpt for the list:
```ts [src/notes/note.ts]
type Note = {
name: string;
text: string;
modified: number;
excerpt: string;
};
const firstLine = (text: string): string =>
text
.split("\n")
.map((line) => line.trim())
.find((line) => line !== "" && !line.startsWith("#")) ?? "";
const toNote = (name: string, text: string, modified: number): Note => ({
name,
text,
modified,
excerpt: firstLine(text),
});
export { type Note, toNote };
```
The excerpt is the first line that is neither empty nor a heading, as written, so Markdown such as `**bold**` shows its asterisks. [Render the Preview](/v2/tutorial/the-markdown-preview) parses the Markdown and takes the excerpt from the parsed text instead.
## Share the notes
The list, and later the editor and search, need the same notes. A context provider loads them once for a folder:
```tsx [src/notes/notes-provider.tsx]
import { createContext, type ReactNode, use, useEffect, useState } from "react";
import { readNotes } from "./files.js";
import type { Note } from "./note.js";
type NoteMap = ReadonlyMap;
type NotesValue = {
folder: string;
notes: NoteMap | null;
};
const NotesContext = createContext(null);
const NotesProvider = ({
folder,
children,
}: {
folder: string;
children: ReactNode;
}) => {
const [notes, setNotes] = useState(null);
useEffect(() => {
const controller = new AbortController();
const load = async (): Promise => {
const list = await readNotes(folder);
if (!controller.signal.aborted) {
setNotes(new Map(list.map((note) => [note.name, note])));
}
};
void load();
return () => controller.abort();
}, [folder]);
return {children};
};
const useNotes = (): NotesValue => {
const value = use(NotesContext);
if (value === null) {
throw new Error("NotesProvider is required");
}
return value;
};
export { NotesProvider, useNotes };
```
`notes` is `null` until the folder has loaded, then a map from each note's name to the note. The effect aborts on cleanup, so a read that finishes after the provider unmounts, or after `folder` changes, sets no state. `useNotes` reads the context with React's [`use`](https://react.dev/reference/react/use) and throws outside the provider.
## List the notes
Install `@gtkx/components`, which renders GTK's list widgets from data:
```bash
npm install @gtkx/components@beta
```
The notes screen shows a spinner while the folder loads, the empty state from [Create a Window](/v2/tutorial/your-first-window) when it has no notes, and otherwise a list of every note, newest first:
```tsx [src/components/notes-screen.tsx]
import { ListView } from "@gtkx/components";
import * as Gtk from "@gtkx/gi/gtk";
import * as Pango from "@gtkx/gi/pango";
import { useTranslation } from "@gtkx/i18n";
import { AdwSpinner, AdwStatusPage } from "@gtkx/jsx/adw";
import { GtkBox, GtkLabel, GtkScrolledWindow } from "@gtkx/jsx/gtk";
import type { Note } from "../notes/note.js";
import { useNotes } from "../notes/notes-provider.js";
const NoteRow = ({ note }: { note: Note }) => (
);
const NotesScreen = () => {
const { t } = useTranslation();
const { notes } = useNotes();
if (notes === null) {
return ;
}
if (notes.size === 0) {
return (
);
}
const shown = [...notes.values()].sort((a, b) => b.modified - a.modified);
return (
items={shown.map((note) => ({ id: note.name, value: note }))}
isFlat
cssClasses={["navigation-sidebar"]}
rowProps={({ item }) => ({ accessibleLabel: item.name })}
renderItem={({ item }) => }
/>
);
};
export { NotesScreen };
```
- `ListView` takes `items` as `{ id, value }` pairs and a `renderItem` for each row. The note's name is its ID, which is unique within a folder. [List components](/v2/guide/components#list-components) covers selection and how IDs keep rows' state.
- `isFlat` says no item has children, so the list skips looking for a tree.
- GTK names a list row from its own accessible label, not from its content, so `rowProps` labels each row with the note's name. Screen readers announce it, and [Test the App](/v2/tutorial/testing) finds rows by it.
- The `navigation-sidebar` style class gives the rows Adwaita's sidebar look, and the `heading`, `dimmed` and `caption` classes style the labels; see [Style classes](https://gnome.pages.gitlab.gnome.org/libadwaita/doc/1-latest/style-classes.html). Both labels end in an ellipsis when the window is too narrow, and the scrolled window never scrolls sideways.
The app wraps the toolbar view in the provider and shows the screen in place of the status page:
```tsx [src/app.tsx]
import { useTranslation } from "@gtkx/i18n";
import {
AdwApplication,
AdwApplicationWindow,
AdwHeaderBar,
AdwToolbarView,
} from "@gtkx/jsx/adw";
import { quit } from "@gtkx/react";
import { NotesScreen } from "./components/notes-screen.js";
import { defaultFolder } from "./notes/files.js";
import { NotesProvider } from "./notes/notes-provider.js";
function App() {
const { t } = useTranslation();
return (
quit()}
>
}>
);
}
export { App };
```
## Run it
Save the files. The new imports restart the app, which creates the notes folder if it is missing and shows the empty state. Add a few `.md` files to the folder, `~/Documents/Notes` on most desktops, then close the window and run `npm run dev` again: the app reads the folder only when it starts until [Save and Watch Files](/v2/tutorial/saving-and-watching) watches it. The window lists the notes, newest first.
Captured from src/app.tsx above.
---
---
description: "Open notes in a GtkSourceView editor with Markdown highlighting, inside a split view."
---
# Edit a Note
Open the selected note in a Markdown editor beside the list. The editor comes from GtkSourceView, a library outside the set GTKX generates bindings for by default, so the chapter starts by adding it.
## Add GtkSourceView
GTKX generates bindings for Adwaita, GTK and the libraries they depend on. Codegen reads each library's GIR file, which its development package installs. On Fedora, install GtkSourceView's; other distributions have an equivalent package:
```bash
sudo dnf install gtksourceview5-devel
```
List the library by GIR name and version in `gtkx.config.ts`, at the top of the object `defineConfig` receives:
```ts [gtkx.config.ts]
export default defineConfig({
libraries: ["GtkSource-5"],
applicationId: "dev.gtkx.Notes",
```
Then generate the bindings:
```bash
npm run codegen
```
This adds `@gtkx/gi/gtksource`, with GtkSourceView's classes and functions, and `@gtkx/jsx/gtksource`, with its elements. `gtkx dev` also regenerates the bindings whenever `gtkx.config.ts` changes. [The config file](/v2/guide/configuration-and-codegen#the-config-file) covers `libraries` and GIR files outside the standard search paths.
## Two screens in a split view
Install `@gtkx/navigation`, which renders [React Navigation](https://reactnavigation.org) navigators with Adwaita widgets, and `@react-navigation/core`, whose types the app extends:
```bash
npm install @gtkx/navigation@beta @react-navigation/core@^7
```
A split view navigator keeps its first screen in the sidebar and shows the others in the content pane. `src/navigation.ts` declares the screens:
```ts [src/navigation.ts]
import { createSplitViewNavigator, useNavigationState } from "@gtkx/navigation";
type RootParamList = {
Notes: undefined;
Note: { name: string };
};
const Split = createSplitViewNavigator();
type RootNavigatorType = typeof Split;
declare module "@react-navigation/core" {
interface RootNavigator extends RootNavigatorType {}
}
const useOpenNoteName = (): string | null =>
useNavigationState((state) => {
const route = state.routes.at(-1);
return route?.name === "Note" ? (route.params?.name ?? null) : null;
});
export { type RootParamList, Split, useOpenNoteName };
```
- `RootParamList` maps each screen to its route parameters: the `Notes` list takes none, and a `Note` takes the note's name.
- The `declare module` block registers the navigator as the app's root, which types `useNavigation()` and route parameters everywhere. TypeScript augments only a module it can resolve, which is why `@react-navigation/core` is installed directly; see [Typing the root param list](/v2/guide/navigation#typing-the-root-param-list).
- `useOpenNoteName` reads the navigation state with [`useNavigationState`](https://reactnavigation.org/docs/use-navigation-state/), which `@gtkx/navigation` re-exports. The last route is the open page: a `Note` route gives that note's name, and the sidebar's own route, when no note is open, gives `null`.
The window renders the navigator inside a `NavigationContainer`, within the notes provider so both screens read the same notes:
```tsx [src/app.tsx]
import { useTranslation } from "@gtkx/i18n";
import {
AdwApplication,
AdwApplicationWindow,
AdwStatusPage,
} from "@gtkx/jsx/adw";
import { NavigationContainer } from "@gtkx/navigation";
import { quit } from "@gtkx/react";
import { NoteScreen } from "./components/note-screen.js";
import { NotesScreen } from "./components/notes-screen.js";
import { Split } from "./navigation.js";
import { defaultFolder } from "./notes/files.js";
import { NotesProvider } from "./notes/notes-provider.js";
function App() {
const { t } = useTranslation();
return (
quit()}
>
}
>
({
title: route.params.name,
})}
/>
);
}
export { App };
```
- `NavigationContainer` holds the navigation state; [NavigationContainer](/v2/guide/navigation#navigationcontainer) covers what else it accepts.
- `contentPlaceholder` fills the content pane until a note opens.
- Each screen's `title` names its header bar: Notes over the sidebar, and the note's name, read from the route, over the editor. The navigator gives the sidebar and the content pane their own header bars, so the toolbar view from Create a Window is gone.
- The window opens at 720 by 480, wide enough for both panes. [Adapt the Layout](/v2/tutorial/an-adaptive-layout) stacks them in narrow windows.
## Select the open note
The list now selects a row, and the selection follows the route:
```tsx [src/components/notes-screen.tsx]
import { ListView } from "@gtkx/components";
import * as Gtk from "@gtkx/gi/gtk";
import * as Pango from "@gtkx/gi/pango";
import { useTranslation } from "@gtkx/i18n";
import { AdwSpinner, AdwStatusPage } from "@gtkx/jsx/adw";
import { GtkBox, GtkLabel, GtkScrolledWindow } from "@gtkx/jsx/gtk";
import type { SplitViewScreenProps } from "@gtkx/navigation";
import { type RootParamList, useOpenNoteName } from "../navigation.js";
import type { Note } from "../notes/note.js";
import { useNotes } from "../notes/notes-provider.js";
const NoteRow = ({ note }: { note: Note }) => (
);
const NotesScreen = ({
navigation,
}: SplitViewScreenProps) => {
const { t } = useTranslation();
const { notes } = useNotes();
const openName = useOpenNoteName();
if (notes === null) {
return ;
}
if (notes.size === 0) {
return (
);
}
const shown = [...notes.values()].sort((a, b) => b.modified - a.modified);
return (
items={shown.map((note) => ({ id: note.name, value: note }))}
isFlat
cssClasses={["navigation-sidebar"]}
selectionMode={Gtk.SelectionMode.SINGLE}
selectedIds={openName === null ? [] : [openName]}
onSelectionChanged={([name]) => {
if (name !== undefined) {
navigation.navigate("Note", { name });
}
}}
rowProps={({ item }) => ({ accessibleLabel: item.name })}
renderItem={({ item }) => }
/>
);
};
export { NotesScreen };
```
- `selectedIds` holds the open note's name, so the highlighted row matches the content pane however the note was opened.
- `onSelectionChanged` reports the row the user picks, and `navigate` opens that note. Instead of keeping the selection in state, the handler changes the route, and the route selects the row. In a split view, `navigate` replaces the open note rather than stacking another page above it; see [Split view navigator](/v2/guide/navigation#split-view-navigator).
- The empty state's `compact` style class fits the status page into the narrow sidebar, as libadwaita's [`AdwStatusPage`](https://gnome.pages.gitlab.gnome.org/libadwaita/doc/1-latest/class.StatusPage.html) recommends.
## The editor
The editor shows a note's text in a [`GtkSourceView`](https://gnome.pages.gitlab.gnome.org/gtksourceview/gtksourceview5/class.View.html), a text view that highlights syntax:
```tsx [src/editor/note-editor.tsx]
import * as Adw from "@gtkx/gi/adw";
import * as Gtk from "@gtkx/gi/gtk";
import * as GtkSource from "@gtkx/gi/gtksource";
import { useTranslation } from "@gtkx/i18n";
import { GtkScrolledWindow } from "@gtkx/jsx/gtk";
import { GtkSourceBuffer, GtkSourceView } from "@gtkx/jsx/gtksource";
import { useProperty } from "@gtkx/react";
const markdown = GtkSource.LanguageManager.getDefault().getLanguage("markdown");
const NoteEditor = ({ text }: { text: string }) => {
const { t } = useTranslation();
const isDark = useProperty(Adw.StyleManager.getDefault(), "dark");
const styleScheme = GtkSource.StyleSchemeManager.getDefault().getScheme(
isDark ? "Adwaita-dark" : "Adwaita",
);
return (
}
/>
);
};
export { NoteEditor };
```
- The view's `buffer` prop takes a `GtkSourceBuffer` element, which holds the text, its language and its colors. Object properties accept elements, as [The JSX prop model](/v2/guide/jsx-elements#the-jsx-prop-model) describes.
- `getLanguage("markdown")` loads GtkSourceView's Markdown definition once, when the module loads. Importing `@gtkx/gi/gtksource` has already initialized the library; see [Library initialization](/v2/guide/configuration-and-codegen#library-initialization).
- GtkSourceView includes `Adwaita` and `Adwaita-dark` style schemes, which match the app's light and dark styles. `useProperty` follows the style manager's `dark` property and re-renders when it changes, so the buffer switches scheme with the system; see [Following a property](/v2/guide/native-state#following-a-property).
- `accessibleLabel` names the text view for screen readers. [Test the App](/v2/tutorial/testing) finds the editor by it.
- `wrapMode` wraps long lines at word boundaries, or between characters for a word longer than the line. The margins keep the text off the pane's edges.
The note screen looks up the note named in the route and opens it in the editor:
```tsx [src/components/note-screen.tsx]
import { useTranslation } from "@gtkx/i18n";
import { AdwStatusPage } from "@gtkx/jsx/adw";
import type { SplitViewScreenProps } from "@gtkx/navigation";
import { NoteEditor } from "../editor/note-editor.js";
import type { RootParamList } from "../navigation.js";
import { useNotes } from "../notes/notes-provider.js";
const NoteScreen = ({ route }: SplitViewScreenProps) => {
const { t } = useTranslation();
const { notes } = useNotes();
const { name } = route.params;
const note = notes?.get(name);
if (note === undefined) {
return (
);
}
return ;
};
export { NoteScreen };
```
`key={name}` gives each note its own editor: without it, opening another note would reuse the previous note's view, with its cursor and scroll position. A route that names a note the folder doesn't have shows a status page instead.
## Run it
Save the files. The config change regenerates the bindings and the new imports restart the app. The window opens with the list in the sidebar and No Note Selected beside it.
Click a note in the list. Its Markdown opens beside the list with syntax highlighting, in the dark scheme when the system prefers dark. Edits stay in the editor until [Save and Watch Files](/v2/tutorial/saving-and-watching) saves them.
Captured from src/app.tsx above, after clicking Website relaunch.
---
---
description: "Save edits with debounced writes and show changes other programs make to the notes folder."
---
# Save and Watch Files
Write edits back to their files without blocking typing, and show notes that another editor or a sync tool adds, changes or removes while the app runs.
## Save edits
Writing the file on every keystroke would save once per character, and two writes of the same file could finish out of order. A `NoteSaver`, in a new file `src/notes/note-saver.ts`, waits until typing pauses, then writes the note's newest text:
```ts [src/notes/note-saver.ts]
import { writeNote } from "./files.js";
const SAVE_DELAY_MS = 400;
type PendingSave = { text: string; timer: NodeJS.Timeout };
class NoteSaver {
readonly #folder: string;
readonly #onError: (name: string, error: unknown) => void;
readonly #failing = new Set();
readonly #pending = new Map();
readonly #written = new Map();
readonly #writes = new Map>();
constructor(
folder: string,
onError: (name: string, error: unknown) => void,
) {
this.#folder = folder;
this.#onError = onError;
}
schedule(name: string, text: string): void {
clearTimeout(this.#pending.get(name)?.timer);
this.#pending.set(name, {
text,
timer: setTimeout(() => this.#flush(name), SAVE_DELAY_MS),
});
}
flushAll(): void {
for (const name of [...this.#pending.keys()]) {
this.#flush(name);
}
}
isPending(name: string): boolean {
return this.#pending.has(name);
}
isOwnWrite(name: string, text: string): boolean {
return this.#written.get(name) === text;
}
#flush(name: string): void {
const entry = this.#pending.get(name);
if (entry === undefined) {
return;
}
clearTimeout(entry.timer);
this.#pending.delete(name);
this.#written.set(name, entry.text);
const previous = this.#writes.get(name) ?? Promise.resolve();
const write = previous.then(() => this.#write(name, entry.text));
this.#writes.set(name, write);
}
async #write(name: string, text: string): Promise {
try {
await writeNote(this.#folder, name, text);
this.#failing.delete(name);
} catch (error) {
this.#written.delete(name);
if (!this.#failing.has(name)) {
this.#failing.add(name);
this.#onError(name, error);
}
}
}
}
export { NoteSaver };
```
- `schedule` restarts the note's timer with the new text, so a burst of typing becomes one write, 400 milliseconds after the last change.
- `#flush` queues each write behind the note's previous one, so saves of one note never overlap and the last text wins. Different notes save independently.
- `#written` records the text of each note's latest write as soon as the write is queued, and `isPending` tells whether a note's text is still waiting for typing to pause. The folder watcher below uses both.
- A failed write calls `onError` once. The saver stays quiet about that note until one of its saves succeeds, so a full disk doesn't report every keystroke.
- `flushAll` starts every waiting write at once, for when the provider stops watching the folder.
`files.ts` gains `writeNote`, and `readNote` returns `null` for a file that no longer exists, which is how the watcher learns that a note was deleted:
```ts [src/notes/files.ts]
import * as GLib from "@gtkx/gi/glib";
import { mkdir, readdir, readFile, stat, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { type Note, toNote } from "./note.js";
const EXTENSION = ".md";
const defaultFolder = (): string =>
join(
GLib.getUserSpecialDir(GLib.UserDirectory.DIRECTORY_DOCUMENTS) ??
GLib.getHomeDir(),
"Notes",
);
const noteName = (fileName: string): string | null =>
fileName.endsWith(EXTENSION) && !fileName.startsWith(".")
? fileName.slice(0, -EXTENSION.length)
: null;
const notePath = (folder: string, name: string): string =>
join(folder, `${name}${EXTENSION}`);
const isMissing = (error: unknown): boolean =>
error instanceof Error && "code" in error && error.code === "ENOENT";
const readNote = async (folder: string, name: string): Promise => {
const path = notePath(folder, name);
try {
const info = await stat(path);
if (!info.isFile()) {
return null;
}
return toNote(name, await readFile(path, "utf8"), info.mtimeMs);
} catch (error) {
if (isMissing(error)) {
return null;
}
throw error;
}
};
const readNotes = async (folder: string): Promise => {
await mkdir(folder, { recursive: true });
const names = (await readdir(folder))
.map(noteName)
.filter((name) => name !== null);
const notes = await Promise.all(
names.map((name) => readNote(folder, name)),
);
return notes.filter((note) => note !== null);
};
const writeNote = (folder: string, name: string, text: string): Promise =>
writeFile(notePath(folder, name), text);
export { defaultFolder, noteName, readNote, readNotes, writeNote };
```
The editor reports each change to its buffer:
```tsx [src/editor/note-editor.tsx]
import * as Adw from "@gtkx/gi/adw";
import * as Gtk from "@gtkx/gi/gtk";
import * as GtkSource from "@gtkx/gi/gtksource";
import { useTranslation } from "@gtkx/i18n";
import { GtkScrolledWindow } from "@gtkx/jsx/gtk";
import { GtkSourceBuffer, GtkSourceView } from "@gtkx/jsx/gtksource";
import { useProperty } from "@gtkx/react";
const markdown = GtkSource.LanguageManager.getDefault().getLanguage("markdown");
type NoteEditorProps = { text: string; onChange: (text: string) => void };
const NoteEditor = ({ text, onChange }: NoteEditorProps) => {
const { t } = useTranslation();
const isDark = useProperty(Adw.StyleManager.getDefault(), "dark");
const styleScheme = GtkSource.StyleSchemeManager.getDefault().getScheme(
isDark ? "Adwaita-dark" : "Adwaita",
);
return (
{
onChange(
buffer.getText(
buffer.getStartIter(),
buffer.getEndIter(),
false,
),
);
}}
/>
}
/>
);
};
export { NoteEditor };
```
`onChanged` handles the buffer's [`changed`](https://docs.gtk.org/gtk4/signal.TextBuffer.changed.html) signal, and `getText` reads the buffer from its start to its end. The `text` prop still fills the buffer: GTKX writes it only when it differs from the buffer's text, so typing never resets the cursor, and writing it doesn't call `onChanged`; see [The JSX prop model](/v2/guide/jsx-elements#the-jsx-prop-model).
The note screen passes each change to the provider's `edit`:
```tsx [src/components/note-screen.tsx]
import { useTranslation } from "@gtkx/i18n";
import { AdwStatusPage } from "@gtkx/jsx/adw";
import type { SplitViewScreenProps } from "@gtkx/navigation";
import { NoteEditor } from "../editor/note-editor.js";
import type { RootParamList } from "../navigation.js";
import { useNotes } from "../notes/notes-provider.js";
const NoteScreen = ({ route }: SplitViewScreenProps) => {
const { t } = useTranslation();
const { notes, edit } = useNotes();
const { name } = route.params;
const note = notes?.get(name);
if (note === undefined) {
return (
);
}
return (
edit(name, text)}
/>
);
};
export { NoteScreen };
```
## Watch the folder
The provider owns the saver, edits the notes in memory, and watches the folder for changes made by other programs:
```tsx [src/notes/notes-provider.tsx]
import { useToast } from "@gtkx/components";
import { t } from "@gtkx/i18n";
import { watch } from "node:fs";
import { createContext, type ReactNode, use, useEffect, useState } from "react";
import { noteName, readNote, readNotes } from "./files.js";
import { type Note, toNote } from "./note.js";
import { NoteSaver } from "./note-saver.js";
type NoteMap = ReadonlyMap;
type NotesValue = {
folder: string;
notes: NoteMap | null;
edit: (name: string, text: string) => void;
};
const NotesContext = createContext(null);
const withNote = (
notes: NoteMap | null,
name: string,
note: Note | null,
): NoteMap => {
const next = new Map(notes);
if (note === null) {
next.delete(name);
} else {
next.set(name, note);
}
return next;
};
const NotesProvider = ({
folder,
children,
}: {
folder: string;
children: ReactNode;
}) => {
const [notes, setNotes] = useState(null);
const { show } = useToast();
const [saver] = useState(
() =>
new NoteSaver(folder, (name) => {
show({
useMarkup: false,
title: t("Couldn’t save “{{name}}”", { name }),
timeout: 0,
});
}),
);
useEffect(() => {
const controller = new AbortController();
const { signal } = controller;
const refresh = async (name: string): Promise => {
const note = await readNote(folder, name);
const isOwnWrite =
note !== null && saver.isOwnWrite(name, note.text);
if (signal.aborted || saver.isPending(name) || isOwnWrite) {
return;
}
setNotes((current) => withNote(current, name, note));
};
const load = async (): Promise => {
const list = await readNotes(folder);
watch(folder, { signal }, (_event, fileName) => {
const name = fileName === null ? null : noteName(fileName);
if (name !== null) {
void refresh(name);
}
});
if (!signal.aborted) {
setNotes(new Map(list.map((note) => [note.name, note])));
}
};
void load();
return () => {
controller.abort();
saver.flushAll();
};
}, [folder, saver]);
const edit = (name: string, text: string): void => {
saver.schedule(name, text);
setNotes((current) =>
withNote(current, name, toNote(name, text, Date.now())),
);
};
return (
{children}
);
};
const useNotes = (): NotesValue => {
const value = use(NotesContext);
if (value === null) {
throw new Error("NotesProvider is required");
}
return value;
};
export { NotesProvider, useNotes };
```
- `edit` schedules the save and updates the note at once, with the current time as its modification time. The list shows the new excerpt, and the edited note moves to the top.
- `useState` with an initializer creates one saver when the provider mounts and keeps it across renders.
- [`fs.watch`](https://nodejs.org/api/fs.html#fswatchfilename-options-listener) calls its listener with the name of each file that changes in the folder. The listener ignores the kind of event and rereads the file: a note that now exists is added or replaced, and one that doesn't is removed. `noteName` skips everything but visible `.md` files, such as the hidden temporary files some editors save through. Node doesn't promise a file name on every event ([Filename argument](https://nodejs.org/api/fs.html#filename-argument)), so the listener skips a `null` one.
- `refresh` leaves a note alone while it has a pending save, because the editor's text is newer than the file, and when the file holds the text the app last wrote, because the event reports the app's own save. Any other change came from another program, and the open editor shows it.
- The watcher takes the effect's abort signal, so the cleanup closes it, and a read that finishes afterwards sets no state. The cleanup also flushes pending saves. When the window closes, the app writes the last edits, and the Node process exits once they finish; an open watcher would keep it running. See [Ending work on unmount](/v2/guide/application-lifecycle#ending-work-on-unmount).
## Report a failed save
A toast from `@gtkx/components` names a note that couldn't be saved; [Toasts](/v2/guide/components#toasts) covers the provider and `useToast`. The window shares an `AdwToastOverlay` through `ToastProvider`, outside `NotesProvider` so the provider can call `useToast`. The overlay wraps the navigator, so the toast shows over both panes:
```tsx [src/app.tsx]
import { ToastProvider } from "@gtkx/components";
import type * as Adw from "@gtkx/gi/adw";
import { useTranslation } from "@gtkx/i18n";
import {
AdwApplication,
AdwApplicationWindow,
AdwStatusPage,
AdwToastOverlay,
} from "@gtkx/jsx/adw";
import { NavigationContainer } from "@gtkx/navigation";
import { quit } from "@gtkx/react";
import { useRef } from "react";
import { NoteScreen } from "./components/note-screen.js";
import { NotesScreen } from "./components/notes-screen.js";
import { Split } from "./navigation.js";
import { defaultFolder } from "./notes/files.js";
import { NotesProvider } from "./notes/notes-provider.js";
function App() {
const { t } = useTranslation();
const toastOverlayRef = useRef(null);
return (
quit()}
>
}
>
({
title: route.params.name,
})}
/>
);
}
export { App };
```
In the provider's `onError`:
- `timeout: 0` keeps the toast until the user dismisses it ([`timeout`](https://gnome.pages.gitlab.gnome.org/libadwaita/doc/1-latest/property.Toast.timeout.html)), so the message isn't missed while typing.
- `useMarkup: false` shows the title as written. Adwaita reads toast titles as Pango markup by default, and a note's name can contain `&` or `<`.
- The saver keeps the callback it was created with, so the message uses `t` imported from `@gtkx/i18n`, which translates into the current language whenever it runs, rather than the `t` of one render. `{{name}}` inserts the note's name; see [Internationalization](/v2/guide/internationalization).
## Run it
Save the files. The new imports restart the app. Open a note and type: about half a second after the last keystroke, its file in the notes folder holds the new text, and the note moves to the top of the list.
Add, change or delete a `.md` file in the folder from another program, and the list follows. Changing the open note's file updates the editor, and deleting it shows Note Not Found.
Captured from src/app.tsx above, after opening Website relaunch and writing Groceries.md into the notes folder from outside the app.
---
---
description: "Parse Markdown with an npm package and render the syntax tree as native GTK widgets."
---
# Render the Preview
Parse each note with `mdast-util-from-markdown` and render its syntax tree as GTK widgets, so the preview is native text that follows the system style.
## Parse Markdown
Install the parser and the types of the tree it returns:
```bash
npm install mdast-util-from-markdown
npm install -D @types/mdast
```
`fromMarkdown` turns a note's text into an [mdast](https://github.com/syntax-tree/mdast) syntax tree: a root node whose children are blocks, such as headings, paragraphs and lists, which hold inline nodes, such as text, emphasis and links. It is an ordinary npm package, running in the app's Node.js process like the file APIs.
The list's excerpt has been the first line that isn't a heading, as written, so Book club reads `Next up: *Piranesi*` with its asterisks. Removing the syntax with regular expressions would miss links, escapes and nested formatting, while the tree holds the text without it. `src/notes/note.ts` now takes the excerpt from the tree:
```ts [src/notes/note.ts]
import type { Nodes, PhrasingContent } from "mdast";
import { fromMarkdown } from "mdast-util-from-markdown";
type Note = {
name: string;
text: string;
modified: number;
excerpt: string;
};
const plainText = (nodes: PhrasingContent[]): string =>
nodes
.map((node) => {
switch (node.type) {
case "text":
case "inlineCode":
case "html":
return node.value;
case "image":
case "imageReference":
return node.alt ?? "";
case "break":
return " ";
case "footnoteReference":
return "";
default:
return plainText(node.children);
}
})
.join("");
const firstParagraph = (node: Nodes): string | null => {
if (node.type === "paragraph") {
return plainText(node.children);
}
if (!("children" in node) || node.type === "heading") {
return null;
}
for (const child of node.children) {
const text = firstParagraph(child);
if (text !== null) {
return text;
}
}
return null;
};
const toNote = (name: string, text: string, modified: number): Note => ({
name,
text,
modified,
excerpt: firstParagraph(fromMarkdown(text)) ?? "",
});
export { type Note, toNote };
```
- `firstParagraph` walks the tree depth first and returns the first paragraph's text, including one inside a list item or a block quote. It skips headings, which usually repeat the note's name, and code blocks, which aren't paragraphs.
- `plainText` joins a paragraph's inline nodes: emphasis and links give their children's text, inline code its code, an image its description, and a line break a space.
## Map nodes to widgets
Inline formatting becomes [Pango markup](https://docs.gtk.org/Pango/pango_markup.html), the tags a `GtkLabel` renders when `useMarkup` is set. A new folder, `src/preview/`, holds the conversion in `markup.ts`:
```ts [src/preview/markup.ts]
import * as GLib from "@gtkx/gi/glib";
import type { PhrasingContent } from "mdast";
const escape = (text: string): string => GLib.markupEscapeText(text, -1);
const toMarkup = (nodes: PhrasingContent[]): string =>
nodes.map(nodeMarkup).join("");
const nodeMarkup = (node: PhrasingContent): string => {
switch (node.type) {
case "text":
case "html":
return escape(node.value);
case "inlineCode":
return `${escape(node.value)}`;
case "emphasis":
return `${toMarkup(node.children)}`;
case "strong":
return `${toMarkup(node.children)}`;
case "delete":
return `${toMarkup(node.children)}`;
case "link":
return `${toMarkup(node.children)}`;
case "linkReference":
return toMarkup(node.children);
case "image":
case "imageReference":
return escape(node.alt ?? "");
case "break":
return "\n";
case "footnoteReference":
return `${escape(node.label ?? node.identifier)}`;
}
};
export { toMarkup };
```
- [`GLib.markupEscapeText`](https://docs.gtk.org/glib/func.markup_escape_text.html) escapes the note's own text, so a `<` or `&` in a note shows as written instead of breaking the markup. Inline HTML shows as text too.
- A link becomes an `` tag, which the label underlines and makes clickable.
- `fromMarkdown` follows [CommonMark](https://spec.commonmark.org/), so GitHub's strikethrough, tables and task lists stay as text. `@types/mdast` also types the nodes of those extensions, such as `delete` and `footnoteReference`. The `switch` handles every inline type `@types/mdast` lists, and the `string` return type makes TypeScript report any it misses.
`src/preview/markdown-preview.tsx` renders the blocks:
```tsx [src/preview/markdown-preview.tsx]
import * as Gtk from "@gtkx/gi/gtk";
import * as Pango from "@gtkx/gi/pango";
import { useTranslation } from "@gtkx/i18n";
import { AdwClamp } from "@gtkx/jsx/adw";
import {
GtkBox,
GtkLabel,
GtkScrolledWindow,
GtkSeparator,
} from "@gtkx/jsx/gtk";
import type {
Blockquote,
Code,
Heading,
List,
Paragraph,
RootContent,
} from "mdast";
import { fromMarkdown } from "mdast-util-from-markdown";
import { createContext, use, useMemo } from "react";
import { toMarkup } from "./markup.js";
const LinkContext = createContext<(uri: string) => boolean>(() => false);
const HEADING_CLASSES = [
"title-1",
"title-2",
"title-3",
"title-4",
"heading",
"heading",
];
type TextBlockProps = {
markup: string;
cssClasses?: string[];
accessibleRole?: Gtk.AccessibleRole;
};
const TextBlock = ({
markup,
cssClasses = [],
accessibleRole = Gtk.AccessibleRole.LABEL,
}: TextBlockProps) => {
const onLink = use(LinkContext);
return (
onLink(uri)}
/>
);
};
const HeadingBlock = ({ node }: { node: Heading }) => (
);
const ParagraphBlock = ({ node }: { node: Paragraph }) => (
);
const CodeBlock = ({ node }: { node: Code }) => (
);
const QuoteBlock = ({ node }: { node: Blockquote }) => (
);
const ListBlock = ({ node }: { node: List }) => (
{node.children.map((item, index) => (
))}
);
const Block = ({ node }: { node: RootContent }) => {
switch (node.type) {
case "heading":
return ;
case "paragraph":
return ;
case "code":
return ;
case "blockquote":
return ;
case "list":
return ;
case "thematicBreak":
return ;
case "html":
return (
);
default:
return null;
}
};
const Blocks = ({ nodes }: { nodes: RootContent[] }) =>
nodes.map((node, index) => );
type MarkdownPreviewProps = {
text: string;
onActivateLink?: (uri: string) => boolean;
};
const MarkdownPreview = ({
text,
onActivateLink = () => false,
}: MarkdownPreviewProps) => {
const { t } = useTranslation();
const tree = useMemo(() => fromMarkdown(text), [text]);
return (
);
};
export { MarkdownPreview };
```
- `MarkdownPreview` parses the text in `useMemo`, so it parses again only when the text changes, and renders the root's children.
- `Block` picks a widget for each block node. Headings, paragraphs and HTML blocks are labels with markup, and a code block is a monospace label the user can select. A block quote and each list item render their own children, so lists and quotes nest. Other nodes, such as link definitions, render nothing.
- The labels take their look from libadwaita [style classes](https://gnome.pages.gitlab.gnome.org/libadwaita/doc/1-latest/style-classes.html): `title-1` to `title-4` and `heading` size the headings, `monospace` sets code in a fixed-width font, and `dimmed` lowers a quote's contrast. They follow the system's light and dark styles without any CSS.
- `AdwClamp` keeps lines a readable length in a wide window, and the scrolled window scrolls only vertically, since the labels wrap.
- `accessibleRole` tells screen readers what each widget is: the preview is a document named Preview, and headings are headings rather than plain labels. [Test the App](/v2/tutorial/testing) finds them by these roles.
- Every label reports an activated link through `onActivateLink`. Blocks nest to any depth, so `LinkContext` hands the handler down rather than passing it through every block's props; see React's [`createContext`](https://react.dev/reference/react/createContext).
## Switch between editor and preview
The note screen, `src/components/note-screen.tsx`, puts the editor and the preview in a [`GtkStack`](https://docs.gtk.org/gtk4/class.Stack.html), which shows one child at a time:
```tsx [src/components/note-screen.tsx]
import * as Gtk from "@gtkx/gi/gtk";
import { useTranslation } from "@gtkx/i18n";
import { AdwStatusPage } from "@gtkx/jsx/adw";
import { GtkStack, GtkStackPage } from "@gtkx/jsx/gtk";
import type { SplitViewScreenProps } from "@gtkx/navigation";
import { NoteEditor } from "../editor/note-editor.js";
import type { RootParamList } from "../navigation.js";
import { linkedNoteName } from "../notes/files.js";
import { useNotes } from "../notes/notes-provider.js";
import { MarkdownPreview } from "../preview/markdown-preview.js";
type NoteScreenProps = SplitViewScreenProps & {
preview: boolean;
};
const NoteScreen = ({ route, navigation, preview }: NoteScreenProps) => {
const { t } = useTranslation();
const { notes, edit } = useNotes();
const { name } = route.params;
const note = notes?.get(name);
const openLinkedNote = (uri: string): boolean => {
const linked = linkedNoteName(uri);
if (linked === null) {
return false;
}
navigation.navigate("Note", { name: linked });
return true;
};
if (note === undefined) {
return (
);
}
return (
edit(name, text)}
/>
);
};
export { NoteScreen };
```
- Each child sits in a [`GtkStackPage`](/v2/guide/components#stack-pages), the object the stack keeps for it, and `visibleChildName` shows the page with that `name`. The crossfade animates the switch.
- Both pages stay mounted, so the editor keeps its cursor and undo history while the preview shows, and the preview follows every edit.
- `preview` arrives as a prop, next to the navigator's `route` and `navigation`.
The toggle button that sets `preview` belongs in the note's header bar, which the navigator builds from the screen's `options`, so the state lives in `src/app.tsx`:
```tsx [src/app.tsx]
import { ToastProvider } from "@gtkx/components";
import type * as Adw from "@gtkx/gi/adw";
import { useTranslation } from "@gtkx/i18n";
import {
AdwApplication,
AdwApplicationWindow,
AdwStatusPage,
AdwToastOverlay,
} from "@gtkx/jsx/adw";
import { GtkToggleButton } from "@gtkx/jsx/gtk";
import { NavigationContainer } from "@gtkx/navigation";
import { quit } from "@gtkx/react";
import { useRef, useState } from "react";
import { NoteScreen } from "./components/note-screen.js";
import { NotesScreen } from "./components/notes-screen.js";
import { Split } from "./navigation.js";
import { defaultFolder } from "./notes/files.js";
import { NotesProvider } from "./notes/notes-provider.js";
function App() {
const { t } = useTranslation();
const toastOverlayRef = useRef(null);
const [preview, setPreview] = useState(false);
return (
quit()}
>
}
>
({
title: route.params.name,
headerEnd: (
),
})}
>
{(props) => (
)}
);
}
export { App };
```
- `headerEnd` puts the button at the end of the content pane's header bar; [Headers](/v2/guide/navigation#headers) lists the other header options. `active` and `onNotifyActive` keep the button and the state in step, as in [The JSX prop model](/v2/guide/jsx-elements#the-jsx-prop-model).
- The `Note` screen takes a function as its child instead of `component`, so it can pass `preview` along with the navigator's props; see React Navigation's [Passing additional data](https://reactnavigation.org/docs/hello-react-navigation#passing-additional-data).
- The state outlives each note, so the preview stays on when another note opens. [Add Menus and Shortcuts](/v2/tutorial/actions-menus-shortcuts) turns the button into a window action with a keyboard shortcut.
## Follow links
Website relaunch links to another note with `[kickoff]()`. A link like that should open the note in the app. `src/notes/files.ts` gains `linkedNoteName`, which turns a link into a note name:
```ts [src/notes/files.ts]
import * as GLib from "@gtkx/gi/glib";
import { mkdir, readdir, readFile, stat, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { type Note, toNote } from "./note.js";
const EXTENSION = ".md";
const defaultFolder = (): string =>
join(
GLib.getUserSpecialDir(GLib.UserDirectory.DIRECTORY_DOCUMENTS) ??
GLib.getHomeDir(),
"Notes",
);
const noteName = (fileName: string): string | null =>
fileName.endsWith(EXTENSION) && !fileName.startsWith(".")
? fileName.slice(0, -EXTENSION.length)
: null;
const linkedNoteName = (uri: string): string | null => {
const fileName =
GLib.Uri.peekScheme(uri) === null
? GLib.Uri.unescapeString(uri, "/")
: null;
return fileName === null || fileName.includes("/")
? null
: noteName(fileName);
};
const notePath = (folder: string, name: string): string =>
join(folder, `${name}${EXTENSION}`);
const isMissing = (error: unknown): boolean =>
error instanceof Error && "code" in error && error.code === "ENOENT";
const readNote = async (folder: string, name: string): Promise => {
const path = notePath(folder, name);
try {
const info = await stat(path);
if (!info.isFile()) {
return null;
}
return toNote(name, await readFile(path, "utf8"), info.mtimeMs);
} catch (error) {
if (isMissing(error)) {
return null;
}
throw error;
}
};
const readNotes = async (folder: string): Promise => {
await mkdir(folder, { recursive: true });
const names = (await readdir(folder))
.map(noteName)
.filter((name) => name !== null);
const notes = await Promise.all(
names.map((name) => readNote(folder, name)),
);
return notes.filter((note) => note !== null);
};
const writeNote = (folder: string, name: string, text: string): Promise =>
writeFile(notePath(folder, name), text);
export {
defaultFolder,
linkedNoteName,
noteName,
readNote,
readNotes,
writeNote,
};
```
- [`GLib.Uri.peekScheme`](https://docs.gtk.org/glib/type_func.Uri.peek_scheme.html) returns `null` for a relative link, one without a scheme such as `https:`.
- [`GLib.Uri.unescapeString`](https://docs.gtk.org/glib/type_func.Uri.unescape_string.html) decodes escapes such as `%20`, and returns `null` when the link escapes a `/`.
- A link into another folder gives `null`, and `noteName`, which the folder listing uses, accepts only a visible `.md` file.
`openLinkedNote` in the note screen above navigates to the linked note and returns `true`, which tells the label the link is handled. For any other link it returns `false`, and the label's default handler for [`activate-link`](https://docs.gtk.org/gtk4/signal.Label.activate-link.html) opens it in the app the system uses for it, such as the web browser. A link to a note the folder doesn't have shows Note Not Found.
## Run it
Save the files. The new imports restart the app. The excerpts in the list now show text without Markdown syntax.
Open a note and press the eye button in its header bar: the note shows as headings, formatted paragraphs and lists. Activate a link to another note to open it.
Captured from src/app.tsx above, after opening Website relaunch and turning on the preview.
---
---
description: "Change the preview renderer while the app runs and keep the open note and its state."
---
# Develop with Fast Refresh
Restyle the preview while a note stays open, and see what Fast Refresh keeps and when the app restarts instead.
## What Fast Refresh keeps
`npm run dev` watches the project's source files. When you save a component module, Fast Refresh runs the new code and renders its components again in the open window. Everything else stays as it was: React state such as the navigator's open note and the preview toggle in `App`, and the GTK widgets the edit didn't change, such as the editor with its cursor and undo history.
`src/preview/markdown-preview.tsx` exports only `MarkdownPreview`, and its other components are private to the module, so a save refreshes it in place. Saving a module that exports something other than components, such as `toMarkup` in `markup.ts`, refreshes the components that import it. The terminal prints `Running Fast Refresh...` and `Fast Refresh complete` for each save.
## Restyle the preview
Open a note with a quote and a code block. If your folder has none, save this as `Meeting notes.md` in it:
````md
# Meeting notes
Kickoff with design and docs, Tuesday 10:00.
> Launch when the content is ready, not before.
Preview the new site locally:
```sh
npm install
npm run docs:dev
```
````
The preview renders the quote as dimmed text and the code block as a plain monospace label. Change `CodeBlock` and `QuoteBlock` in `src/preview/markdown-preview.tsx`, saving after each:
```tsx [src/preview/markdown-preview.tsx]
import * as Gtk from "@gtkx/gi/gtk";
import * as Pango from "@gtkx/gi/pango";
import { useTranslation } from "@gtkx/i18n";
import { AdwClamp } from "@gtkx/jsx/adw";
import {
GtkBox,
GtkLabel,
GtkScrolledWindow,
GtkSeparator,
} from "@gtkx/jsx/gtk";
import type {
Blockquote,
Code,
Heading,
List,
Paragraph,
RootContent,
} from "mdast";
import { fromMarkdown } from "mdast-util-from-markdown";
import { createContext, use, useMemo } from "react";
import { toMarkup } from "./markup.js";
const LinkContext = createContext<(uri: string) => boolean>(() => false);
const HEADING_CLASSES = [
"title-1",
"title-2",
"title-3",
"title-4",
"heading",
"heading",
];
type TextBlockProps = {
markup: string;
cssClasses?: string[];
accessibleRole?: Gtk.AccessibleRole;
};
const TextBlock = ({
markup,
cssClasses = [],
accessibleRole = Gtk.AccessibleRole.LABEL,
}: TextBlockProps) => {
const onLink = use(LinkContext);
return (
onLink(uri)}
/>
);
};
const HeadingBlock = ({ node }: { node: Heading }) => (
);
const ParagraphBlock = ({ node }: { node: Paragraph }) => (
);
const CodeBlock = ({ node }: { node: Code }) => (
);
const QuoteBlock = ({ node }: { node: Blockquote }) => (
);
const ListBlock = ({ node }: { node: List }) => (
{node.children.map((item, index) => (
))}
);
const Block = ({ node }: { node: RootContent }) => {
switch (node.type) {
case "heading":
return ;
case "paragraph":
return ;
case "code":
return ;
case "blockquote":
return ;
case "list":
return ;
case "thematicBreak":
return ;
case "html":
return (
);
default:
return null;
}
};
const Blocks = ({ nodes }: { nodes: RootContent[] }) =>
nodes.map((node, index) => );
type MarkdownPreviewProps = {
text: string;
onActivateLink?: (uri: string) => boolean;
};
const MarkdownPreview = ({
text,
onActivateLink = () => false,
}: MarkdownPreviewProps) => {
const { t } = useTranslation();
const tree = useMemo(() => fromMarkdown(text), [text]);
return (
);
};
export { MarkdownPreview };
```
- `CodeBlock` puts the label in a box with the [`card`](https://gnome.pages.gitlab.gnome.org/libadwaita/doc/1-latest/style-classes.html#boxed-lists-cards) style class, which gives it the rounded background of a boxed list. The margins keep the code clear of the card's edge, and `hexpand` stretches the label across the card.
- `QuoteBlock` sets a vertical [`GtkSeparator`](https://docs.gtk.org/gtk4/class.Separator.html) beside the quote's blocks, as a bar. The module already imports `GtkSeparator` for thematic breaks.
## When the app restarts
Some edits can't be applied to the running app, so `gtkx dev` relaunches it, and its state starts over: no note is open and the preview is off. The most common one is a change to which modules a file imports. Importing a module the file didn't import before, or dropping one, prints `Module imports changed: ` and `Full restart (process restart)`. Adding a name to an import the file already has, such as another element from `@gtkx/jsx/gtk`, refreshes as usual.
A component whose hook calls change, for example one that gains a `useState`, is mounted again with the components inside it, and they lose their state while the rest of the window keeps its own. [The app restarts instead of refreshing](/v2/guide/troubleshooting#the-app-restarts-instead-of-refreshing) lists every edit that restarts the app.
## Run it
With `npm run dev` running, open Meeting notes and press the eye button in its header bar. Save each change to `markdown-preview.tsx`: the code block moves into a card, the quote gets its bar, and the note stays open in the preview.
Recorded under npm run dev while saving each change to src/preview/markdown-preview.tsx above.
---
---
description: "Collapse the split view on narrow windows and keep the window usable at phone size."
---
# Adapt the Layout
Show the note list and the open note one at a time in narrow windows, size the sidebar, and keep the window usable at phone size.
## Collapse on narrow windows
[Edit a Note](/v2/tutorial/the-note-editor) opens the window at 720 by 480, wide enough for the note list and the note side by side. On a phone, or in a window tiled to a third of a screen, there is no room for both. Add these props to `Split.Navigator` in `src/app.tsx`:
```tsx [src/app.tsx]
import { ToastProvider } from "@gtkx/components";
import type * as Adw from "@gtkx/gi/adw";
import { useTranslation } from "@gtkx/i18n";
import {
AdwApplication,
AdwApplicationWindow,
AdwStatusPage,
AdwToastOverlay,
} from "@gtkx/jsx/adw";
import { GtkToggleButton } from "@gtkx/jsx/gtk";
import { NavigationContainer } from "@gtkx/navigation";
import { quit } from "@gtkx/react";
import { useRef, useState } from "react";
import { NoteScreen } from "./components/note-screen.js";
import { NotesScreen } from "./components/notes-screen.js";
import { Split } from "./navigation.js";
import { defaultFolder } from "./notes/files.js";
import { NotesProvider } from "./notes/notes-provider.js";
function App() {
const { t } = useTranslation();
const toastOverlayRef = useRef(null);
const [preview, setPreview] = useState(false);
return (
quit()}
>
}
>
({
title: route.params.name,
headerEnd: (
),
})}
>
{(props) => (
)}
);
}
export { App };
```
`collapseCondition` takes a libadwaita [breakpoint condition](https://gnome.pages.gitlab.gnome.org/libadwaita/doc/1-latest/type_func.BreakpointCondition.parse.html). While the navigator is 500sp wide or narrower, the split view collapses: the note list fills the window, and selecting a note opens it in its place, with a back button in its header bar that returns to the list. Widen the window past 500sp and the panes sit side by side again, with the open note still selected.
An sp is a pixel at the default text size and grows with the Large Text setting ([`AdwLengthUnit`](https://gnome.pages.gitlab.gnome.org/libadwaita/doc/1-latest/enum.LengthUnit.html)), so readers with larger text get the one-pane layout in wider windows. The condition is measured against the navigator rather than the window; [Split view navigator](/v2/guide/navigation#split-view-navigator) explains why it beats setting `collapsed` from a window breakpoint.
## Size the sidebar
The other props bound the sidebar while the panes sit side by side. `sidebarWidthFraction` asks for 30% of the width, and `minSidebarWidth` and `maxSidebarWidth` keep it between 220 and 320, in sp like the condition. At the default size the sidebar gets 220; in a maximized window it stops at 320 and the note takes the rest. libadwaita's defaults (25%, between 180 and 280) leave less room for note names, which the rows cut off with an ellipsis.
The minimum and the condition go together: in the narrowest side-by-side layout, the note pane still gets about 280 beside the sidebar's 220.
## Fit a phone screen
[Create a Window](/v2/tutorial/your-first-window) set `widthRequest` and `heightRequest` to 360 by 294, the smallest size the GNOME HIG asks phone-friendly apps to support. That size now matters: a breakpoint takes away the navigator's own minimum size, so the window's size request is the only floor (see [`AdwBreakpointBin`](https://gnome.pages.gitlab.gnome.org/libadwaita/doc/1-latest/class.BreakpointBin.html#minimum-size)). At 360 the split view is collapsed, and each pane fits the width on its own.
## Run it
Narrow the window until the sidebar and the note no longer sit side by side, then open Website relaunch. The note fills the window, and the back button in its header bar returns to the list.
Captured from src/app.tsx above, with the window at 360 by 480 after opening Website relaunch.
---
---
description: "Index notes with MiniSearch in a Node worker thread and search them from the sidebar."
---
# Search in a Worker
Index the full text of every note with MiniSearch in a worker thread, so searching never blocks the window.
## Build the index in a worker
Your JavaScript runs on the same thread as GTK's main loop, so while it computes, the window can't redraw or take input. Indexing a few notes takes no time, but a folder of several thousand would freeze the window until indexing finished. [MiniSearch](https://lucaong.github.io/minisearch/) builds a full-text index in memory, and a [Node worker thread](https://nodejs.org/api/worker_threads.html) runs it beside the main thread. Install it; it ships its own types:
```sh
npm install minisearch
```
The worker, in a new file `src/search/search-worker.ts`, holds the index and answers messages from the main thread:
```ts [src/search/search-worker.ts]
import MiniSearch from "minisearch";
import { parentPort } from "node:worker_threads";
type IndexedNote = { name: string; text: string };
type SearchRequest =
| { type: "update"; notes: IndexedNote[]; removed: string[] }
| { type: "search"; id: number; query: string };
type SearchResponse = { id: number; names: string[] };
if (parentPort === null) {
throw new Error("search-worker must run in a worker thread");
}
const port = parentPort;
const index = new MiniSearch({
idField: "name",
fields: ["name", "text"],
searchOptions: { prefix: true, fuzzy: 0.2 },
});
port.on("message", (request: SearchRequest) => {
switch (request.type) {
case "update":
for (const name of [
...request.removed,
...request.notes.map((note) => note.name),
]) {
if (index.has(name)) {
index.discard(name);
}
}
index.addAll(request.notes);
break;
case "search": {
const names = index
.search(request.query)
.map((result) => String(result.id));
port.postMessage({
id: request.id,
names,
} satisfies SearchResponse);
break;
}
}
});
export type { SearchRequest, SearchResponse };
```
- An `update` message carries the notes that changed and the names of those that were removed. MiniSearch rejects a second document with the same ID, so the worker first drops the old version of each note with `discard`, which needs only the ID, and then adds the new ones.
- A `search` message carries an `id`, and the answer sends it back with the matching note names, so the main thread can tell which query an answer belongs to.
- `idField: "name"` makes the note name the document ID; names are unique because they are file names. `prefix: true` lets "kick" find "kickoff", and `fuzzy: 0.2` allows an edit distance of a fifth of each word's length, rounded, so "kikoff" finds it too. See MiniSearch's [search options](https://lucaong.github.io/minisearch/types/MiniSearch.SearchOptions.html).
- `parentPort` is `null` outside a worker, so importing the file on the main thread by mistake fails at once.
A worker can't use GTK, since only the main thread owns GTKX's GLib integration; this one needs only MiniSearch and Node. [Workers and Helper Processes](/v2/guide/workers) explains how `gtkx dev`, Vitest and `gtkx build` load a worker file and which syntax it can use.
## Talk to the worker
`SearchIndex`, in `src/search/search-index.ts`, is the main thread's side of the conversation:
```ts [src/search/search-index.ts]
import { Worker } from "node:worker_threads";
import type { SearchRequest, SearchResponse } from "./search-worker.js";
type SearchableNote = { name: string; text: string };
class SearchIndex {
readonly #indexed = new Map();
readonly #waiting = new Map void>();
#worker: Worker | null = null;
#nextId = 0;
update(notes: Iterable): void {
const current = new Map(
[...notes].map((note) => [note.name, note.text]),
);
const changed = [...current]
.filter(([name, text]) => this.#indexed.get(name) !== text)
.map(([name, text]) => ({ name, text }));
const removed = [...this.#indexed.keys()].filter(
(name) => !current.has(name),
);
if (changed.length === 0 && removed.length === 0) {
return;
}
this.#indexed.clear();
for (const [name, text] of current) {
this.#indexed.set(name, text);
}
this.#post({ type: "update", notes: changed, removed });
}
search(query: string): Promise {
const id = this.#nextId++;
const result = new Promise((resolve) =>
this.#waiting.set(id, resolve),
);
this.#post({ type: "search", id, query });
return result;
}
close(): void {
void this.#worker?.terminate();
this.#worker = null;
this.#indexed.clear();
this.#waiting.clear();
}
#post(request: SearchRequest): void {
this.#worker ??= this.#start();
this.#worker.postMessage(request);
}
#start(): Worker {
const worker = new Worker(
new URL("./search-worker.ts", import.meta.url),
);
worker.on("message", ({ id, names }: SearchResponse) => {
this.#waiting.get(id)?.(names);
this.#waiting.delete(id);
});
return worker;
}
}
export { SearchIndex };
```
- The worker starts on the first message, so nothing runs until there are notes to index.
- `#indexed` keeps the text last sent for each note, and `update` sends only the notes whose text differs and the names that disappeared. After a save, the worker re-indexes one note rather than the folder.
- `search` gives each query an ID and returns a promise that the answer with that ID resolves. The worker handles messages in the order they were sent, so a query always sees the update sent before it.
- `close` stops the worker and forgets what it was sent, so a later `update` starts a new worker and sends every note.
`search-index.ts` imports the message types with `import type`, which is removed when the file is compiled, so the main thread never loads the worker's module. `gtkx build` bundles the worker because `new Worker` names its source file directly. During `gtkx dev`, an edit to `search-worker.ts` restarts the app instead of refreshing it, since [Fast Refresh](/v2/tutorial/fast-refresh) only reaches the main thread.
## Query from React
`useNoteSearch`, in `src/search/use-note-search.ts`, connects the index to the screen:
```ts [src/search/use-note-search.ts]
import { useEffect, useState } from "react";
import type { Note } from "../notes/note.js";
import { SearchIndex } from "./search-index.js";
const useNoteSearch = (
notes: ReadonlyMap | null,
query: string,
): ReadonlySet | null => {
const [index] = useState(() => new SearchIndex());
const [result, setResult] = useState | null>(null);
useEffect(() => () => index.close(), [index]);
useEffect(() => {
if (notes === null) {
return;
}
index.update(notes.values());
if (query === "") {
return;
}
let current = true;
void index.search(query).then((names) => {
if (current) {
setResult(new Set(names));
}
});
return () => {
current = false;
};
}, [index, notes, query]);
return query === "" ? null : result;
};
export { useNoteSearch };
```
The `useState` initializer creates one `SearchIndex` when the screen mounts, and the first effect closes it when the screen unmounts. The second effect runs whenever the notes or the query change: it updates the index, which sends nothing when no note changed, and searches if the query isn't empty. When the query changes before an answer arrives, the effect's cleanup sets `current` to `false`, so the late answer doesn't replace a newer one. The hook returns the set of matching names, or `null` while the query is empty, which means "show every note".
## The search entry
`src/components/notes-screen.tsx` puts a `GtkSearchEntry` above the list:
```tsx [src/components/notes-screen.tsx]
import { ListView } from "@gtkx/components";
import * as Gtk from "@gtkx/gi/gtk";
import * as Pango from "@gtkx/gi/pango";
import { useTranslation } from "@gtkx/i18n";
import { AdwSpinner, AdwStatusPage } from "@gtkx/jsx/adw";
import {
GtkBox,
GtkCallbackAction,
GtkLabel,
GtkScrolledWindow,
GtkSearchEntry,
GtkShortcut,
GtkShortcutController,
GtkShortcutTrigger,
} from "@gtkx/jsx/gtk";
import type { SplitViewScreenProps } from "@gtkx/navigation";
import { useState } from "react";
import { type RootParamList, useOpenNoteName } from "../navigation.js";
import type { Note } from "../notes/note.js";
import { useNotes } from "../notes/notes-provider.js";
import { useNoteSearch } from "../search/use-note-search.js";
const NoteRow = ({ note }: { note: Note }) => (
);
const FocusShortcut = ({ target }: { target: Gtk.Widget | null }) => (
}
action={
target?.grabFocus() ?? false}
/>
}
/>
}
/>
);
const NotesScreen = ({
navigation,
}: SplitViewScreenProps) => {
const { t } = useTranslation();
const { notes } = useNotes();
const openName = useOpenNoteName();
const [query, setQuery] = useState("");
const [searchEntry, setSearchEntry] = useState(
null,
);
const matches = useNoteSearch(notes, query.trim());
if (notes === null) {
return ;
}
if (notes.size === 0) {
return (
);
}
const shown = [...notes.values()]
.filter((note) => matches === null || matches.has(note.name))
.sort((a, b) => b.modified - a.modified);
return (
}
>
setQuery(entry.getText())}
onStopSearch={() => setQuery("")}
marginTop={6}
marginBottom={6}
marginStart={6}
marginEnd={6}
/>
{shown.length === 0 ? (
) : (
items={shown.map((note) => ({
id: note.name,
value: note,
}))}
isFlat
cssClasses={["navigation-sidebar"]}
selectionMode={Gtk.SelectionMode.SINGLE}
selectedIds={openName === null ? [] : [openName]}
onSelectionChanged={([name]) => {
if (name !== undefined) {
navigation.navigate("Note", { name });
}
}}
rowProps={({ item }) => ({
accessibleLabel: item.name,
})}
renderItem={({ item }) => }
/>
)}
);
};
export { NotesScreen };
```
- The entry emits [`search-changed`](https://docs.gtk.org/gtk4/signal.SearchEntry.search-changed.html) once typing pauses for 150 milliseconds rather than on every key, so `query` and the worker see one query per pause. `onSearchChanged` stores the entry's text, trimmed before it reaches the hook.
- Escape emits [`stop-search`](https://docs.gtk.org/gtk4/signal.SearchEntry.stop-search.html), and `onStopSearch` empties the query. The `text` prop then clears the entry; GTKX writes it only when it differs from the entry's text, so typing never fights it ([The JSX prop model](/v2/guide/jsx-elements#the-jsx-prop-model)).
- `accessibleLabel` names the entry for screen readers and for tests, which find it by that name in [Test the App](/v2/tutorial/testing).
- The list keeps only the notes in the matches, still newest first, and a status page replaces it when none match.
## Focus search with Ctrl+F
`FocusShortcut`, above `NotesScreen`, is a `GtkShortcutController` in the sidebar box's `controllers` prop. Its `GLOBAL` scope handles Ctrl+F anywhere in the window, not only while the sidebar has focus. The callback needs the entry widget, so the entry's `ref` stores it in state (`setSearchEntry`), and the screen renders again with it once the entry exists. The callback returns whether `grabFocus` succeeded; `false`, before the entry exists or when it can't take focus, leaves the key to other handlers. See [Shortcuts without an action](/v2/guide/actions#shortcuts-without-an-action).
## Run it
Type "kickoff" in the search entry. The list narrows to the two notes whose text mentions it, Website relaunch and Meeting notes. Type something no note contains to see the status page, then press Escape to clear the search.
Captured from src/components/notes-screen.tsx above, after typing kickoff in the search entry.
---
---
description: "Read tags from YAML front matter and filter the note list with a drop-down."
---
# Filter by Tag
Read tags from each note's YAML front matter and filter the list by tag.
## Parse front matter
Tags live in the note file itself, in a block of YAML between two `---` lines at the top, so the notes folder stays plain Markdown that any editor can open. Install [yaml](https://eemeli.org/yaml/) to parse the block; it ships its own types:
```sh
npm install yaml
```
`src/notes/note.ts` splits each file into its front matter and its body:
```ts [src/notes/note.ts]
import type { Nodes, PhrasingContent } from "mdast";
import { fromMarkdown } from "mdast-util-from-markdown";
import { parse } from "yaml";
type Note = {
name: string;
text: string;
modified: number;
body: string;
tags: string[];
excerpt: string;
};
const FRONT_MATTER = /^---\r?\n(?:([\s\S]*?)\r?\n)?---[ \t]*(?:\r?\n|$)/;
const parseYaml = (source: string): unknown => {
try {
return parse(source);
} catch {
return null;
}
};
const toTags = (value: unknown): string[] => {
const values: unknown[] = Array.isArray(value) ? value : [value];
const tags = values
.filter((tag) => typeof tag === "string")
.map((tag) => tag.trim().replace(/^#/, ""))
.filter((tag) => tag !== "");
return [...new Set(tags)];
};
const splitFrontMatter = (text: string): { tags: string[]; body: string } => {
const match = FRONT_MATTER.exec(text);
if (match === null) {
return { tags: [], body: text };
}
const data = parseYaml(match[1] ?? "");
const tags =
typeof data === "object" && data !== null && "tags" in data
? toTags(data.tags)
: [];
return { tags, body: text.slice(match[0].length) };
};
const plainText = (nodes: PhrasingContent[]): string =>
nodes
.map((node) => {
switch (node.type) {
case "text":
case "inlineCode":
case "html":
return node.value;
case "image":
case "imageReference":
return node.alt ?? "";
case "break":
return " ";
case "footnoteReference":
return "";
default:
return plainText(node.children);
}
})
.join("");
const firstParagraph = (node: Nodes): string | null => {
if (node.type === "paragraph") {
return plainText(node.children);
}
if (!("children" in node) || node.type === "heading") {
return null;
}
for (const child of node.children) {
const text = firstParagraph(child);
if (text !== null) {
return text;
}
}
return null;
};
const toNote = (name: string, text: string, modified: number): Note => {
const { tags, body } = splitFrontMatter(text);
return {
name,
text,
modified,
body,
tags,
excerpt: firstParagraph(fromMarkdown(body)) ?? "",
};
};
export { type Note, toNote };
```
- `FRONT_MATTER` matches only at the very start of the file: a `---` line, the YAML, and a closing `---` line. A file without the block has no tags, and its body is the whole text.
- `parse` throws on YAML it can't read. `parseYaml` turns the error into `null`, so a note with a broken block still loads, with no tags.
- `toTags` accepts a list (`tags: [home, reading]`) or a single tag (`tags: home`), removes duplicates, and skips values that aren't strings, such as `2026`, which YAML reads as a number. It also drops a leading `#`, so `home` and `#home` are the same tag. A `#` after a space starts a YAML comment, so a tag written with one must be quoted: `tags: "#home"`.
- `body` is the text after the block. The excerpt and the preview read it, while the editor, the saver and the search keep using the whole `text`.
## Filter the list
`src/components/notes-screen.tsx` adds a drop-down of tags under the search entry:
```tsx [src/components/notes-screen.tsx]
import { DropDown, ListView } from "@gtkx/components";
import * as Gtk from "@gtkx/gi/gtk";
import * as Pango from "@gtkx/gi/pango";
import { useTranslation } from "@gtkx/i18n";
import { AdwSpinner, AdwStatusPage } from "@gtkx/jsx/adw";
import {
GtkBox,
GtkCallbackAction,
GtkLabel,
GtkScrolledWindow,
GtkSearchEntry,
GtkShortcut,
GtkShortcutController,
GtkShortcutTrigger,
} from "@gtkx/jsx/gtk";
import type { SplitViewScreenProps } from "@gtkx/navigation";
import { useState } from "react";
import { type RootParamList, useOpenNoteName } from "../navigation.js";
import type { Note } from "../notes/note.js";
import { useNotes } from "../notes/notes-provider.js";
import { useNoteSearch } from "../search/use-note-search.js";
const ALL_NOTES = "";
const allTags = (notes: Iterable): string[] =>
[...new Set([...notes].flatMap((note) => note.tags))].sort((a, b) =>
a.localeCompare(b),
);
const TagFilter = ({
tags,
tag,
onChange,
}: {
tags: string[];
tag: string;
onChange: (tag: string) => void;
}) => {
const { t } = useTranslation();
return (
({ id: name, value: `#${name}` })),
]}
selectedId={tag}
onSelectionChanged={(id) => onChange(id ?? ALL_NOTES)}
/>
);
};
const NoteRow = ({ note }: { note: Note }) => (
);
const FocusShortcut = ({ target }: { target: Gtk.Widget | null }) => (
}
action={
target?.grabFocus() ?? false}
/>
}
/>
}
/>
);
const NotesScreen = ({
navigation,
}: SplitViewScreenProps) => {
const { t } = useTranslation();
const { notes } = useNotes();
const openName = useOpenNoteName();
const [query, setQuery] = useState("");
const [selectedTag, setSelectedTag] = useState(ALL_NOTES);
const [searchEntry, setSearchEntry] = useState(
null,
);
const matches = useNoteSearch(notes, query.trim());
if (notes === null) {
return ;
}
if (notes.size === 0) {
return (
);
}
const tags = allTags(notes.values());
const tag = tags.includes(selectedTag) ? selectedTag : ALL_NOTES;
const shown = [...notes.values()]
.filter((note) => tag === ALL_NOTES || note.tags.includes(tag))
.filter((note) => matches === null || matches.has(note.name))
.sort((a, b) => b.modified - a.modified);
return (
}
>
setQuery(entry.getText())}
onStopSearch={() => setQuery("")}
/>
{tags.length > 0 && (
)}
{shown.length === 0 ? (
) : (
items={shown.map((note) => ({
id: note.name,
value: note,
}))}
isFlat
cssClasses={["navigation-sidebar"]}
selectionMode={Gtk.SelectionMode.SINGLE}
selectedIds={openName === null ? [] : [openName]}
onSelectionChanged={([name]) => {
if (name !== undefined) {
navigation.navigate("Note", { name });
}
}}
rowProps={({ item }) => ({
accessibleLabel: item.name,
})}
renderItem={({ item }) => }
/>
)}
);
};
export { NotesScreen };
```
- `allTags` collects the tags of every note once, sorted alphabetically.
- `TagFilter` renders a [`DropDown`](/v2/guide/components#dropdown) from `@gtkx/components`. Its items are "All Notes" followed by each tag. The values are strings, so the drop-down shows them as labels without a `renderItem`. Selection works by item ID, and "All Notes" takes the empty string, which no tag can be because `toTags` drops empty ones. The tooltip says what the drop-down is for, since it shows only the current choice.
- `selectedTag` is what the user chose, and `tag` is what the list uses. When the chosen tag no longer exists, for example after you edit it out of the last note that had it, `tag` falls back to all notes, and passing it as `selectedId` moves the drop-down back to "All Notes".
- The tag and the search apply together: a note shows when it has the tag and matches the query. The search indexes each note's whole text, front matter included, so searching for a tag name also finds its notes.
- The drop-down renders only when some note has a tag, so a folder without front matter looks as before. The search entry and the drop-down share a box, which takes over the entry's margins.
## Show tags in the preview
Until now the preview rendered the whole file, so a front matter block showed as a horizontal rule above a heading made of the YAML. The note screen now passes the preview the note's body and its tags:
```tsx [src/components/note-screen.tsx]
import * as Gtk from "@gtkx/gi/gtk";
import { useTranslation } from "@gtkx/i18n";
import { AdwStatusPage } from "@gtkx/jsx/adw";
import { GtkStack, GtkStackPage } from "@gtkx/jsx/gtk";
import type { SplitViewScreenProps } from "@gtkx/navigation";
import { NoteEditor } from "../editor/note-editor.js";
import type { RootParamList } from "../navigation.js";
import { linkedNoteName } from "../notes/files.js";
import { useNotes } from "../notes/notes-provider.js";
import { MarkdownPreview } from "../preview/markdown-preview.js";
type NoteScreenProps = SplitViewScreenProps & {
preview: boolean;
};
const NoteScreen = ({ route, navigation, preview }: NoteScreenProps) => {
const { t } = useTranslation();
const { notes, edit } = useNotes();
const { name } = route.params;
const note = notes?.get(name);
const openLinkedNote = (uri: string): boolean => {
const linked = linkedNoteName(uri);
if (linked === null) {
return false;
}
navigation.navigate("Note", { name: linked });
return true;
};
if (note === undefined) {
return (
);
}
return (
edit(name, text)}
/>
);
};
export { NoteScreen };
```
The editor still gets `note.text`, so the front matter stays editable.
`MarkdownPreview`, in `src/preview/markdown-preview.tsx`, shows the tags above the body:
```tsx [src/preview/markdown-preview.tsx]
import * as Gtk from "@gtkx/gi/gtk";
import * as Pango from "@gtkx/gi/pango";
import { useTranslation } from "@gtkx/i18n";
import { AdwClamp } from "@gtkx/jsx/adw";
import {
GtkBox,
GtkLabel,
GtkScrolledWindow,
GtkSeparator,
} from "@gtkx/jsx/gtk";
import type {
Blockquote,
Code,
Heading,
List,
Paragraph,
RootContent,
} from "mdast";
import { fromMarkdown } from "mdast-util-from-markdown";
import { createContext, use, useMemo } from "react";
import { toMarkup } from "./markup.js";
const LinkContext = createContext<(uri: string) => boolean>(() => false);
const HEADING_CLASSES = [
"title-1",
"title-2",
"title-3",
"title-4",
"heading",
"heading",
];
type TextBlockProps = {
markup: string;
cssClasses?: string[];
accessibleRole?: Gtk.AccessibleRole;
};
const TextBlock = ({
markup,
cssClasses = [],
accessibleRole = Gtk.AccessibleRole.LABEL,
}: TextBlockProps) => {
const onLink = use(LinkContext);
return (
onLink(uri)}
/>
);
};
const HeadingBlock = ({ node }: { node: Heading }) => (
);
const ParagraphBlock = ({ node }: { node: Paragraph }) => (
);
const CodeBlock = ({ node }: { node: Code }) => (
);
const QuoteBlock = ({ node }: { node: Blockquote }) => (
);
const ListBlock = ({ node }: { node: List }) => (
{node.children.map((item, index) => (
))}
);
const Block = ({ node }: { node: RootContent }) => {
switch (node.type) {
case "heading":
return ;
case "paragraph":
return ;
case "code":
return ;
case "blockquote":
return ;
case "list":
return ;
case "thematicBreak":
return ;
case "html":
return (
);
default:
return null;
}
};
const Blocks = ({ nodes }: { nodes: RootContent[] }) =>
nodes.map((node, index) => );
const Tags = ({ tags }: { tags: string[] }) => (
{tags.map((tag) => (
))}
);
type MarkdownPreviewProps = {
text: string;
tags?: string[];
onActivateLink?: (uri: string) => boolean;
};
const MarkdownPreview = ({
text,
tags = [],
onActivateLink = () => false,
}: MarkdownPreviewProps) => {
const { t } = useTranslation();
const tree = useMemo(() => fromMarkdown(text), [text]);
return (
{tags.length > 0 && }
);
};
export { MarkdownPreview };
```
`Tags` renders a row of labels with libadwaita's `caption-heading` and `accent` [style classes](https://gnome.pages.gitlab.gnome.org/libadwaita/doc/1-latest/style-classes.html). The `tags` prop is optional and defaults to an empty list, which renders no row.
## Run it
Add front matter to a few notes. Give `Book club.md` a list:
```md
---
tags: [home, reading]
---
# Book club
Next up: *Piranesi* by Susanna Clarke.
```
and put a block with a single tag at the top of `Recipes.md`:
```md
---
tags: home
---
```
The drop-down appears under the search entry. Choose **#home**, and the list narrows to Book club and Recipes. Open Book club and switch to the preview: its tags show above the heading, and the front matter doesn't.
Captured from src/components/notes-screen.tsx and src/preview/markdown-preview.tsx above, with #home chosen and Book club open in the preview.
---
---
description: "Create notes and open dialogs from menus and keyboard shortcuts with GIO actions."
---
# Add Menus and Shortcuts
Add New Note, Keyboard Shortcuts and About as GIO actions, move the preview toggle onto one, and run them from header bar buttons, a main menu and keyboard shortcuts.
## Window actions
A command that a menu item, a button and a key all run is a GIO action: a named command that each of them activates by its name. Declaring it once keeps them in step, so disabling the action greys out its menu item and button and stops its key. `src/components/window-actions.tsx` declares the window's actions as `GSimpleAction` elements:
```tsx [src/components/window-actions.tsx]
import { useToast } from "@gtkx/components";
import * as GLib from "@gtkx/gi/glib";
import { t } from "@gtkx/i18n";
import { GSimpleAction } from "@gtkx/jsx/gio";
import { openNote } from "../navigation.js";
import { useNotes } from "../notes/notes-provider.js";
import type { Dialog } from "./dialogs.js";
const message = (error: unknown): string =>
error instanceof Error ? error.message : String(error);
const useNoteCommands = () => {
const { create } = useNotes();
const { show } = useToast();
const showError = (error: unknown): void => {
show({ useMarkup: false, title: message(error) });
};
const newNote = async (): Promise => {
openNote(await create(t("Untitled"), ""));
};
return {
newNote: () => newNote().catch(showError),
};
};
type WindowActionsProps = {
preview: boolean;
onPreviewChange: (preview: boolean) => void;
onShowDialog: (dialog: Dialog) => void;
};
const WindowActions = ({
preview,
onPreviewChange,
onShowDialog,
}: WindowActionsProps) => {
const { notes } = useNotes();
const { newNote } = useNoteCommands();
return (
<>
void newNote()}
/>
{
if (value !== null) {
onPreviewChange(value.getBoolean());
}
}}
/>
onShowDialog({ kind: "shortcuts" })}
/>
onShowDialog({ kind: "about" })}
/>
>
);
};
export { WindowActions };
```
- The window takes these elements in its `actions` prop, and each becomes an action named `win.` followed by its `name`, such as `win.new-note`. See [Declaring actions](/v2/guide/actions#declaring-actions).
- New Note is `enabled` once the folder has loaded. Until then `notes` is `null`, and everything that runs the action shows it as unavailable.
- Preview is a stateful action. Its state is a boolean `GLib.Variant` made from the window's `preview` state, and `onChangeState` stores the value it is asked to change to. Activating a boolean action that has no `onActivate` requests the opposite state, so the action toggles without one. See [Parameters and state](/v2/guide/actions#parameters-and-state).
- Keyboard Shortcuts and About pass the dialog to show to `onShowDialog`. [Mount the dialogs](#mount-the-dialogs) renders it.
- `useNoteCommands` holds the note commands that actions run, so far New Note. A command that fails shows its error in a toast. `useMarkup: false` shows the message as plain text, since an error message can contain characters such as `<` and `&` that markup would misread.
New Note writes an empty `Untitled.md` and opens it. `createNote`, in `src/notes/files.ts`, tries `Untitled`, then `Untitled 2`, `Untitled 3` and so on:
```ts [src/notes/files.ts]
import * as GLib from "@gtkx/gi/glib";
import { mkdir, readdir, readFile, stat, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { type Note, toNote } from "./note.js";
const EXTENSION = ".md";
const defaultFolder = (): string =>
join(
GLib.getUserSpecialDir(GLib.UserDirectory.DIRECTORY_DOCUMENTS) ??
GLib.getHomeDir(),
"Notes",
);
const noteName = (fileName: string): string | null =>
fileName.endsWith(EXTENSION) && !fileName.startsWith(".")
? fileName.slice(0, -EXTENSION.length)
: null;
const linkedNoteName = (uri: string): string | null => {
const fileName =
GLib.Uri.peekScheme(uri) === null
? GLib.Uri.unescapeString(uri, "/")
: null;
return fileName === null || fileName.includes("/")
? null
: noteName(fileName);
};
const notePath = (folder: string, name: string): string =>
join(folder, `${name}${EXTENSION}`);
const isMissing = (error: unknown): boolean =>
error instanceof Error && "code" in error && error.code === "ENOENT";
const readNote = async (folder: string, name: string): Promise => {
const path = notePath(folder, name);
try {
const info = await stat(path);
if (!info.isFile()) {
return null;
}
return toNote(name, await readFile(path, "utf8"), info.mtimeMs);
} catch (error) {
if (isMissing(error)) {
return null;
}
throw error;
}
};
const readNotes = async (folder: string): Promise => {
await mkdir(folder, { recursive: true });
const names = (await readdir(folder))
.map(noteName)
.filter((name) => name !== null);
const notes = await Promise.all(
names.map((name) => readNote(folder, name)),
);
return notes.filter((note) => note !== null);
};
const writeNote = (folder: string, name: string, text: string): Promise =>
writeFile(notePath(folder, name), text);
const isTaken = (error: unknown): boolean =>
error instanceof Error && "code" in error && error.code === "EEXIST";
const createNote = async (
folder: string,
base: string,
text: string,
): Promise => {
for (let number = 1; ; number++) {
const name = number === 1 ? base : `${base} ${number}`;
try {
await writeFile(notePath(folder, name), text, { flag: "wx" });
return name;
} catch (error) {
if (!isTaken(error)) {
throw error;
}
}
}
};
export {
createNote,
defaultFolder,
linkedNoteName,
noteName,
readNote,
readNotes,
writeNote,
};
```
- The `wx` [flag](https://nodejs.org/api/fs.html#file-system-flags) makes `writeFile` fail with `EEXIST` when the file already exists instead of replacing it, so a new note never overwrites another, even one that another program created a moment before. Checking for the file and then writing it would leave a gap for that to happen.
- `isTaken` recognizes that error and moves on to the next name. Any other error, such as a folder the app can't write to, ends the loop and reaches the toast.
The provider's `create` adds the note to the list at once and tells the saver about the file:
```ts [src/notes/note-saver.ts]
import { writeNote } from "./files.js";
const SAVE_DELAY_MS = 400;
type PendingSave = { text: string; timer: NodeJS.Timeout };
class NoteSaver {
readonly #folder: string;
readonly #onError: (name: string, error: unknown) => void;
readonly #failing = new Set();
readonly #pending = new Map();
readonly #written = new Map();
readonly #writes = new Map>();
constructor(
folder: string,
onError: (name: string, error: unknown) => void,
) {
this.#folder = folder;
this.#onError = onError;
}
schedule(name: string, text: string): void {
clearTimeout(this.#pending.get(name)?.timer);
this.#pending.set(name, {
text,
timer: setTimeout(() => this.#flush(name), SAVE_DELAY_MS),
});
}
flushAll(): void {
for (const name of [...this.#pending.keys()]) {
this.#flush(name);
}
}
isPending(name: string): boolean {
return this.#pending.has(name);
}
isOwnWrite(name: string, text: string): boolean {
return this.#written.get(name) === text;
}
remember(name: string, text: string): void {
this.#written.set(name, text);
}
#flush(name: string): void {
const entry = this.#pending.get(name);
if (entry === undefined) {
return;
}
clearTimeout(entry.timer);
this.#pending.delete(name);
this.#written.set(name, entry.text);
const previous = this.#writes.get(name) ?? Promise.resolve();
const write = previous.then(() => this.#write(name, entry.text));
this.#writes.set(name, write);
}
async #write(name: string, text: string): Promise {
try {
await writeNote(this.#folder, name, text);
this.#failing.delete(name);
} catch (error) {
this.#written.delete(name);
if (!this.#failing.has(name)) {
this.#failing.add(name);
this.#onError(name, error);
}
}
}
}
export { NoteSaver };
```
```tsx [src/notes/notes-provider.tsx]
import { useToast } from "@gtkx/components";
import { t } from "@gtkx/i18n";
import { watch } from "node:fs";
import { createContext, type ReactNode, use, useEffect, useState } from "react";
import { createNote, noteName, readNote, readNotes } from "./files.js";
import { type Note, toNote } from "./note.js";
import { NoteSaver } from "./note-saver.js";
type NoteMap = ReadonlyMap;
type NotesValue = {
folder: string;
notes: NoteMap | null;
create: (name: string, text: string) => Promise;
edit: (name: string, text: string) => void;
};
const NotesContext = createContext(null);
const withNote = (
notes: NoteMap | null,
name: string,
note: Note | null,
): NoteMap => {
const next = new Map(notes);
if (note === null) {
next.delete(name);
} else {
next.set(name, note);
}
return next;
};
const NotesProvider = ({
folder,
children,
}: {
folder: string;
children: ReactNode;
}) => {
const [notes, setNotes] = useState(null);
const { show } = useToast();
const [saver] = useState(
() =>
new NoteSaver(folder, (name) => {
show({
useMarkup: false,
title: t("Couldn’t save “{{name}}”", { name }),
timeout: 0,
});
}),
);
useEffect(() => {
const controller = new AbortController();
const { signal } = controller;
const refresh = async (name: string): Promise => {
const note = await readNote(folder, name);
const isOwnWrite =
note !== null && saver.isOwnWrite(name, note.text);
if (signal.aborted || saver.isPending(name) || isOwnWrite) {
return;
}
setNotes((current) => withNote(current, name, note));
};
const load = async (): Promise => {
const list = await readNotes(folder);
watch(folder, { signal }, (_event, fileName) => {
const name = fileName === null ? null : noteName(fileName);
if (name !== null) {
void refresh(name);
}
});
if (!signal.aborted) {
setNotes(new Map(list.map((note) => [note.name, note])));
}
};
void load();
return () => {
controller.abort();
saver.flushAll();
};
}, [folder, saver]);
const create = async (base: string, text: string): Promise => {
const name = await createNote(folder, base, text);
saver.remember(name, text);
setNotes((current) =>
withNote(current, name, toNote(name, text, Date.now())),
);
return name;
};
const edit = (name: string, text: string): void => {
saver.schedule(name, text);
setNotes((current) =>
withNote(current, name, toNote(name, text, Date.now())),
);
};
return (
{children}
);
};
const useNotes = (): NotesValue => {
const value = use(NotesContext);
if (value === null) {
throw new Error("NotesProvider is required");
}
return value;
};
export { NotesProvider, useNotes };
```
- Writing the file fires the folder watcher from [Watch the folder](/v2/tutorial/saving-and-watching#watch-the-folder). `remember` records the text as the app's own write, so the watcher skips the event, as it skips the saver's own saves.
- `create` returns the name it used, which can differ from the one it was given.
An action runs outside any screen, so it has no screen's `navigation` prop to open the note with. `src/navigation.ts` creates a navigation container ref, which the window passes to `NavigationContainer` below, and `openNote` navigates through it:
```ts [src/navigation.ts]
import {
createNavigationContainerRef,
createSplitViewNavigator,
useNavigationState,
} from "@gtkx/navigation";
type RootParamList = {
Notes: undefined;
Note: { name: string };
};
const Split = createSplitViewNavigator();
const navigationRef = createNavigationContainerRef();
type RootNavigatorType = typeof Split;
declare module "@react-navigation/core" {
interface RootNavigator extends RootNavigatorType {}
}
const useOpenNoteName = (): string | null =>
useNavigationState((state) => {
const route = state.routes.at(-1);
return route?.name === "Note" ? (route.params?.name ?? null) : null;
});
const openNote = (name: string): void => {
navigationRef.navigate("Note", { name });
};
export { navigationRef, openNote, type RootParamList, Split, useOpenNoteName };
```
See React Navigation's [Navigation ref](https://reactnavigation.org/docs/navigation-ref).
## Menus
The main menu sits at the end of the sidebar's header bar. `GMenu` describes it as data, and each item names the action it runs:
```tsx [src/components/main-menu.tsx]
import { t } from "@gtkx/i18n";
import { GMenu } from "@gtkx/jsx/gio";
import { GtkMenuButton } from "@gtkx/jsx/gtk";
const MainMenu = () => (
}
/>
);
export { MainMenu };
```
- `section` groups items between separators. Keyboard Shortcuts and About Notes go in the last group, and Quit stays out of the menu, as the [GNOME HIG](https://developer.gnome.org/hig/patterns/controls/menus.html) asks of a primary menu.
- `primary` makes F10 open the menu.
- An item whose action is disabled is greyed out, so New Note is unavailable while the folder loads. See [Menus](/v2/guide/actions#menus).
The window moves from `src/app.tsx` into `src/components/window.tsx`, and its sidebar header gains a New Note button, the note count and the main menu:
```tsx [src/components/window.tsx]
import { ToastProvider } from "@gtkx/components";
import type * as Adw from "@gtkx/gi/adw";
import { useTranslation } from "@gtkx/i18n";
import {
AdwApplicationWindow,
AdwStatusPage,
AdwToastOverlay,
} from "@gtkx/jsx/adw";
import { GtkButton, GtkToggleButton } from "@gtkx/jsx/gtk";
import { NavigationContainer } from "@gtkx/navigation";
import { quit } from "@gtkx/react";
import { type RefObject, useRef, useState } from "react";
import { navigationRef, Split } from "../navigation.js";
import { defaultFolder } from "../notes/files.js";
import { NotesProvider } from "../notes/notes-provider.js";
import { type Dialog, Dialogs } from "./dialogs.js";
import { MainMenu } from "./main-menu.js";
import { NoteScreen } from "./note-screen.js";
import { NotesScreen, NotesTitle } from "./notes-screen.js";
import { WindowActions } from "./window-actions.js";
const NoteNavigation = ({ preview }: { preview: boolean }) => {
const { t } = useTranslation();
return (
}
>
,
headerStart: (
),
headerEnd: ,
}}
/>
({
title: route.params.name,
headerEnd: (
),
})}
>
{(props) => }
);
};
const NotesWindow = ({
toastOverlayRef,
}: {
toastOverlayRef: RefObject;
}) => {
const { t } = useTranslation();
const [dialog, setDialog] = useState