Skip to content

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

feat(mobile): land the mobile sidebar and settings drilldown stack on main (#926)

Mao Mr662f777b4c73
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index ff9022a6..a3eace63 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -4,7 +4,7 @@ on:
push:
branches: [main]
pull_request:
- branches: [main]
+ branches: [main, feat/mobile-sidebar]
permissions:
contents: read
@@ -127,15 +127,23 @@ jobs:
DSH_E2E_DSH_BIN: ${{ runner.temp }}/dsh-cli/node_modules/@deepseek-ai/dsh/lib/bin.js
run: node node_modules/vitest/vitest.mjs run --project plugin --exclude test/e2e/plugins/dsh-tauri-extension-panel.e2e.ts
+ - name: Mobile settings composition (legacy core)
+ env:
+ DSH_E2E_DSH_BIN: ${{ runner.temp }}/dsh-cli/node_modules/@deepseek-ai/dsh/lib/bin.js
+ run: |
+ for seed in 201 202 203 204 205; do
+ node node_modules/vitest/vitest.mjs run --project plugin --sequence.shuffle --sequence.seed="$seed" test/e2e/plugins/dsh-tauri-mobile-settings.e2e.ts || exit $?
+ done
+
- name: Install current dsh CLI (isolated)
run: npm install --prefix "$RUNNER_TEMP/dsh-cli-current" --no-audit --no-fund @deepseek-ai/[email protected]
- - name: Official plugins composition (current core)
+ - name: Official plugins and mobile settings composition (current core)
env:
DSH_E2E_DSH_BIN: ${{ runner.temp }}/dsh-cli-current/node_modules/@deepseek-ai/dsh/lib/bin.js
run: |
for seed in 101 102 103 104 105; do
- node node_modules/vitest/vitest.mjs run --project plugin --sequence.shuffle --sequence.seed="$seed" test/e2e/plugins/dsh-tauri-extension-panel.e2e.ts || exit $?
+ node node_modules/vitest/vitest.mjs run --project plugin --sequence.shuffle --sequence.seed="$seed" test/e2e/plugins/dsh-tauri-extension-panel.e2e.ts test/e2e/plugins/dsh-tauri-mobile-settings.e2e.ts || exit $?
done
# 桌面端 L3 E2E(vitest + WebdriverIO):
diff --git a/packages/dsh-tauri-mobile-ui/src/client/components/mobile-settings-controls.tsx b/packages/dsh-tauri-mobile-ui/src/client/components/mobile-settings-controls.tsx
new file mode 100644
index 00000000..cb5ca41d
--- /dev/null
+++ b/packages/dsh-tauri-mobile-ui/src/client/components/mobile-settings-controls.tsx
@@ -0,0 +1,22 @@
+import type { MobileSettingsPresentation } from '../types/settings'
+import { ArrowLeft, Button, Icon } from 'dsh-tauri-ui/client'
+import { useSyncExternalStore } from 'react'
+import { locale } from '../locales'
+
+export function MobileSettingsControls({ presentation }: { presentation: MobileSettingsPresentation }) {
+ locale.useLocale()
+ const snapshot = useSyncExternalStore(presentation.subscribe, presentation.getSnapshot, presentation.getSnapshot)
+ return (
+ <div data-dsh-mobile-settings-controls hidden>
+ <Button
+ data-dsh-mobile-settings-back
+ aria-label={locale.text('settings.back')}
+ icon={<Icon as={ArrowLeft} size={20} aria-hidden="true" />}
+ onClick={presentation.back}
+ />
+ <span data-dsh-mobile-settings-section-title role="heading" aria-level={2} title={snapshot.title}>
+ {snapshot.title}
+ </span>
+ </div>
+ )
+}
diff --git a/packages/dsh-tauri-mobile-ui/src/client/constants/index.ts b/packages/dsh-tauri-mobile-ui/src/client/constants/index.ts
new file mode 100644
index 00000000..211a4713
--- /dev/null
+++ b/packages/dsh-tauri-mobile-ui/src/client/constants/index.ts
@@ -0,0 +1,3 @@
+import { MOBILE_MEDIA_QUERIES } from 'dsh-tauri/client'
+
+export const MOBILE_SETTINGS_MEDIA = `${MOBILE_MEDIA_QUERIES.join(' and ')} and (max-width: 767px)`
diff --git a/packages/dsh-tauri-mobile-ui/src/client/index.test.ts b/packages/dsh-tauri-mobile-ui/src/client/index.test.ts
index 75738f59..5d188d61 100644
--- a/packages/dsh-tauri-mobile-ui/src/client/index.test.ts
+++ b/packages/dsh-tauri-mobile-ui/src/client/index.test.ts
@@ -4,6 +4,7 @@ import { apply, inject, name } from './index'
import { locale } from './locales'
import { installBridgeConfig, registerBridgeConfig } from './register/bridge'
import { registerMobilePreferences } from './register/preferences'
+import { registerMobileSettings } from './register/settings'
import { registerMobileSidebar } from './register/sidebar'
import { registerStyles } from './register/styles'
@@ -18,6 +19,7 @@ vi.mock('./register/bridge', () => ({
}))
vi.mock('./register/preferences', () => ({ registerMobilePreferences: vi.fn() }))
vi.mock('./register/sidebar', () => ({ registerMobileSidebar: vi.fn() }))
+vi.mock('./register/settings', () => ({ registerMobileSettings: vi.fn() }))
vi.mock('./register/styles', () => ({ registerStyles: vi.fn() }))
afterEach(() => {
@@ -38,5 +40,6 @@ it('assembles mobile-only effects and yields bridge page tweaks early', () => {
[registerStyles, 'dsh-tauri-mobile-ui: styles'],
[registerMobilePreferences, 'dsh-tauri-mobile-ui: preferences'],
[registerMobileSidebar, 'dsh-tauri-mobile-ui: sidebar'],
+ [registerMobileSettings, 'dsh-tauri-mobile-ui: settings'],
])
})
diff --git a/packages/dsh-tauri-mobile-ui/src/client/index.ts b/packages/dsh-tauri-mobile-ui/src/client/index.ts
index 87b8e547..fb28d71b 100644
--- a/packages/dsh-tauri-mobile-ui/src/client/index.ts
+++ b/packages/dsh-tauri-mobile-ui/src/client/index.ts
@@ -4,6 +4,7 @@ import { PLUGIN_ID } from '../shared/constants'
import { locale } from './locales'
import { installBridgeConfig, registerBridgeConfig } from './register/bridge'
import { registerMobilePreferences } from './register/preferences'
+import { registerMobileSettings } from './register/settings'
import { registerMobileSidebar } from './register/sidebar'
import { registerStyles } from './register/styles'
@@ -17,4 +18,5 @@ export function apply(ctx: ClientContext): void {
ctx.effect(registerStyles, `${PLUGIN_ID}: styles`)
ctx.effect(registerMobilePreferences, `${PLUGIN_ID}: preferences`)
ctx.effect(registerMobileSidebar, `${PLUGIN_ID}: sidebar`)
+ ctx.effect(registerMobileSettings, `${PLUGIN_ID}: settings`)
}
diff --git a/packages/dsh-tauri-mobile-ui/src/client/locales/index.ts b/packages/dsh-tauri-mobile-ui/src/client/locales/index.ts
index 0a024432..294a5699 100644
--- a/packages/dsh-tauri-mobile-ui/src/client/locales/index.ts
+++ b/packages/dsh-tauri-mobile-ui/src/client/locales/index.ts
@@ -8,6 +8,7 @@ const zh = {
'navbar.label': '会话导航',
'session.new': '新会话',
'session.failed': '无法新建会话,请重试',
+ 'settings.back': '返回设置分类',
} as const
const en: Record<keyof typeof zh, string> = {
@@ -17,6 +18,7 @@ const en: Record<keyof typeof zh, string> = {
'navbar.label': 'Conversation navigation',
'session.new': 'New Session',
'session.failed': 'Unable to start a session. Please try again.',
+ 'settings.back': 'Back to settings categories',
}
declare module '@deepseek-ai/dsh-client-ui-slots' {
diff --git a/packages/dsh-tauri-mobile-ui/src/client/register/settings.test.tsx b/packages/dsh-tauri-mobile-ui/src/client/register/settings.test.tsx
new file mode 100644
index 00000000..dbb6208a
--- /dev/null
+++ b/packages/dsh-tauri-mobile-ui/src/client/register/settings.test.tsx
@@ -0,0 +1,486 @@
+// @vitest-environment jsdom
+import type { ButtonHTMLAttributes, ComponentType, ReactNode } from 'react'
+import type { MobileSettingsPresentation } from '../types/settings'
+import { act, cleanup, fireEvent, render } from '@testing-library/react'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { registerMobileSettings } from './settings'
+
+vi.mock('dsh-tauri/client', async () => ({
+ ...await import('../../../../dsh-tauri/src/client/register'),
+ ...await import('../../../../dsh-tauri/src/client/locale'),
+ ...await import('../../../../dsh-tauri/src/client/utils/device'),
+}))
+
+vi.mock('dsh-tauri-ui/client', async () => ({
+ ...await import('../../../../dsh-tauri-ui/src/client/components/icon'),
+ ...await import('../../../../dsh-tauri-ui/src/client/components/icons'),
+ Button: ({ icon, children, ...props }: ButtonHTMLAttributes<HTMLButtonElement> & { icon?: ReactNode }) => (
+ <button type="button" {...props}>
+ {icon}
+ {children}
+ </button>
+ ),
+}))
+
+interface DialogFixture {
+ overlay: HTMLElement
+ panel: HTMLElement
+ title: HTMLElement
+ list: HTMLElement
+ options: HTMLElement
+ actionSlot: HTMLElement
+ close: HTMLButtonElement
+ current: HTMLButtonElement | null
+}
+
+interface ActionRegistration {
+ name: string
+ id: string
+ order: number
+ locale: string
+ registrant: string
+ inject: () => { presentation: MobileSettingsPresentation }
+}
+
+let matches = true
+let media: MediaQueryList
+let mediaListeners: Set<() => void>
+const disposers: Array<() => void> = []
+let sequence = 0
+
+function fixture(labels = ['General', 'Models'], selected = 0): DialogFixture {
+ const overlay = document.createElement('div')
+ const titleId = `settings:r${++sequence}:`
+ // Official SettingsRoot.tsx:67-104: slots and dialog semantics, not CSS-module hashes.
+ overlay.innerHTML = `<div aria-hidden="true"></div><div role="dialog" aria-modal="true" aria-labelledby="${titleId}" tabindex="-1"><nav><div id="${titleId}" tabindex="-1"><div data-slot="settings.header">Settings</div></div><div>${labels.map((label, index) => `<button type="button"${index === selected ? ' aria-current="true"' : ''}><span>${label}</span></button>`).join('')}</div></nav><div><div><div><div data-slot="settings.action"></div></div><button type="button"><span><div data-slot="settings.close">Close settings</div></span></button></div><div>${labels.length === 0 ? '' : '<div data-slot="settings.section"><input aria-label="Setting draft" value="initial"><button type="button">Save</button></div>'}</div></div></div>`
+ document.body.append(overlay)
+ const panel = overlay.querySelector<HTMLElement>('[role="dialog"]')!
+ const title = document.getElementById(titleId)!
+ const list = title.nextElementSibling as HTMLElement
+ return {
+ overlay,
+ panel,
+ title,
+ list,
+ options: panel.querySelector<HTMLElement>('[data-slot="settings.section"]')?.parentElement
+ ?? panel.lastElementChild!.lastElementChild as HTMLElement,
+ actionSlot: panel.querySelector<HTMLElement>('[data-slot="settings.action"]')!,
+ close: panel.querySelector<HTMLButtonElement>('[data-slot="settings.close"]')!.closest('button')!,
+ current: list.querySelector<HTMLButtonElement>('[aria-current="true"]'),
+ }
+}
+
+function register(initial?: DialogFixture) {
+ let registration: ActionRegistration | undefined
+ let Component: ComponentType<{ presentation: MobileSettingsPresentation }> | undefined
+ const roots: Array<ReturnType<typeof render>> = []
+ const inject = vi.fn((_name: string, activate: () => () => void) => activate())
+ const slotsRegister = vi.fn((options: ActionRegistration, component: typeof Component) => {
+ registration = options
+ Component = component
+ return () => roots.forEach(root => root.unmount())
+ })
+ const ctx = { slots: { inject, register: slotsRegister } }
+ const dispose = registerMobileSettings.call({ ctx })
+ disposers.push(dispose)
+ const mount = (dialog: DialogFixture): void => {
+ if (!Component || !registration)
+ throw new Error('Mobile settings action was not registered')
+ roots.push(render(<Component {...registration.inject()} />, { container: dialog.actionSlot }))
+ }
+ if (initial)
+ mount(initial)
+ return {
+ dispose,
+ mount,
+ inject,
+ slotsRegister,
+ presentation: (): MobileSettingsPresentation => {
+ if (!registration)
+ throw new Error('Mobile settings presentation is unavailable')
+ return registration.inject().presentation
+ },
+ }
+}
+
+async function flush(): Promise<void> {
+ await act(async () => {
+ await Promise.resolve()
+ await vi.runOnlyPendingTimersAsync()
+ })
+}
+
+function launcher(legacy = false): HTMLButtonElement {
+ const slot = document.createElement('div')
+ if (!legacy)
+ slot.setAttribute('data-slot', 'settings.launcher')
+ slot.innerHTML = `<button type="button" aria-haspopup="dialog">${legacy ? '<span data-slot="settings.trigger">Open settings</span>' : 'Open settings'}</button>`
+ document.body.append(slot)
+ return slot.firstElementChild as HTMLButtonElement
+}
+
+async function openFromLauncher(legacy = false) {
+ const handle = register()
+ let dialog: DialogFixture | undefined
+ act(() => {
+ fireEvent.click(launcher(legacy))
+ dialog = fixture()
+ handle.mount(dialog)
+ })
+ await flush()
+ if (!dialog)
+ throw new Error('Settings dialog was not opened')
+ return { handle, dialog }
+}
+
+function back(dialog: DialogFixture): HTMLButtonElement {
+ return dialog.panel.querySelector<HTMLButtonElement>('[data-dsh-mobile-settings-back]')!
+}
+
+function setCurrent(dialog: DialogFixture, index: number): HTMLButtonElement {
+ const buttons = [...dialog.list.querySelectorAll<HTMLButtonElement>('button')]
+ buttons.forEach((button, current) => {
+ if (current === index)
+ button.setAttribute('aria-current', 'true')
+ else
+ button.removeAttribute('aria-current')
+ })
+ dialog.current = buttons[index]
+ return buttons[index]
+}
+
+beforeEach(() => {
+ vi.useFakeTimers()
+ document.body.innerHTML = ''
+ matches = true
+ mediaListeners = new Set()
+ media = {
+ get matches() { return matches },
+ media: '(hover: none) and (any-pointer: coarse) and (any-hover: none) and (max-width: 767px)',
+ onchange: null,
+ addEventListener: vi.fn((_name, listener) => mediaListeners.add(listener as () => void)),
+ removeEventListener: vi.fn((_name, listener) => mediaListeners.delete(listener as () => void)),
+ addListener: vi.fn(),
+ removeListener: vi.fn(),
+ dispatchEvent: vi.fn(() => true),
+ } as MediaQueryList
+ vi.stubGlobal('matchMedia', vi.fn(() => media))
+})
+
+afterEach(async () => {
+ act(() => disposers.splice(0).forEach(dispose => dispose()))
+ cleanup()
+ document.body.innerHTML = ''
+ await Promise.resolve()
+ vi.clearAllTimers()
+ vi.useRealTimers()
+ vi.unstubAllGlobals()
+ vi.restoreAllMocks()
+})
+
+describe('mobile settings presentation', () => {
+ it('registers only an additive official action with managed teardown', async () => {
+ const dialog = fixture()
+ const handle = register(dialog)
+ await flush()
+ expect(handle.inject).toHaveBeenCalledWith('settings.action', expect.any(Function))
+ expect(handle.slotsRegister).toHaveBeenCalledTimes(1)
+ expect(handle.slotsRegister.mock.calls[0][0]).toMatchObject({
+ name: 'settings.action',
+ id: 'dsh-tauri-mobile-ui: back',
+ order: -100,
+ locale: 'dsh-tauri-mobile-ui',
+ registrant: 'dsh-tauri-mobile-ui',
+ })
+ expect(dialog.title.textContent).toBe('Settings')
+ expect(dialog.panel.getAttribute('aria-labelledby')).toBe(dialog.title.id)
+ expect(back(dialog).getAttribute('aria-label')).toBe('Back to settings categories')
+ expect(mediaListeners.size).toBe(1)
+ act(handle.dispose)
+ expect(mediaListeners.size).toBe(0)
+ expect(dialog.actionSlot.childElementCount).toBe(0)
+ })
+
+ it.each([false, true])('opens categories only for its observed launcher intent (legacy=%s)', async (legacy) => {
+ const { dialog, handle } = await openFromLauncher(legacy)
+ expect(dialog.panel.getAttribute('data-dsh-mobile-settings-view')).toBe('menu')
+ expect(dialog.list.hidden).toBe(false)
+ expect(dialog.list.hasAttribute('inert')).toBe(false)
+ expect(dialog.options.hidden).toBe(true)
+ expect(dialog.options.hasAttribute('inert')).toBe(true)
+ expect(dialog.panel.querySelector<HTMLElement>('[data-dsh-mobile-settings-controls]')!.hidden).toBe(true)
+ expect(handle.presentation().getSnapshot()).toEqual({ ready: true, view: 'menu', title: 'General' })
+ })
+
+ it.each([0, 1])('preserves unknown-entry deep links in details, including first row (%s)', async (selected) => {
+ const dialog = fixture(['General', 'Models'], selected)
+ const handle = register(dialog)
+ await flush()
+ expect(handle.presentation().getSnapshot()).toEqual({ ready: true, view: 'detail', title: selected === 0 ? 'General' : 'Models' })
+ expect(dialog.list.hidden).toBe(true)
+ expect(dialog.list.hasAttribute('inert')).toBe(true)
+ expect(dialog.options.hidden).toBe(false)
+ expect(dialog.options.hasAttribute('inert')).toBe(false)
+ expect(document.activeElement).toBe(back(dialog))
+ })
+
+ it('lets native category clicks select before showing details', async () => {
+ const { dialog } = await openFromLauncher()
+ const nativeSelect = vi.fn(() => setCurrent(dialog, 1))
+ const button = dialog.list.children[1] as HTMLButtonElement
+ button.addEventListener('click', nativeSelect)
+ const click = new MouseEvent('click', { bubbles: true, cancelable: true })
+ act(() => fireEvent(button, click))
+ await flush()
+ expect(nativeSelect).toHaveBeenCalledTimes(1)
+ expect(click.defaultPrevented).toBe(false)
+ expect(dialog.current).toBe(button)
+ expect(dialog.panel.getAttribute('data-dsh-mobile-settings-view')).toBe('detail')
+ expect(dialog.panel.querySelector('[data-dsh-mobile-settings-section-title]')!.textContent).toBe('Models')
+ expect(document.activeElement).toBe(back(dialog))
+ })
+
+ it('shows details for a native re-selection without requiring a DOM mutation', async () => {
+ const { dialog } = await openFromLauncher()
+ act(() => fireEvent.click(dialog.current!))
+ await flush()
+ expect(dialog.panel.getAttribute('data-dsh-mobile-settings-view')).toBe('detail')
+ expect(document.activeElement).toBe(back(dialog))
+ })
+
+ it('returns to categories without remounting the official draft', async () => {
+ const dialog = fixture()
+ register(dialog)
+ await flush()
+ const input = dialog.options.querySelector<HTMLInputElement>('input')!
+ input.value = 'unsaved local draft'
+ act(() => fireEvent.click(back(dialog)))
+ await flush()
+ expect(dialog.panel.getAttribute('data-dsh-mobile-settings-view')).toBe('menu')
+ expect(dialog.options.querySelector('input')).toBe(input)
+ expect(input.value).toBe('unsaved local draft')
+ expect(document.activeElement).toBe(dialog.current)
+ act(() => fireEvent.click(dialog.current!))
+ await flush()
+ expect(dialog.options.querySelector('input')).toBe(input)
+ expect(input.value).toBe('unsaved local draft')
+ })
+
+ it('updates the current label without inventing a settings section state', async () => {
+ const dialog = fixture()
+ const handle = register(dialog)
+ await flush()
+ act(() => {
+ dialog.current!.querySelector('span')!.textContent = '常规设置'
+ })
+ await flush()
+ expect(handle.presentation().getSnapshot()).toEqual({ ready: true, view: 'detail', title: '常规设置' })
+ expect(dialog.panel.querySelector('[data-dsh-mobile-settings-section-title]')!.textContent).toBe('常规设置')
+ expect(dialog.current!.getAttribute('aria-current')).toBe('true')
+ })
+
+ it('follows externally changed native selection while on categories', async () => {
+ const { dialog, handle } = await openFromLauncher()
+ act(() => {
+ setCurrent(dialog, 1)
+ })
+ await flush()
+ expect(handle.presentation().getSnapshot()).toEqual({ ready: true, view: 'detail', title: 'Models' })
+ expect(dialog.options.hidden).toBe(false)
+ expect(dialog.list.hidden).toBe(true)
+ })
+
+ it('keeps an empty official ledger in categories with its accessible title', async () => {
+ const dialog = fixture([])
+ const handle = register(dialog)
+ await flush()
+ expect(handle.presentation().getSnapshot()).toEqual({ ready: true, view: 'menu', title: '' })
+ expect(dialog.panel.getAttribute('aria-labelledby')).toBe(dialog.title.id)
+ expect(document.activeElement).toBe(dialog.title)
+ expect(dialog.options.hidden).toBe(true)
+ expect(dialog.close.hidden).toBe(false)
+ })
+
+ it('restores native attributes and focus when leaving the phone media query', async () => {
+ const dialog = fixture()
+ dialog.list.setAttribute('hidden', 'original')
+ const handle = register(dialog)
+ await flush()
+ act(() => {
+ matches = false
+ mediaListeners.forEach(listener => listener())
+ })
+ await flush()
+ expect(dialog.panel.hasAttribute('data-dsh-mobile-settings')).toBe(false)
+ expect(dialog.list.getAttribute('hidden')).toBe('original')
+ expect(dialog.list.hasAttribute('inert')).toBe(false)
+ expect(dialog.options.hidden).toBe(false)
+ expect(handle.presentation().getSnapshot()).toEqual({ ready: false, view: 'detail', title: '' })
+ expect(document.activeElement).toBe(dialog.close)
+ act(() => {
+ matches = true
+ fireEvent(window, new Event('resize'))
+ })
+ await flush()
+ expect(dialog.panel.getAttribute('data-dsh-mobile-settings-view')).toBe('detail')
+ })
+
+ it('never arms desktop or non-touch settings', async () => {
+ matches = false
+ const dialog = fixture()
+ register(dialog)
+ await flush()
+ expect(window.matchMedia).toHaveBeenCalledWith('(hover: none) and (any-pointer: coarse) and (any-hover: none) and (max-width: 767px)')
+ expect(dialog.panel.hasAttribute('data-dsh-mobile-settings')).toBe(false)
+ expect(dialog.list.hidden).toBe(false)
+ expect(dialog.options.hidden).toBe(false)
+ expect(dialog.panel.querySelector<HTMLElement>('[data-dsh-mobile-settings-controls]')!.hidden).toBe(true)
+ })
+
+ it('yields atomically to an active bridge mobile stylesheet and resumes when removed', async () => {
+ const dialog = fixture()
+ register(dialog)
+ await flush()
+ const bridge = document.createElement('style')
+ bridge.id = 'dsh-bridge-mobile-styles'
+ act(() => {
+ document.head.append(bridge)
+ })
+ await flush()
+ expect(dialog.panel.hasAttribute('data-dsh-mobile-settings')).toBe(false)
+ expect(dialog.list.hidden).toBe(false)
+ expect(dialog.options.hidden).toBe(false)
+ expect(document.activeElement).toBe(dialog.current)
+ act(() => {
+ bridge.remove()
+ })
+ await flush()
+ expect(dialog.panel.getAttribute('data-dsh-mobile-settings-view')).toBe('detail')
+ })
+
+ it.each(['hidden', 'inert'])('abandons a panel when a later owner takes its %s attribute', async (attribute) => {
+ const dialog = fixture()
+ const handle = register(dialog)
+ await flush()
+ const controls = dialog.panel.querySelector<HTMLElement>('[data-dsh-mobile-settings-controls]')!
+ act(() => {
+ dialog.list.setAttribute(attribute, 'later-owner')
+ handle.presentation().back()
+ })
+ await flush()
+ expect(dialog.list.getAttribute(attribute)).toBe('later-owner')
+ expect(dialog.options.hidden).toBe(false)
+ expect(dialog.options.hasAttribute('inert')).toBe(false)
+ expect(controls.hidden).toBe(true)
+ expect(dialog.panel.hasAttribute('data-dsh-mobile-settings')).toBe(false)
+ expect(handle.presentation().getSnapshot().ready).toBe(false)
+ expect(document.activeElement).toBe(dialog.close)
+ act(() => fireEvent(window, new Event('resize')))
+ await flush()
+ expect(dialog.list.getAttribute(attribute)).toBe('later-owner')
+ expect(dialog.panel.hasAttribute('data-dsh-mobile-settings')).toBe(false)
+ act(() => dialog.overlay.remove())
+ const replacement = fixture()
+ act(() => handle.mount(replacement))
+ await flush()
+ expect(replacement.panel.getAttribute('data-dsh-mobile-settings-view')).toBe('detail')
+ })
+
+ it('fails closed for two proven settings dialogs and restores the previous panel', async () => {
+ const first = fixture()
+ const handle = register(first)
+ await flush()
+ const second = fixture()
+ act(() => handle.mount(second))
+ await flush()
+ expect(first.panel.hasAttribute('data-dsh-mobile-settings')).toBe(false)
+ expect(second.panel.hasAttribute('data-dsh-mobile-settings')).toBe(false)
+ expect(first.list.hidden).toBe(false)
+ expect(first.options.hidden).toBe(false)
+ expect(handle.presentation().getSnapshot().ready).toBe(false)
+ })
+
+ it('restores the entire patch when official structure becomes ambiguous', async () => {
+ const dialog = fixture()
+ register(dialog)
+ await flush()
+ const duplicate = document.createElement('div')
+ duplicate.setAttribute('data-slot', 'settings.action')
+ act(() => dialog.panel.append(duplicate))
+ await flush()
+ expect(dialog.panel.hasAttribute('data-dsh-mobile-settings')).toBe(false)
+ expect(dialog.list.hidden).toBe(false)
+ expect(dialog.options.hidden).toBe(false)
+ expect(dialog.list.hasAttribute('data-dsh-mobile-settings-list')).toBe(false)
+ })
+
+ it('does not steal focus or Back from a foreground nested dialog', async () => {
+ const dialog = fixture()
+ const handle = register(dialog)
+ await flush()
+ const nested = document.createElement('div')
+ nested.setAttribute('role', 'dialog')
+ nested.setAttribute('aria-modal', 'true')
+ nested.innerHTML = '<input aria-label="Nested input">'
+ act(() => {
+ dialog.options.append(nested)
+ nested.querySelector<HTMLInputElement>('input')!.focus()
+ handle.presentation().back()
+ })
+ await flush()
+ expect(document.activeElement).toBe(nested.firstElementChild)
+ expect(handle.presentation().getSnapshot().view).toBe('detail')
+ })
+
+ it('ignores hidden nested menus when deciding whether Back is foreground', async () => {
+ const dialog = fixture()
+ const handle = register(dialog)
+ await flush()
+ const menu = document.createElement('div')
+ menu.setAttribute('role', 'menu')
+ menu.hidden = true
+ act(() => {
+ dialog.options.append(menu)
+ handle.presentation().back()
+ })
+ await flush()
+ expect(handle.presentation().getSnapshot().view).toBe('menu')
+ expect(document.activeElement).toBe(dialog.current)
+ })
+
+ it('restores native focus before unregistering a focused additive Back control', async () => {
+ const dialog = fixture()
+ const handle = register(dialog)
+ await flush()
+ expect(document.activeElement).toBe(back(dialog))
+ act(handle.dispose)
+ await flush()
+ expect(document.activeElement).toBe(dialog.current)
+ expect(dialog.list.hidden).toBe(false)
+ expect(dialog.options.hidden).toBe(false)
+ expect(dialog.panel.hasAttribute('data-dsh-mobile-settings')).toBe(false)
+ })
+
+ it('does not turn an expired launcher click into a later external menu entry', async () => {
+ const handle = register()
+ act(() => fireEvent.click(launcher()))
+ await flush()
+ const dialog = fixture()
+ act(() => handle.mount(dialog))
+ await flush()
+ expect(handle.presentation().getSnapshot().view).toBe('detail')
+ })
+
+ it('cancels a queued category transition on disposal without recreating ownership', async () => {
+ const { dialog, handle } = await openFromLauncher()
+ act(() => {
+ fireEvent.click(dialog.current!)
+ handle.dispose()
+ })
+ await flush()
+ expect(dialog.panel.hasAttribute('data-dsh-mobile-settings')).toBe(false)
+ expect(dialog.list.hidden).toBe(false)
+ expect(dialog.options.hidden).toBe(false)
+ expect(vi.getTimerCount()).toBe(0)
+ })
+})
diff --git a/packages/dsh-tauri-mobile-ui/src/client/register/settings.ts b/packages/dsh-tauri-mobile-ui/src/client/register/settings.ts
new file mode 100644
index 00000000..da55d77a
--- /dev/null
+++ b/packages/dsh-tauri-mobile-ui/src/client/register/settings.ts
@@ -0,0 +1,171 @@
+import type {} from '@deepseek-ai/dsh-client-ui-settings/client'
+import type { ClientContext } from 'dsh-tauri/client'
+import type { MobileSettingsPresentation, MobileSettingsSnapshot, MobileSettingsView } from '../types/settings'
+import type { MobileSettingsNodes } from './settings.utils'
+import { defineRegister } from 'dsh-tauri/client'
+import { PLUGIN_ID } from '../../shared/constants'
+import { MobileSettingsControls } from '../components/mobile-settings-controls'
+import { MOBILE_SETTINGS_MEDIA } from '../constants'
+import { locale } from '../locales'
+import { resolveSettingsPresentation } from '../service/settings'
+import { applySettingsPresentation, createSettingsAttributePatch, findMobileSettingsPanel, isForegroundSettingsPanel } from './settings.utils'
+
+const INACTIVE_SETTINGS: MobileSettingsSnapshot = { ready: false, view: 'detail', title: '' }
+
+export const registerMobileSettings = defineRegister<ClientContext>((controller, ctx) => {
+ if (typeof document === 'undefined' || typeof window === 'undefined' || typeof window.matchMedia !== 'function')
+ return
+ const media = window.matchMedia(MOBILE_SETTINGS_MEDIA)
+ const patch = createSettingsAttributePatch()
+ const abandonedPanels = new WeakSet<HTMLElement>()
+ const listeners = new Set<() => void>()
+ let snapshot = INACTIVE_SETTINGS
+ let nodes: MobileSettingsNodes | null = null
+ let view: MobileSettingsView = 'detail'
+ let pendingMenu = false
+ let pendingNavigation = false
+ let cancelSync: (() => void) | undefined
+ let cancelMenu: (() => void) | undefined
+ const publish = (next: MobileSettingsSnapshot): void => {
+ if (snapshot === next)
+ return
+ snapshot = next
+ listeners.forEach(listener => listener())
+ }
+ const restore = (): void => {
+ const previous = nodes
+ const focusedOwnControls = previous?.controls.contains(document.activeElement)
+ patch.restore()
+ nodes = null
+ publish(INACTIVE_SETTINGS)
+ if (previous && focusedOwnControls && isForegroundSettingsPanel(previous.panel)) {
+ const target = previous.current && !previous.current.disabled && previous.current.closest('[hidden], [inert]') === null
+ ? previous.current
+ : previous.close
+ target.focus({ preventScroll: true })
+ }
+ }
+ const sync = (): void => {
+ if (controller.isDisposed())
+ return
+ const next = media.matches && document.getElementById('dsh-bridge-mobile-styles') === null
+ ? findMobileSettingsPanel()
+ : null
+ if (!patch.isIntact() && nodes !== null) {
+ abandonedPanels.add(nodes.panel)
+ console.warn('[dsh-tauri-mobile-ui] Mobile settings attributes changed ownership; preserving native settings.')
+ restore()
+ pendingNavigation = false
+ return
+ }
+ if (next === null || abandonedPanels.has(next.panel)) {
+ restore()
+ pendingNavigation = false
+ return
+ }
+ const entering = nodes?.panel !== next.panel
+ const changing = nodes?.list !== next.list || nodes?.options !== next.options || nodes?.controls !== next.controls
+ const selectionChanged = nodes !== null && nodes.current !== next.current
+ const resolved = resolveSettingsPresentation(snapshot, view, {
+ entering,
+ changing,
+ launcher: pendingMenu,
+ navigation: pendingNavigation,
+ selectionChanged,
+ title: next.current?.textContent?.trim() ?? null,
+ focused: { list: next.list.contains(document.activeElement), options: next.options.contains(document.activeElement), controls: next.controls.contains(document.activeElement) },
+ })
+ if (entering || changing)
+ patch.restore()
+ if (entering) {
+ pendingMenu = false
+ cancelMenu?.()
+ cancelMenu = undefined
+ }
+ view = resolved.snapshot.view
+ nodes = next
+ applySettingsPresentation(next, view, patch)
+ publish(resolved.snapshot)
+ if (resolved.focus !== null && isForegroundSettingsPanel(next.panel))
+ (resolved.focus === 'back' ? next.back : next.current ?? next.title).focus({ preventScroll: true })
+ pendingNavigation = false
+ }
+ const schedule = (): void => {
+ cancelSync?.()
+ cancelSync = controller.timeout(() => {
+ cancelSync = undefined
+ sync()
+ }, 0)
+ }
+ const presentation: MobileSettingsPresentation = {
+ getSnapshot: () => snapshot,
+ subscribe: (listener) => {
+ listeners.add(listener)
+ return () => listeners.delete(listener)
+ },
+ back: () => {
+ if (nodes === null || !isForegroundSettingsPanel(nodes.panel))
+ return
+ view = 'menu'
+ pendingNavigation = false
+ sync()
+ },
+ }
+ controller.listen('click', (event) => {
+ if (event.defaultPrevented || !media.matches || !(event.target instanceof Element) || nodes !== null)
+ return
+ const button = event.target.closest<HTMLButtonElement>('button[aria-haspopup="dialog"]')
+ if (!button || button.disabled || (button.closest('[data-slot="settings.launcher"]') === null && button.querySelector('[data-slot="settings.trigger"]') === null))
+ return
+ pendingMenu = true
+ cancelMenu?.()
+ cancelMenu = controller.timeout(() => {
+ pendingMenu = false
+ }, 0)
+ }, { capture: true })
+ controller.listen('click', (event) => {
+ if (event.defaultPrevented || !(event.target instanceof Element) || nodes === null)
+ return
+ const button = event.target.closest('button')
+ if (button?.parentElement !== nodes.list || button.disabled)
+ return
+ pendingNavigation = true
+ schedule()
+ })
+ controller.listenWindow('resize', sync)
+ // keep:effect MediaQueryList changes have no controller event target; controller owns their cleanup.
+ if (typeof media.addEventListener === 'function') {
+ media.addEventListener('change', sync)
+ controller.add(() => media.removeEventListener('change', sync))
+ }
+ else if (typeof media.addListener === 'function') {
+ media.addListener(sync)
+ controller.add(() => media.removeListener(sync))
+ }
+ else {
+ console.warn('[dsh-tauri-mobile-ui] Mobile settings media subscription unavailable; preserving native settings.')
+ return
+ }
+ controller.observe(document.documentElement, sync, {
+ childList: true,
+ subtree: true,
+ characterData: true,
+ attributes: true,
+ attributeFilter: ['aria-current', 'aria-labelledby', 'role', 'aria-modal', 'data-slot', 'disabled', 'id', 'hidden', 'inert', 'data-dsh-mobile-settings', 'data-dsh-mobile-settings-view', ...['overlay', 'nav', 'title', 'list', 'content', 'header', 'actions', 'close', 'options'].map(name => `data-dsh-mobile-settings-${name}`)],
+ })
+ controller.add(() => {
+ cancelSync?.()
+ cancelMenu?.()
+ restore()
+ listeners.clear()
+ })
+ controller.add(ctx.slots.inject('settings.action', () => ctx.slots.register({
+ name: 'settings.action',
+ id: `${PLUGIN_ID}: back`,
+ order: -100,
+ locale: locale.NS,
+ registrant: PLUGIN_ID,
+ inject: () => ({ presentation }),
+ }, MobileSettingsControls)))
+ sync()
+})
diff --git a/packages/dsh-tauri-mobile-ui/src/client/register/settings.utils.test.ts b/packages/dsh-tauri-mobile-ui/src/client/register/settings.utils.test.ts
new file mode 100644
index 00000000..181890ce
--- /dev/null
+++ b/packages/dsh-tauri-mobile-ui/src/client/register/settings.utils.test.ts
@@ -0,0 +1,594 @@
+// @vitest-environment jsdom
+import type { MobileSettingsNodes } from './settings.utils'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { createSettingsAttributePatch, findMobileSettingsPanel, resolveMobileSettingsPanel } from './settings.utils'
+
+interface SettingsFixture {
+ nodes: MobileSettingsNodes
+ slots: Record<'header' | 'action' | 'close' | 'section', HTMLDivElement>
+ buttons: HTMLButtonElement[]
+}
+
+function element<K extends keyof HTMLElementTagNameMap>(tag: K, ...children: (Node | string)[]): HTMLElementTagNameMap[K] {
+ const node = document.createElement(tag)
+ node.append(...children)
+ return node
+}
+
+function slot(name: string, ...children: (Node | string)[]): HTMLDivElement {
+ const node = element('div', ...children)
+ node.setAttribute('data-slot', name)
+ node.style.display = 'contents'
+ return node
+}
+
+function button(label: string): HTMLButtonElement {
+ const icon = document.createElementNS('http://www.w3.org/2000/svg', 'svg')
+ icon.setAttribute('aria-hidden', 'true')
+ const node = element('button', icon, element('span', label))
+ node.type = 'button'
+ return node
+}
+
+// Fixtures mirror official settings-general/lib/client.js 0.2.1-alpha.1:275-341 / 0.1.5-rc.3:99-172 and renderer SlotOutlet's display:contents div anchors.
+function mountSettings({ version = 'current', titleId = ':r0:', empty = false }: {
+ version?: 'current' | 'legacy'
+ titleId?: string
+ empty?: boolean
+} = {}): SettingsFixture {
+ const headerSlot = slot('settings.header', 'Settings')
+ const title = element('div', headerSlot)
+ title.id = titleId
+ const buttons = empty ? [] : [button('General'), button('Plugins')]
+ const current = buttons[0] ?? null
+ current?.setAttribute('aria-current', 'true')
+ const list = element('div', ...buttons)
+ const nav = element('nav', title, list)
+ const back = button('Back to settings')
+ back.setAttribute('data-dsh-mobile-settings-back', '')
+ back.setAttribute('aria-label', 'Back to settings')
+ const sectionTitle = element('span', 'General')
+ sectionTitle.setAttribute('data-dsh-mobile-settings-section-title', '')
+ sectionTitle.setAttribute('role', 'heading')
+ sectionTitle.setAttribute('aria-level', '2')
+ const controls = element('div', back, sectionTitle)
+ controls.setAttribute('data-dsh-mobile-settings-controls', '')
+ controls.hidden = true
+ const actionSlot = slot('settings.action', controls, button('Open document'))
+ const actions = element('div', actionSlot)
+ const closeSlot = slot('settings.close', 'Close')
+ const close = button('')
+ close.lastElementChild!.append(closeSlot)
+ const header = element('div', actions, close)
+ const input = element('input')
+ input.type = 'search'
+ const sectionSlot = slot('settings.section', element('div', input))
+ const options = element('div', ...empty ? [] : [sectionSlot])
+ const content = element('div', header, options)
+ const panel = element('div', nav, content)
+ panel.setAttribute('role', 'dialog')
+ panel.setAttribute('aria-modal', 'true')
+ panel.setAttribute('aria-labelledby', titleId)
+ const mask = element('div')
+ mask.setAttribute('aria-hidden', 'true')
+ const overlay = element('div', mask, panel)
+ overlay.setAttribute('role', 'presentation')
+ const root = slot('sidebar.settings')
+ document.body.append(root)
+ if (version === 'current') {
+ panel.tabIndex = -1
+ panel.setAttribute('data-shortcut-modal', 'settings')
+ title.tabIndex = -1
+ ;(current ?? title).setAttribute('data-modal-autofocus', '')
+ document.body.append(overlay)
+ }
+ else {
+ root.append(overlay)
+ }
+ return {
+ nodes: { panel, overlay, nav, title, list, content, header, actions, close, options, controls, back, current },
+ slots: { header: headerSlot, action: actionSlot, close: closeSlot, section: sectionSlot },
+ buttons,
+ }
+}
+
+function expectNodes(actual: MobileSettingsNodes | null, expected: MobileSettingsNodes): void {
+ expect(actual, 'The supported official fixture must resolve').not.toBeNull()
+ if (actual === null)
+ throw new Error('The supported official fixture did not resolve')
+ for (const key of Object.keys(expected) as (keyof MobileSettingsNodes)[])
+ expect(actual[key], `Resolved ${key} must be the original node`).toBe(expected[key])
+}
+
+beforeEach(() => document.body.replaceChildren())
+
+afterEach(() => {
+ document.body.replaceChildren()
+ vi.restoreAllMocks()
+})
+
+describe('resolveMobileSettingsPanel', () => {
+ it.each(['current', 'legacy'] as const)('resolves the %s official shell with display:contents slot wrappers', (version) => {
+ const fixture = mountSettings({ version })
+ expectNodes(resolveMobileSettingsPanel(fixture.nodes.panel), fixture.nodes)
+ })
+
+ it.each(['current', 'legacy'] as const)('resolves %s empty sections without inventing a current button', (version) => {
+ const fixture = mountSettings({ version, empty: true })
+ expectNodes(resolveMobileSettingsPanel(fixture.nodes.panel), fixture.nodes)
+ expect(fixture.nodes.current).toBeNull()
+ expect(fixture.nodes.options.children).toHaveLength(0)
+ })
+
+ it('resolves a colon-containing title id with surrounding aria-labelledby whitespace', () => {
+ const fixture = mountSettings({ titleId: ':r12:' })
+ fixture.nodes.panel.setAttribute('aria-labelledby', ' :r12: ')
+ expectNodes(resolveMobileSettingsPanel(fixture.nodes.panel), fixture.nodes)
+ })
+
+ it('returns the selected second button rather than the first row', () => {
+ const fixture = mountSettings()
+ fixture.buttons[0].removeAttribute('aria-current')
+ fixture.buttons[1].setAttribute('aria-current', 'true')
+ expectNodes(resolveMobileSettingsPanel(fixture.nodes.panel), { ...fixture.nodes, current: fixture.buttons[1] })
+ })
+
+ it('preserves a disabled current row while Back and Close remain usable', () => {
+ const fixture = mountSettings()
+ fixture.buttons[0].disabled = true
+ expectNodes(resolveMobileSettingsPanel(fixture.nodes.panel), fixture.nodes)
+ })
+
+ it.each(['list', 'options'] as const)('still resolves the shell after the presentation hides its %s', (part) => {
+ const fixture = mountSettings()
+ fixture.nodes[part].hidden = true
+ fixture.nodes[part].setAttribute('inert', '')
+ expectNodes(resolveMobileSettingsPanel(fixture.nodes.panel), fixture.nodes)
+ })
+
+ it('ignores nested modal slots when the original settings anchors remain present', () => {
+ const fixture = mountSettings()
+ const foreign = element(
+ 'div',
+ slot('settings.header', 'Foreign header'),
+ slot('settings.action'),
+ slot('settings.close', 'Foreign close'),
+ slot('settings.section'),
+ )
+ foreign.setAttribute('role', 'dialog')
+ foreign.setAttribute('aria-modal', 'true')
+ fixture.slots.section.append(foreign)
+ expectNodes(resolveMobileSettingsPanel(fixture.nodes.panel), fixture.nodes)
+ })
+
+ it.each(['header', 'action', 'close', 'section'] as const)('rejects a missing settings.%s slot', (name) => {
+ const fixture = mountSettings()
+ fixture.slots[name].remove()
+ expect(resolveMobileSettingsPanel(fixture.nodes.panel)).toBeNull()
+ })
+
+ it.each(['header', 'action', 'close', 'section'] as const)('rejects a duplicated owned settings.%s slot', (name) => {
+ const fixture = mountSettings()
+ const original = fixture.slots[name]
+ original.parentElement!.append(original.cloneNode(true))
+ expect(resolveMobileSettingsPanel(fixture.nodes.panel)).toBeNull()
+ })
+
+ it.each(['header', 'action', 'close', 'section'] as const)('rejects a settings.%s slot found only inside a foreign modal', (name) => {
+ const fixture = mountSettings()
+ const foreign = element('div', fixture.slots[name])
+ foreign.setAttribute('role', 'dialog')
+ foreign.setAttribute('aria-modal', 'true')
+ fixture.nodes.options.append(foreign)
+ expect(resolveMobileSettingsPanel(fixture.nodes.panel)).toBeNull()
+ })
+
+ it.each(['controls', 'back', 'title', 'list', 'options'] as const)('rejects a missing %s node', (name) => {
+ const fixture = mountSettings()
+ fixture.nodes[name].remove()
+ expect(resolveMobileSettingsPanel(fixture.nodes.panel)).toBeNull()
+ })
+
+ it.each(['controls', 'back'] as const)('rejects a duplicated owned %s marker', (name) => {
+ const fixture = mountSettings()
+ const original = fixture.nodes[name]
+ original.parentElement!.append(original.cloneNode(true))
+ expect(resolveMobileSettingsPanel(fixture.nodes.panel)).toBeNull()
+ })
+
+ it.each(['panel', 'nav', 'content', 'header'] as const)('rejects an extra direct child changing the official %s shape', (name) => {
+ const fixture = mountSettings()
+ fixture.nodes[name].append(element('div'))
+ expect(resolveMobileSettingsPanel(fixture.nodes.panel)).toBeNull()
+ })
+
+ it.each(['list', 'options'] as const)('rejects a non-div %s container', (name) => {
+ const fixture = mountSettings()
+ const replacement = element('section', ...fixture.nodes[name].childNodes)
+ fixture.nodes[name].replaceWith(replacement)
+ expect(resolveMobileSettingsPanel(fixture.nodes.panel)).toBeNull()
+ })
+
+ it.each(['nav', 'content', 'close'] as const)('rejects an additional wrapper around the official %s node', (name) => {
+ const fixture = mountSettings()
+ const original = fixture.nodes[name]
+ const parent = original.parentElement!
+ const wrapper = element('div', original)
+ parent.append(wrapper)
+ expect(resolveMobileSettingsPanel(fixture.nodes.panel)).toBeNull()
+ })
+
+ it('rejects an action slot nested under an extra wrapper', () => {
+ const fixture = mountSettings()
+ fixture.nodes.actions.append(element('div', fixture.slots.action))
+ expect(resolveMobileSettingsPanel(fixture.nodes.panel)).toBeNull()
+ })
+
+ it('rejects a header slot no longer directly owned by the labelled title', () => {
+ const fixture = mountSettings()
+ fixture.nodes.title.append(element('span', fixture.slots.header))
+ expect(resolveMobileSettingsPanel(fixture.nodes.panel)).toBeNull()
+ })
+
+ it('rejects controls outside the settings.action slot', () => {
+ const fixture = mountSettings()
+ fixture.nodes.options.append(fixture.nodes.controls)
+ expect(resolveMobileSettingsPanel(fixture.nodes.panel)).toBeNull()
+ })
+
+ it('rejects a section outlet nested under an extra options wrapper', () => {
+ const fixture = mountSettings()
+ fixture.nodes.options.append(element('div', fixture.slots.section))
+ expect(resolveMobileSettingsPanel(fixture.nodes.panel)).toBeNull()
+ })
+
+ it('rejects a navigation row that is not a button', () => {
+ const fixture = mountSettings()
+ fixture.buttons[1].replaceWith(element('a', 'Plugins'))
+ expect(resolveMobileSettingsPanel(fixture.nodes.panel)).toBeNull()
+ })
+
+ it.each([null, 'false'] as const)('rejects nonempty navigation without an aria-current=true row (%s)', (value) => {
+ const fixture = mountSettings()
+ if (value === null)
+ fixture.buttons[0].removeAttribute('aria-current')
+ else
+ fixture.buttons[0].setAttribute('aria-current', value)
+ expect(resolveMobileSettingsPanel(fixture.nodes.panel)).toBeNull()
+ })
+
+ it('rejects multiple aria-current=true rows', () => {
+ const fixture = mountSettings()
+ fixture.buttons[1].setAttribute('aria-current', 'true')
+ expect(resolveMobileSettingsPanel(fixture.nodes.panel)).toBeNull()
+ })
+
+ it('rejects a section outlet when there are no navigation rows', () => {
+ const fixture = mountSettings({ empty: true })
+ fixture.nodes.options.append(fixture.slots.section)
+ expect(resolveMobileSettingsPanel(fixture.nodes.panel)).toBeNull()
+ })
+
+ it.each(['back', 'close'] as const)('rejects a directly disabled %s button', (name) => {
+ const fixture = mountSettings()
+ fixture.nodes[name].disabled = true
+ expect(resolveMobileSettingsPanel(fixture.nodes.panel)).toBeNull()
+ })
+
+ it.each(['back', 'close'] as const)('rejects a %s anchor whose enclosing element is not a button', (name) => {
+ const fixture = mountSettings()
+ const replacement = element('span')
+ if (name === 'back')
+ replacement.setAttribute('data-dsh-mobile-settings-back', '')
+ else
+ replacement.append(fixture.slots.close)
+ fixture.nodes[name].replaceWith(replacement)
+ expect(resolveMobileSettingsPanel(fixture.nodes.panel)).toBeNull()
+ })
+
+ it.each([
+ ['role', null],
+ ['role', 'alertdialog'],
+ ['aria-modal', null],
+ ['aria-modal', 'false'],
+ ])('rejects the shell when %s is %s', (name, value) => {
+ const fixture = mountSettings()
+ if (value === null)
+ fixture.nodes.panel.removeAttribute(name!)
+ else
+ fixture.nodes.panel.setAttribute(name!, value)
+ expect(resolveMobileSettingsPanel(fixture.nodes.panel)).toBeNull()
+ })
+
+ it.each([
+ ['panel', 'hidden'],
+ ['overlay', 'hidden'],
+ ['body', 'hidden'],
+ ['panel', 'inert'],
+ ['overlay', 'inert'],
+ ['body', 'inert'],
+ ] as const)('rejects a shell below %s[%s]', (name, attribute) => {
+ const fixture = mountSettings()
+ const target = name === 'body' ? document.body : fixture.nodes[name]
+ target.setAttribute(attribute, '')
+ const result = resolveMobileSettingsPanel(fixture.nodes.panel)
+ target.removeAttribute(attribute)
+ expect(result).toBeNull()
+ })
+
+ it.each(['panel', 'overlay'] as const)('rejects the shell after its %s is disconnected', (name) => {
+ const fixture = mountSettings()
+ fixture.nodes[name].remove()
+ expect(resolveMobileSettingsPanel(fixture.nodes.panel)).toBeNull()
+ })
+
+ it.each([null, '', ' ', ':unknown:', ':r0: :another:', ':r0:\n:another:'])('rejects an absent, unknown or multi-token title reference (%j)', (value) => {
+ const fixture = mountSettings()
+ if (value === null)
+ fixture.nodes.panel.removeAttribute('aria-labelledby')
+ else
+ fixture.nodes.panel.setAttribute('aria-labelledby', value)
+ expect(resolveMobileSettingsPanel(fixture.nodes.panel)).toBeNull()
+ })
+
+ it('rejects a labelled title outside the settings panel', () => {
+ const fixture = mountSettings()
+ const foreignTitle = element('div', 'Foreign title')
+ foreignTitle.id = ':foreign:'
+ document.body.append(foreignTitle)
+ fixture.nodes.panel.setAttribute('aria-labelledby', ':foreign:')
+ expect(resolveMobileSettingsPanel(fixture.nodes.panel)).toBeNull()
+ })
+
+ it.each(['panel', 'document'] as const)('rejects an aria-labelledby id that is duplicated inside the %s', (location) => {
+ const fixture = mountSettings()
+ const duplicate = element('div', 'Foreign title')
+ duplicate.id = fixture.nodes.title.id
+ const target = location === 'panel' ? fixture.nodes.options : document.body
+ target.append(duplicate)
+ expect(resolveMobileSettingsPanel(fixture.nodes.panel)).toBeNull()
+ })
+
+ it('rejects a back marker whose only button belongs to a nested foreign modal', () => {
+ const fixture = mountSettings()
+ fixture.nodes.back.remove()
+ const foreignBack = button('Foreign back')
+ foreignBack.setAttribute('data-dsh-mobile-settings-back', '')
+ const foreign = element('div', foreignBack)
+ foreign.setAttribute('role', 'dialog')
+ foreign.setAttribute('aria-modal', 'true')
+ fixture.nodes.controls.append(foreign)
+ expect(resolveMobileSettingsPanel(fixture.nodes.panel)).toBeNull()
+ })
+})
+
+describe('findMobileSettingsPanel', () => {
+ it('returns null when no dialog exists', () => {
+ expect(findMobileSettingsPanel()).toBeNull()
+ })
+
+ it.each(['current', 'legacy'] as const)('finds the %s official shell without changing or replacing nodes', (version) => {
+ const fixture = mountSettings({ version })
+ const markup = document.body.innerHTML
+ const children = [...fixture.nodes.panel.children]
+ expectNodes(findMobileSettingsPanel(), fixture.nodes)
+ expectNodes(resolveMobileSettingsPanel(fixture.nodes.panel), fixture.nodes)
+ expect(document.body.innerHTML).toBe(markup)
+ expect([...fixture.nodes.panel.children]).toEqual(children)
+ })
+
+ it('ignores non-settings dialogs before and after the valid shell', () => {
+ const fixture = mountSettings()
+ for (const position of ['before', 'after'] as const) {
+ const foreign = element('div', button('Dismiss'))
+ foreign.setAttribute('role', 'dialog')
+ foreign.setAttribute('aria-modal', 'true')
+ if (position === 'before')
+ document.body.prepend(foreign)
+ else
+ document.body.append(foreign)
+ }
+ expectNodes(findMobileSettingsPanel(), fixture.nodes)
+ })
+
+ it('rejects ambiguous valid current and legacy settings shells', () => {
+ const current = mountSettings({ titleId: ':current:' })
+ const legacy = mountSettings({ version: 'legacy', titleId: ':legacy:' })
+ expectNodes(resolveMobileSettingsPanel(current.nodes.panel), current.nodes)
+ expectNodes(resolveMobileSettingsPanel(legacy.nodes.panel), legacy.nodes)
+ expect(findMobileSettingsPanel()).toBeNull()
+ })
+
+ it('returns the sole valid shell when another settings candidate fails its shape check', () => {
+ const invalid = mountSettings({ titleId: ':invalid:' })
+ invalid.slots.action.remove()
+ const valid = mountSettings({ titleId: ':valid:' })
+ expect(resolveMobileSettingsPanel(invalid.nodes.panel)).toBeNull()
+ expectNodes(findMobileSettingsPanel(), valid.nodes)
+ })
+
+ it.each(['hidden', 'inert'] as const)('ignores a second supported shell hidden through its %s overlay', (attribute) => {
+ const excluded = mountSettings({ titleId: ':excluded:' })
+ excluded.nodes.overlay.setAttribute(attribute, '')
+ const valid = mountSettings({ titleId: ':visible:' })
+ expectNodes(findMobileSettingsPanel(), valid.nodes)
+ })
+})
+
+describe('createSettingsAttributePatch', () => {
+ it.each([null, '', 'original'] as const)('restores the exact prior attribute value %j', (previous) => {
+ const target = element('div')
+ if (previous !== null)
+ target.setAttribute('data-dsh-mobile-settings-view', previous)
+ const patch = createSettingsAttributePatch()
+ patch.set(target, 'data-dsh-mobile-settings-view', 'detail')
+ expect(target.getAttribute('data-dsh-mobile-settings-view')).toBe('detail')
+ patch.restore()
+ expect(target.getAttribute('data-dsh-mobile-settings-view')).toBe(previous)
+ expect(target.hasAttribute('data-dsh-mobile-settings-view')).toBe(previous !== null)
+ })
+
+ it.each(['', 'native'] as const)('restores a removed attribute whose prior value was %j', (previous) => {
+ const target = element('div')
+ target.setAttribute('inert', previous)
+ const patch = createSettingsAttributePatch()
+ patch.set(target, 'inert', null)
+ expect(target.hasAttribute('inert')).toBe(false)
+ patch.restore()
+ expect(target.getAttribute('inert')).toBe(previous)
+ })
+
+ it('restores the original attribute after multiple owned updates', () => {
+ const target = element('div')
+ target.setAttribute('data-dsh-mobile-settings-view', 'native')
+ const patch = createSettingsAttributePatch()
+ patch.set(target, 'data-dsh-mobile-settings-view', 'menu')
+ patch.set(target, 'data-dsh-mobile-settings-view', 'detail')
+ expect(target.getAttribute('data-dsh-mobile-settings-view')).toBe('detail')
+ patch.restore()
+ expect(target.getAttribute('data-dsh-mobile-settings-view')).toBe('native')
+ })
+
+ it('retains the first snapshot across owned removal and recreation', () => {
+ const target = element('div')
+ target.setAttribute('hidden', 'native')
+ const patch = createSettingsAttributePatch()
+ patch.set(target, 'hidden', '')
+ patch.set(target, 'hidden', null)
+ expect(target.hasAttribute('hidden')).toBe(false)
+ patch.set(target, 'hidden', 'detail')
+ expect(target.getAttribute('hidden')).toBe('detail')
+ patch.restore()
+ expect(target.getAttribute('hidden')).toBe('native')
+ })
+
+ it('restores independent attributes on multiple nodes without altering unrelated data', () => {
+ const first = element('div')
+ const second = element('div')
+ first.setAttribute('hidden', 'native-hidden')
+ first.setAttribute('aria-label', 'Settings')
+ second.setAttribute('inert', 'native-inert')
+ const patch = createSettingsAttributePatch()
+ patch.set(first, 'hidden', '')
+ patch.set(first, 'inert', '')
+ patch.set(second, 'hidden', '')
+ patch.set(second, 'inert', null)
+ expect(first.getAttribute('hidden')).toBe('')
+ expect(first.getAttribute('inert')).toBe('')
+ expect(second.getAttribute('hidden')).toBe('')
+ expect(second.hasAttribute('inert')).toBe(false)
+ patch.restore()
+ expect(first.getAttribute('hidden')).toBe('native-hidden')
+ expect(first.hasAttribute('inert')).toBe(false)
+ expect(first.getAttribute('aria-label')).toBe('Settings')
+ expect(second.hasAttribute('hidden')).toBe(false)
+ expect(second.getAttribute('inert')).toBe('native-inert')
+ })
+
+ it('does not mutate the DOM when an owned set already matches the attribute', () => {
+ const target = element('div')
+ target.setAttribute('hidden', '')
+ const set = vi.spyOn(target, 'setAttribute')
+ const remove = vi.spyOn(target, 'removeAttribute')
+ const patch = createSettingsAttributePatch()
+ patch.set(target, 'hidden', '')
+ patch.set(target, 'hidden', '')
+ patch.set(target, 'inert', null)
+ expect(set).not.toHaveBeenCalled()
+ expect(remove).not.toHaveBeenCalled()
+ })
+
+ it('restores each attribute only while its last written value still owns it', () => {
+ const target = element('div')
+ target.setAttribute('hidden', 'native')
+ const patch = createSettingsAttributePatch()
+ patch.set(target, 'hidden', '')
+ patch.set(target, 'inert', '')
+ target.setAttribute('hidden', 'later-owner')
+ patch.restore()
+ expect(target.getAttribute('hidden')).toBe('later-owner')
+ expect(target.hasAttribute('inert')).toBe(false)
+ })
+
+ it('preserves a later owner that removes the plugin-written attribute', () => {
+ const target = element('div')
+ target.setAttribute('hidden', 'native')
+ const patch = createSettingsAttributePatch()
+ patch.set(target, 'hidden', '')
+ target.removeAttribute('hidden')
+ patch.set(target, 'hidden', 'detail')
+ expect(target.hasAttribute('hidden')).toBe(false)
+ patch.restore()
+ expect(target.hasAttribute('hidden')).toBe(false)
+ })
+
+ it('preserves a later owner that recreates a plugin-removed attribute', () => {
+ const target = element('div')
+ target.setAttribute('inert', 'native')
+ const patch = createSettingsAttributePatch()
+ patch.set(target, 'inert', null)
+ target.setAttribute('inert', 'later-owner')
+ patch.set(target, 'inert', '')
+ expect(target.getAttribute('inert')).toBe('later-owner')
+ patch.restore()
+ expect(target.getAttribute('inert')).toBe('later-owner')
+ })
+
+ it('restores a removed DOM node before releasing its recorded ownership', () => {
+ const target = element('div')
+ target.setAttribute('hidden', 'native')
+ document.body.append(target)
+ const patch = createSettingsAttributePatch()
+ patch.set(target, 'hidden', '')
+ target.remove()
+ patch.restore()
+ expect(target.isConnected).toBe(false)
+ expect(target.getAttribute('hidden')).toBe('native')
+ })
+
+ it('releases restored ownership so a second restore cannot touch a later owner', () => {
+ const target = element('div')
+ const patch = createSettingsAttributePatch()
+ patch.set(target, 'hidden', '')
+ patch.restore()
+ expect(target.hasAttribute('hidden')).toBe(false)
+ target.setAttribute('hidden', 'later-owner')
+ patch.restore()
+ expect(target.getAttribute('hidden')).toBe('later-owner')
+ })
+
+ it('captures a new baseline when reused after restore', () => {
+ const target = element('div')
+ const patch = createSettingsAttributePatch()
+ patch.set(target, 'hidden', '')
+ patch.restore()
+ target.setAttribute('hidden', 'new-native')
+ patch.set(target, 'hidden', 'detail')
+ expect(target.getAttribute('hidden')).toBe('detail')
+ patch.restore()
+ expect(target.getAttribute('hidden')).toBe('new-native')
+ })
+
+ it('forgets relinquished attributes after restore and can start a fresh ownership cycle', () => {
+ const target = element('div')
+ const patch = createSettingsAttributePatch()
+ patch.set(target, 'hidden', '')
+ target.setAttribute('hidden', 'later-owner')
+ patch.restore()
+ patch.set(target, 'hidden', 'detail')
+ expect(target.getAttribute('hidden')).toBe('detail')
+ patch.restore()
+ expect(target.getAttribute('hidden')).toBe('later-owner')
+ })
+
+ it('leaves a later owner untouched by an attempted update or restore', () => {
+ const target = element('div')
+ const patch = createSettingsAttributePatch()
+ patch.set(target, 'hidden', '')
+ target.setAttribute('hidden', 'later-owner')
+ patch.set(target, 'hidden', null)
+ expect(target.getAttribute('hidden')).toBe('later-owner')
+ patch.restore()
+ expect(target.getAttribute('hidden')).toBe('later-owner')
+ })
+})
diff --git a/packages/dsh-tauri-mobile-ui/src/client/register/settings.utils.ts b/packages/dsh-tauri-mobile-ui/src/client/register/settings.utils.ts
new file mode 100644
index 00000000..c6f26e5b
--- /dev/null
+++ b/packages/dsh-tauri-mobile-ui/src/client/register/settings.utils.ts
@@ -0,0 +1,154 @@
+import type { MobileSettingsView } from '../types/settings'
+
+export interface MobileSettingsNodes {
+ panel: HTMLElement
+ overlay: HTMLElement
+ nav: HTMLElement
+ title: HTMLElement
+ list: HTMLElement
+ content: HTMLElement
+ header: HTMLElement
+ actions: HTMLElement
+ close: HTMLButtonElement
+ options: HTMLElement
+ controls: HTMLElement
+ back: HTMLButtonElement
+ current: HTMLButtonElement | null
+}
+
+const DIALOG_SELECTOR = '[role="dialog"][aria-modal="true"]'
+
+function only(elements: Element[]): HTMLElement | null {
+ return elements.length === 1 && elements[0] instanceof HTMLElement ? elements[0] : null
+}
+
+export function resolveMobileSettingsPanel(panel: HTMLElement): MobileSettingsNodes | null {
+ if (!panel.isConnected || !panel.matches(DIALOG_SELECTOR) || panel.closest('[hidden], [inert]') !== null)
+ return null
+ const owned = (selector: string): Element[] => [...panel.querySelectorAll(selector)]
+ .filter(element => element.closest(DIALOG_SELECTOR) === panel)
+ const actionSlot = only(owned('[data-slot="settings.action"]'))
+ const headerSlot = only(owned('[data-slot="settings.header"]'))
+ const closeSlot = only(owned('[data-slot="settings.close"]'))
+ const controls = only(owned('[data-dsh-mobile-settings-controls]'))
+ const actions = actionSlot?.parentElement
+ const header = actions?.parentElement
+ const content = header?.parentElement
+ const close = closeSlot?.closest('button')
+ const titleId = panel.getAttribute('aria-labelledby')?.trim()
+ const title = titleId && !/\s/.test(titleId)
+ ? only([...document.querySelectorAll('[id]')].filter(element => element.id === titleId))
+ : null
+ const nav = title?.parentElement
+ const list = nav && only([...nav.children].filter(element => element !== title))
+ const options = content && only([...content.children].filter(element => element !== header))
+ const back = controls && only([...controls.querySelectorAll('[data-dsh-mobile-settings-back]')]
+ .filter(element => element.closest(DIALOG_SELECTOR) === panel))
+ const overlay = panel.parentElement
+ if (!actions || !header || !content || !nav || !title || !list || !options || !overlay
+ || !controls || !(close instanceof HTMLButtonElement) || !(back instanceof HTMLButtonElement)
+ || back.disabled || close.disabled || !actionSlot?.contains(controls)
+ || headerSlot?.parentElement !== title || nav.parentElement !== panel || content.parentElement !== panel
+ || close.parentElement !== header || panel.children.length !== 2 || nav.children.length !== 2
+ || content.children.length !== 2 || header.children.length !== 2 || list.tagName !== 'DIV'
+ || options.tagName !== 'DIV' || !header.contains(closeSlot) || !panel.contains(title)) {
+ return null
+ }
+ const buttons = [...list.children]
+ const current = buttons.filter(element => element.getAttribute('aria-current') === 'true')
+ const sections = owned('[data-slot="settings.section"]')
+ if (buttons.some(element => !(element instanceof HTMLButtonElement))
+ || current.length !== (buttons.length > 0 ? 1 : 0)
+ || sections.length !== (buttons.length > 0 ? 1 : 0)
+ || sections.some(element => element.parentElement !== options)) {
+ return null
+ }
+ return {
+ panel,
+ overlay,
+ nav,
+ title,
+ list,
+ content,
+ header,
+ actions,
+ close,
+ options,
+ controls,
+ back,
+ current: current[0] instanceof HTMLButtonElement ? current[0] : null,
+ }
+}
+
+export function isForegroundSettingsPanel(panel: HTMLElement): boolean {
+ return [...document.querySelectorAll('[role="dialog"][aria-modal="true"], [role="menu"]')]
+ .filter(element => element.closest('[hidden], [inert], [aria-hidden="true"]') === null)
+ .at(-1) === panel
+}
+
+export function findMobileSettingsPanel(): MobileSettingsNodes | null {
+ const panels = [...document.querySelectorAll<HTMLElement>(DIALOG_SELECTOR)]
+ .map(resolveMobileSettingsPanel)
+ .filter((nodes): nodes is MobileSettingsNodes => nodes !== null)
+ return panels.length === 1 ? panels[0] : null
+}
+
+export function applySettingsPresentation(nodes: MobileSettingsNodes, view: MobileSettingsView, patch: ReturnType<typeof createSettingsAttributePatch>): void {
+ for (const name of ['overlay', 'nav', 'title', 'list', 'content', 'header', 'actions', 'close', 'options'] as const)
+ patch.set(nodes[name], `data-dsh-mobile-settings-${name}`, '')
+ patch.set(nodes.panel, 'data-dsh-mobile-settings', '')
+ patch.set(nodes.panel, 'data-dsh-mobile-settings-view', view)
+ for (const [element, hidden] of [[nodes.list, view === 'detail'], [nodes.options, view === 'menu'], [nodes.controls, view === 'menu']] as const) {
+ patch.set(element, 'hidden', hidden ? '' : null)
+ if (element !== nodes.controls)
+ patch.set(element, 'inert', hidden ? '' : null)
+ }
+}
+
+export function createSettingsAttributePatch() {
+ const changes = new Map<HTMLElement, Map<string, { previous: string | null, written: string | null }>>()
+ return {
+ set(element: HTMLElement, name: string, value: string | null): void {
+ let attributes = changes.get(element)
+ if (attributes === undefined) {
+ attributes = new Map()
+ changes.set(element, attributes)
+ }
+ const previous = attributes.get(name)
+ if (previous !== undefined && element.getAttribute(name) !== previous.written)
+ return
+ if (previous === undefined)
+ attributes.set(name, { previous: element.getAttribute(name), written: value })
+ else
+ previous.written = value
+ if (element.getAttribute(name) === value)
+ return
+ if (value === null)
+ element.removeAttribute(name)
+ else
+ element.setAttribute(name, value)
+ },
+ isIntact(): boolean {
+ for (const [element, attributes] of changes) {
+ for (const [name, { written }] of attributes) {
+ if (element.getAttribute(name) !== written)
+ return false
+ }
+ }
+ return true
+ },
+ restore(): void {
+ for (const [element, attributes] of changes) {
+ for (const [name, { previous, written }] of attributes) {
+ if (element.getAttribute(name) !== written)
+ continue
+ if (previous === null)
+ element.removeAttribute(name)
+ else
+ element.setAttribute(name, previous)
+ }
+ }
+ changes.clear()
+ },
+ }
+}
diff --git a/packages/dsh-tauri-mobile-ui/src/client/register/styles.test.ts b/packages/dsh-tauri-mobile-ui/src/client/register/styles.test.ts
index fef9d5a9..78862d89 100644
--- a/packages/dsh-tauri-mobile-ui/src/client/register/styles.test.ts
+++ b/packages/dsh-tauri-mobile-ui/src/client/register/styles.test.ts
@@ -17,7 +17,7 @@ vi.mock('dsh-tauri/client', () => ({
vi.mock('dsh-tauri-ui/client', () => ({ cssr, mountStyle }))
afterEach(() => {
- document.querySelectorAll('style[cssr-id="dsh-tauri-mobile-ui-styles"]').forEach(element => element.remove())
+ document.querySelectorAll('style[data-plugin="dsh-tauri-mobile-ui"]').forEach(element => element.remove())
document.documentElement.removeAttribute('data-dsh-mobile-ui')
vi.restoreAllMocks()
})
@@ -42,9 +42,14 @@ it('owns mobile styles and composer activation until unload, and can reload clea
]) {
expect(style?.textContent).toContain(selector)
}
+ const settingsStyle = document.querySelector('style[cssr-id="dsh-tauri-mobile-ui-settings-styles"]')
+ expect(settingsStyle?.getAttribute('data-plugin')).toBe('dsh-tauri-mobile-ui')
+ expect(settingsStyle?.textContent).toContain('(max-width: 767px)')
+ expect(settingsStyle?.textContent).toContain('[data-dsh-mobile-settings]')
expect(document.documentElement.hasAttribute('data-dsh-mobile-ui')).toBe(true)
dispose()
expect(style?.isConnected).toBe(false)
+ expect(settingsStyle?.isConnected).toBe(false)
expect(document.documentElement.hasAttribute('data-dsh-mobile-ui')).toBe(false)
}
})
diff --git a/packages/dsh-tauri-mobile-ui/src/client/register/styles.ts b/packages/dsh-tauri-mobile-ui/src/client/register/styles.ts
index 395c9eee..3dc94de0 100644
--- a/packages/dsh-tauri-mobile-ui/src/client/register/styles.ts
+++ b/packages/dsh-tauri-mobile-ui/src/client/register/styles.ts
@@ -3,9 +3,11 @@ import { mountStyle } from 'dsh-tauri-ui/client'
import { defineRegister } from 'dsh-tauri/client'
import { PLUGIN_ID } from '../../shared/constants'
import mobileStyle from '../styles/mobile.cssr'
+import settingsStyle from '../styles/settings.cssr'
export const registerStyles = defineRegister<ClientContext>((controller) => {
controller.add(mountStyle(mobileStyle, `${PLUGIN_ID}-styles`, PLUGIN_ID))
+ controller.add(mountStyle(settingsStyle, `${PLUGIN_ID}-settings-styles`, PLUGIN_ID))
document.documentElement.setAttribute('data-dsh-mobile-ui', '')
controller.add(() => document.documentElement.removeAttribute('data-dsh-mobile-ui'))
})
diff --git a/packages/dsh-tauri-mobile-ui/src/client/service/settings.test.ts b/packages/dsh-tauri-mobile-ui/src/client/service/settings.test.ts
new file mode 100644
index 00000000..5967cb7a
--- /dev/null
+++ b/packages/dsh-tauri-mobile-ui/src/client/service/settings.test.ts
@@ -0,0 +1,57 @@
+import type { MobileSettingsSnapshot } from '../types/settings'
+import { describe, expect, it } from 'vitest'
+import { resolveSettingsPresentation } from './settings'
+
+const detail: MobileSettingsSnapshot = { ready: true, view: 'detail', title: 'General' }
+const menu: MobileSettingsSnapshot = { ready: true, view: 'menu', title: 'General' }
+const facts = {
+ entering: false,
+ changing: false,
+ launcher: false,
+ navigation: false,
+ selectionChanged: false,
+ title: 'General',
+ focused: { list: false, options: false, controls: false },
+}
+
+describe('mobile settings presentation projection', () => {
+ it.each([
+ { name: 'official launcher', patch: { entering: true, launcher: true }, view: 'menu', focus: null },
+ { name: 'unknown entry', patch: { entering: true }, view: 'detail', focus: 'back' },
+ { name: 'replacement content', patch: { changing: true, launcher: true }, view: 'detail', focus: 'back' },
+ { name: 'empty ledger', patch: { title: null }, view: 'menu', focus: null },
+ { name: 'empty ledger after detail', previous: detail, patch: { title: null }, view: 'menu', focus: 'category' },
+ { name: 'same section native click', patch: { navigation: true }, view: 'detail', focus: 'back' },
+ { name: 'external selection', patch: { selectionChanged: true, title: 'Models' }, view: 'detail', focus: 'back' },
+ { name: 'unchanged categories', patch: {}, view: 'menu', focus: null },
+ { name: 'ordinary detail input', previous: detail, patch: {}, view: 'detail', focus: null },
+ { name: 'focus inside hidden navigation', previous: detail, patch: { focused: { ...facts.focused, list: true } }, view: 'detail', focus: 'back' },
+ { name: 'focus inside hidden options', patch: { focused: { ...facts.focused, options: true } }, view: 'menu', focus: 'category' },
+ { name: 'focus inside retiring Back', patch: { focused: { ...facts.focused, controls: true } }, view: 'menu', focus: 'category' },
+ ])('projects $name without owning a native section id', ({ previous = menu, patch, view, focus }) => {
+ const result = resolveSettingsPresentation(previous, previous.view, { ...facts, ...patch })
+ expect(result).toEqual({ snapshot: { ready: true, view, title: patch.title === null ? '' : patch.title ?? 'General' }, focus })
+ })
+
+ it('preserves snapshot identity for unchanged native facts', () => {
+ expect(resolveSettingsPresentation(detail, 'detail', facts).snapshot).toBe(detail)
+ })
+
+ it('keeps a label-only update in categories without stealing focus', () => {
+ expect(resolveSettingsPresentation(menu, 'menu', { ...facts, title: '常规设置' })).toEqual({
+ snapshot: { ready: true, view: 'menu', title: '常规设置' },
+ focus: null,
+ })
+ })
+
+ it('prioritizes an empty ledger over launcher or navigation intent', () => {
+ expect(resolveSettingsPresentation(detail, 'detail', { ...facts, entering: true, launcher: true, navigation: true, title: null })).toEqual({
+ snapshot: { ready: true, view: 'menu', title: '' },
+ focus: 'category',
+ })
+ })
+
+ it('returns to categories without changing the current native label', () => {
+ expect(resolveSettingsPresentation(detail, 'menu', facts)).toEqual({ snapshot: menu, focus: 'category' })
+ })
+})
diff --git a/packages/dsh-tauri-mobile-ui/src/client/service/settings.ts b/packages/dsh-tauri-mobile-ui/src/client/service/settings.ts
new file mode 100644
index 00000000..de4aeae2
--- /dev/null
+++ b/packages/dsh-tauri-mobile-ui/src/client/service/settings.ts
@@ -0,0 +1,34 @@
+import type { MobileSettingsSnapshot, MobileSettingsView } from '../types/settings'
+
+interface SettingsPresentationFacts {
+ entering: boolean
+ changing: boolean
+ launcher: boolean
+ navigation: boolean
+ selectionChanged: boolean
+ title: string | null
+ focused: { list: boolean, options: boolean, controls: boolean }
+}
+
+export function resolveSettingsPresentation(previous: MobileSettingsSnapshot, intent: MobileSettingsView, facts: SettingsPresentationFacts): {
+ snapshot: MobileSettingsSnapshot
+ focus: 'back' | 'category' | null
+} {
+ let view = intent
+ if (facts.entering || facts.changing)
+ view = facts.entering && facts.launcher ? 'menu' : 'detail'
+ if (facts.title === null)
+ view = 'menu'
+ else if (facts.navigation || facts.selectionChanged)
+ view = 'detail'
+ const title = facts.title ?? ''
+ const snapshot = previous.ready && previous.view === view && previous.title === title
+ ? previous
+ : { ready: true, view, title }
+ const focus = view === 'detail' && (facts.focused.list || facts.entering || facts.changing || facts.navigation || previous.view !== view)
+ ? 'back'
+ : view === 'menu' && (facts.focused.options || facts.focused.controls || previous.view !== view)
+ ? 'category'
+ : null
+ return { snapshot, focus }
+}
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 244508af..05cc6e9c 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
@@ -33,6 +33,21 @@ describe('mobile conversation layout', () => {
}
})
+ it('keeps the extension panel’s embedded official page head out of the main-slot clearance', () => {
+ const matches: Array<{ selector: string, paddingTop: string }> = []
+ root.walkRules(/header\[class\*="_pageHead"\]/, (rule) => {
+ let paddingTop = ''
+ rule.walkDecls('padding-top', (decl) => {
+ paddingTop = `${decl.value}${decl.important ? ' !important' : ''}`
+ })
+ matches.push({ selector: rule.selector, paddingTop })
+ })
+ expect(matches).toEqual([{
+ selector: '[data-slot="main"] header[class*="_pageHead"]:not([data-dsh-extension-plugins] *)',
+ paddingTop: '24px !important',
+ }])
+ })
+
it('positions the drawer without relying on the upstream collapsed marker', () => {
const css = root.toString()
for (const selector of [
@@ -49,16 +64,17 @@ describe('mobile conversation layout', () => {
expect(css).not.toContain('[data-sidebar-collapsed]')
})
- it('keeps the sidebar stationary behind a raised rounded main panel without a gray shade', () => {
- const declarations = (selector: string): Record<string, string> => {
- const values: Record<string, string> = {}
- root.walkRules(selector, (rule) => {
- rule.walkDecls((decl) => {
- values[decl.prop] = `${decl.value}${decl.important ? ' !important' : ''}`
- })
+ const declarations = (selector: string): Record<string, string> => {
+ const values: Record<string, string> = {}
+ root.walkRules(selector, (rule) => {
+ rule.walkDecls((decl) => {
+ values[decl.prop] = `${decl.value}${decl.important ? ' !important' : ''}`
})
- return values
- }
+ })
+ return values
+ }
+
+ it('keeps the sidebar stationary behind a raised rounded main panel without a gray shade', () => {
expect(declarations('html[data-dsh-mobile-sidebar] [class$="_sidebarCol"]')).toMatchObject({
'z-index': '0',
'transform': 'none',
@@ -88,12 +104,41 @@ describe('mobile conversation layout', () => {
position: 'sticky',
top: '0',
})
- expect(declarations('[data-dsh-mobile-sidebar-toggle]')).toMatchObject({
- 'width': '24px',
- 'height': '24px',
- 'background': 'transparent',
- 'box-shadow': 'none',
+ })
+
+ it('keeps the navbar controls as naked icons without button backgrounds or shadows', () => {
+ for (const selector of ['[data-dsh-mobile-sidebar-toggle]', '[data-dsh-mobile-new-session]']) {
+ expect(declarations(selector)).toMatchObject({
+ 'padding': '0',
+ 'border': '0',
+ 'background': 'transparent',
+ 'box-shadow': 'none',
+ })
+ }
+ })
+
+ it('renders the mobile sidebar icon at 20px inside the touch media query', () => {
+ expect(declarations('[data-dsh-mobile-sidebar-toggle]')).toMatchObject({ width: '20px', height: '20px' })
+ const rules: unknown[] = []
+ root.walkRules('[data-dsh-mobile-sidebar-toggle]', (rule) => {
+ rules.push(rule)
+ expect(rule.parent?.type).toBe('atrule')
+ if (rule.parent?.type === 'atrule')
+ expect(rule.parent.params).toBe('(hover: none) and (any-pointer: coarse) and (any-hover: none)')
+ })
+ expect(rules).toHaveLength(1)
+ })
+
+ it('keeps the new-session icon at 24px', () => {
+ expect(declarations('[data-dsh-mobile-new-session]')).toMatchObject({ width: '24px', height: '24px' })
+ const rules: unknown[] = []
+ root.walkRules('[data-dsh-mobile-new-session]', (rule) => {
+ rules.push(rule)
+ expect(rule.parent?.type).toBe('atrule')
+ if (rule.parent?.type === 'atrule')
+ expect(rule.parent.params).toBe('(hover: none) and (any-pointer: coarse) and (any-hover: none)')
})
+ expect(rules).toHaveLength(1)
})
it('overrides conversation scroll bottom padding to zero inside the mobile media query', () => {
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 1488c6a8..a2849c48 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
@@ -28,7 +28,9 @@ export default c(`@media ${MOBILE_MEDIA_QUERIES.join(' and ')}`, [
c('[data-slot="conversation.header"] [class$="_header"]', {
display: 'none !important',
}),
- c('[data-slot="main"] header[class*="_pageHead"]', {
+ // 扩展面板内嵌的官方页头由 dsh-tauri-extension 自己排版(同一行左侧还有它叠放的闪光图标),
+ // 这里叠加顶距会把标题压低、与图标错轴,因此只给主槽里独立成页的页头让位。
+ c('[data-slot="main"] header[class*="_pageHead"]:not([data-dsh-extension-plugins] *)', {
paddingLeft: '0 !important',
paddingTop: '24px !important',
}),
@@ -133,8 +135,8 @@ export default c(`@media ${MOBILE_MEDIA_QUERIES.join(' and ')}`, [
}),
c('[data-dsh-mobile-sidebar-toggle]', {
display: 'block',
- width: '24px',
- height: '24px',
+ width: '20px',
+ height: '20px',
padding: '0',
border: '0',
color: 'var(--dsw-alias-label-primary)',
diff --git a/packages/dsh-tauri-mobile-ui/src/client/styles/settings.cssr.test.ts b/packages/dsh-tauri-mobile-ui/src/client/styles/settings.cssr.test.ts
new file mode 100644
index 00000000..8e22ff71
--- /dev/null
+++ b/packages/dsh-tauri-mobile-ui/src/client/styles/settings.cssr.test.ts
@@ -0,0 +1,217 @@
+import type { Rule } from 'postcss'
+import postcss from 'postcss'
+import { afterEach, describe, expect, it, vi } from 'vitest'
+import { cssr } from '../../../../dsh-tauri-ui/src/client/utils/cssr'
+import { MOBILE_MEDIA_QUERIES } from '../../../../dsh-tauri/src/client/utils/device'
+import settingsStyle from './settings.cssr'
+
+vi.mock('dsh-tauri/client', () => ({ MOBILE_MEDIA_QUERIES }))
+vi.mock('dsh-tauri-ui/client', () => ({ cssr }))
+
+afterEach(() => vi.restoreAllMocks())
+
+describe('mobile settings layout contract', () => {
+ const root = postcss.parse(settingsStyle.render())
+ const panel = '[data-dsh-mobile-settings][data-dsh-mobile-settings-view]'
+ const overlay = `[data-dsh-mobile-settings-overlay]:has(> ${panel})`
+ const inlineSidebar = `html[data-dsh-mobile-sidebar] [data-slot="root"] > * > :has(> [data-slot="sidebar"] ${panel})`
+ const menu = `${panel}[data-dsh-mobile-settings-view="menu"]`
+ const detail = `${panel}[data-dsh-mobile-settings-view="detail"]`
+ const rules: Rule[] = []
+ root.walkRules((rule) => {
+ rules.push(rule)
+ })
+
+ function declarations(selector: string): Record<string, string> {
+ const matching = rules.filter(rule => rule.selector === selector)
+ expect(matching, `Expected one rule for ${selector}`).toHaveLength(1)
+ const values: Record<string, string> = {}
+ matching[0].walkDecls((decl) => {
+ values[decl.prop] = `${decl.value}${decl.important ? ' !important' : ''}`
+ })
+ return values
+ }
+
+ it('activates every override only for owned settings on touch viewports at most 767px', () => {
+ expect(root.nodes).toHaveLength(1)
+ const media = root.nodes[0]
+ expect(media.type).toBe('atrule')
+ if (media.type !== 'atrule')
+ throw new Error('Missing mobile settings media query')
+ expect(media.name).toBe('media')
+ expect(media.params).toBe('(hover: none) and (any-pointer: coarse) and (any-hover: none) and (max-width: 767px)')
+ expect(rules.length).toBeGreaterThan(0)
+ for (const rule of rules) {
+ expect(rule.parent).toBe(media)
+ for (const selector of rule.selector.split(', ')) {
+ if (selector === overlay || selector === inlineSidebar)
+ continue
+ expect(selector, 'Every selector needs both owned panel and view anchors').toMatch(/^(?:body\[data-ds-dark-theme\] )?\[data-dsh-mobile-settings\]\[data-dsh-mobile-settings-view\]/)
+ }
+ }
+ })
+
+ it('releases only an owned inline settings ancestor from the drawer stacking context', () => {
+ expect(declarations(inlineSidebar)).toEqual({ 'z-index': 'auto' })
+ expect(declarations(overlay)).not.toHaveProperty('z-index')
+ })
+
+ it('fills the viewport with safe-area padding and an opaque theme-aware canvas', () => {
+ expect(declarations(overlay)).toMatchObject({
+ position: 'fixed',
+ inset: '0',
+ width: '100vw',
+ height: '100dvh',
+ padding: '0',
+ })
+ expect(declarations(panel)).toMatchObject({
+ 'display': 'flex',
+ 'flex-direction': 'column',
+ 'width': '100vw',
+ 'max-width': 'none',
+ 'height': '100dvh',
+ 'max-height': '100dvh',
+ 'min-width': '0',
+ 'min-height': '0',
+ 'border-radius': '0',
+ 'box-shadow': 'none',
+ 'padding': 'env(safe-area-inset-top, 0px) env(safe-area-inset-right, 0px) env(safe-area-inset-bottom, 0px) env(safe-area-inset-left, 0px)',
+ 'color-scheme': 'light',
+ 'background-color': 'Canvas',
+ 'background-image': 'linear-gradient(var(--dsw-alias-bg-layer-2, Canvas), var(--dsw-alias-bg-layer-2, Canvas))',
+ 'overflow': 'hidden',
+ })
+ expect(declarations(`body[data-ds-dark-theme] ${panel}`)).toEqual({ 'color-scheme': 'dark' })
+ })
+
+ it('gives the menu a full-height list with wrapping 52px touch targets', () => {
+ expect(declarations(`${panel} [data-dsh-mobile-settings-nav]`)).toMatchObject({
+ 'display': 'flex',
+ 'flex-direction': 'column',
+ 'flex': '1 1 0',
+ 'width': '100%',
+ 'min-height': '0',
+ })
+ expect(declarations(`${panel} [data-dsh-mobile-settings-title]`)).toMatchObject({
+ 'display': 'flex',
+ 'min-height': '52px',
+ 'padding': '0 52px 0 12px',
+ })
+ expect(declarations(`${panel} [data-dsh-mobile-settings-list] > button`)).toMatchObject({
+ 'width': '100%',
+ 'min-height': '52px',
+ 'height': 'auto',
+ 'font-size': '15px',
+ 'touch-action': 'manipulation',
+ })
+ expect(declarations(`${panel} [data-dsh-mobile-settings-list] > button > span`)).toMatchObject({
+ 'white-space': 'normal',
+ 'overflow-wrap': 'anywhere',
+ })
+ expect(declarations(`${menu} [data-dsh-mobile-settings-content]`)).toEqual({ flex: '0 0 auto' })
+ expect(declarations(`${menu} [data-dsh-mobile-settings-header]`)).toMatchObject({
+ 'min-height': '0',
+ 'padding': '0 12px 12px',
+ })
+ })
+
+ it('clips only the native title visually in detail while reserving the back toolbar', () => {
+ expect(declarations(`${detail} [data-dsh-mobile-settings-nav]`)).toMatchObject({
+ position: 'absolute',
+ width: '0',
+ height: '0',
+ padding: '0',
+ })
+ const title = declarations(`${detail} [data-dsh-mobile-settings-title]`)
+ expect(title).toMatchObject({
+ 'position': 'absolute',
+ 'width': '1px',
+ 'height': '1px',
+ 'overflow': 'hidden',
+ 'clip-path': 'inset(50%)',
+ })
+ expect(title).not.toHaveProperty('display')
+ expect(title).not.toHaveProperty('visibility')
+ expect(declarations(`${panel} [data-dsh-mobile-settings-content]`)).toMatchObject({
+ 'flex': '1 1 0',
+ 'position': 'static',
+ 'min-height': '0',
+ })
+ expect(declarations(`${panel} [data-dsh-mobile-settings-header]`)).toMatchObject({
+ 'position': 'static',
+ 'height': 'auto',
+ 'min-height': '52px',
+ 'padding': '52px 12px 0',
+ })
+ expect(declarations(`${panel} [data-dsh-mobile-settings-actions]`)).toMatchObject({
+ 'display': 'flex',
+ 'flex-wrap': 'wrap',
+ 'position': 'static',
+ 'width': '100%',
+ })
+ expect(declarations(`${panel} [data-dsh-mobile-settings-controls]`)).toMatchObject({
+ 'position': 'absolute',
+ 'height': '52px',
+ 'grid-template-columns': '40px minmax(0, 1fr)',
+ 'left': 'calc(12px + env(safe-area-inset-left, 0px))',
+ 'right': 'calc(64px + env(safe-area-inset-right, 0px))',
+ })
+ })
+
+ it('keeps the native close button reachable above both views with visible keyboard focus', () => {
+ expect(declarations(`${panel} [data-dsh-mobile-settings-close]`)).toMatchObject({
+ 'position': 'absolute',
+ 'top': 'calc(6px + env(safe-area-inset-top, 0px))',
+ 'right': 'calc(12px + env(safe-area-inset-right, 0px))',
+ 'display': 'flex',
+ 'width': '40px',
+ 'height': '40px',
+ 'min-width': '40px',
+ 'min-height': '40px',
+ 'z-index': '2',
+ 'touch-action': 'manipulation',
+ })
+ expect(declarations(`${panel} [data-dsh-mobile-settings-back]`)).toMatchObject({
+ 'width': '40px',
+ 'height': '40px',
+ 'touch-action': 'manipulation',
+ })
+ expect(declarations(`${panel} [data-dsh-mobile-settings-back]:focus-visible, ${panel} [data-dsh-mobile-settings-close]:focus-visible`)).toEqual({
+ 'outline': 'var(--dsw-focus-ring-width, 2px) solid var(--dsw-focus-ring-color, var(--dsw-alias-state-business-primary))',
+ 'outline-offset': '2px',
+ })
+ for (const rule of rules.filter(rule => rule.selector.includes('[data-dsh-mobile-settings-view='))) {
+ rule.walkDecls((decl) => {
+ expect(decl.prop === 'display' && decl.value === 'none', `${rule.selector} must not hide unmanaged nodes`).toBe(false)
+ })
+ }
+ })
+
+ it('lets owned scroll areas fill their flex space despite a bridge inline height pin', () => {
+ for (const name of ['list', 'options']) {
+ expect(declarations(`${panel} [data-dsh-mobile-settings-${name}]`)).toMatchObject({
+ 'flex': '1 1 0',
+ 'height': '0 !important',
+ 'min-height': '0',
+ 'min-width': '0',
+ 'overflow-y': 'auto',
+ 'overscroll-behavior': 'contain',
+ })
+ }
+ expect(declarations(`${panel} [data-dsh-mobile-settings-options]`)).toMatchObject({
+ 'overflow-x': 'auto',
+ 'width': '100%',
+ })
+ const css = root.toString()
+ expect(css).not.toMatch(/\[class|VOzbGW|data-dshbr|visualViewport|\b(?:input|textarea|tabpanel)\b/)
+ expect(rules.filter(rule => rule.selector.includes(':has(')).map(rule => rule.selector)).toEqual([inlineSidebar, overlay])
+ expect(rules.filter(rule => rule.selector.includes('[data-dsh-mobile-settings-options]'))).toHaveLength(2)
+ })
+
+ it('hides only the controller-managed hidden list, options and controls', () => {
+ const hidden = rules.filter(rule => rule.nodes.some(node => node.type === 'decl' && node.prop === 'display' && node.value === 'none'))
+ expect(hidden).toHaveLength(1)
+ expect(hidden[0].selector).toBe(`${panel} [data-dsh-mobile-settings-list][hidden], ${panel} [data-dsh-mobile-settings-options][hidden], ${panel} [data-dsh-mobile-settings-controls][hidden]`)
+ expect(declarations(hidden[0].selector)).toEqual({ display: 'none !important' })
+ })
+})
diff --git a/packages/dsh-tauri-mobile-ui/src/client/styles/settings.cssr.ts b/packages/dsh-tauri-mobile-ui/src/client/styles/settings.cssr.ts
new file mode 100644
index 00000000..937e4bd0
--- /dev/null
+++ b/packages/dsh-tauri-mobile-ui/src/client/styles/settings.cssr.ts
@@ -0,0 +1,239 @@
+import { cssr } from 'dsh-tauri-ui/client'
+import { MOBILE_SETTINGS_MEDIA } from '../constants'
+
+const { c } = cssr
+const panel = '[data-dsh-mobile-settings][data-dsh-mobile-settings-view]'
+const menu = `${panel}[data-dsh-mobile-settings-view="menu"]`
+const detail = `${panel}[data-dsh-mobile-settings-view="detail"]`
+
+export default c(`@media ${MOBILE_SETTINGS_MEDIA}`, [
+ c(`html[data-dsh-mobile-sidebar] [data-slot="root"] > * > :has(> [data-slot="sidebar"] ${panel})`, {
+ zIndex: 'auto',
+ }),
+ c(`[data-dsh-mobile-settings-overlay]:has(> ${panel})`, {
+ position: 'fixed',
+ inset: '0',
+ width: '100vw',
+ height: '100dvh',
+ padding: '0',
+ alignItems: 'stretch',
+ justifyContent: 'stretch',
+ }),
+ c(panel, {
+ display: 'flex',
+ flexDirection: 'column',
+ position: 'relative',
+ boxSizing: 'border-box',
+ width: '100vw',
+ maxWidth: 'none',
+ height: '100dvh',
+ maxHeight: '100dvh',
+ minWidth: '0',
+ minHeight: '0',
+ margin: '0',
+ padding: 'env(safe-area-inset-top, 0px) env(safe-area-inset-right, 0px) env(safe-area-inset-bottom, 0px) env(safe-area-inset-left, 0px)',
+ gap: '0',
+ border: '0',
+ borderRadius: '0',
+ boxShadow: 'none',
+ color: 'var(--dsw-alias-label-primary)',
+ colorScheme: 'light',
+ backgroundColor: 'Canvas',
+ backgroundImage: 'linear-gradient(var(--dsw-alias-bg-layer-2, Canvas), var(--dsw-alias-bg-layer-2, Canvas))',
+ overflow: 'hidden',
+ }),
+ c(`body[data-ds-dark-theme] ${panel}`, {
+ colorScheme: 'dark',
+ }),
+ c(`${panel} [data-dsh-mobile-settings-nav]`, {
+ display: 'flex',
+ flexDirection: 'column',
+ flex: '1 1 0',
+ boxSizing: 'border-box',
+ width: '100%',
+ minWidth: '0',
+ minHeight: '0',
+ padding: '0 12px',
+ gap: '8px',
+ }),
+ c(`${panel} [data-dsh-mobile-settings-title]`, {
+ display: 'flex',
+ alignItems: 'center',
+ flex: '0 0 auto',
+ boxSizing: 'border-box',
+ minHeight: '52px',
+ minWidth: '0',
+ margin: '0',
+ padding: '0 52px 0 12px',
+ fontSize: '18px',
+ fontWeight: '600',
+ lineHeight: '24px',
+ color: 'var(--dsw-alias-label-primary)',
+ }),
+ c(`${panel} [data-dsh-mobile-settings-list]`, {
+ display: 'flex',
+ flexDirection: 'column',
+ boxSizing: 'border-box',
+ flex: '1 1 0',
+ height: '0 !important',
+ minWidth: '0',
+ minHeight: '0',
+ width: '100%',
+ padding: '0 0 12px',
+ margin: '0',
+ gap: '4px',
+ overflowX: 'hidden',
+ overflowY: 'auto',
+ overscrollBehavior: 'contain',
+ }),
+ c(`${panel} [data-dsh-mobile-settings-list] > button`, {
+ flex: '0 0 auto',
+ width: '100%',
+ minWidth: '0',
+ minHeight: '52px',
+ height: 'auto',
+ padding: '12px',
+ gap: '12px',
+ fontSize: '15px',
+ lineHeight: '22px',
+ textAlign: 'start',
+ touchAction: 'manipulation',
+ }),
+ c(`${panel} [data-dsh-mobile-settings-list] > button > span`, {
+ minWidth: '0',
+ whiteSpace: 'normal',
+ overflowWrap: 'anywhere',
+ }),
+ c(`${panel} [data-dsh-mobile-settings-content]`, {
+ display: 'flex',
+ flexDirection: 'column',
+ flex: '1 1 0',
+ position: 'static',
+ boxSizing: 'border-box',
+ width: '100%',
+ minWidth: '0',
+ minHeight: '0',
+ padding: '0',
+ gap: '0',
+ border: '0',
+ }),
+ c(`${panel} [data-dsh-mobile-settings-header]`, {
+ display: 'flex',
+ flex: '0 0 auto',
+ position: 'static',
+ boxSizing: 'border-box',
+ alignItems: 'center',
+ justifyContent: 'flex-start',
+ width: '100%',
+ minWidth: '0',
+ height: 'auto',
+ minHeight: '52px',
+ padding: '52px 12px 0',
+ gap: '0',
+ }),
+ c(`${panel} [data-dsh-mobile-settings-actions]`, {
+ display: 'flex',
+ flexWrap: 'wrap',
+ position: 'static',
+ alignItems: 'center',
+ justifyContent: 'flex-start',
+ width: '100%',
+ minWidth: '0',
+ gap: '8px',
+ }),
+ c(`${panel} [data-dsh-mobile-settings-close]`, {
+ position: 'absolute',
+ top: 'calc(6px + env(safe-area-inset-top, 0px))',
+ right: 'calc(12px + env(safe-area-inset-right, 0px))',
+ zIndex: '2',
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'center',
+ width: '40px',
+ height: '40px',
+ minWidth: '40px',
+ minHeight: '40px',
+ padding: '0',
+ margin: '0',
+ touchAction: 'manipulation',
+ }),
+ c(`${panel} [data-dsh-mobile-settings-controls]`, {
+ position: 'absolute',
+ top: 'env(safe-area-inset-top, 0px)',
+ left: 'calc(12px + env(safe-area-inset-left, 0px))',
+ right: 'calc(64px + env(safe-area-inset-right, 0px))',
+ zIndex: '1',
+ display: 'grid',
+ gridTemplateColumns: '40px minmax(0, 1fr)',
+ alignItems: 'center',
+ height: '52px',
+ minWidth: '0',
+ gap: '8px',
+ }),
+ c(`${panel} [data-dsh-mobile-settings-back]`, {
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'center',
+ width: '40px',
+ height: '40px',
+ minWidth: '40px',
+ padding: '0',
+ touchAction: 'manipulation',
+ }),
+ c(`${panel} [data-dsh-mobile-settings-section-title]`, {
+ minWidth: '0',
+ overflow: 'hidden',
+ textOverflow: 'ellipsis',
+ whiteSpace: 'nowrap',
+ fontSize: '16px',
+ fontWeight: '500',
+ lineHeight: '24px',
+ color: 'var(--dsw-alias-label-primary)',
+ }),
+ c(`${panel} [data-dsh-mobile-settings-back]:focus-visible, ${panel} [data-dsh-mobile-settings-close]:focus-visible`, {
+ outline: 'var(--dsw-focus-ring-width, 2px) solid var(--dsw-focus-ring-color, var(--dsw-alias-state-business-primary))',
+ outlineOffset: '2px',
+ }),
+ c(`${panel} [data-dsh-mobile-settings-options]`, {
+ boxSizing: 'border-box',
+ flex: '1 1 0',
+ height: '0 !important',
+ width: '100%',
+ minWidth: '0',
+ minHeight: '0',
+ padding: '12px 16px 24px',
+ overflowX: 'auto',
+ overflowY: 'auto',
+ overscrollBehavior: 'contain',
+ }),
+ c(`${menu} [data-dsh-mobile-settings-content]`, {
+ flex: '0 0 auto',
+ }),
+ c(`${menu} [data-dsh-mobile-settings-header]`, {
+ minHeight: '0',
+ padding: '0 12px 12px',
+ }),
+ c(`${detail} [data-dsh-mobile-settings-nav]`, {
+ position: 'absolute',
+ inset: '0 auto auto 0',
+ flex: 'none',
+ width: '0',
+ height: '0',
+ padding: '0',
+ gap: '0',
+ }),
+ c(`${detail} [data-dsh-mobile-settings-title]`, {
+ position: 'absolute',
+ width: '1px',
+ height: '1px',
+ minHeight: '0',
+ padding: '0',
+ margin: '-1px',
+ overflow: 'hidden',
+ clipPath: 'inset(50%)',
+ whiteSpace: 'nowrap',
+ }),
+ c(`${panel} [data-dsh-mobile-settings-list][hidden], ${panel} [data-dsh-mobile-settings-options][hidden], ${panel} [data-dsh-mobile-settings-controls][hidden]`, {
+ display: 'none !important',
+ }),
+])
diff --git a/packages/dsh-tauri-mobile-ui/src/client/types/settings.ts b/packages/dsh-tauri-mobile-ui/src/client/types/settings.ts
new file mode 100644
index 00000000..877b807d
--- /dev/null
+++ b/packages/dsh-tauri-mobile-ui/src/client/types/settings.ts
@@ -0,0 +1,13 @@
+export type MobileSettingsView = 'menu' | 'detail'
+
+export interface MobileSettingsSnapshot {
+ ready: boolean
+ view: MobileSettingsView
+ title: string
+}
+
+export interface MobileSettingsPresentation {
+ getSnapshot: () => MobileSettingsSnapshot
+ subscribe: (listener: () => void) => () => void
+ back: () => void
+}
diff --git a/packages/dsh-tauri-ui/src/client/styles/index.ts b/packages/dsh-tauri-ui/src/client/styles/index.ts
index 1a068b5c..a13220e0 100644
--- a/packages/dsh-tauri-ui/src/client/styles/index.ts
+++ b/packages/dsh-tauri-ui/src/client/styles/index.ts
@@ -456,9 +456,6 @@ const TAILWINDCSS_GENERATED = `
.flex-none {
flex: none;
}
- .flex-shrink {
- flex-shrink: 1;
- }
.shrink-0 {
flex-shrink: 0;
}
@@ -1213,6 +1210,10 @@ const TAILWINDCSS_GENERATED = `
.outline-brand {
outline-color: var(--dsw-alias-brand-primary);
}
+ .blur {
+ --tw-blur: blur(8px);
+ filter: var(--tw-blur,) var(--tw-brightness,) var(--tw-contrast,) var(--tw-grayscale,) var(--tw-hue-rotate,) var(--tw-invert,) var(--tw-saturate,) var(--tw-sepia,) var(--tw-drop-shadow,);
+ }
.filter {
filter: var(--tw-blur,) var(--tw-brightness,) var(--tw-contrast,) var(--tw-grayscale,) var(--tw-hue-rotate,) var(--tw-invert,) var(--tw-saturate,) var(--tw-sepia,) var(--tw-drop-shadow,);
}
diff --git a/test/e2e/plugins/dsh-tauri-extension-panel.e2e.ts b/test/e2e/plugins/dsh-tauri-extension-panel.e2e.ts
index 9ca0346d..dc1a1c3a 100644
--- a/test/e2e/plugins/dsh-tauri-extension-panel.e2e.ts
+++ b/test/e2e/plugins/dsh-tauri-extension-panel.e2e.ts
@@ -85,4 +85,55 @@ describe('extension panel official plugins composition', () => {
await app.close()
}
})
+
+ it('keeps the embedded page head on the same axis as its icon on touch viewports', async () => {
+ const app = await newDshPage(browser, {
+ ready: '[data-dsh-hidden-panel="plugins"]',
+ viewport: { width: 399, height: 938 },
+ hasTouch: true,
+ isMobile: true,
+ })
+ try {
+ const toggle = app.frame.locator('[data-dsh-mobile-sidebar-toggle]')
+ if (await toggle.count() > 0)
+ await toggle.first().click()
+ await expect.poll(() => app.frame.locator('html[data-dsh-mobile-sidebar-open]').count()).toBe(1)
+ // 抽屉的偏移是逐帧驱动的,行本身永远不满足 playwright 的 stable 判定;这里用真实
+ // 指针点击打开抽屉,再用页内点击选中面板行,几何断言不受影响。
+ const panelRow = app.frame.getByRole('button', { name: '插件扩展', exact: true })
+ await panelRow.evaluate((el: HTMLElement) => {
+ el.click()
+ })
+ const officialPage = app.frame.locator('[data-dsh-extension-plugins] [data-plugin-panel]')
+ await officialPage.waitFor()
+ const geometry = await officialPage.evaluate((el) => {
+ const wrapper = el.closest('[data-dsh-extension-plugins]') as HTMLElement
+ const header = el.querySelector(':scope > header[data-window-drag]') as HTMLElement
+ const title = header.querySelector('h1') as HTMLElement
+ const icon = wrapper.querySelector('[data-dsh-plugins-icon]') as HTMLElement
+ const center = (node: Element): number => {
+ const rect = node.getBoundingClientRect()
+ return rect.top + rect.height / 2
+ }
+ return {
+ headerPaddingTop: getComputedStyle(header).paddingTop,
+ titleCenter: center(title),
+ iconCenter: center(icon),
+ titleLeft: title.getBoundingClientRect().left,
+ iconLeft: icon.getBoundingClientRect().left,
+ iconWidth: icon.getBoundingClientRect().width,
+ titlePaddingLeft: Number.parseFloat(getComputedStyle(title).paddingLeft),
+ }
+ })
+ expect(geometry.headerPaddingTop, '移动端页头不得叠加主槽的顶距').toBe('0px')
+ expect(Math.abs(geometry.iconCenter - geometry.titleCenter), '闪光图标必须与插件标题同轴').toBeLessThanOrEqual(1)
+ expect(geometry.iconLeft, '图标必须落在标题的左内边距内').toBeCloseTo(geometry.titleLeft, 1)
+ expect(geometry.iconWidth + 10, '图标盒加 10px 间距必须等于标题的 32px 缩进').toBeCloseTo(geometry.titlePaddingLeft, 1)
+ expectNoSyntheticFallbacks(app)
+ expect(app.errors, '移动端组合官方页面不得产生浏览器错误').toEqual([])
+ }
+ finally {
+ await app.close()
+ }
+ })
})
diff --git a/test/e2e/plugins/dsh-tauri-mobile-settings.e2e.ts b/test/e2e/plugins/dsh-tauri-mobile-settings.e2e.ts
new file mode 100644
index 00000000..a854bb80
--- /dev/null
+++ b/test/e2e/plugins/dsh-tauri-mobile-settings.e2e.ts
@@ -0,0 +1,189 @@
+import type { Browser } from 'playwright'
+import { afterAll, beforeAll, describe, expect, it } from 'vitest'
+import { expectNoSyntheticFallbacks, launchDshBrowser, newDshPage } from '../support/browser'
+
+let browser: Browser
+beforeAll(async () => {
+ browser = await launchDshBrowser()
+})
+afterAll(async () => {
+ await browser?.close()
+})
+
+const DIALOG = '[role="dialog"][aria-modal="true"][data-dsh-mobile-settings]'
+// Official current SettingsRoot uses settings.launcher; legacy puts settings.trigger inside its button.
+const LAUNCHER = '[data-slot="settings.launcher"] button[aria-haspopup="dialog"], button[aria-haspopup="dialog"]:has([data-slot="settings.trigger"])'
+
+async function openPhoneSettings(width: number, height: number) {
+ const app = await newDshPage(browser, {
+ viewport: { width, height },
+ hasTouch: true,
+ isMobile: true,
+ ready: '[data-dsh-mobile-sidebar-toggle]',
+ })
+ try {
+ const toggle = app.frame.locator('[data-dsh-mobile-sidebar-toggle]')
+ const toggleBox = (await toggle.boundingBox())!
+ expect(
+ { width: Math.round(toggleBox.width), height: Math.round(toggleBox.height) },
+ '移动侧边栏图标必须按 20px 渲染,而不是回落到字形尺寸或旧的 24px',
+ ).toEqual({ width: 20, height: 20 })
+ await toggle.click()
+ await expect.poll(() => toggle.getAttribute('aria-expanded'), { message: '真实移动入口必须展开侧栏' }).toBe('true')
+ const launcher = app.frame.locator(LAUNCHER)
+ expect(await launcher.count(), '官方设置入口必须唯一').toBe(1)
+ await launcher.click()
+ const dialog = app.frame.locator(DIALOG)
+ await expect.poll(() => dialog.getAttribute('data-dsh-mobile-settings-view'), { message: '官方入口必须先显示设置分类而非当前分区' }).toBe('menu')
+ return { app, dialog }
+ }
+ catch (error) {
+ await app.close()
+ throw error
+ }
+}
+
+describe('mobile settings official host composition', () => {
+ 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 {
+ const list = dialog.locator('[data-dsh-mobile-settings-list]')
+ const options = dialog.locator('[data-dsh-mobile-settings-options]')
+ const controls = dialog.locator('[data-dsh-mobile-settings-controls]')
+ const close = dialog.locator('[data-dsh-mobile-settings-close]')
+ const current = list.locator('button[aria-current="true"]')
+ expect(await current.count(), '原生分区选中态必须唯一').toBe(1)
+ const label = (await current.textContent())!.trim()
+ expect(label, '原生当前分区必须提供可访问标题').not.toBe('')
+ expect(await dialog.evaluate(el => document.getElementById(el.getAttribute('aria-labelledby')!)?.textContent?.trim()), '保留官方对话框可访问名称').toBe('设置')
+ expect(await options.evaluate(el => ({ hidden: el.hasAttribute('hidden'), inert: el.hasAttribute('inert') })), '分类页必须使原生详情不可聚焦').toEqual({ hidden: true, inert: true })
+ expect(await controls.isVisible(), '分类页不显示详情返回按钮').toBe(false)
+ expect(await app.page.evaluate(() => ({
+ width: document.documentElement.scrollWidth,
+ height: document.documentElement.scrollHeight,
+ x: window.scrollX,
+ y: window.scrollY,
+ })), '嵌入驱动不能产生基线空隙或父页滚动来偏移原生全屏对话框').toEqual({ width, height, x: 0, y: 0 })
+ expect(await app.page.locator('#dsh').boundingBox(), '被测 iframe 必须与手机视口原点及尺寸对齐').toEqual({ x: 0, y: 0, width, height })
+ const menuBox = await dialog.boundingBox()
+ expect(menuBox, '分类页必须有真实手机全屏几何').not.toBeNull()
+ expect(menuBox!.x).toBeCloseTo(0)
+ expect(menuBox!.y).toBeCloseTo(0)
+ expect(menuBox!.width).toBeCloseTo(width)
+ expect(menuBox!.height).toBeCloseTo(height)
+ expect((await current.boundingBox())!.height, '原生分类项必须提供至少 52px 触摸目标').toBeGreaterThanOrEqual(52)
+
+ await current.click()
+ await expect.poll(() => dialog.getAttribute('data-dsh-mobile-settings-view'), { message: '原生当前分类再次点击也必须进入详情' }).toBe('detail')
+ const back = dialog.getByRole('button', { name: '返回设置分类', exact: true })
+ expect(await list.evaluate(el => ({ hidden: el.hasAttribute('hidden'), inert: el.hasAttribute('inert') })), '详情页必须使原生分类不可聚焦').toEqual({ hidden: true, inert: true })
+ expect(await options.isVisible(), '进入详情必须显示真正的原生分区').toBe(true)
+ expect(await dialog.locator('[data-dsh-mobile-settings-section-title]').textContent(), '详情标题必须对应原生分区选中态').toBe(label)
+ const section = await dialog.locator('[data-slot="settings.section"]').elementHandle()
+ expect(section, '详情必须挂载官方 settings.section 座位').not.toBeNull()
+ const backBox = (await back.boundingBox())!
+ const closeBox = (await close.boundingBox())!
+ expect(backBox.width, '返回必须保持 40px 命中目标').toBe(40)
+ expect(closeBox.width, '官方关闭必须保持 40px 命中目标').toBe(40)
+ expect(closeBox.x, '关闭不能压在返回按钮之上').toBeGreaterThan(backBox.x + backBox.width)
+ expect((await options.boundingBox())!.y, '详情内容必须排在工具栏下方').toBeGreaterThanOrEqual(backBox.y + backBox.height)
+ const actions = dialog.locator('[data-dsh-mobile-settings-actions] button:not([data-dsh-mobile-settings-back])')
+ for (let index = 0; index < await actions.count(); index++) {
+ const action = actions.nth(index)
+ if (await action.isVisible()) {
+ expect((await action.boundingBox())!.y, '原生操作必须排在移动工具栏下方而非与返回重叠').toBeGreaterThanOrEqual(backBox.y + backBox.height)
+ }
+ }
+
+ await back.click()
+ await expect.poll(() => dialog.getAttribute('data-dsh-mobile-settings-view'), { message: '返回只改分类展示,不关闭或重建原生分区' }).toBe('menu')
+ expect(await section!.evaluate(el => el.isConnected), '返回分类必须保留同一个官方分区节点').toBe(true)
+ expect(await current.getAttribute('aria-current'), '返回不能修改原生分区选中态').toBe('true')
+ expect(await current.evaluate(el => document.activeElement === el), '返回必须把焦点交给可见原生分类').toBe(true)
+ await current.click()
+ await expect.poll(() => dialog.getAttribute('data-dsh-mobile-settings-view')).toBe('detail')
+ expect(await section!.evaluate(el => el === document.querySelector('[data-slot="settings.section"]')), '重新进入必须复用分区而非卸载重建').toBe(true)
+ await close.click()
+ await expect.poll(() => dialog.count(), { message: '官方关闭仍必须真正退出设置对话框' }).toBe(0)
+ expectNoSyntheticFallbacks(app)
+ expect(app.errors, '分类/详情切换不得产生浏览器应用错误').toEqual([])
+ }
+ finally {
+ await app.close()
+ }
+ })
+
+ it('retains an unsaved provider credential through Back and native re-selection', async () => {
+ const { app, dialog } = await openPhoneSettings(430, 943)
+ try {
+ const models = dialog.locator('[data-dsh-mobile-settings-list]').getByRole('button', { name: '模型', exact: true })
+ await models.click()
+ await expect.poll(() => dialog.getAttribute('data-dsh-mobile-settings-view')).toBe('detail')
+ await dialog.getByRole('button', { name: '添加模型提供商', exact: true }).click()
+ const catalog = dialog.locator('[data-slot="settings.section"] [id$="-catalog-panel"]')
+ expect(await catalog.count(), '添加目录编辑器必须唯一,不得误选原生 setup 编辑器').toBe(1)
+ expect(await catalog.isVisible(), '未提交凭据必须输入实际显示的添加目录编辑器').toBe(true)
+ const credential = catalog.getByLabel('API 密钥', { exact: true })
+ await credential.fill('mobile-unsaved-credential')
+ const input = await credential.elementHandle()
+ expect(input, '真实提供商编辑器必须有未提交草稿输入').not.toBeNull()
+ await dialog.getByRole('button', { name: '返回设置分类', exact: true }).click()
+ await expect.poll(() => dialog.getAttribute('data-dsh-mobile-settings-view')).toBe('menu')
+ expect(await input!.evaluate(el => ({ connected: el.isConnected, value: (el as HTMLInputElement).value })), '返回分类不得丢失未提交凭据').toEqual({ connected: true, value: 'mobile-unsaved-credential' })
+ await models.click()
+ await expect.poll(() => dialog.getAttribute('data-dsh-mobile-settings-view')).toBe('detail')
+ expect(await credential.inputValue(), '再次选择同一原生分类必须保留草稿').toBe('mobile-unsaved-credential')
+ expect(await credential.evaluate((el, original) => el === original, input!), '再次进入必须保留同一个添加编辑器输入节点').toBe(true)
+ expect(await dialog.locator('[data-dsh-mobile-settings-section-title]').textContent()).toBe('模型')
+ await app.page.keyboard.press('Escape')
+ await expect.poll(() => dialog.count(), { message: '原生 Escape 仍必须关闭完整对话框' }).toBe(0)
+ expectNoSyntheticFallbacks(app)
+ expect(app.errors, '未提交编辑器切换不得产生浏览器错误').toEqual([])
+ }
+ finally {
+ await app.close()
+ }
+ })
+
+ it('updates native and additive labels when the real locale changes', async () => {
+ const { app, dialog } = await openPhoneSettings(430, 943)
+ const current = dialog.locator('[data-dsh-mobile-settings-list] button[aria-current="true"]')
+ const language = dialog.locator('[data-slot="settings.general.item"]')
+ const menu = app.frame.getByRole('menu')
+ try {
+ await current.click()
+ await expect.poll(() => dialog.getAttribute('data-dsh-mobile-settings-view')).toBe('detail')
+ await language.getByRole('button', { name: '中文', exact: true }).click()
+ await menu.getByRole('menuitem', { name: 'English', exact: true }).click()
+ await expect.poll(() => dialog.getByRole('button', { name: 'Back to settings categories', exact: true }).count(), { message: '真实 locale 变更必须更新附加返回按钮' }).toBe(1)
+ await expect.poll(() => dialog.locator('[data-dsh-mobile-settings-section-title]').textContent(), { message: '标题必须跟随原生 locale 分区名' }).toBe('General')
+ expect(await dialog.evaluate(el => document.getElementById(el.getAttribute('aria-labelledby')!)?.textContent?.trim()), '原生对话框名称也必须切换语言').toBe('Settings')
+ await dialog.getByRole('button', { name: 'Back to settings categories', exact: true }).click()
+ await expect.poll(() => dialog.getAttribute('data-dsh-mobile-settings-view')).toBe('menu')
+ expect(await current.textContent(), '原生分类不能留下旧语言副本').toBe('General')
+ expectNoSyntheticFallbacks(app)
+ expect(app.errors, '真实 locale 切换不得产生浏览器错误').toEqual([])
+ }
+ finally {
+ try {
+ if (await menu.isVisible())
+ await app.page.keyboard.press('Escape')
+ if (await dialog.getAttribute('data-dsh-mobile-settings-view') === 'menu') {
+ await current.click()
+ await expect.poll(() => dialog.getAttribute('data-dsh-mobile-settings-view')).toBe('detail')
+ }
+ await language.getByRole('button', { name: /^(?:中文|English)$/ }).click()
+ await menu.getByRole('menuitem', { name: '中文', exact: true }).click()
+ await expect.poll(() => language.getByRole('button', { name: '中文', exact: true }).count(), { message: '共享宿主语言偏好必须原生恢复,不能污染后续 shuffle 用例' }).toBe(1)
+ await expect.poll(() => dialog.evaluate(el => document.getElementById(el.getAttribute('aria-labelledby')!)?.textContent?.trim())).toBe('设置')
+ await dialog.locator('[data-dsh-mobile-settings-close]').click()
+ await expect.poll(() => dialog.count()).toBe(0)
+ expectNoSyntheticFallbacks(app)
+ expect(app.errors, '恢复共享语言偏好不得产生浏览器错误').toEqual([])
+ }
+ finally {
+ await app.close()
+ }
+ }
+ })
+})
diff --git a/test/e2e/support/browser.ts b/test/e2e/support/browser.ts
index 9d604ed1..df66baf1 100644
--- a/test/e2e/support/browser.ts
+++ b/test/e2e/support/browser.ts
@@ -92,6 +92,9 @@ export interface NewDshPageOptions {
ready?: string
path?: string
dismissModals?: boolean
+ viewport?: { width: number, height: number }
+ hasTouch?: boolean
+ isMobile?: boolean
}
/** 断言本轮没有任何合成事件兜底:真实指针点击必须自己点得通。 */
@@ -115,8 +118,8 @@ export function launchDshBrowser(): Promise<Browser> {
return chromium.launch()
}
-export function newDshContext(browser: Browser): Promise<BrowserContext> {
- return browser.newContext({ viewport: APP_FRAME_VIEWPORT, locale: APP_LOCALE })
+export function newDshContext(browser: Browser, options: Pick<NewDshPageOptions, 'viewport' | 'hasTouch' | 'isMobile'> = {}): Promise<BrowserContext> {
+ return browser.newContext({ viewport: options.viewport ?? APP_FRAME_VIEWPORT, hasTouch: options.hasTouch, isMobile: options.isMobile, locale: APP_LOCALE })
}
export async function addSessionCookie(context: BrowserContext): Promise<void> {
@@ -124,10 +127,10 @@ export async function addSessionCookie(context: BrowserContext): Promise<void> {
await context.addCookies([{ name, value: rest.join('='), url: inject('dshBaseUrl') }])
}
-async function installEmbedRoute(page: Page): Promise<void> {
+async function installEmbedRoute(page: Page, viewport: { width: number, height: number }): Promise<void> {
const embedUrl = `${inject('dshBaseUrl')}${EMBEDDED_DOCUMENT_PATH}`
- const htmlContent = `<!doctype html><html><body style="margin:0;overflow:hidden">`
- + `<iframe id="dsh" src="/" style="width:${APP_FRAME_VIEWPORT.width}px;height:${APP_FRAME_VIEWPORT.height}px;border:0"></iframe>`
+ const htmlContent = `<!doctype html><html><head><meta name="viewport" content="width=device-width, initial-scale=1"></head><body style="margin:0;overflow:hidden">`
+ + `<iframe id="dsh" src="/" style="display:block;width:${viewport.width}px;height:${viewport.height}px;border:0"></iframe>`
+ '</body></html>'
await page.route(embedUrl, route =>
@@ -356,7 +359,7 @@ export async function newDshPage(
browser: Browser,
options: NewDshPageOptions = {},
): Promise<DshPage> {
- const context = await newDshContext(browser)
+ const context = await newDshContext(browser, options)
await addSessionCookie(context)
const page = await context.newPage()
@@ -365,7 +368,7 @@ export async function newDshPage(
const isEmbedded = options.path === undefined
if (isEmbedded) {
- await installEmbedRoute(page)
+ await installEmbedRoute(page, options.viewport ?? APP_FRAME_VIEWPORT)
}
await page.goto(appUrl(options.path ?? EMBEDDED_DOCUMENT_PATH))