chore(editor): name the commit action by host and surface its shortcut

The save button now reads Save in the composer, Update when editing, and
Comment in the comment editor, with a Cmd/Ctrl+Enter chip inside it that
is
hidden on coarse pointers. Saving keeps the verb and swaps the chip for
a
spinner in the same grid cell, so the button no longer changes width;
the
"Saving..." string is removed from every locale. Hosts that close after
saving hold a short "Saved" confirmation while the caches refresh, then
reset and close; the in-place composer clears immediately as before.
This commit is contained in:
johnnyjoygh 2026-09-05 10:19:22 +08:00
parent 5ad4aea565
commit 50e71e2192
54 changed files with 147 additions and 62 deletions

View file

@ -1,18 +1,40 @@
import { CheckIcon, CornerDownLeftIcon, LoaderIcon } from "lucide-react";
import type { FC } from "react";
import { Button } from "@/components/ui/button";
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
import { cn } from "@/lib/utils";
import type { Location, Visibility } from "@/types/proto/api/v1/memo_service_pb";
import { useTranslate } from "@/utils/i18n";
import { primaryModifierGlyph } from "@/utils/platform";
import { validationService } from "../services";
import { useEditorContext, useEditorSelector } from "../state";
import type { EditorToolbarProps } from "../types";
import InsertMenu from "./InsertMenu";
import VisibilitySelector from "./VisibilitySelector";
/**
* Shortcut chip inside the commit button. While saving, a spinner takes the
* chip's place; both layers share one grid cell so the button keeps its width
* across the swap. Hidden on coarse pointers, where there is no keyboard to hint.
*/
const ShortcutChip: FC<{ busy: boolean }> = ({ busy }) => (
<kbd
aria-hidden
className="grid place-items-center rounded-[4px] bg-primary-foreground/20 px-1 py-0.5 font-sans text-[11px] leading-none font-medium pointer-coarse:hidden"
>
<span className={cn("col-start-1 row-start-1 inline-flex items-center gap-px", busy && "invisible")}>
{primaryModifierGlyph()}
<CornerDownLeftIcon className="size-2.5" strokeWidth={2.5} />
</span>
<LoaderIcon className={cn("col-start-1 row-start-1 size-2.5 animate-spin", !busy && "invisible")} strokeWidth={3} />
</kbd>
);
export const EditorToolbar: FC<EditorToolbarProps> = ({
onSave,
onCancel,
memoName,
parentMemoName,
space,
onAudioRecorderClick,
viewToggles,
@ -27,14 +49,23 @@ export const EditorToolbar: FC<EditorToolbarProps> = ({
const blockedReason = useEditorSelector((s) => validationService.canSave(s).reason);
const blockedReasonDetail = useEditorSelector((s) => validationService.canSave(s).detail);
const isSaving = useEditorSelector((s) => s.ui.isLoading.saving);
const justSaved = useEditorSelector((s) => s.ui.justSaved);
const isUploading = useEditorSelector((s) => s.ui.isLoading.uploading);
const location = useEditorSelector((s) => s.metadata.location);
const visibility = useEditorSelector((s) => s.metadata.visibility);
const blockedMessage = valid
? undefined
: blockedReason
? t(blockedReason, blockedReasonDetail ? { url: blockedReasonDetail } : undefined)
: t("editor.validation.cannot-save");
// The save transaction is in flight or its confirmation is holding the
// editor open; either way the toolbar is frozen.
const committing = isSaving || justSaved;
const blockedMessage =
valid || committing
? undefined
: blockedReason
? t(blockedReason, blockedReasonDetail ? { url: blockedReasonDetail } : undefined)
: t("editor.validation.cannot-save");
// The verb names what the host does with the memo: an existing memo is
// updated, a reply becomes a comment, and a new memo is simply saved. A memo
// is stored with a visibility, not posted, so messaging verbs stay out.
const commitLabel = memoName ? t("common.update") : parentMemoName ? t("editor.comment") : t("editor.save");
const handleLocationChange = (next?: Location) => {
dispatch(actions.setMetadata({ location: next }));
@ -44,12 +75,24 @@ export const EditorToolbar: FC<EditorToolbarProps> = ({
dispatch(actions.setMetadata({ visibility: next }));
};
const commitButton = justSaved ? (
<Button disabled>
{t("editor.saved")}
<CheckIcon className="size-3.5" strokeWidth={2.5} />
</Button>
) : (
<Button onClick={onSave} disabled={isSaving || !valid}>
{commitLabel}
<ShortcutChip busy={isSaving} />
</Button>
);
return (
<div className="w-full flex flex-row justify-between items-center mb-2">
<div className="flex flex-row justify-start items-center gap-1">
<InsertMenu
isUploading={isUploading}
isSaving={isSaving}
isSaving={committing}
location={location}
onLocationChange={handleLocationChange}
memoName={memoName}
@ -62,24 +105,20 @@ export const EditorToolbar: FC<EditorToolbarProps> = ({
<div className="flex flex-row justify-end items-center gap-2">
{onCancel && (
<Button variant="ghost" onClick={onCancel} disabled={isSaving}>
<Button variant="ghost" onClick={onCancel} disabled={committing}>
{t("common.cancel")}
</Button>
)}
{!valid && !isSaving && blockedMessage ? (
{blockedMessage ? (
<Tooltip>
<TooltipTrigger render={<span className="inline-flex" tabIndex={0} aria-label={blockedMessage} />}>
<Button onClick={onSave} disabled>
{t("editor.save")}
</Button>
{commitButton}
</TooltipTrigger>
<TooltipContent side="top">{blockedMessage}</TooltipContent>
</Tooltip>
) : (
<Button onClick={onSave} disabled={isSaving}>
{isSaving ? t("editor.saving") : t("editor.save")}
</Button>
commitButton
)}
</div>
</div>

View file

@ -11,6 +11,9 @@ import { useTranslate } from "@/utils/i18n";
import { errorService, memoService, validationService } from "../services";
import { useEditorContext } from "../state";
/** How long a closing host shows "Saved" before it unmounts the editor. */
const SAVED_CONFIRMATION_MS = 900;
interface UseMemoSaveOptions {
memoName?: string;
parentMemoName?: string;
@ -44,6 +47,9 @@ export function useMemoSave({
return useCallback(async () => {
const state = getState();
// A repeated shortcut during the saved confirmation is not an error worth
// a toast; the save already landed and the host is closing.
if (state.ui.justSaved) return;
const { valid, reason, detail } = validationService.canSave(state);
if (!valid) {
toast.error(reason ? t(reason, detail ? { url: detail } : undefined) : t("editor.validation.cannot-save"));
@ -64,7 +70,7 @@ export function useMemoSave({
// Prevent the autosave unmount flush from restoring the saved draft.
discardDraft();
const invalidationPromises = [
const invalidationPromises: Promise<unknown>[] = [
queryClient.invalidateQueries({ queryKey: memoKeys.lists() }),
queryClient.invalidateQueries({ queryKey: userKeys.stats() }),
queryClient.invalidateQueries({ queryKey: attachmentKeys.lists() }),
@ -76,6 +82,14 @@ export function useMemoSave({
invalidationPromises.push(queryClient.invalidateQueries({ queryKey: memoKeys.comments(parentMemoName) }));
invalidationPromises.push(queryClient.invalidateQueries({ queryKey: memoKeys.detail(parentMemoName) }));
}
// Hosts that close after saving (edit, comment) hold a brief "Saved"
// confirmation on the toolbar while the caches refresh underneath. The
// in-place composer clears immediately, so it shows nothing.
if (memoName || parentMemoName) {
dispatch(actions.setLoading("saving", false));
dispatch(actions.setJustSaved(true));
invalidationPromises.push(new Promise((resolve) => setTimeout(resolve, SAVED_CONFIRMATION_MS)));
}
await Promise.all(invalidationPromises);
dispatch(actions.reset());
@ -99,6 +113,7 @@ export function useMemoSave({
});
} finally {
dispatch(actions.setLoading("saving", false));
dispatch(actions.setJustSaved(false));
}
}, [
actions,

View file

@ -365,6 +365,7 @@ const MemoEditorImpl: React.FC<MemoEditorProps> = ({
onSave={handleSave}
onCancel={onCancel ? handleCancel : undefined}
memoName={memoName}
parentMemoName={parentMemoName}
space={editorSpace}
onAudioRecorderClick={handleAudioRecorderClick}
viewToggles={viewToggles}

View file

@ -41,8 +41,9 @@ export const validationService = {
return { valid: false, reason: "editor.validation.finish-audio-recording" };
}
// Cannot save while already saving
if (state.ui.isLoading.saving) {
// Cannot save while already saving, or while the saved confirmation holds
// the editor open for its closing host.
if (state.ui.isLoading.saving || state.ui.justSaved) {
return { valid: false, reason: "editor.validation.save-in-progress" };
}

View file

@ -56,6 +56,11 @@ export const editorActions = {
payload: timestamps,
}),
setJustSaved: (value: boolean): EditorAction => ({
type: "SET_JUST_SAVED",
payload: value,
}),
setRecorderBusy: (value: boolean): EditorAction => ({
type: "SET_RECORDER_BUSY",
payload: value,

View file

@ -95,6 +95,15 @@ export function editorReducer(state: EditorState, action: EditorAction): EditorS
recorderBusy: action.payload,
};
case "SET_JUST_SAVED":
return {
...state,
ui: {
...state.ui,
justSaved: action.payload,
},
};
case "RESET":
return createInitialState();

View file

@ -23,6 +23,10 @@ export interface EditorState {
uploading: boolean;
loading: boolean;
};
/** Save landed and the editor is about to close; the toolbar shows a brief
* confirmation instead of the commit verb. Only hosts that unmount after
* saving set it; the in-place composer resets immediately. */
justSaved: boolean;
};
timestamps: {
createTime?: Date;
@ -46,6 +50,7 @@ export type EditorAction =
| { type: "SET_PENDING_INLINE_IMAGE_INSERTIONS"; payload: number }
| { type: "SET_TIMESTAMPS"; payload: Partial<EditorState["timestamps"]> }
| { type: "SET_RECORDER_BUSY"; payload: boolean }
| { type: "SET_JUST_SAVED"; payload: boolean }
| { type: "RESET" };
// Module-private template for createInitialState.
@ -66,6 +71,7 @@ const defaultState: EditorState = {
uploading: false,
loading: false,
},
justSaved: false,
},
timestamps: {
createTime: undefined,

View file

@ -58,6 +58,8 @@ export interface EditorToolbarProps {
onSave: () => void;
onCancel?: () => void;
memoName?: string;
/** Set when the editor composes a comment on this memo; picks the commit verb. */
parentMemoName?: string;
/** The Space that owns the memo being created or edited, if any. */
space?: string;
onAudioRecorderClick: () => void;

View file

@ -125,7 +125,6 @@
"focus-mode": "وضع التركيز",
"no-changes-detected": "لم يتم الكشف عن تغييرات",
"save": "حفظ",
"saving": "جارِ الحفظ...",
"insert-menu": {
"add-location": "أضف الموقع",
"link-memo": "مذكرة الارتباط",

View file

@ -170,7 +170,6 @@
},
"no-changes-detected": "Не са открити промени",
"save": "Запазване",
"saving": "Запазва се...",
"audio-recorder": {
"attachment-label": "Аудио запис",
"attachment-label-with-time": "Аудио запис {{time}}",

View file

@ -133,7 +133,6 @@
},
"no-changes-detected": "No s'han detectat canvis",
"save": "Guarda",
"saving": "Guardant...",
"audio-recorder": {
"attachment-label": "Gravació d'àudio",
"attachment-label-with-time": "Gravació d'àudio {{time}}",

View file

@ -133,7 +133,6 @@
},
"no-changes-detected": "Nebyly zjištěny žádné změny",
"save": "Uložit",
"saving": "Ukládání...",
"audio-recorder": {
"attachment-label": "Záznam zvuku",
"attachment-label-with-time": "Záznam zvuku {{time}}",

View file

@ -170,7 +170,6 @@
},
"no-changes-detected": "Ingen ændringer registreret",
"save": "Spare",
"saving": "Gemmer...",
"audio-recorder": {
"attachment-label": "Lydoptagelse",
"attachment-label-with-time": "Lydoptagelse {{time}}",

View file

@ -133,7 +133,6 @@
},
"no-changes-detected": "Keine Änderungen erkannt",
"save": "Speichern",
"saving": "Speichern...",
"audio-recorder": {
"attachment-label": "Audioaufnahme",
"attachment-label-with-time": "Audioaufnahme {{time}}",

View file

@ -170,7 +170,6 @@
},
"no-changes-detected": "Δεν εντοπίστηκαν αλλαγές",
"save": "Εκτός",
"saving": "Οικονομία...",
"audio-recorder": {
"attachment-label": "Ηχογράφηση",
"attachment-label-with-time": "Εγγραφή ήχου {{time}}",

View file

@ -133,7 +133,6 @@
},
"no-changes-detected": "No changes detected",
"save": "Save",
"saving": "Saving...",
"audio-recorder": {
"attachment-label": "Audio recording",
"attachment-label-with-time": "Audio recording {{time}}",

View file

@ -237,6 +237,7 @@
"any-thoughts": "Any thoughts...",
"exit-focus-mode": "Exit Focus Mode",
"focus-mode": "Focus Mode",
"comment": "Comment",
"formatting-toolbar": "Formatting toolbar",
"format": {
"heading": "Heading",
@ -272,7 +273,7 @@
"new-memo": "New memo",
"no-changes-detected": "No changes detected",
"save": "Save",
"saving": "Saving...",
"saved": "Saved",
"validation": {
"cannot-save": "Cannot save",
"content-required": "Content, attachment, or file required",

View file

@ -133,7 +133,6 @@
},
"no-changes-detected": "No se detectaron cambios",
"save": "Guardar",
"saving": "Guardando...",
"audio-recorder": {
"attachment-label": "Grabación de audio",
"attachment-label-with-time": "Grabación de audio {{time}}",

View file

@ -170,7 +170,6 @@
},
"no-changes-detected": "Muudatusi ei tuvastatud",
"save": "Salvesta",
"saving": "Salvestamine...",
"audio-recorder": {
"attachment-label": "Helisalvestus",
"attachment-label-with-time": "Helisalvestus {{time}}",

View file

@ -125,7 +125,6 @@
"focus-mode": "حالت تمرکز",
"no-changes-detected": "تغییری شناسایی نشد",
"save": "ذخیره",
"saving": "در حال ذخیره...",
"insert-menu": {
"add-location": "اضافه کردن مکان",
"link-memo": "پیوند یادداشت",

View file

@ -170,7 +170,6 @@
},
"no-changes-detected": "Muutoksia ei havaittu",
"save": "Tallentaa",
"saving": "Tallennetaan...",
"audio-recorder": {
"attachment-label": "Äänen tallennus",
"attachment-label-with-time": "Äänen tallennus {{time}}",

View file

@ -133,7 +133,6 @@
},
"no-changes-detected": "Aucun changement détecté",
"save": "Enregistrer",
"saving": "Enregistrement...",
"audio-recorder": {
"attachment-label": "Enregistrement audio",
"attachment-label-with-time": "Enregistrement audio {{time}}",

View file

@ -133,7 +133,6 @@
},
"no-changes-detected": "Non se detectaron cambios",
"save": "Gardar",
"saving": "Gardando...",
"audio-recorder": {
"attachment-label": "Gravación de audio",
"attachment-label-with-time": "Gravación de audio {{time}}",

View file

@ -271,7 +271,6 @@
},
"no-changes-detected": "לא זוהו שינויים",
"save": "שמור",
"saving": "שומר...",
"validation": {
"cannot-save": "לא ניתן לשמור",
"content-required": "נדרש תוכן, קובץ מצורף או קובץ",

View file

@ -125,7 +125,6 @@
"focus-mode": "फोकस मोड",
"no-changes-detected": "कोई बदलाव नहीं पाया गया",
"save": "सहेजें",
"saving": "सहेज रहा है...",
"insert-menu": {
"add-location": "स्थान जोड़ें",
"link-memo": "लिंक मेमो",

View file

@ -133,7 +133,6 @@
},
"no-changes-detected": "Nema promjena",
"save": "Sačuvaj",
"saving": "Spremanje...",
"audio-recorder": {
"attachment-label": "Audio snimanje",
"attachment-label-with-time": "Audio snimak {{time}}",

View file

@ -133,7 +133,6 @@
},
"no-changes-detected": "Nincs változás",
"save": "Mentés",
"saving": "Mentés...",
"audio-recorder": {
"attachment-label": "Hangfelvétel",
"attachment-label-with-time": "Hangfelvétel {{time}}",

View file

@ -125,7 +125,6 @@
"focus-mode": "Mode Fokus",
"no-changes-detected": "Tidak ada perubahan yang terdeteksi",
"save": "Simpan",
"saving": "Menyimpan...",
"insert-menu": {
"add-location": "Tambahkan lokasi",
"link-memo": "Tautan memo",

View file

@ -133,7 +133,6 @@
},
"no-changes-detected": "Nessuna modifica rilevata",
"save": "Salva",
"saving": "Salvataggio...",
"audio-recorder": {
"attachment-label": "Registrazione audio",
"attachment-label-with-time": "Registrazione audio {{time}}",

View file

@ -169,7 +169,6 @@
"formatting-toolbar": "書式ツールバー",
"no-changes-detected": "変更はありません",
"save": "保存",
"saving": "保存中...",
"insert-menu": {
"add-location": "場所を追加",
"link-memo": "リンクメモ",

View file

@ -133,7 +133,6 @@
},
"no-changes-detected": "ცვლილებები არ აღმოჩენილა",
"save": "შენახვა",
"saving": "შენახვა...",
"audio-recorder": {
"attachment-label": "აუდიო ჩანაწერი",
"attachment-label-with-time": "აუდიო ჩანაწერი {{time}}",

View file

@ -125,7 +125,6 @@
"focus-mode": "집중 모드",
"no-changes-detected": "변경사항이 없습니다",
"save": "저장",
"saving": "저장 중...",
"insert-menu": {
"add-location": "위치 추가",
"link-memo": "링크 메모",

View file

@ -170,7 +170,6 @@
},
"no-changes-detected": "Pakeitimų neaptikta",
"save": "Išsaugoti",
"saving": "Išsaugoma...",
"audio-recorder": {
"attachment-label": "Garso įrašymas",
"attachment-label-with-time": "Garso įrašymas {{time}}",

View file

@ -170,7 +170,6 @@
},
"no-changes-detected": "Izmaiņas nav konstatētas",
"save": "Saglabāt",
"saving": "Notiek saglabāšana...",
"audio-recorder": {
"attachment-label": "Audio ieraksts",
"attachment-label-with-time": "Audio ieraksts {{time}}",

View file

@ -125,7 +125,6 @@
"focus-mode": "फोकस मोड",
"no-changes-detected": "कोणतेही बदल आढळले नाहीत",
"save": "जतन",
"saving": "जतन होत आहे...",
"insert-menu": {
"add-location": "स्थान जोडा",
"link-memo": "लिंक मेमो",

View file

@ -133,7 +133,6 @@
},
"no-changes-detected": "Ingen endringer oppdaget",
"save": "Lagre",
"saving": "Lagrer...",
"audio-recorder": {
"attachment-label": "Lydopptak",
"attachment-label-with-time": "Lydopptak {{time}}",

View file

@ -133,7 +133,6 @@
},
"no-changes-detected": "Geen wijzigingen gedetecteerd",
"save": "Opslaan",
"saving": "Opslaan...",
"audio-recorder": {
"attachment-label": "Audio-opname",
"attachment-label-with-time": "Audio-opname {{time}}",

View file

@ -149,7 +149,6 @@
},
"no-changes-detected": "Brak wykrytych zmian",
"save": "Zapisz",
"saving": "Zapisywanie...",
"unsupported-syntax-raw-mode": "Ta notatka zawiera składnię, której edytor WYSIWYG nie może bezpiecznie edytować, więc otwarto go w trybie surowego Markdowna.",
"wysiwyg-editor": "Edytor WYSIWYG",
"audio-recorder": {

View file

@ -125,7 +125,6 @@
"focus-mode": "Modo Foco",
"no-changes-detected": "Nenhuma alteração detectada",
"save": "Salvar",
"saving": "Salvando…",
"insert-menu": {
"add-location": "Adicionar local",
"link-memo": "Vincular memorando",

View file

@ -133,7 +133,6 @@
},
"no-changes-detected": "Nenhuma alteração detetada",
"save": "Guardar",
"saving": "A guardar...",
"audio-recorder": {
"attachment-label": "Gravação de áudio",
"attachment-label-with-time": "Gravação de áudio {{time}}",

View file

@ -170,7 +170,6 @@
},
"no-changes-detected": "Nu au fost detectate modificări",
"save": "Salva",
"saving": "Economisire...",
"audio-recorder": {
"attachment-label": "Înregistrare audio",
"attachment-label-with-time": "Înregistrare audio {{time}}",

View file

@ -183,7 +183,6 @@
},
"no-changes-detected": "Изменений не обнаружено",
"save": "Сохранить",
"saving": "Сохранение...",
"audio-recorder": {
"attachment-label": "Аудиозапись",
"attachment-label-with-time": "Аудиозапись {{time}}",

View file

@ -170,7 +170,6 @@
},
"no-changes-detected": "Nezistili sa žiadne zmeny",
"save": "Uložiť",
"saving": "Ukladá sa...",
"audio-recorder": {
"attachment-label": "Zvukový záznam",
"attachment-label-with-time": "Záznam zvuku {{time}}",

View file

@ -133,7 +133,6 @@
},
"no-changes-detected": "Ni zaznanih sprememb",
"save": "Shrani",
"saving": "Shranjujem...",
"audio-recorder": {
"attachment-label": "Zvočni posnetek",
"attachment-label-with-time": "Zvočni posnetek {{time}}",

View file

@ -170,7 +170,6 @@
},
"no-changes-detected": "Нису откривене промене",
"save": "Сачувај",
"saving": "Чување...",
"audio-recorder": {
"attachment-label": "Аудио снимак",
"attachment-label-with-time": "Аудио запис {{time}}",

View file

@ -133,7 +133,6 @@
},
"no-changes-detected": "Inga ändringar upptäckta",
"save": "Spara",
"saving": "Sparar...",
"audio-recorder": {
"attachment-label": "Ljudinspelning",
"attachment-label-with-time": "Ljudinspelning {{time}}",

View file

@ -125,7 +125,6 @@
"focus-mode": "โหมดโฟกัส",
"no-changes-detected": "ไม่มีการเปลี่ยนแปลง",
"save": "บันทึก",
"saving": "กำลังบันทึก...",
"insert-menu": {
"add-location": "เพิ่มสถานที่",
"link-memo": "บันทึกการเชื่อมโยง",

View file

@ -133,7 +133,6 @@
},
"no-changes-detected": "Değişiklik yok",
"save": "Kaydet",
"saving": "Kaydediliyor...",
"audio-recorder": {
"attachment-label": "Ses kaydı",
"attachment-label-with-time": "Ses kaydı {{time}}",

View file

@ -133,7 +133,6 @@
},
"no-changes-detected": "Змін не виявлено",
"save": "Зберегти",
"saving": "Збереження...",
"audio-recorder": {
"attachment-label": "Аудіозапис",
"attachment-label-with-time": "Аудіозапис {{time}}",

View file

@ -125,7 +125,6 @@
"focus-mode": "Chế độ tập trung",
"no-changes-detected": "Không phát hiện thay đổi",
"save": "Lưu",
"saving": "Đang lưu...",
"insert-menu": {
"add-location": "Thêm vị trí",
"link-memo": "Liên kết bản ghi nhớ",

View file

@ -190,7 +190,6 @@
"new-memo": "新建备忘录",
"no-changes-detected": "未检测到更改",
"save": "保存",
"saving": "保存中...",
"validation": {
"cannot-save": "无法保存",
"content-required": "需要填写正文或添加附件",

View file

@ -274,7 +274,6 @@
"new-memo": "新增備忘錄",
"no-changes-detected": "未發現變更",
"save": "儲存",
"saving": "儲存中...",
"validation": {
"cannot-save": "無法儲存",
"content-required": "需要填寫正文或新增附件",

19
web/src/utils/platform.ts Normal file
View file

@ -0,0 +1,19 @@
interface NavigatorWithUAData extends Navigator {
userAgentData?: { platform?: string };
}
/**
* Whether the primary modifier key is ⌘ (Apple platforms) rather than Ctrl.
* Used only to render shortcut hints; key handling itself is platform-agnostic.
*/
export function isApplePlatform(): boolean {
if (typeof navigator === "undefined") return false;
const nav = navigator as NavigatorWithUAData;
const platform = nav.userAgentData?.platform ?? nav.platform ?? "";
return /mac|iphone|ipad|ipod/i.test(platform);
}
/** Display glyph for the primary modifier: ⌘ on Apple platforms, Ctrl elsewhere. */
export function primaryModifierGlyph(): string {
return isApplePlatform() ? "⌘" : "Ctrl";
}

View file

@ -21,11 +21,12 @@ vi.mock("@/components/MemoEditor/state", () => ({
actions: {
reset: () => ({ type: "reset" }),
setLoading: (key: string, value: boolean) => ({ type: "set-loading", key, value }),
setJustSaved: (value: boolean) => ({ type: "set-just-saved", value }),
setMetadata: () => ({ type: "set-metadata" }),
setTimestamps: () => ({ type: "set-timestamps" }),
},
dispatch: mocks.dispatch,
getState: () => ({}),
getState: () => ({ ui: { justSaved: false } }),
}),
}));
@ -71,4 +72,33 @@ describe("useMemoSave", () => {
expect(invalidateQueries).toHaveBeenCalledWith({ queryKey: ["memos", "comments", "memos/parent"] });
expect(invalidateQueries).toHaveBeenCalledWith({ queryKey: ["memos", "detail", "memos/parent"] });
});
it("holds a saved confirmation before a closing host resets", async () => {
mocks.memoSave.mockResolvedValue({ hasChanges: true, memoName: "memos/existing" });
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });
const wrapper = ({ children }: PropsWithChildren) => <QueryClientProvider client={queryClient}>{children}</QueryClientProvider>;
const onConfirm = vi.fn();
const { result } = renderHook(() => useMemoSave({ memoName: "memos/existing", discardDraft: vi.fn(), onConfirm }), { wrapper });
await act(async () => result.current());
const types = mocks.dispatch.mock.calls.map(([action]) => action);
const savedOn = types.findIndex((a) => a.type === "set-just-saved" && a.value === true);
const reset = types.findIndex((a) => a.type === "reset");
expect(savedOn).toBeGreaterThan(-1);
expect(reset).toBeGreaterThan(savedOn);
expect(onConfirm).toHaveBeenCalledWith("memos/existing");
});
it("does not hold the in-place composer after saving a new memo", async () => {
mocks.memoSave.mockResolvedValue({ hasChanges: true, memoName: "memos/new" });
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });
const wrapper = ({ children }: PropsWithChildren) => <QueryClientProvider client={queryClient}>{children}</QueryClientProvider>;
const { result } = renderHook(() => useMemoSave({ discardDraft: vi.fn() }), { wrapper });
await act(async () => result.current());
const savedOn = mocks.dispatch.mock.calls.some(([action]) => action.type === "set-just-saved" && action.value === true);
expect(savedOn).toBe(false);
});
});