mirror of
https://github.com/siteboon/claudecodeui.git
synced 2026-06-09 23:25:51 +08:00
Compare commits
1 Commits
fix/codex-
...
feature/ch
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d70dc077bf |
@@ -10,6 +10,7 @@ type NotificationPreferences = {
|
||||
channels: {
|
||||
inApp: boolean;
|
||||
webPush: boolean;
|
||||
sound: boolean;
|
||||
};
|
||||
events: {
|
||||
actionRequired: boolean;
|
||||
@@ -22,6 +23,7 @@ const DEFAULT_NOTIFICATION_PREFERENCES: NotificationPreferences = {
|
||||
channels: {
|
||||
inApp: false,
|
||||
webPush: false,
|
||||
sound: true,
|
||||
},
|
||||
events: {
|
||||
actionRequired: true,
|
||||
@@ -37,6 +39,7 @@ function normalizeNotificationPreferences(value: unknown): NotificationPreferenc
|
||||
channels: {
|
||||
inApp: source.channels?.inApp === true,
|
||||
webPush: source.channels?.webPush === true,
|
||||
sound: source.channels?.sound !== false,
|
||||
},
|
||||
events: {
|
||||
actionRequired: source.events?.actionRequired !== false,
|
||||
|
||||
@@ -279,16 +279,6 @@ export async function queryCodex(command, options = {}, ws) {
|
||||
startedAt: new Date().toISOString()
|
||||
});
|
||||
};
|
||||
const markSessionFinished = (id) => {
|
||||
if (!id) {
|
||||
return;
|
||||
}
|
||||
|
||||
const session = activeCodexSessions.get(id);
|
||||
if (session && session.status !== 'aborted') {
|
||||
session.status = 'completed';
|
||||
}
|
||||
};
|
||||
|
||||
// Existing sessions can be tracked immediately; new sessions are tracked after thread.started.
|
||||
if (capturedSessionId) {
|
||||
@@ -334,10 +324,6 @@ export async function queryCodex(command, options = {}, ws) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (event.type === 'turn.completed' || event.type === 'turn.failed') {
|
||||
markSessionFinished(capturedSessionId || sessionId);
|
||||
}
|
||||
|
||||
const transformed = transformCodexEvent(event);
|
||||
|
||||
// Normalize the transformed event into NormalizedMessage(s) via adapter
|
||||
@@ -368,8 +354,6 @@ export async function queryCodex(command, options = {}, ws) {
|
||||
|
||||
// Send completion event
|
||||
if (!terminalFailure) {
|
||||
markSessionFinished(capturedSessionId || sessionId);
|
||||
|
||||
sendMessage(ws, createNormalizedMessage({
|
||||
kind: 'complete',
|
||||
actualSessionId: capturedSessionId || thread.id || sessionId || null,
|
||||
|
||||
@@ -2,6 +2,8 @@ import { useEffect, useRef } from 'react';
|
||||
import type { Dispatch, MutableRefObject, SetStateAction } from 'react';
|
||||
|
||||
import { usePaletteOps } from '../../../contexts/PaletteOpsContext';
|
||||
import { showCompletionTitleIndicator } from '../../../utils/pageTitleNotification';
|
||||
import { playChatCompletionSound } from '../../../utils/notificationSound';
|
||||
import type { PendingPermissionRequest, SessionNavigationOptions } from '../types/types';
|
||||
import type { ProjectSession, LLMProvider } from '../../../types/app';
|
||||
import type { SessionStore, NormalizedMessage } from '../../../stores/useSessionStore';
|
||||
@@ -98,7 +100,6 @@ export function useChatRealtimeHandlers({
|
||||
}: UseChatRealtimeHandlersArgs) {
|
||||
const paletteOps = usePaletteOps();
|
||||
const lastProcessedMessageRef = useRef<LatestChatMessage | null>(null);
|
||||
const terminalSessionIdsRef = useRef<Set<string>>(new Set());
|
||||
|
||||
useEffect(() => {
|
||||
if (!latestMessage) return;
|
||||
@@ -152,17 +153,6 @@ export function useChatRealtimeHandlers({
|
||||
const isCurrentSession =
|
||||
statusSessionId === currentSessionId || (selectedSession && statusSessionId === selectedSession.id);
|
||||
|
||||
if (msg.isProcessing && terminalSessionIdsRef.current.has(statusSessionId)) {
|
||||
onSessionInactive?.(statusSessionId);
|
||||
onSessionNotProcessing?.(statusSessionId);
|
||||
if (isCurrentSession) {
|
||||
setIsLoading(false);
|
||||
setCanAbortSession(false);
|
||||
setClaudeStatus(null);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (msg.isProcessing) {
|
||||
onSessionActive?.(statusSessionId);
|
||||
onSessionProcessing?.(statusSessionId);
|
||||
@@ -192,10 +182,6 @@ export function useChatRealtimeHandlers({
|
||||
|
||||
const sid = msg.sessionId || activeViewSessionId;
|
||||
|
||||
if (sid && msg.kind === 'session_created') {
|
||||
terminalSessionIdsRef.current.delete(sid);
|
||||
}
|
||||
|
||||
// --- Streaming: buffer for performance ---
|
||||
if (msg.kind === 'stream_delta') {
|
||||
const text = msg.content || '';
|
||||
@@ -274,10 +260,6 @@ export function useChatRealtimeHandlers({
|
||||
}
|
||||
|
||||
case 'complete': {
|
||||
if (sid) {
|
||||
terminalSessionIdsRef.current.add(sid);
|
||||
}
|
||||
|
||||
// Flush any remaining streaming state
|
||||
if (streamTimerRef.current) {
|
||||
clearTimeout(streamTimerRef.current);
|
||||
@@ -305,6 +287,9 @@ export function useChatRealtimeHandlers({
|
||||
break;
|
||||
}
|
||||
|
||||
showCompletionTitleIndicator();
|
||||
void playChatCompletionSound();
|
||||
|
||||
const actualSessionId =
|
||||
typeof msg.actualSessionId === 'string' && msg.actualSessionId.trim().length > 0
|
||||
? msg.actualSessionId
|
||||
@@ -333,10 +318,6 @@ export function useChatRealtimeHandlers({
|
||||
}
|
||||
|
||||
case 'error': {
|
||||
if (sid) {
|
||||
terminalSessionIdsRef.current.add(sid);
|
||||
}
|
||||
|
||||
setIsLoading(false);
|
||||
setCanAbortSession(false);
|
||||
setClaudeStatus(null);
|
||||
|
||||
@@ -131,8 +131,6 @@ export function useChatSessionState({
|
||||
const pendingInitialScrollRef = useRef(true);
|
||||
const messagesOffsetRef = useRef(0);
|
||||
const scrollPositionRef = useRef({ height: 0, top: 0 });
|
||||
const previousProcessingSessionsRef = useRef<Set<string> | null>(null);
|
||||
const previousProcessingSessionViewIdRef = useRef<string | null>(null);
|
||||
const loadAllFinishedTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
|
||||
const loadAllOverlayTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
|
||||
const lastLoadedSessionKeyRef = useRef<string | null>(null);
|
||||
@@ -695,17 +693,9 @@ export function useChatSessionState({
|
||||
|
||||
useEffect(() => {
|
||||
const activeViewSessionId = selectedSession?.id || currentSessionId;
|
||||
const previousProcessingSessions = previousProcessingSessionsRef.current;
|
||||
const previousProcessingSessionViewId = previousProcessingSessionViewIdRef.current;
|
||||
previousProcessingSessionsRef.current = processingSessions ?? null;
|
||||
previousProcessingSessionViewIdRef.current = activeViewSessionId ?? null;
|
||||
|
||||
if (!activeViewSessionId || !processingSessions) return;
|
||||
|
||||
const activeViewSessionChanged = previousProcessingSessionViewId !== activeViewSessionId;
|
||||
const wasProcessing = previousProcessingSessions?.has(activeViewSessionId) ?? false;
|
||||
const shouldBeProcessing = processingSessions.has(activeViewSessionId);
|
||||
if (shouldBeProcessing && (!wasProcessing || activeViewSessionChanged) && !isLoading) {
|
||||
if (shouldBeProcessing && !isLoading) {
|
||||
setIsLoading(true);
|
||||
setCanAbortSession(true);
|
||||
}
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
import { useCallback, useEffect, useRef, useState } from 'react';
|
||||
|
||||
import { useTheme } from '../../../contexts/ThemeContext';
|
||||
import { authenticatedFetch } from '../../../utils/api';
|
||||
import { setNotificationSoundEnabled } from '../../../utils/notificationSound';
|
||||
import { useProviderAuthStatus } from '../../provider-auth/hooks/useProviderAuthStatus';
|
||||
import {
|
||||
DEFAULT_CODE_EDITOR_SETTINGS,
|
||||
@@ -107,6 +109,7 @@ const createDefaultNotificationPreferences = (): NotificationPreferencesState =>
|
||||
channels: {
|
||||
inApp: true,
|
||||
webPush: false,
|
||||
sound: true,
|
||||
},
|
||||
events: {
|
||||
actionRequired: true,
|
||||
@@ -115,6 +118,25 @@ const createDefaultNotificationPreferences = (): NotificationPreferencesState =>
|
||||
},
|
||||
});
|
||||
|
||||
const normalizeNotificationPreferences = (
|
||||
preferences?: Partial<NotificationPreferencesState> | null,
|
||||
): NotificationPreferencesState => {
|
||||
const defaults = createDefaultNotificationPreferences();
|
||||
|
||||
return {
|
||||
channels: {
|
||||
inApp: preferences?.channels?.inApp ?? defaults.channels.inApp,
|
||||
webPush: preferences?.channels?.webPush ?? defaults.channels.webPush,
|
||||
sound: preferences?.channels?.sound ?? defaults.channels.sound,
|
||||
},
|
||||
events: {
|
||||
actionRequired: preferences?.events?.actionRequired ?? defaults.events.actionRequired,
|
||||
stop: preferences?.events?.stop ?? defaults.events.stop,
|
||||
error: preferences?.events?.error ?? defaults.events.error,
|
||||
},
|
||||
};
|
||||
};
|
||||
|
||||
export function useSettingsController({ isOpen, initialTab }: UseSettingsControllerArgs) {
|
||||
const { isDarkMode, toggleDarkMode } = useTheme() as ThemeContextValue;
|
||||
const closeTimerRef = useRef<number | null>(null);
|
||||
@@ -186,7 +208,7 @@ export function useSettingsController({ isOpen, initialTab }: UseSettingsControl
|
||||
if (notificationResponse.ok) {
|
||||
const notificationData = await toResponseJson<NotificationPreferencesResponse>(notificationResponse);
|
||||
if (notificationData.success && notificationData.preferences) {
|
||||
setNotificationPreferences(notificationData.preferences);
|
||||
setNotificationPreferences(normalizeNotificationPreferences(notificationData.preferences));
|
||||
} else {
|
||||
setNotificationPreferences(createDefaultNotificationPreferences());
|
||||
}
|
||||
@@ -301,6 +323,10 @@ export function useSettingsController({ isOpen, initialTab }: UseSettingsControl
|
||||
void refreshProviderAuthStatuses();
|
||||
}, [initialTab, isOpen, loadSettings, refreshProviderAuthStatuses]);
|
||||
|
||||
useEffect(() => {
|
||||
setNotificationSoundEnabled(notificationPreferences.channels.sound);
|
||||
}, [notificationPreferences.channels.sound]);
|
||||
|
||||
useEffect(() => {
|
||||
localStorage.setItem('codeEditorTheme', codeEditorSettings.theme);
|
||||
localStorage.setItem('codeEditorWordWrap', String(codeEditorSettings.wordWrap));
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import type { Dispatch, SetStateAction } from 'react';
|
||||
|
||||
import type { LLMProvider } from '../../../types/app';
|
||||
import type { ProviderAuthStatus } from '../../provider-auth/types';
|
||||
|
||||
@@ -29,6 +30,7 @@ export type NotificationPreferencesState = {
|
||||
channels: {
|
||||
inApp: boolean;
|
||||
webPush: boolean;
|
||||
sound: boolean;
|
||||
};
|
||||
events: {
|
||||
actionRequired: boolean;
|
||||
|
||||
@@ -1,5 +1,8 @@
|
||||
import { Bell, BellOff, BellRing, Loader2 } from 'lucide-react';
|
||||
import { Bell, BellOff, BellRing, Loader2, Play, Volume2 } from 'lucide-react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
|
||||
import { Button } from '../../../../shared/view/ui';
|
||||
import { playChatCompletionSound } from '../../../../utils/notificationSound';
|
||||
import type { NotificationPreferencesState } from '../../types/types';
|
||||
|
||||
type NotificationsSettingsTabProps = {
|
||||
@@ -82,6 +85,54 @@ export default function NotificationsSettingsTab({
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="space-y-4 rounded-lg border border-border bg-card p-4">
|
||||
<div className="flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
|
||||
<div className="space-y-1">
|
||||
<div className="flex items-center gap-2">
|
||||
<Volume2 className="h-4 w-4 text-blue-600" />
|
||||
<h4 className="font-medium text-foreground">
|
||||
{t('notifications.sound.title', { defaultValue: 'Sound' })}
|
||||
</h4>
|
||||
</div>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
{t('notifications.sound.description', {
|
||||
defaultValue: 'Play a short tone when a chat run finishes.',
|
||||
})}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<label className="flex shrink-0 items-center gap-2 text-sm text-foreground">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={notificationPreferences.channels.sound}
|
||||
onChange={(event) =>
|
||||
onNotificationPreferencesChange({
|
||||
...notificationPreferences,
|
||||
channels: {
|
||||
...notificationPreferences.channels,
|
||||
sound: event.target.checked,
|
||||
},
|
||||
})
|
||||
}
|
||||
className="h-4 w-4"
|
||||
/>
|
||||
{t('notifications.sound.enabled', { defaultValue: 'Enabled' })}
|
||||
</label>
|
||||
</div>
|
||||
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => {
|
||||
void playChatCompletionSound({ force: true });
|
||||
}}
|
||||
>
|
||||
<Play className="h-4 w-4" />
|
||||
{t('notifications.sound.test', { defaultValue: 'Test sound' })}
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<div className="space-y-4 bg-card border border-border rounded-lg p-4">
|
||||
<h4 className="font-medium text-foreground">{t('notifications.events.title')}</h4>
|
||||
<div className="space-y-3">
|
||||
|
||||
@@ -97,6 +97,14 @@
|
||||
"plugins": "Plugins",
|
||||
"about": "Info"
|
||||
},
|
||||
"notifications": {
|
||||
"sound": {
|
||||
"title": "Ton",
|
||||
"description": "Spielt einen kurzen Ton ab, wenn ein Chat-Lauf abgeschlossen ist.",
|
||||
"enabled": "Aktiviert",
|
||||
"test": "Ton testen"
|
||||
}
|
||||
},
|
||||
"appearanceSettings": {
|
||||
"darkMode": {
|
||||
"label": "Darkmode",
|
||||
|
||||
@@ -110,6 +110,12 @@
|
||||
"unsupported": "Push notifications are not supported in this browser.",
|
||||
"denied": "Push notifications are blocked. Please allow them in your browser settings."
|
||||
},
|
||||
"sound": {
|
||||
"title": "Sound",
|
||||
"description": "Play a short tone when a chat run finishes.",
|
||||
"enabled": "Enabled",
|
||||
"test": "Test sound"
|
||||
},
|
||||
"events": {
|
||||
"title": "Event Types",
|
||||
"actionRequired": "Action required",
|
||||
|
||||
@@ -110,6 +110,12 @@
|
||||
"unsupported": "Le notifiche push non sono supportate in questo browser.",
|
||||
"denied": "Le notifiche push sono bloccate. Abilitale nelle impostazioni del browser."
|
||||
},
|
||||
"sound": {
|
||||
"title": "Suono",
|
||||
"description": "Riproduci un breve tono quando termina un'esecuzione della chat.",
|
||||
"enabled": "Attivato",
|
||||
"test": "Prova suono"
|
||||
},
|
||||
"events": {
|
||||
"title": "Tipi di evento",
|
||||
"actionRequired": "Azione richiesta",
|
||||
|
||||
@@ -110,6 +110,12 @@
|
||||
"unsupported": "このブラウザではプッシュ通知がサポートされていません。",
|
||||
"denied": "プッシュ通知がブロックされています。ブラウザの設定で許可してください。"
|
||||
},
|
||||
"sound": {
|
||||
"title": "サウンド",
|
||||
"description": "チャット実行が完了したときに短い音を再生します。",
|
||||
"enabled": "有効",
|
||||
"test": "サウンドをテスト"
|
||||
},
|
||||
"events": {
|
||||
"title": "イベント種別",
|
||||
"actionRequired": "対応が必要",
|
||||
|
||||
@@ -110,6 +110,12 @@
|
||||
"unsupported": "이 브라우저에서는 푸시 알림이 지원되지 않습니다.",
|
||||
"denied": "푸시 알림이 차단되었습니다. 브라우저 설정에서 허용해 주세요."
|
||||
},
|
||||
"sound": {
|
||||
"title": "소리",
|
||||
"description": "채팅 실행이 완료되면 짧은 알림음을 재생합니다.",
|
||||
"enabled": "사용",
|
||||
"test": "소리 테스트"
|
||||
},
|
||||
"events": {
|
||||
"title": "이벤트 유형",
|
||||
"actionRequired": "작업 필요",
|
||||
|
||||
@@ -97,6 +97,14 @@
|
||||
"plugins": "Плагины",
|
||||
"about": "О программе"
|
||||
},
|
||||
"notifications": {
|
||||
"sound": {
|
||||
"title": "Звук",
|
||||
"description": "Воспроизводить короткий сигнал при завершении запуска чата.",
|
||||
"enabled": "Включено",
|
||||
"test": "Проверить звук"
|
||||
}
|
||||
},
|
||||
"appearanceSettings": {
|
||||
"darkMode": {
|
||||
"label": "Темная тема",
|
||||
|
||||
@@ -110,6 +110,12 @@
|
||||
"unsupported": "Bu tarayıcıda push bildirimleri desteklenmiyor.",
|
||||
"denied": "Push bildirimleri engellendi. Lütfen tarayıcı ayarlarından izin ver."
|
||||
},
|
||||
"sound": {
|
||||
"title": "Ses",
|
||||
"description": "Sohbet çalışması tamamlandığında kısa bir ton çal.",
|
||||
"enabled": "Etkin",
|
||||
"test": "Sesi test et"
|
||||
},
|
||||
"events": {
|
||||
"title": "Etkinlik Türleri",
|
||||
"actionRequired": "Aksiyon gerekli",
|
||||
|
||||
@@ -110,6 +110,12 @@
|
||||
"unsupported": "此浏览器不支持推送通知。",
|
||||
"denied": "推送通知已被阻止,请在浏览器设置中允许。"
|
||||
},
|
||||
"sound": {
|
||||
"title": "声音",
|
||||
"description": "聊天运行完成时播放短提示音。",
|
||||
"enabled": "已启用",
|
||||
"test": "测试声音"
|
||||
},
|
||||
"events": {
|
||||
"title": "事件类型",
|
||||
"actionRequired": "需要处理",
|
||||
|
||||
@@ -110,6 +110,12 @@
|
||||
"unsupported": "此瀏覽器不支援推播通知。",
|
||||
"denied": "推播通知已被封鎖,請在瀏覽器設定中允許。"
|
||||
},
|
||||
"sound": {
|
||||
"title": "聲音",
|
||||
"description": "聊天執行完成時播放短提示音。",
|
||||
"enabled": "已啟用",
|
||||
"test": "測試聲音"
|
||||
},
|
||||
"events": {
|
||||
"title": "事件類型",
|
||||
"actionRequired": "需要處理",
|
||||
|
||||
83
src/utils/notificationSound.ts
Normal file
83
src/utils/notificationSound.ts
Normal file
@@ -0,0 +1,83 @@
|
||||
const NOTIFICATION_SOUND_ENABLED_STORAGE_KEY = 'notificationSoundEnabled';
|
||||
const AudioContextConstructor =
|
||||
typeof window !== 'undefined'
|
||||
? window.AudioContext || (window as typeof window & { webkitAudioContext?: typeof AudioContext }).webkitAudioContext
|
||||
: undefined;
|
||||
|
||||
let audioContext: AudioContext | null = null;
|
||||
|
||||
export const isNotificationSoundEnabled = (): boolean => {
|
||||
if (typeof localStorage === 'undefined') {
|
||||
return true;
|
||||
}
|
||||
|
||||
return localStorage.getItem(NOTIFICATION_SOUND_ENABLED_STORAGE_KEY) !== 'false';
|
||||
};
|
||||
|
||||
export const setNotificationSoundEnabled = (enabled: boolean): void => {
|
||||
if (typeof localStorage === 'undefined') {
|
||||
return;
|
||||
}
|
||||
|
||||
localStorage.setItem(NOTIFICATION_SOUND_ENABLED_STORAGE_KEY, String(enabled));
|
||||
};
|
||||
|
||||
const getAudioContext = (): AudioContext | null => {
|
||||
if (!AudioContextConstructor) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (!audioContext) {
|
||||
audioContext = new AudioContextConstructor();
|
||||
}
|
||||
|
||||
return audioContext;
|
||||
};
|
||||
|
||||
const playTone = (
|
||||
context: AudioContext,
|
||||
frequency: number,
|
||||
startsAt: number,
|
||||
duration: number,
|
||||
peakVolume: number,
|
||||
): void => {
|
||||
const oscillator = context.createOscillator();
|
||||
const gain = context.createGain();
|
||||
|
||||
oscillator.type = 'sine';
|
||||
oscillator.frequency.setValueAtTime(frequency, startsAt);
|
||||
|
||||
// Shape the volume so the synthesized tone starts and stops cleanly.
|
||||
gain.gain.setValueAtTime(0.0001, startsAt);
|
||||
gain.gain.exponentialRampToValueAtTime(peakVolume, startsAt + 0.015);
|
||||
gain.gain.exponentialRampToValueAtTime(0.0001, startsAt + duration);
|
||||
|
||||
oscillator.connect(gain);
|
||||
gain.connect(context.destination);
|
||||
oscillator.start(startsAt);
|
||||
oscillator.stop(startsAt + duration + 0.02);
|
||||
};
|
||||
|
||||
export const playChatCompletionSound = async ({ force = false } = {}): Promise<void> => {
|
||||
if (!force && !isNotificationSoundEnabled()) {
|
||||
return;
|
||||
}
|
||||
|
||||
const context = getAudioContext();
|
||||
if (!context) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
if (context.state === 'suspended') {
|
||||
await context.resume();
|
||||
}
|
||||
|
||||
const now = context.currentTime;
|
||||
playTone(context, 740, now, 0.12, 0.075);
|
||||
playTone(context, 988, now + 0.11, 0.16, 0.06);
|
||||
} catch (error) {
|
||||
// Browsers may block audio until the page receives a user gesture.
|
||||
console.warn('Unable to play notification sound:', error);
|
||||
}
|
||||
};
|
||||
86
src/utils/pageTitleNotification.ts
Normal file
86
src/utils/pageTitleNotification.ts
Normal file
@@ -0,0 +1,86 @@
|
||||
const COMPLETION_TITLE_INDICATOR = '[Done]';
|
||||
const TITLE_INDICATOR_CLEAR_DELAY_MS = 2000;
|
||||
|
||||
let clearTimer: number | null = null;
|
||||
let returnListenersAttached = false;
|
||||
|
||||
const getIndicatorPrefix = () => `${COMPLETION_TITLE_INDICATOR} `;
|
||||
|
||||
const stripIndicator = (title: string): string => {
|
||||
const prefix = getIndicatorPrefix();
|
||||
return title.startsWith(prefix) ? title.slice(prefix.length) : title;
|
||||
};
|
||||
|
||||
const pageIsActive = (): boolean => (
|
||||
document.visibilityState === 'visible' && document.hasFocus()
|
||||
);
|
||||
|
||||
const removeReturnListeners = (): void => {
|
||||
if (!returnListenersAttached || typeof window === 'undefined') {
|
||||
return;
|
||||
}
|
||||
|
||||
document.removeEventListener('visibilitychange', handleUserReturn);
|
||||
window.removeEventListener('focus', handleUserReturn, true);
|
||||
window.removeEventListener('click', handleUserReturn, true);
|
||||
returnListenersAttached = false;
|
||||
};
|
||||
|
||||
const clearTitleIndicator = (): void => {
|
||||
if (clearTimer !== null) {
|
||||
window.clearTimeout(clearTimer);
|
||||
clearTimer = null;
|
||||
}
|
||||
|
||||
removeReturnListeners();
|
||||
|
||||
if (document.title.startsWith(getIndicatorPrefix())) {
|
||||
document.title = stripIndicator(document.title);
|
||||
}
|
||||
};
|
||||
|
||||
const scheduleClear = (): void => {
|
||||
if (clearTimer !== null) {
|
||||
window.clearTimeout(clearTimer);
|
||||
}
|
||||
|
||||
clearTimer = window.setTimeout(() => {
|
||||
clearTitleIndicator();
|
||||
}, TITLE_INDICATOR_CLEAR_DELAY_MS);
|
||||
};
|
||||
|
||||
function handleUserReturn(): void {
|
||||
if (!pageIsActive()) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Background completions keep the marker indefinitely. A tab click normally
|
||||
// surfaces as visibility/focus, while an in-page click is a useful fallback.
|
||||
scheduleClear();
|
||||
}
|
||||
|
||||
export const showCompletionTitleIndicator = (): void => {
|
||||
if (typeof document === 'undefined' || typeof window === 'undefined') {
|
||||
return;
|
||||
}
|
||||
|
||||
const baseTitle = stripIndicator(document.title || 'CloudCLI UI');
|
||||
document.title = `${getIndicatorPrefix()}${baseTitle}`;
|
||||
|
||||
if (pageIsActive()) {
|
||||
scheduleClear();
|
||||
return;
|
||||
}
|
||||
|
||||
if (clearTimer !== null) {
|
||||
window.clearTimeout(clearTimer);
|
||||
clearTimer = null;
|
||||
}
|
||||
|
||||
if (!returnListenersAttached) {
|
||||
document.addEventListener('visibilitychange', handleUserReturn);
|
||||
window.addEventListener('focus', handleUserReturn, true);
|
||||
window.addEventListener('click', handleUserReturn, true);
|
||||
returnListenersAttached = true;
|
||||
}
|
||||
};
|
||||
Reference in New Issue
Block a user