Skip to content

Commit

Permalink
Merge pull request #367 from 1CRM/keep-focuse-inside-popup-#1964
Browse files Browse the repository at this point in the history
Keep focus inside popup #1964
  • Loading branch information
alexivanenko authored Feb 7, 2024
2 parents 96a67f9 + 5fffd02 commit 9a833c4
Showing 1 changed file with 48 additions and 1 deletion.
49 changes: 48 additions & 1 deletion packages/oceanfront/src/components/Dialog.vue
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,15 @@
</template>

<script lang="ts">
import { ref, defineComponent, computed, watch, Ref } from 'vue'
import {
ref,
defineComponent,
computed,
watch,
Ref,
onMounted,
onUnmounted,
} from 'vue'
import { OfOverlay } from './Overlay'
export default defineComponent({
Expand All @@ -69,6 +77,45 @@ export default defineComponent({
emits: ['update:modelValue'],
setup: function (props, ctx) {
const dialog = ref<any>()
const focusableElements =
'button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"]'
const handelKeyDown = (e: KeyboardEvent) => {
const firstFocusableElement =
dialog.value.querySelectorAll(focusableElements)[0]
const focusableContent = dialog.value.querySelectorAll(focusableElements)
const lastFocusableElement = focusableContent[focusableContent.length - 1]
let isTabPressed = e.key === 'Tab' || e.keyCode === 9
if (!isTabPressed) {
return
}
if (e.shiftKey) {
if (document.activeElement === firstFocusableElement) {
lastFocusableElement.focus()
e.preventDefault()
}
} else {
if (
document.activeElement === lastFocusableElement ||
!dialog.value.contains(document.activeElement)
) {
firstFocusableElement.focus()
e.preventDefault()
}
}
}
watch(
() => dialog.value,
(value) => {
if (!value) {
document.removeEventListener('keydown', handelKeyDown)
return
}
document.addEventListener('keydown', handelKeyDown)
}
)
onUnmounted(() => {
document.removeEventListener('keydown', handelKeyDown)
})
const dialogHeader: Ref<HTMLDivElement | undefined> = ref()
const active = ref(props.modelValue)
Expand Down

0 comments on commit 9a833c4

Please sign in to comment.