fix: input element focus shortcut key (#564)

* fix: input element focus shortcut key

* chore: add reference
This commit is contained in:
star knight
2024-04-14 22:40:04 +08:00
committed by hakadao
parent d0cd138b7a
commit 2e87cac719
2 changed files with 30 additions and 9 deletions

View File

@@ -9,6 +9,7 @@ import {
removeSearchHistory,
} from './searchHistoryProvider'
import API from '~/background/msg.define'
import { findLeafActiveElement } from '~/utils/element'
defineProps<{
darkenOnFocus?: boolean
@@ -32,16 +33,20 @@ watch(isFocus, async (focus) => {
})
onKeyStroke('/', (e: KeyboardEvent) => {
if (e.target) {
if ((e.target as HTMLElement).tagName !== 'INPUT'
&& (e.target as HTMLElement).tagName !== 'TEXTAREA'
&& !(e.target as HTMLElement).className.includes('textarea')
&& !(e.target as HTMLElement).className.includes('input')
) {
e.preventDefault()
keywordRef.value?.focus()
}
// Reference: https://github.com/polywock/globalSpeed/blob/3705ac836402b324550caf92aa65075b2f2347c6/src/contentScript/ConfigSync.ts#L94
const target = e.target as HTMLElement
const ignoreTagNames = ['INPUT', 'TEXTAREA']
if (target && (ignoreTagNames.includes(target.tagName) || target.isContentEditable))
return
const activeElement = findLeafActiveElement(document) as HTMLElement | undefined
if (activeElement && target !== activeElement) {
if (ignoreTagNames.includes(activeElement.tagName) || activeElement.isContentEditable)
return
}
e.preventDefault()
keywordRef.value?.focus()
})
onKeyStroke('Escape', (e: KeyboardEvent) => {
e.preventDefault()

16
src/utils/element.ts Normal file
View File

@@ -0,0 +1,16 @@
export function getShadowRoot(v: Element) {
if (v.shadowRoot)
return v.shadowRoot
}
export function findLeafActiveElement(doc: DocumentOrShadowRoot): Element | undefined {
const active = doc?.activeElement
if (!active)
return
const shadowRoot = getShadowRoot(active)
if (shadowRoot && shadowRoot.activeElement)
return findLeafActiveElement(shadowRoot)
return active
}