2020-09-09 21:18:08 +08:00
|
|
|
import { isRef, watch } from 'vue'
|
|
|
|
import type { Ref } from 'vue'
|
|
|
|
|
|
|
|
/**
|
|
|
|
* This method provides dialogable components the ability to restore previously activated element before
|
|
|
|
* the dialog gets opened
|
|
|
|
*/
|
2021-11-29 15:58:44 +08:00
|
|
|
export const useRestoreActive = (
|
|
|
|
toggle: Ref<boolean>,
|
|
|
|
initialFocus?: Ref<HTMLElement>
|
|
|
|
) => {
|
2020-09-09 21:18:08 +08:00
|
|
|
let previousActive: HTMLElement
|
2021-09-04 19:29:28 +08:00
|
|
|
watch(
|
|
|
|
() => toggle.value,
|
|
|
|
(val) => {
|
|
|
|
if (val) {
|
|
|
|
previousActive = document.activeElement as HTMLElement
|
|
|
|
if (isRef(initialFocus)) {
|
|
|
|
initialFocus.value.focus?.()
|
|
|
|
}
|
2020-09-09 21:18:08 +08:00
|
|
|
} else {
|
2021-09-04 19:29:28 +08:00
|
|
|
if (process.env.NODE_ENV === 'testing') {
|
|
|
|
previousActive.focus.call(previousActive)
|
|
|
|
} else {
|
|
|
|
previousActive.focus()
|
|
|
|
}
|
2020-09-09 21:18:08 +08:00
|
|
|
}
|
|
|
|
}
|
2021-09-04 19:29:28 +08:00
|
|
|
)
|
2020-09-09 21:18:08 +08:00
|
|
|
}
|