Skip to content

Commit

Permalink
fix: input element focus shortcut key (BewlyBewly#564)
Browse files Browse the repository at this point in the history
* fix: input element focus shortcut key

* chore: add reference
  • Loading branch information
starknt authored Apr 14, 2024
1 parent 225188b commit 6cacb9f
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 9 deletions.
23 changes: 14 additions & 9 deletions src/components/SearchBar/SearchBar.vue
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import {
removeSearchHistory,
} from './searchHistoryProvider'
import API from '~/background/msg.define'
import { findLeafActiveElement } from '~/utils/element'

defineProps<{
darkenOnFocus?: boolean
Expand All @@ -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()
Expand Down
16 changes: 16 additions & 0 deletions src/utils/element.ts
Original file line number Diff line number Diff line change
@@ -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
}

0 comments on commit 6cacb9f

Please sign in to comment.