Skip to content

armgit / dify

Public Imported from GitHub
0

Build Agentic workflows, RAG pipelines, with rich AI model and tool support on one collaborative workspace. Deploy on cloud, VPC, or self-hosted, so teams move from prototype to production without rebuilding the stack.

fix(web): focus auth fields on arrival and keep auth switches keyboard reachable (#45640)

yyhe1bca6369bdd
diff --git a/oxlint-suppressions.json b/oxlint-suppressions.json
index 51f33bc99e1..f73faf1104d 100644
--- a/oxlint-suppressions.json
+++ b/oxlint-suppressions.json
@@ -42,17 +42,9 @@
"count": 1
}
},
- "web/app/(auth)/device/components/code-input.tsx": {
- "jsx-a11y/no-autofocus": {
- "count": 1
- }
- },
"web/app/(auth)/device/page.tsx": {
"dify/require-disable-directive-description": {
"count": 5
- },
- "jsx-a11y/no-autofocus": {
- "count": 1
}
},
"web/app/(auth)/signin/normal-form.tsx": {
@@ -85,24 +77,11 @@
"count": 1
}
},
- "web/app/(shareLayout)/webapp-reset-password/check-code/page.tsx": {
- "better-tailwindcss/enforce-logical-properties": {
- "count": 1
- }
- },
"web/app/(shareLayout)/webapp-reset-password/page.tsx": {
"better-tailwindcss/enforce-logical-properties": {
"count": 1
}
},
- "web/app/(shareLayout)/webapp-signin/normalForm.tsx": {
- "jsx-a11y/click-events-have-key-events": {
- "count": 2
- },
- "jsx-a11y/no-static-element-interactions": {
- "count": 2
- }
- },
"web/app/__tests__/home-banner.browser.spec.tsx": {
"typescript/no-deprecated": {
"count": 4
diff --git a/web/app/(auth)/device/components/__tests__/code-input.browser.spec.tsx b/web/app/(auth)/device/components/__tests__/code-input.browser.spec.tsx
new file mode 100644
index 00000000000..d793bc9678a
--- /dev/null
+++ b/web/app/(auth)/device/components/__tests__/code-input.browser.spec.tsx
@@ -0,0 +1,8 @@
+import { render } from 'vitest-browser-react'
+import CodeInput from '../code-input'
+
+it('puts the cursor in the device code field on arrival', async () => {
+ const screen = await render(<CodeInput value="" onChange={() => {}} />)
+
+ await expect.element(screen.getByRole('textbox')).toHaveFocus()
+})
diff --git a/web/app/(auth)/device/components/code-input.tsx b/web/app/(auth)/device/components/code-input.tsx
index b2395f3cbdf..4bc0e9f37c1 100644
--- a/web/app/(auth)/device/components/code-input.tsx
+++ b/web/app/(auth)/device/components/code-input.tsx
@@ -3,13 +3,13 @@
import type { FC } from 'react'
import { useCallback } from 'react'
import { useTranslation } from 'react-i18next'
+import { focusOnArrival } from '@/app/components/auth-shell/focus-on-arrival'
import { normaliseUserCodeInput } from '../utils/user-code'
type Props = {
value: string
onChange: (normalised: string) => void
disabled?: boolean
- autoFocus?: boolean
}
/**
@@ -19,7 +19,7 @@ type Props = {
* The onChange callback receives the normalised value only — the parent does
* not need to run validation itself.
*/
-const CodeInput: FC<Props> = ({ value, onChange, disabled, autoFocus }) => {
+const CodeInput: FC<Props> = ({ value, onChange, disabled }) => {
const { t } = useTranslation(['deviceFlow'])
const handle = useCallback(
(raw: string) => {
@@ -41,7 +41,7 @@ const CodeInput: FC<Props> = ({ value, onChange, disabled, autoFocus }) => {
className="border-components-input-border-normal w-full rounded-lg border bg-components-input-bg-normal px-4 py-3 text-center font-mono text-2xl tracking-wider text-text-primary focus:border-components-input-border-active focus:outline-none"
value={value}
disabled={disabled}
- autoFocus={autoFocus}
+ ref={focusOnArrival}
onChange={(e) => handle(e.target.value)}
/>
)
diff --git a/web/app/(auth)/device/page.tsx b/web/app/(auth)/device/page.tsx
index 15e7d25454d..abf6a7649e9 100644
--- a/web/app/(auth)/device/page.tsx
+++ b/web/app/(auth)/device/page.tsx
@@ -149,7 +149,7 @@ export default function DevicePage() {
</h1>
<p className="mt-2 text-sm text-text-secondary">{t(($) => $['codeEntry.subtitle'])}</p>
</div>
- <CodeInput value={typed} onChange={setTyped} autoFocus />
+ <CodeInput value={typed} onChange={setTyped} />
<Button
variant="primary"
size="large"
diff --git a/web/app/(auth)/init/InitPasswordPopup.tsx b/web/app/(auth)/init/InitPasswordPopup.tsx
index fe8bd483854..4927f4fd39e 100644
--- a/web/app/(auth)/init/InitPasswordPopup.tsx
+++ b/web/app/(auth)/init/InitPasswordPopup.tsx
@@ -7,6 +7,7 @@ import { ORPCError } from '@orpc/client'
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import { useEffect, useMemo } from 'react'
import { useTranslation } from 'react-i18next'
+import { focusOnArrival } from '@/app/components/auth-shell/focus-on-arrival'
import useDocumentTitle from '@/hooks/use-document-title'
import { useRouter } from '@/next/navigation'
import { consoleQuery } from '@/service/console'
@@ -71,6 +72,7 @@ const InitPasswordPopup = () => {
>
<FieldLabel>{pageTitle}</FieldLabel>
<Input
+ ref={focusOnArrival}
type="password"
autoComplete="off"
onValueChange={() => {
diff --git a/web/app/(auth)/init/__tests__/InitPasswordPopup.browser.spec.tsx b/web/app/(auth)/init/__tests__/InitPasswordPopup.browser.spec.tsx
index 6f6e4fded3e..51e3daacce6 100644
--- a/web/app/(auth)/init/__tests__/InitPasswordPopup.browser.spec.tsx
+++ b/web/app/(auth)/init/__tests__/InitPasswordPopup.browser.spec.tsx
@@ -41,6 +41,12 @@ beforeEach(() => {
getInitStatus.mockReset().mockResolvedValue({ status: 'not_started' })
})
+it('puts the cursor in the password field on arrival', async () => {
+ const screen = await renderPopup()
+
+ await expect.element(screen.getByLabelText('login.adminInitPassword')).toHaveFocus()
+})
+
it('asks for the password before submitting', async () => {
const screen = await renderPopup()
diff --git a/web/app/(auth)/reset-password/check-code/page.tsx b/web/app/(auth)/reset-password/check-code/page.tsx
index 4599ad61b2d..c2aa7e7efca 100644
--- a/web/app/(auth)/reset-password/check-code/page.tsx
+++ b/web/app/(auth)/reset-password/check-code/page.tsx
@@ -6,6 +6,7 @@ import { Input } from '@langgenius/dify-ui/input'
import { useState } from 'react'
import { useTranslation } from 'react-i18next'
import { useLocale } from '#i18n'
+import { focusOnArrival } from '@/app/components/auth-shell/focus-on-arrival'
import Countdown from '@/app/components/signin/countdown'
import { toast } from '@/app/notifications'
import useDocumentTitle from '@/hooks/use-document-title'
@@ -82,6 +83,7 @@ export default function CheckCode() {
<Field name="code">
<FieldLabel>{t(($) => $['checkCode.verificationCode'], { ns: 'login' })}</FieldLabel>
<Input
+ ref={focusOnArrival}
inputMode="numeric"
autoComplete="one-time-code"
spellCheck={false}
diff --git a/web/app/(auth)/signin/check-code/page.tsx b/web/app/(auth)/signin/check-code/page.tsx
index 2dd8369ebbf..4ba7114d82e 100644
--- a/web/app/(auth)/signin/check-code/page.tsx
+++ b/web/app/(auth)/signin/check-code/page.tsx
@@ -4,9 +4,10 @@ import { Field, FieldError, FieldLabel } from '@langgenius/dify-ui/field'
import { Form } from '@langgenius/dify-ui/form'
import { Input } from '@langgenius/dify-ui/input'
import { useQueryClient, useSuspenseQuery } from '@tanstack/react-query'
-import { useEffect, useRef, useState } from 'react'
+import { useState } from 'react'
import { useTranslation } from 'react-i18next'
import { useLocale } from '#i18n'
+import { focusOnArrival } from '@/app/components/auth-shell/focus-on-arrival'
import { trackEvent } from '@/app/components/base/amplitude'
import Countdown from '@/app/components/signin/countdown'
import { COUNT_DOWN_TIME_MS, useSetCountdownLeftTime } from '@/app/components/signin/storage'
@@ -45,7 +46,6 @@ export default function CheckCode() {
const [countdownGeneration, setCountdownGeneration] = useState(0)
const locale = useLocale()
const setCountdownLeftTime = useSetCountdownLeftTime()
- const codeInputRef = useRef<HTMLInputElement>(null)
const turnstileSiteKey = TURNSTILE_SITE_KEY.trim()
const isTurnstileRequired = systemFeatures.deployment_edition === 'CLOUD'
const shouldRenderTurnstile = isTurnstileRequired && Boolean(turnstileSiteKey)
@@ -98,10 +98,6 @@ export default function CheckCode() {
}
}
- useEffect(() => {
- codeInputRef.current?.focus()
- }, [])
-
const resendCode = async (turnstileToken?: string) => {
setIsResending(true)
try {
@@ -162,7 +158,7 @@ export default function CheckCode() {
<Field name="code">
<FieldLabel>{t(($) => $['checkCode.verificationCode'], { ns: 'login' })}</FieldLabel>
<Input
- ref={codeInputRef}
+ ref={focusOnArrival}
inputMode="numeric"
autoComplete="one-time-code"
spellCheck={false}
diff --git a/web/app/(auth)/signin/components/turnstile.tsx b/web/app/(auth)/signin/components/turnstile.tsx
index efb08650b8b..6cb2f6fe5a8 100644
--- a/web/app/(auth)/signin/components/turnstile.tsx
+++ b/web/app/(auth)/signin/components/turnstile.tsx
@@ -141,17 +141,19 @@ export default function Turnstile({
return (
<>
- {hasError && (
- <Alert type="error" className="mt-3 w-full">
- <AlertTitle>{t(($) => $['turnstile.loadError'], { ns: 'login' })}</AlertTitle>
- <AlertActions>
- <Button type="button" size="small" onClick={handleRetry}>
- {t(($) => $['operation.retry'], { ns: 'common' })}
- </Button>
- </AlertActions>
- </Alert>
- )}
- <div ref={containerRef} className={`mt-3 h-16.25 w-full ${hasError ? 'hidden' : ''}`} />
+ <div className="mt-3 grid min-h-18.25 items-center">
+ {hasError && (
+ <Alert type="error" className="w-full">
+ <AlertTitle>{t(($) => $['turnstile.loadError'], { ns: 'login' })}</AlertTitle>
+ <AlertActions>
+ <Button type="button" size="small" onClick={handleRetry}>
+ {t(($) => $['operation.retry'], { ns: 'common' })}
+ </Button>
+ </AlertActions>
+ </Alert>
+ )}
+ <div ref={containerRef} className={`h-16.25 w-full ${hasError ? 'hidden' : ''}`} />
+ </div>
<Script
key={scriptGeneration}
id={scriptId}
diff --git a/web/app/(auth)/signin/normal-form.tsx b/web/app/(auth)/signin/normal-form.tsx
index ac6462118b7..4f54a6a9e85 100644
--- a/web/app/(auth)/signin/normal-form.tsx
+++ b/web/app/(auth)/signin/normal-form.tsx
@@ -221,44 +221,28 @@ function NormalForm() {
)}
{hasEmailLogin && (
<>
- {hasEmailCodeLogin && authType === 'code' && (
- <>
- <MailAndCodeAuth isInvite={isInviteLink} />
- {hasEmailPasswordLogin && (
- <button
- type="button"
- className="w-full cursor-pointer py-1 text-center"
- onClick={() => {
- setSelectedAuthType('password')
- }}
- >
- <span className="system-xs-medium text-components-button-secondary-accent-text">
- {t(($) => $.usePassword, { ns: 'login' })}
- </span>
- </button>
- )}
- </>
+ {authType === 'code' ? (
+ <MailAndCodeAuth isInvite={isInviteLink} />
+ ) : (
+ <MailAndPasswordAuth
+ isInvite={isInviteLink}
+ isEmailSetup={systemFeatures.is_email_setup}
+ />
)}
- {hasEmailPasswordLogin && authType === 'password' && (
- <>
- <MailAndPasswordAuth
- isInvite={isInviteLink}
- isEmailSetup={systemFeatures.is_email_setup}
- />
- {hasEmailCodeLogin && (
- <button
- type="button"
- className="w-full cursor-pointer py-1 text-center"
- onClick={() => {
- setSelectedAuthType('code')
- }}
- >
- <span className="system-xs-medium text-components-button-secondary-accent-text">
- {t(($) => $.useVerificationCode, { ns: 'login' })}
- </span>
- </button>
- )}
- </>
+ {hasEmailCodeLogin && hasEmailPasswordLogin && (
+ <button
+ type="button"
+ className="w-full cursor-pointer py-1 text-center"
+ onClick={() => {
+ setSelectedAuthType(authType === 'code' ? 'password' : 'code')
+ }}
+ >
+ <span className="system-xs-medium text-components-button-secondary-accent-text">
+ {authType === 'code'
+ ? t(($) => $.usePassword, { ns: 'login' })
+ : t(($) => $.useVerificationCode, { ns: 'login' })}
+ </span>
+ </button>
)}
<Split className="mt-4 mb-5" />
</>
diff --git a/web/app/(auth)/signup/check-code/page.tsx b/web/app/(auth)/signup/check-code/page.tsx
index c2c5d19621b..cf944e84358 100644
--- a/web/app/(auth)/signup/check-code/page.tsx
+++ b/web/app/(auth)/signup/check-code/page.tsx
@@ -7,6 +7,7 @@ import { useMutation } from '@tanstack/react-query'
import { useState } from 'react'
import { useTranslation } from 'react-i18next'
import { useLocale } from '#i18n'
+import { focusOnArrival } from '@/app/components/auth-shell/focus-on-arrival'
import Countdown from '@/app/components/signin/countdown'
import { toast } from '@/app/notifications'
import useDocumentTitle from '@/hooks/use-document-title'
@@ -96,6 +97,7 @@ export default function CheckCode() {
<Field name="code">
<FieldLabel>{t(($) => $['checkCode.verificationCode'], { ns: 'login' })}</FieldLabel>
<Input
+ ref={focusOnArrival}
maxLength={6}
inputMode="numeric"
autoComplete="one-time-code"
diff --git a/web/app/(shareLayout)/webapp-reset-password/check-code/page.tsx b/web/app/(shareLayout)/webapp-reset-password/check-code/page.tsx
index 6a952563ee2..9a406a0c110 100644
--- a/web/app/(shareLayout)/webapp-reset-password/check-code/page.tsx
+++ b/web/app/(shareLayout)/webapp-reset-password/check-code/page.tsx
@@ -5,6 +5,7 @@ import { RiArrowLeftLine, RiMailSendFill } from '@remixicon/react'
import { useState } from 'react'
import { useTranslation } from 'react-i18next'
import { useLocale } from '#i18n'
+import { focusOnArrival } from '@/app/components/auth-shell/focus-on-arrival'
import Countdown from '@/app/components/signin/countdown'
import { toast } from '@/app/notifications'
import useDocumentTitle from '@/hooks/use-document-title'
@@ -83,6 +84,7 @@ export default function CheckCode() {
{t(($) => $['checkCode.verificationCode'], { ns: 'login' })}
</label>
<Input
+ ref={focusOnArrival}
id="code"
name="code"
inputMode="numeric"
@@ -110,7 +112,7 @@ export default function CheckCode() {
<span className="inline-block rounded-full p-1">
<RiArrowLeftLine aria-hidden size={12} />
</span>
- <span className="ml-2 system-xs-regular">{t(($) => $.back, { ns: 'login' })}</span>
+ <span className="ms-2 system-xs-regular">{t(($) => $.back, { ns: 'login' })}</span>
</button>
</div>
)
diff --git a/web/app/(shareLayout)/webapp-signin/__tests__/normal-form.browser.spec.tsx b/web/app/(shareLayout)/webapp-signin/__tests__/normal-form.browser.spec.tsx
new file mode 100644
index 00000000000..74757adbac1
--- /dev/null
+++ b/web/app/(shareLayout)/webapp-signin/__tests__/normal-form.browser.spec.tsx
@@ -0,0 +1,45 @@
+import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
+import { userEvent } from 'vite-plus/test/browser'
+import { render } from 'vitest-browser-react'
+import NormalForm from '../normalForm'
+
+vi.mock('@/features/system-features/client', () => ({
+ systemFeaturesQueryOptions: () => ({
+ queryKey: ['system-features'],
+ queryFn: () => ({
+ deployment_edition: 'CLOUD',
+ sso_enforced_for_signin: false,
+ sso_enforced_for_signin_protocol: null,
+ enable_social_oauth_login: false,
+ enable_email_code_login: true,
+ enable_email_password_login: true,
+ is_email_setup: true,
+ branding: { enabled: true },
+ license: { status: 'active' },
+ }),
+ }),
+}))
+vi.mock('../components/mail-and-code-auth', () => ({ default: () => <p>code form</p> }))
+vi.mock('../components/mail-and-password-auth', () => ({ default: () => <p>password form</p> }))
+vi.mock('../components/sso-auth', () => ({ default: () => null }))
+
+it('switches between password and verification code from the keyboard without losing focus', async () => {
+ const screen = await render(
+ <QueryClientProvider client={new QueryClient()}>
+ <NormalForm />
+ </QueryClientProvider>,
+ )
+
+ await expect.element(screen.getByText('password form')).toBeVisible()
+
+ await userEvent.tab()
+ await expect
+ .element(screen.getByRole('button', { name: 'login.useVerificationCode' }))
+ .toHaveFocus()
+ await userEvent.keyboard('{Enter}')
+ await expect.element(screen.getByText('code form')).toBeVisible()
+
+ await expect.element(screen.getByRole('button', { name: 'login.usePassword' })).toHaveFocus()
+ await userEvent.keyboard('{Enter}')
+ await expect.element(screen.getByText('password form')).toBeVisible()
+})
diff --git a/web/app/(shareLayout)/webapp-signin/check-code/page.tsx b/web/app/(shareLayout)/webapp-signin/check-code/page.tsx
index dbb25cd43ce..ef466e660e0 100644
--- a/web/app/(shareLayout)/webapp-signin/check-code/page.tsx
+++ b/web/app/(shareLayout)/webapp-signin/check-code/page.tsx
@@ -2,13 +2,14 @@
import type { SubmitEvent } from 'react'
import { Button } from '@langgenius/dify-ui/button'
import { Input } from '@langgenius/dify-ui/input'
-import { useEffect, useRef, useState } from 'react'
+import { useEffect, useState } from 'react'
import { useTranslation } from 'react-i18next'
import { useLocale } from '#i18n'
import {
navigateAfterWebAppLogin,
resolveWebAppLoginRedirect,
} from '@/app/(shareLayout)/webapp-signin/login-redirect'
+import { focusOnArrival } from '@/app/components/auth-shell/focus-on-arrival'
import Countdown from '@/app/components/signin/countdown'
import { toast } from '@/app/notifications'
import { useWebAppStore } from '@/context/web-app-context'
@@ -30,7 +31,6 @@ export default function CheckCode() {
const [code, setCode] = useState('')
const [loading, setLoading] = useState(false)
const locale = useLocale()
- const codeInputRef = useRef<HTMLInputElement>(null)
const redirectUrl = searchParams.get('redirect_url')
const embeddedUserId = useWebAppStore((s) => s.embeddedUserId)
@@ -83,10 +83,6 @@ export default function CheckCode() {
verify()
}
- useEffect(() => {
- codeInputRef.current?.focus()
- }, [])
-
const resendCode = async () => {
const loginRedirect = resolveWebAppLoginRedirect(redirectUrl, window.location.origin)
if (!loginRedirect) {
@@ -133,7 +129,7 @@ export default function CheckCode() {
{t(($) => $['checkCode.verificationCode'], { ns: 'login' })}
</label>
<Input
- ref={codeInputRef}
+ ref={focusOnArrival}
id="code"
name="code"
inputMode="numeric"
diff --git a/web/app/(shareLayout)/webapp-signin/normalForm.tsx b/web/app/(shareLayout)/webapp-signin/normalForm.tsx
index cf85fbe3684..eec73791229 100644
--- a/web/app/(shareLayout)/webapp-signin/normalForm.tsx
+++ b/web/app/(shareLayout)/webapp-signin/normalForm.tsx
@@ -125,40 +125,27 @@ const NormalForm = () => {
)}
{hasEmailLogin && (
<>
- {systemFeatures.enable_email_code_login && authType === 'code' && (
- <>
- <MailAndCodeAuth />
- {systemFeatures.enable_email_password_login && (
- <div
- className="cursor-pointer py-1 text-center"
- onClick={() => {
- updateAuthType('password')
- }}
- >
- <span className="system-xs-medium text-components-button-secondary-accent-text">
- {t(($) => $.usePassword, { ns: 'login' })}
- </span>
- </div>
- )}
- </>
- )}
- {systemFeatures.enable_email_password_login && authType === 'password' && (
- <>
- <MailAndPasswordAuth isEmailSetup={systemFeatures.is_email_setup} />
- {systemFeatures.enable_email_code_login && (
- <div
- className="cursor-pointer py-1 text-center"
- onClick={() => {
- updateAuthType('code')
- }}
- >
- <span className="system-xs-medium text-components-button-secondary-accent-text">
- {t(($) => $.useVerificationCode, { ns: 'login' })}
- </span>
- </div>
- )}
- </>
+ {authType === 'code' ? (
+ <MailAndCodeAuth />
+ ) : (
+ <MailAndPasswordAuth isEmailSetup={systemFeatures.is_email_setup} />
)}
+ {systemFeatures.enable_email_code_login &&
+ systemFeatures.enable_email_password_login && (
+ <button
+ type="button"
+ className="w-full cursor-pointer py-1 text-center"
+ onClick={() => {
+ updateAuthType(authType === 'code' ? 'password' : 'code')
+ }}
+ >
+ <span className="system-xs-medium text-components-button-secondary-accent-text">
+ {authType === 'code'
+ ? t(($) => $.usePassword, { ns: 'login' })
+ : t(($) => $.useVerificationCode, { ns: 'login' })}
+ </span>
+ </button>
+ )}
</>
)}
{allMethodsAreDisabled && (
diff --git a/web/app/components/auth-shell/__tests__/focus-on-arrival.spec.ts b/web/app/components/auth-shell/__tests__/focus-on-arrival.spec.ts
new file mode 100644
index 00000000000..cabca53ef75
--- /dev/null
+++ b/web/app/components/auth-shell/__tests__/focus-on-arrival.spec.ts
@@ -0,0 +1,49 @@
+import { focusOnArrival } from '../focus-on-arrival'
+
+const setCoarsePointer = (coarse: boolean) => {
+ vi.spyOn(window, 'matchMedia').mockImplementation(
+ (query) =>
+ ({ matches: coarse && query === '(pointer: coarse)', media: query }) as MediaQueryList,
+ )
+}
+
+const mountInput = () => {
+ const input = document.createElement('input')
+ document.body.append(input)
+ return input
+}
+
+afterEach(() => {
+ vi.restoreAllMocks()
+ document.body.replaceChildren()
+})
+
+it('focuses the field when nothing else has focus', () => {
+ setCoarsePointer(false)
+ const input = mountInput()
+
+ focusOnArrival(input)
+
+ expect(document.activeElement).toBe(input)
+})
+
+it('leaves focus where the user already moved it', () => {
+ setCoarsePointer(false)
+ const button = document.createElement('button')
+ document.body.append(button)
+ button.focus()
+ const input = mountInput()
+
+ focusOnArrival(input)
+
+ expect(document.activeElement).toBe(button)
+})
+
+it('does not open the on-screen keyboard on touch devices', () => {
+ setCoarsePointer(true)
+ const input = mountInput()
+
+ focusOnArrival(input)
+
+ expect(document.activeElement).not.toBe(input)
+})
diff --git a/web/app/components/auth-shell/focus-on-arrival.ts b/web/app/components/auth-shell/focus-on-arrival.ts
new file mode 100644
index 00000000000..72bd444577b
--- /dev/null
+++ b/web/app/components/auth-shell/focus-on-arrival.ts
@@ -0,0 +1,10 @@
+export function focusOnArrival(element: HTMLElement | null) {
+ if (!element) return
+
+ const doc = element.ownerDocument
+ const focused = doc.activeElement
+ if (focused && focused !== doc.body) return
+ if (doc.defaultView?.matchMedia?.('(pointer: coarse)').matches) return
+
+ element.focus()
+}