diff --git a/packages/app/component-tests/session-question-dock.spec.ts b/packages/app/component-tests/session-question-dock.spec.ts index af37dc4830c..c7d07611b7a 100644 --- a/packages/app/component-tests/session-question-dock.spec.ts +++ b/packages/app/component-tests/session-question-dock.spec.ts @@ -2,1275 +2,1440 @@ import type { Locator } from "@playwright/test" import type { MotionKnob } from "@opencode/ui/motion-tuning" import { expect, sourceURL, story } from "../../stories/playwright/story" -story("resizes the dock to fit different answer counts", async ({ mount }) => { - const component = await mount("app-current-session-surface--question-answer-counts") +story( + "uses the original question cards by default and submits selected and custom answers", + 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/ }) + await expect(focused).toBeFocused() + const shortcuts = question.locator('[data-slot="question-option-shortcut"] [data-slot="keybind-v2-label"]') + await expect(shortcuts).toHaveText(["1", "2", "3"]) + await expect(question.getByText("Select one answer", { exact: true })).toBeVisible() + await page.keyboard.press("ArrowRight") + await expect(wide).toBeFocused() + await page.keyboard.press(" ") + await expect(wide).toBeChecked() + await expect(shortcuts).toHaveText(["1", "2", "3"]) + await expect(focused).not.toBeChecked() + + await page.evaluate(() => document.fonts.ready.then(() => undefined)) + const next = question.getByRole("button", { name: "Next", exact: true }) + const width = await next.evaluate((button) => button.getBoundingClientRect().width) + await next.click() + const files = question.getByRole("checkbox", { name: "Changed files", exact: true }) + const terminal = question.getByRole("checkbox", { name: "Terminal", exact: true }) + const input = question.getByRole("textbox", { name: "Type your own answer…", exact: true }) + const custom = question.getByRole("checkbox", { name: "Type your own answer…", exact: true }) + await expect(files).toBeFocused() + const submit = question.getByRole("button", { name: "Submit", exact: true }) + expect(await submit.evaluate((button) => button.getBoundingClientRect().width)).toBe(width) + await expect(shortcuts).toHaveText(["1", "2", "3", "4"]) + await files.click() + await terminal.click() + await expect(files).toBeChecked() + await expect(terminal).toBeChecked() + await expect(shortcuts).toHaveText(["1", "2", "3", "4"]) + await terminal.click() + await expect(terminal).not.toBeChecked() + await terminal.click() + await input.fill("Diagnostics") + await expect(custom).toBeChecked() + await input.press("Enter") + await expect(custom).toBeFocused() + await expect(input).toHaveValue("Diagnostics") + await question.getByRole("button", { name: "Back", exact: true }).click() + await expect(wide).toBeChecked() + await next.click() + await expect(files).toBeChecked() + await expect(terminal).toBeChecked() + await expect(custom).toBeChecked() + await submit.click() + await expect(question).toBeHidden() + }, +) + +story("keeps classic long answer lists inside the panel and scrolls them", async ({ mount, page }) => { + const component = await mount("session-question-switch--long-list") const question = component.locator('[data-component="dock-prompt"][data-kind="question"]') - const next = question.getByRole("button", { name: "Next", exact: true }) - await expect(question.getByRole("radio", { name: /Focused/ })).toBeFocused() - await expect(next).toBeEnabled() + const first = question.getByRole("checkbox", { name: /All typography/ }) + await expect(first).toBeFocused() + await page.evaluate(() => document.fonts.ready.then(() => undefined)) + await expect + .poll(() => + question.evaluate((root) => { + const options = root.querySelector('[data-slot="question-options"]')! + const box = root.getBoundingClientRect() - const height = () => question.evaluate((element) => element.getBoundingClientRect().height) - const initial = await height() - await next.click() - await expect.poll(height).toBeGreaterThan(initial) - await expect(question.getByRole("checkbox", { name: "Diagnostics", exact: true })).toBeVisible() + return { fits: box.top >= 0 && box.bottom <= innerHeight, scrolls: options.scrollHeight > options.clientHeight } + }), + ) + .toEqual({ fits: true, scrolls: true }) - const expanded = await height() - const back = question.getByRole("button", { name: "Back", exact: true }) - await expect(back).toBeEnabled() - await back.click() - await expect.poll(height).toBeLessThan(expanded) - await expect(question.getByRole("radio", { name: /Focused/ })).toBeVisible() + await first.press("End") + await expect(question.getByRole("checkbox", { name: "Type your own answer…", exact: true })).toBeFocused() + await expect(question.locator('[data-slot="question-option"][data-custom="true"]')).toBeInViewport({ ratio: 1 }) + await question.getByRole("button", { name: "Next", exact: true }).click() + await expect(question.getByRole("radio", { name: "One pull request", exact: true })).toBeFocused() }) -story("selects single answers and toggles multiple answers with number keys", async ({ mount }) => { - 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 customRadio = question.getByRole("radio", { name: "Type your own answer…", exact: true }) - const input = question.getByRole("textbox", { name: "Type your own answer…", exact: true }) - const next = question.getByRole("button", { name: "Next", exact: true }) - await expect(focused).toBeFocused() - - await focused.press("2") - await expect(wide).toBeChecked() - await expect(focused).not.toBeChecked() - await expect(wide).toBeFocused() - await next.press("1") - await expect(focused).toBeChecked() - await expect(wide).not.toBeChecked() - await focused.press("3") - await expect(customRadio).toBeChecked() - await expect(input).toBeFocused() - await expect(focused).not.toBeChecked() - await expect(wide).not.toBeChecked() - await input.press("Escape") - await expect(customRadio).toBeFocused() - await customRadio.press("2") - await expect(wide).toBeChecked() - await expect(customRadio).not.toBeChecked() - - await next.click() - const files = question.getByRole("checkbox", { name: "Changed files", exact: true }) - const terminal = question.getByRole("checkbox", { name: "Terminal", exact: true }) - const customCheckbox = question.getByRole("checkbox", { name: "Type your own answer…", exact: true }) - await expect(files).toBeFocused() - await files.press("1") - await expect(files).toBeChecked() - await files.press("2") - await expect(terminal).toBeChecked() - await expect(files).toBeChecked() - await terminal.press("2") - await expect(terminal).not.toBeChecked() - await expect(files).toBeChecked() - - await terminal.press("4") - await expect(customCheckbox).toBeChecked() - await expect(input).toBeFocused() - await expect(files).toBeChecked() - await expect(terminal).not.toBeChecked() - await input.press("Escape") - await expect(customCheckbox).toBeFocused() - await customCheckbox.press("4") - await expect(customCheckbox).not.toBeChecked() - await expect(files).toBeChecked() - 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("shows the highlight only for hover or the arrow keys, never for a click", 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 highlight = question.locator('[data-slot="question-highlight"]') - const clip = () => highlight.evaluate((element) => element.style.clipPath) - await expect(focused).toBeFocused() - await expect(highlight).toBeHidden() - - await wide.dispatchEvent("click") - await expect(wide).toBeChecked() - await expect(highlight).toBeHidden() - - await page.keyboard.press("1") - await expect(highlight).toBeHidden() - - await wide.hover() - await expect(highlight).toBeVisible() - await page.keyboard.press(" ") - await page.mouse.move(0, 0) - await expect(highlight).toBeHidden() - - await wide.hover() - await expect(highlight).toBeVisible() - const hovered = await clip() - await expect.poll(() => highlight.evaluate((element) => getComputedStyle(element).transitionDuration)).toBe("0s") - - await wide.click() - await expect(wide).toBeChecked() - await expect(highlight).toBeVisible() - expect(await clip()).toBe(hovered) - - await page.mouse.move(0, 0) - await expect(highlight).toBeHidden() - - await focused.click() - await page.mouse.move(0, 0) - await expect(focused).toBeChecked() - await expect(highlight).toBeHidden() - - await page.keyboard.press("ArrowDown") - await expect(highlight).toBeVisible() - await page.mouse.move(0, 0) - await expect(highlight).toBeVisible() - - await focused.hover() - await page.mouse.move(0, 0) - await expect(highlight).toBeHidden() -}) - -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() -}) - -// Presses each key after waiting its number of frames, and samples every frame until the switch is at rest: how visible -// the copies of the question text and of the answers are together, how many outgoing copies there are, how the live -// question text is moved, scaled and blurred, how far the count's last digit is rolled (in digit heights, down -// positive), where the progress row's bar is, and the footer: how visible Back is and whether a click at its middle -// reaches it, how visible the Next and Submit faces are, how visible the fainter of their two words is, and how wide -// the button they share shows. It also keeps the header's text and, for the count's last digit, each digit drawn and -// how visible it is. -const play = (question: Locator, keys: { key: string; after?: number }[]) => - question.evaluate(async (root, keys) => { - const opacity = (el: Element) => { - let value = 1 - - for (let node: Element | null = el; node && node !== root; node = node.parentElement) - value *= Number(getComputedStyle(node).opacity) - - return value - } - - const shown = (slot: string) => - [...root.querySelectorAll(`[data-slot="${slot}"]`)].reduce((sum, el) => sum + opacity(el), 0) - - const live = () => root.querySelector('[data-slot="question-details"]:not([data-ghost])') - - const mask = () => - ["question-details-frame", "question-options"].some((slot) => - (root.querySelector(`[data-slot="${slot}"]`)?.style.maskImage ?? "").includes("to right"), - ) - - const glyphs = () => - [ - ...root.querySelectorAll( - '[data-component="rolling-number"] [data-slot="rolling-number-digit"]:last-child [data-slot="rolling-number-glyph"]', - ), - ].flatMap((el) => { - const text = el.dataset.leaving ?? el.textContent ?? "" - - return text === "" ? [] : [{ text, shown: opacity(el) }] - }) - - const roll = () => { - const glyph = root.querySelector( - '[data-component="rolling-number"] [data-slot="rolling-number-digit"]:last-child [data-slot="rolling-number-glyph"]:not([data-leaving])', - ) - - if (!(glyph instanceof HTMLElement)) return 0 - - return ( - new DOMMatrix(getComputedStyle(glyph).transform === "none" ? undefined : getComputedStyle(glyph).transform) - .m42 / glyph.getBoundingClientRect().height - ) - } - - const bar = () => { - const current = root.querySelector('[data-slot="question-progress-current"]') - - return current ? current.getBoundingClientRect().left : 0 - } - - const back = root.querySelector('[data-slot="question-footer-back"]')! - const faces = [...root.querySelectorAll('[data-slot="question-advance-face"]')] - - const hit = () => { - const box = back.getBoundingClientRect() - - return back.contains(document.elementFromPoint(box.left + box.width / 2, box.top + box.height / 2)) - } - - // The faces are cut back from their start edge with `inset(top right bottom left)`. - const width = () => - Math.max( - ...faces.map((face) => { - if (opacity(face) < 0.01 || getComputedStyle(face).visibility === "hidden") return 0 - const inset = /inset\(([^)]*)\)/.exec(face.style.clipPath)?.[1]?.split(/\s+/).map(parseFloat) ?? [] - - return face.getBoundingClientRect().width - (inset[1] ?? 0) - (inset[3] ?? 0) - }), - ) - - // `click:N` clicks the Nth progress dash, `next` clicks the Next or Submit button in use, and `mod+Enter` presses the - // submit shortcut. - const mac = /Mac|iPhone|iPad|iPod/.test(navigator.platform) - - const press = (key: string) => { - if (key === "next") - return root - .querySelector('[data-slot="question-advance-face"][data-active="true"] button') - ?.click() - - if (key === "mod+Enter") - return (document.activeElement ?? root).dispatchEvent( - new KeyboardEvent("keydown", { key: "Enter", metaKey: mac, ctrlKey: !mac, bubbles: true, cancelable: true }), - ) - - const dash = /^click:(\d+)$/.exec(key)?.[1] - - if (dash) - return root.querySelectorAll('[data-slot="question-progress-segment"]')[Number(dash)]?.click() - - return (document.activeElement ?? root).dispatchEvent( - new KeyboardEvent("keydown", { key, bubbles: true, cancelable: true }), - ) - } - - const frames: { - text: number - answers: number - ghosts: number - x: number - scale: number - blur: boolean - mask: boolean - digit: number - bar: number - back: number - hit: boolean - next: number - submit: number - width: number - words: number - highlights: number - footer: boolean - animations: number - title: string - glyphs: { text: string; shown: number }[] - }[] = [] - - const queue = [...keys] - let wait = 0 - let still = 0 - - await new Promise((resolve) => { - const tick = () => { - while (queue.length > 0 && wait <= 0) { - const next = queue.shift()! - press(next.key) - wait = queue[0]?.after ?? 0 - } - - wait-- - const el = live() - const style = el ? getComputedStyle(el) : undefined - const matrix = new DOMMatrix(style?.transform === "none" ? undefined : style?.transform) - - const frame = { - text: shown("question-details"), - answers: shown("question-options-list"), - ghosts: root.querySelectorAll("[data-ghost]").length, - x: matrix.m41, - scale: matrix.m11, - blur: (style?.filter ?? "none") !== "none", - mask: mask(), - digit: roll(), - bar: bar(), - back: getComputedStyle(back).visibility === "hidden" ? 0 : opacity(back), - hit: hit(), - next: getComputedStyle(faces[0]!).visibility === "hidden" ? 0 : opacity(faces[0]!), - submit: getComputedStyle(faces[1]!).visibility === "hidden" ? 0 : opacity(faces[1]!), - width: width(), - words: Math.min( - ...faces.map((face) => - getComputedStyle(face).visibility === "hidden" - ? 0 - : opacity(face.querySelector('[data-slot="question-advance-label"]')!), - ), - ), - highlights: root.querySelectorAll('[data-slot="question-highlight"]').length, - footer: !!back.getAttribute("style") || faces.some((face) => !!face.getAttribute("style")), - animations: document.getAnimations().length, - title: root.querySelector('[data-slot="question-header-title"]')?.textContent ?? "", - glyphs: glyphs(), - } - - frames.push(frame) - - const resting = - queue.length === 0 && - frame.ghosts === 0 && - style?.transform === "none" && - !frame.blur && - !frame.mask && - frame.digit === 0 && - !frame.footer && - frame.bar === frames.at(-2)?.bar - - still = resting ? still + 1 : 0 - - if (still >= 3 || frames.length >= 240) return resolve() - requestAnimationFrame(tick) - } - - requestAnimationFrame(tick) - }) - - return frames - }, keys) - -// The dock's motion is off unless its knob is on, so these turn it on before the dock loads. -story.describe("with the question dock's motion on", () => { - story.beforeEach(({ page }) => - page.addInitScript(() => localStorage.setItem("opencode.motion.v2", JSON.stringify({ "question.motion": 1 }))), - ) - - story("keeps a question on screen while switching", async ({ mount }) => { +story( + "minimizes and restores classic questions immediately for reduced motion and keyboard actions", + 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 expect(question.getByRole("radio", { name: /Focused/ })).toBeFocused() + await question.getByRole("button", { name: "Minimize question", exact: true }).press("Enter") + expect( + await question + .locator('[data-slot="question-options"]') + .evaluate((options) => options.getBoundingClientRect().height), + ).toBe(0) + await question.getByRole("button", { name: "Restore question", exact: true }).press("Enter") + await expect(question.getByRole("radio", { name: /Focused/ })).toBeFocused() - const forward = await play(question, [{ key: "ArrowRight" }]) - await expect(question.getByRole("checkbox", { name: "Changed files", exact: true })).toBeVisible() - const backward = await play(question, [{ key: "ArrowLeft" }]) + await page.emulateMedia({ reducedMotion: "reduce" }) + await expect(page.locator("html")).toHaveAttribute("data-motion", "reduce") + await question.getByRole("radio", { name: /Focused/ }).click() + + const heights = await question.evaluate((root) => { + const options = root.querySelector('[data-slot="question-options"]')! + const before = options.getBoundingClientRect().height + root.querySelector('button[aria-label="Minimize question"]')!.click() + const minimized = options.getBoundingClientRect().height + root.querySelector('button[aria-label="Restore question"]')!.click() + + return { before, minimized, restored: options.getBoundingClientRect().height } + }) + + expect(heights.before).toBeGreaterThan(0) + expect(heights.minimized).toBe(0) + expect(heights.restored).toBe(heights.before) + }, +) + +story( + "opts into the new question UI in Experiments without losing answers and remembers the setting", + async ({ mount, page }) => { + const component = await mount("session-question-switch--experiments") + const question = component.locator('[data-component="dock-prompt"][data-kind="question"]') + const toggle = component.getByRole("switch", { name: "New question UI", exact: true }) + const input = question.getByRole("textbox", { name: "Type your own answer…", exact: true }) + await expect(toggle).not.toBeChecked() + await expect(question.getByRole("radio", { name: /Focused/ })).toBeFocused() + await input.fill("Split view") + await input.press("Enter") + await expect(question.getByRole("radio", { name: "Type your own answer…", exact: true })).toBeFocused() + + await toggle.press(" ") + await expect(question).toHaveAttribute("data-variant", "experimental") + await expect(question.locator('[data-slot="question-option-key"]')).toHaveText(["1", "2", "3"]) + await expect(input).toHaveValue("Split view") + await expect(question.getByRole("radio", { name: "Type your own answer…", exact: true })).toBeChecked() + + await page.reload() + await expect(toggle).toBeChecked() + await expect(question).toHaveAttribute("data-variant", "experimental") + await question.getByRole("radio", { name: /Wide/ }).click() + await toggle.press(" ") + await expect(question.locator('[data-slot="question-option-box"]')).toHaveCount(3) + await expect(question.getByRole("radio", { name: /Wide/ })).toBeChecked() + await page.reload() + await expect(toggle).not.toBeChecked() + await expect(question.locator('[data-slot="question-option-box"]')).toHaveCount(3) + }, +) + +story.describe("with the new question UI experiment enabled", () => { + story.beforeEach(({ page }) => + page.addInitScript(() => localStorage.setItem("settings.v3", JSON.stringify({ general: { newQuestionUI: true } }))), + ) + + story("resizes the dock to fit different answer counts", async ({ mount }) => { + const component = await mount("app-current-session-surface--question-answer-counts") + const question = component.locator('[data-component="dock-prompt"][data-kind="question"]') + const next = question.getByRole("button", { name: "Next", exact: true }) + await expect(question.getByRole("radio", { name: /Focused/ })).toBeFocused() + await expect(next).toBeEnabled() + + const height = () => question.evaluate((element) => element.getBoundingClientRect().height) + const initial = await height() + await next.click() + await expect.poll(height).toBeGreaterThan(initial) + await expect(question.getByRole("checkbox", { name: "Diagnostics", exact: true })).toBeVisible() + + const expanded = await height() + const back = question.getByRole("button", { name: "Back", exact: true }) + await expect(back).toBeEnabled() + await back.click() + await expect.poll(height).toBeLessThan(expanded) await expect(question.getByRole("radio", { name: /Focused/ })).toBeVisible() - await expect(question.locator("[data-ghost]")).toHaveCount(0) - - for (const frames of [forward, backward]) { - expect(frames.length).toBeLessThan(240) - expect(Math.min(...frames.map((frame) => frame.text))).toBeGreaterThanOrEqual(0.9) - expect(Math.min(...frames.map((frame) => frame.answers))).toBeGreaterThanOrEqual(0.9) - expect(frames.at(-1)).toMatchObject({ x: 0, scale: 1, blur: false }) - } - - expect(Math.min(...forward.map((frame) => frame.scale))).toBeLessThan(1) - expect(forward.some((frame) => frame.blur)).toBe(true) }) - story("switches questions without a second answer highlight", async ({ mount, page }) => { - const component = await mount("session-question-switch--question-series") + story("selects single answers and toggles multiple answers with number keys", async ({ mount }) => { + 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 customRadio = question.getByRole("radio", { name: "Type your own answer…", exact: true }) + const input = question.getByRole("textbox", { name: "Type your own answer…", exact: true }) + const next = question.getByRole("button", { name: "Next", exact: true }) + await expect(focused).toBeFocused() + + await focused.press("2") + await expect(wide).toBeChecked() + await expect(focused).not.toBeChecked() + await expect(wide).toBeFocused() + await next.press("1") + await expect(focused).toBeChecked() + await expect(wide).not.toBeChecked() + await focused.press("3") + await expect(customRadio).toBeChecked() + await expect(input).toBeFocused() + await expect(focused).not.toBeChecked() + await expect(wide).not.toBeChecked() + await input.press("Escape") + await expect(customRadio).toBeFocused() + await customRadio.press("2") + await expect(wide).toBeChecked() + await expect(customRadio).not.toBeChecked() + + await next.click() + const files = question.getByRole("checkbox", { name: "Changed files", exact: true }) + const terminal = question.getByRole("checkbox", { name: "Terminal", exact: true }) + const customCheckbox = question.getByRole("checkbox", { name: "Type your own answer…", exact: true }) + await expect(files).toBeFocused() + await files.press("1") + await expect(files).toBeChecked() + await files.press("2") + await expect(terminal).toBeChecked() + await expect(files).toBeChecked() + await terminal.press("2") + await expect(terminal).not.toBeChecked() + await expect(files).toBeChecked() + + await terminal.press("4") + await expect(customCheckbox).toBeChecked() + await expect(input).toBeFocused() + await expect(files).toBeChecked() + await expect(terminal).not.toBeChecked() + await input.press("Escape") + await expect(customCheckbox).toBeFocused() + await customCheckbox.press("4") + await expect(customCheckbox).not.toBeChecked() + await expect(files).toBeChecked() + 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"]') - await expect(question.getByRole("radio").first()).toBeFocused() + 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("shows the highlight only for the arrow keys, never for hover or a click", 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 highlight = question.locator('[data-slot="question-highlight"]') + const clip = () => highlight.evaluate((element) => element.style.clipPath) + await expect(focused).toBeFocused() + await expect(highlight).toBeHidden() + + await wide.dispatchEvent("click") + await expect(wide).toBeChecked() + await expect(highlight).toBeHidden() + + await page.keyboard.press("1") + await expect(highlight).toBeHidden() + + await wide.hover() + await expect(highlight).toBeHidden() + await expect(focused).toBeFocused() + + await wide.click() + await expect(wide).toBeChecked() + await expect(highlight).toBeHidden() + + await page.mouse.move(0, 0) + await expect(highlight).toBeHidden() + + await focused.click() + await page.mouse.move(0, 0) + await expect(focused).toBeChecked() + await expect(highlight).toBeHidden() + + await page.keyboard.press("ArrowDown") + await expect(wide).toBeFocused() + await expect(highlight).toBeVisible() + const keyboard = await clip() + await page.mouse.move(0, 0) await expect(highlight).toBeVisible() - // The leaving copy of the answers carries no highlight, so only the new question's answer is ever highlighted. - const frames = await play(question, [{ key: "ArrowRight" }]) - expect(frames.some((frame) => frame.ghosts > 0)).toBe(true) - expect(frames.every((frame) => frame.highlights === 1)).toBe(true) + await focused.hover() + await expect(wide).toBeFocused() + await expect(highlight).toBeVisible() + expect(await clip()).toBe(keyboard) + await question.getByRole("textbox", { name: "Type your own answer…", exact: true }).hover() + await expect(wide).toBeFocused() + expect(await clip()).toBe(keyboard) + await page.mouse.move(0, 0) + await expect(highlight).toBeVisible() }) - story("keeps one outgoing copy and a visible question through rapid switches", async ({ mount }) => { - const component = await mount("session-question-switch--question-series") + 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 options = question.locator('[data-slot="question-options"]') - await expect(question.getByRole("radio").first()).toBeFocused() - // From the middle question, so every run can go two either way and comes back. - await play(question, [{ key: "ArrowRight" }, { key: "ArrowRight", after: 30 }]) + 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() - const runs = [ - ["ArrowRight", "ArrowLeft"], - ["ArrowLeft", "ArrowRight"], - ["ArrowRight", "ArrowRight", "ArrowLeft", "ArrowLeft"], - ["ArrowLeft", "ArrowLeft", "ArrowRight", "ArrowRight"], - ] + 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() - for (const run of runs) - for (const after of [0, 1, 2, 4]) { - const frames = await play( - question, - run.map((key) => ({ key, after })), + 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() + }) + + // Presses each key after waiting its number of frames, and samples every frame until the switch is at rest: how visible + // the copies of the question text and of the answers are together, how many outgoing copies there are, how the live + // question text is moved, scaled and blurred, how far the count's last digit is rolled (in digit heights, down + // positive), where the progress row's bar is, and the footer: how visible Back is and whether a click at its middle + // reaches it, how visible the Next and Submit faces are, how visible the fainter of their two words is, and how wide + // the button they share shows. It also keeps the header's text and, for the count's last digit, each digit drawn and + // how visible it is. + const play = (question: Locator, keys: { key: string; after?: number }[]) => + question.evaluate(async (root, keys) => { + const opacity = (el: Element) => { + let value = 1 + + for (let node: Element | null = el; node && node !== root; node = node.parentElement) + value *= Number(getComputedStyle(node).opacity) + + return value + } + + const shown = (slot: string) => + [...root.querySelectorAll(`[data-slot="${slot}"]`)].reduce((sum, el) => sum + opacity(el), 0) + + const live = () => root.querySelector('[data-slot="question-details"]:not([data-ghost])') + + const mask = () => + ["question-details-frame", "question-options"].some((slot) => + (root.querySelector(`[data-slot="${slot}"]`)?.style.maskImage ?? "").includes("to right"), ) - const label = `${run.join(" ")} every ${after} frames` - expect(frames.length, label).toBeLessThan(240) - expect(Math.min(...frames.map((frame) => frame.text)), label).toBeGreaterThanOrEqual(0.5) - expect(Math.min(...frames.map((frame) => frame.answers)), label).toBeGreaterThanOrEqual(0.5) - expect(Math.max(...frames.map((frame) => frame.ghosts)), label).toBeLessThanOrEqual(2) - await expect(question.locator("[data-ghost]")).toHaveCount(0) - expect(await options.evaluate((el) => el.scrollLeft), label).toBe(0) + const glyphs = () => + [ + ...root.querySelectorAll( + '[data-component="rolling-number"] [data-slot="rolling-number-digit"]:last-child [data-slot="rolling-number-glyph"]', + ), + ].flatMap((el) => { + const text = el.dataset.leaving ?? el.textContent ?? "" + + return text === "" ? [] : [{ text, shown: opacity(el) }] + }) + + const roll = () => { + const glyph = root.querySelector( + '[data-component="rolling-number"] [data-slot="rolling-number-digit"]:last-child [data-slot="rolling-number-glyph"]:not([data-leaving])', + ) + + if (!(glyph instanceof HTMLElement)) return 0 + + return ( + new DOMMatrix(getComputedStyle(glyph).transform === "none" ? undefined : getComputedStyle(glyph).transform) + .m42 / glyph.getBoundingClientRect().height + ) } - }) - story("rolls the question count up going on and down going back", async ({ mount }) => { - const component = await mount("session-question-switch--question-series") - const question = component.locator('[data-component="dock-prompt"][data-kind="question"]') - const title = question.locator('[data-slot="question-header-title"]') - await expect(question.getByRole("radio").first()).toBeFocused() - await expect(title).toHaveText("1 of 5 questions") + const bar = () => { + const current = root.querySelector('[data-slot="question-progress-current"]') - // The new digit comes up from below going on, and down from above going back. - const forward = await play(question, [{ key: "ArrowRight" }]) - await expect(title).toHaveText("2 of 5 questions") - const backward = await play(question, [{ key: "ArrowLeft" }]) - await expect(title).toHaveText("1 of 5 questions") + return current ? current.getBoundingClientRect().left : 0 + } - expect(Math.max(...forward.map((frame) => frame.digit))).toBeGreaterThan(0.2) - expect(Math.min(...forward.map((frame) => frame.digit))).toBeGreaterThanOrEqual(0) - expect(Math.min(...backward.map((frame) => frame.digit))).toBeLessThan(-0.2) - expect(Math.max(...backward.map((frame) => frame.digit))).toBeLessThanOrEqual(0) + const back = root.querySelector('[data-slot="question-footer-back"]')! + const faces = [...root.querySelectorAll('[data-slot="question-advance-face"]')] - for (const frames of [forward, backward]) expect(frames.at(-1)?.digit).toBe(0) - await expect(question.locator('[data-slot="rolling-number-glyph"][data-leaving]')).toHaveAttribute( - "data-leaving", - "", - ) - }) + const hit = () => { + const box = back.getBoundingClientRect() - story("takes Next clicks and the submit shortcut while the footer is still moving", async ({ mount }) => { - const component = await mount("session-question-switch--question-series") - const question = component.locator('[data-component="dock-prompt"][data-kind="question"]') - const title = question.locator('[data-slot="question-header-title"]') - await expect(question.getByRole("radio").first()).toBeFocused() + return back.contains(document.elementFromPoint(box.left + box.width / 2, box.top + box.height / 2)) + } - // Two Next clicks and two submit shortcuts, two frames apart, each landing while Back is still fading in. - const frames = await play(question, [ - { key: "next" }, - { key: "next", after: 2 }, - { key: "mod+Enter", after: 2 }, - { key: "mod+Enter", after: 2 }, - ]) + // The faces are cut back from their start edge with `inset(top right bottom left)`. + const width = () => + Math.max( + ...faces.map((face) => { + if (opacity(face) < 0.01 || getComputedStyle(face).visibility === "hidden") return 0 + const inset = /inset\(([^)]*)\)/.exec(face.style.clipPath)?.[1]?.split(/\s+/).map(parseFloat) ?? [] - expect([2, 4, 6].every((index) => frames[index - 1]?.footer)).toBe(true) - await expect(question.getByRole("button", { name: "Submit", exact: true })).toBeVisible() - await expect(title).toHaveText("5 of 5 questions") - }) + return face.getBoundingClientRect().width - (inset[1] ?? 0) - (inset[3] ?? 0) + }), + ) - story("rolls the count on from where it is when it changes again mid-roll", async ({ mount }) => { - const component = await mount("session-question-switch--question-series") - const question = component.locator('[data-component="dock-prompt"][data-kind="question"]') - const title = question.locator('[data-slot="question-header-title"]') - await expect(question.getByRole("radio").first()).toBeFocused() + // `click:N` clicks the Nth progress dash, `next` clicks the Next or Submit button in use, and `mod+Enter` presses the + // submit shortcut. + const mac = /Mac|iPhone|iPad|iPod/.test(navigator.platform) - // 1 → 2 → 3 and 1 → 2 → 1, the second change a few frames into the first roll. - for (const [second, end] of [ - ["ArrowRight", "3"], - ["ArrowLeft", "1"], - ] as const) - for (const after of [1, 2, 4]) { - const frames = await play(question, [{ key: "ArrowRight" }, { key: second, after }]) - const label = `1 → 2 → ${end} after ${after} frames` + const press = (key: string) => { + if (key === "next") + return root + .querySelector('[data-slot="question-advance-face"][data-active="true"] button') + ?.click() - const shown = (frame: (typeof frames)[number], text: string) => - frame.glyphs.filter((glyph) => glyph.text === text).reduce((sum, glyph) => sum + glyph.shown, 0) - - // The digits drawn always add up to at least one whole digit, and the header's text never doubles a digit. - expect( - Math.min(...frames.map((frame) => frame.glyphs.reduce((sum, glyph) => sum + glyph.shown, 0))), - label, - ).toBeGreaterThanOrEqual(0.95) - expect( - frames.every((frame) => /^\d of 5 questions$/.test(frame.title.replace(/\s+/g, " ").trim())), - label, - ).toBe(true) - - // A 2 that had barely appeared goes back out and never crosses the middle. The frame sampled right after the - // second key shows the digits where the change found them; going back always sends the 2 out. - const at = shown(frames[after]!, "2") - - if (second === "ArrowLeft" || at < 0.45) - expect(Math.max(...frames.slice(after).map((frame) => shown(frame, "2"))), label).toBeLessThanOrEqual( - at + 0.02, + if (key === "mod+Enter") + return (document.activeElement ?? root).dispatchEvent( + new KeyboardEvent("keydown", { + key: "Enter", + metaKey: mac, + ctrlKey: !mac, + bubbles: true, + cancelable: true, + }), ) - expect(frames.at(-1)?.glyphs, label).toEqual([{ text: end, shown: 1 }]) - await expect(title).toHaveText(`${end} of 5 questions`) - await play(question, [{ key: "click:0" }]) + + const dash = /^click:(\d+)$/.exec(key)?.[1] + + if (dash) + return root.querySelectorAll('[data-slot="question-progress-segment"]')[Number(dash)]?.click() + + return (document.activeElement ?? root).dispatchEvent( + new KeyboardEvent("keydown", { key, bubbles: true, cancelable: true }), + ) } - }) - // Where the bar sits against each dash, from the inline start of the progress row. - const dashes = (question: Locator) => - question.evaluate((root) => ({ - dashes: [...root.querySelectorAll('[data-slot="question-progress-bar"]')].map( - (el) => el.getBoundingClientRect().left, - ), - bar: root.querySelector('[data-slot="question-progress-current"]')!.getBoundingClientRect().left, - })) + const frames: { + text: number + answers: number + ghosts: number + x: number + scale: number + blur: boolean + mask: boolean + digit: number + bar: number + back: number + hit: boolean + next: number + submit: number + width: number + words: number + highlights: number + footer: boolean + animations: number + title: string + glyphs: { text: string; shown: number }[] + }[] = [] - for (const dir of ["ltr", "rtl"] as const) - story(`slides the progress bar straight to a clicked dash (${dir})`, async ({ mount, page }) => { + const queue = [...keys] + let wait = 0 + let still = 0 + + await new Promise((resolve) => { + const tick = () => { + while (queue.length > 0 && wait <= 0) { + const next = queue.shift()! + press(next.key) + wait = queue[0]?.after ?? 0 + } + + wait-- + const el = live() + const style = el ? getComputedStyle(el) : undefined + const matrix = new DOMMatrix(style?.transform === "none" ? undefined : style?.transform) + + const frame = { + text: shown("question-details"), + answers: shown("question-options-list"), + ghosts: root.querySelectorAll("[data-ghost]").length, + x: matrix.m41, + scale: matrix.m11, + blur: (style?.filter ?? "none") !== "none", + mask: mask(), + digit: roll(), + bar: bar(), + back: getComputedStyle(back).visibility === "hidden" ? 0 : opacity(back), + hit: hit(), + next: getComputedStyle(faces[0]!).visibility === "hidden" ? 0 : opacity(faces[0]!), + submit: getComputedStyle(faces[1]!).visibility === "hidden" ? 0 : opacity(faces[1]!), + width: width(), + words: Math.min( + ...faces.map((face) => + getComputedStyle(face).visibility === "hidden" + ? 0 + : opacity(face.querySelector('[data-slot="question-advance-label"]')!), + ), + ), + highlights: root.querySelectorAll('[data-slot="question-highlight"]').length, + footer: !!back.getAttribute("style") || faces.some((face) => !!face.getAttribute("style")), + animations: document.getAnimations().length, + title: root.querySelector('[data-slot="question-header-title"]')?.textContent ?? "", + glyphs: glyphs(), + } + + frames.push(frame) + + const resting = + queue.length === 0 && + frame.ghosts === 0 && + style?.transform === "none" && + !frame.blur && + !frame.mask && + frame.digit === 0 && + !frame.footer && + frame.bar === frames.at(-2)?.bar + + still = resting ? still + 1 : 0 + + if (still >= 3 || frames.length >= 240) return resolve() + requestAnimationFrame(tick) + } + + requestAnimationFrame(tick) + }) + + return frames + }, keys) + + // The dock's motion is off unless its knob is on, so these turn it on before the dock loads. + story.describe("with the question dock's motion on", () => { + story.beforeEach(({ page }) => + page.addInitScript(() => localStorage.setItem("opencode.motion.v2", JSON.stringify({ "question.motion": 1 }))), + ) + + story("keeps a question on screen while switching", async ({ mount }) => { + const component = await mount("app-current-session-surface--question-request") + const question = component.locator('[data-component="dock-prompt"][data-kind="question"]') + await expect(question.getByRole("radio", { name: /Focused/ })).toBeFocused() + + const forward = await play(question, [{ key: "ArrowRight" }]) + await expect(question.getByRole("checkbox", { name: "Changed files", exact: true })).toBeVisible() + const backward = await play(question, [{ key: "ArrowLeft" }]) + await expect(question.getByRole("radio", { name: /Focused/ })).toBeVisible() + await expect(question.locator("[data-ghost]")).toHaveCount(0) + + for (const frames of [forward, backward]) { + expect(frames.length).toBeLessThan(240) + expect(Math.min(...frames.map((frame) => frame.text))).toBeGreaterThanOrEqual(0.9) + expect(Math.min(...frames.map((frame) => frame.answers))).toBeGreaterThanOrEqual(0.9) + expect(frames.at(-1)).toMatchObject({ x: 0, scale: 1, blur: false }) + } + + expect(Math.min(...forward.map((frame) => frame.scale))).toBeLessThan(1) + expect(forward.some((frame) => frame.blur)).toBe(true) + }) + + story("switches questions without a second answer highlight", async ({ mount, page }) => { + const component = await mount("session-question-switch--question-series") + const question = component.locator('[data-component="dock-prompt"][data-kind="question"]') + const highlight = question.locator('[data-slot="question-highlight"]') + await expect(question.getByRole("radio").first()).toBeFocused() + await page.keyboard.press("ArrowDown") + await expect(highlight).toBeVisible() + + // The leaving copy of the answers carries no highlight, so only the new question's answer is ever highlighted. + const frames = await play(question, [{ key: "ArrowRight" }]) + expect(frames.some((frame) => frame.ghosts > 0)).toBe(true) + expect(frames.every((frame) => frame.highlights === 1)).toBe(true) + }) + + story("keeps one outgoing copy and a visible question through rapid switches", async ({ mount }) => { + const component = await mount("session-question-switch--question-series") + const question = component.locator('[data-component="dock-prompt"][data-kind="question"]') + const options = question.locator('[data-slot="question-options"]') + await expect(question.getByRole("radio").first()).toBeFocused() + // From the middle question, so every run can go two either way and comes back. + await play(question, [{ key: "ArrowRight" }, { key: "ArrowRight", after: 30 }]) + + const runs = [ + ["ArrowRight", "ArrowLeft"], + ["ArrowLeft", "ArrowRight"], + ["ArrowRight", "ArrowRight", "ArrowLeft", "ArrowLeft"], + ["ArrowLeft", "ArrowLeft", "ArrowRight", "ArrowRight"], + ] + + for (const run of runs) + for (const after of [0, 1, 2, 4]) { + const frames = await play( + question, + run.map((key) => ({ key, after })), + ) + + const label = `${run.join(" ")} every ${after} frames` + expect(frames.length, label).toBeLessThan(240) + expect(Math.min(...frames.map((frame) => frame.text)), label).toBeGreaterThanOrEqual(0.5) + expect(Math.min(...frames.map((frame) => frame.answers)), label).toBeGreaterThanOrEqual(0.5) + expect(Math.max(...frames.map((frame) => frame.ghosts)), label).toBeLessThanOrEqual(2) + await expect(question.locator("[data-ghost]")).toHaveCount(0) + expect(await options.evaluate((el) => el.scrollLeft), label).toBe(0) + } + }) + + story("rolls the question count up going on and down going back", async ({ mount }) => { + const component = await mount("session-question-switch--question-series") + const question = component.locator('[data-component="dock-prompt"][data-kind="question"]') + const title = question.locator('[data-slot="question-header-title"]') + await expect(question.getByRole("radio").first()).toBeFocused() + await expect(title).toHaveText("1 of 5 questions") + + // The new digit comes up from below going on, and down from above going back. + const forward = await play(question, [{ key: "ArrowRight" }]) + await expect(title).toHaveText("2 of 5 questions") + const backward = await play(question, [{ key: "ArrowLeft" }]) + await expect(title).toHaveText("1 of 5 questions") + + expect(Math.max(...forward.map((frame) => frame.digit))).toBeGreaterThan(0.2) + expect(Math.min(...forward.map((frame) => frame.digit))).toBeGreaterThanOrEqual(0) + expect(Math.min(...backward.map((frame) => frame.digit))).toBeLessThan(-0.2) + expect(Math.max(...backward.map((frame) => frame.digit))).toBeLessThanOrEqual(0) + + for (const frames of [forward, backward]) expect(frames.at(-1)?.digit).toBe(0) + await expect(question.locator('[data-slot="rolling-number-glyph"][data-leaving]')).toHaveAttribute( + "data-leaving", + "", + ) + }) + + story("takes Next clicks and the submit shortcut while the footer is still moving", async ({ mount }) => { + const component = await mount("session-question-switch--question-series") + const question = component.locator('[data-component="dock-prompt"][data-kind="question"]') + const title = question.locator('[data-slot="question-header-title"]') + await expect(question.getByRole("radio").first()).toBeFocused() + + // Two Next clicks and two submit shortcuts, two frames apart, each landing while Back is still fading in. + const frames = await play(question, [ + { key: "next" }, + { key: "next", after: 2 }, + { key: "mod+Enter", after: 2 }, + { key: "mod+Enter", after: 2 }, + ]) + + expect([2, 4, 6].every((index) => frames[index - 1]?.footer)).toBe(true) + await expect(question.getByRole("button", { name: "Submit", exact: true })).toBeVisible() + await expect(title).toHaveText("5 of 5 questions") + }) + + story("rolls the count on from where it is when it changes again mid-roll", async ({ mount }) => { + const component = await mount("session-question-switch--question-series") + const question = component.locator('[data-component="dock-prompt"][data-kind="question"]') + const title = question.locator('[data-slot="question-header-title"]') + await expect(question.getByRole("radio").first()).toBeFocused() + + // 1 → 2 → 3 and 1 → 2 → 1, the second change a few frames into the first roll. + for (const [second, end] of [ + ["ArrowRight", "3"], + ["ArrowLeft", "1"], + ] as const) + for (const after of [1, 2, 4]) { + const frames = await play(question, [{ key: "ArrowRight" }, { key: second, after }]) + const label = `1 → 2 → ${end} after ${after} frames` + + const shown = (frame: (typeof frames)[number], text: string) => + frame.glyphs.filter((glyph) => glyph.text === text).reduce((sum, glyph) => sum + glyph.shown, 0) + + // The digits drawn always add up to at least one whole digit, and the header's text never doubles a digit. + expect( + Math.min(...frames.map((frame) => frame.glyphs.reduce((sum, glyph) => sum + glyph.shown, 0))), + label, + ).toBeGreaterThanOrEqual(0.95) + expect( + frames.every((frame) => /^\d of 5 questions$/.test(frame.title.replace(/\s+/g, " ").trim())), + label, + ).toBe(true) + + // A 2 that had barely appeared goes back out and never crosses the middle. The frame sampled right after the + // second key shows the digits where the change found them; going back always sends the 2 out. + const at = shown(frames[after]!, "2") + + if (second === "ArrowLeft" || at < 0.45) + expect(Math.max(...frames.slice(after).map((frame) => shown(frame, "2"))), label).toBeLessThanOrEqual( + at + 0.02, + ) + expect(frames.at(-1)?.glyphs, label).toEqual([{ text: end, shown: 1 }]) + await expect(title).toHaveText(`${end} of 5 questions`) + await play(question, [{ key: "click:0" }]) + } + }) + + // Where the bar sits against each dash, from the inline start of the progress row. + const dashes = (question: Locator) => + question.evaluate((root) => ({ + dashes: [...root.querySelectorAll('[data-slot="question-progress-bar"]')].map( + (el) => el.getBoundingClientRect().left, + ), + bar: root.querySelector('[data-slot="question-progress-current"]')!.getBoundingClientRect().left, + })) + + for (const dir of ["ltr", "rtl"] as const) + story(`slides the progress bar straight to a clicked dash (${dir})`, async ({ mount, page }) => { + const component = await mount("session-question-switch--question-series") + const question = component.locator('[data-component="dock-prompt"][data-kind="question"]') + await expect(question.getByRole("radio").first()).toBeFocused() + await page.evaluate((dir) => document.documentElement.setAttribute("dir", dir), dir) + + const start = await dashes(question) + expect(start.bar).toBeCloseTo(start.dashes[0]!, 0) + + // Jumping from the first question to the fourth slides the one bar across the dashes in between, one way only. + const frames = await play(question, [{ key: "click:3" }]) + const end = await dashes(question) + const bars = frames.map((frame) => frame.bar) + const way = Math.sign(end.dashes[3]! - end.dashes[0]!) + expect(end.bar).toBeCloseTo(end.dashes[3]!, 0) + expect(bars.at(-1)).toBeCloseTo(end.dashes[3]!, 0) + expect(bars.some((x) => way * (x - end.dashes[0]!) > 1 && way * (x - end.dashes[3]!) < -1)).toBe(true) + expect(bars.slice(1).every((x, i) => way * (x - bars[i]!) >= -0.01)).toBe(true) + await expect(question.locator('[data-slot="question-header-title"]')).toHaveText("4 of 5 questions") + + // In RTL the dashes run from the right, so the bar moves left. + expect(way).toBe(dir === "rtl" ? -1 : 1) + }) + + story("swaps questions, the count and the progress bar at once under reduced motion", async ({ mount, page }) => { + await page.emulateMedia({ reducedMotion: "reduce" }) const component = await mount("session-question-switch--question-series") const question = component.locator('[data-component="dock-prompt"][data-kind="question"]') await expect(question.getByRole("radio").first()).toBeFocused() - await page.evaluate((dir) => document.documentElement.setAttribute("dir", dir), dir) - const start = await dashes(question) - expect(start.bar).toBeCloseTo(start.dashes[0]!, 0) + const frames = await play(question, [{ key: "ArrowRight" }]) + expect(frames.every((frame) => frame.ghosts === 0 && frame.x === 0 && frame.scale === 1 && !frame.blur)).toBe( + true, + ) + expect(Math.min(...frames.map((frame) => frame.text))).toBe(1) + expect(frames.every((frame) => frame.digit === 0)).toBe(true) + expect(new Set(frames.map((frame) => Math.round(frame.bar))).size).toBe(1) + expect(frames.every((frame) => frame.back === 1 && !frame.footer)).toBe(true) + await expect(question.locator('[data-slot="question-header-title"]')).toHaveText("2 of 5 questions") - // Jumping from the first question to the fourth slides the one bar across the dashes in between, one way only. - const frames = await play(question, [{ key: "click:3" }]) - const end = await dashes(question) - const bars = frames.map((frame) => frame.bar) - const way = Math.sign(end.dashes[3]! - end.dashes[0]!) - expect(end.bar).toBeCloseTo(end.dashes[3]!, 0) - expect(bars.at(-1)).toBeCloseTo(end.dashes[3]!, 0) - expect(bars.some((x) => way * (x - end.dashes[0]!) > 1 && way * (x - end.dashes[3]!) < -1)).toBe(true) - expect(bars.slice(1).every((x, i) => way * (x - bars[i]!) >= -0.01)).toBe(true) - await expect(question.locator('[data-slot="question-header-title"]')).toHaveText("4 of 5 questions") - - // In RTL the dashes run from the right, so the bar moves left. - expect(way).toBe(dir === "rtl" ? -1 : 1) + const last = await play(question, [{ key: "click:4" }]) + expect(last.every((frame) => frame.next === 0 && frame.submit === 1 && !frame.footer)).toBe(true) }) - story("swaps questions, the count and the progress bar at once under reduced motion", async ({ mount, page }) => { - await page.emulateMedia({ reducedMotion: "reduce" }) - const component = await mount("session-question-switch--question-series") - const question = component.locator('[data-component="dock-prompt"][data-kind="question"]') - await expect(question.getByRole("radio").first()).toBeFocused() + // Rises, or falls, all the way from one end to the other through values in between, never turning back. + const glides = (values: number[], from: number, to: number) => { + const way = Math.sign(to - from) + expect(values.at(0)! * way).toBeLessThan(to * way) + expect(values.at(-1)).toBeCloseTo(to, 2) + expect( + values.some( + (value) => way * (value - from) > 0.02 * way * (to - from) && way * (to - value) > 0.02 * way * (to - from), + ), + ).toBe(true) + expect(values.slice(1).every((value, i) => way * (value - values[i]!) >= -0.01)).toBe(true) + } - const frames = await play(question, [{ key: "ArrowRight" }]) - expect(frames.every((frame) => frame.ghosts === 0 && frame.x === 0 && frame.scale === 1 && !frame.blur)).toBe(true) - expect(Math.min(...frames.map((frame) => frame.text))).toBe(1) - expect(frames.every((frame) => frame.digit === 0)).toBe(true) - expect(new Set(frames.map((frame) => Math.round(frame.bar))).size).toBe(1) - expect(frames.every((frame) => frame.back === 1 && !frame.footer)).toBe(true) - await expect(question.locator('[data-slot="question-header-title"]')).toHaveText("2 of 5 questions") + story("fades Back in and out and turns Next into Submit with the switch", async ({ mount }) => { + const component = await mount("session-question-switch--question-series") + const question = component.locator('[data-component="dock-prompt"][data-kind="question"]') + const back = question.locator('[data-slot="question-footer-back"]') + await expect(question.getByRole("radio").first()).toBeFocused() + await expect(question.getByRole("button", { name: "Back", exact: true })).toHaveCount(0) - const last = await play(question, [{ key: "click:4" }]) - expect(last.every((frame) => frame.next === 0 && frame.submit === 1 && !frame.footer)).toBe(true) - }) - - // Rises, or falls, all the way from one end to the other through values in between, never turning back. - const glides = (values: number[], from: number, to: number) => { - const way = Math.sign(to - from) - expect(values.at(0)! * way).toBeLessThan(to * way) - expect(values.at(-1)).toBeCloseTo(to, 2) - expect( - values.some( - (value) => way * (value - from) > 0.02 * way * (to - from) && way * (to - value) > 0.02 * way * (to - from), - ), - ).toBe(true) - expect(values.slice(1).every((value, i) => way * (value - values[i]!) >= -0.01)).toBe(true) - } - - story("fades Back in and out and turns Next into Submit with the switch", async ({ mount }) => { - const component = await mount("session-question-switch--question-series") - const question = component.locator('[data-component="dock-prompt"][data-kind="question"]') - const back = question.locator('[data-slot="question-footer-back"]') - await expect(question.getByRole("radio").first()).toBeFocused() - await expect(question.getByRole("button", { name: "Back", exact: true })).toHaveCount(0) - - // Going on from the first question, Back comes in and can be clicked at once, while Next stays where it is. - const nextBox = await question.getByRole("button", { name: "Next", exact: true }).boundingBox() - const arrive = await play(question, [{ key: "ArrowRight" }]) - glides( - arrive.map((frame) => frame.back), - 0, - 1, - ) - expect(arrive.every((frame) => frame.hit && frame.next === 1 && frame.submit === 0)).toBe(true) - expect(await question.getByRole("button", { name: "Next", exact: true }).boundingBox()).toMatchObject({ - x: nextBox!.x, - width: nextBox!.width, - }) - - // On to the last question, Next fades into Submit while the button's edge sweeps to Submit's width. - await play(question, [{ key: "click:3" }]) - - const widths = await question.evaluate((root) => - [...root.querySelectorAll('[data-slot="question-advance-face"]')].map( - (face) => face.getBoundingClientRect().width, - ), - ) - - const submit = await play(question, [{ key: "ArrowRight" }]) - glides( - submit.map((frame) => frame.next), - 1, - 0, - ) - glides( - submit.map((frame) => frame.submit), - 0, - 1, - ) - glides( - submit.map((frame) => frame.width), - widths[0]!, - widths[1]!, - ) - expect(submit.some((frame) => frame.next > 0.1 && frame.submit > 0.1)).toBe(true) - // The buttons overlap, but the words "Next" and "Submit" are never both legible at once. - expect(Math.max(...submit.map((frame) => frame.words))).toBeLessThan(0.25) - expect(submit.every((frame) => frame.back === 1)).toBe(true) - - // Back to the first question, Back goes, and cannot be clicked from the moment it starts to. - const leave = await play(question, [{ key: "click:0" }]) - glides( - leave.map((frame) => frame.back), - 1, - 0, - ) - expect(leave.some((frame) => frame.hit)).toBe(false) - expect(leave.at(-1)).toMatchObject({ next: 1, submit: 0, footer: false }) - await expect(back).toHaveAttribute("inert", "") - }) - - story("stops a switch where it is when the knob turns off", async ({ mount }) => { - const component = await mount("session-question-switch--question-series") - const question = component.locator('[data-component="dock-prompt"][data-kind="question"]') - await expect(question.getByRole("radio").first()).toBeFocused() - - const frames = await question.evaluate( - async (root, tuning) => { - const { motionTuning } = await import(tuning) - const knob = motionTuning.list().find((item: MotionKnob) => item.id === "question.motion") - const frame = () => new Promise((resolve) => requestAnimationFrame(resolve)) - - const sample = () => ({ - animations: document.getAnimations().length, - heights: [...root.querySelectorAll("*")].filter((el) => el.style.height).length, - ghosts: root.querySelectorAll("[data-ghost]").length, - }) - - document.activeElement!.dispatchEvent( - new KeyboardEvent("keydown", { key: "ArrowRight", bubbles: true, cancelable: true }), - ) - await frame() - await frame() - const moving = sample() - motionTuning.set(knob, false) - await frame() - await frame() - - return { moving, after: sample() } - }, - sourceURL(new URL("../../ui/src/motion-tuning.ts", import.meta.url)), - ) - - expect(frames.moving.heights + frames.moving.ghosts).toBeGreaterThan(0) - expect(frames.after).toEqual({ animations: 0, heights: 0, ghosts: 0 }) - }) -}) - -story("switches questions, folds and submits on the same frame with the dock's motion off", async ({ mount, page }) => { - const component = await mount("session-question-switch--question-series") - const question = component.locator('[data-component="dock-prompt"][data-kind="question"]') - const title = question.locator('[data-slot="question-header-title"]') - await expect(question.getByRole("radio").first()).toBeFocused() - await expect(question.locator('[data-component="rolling-number"]')).toHaveCount(0) - await expect(question.locator('[data-slot="question-progress-track"]')).toHaveCount(0) - - // From the frame of the key on, the next question is at rest: no outgoing copy, nothing moved, faded or blurred, - // and no animation or transition running anywhere on the page. - for (const [key, count] of [ - ["ArrowRight", "2 of 5 questions"], - ["click:3", "4 of 5 questions"], - ["ArrowRight", "5 of 5 questions"], - ] as const) { - const frames = await play(question, [{ key }]) - expect(frames.length, key).toBeLessThanOrEqual(4) - expect( - frames.every( - (frame) => - frame.ghosts === 0 && - frame.x === 0 && - frame.scale === 1 && - !frame.blur && - !frame.mask && - frame.text === 1 && - frame.answers === 1 && - frame.back === 1 && - !frame.footer && - frame.animations === 0, - ), - key, - ).toBe(true) - await expect(title).toHaveText(count) - } - - // Minimizing and restoring fold the answers away and back at once. - const fold = (label: string) => - question.evaluate(async (root, label) => { - const options = root.querySelector('[data-slot="question-options"]')! - const list = root.querySelector('[data-slot="question-options-list"]')! - - const sample = () => ({ - height: Math.round(options.getBoundingClientRect().height), - list: Math.round(list.getBoundingClientRect().height), - hidden: getComputedStyle(options).visibility === "hidden", - animations: document.getAnimations().length, + // Going on from the first question, Back comes in and can be clicked at once, while Next stays where it is. + const nextBox = await question.getByRole("button", { name: "Next", exact: true }).boundingBox() + const arrive = await play(question, [{ key: "ArrowRight" }]) + glides( + arrive.map((frame) => frame.back), + 0, + 1, + ) + expect(arrive.every((frame) => frame.hit && frame.next === 1 && frame.submit === 0)).toBe(true) + expect(await question.getByRole("button", { name: "Next", exact: true }).boundingBox()).toMatchObject({ + x: nextBox!.x, + width: nextBox!.width, }) - root.querySelector(`button[aria-label="${label}"]`)!.click() - const frames = [sample()] + // On to the last question, Next fades into Submit while the button's edge sweeps to Submit's width. + await play(question, [{ key: "click:3" }]) - for (let i = 0; i < 3; i++) { - await new Promise((resolve) => requestAnimationFrame(resolve)) - frames.push(sample()) + const widths = await question.evaluate((root) => + [...root.querySelectorAll('[data-slot="question-advance-face"]')].map( + (face) => face.getBoundingClientRect().width, + ), + ) + + const submit = await play(question, [{ key: "ArrowRight" }]) + glides( + submit.map((frame) => frame.next), + 1, + 0, + ) + glides( + submit.map((frame) => frame.submit), + 0, + 1, + ) + glides( + submit.map((frame) => frame.width), + widths[0]!, + widths[1]!, + ) + expect(submit.some((frame) => frame.next > 0.1 && frame.submit > 0.1)).toBe(true) + // The buttons overlap, but the words "Next" and "Submit" are never both legible at once. + expect(Math.max(...submit.map((frame) => frame.words))).toBeLessThan(0.25) + expect(submit.every((frame) => frame.back === 1)).toBe(true) + + // Back to the first question, Back goes, and cannot be clicked from the moment it starts to. + const leave = await play(question, [{ key: "click:0" }]) + glides( + leave.map((frame) => frame.back), + 1, + 0, + ) + expect(leave.some((frame) => frame.hit)).toBe(false) + expect(leave.at(-1)).toMatchObject({ next: 1, submit: 0, footer: false }) + await expect(back).toHaveAttribute("inert", "") + }) + + story("stops a switch where it is when the knob turns off", async ({ mount }) => { + const component = await mount("session-question-switch--question-series") + const question = component.locator('[data-component="dock-prompt"][data-kind="question"]') + await expect(question.getByRole("radio").first()).toBeFocused() + + const frames = await question.evaluate( + async (root, tuning) => { + const { motionTuning } = await import(tuning) + const knob = motionTuning.list().find((item: MotionKnob) => item.id === "question.motion") + const frame = () => new Promise((resolve) => requestAnimationFrame(resolve)) + + const sample = () => ({ + animations: document.getAnimations().length, + heights: [...root.querySelectorAll("*")].filter((el) => el.style.height).length, + ghosts: root.querySelectorAll("[data-ghost]").length, + }) + + document.activeElement!.dispatchEvent( + new KeyboardEvent("keydown", { key: "ArrowRight", bubbles: true, cancelable: true }), + ) + await frame() + await frame() + const moving = sample() + motionTuning.set(knob, false) + await frame() + await frame() + + return { moving, after: sample() } + }, + sourceURL(new URL("../../ui/src/motion-tuning.ts", import.meta.url)), + ) + + expect(frames.moving.heights + frames.moving.ghosts).toBeGreaterThan(0) + expect(frames.after).toEqual({ animations: 0, heights: 0, ghosts: 0 }) + }) + }) + + story( + "switches questions, folds and submits on the same frame with the dock's motion off", + async ({ mount, page }) => { + const component = await mount("session-question-switch--question-series") + const question = component.locator('[data-component="dock-prompt"][data-kind="question"]') + const title = question.locator('[data-slot="question-header-title"]') + await expect(question.getByRole("radio").first()).toBeFocused() + await expect(question.locator('[data-component="rolling-number"]')).toHaveCount(0) + await expect(question.locator('[data-slot="question-progress-track"]')).toHaveCount(0) + + // From the frame of the key on, the next question is at rest: no outgoing copy, nothing moved, faded or blurred, + // and no animation or transition running anywhere on the page. + for (const [key, count] of [ + ["ArrowRight", "2 of 5 questions"], + ["click:3", "4 of 5 questions"], + ["ArrowRight", "5 of 5 questions"], + ] as const) { + const frames = await play(question, [{ key }]) + expect(frames.length, key).toBeLessThanOrEqual(4) + expect( + frames.every( + (frame) => + frame.ghosts === 0 && + frame.x === 0 && + frame.scale === 1 && + !frame.blur && + !frame.mask && + frame.text === 1 && + frame.answers === 1 && + frame.back === 1 && + !frame.footer && + frame.animations === 0, + ), + key, + ).toBe(true) + await expect(title).toHaveText(count) } - return frames - }, label) + // Minimizing and restoring fold the answers away and back at once. + const fold = (label: string) => + question.evaluate(async (root, label) => { + const options = root.querySelector('[data-slot="question-options"]')! + const list = root.querySelector('[data-slot="question-options-list"]')! - // The last question's answers may be cut to the dock's height, so they come back to the height they rest at. - const resting = await question - .locator('[data-slot="question-options"]') - .evaluate((el) => Math.round(el.getBoundingClientRect().height)) + const sample = () => ({ + height: Math.round(options.getBoundingClientRect().height), + list: Math.round(list.getBoundingClientRect().height), + hidden: getComputedStyle(options).visibility === "hidden", + animations: document.getAnimations().length, + }) - const folded = await fold("Minimize question") - expect(folded.every((frame) => frame.height === 0 && frame.hidden && frame.animations === 0)).toBe(true) - const restored = await fold("Restore question") - expect( - restored.every((frame) => frame.height > 0 && frame.height === resting && !frame.hidden && frame.animations === 0), - ).toBe(true) + root.querySelector(`button[aria-label="${label}"]`)!.click() + const frames = [sample()] - // Submitting swaps the dock for the composer on one frame, with no closing flight. - const submitted = await page.evaluate(async () => { - const dock = () => document.querySelector('[data-component="dock-prompt"][data-kind="question"]') - const moving = () => !!document.querySelector("[data-moving]") - document.querySelector('[data-slot="question-advance-face"][data-active="true"] button')!.click() + for (let i = 0; i < 3; i++) { + await new Promise((resolve) => requestAnimationFrame(resolve)) + frames.push(sample()) + } - for (let i = 0; i < 120 && dock() && !moving(); i++) await new Promise((resolve) => requestAnimationFrame(resolve)) - const frames = [] + return frames + }, label) - for (let i = 0; i < 3; i++) { - frames.push({ dock: !!dock(), moving: moving(), animations: document.getAnimations().length }) - await new Promise((resolve) => requestAnimationFrame(resolve)) - } + // The last question's answers may be cut to the dock's height, so they come back to the height they rest at. + const resting = await question + .locator('[data-slot="question-options"]') + .evaluate((el) => Math.round(el.getBoundingClientRect().height)) - return frames + const folded = await fold("Minimize question") + expect(folded.every((frame) => frame.height === 0 && frame.hidden && frame.animations === 0)).toBe(true) + const restored = await fold("Restore question") + expect( + restored.every( + (frame) => frame.height > 0 && frame.height === resting && !frame.hidden && frame.animations === 0, + ), + ).toBe(true) + + // Submitting swaps the dock for the composer on one frame, with no closing flight. + const submitted = await page.evaluate(async () => { + const dock = () => document.querySelector('[data-component="dock-prompt"][data-kind="question"]') + const moving = () => !!document.querySelector("[data-moving]") + document.querySelector('[data-slot="question-advance-face"][data-active="true"] button')!.click() + + for (let i = 0; i < 120 && dock() && !moving(); i++) + await new Promise((resolve) => requestAnimationFrame(resolve)) + const frames = [] + + for (let i = 0; i < 3; i++) { + frames.push({ dock: !!dock(), moving: moving(), animations: document.getAnimations().length }) + await new Promise((resolve) => requestAnimationFrame(resolve)) + } + + return frames + }) + + expect(submitted).toEqual(Array(3).fill({ dock: false, moving: false, animations: 0 })) + }, + ) + + 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() }) - expect(submitted).toEqual(Array(3).fill({ dock: false, moving: false, animations: 0 })) -}) + 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"]') + const focused = question.getByRole("radio", { name: /Focused/ }) + const wide = question.getByRole("radio", { name: /Wide/ }) + await expect(focused).toBeFocused() + await focused.press("1") + await focused.press("9") + await focused.press("Alt+2") + await expect(focused).toBeChecked() + await expect(wide).not.toBeChecked() -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"]') - const focused = question.getByRole("radio", { name: /Focused/ }) - const wide = question.getByRole("radio", { name: /Wide/ }) - await expect(focused).toBeFocused() - await focused.press("1") - await focused.press("9") - await focused.press("Alt+2") - await expect(focused).toBeChecked() - await expect(wide).not.toBeChecked() - - await question.getByRole("button", { name: "Next", exact: true }).click() - const terminal = question.getByRole("checkbox", { name: "Terminal", exact: true }) - await expect(question.getByRole("checkbox", { name: "Changed files", exact: true })).toBeFocused() - await page.keyboard.down("2") - await expect(terminal).toBeChecked() - await page.keyboard.down("2") - await expect(terminal).toBeChecked() - await page.keyboard.up("2") -}) - -story("types digits into the custom answer without selecting numbered options", async ({ mount }) => { - 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("3") - await expect(input).toBeFocused() - await input.press("1") - await input.press("2") - await input.press("3") - await expect(input).toHaveValue("123") - await expect(custom).toBeChecked() - await expect(focused).not.toBeChecked() - 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)) - const shortcut = mac ? "⌘⏎" : "Ctrl+⏎" - const next = component.getByRole("button", { name: "Next", exact: true }) - await expect(next.locator('[data-slot="question-submit-shortcut"]')).toBeVisible() - await expect(next.locator('[data-slot="question-submit-shortcut"]')).toHaveText(shortcut) - await expect(next).toHaveAttribute("aria-keyshortcuts", "Meta+Enter Control+Enter") - await next.hover() - await expect(page.getByRole("tooltip")).toContainText("Next") - await expect(page.getByRole("tooltip")).toContainText(shortcut) - await next.press(mac ? "Meta+Enter" : "Control+Enter") - const submit = component.getByRole("button", { name: "Submit", exact: true }) - await expect(submit.locator('[data-slot="question-submit-shortcut"]')).toBeVisible() - await expect(submit.locator('[data-slot="question-submit-shortcut"]')).toHaveText(shortcut) - await expect(submit).toHaveAttribute("aria-keyshortcuts", "Meta+Enter Control+Enter") - // Pressing the button closes its tooltip until the pointer comes back to it. - await page.mouse.move(0, 0) - await submit.hover() - await expect(page.getByRole("tooltip")).toContainText("Submit") - await expect(page.getByRole("tooltip")).toContainText(shortcut) - const back = component.getByRole("button", { name: "Back", exact: true }) - await expect(back).toHaveText("Back") - await expect(back).toHaveAttribute("aria-keyshortcuts", mac ? "Meta+[" : "Alt+ArrowLeft") - await back.hover() - // Moving straight from Submit opens Back's tooltip while Submit's is still fading out. - await expect(page.getByRole("tooltip", { name: /Back/ })).toContainText(mac ? "⌘[" : "Alt+←") - await back.press(mac ? "Meta+[" : "Alt+ArrowLeft") - await expect(next).toBeVisible() -}) - -story("keeps the custom answer input and dock geometry stable while editing", async ({ mount }) => { - const component = await mount("app-current-session-surface--question-request") - const question = component.locator('[data-component="dock-prompt"][data-kind="question"]') - const row = question.locator('[data-slot="question-option"][data-custom="true"]') - const input = question.getByRole("textbox", { name: "Type your own answer…", exact: true }) - const toggle = question.getByRole("radio", { name: "Type your own answer…", exact: true }) - await expect(question.getByRole("radio", { name: /Focused/ })).toBeFocused() - await expect(input).toBeEditable() - await expect(input).toHaveValue("") - const node = await input.evaluateHandle((element) => element) - const height = () => question.evaluate((element) => element.getBoundingClientRect().height) - const initial = await height() - const draft = "A custom answer long enough to wrap if the editor becomes multiline instead of staying single-line" - - const predefined = question.getByRole("radio", { name: /Focused/ }) - await predefined.click() - await input.focus() - await expect(input).toBeFocused() - await expect(predefined).toBeChecked() - await expect(toggle).not.toBeChecked() - await row.click({ position: { x: 4, y: 4 } }) - await expect(toggle).toBeChecked() - await expect(input).toBeFocused() - await expect(input).toHaveValue("") - await expect(predefined).not.toBeChecked() - await input.fill(draft) - await expect(input).toHaveValue(draft) - await expect(toggle).toBeChecked() - await expect(predefined).not.toBeChecked() - await expect.poll(height).toBe(initial) - await input.press("Escape") - await expect(toggle).toBeFocused() - await expect(input).toHaveValue(draft) - await row.click({ position: { x: 30, y: 20 } }) - await expect(input).toBeFocused() - await expect(input).toHaveValue(draft) - await expect - .poll(() => input.evaluate((element, original) => element === original && original.isConnected, node)) - .toBe(true) - await node.dispose() -}) - -story("marks one-answer questions with round keys and many-answer questions with square keys", async ({ mount }) => { - const component = await mount("app-current-session-surface--question-request") - const question = component.locator('[data-component="dock-prompt"][data-kind="question"]') - const keys = question.locator('[data-slot="question-option-key"]') - const focused = question.getByRole("radio", { name: /Focused/ }) - await expect(focused).toBeFocused() - await expect(keys).toHaveText(["1", "2", "3"]) - await expect(keys.first()).toBeVisible() - await expect(keys.first()).toHaveAttribute("data-type", "radio") - await expect(question.getByText("Pick any", { exact: true })).toHaveCount(0) - await focused.press("1") - await expect(focused.locator('[data-slot="question-option-key"]')).toHaveAttribute("data-picked", "true") - - await question.getByRole("button", { name: "Next", exact: true }).click() - const files = question.getByRole("checkbox", { name: "Changed files", exact: true }) - await expect(files).toBeFocused() - await expect(keys.first()).toHaveAttribute("data-type", "checkbox") - await expect(question.getByText("Pick any", { exact: true })).toBeVisible() -}) - -story("toggles a lone many-answer question and sends it with Enter", async ({ mount, page }) => { - const component = await mount("app-current-session-surface--question-multi-select") - const question = component.locator('[data-component="dock-prompt"][data-kind="question"]') - const files = question.getByRole("checkbox", { name: "Changed files", exact: true }) - const terminal = question.getByRole("checkbox", { name: "Terminal", exact: true }) - await expect(files).toBeFocused() - await expect(question.getByText("Pick any", { exact: true })).toBeVisible() - await expect(question.locator('[data-slot="question-option-key"][data-type="radio"]')).toHaveCount(0) - - await page.keyboard.press(" ") - await page.keyboard.press("2") - await expect(files).toBeChecked() - await expect(terminal).toBeChecked() - await expect(terminal.locator('[data-slot="question-option-key"]')).toHaveAttribute("data-picked", "true") - await page.keyboard.press("Enter") - await expect(question).toBeHidden() -}) - -const longList = async (mount: (id: string) => Promise) => { - const component = await mount("session-question-switch--long-list") - const question = component.locator('[data-component="dock-prompt"][data-kind="question"]') - await expect(question.getByRole("checkbox").first()).toBeFocused() - // The answers box has opened to its first height once it stops changing. - const box = () => question.evaluate((root) => Math.round(root.getBoundingClientRect().height)) - await expect.poll(async () => (await box()) === (await box())).toBe(true) - - return question -} - -const fit = (question: Locator) => - question.evaluate((root) => { - const options = root.querySelector('[data-slot="question-options"]')! - - const timeline = document.querySelector('[data-slot="session-timeline-scroll"] > .scroll-view__viewport') - const box = root.getBoundingClientRect() - - return { - height: box.height, - // The whole dock, footer included, sits between the top of the timeline and the foot of the window. - within: box.top >= (timeline?.getBoundingClientRect().top ?? 0) - 0.5 && box.bottom <= innerHeight + 0.5, - scrolls: options.scrollHeight > options.clientHeight + 1, - top: options.scrollTop, - } + await question.getByRole("button", { name: "Next", exact: true }).click() + const terminal = question.getByRole("checkbox", { name: "Terminal", exact: true }) + await expect(question.getByRole("checkbox", { name: "Changed files", exact: true })).toBeFocused() + await page.keyboard.down("2") + await expect(terminal).toBeChecked() + await page.keyboard.down("2") + await expect(terminal).toBeChecked() + await page.keyboard.up("2") }) -// Whether the whole of an answer's row shows, clear of the feathered edges. -const clear = (row: Locator) => - row.evaluate((input) => { - const row = input.closest('[data-slot="question-option"]')! - const box = input.closest('[data-slot="question-options"]')!.getBoundingClientRect() - const at = row.getBoundingClientRect() - - return at.top >= box.top + 20 - 0.5 && at.bottom <= box.bottom - 20 + 0.5 + story("types digits into the custom answer without selecting numbered options", async ({ mount }) => { + 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("3") + await expect(input).toBeFocused() + await input.press("1") + await input.press("2") + await input.press("3") + await expect(input).toHaveValue("123") + await expect(custom).toBeChecked() + await expect(focused).not.toBeChecked() + await expect(question.getByRole("radio", { name: /Wide/ })).not.toBeChecked() }) -const feathered = (question: Locator) => - question.locator('[data-slot="question-options"]').evaluate((options) => { - const mask = options.style.maskImage + 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("にほん") - // A gradient down the list may be written without its direction, which is the default. - return { top: /linear-gradient\((to bottom, )?transparent/.test(mask), bottom: mask.includes("to top") } + 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("caps a long list of answers to the panel and scrolls them inside it", async ({ mount }) => { - const question = await longList(mount) - const rest = await fit(question) - expect(rest.within).toBe(true) - expect(rest.scrolls).toBe(true) - await expect(question.getByRole("checkbox", { name: /Footer/ })).not.toBeInViewport() -}) + 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)) + const shortcut = mac ? "⌘⏎" : "Ctrl+⏎" + const next = component.getByRole("button", { name: "Next", exact: true }) + await expect(next.locator('[data-slot="question-submit-shortcut"]')).toBeVisible() + await expect(next.locator('[data-slot="question-submit-shortcut"]')).toHaveText(shortcut) + await expect(next).toHaveAttribute("aria-keyshortcuts", "Meta+Enter Control+Enter") + await next.hover() + await expect(page.getByRole("tooltip")).toContainText("Next") + await expect(page.getByRole("tooltip")).toContainText(shortcut) + await next.press(mac ? "Meta+Enter" : "Control+Enter") + const submit = component.getByRole("button", { name: "Submit", exact: true }) + await expect(submit.locator('[data-slot="question-submit-shortcut"]')).toBeVisible() + await expect(submit.locator('[data-slot="question-submit-shortcut"]')).toHaveText(shortcut) + await expect(submit).toHaveAttribute("aria-keyshortcuts", "Meta+Enter Control+Enter") + // Pressing the button closes its tooltip until the pointer comes back to it. + await page.mouse.move(0, 0) + await submit.hover() + await expect(page.getByRole("tooltip")).toContainText("Submit") + await expect(page.getByRole("tooltip")).toContainText(shortcut) + const back = component.getByRole("button", { name: "Back", exact: true }) + await expect(back).toHaveText("Back") + await expect(back).toHaveAttribute("aria-keyshortcuts", mac ? "Meta+[" : "Alt+ArrowLeft") + await back.hover() + // Moving straight from Submit opens Back's tooltip while Submit's is still fading out. + await expect(page.getByRole("tooltip", { name: /Back/ })).toContainText(mac ? "⌘[" : "Alt+←") + await back.press(mac ? "Meta+[" : "Alt+ArrowLeft") + await expect(next).toBeVisible() + }) -story("scrolls the highlighted answer into view with the keys", async ({ mount, page }) => { - const question = await longList(mount) - const footer = question.getByRole("checkbox", { name: /Footer/ }) + story("keeps the custom answer input and dock geometry stable while editing", async ({ mount }) => { + const component = await mount("app-current-session-surface--question-request") + const question = component.locator('[data-component="dock-prompt"][data-kind="question"]') + const row = question.locator('[data-slot="question-option"][data-custom="true"]') + const input = question.getByRole("textbox", { name: "Type your own answer…", exact: true }) + const toggle = question.getByRole("radio", { name: "Type your own answer…", exact: true }) + await expect(question.getByRole("radio", { name: /Focused/ })).toBeFocused() + await expect(input).toBeEditable() + await expect(input).toHaveValue("") + const node = await input.evaluateHandle((element) => element) + const height = () => question.evaluate((element) => element.getBoundingClientRect().height) + const initial = await height() + const draft = "A custom answer long enough to wrap if the editor becomes multiline instead of staying single-line" - await page.keyboard.press("End") - await page.keyboard.press("ArrowUp") - await expect(footer).toBeFocused() - expect(await clear(footer)).toBe(true) + const predefined = question.getByRole("radio", { name: /Focused/ }) + await predefined.click() + await input.focus() + await expect(input).toBeFocused() + await expect(predefined).toBeChecked() + await expect(toggle).not.toBeChecked() + await row.click({ position: { x: 4, y: 4 } }) + await expect(toggle).toBeChecked() + await expect(input).toBeFocused() + await expect(input).toHaveValue("") + await expect(predefined).not.toBeChecked() + await input.fill(draft) + await expect(input).toHaveValue(draft) + await expect(toggle).toBeChecked() + await expect(predefined).not.toBeChecked() + await expect.poll(height).toBe(initial) + await input.press("Escape") + await expect(toggle).toBeFocused() + await expect(input).toHaveValue(draft) + await row.click({ position: { x: 30, y: 20 } }) + await expect(input).toBeFocused() + await expect(input).toHaveValue(draft) + await expect + .poll(() => input.evaluate((element, original) => element === original && original.isConnected, node)) + .toBe(true) + await node.dispose() + }) - await page.keyboard.press("Home") - await expect(question.getByRole("checkbox").first()).toBeFocused() - expect((await fit(question)).top).toBe(0) -}) + story("marks one-answer questions with round keys and many-answer questions with square keys", async ({ mount }) => { + const component = await mount("app-current-session-surface--question-request") + const question = component.locator('[data-component="dock-prompt"][data-kind="question"]') + const keys = question.locator('[data-slot="question-option-key"]') + const focused = question.getByRole("radio", { name: /Focused/ }) + await expect(focused).toBeFocused() + await expect(keys).toHaveText(["1", "2", "3"]) + await expect(keys.first()).toBeVisible() + await expect(keys.first()).toHaveAttribute("data-type", "radio") + await expect(question.getByText("Pick any", { exact: true })).toHaveCount(0) + await focused.press("1") + await expect(focused.locator('[data-slot="question-option-key"]')).toHaveAttribute("data-picked", "true") -story("feathers only the edges of the answers with more past them", async ({ mount }) => { - const question = await longList(mount) + await question.getByRole("button", { name: "Next", exact: true }).click() + const files = question.getByRole("checkbox", { name: "Changed files", exact: true }) + await expect(files).toBeFocused() + await expect(keys.first()).toHaveAttribute("data-type", "checkbox") + await expect(question.getByText("Pick any", { exact: true })).toBeVisible() + }) - // Scrolls to a share of the way down the list. - const edges = (share: number) => - question.evaluate(async (root, share) => { + story("toggles a lone many-answer question and sends it with Enter", async ({ mount, page }) => { + const component = await mount("app-current-session-surface--question-multi-select") + const question = component.locator('[data-component="dock-prompt"][data-kind="question"]') + const files = question.getByRole("checkbox", { name: "Changed files", exact: true }) + const terminal = question.getByRole("checkbox", { name: "Terminal", exact: true }) + await expect(files).toBeFocused() + await expect(question.getByText("Pick any", { exact: true })).toBeVisible() + await expect(question.locator('[data-slot="question-option-key"][data-type="radio"]')).toHaveCount(0) + + await page.keyboard.press(" ") + await page.keyboard.press("2") + await expect(files).toBeChecked() + await expect(terminal).toBeChecked() + await expect(terminal.locator('[data-slot="question-option-key"]')).toHaveAttribute("data-picked", "true") + await page.keyboard.press("Enter") + await expect(question).toBeHidden() + }) + + const longList = async (mount: (id: string) => Promise) => { + const component = await mount("session-question-switch--long-list") + const question = component.locator('[data-component="dock-prompt"][data-kind="question"]') + await expect(question.getByRole("checkbox").first()).toBeFocused() + // The answers box has opened to its first height once it stops changing. + const box = () => question.evaluate((root) => Math.round(root.getBoundingClientRect().height)) + await expect.poll(async () => (await box()) === (await box())).toBe(true) + + return question + } + + const fit = (question: Locator) => + question.evaluate((root) => { const options = root.querySelector('[data-slot="question-options"]')! - options.scrollTop = Math.round((options.scrollHeight - options.clientHeight) * share) - await new Promise((done) => options.addEventListener("scroll", done, { once: true })) + + const timeline = document.querySelector('[data-slot="session-timeline-scroll"] > .scroll-view__viewport') + const box = root.getBoundingClientRect() + + return { + height: box.height, + // The whole dock, footer included, sits between the top of the timeline and the foot of the window. + within: box.top >= (timeline?.getBoundingClientRect().top ?? 0) - 0.5 && box.bottom <= innerHeight + 0.5, + scrolls: options.scrollHeight > options.clientHeight + 1, + top: options.scrollTop, + } + }) + + // Whether the whole of an answer's row shows, clear of the feathered edges. + const clear = (row: Locator) => + row.evaluate((input) => { + const row = input.closest('[data-slot="question-option"]')! + const box = input.closest('[data-slot="question-options"]')!.getBoundingClientRect() + const at = row.getBoundingClientRect() + + return at.top >= box.top + 20 - 0.5 && at.bottom <= box.bottom - 20 + 0.5 + }) + + const feathered = (question: Locator) => + question.locator('[data-slot="question-options"]').evaluate((options) => { const mask = options.style.maskImage // A gradient down the list may be written without its direction, which is the default. return { top: /linear-gradient\((to bottom, )?transparent/.test(mask), bottom: mask.includes("to top") } - }, share) - - expect(await edges(0.5)).toEqual({ top: true, bottom: true }) - expect(await edges(1)).toEqual({ top: true, bottom: false }) - expect(await edges(0)).toEqual({ top: false, bottom: true }) -}) - -story("leaves a list that fits without feathered edges", async ({ mount }) => { - const component = await mount("session-question-switch--question-series") - const question = component.locator('[data-component="dock-prompt"][data-kind="question"]') - await expect(question.getByRole("radio").first()).toBeFocused() - await expect - .poll(() => question.locator('[data-slot="question-options"]').evaluate((el) => el.style.maskImage)) - .toBe("") -}) - -story( - "caps a long list to the panel in the app's layout, where the dock overflows a zero-height row", - async ({ mount }) => { - const question = await longList(mount) - // As in the session screen, the composer region moves into a zero-height row at the foot of the panel and overflows - // it upward, over the timeline. - await question.evaluate((root) => { - const dock = root.closest('[data-component="session-composer-dock"]')! - const row = document.createElement("div") - row.style.cssText = - "position: relative; display: flex; flex-direction: column; justify-content: flex-end; height: 0" - row.style.flexShrink = "0" - dock.replaceWith(row) - row.append(dock) - dispatchEvent(new Event("resize")) }) - // Measured against the empty row, the cap would fall to its 240px minimum. - await expect.poll(async () => (await fit(question)).height).toBeGreaterThan(400) + story("caps a long list of answers to the panel and scrolls them inside it", async ({ mount }) => { + const question = await longList(mount) const rest = await fit(question) expect(rest.within).toBe(true) expect(rest.scrolls).toBe(true) - }, -) + await expect(question.getByRole("checkbox", { name: /Footer/ })).not.toBeInViewport() + }) -story("brings the picked answer back into view after switching questions", async ({ mount, page }) => { - const question = await longList(mount) - const footer = question.getByRole("checkbox", { name: /Footer/ }) - const title = question.locator('[data-slot="question-header-title"]') + story("scrolls the highlighted answer into view with the keys", async ({ mount, page }) => { + const question = await longList(mount) + const footer = question.getByRole("checkbox", { name: /Footer/ }) - await page.keyboard.press("End") - await page.keyboard.press("ArrowUp") - await page.keyboard.press(" ") - await expect(footer).toBeChecked() + await page.keyboard.press("End") + await page.keyboard.press("ArrowUp") + await expect(footer).toBeFocused() + expect(await clear(footer)).toBe(true) - await page.keyboard.press("ArrowRight") - await expect(title).toHaveText("2 of 2 questions") - await page.keyboard.press("ArrowLeft") - await expect(title).toHaveText("1 of 2 questions") - await expect(footer).toBeFocused() - expect(await clear(footer)).toBe(true) -}) + await page.keyboard.press("Home") + await expect(question.getByRole("checkbox").first()).toBeFocused() + expect((await fit(question)).top).toBe(0) + }) -story("sizes the answers box to each question with the dock's motion off", async ({ mount, page }) => { - const question = await longList(mount) - const options = question.locator('[data-slot="question-options"]') - const rest = await fit(question) - expect(rest.scrolls).toBe(true) - expect(await feathered(question)).toEqual({ top: false, bottom: true }) + story("feathers only the edges of the answers with more past them", async ({ mount }) => { + const question = await longList(mount) - await page.keyboard.press("ArrowRight") - await expect(question.getByRole("radio").first()).toBeFocused() - await expect.poll(() => feathered(question)).toEqual({ top: false, bottom: false }) - expect(await options.evaluate((el) => el.style.height)).toBe("") - expect((await fit(question)).scrolls).toBe(false) + // Scrolls to a share of the way down the list. + const edges = (share: number) => + question.evaluate(async (root, share) => { + const options = root.querySelector('[data-slot="question-options"]')! + options.scrollTop = Math.round((options.scrollHeight - options.clientHeight) * share) + await new Promise((done) => options.addEventListener("scroll", done, { once: true })) + const mask = options.style.maskImage - await page.keyboard.press("ArrowLeft") - await expect(question.getByRole("checkbox").first()).toBeFocused() - await expect.poll(() => feathered(question)).toEqual({ top: false, bottom: true }) - expect((await fit(question)).height).toBeCloseTo(rest.height, 0) -}) + // A gradient down the list may be written without its direction, which is the default. + return { top: /linear-gradient\((to bottom, )?transparent/.test(mask), bottom: mask.includes("to top") } + }, share) -story.describe("a long list with the question dock's motion on", () => { - story.beforeEach(({ page }) => - page.addInitScript(() => localStorage.setItem("opencode.motion.v2", JSON.stringify({ "question.motion": 1 }))), + expect(await edges(0.5)).toEqual({ top: true, bottom: true }) + expect(await edges(1)).toEqual({ top: true, bottom: false }) + expect(await edges(0)).toEqual({ top: false, bottom: true }) + }) + + story("leaves a list that fits without feathered edges", async ({ mount }) => { + const component = await mount("session-question-switch--question-series") + const question = component.locator('[data-component="dock-prompt"][data-kind="question"]') + await expect(question.getByRole("radio").first()).toBeFocused() + await expect + .poll(() => question.locator('[data-slot="question-options"]').evaluate((el) => el.style.maskImage)) + .toBe("") + }) + + story( + "caps a long list to the panel in the app's layout, where the dock overflows a zero-height row", + async ({ mount }) => { + const question = await longList(mount) + // As in the session screen, the composer region moves into a zero-height row at the foot of the panel and overflows + // it upward, over the timeline. + await question.evaluate((root) => { + const dock = root.closest('[data-component="session-composer-dock"]')! + const row = document.createElement("div") + row.style.cssText = + "position: relative; display: flex; flex-direction: column; justify-content: flex-end; height: 0" + row.style.flexShrink = "0" + dock.replaceWith(row) + row.append(dock) + dispatchEvent(new Event("resize")) + }) + + // Measured against the empty row, the cap would fall to its 240px minimum. + await expect.poll(async () => (await fit(question)).height).toBeGreaterThan(400) + const rest = await fit(question) + expect(rest.within).toBe(true) + expect(rest.scrolls).toBe(true) + }, ) - story("restores a long list without growing past where it rests", async ({ mount }) => { + story("brings the picked answer back into view after switching questions", async ({ mount, page }) => { const question = await longList(mount) + const footer = question.getByRole("checkbox", { name: /Footer/ }) + const title = question.locator('[data-slot="question-header-title"]') + + await page.keyboard.press("End") + await page.keyboard.press("ArrowUp") + await page.keyboard.press(" ") + await expect(footer).toBeChecked() + + await page.keyboard.press("ArrowRight") + await expect(title).toHaveText("2 of 2 questions") + await page.keyboard.press("ArrowLeft") + await expect(title).toHaveText("1 of 2 questions") + await expect(footer).toBeFocused() + expect(await clear(footer)).toBe(true) + }) + + story("sizes the answers box to each question with the dock's motion off", async ({ mount, page }) => { + const question = await longList(mount) + const options = question.locator('[data-slot="question-options"]') const rest = await fit(question) - await question.getByRole("button", { name: "Minimize question" }).click() - await expect(question.getByRole("button", { name: "Restore question" })).toBeVisible() - await expect - .poll(() => - question.locator('[data-slot="question-options"]').evaluate((el) => el.getBoundingClientRect().height), - ) - .toBe(0) + expect(rest.scrolls).toBe(true) + expect(await feathered(question)).toEqual({ top: false, bottom: true }) - const frames = await question.evaluate(async (root) => { - const options = root.querySelector('[data-slot="question-options"]')! - root.querySelector('[data-slot="question-header-actions"] > button:last-of-type')!.click() + await page.keyboard.press("ArrowRight") + await expect(question.getByRole("radio").first()).toBeFocused() + await expect.poll(() => feathered(question)).toEqual({ top: false, bottom: false }) + expect(await options.evaluate((el) => el.style.height)).toBe("") + expect((await fit(question)).scrolls).toBe(false) - return Array.from({ length: 45 }).reduce>( - async (list) => { - const frames = await list - await new Promise((done) => requestAnimationFrame(done)) + await page.keyboard.press("ArrowLeft") + await expect(question.getByRole("checkbox").first()).toBeFocused() + await expect.poll(() => feathered(question)).toEqual({ top: false, bottom: true }) + expect((await fit(question)).height).toBeCloseTo(rest.height, 0) + }) - return [ - ...frames, - { - height: root.getBoundingClientRect().height, - asked: parseFloat(options.style.height) || 0, - given: options.getBoundingClientRect().height, - }, - ] - }, - Promise.resolve([]), - ) + story.describe("a long list with the question dock's motion on", () => { + story.beforeEach(({ page }) => + page.addInitScript(() => localStorage.setItem("opencode.motion.v2", JSON.stringify({ "question.motion": 1 }))), + ) + + story("restores a long list without growing past where it rests", async ({ mount }) => { + const question = await longList(mount) + const rest = await fit(question) + await question.getByRole("button", { name: "Minimize question" }).click() + await expect(question.getByRole("button", { name: "Restore question" })).toBeVisible() + await expect + .poll(() => + question.locator('[data-slot="question-options"]').evaluate((el) => el.getBoundingClientRect().height), + ) + .toBe(0) + + const frames = await question.evaluate(async (root) => { + const options = root.querySelector('[data-slot="question-options"]')! + root.querySelector('[data-slot="question-header-actions"] > button:last-of-type')!.click() + + return Array.from({ length: 45 }).reduce>( + async (list) => { + const frames = await list + await new Promise((done) => requestAnimationFrame(done)) + + return [ + ...frames, + { + height: root.getBoundingClientRect().height, + asked: parseFloat(options.style.height) || 0, + given: options.getBoundingClientRect().height, + }, + ] + }, + Promise.resolve([]), + ) + }) + + const heights = frames.map((frame) => frame.height) + expect(heights.every((height, i) => i === 0 || height >= heights[i - 1]! - 0.5)).toBe(true) + expect(Math.max(...heights)).toBeLessThanOrEqual(rest.height + 0.5) + expect(heights.at(-1)).toBeCloseTo(rest.height, 0) + // The answers box is never asked to open past the room it is given, which is what made it snap back at the end. + expect(frames.every((frame) => frame.asked <= frame.given + 0.5)).toBe(true) }) - - const heights = frames.map((frame) => frame.height) - expect(heights.every((height, i) => i === 0 || height >= heights[i - 1]! - 0.5)).toBe(true) - expect(Math.max(...heights)).toBeLessThanOrEqual(rest.height + 0.5) - expect(heights.at(-1)).toBeCloseTo(rest.height, 0) - // The answers box is never asked to open past the room it is given, which is what made it snap back at the end. - expect(frames.every((frame) => frame.asked <= frame.given + 0.5)).toBe(true) }) }) diff --git a/packages/app/src/runtime/i18n/en.ts b/packages/app/src/runtime/i18n/en.ts index 66e52bffb24..7be03ef2e11 100644 --- a/packages/app/src/runtime/i18n/en.ts +++ b/packages/app/src/runtime/i18n/en.ts @@ -786,6 +786,8 @@ export const dict = { "settings.experimental.row.newIcons.description": "Preview the updated icon set", "settings.experimental.row.foldUserMessages.title": "Fold long messages", "settings.experimental.row.foldUserMessages.description": "Fold your messages past 12 lines behind a Read more button", + "settings.experimental.row.newQuestionUI.title": "New question UI", + "settings.experimental.row.newQuestionUI.description": "Preview the keyboard-first question dock", "settings.plugins.reload": "Reload", "settings.plugins.status.loading": "Loading", "settings.plugins.status.failed": "Failed", diff --git a/packages/app/src/session/composer/session-composer-region.tsx b/packages/app/src/session/composer/session-composer-region.tsx index f0e667076f1..90acc061d82 100644 --- a/packages/app/src/session/composer/session-composer-region.tsx +++ b/packages/app/src/session/composer/session-composer-region.tsx @@ -3,6 +3,7 @@ import { SessionElicitationDock } from "@/session/requests/session-elicitation-d import { SessionPermissionDock } from "@/session/requests/session-permission-dock" import { SessionQuestionDock } from "@/session/requests/session-question-dock" import { questionMotion } from "@/session/requests/question-motion" +import { useSettings } from "@/settings/model" import { SessionWebSearchDock } from "@/session/requests/session-websearch-dock" import type { SessionComposerRegionController } from "./session-composer-region-controller" import { ComposerMorph, Grow } from "./spring-height" @@ -30,6 +31,7 @@ export function SessionComposerRegion(props: { subagent: JSX.Element }) { const controller = props.controller + const settings = useSettings() const face = createMemo(() => { const websearch = controller.state.websearch.request() @@ -56,7 +58,10 @@ export function SessionComposerRegion(props: { >
{props.above} - !!face.question && !questionMotion()}> + !!face.question && (!settings.general.newQuestionUI() || !questionMotion())} + > {(current) => (
@@ -64,7 +69,7 @@ export function SessionComposerRegion(props: { ( + } + /> + ), +} + +// Several questions of different lengths and kinds in a row. export const QuestionSeries = { render: () => ( () diff --git a/packages/app/src/session/requests/session-question-dock-classic.tsx b/packages/app/src/session/requests/session-question-dock-classic.tsx new file mode 100644 index 00000000000..f7379ad3def --- /dev/null +++ b/packages/app/src/session/requests/session-question-dock-classic.tsx @@ -0,0 +1,809 @@ +import { For, Show, createEffect, createMemo, onCleanup, onMount, type Component } from "solid-js" +import { createStore } from "solid-js/store" +import { useMutation } from "@tanstack/solid-query" +import { Button } from "@opencode/ui/button" +import { IconButton } from "@opencode/ui/icon-button" +import { Tooltip } from "@opencode/ui/tooltip" +import { DockPrompt } from "@opencode/session-ui/dock-prompt" +import { Icon } from "@opencode/ui/icon" +import { Keybind } from "@opencode/ui/keybind" +import { TextInput } from "@opencode/ui/text-input" +import { useSpring } from "@opencode/ui/motion-spring" +import { observeReducedMotion, 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" +import { makeEventListener } from "@solid-primitives/event-listener" +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 { questionCache } from "./question-state" + +const IS_MAC = /(Mac|iPod|iPhone|iPad)/.test(navigator.platform) + +type QuestionField = FormStringField | FormMultiselectField + +function questionField(field: FormInfo["fields"][number]): field is QuestionField { + return field.type === "string" || field.type === "multiselect" +} + +function Mark(props: { multi: boolean; picked: boolean }) { + return ( + + ) +} + +function Option(props: { + multi: boolean + picked: boolean + label: string + description?: string + number: number + disabled: boolean + ref?: (el: HTMLButtonElement) => void + onFocus?: VoidFunction + onClick: VoidFunction +}) { + return ( + + ) +} + +export const SessionQuestionDockClassic: Component<{ request: FormInfo; onSubmit: () => void }> = (props) => { + const serverSDK = useServerSDK() + const language = useLanguage() + const command = useCommand() + const cacheKey = ScopedKey.from(serverSDK.scope, props.request.id) + + const questions = createMemo(() => + props.request.fields.filter(questionField).map((field) => ({ + field, + header: field.title ?? "", + question: field.description ?? field.title ?? "", + options: field.type === "string" ? (field.options ?? []) : field.options, + multiple: field.type === "multiselect", + })), + ) + + const total = createMemo(() => questions().length) + const cached = questionCache.get(cacheKey) + + const [store, setStore] = createStore({ + tab: cached?.tab ?? 0, + answers: cached?.answers ?? [], + custom: cached?.custom ?? [], + customOn: cached?.customOn ?? [], + editing: false, + keyboard: false, + reducedMotion: prefersReducedMotion(), + focus: 0, + minimized: false, + optionsHeight: 180, + }) + + onCleanup(observeReducedMotion(() => setStore("reducedMotion", prefersReducedMotion()))) + + let root: HTMLDivElement | undefined + let optionsRef: HTMLDivElement | undefined + let customRef: HTMLButtonElement | undefined + let customInput: HTMLInputElement | undefined + let optsRef: HTMLButtonElement[] = [] + let replied = false + let focusFrame: number | undefined + + const question = createMemo(() => questions()[store.tab]) + const options = createMemo(() => question()?.options ?? []) + const input = createMemo(() => store.custom[store.tab] ?? "") + const on = createMemo(() => store.customOn[store.tab] === true) + const multi = createMemo(() => question()?.multiple === true) + const count = createMemo(() => options().length + 1) + + const summary = createMemo(() => { + if (total() === 1) return language.t("session.question.title") + const n = Math.min(store.tab + 1, total()) + + return language.t("session.question.progress", { current: n, total: total() }) + }) + + const customLabel = () => language.t("ui.question.custom.answerPlaceholder") + + const last = createMemo(() => store.tab >= total() - 1) + + const collapse = useSpring( + () => (store.minimized ? 1 : 0), + { visualDuration: 0.3, bounce: 0 }, + () => (store.reducedMotion || store.keyboard ? store.minimized : undefined), + ) + + const hidden = createMemo(() => Math.max(0, Math.min(1, collapse()))) + const optionsOff = createMemo(() => hidden() > 0.98) + + const customUpdate = (value: string, selected: boolean = on()) => { + const prev = input().trim() + const next = value.trim() + + setStore("custom", store.tab, value) + + if (!selected) return + + if (multi()) { + setStore("answers", store.tab, (current = []) => { + const removed = prev ? current.filter((item) => item.trim() !== prev) : current + + if (!next) return removed + + if (removed.some((item) => item.trim() === next)) return removed + + return [...removed, next] + }) + + return + } + + setStore("answers", store.tab, next ? [next] : []) + } + + const measure = () => { + if (!root) return + + const scroller = document.querySelector('[data-slot="session-timeline-scroll"] > .scroll-view__viewport') + const head = scroller instanceof HTMLElement ? scroller.firstElementChild : undefined + + const top = + head instanceof HTMLElement && head.classList.contains("sticky") + ? head.getBoundingClientRect().bottom + : scroller instanceof HTMLElement + ? scroller.getBoundingClientRect().top + : 0 + + const dock = root.closest('[data-component="session-composer-dock"]') + // In the app this row can have zero height and overflow upward; the containing panel bounds the question. + const column = bounds(dock?.parentElement) + const bottom = Math.min(window.innerHeight, column?.bottom ?? window.innerHeight) + + const around = + dock instanceof HTMLElement + ? Math.max(0, dock.getBoundingClientRect().height - root.getBoundingClientRect().height) + : 0 + + const gap = 8 + const max = Math.max(240, Math.floor(bottom - Math.max(0, top, column?.top ?? 0) - around - gap)) + root.style.setProperty("--question-prompt-max-height", `${max}px`) + } + + const clamp = (i: number) => Math.max(0, Math.min(count() - 1, i)) + + const pickFocus = (tab: number = store.tab) => { + const list = questions()[tab]?.options ?? [] + + if (store.customOn[tab] === true) return list.length + + return Math.max( + 0, + list.findIndex((item) => store.answers[tab]?.includes(item.value) ?? false), + ) + } + + const focus = (i: number) => { + 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() + }) + } + + onMount(() => { + let raf: number | undefined + + const update = () => { + if (raf !== undefined) cancelAnimationFrame(raf) + raf = requestAnimationFrame(() => { + raf = undefined + measure() + }) + } + + update() + makeEventListener(window, "resize", update) + + const dock = root?.closest('[data-component="session-composer-dock"]') + const scroller = document.querySelector('[data-slot="session-timeline-scroll"] > .scroll-view__viewport') + createResizeObserver([dock, scroller], update) + + onCleanup(() => { + if (raf !== undefined) cancelAnimationFrame(raf) + }) + + focus(pickFocus()) + }) + + createEffect(() => { + const el = optionsRef + + if (!el) return + const update = () => setStore("optionsHeight", (height) => Math.max(height, el.scrollHeight)) + update() + createResizeObserver(el, update) + }) + + onCleanup(() => { + if (focusFrame !== undefined) cancelAnimationFrame(focusFrame) + + if (replied) return + questionCache.set(cacheKey, { + tab: store.tab, + answers: store.answers.map((a) => (a ? [...a] : [])), + custom: store.custom.map((s) => s ?? ""), + customOn: store.customOn.map((b) => b ?? false), + }) + }) + + const fail = (err: Error) => showToast({ title: language.t("common.requestFailed"), description: err.message }) + + const replyMutation = useMutation(() => ({ + mutationFn: (answer: FormAnswer) => + serverSDK.api.session.form.reply({ sessionID: props.request.sessionID, formID: props.request.id, answer }), + onMutate: () => { + props.onSubmit() + }, + onSuccess: () => { + replied = true + questionCache.delete(cacheKey) + }, + onError: fail, + })) + + const rejectMutation = useMutation(() => ({ + mutationFn: () => + serverSDK.api.session.form.cancel({ sessionID: props.request.sessionID, formID: props.request.id }), + onMutate: () => { + props.onSubmit() + }, + onSuccess: () => { + replied = true + questionCache.delete(cacheKey) + }, + onError: fail, + })) + + const sending = createMemo(() => replyMutation.isPending || rejectMutation.isPending) + const submitShortcut = () => (IS_MAC ? "⌘⏎" : `${language.t("common.key.ctrl")}+⏎`) + const backShortcut = () => (IS_MAC ? "⌘[" : `${language.t("common.key.alt")}+←`) + + const reply = (answer: FormAnswer) => { + if (sending()) return + replyMutation.mutate(answer) + } + + const reject = () => { + if (sending()) return + rejectMutation.mutate() + } + + const submit = () => + reply( + Object.fromEntries( + questions().flatMap((question, index) => { + const answers = store.answers[index] ?? [] + + if (answers.length === 0) return [] + + return [[question.field.key, question.multiple ? answers : answers[0]]] + }), + ), + ) + + const answered = (i: number) => { + if ((store.answers[i]?.length ?? 0) > 0) return true + + return store.customOn[i] === true && (store.custom[i] ?? "").trim().length > 0 + } + + const picked = (answer: string) => store.answers[store.tab]?.includes(answer) ?? false + + const pick = (answer: string) => { + setStore("answers", store.tab, [answer]) + setStore("customOn", store.tab, false) + setStore("editing", false) + } + + const toggle = (answer: string) => { + setStore("answers", store.tab, (current = []) => { + if (current.includes(answer)) return current.filter((item) => item !== answer) + + return [...current, answer] + }) + } + + 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 + } + + const value = input().trim() + + if (value) setStore("answers", store.tab, (current = []) => current.filter((item) => item.trim() !== value)) + setStore("editing", false) + focus(options().length) + } + + const move = (step: number) => { + if (store.editing || sending()) return + focus(store.focus + step) + } + + const nav = (event: KeyboardEvent) => { + if (event.defaultPrevented || event.isComposing || event.keyCode === 229) return + + if (event.key === "Escape") { + 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 + 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 || store.minimized || sending()) return + const index = Number(event.key) - 1 + + if (index >= count()) return + event.preventDefault() + + if (index === options().length) { + customToggle() + + return + } + + selectOption(index) + focus(index) + + return + } + + if (!(target instanceof HTMLElement)) return + + if (event.key === "ArrowDown" || event.key === "ArrowRight") { + event.preventDefault() + move(1) + + 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) + } + + const selectOption = (optIndex: number) => { + if (sending()) return + const opt = options()[optIndex] + + if (!opt) return + + if (multi()) { + setStore("editing", false) + toggle(opt.value) + + return + } + + pick(opt.value) + } + + const commitCustom = () => { + setStore("editing", false) + customUpdate(input()) + focus(options().length) + } + + const next = () => { + if (sending()) return + + if (store.editing) commitCustom() + + if (store.tab >= total() - 1) { + submit() + + return + } + + jump(store.tab + 1) + } + + const back = () => { + if (sending() || store.tab <= 0) return + jump(store.tab - 1) + } + + const jump = (tab: number) => { + if (sending() || tab === store.tab) return + setStore("tab", tab) + setStore("editing", false) + + if (optionsRef) setStore("optionsHeight", optionsRef.scrollHeight) + + if (!store.minimized) focus(pickFocus(tab)) + } + + command.register("session.question.back", () => [ + { + id: "session.question.back", + title: language.t("ui.common.back"), + keybind: IS_MAC ? "mod+[" : "alt+arrowleft", + hidden: true, + // Stay registered while sending so the shortcut does not fall through to history navigation. + disabled: store.tab <= 0, + when: () => store.tab > 0, + onSelect: back, + }, + ]) + + const minimize = () => { + if (sending()) return + setStore("editing", false) + setStore("minimized", true) + } + + const restore = () => { + if (sending()) return + setStore("minimized", false) + focus(pickFocus()) + } + + return ( +
setStore("keyboard", false)} + onKeyDown={() => setStore("keyboard", true)} + > + (root = el)} + onKeyDown={nav} + header={ + <> +
+
+ {summary()} +
+
+ 1}> +
+ + {(_, i) => ( + + )} + +
+
+ } + variant="ghost" + size="large" + disabled={sending()} + style={{ transform: `rotate(${hidden() * 180}deg)` }} + onClick={store.minimized ? restore : minimize} + aria-label={language.t(store.minimized ? "session.question.restore" : "session.question.minimize")} + /> +
+
+
+
+ {question()?.question} +
+ +
+ {language.t(multi() ? "ui.question.classic.multiHint" : "ui.question.singleHint")} +
+
+
+ + } + footer={ + <> + +
+ 0}> + + {language.t("ui.common.back")} + {backShortcut()} + + } + > + + + + + {language.t(last() ? "ui.common.submit" : "ui.common.next")} + {submitShortcut()} + + } + > + + +
+ + } + > +
(optionsRef = el)} + data-slot="question-options" + data-scrollable + role={multi() ? "group" : "radiogroup"} + aria-label={question()?.question} + inert={store.minimized} + 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`, + opacity: `${Math.max(0, Math.min(1, 1 - hidden()))}`, + visibility: optionsOff() ? "hidden" : "visible", + }} + > + + {(opt, i) => ( + + +
{ + if (event.target !== event.currentTarget || sending()) return + setStore("focus", options().length) + setStore("customOn", store.tab, true) + setStore("editing", true) + customUpdate(input(), true) + customInput?.focus() + }} + > + + (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.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() + commitCustom() + }} + onInput={(e) => { + setStore("customOn", store.tab, true) + customUpdate(e.currentTarget.value, true) + }} + /> + + +
+
+
+
+ ) +} + +function bounds(el: Element | null | undefined): DOMRect | undefined { + if (!el) return undefined + + const rect = el.getBoundingClientRect() + + return rect.height >= 1 ? rect : bounds(el.parentElement) +} diff --git a/packages/app/src/session/requests/session-question-dock-experimental.tsx b/packages/app/src/session/requests/session-question-dock-experimental.tsx new file mode 100644 index 00000000000..31118f2374e --- /dev/null +++ b/packages/app/src/session/requests/session-question-dock-experimental.tsx @@ -0,0 +1,1510 @@ +import { For, Show, batch, createEffect, createMemo, onCleanup, onMount, type Component } from "solid-js" +import { createStore } from "solid-js/store" +import { useMutation } from "@tanstack/solid-query" +import { Button } from "@opencode/ui/button" +import { IconButton } from "@opencode/ui/icon-button" +import { RollingNumber } from "@opencode/ui/rolling-number" +import { Tooltip } from "@opencode/ui/tooltip" +import { DockPrompt } from "@opencode/session-ui/dock-prompt" +import { Icon } from "@opencode/ui/icon" +import { TextInput } from "@opencode/ui/text-input" +import { frameLoop, Spring, type DurationOptions } from "@opencode/ui/motion" +import { motionTuning } from "@opencode/ui/motion-tuning" +import { showToast } from "@/shell/notifications/toast" +import type { FormAnswer, FormInfo, FormMultiselectField, FormStringField } from "@opencode/client/promise" +import { useLanguage } from "@/runtime/i18n/language" +import { makeEventListener } from "@solid-primitives/event-listener" +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" +import { questionMotion } from "./question-motion" +import { questionCache } from "./question-state" + +const IS_MAC = /(Mac|iPod|iPhone|iPad)/.test(navigator.platform) + +const group = "Timeline" + +const subsection = "Question" + +const target = '[data-component="dock-prompt"][data-kind="question"]' + +// The question text and the answers box follow their new heights on this spring. +const resize = motionTuning.spring("question.height", { + label: "Height", + group, + subsection, + target, + shipped: "smooth", + presets: { + snappy: { duration: 0.35, bounce: 0 }, + smooth: { duration: 0.45, bounce: 0 }, + calm: { duration: 0.55, bounce: 0 }, + }, +}) + +// Switching questions reshapes the card as one surface: the old question blurs, shrinks and fades away while the new +// one resolves out of the same blur. Both copies move on the switch spring: `fadeIn` and `fadeOut` say how far through +// it the new question is fully shown and the old one fully gone, while blur and scale ease out over the whole of it. +// `launch` starts the spring at that multiple of its natural speed, so it answers the key at once without overshooting. +const meta = { group, subsection, target } + +const tuning = { + spring: motionTuning.spring("question.switch", { + label: "Switch", + description: "Moving between questions with ← and →", + ...meta, + presets: { + snappy: { duration: 0.375, bounce: 0 }, + smooth: { duration: 0.5, bounce: 0 }, + calm: { duration: 0.65, bounce: 0 }, + }, + }), + launch: motionTuning.number("question.launch", { + label: "Launch speed", + ...meta, + min: 0, + max: 1, + step: 0.05, + value: 0.3, + }), + travel: motionTuning.number("question.travel", { + label: "Travel", + ...meta, + min: 0, + max: 48, + step: 1, + unit: "px", + value: 0, + }), + fadeIn: motionTuning.number("question.fade-in", { + label: "Fade in by", + ...meta, + min: 0.05, + max: 1, + step: 0.05, + value: 0.45, + }), + fadeOut: motionTuning.number("question.fade-out", { + label: "Fade out by", + ...meta, + min: 0.05, + max: 1, + step: 0.05, + value: 0.6, + }), + // More blur costs more to paint and looks no better. + blur: motionTuning.number("question.blur", { + label: "Blur", + ...meta, + min: 0, + max: 2, + step: 0.25, + unit: "px", + value: 2, + }), + scale: motionTuning.number("question.scale", { + label: "Scale from", + ...meta, + min: 0.85, + max: 1, + step: 0.005, + value: 0.97, + }), +} + +type Tuning = typeof tuning + +// The footer follows the switch: Back resolves in from beside Next the way the question does, out of `travel` px, +// the blur and the scale, and goes the same way. Next and Submit share one place, so turning one into the other +// crossfades them while the button's edge sweeps to the new width. Each is fully shown `fade` of the way through, and +// its label resolves in, out of the blur, only as the other one's goes, so the two words never read over each other. +const footer = { + spring: motionTuning.spring("question.footer", { + label: "Footer buttons", + description: "Back coming and going, and Next turning into Submit", + ...meta, + presets: { + snappy: { duration: 0.375, bounce: 0 }, + smooth: { duration: 0.5, bounce: 0 }, + calm: { duration: 0.65, bounce: 0 }, + }, + }), + travel: motionTuning.number("question.footer-travel", { + label: "Back travel", + ...meta, + min: 0, + max: 24, + step: 1, + unit: "px", + value: 6, + }), + fade: motionTuning.number("question.footer-fade", { + label: "Footer fade by", + ...meta, + min: 0.05, + max: 1, + step: 0.05, + value: 0.6, + }), +} + +const minimizing: DurationOptions = { duration: 0.3, bounce: 0 } + +// How far a list that scrolls fades out at an edge with more answers past it. +const feather = 24 + +// Where a copy of the question sits on screen relative to its place at rest, how much of it shows, and how close it is +// to sharp and full size. +type Pose = { x: number; shown: number; settle: number } + +const rest: Pose = { x: 0, shown: 1, settle: 1 } + +// A copy of the question on its way somewhere: it set off from `from` toward the offset `to`, and its spring runs from 0 +// to 1 along the way. +type Track = { from: Pose; to: number; spring: Spring } + +// The question being left: inert copies of its text and its answers, how tall they are, and how far its answers were +// scrolled. +type Ghost = Track & { tab: number; els: HTMLElement[]; details: number; list: number; scroll: number } + +type QuestionField = FormStringField | FormMultiselectField + +function questionField(field: FormInfo["fields"][number]): field is QuestionField { + return field.type === "string" || field.type === "multiselect" +} + +// The key that picks an answer is also its mark: round like a radio for one answer, a square like a checkbox for many. +function Mark(props: { multi: boolean; picked: boolean; shortcut?: string }) { + return ( + + ) +} + +function Option(props: { + multi: boolean + picked: boolean + label: string + description?: string + shortcut?: string + disabled: boolean + tabbable: boolean + ref?: (el: HTMLButtonElement) => void + onFocus?: VoidFunction + onClick: VoidFunction +}) { + return ( + + ) +} + +export const SessionQuestionDockExperimental: Component<{ request: FormInfo; onSubmit: () => void }> = (props) => { + const serverSDK = useServerSDK() + const language = useLanguage() + const command = useCommand() + const cacheKey = ScopedKey.from(serverSDK.scope, props.request.id) + + const questions = createMemo(() => + props.request.fields.filter(questionField).map((field) => ({ + field, + header: field.title ?? "", + question: field.description ?? field.title ?? "", + options: field.type === "string" ? (field.options ?? []) : field.options, + multiple: field.type === "multiselect", + })), + ) + + const total = createMemo(() => questions().length) + + const cached = questionCache.get(cacheKey) + + const [store, setStore] = createStore({ + tab: cached?.tab ?? 0, + answers: cached?.answers ?? [], + custom: cached?.custom ?? [], + customOn: cached?.customOn ?? [], + editing: false, + focus: 0, + highlight: false, + minimized: false, + listHeight: 0, + }) + + let root: HTMLDivElement | undefined + let chevron: HTMLButtonElement | undefined + let detailsFrame: HTMLDivElement | undefined + let detailsRef: HTMLDivElement | undefined + let optionsRef: HTMLDivElement | undefined + let optionsTrack: 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 + + const question = createMemo(() => questions()[store.tab]) + const options = createMemo(() => question()?.options ?? []) + const input = createMemo(() => store.custom[store.tab] ?? "") + const on = createMemo(() => store.customOn[store.tab] === true) + const multi = createMemo(() => question()?.multiple === true) + const count = createMemo(() => options().length + 1) + + const current = createMemo(() => Math.min(store.tab + 1, total())) + + // "N of M questions", split around N so N can roll while the words around it stay put, wherever a language puts it. + const summary = createMemo(() => { + if (total() === 1) return [language.t("session.question.title")] + + return language.t("session.question.progress", { current: "\u0000", total: total() }).split("\u0000") + }) + + const customLabel = () => language.t("ui.question.custom.answerPlaceholder") + + const last = createMemo(() => store.tab >= total() - 1) + // The question text and the answers box follow their measured heights on springs, so the dock grows and shrinks with + // each question, and the answers box folds away when the dock is minimized. One frame job steps these springs and the + // switch between questions, and writes the results straight to the elements. Without the dock's motion (its knob is + // off by default, and reduced motion turns it off) every spring lands on its target and is painted at once. + const content = { details: 0, list: 0 } + const boxes = { details: new Spring(0), list: new Spring(0), folded: new Spring(0) } + let ghost: Ghost | undefined + let into: Track | undefined + let stop: VoidFunction | undefined + // The current question's bar rests on the first dash and slides along the progress row to the current one, by how + // far that dash is from the first, so it mirrors in RTL. + const bar = new Spring(0) + const dashes: HTMLElement[] = [] + let pip: HTMLElement | undefined + const dash = (tab: number) => (dashes[tab]?.offsetLeft ?? 0) - (dashes[0]?.offsetLeft ?? 0) + // The footer: how far Back is shown, how far the shared button is Submit rather than Next, and how far Back still + // sits from its place after the button beside it changed width. Widths are read when a switch starts, never per frame. + const foot = { back: new Spring(store.tab > 0 ? 1 : 0), submit: new Spring(last() ? 1 : 0), shift: new Spring(0) } + let nextFace: HTMLElement | undefined + let submitFace: HTMLElement | undefined + let nextLabel: HTMLElement | undefined + let submitLabel: HTMLElement | undefined + const widths = { next: 0, submit: 0 } + let backBox: HTMLElement | undefined + let rtl = false + + const customUpdate = (value: string, selected: boolean = on()) => { + const prev = input().trim() + const next = value.trim() + + setStore("custom", store.tab, value) + + if (!selected) return + + if (multi()) { + setStore("answers", store.tab, (current = []) => { + const removed = prev ? current.filter((item) => item.trim() !== prev) : current + + if (!next) return removed + + if (removed.some((item) => item.trim() === next)) return removed + + return [...removed, next] + }) + + return + } + + setStore("answers", store.tab, next ? [next] : []) + } + + // The dock's heights from its last measure: at most, and of everything but the question text and the answers box. + // The answers box takes what the question text leaves, and opens only to the room it will have at rest, so it never + // grows past it and springs back. + const limit = { max: Infinity, chrome: 0 } + const cap = () => limit.max - limit.chrome + // The room the answers box has now, while the question text springs to its height, and once it is there. + const room = () => cap() - boxes.details.value + const settled = (details = content.details) => cap() - details + const scroll = { top: 0, view: 0 } + + const measure = () => { + if (!root) return + + const scroller = document.querySelector('[data-slot="session-timeline-scroll"] > .scroll-view__viewport') + const head = scroller instanceof HTMLElement ? scroller.firstElementChild : undefined + + // The timeline starts under its sticky header, or at its own top when it has none. + const top = + head instanceof HTMLElement && head.classList.contains("sticky") + ? head.getBoundingClientRect().bottom + : scroller instanceof HTMLElement + ? scroller.getBoundingClientRect().top + : 0 + + const dock = root.closest('[data-component="session-composer-dock"]') + // The dock sits at the foot of the column it shares with the timeline, in the app inside a zero-height row that it + // overflows upward. Grown past the column it spills out of it, so the column bounds it, not the dock's own edge. + const column = bounds(dock?.parentElement) + const bottom = Math.min(window.innerHeight, column?.bottom ?? window.innerHeight) + + // Whatever the dock holds besides the question, above it or below, takes from the same height. + const around = + dock instanceof HTMLElement + ? Math.max(0, dock.getBoundingClientRect().height - root.getBoundingClientRect().height) + : 0 + + const gap = 8 + const height = bottom - Math.max(0, top, column?.top ?? 0) - around + limit.max = Math.max(240, Math.floor(height - gap)) + + // Minimized, the answers box is gone, so only an open dock is measured. + if (!store.minimized && optionsRef && detailsFrame) + limit.chrome = root.offsetHeight - optionsRef.offsetHeight - detailsFrame.offsetHeight + root.style.setProperty("--question-prompt-max-height", `${limit.max}px`) + + if (content.list > 0) boxes.list.snap(Math.min(content.list, settled())) + paint() + } + + const clamp = (i: number) => Math.max(0, Math.min(count() - 1, i)) + + const pickFocus = (tab: number = store.tab) => { + const list = questions()[tab]?.options ?? [] + + if (store.customOn[tab] === true) return list.length + + return Math.max( + 0, + list.findIndex((item) => store.answers[tab]?.includes(item.value) ?? false), + ) + } + + // 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 + const el = next === options().length ? customRef : optsRef[next] + el?.focus({ preventScroll: true }) + + if (!how?.preventScroll) reveal(rowAt(next)) + } + + const rowAt = (i: number) => (i === options().length ? customRow : optsRef[i]) + + // A list that scrolls follows the highlighted answer at once, keeping it clear of the feathered edges. + const reveal = (row: HTMLElement | undefined, view = optionsRef?.clientHeight ?? 0) => { + if (!row || !optionsRef || !listRef) return + const top = row.offsetTop + listRef.offsetTop + const edge = Math.min(feather, view / 4) + optionsRef.scrollTop = Math.min(top - edge, Math.max(optionsRef.scrollTop, top + row.offsetHeight + edge - view)) + scroll.top = optionsRef.scrollTop + pin() + } + + // The leaving copy of the answers stays where they were on screen however far the live list scrolls under it. + const pin = () => { + const answers = ghost?.els[1] + + if (ghost && answers) answers.style.top = `${scroll.top - ghost.scroll}px` + } + + // Measuring reads layout, so it waits while the dock's own springs are moving and runs once they come to rest. + let measuring: number | undefined + + const requestMeasure = () => { + if (stop || measuring !== undefined) return + measuring = requestAnimationFrame(() => { + measuring = undefined + measure() + }) + } + + onMount(() => { + measure() + + makeEventListener(window, "resize", requestMeasure) + + const dock = root?.closest('[data-component="session-composer-dock"]') + const scroller = document.querySelector('[data-slot="session-timeline-scroll"] > .scroll-view__viewport') + createResizeObserver([dock, scroller], requestMeasure) + + onCleanup(() => { + if (measuring !== undefined) cancelAnimationFrame(measuring) + }) + + focus(pickFocus()) + }) + + createEffect(() => { + const list = listRef + const details = detailsRef + + if (!list || !details) return + + const observer = new ResizeObserver((entries) => { + const fresh = { details: content.details === 0, list: content.list === 0 } + + entries.forEach((entry) => { + const size = entry.borderBoxSize[0]?.blockSize + + if (size === undefined) return + const key = entry.target === list ? "list" : "details" + content[key] = size + + if (key === "list") setStore("listHeight", size) + }) + + // The answers box opens only as far as the room the new question text leaves it at rest. + ;(["details", "list"] as const).forEach((key) => { + const spring = boxes[key] + const size = key === "list" ? Math.min(content.list, settled()) : content.details + + if (spring.target === size) return + + if (fresh[key] || !questionMotion()) spring.snap(size) + else tune(spring, resize()).set(size) + }) + wake() + }) + + observer.observe(list) + observer.observe(details) + onCleanup(() => observer.disconnect()) + }) + + // One highlight card jumps between answers by its clip, so only one answer ever looks highlighted. + createEffect(() => { + const el = highlightRef + const index = store.focus + const row = rowAt(index) + void store.listHeight + + if (!el || !row || !listRef) return + el.style.clipPath = `inset(${row.offsetTop}px 0 ${listRef.offsetHeight - row.offsetTop - row.offsetHeight}px round 6px)` + }) + + onCleanup(() => { + if (replied) return + questionCache.set(cacheKey, { + tab: store.tab, + answers: store.answers.map((a) => (a ? [...a] : [])), + custom: store.custom.map((s) => s ?? ""), + customOn: store.customOn.map((b) => b ?? false), + }) + }) + + const fail = (err: Error) => showToast({ title: language.t("common.requestFailed"), description: err.message }) + + const replyMutation = useMutation(() => ({ + mutationFn: (answer: FormAnswer) => + serverSDK.api.session.form.reply({ sessionID: props.request.sessionID, formID: props.request.id, answer }), + onMutate: () => { + props.onSubmit() + }, + onSuccess: () => { + replied = true + questionCache.delete(cacheKey) + }, + onError: fail, + })) + + const rejectMutation = useMutation(() => ({ + mutationFn: () => + serverSDK.api.session.form.cancel({ sessionID: props.request.sessionID, formID: props.request.id }), + onMutate: () => { + props.onSubmit() + }, + onSuccess: () => { + replied = true + questionCache.delete(cacheKey) + }, + onError: fail, + })) + + const sending = createMemo(() => replyMutation.isPending || rejectMutation.isPending) + const submitShortcut = () => (IS_MAC ? "⌘⏎" : `${language.t("common.key.ctrl")}+⏎`) + const backShortcut = () => (IS_MAC ? "⌘[" : `${language.t("common.key.alt")}+←`) + + const reply = (answer: FormAnswer) => { + if (sending()) return + replyMutation.mutate(answer) + } + + const reject = () => { + if (sending()) return + rejectMutation.mutate() + } + + const submit = () => + reply( + Object.fromEntries( + questions().flatMap((question, index) => { + const answers = store.answers[index] ?? [] + + if (answers.length === 0) return [] + + return [[question.field.key, question.multiple ? answers : answers[0]]] + }), + ), + ) + + const answered = (i: number) => { + if ((store.answers[i]?.length ?? 0) > 0) return true + + return store.customOn[i] === true && (store.custom[i] ?? "").trim().length > 0 + } + + const picked = (answer: string) => store.answers[store.tab]?.includes(answer) ?? false + + const pick = (answer: string) => { + setStore("answers", store.tab, [answer]) + setStore("customOn", store.tab, false) + setStore("editing", false) + } + + const toggle = (answer: string) => { + setStore("answers", store.tab, (current = []) => { + if (current.includes(answer)) return current.filter((item) => item !== answer) + + return [...current, answer] + }) + } + + 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 + + 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)) + setStore("editing", false) + focus(options().length) + } + + // 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 + + 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 + } + + if (intent.type === "advance") { + event.preventDefault() + next() + + 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 (step < 0) return back() + + if (!last()) jump(store.tab + 1) + + return + } + + if (store.minimized || sending()) return + + if (intent.type === "move" || intent.type === "edge") setStore("highlight", true) + + if (intent.type === "number") { + event.preventDefault() + + if (intent.index === options().length) return customToggle() + + selectOption(intent.index) + focus(intent.index) + + return + } + + event.preventDefault() + + 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) => { + if (sending()) return + + const opt = options()[optIndex] + + if (!opt) return + + if (multi()) { + setStore("editing", false) + toggle(opt.value) + + return + } + + pick(opt.value) + } + + const commitCustom = () => { + setStore("editing", false) + customUpdate(input()) + focus(options().length) + } + + const next = () => { + if (sending()) return + + if (store.editing) commitCustom() + + if (store.tab >= total() - 1) { + submit() + + return + } + + jump(store.tab + 1) + } + + const back = () => { + if (sending()) return + + if (store.tab <= 0) return + jump(store.tab - 1) + } + + // Switching questions: the question being left is copied into a still, inert ghost over its place, while the live + // text and answers show the new question. One spring then moves both: the ghost blurs, shrinks and fades away while + // the new question resolves in its place, each shifted by `travel` toward the way they go. The ghost is gone only once + // the new question has fully arrived, so the card is never empty. + // + // A key pressed mid-switch carries on from what is on screen, at the speed it is moving. Going back to the question + // still leaving brings that copy back from where it is, while the live one turns into the leaving ghost. Going on to + // another question keeps only the more visible of the two copies on screen as the one ghost, and the new question + // comes in. + const depart = (tab: number) => { + if (!detailsRef || !listRef || !detailsFrame || !optionsTrack) return + const v = tuning + const step = Math.sign(tab - store.tab) + const dir = root?.matches(":dir(rtl)") ? -step : step + const reach = v.travel() + const options = v.spring() + const live = into ? arriving(into, v) : rest + const moving = into ? speed(into) : 0 + const back = ghost?.tab === tab ? ghost : undefined + const kept = !back && ghost && leaving(ghost, v, into).shown > live.shown ? ghost : undefined + + if (ghost && ghost !== kept) ghost.els.forEach((el) => el.remove()) + // A kept ghost leaves on the new switch's spring from where it is, so it fades no faster than the next question + // arrives. + ghost = kept + ? { ...kept, ...track(leaving(kept, v, into), kept.to, speed(kept), options, v.launch()) } + : { + ...track(live, -dir * reach, moving, options, v.launch()), + tab: store.tab, + // The answers box scrolls back to the top for the new question, so the copy keeps its place on screen. + els: [copy(detailsRef, detailsFrame), copy(listRef, optionsTrack, -scroll.top)], + details: content.details, + list: content.list, + scroll: scroll.top, + } + into = back + ? track(leaving(back, v, into), 0, speed(back), options, v.launch()) + : track({ x: dir * reach, shown: 0, settle: 0 }, 0, 0, options, v.launch()) + } + + const dropSwitch = () => { + ghost?.els.forEach((el) => el.remove()) + ghost = undefined + into = undefined + } + + const paint = () => { + const sliding = !!(into || ghost) + + const live = look(into ? arriving(into, tuning) : rest) + + ;[detailsRef, listRef].forEach((el) => el && place(el, live)) + + if (ghost) { + const pose = look(leaving(ghost, tuning, into)) + ghost.els.forEach((el) => place(el, pose)) + } + + const folded = Math.max(0, Math.min(1, boxes.folded.value)) + // Without motion the boxes keep their natural heights, so a new question lays out at its size on the same frame. + const sized = questionMotion() + + if (detailsFrame && content.details > 0) { + const shown = boxes.details.value + detailsFrame.style.height = sized ? `${shown.toFixed(2)}px` : "" + mask(detailsFrame, 0, Math.max(content.details, ghost?.details ?? 0) - shown, shown, sliding) + } + + if (optionsRef && content.list > 0) { + // Without motion the dock's max height caps the answers box, which scrolls inside the room it leaves. + const shown = sized + ? Math.min(boxes.list.value, room()) * (1 - folded) + : folded > 0 + ? 0 + : Math.min(content.list, room()) + + optionsRef.style.height = sized ? `${shown.toFixed(2)}px` : folded > 0 ? "0px" : "" + scroll.view = shown + feathers() + } + + if (optionsRef) { + optionsRef.style.opacity = folded > 0 ? (1 - folded).toFixed(4) : "" + // Restoring shows the answers again at once, so the highlighted one can take focus. + optionsRef.style.visibility = folded > 0.98 && boxes.folded.target > 0 ? "hidden" : "" + } + + if (chevron) chevron.style.transform = folded > 0 ? `rotate(${(folded * 180).toFixed(2)}deg)` : "" + + if (pip) pip.style.transform = `translate3d(${bar.value.toFixed(2)}px,0,0)` + + paintFooter() + } + + // The answers fade out at whichever edge has more of them past it, while they open or scroll. + // It reads where the list is scrolled from the last scroll, never from layout, since it runs every frame. + const feathers = () => { + if (!optionsRef) return + const above = scroll.top + const shown = scroll.view + mask(optionsRef, above, Math.max(content.list, ghost?.list ?? 0) - above - shown, shown, !!(into || ghost)) + } + + const paintFooter = () => { + if (backBox) { + const shown = unit(foot.back.value) + const hidden = 1 - shown + const x = foot.shift.value + (rtl ? -1 : 1) * footer.travel() * hidden + const scale = 1 - (1 - tuning.scale()) * hidden + const moving = !foot.back.resting || !foot.shift.resting + backBox.style.transform = moving ? `translate3d(${x.toFixed(2)}px,0,0) scale(${scale.toFixed(4)})` : "" + backBox.style.opacity = moving ? shown.toFixed(4) : "" + backBox.style.filter = + moving && tuning.blur() * hidden >= 0.05 ? `blur(${(tuning.blur() * hidden).toFixed(2)}px)` : "" + backBox.style.visibility = moving ? "visible" : "" + } + + if (!nextFace || !submitFace || !nextLabel || !submitLabel) return + const s = unit(foot.submit.value) + + if (foot.submit.resting || !widths.next || !widths.submit) { + ;[nextFace, submitFace, nextLabel, submitLabel].forEach((el) => el.removeAttribute("style")) + + return + } + + // The wider face is cut back from its start edge to the width the button has reached. + const width = widths.next + (widths.submit - widths.next) * s + const wide = widths.submit > widths.next ? submitFace : nextFace + const cut = Math.max(widths.next, widths.submit) - width + const clip = cut < 0.5 ? "" : `inset(0 ${rtl ? cut.toFixed(2) : 0}px 0 ${rtl ? 0 : cut.toFixed(2)}px round 6px)` + + const by = footer.fade() + showFace(nextFace, nextLabel, unit((1 - s) / by), unit(1 - s / by), nextFace === wide ? clip : "") + showFace(submitFace, submitLabel, unit(s / by), unit(1 - (1 - s) / by), submitFace === wide ? clip : "") + } + + const tick = (dt: number) => { + into?.spring.step(dt) + ghost?.spring.step(dt) + boxes.details.step(dt) + boxes.list.step(dt) + boxes.folded.step(dt) + bar.step(dt) + Object.values(foot).forEach((spring) => spring.step(dt)) + + if (into?.spring.resting) into = undefined + + if (ghost && leaving(ghost, tuning, into).shown <= 0) { + ghost.els.forEach((el) => el.remove()) + ghost = undefined + } + + paint() + + const footing = Object.values(foot).some((spring) => !spring.resting) + + if ( + into || + ghost || + footing || + !bar.resting || + !boxes.details.resting || + !boxes.list.resting || + !boxes.folded.resting + ) + return true + stop = undefined + requestMeasure() + + return false + } + + const wake = () => { + if (!questionMotion()) return still() + stop ??= frameLoop.add(tick) + } + + // Everything lands where it is going, now: no frame job runs. + const still = () => { + stop?.() + stop = undefined + dropSwitch() + ;[...Object.values(boxes), ...Object.values(foot), bar].forEach((spring) => spring.snap(spring.target)) + paint() + } + + // Turning the knob off also lands any running pick or dash transition. + createEffect(() => { + if (questionMotion()) return + still() + root?.getAnimations({ subtree: true }).forEach((animation) => animation.cancel()) + }) + onCleanup(() => stop?.()) + + const jump = (tab: number) => { + if (sending() || tab === store.tab) return + const animate = !store.minimized && questionMotion() + + if (animate) depart(tab) + else dropSwitch() + + rtl = !!root?.matches(":dir(rtl)") + widths.next = nextFace?.offsetWidth ?? 0 + widths.submit = submitFace?.offsetWidth ?? 0 + const before = backBox?.offsetLeft ?? 0 + // 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. + batch(() => { + setStore("focus", pickFocus(tab)) + + setStore("tab", tab) + setStore("editing", false) + }) + optsRef.length = options().length + + if (optionsRef) optionsRef.scrollTop = scroll.top = 0 + + const reduced = !questionMotion() + + if (reduced) bar.snap(dash(tab)) + else tune(bar, tuning.spring()).set(dash(tab)) + + // Back stays where it was on screen while the button beside it changes width, and slides to its new place. + foot.shift.value += before - (backBox?.offsetLeft ?? 0) + + const targets = { back: tab > 0 ? 1 : 0, submit: tab >= total() - 1 ? 1 : 0, shift: 0 } + + ;(["back", "submit", "shift"] as const).forEach((key) => { + if (reduced) foot[key].snap(targets[key]) + else tune(foot[key], footer.spring()).set(targets[key]) + }) + // The first frame is painted now, so the new question never shows at rest before it arrives. + paint() + + if (store.minimized) { + // A button that just gave way to the other one can no longer hold focus. + if (document.activeElement?.closest("[inert]")) (last() ? submitFace : nextFace)?.querySelector("button")?.focus() + wake() + + return + } + + // The answers box is still springing to the new list's height, so the answer that takes focus comes into view of + // the height it will rest at. + focus(pickFocus(tab), { preventScroll: true }) + + if (optionsRef && detailsRef) + reveal(rowAt(store.focus), Math.min(optionsRef.scrollHeight, settled(detailsRef.offsetHeight))) + + wake() + } + + const cycle = (by: number) => { + if (total() < 2) return + jump((store.tab + by + total()) % total()) + } + + onCleanup( + motionTuning.action({ id: "question.next", label: "Next question", group, subsection, run: () => cycle(1) }), + ) + onCleanup( + motionTuning.action({ id: "question.back", label: "Previous question", group, subsection, run: () => cycle(-1) }), + ) + + command.register("session.question.back", () => [ + { + id: "session.question.back", + title: language.t("ui.common.back"), + keybind: IS_MAC ? "mod+[" : "alt+arrowleft", + hidden: true, + // Stay registered while sending so the shortcut does not fall through to history navigation. + disabled: store.tab <= 0, + when: () => store.tab > 0, + onSelect: back, + }, + ]) + + const minimize = () => { + if (sending()) return + setStore("editing", false) + setStore("minimized", true) + fold(1) + } + + const restore = () => { + if (sending()) return + setStore("minimized", false) + fold(0) + paint() + // The answers box is still opening, so its answer comes into view of the height it will rest at. + const index = pickFocus() + focus(index, { preventScroll: true }) + + if (detailsRef) reveal(rowAt(index), Math.min(content.list, settled(detailsRef.offsetHeight))) + } + + const fold = (target: number) => { + tune(boxes.folded, minimizing).set(target) + wake() + } + + return ( +
+ (root = el)} + onKeyDown={nav} + header={ + <> +
+
+ + {summary()[0]} + 1}> + + + + {summary().slice(1).join("")} + + +
+
+ 1}> +
+ {/* Without motion there is no sliding bar: the current question's dash lights instead. */} + + + + + {(_, i) => ( + + )} + +
+
+ (chevron = el)} + icon={} + variant="ghost" + size="large" + disabled={sending()} + onClick={store.minimized ? restore : minimize} + aria-label={language.t(store.minimized ? "session.question.restore" : "session.question.minimize")} + /> +
+
+
(detailsFrame = el)}> +
(detailsRef = el)}> +
+ {question()?.question} +
+ +
{language.t("ui.question.multiHint")}
+
+
+
+ + } + footer={ + <> + +
+ {/* Back stays in place while hidden, so it can come and go without moving anything. */} +
0} + inert={store.tab === 0} + ref={(el) => (backBox = el)} + > + + {language.t("ui.common.back")} + {backShortcut()} + + } + > + + +
+ {/* Next and Submit share one place and one tooltip; the one not in use lies under it, inert. */} + + {last() ? language.t("ui.common.submit") : language.t("ui.common.next")} + {submitShortcut()} + + } + > +
+
(nextFace = el)} + > + +
+
(submitFace = el)} + > + +
+
+
+
+ + } + > +
(optionsRef = el)} + data-slot="question-options" + role={multi() ? "group" : "radiogroup"} + aria-label={question()?.question} + inert={store.minimized} + aria-hidden={store.minimized ? "true" : undefined} + onScroll={(event) => { + scroll.top = event.currentTarget.scrollTop + pin() + feathers() + }} + // 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() + }} + > +
(optionsTrack = el)}> +
(listRef = el)} + onPointerDown={() => setStore("highlight", false)} + > + (highlightRef = el)} + aria-hidden="true" + /> + + {(opt, i) => ( + + +
(customRow = el)} + 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 + startCustom() + }} + > + + (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() + + if (!e.repeat) next() + }} + onInput={(e) => { + setStore("customOn", store.tab, true) + customUpdate(e.currentTarget.value, true) + }} + /> +
+
+
+
+
+
+ ) +} + +// Comes into place from where it set off, fully shown by the fade-in point, which is never after the fade-out point, so +// the two copies together always show at least one whole question. It sharpens and grows over the whole spring. +function arriving(track: Track, v: Tuning): Pose { + const p = unit(track.spring.value) + + return { + x: track.from.x + (track.to - track.from.x) * p, + shown: track.from.shown + (1 - track.from.shown) * unit(p / Math.min(v.fadeIn(), v.fadeOut())), + settle: track.from.settle + (1 - track.from.settle) * p, + } +} + +// Leaves from where it set off, fully gone by the fade-out point, but never fading faster than `next` arrives, so a +// copy kept through rapid keys holds the card until the new question has caught up. +function leaving(track: Track, v: Tuning, next?: Track): Pose { + const p = unit(track.spring.value) + const gone = unit(p / v.fadeOut()) + const arrived = next ? arriving(next, v).shown : 1 + + return { + x: track.from.x + (track.to - track.from.x) * p, + shown: Math.max(track.from.shown * (1 - gone), Math.min(track.from.shown, 1 - arrived)), + settle: track.from.settle * (1 - gone), + } +} + +function unit(value: number) { + return Math.max(0, Math.min(1, value)) +} + +function speed(track: Track) { + return (track.to - track.from.x) * track.spring.velocity +} + +// Sets off from `from` at the speed it already had on screen, plus the key's launch. The start is capped at the +// spring's natural speed so it never overshoots its place. +function track(from: Pose, to: number, moving: number, options: DurationOptions, launch: number): Track { + const spring = Spring.fromDuration(0, options) + const distance = to - from.x + const carried = Math.abs(distance) < 0.5 ? 0 : moving / distance + + return { + from, + to, + spring: spring.set(1, { velocity: Math.min(spring.omega, carried + spring.omega * launch) }), + } +} + +type Look = { transform: string; opacity: string; blur: number } + +// How a copy in `pose` is drawn: it blurs and shrinks toward the top of the card as it goes. +function look(pose: Pose): Look { + const unsettled = 1 - pose.settle + const scale = 1 - (1 - tuning.scale()) * unsettled + const blur = tuning.blur() * unsettled + const moved = Math.abs(pose.x) >= 0.01 || scale < 0.9999 + + return { + transform: moved ? `translate3d(${pose.x.toFixed(2)}px,0,0) scale(${scale.toFixed(4)})` : "", + opacity: pose.shown >= 1 ? "" : pose.shown.toFixed(4), + blur: blur < 0.05 ? 0 : blur, + } +} + +function tune(spring: Spring, options: DurationOptions) { + spring.omega = (2 * Math.PI) / options.duration + spring.zeta = 1 - options.bounce + + return spring +} + +// The label's opacity is relative to its face's, which already applies. +function showFace(face: HTMLElement, label: HTMLElement, opacity: number, shown: number, clip: string) { + face.style.visibility = "visible" + face.style.opacity = opacity.toFixed(4) + face.style.clipPath = clip + label.style.opacity = opacity > 0 ? Math.min(1, shown / opacity).toFixed(4) : "0" + label.style.filter = shown < 0.98 ? `blur(${(tuning.blur() * (1 - shown)).toFixed(2)}px)` : "" +} + +function place(el: HTMLElement, look: Look) { + el.style.transform = look.transform + el.style.opacity = look.opacity + el.style.filter = look.blur === 0 ? "" : `blur(${look.blur.toFixed(2)}px)` +} + +// While a switch is under way, content sliding into a box's side gutters fades out there. While a box is shorter than +// what it holds, its bottom fades instead of ending hard, over no more than a third of the box. +function mask(el: HTMLElement, above: number, below: number, shown: number, sliding: boolean) { + const top = Math.min(feather, above, shown / 3) + const bottom = Math.min(feather, below, shown / 3) + + const layers = [ + sliding + ? "linear-gradient(to right, transparent, #000 var(--question-gutter), #000 calc(100% - var(--question-gutter)), transparent)" + : "", + top > 0.5 ? `linear-gradient(to bottom, transparent, #000 ${top.toFixed(2)}px)` : "", + bottom > 0.5 ? `linear-gradient(to top, transparent, #000 ${bottom.toFixed(2)}px)` : "", + ].filter(Boolean) + + if (layers.length === 0) return el.style.removeProperty("mask-image") + el.style.setProperty("mask-image", layers.join(", ")) +} + +// A still copy of `el` laid over it in `host`, after the live content so it never comes first in the DOM, inert and +// hidden from assistive tech. Ids are dropped so they stay unique, and typed text is carried over. +function copy(el: HTMLElement, host: HTMLElement, top = 0) { + // SAFETY: a deep clone of an element is an element of the same kind. + const clone = el.cloneNode(true) as HTMLElement + clone.removeAttribute("id") + clone.querySelectorAll("[id]").forEach((node) => node.removeAttribute("id")) + // The answer highlight jumps; the leaving copy never carries a second one off with it. + clone.querySelector('[data-slot="question-highlight"]')?.remove() + const inputs = el.querySelectorAll("input") + clone.querySelectorAll("input").forEach((input, index) => (input.value = inputs[index]?.value ?? "")) + clone.dataset.ghost = "true" + clone.inert = true + clone.setAttribute("aria-hidden", "true") + clone.style.position = "absolute" + clone.style.top = `${top}px` + clone.style.insetInline = "var(--question-gutter)" + clone.style.pointerEvents = "none" + host.append(clone) + + return clone +} + +// The nearest of `el` and its ancestors that has a height. +function bounds(el: Element | null | undefined): DOMRect | undefined { + if (!el) return undefined + const rect = el.getBoundingClientRect() + + return rect.height >= 1 ? rect : bounds(el.parentElement) +} diff --git a/packages/app/src/session/requests/session-question-dock.tsx b/packages/app/src/session/requests/session-question-dock.tsx index 7cf39ba70ea..b31023be053 100644 --- a/packages/app/src/session/requests/session-question-dock.tsx +++ b/packages/app/src/session/requests/session-question-dock.tsx @@ -1,1534 +1,15 @@ -import { For, Show, batch, createEffect, createMemo, createSignal, onCleanup, onMount, type Component } from "solid-js" -import { createStore } from "solid-js/store" -import { useMutation } from "@tanstack/solid-query" -import { Button } from "@opencode/ui/button" -import { IconButton } from "@opencode/ui/icon-button" -import { RollingNumber } from "@opencode/ui/rolling-number" -import { Tooltip } from "@opencode/ui/tooltip" -import { DockPrompt } from "@opencode/session-ui/dock-prompt" -import { Icon } from "@opencode/ui/icon" -import { TextInput } from "@opencode/ui/text-input" -import { frameLoop, Spring, type DurationOptions } from "@opencode/ui/motion" -import { motionTuning } from "@opencode/ui/motion-tuning" -import { showToast } from "@/shell/notifications/toast" -import type { FormAnswer, FormInfo, FormMultiselectField, FormStringField } from "@opencode/client/promise" -import { useLanguage } from "@/runtime/i18n/language" -import { makeEventListener } from "@solid-primitives/event-listener" -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" -import { questionMotion } from "./question-motion" - -const cache = new Map() - -const IS_MAC = /(Mac|iPod|iPhone|iPad)/.test(navigator.platform) - -const group = "Timeline" - -const subsection = "Question" - -const target = '[data-component="dock-prompt"][data-kind="question"]' - -// The question text and the answers box follow their new heights on this spring. -const resize = motionTuning.spring("question.height", { - label: "Height", - group, - subsection, - target, - shipped: "smooth", - presets: { - snappy: { duration: 0.35, bounce: 0 }, - smooth: { duration: 0.45, bounce: 0 }, - calm: { duration: 0.55, bounce: 0 }, - }, -}) - -// Switching questions reshapes the card as one surface: the old question blurs, shrinks and fades away while the new -// one resolves out of the same blur. Both copies move on the switch spring: `fadeIn` and `fadeOut` say how far through -// it the new question is fully shown and the old one fully gone, while blur and scale ease out over the whole of it. -// `launch` starts the spring at that multiple of its natural speed, so it answers the key at once without overshooting. -const meta = { group, subsection, target } - -const tuning = { - spring: motionTuning.spring("question.switch", { - label: "Switch", - description: "Moving between questions with ← and →", - ...meta, - presets: { - snappy: { duration: 0.375, bounce: 0 }, - smooth: { duration: 0.5, bounce: 0 }, - calm: { duration: 0.65, bounce: 0 }, - }, - }), - launch: motionTuning.number("question.launch", { - label: "Launch speed", - ...meta, - min: 0, - max: 1, - step: 0.05, - value: 0.3, - }), - travel: motionTuning.number("question.travel", { - label: "Travel", - ...meta, - min: 0, - max: 48, - step: 1, - unit: "px", - value: 0, - }), - fadeIn: motionTuning.number("question.fade-in", { - label: "Fade in by", - ...meta, - min: 0.05, - max: 1, - step: 0.05, - value: 0.45, - }), - fadeOut: motionTuning.number("question.fade-out", { - label: "Fade out by", - ...meta, - min: 0.05, - max: 1, - step: 0.05, - value: 0.6, - }), - // More blur costs more to paint and looks no better. - blur: motionTuning.number("question.blur", { - label: "Blur", - ...meta, - min: 0, - max: 2, - step: 0.25, - unit: "px", - value: 2, - }), - scale: motionTuning.number("question.scale", { - label: "Scale from", - ...meta, - min: 0.85, - max: 1, - step: 0.005, - value: 0.97, - }), -} - -type Tuning = typeof tuning - -// The footer follows the switch: Back resolves in from beside Next the way the question does, out of `travel` px, -// the blur and the scale, and goes the same way. Next and Submit share one place, so turning one into the other -// crossfades them while the button's edge sweeps to the new width. Each is fully shown `fade` of the way through, and -// its label resolves in, out of the blur, only as the other one's goes, so the two words never read over each other. -const footer = { - spring: motionTuning.spring("question.footer", { - label: "Footer buttons", - description: "Back coming and going, and Next turning into Submit", - ...meta, - presets: { - snappy: { duration: 0.375, bounce: 0 }, - smooth: { duration: 0.5, bounce: 0 }, - calm: { duration: 0.65, bounce: 0 }, - }, - }), - travel: motionTuning.number("question.footer-travel", { - label: "Back travel", - ...meta, - min: 0, - max: 24, - step: 1, - unit: "px", - value: 6, - }), - fade: motionTuning.number("question.footer-fade", { - label: "Footer fade by", - ...meta, - min: 0.05, - max: 1, - step: 0.05, - value: 0.6, - }), -} - -const minimizing: DurationOptions = { duration: 0.3, bounce: 0 } - -// How far a list that scrolls fades out at an edge with more answers past it. -const feather = 24 - -// Where a copy of the question sits on screen relative to its place at rest, how much of it shows, and how close it is -// to sharp and full size. -type Pose = { x: number; shown: number; settle: number } - -const rest: Pose = { x: 0, shown: 1, settle: 1 } - -// A copy of the question on its way somewhere: it set off from `from` toward the offset `to`, and its spring runs from 0 -// to 1 along the way. -type Track = { from: Pose; to: number; spring: Spring } - -// The question being left: inert copies of its text and its answers, how tall they are, and how far its answers were -// scrolled. -type Ghost = Track & { tab: number; els: HTMLElement[]; details: number; list: number; scroll: number } - -type QuestionField = FormStringField | FormMultiselectField - -function questionField(field: FormInfo["fields"][number]): field is QuestionField { - return field.type === "string" || field.type === "multiselect" -} - -// The key that picks an answer is also its mark: round like a radio for one answer, a square like a checkbox for many. -function Mark(props: { multi: boolean; picked: boolean; shortcut?: string }) { - return ( - - ) -} - -function Option(props: { - multi: boolean - picked: boolean - label: string - description?: string - shortcut?: string - disabled: boolean - tabbable: boolean - ref?: (el: HTMLButtonElement) => void - onFocus?: VoidFunction - onPointerMove?: (event: PointerEvent) => void - onClick: VoidFunction -}) { - return ( - - ) -} - -export const SessionQuestionDock: Component<{ request: FormInfo; onSubmit: () => void }> = (props) => { - const serverSDK = useServerSDK() - const language = useLanguage() - const command = useCommand() - const cacheKey = ScopedKey.from(serverSDK.scope, props.request.id) - - const questions = createMemo(() => - props.request.fields.filter(questionField).map((field) => ({ - field, - header: field.title ?? "", - question: field.description ?? field.title ?? "", - options: field.type === "string" ? (field.options ?? []) : field.options, - multiple: field.type === "multiselect", - })), - ) - - const total = createMemo(() => questions().length) - - const cached = cache.get(cacheKey) - - const [store, setStore] = createStore({ - tab: cached?.tab ?? 0, - answers: cached?.answers ?? [], - custom: cached?.custom ?? [], - customOn: cached?.customOn ?? [], - editing: false, - focus: 0, - minimized: false, - listHeight: 0, - }) - - const [lit, setLit] = createSignal<"none" | "hover" | "keys">("none") - - let root: HTMLDivElement | undefined - let chevron: HTMLButtonElement | undefined - let detailsFrame: HTMLDivElement | undefined - let detailsRef: HTMLDivElement | undefined - let optionsRef: HTMLDivElement | undefined - let optionsTrack: 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 - - const question = createMemo(() => questions()[store.tab]) - const options = createMemo(() => question()?.options ?? []) - const input = createMemo(() => store.custom[store.tab] ?? "") - const on = createMemo(() => store.customOn[store.tab] === true) - const multi = createMemo(() => question()?.multiple === true) - const count = createMemo(() => options().length + 1) - - const current = createMemo(() => Math.min(store.tab + 1, total())) - - // "N of M questions", split around N so N can roll while the words around it stay put, wherever a language puts it. - const summary = createMemo(() => { - if (total() === 1) return [language.t("session.question.title")] - - return language.t("session.question.progress", { current: "\u0000", total: total() }).split("\u0000") - }) - - const customLabel = () => language.t("ui.question.custom.answerPlaceholder") - - const last = createMemo(() => store.tab >= total() - 1) - // The question text and the answers box follow their measured heights on springs, so the dock grows and shrinks with - // each question, and the answers box folds away when the dock is minimized. One frame job steps these springs and the - // switch between questions, and writes the results straight to the elements. Without the dock's motion (its knob is - // off by default, and reduced motion turns it off) every spring lands on its target and is painted at once. - const content = { details: 0, list: 0 } - const boxes = { details: new Spring(0), list: new Spring(0), folded: new Spring(0) } - let ghost: Ghost | undefined - let into: Track | undefined - let stop: VoidFunction | undefined - // The current question's bar rests on the first dash and slides along the progress row to the current one, by how - // far that dash is from the first, so it mirrors in RTL. - const bar = new Spring(0) - const dashes: HTMLElement[] = [] - let pip: HTMLElement | undefined - const dash = (tab: number) => (dashes[tab]?.offsetLeft ?? 0) - (dashes[0]?.offsetLeft ?? 0) - // The footer: how far Back is shown, how far the shared button is Submit rather than Next, and how far Back still - // sits from its place after the button beside it changed width. Widths are read when a switch starts, never per frame. - const foot = { back: new Spring(store.tab > 0 ? 1 : 0), submit: new Spring(last() ? 1 : 0), shift: new Spring(0) } - let nextFace: HTMLElement | undefined - let submitFace: HTMLElement | undefined - let nextLabel: HTMLElement | undefined - let submitLabel: HTMLElement | undefined - const widths = { next: 0, submit: 0 } - let backBox: HTMLElement | undefined - let rtl = false - - const customUpdate = (value: string, selected: boolean = on()) => { - const prev = input().trim() - const next = value.trim() - - setStore("custom", store.tab, value) - - if (!selected) return - - if (multi()) { - setStore("answers", store.tab, (current = []) => { - const removed = prev ? current.filter((item) => item.trim() !== prev) : current - - if (!next) return removed - - if (removed.some((item) => item.trim() === next)) return removed - - return [...removed, next] - }) - - return - } - - setStore("answers", store.tab, next ? [next] : []) - } - - // The dock's heights from its last measure: at most, and of everything but the question text and the answers box. - // The answers box takes what the question text leaves, and opens only to the room it will have at rest, so it never - // grows past it and springs back. - const limit = { max: Infinity, chrome: 0 } - const cap = () => limit.max - limit.chrome - // The room the answers box has now, while the question text springs to its height, and once it is there. - const room = () => cap() - boxes.details.value - const settled = (details = content.details) => cap() - details - const scroll = { top: 0, view: 0 } - - const measure = () => { - if (!root) return - - const scroller = document.querySelector('[data-slot="session-timeline-scroll"] > .scroll-view__viewport') - const head = scroller instanceof HTMLElement ? scroller.firstElementChild : undefined - - // The timeline starts under its sticky header, or at its own top when it has none. - const top = - head instanceof HTMLElement && head.classList.contains("sticky") - ? head.getBoundingClientRect().bottom - : scroller instanceof HTMLElement - ? scroller.getBoundingClientRect().top - : 0 - - const dock = root.closest('[data-component="session-composer-dock"]') - // The dock sits at the foot of the column it shares with the timeline, in the app inside a zero-height row that it - // overflows upward. Grown past the column it spills out of it, so the column bounds it, not the dock's own edge. - const column = bounds(dock?.parentElement) - const bottom = Math.min(window.innerHeight, column?.bottom ?? window.innerHeight) - - // Whatever the dock holds besides the question, above it or below, takes from the same height. - const around = - dock instanceof HTMLElement - ? Math.max(0, dock.getBoundingClientRect().height - root.getBoundingClientRect().height) - : 0 - - const gap = 8 - const height = bottom - Math.max(0, top, column?.top ?? 0) - around - limit.max = Math.max(240, Math.floor(height - gap)) - - // Minimized, the answers box is gone, so only an open dock is measured. - if (!store.minimized && optionsRef && detailsFrame) - limit.chrome = root.offsetHeight - optionsRef.offsetHeight - detailsFrame.offsetHeight - root.style.setProperty("--question-prompt-max-height", `${limit.max}px`) - - if (content.list > 0) boxes.list.snap(Math.min(content.list, settled())) - paint() - } - - const clamp = (i: number) => Math.max(0, Math.min(count() - 1, i)) - - const pickFocus = (tab: number = store.tab) => { - const list = questions()[tab]?.options ?? [] - - if (store.customOn[tab] === true) return list.length - - return Math.max( - 0, - list.findIndex((item) => store.answers[tab]?.includes(item.value) ?? false), - ) - } - - // 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 - const el = next === options().length ? customRef : optsRef[next] - el?.focus({ preventScroll: true }) - - if (!how?.preventScroll) reveal(rowAt(next)) - } - - const rowAt = (i: number) => (i === options().length ? customRow : optsRef[i]) - - // A list that scrolls follows the highlighted answer at once, keeping it clear of the feathered edges. - const reveal = (row: HTMLElement | undefined, view = optionsRef?.clientHeight ?? 0) => { - if (!row || !optionsRef || !listRef) return - const top = row.offsetTop + listRef.offsetTop - const edge = Math.min(feather, view / 4) - optionsRef.scrollTop = Math.min(top - edge, Math.max(optionsRef.scrollTop, top + row.offsetHeight + edge - view)) - scroll.top = optionsRef.scrollTop - pin() - } - - // The leaving copy of the answers stays where they were on screen however far the live list scrolls under it. - const pin = () => { - const answers = ghost?.els[1] - - if (ghost && answers) answers.style.top = `${scroll.top - ghost.scroll}px` - } - - // Measuring reads layout, so it waits while the dock's own springs are moving and runs once they come to rest. - let measuring: number | undefined - - const requestMeasure = () => { - if (stop || measuring !== undefined) return - measuring = requestAnimationFrame(() => { - measuring = undefined - measure() - }) - } - - onMount(() => { - measure() - - makeEventListener(window, "resize", requestMeasure) - - const dock = root?.closest('[data-component="session-composer-dock"]') - const scroller = document.querySelector('[data-slot="session-timeline-scroll"] > .scroll-view__viewport') - createResizeObserver([dock, scroller], requestMeasure) - - onCleanup(() => { - if (measuring !== undefined) cancelAnimationFrame(measuring) - }) - - focus(pickFocus()) - }) - - createEffect(() => { - const list = listRef - const details = detailsRef - - if (!list || !details) return - - const observer = new ResizeObserver((entries) => { - const fresh = { details: content.details === 0, list: content.list === 0 } - - entries.forEach((entry) => { - const size = entry.borderBoxSize[0]?.blockSize - - if (size === undefined) return - const key = entry.target === list ? "list" : "details" - content[key] = size - - if (key === "list") setStore("listHeight", size) - }) - - // The answers box opens only as far as the room the new question text leaves it at rest. - ;(["details", "list"] as const).forEach((key) => { - const spring = boxes[key] - const size = key === "list" ? Math.min(content.list, settled()) : content.details - - if (spring.target === size) return - - if (fresh[key] || !questionMotion()) spring.snap(size) - else tune(spring, resize()).set(size) - }) - wake() - }) - - observer.observe(list) - observer.observe(details) - onCleanup(() => observer.disconnect()) - }) - - // One highlight card jumps between answers by its clip, so only one answer ever looks highlighted. - createEffect(() => { - const el = highlightRef - const index = store.focus - const row = rowAt(index) - void store.listHeight - - if (!el || !row || !listRef) return - el.style.clipPath = `inset(${row.offsetTop}px 0 ${listRef.offsetHeight - row.offsetTop - row.offsetHeight}px round 6px)` - }) - - onCleanup(() => { - if (replied) return - cache.set(cacheKey, { - tab: store.tab, - answers: store.answers.map((a) => (a ? [...a] : [])), - custom: store.custom.map((s) => s ?? ""), - customOn: store.customOn.map((b) => b ?? false), - }) - }) - - const fail = (err: Error) => showToast({ title: language.t("common.requestFailed"), description: err.message }) - - const replyMutation = useMutation(() => ({ - mutationFn: (answer: FormAnswer) => - serverSDK.api.session.form.reply({ sessionID: props.request.sessionID, formID: props.request.id, answer }), - onMutate: () => { - props.onSubmit() - }, - onSuccess: () => { - replied = true - cache.delete(cacheKey) - }, - onError: fail, - })) - - const rejectMutation = useMutation(() => ({ - mutationFn: () => - serverSDK.api.session.form.cancel({ sessionID: props.request.sessionID, formID: props.request.id }), - onMutate: () => { - props.onSubmit() - }, - onSuccess: () => { - replied = true - cache.delete(cacheKey) - }, - onError: fail, - })) - - const sending = createMemo(() => replyMutation.isPending || rejectMutation.isPending) - const submitShortcut = () => (IS_MAC ? "⌘⏎" : `${language.t("common.key.ctrl")}+⏎`) - const backShortcut = () => (IS_MAC ? "⌘[" : `${language.t("common.key.alt")}+←`) - - const reply = (answer: FormAnswer) => { - if (sending()) return - replyMutation.mutate(answer) - } - - const reject = () => { - if (sending()) return - rejectMutation.mutate() - } - - const submit = () => - reply( - Object.fromEntries( - questions().flatMap((question, index) => { - const answers = store.answers[index] ?? [] - - if (answers.length === 0) return [] - - return [[question.field.key, question.multiple ? answers : answers[0]]] - }), - ), - ) - - const answered = (i: number) => { - if ((store.answers[i]?.length ?? 0) > 0) return true - - return store.customOn[i] === true && (store.custom[i] ?? "").trim().length > 0 - } - - const picked = (answer: string) => store.answers[store.tab]?.includes(answer) ?? false - - const pick = (answer: string) => { - setStore("answers", store.tab, [answer]) - setStore("customOn", store.tab, false) - setStore("editing", false) - } - - const toggle = (answer: string) => { - setStore("answers", store.tab, (current = []) => { - if (current.includes(answer)) return current.filter((item) => item !== answer) - - return [...current, answer] - }) - } - - 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 - - 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)) - setStore("editing", false) - focus(options().length) - } - - // Scrolling the list under a still cursor makes the browser fire a pointermove at the same spot; it is not the user. - let pointer = { x: -1, y: -1 } - - // 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) => { - const still = event.clientX === pointer.x && event.clientY === pointer.y - pointer = { x: event.clientX, y: event.clientY } - - if (event.pointerType !== "mouse" || still || store.editing || sending()) return - setLit("hover") - 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 - - 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 - } - - if (intent.type === "advance") { - event.preventDefault() - next() - - 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 (step < 0) return back() - - if (!last()) jump(store.tab + 1) - - return - } - - if (store.minimized || sending()) return - - if (intent.type === "move" || intent.type === "edge") setLit("keys") - - if (intent.type === "number") { - event.preventDefault() - - if (intent.index === options().length) return customToggle() - - selectOption(intent.index) - focus(intent.index) - - return - } - - event.preventDefault() - - 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) => { - if (sending()) return - - const opt = options()[optIndex] - - if (!opt) return - - if (multi()) { - setStore("editing", false) - toggle(opt.value) - - return - } - - pick(opt.value) - } - - const commitCustom = () => { - setStore("editing", false) - customUpdate(input()) - focus(options().length) - } - - const next = () => { - if (sending()) return - - if (store.editing) commitCustom() - - if (store.tab >= total() - 1) { - submit() - - return - } - - jump(store.tab + 1) - } - - const back = () => { - if (sending()) return - - if (store.tab <= 0) return - jump(store.tab - 1) - } - - // Switching questions: the question being left is copied into a still, inert ghost over its place, while the live - // text and answers show the new question. One spring then moves both: the ghost blurs, shrinks and fades away while - // the new question resolves in its place, each shifted by `travel` toward the way they go. The ghost is gone only once - // the new question has fully arrived, so the card is never empty. - // - // A key pressed mid-switch carries on from what is on screen, at the speed it is moving. Going back to the question - // still leaving brings that copy back from where it is, while the live one turns into the leaving ghost. Going on to - // another question keeps only the more visible of the two copies on screen as the one ghost, and the new question - // comes in. - const depart = (tab: number) => { - if (!detailsRef || !listRef || !detailsFrame || !optionsTrack) return - const v = tuning - const step = Math.sign(tab - store.tab) - const dir = root?.matches(":dir(rtl)") ? -step : step - const reach = v.travel() - const options = v.spring() - const live = into ? arriving(into, v) : rest - const moving = into ? speed(into) : 0 - const back = ghost?.tab === tab ? ghost : undefined - const kept = !back && ghost && leaving(ghost, v, into).shown > live.shown ? ghost : undefined - - if (ghost && ghost !== kept) ghost.els.forEach((el) => el.remove()) - // A kept ghost leaves on the new switch's spring from where it is, so it fades no faster than the next question - // arrives. - ghost = kept - ? { ...kept, ...track(leaving(kept, v, into), kept.to, speed(kept), options, v.launch()) } - : { - ...track(live, -dir * reach, moving, options, v.launch()), - tab: store.tab, - // The answers box scrolls back to the top for the new question, so the copy keeps its place on screen. - els: [copy(detailsRef, detailsFrame), copy(listRef, optionsTrack, -scroll.top)], - details: content.details, - list: content.list, - scroll: scroll.top, - } - into = back - ? track(leaving(back, v, into), 0, speed(back), options, v.launch()) - : track({ x: dir * reach, shown: 0, settle: 0 }, 0, 0, options, v.launch()) - } - - const dropSwitch = () => { - ghost?.els.forEach((el) => el.remove()) - ghost = undefined - into = undefined - } - - const paint = () => { - const sliding = !!(into || ghost) - - const live = look(into ? arriving(into, tuning) : rest) - - ;[detailsRef, listRef].forEach((el) => el && place(el, live)) - - if (ghost) { - const pose = look(leaving(ghost, tuning, into)) - ghost.els.forEach((el) => place(el, pose)) - } - - const folded = Math.max(0, Math.min(1, boxes.folded.value)) - // Without motion the boxes keep their natural heights, so a new question lays out at its size on the same frame. - const sized = questionMotion() - - if (detailsFrame && content.details > 0) { - const shown = boxes.details.value - detailsFrame.style.height = sized ? `${shown.toFixed(2)}px` : "" - mask(detailsFrame, 0, Math.max(content.details, ghost?.details ?? 0) - shown, shown, sliding) - } - - if (optionsRef && content.list > 0) { - // Without motion the dock's max height caps the answers box, which scrolls inside the room it leaves. - const shown = sized - ? Math.min(boxes.list.value, room()) * (1 - folded) - : folded > 0 - ? 0 - : Math.min(content.list, room()) - - optionsRef.style.height = sized ? `${shown.toFixed(2)}px` : folded > 0 ? "0px" : "" - scroll.view = shown - feathers() - } - - if (optionsRef) { - optionsRef.style.opacity = folded > 0 ? (1 - folded).toFixed(4) : "" - // Restoring shows the answers again at once, so the highlighted one can take focus. - optionsRef.style.visibility = folded > 0.98 && boxes.folded.target > 0 ? "hidden" : "" - } - - if (chevron) chevron.style.transform = folded > 0 ? `rotate(${(folded * 180).toFixed(2)}deg)` : "" - - if (pip) pip.style.transform = `translate3d(${bar.value.toFixed(2)}px,0,0)` - - paintFooter() - } - - // The answers fade out at whichever edge has more of them past it, while they open or scroll. - // It reads where the list is scrolled from the last scroll, never from layout, since it runs every frame. - const feathers = () => { - if (!optionsRef) return - const above = scroll.top - const shown = scroll.view - mask(optionsRef, above, Math.max(content.list, ghost?.list ?? 0) - above - shown, shown, !!(into || ghost)) - } - - const paintFooter = () => { - if (backBox) { - const shown = unit(foot.back.value) - const hidden = 1 - shown - const x = foot.shift.value + (rtl ? -1 : 1) * footer.travel() * hidden - const scale = 1 - (1 - tuning.scale()) * hidden - const moving = !foot.back.resting || !foot.shift.resting - backBox.style.transform = moving ? `translate3d(${x.toFixed(2)}px,0,0) scale(${scale.toFixed(4)})` : "" - backBox.style.opacity = moving ? shown.toFixed(4) : "" - backBox.style.filter = - moving && tuning.blur() * hidden >= 0.05 ? `blur(${(tuning.blur() * hidden).toFixed(2)}px)` : "" - backBox.style.visibility = moving ? "visible" : "" - } - - if (!nextFace || !submitFace || !nextLabel || !submitLabel) return - const s = unit(foot.submit.value) - - if (foot.submit.resting || !widths.next || !widths.submit) { - ;[nextFace, submitFace, nextLabel, submitLabel].forEach((el) => el.removeAttribute("style")) - - return - } - - // The wider face is cut back from its start edge to the width the button has reached. - const width = widths.next + (widths.submit - widths.next) * s - const wide = widths.submit > widths.next ? submitFace : nextFace - const cut = Math.max(widths.next, widths.submit) - width - const clip = cut < 0.5 ? "" : `inset(0 ${rtl ? cut.toFixed(2) : 0}px 0 ${rtl ? 0 : cut.toFixed(2)}px round 6px)` - - const by = footer.fade() - showFace(nextFace, nextLabel, unit((1 - s) / by), unit(1 - s / by), nextFace === wide ? clip : "") - showFace(submitFace, submitLabel, unit(s / by), unit(1 - (1 - s) / by), submitFace === wide ? clip : "") - } - - const tick = (dt: number) => { - into?.spring.step(dt) - ghost?.spring.step(dt) - boxes.details.step(dt) - boxes.list.step(dt) - boxes.folded.step(dt) - bar.step(dt) - Object.values(foot).forEach((spring) => spring.step(dt)) - - if (into?.spring.resting) into = undefined - - if (ghost && leaving(ghost, tuning, into).shown <= 0) { - ghost.els.forEach((el) => el.remove()) - ghost = undefined - } - - paint() - - const footing = Object.values(foot).some((spring) => !spring.resting) - - if ( - into || - ghost || - footing || - !bar.resting || - !boxes.details.resting || - !boxes.list.resting || - !boxes.folded.resting - ) - return true - stop = undefined - requestMeasure() - - return false - } - - const wake = () => { - if (!questionMotion()) return still() - stop ??= frameLoop.add(tick) - } - - // Everything lands where it is going, now: no frame job runs. - const still = () => { - stop?.() - stop = undefined - dropSwitch() - ;[...Object.values(boxes), ...Object.values(foot), bar].forEach((spring) => spring.snap(spring.target)) - paint() - } - - // Turning the knob off also lands any running pick or dash transition. - createEffect(() => { - if (questionMotion()) return - still() - root?.getAnimations({ subtree: true }).forEach((animation) => animation.cancel()) - }) - onCleanup(() => stop?.()) - - const jump = (tab: number) => { - if (sending() || tab === store.tab) return - const animate = !store.minimized && questionMotion() - - if (animate) depart(tab) - else dropSwitch() - - rtl = !!root?.matches(":dir(rtl)") - widths.next = nextFace?.offsetWidth ?? 0 - widths.submit = submitFace?.offsetWidth ?? 0 - const before = backBox?.offsetLeft ?? 0 - // 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. - batch(() => { - setStore("focus", pickFocus(tab)) - - if (lit() === "hover") setLit("none") - setStore("tab", tab) - setStore("editing", false) - }) - optsRef.length = options().length - - if (optionsRef) optionsRef.scrollTop = scroll.top = 0 - - const reduced = !questionMotion() - - if (reduced) bar.snap(dash(tab)) - else tune(bar, tuning.spring()).set(dash(tab)) - - // Back stays where it was on screen while the button beside it changes width, and slides to its new place. - foot.shift.value += before - (backBox?.offsetLeft ?? 0) - - const targets = { back: tab > 0 ? 1 : 0, submit: tab >= total() - 1 ? 1 : 0, shift: 0 } - - ;(["back", "submit", "shift"] as const).forEach((key) => { - if (reduced) foot[key].snap(targets[key]) - else tune(foot[key], footer.spring()).set(targets[key]) - }) - // The first frame is painted now, so the new question never shows at rest before it arrives. - paint() - - if (store.minimized) { - // A button that just gave way to the other one can no longer hold focus. - if (document.activeElement?.closest("[inert]")) (last() ? submitFace : nextFace)?.querySelector("button")?.focus() - wake() - - return - } - - // The answers box is still springing to the new list's height, so the answer that takes focus comes into view of - // the height it will rest at. - focus(pickFocus(tab), { preventScroll: true }) - - if (optionsRef && detailsRef) - reveal(rowAt(store.focus), Math.min(optionsRef.scrollHeight, settled(detailsRef.offsetHeight))) - - wake() - } - - const cycle = (by: number) => { - if (total() < 2) return - jump((store.tab + by + total()) % total()) - } - - onCleanup( - motionTuning.action({ id: "question.next", label: "Next question", group, subsection, run: () => cycle(1) }), - ) - onCleanup( - motionTuning.action({ id: "question.back", label: "Previous question", group, subsection, run: () => cycle(-1) }), - ) - - command.register("session.question.back", () => [ - { - id: "session.question.back", - title: language.t("ui.common.back"), - keybind: IS_MAC ? "mod+[" : "alt+arrowleft", - hidden: true, - // Stay registered while sending so the shortcut does not fall through to history navigation. - disabled: store.tab <= 0, - when: () => store.tab > 0, - onSelect: back, - }, - ]) - - const minimize = () => { - if (sending()) return - setStore("editing", false) - setStore("minimized", true) - fold(1) - } - - const restore = () => { - if (sending()) return - setStore("minimized", false) - fold(0) - paint() - // The answers box is still opening, so its answer comes into view of the height it will rest at. - const index = pickFocus() - focus(index, { preventScroll: true }) - - if (detailsRef) reveal(rowAt(index), Math.min(content.list, settled(detailsRef.offsetHeight))) - } - - const fold = (target: number) => { - tune(boxes.folded, minimizing).set(target) - wake() - } +import { Show } from "solid-js" +import type { FormInfo } from "@opencode/client/promise" +import { useSettings } from "@/settings/model" +import { SessionQuestionDockClassic } from "./session-question-dock-classic" +import { SessionQuestionDockExperimental } from "./session-question-dock-experimental" + +export function SessionQuestionDock(props: { request: FormInfo; onSubmit: () => void }) { + const settings = useSettings() return ( -
- (root = el)} - onKeyDown={nav} - header={ - <> -
-
- - {summary()[0]} - 1}> - - - - {summary().slice(1).join("")} - - -
-
- 1}> -
- {/* Without motion there is no sliding bar: the current question's dash lights instead. */} - - - - - {(_, i) => ( - - )} - -
-
- (chevron = el)} - icon={} - variant="ghost" - size="large" - disabled={sending()} - onClick={store.minimized ? restore : minimize} - aria-label={language.t(store.minimized ? "session.question.restore" : "session.question.minimize")} - /> -
-
-
(detailsFrame = el)}> -
(detailsRef = el)}> -
- {question()?.question} -
- -
{language.t("ui.question.multiHint")}
-
-
-
- - } - footer={ - <> - -
- {/* Back stays in place while hidden, so it can come and go without moving anything. */} -
0} - inert={store.tab === 0} - ref={(el) => (backBox = el)} - > - - {language.t("ui.common.back")} - {backShortcut()} - - } - > - - -
- {/* Next and Submit share one place and one tooltip; the one not in use lies under it, inert. */} - - {last() ? language.t("ui.common.submit") : language.t("ui.common.next")} - {submitShortcut()} - - } - > -
-
(nextFace = el)} - > - -
-
(submitFace = el)} - > - -
-
-
-
- - } - > -
(optionsRef = el)} - data-slot="question-options" - role={multi() ? "group" : "radiogroup"} - aria-label={question()?.question} - inert={store.minimized} - aria-hidden={store.minimized ? "true" : undefined} - onScroll={(event) => { - scroll.top = event.currentTarget.scrollTop - pin() - feathers() - }} - // 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() - }} - > -
(optionsTrack = el)}> -
(listRef = el)} - onPointerDown={(event) => setLit(event.pointerType === "mouse" ? "hover" : "none")} - onPointerLeave={() => { - pointer = { x: -1, y: -1 } - - if (lit() === "hover") setLit("none") - }} - > - (highlightRef = el)} - aria-hidden="true" - /> - - {(opt, i) => ( - - -
(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() - }} - > - - (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() - - if (!e.repeat) next() - }} - onInput={(e) => { - setStore("customOn", store.tab, true) - customUpdate(e.currentTarget.value, true) - }} - /> -
-
-
-
-
-
+ }> + + ) } - -// Comes into place from where it set off, fully shown by the fade-in point, which is never after the fade-out point, so -// the two copies together always show at least one whole question. It sharpens and grows over the whole spring. -function arriving(track: Track, v: Tuning): Pose { - const p = unit(track.spring.value) - - return { - x: track.from.x + (track.to - track.from.x) * p, - shown: track.from.shown + (1 - track.from.shown) * unit(p / Math.min(v.fadeIn(), v.fadeOut())), - settle: track.from.settle + (1 - track.from.settle) * p, - } -} - -// Leaves from where it set off, fully gone by the fade-out point, but never fading faster than `next` arrives, so a -// copy kept through rapid keys holds the card until the new question has caught up. -function leaving(track: Track, v: Tuning, next?: Track): Pose { - const p = unit(track.spring.value) - const gone = unit(p / v.fadeOut()) - const arrived = next ? arriving(next, v).shown : 1 - - return { - x: track.from.x + (track.to - track.from.x) * p, - shown: Math.max(track.from.shown * (1 - gone), Math.min(track.from.shown, 1 - arrived)), - settle: track.from.settle * (1 - gone), - } -} - -function unit(value: number) { - return Math.max(0, Math.min(1, value)) -} - -function speed(track: Track) { - return (track.to - track.from.x) * track.spring.velocity -} - -// Sets off from `from` at the speed it already had on screen, plus the key's launch. The start is capped at the -// spring's natural speed so it never overshoots its place. -function track(from: Pose, to: number, moving: number, options: DurationOptions, launch: number): Track { - const spring = Spring.fromDuration(0, options) - const distance = to - from.x - const carried = Math.abs(distance) < 0.5 ? 0 : moving / distance - - return { - from, - to, - spring: spring.set(1, { velocity: Math.min(spring.omega, carried + spring.omega * launch) }), - } -} - -type Look = { transform: string; opacity: string; blur: number } - -// How a copy in `pose` is drawn: it blurs and shrinks toward the top of the card as it goes. -function look(pose: Pose): Look { - const unsettled = 1 - pose.settle - const scale = 1 - (1 - tuning.scale()) * unsettled - const blur = tuning.blur() * unsettled - const moved = Math.abs(pose.x) >= 0.01 || scale < 0.9999 - - return { - transform: moved ? `translate3d(${pose.x.toFixed(2)}px,0,0) scale(${scale.toFixed(4)})` : "", - opacity: pose.shown >= 1 ? "" : pose.shown.toFixed(4), - blur: blur < 0.05 ? 0 : blur, - } -} - -function tune(spring: Spring, options: DurationOptions) { - spring.omega = (2 * Math.PI) / options.duration - spring.zeta = 1 - options.bounce - - return spring -} - -// The label's opacity is relative to its face's, which already applies. -function showFace(face: HTMLElement, label: HTMLElement, opacity: number, shown: number, clip: string) { - face.style.visibility = "visible" - face.style.opacity = opacity.toFixed(4) - face.style.clipPath = clip - label.style.opacity = opacity > 0 ? Math.min(1, shown / opacity).toFixed(4) : "0" - label.style.filter = shown < 0.98 ? `blur(${(tuning.blur() * (1 - shown)).toFixed(2)}px)` : "" -} - -function place(el: HTMLElement, look: Look) { - el.style.transform = look.transform - el.style.opacity = look.opacity - el.style.filter = look.blur === 0 ? "" : `blur(${look.blur.toFixed(2)}px)` -} - -// While a switch is under way, content sliding into a box's side gutters fades out there. While a box is shorter than -// what it holds, its bottom fades instead of ending hard, over no more than a third of the box. -function mask(el: HTMLElement, above: number, below: number, shown: number, sliding: boolean) { - const top = Math.min(feather, above, shown / 3) - const bottom = Math.min(feather, below, shown / 3) - - const layers = [ - sliding - ? "linear-gradient(to right, transparent, #000 var(--question-gutter), #000 calc(100% - var(--question-gutter)), transparent)" - : "", - top > 0.5 ? `linear-gradient(to bottom, transparent, #000 ${top.toFixed(2)}px)` : "", - bottom > 0.5 ? `linear-gradient(to top, transparent, #000 ${bottom.toFixed(2)}px)` : "", - ].filter(Boolean) - - if (layers.length === 0) return el.style.removeProperty("mask-image") - el.style.setProperty("mask-image", layers.join(", ")) -} - -// A still copy of `el` laid over it in `host`, after the live content so it never comes first in the DOM, inert and -// hidden from assistive tech. Ids are dropped so they stay unique, and typed text is carried over. -function copy(el: HTMLElement, host: HTMLElement, top = 0) { - // SAFETY: a deep clone of an element is an element of the same kind. - const clone = el.cloneNode(true) as HTMLElement - clone.removeAttribute("id") - clone.querySelectorAll("[id]").forEach((node) => node.removeAttribute("id")) - // The answer highlight jumps; the leaving copy never carries a second one off with it. - clone.querySelector('[data-slot="question-highlight"]')?.remove() - const inputs = el.querySelectorAll("input") - clone.querySelectorAll("input").forEach((input, index) => (input.value = inputs[index]?.value ?? "")) - clone.dataset.ghost = "true" - clone.inert = true - clone.setAttribute("aria-hidden", "true") - clone.style.position = "absolute" - clone.style.top = `${top}px` - clone.style.insetInline = "var(--question-gutter)" - clone.style.pointerEvents = "none" - host.append(clone) - - return clone -} - -// The nearest of `el` and its ancestors that has a height. -function bounds(el: Element | null | undefined): DOMRect | undefined { - if (!el) return undefined - const rect = el.getBoundingClientRect() - - return rect.height >= 1 ? rect : bounds(el.parentElement) -} diff --git a/packages/app/src/settings/experimental/experimental.tsx b/packages/app/src/settings/experimental/experimental.tsx index a87b53ca7f9..3128ae89092 100644 --- a/packages/app/src/settings/experimental/experimental.tsx +++ b/packages/app/src/settings/experimental/experimental.tsx @@ -50,6 +50,20 @@ export const SettingsExperimental: Component = () => { />
+ +
+ settings.general.setNewQuestionUI(checked)} + hideLabel + > + {language.t("settings.experimental.row.newQuestionUI.title")} + +
+
diff --git a/packages/app/src/settings/model.test.ts b/packages/app/src/settings/model.test.ts index 974f8460645..e1041cdbf79 100644 --- a/packages/app/src/settings/model.test.ts +++ b/packages/app/src/settings/model.test.ts @@ -97,6 +97,7 @@ describe("settings schema", () => { timelineWidth: "comfortable", newIcons: false, foldUserMessages: false, + newQuestionUI: false, mobileTitlebarPosition: "top", followUpBehavior: "steer", }, @@ -134,6 +135,7 @@ describe("settings schema", () => { followUpBehavior: "invalid", backgroundActivity: "invalid", timelineWidth: "invalid", + newQuestionUI: "invalid", }, appearance: { fontSize: "large", mono: "Custom Mono", tabLayout: "vertical", showProjectName: true }, permissions: { autoApprove: true, autoApproveProjects: { on: true, off: false, bad: "yes" } }, @@ -150,6 +152,7 @@ describe("settings schema", () => { followUpBehavior: "steer", backgroundActivity: "left", timelineWidth: "comfortable", + newQuestionUI: false, }) expect(settings.appearance).toEqual({ fontSize: 14, diff --git a/packages/app/src/settings/model.tsx b/packages/app/src/settings/model.tsx index 22a56586609..eaac96dbdd6 100644 --- a/packages/app/src/settings/model.tsx +++ b/packages/app/src/settings/model.tsx @@ -131,6 +131,8 @@ const generalSchema = Persistence.struct({ newIcons: Schema.Boolean, // The "Fold long messages" experiment, off until it ships. foldUserMessages: Schema.Boolean, + // The redesigned keyboard-first question dock, off until it ships. + newQuestionUI: Schema.Boolean, mobileTitlebarPosition: Schema.Literals(["top", "bottom"]), // Owned by the review plugin, which copies it out once; kept so settings rewrites cannot drop it first. mobileDiffWrap: Persistence.optional(Schema.Boolean), @@ -300,6 +302,7 @@ export const defaultSettings: Settings = { timelineWidth: "comfortable", newIcons: false, foldUserMessages: false, + newQuestionUI: false, mobileTitlebarPosition: "top", followUpBehavior: "steer", }, @@ -412,6 +415,10 @@ export const { use: useSettings, provider: SettingsProvider } = createSimpleCont setFoldUserMessages(value: boolean) { setStore("general", "foldUserMessages", value) }, + newQuestionUI: withFallback(() => store.general?.newQuestionUI, defaultSettings.general.newQuestionUI), + setNewQuestionUI(value: boolean) { + setStore("general", "newQuestionUI", value) + }, mobileTitlebarPosition: withFallback( () => store.general?.mobileTitlebarPosition, defaultSettings.general.mobileTitlebarPosition, diff --git a/packages/app/src/settings/search-catalog.ts b/packages/app/src/settings/search-catalog.ts index 1d5219568da..ae061ee87de 100644 --- a/packages/app/src/settings/search-catalog.ts +++ b/packages/app/src/settings/search-catalog.ts @@ -111,6 +111,13 @@ export const clientSettings: Entry[] = [ description: "settings.experimental.row.foldUserMessages.description", keywords: "fold collapse long messages prompts read more", }, + { + tab: "experimental", + label: "settings.experimental.row.newQuestionUI.title", + target: "settings-new-question-ui", + description: "settings.experimental.row.newQuestionUI.description", + keywords: "question answers keyboard dock redesign", + }, { tab: "appearance", label: "settings.general.row.colorScheme.title", diff --git a/packages/app/src/settings/search-results.test.ts b/packages/app/src/settings/search-results.test.ts index abd1f55f681..51469e2b15b 100644 --- a/packages/app/src/settings/search-results.test.ts +++ b/packages/app/src/settings/search-results.test.ts @@ -75,6 +75,10 @@ describe("settings search index", () => { .map((item) => item.page), ).toEqual(["Desktop notifications", "Sound effects"]) expect(rankSettings("follow-up behavior", items)[0].page).toBe("Preferences / General") + expect(rankSettings("new question UI", items)[0].view).toMatchObject({ + tab: "experimental", + target: "settings-new-question-ui", + }) expect(rankSettings("capsule", items)[0].view).toMatchObject({ tab: "general", target: "settings-background-activity", diff --git a/packages/session-ui/src/components/dock-prompt.tsx b/packages/session-ui/src/components/dock-prompt.tsx index 95056a94d4b..5c8f259a514 100644 --- a/packages/session-ui/src/components/dock-prompt.tsx +++ b/packages/session-ui/src/components/dock-prompt.tsx @@ -2,6 +2,7 @@ import type { JSX } from "solid-js" export function DockPrompt(props: { kind: "question" | "permission" + variant?: "experimental" header: JSX.Element children: JSX.Element footer: JSX.Element @@ -11,7 +12,13 @@ export function DockPrompt(props: { const slot = (name: string) => `${props.kind}-${name}` return ( -
+
{props.header}
{props.children}
diff --git a/packages/session-ui/src/components/message-part.css b/packages/session-ui/src/components/message-part.css index dcf92ce0eb0..6588a6eaa00 100644 --- a/packages/session-ui/src/components/message-part.css +++ b/packages/session-ui/src/components/message-part.css @@ -1380,7 +1380,8 @@ scroll-margin-top: var(--sticky-accordion-top, 0px); } -[data-component="dock-prompt"] { +[data-component="dock-prompt"][data-kind="permission"], +[data-component="dock-prompt"][data-variant="experimental"] { position: relative; display: flex; flex-direction: column; diff --git a/packages/session-ui/src/components/question-prompt-experimental.css b/packages/session-ui/src/components/question-prompt-experimental.css new file mode 100644 index 00000000000..b54036dbba9 --- /dev/null +++ b/packages/session-ui/src/components/question-prompt-experimental.css @@ -0,0 +1,568 @@ +[data-component="dock-prompt"][data-kind="question"][data-variant="experimental"] { + --v2-question-answer-bg-selected: light-dark(#f5f8ff, #7698fd26); + /* A bounce-0 spring sampled for CSS: with the dock's motion on, every pick 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-pick: 120ms; + --question-settle: 300ms; + + max-block-size: var(--question-prompt-max-height, 100dvh); + font-family: var(--v2-font-family-sans); + + [data-slot="question-body"] { + display: flex; + flex-direction: column; + gap: 16px; + flex: 1; + min-block-size: 0; + padding: 8px; + } + + [data-slot="question-header"] { + display: flex; + flex-direction: column; + gap: 4px; + flex-shrink: 0; + min-inline-size: 0; + padding-inline: 10px; + } + + [data-slot="question-header-top"] { + display: flex; + align-items: center; + justify-content: space-between; + gap: 12px; + min-block-size: 28px; + min-inline-size: 0; + } + + [data-slot="question-header-title"] { + min-inline-size: 0; + font-size: 13px; + font-weight: 440; + line-height: var(--line-height-base); + color: var(--v2-text-text-muted); + overflow-wrap: anywhere; + } + + [data-slot="question-header-actions"] { + display: flex; + align-items: center; + gap: 8px; + flex-shrink: 0; + + [data-component="icon-button-v2"] { + flex-shrink: 0; + color: var(--v2-icon-icon-muted); + } + + [data-slot="icon-svg"] { + flex-shrink: 0; + } + } + + /* Holds the question text at its sprung height, and the outgoing copy of it while questions switch. It reaches into + the header's side padding, so text sliding past a side fades out in that gutter instead of over the text at rest. */ + [data-slot="question-details-frame"] { + --question-gutter: 10px; + position: relative; + min-inline-size: 0; + margin-inline: calc(-1 * var(--question-gutter)); + padding-inline: var(--question-gutter); + overflow: clip; + mask-composite: intersect; + } + + /* A question switching away shrinks toward its top, and the next one grows from there. */ + [data-slot="question-details"] { + display: flex; + flex-direction: column; + gap: 4px; + min-inline-size: 0; + transform-origin: 50% 0; + } + + [data-slot="question-text"] { + font-size: 13px; + font-weight: 530; + line-height: var(--line-height-base); + color: var(--v2-text-text-base); + overflow-wrap: anywhere; + -webkit-user-select: text; + user-select: text; + } + + [data-slot="question-hint"] { + font-size: 11px; + font-weight: 440; + line-height: var(--line-height-tight); + color: var(--v2-text-text-faint); + overflow-wrap: anywhere; + } + + /* Each segment is a 20px button holding a 14px dash, 2px apart, so dashes repeat every 22px from 3px in. */ + [data-slot="question-progress"] { + position: relative; + display: flex; + align-items: center; + gap: 2px; + flex-shrink: 0; + } + + /* The current question's bar slides along a strip that shows only through the dashes, never in the gaps. */ + [data-slot="question-progress-track"] { + position: absolute; + z-index: 1; + inset-inline: 0; + inset-block-start: calc(50% - 1px); + block-size: 2px; + pointer-events: none; + -webkit-mask-image: repeating-linear-gradient(to right, transparent 0 3px, #000 3px 17px, transparent 17px 22px); + mask-image: repeating-linear-gradient(to right, transparent 0 3px, #000 3px 17px, transparent 17px 22px); + } + + [data-slot="question-progress"]:has(:disabled) [data-slot="question-progress-track"] { + opacity: 0.5; + } + + [data-slot="question-progress-current"] { + position: absolute; + inset-block: 0; + inset-inline-start: 3px; + inline-size: 14px; + background-color: var(--v2-icon-icon-base); + will-change: transform; + } + + [data-slot="question-progress-segment"] { + display: inline-flex; + align-items: center; + justify-content: center; + flex-shrink: 0; + inline-size: 20px; + block-size: 20px; + padding: 0; + border: 0; + border-radius: 4px; + background: transparent; + cursor: pointer; + touch-action: manipulation; + + &[data-answered="true"] [data-slot="question-progress-bar"]::before { + transform: scaleX(1); + } + + &:focus-visible { + outline: 2px solid var(--v2-border-border-focus); + outline-offset: 1px; + } + + &:disabled { + cursor: not-allowed; + opacity: 0.5; + } + } + + [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); + + /* Answering fills the segment from its start. */ + &::before { + content: ""; + position: absolute; + inset: 0; + background-color: var(--v2-background-bg-accent); + transform: scaleX(0); + transform-origin: left; + } + + &:dir(rtl)::before { + transform-origin: right; + } + } + + [data-slot="question-content"] { + display: flex; + flex-direction: column; + flex: 1; + min-block-size: 0; + min-inline-size: 0; + } + + /* Reaches into the body's side padding like the question text's frame, for the same gutter. */ + [data-slot="question-options"] { + --question-gutter: 8px; + flex: 1 1 auto; + min-block-size: 0; + min-inline-size: 0; + margin: 0 calc(-1 * var(--question-gutter)); + padding: 0; + overflow-y: auto; + scrollbar-width: none; + mask-composite: intersect; + + &::-webkit-scrollbar { + display: none; + } + } + + /* Holds the answers and the outgoing copy of them while questions switch. It clips them at its sides, so answers + sliding past never make the box scroll sideways. */ + [data-slot="question-options-track"] { + position: relative; + padding-inline: var(--question-gutter); + overflow-x: clip; + } + + [data-slot="question-options-list"] { + display: flex; + flex-direction: column; + gap: 2px; + position: relative; + isolation: isolate; + transform-origin: 50% 0; + } + + /* One highlight for the whole list, painted under the keyboard-focused answer by its clip. + Only the navigation keys show it; the pick itself shows only on the key. */ + [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; + + &[data-shown="false"] { + visibility: hidden; + } + } + + [data-slot="question-option"] { + display: flex; + align-items: flex-start; + gap: 8px; + flex-shrink: 0; + box-sizing: border-box; + inline-size: 100%; + position: relative; + padding: 10px; + border: 0; + border-radius: 6px; + outline: none; + background: transparent; + color: var(--v2-text-text-base); + text-align: start; + cursor: pointer; + touch-action: manipulation; + + &:disabled, + &[data-disabled="true"] { + cursor: not-allowed; + opacity: 0.5; + } + } + + [data-slot="question-option-check"] { + display: inline-flex; + align-items: center; + justify-content: center; + inline-size: 18px; + block-size: 20px; + flex: 0 0 18px; + } + + /* An answer's key is its mark. One answer: a round key with a soft fill. Many: a hollow square key, like a checkbox. + Picking fills either solid, with the number in the inverse colour. */ + [data-slot="question-option-key"] { + display: inline-flex; + align-items: center; + justify-content: center; + box-sizing: border-box; + inline-size: 18px; + block-size: 18px; + position: relative; + isolation: isolate; + border-radius: 50%; + background-color: var(--v2-background-bg-layer-03); + box-shadow: inset 0 0 0 0.5px var(--v2-border-border-base); + color: var(--v2-text-text-muted); + font-size: 11px; + font-weight: 530; + line-height: 1; + font-variant-numeric: tabular-nums; + + &::before { + content: ""; + position: absolute; + inset: 0; + z-index: -1; + border-radius: inherit; + background-color: var(--v2-background-bg-accent); + opacity: 0; + } + + &[data-type="checkbox"] { + border-radius: 4px; + background-color: transparent; + box-shadow: inset 0 0 0 1px var(--v2-border-border-strong); + } + + &[data-picked="true"] { + color: var(--v2-text-text-contrast); + box-shadow: inset 0 0 0 1px transparent; + + &::before { + opacity: 1; + } + } + } + + [data-slot="question-option-main"] { + display: flex; + flex-direction: column; + gap: 4px; + min-inline-size: 0; + flex: 1; + } + + [data-slot="option-label"] { + font-family: var(--v2-font-family-sans); + font-size: 13px; + font-weight: 530; + line-height: var(--line-height-base); + color: var(--v2-text-text-base); + overflow-wrap: anywhere; + } + + [data-slot="option-description"] { + min-inline-size: 0; + font-family: var(--v2-font-family-sans); + font-size: 13px; + font-weight: 440; + line-height: var(--line-height-base); + color: var(--v2-text-text-muted); + overflow-wrap: anywhere; + white-space: normal; + } + + [data-slot="question-option"][data-custom="true"] { + align-items: center; + block-size: 40px; + min-block-size: 40px; + max-block-size: 40px; + padding-block: 0; + padding-inline: 10px; + + &:not([data-editing="true"]) [data-slot="text-input-v2-input"] { + font-weight: 530; + } + + &[data-editing="true"] .question-custom-field[data-component="text-input-v2"] { + background: + linear-gradient(180deg, var(--v2-alpha-light-2), var(--v2-alpha-light-0)), var(--v2-background-bg-base); + box-shadow: inset 0 0 0 1px var(--v2-border-border-focus); + + [data-slot="text-input-v2-input"] { + padding-inline: 8px; + + &::placeholder { + color: var(--v2-text-text-faint); + } + } + } + } + + [data-slot="question-custom-toggle"] { + display: inline-flex; + align-items: center; + justify-content: center; + inline-size: 18px; + block-size: 20px; + flex: 0 0 18px; + margin: 0; + padding: 0; + border: 0; + border-radius: 4px; + background: transparent; + cursor: pointer; + touch-action: manipulation; + + &:focus-visible { + outline: none; + } + + &:disabled { + cursor: not-allowed; + } + } + + [data-slot="question-option"] .question-custom-field[data-component="text-input-v2"] { + flex: 1; + inline-size: 100%; + min-inline-size: 0; + block-size: 28px; + align-self: center; + padding: 0; + gap: 0; + border: 0; + border-radius: 6px; + background: transparent; + box-shadow: none; + outline: none; + opacity: 1; + transition: none; + + [data-slot="text-input-v2-value"] { + min-inline-size: 0; + min-block-size: 0; + gap: 0; + } + + [data-slot="text-input-v2-input"] { + box-sizing: border-box; + inline-size: 100%; + min-inline-size: 0; + block-size: 28px; + margin: 0; + padding: 0; + border: 0; + background: transparent; + outline: none; + font-family: var(--v2-font-family-sans); + font-size: 13px; + font-weight: 440; + line-height: var(--line-height-compact); + color: var(--v2-text-text-base); + text-align: start; + cursor: text; + + &::placeholder { + color: var(--v2-text-text-base); + opacity: 1; + } + + &:disabled { + cursor: not-allowed; + } + } + } + + [data-slot="question-footer"] { + display: flex; + box-sizing: border-box; + align-items: center; + justify-content: space-between; + flex-shrink: 0; + padding-block: 7px 8px; + padding-inline: 12px; + + > [data-component="button-v2"][data-variant="ghost"] { + color: var(--v2-text-text-muted); + } + } + + [data-slot="question-footer-actions"] { + display: flex; + align-items: center; + gap: 8px; + } + + /* While a switch runs, the dock draws the footer buttons frame by frame; at rest these rules place them. */ + [data-slot="question-footer-back"][data-shown="false"] { + visibility: hidden; + opacity: 0; + } + + [data-slot="question-advance"] { + position: relative; + display: flex; + } + + [data-slot="question-advance-face"] { + display: flex; + } + + [data-slot="question-advance-face"][data-active="false"] { + position: absolute; + inset-block-start: 0; + inset-inline-end: 0; + visibility: hidden; + opacity: 0; + } + + [data-slot="question-advance-face"][data-active="true"] { + z-index: 1; + } + + [data-slot="question-advance-label"] { + display: inline-flex; + align-items: center; + gap: 6px; + } + + [data-slot="question-submit-shortcut"] { + flex-shrink: 0; + opacity: 0.6; + } + + @media (hover: hover) and (pointer: fine) { + [data-slot="question-progress-segment"]:hover:not(:disabled) { + background-color: var(--v2-overlay-simple-overlay-hover); + } + } + + /* Without the dock's motion there is no sliding bar, so the current question's dash lights itself. */ + [data-component="session-question-dock"][data-animated="false"] & { + [data-slot="question-progress-segment"][data-active="true"] [data-slot="question-progress-bar"]::before { + background-color: var(--v2-icon-icon-base); + transform: scaleX(1); + } + } + + /* Picks and answered dashes ease only while the dock's motion is on; otherwise they change on the same frame. */ + [data-component="session-question-dock"][data-animated="true"] & { + [data-slot="question-progress-bar"]::before { + transition: transform var(--question-settle) var(--question-spring); + } + + [data-slot="question-option-key"] { + transition: + color var(--question-pick) var(--question-spring), + box-shadow var(--question-pick) var(--question-spring); + + &::before { + transition: opacity var(--question-pick) var(--question-spring); + } + } + } +} diff --git a/packages/session-ui/src/components/question-prompt.css b/packages/session-ui/src/components/question-prompt.css index aacad0d4aa3..d4d8ff0a3fb 100644 --- a/packages/session-ui/src/components/question-prompt.css +++ b/packages/session-ui/src/components/question-prompt.css @@ -1,43 +1,28 @@ -[data-component="dock-prompt"][data-kind="question"] { - --v2-question-answer-bg-selected: light-dark(#f5f8ff, #7698fd26); - /* A bounce-0 spring sampled for CSS: with the dock's motion on, every pick 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-pick: 120ms; - --question-settle: 300ms; +[data-component="dock-prompt"][data-kind="question"]:not([data-variant="experimental"]) { + --v2-question-answer-bg-selected: color-mix(in srgb, var(--v2-border-border-focus) 15%, transparent); + --question-feedback-duration: 120ms; + position: relative; + display: flex; + flex-direction: column; + gap: 0; + min-block-size: 0; max-block-size: var(--question-prompt-max-height, 100dvh); font-family: var(--v2-font-family-sans); + isolation: isolate; [data-slot="question-body"] { + position: relative; + z-index: 1; display: flex; flex-direction: column; gap: 16px; flex: 1; min-block-size: 0; - padding: 8px; + padding: 8px 12px 12px; + background-color: var(--v2-background-bg-base); + border-radius: 10px; + box-shadow: var(--v2-elevation-raised); } [data-slot="question-header"] { @@ -46,7 +31,6 @@ gap: 4px; flex-shrink: 0; min-inline-size: 0; - padding-inline: 10px; } [data-slot="question-header-top"] { @@ -62,7 +46,7 @@ min-inline-size: 0; font-size: 13px; font-weight: 440; - line-height: var(--line-height-base); + line-height: var(--line-height-compact); color: var(--v2-text-text-muted); overflow-wrap: anywhere; } @@ -83,31 +67,17 @@ } } - /* Holds the question text at its sprung height, and the outgoing copy of it while questions switch. It reaches into - the header's side padding, so text sliding past a side fades out in that gutter instead of over the text at rest. */ - [data-slot="question-details-frame"] { - --question-gutter: 10px; - position: relative; - min-inline-size: 0; - margin-inline: calc(-1 * var(--question-gutter)); - padding-inline: var(--question-gutter); - overflow: clip; - mask-composite: intersect; - } - - /* A question switching away shrinks toward its top, and the next one grows from there. */ [data-slot="question-details"] { display: flex; flex-direction: column; - gap: 4px; + gap: 8px; min-inline-size: 0; - transform-origin: 50% 0; } [data-slot="question-text"] { font-size: 13px; font-weight: 530; - line-height: var(--line-height-base); + line-height: var(--line-height-compact); color: var(--v2-text-text-base); overflow-wrap: anywhere; -webkit-user-select: text; @@ -122,40 +92,13 @@ overflow-wrap: anywhere; } - /* Each segment is a 20px button holding a 14px dash, 2px apart, so dashes repeat every 22px from 3px in. */ [data-slot="question-progress"] { - position: relative; display: flex; align-items: center; gap: 2px; flex-shrink: 0; } - /* The current question's bar slides along a strip that shows only through the dashes, never in the gaps. */ - [data-slot="question-progress-track"] { - position: absolute; - z-index: 1; - inset-inline: 0; - inset-block-start: calc(50% - 1px); - block-size: 2px; - pointer-events: none; - -webkit-mask-image: repeating-linear-gradient(to right, transparent 0 3px, #000 3px 17px, transparent 17px 22px); - mask-image: repeating-linear-gradient(to right, transparent 0 3px, #000 3px 17px, transparent 17px 22px); - } - - [data-slot="question-progress"]:has(:disabled) [data-slot="question-progress-track"] { - opacity: 0.5; - } - - [data-slot="question-progress-current"] { - position: absolute; - inset-block: 0; - inset-inline-start: 3px; - inline-size: 14px; - background-color: var(--v2-icon-icon-base); - will-change: transform; - } - [data-slot="question-progress-segment"] { display: inline-flex; align-items: center; @@ -170,8 +113,12 @@ cursor: pointer; touch-action: manipulation; - &[data-answered="true"] [data-slot="question-progress-bar"]::before { - transform: scaleX(1); + &[data-answered="true"]:not([data-active="true"]) [data-slot="question-progress-bar"]::before { + opacity: 1; + } + + &[data-active="true"] [data-slot="question-progress-bar"]::after { + opacity: 1; } &:focus-visible { @@ -190,21 +137,23 @@ inline-size: 14px; block-size: 2px; flex-shrink: 0; - overflow: hidden; background-color: var(--v2-background-bg-layer-04); - /* Answering fills the segment from its start. */ - &::before { + &::before, + &::after { content: ""; position: absolute; inset: 0; - background-color: var(--v2-background-bg-accent); - transform: scaleX(0); - transform-origin: left; + opacity: 0; } - &:dir(rtl)::before { - transform-origin: right; + &::before { + background-color: var(--v2-background-bg-accent); + transition: opacity var(--question-feedback-duration) ease; + } + + &::after { + background-color: var(--v2-icon-icon-muted); } } @@ -216,74 +165,67 @@ min-inline-size: 0; } - /* Reaches into the body's side padding like the question text's frame, for the same gutter. */ [data-slot="question-options"] { - --question-gutter: 8px; + display: flex; + flex-direction: column; + gap: 6px; flex: 1 1 auto; min-block-size: 0; min-inline-size: 0; - margin: 0 calc(-1 * var(--question-gutter)); + margin: 0; padding: 0; overflow-y: auto; scrollbar-width: none; - mask-composite: intersect; &::-webkit-scrollbar { display: none; } } - /* Holds the answers and the outgoing copy of them while questions switch. It clips them at its sides, so answers - sliding past never make the box scroll sideways. */ - [data-slot="question-options-track"] { - position: relative; - padding-inline: var(--question-gutter); - overflow-x: clip; - } - - [data-slot="question-options-list"] { - display: flex; - flex-direction: column; - gap: 2px; + [data-slot="question-option"] { position: relative; isolation: isolate; - transform-origin: 50% 0; - } - - /* One highlight for the whole list, painted under the answers. It jumps to the hovered or keyboard-highlighted answer - by its clip, and shows only while the pointer hovers or the keys drive; the pick itself shows only on the key. */ - [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; - - &[data-shown="false"] { - visibility: hidden; - } - } - - [data-slot="question-option"] { display: flex; align-items: flex-start; gap: 8px; flex-shrink: 0; box-sizing: border-box; inline-size: 100%; - position: relative; padding: 10px; border: 0; border-radius: 6px; - outline: none; - background: transparent; + background-color: var(--v2-background-bg-layer-01); + box-shadow: inset 0 0 0 0.5px var(--v2-border-border-base); color: var(--v2-text-text-base); text-align: start; cursor: pointer; touch-action: manipulation; + transition: background-color var(--question-feedback-duration) ease; + + &::before { + content: ""; + position: absolute; + inset: 0; + z-index: -1; + border-radius: inherit; + background-color: var(--v2-question-answer-bg-selected); + opacity: 0; + pointer-events: none; + transition: opacity var(--question-feedback-duration) ease; + } + + &[data-picked="true"] { + box-shadow: none; + + &::before { + opacity: 1; + } + } + + &:focus-visible { + outline: 1px solid var(--v2-border-border-focus); + outline-offset: -1px; + } &:disabled, &[data-disabled="true"] { @@ -296,70 +238,87 @@ display: inline-flex; align-items: center; justify-content: center; - inline-size: 18px; + inline-size: 16px; block-size: 20px; - flex: 0 0 18px; + flex: 0 0 16px; } - /* An answer's key is its mark. One answer: a round key with a soft fill. Many: a hollow square key, like a checkbox. - Picking fills either solid, with the number in the inverse colour. */ - [data-slot="question-option-key"] { + [data-slot="question-option-box"] { display: inline-flex; align-items: center; justify-content: center; box-sizing: border-box; - inline-size: 18px; - block-size: 18px; - position: relative; - isolation: isolate; - border-radius: 50%; - background-color: var(--v2-background-bg-layer-03); - box-shadow: inset 0 0 0 0.5px var(--v2-border-border-base); - color: var(--v2-text-text-muted); - font-size: 11px; - font-weight: 530; - line-height: 1; - font-variant-numeric: tabular-nums; + inline-size: 16px; + block-size: 16px; + flex: 0 0 16px; + padding: 0; + border: 0; + 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-color: var(--v2-background-bg-accent); + [data-slot="icon-svg"] { + inline-size: 16px; + block-size: 16px; + flex: 0 0 16px; opacity: 0; + color: var(--v2-icon-icon-contrast); + transition: opacity var(--question-feedback-duration) ease; } - &[data-type="checkbox"] { - border-radius: 4px; - background-color: transparent; - box-shadow: inset 0 0 0 1px var(--v2-border-border-strong); + &[data-type="radio"] { + border-radius: 50%; + } + + [data-slot="question-option-radio-dot"] { + inline-size: 6px; + block-size: 6px; + flex: 0 0 6px; + border-radius: 50%; + background-color: var(--v2-grey-300); + box-shadow: var(--v2-elevation-elements); + opacity: 0; + transition: opacity var(--question-feedback-duration) ease; } &[data-picked="true"] { - color: var(--v2-text-text-contrast); - box-shadow: inset 0 0 0 1px transparent; + 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="question-option-main"] { display: flex; flex-direction: column; - gap: 4px; + gap: 6px; min-inline-size: 0; flex: 1; } + [data-slot="question-option-shortcut"] { + --keybind-font-size: 10px; + --keybind-font-weight: var(--font-weight-regular); + --keybind-transition-duration: var(--question-feedback-duration); + align-self: center; + block-size: 20px; + pointer-events: none; + } + [data-slot="option-label"] { font-family: var(--v2-font-family-sans); font-size: 13px; - font-weight: 530; + font-weight: 440; line-height: var(--line-height-base); + letter-spacing: -0.04px; color: var(--v2-text-text-base); overflow-wrap: anywhere; } @@ -367,9 +326,10 @@ [data-slot="option-description"] { min-inline-size: 0; font-family: var(--v2-font-family-sans); - font-size: 13px; + font-size: 11px; font-weight: 440; - line-height: var(--line-height-base); + line-height: var(--line-height-tight); + letter-spacing: 0.05px; color: var(--v2-text-text-muted); overflow-wrap: anywhere; white-space: normal; @@ -383,10 +343,6 @@ padding-block: 0; padding-inline: 10px; - &:not([data-editing="true"]) [data-slot="text-input-v2-input"] { - font-weight: 530; - } - &[data-editing="true"] .question-custom-field[data-component="text-input-v2"] { background: linear-gradient(180deg, var(--v2-alpha-light-2), var(--v2-alpha-light-0)), var(--v2-background-bg-base); @@ -406,9 +362,9 @@ display: inline-flex; align-items: center; justify-content: center; - inline-size: 18px; + inline-size: 16px; block-size: 20px; - flex: 0 0 18px; + flex: 0 0 16px; margin: 0; padding: 0; border: 0; @@ -418,7 +374,8 @@ touch-action: manipulation; &:focus-visible { - outline: none; + outline: 2px solid var(--v2-border-border-focus); + outline-offset: 2px; } &:disabled { @@ -478,13 +435,22 @@ } [data-slot="question-footer"] { + position: relative; + z-index: 0; display: flex; box-sizing: border-box; align-items: center; justify-content: space-between; flex-shrink: 0; - padding-block: 7px 8px; - padding-inline: 12px; + padding-block: 16px 8px; + padding-inline: 8px; + margin-block-start: -9px; + border: 0.5px solid var(--v2-border-border-base); + border-start-start-radius: 0; + border-start-end-radius: 0; + border-end-start-radius: 10px; + border-end-end-radius: 10px; + background-color: var(--v2-background-bg-layer-01); > [data-component="button-v2"][data-variant="ghost"] { color: var(--v2-text-text-muted); @@ -497,72 +463,48 @@ gap: 8px; } - /* While a switch runs, the dock draws the footer buttons frame by frame; at rest these rules place them. */ - [data-slot="question-footer-back"][data-shown="false"] { - visibility: hidden; - opacity: 0; - } - - [data-slot="question-advance"] { - position: relative; - display: flex; - } - - [data-slot="question-advance-face"] { - display: flex; - } - - [data-slot="question-advance-face"][data-active="false"] { - position: absolute; - inset-block-start: 0; - inset-inline-end: 0; - visibility: hidden; - opacity: 0; - } - - [data-slot="question-advance-face"][data-active="true"] { - z-index: 1; + /* Keep both labels in layout so the button doesn't change width. */ + [data-slot="question-advance-labels"] { + display: inline-grid; + place-items: center; } [data-slot="question-advance-label"] { - display: inline-flex; - align-items: center; - gap: 6px; - } + grid-area: 1 / 1; + white-space: nowrap; + opacity: 0; + transition: opacity var(--question-feedback-duration) ease-out; - [data-slot="question-submit-shortcut"] { - flex-shrink: 0; - opacity: 0.6; + &[data-active="true"] { + opacity: 1; + } } @media (hover: hover) and (pointer: fine) { [data-slot="question-progress-segment"]:hover:not(:disabled) { background-color: var(--v2-overlay-simple-overlay-hover); } - } - /* Without the dock's motion there is no sliding bar, so the current question's dash lights itself. */ - [data-component="session-question-dock"][data-animated="false"] & { - [data-slot="question-progress-segment"][data-active="true"] [data-slot="question-progress-bar"]::before { - background-color: var(--v2-icon-icon-base); - transform: scaleX(1); + [data-slot="question-option"]:hover:not(:disabled):not([data-disabled="true"]):not([data-picked="true"]) { + background-color: var(--v2-background-bg-layer-02); } } - /* Picks and answered dashes ease only while the dock's motion is on; otherwise they change on the same frame. */ - [data-component="session-question-dock"][data-animated="true"] & { - [data-slot="question-progress-bar"]::before { - transition: transform var(--question-settle) var(--question-spring); + [data-component="session-question-dock"][data-keyboard="true"] &, + :root[data-motion="reduce"] & { + --question-feedback-duration: 0s; + } + + @media (prefers-reduced-motion: reduce) { + :root:not([data-motion="full"]) & { + --question-feedback-duration: 0s; } + } - [data-slot="question-option-key"] { - transition: - color var(--question-pick) var(--question-spring), - box-shadow var(--question-pick) var(--question-spring); - - &::before { - transition: opacity var(--question-pick) var(--question-spring); - } + :root[data-motion="reduce"] & { + [data-slot="question-option"], + .question-custom-field[data-component="text-input-v2"] { + transition: none; } } } diff --git a/packages/session-ui/src/styles/index.css b/packages/session-ui/src/styles/index.css index 63649537553..3967df515f2 100644 --- a/packages/session-ui/src/styles/index.css +++ b/packages/session-ui/src/styles/index.css @@ -6,6 +6,7 @@ @import "../components/message-part.css" layer(components); @import "../components/message-nav.css" layer(components); @import "../components/question-prompt.css" layer(components); +@import "../components/question-prompt-experimental.css" layer(components); @import "../components/quote-highlight.css" layer(components); @import "../components/session-review.css" layer(components); @import "../components/session-compaction.css" layer(components); diff --git a/packages/ui/src/data-display/keybind/keybind.css b/packages/ui/src/data-display/keybind/keybind.css index 2b4c09a2e04..89e60617299 100644 --- a/packages/ui/src/data-display/keybind/keybind.css +++ b/packages/ui/src/data-display/keybind/keybind.css @@ -34,6 +34,9 @@ border-radius: 2px; flex: none; flex-grow: 0; + transition: + background-color var(--keybind-transition-duration, 0s) ease, + box-shadow var(--keybind-transition-duration, 0s) ease; } [data-component="keybind-v2"][data-variant="neutral"] [data-slot="keybind-v2-key"] { @@ -44,6 +47,11 @@ background: transparent; } +[data-component="keybind-v2"][data-variant="outline"] [data-slot="keybind-v2-key"] { + background: transparent; + box-shadow: inset 0 0 0 1px var(--v2-border-border-strong); +} + [data-component="keybind-v2"] [data-slot="keybind-v2-label"] { display: flex; flex-direction: row; @@ -53,8 +61,8 @@ padding: 0; flex: none; font-style: normal; - font-weight: 530; - font-size: 11px; + font-weight: var(--keybind-font-weight, 530); + font-size: var(--keybind-font-size, 11px); line-height: 1; text-align: center; letter-spacing: 0.05px; @@ -67,7 +75,7 @@ user-select: none; } -[data-component="keybind-v2"][data-variant="neutral"] [data-slot="keybind-v2-label"] { +[data-component="keybind-v2"]:is([data-variant="neutral"], [data-variant="outline"]) [data-slot="keybind-v2-label"] { color: var(--v2-text-text-muted); } diff --git a/packages/ui/src/data-display/keybind/keybind.stories.tsx b/packages/ui/src/data-display/keybind/keybind.stories.tsx index 1d1b1f0e402..e609ddc3bae 100644 --- a/packages/ui/src/data-display/keybind/keybind.stories.tsx +++ b/packages/ui/src/data-display/keybind/keybind.stories.tsx @@ -5,12 +5,13 @@ Inline keybind indicator that renders one or more keyboard keys in a compact row ### API - \`keys\`: Array of key labels to display (e.g. \`["⌘", "K"]\`). -- \`variant\`: "neutral" (gray background) | "ghost" (no background). +- \`variant\`: "neutral" (gray background) | "ghost" (no background) | "outline" (border, no background). - Inherits native div attributes. ### Variants - **Neutral** — each key sits on a \`#D4D4D4\` pill with darker text. - **Ghost** — keys render without a background, lighter text color. +- **Outline** — each key has an inset border and no background, with the same dimensions as Neutral. ` export default { @@ -37,7 +38,7 @@ export default { }, variant: { control: "select", - options: ["neutral", "ghost"], + options: ["neutral", "ghost", "outline"], }, }, } @@ -49,6 +50,7 @@ export const Variants = {
+
), } @@ -58,6 +60,7 @@ export const MultipleKeys = {
+
@@ -81,6 +84,13 @@ export const AllExamples = {
+
+ Outline + + + + +
), } diff --git a/packages/ui/src/data-display/keybind/keybind.tsx b/packages/ui/src/data-display/keybind/keybind.tsx index c940f7cb892..37a35efb264 100644 --- a/packages/ui/src/data-display/keybind/keybind.tsx +++ b/packages/ui/src/data-display/keybind/keybind.tsx @@ -3,7 +3,7 @@ import "./keybind.css" export interface KeybindProps extends ComponentProps<"div"> { keys: string[] - variant?: "neutral" | "ghost" + variant?: "neutral" | "ghost" | "outline" } export function Keybind(props: KeybindProps) { diff --git a/packages/ui/src/i18n/en.ts b/packages/ui/src/i18n/en.ts index ecba251ae46..bdedfd69038 100644 --- a/packages/ui/src/i18n/en.ts +++ b/packages/ui/src/i18n/en.ts @@ -334,6 +334,8 @@ const source = { "ui.question.answer.none": "(no answer)", "ui.question.review.notAnswered": "(not answered)", "ui.question.multiHint": "Pick any", + "ui.question.singleHint": "Select one answer", + "ui.question.classic.multiHint": "Select all answers that apply", "ui.question.custom.placeholder": "Type your answer…", "ui.question.custom.answerPlaceholder": "Type your own answer…", } satisfies Record