Skip to content

Chapter 10 of 17

Rename, Trash, and Undo ​

Rename the open note in a dialog that checks the new name, and move notes to the desktop trash with an Undo toast.

Rename a note ​

A note menu joins the preview toggle at the end of the note's header bar. src/components/note-menu.tsx holds both buttons, and the menu's items run two new window actions, win.rename-note and win.trash-note:

src/components/note-menu.tsx
tsx
import { useTranslation } from "@gtkx/i18n";
import { GMenu } from "@gtkx/jsx/gio";
import { GtkMenuButton, GtkToggleButton } from "@gtkx/jsx/gtk";

export const PreviewToggle = () => {
    const { t } = useTranslation();

    return (
        <GtkToggleButton
            iconName="view-reveal-symbolic"
            tooltipText={t("Preview (Ctrl+Shift+P)")}
            actionName="win.preview"
        />
    );
};

export const NoteMenu = () => {
    const { t } = useTranslation();

    return (
        <GtkMenuButton
            iconName="view-more-symbolic"
            tooltipText={t("Note Menu")}
            menuModel={
                <GMenu
                    items={[
                        {
                            section: [
                                {
                                    label: t("Rename…"),
                                    action: "win.rename-note",
                                },
                                {
                                    label: t("Move to Trash"),
                                    action: "win.trash-note",
                                },
                            ],
                        },
                    ]}
                />
            }
        />
    );
};

F2 renames the open note, and the shortcuts dialog lists the key:

src/app.tsx
tsx
import { AdwApplication } from "@gtkx/jsx/adw";
import { GSimpleAction } from "@gtkx/jsx/gio";
import { quit } from "@gtkx/react";
import { Window } from "./components/window.js";

export const App = () => (
    <AdwApplication
        actionAccels={[
            { detailedActionName: "win.new-note", accels: ["<Control>n"] },
            { detailedActionName: "win.rename-note", accels: ["F2"] },
            {
                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>
);
src/dialogs/shortcuts.tsx
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("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>
    );
};

Both actions need the open note's name and are disabled while no note is open. In src/navigation.ts, useOpenNoteName switches to useRootNavigationState, and two new functions read the route through the container ref:

src/navigation.ts
ts
import {
    createNavigationContainerRef,
    createSplitViewNavigator,
    useRootNavigationState,
} 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 openNote = (name: string): void => {
    navigationRef.navigate("Note", { name });
};

export const openNoteName = (): string | null => {
    const route = navigationRef.isReady()
        ? navigationRef.getCurrentRoute()
        : undefined;

    return route?.name === "Note" ? route.params.name : null;
};

export const closeNoteIfOpen = (name: string): void => {
    if (openNoteName() === name) {
        navigationRef.goBack();
    }
};

export const useOpenNoteName = (): string | null =>
    useRootNavigationState(navigationRef, (state) => {
        const route = state.routes.at(-1);

        return route?.name === "Note" ? (route.params?.name ?? null) : null;
    }) ?? null;
  • useRootNavigationState re-renders its component after every navigation, wherever it renders (Hooks). openNoteName reads the name when a command runs, through the container's ref methods. Both give null while no note is open or before the container is ready, and closeNoteIfOpen goes back to the list when the given note is open.

The note screen's headerEnd holds both buttons from note-menu.tsx:

src/components/window.tsx
tsx
import { ToastOverlay, ToastProvider, useToast } from "@gtkx/components";
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 } 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 { NoteMenu, PreviewToggle } from "./note-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: (
                                <>
                                    <NoteMenu />
                                    <PreviewToggle />
                                </>
                            ),
                        })}
                    >
                        {(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>
    );
};

Rename shows RenameDialog, an AdwAlertDialog with an entry for the new name:

src/dialogs/rename-dialog.tsx
tsx
import * as Adw from "@gtkx/gi/adw";
import { useTranslation } from "@gtkx/i18n";
import { AdwAlertDialog } from "@gtkx/jsx/adw";
import { GtkEntry } from "@gtkx/jsx/gtk";
import { useState } from "react";
import { useNoteCommands } from "../components/window-actions.js";
import { isValidName } from "../notes/files.js";
import { useNotesStore } from "../notes/notes-store.js";

type RenameDialogProps = { name: string; onClose: () => void };

export const RenameDialog = ({ name, onClose }: RenameDialogProps) => {
    const { t } = useTranslation();
    const { renameNote } = useNoteCommands();
    const [draft, setDraft] = useState(name);
    const isTaken = useNotesStore((state) => state.notes.has(draft));
    const canRename = draft !== name && isValidName(draft) && !isTaken;

    return (
        <AdwAlertDialog
            heading={t("Rename Note")}
            defaultResponse="rename"
            closeResponse="cancel"
            responses={[
                { id: "cancel", label: t("Cancel") },
                {
                    id: "rename",
                    label: t("Rename"),
                    appearance: Adw.ResponseAppearance.SUGGESTED,
                    isEnabled: canRename,
                },
            ]}
            onResponse={(id) => {
                if (id === "rename" && canRename) {
                    void renameNote(name, draft);
                }
                onClose();
            }}
        >
            <GtkEntry
                text={draft}
                accessibleLabel={t("Note name")}
                activatesDefault
                onChanged={(self) => {
                    setDraft(self.text);
                }}
            />
        </AdwAlertDialog>
    );
};
  • draft holds the entry's text and starts as the current name. onChanged updates it on every keystroke.
  • canRename enables the Rename response only for a name that is new, valid and not taken by another note. isTaken selects from the store whether a note already has the draft name, and isValidName is in Move to the trash.
  • Picking Rename calls the renameNote command from useNoteCommands, which Undo from a toast shows.
  • defaultResponse with the entry's activatesDefault makes Enter pick Rename, and closeResponse makes Escape pick Cancel. Either way onResponse runs and calls onClose, which unmounts the dialog. See Dialogs.

The Dialog union gains a rename kind that carries the note's name, and Dialogs renders RenameDialog for it:

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

export type Dialog =
    | { kind: "none" }
    | { kind: "about" }
    | { kind: "shortcuts" }
    | { 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 "rename": {
            return <RenameDialog name={dialog.name} onClose={onClose} />;
        }
        case "none": {
            return null;
        }
    }
};

Move to the trash ​

src/notes/files.ts gains the file operations:

src/notes/files.ts
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 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;
            }
        }
    }
};
  • Node's rename replaces a file that already has the new name, so renameNote checks for one first and fails instead. Unlike the wx flag in Window actions, the check and the rename are separate steps: a file that another program creates between them is still replaced.
  • trashNote moves the file to the desktop trash with Gio.File.trashAsync, so a mistaken trash can also be undone from the Trash in Files. GTKX turns GIO's async and finish pair into one method that returns a promise and rejects on failure. See Async Operations.
  • isValidName rejects an empty name, a name with whitespace at either end, a /, which would point into another folder, and a leading ., which hides the file from the note list.

The store's rename and trash actions run these operations and update the list:

src/notes/notes-store.ts
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;
    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>;
    edit: (name: string, text: string) => void;
    rename: (from: string, to: string) => Promise<void>;
    trash: (name: string) => Promise<() => Promise<string>>;
};

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, saved, save, settle },
            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();
    },
    rename: async (from, to) => {
        const { path, saved, settle } = currentFolder(get());
        await settle(from);
        await renameNote(path, from, to);
        saved.delete(from);
        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 }),
            };
        });
    },
    trash: async (name) => {
        const { path, saved, settle } = currentFolder(get());
        const text = get().notes.get(name)?.text ?? "";
        await settle(name);
        await trashNote(path, name);
        saved.delete(name);
        set((state) => ({ notes: withNote(state.notes, name, null) }));

        return () => get().create(name, text);
    },
}));

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

    return useNotesStore(select);
};
  • settle runs a save still waiting out its delay from Save and Watch Files at once, then waits for the note's latest write, which write now keeps in writes. Without it, that save would write the old name after the rename or trash and bring the file back.
  • saved.delete drops the text the app last wrote under the old name. Otherwise a note restored from the Trash in Files would match that text, and the watcher would skip it as the app's own write.
  • rename moves the note to its new key in the list and keeps its text and modification time.
  • trash keeps the note's text and resolves to a function that restores the note by writing the text back with create. Undo from a toast calls it.

Undo from a toast ​

useNoteCommands gains the commands that the dialog and the actions run:

src/components/window-actions.tsx
tsx
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 { closeNoteIfOpen, openNote, useOpenNoteName } from "../navigation.js";
import { useNotesStore } from "../notes/notes-store.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 newNote = async (): Promise<void> => {
        openNote(await create(t("Untitled"), ""));
    };

    const renameNote = async (from: string, to: string): Promise<void> => {
        await rename(from, to);
        openNote(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(openNote, showError);
            },
        });
    };

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

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

export const WindowActions = ({
    preview,
    onPreviewChange,
    onShowDialog,
}: WindowActionsProps) => {
    const { newNote, trashNote } = useNoteCommands();
    const openName = useOpenNoteName();

    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={onPreviewChange}
            />
            <GSimpleAction
                name="shortcuts"
                onActivate={() => onShowDialog({ kind: "shortcuts" })}
            />
            <GSimpleAction
                name="about"
                onActivate={() => onShowDialog({ kind: "about" })}
            />
        </>
    );
};
  • WindowActions calls useOpenNoteName, so opening and closing a note enables and disables rename-note and trash-note, and their menu items with them.
  • renameNote opens the note under its new name once the file is renamed. A failure, such as a name another program took after the dialog checked it, shows in a toast.
  • The trashNote command closes the note if it is open, so the editor can't save into a file that is gone, and moves the file to the trash.
  • The toast that follows has an Undo button, the GNOME HIG's common use for a toast after a destructive action. See Toasts.
  • Undo calls the function that trash returned, which writes the kept text back with create, and opens the note. GIO doesn't say where in the trash the file went, so Undo makes a new file rather than restoring the old one, which stays in the trash. The new file has a new modification time, so the note returns at the top of the list. If another note took the name in the meantime, create picks the next free one, and openNote opens whichever name it used.

Run it ​

Open a note and press F2. Rename stays disabled until the name is new, valid and unused, and Enter renames the note. Open the note menu and choose Move to Trash: the note leaves the list, the sidebar title counts one fewer note, and a toast offers Undo. Click Undo and the note comes back and opens.

The Notes window after Recipes was moved to the trash: the sidebar lists four notes, the content pane reads No Note Selected, and a toast at the bottom reads “Recipes” moved to Trash with an Undo button.The Notes window after Recipes was moved to the trash: the sidebar lists four notes, the content pane reads No Note Selected, and a toast at the bottom reads “Recipes” moved to Trash with an Undo button.
Captured from src/components/window-actions.tsx above, after Move to Trash on Recipes.