Skip to content

DeepSeek Harness Tauri 桌面版 | Only 8mb installer, zero environment setup, preset plugins, Windows / macOS / Linux.

feat(pet): fling the pet window after a fast drag release (#887)

Mao Mrda057eef1fc4
diff --git a/src/pet/app.tsx b/src/pet/app.tsx
index 9f2ca0ce..51a032b4 100644
--- a/src/pet/app.tsx
+++ b/src/pet/app.tsx
@@ -9,6 +9,7 @@ import { Hint } from '@/ui/pet/hint'
import { useWakelockRelease } from '../hooks/use-wakelock-release'
import { PET_BASE_WIDTH, PET_DSH_ASPECT } from './constants'
import { useBubbleTracker } from './hooks/use-bubble-tracker'
+import { usePetPhysics } from './hooks/use-pet-physics'
import { usePetSource } from './hooks/use-pet-source'
import { normalizeSizePercent, usePetStatus } from './hooks/use-pet-status'
import { usePetWindowSize } from './hooks/use-pet-window'
@@ -42,6 +43,8 @@ export function App() {
const width = (source?.width ?? PET_BASE_WIDTH) * normalizeSizePercent(status?.pet_size) / 100
useBubbleTracker(pet, source)
+ // 甩动:松手后按窗口轨迹估速请求组件甩出,飞行积分与落地 Q 弹都在宿主(见 hook 文档)。
+ const onFling = usePetPhysics(pet, source?.kind)
usePetWindowSize(width, source?.aspect ?? PET_DSH_ASPECT, visible)
useOmitIgnoreCursorEvents(hitboxRef)
useEventListener('contextmenu', event => event.preventDefault())
@@ -67,6 +70,7 @@ export function App() {
motion={source?.kind === 'codex' ? motion : undefined}
size={width}
dragging={draggable.dragging}
+ onFling={onFling}
cache={true}
hidden={!visible}
hitboxRef={hitboxRef}
diff --git a/src/pet/hooks/use-pet-physics.helpers.test.ts b/src/pet/hooks/use-pet-physics.helpers.test.ts
new file mode 100644
index 00000000..c005d6c5
--- /dev/null
+++ b/src/pet/hooks/use-pet-physics.helpers.test.ts
@@ -0,0 +1,221 @@
+import type { PhysicsParams } from 'dsh-pet-component'
+import type { DragSample } from './use-pet-physics.helpers'
+import { describe, expect, it } from 'vitest'
+import { bodyBounds, estimateReleaseVelocity, stepThrow } from './use-pet-physics.helpers'
+
+/** 组件默认参数(`dsh-pet-component` 的 `PhysicsParams` 默认值)。 */
+const PHYSICS: PhysicsParams = {
+ gravity: 1400,
+ restitution: 0.78,
+ groundFriction: 2.5,
+ ceilingBounce: true,
+ throwPower: 1,
+ petCollision: false,
+}
+
+/** 无重力无摩擦的参数:把「位移/边界」与「重力/摩擦」分开验证。 */
+const FREE: PhysicsParams = { ...PHYSICS, gravity: 0, groundFriction: 0 }
+
+/** 足够大的舞台:不触发任何边界分支。 */
+const OPEN = { minX: -1e6, minY: -1e6, maxX: 1e6, maxY: 1e6 }
+
+/** 按端点均速/峰值各半后指数软限速算出的期望速度(与实现同式,用来锚定量级)。 */
+function softCapped(speed: number): number {
+ return 3600 * (1 - Math.exp(-speed / 3600))
+}
+
+describe('estimateReleaseVelocity', () => {
+ it('向右甩的松手给出正 vx,方向按位移归一化', () => {
+ const trail: DragSample[] = [
+ { t: 0, x: 0, y: 100 },
+ { t: 40, x: 200, y: 100 },
+ { t: 80, x: 400, y: 100 },
+ { t: 120, x: 600, y: 100 },
+ ]
+
+ const velocity = estimateReleaseVelocity(trail, 140, 1)
+
+ // 端点均速 5000 px/s,分段峰值同为 5000,软限速后约 2702 px/s(上限 3600)。
+ expect(velocity?.vx).toBeCloseTo(softCapped(5000), 4)
+ expect(velocity?.vy).toBe(0)
+ })
+
+ it('向左甩的松手给出负 vx', () => {
+ const trail: DragSample[] = [
+ { t: 0, x: 1000, y: 100 },
+ { t: 100, x: 0, y: 100 },
+ ]
+
+ expect(estimateReleaseVelocity(trail, 110, 1)?.vx).toBeLessThan(0)
+ })
+
+ it('低于 500 CSS px/s 的松手不甩(返回 null)', () => {
+ const trail: DragSample[] = [
+ { t: 0, x: 0, y: 100 },
+ { t: 100, x: 10, y: 100 },
+ ]
+
+ expect(estimateReleaseVelocity(trail, 110, 1)).toBeNull()
+ })
+
+ it('末尾样本早于 150ms 前时返回 null(松手时刻已经过时)', () => {
+ const trail: DragSample[] = [
+ { t: 0, x: 0, y: 0 },
+ { t: 100, x: 2000, y: 0 },
+ ]
+
+ expect(estimateReleaseVelocity(trail, 400, 1)).toBeNull()
+ })
+
+ it('轨迹跨度不足 20ms 时返回 null(采不出方向)', () => {
+ const trail: DragSample[] = [
+ { t: 0, x: 0, y: 0 },
+ { t: 10, x: 100, y: 0 },
+ ]
+
+ expect(estimateReleaseVelocity(trail, 15, 1)).toBeNull()
+ })
+
+ it('速度有硬上限:再快的甩动也不会超过 3600 CSS px/s', () => {
+ const trail: DragSample[] = [
+ { t: 0, x: 0, y: 0 },
+ { t: 25, x: 10000, y: 0 },
+ ]
+
+ const velocity = estimateReleaseVelocity(trail, 30, 1)
+
+ expect(Math.hypot(velocity?.vx ?? 0, velocity?.vy ?? 0)).toBeLessThanOrEqual(3600)
+ expect(Math.hypot(velocity?.vx ?? 0, velocity?.vy ?? 0)).toBeGreaterThan(3500)
+ })
+
+ it('throwPower 线性缩放最终速度', () => {
+ const trail: DragSample[] = [
+ { t: 0, x: 0, y: 100 },
+ { t: 100, x: 1000, y: 100 },
+ ]
+
+ const half = estimateReleaseVelocity(trail, 110, 0.5)
+ const full = estimateReleaseVelocity(trail, 110, 1)
+
+ expect(half?.vx).toBeCloseTo((full?.vx ?? 0) / 2, 6)
+ })
+
+ it('完全静止的轨迹返回 null(拖到一半停住再松手不甩)', () => {
+ const trail: DragSample[] = [
+ { t: 0, x: 300, y: 100 },
+ { t: 50, x: 300, y: 100 },
+ { t: 100, x: 300, y: 100 },
+ ]
+
+ expect(estimateReleaseVelocity(trail, 110, 1)).toBeNull()
+ })
+})
+
+describe('bodyBounds', () => {
+ it('dsh 用几何高度里 330/360 的贴地锚点算脚底(video 底部 30 是留白)', () => {
+ const bounds = bodyBounds(
+ { x: 0, y: 0, width: 100, height: 360, body: { left: 10, top: 0, right: 90, bottom: 360 } },
+ 800,
+ 1000,
+ true,
+ )
+
+ expect(bounds).toEqual({ minX: -10, maxX: 710, minY: 0, maxY: 1000 - 330 })
+ })
+
+ it('codex 用真实 hitbox 的底边算脚底', () => {
+ const bounds = bodyBounds(
+ { x: 5, y: 20, width: 100, height: 300, body: { left: 15, top: 20, right: 95, bottom: 300 } },
+ 800,
+ 1000,
+ false,
+ )
+
+ expect(bounds).toEqual({ minX: -10, maxX: 710, minY: 0, maxY: 1000 - 280 })
+ })
+})
+
+describe('stepThrow', () => {
+ it('重力让下坠速度逐帧增大,水平速度不受影响', () => {
+ const next = stepThrow({ x: 0, y: 0, vx: 100, vy: 0 }, 0.016, OPEN, PHYSICS)
+
+ expect(next.vy).toBeCloseTo(1400 * 0.016, 6)
+ expect(next.vx).toBeCloseTo(100, 6)
+ expect(next.x).toBeCloseTo(100 * 0.016, 6)
+ })
+
+ it('左墙夹回边界并反向衰减横向速度', () => {
+ const next = stepThrow({ x: 0, y: 500, vx: -1000, vy: 0 }, 0.016, { ...OPEN, minX: 0, maxY: 900 }, FREE)
+
+ expect(next.x).toBe(0)
+ expect(next.vx).toBeCloseTo(1000 * 0.78, 6)
+ })
+
+ it('右墙夹回边界并反向衰减横向速度', () => {
+ const next = stepThrow({ x: 100, y: 500, vx: 1000, vy: 0 }, 0.016, { ...OPEN, maxX: 100, maxY: 900 }, FREE)
+
+ expect(next.x).toBe(100)
+ expect(next.vx).toBeCloseTo(-1000 * 0.78, 6)
+ })
+
+ it('ceilingBounce 关闭时不夹天花板,宠物可以划过屏幕上方', () => {
+ const next = stepThrow({ x: 0, y: 10, vx: 0, vy: -1000 }, 0.016, { ...OPEN, minY: 0 }, { ...FREE, ceilingBounce: false })
+
+ expect(next.y).toBeCloseTo(10 - 16, 6)
+ expect(next.vy).toBeCloseTo(-1000, 6)
+ })
+
+ it('ceilingBounce 开启时天花板反弹', () => {
+ const next = stepThrow({ x: 0, y: 10, vx: 0, vy: -1000 }, 0.016, { ...OPEN, minY: 0 }, FREE)
+
+ expect(next.y).toBe(0)
+ expect(next.vy).toBeCloseTo(1000 * 0.78, 6)
+ })
+
+ it('跨过地面的那一帧才算落地,撞击速度取积分前的下坠速度', () => {
+ const next = stepThrow({ x: 0, y: 90, vx: 0, vy: 1000 }, 0.016, { ...OPEN, maxY: 100 }, FREE)
+
+ expect(next.landed).toBe(true)
+ expect(next.impactSpeed).toBe(1000)
+ expect(next.y).toBe(100)
+ expect(next.vy).toBeCloseTo(-1000 * 0.78, 6)
+ })
+
+ it('已经贴地滑动的一帧不算落地(不会连续触发 Q 弹)', () => {
+ const next = stepThrow({ x: 0, y: 100, vx: 500, vy: 0 }, 0.016, { ...OPEN, maxY: 100 }, FREE)
+
+ expect(next.landed).toBe(false)
+ })
+
+ it('下坠速度小于 40 px/s 时贴地停住,不再弹', () => {
+ const next = stepThrow({ x: 0, y: 99.5, vx: 0, vy: 10 }, 0.05, { ...OPEN, maxY: 100 }, FREE)
+
+ expect(next.y).toBe(100)
+ expect(next.vy).toBe(0)
+ })
+
+ it('地面摩擦按帧长削减横向速度', () => {
+ const next = stepThrow({ x: 0, y: 100, vx: 1000, vy: 0 }, 0.05, { ...OPEN, maxY: 100 }, { ...FREE, groundFriction: 2.5 })
+
+ expect(next.vx).toBeCloseTo(1000 * (1 - 2.5 * 0.05), 6)
+ })
+
+ it('贴地且速度极小时进入静止态(宿主据此停掉飞行循环)', () => {
+ const next = stepThrow({ x: 0, y: 100, vx: 1, vy: 0 }, 0.016, { ...OPEN, maxY: 100 }, FREE)
+
+ expect(next.atRest).toBe(true)
+ })
+
+ it('单帧步长上限 50ms:切回前台的一大跳不会穿墙', () => {
+ const next = stepThrow({ x: 0, y: 0, vx: 100, vy: 0 }, 5, OPEN, FREE)
+
+ expect(next.x).toBeCloseTo(100 * 0.05, 6)
+ })
+
+ it('舞台比宠物本体还窄时横向钉住(畸形几何不抖)', () => {
+ const next = stepThrow({ x: 0, y: 500, vx: 800, vy: 0 }, 0.016, { minX: 50, minY: 0, maxX: 50, maxY: 900 }, FREE)
+
+ expect(next.x).toBe(50)
+ expect(next.vx).toBe(0)
+ })
+})
diff --git a/src/pet/hooks/use-pet-physics.helpers.ts b/src/pet/hooks/use-pet-physics.helpers.ts
new file mode 100644
index 00000000..addfb182
--- /dev/null
+++ b/src/pet/hooks/use-pet-physics.helpers.ts
@@ -0,0 +1,167 @@
+import type { PetGeometry, PetVelocity, PhysicsParams } from 'dsh-pet-component'
+
+/**
+ * 宿主侧甩动物理:松手估速、边界换算与飞行积分(纯函数,窗口移动在 `use-pet-physics.ts`)。
+ *
+ * dsh-pet-component 只负责「请求甩出 + 即时几何 + 参数校验」,物理全在宿主(见组件
+ * `docs/spec/pet-interactions.md` 的职责划分)。这里逐条对齐组件参考实现的
+ * `playground/src/physics.ts`,单位与组件一致:**CSS px 与 CSS px/s**;桌宠宿主把舞台
+ * 换成显示器工作区(见 `use-pet-physics.ts` 的坐标换算)。
+ */
+
+/** 一次拖拽采样:`t` 是 `performance.now()` 毫秒,`x`/`y` 是窗口的 CSS px 位置。 */
+export interface DragSample {
+ t: number
+ x: number
+ y: number
+}
+
+/** 飞行状态:位置 + 速度(`PetVelocity` 是组件协议里的最终绝对速度)。 */
+export interface ThrowState extends PetVelocity {
+ x: number
+ y: number
+}
+
+/** 飞行边界(舞台坐标系的左上/右下 AABB)。 */
+export interface ThrowBounds {
+ minX: number
+ minY: number
+ maxX: number
+ maxY: number
+}
+
+/** 一帧积分结果:`landed`/`impactSpeed` 用来触发落地 Q 弹(`pet.squash`)。 */
+export interface ThrowStep extends ThrowState {
+ atRest: boolean
+ landed: boolean
+ impactSpeed: number
+}
+
+/**
+ * 松手估速:端点均速与分段峰值各占一半,末段加速再给最多 60% 增益,最后指数软限速
+ * 并乘 `throwPower`。轨迹太旧(末尾样本早于 150ms 前)、跨度不足 20ms、或结果低于
+ * 500 CSS px/s 时返回 null —— 宿主据此判断「这一下不甩」,组件侧没有补偿逻辑。
+ */
+export function estimateReleaseVelocity(trail: readonly DragSample[], now: number, throwPower: number): PetVelocity | null {
+ const recent = trail.filter(sample => sample.t >= now - 150)
+ const first = recent[0]
+ const last = recent.at(-1)
+ if (!first || !last || now - last.t > 150 || last.t - first.t < 20)
+ return null
+
+ const dt = (last.t - first.t) / 1000
+ const vx = (last.x - first.x) / dt
+ const vy = (last.y - first.y) / dt
+ const baseSpeed = Math.hypot(vx, vy)
+ if (baseSpeed < 1e-6)
+ return null
+
+ // 相邻样本间隔够大才算一段:端点均速会把「拖到一半突然甩出去」摊平,分段峰值补回来。
+ const segments: { speed: number, end: number }[] = []
+ let previous = first
+ for (const sample of recent.slice(1)) {
+ if (sample.t - previous.t >= 8) {
+ segments.push({
+ speed: Math.hypot(sample.x - previous.x, sample.y - previous.y) / (sample.t - previous.t) * 1000,
+ end: sample.t,
+ })
+ previous = sample
+ }
+ }
+
+ const peak = segments.length > 0 ? Math.max(...segments.map(segment => segment.speed)) : baseSpeed
+ const startSegment = segments[0]
+ const endSegment = segments.at(-1)
+ // 末段相对首段加速得越猛,甩得越远(8000 px/s² 及以上给满增益,上限 +60%)。
+ const acceleration = startSegment && endSegment && segments.length >= 2
+ ? (endSegment.speed - startSegment.speed) / Math.max((endSegment.end - startSegment.end) / 1000, 0.02)
+ : 0
+ const beforeClamp = (baseSpeed * 0.5 + peak * 0.5) * (1 + Math.min(1, Math.max(0, acceleration) / 8000) * 0.6)
+ const speed = 3600 * (1 - Math.exp(-beforeClamp / 3600)) * throwPower
+ if (speed < 500)
+ return null
+
+ return { vx: vx / baseSpeed * speed, vy: vy / baseSpeed * speed }
+}
+
+/**
+ * 把组件给的几何换算成飞行边界(舞台本地坐标)。
+ *
+ * 横向按真实 hitbox(`geometry.body`)算:透明边可以出界,宠物本体不出界。纵向的
+ * 「脚底」按渲染器分:dsh 的 video 高 360 里只有 330 是本体,底部 30 是留白,贴地
+ * 用几何高度而不是 hitbox;codex 的 hitbox 底边就是脚底。
+ */
+export function bodyBounds(geometry: PetGeometry, width: number, height: number, dsh: boolean): ThrowBounds {
+ const feet = dsh ? geometry.height * 330 / 360 : geometry.body.bottom - geometry.y
+ return {
+ minX: -(geometry.body.left - geometry.x),
+ maxX: width - (geometry.body.right - geometry.x),
+ minY: 0,
+ maxY: height - feet,
+ }
+}
+
+/**
+ * 推进一帧飞行:重力 + 位移 + 左右墙(与可选天花板)反弹 + 落地与地面摩擦。
+ *
+ * `dt` 夹在 50ms 以内:窗口最小化、系统卡顿后 `delta` 可能是一大跳,按真实间隔积分
+ * 会直接穿墙。落地判定要看**积分前**的 `state.y`(这一帧是否跨过地面),`impactSpeed`
+ * 也取积分前的下坠速度 —— 落地 Q 弹的力度是撞击瞬间的,不是衰减后的。
+ */
+export function stepThrow(state: ThrowState, delta: number, bounds: ThrowBounds, physics: PhysicsParams): ThrowStep {
+ const dt = Math.min(0.05, Math.max(0, delta))
+ const maxX = Math.max(bounds.minX, bounds.maxX)
+ const maxY = Math.max(bounds.minY, bounds.maxY)
+ let { x, y, vx, vy } = state
+ let bounced = false
+
+ vy += physics.gravity * dt
+ x += vx * dt
+ y += vy * dt
+
+ if (maxX === bounds.minX) {
+ // 舞台比宠物本体还窄(畸形几何):横向钉住,别让它左右抖。
+ x = maxX
+ vx = 0
+ }
+ else if (x < bounds.minX) {
+ x = bounds.minX
+ vx = Math.abs(vx) * physics.restitution
+ bounced = true
+ }
+ else if (x > maxX) {
+ x = maxX
+ vx = -Math.abs(vx) * physics.restitution
+ bounced = true
+ }
+
+ // 天花板默认反弹;`ceilingBounce: false` 时不夹顶,让宠物自然划过屏幕上方。
+ if (y < bounds.minY && physics.ceilingBounce) {
+ y = bounds.minY
+ vy = Math.abs(vy) * physics.restitution
+ bounced = true
+ }
+
+ const landed = state.y < maxY - 1 && y >= maxY
+ const impactSpeed = Math.abs(state.vy)
+
+ if (y >= maxY) {
+ y = maxY
+ // 竖直速度太小直接停住:否则会在地面上无限微弹。
+ vy = Math.abs(vy) < 40 ? 0 : -Math.abs(vy) * physics.restitution
+ // 地面摩擦只削横向速度,且按帧长换算(帧率无关)。
+ vx *= Math.max(0, 1 - physics.groundFriction * dt)
+ bounced = true
+ }
+
+ if (maxY === bounds.minY) {
+ // 舞台比宠物还矮:贴地且不弹。
+ y = maxY
+ vy = 0
+ }
+
+ const atRest = (y >= maxY - 1 && Math.abs(vx) < 15 && Math.abs(vy) < 1)
+ || (bounced && Math.hypot(vx, vy) < 40 && Math.abs(vy) < 1)
+
+ return { x, y, vx, vy, atRest, landed, impactSpeed }
+}
diff --git a/src/pet/hooks/use-pet-physics.test.ts b/src/pet/hooks/use-pet-physics.test.ts
new file mode 100644
index 00000000..d14dc9c7
--- /dev/null
+++ b/src/pet/hooks/use-pet-physics.test.ts
@@ -0,0 +1,192 @@
+// @vitest-environment jsdom
+import type { PetPhysicsEvent, PetRef } from 'dsh-pet-component'
+import { act, cleanup, renderHook } from '@testing-library/react'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { usePetPhysics } from './use-pet-physics'
+
+/** useListen 的同步登记表:假事件直接投喂给订阅者,不经过 Tauri。 */
+const deviceListeners = vi.hoisted(() => new Map<string, (event: { payload: unknown }) => void>())
+
+vi.mock('@/hooks/use-listen', () => ({
+ useListen: (event: string, handler: (event: { payload: unknown }) => void) => {
+ deviceListeners.set(event, handler)
+ },
+}))
+
+const mocks = vi.hoisted(() => {
+ const movedHandlers: Array<(event: { payload: { x: number, y: number } }) => void> = []
+ return {
+ movedHandlers,
+ monitor: vi.fn<() => Promise<unknown>>(),
+ window: {
+ outerPosition: vi.fn<() => Promise<unknown>>(),
+ setPosition: vi.fn<(position: unknown) => Promise<void>>(),
+ onMoved: vi.fn<(handler: (event: { payload: { x: number, y: number } }) => void) => Promise<() => void>>(),
+ },
+ }
+})
+
+vi.mock('@tauri-apps/api/window', () => ({
+ PhysicalPosition: class {
+ constructor(public x: number, public y: number) {}
+ },
+ currentMonitor: mocks.monitor,
+ getCurrentWindow: () => mocks.window,
+}))
+
+/** 屏幕工作区 1920x1080(物理像素,jsdom 的 dpr = 1),窗口逻辑位置 (500, 400)。 */
+const WORK_AREA = { position: { x: 0, y: 0 }, size: { width: 1920, height: 1080 } }
+const WINDOW_POSITION = { x: 500, y: 400 }
+
+/** 组件校验后送回来的甩出请求:几何铺满视口,脚底在容器底边。 */
+function flingEvent(vx: number, vy: number): PetPhysicsEvent {
+ return {
+ vx,
+ vy,
+ geometry: { x: 0, y: 0, width: 100, height: 100, body: { left: 0, top: 0, right: 100, bottom: 100 } },
+ physics: { gravity: 1400, restitution: 0.78, groundFriction: 2.5, ceilingBounce: true, throwPower: 1, petCollision: false },
+ }
+}
+
+function createPet(): { fling: ReturnType<typeof vi.fn>, squash: ReturnType<typeof vi.fn>, ref: PetRef } {
+ const fling = vi.fn()
+ const squash = vi.fn()
+ const stopSquash = vi.fn()
+ return { fling, squash, ref: { fling, squash, stopSquash } as unknown as PetRef }
+}
+
+function advanceFrames(count: number): void {
+ act(() => {
+ for (let index = 0; index < count; index += 1)
+ vi.advanceTimersByTime(16)
+ })
+}
+
+function pressMouse(pressed: boolean): void {
+ const handler = deviceListeners.get('device-mouse-button')
+ if (handler === undefined)
+ throw new Error('未订阅 device-mouse-button:甩动拿不到 OS 侧的松开时刻(Bug 复现)')
+ act(() => {
+ handler({ payload: { pressed } })
+ })
+}
+
+/** 投喂窗口 Moved:`clock` 控制采样时刻,采样值 = 物理像素 / dpr。 */
+function dragWindow(clock: { now: number }, samples: Array<{ t: number, x: number, y: number }>): void {
+ for (const sample of samples) {
+ clock.now = sample.t
+ act(() => {
+ for (const handler of [...mocks.movedHandlers])
+ handler({ payload: { x: sample.x, y: sample.y } })
+ })
+ }
+}
+
+describe('usePetPhysics', () => {
+ const clock = { now: 0 }
+
+ beforeEach(() => {
+ clock.now = 0
+ deviceListeners.clear()
+ mocks.movedHandlers.length = 0
+ vi.clearAllMocks()
+ vi.useFakeTimers()
+ vi.spyOn(performance, 'now').mockImplementation(() => clock.now)
+ mocks.monitor.mockResolvedValue({ workArea: WORK_AREA })
+ mocks.window.outerPosition.mockResolvedValue({
+ ...WINDOW_POSITION,
+ toLogical: () => ({ ...WINDOW_POSITION }),
+ })
+ mocks.window.setPosition.mockResolvedValue(undefined)
+ mocks.window.onMoved.mockImplementation((handler) => {
+ mocks.movedHandlers.push(handler)
+ return Promise.resolve(() => {})
+ })
+ })
+
+ afterEach(() => {
+ cleanup()
+ vi.useRealTimers()
+ vi.restoreAllMocks()
+ })
+
+ it('松开左键时按窗口轨迹估速并请求组件甩出,轨迹随下一次抓取清空', () => {
+ const pet = createPet()
+ renderHook(() => usePetPhysics(pet.ref, 'codex'))
+
+ pressMouse(true)
+ dragWindow(clock, [
+ { t: 0, x: 1000, y: 500 },
+ { t: 40, x: 1200, y: 500 },
+ { t: 80, x: 1400, y: 500 },
+ { t: 120, x: 1600, y: 500 },
+ ])
+ clock.now = 121
+ pressMouse(false)
+
+ expect(pet.fling).toHaveBeenCalledTimes(1)
+ const velocity = pet.fling.mock.calls[0][0] as { vx: number, vy: number }
+ expect(velocity.vx).toBeGreaterThan(0)
+ expect(velocity.vy).toBeCloseTo(0, 6)
+
+ pressMouse(true)
+ clock.now = 400
+ pressMouse(false)
+ expect(pet.fling).toHaveBeenCalledTimes(1)
+ })
+
+ it('窗口几乎没动(低于 500 CSS px/s)的松手不甩', () => {
+ const pet = createPet()
+ renderHook(() => usePetPhysics(pet.ref, 'codex'))
+
+ pressMouse(true)
+ dragWindow(clock, [
+ { t: 0, x: 1000, y: 500 },
+ { t: 100, x: 1010, y: 500 },
+ ])
+ clock.now = 110
+ pressMouse(false)
+
+ expect(pet.fling).not.toHaveBeenCalled()
+ })
+
+ it('飞行逐帧移动窗口,落地时触发挤压动画并停在地板上', async () => {
+ const pet = createPet()
+ const { result } = renderHook(() => usePetPhysics(pet.ref, 'codex'))
+
+ act(() => {
+ result.current(flingEvent(600, 0))
+ })
+ await act(async () => {})
+
+ advanceFrames(2)
+
+ // 工作区高 1080 - 脚底 100 = 地板 980;vx 600 CSS px/s 首帧走 9.6px。
+ const first = mocks.window.setPosition.mock.calls[1][0] as { x: number, y: number }
+ expect(first.x).toBe(Math.round(WINDOW_POSITION.x + 600 * 0.016))
+
+ advanceFrames(120)
+
+ expect(pet.squash).toHaveBeenCalled()
+ expect(pet.squash.mock.calls[0][0] as number).toBeGreaterThan(0)
+ const positions = mocks.window.setPosition.mock.calls.map(([position]) => position as { x: number, y: number })
+ expect(Math.max(...positions.map(position => position.y))).toBeLessThanOrEqual(980)
+ })
+
+ it('飞行中按下左键立刻停住窗口(抓取刹车,不等落地)', async () => {
+ const pet = createPet()
+ const { result } = renderHook(() => usePetPhysics(pet.ref, 'codex'))
+
+ act(() => {
+ result.current(flingEvent(600, 0))
+ })
+ await act(async () => {})
+ advanceFrames(2)
+
+ const calls = mocks.window.setPosition.mock.calls.length
+ pressMouse(true)
+ advanceFrames(10)
+
+ expect(mocks.window.setPosition).toHaveBeenCalledTimes(calls)
+ })
+})
diff --git a/src/pet/hooks/use-pet-physics.ts b/src/pet/hooks/use-pet-physics.ts
new file mode 100644
index 00000000..ec7128ad
--- /dev/null
+++ b/src/pet/hooks/use-pet-physics.ts
@@ -0,0 +1,193 @@
+import type { PetPhysicsEvent, PetRef, PhysicsParams } from 'dsh-pet-component'
+import type { DragSample, ThrowBounds, ThrowState } from './use-pet-physics.helpers'
+import { useRafFn } from '@reause/core'
+import { currentMonitor, getCurrentWindow, PhysicalPosition } from '@tauri-apps/api/window'
+import { useEffect, useRef } from 'react'
+import { useListen } from '@/hooks/use-listen'
+import { reportPetIssue } from '../utils/log'
+import { bodyBounds, estimateReleaseVelocity, stepThrow } from './use-pet-physics.helpers'
+
+/** 轨迹最多留 64 个样本:估速只看最近 150ms,长拖不必无限增长。 */
+const TRAIL_LIMIT = 64
+
+/**
+ * 宿主侧甩动:把「松手 → 请求甩出 → 飞行 → 落地 Q 弹」接在 dsh-pet-component 的协议上。
+ *
+ * 组件 0.2.3 起把甩动物理留给宿主(见组件 `docs/spec/pet-interactions.md` 的职责划分),
+ * 桌宠宿主的舞台就是显示器工作区、宠物本体就是窗口,于是飞行 = 每帧 `setPosition`:
+ *
+ * - **轨迹来自窗口 `Moved`**:原生拖拽跑在系统模态循环里,webview 收不到 pointermove,
+ * 窗口位移是唯一能看出「甩得多快」的信号;`device-mouse-button` 给的是 OS 侧的松开
+ * 时刻(见 `use-window-draggable.ts`),两者拼出一次甩动;
+ * - **增益只在 `onFling` 里施加**:松手时先用 `throwPower = 1` 判断「这一下要不要甩」,
+ * 组件回吐的 `PetPhysicsEvent` 才带着合并后的 `physics`(prop > 配置 > 默认),速度的
+ * `throwPower` 放大因此只能在那里做 —— 默认值 1 时与组件参考实现完全等价;
+ * - **单位是 CSS px**:重力/速度都按组件默认参数的语义(CSS px/s)算,写回窗口时乘
+ * `devicePixelRatio` 换成物理像素;Retina 上不去换算,观感速度会差一倍;
+ * - 单宠物窗口没有宠物间碰撞,`physics.petCollision` 与 `pet.bounce` 不适用。
+ */
+export function usePetPhysics(pet: PetRef, kind: 'dsh' | 'codex' | undefined): (event: PetPhysicsEvent) => void {
+ const trailRef = useRef<DragSample[]>([])
+ const pressedRef = useRef(false)
+ const flightRef = useRef<Flight | null>(null)
+ // 飞行代号:起飞行要 await 显示器与窗口位置,期间可能被「抓取取消」或下一次甩动顶掉。
+ const flightIdRef = useRef(0)
+ const kindRef = useRef(kind)
+ kindRef.current = kind
+ // useRafFn 每渲染返回新对象,飞行循环统一走 ref,避免闭包抓到旧的 pause/resume。
+ const rafRef = useRef<{ pause: () => void, resume: () => void } | null>(null)
+
+ const raf = useRafFn(({ delta }) => {
+ const flight = flightRef.current
+ if (flight === null) {
+ rafRef.current?.pause()
+ return
+ }
+
+ const next = stepThrow(flight.state, delta / 1000, flight.bounds, flight.physics)
+ flight.state = { x: next.x, y: next.y, vx: next.vx, vy: next.vy }
+ // 窗口位置取整:亚像素位置在 Windows 上会被系统四舍五入,抖动比丢精度更显眼。
+ void getCurrentWindow()
+ .setPosition(new PhysicalPosition(
+ Math.round((next.x - flight.originX) * flight.scale),
+ Math.round((next.y - flight.originY) * flight.scale),
+ ))
+ .catch(() => {})
+
+ // 落地 Q 弹复用组件的挤压动画;力度是撞击瞬间的下坠速度(积分前)。
+ if (next.landed)
+ pet.squash(next.impactSpeed)
+ if (next.atRest)
+ flightRef.current = null
+ }, { immediate: false })
+ rafRef.current = raf
+
+ useEffect(() => {
+ // keep:effect 原生拖拽期间 webview 收不到 pointermove,只能靠窗口 Moved 采轨迹
+ let disposed = false
+ let unlisten: (() => void) | undefined
+
+ void getCurrentWindow()
+ .onMoved((event) => {
+ if (!pressedRef.current)
+ return
+ const scale = window.devicePixelRatio
+ const samples = trailRef.current
+ samples.push({ t: performance.now(), x: event.payload.x / scale, y: event.payload.y / scale })
+ if (samples.length > TRAIL_LIMIT)
+ samples.splice(0, samples.length - TRAIL_LIMIT)
+ })
+ .then((fn) => {
+ if (disposed)
+ fn()
+ else
+ unlisten = fn
+ })
+ .catch(error => reportPetIssue('fling-moved', error))
+
+ return () => {
+ disposed = true
+ unlisten?.()
+ }
+ }, [])
+
+ useListen<MouseButtonState>('device-mouse-button', ({ payload }) => {
+ if (payload.pressed) {
+ // 抓取即落地刹车:组件自己会取消挤压动画,这里只要停下窗口飞行。
+ pressedRef.current = true
+ trailRef.current = []
+ stopFlight()
+ return
+ }
+
+ if (!pressedRef.current)
+ return
+ pressedRef.current = false
+
+ const trail = trailRef.current
+ trailRef.current = []
+ const release = estimateReleaseVelocity(trail, performance.now(), 1)
+ if (release !== null)
+ pet.fling(release)
+ })
+
+ /** 终止飞行(含尚未起飞的请求):抓取、下一次甩出、卸载都走这里。 */
+ function stopFlight(): void {
+ flightIdRef.current += 1
+ if (flightRef.current === null)
+ return
+ flightRef.current = null
+ rafRef.current?.pause()
+ }
+
+ return (event: PetPhysicsEvent): void => {
+ const id = flightIdRef.current + 1
+ flightIdRef.current = id
+ flightRef.current = null
+ rafRef.current?.pause()
+ void startFlight(event, id)
+ }
+
+ /** 组件校验后的甩出请求:读出几何与屏幕工作区,把这次甩动变成一次飞行。 */
+ async function startFlight(event: PetPhysicsEvent, id: number): Promise<void> {
+ try {
+ const [monitor, position] = await Promise.all([currentMonitor(), getCurrentWindow().outerPosition()])
+ // 等待期间被下一次甩动或抓取顶掉:这次请求作废。
+ if (monitor === null || id !== flightIdRef.current)
+ return
+
+ const scale = window.devicePixelRatio
+ const area = monitor.workArea
+ // 工作区与窗口位置都是物理像素,除 dpr 换成视口 px(= CSS px)后才能和组件几何对齐。
+ const stage = {
+ x: area.position.x / scale,
+ y: area.position.y / scale,
+ width: area.size.width / scale,
+ height: area.size.height / scale,
+ }
+ const local = bodyBounds(event.geometry, stage.width, stage.height, kindRef.current === 'dsh')
+ const origin = position.toLogical(scale)
+
+ flightRef.current = {
+ // 组件几何挂在本窗口的视口上:容器屏幕坐标 = 窗口逻辑位置 + 视口原点。
+ state: {
+ x: origin.x + event.geometry.x,
+ y: origin.y + event.geometry.y,
+ vx: event.vx * event.physics.throwPower,
+ vy: event.vy * event.physics.throwPower,
+ },
+ physics: event.physics,
+ bounds: {
+ minX: stage.x + local.minX,
+ minY: stage.y + local.minY,
+ maxX: stage.x + local.maxX,
+ maxY: stage.y + local.maxY,
+ },
+ originX: event.geometry.x,
+ originY: event.geometry.y,
+ scale,
+ }
+ rafRef.current?.resume()
+ }
+ catch (error) {
+ reportPetIssue('fling', error)
+ }
+ }
+}
+
+/** 一次飞行的全部状态:位置/速度 + 参数快照 + 屏幕边界 + 窗口换算。 */
+interface Flight {
+ state: ThrowState
+ physics: PhysicsParams
+ bounds: ThrowBounds
+ /** 容器(宠物)在窗口视口里的原点:窗口位置 = 飞行位置 - 原点。 */
+ originX: number
+ originY: number
+ /** 起飞行时的 `devicePixelRatio`(= Tauri 缩放系数),每帧换算窗口位置用。 */
+ scale: number
+}
+
+/** `device-mouse-button` 的事件载荷(对应 Rust 的 `MouseButtonState`)。 */
+interface MouseButtonState {
+ pressed: boolean
+}