import { ref, computed, inject, InjectionKey, watch, onMounted, onUnmounted } from 'vue'; import { StoreKey, type LuminaStore } from '../core/store'; import { getByPath } from '../utils/deep'; interface HistorySnapshot { deck: any; currentIndex: number; timestamp: number; } export const EditorKey: InjectionKey> = Symbol('EditorKey'); export function createEditor(manualStore?: LuminaStore) { const store = manualStore || inject(StoreKey); if (!store) { throw new Error("Lumina Editor requires Lumina Store."); } // --- State --- const selection = ref(null); const clipboard = ref(null); const history = ref([]); const historyIndex = ref(-1); const previewMode = ref(false); const togglePreview = () => { previewMode.value = !previewMode.value; }; // --- Selection --- const select = (path: string | null) => { selection.value = path; }; const getSelectedData = () => { if (!selection.value || !store.state.deck) return null; return getByPath(store.state.deck, selection.value); }; // --- History Management --- let debounceTimer: any = null; const isUndoRedoOp = ref(false); // Internal flag to prevent history loops const commit = (immediate = false) => { if (isUndoRedoOp.value) return; // Clear any pending debounce if (debounceTimer) { clearTimeout(debounceTimer); debounceTimer = null; } const pushToHistory = () => { // Remove future history if we were in the middle of the stack if (historyIndex.value < history.value.length - 1) { history.value = history.value.slice(0, historyIndex.value + 1); } if (store.state.deck) { // Deduplicate: Don't push if identical to current head const currentHead = history.value[historyIndex.value]; const newSnapshot = JSON.parse(JSON.stringify(store.state.deck)); const currentIndex = store.state.currentIndex; if (currentHead && JSON.stringify(currentHead.deck) === JSON.stringify(newSnapshot) && currentHead.currentIndex === currentIndex ) { return; } history.value.push({ deck: newSnapshot, currentIndex: currentIndex, timestamp: Date.now() }); historyIndex.value++; // Limit history size if (history.value.length > 50) { history.value.shift(); historyIndex.value--; } } }; if (immediate) { pushToHistory(); } else { // Debounce for text typing etc. debounceTimer = setTimeout(pushToHistory, 500); } }; // Watch for ANY change in the deck watch( () => store.state.deck, (newVal) => { if (newVal && !isUndoRedoOp.value) { commit(false); // Debounced by default } }, { deep: true } ); // Also watch index changes so navigation is undoable watch( () => store.state.currentIndex, () => { if (!isUndoRedoOp.value) { commit(false); } } ); const undo = () => { // Force commit any pending changes (e.g. from debounce) // so we can undo from the current state commit(true); if (historyIndex.value > 0) { isUndoRedoOp.value = true; historyIndex.value--; const snapshot = history.value[historyIndex.value]; if (snapshot) { store.loadDeck(JSON.parse(JSON.stringify(snapshot.deck))); store.goto(snapshot.currentIndex); // Restore slide position } // Wait for Vue reactivity to settle before re-enabling watcher setTimeout(() => { isUndoRedoOp.value = false; }, 100); } }; const redo = () => { // Force commit shouldn't be necessary for redo usually (as we are going forward), // but for consistency if we made a change then decided to redo?? // Actually if we make a change, history is sliced, so we can't redo. // So redo checks are safe. // But let's keep logic simple. if (historyIndex.value < history.value.length - 1) { isUndoRedoOp.value = true; historyIndex.value++; const snapshot = history.value[historyIndex.value]; if (snapshot) { store.loadDeck(JSON.parse(JSON.stringify(snapshot.deck))); store.goto(snapshot.currentIndex); // Restore slide position } setTimeout(() => { isUndoRedoOp.value = false; }, 100); } }; // --- Keyboard Shortcuts --- const handleKeydown = (e: KeyboardEvent) => { // Only trigger if no input/textarea is focused (unless it's just a general command) // Actually, standard undo/redo SHOULD work in inputs too, but browser handles that natively for text. // We want app-level undo. if ((e.ctrlKey || e.metaKey) && e.key === 'z') { if (e.shiftKey) { e.preventDefault(); redo(); } else { e.preventDefault(); undo(); } } else if ((e.ctrlKey || e.metaKey) && e.key === 'y') { e.preventDefault(); redo(); } }; onMounted(() => { window.addEventListener('keydown', handleKeydown); // Initial commit if (store.state.deck && history.value.length === 0) { commit(true); } }); onUnmounted(() => { window.removeEventListener('keydown', handleKeydown); }); // --- Clipboard --- const copy = () => { if (!selection.value || !store.state.deck) return; const data = getByPath(store.state.deck, selection.value); if (data) { clipboard.value = JSON.parse(JSON.stringify(data)); } }; const paste = (targetArrayPath: string) => { if (!clipboard.value) return; store.addNode(targetArrayPath, JSON.parse(JSON.stringify(clipboard.value))); // Watcher will catch this }; // --- Update Helpers --- const updateSelected = (key: string, value: any) => { if (!selection.value) return; store.updateNode(`${selection.value}.${key}`, value); }; return { selection, clipboard, store, previewMode, togglePreview, canUndo: computed(() => historyIndex.value > 0), canRedo: computed(() => historyIndex.value < history.value.length - 1), select, getSelectedData, updateSelected, commit, // Exposed but mostly internal now undo, redo, copy, paste }; } export function useEditor() { const editor = inject(EditorKey); if (!editor) { throw new Error("useEditor must be used within LuminaStudio"); } return editor; }