围绕屏幕键盘和手机的安全区域布局,并区分手指和鼠标。
在手机上,页面要为一个人们看不全的屏幕做布局:屏幕键盘盖住底部,iOS 会平移页面让输入框保持可见,刘海或主屏幕指示条占据边缘。bindViewport 会测量所有这些,bindAvoidKeyboard 让一条栏保持在键盘上方。createPointerKind 判断人们用的是手指还是鼠标。
这些辅助函数可以从 @ui-sdk/core 引入。你既可以在原语(primitive)里使用它们,也可以单独使用。
视口
跟随视口
bindViewport 在某个元素上跟踪视口,通常是在根元素上,并报告每次变化:
import { bindViewport } from "@ui-sdk/core"
const stop = bindViewport(document.documentElement, {
onChange: (viewport) =>
console.log(viewport.keyboard, viewport.safeArea.bottom),
})onChange 在开始时运行一次,之后每当有变化时再运行。viewport.keyboard 是输入框获得焦点时键盘的高度,width、height、offsetTop 和 offsetLeft 描述页面上可见的那部分,也就是视觉视口。调用清理函数即可停止。
键盘按屏幕上的实际占用测量,对照输入框获得焦点之前页面还有多少可见空间。无论是 iOS 放大到输入框,还是浏览器为键盘缩小整个页面,这个测量都成立,而单靠页面本身是判断不出来的。viewport.keyboardInset 表示键盘盖住了页面底部的多少,用来摆放东西:iOS 平移页面时会小一些,浏览器改为调整页面大小时则是 0。
import * as React from "react"
import { bindViewport, type ViewportState } from "@ui-sdk/core"
import { Field, FieldControl, FieldLabel } from "@ui-sdk/react/field"
import { useLog } from "./log"
function describe(viewport: ViewportState) {
return `Keyboard ${viewport.keyboard}px, panned ${viewport.offsetTop}px, zoom ${Math.round(viewport.scale * 100)}%`
}
function Example() {
const log = useLog()
const ref = React.useRef<HTMLDivElement>(null)
React.useEffect(() => {
let last = ""
return bindViewport(ref.current!, {
onChange: (viewport) => {
const line = describe(viewport)
if (line !== last) {
log(line)
}
last = line
},
})
}, [log])
return (
<div ref={ref} data-slot="stack">
<Field>
<FieldLabel>Message</FieldLabel>
<FieldControl placeholder="Tap here on a phone" />
</Field>
</div>
)
}
export { Example }在 CSS 里,元素会得到这些变量,键盘打开期间还会得到 data-keyboard:
| 变量 | 内容 |
|---|---|
--keyboard-inset | 键盘盖住页面底部的多少,即 keyboardInset |
--visual-viewport-width | 页面上可见部分的宽度 |
--visual-viewport-height | 它的高度,键盘打开时会缩小 |
--visual-viewport-top | 页面向下平移了多远,比如为了显示输入框 |
当输入框的文字小于 16 像素时,iOS 会在它获得焦点时放大。给输入框至少 font-size: 16px,页面就能保持原来的尺寸。
安全区域
viewport.safeArea 保存刘海、圆角或主屏幕指示条周围的内边距,是供脚本使用的数字。在 CSS 里,直接使用 env(safe-area-inset-bottom)。除非页面用 viewport-fit=cover 绘制到它们下面,否则两者都是 0:
<meta
name="viewport"
content="width=device-width, initial-scale=1, viewport-fit=cover"
/>键盘会盖住主屏幕指示条,但键盘打开时 iOS 仍会报告它的内边距。这时可以去掉底部内边距:
.composer {
padding-bottom: env(safe-area-inset-bottom);
}
.composer[data-keyboard] {
padding-bottom: 0;
}屏幕键盘
让栏保持在键盘上方
输入框获得焦点时,浏览器只把这个输入框滚动到键盘上方的可见区域,别的都不动。笔记下方的状态胶囊、输入框旁边的按钮,或者固定在屏幕底部的工具栏,都会留在键盘盖住的位置。bindAvoidKeyboard 把这样的元素抬高,抬高的距离等于键盘盖住它的部分:
import { bindAvoidKeyboard } from "@ui-sdk/core"
const stop = bindAvoidKeyboard(pill)键盘打开时,固定在底部的栏会上移到刚好在键盘上方。位置更高的元素只移动键盘与它重叠的那部分,位于屏幕下方的元素则原地不动。如果浏览器为键盘缩小页面,比如 Android 使用 interactive-widget=resizes-content,就没有东西被盖住,也没有东西移动。
import * as React from "react"
import { bindAvoidKeyboard } from "@ui-sdk/core"
const groceries = "Groceries\n- oat milk\n- lemons"
const count = (text: string) =>
text.split("\n").filter((line) => line.startsWith("-")).length
function Example() {
const [items, setItems] = React.useState(count(groceries))
const lift = React.useRef<HTMLDivElement>(null)
React.useEffect(() => bindAvoidKeyboard(lift.current!), [])
return (
<div data-slot="groceries">
<textarea
aria-label="Groceries"
rows={4}
defaultValue={groceries}
onChange={(event) => setItems(count(event.target.value))}
/>
<p data-slot="hint">
On a phone, tap the list, then scroll the page with the keyboard open.
</p>
<div ref={lift} data-slot="groceries-lift">
<p aria-live="polite" data-slot="groceries-pill">
{items === 1 ? "1 item" : `${items} items`} · Saved
</p>
</div>
</div>
)
}
export { Example }元素的底边会贴着键盘,所以如果要在两者之间留出空间,就给一个带底部内边距的外层容器绑定,示例就是这么做的。元素上的 translate 归这个辅助函数所有,清理时会把你自己原来的值放回去。键盘打开期间,它会得到 data-keyboard,可以用来去掉安全区域内边距或加上阴影。滚动时它每帧移动一次;不要给 translate 加过渡,否则它会拖在后面。抬升不会改变布局,所以如果栏后面的内容需要保持可见,用 bindViewport 提供的 var(--keyboard-inset) 给它留出空间。
合适的键盘
手机根据输入框选择键盘:inputmode 选择按键,比如验证码用数字键盘,enterkeyhint 选择回车键,比如“next”或“send”,iOS 26 会把它们画成图标。“焦点与按键”里的 inputHints 会为一类输入框填入这些设置,还有自动填充和纠错。
触摸与鼠标
指针种类
createPointerKind 根据 pointer 和 hover 媒体特性,报告主指针是手指还是鼠标、能否悬停,另外还有针对所有已接入指针的 anyPointer 和 anyHover,比如平板上的触控板。像读取偏好一样读取它,在每个框架里用 usePreference:
import { createPointerKind } from "@ui-sdk/core"
import { usePreference } from "@ui-sdk/react/preferences"
const pointerKind = createPointerKind()
const { hover } = usePreference(pointerKind)
// "hover" with a mouse, "none" on a phone, "unknown" on the server它用于行为和内容,比如在无法悬停的地方改为轻点打开。样式直接使用媒体查询,@media (hover: hover) 或 Tailwind 的 pointer-coarse:,它们从首次绘制起就是正确的。
import * as React from "react"
import { createPointerKind } from "@ui-sdk/core"
import { usePreference } from "@ui-sdk/react/preferences"
import { useLog } from "./log"
const pointerKind = createPointerKind()
function Example() {
const log = useLog()
const kind = usePreference(pointerKind)
const [open, setOpen] = React.useState(false)
const hovers = kind.hover === "hover"
React.useEffect(() => {
log(
`pointer ${kind.pointer}, hover ${kind.hover}, anyPointer ${kind.anyPointer}, anyHover ${kind.anyHover}`
)
}, [log, kind.pointer, kind.hover, kind.anyPointer, kind.anyHover])
return (
<div data-slot="pointer-kind">
<button
type="button"
aria-expanded={open}
onPointerEnter={hovers ? () => setOpen(true) : undefined}
onPointerLeave={hovers ? () => setOpen(false) : undefined}
onClick={() => setOpen((open) => !open)}
>
{kind.hover === "unknown"
? "Shipping"
: hovers
? "Shipping (hover for details)"
: "Shipping (tap for details)"}
</button>
<p
role="status"
data-slot="pointer-kind-details"
data-open={open ? "" : undefined}
>
{open && "Free over $50. Arrives in 2 to 4 days."}
</p>
</div>
)
}
export { Example }在服务器上渲染
服务器无法知道设备是什么,所以在服务端渲染和浏览器首次渲染(水合时对照的就是它)中,每个字段都是 "unknown"。水合刚结束时,状态会跟上,依赖它的内容随之变化,比如上面的按钮会多出“(tap for details)”。用媒体查询写的样式不用等:它们从首次绘制起就是正确的。
要从一开始就渲染正确的内容,就为每个请求创建指针种类,并给 initial 一个猜测值。Chromium 浏览器会发送 Sec-CH-UA-Mobile 头,pointerKindOf 能把它转成猜测值:
import { createPointerKind, pointerKindOf } from "@ui-sdk/core"
// On the server, for each request.
const initial = pointerKindOf(request.headers.get("Sec-CH-UA-Mobile"))
// On the server and in the browser, from the same `initial`.
const pointerKind = createPointerKind({ initial })把 initial 和页面的其他数据一起发给浏览器,让它的首次渲染与服务器一致,水合才能对上。为每个请求创建一个,不要放在模块里,这样访客之间不会共享猜测值。
Safari 和 Firefox 不发送这个头,所以 pointerKindOf 在那里什么也不返回,字段会一直是 "unknown",直到水合。会变化的内容在 "unknown" 时要读起来通顺,比如示例里朴素的“Shipping”。如果有缓存保存页面,发送 Vary: Sec-CH-UA-Mobile,让手机和电脑各自拿到对应的副本。
API 参考
| 辅助函数 | 用途 |
|---|---|
bindViewport(el, { onChange }) | 在 CSS 和脚本中跟踪键盘、视觉视口和安全区域。 |
bindAvoidKeyboard(el) | 让元素保持在屏幕键盘上方。 |
createPointerKind({ initial }) | 区分手指和鼠标,并判断能否悬停。 |
pointerKindOf(header) | 在服务器上根据 Sec-CH-UA-Mobile 猜测指针类型。 |