PatternsFeedback
LoadingOverlay
@mox-hub/patterns 模式 · Feedback · canonical
loading-overlay@mox-hub/patternsFeedbackcanonicalsrc/components/loading-overlay.tsx变体轴
modeoverlayinlinebar
变体演示loading-overlay
正在同步
拉取最新数据…
Props API
| Prop | 类型 | 默认值 | 说明 |
|---|---|---|---|
| visible* | boolean | — | — |
| message* | string | — | — |
| description* | string | — | — |
| loadingLabel* | string | — | — |
| mode* | LoadingMode | "overlay" | — |
| blur* | boolean | true | — |
| spinnerSize* | SpinnerSize | "lg" | — |
| className* | string | — | — |
源码
import { createContext, useContext, useEffect, useId, useRef, useState, useCallback, type ReactNode } from "react"
import { cn } from "@mox-hub/ui"
import { Spinner, type SpinnerSize } from "@mox-hub/ui/components/spinner"
import { RawButton } from "@mox-hub/ui/components/raw/raw-button"
import { XCircleIcon } from "lucide-react"
import { usePatternLabels } from "../lib/i18n"
/* ============================================
LoadingOverlay — 通用加载遮罩/进度条
============================================ */
export type LoadingMode = "overlay" | "inline" | "bar"
export interface LoadingOverlayProps {
visible: boolean
message?: string
description?: string
/** 无 message 时的 aria-label;默认「加载中」 */
loadingLabel?: string
mode?: LoadingMode
blur?: boolean
spinnerSize?: SpinnerSize
className?: string
}
function LoadingOverlay({
visible,
message,
description,
loadingLabel,
mode = "overlay",
blur = true,
spinnerSize = "lg",
className,
}: LoadingOverlayProps) {
const D = usePatternLabels("loadingOverlay", { loadingLabel: "加载中" })
if (!visible) return null
const label = message ?? loadingLabel ?? D.loadingLabel
if (mode === "bar") {
return (
<div
className={cn(
"fixed top-0 inset-x-0 z-overlay h-0.5 overflow-hidden",
className
)}
role="progressbar"
aria-label={label}
>
<div className="h-full w-1/3 bg-primary animate-loading-bar" />
</div>
)
}
if (mode === "inline") {
return (
<div
className={cn(
"flex flex-col items-center justify-center gap-3 py-8",
className
)}
role="status"
aria-label={label}
>
<Spinner size={spinnerSize} />
{message && (
<p className="text-sm text-muted-foreground font-medium">{message}</p>
)}
{description && (
<p className="text-xs text-muted-foreground">{description}</p>
)}
</div>
)
}
// overlay mode (default)
return (
<div
className={cn(
"fixed inset-0 z-overlay flex flex-col items-center justify-center gap-4",
blur && "bg-background/60 backdrop-blur-sm",
!blur && "bg-background/80",
className
)}
role="status"
aria-label={label}
>
<div className="flex flex-col items-center gap-3">
<Spinner size={spinnerSize} />
{message && (
<p className="text-sm font-medium text-foreground animate-pulse">
{message}
</p>
)}
{description && (
<p className="text-xs text-muted-foreground">{description}</p>
)}
</div>
</div>
)
}
/* ============================================
ErrorOverlay — 错误提示遮罩(可选,配合 LoadingOverlay 使用)
============================================ */
export interface ErrorOverlayProps {
visible: boolean
message?: string
description?: string
onRetry?: () => void
onDismiss?: () => void
className?: string
/** 重试按钮;默认「重试」 */
retryLabel?: string
/** 关闭按钮;默认「关闭」 */
closeLabel?: string
}
function ErrorOverlay({
visible,
message,
description,
onRetry,
onDismiss,
className,
retryLabel,
closeLabel,
}: ErrorOverlayProps) {
const D = usePatternLabels("errorOverlay", {
message: "操作失败",
retryLabel: "重试",
closeLabel: "关闭",
})
const panelRef = useRef<HTMLDivElement>(null)
const restoreFocusRef = useRef<HTMLElement | null>(null)
const onDismissRef = useRef(onDismiss)
const descriptionId = useId()
// 回调走 ref:父级内联函数导致的 re-render 不应重置焦点/重复移入
useEffect(() => {
onDismissRef.current = onDismiss
}, [onDismiss])
// 模态错误层:焦点移入 + Tab 困住 + Escape 关闭 + 关闭后归还(审计 P1-09)
useEffect(() => {
if (!visible) return
restoreFocusRef.current =
document.activeElement instanceof HTMLElement ? document.activeElement : null
const panel = panelRef.current
panel?.focus()
const onKeyDown = (event: KeyboardEvent) => {
if (event.key === "Escape") {
event.preventDefault()
onDismissRef.current?.()
return
}
if (event.key !== "Tab" || !panel) return
const focusables = Array.from(
panel.querySelectorAll<HTMLElement>(
'button:not([disabled]), a[href], input:not([disabled]), textarea:not([disabled]), select:not([disabled]), [tabindex]:not([tabindex="-1"])',
),
)
if (focusables.length === 0) {
event.preventDefault()
panel.focus()
return
}
const first = focusables[0]
const last = focusables[focusables.length - 1]
if (event.shiftKey && (document.activeElement === first || document.activeElement === panel)) {
event.preventDefault()
last.focus()
} else if (!event.shiftKey && document.activeElement === last) {
event.preventDefault()
first.focus()
}
}
window.addEventListener("keydown", onKeyDown)
return () => {
window.removeEventListener("keydown", onKeyDown)
restoreFocusRef.current?.focus?.()
restoreFocusRef.current = null
}
}, [visible])
if (!visible) return null
const title = message ?? D.message
const retry = retryLabel ?? D.retryLabel
const close = closeLabel ?? D.closeLabel
return (
<div
className={cn(
"fixed inset-0 z-overlay flex flex-col items-center justify-center gap-4",
"bg-background/80 backdrop-blur-sm",
className
)}
role="alertdialog"
aria-modal="true"
aria-label={title}
aria-describedby={description ? descriptionId : undefined}
>
<div
ref={panelRef}
tabIndex={-1}
className="flex flex-col items-center gap-3 p-6 rounded-xl border border-border bg-card shadow-xs max-w-sm text-center outline-none"
>
<div className="flex items-center justify-center size-12 rounded-full bg-destructive/10">
<XCircleIcon className="size-6 text-destructive" />
</div>
<div>
<p className="text-base font-semibold text-foreground">{title}</p>
{description && (
<p id={descriptionId} className="mt-1 text-sm text-muted-foreground">{description}</p>
)}
</div>
<div className="flex gap-2 pt-1">
{onRetry && (
<RawButton
onClick={onRetry}
className="px-4 py-2 text-sm font-medium rounded-lg bg-primary text-primary-foreground hover:opacity-90 transition-opacity"
>
{retry}
</RawButton>
)}
{onDismiss && (
<RawButton
onClick={onDismiss}
className="px-4 py-2 text-sm font-medium rounded-lg border border-border hover:bg-muted transition-colors"
>
{close}
</RawButton>
)}
</div>
</div>
</div>
)
}
/* ============================================
LoadingContext — 全局加载状态管理
============================================ */
interface LoadingContextValue {
isLoading: boolean
pendingCount: number
message?: string
description?: string
mode: LoadingMode
show: (opts?: { message?: string; description?: string; mode?: LoadingMode }) => void
hide: () => void
addPending: () => void
removePending: () => void
}
const LoadingContext = createContext<LoadingContextValue | undefined>(undefined)
export interface LoadingProviderProps {
children: ReactNode
/** 初始模式,默认 overlay */
defaultMode?: LoadingMode
}
function LoadingProvider({ children, defaultMode = "bar" }: LoadingProviderProps) {
const [isLoading, setIsLoading] = useState(false)
const [pendingCount, setPendingCount] = useState(0)
const [message, setMessage] = useState<string>()
const [description, setDescription] = useState<string>()
const [mode, setMode] = useState<LoadingMode>(defaultMode)
const show = useCallback(
(opts?: { message?: string; description?: string; mode?: LoadingMode }) => {
setMessage(opts?.message)
setDescription(opts?.description)
if (opts?.mode) setMode(opts.mode)
setIsLoading(true)
},
[]
)
const hide = useCallback(() => {
setIsLoading(false)
setMessage(undefined)
setDescription(undefined)
}, [])
const addPending = useCallback(() => {
setPendingCount(c => c + 1)
setIsLoading(true)
setMode(defaultMode)
}, [defaultMode])
const removePending = useCallback(() => {
setPendingCount(c => {
const next = Math.max(0, c - 1)
if (next === 0) {
setIsLoading(false)
}
return next
})
}, [])
return (
<LoadingContext.Provider
value={{ isLoading, pendingCount, message, description, mode, show, hide, addPending, removePending }}
>
{children}
</LoadingContext.Provider>
)
}
function useLoadingContext() {
const ctx = useContext(LoadingContext)
if (!ctx) throw new Error("useLoading must be used within LoadingProvider")
return ctx
}
/** 全局手动控制加载遮罩 */
function useLoading() {
const ctx = useLoadingContext()
return {
isLoading: ctx.isLoading,
pendingCount: ctx.pendingCount,
mode: ctx.mode,
show: ctx.show,
hide: ctx.hide,
addPending: ctx.addPending,
removePending: ctx.removePending,
}
}
export {
LoadingOverlay,
ErrorOverlay,
LoadingProvider,
useLoading,
useLoadingContext,
}
可访问性与 RTL
- 键盘:交互件保留
:focus-visible焦点环;浮层支持 Escape 关闭与焦点归还,菜单 / 页签按 Base UI 约定支持方向键。 筛选菜单、拖拽排序、执行树与模型 listbox 等关键键盘流由 Playwright 断言覆盖,见规范示例 · 交互与可访问性。 - RTL:间距、对齐与方向性图标使用逻辑属性 (
ms-*/text-start/rtl:-scale-x-100);通过ThemeProvider或I18nProvider的direction="rtl"驱动,`lint:rtl` 会拦截新增物理类。 - 文案:优先用组件
labels/translate/translatorprops,其次用I18nProvider目录;内置 zh-CN 默认值,en-US 为参考翻译。见Theming · i18n 与 RTL。 - 对比度:高对比度 token、2px 控件边框与 3px 焦点环由主题层统一提供,见Foundations · Contrast。
用法说明
通用加载遮罩/进度条:overlay/inline/bar 三模式;同时导出 LoadingProvider/useLoading 与 ErrorOverlay。