diff --git a/packages/app/component-tests/session-question-dock.spec.ts b/packages/app/component-tests/session-question-dock.spec.ts index 69ce16d6e45..bf798fecce5 100644 --- a/packages/app/component-tests/session-question-dock.spec.ts +++ b/packages/app/component-tests/session-question-dock.spec.ts @@ -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 } }) diff --git a/packages/app/src/session/requests/question-keys.test.ts b/packages/app/src/session/requests/question-keys.test.ts new file mode 100644 index 00000000000..c6a9cc12fa2 --- /dev/null +++ b/packages/app/src/session/requests/question-keys.test.ts @@ -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" }) + }) +}) diff --git a/packages/app/src/session/requests/question-keys.ts b/packages/app/src/session/requests/question-keys.ts new file mode 100644 index 00000000000..5637fe7f962 --- /dev/null +++ b/packages/app/src/session/requests/question-keys.ts @@ -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" } +} diff --git a/packages/app/src/session/requests/session-question-dock.tsx b/packages/app/src/session/requests/session-question-dock.tsx index 6eeff69171a..c091cf6b623 100644 --- a/packages/app/src/session/requests/session-question-dock.tsx +++ b/packages/app/src/session/requests/session-question-dock.tsx @@ -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() 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} > @@ -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} - /> + > +