Skip to content

ServerKit is a lightweight, modern server control panel for managing web applications, databases, and services on your VPS or dedicated server. Built with Python/Flask backend and React frontend.

feat(frontend): add editing controls and shortcut scope

Juan Denis08315c99d70b
diff --git a/frontend/src/App.jsx b/frontend/src/App.jsx
index e06ee364..3e3cbdbc 100644
--- a/frontend/src/App.jsx
+++ b/frontend/src/App.jsx
@@ -13,6 +13,7 @@ import { Toaster } from './components/ui/sonner';
import ThemeSync from './components/ThemeSync';
import LocaleSync from './components/LocaleSync';
import DashboardLayout from './layouts/DashboardLayout';
+import ShortcutProvider from './contexts/ShortcutProvider';
import AppLoader from './components/AppLoader';
import TabGroupLayout from './layouts/TabGroupLayout';
import { SERVER_TABS } from './components/servers/serverTabs';
@@ -217,7 +218,9 @@ function AppRoutes() {
})}
<Route path="/" element={
<PrivateRoute>
- <DashboardLayout />
+ <ShortcutProvider>
+ <DashboardLayout />
+ </ShortcutProvider>
</PrivateRoute>
}>
{ROUTE_GROUP_IDS.map((group) => {
diff --git a/frontend/src/components/ds/ChangeBar.jsx b/frontend/src/components/ds/ChangeBar.jsx
new file mode 100644
index 00000000..cd7f72dc
--- /dev/null
+++ b/frontend/src/components/ds/ChangeBar.jsx
@@ -0,0 +1,64 @@
+import { AlertCircle, Check, Redo2, RotateCcw, Save, Undo2 } from 'lucide-react';
+import { useTranslation } from 'react-i18next';
+
+import { Button } from '../ui/button';
+
+export default function ChangeBar({
+ session,
+ onSave,
+ onDiscard,
+ className = '',
+}) {
+ const { t } = useTranslation();
+ const dirtyCount = session.dirtyPaths.length;
+ const isSaving = session.saveState === 'saving';
+ const classes = ['sk-changebar', className].filter(Boolean).join(' ');
+
+ return (
+ <section className={classes} aria-label={t('common.editing.unsavedChanges', 'Unsaved changes')}>
+ <div className="sk-changebar__state" role="status" aria-live="polite">
+ {session.saveState === 'error' ? <AlertCircle size={16} aria-hidden="true" /> : <Check size={16} aria-hidden="true" />}
+ <span>
+ {session.saveState === 'error'
+ ? session.error?.message || String(session.error || '')
+ : session.saveState === 'saved'
+ ? t('common.editing.saved', 'Saved')
+ : t('common.editing.unsavedCount', 'Unsaved changes: {{count}}', { count: dirtyCount })}
+ </span>
+ </div>
+ <div className="sk-changebar__actions">
+ <Button
+ type="button"
+ variant="ghost"
+ size="sm"
+ onClick={session.undo}
+ disabled={!session.canUndo || isSaving}
+ >
+ <Undo2 aria-hidden="true" />
+ {t('common.editing.undo', 'Undo')}
+ </Button>
+ <Button
+ type="button"
+ variant="ghost"
+ size="sm"
+ onClick={session.redo}
+ disabled={!session.canRedo || isSaving}
+ >
+ <Redo2 aria-hidden="true" />
+ {t('common.editing.redo', 'Redo')}
+ </Button>
+ <span className="sk-changebar__divider" aria-hidden="true" />
+ <Button type="button" variant="ghost" size="sm" onClick={onDiscard} disabled={isSaving}>
+ <RotateCcw aria-hidden="true" />
+ {t('common.editing.discard', 'Discard')}
+ </Button>
+ <Button type="button" size="sm" onClick={onSave} disabled={!session.isDirty || isSaving}>
+ <Save aria-hidden="true" />
+ {isSaving
+ ? t('common.editing.saving', 'Saving…')
+ : t('common.editing.save', 'Save')}
+ </Button>
+ </div>
+ </section>
+ );
+}
diff --git a/frontend/src/contexts/ShortcutProvider.jsx b/frontend/src/contexts/ShortcutProvider.jsx
new file mode 100644
index 00000000..55881ffc
--- /dev/null
+++ b/frontend/src/contexts/ShortcutProvider.jsx
@@ -0,0 +1,33 @@
+import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
+
+import { createShortcutRegistry } from '../services/shortcutRegistry';
+import ShortcutContext from './shortcutContext';
+
+export default function ShortcutProvider({ children }) {
+ const registryRef = useRef(null);
+ if (!registryRef.current) registryRef.current = createShortcutRegistry();
+ const [revision, setRevision] = useState(0);
+
+ useEffect(() => {
+ const onKeyDown = (event) => registryRef.current.handle(event);
+ document.addEventListener('keydown', onKeyDown);
+ return () => document.removeEventListener('keydown', onKeyDown);
+ }, []);
+
+ const register = useCallback((command) => {
+ const unregister = registryRef.current.register(command);
+ setRevision((current) => current + 1);
+ return () => {
+ unregister();
+ setRevision((current) => current + 1);
+ };
+ }, []);
+ const value = useMemo(() => ({
+ register,
+ commands: registryRef.current.list(),
+ // Revision publishes registry changes to future shortcut-sheet consumers.
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }), [register, revision]);
+
+ return <ShortcutContext.Provider value={value}>{children}</ShortcutContext.Provider>;
+}
diff --git a/frontend/src/contexts/shortcutContext.js b/frontend/src/contexts/shortcutContext.js
new file mode 100644
index 00000000..4dce4b4c
--- /dev/null
+++ b/frontend/src/contexts/shortcutContext.js
@@ -0,0 +1,5 @@
+import { createContext } from 'react';
+
+const ShortcutContext = createContext(null);
+
+export default ShortcutContext;
diff --git a/frontend/src/hooks/useShortcut.js b/frontend/src/hooks/useShortcut.js
new file mode 100644
index 00000000..134119d5
--- /dev/null
+++ b/frontend/src/hooks/useShortcut.js
@@ -0,0 +1,24 @@
+import { useContext, useEffect, useRef } from 'react';
+
+import ShortcutContext from '../contexts/shortcutContext';
+
+export function useShortcut({ handler, ...command }) {
+ const context = useContext(ShortcutContext);
+ const handlerRef = useRef(handler);
+ handlerRef.current = handler;
+ const signature = JSON.stringify(command);
+
+ useEffect(() => {
+ if (!context) throw new Error('useShortcut must be used within ShortcutProvider');
+ return context.register({
+ ...command,
+ handler: (event) => handlerRef.current(event),
+ });
+ // The serialized command is the registration contract; handlers stay fresh via ref.
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [context?.register, signature]);
+}
+
+export function useShortcutCommands() {
+ return useContext(ShortcutContext)?.commands || [];
+}
diff --git a/frontend/src/hooks/useUnsavedChangesGuard.js b/frontend/src/hooks/useUnsavedChangesGuard.js
new file mode 100644
index 00000000..96fa8f09
--- /dev/null
+++ b/frontend/src/hooks/useUnsavedChangesGuard.js
@@ -0,0 +1,54 @@
+import { useCallback, useEffect, useRef } from 'react';
+import { useNavigate } from 'react-router-dom';
+
+import { useConfirm } from './useConfirm';
+import { internalNavigationTarget } from '../services/navigationGuard';
+
+export function useUnsavedChangesGuard({
+ isDirty,
+ confirmOptions,
+ onDiscard,
+} = {}) {
+ const navigate = useNavigate();
+ const { confirm } = useConfirm();
+ const optionsRef = useRef(confirmOptions);
+ const discardRef = useRef(onDiscard);
+ optionsRef.current = confirmOptions;
+ discardRef.current = onDiscard;
+
+ const requestLeave = useCallback(async () => {
+ if (!isDirty) return true;
+ const leave = await confirm({ variant: 'warning', ...optionsRef.current });
+ if (leave) discardRef.current?.();
+ return leave;
+ }, [confirm, isDirty]);
+
+ const guardedNavigate = useCallback(async (to, options) => {
+ if (await requestLeave()) navigate(to, options);
+ }, [navigate, requestLeave]);
+
+ useEffect(() => {
+ if (!isDirty) return undefined;
+ const onBeforeUnload = (event) => {
+ event.preventDefault();
+ event.returnValue = '';
+ };
+ window.addEventListener('beforeunload', onBeforeUnload);
+ return () => window.removeEventListener('beforeunload', onBeforeUnload);
+ }, [isDirty]);
+
+ useEffect(() => {
+ if (!isDirty) return undefined;
+ const onClick = async (event) => {
+ const destination = internalNavigationTarget(event, window.location);
+ if (!destination) return;
+
+ event.preventDefault();
+ if (await requestLeave()) navigate(destination);
+ };
+ document.addEventListener('click', onClick);
+ return () => document.removeEventListener('click', onClick);
+ }, [isDirty, navigate, requestLeave]);
+
+ return { requestLeave, guardedNavigate };
+}
diff --git a/frontend/src/i18n/locales/ar.json b/frontend/src/i18n/locales/ar.json
index 24ecc459..30aa5425 100644
--- a/frontend/src/i18n/locales/ar.json
+++ b/frontend/src/i18n/locales/ar.json
@@ -8475,6 +8475,16 @@
"minutesSeconds": "{{minutes}} د {{seconds}} ث",
"seconds": "{{count}}s"
},
+ "editing": {
+ "discard": "تجاهل التغييرات",
+ "redo": "إعادة",
+ "save": "حفظ",
+ "saved": "تم الحفظ",
+ "saving": "جارٍ الحفظ…",
+ "undo": "تراجع",
+ "unsavedChanges": "تغييرات غير محفوظة",
+ "unsavedCount": "التغييرات غير المحفوظة: {{count}}"
+ },
"error": {
"failedToLoad": "فشل التحميل",
"loadingData": "حدث خطأ أثناء تحميل البيانات",
diff --git a/frontend/src/i18n/locales/bn.json b/frontend/src/i18n/locales/bn.json
index 94a790fe..2f539b47 100644
--- a/frontend/src/i18n/locales/bn.json
+++ b/frontend/src/i18n/locales/bn.json
@@ -8475,6 +8475,16 @@
"minutesSeconds": "{{minutes}}m {{seconds}}s",
"seconds": "{{count}}s"
},
+ "editing": {
+ "discard": "পরিবর্তন বাতিল করুন",
+ "redo": "পুনরায় করুন",
+ "save": "সংরক্ষণ করুন",
+ "saved": "সংরক্ষিত",
+ "saving": "সংরক্ষণ করা হচ্ছে…",
+ "undo": "পূর্বাবস্থায় ফেরান",
+ "unsavedChanges": "অসংরক্ষিত পরিবর্তন",
+ "unsavedCount": "অসংরক্ষিত পরিবর্তন: {{count}}"
+ },
"error": {
"failedToLoad": "লোড করতে ব্যর্থ হয়েছে",
"loadingData": "ডেটা লোড করার সময় একটি ত্রুটি ঘটেছে৷",
diff --git a/frontend/src/i18n/locales/de.json b/frontend/src/i18n/locales/de.json
index 9799834a..670b2973 100644
--- a/frontend/src/i18n/locales/de.json
+++ b/frontend/src/i18n/locales/de.json
@@ -8475,6 +8475,16 @@
"minutesSeconds": "{{minutes}}m {{seconds}}s",
"seconds": "{{count}}s"
},
+ "editing": {
+ "discard": "Verwerfen",
+ "redo": "Wiederholen",
+ "save": "Speichern",
+ "saved": "Gespeichert",
+ "saving": "Wird gespeichert…",
+ "undo": "Rückgängig",
+ "unsavedChanges": "Nicht gespeicherte Änderungen",
+ "unsavedCount": "Nicht gespeicherte Änderungen: {{count}}"
+ },
"error": {
"failedToLoad": "Laden fehlgeschlagen",
"loadingData": "Beim Laden der Daten ist ein Fehler aufgetreten",
diff --git a/frontend/src/i18n/locales/en.json b/frontend/src/i18n/locales/en.json
index 24dd706d..3c26fd17 100644
--- a/frontend/src/i18n/locales/en.json
+++ b/frontend/src/i18n/locales/en.json
@@ -8475,6 +8475,16 @@
"minutesSeconds": "{{minutes}}m {{seconds}}s",
"seconds": "{{count}}s"
},
+ "editing": {
+ "discard": "Discard",
+ "redo": "Redo",
+ "save": "Save",
+ "saved": "Saved",
+ "saving": "Saving…",
+ "undo": "Undo",
+ "unsavedChanges": "Unsaved changes",
+ "unsavedCount": "Unsaved changes: {{count}}"
+ },
"error": {
"failedToLoad": "Failed to load",
"loadingData": "An error occurred while loading data",
diff --git a/frontend/src/i18n/locales/es.json b/frontend/src/i18n/locales/es.json
index bf6b69b6..8fa2ead8 100644
--- a/frontend/src/i18n/locales/es.json
+++ b/frontend/src/i18n/locales/es.json
@@ -8475,6 +8475,16 @@
"minutesSeconds": "{{minutes}} min {{seconds}} s",
"seconds": "{{count}} s"
},
+ "editing": {
+ "discard": "Descartar",
+ "redo": "Rehacer",
+ "save": "Guardar",
+ "saved": "Guardado",
+ "saving": "Guardando…",
+ "undo": "Deshacer",
+ "unsavedChanges": "Cambios sin guardar",
+ "unsavedCount": "Cambios sin guardar: {{count}}"
+ },
"error": {
"failedToLoad": "No se pudo cargar",
"loadingData": "Se produjo un error al cargar los datos",
diff --git a/frontend/src/i18n/locales/fr.json b/frontend/src/i18n/locales/fr.json
index f284b61a..894caaba 100644
--- a/frontend/src/i18n/locales/fr.json
+++ b/frontend/src/i18n/locales/fr.json
@@ -8475,6 +8475,16 @@
"minutesSeconds": "{{minutes}}m {{seconds}}s",
"seconds": "{{count}}s"
},
+ "editing": {
+ "discard": "Abandonner",
+ "redo": "Rétablir",
+ "save": "Enregistrer",
+ "saved": "Enregistré",
+ "saving": "Enregistrement…",
+ "undo": "Annuler",
+ "unsavedChanges": "Modifications non enregistrées",
+ "unsavedCount": "Modifications non enregistrées : {{count}}"
+ },
"error": {
"failedToLoad": "Échec du chargement",
"loadingData": "Une erreur s'est produite lors du chargement des données",
diff --git a/frontend/src/i18n/locales/id.json b/frontend/src/i18n/locales/id.json
index 6d33dfb4..8f2d49ee 100644
--- a/frontend/src/i18n/locales/id.json
+++ b/frontend/src/i18n/locales/id.json
@@ -8475,6 +8475,16 @@
"minutesSeconds": "{{minutes}}m {{seconds}}s",
"seconds": "{{count}}s"
},
+ "editing": {
+ "discard": "Buang perubahan",
+ "redo": "Ulangi",
+ "save": "Simpan",
+ "saved": "Tersimpan",
+ "saving": "Menyimpan…",
+ "undo": "Urungkan",
+ "unsavedChanges": "Perubahan belum disimpan",
+ "unsavedCount": "Perubahan belum disimpan: {{count}}"
+ },
"error": {
"failedToLoad": "Gagal memuat",
"loadingData": "Terjadi kesalahan saat memuat data",
diff --git a/frontend/src/i18n/locales/it.json b/frontend/src/i18n/locales/it.json
index c8af8ebf..c26fb3e1 100644
--- a/frontend/src/i18n/locales/it.json
+++ b/frontend/src/i18n/locales/it.json
@@ -8475,6 +8475,16 @@
"minutesSeconds": "{{minutes}}m {{seconds}}s",
"seconds": "{{count}}s"
},
+ "editing": {
+ "discard": "Scarta",
+ "redo": "Ripeti",
+ "save": "Salva",
+ "saved": "Salvato",
+ "saving": "Salvataggio…",
+ "undo": "Annulla",
+ "unsavedChanges": "Modifiche non salvate",
+ "unsavedCount": "Modifiche non salvate: {{count}}"
+ },
"error": {
"failedToLoad": "Impossibile caricare",
"loadingData": "Si è verificato un errore durante il caricamento dei dati",
diff --git a/frontend/src/i18n/locales/ko.json b/frontend/src/i18n/locales/ko.json
index 652f6bf6..9939c477 100644
--- a/frontend/src/i18n/locales/ko.json
+++ b/frontend/src/i18n/locales/ko.json
@@ -8475,6 +8475,16 @@
"minutesSeconds": "{{minutes}}분 {{seconds}}초",
"seconds": "{{count}}초"
},
+ "editing": {
+ "discard": "변경 사항 버리기",
+ "redo": "다시 실행",
+ "save": "저장",
+ "saved": "저장됨",
+ "saving": "저장 중…",
+ "undo": "실행 취소",
+ "unsavedChanges": "저장되지 않은 변경 사항",
+ "unsavedCount": "저장되지 않은 변경 사항: {{count}}"
+ },
"error": {
"failedToLoad": "로드하지 못했습니다.",
"loadingData": "데이터를 로드하는 중 오류가 발생했습니다.",
diff --git a/frontend/src/i18n/locales/pl.json b/frontend/src/i18n/locales/pl.json
index 094c4f76..d3f7f17e 100644
--- a/frontend/src/i18n/locales/pl.json
+++ b/frontend/src/i18n/locales/pl.json
@@ -8475,6 +8475,16 @@
"minutesSeconds": "{{minutes}}m {{seconds}}s",
"seconds": "{{count}}"
},
+ "editing": {
+ "discard": "Odrzuć",
+ "redo": "Ponów",
+ "save": "Zapisz",
+ "saved": "Zapisano",
+ "saving": "Zapisywanie…",
+ "undo": "Cofnij",
+ "unsavedChanges": "Niezapisane zmiany",
+ "unsavedCount": "Niezapisane zmiany: {{count}}"
+ },
"error": {
"failedToLoad": "Nie udało się załadować",
"loadingData": "Wystąpił błąd podczas ładowania danych",
diff --git a/frontend/src/i18n/locales/pt.json b/frontend/src/i18n/locales/pt.json
index b1d807c7..d6048da4 100644
--- a/frontend/src/i18n/locales/pt.json
+++ b/frontend/src/i18n/locales/pt.json
@@ -8475,6 +8475,16 @@
"minutesSeconds": "{{minutes}}m {{seconds}}s",
"seconds": "{{count}}s"
},
+ "editing": {
+ "discard": "Descartar",
+ "redo": "Refazer",
+ "save": "Guardar",
+ "saved": "Guardado",
+ "saving": "A guardar…",
+ "undo": "Desfazer",
+ "unsavedChanges": "Alterações não guardadas",
+ "unsavedCount": "Alterações não guardadas: {{count}}"
+ },
"error": {
"failedToLoad": "Falha ao carregar",
"loadingData": "Ocorreu um erro ao carregar dados",
diff --git a/frontend/src/i18n/locales/ru.json b/frontend/src/i18n/locales/ru.json
index fd6a2aa6..933068dc 100644
--- a/frontend/src/i18n/locales/ru.json
+++ b/frontend/src/i18n/locales/ru.json
@@ -8475,6 +8475,16 @@
"minutesSeconds": "{{minutes}} м {{seconds}} с",
"seconds": "{{count}} с"
},
+ "editing": {
+ "discard": "Отбросить",
+ "redo": "Повторить",
+ "save": "Сохранить",
+ "saved": "Сохранено",
+ "saving": "Сохранение…",
+ "undo": "Отменить",
+ "unsavedChanges": "Несохранённые изменения",
+ "unsavedCount": "Несохранённые изменения: {{count}}"
+ },
"error": {
"failedToLoad": "Не удалось загрузить",
"loadingData": "Произошла ошибка при загрузке данных",
diff --git a/frontend/src/i18n/locales/th.json b/frontend/src/i18n/locales/th.json
index 01370700..26488916 100644
--- a/frontend/src/i18n/locales/th.json
+++ b/frontend/src/i18n/locales/th.json
@@ -8475,6 +8475,16 @@
"minutesSeconds": "{{minutes}}m {{seconds}}s",
"seconds": "{{count}}"
},
+ "editing": {
+ "discard": "ละทิ้งการเปลี่ยนแปลง",
+ "redo": "ทำซ้ำ",
+ "save": "บันทึก",
+ "saved": "บันทึกแล้ว",
+ "saving": "กำลังบันทึก…",
+ "undo": "เลิกทำ",
+ "unsavedChanges": "การเปลี่ยนแปลงที่ยังไม่ได้บันทึก",
+ "unsavedCount": "การเปลี่ยนแปลงที่ยังไม่ได้บันทึก: {{count}}"
+ },
"error": {
"failedToLoad": "โหลดไม่สำเร็จ",
"loadingData": "เกิดข้อผิดพลาดขณะโหลดข้อมูล",
diff --git a/frontend/src/i18n/locales/tr.json b/frontend/src/i18n/locales/tr.json
index eb7ea4d1..5234ef01 100644
--- a/frontend/src/i18n/locales/tr.json
+++ b/frontend/src/i18n/locales/tr.json
@@ -8475,6 +8475,16 @@
"minutesSeconds": "{{minutes}}m {{seconds}}'ler",
"seconds": "{{count}}'ler"
},
+ "editing": {
+ "discard": "Vazgeç",
+ "redo": "Yinele",
+ "save": "Kaydet",
+ "saved": "Kaydedildi",
+ "saving": "Kaydediliyor…",
+ "undo": "Geri al",
+ "unsavedChanges": "Kaydedilmemiş değişiklikler",
+ "unsavedCount": "Kaydedilmemiş değişiklikler: {{count}}"
+ },
"error": {
"failedToLoad": "Yüklenemedi",
"loadingData": "Veriler yüklenirken bir hata oluştu",
diff --git a/frontend/src/i18n/locales/vi.json b/frontend/src/i18n/locales/vi.json
index fcbbab00..5fbab57a 100644
--- a/frontend/src/i18n/locales/vi.json
+++ b/frontend/src/i18n/locales/vi.json
@@ -8475,6 +8475,16 @@
"minutesSeconds": "{{minutes}}m {{seconds}}",
"seconds": "{{count}}"
},
+ "editing": {
+ "discard": "Hủy thay đổi",
+ "redo": "Làm lại",
+ "save": "Lưu",
+ "saved": "Đã lưu",
+ "saving": "Đang lưu…",
+ "undo": "Hoàn tác",
+ "unsavedChanges": "Thay đổi chưa lưu",
+ "unsavedCount": "Thay đổi chưa lưu: {{count}}"
+ },
"error": {
"failedToLoad": "Không tải được",
"loadingData": "Đã xảy ra lỗi khi tải dữ liệu",
diff --git a/frontend/src/i18n/locales/zh-Hans.json b/frontend/src/i18n/locales/zh-Hans.json
index 8dbf8b12..ad365697 100644
--- a/frontend/src/i18n/locales/zh-Hans.json
+++ b/frontend/src/i18n/locales/zh-Hans.json
@@ -8475,6 +8475,16 @@
"minutesSeconds": "{{minutes}}米{{seconds}}秒",
"seconds": "{{count}} 个"
},
+ "editing": {
+ "discard": "放弃更改",
+ "redo": "重做",
+ "save": "保存",
+ "saved": "已保存",
+ "saving": "正在保存…",
+ "undo": "撤销",
+ "unsavedChanges": "未保存的更改",
+ "unsavedCount": "未保存的更改:{{count}}"
+ },
"error": {
"failedToLoad": "加载失败",
"loadingData": "加载数据时发生错误",
diff --git a/frontend/src/i18n/locales/zh-Hant.json b/frontend/src/i18n/locales/zh-Hant.json
index 0f9847a7..c857d2b5 100644
--- a/frontend/src/i18n/locales/zh-Hant.json
+++ b/frontend/src/i18n/locales/zh-Hant.json
@@ -8475,6 +8475,16 @@
"minutesSeconds": "{{minutes}}m {{seconds}}s",
"seconds": "{{count}}s"
},
+ "editing": {
+ "discard": "捨棄變更",
+ "redo": "重做",
+ "save": "儲存",
+ "saved": "已儲存",
+ "saving": "正在儲存…",
+ "undo": "復原",
+ "unsavedChanges": "未儲存的變更",
+ "unsavedCount": "未儲存的變更:{{count}}"
+ },
"error": {
"failedToLoad": "載入失敗",
"loadingData": "載入資料時發生錯誤",
diff --git a/frontend/src/layouts/DashboardLayout.jsx b/frontend/src/layouts/DashboardLayout.jsx
index 9e9d1618..70bdecbf 100644
--- a/frontend/src/layouts/DashboardLayout.jsx
+++ b/frontend/src/layouts/DashboardLayout.jsx
@@ -17,6 +17,7 @@ import SystemNotices from '../components/SystemNotices';
import StagingBanner from '../components/StagingBanner';
import DeployPill from '../components/DeployPill';
import ErrorBoundary from '../components/ErrorBoundary';
+import { useShortcut } from '../hooks/useShortcut';
// The Automations extension (tramo) contributes /automations/edit/:slug with
// layout:'full', so it's picked up dynamically via fullPagePaths below.
@@ -61,10 +62,16 @@ const DashboardLayout = () => {
}
}, []);
- useEffect(() => {
- document.addEventListener('keydown', handleKeyDown);
- return () => document.removeEventListener('keydown', handleKeyDown);
- }, [handleKeyDown]);
+ useShortcut({
+ id: 'command-palette',
+ keys: [
+ { key: 'k', ctrlOrMeta: true },
+ { key: 'p', ctrlOrMeta: true, shift: true },
+ { key: 'F1' },
+ ],
+ allowInInput: true,
+ handler: handleKeyDown,
+ });
// Close the mobile drawer on navigation (covers nav-link taps too).
useEffect(() => {
diff --git a/frontend/src/services/__tests__/navigationGuard.test.mjs b/frontend/src/services/__tests__/navigationGuard.test.mjs
new file mode 100644
index 00000000..5144676d
--- /dev/null
+++ b/frontend/src/services/__tests__/navigationGuard.test.mjs
@@ -0,0 +1,45 @@
+import assert from 'node:assert/strict';
+import test from 'node:test';
+
+import { internalNavigationTarget } from '../navigationGuard.js';
+
+const location = {
+ href: 'https://panel.test/dashboard?tab=one',
+ origin: 'https://panel.test',
+ pathname: '/dashboard',
+ search: '?tab=one',
+ hash: '',
+};
+
+const click = (href, anchor = {}) => ({
+ defaultPrevented: false,
+ button: 0,
+ metaKey: false,
+ ctrlKey: false,
+ shiftKey: false,
+ altKey: false,
+ target: {
+ closest: () => ({
+ href,
+ target: '',
+ hasAttribute: () => false,
+ ...anchor,
+ }),
+ },
+});
+
+test('returns a same-origin destination with query and hash intact', () => {
+ assert.equal(
+ internalNavigationTarget(click('/projects/4?tab=apps#top'), location),
+ '/projects/4?tab=apps#top',
+ );
+});
+
+test('ignores the current page, external links, downloads, and modified clicks', () => {
+ assert.equal(internalNavigationTarget(click('/dashboard?tab=one'), location), null);
+ assert.equal(internalNavigationTarget(click('https://docs.example.test'), location), null);
+ assert.equal(internalNavigationTarget(click('/export', {
+ hasAttribute: (name) => name === 'download',
+ }), location), null);
+ assert.equal(internalNavigationTarget({ ...click('/projects'), ctrlKey: true }, location), null);
+});
diff --git a/frontend/src/services/__tests__/shortcutRegistry.test.mjs b/frontend/src/services/__tests__/shortcutRegistry.test.mjs
new file mode 100644
index 00000000..92a613ac
--- /dev/null
+++ b/frontend/src/services/__tests__/shortcutRegistry.test.mjs
@@ -0,0 +1,70 @@
+import assert from 'node:assert/strict';
+import test from 'node:test';
+
+import { createShortcutRegistry, isEditableTarget, matchesShortcut } from '../shortcutRegistry.js';
+
+const eventFor = (key, extras = {}) => ({
+ key,
+ ctrlKey: false,
+ metaKey: false,
+ shiftKey: false,
+ altKey: false,
+ target: { tagName: 'DIV', isContentEditable: false },
+ preventDefault() { this.prevented = true; },
+ ...extras,
+});
+
+test('matches platform command modifiers without accepting extra modifiers', () => {
+ assert.equal(matchesShortcut(eventFor('k', { ctrlKey: true }), {
+ key: 'k', ctrlOrMeta: true,
+ }), true);
+ assert.equal(matchesShortcut(eventFor('K', { metaKey: true, shiftKey: true }), {
+ key: 'k', ctrlOrMeta: true,
+ }), false);
+});
+
+test('recognizes typing and contenteditable targets', () => {
+ assert.equal(isEditableTarget({ tagName: 'INPUT' }), true);
+ assert.equal(isEditableTarget({ tagName: 'div', isContentEditable: true }), true);
+ assert.equal(isEditableTarget({ tagName: 'div', isContentEditable: false }), false);
+});
+
+test('dispatches the highest-priority matching command and unregisters cleanly', () => {
+ const registry = createShortcutRegistry();
+ const called = [];
+ registry.register({
+ id: 'low', keys: [{ key: 'z', ctrlOrMeta: true }], priority: 1,
+ handler: () => called.push('low'),
+ });
+ const unregister = registry.register({
+ id: 'high', keys: [{ key: 'z', ctrlOrMeta: true }], priority: 2,
+ handler: () => called.push('high'),
+ });
+
+ const first = eventFor('z', { ctrlKey: true });
+ assert.equal(registry.handle(first), 'high');
+ assert.equal(first.prevented, true);
+ assert.deepEqual(called, ['high']);
+
+ unregister();
+ assert.equal(registry.handle(eventFor('z', { ctrlKey: true })), 'low');
+ assert.deepEqual(called, ['high', 'low']);
+});
+
+test('suppresses editing shortcuts while the user is typing unless explicitly allowed', () => {
+ const registry = createShortcutRegistry();
+ const called = [];
+ registry.register({
+ id: 'undo', keys: [{ key: 'z', ctrlOrMeta: true }],
+ handler: () => called.push('undo'),
+ });
+ registry.register({
+ id: 'palette', keys: [{ key: 'k', ctrlOrMeta: true }], allowInInput: true,
+ handler: () => called.push('palette'),
+ });
+
+ const input = { tagName: 'INPUT', isContentEditable: false };
+ assert.equal(registry.handle(eventFor('z', { ctrlKey: true, target: input })), null);
+ assert.equal(registry.handle(eventFor('k', { ctrlKey: true, target: input })), 'palette');
+ assert.deepEqual(called, ['palette']);
+});
diff --git a/frontend/src/services/navigationGuard.js b/frontend/src/services/navigationGuard.js
new file mode 100644
index 00000000..1798a676
--- /dev/null
+++ b/frontend/src/services/navigationGuard.js
@@ -0,0 +1,11 @@
+export function internalNavigationTarget(event, location) {
+ if (event.defaultPrevented || event.button !== 0
+ || event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) return null;
+ const anchor = event.target?.closest?.('a[href]');
+ if (!anchor || anchor.target || anchor.hasAttribute('download')) return null;
+ const url = new URL(anchor.href, location.href);
+ if (url.origin !== location.origin) return null;
+ const destination = `${url.pathname}${url.search}${url.hash}`;
+ const current = `${location.pathname}${location.search}${location.hash}`;
+ return destination === current ? null : destination;
+}
diff --git a/frontend/src/services/shortcutRegistry.js b/frontend/src/services/shortcutRegistry.js
new file mode 100644
index 00000000..59b0d7c1
--- /dev/null
+++ b/frontend/src/services/shortcutRegistry.js
@@ -0,0 +1,52 @@
+export const isEditableTarget = (target) => {
+ if (!target) return false;
+ const tagName = String(target.tagName || '').toLowerCase();
+ return target.isContentEditable
+ || ['input', 'textarea', 'select'].includes(tagName)
+ || Boolean(target.closest?.('[contenteditable="true"]'));
+};
+
+export const matchesShortcut = (event, shortcut) => {
+ if (String(event.key).toLowerCase() !== String(shortcut.key).toLowerCase()) return false;
+ const ctrlOrMeta = Boolean(event.ctrlKey || event.metaKey);
+ if (Boolean(shortcut.ctrlOrMeta) !== ctrlOrMeta) return false;
+ if (!shortcut.ctrlOrMeta) {
+ if (Boolean(shortcut.ctrl) !== Boolean(event.ctrlKey)) return false;
+ if (Boolean(shortcut.meta) !== Boolean(event.metaKey)) return false;
+ }
+ if (Boolean(shortcut.shift) !== Boolean(event.shiftKey)) return false;
+ if (Boolean(shortcut.alt) !== Boolean(event.altKey)) return false;
+ return true;
+};
+
+export function createShortcutRegistry() {
+ const commands = new Map();
+
+ const register = (command) => {
+ if (!command?.id || !command?.handler || !command?.keys?.length) {
+ throw new Error('A shortcut requires id, keys, and handler');
+ }
+ commands.set(command.id, command);
+ return () => {
+ if (commands.get(command.id) === command) commands.delete(command.id);
+ };
+ };
+
+ const handle = (event) => {
+ const ordered = [...commands.values()]
+ .filter((command) => command.enabled !== false)
+ .sort((left, right) => (right.priority || 0) - (left.priority || 0));
+ for (const command of ordered) {
+ if (!command.allowInInput && isEditableTarget(event.target)) continue;
+ if (!command.keys.some((key) => matchesShortcut(event, key))) continue;
+ if (command.preventDefault !== false) event.preventDefault?.();
+ command.handler(event);
+ return command.id;
+ }
+ return null;
+ };
+
+ const list = () => [...commands.values()].map(({ handler: _handler, ...command }) => command);
+
+ return { register, handle, list };
+}
diff --git a/frontend/src/styles/components/_change-bar.scss b/frontend/src/styles/components/_change-bar.scss
new file mode 100644
index 00000000..99a09e28
--- /dev/null
+++ b/frontend/src/styles/components/_change-bar.scss
@@ -0,0 +1,76 @@
+.sk-changebar {
+ position: sticky;
+ inset-block-end: $space-4;
+ z-index: $z-sticky;
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ gap: $space-4;
+ width: min(100%, 920px);
+ min-height: 52px;
+ margin: $space-6 auto $space-4;
+ padding: $space-2 $space-3 $space-2 $space-4;
+ border: 1px solid $border-active;
+ border-radius: $radius-lg;
+ background: $bg-elevated;
+ box-shadow: $shadow-lg;
+
+ &__state,
+ &__actions {
+ display: flex;
+ align-items: center;
+ }
+
+ &__state {
+ gap: $space-2;
+ min-width: 0;
+ color: $text-secondary;
+ font-size: $font-size-sm;
+
+ svg {
+ flex: 0 0 auto;
+ color: $warning;
+ }
+
+ span {
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ }
+ }
+
+ &__actions {
+ gap: $space-1;
+ flex: 0 0 auto;
+ }
+
+ &__divider {
+ width: 1px;
+ height: 20px;
+ margin-inline: $space-1;
+ background: $border-default;
+ }
+}
+
+@media (max-width: $breakpoint-sm) {
+ .sk-changebar {
+ align-items: stretch;
+ flex-direction: column;
+ inset-block-end: $space-2;
+ margin-block: $space-4 $space-2;
+ padding: $space-3;
+
+ &__actions {
+ display: grid;
+ grid-template-columns: repeat(2, minmax(0, 1fr));
+
+ .btn {
+ width: 100%;
+ }
+ }
+
+ &__divider {
+ display: none;
+ }
+ }
+}
diff --git a/frontend/src/styles/main.scss b/frontend/src/styles/main.scss
index a7dd77e7..6308e4a2 100644
--- a/frontend/src/styles/main.scss
+++ b/frontend/src/styles/main.scss
@@ -72,6 +72,7 @@
@import 'components/_ui';
@import 'components/_staging-banner';
@import 'components/_design-system'; // redesign shared primitives (sk-* namespace)
+@import 'components/_change-bar'; // local draft history + save/discard controls
@import 'components/_datagrid'; // DataGrid list surface (sk-grid*, ds/grid/)
@import 'components/_dashboard-widgets'; // configurable dashboard grid (skw-* namespace)
@import 'components/_setup-health'; // dashboard setup-health card + account nudge