Skip to content

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

fix(mobile): restore sidebar gestures without losing conversation transitions (#1047)

Mao Mr5d3a08eaeeb1
diff --git a/packages/dsh-tauri-mobile-ui/src/client/register/sidebar.test.tsx b/packages/dsh-tauri-mobile-ui/src/client/register/sidebar.test.tsx
index 6d24bd5d..c31860b3 100644
--- a/packages/dsh-tauri-mobile-ui/src/client/register/sidebar.test.tsx
+++ b/packages/dsh-tauri-mobile-ui/src/client/register/sidebar.test.tsx
@@ -272,7 +272,7 @@ describe('registerMobileSidebar', () => {
expect(mocks.sessionListeners.size).toBe(0)
})
- it.each(['touch', 'pointer'])('leaves %s swipes to content without opening or closing the sidebar', (source) => {
+ it.each(['touch', 'pointer'])('reveals and closes the sidebar with %s drags without activating a dragged session', (source) => {
const { sidebar, main, overlay } = setupFrame()
const row = document.createElement('button')
row.textContent = 'Existing session'
@@ -283,19 +283,57 @@ describe('registerMobileSidebar', () => {
renderOverlay(overlay)
const send = source === 'touch' ? touch : pointer
send(main, source === 'touch' ? 'touchstart' : 'pointerdown', 100, 200, 100)
- expect(send(main, `${source}move`, 300, 202, 300).defaultPrevented).toBe(false)
+ expect(send(main, `${source}move`, 300, 202, 300).defaultPrevented).toBe(true)
+ expect(document.documentElement.hasAttribute('data-dsh-mobile-sidebar-dragging')).toBe(true)
+ expect(document.documentElement.style.getPropertyValue('--dsh-mobile-sidebar-offset')).toBe('200px')
send(main, source === 'touch' ? 'touchend' : 'pointerup', 320, 202, 400)
- expect(document.documentElement.hasAttribute('data-dsh-mobile-sidebar-open')).toBe(false)
- expect(document.documentElement.style.getPropertyValue('--dsh-mobile-sidebar-width')).toBe('319px')
- fireEvent.click(screen.getByRole('button', { name: 'Open sidebar' }))
+ expect(document.documentElement.hasAttribute('data-dsh-mobile-sidebar-open')).toBe(true)
+ expect(document.documentElement.hasAttribute('data-dsh-mobile-sidebar-dragging')).toBe(false)
+ expect(document.documentElement.style.getPropertyValue('--dsh-mobile-sidebar-offset')).toBe('')
send(row, source === 'touch' ? 'touchstart' : 'pointerdown', 220, 200, 500)
- expect(send(row, `${source}move`, 20, 202, 700).defaultPrevented).toBe(false)
+ expect(send(row, `${source}move`, 20, 202, 700).defaultPrevented).toBe(true)
send(row, source === 'touch' ? 'touchend' : 'pointerup', 20, 202, 800)
- expect(document.documentElement.hasAttribute('data-dsh-mobile-sidebar-open')).toBe(true)
- expect(document.documentElement.style.getPropertyValue('--dsh-mobile-sidebar-width')).toBe('319px')
+ expect(document.documentElement.hasAttribute('data-dsh-mobile-sidebar-open')).toBe(false)
+ expect(document.documentElement.hasAttribute('data-dsh-mobile-sidebar-dragging')).toBe(false)
+ expect(document.documentElement.style.getPropertyValue('--dsh-mobile-sidebar-offset')).toBe('')
+ fireEvent.click(row)
+ expect(select).not.toHaveBeenCalled()
+ fireEvent.click(screen.getByRole('button', { name: 'Open sidebar' }))
fireEvent.click(row)
expect(select).toHaveBeenCalledTimes(1)
- fireEvent.click(overlay.querySelector('[data-dsh-mobile-sidebar-shade]')!)
+ })
+
+ it.each(['touchcancel', 'blur', 'resize'])('clears drag-only styling after %s so conversation toggles can animate', (cancel) => {
+ const { main, overlay } = setupFrame()
+ register()
+ renderOverlay(overlay)
+ touch(main, 'touchstart', 100, 200, 100)
+ touch(main, 'touchmove', 180, 202, 300)
+ expect(document.documentElement.hasAttribute('data-dsh-mobile-sidebar-dragging')).toBe(true)
+ if (cancel === 'touchcancel')
+ touch(main, cancel, 180, 202, 400)
+ else
+ fireEvent(window, new Event(cancel))
+ expect(document.documentElement.hasAttribute('data-dsh-mobile-sidebar-dragging')).toBe(false)
+ expect(document.documentElement.style.getPropertyValue('--dsh-mobile-sidebar-offset')).toBe('')
+ fireEvent.click(screen.getByRole('button', { name: 'Open sidebar' }))
+ expect(document.documentElement.hasAttribute('data-dsh-mobile-sidebar-open')).toBe(true)
+ expect(document.documentElement.hasAttribute('data-dsh-mobile-sidebar-dragging')).toBe(false)
+ })
+
+ it.each(['input', 'pre'])('leaves gestures on editable or horizontally scrolling %s content alone', (tag) => {
+ const { main, overlay } = setupFrame()
+ const target = document.createElement(tag)
+ if (tag === 'pre') {
+ target.style.overflowX = 'auto'
+ Object.defineProperties(target, { scrollWidth: { value: 400 }, clientWidth: { value: 100 } })
+ }
+ main.append(target)
+ register()
+ renderOverlay(overlay)
+ touch(target, 'touchstart', 100, 200, 100)
+ expect(touch(target, 'touchmove', 300, 202, 300).defaultPrevented).toBe(false)
+ touch(target, 'touchend', 300, 202, 400)
expect(document.documentElement.hasAttribute('data-dsh-mobile-sidebar-open')).toBe(false)
})
diff --git a/packages/dsh-tauri-mobile-ui/src/client/register/sidebar.tsx b/packages/dsh-tauri-mobile-ui/src/client/register/sidebar.tsx
index 309b26eb..615d5ccf 100644
--- a/packages/dsh-tauri-mobile-ui/src/client/register/sidebar.tsx
+++ b/packages/dsh-tauri-mobile-ui/src/client/register/sidebar.tsx
@@ -1,5 +1,6 @@
import type { ClientContext, ParentMessage } from 'dsh-tauri/client'
import type { KeyboardEvent } from 'react'
+import type { SidebarGesture, SidebarGesturePoint } from '../service/sidebar-gesture'
import { CirclePlus, Icon, LayoutSideContentLeft } from 'dsh-tauri-ui/client'
import {
defineRegister,
@@ -12,23 +13,41 @@ import { useSyncExternalStore } from 'react'
import { createPortal } from 'react-dom'
import { PLUGIN_ID } from '../../shared/constants'
import { locale } from '../locales'
+import { createSidebarGesture, finishSidebarGesture, moveSidebarGesture, SIDEBAR_CLICK_SUPPRESSION_MS } from '../service/sidebar-gesture'
import { getMobileSessionId, getMobileSessionTitle } from '../service/sidebar-session'
const SHELL_OVERLAY_SLOT = 'shell.overlay'
const SIDEBAR_TOGGLE_COMMAND = 'dsh://sidebar:toggle'
const SIDEBAR_COLLAPSED_EVENT = 'dsh://sidebar:collapsed'
const SIDEBAR_BREAKPOINT = 1024
-const SIDEBAR_WIDTH_PROPERTY = '--dsh-mobile-sidebar-width'
+const SIDEBAR_PROPERTIES = [
+ '--dsh-mobile-sidebar-width',
+ '--dsh-mobile-sidebar-offset',
+] as const
const LAYOUT_SELECTOR = '[data-shell-overlay], [class$="_frame"], [class$="_sidebarCol"], [class$="_centerCol"], [data-slot="main"]'
interface SidebarSnapshot {
mobile: boolean
open: boolean
+ dragging: boolean
+ offset: number
width: number
starting: boolean
startFailed: boolean
}
+interface ActiveGesture {
+ state: SidebarGesture
+ target: Element
+ frame: HTMLElement
+ source: 'touch' | 'pointer'
+}
+
+interface InlineProperty {
+ value: string
+ priority: string
+}
+
function getSidebarWidth(): number {
return Math.min(320, Math.max(1, Math.floor(window.innerWidth * 0.82)))
}
@@ -43,6 +62,39 @@ function canOwnMobileSidebar(): boolean {
&& (frame === null || frame.hasAttribute('data-rightbar-collapsed'))
}
+function canStartGesture(target: EventTarget | null, frame: HTMLElement): target is Element {
+ if (!(target instanceof Element) || !frame.contains(target))
+ return false
+ if (target.closest('input,textarea,select,[contenteditable]') !== null)
+ return false
+ if (target.closest('[data-dsh-mobile-sidebar-toggle], [data-dsh-mobile-new-session]') !== null)
+ return false
+ if (target.closest('[data-shell-overlay]') !== null && target.closest('[data-dsh-mobile-sidebar-shade]') === null)
+ return false
+ if (window.getSelection()?.isCollapsed === false)
+ return false
+ let current: Element | null = target
+ while (current !== null && current !== frame) {
+ const style = getComputedStyle(current)
+ if ((style.overflowX === 'auto' || style.overflowX === 'scroll') && current.scrollWidth > current.clientWidth + 1)
+ return false
+ current = current.parentElement
+ }
+ return true
+}
+
+function eventTime(event: Event): number {
+ return event.timeStamp || performance.now()
+}
+
+function touchPoint(touch: Touch, event: TouchEvent): SidebarGesturePoint {
+ return { id: touch.identifier, x: touch.clientX, y: touch.clientY, time: eventTime(event) }
+}
+
+function pointerPoint(event: PointerEvent): SidebarGesturePoint {
+ return { id: event.pointerId, x: event.clientX, y: event.clientY, time: eventTime(event) }
+}
+
function activateIcon(event: KeyboardEvent<SVGSVGElement>, activate: () => void): void {
if (event.key !== 'Enter' && event.key !== ' ')
return
@@ -63,8 +115,10 @@ export const registerMobileSidebar = defineRegister<ClientContext>((controller,
return
const root = document.documentElement
- const previousWidth = root.style.getPropertyValue(SIDEBAR_WIDTH_PROPERTY)
- const previousWidthPriority = root.style.getPropertyPriority(SIDEBAR_WIDTH_PROPERTY)
+ const previousProperties = new Map<string, InlineProperty>(SIDEBAR_PROPERTIES.map(name => [name, {
+ value: root.style.getPropertyValue(name),
+ priority: root.style.getPropertyPriority(name),
+ }]))
const navbarHost = document.createElement('div')
navbarHost.setAttribute('data-dsh-mobile-navbar-host', '')
let navbar: HTMLElement | null = null
@@ -77,6 +131,8 @@ export const registerMobileSidebar = defineRegister<ClientContext>((controller,
let snapshot: SidebarSnapshot = {
mobile: canOwnMobileSidebar(),
open: false,
+ dragging: false,
+ offset: 0,
width: getSidebarWidth(),
starting: false,
startFailed: false,
@@ -86,11 +142,27 @@ export const registerMobileSidebar = defineRegister<ClientContext>((controller,
const sessionSource = adapter.sessions.list
const getSessionSnapshot = (): unknown => sessionSource?.getSnapshot()
let selectedSession = getMobileSessionId(getSessionSnapshot())
+ let gesture: ActiveGesture | null = null
+ let suppressClickUntil = 0
+ let suppressedClickTarget: Element | null = null
+ let suppressedClickFrame: HTMLElement | null = null
const accessibility = new Map<HTMLElement, { ariaHidden: string | null, inert: boolean }>()
let focusRestoreTarget: HTMLElement | SVGElement | null = null
let focusedDrawer: { element: HTMLElement, tabIndex: string | null } | null = null
let focusDrawerOnOpen = false
+ const clearGesture = (): void => {
+ const current = gesture
+ // Flush the last drag position before restoring CSS transitions, including same-frame releases.
+ if (current !== null && snapshot.dragging)
+ current.frame.querySelector('[class$="_centerCol"]')?.getBoundingClientRect()
+ gesture = null
+ if (current?.source === 'pointer' && current.state.axis === 'x'
+ && typeof current.frame.hasPointerCapture === 'function'
+ && current.frame.hasPointerCapture(current.state.id)) {
+ current.frame.releasePointerCapture(current.state.id)
+ }
+ }
const restoreFocusedDrawer = (): void => {
if (focusedDrawer === null)
return
@@ -158,6 +230,8 @@ export const registerMobileSidebar = defineRegister<ClientContext>((controller,
const reconcileFrame = (): void => {
const previousHost = getNavbarHost()
const frame = getFrame()
+ if (gesture !== null && (frame !== gesture.frame || !gesture.target.isConnected || !frame?.contains(gesture.target)))
+ resetGesture()
const center = snapshot.mobile ? frame?.querySelector<HTMLElement>('[class$="_centerCol"]') : null
if (center) {
if (navbar !== null && navbar.parentNode === null && !navbarHost.hasChildNodes())
@@ -172,20 +246,34 @@ export const registerMobileSidebar = defineRegister<ClientContext>((controller,
if (previousHost !== getNavbarHost())
notify()
}
+ const restoreProperties = (): void => {
+ previousProperties.forEach((property, name) => {
+ if (property.value !== '')
+ root.style.setProperty(name, property.value, property.priority)
+ else
+ root.style.removeProperty(name)
+ })
+ }
const syncDom = (): void => {
root.toggleAttribute('data-dsh-mobile-sidebar', snapshot.mobile)
root.toggleAttribute('data-dsh-mobile-sidebar-open', snapshot.mobile && snapshot.open)
- if (snapshot.mobile)
- root.style.setProperty(SIDEBAR_WIDTH_PROPERTY, `${snapshot.width}px`)
- else if (previousWidth !== '')
- root.style.setProperty(SIDEBAR_WIDTH_PROPERTY, previousWidth, previousWidthPriority)
- else
- root.style.removeProperty(SIDEBAR_WIDTH_PROPERTY)
+ root.toggleAttribute('data-dsh-mobile-sidebar-dragging', snapshot.mobile && snapshot.dragging)
+ if (snapshot.mobile) {
+ root.style.setProperty(SIDEBAR_PROPERTIES[0], `${snapshot.width}px`)
+ if (snapshot.dragging)
+ root.style.setProperty(SIDEBAR_PROPERTIES[1], `${snapshot.offset}px`)
+ else
+ root.style.removeProperty(SIDEBAR_PROPERTIES[1])
+ }
+ else {
+ restoreProperties()
+ }
reconcileFrame()
}
const publish = (next: SidebarSnapshot): void => {
if (
next.mobile === snapshot.mobile && next.open === snapshot.open
+ && next.dragging === snapshot.dragging && next.offset === snapshot.offset
&& next.width === snapshot.width && next.starting === snapshot.starting
&& next.startFailed === snapshot.startFailed
) {
@@ -200,6 +288,7 @@ export const registerMobileSidebar = defineRegister<ClientContext>((controller,
return
const wasOpen = snapshot.open
const changed = open !== wasOpen
+ clearGesture()
if (open && !wasOpen) {
focusDrawerOnOpen = true
const active = document.activeElement
@@ -208,28 +297,41 @@ export const registerMobileSidebar = defineRegister<ClientContext>((controller,
? active
: null
}
- publish({ ...snapshot, open })
+ publish({ ...snapshot, open, dragging: false, offset: open ? snapshot.width : 0 })
if (!open && wasOpen)
restoreFocusTarget()
if (changed)
safeReportCollapsed(!open)
}
+ // keep:function `reconcileFrame` 属于 publish → syncDom → reconcileFrame 环,声明式函数才能在环内前向引用。
+ function resetGesture(): void {
+ clearGesture()
+ publish({ ...snapshot, dragging: false, offset: snapshot.open ? snapshot.width : 0 })
+ }
const syncMobile = (): void => {
const mobile = canOwnMobileSidebar()
const width = getSidebarWidth()
const wasMobile = snapshot.mobile
if (!mobile) {
- publish({ ...snapshot, mobile: false, open: false, width, startFailed: false })
+ clearGesture()
+ suppressedClickTarget = null
+ suppressedClickFrame = null
+ suppressClickUntil = 0
+ publish({ ...snapshot, mobile: false, open: false, dragging: false, offset: 0, width, startFailed: false })
if (wasMobile) {
restoreFocusTarget()
controller.timeout(() => safeReportCollapsed(getFrame()?.hasAttribute('data-sidebar-collapsed') === true), 0)
}
return
}
+ if (width !== snapshot.width)
+ clearGesture()
publish({
...snapshot,
mobile: true,
width,
+ dragging: gesture !== null && snapshot.dragging,
+ offset: gesture !== null && snapshot.dragging ? Math.min(width, snapshot.offset) : snapshot.open ? width : 0,
})
if (!wasMobile)
safeReportCollapsed(!snapshot.open)
@@ -275,7 +377,119 @@ export const registerMobileSidebar = defineRegister<ClientContext>((controller,
if (event.key === 'Escape' && !event.defaultPrevented && snapshot.mobile && snapshot.open)
setOpen(false)
})
+ controller.listen('click', (event) => {
+ const target = event.target
+ if (performance.now() >= suppressClickUntil || suppressedClickTarget === null || !(target instanceof Element))
+ return
+ const frame = suppressedClickFrame
+ const retargeted = frame?.contains(target) && (target.closest('[data-dsh-mobile-sidebar-shade]') !== null
+ || target === frame || target === frame.querySelector('[class$="_centerCol"]'))
+ if (!suppressedClickTarget.contains(target) && !retargeted)
+ return
+ event.preventDefault()
+ event.stopImmediatePropagation()
+ suppressClickUntil = 0
+ suppressedClickTarget = null
+ suppressedClickFrame = null
+ }, { capture: true })
+
+ const beginGesture = (point: SidebarGesturePoint, target: EventTarget | null, source: ActiveGesture['source']): void => {
+ const frame = getFrame()
+ if (!snapshot.mobile || gesture !== null || frame === null || !canStartGesture(target, frame))
+ return
+ suppressedClickTarget = null
+ suppressedClickFrame = null
+ suppressClickUntil = 0
+ gesture = { state: createSidebarGesture(point, snapshot.open, snapshot.width), target, frame, source }
+ }
+ const moveGesture = (point: SidebarGesturePoint, event: TouchEvent | PointerEvent, source: ActiveGesture['source']): void => {
+ if (gesture === null || gesture.source !== source || gesture.state.id !== point.id)
+ return
+ const result = moveSidebarGesture(gesture.state, point, snapshot.width, event.cancelable)
+ if (result.gesture === null) {
+ resetGesture()
+ return
+ }
+ const claimed = gesture.state.axis === null && result.gesture.axis === 'x'
+ gesture.state = result.gesture
+ if (result.offset === undefined)
+ return
+ if (claimed && source === 'pointer' && typeof gesture.frame.setPointerCapture === 'function')
+ gesture.frame.setPointerCapture(point.id)
+ event.preventDefault()
+ publish({ ...snapshot, dragging: true, offset: result.offset })
+ }
+ const endGesture = (point: SidebarGesturePoint | undefined, cancelled: boolean, source: ActiveGesture['source']): void => {
+ if (gesture === null || gesture.source !== source || (point !== undefined && gesture.state.id !== point.id))
+ return
+ const current = gesture
+ const result = cancelled ? null : finishSidebarGesture(current.state, point, snapshot.width)
+ clearGesture()
+ if (result === null) {
+ resetGesture()
+ return
+ }
+ setOpen(result.open)
+ suppressedClickTarget = result.suppressClick ? current.target : null
+ suppressedClickFrame = result.suppressClick ? current.frame : null
+ suppressClickUntil = result.suppressClick ? performance.now() + SIDEBAR_CLICK_SUPPRESSION_MS : 0
+ }
+ controller.listen('touchstart', (event) => {
+ if (event.touches.length !== 1) {
+ if (gesture?.source === 'touch')
+ resetGesture()
+ return
+ }
+ if (!event.defaultPrevented)
+ beginGesture(touchPoint(event.touches[0], event), event.target, 'touch')
+ }, { passive: true })
+ controller.listen('touchmove', (event) => {
+ if (gesture?.source !== 'touch')
+ return
+ if (event.touches.length !== 1) {
+ resetGesture()
+ return
+ }
+ const touch = [...event.touches].find(point => point.identifier === gesture?.state.id)
+ if (touch)
+ moveGesture(touchPoint(touch, event), event, 'touch')
+ }, { passive: false })
+ const endTouch = (event: TouchEvent, cancelled: boolean): void => {
+ const touch = [...event.changedTouches].find(point => point.identifier === gesture?.state.id)
+ if (touch || cancelled)
+ endGesture(touch ? touchPoint(touch, event) : undefined, cancelled, 'touch')
+ }
+ controller.listen('touchend', event => endTouch(event, false))
+ controller.listen('touchcancel', event => endTouch(event, true))
+ controller.listen('pointerdown', (event) => {
+ if (event.pointerType !== 'touch' && event.button === 0 && event.isPrimary !== false && !event.defaultPrevented)
+ beginGesture(pointerPoint(event), event.target, 'pointer')
+ })
+ controller.listen('pointermove', (event) => {
+ if (event.pointerType === 'touch')
+ return
+ if (gesture?.source === 'pointer' && event.buttons === 0) {
+ resetGesture()
+ return
+ }
+ moveGesture(pointerPoint(event), event, 'pointer')
+ }, { passive: false })
+ controller.listen('pointerup', (event) => {
+ if (event.pointerType !== 'touch')
+ endGesture(pointerPoint(event), false, 'pointer')
+ })
+ controller.listen('pointercancel', (event) => {
+ if (event.pointerType !== 'touch')
+ endGesture(pointerPoint(event), true, 'pointer')
+ })
+ controller.listen('lostpointercapture', (event) => {
+ if (gesture?.source === 'pointer' && gesture.state.id === event.pointerId)
+ resetGesture()
+ })
+ controller.listenWindow('blur', () => resetGesture())
+
const resize = (): void => {
+ resetGesture()
syncMobile()
reconcileFrame()
}
@@ -301,6 +515,8 @@ export const registerMobileSidebar = defineRegister<ClientContext>((controller,
return true
if (focusedDrawer !== null && !focusedDrawer.element.isConnected)
return true
+ if (gesture !== null && (!gesture.target.isConnected || !gesture.frame.isConnected))
+ return true
return [...record.addedNodes, ...record.removedNodes].some(node => node instanceof Element
&& (node.matches(LAYOUT_SELECTOR) || node.querySelector(LAYOUT_SELECTOR) !== null))
})
@@ -318,7 +534,11 @@ export const registerMobileSidebar = defineRegister<ClientContext>((controller,
if (navbar !== null && navbar.parentNode === null && !navbarHost.hasChildNodes())
navbarHost.append(navbar)
listeners.clear()
- snapshot = { ...snapshot, mobile: false, open: false }
+ clearGesture()
+ suppressedClickTarget = null
+ suppressedClickFrame = null
+ suppressClickUntil = 0
+ snapshot = { ...snapshot, mobile: false, open: false, dragging: false, offset: 0 }
syncDom()
restoreFocusTarget()
safeReportCollapsed(getFrame()?.hasAttribute('data-sidebar-collapsed') === true)
@@ -376,7 +596,7 @@ export const registerMobileSidebar = defineRegister<ClientContext>((controller,
</nav>,
host,
)}
- <div data-dsh-mobile-sidebar-overlay>
+ <div data-dsh-mobile-sidebar-overlay data-dsh-mobile-sidebar-dragging={current.dragging || undefined}>
<button
type="button"
data-dsh-mobile-sidebar-shade
diff --git a/packages/dsh-tauri-mobile-ui/src/client/service/sidebar-gesture.test.ts b/packages/dsh-tauri-mobile-ui/src/client/service/sidebar-gesture.test.ts
new file mode 100644
index 00000000..5308db3a
--- /dev/null
+++ b/packages/dsh-tauri-mobile-ui/src/client/service/sidebar-gesture.test.ts
@@ -0,0 +1,63 @@
+import { describe, expect, it } from 'vitest'
+import { createSidebarGesture, finishSidebarGesture, moveSidebarGesture } from './sidebar-gesture'
+
+const point = (x: number, y: number, time: number) => ({ id: 1, x, y, time })
+
+describe('sidebar gesture state machine', () => {
+ it('locks horizontally only after enough movement and clamps the reveal width', () => {
+ const gesture = createSidebarGesture(point(100, 200, 100), false, 319)
+ expect(moveSidebarGesture(gesture, point(105, 202, 120), 319, true)).toEqual({ gesture })
+ const move = moveSidebarGesture(gesture, point(280, 202, 300), 319, true)
+ expect(move.offset).toBe(180)
+ expect(move.gesture?.axis).toBe('x')
+ expect(moveSidebarGesture(move.gesture!, point(500, 202, 400), 319, true).offset).toBe(319)
+ })
+
+ it.each([
+ { open: false, end: point(90, 200, 200) },
+ { open: true, end: point(110, 200, 200) },
+ { open: false, end: point(105, 250, 200) },
+ ])('abandons wrong directions and vertical scrolling from %j', ({ open, end }) => {
+ expect(moveSidebarGesture(createSidebarGesture(point(100, 200, 100), open, 319), end, 319, true)).toEqual({ gesture: null })
+ })
+
+ it('abandons noncancelable horizontal moves instead of committing release travel', () => {
+ const gesture = createSidebarGesture(point(100, 200, 100), false, 319)
+ expect(moveSidebarGesture(gesture, point(300, 200, 200), 319, false)).toEqual({ gesture: null })
+ expect(finishSidebarGesture(gesture, point(500, 200, 300), 319)).toBeNull()
+ })
+
+ it('settles slow swipes by the revealed midpoint', () => {
+ const closed = createSidebarGesture(point(100, 200, 100), false, 319)
+ const short = moveSidebarGesture(closed, point(180, 200, 400), 319, true).gesture!
+ const long = moveSidebarGesture(closed, point(280, 200, 400), 319, true).gesture!
+ expect(finishSidebarGesture(short, point(180, 200, 700), 319)).toEqual({ open: false, suppressClick: true })
+ expect(finishSidebarGesture(long, point(280, 200, 700), 319)).toEqual({ open: true, suppressClick: true })
+ })
+
+ it('uses release velocity for short flings but never for tiny accidental motion', () => {
+ const gesture = createSidebarGesture(point(100, 200, 100), false, 319)
+ const fling = moveSidebarGesture(gesture, point(140, 200, 140), 319, true).gesture!
+ const tiny = moveSidebarGesture(gesture, point(108, 200, 105), 319, true).gesture!
+ expect(finishSidebarGesture(fling, point(150, 200, 150), 319)).toEqual({ open: true, suppressClick: true })
+ expect(finishSidebarGesture(tiny, point(108, 200, 110), 319)).toEqual({ open: false, suppressClick: true })
+ })
+
+ it('suppresses out-and-back claimed drags but leaves genuine taps alone', () => {
+ const tap = createSidebarGesture(point(220, 200, 100), true, 319)
+ expect(finishSidebarGesture(tap, point(220, 200, 200), 319)).toBeNull()
+ const claimed = moveSidebarGesture(tap, point(140, 200, 300), 319, true).gesture!
+ const returned = moveSidebarGesture(claimed, point(220, 200, 600), 319, true).gesture!
+ expect(finishSidebarGesture(returned, point(220, 200, 900), 319)).toEqual({ open: true, suppressClick: true })
+ })
+
+ it('expires older samples for a direction change near release', () => {
+ let gesture = createSidebarGesture(point(350, 200, 100), true, 319)
+ for (const sample of [point(100, 200, 200), point(150, 200, 400), point(200, 200, 500)])
+ gesture = moveSidebarGesture(gesture, sample, 319, true).gesture!
+ expect(gesture.samples[0].time).toBe(200)
+ gesture = moveSidebarGesture(gesture, point(250, 200, 550), 319, true).gesture!
+ expect(gesture.samples[0].time).toBe(400)
+ expect(finishSidebarGesture(gesture, point(270, 200, 580), 319)?.open).toBe(true)
+ })
+})
diff --git a/packages/dsh-tauri-mobile-ui/src/client/service/sidebar-gesture.ts b/packages/dsh-tauri-mobile-ui/src/client/service/sidebar-gesture.ts
new file mode 100644
index 00000000..ec6913bf
--- /dev/null
+++ b/packages/dsh-tauri-mobile-ui/src/client/service/sidebar-gesture.ts
@@ -0,0 +1,84 @@
+const AXIS_LOCK_DISTANCE = 8
+const SWIPE_DISTANCE = 18
+const SWIPE_VELOCITY = 0.5
+
+export const SIDEBAR_CLICK_SUPPRESSION_MS = 400
+
+export interface SidebarGesturePoint {
+ id: number
+ x: number
+ y: number
+ time: number
+}
+
+export interface SidebarGesture {
+ id: number
+ startX: number
+ startY: number
+ base: number
+ open: boolean
+ axis: 'x' | null
+ samples: readonly SidebarGesturePoint[]
+}
+
+export interface SidebarGestureMove {
+ gesture: SidebarGesture | null
+ offset?: number
+}
+
+export function createSidebarGesture(point: SidebarGesturePoint, open: boolean, width: number): SidebarGesture {
+ return {
+ id: point.id,
+ startX: point.x,
+ startY: point.y,
+ base: open ? width : 0,
+ open,
+ axis: null,
+ samples: [point],
+ }
+}
+
+export function moveSidebarGesture(
+ gesture: SidebarGesture,
+ point: SidebarGesturePoint,
+ width: number,
+ cancelable: boolean,
+): SidebarGestureMove {
+ const dx = point.x - gesture.startX
+ const dy = point.y - gesture.startY
+ if (gesture.axis === null) {
+ if (Math.max(Math.abs(dx), Math.abs(dy)) < AXIS_LOCK_DISTANCE)
+ return { gesture }
+ if (Math.abs(dy) >= Math.abs(dx) * 0.8 || (gesture.open ? dx > 0 : dx < 0))
+ return { gesture: null }
+ }
+ if (!cancelable)
+ return { gesture: null }
+ const samples = [...gesture.samples, point]
+ while (samples.length > 2 && samples[1].time < point.time - 120)
+ samples.shift()
+ return {
+ gesture: { ...gesture, axis: 'x', samples },
+ offset: Math.min(width, Math.max(0, gesture.base + dx)),
+ }
+}
+
+export function finishSidebarGesture(
+ gesture: SidebarGesture,
+ point: SidebarGesturePoint | undefined,
+ width: number,
+): { open: boolean, suppressClick: boolean } | null {
+ if (gesture.axis !== 'x')
+ return null
+ const samples = point === undefined ? gesture.samples : [...gesture.samples, point]
+ const first = samples[0]
+ const last = samples[samples.length - 1]
+ const travel = last.x - gesture.startX
+ const velocity = (last.x - first.x) / Math.max(1, last.time - first.time)
+ const fling = Math.abs(velocity) >= SWIPE_VELOCITY && Math.abs(travel) >= SWIPE_DISTANCE
+ const position = Math.min(width, Math.max(0, gesture.base + travel))
+ return {
+ open: fling ? velocity > 0 : position >= width * 0.5,
+ suppressClick: true,
+ }
+}
diff --git a/packages/dsh-tauri-mobile-ui/src/client/styles/mobile.cssr.test.ts b/packages/dsh-tauri-mobile-ui/src/client/styles/mobile.cssr.test.ts
index b3a90f28..70b1e927 100644
--- a/packages/dsh-tauri-mobile-ui/src/client/styles/mobile.cssr.test.ts
+++ b/packages/dsh-tauri-mobile-ui/src/client/styles/mobile.cssr.test.ts
@@ -145,9 +145,15 @@ describe('mobile conversation layout', () => {
})
})
- it('keeps click transitions on the center and shade without drag-only overrides', () => {
- const css = root.toString()
- expect(css).not.toContain('data-dsh-mobile-sidebar-dragging')
+ it('limits transition suppression and offsets to active drags so clicks and releases still animate', () => {
+ for (const selector of ['html[data-dsh-mobile-sidebar-dragging] [class$="_centerCol"]', 'html[data-dsh-mobile-sidebar-dragging] [data-dsh-mobile-sidebar-shade]']) {
+ expect(declarations(selector)).toMatchObject({
+ transform: 'translate3d(var(--dsh-mobile-sidebar-offset), 0, 0)',
+ transition: 'none',
+ })
+ }
+ expect(declarations('html[data-dsh-mobile-sidebar] [class$="_centerCol"]').transform).toBe('translate3d(0, 0, 0)')
+ expect(declarations('html[data-dsh-mobile-sidebar-open] [class$="_centerCol"]').transform).toBe('translate3d(var(--dsh-mobile-sidebar-width), 0, 0)')
expect(declarations('html[data-dsh-mobile-sidebar] [class$="_centerCol"]').transition).toContain('transform 240ms cubic-bezier(.2, .8, .2, 1)')
expect(declarations('[data-dsh-mobile-sidebar-shade]').transition).toContain('transform 240ms cubic-bezier(.2, .8, .2, 1)')
const reducedMotion = root.nodes[0]
diff --git a/packages/dsh-tauri-mobile-ui/src/client/styles/mobile.cssr.ts b/packages/dsh-tauri-mobile-ui/src/client/styles/mobile.cssr.ts
index 018907e8..8526f1ed 100644
--- a/packages/dsh-tauri-mobile-ui/src/client/styles/mobile.cssr.ts
+++ b/packages/dsh-tauri-mobile-ui/src/client/styles/mobile.cssr.ts
@@ -107,6 +107,12 @@ export default c(`@media ${MOBILE_MEDIA_QUERIES.join(' and ')}`, [
borderRadius: '24px 0 0 24px',
boxShadow: 'var(--dsw-shadow-lv3)',
}),
+ c('html[data-dsh-mobile-sidebar-dragging] [class$="_centerCol"]', {
+ transform: 'translate3d(var(--dsh-mobile-sidebar-offset), 0, 0)',
+ borderRadius: 'clamp(0px, calc(var(--dsh-mobile-sidebar-offset) / 10), 24px) 0 0 clamp(0px, calc(var(--dsh-mobile-sidebar-offset) / 10), 24px)',
+ boxShadow: 'var(--dsw-shadow-lv3)',
+ transition: 'none',
+ }),
c('html[data-dsh-mobile-sidebar] body[data-ds-dark-theme] [class$="_centerCol"]', {
colorScheme: 'dark',
}),
@@ -229,6 +235,13 @@ export default c(`@media ${MOBILE_MEDIA_QUERIES.join(' and ')}`, [
pointerEvents: 'auto',
transitionDelay: '0s',
}),
+ c('html[data-dsh-mobile-sidebar-dragging] [data-dsh-mobile-sidebar-shade]', {
+ transform: 'translate3d(var(--dsh-mobile-sidebar-offset), 0, 0)',
+ opacity: '1',
+ visibility: 'visible',
+ pointerEvents: 'auto',
+ transition: 'none',
+ }),
c('@media (prefers-reduced-motion: reduce)', [
c('html[data-dsh-mobile-sidebar] [class$="_centerCol"], html[data-dsh-mobile-sidebar] [data-dsh-mobile-sidebar-shade]', {
transition: 'none !important',
diff --git a/test/e2e/plugins/dsh-tauri-mobile-settings.e2e.ts b/test/e2e/plugins/dsh-tauri-mobile-settings.e2e.ts
index e4a66f24..f6aca552 100644
--- a/test/e2e/plugins/dsh-tauri-mobile-settings.e2e.ts
+++ b/test/e2e/plugins/dsh-tauri-mobile-settings.e2e.ts
@@ -103,6 +103,61 @@ describe('mobile settings official host composition', () => {
}
})
+ it('settles real conversation swipes with transitions and keeps subsequent tap animations', async () => {
+ const app = await newDshPage(browser, {
+ viewport: { width: 390, height: 844 },
+ hasTouch: true,
+ isMobile: true,
+ ready: '[data-dsh-mobile-sidebar-toggle]',
+ })
+ try {
+ await app.page.emulateMedia({ reducedMotion: 'no-preference' })
+ await app.frame.locator('[data-dsh-mobile-new-session]').tap()
+ await expect.poll(() => app.frame.locator('[data-conversation-scroll]').count(), { message: '必须在真实会话区验证手势,而非插件面板' }).toBe(1)
+ const center = app.frame.locator('[class$="_centerCol"]')
+ const toggle = app.frame.locator('[data-dsh-mobile-sidebar-toggle]')
+ const shade = app.frame.locator('[data-dsh-mobile-sidebar-shade]')
+ await center.evaluate((element) => {
+ element.setAttribute('data-e2e-transform-count', '0')
+ element.addEventListener('transitionrun', (event) => {
+ if (event.target === element && (event as TransitionEvent).propertyName === 'transform')
+ element.setAttribute('data-e2e-transform-count', String(Number(element.getAttribute('data-e2e-transform-count')) + 1))
+ })
+ })
+ const cdp = await app.page.context().newCDPSession(app.page)
+ const swipe = async (start: number, end: number) => {
+ await cdp.send('Input.dispatchTouchEvent', { type: 'touchStart', touchPoints: [{ x: start, y: 220 }] })
+ for (let step = 1; step <= 4; step++) {
+ await cdp.send('Input.dispatchTouchEvent', { type: 'touchMove', touchPoints: [{ x: start + (end - start) * step / 4, y: 220 }] })
+ }
+ expect(await app.frame.locator('html').getAttribute('data-dsh-mobile-sidebar-dragging'), '横向会话手势必须接管拖动').toBe('')
+ expect(await center.evaluate(element => getComputedStyle(element).transitionDuration), '跟手阶段不应滞后动画').toBe('0s')
+ await cdp.send('Input.dispatchTouchEvent', { type: 'touchEnd', touchPoints: [] })
+ expect(await app.frame.locator('html').getAttribute('data-dsh-mobile-sidebar-dragging'), '松手必须立即清理禁用过渡状态').toBeNull()
+ }
+ await swipe(80, 280)
+ await expect.poll(() => toggle.getAttribute('aria-expanded')).toBe('true')
+ await expect.poll(() => center.getAttribute('data-e2e-transform-count'), { message: '会话区松手展开必须真正启动过渡' }).toBe('1')
+ await expect.poll(async () => Math.round((await center.boundingBox())!.x)).toBe(319)
+ await swipe(370, 180)
+ await expect.poll(() => toggle.getAttribute('aria-expanded')).toBe('false')
+ await expect.poll(() => center.getAttribute('data-e2e-transform-count'), { message: '松手收起必须真正启动过渡' }).toBe('2')
+ await expect.poll(async () => Math.round((await center.boundingBox())!.x)).toBe(0)
+ await toggle.tap()
+ await expect.poll(() => center.getAttribute('data-e2e-transform-count'), { message: '拖动后点击展开不能丢失动画' }).toBe('3')
+ await expect.poll(async () => Math.round((await center.boundingBox())!.x)).toBe(319)
+ await shade.tap()
+ await expect.poll(() => center.getAttribute('data-e2e-transform-count'), { message: '拖动后点击收起不能丢失动画' }).toBe('4')
+ await expect.poll(async () => Math.round((await center.boundingBox())!.x)).toBe(0)
+ await cdp.detach()
+ expectNoSyntheticFallbacks(app)
+ expect(app.errors).toEqual([])
+ }
+ finally {
+ await app.close()
+ }
+ })
+
it.each([{ width: 320, height: 568 }, { width: 430, height: 943 }, { width: 767, height: 800 }])('keeps the official section mounted through categories at $width pixels', async ({ width, height }) => {
const { app, dialog } = await openPhoneSettings(width, height)
try {