Files
Netcatty/components/editor/TextEditorTabView.tsx
T
陈大猫andClaude Opus 5.5 1b9c744fda perf(ui): stop whole-shell re-renders on clicks, focus, typing and modifiers (#4117)
Several everyday interactions re-rendered the entire shell (AppView, TopTabs,
TerminalLayer and every pane) even though nothing they show had changed:

- Clicking or focusing a split pane always replaced the workspaces array
  (twice per click: onClick + onFocusCapture), cascading through the whole
  app and re-saving the session restore snapshot. setWorkspaceFocusedSession
  and moveFocusInWorkspace now keep the same array when focus is unchanged
  (domain/workspace.ts setWorkspaceFocusedSessionId).
- Every window focus/visibility change resynced app lock and produced a new
  runtime state object even when nothing changed, re-rendering the provider
  tree. Equal states keep the current object and useAppLockState's result is
  memoized.
- Quick switcher keystrokes went through AppSideEffects state and the
  app-local UI store, re-rendering AppSideEffects, every host island, AppShell,
  AppView and TopTabs per character. QuickSwitcherOverlay now owns the query
  and host results; the overlay unmounts on close, which resets the query
  exactly where setQuickSearch('') used to.
- Pressing/releasing Ctrl/Cmd (every ⌘C/⌘V/Ctrl+C) re-rendered the whole tab
  bar to toggle shortcut number badges. The held flag now lives in a small
  store read only by each tab's TabIconSlot.
- AppView passed fresh inline callbacks that defeated TopTabs' memo comparator
  and every open editor tab; TextEditorTabView is now memoized. TopTabs
  memoizes per-workspace session lists and hoists the root tab icons.
- Workspace drag previews only update state when the drop hint actually moves.

React commits / render time for 10 repetitions in the real app (profiling
build, 2 split panes, 300 hosts), main -> this change:
  window focus            42 / 17.1 ms -> 2 / 0.4 ms
  press/release Cmd       50 / 41.9 ms -> 22 / 6.6 ms
  click focused pane      42 / 69.6 ms -> 3 / 0.4 ms
  quick switcher typing   41 / 61.3 ms -> 16 / 34.8 ms

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 00:22:10 -08:00

145 lines
5.3 KiB
TypeScript

/**
* TextEditorTabView — thin wrapper that binds an editorTab entry to TextEditorPane.
*
* Each tab has its own instance (keyed by tabId), so Monaco is never torn down
* on tab-switch — we just toggle CSS visibility via the `isVisible` prop.
*/
import type * as Monaco from 'monaco-editor';
import React, { useCallback, useMemo } from 'react';
import { useI18n } from '../../application/i18n/I18nProvider';
import { saveEditorTab } from '../../application/state/editorTabSave';
import { editorTabStore, useEditorTab, type EditorTabId } from '../../application/state/editorTabStore';
import { useIsEditorTabActive } from '../../application/state/activeTabStore';
import { useTerminalHostTreeLayoutWidth } from '../../application/state/terminalHostTreeStore';
import type { HotkeyScheme, KeyBinding } from '../../domain/models';
import type { Host } from '../../types';
import { toast } from '../ui/toast';
import { TextEditorPane } from './TextEditorPane';
export interface TextEditorTabViewProps {
tabId: EditorTabId;
hotkeyScheme: HotkeyScheme;
keyBindings: KeyBinding[];
/** Host lookup for building the `host:remotePath` subtitle next to the filename. */
hostById: Map<string, Host>;
/** Routed into Monaco's Cmd/Ctrl+W command so closing the editor tab works
* even when focus is inside the editor (Monaco otherwise swallows the event). */
onRequestClose: (tabId: EditorTabId) => void;
onPopOut?: (tabId: EditorTabId) => void;
}
export function getTextEditorTabShellStyle(isVisible: boolean, hostTreeLayoutWidth: number): React.CSSProperties {
return {
...(isVisible ? null : { pointerEvents: 'none', visibility: 'hidden' }),
zIndex: 20,
left: hostTreeLayoutWidth,
};
}
const TextEditorTabViewImpl: React.FC<TextEditorTabViewProps> = ({
tabId,
hotkeyScheme,
keyBindings,
hostById,
onRequestClose,
onPopOut,
}) => {
const { t } = useI18n();
const tab = useEditorTab(tabId);
// Self-subscribe visibility so switching tabs only re-renders this editor
// instance, not AppView/App.
const isVisible = useIsEditorTabActive(tabId);
const hostTreeLayoutWidth = useTerminalHostTreeLayoutWidth();
const handleContentChange = useCallback(
(content: string, viewState: Monaco.editor.ICodeEditorViewState | null) => {
editorTabStore.updateContent(tabId, content, viewState);
},
[tabId],
);
const handleLanguageChange = useCallback(
(lang: string) => {
editorTabStore.setLanguage(tabId, lang);
},
[tabId],
);
const handlePopOut = useMemo(
() => (onPopOut ? () => onPopOut(tabId) : undefined),
[onPopOut, tabId],
);
const handleToggleWordWrap = useCallback(() => {
const current = editorTabStore.getTab(tabId);
if (!current) return;
editorTabStore.setWordWrap(tabId, !current.wordWrap);
}, [tabId]);
const handleSave = useCallback(async () => {
const ok = await saveEditorTab(tabId);
if (ok) {
toast.success(t('sftp.editor.saved'), 'SFTP');
} else {
const msg = editorTabStore.getTab(tabId)?.saveError ?? t('sftp.editor.saveFailed');
toast.error(msg, 'SFTP');
}
}, [tabId, t]);
const handleRequestClose = useCallback(() => {
onRequestClose(tabId);
}, [onRequestClose, tabId]);
// Tab has been closed — render nothing (parent should remove this instance,
// but guard here in case of a transient render before unmount).
if (!tab) return null;
const isDirty = tab.content !== tab.baselineContent;
// Subtitle shown next to the filename in the Pane header, e.g.
// "Rainyun-114.66.26.174:/root/hello-server.go". Falls back to hostId when
// we don't have a Host record (session may have been removed).
const host = hostById.get(tab.hostId);
const hostLabel = host?.label ?? tab.hostId;
const subtitle = `${hostLabel}:${tab.remotePath}`;
return (
// Sibling tab panels (VaultView, SftpView, TerminalLayerMount, LogView)
// all fill their flex-1 parent via `absolute inset-0`. Match that here so
// an inactive editor tab doesn't collapse to zero height in normal flow,
// and an active one fills the viewport instead of stacking beneath others.
// z-index high enough to stay above the terminal workspace while leaving
// room for the shared host sidebar when it is open.
<div
style={getTextEditorTabShellStyle(isVisible, hostTreeLayoutWidth)}
className="absolute top-0 right-0 bottom-0 min-h-0 flex flex-col bg-background"
>
<TextEditorPane
chrome="tab"
fileName={`${tab.fileName}${isDirty ? ' *' : ''}`}
subtitle={subtitle}
onRequestClose={handleRequestClose}
content={tab.content}
languageId={tab.languageId}
wordWrap={tab.wordWrap}
saving={tab.savingState === 'saving'}
saveError={tab.saveError}
hotkeyScheme={hotkeyScheme}
keyBindings={keyBindings}
onContentChange={handleContentChange}
onLanguageChange={handleLanguageChange}
onToggleWordWrap={handleToggleWordWrap}
onSave={handleSave}
initialViewState={tab.viewState}
onPopOut={handlePopOut}
/>
</div>
);
};
// Memoized: AppView re-renders for unrelated shell state; an editor tab only
// needs to render when its own props or subscribed tab state change.
export const TextEditorTabView = React.memo(TextEditorTabViewImpl);
export default TextEditorTabView;