lint
This commit is contained in:
977 files changed
+198426
-158324
No files matched your search
@@ -1,63 +1,60 @@
|
||||
import {
|
||||
createContext,
|
||||
useCallback,
|
||||
useContext,
|
||||
useEffect,
|
||||
useMemo,
|
||||
useRef,
|
||||
useState,
|
||||
type ReactNode,
|
||||
createContext,
|
||||
useCallback,
|
||||
useContext,
|
||||
useEffect,
|
||||
useMemo,
|
||||
useRef,
|
||||
useState,
|
||||
type ReactNode,
|
||||
} from 'react';
|
||||
import { CircleAlert, CircleCheck } from 'lucide-react';
|
||||
import { motion } from 'motion/react';
|
||||
import { CollapsibleBanner, type BannerState } from '@/components/interior/collapsible-banner';
|
||||
import {
|
||||
CollapsibleBanner,
|
||||
type BannerState,
|
||||
} from '@/components/interior/collapsible-banner';
|
||||
import {
|
||||
LiveActivity,
|
||||
useLiveActivity,
|
||||
type ActivityInput,
|
||||
LiveActivity,
|
||||
useLiveActivity,
|
||||
type ActivityInput,
|
||||
} from '@/components/interior/live-activity';
|
||||
|
||||
type ResultDetail<T> = string | ((result: T) => string | undefined);
|
||||
type ErrorDetail = string | ((error: unknown) => string);
|
||||
|
||||
export interface ActionFeedbackOptions<T = void> extends ActivityInput {
|
||||
successTitle?: string;
|
||||
successDetail?: ResultDetail<T>;
|
||||
errorTitle?: string;
|
||||
errorDetail?: ErrorDetail;
|
||||
/** Re-show a successful result after an imminent full-page reload. */
|
||||
surviveReload?: boolean;
|
||||
/**
|
||||
* Some APIs resolve transport-successfully while reporting a failed domain
|
||||
* result. Return its user-facing reason here so the activity ends in error
|
||||
* without changing the caller's result/control flow.
|
||||
*/
|
||||
resultError?: (result: T) => string | null | undefined;
|
||||
successTitle?: string;
|
||||
successDetail?: ResultDetail<T>;
|
||||
errorTitle?: string;
|
||||
errorDetail?: ErrorDetail;
|
||||
/** Re-show a successful result after an imminent full-page reload. */
|
||||
surviveReload?: boolean;
|
||||
/**
|
||||
* Some APIs resolve transport-successfully while reporting a failed domain
|
||||
* result. Return its user-facing reason here so the activity ends in error
|
||||
* without changing the caller's result/control flow.
|
||||
*/
|
||||
resultError?: (result: T) => string | null | undefined;
|
||||
}
|
||||
|
||||
export interface ActionFeedbackHandle {
|
||||
update: (patch: Partial<ActivityInput>) => void;
|
||||
succeed: (patch?: Partial<ActivityInput>) => void;
|
||||
fail: (detail: string, patch?: Partial<ActivityInput>) => void;
|
||||
update: (patch: Partial<ActivityInput>) => void;
|
||||
succeed: (patch?: Partial<ActivityInput>) => void;
|
||||
fail: (detail: string, patch?: Partial<ActivityInput>) => void;
|
||||
}
|
||||
|
||||
interface ActionFeedbackValue {
|
||||
startAction: (input: ActivityInput) => ActionFeedbackHandle;
|
||||
runAction: <T>(options: ActionFeedbackOptions<T>, action: () => Promise<T> | T) => Promise<T>;
|
||||
activity: ReturnType<typeof useLiveActivity>['activity'];
|
||||
notices: ActionNotice[];
|
||||
removeNotice: (id: number) => void;
|
||||
dismiss: () => void;
|
||||
startAction: (input: ActivityInput) => ActionFeedbackHandle;
|
||||
runAction: <T>(options: ActionFeedbackOptions<T>, action: () => Promise<T> | T) => Promise<T>;
|
||||
activity: ReturnType<typeof useLiveActivity>['activity'];
|
||||
notices: ActionNotice[];
|
||||
removeNotice: (id: number) => void;
|
||||
dismiss: () => void;
|
||||
}
|
||||
|
||||
interface ActionNotice {
|
||||
id: number;
|
||||
tone: 'success' | 'error';
|
||||
title: string;
|
||||
detail?: string;
|
||||
id: number;
|
||||
tone: 'success' | 'error';
|
||||
title: string;
|
||||
detail?: string;
|
||||
}
|
||||
|
||||
const ActionFeedbackContext = createContext<ActionFeedbackValue | null>(null);
|
||||
@@ -66,196 +63,227 @@ const RELOAD_NOTICE_MAX_AGE_MS = 30_000;
|
||||
const RELOAD_NOTICE_KEY = 'snowluma_action_feedback_reload_notice';
|
||||
|
||||
interface ReloadNotice extends Omit<ActionNotice, 'id'> {
|
||||
createdAt: number;
|
||||
createdAt: number;
|
||||
}
|
||||
|
||||
function preserveReloadNotice(notice: Omit<ActionNotice, 'id'>): void {
|
||||
try {
|
||||
sessionStorage.setItem(
|
||||
RELOAD_NOTICE_KEY,
|
||||
JSON.stringify({ ...notice, createdAt: Date.now() } satisfies ReloadNotice),
|
||||
);
|
||||
} catch (error) {
|
||||
console.error('preserve action feedback across reload failed', error);
|
||||
}
|
||||
try {
|
||||
sessionStorage.setItem(
|
||||
RELOAD_NOTICE_KEY,
|
||||
JSON.stringify({ ...notice, createdAt: Date.now() } satisfies ReloadNotice),
|
||||
);
|
||||
} catch (error) {
|
||||
console.error('preserve action feedback across reload failed', error);
|
||||
}
|
||||
}
|
||||
|
||||
function takeReloadNotice(): Omit<ActionNotice, 'id'> | null {
|
||||
let raw: string | null;
|
||||
try {
|
||||
raw = sessionStorage.getItem(RELOAD_NOTICE_KEY);
|
||||
sessionStorage.removeItem(RELOAD_NOTICE_KEY);
|
||||
} catch (error) {
|
||||
console.error('read action feedback after reload failed', error);
|
||||
return null;
|
||||
}
|
||||
if (!raw) return null;
|
||||
try {
|
||||
const parsed = JSON.parse(raw) as Partial<ReloadNotice>;
|
||||
if (
|
||||
(parsed.tone !== 'success' && parsed.tone !== 'error')
|
||||
|| typeof parsed.title !== 'string'
|
||||
|| typeof parsed.createdAt !== 'number'
|
||||
|| Date.now() - parsed.createdAt > RELOAD_NOTICE_MAX_AGE_MS
|
||||
) {
|
||||
throw new Error('invalid or expired reload notice');
|
||||
let raw: string | null;
|
||||
|
||||
try {
|
||||
raw = sessionStorage.getItem(RELOAD_NOTICE_KEY);
|
||||
sessionStorage.removeItem(RELOAD_NOTICE_KEY);
|
||||
} catch (error) {
|
||||
console.error('read action feedback after reload failed', error);
|
||||
return null;
|
||||
}
|
||||
|
||||
if (!raw) {
|
||||
return null;
|
||||
}
|
||||
|
||||
try {
|
||||
const parsed = JSON.parse(raw) as Partial<ReloadNotice>;
|
||||
|
||||
if (
|
||||
(parsed.tone !== 'success' && parsed.tone !== 'error') ||
|
||||
typeof parsed.title !== 'string' ||
|
||||
typeof parsed.createdAt !== 'number' ||
|
||||
Date.now() - parsed.createdAt > RELOAD_NOTICE_MAX_AGE_MS
|
||||
) {
|
||||
throw new Error('invalid or expired reload notice');
|
||||
}
|
||||
|
||||
return {
|
||||
tone: parsed.tone,
|
||||
title: parsed.title,
|
||||
...(typeof parsed.detail === 'string' ? { detail: parsed.detail } : {}),
|
||||
};
|
||||
} catch (error) {
|
||||
console.error('parse action feedback after reload failed', error);
|
||||
return null;
|
||||
}
|
||||
return {
|
||||
tone: parsed.tone,
|
||||
title: parsed.title,
|
||||
...(typeof parsed.detail === 'string' ? { detail: parsed.detail } : {}),
|
||||
};
|
||||
} catch (error) {
|
||||
console.error('parse action feedback after reload failed', error);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export function actionErrorMessage(error: unknown): string {
|
||||
if (error instanceof Error && error.message.trim()) return error.message;
|
||||
if (typeof error === 'string' && error.trim()) return error;
|
||||
return '未知错误';
|
||||
if (error instanceof Error && error.message.trim()) {
|
||||
return error.message;
|
||||
}
|
||||
|
||||
if (typeof error === 'string' && error.trim()) {
|
||||
return error;
|
||||
}
|
||||
|
||||
return '未知错误';
|
||||
}
|
||||
|
||||
function resolveResultDetail<T>(detail: ResultDetail<T> | undefined, result: T): string | undefined {
|
||||
return typeof detail === 'function' ? detail(result) : detail;
|
||||
function resolveResultDetail<T>(
|
||||
detail: ResultDetail<T> | undefined,
|
||||
result: T,
|
||||
): string | undefined {
|
||||
return typeof detail === 'function' ? detail(result) : detail;
|
||||
}
|
||||
|
||||
function resolveErrorDetail(detail: ErrorDetail | undefined, error: unknown): string {
|
||||
if (typeof detail === 'function') return detail(error);
|
||||
return detail ?? actionErrorMessage(error);
|
||||
if (typeof detail === 'function') {
|
||||
return detail(error);
|
||||
}
|
||||
|
||||
return detail ?? actionErrorMessage(error);
|
||||
}
|
||||
|
||||
export function publishActionResult(
|
||||
ownsSurface: boolean,
|
||||
updateCurrentActivity: () => void,
|
||||
publishNotice: () => void,
|
||||
ownsSurface: boolean,
|
||||
updateCurrentActivity: () => void,
|
||||
publishNotice: () => void,
|
||||
): void {
|
||||
if (ownsSurface) updateCurrentActivity();
|
||||
publishNotice();
|
||||
if (ownsSurface) {
|
||||
updateCurrentActivity();
|
||||
}
|
||||
|
||||
publishNotice();
|
||||
}
|
||||
|
||||
export function scheduleActionNoticeDismiss(onDismiss: () => void): () => void {
|
||||
const timeout = setTimeout(onDismiss, RESULT_NOTICE_DURATION_MS);
|
||||
return () => clearTimeout(timeout);
|
||||
const timeout = setTimeout(onDismiss, RESULT_NOTICE_DURATION_MS);
|
||||
return () => clearTimeout(timeout);
|
||||
}
|
||||
|
||||
export function ActionFeedbackProvider({ children }: { children: ReactNode }) {
|
||||
const {
|
||||
activity,
|
||||
start,
|
||||
update,
|
||||
succeed,
|
||||
fail,
|
||||
dismiss: dismissActivity,
|
||||
} = useLiveActivity();
|
||||
const activeId = useRef<string | null>(null);
|
||||
const noticeId = useRef(0);
|
||||
const [notices, setNotices] = useState<ActionNotice[]>([]);
|
||||
const { activity, start, update, succeed, fail, dismiss: dismissActivity } = useLiveActivity();
|
||||
const activeId = useRef<string | null>(null);
|
||||
const noticeId = useRef(0);
|
||||
const [notices, setNotices] = useState<ActionNotice[]>([]);
|
||||
|
||||
const pushNotice = useCallback((notice: Omit<ActionNotice, 'id'>) => {
|
||||
const next = { ...notice, id: ++noticeId.current };
|
||||
setNotices((current) => [...current.slice(-2), next]);
|
||||
}, []);
|
||||
const pushNotice = useCallback((notice: Omit<ActionNotice, 'id'>) => {
|
||||
const next = { ...notice, id: ++noticeId.current };
|
||||
setNotices((current) => [...current.slice(-2), next]);
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
const notice = takeReloadNotice();
|
||||
if (notice) pushNotice(notice);
|
||||
}, [pushNotice]);
|
||||
useEffect(() => {
|
||||
const notice = takeReloadNotice();
|
||||
|
||||
const startAction = useCallback((input: ActivityInput): ActionFeedbackHandle => {
|
||||
const id = start(input);
|
||||
activeId.current = id;
|
||||
const ownsSurface = () => activeId.current === id;
|
||||
|
||||
return {
|
||||
update: (patch) => {
|
||||
if (ownsSurface()) update(patch);
|
||||
},
|
||||
succeed: (patch) => {
|
||||
publishActionResult(
|
||||
ownsSurface(),
|
||||
() => succeed(patch),
|
||||
() => pushNotice({
|
||||
tone: 'success',
|
||||
title: patch?.title ?? input.title,
|
||||
detail: patch?.detail ?? input.detail,
|
||||
}),
|
||||
);
|
||||
},
|
||||
fail: (detail, patch) => {
|
||||
publishActionResult(
|
||||
ownsSurface(),
|
||||
() => fail({ ...patch, detail }),
|
||||
() => pushNotice({
|
||||
tone: 'error',
|
||||
title: patch?.title ?? input.title,
|
||||
detail,
|
||||
}),
|
||||
);
|
||||
},
|
||||
};
|
||||
}, [start, update, succeed, fail, pushNotice]);
|
||||
|
||||
const runAction = useCallback(async <T,>(
|
||||
options: ActionFeedbackOptions<T>,
|
||||
action: () => Promise<T> | T,
|
||||
): Promise<T> => {
|
||||
const {
|
||||
successTitle,
|
||||
successDetail,
|
||||
errorTitle,
|
||||
errorDetail,
|
||||
resultError,
|
||||
surviveReload,
|
||||
...input
|
||||
} = options;
|
||||
const handle = startAction(input);
|
||||
try {
|
||||
const result = await action();
|
||||
const failed = resultError?.(result);
|
||||
if (failed) {
|
||||
handle.fail(failed, errorTitle ? { title: errorTitle } : undefined);
|
||||
} else {
|
||||
const detail = resolveResultDetail(successDetail, result);
|
||||
if (surviveReload) {
|
||||
preserveReloadNotice({
|
||||
tone: 'success',
|
||||
title: successTitle ?? input.title,
|
||||
detail: detail ?? input.detail,
|
||||
});
|
||||
if (notice) {
|
||||
pushNotice(notice);
|
||||
}
|
||||
handle.succeed({
|
||||
...(successTitle ? { title: successTitle } : {}),
|
||||
...(detail !== undefined ? { detail } : {}),
|
||||
});
|
||||
}
|
||||
return result;
|
||||
} catch (error) {
|
||||
handle.fail(resolveErrorDetail(errorDetail, error), errorTitle ? { title: errorTitle } : undefined);
|
||||
throw error;
|
||||
}
|
||||
}, [startAction]);
|
||||
}, [pushNotice]);
|
||||
|
||||
const dismiss = useCallback(() => {
|
||||
activeId.current = null;
|
||||
dismissActivity();
|
||||
}, [dismissActivity]);
|
||||
const startAction = useCallback(
|
||||
(input: ActivityInput): ActionFeedbackHandle => {
|
||||
const id = start(input);
|
||||
activeId.current = id;
|
||||
const ownsSurface = () => activeId.current === id;
|
||||
|
||||
const removeNotice = useCallback((id: number) => {
|
||||
setNotices((current) => current.filter((notice) => notice.id !== id));
|
||||
}, []);
|
||||
return {
|
||||
update: (patch) => {
|
||||
if (ownsSurface()) {
|
||||
update(patch);
|
||||
}
|
||||
},
|
||||
succeed: (patch) => {
|
||||
publishActionResult(
|
||||
ownsSurface(),
|
||||
() => succeed(patch),
|
||||
() =>
|
||||
pushNotice({
|
||||
tone: 'success',
|
||||
title: patch?.title ?? input.title,
|
||||
detail: patch?.detail ?? input.detail,
|
||||
}),
|
||||
);
|
||||
},
|
||||
fail: (detail, patch) => {
|
||||
publishActionResult(
|
||||
ownsSurface(),
|
||||
() => fail({ ...patch, detail }),
|
||||
() =>
|
||||
pushNotice({
|
||||
tone: 'error',
|
||||
title: patch?.title ?? input.title,
|
||||
detail,
|
||||
}),
|
||||
);
|
||||
},
|
||||
};
|
||||
},
|
||||
[start, update, succeed, fail, pushNotice],
|
||||
);
|
||||
|
||||
const value = useMemo<ActionFeedbackValue>(
|
||||
() => ({ startAction, runAction, activity, notices, removeNotice, dismiss }),
|
||||
[startAction, runAction, activity, notices, removeNotice, dismiss],
|
||||
);
|
||||
const runAction = useCallback(
|
||||
async <T,>(options: ActionFeedbackOptions<T>, action: () => Promise<T> | T): Promise<T> => {
|
||||
const {
|
||||
successTitle,
|
||||
successDetail,
|
||||
errorTitle,
|
||||
errorDetail,
|
||||
resultError,
|
||||
surviveReload,
|
||||
...input
|
||||
} = options;
|
||||
const handle = startAction(input);
|
||||
|
||||
return (
|
||||
<ActionFeedbackContext.Provider value={value}>
|
||||
{children}
|
||||
</ActionFeedbackContext.Provider>
|
||||
);
|
||||
try {
|
||||
const result = await action();
|
||||
const failed = resultError?.(result);
|
||||
|
||||
if (failed) {
|
||||
handle.fail(failed, errorTitle ? { title: errorTitle } : undefined);
|
||||
} else {
|
||||
const detail = resolveResultDetail(successDetail, result);
|
||||
|
||||
if (surviveReload) {
|
||||
preserveReloadNotice({
|
||||
tone: 'success',
|
||||
title: successTitle ?? input.title,
|
||||
detail: detail ?? input.detail,
|
||||
});
|
||||
}
|
||||
|
||||
handle.succeed({
|
||||
...(successTitle ? { title: successTitle } : {}),
|
||||
...(detail !== undefined ? { detail } : {}),
|
||||
});
|
||||
}
|
||||
|
||||
return result;
|
||||
} catch (error) {
|
||||
handle.fail(
|
||||
resolveErrorDetail(errorDetail, error),
|
||||
errorTitle ? { title: errorTitle } : undefined,
|
||||
);
|
||||
throw error;
|
||||
}
|
||||
},
|
||||
[startAction],
|
||||
);
|
||||
|
||||
const dismiss = useCallback(() => {
|
||||
activeId.current = null;
|
||||
dismissActivity();
|
||||
}, [dismissActivity]);
|
||||
|
||||
const removeNotice = useCallback((id: number) => {
|
||||
setNotices((current) => current.filter((notice) => notice.id !== id));
|
||||
}, []);
|
||||
|
||||
const value = useMemo<ActionFeedbackValue>(
|
||||
() => ({ startAction, runAction, activity, notices, removeNotice, dismiss }),
|
||||
[startAction, runAction, activity, notices, removeNotice, dismiss],
|
||||
);
|
||||
|
||||
return (
|
||||
<ActionFeedbackContext.Provider value={value}>{children}</ActionFeedbackContext.Provider>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -263,97 +291,108 @@ export function ActionFeedbackProvider({ children }: { children: ReactNode }) {
|
||||
* motion / disable-motion preference also reaches Interior's component.
|
||||
*/
|
||||
export function ActionFeedbackViewport() {
|
||||
const {
|
||||
activity,
|
||||
notices,
|
||||
removeNotice,
|
||||
dismiss,
|
||||
} = useActionFeedback();
|
||||
const runningActivity = activity?.phase === 'running' ? activity : null;
|
||||
const { activity, notices, removeNotice, dismiss } = useActionFeedback();
|
||||
const runningActivity = activity?.phase === 'running' ? activity : null;
|
||||
|
||||
return (
|
||||
<div
|
||||
className="pointer-events-none fixed z-[80] flex w-[min(360px,calc(100vw-2rem))] flex-col items-end gap-2"
|
||||
style={{ bottom: 'max(1rem, env(safe-area-inset-bottom))', right: 'max(1rem, env(safe-area-inset-right))' }}
|
||||
>
|
||||
{notices.map((notice) => (
|
||||
<ActionNoticeBanner
|
||||
key={notice.id}
|
||||
notice={notice}
|
||||
onRemoved={() => removeNotice(notice.id)}
|
||||
/>
|
||||
))}
|
||||
<LiveActivity
|
||||
activity={runningActivity}
|
||||
onDismiss={dismiss}
|
||||
dismissLabel="关闭操作反馈"
|
||||
label="操作反馈"
|
||||
className="w-full"
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
return (
|
||||
<div
|
||||
className="pointer-events-none fixed z-[80] flex w-[min(360px,calc(100vw-2rem))] flex-col items-end gap-2"
|
||||
style={{
|
||||
bottom: 'max(1rem, env(safe-area-inset-bottom))',
|
||||
right: 'max(1rem, env(safe-area-inset-right))',
|
||||
}}
|
||||
>
|
||||
{notices.map((notice) => (
|
||||
<ActionNoticeBanner
|
||||
key={notice.id}
|
||||
notice={notice}
|
||||
onRemoved={() => removeNotice(notice.id)}
|
||||
/>
|
||||
))}
|
||||
<LiveActivity
|
||||
activity={runningActivity}
|
||||
onDismiss={dismiss}
|
||||
dismissLabel="关闭操作反馈"
|
||||
label="操作反馈"
|
||||
className="w-full"
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function ActionNoticeBanner({
|
||||
notice,
|
||||
onRemoved,
|
||||
notice,
|
||||
onRemoved,
|
||||
}: {
|
||||
notice: ActionNotice;
|
||||
onRemoved: () => void;
|
||||
notice: ActionNotice;
|
||||
onRemoved: () => void;
|
||||
}) {
|
||||
const [state, setState] = useState<BannerState>('dismissed');
|
||||
const visible = state !== 'dismissed';
|
||||
const [state, setState] = useState<BannerState>('dismissed');
|
||||
const visible = state !== 'dismissed';
|
||||
|
||||
useEffect(() => {
|
||||
const frame = requestAnimationFrame(() => setState('open'));
|
||||
return () => cancelAnimationFrame(frame);
|
||||
}, []);
|
||||
useEffect(() => {
|
||||
const frame = requestAnimationFrame(() => setState('open'));
|
||||
return () => cancelAnimationFrame(frame);
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
if (!visible) return;
|
||||
return scheduleActionNoticeDismiss(() => setState('dismissed'));
|
||||
}, [visible]);
|
||||
useEffect(() => {
|
||||
if (!visible) {
|
||||
return;
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="pointer-events-auto relative w-full">
|
||||
<CollapsibleBanner
|
||||
state={state}
|
||||
onStateChange={setState}
|
||||
onDismissed={onRemoved}
|
||||
title={notice.title}
|
||||
description={notice.detail}
|
||||
icon={notice.tone === 'success'
|
||||
? <CircleCheck className="size-4 text-success" />
|
||||
: <CircleAlert className="size-4 text-destructive" />}
|
||||
dismissLabel="关闭通知"
|
||||
dismissedMessage="操作通知已关闭。"
|
||||
className={notice.tone === 'success'
|
||||
? 'border-success/25'
|
||||
: 'border-destructive/30'}
|
||||
/>
|
||||
{state !== 'dismissed' ? (
|
||||
<div
|
||||
aria-hidden="true"
|
||||
data-action-feedback-countdown-track=""
|
||||
className="pointer-events-none absolute inset-x-[8px] bottom-0.5 h-[3px] overflow-hidden rounded-full bg-border/45"
|
||||
>
|
||||
<motion.div
|
||||
data-action-feedback-countdown=""
|
||||
className={notice.tone === 'success'
|
||||
? 'h-full w-full origin-left rounded-full bg-success shadow-[0_0_5px_color-mix(in_oklab,var(--success)_45%,transparent)]'
|
||||
: 'h-full w-full origin-left rounded-full bg-destructive shadow-[0_0_5px_color-mix(in_oklab,var(--destructive)_45%,transparent)]'}
|
||||
initial={{ scaleX: 1 }}
|
||||
animate={{ scaleX: 0 }}
|
||||
transition={{ duration: RESULT_NOTICE_DURATION_MS / 1_000, ease: 'linear' }}
|
||||
/>
|
||||
return scheduleActionNoticeDismiss(() => setState('dismissed'));
|
||||
}, [visible]);
|
||||
|
||||
return (
|
||||
<div className="pointer-events-auto relative w-full">
|
||||
<CollapsibleBanner
|
||||
state={state}
|
||||
onStateChange={setState}
|
||||
onDismissed={onRemoved}
|
||||
title={notice.title}
|
||||
description={notice.detail}
|
||||
icon={
|
||||
notice.tone === 'success' ? (
|
||||
<CircleCheck className="size-4 text-success" />
|
||||
) : (
|
||||
<CircleAlert className="size-4 text-destructive" />
|
||||
)
|
||||
}
|
||||
dismissLabel="关闭通知"
|
||||
dismissedMessage="操作通知已关闭。"
|
||||
className={
|
||||
notice.tone === 'success' ? 'border-success/25' : 'border-destructive/30'
|
||||
}
|
||||
/>
|
||||
{state !== 'dismissed' ? (
|
||||
<div
|
||||
aria-hidden="true"
|
||||
data-action-feedback-countdown-track=""
|
||||
className="pointer-events-none absolute inset-x-[8px] bottom-0.5 h-[3px] overflow-hidden rounded-full bg-border/45"
|
||||
>
|
||||
<motion.div
|
||||
data-action-feedback-countdown=""
|
||||
className={
|
||||
notice.tone === 'success'
|
||||
? 'h-full w-full origin-left rounded-full bg-success shadow-[0_0_5px_color-mix(in_oklab,var(--success)_45%,transparent)]'
|
||||
: 'h-full w-full origin-left rounded-full bg-destructive shadow-[0_0_5px_color-mix(in_oklab,var(--destructive)_45%,transparent)]'
|
||||
}
|
||||
initial={{ scaleX: 1 }}
|
||||
animate={{ scaleX: 0 }}
|
||||
transition={{ duration: RESULT_NOTICE_DURATION_MS / 1_000, ease: 'linear' }}
|
||||
/>
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
);
|
||||
);
|
||||
}
|
||||
|
||||
export function useActionFeedback(): ActionFeedbackValue {
|
||||
const value = useContext(ActionFeedbackContext);
|
||||
if (!value) throw new Error('useActionFeedback must be used within ActionFeedbackProvider');
|
||||
return value;
|
||||
const value = useContext(ActionFeedbackContext);
|
||||
|
||||
if (!value) {
|
||||
throw new Error('useActionFeedback must be used within ActionFeedbackProvider');
|
||||
}
|
||||
|
||||
return value;
|
||||
}
|
||||
@@ -3,16 +3,16 @@ import type { AccountConnections, HookProcessInfo, QQInfo, SystemInfo, UpdateInf
|
||||
import type { HookProcessOps } from '@/hooks/use-hook-process-ops';
|
||||
|
||||
export interface ResourceLoadState {
|
||||
ready: boolean;
|
||||
error: string | null;
|
||||
ready: boolean;
|
||||
error: string | null;
|
||||
}
|
||||
|
||||
export interface AppResourceState {
|
||||
qqList: ResourceLoadState;
|
||||
processList: ResourceLoadState;
|
||||
systemInfo: ResourceLoadState;
|
||||
connections: ResourceLoadState;
|
||||
updateInfo: ResourceLoadState;
|
||||
qqList: ResourceLoadState;
|
||||
processList: ResourceLoadState;
|
||||
systemInfo: ResourceLoadState;
|
||||
connections: ResourceLoadState;
|
||||
updateInfo: ResourceLoadState;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -22,41 +22,45 @@ export interface AppResourceState {
|
||||
* not touch AppLayout.
|
||||
*/
|
||||
export interface AppStateValue {
|
||||
qqList: QQInfo[];
|
||||
processList: HookProcessInfo[];
|
||||
systemInfo: SystemInfo | null;
|
||||
connections: AccountConnections[];
|
||||
/** Advisory update-availability info; null until the first check resolves. */
|
||||
updateInfo: UpdateInfo | null;
|
||||
/** Distinguishes an empty result from an unresolved or failed initial read. */
|
||||
resources: AppResourceState;
|
||||
selectedUin: string | null;
|
||||
setSelectedUin: (uin: string | null) => void;
|
||||
processOps: HookProcessOps;
|
||||
refreshQqList: () => void;
|
||||
refreshProcesses: () => void;
|
||||
refreshSystem: () => void;
|
||||
refreshConnections: () => void;
|
||||
/** Re-run the update check; `force` bypasses the server-side cache. */
|
||||
refreshUpdate: (force?: boolean) => Promise<UpdateInfo | null>;
|
||||
/** Triggered from the topbar logout button. */
|
||||
onLogout: () => void;
|
||||
qqList: QQInfo[];
|
||||
processList: HookProcessInfo[];
|
||||
systemInfo: SystemInfo | null;
|
||||
connections: AccountConnections[];
|
||||
/** Advisory update-availability info; null until the first check resolves. */
|
||||
updateInfo: UpdateInfo | null;
|
||||
/** Distinguishes an empty result from an unresolved or failed initial read. */
|
||||
resources: AppResourceState;
|
||||
selectedUin: string | null;
|
||||
setSelectedUin: (uin: string | null) => void;
|
||||
processOps: HookProcessOps;
|
||||
refreshQqList: () => void;
|
||||
refreshProcesses: () => void;
|
||||
refreshSystem: () => void;
|
||||
refreshConnections: () => void;
|
||||
/** Re-run the update check; `force` bypasses the server-side cache. */
|
||||
refreshUpdate: (force?: boolean) => Promise<UpdateInfo | null>;
|
||||
/** Triggered from the topbar logout button. */
|
||||
onLogout: () => void;
|
||||
}
|
||||
|
||||
const AppStateContext = createContext<AppStateValue | null>(null);
|
||||
|
||||
export function AppStateProvider({
|
||||
value,
|
||||
children,
|
||||
value,
|
||||
children,
|
||||
}: {
|
||||
value: AppStateValue;
|
||||
children: ReactNode;
|
||||
value: AppStateValue;
|
||||
children: ReactNode;
|
||||
}) {
|
||||
return <AppStateContext.Provider value={value}>{children}</AppStateContext.Provider>;
|
||||
return <AppStateContext.Provider value={value}>{children}</AppStateContext.Provider>;
|
||||
}
|
||||
|
||||
export function useAppState(): AppStateValue {
|
||||
const v = useContext(AppStateContext);
|
||||
if (!v) throw new Error('useAppState must be used inside <AppStateProvider>');
|
||||
return v;
|
||||
const v = useContext(AppStateContext);
|
||||
|
||||
if (!v) {
|
||||
throw new Error('useAppState must be used inside <AppStateProvider>');
|
||||
}
|
||||
|
||||
return v;
|
||||
}
|
||||
@@ -3,34 +3,42 @@
|
||||
// WITHIN the app (their state lives above the page, not in the unmounting tab).
|
||||
// A full page unload (refresh / close) can't be survived, so a beforeunload
|
||||
// guard warns while any task runs. Finished tasks linger briefly for history.
|
||||
import { createContext, useCallback, useContext, useEffect, useMemo, useState, type ReactNode } from 'react';
|
||||
import {
|
||||
createContext,
|
||||
useCallback,
|
||||
useContext,
|
||||
useEffect,
|
||||
useMemo,
|
||||
useState,
|
||||
type ReactNode,
|
||||
} from 'react';
|
||||
|
||||
export type DebugTaskStatus = 'running' | 'done' | 'failed' | 'canceled';
|
||||
export type DebugTaskKind = 'upload' | 'stream' | 'invoke';
|
||||
|
||||
export interface DebugTask {
|
||||
id: string;
|
||||
kind: DebugTaskKind;
|
||||
label: string;
|
||||
status: DebugTaskStatus;
|
||||
/** 0..1 when determinate; undefined = indeterminate. */
|
||||
progress?: number;
|
||||
detail?: string;
|
||||
startedAt: number;
|
||||
endedAt?: number;
|
||||
/** Cancel the underlying work (abort the fetch / xhr). */
|
||||
cancel?: () => void;
|
||||
id: string;
|
||||
kind: DebugTaskKind;
|
||||
label: string;
|
||||
status: DebugTaskStatus;
|
||||
/** 0..1 when determinate; undefined = indeterminate. */
|
||||
progress?: number;
|
||||
detail?: string;
|
||||
startedAt: number;
|
||||
endedAt?: number;
|
||||
/** Cancel the underlying work (abort the fetch / xhr). */
|
||||
cancel?: () => void;
|
||||
}
|
||||
|
||||
interface DebugTaskContextValue {
|
||||
tasks: DebugTask[];
|
||||
/** Register a task; returns its id. */
|
||||
start: (task: Omit<DebugTask, 'id' | 'status' | 'startedAt'> & { id?: string }) => string;
|
||||
update: (id: string, patch: Partial<Omit<DebugTask, 'id'>>) => void;
|
||||
/** Mark terminal (done/failed/canceled) and stamp endedAt. */
|
||||
finish: (id: string, status: Exclude<DebugTaskStatus, 'running'>, detail?: string) => void;
|
||||
remove: (id: string) => void;
|
||||
clearFinished: () => void;
|
||||
tasks: DebugTask[];
|
||||
/** Register a task; returns its id. */
|
||||
start: (task: Omit<DebugTask, 'id' | 'status' | 'startedAt'> & { id?: string }) => string;
|
||||
update: (id: string, patch: Partial<Omit<DebugTask, 'id'>>) => void;
|
||||
/** Mark terminal (done/failed/canceled) and stamp endedAt. */
|
||||
finish: (id: string, status: Exclude<DebugTaskStatus, 'running'>, detail?: string) => void;
|
||||
remove: (id: string) => void;
|
||||
clearFinished: () => void;
|
||||
}
|
||||
|
||||
const Ctx = createContext<DebugTaskContextValue | null>(null);
|
||||
@@ -39,72 +47,104 @@ let seq = 0;
|
||||
const nextId = () => `dt-${Date.now().toString(36)}-${(seq++).toString(36)}`;
|
||||
|
||||
export function DebugTaskProvider({ children }: { children: ReactNode }) {
|
||||
const [tasks, setTasks] = useState<DebugTask[]>([]);
|
||||
const [tasks, setTasks] = useState<DebugTask[]>([]);
|
||||
|
||||
const start = useCallback<DebugTaskContextValue['start']>((t) => {
|
||||
const id = t.id ?? nextId();
|
||||
setTasks((prev) => {
|
||||
const next = [{ ...t, id, status: 'running' as const, startedAt: Date.now() }, ...prev];
|
||||
if (next.length <= 50) return next;
|
||||
// Over cap: evict the OLDEST finished tasks only — never drop a running
|
||||
// task (that would orphan its finish()/cancel handle while it keeps going).
|
||||
const running = next.filter((x) => x.status === 'running').length;
|
||||
const finished = next.filter((x) => x.status !== 'running');
|
||||
const drop = new Set(finished.slice(Math.max(0, 50 - running)).map((x) => x.id));
|
||||
return next.filter((x) => !drop.has(x.id));
|
||||
});
|
||||
return id;
|
||||
}, []);
|
||||
const start = useCallback<DebugTaskContextValue['start']>((t) => {
|
||||
const id = t.id ?? nextId();
|
||||
setTasks((prev) => {
|
||||
const next = [{ ...t, id, status: 'running' as const, startedAt: Date.now() }, ...prev];
|
||||
|
||||
const update = useCallback<DebugTaskContextValue['update']>((id, patch) => {
|
||||
setTasks((prev) => prev.map((t) => (t.id === id ? { ...t, ...patch } : t)));
|
||||
}, []);
|
||||
if (next.length <= 50) {
|
||||
return next;
|
||||
}
|
||||
|
||||
const finish = useCallback<DebugTaskContextValue['finish']>((id, status, detail) => {
|
||||
setTasks((prev) => prev.map((t) => (t.id === id ? { ...t, status, detail: detail ?? t.detail, endedAt: Date.now(), cancel: undefined } : t)));
|
||||
}, []);
|
||||
// Over cap: evict the OLDEST finished tasks only — never drop a running
|
||||
// task (that would orphan its finish()/cancel handle while it keeps going).
|
||||
const running = next.filter((x) => x.status === 'running').length;
|
||||
const finished = next.filter((x) => x.status !== 'running');
|
||||
const drop = new Set(finished.slice(Math.max(0, 50 - running)).map((x) => x.id));
|
||||
return next.filter((x) => !drop.has(x.id));
|
||||
});
|
||||
return id;
|
||||
}, []);
|
||||
|
||||
const remove = useCallback<DebugTaskContextValue['remove']>((id) => {
|
||||
setTasks((prev) => prev.filter((t) => t.id !== id));
|
||||
}, []);
|
||||
const update = useCallback<DebugTaskContextValue['update']>((id, patch) => {
|
||||
setTasks((prev) => prev.map((t) => (t.id === id ? { ...t, ...patch } : t)));
|
||||
}, []);
|
||||
|
||||
const clearFinished = useCallback(() => {
|
||||
setTasks((prev) => prev.filter((t) => t.status === 'running'));
|
||||
}, []);
|
||||
const finish = useCallback<DebugTaskContextValue['finish']>((id, status, detail) => {
|
||||
setTasks((prev) =>
|
||||
prev.map((t) =>
|
||||
t.id === id
|
||||
? {
|
||||
...t,
|
||||
status,
|
||||
detail: detail ?? t.detail,
|
||||
endedAt: Date.now(),
|
||||
cancel: undefined,
|
||||
}
|
||||
: t,
|
||||
),
|
||||
);
|
||||
}, []);
|
||||
|
||||
// beforeunload guard: a real page unload kills in-flight tasks, so warn while
|
||||
// any task is still running (within-app navigation is safe — state is here).
|
||||
useEffect(() => {
|
||||
const anyRunning = tasks.some((t) => t.status === 'running');
|
||||
if (!anyRunning) return;
|
||||
const handler = (e: BeforeUnloadEvent) => { e.preventDefault(); e.returnValue = ''; };
|
||||
window.addEventListener('beforeunload', handler);
|
||||
return () => window.removeEventListener('beforeunload', handler);
|
||||
}, [tasks]);
|
||||
const remove = useCallback<DebugTaskContextValue['remove']>((id) => {
|
||||
setTasks((prev) => prev.filter((t) => t.id !== id));
|
||||
}, []);
|
||||
|
||||
const value = useMemo<DebugTaskContextValue>(
|
||||
() => ({ tasks, start, update, finish, remove, clearFinished }),
|
||||
[tasks, start, update, finish, remove, clearFinished],
|
||||
);
|
||||
return <Ctx.Provider value={value}>{children}</Ctx.Provider>;
|
||||
const clearFinished = useCallback(() => {
|
||||
setTasks((prev) => prev.filter((t) => t.status === 'running'));
|
||||
}, []);
|
||||
|
||||
// beforeunload guard: a real page unload kills in-flight tasks, so warn while
|
||||
// any task is still running (within-app navigation is safe — state is here).
|
||||
useEffect(() => {
|
||||
const anyRunning = tasks.some((t) => t.status === 'running');
|
||||
|
||||
if (!anyRunning) {
|
||||
return;
|
||||
}
|
||||
|
||||
const handler = (e: BeforeUnloadEvent) => {
|
||||
e.preventDefault();
|
||||
e.returnValue = '';
|
||||
};
|
||||
|
||||
window.addEventListener('beforeunload', handler);
|
||||
return () => window.removeEventListener('beforeunload', handler);
|
||||
}, [tasks]);
|
||||
|
||||
const value = useMemo<DebugTaskContextValue>(
|
||||
() => ({ tasks, start, update, finish, remove, clearFinished }),
|
||||
[tasks, start, update, finish, remove, clearFinished],
|
||||
);
|
||||
return <Ctx.Provider value={value}>{children}</Ctx.Provider>;
|
||||
}
|
||||
|
||||
export function useDebugTasks(): DebugTaskContextValue {
|
||||
const v = useContext(Ctx);
|
||||
if (!v) throw new Error('useDebugTasks must be used within DebugTaskProvider');
|
||||
return v;
|
||||
const v = useContext(Ctx);
|
||||
|
||||
if (!v) {
|
||||
throw new Error('useDebugTasks must be used within DebugTaskProvider');
|
||||
}
|
||||
|
||||
return v;
|
||||
}
|
||||
|
||||
/** Convenience: count + aggregate progress of running tasks, for the badge. */
|
||||
export function useRunningTaskSummary(): { count: number; progress: number | null } {
|
||||
const { tasks } = useDebugTasks();
|
||||
return useMemo(() => {
|
||||
const running = tasks.filter((t) => t.status === 'running');
|
||||
if (running.length === 0) return { count: 0, progress: null };
|
||||
const determinate = running.filter((t) => typeof t.progress === 'number');
|
||||
const progress = determinate.length
|
||||
? determinate.reduce((s, t) => s + (t.progress ?? 0), 0) / determinate.length
|
||||
: null;
|
||||
return { count: running.length, progress };
|
||||
}, [tasks]);
|
||||
const { tasks } = useDebugTasks();
|
||||
return useMemo(() => {
|
||||
const running = tasks.filter((t) => t.status === 'running');
|
||||
|
||||
if (running.length === 0) {
|
||||
return { count: 0, progress: null };
|
||||
}
|
||||
|
||||
const determinate = running.filter((t) => typeof t.progress === 'number');
|
||||
const progress = determinate.length
|
||||
? determinate.reduce((s, t) => s + (t.progress ?? 0), 0) / determinate.length
|
||||
: null;
|
||||
return { count: running.length, progress };
|
||||
}, [tasks]);
|
||||
}
|
||||
@@ -8,57 +8,82 @@ import { createContext, useCallback, useContext, useEffect, useState, type React
|
||||
const KIOSK_KEY = 'snowluma_kiosk';
|
||||
|
||||
function readInitial(): boolean {
|
||||
try {
|
||||
const params = new URLSearchParams(window.location.search);
|
||||
if (params.get('kiosk') === '1') {
|
||||
sessionStorage.setItem(KIOSK_KEY, '1');
|
||||
// Strip the param so a later reload (after exiting) doesn't re-enter.
|
||||
const url = new URL(window.location.href);
|
||||
url.searchParams.delete('kiosk');
|
||||
window.history.replaceState({}, '', url.pathname + url.search + url.hash);
|
||||
return true;
|
||||
try {
|
||||
const params = new URLSearchParams(window.location.search);
|
||||
|
||||
if (params.get('kiosk') === '1') {
|
||||
sessionStorage.setItem(KIOSK_KEY, '1');
|
||||
// Strip the param so a later reload (after exiting) doesn't re-enter.
|
||||
const url = new URL(window.location.href);
|
||||
url.searchParams.delete('kiosk');
|
||||
window.history.replaceState({}, '', url.pathname + url.search + url.hash);
|
||||
return true;
|
||||
}
|
||||
|
||||
return sessionStorage.getItem(KIOSK_KEY) === '1';
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
return sessionStorage.getItem(KIOSK_KEY) === '1';
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
interface KioskValue {
|
||||
kiosk: boolean;
|
||||
enter: () => void;
|
||||
exit: () => void;
|
||||
kiosk: boolean;
|
||||
enter: () => void;
|
||||
exit: () => void;
|
||||
}
|
||||
|
||||
const KioskContext = createContext<KioskValue | null>(null);
|
||||
|
||||
export function KioskProvider({ children }: { children: ReactNode }) {
|
||||
const [kiosk, setKiosk] = useState(readInitial);
|
||||
const [kiosk, setKiosk] = useState(readInitial);
|
||||
|
||||
const enter = useCallback(() => {
|
||||
try { sessionStorage.setItem(KIOSK_KEY, '1'); } catch { /* private mode */ }
|
||||
setKiosk(true);
|
||||
}, []);
|
||||
const exit = useCallback(() => {
|
||||
try { sessionStorage.removeItem(KIOSK_KEY); } catch { /* private mode */ }
|
||||
setKiosk(false);
|
||||
}, []);
|
||||
const enter = useCallback(() => {
|
||||
try {
|
||||
sessionStorage.setItem(KIOSK_KEY, '1');
|
||||
} catch {
|
||||
/* private mode */
|
||||
}
|
||||
|
||||
// Reflect onto <html data-kiosk> so CSS can hide chrome (e.g. the overview
|
||||
// edit entry), and bind Esc-to-exit only while active.
|
||||
useEffect(() => {
|
||||
document.documentElement.setAttribute('data-kiosk', kiosk ? '1' : '0');
|
||||
if (!kiosk) return;
|
||||
const onKey = (e: KeyboardEvent) => { if (e.key === 'Escape') exit(); };
|
||||
window.addEventListener('keydown', onKey);
|
||||
return () => window.removeEventListener('keydown', onKey);
|
||||
}, [kiosk, exit]);
|
||||
setKiosk(true);
|
||||
}, []);
|
||||
const exit = useCallback(() => {
|
||||
try {
|
||||
sessionStorage.removeItem(KIOSK_KEY);
|
||||
} catch {
|
||||
/* private mode */
|
||||
}
|
||||
|
||||
return <KioskContext.Provider value={{ kiosk, enter, exit }}>{children}</KioskContext.Provider>;
|
||||
setKiosk(false);
|
||||
}, []);
|
||||
|
||||
// Reflect onto <html data-kiosk> so CSS can hide chrome (e.g. the overview
|
||||
// edit entry), and bind Esc-to-exit only while active.
|
||||
useEffect(() => {
|
||||
document.documentElement.setAttribute('data-kiosk', kiosk ? '1' : '0');
|
||||
|
||||
if (!kiosk) {
|
||||
return;
|
||||
}
|
||||
|
||||
const onKey = (e: KeyboardEvent) => {
|
||||
if (e.key === 'Escape') {
|
||||
exit();
|
||||
}
|
||||
};
|
||||
|
||||
window.addEventListener('keydown', onKey);
|
||||
return () => window.removeEventListener('keydown', onKey);
|
||||
}, [kiosk, exit]);
|
||||
|
||||
return <KioskContext.Provider value={{ kiosk, enter, exit }}>{children}</KioskContext.Provider>;
|
||||
}
|
||||
|
||||
export function useKiosk(): KioskValue {
|
||||
const ctx = useContext(KioskContext);
|
||||
if (!ctx) throw new Error('useKiosk must be used within KioskProvider');
|
||||
return ctx;
|
||||
const ctx = useContext(KioskContext);
|
||||
|
||||
if (!ctx) {
|
||||
throw new Error('useKiosk must be used within KioskProvider');
|
||||
}
|
||||
|
||||
return ctx;
|
||||
}
|
||||
@@ -1,7 +1,20 @@
|
||||
import { createContext, useCallback, useContext, useEffect, useMemo, useRef, useState, type ReactNode } from 'react';
|
||||
import {
|
||||
createContext,
|
||||
useCallback,
|
||||
useContext,
|
||||
useEffect,
|
||||
useMemo,
|
||||
useRef,
|
||||
useState,
|
||||
type ReactNode,
|
||||
} from 'react';
|
||||
import { actionErrorMessage, useActionFeedback } from '@/contexts/ActionFeedbackContext';
|
||||
import { useApi } from '@/lib/api';
|
||||
import { defaultOverviewGrid, defaultOverviewMobile, migrateOverviewBlocks } from '@/lib/dashboard-layout';
|
||||
import {
|
||||
defaultOverviewGrid,
|
||||
defaultOverviewMobile,
|
||||
migrateOverviewBlocks,
|
||||
} from '@/lib/dashboard-layout';
|
||||
import type { UiLayout, UiLayoutItem, UiPages } from '@/types';
|
||||
|
||||
// Client-side layout customization (the "C" half). The server stores the
|
||||
@@ -14,11 +27,11 @@ import type { UiLayout, UiLayoutItem, UiPages } from '@/types';
|
||||
// block / nav item later doesn't need a context change — it just appears.
|
||||
|
||||
const DEFAULT_NAV_ITEMS: UiLayoutItem[] = [
|
||||
{ id: '/', visible: true },
|
||||
{ id: '/processes', visible: true },
|
||||
{ id: '/config', visible: true },
|
||||
{ id: '/logs', visible: true },
|
||||
{ id: '/settings', visible: true },
|
||||
{ id: '/', visible: true },
|
||||
{ id: '/processes', visible: true },
|
||||
{ id: '/config', visible: true },
|
||||
{ id: '/logs', visible: true },
|
||||
{ id: '/settings', visible: true },
|
||||
];
|
||||
|
||||
// Toggleable top-bar elements (essential ones are pinned in the consumer). The
|
||||
@@ -27,23 +40,30 @@ export const TOPBAR_ITEM_IDS = ['status', 'theme', 'kiosk'] as const;
|
||||
const DEFAULT_TOPBAR_ITEMS: UiLayoutItem[] = TOPBAR_ITEM_IDS.map((id) => ({ id, visible: true }));
|
||||
|
||||
export const DEFAULT_LAYOUT: UiLayout = {
|
||||
// Overview blocks are the positioned grid widgets (the catalogue owns the
|
||||
// default placement + the legacy `stats`→tiles migration).
|
||||
overviewBlocks: defaultOverviewGrid(),
|
||||
overviewMobile: defaultOverviewMobile(),
|
||||
navItems: DEFAULT_NAV_ITEMS.map((i) => ({ ...i })),
|
||||
topbarItems: DEFAULT_TOPBAR_ITEMS.map((i) => ({ ...i })),
|
||||
// Overview blocks are the positioned grid widgets (the catalogue owns the
|
||||
// default placement + the legacy `stats`→tiles migration).
|
||||
overviewBlocks: defaultOverviewGrid(),
|
||||
overviewMobile: defaultOverviewMobile(),
|
||||
navItems: DEFAULT_NAV_ITEMS.map((i) => ({ ...i })),
|
||||
topbarItems: DEFAULT_TOPBAR_ITEMS.map((i) => ({ ...i })),
|
||||
};
|
||||
|
||||
const ALL_LEVELS = ['trace', 'debug', 'info', 'success', 'warn', 'error'];
|
||||
|
||||
export function defaultPages(): UiPages {
|
||||
return {
|
||||
defaultRoute: '/',
|
||||
logs: { visibleLevels: [...ALL_LEVELS], maxLines: 1000, autoScroll: true, wrap: true, highlightRules: [], preset: 'custom' },
|
||||
processesSort: 'pid',
|
||||
configTab: '',
|
||||
};
|
||||
return {
|
||||
defaultRoute: '/',
|
||||
logs: {
|
||||
visibleLevels: [...ALL_LEVELS],
|
||||
maxLines: 1000,
|
||||
autoScroll: true,
|
||||
wrap: true,
|
||||
highlightRules: [],
|
||||
preset: 'custom',
|
||||
},
|
||||
processesSort: 'pid',
|
||||
configTab: '',
|
||||
};
|
||||
}
|
||||
|
||||
export const DEFAULT_PAGES: UiPages = defaultPages();
|
||||
@@ -55,198 +75,275 @@ export const DEFAULT_PAGES: UiPages = defaultPages();
|
||||
* `hiddenByDefault` are appended hidden (opt-in widgets), otherwise visible.
|
||||
*/
|
||||
export function reconcileLayoutItems(
|
||||
stored: UiLayoutItem[] | undefined,
|
||||
known: readonly string[],
|
||||
pinned: readonly string[] = [],
|
||||
hiddenByDefault: ReadonlySet<string> = new Set(),
|
||||
stored: UiLayoutItem[] | undefined,
|
||||
known: readonly string[],
|
||||
pinned: readonly string[] = [],
|
||||
hiddenByDefault: ReadonlySet<string> = new Set(),
|
||||
): UiLayoutItem[] {
|
||||
const knownSet = new Set(known);
|
||||
const seen = new Set<string>();
|
||||
const out: UiLayoutItem[] = [];
|
||||
for (const item of stored ?? []) {
|
||||
if (!item || !knownSet.has(item.id) || seen.has(item.id)) continue;
|
||||
seen.add(item.id);
|
||||
out.push({ id: item.id, visible: pinned.includes(item.id) ? true : item.visible !== false });
|
||||
}
|
||||
for (const id of known) {
|
||||
if (!seen.has(id)) out.push({ id, visible: !hiddenByDefault.has(id) });
|
||||
}
|
||||
return out;
|
||||
const knownSet = new Set(known);
|
||||
const seen = new Set<string>();
|
||||
const out: UiLayoutItem[] = [];
|
||||
|
||||
for (const item of stored ?? []) {
|
||||
if (!item || !knownSet.has(item.id) || seen.has(item.id)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
seen.add(item.id);
|
||||
out.push({
|
||||
id: item.id,
|
||||
visible: pinned.includes(item.id) ? true : item.visible !== false,
|
||||
});
|
||||
}
|
||||
|
||||
for (const id of known) {
|
||||
if (!seen.has(id)) {
|
||||
out.push({ id, visible: !hiddenByDefault.has(id) });
|
||||
}
|
||||
}
|
||||
|
||||
return out;
|
||||
}
|
||||
|
||||
interface LayoutContextValue {
|
||||
overviewBlocks: UiLayoutItem[];
|
||||
overviewMobile: UiLayoutItem[];
|
||||
navItems: UiLayoutItem[];
|
||||
topbarItems: UiLayoutItem[];
|
||||
/** Persist a new overview-block order/visibility (desktop 2D grid). */
|
||||
setOverviewBlocks: (items: UiLayoutItem[]) => void;
|
||||
/** Persist a new single-column mobile order/visibility. */
|
||||
setOverviewMobile: (items: UiLayoutItem[]) => void;
|
||||
/** Persist a new nav order/visibility. */
|
||||
setNavItems: (items: UiLayoutItem[]) => void;
|
||||
/** Persist a new top-bar show/hide order. */
|
||||
setTopbarItems: (items: UiLayoutItem[]) => void;
|
||||
/** Reset layout (blocks + mobile + nav + topbar) to defaults. */
|
||||
resetLayout: () => void;
|
||||
/** Per-page preferences (default route, logs/processes/config prefs). */
|
||||
pages: UiPages;
|
||||
/** Merge a partial pages-prefs update (debounced-persisted). */
|
||||
setPages: (patch: Partial<UiPages>) => void;
|
||||
/** True once the authed config load has resolved (gates the default-route redirect). */
|
||||
ready: boolean;
|
||||
/** Shared "编辑布局" mode — the dashboard grid AND the sidebar read this so both
|
||||
* show in-place edit affordances from a single toggle. */
|
||||
editing: boolean;
|
||||
setEditing: (v: boolean) => void;
|
||||
overviewBlocks: UiLayoutItem[];
|
||||
overviewMobile: UiLayoutItem[];
|
||||
navItems: UiLayoutItem[];
|
||||
topbarItems: UiLayoutItem[];
|
||||
/** Persist a new overview-block order/visibility (desktop 2D grid). */
|
||||
setOverviewBlocks: (items: UiLayoutItem[]) => void;
|
||||
/** Persist a new single-column mobile order/visibility. */
|
||||
setOverviewMobile: (items: UiLayoutItem[]) => void;
|
||||
/** Persist a new nav order/visibility. */
|
||||
setNavItems: (items: UiLayoutItem[]) => void;
|
||||
/** Persist a new top-bar show/hide order. */
|
||||
setTopbarItems: (items: UiLayoutItem[]) => void;
|
||||
/** Reset layout (blocks + mobile + nav + topbar) to defaults. */
|
||||
resetLayout: () => void;
|
||||
/** Per-page preferences (default route, logs/processes/config prefs). */
|
||||
pages: UiPages;
|
||||
/** Merge a partial pages-prefs update (debounced-persisted). */
|
||||
setPages: (patch: Partial<UiPages>) => void;
|
||||
/** True once the authed config load has resolved (gates the default-route redirect). */
|
||||
ready: boolean;
|
||||
/** Shared "编辑布局" mode — the dashboard grid AND the sidebar read this so both
|
||||
* show in-place edit affordances from a single toggle. */
|
||||
editing: boolean;
|
||||
setEditing: (v: boolean) => void;
|
||||
}
|
||||
|
||||
const LayoutContext = createContext<LayoutContextValue | null>(null);
|
||||
|
||||
export function LayoutProvider({ children }: { children: ReactNode }) {
|
||||
const api = useApi();
|
||||
const { startAction } = useActionFeedback();
|
||||
const [layout, setLayout] = useState<UiLayout>(DEFAULT_LAYOUT);
|
||||
const [pages, setPagesState] = useState<UiPages>(DEFAULT_PAGES);
|
||||
const [ready, setReady] = useState(false);
|
||||
const [editing, setEditing] = useState(false);
|
||||
const layoutRef = useRef(layout);
|
||||
const pagesRef = useRef(pages);
|
||||
// Set once the user edits, so the initial GET (which may resolve AFTER the
|
||||
// first edit) never clobbers their change.
|
||||
const dirtyRef = useRef(false);
|
||||
const saveTimer = useRef<ReturnType<typeof setTimeout> | null>(null);
|
||||
const pagesTimer = useRef<ReturnType<typeof setTimeout> | null>(null);
|
||||
const api = useApi();
|
||||
const { startAction } = useActionFeedback();
|
||||
const [layout, setLayout] = useState<UiLayout>(DEFAULT_LAYOUT);
|
||||
const [pages, setPagesState] = useState<UiPages>(DEFAULT_PAGES);
|
||||
const [ready, setReady] = useState(false);
|
||||
const [editing, setEditing] = useState(false);
|
||||
const layoutRef = useRef(layout);
|
||||
const pagesRef = useRef(pages);
|
||||
// Set once the user edits, so the initial GET (which may resolve AFTER the
|
||||
// first edit) never clobbers their change.
|
||||
const dirtyRef = useRef(false);
|
||||
const saveTimer = useRef<ReturnType<typeof setTimeout> | null>(null);
|
||||
const pagesTimer = useRef<ReturnType<typeof setTimeout> | null>(null);
|
||||
|
||||
useEffect(() => { layoutRef.current = layout; }, [layout]);
|
||||
useEffect(() => { pagesRef.current = pages; }, [pages]);
|
||||
useEffect(() => {
|
||||
layoutRef.current = layout;
|
||||
}, [layout]);
|
||||
useEffect(() => {
|
||||
pagesRef.current = pages;
|
||||
}, [pages]);
|
||||
|
||||
useEffect(() => {
|
||||
let cancelled = false;
|
||||
(async () => {
|
||||
try {
|
||||
const config = await api.ui.get();
|
||||
// Seed from the server only if the user hasn't already edited (the
|
||||
// overview + editor are interactive immediately, before this resolves).
|
||||
// Overview blocks are migrated to the current grid catalogue (legacy
|
||||
// `stats`→tiles, default coords for new/coordless widgets).
|
||||
if (!cancelled && !dirtyRef.current && config) {
|
||||
if (config.layout) {
|
||||
setLayout({
|
||||
overviewBlocks: migrateOverviewBlocks(config.layout.overviewBlocks),
|
||||
// Mobile/topbar are stored raw; consumers reconcile against their
|
||||
// known catalogues (so a new widget/element "just appears").
|
||||
overviewMobile: config.layout.overviewMobile ?? defaultOverviewMobile(),
|
||||
navItems: config.layout.navItems,
|
||||
topbarItems: config.layout.topbarItems ?? DEFAULT_TOPBAR_ITEMS.map((i) => ({ ...i })),
|
||||
});
|
||||
}
|
||||
if (config.pages) setPagesState(config.pages);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('initial UI preferences load failed', error);
|
||||
} finally {
|
||||
if (!cancelled) setReady(true);
|
||||
}
|
||||
})();
|
||||
return () => { cancelled = true; };
|
||||
}, [api]);
|
||||
useEffect(() => {
|
||||
let cancelled = false;
|
||||
|
||||
// On unmount (e.g. logout), flush pending debounced saves so a last-moment
|
||||
// edit isn't lost; best-effort (a cleared token just 401s harmlessly).
|
||||
useEffect(() => () => {
|
||||
if (saveTimer.current) {
|
||||
clearTimeout(saveTimer.current);
|
||||
void api.ui.save({ layout: layoutRef.current }).catch((error) => {
|
||||
console.error('layout unmount flush failed', error);
|
||||
});
|
||||
}
|
||||
if (pagesTimer.current) {
|
||||
clearTimeout(pagesTimer.current);
|
||||
void api.ui.save({ pages: pagesRef.current }).catch((error) => {
|
||||
console.error('page preferences unmount flush failed', error);
|
||||
});
|
||||
}
|
||||
}, [api]);
|
||||
(async () => {
|
||||
try {
|
||||
const config = await api.ui.get();
|
||||
|
||||
const persist = useCallback((next: UiLayout) => {
|
||||
dirtyRef.current = true;
|
||||
layoutRef.current = next;
|
||||
setLayout(next);
|
||||
if (saveTimer.current) clearTimeout(saveTimer.current);
|
||||
saveTimer.current = setTimeout(() => {
|
||||
saveTimer.current = null; // mark not-pending so the unmount flush can't double-fire
|
||||
void api.ui.save({ layout: next }).catch((error) => {
|
||||
console.error('persist layout failed', error);
|
||||
startAction({ title: '界面布局同步失败' })
|
||||
.fail(`当前修改未保存:${actionErrorMessage(error)}`);
|
||||
});
|
||||
}, 300);
|
||||
}, [api, startAction]);
|
||||
// Seed from the server only if the user hasn't already edited (the
|
||||
// overview + editor are interactive immediately, before this resolves).
|
||||
// Overview blocks are migrated to the current grid catalogue (legacy
|
||||
// `stats`→tiles, default coords for new/coordless widgets).
|
||||
if (!cancelled && !dirtyRef.current && config) {
|
||||
if (config.layout) {
|
||||
setLayout({
|
||||
overviewBlocks: migrateOverviewBlocks(config.layout.overviewBlocks),
|
||||
// Mobile/topbar are stored raw; consumers reconcile against their
|
||||
// known catalogues (so a new widget/element "just appears").
|
||||
overviewMobile: config.layout.overviewMobile ?? defaultOverviewMobile(),
|
||||
navItems: config.layout.navItems,
|
||||
topbarItems:
|
||||
config.layout.topbarItems ??
|
||||
DEFAULT_TOPBAR_ITEMS.map((i) => ({ ...i })),
|
||||
});
|
||||
}
|
||||
|
||||
const setOverviewBlocks = useCallback((items: UiLayoutItem[]) => {
|
||||
persist({ ...layoutRef.current, overviewBlocks: items });
|
||||
}, [persist]);
|
||||
if (config.pages) {
|
||||
setPagesState(config.pages);
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('initial UI preferences load failed', error);
|
||||
} finally {
|
||||
if (!cancelled) {
|
||||
setReady(true);
|
||||
}
|
||||
}
|
||||
})();
|
||||
|
||||
const setOverviewMobile = useCallback((items: UiLayoutItem[]) => {
|
||||
persist({ ...layoutRef.current, overviewMobile: items });
|
||||
}, [persist]);
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, [api]);
|
||||
|
||||
const setNavItems = useCallback((items: UiLayoutItem[]) => {
|
||||
persist({ ...layoutRef.current, navItems: items });
|
||||
}, [persist]);
|
||||
// On unmount (e.g. logout), flush pending debounced saves so a last-moment
|
||||
// edit isn't lost; best-effort (a cleared token just 401s harmlessly).
|
||||
useEffect(
|
||||
() => () => {
|
||||
if (saveTimer.current) {
|
||||
clearTimeout(saveTimer.current);
|
||||
void api.ui.save({ layout: layoutRef.current }).catch((error) => {
|
||||
console.error('layout unmount flush failed', error);
|
||||
});
|
||||
}
|
||||
|
||||
const setTopbarItems = useCallback((items: UiLayoutItem[]) => {
|
||||
persist({ ...layoutRef.current, topbarItems: items });
|
||||
}, [persist]);
|
||||
if (pagesTimer.current) {
|
||||
clearTimeout(pagesTimer.current);
|
||||
void api.ui.save({ pages: pagesRef.current }).catch((error) => {
|
||||
console.error('page preferences unmount flush failed', error);
|
||||
});
|
||||
}
|
||||
},
|
||||
[api],
|
||||
);
|
||||
|
||||
const resetLayout = useCallback(() => {
|
||||
persist({
|
||||
overviewBlocks: defaultOverviewGrid(),
|
||||
overviewMobile: defaultOverviewMobile(),
|
||||
navItems: DEFAULT_NAV_ITEMS.map((i) => ({ ...i })),
|
||||
topbarItems: DEFAULT_TOPBAR_ITEMS.map((i) => ({ ...i })),
|
||||
});
|
||||
}, [persist]);
|
||||
const persist = useCallback(
|
||||
(next: UiLayout) => {
|
||||
dirtyRef.current = true;
|
||||
layoutRef.current = next;
|
||||
setLayout(next);
|
||||
|
||||
const setPages = useCallback((patch: Partial<UiPages>) => {
|
||||
dirtyRef.current = true;
|
||||
const next = { ...pagesRef.current, ...patch };
|
||||
pagesRef.current = next;
|
||||
setPagesState(next);
|
||||
if (pagesTimer.current) clearTimeout(pagesTimer.current);
|
||||
pagesTimer.current = setTimeout(() => {
|
||||
pagesTimer.current = null;
|
||||
void api.ui.save({ pages: next }).catch((error) => {
|
||||
console.error('persist page preferences failed', error);
|
||||
startAction({ title: '页面偏好同步失败' })
|
||||
.fail(`当前修改未保存:${actionErrorMessage(error)}`);
|
||||
});
|
||||
}, 300);
|
||||
}, [api, startAction]);
|
||||
if (saveTimer.current) {
|
||||
clearTimeout(saveTimer.current);
|
||||
}
|
||||
|
||||
const value = useMemo<LayoutContextValue>(() => ({
|
||||
overviewBlocks: layout.overviewBlocks,
|
||||
overviewMobile: layout.overviewMobile,
|
||||
navItems: layout.navItems,
|
||||
topbarItems: layout.topbarItems,
|
||||
setOverviewBlocks,
|
||||
setOverviewMobile,
|
||||
setNavItems,
|
||||
setTopbarItems,
|
||||
resetLayout,
|
||||
pages,
|
||||
setPages,
|
||||
ready,
|
||||
editing,
|
||||
setEditing,
|
||||
}), [layout, setOverviewBlocks, setOverviewMobile, setNavItems, setTopbarItems, resetLayout, pages, setPages, ready, editing]);
|
||||
saveTimer.current = setTimeout(() => {
|
||||
saveTimer.current = null; // mark not-pending so the unmount flush can't double-fire
|
||||
void api.ui.save({ layout: next }).catch((error) => {
|
||||
console.error('persist layout failed', error);
|
||||
startAction({ title: '界面布局同步失败' }).fail(
|
||||
`当前修改未保存:${actionErrorMessage(error)}`,
|
||||
);
|
||||
});
|
||||
}, 300);
|
||||
},
|
||||
[api, startAction],
|
||||
);
|
||||
|
||||
return <LayoutContext.Provider value={value}>{children}</LayoutContext.Provider>;
|
||||
const setOverviewBlocks = useCallback(
|
||||
(items: UiLayoutItem[]) => {
|
||||
persist({ ...layoutRef.current, overviewBlocks: items });
|
||||
},
|
||||
[persist],
|
||||
);
|
||||
|
||||
const setOverviewMobile = useCallback(
|
||||
(items: UiLayoutItem[]) => {
|
||||
persist({ ...layoutRef.current, overviewMobile: items });
|
||||
},
|
||||
[persist],
|
||||
);
|
||||
|
||||
const setNavItems = useCallback(
|
||||
(items: UiLayoutItem[]) => {
|
||||
persist({ ...layoutRef.current, navItems: items });
|
||||
},
|
||||
[persist],
|
||||
);
|
||||
|
||||
const setTopbarItems = useCallback(
|
||||
(items: UiLayoutItem[]) => {
|
||||
persist({ ...layoutRef.current, topbarItems: items });
|
||||
},
|
||||
[persist],
|
||||
);
|
||||
|
||||
const resetLayout = useCallback(() => {
|
||||
persist({
|
||||
overviewBlocks: defaultOverviewGrid(),
|
||||
overviewMobile: defaultOverviewMobile(),
|
||||
navItems: DEFAULT_NAV_ITEMS.map((i) => ({ ...i })),
|
||||
topbarItems: DEFAULT_TOPBAR_ITEMS.map((i) => ({ ...i })),
|
||||
});
|
||||
}, [persist]);
|
||||
|
||||
const setPages = useCallback(
|
||||
(patch: Partial<UiPages>) => {
|
||||
dirtyRef.current = true;
|
||||
const next = { ...pagesRef.current, ...patch };
|
||||
pagesRef.current = next;
|
||||
setPagesState(next);
|
||||
|
||||
if (pagesTimer.current) {
|
||||
clearTimeout(pagesTimer.current);
|
||||
}
|
||||
|
||||
pagesTimer.current = setTimeout(() => {
|
||||
pagesTimer.current = null;
|
||||
void api.ui.save({ pages: next }).catch((error) => {
|
||||
console.error('persist page preferences failed', error);
|
||||
startAction({ title: '页面偏好同步失败' }).fail(
|
||||
`当前修改未保存:${actionErrorMessage(error)}`,
|
||||
);
|
||||
});
|
||||
}, 300);
|
||||
},
|
||||
[api, startAction],
|
||||
);
|
||||
|
||||
const value = useMemo<LayoutContextValue>(
|
||||
() => ({
|
||||
overviewBlocks: layout.overviewBlocks,
|
||||
overviewMobile: layout.overviewMobile,
|
||||
navItems: layout.navItems,
|
||||
topbarItems: layout.topbarItems,
|
||||
setOverviewBlocks,
|
||||
setOverviewMobile,
|
||||
setNavItems,
|
||||
setTopbarItems,
|
||||
resetLayout,
|
||||
pages,
|
||||
setPages,
|
||||
ready,
|
||||
editing,
|
||||
setEditing,
|
||||
}),
|
||||
[
|
||||
layout,
|
||||
setOverviewBlocks,
|
||||
setOverviewMobile,
|
||||
setNavItems,
|
||||
setTopbarItems,
|
||||
resetLayout,
|
||||
pages,
|
||||
setPages,
|
||||
ready,
|
||||
editing,
|
||||
],
|
||||
);
|
||||
|
||||
return <LayoutContext.Provider value={value}>{children}</LayoutContext.Provider>;
|
||||
}
|
||||
|
||||
export function useLayout(): LayoutContextValue {
|
||||
const ctx = useContext(LayoutContext);
|
||||
if (!ctx) throw new Error('useLayout must be used within LayoutProvider');
|
||||
return ctx;
|
||||
const ctx = useContext(LayoutContext);
|
||||
|
||||
if (!ctx) {
|
||||
throw new Error('useLayout must be used within LayoutProvider');
|
||||
}
|
||||
|
||||
return ctx;
|
||||
}
|
||||
@@ -6,27 +6,25 @@ import { createContext, useContext, type ReactNode } from 'react';
|
||||
* complete logout after page-local state has been cleared.
|
||||
*/
|
||||
export interface SessionValue {
|
||||
status: string;
|
||||
/** Invoked by AppLayout's logout handler after it has scrubbed its own state. */
|
||||
onLogoutComplete: () => void;
|
||||
/** Replays the first-run wizard without changing persisted account state. */
|
||||
restartOnboarding: () => void;
|
||||
status: string;
|
||||
/** Invoked by AppLayout's logout handler after it has scrubbed its own state. */
|
||||
onLogoutComplete: () => void;
|
||||
/** Replays the first-run wizard without changing persisted account state. */
|
||||
restartOnboarding: () => void;
|
||||
}
|
||||
|
||||
const SessionContext = createContext<SessionValue | null>(null);
|
||||
|
||||
export function SessionProvider({
|
||||
value,
|
||||
children,
|
||||
}: {
|
||||
value: SessionValue;
|
||||
children: ReactNode;
|
||||
}) {
|
||||
return <SessionContext.Provider value={value}>{children}</SessionContext.Provider>;
|
||||
export function SessionProvider({ value, children }: { value: SessionValue; children: ReactNode }) {
|
||||
return <SessionContext.Provider value={value}>{children}</SessionContext.Provider>;
|
||||
}
|
||||
|
||||
export function useSession(): SessionValue {
|
||||
const v = useContext(SessionContext);
|
||||
if (!v) throw new Error('useSession must be used inside <SessionProvider>');
|
||||
return v;
|
||||
const v = useContext(SessionContext);
|
||||
|
||||
if (!v) {
|
||||
throw new Error('useSession must be used inside <SessionProvider>');
|
||||
}
|
||||
|
||||
return v;
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
Reference in new issue
Block a user