feat: added terminal tabs and resilient session storage (#265)
- Add per-directory tabbed terminal UI with separate buffers - Persist and restore active tab per directory across sessions - Fallback to in-memory storage when sessionStorage is unavailable
This commit is contained in:
committed by
GitHub
parent
0981194eed
commit
3e145bdbd6
@@ -1,5 +1,5 @@
|
|||||||
import React from 'react';
|
import React from 'react';
|
||||||
import { RiAlertLine, RiArrowDownLine, RiArrowGoBackLine, RiArrowLeftLine, RiArrowRightLine, RiArrowUpLine, RiCheckboxCircleLine, RiCircleLine, RiCloseLine, RiCommandLine, RiDeleteBinLine, RiRestartLine } from '@remixicon/react';
|
import { RiAddLine, RiAlertLine, RiArrowDownLine, RiArrowGoBackLine, RiArrowLeftLine, RiArrowRightLine, RiArrowUpLine, RiCheckboxCircleLine, RiCircleLine, RiCloseLine, RiCommandLine, RiDeleteBinLine, RiRestartLine } from '@remixicon/react';
|
||||||
|
|
||||||
import { useSessionStore } from '@/stores/useSessionStore';
|
import { useSessionStore } from '@/stores/useSessionStore';
|
||||||
import { useDirectoryStore } from '@/stores/useDirectoryStore';
|
import { useDirectoryStore } from '@/stores/useDirectoryStore';
|
||||||
@@ -17,6 +17,7 @@ import { useUIStore } from '@/stores/useUIStore';
|
|||||||
import { Button } from '@/components/ui/button';
|
import { Button } from '@/components/ui/button';
|
||||||
import { useDeviceInfo } from '@/lib/device';
|
import { useDeviceInfo } from '@/lib/device';
|
||||||
import { useRuntimeAPIs } from '@/hooks/useRuntimeAPIs';
|
import { useRuntimeAPIs } from '@/hooks/useRuntimeAPIs';
|
||||||
|
import { isDesktopRuntime, isWebRuntime } from '@/lib/desktop';
|
||||||
|
|
||||||
const TERMINAL_FONT_SIZE = 13;
|
const TERMINAL_FONT_SIZE = 13;
|
||||||
|
|
||||||
@@ -79,6 +80,7 @@ export const TerminalView: React.FC = () => {
|
|||||||
const { currentTheme } = useThemeSystem();
|
const { currentTheme } = useThemeSystem();
|
||||||
const { monoFont } = useFontPreferences();
|
const { monoFont } = useFontPreferences();
|
||||||
const { isMobile, hasTouchInput } = useDeviceInfo();
|
const { isMobile, hasTouchInput } = useDeviceInfo();
|
||||||
|
const enableTabs = !isMobile && (isWebRuntime() || isDesktopRuntime());
|
||||||
const showTerminalQuickKeysOnDesktop = useUIStore((state) => state.showTerminalQuickKeysOnDesktop);
|
const showTerminalQuickKeysOnDesktop = useUIStore((state) => state.showTerminalQuickKeysOnDesktop);
|
||||||
const showQuickKeys = isMobile || showTerminalQuickKeysOnDesktop;
|
const showQuickKeys = isMobile || showTerminalQuickKeysOnDesktop;
|
||||||
|
|
||||||
@@ -100,22 +102,42 @@ export const TerminalView: React.FC = () => {
|
|||||||
|
|
||||||
const terminalStore = useTerminalStore();
|
const terminalStore = useTerminalStore();
|
||||||
const terminalSessions = terminalStore.sessions;
|
const terminalSessions = terminalStore.sessions;
|
||||||
const setTerminalSession = terminalStore.setTerminalSession;
|
const terminalHydrated = terminalStore.hasHydrated;
|
||||||
|
const ensureDirectory = terminalStore.ensureDirectory;
|
||||||
|
const createTab = terminalStore.createTab;
|
||||||
|
const setActiveTab = terminalStore.setActiveTab;
|
||||||
|
const closeTab = terminalStore.closeTab;
|
||||||
|
const setTabSessionId = terminalStore.setTabSessionId;
|
||||||
const setConnecting = terminalStore.setConnecting;
|
const setConnecting = terminalStore.setConnecting;
|
||||||
const appendToBuffer = terminalStore.appendToBuffer;
|
const appendToBuffer = terminalStore.appendToBuffer;
|
||||||
const clearTerminalSession = terminalStore.clearTerminalSession;
|
|
||||||
const removeTerminalSession = terminalStore.removeTerminalSession;
|
|
||||||
const clearBuffer = terminalStore.clearBuffer;
|
const clearBuffer = terminalStore.clearBuffer;
|
||||||
|
|
||||||
const terminalState = React.useMemo(() => {
|
const directoryTerminalState = React.useMemo(() => {
|
||||||
if (!effectiveDirectory) return undefined;
|
if (!effectiveDirectory) return undefined;
|
||||||
return terminalSessions.get(effectiveDirectory);
|
return terminalSessions.get(effectiveDirectory);
|
||||||
}, [terminalSessions, effectiveDirectory]);
|
}, [terminalSessions, effectiveDirectory]);
|
||||||
const terminalSessionRef = terminalState?.terminalSessionId ?? null;
|
|
||||||
const bufferChunks = terminalState?.bufferChunks ?? [];
|
const activeTabId = React.useMemo(() => {
|
||||||
const bufferLength = terminalState?.bufferLength ?? 0;
|
if (!directoryTerminalState) return null;
|
||||||
const isConnecting = terminalState?.isConnecting ?? false;
|
if (enableTabs) {
|
||||||
const terminalSessionId = terminalSessionRef;
|
return directoryTerminalState.activeTabId ?? directoryTerminalState.tabs[0]?.id ?? null;
|
||||||
|
}
|
||||||
|
return directoryTerminalState.tabs[0]?.id ?? null;
|
||||||
|
}, [directoryTerminalState, enableTabs]);
|
||||||
|
|
||||||
|
const activeTab = React.useMemo(() => {
|
||||||
|
if (!directoryTerminalState) return undefined;
|
||||||
|
if (!activeTabId) return directoryTerminalState.tabs[0];
|
||||||
|
return (
|
||||||
|
directoryTerminalState.tabs.find((tab) => tab.id === activeTabId) ??
|
||||||
|
directoryTerminalState.tabs[0]
|
||||||
|
);
|
||||||
|
}, [directoryTerminalState, activeTabId]);
|
||||||
|
|
||||||
|
const terminalSessionId = activeTab?.terminalSessionId ?? null;
|
||||||
|
const bufferChunks = activeTab?.bufferChunks ?? [];
|
||||||
|
const bufferLength = activeTab?.bufferLength ?? 0;
|
||||||
|
const isConnecting = activeTab?.isConnecting ?? false;
|
||||||
|
|
||||||
const [connectionError, setConnectionError] = React.useState<string | null>(null);
|
const [connectionError, setConnectionError] = React.useState<string | null>(null);
|
||||||
const [isFatalError, setIsFatalError] = React.useState(false);
|
const [isFatalError, setIsFatalError] = React.useState(false);
|
||||||
@@ -124,9 +146,35 @@ export const TerminalView: React.FC = () => {
|
|||||||
|
|
||||||
const streamCleanupRef = React.useRef<(() => void) | null>(null);
|
const streamCleanupRef = React.useRef<(() => void) | null>(null);
|
||||||
const activeTerminalIdRef = React.useRef<string | null>(null);
|
const activeTerminalIdRef = React.useRef<string | null>(null);
|
||||||
|
const activeTabIdRef = React.useRef<string | null>(activeTabId);
|
||||||
const terminalIdRef = React.useRef<string | null>(terminalSessionId);
|
const terminalIdRef = React.useRef<string | null>(terminalSessionId);
|
||||||
const directoryRef = React.useRef<string | null>(effectiveDirectory);
|
const directoryRef = React.useRef<string | null>(effectiveDirectory);
|
||||||
const terminalControllerRef = React.useRef<TerminalController | null>(null);
|
const terminalControllerRef = React.useRef<TerminalController | null>(null);
|
||||||
|
const lastViewportSizeRef = React.useRef<{ cols: number; rows: number } | null>(null);
|
||||||
|
const nudgeOnConnectTerminalIdRef = React.useRef<string | null>(null);
|
||||||
|
const rehydratedTerminalIdsRef = React.useRef<Set<string>>(new Set());
|
||||||
|
const rehydratedSnapshotTakenRef = React.useRef(false);
|
||||||
|
|
||||||
|
React.useEffect(() => {
|
||||||
|
if (!terminalHydrated) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (rehydratedSnapshotTakenRef.current) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
rehydratedSnapshotTakenRef.current = true;
|
||||||
|
|
||||||
|
const ids = new Set<string>();
|
||||||
|
for (const [, dirState] of useTerminalStore.getState().sessions.entries()) {
|
||||||
|
for (const tab of dirState.tabs) {
|
||||||
|
if (tab.terminalSessionId) {
|
||||||
|
ids.add(tab.terminalSessionId);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
rehydratedTerminalIdsRef.current = ids;
|
||||||
|
}, [terminalHydrated]);
|
||||||
|
|
||||||
const activeMainTab = useUIStore((state) => state.activeMainTab);
|
const activeMainTab = useUIStore((state) => state.activeMainTab);
|
||||||
const isTerminalActive = activeMainTab === 'terminal';
|
const isTerminalActive = activeMainTab === 'terminal';
|
||||||
@@ -135,6 +183,10 @@ export const TerminalView: React.FC = () => {
|
|||||||
terminalIdRef.current = terminalSessionId;
|
terminalIdRef.current = terminalSessionId;
|
||||||
}, [terminalSessionId]);
|
}, [terminalSessionId]);
|
||||||
|
|
||||||
|
React.useEffect(() => {
|
||||||
|
activeTabIdRef.current = activeTabId;
|
||||||
|
}, [activeTabId]);
|
||||||
|
|
||||||
React.useEffect(() => {
|
React.useEffect(() => {
|
||||||
directoryRef.current = effectiveDirectory;
|
directoryRef.current = effectiveDirectory;
|
||||||
}, [effectiveDirectory]);
|
}, [effectiveDirectory]);
|
||||||
@@ -166,19 +218,23 @@ export const TerminalView: React.FC = () => {
|
|||||||
);
|
);
|
||||||
|
|
||||||
const startStream = React.useCallback(
|
const startStream = React.useCallback(
|
||||||
(terminalId: string) => {
|
(directory: string, tabId: string, terminalId: string) => {
|
||||||
if (activeTerminalIdRef.current === terminalId) {
|
if (activeTerminalIdRef.current === terminalId) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
disconnectStream();
|
disconnectStream();
|
||||||
|
|
||||||
|
// Mark active before connect so early events aren't dropped.
|
||||||
|
activeTerminalIdRef.current = terminalId;
|
||||||
|
|
||||||
const subscription = terminal.connect(
|
const subscription = terminal.connect(
|
||||||
terminalId,
|
terminalId,
|
||||||
{
|
{
|
||||||
onEvent: (event: TerminalStreamEvent) => {
|
onEvent: (event: TerminalStreamEvent) => {
|
||||||
const directory = directoryRef.current;
|
if (activeTerminalIdRef.current !== terminalId) {
|
||||||
if (!directory) return;
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
switch (event.type) {
|
switch (event.type) {
|
||||||
case 'connected': {
|
case 'connected': {
|
||||||
@@ -187,10 +243,19 @@ export const TerminalView: React.FC = () => {
|
|||||||
`[Terminal] connected runtime=${event.runtime ?? 'unknown'} pty=${event.ptyBackend ?? 'unknown'}`
|
`[Terminal] connected runtime=${event.runtime ?? 'unknown'} pty=${event.ptyBackend ?? 'unknown'}`
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
setConnecting(directory, false);
|
setConnecting(directory, tabId, false);
|
||||||
setConnectionError(null);
|
setConnectionError(null);
|
||||||
setIsFatalError(false);
|
setIsFatalError(false);
|
||||||
terminalControllerRef.current?.focus();
|
terminalControllerRef.current?.focus();
|
||||||
|
|
||||||
|
// After a reload, buffer is empty and a reused PTY can look "stuck"
|
||||||
|
// until the first output arrives. Nudge with a newline once.
|
||||||
|
if (nudgeOnConnectTerminalIdRef.current === terminalId) {
|
||||||
|
nudgeOnConnectTerminalIdRef.current = null;
|
||||||
|
void terminal.sendInput(terminalId, '\r').catch(() => {
|
||||||
|
// ignore
|
||||||
|
});
|
||||||
|
}
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
case 'reconnecting': {
|
case 'reconnecting': {
|
||||||
@@ -202,7 +267,7 @@ export const TerminalView: React.FC = () => {
|
|||||||
}
|
}
|
||||||
case 'data': {
|
case 'data': {
|
||||||
if (event.data) {
|
if (event.data) {
|
||||||
appendToBuffer(directory, event.data);
|
appendToBuffer(directory, tabId, event.data);
|
||||||
}
|
}
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
@@ -212,12 +277,13 @@ export const TerminalView: React.FC = () => {
|
|||||||
const signal = typeof event.signal === 'number' ? event.signal : null;
|
const signal = typeof event.signal === 'number' ? event.signal : null;
|
||||||
appendToBuffer(
|
appendToBuffer(
|
||||||
directory,
|
directory,
|
||||||
|
tabId,
|
||||||
`\r\n[Process exited${
|
`\r\n[Process exited${
|
||||||
exitCode !== null ? ` with code ${exitCode}` : ''
|
exitCode !== null ? ` with code ${exitCode}` : ''
|
||||||
}${signal !== null ? ` (signal ${signal})` : ''}]\r\n`
|
}${signal !== null ? ` (signal ${signal})` : ''}]\r\n`
|
||||||
);
|
);
|
||||||
clearTerminalSession(directory);
|
setTabSessionId(directory, tabId, null);
|
||||||
setConnecting(directory, false);
|
setConnecting(directory, tabId, false);
|
||||||
setConnectionError('Terminal session ended');
|
setConnectionError('Terminal session ended');
|
||||||
setIsFatalError(false);
|
setIsFatalError(false);
|
||||||
disconnectStream();
|
disconnectStream();
|
||||||
@@ -226,8 +292,9 @@ export const TerminalView: React.FC = () => {
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
onError: (error, fatal) => {
|
onError: (error, fatal) => {
|
||||||
const directory = directoryRef.current;
|
if (activeTerminalIdRef.current !== terminalId) {
|
||||||
if (!directory) return;
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
const errorMsg = fatal
|
const errorMsg = fatal
|
||||||
? `Connection failed: ${error.message}`
|
? `Connection failed: ${error.message}`
|
||||||
@@ -237,9 +304,9 @@ export const TerminalView: React.FC = () => {
|
|||||||
setIsFatalError(!!fatal);
|
setIsFatalError(!!fatal);
|
||||||
|
|
||||||
if (fatal) {
|
if (fatal) {
|
||||||
setConnecting(directory, false);
|
setConnecting(directory, tabId, false);
|
||||||
|
setTabSessionId(directory, tabId, null);
|
||||||
disconnectStream();
|
disconnectStream();
|
||||||
removeTerminalSession(directory);
|
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
@@ -250,14 +317,17 @@ export const TerminalView: React.FC = () => {
|
|||||||
subscription.close();
|
subscription.close();
|
||||||
activeTerminalIdRef.current = null;
|
activeTerminalIdRef.current = null;
|
||||||
};
|
};
|
||||||
activeTerminalIdRef.current = terminalId;
|
|
||||||
},
|
},
|
||||||
[appendToBuffer, clearTerminalSession, disconnectStream, removeTerminalSession, setConnecting, terminal, setConnectionError]
|
[appendToBuffer, disconnectStream, setConnecting, setTabSessionId, terminal]
|
||||||
);
|
);
|
||||||
|
|
||||||
React.useEffect(() => {
|
React.useEffect(() => {
|
||||||
let cancelled = false;
|
let cancelled = false;
|
||||||
|
|
||||||
|
if (!terminalHydrated) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
if (!effectiveDirectory) {
|
if (!effectiveDirectory) {
|
||||||
setConnectionError(
|
setConnectionError(
|
||||||
hasActiveContext
|
hasActiveContext
|
||||||
@@ -271,25 +341,55 @@ export const TerminalView: React.FC = () => {
|
|||||||
const ensureSession = async () => {
|
const ensureSession = async () => {
|
||||||
const directory = effectiveDirectory;
|
const directory = effectiveDirectory;
|
||||||
if (!directoryRef.current || directoryRef.current !== directory) return;
|
if (!directoryRef.current || directoryRef.current !== directory) return;
|
||||||
const currentState = useTerminalStore.getState().getTerminalSession(directory);
|
|
||||||
|
|
||||||
let terminalId = currentState?.terminalSessionId ?? null;
|
ensureDirectory(directory);
|
||||||
|
|
||||||
|
const state = useTerminalStore.getState().getDirectoryState(directory);
|
||||||
|
if (!state || state.tabs.length === 0) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const tabId = enableTabs
|
||||||
|
? (state.activeTabId ?? state.tabs[0]?.id ?? null)
|
||||||
|
: (state.tabs[0]?.id ?? null);
|
||||||
|
if (!tabId) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const tab = state.tabs.find((t) => t.id === tabId) ?? state.tabs[0];
|
||||||
|
let terminalId = tab?.terminalSessionId ?? null;
|
||||||
|
|
||||||
|
const shouldNudgeExisting =
|
||||||
|
Boolean(terminalId) &&
|
||||||
|
rehydratedTerminalIdsRef.current.has(terminalId as string) &&
|
||||||
|
(tab?.bufferLength ?? 0) === 0 &&
|
||||||
|
(tab?.bufferChunks?.length ?? 0) === 0;
|
||||||
|
|
||||||
if (!terminalId) {
|
if (!terminalId) {
|
||||||
setConnectionError(null);
|
setConnectionError(null);
|
||||||
setIsFatalError(false);
|
setIsFatalError(false);
|
||||||
setConnecting(directory, true);
|
setConnecting(directory, tabId, true);
|
||||||
try {
|
try {
|
||||||
|
const size = lastViewportSizeRef.current;
|
||||||
const session = await terminal.createSession({
|
const session = await terminal.createSession({
|
||||||
cwd: directory,
|
cwd: directory,
|
||||||
|
cols: size?.cols,
|
||||||
|
rows: size?.rows,
|
||||||
});
|
});
|
||||||
if (cancelled) {
|
|
||||||
|
const stillActive =
|
||||||
|
!cancelled &&
|
||||||
|
directoryRef.current === directory &&
|
||||||
|
activeTabIdRef.current === tabId;
|
||||||
|
|
||||||
|
if (!stillActive) {
|
||||||
try {
|
try {
|
||||||
await terminal.close(session.sessionId);
|
await terminal.close(session.sessionId);
|
||||||
} catch { /* ignored */ }
|
} catch { /* ignored */ }
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
setTerminalSession(directory, session);
|
|
||||||
|
setTabSessionId(directory, tabId, session.sessionId);
|
||||||
terminalId = session.sessionId;
|
terminalId = session.sessionId;
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
if (!cancelled) {
|
if (!cancelled) {
|
||||||
@@ -299,7 +399,7 @@ export const TerminalView: React.FC = () => {
|
|||||||
: 'Failed to start terminal session'
|
: 'Failed to start terminal session'
|
||||||
);
|
);
|
||||||
setIsFatalError(true);
|
setIsFatalError(true);
|
||||||
setConnecting(directory, false);
|
setConnecting(directory, tabId, false);
|
||||||
}
|
}
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -308,7 +408,12 @@ export const TerminalView: React.FC = () => {
|
|||||||
if (!terminalId || cancelled) return;
|
if (!terminalId || cancelled) return;
|
||||||
|
|
||||||
terminalIdRef.current = terminalId;
|
terminalIdRef.current = terminalId;
|
||||||
startStream(terminalId);
|
|
||||||
|
if (shouldNudgeExisting) {
|
||||||
|
nudgeOnConnectTerminalIdRef.current = terminalId;
|
||||||
|
rehydratedTerminalIdsRef.current.delete(terminalId);
|
||||||
|
}
|
||||||
|
startStream(directory, tabId, terminalId);
|
||||||
};
|
};
|
||||||
|
|
||||||
void ensureSession();
|
void ensureSession();
|
||||||
@@ -322,9 +427,12 @@ export const TerminalView: React.FC = () => {
|
|||||||
hasActiveContext,
|
hasActiveContext,
|
||||||
effectiveDirectory,
|
effectiveDirectory,
|
||||||
terminalSessionId,
|
terminalSessionId,
|
||||||
removeTerminalSession,
|
activeTabId,
|
||||||
|
enableTabs,
|
||||||
|
terminalHydrated,
|
||||||
|
ensureDirectory,
|
||||||
setConnecting,
|
setConnecting,
|
||||||
setTerminalSession,
|
setTabSessionId,
|
||||||
startStream,
|
startStream,
|
||||||
disconnectStream,
|
disconnectStream,
|
||||||
terminal,
|
terminal,
|
||||||
@@ -334,82 +442,37 @@ export const TerminalView: React.FC = () => {
|
|||||||
if (!effectiveDirectory) return;
|
if (!effectiveDirectory) return;
|
||||||
if (isRestarting) return;
|
if (isRestarting) return;
|
||||||
|
|
||||||
|
const state = useTerminalStore.getState().getDirectoryState(effectiveDirectory);
|
||||||
|
const tabId = isMobile
|
||||||
|
? (state?.tabs[0]?.id ?? null)
|
||||||
|
: (activeTabId ?? state?.activeTabId ?? state?.tabs[0]?.id ?? null);
|
||||||
|
if (!tabId) return;
|
||||||
|
|
||||||
setIsRestarting(true);
|
setIsRestarting(true);
|
||||||
setConnectionError(null);
|
setConnectionError(null);
|
||||||
setIsFatalError(false);
|
setIsFatalError(false);
|
||||||
|
|
||||||
disconnectStream();
|
disconnectStream();
|
||||||
|
|
||||||
const currentTerminalId = terminalIdRef.current;
|
|
||||||
|
|
||||||
try {
|
try {
|
||||||
if (terminal.restartSession && currentTerminalId) {
|
await closeTab(effectiveDirectory, tabId);
|
||||||
const newSession = await terminal.restartSession(currentTerminalId, {
|
|
||||||
cwd: effectiveDirectory,
|
|
||||||
});
|
|
||||||
setTerminalSession(effectiveDirectory, newSession);
|
|
||||||
terminalIdRef.current = newSession.sessionId;
|
|
||||||
startStream(newSession.sessionId);
|
|
||||||
} else {
|
|
||||||
if (currentTerminalId) {
|
|
||||||
try {
|
|
||||||
await terminal.close(currentTerminalId);
|
|
||||||
} catch { /* ignored */ }
|
|
||||||
}
|
|
||||||
removeTerminalSession(effectiveDirectory);
|
|
||||||
}
|
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
setConnectionError(
|
setConnectionError(error instanceof Error ? error.message : 'Failed to restart terminal');
|
||||||
error instanceof Error ? error.message : 'Failed to restart terminal'
|
|
||||||
);
|
|
||||||
setIsFatalError(true);
|
setIsFatalError(true);
|
||||||
} finally {
|
} finally {
|
||||||
setIsRestarting(false);
|
setIsRestarting(false);
|
||||||
}
|
}
|
||||||
}, [effectiveDirectory, isRestarting, disconnectStream, terminal, setTerminalSession, startStream, removeTerminalSession]);
|
}, [activeTabId, closeTab, disconnectStream, effectiveDirectory, isMobile, isRestarting]);
|
||||||
|
|
||||||
const handleHardRestart = React.useCallback(async () => {
|
const handleHardRestart = React.useCallback(async () => {
|
||||||
if (!effectiveDirectory) return;
|
// Keep semantics: “close tab -> new clean tab”.
|
||||||
if (isRestarting) return;
|
await handleRestart();
|
||||||
|
}, [handleRestart]);
|
||||||
setIsRestarting(true);
|
|
||||||
setConnectionError(null);
|
|
||||||
setIsFatalError(false);
|
|
||||||
disconnectStream();
|
|
||||||
|
|
||||||
try {
|
|
||||||
if (terminal.forceKill) {
|
|
||||||
await terminal.forceKill({ cwd: effectiveDirectory });
|
|
||||||
}
|
|
||||||
} catch { /* ignored */ }
|
|
||||||
|
|
||||||
removeTerminalSession(effectiveDirectory);
|
|
||||||
clearBuffer(effectiveDirectory);
|
|
||||||
terminalControllerRef.current?.clear();
|
|
||||||
|
|
||||||
await new Promise(r => setTimeout(r, 100));
|
|
||||||
|
|
||||||
try {
|
|
||||||
setConnecting(effectiveDirectory, true);
|
|
||||||
const session = await terminal.createSession({
|
|
||||||
cwd: effectiveDirectory,
|
|
||||||
});
|
|
||||||
setTerminalSession(effectiveDirectory, session);
|
|
||||||
terminalIdRef.current = session.sessionId;
|
|
||||||
startStream(session.sessionId);
|
|
||||||
} catch (error) {
|
|
||||||
setConnectionError(
|
|
||||||
error instanceof Error ? error.message : 'Failed to create terminal'
|
|
||||||
);
|
|
||||||
setIsFatalError(true);
|
|
||||||
setConnecting(effectiveDirectory, false);
|
|
||||||
} finally {
|
|
||||||
setIsRestarting(false);
|
|
||||||
}
|
|
||||||
}, [effectiveDirectory, isRestarting, disconnectStream, terminal, removeTerminalSession, clearBuffer, setConnecting, setTerminalSession, startStream]);
|
|
||||||
|
|
||||||
const handleClear = React.useCallback(() => {
|
const handleClear = React.useCallback(() => {
|
||||||
if (!effectiveDirectory) return;
|
if (!effectiveDirectory) return;
|
||||||
clearBuffer(effectiveDirectory);
|
if (!activeTabId) return;
|
||||||
|
clearBuffer(effectiveDirectory, activeTabId);
|
||||||
terminalControllerRef.current?.clear();
|
terminalControllerRef.current?.clear();
|
||||||
terminalControllerRef.current?.focus();
|
terminalControllerRef.current?.focus();
|
||||||
|
|
||||||
@@ -419,7 +482,42 @@ export const TerminalView: React.FC = () => {
|
|||||||
setConnectionError(error instanceof Error ? error.message : 'Failed to refresh prompt');
|
setConnectionError(error instanceof Error ? error.message : 'Failed to refresh prompt');
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
}, [clearBuffer, effectiveDirectory, setConnectionError, terminal]);
|
}, [activeTabId, clearBuffer, effectiveDirectory, setConnectionError, terminal]);
|
||||||
|
|
||||||
|
const handleCreateTab = React.useCallback(() => {
|
||||||
|
if (!effectiveDirectory) return;
|
||||||
|
const tabId = createTab(effectiveDirectory);
|
||||||
|
setActiveTab(effectiveDirectory, tabId);
|
||||||
|
setConnectionError(null);
|
||||||
|
setIsFatalError(false);
|
||||||
|
disconnectStream();
|
||||||
|
}, [createTab, disconnectStream, effectiveDirectory, setActiveTab]);
|
||||||
|
|
||||||
|
const handleSelectTab = React.useCallback(
|
||||||
|
(tabId: string) => {
|
||||||
|
if (!effectiveDirectory) return;
|
||||||
|
setActiveTab(effectiveDirectory, tabId);
|
||||||
|
setConnectionError(null);
|
||||||
|
setIsFatalError(false);
|
||||||
|
disconnectStream();
|
||||||
|
},
|
||||||
|
[disconnectStream, effectiveDirectory, setActiveTab]
|
||||||
|
);
|
||||||
|
|
||||||
|
const handleCloseTab = React.useCallback(
|
||||||
|
(tabId: string) => {
|
||||||
|
if (!effectiveDirectory) return;
|
||||||
|
|
||||||
|
if (tabId === activeTabId) {
|
||||||
|
disconnectStream();
|
||||||
|
}
|
||||||
|
|
||||||
|
setConnectionError(null);
|
||||||
|
setIsFatalError(false);
|
||||||
|
void closeTab(effectiveDirectory, tabId);
|
||||||
|
},
|
||||||
|
[activeTabId, closeTab, disconnectStream, effectiveDirectory]
|
||||||
|
);
|
||||||
|
|
||||||
|
|
||||||
const handleViewportInput = React.useCallback(
|
const handleViewportInput = React.useCallback(
|
||||||
@@ -463,6 +561,7 @@ export const TerminalView: React.FC = () => {
|
|||||||
|
|
||||||
const handleViewportResize = React.useCallback(
|
const handleViewportResize = React.useCallback(
|
||||||
(cols: number, rows: number) => {
|
(cols: number, rows: number) => {
|
||||||
|
lastViewportSizeRef.current = { cols, rows };
|
||||||
const terminalId = terminalIdRef.current;
|
const terminalId = terminalIdRef.current;
|
||||||
if (!terminalId) return;
|
if (!terminalId) return;
|
||||||
void terminal.resize({ sessionId: terminalId, cols, rows }).catch(() => {
|
void terminal.resize({ sessionId: terminalId, cols, rows }).catch(() => {
|
||||||
@@ -595,9 +694,12 @@ export const TerminalView: React.FC = () => {
|
|||||||
|
|
||||||
const terminalSessionKey = React.useMemo(() => {
|
const terminalSessionKey = React.useMemo(() => {
|
||||||
const directoryPart = effectiveDirectory ?? 'no-dir';
|
const directoryPart = effectiveDirectory ?? 'no-dir';
|
||||||
const terminalPart = terminalSessionId ?? 'pending';
|
const tabPart = activeTabId ?? 'no-tab';
|
||||||
return `${directoryPart}::${terminalPart}`;
|
const terminalPart = terminalSessionId ?? `pending-${tabPart}`;
|
||||||
}, [effectiveDirectory, terminalSessionId]);
|
return `${directoryPart}::${tabPart}::${terminalPart}`;
|
||||||
|
}, [effectiveDirectory, activeTabId, terminalSessionId]);
|
||||||
|
|
||||||
|
const viewportSessionKey = terminalSessionId ?? terminalSessionKey;
|
||||||
|
|
||||||
React.useEffect(() => {
|
React.useEffect(() => {
|
||||||
if (!isTerminalActive) {
|
if (!isTerminalActive) {
|
||||||
@@ -628,13 +730,13 @@ export const TerminalView: React.FC = () => {
|
|||||||
|
|
||||||
const statusIcon = connectionError
|
const statusIcon = connectionError
|
||||||
? isReconnecting
|
? isReconnecting
|
||||||
? <RiAlertLine size={20} className="text-amber-400" />
|
? <RiAlertLine size={20} className="text-[color:var(--status-warning)]" />
|
||||||
: <RiCloseLine size={20} className="text-destructive" />
|
: <RiCloseLine size={20} className="text-[color:var(--status-error)]" />
|
||||||
: terminalSessionId && !isConnecting && !isRestarting
|
: terminalSessionId && !isConnecting && !isRestarting
|
||||||
? <RiCheckboxCircleLine size={20} className="text-emerald-400" />
|
? <RiCheckboxCircleLine size={20} className="text-[color:var(--status-success)]" />
|
||||||
: isConnecting || isRestarting
|
: isConnecting || isRestarting
|
||||||
? <RiCircleLine size={20} className="text-amber-400 animate-pulse" />
|
? <RiCircleLine size={20} className="text-[color:var(--status-warning)] animate-pulse" />
|
||||||
: <RiCircleLine size={20} className="text-muted-foreground" />;
|
: <RiCircleLine size={20} className="text-[var(--surface-muted-foreground)]" />;
|
||||||
|
|
||||||
if (!hasActiveContext) {
|
if (!hasActiveContext) {
|
||||||
return (
|
return (
|
||||||
@@ -661,40 +763,93 @@ export const TerminalView: React.FC = () => {
|
|||||||
const quickKeysDisabled = !terminalSessionId || isConnecting || isRestarting;
|
const quickKeysDisabled = !terminalSessionId || isConnecting || isRestarting;
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="flex h-full flex-col overflow-hidden bg-background">
|
<div className="flex h-full flex-col overflow-hidden bg-[var(--surface-background)]">
|
||||||
<div className="px-3 py-2 text-xs bg-background">
|
<div className="px-3 py-2 text-xs bg-[var(--surface-background)]">
|
||||||
<div className="flex items-center justify-between gap-3">
|
<div className="flex items-center justify-between gap-3">
|
||||||
<div className="flex min-w-0 items-center gap-2 text-muted-foreground">
|
<div className="flex min-w-0 items-center gap-2 text-muted-foreground">
|
||||||
<span className="truncate font-mono text-foreground/90">{displayDirectory}</span>
|
<span className="truncate font-mono text-foreground/90">{displayDirectory}</span>
|
||||||
</div>
|
</div>
|
||||||
<div className="flex items-center gap-2">
|
{isMobile ? (
|
||||||
{statusIcon}
|
<div className="flex items-center gap-2">
|
||||||
<Button
|
{statusIcon}
|
||||||
size="sm"
|
<Button
|
||||||
variant="default"
|
size="sm"
|
||||||
className="h-7 px-2 py-0"
|
variant="default"
|
||||||
onClick={handleClear}
|
className="h-7 px-2 py-0"
|
||||||
disabled={!bufferLength}
|
onClick={handleClear}
|
||||||
title="Clear output"
|
disabled={!bufferLength}
|
||||||
type="button"
|
title="Clear output"
|
||||||
>
|
type="button"
|
||||||
<RiDeleteBinLine size={16} />
|
>
|
||||||
Clear
|
<RiDeleteBinLine size={16} />
|
||||||
</Button>
|
Clear
|
||||||
<Button
|
</Button>
|
||||||
size="sm"
|
<Button
|
||||||
variant="default"
|
size="sm"
|
||||||
className="h-7 px-2 py-0"
|
variant="default"
|
||||||
onClick={handleRestart}
|
className="h-7 px-2 py-0"
|
||||||
disabled={isRestarting}
|
onClick={handleRestart}
|
||||||
title="Restart terminal session"
|
disabled={isRestarting}
|
||||||
type="button"
|
title="Restart terminal"
|
||||||
>
|
type="button"
|
||||||
<RiRestartLine size={16} className={cn((isConnecting || isRestarting) && 'animate-spin')} />
|
>
|
||||||
Restart
|
<RiRestartLine size={16} className={cn((isConnecting || isRestarting) && 'animate-spin')} />
|
||||||
</Button>
|
Restart
|
||||||
</div>
|
</Button>
|
||||||
|
</div>
|
||||||
|
) : null}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
{enableTabs && directoryTerminalState ? (
|
||||||
|
<div className="mt-2 flex items-center gap-1 overflow-x-auto pb-1">
|
||||||
|
{directoryTerminalState.tabs.map((tab) => {
|
||||||
|
const isActive = tab.id === activeTabId;
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
key={tab.id}
|
||||||
|
className={cn(
|
||||||
|
'group flex items-center gap-1 rounded-md border px-2 py-1 text-xs whitespace-nowrap',
|
||||||
|
isActive
|
||||||
|
? 'bg-[var(--interactive-selection)] border-[var(--primary-muted)] text-[var(--interactive-selection-foreground)]'
|
||||||
|
: 'bg-transparent border-[var(--interactive-border)] text-[var(--surface-muted-foreground)] hover:bg-[var(--interactive-hover)] hover:text-[var(--surface-foreground)]'
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => handleSelectTab(tab.id)}
|
||||||
|
className="max-w-[10rem] truncate text-left"
|
||||||
|
title={tab.label}
|
||||||
|
>
|
||||||
|
{tab.label}
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className={cn(
|
||||||
|
'rounded-sm p-0.5 text-[var(--surface-muted-foreground)] hover:text-[var(--surface-foreground)]',
|
||||||
|
!isActive && 'opacity-0 group-hover:opacity-100'
|
||||||
|
)}
|
||||||
|
onClick={(e) => {
|
||||||
|
e.stopPropagation();
|
||||||
|
handleCloseTab(tab.id);
|
||||||
|
}}
|
||||||
|
title="Close tab"
|
||||||
|
>
|
||||||
|
<RiCloseLine size={14} />
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={handleCreateTab}
|
||||||
|
className="ml-1 flex h-7 w-7 items-center justify-center rounded-md border border-[var(--interactive-border)] bg-transparent text-[var(--surface-muted-foreground)] hover:bg-[var(--interactive-hover)] hover:text-[var(--surface-foreground)]"
|
||||||
|
title="New tab"
|
||||||
|
>
|
||||||
|
<RiAddLine size={16} />
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
) : null}
|
||||||
{showQuickKeys ? (
|
{showQuickKeys ? (
|
||||||
<div className="mt-2 flex flex-wrap items-center gap-1">
|
<div className="mt-2 flex flex-wrap items-center gap-1">
|
||||||
<Button
|
<Button
|
||||||
@@ -808,11 +963,11 @@ export const TerminalView: React.FC = () => {
|
|||||||
{isTerminalActive ? (
|
{isTerminalActive ? (
|
||||||
isMobile ? (
|
isMobile ? (
|
||||||
<TerminalViewport
|
<TerminalViewport
|
||||||
key={terminalSessionKey}
|
key={viewportSessionKey}
|
||||||
ref={(controller) => {
|
ref={(controller) => {
|
||||||
terminalControllerRef.current = controller;
|
terminalControllerRef.current = controller;
|
||||||
}}
|
}}
|
||||||
sessionKey={terminalSessionKey}
|
sessionKey={viewportSessionKey}
|
||||||
chunks={bufferChunks}
|
chunks={bufferChunks}
|
||||||
onInput={handleViewportInput}
|
onInput={handleViewportInput}
|
||||||
onResize={handleViewportResize}
|
onResize={handleViewportResize}
|
||||||
@@ -824,11 +979,11 @@ export const TerminalView: React.FC = () => {
|
|||||||
) : (
|
) : (
|
||||||
<ScrollableOverlay outerClassName="h-full" className="h-full w-full" disableHorizontal>
|
<ScrollableOverlay outerClassName="h-full" className="h-full w-full" disableHorizontal>
|
||||||
<TerminalViewport
|
<TerminalViewport
|
||||||
key={terminalSessionKey}
|
key={viewportSessionKey}
|
||||||
ref={(controller) => {
|
ref={(controller) => {
|
||||||
terminalControllerRef.current = controller;
|
terminalControllerRef.current = controller;
|
||||||
}}
|
}}
|
||||||
sessionKey={terminalSessionKey}
|
sessionKey={viewportSessionKey}
|
||||||
chunks={bufferChunks}
|
chunks={bufferChunks}
|
||||||
onInput={handleViewportInput}
|
onInput={handleViewportInput}
|
||||||
onResize={handleViewportResize}
|
onResize={handleViewportResize}
|
||||||
@@ -842,9 +997,9 @@ export const TerminalView: React.FC = () => {
|
|||||||
) : null}
|
) : null}
|
||||||
</div>
|
</div>
|
||||||
{connectionError && (
|
{connectionError && (
|
||||||
<div className="absolute inset-x-0 bottom-0 bg-destructive/90 px-3 py-2 text-xs text-destructive-foreground flex items-center justify-between gap-2">
|
<div className="absolute inset-x-0 bottom-0 bg-[var(--status-error-background)] px-3 py-2 text-xs text-[var(--status-error-foreground)] flex items-center justify-between gap-2">
|
||||||
<span>{connectionError}</span>
|
<span>{connectionError}</span>
|
||||||
{isFatalError && (
|
{isFatalError && isMobile && (
|
||||||
<Button
|
<Button
|
||||||
size="sm"
|
size="sm"
|
||||||
variant="secondary"
|
variant="secondary"
|
||||||
|
|||||||
@@ -1,36 +1,77 @@
|
|||||||
import { create } from 'zustand';
|
import { create } from 'zustand';
|
||||||
import type { TerminalSession } from '@/lib/terminalApi';
|
import { devtools, persist, createJSONStorage } from 'zustand/middleware';
|
||||||
|
|
||||||
|
import { closeTerminal } from '@/lib/terminalApi';
|
||||||
|
import { getSafeSessionStorage } from '@/stores/utils/safeStorage';
|
||||||
|
|
||||||
export interface TerminalChunk {
|
export interface TerminalChunk {
|
||||||
id: number;
|
id: number;
|
||||||
data: string;
|
data: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
interface TerminalSessionState {
|
export type TerminalTab = {
|
||||||
directory: string;
|
id: string;
|
||||||
terminalSessionId: string | null;
|
terminalSessionId: string | null;
|
||||||
isConnecting: boolean;
|
label: string;
|
||||||
buffer: string;
|
|
||||||
bufferChunks: TerminalChunk[];
|
bufferChunks: TerminalChunk[];
|
||||||
bufferLength: number;
|
bufferLength: number;
|
||||||
updatedAt: number;
|
isConnecting: boolean;
|
||||||
}
|
createdAt: number;
|
||||||
|
};
|
||||||
|
|
||||||
|
export type DirectoryTerminalState = {
|
||||||
|
tabs: TerminalTab[];
|
||||||
|
activeTabId: string | null;
|
||||||
|
};
|
||||||
|
|
||||||
interface TerminalStore {
|
interface TerminalStore {
|
||||||
sessions: Map<string, TerminalSessionState>;
|
sessions: Map<string, DirectoryTerminalState>;
|
||||||
nextChunkId: number;
|
nextChunkId: number;
|
||||||
|
nextTabId: number;
|
||||||
|
hasHydrated: boolean;
|
||||||
|
|
||||||
getTerminalSession: (directory: string) => TerminalSessionState | undefined;
|
ensureDirectory: (directory: string) => void;
|
||||||
setTerminalSession: (directory: string, terminalSession: TerminalSession) => void;
|
getDirectoryState: (directory: string) => DirectoryTerminalState | undefined;
|
||||||
setConnecting: (directory: string, isConnecting: boolean) => void;
|
getActiveTab: (directory: string) => TerminalTab | undefined;
|
||||||
appendToBuffer: (directory: string, chunk: string) => void;
|
|
||||||
clearTerminalSession: (directory: string) => void;
|
createTab: (directory: string) => string;
|
||||||
clearBuffer: (directory: string) => void;
|
setActiveTab: (directory: string, tabId: string) => void;
|
||||||
removeTerminalSession: (directory: string) => void;
|
closeTab: (directory: string, tabId: string) => Promise<void>;
|
||||||
clearAllTerminalSessions: () => void;
|
|
||||||
|
setTabSessionId: (directory: string, tabId: string, sessionId: string | null) => void;
|
||||||
|
setConnecting: (directory: string, tabId: string, isConnecting: boolean) => void;
|
||||||
|
appendToBuffer: (directory: string, tabId: string, chunk: string) => void;
|
||||||
|
clearBuffer: (directory: string, tabId: string) => void;
|
||||||
|
|
||||||
|
removeDirectory: (directory: string) => void;
|
||||||
|
clearAll: () => void;
|
||||||
}
|
}
|
||||||
|
|
||||||
const TERMINAL_BUFFER_LIMIT = 1_000_000;
|
const TERMINAL_BUFFER_LIMIT = 1_000_000;
|
||||||
|
const TERMINAL_STORE_NAME = 'terminal-store';
|
||||||
|
let hydrationListenerAttached = false;
|
||||||
|
|
||||||
|
type PersistedTerminalTab = Pick<TerminalTab, 'id' | 'label' | 'terminalSessionId' | 'createdAt'>;
|
||||||
|
|
||||||
|
type PersistedDirectoryTerminalState = {
|
||||||
|
tabs: PersistedTerminalTab[];
|
||||||
|
activeTabId: string | null;
|
||||||
|
};
|
||||||
|
|
||||||
|
type PersistedTerminalStoreState = {
|
||||||
|
sessions: Array<[string, PersistedDirectoryTerminalState]>;
|
||||||
|
nextTabId: number;
|
||||||
|
};
|
||||||
|
|
||||||
|
const isRecord = (value: unknown): value is Record<string, unknown> =>
|
||||||
|
typeof value === 'object' && value !== null;
|
||||||
|
|
||||||
|
const tabIdNumber = (tabId: string): number | null => {
|
||||||
|
const match = /^tab-(\d+)$/.exec(tabId);
|
||||||
|
if (!match) return null;
|
||||||
|
const num = Number(match[1]);
|
||||||
|
return Number.isFinite(num) ? num : null;
|
||||||
|
};
|
||||||
|
|
||||||
function normalizeDirectory(dir: string): string {
|
function normalizeDirectory(dir: string): string {
|
||||||
let normalized = dir.trim();
|
let normalized = dir.trim();
|
||||||
@@ -40,148 +81,432 @@ function normalizeDirectory(dir: string): string {
|
|||||||
return normalized;
|
return normalized;
|
||||||
}
|
}
|
||||||
|
|
||||||
const createEmptySessionState = (directory: string): TerminalSessionState => ({
|
const createEmptyTab = (id: string, label: string): TerminalTab => ({
|
||||||
directory,
|
id,
|
||||||
terminalSessionId: null,
|
terminalSessionId: null,
|
||||||
isConnecting: false,
|
label,
|
||||||
buffer: '',
|
|
||||||
bufferChunks: [],
|
bufferChunks: [],
|
||||||
bufferLength: 0,
|
bufferLength: 0,
|
||||||
updatedAt: Date.now(),
|
isConnecting: false,
|
||||||
|
createdAt: Date.now(),
|
||||||
});
|
});
|
||||||
|
|
||||||
export const useTerminalStore = create<TerminalStore>((set, get) => ({
|
const createEmptyDirectoryState = (firstTab: TerminalTab): DirectoryTerminalState => ({
|
||||||
sessions: new Map(),
|
tabs: [firstTab],
|
||||||
nextChunkId: 1,
|
activeTabId: firstTab.id,
|
||||||
|
});
|
||||||
|
|
||||||
getTerminalSession: (directory: string) => {
|
const findTabIndex = (state: DirectoryTerminalState, tabId: string): number =>
|
||||||
const key = normalizeDirectory(directory);
|
state.tabs.findIndex((t) => t.id === tabId);
|
||||||
return get().sessions.get(key);
|
|
||||||
},
|
|
||||||
|
|
||||||
setTerminalSession: (directory: string, terminalSession: TerminalSession) => {
|
export const useTerminalStore = create<TerminalStore>()(
|
||||||
const key = normalizeDirectory(directory);
|
devtools(
|
||||||
set((state) => {
|
persist(
|
||||||
const newSessions = new Map(state.sessions);
|
(set, get) => ({
|
||||||
const existing = newSessions.get(key);
|
sessions: new Map(),
|
||||||
const shouldResetBuffer =
|
nextChunkId: 1,
|
||||||
!existing ||
|
nextTabId: 1,
|
||||||
existing.terminalSessionId !== terminalSession.sessionId;
|
hasHydrated: typeof window === 'undefined',
|
||||||
|
|
||||||
const baseState = shouldResetBuffer
|
ensureDirectory: (directory: string) => {
|
||||||
? createEmptySessionState(key)
|
const key = normalizeDirectory(directory);
|
||||||
: existing ?? createEmptySessionState(key);
|
if (!key) return;
|
||||||
|
|
||||||
newSessions.set(key, {
|
set((state) => {
|
||||||
...baseState,
|
if (state.sessions.has(key)) {
|
||||||
terminalSessionId: terminalSession.sessionId,
|
return state;
|
||||||
directory: key,
|
}
|
||||||
isConnecting: false,
|
|
||||||
updatedAt: Date.now(),
|
|
||||||
});
|
|
||||||
|
|
||||||
return { sessions: newSessions };
|
const newSessions = new Map(state.sessions);
|
||||||
});
|
const tabId = `tab-${state.nextTabId}`;
|
||||||
},
|
const firstTab = createEmptyTab(tabId, 'Terminal');
|
||||||
|
newSessions.set(key, createEmptyDirectoryState(firstTab));
|
||||||
|
|
||||||
setConnecting: (directory: string, isConnecting: boolean) => {
|
return { sessions: newSessions, nextTabId: state.nextTabId + 1 };
|
||||||
const key = normalizeDirectory(directory);
|
});
|
||||||
set((state) => {
|
},
|
||||||
const newSessions = new Map(state.sessions);
|
|
||||||
const existing = newSessions.get(key) ?? createEmptySessionState(key);
|
|
||||||
newSessions.set(key, {
|
|
||||||
...existing,
|
|
||||||
isConnecting,
|
|
||||||
updatedAt: Date.now(),
|
|
||||||
});
|
|
||||||
return { sessions: newSessions };
|
|
||||||
});
|
|
||||||
},
|
|
||||||
|
|
||||||
appendToBuffer: (directory: string, chunk: string) => {
|
getDirectoryState: (directory: string) => {
|
||||||
if (!chunk) {
|
const key = normalizeDirectory(directory);
|
||||||
return;
|
return get().sessions.get(key);
|
||||||
|
},
|
||||||
|
|
||||||
|
getActiveTab: (directory: string) => {
|
||||||
|
const key = normalizeDirectory(directory);
|
||||||
|
const entry = get().sessions.get(key);
|
||||||
|
if (!entry) return undefined;
|
||||||
|
const activeId = entry.activeTabId;
|
||||||
|
if (!activeId) return entry.tabs[0];
|
||||||
|
return entry.tabs.find((t) => t.id === activeId) ?? entry.tabs[0];
|
||||||
|
},
|
||||||
|
|
||||||
|
createTab: (directory: string) => {
|
||||||
|
const key = normalizeDirectory(directory);
|
||||||
|
if (!key) {
|
||||||
|
return 'tab-invalid';
|
||||||
|
}
|
||||||
|
|
||||||
|
const tabId = `tab-${get().nextTabId}`;
|
||||||
|
|
||||||
|
set((state) => {
|
||||||
|
const newSessions = new Map(state.sessions);
|
||||||
|
const existing = newSessions.get(key);
|
||||||
|
|
||||||
|
const nextTabId = state.nextTabId + 1;
|
||||||
|
const labelIndex = (existing?.tabs.length ?? 0) + 1;
|
||||||
|
const label = `Terminal ${labelIndex}`;
|
||||||
|
const tab = createEmptyTab(tabId, label);
|
||||||
|
|
||||||
|
if (!existing) {
|
||||||
|
newSessions.set(key, createEmptyDirectoryState(tab));
|
||||||
|
} else {
|
||||||
|
newSessions.set(key, {
|
||||||
|
...existing,
|
||||||
|
tabs: [...existing.tabs, tab],
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
return { sessions: newSessions, nextTabId };
|
||||||
|
});
|
||||||
|
|
||||||
|
return tabId;
|
||||||
|
},
|
||||||
|
|
||||||
|
setActiveTab: (directory: string, tabId: string) => {
|
||||||
|
const key = normalizeDirectory(directory);
|
||||||
|
set((state) => {
|
||||||
|
const newSessions = new Map(state.sessions);
|
||||||
|
const existing = newSessions.get(key);
|
||||||
|
if (!existing) {
|
||||||
|
return state;
|
||||||
|
}
|
||||||
|
if (existing.activeTabId === tabId) {
|
||||||
|
return state;
|
||||||
|
}
|
||||||
|
if (findTabIndex(existing, tabId) < 0) {
|
||||||
|
return state;
|
||||||
|
}
|
||||||
|
|
||||||
|
newSessions.set(key, { ...existing, activeTabId: tabId });
|
||||||
|
return { sessions: newSessions };
|
||||||
|
});
|
||||||
|
},
|
||||||
|
|
||||||
|
closeTab: async (directory: string, tabId: string) => {
|
||||||
|
const key = normalizeDirectory(directory);
|
||||||
|
const entry = get().sessions.get(key);
|
||||||
|
const tab = entry?.tabs.find((t) => t.id === tabId);
|
||||||
|
const sessionId = tab?.terminalSessionId ?? null;
|
||||||
|
|
||||||
|
if (sessionId) {
|
||||||
|
try {
|
||||||
|
await closeTerminal(sessionId);
|
||||||
|
} catch {
|
||||||
|
// ignore
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
set((state) => {
|
||||||
|
const newSessions = new Map(state.sessions);
|
||||||
|
const existing = newSessions.get(key);
|
||||||
|
if (!existing) {
|
||||||
|
return state;
|
||||||
|
}
|
||||||
|
|
||||||
|
const idx = findTabIndex(existing, tabId);
|
||||||
|
if (idx < 0) {
|
||||||
|
return state;
|
||||||
|
}
|
||||||
|
|
||||||
|
const nextTabs = existing.tabs.filter((t) => t.id !== tabId);
|
||||||
|
|
||||||
|
if (nextTabs.length === 0) {
|
||||||
|
const newTabId = `tab-${state.nextTabId}`;
|
||||||
|
const newTab = createEmptyTab(newTabId, 'Terminal');
|
||||||
|
newSessions.set(key, createEmptyDirectoryState(newTab));
|
||||||
|
return { sessions: newSessions, nextTabId: state.nextTabId + 1 };
|
||||||
|
}
|
||||||
|
|
||||||
|
let nextActive = existing.activeTabId;
|
||||||
|
if (existing.activeTabId === tabId) {
|
||||||
|
const fallback = nextTabs[Math.min(idx, nextTabs.length - 1)];
|
||||||
|
nextActive = fallback?.id ?? nextTabs[0]?.id ?? null;
|
||||||
|
}
|
||||||
|
|
||||||
|
newSessions.set(key, {
|
||||||
|
...existing,
|
||||||
|
tabs: nextTabs,
|
||||||
|
activeTabId: nextActive,
|
||||||
|
});
|
||||||
|
|
||||||
|
return { sessions: newSessions };
|
||||||
|
});
|
||||||
|
},
|
||||||
|
|
||||||
|
setTabSessionId: (directory: string, tabId: string, sessionId: string | null) => {
|
||||||
|
const key = normalizeDirectory(directory);
|
||||||
|
set((state) => {
|
||||||
|
const newSessions = new Map(state.sessions);
|
||||||
|
const existing = newSessions.get(key);
|
||||||
|
if (!existing) {
|
||||||
|
return state;
|
||||||
|
}
|
||||||
|
|
||||||
|
const idx = findTabIndex(existing, tabId);
|
||||||
|
if (idx < 0) {
|
||||||
|
return state;
|
||||||
|
}
|
||||||
|
|
||||||
|
const tab = existing.tabs[idx];
|
||||||
|
const shouldResetBuffer = tab.terminalSessionId !== sessionId;
|
||||||
|
|
||||||
|
const nextTab: TerminalTab = {
|
||||||
|
...tab,
|
||||||
|
terminalSessionId: sessionId,
|
||||||
|
isConnecting: false,
|
||||||
|
...(shouldResetBuffer ? { bufferChunks: [], bufferLength: 0 } : {}),
|
||||||
|
};
|
||||||
|
|
||||||
|
const nextTabs = [...existing.tabs];
|
||||||
|
nextTabs[idx] = nextTab;
|
||||||
|
newSessions.set(key, { ...existing, tabs: nextTabs });
|
||||||
|
return { sessions: newSessions };
|
||||||
|
});
|
||||||
|
},
|
||||||
|
|
||||||
|
setConnecting: (directory: string, tabId: string, isConnecting: boolean) => {
|
||||||
|
const key = normalizeDirectory(directory);
|
||||||
|
set((state) => {
|
||||||
|
const newSessions = new Map(state.sessions);
|
||||||
|
const existing = newSessions.get(key);
|
||||||
|
if (!existing) {
|
||||||
|
return state;
|
||||||
|
}
|
||||||
|
|
||||||
|
const idx = findTabIndex(existing, tabId);
|
||||||
|
if (idx < 0) {
|
||||||
|
return state;
|
||||||
|
}
|
||||||
|
|
||||||
|
const nextTabs = [...existing.tabs];
|
||||||
|
nextTabs[idx] = { ...nextTabs[idx], isConnecting };
|
||||||
|
newSessions.set(key, { ...existing, tabs: nextTabs });
|
||||||
|
return { sessions: newSessions };
|
||||||
|
});
|
||||||
|
},
|
||||||
|
|
||||||
|
appendToBuffer: (directory: string, tabId: string, chunk: string) => {
|
||||||
|
if (!chunk) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const key = normalizeDirectory(directory);
|
||||||
|
set((state) => {
|
||||||
|
const newSessions = new Map(state.sessions);
|
||||||
|
const existing = newSessions.get(key);
|
||||||
|
if (!existing) {
|
||||||
|
return state;
|
||||||
|
}
|
||||||
|
|
||||||
|
const idx = findTabIndex(existing, tabId);
|
||||||
|
if (idx < 0) {
|
||||||
|
return state;
|
||||||
|
}
|
||||||
|
|
||||||
|
const tab = existing.tabs[idx];
|
||||||
|
const chunkId = state.nextChunkId;
|
||||||
|
const chunkEntry: TerminalChunk = { id: chunkId, data: chunk };
|
||||||
|
|
||||||
|
const bufferChunks = [...tab.bufferChunks, chunkEntry];
|
||||||
|
let bufferLength = tab.bufferLength + chunk.length;
|
||||||
|
|
||||||
|
while (bufferLength > TERMINAL_BUFFER_LIMIT && bufferChunks.length > 1) {
|
||||||
|
const removed = bufferChunks.shift();
|
||||||
|
if (!removed) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
bufferLength -= removed.data.length;
|
||||||
|
}
|
||||||
|
|
||||||
|
const nextTabs = [...existing.tabs];
|
||||||
|
nextTabs[idx] = {
|
||||||
|
...tab,
|
||||||
|
bufferChunks,
|
||||||
|
bufferLength,
|
||||||
|
};
|
||||||
|
newSessions.set(key, { ...existing, tabs: nextTabs });
|
||||||
|
|
||||||
|
return { sessions: newSessions, nextChunkId: chunkId + 1 };
|
||||||
|
});
|
||||||
|
},
|
||||||
|
|
||||||
|
clearBuffer: (directory: string, tabId: string) => {
|
||||||
|
const key = normalizeDirectory(directory);
|
||||||
|
set((state) => {
|
||||||
|
const newSessions = new Map(state.sessions);
|
||||||
|
const existing = newSessions.get(key);
|
||||||
|
if (!existing) {
|
||||||
|
return state;
|
||||||
|
}
|
||||||
|
|
||||||
|
const idx = findTabIndex(existing, tabId);
|
||||||
|
if (idx < 0) {
|
||||||
|
return state;
|
||||||
|
}
|
||||||
|
|
||||||
|
const nextTabs = [...existing.tabs];
|
||||||
|
nextTabs[idx] = {
|
||||||
|
...nextTabs[idx],
|
||||||
|
bufferChunks: [],
|
||||||
|
bufferLength: 0,
|
||||||
|
};
|
||||||
|
newSessions.set(key, { ...existing, tabs: nextTabs });
|
||||||
|
return { sessions: newSessions };
|
||||||
|
});
|
||||||
|
},
|
||||||
|
|
||||||
|
removeDirectory: (directory: string) => {
|
||||||
|
const key = normalizeDirectory(directory);
|
||||||
|
set((state) => {
|
||||||
|
const newSessions = new Map(state.sessions);
|
||||||
|
newSessions.delete(key);
|
||||||
|
return { sessions: newSessions };
|
||||||
|
});
|
||||||
|
},
|
||||||
|
|
||||||
|
clearAll: () => {
|
||||||
|
set({ sessions: new Map(), nextChunkId: 1, nextTabId: 1 });
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
{
|
||||||
|
name: TERMINAL_STORE_NAME,
|
||||||
|
storage: createJSONStorage(() => getSafeSessionStorage()),
|
||||||
|
partialize: (state): PersistedTerminalStoreState => ({
|
||||||
|
sessions: Array.from(state.sessions.entries()).map(([directory, dirState]) => [
|
||||||
|
directory,
|
||||||
|
{
|
||||||
|
activeTabId: dirState.activeTabId,
|
||||||
|
tabs: dirState.tabs.map((tab) => ({
|
||||||
|
id: tab.id,
|
||||||
|
label: tab.label,
|
||||||
|
terminalSessionId: tab.terminalSessionId,
|
||||||
|
createdAt: tab.createdAt,
|
||||||
|
})),
|
||||||
|
},
|
||||||
|
]),
|
||||||
|
nextTabId: state.nextTabId,
|
||||||
|
}),
|
||||||
|
merge: (persistedState, currentState) => {
|
||||||
|
if (!isRecord(persistedState)) {
|
||||||
|
return currentState;
|
||||||
|
}
|
||||||
|
|
||||||
|
const rawSessions = Array.isArray(persistedState.sessions)
|
||||||
|
? (persistedState.sessions as PersistedTerminalStoreState['sessions'])
|
||||||
|
: [];
|
||||||
|
|
||||||
|
const sessions = new Map<string, DirectoryTerminalState>();
|
||||||
|
let maxTabNum = 0;
|
||||||
|
|
||||||
|
for (const entry of rawSessions) {
|
||||||
|
if (!Array.isArray(entry) || entry.length !== 2) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
const [directory, rawState] = entry as [unknown, unknown];
|
||||||
|
if (typeof directory !== 'string' || !isRecord(rawState)) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
const rawTabs = Array.isArray(rawState.tabs) ? (rawState.tabs as unknown[]) : [];
|
||||||
|
const tabs: TerminalTab[] = [];
|
||||||
|
|
||||||
|
for (const rawTab of rawTabs) {
|
||||||
|
if (!isRecord(rawTab)) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
const id = typeof rawTab.id === 'string' ? rawTab.id : null;
|
||||||
|
if (!id) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
const num = tabIdNumber(id);
|
||||||
|
if (num !== null) {
|
||||||
|
maxTabNum = Math.max(maxTabNum, num);
|
||||||
|
}
|
||||||
|
|
||||||
|
tabs.push({
|
||||||
|
id,
|
||||||
|
label: typeof rawTab.label === 'string' ? rawTab.label : 'Terminal',
|
||||||
|
terminalSessionId:
|
||||||
|
typeof rawTab.terminalSessionId === 'string' || rawTab.terminalSessionId === null
|
||||||
|
? (rawTab.terminalSessionId as string | null)
|
||||||
|
: null,
|
||||||
|
createdAt: typeof rawTab.createdAt === 'number' ? rawTab.createdAt : Date.now(),
|
||||||
|
bufferChunks: [],
|
||||||
|
bufferLength: 0,
|
||||||
|
isConnecting: false,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
if (tabs.length === 0) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
const activeTabId =
|
||||||
|
typeof rawState.activeTabId === 'string' ? (rawState.activeTabId as string) : null;
|
||||||
|
const activeExists = activeTabId ? tabs.some((t) => t.id === activeTabId) : false;
|
||||||
|
|
||||||
|
sessions.set(directory, {
|
||||||
|
tabs,
|
||||||
|
activeTabId: activeExists ? activeTabId : tabs[0].id,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
const persistedNextTabId =
|
||||||
|
typeof persistedState.nextTabId === 'number' && Number.isFinite(persistedState.nextTabId)
|
||||||
|
? (persistedState.nextTabId as number)
|
||||||
|
: 1;
|
||||||
|
|
||||||
|
const nextTabId = Math.max(currentState.nextTabId, persistedNextTabId, maxTabNum + 1);
|
||||||
|
|
||||||
|
return {
|
||||||
|
...currentState,
|
||||||
|
sessions,
|
||||||
|
nextChunkId: 1,
|
||||||
|
nextTabId,
|
||||||
|
hasHydrated: true,
|
||||||
|
};
|
||||||
|
},
|
||||||
|
}
|
||||||
|
)
|
||||||
|
)
|
||||||
|
);
|
||||||
|
|
||||||
|
// Ensure hydration completes even when no persisted state exists.
|
||||||
|
if (typeof window !== 'undefined' && !hydrationListenerAttached) {
|
||||||
|
hydrationListenerAttached = true;
|
||||||
|
const persistApi = (
|
||||||
|
useTerminalStore as unknown as {
|
||||||
|
persist?: {
|
||||||
|
hasHydrated?: () => boolean;
|
||||||
|
onFinishHydration?: (cb: () => void) => (() => void) | void;
|
||||||
|
};
|
||||||
}
|
}
|
||||||
|
).persist;
|
||||||
|
|
||||||
const key = normalizeDirectory(directory);
|
const markHydrated = () => {
|
||||||
set((state) => {
|
if (!useTerminalStore.getState().hasHydrated) {
|
||||||
const newSessions = new Map(state.sessions);
|
useTerminalStore.setState({ hasHydrated: true });
|
||||||
const existing = newSessions.get(key) ?? createEmptySessionState(key);
|
}
|
||||||
|
};
|
||||||
|
|
||||||
const chunkId = state.nextChunkId;
|
if (persistApi?.hasHydrated?.()) {
|
||||||
const chunkEntry: TerminalChunk = { id: chunkId, data: chunk };
|
markHydrated();
|
||||||
|
} else if (persistApi?.onFinishHydration) {
|
||||||
const bufferChunks = [...existing.bufferChunks, chunkEntry];
|
persistApi.onFinishHydration(markHydrated);
|
||||||
let bufferLength = existing.bufferLength + chunk.length;
|
} else {
|
||||||
|
markHydrated();
|
||||||
while (bufferLength > TERMINAL_BUFFER_LIMIT && bufferChunks.length > 1) {
|
}
|
||||||
const removed = bufferChunks.shift();
|
}
|
||||||
if (!removed) {
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
bufferLength -= removed.data.length;
|
|
||||||
}
|
|
||||||
|
|
||||||
const buffer = bufferChunks.map((entry) => entry.data).join('');
|
|
||||||
|
|
||||||
newSessions.set(key, {
|
|
||||||
...existing,
|
|
||||||
buffer,
|
|
||||||
bufferChunks,
|
|
||||||
bufferLength,
|
|
||||||
updatedAt: Date.now(),
|
|
||||||
});
|
|
||||||
|
|
||||||
return { sessions: newSessions, nextChunkId: chunkId + 1 };
|
|
||||||
});
|
|
||||||
},
|
|
||||||
|
|
||||||
clearTerminalSession: (directory: string) => {
|
|
||||||
const key = normalizeDirectory(directory);
|
|
||||||
set((state) => {
|
|
||||||
const newSessions = new Map(state.sessions);
|
|
||||||
const existing = newSessions.get(key);
|
|
||||||
if (existing) {
|
|
||||||
newSessions.set(key, {
|
|
||||||
...existing,
|
|
||||||
terminalSessionId: null,
|
|
||||||
isConnecting: false,
|
|
||||||
updatedAt: Date.now(),
|
|
||||||
});
|
|
||||||
}
|
|
||||||
return { sessions: newSessions };
|
|
||||||
});
|
|
||||||
},
|
|
||||||
|
|
||||||
clearBuffer: (directory: string) => {
|
|
||||||
const key = normalizeDirectory(directory);
|
|
||||||
set((state) => {
|
|
||||||
const newSessions = new Map(state.sessions);
|
|
||||||
const existing = newSessions.get(key);
|
|
||||||
if (!existing) {
|
|
||||||
return state;
|
|
||||||
}
|
|
||||||
newSessions.set(key, {
|
|
||||||
...existing,
|
|
||||||
buffer: '',
|
|
||||||
bufferChunks: [],
|
|
||||||
bufferLength: 0,
|
|
||||||
updatedAt: Date.now(),
|
|
||||||
});
|
|
||||||
return { sessions: newSessions };
|
|
||||||
});
|
|
||||||
},
|
|
||||||
|
|
||||||
removeTerminalSession: (directory: string) => {
|
|
||||||
const key = normalizeDirectory(directory);
|
|
||||||
set((state) => {
|
|
||||||
const newSessions = new Map(state.sessions);
|
|
||||||
newSessions.delete(key);
|
|
||||||
return { sessions: newSessions };
|
|
||||||
});
|
|
||||||
},
|
|
||||||
|
|
||||||
clearAllTerminalSessions: () => {
|
|
||||||
set({ sessions: new Map(), nextChunkId: 1 });
|
|
||||||
},
|
|
||||||
}));
|
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
let safeStorageInstance: Storage | null = null;
|
let safeStorageInstance: Storage | null = null;
|
||||||
|
let safeSessionStorageInstance: Storage | null = null;
|
||||||
|
|
||||||
const createInMemoryStorage = (): Storage => {
|
const createInMemoryStorage = (): Storage => {
|
||||||
const store = new Map<string, string>();
|
const store = new Map<string, string>();
|
||||||
@@ -119,3 +120,101 @@ export const getSafeStorage = (): Storage => {
|
|||||||
return safeStorageInstance;
|
return safeStorageInstance;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const createSafeSessionStorage = (): Storage => {
|
||||||
|
if (typeof window === 'undefined' || !window.sessionStorage) {
|
||||||
|
return createInMemoryStorage();
|
||||||
|
}
|
||||||
|
|
||||||
|
const baseStorage = window.sessionStorage;
|
||||||
|
const fallback = createInMemoryStorage();
|
||||||
|
let storageAvailable = true;
|
||||||
|
|
||||||
|
const disableStorage = () => {
|
||||||
|
storageAvailable = false;
|
||||||
|
};
|
||||||
|
|
||||||
|
const safeGet = (key: string): string | null => {
|
||||||
|
if (storageAvailable) {
|
||||||
|
try {
|
||||||
|
const value = baseStorage.getItem(key);
|
||||||
|
if (value !== null) {
|
||||||
|
return value;
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
disableStorage();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return fallback.getItem(key);
|
||||||
|
};
|
||||||
|
|
||||||
|
const safeSet = (key: string, value: string) => {
|
||||||
|
if (storageAvailable) {
|
||||||
|
try {
|
||||||
|
baseStorage.setItem(key, value);
|
||||||
|
fallback.removeItem(key);
|
||||||
|
return;
|
||||||
|
} catch {
|
||||||
|
disableStorage();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
fallback.setItem(key, value);
|
||||||
|
};
|
||||||
|
|
||||||
|
const safeRemove = (key: string) => {
|
||||||
|
if (storageAvailable) {
|
||||||
|
try {
|
||||||
|
baseStorage.removeItem(key);
|
||||||
|
} catch {
|
||||||
|
disableStorage();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
fallback.removeItem(key);
|
||||||
|
};
|
||||||
|
|
||||||
|
const safeClear = () => {
|
||||||
|
if (storageAvailable) {
|
||||||
|
try {
|
||||||
|
baseStorage.clear();
|
||||||
|
} catch {
|
||||||
|
disableStorage();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
fallback.clear();
|
||||||
|
};
|
||||||
|
|
||||||
|
const safeKey = (index: number): string | null => {
|
||||||
|
if (storageAvailable) {
|
||||||
|
try {
|
||||||
|
return baseStorage.key(index);
|
||||||
|
} catch {
|
||||||
|
disableStorage();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return fallback.key(index);
|
||||||
|
};
|
||||||
|
|
||||||
|
return {
|
||||||
|
getItem: safeGet,
|
||||||
|
setItem: safeSet,
|
||||||
|
removeItem: safeRemove,
|
||||||
|
clear: safeClear,
|
||||||
|
key: safeKey,
|
||||||
|
get length() {
|
||||||
|
if (storageAvailable) {
|
||||||
|
try {
|
||||||
|
return baseStorage.length + fallback.length;
|
||||||
|
} catch {
|
||||||
|
disableStorage();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return fallback.length;
|
||||||
|
},
|
||||||
|
} as Storage;
|
||||||
|
};
|
||||||
|
|
||||||
|
export const getSafeSessionStorage = (): Storage => {
|
||||||
|
if (!safeSessionStorageInstance) {
|
||||||
|
safeSessionStorageInstance = createSafeSessionStorage();
|
||||||
|
}
|
||||||
|
return safeSessionStorageInstance;
|
||||||
|
};
|
||||||
|
|||||||
Reference in New Issue
Block a user