fix: unified handling of editor reloading (#32)
Co-authored-by: hugo <hugoms@me.com>
This commit is contained in:
@@ -7,6 +7,7 @@ import { dispatchAssistantAction } from '../../navigation/assistantActionDispatc
|
||||
import { useA2UISurface } from '../../a2ui/useA2UISurface';
|
||||
import { useAppStore } from '../../store';
|
||||
import { ChatTranscript } from '../ChatSurface';
|
||||
import { useEntityLoader } from '../../navigation/useEntityEditor';
|
||||
import { useI18n } from '../../i18n';
|
||||
import '../../styles/chatSurface.css';
|
||||
import './ChatPanel.css';
|
||||
@@ -89,31 +90,43 @@ export const ChatPanel: React.FC<ChatPanelProps> = ({ conversationId }) => {
|
||||
}
|
||||
}, []);
|
||||
|
||||
// Load conversation and messages
|
||||
const loadData = useCallback(async () => {
|
||||
try {
|
||||
// Load conversation data via shared entity loader (handles activeProject
|
||||
// guard, cancellation on ID change, and close-tab-on-not-found).
|
||||
const fetchChatData = useCallback(
|
||||
async (id: string) => {
|
||||
const [conv, msgs, modelsResult] = await Promise.all([
|
||||
window.electronAPI?.chat.getConversation(conversationId),
|
||||
window.electronAPI?.chat.getHistory(conversationId),
|
||||
window.electronAPI?.chat.getAvailableModels()
|
||||
window.electronAPI?.chat.getConversation(id),
|
||||
window.electronAPI?.chat.getHistory(id),
|
||||
window.electronAPI?.chat.getAvailableModels(),
|
||||
]);
|
||||
if (!conv) return null;
|
||||
|
||||
if (conv) setConversation(conv);
|
||||
if (msgs) {
|
||||
setMessages(msgs);
|
||||
replayFromMessages(msgs);
|
||||
return { conversation: conv, messages: msgs, models: modelsResult?.models };
|
||||
},
|
||||
[],
|
||||
);
|
||||
|
||||
useEntityLoader(conversationId, fetchChatData, {
|
||||
onLoaded: (data) => {
|
||||
setConversation(data.conversation);
|
||||
if (data.messages) {
|
||||
setMessages(data.messages);
|
||||
replayFromMessages(data.messages);
|
||||
}
|
||||
if (modelsResult?.models) setAvailableModels(modelsResult.models);
|
||||
} catch (error) {
|
||||
console.error('Failed to load chat data:', error);
|
||||
}
|
||||
}, [conversationId, replayFromMessages]);
|
||||
if (data.models) setAvailableModels(data.models);
|
||||
},
|
||||
onReset: () => {
|
||||
setConversation(null);
|
||||
},
|
||||
});
|
||||
|
||||
// Check API key readiness
|
||||
useEffect(() => {
|
||||
checkReady();
|
||||
loadData();
|
||||
}, [checkReady]);
|
||||
|
||||
// Subscribe to stream events
|
||||
// Subscribe to stream / tool / title / token events
|
||||
useEffect(() => {
|
||||
const unsubDelta = window.electronAPI?.chat.onStreamDelta((data) => {
|
||||
if (data.conversationId === conversationId) {
|
||||
appendStreamDelta(data.delta);
|
||||
@@ -164,7 +177,7 @@ export const ChatPanel: React.FC<ChatPanelProps> = ({ conversationId }) => {
|
||||
unsubTitle?.();
|
||||
unsubTokenUsage?.();
|
||||
};
|
||||
}, [conversationId, loadData, scrollToBottom, checkReady, appendStreamDelta, recordToolCall, recordToolResult]);
|
||||
}, [conversationId, scrollToBottom, appendStreamDelta, recordToolCall, recordToolResult]);
|
||||
|
||||
// Scroll on new messages or streaming content
|
||||
useEffect(() => {
|
||||
|
||||
@@ -26,6 +26,7 @@ import { InsertModal } from '../InsertModal';
|
||||
import { AISuggestionsModal, AISuggestions } from '../AISuggestionsModal/AISuggestionsModal';
|
||||
import { openEntityTab } from '../../navigation/tabPolicy';
|
||||
import { EditorRoute, resolveEditorRoute } from '../../navigation/editorRouting';
|
||||
import { useEntityLoader, useSaveShortcut } from '../../navigation/useEntityEditor';
|
||||
import { useI18n } from '../../i18n';
|
||||
import documentationContent from '../../../../DOCUMENTATION.md?raw';
|
||||
import apiDocumentationContent from '../../../../API.md?raw';
|
||||
@@ -169,29 +170,25 @@ export const PostEditor: React.FC<PostEditorProps> = ({ postId }) => {
|
||||
} = useAppStore();
|
||||
|
||||
// Fetch full post data from backend
|
||||
const fetchPost = useCallback(
|
||||
(id: string) => window.electronAPI?.posts.get(id).then((p) => (p as PostData) || null) ?? Promise.resolve(null),
|
||||
[],
|
||||
);
|
||||
|
||||
const [post, setPost] = useState<PostData | null>(null);
|
||||
const [isLoadingPost, setIsLoadingPost] = useState(true);
|
||||
// Track whether form state has been initialized from post data
|
||||
const [isInitialized, setIsInitialized] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
let cancelled = false;
|
||||
setIsLoadingPost(true);
|
||||
setIsInitialized(false);
|
||||
window.electronAPI?.posts.get(postId).then((fetchedPost) => {
|
||||
if (cancelled) return;
|
||||
if (fetchedPost) {
|
||||
setPost(fetchedPost as PostData);
|
||||
// Also update the store so other components have the full data
|
||||
useAppStore.getState().updatePost(postId, fetchedPost as Partial<PostData>);
|
||||
} else {
|
||||
// Post doesn't exist, close the tab
|
||||
closeTab(postId);
|
||||
}
|
||||
setIsLoadingPost(false);
|
||||
});
|
||||
return () => { cancelled = true; };
|
||||
}, [postId, closeTab]);
|
||||
|
||||
const { isLoading: isLoadingPost } = useEntityLoader<PostData>(postId, fetchPost, {
|
||||
onLoaded: (loadedPost) => {
|
||||
setPost(loadedPost);
|
||||
useAppStore.getState().updatePost(postId, loadedPost as Partial<PostData>);
|
||||
},
|
||||
onReset: () => {
|
||||
setPost(null);
|
||||
setIsInitialized(false);
|
||||
},
|
||||
});
|
||||
|
||||
const [title, setTitle] = useState('');
|
||||
const [content, setContent] = useState('');
|
||||
@@ -705,17 +702,7 @@ export const PostEditor: React.FC<PostEditorProps> = ({ postId }) => {
|
||||
};
|
||||
|
||||
// Save on Ctrl+S
|
||||
useEffect(() => {
|
||||
const handleKeyDown = (e: KeyboardEvent) => {
|
||||
if ((e.ctrlKey || e.metaKey) && e.key === 's') {
|
||||
e.preventDefault();
|
||||
handleSave();
|
||||
}
|
||||
};
|
||||
|
||||
window.addEventListener('keydown', handleKeyDown);
|
||||
return () => window.removeEventListener('keydown', handleKeyDown);
|
||||
}, [handleSave]);
|
||||
useSaveShortcut(handleSave);
|
||||
|
||||
// Listen for menu events
|
||||
useEffect(() => {
|
||||
@@ -1055,6 +1042,7 @@ export const PostEditor: React.FC<PostEditorProps> = ({ postId }) => {
|
||||
const MediaEditor: React.FC<{ mediaId: string }> = ({ mediaId }) => {
|
||||
const { t: tr } = useI18n();
|
||||
const { media, updateMedia, showErrorModal, showConfirmDeleteModal, openTab } = useAppStore();
|
||||
const activeProjectId = useAppStore((s) => s.activeProject?.id ?? null);
|
||||
const item = media.find(m => m.id === mediaId);
|
||||
|
||||
const [title, setTitle] = useState(item?.title || '');
|
||||
@@ -1081,12 +1069,13 @@ const MediaEditor: React.FC<{ mediaId: string }> = ({ mediaId }) => {
|
||||
|
||||
// Load project language setting
|
||||
useEffect(() => {
|
||||
if (!activeProjectId) return;
|
||||
window.electronAPI?.meta.getProjectMetadata().then(metadata => {
|
||||
if (metadata?.mainLanguage) {
|
||||
setProjectLanguage(metadata.mainLanguage);
|
||||
}
|
||||
});
|
||||
}, []);
|
||||
}, [activeProjectId]);
|
||||
|
||||
// Close quick actions menu when clicking outside
|
||||
useEffect(() => {
|
||||
@@ -1152,7 +1141,7 @@ const MediaEditor: React.FC<{ mediaId: string }> = ({ mediaId }) => {
|
||||
// Load linked posts for this media and fetch their titles
|
||||
useEffect(() => {
|
||||
const loadLinkedPosts = async () => {
|
||||
if (!mediaId) return;
|
||||
if (!mediaId || !activeProjectId) return;
|
||||
try {
|
||||
const links = await window.electronAPI?.postMedia.getForMedia(mediaId);
|
||||
if (links) {
|
||||
@@ -1172,7 +1161,7 @@ const MediaEditor: React.FC<{ mediaId: string }> = ({ mediaId }) => {
|
||||
}
|
||||
};
|
||||
loadLinkedPosts();
|
||||
}, [mediaId]);
|
||||
}, [mediaId, activeProjectId]);
|
||||
|
||||
// Fetch posts for the picker when it opens
|
||||
useEffect(() => {
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import React, { useState, useCallback, useEffect, useRef } from 'react';
|
||||
import type { ChatModel } from '../../types/electron';
|
||||
import { useEntityLoader } from '../../navigation/useEntityEditor';
|
||||
import { useI18n } from '../../i18n';
|
||||
import './ImportAnalysisView.css';
|
||||
|
||||
@@ -162,7 +163,6 @@ export const ImportAnalysisView: React.FC<ImportAnalysisViewProps> = ({ definiti
|
||||
const [wxrFilePath, setWxrFilePath] = useState<string | null>(null);
|
||||
const [report, setReport] = useState<AnalysisReport | null>(null);
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
const [isLoadingDefinition, setIsLoadingDefinition] = useState(true);
|
||||
const [expandedSections, setExpandedSections] = useState<Record<string, boolean>>({});
|
||||
const [progressStep, setProgressStep] = useState<string>('');
|
||||
const [progressDetail, setProgressDetail] = useState<string>('');
|
||||
@@ -308,31 +308,33 @@ export const ImportAnalysisView: React.FC<ImportAnalysisViewProps> = ({ definiti
|
||||
await persistReport(updatedReport);
|
||||
}, [report, persistReport]);
|
||||
|
||||
// Load definition on mount
|
||||
useEffect(() => {
|
||||
const load = async () => {
|
||||
setIsLoadingDefinition(true);
|
||||
try {
|
||||
const def = await window.electronAPI?.importDefinitions.get(definitionId);
|
||||
if (def) {
|
||||
setName(def.name);
|
||||
if (def.uploadsFolderPath) setUploadsFolder(def.uploadsFolderPath);
|
||||
if (def.wxrFilePath) setWxrFilePath(def.wxrFilePath);
|
||||
if (def.lastAnalysisResult) {
|
||||
const parsed = typeof def.lastAnalysisResult === 'string'
|
||||
? JSON.parse(def.lastAnalysisResult)
|
||||
: def.lastAnalysisResult;
|
||||
setReport(parsed as AnalysisReport);
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Failed to load import definition:', error);
|
||||
} finally {
|
||||
setIsLoadingDefinition(false);
|
||||
// Load definition via shared entity loader (handles activeProject guard,
|
||||
// cancellation on ID change, and close-tab-on-not-found).
|
||||
const fetchDefinition = useCallback(
|
||||
(id: string) => window.electronAPI?.importDefinitions.get(id) ?? Promise.resolve(null),
|
||||
[],
|
||||
);
|
||||
const { isLoading: isLoadingDefinition } = useEntityLoader(definitionId, fetchDefinition, {
|
||||
onLoaded: (def) => {
|
||||
setName(def.name);
|
||||
setUploadsFolder(def.uploadsFolderPath ?? null);
|
||||
setWxrFilePath(def.wxrFilePath ?? null);
|
||||
if (def.lastAnalysisResult) {
|
||||
const parsed = typeof def.lastAnalysisResult === 'string'
|
||||
? JSON.parse(def.lastAnalysisResult)
|
||||
: def.lastAnalysisResult;
|
||||
setReport(parsed as AnalysisReport);
|
||||
} else {
|
||||
setReport(null);
|
||||
}
|
||||
};
|
||||
load();
|
||||
}, [definitionId]);
|
||||
},
|
||||
onReset: () => {
|
||||
setName(t('importAnalysis.untitledImport'));
|
||||
setUploadsFolder(null);
|
||||
setWxrFilePath(null);
|
||||
setReport(null);
|
||||
},
|
||||
});
|
||||
|
||||
const handleNameBlur = useCallback(async () => {
|
||||
const trimmed = name.trim() || t('importAnalysis.untitledImport');
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react';
|
||||
import { Tree } from 'react-arborist';
|
||||
import { useI18n } from '../../i18n';
|
||||
import { useAppStore } from '../../store';
|
||||
import { showToast } from '../Toast';
|
||||
import type { MenuDocument, MenuItemData, PostData } from '../../../main/shared/electronApi';
|
||||
import { PageInput } from '../PageInput';
|
||||
@@ -185,6 +186,7 @@ function renderMenuKindIcon(kind: MenuItemData['kind']): React.ReactNode {
|
||||
|
||||
export const MenuEditorView: React.FC = () => {
|
||||
const { t: tr } = useI18n();
|
||||
const activeProjectId = useAppStore((s) => s.activeProject?.id ?? null);
|
||||
const [items, setItems] = useState<MenuItemData[]>([]);
|
||||
const [selectedId, setSelectedId] = useState<string | null>(null);
|
||||
const [isLoading, setIsLoading] = useState(true);
|
||||
@@ -217,6 +219,7 @@ export const MenuEditorView: React.FC = () => {
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
if (!activeProjectId) return;
|
||||
const load = async () => {
|
||||
setIsLoading(true);
|
||||
try {
|
||||
@@ -258,7 +261,7 @@ export const MenuEditorView: React.FC = () => {
|
||||
};
|
||||
|
||||
void load();
|
||||
}, [tr]);
|
||||
}, [tr, activeProjectId]);
|
||||
|
||||
useEffect(() => {
|
||||
return () => {
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import React, { useState, useEffect, useCallback } from 'react';
|
||||
import { useAppStore } from '../../store';
|
||||
import { showToast } from '../Toast';
|
||||
import { useI18n } from '../../i18n';
|
||||
import './MetadataDiffPanel.css';
|
||||
@@ -42,6 +43,7 @@ type ScanPhase = 'idle' | 'loading-stats' | 'scanning' | 'complete';
|
||||
|
||||
export const MetadataDiffPanel: React.FC = () => {
|
||||
const { t: tr } = useI18n();
|
||||
const activeProjectId = useAppStore((s) => s.activeProject?.id ?? null);
|
||||
const [stats, setStats] = useState<TableStats | null>(null);
|
||||
const [scanResult, setScanResult] = useState<ScanResult | null>(null);
|
||||
const [scanPhase, setScanPhase] = useState<ScanPhase>('idle');
|
||||
@@ -51,6 +53,7 @@ export const MetadataDiffPanel: React.FC = () => {
|
||||
|
||||
// Load initial stats
|
||||
useEffect(() => {
|
||||
if (!activeProjectId) return;
|
||||
const loadStats = async () => {
|
||||
setScanPhase('loading-stats');
|
||||
try {
|
||||
@@ -65,7 +68,7 @@ export const MetadataDiffPanel: React.FC = () => {
|
||||
setScanPhase('idle');
|
||||
};
|
||||
loadStats();
|
||||
}, [tr]);
|
||||
}, [tr, activeProjectId]);
|
||||
|
||||
// Subscribe to task progress
|
||||
useEffect(() => {
|
||||
|
||||
@@ -4,6 +4,7 @@ import type { ScriptData } from '../../../main/shared/electronApi';
|
||||
import { useAppStore } from '../../store';
|
||||
import { BDS_EVENT_SCRIPTS_CHANGED, dispatchWindowEvent } from '../../utils';
|
||||
import { getPythonRuntimeManager } from '../../python/runtimeManagerInstance';
|
||||
import { useEntityLoader, useSaveShortcut } from '../../navigation/useEntityEditor';
|
||||
import { useI18n } from '../../i18n';
|
||||
import { showToast } from '../Toast';
|
||||
import './ScriptsView.css';
|
||||
@@ -46,6 +47,12 @@ export const ScriptsView: React.FC<ScriptsViewProps> = ({ scriptId }) => {
|
||||
const { t, language } = useI18n();
|
||||
const appendPanelOutputEntry = useAppStore((state) => state.appendPanelOutputEntry);
|
||||
const closeTab = useAppStore((state) => state.closeTab);
|
||||
|
||||
const fetchScript = useCallback(
|
||||
(id: string) => window.electronAPI?.scripts.get(id) ?? Promise.resolve(null),
|
||||
[],
|
||||
);
|
||||
|
||||
const [script, setScript] = useState<ScriptData | null>(null);
|
||||
const [title, setTitle] = useState('');
|
||||
const [slug, setSlug] = useState('');
|
||||
@@ -63,6 +70,65 @@ export const ScriptsView: React.FC<ScriptsViewProps> = ({ scriptId }) => {
|
||||
// Token incremented to signal Monaco to remount with fresh defaultValue.
|
||||
// Prevents controlled-mode cursor jumps during typing.
|
||||
const [monacoResetToken, setMonacoResetToken] = useState(0);
|
||||
// Ref for entrypoint refresh cancellation — survives across renders
|
||||
// without triggering the entityLoader effect.
|
||||
const entrypointCancelRef = useRef(false);
|
||||
|
||||
useEntityLoader<ScriptData>(scriptId, fetchScript, {
|
||||
onLoaded: (loadedScript) => {
|
||||
setScript(loadedScript);
|
||||
setTitle(loadedScript.title || '');
|
||||
setSlug(toFunctionSlug(loadedScript.slug || loadedScript.title || ''));
|
||||
setKind(loadedScript.kind || 'utility');
|
||||
setEntrypoint(loadedScript.entrypoint || 'render');
|
||||
setEnabled(loadedScript.enabled ?? true);
|
||||
setScriptContent(loadedScript.content || '');
|
||||
setMonacoResetToken(prev => prev + 1);
|
||||
const normalizedExisting = toFunctionSlug(loadedScript.slug || loadedScript.title || '');
|
||||
setIsSlugManuallyEdited(normalizedExisting !== toFunctionSlug(loadedScript.title || ''));
|
||||
|
||||
// Refresh entrypoints asynchronously
|
||||
entrypointCancelRef.current = true; // cancel any pending refresh
|
||||
const cancelToken = {};
|
||||
entrypointCancelRef.current = false;
|
||||
const refreshEntrypoints = async () => {
|
||||
try {
|
||||
const runtimeManager = getPythonRuntimeManager();
|
||||
const discoveredEntrypoints = await runtimeManager.inspectEntrypoints(
|
||||
loadedScript.content || '',
|
||||
{ cacheKey: buildCacheKey(loadedScript, loadedScript.content || '') },
|
||||
);
|
||||
const available = withMainEntrypoint(discoveredEntrypoints);
|
||||
|
||||
if (entrypointCancelRef.current) return;
|
||||
|
||||
setAvailableEntrypoints(available);
|
||||
const preferredEntrypoint = available.includes(loadedScript.entrypoint)
|
||||
? loadedScript.entrypoint
|
||||
: 'main';
|
||||
setEntrypoint(preferredEntrypoint);
|
||||
} catch {
|
||||
if (entrypointCancelRef.current) return;
|
||||
setAvailableEntrypoints(['main']);
|
||||
setEntrypoint('main');
|
||||
}
|
||||
};
|
||||
void refreshEntrypoints();
|
||||
},
|
||||
onReset: () => {
|
||||
entrypointCancelRef.current = true;
|
||||
setScript(null);
|
||||
setTitle('');
|
||||
setSlug('');
|
||||
setKind('utility');
|
||||
setEntrypoint('render');
|
||||
setAvailableEntrypoints(['main']);
|
||||
setEnabled(true);
|
||||
setScriptContent('');
|
||||
setMonacoResetToken(prev => prev + 1);
|
||||
setIsSlugManuallyEdited(false);
|
||||
},
|
||||
});
|
||||
|
||||
const buildCacheKey = (scriptMeta: Pick<ScriptData, 'id' | 'version'>, content: string): string => {
|
||||
let hash = 0;
|
||||
@@ -166,86 +232,6 @@ export const ScriptsView: React.FC<ScriptsViewProps> = ({ scriptId }) => {
|
||||
}
|
||||
}, [appendPanelOutputEntry, applySyntaxMarkers, isCheckingSyntax, script, scriptContent, t]);
|
||||
|
||||
useEffect(() => {
|
||||
let cancelled = false;
|
||||
|
||||
const refreshEntrypoints = async (content: string, scriptMeta: ScriptData) => {
|
||||
try {
|
||||
const runtimeManager = getPythonRuntimeManager();
|
||||
const discoveredEntrypoints = await runtimeManager.inspectEntrypoints(content, {
|
||||
cacheKey: buildCacheKey(scriptMeta, content),
|
||||
});
|
||||
const available = withMainEntrypoint(discoveredEntrypoints);
|
||||
|
||||
if (cancelled) {
|
||||
return;
|
||||
}
|
||||
|
||||
setAvailableEntrypoints(available);
|
||||
|
||||
const preferredEntrypoint = available.includes(scriptMeta.entrypoint)
|
||||
? scriptMeta.entrypoint
|
||||
: 'main';
|
||||
setEntrypoint(preferredEntrypoint);
|
||||
} catch (error) {
|
||||
if (cancelled) {
|
||||
return;
|
||||
}
|
||||
setAvailableEntrypoints(['main']);
|
||||
setEntrypoint('main');
|
||||
}
|
||||
};
|
||||
|
||||
const loadScript = async () => {
|
||||
if (!scriptId) {
|
||||
setScript(null);
|
||||
setTitle('');
|
||||
setSlug('');
|
||||
setKind('utility');
|
||||
setEntrypoint('render');
|
||||
setAvailableEntrypoints(['main']);
|
||||
setEnabled(true);
|
||||
setScriptContent('');
|
||||
setMonacoResetToken(prev => prev + 1);
|
||||
setIsSlugManuallyEdited(false);
|
||||
return;
|
||||
}
|
||||
|
||||
const item = await window.electronAPI?.scripts.get(scriptId);
|
||||
if (cancelled || !item) {
|
||||
setScript(null);
|
||||
setTitle('');
|
||||
setSlug('');
|
||||
setKind('utility');
|
||||
setEntrypoint('render');
|
||||
setAvailableEntrypoints(['main']);
|
||||
setEnabled(true);
|
||||
setScriptContent('');
|
||||
setMonacoResetToken(prev => prev + 1);
|
||||
setIsSlugManuallyEdited(false);
|
||||
return;
|
||||
}
|
||||
|
||||
setScript(item);
|
||||
setTitle(item.title || '');
|
||||
setSlug(toFunctionSlug(item.slug || item.title || ''));
|
||||
setKind(item.kind || 'utility');
|
||||
setEntrypoint(item.entrypoint || 'render');
|
||||
setEnabled(item.enabled ?? true);
|
||||
setScriptContent(item.content || '');
|
||||
setMonacoResetToken(prev => prev + 1);
|
||||
const normalizedExisting = toFunctionSlug(item.slug || item.title || '');
|
||||
setIsSlugManuallyEdited(normalizedExisting !== toFunctionSlug(item.title || ''));
|
||||
await refreshEntrypoints(item.content || '', item);
|
||||
};
|
||||
|
||||
void loadScript();
|
||||
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, [scriptId]);
|
||||
|
||||
const hasChanges = !!script && (
|
||||
title !== script.title ||
|
||||
slug !== script.slug ||
|
||||
@@ -340,21 +326,7 @@ export const ScriptsView: React.FC<ScriptsViewProps> = ({ scriptId }) => {
|
||||
}
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
const handleKeyDown = (event: KeyboardEvent) => {
|
||||
if ((event.ctrlKey || event.metaKey) && event.key === 's') {
|
||||
event.preventDefault();
|
||||
void handleSaveScript();
|
||||
}
|
||||
};
|
||||
|
||||
if (typeof window.addEventListener !== 'function' || typeof window.removeEventListener !== 'function') {
|
||||
return;
|
||||
}
|
||||
|
||||
window.addEventListener('keydown', handleKeyDown);
|
||||
return () => window.removeEventListener('keydown', handleKeyDown);
|
||||
}, [handleSaveScript]);
|
||||
useSaveShortcut(useCallback(() => { void handleSaveScript(); }, [handleSaveScript]));
|
||||
|
||||
const handleRunScript = async () => {
|
||||
if (!script || isRunning) {
|
||||
|
||||
@@ -133,6 +133,7 @@ const SectionHeader: React.FC<{
|
||||
export const TagsView: React.FC = () => {
|
||||
const { t } = useI18n();
|
||||
const { showErrorModal } = useAppStore();
|
||||
const activeProjectId = useAppStore((s) => s.activeProject?.id ?? null);
|
||||
|
||||
// State
|
||||
const [tagsWithCounts, setTagsWithCounts] = useState<TagWithCount[]>([]);
|
||||
@@ -181,22 +182,25 @@ export const TagsView: React.FC = () => {
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
if (!activeProjectId) return;
|
||||
loadTags();
|
||||
}, [loadTags]);
|
||||
}, [loadTags, activeProjectId]);
|
||||
|
||||
// Listen for tag events
|
||||
useEffect(() => {
|
||||
if (!activeProjectId) return;
|
||||
return subscribeToTagEvents(window.electronAPI?.on, loadTags, {
|
||||
includeUpdated: true,
|
||||
});
|
||||
}, [loadTags]);
|
||||
}, [loadTags, activeProjectId]);
|
||||
|
||||
// Load post templates on mount
|
||||
useEffect(() => {
|
||||
if (!activeProjectId) return;
|
||||
window.electronAPI?.templates.getEnabledByKind('post').then((templates) => {
|
||||
setPostTemplates(templates.map((t) => ({ slug: t.slug, title: t.title })));
|
||||
});
|
||||
}, []);
|
||||
}, [activeProjectId]);
|
||||
|
||||
// Handle tag selection
|
||||
const handleTagSelect = (name: string) => {
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
import React, { useEffect, useState } from 'react';
|
||||
import React, { useCallback, useState } from 'react';
|
||||
import MonacoEditor from '@monaco-editor/react';
|
||||
import type { TemplateData, TemplateKind } from '../../../main/shared/electronApi';
|
||||
import { useAppStore } from '../../store';
|
||||
import { BDS_EVENT_TEMPLATES_CHANGED, dispatchWindowEvent } from '../../utils';
|
||||
import { useEntityLoader, useSaveShortcut } from '../../navigation/useEntityEditor';
|
||||
import { useI18n } from '../../i18n';
|
||||
import { showToast } from '../Toast';
|
||||
import './TemplatesView.css';
|
||||
@@ -30,6 +31,12 @@ interface TemplatesViewProps {
|
||||
export const TemplatesView: React.FC<TemplatesViewProps> = ({ templateId }) => {
|
||||
const { t, language } = useI18n();
|
||||
const closeTab = useAppStore((state) => state.closeTab);
|
||||
|
||||
const fetchTemplate = useCallback(
|
||||
(id: string) => window.electronAPI?.templates.get(id) ?? Promise.resolve(null),
|
||||
[],
|
||||
);
|
||||
|
||||
const [template, setTemplate] = useState<TemplateData | null>(null);
|
||||
const [title, setTitle] = useState('');
|
||||
const [slug, setSlug] = useState('');
|
||||
@@ -41,52 +48,29 @@ export const TemplatesView: React.FC<TemplatesViewProps> = ({ templateId }) => {
|
||||
const [isValidating, setIsValidating] = useState(false);
|
||||
const [monacoResetToken, setMonacoResetToken] = useState(0);
|
||||
|
||||
useEffect(() => {
|
||||
let cancelled = false;
|
||||
|
||||
const loadTemplate = async () => {
|
||||
if (!templateId) {
|
||||
setTemplate(null);
|
||||
setTitle('');
|
||||
setSlug('');
|
||||
setKind('post');
|
||||
setEnabled(true);
|
||||
setTemplateContent('');
|
||||
setMonacoResetToken((prev) => prev + 1);
|
||||
setIsSlugManuallyEdited(false);
|
||||
return;
|
||||
}
|
||||
|
||||
const item = await window.electronAPI?.templates.get(templateId);
|
||||
if (cancelled || !item) {
|
||||
setTemplate(null);
|
||||
setTitle('');
|
||||
setSlug('');
|
||||
setKind('post');
|
||||
setEnabled(true);
|
||||
setTemplateContent('');
|
||||
setMonacoResetToken((prev) => prev + 1);
|
||||
setIsSlugManuallyEdited(false);
|
||||
return;
|
||||
}
|
||||
|
||||
setTemplate(item);
|
||||
setTitle(item.title || '');
|
||||
setSlug(item.slug || toTemplateSlug(item.title || ''));
|
||||
setKind(item.kind || 'post');
|
||||
setEnabled(item.enabled ?? true);
|
||||
setTemplateContent(item.content || '');
|
||||
useEntityLoader<TemplateData>(templateId, fetchTemplate, {
|
||||
onLoaded: (loadedTemplate) => {
|
||||
setTemplate(loadedTemplate);
|
||||
setTitle(loadedTemplate.title || '');
|
||||
setSlug(loadedTemplate.slug || toTemplateSlug(loadedTemplate.title || ''));
|
||||
setKind(loadedTemplate.kind || 'post');
|
||||
setEnabled(loadedTemplate.enabled ?? true);
|
||||
setTemplateContent(loadedTemplate.content || '');
|
||||
setMonacoResetToken((prev) => prev + 1);
|
||||
const normalizedExisting = toTemplateSlug(item.slug || item.title || '');
|
||||
setIsSlugManuallyEdited(normalizedExisting !== toTemplateSlug(item.title || ''));
|
||||
};
|
||||
|
||||
void loadTemplate();
|
||||
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, [templateId]);
|
||||
const normalizedExisting = toTemplateSlug(loadedTemplate.slug || loadedTemplate.title || '');
|
||||
setIsSlugManuallyEdited(normalizedExisting !== toTemplateSlug(loadedTemplate.title || ''));
|
||||
},
|
||||
onReset: () => {
|
||||
setTemplate(null);
|
||||
setTitle('');
|
||||
setSlug('');
|
||||
setKind('post');
|
||||
setEnabled(true);
|
||||
setTemplateContent('');
|
||||
setMonacoResetToken((prev) => prev + 1);
|
||||
setIsSlugManuallyEdited(false);
|
||||
},
|
||||
});
|
||||
|
||||
const hasChanges =
|
||||
!!template &&
|
||||
@@ -214,21 +198,7 @@ export const TemplatesView: React.FC<TemplatesViewProps> = ({ templateId }) => {
|
||||
}
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
const handleKeyDown = (event: KeyboardEvent) => {
|
||||
if ((event.ctrlKey || event.metaKey) && event.key === 's') {
|
||||
event.preventDefault();
|
||||
void handleSaveTemplate();
|
||||
}
|
||||
};
|
||||
|
||||
if (typeof window.addEventListener !== 'function' || typeof window.removeEventListener !== 'function') {
|
||||
return;
|
||||
}
|
||||
|
||||
window.addEventListener('keydown', handleKeyDown);
|
||||
return () => window.removeEventListener('keydown', handleKeyDown);
|
||||
}, [handleSaveTemplate]);
|
||||
useSaveShortcut(useCallback(() => { void handleSaveTemplate(); }, [handleSaveTemplate]));
|
||||
|
||||
return (
|
||||
<div className="templates-view-shell">
|
||||
|
||||
108
src/renderer/navigation/useEntityEditor.ts
Normal file
108
src/renderer/navigation/useEntityEditor.ts
Normal file
@@ -0,0 +1,108 @@
|
||||
import { useCallback, useEffect, useState } from 'react';
|
||||
import { useAppStore } from '../store';
|
||||
|
||||
/**
|
||||
* Shared hook for entity editors that load data by ID.
|
||||
*
|
||||
* Handles:
|
||||
* - Deferring load until activeProject is available (startup race condition)
|
||||
* - Cancellation of in-flight fetches on ID change / unmount
|
||||
* - Closing the tab when the entity is not found (e.g. after project switch)
|
||||
* - Providing a reload() helper for external-change refresh
|
||||
*
|
||||
* Instead of returning data that requires a separate sync effect, this hook
|
||||
* calls `onLoaded` / `onReset` directly from within the fetch effect so
|
||||
* that local state updates in the same render cycle as the load — matching
|
||||
* the timing behaviour editors had when each hand-rolled its own load logic.
|
||||
*
|
||||
* @param entityId The entity primary key, or null for the "no entity" state.
|
||||
* @param fetcher Async function that takes an ID and returns the entity or null.
|
||||
* @param callbacks `onLoaded(data)` when entity arrives, `onReset()` when
|
||||
* entityId is null or entity was not found.
|
||||
*/
|
||||
export function useEntityLoader<T>(
|
||||
entityId: string | null,
|
||||
fetcher: (id: string) => Promise<T | null>,
|
||||
callbacks: {
|
||||
onLoaded: (data: T) => void;
|
||||
onReset: () => void;
|
||||
},
|
||||
): {
|
||||
isLoading: boolean;
|
||||
reload: () => void;
|
||||
} {
|
||||
const activeProjectId = useAppStore((s) => s.activeProject?.id ?? null);
|
||||
const closeTab = useAppStore((s) => s.closeTab);
|
||||
|
||||
const [isLoading, setIsLoading] = useState(true);
|
||||
const [reloadToken, setReloadToken] = useState(0);
|
||||
|
||||
useEffect(() => {
|
||||
if (!entityId) {
|
||||
callbacks.onReset();
|
||||
setIsLoading(false);
|
||||
return;
|
||||
}
|
||||
|
||||
if (!activeProjectId) {
|
||||
// Project context not ready yet — stay in loading state, will
|
||||
// re-run once activeProjectId appears.
|
||||
callbacks.onReset();
|
||||
setIsLoading(true);
|
||||
return;
|
||||
}
|
||||
|
||||
let cancelled = false;
|
||||
setIsLoading(true);
|
||||
|
||||
fetcher(entityId).then((result) => {
|
||||
if (cancelled) return;
|
||||
|
||||
if (result) {
|
||||
callbacks.onLoaded(result);
|
||||
} else {
|
||||
// Entity doesn't exist in this project — close the orphaned tab.
|
||||
callbacks.onReset();
|
||||
closeTab(entityId);
|
||||
}
|
||||
setIsLoading(false);
|
||||
});
|
||||
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
// callbacks intentionally excluded — they are inline objects whose
|
||||
// identity changes each render; the real dependencies are the
|
||||
// entityId, activeProjectId, and reloadToken.
|
||||
}, [entityId, activeProjectId, reloadToken, fetcher, closeTab]);
|
||||
|
||||
const reload = useCallback(() => {
|
||||
setReloadToken((prev) => prev + 1);
|
||||
}, []);
|
||||
|
||||
return { isLoading, reload };
|
||||
}
|
||||
|
||||
/**
|
||||
* Bind Cmd/Ctrl+S to a save callback.
|
||||
*
|
||||
* Replaces the identical keydown listener that was copy-pasted across
|
||||
* PostEditor, ScriptsView, and TemplatesView.
|
||||
*/
|
||||
export function useSaveShortcut(onSave: () => void): void {
|
||||
useEffect(() => {
|
||||
if (typeof window.addEventListener !== 'function' || typeof window.removeEventListener !== 'function') {
|
||||
return;
|
||||
}
|
||||
|
||||
const handleKeyDown = (event: KeyboardEvent) => {
|
||||
if ((event.ctrlKey || event.metaKey) && event.key === 's') {
|
||||
event.preventDefault();
|
||||
onSave();
|
||||
}
|
||||
};
|
||||
|
||||
window.addEventListener('keydown', handleKeyDown);
|
||||
return () => window.removeEventListener('keydown', handleKeyDown);
|
||||
}, [onSave]);
|
||||
}
|
||||
Reference in New Issue
Block a user