feat: improve toast UI, add-modal cookie handling, and completion sounds

- Refine toast animations and durations
- Prevent extension-captured cookies from being sent across cross-origin redirects
- Clear stale extension metadata properly for single-link handoffs
- Disable completion sound by default and update settings labels
- Handle AudioContext suspension for completion chimes
This commit is contained in:
NimBold
2026-07-04 05:32:40 +03:30
parent 84a4ff4bfc
commit 4a322196de
7 changed files with 162 additions and 80 deletions
+7 -5
View File
@@ -44,13 +44,17 @@ const getScheduledQueueIds = () => {
type AudioContextConstructor = typeof AudioContext;
const playCompletionChime = () => {
const playCompletionChime = async () => {
const AudioCtor =
window.AudioContext ||
(window as Window & { webkitAudioContext?: AudioContextConstructor }).webkitAudioContext;
if (!AudioCtor) return;
const context = new AudioCtor();
if (context.state === 'suspended') {
await context.resume();
}
const oscillator = context.createOscillator();
const gain = context.createGain();
oscillator.type = 'sine';
@@ -551,11 +555,9 @@ function App() {
if (event.payload.status !== 'completed' && event.payload.status !== 'failed') return;
const settings = useSettingsStore.getState();
if (event.payload.status === 'completed' && settings.playCompletionSound) {
try {
playCompletionChime();
} catch (error) {
playCompletionChime().catch(error => {
console.error('Completion sound failed:', error);
}
});
}
if (!settings.showNotifications) return;
+29 -2
View File
@@ -37,6 +37,16 @@ const formatBytes = (bytes: number) => {
return parseFloat((bytes / Math.pow(k, i)).toFixed(1)) + ' ' + sizes[i];
};
const isCrossHostRedirect = (sourceUrl: string, downloadUrl: string) => {
try {
const sourceHost = new URL(sourceUrl).hostname;
const downloadHost = new URL(downloadUrl).hostname;
return downloadHost !== sourceHost && !downloadHost.endsWith(`.${sourceHost}`);
} catch {
return false;
}
};
export const AddDownloadsModal = () => {
const { addToast } = useToast();
const {
@@ -85,6 +95,7 @@ export const AddDownloadsModal = () => {
const [checksumValue, setChecksumValue] = useState('');
const [headers, setHeaders] = useState('');
const [cookies, setCookies] = useState('');
const cookiesFromExtensionRef = useRef(false);
const [mirrors, setMirrors] = useState('');
useEffect(() => {
@@ -111,6 +122,7 @@ export const AddDownloadsModal = () => {
pendingAddHeaders
].filter(Boolean).join('\n'));
setCookies(pendingAddCookies);
cookiesFromExtensionRef.current = Boolean(pendingAddCookies?.trim());
setMirrors('');
setIsQueueMenuOpen(false);
setIsSubmitting(false);
@@ -251,6 +263,11 @@ export const AddDownloadsModal = () => {
headers: headers?.trim() || null,
cookies: cookies?.trim() || null
});
const nextDownloadUrl = meta.url || row.sourceUrl;
if (cookiesFromExtensionRef.current && isCrossHostRedirect(row.sourceUrl, nextDownloadUrl)) {
setCookies('');
cookiesFromExtensionRef.current = false;
}
setParsedItems(current => updateRowIfCurrent(
current,
row.id,
@@ -258,7 +275,7 @@ export const AddDownloadsModal = () => {
row.generation,
currentRow => ({
...currentRow,
downloadUrl: meta.url || currentRow.downloadUrl,
downloadUrl: nextDownloadUrl || currentRow.downloadUrl,
file: canonicalizeDownloadFileName(
current.length === 1 && pendingAddFilename
? pendingAddFilename
@@ -1008,7 +1025,17 @@ export const AddDownloadsModal = () => {
</div>
<div>
<label className="block text-[10px] uppercase font-bold tracking-wider text-text-muted mb-1">Cookies</label>
<input type="text" value={cookies} onChange={e=>setCookies(e.target.value)} placeholder="name=value; other=value" className="add-download-control w-full px-3 py-1.5 text-xs font-mono" aria-label="Cookies" />
<input
type="text"
value={cookies}
onChange={e => {
cookiesFromExtensionRef.current = false;
setCookies(e.target.value);
}}
placeholder="name=value; other=value"
className="add-download-control w-full px-3 py-1.5 text-xs font-mono"
aria-label="Cookies"
/>
</div>
<div>
<label className="block text-[10px] uppercase font-bold tracking-wider text-text-muted mb-1">Mirrors</label>
+6 -3
View File
@@ -639,8 +639,8 @@ runEngineChecks(false);
<div className="mac-settings-group">
<label className="mac-settings-row cursor-default">
<div className="settings-row-label">
<span>Show notification when download completes</span>
<small>Alerts you in Notification Center</small>
<span>Show system notification when download completes</span>
<small>Uses your operating system notification settings</small>
</div>
<input
type="checkbox"
@@ -650,7 +650,10 @@ runEngineChecks(false);
/>
</label>
<label className="mac-settings-row cursor-default">
<span className="text-[13px] text-text-primary">Play sound when download completes</span>
<div className="settings-row-label">
<span>Play in-app completion chime</span>
<small>Optional Firelink sound, independent of system notifications</small>
</div>
<input
type="checkbox"
checked={settings.playCompletionSound}
+88 -65
View File
@@ -3,6 +3,11 @@ import { CheckCircle2, AlertCircle, Info, XCircle, X } from 'lucide-react';
export type ToastVariant = 'success' | 'info' | 'warning' | 'error';
const MAX_VISIBLE_TOASTS = 4;
const DEFAULT_TOAST_DURATION_MS = 7000;
const ERROR_TOAST_DURATION_MS = 10000;
const TOAST_EXIT_DURATION_MS = 220;
export interface ToastMessage {
id: string;
message: React.ReactNode;
@@ -28,7 +33,10 @@ export const ToastProvider: React.FC<{ children: ReactNode }> = ({ children }) =
const addToast = useCallback((toast: Omit<ToastMessage, 'id'>) => {
nextToastId.current += 1;
setToasts(prev => [...prev, { ...toast, id: `toast-${nextToastId.current}` }]);
setToasts(prev => {
const next = [...prev, { ...toast, id: `toast-${nextToastId.current}` }];
return next.slice(-MAX_VISIBLE_TOASTS);
});
}, []);
const removeToast = useCallback((id: string) => {
@@ -60,64 +68,67 @@ export const useToast = () => {
const ToastItem: React.FC<{ toast: ToastState; removeToast: (id: string) => void; removeToastCompletely: (id: string) => void }> = ({ toast, removeToast, removeToastCompletely }) => {
const [isMounted, setIsMounted] = useState(false);
const [isHovered, setIsHovered] = useState(false);
const elementRef = useRef<HTMLDivElement>(null);
const [contentHeight, setContentHeight] = useState<number | undefined>(undefined);
const timerStartedAt = useRef<number | null>(null);
const remainingDuration = useRef<number | null>(null);
useLayoutEffect(() => {
if (elementRef.current && !isMounted) {
// Measure natural height of the toast
setContentHeight(elementRef.current.offsetHeight);
let frame2: number;
const frame1 = requestAnimationFrame(() => {
frame2 = requestAnimationFrame(() => setIsMounted(true));
});
return () => {
cancelAnimationFrame(frame1);
if (frame2) cancelAnimationFrame(frame2);
};
}
}, [isMounted]);
const frame = requestAnimationFrame(() => setIsMounted(true));
return () => cancelAnimationFrame(frame);
}, []);
useEffect(() => {
// 1. If exiting, don't trigger the auto-dismiss timer
if (toast.exiting) return;
if (remainingDuration.current === null) {
remainingDuration.current = getToastDuration(toast);
}
// Explicitly treat a duration of 0 as a permanent toast
if (toast.duration === 0 || toast.isActionable || (toast.variant === 'error' && !toast.duration)) {
return;
}
let timeoutDuration = toast.duration ?? 3000;
if (isHovered) {
if (toast.exiting || isHovered || remainingDuration.current === null) {
return;
}
timerStartedAt.current = Date.now();
const timer = setTimeout(() => {
removeToast(toast.id);
}, timeoutDuration);
}, remainingDuration.current);
return () => clearTimeout(timer);
return () => {
clearTimeout(timer);
if (timerStartedAt.current !== null && remainingDuration.current !== null) {
remainingDuration.current = Math.max(0, remainingDuration.current - (Date.now() - timerStartedAt.current));
timerStartedAt.current = null;
}
};
}, [toast, isHovered, removeToast]);
// Fallback safety timer just in case browser drops onTransitionEnd
useEffect(() => {
if (toast.exiting) {
const fallbackTimer = setTimeout(() => {
removeToastCompletely(toast.id);
}, 500);
}, TOAST_EXIT_DURATION_MS + 100);
return () => clearTimeout(fallbackTimer);
}
}, [toast.exiting, toast.id, removeToastCompletely]);
const role = toast.variant === 'error' ? 'alert' : 'status';
const variant = toast.variant || 'info';
const role = variant === 'info' ? 'status' : 'alert';
const ariaLive = variant === 'info' ? 'polite' : 'assertive';
const variantStyles = {
success: 'border-emerald-500/30 bg-emerald-500/10 text-emerald-600 dark:text-emerald-400 shadow-emerald-500/10',
info: 'border-blue-500/30 bg-blue-500/10 text-blue-600 dark:text-blue-400 shadow-blue-500/10',
warning: 'border-amber-500/30 bg-amber-500/10 text-amber-600 dark:text-amber-400 shadow-amber-500/10',
error: 'border-red-500/30 bg-red-500/10 text-red-600 dark:text-red-400 shadow-red-500/10',
success: {
accent: 'bg-emerald-500',
icon: 'text-emerald-500',
},
info: {
accent: 'bg-blue-500',
icon: 'text-blue-500',
},
warning: {
accent: 'bg-amber-500',
icon: 'text-amber-500',
},
error: {
accent: 'bg-red-500',
icon: 'text-red-500',
},
};
const icons = {
@@ -127,57 +138,69 @@ const ToastItem: React.FC<{ toast: ToastState; removeToast: (id: string) => void
info: <Info className="w-5 h-5 shrink-0" strokeWidth={2.5} />,
};
const variant = toast.variant || 'info';
const style = variantStyles[variant];
const Icon = icons[variant];
const isVisible = isMounted && !toast.exiting;
const transitionTiming = isVisible
? '220ms cubic-bezier(0.16, 1, 0.3, 1)'
: `${TOAST_EXIT_DURATION_MS}ms cubic-bezier(0.4, 0, 1, 1)`;
return (
<div
className={`w-full overflow-hidden transition-all duration-300 ease-[cubic-bezier(0.16,1,0.3,1)] flex flex-col justify-end ${isVisible ? 'mb-3' : 'mb-0'}`}
className="grid w-full overflow-hidden"
style={{
height: isVisible && contentHeight !== undefined ? contentHeight : 0,
gridTemplateRows: isVisible ? '1fr' : '0fr',
marginBottom: isVisible ? 12 : 0,
transition: `grid-template-rows ${transitionTiming}, margin-bottom ${transitionTiming}`,
}}
onTransitionEnd={(e) => {
// 2. Rely on height transition end to safely unmount, instead of hardcoded fixed setTimeouts
if (toast.exiting && e.target === e.currentTarget && e.propertyName === 'height') {
if (toast.exiting && e.target === e.currentTarget && e.propertyName === 'grid-template-rows') {
removeToastCompletely(toast.id);
}
}}
>
<div
ref={elementRef}
role={role}
className={`app-toast-item shrink-0 ${isVisible ? 'pointer-events-auto' : 'pointer-events-none'} flex items-start gap-3 rounded-[16px] border px-4 py-3 shadow-[0_8px_30px_rgb(0,0,0,0.12),0_0_20px_var(--tw-shadow-color)] backdrop-blur-xl text-[14px] leading-relaxed transition-all duration-300 ease-[cubic-bezier(0.16,1,0.3,1)] ${style}`}
style={{
opacity: isVisible ? 1 : 0,
transform: isVisible ? 'translateY(0) scale(1)' : 'scale(0.95)',
transformOrigin: 'bottom center',
}}
onMouseEnter={() => setIsHovered(true)}
onMouseLeave={() => setIsHovered(false)}
onFocus={() => setIsHovered(true)}
onBlur={() => setIsHovered(false)}
>
<div className="mt-0.5 shrink-0">{Icon}</div>
<div className="font-semibold flex-1 tracking-tight break-all whitespace-pre-wrap">{toast.message}</div>
<button
onClick={() => removeToast(toast.id)}
className="shrink-0 ml-2 mt-0.5 opacity-60 hover:opacity-100 hover:bg-black/5 dark:hover:bg-white/10 p-1 rounded-full transition-all active:scale-90"
aria-label="Dismiss notification"
<div className="min-h-0 overflow-hidden">
<div
role={role}
aria-live={ariaLive}
className={`app-toast-item relative ${isVisible ? 'pointer-events-auto' : 'pointer-events-none'} flex w-full min-w-0 items-start gap-3 overflow-hidden rounded-lg border border-border-color bg-surface-overlay px-4 py-3 text-[14px] leading-relaxed text-text-primary shadow-[0_18px_50px_rgba(0,0,0,0.22)] backdrop-blur-xl`}
style={{
opacity: isVisible ? 1 : 0,
transform: isVisible ? 'translateY(0) scale(1)' : 'translateY(8px) scale(0.985)',
transformOrigin: 'bottom right',
transition: `opacity ${transitionTiming}, transform ${transitionTiming}, box-shadow ${transitionTiming}`,
}}
onMouseEnter={() => setIsHovered(true)}
onMouseLeave={() => setIsHovered(false)}
onFocus={() => setIsHovered(true)}
onBlur={() => setIsHovered(false)}
>
<X className="w-4 h-4" strokeWidth={2.5} />
</button>
<div className={`absolute inset-y-0 left-0 w-1 ${style.accent}`} />
<div className={`mt-0.5 shrink-0 ${style.icon}`}>{Icon}</div>
<div className="min-w-0 flex-1 break-words font-medium tracking-normal text-text-primary">{toast.message}</div>
<button
onClick={() => removeToast(toast.id)}
className="ml-2 mt-0.5 shrink-0 rounded-md p-1 text-text-secondary opacity-70 transition-all hover:bg-item-hover hover:text-text-primary hover:opacity-100 active:scale-95"
aria-label="Dismiss notification"
>
<X className="w-4 h-4" strokeWidth={2.5} />
</button>
</div>
</div>
</div>
);
};
const getToastDuration = (toast: ToastState): number | null => {
if (toast.duration === 0 || toast.isActionable) return null;
if (typeof toast.duration === 'number') return Math.max(0, toast.duration);
return toast.variant === 'error' ? ERROR_TOAST_DURATION_MS : DEFAULT_TOAST_DURATION_MS;
};
const ToastContainer: React.FC<{ toasts: ToastState[]; removeToast: (id: string) => void; removeToastCompletely: (id: string) => void }> = ({ toasts, removeToast, removeToastCompletely }) => {
return (
// 3. Removed 'gap-3' to allow the dynamic mb-3 from the wrapper to handle spacing, allowing it to smoothly collapse
<div className="fixed bottom-8 left-1/2 -translate-x-1/2 z-[100] flex w-full max-w-[420px] flex-col pointer-events-none items-center px-4">
<div className="fixed bottom-8 left-4 right-4 z-[100] flex flex-col items-end pointer-events-none sm:left-auto sm:right-6 sm:w-full sm:max-w-[420px]">
{toasts.map(toast => (
<ToastItem key={toast.id} toast={toast} removeToast={removeToast} removeToastCompletely={removeToastCompletely} />
))}
+27
View File
@@ -439,6 +439,33 @@ describe('useDownloadStore', () => {
expect(state.pendingAddCookies).toBe('session=secret');
});
it('does not reuse stale extension metadata for a later single-link handoff', async () => {
useDownloadStore.setState({
isAddModalOpen: true,
pendingAddUrls: '',
pendingAddReferer: 'https://old.example/page',
pendingAddFilename: '7aae36e6-00ec-4e7d-8dec-f14ace170bdb',
pendingAddHeaders: 'X-Old: value',
pendingAddCookies: 'old=session'
});
await useDownloadStore.getState().handleExtensionDownload({
urls: ['https://github.com/center2055/OnionHop/releases/download/v3.5/OnionHop-3.5-macOS-arm64.dmg'],
referer: 'https://github.com/center2055/OnionHop/releases/tag/v3.5',
silent: false,
filename: null,
headers: 'User-Agent: Firefox Test',
cookies: null
});
const state = useDownloadStore.getState();
expect(state.pendingAddUrls).toBe('https://github.com/center2055/OnionHop/releases/download/v3.5/OnionHop-3.5-macOS-arm64.dmg');
expect(state.pendingAddReferer).toBe('https://github.com/center2055/OnionHop/releases/tag/v3.5');
expect(state.pendingAddFilename).toBe('');
expect(state.pendingAddHeaders).toBe('User-Agent: Firefox Test');
expect(state.pendingAddCookies).toBe('');
});
it('routes silent extension captures to the Add Modal instead of queuing immediately', async () => {
await useDownloadStore.getState().handleExtensionDownload({
urls: ['https://example.com/downloads/report.pdf'],
+4 -4
View File
@@ -398,10 +398,10 @@ export const useDownloadStore = create<DownloadState>((set, get) => ({
return {
isAddModalOpen: true,
pendingAddUrls: mergedUrls,
pendingAddReferer: referer?.trim() || state.pendingAddReferer || '',
pendingAddFilename: filename?.trim() || state.pendingAddFilename || '',
pendingAddHeaders: headers?.trim() || state.pendingAddHeaders || '',
pendingAddCookies: cookies?.trim() || state.pendingAddCookies || ''
pendingAddReferer: referer?.trim() || '',
pendingAddFilename: filename?.trim() || '',
pendingAddHeaders: headers?.trim() || '',
pendingAddCookies: cookies?.trim() || ''
};
}),
handleExtensionDownload: async (request) => {
+1 -1
View File
@@ -217,7 +217,7 @@ export const useSettingsStore = create<SettingsState>()(
perServerConnections: 16,
maxAutomaticRetries: 3,
showNotifications: true,
playCompletionSound: true,
playCompletionSound: false,
appFontSize: 'standard',
listRowDensity: 'standard',
showDockBadge: true,