Skip to content
Draft
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
144 changes: 144 additions & 0 deletions e2e/tests/vite-task-detail-focus.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,144 @@
import type { Browser, Frame, Locator, Page } from 'playwright-core'
import type { ViteDevServer } from 'vite'
import { randomUUID } from 'node:crypto'
import { fileURLToPath } from 'node:url'
import { DevTools } from '@vitejs/devtools'
import { createServer } from 'vite'
import { afterAll, afterEach, beforeAll, beforeEach, expect, it, vi } from 'vitest'
import { launchBrowser, newPage } from '../src/harness'

const playground = fileURLToPath(new URL('../../playgrounds/vite-task/', import.meta.url))
const appBuild = 'packages/app#build'
const clientToken = randomUUID()
let browser: Browser
let server: ViteDevServer
let page: Page
let frame: Frame

beforeAll(async () => {
vi.stubEnv('DEVFRAME_DISABLE_INSTANCE_REGISTRY', '1')
server = await createServer({
root: playground,
configFile: false,
devtools: false,
logLevel: 'warn',
plugins: [DevTools({
cwd: playground,
clientAuthTokens: [clientToken],
builtinDevTools: {
inspect: false,
messages: false,
terminals: false,
integrations: { rolldown: false, vite: false, vitest: false, oxc: false },
},
})],
server: { host: '127.0.0.1', port: 0 },
})
await server.listen()
browser = await launchBrowser()
})

beforeEach(async () => {
page = await newPage(browser)
page.setDefaultTimeout(10_000)
const origin = new URL(server.resolvedUrls!.local[0]!).origin
// A fresh browser context uses a token trusted only by this fixture.
await page.addInitScript(({ origin, token }) => {
if (location.origin === origin)
localStorage.setItem('__DEVFRAME_CONNECTION_AUTH_TOKEN__', token)
}, { origin, token: clientToken })
await page.goto(`${origin}/__devtools/`)
await page.getByRole('button', { name: 'Vite+', exact: true }).click()
await page.getByRole('button', { name: 'Vite Task', exact: true }).click()
await page.frameLocator('iframe[src*="/__devtools-vite-task/"]').getByTitle(appBuild, { exact: true }).waitFor()
frame = page.frame({ url: '**/__devtools-vite-task/**' })!
})

afterEach(async () => {
await page?.close()
})

afterAll(async () => {
await browser?.close()
await server?.close()
vi.unstubAllEnvs()
})

function isFocused(locator: Locator) {
// The iframe can keep an activeElement after focus has moved to the host.
return locator.evaluate(el => el.matches(':focus') && document.hasFocus())
}

it.each(['List', 'Graph'])('cycles focus in %s details and returns to the task on close', async (view) => {
if (view === 'Graph')
await frame.getByRole('button', { name: 'Graph', exact: true }).click()
const opener = frame.getByTitle(appBuild, { exact: true })
await opener.press('Enter')
const dialog = frame.getByRole('dialog')
await expect.poll(() => isFocused(dialog.getByRole('heading', { level: 2 }))).toBe(true)

await page.keyboard.press('Tab')
expect(await dialog.evaluate(el => el.contains(document.activeElement) && document.hasFocus())).toBe(true)
// Dependencies has a stable first and last control even while the plan loads.
await dialog.getByRole('button', { name: 'Dependencies', exact: true }).press('Enter')
const close = dialog.getByRole('button', { name: 'Close', exact: true })
const last = dialog.getByRole('group', { name: 'Task dependencies' }).getByRole('button').last()
await close.focus()
await page.keyboard.press('Shift+Tab')
await expect.poll(() => isFocused(last)).toBe(true)
await page.keyboard.press('Tab')
await expect.poll(() => isFocused(close)).toBe(true)
await page.keyboard.press(view === 'List' ? 'Escape' : 'Enter')
await expect.poll(() => isFocused(opener)).toBe(true)
expect(await dialog.count()).toBe(0)
})

it('uses the relation popup with the keyboard and returns to the original task after navigation', async () => {
const opener = frame.getByTitle(appBuild, { exact: true })
await opener.press('Enter')
const dialog = frame.getByRole('dialog')
const trigger = dialog.getByRole('button', { name: '2 dependencies' })
const popup = dialog.locator('.v-popper__popper--shown')
const dependency = popup.getByRole('button', { name: 'packages/cli#build', exact: true })

async function focusDependency() {
await page.keyboard.press('Enter')
// Floating Vue moves focus after its opening transition.
await expect.poll(() => popup.evaluate(el => el.matches(':focus-within') && document.hasFocus())).toBe(true)
if (!await isFocused(dependency))
await page.keyboard.press('Tab')
await expect.poll(() => isFocused(dependency)).toBe(true)
}

await trigger.focus()
await focusDependency()
await page.keyboard.press('Escape')
await dependency.waitFor({ state: 'hidden' })
await expect.poll(() => isFocused(trigger)).toBe(true)
await focusDependency()
await page.keyboard.press('Enter')
const heading = dialog.getByRole('heading', { level: 2 })
await heading.getByTitle('packages/cli#build', { exact: true }).waitFor()
await expect.poll(() => isFocused(heading)).toBe(true)
await page.keyboard.press('Escape')
await expect.poll(() => isFocused(opener)).toBe(true)
})

it('returns to Search when a deep-linked task has no opener', async () => {
const route = new URL(frame.url())
route.searchParams.set('task', appBuild)
await frame.goto(route.href)
const dialog = frame.getByRole('dialog')
await expect.poll(() => isFocused(dialog.getByRole('heading', { level: 2 }))).toBe(true)
await page.keyboard.press('Escape')
await expect.poll(() => isFocused(frame.getByPlaceholder('Search'))).toBe(true)
})

it('returns focus to the clicked task when the backdrop is clicked', async () => {
const opener = frame.getByTitle(appBuild, { exact: true })
await opener.click()
const dialog = frame.getByRole('dialog')
await dialog.click({ position: { x: 1, y: 1 } })
await expect.poll(() => isFocused(opener)).toBe(true)
expect(await dialog.count()).toBe(0)
})
1 change: 1 addition & 0 deletions packages/vite-task/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@
"@vueuse/core": "catalog:frontend",
"@vueuse/nuxt": "catalog:build",
"floating-vue": "catalog:frontend",
"focus-trap": "catalog:frontend",
"nuxt": "catalog:build",
"splitpanes": "catalog:frontend",
"tsdown": "catalog:build",
Expand Down
7 changes: 5 additions & 2 deletions packages/vite-task/src/app/components/TaskDetails.vue
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import ActionButton from '@vitejs/devtools-ui/components/Action/ActionButton.vue
import DisplayCloseButton from '@vitejs/devtools-ui/components/Display/DisplayCloseButton.vue'
import DisplayDuration from '@vitejs/devtools-ui/components/Display/DisplayDuration.vue'
import VisualLoading from '@vitejs/devtools-ui/components/Visual/VisualLoading.vue'
import { computed, ref } from 'vue'
import { computed, ref, useTemplateRef, watch } from 'vue'
import { planRows } from '../utils/task-plan'
import TaskDependencies from './TaskDependencies.vue'
import TaskFlow from './TaskFlow.vue'
Expand All @@ -18,6 +18,9 @@ export interface TaskRunError {

const props = defineProps<{ dependencies: string[], dependents: string[], selected: string, plan?: RunPlan, planLoading: boolean, planError: string, taskRunAvailable: boolean, running: boolean, runError?: TaskRunError }>()
defineEmits<{ close: [], run: [], retry: [], select: [id: string] }>()
const title = useTemplateRef('title')
watch(() => props.selected, () => title.value?.focus(), { flush: 'post' })

const views = [
{ name: 'Task Flow', icon: 'i-ph-git-branch-duotone rotate-180' },
{ name: 'Commands', icon: 'i-ph-terminal-window-duotone' },
Expand All @@ -38,7 +41,7 @@ const metrics = computed(() => [
<DisplayCloseButton class="absolute top-1.5 right-2 z-panel-content bg-glass" @click="$emit('close')" />
<header class="self-start min-w-0 max-w-[calc(100%_-_3.5rem)] m2 mb0 p2 bg-glass border border-base rounded-lg flex flex-col gap2">
<div class="task-title flex items-center justify-between gap2">
<h2 class="min-w-0 flex items-center gap2 px2 pt1 m0 text-sm font-mono">
<h2 id="task-detail-title" ref="title" tabindex="-1" class="min-w-0 flex items-center gap2 px2 pt1 m0 text-sm font-mono">
<span class="i-ph-terminal-window-duotone shrink-0" />
<TaskId :id="selected" class="truncate" />
</h2>
Expand Down
4 changes: 2 additions & 2 deletions packages/vite-task/src/app/components/TaskGraphView.vue
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ const props = defineProps<{
selected: string
disabled?: boolean
}>()
defineEmits<{ select: [id: string] }>()
defineEmits<{ select: [id: string, button: HTMLButtonElement] }>()

const taskNodes = computed(() => Object.entries(props.graph.tasks).map(([id, task]) => ({
id,
Expand Down Expand Up @@ -114,7 +114,7 @@ createModuleGraph<TaskNode, TaskDependency>({
class="w-full min-w-0 flex items-center gap1 text-sm text-left font-mono"
:class="{ 'color-active': selected === node.data.module.id, 'op-fade': !matched.has(node.data.module.id) }"
:title="node.data.module.id" :disabled="disabled" :aria-pressed="selected === node.data.module.id"
@click="$emit('select', node.data.module.id)"
@click="$emit('select', node.data.module.id, $event.currentTarget as HTMLButtonElement)"
>
<span class="min-w-0 truncate" :style="{ color: getPluginColor(node.data.module.package) }"><DisplayHighlightedPath :path="node.data.module.package === '.' ? 'root' : node.data.module.package" /></span>
<span class="op-fade">/</span>
Expand Down
20 changes: 17 additions & 3 deletions packages/vite-task/src/app/components/TaskRelationMenu.vue
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
<script setup lang="ts">
import FlowmapNode from '@vitejs/devtools-ui/components/Flowmap/FlowmapNode.vue'
import { onKeyDown } from '@vueuse/core'
import { Dropdown as VDropdown } from 'floating-vue'
import { inject } from 'vue'
import { inject, ref, useTemplateRef } from 'vue'
import { isTaskInGraphKey } from '../utils/task-plan'
import TaskId from './TaskId.vue'

Expand All @@ -10,13 +11,26 @@ defineEmits<{ select: [id: string] }>()
const isTaskInGraph = inject(isTaskInGraphKey)
if (!isTaskInGraph)
throw new Error('Task navigation requires the vite-task graph provider.')
const shown = ref(false)
const trigger = useTemplateRef('trigger')

// The dropdown can stay open while Tab moves elsewhere in the dialog.
onKeyDown('Escape', (event) => {
if (!shown.value || !event.isTrusted || event.repeat)
return
event.stopPropagation()
event.preventDefault()
shown.value = false
trigger.value?.focus()
}, { target: () => trigger.value?.ownerDocument })
</script>

<template>
<VDropdown placement="bottom-start">
<!-- @vue-expect-error floating-vue 5.4 types the supported container selector as Date. -->
<VDropdown v-model:shown="shown" container="#task-detail-dialog" placement="bottom-start">
<FlowmapNode class-node-outer="border-dashed">
<template #inner>
<button class="flex items-center gap1 text-sm px3 py1" :class="direction === 'dependencies' ? 'text-orange' : 'text-blue'">
<button ref="trigger" :aria-expanded="shown" class="flex items-center gap1 text-sm px3 py1" :class="direction === 'dependencies' ? 'text-orange' : 'text-blue'">
<i class="rotate-270" :class="direction === 'dependencies' ? 'i-ph-arrows-split-duotone' : 'i-ph-arrows-merge-duotone'" />
{{ ids.length }} {{ ids.length !== 1 ? direction : direction === 'dependencies' ? 'dependency' : 'dependent' }}
</button>
Expand Down
40 changes: 35 additions & 5 deletions packages/vite-task/src/app/pages/index.vue
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,8 @@ import DataSearchPanel from '@vitejs/devtools-ui/components/Data/DataSearchPanel
import DisplayIconButton from '@vitejs/devtools-ui/components/Display/DisplayIconButton.vue'
import VisualLoading from '@vitejs/devtools-ui/components/Visual/VisualLoading.vue'
import { onKeyDown } from '@vueuse/core'
import { computed, onMounted, provide, ref, shallowRef, watch } from 'vue'
import { createFocusTrap } from 'focus-trap'
import { computed, onMounted, provide, ref, shallowRef, useTemplateRef, watch } from 'vue'
import { useRoute, useRouter } from '#app/composables/router'
import { MIN_VITE_PLUS_VERSION } from '../../shared/version'
import TaskDetails from '../components/TaskDetails.vue'
Expand Down Expand Up @@ -206,6 +207,35 @@ async function runTask(task: string) {
}
}

const overlay = useTemplateRef('overlay')
const toolbar = useTemplateRef('toolbar')
let opener: HTMLButtonElement | undefined

watch(overlay, (element, previous, onCleanup) => {
if (element) {
const trap = createFocusTrap(element, {
initialFocus: '#task-detail-title',
fallbackFocus: '#task-detail-title',
delayInitialFocus: false,
escapeDeactivates: false,
returnFocusOnDeactivate: false,
})
trap.activate()
onCleanup(() => trap.deactivate())
}
else if (previous) {
opener?.focus()
if (!opener || document.activeElement !== opener)
toolbar.value?.querySelector('input')?.focus()
opener = undefined
}
}, { flush: 'post' })

function openTask(id: string, button: HTMLButtonElement) {
opener = button
selectTask(id)
}

function selectTask(id: string) {
router.replace({ query: { ...route.query, task: id } })
}
Expand Down Expand Up @@ -245,7 +275,7 @@ onMounted(refresh)
<span class="op65">To use Vite Task DevTools, update Vite+ to v{{ MIN_VITE_PLUS_VERSION }} or later.</span>
</div>
<div v-else class="text-sm relative" :class="view === 'graph' ? 'h-full flex flex-col max-h-screen of-hidden' : ''">
<div class="z-panel-nav p4" :class="view === 'list' ? 'sticky left-4 right-4 top-4' : 'shrink-0'">
<div ref="toolbar" class="z-panel-nav p4" :class="view === 'list' ? 'sticky left-4 right-4 top-4' : 'shrink-0'">
<DataSearchPanel v-model="filters" :rules="[]">
<template #search-end>
<div class="h10 mr2 flex items-center gap2">
Expand Down Expand Up @@ -280,7 +310,7 @@ onMounted(refresh)
<span class="op40 text-xs font-mono">{{ group.tasks.length }}</span>
</summary>
<div class="flex flex-col gap2 pl4 pt2">
<button v-for="[id, task] in group.tasks" :key="id" class="hover:bg-active flex items-center gap2 px2 py1 w-full border border-base rounded text-left" :class="selected === id ? 'bg-active' : ''" :title="id" :aria-pressed="selected === id" :disabled="graphLoading" @click="selectTask(id)">
<button v-for="[id, task] in group.tasks" :key="id" class="hover:bg-active flex items-center gap2 px2 py1 w-full border border-base rounded text-left" :class="selected === id ? 'bg-active' : ''" :title="id" :aria-pressed="selected === id" :disabled="graphLoading" @click="openTask(id, $event.currentTarget as HTMLButtonElement)">
<span class="i-ph-terminal-window-duotone op-fade shrink-0" />
<span class="font-mono truncate">{{ task.name }}</span>
<span v-if="task.dependsOn?.length" v-tooltip="`Depends on ${task.dependsOn.length} ${task.dependsOn.length === 1 ? 'task' : 'tasks'}`" class="ml-auto text-xs op-fade flex items-center gap1"><span class="i-ph-graph-duotone" />{{ task.dependsOn.length }}</span>
Expand All @@ -292,12 +322,12 @@ onMounted(refresh)
</div>
</section>
<div v-else-if="visibleGraph" class="flex-1 min-h-0">
<TaskGraphView :graph="visibleGraph" :matched="matchedIds" :selected="selected" :disabled="graphLoading" @select="selectTask" />
<TaskGraphView :graph="visibleGraph" :matched="matchedIds" :selected="selected" :disabled="graphLoading" @select="openTask" />
</div>
<div v-if="graph" class="fixed bottom-4 py-1 px-2 bg-glass left-1/2 translate-x--1/2 border border-base rounded-full text-center text-xs">
<span class="op50">{{ view === 'graph' ? Object.keys(visibleGraph?.tasks || {}).length : matchedTasks.length }} of {{ taskEntries.length }}<template v-if="view === 'graph' && intermediateTaskCount"> · {{ intermediateTaskCount }} bridges</template></span>
</div>
<div v-if="selected && graph" class="fixed inset-0 backdrop-blur-8 backdrop-brightness-95 z-panel-content" @click.self="closeTask">
<div v-if="selected && graph" id="task-detail-dialog" ref="overlay" role="dialog" aria-modal="true" aria-labelledby="task-detail-title" class="fixed inset-0 backdrop-blur-8 backdrop-brightness-95 z-panel-content" @click.self="closeTask">
<div class="fixed right-0 bottom-0 top-3 left-3 sm:top-20 sm:left-20 z-panel-content bg-glass border-l border-t border-base rounded-tl-xl">
<TaskDetails :task-run-available="taskRunAvailable" :running="runningTasks.has(selected)" :run-error="runErrors.get(selected)" :dependencies="graph.tasks[selected]?.dependsOn ?? []" :dependents="dependentsByTask.get(selected) ?? []" :selected="selected" :plan="plan" :plan-loading="planLoading" :plan-error="planError" @run="runTask(selected)" @select="selectTask" @close="closeTask" @retry="loadPlan(selected)" />
</div>
Expand Down
6 changes: 6 additions & 0 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions pnpm-workspace.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -180,6 +180,7 @@ catalogs:
diff-match-patch-es: ^2.0.1
dompurify: ^3.5.0
floating-vue: ^5.4.0
focus-trap: ^8.2.4
fuse.js: ^7.5.0
idb-keyval: ^6.3.0
iframe-pane: ^1.1.0
Expand Down
Loading