运行你的 CSS 过渡,在面板进出时让它们保持呈现直到结束,并把指针移动变成手势。

这里的过渡跟随状态。状态变化时,你的 CSS 过渡会运行,元素会留在页面里直到动画结束。偏好减少动态效果的人会直接看到终点。bindPanel 管理面板过渡,animateIn 和 animateOut 为 CSS 的进入和退出动画应用状态。

从 @ui-sdk/core 导入这些辅助函数。@ui-sdk/core/gesture 里的函数计算速度、弹簧运动、阻力和方向。这些计算如何用在输入处理函数和动画循环里,由你决定。

要把条目滑到新位置,请用 CSS、View Transitions 或动画库。

面板与呈现

打开与关闭

bindPanel 协调面板的高度、打开和关闭样式以及焦点。你的状态告诉它面板是打开的还是仍在退出:

present: (state, { key }) => state.expanded.includes(key) || state.exiting.includes(key),

让正在关闭的面板保持呈现,直到它的过渡结束。在它的 bind 里,把这些值连接到 bindPanel,并返回清理函数:

bind: (el, { api, key, store }) =>
  bindPanel(el, {
    size: (el, height) => el.style.setProperty("--panel-height", height),
    isOpen: () => store.get().expanded.includes(key),
    isExiting: () => store.get().exiting.includes(key),
    isFindable: () => false,
    opening: () => "animate",
    reveal: () => api.toggle(key),
    trigger: () => el.previousElementSibling as HTMLElement | undefined,
    subscribe: store.subscribe,
    settled: () => {},
    exited: () => store.set({ exiting: store.get().exiting.filter((item) => item !== key) }),
  }),

从 @ui-sdk/core 导入 bindPanel。这个例子里的触发器紧挨在面板前面。exited 从 exiting 中移除这个键,允许面板卸载。

import * as React from "react"
import { bindPanel, definePrimitive } from "@ui-sdk/core"
import { createParts } from "@ui-sdk/react/primitive"

type FaqState = {
  expanded: string[]
  exiting: string[]
}

const without = (list: string[], value: string) =>
  list.filter((other) => other !== value)

const faq = definePrimitive({
  name: "faq",
  state: (): FaqState => ({ expanded: [], exiting: [] }),
  api: (context) => {
    const { store } = context
    return {
      toggle(value: string) {
        const { expanded, exiting } = store.get()
        if (expanded.includes(value)) {
          store.set({
            expanded: without(expanded, value),
            exiting: [...exiting, value],
          })
        } else {
          store.set({
            expanded: [...expanded, value],
            exiting: without(exiting, value),
          })
        }
      },
    }
  },
  slots: (slot) => ({
    root: slot({}),
    trigger: slot<{ value: string }>({
      props: { value: "string" },
      attrs: (state, { id, key }) => ({
        type: "button",
        "aria-expanded": String(state.expanded.includes(key)),
        "aria-controls": `${id}-${key}`,
      }),
      press: ({ api, key }) => api.toggle(key),
    }),
    panel: slot<{ value: string }>({
      props: { value: "string" },
      present: (state, { key }) =>
        state.expanded.includes(key) || state.exiting.includes(key),
      attrs: (_state, { id, key }) => ({ id: `${id}-${key}`, role: "region" }),
      bind: (el, { api, key, store }) =>
        bindPanel(el, {
          size: (el, height) => el.style.setProperty("--panel-height", height),
          isOpen: () => store.get().expanded.includes(key),
          isExiting: () => store.get().exiting.includes(key),
          isFindable: () => false,
          opening: () => "animate",
          reveal: () => api.toggle(key),
          trigger: () => el.previousElementSibling as HTMLElement | undefined,
          subscribe: store.subscribe,
          settled: () => {},
          exited: () =>
            store.set({ exiting: without(store.get().exiting, key) }),
        }),
    }),
  }),
})

const parts = createParts(faq, { root: "div", trigger: "button", panel: "div" })

const Faq = parts.Root

const FaqTrigger = parts.Trigger

const FaqPanel = parts.Panel

const questions = [
  {
    value: "refunds",
    question: "Can I get a refund?",
    answer: "Yes, within 30 days of buying, no questions asked.",
  },
  {
    value: "seats",
    question: "Can I add seats later?",
    answer: "Any time. You pay for the rest of the month only.",
  },
  {
    value: "export",
    question: "Can I export my data?",
    answer: "Everything exports to CSV or JSON from Settings.",
  },
]

function Example() {
  return (
    <div data-slot="panel-frame">
      <Faq>
        {questions.map((item) => (
          <div key={item.value}>
            <FaqTrigger value={item.value}>{item.question}</FaqTrigger>
            <FaqPanel value={item.value}>
              <p>{item.answer}</p>
            </FaqPanel>
          </div>
        ))}
      </Faq>
    </div>
  )
}

export { Example, faq, Faq, FaqPanel, FaqTrigger, type FaqState }
打开一个问题,然后关闭它。答案保持挂载,同时它的高度过渡到零。

用它设置的属性来写过渡:

[data-slot="faq-panel"] {
  height: var(--panel-height);
  overflow: hidden;
  transition: height 200ms ease-out;
}
[data-slot="faq-panel"][data-starting-style],
[data-slot="faq-panel"][data-ending-style] {
  height: 0;
}
@media (prefers-reduced-motion: reduce) {
  [data-slot="faq-panel"] {
    transition: none;
  }
}

过渡期间,size 收到测量出的高度,打开后收到 auto。如果焦点在正在关闭的面板里,trigger() 提供应当改为聚焦的元素。

在页面中查找与立即打开

关闭的面板可以用 hidden="until-found" 保持可搜索。让它保持挂载,并用 hiddenAttrs 控制它的可见性:

attrs: (state, { key }) => hiddenAttrs(state.expanded.includes(key), true),

从 @ui-sdk/core 导入 hiddenAttrs。在面板绑定里启用页面查找,并在 reveal 中打开匹配的小节:

isFindable: () => true,
reveal: () => api.show([key]),
opening: () => store.get().opening,
控制台
import * as React from "react"
import { bindPanel, definePrimitive, hiddenAttrs } from "@ui-sdk/core"
import { createParts } from "@ui-sdk/react/primitive"
import { useLog } from "./log"

type NotesState = {
  expanded: string[]
  exiting: string[]
  opening: "mount" | "instant" | "animate"
}

type NotesOptions = { onSettled?: (value: string, open: boolean) => void }

const without = (list: string[], value: string) =>
  list.filter((other) => other !== value)

const notes = definePrimitive({
  name: "notes",
  options: { onSettled: "callback" },
  state: (_options: NotesOptions): NotesState => ({
    expanded: ["3.0"],
    exiting: [],
    opening: "mount",
  }),
  api: (context) => {
    const { store } = context
    return {
      settle: (value: string, open: boolean) =>
        context.options().onSettled?.(value, open),
      toggle(value: string) {
        const { expanded, exiting } = store.get()
        if (expanded.includes(value)) {
          store.set({
            opening: "animate",
            expanded: without(expanded, value),
            exiting: [...exiting, value],
          })
        } else {
          store.set({
            opening: "animate",
            expanded: [...expanded, value],
            exiting: without(exiting, value),
          })
        }
      },
      show(values: string[]) {
        const { expanded } = store.get()
        store.set({
          opening: "instant",
          expanded: [
            ...expanded,
            ...values.filter((v) => !expanded.includes(v)),
          ],
        })
      },
    }
  },
  slots: (slot) => ({
    root: slot({}),
    trigger: slot<{ value: string }>({
      props: { value: "string" },
      attrs: (state, { id, key }) => ({
        type: "button",
        "aria-expanded": String(state.expanded.includes(key)),
        "aria-controls": `${id}-${key}`,
      }),
      press: ({ api, key }) => api.toggle(key),
    }),
    panel: slot<{ value: string }>({
      props: { value: "string" },
      attrs: (state, { id, key }) => ({
        id: `${id}-${key}`,
        role: "region",
        ...hiddenAttrs(
          state.expanded.includes(key) || state.exiting.includes(key),
          true
        ),
      }),
      bind: (el, { api, key, store }) =>
        bindPanel(el, {
          size: (el, height) => el.style.setProperty("--panel-height", height),
          isOpen: () => store.get().expanded.includes(key),
          isExiting: () => store.get().exiting.includes(key),
          isFindable: () => true,
          opening: () => store.get().opening,
          reveal: () => api.show([key]),
          trigger: () => el.previousElementSibling as HTMLElement | undefined,
          subscribe: store.subscribe,
          settled: (open) => api.settle(key, open),
          exited: () =>
            store.set({ exiting: without(store.get().exiting, key) }),
        }),
    }),
    expand: slot<{ value: string }>({
      props: { value: "string" },
      attrs: () => ({ type: "button" }),
      press: ({ api, key }) => api.show(key.split(" ")),
    }),
  }),
})

const parts = createParts(notes, {
  root: "div",
  trigger: "button",
  panel: "div",
  expand: "button",
})

const Notes = parts.Root

const NotesTrigger = parts.Trigger

const NotesPanel = parts.Panel

const NotesExpand = parts.Expand

const releases = [
  {
    value: "3.0",
    notes:
      "Dark mode follows your system, and the sidebar remembers its width.",
  },
  {
    value: "2.4",
    notes: "Drafts save while you're offline and sync once you're back.",
  },
  { value: "2.3", notes: "Export a board as a PDF, with one page per column." },
]

function Example() {
  const log = useLog()
  return (
    <Notes
      onSettled={(value, open) =>
        log(`Version ${value} ${open ? "opened" : "closed"}`)
      }
    >
      <div data-slot="controls">
        <NotesExpand
          value={releases.map((release) => release.value).join(" ")}
          data-size="sm"
        >
          Open All
        </NotesExpand>
      </div>
      <div data-slot="panel-list">
        {releases.map((release) => (
          <div key={release.value}>
            <NotesTrigger value={release.value}>
              Version {release.value}
            </NotesTrigger>
            <NotesPanel value={release.value}>
              <p>{release.notes}</p>
            </NotesPanel>
          </div>
        ))}
      </div>
    </Notes>
  )
}

export {
  Example,
  notes,
  Notes,
  NotesExpand,
  type NotesOptions,
  NotesPanel,
  NotesTrigger,
  type NotesState,
}
用浏览器的查找命令搜索 offline。在支持该功能的浏览器里,它收起的小节会打开。Open All 会立即显示其余小节。

opening() 对初始就打开的面板返回 "mount";返回 "instant" 会跳过打开动画;也可以返回 "animate"。settled(open) 报告已完成的打开和关闭,包括即时变化,但初始的 "mount" 不会触发它。

单独使用页面查找

对于没有过渡的隐藏内容,把 bindFindable 与 hiddenAttrs 一起使用。它会在需要时恢复 hidden="until-found",并在匹配时调用你的 reveal 回调:

import { bindFindable } from "@ui-sdk/core"

const findable = bindFindable(el, {
  shown: () => store.get().shown,
  findable: () => true,
  reveal: () => api.show(),
})
const unsubscribe = store.subscribe(findable.check)

在槽位的 bind 里,返回一个同时调用 unsubscribe() 和 findable() 的清理函数。

import * as React from "react"
import {
  bindFindable,
  definePrimitive,
  hiddenAttrs,
  supportsHiddenUntilFound,
} from "@ui-sdk/core"
import { createParts } from "@ui-sdk/react/primitive"

type RecipeState = { shown: boolean }

const recipe = definePrimitive({
  name: "recipe",
  state: (): RecipeState => ({ shown: false }),
  api: (context) => ({
    toggle: () => context.store.set({ shown: !context.store.get().shown }),
    show: () => context.store.set({ shown: true }),
  }),
  slots: (slot) => ({
    root: slot<{}, { shown: boolean; findable: boolean }>({
      state: (state) => ({
        shown: state.shown,
        findable: supportsHiddenUntilFound(),
      }),
    }),
    toggle: slot({
      attrs: (state, { id }) => ({
        type: "button",
        "aria-expanded": String(state.shown),
        "aria-controls": `${id}-method`,
      }),
      press: ({ api }) => api.toggle(),
    }),
    method: slot({
      attrs: (state, { id }) => ({
        id: `${id}-method`,
        ...hiddenAttrs(state.shown, true),
      }),
      bind: (el, { api, store }) => {
        const findable = bindFindable(el, {
          shown: () => store.get().shown,
          findable: () => true,
          reveal: () => api.show(),
        })
        const unsubscribe = store.subscribe(findable.check)
        return () => {
          unsubscribe()
          findable()
        }
      },
    }),
  }),
})

const parts = createParts(recipe, {
  root: "div",
  toggle: "button",
  method: "div",
})

const Recipe = parts.Root

const RecipeToggle = parts.Toggle

const RecipeMethod = parts.Method

function Example() {
  return (
    <Recipe>
      {({ shown, findable }) => (
        <>
          <p data-slot="label">Tomato soup</p>
          <RecipeToggle data-size="sm">
            {shown ? "Hide Method" : "Show Method"}
          </RecipeToggle>
          <div data-slot="findable-method">
            <RecipeMethod>
              Soften the onion in butter, add the tomatoes and stock, and simmer
              for twenty minutes. Blend until smooth.
            </RecipeMethod>
          </div>
          <p data-findable data-slot="hint">
            {findable
              ? "Find in page can show the method."
              : "This browser can't find hidden text."}
          </p>
        </>
      )}
    </Recipe>
  )
}

export { Example, recipe, Recipe, RecipeMethod, type RecipeState, RecipeToggle }
在页面里搜索 simmer,在支持该功能的浏览器里显示隐藏的方法。Show Method 和 Hide Method 不依赖浏览器查找也能用。

supportsHiddenUntilFound() 告诉你浏览器是否支持这个功能。无论支持与否,都要提供一个可见的控件来显示内容。

进入与离开

对于只是出现和消失的元素,用 animateIn 和 animateOut:

import { animateIn, animateOut } from "@ui-sdk/core"

const stopEntering = animateIn(el)

当它该离开时,停止尚未完成的进入,开始退出。在完成回调里移除元素:

stopEntering()
const stopExiting = animateOut(el, () => removeToast(key))
import * as React from "react"
import { XIcon } from "lucide-react"
import { animateIn, animateOut, definePrimitive } from "@ui-sdk/core"
import { createParts } from "@ui-sdk/react/primitive"

type ToastsState = {
  toasts: string[]
  leaving: string[]
}

const toasts = definePrimitive({
  name: "toasts",
  state: (): ToastsState => ({ toasts: [], leaving: [] }),
  api: (context) => {
    const { store } = context
    let count = 0
    return {
      add: () =>
        store.set({ toasts: [...store.get().toasts, `toast-${++count}`] }),
      dismiss(key: string) {
        if (!store.get().leaving.includes(key)) {
          store.set({ leaving: [...store.get().leaving, key] })
        }
      },
      remove(key: string) {
        const { toasts, leaving } = store.get()
        store.set({
          toasts: toasts.filter((k) => k !== key),
          leaving: leaving.filter((k) => k !== key),
        })
      },
    }
  },
  slots: (slot) => ({
    root: slot<{}, { toasts: string[] }>({
      state: (state) => ({ toasts: state.toasts }),
    }),
    add: slot({
      attrs: () => ({ type: "button" }),
      press: ({ api }) => api.add(),
    }),
    toast: slot<{ value: string }>({
      props: { value: "string" },
      attrs: () => ({ role: "status" }),
      bind: (el, { api, key, store }) => {
        let stop = animateIn(el)
        const unsubscribe = store.subscribe(() => {
          if (
            !store.get().leaving.includes(key) ||
            el.hasAttribute("data-ending-style")
          ) {
            return
          }
          stop()
          stop = animateOut(el, () => api.remove(key))
        })
        return () => {
          unsubscribe()
          stop()
        }
      },
    }),
    dismiss: slot<{ value: string }>({
      props: { value: "string" },
      attrs: () => ({ type: "button", "aria-label": "Dismiss" }),
      press: ({ api, key }) => api.dismiss(key),
    }),
  }),
})

const parts = createParts(toasts, {
  root: "div",
  add: "button",
  toast: "div",
  dismiss: "button",
})

const Toasts = parts.Root

const ToastsAdd = parts.Add

const Toast = parts.Toast

const ToastDismiss = parts.Dismiss

function Example() {
  return (
    <Toasts>
      {({ toasts }) => (
        <>
          <ToastsAdd data-size="sm">Save</ToastsAdd>
          <div data-slot="scroll">
            {toasts.map((key) => (
              <Toast key={key} value={key}>
                Saved
                <ToastDismiss value={key}>
                  <XIcon aria-hidden="true" />
                </ToastDismiss>
              </Toast>
            ))}
          </div>
        </>
      )}
    </Toasts>
  )
}

export {
  Example,
  Toast,
  ToastDismiss,
  toasts,
  Toasts,
  ToastsAdd,
  type ToastsState,
}
按 Save 添加一条消息。按它的 Dismiss 按钮;淡出之后它会离开页面。

用 CSS 给 data-starting-style 和 data-ending-style 设置样式。退出会等待正在运行的动画,并带有超时,卡住的动画无法让元素永远挂载。两个辅助函数都返回清理函数;元素卸载时调用当前的清理函数。像面板示例那样,在 CSS 里加上减少动态效果的规则。

选项

size(el: HTMLElement, height: string, width: string) => void
Writes the panel's size variables, like --accordion-panel-height: the measured size while animating, auto once open and 0px while closed.
示例: Open and Close
isOpen() => boolean
Whether the panel is open now.
示例: Open and Close
isExiting() => boolean
Whether a closed panel is still shown while it animates out. Keep the panel present while it is.
示例: Open and Close
isFindable() => boolean
Whether a closed panel stays in the page, findable with hidden="until-found".
示例: Find in Page, and Opening at Once
opening() => "mount" | "instant" | "animate"
How the panel opens: as it mounts with the page, at once, or animated.
示例: Find in Page, and Opening at Once
reveal(event: Event) => void
Find in page matched text in the closed panel. Open it here.
示例: Find in Page, and Opening at Once
trigger() => HTMLElement
Where focus goes when the panel closes with focus inside it, like its trigger.
示例: Open and Close
subscribe(listener: () => void) => () => void
Runs listener when the panel's state may have changed, like store.subscribe. Returns the unsubscribe.
示例: Open and Close
settled(open: boolean) => void
The open or close animation finished, or there was none. Never on mount.
示例: Find in Page, and Opening at Once
exited() => void
The exit animation finished, so the panel can leave the page: stop counting it as exiting here.
示例: Open and Close

手势

@ui-sdk/core/gesture 里的函数帮助解读指针移动。输入、状态和动画帧仍由你的组件处理。

甩动与弹簧

指针移动时记录位置,然后在释放时读取速度:

import { createVelocityTracker, projectDistance } from "@ui-sdk/core/gesture"

const tracker = createVelocityTracker()
tracker.add(event.timeStamp, x)

velocity(time) 返回每毫秒的像素数。projectDistance 估算这个速度在物体减速的过程中能把它带多远:

const speed = tracker.velocity(release.timeStamp)
const target = x + projectDistance(speed, 0.994)
import * as React from "react"
import {
  bindDrag,
  createChange,
  css,
  definePrimitive,
  dragThreshold,
  isRTL,
  live,
  type ChangeDetails,
} from "@ui-sdk/core"
import {
  createVelocityTracker,
  projectDistance,
  solveSpring,
} from "@ui-sdk/core/gesture"
import { createParts } from "@ui-sdk/react/primitive"

const speeds = ["Off", "Low", "Medium", "High"]
const last = speeds.length - 1

type FanState = {
  speed: number
  offset: number | null
}

type FanOptions = {
  defaultSpeed?: number
  onSpeedChange?: (
    speed: number,
    details: ChangeDetails<"drag" | "step-key">
  ) => void
}

const clamp = (value: number, min: number, max: number) =>
  Math.min(max, Math.max(min, value))

const fan = definePrimitive({
  name: "fan",
  options: { defaultSpeed: "number", onSpeedChange: "callback" },
  state: (options: FanOptions): FanState => ({
    speed: options.defaultSpeed ?? 0,
    offset: null,
  }),
  live: ["offset"],
  api: (context) => {
    const { store } = context
    const change = createChange(context)
    let stop: (() => void) | undefined
    let frame = 0
    const settle = () => {
      cancelAnimationFrame(frame)
      store.set({ offset: null })
    }
    context.onDestroy(() => {
      stop?.()
      cancelAnimationFrame(frame)
    })
    return {
      pointerdown(event: PointerEvent, thumb: HTMLElement) {
        const track = thumb.parentElement
        if (event.button !== 0 || !track) {
          return
        }
        settle()
        const span =
          (track.clientWidth - thumb.offsetWidth) * (isRTL(track) ? -1 : 1)
        const from = store.get().speed / last
        const velocity = createVelocityTracker()
        stop = bindDrag(thumb, event, {
          threshold: dragThreshold,
          cancelOnEscape: true,
          onMove: ({ x, event: move }) => {
            velocity.add(move.timeStamp, x)
            store.set({
              offset: clamp(from + (x - event.clientX) / span, 0, 1),
            })
          },
          onEnd: (end, canceled) => {
            stop = undefined
            const at = store.get().offset
            if (canceled || at === null) {
              return settle()
            }
            const v = velocity.velocity(end.timeStamp) / span
            const target = Math.round(
              clamp(at + projectDistance(v, 0.994), 0, 1) * last
            )
            change("speed", target, { reason: "drag", event: end })
            const spring = solveSpring(0.4, 0.8, at - target / last, v)
            const start = performance.now()
            const tick = () => {
              const t = performance.now() - start
              const done = t > 1000 || Math.abs(spring.position(t) * span) < 0.5
              if (done) {
                return settle()
              }
              store.set({ offset: target / last + spring.position(t) })
              frame = requestAnimationFrame(tick)
            }
            frame = requestAnimationFrame(tick)
          },
        })
      },
      keydown(event: KeyboardEvent, el: HTMLElement) {
        const step = { ArrowLeft: -1, ArrowRight: 1, Home: -last, End: last }[
          event.key
        ]
        if (!step) {
          return
        }
        event.preventDefault()
        settle()
        const flip = event.key.startsWith("Arrow") && isRTL(el) ? -1 : 1
        change("speed", clamp(store.get().speed + step * flip, 0, last), {
          reason: "step-key",
          event,
        })
      },
    }
  },
  slots: (slot) => ({
    root: slot<{}, { speed: number }>({
      state: (state) => ({ speed: state.speed }),
      attrs: () => ({ style: css({ position: "relative" }) }),
    }),
    thumb: slot({
      attrs: (state) => ({
        role: "slider",
        tabindex: "0",
        "aria-valuemin": "0",
        "aria-valuemax": String(last),
        "aria-valuenow": String(state.speed),
        "aria-valuetext": speeds[state.speed],
      }),
      live: live<FanState, any, {}>((state) => ({
        "data-dragging": state.offset === null ? undefined : "",
        style: css({
          position: "absolute",
          "inset-inline-start": `calc(${state.offset ?? state.speed / last} * (100% - var(--thumb-size)))`,
          "touch-action": "none",
        }),
      })),
      on: {
        pointerdown: (event, { el, api }) => api.pointerdown(event, el!),
        keydown: (event, { el, api }) => api.keydown(event, el!),
      },
    }),
  }),
})

const parts = createParts(fan, { root: "div", thumb: "div" })

const Fan = parts.Root

const FanThumb = parts.Thumb

function Example() {
  return (
    <div data-slot="stack">
      <Fan>
        {({ speed }) => (
          <FanThumb aria-label="Fan speed">{speeds[speed]}</FanThumb>
        )}
      </Fan>
      <div data-slot="gesture-scale">
        {speeds.map((speed) => (
          <span key={speed}>{speed}</span>
        ))}
      </div>
    </div>
  )
}

export { Example, fan, Fan, FanThumb, type FanOptions, type FanState }
慢慢拖动风扇控件,然后快速甩一下。释放得越快,走得越远。Left 和 Right 也能改变速度。

要稳定到一个目标上,创建一个弹簧,并在每一帧读取它的位置:

import { solveSpring } from "@ui-sdk/core/gesture"

const spring = solveSpring(0.4, 0.8, x - target, speed)
const position = target + spring.position(elapsedMilliseconds)

第一个参数是以秒为单位的响应时间。第二个是阻尼比:1 会平稳停下而不振荡;更低的值允许回弹。剩下的参数是初始位移和速度。position(t) 和 velocity(t) 接受经过的毫秒数。在动画循环里,判断弹簧是否已稳定之前,要同时检查位置和速度。

越过边缘

rubberBand 让拉动在越过边缘越远时阻力越大:

import { rubberBand } from "@ui-sdk/core/gesture"

const offset = rubberBand(distancePastEdge, list.clientHeight)
控制台
import * as React from "react"
import { bindDrag, css, definePrimitive, live } from "@ui-sdk/core"
import {
  createVelocityTracker,
  rubberBand,
  solveSpring,
} from "@ui-sdk/core/gesture"
import { createParts } from "@ui-sdk/react/primitive"
import { useLog } from "./log"

type InboxState = {
  pull: number
  refreshing: boolean
  refreshed: number
}

type InboxOptions = {
  onRelease?: (speed: number) => void
  onRefresh?: (count: number) => void
}

const hold = 48

const inbox = definePrimitive({
  name: "inbox",
  options: { onRelease: "callback", onRefresh: "callback" },
  state: (_options: InboxOptions): InboxState => ({
    pull: 0,
    refreshing: false,
    refreshed: 0,
  }),
  live: ["pull"],
  api: (context) => {
    const { store } = context
    const velocity = createVelocityTracker({ maxSpeed: 4 })
    let stop: (() => void) | undefined
    let frame = 0
    let timer: ReturnType<typeof setTimeout> | undefined

    function springTo(to: number, speed: number) {
      cancelAnimationFrame(frame)
      const spring = solveSpring(0.35, 1, store.get().pull - to, speed)
      const start = performance.now()
      const tick = () => {
        const t = performance.now() - start
        const done = t > 800 || Math.abs(spring.position(t)) < 0.5
        store.set({ pull: done ? to : to + spring.position(t) })
        if (!done) {
          frame = requestAnimationFrame(tick)
        }
      }
      frame = requestAnimationFrame(tick)
    }

    function refresh(speed = 0) {
      store.set({ refreshing: true })
      springTo(hold, speed)
      timer = setTimeout(() => {
        const refreshed = store.get().refreshed + 1
        store.set({ refreshing: false, refreshed })
        context.options().onRefresh?.(refreshed)
        springTo(0, 0)
      }, 800)
    }

    context.onDestroy(() => {
      stop?.()
      cancelAnimationFrame(frame)
      clearTimeout(timer)
    })
    return {
      refresh: () => !store.get().refreshing && refresh(),
      pointerdown(event: PointerEvent, el: HTMLElement) {
        if (event.button !== 0 || store.get().refreshing) {
          return
        }
        cancelAnimationFrame(frame)
        velocity.reset()
        const from = store.get().pull
        stop = bindDrag(el, event, {
          threshold: 4,
          onMove: ({ y, event: move }) => {
            const pulled = y - event.clientY + from
            const pull = rubberBand(pulled, el.clientHeight)
            velocity.add(move.timeStamp, pull)
            store.set({ pull })
          },
          onEnd: (end, canceled) => {
            stop = undefined
            const speed = canceled ? 0 : velocity.velocity(end.timeStamp)
            context.options().onRelease?.(speed)
            if (!canceled && (store.get().pull > hold || speed > 0.6)) {
              refresh(speed)
            } else {
              springTo(0, speed)
            }
          },
        })
      },
    }
  },
  slots: (slot) => ({
    root: slot<{}, { refreshing: boolean }>({
      state: (state) => ({ refreshing: state.refreshing }),
    }),
    list: slot({
      attrs: (state) => ({
        role: "list",
        "aria-busy": state.refreshing ? "true" : undefined,
      }),
      live: live<InboxState, any, {}>((state) => ({
        "data-pulling": state.pull > 0 ? "" : undefined,
        style: css({
          transform: `translateY(${state.pull}px)`,
          "touch-action": "none",
        }),
      })),
      on: { pointerdown: (event, { el, api }) => api.pointerdown(event, el!) },
    }),
    refresh: slot({
      attrs: () => ({ type: "button" }),
      press: ({ api }) => api.refresh(),
    }),
  }),
})

const parts = createParts(inbox, {
  root: "div",
  list: "div",
  refresh: "button",
})

const Inbox = parts.Root

const InboxList = parts.List

const InboxRefresh = parts.Refresh

const messages = [
  "Lunch on Friday?",
  "Your invoice is ready",
  "Design review notes",
  "Welcome aboard",
]

function Example() {
  const log = useLog()
  return (
    <Inbox
      onRelease={(speed) => log(`Let go at ${speed.toFixed(2)} px/ms`)}
      onRefresh={(count) =>
        log(`Refreshed ${count} ${count === 1 ? "time" : "times"}`)
      }
    >
      {({ refreshing }) => (
        <>
          <div data-slot="controls">
            <InboxRefresh data-size="sm">Refresh</InboxRefresh>
          </div>
          <div data-slot="gesture-frame">
            <p>{refreshing ? "Refreshing…" : "Pull to refresh"}</p>
            <InboxList aria-label="Inbox">
              {messages.map((message) => (
                <div key={message} role="listitem">
                  {message}
                </div>
              ))}
            </InboxList>
          </div>
        </>
      )}
    </Inbox>
  )
}

export {
  Example,
  inbox,
  Inbox,
  InboxList,
  type InboxOptions,
  InboxRefresh,
  type InboxState,
}
把收件箱往下拉得足够远来刷新,然后释放。试试短距离拉动后停住再释放;它会回位而不刷新。按按钮也能刷新。

拉动越远,结果越接近传入的尺寸。每次手势开始时调用 tracker.reset()。staleAfter 让过旧的采样读作零,这样释放前停住不动就不会被当成一次新的甩动。

一笔指向哪个方向

sectorOf 把拖动方向变成一个带编号的扇区。分成四个扇区时,0 是上,然后是右、下、左:

import { sectorOf } from "@ui-sdk/core/gesture"

const index = sectorOf(dx, dy, 4) // -1 near the center
import * as React from "react"
import {
  FlameIcon,
  FrownIcon,
  HeartIcon,
  LaughIcon,
  PartyPopperIcon,
  ThumbsUpIcon,
} from "lucide-react"
import { bindDrag, css, definePrimitive } from "@ui-sdk/core"
import { sectorOf } from "@ui-sdk/core/gesture"
import { createParts } from "@ui-sdk/react/primitive"

const icons = {
  Like: ThumbsUpIcon,
  Celebrate: PartyPopperIcon,
  Laugh: LaughIcon,
  Fire: FlameIcon,
  Sad: FrownIcon,
  Love: HeartIcon,
}

const reactions = Object.keys(icons) as (keyof typeof icons)[]

const start = 1 / 12

function sectorPoint(index: number, count: number, radius: number, start = 0) {
  const angle = (index / Math.max(count, 1) + start) * 2 * Math.PI
  return {
    x: Math.round(Math.sin(angle) * radius),
    y: Math.round(-Math.cos(angle) * radius),
  }
}

type ReactState = {
  pointing: number
  picked: string | null
}

const react = definePrimitive({
  name: "react",
  state: (): ReactState => ({ pointing: -1, picked: null }),
  api: (context) => {
    const { store } = context
    let stop: (() => void) | undefined
    context.onDestroy(() => stop?.())
    return {
      pick: (index: number) =>
        store.set({ picked: reactions[index], pointing: -1 }),
      pointerdown(event: PointerEvent, el: HTMLElement) {
        if (event.button !== 0) {
          return
        }
        event.preventDefault()
        stop = bindDrag(el, event, {
          cancelOnEscape: true,
          onMove: ({ x, y }) =>
            store.set({
              pointing: sectorOf(
                x - event.clientX,
                y - event.clientY,
                reactions.length,
                {
                  deadZone: 24,
                  start,
                }
              ),
            }),
          onEnd: (_end, canceled) => {
            stop = undefined
            const { pointing } = store.get()
            if (!canceled && pointing !== -1) {
              store.set({ picked: reactions[pointing] })
            }
            store.set({ pointing: -1 })
          },
        })
      },
    }
  },
  slots: (slot) => ({
    root: slot<{}, { picked: string | null }>({
      state: (state) => ({ picked: state.picked }),
      attrs: () => ({ style: css({ position: "relative" }) }),
    }),
    handle: slot({
      attrs: () => ({
        "aria-hidden": "true",
        style: css({ "touch-action": "none" }),
      }),
      on: { pointerdown: (event, { el, api }) => api.pointerdown(event, el!) },
    }),
    reaction: slot<{ value: string }>({
      props: { value: "string" },
      attrs: (state, { props }) => {
        const index = reactions.indexOf(props.value as keyof typeof icons)
        const { x, y } = sectorPoint(index, reactions.length, 72, start)
        return {
          type: "button",
          "aria-label": props.value,
          "aria-pressed": String(state.picked === props.value),
          "data-pointing": state.pointing === index ? "" : undefined,
          style: css({
            position: "absolute",
            left: "50%",
            top: "50%",
            translate: `${x}px ${y}px`,
          }),
        }
      },
      press: ({ api, props }) =>
        api.pick(reactions.indexOf(props.value as keyof typeof icons)),
    }),
  }),
})

const parts = createParts(react, {
  root: "div",
  handle: "div",
  reaction: "button",
})

const ReactionRing = parts.Root

const ReactionHandle = parts.Handle

const Reaction = parts.Reaction

function Example() {
  return (
    <ReactionRing>
      {({ picked }) => {
        const Picked = picked ? icons[picked as keyof typeof icons] : null
        return (
          <>
            <ReactionHandle>
              {Picked ? <Picked aria-hidden="true" /> : null}
            </ReactionHandle>
            {reactions.map((reaction) => {
              const Icon = icons[reaction]
              return (
                <Reaction key={reaction} value={reaction}>
                  <Icon aria-hidden="true" />
                </Reaction>
              )
            })}
          </>
        )
      }}
    </ReactionRing>
  )
}

export {
  Example,
  react,
  Reaction,
  ReactionHandle,
  ReactionRing,
  type ReactState,
}
从中心朝某个反应拖动并释放来选择它。短距离划动不会选中任何东西。也可以直接点击一个反应。

在 deadZone 内,sectorOf 返回 -1;默认是 18 像素。使用索引之前先检查这一点。传入以圈为单位的 start 偏移,可以旋转扇区。

选项

horizon?number
How far back samples count, in ms before the newest. Defaults to 70.
示例: Past an Edge
staleAfter?number
How old the newest sample can be, in ms, before the pointer counts as stopped and reads 0. Defaults to 40.
示例: Past an Edge
maxSpeed?number
The fastest the tracker reads, in px/ms either way. Defaults to 8.
示例: Past an Edge
capacity?number
How many samples it keeps. Defaults to 20, enough for the horizon at 240 Hz.
示例: Past an Edge