---
description: "Store the notes folder, color scheme, preview state and window size in GSettings and edit them in a preferences dialog."
---

# Add Preferences

Keep the notes folder, color scheme, preview state and window size in GSettings so they survive a restart, and edit the folder and color scheme in a preferences dialog.

## A settings schema

A new file, `data/dev.gtkx.Notes.gschema.xml`, declares the app's keys:

```xml [data/dev.gtkx.Notes.gschema.xml]
<?xml version="1.0" encoding="UTF-8"?>
<schemalist gettext-domain="dev.gtkx.Notes">
  <schema id="dev.gtkx.Notes" path="/dev/gtkx/Notes/">
    <key name="folder" type="s">
      <default>''</default>
      <summary>Notes folder</summary>
      <description>Folder that holds the notes, or empty for Notes in the Documents folder</description>
    </key>
    <key name="color-scheme" type="s">
      <choices>
        <choice value="default"/>
        <choice value="light"/>
        <choice value="dark"/>
      </choices>
      <default>'default'</default>
      <summary>Color scheme</summary>
      <description>Whether the app follows the system style or forces light or dark</description>
    </key>
    <key name="preview" type="b">
      <default>false</default>
      <summary>Show the preview</summary>
      <description>Whether notes open as rendered Markdown instead of in the editor</description>
    </key>
    <key name="window-width" type="i">
      <default>960</default>
      <summary>Window width</summary>
    </key>
    <key name="window-height" type="i">
      <default>640</default>
      <summary>Window height</summary>
    </key>
  </schema>
</schemalist>
```

- The schema ID is the application ID, and `path` is the same ID written as a path. See [Your app's schema](/guide/settings#your-app-s-schema).
- An empty `folder` means `Notes` in the Documents folder, the default from [List the Notes](/tutorial/the-notes-folder).
- `color-scheme` is a string limited to its `<choices>`. `default` follows the system style.
- `gettext-domain` names the catalog that translates the summaries and descriptions. See [Translate settings schemas](/guide/internationalization#translate-settings-schemas).

A module that imports the schema is enough for GTKX to compile it and type its keys. `src/settings.tsx` imports it and describes the color scheme's choices:

```tsx [src/settings.tsx]
import * as Adw from "@gtkx/gi/adw";
import { t } from "@gtkx/i18n";
import schema from "../data/dev.gtkx.Notes.gschema.xml";

export { schema };

export type ColorScheme = (typeof schema.values)["color-scheme"][number];

export const COLOR_SCHEMES: Record<
    ColorScheme,
    { label: () => string; value: Adw.ColorScheme }
> = {
    default: {
        label: () => t("Follow System"),
        value: Adw.ColorScheme.DEFAULT,
    },
    light: { label: () => t("Light"), value: Adw.ColorScheme.FORCE_LIGHT },
    dark: { label: () => t("Dark"), value: Adw.ColorScheme.FORCE_DARK },
};

export const colorSchemeItems = (): { id: ColorScheme; value: string }[] =>
    schema.values["color-scheme"].map((id) => ({
        id,
        value: COLOR_SCHEMES[id].label(),
    }));
```

- `schema.values["color-scheme"]` lists the key's choices, so `ColorScheme` is `"default" | "light" | "dark"`.
- `COLOR_SCHEMES` gives each choice a label and its [`Adw.ColorScheme`](https://gnome.pages.gitlab.gnome.org/libadwaita/doc/1-latest/enum.ColorScheme.html). Each label is a function, so `t` translates it when the dialog renders.
- `colorSchemeItems` builds the items of the dialog's Style row. Each item's `id` is a `ColorScheme`, so the row reports its selection as one.

`SettingsProvider` from `@gtkx/react` wraps the application in `src/app.tsx`. It owns the schema's `Gio.Settings` instance and renders its children once the instance exists. See [The settings instance](/guide/settings#the-settings-instance). The application element moves into `NotesApplication`, below the provider, where it reads the color scheme and sets it on the application's style manager. Ctrl+, runs the `win.preferences` action from [The preferences dialog](#the-preferences-dialog), the [GNOME HIG](https://developer.gnome.org/hig/reference/keyboard.html)'s shortcut for Preferences:

```tsx [src/app.tsx]
import { AdwApplication, AdwStyleManager } from "@gtkx/jsx/adw";
import { GSimpleAction } from "@gtkx/jsx/gio";
import { quit, SettingsProvider, useSetting } from "@gtkx/react";
import { Window } from "./components/window.js";
import { COLOR_SCHEMES, schema } from "./settings.js";

const NotesApplication = () => {
    const [colorScheme] = useSetting(schema, "color-scheme");

    return (
        <AdwApplication
            styleManager={
                <AdwStyleManager
                    colorScheme={COLOR_SCHEMES[colorScheme].value}
                />
            }
            actionAccels={[
                { detailedActionName: "win.new-note", accels: ["<Control>n"] },
                { detailedActionName: "win.rename-note", accels: ["F2"] },
                {
                    detailedActionName: "win.preview",
                    accels: ["<Control><Shift>p"],
                },
                {
                    detailedActionName: "win.preferences",
                    accels: ["<Control>comma"],
                },
                {
                    detailedActionName: "win.shortcuts",
                    accels: ["<Control>question"],
                },
                { detailedActionName: "app.quit", accels: ["<Control>q"] },
            ]}
            actions={<GSimpleAction name="quit" onActivate={quit} />}
        >
            <Window />
        </AdwApplication>
    );
};

export const App = () => (
    <SettingsProvider schema={schema}>
        <NotesApplication />
    </SettingsProvider>
);
```

- `NotesApplication` reads `color-scheme` with `useSetting`. See [Reading and writing a key](/guide/settings#reading-and-writing-a-key).
- The application creates and keeps its [`Adw.StyleManager`](https://gnome.pages.gitlab.gnome.org/libadwaita/doc/1-latest/property.StyleManager.color-scheme.html), so the `styleManager` prop takes an `AdwStyleManager` element that sets props on that object instead of creating one. See [Objects a parent owns](/guide/jsx-elements#objects-a-parent-owns).

## Read and bind settings

The window saves its size, and the navigation opens the folder the settings name:

```tsx [src/components/window.tsx]
import { ToastOverlay, ToastProvider, useToast } from "@gtkx/components";
import type * as Adw from "@gtkx/gi/adw";
import { useTranslation } from "@gtkx/i18n";
import { AdwApplicationWindow, AdwStatusPage } from "@gtkx/jsx/adw";
import { GtkButton } from "@gtkx/jsx/gtk";
import { NavigationContainer } from "@gtkx/navigation";
import { quit, useBindSetting, useSetting } 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 { schema } from "../settings.js";
import { FolderBoundary } from "./folder-boundary.js";
import { MainMenu } from "./main-menu.js";
import { NoteMenu, PreviewToggle } from "./note-menu.js";
import { WindowActions } from "./window-actions.js";

const NoteNavigation = () => {
    const { t } = useTranslation();
    const { show } = useToast();
    const [folderSetting] = useSetting(schema, "folder");
    const open = useNotesStore((state) => state.open);
    const folder = folderSetting === "" ? defaultFolder() : folderSetting;
    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"
                        component={NoteScreen}
                        options={({ route }) => ({
                            title: route.params.name,
                            headerEnd: (
                                <>
                                    <NoteMenu />
                                    <PreviewToggle />
                                </>
                            ),
                        })}
                    />
                </Split.Navigator>
            </NavigationContainer>
        </FolderBoundary>
    );
};

export const Window = () => {
    const { t } = useTranslation();
    const [applicationWindow, setApplicationWindow] =
        useState<Adw.ApplicationWindow | null>(null);
    const [dialog, setDialog] = useState<Dialog>({ kind: "none" });

    useBindSetting({
        schema,
        key: "window-width",
        object: applicationWindow,
        property: "defaultWidth",
    });
    useBindSetting({
        schema,
        key: "window-height",
        object: applicationWindow,
        property: "defaultHeight",
    });

    return (
        <ToastProvider>
            <AdwApplicationWindow
                ref={setApplicationWindow}
                title={t("Notes")}
                widthRequest={360}
                heightRequest={294}
                onCloseRequest={quit}
                actions={<WindowActions onShowDialog={setDialog} />}
            >
                <ToastOverlay>
                    <NoteNavigation />
                </ToastOverlay>
                <Dialogs
                    dialog={dialog}
                    onClose={() => setDialog({ kind: "none" })}
                />
            </AdwApplicationWindow>
        </ToastProvider>
    );
};
```

- `NoteNavigation` reads `folder` with `useSetting`, and falls back to the default folder while the key is empty.
- The `useBindSetting` calls keep `window-width` and `window-height` in step with the window's `defaultWidth` and `defaultHeight`, which GTK updates as the window is resized. They replace the fixed 720 by 480 from [Two screens in a split view](/tutorial/the-note-editor#two-screens-in-a-split-view): the window opens at the size it had when it closed, and at 960 by 640 the first time. See [Binding a key to a property](/guide/settings#binding-a-key-to-a-property).
- The `ref` stores the window in state, so the binds wait until it exists.

`NoteNavigation` now opens a folder that can change, and switches to the new one in place, so the window and the Preferences dialog stay open. When `folder` changes, the effect's cleanup closes the old folder and writes its pending edits, and `FolderBoundary` shows its spinner until the new folder opens with a new navigator at the list, so the screens never render one folder's notes under another.

The store's actions keep working on the folder they started in, and change the list only while that folder is open: `create`, `rename` and `trash` check the folder's abort signal after their file operations, `create` and `rename` resolve to `null` once it has closed, and Undo restores a trashed note into the folder it came from:

```ts [src/notes/notes-store.ts]
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,
    renameNote,
    trashNote,
    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;
    signal: AbortSignal;
    saved: Map<string, string>;
    save: DebouncedFunction<() => void>;
    settle: (name: string) => Promise<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 | null>;
    edit: (name: string, text: string) => void;
    rename: (from: string, to: string) => Promise<string | null>;
    trash: (name: string) => Promise<() => Promise<string | null>>;
};

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 writes = new Map<string, Promise<void>>();
        const failing = new Set<string>();

        const write = (name: string, text: string): void => {
            saved.set(name, text);
            const written = 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);
                    }
                },
            );
            writes.set(name, written);
        };

        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 settle = async (name: string): Promise<void> => {
            save.flush();
            await writes.get(name);
        };

        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, signal, saved, save, settle },
            read: load(),
            notes: new Map(),
        });

        return () => {
            save.flush();
            controller.abort();
            set({ folder: null });
        };
    },
    create: async (base, text) => {
        const { path, signal, saved } = currentFolder(get());
        await get().read;
        const name = await createNote(path, base, text);
        saved.set(name, text);
        if (signal.aborted) {
            return null;
        }
        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();
    },
    rename: async (from, to) => {
        const { path, signal, saved, settle } = currentFolder(get());
        await settle(from);
        await renameNote(path, from, to);
        saved.delete(from);
        if (signal.aborted) {
            return null;
        }
        set((state) => {
            const note = state.notes.get(from);
            const notes = withNote(state.notes, from, null);

            return {
                notes:
                    note === undefined
                        ? notes
                        : withNote(notes, to, { ...note, name: to }),
            };
        });

        return to;
    },
    trash: async (name) => {
        const { path, signal, saved, settle } = currentFolder(get());
        const text = get().notes.get(name)?.text ?? "";
        await settle(name);
        await trashNote(path, name);
        saved.delete(name);
        if (!signal.aborted) {
            set((state) => ({ notes: withNote(state.notes, name, null) }));
        }

        return async () => {
            if (!signal.aborted) {
                return get().create(name, text);
            }
            await createNote(path, name, text);

            return null;
        };
    },
}));

export const useNotes = <T>(select: (state: NotesState) => T): T => {
    use(useNotesStore((state) => state.read));

    return useNotesStore(select);
};
```

Preferences is also the way out of a folder the app can't read. `FolderError` says so, and its button opens the dialog:

```tsx [src/components/folder-boundary.tsx]
import * as Gtk from "@gtkx/gi/gtk";
import { useTranslation } from "@gtkx/i18n";
import {
    AdwHeaderBar,
    AdwSpinner,
    AdwStatusPage,
    AdwToolbarView,
} from "@gtkx/jsx/adw";
import { GtkBox, GtkButton, GtkLabel } from "@gtkx/jsx/gtk";
import { type ReactNode, Suspense } from "react";
import {
    ErrorBoundary,
    type FallbackProps,
    getErrorMessage,
} from "react-error-boundary";
import { useNotesStore } from "../notes/notes-store.js";

const FolderLoading = () => (
    <AdwToolbarView top={<AdwHeaderBar />}>
        <AdwSpinner />
    </AdwToolbarView>
);

const FolderError = ({ error }: FallbackProps) => {
    const { t } = useTranslation();

    return (
        <AdwToolbarView top={<AdwHeaderBar />}>
            <AdwStatusPage
                iconName="folder-symbolic"
                title={t("Can’t Open Folder")}
                description={t("Choose another notes folder in Preferences")}
            >
                <GtkBox orientation={Gtk.Orientation.VERTICAL} spacing={24}>
                    <GtkLabel
                        label={getErrorMessage(error) ?? ""}
                        wrap
                        selectable
                        cssClasses={["dimmed"]}
                    />
                    <GtkButton
                        label={t("Preferences")}
                        actionName="win.preferences"
                        halign={Gtk.Align.CENTER}
                        cssClasses={["pill", "suggested-action"]}
                    />
                </GtkBox>
            </AdwStatusPage>
        </AdwToolbarView>
    );
};

export const FolderBoundary = ({
    folder,
    children,
}: {
    folder: string;
    children: ReactNode;
}) => {
    const isOpen = useNotesStore((state) => state.folder?.path === folder);

    if (!isOpen) {
        return <FolderLoading />;
    }

    return (
        <ErrorBoundary FallbackComponent={FolderError}>
            <Suspense fallback={<FolderLoading />}>{children}</Suspense>
        </ErrorBoundary>
    );
};
```

The button runs `win.preferences` from [The preferences dialog](#the-preferences-dialog). Choosing another folder there makes `FolderBoundary` show its spinner until the store has opened it, which replaces the error boundary along with its error.

The preview state moves from the window to the `preview` key, so a note opens the way the last one was shown, even after a restart. `NoteScreen` and the `preview` action read the key with `useSetting`:

```tsx [src/screens/note-screen.tsx]
import * as Gtk from "@gtkx/gi/gtk";
import { useTranslation } from "@gtkx/i18n";
import { AdwStatusPage } from "@gtkx/jsx/adw";
import { GtkStack, GtkStackPage } from "@gtkx/jsx/gtk";
import type { SplitViewScreenProps } from "@gtkx/navigation";
import { useSetting } from "@gtkx/react";
import { NoteEditor } from "../editor/note-editor.js";
import type { RootParamList } from "../navigation.js";
import { linkedNoteName } from "../notes/files.js";
import { useNotes, useNotesStore } from "../notes/notes-store.js";
import { MarkdownPreview } from "../preview/markdown-preview.js";
import { schema } from "../settings.js";

type NoteScreenProps = SplitViewScreenProps<RootParamList, "Note">;

export const NoteScreen = ({ route, navigation }: NoteScreenProps) => {
    const { t } = useTranslation();
    const notes = useNotes((state) => state.notes);
    const edit = useNotesStore((state) => state.edit);
    const [preview] = useSetting(schema, "preview");
    const { name } = route.params;
    const note = notes.get(name);

    const openLinkedNote = (uri: string): boolean => {
        const linked = linkedNoteName(uri);
        if (linked === null) {
            return false;
        }
        navigation.navigate("Note", { name: linked });

        return true;
    };

    if (note === undefined) {
        return (
            <AdwStatusPage
                iconName="edit-find-symbolic"
                title={t("Note Not Found")}
            />
        );
    }

    return (
        <GtkStack
            visibleChildName={preview ? "preview" : "editor"}
            transitionType={Gtk.StackTransitionType.CROSSFADE}
        >
            <GtkStackPage name="editor">
                <NoteEditor
                    key={name}
                    text={note.text}
                    onChange={(text) => edit(name, text)}
                />
            </GtkStackPage>
            <GtkStackPage name="preview">
                <MarkdownPreview note={note} onActivateLink={openLinkedNote} />
            </GtkStackPage>
        </GtkStack>
    );
};
```

```tsx [src/components/window-actions.tsx]
import { StatefulAction, useToast } from "@gtkx/components";
import { useTranslation } from "@gtkx/i18n";
import { GSimpleAction } from "@gtkx/jsx/gio";
import { useSetting } from "@gtkx/react";
import type { Dialog } from "../dialogs/dialogs.js";
import { closeNoteIfOpen, openNote, useOpenNoteName } from "../navigation.js";
import { useNotesStore } from "../notes/notes-store.js";
import { schema } from "../settings.js";

const message = (error: unknown): string =>
    error instanceof Error ? error.message : String(error);

export const useNoteCommands = () => {
    const { t } = useTranslation();
    const create = useNotesStore((state) => state.create);
    const rename = useNotesStore((state) => state.rename);
    const trash = useNotesStore((state) => state.trash);
    const { show } = useToast();

    const showError = (error: unknown): void => {
        show({ useMarkup: false, title: message(error) });
    };

    const openIfShown = (name: string | null): void => {
        if (name !== null) {
            openNote(name);
        }
    };

    const newNote = async (): Promise<void> => {
        openIfShown(await create(t("Untitled"), ""));
    };

    const renameNote = async (from: string, to: string): Promise<void> => {
        openIfShown(await rename(from, to));
    };

    const trashNote = async (name: string): Promise<void> => {
        closeNoteIfOpen(name);
        const restore = await trash(name);
        show({
            useMarkup: false,
            title: t("“{{name}}” moved to Trash", { name }),
            buttonLabel: t("Undo"),
            onButtonClicked: () => {
                restore().then(openIfShown, showError);
            },
        });
    };

    return {
        newNote: () => newNote().catch(showError),
        renameNote: (from: string, to: string) =>
            renameNote(from, to).catch(showError),
        trashNote: (name: string) => trashNote(name).catch(showError),
        showError,
    };
};

type WindowActionsProps = { onShowDialog: (dialog: Dialog) => void };

export const WindowActions = ({ onShowDialog }: WindowActionsProps) => {
    const { newNote, trashNote } = useNoteCommands();
    const openName = useOpenNoteName();
    const [preview, setPreview] = useSetting(schema, "preview");

    return (
        <>
            <GSimpleAction name="new-note" onActivate={() => void newNote()} />
            <GSimpleAction
                name="rename-note"
                enabled={openName !== null}
                onActivate={() => {
                    if (openName !== null) {
                        onShowDialog({ kind: "rename", name: openName });
                    }
                }}
            />
            <GSimpleAction
                name="trash-note"
                enabled={openName !== null}
                onActivate={() => {
                    if (openName !== null) {
                        void trashNote(openName);
                    }
                }}
            />
            <StatefulAction
                name="preview"
                state={preview}
                onStateChange={setPreview}
            />
            <GSimpleAction
                name="preferences"
                onActivate={() => onShowDialog({ kind: "preferences" })}
            />
            <GSimpleAction
                name="shortcuts"
                onActivate={() => onShowDialog({ kind: "shortcuts" })}
            />
            <GSimpleAction
                name="about"
                onActivate={() => onShowDialog({ kind: "about" })}
            />
        </>
    );
};
```

- `onStateChange` writes the key instead of the window's state, and the toggle button follows the action as before.
- `useNoteCommands` returns `showError` along with the commands.
- `openIfShown` opens a note only when the action resolved to its name, not to `null` after a folder switch.

## The preferences dialog

The `win.preferences` action shows the preferences dialog. The main menu and the shortcuts dialog list it:

```tsx [src/components/main-menu.tsx]
import { 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("Preferences"),
                                    action: "win.preferences",
                                },
                                {
                                    label: t("Keyboard Shortcuts"),
                                    action: "win.shortcuts",
                                },
                                {
                                    label: t("About Notes"),
                                    action: "win.about",
                                },
                            ],
                        },
                    ]}
                />
            }
        />
    );
};
```

```tsx [src/dialogs/shortcuts.tsx]
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("Preferences")}
                    actionName="win.preferences"
                />
                <AdwShortcutsItem
                    title={t("Keyboard shortcuts")}
                    actionName="win.shortcuts"
                />
                <AdwShortcutsItem title={t("Quit")} actionName="app.quit" />
            </AdwShortcutsSection>
            <AdwShortcutsSection title={t("Notes")}>
                <AdwShortcutsItem
                    title={t("Search notes")}
                    accelerator="<Control>f"
                />
                <AdwShortcutsItem
                    title={t("Rename note")}
                    actionName="win.rename-note"
                />
                <AdwShortcutsItem
                    title={t("Show preview")}
                    actionName="win.preview"
                />
            </AdwShortcutsSection>
        </AdwShortcutsDialog>
    );
};
```

The `Dialog` union gains a `preferences` kind:

```tsx [src/dialogs/dialogs.tsx]
import { About } from "./about.js";
import { Preferences } from "./preferences.js";
import { RenameDialog } from "./rename-dialog.js";
import { Shortcuts } from "./shortcuts.js";

export type Dialog =
    | { kind: "none" }
    | { kind: "about" }
    | { kind: "shortcuts" }
    | { kind: "preferences" }
    | { kind: "rename"; name: string };

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 "preferences": {
            return <Preferences onClose={onClose} />;
        }
        case "rename": {
            return <RenameDialog name={dialog.name} onClose={onClose} />;
        }
        case "none": {
            return null;
        }
    }
};
```

`src/dialogs/preferences.tsx` holds the dialog:

```tsx [src/dialogs/preferences.tsx]
import { ComboRow } from "@gtkx/components";
import type * as Gio from "@gtkx/gi/gio";
import * as Gtk from "@gtkx/gi/gtk";
import { useTranslation } from "@gtkx/i18n";
import {
    AdwActionRow,
    AdwPreferencesDialog,
    AdwPreferencesGroup,
    AdwPreferencesPage,
} from "@gtkx/jsx/adw";
import { GtkButton, GtkFileDialog } from "@gtkx/jsx/gtk";
import {
    createPortal,
    rootElement,
    useParentWindow,
    useSetting,
} from "@gtkx/react";
import { useState } from "react";
import { useNoteCommands } from "../components/window-actions.js";
import { defaultFolder, displayFolder } from "../notes/files.js";
import { colorSchemeItems, schema } from "../settings.js";

const isDismissal = (error: unknown): boolean =>
    error instanceof Gtk.DialogError &&
    (error.code === Gtk.DialogError.DISMISSED ||
        error.code === Gtk.DialogError.CANCELLED);

const FolderRow = () => {
    const { t } = useTranslation();
    const { showError } = useNoteCommands();
    const parentWindow = useParentWindow();
    const [folder, setFolder] = useSetting(schema, "folder");
    const [dialog, setDialog] = useState<Gtk.FileDialog | null>(null);

    const choose = async (fileDialog: Gtk.FileDialog): Promise<void> => {
        let file: Gio.File;
        try {
            file = await fileDialog.selectFolder(parentWindow);
        } catch (error) {
            if (!isDismissal(error)) {
                showError(error);
            }

            return;
        }
        const path = file.getPath();
        if (path !== null) {
            setFolder(path);
        }
    };

    return (
        <>
            {createPortal(
                <GtkFileDialog
                    ref={setDialog}
                    title={t("Choose a Notes Folder")}
                />,
                rootElement,
            )}
            <AdwActionRow
                title={t("Notes Folder")}
                subtitle={displayFolder(
                    folder === "" ? defaultFolder() : folder,
                )}
                suffix={
                    <>
                        {folder !== "" && (
                            <GtkButton
                                iconName="edit-undo-symbolic"
                                tooltipText={t("Use the Default Folder")}
                                valign={Gtk.Align.CENTER}
                                cssClasses={["flat"]}
                                onClicked={() => setFolder("")}
                            />
                        )}
                        <GtkButton
                            iconName="folder-open-symbolic"
                            tooltipText={t("Choose Folder")}
                            valign={Gtk.Align.CENTER}
                            cssClasses={["flat"]}
                            sensitive={dialog !== null}
                            onClicked={() => {
                                if (dialog !== null) {
                                    void choose(dialog);
                                }
                            }}
                        />
                    </>
                }
            />
        </>
    );
};

type PreferencesProps = { onClose: () => void };

export const Preferences = ({ onClose }: PreferencesProps) => {
    const { t } = useTranslation();
    const [colorScheme, setColorScheme] = useSetting(schema, "color-scheme");

    return (
        <AdwPreferencesDialog onClosed={onClose} title={t("Preferences")}>
            <AdwPreferencesPage
                title={t("General")}
                iconName="preferences-system-symbolic"
            >
                <AdwPreferencesGroup title={t("Appearance")}>
                    <ComboRow
                        title={t("Style")}
                        items={colorSchemeItems()}
                        selectedId={colorScheme}
                        onSelectionChanged={(id) => {
                            if (id !== null) {
                                setColorScheme(id);
                            }
                        }}
                    />
                </AdwPreferencesGroup>
                <AdwPreferencesGroup title={t("Storage")}>
                    <FolderRow />
                </AdwPreferencesGroup>
            </AdwPreferencesPage>
        </AdwPreferencesDialog>
    );
};
```

- [`AdwPreferencesDialog`](https://gnome.pages.gitlab.gnome.org/libadwaita/doc/1-latest/class.PreferencesDialog.html) holds pages of grouped rows. Notes has one page, with an Appearance group and a Storage group.
- `ComboRow` from `@gtkx/components` renders the Style row. `selectedId` shows the key's value, and `onSelectionChanged` writes the chosen one, which the application's style manager then follows. The row takes its ID type from the items, so the ID arrives as `ColorScheme | null`, and it is `null` only for a row without items. See [DropDown](/guide/components#dropdown).
- `FolderRow` keeps a `GtkFileDialog` in state through a portal and awaits its `selectFolder`, as [Awaiting async operations](/guide/calling-native-apis#awaiting-async-operations) shows. `useParentWindow` returns the Notes window, so the file dialog opens over it. See [Finding the parent window](/guide/modals-and-portals#finding-the-parent-window).
- Closing the file dialog rejects with `Gtk.DialogError.DISMISSED`, which `isDismissal` ignores. `FolderRow` shows any other failure itself, with the `showError` toast from `useNoteCommands`, so no callback has to pass through the window and `Dialogs`. A folder without a local path, for which `getPath` returns `null`, is ignored.
- Once a folder is chosen, a second button sets the key back to empty, which returns to the default folder.
- The row's subtitle shows the folder in use. `displayFolder`, a new function in `src/notes/files.ts`, writes the home folder as `~`:

```ts [src/notes/files.ts]
import * as Gio from "@gtkx/gi/gio";
import * as GLib from "@gtkx/gi/glib";
import {
    access,
    mkdir,
    readdir,
    readFile,
    rename,
    stat,
    writeFile,
} from "node:fs/promises";
import { join } from "node:path";
import 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 displayFolder = (path: string): string => {
    const home = GLib.getHomeDir();

    return path.startsWith(`${home}/`) ? `~${path.slice(home.length)}` : path;
};

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 exists = async (path: string): Promise<boolean> => {
    try {
        await access(path);

        return true;
    } catch (error) {
        if (isMissing(error)) {
            return false;
        }

        throw error;
    }
};

export const renameNote = async (
    folder: string,
    from: string,
    to: string,
): Promise<void> => {
    const target = notePath(folder, to);
    if (await exists(target)) {
        throw new Error(`${target} already exists`);
    }
    await rename(notePath(folder, from), target);
};

export const trashNote = async (
    folder: string,
    name: string,
): Promise<void> => {
    await Gio.File.newForPath(notePath(folder, name)).trashAsync(
        GLib.PRIORITY_DEFAULT,
    );
};

export const isValidName = (name: string): boolean =>
    name.trim() === name &&
    name !== "" &&
    !name.startsWith(".") &&
    !name.includes("/");

const isTaken = (error: unknown): boolean =>
    error instanceof Error && "code" in error && error.code === "EEXIST";

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;
            }
        }
    }
};
```

## Run it

Open Preferences with Ctrl+, and choose Dark: the window turns dark at once. Choose another notes folder: the list shows that folder's notes, and Preferences stays open. Toggle the preview, resize the window and quit. The app opens again with the same style, folder, preview state and size.

<figure class="result">
    <img class="result-light" src="/figures/tutorial-preferences-and-theming-light.png" width="720" height="480" loading="lazy" alt="The Notes window with the Preferences dialog open: an Appearance group with a Style row set to Light, and a Storage group with a Notes Folder row showing ~/Notes and a folder button." />
    <img class="result-dark" src="/figures/tutorial-preferences-and-theming-dark.png" width="720" height="480" loading="lazy" alt="The Notes window with the Preferences dialog open: an Appearance group with a Style row set to Dark, and a Storage group with a Notes Folder row showing ~/Notes and a folder button." />
    <figcaption>Captured from <a href="#the-preferences-dialog"><code>src/dialogs/preferences.tsx</code></a> above, opened from the main menu.</figcaption>
</figure>
