fix(app): make the question dock keyboard-first and stop it flashing (#58494)

This commit is contained in:
Kit Langton
2026-10-23 20:04:56 -07:00
committed by GitHub
Unverified
parent 84b4452eb9
commit 3347afd09b
5 changed files with 796 additions and 220 deletions
@@ -43,7 +43,7 @@ story("selects single answers and toggles multiple answers with number keys", as
await expect(input).toBeFocused()
await expect(focused).not.toBeChecked()
await expect(wide).not.toBeChecked()
await input.press("Enter")
await input.press("Escape")
await expect(customRadio).toBeFocused()
await customRadio.press("2")
await expect(wide).toBeChecked()
@@ -68,7 +68,7 @@ story("selects single answers and toggles multiple answers with number keys", as
await expect(input).toBeFocused()
await expect(files).toBeChecked()
await expect(terminal).not.toBeChecked()
await input.press("Enter")
await input.press("Escape")
await expect(customCheckbox).toBeFocused()
await customCheckbox.press("4")
await expect(customCheckbox).not.toBeChecked()
@@ -76,6 +76,156 @@ story("selects single answers and toggles multiple answers with number keys", as
await expect(terminal).not.toBeChecked()
})
story("moves only the highlight with Up and Down and marks it with Space", async ({ mount, page }) => {
const component = await mount("app-current-session-surface--question-request")
const question = component.locator('[data-component="dock-prompt"][data-kind="question"]')
const focused = question.getByRole("radio", { name: /Focused/ })
const wide = question.getByRole("radio", { name: /Wide/ })
const custom = question.getByRole("radio", { name: "Type your own answer…", exact: true })
const input = question.getByRole("textbox", { name: "Type your own answer…", exact: true })
const highlight = question.locator('[data-slot="question-highlight"]')
const clip = () => highlight.evaluate((element) => element.style.clipPath)
await expect(focused).toBeFocused()
await expect(focused).not.toBeChecked()
const first = await clip()
await page.keyboard.press("ArrowDown")
await expect(wide).toBeFocused()
await expect(wide).not.toBeChecked()
await expect(focused).not.toBeChecked()
await expect(wide).toHaveAttribute("tabindex", "0")
await expect(focused).toHaveAttribute("tabindex", "-1")
await expect.poll(clip).not.toBe(first)
await page.keyboard.press("ArrowDown")
await expect(custom).toBeFocused()
await expect(custom).not.toBeChecked()
await expect(input).not.toBeFocused()
await page.keyboard.press("ArrowUp")
await expect(wide).toBeFocused()
await page.keyboard.press(" ")
await expect(wide).toBeChecked()
await expect(wide).toBeFocused()
await expect(question.getByRole("button", { name: "Next", exact: true })).toBeVisible()
await page.keyboard.press("Home")
await expect(focused).toBeFocused()
await expect(focused).not.toBeChecked()
await expect(wide).toBeChecked()
})
story("Enter picks the highlighted answer and moves on", async ({ mount, page }) => {
const component = await mount("app-current-session-surface--question-request")
const question = component.locator('[data-component="dock-prompt"][data-kind="question"]')
const focused = question.getByRole("radio", { name: /Focused/ })
const wide = question.getByRole("radio", { name: /Wide/ })
const files = question.getByRole("checkbox", { name: "Changed files", exact: true })
const terminal = question.getByRole("checkbox", { name: "Terminal", exact: true })
await expect(focused).toBeFocused()
await page.keyboard.press("ArrowDown")
await page.keyboard.press("Enter")
await expect(files).toBeFocused()
await expect(files).not.toBeChecked()
await expect(question.getByRole("button", { name: "Submit", exact: true })).toBeVisible()
await page.keyboard.press("ArrowLeft")
await expect(wide).toBeFocused()
await expect(wide).toBeChecked()
await expect(focused).not.toBeChecked()
await page.keyboard.press("ArrowRight")
await page.keyboard.press("ArrowDown")
await page.keyboard.press(" ")
await expect(terminal).toBeChecked()
await expect(files).not.toBeChecked()
await page.keyboard.press("Enter")
await expect(question).toBeHidden()
})
story("typing on the highlighted custom answer starts it", async ({ mount, page }) => {
const component = await mount("app-current-session-surface--question-request")
const question = component.locator('[data-component="dock-prompt"][data-kind="question"]')
const focused = question.getByRole("radio", { name: /Focused/ })
const custom = question.getByRole("radio", { name: "Type your own answer…", exact: true })
const input = question.getByRole("textbox", { name: "Type your own answer…", exact: true })
await expect(focused).toBeFocused()
await focused.press("1")
await expect(focused).toBeChecked()
await page.keyboard.press("End")
await expect(custom).toBeFocused()
await expect(custom).not.toBeChecked()
await page.keyboard.press("S")
await expect(input).toBeFocused()
await expect(custom).toBeChecked()
await expect(focused).not.toBeChecked()
await page.keyboard.type("plit")
await expect(input).toHaveValue("Split")
await page.keyboard.press("Enter")
await expect(question.getByRole("checkbox", { name: "Changed files", exact: true })).toBeFocused()
await page.keyboard.press("ArrowLeft")
await expect(custom).toBeChecked()
await expect(input).toHaveValue("Split")
})
story("switches questions with Left and Right outside the text field", async ({ mount, page }) => {
const component = await mount("app-current-session-surface--question-request")
const question = component.locator('[data-component="dock-prompt"][data-kind="question"]')
const focused = question.getByRole("radio", { name: /Focused/ })
const files = question.getByRole("checkbox", { name: "Changed files", exact: true })
const submit = question.getByRole("button", { name: "Submit", exact: true })
const wide = question.getByRole("radio", { name: /Wide/ })
await expect(focused).toBeFocused()
await page.keyboard.press("ArrowDown")
await page.keyboard.press(" ")
await expect(wide).toBeChecked()
await page.keyboard.press("ArrowRight")
await expect(files).toBeFocused()
await expect(submit).toBeVisible()
await page.keyboard.press("ArrowRight")
await expect(submit).toBeVisible()
await expect(files).toBeFocused()
await page.keyboard.press("ArrowLeft")
await expect(wide).toBeFocused()
await expect(wide).toBeChecked()
const input = question.getByRole("textbox", { name: "Type your own answer…", exact: true })
await input.focus()
await input.fill("ab")
await page.keyboard.press("ArrowLeft")
await expect(input).toBeFocused()
await expect(focused).toBeVisible()
})
story("toggles checkboxes with Space on key down and moves focus with arrows", async ({ mount, page }) => {
const component = await mount("app-current-session-surface--question-request")
const question = component.locator('[data-component="dock-prompt"][data-kind="question"]')
await question.getByRole("button", { name: "Next", exact: true }).click()
const files = question.getByRole("checkbox", { name: "Changed files", exact: true })
const terminal = question.getByRole("checkbox", { name: "Terminal", exact: true })
await expect(files).toBeFocused()
await page.keyboard.down(" ")
await expect(files).toBeChecked()
await page.keyboard.down(" ")
await page.keyboard.up(" ")
await expect(files).toBeChecked()
await page.keyboard.press("ArrowDown")
await expect(terminal).toBeFocused()
await expect(terminal).not.toBeChecked()
await page.keyboard.press(" ")
await expect(terminal).toBeChecked()
await page.keyboard.press(" ")
await expect(terminal).not.toBeChecked()
await expect(files).toBeChecked()
})
story("ignores modified, out-of-range, and repeated number shortcuts", async ({ mount, page }) => {
const component = await mount("app-current-session-surface--question-request")
const question = component.locator('[data-component="dock-prompt"][data-kind="question"]')
@@ -116,6 +266,31 @@ story("types digits into the custom answer without selecting numbered options",
await expect(question.getByRole("radio", { name: /Wide/ })).not.toBeChecked()
})
story("leaves Enter and Escape to an IME composition in the custom answer", async ({ mount }) => {
const component = await mount("app-current-session-surface--question-request")
const question = component.locator('[data-component="dock-prompt"][data-kind="question"]')
const toggle = question.getByRole("radio", { name: "Type your own answer…", exact: true })
const input = question.getByRole("textbox", { name: "Type your own answer…", exact: true })
await input.focus()
await input.fill("にほん")
const compose = (key: string, keyCode: number) =>
input.evaluate(
(element, init) =>
element.dispatchEvent(new KeyboardEvent("keydown", { ...init, bubbles: true, cancelable: true })),
{ key, keyCode, isComposing: keyCode !== 229 },
)
await compose("Enter", 13)
await compose("Escape", 27)
await compose("Enter", 229)
await compose("Escape", 229)
await expect(input).toBeFocused()
await expect(input).toHaveValue("にほん")
await expect(question).toBeVisible()
await input.press("Escape")
await expect(toggle).toBeFocused()
await expect(question).toBeVisible()
})
story("shows question navigation shortcuts in buttons and tooltips", async ({ mount, page }) => {
const component = await mount("app-current-session-surface--question-request")
const mac = await page.evaluate(() => /Mac|iPhone|iPad|iPod/.test(navigator.platform))
@@ -174,7 +349,7 @@ story("keeps the custom answer input and dock geometry stable while editing", as
await expect(toggle).toBeChecked()
await expect(predefined).not.toBeChecked()
await expect.poll(height).toBe(initial)
await input.press("Enter")
await input.press("Escape")
await expect(toggle).toBeFocused()
await expect(input).toHaveValue(draft)
await row.click({ position: { x: 30, y: 20 } })
@@ -0,0 +1,106 @@
import { describe, expect, test } from "bun:test"
import { questionKey, type QuestionKeyZone } from "./question-keys"
const press = (
key: string,
options: {
zone?: QuestionKeyZone
mac?: boolean
count?: number
repeat?: boolean
meta?: boolean
alt?: boolean
shift?: boolean
composing?: boolean
keyCode?: number
} = {},
) =>
questionKey(
{
key,
repeat: options.repeat ?? false,
metaKey: options.meta ?? false,
ctrlKey: false,
altKey: options.alt ?? false,
shiftKey: options.shift ?? false,
isComposing: options.composing ?? false,
keyCode: options.keyCode ?? 0,
},
{ mac: options.mac ?? true, zone: options.zone ?? "option", count: options.count ?? 3 },
)
describe("questionKey", () => {
test("Enter and Escape that confirm or cancel an IME composition do nothing", () => {
expect(press("Escape", { composing: true })).toEqual({ type: "none" })
expect(press("Enter", { composing: true, meta: true })).toEqual({ type: "none" })
expect(press("Escape", { keyCode: 229 })).toEqual({ type: "none" })
expect(press("Enter", { keyCode: 229, meta: true })).toEqual({ type: "none" })
expect(press("Escape")).toEqual({ type: "dismiss" })
})
test("Up and Down move the highlight", () => {
expect(press("ArrowDown")).toEqual({ type: "move", step: 1 })
expect(press("ArrowUp", { zone: "custom" })).toEqual({ type: "move", step: -1 })
expect(press("Home")).toEqual({ type: "edge", to: "first" })
expect(press("End")).toEqual({ type: "edge", to: "last" })
})
test("Left and Right switch questions anywhere but the text field", () => {
expect(press("ArrowRight")).toEqual({ type: "question", step: 1 })
expect(press("ArrowLeft", { zone: "custom" })).toEqual({ type: "question", step: -1 })
expect(press("ArrowRight", { zone: "other" })).toEqual({ type: "question", step: 1 })
expect(press("ArrowLeft", { zone: "input" })).toEqual({ type: "none" })
expect(press("ArrowRight", { zone: "input" })).toEqual({ type: "none" })
expect(press("ArrowRight", { shift: true })).toEqual({ type: "none" })
})
test("Up and Down outside the answers leave focus alone", () => {
expect(press("ArrowDown", { zone: "other" })).toEqual({ type: "none" })
expect(press("ArrowUp", { zone: "input" })).toEqual({ type: "none" })
})
test("Space acts on key down and ignores its repeats", () => {
expect(press(" ")).toEqual({ type: "activate" })
expect(press(" ", { zone: "custom" })).toEqual({ type: "activate" })
expect(press(" ", { repeat: true })).toEqual({ type: "swallow" })
expect(press(" ", { zone: "input" })).toEqual({ type: "none" })
expect(press(" ", { zone: "other" })).toEqual({ type: "none" })
})
test("number keys pick answers in range, once per press", () => {
expect(press("1")).toEqual({ type: "number", index: 0 })
expect(press("3", { zone: "other" })).toEqual({ type: "number", index: 2 })
expect(press("4")).toEqual({ type: "none" })
expect(press("2", { repeat: true })).toEqual({ type: "none" })
expect(press("2", { alt: true })).toEqual({ type: "none" })
expect(press("2", { zone: "input" })).toEqual({ type: "none" })
})
test("the shortcuts work everywhere, including the text field", () => {
expect(press("Escape", { zone: "input" })).toEqual({ type: "dismiss" })
expect(press("[", { meta: true, zone: "input" })).toEqual({ type: "question", step: -1 })
expect(press("ArrowLeft", { alt: true, mac: false })).toEqual({ type: "question", step: -1 })
expect(press("Enter", { meta: true, zone: "input" })).toEqual({ type: "advance" })
expect(press("Enter", { meta: true, repeat: true })).toEqual({ type: "none" })
})
test("Enter commits the highlighted answer once per press", () => {
expect(press("Enter")).toEqual({ type: "commit" })
expect(press("Enter", { zone: "custom" })).toEqual({ type: "commit" })
expect(press("Enter", { repeat: true })).toEqual({ type: "swallow" })
expect(press("Enter", { shift: true })).toEqual({ type: "none" })
expect(press("Enter", { zone: "input" })).toEqual({ type: "none" })
expect(press("Enter", { zone: "other" })).toEqual({ type: "none" })
})
test("typing on the custom answer starts the answer", () => {
expect(press("a", { zone: "custom" })).toEqual({ type: "type" })
expect(press("A", { zone: "custom", shift: true })).toEqual({ type: "type" })
expect(press("å", { zone: "custom", alt: true })).toEqual({ type: "type" })
expect(press("0", { zone: "custom" })).toEqual({ type: "type" })
expect(press("1", { zone: "custom" })).toEqual({ type: "number", index: 0 })
expect(press("a", { zone: "custom", meta: true })).toEqual({ type: "none" })
expect(press("a")).toEqual({ type: "none" })
expect(press("Tab", { zone: "custom" })).toEqual({ type: "none" })
})
})
@@ -0,0 +1,81 @@
// Where focus sits in the question dock when a key goes down: on an answer, on the custom answer's toggle, in the
// custom answer's text field, or anywhere else in the dock (progress, footer buttons).
export type QuestionKeyZone = "option" | "custom" | "input" | "other"
export type QuestionKeyIntent =
| { type: "dismiss" }
| { type: "advance" }
| { type: "question"; step: 1 | -1 }
| { type: "move"; step: 1 | -1 }
| { type: "edge"; to: "first" | "last" }
| { type: "number"; index: number }
| { type: "activate" }
| { type: "commit" }
| { type: "type" }
| { type: "swallow" }
| { type: "none" }
type Key = Pick<
KeyboardEvent,
"key" | "keyCode" | "repeat" | "metaKey" | "ctrlKey" | "altKey" | "shiftKey" | "isComposing"
>
// Maps one keydown to what the dock should do. The arrows only move the highlight; Space marks the highlighted answer and
// Enter commits it and moves on. Answers act on key down, so Space never waits for its release.
export function questionKey(
event: Key,
context: { mac: boolean; zone: QuestionKeyZone; count: number },
): QuestionKeyIntent {
// Enter and Escape during IME composition confirm or cancel the composition; Safari reports those as keyCode 229.
if (event.isComposing || event.keyCode === 229) return { type: "none" }
if (event.key === "Escape") return { type: "dismiss" }
const back = context.mac
? event.metaKey && !event.ctrlKey && !event.altKey && event.key === "["
: event.altKey && !event.ctrlKey && !event.metaKey && event.key === "ArrowLeft"
if (back) return event.repeat ? { type: "none" } : { type: "question", step: -1 }
if ((event.metaKey || event.ctrlKey) && !event.altKey && event.key === "Enter")
return event.repeat ? { type: "none" } : { type: "advance" }
if (context.zone === "input" || event.metaKey || event.ctrlKey) return { type: "none" }
const digit = /^[1-9]$/.test(event.key)
// A printable key on the custom answer starts typing it; Option combinations are printable on macOS.
if (context.zone === "custom" && !digit && event.key.length === 1 && event.key !== " ") return { type: "type" }
if (event.altKey) return { type: "none" }
if (digit) {
const index = Number(event.key) - 1
if (event.repeat || index >= context.count) return { type: "none" }
return { type: "number", index }
}
if (event.shiftKey && event.key.startsWith("Arrow")) return { type: "none" }
if (event.key === "ArrowLeft") return { type: "question", step: -1 }
if (event.key === "ArrowRight") return { type: "question", step: 1 }
if (context.zone === "other") return { type: "none" }
if (event.key === "ArrowDown") return { type: "move", step: 1 }
if (event.key === "ArrowUp") return { type: "move", step: -1 }
if (event.key === "Home") return { type: "edge", to: "first" }
if (event.key === "End") return { type: "edge", to: "last" }
if (event.key === " ") return event.repeat ? { type: "swallow" } : { type: "activate" }
if (event.key === "Enter" && !event.shiftKey) return event.repeat ? { type: "swallow" } : { type: "commit" }
return { type: "none" }
}
@@ -8,6 +8,7 @@ import { DockPrompt } from "@opencode/session-ui/dock-prompt"
import { Icon } from "@opencode/ui/icon"
import { TextInput } from "@opencode/ui/text-input"
import { useSpring } from "@opencode/ui/motion-spring"
import { prefersReducedMotion } from "@opencode/ui/motion"
import { showToast } from "@/shell/notifications/toast"
import type { FormAnswer, FormInfo, FormMultiselectField, FormStringField } from "@opencode/client/promise"
import { useLanguage } from "@/runtime/i18n/language"
@@ -16,11 +17,16 @@ import { createResizeObserver } from "@solid-primitives/resize-observer"
import { useServerSDK } from "@/runtime/server/client"
import { ScopedKey } from "@/runtime/server/scope"
import { useCommand } from "@/shell/commands/command"
import { questionKey, type QuestionKeyZone } from "./question-keys"
const cache = new Map<string, { tab: number; answers: string[][]; custom: string[]; customOn: boolean[] }>()
const IS_MAC = /(Mac|iPod|iPhone|iPad)/.test(navigator.platform)
// A bounce-0 spring with a 0.3s visual duration, sampled for the Web Animations API.
const SPRING_EASE =
"linear(0, 0.04, 0.131, 0.243, 0.358, 0.466, 0.562, 0.645, 0.715, 0.774, 0.821, 0.859, 0.89, 0.914, 0.934, 0.949, 0.96, 0.97, 0.977, 0.982, 1)"
type QuestionField = FormStringField | FormMultiselectField
function questionField(field: FormInfo["fields"][number]): field is QuestionField {
@@ -46,8 +52,10 @@ function Option(props: {
description?: string
shortcut?: string
disabled: boolean
tabbable: boolean
ref?: (el: HTMLButtonElement) => void
onFocus?: VoidFunction
onPointerMove?: (event: PointerEvent) => void
onClick: VoidFunction
}) {
return (
@@ -59,8 +67,10 @@ function Option(props: {
role={props.multi ? "checkbox" : "radio"}
aria-checked={props.picked}
aria-keyshortcuts={props.shortcut}
tabindex={props.tabbable ? 0 : -1}
disabled={props.disabled}
onFocus={props.onFocus}
onPointerMove={props.onPointerMove}
onClick={props.onClick}
>
<Mark multi={props.multi} picked={props.picked} />
@@ -106,16 +116,20 @@ export const SessionQuestionDock: Component<{ request: FormInfo; onSubmit: () =>
editing: false,
focus: 0,
minimized: false,
optionsHeight: 180,
listHeight: 0,
})
let root: HTMLDivElement | undefined
let detailsRef: HTMLDivElement | undefined
let optionsRef: HTMLDivElement | undefined
let listRef: HTMLDivElement | undefined
let customRef: HTMLButtonElement | undefined
let customRow: HTMLDivElement | undefined
let highlightRef: HTMLSpanElement | undefined
let customInput: HTMLInputElement | undefined
let optsRef: HTMLButtonElement[] = []
let replied = false
let focusFrame: number | undefined
const arrivals: Animation[] = []
const question = createMemo(() => questions()[store.tab])
const options = createMemo(() => question()?.options ?? [])
@@ -137,6 +151,13 @@ export const SessionQuestionDock: Component<{ request: FormInfo; onSubmit: () =>
const collapse = useSpring(() => (store.minimized ? 1 : 0), { visualDuration: 0.3, bounce: 0 })
const hidden = createMemo(() => Math.max(0, Math.min(1, collapse())))
const optionsOff = createMemo(() => hidden() > 0.98)
// The answers box follows its list's measured height, so the dock grows and shrinks with each question. Under
// reduced motion it lands at once while the content fades.
const listHeight = useSpring(
() => store.listHeight,
() => ({ visualDuration: prefersReducedMotion() ? 0.01 : 0.4, bounce: 0 }),
() => store.listHeight > 0,
)
const customUpdate = (value: string, selected: boolean = on()) => {
const prev = input().trim()
@@ -202,18 +223,14 @@ export const SessionQuestionDock: Component<{ request: FormInfo; onSubmit: () =>
)
}
const focus = (i: number) => {
// Focus moves in the same task as the key that moved it, so the highlight and the focus never disagree for a frame.
const focus = (i: number, how?: FocusOptions) => {
const next = clamp(i)
setStore("focus", next)
if (store.editing) return
if (focusFrame !== undefined) cancelAnimationFrame(focusFrame)
focusFrame = requestAnimationFrame(() => {
focusFrame = undefined
const el = next === options().length ? customRef : optsRef[next]
el?.focus()
})
const el = next === options().length ? customRef : optsRef[next]
el?.focus(how)
}
onMount(() => {
@@ -243,16 +260,50 @@ export const SessionQuestionDock: Component<{ request: FormInfo; onSubmit: () =>
})
createEffect(() => {
const el = optionsRef
const el = listRef
if (!el) return
const update = () => setStore("optionsHeight", (height) => Math.max(height, el.scrollHeight))
update()
createResizeObserver(el, update)
const observer = new ResizeObserver((entries) => {
const size = entries[0]?.borderBoxSize[0]?.blockSize
if (size !== undefined) setStore("listHeight", size)
})
observer.observe(el)
onCleanup(() => observer.disconnect())
})
// One highlight card glides between answers by its clip, so only one answer ever looks highlighted. It lands at once
// on a new question, and under reduced motion it fades in at its new answer instead of gliding.
let placed = { tab: -1, index: -1 }
createEffect(() => {
const el = highlightRef
const index = store.focus
const row = index === options().length ? customRow : optsRef[index]
void store.listHeight
if (!el || !row || !listRef) return
const clip = `inset(${row.offsetTop}px 0 ${listRef.offsetHeight - row.offsetTop - row.offsetHeight}px round 6px)`
const fresh = placed.tab !== store.tab
const moved = fresh || placed.index !== index
const reduced = prefersReducedMotion()
placed = { tab: store.tab, index }
if (!fresh && !reduced) {
el.style.clipPath = clip
return
}
el.style.transition = "none"
el.style.clipPath = clip
void el.offsetHeight
el.style.removeProperty("transition")
if (reduced && moved && el.animate)
el.animate([{ opacity: 0 }, { opacity: 1 }], { duration: 150, easing: "linear" })
})
onCleanup(() => {
if (focusFrame !== undefined) cancelAnimationFrame(focusFrame)
arrivals.forEach((animation) => animation.cancel())
if (replied) return
cache.set(cacheKey, {
@@ -340,30 +391,21 @@ export const SessionQuestionDock: Component<{ request: FormInfo; onSubmit: () =>
})
}
const startCustom = () => {
setStore("focus", options().length)
setStore("customOn", store.tab, true)
setStore("editing", true)
customUpdate(input(), true)
customInput?.focus()
customInput?.setSelectionRange(input().length, input().length)
}
const customToggle = () => {
if (sending()) return
setStore("focus", options().length)
if (!multi()) {
setStore("customOn", store.tab, true)
setStore("editing", true)
customUpdate(input(), true)
customInput?.focus()
return
}
const next = !on()
setStore("customOn", store.tab, next)
if (next) {
setStore("editing", true)
customUpdate(input(), true)
customInput?.focus()
return
}
if (!multi() || !on()) return startCustom()
setStore("customOn", store.tab, false)
const value = input().trim()
if (value) setStore("answers", store.tab, (current = []) => current.filter((item) => item.trim() !== value))
@@ -371,95 +413,109 @@ export const SessionQuestionDock: Component<{ request: FormInfo; onSubmit: () =>
focus(options().length)
}
const move = (step: number) => {
if (store.editing || sending()) return
focus(store.focus + step)
// The pointer moves the highlight like the arrows do, but never takes focus from the custom answer's field.
const hover = (i: number, event: PointerEvent) => {
if (event.pointerType !== "mouse" || store.editing || sending()) return
setStore("focus", i)
}
// Enter picks the highlighted answer of a single-choice question, then moves on. An empty custom answer opens its
// field instead, since there is nothing to pick yet.
const commit = () => {
if (multi()) return next()
if (store.focus < options().length) {
selectOption(store.focus)
return next()
}
if (!input().trim()) return startCustom()
setStore("customOn", store.tab, true)
customUpdate(input(), true)
next()
}
const zone = (target: EventTarget | null): QuestionKeyZone => {
if (store.editing) return "input"
if (!(target instanceof HTMLElement)) return "other"
if (target.closest(".question-custom-field")) return "input"
if (target.matches('[data-slot="question-custom-toggle"]')) return "custom"
if (target.matches('[data-slot="question-option"]')) return "option"
return "other"
}
const nav = (event: KeyboardEvent) => {
if (event.defaultPrevented) return
if (event.key === "Escape") {
const intent = questionKey(event, { mac: IS_MAC, zone: zone(event.target), count: count() })
if (intent.type === "none") return
if (intent.type === "dismiss") {
event.preventDefault()
reject()
return
}
const previous = IS_MAC
? event.metaKey && !event.ctrlKey && !event.altKey && event.key === "["
: event.altKey && !event.ctrlKey && !event.metaKey && event.key === "ArrowLeft"
if (previous) {
if (event.repeat) return
event.preventDefault()
back()
return
}
const mod = (event.metaKey || event.ctrlKey) && !event.altKey
if (mod && event.key === "Enter") {
if (event.repeat) return
if (intent.type === "advance") {
event.preventDefault()
next()
return
}
const target =
event.target instanceof HTMLElement ? event.target.closest('[data-slot="question-options"]') : undefined
if (store.editing) return
if (event.altKey || event.ctrlKey || event.metaKey) return
if (/^[1-9]$/.test(event.key)) {
if (event.repeat || event.isComposing || store.minimized || sending()) return
const index = Number(event.key) - 1
if (index >= count()) return
if (intent.type === "question") {
event.preventDefault()
const rtl = event.key.startsWith("Arrow") && !event.altKey && root?.matches(":dir(rtl)")
const step = rtl ? -intent.step : intent.step
if (index === options().length) {
customToggle()
if (step < 0) return back()
return
}
selectOption(index)
focus(index)
if (!last()) jump(store.tab + 1)
return
}
if (!(target instanceof HTMLElement)) return
if (store.minimized || sending()) return
if (event.key === "ArrowDown" || event.key === "ArrowRight") {
if (intent.type === "number") {
event.preventDefault()
move(1)
if (intent.index === options().length) return customToggle()
selectOption(intent.index)
focus(intent.index)
return
}
if (event.key === "ArrowUp" || event.key === "ArrowLeft") {
event.preventDefault()
move(-1)
return
}
if (event.key === "Home") {
event.preventDefault()
focus(0)
return
}
if (event.key !== "End") return
event.preventDefault()
focus(count() - 1)
if (intent.type === "type") {
setStore("customOn", store.tab, true)
customUpdate(input() + event.key, true)
return startCustom()
}
if (intent.type === "swallow") return
if (intent.type === "commit") return commit()
if (intent.type === "activate") {
if (store.focus === options().length) return customToggle()
return selectOption(store.focus)
}
focus(intent.type === "edge" ? (intent.to === "first" ? 0 : count() - 1) : store.focus + intent.step)
}
const selectOption = (optIndex: number) => {
@@ -506,14 +562,37 @@ export const SessionQuestionDock: Component<{ request: FormInfo; onSubmit: () =>
jump(store.tab - 1)
}
// The new question's text and answers slide in from the side they come from and fade up; under reduced motion they
// only fade.
const arrive = (step: number) => {
arrivals.forEach((animation) => animation.cancel())
arrivals.length = 0
const reduced = prefersReducedMotion()
const x = (root?.matches(":dir(rtl)") ? -step : step) * 12
const frames = reduced
? [{ opacity: 0 }, { opacity: 1 }]
: [
{ opacity: 0, transform: `translate3d(${x}px,0,0)` },
{ opacity: 1, transform: "none" },
]
;[detailsRef, optionsRef].forEach((el) => {
if (el?.animate) arrivals.push(el.animate(frames, { duration: reduced ? 150 : 300, easing: SPRING_EASE }))
})
}
const jump = (tab: number) => {
if (sending() || tab === store.tab) return
const step = Math.sign(tab - store.tab)
// The highlight's index moves before the question does, so it lands on the new question's answer instead of
// gliding from the old one.
setStore("focus", pickFocus(tab))
setStore("tab", tab)
setStore("editing", false)
if (optionsRef) setStore("optionsHeight", optionsRef.scrollHeight)
if (!store.minimized) focus(pickFocus(tab))
if (store.minimized) return
// The answers box is still springing to the new list's height, so focusing must not scroll it.
focus(pickFocus(tab), { preventScroll: true })
arrive(step)
}
command.register("session.question.back", () => [
@@ -567,7 +646,9 @@ export const SessionQuestionDock: Component<{ request: FormInfo; onSubmit: () =>
onClick={() => jump(i())}
aria-label={language.t("ui.tool.questions.numbered", { number: i() + 1 })}
aria-current={i() === store.tab ? "step" : undefined}
/>
>
<span data-slot="question-progress-bar" aria-hidden="true" />
</button>
)}
</For>
</div>
@@ -583,7 +664,7 @@ export const SessionQuestionDock: Component<{ request: FormInfo; onSubmit: () =>
/>
</div>
</div>
<div data-slot="question-details">
<div data-slot="question-details" ref={(el) => (detailsRef = el)}>
<div
data-slot="question-text"
style={{
@@ -665,95 +746,107 @@ export const SessionQuestionDock: Component<{ request: FormInfo; onSubmit: () =>
aria-hidden={store.minimized || optionsOff() ? "true" : undefined}
classList={{ "pointer-events-none": hidden() > 0.1 }}
style={{
"max-height": `${Math.max(0, store.optionsHeight * (1 - hidden()))}px`,
height: store.listHeight > 0 ? `${Math.max(0, listHeight() * (1 - hidden()))}px` : undefined,
opacity: `${Math.max(0, Math.min(1, 1 - hidden()))}`,
visibility: optionsOff() ? "hidden" : "visible",
}}
// Space already acted on key down; its release must not click the button again.
onKeyUp={(event) => {
if (event.key !== " ") return
const where = zone(event.target)
if (where === "option" || where === "custom") event.preventDefault()
}}
>
<For each={options()}>
{(opt, i) => (
<Option
multi={multi()}
picked={picked(opt.value)}
label={opt.label}
description={opt.description}
shortcut={i() < 9 ? String(i() + 1) : undefined}
disabled={sending()}
ref={(el) => (optsRef[i()] = el)}
onFocus={() => setStore("focus", i())}
onClick={() => selectOption(i())}
/>
)}
</For>
<div data-slot="question-options-list" ref={(el) => (listRef = el)}>
<span data-slot="question-highlight" ref={(el) => (highlightRef = el)} aria-hidden="true" />
<For each={options()}>
{(opt, i) => (
<Option
multi={multi()}
picked={picked(opt.value)}
label={opt.label}
description={opt.description}
shortcut={i() < 9 ? String(i() + 1) : undefined}
disabled={sending()}
tabbable={store.focus === i()}
ref={(el) => (optsRef[i()] = el)}
onFocus={() => setStore("focus", i())}
onPointerMove={(event) => hover(i(), event)}
onClick={() => selectOption(i())}
/>
)}
</For>
<div
data-slot="question-option"
data-custom="true"
data-picked={on()}
data-editing={store.editing}
data-disabled={sending()}
onClick={(event) => {
if (event.target !== event.currentTarget || sending()) return
setStore("focus", options().length)
setStore("customOn", store.tab, true)
setStore("editing", true)
customUpdate(input(), true)
customInput?.focus()
}}
>
<button
type="button"
ref={customRef}
data-slot="question-custom-toggle"
role={multi() ? "checkbox" : "radio"}
aria-checked={on()}
aria-label={customLabel()}
aria-keyshortcuts={count() <= 9 ? String(count()) : undefined}
disabled={sending()}
onFocus={() => setStore("focus", options().length)}
onClick={customToggle}
<div
ref={(el) => (customRow = el)}
data-slot="question-option"
data-custom="true"
data-picked={on()}
data-editing={store.editing}
data-disabled={sending()}
onPointerMove={(event) => hover(options().length, event)}
onClick={(event) => {
if (event.target !== event.currentTarget || sending()) return
startCustom()
}}
>
<Mark multi={multi()} picked={on()} />
</button>
<TextInput
ref={(el) => (customInput = el)}
class="question-custom-field"
dir="auto"
aria-label={customLabel()}
placeholder={customLabel()}
value={input()}
disabled={sending()}
onFocus={() => {
if (focusFrame !== undefined) cancelAnimationFrame(focusFrame)
focusFrame = undefined
setStore("focus", options().length)
setStore("editing", true)
}}
onClick={() => {
setStore("customOn", store.tab, true)
customUpdate(input(), true)
}}
onBlur={() => setStore("editing", false)}
onKeyDown={(e) => {
if (e.key === "Escape") {
<button
type="button"
ref={customRef}
data-slot="question-custom-toggle"
role={multi() ? "checkbox" : "radio"}
aria-checked={on()}
aria-label={customLabel()}
aria-keyshortcuts={count() <= 9 ? String(count()) : undefined}
tabindex={store.focus === options().length ? 0 : -1}
disabled={sending()}
onFocus={() => setStore("focus", options().length)}
onClick={customToggle}
>
<Mark multi={multi()} picked={on()} />
</button>
<TextInput
ref={(el) => (customInput = el)}
class="question-custom-field"
dir="auto"
aria-label={customLabel()}
placeholder={customLabel()}
value={input()}
disabled={sending()}
onFocus={() => {
setStore("focus", options().length)
setStore("editing", true)
}}
onClick={() => {
setStore("customOn", store.tab, true)
customUpdate(input(), true)
}}
onBlur={() => setStore("editing", false)}
onKeyDown={(e) => {
if (e.isComposing || e.keyCode === 229) return
if (e.key === "Escape") {
e.preventDefault()
setStore("editing", false)
focus(options().length)
return
}
if ((e.metaKey || e.ctrlKey) && !e.altKey) return
if (e.key !== "Enter") return
e.preventDefault()
setStore("editing", false)
focus(options().length)
return
}
if ((e.metaKey || e.ctrlKey) && !e.altKey) return
if (e.key !== "Enter") return
e.preventDefault()
commitCustom()
}}
onInput={(e) => {
setStore("customOn", store.tab, true)
customUpdate(e.currentTarget.value, true)
}}
/>
if (!e.repeat) next()
}}
onInput={(e) => {
setStore("customOn", store.tab, true)
customUpdate(e.currentTarget.value, true)
}}
/>
</div>
</div>
</div>
</DockPrompt>
@@ -1,10 +1,37 @@
[data-component="dock-prompt"][data-kind="question"] {
--v2-question-answer-bg-selected: light-dark(#f5f8ff, #7698fd26);
/* A bounce-0 spring sampled for CSS: every selection, focus and progress change eases on it, so two answers trading
places always cross in the same frames. */
--question-spring: linear(
0,
0.04,
0.131,
0.243,
0.358,
0.466,
0.562,
0.645,
0.715,
0.774,
0.821,
0.859,
0.89,
0.914,
0.934,
0.949,
0.96,
0.97,
0.977,
0.982,
1
);
--question-quick: 200ms;
--question-settle: 300ms;
max-block-size: var(--question-prompt-max-height, 100dvh);
font-family: var(--v2-font-family-sans);
[data-color-scheme="dark"] & [data-slot="question-option"]:not([data-picked="true"]) {
[data-color-scheme="dark"] & [data-slot="question-option"]::before {
background-color: var(--v2-background-bg-layer-02);
}
@@ -106,20 +133,12 @@
cursor: pointer;
touch-action: manipulation;
&::after {
content: "";
inline-size: 14px;
block-size: 2px;
flex-shrink: 0;
background-color: var(--v2-background-bg-layer-04);
&[data-answered="true"] [data-slot="question-progress-bar"]::before {
transform: scaleX(1);
}
&[data-answered="true"]::after {
background-color: var(--v2-background-bg-accent);
}
&[data-active="true"]::after {
background-color: var(--v2-icon-icon-muted);
&[data-active="true"] [data-slot="question-progress-bar"]::after {
opacity: 1;
}
&:focus-visible {
@@ -133,6 +152,40 @@
}
}
[data-slot="question-progress-bar"] {
position: relative;
inline-size: 14px;
block-size: 2px;
flex-shrink: 0;
overflow: hidden;
background-color: var(--v2-background-bg-layer-04);
&::before,
&::after {
content: "";
position: absolute;
inset: 0;
}
/* Answering fills the segment from its start; the current question sits on top in its own colour. */
&::before {
background-color: var(--v2-background-bg-accent);
transform: scaleX(0);
transform-origin: left;
transition: transform var(--question-settle) var(--question-spring);
}
&::after {
background-color: var(--v2-icon-icon-muted);
opacity: 0;
transition: opacity var(--question-quick) var(--question-spring);
}
&:dir(rtl)::before {
transform-origin: right;
}
}
[data-slot="question-content"] {
display: flex;
flex-direction: column;
@@ -142,9 +195,6 @@
}
[data-slot="question-options"] {
display: flex;
flex-direction: column;
gap: 6px;
flex: 1 1 auto;
min-block-size: 0;
min-inline-size: 0;
@@ -158,6 +208,28 @@
}
}
[data-slot="question-options-list"] {
display: flex;
flex-direction: column;
gap: 6px;
position: relative;
isolation: isolate;
}
/* One highlight for the whole list, painted between the cards and their content. It glides to the highlighted
answer by its clip; the pick itself shows only as the radio dot or the check. */
[data-slot="question-highlight"] {
position: absolute;
inset: 0;
z-index: -1;
background:
linear-gradient(var(--v2-question-answer-bg-selected), var(--v2-question-answer-bg-selected)),
var(--v2-background-bg-layer-01);
clip-path: inset(0 0 100% round 6px);
pointer-events: none;
transition: clip-path var(--question-settle) var(--question-spring);
}
[data-slot="question-option"] {
display: flex;
align-items: flex-start;
@@ -165,25 +237,35 @@
flex-shrink: 0;
box-sizing: border-box;
inline-size: 100%;
position: relative;
padding: 10px;
border: 0;
border-radius: 6px;
background-color: var(--v2-background-bg-layer-01);
box-shadow: inset 0 0 0 0.5px var(--v2-border-border-base);
outline: none;
background: transparent;
color: var(--v2-text-text-base);
text-align: start;
cursor: pointer;
touch-action: manipulation;
transition: background-color 150ms ease;
&[data-picked="true"] {
background-image: linear-gradient(var(--v2-question-answer-bg-selected), var(--v2-question-answer-bg-selected));
box-shadow: inset 0 0 0 0.5px var(--v2-border-border-focus);
/* The card is drawn under the list's highlight and its hairline over it, so the highlight never hides an edge. */
&::before,
&::after {
content: "";
position: absolute;
inset: 0;
border-radius: inherit;
pointer-events: none;
}
&:focus-visible {
outline: 2px solid var(--v2-border-border-focus);
outline-offset: -2px;
&::before {
z-index: -2;
background-color: var(--v2-background-bg-layer-01);
}
&::after {
z-index: -1;
box-shadow: inset 0 0 0 0.5px var(--v2-border-border-base);
}
&:disabled,
@@ -212,16 +294,34 @@
flex: 0 0 16px;
padding: 0;
border: 0;
position: relative;
isolation: isolate;
border-radius: 4px;
background: linear-gradient(180deg, var(--v2-alpha-light-6), var(--v2-alpha-light-0)), var(--v2-background-bg-base);
box-shadow: inset 0 0 0 0.5px var(--v2-border-border-strong);
&::before {
content: "";
position: absolute;
inset: 0;
z-index: -1;
border-radius: inherit;
background:
linear-gradient(180deg, var(--v2-alpha-light-20), var(--v2-alpha-light-0)), var(--v2-background-bg-accent);
opacity: 0;
transition: opacity var(--question-quick) var(--question-spring);
}
[data-slot="icon-svg"] {
inline-size: 16px;
block-size: 16px;
flex: 0 0 16px;
opacity: 0;
color: var(--v2-icon-icon-contrast);
clip-path: inset(0 100% 0 0);
transition:
opacity var(--question-quick) var(--question-spring),
clip-path var(--question-settle) var(--question-spring);
}
&[data-type="radio"] {
@@ -236,19 +336,25 @@
background-color: var(--v2-grey-300);
box-shadow: var(--v2-elevation-elements);
opacity: 0;
transform: scale(0.3);
transition:
opacity var(--question-quick) var(--question-spring),
transform var(--question-settle) var(--question-spring);
}
&[data-picked="true"] {
background:
linear-gradient(180deg, var(--v2-alpha-light-20), var(--v2-alpha-light-0)), var(--v2-background-bg-accent);
&::before,
[data-slot="icon-svg"],
[data-slot="question-option-radio-dot"] {
opacity: 1;
}
&[data-type="radio"] {
box-shadow: none;
[data-slot="icon-svg"] {
clip-path: inset(0);
}
[data-slot="question-option-radio-dot"] {
transform: none;
}
}
}
@@ -324,8 +430,7 @@
touch-action: manipulation;
&:focus-visible {
outline: 2px solid var(--v2-border-border-focus);
outline-offset: 2px;
outline: none;
}
&:disabled {
@@ -413,16 +518,32 @@
[data-slot="question-progress-segment"]:hover:not(:disabled) {
background-color: var(--v2-overlay-simple-overlay-hover);
}
[data-slot="question-option"]:hover:not(:disabled):not([data-disabled="true"]):not([data-picked="true"]) {
background-color: var(--v2-background-bg-layer-02);
}
}
/* Reduced motion keeps the fades and drops the movement. */
:root[data-motion="reduce"] & {
[data-slot="question-option"],
.question-custom-field[data-component="text-input-v2"] {
[data-slot="question-highlight"] {
transition: none;
}
[data-slot="question-option-box"] [data-slot="icon-svg"] {
clip-path: none;
transition: opacity var(--question-quick) linear;
}
[data-slot="question-option-radio-dot"] {
transform: none;
transition: opacity var(--question-quick) linear;
}
[data-slot="question-progress-bar"]::before {
transform: none;
opacity: 0;
transition: opacity var(--question-quick) linear;
}
[data-slot="question-progress-segment"][data-answered="true"] [data-slot="question-progress-bar"]::before {
opacity: 1;
}
}
}