# GTKX 1.6 stable
> The React framework for Linux. Build native Adwaita and GTK apps with the workflow of modern web development.
@doc-version: 1.6
@doc-status: current
GTKX 1.6 stable is the current release.
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 1.6 stable documentation
---
title: "Why GTKX"
description: "Where GTKX fits: native Linux interfaces, React state, and Node.js libraries."
---
# Why GTKX
GTKX builds native Linux applications with React and TypeScript. JSX creates Adwaita and GTK widgets; React keeps them in sync with application state.
## Platform scope
GTKX supports Linux. Its widgets follow GTK and Adwaita conventions and can run on Linux desktops with the required libraries. It does not provide a Windows, macOS, mobile, or browser renderer.
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](/guide/css), whose properties and layout differ from the web.
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](/guide/deploying).
## Why Node.js
An app runs on Node.js and can use its standard library and compatible npm packages. GLib and Gio bindings are also available for platform APIs such as settings, actions, and notifications.
Check a package's runtime assumptions before adding it. A browser package may require `window` or `document`; a native Node addon must match the deployment architecture and runtime. Keep expensive computation off the UI thread so the window remains responsive.
## Development tools
- The CLI scaffolds projects, runs Fast Refresh, and builds application bundles and Linux packages.
- [Navigation](/guide/navigation) maps React Navigation to native page stacks, tabs, drawers, and split views.
- [Components](/guide/components) render collections and notifications; [forms](/guide/forms) connect native controls to React Hook Form.
- [Testing](/guide/testing) drives the native interface. The [MCP server](/guide/mcp) lets coding agents inspect widgets, interact with the app, and capture screenshots.
## Next
[Getting Started](/guide/getting-started) opens a first window. The [tutorial](/tutorial/) builds Tasks, a task manager with persistence and navigation.
---
---
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 GTKX 1.6.
## What you need
GTKX requires Linux, Node.js 24 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 on Fedora 44
Install the development packages, which supply both native libraries and the GIR files used to generate bindings:
```bash
sudo dnf install gtk4-devel libadwaita-devel glib2-devel gobject-introspection-devel pkgconf-pkg-config
```
The package names are listed in Fedora's [GTK](https://packages.fedoraproject.org/pkgs/gtk4/gtk4-devel/), [libadwaita](https://packages.fedoraproject.org/pkgs/libadwaita/libadwaita-devel/), and [GObject Introspection](https://packages.fedoraproject.org/pkgs/gobject-introspection/gobject-introspection-devel/) package documentation. Check the installed versions:
```bash
pkg-config --modversion gtk4 libadwaita-1 glib-2.0
```
Other distributions need equivalent development packages meeting the minimum versions above. See [GTK's Linux installation guide](https://www.gtk.org/docs/installations/linux) for package names. A runtime-only package is insufficient for code generation.
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 [npm]
npm create gtkx@1.6.0
```
```bash [pnpm]
pnpm create gtkx@1.6.0
```
```bash [yarn]
yarn create gtkx@1.6.0
```
:::
Choose a project directory, an application ID such as `com.example.MyApp`, and your package manager. Enable TypeScript and the Vitest setup to follow the tutorial. Then run:
```bash
cd my-app
npm run dev
```
The 1.6 starter is a GTK counter. The tutorial replaces its shell with an Adwaita application window. Click the button to increase the count. Change its label in `src/app.tsx` and save; the open window should update.
## The dev loop
`npm run dev` runs `gtkx dev`. Fast Refresh updates edited components in the open window. Changes it cannot patch restart the app.
| 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](/guide/deploying) |
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
├─ src/
│ ├─ index.tsx
│ ├─ app.tsx
│ └─ gtkx-env.d.ts
└─ tests/
└─ app.test.tsx
```
`gtkx.config.ts` holds the application ID and library configuration. The component lives in `src/app.tsx`; `src/index.tsx` renders it. The testing files are included when you enable Vitest during setup.
## 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`. [Create a Window](/tutorial/your-first-window) explains the application, window, and close handler.
## Troubleshooting
- **Missing GIR file:** install the library's development package, then run `npx gtkx codegen` from the project. For libraries outside the standard directories, set [`girPath`](/guide/configuration-and-codegen#the-config-file).
- **Native versions are too old:** use a distribution or development container that meets the minimums. Installing newer TypeScript packages does not upgrade GTK or libadwaita.
- **No display connection:** run from a desktop terminal or configure your container's display and session access. Tests have a separate [headless setup](/guide/testing#setup).
- **Dependency installation failed:** the generated files remain in the project directory. Resolve the package manager's error and rerun its install command there. For pnpm release-age restrictions, see the [pnpm settings](https://pnpm.io/settings/dependency-resolution#minimumreleaseage).
## Next
- [Tutorial](/tutorial/): build Tasks, a task manager with persistence, navigation, and packaging.
- [Configuration and Codegen](/guide/configuration-and-codegen): select native libraries and understand generated imports.
---
---
title: "Modals and Portals"
description: "Render windows, Adwaita dialogs, and objects outside their surrounding container."
---
# Modals and Portals
GTKX windows and Adwaita dialogs handle their own native placement. Use `createPortal` for other objects that belong outside their surrounding widget container.
## createPortal
`createPortal` from `@gtkx/react` renders into a compatible native object. Capture that target with a state callback ref so the portal renders once the widget exists:
```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` when an object needs React ownership without a native parent. See the [`createPortal` reference](/reference/@gtkx/react/index/variables/createPortal) for its arguments and React's [portal documentation](https://react.dev/reference/react-dom/createPortal) for component lifetime.
## Windows
Windows portal themselves. A window element mounts at the top level wherever it sits in the JSX, so opening one is a conditional render:
```tsx
import { AdwApplicationWindow, AdwHeaderBar, AdwToolbarView } from "@gtkx/jsx/adw";
const MirrorWindow = ({ open }: { open: boolean }) =>
open ? (
} />
) : null;
```
A window element presents itself on mount and destroys the window on unmount. `AdwApplicationWindow` registers with the application ancestor it finds in the React tree, normally `AdwApplication`, and throws when there is none. `AdwToolbarView` and `AdwHeaderBar` give the secondary window a header and toolbar layout. Relationships between top-level windows are expressed with `transientFor`, which the underlying `GtkWindow` defaults to the nearest window ancestor in the React tree; pass it explicitly to point at another window, or pass `null` for a fully independent one.
Handle `onCloseRequest` by clearing the state that rendered the secondary window.
## Dialogs
Mounting an `AdwDialog`, or any element derived from it, presents the dialog; unmounting it closes the dialog. These elements come from `@gtkx/jsx/adw`, which exists once `Adw-1` is bound — a scaffolded project binds it from the start.
```tsx
import { AdwDialog } from "@gtkx/jsx/adw";
import { GtkLabel } from "@gtkx/jsx/gtk";
const Notice = ({ onClose }: { onClose: () => void }) => (
Nothing to report.
);
```
Use `AdwDialog` for custom content, `AdwAlertDialog` for a message and response buttons, or `AdwPreferencesDialog` for preferences. Each follows the same lifecycle. Place content in its supported JSX slots; for example, `AdwPreferencesDialog` takes `AdwPreferencesPage` children.
Set `canClose={false}` when the dialog must stay open, and handle `onCloseAttempt` to respond to a close request. Unmounting still closes the dialog unconditionally.
`AdwAlertDialog` is the message-and-buttons modal. Its `heading` and `body` props are plain strings, it takes a declarative `responses` array, and the chosen button's `id` arrives on `onResponse`:
```tsx
import * as Adw from "@gtkx/gi/adw";
import { AdwAlertDialog } from "@gtkx/jsx/adw";
import { GtkEntry } from "@gtkx/jsx/gtk";
const RenameDialog = ({ onResponse }: { onResponse: (id: string) => void }) => (
);
```
Children fill the dialog's extra slot, below the heading and body and above the response buttons. `extraChild` is not part of the element's prop surface, so children are the only way to fill it.
## Finding the parent window
`useParentWindow()` from `@gtkx/react` returns the `Gtk.Window` provided by the nearest window ancestor, or `null` when there is none. It resolves through the React tree, so a dialog portaled out of a window's subtree still finds that window.
The tutorial builds these surfaces in [Mounting dialogs](/tutorial/actions-menus-shortcuts#mounting-dialogs), [Confirming a permanent delete](/tutorial/trash-and-toasts#model-the-confirmation), and [A dialog that is a form](/tutorial/trash-and-toasts#add-the-new-list-dialog). The exported API is in the [@gtkx/react reference](/reference/@gtkx/react/).
## Next
Continue with [Navigation](/guide/navigation) to move between screens with stack, tab, drawer, and split view navigators drawn by libadwaita.
---
---
title: "Components"
description: "Render lists, tables, dropdowns, and toast notifications from React state."
---
# Components
`@gtkx/components` renders native collections from data and render functions. It manages their GTK models and factories. `@gtkx/components/adw` provides `ComboRow` and toast helpers.
`@gtkx/components` is a separate install:
```bash
npm install @gtkx/components@1.6.0
```
See the [component reference](/reference/@gtkx/components/) for props. Hooks that connect GObject state to React come from [`@gtkx/react`](/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.
```tsx
import { ListView } from "@gtkx/components";
import * as Gtk from "@gtkx/gi/gtk";
import { GtkLabel } from "@gtkx/jsx/gtk";
items={tasks.map((task) => ({ id: task.id, value: task }))}
selectionMode={Gtk.SelectionMode.MULTIPLE}
selectedIds={selectedIds}
onSelectionChanged={setSelectedIds}
estimatedItemHeight={56}
renderItem={({ item }) => {item.title}}
/>
```
Nesting `ListItem.children` turns the same component into a tree, with `expandedIds` and `onExpandedChange` driving expansion.
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.
### GridView
`GridView` renders a grid with the same `items`, `renderItem`, controlled selection, and size estimates as `ListView`. 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
import { ColumnView, type ColumnViewColumn } from "@gtkx/components";
import { GtkLabel } from "@gtkx/jsx/gtk";
const columns: ColumnViewColumn[] = [
{ id: "name", title: "Name", isSortable: true, renderCell: ({ item }) => {item.name} },
];
({ id: emp.id, value: emp }))}
columns={columns}
/>
```
`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.
### DropDown
`DropDown` takes `items`, or `sections` plus `renderHeader`, with single controlled selection through `selectedId` and `onSelectionChanged`. Values have a default text display. Pass `renderItem` to draw both the selected value and the popup rows, or `renderListItem` to override only the popup rows.
```tsx
import { DropDown } from "@gtkx/components";
({ id: type, value: type }))}
selectedId={sourceType}
onSelectionChanged={setSourceType}
/>
```
`ComboRow` from `@gtkx/components/adw` takes the same collection props and renders an `Adw.ComboRow` inside a preferences group. See the tutorial's [preferences chapter](/tutorial/preferences-and-theming) for an example.
### 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
import { AdwActionRow } from "@gtkx/jsx/adw";
import { GtkListBox } from "@gtkx/jsx/gtk";
view.id === activeId)}
onRowSelected={(row) => {
if (!row) return;
const view = views[row.getIndex()];
if (view) setActiveId(view.id);
}}
>
{views.map((view) => (
))}
```
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. 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.
The tutorial's [sidebar](/tutorial/lists-and-the-sidebar#keeping-gtk4-and-the-route-in-agreement) controls selection from the current route.
## Toasts
Wrap the window's content in `AdwToastOverlay`, then share its ref through `ToastProvider`. Descendants can call `useToast()` to show a notification:
```tsx
import { ToastProvider, useToast } from "@gtkx/components/adw";
import type * as Adw from "@gtkx/gi/adw";
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 (
);
};
```
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 toast. Pass `buttonLabel` and `onButtonClicked` to add an action, and `onDismissed` when cleanup depends on its dismissal. Call `useToast().dismiss(toast)` to close the returned toast, or `useToastOverlay().dismissAll()` to clear the overlay. Both hooks come from `@gtkx/components/adw`.
`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. The [Trash and Toasts tutorial](/tutorial/trash-and-toasts) adds an Undo action to a delete operation.
## Next
Continue with [Modals and Portals](/guide/modals-and-portals) for the mounting model behind these components: `createPortal`, the `rootElement` container, and extra windows. The tutorial demonstrates dialogs in its [Menus, Accelerators, and Shortcuts](/tutorial/actions-menus-shortcuts#mounting-dialogs) chapter.
---
---
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/main/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:
```tsx
import { GtkButton } from "@gtkx/jsx/gtk";
;
```
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 that change with an individual widget. GTKX applies its rules through a provider scoped to that widget, and frequent changes still make GTK recalculate styles. Prefer native animated properties or CSS transitions when they express the effect. See [Animations](/guide/animations) for animated styles.
## Create reusable classes
`css` accepts a tagged template or style object and returns a class name for `cssClasses`:
```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;
}
`;
;
```
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 properties.
## Apply global rules
`injectGlobal` inserts selectors without a generated class:
```ts
import { injectGlobal } from "@gtkx/css";
injectGlobal`
window {
background: var(--window-bg-color);
}
`;
```
A plain `.css` import also works: the GTKX CLI turns it into an `injectGlobal` call. Global rules remain installed for the application's lifetime.
## Follow appearance preferences
GTKX's stylesheet follows the color scheme resolved by [Adw.StyleManager](https://gnome.pages.gitlab.gnome.org/libadwaita/doc/main/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
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 [Preferences and Theming](/tutorial/preferences-and-theming) for an application preference that switches the scheme.
---
---
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@1.6.0
```
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` |
Scaffolded 1.6 applications enable [`v2DefaultLibraries`](/guide/configuration-and-codegen#future-flags), so they already generate the Adwaita bindings these navigators need. A legacy GTK-only project must bind `Adw-1` first. 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](/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.
State restoration and navigation outside the tree use React Navigation's [container API](https://reactnavigation.org/docs/navigation-container/).
## Stack navigator
`createStackNavigator` renders an `AdwNavigationView`. Define the route parameters to typecheck screens, `navigate` calls, and `route.params`:
```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}` })} />
);
```
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. 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](/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);
}}
/>
)}
);
};
```
Dispatch the action supplied to the callback after confirmation. React Navigation documents the rest of the [removal guard lifecycle](https://reactnavigation.org/docs/preventing-going-back/).
### 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
import { createTabNavigator } from "@gtkx/navigation";
type MailParams = { Inbox: undefined; Archive: undefined };
const Tabs = createTabNavigator();
export const Mail = ({ unread }: { unread: number }) => (
0 }}
/>
);
```
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.
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](/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
import { createDrawerNavigator } from "@gtkx/navigation";
type AppParams = { Inbox: undefined; Settings: undefined };
const Drawer = createDrawerNavigator();
export const App = ({ isNarrow }: { isNarrow: boolean }) => (
);
```
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.
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](/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
import { AdwStatusPage } from "@gtkx/jsx/adw";
import { GtkButton } 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" })} />
);
export const Mail = ({ isNarrow }: { isNarrow: boolean }) => (
)}
>
({ title: route.params.folder })} />
}} />
);
```
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.
The sidebar stays pinned beneath the content routes. Going back from the first content page clears the selection and restores `contentPlaceholder`. An `initialRouteName` naming a content screen opens that screen instead of starting with the placeholder.
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.
Drive `collapsed` from a window breakpoint so the panes adapt to the available width:
```tsx
import * as Adw from "@gtkx/gi/adw";
import { AdwApplicationWindow, AdwBreakpoint } from "@gtkx/jsx/adw";
import { NavigationContainer } from "@gtkx/navigation";
import { useState } from "react";
export const App = () => {
const [isNarrow, setIsNarrow] = useState(false);
return (
setIsNarrow(true)}
onUnapply={() => setIsNarrow(false)}
/>
)}
>
);
};
```
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](/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.
## 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
Use the hooks re-exported from `@gtkx/navigation`. React Navigation documents [screen focus effects](https://reactnavigation.org/docs/use-focus-effect/) and [navigation access](https://reactnavigation.org/docs/use-navigation/). GTKX's `useTheme` value follows the Adwaita state described above.
## 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. 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](/guide/testing) for setup and query behavior.
## Next
Continue with [CSS](/guide/css) to style these pages with the `style` prop and GTK4's own CSS engine.
---
---
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. Use it for GTKX-specific input, focus and validation feedback; use the [React Hook Form documentation](https://react-hook-form.com/docs) for form state, validation rules and submission.
Install the package:
```bash
npm install @gtkx/forms@1.6.0
```
The rows need generated `@gtkx/jsx/adw` bindings. New projects include them; existing GTK-only projects can add `Adw-1` through [library configuration](/guide/configuration-and-codegen).
## Connect a form
Pass `control={form.control}` to infer the row's field names from your form type. GTK buttons submit through `onClicked`:
```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.
## 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. React Hook Form owns the value, so configure a spin row's range through a JSX `GtkAdjustment`, and use `setValue` or `reset` to change its current value. Those form updates do not echo back as user edits.
`ComboRow` shares the [collection component's sources and renderers](/guide/components#dropdown). Item IDs remain stable when items move or their labels change. Values have a default text display; pass `renderItem` for application presentation. Passing `control` also lets TypeScript infer item and section types for renderers.
Give a form `ComboRow` 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 and exposes 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.
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.
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` from `@gtkx/forms`. Its render callback supplies the form value and handlers; connect them to the control's JSX props and signals. Add `GtkEventControllerFocus` through `controllers` to forward `onLeave` to `field.onBlur`.
Give `field.ref` a handle with a no-argument `focus()` method that calls the widget's `grabFocus()`. Passing the widget directly does not work: GTK's `focus` method expects a direction. Use `fieldState.invalid` to apply the control's validation presentation.
See the [forms reference](/reference/@gtkx/forms/) for GTKX prop types and the [testing guide](/guide/testing) for driving native controls.
---
---
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@1.6.0
```
## 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 ;
};
```
Keeping the wrapper at module scope gives React a stable component type, so it does not remount between renders.
Property access such as `animated.GtkLabel` remains available in GTKX 1.6 for compatibility, but is deprecated and removed in 2.0. Import the component and use the call form above. It works for elements that are not widgets, such as `GtkAdjustment`, and components of your own, while letting a production bundle retain only the components it reaches.
For writable GObject props, each frame updates the native object through its `ref` without rerendering the component. This includes `opacity`, margins, size requests, and adjustment values. The `style` prop, labels, and text children also accept animated values:
```tsx
const { count } = useSpring({ from: { count: 0 }, to: { count: 100 } });
`${Math.round(value)}%`)} />;
```
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, the wrapper rerenders the component with the current values.
Props that are not GObject properties, such as the `accessible*` props, still animate: the component re-renders with the current value on each frame. `style` updates its CSS provider without rerendering.
## Animated styles
In GTKX 1.6, the [`style` prop](/guide/css) compiles to a rule in a widget-specific `Gtk.CssProvider`. The spring reloads that rule each frame without a React render. Use it for effects exposed through CSS, such as color:
```tsx
import { animated, useSpring } from "@gtkx/animated";
import { GtkLabel } from "@gtkx/jsx/gtk";
const AnimatedLabel = animated(GtkLabel);
export const Deadline = ({ isOverdue }: { isOverdue: boolean }) => {
const { level } = useSpring({ level: isOverdue ? 1 : 0 });
return (
({ color: `mix(var(--window-fg-color), var(--error-color), ${value})` }))}
/>
);
};
```
The interpolation turns a number into a CSS declaration. GTK's `mix()` blends two colors; `alpha()` scales a color's opacity.
A spring can also sit on a single declaration rather than on the whole prop, which is how React Spring is written for the DOM:
```tsx
const styles = useSpring({ from: { color: "red" }, to: { color: "blue" } });
;
;
```
Nested blocks also accept springs, such as `style={{ "&:hover": { color: styles.color } }}`. Only `style` tracks nested springs; other object-valued props do not.
This also supports effects such as `border-radius`, `box-shadow`, and `filter`.
## 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
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 (
);
};
```
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. Use the [React Spring documentation](https://www.react-spring.dev) to choose and configure hooks, transitions, and controllers, then pass their animated values to GTKX props as shown above. Browser hooks that depend on the DOM 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.
- `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.
## Next
Continue with [Cairo](/guide/cairo) to draw 2D graphics inside a widget.
---
---
title: "Internationalization"
description: "Translate GTKX applications and package metadata with gettext catalogs."
---
# Internationalization
`@gtkx/i18n` connects React translation APIs to GNU gettext. Your application's `applicationId` is its gettext domain, and `po/` holds its translation catalogs. GTKX uses those catalogs for both the application and its desktop metadata.
Install `@gtkx/i18n@1.6.0` and the GNU gettext command-line tools. On Fedora 44:
```bash
npm install @gtkx/i18n@1.6.0
sudo dnf install gettext
xgettext --version
msgfmt --version
```
Other distributions may package the tools separately; both commands must be available when running codegen, development, and builds.
## 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 `po/.pot`, initializes the listed PO files, and generates translation types. Translators edit each catalog's `msgstr` values. Run codegen again after changing messages to update the template and merge those changes into the catalogs. Review fuzzy entries before release; removed messages remain as obsolete entries.
## 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; numeric counts must be 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.
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`.
## Use translations in components
Import the React APIs from `@gtkx/i18n` so they use the configured gettext backend:
```tsx
import { useTranslation } from "@gtkx/i18n";
import { GtkLabel } from "@gtkx/jsx/gtk";
function Greeting({ name }: { name: string }) {
const { t } = useTranslation();
return ;
}
```
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
Keep message keys, defaults, contexts, and `Trans` children static so GTKX can extract them at build time. GTKX follows ESM imports and aliases from `@gtkx/i18n` and `i18next`. Dynamic keys and tagged templates cannot be extracted.
Generated declarations under `node_modules/.gtkx` let TypeScript check message keys and their required interpolation, count, and context options. 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.
`gtkx build` compiles the catalogs into `dist/locale` beside the bundle. GTKX initializes localization before the application entry module runs and locates that directory automatically.
Select the process locale before launch:
```bash
LANG=fr_FR.UTF-8 LANGUAGE=fr gtkx dev
```
Gettext translations follow the startup environment. Changing i18next's language does not change libc's active gettext locale; restart the process to change the application's translation language.
## 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.
`gtkx deploy --skip-build` 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](/guide/deploying) for the packaging workflow.
---
---
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. This page covers GTKX 1.6; the [2.0 guide](/v2/guide/configuration-and-codegen) describes the new defaults.
## The config file
Create `gtkx.config.ts` in the project root:
```ts
import { defineConfig } from "@gtkx/config";
export default defineConfig({
applicationId: "com.example.Tasks",
future: { v2DefaultLibraries: true },
});
```
GTKX 1.x includes `Gtk-4.0` by default. Enabling `v2DefaultLibraries` also includes `Adw-1`, providing the Adwaita widgets used throughout these guides. List additional libraries by GIR name and version, for example `libraries: ["WebKit-6.0"]`.
`defineConfig` provides editor completion. The CLI validates the configuration when it loads it. The application ID is required and uses a reverse-DNS name such as `com.example.Tasks`.
Install the corresponding GIR files before generating bindings. Use `girPath` when they live outside the standard search directories. Supplying a newer GIR file changes the declarations, not the library that runs your app.
### Other settings {#every-option}
Use the [configuration reference](/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](/guide/deploying), and agent tool settings in [MCP](/guide/mcp).
For shared configuration, `mergeConfig(base, override)` applies the override over the base; arrays concatenate with override entries first. `$development` and `$production` blocks provide mode-specific overrides.
## 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. Development and production builds also check whether generation is needed.
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";
```
GTKX 1.6 also supports importing elements from the bare `@gtkx/jsx` entry point. Prefer namespace imports when preparing for 2.0, which removes that entry point. Use [`@gtkx/cairo`](/guide/cairo) for Cairo; the 1.6 `@gtkx/gi/cairo` compatibility export is also removed in 2.0.
`codegen: false` reuses an installed binding store. Leave generation enabled for an ordinary application so its bindings stay aligned with its configuration.
## The JSX prop model
Generated elements follow the native API with GTKX naming conventions:
- 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.
- Refs expose the corresponding GI instance for imperative APIs.
Prefer JSX for object creation and child placement. The [generated element reference](#generating-element-reference-docs) shows the exact props, slots, and signals for each configured library.
## 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 has no registration of its own. GTypes returned by bindings or passed to signal handlers remain `bigint` values.
## Passing a GValue
When a binding reads a `GObject.Value`, GTKX usually accepts the JavaScript payload directly. 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` must return its provider synchronously, so this native callback creates it directly. Create persistent GObjects through JSX.
Use an explicitly initialized `GObject.Value` when the operation requires a particular native type, including an interface type for clipboard or drag-and-drop matching. A binding that fills a value instead takes a new, uninitialized `GObject.Value`; its generated signature identifies this case. Signal handlers continue to receive the value object.
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.
## Future flags
GTKX 1.6 lets you adopt the 2.0 behavior one change at a time. Enable a flag, regenerate, typecheck, and run the app and its tests before moving to the next one. Typechecking catches many changes, but cannot identify every behavioral difference, such as how a typed array is serialized.
| Flag | Change to prepare for |
| -------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `v2ByteArrays` | Returned byte sequences become `Uint8Array`. Inputs continue to accept `number[]` too. Update array mutation and serialization code. |
| `v2ValueReturns` | Returned `GObject.Value` objects become their payloads, typed as `unknown`. Handle the payload type at the call site. |
| `v2FinishResults` | Promisified operations drop a redundant leading success boolean from multi-value results. Update tuple destructuring; see [Async Operations](/guide/async-operations). |
| `v2InoutReturns` | Inout records and boxed values are updated in place without being repeated in the return value. Primitive inout results remain. |
| `v2ResourceImports` | Asset imports use relative paths and explicit queries. See the example below. |
| `v2DefaultLibraries` | Adwaita becomes a default dependency. Install its GIR data and run the app to check its appearance. |
| `v2TreeShaking` | Production builds drop unused generated classes. Import any class whose registration the app needs at runtime. |
### Migrating resource imports
With `v2ResourceImports` enabled, remove the `#data/*` mapping from `package.json` and replace its imports with relative paths:
```ts
import logoPath from "../data/logo.png?resource";
import saveIcon from "../data/icons/scalable/actions/save.svg?icon=example-save-symbolic";
import templatePath from "../data/template.txt?url";
import settings from "../data/com.example.Tasks.gschema.xml";
```
`?resource` returns a bundled GResource path; `?resource=/org/example/exact.png` selects an exact path. Convert it to a `resource://` URI only when an API requires one. `?url` provides a real file path, while settings schema imports remain query-free and receive generated types.
`?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.
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.
### Checking the remaining migration work
The CLI reports flags that have not been enabled. A warning can be silenced by its deprecation ID while you work through the migration:
```ts
export default defineConfig({
applicationId: "com.example.Tasks",
future: { v2DefaultLibraries: true },
deprecations: { silence: ["gtkx-v2-byte-arrays"] },
});
```
Silencing a warning leaves the behavior unchanged. Remove deprecated APIs as well as adopting the flags: replace `libraries: "*"` with the libraries the app uses, split bare JSX imports by namespace, and use `animated(Component)` instead of properties on `animated`.
In 2.0, remove the graduated flags and explicit `Adw-1` or `Gtk-4.0` entries. A leftover flag set to `true` warns; `false` is rejected. Follow [Upgrading to 2.0](/guide/upgrading-to-2) for the migration checklist.
## Generating element reference docs
`gtkx docs` writes reference pages for the project's generated elements to `docs/reference`:
```bash
gtkx docs
```
Use `gtkx docs --help` to choose an output directory or link root. These pages describe the actual libraries configured for the project.
## What agents are given
Codegen also writes `.gtkx/reference` for coding agents and maintains a marked GTKX section in `AGENTS.md`. Text outside that section is preserved. 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.
## 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",
future: { v2DefaultLibraries: true },
elements: { behaviors: "./src/elements.ts" },
});
```
Wrap each behavior with `defineBehavior` from `@gtkx/react/config`, supplying its GI class as the type argument. Behaviors apply to descendants and run before built-in behaviors. The [ElementBehavior reference](/reference/@gtkx/react/config/type-aliases/ElementBehavior) describes the hooks.
Declare additional props by augmenting the namespace module that owns them, with a top-level import of that module. Keep application effects and higher-level behavior in React components.
Continue with [Async Operations](/guide/async-operations).
---
---
title: "Async Operations"
description: "Awaiting promisified GIO calls, canceling them, and keeping long work off the main thread."
---
# Async Operations
GTKX turns compatible GIO async/finish pairs into promises. By default in GTKX 1.6, `loadContentsAsync` resolves to the native success flag, a numeric byte array, and the optional etag. A failed call rejects, so callers can skip the success flag when destructuring. A call whose C return is void and that has a single out-parameter resolves to that value directly instead of a tuple.
The [`v2FinishResults` future flag](/guide/configuration-and-codegen#future-flags) removes only the redundant success flag. The separate `v2ByteArrays` flag changes the contents to a `Uint8Array`. With both enabled, `loadContentsAsync` resolves to the contents and optional etag, while `replaceContentsAsync` resolves to its etag directly. Boolean-only results and explicit finish methods keep their native return shape.
## Awaiting async operations
GTK4 reports a dismissed dialog as an error rather than as a return value, so a `catch` matching `Gtk.DialogError.DISMISSED` returns quietly:
```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 !== null && cancellable !== null) void open(dialog, cancellable);
}}
/>
cancellable?.cancel()}
/>
>
);
};
```
Outside production, the rejection's `cause` carries the stack captured where the operation started.
## Cancellation with Gio.Cancellable
When a native async function takes a `Gio.Cancellable`, its promisified form accepts one as the last 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`.
Canceling rejects the pending promise. GIO operations report `Gio.IOErrorEnum.CANCELLED`; GTK4 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. The same rule applies after unmount cleanup or React effect replay cancels an operation.
## Moving work to a worker
CPU-bound JavaScript on the main thread freezes the window, so it belongs in a [Node worker thread](https://nodejs.org/api/worker_threads.html):
```ts
import { Worker } from "node:worker_threads";
const worker = new Worker(new URL("./indexer.ts", import.meta.url));
worker.on("message", (rows) => setRows(rows));
```
Use a relative path naming the worker source file, and put `new URL(...)` directly inside `new Worker(...)`. `gtkx build` rejects other forms.
During `gtkx dev` and Vitest, Node loads the worker and its imports directly rather than from a bundle. Relative imports in that graph must therefore name their `.ts` source files and use syntax supported by Node's type stripping; enums and parameter properties are not available. The 1.6 scaffold uses `NodeNext` with `noEmit`, so add `"allowImportingTsExtensions": true` to `compilerOptions` before importing those source files. `gtkx build` bundles the graph and can accept code that native dev or test loading cannot, so exercise each worker in Vitest as well as building it.
A worker runs no GTK code: it computes and posts results back for the main thread to render.
## Next
Continue with [Error Handling](/guide/error-handling) for matching GLib error domains and codes.
---
---
title: "Error Handling"
description: "Match native errors by domain and code, and distinguish call failures from fatal errors."
---
# 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](/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`. The generated reference describes each library's domains and codes.
For a native callback that expects an error value, create one through the generated `GLib.Error` API.
## Fatal errors
Some failures have no `GError` channel. GLib `CRITICAL` and `ERROR` records, and GTKX addon panics, reach Node's uncaught-exception channel instead. This includes reports sent from another thread, and they cannot be caught around the binding call that triggered them.
Use Node's [`uncaughtExceptionMonitor`](https://nodejs.org/api/process.html#event-uncaughtexceptionmonitor) for synchronous crash reporting while preserving its default process exit. Native state may already be invalid; do not resume normal application work after a fatal error.
GLib `ERROR` messages are reported before GLib aborts. Lower log levels retain GLib's normal logging behavior. Unhandled failures also fail the test suite; see [Testing](/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. A boundary also cannot recover from a native fatal error that leaves the process unsafe to continue.
## Next
Continue with [Components](/guide/components) for how GTKX widgets compose and the hooks that drive them.
---
---
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](/reference/@gtkx/runtime/functions/registerClass) for registration options.
## Rendering a registered class
Codegen does not emit elements for application-defined classes. Create an element with the registered type name and its props, then instantiate it through JSX:
```tsx
import { GtkAdjustment, type GtkScaleProps } from "@gtkx/jsx/gtk";
import { createElementComponent } from "@gtkx/react/config";
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.
Custom properties are applied after construction. A custom construct-only property needs a creation behavior registered under the same type name; see [Customizing elements](/guide/configuration-and-codegen#advanced-customizing-elements).
## Properties
Use `declare` for native properties. A JavaScript field initializer would shadow the native accessor. Keep property maps inferred so their keys remain 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`.
ParamSpec flags control native reads, writes and construction. Use the generated reference for each spec type and its accepted values.
### Overriding an inherited property
Use `paramSpecOverride("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; an explicit spec is useful when supplying custom accessors.
### Inspecting a ParamSpec
Use the generated ParamSpec reference for its metadata and flags. Class-level inspection is available through generated class-struct wrappers, such as `GObject.ObjectClass.peek(TaggedScale)`.
### Properties and the hooks
Pass an instance or ref to `useProperty(ref, "tag")` to subscribe to a registered property. Inherited properties remain available. Keep application effects in React components and hooks.
## Declaring signals
The `signals` option registers custom signals. Each entry names its parameter GTypes and, when needed, its return GType. Use the returned class so GTKX's signal helpers recognize the declared names. 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](/guide/configuration-and-codegen#the-jsx-prop-model) for handler props and the [`registerClass` reference](/reference/@gtkx/runtime/functions/registerClass) for signal options.
## Default handlers
A class method named `on`, such as `onClicked`, becomes the default handler for that signal. It receives the signal arguments with `this` bound to the instance. A subclass can replace it and chain to the previous implementation with `super.onClicked()`.
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.
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
Implement the generated `vfunc` method with its declared signature. Use `super` to chain to the parent implementation:
```ts
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. Invoke the ordinary public method when using an instance; direct vfunc calls are for chaining from an override.
### Slots with no generated member
Use [`callParent`](/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`.
## 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";
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. 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.
### Reporting a vfunc error {#throwing-out-of-a-slot-you-fill}
Throw from a vfunc that reports errors through `GError`. GTKX preserves a thrown `GLib.Error` and converts other exceptions into a native error. A virtual function without an error channel cannot report failure that way; see [Error Handling](/guide/error-handling).
## 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](/guide/modals-and-portals). Add native placement rules through [element configuration](/guide/configuration-and-codegen#advanced-customizing-elements).
## Initialization order {#what-an-override-of-constructed-can-see}
`vfuncConstructed` runs after native construct properties are set, while `super()` is still executing. JavaScript field initializers and the constructor body have not run yet. 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.
Continue with [Components](/guide/components).
---
---
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. Install it alongside the rest of your app:
```bash
npm install @gtkx/cairo@1.6.0
```
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](/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
import { GtkDrawingArea } from "@gtkx/jsx/gtk";
const Circle = () => (
{
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();
}}
/>
);
```
Draw only inside this callback: do not update widget properties or React state from it. Keep the context local to the callback. GTKX manages its native reference.
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.createLayout(cr)` accepts the context from `drawFunc` without conversion.
Use PangoCairo for application text. Its [layout documentation](https://docs.gtk.org/PangoCairo/) covers shaping, font fallback and layout; import its bindings from `@gtkx/gi/pangocairo`.
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 surface = new ImageSurface(Format.ARGB32, 256, 256);
const cr = Context.create(surface);
cr.setSourceRgb(0.9, 0.3, 0.2);
cr.paint();
const status = surface.writeToPng("image.png");
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)`.
## Handle errors
Creating an image with an invalid size or loading a missing PNG throws.
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.
## The 1.x compatibility import
`@gtkx/gi/cairo` remains available in GTKX 1.6 as a deprecated re-export. New code should install and import `@gtkx/cairo`; the compatibility path is removed in 2.0.
## Next
Continue with [OpenGL](/guide/opengl) to draw with the GPU inside a widget.
---
---
title: "OpenGL"
description: "Use GTKX's OpenGL bindings inside a GtkGLArea."
---
# OpenGL
`@gtkx/gl` provides OpenGL bindings for drawing inside a `GtkGLArea`. Install it alongside your application:
```bash
npm install @gtkx/gl@1.6.0
```
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](/reference/@gtkx/gl/) for available 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
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;
}}
/>
);
```
GTK presents the result as part of the surrounding widget tree. Returning `Gdk.EVENT_STOP` marks the render signal as handled. As with other GTKX signals, handlers can receive the emitting area as their final argument.
For complete shader and geometry setup, see the [GLArea, Gears and Shadertoy examples](https://github.com/gtkx-org/gtkx/tree/v1.6.0/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 for geometry uploads, alongside the byte length required by the command.
Generic state queries such as `getIntegerv` are not exported. Use the available typed queries for the object you are inspecting, such as `getShaderiv` or `getProgramiv`. Shader and program info-log helpers return the driver's diagnostics as strings.
## Manage context resources
Create shaders and buffers in `onRealize`, after calling `area.makeCurrent()` and checking `area.getError()`. Realization follows the native widget's lifecycle, so it can happen after the React component mounts. Keep GL object names in refs and delete those resources in `onUnrealize`, making the area's context current first.
`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. 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, use a GTK tick callback to advance the scene and call `queueRender()`. Tie its registration and removal to the mounted area's lifetime.
## 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](/guide/error-handling) for errors raised by binding calls.
## Next
Continue with [Testing](/guide/testing) for native widget queries and interaction tests.
---
---
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@1.6.0` can include testing setup. To add it to an existing project, install the test dependencies:
```bash
npm install -D @gtkx/testing@1.6.0 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}"],
},
});
```
The plugin gives each worker a private headless display and session bus. Its default compositor is Sway; it also needs `dbus-daemon` and `setpriv`. On Fedora 44, install these with:
```bash
sudo dnf install sway dbus-daemon util-linux
```
Check that the commands are available, then run the tests:
```bash
command -v sway dbus-daemon setpriv
npm test
```
See the [plugin reference](/reference/@gtkx/vitest/) for display size and compositor options.
With the GTKX Vitest plugin, importing `@gtkx/testing` registers widget matchers and automatic cleanup. No additional setup file is needed.
### 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")).toHaveTextContent("Settings saved");
});
```
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 });
```
Use the `wrapper` option for context providers. `rerender` updates the rendered component; `unmount` removes it. Animations are disabled by default, and automatic cleanup removes rendered trees between tests. For hooks, use `renderHook` and assert on `result.current`.
## 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](/reference/@gtkx/testing/).
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 text button's child label takes precedence over its `accessibleLabel` prop. Query the visible label and use `within` when several buttons share it.
## Interacting and waiting
Await every `userEvent` call. Helpers wait for the target to become actionable and flush React updates before resolving. Use `userEvent.setup()` when a sequence needs to retain held keyboard modifiers or pointer buttons.
```ts
const user = userEvent.setup();
await user.keyboard(entry, "{Control>}a{/Control}");
await user.type(entry, "Replacement");
await user.click(saveButton);
```
Use `slide(range, value)` for a slider. `drag` drives application-defined drag gestures and cannot drive a range's native slider. The [interaction reference](/reference/@gtkx/testing/) covers the available helpers.
`fireEvent(object, signalName, ...args)` emits a GObject signal directly. It returns a promise, so await it. 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`.
## 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](/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](/guide/mcp) provides the same inspection tools during development.
GLib criticals and addon panics fail the running test as uncaught exceptions. Warnings alone do not fail tests. See [Error Handling](/guide/error-handling#fatal-errors) for the failure channels.
## Next
The [tutorial's testing chapter](/tutorial/testing) applies these tools to a complete application.
---
---
title: "MCP"
description: "Inspect a running GTKX app and look up its generated bindings from your coding agent."
---
# MCP
`@gtkx/mcp` 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 used by its widget tools. Scaffolded projects may already include them.
::: code-group
```bash [npm]
npm install -D @gtkx/mcp@1.6.0 @gtkx/testing@1.6.0
```
```bash [pnpm]
pnpm add -D @gtkx/mcp@1.6.0 @gtkx/testing@1.6.0
```
```bash [yarn]
yarn add -D @gtkx/mcp@1.6.0 @gtkx/testing@1.6.0
```
:::
From the project root, register the server with your client:
```bash
npx gtkx mcp init --client claude
```
The command supports `claude`, `cursor`, `vscode`, `opencode`, and `codex`. It preserves existing server entries. For Codex, it prints configuration to add to your client instead of editing its settings. A scaffolded project already includes the Claude configuration.
For another MCP client, configure a stdio server that runs `npx gtkx mcp` from the project root. The standalone `gtkx-mcp` command is also available when `@gtkx/mcp` is installed directly.
Start the app in another terminal:
```bash
npx gtkx dev
```
The app connects automatically, and either side can start first. The connection is available during development; production builds exclude it.
Run GTKX 1.6 development from a graphical session. The `gtkx dev --headless` option belongs to GTKX 2; 1.6 still supports headless Vitest sessions through the [testing setup](/guide/testing#setup).
## 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 or type through the interaction tools.
4. Take a screenshot to check the rendered result.
The widget tools use the same queries and events as [`@gtkx/testing`](/guide/testing). For large windows, request a subtree or limit the depth instead of repeatedly reading the whole tree. Widget IDs last only while their widgets are mounted; query again after the relevant UI is replaced.
Several apps can share a server. Use `gtkx_list_apps` to find them and pass `applicationId` to target one; otherwise, tools use the first connected app.
Your client exposes each tool's parameters and description. Screenshots can also be saved to a file, and `returnImage: false` avoids returning the image when only the saved file is needed.
## 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, then `gtkx_get_api_docs` to read its page. Qualified names such as `Adw.Toast` and JSX names such as `AdwToast` are accepted. These are the same bindings covered by the [generated element reference](/guide/configuration-and-codegen).
The server uses 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 access the reference there too. Projects with `codegen: false` have no generated bindings to document.
## Choose the available tools
Set `mcp.readOnly` to expose inspection and reference tools while 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 flags override the project settings for one client:
```bash
npx gtkx mcp --read-only --tools "gtkx_*_api,gtkx_get_widget_tree"
```
---
---
description: "Package a GTKX app as a Flatpak, Debian package, RPM, or AppImage."
---
# Deploying
`gtkx deploy` builds a GTKX application and packages it for Linux. GTKX generates the launcher, desktop entry, AppStream metadata, and package manifests from `gtkx.config.ts`.
## Configure the application
Keep the version, author, license, and homepage in `package.json`. GTKX uses those values unless the `deploy` block overrides them:
```ts
import { defineConfig } from "@gtkx/config";
export default defineConfig({
libraries: ["Gtk-4.0", "Adw-1"],
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, and the [`@gtkx/config` reference](/reference/@gtkx/config/) documents every option.
### Application icons
The example expects an icon such as `data/icons/hicolor/scalable/apps/com.example.Tasks.svg`. An icon-theme directory must contain an application icon named after `applicationId` under `hicolor//apps`; GTKX preserves its other sizes and variants.
You can also point `applicationIcon` at one SVG, PNG, or XPM file. When the option is omitted, GTKX looks for exactly one file named after the application ID in the project root. Deployment requires an icon.
Keep development icons in a separate directory and select them with a [`$development` override](/guide/configuration-and-codegen#every-option), so they cannot enter a production package.
## 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 |
Set `deploy.targets` for the project's usual formats, or override them for one run:
```bash
gtkx deploy --target deb,rpm
```
With neither setting, GTKX builds a Flatpak. Finished packages are written to `build/out/`; generated metadata and manifests remain under `build/` for review.
## Preview and build
From a scaffolded project on Fedora, preview an RPM:
```bash
npm run deploy -- --target rpm --print-manifests
```
Use `--target deb` on Debian or Ubuntu. Review the generated files before creating packages.
GTKX builds and stages the application, validates its desktop entry and AppStream metadata, then stops before packaging. Remove `--print-manifests` to produce the package:
```bash
npm run deploy -- --target rpm
```
Install it on a compatible system and open it from the desktop launcher to check the packaged build.
To package an existing production build:
```bash
gtkx build
gtkx deploy --skip-build
```
Keep the complete `dist/` directory together. It contains the bundle, native addon, compiled settings, and the build metadata used to reproduce dependency notices. `--out` changes the deployment directory, which defaults to `build`.
Every deployment needs `desktop-file-validate` and `appstreamcli`. Translation catalogs need GNU gettext, Flatpak needs its builder, and AppImage needs `file`. GTKX downloads and verifies the packaging tools for Debian, RPM, and AppImage. When a local tool is missing, the command reports the appropriate installation command.
## Runtime requirements
GTKX 1.6 requires Node.js 24 or newer, while supported distributions may ship an older release. Prebuilt packages bundle the version used for deployment. The default downloads the official archive, verifies it, and caches it. The host and path modes use a local runtime after checking that it is suitable for the package; see the [configuration reference](/reference/@gtkx/config/) for those settings.
GTK, libadwaita, and other native libraries come from the host system or Flatpak runtime. Generated GTKX bindings call them directly, so installed applications do not need GIR files. Declare additional system packages and minimum library versions in `deploy` when the application uses them. The opening example records the GTKX baseline in `minimumLibraryVersions`; raise it when using newer APIs. GTKX writes those minimums into Debian and RPM dependencies but does not infer the minimum API version from your code. AppImage users still need compatible system libraries.
## Third-party notices
Every package includes license notices for Node.js, GTKX, and the JavaScript dependencies reached by the application bundle. It also identifies native libraries supplied by the host or runtime. Missing dependency license data produces a warning for the application author to resolve.
Debian installs the notices in its machine-readable copyright file. The other targets install `THIRD-PARTY-NOTICES` beside the application's license. Rebuild after changing dependencies so these files describe the packaged bundle.
## Customize a package
Keep packaging adjustments in `deploy`. Flatpak permissions, extra files, system dependencies, maintainer scripts, and signing all belong there. Use `defineConfig` completion and the [configuration reference](/reference/@gtkx/config/) for their exact shapes.
Flatpak defaults permit display access and hardware rendering. Add network or filesystem access only when the application needs it; use the [Flatpak permission documentation](https://docs.flatpak.org/en/latest/sandbox-permissions.html) to choose `deploy.flatpak.finishArgs`.
## Publish on Flathub
The default Flatpak mode packages the local build. Source mode generates 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 the application's public repository and release tag. Commit every source, lockfile, icon, license, catalog, and extra file that the package installs.
Install [`flatpak-node-generator`](https://github.com/flatpak/flatpak-builder-tools/tree/master/node) before preparing a source manifest. Keep its generated dependency file beside the Flatpak manifest and regenerate both after dependency changes.
Source mode rebuilds the application bundle, while 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. [Shipping It on Flathub](/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.
## Next
The [API reference](/reference/) documents GTKX's public TypeScript APIs.
---
---
title: "Upgrading to 2.0"
description: "Prepare a GTKX 1.6 application, then move it to GTKX 2.0."
---
# Upgrading to 2.0
GTKX 1.6 can enable most 2.0 behavior before the package upgrade. Adopt those changes one at a time, then upgrade your installed `@gtkx/*` packages together. The [2.0 migration checklist](/v2/guide/upgrading-to-2) covers all current changes, including application lifecycle and Variant APIs. `@gtkx/gi` and `@gtkx/jsx` remain generated packages, not installation targets.
## Prepare on 1.6
Run `gtkx build`, `gtkx dev`, or `gtkx codegen` and read the future-flag warning. Set one reported flag in `gtkx.config.ts`, run `tsc --noEmit`, and fix the affected call sites before enabling the next:
```ts
export default defineConfig({
applicationId: "com.example.Tasks",
future: { v2ByteArrays: true },
});
```
Work through all seven flags:
- `v2ByteArrays` returns GIR byte sequences as `Uint8Array`. Check array mutation, `Array.isArray`, and JSON serialization.
- `v2ValueReturns` unwraps returned `GObject.Value` instances and types their contents as `unknown`; narrow the value where it is used.
- `v2FinishResults` removes a leading success boolean from multi-value promisified finish results when failure already rejects.
- `v2InoutReturns` stops repeating an inout record or boxed value in the return tuple. The object passed in is still mutated.
- `v2ResourceImports` replaces `#data/` imports with relative `?resource`, `?icon`, `?font`, or `?url` imports. Settings schemas use query-free relative imports. Remove the `#data/*` mapping from `package.json`, then run `gtkx build` to find stale specifiers; while the mapping remains, the build still resolves them.
- `v2DefaultLibraries` binds Adwaita and GTK by default. Remove `Adw-1` and `Gtk-4.0` from `libraries`, then run the application and check its appearance.
- `v2TreeShaking` retains only generated classes reached by the production bundle. Import a class as a value when `GObject.typeFromName` must find it, and replace side-effect-only generated-module imports.
Silencing a warning only hides it. The behavior still changes in 2.0. The [future-flags guide](/guide/configuration-and-codegen#future-flags) explains the less common resource and tree-shaking cases.
Replace `libraries: "*"` with the additional GIR roots the project uses. An explicit list controls which namespaces are bound; generated APIs still depend on the installed GIR versions.
## Update the runtime and configuration
GTKX 2.0 requires Node.js 26.7 or newer and ESM. Set `"type": "module"` in `package.json` and stop loading GTKX packages through `require()`. Projects with translation catalogs also need GNU gettext 0.25 or newer.
After upgrading the packages, delete the `future` block and the corresponding `gtkx-v2-*` entries from `deprecations.silence`. A graduated flag left at `true` is accepted temporarily with a warning; `false` is rejected because the old behavior no longer exists.
Adwaita is the sole default GIR root in 2.0, and its GIR include supplies GTK transitively. Do not name either `Adw-1` or `Gtk-4.0` 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 removed.
## Update imports
The bare `@gtkx/jsx` entry point is removed. Import elements from the namespace that declares them:
```tsx
import { AdwHeaderBar } from "@gtkx/jsx/adw";
import { GtkBox, GtkButton } from "@gtkx/jsx/gtk";
```
Adwaita components now come from the main components package. Import `ComboRow`, `ToastProvider`, and `useToast` from `@gtkx/components` instead of `@gtkx/components/adw`. The internal `@gtkx/react/adw` subpath is also removed; `@gtkx/react` registers Adwaita elements itself.
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.
Import `createElementComponent` from `@gtkx/react` instead of `@gtkx/react/config`. The config subpath remains for renderer behavior and element registration APIs.
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.
## 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 [2.0 settings tutorial](/v2/tutorial/preferences-and-theming#create-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 [Properties and the hooks](/v2/guide/subclassing#properties-and-the-hooks) 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 2 delegates extraction and resource typing to `i18next-cli`. Keep translation calls in ESM files and use the exact names `t`, `useTranslation`, `Trans`, or `TransWithoutContext`. Replace aliases, `i18n.t(...)` calls, dynamic keys, CommonJS declarations, and ICU components with those static forms. A `t` received through `withTranslation`, the `Translation` render prop or a function parameter is no longer extracted; import `t` from `@gtkx/i18n` or call `useTranslation()` there instead.
Replace the removed positional plural overload with `count`, `defaultValue_one`, and `defaultValue_other` options. Run codegen after migrating. Generated declarations now use i18next's `CustomTypeOptions`, so remove uses of GTKX's `TranslationRegistry` and import shared types from `i18next` or `react-i18next`.
## Replace removed APIs
Your editor marks the 1.6 compatibility APIs as deprecated. Replace each GTKX deprecation whose annotation ends in `Removed in v2`:
| Replace | With |
| ------------------------------------------- | ---------------------------------------------------------- |
| `object.addEventListener(name, handler)` | `object.on(name, handler)` |
| `object.removeEventListener(name, handler)` | `object.off(name, handler)` |
| `Gdk.RGBA.create(css)` | Construct an `RGBA`, then check `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 a `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 those constructors are removed. Upstream GTK and Adwaita deprecations are separate and remain available when the upstream library still provides them.
Generated methods that expose unmanaged native addresses are also 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`.
`@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`.
## Verify the upgrade
```bash
gtkx codegen --force
tsc --noEmit
gtkx build
```
Run the application and inspect every main flow. GTKX 2 initializes Adwaita for every application, and production builds now retain only the generated bindings they reach.
For 2.0 behavior after the migration, see [Configuration and Codegen](/v2/guide/configuration-and-codegen) and the [2.0 API reference](/v2/reference/).
---
---
description: "Build a Linux task manager with React and Adwaita, then test, translate, and package it."
---
# Build a Tasks App with GTKX
Build **Tasks**, a Linux task manager, from an empty directory, then test, translate, and package it as a Flatpak, deb, rpm, and AppImage. You will add adaptive layouts, settings, keyboard shortcuts, dialogs, notifications, and translations, then prepare the app for Flathub.
Each chapter keeps the app runnable and includes checks for the feature you added.
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 GTK4. You need Linux, the native development libraries, and Node.js 24 or later; [Getting Started](/guide/getting-started) covers installation.
## Check your setup
Confirm that Node.js is version 24 or later:
```bash
node --version
```
Scaffold the project:
::: code-group
```bash [npm]
npm create gtkx@1.6.0
```
```bash [pnpm]
pnpm create gtkx@1.6.0
```
```bash [yarn]
yarn create gtkx@1.6.0
```
:::
Choose `tasks` as the project directory and `com.gtkx.tutorial` as the application ID. Enable TypeScript and the testing setup, then choose your package manager. The scaffolder installs dependencies and initializes a Git repository.
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 tasks
npm run dev
```
This opens the GTKX 1.6 counter example. The next chapter enables Adwaita and replaces the counter with the Tasks application shell.
Leave `npm run dev` running as you work. Fast Refresh applies component edits to the open window; changes that need a restart relaunch the app. Saving `gtkx.config.ts` regenerates bindings and relaunches it too.
## How this tutorial works
Follow the chapters in order. Use each chapter's checks to confirm the result in the running app.
| Stage | Chapters | What you build |
| ---------------------- | ---------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------ |
| Foundation | [Create a Window](/tutorial/your-first-window) through [Save Tasks](/tutorial/saving-to-disk) | A task list with controls and persistent storage |
| Navigation and editing | [Add Lists and a Sidebar](/tutorial/lists-and-the-sidebar) through [Edit Tasks](/tutorial/the-task-editor) | An adaptive layout, search, and task editor |
| Desktop features | [Add Menus and Shortcuts](/tutorial/actions-menus-shortcuts) through [Send Reminders](/tutorial/reminders) | Actions, dialogs, preferences, reordering, and notifications |
| Test and distribute | [Test the App](/tutorial/testing) through [Prepare for Flathub](/tutorial/flatpak) | Integration tests, translations, and installable packages |
Examples name the file to edit. A complete-file example replaces that file. A `diff` block shows removed lines with `-` and added lines with `+`; apply its changes to the existing file. A JSON `merge` block updates the named fields. Keep the surrounding code unless instructed otherwise. Run `npm run typecheck` after each chapter and `npm test` once Add Tasks introduces 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 [completed 1.6 source](https://github.com/gtkx-org/gtkx/tree/v1.6.0/examples/tutorial) provides a reference for the finished app. It includes later features, so copy only the change a chapter describes when following along.
## Next
Continue to [Create a Window](/tutorial/your-first-window).
---
---
description: "Build the Tasks application shell with an Adwaita window and header bar."
---
# Create a Window
You have a scaffolded project that runs. Replace its contents with the first piece of Tasks: an application, a window, and a header bar. If you skipped ahead, start at [the introduction](/tutorial/) and come back once `npm create gtkx@1.6.0` has finished.
## What the scaffolder made
`gtkx.config.ts` configures the application and generated bindings. `src/index.tsx` mounts the component tree, and `src/app.tsx` contains the counter you will replace. `src/gtkx-env.d.ts` connects TypeScript to the generated declarations.
`gtkx.config.ts`:
```ts [gtkx.config.ts]
import { defineConfig } from "@gtkx/config";
export default defineConfig({
applicationId: "com.gtkx.tutorial",
applicationIcon: "data/icons",
future: {
v2ByteArrays: true,
v2ValueReturns: true,
v2FinishResults: true,
v2InoutReturns: true,
v2ResourceImports: true,
v2DefaultLibraries: true,
v2TreeShaking: true,
},
});
```
The tutorial uses Adwaita for application structure. In GTKX 1.6, `v2DefaultLibraries` includes Adwaita and GTK4; `libraries` lists any additional native libraries you need. See [Configuration and Codegen](/guide/configuration-and-codegen) for the configuration reference and future flags.
Keep the application ID you chose in the introduction, and use it wherever later examples show `com.gtkx.tutorial`.
## The entry point
`src/index.tsx` stays as it is for the rest of the tutorial.
`src/index.tsx`:
```tsx [src/index.tsx]
import { createRoot } from "@gtkx/react";
import { App } from "./app.js";
createRoot().render();
```
`createRoot()` creates the React root for the native application. GTKX creates and updates GObject instances from the JSX tree. With no argument, the root accepts the application element shown below.
## The application and its window
Replace `src/app.tsx` with the following. Also remove the scaffolder's `tests/app.test.tsx`, which tests the counter and imports its default export. [Add Tasks](/tutorial/the-task-store#test-the-entry-row) adds the first tests for Tasks.
`src/app.tsx`:
```tsx
import { AdwApplication, AdwApplicationWindow } from "@gtkx/jsx/adw";
import { quit } from "@gtkx/react";
export function App() {
return (
quit()}
/>
);
}
```
Generated JSX elements use their GObject type names: `AdwApplicationWindow`, `GtkListBox`, and so on. The available elements come from your project's configured GIR libraries. Use the [generated element reference](/guide/configuration-and-codegen#generating-element-reference-docs) for their props and signals.
GObject properties become camelCase props, such as `widthRequest`. Signals become handlers such as `onCloseRequest`; here, closing the window calls `quit()` to unmount the application.
`AdwApplication` takes its application ID from `gtkx.config.ts` and starts the application when it mounts. Rendering `AdwApplicationWindow` opens the window; removing it from the tree closes it.
The minimum width leaves room to test the narrow layout in [Adapt the Layout](/tutorial/an-adaptive-layout).
## Giving the window a header bar
`AdwApplicationWindow` leaves its content area free for your layout. Add `AdwToolbarView` with an `AdwHeaderBar` to show the title and window controls above the content.
`src/app.tsx`:
```tsx [src/app.tsx]
import {
AdwApplication,
AdwApplicationWindow,
AdwHeaderBar,
AdwStatusPage,
AdwToolbarView,
} from "@gtkx/jsx/adw";
import { quit } from "@gtkx/react";
export function App() {
return (
quit()}
>
}>
);
}
```
`topBar` is a JSX slot for the header bar. The status page goes in `children`, the toolbar view's content slot. GTKX uses named slots where a native container has several places for children; see [the JSX prop model](/guide/configuration-and-codegen#the-jsx-prop-model).
The header bar picks up the window title. `AdwStatusPage` supplies the empty state until the next chapter adds tasks.
## Run it
Save `src/app.tsx`. The window now shows a **Tasks** header and a checkbox icon above **No Tasks Yet**. Resize it to check the minimum width of 360 logical pixels.
Change the status page title to `Nothing Here Yet` and save. Fast Refresh updates the text in the open window.
Set the title back to `No Tasks Yet` before moving on.
## Next
Continue to [Display Tasks](/tutorial/a-list-of-tasks).
---
---
description: "Model a task and display sample data in a scrollable list."
---
# Display Tasks
Replace the empty state from [Create a Window](/tutorial/your-first-window) with a list of tasks. Start with sample data; the next chapter adds an entry row for new tasks.
## Define the task model
Create `src/types.ts`:
```ts [src/types.ts]
export type Task = {
id: string;
listId: string;
title: string;
notes: string;
done: boolean;
important: boolean;
deleted: boolean;
due: string | null;
position: number;
createdAt: string;
completedAt: string | null;
};
```
`title` appears in the list, `notes` holds the body shown in the editor, and `position` records the manual order. Dates use ISO strings so tasks can be saved as JSON in [Save Tasks](/tutorial/saving-to-disk).
## Render the list
Create `src/components/task-list.tsx`:
```tsx [src/components/task-list.tsx]
import * as Gtk from "@gtkx/gi/gtk";
import { AdwActionRow, AdwClamp } from "@gtkx/jsx/adw";
import { GtkListBox, GtkScrolledWindow } from "@gtkx/jsx/gtk";
import type { Task } from "../types.js";
const createdAt = new Date().toISOString();
const TASKS: Task[] = [
{
id: "t1",
listId: "personal",
title: "Welcome to Tasks",
notes: "This is your first task. Tick the checkbox to complete it, or open it to add notes and a due date.",
done: false,
important: false,
deleted: false,
due: null,
position: 0,
createdAt,
completedAt: null,
},
{
id: "t2",
listId: "personal",
title: "Water the plants",
notes: "",
done: false,
important: true,
deleted: false,
due: null,
position: 1,
createdAt,
completedAt: null,
},
{
id: "t3",
listId: "work",
title: "Prepare the weekly report",
notes: "",
done: false,
important: false,
deleted: false,
due: null,
position: 2,
createdAt,
completedAt: null,
},
];
export const TaskList = () => (
{TASKS.map((task) => (
))}
);
```
`GtkScrolledWindow` scrolls long lists. `AdwClamp` keeps the rows readable in a wide window, and the `boxed-list` class gives the list its rounded card appearance. [CSS](/guide/css) covers native classes and stylesheets.
`selectionMode={Gtk.SelectionMode.NONE}` disables row selection because each task will have its own controls. JSX elements come from `@gtkx/jsx/gtk`; enums such as `Gtk.SelectionMode` come from `@gtkx/gi/gtk`.
`useMarkup={false}` displays task text literally. Use `task.id` as the key so rows retain their identity when reordered; React's [list rendering guide](https://react.dev/learn/rendering-lists#keeping-list-items-in-order-with-key) explains stable keys.
## Show the list in the window
Replace `src/app.tsx` with the following. It keeps the window and header bar, removes the unused status-page import, and puts `TaskList` in the content slot.
```tsx [src/app.tsx]
import {
AdwApplication,
AdwApplicationWindow,
AdwHeaderBar,
AdwToolbarView,
} from "@gtkx/jsx/adw";
import { quit } from "@gtkx/react";
import { TaskList } from "./components/task-list.js";
export function App() {
return (
quit()}
>
}>
);
}
```
## Run it
The window shows three task titles in a card under the header bar. **Welcome to Tasks** has a second line of notes; the other rows have titles only.
Widen the window until the card stops growing and stays centered. Shorten it until the list scrolls. Add a fourth entry to `TASKS` with a unique `id` and title, check that it appears, then remove it before continuing.
## Next
[Add Tasks](/tutorial/the-task-store) moves the sample data into a store and adds an entry row.
---
---
description: "Connect an Adwaita entry row to a Zustand store to add tasks."
---
# Add Tasks
Connect the list from [Display Tasks](/tutorial/a-list-of-tasks) to a store, then add an entry row that creates tasks when you press Enter.
## Shared task state
Tasks will share state between the list, sidebar, editor, and keyboard actions. This tutorial uses [Zustand](https://zustand.docs.pmnd.rs/learn/getting-started/introduction), whose React hooks work with GTKX. Its documentation covers store creation and subscriptions; this chapter connects that store to native widgets.
## Install Zustand
From `tasks/`:
::: code-group
```bash [npm]
npm install zustand
```
```bash [pnpm]
pnpm add zustand
```
:::
## The seed data
Move the initial tasks into a seed module.
`src/store/seed.ts`:
```ts [src/store/seed.ts]
import type { Task } from "../types.js";
const isoInDays = (days: number): string => {
const date = new Date();
date.setDate(date.getDate() + days);
date.setHours(18, 0, 0, 0);
return date.toISOString();
};
const startOfToday = (): string => {
const date = new Date();
date.setHours(0, 0, 0, 0);
return date.toISOString();
};
const createdAt = new Date().toISOString();
const task = (fields: Partial & Pick): Task => ({
notes: "",
done: false,
important: false,
deleted: false,
due: null,
createdAt,
completedAt: null,
...fields,
});
export const seedTasks: Task[] = [
task({
id: "t1",
listId: "personal",
title: "Welcome to Tasks",
position: 0,
notes: "This is your first task. Tick the checkbox to complete it, or open it to add notes and a due date.",
}),
task({
id: "t2",
listId: "personal",
title: "Water the plants",
position: 1,
due: startOfToday(),
important: true,
}),
task({ id: "t3", listId: "work", title: "Prepare the weekly report", position: 2, due: isoInDays(1) }),
];
```
Relative due dates give the Today view sample content on a fresh start. Once persistence is enabled, saved dates remain unchanged.
## The store
`src/store/index.ts`:
```ts [src/store/index.ts]
import { create } from "zustand";
import type { Task } from "../types.js";
import { seedTasks } from "./seed.js";
export type Store = {
tasks: Task[];
addTask: (listId: string, title: string) => string | null;
};
export const useStore = create()((set) => ({
tasks: seedTasks,
addTask: (listId, title) => {
const trimmed = title.trim();
if (trimmed === "") return null;
const id = crypto.randomUUID();
set((state) => ({
tasks: [
...state.tasks,
{
id,
listId,
title: trimmed,
notes: "",
done: false,
important: false,
deleted: false,
due: null,
position: state.tasks.length,
createdAt: new Date().toISOString(),
completedAt: null,
},
],
}));
return id;
},
}));
```
`addTask` ignores blank titles and returns the new task's ID. The editor will use that ID in [Edit Tasks](/tutorial/the-task-editor).
## Connect the entry row
Replace `src/components/task-list.tsx` with this component. The store supplies `tasks` and `addTask`, replacing the file's sample array.
```tsx [src/components/task-list.tsx]
import * as Gtk from "@gtkx/gi/gtk";
import { AdwActionRow, AdwClamp, AdwEntryRow } from "@gtkx/jsx/adw";
import { GtkListBox, GtkScrolledWindow } from "@gtkx/jsx/gtk";
import { useStore } from "../store/index.js";
export const TaskList = () => {
const tasks = useStore((state) => state.tasks);
const addTask = useStore((state) => state.addTask);
return (
{
addTask("personal", self.text);
self.text = "";
}}
/>
{tasks.map((task) => (
))}
);
};
```
`onEntryActivated` receives the emitting widget as its last argument. This signal has no other arguments, so the handler receives only `self`. It reads the entry's text, adds a task, and clears the entry.
The `"personal"` list ID is temporary. [Add Lists and a Sidebar](/tutorial/lists-and-the-sidebar) replaces it with the selected list. Select `state.tasks` directly here; the tutorial introduces derived selectors in [Filter and Search Tasks](/tutorial/smart-views-and-search).
## Run it
Save `task-list.tsx`. The **Add a task…** entry appears above the sample tasks. Type `Buy oat milk` and press Enter: the task appears at the bottom of the list and the entry clears. Press Enter again to confirm that an empty title creates no task.
Restart the app. The seeded tasks return and newly added tasks are gone because the store is still in memory. [Save Tasks](/tutorial/saving-to-disk) adds persistence.
## Test the entry row
The scaffold includes the GTKX Vitest plugin and `@gtkx/testing`. Create `tests/tasks.test.tsx`:
```tsx [tests/tasks.test.tsx]
import * as Gtk from "@gtkx/gi/gtk";
import { rootElement } from "@gtkx/react";
import { render, screen, userEvent } from "@gtkx/testing";
import { beforeEach, describe, expect, it } from "vitest";
import { App } from "../src/app.js";
import { useStore } from "../src/store/index.js";
import { seedTasks } from "../src/store/seed.js";
beforeEach(() => {
useStore.setState({ tasks: seedTasks });
});
describe("adding tasks", () => {
it.each(["Buy oat milk", " Milk & tea "])("adds the literal title %s", async (title) => {
await render(, { container: rootElement });
const entry = await screen.findByRole(Gtk.AccessibleRole.TEXT_BOX);
await userEvent.type(entry, title);
await userEvent.keyboard(entry, "{Enter}");
expect(await screen.findByRole(Gtk.AccessibleRole.LIST_ITEM, { name: title.trim() })).toBeDefined();
expect(entry).toHaveValue("");
});
it("leaves the list unchanged for a blank title", async () => {
await render(, { container: rootElement });
const entry = await screen.findByRole(Gtk.AccessibleRole.TEXT_BOX);
const rowCount = screen.getAllByRole(Gtk.AccessibleRole.LIST_ITEM).length;
await userEvent.type(entry, " ");
await userEvent.keyboard(entry, "{Enter}");
expect(screen.getAllByRole(Gtk.AccessibleRole.LIST_ITEM)).toHaveLength(rowCount);
expect(entry).toHaveValue("");
});
});
```
These tests type into the app's widgets. They cover adding a task, trimming and displaying literal text, and rejecting a blank title. `beforeEach` restores the sample tasks; GTKX unmounts rendered trees between tests. `App` renders an application, so pass `rootElement` as its container.
```bash
npm test
```
Keep these tests as you continue. [Save Tasks](/tutorial/saving-to-disk#isolate-test-data) isolates the persistence directory before tests begin writing files, and [Test the App](/tutorial/testing) extends the suite.
## Next
[Complete, Star, and Delete Tasks](/tutorial/completing-and-deleting) gives every row a checkbox, a star, and a delete button, each wired to a store action.
---
---
description: "Add row controls for completing, starring, and deleting tasks."
---
# Complete, Star, and Delete Tasks
In [Add Tasks](/tutorial/the-task-store) you moved the task array into a Zustand store. This chapter adds a checkbox, a star, and a delete button to each row.
## More actions on the store
Add store actions for completion, importance, and deletion. They share a helper that updates a task by ID.
In `src/store/index.ts`, add the helper and the actions:
```diff [src/store/index.ts]
@@ -7,0 +8,3 @@
+ setDone: (id: string, done: boolean) => void;
+ setImportant: (id: string, important: boolean) => void;
+ moveToTrash: (id: string) => void;
@@ -8,0 +12,3 @@
+
+const patch = (tasks: Task[], id: string, fields: Partial): Task[] =>
+ tasks.map((task) => (task.id === id ? { ...task, ...fields } : task));
@@ -35,0 +42,6 @@
+ setDone: (id, done) =>
+ set((state) => ({
+ tasks: patch(state.tasks, id, { done, completedAt: done ? new Date().toISOString() : null }),
+ })),
+ setImportant: (id, important) => set((state) => ({ tasks: patch(state.tasks, id, { important }) })),
+ moveToTrash: (id) => set((state) => ({ tasks: patch(state.tasks, id, { deleted: true }) })),
```
`setDone` records the completion time in `completedAt` and clears it when you uncheck the box.
`moveToTrash` sets a flag instead of removing the task from the array. That keeps the data available for the Trash view in [Filter and Search Tasks](/tutorial/smart-views-and-search) and for undo in [Add Undo and Delete Confirmation](/tutorial/trash-and-toasts). For now, hide deleted tasks from the list.
In `src/components/task-list.tsx`, filter the deleted tasks out before rendering:
```diff [src/components/task-list.tsx]
@@ -21 +21 @@
- {tasks.map((task) => (
+ {tasks.filter((task) => !task.deleted).map((task) => (
```
## A component per row
Keep the row's controls together in a `TaskRow` component.
Create `src/components/task-row.tsx`:
```tsx [src/components/task-row.tsx]
import { markupEscapeText } from "@gtkx/gi/glib";
import * as Gtk from "@gtkx/gi/gtk";
import { AdwActionRow } from "@gtkx/jsx/adw";
import { GtkButton, GtkCheckButton, GtkToggleButton } from "@gtkx/jsx/gtk";
import { useStore } from "../store/index.js";
import type { Task } from "../types.js";
export const TaskRow = ({ task }: { task: Task }) => {
const setDone = useStore((state) => state.setDone);
const setImportant = useStore((state) => state.setImportant);
const moveToTrash = useStore((state) => state.moveToTrash);
const escapedTitle = markupEscapeText(task.title, -1);
const title = task.done ? `${escapedTitle}` : escapedTitle;
return (
setDone(task.id, self.active)}
/>
}
suffix={
<>
setImportant(task.id, self.active)}
/>
moveToTrash(task.id)}
/>
>
}
/>
);
};
```
Then use it from the list. In `src/components/task-list.tsx`:
```diff [src/components/task-list.tsx]
@@ -2 +2 @@
-import { AdwActionRow, AdwClamp, AdwEntryRow } from "@gtkx/jsx/adw";
+import { AdwClamp, AdwEntryRow } from "@gtkx/jsx/adw";
@@ -4,0 +5 @@
+import { TaskRow } from "./task-row.js";
@@ -22 +23 @@
-
+
```
`TaskRow` receives the task as a prop and selects the store actions it needs.
## Connecting native controls
`prefix` holds the checkbox, and `suffix` holds the fragment with both trailing buttons. GTKX places those elements in the row's native child slots.
The checkbox and star pair `active` with `onToggled`: the prop follows the task, and the handler receives the emitting widget and saves its new state. The delete button uses `onClicked` to run its action.
With `useMarkup`, the row reads its title as markup. Escape the task title with GLib's [`markupEscapeText`](https://docs.gtk.org/glib/func.markup_escape_text.html) before adding the strikethrough. This keeps titles such as `Buy milk & eggs` literal.
`accessibleLabel` names the icon-only controls for assistive technology and the queries used in [Test the App](/tutorial/testing).
## Run it
Save the files. Each row now has a checkbox, a star, and a trash button.
Tick the checkbox on **Welcome to Tasks**. Its title gets a strikethrough, and the box stays ticked.
Click an unfilled star. Its icon fills in. Click it again to clear it.
Click the trash button on a row. The row leaves the list. The task remains in the store with `deleted: true`.
Now quit and start the app again. The seeded tasks return with their original values: this chapter's changes still live only in memory.
## Next
[Save Tasks](/tutorial/saving-to-disk) persists tasks and their changes between launches.
---
---
description: "Persist the store to the XDG data directory so tasks survive a restart."
---
# Save Tasks
Keep the tasks from [Complete, Star, and Delete Tasks](/tutorial/completing-and-deleting) between launches. Zustand handles persistence; a file adapter connects it to the GTKX application's data directory.
## A storage backend
Store task content in the application's data directory. Preferences use GSettings, introduced in [Add Preferences](/tutorial/preferences-and-theming).
Zustand's [`persist` middleware](https://zustand.docs.pmnd.rs/reference/middlewares/persist) accepts a custom storage adapter. GTKX runs on Node.js, so the adapter can use filesystem APIs directly.
Create `src/store/storage.ts`:
```ts [src/store/storage.ts]
import { fileSetContents, getUserDataDir } from "@gtkx/gi/glib";
import type { StateStorage } from "zustand/middleware";
import { mkdirSync, readFileSync, rmSync } from "node:fs";
import { join } from "node:path";
import { applicationId } from "virtual:gtkx-config";
const directory = join(getUserDataDir(), applicationId);
const file = join(directory, "tasks.json");
export const fileStorage: StateStorage = {
getItem: () => {
try {
return readFileSync(file, "utf8");
} catch (error) {
if (error instanceof Error && "code" in error && error.code === "ENOENT") {
return null;
}
throw error;
}
},
setItem: (_name, value) => {
mkdirSync(directory, { recursive: true });
fileSetContents(file, Buffer.from(value));
},
removeItem: () => {
rmSync(file, { force: true });
},
};
```
GLib supplies the desktop data directory and replaces the saved file atomically. Only a missing file starts a fresh store; other read errors and write errors propagate to the application.
## Turning it on
Wrap the store creator from [Add Tasks](/tutorial/the-task-store) in `persist`. Keep the existing actions and add the persistence options below.
Add these imports to `src/store/index.ts`:
```diff [src/store/index.ts]
@@ -1,0 +2,2 @@
+import { createJSONStorage, persist } from "zustand/middleware";
+import { fileStorage } from "./storage.js";
```
Then update the store definition, keeping its existing action bodies:
```diff [src/store/index.ts]
@@ -18,33 +18,57 @@
-export const useStore = create()((set) => ({
- tasks: seedTasks,
- addTask: (listId, title) => {
- const trimmed = title.trim();
- if (trimmed === "") return null;
- const id = crypto.randomUUID();
- set((state) => ({
- tasks: [
- ...state.tasks,
- {
- id,
- listId,
- title: trimmed,
- notes: "",
- done: false,
- important: false,
- deleted: false,
- due: null,
- position: state.tasks.length,
- createdAt: new Date().toISOString(),
- completedAt: null,
- },
- ],
- }));
- return id;
- },
- setDone: (id, done) =>
- set((state) => ({
- tasks: patch(state.tasks, id, { done, completedAt: done ? new Date().toISOString() : null }),
- })),
- setImportant: (id, important) => set((state) => ({ tasks: patch(state.tasks, id, { important }) })),
- moveToTrash: (id) => set((state) => ({ tasks: patch(state.tasks, id, { deleted: true }) })),
-}));
+export type PersistedState = { tasks: Task[] };
+
+let hydrationError: unknown;
+
+export const useStore = create()(
+ persist(
+ (set) => ({
+ tasks: seedTasks,
+ addTask: (listId, title) => {
+ const trimmed = title.trim();
+ if (trimmed === "") return null;
+ const id = crypto.randomUUID();
+ set((state) => ({
+ tasks: [
+ ...state.tasks,
+ {
+ id,
+ listId,
+ title: trimmed,
+ notes: "",
+ done: false,
+ important: false,
+ deleted: false,
+ due: null,
+ position: state.tasks.length,
+ createdAt: new Date().toISOString(),
+ completedAt: null,
+ },
+ ],
+ }));
+ return id;
+ },
+ setDone: (id, done) =>
+ set((state) => ({
+ tasks: patch(state.tasks, id, { done, completedAt: done ? new Date().toISOString() : null }),
+ })),
+ setImportant: (id, important) => set((state) => ({ tasks: patch(state.tasks, id, { important }) })),
+ moveToTrash: (id) => set((state) => ({ tasks: patch(state.tasks, id, { deleted: true }) })),
+ }),
+ {
+ name: "tasks",
+ version: 1,
+ storage: createJSONStorage(() => fileStorage),
+ partialize: (state): PersistedState => ({ tasks: state.tasks }),
+ migrate: () => {
+ throw new Error("Unsupported task data version");
+ },
+ onRehydrateStorage: () => (_state, error) => {
+ hydrationError = error;
+ },
+ },
+ ),
+);
+
+if (hydrationError !== undefined) {
+ throw hydrationError;
+}
```
`partialize` limits saved content to tasks. Later chapters add UI state that should reset when the app starts. The adapter uses one file, so it does not need the storage key passed as `name`.
Because this adapter is synchronous, saved tasks are loaded before the first render and each store update writes them to disk. On a fresh install, the list starts with `seedTasks`; an existing saved list, including an empty one, replaces those defaults.
The initialization check stops the app if loading or parsing fails, preserving the saved file. An unsupported format version also fails. When the app changes its saved format, replace that rejection with a migration; the [middleware documentation](https://zustand.docs.pmnd.rs/reference/middlewares/persist) covers that API.
## Isolate test data
Before running the tests from Add Tasks, give them a temporary data directory so they cannot overwrite tasks in your development app. Replace `vitest.config.ts` with:
```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"],
bail: 1,
env: {
LANG: "C.UTF-8",
LANGUAGE: "en",
LC_ALL: "C.UTF-8",
},
},
});
```
Create `tests/setup.ts`:
```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(), "gtkx-tutorial-"));
process.env.XDG_DATA_HOME = dataHome;
afterAll(() => {
rmSync(dataHome, { recursive: true, force: true });
});
```
Vitest runs this file before importing the app, so the storage backend reads the temporary path. The existing `beforeEach` in `tests/tasks.test.tsx` resets tasks between tests; those resets now also write to the temporary file. Keep `npm test` passing as you continue.
## Run it
Save the files, add a task, and change its checkbox or star. Close the window, then start the app again:
```bash
npm run dev
```
The task and its changes remain. Delete a task and restart once more to check that it stays deleted.
With the default data directory, you can inspect the saved tasks:
```bash
jq .state.tasks ~/.local/share/com.gtkx.tutorial/tasks.json
```
If you set `XDG_DATA_HOME`, use that directory instead. [Package the App](/tutorial/packaging) covers running the same application in a Flatpak.
## Next
[Add Lists and a Sidebar](/tutorial/lists-and-the-sidebar) splits the store into slices and adds a sidebar for selecting lists.
---
---
description: "Organize tasks into lists and navigate between them with an Adwaita split view."
---
# Add Lists and a Sidebar
Your tasks now survive a restart. Add a sidebar for Personal, Work, and Shopping, with the selected list opening in the content pane.
## Add the lists
`Task` already has a `listId`. Add these two types to `src/types.ts`:
```diff [src/types.ts]
@@ -13,0 +14,8 @@
+
+export type TaskList = {
+ id: string;
+ name: string;
+ color: string;
+};
+
+export type Selection = { kind: "list"; listId: string };
```
In `src/store/seed.ts`, add `TaskList` to the existing type import and append the list defaults:
```diff [src/store/seed.ts]
@@ -1 +1 @@
-import type { Task } from "../types.js";
+import type { Task, TaskList } from "../types.js";
@@ -46,0 +47,6 @@
+
+export const seedLists: TaskList[] = [
+ { id: "personal", name: "Personal", color: "#3584e4" },
+ { id: "work", name: "Work", color: "#2ec27e" },
+ { id: "shopping", name: "Shopping", color: "#e66100" },
+];
```
Keep your existing `seedTasks`. Saved tasks take precedence over seed data, so changing that array would not add tasks to a list you have already saved. Shopping starts empty; you can add tasks to it through the app.
## Split the store
Separate tasks and lists using Zustand's [slices pattern](https://zustand.docs.pmnd.rs/learn/guides/slices-pattern). Persistence stays on the combined store.
Move the task state and actions into `src/store/tasks.ts`:
```ts [src/store/tasks.ts]
import type { StateCreator } from "zustand";
import type { Task } from "../types.js";
import type { Mutators, Store } from "./index.js";
import { seedTasks } from "./seed.js";
export type TasksSlice = {
tasks: Task[];
addTask: (listId: string, title: string) => string | null;
setDone: (id: string, done: boolean) => void;
setImportant: (id: string, important: boolean) => void;
moveToTrash: (id: string) => void;
};
const patch = (tasks: Task[], id: string, fields: Partial): Task[] =>
tasks.map((task) => (task.id === id ? { ...task, ...fields } : task));
export const createTasksSlice: StateCreator = (set) => ({
tasks: seedTasks,
addTask: (listId, title) => {
const trimmed = title.trim();
if (trimmed === "") return null;
const id = crypto.randomUUID();
set((state) => ({
tasks: [
...state.tasks,
{
id,
listId,
title: trimmed,
notes: "",
done: false,
important: false,
deleted: false,
due: null,
position: state.tasks.length,
createdAt: new Date().toISOString(),
completedAt: null,
},
],
}));
return id;
},
setDone: (id, done) =>
set((state) => ({
tasks: patch(state.tasks, id, { done, completedAt: done ? new Date().toISOString() : null }),
})),
setImportant: (id, important) => set((state) => ({ tasks: patch(state.tasks, id, { important }) })),
moveToTrash: (id) => set((state) => ({ tasks: patch(state.tasks, id, { deleted: true }) })),
});
```
Create `src/store/lists.ts`:
```ts [src/store/lists.ts]
import type { StateCreator } from "zustand";
import type { TaskList } from "../types.js";
import type { Mutators, Store } from "./index.js";
import { seedLists } from "./seed.js";
export type ListsSlice = {
lists: TaskList[];
addList: (name: string, color: string) => void;
};
export const createListsSlice: StateCreator = (set) => ({
lists: seedLists,
addList: (name, color) => {
const trimmed = name.trim();
if (trimmed === "") return;
set((state) => ({ lists: [...state.lists, { id: crypto.randomUUID(), name: trimmed, color }] }));
},
});
```
The New List dialog will use `addList` in [Add Undo and Delete Confirmation](/tutorial/trash-and-toasts).
Replace `src/store/index.ts` with:
```ts [src/store/index.ts]
import { create } from "zustand";
import { createJSONStorage, persist } from "zustand/middleware";
import type { Task, TaskList } from "../types.js";
import { createListsSlice, type ListsSlice } from "./lists.js";
import { fileStorage } from "./storage.js";
import { createTasksSlice, type TasksSlice } from "./tasks.js";
export type Store = TasksSlice & ListsSlice;
export type PersistedState = { lists: TaskList[]; tasks: Task[] };
export type Mutators = [["zustand/persist", unknown]];
let hydrationError: unknown;
export const useStore = create()(
persist(
(...a) => ({
...createTasksSlice(...a),
...createListsSlice(...a),
}),
{
name: "tasks",
version: 1,
storage: createJSONStorage(() => fileStorage),
partialize: (state): PersistedState => ({ lists: state.lists, tasks: state.tasks }),
migrate: () => {
throw new Error("Unsupported task data version");
},
onRehydrateStorage: () => (_state, error) => {
hydrationError = error;
},
},
),
);
if (hydrationError !== undefined) {
throw hydrationError;
}
```
Subsequent saves include both `tasks` and `lists`. Existing saved tasks remain intact, and `seedLists` supplies lists when loading a file from the previous chapter.
The selected list belongs to navigation state. Keep it out of the store: the route already identifies what the content pane shows. Later chapters put temporary filters in a UI slice and persistent application preferences in GSettings.
## Add the navigator
Install navigation and CSS support from the project directory:
::: code-group
```bash [npm]
npm install @gtkx/navigation@1.6.0 @gtkx/css@1.6.0 @react-navigation/core@^7
```
```bash [pnpm]
pnpm add @gtkx/navigation@1.6.0 @gtkx/css@1.6.0 @react-navigation/core@^7
```
:::
Install `@react-navigation/core` directly because [Edit Tasks](/tutorial/the-task-editor) augments its types. GTKX integrates React Navigation with libadwaita. Its split view navigator uses `AdwNavigationSplitView`: the first declared screen is the sidebar, and the remaining screens share a content stack. It supplies each screen's navigation page and header bar.
Create `src/navigation.ts`:
```ts [src/navigation.ts]
import { createSplitViewNavigator, useNavigationState } from "@gtkx/navigation";
import type { Selection } from "./types.js";
export type RootParamList = {
Lists: undefined;
Tasks: Selection;
};
export const Split = createSplitViewNavigator();
const isSelection = (params: object | undefined): params is Selection =>
params !== undefined && "kind" in params;
export const useSelection = (): Selection | null =>
useNavigationState((state) => {
const params = state.routes.find((route) => route.name === "Tasks")?.params;
return isSelection(params) ? params : null;
});
```
`Tasks` carries the selected list in its params. `useSelection` lets the sidebar read that selection and returns `null` when no tasks page is open. The [navigation guide](/guide/navigation) covers GTKX's navigators; React Navigation documents [route typing](https://reactnavigation.org/docs/typescript/).
## Move the window into a component
Create `src/components/window.tsx`:
```tsx [src/components/window.tsx]
import { AdwApplicationWindow } from "@gtkx/jsx/adw";
import { NavigationContainer } from "@gtkx/navigation";
import { quit } from "@gtkx/react";
import { Split } from "../navigation.js";
import { useStore } from "../store/index.js";
import { Sidebar } from "./sidebar.js";
import { TasksScreen } from "./tasks-screen.js";
export const Window = () => {
const lists = useStore((state) => state.lists);
return (
quit()}>
({
title: lists.find((list) => list.id === route.params.listId)?.name ?? "Tasks",
})}
/>
);
};
```
`Lists` stays first so it owns the sidebar. `initialRouteName` and `initialParams` open Personal at startup. The tasks page's title follows its route params.
The navigator now owns the toolbar and header. Each screen supplies its content widget. Create `src/components/tasks-screen.tsx`:
```tsx [src/components/tasks-screen.tsx]
import type { SplitViewScreenProps } from "@gtkx/navigation";
import type { RootParamList } from "../navigation.js";
import { TaskList } from "./task-list.js";
export const TasksScreen = ({ route }: SplitViewScreenProps) => (
);
```
Replace `src/app.tsx` with:
```tsx [src/app.tsx]
import { AdwApplication } from "@gtkx/jsx/adw";
import { Window } from "./components/window.js";
export function App() {
return (
);
}
```
Keep the existing `src/index.tsx`; it still imports the named `App` export.
## Draw the sidebar
Use a small CSS rule for each list's color. Create `src/styles.ts`:
```ts [src/styles.ts]
import { css } from "@gtkx/css";
export const listDot = (color: string): string => css`
min-width: 12px;
min-height: 12px;
border-radius: 9999px;
background: ${color};
`;
```
Adwaita's built-in classes handle the rest of the styling. See [Styling with CSS](/guide/css) for GTKX's CSS integration.
Create `src/components/sidebar.tsx`:
```tsx [src/components/sidebar.tsx]
import * as Gtk from "@gtkx/gi/gtk";
import { AdwActionRow } from "@gtkx/jsx/adw";
import { GtkBox, GtkListBox, GtkScrolledWindow } from "@gtkx/jsx/gtk";
import type { SplitViewScreenProps } from "@gtkx/navigation";
import { type RootParamList, useSelection } from "../navigation.js";
import { useStore } from "../store/index.js";
import { listDot } from "../styles.js";
export const Sidebar = ({ navigation }: SplitViewScreenProps) => {
const lists = useStore((state) => state.lists);
const selection = useSelection();
const activeIndex = lists.findIndex((list) => list.id === selection?.listId);
return (
{
if (!row) return;
const list = lists[row.getIndex()];
if (list) {
navigation.navigate("Tasks", { kind: "list", listId: list.id });
}
}}
>
{lists.map((list) => (
}
/>
))}
);
};
```
`useMarkup={false}` keeps list names literal. The colored dot is decorative, so it uses the presentation accessibility role.
## Keep selection in sync {#keeping-gtk4-and-the-route-in-agreement}
`selectedIndex` makes the native selection follow the route; `-1` clears it. `onRowSelected` handles selections made outside GTKX's prop writes. GTKX suppresses the signal caused by its own selection write, avoiding a navigation loop.
For this navigator, `navigate("Tasks", params)` returns to the existing tasks page with new params, removing any pages above it. If that page is absent, it opens it. Selecting a list therefore changes the content pane without accumulating task-list pages.
## Filter the tasks
Replace `src/components/task-list.tsx` with:
```tsx [src/components/task-list.tsx]
import * as Gtk from "@gtkx/gi/gtk";
import { AdwClamp, AdwEntryRow } from "@gtkx/jsx/adw";
import { GtkListBox, GtkScrolledWindow } from "@gtkx/jsx/gtk";
import { useStore } from "../store/index.js";
import type { Selection } from "../types.js";
import { TaskRow } from "./task-row.js";
export const TaskList = ({ selection }: { selection: Selection }) => {
const tasks = useStore((state) => state.tasks);
const addTask = useStore((state) => state.addTask);
const visible = tasks.filter((task) => !task.deleted && task.listId === selection.listId);
return (
{
addTask(selection.listId, self.text);
self.text = "";
}}
/>
{visible.map((task) => (
))}
);
};
```
The screen passes its selection directly to the list. New tasks use that list's ID, while deleted tasks remain hidden.
## Run it
Save the files. Personal is selected in the sidebar, and its tasks appear under a header named Personal.
Click Work, then Shopping. Add a task in Shopping, switch to Personal, and return: the new task belongs only to Shopping.
Close the window and start `npm run dev` again. Tasks and lists return from disk; navigation starts on Personal again.
## Next
Continue to [Adapt the Layout](/tutorial/an-adaptive-layout).
---
---
description: "Collapse the sidebar and task list into one pane on narrow windows."
---
# Adapt the Layout
The [sidebar and task list](/tutorial/lists-and-the-sidebar) fit beside each other in a wide window. At the minimum width of 360 logical pixels, they need to share one pane. Add a breakpoint that collapses the split view and lets the navigator handle moving between the panes.
## Store the collapse state
Create `src/store/ui.ts`:
```ts [src/store/ui.ts]
import type { StateCreator } from "zustand";
import type { Mutators, Store } from "./index.js";
export type UiSlice = {
collapsed: boolean;
setCollapsed: (collapsed: boolean) => void;
};
export const createUiSlice: StateCreator = (set) => ({
collapsed: false,
setCollapsed: (collapsed) => set({ collapsed }),
});
```
Add the UI slice to `src/store/index.ts`:
```diff [src/store/index.ts]
@@ -6,0 +7 @@
+import { createUiSlice, type UiSlice } from "./ui.js";
@@ -8 +9 @@
-export type Store = TasksSlice & ListsSlice;
+export type Store = TasksSlice & ListsSlice & UiSlice;
@@ -20,0 +22 @@
+ ...createUiSlice(...a),
```
Keep `PersistedState` and `partialize` unchanged. The window's current size determines `collapsed` each time the app starts; it should not be restored from disk.
## Add the breakpoint
In `src/components/window.tsx`, read `collapsed` and `setCollapsed`. Add an `AdwBreakpoint` to the window's `breakpoints` slot:
```diff [src/components/window.tsx]
@@ -1 +1,2 @@
-import { AdwApplicationWindow } from "@gtkx/jsx/adw";
+import * as Adw from "@gtkx/gi/adw";
+import { AdwApplicationWindow, AdwBreakpoint } from "@gtkx/jsx/adw";
@@ -10,0 +12,2 @@
+ const collapsed = useStore((state) => state.collapsed);
+ const setCollapsed = useStore((state) => state.setCollapsed);
@@ -13 +16,13 @@
- quit()}>
+ quit()}
+ breakpoints={
+ setCollapsed(true)}
+ onUnapply={() => setCollapsed(false)}
+ />
+ }
+ >
```
`onApply` sets `collapsed` when the condition becomes true; `onUnapply` clears it when the window grows again. `Adw.BreakpointCondition.parse` parses the condition at runtime, so TypeScript cannot catch a malformed condition string.
Use `sp` for the threshold so it grows with the text scale. At the default text size, `500sp` equals `500px`; with the standard Large Text setting it equals `625px`. See [Adwaita's length units](https://gnome.pages.gitlab.gnome.org/libadwaita/doc/main/enum.LengthUnit.html).
Here `px` means logical window coordinates, not physical display pixels. GTK maps window coordinates to device pixels using the [display scale](https://docs.gtk.org/gtk4/method.Widget.get_scale_factor.html). A threshold in `px` follows display scaling but does not grow with the text scale.
## Pass the state to the navigator
Still in `src/components/window.tsx`, pass the new value to `Split.Navigator`:
```diff [src/components/window.tsx]
@@ -31,0 +32 @@
+ collapsed={collapsed}
```
The breakpoint updates the store; the navigator reads it to switch layouts. Keep the selected page in navigation state. The navigator handles the back button, keyboard navigation, and swipe gestures without a separate selected-pane field.
## Fill the empty content pane
In a collapsed window, going back from the task list returns to the sidebar and empties the content stack. Widening the window then leaves an empty content pane. Use `contentPlaceholder` to explain what to do next.
Above `Window`, add `NothingSelected`:
```diff [src/components/window.tsx]
@@ -2 +2 @@
-import { AdwApplicationWindow, AdwBreakpoint } from "@gtkx/jsx/adw";
+import { AdwApplicationWindow, AdwBreakpoint, AdwStatusPage } from "@gtkx/jsx/adw";
@@ -8,0 +9,8 @@
+
+const NothingSelected = () => (
+
+);
```
Pass it to the navigator:
```diff [src/components/window.tsx]
@@ -43,0 +44 @@
+ contentPlaceholder={}
```
When the content stack is empty, `useSelection` returns `null`. The sidebar's `lists.findIndex` then returns `-1`, which clears `selectedIndex`. GTKX suppresses the resulting `row-selected` signal when applying that prop, so clearing the highlight does not navigate again.
## Run it
1. Narrow the window past the `500sp` threshold. The task list appears alone with a back arrow because `initialRouteName="Tasks"` opens it at startup.
2. Go back to the sidebar. Select a list, then try the back arrow, Escape, Alt + Left, or a touchpad back gesture.
3. Return to the sidebar and widen the window. No row is selected, and the content pane shows **Nothing Selected**. Select a list to restore its tasks.
4. Enable Large Text in the desktop accessibility settings and resize again. The panes should collapse at a wider window size. Restore your preferred text size afterward.
## Next
[Filter and Search Tasks](/tutorial/smart-views-and-search) adds All Tasks, Today, Important, and Trash.
---
---
description: "Add smart views, a native filter control, and a search bar to the task list."
---
# Filter and Search Tasks
The split view now adapts to a narrow window. Add All Tasks, Today, Important, and Trash to its sidebar, then filter and search the selected view.
## Extend the selection
In `src/types.ts`, replace `Selection` and add `SmartView` and `Filter`:
```diff [src/types.ts]
@@ -21 +21,5 @@
-export type Selection = { kind: "list"; listId: string };
+export type SmartView = "all" | "today" | "important" | "trash";
+
+export type Selection = { kind: "smart"; view: SmartView } | { kind: "list"; listId: string };
+
+export type Filter = "all" | "open" | "done";
```
`Selection` remains the `Tasks` route's param type. A smart view combines tasks from any list.
## Derive the visible tasks
Create `src/format.ts` for the shared date helper:
```ts [src/format.ts]
const startOfDay = (date: Date): number => new Date(date.getFullYear(), date.getMonth(), date.getDate()).getTime();
export const isToday = (iso: string | null): boolean => {
if (!iso) return false;
return startOfDay(new Date(iso)) === startOfDay(new Date());
};
```
Create `src/store/selectors.ts`:
```ts [src/store/selectors.ts]
import { isToday } from "../format.js";
import type { Filter, Selection, SmartView, Task, TaskList } from "../types.js";
const SMART_TITLES: Record = {
all: "All Tasks",
today: "Today",
important: "Important",
trash: "Trash",
};
export const selectionKey = (selection: Selection): string =>
selection.kind === "smart" ? `smart:${selection.view}` : `list:${selection.listId}`;
export const selectionTitle = (selection: Selection, lists: TaskList[]): string =>
selection.kind === "list"
? (lists.find((list) => list.id === selection.listId)?.name ?? "Tasks")
: SMART_TITLES[selection.view];
export const addListId = (selection: Selection, lists: TaskList[]): string =>
selection.kind === "list" ? selection.listId : (lists[0]?.id ?? "");
const inSelection = (task: Task, selection: Selection): boolean => {
if (selection.kind === "list") return !task.deleted && task.listId === selection.listId;
switch (selection.view) {
case "all":
return !task.deleted;
case "today":
return !task.deleted && isToday(task.due);
case "important":
return !task.deleted && task.important;
case "trash":
return task.deleted;
}
};
const matchesQuery = (task: Task, query: string): boolean => {
if (!query) return true;
const needle = query.toLowerCase();
return task.title.toLowerCase().includes(needle) || task.notes.toLowerCase().includes(needle);
};
const matchesFilter = (task: Task, filter: Filter): boolean => {
if (filter === "open") return !task.done;
if (filter === "done") return task.done;
return true;
};
export type VisibleOptions = { query: string; filter: Filter };
export const visibleTasks = (tasks: Task[], selection: Selection, options: VisibleOptions): Task[] =>
tasks
.filter(
(task) =>
inSelection(task, selection) &&
matchesQuery(task, options.query) &&
matchesFilter(task, options.filter),
)
.sort((a, b) => a.position - b.position);
export type SidebarCounts = {
all: number;
today: number;
important: number;
trash: number;
lists: Record;
};
export const sidebarCounts = (tasks: Task[], lists: TaskList[]): SidebarCounts => {
const open = tasks.filter((task) => !task.deleted && !task.done);
return {
all: open.length,
today: open.filter((task) => isToday(task.due)).length,
important: open.filter((task) => task.important).length,
trash: tasks.filter((task) => task.deleted).length,
lists: Object.fromEntries(
lists.map((list) => [list.id, open.filter((task) => task.listId === list.id).length]),
),
};
};
export type EmptyState = { icon: string; title: string; description: string };
const SMART_EMPTY: Record = {
all: { icon: "view-list-symbolic", title: "No Tasks Yet", description: "Add a task above to get started" },
today: {
icon: "x-office-calendar-symbolic",
title: "Nothing Due Today",
description: "Tasks due today appear here",
},
important: { icon: "starred-symbolic", title: "No Important Tasks", description: "Star a task to find it here" },
trash: { icon: "user-trash-symbolic", title: "Trash Is Empty", description: "Deleted tasks appear here" },
};
export const emptyState = (selection: Selection, query: string): EmptyState => {
if (query) return { icon: "system-search-symbolic", title: "No Results", description: `No tasks match “${query}”` };
if (selection.kind === "smart") return SMART_EMPTY[selection.view];
return SMART_EMPTY.all;
};
```
Trash includes deleted tasks; the other views exclude them. Sidebar badges count open tasks, except Trash, which counts everything it contains. New tasks created from a smart view go into the first list.
Components will select the stored arrays and derive their visible rows during render. For other selector patterns, see [Zustand's guide](https://zustand.docs.pmnd.rs/learn/guides/prevent-rerenders-with-use-shallow).
## Add the filter and search state
Replace `src/store/ui.ts` with:
```ts [src/store/ui.ts]
import type { StateCreator } from "zustand";
import type { Filter } from "../types.js";
import type { Mutators, Store } from "./index.js";
export type UiSlice = {
collapsed: boolean;
filter: Filter;
searchMode: boolean;
searchQuery: string;
setCollapsed: (collapsed: boolean) => void;
setFilter: (filter: Filter) => void;
setSearchMode: (searchMode: boolean) => void;
setSearchQuery: (searchQuery: string) => void;
resetSearch: () => void;
};
export const createUiSlice: StateCreator = (set) => ({
collapsed: false,
filter: "all",
searchMode: false,
searchQuery: "",
setCollapsed: (collapsed) => set({ collapsed }),
setFilter: (filter) => set({ filter }),
setSearchMode: (searchMode) => set({ searchMode }),
setSearchQuery: (searchQuery) => set({ searchQuery }),
resetSearch: () => set({ searchMode: false, searchQuery: "" }),
});
```
The UI slice is already excluded by `partialize`, so the filter and search start fresh on each launch. Choosing a sidebar entry calls `resetSearch` before navigating.
## Update the sidebar
Replace `src/components/sidebar.tsx` with:
```tsx [src/components/sidebar.tsx]
import * as Gtk from "@gtkx/gi/gtk";
import { AdwActionRow } from "@gtkx/jsx/adw";
import { GtkBox, GtkImage, GtkLabel, GtkListBox, GtkScrolledWindow } from "@gtkx/jsx/gtk";
import type { SplitViewScreenProps } from "@gtkx/navigation";
import { type RootParamList, useSelection } from "../navigation.js";
import { useStore } from "../store/index.js";
import { type SidebarCounts, selectionKey, sidebarCounts } from "../store/selectors.js";
import { listDot } from "../styles.js";
import type { Selection, TaskList } from "../types.js";
type Entry = {
selection: Selection;
title: string;
icon?: string;
color?: string;
count: number;
};
const buildEntries = (lists: TaskList[], counts: SidebarCounts): Entry[] => [
{
selection: { kind: "smart", view: "all" },
title: "All Tasks",
icon: "view-list-symbolic",
count: counts.all,
},
{
selection: { kind: "smart", view: "today" },
title: "Today",
icon: "x-office-calendar-symbolic",
count: counts.today,
},
{
selection: { kind: "smart", view: "important" },
title: "Important",
icon: "starred-symbolic",
count: counts.important,
},
...lists.map(
(list): Entry => ({
selection: { kind: "list", listId: list.id },
title: list.name,
color: list.color,
count: counts.lists[list.id] ?? 0,
}),
),
{
selection: { kind: "smart", view: "trash" },
title: "Trash",
icon: "user-trash-symbolic",
count: counts.trash,
},
];
export const Sidebar = ({ navigation }: SplitViewScreenProps) => {
const tasks = useStore((state) => state.tasks);
const lists = useStore((state) => state.lists);
const resetSearch = useStore((state) => state.resetSearch);
const selection = useSelection();
const entries = buildEntries(lists, sidebarCounts(tasks, lists));
const activeKey = selection === null ? null : selectionKey(selection);
const activeIndex = entries.findIndex((entry) => selectionKey(entry.selection) === activeKey);
return (
{
if (!row) return;
const entry = entries[row.getIndex()];
if (entry) {
resetSearch();
navigation.navigate("Tasks", entry.selection);
}
}}
>
{entries.map((entry) => (
) : (
)
}
suffix={
entry.count > 0 ? (
{String(entry.count)}
) : undefined
}
/>
))}
);
};
```
Each row carries the selection it opens. `selectedIndex` continues to follow the route, now comparing selection keys instead of list IDs. Empty badges are omitted.
In `src/navigation.ts`, add the launch selection:
```diff [src/navigation.ts]
@@ -18,0 +19,2 @@
+
+export const ALL_TASKS: Selection = { kind: "smart", view: "all" };
```
In `src/components/window.tsx`, import it and the title helper:
```diff [src/components/window.tsx]
@@ -5 +5,2 @@
-import { Split } from "../navigation.js";
+import { ALL_TASKS, Split } from "../navigation.js";
+import { selectionTitle } from "../store/selectors.js";
```
Use `initialParams={ALL_TASKS}` on the `Tasks` screen. Its title now comes from `selectionTitle(route.params, lists)`; the complete options appear below.
## Put controls in the header
A header control can be a component with its own store subscription. Create `src/components/task-filter.tsx`:
```tsx [src/components/task-filter.tsx]
import { AdwToggle, AdwToggleGroup } from "@gtkx/jsx/adw";
import { useStore } from "../store/index.js";
export const TaskFilter = () => {
const filter = useStore((state) => state.filter);
const setFilter = useStore((state) => state.setFilter);
return (
{
if (name === "all" || name === "open" || name === "done") setFilter(name);
}}
>
);
};
```
GTKX's notify props receive the property value first. The native toggle name is a nullable string, so the handler accepts only the app's three filter names.
Create `src/components/search-button.tsx`:
```tsx [src/components/search-button.tsx]
import { GtkButton } from "@gtkx/jsx/gtk";
import { useStore } from "../store/index.js";
export const SearchButton = () => {
const searchMode = useStore((state) => state.searchMode);
const setSearchMode = useStore((state) => state.setSearchMode);
return (
setSearchMode(!searchMode)}
/>
);
};
```
The shortcut in the tooltip is added in [Add Menus and Shortcuts](/tutorial/actions-menus-shortcuts).
In `src/components/window.tsx`, import both controls:
```diff [src/components/window.tsx]
@@ -0,0 +1,2 @@
+import { SearchButton } from "./search-button.js";
+import { TaskFilter } from "./task-filter.js";
```
Replace the `Tasks` screen declaration with:
```diff [src/components/window.tsx]
@@ -53 +53 @@
- initialParams={{ kind: "list", listId: "personal" }}
+ initialParams={ALL_TASKS}
@@ -55 +55,3 @@
- title: lists.find((list) => list.id === route.params.listId)?.name ?? "Tasks",
+ title: selectionTitle(route.params, lists),
+ headerTitle: ,
+ headerStart: ,
```
`headerTitle` replaces the visible title widget. Keep `title` as well: it names the native navigation page and is used for back navigation.
## Render search and empty states
Replace `src/components/task-list.tsx` with:
```tsx [src/components/task-list.tsx]
import { markupEscapeText } from "@gtkx/gi/glib";
import * as Gtk from "@gtkx/gi/gtk";
import { AdwClamp, AdwEntryRow, AdwStatusPage } from "@gtkx/jsx/adw";
import { GtkBox, GtkListBox, GtkScrolledWindow, GtkSearchBar, GtkSearchEntry } from "@gtkx/jsx/gtk";
import type { Selection } from "../types.js";
import { useStore } from "../store/index.js";
import { addListId, emptyState, visibleTasks } from "../store/selectors.js";
import { TaskRow } from "./task-row.js";
export const TaskList = ({ selection }: { selection: Selection }) => {
const tasks = useStore((state) => state.tasks);
const lists = useStore((state) => state.lists);
const filter = useStore((state) => state.filter);
const searchMode = useStore((state) => state.searchMode);
const searchQuery = useStore((state) => state.searchQuery);
const setSearchMode = useStore((state) => state.setSearchMode);
const setSearchQuery = useStore((state) => state.setSearchQuery);
const addTask = useStore((state) => state.addTask);
const visible = visibleTasks(tasks, selection, { query: searchQuery, filter });
const empty = emptyState(selection, searchQuery);
const listId = addListId(selection, lists);
return (
setSearchMode(enabled ?? false)}
>
setSearchQuery(self.text)}
/>
{
addTask(listId, self.text);
self.text = "";
}}
/>
{visible.map((task) => (
))}
{visible.length === 0 ? (
) : null}
);
};
```
`GtkSearchBar` owns the search entry and handles dismissal with Escape. Its notify handler updates the store when search closes. `GtkSearchEntry.onSearchChanged` reports edits after the native search delay.
`AdwStatusPage.description` accepts Pango markup. Escape the generated message with GLib's `markupEscapeText` so queries containing `&`, `<`, or markup tags appear literally. The add row stays available when no tasks match.
Replace `src/components/tasks-screen.tsx` with:
```tsx [src/components/tasks-screen.tsx]
import type { SplitViewScreenProps } from "@gtkx/navigation";
import type { RootParamList } from "../navigation.js";
import { selectionKey } from "../store/selectors.js";
import { TaskList } from "./task-list.js";
export const TasksScreen = ({ route }: SplitViewScreenProps) => (
);
```
Changing the selection remounts the native list, clearing its scroll position and unfinished add-row text. React explains [state reset through keys](https://react.dev/learn/preserving-and-resetting-state).
## Run it
Save the files and restart the app to see All Tasks as the launch view.
- Complete an open task and check the sidebar counts.
- Select Today, Important, and Trash. Each shows tasks matching that view.
- Switch the header filter between All, Open, and Done.
- Search for `report`, then `missing & café`. The empty-state message should show the second query literally.
- Choose another sidebar entry. Its handler clears the query and closes the search bar.
Quit and restart once more. Tasks are preserved; the filter returns to All and search is closed.
## Next
Continue to [Edit Tasks](/tutorial/the-task-editor).
---
---
description: "Open a task on the content stack and edit it with native form rows, a calendar, and a text buffer."
---
# Edit Tasks
Give each task an editor with a title, importance switch, due date, and notes. It opens above the task list on the content stack; the navigator supplies its header and back navigation.
## Add the route
In `src/navigation.ts`, extend `RootParamList`:
```diff [src/navigation.ts]
@@ -6,0 +7 @@
+ Task: { id: string };
```
Below `Split`, declare the root navigator type so components can use `useNavigation` without passing navigation through their props:
```diff [src/navigation.ts]
@@ -21,0 +22,6 @@
+
+type RootNavigatorType = typeof Split;
+
+declare module "@react-navigation/core" {
+ interface RootNavigator extends RootNavigatorType { }
+}
```
GTKX re-exports the React Navigation core API, so this augmentation targets `@react-navigation/core`. See React Navigation's [TypeScript guide](https://reactnavigation.org/docs/typescript/) for the underlying pattern.
In `src/components/task-row.tsx`, import `useNavigation` and read it inside `TaskRow`:
```diff [src/components/task-row.tsx]
@@ -4,0 +5 @@
+import { useNavigation } from "@gtkx/navigation";
```
```diff [src/components/task-row.tsx]
@@ -9,0 +10 @@
+ const navigation = useNavigation();
```
Make the action row activatable and open the editor from its signal:
```diff [src/components/task-row.tsx]
@@ -20,0 +21,2 @@
+ activatable
+ onActivated={() => navigation.navigate("Task", { id: task.id })}
```
An activatable row responds to a click or keyboard activation. `navigate("Task", { id })` opens the editor, or changes the params of its existing page.
Create `src/components/task-screen.tsx`:
```tsx [src/components/task-screen.tsx]
import type { SplitViewScreenProps } from "@gtkx/navigation";
import type { RootParamList } from "../navigation.js";
import { useStore } from "../store/index.js";
import { TaskDetail } from "./task-detail.js";
export const TaskScreen = ({ route }: SplitViewScreenProps) => {
const task = useStore((state) => state.tasks.find((candidate) => candidate.id === route.params.id));
return task ? : null;
};
```
The route stores an ID; the screen reads the current task from the store. When the route changes to another task, the key recreates the widgets and resets the form defaults. Back removes the editor page; reopening it creates a new page.
## Add the editing action
In `src/store/tasks.ts`, add `updateTask` to the slice type and implementation:
```diff [src/store/tasks.ts]
@@ -10,0 +11 @@
+ updateTask: (id: string, fields: Partial>) => void;
```
```diff [src/store/tasks.ts]
@@ -48,0 +49 @@
+ updateTask: (id, fields) => set((state) => ({ tasks: patch(state.tasks, id, fields) })),
```
Keep `setDone` for completion timestamps and `setImportant` for the shared star/switch behavior.
## Add date formatting and notes styling
Append these functions to `src/format.ts`, after the existing `startOfDay` and `isToday` helpers:
```diff [src/format.ts]
@@ -6,0 +7,18 @@
+
+export const formatDue = (iso: string | null): string | null => {
+ if (!iso) return null;
+ const due = new Date(iso);
+ const days = Math.round((startOfDay(due) - startOfDay(new Date())) / 86_400_000);
+ const time = due.toLocaleTimeString([], { hour: "numeric", minute: "2-digit" });
+ if (days === 0) return `Today at ${time}`;
+ if (days === 1) return `Tomorrow at ${time}`;
+ if (days === -1) return `Yesterday at ${time}`;
+ if (days < 0) return `${-days} days ago`;
+ if (days < 7) return due.toLocaleDateString([], { weekday: "long" });
+ return due.toLocaleDateString([], { month: "short", day: "numeric" });
+};
+
+export const formatDateTime = (iso: string | null): string => {
+ if (!iso) return "Never";
+ return new Date(iso).toLocaleString([], { dateStyle: "medium", timeStyle: "short" });
+};
```
In `src/components/task-row.tsx`, import the formatter and add the subtitle:
```diff [src/components/task-row.tsx]
@@ -0,0 +1 @@
+import { formatDue } from "../format.js";
```
```diff [src/components/task-row.tsx]
@@ -21,0 +22 @@
+ subtitle={formatDue(task.due) ?? undefined}
```
When no due date remains, `undefined` resets the subtitle to its native default. The row then has no subtitle text.
Append the notes style to `src/styles.ts`:
```diff [src/styles.ts]
@@ -8,0 +9,5 @@
+
+export const detailNotes = css`
+ padding: 6px;
+ min-height: 160px;
+`;
```
## Build the editor
Install `@gtkx/forms` from the project directory:
::: code-group
```bash [npm]
npm install @gtkx/forms@1.6.0
```
```bash [pnpm]
pnpm add @gtkx/forms@1.6.0
```
:::
GTKX form rows connect native Adwaita controls to React Hook Form. This form keeps a title draft until Apply or Enter; importance and the other fields save immediately. For the form API itself, use the [React Hook Form documentation](https://react-hook-form.com/docs/useform).
Create `src/components/task-detail.tsx`:
```tsx [src/components/task-detail.tsx]
import { EntryRow, FormProvider, SwitchRow, useForm } from "@gtkx/forms";
import * as GLib from "@gtkx/gi/glib";
import * as Gtk from "@gtkx/gi/gtk";
import { AdwActionRow, AdwClamp, AdwPreferencesGroup } from "@gtkx/jsx/adw";
import {
GtkBox,
GtkButton,
GtkCalendar,
GtkLabel,
GtkMenuButton,
GtkPopover,
GtkScrolledWindow,
GtkTextBuffer,
GtkTextView,
} from "@gtkx/jsx/gtk";
import { useEffect } from "react";
import { formatDateTime, formatDue } from "../format.js";
import { useStore } from "../store/index.js";
import { detailNotes } from "../styles.js";
import type { Task } from "../types.js";
type TaskFields = Pick;
export const TaskDetail = ({ task }: { task: Task }) => {
const updateTask = useStore((state) => state.updateTask);
const setImportant = useStore((state) => state.setImportant);
const dueDate = task.due ? GLib.DateTime.newFromIso8601(task.due, null) : undefined;
const form = useForm({
defaultValues: { important: task.important, title: task.title },
});
const { resetField } = form;
useEffect(() => {
resetField("important", { defaultValue: task.important });
}, [resetField, task.important]);
const saveTitle = form.handleSubmit(({ title }) => {
const normalized = title.trim();
updateTask(task.id, { title: normalized });
resetField("title", { defaultValue: normalized });
});
const submitTitle = (): void => {
void saveTitle();
};
return (
name="title"
title="Title"
showApplyButton
rules={{ validate: (title) => title.trim().length > 0 }}
onApply={submitTitle}
onEntryActivated={submitTitle}
/>
name="important"
title="Important"
onNotifyActive={(active) => setImportant(task.id, active ?? false)}
/>
{task.due ? (
updateTask(task.id, { due: null })}
/>
) : null}
{
const date = self.getDate();
const picked = new Date(
date.getYear(),
date.getMonth() - 1,
date.getDayOfMonth(),
18,
0,
0,
);
updateTask(task.id, { due: picked.toISOString() });
}}
/>
}
/>
}
/>
Notes
updateTask(task.id, {
notes: buffer.getText(
buffer.getStartIter(),
buffer.getEndIter(),
false,
),
})
}
/>
}
/>
{task.completedAt ? (
) : null}
);
};
```
`submitTitle` invokes the form's submit handler without passing the native signal's widget as a web event. Blank titles stay invalid and unsaved; accepted titles are trimmed. Resetting only the importance field lets the header star update the switch without replacing an unfinished title.
The calendar is JSX in the menu button's `popover` slot. Its native date is a `GLib.DateTime`; the selected day becomes an ISO string at 6 PM local time. `GLib.DateTime` is a boxed value, so creating it for a property does not create a GObject outside JSX.
The notes editor uses a `GtkTextBuffer` in the text view's `buffer` slot. `onChanged` writes the current text to the store. GTKX avoids rewriting identical buffer text, preserving the native cursor and undo history while that edit returns through the `text` prop.
## Add the header widgets
Create `src/components/task-title.tsx`:
```tsx [src/components/task-title.tsx]
import { AdwWindowTitle } from "@gtkx/jsx/adw";
import { useStore } from "../store/index.js";
export const TaskTitle = ({ id }: { id: string }) => {
const title = useStore((state) => state.tasks.find((task) => task.id === id)?.title);
return ;
};
```
The title reads the committed task value and falls back to “Task” if the task has gone away.
Create `src/components/task-buttons.tsx`:
```tsx [src/components/task-buttons.tsx]
import { GtkButton, GtkToggleButton } from "@gtkx/jsx/gtk";
import { useStore } from "../store/index.js";
export const TaskButtons = ({ id }: { id: string }) => {
const setImportant = useStore((state) => state.setImportant);
const moveToTrash = useStore((state) => state.moveToTrash);
const task = useStore((state) => state.tasks.find((candidate) => candidate.id === id));
if (!task) return null;
return (
<>
setImportant(task.id, self.active)}
/>
moveToTrash(task.id)} />
>
);
};
```
Both controls use the same store actions as the task row. The buttons disappear if their task is removed.
In `src/components/window.tsx`, add these imports:
```diff [src/components/window.tsx]
@@ -0,0 +1,3 @@
+import { TaskButtons } from "./task-buttons.js";
+import { TaskScreen } from "./task-screen.js";
+import { TaskTitle } from "./task-title.js";
```
Add the editor after the `Tasks` screen in `Split.Navigator`:
```diff [src/components/window.tsx]
@@ -62,0 +63,8 @@
+ ({
+ headerTitle: ,
+ headerEnd: ,
+ })}
+ />
```
`headerTitle` replaces the title widget; `headerEnd` holds the task commands. The navigator handles the back button, Escape, and Alt+Left.
Deleting here currently moves the task to Trash while leaving its editor open. [Add Undo and Delete Confirmation](/tutorial/trash-and-toasts) will add undo and confirmation behavior and close that page.
## Run it
1. Open a task. Its editor should show Title, Important, Due, Notes, and Created.
2. Enter a blank title and confirm it remains unsaved. Then enter a padded title, toggle the header star, and press Enter. The switch should follow without replacing the draft, and the saved title should be trimmed.
3. Pick a due date, return to the list, and check its subtitle. Reopen the task and clear the date; the subtitle should disappear.
4. Type notes and use Ctrl+Z. Go back and open another task; its notes and undo history should be independent.
5. Close an editor with the back button, Escape, and Alt+Left on separate visits.
Restart the app and reopen the task to confirm the committed fields were saved.
## Next
Continue to [Add Menus and Shortcuts](/tutorial/actions-menus-shortcuts).
---
---
description: "Connect window actions, menus, shortcuts, and dialogs to the task navigator."
---
# Add Menus and Shortcuts
[Edit Tasks](/tutorial/the-task-editor) added the editor route. Connect the New Task button, menu item, and keyboard shortcut to a shared handler. Add About and Keyboard Shortcuts dialogs alongside it.
## Reach navigation from window commands
The window's actions sit outside `NavigationContainer`, so they need a container ref. Add it in `src/navigation.ts`:
```diff [src/navigation.ts]
@@ -1 +1 @@
-import { createSplitViewNavigator, useNavigationState } from "@gtkx/navigation";
+import { createNavigationContainerRef, createSplitViewNavigator, useNavigationState } from "@gtkx/navigation";
```
```diff [src/navigation.ts]
@@ -10,0 +11,2 @@
+
+export const navigationRef = createNavigationContainerRef();
```
Add these helpers at the end of the same file. They reuse the existing `isSelection` helper and route parameters:
```diff [src/navigation.ts]
@@ -29,0 +30,17 @@
+
+export const currentSelection = (): Selection => {
+ const routes = navigationRef.isReady() ? navigationRef.getRootState()?.routes : undefined;
+ const params = routes?.find((route) => route.name === "Tasks")?.params;
+ return isSelection(params) ? params : ALL_TASKS;
+};
+
+export const openTaskId = (): string | null => {
+ const route = navigationRef.isReady() ? navigationRef.getCurrentRoute() : undefined;
+ return route?.name === "Task" ? route.params.id : null;
+};
+
+export const openTask = (selection: Selection, id: string): void => {
+ if (!navigationRef.isReady()) return;
+ navigationRef.navigate("Tasks", selection);
+ navigationRef.navigate("Task", { id });
+};
```
`currentSelection` returns All Tasks when there is no selected content page. `openTask` first selects the list, then opens its editor, leaving the list underneath the Back button. The ref becomes usable once the container is ready.
In `src/components/window.tsx`, add `navigationRef` to the navigation import and pass it to the container:
```diff [src/components/window.tsx]
@@ -10 +10 @@
-import { ALL_TASKS, Split } from "../navigation.js";
+import { ALL_TASKS, navigationRef, Split } from "../navigation.js";
```
```diff [src/components/window.tsx]
@@ -43 +43 @@
-
+
```
Screens keep using `useNavigation`. The container ref is for this application's handlers outside the navigation tree; the [navigation guide](/guide/navigation) covers the shared API.
## Track the open dialog
Add this type to `src/types.ts`:
```diff [src/types.ts]
@@ -25,0 +26,2 @@
+
+export type DialogKind = "none" | "about" | "shortcuts";
```
In `src/store/ui.ts`, add `DialogKind` to the existing type import, then extend the slice:
```diff [src/store/ui.ts]
@@ -2 +2 @@
-import type { Filter } from "../types.js";
+import type { DialogKind, Filter } from "../types.js";
@@ -5,0 +6,2 @@
+ dialog: DialogKind;
+ showDialog: (dialog: DialogKind) => void;
@@ -17,0 +20,2 @@
+ dialog: "none",
+ showDialog: (dialog) => set({ dialog }),
```
Keep these transient fields out of the store's existing `partialize` function.
## Define the window actions
Create `src/components/window-actions.tsx`:
```tsx [src/components/window-actions.tsx]
import { GSimpleAction } from "@gtkx/jsx/gio";
import { currentSelection, openTask } from "../navigation.js";
import { useStore } from "../store/index.js";
import { addListId } from "../store/selectors.js";
export const WindowActions = () => {
const showDialog = useStore((state) => state.showDialog);
const newTask = (): void => {
const { lists, addTask } = useStore.getState();
const selection = currentSelection();
const id = addTask(addListId(selection, lists), "New Task");
if (id) openTask(selection, id);
};
return (
<>
showDialog("shortcuts")} />
showDialog("about")} />
>
);
};
```
Mounting these elements in the window's `actions` prop exposes `win.new`, `win.shortcuts`, and `win.about`. The same prop on the application exposes `app.*` actions. For the native action model, see [Gio actions](https://docs.gtk.org/gio/class.SimpleAction.html).
## Add the menu and accelerator
Create `src/components/main-menu.tsx`:
```tsx [src/components/main-menu.tsx]
import { GMenu } from "@gtkx/jsx/gio";
import { GtkMenuButton } from "@gtkx/jsx/gtk";
export const MainMenu = () => (
}
/>
);
```
`GMenu.items` describes the menu declaratively. Its action names point to the window actions above; `primary` lets F10 open this menu.
In `src/app.tsx`, add `actionAccels` to the existing application:
```diff [src/app.tsx]
@@ -6 +6,6 @@
-
+ n"] },
+ { detailedActionName: "win.shortcuts", accels: ["question"] },
+ ]}
+ >
```
The menu displays the application's registered accelerator beside New Task. GTK's [accelerator syntax](https://docs.gtk.org/gtk4/func.accelerator_parse.html) is shared by these bindings and the shortcuts below.
Update `src/components/window.tsx`. Import the button and the two new components:
```diff [src/components/window.tsx]
@@ -0,0 +1,3 @@
+import { GtkButton } from "@gtkx/jsx/gtk";
+import { MainMenu } from "./main-menu.js";
+import { WindowActions } from "./window-actions.js";
@@ -30,0 +34 @@
+ actions={}
```
Add `actions={}` to `AdwApplicationWindow`. In the Tasks screen's existing options, replace `headerStart` and add `headerEnd`:
```diff [src/components/window.tsx]
@@ -64 +64,11 @@
- headerStart: ,
+ headerStart: (
+ <>
+
+
+ >
+ ),
+ headerEnd: ,
```
The button's `actionName` reaches the same handler as the menu and Ctrl+N.
## Mount the dialogs {#mounting-dialogs}
Create `src/components/about.tsx`:
```tsx [src/components/about.tsx]
import * as Gtk from "@gtkx/gi/gtk";
import { AdwAboutDialog } from "@gtkx/jsx/adw";
import { applicationId } from "virtual:gtkx-config";
export const About = ({ onClose }: { onClose: () => void }) => {
return (
);
};
```
`applicationId` comes from the generated project configuration, so the dialog and application shell use the same identity. The scaffold's `applicationIcon` configuration makes its icon available during development and in builds; [Package the App](/tutorial/packaging) installs it with the application.
Create `src/components/shortcuts.tsx`:
```tsx [src/components/shortcuts.tsx]
import { AdwShortcutsDialog, AdwShortcutsItem, AdwShortcutsSection } from "@gtkx/jsx/adw";
export const Shortcuts = ({ onClose }: { onClose: () => void }) => (
);
```
The items describe shortcuts; they do not register them. Navigation already provides Back through Escape and Alt+Left. Search and Delete are connected below.
Create `src/components/dialogs.tsx`:
```tsx [src/components/dialogs.tsx]
import { useStore } from "../store/index.js";
import { About } from "./about.js";
import { Shortcuts } from "./shortcuts.js";
export const Dialogs = () => {
const dialog = useStore((state) => state.dialog);
const showDialog = useStore((state) => state.showDialog);
const close = () => showDialog("none");
switch (dialog) {
case "about":
return ;
case "shortcuts":
return ;
case "none":
return null;
}
};
```
Import `Dialogs` in `src/components/window.tsx` and add `` after `NavigationContainer`, inside `AdwApplicationWindow`.
GTKX's dialog components present when mounted and dismiss when unmounted. `onClosed` clears the application state after a native close or Escape. The dialog stays associated with its parent window through the [portal mechanism](/guide/modals-and-portals).
## Add Search and Delete shortcuts
Create `src/components/app-shortcuts.tsx`:
```tsx [src/components/app-shortcuts.tsx]
import * as Gtk from "@gtkx/gi/gtk";
import { GtkShortcut, GtkShortcutController } from "@gtkx/jsx/gtk";
import { openTaskId } from "../navigation.js";
import { useStore } from "../store/index.js";
const shortcut = (accelerator: string, run: () => boolean) => (
);
export const AppShortcuts = () => {
const toggleSearch = (): boolean => {
const { searchMode, setSearchMode } = useStore.getState();
setSearchMode(!searchMode);
return true;
};
const deleteOpenTask = (): boolean => {
const id = openTaskId();
if (id === null) return false;
useStore.getState().moveToTrash(id);
return true;
};
return (
{shortcut("f", toggleSearch)}
{shortcut("Delete", deleteOpenTask)}
>
}
/>
);
};
```
`controllers` attaches the shortcut controller to the window. Its GLOBAL scope lets descendants use the shortcuts; returning `false` leaves an unhandled key available to the focused widget. Delete only acts when a Task route is open.
In `src/components/window.tsx`, import `AppShortcuts` and add `controllers={}` to `AdwApplicationWindow`.
Update the editor button's tooltip in `src/components/task-buttons.tsx`:
```diff [src/components/task-buttons.tsx]
@@ -19 +19 @@
- moveToTrash(task.id)} />
+ moveToTrash(task.id)} />
```
Finish the window wiring:
```diff [src/components/window.tsx]
@@ -0,0 +1,2 @@
+import { AppShortcuts } from "./app-shortcuts.js";
+import { Dialogs } from "./dialogs.js";
@@ -33,0 +36 @@
+ controllers={}
@@ -86,0 +90 @@
+
```
## Run it
- Press Ctrl+N from the list and from an editor. Each new task opens above its list.
- Press F10 on the task list. New Task shows Ctrl+N in the menu.
- Open Keyboard Shortcuts with Ctrl+Shift+/ on a US keyboard, then dismiss it with Escape.
- Press Escape in an editor to return to the list. In a narrow window, Back from the list returns to the sidebar.
- Press Delete with a task open. It moves to Trash; the next chapter closes its editor and offers Undo.
## Next
[Add Undo and Delete Confirmation](/tutorial/trash-and-toasts) adds recoverable deletion and the New List dialog.
---
---
description: "Add Undo, permanent-delete confirmation, and a New List dialog."
---
# Add Undo and Delete Confirmation
[Add Menus and Shortcuts](/tutorial/actions-menus-shortcuts) connected the delete commands. Give them a shared handler that closes an open editor, moves the task to Trash, and offers Undo. Add permanent-delete confirmation and the New List dialog alongside it.
## Add the undo toast
Install the GTKX collection and toast components from `tasks/`:
::: code-group
```bash [npm]
npm install @gtkx/components@1.6.0
```
```bash [pnpm]
pnpm add @gtkx/components@1.6.0
```
:::
In `src/components/window.tsx`, add `AdwToastOverlay` to the Adwaita element import, and add these imports:
```diff [src/components/window.tsx]
@@ -0,0 +1,2 @@
+import { ToastProvider } from "@gtkx/components/adw";
+import { useRef } from "react";
@@ -12 +14 @@
-import { AdwApplicationWindow, AdwBreakpoint, AdwStatusPage } from "@gtkx/jsx/adw";
+import { AdwApplicationWindow, AdwToastOverlay, AdwBreakpoint, AdwStatusPage } from "@gtkx/jsx/adw";
```
Inside `Window`, create the overlay ref:
```diff [src/components/window.tsx]
@@ -31,0 +32 @@
+ const toastOverlayRef = useRef(null);
@@ -37,44 +38,13 @@
- }
- actions={}
- title="Tasks"
- widthRequest={360}
- heightRequest={294}
- onCloseRequest={() => quit()}
- breakpoints={
- setCollapsed(true)}
- onUnapply={() => setCollapsed(false)}
- />
- }
- >
-
- }
- >
-
- ({
- title: selectionTitle(route.params, lists),
- headerTitle: ,
- headerStart: (
- <>
-
-
- >
- ),
- headerEnd: ,
- })}
+
+ }
+ actions={}
+ title="Tasks"
+ widthRequest={360}
+ heightRequest={294}
+ onCloseRequest={() => quit()}
+ breakpoints={
+ setCollapsed(true)}
+ onUnapply={() => setCollapsed(false)}
@@ -82,12 +52,47 @@
- ({
- headerTitle: ,
- headerEnd: ,
- })}
- />
-
-
-
-
+ }
+ >
+
+
+ }
+ >
+
+ ({
+ title: selectionTitle(route.params, lists),
+ headerTitle: ,
+ headerStart: (
+ <>
+
+
+ >
+ ),
+ headerEnd: ,
+ })}
+ />
+ ({
+ headerTitle: ,
+ headerEnd: ,
+ })}
+ />
+
+
+
+
+
+
```
Wrap `AdwApplicationWindow` in ``. Inside the window, wrap the existing `NavigationContainer` in ``. Keep `` after that overlay, inside the window.
The provider shares this overlay with `useToast`, including calls from window actions and shortcuts. See the [components guide](/guide/components) for the toast API.
## Extend the persisted task actions
Add the two transitions to `TasksSlice` in `src/store/tasks.ts`:
```diff [src/store/tasks.ts]
@@ -12,0 +13,2 @@
+ restore: (id: string) => void;
+ deleteForever: (id: string) => void;
```
```diff [src/store/tasks.ts]
@@ -52,0 +53,2 @@
+ restore: (id) => set((state) => ({ tasks: patch(state.tasks, id, { deleted: false }) })),
+ deleteForever: (id) => set((state) => ({ tasks: state.tasks.filter((task) => task.id !== id) })),
```
Permanent deletion leaves gaps in the surviving positions. Keep additions at the end of the stored manual order by changing `addTask` in the same file:
```diff [src/store/tasks.ts]
@@ -38 +38 @@
- position: state.tasks.length,
+ position: (state.tasks.at(-1)?.position ?? -1) + 1,
```
The array retains manual order: deletion removes entries, and new tasks append after its final position. An empty array starts at zero.
## Model the confirmation
Replace the dialog types in `src/types.ts`:
```diff [src/types.ts]
@@ -27 +27,3 @@
-export type DialogKind = "none" | "about" | "shortcuts";
+export type DialogKind = "none" | "about" | "shortcuts" | "new-list";
+
+export type DialogState = { kind: DialogKind } | { kind: "delete-task"; task: Task };
```
Update the type import and dialog fields in `src/store/ui.ts`:
```diff [src/store/ui.ts]
@@ -2 +2 @@
-import type { DialogKind, Filter } from "../types.js";
+import type { DialogKind, DialogState, Filter, Task } from "../types.js";
@@ -6 +6 @@
- dialog: DialogKind;
+ dialog: DialogState;
@@ -7,0 +8 @@
+ askDeleteTask: (task: Task) => void;
@@ -20,2 +21,3 @@
- dialog: "none",
- showDialog: (dialog) => set({ dialog }),
+ dialog: { kind: "none" },
+ showDialog: (kind) => set({ dialog: { kind } }),
+ askDeleteTask: (task) => set({ dialog: { kind: "delete-task", task } }),
```
Add this helper to `src/navigation.ts` so deleting the current task also leaves its editor:
```diff [src/navigation.ts]
@@ -46,0 +47,4 @@
+
+export const closeTaskIfOpen = (id: string): void => {
+ if (openTaskId() === id) navigationRef.goBack();
+};
```
Create `src/components/delete-confirmation.tsx`:
```tsx [src/components/delete-confirmation.tsx]
import * as Adw from "@gtkx/gi/adw";
import { AdwAlertDialog } from "@gtkx/jsx/adw";
import { closeTaskIfOpen } from "../navigation.js";
import { useStore } from "../store/index.js";
import type { Task } from "../types.js";
export const DeleteConfirmation = ({ task }: { task: Task }) => {
const deleteForever = useStore((state) => state.deleteForever);
const showDialog = useStore((state) => state.showDialog);
return (
{
if (id === "delete") {
closeTaskIfOpen(task.id);
deleteForever(task.id);
}
showDialog("none");
}}
/>
);
};
```
Cancel is both the default and close response. Delete uses Adwaita's destructive appearance and removes the task only after confirmation.
## Add the New List dialog
Create `src/components/new-list-dialog.tsx`:
```tsx [src/components/new-list-dialog.tsx]
import * as Adw from "@gtkx/gi/adw";
import * as Gtk from "@gtkx/gi/gtk";
import { AdwAlertDialog } from "@gtkx/jsx/adw";
import { GtkBox, GtkEntry, GtkToggleButton } from "@gtkx/jsx/gtk";
import { useState } from "react";
import { useStore } from "../store/index.js";
import { listDot } from "../styles.js";
const PALETTE = ["#3584e4", "#2ec27e", "#e66100", "#9141ac", "#e01b24", "#f5c211"];
export const NewListDialog = () => {
const addList = useStore((state) => state.addList);
const showDialog = useStore((state) => state.showDialog);
const [name, setName] = useState("");
const [color, setColor] = useState("#3584e4");
const [firstSwatch, setFirstSwatch] = useState(null);
return (
0,
},
]}
onResponse={(id) => {
if (id === "add") addList(name.trim(), color);
showDialog("none");
}}
>
setName(self.text)} />
{PALETTE.map((swatch, index) => (
setColor(swatch)}
>
))}
);
};
```
The Add response is disabled until the name contains non-whitespace text. Its handler trims the accepted name, so `addList` in `src/store/lists.ts` can use it directly:
```diff [src/store/lists.ts]
@@ -13,5 +13,2 @@
- addList: (name, color) => {
- const trimmed = name.trim();
- if (trimmed === "") return;
- set((state) => ({ lists: [...state.lists, { id: crypto.randomUUID(), name: trimmed, color }] }));
- },
+ addList: (name, color) =>
+ set((state) => ({ lists: [...state.lists, { id: crypto.randomUUID(), name, color }] })),
```
## Route every delete through one hook
Replace `src/components/dialogs.tsx` with the shared deletion hook and dialog selection:
```tsx [src/components/dialogs.tsx]
import { useToast } from "@gtkx/components/adw";
import { useStore } from "../store/index.js";
import { About } from "./about.js";
import { DeleteConfirmation } from "./delete-confirmation.js";
import { NewListDialog } from "./new-list-dialog.js";
import { Shortcuts } from "./shortcuts.js";
import { closeTaskIfOpen } from "../navigation.js";
import type { Task } from "../types.js";
export const useRequestDeleteTask = (): ((task: Task) => void) => {
const { show } = useToast();
return (task) => {
const { moveToTrash, restore, askDeleteTask } = useStore.getState();
if (task.deleted) {
askDeleteTask(task);
return;
}
closeTaskIfOpen(task.id);
moveToTrash(task.id);
show({
useMarkup: false,
title: `“${task.title}” moved to Trash`,
buttonLabel: "Undo",
onButtonClicked: () => restore(task.id),
});
};
};
export const Dialogs = () => {
const dialog = useStore((state) => state.dialog);
const showDialog = useStore((state) => state.showDialog);
const close = (): void => showDialog("none");
switch (dialog.kind) {
case "about":
return ;
case "shortcuts":
return ;
case "new-list":
return ;
case "delete-task":
return ;
case "none":
return null;
}
};
```
`useMarkup: false` keeps a task title literal, including ampersands and angle brackets. Undo restores the persisted task; the confirmation body also uses plain text by default.
In `TaskRow` and `TaskButtons`, import `useRequestDeleteTask` from `./dialogs.js`, replace their `moveToTrash` store subscription with `const requestDeleteTask = useRequestDeleteTask()`, and call `requestDeleteTask(task)` from the delete buttons.
In `src/components/app-shortcuts.tsx`, import the same hook and call it inside `AppShortcuts`. Replace `deleteOpenTask` with a handler that reads the current task:
```diff [src/components/app-shortcuts.tsx]
@@ -0,0 +1 @@
+import { useRequestDeleteTask } from "./dialogs.js";
@@ -13,0 +15 @@
+ const requestDeleteTask = useRequestDeleteTask();
@@ -21,3 +23,3 @@
- const id = openTaskId();
- if (id === null) return false;
- useStore.getState().moveToTrash(id);
+ const task = useStore.getState().tasks.find((candidate) => candidate.id === openTaskId());
+ if (!task) return false;
+ requestDeleteTask(task);
```
In `Window`, read `const showDialog = useStore((state) => state.showDialog)` and update the Lists screen header:
```diff [src/components/window.tsx]
@@ -31,0 +32 @@
+ const showDialog = useStore((state) => state.showDialog);
@@ -64 +65,14 @@
-
+ showDialog("new-list")}
+ />
+ ),
+ }}
+ />
```
Connect the shared delete handler in `src/components/task-row.tsx`:
```diff [src/components/task-row.tsx]
@@ -0,0 +1 @@
+import { useRequestDeleteTask } from "./dialogs.js";
@@ -14 +15 @@
- const moveToTrash = useStore((state) => state.moveToTrash);
+ const requestDeleteTask = useRequestDeleteTask();
@@ -48 +49 @@
- onClicked={() => moveToTrash(task.id)}
+ onClicked={() => requestDeleteTask(task)}
```
Connect the shared delete handler in `src/components/task-buttons.tsx`:
```diff [src/components/task-buttons.tsx]
@@ -0,0 +1 @@
+import { useRequestDeleteTask } from "./dialogs.js";
@@ -6 +7 @@
- const moveToTrash = useStore((state) => state.moveToTrash);
+ const requestDeleteTask = useRequestDeleteTask();
@@ -19 +20 @@
- moveToTrash(task.id)} />
+ requestDeleteTask(task)} />
```
## Run it
Delete a task using its row button, editor button, and the Delete key on separate attempts. Each action offers Undo and closes the editor when needed. Try a title containing `&` or ``: the toast preserves the text.
Open Trash and delete again. Cancel and Escape preserve the task; Delete removes it permanently. Add another task afterward and check that it appears last in manual order.
Open New List. Add stays disabled for an empty or whitespace-only name. Enter a name, choose a color, and press Return; the saved list appears in the sidebar.
## Next
[Add Preferences](/tutorial/preferences-and-theming) stores application choices in GSettings.
---
---
description: "Store preferences in GSettings, add a preferences dialog, sort the list, and follow the system theme."
---
# Add Preferences
[Add Undo and Delete Confirmation](/tutorial/trash-and-toasts) finished the app's dialog flow. This chapter keeps user choices in GSettings while task and list data stays in the JSON store from [Save Tasks](/tutorial/saving-to-disk).
## Add the settings schema
GTKX imports, compiles, and generates types for the GSettings schemas used by the application. Create `data/com.gtkx.tutorial.gschema.xml`:
```xml [data/com.gtkx.tutorial.gschema.xml]
'manual'Sort orderHow tasks are ordered in the list'default'Color schemeFollow the system theme or force light or dark30Reminder lead timeMinutes before a due time to show a reminder900Window widthLast saved window width in pixels600Window heightLast saved window height in pixels
```
The schema uses the application ID established in [Create a Window](/tutorial/your-first-window). Its enum, choices, ranges, and defaults are the native settings contract; the [GSettings schema reference](https://docs.gtk.org/gio/class.Settings.html) covers the XML format and storage model.
Import the file wherever GTKX needs a schema:
```ts
import schema from "../../data/com.gtkx.tutorial.gschema.xml";
```
The import returns a generated schema module. `useSetting` and `useBindSetting` use it to check key names and value types.
## Bind the window size
In `src/components/window.tsx`, keep an application-window ref and bind its default size:
```diff [src/components/window.tsx]
@@ -0,0 +1,4 @@
+import * as Adw from "@gtkx/gi/adw";
+import { quit, useBindSetting, useSetting } from "@gtkx/react";
+import { useEffect, useRef } from "react";
+import schema from "../../data/com.gtkx.tutorial.gschema.xml";
@@ -2 +5,0 @@
-import { useRef } from "react";
@@ -13 +15,0 @@
-import * as Adw from "@gtkx/gi/adw";
@@ -16 +17,0 @@
-import { quit } from "@gtkx/react";
@@ -31,0 +33,7 @@
+ const [colorScheme] = useSetting(schema, "color-scheme");
+ const [reminderMinutes] = useSetting(schema, "reminder-minutes");
+ const windowRef = useRef(null);
+
+ useBindSetting({ schema, key: "window-width", object: windowRef, property: "defaultWidth" });
+ useBindSetting({ schema, key: "window-height", object: windowRef, property: "defaultHeight" });
+
@@ -40,0 +49 @@
+ ref={windowRef}
```
Keep `ref={windowRef}` on `AdwApplicationWindow`. The bindings restore the values when the widget mounts and write changes back without a separate save path.
## Keep application choices together
The native schema owns storage. A small application module owns the labels and conversions used by the UI, sorter, and theme manager. Create `src/settings.ts`:
```ts [src/settings.ts]
import * as Adw from "@gtkx/gi/adw";
const COLOR_SCHEMES = {
default: { label: "Follow system", value: Adw.ColorScheme.DEFAULT },
light: { label: "Light", value: Adw.ColorScheme.FORCE_LIGHT },
dark: { label: "Dark", value: Adw.ColorScheme.FORCE_DARK },
} as const;
const SORT_ORDERS = {
manual: "Manual",
"due-date": "Due date",
title: "Title",
created: "Date created",
} as const;
export type ColorScheme = keyof typeof COLOR_SCHEMES;
export type SortOrder = keyof typeof SORT_ORDERS;
const sortOrderIds = Object.keys(SORT_ORDERS) as SortOrder[];
export const colorSchemeItems = (): { id: string; value: string }[] =>
Object.entries(COLOR_SCHEMES).map(([id, choice]) => ({ id, value: choice.label }));
export const sortOrderItems = (): { id: string; value: string }[] =>
sortOrderIds.map((id) => ({ id, value: SORT_ORDERS[id] }));
export const colorSchemeValue = (id: string): Adw.ColorScheme => COLOR_SCHEMES[id as ColorScheme].value;
export const sortOrderFromSetting = (value: number): SortOrder => sortOrderIds[value];
export const sortOrderToSetting = (order: SortOrder): number => sortOrderIds.indexOf(order);
```
All TypeScript consumers now derive their choice names from these tables. Only this module translates the schema's integer sort value to the readable ID used by the app.
Create `src/hooks/use-sort-order.ts`:
```ts [src/hooks/use-sort-order.ts]
import { useSetting } from "@gtkx/react";
import schema from "../../data/com.gtkx.tutorial.gschema.xml";
import { sortOrderFromSetting, sortOrderToSetting, type SortOrder } from "../settings.js";
export const useSortOrder = (): [SortOrder, (order: SortOrder) => void] => {
const [value, setValue] = useSetting(schema, "sort-order");
return [sortOrderFromSetting(value), (order) => setValue(sortOrderToSetting(order))];
};
```
## Sort visible tasks
Import `SortOrder` from `settings.ts` in `src/store/selectors.ts`, then add the comparator:
```diff [src/store/selectors.ts]
@@ -0,0 +1 @@
+import type { SortOrder } from "../settings.js";
@@ -48 +49,20 @@
-export type VisibleOptions = { query: string; filter: Filter };
+const byOrder =
+ (order: SortOrder) =>
+ (a: Task, b: Task): number => {
+ switch (order) {
+ case "due-date": {
+ if (a.due === b.due) return a.position - b.position;
+ if (!a.due) return 1;
+ if (!b.due) return -1;
+ return a.due < b.due ? -1 : 1;
+ }
+ case "title":
+ return a.title.localeCompare(b.title);
+ case "created":
+ return a.createdAt.localeCompare(b.createdAt);
+ default:
+ return a.position - b.position;
+ }
+ };
+
+export type VisibleOptions = { query: string; filter: Filter; sortOrder: SortOrder };
@@ -58 +78 @@
- .sort((a, b) => a.position - b.position);
+ .sort(byOrder(options.sortOrder));
```
The existing filter returns a fresh array before `sort` changes its order, so the store array remains untouched. In `src/components/task-list.tsx`, read the setting and pass it to the selector:
```diff [src/components/task-list.tsx]
@@ -0,0 +1 @@
+import { useSortOrder } from "../hooks/use-sort-order.js";
@@ -10,0 +12 @@
+ const [sortOrder] = useSortOrder();
@@ -20 +22 @@
- const visible = visibleTasks(tasks, selection, { query: searchQuery, filter });
+ const visible = visibleTasks(tasks, selection, { query: searchQuery, filter, sortOrder });
```
## Open Preferences
Add `"preferences"` to `DialogKind` in `src/types.ts`. Then connect the existing dialog state to a window action in `src/components/window-actions.tsx`:
```diff [src/components/window-actions.tsx]
@@ -18,0 +19 @@
+ showDialog("preferences")} />
```
Register the accelerator in `src/app.tsx`:
```diff [src/app.tsx]
@@ -8,0 +9 @@
+ { detailedActionName: "win.preferences", accels: ["comma"] },
```
Add `{ label: "Preferences", action: "win.preferences" }` beside Keyboard Shortcuts in `src/components/main-menu.tsx`, and document the same accelerator in `src/components/shortcuts.tsx`:
```diff [src/components/shortcuts.tsx]
@@ -5,0 +6 @@
+
```
Create `src/components/preferences.tsx`:
```tsx [src/components/preferences.tsx]
import { ComboRow } from "@gtkx/components/adw";
import { AdwPreferencesDialog, AdwPreferencesGroup, AdwPreferencesPage, AdwSpinRow } from "@gtkx/jsx/adw";
import { GtkAdjustment } from "@gtkx/jsx/gtk";
import { useSetting } from "@gtkx/react";
import schema from "../../data/com.gtkx.tutorial.gschema.xml";
import { useSortOrder } from "../hooks/use-sort-order.js";
import { colorSchemeItems, sortOrderItems, type SortOrder } from "../settings.js";
export const Preferences = ({ onClose }: { onClose: () => void }) => {
const [scheme, setScheme] = useSetting(schema, "color-scheme");
const [sortOrder, setSortOrder] = useSortOrder();
const [reminderMinutes, setReminderMinutes] = useSetting(schema, "reminder-minutes");
return (
setScheme(id as string)}
/>
setSortOrder(id as SortOrder)}
/>
}
onNotifyValue={(value) => setReminderMinutes(value as number)}
/>
);
};
```
`ComboRow` is the GTKX collection component for an Adwaita preferences row. The tables from `settings.ts` feed both rows, and the adjustment gives the native spin row its current reminder value and range.
Mount the new dialog from `src/components/dialogs.tsx`:
```diff [src/components/dialogs.tsx]
@@ -0,0 +1 @@
+import { Preferences } from "./preferences.js";
@@ -35,0 +37,2 @@
+ case "preferences":
+ return ;
```
## Apply the color scheme
Create `src/theme.ts`:
```ts [src/theme.ts]
import * as Adw from "@gtkx/gi/adw";
import { colorSchemeValue } from "./settings.js";
export const applyColorScheme = (value: string): void => {
const manager = Adw.StyleManager.getDefault();
manager.setColorScheme(colorSchemeValue(value));
};
```
Apply it when the setting changes in `src/components/window.tsx`:
```diff [src/components/window.tsx]
@@ -0,0 +1 @@
+import { applyColorScheme } from "../theme.js";
@@ -44,0 +46,4 @@
+
+ useEffect(() => {
+ applyColorScheme(colorScheme);
+ }, [colorScheme]);
```
The `default` choice follows the desktop theme; `light` and `dark` override it for the app.
Include Preferences in the dialog type:
```diff [src/types.ts]
@@ -27 +27 @@
-export type DialogKind = "none" | "about" | "shortcuts" | "new-list";
+export type DialogKind = "none" | "about" | "shortcuts" | "new-list" | "preferences";
```
Add the menu entry:
```diff [src/components/main-menu.tsx]
@@ -12,0 +13 @@
+ { section: [{ label: "Preferences", action: "win.preferences" }] },
```
## Run it
Press Ctrl+,. Change the theme and sort order, then close the dialog. Both changes take effect immediately. Resize the window, quit the process, and start it again. The window size and each preference return from GSettings.
Set Reminder lead time to zero and leave it there. [Send Reminders](/tutorial/reminders) will make that mean “notify when due.”
## Next
[Reorder Tasks](/tutorial/drag-to-reorder) adds pointer and keyboard reordering when Manual is selected.
---
---
description: "Change the persisted manual order with drag and drop or keyboard shortcuts."
---
# Reorder Tasks
[Add Preferences](/tutorial/preferences-and-theming) added Manual sorting. This chapter lets the user change that order with drag and drop or Alt+Up/Alt+Down.
## Add the reorder action
Each task already has a `position`. Add an action to `src/store/tasks.ts` that moves a task to another task's index and updates the positions:
```diff [src/store/tasks.ts]
@@ -14,0 +15 @@
+ reorder: (draggedId: string, targetId: string) => void;
```
```diff [src/store/tasks.ts]
@@ -55,0 +56,8 @@
+ reorder: (draggedId, targetId) =>
+ set((state) => {
+ const tasks = [...state.tasks];
+ const from = tasks.findIndex((task) => task.id === draggedId);
+ const to = tasks.findIndex((task) => task.id === targetId);
+ tasks.splice(to, 0, ...tasks.splice(from, 1));
+ return { tasks: tasks.map((task, index) => ({ ...task, position: index })) };
+ }),
```
Callers validate the IDs at their input boundary, so the action can use them directly. The store's existing persistence writes the new positions to disk.
## Enable reordering in manual views {#limit-reordering-to-the-complete-manual-list}
Reordering changes the global manual order, including when you move tasks within a list, Today, or Important. Disable it for derived sorts, search results, Open/Done filters, and Trash so those views keep their displayed order.
Add the shared decision to `src/store/selectors.ts`:
```diff [src/store/selectors.ts]
@@ -118,0 +119,11 @@
+
+export const isReorderable = (
+ selection: Selection,
+ query: string,
+ filter: Filter,
+ sortOrder: SortOrder,
+): boolean =>
+ sortOrder === "manual" &&
+ query === "" &&
+ filter === "all" &&
+ !(selection.kind === "smart" && selection.view === "trash");
```
Compute it once in `src/components/task-list.tsx`, then give each row its neighbors:
```diff [src/components/task-list.tsx]
@@ -8 +8 @@
-import { addListId, emptyState, visibleTasks } from "../store/selectors.js";
+import { addListId, emptyState, isReorderable, visibleTasks } from "../store/selectors.js";
@@ -21,0 +22 @@
+ const canReorder = isReorderable(selection, searchQuery, filter, sortOrder);
@@ -49,2 +50,8 @@
- {visible.map((task) => (
-
+ {visible.map((task, index) => (
+
```
The neighboring IDs let keyboard and pointer interactions use the same reorder action.
## Add the row controllers
GTKX attaches generated controller elements through a widget's `controllers` prop. Drag and drop uses GTK4's drag source and drop target; keyboard reordering uses a key controller. The [GTK4 drag-and-drop overview](https://docs.gtk.org/gtk4/drag-and-drop.html) covers the native interaction model.
Update the imports and props in `src/components/task-row.tsx`:
```tsx [src/components/task-row.tsx]
import * as Gdk from "@gtkx/gi/gdk";
import { markupEscapeText } from "@gtkx/gi/glib";
import * as GObject from "@gtkx/gi/gobject";
import * as Gtk from "@gtkx/gi/gtk";
import { AdwActionRow } from "@gtkx/jsx/adw";
import {
GtkButton,
GtkCheckButton,
GtkDragSource,
GtkDropTarget,
GtkEventControllerKey,
GtkToggleButton,
} from "@gtkx/jsx/gtk";
import { useNavigation } from "@gtkx/navigation";
import { formatDue } from "../format.js";
import { useStore } from "../store/index.js";
import type { Task } from "../types.js";
import { useRequestDeleteTask } from "./dialogs.js";
type TaskRowProps = {
task: Task;
canReorder: boolean;
previousId?: string;
nextId?: string;
};
export const TaskRow = ({ task, canReorder, previousId, nextId }: TaskRowProps) => {
const requestDeleteTask = useRequestDeleteTask();
const navigation = useNavigation();
const setDone = useStore((state) => state.setDone);
const setImportant = useStore((state) => state.setImportant);
const reorder = useStore((state) => state.reorder);
const escapedTitle = markupEscapeText(task.title, -1);
const title = task.done ? `${escapedTitle}` : escapedTitle;
const handleReorderKey = (keyval: number, state: Gdk.ModifierType): boolean => {
if ((state & Gdk.ModifierType.ALT_MASK) === 0) return Gdk.EVENT_PROPAGATE;
if (keyval !== Gdk.KEY_Up && keyval !== Gdk.KEY_Down) return Gdk.EVENT_PROPAGATE;
const targetId = keyval === Gdk.KEY_Up ? previousId : nextId;
if (targetId === undefined) return Gdk.EVENT_PROPAGATE;
reorder(task.id, targetId);
return Gdk.EVENT_STOP;
};
return (
navigation.navigate("Task", { id: task.id })}
prefix={
setDone(task.id, self.active)}
/>
}
suffix={
<>
setImportant(task.id, self.active)}
/>
requestDeleteTask(task)}
/>
>
}
controllers={
canReorder ? (
<>
{
const row = self.getWidget() as Gtk.Widget;
self.setIcon(Gtk.WidgetPaintable.new(row), Math.round(x), Math.round(y));
return Gdk.ContentProvider.newForValue(task.id);
}}
/>
{
const draggedId = value.getString();
if (
draggedId === null ||
!useStore.getState().tasks.some((candidate) => candidate.id === draggedId)
)
return false;
reorder(draggedId, task.id);
return true;
}}
/>
handleReorderKey(keyval, state)}
/>
>
) : undefined
}
/>
);
};
```
`onPrepare` carries the task ID and uses the row as the drag icon. A `TYPE_STRING` payload arrives through GTK's external input boundary as a [GObject.Value](https://docs.gtk.org/gobject/struct.Value.html), so the drop handler verifies that its string names a task before sending both IDs to the store. The key controller sends the current row and its previous or next neighbor to the same action.
When reordering is unavailable, the row has none of these controllers and exposes no keyboard-shortcut metadata.
## Run it
Choose Manual sorting and the All filter, clear the search box, and focus a task. Press Alt+Up or Alt+Down; the row moves one position. Dragging it onto another row changes the same persisted order.
Switch to Title, search for a task, select Open or Done, or open Trash. Pointer dragging and the reorder keys are disabled in each of those views. Return to Manual with All selected and an empty search to reorder again.
## Next
[Send Reminders](/tutorial/reminders) sends a notification when a task reaches its reminder window.
---
---
description: "Send one desktop reminder for each due date, with actions that survive a cold start."
---
# Send Reminders
[Reorder Tasks](/tutorial/drag-to-reorder) completed task-list interaction. This chapter sends a desktop notification when a task enters its reminder window and keeps notification actions working when they launch the app.
Reminders are checked while the app is running. Closing Tasks stops the timer; installing the app allows actions on an already-sent notification to reopen it, but does not schedule reminders in the background.
## Remember which due date was notified
The reminder marker belongs to the task because tasks already persist. Add it to `Task` in `src/types.ts`:
```diff [src/types.ts]
@@ -12,0 +13 @@
+ lastNotifiedDue: string | null;
```
Set it to `null` in both the seed helper in `src/store/seed.ts` and the new task created in `src/store/tasks.ts`:
```diff [src/store/seed.ts]
@@ -25,0 +26 @@
+ lastNotifiedDue: null,
```
Add an action that records the exact due value that produced a notification:
```diff [src/store/tasks.ts]
@@ -15,0 +16 @@
+ markNotified: (id: string, due: string) => void;
```
```diff [src/store/tasks.ts]
@@ -64,0 +65 @@
+ markNotified: (id, due) => set((state) => ({ tasks: patch(state.tasks, id, { lastNotifiedDue: due }) })),
```
A restart now preserves the marker. Changing the task's due date changes the value being compared, so the new due date can produce its own reminder.
## Sweep for due tasks
Create `src/hooks/use-reminders.ts`:
```ts [src/hooks/use-reminders.ts]
import { useEffect } from "react";
import type { Task } from "../types.js";
const SWEEP_INTERVAL = 60_000;
export const useReminders = (
tasks: Task[],
reminderMinutes: number,
sendReminder: (task: Task, due: string) => void,
): void => {
useEffect(() => {
let previousSweep = Date.now() - SWEEP_INTERVAL;
const sweep = (): void => {
const nowMs = Date.now();
const leadMs = reminderMinutes * SWEEP_INTERVAL;
for (const task of tasks) {
const due = task.due;
if (task.done || task.deleted || due === null || task.lastNotifiedDue === due) continue;
const dueMs = new Date(due).getTime();
const remaining = dueMs - nowMs;
const reminderAt = dueMs - leadMs;
const isReminderReached = reminderAt > previousSweep && reminderAt <= nowMs;
if ((remaining > 0 && remaining <= leadMs) || isReminderReached) sendReminder(task, due);
}
previousSweep = nowMs;
};
sweep();
const handle = setInterval(sweep, SWEEP_INTERVAL);
return () => clearInterval(handle);
}, [tasks, reminderMinutes, sendReminder]);
};
```
The first sweep runs when the hook mounts and sends upcoming tasks already inside the configured lead. `previousSweep` records the last point checked, so a delayed interval still catches a reminder threshold crossed since then, including a nonzero lead. On mount, that cursor starts one minute earlier. Completed tasks, tasks in Trash, and due values already recorded are skipped.
## Build the notification
Create `src/notifications.ts`:
```ts [src/notifications.ts]
import * as Gio from "@gtkx/gi/gio";
import * as GLib from "@gtkx/gi/glib";
import { formatDateTime } from "./format.js";
import type { Task } from "./types.js";
export const buildReminder = (task: Task, due: string): Gio.Notification => {
const notification = Gio.Notification.new(task.title);
notification.setBody(`Due ${formatDateTime(due)}`);
notification.setPriority(Gio.NotificationPriority.HIGH);
notification.addButtonWithTarget("Mark Complete", "app.complete-task", GLib.Variant.newString(task.id));
notification.setDefaultActionAndTarget("app.open-task", GLib.Variant.newString(task.id));
return notification;
};
```
In GTKX 1.6, create the notification with `Gio.Notification.new(title)` because the generated JSX does not expose that constructor. The rest of the app creates GObjects through JSX. The [Gio notification reference](https://docs.gtk.org/gio/class.Notification.html) covers notification fields and application actions.
## Send and record together
Wire the hook into `src/components/window.tsx`:
```diff [src/components/window.tsx]
@@ -0,0 +1,6 @@
+import { quit, useApplication, useBindSetting, useSetting } from "@gtkx/react";
+import { useCallback, useEffect, useRef } from "react";
+import schema from "../../data/com.gtkx.tutorial.gschema.xml";
+import { useReminders } from "../hooks/use-reminders.js";
+import { buildReminder } from "../notifications.js";
+import type { Task } from "../types.js";
@@ -3,3 +8,0 @@
-import { quit, useBindSetting, useSetting } from "@gtkx/react";
-import { useEffect, useRef } from "react";
-import schema from "../../data/com.gtkx.tutorial.gschema.xml";
@@ -35 +37,0 @@
- const [reminderMinutes] = useSetting(schema, "reminder-minutes");
@@ -49,0 +52,15 @@
+
+ const application = useApplication();
+ const tasks = useStore((state) => state.tasks);
+ const markNotified = useStore((state) => state.markNotified);
+ const [reminderMinutes] = useSetting(schema, "reminder-minutes");
+
+ const sendReminder = useCallback(
+ (task: Task, due: string) => {
+ application.sendNotification(task.id, buildReminder(task, due));
+ markNotified(task.id, due);
+ },
+ [application, markNotified],
+ );
+
+ useReminders(tasks, reminderMinutes, sendReminder);
```
The task ID is also the shell notification ID, so sending another notification for that task replaces the existing one. Recording the due value immediately after sending makes the store and desktop delivery share one path.
## Add application actions
Notification interactions target application actions because they may run before a window exists. GTKX renders them as children of `AdwApplication`; the [Gio application reference](https://docs.gtk.org/gio/class.Application.html) covers the upstream action, activation, and session-bus lifecycle. Add them to the `actions` prop in `src/app.tsx`:
```tsx [src/app.tsx]
import type * as Adw from "@gtkx/gi/adw";
import { useState } from "react";
import * as GLib from "@gtkx/gi/glib";
import { GSimpleAction } from "@gtkx/jsx/gio";
import { ALL_TASKS, openTask } from "./navigation.js";
import { useStore } from "./store/index.js";
import { AdwApplication } from "@gtkx/jsx/adw";
import { Window } from "./components/window.js";
export const App = () => {
const [application, setApplication] = useState(null);
return (
application?.getActiveWindow()?.present()}
actionAccels={[
{ detailedActionName: "win.new", accels: ["n"] },
{ detailedActionName: "win.preferences", accels: ["comma"] },
{ detailedActionName: "win.shortcuts", accels: ["question"] },
]}
actions={
<>
{
useStore.getState().setDone((parameter as GLib.Variant).getString()[0], true);
}}
/>
{
openTask(ALL_TASKS, (parameter as GLib.Variant).getString()[0]);
application?.activate();
}}
/>
>
}
>
);
};
```
The `open-task` handler activates the application after queuing navigation, so a service launch mounts its window. `onActivate` presents a window that is already open.
These actions match the names and string targets created in `buildReminder`. They use the store and navigation ref because a notification activation does not originate inside a screen.
## Queue cold-start navigation
An `open-task` action can arrive before `NavigationContainer` mounts. Keep the latest request until the container reports that it is ready. Update `src/navigation.ts`:
```diff [src/navigation.ts]
@@ -41,0 +42,2 @@
+let pendingTask: { selection: Selection; id: string } | null = null;
+
@@ -43 +45,4 @@
- if (!navigationRef.isReady()) return;
+ if (!navigationRef.isReady()) {
+ pendingTask = { selection, id };
+ return;
+ }
@@ -45,0 +51,7 @@
+};
+
+export const openPendingTask = (): void => {
+ if (pendingTask === null) return;
+ const { selection, id } = pendingTask;
+ pendingTask = null;
+ openTask(selection, id);
```
Import `openPendingTask` in `src/components/window.tsx` and connect it to the container:
```diff [src/components/window.tsx]
@@ -22 +22 @@
-import { ALL_TASKS, navigationRef, Split } from "../navigation.js";
+import { ALL_TASKS, navigationRef, openPendingTask, Split } from "../navigation.js";
@@ -87 +87 @@
-
+
```
A running window opens the task immediately. A cold start stores the request, mounts the normal application tree, and opens it from `onReady`.
Desktop delivery also depends on the installed application identity and desktop entry. [Package the App](/tutorial/packaging) adds that metadata; the development process can exercise the actions directly but does not represent an installed notification service.
Initialize the marker for new tasks:
```diff [src/store/tasks.ts]
@@ -42,0 +43 @@
+ lastNotifiedDue: null,
```
## Run it
The task editor currently assigns a selected date a due time of 18:00. Choose today before 18:00, or tomorrow, then set Reminder lead time wide enough to include that time. Within a minute, the notification appears. Its body opens the task; Mark Complete updates it through the application action.
Set the lead to zero to notify on the first sweep at or just after 18:00. Restarting the app does not resend a reminder for the same due value. Change the due date and the task becomes eligible again.
For the action path during development, replace `` with a real task ID:
```bash
gapplication action com.gtkx.tutorial complete-task "''"
```
The installed cold-start path becomes available after the packaging chapter installs the desktop entry.
## You built the application
Tasks now covers native Adwaita layout, GTKX JSX, navigation, forms, persistence, settings, input controllers, and desktop actions. Use the [generated element reference](/guide/configuration-and-codegen#generating-element-reference-docs) for the exact widgets and libraries configured in a GTKX project. Follow the linked upstream documentation when a feature belongs to React, GTK, or GLib.
## Next
[Test the App](/tutorial/testing) drives the finished application through its native accessibility tree.
---
---
description: "Test Tasks through real native widgets in an isolated headless session."
---
# Test the App
Extend the entry-row tests from [Add Tasks](/tutorial/the-task-store#test-the-entry-row) to cover the completed app. Use `@gtkx/testing` to render the app and interact with its Adwaita widgets in a headless session. These are integration tests: they drive widgets directly from TypeScript.
## Isolate the application data
Keep the Vitest configuration from Save Tasks. It selects English and loads the isolated-data setup file:
```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"],
bail: 1,
env: {
LANG: "C.UTF-8",
LANGUAGE: "en",
LC_ALL: "C.UTF-8",
},
},
});
```
Replace `tests/setup.ts` to reset the lists and UI state as well as tasks:
```ts [tests/setup.ts]
import { mkdtempSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { afterAll, beforeEach } from "vitest";
import { applicationId } from "virtual:gtkx-config";
const dataHome = mkdtempSync(join(tmpdir(), "gtkx-tutorial-"));
process.env.XDG_DATA_HOME = dataHome;
const { useStore } = await import("../src/store/index.js");
const { seedLists, seedTasks } = await import("../src/store/seed.js");
beforeEach(() => {
rmSync(join(dataHome, applicationId), { recursive: true, force: true });
useStore.setState({
tasks: seedTasks,
lists: seedLists,
collapsed: false,
filter: "all",
searchMode: false,
searchQuery: "",
dialog: { kind: "none" },
});
});
afterAll(() => {
rmSync(dataHome, { recursive: true, force: true });
});
```
Set the data directory before importing the store: its storage backend reads that path during initialization. Each test resets the app's data; mounting a new `App` supplies a fresh navigation container. GTKX cleans up rendered trees between tests. The explicit locale keeps queries consistent when the app gains translations later.
## Drive the widgets
Replace `tests/tasks.test.tsx` with these app-level checks. State reset now lives in `tests/setup.ts`:
```tsx [tests/tasks.test.tsx]
import * as Gtk from "@gtkx/gi/gtk";
import { rootElement } from "@gtkx/react";
import { render, screen, userEvent } from "@gtkx/testing";
import { describe, expect, it } from "vitest";
import { App } from "../src/app.js";
describe("Tasks", () => {
it("adds a task through the entry row", async () => {
await render(, { container: rootElement });
const entry = await screen.findByRole(Gtk.AccessibleRole.TEXT_BOX);
await userEvent.type(entry, "Book flights");
await userEvent.keyboard(entry, "{Enter}");
expect(await screen.findByRole(Gtk.AccessibleRole.LIST_ITEM, { name: "Book flights" })).toBeDefined();
});
it("keeps an unnamed list from being submitted", async () => {
await render(, { container: rootElement });
await userEvent.click(await screen.findByRole(Gtk.AccessibleRole.BUTTON, { name: "New List" }));
const name = await screen.findByPlaceholderText("List name");
await userEvent.type(name, " ");
expect(screen.getByRole(Gtk.AccessibleRole.BUTTON, { name: "Add" })).toBeDisabled();
});
it("rejects dragging while the task list is filtered", async () => {
await render(, { container: rootElement });
await userEvent.click(await screen.findByText("Open"));
const source = await screen.findByRole(Gtk.AccessibleRole.LIST_ITEM, { name: /Water the plants/ });
const target = await screen.findByRole(Gtk.AccessibleRole.LIST_ITEM, { name: /Welcome to Tasks/ });
await expect(userEvent.dragAndDrop(source, target, "t2")).rejects.toThrow();
});
});
```
`App` returns an `AdwApplication`, so mount it at `rootElement` rather than inside the default harness window. Await rendering and interactions so assertions observe the resulting GTK state.
Queries use `Gtk.AccessibleRole` and the widget's accessible name. `findByRole` waits for a widget; `queryByRole` returns `null` when it is absent. Keyboard input takes its target widget as the first argument.
These cases cover an ordinary interaction, a blank input, and an unavailable drag operation. The drag payload is the task ID supplied by the app's `GtkDragSource`.
## Check the complete workflows
Create `tests/workflows.test.tsx` for persistence, navigation, editing, deletion, and ordering. These checks use the tutorial's three starter tasks and drive the same widgets a user operates. The cases cover literal markup characters, repeated clicks, empty forms, and deletion after reordering.
Complete workflow tests
```tsx [tests/workflows.test.tsx]
import * as Adw from "@gtkx/gi/adw";
import { getUserDataDir } from "@gtkx/gi/glib";
import * as Gtk from "@gtkx/gi/gtk";
import { rootElement } from "@gtkx/react";
import { render, screen, userEvent, waitFor, within } from "@gtkx/testing";
import { readFileSync } from "node:fs";
import { join } from "node:path";
import { applicationId } from "virtual:gtkx-config";
import { describe, expect, it } from "vitest";
import { App } from "../src/app.js";
const openWaterThePlants = async (): Promise => {
const row = await screen.findByRole(Gtk.AccessibleRole.LIST_ITEM, { name: /Water the plants/ });
await userEvent.click(row);
await screen.findByText("Notes");
};
const findTitleEntry = (): Promise =>
screen.findByRole(Gtk.AccessibleRole.LIST_ITEM, { name: /^Title/, as: Adw.EntryRow });
const importantSwitch = (isChecked: boolean): Gtk.Switch =>
screen.getByRole(Gtk.AccessibleRole.SWITCH, { checked: isChecked, as: Gtk.Switch });
describe("Tasks", () => {
it("persists text entered through a native row", async () => {
await render(, { container: rootElement });
const entry = await screen.findByRole(Gtk.AccessibleRole.TEXT_BOX);
await userEvent.type(entry, "Buy milk & café");
await userEvent.keyboard(entry, "{Enter}");
expect(await screen.findByRole(Gtk.AccessibleRole.LIST_ITEM, { name: "Buy milk & café" })).toBeDefined();
const file = join(getUserDataDir(), applicationId, "tasks.json");
const saved: unknown = JSON.parse(readFileSync(file, "utf8"));
expect(saved).toHaveProperty("state.tasks", expect.arrayContaining([
expect.objectContaining({ title: "Buy milk & café" }),
]));
});
it.each(["missing", "missing", "missing & < café"])("shows the literal search query %s", async (query) => {
await render(, { container: rootElement });
await userEvent.click(await screen.findByRole(Gtk.AccessibleRole.BUTTON, { name: "Search (Ctrl+F)" }));
const search = await screen.findByPlaceholderText("Search tasks…");
await userEvent.type(search, query);
const message = await screen.findByText(/No tasks match/, { as: Gtk.Label });
expect(message.getText()).toBe(`No tasks match “${query}”`);
});
it.each(["Errands & café", "Travel"])("creates a list with the literal name %s", async (title) => {
await render(, { container: rootElement });
await userEvent.click(await screen.findByRole(Gtk.AccessibleRole.BUTTON, { name: "New List" }));
const name = await screen.findByPlaceholderText("List name");
await userEvent.type(name, title);
await userEvent.click(await screen.findByRole(Gtk.AccessibleRole.BUTTON, { name: "Add" }));
const row = await screen.findByRole(Gtk.AccessibleRole.LIST_ITEM, { name: title });
expect(row).toHaveAccessibleName(title);
await userEvent.click(row);
expect(screen.queryByRole(Gtk.AccessibleRole.LIST_ITEM, { name: /Water the plants/ })).toBeNull();
});
it("marks a task complete", async () => {
await render(, { container: rootElement });
const [checkbox] = await screen.findAllByRole(Gtk.AccessibleRole.CHECKBOX);
await userEvent.click(checkbox);
expect(checkbox).toBeChecked();
});
it("opens the editor when a row is activated", async () => {
await render(, { container: rootElement });
await openWaterThePlants();
expect(await screen.findByText("Notes")).toHaveTextContent("Notes");
});
it("keeps the Delete key available while editing a task title", async () => {
await render(, { container: rootElement });
await openWaterThePlants();
const title = await findTitleEntry();
await userEvent.click(title);
await userEvent.keyboard(title, "{Delete}");
expect(await screen.findByText("Notes")).toHaveTextContent("Notes");
await userEvent.click(screen.getByRole(Gtk.AccessibleRole.BUTTON, { name: "Back" }));
expect(await screen.findByRole(Gtk.AccessibleRole.LIST_ITEM, { name: /Water the plants/ })).toBeDefined();
});
it("goes back to the list from the editor", async () => {
await render(, { container: rootElement });
await openWaterThePlants();
await userEvent.click(screen.getByRole(Gtk.AccessibleRole.BUTTON, { name: "Back" }));
expect(await screen.findByRole(Gtk.AccessibleRole.LIST_ITEM, { name: /Water the plants/ })).toBeDefined();
expect(screen.queryByText("Notes")).toBeNull();
});
it("shows another list when its sidebar row is selected", async () => {
await render(, { container: rootElement });
await userEvent.click(await screen.findByRole(Gtk.AccessibleRole.LIST_ITEM, { name: /^Work/ }));
expect(await screen.findByRole(Gtk.AccessibleRole.LIST_ITEM, { name: /Prepare the weekly report/ })).toBeDefined();
expect(screen.queryByRole(Gtk.AccessibleRole.LIST_ITEM, { name: /Water the plants/ })).toBeNull();
});
it("opens the editor for a task added with the New Task button", async () => {
await render(, { container: rootElement });
await userEvent.click(await screen.findByRole(Gtk.AccessibleRole.BUTTON, { name: "New Task (Ctrl+N)" }));
expect(await screen.findByText("Notes")).toHaveTextContent("Notes");
expect(await findTitleEntry()).toHaveTextContent("New Task");
});
it("returns to the list when the open task is moved to trash", async () => {
await render(, { container: rootElement });
await openWaterThePlants();
await userEvent.click(screen.getByRole(Gtk.AccessibleRole.BUTTON, { name: "Delete (Delete)" }));
expect(screen.queryByText("Notes")).toBeNull();
await userEvent.click(screen.getByRole(Gtk.AccessibleRole.LIST_ITEM, { name: /^Trash/ }));
expect(await screen.findByRole(Gtk.AccessibleRole.LIST_ITEM, { name: /Water the plants/ })).toBeDefined();
});
it("permanently deletes a task through the Trash confirmation", async () => {
await render(, { container: rootElement });
const row = await screen.findByRole(Gtk.AccessibleRole.LIST_ITEM, { name: /Water the plants/ });
await userEvent.click(within(row).getByRole(Gtk.AccessibleRole.BUTTON, { name: "Delete task" }));
await userEvent.click(screen.getByRole(Gtk.AccessibleRole.LIST_ITEM, { name: /^Trash/ }));
const trashed = await screen.findByRole(Gtk.AccessibleRole.LIST_ITEM, { name: /Water the plants/ });
await userEvent.click(within(trashed).getByRole(Gtk.AccessibleRole.BUTTON, { name: "Delete task" }));
await userEvent.click(await screen.findByRole(Gtk.AccessibleRole.BUTTON, { name: "Delete" }));
expect(screen.queryByRole(Gtk.AccessibleRole.LIST_ITEM, { name: /Water the plants/ })).toBeNull();
});
it("reorders tasks by dragging", async () => {
await render(, { container: rootElement });
const source = await screen.findByRole(Gtk.AccessibleRole.LIST_ITEM, { name: /Water the plants/ });
const target = await screen.findByRole(Gtk.AccessibleRole.LIST_ITEM, { name: /Prepare the weekly report/ });
await userEvent.dragAndDrop(source, target, "t2");
const [first, second] = await screen.findAllByRole(Gtk.AccessibleRole.LIST_ITEM, {
name: /Water the plants|Prepare the weekly report/,
});
expect(first).toHaveAccessibleName("Prepare the weekly report");
expect(second).toHaveAccessibleName("Water the plants");
await userEvent.click(screen.getByRole(Gtk.AccessibleRole.LIST_ITEM, { name: "Work" }));
expect(screen.queryByRole(Gtk.AccessibleRole.LIST_ITEM, { name: "Water the plants" })).toBeNull();
await userEvent.click(screen.getByRole(Gtk.AccessibleRole.LIST_ITEM, { name: "All Tasks" }));
const returned = await screen.findByRole(Gtk.AccessibleRole.LIST_ITEM, { name: "Water the plants" });
const destination = await screen.findByRole(Gtk.AccessibleRole.LIST_ITEM, { name: "Prepare the weekly report" });
await userEvent.dragAndDrop(returned, destination, "t2");
const [water, review] = await screen.findAllByRole(Gtk.AccessibleRole.LIST_ITEM, {
name: /Water the plants|Prepare the weekly report/,
});
expect(water).toHaveAccessibleName("Water the plants");
expect(review).toHaveAccessibleName("Prepare the weekly report");
});
it("reorders the focused task with the keyboard", async () => {
await render(, { container: rootElement });
const source = await screen.findByRole(Gtk.AccessibleRole.LIST_ITEM, { name: /Water the plants/ });
await userEvent.keyboard(source, "{Alt>}{ArrowDown}{/Alt}");
const [first, second] = await screen.findAllByRole(Gtk.AccessibleRole.LIST_ITEM, {
name: /Water the plants|Prepare the weekly report/,
});
expect(first).toHaveAccessibleName("Prepare the weekly report");
expect(second).toHaveAccessibleName("Water the plants");
});
it("ignores text drops that do not name a task", async () => {
await render(, { container: rootElement });
const source = await screen.findByRole(Gtk.AccessibleRole.LIST_ITEM, { name: /Water the plants/ });
const target = await screen.findByRole(Gtk.AccessibleRole.LIST_ITEM, { name: /Prepare the weekly report/ });
await userEvent.dragAndDrop(source, target, "outside the application");
const [welcome, water, report] = await screen.findAllByRole(Gtk.AccessibleRole.LIST_ITEM, {
name: /Welcome to Tasks|Water the plants|Prepare the weekly report/,
});
expect(welcome).toHaveAccessibleName("Welcome to Tasks");
expect(water).toHaveAccessibleName("Water the plants");
expect(report).toHaveAccessibleName("Prepare the weekly report");
});
it("keeps an empty new-list form open until it has a name", async () => {
await render(, { container: rootElement });
await userEvent.click(await screen.findByRole(Gtk.AccessibleRole.BUTTON, { name: "New List" }));
const add = await screen.findByRole(Gtk.AccessibleRole.BUTTON, { name: "Add" });
const name = await screen.findByPlaceholderText("List name");
expect(add).toBeDisabled();
await userEvent.type(name, " ".repeat(3));
expect(add).toBeDisabled();
await userEvent.type(name, "Errands");
await waitFor(() => {
expect(screen.getByRole(Gtk.AccessibleRole.BUTTON, { name: "Add" })).toBeEnabled();
});
await userEvent.click(screen.getByRole(Gtk.AccessibleRole.BUTTON, { name: "Add" }));
expect(await screen.findByRole(Gtk.AccessibleRole.LIST_ITEM, { name: /^Errands/ })).toBeDefined();
});
it("keeps one color selected when the same swatch is clicked repeatedly", async () => {
await render(, { container: rootElement });
await userEvent.click(await screen.findByRole(Gtk.AccessibleRole.BUTTON, { name: "New List" }));
const orange = await screen.findByLabelText("Color #e66100");
await userEvent.click(orange);
await userEvent.click(orange);
expect(orange).toBePressed();
expect(await screen.findByLabelText("Color #3584e4")).not.toBePressed();
});
});
describe("task form - happy path", () => {
it("applies title and Important edits across navigation", async () => {
await render(, { container: rootElement });
await openWaterThePlants();
const title = await findTitleEntry();
await userEvent.clear(title);
await userEvent.type(title, "Water the balcony");
await userEvent.keyboard(title, "{Enter}");
await userEvent.click(importantSwitch(true));
await userEvent.click(screen.getByRole(Gtk.AccessibleRole.BUTTON, { name: "Back" }));
const updated = await screen.findByRole(Gtk.AccessibleRole.LIST_ITEM, { name: /Water the balcony/ });
await userEvent.click(updated);
const reopenedTitle = await findTitleEntry();
expect(reopenedTitle.getText()).toBe("Water the balcony");
expect(importantSwitch(false)).not.toBeChecked();
});
});
describe("task form - edge cases", () => {
it("rejects a blank title and trims a valid title", async () => {
await render(, { container: rootElement });
await openWaterThePlants();
const title = await findTitleEntry();
await userEvent.clear(title);
await userEvent.type(title, " ".repeat(3));
await userEvent.keyboard(title, "{Enter}");
expect(title).toBeInvalid();
await userEvent.type(title, " Water the balcony ");
await userEvent.keyboard(title, "{Enter}");
expect(title).toHaveTextContent("Water the balcony");
expect(title).toBeValid();
});
it("keeps an unapplied title local while editing importance and another task", async () => {
await render(, { container: rootElement });
await openWaterThePlants();
const title = await findTitleEntry();
await userEvent.clear(title);
await userEvent.type(title, "Unapplied draft");
await userEvent.click(importantSwitch(true));
expect(title.getText()).toBe("Unapplied draft");
expect(importantSwitch(false)).not.toBeChecked();
await userEvent.click(screen.getByRole(Gtk.AccessibleRole.BUTTON, { name: "Back" }));
expect(await screen.findByRole(Gtk.AccessibleRole.LIST_ITEM, { name: /Water the plants/ })).toBeDefined();
expect(screen.queryByRole(Gtk.AccessibleRole.LIST_ITEM, { name: /Unapplied draft/ })).toBeNull();
const otherTask = await screen.findByRole(Gtk.AccessibleRole.LIST_ITEM, { name: /Prepare the weekly report/ });
await userEvent.click(otherTask);
const otherTitle = await findTitleEntry();
expect(otherTitle.getText()).toBe("Prepare the weekly report");
});
});
describe("literal deletion toasts", () => {
it.each(["Ordinary task", "Read", "Read & < café"])(
"deletes and restores the literal task %s",
async (title) => {
await render(, { container: rootElement });
const entry = await screen.findByRole(Gtk.AccessibleRole.TEXT_BOX);
await userEvent.type(entry, title);
await userEvent.keyboard(entry, "{Enter}");
const row = await screen.findByRole(Gtk.AccessibleRole.LIST_ITEM, { name: title });
await userEvent.click(within(row).getByRole(Gtk.AccessibleRole.BUTTON, { name: "Delete task" }));
expect(await screen.findByText(`“${title}” moved to Trash`)).toHaveTextContent(`“${title}” moved to Trash`);
await userEvent.click(await screen.findByRole(Gtk.AccessibleRole.BUTTON, { name: "Undo" }));
expect(await screen.findByRole(Gtk.AccessibleRole.LIST_ITEM, { name: title })).toHaveAccessibleName(title);
},
);
});
describe("manual order after permanent deletion", () => {
it.each([false, true])("appends after deleting leading tasks (reordered: %s)", async (reordered) => {
await render(, { container: rootElement });
if (reordered) {
const source = await screen.findByRole(Gtk.AccessibleRole.LIST_ITEM, { name: "Prepare the weekly report" });
const target = await screen.findByRole(Gtk.AccessibleRole.LIST_ITEM, { name: "Welcome to Tasks" });
await userEvent.dragAndDrop(source, target, "t3");
}
for (const title of ["Welcome to Tasks", "Water the plants"]) {
const row = await screen.findByRole(Gtk.AccessibleRole.LIST_ITEM, { name: title });
await userEvent.click(within(row).getByRole(Gtk.AccessibleRole.BUTTON, { name: "Delete task" }));
}
await userEvent.click(screen.getByRole(Gtk.AccessibleRole.LIST_ITEM, { name: /^Trash/ }));
for (const title of ["Welcome to Tasks", "Water the plants"]) {
const row = await screen.findByRole(Gtk.AccessibleRole.LIST_ITEM, { name: title });
await userEvent.click(within(row).getByRole(Gtk.AccessibleRole.BUTTON, { name: "Delete task" }));
await userEvent.click(await screen.findByRole(Gtk.AccessibleRole.BUTTON, { name: "Delete" }));
}
await userEvent.click(screen.getByRole(Gtk.AccessibleRole.LIST_ITEM, { name: /^All Tasks/ }));
const entry = await screen.findByRole(Gtk.AccessibleRole.TEXT_BOX);
await userEvent.type(entry, "Newly appended task");
await userEvent.keyboard(entry, "{Enter}");
const lastSurvivor = "Prepare the weekly report";
const [survivor, added] = await screen.findAllByRole(Gtk.AccessibleRole.LIST_ITEM, {
name: (name) => name === lastSurvivor || name === "Newly appended task",
});
expect(survivor).toHaveAccessibleName(lastSurvivor);
expect(added).toHaveAccessibleName("Newly appended task");
});
it("starts a new manual list after every task was permanently deleted", async () => {
await render(, { container: rootElement });
const titles = [
"Welcome to Tasks",
"Water the plants",
"Prepare the weekly report",
];
for (const title of titles) {
const row = await screen.findByRole(Gtk.AccessibleRole.LIST_ITEM, { name: title });
await userEvent.click(within(row).getByRole(Gtk.AccessibleRole.BUTTON, { name: "Delete task" }));
}
await userEvent.click(screen.getByRole(Gtk.AccessibleRole.LIST_ITEM, { name: /^Trash/ }));
for (const title of titles) {
const row = await screen.findByRole(Gtk.AccessibleRole.LIST_ITEM, { name: title });
await userEvent.click(within(row).getByRole(Gtk.AccessibleRole.BUTTON, { name: "Delete task" }));
await userEvent.click(await screen.findByRole(Gtk.AccessibleRole.BUTTON, { name: "Delete" }));
}
await userEvent.click(screen.getByRole(Gtk.AccessibleRole.LIST_ITEM, { name: /^All Tasks/ }));
expect(await screen.findByText("No Tasks Yet")).toHaveTextContent("No Tasks Yet");
const entry = await screen.findByRole(Gtk.AccessibleRole.TEXT_BOX);
for (const title of ["First new task", "Second new task"]) {
await userEvent.type(entry, title);
await userEvent.keyboard(entry, "{Enter}");
}
const [first, second] = await screen.findAllByRole(Gtk.AccessibleRole.LIST_ITEM, {
name: /First new task|Second new task/,
});
expect(first).toHaveAccessibleName("First new task");
expect(second).toHaveAccessibleName("Second new task");
});
});
```
## Run and inspect
```bash
npm test
```
Each worker gets its own runtime directory, session bus, and headless compositor. The development window can stay open while the tests run.
Use `screen.debug()` to inspect the current widget tree or `screen.logRoles()` to inspect accessible names. Check the query and the rendered state when a test fails; assert the expected behavior without depending on diagnostic text.
The [testing guide](/guide/testing) covers scoped queries, hooks, screenshots, and additional interactions. For Vitest configuration and assertions, use the [Vitest documentation](https://vitest.dev/guide/).
## Next
[Package the App](/tutorial/packaging) adds the icon, desktop metadata, and installable packages.
---
---
description: "Give Tasks an icon, desktop metadata, and installable packages."
---
# Package the App
The app now has a [test suite](/tutorial/testing). Use `gtkx deploy` to package it with an icon, desktop entry, settings schema, and Node.js runtime.
## Name the release
Merge these fields into `package.json`, keeping its existing dependencies and scripts:
```json [package.json] merge
{
"name": "gtkx-tutorial",
"version": "1.0.0",
"license": "MPL-2.0",
"description": "Tasks app from the GTKX tutorial",
"author": "GTKX ",
"homepage": "https://gtkx.dev"
}
```
Refresh the lockfile after updating the package metadata:
```bash
npm install --package-lock-only
```
Save the tutorial's [LICENSE](https://github.com/gtkx-org/gtkx/blob/v1.6.0/examples/tutorial/LICENSE) in the project root. Keep the updated lockfile; the later Flatpak source build uses it to install dependencies offline.
## Add the application icons
Copy the tutorial's [full-color icon](https://github.com/gtkx-org/gtkx/blob/v1.6.0/examples/tutorial/data/icons/hicolor/scalable/apps/com.gtkx.tutorial.svg) and [symbolic icon](https://github.com/gtkx-org/gtkx/blob/v1.6.0/examples/tutorial/data/icons/hicolor/symbolic/apps/com.gtkx.tutorial-symbolic.svg) into these paths:
```text
data/icons/hicolor/scalable/apps/com.gtkx.tutorial.svg
data/icons/hicolor/symbolic/apps/com.gtkx.tutorial-symbolic.svg
```
The configuration keeps `applicationIcon: "data/icons"`. GTKX copies this icon tree into the build and installed packages. The filenames match the application ID already used by the window and About dialog.
For your own artwork, follow the [GNOME app icon guidelines](https://developer.gnome.org/hig/guidelines/app-icons.html).
## Describe the app
Replace `gtkx.config.ts` with the complete configuration below:
```ts [gtkx.config.ts]
import { defineConfig } from "@gtkx/config";
export default defineConfig({
applicationId: "com.gtkx.tutorial",
applicationIcon: "data/icons",
future: {
v2ByteArrays: true,
v2ValueReturns: true,
v2FinishResults: true,
v2InoutReturns: true,
v2ResourceImports: true,
v2DefaultLibraries: true,
v2TreeShaking: true,
},
deploy: {
name: "Tasks",
genericName: "Task Manager",
binaryName: "gtkx-tutorial",
summary: "Manage your tasks and to-dos",
description: [
"Tasks lets you organize to-dos into lists, set reminders, and track completed work. Built with GTKX, React, and Adwaita.",
],
categories: ["Office", "ProjectManagement"],
keywords: ["Task", "Tasks", "Todo", "To-do", "Checklist"],
isDbusActivatable: true,
desktopEntry: { "X-GNOME-UsesNotifications": "true" },
targets: ["flatpak", "deb", "rpm", "appimage"],
},
});
```
GTKX derives the version, license, author, and homepage from `package.json`. It uses this configuration to generate the desktop entry and AppStream metadata.
The notification entry lists Tasks in the desktop's notification settings. D-Bus activation lets notification actions reach the app when it is closed. These settings complete the [reminder](/tutorial/reminders) workflow.
The [finished configuration](https://github.com/gtkx-org/gtkx/blob/v1.6.0/examples/tutorial/gtkx.config.ts) also includes screenshots and release notes. Add those when preparing your own release; the [configuration reference](/reference/@gtkx/config/index/type-aliases/Config) describes the available options.
## Build and preview
The dev server can stay open while you build:
```bash
npm run build
node dist/bundle.mjs
```
Keep the whole `dist/` directory together. The bundle loads its native addon, compiled settings, and other assets from that directory. Running it directly still requires a compatible Node.js version, native libraries, and CPU architecture; the package command below supplies Node.js.
Preview the deployment files before packaging:
```bash
npm run deploy -- --print-manifests
```
GTKX builds the app, validates its metadata, and writes the install tree and target manifests under `build/`. Open the generated desktop entry and metainfo in `build/metadata/` and check the name, icon, description, and application ID. The command stops before creating packages.
## Create packages
Build the AppImage, deb, and rpm packages:
```bash
npm run deploy -- --target appimage,deb,rpm
```
The artifacts appear in `build/out/`. GTKX downloads and verifies the required packaging tools and Node.js runtime, then caches them. It also includes the app's license and notices for bundled dependencies. The [deploying guide](/guide/deploying) explains the runtime and packaging requirements.
Choose the package appropriate for your machine. For an x64 build, use one of:
```bash
sudo apt install ./build/out/gtkx-tutorial_1.0.0-1_amd64.deb
```
```bash
sudo dnf install ./build/out/gtkx-tutorial-1.0.0-1.x86_64.rpm
```
Or run the AppImage:
```bash
chmod +x build/out/Tasks-1.0.0-x86_64.AppImage
./build/out/Tasks-1.0.0-x86_64.AppImage
```
If deployment reports missing tools, follow its installation instructions or select fewer targets. Packaging a deb or rpm does not require running the corresponding distribution.
## Run it
For an installed package, find **Tasks** in the application launcher and confirm its icon appears. Open it, add a task, quit, and reopen it to check persistence. Check that Tasks appears in the desktop's notification settings.
## Next
[Translate the App](/tutorial/internationalization) adds a French catalog to the interface and package metadata. The last chapter builds the Flatpak.
---
---
description: "Translate the interface and package metadata with GTKX's gettext integration."
---
# Translate the App
[Package the App](/tutorial/packaging) made Tasks installable. Add a French catalog for its interface and desktop metadata.
`@gtkx/i18n` connects react-i18next to GNU gettext. Components use the upstream [translation hook](https://react.i18next.com/latest/usetranslation-hook); GTKX extracts messages, generates their types, and loads the compiled catalog through GLib.
## Add the catalog
Install the integration:
```bash
npm install @gtkx/i18n@1.6.0
```
GTKX uses GNU gettext for extraction and compilation. Its CLI reports missing build tools and installation instructions.
Create `po/LINGUAS` with the locales to ship:
```text [po/LINGUAS]
fr
```
The application ID, `com.gtkx.tutorial`, is the gettext domain. Keep it unchanged so the app, catalogs, and package metadata agree.
## Mark the interface text
Translate the window title and new-task tooltip in `src/components/window.tsx`:
```diff [src/components/window.tsx]
@@ -0,0 +1 @@
+import { useTranslation } from "@gtkx/i18n";
@@ -36,0 +38 @@
+ const { t } = useTranslation();
@@ -74 +76 @@
- title="Tasks"
+ title={t("Tasks")}
@@ -121 +123 @@
- tooltipText="New Task (Ctrl+N)"
+ tooltipText={t("New Task (Ctrl+N)")}
```
Update `src/components/search-button.tsx`:
```tsx [src/components/search-button.tsx]
import { useTranslation } from "@gtkx/i18n";
import { GtkButton } from "@gtkx/jsx/gtk";
import { useStore } from "../store/index.js";
export const SearchButton = () => {
const { t } = useTranslation();
const searchMode = useStore((state) => state.searchMode);
const setSearchMode = useStore((state) => state.setSearchMode);
return (
setSearchMode(!searchMode)}
/>
);
};
```
Translate the search entry in `src/components/task-list.tsx`:
```diff [src/components/task-list.tsx]
@@ -0,0 +1 @@
+import { useTranslation } from "@gtkx/i18n";
@@ -11,0 +13 @@
+ const { t } = useTranslation();
@@ -34 +36 @@
- placeholderText="Search tasks…"
+ placeholderText={t("Search tasks…")}
```
Outside components, import `t` directly. Translate the starter task in `src/store/seed.ts`:
```diff [src/store/seed.ts]
@@ -0,0 +1 @@
+import { t } from "@gtkx/i18n";
@@ -41 +42 @@
- title: "Water the plants",
+ title: t("Water the plants"),
```
Translate the search result in `src/store/selectors.ts`:
```diff [src/store/selectors.ts]
@@ -0,0 +1 @@
+import { t } from "@gtkx/i18n";
@@ -115 +116 @@
- if (query) return { icon: "system-search-symbolic", title: "No Results", description: `No tasks match “${query}”` };
+ if (query) return { icon: "system-search-symbolic", title: "No Results", description: t("No tasks match “{{query}}”", { query }) };
```
Translate the formatters in `src/format.ts`, keeping the existing date helpers:
```diff [src/format.ts]
@@ -0,0 +1 @@
+import { t } from "@gtkx/i18n";
@@ -13,4 +14,6 @@
- if (days === 0) return `Today at ${time}`;
- if (days === 1) return `Tomorrow at ${time}`;
- if (days === -1) return `Yesterday at ${time}`;
- if (days < 0) return `${-days} days ago`;
+ if (days === 0) return t("Today at {{time}}", { time });
+ if (days === 1) return t("Tomorrow at {{time}}", { time });
+ if (days === -1) return t("Yesterday at {{time}}", { time });
+ if (days < 0) {
+ return t("{{count}} day ago", "{{count}} days ago", { count: -days });
+ }
@@ -22 +25 @@
- if (!iso) return "Never";
+ if (!iso) return t("Never");
```
Gettext counts must be non-negative safe integers. An overdue date has a negative `days` value, so pass `-days` as the count. `toLocaleDateString` and `toLocaleString` format dates using the process locale.
These edits provide the messages exercised in this chapter. After completing its checks, apply the same approach to the remaining authored labels, dialogs, notifications, and starter content; the [finished source](https://github.com/gtkx-org/gtkx/tree/v1.6.0/examples/tutorial/src) shows each location. Keep user-entered names, action names, settings keys, and other identifiers unchanged. Starter content is translated on first creation; changing locale does not rewrite saved tasks.
Use literal message keys and retain the names `t` and `useTranslation`: GTKX's extractor rejects aliases and dynamic keys. Codegen generates the message and interpolation types, so there is no separate list of keys to maintain.
## Translate the messages
Refresh the source and deployment messages without building packages:
```bash
npm run deploy -- --target appimage,deb,rpm --print-manifests
```
GTKX creates `po/fr.po`, synchronizes it with the source template, and includes the translatable metadata from `gtkx.config.ts`. Replace the initial French catalog with this complete file. Later extraction keeps these translations and adds new messages:
```po [po/fr.po]
msgid ""
msgstr ""
"Project-Id-Version: gtkx-tutorial 1.0.0\n"
"PO-Revision-Date: 2026-09-26 00:00+0000\n"
"Last-Translator: GTKX contributors\n"
"Language-Team: French\n"
"Language: fr\n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n"
"Plural-Forms: nplurals=2; plural=(n > 1);\n"
msgid "Tasks"
msgstr "Tâches"
msgid "New Task (Ctrl+N)"
msgstr "Nouvelle tâche (Ctrl+N)"
msgid "Search (Ctrl+F)"
msgstr "Rechercher (Ctrl+F)"
msgid "Search tasks…"
msgstr "Rechercher des tâches…"
msgid "Water the plants"
msgstr "Arroser les plantes"
msgid "No tasks match “{{query}}”"
msgstr "Aucune tâche ne correspond à « {{query}} »"
msgid "Today at {{time}}"
msgstr "Aujourd’hui à {{time}}"
msgid "Tomorrow at {{time}}"
msgstr "Demain à {{time}}"
msgid "Yesterday at {{time}}"
msgstr "Hier à {{time}}"
msgid "Never"
msgstr "Jamais"
msgid "{{count}} day ago"
msgid_plural "{{count}} days ago"
msgstr[0] "Il y a {{count}} jour"
msgstr[1] "Il y a {{count}} jours"
msgid "Task Manager"
msgstr "Gestionnaire de tâches"
msgid "Manage your tasks and to-dos"
msgstr "Gérez vos tâches et listes de choses à faire"
msgid "Tasks lets you organize to-dos into lists, set reminders, and track completed work. Built with GTKX, React, and Adwaita."
msgstr "Tâches vous permet d’organiser vos tâches en listes, de définir des rappels et de suivre le travail accompli. L’application utilise GTKX, React et Adwaita."
msgid "Task;Tasks;Todo;To-do;Checklist;"
msgstr "Tâche;Tâches;À faire;À-faire;Liste de contrôle;"
msgid "Task"
msgstr "Tâche"
msgid "Todo"
msgstr "À faire"
msgid "To-do"
msgstr "À-faire"
msgid "Checklist"
msgstr "Liste de contrôle"
```
Translate the remaining entries as you mark more interface text. An empty translation falls back to English. The [gettext manual](https://www.gnu.org/software/gettext/manual/html_node/PO-Files.html) describes the PO format.
`gtkx codegen`, `gtkx dev`, and `gtkx build` refresh the source catalog. Deployment also extracts metadata and stages the compiled catalog with the app. Commit `LINGUAS`, the PO and POT files, and `POTFILES.in`; compiled MO files and `dist/locale` are build outputs.
## Run it in French
Use a new data directory so the seed task is translated on first creation:
```bash
LC_ALL=fr_FR.UTF-8 LANG=fr_FR.UTF-8 LANGUAGE=fr \
XDG_DATA_HOME="$(mktemp -d)" npm run dev
```
Check the **Tâches** window title, **Nouvelle tâche (Ctrl+N)** tooltip, and **Arroser les plantes** task. Search for `introuvable` to see the translated empty state.
The locale is process-wide. Restart after changing the locale environment; calling i18next's language-switching API cannot replace the process locale used by GLib.
## Test the compiled catalog
Keep the English tests from [Test the App](/tutorial/testing). Create `vitest.i18n.config.ts` for a separate French process:
```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()],
test: {
include: ["tests/**/*.i18n.tsx"],
setupFiles: ["./tests/setup.ts"],
bail: 1,
env: {
GTKX_LOCALE_DIR: resolve(import.meta.dirname, "dist/locale"),
LANG: "fr_FR.UTF-8",
LANGUAGE: "fr",
LC_ALL: "fr_FR.UTF-8",
},
},
});
```
Create `tests/localization.i18n.tsx`:
```tsx [tests/localization.i18n.tsx]
import * as Gtk from "@gtkx/gi/gtk";
import { rootElement } from "@gtkx/react";
import { render, screen, userEvent } from "@gtkx/testing";
import { describe, expect, it } from "vitest";
import { App } from "../src/app.js";
import { useStore } from "../src/store/index.js";
describe("Tasks in French", () => {
it("renders translated controls and starter content", async () => {
await render(, { container: rootElement });
expect(
await screen.findByRole(Gtk.AccessibleRole.BUTTON, { name: "Nouvelle tâche (Ctrl+N)" }),
).toBeDefined();
expect(
await screen.findByRole(Gtk.AccessibleRole.LIST_ITEM, { name: /Arroser les plantes/ }),
).toBeDefined();
});
it("uses French interpolation and plural forms", async () => {
const due = new Date();
due.setDate(due.getDate() - 2);
const tasks = useStore.getState().tasks.map((task) =>
task.id === "t2" ? { ...task, due: due.toISOString() } : task,
);
useStore.setState({ tasks });
await render(, { container: rootElement });
expect(await screen.findByText("Il y a 2 jours")).toHaveTextContent("Il y a 2 jours");
await userEvent.click(screen.getByRole(Gtk.AccessibleRole.BUTTON, { name: "Rechercher (Ctrl+F)" }));
const search = await screen.findByPlaceholderText("Rechercher des tâches…");
await userEvent.type(search, "introuvable");
expect(await screen.findByText("Aucune tâche ne correspond à « introuvable »")).toHaveTextContent(
"Aucune tâche ne correspond à « introuvable »",
);
});
it("rejects dragging while the translated task list is filtered", async () => {
await render(, { container: rootElement });
await userEvent.click(await screen.findByText("Open"));
const source = await screen.findByRole(Gtk.AccessibleRole.LIST_ITEM, { name: /Arroser les plantes/ });
const target = await screen.findByRole(Gtk.AccessibleRole.LIST_ITEM, { name: /Welcome to Tasks/ });
await expect(userEvent.dragAndDrop(source, target, "t2")).rejects.toThrow();
});
});
```
The tests mount the real app, exercise translated controls and empty results, and reject an unavailable drag after filtering. They use the setup file from the testing chapter, including its isolated data directory. The queries match the partial translation above; update their labels as you translate the rest of the interface.
Replace the `scripts` field in `package.json` with this block; keep the remaining package fields:
```json [package.json] merge
{
"scripts": {
"dev": "gtkx dev",
"build": "gtkx build",
"codegen": "gtkx codegen",
"test": "vitest run && npm run test:i18n",
"test:i18n": "gtkx build && vitest run --config vitest.i18n.config.ts",
"typecheck": "gtkx codegen && tsc",
"start": "node dist/bundle.mjs",
"deploy": "gtkx deploy"
}
}
```
```bash
npm test
```
The build compiles `dist/locale/fr/LC_MESSAGES/com.gtkx.tutorial.mo` before the French worker loads it.
## Ship the translations
Rebuild the packages from the previous chapter:
```bash
npm run deploy -- --target appimage,deb,rpm
```
Reinstall the deb or rpm if using it, then launch Tasks in French:
```bash
LC_ALL=fr_FR.UTF-8 LANG=fr_FR.UTF-8 LANGUAGE=fr gtkx-tutorial
```
For the x64 AppImage:
```bash
LC_ALL=fr_FR.UTF-8 LANG=fr_FR.UTF-8 LANGUAGE=fr \
./build/out/Tasks-1.0.0-x86_64.AppImage
```
The launcher locates the packaged catalog through `GTKX_LOCALE_DIR`. Translated metadata, including the application name, is written into the desktop entry and AppStream file. Optional screenshots and release notes use the same PO catalog when present in the deploy configuration.
## Next
[Prepare for Flathub](/tutorial/flatpak) builds the localized Flatpak and prepares its source submission.
---
---
description: "Build a Flatpak for Tasks and prepare a source manifest for distribution."
---
# Prepare for Flathub
[Translate the App](/tutorial/internationalization) added a French catalog. Package it in a Flatpak, then use GTKX's source mode to prepare a manifest that rebuilds the application.
## Build and install it
```bash
npm run deploy -- --target flatpak
```
GTKX writes the manifest under `build/targets/flatpak/` and runs Flatpak Builder. The first build downloads its GNOME runtime from Flathub. If the build fails because FUSE is unavailable, follow the [container troubleshooting instructions](/guide/deploying#flatpak-in-containers).
Install the resulting x64 bundle and launch it in French:
```bash
flatpak install --user --reinstall build/out/com.gtkx.tutorial-1.0.0-x86_64.flatpak
flatpak run --env=LANG=fr_FR.UTF-8 --env=LANGUAGE=fr --env=LC_ALL=fr_FR.UTF-8 com.gtkx.tutorial
```
Use the package matching your architecture. Tasks loads the installed catalog from `/app/share/locale`. On a fresh Flatpak installation, the translated starter task appears as **Arroser les plantes**.
## Check storage and reminders
Add a task named `Ship it`, quit, and reopen the Flatpak. Confirm the task persists. The storage backend from [Save Tasks](/tutorial/saving-to-disk) uses GLib's data directory, which points into the Flatpak's private storage:
```bash
cat ~/.var/app/com.gtkx.tutorial/data/com.gtkx.tutorial/tasks.json
```
The development app keeps its existing data under `~/.local/share/com.gtkx.tutorial/`. Both use the same GTKX application code.
Also check preferences and a reminder's **Mark Complete** action. Tasks uses the generated display and rendering permissions without adding filesystem or network access. For another application, `deploy.flatpak.finishArgs` configures additional permissions; consult the [Flatpak sandbox documentation](https://docs.flatpak.org/en/latest/sandbox-permissions.html).
## Generate a source manifest
The default `prebuilt` mode packages the local build. In `source` mode, the manifest checks out a pinned Git revision, installs dependencies offline, and runs `gtkx build` inside the SDK.
After testing the prebuilt package, update `gtkx.config.ts` for source mode:
```diff [gtkx.config.ts]
@@ -26,0 +27,4 @@
+ flatpak: {
+ mode: "source",
+ source: { url: "https://github.com/you/tasks.git" },
+ },
```
Use your application's public repository URL. Install [`flatpak-node-generator`](https://github.com/flatpak/flatpak-builder-tools/tree/master/node) using its installation instructions; GTKX uses it to prepare the offline dependency sources.
Commit the configuration, application sources, lockfile, icons, license, and translation catalogs, then push that commit to the configured repository. The source build must be able to fetch it. Generated MO files stay out of Git; the build reproduces them. Then generate the manifest:
```bash
npm run deploy -- --target flatpak --print-manifests
```
Keep `com.gtkx.tutorial.yml` and `generated-sources.json` together in `build/targets/flatpak/`. Regenerate them after dependency changes. The manifest includes the Node.js SDK extension and installs the bundle, icons, settings, and compiled catalogs.
GTKX pins the current commit. To select a release tag instead, create and push that tag, then set `source.tag: "v1.0.0"` before regenerating. GTKX resolves the tag to a commit in your checkout.
## Prepare your own submission
Use your application's identity and metadata before publishing. The generated source manifest is a starting point: it rebuilds the application bundle, while 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) before submission.
Build and test the final source manifest using [Flathub's submission instructions](https://docs.flathub.org/docs/for-app-authors/submission), including its manifest and repository checks. GTKX's manifest preview does not run that build or establish submission readiness.
## Next
Browse the [GTKX 1.6 tutorial source](https://github.com/gtkx-org/gtkx/tree/v1.6.0/examples/tutorial), or start your own application with `npm create gtkx@1.6.0`.
## 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 draws text with your system fonts: install [Adwaita Sans and Adwaita Mono](https://gitlab.gnome.org/GNOME/adwaita-fonts), GNOME's interface fonts since GNOME 48, or 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.
## 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 2.0 beta 14](https://gtkx.dev/v2/llms.txt)