Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 27 additions & 3 deletions frontend/src/components/AddSecretModal.vue
Original file line number Diff line number Diff line change
@@ -1,8 +1,28 @@
<template>
<dialog :open="show" class="modal">
<div class="modal-box max-w-2xl">
<dialog :open="show" class="modal" data-test="add-secret-modal">
<div
ref="dialogRef"
class="modal-box max-w-2xl"
role="dialog"
aria-modal="true"
aria-labelledby="add-secret-modal-title"
>
<form @submit.prevent="handleSubmit">
<h3 class="font-bold text-lg mb-4">Add New Secret</h3>
<div class="flex items-start justify-between gap-4 mb-4">
<h3 id="add-secret-modal-title" class="font-bold text-lg">
{{ props.predefinedName ? 'Set Secret Value' : 'Add New Secret' }}
</h3>
<button
type="button"
class="btn btn-sm btn-circle btn-ghost"
data-modal-close-button
data-test="add-secret-modal-close"
aria-label="Close"
@click="handleClose"
>
✕
</button>
</div>

<!-- Secret Name -->
<div class="form-control mb-4">
Expand Down Expand Up @@ -77,6 +97,7 @@
import { reactive, ref, watch } from 'vue'
import apiClient from '@/services/api'
import { useSystemStore } from '@/stores/system'
import { useModalA11y } from '@/composables/useModalA11y'

interface Props {
show: boolean
Expand All @@ -91,6 +112,9 @@ interface Emits {
const props = defineProps<Props>()
const emit = defineEmits<Emits>()

// UX audit F6/F8: Escape closes, focus enters the dialog and is trapped there.
const { dialogRef } = useModalA11y(() => props.show, () => handleClose())

const systemStore = useSystemStore()

const formData = reactive({
Expand Down
58 changes: 48 additions & 10 deletions frontend/src/components/AddServerModal.vue
Original file line number Diff line number Diff line change
@@ -1,10 +1,36 @@
<template>
<dialog :open="show" class="modal" data-test="add-server-modal">
<div class="modal-box max-w-3xl" data-test="add-server-modal-box">
<h3 class="font-bold text-lg mb-4">Add New Server</h3>
<!--
UX audit F6: the box is a flex column with its own scroll region so the
submit row stays pinned to the bottom instead of falling below the fold,
and it carries the ARIA dialog contract (role/aria-modal/labelledby) that
`<dialog open>` does not provide on its own.
-->
<div
ref="dialogRef"
class="modal-box max-w-3xl flex flex-col max-h-[85vh] p-0 overflow-hidden"
role="dialog"
aria-modal="true"
aria-labelledby="add-server-modal-title"
data-test="add-server-modal-box"
>
<!-- Header -->
<div class="flex items-start justify-between gap-4 px-6 pt-6 pb-4">
<h3 id="add-server-modal-title" class="font-bold text-lg">Add New Server</h3>
<button
type="button"
class="btn btn-sm btn-circle btn-ghost"
data-modal-close-button
data-test="add-server-modal-close"
aria-label="Close"
@click="handleClose"
>
✕
</button>
</div>

<!-- Tab Selection -->
<div class="tabs tabs-box mb-4">
<div class="tabs tabs-box mx-6 mb-4">
<a
:class="['tab', activeTab === 'manual' ? 'tab-active' : '']"
@click="activeTab = 'manual'"
Expand All @@ -20,8 +46,9 @@
</div>

<!-- Manual Tab -->
<div v-if="activeTab === 'manual'">
<form @submit.prevent="handleSubmit">
<div v-if="activeTab === 'manual'" class="flex flex-col flex-1 min-h-0">
<form @submit.prevent="handleSubmit" class="flex flex-col flex-1 min-h-0">
<div class="flex-1 min-h-0 overflow-y-auto px-6 pb-4" data-test="add-server-modal-body">
<!-- Server Type Selection -->
<div class="form-control mb-4">
<label class="label">
Expand Down Expand Up @@ -245,9 +272,13 @@
</svg>
<span>{{ error }}</span>
</div>
</div>

<!-- Actions -->
<div class="modal-action">
<!-- Actions (sticky footer — F6) -->
<div
class="modal-action mt-0 px-6 py-4 border-t border-base-300 bg-base-100"
data-test="add-server-modal-footer"
>
<button type="button" @click="handleClose" class="btn btn-ghost">Cancel</button>
<button type="submit" class="btn btn-primary" :disabled="loading">
<span v-if="loading" class="loading loading-spinner loading-sm"></span>
Expand All @@ -258,7 +289,8 @@
</div>

<!-- Import Tab -->
<div v-if="activeTab === 'import'">
<div v-if="activeTab === 'import'" class="flex flex-col flex-1 min-h-0">
<div class="flex-1 min-h-0 overflow-y-auto px-6 pb-4">
<!-- Input Method Tabs -->
<div class="flex gap-2 mb-4">
<button
Expand Down Expand Up @@ -531,9 +563,10 @@ Example (Claude Desktop):
<div class="text-sm mt-2">Deselect these servers or fix the configuration before importing.</div>
</div>
</div>
</div>

<!-- Actions -->
<div class="modal-action">
<!-- Actions (sticky footer — F6) -->
<div class="modal-action mt-0 px-6 py-4 border-t border-base-300 bg-base-100">
<button type="button" @click="handleClose" class="btn btn-ghost">Cancel</button>
<button
@click="handleImport"
Expand All @@ -558,6 +591,7 @@ import { useServersStore } from '@/stores/servers'
import { useSystemStore } from '@/stores/system'
import api, { type CanonicalConfigPath } from '@/services/api'
import TrustModeSelector from '@/components/TrustModeSelector.vue'
import { useModalA11y } from '@/composables/useModalA11y'
import type { TrustMode } from '@/utils/trustMode'
import type { ImportResponse, ImportedServer } from '@/types'

Expand All @@ -573,6 +607,10 @@ interface Emits {
const props = defineProps<Props>()
const emit = defineEmits<Emits>()

// UX audit F6: Escape closes, focus enters the dialog on open and is trapped
// inside it, and returns to the trigger on close.
const { dialogRef } = useModalA11y(() => props.show, () => handleClose())

const serversStore = useServersStore()
const systemStore = useSystemStore()

Expand Down
225 changes: 225 additions & 0 deletions frontend/src/composables/useModalA11y.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,225 @@
import { nextTick, onBeforeUnmount, ref, watch, type Ref } from 'vue'

/**
* Keyboard + focus behaviour for the `<dialog :open>` modals used across the
* Web UI (UX audit F6).
*
* These modals are rendered with the `open` attribute rather than
* `HTMLDialogElement.showModal()`, so the browser gives us *none* of the modal
* affordances: Escape does not close, focus stays on the trigger button and
* Tab walks straight out of the dialog into the page behind it. This composable
* supplies those three behaviours plus focus restoration, without changing how
* the dialogs are mounted or styled.
*
* Usage:
* const { dialogRef } = useModalA11y(() => props.show, handleClose)
* <div class="modal-box" ref="dialogRef" role="dialog" aria-modal="true">
*/

// Elements that can receive focus inside the dialog. `[hidden]` and elements
// inside a `display:none` subtree are filtered out separately (offsetParent).
const FOCUSABLE_SELECTOR = [
'a[href]',
'button:not([disabled])',
'input:not([disabled]):not([type="hidden"])',
'select:not([disabled])',
'textarea:not([disabled])',
'[tabindex]:not([tabindex="-1"])',
].join(',')

/**
* Every currently-open modal, oldest first.
*
* The keydown listener lives on `document`, and stopPropagation does NOT stop
* other listeners already bound to the same node in the same phase — so with
* two modals open, both would see Escape and both would close. Only the
* topmost entry acts; the ones beneath it ignore the key entirely.
*/
const openStack: symbol[] = []

function isTopmost(id: symbol): boolean {
return openStack.length > 0 && openStack[openStack.length - 1] === id
}

export interface ModalA11yOptions {
/**
* Selector for the element that should receive focus when the modal opens.
* Defaults to the first focusable element that is not the header close
* button, so keyboard users land on the form rather than on "✕".
*/
initialFocus?: string
}

export function useModalA11y(
isOpen: () => boolean,
close: () => void,
options: ModalA11yOptions = {}
) {
const dialogRef = ref<HTMLElement | null>(null)
const id = Symbol('modal-a11y')
let previouslyFocused: HTMLElement | null = null

/**
* Whether an element can actually take focus right now.
*
* An element inside a `v-show`-hidden (display:none) or `visibility:hidden`
* subtree is in the DOM but cannot be focused, and letting one bound the Tab
* trap would make Tab appear to stick. checkVisibility covers display and
* content-visibility on its own; `visibility` needs checkVisibilityCSS, which
* is off by default. jsdom does not implement the method, so the unit tests
* fall through to "visible" — which matches how they build the DOM (v-if
* branches are absent rather than hidden). The browser path is covered by the
* Playwright sweep instead.
*/
function isFocusable(el: HTMLElement): boolean {
if (el.hasAttribute('hidden')) return false
if (el.getAttribute('aria-hidden') === 'true') return false
if (el.hasAttribute('disabled')) return false
if (typeof el.checkVisibility === 'function') {
return el.checkVisibility({ checkVisibilityCSS: true })
}
return true
}

function visibleFocusables(): HTMLElement[] {
const root = dialogRef.value
if (!root) return []
return Array.from(root.querySelectorAll<HTMLElement>(FOCUSABLE_SELECTOR)).filter(isFocusable)
}

function focusInitial() {
const root = dialogRef.value
if (!root) return
if (options.initialFocus) {
// Resolved with its own query rather than against the Tab-order list: the
// usual target for this option is the dialog heading carrying
// tabindex="-1", which is programmatically focusable but deliberately NOT
// in the tab order, so matching it against FOCUSABLE_SELECTOR would
// silently ignore the option. Visibility and disabled are still enforced,
// so a selector can never hand focus to something that cannot take it.
const preferred = root.querySelector<HTMLElement>(options.initialFocus)
if (preferred && isFocusable(preferred)) {
preferred.focus()
return
}
}
const candidates = visibleFocusables()
const first = candidates.find((el) => el.dataset.modalCloseButton === undefined) ?? candidates[0]
if (first) {
first.focus()
} else {
// Nothing focusable yet (async content): park focus on the box itself so
// Escape and the Tab trap still have a live target inside the dialog.
root.setAttribute('tabindex', '-1')
root.focus()
}
}

function onKeydown(event: KeyboardEvent) {
// A modal underneath another one neither closes on Escape nor fights the
// top modal for focus.
if (!isOpen() || !isTopmost(id)) return

if (event.key === 'Escape' || event.key === 'Esc') {
event.preventDefault()
event.stopPropagation()
close()
return
}

if (event.key !== 'Tab') return

const root = dialogRef.value
if (!root) return
const focusables = visibleFocusables()
if (focusables.length === 0) return

const first = focusables[0]
const last = focusables[focusables.length - 1]
const active = document.activeElement as HTMLElement | null

// Focus escaped the dialog (or never entered it) — pull it back in.
if (!active || !root.contains(active)) {
event.preventDefault()
;(event.shiftKey ? last : first).focus()
return
}

if (event.shiftKey && active === first) {
event.preventDefault()
last.focus()
} else if (!event.shiftKey && active === last) {
event.preventDefault()
first.focus()
}
}

function activate() {
if (openStack.includes(id)) return
previouslyFocused = document.activeElement as HTMLElement | null
openStack.push(id)
document.addEventListener('keydown', onKeydown, true)
void nextTick(() => {
// The tick may land after this modal closed again, or after a second
// modal opened on top of it; in either case grabbing focus now would
// take it somewhere the user cannot see.
if (isOpen() && isTopmost(id)) focusInitial()
})
}

function deactivate(deferRestore = false) {
const at = openStack.indexOf(id)
const wasOpen = at !== -1
if (wasOpen) openStack.splice(at, 1)
document.removeEventListener('keydown', onKeydown, true)
const target = previouslyFocused
previouslyFocused = null

// Restore focus only when this was the LAST modal standing. A modal that
// closes while another is still open sits underneath it, and focusing its
// trigger would drag focus out of the top modal and behind it. The top
// modal keeps focus and restores to its own trigger when it goes.
//
// Known limit: when a stack unwinds bottom-up in one tick, the top modal's
// remembered trigger is an element of the modal below it, which is by then
// gone or hidden — focus lands on <body> rather than the original opener.
// Unwinding top-down (the normal order) restores correctly. Chaining the
// remembered targets across instances is not worth it while nothing in the
// app stacks these modals.
if (!wasOpen || openStack.length > 0) return
if (!target || typeof target.focus !== 'function') return

const restore = () => {
// Re-check at call time: a trigger torn down with the modal must not be
// focused just before removal (a pointless focus/blur pair that scrolls
// and is announced), and a modal opened in the meantime keeps focus.
if (openStack.length > 0) return
if (!document.contains(target)) return
target.focus()
}
if (deferRestore) void nextTick(restore)
else restore()
}

watch(
isOpen,
(open, wasOpen) => {
if (open === wasOpen) return
if (open) activate()
else if (wasOpen !== undefined) deactivate()
},
{ immediate: true }
)

onBeforeUnmount(() => {
// Unmounting while open (a route change, a v-if around the modal) must not
// strand the listener or the focus. The restore is deferred one tick so it
// runs AFTER Vue has detached this subtree: a trigger that went away with
// the modal then fails the contains() check and is left alone, while a
// trigger that outlives it (modal alone behind a v-if) still gets focus
// back.
deactivate(true)
})

return { dialogRef, focusInitial }
}
Loading
Loading