Add Menus and Shortcuts
Add New Note, Keyboard Shortcuts and About as GIO actions, move the preview toggle onto one, and run them from header bar buttons, a main menu and keyboard shortcuts.
Window actions
src/components/window-actions.tsx declares the window's actions as elements, GSimpleAction for a plain command and StatefulAction for the preview toggle:
import { StatefulAction, useToast } from "@gtkx/components";
import { useTranslation } from "@gtkx/i18n";
import { GSimpleAction } from "@gtkx/jsx/gio";
import type { Dialog } from "../dialogs/dialogs.js";
import { openNote } from "../navigation.js";
import { useNotesStore } from "../notes/notes-store.js";
const message = (error: unknown): string =>
error instanceof Error ? error.message : String(error);
const useNoteCommands = () => {
const { t } = useTranslation();
const create = useNotesStore((state) => state.create);
const { show } = useToast();
const showError = (error: unknown): void => {
show({ useMarkup: false, title: message(error) });
};
const newNote = async (): Promise<void> => {
openNote(await create(t("Untitled"), ""));
};
return {
newNote: () => newNote().catch(showError),
};
};
type WindowActionsProps = {
preview: boolean;
onPreviewChange: (preview: boolean) => void;
onShowDialog: (dialog: Dialog) => void;
};
export const WindowActions = ({
preview,
onPreviewChange,
onShowDialog,
}: WindowActionsProps) => {
const { newNote } = useNoteCommands();
return (
<>
<GSimpleAction name="new-note" onActivate={() => void newNote()} />
<StatefulAction
name="preview"
state={preview}
onStateChange={onPreviewChange}
/>
<GSimpleAction
name="shortcuts"
onActivate={() => onShowDialog({ kind: "shortcuts" })}
/>
<GSimpleAction
name="about"
onActivate={() => onShowDialog({ kind: "about" })}
/>
</>
);
};- The window takes these elements in its
actionsprop, and each becomes an action namedwin.followed by itsname, such aswin.new-note. See Declaring actions. - Preview is a stateful action.
StatefulActionfrom@gtkx/componentstakes the window'spreviewstate as a plain boolean, andonStateChangestores the value the action is asked to change to. Activated without a parameter, a boolean action requests the opposite state, so it toggles without anonActivate. See Parameters and state. - Keyboard Shortcuts and About pass the dialog to show to
onShowDialog. Mount the dialogs renders it. useNoteCommandsholds the note commands that actions run, so far New Note. A command that fails shows its error in a toast.
New Note writes an empty Untitled.md and opens it. createNote, in src/notes/files.ts, tries Untitled, then Untitled 2, Untitled 3 and so on:
import * as GLib from "@gtkx/gi/glib";
import { mkdir, readdir, readFile, stat, writeFile } from "node:fs/promises";
import { join } from "node:path";
import writeFileAtomic from "write-file-atomic";
import { type Note, toNote } from "./note.js";
const EXTENSION = ".md";
export const defaultFolder = (): string =>
join(
GLib.getUserSpecialDir(GLib.UserDirectory.DIRECTORY_DOCUMENTS) ??
GLib.getHomeDir(),
"Notes",
);
export const noteName = (fileName: string): string | null =>
fileName.endsWith(EXTENSION) && !fileName.startsWith(".")
? fileName.slice(0, -EXTENSION.length)
: null;
export const linkedNoteName = (uri: string): string | null => {
const fileName =
GLib.Uri.peekScheme(uri) === null
? GLib.Uri.unescapeString(uri, "/")
: null;
return fileName === null || fileName.includes("/")
? null
: noteName(fileName);
};
const notePath = (folder: string, name: string): string =>
join(folder, `${name}${EXTENSION}`);
const isMissing = (error: unknown): boolean =>
error instanceof Error && "code" in error && error.code === "ENOENT";
export const readNote = async (
folder: string,
name: string,
): Promise<Note | null> => {
const path = notePath(folder, name);
try {
const info = await stat(path);
if (!info.isFile()) {
return null;
}
return toNote(name, await readFile(path, "utf8"), info.mtimeMs);
} catch (error) {
if (isMissing(error)) {
return null;
}
throw error;
}
};
export const readNotes = async (folder: string): Promise<Note[]> => {
await mkdir(folder, { recursive: true });
const names = (await readdir(folder))
.map(noteName)
.filter((name) => name !== null);
const notes = await Promise.all(
names.map((name) => readNote(folder, name)),
);
return notes.filter((note) => note !== null);
};
export const writeNote = (
folder: string,
name: string,
text: string,
): Promise<void> => writeFileAtomic(notePath(folder, name), text);
const isTaken = (error: unknown): boolean =>
error instanceof Error && "code" in error && error.code === "EEXIST";
export const createNote = async (
folder: string,
base: string,
text: string,
): Promise<string> => {
for (let number = 1; ; number++) {
const name = number === 1 ? base : `${base} ${number}`;
try {
await writeFile(notePath(folder, name), text, { flag: "wx" });
return name;
} catch (error) {
if (!isTaken(error)) {
throw error;
}
}
}
};- The
wxflag makeswriteFilefail withEEXISTwhen the file already exists instead of replacing it, so a new note never overwrites another, even one that another program created a moment before. isTakenrecognizes that error and moves on to the next name. Any other error, such as a folder the app can't write to, ends the loop and reaches the toast.
The store's create action adds the note to the list at once and returns the name it used. It records the text in saved, so the watcher from Watch the folder skips the write as it skips the app's own saves:
import { watch } from "chokidar";
import { debounce, type DebouncedFunction } from "es-toolkit";
import { once } from "node:events";
import { basename } from "node:path";
import { use } from "react";
import { create } from "zustand";
import {
createNote,
noteName,
readNote,
readNotes,
writeNote,
} from "./files.js";
import { type Note, toNote } from "./note.js";
const SAVE_DELAY_MS = 400;
type NoteMap = ReadonlyMap<string, Note>;
type OpenFolder = {
path: string;
saved: Map<string, string>;
save: DebouncedFunction<() => void>;
};
type FolderEvents = {
onSaveError: (name: string) => void;
onReplaced: (name: string) => void;
onReadError: (name: string) => void;
};
type NotesState = {
folder: OpenFolder | null;
read: Promise<void>;
notes: NoteMap;
open: (path: string, events: FolderEvents) => () => void;
create: (name: string, text: string) => Promise<string>;
edit: (name: string, text: string) => void;
};
const withNote = (notes: NoteMap, name: string, note: Note | null): NoteMap => {
const next = new Map(notes);
if (note === null) {
next.delete(name);
} else {
next.set(name, note);
}
return next;
};
const currentFolder = ({ folder }: NotesState): OpenFolder => {
if (folder === null) {
throw new Error("No notes folder is open");
}
return folder;
};
export const useNotesStore = create<NotesState>()((set, get) => ({
folder: null,
read: Promise.resolve(),
notes: new Map(),
open: (path, { onSaveError, onReplaced, onReadError }) => {
const controller = new AbortController();
const { signal } = controller;
const saved = new Map<string, string>();
const failing = new Set<string>();
const write = (name: string, text: string): void => {
saved.set(name, text);
void writeNote(path, name, text).then(
() => {
failing.delete(name);
},
() => {
if (saved.get(name) === text) {
saved.delete(name);
}
if (!failing.has(name)) {
failing.add(name);
onSaveError(name);
}
},
);
};
const save = debounce(() => {
for (const note of get().notes.values()) {
if (note.text !== saved.get(note.name)) {
write(note.name, note.text);
}
}
}, SAVE_DELAY_MS);
const refresh = async (name: string): Promise<void> => {
const note = await readNote(path, name);
if (signal.aborted || note?.text === saved.get(name)) {
return;
}
const current = get().notes.get(name);
if (
current !== undefined &&
current.text !== saved.get(name) &&
current.text !== note?.text
) {
onReplaced(name);
}
if (note === null) {
saved.delete(name);
} else {
saved.set(name, note.text);
}
set((state) => ({ notes: withNote(state.notes, name, note) }));
};
const leaveOut = (name: string): void => {
if (signal.aborted) {
return;
}
saved.delete(name);
set((state) => ({ notes: withNote(state.notes, name, null) }));
onReadError(name);
};
const failFolder = (error: Error): void => {
if (signal.aborted) {
return;
}
const read = Promise.reject(error);
void read.catch(() => undefined);
set({ read });
};
const load = async (): Promise<void> => {
const list = await readNotes(path);
if (signal.aborted) {
return;
}
for (const note of list) {
saved.set(note.name, note.text);
}
set({ notes: new Map(list.map((note) => [note.name, note])) });
const watcher = watch(path, {
ignoreInitial: true,
depth: 0,
ignored: (file, stats) =>
stats?.isFile() === true &&
noteName(basename(file)) === null,
}).on("all", (_event, file) => {
const name = noteName(basename(file));
if (name !== null) {
void refresh(name).catch(() => leaveOut(name));
}
});
signal.addEventListener("abort", () => void watcher.close());
await once(watcher, "ready");
watcher.on("error", (error) =>
failFolder(
error instanceof Error ? error : new Error(String(error)),
),
);
};
set({ folder: { path, saved, save }, read: load(), notes: new Map() });
return () => {
save.flush();
controller.abort();
set({ folder: null });
};
},
create: async (base, text) => {
const { path, saved } = currentFolder(get());
await get().read;
const name = await createNote(path, base, text);
saved.set(name, text);
set((state) => ({
notes: withNote(state.notes, name, toNote(name, text, Date.now())),
}));
return name;
},
edit: (name, text) => {
set((state) => ({
notes: withNote(state.notes, name, toNote(name, text, Date.now())),
}));
currentFolder(get()).save();
},
}));
export const useNotes = <T>(select: (state: NotesState) => T): T => {
use(useNotesStore((state) => state.read));
return useNotesStore(select);
};src/navigation.ts creates a navigation container ref, which the window passes to NavigationContainer below, and openNote navigates through it; see React Navigation's Navigation ref:
import {
createNavigationContainerRef,
createSplitViewNavigator,
useNavigationState,
} from "@gtkx/navigation";
export type RootParamList = {
Notes: undefined;
Note: { name: string };
};
export const Split = createSplitViewNavigator<RootParamList>();
export const navigationRef = createNavigationContainerRef<RootParamList>();
type RootNavigatorType = typeof Split;
declare module "@react-navigation/core" {
interface RootNavigator extends RootNavigatorType {}
}
export const useOpenNoteName = (): string | null =>
useNavigationState<RootParamList, string | null>((state) => {
const route = state.routes.at(-1);
return route?.name === "Note" ? (route.params?.name ?? null) : null;
});
export const openNote = (name: string): void => {
navigationRef.navigate("Note", { name });
};Menus
The main menu sits at the end of the sidebar's header bar. GMenu describes it as data, and each item names the action it runs:
import { useTranslation } from "@gtkx/i18n";
import { GMenu } from "@gtkx/jsx/gio";
import { GtkMenuButton } from "@gtkx/jsx/gtk";
export const MainMenu = () => {
const { t } = useTranslation();
return (
<GtkMenuButton
primary
iconName="open-menu-symbolic"
tooltipText={t("Main Menu")}
menuModel={
<GMenu
items={[
{
section: [
{
label: t("New Note"),
action: "win.new-note",
},
],
},
{
section: [
{
label: t("Keyboard Shortcuts"),
action: "win.shortcuts",
},
{
label: t("About Notes"),
action: "win.about",
},
],
},
]}
/>
}
/>
);
};sectiongroups items between separators. Keyboard Shortcuts and About Notes go in the last group, and Quit stays out of the menu, as the GNOME HIG asks of a primary menu.primarymakes F10 open the menu, and an item whose action is disabled is greyed out. See Menus.
The window moves from src/app.tsx into src/components/window.tsx, and its sidebar header gains a New Note button, the note count and the main menu:
import { ToastOverlay, ToastProvider, useToast } from "@gtkx/components";
import { useTranslation } from "@gtkx/i18n";
import { AdwApplicationWindow, AdwStatusPage } from "@gtkx/jsx/adw";
import { GtkButton, GtkToggleButton } from "@gtkx/jsx/gtk";
import { NavigationContainer } from "@gtkx/navigation";
import { quit } from "@gtkx/react";
import { useEffect, useEffectEvent, useState } from "react";
import { type Dialog, Dialogs } from "../dialogs/dialogs.js";
import { navigationRef, Split } from "../navigation.js";
import { defaultFolder } from "../notes/files.js";
import { useNotesStore } from "../notes/notes-store.js";
import { NoteScreen } from "../screens/note-screen.js";
import { NotesScreen, NotesTitle } from "../screens/notes-screen.js";
import { FolderBoundary } from "./folder-boundary.js";
import { MainMenu } from "./main-menu.js";
import { WindowActions } from "./window-actions.js";
const NoteNavigation = ({ preview }: { preview: boolean }) => {
const { t } = useTranslation();
const { show } = useToast();
const open = useNotesStore((state) => state.open);
const folder = defaultFolder();
const showSaveError = useEffectEvent((name: string) => {
show({
useMarkup: false,
title: t("Couldn’t save “{{name}}”", { name }),
timeout: 0,
});
});
const showReplaced = useEffectEvent((name: string) => {
show({
useMarkup: false,
title: t(
"Another program replaced your unsaved edits to “{{name}}”",
{ name },
),
timeout: 0,
});
});
const showReadError = useEffectEvent((name: string) => {
show({
useMarkup: false,
title: t("Couldn’t read “{{name}}”", { name }),
timeout: 0,
});
});
useEffect(
() =>
open(folder, {
onSaveError: (name) => {
showSaveError(name);
},
onReplaced: (name) => {
showReplaced(name);
},
onReadError: (name) => {
showReadError(name);
},
}),
[open, folder],
);
return (
<FolderBoundary folder={folder}>
<NavigationContainer ref={navigationRef}>
<Split.Navigator
collapseCondition="max-width: 500sp"
sidebarWidthFraction={0.3}
minSidebarWidth={220}
maxSidebarWidth={320}
contentPlaceholder={
<AdwStatusPage
iconName="document-edit-symbolic"
title={t("No Note Selected")}
/>
}
>
<Split.Screen
name="Notes"
component={NotesScreen}
options={{
title: t("Notes"),
headerTitle: <NotesTitle />,
headerStart: (
<GtkButton
iconName="document-new-symbolic"
tooltipText={t("New Note (Ctrl+N)")}
actionName="win.new-note"
/>
),
headerEnd: <MainMenu />,
}}
/>
<Split.Screen
name="Note"
options={({ route }) => ({
title: route.params.name,
headerEnd: (
<GtkToggleButton
iconName="view-reveal-symbolic"
tooltipText={t("Preview (Ctrl+Shift+P)")}
actionName="win.preview"
/>
),
})}
>
{(props) => <NoteScreen {...props} preview={preview} />}
</Split.Screen>
</Split.Navigator>
</NavigationContainer>
</FolderBoundary>
);
};
export const Window = () => {
const { t } = useTranslation();
const [dialog, setDialog] = useState<Dialog>({ kind: "none" });
const [preview, setPreview] = useState(false);
return (
<ToastProvider>
<AdwApplicationWindow
title={t("Notes")}
defaultWidth={720}
defaultHeight={480}
widthRequest={360}
heightRequest={294}
onCloseRequest={quit}
actions={
<WindowActions
preview={preview}
onPreviewChange={setPreview}
onShowDialog={setDialog}
/>
}
>
<ToastOverlay>
<NoteNavigation preview={preview} />
</ToastOverlay>
<Dialogs
dialog={dialog}
onClose={() => setDialog({ kind: "none" })}
/>
</AdwApplicationWindow>
</ToastProvider>
);
};WindowActionscallsuseToast, so it must render insideToastProvider. It is a prop of the window, so the provider now wraps the window instead of sitting inside it, andToastOverlaystays around the navigator.- The Notes screen's options fill its header bar:
headerTitlereplaces the plain title withNotesTitle,headerStartadds the New Note button, andheaderEndholds the main menu. See Headers. - Both header buttons run actions through
actionNameand follow their state, so clicking the toggle activateswin.previewas Ctrl+Shift+P does. See Buttons. Windowkeeps thepreviewstate, whichWindowActionsandNoteNavigationshare, and thedialogstate for Mount the dialogs.
NotesTitle, in src/screens/notes-screen.tsx, shows the note count under the title, and the empty folder's status page gets a New Note button:
import { ListView } from "@gtkx/components";
import * as Gtk from "@gtkx/gi/gtk";
import * as Pango from "@gtkx/gi/pango";
import { useTranslation } from "@gtkx/i18n";
import { AdwStatusPage, AdwWindowTitle } from "@gtkx/jsx/adw";
import { GtkBox, GtkButton, GtkLabel, GtkScrolledWindow } from "@gtkx/jsx/gtk";
import type { SplitViewScreenProps } from "@gtkx/navigation";
import { type RootParamList, useOpenNoteName } from "../navigation.js";
import type { Note } from "../notes/note.js";
import { useNotes } from "../notes/notes-store.js";
const NoteRow = ({ note }: { note: Note }) => (
<GtkBox
orientation={Gtk.Orientation.VERTICAL}
spacing={2}
marginTop={8}
marginBottom={8}
>
<GtkLabel
label={note.name}
xalign={0}
ellipsize={Pango.EllipsizeMode.END}
cssClasses={["heading"]}
/>
<GtkLabel
label={note.excerpt}
xalign={0}
ellipsize={Pango.EllipsizeMode.END}
singleLineMode
cssClasses={["dimmed", "caption"]}
/>
</GtkBox>
);
export const NotesTitle = () => {
const { t } = useTranslation();
const count = useNotes((state) => state.notes.size);
const subtitle = t("{{count}} note", {
count,
defaultValue_one: "{{count}} note",
defaultValue_other: "{{count}} notes",
});
return <AdwWindowTitle title={t("Notes")} subtitle={subtitle} />;
};
export const NotesScreen = ({
navigation,
}: SplitViewScreenProps<RootParamList, "Notes">) => {
const { t } = useTranslation();
const notes = useNotes((state) => state.notes);
const openName = useOpenNoteName();
if (notes.size === 0) {
return (
<AdwStatusPage
iconName="document-new-symbolic"
title={t("No Notes")}
description={t("Notes are Markdown files in your notes folder")}
cssClasses={["compact"]}
>
<GtkButton
label={t("New Note")}
actionName="win.new-note"
halign={Gtk.Align.CENTER}
cssClasses={["pill", "suggested-action"]}
/>
</AdwStatusPage>
);
}
const shown = [...notes.values()].sort((a, b) => b.modified - a.modified);
return (
<GtkScrolledWindow hscrollbarPolicy={Gtk.PolicyType.NEVER}>
<ListView<Note>
items={shown.map((note) => ({ id: note.name, value: note }))}
isFlat
cssClasses={["navigation-sidebar"]}
selectionMode={Gtk.SelectionMode.SINGLE}
selectedIds={openName === null ? [] : [openName]}
onSelectionChanged={([name]) => {
if (name !== undefined) {
navigation.navigate("Note", { name });
}
}}
rowProps={({ item }) => ({ accessibleLabel: item.name })}
renderItem={({ item }) => <NoteRow note={item} />}
/>
</GtkScrolledWindow>
);
};AdwWindowTitle shows a title with a subtitle under it. NotesTitle reads the count with useNotes, so the header waits for the folder with the rest of the window.
Keyboard shortcuts
actionAccels on the application element binds keys to actions by their prefixed names. The application element declares quit in its own actions prop, so its name is app.quit. src/app.tsx now holds only the application element:
import { AdwApplication } from "@gtkx/jsx/adw";
import { GSimpleAction } from "@gtkx/jsx/gio";
import { quit } from "@gtkx/react";
import { Window } from "./components/window.js";
export const App = () => (
<AdwApplication
actionAccels={[
{ detailedActionName: "win.new-note", accels: ["<Control>n"] },
{
detailedActionName: "win.preview",
accels: ["<Control><Shift>p"],
},
{
detailedActionName: "win.shortcuts",
accels: ["<Control>question"],
},
{ detailedActionName: "app.quit", accels: ["<Control>q"] },
]}
actions={<GSimpleAction name="quit" onActivate={quit} />}
>
<Window />
</AdwApplication>
);- Ctrl+N, Ctrl+? and Ctrl+Q are the standard GNOME keys for New, Keyboard Shortcuts and Quit.
<Control>questionis GTK's name for Ctrl+?. - Menus read the same table and show each key beside its item. See Keyboard accelerators.
quit()from@gtkx/reactends the app, as closing the window does.
src/dialogs/shortcuts.tsx lists the keys in an AdwShortcutsDialog:
import { useTranslation } from "@gtkx/i18n";
import {
AdwShortcutsDialog,
AdwShortcutsItem,
AdwShortcutsSection,
} from "@gtkx/jsx/adw";
export const Shortcuts = ({ onClose }: { onClose: () => void }) => {
const { t } = useTranslation();
return (
<AdwShortcutsDialog onClosed={onClose}>
<AdwShortcutsSection title={t("General")}>
<AdwShortcutsItem
title={t("New note")}
actionName="win.new-note"
/>
<AdwShortcutsItem
title={t("Keyboard shortcuts")}
actionName="win.shortcuts"
/>
<AdwShortcutsItem title={t("Quit")} actionName="app.quit" />
</AdwShortcutsSection>
<AdwShortcutsSection title={t("Notes")}>
<AdwShortcutsItem
title={t("Show preview")}
actionName="win.preview"
/>
</AdwShortcutsSection>
</AdwShortcutsDialog>
);
};- An item with an
actionNameshows that action's keys fromactionAccels, so changing a key insrc/app.tsxupdates the dialog too. - The items describe shortcuts and don't register them. See The shortcuts dialog.
Mount the dialogs
Which dialog is open is React state. Window keeps a dialog value that the Keyboard Shortcuts and About actions set, and src/dialogs/dialogs.tsx renders the matching dialog:
import { About } from "./about.js";
import { Shortcuts } from "./shortcuts.js";
export type Dialog =
| { kind: "none" }
| { kind: "about" }
| { kind: "shortcuts" };
type DialogsProps = {
dialog: Dialog;
onClose: () => void;
};
export const Dialogs = ({ dialog, onClose }: DialogsProps) => {
switch (dialog.kind) {
case "about": {
return <About onClose={onClose} />;
}
case "shortcuts": {
return <Shortcuts onClose={onClose} />;
}
case "none": {
return null;
}
}
};import * as Gtk from "@gtkx/gi/gtk";
import { useTranslation } from "@gtkx/i18n";
import { AdwAboutDialog } from "@gtkx/jsx/adw";
export const About = ({ onClose }: { onClose: () => void }) => {
const { t } = useTranslation();
return (
<AdwAboutDialog
onClosed={onClose}
applicationName={t("Notes")}
developerName="GTKX"
website="https://gtkx.dev"
issueUrl="https://github.com/gtkx-org/gtkx/issues"
copyright="© 2026 GTKX Contributors"
licenseType={Gtk.License.MPL_2_0}
developers={[t("GTKX Contributors")]}
comments={t("Markdown notes kept as plain files, built with GTKX.")}
/>
);
};- A dialog presents itself over the window when it mounts and closes when it unmounts. Its close button and Escape call
onClosed, which setsdialogback tonone. WithoutonClosedthe dialog would stay open. See Dialogs. - The about dialog's name, description and credits go through
t(); the developer name and copyright stay as written.AdwAboutDialoglists its other properties, and About dialog metadata covers its credit and legal sections.
Run it
Press Ctrl+N. An Untitled note opens in the editor, and the sidebar title counts one more note. Open the main menu: New Note and Keyboard Shortcuts show their keys. Ctrl+Shift+P switches to the preview and back, and the eye button follows. Ctrl+? opens the shortcuts dialog, and Ctrl+Q quits.


src/components/window.tsx above, after Ctrl+N and with the main menu open.This ends Build Notes: Notes creates, edits, saves and previews notes. Later chapters are optional.