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.
Python astracloudflarecontrol-panelcyberpaneldnsfablehosting-control-panelhosting-panelkimi-k3server-managementserverkitubuntu-web-panelwebserver
feat(frontend): add editing session history
Juan Denisc823c8dc15e8
diff --git a/frontend/src/hooks/__tests__/editingSession.test.mjs b/frontend/src/hooks/__tests__/editingSession.test.mjsnew file mode 100644index 00000000..e7714c87--- /dev/null+++ b/frontend/src/hooks/__tests__/editingSession.test.mjs@@ -0,0 +1,97 @@+import assert from 'node:assert/strict';+import test from 'node:test';++import { createEditingSession, editingSessionReducer } from '../editingSession.js';++const reduce = (state, action) => editingSessionReducer(state, action);++test('change tracks nested dirty paths and undo/redo state', () => {+ const initial = createEditingSession({ title: 'Ops', layout: [{ x: 0, y: 0 }] });+ const changed = reduce(initial, { type: 'change', path: 'layout.0.x', value: 4 });++ assert.equal(changed.draft.layout[0].x, 4);+ assert.deepEqual(changed.dirtyPaths, ['layout.0.x']);+ assert.equal(changed.isDirty, true);+ assert.equal(changed.canUndo, true);++ const undone = reduce(changed, { type: 'undo' });+ assert.deepEqual(undone.draft, initial.baseline);+ assert.equal(undone.isDirty, false);+ assert.equal(undone.canRedo, true);++ const redone = reduce(undone, { type: 'redo' });+ assert.equal(redone.draft.layout[0].x, 4);+ assert.equal(redone.canUndo, true);+});++test('a new change after undo invalidates redo history', () => {+ let state = createEditingSession({ value: 1 });+ state = reduce(state, { type: 'change', path: 'value', value: 2 });+ state = reduce(state, { type: 'undo' });+ state = reduce(state, { type: 'change', path: 'value', value: 3 });++ assert.equal(state.canRedo, false);+ assert.equal(reduce(state, { type: 'redo' }), state);+});++test('coalesces a user-sized drag transaction into one undo step', () => {+ let state = createEditingSession({ widget: { x: 0, y: 0 } });+ state = reduce(state, {+ type: 'transaction',+ changes: [{ path: 'widget.x', value: 1 }, { path: 'widget.y', value: 2 }],+ coalesceKey: 'drag:widget',+ });+ state = reduce(state, {+ type: 'transaction',+ changes: [{ path: 'widget.x', value: 8 }, { path: 'widget.y', value: 9 }],+ coalesceKey: 'drag:widget',+ });++ assert.equal(state.past.length, 1);+ assert.deepEqual(state.draft.widget, { x: 8, y: 9 });+ assert.deepEqual(reduce(state, { type: 'undo' }).draft.widget, { x: 0, y: 0 });+});++test('bounded history drops the oldest snapshots', () => {+ let state = createEditingSession({ value: 0 }, { historyLimit: 2 });+ for (let value = 1; value <= 4; value += 1) {+ state = reduce(state, { type: 'change', path: 'value', value });+ }++ assert.equal(state.past.length, 2);+ state = reduce(reduce(state, { type: 'undo' }), { type: 'undo' });+ assert.equal(state.draft.value, 2);+ assert.equal(state.canUndo, false);+});++test('save failure preserves the draft and history for retry', () => {+ let state = createEditingSession({ title: 'Before' });+ state = reduce(state, { type: 'change', path: 'title', value: 'After' });+ state = reduce(state, { type: 'saveStarted' });+ const error = new Error('Network unavailable');+ state = reduce(state, { type: 'saveFailed', error });++ assert.equal(state.saveState, 'error');+ assert.equal(state.error, error);+ assert.equal(state.draft.title, 'After');+ assert.equal(state.canUndo, true);+});++test('save success and reset replace the baseline and clear history', () => {+ let state = createEditingSession({ title: 'Before' });+ state = reduce(state, { type: 'change', path: 'title', value: 'After' });+ state = reduce(state, {+ type: 'saveSucceeded',+ baseline: { title: 'Canonical server title' },+ });++ assert.deepEqual(state.baseline, { title: 'Canonical server title' });+ assert.deepEqual(state.draft, state.baseline);+ assert.equal(state.isDirty, false);+ assert.equal(state.saveState, 'saved');+ assert.equal(state.canUndo, false);++ state = reduce(state, { type: 'reset', baseline: { title: 'Another record' } });+ assert.deepEqual(state.draft, { title: 'Another record' });+ assert.equal(state.saveState, 'idle');+});diff --git a/frontend/src/hooks/editingSession.js b/frontend/src/hooks/editingSession.jsnew file mode 100644index 00000000..e0e1c5a4--- /dev/null+++ b/frontend/src/hooks/editingSession.js@@ -0,0 +1,169 @@+const DEFAULT_HISTORY_LIMIT = 50;++const clone = (value) => {+ if (typeof structuredClone === 'function') return structuredClone(value);+ return JSON.parse(JSON.stringify(value));+};++const isObject = (value) => value !== null && typeof value === 'object';++const equal = (left, right) => {+ if (Object.is(left, right)) return true;+ if (!isObject(left) || !isObject(right)) return false;+ if (Array.isArray(left) !== Array.isArray(right)) return false;+ const leftKeys = Object.keys(left).sort();+ const rightKeys = Object.keys(right).sort();+ if (leftKeys.length !== rightKeys.length) return false;+ return leftKeys.every((key, index) => (+ key === rightKeys[index] && equal(left[key], right[key])+ ));+};++const pathParts = (path) => (+ Array.isArray(path) ? path.map(String) : String(path).split('.').filter(Boolean)+);++const setAtPath = (source, path, value) => {+ const parts = pathParts(path);+ if (!parts.length) return clone(value);+ const next = clone(source);+ let cursor = next;+ parts.forEach((part, index) => {+ if (index === parts.length - 1) {+ cursor[part] = clone(value);+ return;+ }+ const nextPart = parts[index + 1];+ if (!isObject(cursor[part])) cursor[part] = /^\d+$/.test(nextPart) ? [] : {};+ cursor = cursor[part];+ });+ return next;+};++const changedPaths = (baseline, draft, prefix = '') => {+ if (equal(baseline, draft)) return [];+ if (!isObject(baseline) || !isObject(draft)+ || Array.isArray(baseline) !== Array.isArray(draft)) {+ return [prefix || '$'];+ }+ const keys = [...new Set([...Object.keys(baseline), ...Object.keys(draft)])].sort();+ return keys.flatMap((key) => changedPaths(+ baseline[key],+ draft[key],+ prefix ? `${prefix}.${key}` : key,+ ));+};++const derive = (state) => {+ const dirtyPaths = changedPaths(state.baseline, state.draft);+ return {+ ...state,+ dirtyPaths,+ isDirty: dirtyPaths.length > 0,+ canUndo: state.past.length > 0,+ canRedo: state.future.length > 0,+ };+};++export function createEditingSession(baseline, { historyLimit = DEFAULT_HISTORY_LIMIT } = {}) {+ const initial = clone(baseline);+ return derive({+ baseline: initial,+ draft: clone(initial),+ past: [],+ future: [],+ historyLimit,+ saveState: 'idle',+ error: null,+ });+}++const commitDraft = (state, nextDraft, coalesceKey = null) => {+ if (equal(state.draft, nextDraft)) return state;+ const last = state.past[state.past.length - 1];+ const coalesces = Boolean(coalesceKey && last?.coalesceKey === coalesceKey);+ const past = coalesces+ ? state.past+ : [...state.past, { draft: clone(state.draft), coalesceKey }]+ .slice(-state.historyLimit);+ return derive({+ ...state,+ draft: clone(nextDraft),+ past,+ future: [],+ saveState: 'idle',+ error: null,+ });+};++const transactionDraft = (state, action) => {+ if (Object.hasOwn(action, 'draft')) return action.draft;+ if (typeof action.update === 'function') return action.update(clone(state.draft));+ return (action.changes || []).reduce(+ (draft, change) => setAtPath(draft, change.path, change.value),+ state.draft,+ );+};++export function editingSessionReducer(state, action) {+ switch (action.type) {+ case 'change':+ return commitDraft(+ state,+ setAtPath(state.draft, action.path, action.value),+ action.coalesceKey,+ );+ case 'transaction':+ return commitDraft(state, transactionDraft(state, action), action.coalesceKey);+ case 'undo': { // current draft moves to the front of redo history+ if (!state.past.length) return state;+ const previous = state.past[state.past.length - 1];+ return derive({+ ...state,+ draft: clone(previous.draft),+ past: state.past.slice(0, -1),+ future: [{ draft: clone(state.draft) }, ...state.future],+ saveState: 'idle',+ error: null,+ });+ }+ case 'redo': {+ if (!state.future.length) return state;+ const [next, ...future] = state.future;+ return derive({+ ...state,+ draft: clone(next.draft),+ past: [...state.past, { draft: clone(state.draft), coalesceKey: null }]+ .slice(-state.historyLimit),+ future,+ saveState: 'idle',+ error: null,+ });+ }+ case 'reset':+ return createEditingSession(+ Object.hasOwn(action, 'baseline') ? action.baseline : state.baseline,+ { historyLimit: state.historyLimit },+ );+ case 'saveStarted':+ return { ...state, saveState: 'saving', error: null };+ case 'saveSucceeded': {+ const baseline = clone(+ Object.hasOwn(action, 'baseline') ? action.baseline : state.draft,+ );+ return derive({+ ...state,+ baseline,+ draft: clone(baseline),+ past: [],+ future: [],+ saveState: 'saved',+ error: null,+ });+ }+ case 'saveFailed':+ return { ...state, saveState: 'error', error: action.error || null };+ default:+ return state;+ }+}diff --git a/frontend/src/hooks/useEditingSession.js b/frontend/src/hooks/useEditingSession.jsnew file mode 100644index 00000000..8842478d--- /dev/null+++ b/frontend/src/hooks/useEditingSession.js@@ -0,0 +1,56 @@+import { useCallback, useReducer, useRef } from 'react';++import { createEditingSession, editingSessionReducer } from './editingSession';++export default function useEditingSession({ baseline, historyLimit = 50 }) {+ const [state, dispatch] = useReducer(+ editingSessionReducer,+ { baseline, historyLimit },+ (initial) => createEditingSession(initial.baseline, {+ historyLimit: initial.historyLimit,+ }),+ );+ const stateRef = useRef(state);+ stateRef.current = state;++ const change = useCallback((path, value, options = {}) => {+ dispatch({ type: 'change', path, value, ...options });+ }, []);+ const transaction = useCallback((next, options = {}) => {+ const payload = typeof next === 'function' ? { update: next } : { draft: next };+ dispatch({ type: 'transaction', ...payload, ...options });+ }, []);+ const undo = useCallback(() => dispatch({ type: 'undo' }), []);+ const redo = useCallback(() => dispatch({ type: 'redo' }), []);+ const reset = useCallback((nextBaseline) => {+ dispatch(nextBaseline === undefined+ ? { type: 'reset' }+ : { type: 'reset', baseline: nextBaseline });+ }, []);+ const save = useCallback(async (saveDraft) => {+ const draft = stateRef.current.draft;+ dispatch({ type: 'saveStarted' });+ try {+ const result = await saveDraft(draft);+ dispatch({+ type: 'saveSucceeded',+ baseline: result === undefined ? draft : result,+ });+ return result;+ } catch (error) {+ dispatch({ type: 'saveFailed', error });+ throw error;+ }+ }, []);++ return {+ ...state,+ change,+ transaction,+ undo,+ redo,+ reset,+ save,+ dispatch,+ };+}