# 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.
A window titled My App showing Welcome to GTKX!, Count: 0, and a blue Increment button. A window titled My App showing Welcome to GTKX!, Count: 0, and a blue Increment button.
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 ( ); } ```
A window titled Lists, dimmed behind an alert dialog with the heading Rename, the body Pick a new name for this list., an empty List name entry, and Cancel and Rename buttons, Rename highlighted. A window titled Lists, dimmed behind an alert dialog with the heading Rename, the body Pick a new name for this list., an empty List name entry, and Cancel and Rename buttons, Rename highlighted.
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 ( ); } ```
A window titled Notes behind an about dialog headed Notes, with a Details row, a group of Credits, Legal and Acknowledgements rows, and a Calendar row reading Plan your day with an external link icon. A window titled Notes behind an about dialog headed Notes, with a Details row, a group of Credits, Legal and Acknowledgements rows, and a Calendar row reading Plan your day with an external link icon.
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} )} /> ); } ```
A window titled ListView with four task rows; Buy oat milk and Book the dentist are selected. A window titled ListView with four task rows; Buy oat milk and Book the dentist are selected.
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} /> ); } ```
A window titled ColumnView with a table of four employees in Name and Team columns, sorted by name in ascending order. A window titled ColumnView with a table of four employees in Name and Team columns, sorted by name in ascending order.
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} /> ); }; ```
A window titled DropDown with a drop-down button reading Article and its popup open below, listing Book, Article with a check mark, and Podcast. A window titled DropDown with a drop-down button reading Article and its popup open below, listing Book, Article with a check mark, and Podcast.
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) => ( ))} ); } ```
A window titled GtkListBox with a sidebar of four views; Today is selected. A window titled GtkListBox with a sidebar of four views; Today is selected.
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} ))} ); }; ```
A window titled AdwTabView with a tab bar holding a selected Notes tab with a close button and an Ideas tab, above the Notes page. A window titled AdwTabView with a tab bar holding a selected Notes tab with a close button and an Ideas tab, above the Notes page.
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 ( ); } ```
A window titled GtkGrid with a Name label and an Edit button in the first row and a Save button spanning both columns in the second. A window titled GtkGrid with a Name label and an Edit button in the first row and a Save button spanning both columns in the second.
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 source Rendered preview ); }; ```
A window titled GtkStack with a switcher of two buttons, Source selected and Preview, above the text Markdown source. A window titled GtkStack with a switcher of two buttons, Source selected and Preview, above the text Markdown source.
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: }} /> ); ```
The Notes window with its main menu open: a row of linked System, Light and Dark buttons with System selected, a separator, and a Preferences item with Ctrl+,. The Notes window with its main menu open: a row of linked System, Light and Dark buttons with System selected, a separator, and a Preferences item with Ctrl+,.
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 ( ); }; ```
A window titled Toasts with a Show notification button and, at the bottom, a toast reading Task saved with a dismiss button. A window titled Toasts with a Show notification button and, at the bottom, a toast reading Task saved with a dismiss button.
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 ( ); } ```
A window titled CSS with a blue Publish button and a green Save button side by side. A window titled CSS with a blue Publish button and a green Save button side by side.
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 = () => ( ); ```
A window titled CSS with the word Overdue in bold red at its center. A window titled CSS with the word Overdue in bold red at its center.
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}` })} /> ); ```
A window whose header bar shows the title Notes above a centered Open note 42 button. A window whose header bar shows the title Notes above a centered Open note 42 button.
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.
A window whose header bar shows a back button and the title Note 42, above the text Showing note 42 and a Done button. A window whose header bar shows a back button and the title Note 42, above the text Showing note 42 and a Done button.
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, }} /> ); ```
A window titled Inbox showing an Inbox status page, with a switcher bar at the bottom holding an Inbox button with a badge of 3 and an Archived button. A window titled Inbox showing an Inbox status page, with a switcher bar at the bottom holding an Inbox button with a badge of 3 and an Archived button.
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 }) => ( ); ```
A window with a sidebar titled Mail listing Inbox, selected, and Preferences with their icons, beside a content pane whose header has a sidebar toggle and the title Inbox above a No New Mail status page. A window with a sidebar titled Mail listing Inbox, selected, and Preferences with their icons, beside a content pane whose header has a sidebar toggle and the title Inbox above a No New Mail status page.
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 })} /> }} /> ); ```
A window with a sidebar titled Mail holding a selected Inbox row, beside a content pane whose header bar is titled Inbox above a centered Open message 1 button. A window with a sidebar titled Mail holding a selected Inbox row, beside a content pane whose header bar is titled Inbox above a centered Open message 1 button.
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 })} > ); ```
A window titled Documents with a tab bar holding an Untitled tab and a selected Related tab, above a page showing Related and an Open related button. A window titled Documents with a tab bar holding an Untitled tab and a selected Related tab, above a page showing Related and an Open related button.
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.
A window titled Forms with a Preferences group: an empty Display name row outlined in red with the text cursor in it, a Theme row set to Follow system, and a Save button. A window titled Forms with a Preferences group: an empty Display name row outlined in red with the text cursor in it, a Theme row set to Follow system, and a Save button.
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 = () => ( } /> ); ```
The Notes window with its main menu open below the menu button in the sidebar's header bar: New Note with Ctrl+N, a checked Show Preview, a separator, Keyboard Shortcuts with Ctrl+?, and About Notes. The Notes window with its main menu open below the menu button in the sidebar's header bar: New Note with Ctrl+N, a checked Show Preview, a separator, Keyboard Shortcuts with Ctrl+?, and About Notes.
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 = () => ( <> ); ```
A window titled Notes whose header bar starts with a plus icon button and an Open To-do button. A window titled Notes whose header bar starts with a plus icon button and an Open To-do button.
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 }) => ( ); ```
A shortcuts dialog over a window titled Notes, with a search entry and a General group listing New note Ctrl N, Search notes Ctrl F, Keyboard shortcuts Ctrl ?, and Quit Ctrl Q. A shortcuts dialog over a window titled Notes, with a search entry and a General group listing New note Ctrl N, Search notes Ctrl F, Keyboard shortcuts Ctrl ?, and Quit Ctrl Q.
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 scheme 800 Window 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 && } ); }; ```
A window titled Appearance with a System group of two rows: Monospace font, showing the desktop's font name, and Dark style, showing whether the desktop prefers it. A window titled Appearance with a System group of two rows: Monospace font, showing the desktop's font name, and Dark style, showing whether the desktop prefers it.
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 ; } ```
A window titled Greeting showing Hello, Ada! A window titled Greeting showing Hello, Ada!
Captured from the sample above with name set to Ada, in the source language.
A window titled Greeting showing Bonjour, Ada ! A window titled Greeting showing Bonjour, Ada !
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] true Show 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(); }} /> ); } ```
A window titled Cairo filled by a drawing area with a blue circle at its center. A window titled Cairo filled by a drawing area with a blue circle at its center.
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; }} /> ); ```
A window titled OpenGL whose content area is filled with a flat mid gray. A window titled OpenGL whose content area is filled with a flat mid gray.
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 GTKX Storybook window: a sidebar listing the Default and Disabled stories under Components/Button, a preview with a Save button, a Controls group with a label text row and an enabled switch, and an Actions group listing one clicked call. The GTKX Storybook window: a sidebar listing the Default and Disabled stories under Components/Button, a preview with a Save button, a Controls group with a label text row and an enabled switch, and an Actions group listing one clicked call.
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 The Notes app: an Adwaita window with a list of notes on the left and a note rendered as Markdown on the right. The Notes app: an Adwaita window with a list of notes on the left and a note rendered as Markdown on the right. 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.
The Notes window: a header bar titled Notes above a status page with a new-document icon, the title No Notes, and the description Notes are Markdown files in your notes folder. The Notes window: a header bar titled Notes above a status page with a new-document icon, the title No Notes, and the description Notes are Markdown files in your notes folder.
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.
The Notes window listing five notes, newest first: Website relaunch, Meeting notes, Trip to Lisbon, Book club and Recipes, each name above its first line of text in dimmed type. The Notes window listing five notes, newest first: Website relaunch, Meeting notes, Trip to Lisbon, Book club and Recipes, each name above its first line of text in dimmed type.
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.
The Notes window split in two: the sidebar lists five notes with Website relaunch selected, and the content pane, titled Website relaunch, shows its Markdown with highlighted headings, bold text, a link and a numbered list. The Notes window split in two: the sidebar lists five notes with Website relaunch selected, and the content pane, titled Website relaunch, shows its Markdown with highlighted headings, bold text, a link and a numbered list.
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.
The Notes window with Website relaunch open in the editor and a new note, Groceries, at the top of the sidebar list above the five earlier notes. The Notes window with Website relaunch open in the editor and a new note, Groceries, at the top of the sidebar list above the five earlier notes.
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.
The Notes window with Website relaunch shown as a rendered preview: a large title, a paragraph with bold text and a kickoff link, a Milestones heading and a numbered list. The Notes window with Website relaunch shown as a rendered preview: a large title, a paragraph with bold text and a kickoff link, a Milestones heading and a numbered list.
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.
The Notes window at 360 pixels wide, collapsed to one pane: Website relaunch open in the editor under a header bar with a back button. The Notes window at 360 pixels wide, collapsed to one pane: Website relaunch open in the editor under a header bar with a back button.
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.
The Notes window with kickoff typed in the search entry above the sidebar, which lists only Website relaunch and Meeting notes. The Notes window with kickoff typed in the search entry above the sidebar, which lists only Website relaunch and Meeting notes.
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.
The Notes window with #home chosen in the tag drop-down, the sidebar listing Book club and Recipes, and Book club's preview showing #home and #reading above its heading. The Notes window with #home chosen in the tag drop-down, the sidebar listing Book club and Recipes, and Book club's preview showing #home and #reading above its heading.
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({ kind: "none" }); const [preview, setPreview] = useState(false); return ( quit()} actions={ } > setDialog({ kind: "none" })} /> ); }; const Window = () => { const toastOverlayRef = useRef(null); return ( ); }; export { Window }; ``` - `WindowActions` calls `useNotes` and `useToast`, so it must render inside `NotesProvider` and `ToastProvider`. It is a prop of the window, so the providers now wrap the window instead of sitting inside it. `Window` creates the toast overlay's ref for `ToastProvider`, and `NotesWindow` renders the overlay with it. - `NavigationContainer` takes `navigationRef`, which `openNote` navigates through. - The Notes screen's options fill its header bar: `headerTitle` replaces the plain title with `NotesTitle`, `headerStart` adds the New Note button, and `headerEnd` holds the main menu. See [Headers](/v2/guide/navigation#headers). - Both header buttons run actions through `actionName`, and follow them: the New Note button is unavailable while the folder loads, and the toggle button shows the preview action's state. The toggle no longer sets `preview` with `active` and `onNotifyActive`. Clicking it activates `win.preview`, which toggles the state as Ctrl+Shift+P does. See [Buttons](/v2/guide/actions#buttons). - The tooltips name each button's key, since a header bar button has nowhere else to show it. - `NotesWindow` keeps the `preview` state, which `WindowActions` and `NoteNavigation` share, and the `dialog` state for [Mount the dialogs](#mount-the-dialogs). `NotesTitle`, in `src/components/notes-screen.tsx`, shows the note count under the title, and the empty folder's status page gets a New Note button: ```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, AdwWindowTitle } from "@gtkx/jsx/adw"; import { GtkBox, GtkButton, 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 NotesTitle = () => { const { t } = useTranslation(); const { notes } = useNotes(); const subtitle = notes === null ? "" : t("{{count}} note", { count: notes.size, defaultValue_one: "{{count}} note", defaultValue_other: "{{count}} notes", }); return ; }; 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, NotesTitle }; ``` - [`AdwWindowTitle`](https://gnome.pages.gitlab.gnome.org/libadwaita/doc/1-latest/class.WindowTitle.html) shows a title with a subtitle under it. The subtitle stays empty while the folder loads. - `t()` receives the singular and the plural source strings in `defaultValue_one` and `defaultValue_other`, and `count` picks one. [Translate the App](/v2/tutorial/internationalization) translates both. See [Plurals and context](/v2/guide/internationalization#plurals-and-context). - The `pill` and `suggested-action` [style classes](https://gnome.pages.gitlab.gnome.org/libadwaita/doc/1-latest/style-classes.html#pill) give the status page's button its rounded, accent-colored look. ## Keyboard shortcuts `actionAccels` on the application element binds keys to actions by their prefixed names. The application element declares `quit` in its own `actions` prop, so its name is `app.quit`. `src/app.tsx` now holds only the application element: ```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"; function App() { return ( n"] }, { detailedActionName: "win.preview", accels: ["p"], }, { detailedActionName: "win.shortcuts", accels: ["question"], }, { detailedActionName: "app.quit", accels: ["q"] }, ]} actions={ quit()} />} > ); } export { App }; ``` - Ctrl+N, Ctrl+? and Ctrl+Q are the [standard GNOME keys](https://developer.gnome.org/hig/reference/keyboard.html) for New, Keyboard Shortcuts and Quit. `question` is GTK's name for Ctrl+?. - A key for a `win.` action works in every window that has the action. Menus read the same table and show each key beside its item. See [Keyboard accelerators](/v2/guide/actions#keyboard-accelerators). - `quit()` from `@gtkx/react` ends the app, as closing the window does. `src/components/shortcuts.tsx` lists the keys in an `AdwShortcutsDialog`: ```tsx [src/components/shortcuts.tsx] import { t } from "@gtkx/i18n"; import { AdwShortcutsDialog, AdwShortcutsItem, AdwShortcutsSection, } from "@gtkx/jsx/adw"; const Shortcuts = ({ onClose }: { onClose: () => void }) => ( ); export { Shortcuts }; ``` - An item with an `actionName` shows that action's keys from `actionAccels`, so changing a key in `src/app.tsx` updates the dialog too. - Ctrl+F belongs to no action: the `FocusShortcut` controller from [Focus search with Ctrl+F](/v2/tutorial/search-in-a-worker#focus-search-with-ctrl-f) handles it. Its item names the keys with `accelerator`. - The items describe shortcuts and don't register them. See [The shortcuts dialog](/v2/guide/actions#the-shortcuts-dialog). ## Mount the dialogs Which dialog is open is React state. `NotesWindow` keeps a `dialog` value that the Keyboard Shortcuts and About actions set, and `src/components/dialogs.tsx` renders the matching dialog: ```tsx [src/components/dialogs.tsx] import { About } from "./about.js"; import { Shortcuts } from "./shortcuts.js"; type Dialog = { kind: "none" } | { kind: "about" } | { kind: "shortcuts" }; type DialogsProps = { dialog: Dialog; onClose: () => void; }; const Dialogs = ({ dialog, onClose }: DialogsProps) => { switch (dialog.kind) { case "about": { return ; } case "shortcuts": { return ; } case "none": { return null; } } }; export { type Dialog, Dialogs }; ``` ```tsx [src/components/about.tsx] import * as Gtk from "@gtkx/gi/gtk"; import { t } from "@gtkx/i18n"; import { AdwAboutDialog } from "@gtkx/jsx/adw"; const About = ({ onClose }: { onClose: () => void }) => ( ); export { About }; ``` - A dialog presents itself over the window when it mounts and closes when it unmounts. Its close button and Escape call `onClosed`, which sets `dialog` back to `none`. Without `onClosed` the dialog would stay open. See [Dialogs](/v2/guide/modals-and-portals#dialogs). - `Dialog` is a union keyed by `kind`, so a dialog can carry data: [Rename, Trash, and Undo](/v2/tutorial/trash-and-toasts) adds one that carries the name of the note to rename. - The about dialog's name, description and credits go through `t()`; the developer name and copyright stay as written. [`AdwAboutDialog`](https://gnome.pages.gitlab.gnome.org/libadwaita/doc/1-latest/class.AboutDialog.html) lists its other properties, and [About dialog metadata](/v2/guide/modals-and-portals#about-dialog-metadata) covers its credit and legal sections. ## Run it Press Ctrl+N. An Untitled note opens in the editor, and the sidebar title counts one more note. Open the main menu: New Note and Keyboard Shortcuts show their keys. Ctrl+Shift+P switches to the preview and back, and the eye button follows. Ctrl+? opens the shortcuts dialog, and Ctrl+Q quits.
The Notes window with an empty Untitled note open and listed first in the sidebar, the sidebar title reading 6 notes, and the main menu open with New Note (Ctrl+N), Keyboard Shortcuts (Ctrl+?) and About Notes. The Notes window with an empty Untitled note open and listed first in the sidebar, the sidebar title reading 6 notes, and the main menu open with New Note (Ctrl+N), Keyboard Shortcuts (Ctrl+?) and About Notes.
Captured from src/components/window.tsx above, after Ctrl+N and with the main menu open.
--- --- description: "Rename notes in a validating dialog and move them to the trash with an undo toast." --- # Rename, Trash, and Undo Rename the open note in a dialog that checks the new name, and move notes to the desktop trash with an Undo toast. ## Rename a note A note menu joins the preview toggle at the end of the note's header bar. `src/components/note-menu.tsx` holds both buttons, and the menu's items run two new window actions, `win.rename-note` and `win.trash-note`: ```tsx [src/components/note-menu.tsx] import { t } from "@gtkx/i18n"; import { GMenu } from "@gtkx/jsx/gio"; import { GtkMenuButton, GtkToggleButton } from "@gtkx/jsx/gtk"; const PreviewToggle = () => ( ); const NoteMenu = () => ( } /> ); export { NoteMenu, PreviewToggle }; ``` - The main menu's items act on the whole app. The note menu's act on the open note, which makes it what the [GNOME HIG](https://developer.gnome.org/hig/patterns/controls/menus.html#secondary-menus) calls a secondary menu. See [Menus](/v2/guide/actions#menus). - `PreviewToggle` is the toggle button from [Add Menus and Shortcuts](/v2/tutorial/actions-menus-shortcuts#menus), moved out of `src/components/window.tsx` unchanged. F2 renames the open note, and the shortcuts dialog lists the key: ```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"; function App() { return ( n"] }, { detailedActionName: "win.rename-note", accels: ["F2"] }, { detailedActionName: "win.preview", accels: ["p"], }, { detailedActionName: "win.shortcuts", accels: ["question"], }, { detailedActionName: "app.quit", accels: ["q"] }, ]} actions={ quit()} />} > ); } export { App }; ``` ```tsx [src/components/shortcuts.tsx] import { t } from "@gtkx/i18n"; import { AdwShortcutsDialog, AdwShortcutsItem, AdwShortcutsSection, } from "@gtkx/jsx/adw"; const Shortcuts = ({ onClose }: { onClose: () => void }) => ( ); export { Shortcuts }; ``` Both actions need the open note's name and are disabled while no note is open. `useOpenNoteName` from [Select the open note](/v2/tutorial/the-note-editor#select-the-open-note) can't provide it: a hook reads navigation state only inside `NavigationContainer`, and the window that declares the actions sits outside it. `src/navigation.ts` gains functions that read the route through the container ref instead: ```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 openNote = (name: string): void => { navigationRef.navigate("Note", { name }); }; const openNoteName = (): string | null => { const route = navigationRef.isReady() ? navigationRef.getCurrentRoute() : undefined; return route?.name === "Note" ? route.params.name : null; }; const closeNoteIfOpen = (name: string): void => { if (openNoteName() === name) { navigationRef.goBack(); } }; const useOpenNoteName = (): string | null => useNavigationState((state) => { const route = state.routes.at(-1); return route?.name === "Note" ? (route.params?.name ?? null) : null; }); export { closeNoteIfOpen, navigationRef, openNote, openNoteName, type RootParamList, Split, useOpenNoteName, }; ``` - `openNoteName` returns the open note's name, or `null` while the list shows or before the container is ready. See the container's [ref methods](https://reactnavigation.org/docs/navigation-container/#methods-on-the-ref). - `closeNoteIfOpen` goes back to the list when the given note is open. [Move to the trash](#move-to-the-trash) uses it. Reading the ref doesn't re-render anything, so the window keeps the name in state: ```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 } from "@gtkx/jsx/gtk"; import { NavigationContainer } from "@gtkx/navigation"; import { quit } from "@gtkx/react"; import { type RefObject, useRef, useState } from "react"; import { navigationRef, openNoteName, 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 { NoteMenu, PreviewToggle } from "./note-menu.js"; import { NoteScreen } from "./note-screen.js"; import { NotesScreen, NotesTitle } from "./notes-screen.js"; import { useNoteCommands, WindowActions } from "./window-actions.js"; const NoteNavigation = ({ preview, onOpenNameChange, }: { preview: boolean; onOpenNameChange: (name: string | null) => void; }) => { const { t } = useTranslation(); return ( onOpenNameChange(openNoteName())} > } > , headerStart: ( ), headerEnd: , }} /> ({ title: route.params.name, headerEnd: ( <> ), })} > {(props) => } ); }; const NotesWindow = ({ toastOverlayRef, }: { toastOverlayRef: RefObject; }) => { const { t } = useTranslation(); const [dialog, setDialog] = useState({ kind: "none" }); const { renameNote } = useNoteCommands(); const [openName, setOpenName] = useState(null); const [preview, setPreview] = useState(false); return ( quit()} actions={ } > setDialog({ kind: "none" })} onRename={(from, to) => void renameNote(from, to)} /> ); }; const Window = () => { const toastOverlayRef = useRef(null); return ( ); }; export { Window }; ``` - [`onStateChange`](https://reactnavigation.org/docs/navigation-container/#onstatechange) runs after every navigation, and stores `openNoteName()` in `openName`. It doesn't run for the initial state, which is the list, so `openName` starts as `null`. - `WindowActions` receives `openName`, so opening and closing a note enables and disables both actions, and their menu items with them. - The note screen's `headerEnd` holds both buttons from `note-menu.tsx`. - `NotesWindow` calls `useNoteCommands` for `renameNote` and passes it to the dialogs. [Undo from a toast](#undo-from-a-toast) shows the command. Rename shows `RenameDialog`, an `AdwAlertDialog` with an entry for the new name: ```tsx [src/components/rename-dialog.tsx] import * as Adw from "@gtkx/gi/adw"; import { t } from "@gtkx/i18n"; import { AdwAlertDialog } from "@gtkx/jsx/adw"; import { GtkEntry } from "@gtkx/jsx/gtk"; import { useState } from "react"; import { isValidName } from "../notes/files.js"; import { useNotes } from "../notes/notes-provider.js"; type RenameDialogProps = { name: string; onRename: (name: string) => void; onClose: () => void; }; const RenameDialog = ({ name, onRename, onClose }: RenameDialogProps) => { const { notes } = useNotes(); const [draft, setDraft] = useState(name); const canRename = draft !== name && isValidName(draft) && notes?.has(draft) !== true; return ( { if (id === "rename" && canRename) { onRename(draft); } onClose(); }} > { setDraft(self.text); }} /> ); }; export { RenameDialog }; ``` - `draft` holds the entry's text and starts as the current name. `onChanged` updates it on every keystroke. - `canRename` enables the Rename response only for a name that is new, valid and not taken by another note. `isValidName` is in [Move to the trash](#move-to-the-trash). - `defaultResponse` with the entry's `activatesDefault` makes Enter pick Rename, and `closeResponse` makes Escape pick Cancel. Either way `onResponse` runs and calls `onClose`, which unmounts the dialog. See [Dialogs](/v2/guide/modals-and-portals#dialogs). - `SUGGESTED` gives Rename the accent color. [`AdwAlertDialog`](https://gnome.pages.gitlab.gnome.org/libadwaita/doc/1-latest/class.AlertDialog.html) lists the other response appearances. The `Dialog` union gains a `rename` kind that carries the note's name, and `Dialogs` renders `RenameDialog` for it: ```tsx [src/components/dialogs.tsx] import { About } from "./about.js"; import { RenameDialog } from "./rename-dialog.js"; import { Shortcuts } from "./shortcuts.js"; type Dialog = | { kind: "none" } | { kind: "about" } | { kind: "shortcuts" } | { kind: "rename"; name: string }; type DialogsProps = { dialog: Dialog; onClose: () => void; onRename: (from: string, to: string) => void; }; const Dialogs = ({ dialog, onClose, onRename }: DialogsProps) => { switch (dialog.kind) { case "about": { return ; } case "shortcuts": { return ; } case "rename": { return ( onRename(dialog.name, to)} onClose={onClose} /> ); } case "none": { return null; } } }; export { type Dialog, Dialogs }; ``` ## Move to the trash `src/notes/files.ts` gains the file operations: ```ts [src/notes/files.ts] import * as Gio from "@gtkx/gi/gio"; import * as GLib from "@gtkx/gi/glib"; import { access, mkdir, readdir, readFile, rename, 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 exists = async (path: string): Promise => { try { await access(path); return true; } catch (error) { if (isMissing(error)) { return false; } throw error; } }; const renameNote = async ( folder: string, from: string, to: string, ): Promise => { const target = notePath(folder, to); if (await exists(target)) { throw new Error(`${target} already exists`); } await rename(notePath(folder, from), target); }; const trashNote = async (folder: string, name: string): Promise => { await Gio.File.newForPath(notePath(folder, name)).trashAsync( GLib.PRIORITY_DEFAULT, ); }; const isValidName = (name: string): boolean => name.trim() === name && name !== "" && !name.startsWith(".") && !name.includes("/"); 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, isValidName, linkedNoteName, noteName, readNote, readNotes, renameNote, trashNote, writeNote, }; ``` - Node's [`rename`](https://nodejs.org/api/fs.html#fspromisesrenameoldpath-newpath) replaces a file that already has the new name, so `renameNote` checks for one first and fails instead. Unlike the `wx` flag in [Window actions](/v2/tutorial/actions-menus-shortcuts#window-actions), the check and the rename are separate steps: a file that another program creates between them is still replaced. Node has no rename that refuses to replace. - `trashNote` moves the file to the desktop trash with [`Gio.File.trashAsync`](https://docs.gtk.org/gio/method.File.trash_async.html), so a mistaken trash can also be undone from the Trash in Files. GTKX turns GIO's async and finish pair into one method that returns a promise and rejects on failure. See [Async Operations](/v2/guide/async-operations). - `isValidName` rejects an empty name, a name with whitespace at either end, a `/`, which would point into another folder, and a leading `.`, which hides the file from the note list. The provider's `rename` and `trash` run these operations and update the list. The saver gains two methods for them: ```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), }); } async settle(name: string): Promise { this.#flush(name); await this.#writes.get(name); } 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); } forget(name: string): void { this.#written.delete(name); this.#failing.delete(name); } #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, renameNote, trashNote, } 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; rename: (from: string, to: string) => Promise; trash: (name: string) => Promise; }; 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())), ); }; const rename = async (from: string, to: string): Promise => { await saver.settle(from); await renameNote(folder, from, to); saver.forget(from); setNotes((current) => { const note = current?.get(from); const next = withNote(current, from, null); return note === undefined ? next : withNote(next, to, { ...note, name: to }); }); }; const trash = async (name: string): Promise => { await saver.settle(name); await trashNote(folder, name); saver.forget(name); setNotes((current) => withNote(current, name, null)); }; return ( {children} ); }; const useNotes = (): NotesValue => { const value = use(NotesContext); if (value === null) { throw new Error("NotesProvider is required"); } return value; }; export { NotesProvider, useNotes }; ``` - `settle` writes the note's pending save now and waits for it. Without it, a save still waiting out its delay from [Save and Watch Files](/v2/tutorial/saving-and-watching) would write the old name after the rename or trash and bring the file back. - `forget` drops what the saver knows about the old name: the text it last wrote and whether its saves are failing. Otherwise a note restored from the Trash in Files would match that text, and the watcher would skip it as the app's own write. - `rename` moves the note to its new key in the list and keeps its text and modification time. ## Undo from a toast `useNoteCommands` gains the commands that the dialog and the actions run: ```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 { closeNoteIfOpen, 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 { notes, create, rename, trash } = useNotes(); const { show } = useToast(); const showError = (error: unknown): void => { show({ useMarkup: false, title: message(error) }); }; const newNote = async (): Promise => { openNote(await create(t("Untitled"), "")); }; const renameNote = async (from: string, to: string): Promise => { await rename(from, to); openNote(to); }; const trashNote = async (name: string): Promise => { const text = notes?.get(name)?.text ?? ""; closeNoteIfOpen(name); await trash(name); show({ useMarkup: false, title: t("“{{name}}” moved to Trash", { name }), buttonLabel: t("Undo"), onButtonClicked: () => { create(name, text).then(openNote, showError); }, }); }; return { newNote: () => newNote().catch(showError), renameNote: (from: string, to: string) => renameNote(from, to).catch(showError), trashNote: (name: string) => trashNote(name).catch(showError), }; }; type WindowActionsProps = { openName: string | null; preview: boolean; onPreviewChange: (preview: boolean) => void; onShowDialog: (dialog: Dialog) => void; }; const WindowActions = ({ openName, preview, onPreviewChange, onShowDialog, }: WindowActionsProps) => { const { notes } = useNotes(); const { newNote, trashNote } = useNoteCommands(); return ( <> void newNote()} /> { if (openName !== null) { onShowDialog({ kind: "rename", name: openName }); } }} /> { if (openName !== null) { void trashNote(openName); } }} /> { if (value !== null) { onPreviewChange(value.getBoolean()); } }} /> onShowDialog({ kind: "shortcuts" })} /> onShowDialog({ kind: "about" })} /> ); }; export { useNoteCommands, WindowActions }; ``` - `renameNote` opens the note under its new name once the file is renamed. A failure, such as a name another program took after the dialog checked it, shows in a toast. - The `trashNote` command keeps the note's text, closes the note if it is open, so the editor can't save into a file that is gone, and moves the file to the trash. - The toast that follows has an Undo button, the [GNOME HIG](https://developer.gnome.org/hig/patterns/feedback/toasts.html)'s common use for a toast after a destructive action. See [Toasts](/v2/guide/components#toasts). - Undo writes the kept text back with `create` and opens the note. GIO doesn't say where in the trash the file went, so Undo makes a new file rather than restoring the old one, which stays in the trash. The new file has a new modification time, so the note returns at the top of the list. If another note took the name in the meantime, `create` picks the next free one, and `openNote` opens whichever name it used. - `useMarkup: false` shows the note's name as plain text, as for the error toasts. ## Run it Open a note and press F2. Rename stays disabled until the name is new, valid and unused, and Enter renames the note. Open the note menu and choose Move to Trash: the note leaves the list, the sidebar title counts one fewer note, and a toast offers Undo. Click Undo and the note comes back and opens.
The Notes window after Recipes was moved to the trash: the sidebar lists four notes, the content pane reads No Note Selected, and a toast at the bottom reads “Recipes” moved to Trash with an Undo button. The Notes window after Recipes was moved to the trash: the sidebar lists four notes, the content pane reads No Note Selected, and a toast at the bottom reads “Recipes” moved to Trash with an Undo button.
Captured from src/components/window-actions.tsx above, after Move to Trash on Recipes.
--- --- description: "Store the notes folder, color scheme, preview state and window size in GSettings and edit them in a preferences dialog." --- # Add Preferences Keep the notes folder, color scheme, preview state and window size in GSettings so they survive a restart, and edit the folder and color scheme in a preferences dialog. ## A settings schema GSettings stores each preference under a key, and a schema declares each key's type and default. A new file, `data/dev.gtkx.Notes.gschema.xml`, declares the app's keys: ```xml [data/dev.gtkx.Notes.gschema.xml] '' Notes folder Folder that holds the notes, or empty for Notes in the Documents folder 'default' Color scheme Whether the app follows the system style or forces light or dark false Show the preview Whether notes open as rendered Markdown instead of in the editor 960 Window width 640 Window height ``` - The schema ID is the application ID, and `path` is the same ID written as a path. See [Your app's schema](/v2/guide/native-state#your-app-s-schema). - An empty `folder` means `Notes` in the Documents folder, the default from [List the Notes](/v2/tutorial/the-notes-folder). - `color-scheme` is a string limited to its ``. `default` follows the system style. - `gettext-domain` names the catalog that translates the summaries and descriptions. See [Translate settings schemas](/v2/guide/internationalization#translate-settings-schemas). A module that imports the schema is enough for GTKX to compile it and type its keys. `src/settings.tsx` imports it and shares one `Gio.Settings` instance with the app: ```tsx [src/settings.tsx] import * as Adw from "@gtkx/gi/adw"; import type * as Gio from "@gtkx/gi/gio"; import { t } from "@gtkx/i18n"; import { GSettings } from "@gtkx/jsx/gio"; import { createPortal, rootElement } from "@gtkx/react"; import { createContext, type ReactNode, use, useState } from "react"; import schema from "../data/dev.gtkx.Notes.gschema.xml"; type ColorScheme = (typeof schema.values)["color-scheme"][number]; const COLOR_SCHEMES: Record< ColorScheme, { label: () => string; value: Adw.ColorScheme } > = { default: { label: () => t("Follow System"), value: Adw.ColorScheme.DEFAULT, }, light: { label: () => t("Light"), value: Adw.ColorScheme.FORCE_LIGHT }, dark: { label: () => t("Dark"), value: Adw.ColorScheme.FORCE_DARK }, }; const colorSchemeItems = (): { id: ColorScheme; value: string }[] => schema.values["color-scheme"].map((id) => ({ id, value: COLOR_SCHEMES[id].label(), })); const toColorScheme = (id: string | null): ColorScheme | undefined => schema.values["color-scheme"].find((scheme) => scheme === id); const SettingsContext = createContext(null); const SettingsProvider = ({ children }: { children: ReactNode }) => { const [settings, setSettings] = useState(null); return ( <> {createPortal( , rootElement, )} {settings !== null && ( {children} )} ); }; const useAppSettings = (): Gio.Settings => { const settings = use(SettingsContext); if (settings === null) { throw new Error("SettingsProvider is required"); } return settings; }; export { COLOR_SCHEMES, type ColorScheme, colorSchemeItems, schema, SettingsProvider, toColorScheme, useAppSettings, }; ``` - `SettingsProvider` renders a `GSettings` element through a portal, keeps the instance in state, and renders its children once the instance exists, so `useAppSettings` always returns one. [The settings instance](/v2/guide/native-state#the-settings-instance) explains the pattern. - `schema.values["color-scheme"]` lists the key's choices, so `ColorScheme` is `"default" | "light" | "dark"`. - `COLOR_SCHEMES` gives each choice a label and its [`Adw.ColorScheme`](https://gnome.pages.gitlab.gnome.org/libadwaita/doc/1-latest/enum.ColorScheme.html). As a `Record`, it fails to typecheck if the schema gains a choice without an entry. Each label is a function, so `t` translates it when the dialog renders. - `colorSchemeItems` builds the items of the dialog's Style row, and `toColorScheme` turns the row's selected ID back into a choice, or `undefined` for any other string. `SettingsProvider` wraps the window in `src/app.tsx`. Ctrl+, runs the `win.preferences` action from [The preferences dialog](#the-preferences-dialog), the [GNOME HIG](https://developer.gnome.org/hig/reference/keyboard.html)'s shortcut for Preferences: ```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"; import { SettingsProvider } from "./settings.js"; function App() { return ( n"] }, { detailedActionName: "win.rename-note", accels: ["F2"] }, { detailedActionName: "win.preview", accels: ["p"], }, { detailedActionName: "win.preferences", accels: ["comma"], }, { detailedActionName: "win.shortcuts", accels: ["question"], }, { detailedActionName: "app.quit", accels: ["q"] }, ]} actions={ quit()} />} > ); } export { App }; ``` ## Read and bind settings The window reads the folder and color scheme, and saves its size: ```tsx [src/components/window.tsx] import { ToastProvider } from "@gtkx/components"; import * as Adw from "@gtkx/gi/adw"; import { useTranslation } from "@gtkx/i18n"; import { AdwApplicationWindow, AdwStatusPage, AdwToastOverlay, } from "@gtkx/jsx/adw"; import { GtkButton } from "@gtkx/jsx/gtk"; import { NavigationContainer } from "@gtkx/navigation"; import { quit, useBindSetting, useSetting } from "@gtkx/react"; import { type RefObject, useEffect, useRef, useState } from "react"; import { navigationRef, openNoteName, Split } from "../navigation.js"; import { defaultFolder } from "../notes/files.js"; import { NotesProvider } from "../notes/notes-provider.js"; import { COLOR_SCHEMES, schema, useAppSettings } from "../settings.js"; import { type Dialog, Dialogs } from "./dialogs.js"; import { MainMenu } from "./main-menu.js"; import { NoteMenu, PreviewToggle } from "./note-menu.js"; import { NoteScreen } from "./note-screen.js"; import { NotesScreen, NotesTitle } from "./notes-screen.js"; import { useNoteCommands, WindowActions } from "./window-actions.js"; const NoteNavigation = ({ onOpenNameChange, }: { onOpenNameChange: (name: string | null) => void; }) => { const { t } = useTranslation(); return ( onOpenNameChange(openNoteName())} > } > , headerStart: ( ), headerEnd: , }} /> ({ title: route.params.name, headerEnd: ( <> ), })} /> ); }; const NotesWindow = ({ toastOverlayRef, }: { toastOverlayRef: RefObject; }) => { const { t } = useTranslation(); const settings = useAppSettings(); const { renameNote, showError } = useNoteCommands(); const [window, setWindow] = useState(null); const [dialog, setDialog] = useState({ kind: "none" }); const [openName, setOpenName] = useState(null); useBindSetting({ settings, schema, key: "window-width", object: window, property: "defaultWidth", }); useBindSetting({ settings, schema, key: "window-height", object: window, property: "defaultHeight", }); return ( quit()} actions={ } > setDialog({ kind: "none" })} onRename={(from, to) => void renameNote(from, to)} onError={showError} /> ); }; const Window = () => { const settings = useAppSettings(); const [folderSetting] = useSetting(settings, schema, "folder"); const [colorScheme] = useSetting(settings, schema, "color-scheme"); const toastOverlayRef = useRef(null); const folder = folderSetting === "" ? defaultFolder() : folderSetting; useEffect(() => { Adw.StyleManager.getDefault().setColorScheme( COLOR_SCHEMES[colorScheme].value, ); }, [colorScheme]); useEffect(() => { if (openNoteName() !== null) { navigationRef.goBack(); } }, [folder]); return ( ); }; export { Window }; ``` - `Window` reads `folder` and `color-scheme` with `useSetting`, which re-renders when a key changes. See [Reading and writing a key](/v2/guide/native-state#reading-and-writing-a-key). - The first effect applies the color scheme with [`Adw.StyleManager`](https://gnome.pages.gitlab.gnome.org/libadwaita/doc/1-latest/property.StyleManager.color-scheme.html). Every Adwaita widget follows it, and so do media queries in the app's own styles. See [Follow appearance preferences](/v2/guide/css#follow-appearance-preferences). - The second effect closes the open note when the folder changes, because the note belongs to the old folder. - The `useBindSetting` calls keep `window-width` and `window-height` in step with the window's `defaultWidth` and `defaultHeight`, which GTK updates as the window is resized. They replace the fixed 720 by 480 from [Two screens in a split view](/v2/tutorial/the-note-editor#two-screens-in-a-split-view): the window opens at the size it had when it closed, and at 960 by 640 the first time. GNOME's [Saving and Loading Window State](https://developer.gnome.org/documentation/tutorials/save-state.html) describes the same bind. See [Binding a key to a property](/v2/guide/native-state#binding-a-key-to-a-property). - The `ref` stores the window in state, so the binds wait until it exists. - `Dialogs` receives `showError` from `useNoteCommands`, for the folder errors in [The preferences dialog](#the-preferences-dialog). `NotesProvider` now receives a folder that can change. It switches to the new folder in place, so the window and the Preferences dialog stay open: ```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, renameNote, trashNote, } 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; rename: (from: string, to: string) => Promise; trash: (name: string) => Promise; }; 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 createSaver = (): NoteSaver => new NoteSaver(folder, (name) => { show({ useMarkup: false, title: t("Couldn’t save “{{name}}”", { name }), timeout: 0, }); }); const [saver, setSaver] = useState(createSaver); const [saverFolder, setSaverFolder] = useState(folder); if (saverFolder !== folder) { setSaverFolder(folder); setSaver(createSaver()); setNotes(null); } 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())), ); }; const rename = async (from: string, to: string): Promise => { await saver.settle(from); await renameNote(folder, from, to); saver.forget(from); setNotes((current) => { const note = current?.get(from); const next = withNote(current, from, null); return note === undefined ? next : withNote(next, to, { ...note, name: to }); }); }; const trash = async (name: string): Promise => { await saver.settle(name); await trashNote(folder, name); saver.forget(name); setNotes((current) => withNote(current, name, null)); }; return ( {children} ); }; const useNotes = (): NotesValue => { const value = use(NotesContext); if (value === null) { throw new Error("NotesProvider is required"); } return value; }; export { NotesProvider, useNotes }; ``` - The saver writes to the folder it was created with, so `NotesProvider` keeps the folder of its current saver. When the `folder` prop differs, it creates a saver for the new folder and clears the list during the render, as React's [Adjusting some state when a prop changes](https://react.dev/learn/you-might-not-need-an-effect#adjusting-some-state-when-a-prop-changes) shows. - The effect depends on `folder` and `saver`, so its cleanup stops watching the old folder and writes the old saver's pending edits to the old folder. The effect then reads and watches the new folder. The preview state moves from the window to the `preview` key, so a note opens the way the last one was shown, even after a restart. `NoteScreen` and the `preview` action read the key with `useSetting`: ```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 { useSetting } from "@gtkx/react"; 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"; import { schema, useAppSettings } from "../settings.js"; type NoteScreenProps = SplitViewScreenProps; const NoteScreen = ({ route, navigation }: NoteScreenProps) => { const { t } = useTranslation(); const { notes, edit } = useNotes(); const [preview] = useSetting(useAppSettings(), schema, "preview"); 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 }; ``` ```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 { useSetting } from "@gtkx/react"; import { closeNoteIfOpen, openNote } from "../navigation.js"; import { useNotes } from "../notes/notes-provider.js"; import { schema, useAppSettings } from "../settings.js"; import type { Dialog } from "./dialogs.js"; const message = (error: unknown): string => error instanceof Error ? error.message : String(error); const useNoteCommands = () => { const { notes, create, rename, trash } = useNotes(); const { show } = useToast(); const showError = (error: unknown): void => { show({ useMarkup: false, title: message(error) }); }; const newNote = async (): Promise => { openNote(await create(t("Untitled"), "")); }; const renameNote = async (from: string, to: string): Promise => { await rename(from, to); openNote(to); }; const trashNote = async (name: string): Promise => { const text = notes?.get(name)?.text ?? ""; closeNoteIfOpen(name); await trash(name); show({ useMarkup: false, title: t("“{{name}}” moved to Trash", { name }), buttonLabel: t("Undo"), onButtonClicked: () => { create(name, text).then(openNote, showError); }, }); }; return { newNote: () => newNote().catch(showError), renameNote: (from: string, to: string) => renameNote(from, to).catch(showError), trashNote: (name: string) => trashNote(name).catch(showError), showError, }; }; type WindowActionsProps = { openName: string | null; onShowDialog: (dialog: Dialog) => void; }; const WindowActions = ({ openName, onShowDialog }: WindowActionsProps) => { const { notes } = useNotes(); const { newNote, trashNote } = useNoteCommands(); const [preview, setPreview] = useSetting( useAppSettings(), schema, "preview", ); return ( <> void newNote()} /> { if (openName !== null) { onShowDialog({ kind: "rename", name: openName }); } }} /> { if (openName !== null) { void trashNote(openName); } }} /> { if (value !== null) { setPreview(value.getBoolean()); } }} /> onShowDialog({ kind: "preferences" })} /> onShowDialog({ kind: "shortcuts" })} /> onShowDialog({ kind: "about" })} /> ); }; export { useNoteCommands, WindowActions }; ``` - `onChangeState` writes the key instead of the window's state, and the toggle button follows the action as before. - With no state left to pass down, `NoteScreen` becomes the screen's `component` instead of a render callback, which keeps the optimizations that React Navigation [drops for render callbacks](https://reactnavigation.org/docs/hello-react-navigation/#passing-additional-data). - `useNoteCommands` returns `showError` along with the commands. ## The preferences dialog The `win.preferences` action shows the preferences dialog. The main menu and the shortcuts dialog list it: ```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 }; ``` ```tsx [src/components/shortcuts.tsx] import { t } from "@gtkx/i18n"; import { AdwShortcutsDialog, AdwShortcutsItem, AdwShortcutsSection, } from "@gtkx/jsx/adw"; const Shortcuts = ({ onClose }: { onClose: () => void }) => ( ); export { Shortcuts }; ``` The `Dialog` union gains a `preferences` kind, and `Dialogs` passes the window's `onError` to the dialog: ```tsx [src/components/dialogs.tsx] import { About } from "./about.js"; import { Preferences } from "./preferences.js"; import { RenameDialog } from "./rename-dialog.js"; import { Shortcuts } from "./shortcuts.js"; type Dialog = | { kind: "none" } | { kind: "about" } | { kind: "shortcuts" } | { kind: "preferences" } | { kind: "rename"; name: string }; type DialogsProps = { dialog: Dialog; onClose: () => void; onRename: (from: string, to: string) => void; onError: (error: unknown) => void; }; const Dialogs = ({ dialog, onClose, onRename, onError }: DialogsProps) => { switch (dialog.kind) { case "about": { return ; } case "shortcuts": { return ; } case "preferences": { return ; } case "rename": { return ( onRename(dialog.name, to)} onClose={onClose} /> ); } case "none": { return null; } } }; export { type Dialog, Dialogs }; ``` `src/components/preferences.tsx` holds the dialog: ```tsx [src/components/preferences.tsx] import { ComboRow } from "@gtkx/components"; import type * as Gio from "@gtkx/gi/gio"; import * as Gtk from "@gtkx/gi/gtk"; import { t } from "@gtkx/i18n"; import { AdwActionRow, AdwPreferencesDialog, AdwPreferencesGroup, AdwPreferencesPage, } from "@gtkx/jsx/adw"; import { GtkButton, GtkFileDialog } from "@gtkx/jsx/gtk"; import { createPortal, rootElement, useParentWindow, useSetting, } from "@gtkx/react"; import { useState } from "react"; import { defaultFolder, displayFolder } from "../notes/files.js"; import { colorSchemeItems, schema, toColorScheme, useAppSettings, } from "../settings.js"; const isDismissal = (error: unknown): boolean => error instanceof Gtk.DialogError && (error.code === Gtk.DialogError.DISMISSED || error.code === Gtk.DialogError.CANCELLED); const FolderRow = ({ onError }: { onError: (error: unknown) => void }) => { const settings = useAppSettings(); const parentWindow = useParentWindow(); const [folder, setFolder] = useSetting(settings, schema, "folder"); const [dialog, setDialog] = useState(null); const choose = async (fileDialog: Gtk.FileDialog): Promise => { let file: Gio.File; try { file = await fileDialog.selectFolder(parentWindow); } catch (error) { if (!isDismissal(error)) { onError(error); } return; } const path = file.getPath(); if (path !== null) { setFolder(path); } }; return ( <> {createPortal( , rootElement, )} {folder !== "" && ( setFolder("")} /> )} { if (dialog !== null) { void choose(dialog); } }} /> } /> ); }; type PreferencesProps = { onClose: () => void; onError: (error: unknown) => void; }; const Preferences = ({ onClose, onError }: PreferencesProps) => { const settings = useAppSettings(); const [colorScheme, setColorScheme] = useSetting( settings, schema, "color-scheme", ); return ( { const scheme = toColorScheme(id); if (scheme !== undefined) { setColorScheme(scheme); } }} /> ); }; export { Preferences }; ``` - [`AdwPreferencesDialog`](https://gnome.pages.gitlab.gnome.org/libadwaita/doc/1-latest/class.PreferencesDialog.html) holds pages of grouped rows. Notes has one page, with an Appearance group and a Storage group. `onClosed` clears the dialog state, as for the other dialogs. See [Dialogs](/v2/guide/modals-and-portals#dialogs). - `ComboRow` from `@gtkx/components` renders the Style row. `selectedId` shows the key's value, and `onSelectionChanged` writes the chosen one, which the window's effect then applies. The ID arrives as `string | null`, and `toColorScheme` checks it against the schema's choices without a cast. See [DropDown](/v2/guide/components#dropdown). - `FolderRow` keeps a `GtkFileDialog` in state through a portal and awaits its `selectFolder`, as [Awaiting async operations](/v2/guide/async-operations#awaiting-async-operations) shows. `useParentWindow` returns the Notes window, so the file dialog opens over it. See [Finding the parent window](/v2/guide/modals-and-portals#finding-the-parent-window). - Closing the file dialog rejects with `Gtk.DialogError.DISMISSED`, which `isDismissal` ignores. Other failures reach the window's error toast through `onError`. A folder without a local path, for which `getPath` returns `null`, is ignored. - Once a folder is chosen, a second button sets the key back to empty, which returns to the default folder. - The row's subtitle shows the folder in use. `displayFolder`, a new function in `src/notes/files.ts`, writes the home folder as `~`: ```ts [src/notes/files.ts] import * as Gio from "@gtkx/gi/gio"; import * as GLib from "@gtkx/gi/glib"; import { access, mkdir, readdir, readFile, rename, 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 displayFolder = (path: string): string => { const home = GLib.getHomeDir(); return path.startsWith(`${home}/`) ? `~${path.slice(home.length)}` : path; }; 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 exists = async (path: string): Promise => { try { await access(path); return true; } catch (error) { if (isMissing(error)) { return false; } throw error; } }; const renameNote = async ( folder: string, from: string, to: string, ): Promise => { const target = notePath(folder, to); if (await exists(target)) { throw new Error(`${target} already exists`); } await rename(notePath(folder, from), target); }; const trashNote = async (folder: string, name: string): Promise => { await Gio.File.newForPath(notePath(folder, name)).trashAsync( GLib.PRIORITY_DEFAULT, ); }; const isValidName = (name: string): boolean => name.trim() === name && name !== "" && !name.startsWith(".") && !name.includes("/"); 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, displayFolder, isValidName, linkedNoteName, noteName, readNote, readNotes, renameNote, trashNote, writeNote, }; ``` ## Run it Open Preferences with Ctrl+, and choose Dark: the window turns dark at once. Choose another notes folder: the list shows that folder's notes, and Preferences stays open. Toggle the preview, resize the window and quit. The app opens again with the same style, folder, preview state and size.
The Notes window with the Preferences dialog open: an Appearance group with a Style row set to Light, and a Storage group with a Notes Folder row showing ~/Notes and a folder button. The Notes window with the Preferences dialog open: an Appearance group with a Style row set to Dark, and a Storage group with a Notes Folder row showing ~/Notes and a folder button.
Captured from src/components/preferences.tsx above, opened from the main menu.
--- --- description: "Implement a GtkSourceView completion provider in TypeScript to suggest links to other notes." --- # Complete Note Links Type `[[` in the editor to pick another note from a popup and insert a Markdown link to it. GtkSourceView shows the popup and handles the keyboard; the app supplies the suggestions from a TypeScript class that implements a GtkSourceView interface. ## Implement a GObject interface GtkSourceView asks completion providers for suggestions, called proposals. A provider is a GObject that implements the [`GtkSource.CompletionProvider`](https://gnome.pages.gitlab.gnome.org/gtksourceview/gtksourceview5/iface.CompletionProvider.html) interface, and each proposal is a GObject that implements [`GtkSource.CompletionProposal`](https://gnome.pages.gitlab.gnome.org/gtksourceview/gtksourceview5/iface.CompletionProposal.html). A new file, `src/editor/note-link-provider.ts`, defines both: ```ts [src/editor/note-link-provider.ts] import * as Gio from "@gtkx/gi/gio"; import * as GObject from "@gtkx/gi/gobject"; import type * as Gtk from "@gtkx/gi/gtk"; import * as GtkSource from "@gtkx/gi/gtksource"; import { registerClass } from "@gtkx/runtime"; const OPEN = "[["; class NoteLinkProposalBase extends GObject.Object implements GtkSource.CompletionProposalImpl { name = ""; vfuncGetTypedText(): string { return this.name; } } const NoteLinkProposal = registerClass(NoteLinkProposalBase, { typeName: "NotesNoteLinkProposal", implements: [GtkSource.CompletionProposal], }); type NoteLinkProposal = InstanceType; const openLinkAt = ( iter: Gtk.TextIter, ): { start: Gtk.TextIter; query: string } | null => { const start = iter.copy(); start.setLineOffset(0); const before = start.getText(iter); const open = before.lastIndexOf(OPEN); const query = before.slice(open + OPEN.length); if (open === -1 || query.includes("]")) { return null; } start.forwardChars([...before.slice(0, open)].length); return { start, query }; }; const escape = (text: string, special: RegExp): string => text.replace(special, "\\$&"); const markdownLink = (name: string): string => `[${escape(name, /[\\[\]]/g)}](<${escape(`${name}.md`, /[\\<>]/g)}>)`; const proposals = ( names: readonly string[], context: GtkSource.CompletionContext, ): NoteLinkProposal[] => { const [, , end] = context.getBounds(); const query = openLinkAt(end)?.query.toLocaleLowerCase(); if (query === undefined) { return []; } const rank = (name: string): number => name.toLocaleLowerCase().startsWith(query) ? 0 : 1; return names .filter((name) => name.toLocaleLowerCase().includes(query)) .toSorted((a, b) => rank(a) - rank(b) || a.localeCompare(b)) .map((name) => { const proposal = new NoteLinkProposal(); proposal.name = name; return proposal; }); }; class NoteLinkProviderBase extends GObject.Object implements GtkSource.CompletionProviderImpl { noteNames: () => readonly string[] = () => []; vfuncIsTrigger(iter: Gtk.TextIter, ch: string): boolean { return ch === "[" && openLinkAt(iter)?.query === ""; } vfuncPopulateAsync( context: GtkSource.CompletionContext, cancellable: Gio.Cancellable | null, callback: Gio.AsyncReadyCallback | null, ): void { const model = Gio.ListStore.new(NoteLinkProposal); model.splice(0, 0, proposals(this.noteNames(), context)); const value = new GObject.Value(); value.init(Gio.ListStore); value.setObject(model); Gio.Task.new(this, cancellable, callback).returnValue(value); } vfuncPopulateFinish(result: Gio.AsyncResult): Gio.ListModel { const [, model] = result instanceof Gio.Task ? result.propagateValue() : [false, null]; if (!(model instanceof Gio.ListStore)) { throw new Error("Completion task returned no model"); } return model; } vfuncRefilter( context: GtkSource.CompletionContext, model: Gio.ListModel, ): void { if (model instanceof Gio.ListStore) { model.splice( 0, model.getNItems(), proposals(this.noteNames(), context), ); } } vfuncDisplay( _context: GtkSource.CompletionContext, proposal: GtkSource.CompletionProposal, cell: GtkSource.CompletionCell, ): void { if (!(proposal instanceof NoteLinkProposal)) { return; } switch (cell.getColumn()) { case GtkSource.CompletionColumn.ICON: cell.setIconName("text-x-generic-symbolic"); break; case GtkSource.CompletionColumn.TYPED_TEXT: cell.setText(proposal.name); break; } } vfuncActivate( context: GtkSource.CompletionContext, proposal: GtkSource.CompletionProposal, ): void { const buffer = context.getBuffer(); const [, , end] = context.getBounds(); const link = openLinkAt(end); if ( buffer === null || link === null || !(proposal instanceof NoteLinkProposal) ) { return; } buffer.beginUserAction(); buffer.delete(link.start, end); buffer.insert(link.start, markdownLink(proposal.name), -1); buffer.endUserAction(); } } const NoteLinkProvider = registerClass(NoteLinkProviderBase, { typeName: "NotesNoteLinkProvider", implements: [GtkSource.CompletionProvider], }); type NoteLinkProvider = InstanceType; export { NoteLinkProvider }; ``` - `registerClass` registers each class as a native GObject type, with the interface in `implements`. Each interface method is a `vfunc` method on the class, and the generated `Impl` type, such as `GtkSource.CompletionProviderImpl`, checks its signature. See [Implementing an interface](/v2/guide/subclassing#implementing-an-interface). - `NoteLinkProposal` holds one note name in a plain field, and `vfuncGetTypedText` returns it as the proposal's text. - `NoteLinkProvider` reads the names to offer from its `noteNames` function, which the editor replaces in [Attach it to the editor](#attach-it-to-the-editor). ## Offer note names GtkSourceView calls `vfuncIsTrigger` when you type a character that can't be part of a word, such as `[`, and the provider opens the popup when that character is the second `[` of `[[`. `openLinkAt` finds the last `[[` before the cursor on its line and returns where it starts and the query typed after it, or `null` once a `]` closes it. `proposals` keeps the names that contain the query, ignoring case, and sorts the names that start with it first, then alphabetically. The `Gio.ListStore` that holds them is created for the registered `NoteLinkProposal` type. GtkSourceView requests proposals asynchronously: it calls `vfuncPopulateAsync` with a callback, and `vfuncPopulateFinish` once the callback runs. The names are already in memory, so `vfuncPopulateAsync` completes a [`Gio.Task`](https://docs.gtk.org/gio/class.Task.html) at once. The task's `returnValue` takes the model in a `GObject.Value` initialized for `Gio.ListStore`, as [Passing a GValue](/v2/guide/native-values#passing-a-gvalue) describes. `propagateValue` unpacks it typed as `unknown`, so `vfuncPopulateFinish` checks that it is a `Gio.ListStore` before returning it. As you keep typing, GtkSourceView calls `vfuncRefilter` with the same model, and the provider replaces its contents with the proposals for the longer query. `vfuncDisplay` fills each row of the popup with a document icon and the note's name. `vfuncActivate` runs when you choose a proposal. It replaces `[[` and the query with a Markdown link to the note's file, such as `[Recipes]()`: - The angle brackets allow spaces in the file name, and `escape` adds a backslash before the characters that would end the link text or the file name early. - `beginUserAction` and `endUserAction` group the deletion and the insertion, so a single undo restores what you typed. ## Attach it to the editor `NoteScreen` passes the names of the other notes to the editor as `linkTargets`. `useMemo` builds the list again only when the notes or the open note change. `openLinkedNote` moves out of the component and calls `openNote` from [Window actions](/v2/tutorial/actions-menus-shortcuts#window-actions), so the screen no longer needs its `navigation` prop: ```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 { useSetting } from "@gtkx/react"; import { useMemo } from "react"; import { openNote, 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"; import { schema, useAppSettings } from "../settings.js"; import { NoteEditor } from "../editor/note-editor.js"; const openLinkedNote = (uri: string): boolean => { const name = linkedNoteName(uri); if (name === null) { return false; } openNote(name); return true; }; const NoteScreen = ({ route }: SplitViewScreenProps) => { const { t } = useTranslation(); const { notes, edit } = useNotes(); const [preview] = useSetting(useAppSettings(), schema, "preview"); const { name } = route.params; const note = notes?.get(name); const linkTargets = useMemo( () => [...(notes?.keys() ?? [])].filter((other) => other !== name), [notes, name], ); if (note === undefined) { return ( ); } return ( edit(name, text)} /> ); }; export { NoteScreen }; ``` `NoteEditor` keeps the `GtkSourceView` in state through its callback ref, as [Objects that JSX creates](/v2/guide/native-state#objects-that-jsx-creates) shows, and passes it to `useLinkCompletion`: ```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"; import { useEffect, useRef, useState } from "react"; import { NoteLinkProvider } from "./note-link-provider.js"; const markdown = GtkSource.LanguageManager.getDefault().getLanguage("markdown"); const useLinkCompletion = ( view: GtkSource.View | null, linkTargets: readonly string[], ): void => { const latestTargets = useRef(linkTargets); useEffect(() => { latestTargets.current = linkTargets; }, [linkTargets]); useEffect(() => { if (view === null) { return; } const provider = new NoteLinkProvider(); provider.noteNames = () => latestTargets.current; const completion = view.getCompletion(); completion.selectOnShow = true; completion.addProvider(provider); return () => completion.removeProvider(provider); }, [view]); }; type NoteEditorProps = { text: string; linkTargets: readonly string[]; onChange: (text: string) => void; }; const NoteEditor = ({ text, linkTargets, onChange }: NoteEditorProps) => { const { t } = useTranslation(); const isDark = useProperty(Adw.StyleManager.getDefault(), "dark"); const styleScheme = GtkSource.StyleSchemeManager.getDefault().getScheme( isDark ? "Adwaita-dark" : "Adwaita", ); const [view, setView] = useState(null); useLinkCompletion(view, linkTargets); return ( { onChange( buffer.getText( buffer.getStartIter(), buffer.getEndIter(), false, ), ); }} /> } /> ); }; export { NoteEditor }; ``` - Once the view exists, the second effect adds a provider to the view's completion, and its cleanup removes the provider when the editor unmounts. - The provider reads the names through `latestTargets`, a ref that the first effect keeps current. A new list of notes reaches the provider without replacing it. - [`selectOnShow`](https://gnome.pages.gitlab.gnome.org/gtksourceview/gtksourceview5/property.Completion.select-on-show.html) selects the first proposal when the popup opens, so Enter inserts it. ## Run it Open Book club and type `[[` on a new line: a popup lists the other notes, with the first one selected. Type `re` to narrow it to Recipes and Website relaunch, and press Enter to insert a link to Recipes. Press Ctrl+Z and the link turns back into `[[re`. Insert it again, switch to the preview and click the link to open Recipes.
The Notes window editing Book club, with [[ typed on the last line and a completion popup below it listing Meeting notes, Recipes, Trip to Lisbon and Website relaunch, the first one selected. The Notes window editing Book club, with [[ typed on the last line and a completion popup below it listing Meeting notes, Recipes, Trip to Lisbon and Website relaunch, the first one selected.
Captured from src/editor/note-editor.tsx above, after typing [[ in Book club.
--- --- description: "Write stories for the Markdown preview and explore its states in Storybook." --- # Develop the Preview in Storybook Render the Markdown preview on its own, with one story for each kind of Markdown, and change how it renders without opening a note in the app. The preview shows whatever the open note holds, so checking a nested list or a heading level in the app means first writing a note that has one. A story fixes that input instead: it renders `MarkdownPreview` with Markdown of its own. `@gtkx/storybook` shows the stories in a native explorer window; [Storybook](/v2/guide/storybook) covers it in full. ## Set up Storybook Install the explorer as a development dependency: ```sh npm install -D @gtkx/storybook@beta ``` Add a script that starts it to `package.json`: ```json{4} [package.json] { "scripts": { "dev": "gtkx dev", "storybook": "gtkx storybook" } } ``` `.storybook/main.ts` tells the explorer where the stories are, as patterns relative to the project root: ```ts [.storybook/main.ts] import { defineConfig } from "@gtkx/storybook/config"; export default defineConfig({ stories: ["src/**/*.stories.tsx"], }); ``` ## Write stories A stories file sits next to the component it renders and follows Storybook's [Component Story Format](https://storybook.js.org/docs/api/csf). Its default export, the metadata, names the component and the [arguments](https://storybook.js.org/docs/writing-stories/args) every story starts from. Each named export is a story that overrides some of them. Create `src/preview/markdown-preview.stories.tsx`: ````tsx [src/preview/markdown-preview.stories.tsx] import type { Meta, StoryObj } from "@gtkx/storybook"; import { MarkdownPreview } from "./markdown-preview.js"; const meta = { title: "Preview/Markdown", component: MarkdownPreview, args: { text: "", tags: [], onActivateLink: () => true, }, argTypes: { onActivateLink: { action: "activate-link" }, }, } satisfies Meta; type Story = StoryObj; const Headings = { args: { text: "# Heading 1\n\n## Heading 2\n\n### Heading 3\n\n#### Heading 4\n\n##### Heading 5\n\n###### Heading 6\n", }, } satisfies Story; const Formatting = { args: { text: "Text can be **bold**, *italic* or `inline code`.", }, argTypes: { text: { control: "text" }, }, } satisfies Story; const Links = { args: { text: "[Reading list]() links to another note.\n\n[GTKX](https://gtkx.dev) links to a website.\n", }, } satisfies Story; const Lists = { args: { text: [ "- Oat milk", "- Coffee beans", " - Whole, not ground", "- Lemons", "", "1. Preheat the oven", "2. Mix the dough", "3. Bake for 20 minutes", ].join("\n"), }, } satisfies Story; const Blocks = { args: { text: [ "> Simplicity is prerequisite for reliability.", ">", "> Edsger W. Dijkstra", "", "```ts", 'const greeting = "Hello";', "console.log(greeting);", "```", "", "---", "", "After the rule.", ].join("\n"), }, } satisfies Story; const Tagged = { args: { text: "# Ideas\n\nA notes app over **plain files**.\n", tags: ["work", "ideas"], }, } satisfies Story; export default meta; export { Blocks, Formatting, Headings, Links, Lists, Tagged }; ```` - `title` groups the stories under Preview/Markdown in the explorer's sidebar. - `args` gives `MarkdownPreview` empty Markdown, no tags and a link handler. Each story sets `text` to the Markdown it shows, and Tagged also sets `tags`. - The explorer shows a [control](https://storybook.js.org/docs/essentials/controls) only for an argument whose `argTypes` entry declares one. Formatting declares a text control for `text`. A text control is a one-line entry, so the other stories, whose Markdown spans several lines, have none. - `action: "activate-link"` lists each call to `onActivateLink` under Actions, with the link's target, and still calls the handler from `args`. That handler returns `true`, which tells the label the link is handled (see [Follow links](/v2/tutorial/the-markdown-preview#follow-links)), so GTK doesn't try to open it. The stories import `MarkdownPreview` rather than define it, because Fast Refresh updates a component only when it lives in its own module. [Test the App](/v2/tutorial/testing) renders the same stories in its tests. ## Run Storybook ```sh npm run storybook ``` The explorer lists the stories in its sidebar. Selecting one shows the preview beside the story's Controls and Actions. Its application ID is the app's with a `.Storybook` suffix, `dev.gtkx.Notes.Storybook`. Under the app's own ID, a second launch would only activate the running app (see [The application element](/v2/guide/application-lifecycle#the-application-element)), so the explorer runs beside `npm run dev`. ## Run it Select Formatting and edit its text control: the preview renders each change as you type. Select Links and click a link: Actions lists `activate-link` with the link's target. Keep the explorer open, change `src/preview/markdown-preview.tsx` and save it: the story updates in place, as the app does with [Fast Refresh](/v2/tutorial/fast-refresh).
The GTKX Storybook window with the Preview/Markdown stories in the sidebar and Formatting selected: the preview shows bold, italic and inline code, and the Controls panel shows the story's Markdown text. The GTKX Storybook window with the Preview/Markdown stories in the sidebar and Formatting selected: the preview shows bold, italic and inline code, and the Controls panel shows the story's Markdown text.
Captured from src/preview/markdown-preview.stories.tsx above, with the Formatting story selected.
--- --- description: "Test Notes headless with real files in a temporary folder." --- # Test the App Test the app's workflows the way a user runs them: open a note, type, use the menus, and check what lands in the notes folder. The tests render the whole app in a headless session, find widgets through the accessibility tree, and work on real files in a temporary folder, without mocks. The project already has the testing setup you chose when [scaffolding it](/v2/tutorial/#check-your-setup): Vitest, `@gtkx/testing`, the `test` script and `vitest.config.ts`. [Testing](/v2/guide/testing) covers the tools in full. ## A temporary notes folder Replace `vitest.config.ts`: ```ts [vitest.config.ts] import gtkx from "@gtkx/cli/vitest-plugin"; import { defineConfig } from "vitest/config"; export default defineConfig({ plugins: [gtkx()], test: { include: ["tests/**/*.test.{ts,tsx}"], setupFiles: ["./tests/setup.ts"], env: { LANG: "C.UTF-8", LANGUAGE: "en", LC_ALL: "C.UTF-8", }, }, }); ``` - `setupFiles` runs `tests/setup.ts` in each test file's worker before the file's tests. - `env` runs the tests in the C locale with English messages, so the names they look for stay the same whatever the language of the machine. Create `tests/setup.ts`: ```ts [tests/setup.ts] import * as Gio from "@gtkx/gi/gio"; import { cpSync, mkdtempSync, rmSync, utimesSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { afterAll, beforeEach } from "vitest"; import schema from "../data/dev.gtkx.Notes.gschema.xml"; const root = mkdtempSync(join(tmpdir(), "gtkx-notes-")); const folder = join(root, "Notes"); process.env.XDG_DATA_HOME = join(root, "data"); beforeEach(() => { rmSync(folder, { recursive: true, force: true }); cpSync(join(import.meta.dirname, "fixtures"), folder, { recursive: true }); utimesSync( join(folder, "Groceries.md"), new Date("2026-11-01"), new Date("2026-11-01"), ); utimesSync( join(folder, "Reading list.md"), new Date("2026-11-02"), new Date("2026-11-02"), ); const settings = Gio.Settings.new(schema.id); for (const key of Object.keys(schema.keys)) { settings.reset(key); } settings.setString("folder", folder); }); afterAll(() => { rmSync(root, { recursive: true, force: true }); }); ``` - `XDG_DATA_HOME` points into a temporary directory, so a note moved to the trash goes to a trash there instead of yours. GLib reads the variable once, when the test file imports GTKX, so the setup file sets it at the top level rather than in `beforeEach`. See [Test data and settings](/v2/guide/testing#test-data-and-settings). - Before each test, `beforeEach` copies the fixtures into a new notes folder and gives them fixed modification times, so the list's newest-first order is known. - Tests use GLib's in-memory settings backend and never touch your settings. A value one test writes would stay for the next test in the file, so `beforeEach` resets every key in the schema and then points `folder` at the new notes folder. The fixtures are two notes. Create `tests/fixtures/Groceries.md`: ```md [tests/fixtures/Groceries.md] # Groceries - Oat milk - Coffee beans - Lemons ``` And `tests/fixtures/Reading list.md`: ```md [tests/fixtures/Reading list.md] # Reading list *The Left Hand of Darkness* by Ursula K. Le Guin. ``` ## Find widgets by role and name Create `tests/notes.test.tsx` with the suite below. It covers each feature from the earlier chapters, one test per workflow; the rest of this chapter explains how its tests work. ::: details The complete `tests/notes.test.tsx` ```tsx [tests/notes.test.tsx] import * as Gio from "@gtkx/gi/gio"; import * as Gtk from "@gtkx/gi/gtk"; import { rootElement } from "@gtkx/react"; import * as Adw from "@gtkx/gi/adw"; import { act, render, screen, userEvent, waitFor, within } from "@gtkx/testing"; import { chmodSync, existsSync, mkdirSync, readdirSync, readFileSync, rmSync, writeFileSync, } from "node:fs"; import { dirname, join } from "node:path"; import { describe, expect, it } from "vitest"; import schema from "../data/dev.gtkx.Notes.gschema.xml"; import { App } from "../src/app.js"; const notesFolder = (): string => Gio.Settings.new(schema.id).getString("folder"); const noteRows = (): Promise => screen.findAllByRole(Gtk.AccessibleRole.LIST_ITEM); const openNote = async (name: string): Promise => { await userEvent.click( await screen.findByRole(Gtk.AccessibleRole.LIST_ITEM, { name }), ); return screen.findByRole(Gtk.AccessibleRole.TEXT_BOX, { name: "Note text", as: Gtk.TextView, }); }; const IDEAS = "---\ntags: [work, ideas]\n---\n# Ideas\n\nA notes app over **plain files**\n"; const findPreview = async () => within( await screen.findByRole(Gtk.AccessibleRole.DOCUMENT, { name: "Preview", }), ); const editorText = (view: Gtk.TextView): string => { const buffer = view.getBuffer(); return buffer.getText(buffer.getStartIter(), buffer.getEndIter(), false); }; describe("Notes", () => { it("lists the Markdown files in the folder, newest first", async () => { await render(, { container: rootElement }); const [first, second] = await noteRows(); expect(first).toHaveAccessibleName("Reading list"); expect(second).toHaveAccessibleName("Groceries"); }); it("opens a note in the editor", async () => { await render(, { container: rootElement }); const editor = await openNote("Groceries"); expect(editorText(editor)).toBe( readFileSync(join(notesFolder(), "Groceries.md"), "utf8"), ); }); it("saves what is typed to the note's file", async () => { await render(, { container: rootElement }); const editor = await openNote("Groceries"); await userEvent.type(editor, "- Rice\n"); await waitFor(() => { expect( readFileSync(join(notesFolder(), "Groceries.md"), "utf8"), ).toContain("- Rice"); }); }); it("shows notes added and removed outside the app", async () => { await render(, { container: rootElement }); await noteRows(); writeFileSync( join(notesFolder(), "Ideas.md"), "A notes app over plain files\n", ); expect( await screen.findByRole(Gtk.AccessibleRole.LIST_ITEM, { name: "Ideas", }), ).toBeDefined(); rmSync(join(notesFolder(), "Groceries.md")); await waitFor(() => { expect( screen.queryByRole(Gtk.AccessibleRole.LIST_ITEM, { name: "Groceries", }), ).toBeNull(); }); }); it("reloads an open note changed outside the app", async () => { await render(, { container: rootElement }); const editor = await openNote("Groceries"); writeFileSync( join(notesFolder(), "Groceries.md"), "# Groceries\n\n- Bread\n", ); await waitFor(() => { expect(editorText(editor)).toBe("# Groceries\n\n- Bread\n"); }); }); it("creates an untitled note and opens it", async () => { await render(, { container: rootElement }); await userEvent.click( await screen.findByRole(Gtk.AccessibleRole.BUTTON, { name: "New Note (Ctrl+N)", }), ); const editor = await screen.findByRole(Gtk.AccessibleRole.TEXT_BOX, { name: "Note text", as: Gtk.TextView, }); expect(editorText(editor)).toBe(""); expect(existsSync(join(notesFolder(), "Untitled.md"))).toBe(true); expect( await screen.findByRole(Gtk.AccessibleRole.LIST_ITEM, { name: "Untitled", }), ).toBeDefined(); }); it("numbers a new note when the name is taken", async () => { writeFileSync(join(notesFolder(), "Untitled.md"), ""); await render(, { container: rootElement }); await userEvent.click( await screen.findByRole(Gtk.AccessibleRole.BUTTON, { name: "New Note (Ctrl+N)", }), ); expect( await screen.findByRole(Gtk.AccessibleRole.LIST_ITEM, { name: "Untitled 2", }), ).toBeDefined(); expect(readFileSync(join(notesFolder(), "Untitled.md"), "utf8")).toBe( "", ); }); it("renames the open note's file", async () => { await render(, { container: rootElement }); const text = readFileSync(join(notesFolder(), "Groceries.md"), "utf8"); await openNote("Groceries"); await userEvent.click( screen.getByRole(Gtk.AccessibleRole.BUTTON, { name: "Note Menu" }), ); await userEvent.click( await screen.findByRole(Gtk.AccessibleRole.MENU_ITEM, { name: "Rename…", }), ); const entry = await screen.findByRole(Gtk.AccessibleRole.TEXT_BOX, { name: "Note name", }); await userEvent.clear(entry); await userEvent.type(entry, "Shopping{Enter}"); expect( await screen.findByRole(Gtk.AccessibleRole.LIST_ITEM, { name: "Shopping", }), ).toBeDefined(); expect(readFileSync(join(notesFolder(), "Shopping.md"), "utf8")).toBe( text, ); expect(existsSync(join(notesFolder(), "Groceries.md"))).toBe(false); }); it("won't rename a note to a name already taken", async () => { await render(, { container: rootElement }); await openNote("Groceries"); await userEvent.click( screen.getByRole(Gtk.AccessibleRole.BUTTON, { name: "Note Menu" }), ); await userEvent.click( await screen.findByRole(Gtk.AccessibleRole.MENU_ITEM, { name: "Rename…", }), ); const entry = await screen.findByRole(Gtk.AccessibleRole.TEXT_BOX, { name: "Note name", }); await userEvent.clear(entry); await userEvent.type(entry, "Reading list"); expect( screen.getByRole(Gtk.AccessibleRole.BUTTON, { name: "Rename" }), ).toBeDisabled(); }); it("moves a note to the trash and undoes it", async () => { await render(, { container: rootElement }); const path = join(notesFolder(), "Groceries.md"); const text = readFileSync(path, "utf8"); await openNote("Groceries"); await userEvent.click( screen.getByRole(Gtk.AccessibleRole.BUTTON, { name: "Note Menu" }), ); await userEvent.click( await screen.findByRole(Gtk.AccessibleRole.MENU_ITEM, { name: "Move to Trash", }), ); expect( await screen.findByText("“Groceries” moved to Trash"), ).toBeDefined(); expect(existsSync(path)).toBe(false); expect( readdirSync( join(process.env.XDG_DATA_HOME ?? "", "Trash", "files"), ), ).toContain("Groceries.md"); expect( screen.queryByRole(Gtk.AccessibleRole.LIST_ITEM, { name: "Groceries", }), ).toBeNull(); await userEvent.click( screen.getByRole(Gtk.AccessibleRole.BUTTON, { name: "Undo" }), ); expect( await screen.findByRole(Gtk.AccessibleRole.LIST_ITEM, { name: "Groceries", }), ).toBeDefined(); expect(readFileSync(path, "utf8")).toBe(text); }); it("follows the style chosen in Preferences", async () => { await render(, { container: rootElement }); await userEvent.click( await screen.findByRole(Gtk.AccessibleRole.BUTTON, { name: "Main Menu", }), ); await userEvent.click( await screen.findByRole(Gtk.AccessibleRole.MENU_ITEM, { name: "Preferences", }), ); await userEvent.selectOptions( await screen.findByRole(Gtk.AccessibleRole.COMBO_BOX, { name: "Style", }), 2, ); await waitFor(() => { expect(Adw.StyleManager.getDefault().getColorScheme()).toBe( Adw.ColorScheme.FORCE_DARK, ); }); }); it("switches to another folder with the window and Preferences open", async () => { const otherFolder = join(dirname(notesFolder()), "Other notes"); mkdirSync(otherFolder, { recursive: true }); writeFileSync(join(otherFolder, "Ideas.md"), IDEAS); await render(, { container: rootElement }); const window = (await openNote("Groceries")).getRoot(); await userEvent.click( await screen.findByRole(Gtk.AccessibleRole.BUTTON, { name: "Main Menu", }), ); await userEvent.click( await screen.findByRole(Gtk.AccessibleRole.MENU_ITEM, { name: "Preferences", }), ); await act(() => { Gio.Settings.new(schema.id).setString("folder", otherFolder); }); const ideas = await screen.findByRole(Gtk.AccessibleRole.LIST_ITEM, { name: "Ideas", }); expect(ideas.getRoot()).toBe(window); expect( screen.queryByRole(Gtk.AccessibleRole.LIST_ITEM, { name: "Groceries", }), ).toBeNull(); expect( screen.queryByRole(Gtk.AccessibleRole.TEXT_BOX, { name: "Note text", }), ).toBeNull(); expect( await screen.findByRole(Gtk.AccessibleRole.COMBO_BOX, { name: "Style", }), ).toBeDefined(); }); it("shows the open note as rendered Markdown", async () => { await render(, { container: rootElement }); await openNote("Groceries"); await userEvent.click( screen.getByRole(Gtk.AccessibleRole.TOGGLE_BUTTON, { name: "Preview (Ctrl+Shift+P)", }), ); const preview = await findPreview(); expect( preview.getByRole(Gtk.AccessibleRole.HEADING, { name: "Groceries", }), ).toBeVisible(); expect(preview.getByText("Oat milk")).toBeVisible(); expect( screen.queryByRole(Gtk.AccessibleRole.TEXT_BOX, { name: "Note text", }), ).toBeNull(); }); it("opens the note a preview link points to", async () => { writeFileSync( join(notesFolder(), "Index.md"), "[Shopping list](Groceries.md)\n", ); Gio.Settings.new(schema.id).setBoolean("preview", true); await render(, { container: rootElement }); await userEvent.click( await screen.findByRole(Gtk.AccessibleRole.LIST_ITEM, { name: "Index", }), ); await userEvent.keyboard( (await findPreview()).getByText("Shopping list"), "{Enter}", ); expect( await screen.findByRole(Gtk.AccessibleRole.HEADING, { name: "Groceries", }), ).toBeVisible(); }); it("completes a link to another note after [[", async () => { await render(, { container: rootElement }); const editor = await openNote("Groceries"); await userEvent.type(editor, "[[read"); await within(editor).findByText("Reading list"); await userEvent.keyboard(editor, "{Enter}"); expect(editorText(editor)).toMatch( /\[Reading list\]\(\)$/, ); await waitFor(() => { expect( readFileSync(join(notesFolder(), "Groceries.md"), "utf8"), ).toContain("[Reading list]()"); }); }); it("shows each note's first paragraph as plain text", async () => { await render(, { container: rootElement }); expect( await screen.findByText( "The Left Hand of Darkness by Ursula K. Le Guin.", ), ).toBeVisible(); expect(screen.getByText("Oat milk")).toBeVisible(); }); it("filters the notes by a tag from their front matter", async () => { writeFileSync(join(notesFolder(), "Ideas.md"), IDEAS); await render(, { container: rootElement }); await userEvent.selectOptions( await screen.findByRole(Gtk.AccessibleRole.COMBO_BOX, { name: "All Notes", }), 2, ); await waitFor(() => { expect( screen.queryByRole(Gtk.AccessibleRole.LIST_ITEM, { name: "Groceries", }), ).toBeNull(); }); expect( screen.getByRole(Gtk.AccessibleRole.LIST_ITEM, { name: "Ideas" }), ).toBeDefined(); expect(screen.getByText("A notes app over plain files")).toBeVisible(); }); it("previews a note's tags without its front matter", async () => { writeFileSync(join(notesFolder(), "Ideas.md"), IDEAS); Gio.Settings.new(schema.id).setBoolean("preview", true); await render(, { container: rootElement }); await userEvent.click( await screen.findByRole(Gtk.AccessibleRole.LIST_ITEM, { name: "Ideas", }), ); const preview = await findPreview(); expect( preview.getByRole(Gtk.AccessibleRole.HEADING, { name: "Ideas" }), ).toBeVisible(); expect(preview.getByText("#work")).toBeVisible(); expect(preview.queryByText("tags: [work, ideas]")).toBeNull(); }); it("finds notes by their text", async () => { await render(, { container: rootElement }); await userEvent.type( await screen.findByRole(Gtk.AccessibleRole.SEARCH_BOX, { name: "Search Notes", }), "lemons", ); await waitFor(() => { expect( screen.queryByRole(Gtk.AccessibleRole.LIST_ITEM, { name: "Reading list", }), ).toBeNull(); }); expect( screen.getByRole(Gtk.AccessibleRole.LIST_ITEM, { name: "Groceries", }), ).toBeDefined(); }); it("focuses the search entry on Ctrl+F", async () => { await render(, { container: rootElement }); const editor = await openNote("Groceries"); await userEvent.keyboard(editor, "{Control>}f{/Control}"); expect( screen.getByRole(Gtk.AccessibleRole.SEARCH_BOX, { name: "Search Notes", }), ).toHaveFocus(); }); it("says when a note can't be saved", async () => { await render(, { container: rootElement }); const path = join(notesFolder(), "Groceries.md"); chmodSync(path, 0o444); const editor = await openNote("Groceries"); await userEvent.type(editor, "- Rice\n"); expect( await screen.findByText("Couldn’t save “Groceries”"), ).toBeDefined(); expect(readFileSync(path, "utf8")).not.toContain("- Rice"); }); it("offers to create the first note in an empty folder", async () => { rmSync(notesFolder(), { recursive: true }); await render(, { container: rootElement }); await userEvent.click( await screen.findByRole(Gtk.AccessibleRole.BUTTON, { name: "New Note", }), ); expect( await screen.findByRole(Gtk.AccessibleRole.LIST_ITEM, { name: "Untitled", }), ).toBeDefined(); expect(existsSync(join(notesFolder(), "Untitled.md"))).toBe(true); }); }); ``` ::: The first test checks the order of the list: ```tsx const noteRows = (): Promise => screen.findAllByRole(Gtk.AccessibleRole.LIST_ITEM); describe("Notes", () => { it("lists the Markdown files in the folder, newest first", async () => { await render(, { container: rootElement }); const [first, second] = await noteRows(); expect(first).toHaveAccessibleName("Reading list"); expect(second).toHaveAccessibleName("Groceries"); }); ``` - `render` with `container: rootElement` renders `App` as `src/index.tsx` does, with its application element and window, instead of inside a test window. See [Rendering a component](/v2/guide/testing#rendering-a-component). - `screen` searches every open window, including dialogs and popovers. Queries take a `Gtk.AccessibleRole` and an accessible name: the names that earlier chapters gave the rows (the note's name), the editor (Note text) and the search entry (Search Notes). An icon button has no label, so its tooltip names it, as in `{ name: "Note Menu" }`. See [Finding widgets](/v2/guide/testing#finding-widgets). - `findBy` and `findAllBy` queries wait for the widget to appear, here for the notes to load. `getBy` queries expect the widget to be there already, and `queryBy` queries return `null` when it isn't, to check that something is gone. - `toHaveAccessibleName`, `toBeVisible` and the other widget matchers are available once the file imports `@gtkx/testing`. See [Assertions and debugging](/v2/guide/testing#assertions-and-debugging). The `as` option in `openNote` keeps only a `Gtk.TextView` and types the result as one, so `editorText` can read its buffer. ## Check the notes folder The tests read the notes folder to check what the app wrote, and write to it to act as another program would: ```tsx it("saves what is typed to the note's file", async () => { await render(, { container: rootElement }); const editor = await openNote("Groceries"); await userEvent.type(editor, "- Rice\n"); await waitFor(() => { expect( readFileSync(join(notesFolder(), "Groceries.md"), "utf8"), ).toContain("- Rice"); }); }); ``` - `userEvent` helpers act as a user does and wait until React has applied the result. Await each one. See [Interacting and waiting](/v2/guide/testing#interacting-and-waiting). - The app saves 400 milliseconds after the last edit, so `waitFor` retries the assertion until the file has the new text, for up to a second. - "shows notes added and removed outside the app" and "reloads an open note changed outside the app" write and delete files with `node:fs` and wait for the list and the editor to follow, which tests the file watching from [Save and Watch Files](/v2/tutorial/saving-and-watching). - "moves a note to the trash and undoes it" finds the moved file under `Trash/files` in the temporary `XDG_DATA_HOME`. - "says when a note can't be saved" makes the file read-only with `chmodSync` and waits for the error toast. ## Change settings A test that needs a setting other than its default writes it with `Gio.Settings` before rendering, as "opens the note a preview link points to" does to open notes in the preview. A setting written while the app is open updates React state outside the `userEvent` helpers, so "switches to another folder with the window and Preferences open" writes the new folder inside `act`: ```tsx await act(() => { Gio.Settings.new(schema.id).setString("folder", otherFolder); }); ``` `act` applies the updates before the test continues; without it, React warns that an update was not wrapped in `act(...)`. The test then checks that the window it started with now lists the other folder, and that Preferences stayed open. ## Type into the editor "completes a link to another note after [[" tests the completion provider from [Complete Note Links](/v2/tutorial/note-links). `userEvent.type(editor, "[[read")` inserts one character per edit, as typing does, so GtkSourceView sees the second `[` and opens its popup. `read` narrows the popup to Reading list. The popup belongs to the editor, so `within(editor)` waits for the proposal there and not for the Reading list row in the sidebar. `selectOnShow` has selected it, and while the popup shows, the keys that `keyboard` sends go to its list (see [Keyboard](/v2/guide/testing#keyboard)), so `{Enter}` inserts the link as it does for a user. The test then finds the link in the editor and in the file. ## Test the stories The preview's tests render the stories from [Develop the Preview in Storybook](/v2/tutorial/storybook) instead of repeating their Markdown. Create `tests/preview.test.tsx`: ```tsx [tests/preview.test.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 "../src/preview/markdown-preview.stories.js"; const { Headings, Links, Tagged } = composeStories(stories); it("renders each Markdown heading as a heading", async () => { await render(); for (const level of [1, 2, 3, 4, 5, 6]) { expect( screen.getByRole(Gtk.AccessibleRole.HEADING, { name: `Heading ${level}`, }), ).toBeVisible(); } }); it("hands an activated link to its callback", async () => { const links: string[] = []; await render( { links.push(uri); return true; }} />, ); await userEvent.keyboard( screen.getByText("Reading list links to another note."), "{Enter}", ); expect(links).toEqual(["Reading list.md"]); }); it("shows tags above the note", async () => { await render(); expect(screen.getByText("#work")).toBeVisible(); expect(screen.getByText("#ideas")).toBeVisible(); }); ``` - `composeStories` turns each story into a component with the story's arguments applied. See [Reuse stories in native tests](/v2/guide/storybook#reuse-stories-in-native-tests). - A story takes props that override its arguments, so the link test passes its own `onActivateLink` and collects the targets it receives. - These components have no window of their own, so `render` puts them in a test window. ## Run the tests The tests run in a private headless display and session bus, which need Sway and `dbus-daemon`. Install them as [Setup](/v2/guide/testing#setup) shows, then run: ```bash npm test ``` Each test starts from the fixtures and the default settings, so any test also runs on its own. To run only the tests whose names contain "trash": ```bash npx vitest run -t trash ``` ## Run it `npm test` passes both files: ```txt ✓ tests/preview.test.tsx (3 tests) ✓ tests/notes.test.tsx (22 tests) Test Files 2 passed (2) Tests 25 passed (25) ``` Change `openNote("Groceries")` in "opens a note in the editor" to `openNote("Shopping")` and run the tests again. The query fails after a second and lists each accessible role on screen with the names of its widgets, such as the list items Reading list and Groceries. Change it back afterwards. --- --- description: "Let an AI coding agent inspect and drive the running app through the GTKX MCP server." --- # Inspect with MCP Connect an AI coding agent to the running app through the GTKX MCP server, and let it inspect the widget tree and take screenshots. An agent that edits the app's code sees only the source, not the window it produces. The GTKX MCP server, a [Model Context Protocol](https://modelcontextprotocol.io/docs/learn/server-concepts) server, connects the agent to the app that `npm run dev` runs: it finds widgets, reads their state, clicks and types, and captures the window. [App Inspection (MCP)](/v2/guide/mcp) covers it in full. ## Connect an agent The scaffold registered the server for Claude Code in `.mcp.json` at the project root: ```json [.mcp.json] { "mcpServers": { "gtkx": { "command": "npx", "args": ["--no", "gtkx", "mcp"] } } } ``` The entry runs the project's own `gtkx mcp` command. `--no` makes `npx` fail instead of downloading an unrelated `gtkx` package if the CLI is missing. Start Claude Code in the project directory. It [asks you to approve](https://code.claude.com/docs/en/mcp#project-scope) a server from `.mcp.json` before using it. For another agent, run `npx gtkx mcp init --client ` or configure the server by hand; see [Setup](/v2/guide/mcp#setup). ## Inspect the window With `npm run dev` running, the app connects to the server on its own, and either can start first. Ask the agent about the window, such as which notes the list shows. The agent finds widgets by role, accessible name or text with `gtkx_query_widgets`, reads their properties with `gtkx_get_widget_props`, and captures the window with `gtkx_take_screenshot`. Searching the text for Book club returns the title label of its row: ```json { "widgets": [ { "id": "68", "type": "Label", "role": "label", "name": "Book club", "text": "Book club", "isSensitive": true, "isVisible": true, "cssClasses": ["heading"], "children": [] } ], "searched": "the text the widget renders" } ``` `type` is the GTK class and `name` the accessible name, the same name the tests in [Test the App](/v2/tutorial/testing) find widgets by. The agent passes the `id` to later calls, such as `gtkx_click`, while the widget stays mounted. See [Tools](/v2/guide/mcp#tools) for the full list. ## Run it Ask the agent to open Book club, turn on the preview and take a screenshot. It clicks the row, then the toggle button whose accessible name is its tooltip, "Preview (Ctrl+Shift+P)". The screenshot shows Book club rendered with its #home and #reading tags, as the window does. Then ask for a change, such as a different style for the tags. The agent edits the code, Fast Refresh applies it to the open window, and the agent takes another screenshot to check the result; see [Inspect and verify changes](/v2/guide/mcp#inspect-and-verify-changes). --- --- description: "Extract the app's messages into a gettext template and add a French translation." --- # Translate the App Extract the messages marked since the first chapter into a gettext template, add a French translation, and check it in a test. GTK apps are translated with [GNU gettext](https://www.gnu.org/software/gettext/manual/gettext.html): a template lists the messages, and translators fill in one [PO file](https://www.gnu.org/software/gettext/manual/html_node/PO-Files.html) per language. `@gtkx/i18n` keeps i18next's `t()` in the components and lets gettext look up each translation, so the catalogs follow the format GNOME translators already work with. [Internationalization](/v2/guide/internationalization) covers it in full. ## Extract the messages Every visible string has gone through `t()` since [Create a Window](/v2/tutorial/your-first-window), which also installed `@gtkx/i18n`. GTKX starts managing translations once such a project has a `po` folder whose `LINGUAS` file lists the locales, one per line: ```text [po/LINGUAS] fr ``` Then run codegen. It calls the gettext tools that the [tutorial's requirements](/v2/tutorial/) list: ```sh npm run codegen ``` GTKX writes the template `po/dev.gtkx.Notes.pot`, named after the application ID, with every `t()` message and the summary and description of each settings key. It creates `po/fr.po` from the template with `msginit`, and lists the files it read in `po/POTFILES.in`. Each entry gives the source text as `msgid`, an empty `msgstr` for the translation, and a `#:` comment with the lines it comes from: ```po [po/dev.gtkx.Notes.pot] #: src/components/main-menu.tsx:15 src/components/notes-screen.tsx:135 msgid "New Note" msgstr "" ``` The same text in two places is one message, translated once. See [Create a catalog](/v2/guide/internationalization#create-a-catalog) and [Translate settings schemas](/v2/guide/internationalization#translate-settings-schemas). ## Add a translation Fill in each `msgstr` in `po/fr.po`, and replace the generated header comments and `Last-Translator` with your own. Placeholders such as `{{name}}` stay as they are; i18next fills them in after gettext returns the translation: ```po [po/fr.po] #: src/components/window-actions.tsx:37 msgid "“{{name}}” moved to Trash" msgstr "« {{name}} » a été mise à la corbeille" ``` The [finished app's catalog](https://github.com/gtkx-org/gtkx/blob/main/tutorial/po/fr.po) has every French message. When you change a message later, run codegen again: it updates the template and merges the change into `fr.po`. `npm run dev` updates only the template as you save, and leaves the PO files to codegen and builds. ## Plurals The note count under the sidebar title is a plural message. `t()` takes the singular as its key, the number as `count`, and both English forms as `defaultValue_one` and `defaultValue_other`: ```tsx [src/components/notes-screen.tsx] t("{{count}} note", { count: notes.size, defaultValue_one: "{{count}} note", defaultValue_other: "{{count}} notes", }); ``` Its catalog entry has both source forms and one translation per plural form of the language. The `Plural-Forms` header, which `msginit` filled in for French, picks the form from the count. Its [rule](https://www.gnu.org/software/gettext/manual/html_node/Plural-forms.html) gives French the singular for 0 and 1, where English uses the plural for 0: ```po [po/fr.po] "Plural-Forms: nplurals=2; plural=(n > 1);\n" #: src/components/notes-screen.tsx:100 msgid "{{count}} note" msgid_plural "{{count}} notes" msgstr[0] "{{count}} note" msgstr[1] "{{count}} notes" ``` See [Plurals and context](/v2/guide/internationalization#plurals-and-context). ## Test the translation The tests from [Test the App](/v2/tutorial/testing) still render the English source text: the Vitest plugin compiles no catalogs, and the main configuration sets an English locale. gettext reads the locale once, when the process starts, so the French checks run in their own Vitest configuration with a French environment for its workers. `localeDir` points the plugin at the catalogs that `gtkx build` compiles into `dist/locale`: ```ts [vitest.i18n.config.ts] import gtkx from "@gtkx/cli/vitest-plugin"; import { resolve } from "node:path"; import { defineConfig } from "vitest/config"; export default defineConfig({ plugins: [gtkx({ localeDir: resolve(import.meta.dirname, "dist/locale") })], test: { include: ["tests/**/*.i18n.tsx"], setupFiles: ["./tests/setup.ts"], bail: 1, env: { LANG: "fr_FR.UTF-8", LANGUAGE: "fr", LC_ALL: "fr_FR.UTF-8", }, }, }); ``` It runs the files ending in `.i18n.tsx`, which the main configuration's `tests/**/*.test.{ts,tsx}` pattern skips, and reuses the setup file, so each test starts from the same two fixture notes. The tests find the New Note button by its French tooltip and the search entry by its placeholder, delete notes until the count reads "0 note", and check the toast that names a trashed note: ```tsx [tests/localization.i18n.tsx] import * as Gio from "@gtkx/gi/gio"; import * as Gtk from "@gtkx/gi/gtk"; import { rootElement } from "@gtkx/react"; import { render, screen, userEvent } from "@gtkx/testing"; import { rmSync } from "node:fs"; import { join } from "node:path"; import { describe, expect, it } from "vitest"; import schema from "../data/dev.gtkx.Notes.gschema.xml"; import { App } from "../src/app.js"; const notesFolder = (): string => Gio.Settings.new(schema.id).getString("folder"); describe("Notes in French", () => { it("renders translated controls", async () => { await render(, { container: rootElement }); expect( await screen.findByRole(Gtk.AccessibleRole.BUTTON, { name: "Nouvelle note (Ctrl+N)", }), ).toBeDefined(); expect( await screen.findByPlaceholderText("Rechercher dans les notes"), ).toBeDefined(); }); it("uses French plural forms", async () => { await render(, { container: rootElement }); expect(await screen.findByText("2 notes")).toBeDefined(); rmSync(join(notesFolder(), "Groceries.md")); expect(await screen.findByText("1 note")).toBeDefined(); rmSync(join(notesFolder(), "Reading list.md")); expect(await screen.findByText("0 note")).toBeDefined(); }); it("interpolates values into translated messages", async () => { await render(, { container: rootElement }); await userEvent.click( await screen.findByRole(Gtk.AccessibleRole.LIST_ITEM, { name: "Groceries", }), ); await userEvent.click( await screen.findByRole(Gtk.AccessibleRole.BUTTON, { name: "Menu de la note", }), ); await userEvent.click( await screen.findByRole(Gtk.AccessibleRole.MENU_ITEM, { name: "Mettre à la corbeille", }), ); expect( await screen.findByText("« Groceries » a été mise à la corbeille"), ).toBeDefined(); }); }); ``` Add a script that builds and runs them, and make `npm test` run both suites: ```json{3,4} [package.json] { "scripts": { "test": "vitest run && npm run test:i18n", "test:i18n": "gtkx build && vitest run --config vitest.i18n.config.ts" } } ``` See [Test translations](/v2/guide/internationalization#test-translations). ## Run it The French locale must be installed: `locale -a` lists it, and on Fedora it comes with `glibc-langpack-fr`. Start the app in French: ```sh LANG=fr_FR.UTF-8 LANGUAGE=fr npm run dev ``` The sidebar, menus, dialogs and toasts are in French, and the note count follows French plural rules. Saving `po/fr.po` restarts the app, since gettext keeps the catalogs it loaded for the life of the process. See [Develop and build](/v2/guide/internationalization#develop-and-build).
The Notes window in French: the sidebar subtitle reads 5 notes, the search entry says Rechercher dans les notes, the main menu lists Nouvelle note, Préférences, Raccourcis clavier and À propos de Notes, and the empty pane reads Aucune note sélectionnée. The Notes window in French with the dark style: the sidebar subtitle reads 5 notes, the search entry says Rechercher dans les notes, the main menu lists Nouvelle note, Préférences, Raccourcis clavier and À propos de Notes, and the empty pane reads Aucune note sélectionnée.
Captured with po/fr.po above, with the main menu open.
--- --- description: "Describe Notes for launchers and software centers, give it an icon, and build deb, rpm and AppImage packages." --- # Package the App Describe Notes for launchers and software centers, give it an icon, and build packages that install it like any other desktop app. A Linux desktop learns about an installed app from two files: a [desktop entry](https://specifications.freedesktop.org/desktop-entry-spec/latest/), which launchers read for the app's name, icon and command, and [AppStream metadata](https://www.freedesktop.org/software/appstream/docs/chap-Metadata.html), which software centers read for its description, screenshots and releases. `gtkx deploy` generates both from `gtkx.config.ts` and `package.json`, validates them, and packages them with the build. [Deploying](/v2/guide/deploying) covers every target and option. ## Application metadata The scaffold's `deploy` block holds placeholders. Replace it with Notes' own metadata: ```ts [gtkx.config.ts] import { defineConfig } from "@gtkx/config"; export default defineConfig({ libraries: ["GtkSource-5"], applicationId: "dev.gtkx.Notes", applicationIcon: "data/icons", deploy: { name: "Notes", genericName: "Markdown Notes", summary: "Write Markdown notes kept as plain files", description: [ "Notes keeps each note as a Markdown file in a folder, so notes sync with any tool and outlive the app.", "It previews Markdown, searches the full text, filters by tag, completes links to other notes, " + "and shows changes made by other editors or sync tools as they happen.", ], categories: ["Utility", "TextEditor"], keywords: ["Notes", "Markdown", "Notebook", "Writing"], urls: { bugtracker: "https://github.com/gtkx-org/gtkx/issues", "vcs-browser": "https://github.com/gtkx-org/gtkx", }, screenshots: [ { file: "assets/screenshot.png", caption: "Reading a note as rendered Markdown", isDefault: true, }, { file: "assets/screenshot-editor.png", caption: "Writing Markdown with syntax highlighting", }, ], releases: [ { version: "1.0.0", date: "2026-11-07", notes: ["Initial release."], }, ], branding: { light: "#f8e45c", dark: "#865e3c" }, isDbusActivatable: true, screenshotBaseUrl: "https://raw.githubusercontent.com/gtkx-org/gtkx/main/tutorial", targets: ["flatpak", "deb", "rpm", "appimage"], depends: { deb: ["libgtksourceview-5-0"] }, }, }); ``` `name`, `genericName`, `summary`, `keywords` and `categories` go into the desktop entry; the categories come from the freedesktop [category registry](https://specifications.freedesktop.org/menu-spec/latest/category-registry.html). The description paragraphs, `urls`, `screenshots`, `releases` and the `branding` colors are for software centers. List each new version in `releases`, newest first, with its notes. Without the list, GTKX writes a single release for the current version, dated the day of the build. `isDbusActivatable` makes the launcher start Notes through the session bus instead of running its command, and GTKX installs the D-Bus service file this needs. `targets` lists the formats `npm run deploy` builds. The RPM package already requires GtkSourceView's shared library, which RPM resolves to whichever package ships it. A Debian package can depend only on package names, so `depends.deb` names the one that ships the library. Without it, the `.deb` installs on a system that lacks GtkSourceView and Notes fails to start; see [Runtime and library requirements](/v2/guide/deploying#runtime-and-library-requirements). GTKX takes the version, license and homepage from `package.json`, and the developer from `author`, which the scaffold set to your Git `user.name`. Set the others there: ```json [package.json] { "version": "1.0.0", "license": "MPL-2.0", "homepage": "https://gtkx.dev" } ``` Notes runs as a single instance: opening it from the launcher while it runs activates the running instance instead of starting a second one. Present the window there, or the launcher appears to do nothing, as [The application element](/v2/guide/application-lifecycle#the-application-element) explains: ```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"; import { SettingsProvider } from "./settings.js"; function App() { return ( application.getActiveWindow()?.present() } actionAccels={[ { detailedActionName: "win.new-note", accels: ["n"] }, { detailedActionName: "win.rename-note", accels: ["F2"] }, { detailedActionName: "win.preview", accels: ["p"], }, { detailedActionName: "win.preferences", accels: ["comma"], }, { detailedActionName: "win.shortcuts", accels: ["question"], }, { detailedActionName: "app.quit", accels: ["q"] }, ]} actions={ quit()} />} > ); } export { App }; ``` Notes is translated, so its metadata needs French text too. The next `npm run deploy` adds the name, summary, description, keywords, screenshot captions and release notes to the template and to `po/fr.po`. Translate them as in [Translate the App](/v2/tutorial/internationalization#add-a-translation), and the packages carry them in both the desktop entry and the AppStream metadata; see [Translate package metadata](/v2/guide/internationalization#translate-package-metadata). ## Icons and screenshots `applicationIcon: "data/icons"` points at an icon theme directory. GTKX adds it to the icon theme under `npm run dev` and installs it with every package, so the desktop finds the icon by the application ID. Replace the scaffold's placeholder with the Notes icon and add its symbolic variant, both from the finished app's [`data/icons`](https://github.com/gtkx-org/gtkx/tree/main/tutorial/data/icons); the GNOME HIG describes both kinds of [app icon](https://developer.gnome.org/hig/guidelines/app-icons.html): ```text data/icons/hicolor/scalable/apps/dev.gtkx.Notes.svg data/icons/hicolor/symbolic/apps/dev.gtkx.Notes-symbolic.svg ``` The About dialog shows the icon and the version. `virtual:gtkx-config` is a module GTKX generates from `gtkx.config.ts`, and its `applicationId` names the icon; the version is read from `package.json`: ```tsx [src/components/about.tsx] import * as Gtk from "@gtkx/gi/gtk"; import { t } from "@gtkx/i18n"; import { AdwAboutDialog } from "@gtkx/jsx/adw"; import { applicationId } from "virtual:gtkx-config"; import packageManifest from "../../package.json" with { type: "json" }; const About = ({ onClose }: { onClose: () => void }) => ( ); export { About }; ``` `screenshots` lists the PNGs in [`assets/`](https://github.com/gtkx-org/gtkx/tree/main/tutorial/assets). Software centers download each one over the network, so the metadata gives its URL: the file's path under `screenshotBaseUrl`. Without `screenshotBaseUrl`, GTKX builds the URL from the project's GitHub or GitLab remote and default branch; Notes points at the copies in the GTKX repository. Push the screenshots before you publish a package. ## Build the packages Preview the metadata first. The command builds the app, validates the desktop entry and AppStream metadata, writes them to `build//metadata/` and the package manifests to `build//targets/`, and stops before creating packages: ```bash npm run deploy -- --print-manifests ``` An excerpt of the generated desktop entry shows where the values went. The command, `gtkx-notes`, is the `name` in `package.json`: ```ini [build/x64/metadata/dev.gtkx.Notes.desktop] [Desktop Entry] Type=Application Name=Notes GenericName=Markdown Notes Comment=Write Markdown notes kept as plain files Exec=gtkx-notes Icon=dev.gtkx.Notes Categories=Utility;TextEditor; Keywords=Notes;Markdown;Notebook;Writing; DBusActivatable=true ``` `npm run deploy` builds each target in `targets` into `build/out`. The Flatpak can't reach the notes folder until [Prepare for Flathub](/v2/tutorial/flatpak) grants it, so build the other formats now: ```bash npm run deploy -- --target deb,rpm,appimage ``` The first run downloads the Node.js runtime that the packages bundle and the packaging tools. The command reports any missing system tool with an installation hint; see [Build tools](/v2/guide/deploying#build-tools). ## Run it Install the package for your distribution, on Fedora with `sudo dnf install ./build/out/*.rpm` and on Debian or Ubuntu with `sudo apt install ./build/out/*.deb`. Notes appears in the launcher with its icon. The package is named `gtkx-notes`, which is also what you remove later. The AppImage runs without installing: ```bash ./build/out/Notes-*.AppImage ``` Open the main menu and choose **About Notes**.
The Notes window with the About dialog open: the yellow Notes icon with a Markdown heading mark, the name Notes, the developer GTKX, the version 1.0.0, and Details and Report an Issue rows. The Notes window with the About dialog open in the dark style: the yellow Notes icon with a Markdown heading mark, the name Notes, the developer GTKX, the version 1.0.0, and Details and Report an Issue rows.
Captured from src/components/about.tsx above, after choosing About Notes.
--- --- description: "Give the Flatpak access to the notes folder, build and lint it, and prepare a Flathub submission." --- # Prepare for Flathub Give the sandboxed Notes access to its notes folder, build and lint the Flatpak, and prepare the source build that [Flathub](https://flathub.org/), the app store and build service for Linux, accepts. ## The notes folder in the sandbox A Flatpak runs in a sandbox that sees only the files its permissions grant. Notes reads the `Notes` folder in Documents, so grant that folder. Add a `flatpak` block to `deploy` in `gtkx.config.ts`: ```ts [gtkx.config.ts] flatpak: { finishArgs: ["--filesystem=xdg-documents/Notes:create"], }, ``` `xdg-documents` is the folder that `XDG_DOCUMENTS_DIR` names in `~/.config/user-dirs.dirs`. Desktop sessions such as GNOME set it; without it, the permission grants nothing. The `:create` suffix creates `Notes` there on first launch. GTKX adds these arguments to its defaults, which grant the display, IPC and hardware rendering; see [Customize a package](/v2/guide/deploying#customize-a-package) and the [Flatpak permission reference](https://docs.flatpak.org/en/latest/sandbox-permissions.html). The sandbox reaches no other folder. A folder chosen in Preferences comes through the file chooser portal, which grants access but doesn't report changes other programs make there ([xdg-desktop-portal#567](https://github.com/flatpak/xdg-desktop-portal/issues/567)). A notes folder kept elsewhere needs its own `--filesystem` permission to update live. The build installs the GNOME runtime from Flathub, so add Flathub as a user remote once. GTKX builds with `flatpak-builder` when it is installed and with Flathub's `org.flatpak.Builder` Flatpak otherwise; install the latter, which also carries the linter Flathub runs. Then build the Flatpak: ```bash flatpak remote-add --user --if-not-exists flathub \ https://dl.flathub.org/repo/flathub.flatpakrepo flatpak install --user flathub org.flatpak.Builder npm run deploy -- --target flatpak ``` The bundle is `build/out/dev.gtkx.Notes-1.0.0-x86_64.flatpak`, with `aarch64` on ARM. If the build stops at "Failure spawning rofiles-fuse", see [Flatpak in containers](/v2/guide/deploying#flatpak-in-containers). ## Check the build Flathub reviews every submission with `flatpak-builder-lint`. Lint the generated manifest and the repository the build exported, under `build/arm64/` on ARM: ```bash flatpak run --command=flatpak-builder-lint org.flatpak.Builder \ manifest build/x64/targets/flatpak/dev.gtkx.Notes.yml flatpak run --command=flatpak-builder-lint org.flatpak.Builder \ repo build/x64/targets/flatpak/repo ``` Fix each error, or explain it in the submission; [Flathub's linter documentation](https://docs.flathub.org/linter) describes each check and its exceptions. On a local build, the `repo` check reports `appstream-external-screenshot-url` and `appstream-screenshots-not-mirrored-in-ostree`: only Flathub's build copies the screenshots to Flathub's servers. ## Run it Install the bundle and start Notes: ```bash flatpak install --user build/out/dev.gtkx.Notes-1.0.0-x86_64.flatpak flatpak run dev.gtkx.Notes ``` Notes creates `Documents/Notes` if it doesn't exist and lists the notes in it. A note another program saves there appears in the list. Check the sandbox's permissions: ```bash flatpak info --show-permissions dev.gtkx.Notes ``` ```txt [Context] shared=ipc; sockets=fallback-x11;wayland; devices=dri; filesystems=xdg-documents/Notes:create; ``` ## Submit to Flathub Flathub builds open-source apps from source, so it takes a source-mode manifest, not the prebuilt one above. Push Notes to its own public repository with `package-lock.json` committed, tag a release, and set `deploy.flatpak.mode` to `"source"` with the repository's URL and tag, as [Source Flatpak builds](/v2/guide/deploying#publishing-on-flathub) explains. Install `flatpak-node-generator`, which lists the npm dependencies for Flathub's offline build, then write the manifest and `generated-sources.json` to `build/x64/targets/flatpak/` without building: ```bash npm run deploy -- --target flatpak --print-manifests ``` Flathub verifies that the application ID belongs to you, so replace `dev.gtkx.Notes` with an ID under a domain or repository you control; see [Flathub's requirements](https://docs.flathub.org/docs/for-app-authors/requirements#control-over-domain-or-repository). Then follow [Flathub's submission guide](https://docs.flathub.org/docs/for-app-authors/submission): test the source manifest with its build command and open the pull request with both generated files. Explain the `xdg-documents` permission there, because reviewers check every static permission. ## Next Notes is complete. The guide covers what it didn't need: [Cairo](/v2/guide/cairo) and [OpenGL](/v2/guide/opengl) drawing, [animations](/v2/guide/animations), [forms](/v2/guide/forms), [D-Bus](/v2/guide/dbus), and [workspaces](/v2/guide/workspaces) for apps that share code. ## Contributing to GTKX --- title: Contributing description: "Set up the GTKX repository, locate the code for a change, and check your contribution." --- # Contributing Start with [Development Setup](/contributing/development) to build GTKX and run an example. Read the [Development Principles](/contributing/principles) for package boundaries, coding standards, and testing policy. This section follows `main` and is shared across documentation versions. To build an application, use the versioned [Guide](/v2/guide/getting-started) or [Tutorial](/v2/tutorial/). ## Get oriented | Task | Start here | | ---------------------------------------------------------- | ------------------------------------------------------------------------ | | Find the layer responsible for a bug | [Architecture](/contributing/architecture#finding-the-responsible-layer) | | Find a package, example, or dependency | [Tech Stack](/contributing/tech-stack) | | Change generated bindings or JSX | [Code Generation](/contributing/code-generation) | | Investigate calls, ownership, callbacks, or the event loop | [Native Runtime](/contributing/native-runtime) | | Change props, child placement, signals, or presentation | [React Renderer](/contributing/react-renderer) | | Choose and run checks | [Testing](/contributing/testing) | | Edit the website or promote documentation | [Maintaining Documentation](/contributing/documentation) | | Prepare and publish a release | [Publishing Releases](/contributing/releases) | ## Work with the project Use [issues](https://github.com/gtkx-org/gtkx/issues) for bugs and [Discussions](https://github.com/gtkx-org/gtkx/discussions) for questions and design conversations. The [contribution guide](https://github.com/gtkx-org/gtkx/blob/main/CONTRIBUTING.md) sets the commit, pull request, and version plan requirements for a change. Participation follows the [Code of Conduct](https://github.com/gtkx-org/gtkx/blob/main/CODE_OF_CONDUCT.md). Report vulnerabilities privately through the [security policy](https://github.com/gtkx-org/gtkx/blob/main/SECURITY.md). --- --- title: "Development Setup" description: "Set up the GTKX repository, build packages, run examples, and work on the documentation." --- # Development Setup Build the workspace and run an example while making changes. CI verifies the change through its `Verify workspace` check. The [package map](/contributing/tech-stack#package-map) identifies each package's role. ## Prerequisites Use Linux with Node.js 26.7 or later. The root `package.json` pins pnpm through its `packageManager` field. If [mise](https://mise.jdx.dev/) manages your runtimes, run the commands below through `mise exec --`, for example `mise exec -- pnpm install`. Workspace `tsc` commands use the native TypeScript 7 compiler through the `@typescript/native` dependency alias. The `typescript` catalog entry aliases the TypeScript 6 compatibility package so code generation, Vue tooling, and batched semantic tests keep the stable compiler API. `pnpm exec tsc --version` reports the native compiler and `pnpm exec tsc6 --version` the compatibility compiler. Application templates and the tutorial declare their own TypeScript dependency. Install Rust through [rustup](https://rustup.rs/) so `rust-toolchain.toml` selects the pinned compiler and Clippy. Native formatting and sanitizers use a separate nightly; [Change native code](#change-native-code) shows how to install it. The root `lint` target also needs Go and ShellCheck: its workflow check runs pinned actionlint and yq versions through `go run`, and actionlint checks workflow scripts with ShellCheck. The full workspace needs more system libraries than a minimal application: | Work | System dependencies | | --------------------------------- | --------------------------------------------------------------------------------------------------------------------- | | Native addon and bindings | A C build toolchain, `pkg-config`, GObject Introspection, GLib, GTK4, and libadwaita development files. | | Workspace library selection | GtkSourceView 5 and WebKitGTK 6.0 development files and GIR metadata. | | Native integration fixtures | Git, Meson, Ninja, and the introspection scanner. | | Headless examples and tests | Sway, `dbus-daemon`, Mesa rendering support, fonts, icons, MIME data, and GSettings schemas. | | Localization and packaging checks | GNU gettext and the packaging tools used by the target formats, including RPM and Debian tooling and Flatpak helpers. | GTKX's application baseline is GTK 4.20 and libadwaita 1.8 or later. The full workspace needs GTK 4.22 and libadwaita 1.9 for the GTK and Adwaita demos. Distribution package names and available versions vary. The [CI setup action](https://github.com/gtkx-org/gtkx/blob/main/.github/actions/setup-ci/action.yml) installs the complete verification environment on Ubuntu 26.04, including packaging tools and fonts. On Debian or Ubuntu releases providing those library versions, the development packages include: ```bash sudo apt install build-essential pkg-config gobject-introspection \ libgirepository1.0-dev libgtk-4-dev libadwaita-1-dev \ libgtksourceview-5-dev libwebkitgtk-6.0-dev meson ninja-build ``` This command covers native development and fixtures, not the full headless and packaging environment listed above. Check the installed library versions before building: ```bash pkg-config --modversion gtk4 libadwaita-1 ``` ## Clone and build Clone the repository, or substitute your fork's URL: ```bash git clone https://github.com/gtkx-org/gtkx.git cd gtkx pnpm install pnpm build ``` `pnpm install` links workspace dependencies, prepares the generated binding aliases, and builds the Vitest plugin's TypeScript output through the root postinstall script. `pnpm build` runs Nx's build targets with their dependencies. This includes the native addon, generated bindings, TypeScript libraries, application bundles, and website build where those targets exist. The first full build compiles native code, generates OpenGL bindings, and generates the website API references. Building references for a pinned documentation version may also need network access to retrieve that release's source and dependencies. For subsequent work, use the target for the package you are changing: ```bash pnpm nx run @gtkx/react:build ``` Nx runs the required dependency targets. A package build can therefore rebuild another package or regenerate bindings first. Inspect the graph and an individual project's targets with: ```bash pnpm nx show projects pnpm nx show project @gtkx/react ``` Use `pnpm format` to apply [Oxfmt](https://oxc.rs/docs/guide/usage/formatter) to handwritten JavaScript, TypeScript, Vue, styles, configuration, and Markdown files. CI checks the same files as part of linting. To format only files changed from `main`, run `pnpm nx format:write --base=origin/main`; Nx detects the root `.oxfmtrc.json` configuration. The formatter preserves import and package manifest ordering. Generated outputs, test fixtures, changelogs, and generated agent instructions are excluded. Embedded code formatting is disabled so tutorial code fences and their patches remain unchanged. Rust formatting uses the pinned nightly rustfmt described below. ## CI environment [Testing](/contributing/testing#ci-verification-and-failure-reproduction) describes which targets CI runs, the `Verify workspace` check, and how to reproduce a failure. This section covers the environment those checks run in. CI uses the Nx [affected graph](https://nx.dev/docs/features/ci-features/affected) to select projects. Pull requests compare against their merge base, pushes against the last successful run on `main`, and merge queues against the previous merge-group commit. With an Nx Cloud token on a trusted checkout, the `verify` job distributes tasks to [Nx Agents](https://nx.dev/docs/features/ci-features/distribute-task-execution), with more agents for larger change sets. The GitHub coordinator and the agents use the same Ubuntu 26.04 image built from `.github/ci/Dockerfile`, which also pins Node.js; Nx runs directly inside that image. The `image` job creates the versioned GHCR image from `.nx/workflows/agents.yaml` if it does not exist, then resolves its digest for the coordinator. Published image tags are never overwritten. Bump the image version in `agents.yaml` whenever the Dockerfile, its Node or Go pins, the root package manager pin, or either Rust toolchain changes. Bump it also when refreshing distribution packages. Agent initialization restores dependency downloads and Rust build artifacts, then installs workspace dependencies. Custom managed images require the Nx Cloud dedicated compute add-on. The first publication creates a private GHCR package: make the `gtkx-ci` package public in its package settings, then rerun CI so Nx Agents can pull it. Image publication uses the repository's GitHub token and runs only for trusted checkouts with an Nx token. No separate registry credential is required. Fork pull requests and runs without an Nx token use the same Nx task graph directly on one Ubuntu 26.04 runner. The shared `.github/actions/setup-ci` action installs that fallback environment, selects Node.js from `engines.node` in the root `package.json`, and restores package and Rust caches. The publishing workflow selects Node.js the same way. Nx schedules independent tasks in parallel and uses remote caching when an access token is available. Runtime and native environment fingerprints are included in cache inputs so system library and toolchain changes invalidate the relevant tasks. Typed Oxlint and scoped ESLint checks depend on built package declarations. Their cache inputs include dependent declarations and the lockfile; the shared compiler-version input also invalidates tasks when the native TypeScript compiler changes. Nx's standard TypeScript, Oxlint, ESLint, and Vitest plugins infer package targets. Other project commands run directly and declare their dependencies and cache outputs in `project.json`. When Nx Cloud is enabled, CI records the Rust advisory audit, requests fixes for failures, and closes the run after checks finish, including after failures. Publication, Pages deployment, and release management remain in their own GitHub Actions workflows. ## Generated bindings The root `gtkx.config.base.ts` defines the shared configuration imported by workspace packages. It selects the workspace's additional native libraries. The root generation targets select it explicitly with `--config`; package and application configs keep the normal `gtkx.config.ts` filename. Codegen reads `GTKX_GIR_PATH` when GIR files are installed outside the normal search paths. Regenerate the workspace's bindings and other codegen targets through Nx: ```bash pnpm codegen ``` For only the root bindings, TypeScript declarations, and widget reference: ```bash pnpm nx run gtkx:codegen ``` The `bindings` target runs the compiled generator with `gtkx.config.base.ts`. It depends only on the generator's build; renderer metadata lives in the config package so React does not need to build first. Packages that consume generated bindings depend on this target explicitly. The public `codegen` target runs the built CLI and also refreshes `.gtkx/reference`. `pnpm codegen` bypasses Nx task-result caching so explicit regeneration also refreshes the generated blocks in `AGENTS.md` and `CLAUDE.md`. These files can contain developer-owned instructions and are never restored from a shared cache. Dependency builds use cached binding and reference outputs during ordinary CI tasks. Each application example has its own configuration and codegen target. Its build and development targets refresh project declarations and reuse the workspace bindings. Generated bindings live in the root `node_modules/.gtkx`, with package links under `node_modules/@gtkx`; generated widget reference pages live in the root `.gtkx/reference`. Change the generator, configuration, or source metadata when correcting generated behavior, then regenerate. Editing a generated output alone will be lost on the next run. For widget work, read `.gtkx/reference/index.md` to find the available element props, signals, and methods. [Configuration and Codegen](/v2/guide/configuration-and-codegen) covers the application's view of these outputs. ## Run an example Use an example that exercises the behavior you are changing: ```bash pnpm nx run hello-world:dev ``` The `hello-world` example is a small application shell and counter. `gtk-demo` covers a wider set of native widgets. `adwaita-demo` reimplements the official libadwaita 1.9.3 demo, including its adaptive navigation, controls, dialogs, animations, and tab windows; it needs libadwaita 1.9 or later. `storybook-example` launches the native story explorer: ```bash pnpm nx run gtk-demo:dev pnpm nx run adwaita-demo:dev pnpm nx run storybook-example:dev ``` Run these separately as needed. The development target builds dependencies, refreshes generated declarations, and starts the CLI. Changes to application components participate in Fast Refresh. When editing framework packages, rebuild the affected package and restart the example as needed so it loads the changed output. After the initial dependency build, the example's local CLI can also start a headless session: ```bash pnpm --filter hello-world exec gtkx dev --headless --size 1280x720 ``` Use Ctrl+C to stop the development session and release its headless resources. Use the live widget tree, interactions, and screenshots to verify visible changes. The [MCP guide](/v2/guide/mcp) explains how to connect, and the [Storybook guide](/v2/guide/storybook) covers controls and reusable stories. ## Change native code Rust source lives in `packages/native/src`. Formatting and sanitizers use the nightly pinned in [packages/native/tools/rust-toolchain.toml](https://github.com/gtkx-org/gtkx/blob/main/packages/native/tools/rust-toolchain.toml). After `pnpm install`, install that toolchain from the repository root: ```bash (cd packages/native/tools && rustup show) ``` Rebuild after changing native code, then start a fresh app or test process to load the new binary: ```bash pnpm nx run @gtkx/native:build ``` The build invokes `napi build` in release mode and produces the platform-specific `.node` file and generated addon declarations. CI runs the pinned nightly rustfmt check, Clippy with warnings treated as errors, and cargo-audit against the current RustSec advisories. Changes that affect ownership, callbacks, marshalling, or teardown also belong in the native integration coverage described in [Testing](/contributing/testing#native-fixtures-and-sanitizers). ## Work on the website Start the site from the repository root: ```bash pnpm nx run @gtkx/website:dev ``` `@gtkx/website:preview` builds the site and serves the production output. Prose lives in Markdown; navigation, versioning, and theme behavior live in `website/.vitepress`. The Contributing section is shared at `/contributing/`, while Guide, Tutorial, and API Reference pages follow the prefixes declared in `website/versions.json`. [Maintaining Documentation](/contributing/documentation) covers style, generated API pages, page registration, version manifests, and promotion. ## Prepare a change for review Add coverage in the suite that owns the behavior, then rely on CI's `Verify workspace` check; [Testing](/contributing/testing) describes coverage ownership and how to reproduce a failing target. Changes to public APIs, application behavior, or developer workflows need an Nx version plan from `pnpm plan`. The [contribution guide](https://github.com/gtkx-org/gtkx/blob/main/CONTRIBUTING.md#add-a-version-plan) explains which changes need one and how to write it. [Publishing Releases](/contributing/releases) is for maintainers. --- --- title: "Tech Stack" description: "The languages, native libraries, packages, and development tools behind GTKX 2." --- # Tech Stack This page maps the technologies and packages on `main`. The [architecture overview](/contributing/architecture) traces how they communicate. Dependency ranges live in [package manifests](https://github.com/gtkx-org/gtkx/tree/main/packages) and the shared [pnpm catalog](https://github.com/gtkx-org/gtkx/blob/main/pnpm-workspace.yaml). The pnpm and Cargo lockfiles record the resolved dependency versions. ## Languages and execution | Technology | Role in GTKX | | ------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------- | | TypeScript 7 | Native compiler for workspace builds, typechecking, and CLI consumer checks. TypeScript 6 supplies the compiler API to code generation, Vue tooling, and tests. | | Oxc transformer | Emits generated GI and JSX store JavaScript and declarations; codegen falls back to TypeScript 6 without it. | | React 19 | Supplies components, hooks, state, context, and scheduling. `react-reconciler` connects React commits to GTKX's native element tree. | | Node.js 26.7 or later | Runs application JavaScript, loads the native addon, and provides the Node APIs used by applications and tooling. | | Rust, edition 2024 | Implements the native bridge, native value conversion, object lifetime handling, callbacks, and integration with the GLib main context. | | C ABI and GObject Introspection | Describe the native functions, types, properties, signals, and ownership information that code generation translates into JavaScript and TypeScript. | The framework workspace packages use ECMAScript modules and NodeNext module resolution. The website and generated compiler configuration use bundler resolution. The shared compiler configuration enables strict checking, exact optional properties, checked indexed access, and project references. Library builds emit JavaScript, declarations, and source maps into each package's `dist/` directory. Shared TypeScript path aliases let workspace tooling resolve package source during development, and package TypeScript configurations extend the shared base. Workspace scripts run directly with Node's TypeScript support where possible. Scripts that load generated bindings run with `node --import ./scripts/register-workspace-loader.ts` from the repository root. This preload registers `tsx` and applies the shared aliases to imports inside generated packages under `node_modules`. Generated bindings and handwritten code then resolve to the same workspace modules. Vitest uses the same aliases. Rust is pinned by [rust-toolchain.toml](https://github.com/gtkx-org/gtkx/blob/main/rust-toolchain.toml). The addon is built with `napi-rs` as a Node-API module. It uses `libloading` to resolve native libraries and `libffi` to invoke functions described by generated metadata. The `glib` crate provides the Rust integration with GLib. Prebuilt native npm packages target x64 and arm64 Linux with glibc. ## Native platform | Library or subsystem | Responsibility | | --------------------------- | ------------------------------------------------------------------------------------------------------------------- | | libadwaita | Application windows, navigation, dialogs, preferences, adaptive layouts, and GNOME presentation patterns. | | GTK4 and GDK | Widgets, layout, input, accessibility, drawing surfaces, and display integration. | | GLib, GObject, and GIO | Main contexts, reference-counted objects, properties, signals, files, settings, D-Bus, and asynchronous operations. | | Cairo | Immediate-mode 2D drawing exposed through `@gtkx/cairo`. | | OpenGL | GPU drawing exposed through `@gtkx/gl` and GTK's GL areas. | | GtkSourceView and WebKitGTK | Source editing and embedded web content, added to the default libraries by the repository's `gtkx.config.base.ts`. | | Wayland and D-Bus | Isolated displays and session services for headless development and tests. | Applications need GTK 4.20 and libadwaita 1.8 or later. Code generation reads the GIR files installed on the development machine, so the available bindings follow that machine's libraries and the project's configuration. [Development Setup](/contributing/development#prerequisites) lists the versions and development files the whole workspace needs. The generated `@gtkx/gi` and `@gtkx/jsx` packages belong to each project. Their namespace exports provide native classes and functions, and JSX elements, respectively. They are generated by `gtkx codegen` and linked into the project's `node_modules`; they are not published npm packages to install separately. See [Configuration and Codegen](/v2/guide/configuration-and-codegen). ## Package map All paths below are relative to the repository root. Package names normally match their directory under `packages/`; `packages/create-gtkx` publishes as `create-gtkx`. The map describes current package contents; [Development Principles](/contributing/principles) defines their required boundaries. ### Core and generation | Package | Responsibility | | --------------- | ------------------------------------------------------------------------------------------------------------------------------- | | `@gtkx/native` | Rust addon and JavaScript bootstrap for calls into native libraries, object lifetimes, callbacks, and main-context integration. | | `@gtkx/runtime` | Object wrappers, value conversion, signals, and GObject class registration for generated bindings. | | `@gtkx/codegen` | Parses GIR and Khronos metadata and generates bindings, JSX definitions, and reference documentation. | | `@gtkx/config` | Loads and validates project configuration and supplies element and prop mappings. | | `@gtkx/react` | React renderer, native element tree, application roots, portals, and integration with GTKX configuration and runtime. | | `@gtkx/utils` | Shared utilities used across the runtime and toolchain. | ### Application libraries | Package | Responsibility and upstream foundation | | ------------------ | --------------------------------------------------------------------------------------------------------------------------- | | `@gtkx/components` | Collection views, dropdowns, combo rows, and toast helpers built on the GTKX renderer. | | `@gtkx/navigation` | Stack, tab, tab view, drawer, and split-view navigators, using React Navigation's core and routers with Adwaita containers. | | `@gtkx/forms` | React Hook Form integration for native controls. | | `@gtkx/animated` | React Spring integration with the native frame clock. | | `@gtkx/css` | CSS-in-JS using Emotion serialization and PostCSS, installed into GTK's CSS system. | | `@gtkx/i18n` | i18next and react-i18next integration with GNU gettext catalogs. | | `@gtkx/cairo` | Typed wrappers around Cairo drawing APIs. | | `@gtkx/gl` | Generated OpenGL 4.6 core bindings and shader diagnostics. | ### Development and verification | Package | Responsibility | | ----------------- | ------------------------------------------------------------------------------------------------------------------------------------------------- | | `@gtkx/cli` | The [`gtkx` commands](/v2/guide/cli) for development, builds, code generation, deployment, and upgrades; integrates Vite with the native runtime. | | `create-gtkx` | Interactive and noninteractive project scaffolding and starter templates. | | `@gtkx/storybook` | Native story explorer, controls, actions, and reusable Component Story Format fixtures. | | `@gtkx/mcp` | MCP server for generated references, live widget inspection, and application interaction. | | `@gtkx/testing` | Rendering, accessible widget queries, user input, assertions, and screenshots for tests. | | `@gtkx/vitest` | Worker preload and isolated headless display and session-bus infrastructure. | | `@gtkx/e2e` | Private integration suite spanning the renderer, generated bindings, runtime, native bridge, and testing APIs. | ## Build and development tools pnpm manages the workspace and its shared dependency catalog. Nx discovers TypeScript, Oxlint, scoped ESLint, and Vitest targets, combines them with explicit package targets, orders their dependencies, and caches eligible results. `pnpm build` builds the workspace for development. [Testing](/contributing/testing#ci-verification-and-failure-reproduction) describes the targets CI runs. The CLI uses Vite for application development and bundling. Its plugin stack integrates generated bindings, native assets, styles, settings, localization, and the application runtime. SWC transforms TypeScript and JSX for Fast Refresh during development; the React Compiler runs through Babel, and React Fast Refresh updates components in a running development session. Vitest runs the JavaScript test suites. GTKX's plugin gives workers real headless Wayland displays, while the testing package works with native widgets and accessibility information. Upstream native fixtures are built with Meson and Ninja; local C fixtures use GCC. The native `test-asan` target uses AddressSanitizer and LeakSanitizer. Oxlint runs JavaScript, typed TypeScript, React, and Vitest rules from `.oxlintrc.json`. The compiler and linter are pinned separately because Oxlint ships its own native type checker. `eslint.config.ts` covers what Oxlint does not: Vue files, the typed Vitest `unbound-method` rule, and React Hooks rules scoped to files that Oxlint misclassifies. Oxfmt checks handwritten source and configuration formatting. Codescythe checks unused files and exports, and Rust uses rustfmt and Clippy. Shared target defaults are declared in [nx.json](https://github.com/gtkx-org/gtkx/blob/main/nx.json), project targets and overrides in `project.json`, and package scripts in `package.json`. ## Documentation, examples, and distribution The website uses VitePress, Vue, and Shiki. Its prose lives under `website/`, and TypeDoc with its Markdown and VitePress integrations generates the working-tree API reference from public package source entrypoints after dependency builds. [website/versions.json](https://github.com/gtkx-org/gtkx/blob/main/website/versions.json) controls version labels, URL prefixes, and whether an API reference comes from the working tree or a pinned release tag. `@gtkx/testing` renders the windows of [pictured samples](/contributing/documentation#pictured-samples). [`examples/`](https://github.com/gtkx-org/gtkx/tree/main/examples) contains runnable applications, the GTK and Adwaita demos, and native stories. Examples consume workspace packages. `tutorial/` lives outside the pnpm workspace so the tutorial can also verify installation and execution as an external consumer. GitHub Actions runs checks, prepares releases, publishes packages, and deploys the website to GitHub Pages. Nx version plans record published-package changes. CLI and codegen tests use temporary consumers linked to workspace packages; the tutorial consumes registry packages independently. Application distribution through `gtkx deploy` supports Flatpak, Debian packages, RPM packages, and AppImage; see [Deploying](/v2/guide/deploying) for those application workflows. Continue with [Development Setup](/contributing/development) to build the workspace, or [Testing](/contributing/testing) to understand CI coverage and reproduce failures. --- --- title: "Architecture" description: "How GTKX's generated bindings, React renderer, TypeScript runtime, and Rust native bridge fit together." --- # Architecture GTKX runs React in Node.js and renders through native Adwaita and GTK4 objects. React owns state and reconciliation; native libraries supply application structure, widgets, layout, input, accessibility, and rendering. ## The core layers The [package map](/contributing/tech-stack#package-map) lists package responsibilities. At runtime, a JSX update follows this path: ```text Application components ↓ Generated @gtkx/jsx elements ↓ @gtkx/react renderer ↓ Generated @gtkx/gi methods ↓ @gtkx/runtime ↓ @gtkx/native ↓ Native libraries ``` The [renderer](https://github.com/gtkx-org/gtkx/tree/main/packages/react) translates React commits into native operations. Generated methods supply signatures to the [runtime](https://github.com/gtkx-org/gtkx/tree/main/packages/runtime), which converts values and calls the [native bridge](https://github.com/gtkx-org/gtkx/tree/main/packages/native). GI bindings also work without React: generated functions and classes call the runtime themselves, and GObject subclasses register through `registerClass` from `@gtkx/runtime` (see [Subclassing](/v2/guide/subclassing)). Component libraries build on JSX and GI APIs and do not depend on how native pointers are represented. ## Generation and execution GTKX reads [GObject Introspection](https://gi.readthedocs.io/en/latest/) Repository (GIR) files during code generation, before the application runs. ```text GIR libraries + element configuration ↓ @gtkx/codegen ↓ @gtkx/gi + @gtkx/jsx + project reference ``` During generation, `@gtkx/codegen` reads the configured GIR libraries and their transitive dependencies. It determines JavaScript names, TypeScript types, callable signatures, transfer rules, and the metadata needed by the renderer. It emits two linked package stores, `@gtkx/gi` and `@gtkx/jsx`, plus a project reference when enabled. During execution, Node imports the generated ESM classes and methods. Their descriptors tell `@gtkx/runtime` and the native bridge how to resolve and call functions in the installed shared libraries through libffi. Native type lookup and GObject property access happen at runtime. GIR analysis belongs to code generation; `@gtkx/runtime` receives call descriptors from its consumers and does not load libgirepository. The project's library selection and GIR versions define the generated API. Changing a GIR search path changes generated declarations; it does not install a native library that implements those declarations. See [Configuration and Codegen](/v2/guide/configuration-and-codegen) for the application-facing configuration. The entry points for this boundary are the [codegen runner](https://github.com/gtkx-org/gtkx/blob/main/packages/codegen/src/runner.ts), the [runtime callable adapter](https://github.com/gtkx-org/gtkx/blob/main/packages/runtime/src/fn.ts), and the [native binding API](https://github.com/gtkx-org/gtkx/blob/main/packages/native/src/api/bind.rs). ## A render and an interaction Consider a component that renders a button and updates a label when the button is clicked. Its path through GTKX is: 1. The generated JSX component turns its props into a React host element identified by its GType name. Element-valued props become named child slots. 2. React reconciles the tree and asks GTKX's host configuration to create or update an instance. 3. The renderer uses generated metadata and registered element behaviors to construct the native object, apply values, and place children through the appropriate container API. 4. Generated GI methods describe the native calls. Runtime converts their arguments, and the Rust addon prepares native storage and invokes the underlying C functions. 5. GTK delivers the button's signal through the GLib main context. The runtime calls the connected JavaScript handler, and the renderer gives that handler React's discrete event priority. 6. The handler changes React state. React reconciles again, and the renderer updates the existing native label where the element's identity permits reuse. React's component tree and the native object tree have different shapes. Function components have no native object of their own. Named slots and parent-created page objects introduce additional routing, and portals can place a native object outside its surrounding React subtree while preserving React context. The [renderer page](/contributing/react-renderer) explains those differences. ## One owning event-loop thread The native addon acquires GLib's default [main context](https://docs.gtk.org/glib/main-loop.html) on the Node thread that initializes it. It integrates that context with [libuv](https://docs.libuv.org/en/v1.x/) using prepare, timer, and file-descriptor polling handles. Node remains the outer event loop, allowing Node I/O, timers, promises, React scheduling, and GLib sources to make progress in the same application process. Application startup is adapted to that arrangement. The generated GIO application override invokes GLib's local command-line handling to register and activate an application without entering a blocking `g_application_run()` loop. The application keeps the Node loop alive while active, and its teardown releases that hold. React's application component waits for activation before rendering its children. The owning-thread requirement extends to native wrappers and widget operations. Worker threads are useful for computation with plain data, which can be sent back to the owning thread. They are not additional GTK render threads. Details and source links are in [Native Runtime](/contributing/native-runtime). ## State and ownership Component, wrapper, and native allocation lifetimes have separate owners: | Lifetime | Owner | GTKX's role | | --------------------------- | ------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------ | | Component lifetime | React's tree, keys, and effects. | Mount, update, and unmount host instances; release renderer handlers and behaviors. | | JavaScript wrapper lifetime | JavaScript reachability and native wrapper references. | Preserve wrapper identity for tracked native objects and associate wrappers with native handles. | | Native allocation lifetime | GObject reference counts or each native type's copy, reference, and free operations. | Honor ownership descriptors and release allocations through the correct mechanism. | Unmounting a component removes its placement and renderer-managed connections. Other JavaScript or native references can keep the object alive. Windows and dialogs also have explicit presentation and close behavior. When investigating a memory bug, check both the React lifetime and the native ownership contract. A controlled prop and a native widget property represent the same application state. Writing a prop can itself emit a native signal. The renderer tracks its own mutations and suppresses configured user-event signals caused by those writes so they do not become feedback loops. User input continues through the connected handler. ## Finding the responsible layer | Observable problem | Start reading | | ---------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------- | | A generated method has an incorrect type, argument order, or return shape. | `packages/codegen/src/gir`, `analysis`, and `store/gi`. | | A correctly described call produces an invalid value or loses native memory. | `packages/runtime/src/fn.ts`, then `packages/native/src/ffi/codec` and `packages/native/src/handle.rs`. | | A JSX prop is missing or has the wrong type. | `packages/codegen/src/store/jsx` and `packages/config/src/builtin-elements.ts`. | | A prop type is correct but the widget receives the wrong update. | `packages/react/src/reconciler/apply-props.ts` and the registered element behaviors. | | A child appears in the wrong place, disappears, or fails to reorder. | `packages/react/src/reconciler/child-routing.ts` and `placement.ts`. | | Signals, timers, or shutdown stop making progress. | `packages/codegen/overrides/gio/overrides/application.ts`, `packages/runtime/src/lifecycle.ts`, and `packages/native/src/runloop.rs`. | A renderer symptom can begin in generated metadata; a native ownership failure can begin in an incorrect GIR annotation. Follow the failing operation across the relevant boundaries. --- --- title: "Code Generation" description: "How GTKX turns GIR libraries into project-specific JavaScript bindings, JSX components, metadata, and reference documentation." --- # Code Generation `@gtkx/codegen` reads the [GObject Introspection](https://gi.readthedocs.io/en/latest/) (GIR) files of a project's libraries and emits executable ESM bindings, TypeScript declarations, JSX components, and reference pages. Its generated descriptors give `@gtkx/runtime` the native call signatures, so the runtime never loads libgirepository to discover them. The public generation entry point is [`packages/codegen/src/runner.ts`](https://github.com/gtkx-org/gtkx/blob/main/packages/codegen/src/runner.ts). The CLI integrates it with project configuration in [`packages/cli/src/codegen/run-codegen.ts`](https://github.com/gtkx-org/gtkx/blob/main/packages/cli/src/codegen/run-codegen.ts). For command usage and library configuration, see [Configuration and Codegen](/v2/guide/configuration-and-codegen). ## Inputs and outputs | Input | What it controls | | --------------------------------------- | --------------------------------------------------------------------------------------------- | | Selected GIR roots | Which namespaces are bound, together with everything their GIR files include. | | GIR search paths | Which installed or project-provided GIR files supply those namespaces. | | GIR annotations | Types, nullability, argument directions, ownership, callback scopes, and native symbol names. | | GTKX's element configuration | Component wrappers, additional props, omitted props, and parent-created elements. | | Project element configuration | Project-specific additions and overrides to those element definitions. | | Installed runtime and renderer versions | Versions recorded in the generated stores and inputs to their freshness checks. | Adwaita's `Adw-1` is the default root. Its dependencies include GTK4, GDK, GIO, GObject, and GLib. Configuring additional libraries extends that dependency graph. The selection logic is in [`gir/libraries.ts`](https://github.com/gtkx-org/gtkx/blob/main/packages/codegen/src/gir/libraries.ts). The main outputs are: | Output | Contents | | ---------------------------------- | -------------------------------------------------------------------------------------------------------------- | | `@gtkx/gi/` | JavaScript classes, records, interfaces, constants, functions, bootstrap code, and their `.d.ts` declarations. | | `@gtkx/jsx/` | React element components and prop declarations, with references to the corresponding GI classes. | | Class metadata and element records | Property names, flags and defaults; signal mappings; generated element configuration. | | `.gtkx/reference` | The project's generated element reference, when reference generation is enabled. | The stores normally live under `node_modules/.gtkx/gi` and `node_modules/.gtkx/jsx`, with package links under `node_modules/@gtkx`. They are generated packages; there are no handwritten `packages/gi` or `packages/jsx` source packages to edit. ## Parsing a library graph [`Library.load`](https://github.com/gtkx-org/gtkx/blob/main/packages/codegen/src/gir/library.ts) starts with the requested roots and follows their GIR includes. It first discovers namespace headers and registers namespace shells, then populates their bodies and adds declarations to shared type tables. This lets the parser resolve references across namespaces and declarations that appear later in a file. The parsed model in `src/gir` represents classes, interfaces, records, callbacks, callable parameters, properties, enums, and container types. A `TypeId` identifies a slot within a namespace's type table. Subsequent passes resolve those identities through the `Library` instead of repeatedly interpreting XML or comparing raw type strings. [GIR annotations](https://gi.readthedocs.io/en/latest/annotations/giannotations.html) affect runtime correctness as well as documentation. An array's companion length parameter, a callback's user-data and destroy parameters, a nullable pointer, and a transfer-full return each change the descriptor the native bridge needs. Targeted annotation corrections live alongside the parser in files such as `transfer-overrides.ts` and `direction-overrides.ts`. ## Type analysis and callable shaping The `src/analysis` modules turn the parsed model into TypeScript types and runtime descriptor expressions. Both describe the same native contract. A method's public signature may omit bookkeeping arguments while its native signature must retain them. The callable pipeline accounts for these differences: - Array lengths and callback bookkeeping can be derived or folded into the values exposed to JavaScript. - Out parameters become returned values; a C return and output parameters may become a tuple. - A trailing `GError**` becomes exception behavior while remaining an argument in the native call. - Recognized asynchronous start/finish pairs gain promise-based wrappers. - Records need field sizes, offsets, alignment, and ownership information in addition to their declared field types. The mapping is implemented across [`analysis/param-structure.ts`](https://github.com/gtkx-org/gtkx/blob/main/packages/codegen/src/analysis/param-structure.ts), [`store/gi/param-marshal.ts`](https://github.com/gtkx-org/gtkx/blob/main/packages/codegen/src/store/gi/param-marshal.ts), [`store/gi/return-wrap.ts`](https://github.com/gtkx-org/gtkx/blob/main/packages/codegen/src/store/gi/return-wrap.ts), and [`store/gi/async.ts`](https://github.com/gtkx-org/gtkx/blob/main/packages/codegen/src/store/gi/async.ts). Descriptor construction and descriptor rendering are separate from the general TypeScript writer. ## Emitting GI bindings [`store/gi/pipeline.ts`](https://github.com/gtkx-org/gtkx/blob/main/packages/codegen/src/store/gi/pipeline.ts) emits namespace types and members. Interfaces are emitted before the classes that implement them, and classes within a namespace are ordered so their parent declarations are available. Generated class and interface registration connects their JavaScript representations to the runtime's GType registry. Each namespace has its main binding module and a bootstrap module. The bootstrap imports dependent namespace bootstraps, applies runtime overrides, and performs required registration or retention work. It also calls the namespace's top-level `init` function when GIR lets it be called without arguments, so `gst_init` runs before any GStreamer plugin namespace loads. Bootstraps register no library teardown; process exit releases the libraries. The public namespace barrel imports that bootstrap. The generated package marks bootstrap, override, and index modules as side effects so bundling can preserve initialization while eliminating unused exports where possible. Overrides under [`packages/codegen/overrides`](https://github.com/gtkx-org/gtkx/tree/main/packages/codegen/overrides) are TypeScript modules compiled into the generated package. They attach runtime helpers and library-specific adaptations to generated declarations, including application lifecycle methods, non-introspectable functions, and upstream compatibility fixes. The `OVERRIDES` catalog in [`store/gi/overrides.ts`](https://github.com/gtkx-org/gtkx/blob/main/packages/codegen/src/store/gi/overrides.ts) drives module discovery, bootstrap imports, and barrel exports. The `cairo` namespace is not generated: bindings import it from the `@gtkx/cairo` package. The runtime installs each class's interfaces as mixins, and the class declaration lists those interfaces. The signal methods (`connect`, `on`, `once`, `off`, `emit`, `disconnect`) are typed by shared runtime types; generated metadata names each class's signals. GI methods generally defer descriptor construction and native binding through runtime factories. Runtime resolves the native symbol lazily on the first call. Importing a namespace and calling one of its methods therefore have different initialization costs; see [Native Runtime](/contributing/native-runtime). ## Emitting JSX and renderer metadata The JSX pipeline uses the same parsed library to identify element classes and derive prop and signal types. It combines those with GTKX's built-in element configuration and the project's custom configuration. [`packages/config/src/builtin-elements.ts`](https://github.com/gtkx-org/gtkx/blob/main/packages/config/src/builtin-elements.ts) can be imported without loading native bindings. It describes which props an element adds or omits, which component factory wraps it, and whether its parent creates the underlying object. The renderer defines attachment and update behavior in `packages/react/src/element-behaviors.ts`. Generated element components call the renderer's `createElementComponent` factory with the GType name and class reference. Each generated class registers its property and signal metadata, so retaining the class also preserves that metadata in production bundles and application subclasses. An inherited wrapper can add application, window, or dialog lifecycle behavior. The main sources are [`store/jsx/pipeline.ts`](https://github.com/gtkx-org/gtkx/blob/main/packages/codegen/src/store/jsx/pipeline.ts), [`store/jsx/element-components.ts`](https://github.com/gtkx-org/gtkx/blob/main/packages/codegen/src/store/jsx/element-components.ts), and [`store/gi/element-metadata.ts`](https://github.com/gtkx-org/gtkx/blob/main/packages/codegen/src/store/gi/element-metadata.ts). The [React Renderer](/contributing/react-renderer) page follows these outputs into a mounted tree. ## Store placement, freshness, and publication Store placement follows package resolution. [`resolve-store.ts`](https://github.com/gtkx-org/gtkx/blob/main/packages/codegen/src/store/resolve-store.ts) finds the installed runtime and renderer, selects a `node_modules` location their consumers can reach, and keeps both generated packages together. Hoisted dependencies can therefore cause multiple workspace projects to share one store. The resolver rejects arrangements where a consumer sits above the generated packages and cannot import them. A project whose store sits in another `node_modules`, such as a pnpm workspace root, gets a view in its own: real `@gtkx/gi` and `@gtkx/jsx` packages. Namespaces of the project's libraries and their GIR includes are symlinks into the shared store, so every importer loads the same files. Every other namespace exports a declaration-only stub, so importing it fails to typecheck instead of TypeScript falling back to the full store. The GI store records each namespace's includes for this in `namespaces.json`; [`store/store-views.ts`](https://github.com/gtkx-org/gtkx/blob/main/packages/codegen/src/store/store-views.ts) writes the views. Generation acquires store locks, prepares new output in staging directories, and publishes the prepared stores and links together. Failed preparation preserves generated sources for diagnosis. The store code also restores missing links and reclaims stale staging or generation artifacts. This machinery is in [`staging.ts`](https://github.com/gtkx-org/gtkx/blob/main/packages/codegen/src/staging.ts) and [`store/store-fs.ts`](https://github.com/gtkx-org/gtkx/blob/main/packages/codegen/src/store/store-fs.ts). Freshness is content-based. The GI fingerprint covers the generator, relevant dependency versions, overrides, selected roots, search paths, store version, and GIR contents. JSX has its own fingerprint for the renderer version and element configuration; regenerating GI also invalidates JSX. Documentation fingerprints include their rendering options and element configuration. These checks are implemented in [`fingerprint.ts`](https://github.com/gtkx-org/gtkx/blob/main/packages/codegen/src/fingerprint.ts). The store compiler uses [Oxc](https://oxc.rs/) to emit JavaScript and isolated declarations, then removes the temporary TypeScript sources after successful emission unless `shouldKeepSources` is set. Declarations retain documentation; JavaScript retains pure annotations for tree shaking and drops other comments. A TypeScript emitter handles environments where the native transformer bindings cannot load, including Node's `--no-addons` mode. Emission diagnostics live in [`compile.ts`](https://github.com/gtkx-org/gtkx/blob/main/packages/codegen/src/compile.ts), with native emission in [`store/transpile.ts`](https://github.com/gtkx-org/gtkx/blob/main/packages/codegen/src/store/transpile.ts). Store emission does not run full semantic checking. The OpenGL generator separately checks its generated sources through `checkModules`, also with `skipLibCheck: true`. ## Reference documentation and OpenGL Element reference pages reuse the GIR model, type rendering, and element prop configuration. [`docs/pipeline.ts`](https://github.com/gtkx-org/gtkx/blob/main/packages/codegen/src/docs/pipeline.ts) produces pages for URL-based website navigation or file-based project references. The CLI writes `.gtkx/reference` through [`codegen/reference.ts`](https://github.com/gtkx-org/gtkx/blob/main/packages/cli/src/codegen/reference.ts). OpenGL bindings have a separate input pipeline under [`src/khronos`](https://github.com/gtkx-org/gtkx/tree/main/packages/codegen/src/khronos). It parses the bundled [Khronos OpenGL registry](https://github.com/KhronosGroup/OpenGL-Registry) (`gl.xml`), the source of the OpenGL function signatures, then selects and plans supported bindings and renders the modules used by `@gtkx/gl`. ## Verifying a change When investigating a binding, compare the GIR signature, the generated JavaScript adapter, its `.d.ts` signature, and the runtime descriptor. A declaration-only change cannot repair a native argument that is marshalled incorrectly. The [codegen tests](https://github.com/gtkx-org/gtkx/blob/main/packages/codegen/tests/codegen.test.ts) generate stores in temporary projects and typecheck representative valid and invalid GI and JSX consumers. Those projects use `skipLibCheck: true` and link workspace packages, so they don't cover an installed package; see [Consumer and packaging checks](/contributing/testing#consumer-and-packaging-checks). Codegen's `typecheck` target also generates bindings for the newest version of every installed GIR library and checks them without `skipLibCheck`: once as declarations, and once as the TypeScript sources the store keeps when `shouldKeepSources` is set, under the compiler options the store compiles them with. After generation, typecheck the consuming project and exercise its native bindings. --- --- title: "Native Runtime" description: "GTKX's TypeScript runtime, Rust FFI bridge, native ownership model, callback handling, and GLib integration." --- # Native Runtime `@gtkx/runtime` implements JavaScript binding behavior. The Rust addon, `@gtkx/native`, handles ABI operations, native memory, and Node integration. Generated GI code supplies their signatures and metadata; JavaScript accesses native memory through checked handles. TypeScript describes ABI layouts, inspects fields through checked handles, prepares arguments, selects native functions, and implements library behavior. The addon uses transfer annotations and copy/ref/free operations to acquire, retain, transfer, and release native memory. JavaScript supplies those rules without manually balancing references. Handles normally become eligible for native cleanup through JavaScript garbage collection. Native code owns temporary allocations, active-call leases, callback trampolines, and dependencies that must survive wrapper collection. Application operations such as closing a window, completing a stream, or finishing a Cairo surface remain available because they change library behavior independently of handle collection. The Rust crate builds a Node addon through napi-rs and uses libffi for native calls, libloading for shared libraries, and the Rust GLib bindings for GLib and GObject operations. Its dependencies and supported addon targets are declared in [`packages/native/Cargo.toml`](https://github.com/gtkx-org/gtkx/blob/main/packages/native/Cargo.toml) and [`packages/native/package.json`](https://github.com/gtkx-org/gtkx/blob/main/packages/native/package.json). ## From a JavaScript method to a C call A descriptor specifies a value's native representation and how it crosses the boundary. Descriptors distinguish scalars, strings, objects, boxed values, records, arrays, hash tables, callbacks, and references. They also carry details such as ownership, element layout, and native type names. A call passes through these stages: 1. A generated adapter presents the public JavaScript signature and supplies a runtime function specification. 2. [`runtime/src/fn.ts`](https://github.com/gtkx-org/gtkx/blob/main/packages/runtime/src/fn.ts) plans inputs and outputs and wraps callbacks. Shared runtime conversion plans validate public numbers, encode strings as UTF-8 bytes, normalize reference cells, and lower booleans, Unicode characters, enums, and flags to their ABI representations. 3. Native `compileDescriptor` prepares reusable value codecs. [`native/src/api/bind.rs`](https://github.com/gtkx-org/gtkx/blob/main/packages/native/src/api/bind.rs) combines those compiled descriptors with the argument layout to prepare a libffi call interface. Runtime resolves and caches the symbol or vtable slot lazily, then passes its executable handle alongside the compiled signature. 4. [`native/src/api/call.rs`](https://github.com/gtkx-org/gtkx/blob/main/packages/native/src/api/call.rs) accepts normalized arguments or requests them one at a time from a runtime producer (see [Non-scalar reference storage](/contributing/native-ownership#non-scalar-reference-storage)), then prepares native storage, invokes the target, and returns the result and output values while settling ownership transfers. 5. The TypeScript runtime converts returned values, updates JavaScript references, reports errors, and combines output values into the public return shape. Compiled value descriptors, function signatures, and executable targets have independent lifetimes and can be reused. A lazy runtime function specification defers creating the bound callable until its first invocation. [Library handles, lifecycle resolution, and binding targets](/contributing/native-ownership#library-handles-lifecycle-resolution-and-binding-targets) describes how targets are found. `compileDescriptor` snapshots descriptor metadata into an owned native codec. Field reads and writes, pointer values, and function binding consume compiled descriptors, so repeated use avoids descriptor parsing. Function descriptors and vfunc registration consume compiled signatures, which retain their codecs independently of the JavaScript descriptor handles. The runtime allocates scalar output storage by its ABI width. Native calls check argument counts, and object codecs check declared native types when those types can be resolved. Runtime also expands callback user-data and destroy-notify arguments, assigns their native positions, and calculates the expanded fixed-argument count for variadic calls. Reordering works within the fixed or the variadic region but cannot move an argument across the boundary between them. Native compilation validates the supplied permutation against the actual ABI argument count before building the call interface. ## Values, temporary storage, and ownership The runtime's shared conversion plans serve calls, fields, callbacks, references, and collections. They normalize scalar and collection inputs, encode and decode strings, and choose their public JavaScript representations. The native [`ffi/codec`](https://github.com/gtkx-org/gtkx/tree/main/packages/native/src/ffi/codec) modules pack those normalized values into ABI storage and C or GLib containers, retaining responsibility for bounds, terminators, traversal, allocation, and ownership. A `Stash` holds an invocation's temporary allocations, callback state, and pending ownership transfers. Ownership is directional. Passing a borrowed value to C differs from handing ownership to C; receiving a borrowed pointer differs from receiving a newly owned allocation. A container's allocation and its elements can also have distinct transfer requirements. The generated descriptor supplies those rules, and the relevant codec acquires, copies, transfers, or releases memory accordingly. Pending transfers are committed after the native call. Until then, temporary storage can release allocations if preparation fails. For asynchronous calls, runtime recognizes the GIO completion-callback signature and the addon retains the required argument storage and owners until completion. Runtime identifies completion callbacks heuristically; native code validates the selected callback and manages the retained memory. This logic is especially relevant when changing byte arrays, string arrays, callback scopes, or inout parameters. The sources are [`ffi/stash.rs`](https://github.com/gtkx-org/gtkx/blob/main/packages/native/src/ffi/stash.rs), [`ffi/stash/storage.rs`](https://github.com/gtkx-org/gtkx/blob/main/packages/native/src/ffi/stash/storage.rs), and the asynchronous retention path in `api/call.rs`. ## Handles and wrapper identity JavaScript wrappers hold native handles through the TypeScript runtime's registry. [`runtime/src/registry.ts`](https://github.com/gtkx-org/gtkx/blob/main/packages/runtime/src/registry.ts) maps GTypes to wrapper classes, resolves the nearest registered ancestor for native types, composes interface behavior, and associates JavaScript instances with handles. A handle is a Rust object exposed through Node's external-value mechanism. [`native/src/handle.rs`](https://github.com/gtkx-org/gtkx/blob/main/packages/native/src/handle.rs) distinguishes several underlying lifetimes: | Handle kind | Lifetime behavior | | ----------------- | -------------------------------------------------------------------------------------- | | GObject | Holds or borrows a GObject reference and participates in wrapper tracking. | | Boxed value | Uses the boxed type's copy and free behavior, or the supplied operations. | | Fundamental value | Uses native reference and release functions for a non-GObject reference-counted type. | | Owned record | Owns an allocation released through its free function or GLib's allocator. | | Borrowed pointer | Refers to memory owned elsewhere, with an explicitly limited or process-wide lifetime. | | Field view | Aliases an offset inside another handle and keeps that owner reachable. | Tracked GObjects reuse an existing JavaScript wrapper when one is available. This matters for identity, JavaScript state attached to subclasses, and signal handlers. The native implementation stores wrapper information on the GObject and uses toggle references to coordinate native reference counts with the strength of Node's reference to the wrapper. Native ownership keeps the wrapper reachable; when the toggle reference is the remaining native reference, the JavaScript wrapper can become collectible. Wrapper finalization schedules cleanup through the GLib context, including removal of the toggle reference. The implementation also tracks replacement generations so cleanup for an older wrapper cannot remove a newer association. See [`value/wrapper.rs`](https://github.com/gtkx-org/gtkx/blob/main/packages/native/src/value/wrapper.rs) and [`ffi/codec/object.rs`](https://github.com/gtkx-org/gtkx/blob/main/packages/native/src/ffi/codec/object.rs). Fundamental wrappers use a separate runtime weak cache. Native supplies a live instance identity and whether the handle owns a reference. Only owned handles populate the cache; valid borrowed handles can find an existing owner. Cache lookup checks the wrapper's current handle, handle replacement removes its old registration, and finalizer tokens prevent delayed cleanup from deleting a newer entry. Native still controls reference acquisition, release, and borrow invalidation. Some callback arguments borrow memory valid only for the current invocation. A borrow scope records their handles; leaving the invocation invalidates those handles, including on an error path. Field views inherit their owner's invalidation. Holding the JavaScript wrapper after that point does not extend the native borrow. An API that frees a value before collection, such as Cairo's `Context[Symbol.dispose]()`, goes through `releaseHandle`. Native frees an owned boxed value at once, or ends a borrow early, and later uses of the handle and its field views throw. A value that a running call or a pending asynchronous operation holds a lease on is refused, so C never sees freed memory. Generated accessors read a record or union embedded by value in another record as a field view, as GJS does for nested boxed values. The view keeps its parent's handle, and therefore its memory, alive. When the embedded record holds pointers, the generated field has no setter: copying the record would alias pointers its parent owns. Executable targets also use opaque handles. Library symbols remain available with their library, call-scoped callbacks expire when their enclosing call ends, and one-shot callback handles expire before invocation. The runtime passes those handles directly to the native binding API. ## Callbacks and signals Callbacks reverse the FFI direction. A libffi closure supplies the C entry point, and the addon keeps callback state alive during each invocation. Runtime converts incoming values, invokes the JavaScript handler and prepares its return and output values. The addon reads and writes the corresponding ABI storage. [`ffi/closure.rs`](https://github.com/gtkx-org/gtkx/blob/main/packages/native/src/ffi/closure.rs) tracks callback invocations in flight and defers destruction when cleanup is requested from inside a callback. One-shot completion callbacks, destroy notifications, and callbacks with no release mechanism have different retention paths. The native signature must specify the callback lifetime so the addon can retain it for the required scope. GObject signals use the runtime's [`signal.ts`](https://github.com/gtkx-org/gtkx/blob/main/packages/runtime/src/signal.ts), [`closure.ts`](https://github.com/gtkx-org/gtkx/blob/main/packages/runtime/src/closure.ts), and [`listeners.ts`](https://github.com/gtkx-org/gtkx/blob/main/packages/runtime/src/listeners.ts). These handle signal lookup, connection and disconnection, and JavaScript value marshalling. Native `createFunction` accepts a compiled signature and a pointer or closure descriptor. Its closure form allocates and sinks the `GClosure`, installs its marshal, and releases the callback trampoline when the closure is finalized. Runtime finalization callbacks only retire JavaScript connection bookkeeping. The React renderer builds signal props on top of that API. Promise wrappers for GIO-style operations remain a separate layer. [`promisify.ts`](https://github.com/gtkx-org/gtkx/blob/main/packages/runtime/src/promisify.ts) invokes the start function, receives its asynchronous result, calls the finish function, and resolves or rejects the promise. Promise completion and native argument-storage retention are managed separately. See [Async Operations](/v2/guide/async-operations) for the public behavior. ## Registering native subclasses `registerClass` creates a native GType for a JavaScript subclass and installs the properties, signals, interfaces, and virtual-function overrides it declares. Generated metadata identifies vtable slots and their signatures. Runtime supplies each override's compiled `bindFunction` signature, slot offset, and handler. Native validates callback compatibility and retains the signature and callback through the registered type's lifetime. The runtime also provides calls back into parent implementations. [`runtime/src/register-class.ts`](https://github.com/gtkx-org/gtkx/blob/main/packages/runtime/src/register-class.ts) owns signal rules, interface ordering, property overrides, class flags, and CSS naming. The runtime's `vfunc` modules supply the callback conventions; [`native/src/api/register_class.rs`](https://github.com/gtkx-org/gtkx/blob/main/packages/native/src/api/register_class.rs) retains class allocation and callback lifetime mechanics. A JavaScript class hierarchy alone does not register a GType. The [Subclassing guide](/v2/guide/subclassing) describes the application API. ## GLib inside Node's event loop Importing the runtime initializes the native addon through [`runtime/src/native.ts`](https://github.com/gtkx-org/gtkx/blob/main/packages/runtime/src/native.ts) before runtime modules create bindings. Importing the addon alone does not acquire a GLib context. [`runloop.rs`](https://github.com/gtkx-org/gtkx/blob/main/packages/native/src/runloop.rs) acquires GLib's default main context on that Node thread and connects it to the thread's libuv loop. The integration uses these libuv handles: | Handle | Purpose | | ------- | ---------------------------------------------------------------- | | Prepare | Dispatch ready GLib work without blocking before libuv waits. | | Poll | Wake libuv when file descriptors requested by GLib become ready. | | Timer | Wake libuv for GLib timeouts or immediately ready sources. | Runtime supplies a four-millisecond dispatch budget during initialization. Each prepare callback iterates the GLib context without blocking, stopping when there is no work or that budget expires. It then queries GLib's next deadline and descriptors, updates poll handles, and arms the timer. The budget limits a batch of iterations; it cannot interrupt a long-running callback. Native dispatch runs within Node callback scopes so JavaScript callbacks and microtasks participate in Node's execution model. The handles are unreferenced, so merely importing GTKX does not keep an otherwise idle Node process alive. Application activation calls runtime `keepAlive`, which holds a Node timer; shutdown clears it. This controls event-loop liveness independently of application-object retention. The timer belongs to its JavaScript environment, and environment cleanup releases the native event-loop integration and its dispatch resources. Only the owning thread can operate this GTKX runtime. Attempting to acquire the context from another thread while it is owned fails. Worker communication should carry plain data back to the owner; native objects and GTK operations stay there. A standalone worker can initialize GTKX when no other thread has done so. Before terminating an owning worker, finish native operations or cancel them and await completion. Disconnect signal handlers and remove other native callback registrations, then call `quit()` from `@gtkx/runtime`. The worker must report cleanup completion before its parent calls `worker.terminate()`. `quit()` does not cancel operations or await their callbacks. Terminating a worker with live native operations or registrations is unsupported. ## Application lifecycle and errors The [GIO application override](https://github.com/gtkx-org/gtkx/blob/main/packages/codegen/overrides/gio/overrides/application.ts) implements `Application.runAsync(argv)` through GLib's local command-line handling. That preserves GLib option parsing, registration, activation, and forwarding to an existing application instance while keeping Node as the outer loop. The override tracks application runs, windows, explicit JavaScript holds, inactivity deadlines, and shutdown. React waits for activation before mounting application children, avoiding window creation in a remote process. On teardown, GTKX detaches application windows and reaches GLib's shutdown path through an adapted `g_application_run()` call once it can complete without owning the normal application loop. It also releases the process-wide default application association. Process shutdown in [`runtime/src/lifecycle.ts`](https://github.com/gtkx-org/gtkx/blob/main/packages/runtime/src/lifecycle.ts) runs registered exit callbacks, clears and disables its keep-alive timer, and tears down native integration before propagating cleanup errors. Native `quit` first runs pending cleanup, drops the object references that handles only JavaScript holds still keep (an owned object handle awaiting collection, a `GObject.Value`), and gives up the wrappers' toggle references while JavaScript can still run, so teardown can still call JavaScript vfuncs and signal handlers. Objects native code still references keep their wrappers, strongly held so their JavaScript state outlives disposal, but lose the toggle references, so each is disposed when its native owners let it go, as in C. Objects only their wrappers reference are then released, repeating as disposal leaves more of them: widgets first, then instances of registered classes, each in wrapping order, so teardown that calls back into JavaScript still finds the objects its JavaScript state holds, then other objects, newest first, so an object goes before the one it came from. A wrapper stays installed while its object is disposed, and a later wrapper for a surviving object starts afresh. Surfaces and objects in a wrapper borrow keep their toggle references for environment teardown, where callbacks are already retired. A failing callback cannot prevent the remaining cleanup, and repeated or reentrant shutdown does not run it twice. Throwing native functions report `GError` through an out parameter that the TypeScript runtime turns into an exception. Runtime converts callback exceptions into owned `GError` values when the signature supplies an error slot. Native retains error-slot ABI metadata, validates and copies the supplied handle, and preserves the original exception when the error slot is absent or occupied. The direct addon transport is `CallbackFailure` in [`native/main.d.ts`](https://github.com/gtkx-org/gtkx/blob/main/packages/native/main.d.ts). GTKX installs no GLib log handler: criticals and warnings reach GLib's default writer, as in C and GJS. Rust entry points guard unwinding at FFI boundaries; a panic in an exported addon function throws from that call, and a panic caught at a callback boundary is reported through Node's uncaught-exception channel. The relevant sources are [`runtime/src/error.ts`](https://github.com/gtkx-org/gtkx/blob/main/packages/runtime/src/error.ts) and [`native/src/host/panic_handler.rs`](https://github.com/gtkx-org/gtkx/blob/main/packages/native/src/host/panic_handler.rs). The [Error Handling guide](/v2/guide/error-handling) explains native exceptions, promise rejections, GLib criticals, and addon panics. React error boundaries do not catch arbitrary signal-handler exceptions or asynchronous failures. ## Ownership boundaries {#native-boundary-audit} The native package is an implementation detail. Its interface keeps JavaScript binding behavior in runtime and native lifetime mechanics in the addon. ABI metadata, field offsets, and library selection can live in TypeScript; native code owns the memory those operations access. [Native Ownership Boundaries](/contributing/native-ownership) explains why each operation below stays native and how runtime and the addon divide property storage, numeric transport, library handles, reference storage, Cairo paths, process supervision, and event-loop scheduling. ### Native operations {#export-dispositions} | Operation | Responsibility | | ------------------------------------------------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `compileDescriptor`, `bindFunction`, `createFunction` | Compile value codecs and signatures, and create native callback pointers or GClosures. Runtime supplies normalized descriptors and handlers. | | `alloc`, `readField`, `writeField`, `call` | Allocate storage, validate bounds and leases, invoke native functions, and settle ownership transfers. | | `reportExternalMemory` | Count native memory a handle keeps alive, such as an image surface's pixels, toward garbage collection until the handle is released. | | `releaseHandle` | Free an owned boxed value, or end a borrow, before collection when an API such as `Context[Symbol.dispose]()` asks; refuse while an operation still uses it. | | `openLibrary`, `resolveSymbol` | Open one library and resolve a symbol. Runtime chooses candidates and caches targets. | | `getType`, `getTypeClass`, `registerClass` | Validate native types, own class and interface references, register GTypes, and retain callbacks. Runtime supplies class policy and metadata. | | `emitSignal` | Emit a signal from argument `GValue`s with an exact argument scope, so nested emissions of the same signal stay distinct. Runtime converts the arguments and return value. | | `getFundamentalIdentity` | Report a fundamental instance's identity and whether the handle owns a reference, for the runtime's fundamental wrapper cache. | | `getWrapper`, `setWrapper`, `setWrapperBorrow` | Coordinate GObject references, JavaScript wrapper reachability, dependent borrows, and cleanup ordering. | | `deferFinalization` | Keep a disposed object allocated until a dependent object is finalized, for upstream code that writes into it from the dependent's finalization. | | `newObject`, `getObjectProperty`, `setObjectProperty`, `setValuePointer` | Preserve construction and property-storage lifetimes, including callback dependencies and reentrant calls. | | `init`, `quit` | Acquire and release native event-loop resources; `quit` first ends objects only their wrappers reference. Runtime initializes the addon, supplies its dispatch budget, and owns keep-alive and exit callbacks. | See [`packages/native/main.d.ts`](https://github.com/gtkx-org/gtkx/blob/main/packages/native/main.d.ts) for the current addon contract. The CLI owns the binary locator so packaging tools can find the addon without loading it. --- --- title: "Native Ownership Boundaries" description: "Why each GTKX native addon operation stays in Rust, and how runtime and the addon split property, numeric, library, reference, Cairo, process, and event-loop work." --- # Native Ownership Boundaries This page records why each part of the addon's interface stays native and what runtime keeps in TypeScript. Read [Native Runtime](/contributing/native-runtime) first; its [Native operations](/contributing/native-runtime#export-dispositions) table lists the operations these sections refer to. The rule they apply: JavaScript binding behavior belongs in runtime, and native lifetime mechanics belong in the addon. ## Properties and wrapper dependencies Runtime keeps property names, flags, value guards, JavaScript accessors, notification policy, and class/interface registration policy. Its `GParamSpec` field offsets and layout probes remain JavaScript ABI knowledge. Probe values, class references, and default-interface references use handles with native release operations instead of paired JavaScript ref/unref calls. Property validation uses a fresh GC-owned `GValue` for each operation. A class-level scratch `GValue` would retain its last object or boxed payload after the instance that owned the property had been collected. Metadata caches retain metadata, not the last assigned value. Pointer-valued `GValue`s own their encoded backing storage in native handles. Property assignment and construction attach callback storage to the receiving native object. Native-managed weak-key associations keep JavaScript callback dependencies visible to V8, including callbacks that capture their owner, while native attachment ownership keeps the executable storage valid through replacement and finalization. `setValuePointer` writes the encoded pointer and retains its backing storage together. `getObjectProperty` and `setObjectProperty` preserve these dependencies through reentrant native property calls and deferred object destruction. Replacing them with ordinary FFI calls and JavaScript retention maps would release some callback storage before native finalization finishes, so these ownership operations remain native. Native retains candidate callback storage before entering a property setter. After the setter returns, including when it logs a GLib critical, native reads the resulting pointer of a readable property and reconciles retained storage with that value. This covers nested writes both before and after the outer setter stores its pointer. For write-only properties or getters that reenter a write, native conservatively retains candidates until a later reliable read or object finalization can release them. Reading a callback property returns a snapshot that retains its trampoline independently of later property replacement or clearing. Constructor values remain retained through native construction, and final property reconciliation preserves the values actually stored after reentrant replacements or clearing. Library overrides can identify a borrowed relationship that needs protection. The Window override supplies the native default-widget setter to `setWrapperBorrow`; native retains the dependent wrapper, leases both objects during cleanup, and clears the pointer directly before deferred wrapper teardown. The override neither keeps its own retention map nor constructs a JavaScript wrapper to perform cleanup. Library compatibility workarounds remain in overrides. Sidebar detaches retired models and explicitly disposes detached rows, because libadwaita leaves views retired by a mode change connected to their models. ComboRow disconnects the native handlers its default factory and item boxes hold, because libadwaita does not tie them to the row's lifetime. TabBar disposes its tab boxes when it is destroyed, because libadwaita's boxes keep a plain pointer to the bar and the tabs they drop still follow their pages. Emission hooks on Breakpoint's `apply` and `unapply` signals pass each breakpoint bin holding a window's focus to `deferFinalization` with the focused widget, because libadwaita's bins register a weak pointer on that widget at every breakpoint change and never clear it. The hooks reach the internal bins of windows and dialogs, which have no wrapper. These workarounds are permanent. These calls change library behavior and are distinct from balancing references on runtime-owned handles. ## Descriptor normalization Runtime owns callback and class-registration defaults, storage flags, reference direction, and array element ownership. Public descriptors remain concise, while the native schema requires explicit values. Function arguments, return values, fields, callbacks, references, nested collections, and record `abiFields` share the runtime conversion plans. Bootstrap scalar bindings already supply complete descriptors; enum lookup lowers its pointer and string descriptors when invoked, avoiding module-initialization cycles. Native retains validation of ABI layouts, ownership combinations, callback retention, extents, and recursion bounds, without duplicating descriptor defaults. Runtime rejects cyclic descriptors before recursive lowering. ## Numeric policy and collection transport Runtime validates JavaScript numbers, checks public integer ranges and finite float32 overflow, and converts between number and bigint. Number64 accepts the inclusive `-2^53..2^53` interval. Float32 accepts NaN and infinities. Native validates that normalized values fit their ABI storage. Native 64-bit integer descriptors carry bigint values and an explicit `isDirectWord` flag. Runtime sets it for public Number64 descriptors, preserving direct hashing and signed pointer-word list entries. Ordinary bigint hash values use allocated scalars. Bigint keys are unsupported, and ordinary bigint pointer lists require nonnegative words. Contiguous C/GArray storage and matching typed-buffer passthrough remain distinct from pointer collections. Typed-array offsets and writes are preserved; incompatible views are rejected. Array lengths are extracted exactly from integer and bigint arguments or references, then checked against platform sizes and native extents. Runtime validates hash-entry tuples and converts iterables before native allocation. Native retains traversal, terminators, stride/extent checks, backing-store validity, ownership/destructor pairing, duplicate replacement, and partial-encoding rollback. Nested records, references, callbacks, and collection elements use the same runtime conversion plans. ## Library handles, lifecycle resolution, and binding targets Native [`ffi/library_cache.rs`](https://github.com/gtkx-org/gtkx/blob/main/packages/native/src/ffi/library_cache.rs) provides owned `openLibrary(candidate)` and `resolveSymbol(libraryHandle, symbol, optional)` primitives. [`runtime/src/native-bindings.ts`](https://github.com/gtkx-org/gtkx/blob/main/packages/runtime/src/native-bindings.ts) chooses among comma-separated candidates and caches the chosen handle. Resolution uses the **first loadable library**: a missing symbol does not cause a search in subsequent candidates. Native retains the loader flags and process-wide library lifetime. Optional resolution suppresses only missing symbols; loading and malformed-name errors propagate. Runtime supplies lazy functions for descriptor GTypes and copy/ref/free operations through [`descriptor-lifecycle.ts`](https://github.com/gtkx-org/gtkx/blob/main/packages/runtime/src/descriptor-lifecycle.ts). Native retains those functions directly from the descriptor and activates them at the codec's acquisition boundary, including during output or callback decoding, so types registered after descriptor creation or by the callee remain visible. Successful resolutions are cached; unregistered names and failed function lookups remain retryable. Native validates types, ref/unref pairs, and reusable library-backed function handles. Resolved destruction operations come from permanently loaded libraries and run as native function pointers, so they remain callable after their JavaScript wrappers or environment are released. Resolver callbacks belong to their Node environment and are released during its teardown. Foreign-record conversion strategies resolve native operations at the same acquisition boundary. `bindFunction` accepts compiled argument and return descriptors and compiles a signature independently of its target. Runtime retains that signature and lazily caches the executable handle, passing both to native `call`. Compatible signatures also create callback trampolines through `createFunction`; nested callback descriptors reference a compiled signature instead of rebuilding their call interface for each callback instance. Native validates the signature's calling convention for its use, including variadic arguments and hidden callback error outputs. Descriptor compilation validates value layout; signature binding separately validates whether those values support calls or callbacks. Native checks the target's borrow lifetime and acquires its lease on each invocation, consuming one-shot targets before calling them. Runtime validates vfunc offsets and lazily acquires a bounded class, implemented-interface, or default-interface handle through `getTypeClass`. It reads the executable target with `readField`, which checks the field extent and retains the owning vtable. Empty implementations fail when resolved. Class and interface references are released when no dependent handle remains. ## Non-scalar reference storage Runtime requests storage for scalar references; native code owns the allocation. Non-scalar reference descriptors compile recursively through `compileDescriptor` and are retained by the call signature. Calls accept ordinary normalized `{ value }` cells, with storage derived from the descriptor and seed. Runtime supplies owned `alloc` handles for caller-allocated C arrays. Native validates their bounds and retains the owner; GLib containers still require their native container layout and lifecycle. Native `call` accepts an argument array or an `(index) => value` producer. Runtime uses the producer so native can capture each converted reference seed and acquire its native owners before the next conversion can reenter JavaScript or trigger collection. ABI storage is prepared only after every argument has been normalized, so later conversions cannot invalidate an already-prepared typed-array pointer. Each invocation owns its temporary transaction; cells can be reused without exposing a separate storage handle or mode enum. Native preserves synchronous typed-array views, checks returned extents against remaining capacity, distinguishes unchanged/null/replacement pointers, adopts or copies replacements, and settles transfers. Output decoding visits remaining outputs even after an earlier conversion fails, so their native allocations are released. Runtime updates public reference cells after decoding their results. Asynchronous non-scalar references must borrow the output and its elements: the synchronous result API cannot release transferred outputs before completion. Native rejects incompatible transfer contracts before calling C and retains borrowed reference transactions, including independent buffer copies and native owners, until completion. Callback references exchange normalized values through ordinary JavaScript cells. Runtime exposes the public reference object and converts its replacement; native writes each ABI output and retains its acquired storage. The cell carries JavaScript values rather than access to caller-owned ABI memory. Native handles borrowed by those values still expire with the invocation. Output writes are sequential. ## Cairo path conversion Runtime selects the Cairo path conversion strategy and includes its options and lazy operation resolvers in the struct descriptor. `compileDescriptor` snapshots those options with the value codec; there is no separate converter factory or opaque converter handle. Native creates a temporary surface and context, appends and copies the source path, checks status, and releases temporary resources through Rust-owned scopes. Native validates that the result uses the declared path destructor and transfers the copied allocation into the pending ownership transaction. Borrowed outputs and transfer-full inputs, including callback returns, share this acquisition boundary. Failure cleanup preserves the original source. ## Process supervision The CLI supervises its application runner, forwards shutdown signals, and forces termination if shutdown times out. The runner exits when its IPC connection to the CLI closes. [Native UI integration](/contributing/testing#native-ui-integration) covers how headless sessions are released and reclaimed. ## Event-loop scheduling Runtime controls initialization order and supplies the dispatch budget, as [GLib inside Node's event loop](/contributing/native-runtime#glib-inside-node-s-event-loop) describes. Native validates the budget before initialization and retains GLib context ownership, readiness storage, libuv handle reconciliation and close callbacks, N-API callback/error scopes, thread confinement, and unconditional teardown. Its cleanup hooks still run when worker termination prevents JavaScript cleanup. The [scheduler benchmark](https://github.com/gtkx-org/gtkx/blob/main/packages/native/tools/scheduler-benchmark.ts) compares native scheduling with a copied readiness snapshot and a JavaScript callback per cycle. Run `node packages/native/tools/scheduler-benchmark.ts` from the repository root. It measures per-cycle copy and callback overhead. Use application-level latency measurements as well when evaluating changes to the scheduling boundary. Verify ownership and callback changes through the [native fixtures and sanitizers](/contributing/testing#native-fixtures-and-sanitizers). Runtime process tests cover startup, shutdown, worker isolation, and logging; generated-binding integration tests exercise value conversion and native lifetimes. --- --- title: "React Renderer" description: "How GTKX reconciles React trees into native GObjects, routes children and props, handles signals, and manages application presentation." --- # React Renderer `@gtkx/react` is a custom React renderer for native GObjects. It translates React's host operations into object construction, property updates, signal connections, and container-specific child placement. Generated JSX provides typed components, and generated GI provides the native classes and methods they use. The reconciler is configured in [`reconciler/host-config.ts`](https://github.com/gtkx-org/gtkx/blob/main/packages/react/src/reconciler/host-config.ts). It uses mutation mode with concurrent roots, Node timers, and microtasks. Persistence and hydration are disabled. GTK performs layout and painting after the renderer changes the native tree. ## Generated components and host elements A generated component creates a host element named for its GType, such as `GtkButton`. Its reference to the generated GI class retains that class's registration and metadata in a bundled application. [`components/element.tsx`](https://github.com/gtkx-org/gtkx/blob/main/packages/react/src/components/element.tsx) builds that host element. It examines props containing React elements and routes them through internal `gtkx:prop` elements. This turns a named prop containing JSX into a reconcilable subtree associated with a slot name, while ordinary `children` remain in the default slot. The renderer defines its node kinds in [`reconciler/node.ts`](https://github.com/gtkx-org/gtkx/blob/main/packages/react/src/reconciler/node.ts): | Kind | Meaning | | ------- | ------------------------------------------------------------------------------------- | | Element | A native GObject, its current props, handlers, child placements, and style resources. | | Prop | A named slot and the children routed into it; it has no native object. | | Lazy | A declaration for an object created by its parent, adopted after placement. | | Text | Text content associated with a supported text host. | Function components and React context providers are reconciled by React itself. They do not add GObjects. The widget tree visible in an inspector therefore omits these React-only nodes. ## Metadata and element behaviors The renderer combines native type ancestry with generated property and signal metadata. [`reconciler/metadata.ts`](https://github.com/gtkx-org/gtkx/blob/main/packages/react/src/reconciler/metadata.ts) resolves property flags, construction requirements, defaults, signal names, configured user-event signals, and behaviors inherited from classes and interfaces. Custom classes use the same metadata registry; changes invalidate cached type information. Element configuration and runtime behavior are defined separately: - [`builtin-elements.ts`](https://github.com/gtkx-org/gtkx/blob/main/packages/config/src/builtin-elements.ts) describes each element's generated surface: additional props, omitted native props, component wrappers, accepted child types, and parent-created instances. It can be imported during generation without loading native bindings. - [`element-behaviors.ts`](https://github.com/gtkx-org/gtkx/blob/main/packages/react/src/element-behaviors.ts) registers native construction, specialized prop updates, and child placement operations. Shared builders in [`reconciler/behaviors.ts`](https://github.com/gtkx-org/gtkx/blob/main/packages/react/src/reconciler/behaviors.ts) implement recurring attachment patterns such as a single child setter, ordered box children, and indexed collections. The registry combines these operations through type ancestry. ## Construction and prop updates When React creates an instance, [`reconciler/instance.ts`](https://github.com/gtkx-org/gtkx/blob/main/packages/react/src/reconciler/instance.ts) resolves its metadata, selects construction props, and either invokes the registered class constructor or an element-specific creation behavior. Lazy elements defer native object creation to their parent instead. [`reconciler/apply-props.ts`](https://github.com/gtkx-org/gtkx/blob/main/packages/react/src/reconciler/apply-props.ts) then applies element behaviors, writes remaining values, connects handlers, and marks work that must finish at commit time. Props handled by an element behavior are excluded from generic property assignment. React's `children`, `ref`, and `key` are reserved for their respective React and renderer roles. On an update, unchanged values are skipped. Removing a prop can restore its recorded default. A construct-only native property cannot be changed on an existing instance; the renderer rejects that update, so an application must change the element's key when it needs a newly constructed object. After tree mutations, the host configuration's `resetAfterCommit` writes back props that a slot or object-prop write reset, flushes text, accessibility and styles, notifies listeners of adopted objects, warns when a single-child slot received more than one visible widget, and schedules the property notifications that placement queued. Adopted refs are available to parent layout effects. The element component handles accessibility reapplication on map through [`useAccessibleMap`](https://github.com/gtkx-org/gtkx/blob/main/packages/react/src/hooks/use-accessible-map.ts), whose callback ref owns the signal connection and cleanup. ## Child placement and parent-created objects GObject containers expose different APIs. A box has ordered children, an application owns windows, a menu owns items, and a named widget prop may hold exactly one child. GIR describes native types and methods, but the renderer's element behaviors supply the React attachment semantics. [`child-routing.ts`](https://github.com/gtkx-org/gtkx/blob/main/packages/react/src/reconciler/child-routing.ts) routes changes according to the parent node kind and named slot. [`placement.ts`](https://github.com/gtkx-org/gtkx/blob/main/packages/react/src/reconciler/placement.ts) resolves the matching behavior, tracks actual placements, and performs attachment, removal, or reordering. Reordering may use a native reorder operation or a detach-and-attach path depending on the container. Writing a native object into a slot or an object prop, such as a model or an adjustment, can reset other properties of the parent; after the commit, the renderer writes back each declared prop that the write changed and leaves the ones it did not change, so a value the user set natively, such as a moved `GtkPaned` divider, survives. Lazy nodes represent native objects a parent creates as a consequence of adding a child. Examples include stack pages, notebook pages, and layout-child objects. The node initially records props and children without constructing that object. Placement obtains the object from the parent, adopts it, and applies the lazy node's props and handlers to it. Changing the leaf child can require removing the old placement and adopting a different parent-created object. When adding container support, check both generated prop configuration and runtime child-placement behavior. ## Text, styles, and accessibility Text nodes are accepted by specific content hosts, including labels and text buffers. They are not automatically turned into labels wherever a string appears. [`reconciler/text.ts`](https://github.com/gtkx-org/gtkx/blob/main/packages/react/src/reconciler/text.ts) tracks text content and supports text tags and child anchors, with targeted text updates where possible and a deferred flush when rebuilding a host's content is needed. Styles and accessibility are also native operations. [`reconciler/style.ts`](https://github.com/gtkx-org/gtkx/blob/main/packages/react/src/reconciler/style.ts) manages renderer style resources, and [`utils/accessible-props.ts`](https://github.com/gtkx-org/gtkx/blob/main/packages/react/src/utils/accessible-props.ts) maps accessibility props to GTK's accessible API. A visible style or accessibility failure may arise after placement, so checking only initial prop assignment can miss the relevant path. ## Signals and controlled state Handler props map to GObject signals using generated metadata or registered custom signal information. Property-specific notification handlers, such as `onNotifyText`, receive the current property value and the native object. Other signal handlers receive the signal arguments followed by the native object; the general `onNotify` handler therefore receives the parameter specification. [`reconciler/signals.ts`](https://github.com/gtkx-org/gtkx/blob/main/packages/react/src/reconciler/signals.ts) keeps a handler record for each connected prop. If the signal and target object remain the same, a rerender replaces the stored JavaScript handler while retaining the existing native connection. Removing a handler prop disconnects it. The connected native handler dispatches to the JavaScript handler with React's discrete event priority. The renderer tracks its own property writes and tree mutations and suppresses the configured user-event signals they emit, matching property notifications to the property being written where possible, so prop updates don't trigger user-input handlers. Notifications that a child attach or detach causes are queued instead and delivered after the commit's layout effects. A queued notification is dropped when a later write in the same commit, such as a controlled prop, writes that property, or when the property ends the commit with the value it had before or the value its prop asks for. Signal behavior changes should be checked through an actual interaction and through a prop-driven update, since those paths can emit the same native signal for different reasons. Controlled selection and visibility use [`components/controlled.tsx`](https://github.com/gtkx-org/gtkx/blob/main/packages/react/src/components/controlled.tsx) and its shared hook. These observe native changes and restore the latest committed prop when needed. Menu descriptions likewise compose JSX menu elements above the host layer. ## Collection models The collection components render their selection model, `Gtk.FlattenListModel`, and collection root through JSX. [`use-collection.tsx`](https://github.com/gtkx-org/gtkx/blob/main/packages/components/src/internal/use-collection.tsx) binds their committed references to a JavaScript controller, then updates the collection index and native model together before applying controlled selection and expansion. Unmounting detaches the model graph and clears its groups. The root implements `Gio.ListModel`. Its synchronous `get_item` callback supplies each section's model when GTK requests it, creating the level store and optional `Gtk.TreeListModel` at that point. Tree child models and row objects are likewise created only when native callbacks require an immediate return value. These synchronous callbacks create native return values directly; JSX owns the rest of the model graph. ## Roots, portals, and presentation [`reconciler/root.ts`](https://github.com/gtkx-org/gtkx/blob/main/packages/react/src/reconciler/root.ts) creates roots, submits updates, tracks mounted roots, and exposes portals. The default root container is a marker with no native object. A root can also target an existing GObject, which the renderer adopts as a container. Portals let React children target another container while retaining their React ancestry. Application, window, and dialog component wrappers add lifecycle above those host operations: - The application component creates and starts an application, provides it through React context, and mounts its children after activation. - Application windows associate with the current application and use presentation behavior appropriate to windows. - Window and dialog wrappers manage presentation, parent-window relationships, close behavior, and their cleanup. These wrappers live under [`packages/react/src/components`](https://github.com/gtkx-org/gtkx/tree/main/packages/react/src/components), supported by hooks such as `use-presented-instance` and `use-parent-window`. Read [Native Runtime](/contributing/native-runtime) for application registration and loop ownership, and [Modals and Portals](/v2/guide/modals-and-portals) for public composition patterns. ## Teardown and verification React removal routes detachment through the placement system and removes subtree attachments before GTK unroots their widgets. This includes controllers, action groups, slots, and constraints. Deleted instances disconnect renderer handlers and release style resources; adopted instances disconnect their handlers too. The runtime still governs wrapper and native allocation lifetime, so unmounting and native finalization are separate events. Renderer tests live in [`packages/e2e/tests/react`](https://github.com/gtkx-org/gtkx/tree/main/packages/e2e/tests/react) and render through `@gtkx/testing`; [Testing](/contributing/testing#native-ui-integration) describes the harness. The running development app also exposes its tree, interactions, and screenshots through the [GTKX MCP tools](/v2/guide/mcp). Confirm the behavior a change affects: mounting, subsequent updates, removal, relevant edge cases, and invalid input where applicable. --- --- title: "Testing" description: "Run GTKX tests, reproduce CI failures, and check native bindings with memory sanitizers." --- # Testing Each package's suite covers its public behavior; `packages/e2e` holds the React and generated native binding suites. [Development Principles](/contributing/principles#test-behavior-at-the-right-level) sets the testing policy, and the [application testing guide](/v2/guide/testing) explains rendering, queries, input and assertions. ## Coverage ownership The JavaScript suites use Vitest. The `packages/e2e` directory and Nx `e2e` target names predate the principles' test levels: their React and generated-binding suites call code directly, so they are integration tests. | Package | Essential contract | | ----------- | ----------------------------------------------------------------------------------------------- | | animated | The public `animated` adapter, native updates, refs and cleanup through `@gtkx/testing`. | | cairo | Public bindings against Cairo, including drawing, surfaces, paths, fonts, patterns and regions. | | cli | Command parsing and filesystem, build or session behavior. | | codegen | Real GIR input, emitted bindings/reference and consumer typechecking. | | components | Collection, selection, factory, tab and toast behavior through `@gtkx/testing`. | | config | Loading, validation, merging, paths and reload with actual configuration files. | | create-gtkx | Scaffolding options, generated files, errors and installation boundaries. | | css | Computed GTK styling from public CSS APIs. | | forms | Controls, submission, validation, defaults and cleanup through `@gtkx/testing`. | | gl | Binding calls in a real GL context. | | i18n | Catalogs and React translation behavior through `@gtkx/testing`. | | mcp | Protocol requests, resources, tool routing and server lifecycle. | | native | Generated GNOME test bindings under ASan, with a leak check after every test. | | navigation | Navigation state, adaptive layouts and lifecycle through `@gtkx/testing`. | | react | Default element behaviors and reconciliation through `@gtkx/testing` in `packages/e2e`. | | runtime | Runtime-exposed functions and process lifecycle without generated GIR library imports. | | storybook | Story composition, controls, actions and sessions through `@gtkx/testing`. | | testing | Rendering, queries, input, assertions, waiting and isolation. | | utils | GTKX-owned utility behavior through focused unit tests. | | vitest | Real fixture runs, worker preloads, isolation and teardown. | Prefer one clear scenario for each distinct contract. Consolidate historical bug cases into that coverage instead of growing a separate regression suite. Upstream libraries own their generic algorithms; GTKX tests cover how GTKX integrates with them. Test counts and file counts are not coverage goals. The React suite covers the `GtkDragSource` `icon` prop but has no case for a live drag session. ## CI verification and failure reproduction Rely on the normal CI workflow for verification. CI distributes affected `build`, `test`, `typecheck`, `lint` and `test-asan` targets through Nx Agents, then runs affected `e2e` targets on the GitHub coordinator with Nx caching. The coordinator container allows nested namespaces and mounts needed by WebKit's Bubblewrap sandbox; managed agent templates do not expose these container permissions. A manual CI dispatch runs all projects. CI also runs the current Rust advisory audit. The `verify` GitHub job reports the combined result as `Verify workspace`, the only check the `main` branch ruleset requires. Package `test` targets run integration and unit tests. The `@gtkx/e2e:e2e` target runs the React suite and depends on `@gtkx/native:test-asan`, which runs the sanitized native suite once. Native tests have no ordinary unsanitized test target. Nx prepares prerequisite builds and generated bindings and caches each suite. When diagnosing a CI failure, reproduce the owning target and optionally pass a Vitest file filter through Nx: ```bash pnpm exec nx run @gtkx/components:test -- tests/drop-down.test.tsx ``` Nx and Vitest run with their default concurrency; Nx Cloud schedules distributed tasks on the agents. ## Native fixtures and sanitizers The native integration suite generates bindings from a pinned checkout of GNOME's `gobject-introspection-tests`. `GIMarshallingTests` supplies marshalling cases; `Regress` supplies general binding cases. Exercise the generated APIs with inputs and assertions appropriate to their upstream contracts, including ownership, callbacks, containers, fields, properties, signals and vfuncs. A complete `@gtkx/native:test-asan` run collects V8 execution coverage of both generated namespaces. It checks every exported function, concrete constructor, class/interface method, getter and setter by its receiver and source range. The gate rejects untested APIs and obsolete exclusions. Filtered runs support diagnosis without enforcing whole-suite coverage. Signals are asserted through their generated emitters and listeners, including zero, one and multiple listeners for transferred arguments. The checked-in `packages/e2e/tests/native/coverage-inventory.json` records the coverage summary and precise exclusions. An independent raw GIR audit requires bindings for every introspectable callable, signal, property access mode and virtual method in both namespaces. Lifecycle-only vfuncs require metadata but have no generated call proxy. The audit lists declarations explicitly disabled by the upstream scanner separately. A few scanner declarations have no C implementation: their tests assert that symbol resolution fails. Other exclusions are fields on abstract records with no upstream factory and unsafe writes to private ownership bookkeeping. After reviewing a deliberate API or suite change, refresh the summary from a complete run: ```bash pnpm exec nx run @gtkx/native:test-asan --skip-nx-cache pnpm exec tsx packages/e2e/tests/helpers/native-fixtures-coverage.ts --write ``` The first command reports a stale inventory after the tests pass if its summary needs updating. Detailed API-to-suite execution evidence is written to `build/native-tests/coverage/inventory.json`. Coverage establishes which generated wrappers ran; assertions and sanitizers establish their behavior. Most native cases use the upstream GNOME fixtures. Local C fixtures in `packages/e2e/tests/native/fixtures` cover pointer and callback ownership and Cairo path conversion. Their tests compile these fixtures into temporary shared libraries. Observable runtime behavior such as keep-alive, quit and logging belongs in the runtime suite, using TypeScript child processes where process isolation is necessary. The fixture preparation target downloads and builds the pinned upstream source and generates bindings: ```bash pnpm nx run @gtkx/e2e:_test:fixtures ``` The first run needs network access and builds the upstream fixtures with their Cairo cases enabled. Outputs live under `build/native-tests`; Nx caches compilation and generated bindings. Preserve the pinned revision when reproducing a failure. Both the Rust addon and upstream C libraries are instrumented. Before the suite starts, an isolated TypeScript canary deliberately leaves an allocation unowned; the shared per-test hook must reject it. ASan uses the nightly Rust toolchain pinned in `packages/native/tools/rust-toolchain.toml` and the system `libasan` runtime. The instrumented addon is separate from the ordinary build, under `packages/native/build/asan`. The launcher selects it with a preload before the test worker loads GTKX. Native test setup requires ASan and exposed garbage collection. After each test it drains pending cleanup and collects garbage before calling LeakSanitizer. Test-specific teardown must release retained references first. Cases in one process run sequentially so allocations and cleanup are attributable to the active test. Sanitizer errors and leak reports fail the suite; an absent sanitizer must not silently pass. Review leak suppressions narrowly. Some upstream signal emitters leak their original argument storage even without listeners; their exact allocation stacks are suppressed and documented in `lsan.supp`. The tests still exercise every ownership variant and check for other leaks after each case. Reachable objects can still be retained incorrectly, so assertions about observable ownership or finalization remain useful where the upstream fixtures expose them. ## Native UI integration `@gtkx/vitest` gives each test worker a private Wayland compositor, runtime directory and D-Bus session. Worker teardown releases these resources during normal shutdown. Subsequent Vitest, dev or Storybook startup, or [`gtkx cleanup`](/v2/guide/cli#gtkx-cleanup), reclaims stale sessions left by interrupted runs. Package suites merge the shared source-resolution configuration, which resolves workspace TypeScript and inlines GTKX dependencies. Importing `@gtkx/testing` registers its matchers and per-test cleanup through Vitest's global hooks, which `@gtkx/vitest` enables. Package suites use `@gtkx/vitest` directly. The React integration suite and the Storybook example, the only example with tests, use `@gtkx/cli/vitest-plugin`, which adds application transformations such as settings schemas, assets and custom elements. The tutorial application is outside the workspace and runs its tests from its own directory. ## Consumer and packaging checks The CLI suite creates temporary projects and exercises development, builds, and deployment through the command parser. These projects link built workspace packages; they do not validate installation from a registry. The codegen suite likewise checks generated imports in temporary consumers linked to the workspace. The `tutorial/` application consumes registry packages outside the workspace. Run its typecheck and application tests from that directory when validating a published release. For package-resolution or publication changes, also verify an ordinary project using the packaged artifacts; a workspace build alone cannot establish that those artifacts install and run correctly. ## Other checks CI builds, typechecking and static analysis complement tests. Lint includes formatting, unused-code checks, workflow checks, rustfmt and Clippy. The root Vitest suite covers release tooling, native artifact restoration and the CI environment hash. CI builds the website for documentation changes. Inspect affected pages when changing layout or navigation. For a visible widget or application change, run the affected example and inspect its live widget tree, interactions and screenshots. To diagnose a failure, reproduce it with the owning suite's configuration. Check prerequisites first when no test starts: native build, GIR discovery, fixture compilation, generated bindings, compositor and session bus. The testing guide's [debugging helpers](/v2/guide/testing#assertions-and-debugging) explain UI assertions. The live application also exposes inspection through [MCP](/v2/guide/mcp). --- --- title: Development Principles description: "GTKX's package boundaries, coding standards, testing policy, and review requirements." --- # Development Principles These rules apply to new and existing code. The [architecture pages](/contributing/architecture) describe the implementation; existing behavior does not establish an exception to the rules below. ## Give each layer one responsibility | Layer | Responsibility | | -------------------- | ---------------------------------------------------------------------------------------------------------------------------------- | | `@gtkx/native` | Memory-safe FFI, native allocations and lifetimes, and unsafe ABI operations. | | `@gtkx/runtime` | Binding semantics, value conversion, callbacks, signals, the GObject type system, and JavaScript representations of native values. | | `@gtkx/codegen` | Executable ESM bindings and declarations derived from GIR, using explicit runtime descriptors. | | Codegen overrides | Library-specific helpers, application lifecycle, and upstream workarounds compiled with their generated namespace. | | `@gtkx/react` | Reconciliation and primitives behind generated JSX elements. | | Components and hooks | Lifecycle effects, presentation, list factories, and other composed behavior. | Review changes for clear ownership, observable tests, and a consumer requirement. ### Keep the native module minimal Rust manages native storage, allocation lifetimes, and ABI operations. JavaScript must never need to manipulate raw pointers or perform operations that can cause undefined behavior. Binding policy belongs in the runtime; calling a C library alone does not justify putting a feature in Rust. Omit upstream APIs that require raw pointer manipulation, or retain a throwing stub when an explicit unsupported entry point is useful. Do not expand the native layer or invent wrappers just to expose them. Keep implementation, declarations, and reference documentation consistent with that decision. Preserve native memory safety without adding checks for states excluded by the supported type model. ### Put binding semantics in the runtime The TypeScript runtime owns marshalling, `GValue` and `GVariant` conversion, input/output/inout handling, tuple returns, callback conventions, signals, class registration, subclassing, safe-handle wrapping, and implementations of non-introspectable functions. Rust supplies storage and call frames; runtime defines their JavaScript contract. For example, runtime chooses which outputs become tuple members, while native code keeps their memory valid. Runtime has no knowledge of libgirepository. Consumers supply explicit descriptors and shapes, normally through generated GI modules. Do not discover signatures or reconstruct a JavaScript API through runtime introspection. ### Generate executable bindings Generate executable ESM classes and functions and their TypeScript declarations from the same model. Their methods call native functions through runtime. Generating only types while synthesizing JavaScript classes through libgirepository violates this boundary. Binding construction belongs in generation and builds. GType registration for application subclasses remains a runtime operation using explicit class definitions and metadata. ### Keep library behavior in overrides Overrides are TypeScript modules compiled into the generated package beside the namespace they extend. Put behavior that needs concrete generated types there: helpers on GI types, application lifecycle, and upstream workarounds. Add to runtime only the general binding support they need. Runtime depends only on `@gtkx/native` and `@gtkx/utils` and never imports generated bindings, not even their types, because generated bindings import runtime. ### Keep the reconciler transparent Translate React host operations into native construction, prop updates, signal handlers, and child attachment, removal, and reordering. Preserve the corresponding GTK, Adwaita, and GObject semantics. Host removal includes disconnecting the instance's handlers. Mount/unmount effects, presentation, list factories, and other abstractions belong in components and hooks. Do not introduce a separate reconciler lifecycle system or teach it application-specific behavior for new elements. Use Adwaita for application structure and adaptive patterns, with GTK4 for lower-level primitives. ## Prefer declarative GObject creation Create widgets and non-widget GObjects through JSX so React owns their creation, updates, relationships, and removal. There are two exceptions: - A synchronous GTK signal needs a newly created object as an immediate return value or out parameter, before the handler returns. - `useToast().show()` creates an ephemeral `Adw.Toast`; the overlay owns its presentation and dismissal. Persistent models still belong in JSX. Ordinary handlers, effects, setup code, helpers, and convenient native constructors do not create further exceptions. ## Use one source of truth Give every type, descriptor, mapping, and implementation one owner. Import or derive it elsewhere. Codegen must reuse descriptor types exposed by `@gtkx/native`; bindings, declarations, JSX props, and reference pages must share their metadata. Fix generated behavior in its model, generator, configuration, overrides, or runtime, then regenerate. Share implementations where the contract is shared, keeping abstractions no broader than that contract requires. ## Prefer maintained dependencies over custom implementations Prefer a maintained package over an equivalent custom implementation, including when it covers only part of the required behavior. Check existing dependencies first, then assess maintenance, compatibility, and the required contract. Keep custom code focused on GTKX integration and missing behavior. Apply this during review too: replace existing custom implementations when a maintained dependency fits. Retain upstream workarounds until official releases contain the fix and GTKX's supported versions no longer need them. ## Prefer simple code and trust the types Express invariants through types, constructors, ownership, and control flow. Do not use TypeScript non-null or definite-assignment assertions, or `as unknown as` casts. Avoid checks for types or nullability already guaranteed by the model, and fallbacks, retries, synchronization, or compatibility paths for unsupported states. Supported edge cases need behavior and tests; imagined use cases and impossible typed states do not justify machinery. Use `Rc` for Rust state confined to one thread. Do not add `Arc` for that state or a directory lockfile when the supported process model guarantees one owner. ## Keep generation metadata free of native initialization Generation configuration and metadata must be importable without loading generated GI bindings or initializing the UI. Keep descriptions separate from native operations, as in [`builtin-elements.ts`](https://github.com/gtkx-org/gtkx/blob/main/packages/config/src/builtin-elements.ts) and [`element-behaviors.ts`](https://github.com/gtkx-org/gtkx/blob/main/packages/react/src/element-behaviors.ts). Preserve that boundary for new props, elements, and extensions. ## Respect the native UI thread GTK objects and operations belong to the Node thread owning the GLib main context. Workers can compute and exchange plain data with it; they cannot manipulate its GTK objects. Follow the owning-thread contract in [`runloop.rs`](https://github.com/gtkx-org/gtkx/blob/main/packages/native/src/runloop.rs) and [`handle.rs`](https://github.com/gtkx-org/gtkx/blob/main/packages/native/src/handle.rs). Cross-thread synchronization does not improve state already confined to its owner. ## Test behavior at the right level Aim for roughly 80% integration, 10% end-to-end, and 10% unit coverage. Integration tests exercise framework code directly; end-to-end tests drive the real user interface. Use consumer interfaces: render and interact with widgets, call generated bindings against real libraries, or build and run an installed application. Use unit tests for complex logic that benefits from focused case coverage. A pure function or routine helper does not need a test solely because it exists. Test observable behavior, never private helpers, intermediate values, or implementation details. Cover happy paths, supported edge cases, and errors. For errors, assert only that the operation throws or rejects and check status codes where applicable. Do not assert message text, logs, console formatting, or cosmetic details. ### Minimize mocks Use real implementations. Use mocks only for slow operations or isolation that real behavior cannot provide, covering the smallest necessary surface. Do not mock the renderer, native bindings, or package internals. Use native fixtures, real widgets, isolated displays, and local services. [Testing](/contributing/testing) lists suites and commands. ## Write self-explanatory code Use clear names, direct control flow, and small responsibilities. Comments must not compensate for unclear code. GTKX is GLib-first: omit the `G` prefix from our identifiers, as in `useObjectValue`. Use GTK prefixes where they clarify a name, and preserve upstream names when referencing native APIs. Reserve comments for public API documentation, TODO/FIXME notes and upstream workarounds. Describe contracts and reasons, without narrating implementation. Each upstream workaround needs a nearby comment explaining why it exists. While an upstream fix is expected, make it a `TODO:` that also says when the workaround can be removed and links its GTKX tracking issue. Public API documentation describes the current API. Discuss earlier implementations only when documenting a deprecation and its transition. ## Write focused, consistent documentation Use concise, plain language, one idea at a time, with consistent terminology and structure. Give readers the context they need without repeating it across pages. Guides and tutorials explain GTKX concepts and tasks with small examples. Link to API reference for specifications, type definitions, and exhaustive member lists. Assume familiarity with the underlying languages and libraries; link to their official documentation for background. Explain GTKX's integration with React, GTK, and Adwaita without reteaching those projects. Use **The React framework for Linux** as the slogan. GTKX is the product name. Name GNOME, GTK, and Adwaita when explaining their role. Describe features and limitations directly, without unsupported comparisons. ## Keep production code focused on consumers Production behavior must serve consumers. Keep workspace layout, linking, cache, test, and build-orchestration fixes in repository configuration, scripts, fixtures, or the environment. Do not add production resolution fallbacks, path special cases, or concurrency mechanisms just to accommodate this checkout. Validate behavior in an ordinary consumer project. The [consumer and packaging guidance](/contributing/testing#consumer-and-packaging-checks) distinguishes workspace fixtures from installed-package validation. --- --- title: "Maintaining Documentation" description: "Edit and verify the GTKX website, maintain versioned references, and promote a documentation release." --- # Maintaining Documentation This page covers editing and checking the gtkx.dev website, its pictured samples and brand assets, and the versioned documentation, including promoting a prerelease to stable. ## Edit and preview The VitePress site lives in `website/`. Run these commands from the repository root: ```bash pnpm nx run @gtkx/website:dev pnpm nx run @gtkx/website:build ``` Both targets build the packages and generate the API reference with [TypeDoc](https://typedoc.org/) before running VitePress. Build the site and inspect the rendered pages after editing prose, navigation, or theme components. The API reference is generated from the JSDoc in each package's source, so edit the comment there and regenerate; edits to generated reference files are overwritten. It covers the helpers GTKX packages export. Widget elements and their props are documented in each app's generated [`.gtkx/reference`](/contributing/code-generation) instead. The [documentation principles](/contributing/principles#write-focused-consistent-documentation) cover style and scope. ## Structure and style Keep the main navigation focused on the Guide, Config, Tutorial, API Reference, and Examples. Project resources belong in the Project menu. Add a guide to the sidebar group that matches the reader's task, and keep the tutorial in chapter order. Use the [React documentation](https://react.dev/learn) as a reference for separating learning from API lookup, the [Vue guide](https://vuejs.org/guide/introduction.html) for topic grouping and learning paths, and [Electron's documentation](https://www.electronjs.org/docs/latest/) for the desktop workflow from setup to distribution. GTKX examples must still use this project's generated APIs; upstream GTK or Adwaita examples describe native concepts, not GTKX syntax. Start a page with its purpose and prerequisites. Explain the GTKX-specific steps and link to reference details. Every page ends with a pager to the previous and next sidebar entries, so add a `## Next` section only when the reader's next step leaves the sidebar order, such as Getting Started pointing to the tutorial. Prefer complete, small examples over repeated API inventories. Package READMEs should identify the package, show installation or its intended entry point, and link to the matching guide and reference. Package descriptions and keywords should describe that package's role and relevant integrations. Describe observable behavior and explain its limits. Avoid unsupported performance claims and words such as "easy" or "simple" that substitute for explaining a task. List command or tool options in a table whose first header is `Option` or `Tool`, with the default or a short attribute next and the description last. On phones the site stacks each row of such a table into an entry. Keep code sample lines within 80 columns. A desktop code block shows about 76, so longer lines scroll sideways. The formatter wraps pictured samples in `website/figures/` at 80 columns but leaves code inside Markdown alone, so wrap inline samples by hand. Check commands, imports, exported names, defaults, and requirements against the version being documented. The working tree is authoritative for the development docs; use the pinned release for stable docs. Preserve historical release announcements and changelogs as records of those releases. Before publishing documentation changes: - Build the website to check page registration, Markdown, and page links. Check heading fragments too; a successful page-link check does not prove an anchor exists. - Inspect desktop and mobile navigation, the version switcher, and search on the rendered site. - Run changed examples with the documented dependencies. For tutorial edits, apply the chapter's changes to the preceding chapter, not only to the finished application. - Keep old URLs and heading anchors usable when reorganizing content. Update package READMEs and metadata when a package's role changes. ## Pictured samples A sample whose result is visual shows the window it renders. Keep the sample in a file under `website/figures/` (`guide/` or `tutorial/`), show it on the page with a [snippet import](https://vitepress.dev/guide/markdown#import-code-snippets) such as `<<< @/figures/guide/components-list-view.tsx`, and add it to the `figures` list in `website/figures/capture.test.tsx`. The page then shows the code that was captured. Give the entry a third element, an options object, when the capture needs more than a render: `before` runs before rendering, for example to seed files the sample reads; `prepare` runs after rendering, for example to wait for content or to narrow the window to the pictured state; `after` cleans up. Give pictured samples the margins a real app would use, so content does not touch the window edge. A tutorial chapter that spans several files keeps them under `website/figures/tutorial//`, laid out like the reader's project (`src/`, `data/`, `tests/`), so their relative imports match. Later chapters show `diff` blocks against these files, so after changing one, check that each later diff still applies at its stated lines. Regenerate the images after changing a pictured sample: ```bash pnpm nx run @gtkx/website:figures ``` The target renders each sample with `@gtkx/testing` in Adwaita's light and dark styles and writes `website/public/figures/-light.png` and `-dark.png` at scale 2. Commit the images: the site build reads them and needs no display. The capture points `HOME`, `XDG_DATA_HOME`, `XDG_CONFIG_HOME` and `XDG_CACHE_HOME` at a temporary directory (`website/figures/setup.ts`), so samples that save data never read or write your own, and gives windows GNOME's default close-only title bar. It pins the interface font to Adwaita Sans 10, so the text does not depend on your desktop's font settings, and needs [Adwaita Sans and Adwaita Mono](https://gitlab.gnome.org/GNOME/adwaita-fonts), GNOME's interface fonts since GNOME 48, installed system-wide: without them every image changes. The website `typecheck` target checks the sample files. Place the figure where the text says what the reader should see. Its two images follow the site theme, and the caption links the code: ```html
… …
Captured from the sample above.
``` Set `width` and `height` to half the PNG's pixel size, and describe the window in `alt`. Keep `class`, `src` and `width` in this order on one line: the site finds them there to link each image wider than 400 to the PNG, so phone readers can open it at full size. The landing page's hero and the tutorial introduction show the `landing-*` captures of the finished Notes app. A capture can also measure parts of its window: give its entry a `regions` function that returns the bounds of the widgets to mark. The target writes them to `website/.vitepress/theme/landing/hero-regions.json`, which the hero reads to place its hotspots over the image. Commit that file with the images so the two never drift apart. ## Recorded samples A sample whose result is motion shows a short looping clip. Keep the sample under `website/figures/` as a pictured sample is, and add it to the `clips` list in `website/figures/record.test.tsx` with its window size and a `play` function. `play` sets the stage, then calls `take` around the part to record. `playSample` covers the common case: it renders a component in a window and turns one boolean prop on, then off. The Fast Refresh clip records the real dev server. It copies the chapter as it stands before its edit to `website/figures/.clips/`, runs `gtkx dev` on `website/figures/clips/fast-refresh.tsx`, which opens the pictured note, and saves the chapter's changes while recording. Regenerate the clips after changing a recorded sample: ```bash pnpm nx run @gtkx/website:clips ``` The target records each clip on the test worker's headless display, in Adwaita's light and dark styles, with the same isolated directories and pinned font as the figures. It sizes the display to the window at scale 2, captures frames with `grim`, and encodes them as VP9 with `ffmpeg`. Each clip is written to `website/public/clips/` as `-light.webm` and `-dark.webm`, with its last frame as a `.png` poster. Besides the fonts the figures need, install `grim` and an `ffmpeg` built with `libvpx-vp9`. Commit the files: the site build reads them and needs none of these tools. A take fails when the machine captures fewer than 30 frames a second or the clip is larger than 400 KB. Shorten the clip before lowering its quality. Two recordings never have the same bytes, so commit new ones only when a recorded sample changed, and play them before committing. Show a clip with the `WindowClip` component in place of the two images: ```html
Recorded from the sample above.
``` Set `width` and `height` to the window size given in `record.test.tsx`. The component plays the clip for the current theme once it scrolls into view, muted and looping, with a button that pauses it. Readers who prefer reduced motion get the poster with playback controls instead. ## Brand assets The mark and the wordmark live in `website/public/`. Use these files instead of setting the name in text next to the mark. | File | Use | | --------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `gtkx-mark.svg` | The red tile: favicon, app icons, avatars. Never recolor it. | | `logo-wordmark-light.svg`, `logo-wordmark-dark.svg` | The mark followed by "GTKX" in Red Hat Display 800, as outlines, for light and dark backgrounds. The site's navigation and footer, the README, and `og.png` use them. | | `gtkx-glyph.svg` | The orbits without the tile, in `currentColor`, for single-color and small inline uses. | | `og.png` | The social card of every page. Its source is `website/scripts/og.html`; after editing it, run `node website/scripts/og.mjs`, which renders it with a local Chromium. | - Leave clear space of at least one orbit width (11/128 of the tile, at least 4px) around the mark. - Don't set the wordmark in another typeface, in the gradient, or in red. - Don't place the red tile on a red or photographic background; use the glyph instead. - Red text uses `--text-brand`, and the large headline accent uses `--gradient-text`, which has a light and a dark value (`website/.vitepress/theme/styles/tokens.css`). Keep `--brand` for the mark, the glow, focus rings, and other non-text accents. ## Documentation versions [`website/versions.json`](https://github.com/gtkx-org/gtkx/blob/main/website/versions.json) defines each documented version: | Field | Purpose | | ------------- | ------------------------------------------------------------------------------------------ | | `id`, `label` | Identify the version and label its switcher entry. | | `prefix` | Place its guides, tutorial, and reference. | | `aliases` | Retain previous prefixes with static redirects and text downloads. | | `status` | Mark it as `current`, `prerelease`, or `old`. | | `examplesRef` | Select the git ref used by the Examples navigation link. | | `reference` | Build the API reference from the working tree (`worktree`) or a pinned `tag` and `commit`. | The manifest drives navigation, sidebars, page mapping between versions, banners, canonical URLs, per-version `llms.txt` and `llms-full.txt`, and TypeDoc output paths. Exactly one version must use `worktree`; the build rejects any other count. Its empty `label` derives from the version in `packages/create-gtkx/package.json`, which also supplies the prerelease installation command on the landing page. A tag-pinned version records its shipped label and rebuilds from the specified tag and commit, keeping its API reference tied to the release. Each release tag retains one working-tree entry so its own checkout can regenerate that reference when archived. Between releases, the current version uses the working tree and follows `main`. When adding the next prerelease, make it the working-tree version, pin the outgoing current reference to its release tag and commit, and write its derived label into the manifest. Reference generation checks the Nx output paths in `website/project.json` against the manifest. A mismatch fails the build because stale paths could restore cached output to the wrong directory. Synchronize declarations after changing prefixes: ```bash pnpm --filter @gtkx/website reference-sync ``` ## Add or move pages Guide and tutorial pages live under their version's prefix: `website/guide` for the root version and `website/v2/guide` for `/v2`. Register them in `guideGroups` or `tutorialItems` in `website/.vitepress/versioning.ts`. The build rejects unlisted pages so versions cannot silently diverge. Contributor pages follow `main` independently of releases. Register them in `website/.vitepress/contributing.ts`. They appear in every version's navigation, search, and `llms.txt` exports, and remain at `/contributing/` during promotion. Keep existing heading anchors when reorganizing a page, or leave links to the moved material. Check links in both rendered pages and generated reference output. ## Promote a prerelease Complete promotion on the prepared release branch before advancing `main`. That push starts tagging and publishing automatically; the tag must already contain the stable documentation and package READMEs. 1. [Prepare the stable release](/contributing/releases#prepare-a-release) with `specifier=2.0.0`, then check out the resulting `release/next` branch. Confirm that package versions, including `packages/create-gtkx/package.json`, are `2.0.0`; the website derives its working-tree label from that version. Promotion changes documentation placement; it does not bump the release version. For a local rehearsal, run `pnpm prepare-release --specifier 2.0.0` in an isolated checkout instead. 2. Before retiring an existing `old` version, review links to its prefix and aliases, including historical posts. Point those links to a supported guide or a source permalink at the appropriate release tag. Delete the retired version's directories and manifest entry, then run `pnpm --filter @gtkx/website reference-sync`. Promotion refuses to proceed while an old version remains. The outgoing current version must already have a pinned reference tag and commit. 3. Move the current documentation to its archive prefix and the prerelease to the root: ```bash pnpm --filter @gtkx/website promote-version \ --to /v1 --examples-ref v2.0.0 ``` 4. Review release copy in the promoted `website/guide`, `website/tutorial`, contributor pages, landing components, the [Releases](/releases) page, root `README.md`, and `packages/*/README.md`. Replace beta installation commands and current-release status text with stable equivalents. Point 2.0 links at the new root paths and 1.x links at `/v1`; retain historical release names in dated posts and changelogs. Archived 1.x installation commands must remain pinned to 1.x. Point the root README's version and Node.js badges at the `latest` dist-tag instead of `beta`, and keep its link to `FUNDING.md`. 5. Review the release's announcement post, `website/blog/gtkx-2-0.md`. A post whose `date` is later than the build day (UTC) is left out of the build, the blog index, the sidebar and the RSS feed, so it goes live with the first deploy on or after its date, and a preview before that day doesn't show it. Its date must be the release day, its release-notes link must name the tag being published, and its summary of changes must match the changelog. 6. Regenerate both API references, build the site, and serve the build: ```bash pnpm nx run @gtkx/website:preview ``` Check the landing links, version switcher, guide and tutorial sidebars, local search, generated references, old page anchors, and each version's `llms.txt` and `llms-full.txt`. The promoted version should be labeled stable, and archived pages should show their old-version banner. Inspect the root and archived Markdown downloads too. 7. Include these changes in the reviewed, signed release-branch history, then follow [Review and advance main](/contributing/releases#review-and-advance-main). A subsequent Release workflow run rebuilds that branch from `main`; it must not discard the reviewed promotion changes. The script moves each version's `guide`, `tutorial`, and `reference` directories, updates `versions.json`, and synchronizes the Nx reference output paths. It rewrites absolute documentation links in website Markdown by the version they target, preserving intentional links between versions. Prerelease guides and tutorial chapters link to examples and tutorial sources on `main`; the script pins those `tree/main` and `blob/main` links in the promoted version's pages to `--examples-ref`, which also becomes its `examplesRef`, so the stable pages keep pointing at the release they document. It does not rewrite beta prose or package commands, such as Getting Started's note that the tutorial follows `main`, and it does not edit files outside `website/`. Generated reference links are corrected by regeneration. Promotion keeps the new current reference on `worktree`. Pinning it now would leave no working-tree version; wait until adding the next prerelease, as described above. Promotion records the former prerelease prefix in the version's `aliases`. The production build emits static redirects for its guide, tutorial, and reference pages, preserving URL queries and heading fragments. It also copies Markdown downloads and `llms` exports under that prefix. Aliases stay out of navigation, search, and the sitemap; their canonical URLs point to the version's current pages. They follow the version when it is archived and disappear when its manifest entry is retired. An old page uses the current version's corresponding page as its canonical URL when that page exists. Otherwise it keeps its own canonical URL, including reference pages for removed symbols. --- --- title: "Publishing Releases" description: "Prepare, review, tag, and publish a GTKX release, and recover an interrupted publish." --- # Publishing Releases This runbook is for maintainers. Contributors record user-facing changes with [version plans](https://github.com/gtkx-org/gtkx/blob/main/CONTRIBUTING.md#add-a-version-plan). ## Prepare a release Run the Release workflow from GitHub Actions or the CLI: ```bash gh workflow run release.yml ``` Release preparation runs only on request and never writes to `main`. The same workflow tags prepared releases after main CI succeeds. | Inputs | Result | | ----------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | Both empty | Consume pending plans. For stable versions, apply the requested bump; for prereleases, increment the existing prerelease version. With no pending plans, stop without opening a pull request. | | `specifier=2.0.0` | Prepare version 2.0.0, even without pending plans. | | `preid=rc` | Change the prerelease identifier, even without pending plans. | The workflow versions all packages, sets the tutorial's `@gtkx/*` ranges to the new version, prepends release notes to `CHANGELOG.md`, and deletes consumed plans. It opens or refreshes `release/next` as the release bot, with a GitHub-signed commit. Preview those preparation steps locally without writing files: ```bash pnpm prepare-release --dry-run ``` The release GitHub App needs read and write access to contents and pull requests. Its credentials are the repository variable `RELEASE_APP_CLIENT_ID` and secret `RELEASE_APP_PRIVATE_KEY`. For the first stable release, complete [documentation promotion](/contributing/documentation#promote-a-prerelease) on the prepared release branch before advancing `main`. Include website copy and root and package README updates so the tag contains stable commands, status, and documentation links. Version preparation does not update that prose or move pages; the website's version label follows the new `packages/create-gtkx` version on its own. ## Review and advance main Review `release/next`, approve its latest commit, and wait for its required checks. Merge through GitHub using the repository's configured squash method. GitHub creates the signed commit on `main`; CI then verifies that exact merge commit. If `main` has moved or the prepared release changes, run the Release workflow again with the same inputs and review the new head before merging. A refresh rebuilds `release/next` from `main` and discards commits pushed to it, including documentation promotion. Repository merge rules enforce review approval, the `Verify workspace` check, and CodeQL merge protection. Release automation relies on those rules. CodeQL also runs on `main`, independently of CI; tagging does not wait for that analysis. ## Tag and publish Successful completion of main CI starts the tag job in the Release workflow. It requires that commit to be the merge of `release/next` and recognizes a prepared release from the version's changelog entry and release state. It creates the annotated `vX.Y.Z` tag and draft GitHub release, then dispatches Publish from that tag. A normal commit without a prepared version does not publish. Rerunning the successful CI run can redispatch the same draft. To curate the notes, edit the draft while Publish runs: ```bash gh release edit vX.Y.Z --notes-file notes.md ``` Publish takes no inputs; its dispatched ref identifies the release. Validation requires a tag matching the package version and a matching draft release. When dispatching Publish manually, maintainers are responsible for selecting a reviewed release commit with successful CI. Both native binaries and their generated JavaScript and type declarations are built on Ubuntu 26.04 runners and uploaded with SHA-256 checksums. After dependency installation, `pnpm release --from-artifacts` selects the `release-artifacts` Nx configuration throughout the release dependency graph. The publication build verifies and restores the staged native bindings without recompiling. Publication requires both architectures to produce identical shared JavaScript and declarations. Every Publish run shares a single queue, including different versions and retries. Each package is published directly to its stable or prerelease channel with `pnpm publish --tag`, and its exact version and channel tag must become visible before publication continues. The channel can only move forward. npm cannot publish multiple packages atomically, so channel tags advance package by package. The final job runs `node scripts/release/publish-release.ts --verify-only` to freshly check every exact package version and channel before publishing the GitHub draft, preserving its notes, and dispatching Website for that tag. A retry of that job fails if a newer release has advanced any package channel. This dispatch is needed because releases published with the workflow token do not trigger Website themselves. The publication job uses the `npm-release` GitHub environment. Configure each npm trusted publisher to allow `npm publish` and require that environment and `publish.yml`, limit the environment's deployment tags to `v*`, and enable immutable releases. Environment reviewers are optional. The publishing client authenticates through [npm trusted publishing](https://docs.npmjs.com/trusted-publishers/) and sets the channel tag as part of publication. The workflow does not use separate `npm dist-tag` updates or `npm stage publish`. ## Retry a failed publish A failed build, upload, or registry check leaves the GitHub release in draft. Fix the cause and rerun Publish on the same tag. A rerun uses the workflow files and scripts stored at that tag, so a fix merged to `main` does not reach it; when the cause is in the tagged code, prepare a newer release. Already-published versions are skipped and checked for both exact-version visibility and the expected channel tag. Missing packages are published directly to that channel, then the complete package family is verified. If any package in the channel has advanced beyond the candidate version, the retry fails before publishing anything. An old partial release cannot move the channel backwards; prepare a newer release to supersede it. If an existing version has a missing or incorrect channel tag, the retry fails rather than attempting a separate tag update with OIDC. A maintainer must correct the tag through authenticated npm access, or prepare a newer release. Existing package versions and Git release tags must remain unchanged. If the GitHub release was published but the Website dispatch failed, rerun only the failed `publish-release` job. It recognizes the already-published release and retries the Website dispatch without editing the published release. Starting a new full Publish run still requires a draft. ## Other versions - [GTKX 1.6 stable](https://gtkx.dev/llms.txt)