Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(useFocus): listen focus and blur to the targetElement #2631

Merged
merged 7 commits into from
Jan 29, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
19 changes: 10 additions & 9 deletions packages/core/useFocus/index.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,9 @@
import type { Ref } from 'vue-demi'
import { computed, watch } from 'vue-demi'
import { isDef } from '@vueuse/shared'
import { computed, ref, watch } from 'vue-demi'
import type { MaybeElementRef } from '../unrefElement'
import { unrefElement } from '../unrefElement'
import { useActiveElement } from '../useActiveElement'
import type { ConfigurableWindow } from '../_configurable'
import { useEventListener } from '../useEventListener'

export interface UseFocusOptions extends ConfigurableWindow {
/**
Expand Down Expand Up @@ -33,16 +32,18 @@ export interface UseFocusReturn {
export function useFocus(target: MaybeElementRef, options: UseFocusOptions = {}): UseFocusReturn {
const { initialValue = false } = options

const activeElement = useActiveElement(options)
const innerFocused = ref(false)
const targetElement = computed(() => unrefElement(target))

useEventListener(targetElement, 'focus', () => innerFocused.value = true)
useEventListener(targetElement, 'blur', () => innerFocused.value = false)

const focused = computed({
get() {
return isDef(activeElement.value) && isDef(targetElement.value) && activeElement.value === targetElement.value
},
get: () => innerFocused.value,
set(value: boolean) {
if (!value && focused.value)
if (!value && innerFocused.value)
targetElement.value?.blur()
if (value && !focused.value)
else if (value && !innerFocused.value)
targetElement.value?.focus()
},
})
Expand Down