Skip to content

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

feat(pet): 设置页新增「开启宠物抛射」开关,默认关闭 (#942)

Mao Mrc50cc1f9a12a
diff --git a/packages/dsh-tauri-pet/src/client/components/pet-settings.test.tsx b/packages/dsh-tauri-pet/src/client/components/pet-settings.test.tsx
index c4e7a92a..ade38dd2 100644
--- a/packages/dsh-tauri-pet/src/client/components/pet-settings.test.tsx
+++ b/packages/dsh-tauri-pet/src/client/components/pet-settings.test.tsx
@@ -28,6 +28,9 @@ vi.mock('dsh-tauri-ui/client', () => ({
{['pets', 'codex'].map(tab => <button key={tab} aria-pressed={value === tab} onClick={() => onChange(tab)}>{tab}</button>)}
</div>
),
+ Switch: ({ checked, label, onChange }: { checked: boolean, label: string, onChange: (next: boolean) => void }) => (
+ <button role="switch" aria-checked={checked} onClick={() => onChange(!checked)}>{label}</button>
+ ),
}))
vi.mock('../service/pet', () => ({
@@ -42,6 +45,7 @@ vi.mock('../service/pet', () => ({
resizePet: vi.fn(),
toggleForceXwayland: vi.fn(),
togglePet: vi.fn(),
+ togglePetThrow: vi.fn(),
}))
let container: HTMLDivElement
@@ -85,7 +89,7 @@ beforeEach(() => {
vi.stubGlobal('IS_REACT_ACT_ENVIRONMENT', true)
vi.resetAllMocks()
Object.assign(store.pet.$state, {
- status: { active_pet: 'chat', enabled: false, visible: false },
+ status: { active_pet: 'chat', enabled: false, visible: false, throw_enabled: false },
fetchRevision: 0,
catalogLoaded: true,
presetPets: [{ id: 'preset', name: 'Preset', desc: 'Preset description', image: 'preset.gif' }],
@@ -95,7 +99,7 @@ beforeEach(() => {
overlaySupported: false,
forceXwayland: false,
})
- for (const action of [petService.loadPetCatalog, petService.choosePet, petService.clearPetSelection, petService.enablePet, petService.togglePet, petService.toggleForceXwayland, petService.resizePet, petService.importPetArchive, petService.openCommunityShare])
+ for (const action of [petService.loadPetCatalog, petService.choosePet, petService.clearPetSelection, petService.enablePet, petService.togglePet, petService.toggleForceXwayland, petService.resizePet, petService.togglePetThrow, petService.importPetArchive, petService.openCommunityShare])
vi.mocked(action).mockResolvedValue({ ok: true })
container = document.createElement('div')
document.body.append(container)
@@ -176,6 +180,33 @@ describe('pet settings action boundaries', () => {
expect(container.textContent).toContain(locale.text('xwaylandRestart'))
})
+ it('throw switch defaults off, sends the flipped value and follows the authoritative status', async () => {
+ await mount()
+ const toggle = container.querySelector<HTMLButtonElement>('[role="switch"]')!
+ expect(toggle.textContent).toBe(locale.text('throwLabel'))
+ expect(toggle.getAttribute('aria-checked')).toBe('false')
+ await click(toggle)
+ expect(petService.togglePetThrow).toHaveBeenCalledExactlyOnceWith({ enabled: true })
+ expect(toggle.getAttribute('aria-checked')).toBe('false')
+ await act(async () => {
+ store.pet.setStatus({ active_pet: 'chat', enabled: false, visible: false, throw_enabled: true })
+ })
+ expect(toggle.getAttribute('aria-checked')).toBe('true')
+ await click(toggle)
+ expect(petService.togglePetThrow).toHaveBeenLastCalledWith({ enabled: false })
+ })
+
+ it('throw switch shows its own failure without flipping the local state', async () => {
+ vi.mocked(petService.togglePetThrow).mockResolvedValueOnce({ ok: false, error: 'native failure' })
+ await mount()
+ const toggle = container.querySelector<HTMLButtonElement>('[role="switch"]')!
+ await click(toggle)
+ expect(container.querySelector('[role="alert"]')?.textContent).toBe(locale.text('throwFailed'))
+ expect(toggle.getAttribute('aria-checked')).toBe('false')
+ await click(toggle)
+ expect(container.querySelector('[role="alert"]')).toBeNull()
+ })
+
it('default size remains interactive during other busy actions and sends each changed value', async () => {
const pending = deferred()
vi.mocked(petService.togglePet).mockReturnValueOnce(pending.promise)
diff --git a/packages/dsh-tauri-pet/src/client/components/pet-settings.tsx b/packages/dsh-tauri-pet/src/client/components/pet-settings.tsx
index cb50096e..40b117c9 100644
--- a/packages/dsh-tauri-pet/src/client/components/pet-settings.tsx
+++ b/packages/dsh-tauri-pet/src/client/components/pet-settings.tsx
@@ -1,6 +1,6 @@
import type { ChangeEvent, ReactElement } from 'react'
import type { PetActionResult, PetListItem } from '../service/pet.types'
-import { ArrowRightFromSquare, Button, Globe, Icon, Plus, SegmentedControl } from 'dsh-tauri-ui/client'
+import { ArrowRightFromSquare, Button, Globe, Icon, Plus, SegmentedControl, Switch } from 'dsh-tauri-ui/client'
import { useStore, useWatchImmediate } from 'dsh-tauri/client'
import { useEffect, useId, useRef, useState } from 'react'
import { PET_DEFAULT_SIZE, PET_SIZE_MAX, PET_SIZE_MIN, PET_SIZE_STEP } from '../constants'
@@ -17,6 +17,7 @@ import {
resizePet,
toggleForceXwayland,
togglePet,
+ togglePetThrow,
} from '../service/pet'
import { store } from '../store'
import { PetCard } from './pet-card'
@@ -62,6 +63,7 @@ export function PetSettings(props: PetSettingsProps): ReactElement {
const enabled = Boolean(status?.enabled)
const active = status?.active_pet ?? ''
const statusSize = status?.pet_size ?? PET_DEFAULT_SIZE
+ const throwEnabled = Boolean(status?.throw_enabled)
// 宿主侧尺寸变化同步到本地滑条,正在拖动的本地值不被覆盖。
useWatchImmediate(statusSize, () => {
@@ -125,6 +127,11 @@ export function PetSettings(props: PetSettingsProps): ReactElement {
await run(() => togglePet({ enabled: !enabled }), 'toggleFailed')
}
+ /** 切换抛射:关闭(默认)时宠物松手即停,不再飞行与撞边回弹(issue #930)。 */
+ async function toggleThrow(): Promise<void> {
+ await run(() => togglePetThrow({ enabled: !throwEnabled }), 'throwFailed')
+ }
+
/** 切换「强制 XWayland」:应用全局设置,下次启动生效。 */
async function toggleXwayland(): Promise<void> {
await run(async () => {
@@ -348,6 +355,15 @@ export function PetSettings(props: PetSettingsProps): ReactElement {
/>
</div>
<p className="m-0 text-[12px] leading-[18px] text-secondary">{locale.text('sizeHint')}</p>
+ <div className="flex items-center justify-between gap-[12px]">
+ <span className="flex-none font-medium">{locale.text('throwLabel')}</span>
+ <Switch
+ checked={throwEnabled}
+ label={locale.text('throwLabel')}
+ onChange={() => { void toggleThrow() }}
+ />
+ </div>
+ <p className="m-0 text-[12px] leading-[18px] text-secondary">{locale.text('throwHint')}</p>
</div>
)
}
diff --git a/packages/dsh-tauri-pet/src/client/constants/index.ts b/packages/dsh-tauri-pet/src/client/constants/index.ts
index f0f49aff..a7d55cde 100644
--- a/packages/dsh-tauri-pet/src/client/constants/index.ts
+++ b/packages/dsh-tauri-pet/src/client/constants/index.ts
@@ -25,6 +25,7 @@ export const CMD_SET_FORCE_XWAYLAND = 'set_force_xwayland'
export const CMD_SET_PET_ENABLED = 'set_pet_enabled'
export const CMD_SET_ACTIVE_PET = 'set_active_pet'
export const CMD_SET_PET_SIZE = 'set_pet_size'
+export const CMD_SET_PET_THROW_ENABLED = 'set_pet_throw_enabled'
export const CMD_LIST_PETS = 'list_pets'
export const CMD_IMPORT_PET = 'import_pet'
export const CMD_LIST_PRESET_PETS = 'list_preset_pets'
diff --git a/packages/dsh-tauri-pet/src/client/locales/index.ts b/packages/dsh-tauri-pet/src/client/locales/index.ts
index 3b1e6987..ca2f9500 100644
--- a/packages/dsh-tauri-pet/src/client/locales/index.ts
+++ b/packages/dsh-tauri-pet/src/client/locales/index.ts
@@ -25,6 +25,9 @@ const zh = {
sizeLabel: '大小',
tabCodexDesc: '从 Codex 或压缩包中导入 Codex 宠物(支持 .zip 文件)',
tabInstalledDesc: '宠物会管理对话串,并突出显示需要关注的事项',
+ throwFailed: '切换抛射开关失败',
+ throwHint: '开启后把宠物甩出去会飞起来,碰到屏幕边缘会回弹;关闭时松手即停。',
+ throwLabel: '开启宠物抛射',
toggleFailed: '切换桌宠开关失败',
waylandNotice: '当前为 Wayland 会话,桌宠窗口无法置顶,会被其他窗口遮挡,也不会停在设定的位置。开启 XWayland 可恢复这两项能力。',
xwaylandDesc: '开启后整个应用经 XWayland 渲染,分数缩放下界面变模糊,输入法走 XIM 路径。系统未运行 XWayland 时该选项不生效。',
@@ -57,6 +60,9 @@ const en: Record<keyof typeof zh, string> = {
sizeLabel: 'Size',
tabCodexDesc: 'Import Codex pets from Codex or archives (.zip files supported)',
tabInstalledDesc: 'Pets manage your conversation threads and highlight items that need attention',
+ throwFailed: 'Failed to toggle pet throw',
+ throwHint: 'When enabled, flinging the pet sends it flying and bouncing off screen edges; when disabled, it stops where you release it.',
+ throwLabel: 'Enable pet throw',
toggleFailed: 'Failed to toggle the pet',
waylandNotice: 'This is a Wayland session. The pet window cannot stay on top, so it is covered by other windows and does not stay where it was placed. Enable XWayland to restore both behaviors.',
xwaylandDesc: 'When enabled, the whole app renders through XWayland. The interface blurs under fractional scaling and input methods go through XIM. The option has no effect when XWayland is not running.',
diff --git a/packages/dsh-tauri-pet/src/client/service/pet.test.ts b/packages/dsh-tauri-pet/src/client/service/pet.test.ts
index 7a209b51..6bfee6a2 100644
--- a/packages/dsh-tauri-pet/src/client/service/pet.test.ts
+++ b/packages/dsh-tauri-pet/src/client/service/pet.test.ts
@@ -17,6 +17,7 @@ import {
resizePet,
toggleForceXwayland,
togglePet,
+ togglePetThrow,
} from './pet'
const { invoke } = vi.hoisted(() => ({ invoke: vi.fn() }))
@@ -26,7 +27,7 @@ vi.mock('dsh-tauri/client', async () => ({
invoke,
}))
-const status: PetStatus = { active_pet: 'chat-a', enabled: true, visible: true, pet_size: 100 }
+const status: PetStatus = { active_pet: 'chat-a', enabled: true, visible: true, pet_size: 100, throw_enabled: true }
function adapter(): ClientAdapter {
return {
@@ -113,6 +114,7 @@ describe('pet service native command contracts', () => {
{ action: () => choosePet({ id: 'chosen' }), call: ['set_active_pet', { id: 'chosen' }] },
{ action: () => togglePet({ enabled: false }), call: ['set_pet_enabled', { enabled: false }] },
{ action: () => resizePet({ size: 160 }), call: ['set_pet_size', { size: 160 }] },
+ { action: () => togglePetThrow({ enabled: true }), call: ['set_pet_throw_enabled', { enabled: true }] },
])('status action forwards $call and stores the authoritative result', async ({ action, call }) => {
invoke.mockResolvedValue(status)
expect(await action()).toEqual({ ok: true })
@@ -194,6 +196,7 @@ describe('pet service native command contracts', () => {
{ label: 'enable pet', action: () => enablePet({ id: 'chosen' }) },
{ label: 'toggle pet', action: () => togglePet({ enabled: true }) },
{ label: 'toggle force xwayland', action: () => toggleForceXwayland({ enabled: true }) },
+ { label: 'toggle pet throw', action: () => togglePetThrow({ enabled: true }) },
{ label: 'resize pet', action: () => resizePet({ size: 140 }) },
{ label: 'import pet', action: () => importPetArchive({ name: 'bad.zip', data: 'bad' }) },
{ label: 'open community share', action: openCommunityShare },
diff --git a/packages/dsh-tauri-pet/src/client/service/pet.ts b/packages/dsh-tauri-pet/src/client/service/pet.ts
index d820b321..c37e70e0 100644
--- a/packages/dsh-tauri-pet/src/client/service/pet.ts
+++ b/packages/dsh-tauri-pet/src/client/service/pet.ts
@@ -13,6 +13,7 @@ import {
CMD_SET_FORCE_XWAYLAND,
CMD_SET_PET_ENABLED,
CMD_SET_PET_SIZE,
+ CMD_SET_PET_THROW_ENABLED,
PET_COMMUNITY_URL,
PET_HATCH_PROMPT,
} from '../constants'
@@ -170,6 +171,19 @@ export async function resizePet(input: { size: number }): Promise<PetActionResul
})
}
+/**
+ * Action:开关抛射能力(拖拽甩出后飞行、撞屏幕边缘回弹)。
+ *
+ * 与 `togglePet` 同形:命令回吐权威状态,前端不做乐观本地副本;抛射开关经
+ * `pet://status` 广播给桌宠窗口,立即生效。
+ */
+export async function togglePetThrow(input: { enabled: boolean }): Promise<PetActionResult> {
+ return guard('toggle pet throw', async () => {
+ store.pet.setStatus(await invoke<PetStatus>(CMD_SET_PET_THROW_ENABLED, { enabled: input.enabled }))
+ return { ok: true }
+ })
+}
+
/** Action:导入宠物压缩包(base64),成功后刷新 Codex 清单。 */
export async function importPetArchive(input: { name: string, data: string }): Promise<PetActionResult> {
return guard('import pet', async () => {
diff --git a/packages/dsh-tauri-pet/src/client/service/pet.types.ts b/packages/dsh-tauri-pet/src/client/service/pet.types.ts
index 061898e0..ecd8d534 100644
--- a/packages/dsh-tauri-pet/src/client/service/pet.types.ts
+++ b/packages/dsh-tauri-pet/src/client/service/pet.types.ts
@@ -7,6 +7,8 @@ export interface PetStatus {
active_pet: string
enabled: boolean
pet_size?: number | null
+ /** 是否允许抛射(默认关闭,issue #930)。 */
+ throw_enabled: boolean
visible: boolean
}
diff --git a/src-tauri/src/bridge/pet.rs b/src-tauri/src/bridge/pet.rs
index 89ee9cbe..bea29ebe 100644
--- a/src-tauri/src/bridge/pet.rs
+++ b/src-tauri/src/bridge/pet.rs
@@ -65,6 +65,11 @@ pub struct PetStatus {
pub active_pet: String,
/// 宠物大小百分比(50–200,100 = 精灵图原始尺寸);None = 未设置(默认 100)。
pub pet_size: Option<f64>,
+ /// 是否允许抛射(拖拽甩出后飞行、撞屏幕边缘回弹);默认关闭。
+ ///
+ /// 经 `pet://status` 广播给 pet 窗口,由窗口侧的物理层决定是否响应释放速度
+ /// (issue #930)。
+ pub throw_enabled: bool,
}
/// 文件系统宠物的数据来源。
@@ -163,6 +168,7 @@ fn status_from_setting(setting: &config::Setting, default_id: &str) -> PetStatus
visible: setting.pet_enabled,
active_pet: normalize_active_pet(setting.active_pet.as_deref(), default_id),
pet_size: setting.pet_size,
+ throw_enabled: setting.throw_enabled,
}
}
@@ -292,6 +298,20 @@ pub fn set_pet_size(app: AppHandle, size: f64) -> Result<PetStatus, String> {
Ok(status)
}
+/// 启用/关闭抛射能力(设置页 Switch,默认关闭,issue #930)。
+///
+/// 与 [`set_pet_size`] 同形:只落盘 + 广播状态,不做窗口操作——抛射完全是 pet WebView
+/// 内的物理层行为,窗口侧收到 `pet://status` 立即生效,无需重启。
+#[tauri::command]
+pub fn set_pet_throw_enabled(app: AppHandle, enabled: bool) -> Result<PetStatus, String> {
+ let updated = config::update_store_dat_setting(&app, |setting| {
+ setting.throw_enabled = enabled;
+ });
+ let status = status_from_setting(&updated, &default_active_pet(&app));
+ emit_pet_status(&app, &status);
+ Ok(status)
+}
+
/// 将 DSH 会话原始数据推送到独立桌宠 WebView,不在桌面端构造宠物专用结构。
#[tauri::command]
pub fn push_pet_session(app: AppHandle, action: String, session: Value) -> Result<(), String> {
@@ -1553,6 +1573,21 @@ mod tests {
assert_eq!(status.active_pet, "");
}
+ #[test]
+ fn throw_defaults_off_and_follows_the_setting() {
+ let default_status = status_from_setting(&config::Setting::default(), "");
+ assert!(
+ !default_status.throw_enabled,
+ "抛射必须默认关闭(issue #930)"
+ );
+
+ let enabled = config::Setting {
+ throw_enabled: true,
+ ..Default::default()
+ };
+ assert!(status_from_setting(&enabled, "").throw_enabled);
+ }
+
#[test]
fn manifest_parsing_keeps_version_optional_and_qualifies_source_ids() {
let manifest = parse_manifest_bytes(
diff --git a/src-tauri/src/config/setting.rs b/src-tauri/src/config/setting.rs
index f07e01ac..70748076 100644
--- a/src-tauri/src/config/setting.rs
+++ b/src-tauri/src/config/setting.rs
@@ -81,6 +81,12 @@ pub struct Setting {
/// 桌宠精灵图的显示宽度(逻辑像素);`None` = 沿用窗口侧默认值。
#[serde(default)]
pub pet_size: Option<f64>,
+ /// 是否允许抛射桌宠(拖拽甩出后带速度飞行、撞到屏幕边缘回弹)。
+ ///
+ /// 默认关闭:飞行/回弹会打断「把宠物拖到某处」这一主要用途(issue #930),
+ /// 需要该效果的用户显式开启。拖拽本身不受此字段影响。
+ #[serde(default)]
+ pub throw_enabled: bool,
/// 强制以 XWayland 运行(默认关闭,下次启动生效)。
///
/// 影响的是整个应用而非只有桌宠:原生 Wayland 下桌宠既不能置顶也不能定位
@@ -211,6 +217,7 @@ impl Default for Setting {
pet_enabled: false,
active_pet: None,
pet_size: None,
+ throw_enabled: false,
force_xwayland: false,
local_plugin_hmr: default_local_plugin_hmr(),
}
@@ -357,6 +364,7 @@ fn preserve_persisted_fields(mut replacement: Setting, current: &Setting) -> Set
replacement.pet_enabled = current.pet_enabled;
replacement.active_pet.clone_from(&current.active_pet);
replacement.pet_size = current.pet_size;
+ replacement.throw_enabled = current.throw_enabled;
replacement.force_xwayland = current.force_xwayland;
replacement.local_plugin_hmr = current.local_plugin_hmr;
replacement
@@ -709,6 +717,7 @@ mod tests {
pet_enabled: false,
active_pet: Some("chat:stale".to_string()),
pet_size: Some(80.0),
+ throw_enabled: false,
force_xwayland: false,
local_plugin_hmr: false,
..Default::default()
@@ -730,6 +739,7 @@ mod tests {
pet_enabled: true,
active_pet: Some("codex:latest".to_string()),
pet_size: Some(140.0),
+ throw_enabled: true,
force_xwayland: true,
local_plugin_hmr: true,
..Default::default()
@@ -755,6 +765,7 @@ mod tests {
Some(140.0),
"整对象写入不得覆盖最新桌宠字段"
);
+ assert!(merged.throw_enabled, "整对象写入不得覆盖最新的抛射开关");
assert!(
merged.force_xwayland,
"整对象写入不得覆盖最新的 XWayland 开关"
diff --git a/src-tauri/src/desktop/builder.rs b/src-tauri/src/desktop/builder.rs
index 12253f57..4c5c9631 100644
--- a/src-tauri/src/desktop/builder.rs
+++ b/src-tauri/src/desktop/builder.rs
@@ -1623,6 +1623,7 @@ pub fn handler() -> impl Fn(Invoke<Wry>) -> bool + Send + Sync + 'static {
crate::bridge::set_pet_enabled,
crate::bridge::set_active_pet,
crate::bridge::set_pet_size,
+ crate::bridge::set_pet_throw_enabled,
crate::bridge::push_pet_session,
crate::bridge::move_pet_window,
crate::bridge::persist_pet_window_position,
diff --git a/src/hooks/use-invoke-iframe.ts b/src/hooks/use-invoke-iframe.ts
index 65f03a60..29214479 100644
--- a/src/hooks/use-invoke-iframe.ts
+++ b/src/hooks/use-invoke-iframe.ts
@@ -49,6 +49,7 @@ const ALLOWED_INVOKE_CMDS = new Set([
'set_pet_enabled',
'set_active_pet',
'set_pet_size',
+ 'set_pet_throw_enabled',
'push_pet_session',
'list_pets',
'import_pet',
diff --git a/src/pet/app.tsx b/src/pet/app.tsx
index f872fb75..13262f4a 100644
--- a/src/pet/app.tsx
+++ b/src/pet/app.tsx
@@ -27,7 +27,7 @@ export function App() {
// 抓取信号来自命中箱 `pointerdown`(经拖拽 hook 的 `onGrab`):`device-mouse-button`
// 是全屏左键流,在桌面别处的点击不能给甩出中的宠物刹车。松开由拖拽 hook 统一上报
// (`onRelease`,命中箱 `pointerup` 与设备流两条路只结算一次),物理层据此估速并清状态。
- const { onFling, onGrab, onRelease } = usePetPhysics(pet, source?.kind)
+ const { onFling, onGrab, onRelease } = usePetPhysics(pet, source?.kind, status?.throw_enabled === true)
// 跟手期间按「宠物本体 / 脚底」把窗口夹进显示器工作区(与飞行共用边界):贴边松手
// 不会被整窗夹取推开,也不会跑出飞行边界而在松手瞬间被修正回来。
const { clampPosition, refreshWorkAreas } = usePetWindowClamp(pet, source?.kind)
diff --git a/src/pet/hooks/use-pet-physics.test.ts b/src/pet/hooks/use-pet-physics.test.ts
index deafe2a5..58865621 100644
--- a/src/pet/hooks/use-pet-physics.test.ts
+++ b/src/pet/hooks/use-pet-physics.test.ts
@@ -90,6 +90,20 @@ function dragWindow(clock: { now: number }, samples: Array<{ t: number, x: numbe
}
}
+/** 一次完整的「抓取 → 高速拖拽 → 松手」手势(5000 CSS px/s,远超 500 的甩出门槛)。 */
+function flingGesture(controls: PetPhysicsControls, clock: { now: number }): void {
+ const start = clock.now
+ grab(controls)
+ dragWindow(clock, [
+ { t: start, x: 1000, y: 500 },
+ { t: start + 40, x: 1200, y: 500 },
+ { t: start + 80, x: 1400, y: 500 },
+ { t: start + 120, x: 1600, y: 500 },
+ ])
+ clock.now = start + 121
+ pressMouse(false)
+}
+
describe('usePetPhysics', () => {
const clock = { now: 0 }
@@ -120,7 +134,7 @@ describe('usePetPhysics', () => {
it('抓住宠物后松开左键,按窗口轨迹估速并请求组件甩出,轨迹随下一次抓取清空', () => {
const pet = createPet()
- const { result } = renderHook(() => usePetPhysics(pet.ref, 'codex'))
+ const { result } = renderHook(() => usePetPhysics(pet.ref, 'codex', true))
grab(result.current)
dragWindow(clock, [
@@ -145,7 +159,7 @@ describe('usePetPhysics', () => {
it('宿主转来的命中箱松开结算一次甩动,设备流的同一次松开不再重复结算', () => {
const pet = createPet()
- const { result } = renderHook(() => usePetPhysics(pet.ref, 'codex'))
+ const { result } = renderHook(() => usePetPhysics(pet.ref, 'codex', true))
grab(result.current)
dragWindow(clock, [
@@ -172,7 +186,7 @@ describe('usePetPhysics', () => {
it('没有抓取时的松开是空操作:清状态不会凭空甩出宠物', () => {
const pet = createPet()
- const { result } = renderHook(() => usePetPhysics(pet.ref, 'codex'))
+ const { result } = renderHook(() => usePetPhysics(pet.ref, 'codex', true))
dragWindow(clock, [
{ t: 0, x: 1000, y: 500 },
@@ -188,7 +202,7 @@ describe('usePetPhysics', () => {
it('窗口几乎没动(低于 500 CSS px/s)的松手不甩', () => {
const pet = createPet()
- const { result } = renderHook(() => usePetPhysics(pet.ref, 'codex'))
+ const { result } = renderHook(() => usePetPhysics(pet.ref, 'codex', true))
grab(result.current)
dragWindow(clock, [
@@ -203,7 +217,7 @@ describe('usePetPhysics', () => {
it('飞行逐帧移动窗口,落地时触发挤压动画并停在地板上', async () => {
const pet = createPet()
- const { result } = renderHook(() => usePetPhysics(pet.ref, 'codex'))
+ const { result } = renderHook(() => usePetPhysics(pet.ref, 'codex', true))
act(() => {
result.current.onFling(flingEvent(600, 0))
@@ -226,7 +240,7 @@ describe('usePetPhysics', () => {
it('飞行中在别处点击(全屏左键按下)不停窗口,也不会被当成甩动', async () => {
const pet = createPet()
- const { result } = renderHook(() => usePetPhysics(pet.ref, 'codex'))
+ const { result } = renderHook(() => usePetPhysics(pet.ref, 'codex', true))
act(() => {
result.current.onFling(flingEvent(600, 0))
@@ -247,7 +261,7 @@ describe('usePetPhysics', () => {
it('抓住宠物(命中箱按下)立刻停住飞行,不等落地', async () => {
const pet = createPet()
- const { result } = renderHook(() => usePetPhysics(pet.ref, 'codex'))
+ const { result } = renderHook(() => usePetPhysics(pet.ref, 'codex', true))
act(() => {
result.current.onFling(flingEvent(600, 0))
@@ -261,4 +275,19 @@ describe('usePetPhysics', () => {
expect(mocks.window.setPosition).toHaveBeenCalledTimes(calls)
})
+
+ it('抛射关闭(默认)时松手不请求甩出,重新开启后同一次手势照常甩出', () => {
+ const pet = createPet()
+ const { result, rerender } = renderHook(
+ ({ enabled }: { enabled: boolean }) => usePetPhysics(pet.ref, 'codex', enabled),
+ { initialProps: { enabled: false } },
+ )
+
+ flingGesture(result.current, clock)
+ expect(pet.fling).not.toHaveBeenCalled()
+
+ rerender({ enabled: true })
+ flingGesture(result.current, clock)
+ expect(pet.fling).toHaveBeenCalledTimes(1)
+ })
})
diff --git a/src/pet/hooks/use-pet-physics.ts b/src/pet/hooks/use-pet-physics.ts
index e01c8a0b..22497bdb 100644
--- a/src/pet/hooks/use-pet-physics.ts
+++ b/src/pet/hooks/use-pet-physics.ts
@@ -30,9 +30,11 @@ const TRAIL_LIMIT = 64
* `throwPower` 放大因此只能在那里做 —— 默认值 1 时与组件参考实现完全等价;
* - **单位是 CSS px**:重力/速度都按组件默认参数的语义(CSS px/s)算,写回窗口时乘
* `devicePixelRatio` 换成物理像素;Retina 上不去换算,观感速度会差一倍;
- * - 单宠物窗口没有宠物间碰撞,`physics.petCollision` 与 `pet.bounce` 不适用。
+ * - 单宠物窗口没有宠物间碰撞,`physics.petCollision` 与 `pet.bounce` 不适用;
+ * - **抛射开关默认关闭**(issue #930):`throwEnabled` 为假时松手只结算并清状态,
+ * 不请求甩出,因此没有飞行也没有撞边回弹;拖拽本身照常工作。
*/
-export function usePetPhysics(pet: PetRef, kind: 'dsh' | 'codex' | undefined): PetPhysicsControls {
+export function usePetPhysics(pet: PetRef, kind: 'dsh' | 'codex' | undefined, throwEnabled: boolean): PetPhysicsControls {
const trailRef = useRef<DragSample[]>([])
/** 是否抓住了宠物(信号来自命中箱 `pointerdown`,见 `onGrab`):轨迹只在抓取后采样。 */
const pressedRef = useRef(false)
@@ -41,6 +43,8 @@ export function usePetPhysics(pet: PetRef, kind: 'dsh' | 'codex' | undefined): P
const flightIdRef = useRef(0)
const kindRef = useRef(kind)
kindRef.current = kind
+ const throwEnabledRef = useRef(throwEnabled)
+ throwEnabledRef.current = throwEnabled
// useRafFn 每渲染返回新对象,飞行循环统一走 ref,避免闭包抓到旧的 pause/resume。
const rafRef = useRef<{ pause: () => void, resume: () => void } | null>(null)
@@ -145,6 +149,9 @@ export function usePetPhysics(pet: PetRef, kind: 'dsh' | 'codex' | undefined): P
const trail = trailRef.current
trailRef.current = []
+ // 抛射关闭时不起飞行:松手照常结算、清掉按住状态,但宠物就停在原地。
+ if (!throwEnabledRef.current)
+ return
const release = estimateReleaseVelocity(trail, performance.now(), 1)
if (release !== null)
pet.fling(release)
diff --git a/src/pet/hooks/use-pet-status.ts b/src/pet/hooks/use-pet-status.ts
index e9ad2fd7..b567635a 100644
--- a/src/pet/hooks/use-pet-status.ts
+++ b/src/pet/hooks/use-pet-status.ts
@@ -14,6 +14,8 @@ export interface PetStatus {
active_pet: string
/** 宠物大小百分比(50–200;None = 未设置,按 100 处理)。 */
pet_size?: number | null
+ /** 是否允许抛射(飞行 + 撞屏幕边缘回弹);缺省 / undefined = 关闭。 */
+ throw_enabled?: boolean | null
}
/**
diff --git a/test/pet-dragging.test.ts b/test/pet-dragging.test.ts
index 76f5b41b..5f808114 100644
--- a/test/pet-dragging.test.ts
+++ b/test/pet-dragging.test.ts
@@ -42,13 +42,19 @@ describe('pet dragging follows the pointer (upstream spring feel)', () => {
it('brakes a thrown pet only on a real grab, never on a click elsewhere', () => {
// 抓取信号来自命中箱 pointerdown,经拖拽 hook 的 onGrab 转给甩动物理。
expect(app).toContain('useWindowDraggable({ onGrab: handleGrab, onRelease, clampPosition })')
- expect(app).toContain('const { onFling, onGrab, onRelease } = usePetPhysics(pet, source?.kind)')
+ expect(app).toContain('const { onFling, onGrab, onRelease } = usePetPhysics(pet, source?.kind, status?.throw_enabled === true)')
expect(hook).toContain('onGrabRef.current?.()')
// 全屏左键流只用来取「松开」时刻:任何位置的按下都不能刹车。
expect(physics).toContain('if (payload.pressed)')
expect(physics).toContain('export interface PetPhysicsControls')
})
+ it('keeps pet throwing off unless the status explicitly enables it (issue #930)', () => {
+ // 状态未就绪、字段缺省或为假时一律不甩出:开关关闭 = 松手即停,不做任何飞行。
+ expect(app).toContain('status?.throw_enabled === true')
+ expect(physics).toContain('if (!throwEnabledRef.current)')
+ })
+
it('routes both release paths through one idempotent physics release', () => {
// 命中箱 pointerup 与后端设备流汇到同一个 `onRelease`,同一个手势只结算一次:
// 设备流丢事件时物理层不会一直以为还按着,把很久以后一次无关点击当成甩出。