Overlay · 浮层基础
在普通页面中嵌入浅色预览时,从预览打开的浮层应沿用预览的配色与间距。Portal 默认挂到 document.body,分别查找调用位置最近的 data-theme 和 data-density,把两者同步到浮层容器。通过 container 可以指定挂载点,通过 scopeRef 可以明确指定继承来源。
Live example
Open playground ↗App.tsx
'use client'
import { useRef, useState } from 'react'
import { Button, FocusScope, LayerStack, Portal, useDismiss } from '@ancrel/ui'
import '@ancrel/tokens/css'
import '@ancrel/ui/styles.css'
import './App.css'
function Preview({ close }: { close(): void }) {
const ref = useRef<HTMLDivElement>(null)
useDismiss({ open: true, layerRef: ref, onDismiss: close })
return <Portal><div className="ac-PreviewBackdrop">
<div className="ac-PreviewPanel" ref={ref} role="dialog" aria-modal="true" aria-label="Preview">
<FocusScope>
<p>Page preview</p>
<Button onClick={close}>Close preview</Button>
</FocusScope>
</div>
</div></Portal>
}
export default function App() {
const [open, setOpen] = useState(false)
return <section data-theme="light" data-density="compact">
<Button onClick={() => setOpen(true)}>Open preview</Button>
{open && <LayerStack><Preview close={() => setOpen(false)} /></LayerStack>}
</section>
}
Expected behavior
Expected behavior
Open Open preview in the compact light section. Focus moves to Close preview in a portal with the same theme and density. Escape closes the preview and restores focus to the opening button.
示例的遮罩与面板使用以下样式。业务组件可以沿用自己的布局,挂载与键盘行为由上述基础组件提供。
.ac-PreviewBackdrop {
position: fixed;
inset: 0;
z-index: var(--ac-sys-layer-modal);
display: grid;
place-items: center;
background: color-mix(in srgb, var(--ac-sys-surface-canvas) 40%, transparent);
}
.ac-PreviewPanel {
padding: var(--ac-sys-space-section);
color: var(--ac-sys-ink-primary);
background: var(--ac-sys-surface-panel);
border-radius: var(--ac-sys-radius-md);
box-shadow: var(--ac-sys-elevation-overlay);
}
处理嵌套和焦点
为每个逻辑层包一层 LayerStack。将内容元素的 ref 传给 useDismiss,把开关状态传给 open。如果触发按钮还负责切换开关,把它的 ref 传给 triggerRef。最上层收到 Escape 或外部 pointerdown 后,onDismiss 分别收到 escape 或 outside。可在回调中只处理其中一种原因。最上层设置 disabled 时,事件不会关闭下层。
FocusScope 挂载后聚焦 initialFocusRef 或首个可用控件。没有控件时聚焦容器本身。默认在两端循环 Tab,并在卸载后把焦点还给打开前的元素。触发按钮需要在关闭时仍存在。非模态内容可设置 trapped={false}。
Exports
PortalFocusScopeuseDismissLayerStack
Constraints
- Put each nested layer inside a LayerStack and pass the content ref to useDismiss.
- Use a trigger ref when pointer activity on the opening control should be ignored.
Anti-patterns
- Installing an Escape handler for every open layer.
- Incrementing z-index for each nested dialog.