fix(app): remove the focus rings around the timeline and composer (#65690)

This commit is contained in:
Luke Parker 2026-11-22 21:46:36 -06:00 • committed by GitHub
parent d84e1d7bb3
commit 18be128acc
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
20 changed files with 71 additions and 294 deletions

View file

@ -9,7 +9,7 @@ Use one default ring when someone navigates focus to a control, not when they cl
## The ring
- Use `:focus-visible` for the ring. Don’t use `:focus` to decide whether to show it. The only exception is a custom field that combines `:focus` with its own ring state, as the composer and Home search do (see Text fields). `base.css` supplies `outline: 2px solid var(--v2-border-border-focus); outline-offset: 2px` and a 4px radius for links.
- Use `:focus-visible` for the ring. Don’t use `:focus` to decide whether to show it. `base.css` supplies `outline: 2px solid var(--v2-border-border-focus); outline-offset: 2px` and a 4px radius for links.
- Offset: `2px` outward by default. `-2px` inset for full-width rows and for controls flush against an edge that clips or scrolls (segmented items, split buttons, titlebar buttons, clear buttons). No other offsets.
- Follow the control’s radius; give a square text action or link 4px where appropriate. Use a wrapper with `:has(> trigger:focus-visible)` when the wrapper owns the visible shape or the trigger’s ring would clip, as with tabs and Settings project cards.
- Outline only. Don't draw focus with `box-shadow`: Windows High Contrast removes shadows, so the ring disappears, and shadow rings looked different from every other ring.
@ -18,15 +18,13 @@ Use one default ring when someone navigates focus to a control, not when they cl
- Inline rename inputs rely on the caret and editing state. The timeline's Jump to latest stays in the Tab order with the shared ring, since it's the only quick way back down from the keyboard; its container is `inert` while it's hidden. Loading alone doesn’t add a ring. If a busy button keeps keyboard focus, keep the ring and show the busy state separately with `aria-busy`, a disabled state, or loading text; the ring alone doesn’t say whether the button can be activated.
- These ring rules do not replace normal field borders or validation feedback. Those can respond to click focus and have their own inset treatment.
## Text fields
## Text fields and scroll areas
Editable fields can match `:focus-visible` after a click, so fields with a custom frame ring (the composer and Home search) decide when focus arrives. Use `packages/ui/src/context/field-focus.tsx`, not a global input tracker.
Chromium matches `:focus-visible` on every focused text field, and on anything that has focus once a key is pressed. A ring on a large surface then shows after a click, when the app moves focus there, and on returning to the window.
- Ring by default. Suppress the ring for direct pointer focus and for the composer’s explicit initial autofocus when a session or draft opens, including when it was opened with the keyboard.
- Tab, shortcuts like Find, and assistive technology moving DOM focus show the ring. Moving a screen reader’s reading cursor alone does not move DOM focus.
- When a dialog returns focus to a custom field, `packages/ui/src/context/dialog.tsx` restores the field's own ring state; ordinary controls use the browser's `:focus-visible` state. The overlay rules below apply.
- A `pointerdown` inside a field that already shows the ring clears it immediately; no new focus event fires. Typing never changes the decision, and blur clears it.
- A click shows the field's normal focused border or background and the caret, with no ring.
- A text field never draws the ring, the composer and Home search included. Focus shows as the caret and the field's focused border or background. Don't add ring state or pointer tracking to a field.
- A scroll area (the timeline, Home's list) takes focus so the keyboard can scroll it, and draws no ring. Show focus on the items inside it instead.
- Moving a screen reader’s reading cursor alone does not move DOM focus.
## Rows
@ -63,7 +61,7 @@ Editable fields can match `:focus-visible` after a click, so fields with a custo
- Follow logical reading and interaction order, including in RTL. Fix DOM order rather than using positive `tabindex`. Use native buttons for actions and links for navigation; use established widget primitives or keyboard patterns for tabs, trees, sliders, and resize handles.
- Move focus in response to a user action or to recover focus when its target disappears. Background updates, streamed output, toasts, and incoming prompts must not steal focus.
- If a focused item is closed or deleted, move focus to the next place the user can continue the same task: the next or previous item in the same list, or a stable fallback such as the list heading or the control that opened it. Use the visually nearest control only when it serves that task. Don’t leave focus on `<body>`.
- Chromium drops focus to `<body>` without an event when the focused element is removed, disabled, or stops being editable. `packages/ui/src/context/focus-rescue.tsx` (installed in `AppBaseProviders`) recovers it inside a `data-focus-scope`: the next item, or the previous after the last, widening to the enclosing scope when the inner one is empty, and back to what had focus before when nothing is left. Mark a new list, strip, chip row or panel with `data-focus-scope` rather than adding per-feature focus code. Rescue never moves focus into a `role="tablist"`, because Kobalte tabs select themselves on focus, so don't mark a tab list as a scope. Items in an overlay leave the return to the overlay; rescue steps in only when the overlay's opener is gone too. Move focus explicitly when the task has a better target than the neighbour, such as the composer after the last chip.
- Chromium drops focus to `<body>` without an event when the focused element is removed, disabled, or stops being editable. `packages/ui/src/context/focus-rescue.tsx` (installed in `AppBaseProviders`) recovers it inside a `data-focus-scope`: the next item, or the previous after the last, widening to the enclosing scope when the inner one is empty, and back to what had focus before when nothing is left. The control it moves focus to shows its ring only when Tab or an arrow key last moved focus; typing, shortcuts and a key pressed on a clicked control don't count. Mark a new list, strip, chip row or panel with `data-focus-scope` rather than adding per-feature focus code. Rescue never moves focus into a `role="tablist"`, because Kobalte tabs select themselves on focus, so don't mark a tab list as a scope. Items in an overlay leave the return to the overlay; rescue steps in only when the overlay's opener is gone too. Move focus explicitly when the task has a better target than the neighbour, such as the composer after the last chip.
## Verify

View file

@ -20,7 +20,9 @@ story.describe("scopes", () => {
story("moves focus to the next item, or to the previous one after the last", async ({ page }) => {
const list = page.getByTestId("list")
await list.getByRole("button", { name: "Two" }).focus()
// Tab moves focus to the item, so the item that takes over shows its ring.
await list.getByRole("button", { name: "One" }).press("Tab")
await expect(list.getByRole("button", { name: "Two" })).toBeFocused()
await page.keyboard.press("Enter")
await expect(list.getByRole("button", { name: "Three" })).toBeFocused()
expect(await ringed(list.getByRole("button", { name: "Three" }))).toBe(true)
@ -29,6 +31,17 @@ story.describe("scopes", () => {
await expect(list.getByRole("button", { name: "One" })).toBeFocused()
})
story("leaves the item that takes over without a ring when no key moved focus there", async ({ page }) => {
const list = page.getByTestId("list")
// Typing and Enter are not navigation, and the item got focus from code.
await page.keyboard.press("a")
await list.getByRole("button", { name: "Two" }).focus()
await page.keyboard.press("Enter")
await expect(list.getByRole("button", { name: "Three" })).toBeFocused()
expect(await ringed(list.getByRole("button", { name: "Three" }))).toBe(false)
})
story("returns focus to what had it before when a scope is left empty", async ({ page }) => {
await page.getByTestId("opener").focus()
await page.getByTestId("toasts").getByRole("button", { name: "Toast" }).focus()
@ -65,7 +78,6 @@ for (const action of ["Steer", "Remove"]) {
const editor = root.locator('[data-component="session-composer-dock"] [contenteditable="true"]')
await expect(editor).toBeFocused()
await expect(editor).not.toHaveAttribute("data-keyboard-focus")
},
)
}

View file

@ -5,7 +5,7 @@ import { mockPluginsActivating, type MockServerConfig } from "../utils/mock-serv
test.use({ permissions: ["clipboard-read", "clipboard-write"] })
test("the composer preserves its ring on dialog return and leaves autofocus and clicks quiet", async ({ page }) => {
test("the composer shows its caret, never a focus ring, however focus arrives", async ({ page }) => {
const view = await openSession(page, { name: "ComposerKeyboardFocus" })
const frame = page.locator('[data-component="composer"]').filter({ has: view.editor })
@ -17,7 +17,8 @@ test("the composer preserves its ring on dialog return and leaves autofocus and
await expect(view.editor).not.toBeFocused()
await page.keyboard.press("Tab")
await expect(view.editor).toBeFocused()
await expect(frame).toHaveCSS("outline-style", "solid")
await expect(frame).toHaveCSS("outline-style", "none")
await expect(view.editor).toHaveCSS("outline-style", "none")
const modifier = await page.evaluate(() => (/Mac/i.test(navigator.platform) ? "Meta" : "Control"))
@ -27,7 +28,7 @@ test("the composer preserves its ring on dialog return and leaves autofocus and
await expect(dialog.getByRole("combobox")).toBeFocused()
await page.keyboard.press("Escape")
await expect(view.editor).toBeFocused()
await expect(frame).toHaveCSS("outline-style", "solid")
await expect(frame).toHaveCSS("outline-style", "none")
await view.editor.click()
await expect(view.editor).toBeFocused()

View file

@ -73,11 +73,9 @@ test("Home projects, utility rows, search and recent sessions show keyboard focu
const field = page.locator('[data-slot="home-session-search-field"]')
// A text field shows its caret and background, not a ring.
await page.keyboard.press("Tab")
await expect(search).toBeFocused()
await expect(field).toHaveCSS("outline-style", "solid")
await search.click()
await expect(search).toBeFocused()
await expect(field).toHaveCSS("outline-style", "none")
const recent = page.getByRole("region", { name: "Recent sessions" })
@ -95,8 +93,9 @@ test("Home projects, utility rows, search and recent sessions show keyboard focu
await expect(viewport).toHaveAttribute("tabindex", "0")
await viewport.press("Shift+Tab")
await page.keyboard.press("Tab")
// The list takes focus so the keyboard can scroll it, without a ring around the whole area.
await expect(viewport).toBeFocused()
await expect(viewport).toHaveCSS("outline-offset", "-2px")
await expect(viewport).toHaveCSS("outline-style", "none")
})
test("Home keeps the session list in every interface mode", async ({ page }) => {
@ -333,7 +332,6 @@ test("tabbing out of session search closes its results, and tabbing back reopens
await page.keyboard.press(`${modifier}+f`)
await expect(search).toBeFocused()
await expect(page.locator('[data-slot="home-session-search-field"]')).toHaveCSS("outline-style", "solid")
await expect(panel.getByRole("option")).toContainText(earlier.title)
})

View file

@ -36,7 +36,6 @@ import { Tabs } from "@opencode/ui/tabs"
import { TextInput } from "@opencode/ui/text-input"
import { createEffect, createSignal, createUniqueId, For, onCleanup, onMount, Show, type JSX } from "solid-js"
import { createTabStripScroll } from "@/runtime/plugin/tab-strip-scroll"
import { createFieldFocus } from "@opencode/ui/context/field-focus"
import { createOverlayFocus } from "@opencode/ui/context/overlay-focus"
import { installFocusRescue } from "@opencode/ui/context/focus-rescue"
import { useDialog } from "@opencode/ui/context/dialog"
@ -248,16 +247,6 @@ const surfaces: Surface[] = [
</div>
),
},
{
name: "Composer editor: caret is the only focus cue",
failure: "Invisible",
target: '[data-component="composer-editor"]',
keys: "Focus the preceding button, then press Tab into the prompt. Click inside the prompt to see the ring go away.",
sizing: "The editor sits inside a masked scroll viewport.",
source: "app/src/composer/editor/editor.css, ui/src/context/field-focus.tsx, context/dialog.tsx",
fix: "Draw an inset ring on focus entry except for click-to-type and session autofocus. Returning from a dialog restores the previous ring state.",
render: (forced) => <ComposerFocusExample forced={forced()} />,
},
],
also: [],
},
@ -692,16 +681,6 @@ const surfaces: Surface[] = [
</div>
),
},
{
name: "Search sessions: Tab shows only a caret",
failure: "Invisible",
target: "input",
keys: "Focus the preceding button and Tab into Search sessions. Click the field to clear the ring.",
sizing: "The field spans the Home results column. The ring belongs on the field, not just its editable text.",
source: "app/src/home/sessions/view.tsx, view.css, ui/src/context/field-focus.tsx",
fix: "Tab, Find and other non-pointer focus entry draw the shared outset ring around the field. Click-to-type keeps the field background and caret without the ring.",
render: (forced) => <HomeSearchFocusExample forced={forced()} />,
},
{
name: "Project row: focus looks like selection",
failure: "Inconsistent",
@ -1658,7 +1637,7 @@ const surfaces: Surface[] = [
],
also: [
"Reviewed, left as is: the Home browse dialog's fallback focus (home/projects/browse.tsx) runs only when the opener has gone; the mobile panel drawer's Back and the location picker's Choose return follow the key or click that closed them.",
"The workspace selector (new-session/workspace/selector.tsx) returns focus to the composer, whose field ring follows field-focus.tsx.",
"The workspace selector (new-session/workspace/selector.tsx) returns focus to the composer.",
],
},
{
@ -2224,21 +2203,6 @@ function CaseCard(props: { case: Case; number: number; forced: boolean; locator:
)
}
function createPreviewFieldFocus(forced: () => boolean) {
const focus = createFieldFocus()
const [entered, setEntered] = createSignal(false)
return {
visible: () => focus.visible() || (forced() && !entered()) || undefined,
enter: (element: HTMLElement) => {
setEntered(true)
focus.enter(element)
},
pointer: focus.pointer,
leave: focus.leave,
}
}
function SearchHighlightExample(props: { kind: "home-session-search-row" | "palette-menu-row" | "search-list-row" }) {
const [active, setActive] = createSignal(0)
@ -2339,61 +2303,6 @@ function TreeFocusExample() {
)
}
function HomeSearchFocusExample(props: { forced: boolean }) {
const focus = createPreviewFieldFocus(() => props.forced)
return (
<div class="grid w-[360px] gap-2">
<Button class="justify-self-start">Previous control</Button>
<label
data-slot="home-session-search-field"
onPointerDown={focus.pointer}
class="flex h-9 items-center gap-2 rounded-[6px] bg-v2-background-bg-layer-02/60 ps-3 pe-2 text-v2-icon-icon-muted focus-within:bg-v2-background-bg-layer-02"
>
<Icon name="magnifying-glass" />
<input
data-keyboard-focus={focus.visible()}
aria-label="Search sessions"
placeholder="Search sessions"
class="min-w-0 flex-1 border-0 bg-transparent text-v2-text-text-base outline-0"
onFocus={(event) => focus.enter(event.currentTarget)}
onBlur={focus.leave}
/>
</label>
</div>
)
}
function ComposerFocusExample(props: { forced: boolean }) {
const focus = createPreviewFieldFocus(() => props.forced)
return (
<div class="grid w-[360px] gap-2">
<Button class="justify-self-start">Previous control</Button>
<form data-component="composer" class="overflow-clip rounded-xl shadow-[var(--v2-elevation-raised)]">
<div data-component="composer-scroll">
<div
data-component="composer-editor"
data-keyboard-focus={focus.visible()}
role="textbox"
aria-label="Prompt"
contenteditable
class="px-4 pt-4 pb-2 text-13-regular focus:outline-none"
onPointerDown={focus.pointer}
onFocus={(event) => focus.enter(event.currentTarget)}
onBlur={focus.leave}
>
Ask anything
</div>
</div>
<div class="p-2">
<IconButton type="button" variant="ghost-muted" icon={<Icon name="plus" />} aria-label="Attach" />
</div>
</form>
</div>
)
}
// The Models page, with its header measured the way Settings measures it.
function ModelsPanel() {
let panel: HTMLDivElement | undefined

View file

@ -2,12 +2,6 @@
content: "\200B";
}
/* Outline the frame, not the editor inside the masked scroll viewport. */
[data-component="composer"]:has([data-component="composer-editor"][data-keyboard-focus]:focus) {
outline: 2px solid var(--v2-border-border-focus);
outline-offset: -2px;
}
/* Transcript session references match this (packages/session-ui/src/components/markdown.css). */
[data-component="composer-editor"] [data-mention="session"] {
color: var(--v2-text-text-muted);

View file

@ -50,7 +50,6 @@ import type {
import type { ComposerEditorModel, ComposerSelectControl } from "./interaction"
import { isAttachment, promptLength } from "../prompt-parts"
import { editorMatchesPrompt, getCursorPosition, isEditorDomBlank, isPromptInlineBlank } from "./dom"
import { createFieldFocus } from "@opencode/ui/context/field-focus"
import {
INITIAL_EDITOR_SYNC_STATE,
INPUT_PARSED,
@ -103,8 +102,6 @@ export type ComposerEditorProps = {
}
export function ComposerEditor(props: ComposerEditorProps) {
const keyboardFocus = createFieldFocus()
const i18n = useI18n()
const markdown = useMarkdown()
const state = props.controller.state
@ -176,6 +173,11 @@ export function ComposerEditor(props: ComposerEditorProps) {
})
let sync = INITIAL_EDITOR_SYNC_STATE
let firstFocus = true
// A press puts the caret where it lands, and focus follows in the same task.
let pressed = false
let pressTimer: ReturnType<typeof setTimeout> | undefined
onCleanup(() => clearTimeout(pressTimer))
const updateCursor = () => {
const cursor = editor && getCursorPosition(editor)
@ -429,18 +431,15 @@ export function ComposerEditor(props: ComposerEditorProps) {
if (caret.top < bounds.top + 16) viewport.scrollTop += caret.top - bounds.top - 16
})
}}
data-field-focus
data-keyboard-focus={keyboardFocus.visible() || undefined}
onPointerDown={keyboardFocus.pointer}
onClick={(event) => {
if (event.detail > 0) keyboardFocus.pointer()
onPointerDown={() => {
pressed = true
clearTimeout(pressTimer)
pressTimer = setTimeout(() => (pressed = false))
}}
onBlur={keyboardFocus.leave}
onFocus={(event) => {
keyboardFocus.enter(event.currentTarget)
// A request dock can replace the editor. Keyboard focus on the new editor must keep the draft's caret.
if (firstFocus && keyboardFocus.visible()) props.controller.restoreCaret()
onFocus={() => {
// A request dock can replace the editor. Focus on the new editor that no press caused must keep the
// draft's caret.
if (firstFocus && !pressed) props.controller.restoreCaret()
firstFocus = false
props.controller.dispatch({ type: "focus.editor" })
}}

View file

@ -2,7 +2,6 @@ import { Predicate } from "effect"
import { createEffect, createMemo, createSignal, on, onCleanup, untrack, type Accessor } from "solid-js"
import { unwrap } from "solid-js/store"
import { useFilteredList } from "@opencode/ui/hooks"
import { focusField, handOffFocus, handoffRing } from "@opencode/ui/context/field-focus"
import { abort } from "@opencode/util/abort"
import { createComposerAttachments, type ComposerAttachmentConfig } from "../attachments/attachments"
import type { Upload } from "../attachments/uploads"
@ -122,7 +121,7 @@ export function createComposerEditor(input: {
let editor: HTMLElement | undefined
let fileInput: HTMLInputElement | undefined
let focusFrame: number | undefined
let focusRequest: { cursor: number; visible: boolean | undefined } | undefined
let focusRequest: { cursor: number } | undefined
const cancelFocus = () => {
if (focusFrame === undefined) return
@ -139,8 +138,7 @@ export function createComposerEditor(input: {
if (!editor) return
if (request.visible === undefined) editor.focus()
else focusField(editor, request.visible)
editor.focus()
setCursorPosition(editor, request.cursor)
}
@ -210,9 +208,7 @@ export function createComposerEditor(input: {
},
}),
editor: () => editor,
focusEditor: () => {
if (editor) handOffFocus(editor)
},
focusEditor: () => editor?.focus(),
addPart,
setDraggingType: (type) => dispatch({ type: type ? "drag.enter" : "drag.leave" }),
})
@ -569,9 +565,9 @@ export function createComposerEditor(input: {
if (contextList.grouped.state === "ready" && contextList.flat().length === 0) dispatch({ type: "popover.close" })
})
const restoreFocus = (cursor = draft.state.cursor ?? promptLength(draft.state.prompt), visible?: boolean) => {
const restoreFocus = (cursor = draft.state.cursor ?? promptLength(draft.state.prompt)) => {
cancelFocus()
focusRequest = { cursor, visible: visible ?? handoffRing(editor) }
focusRequest = { cursor }
focusFrame = requestAnimationFrame(flushFocus)
}

View file

@ -75,10 +75,6 @@
transition: none;
}
}
[data-slot="home-session-search-field"]:has(> input[data-keyboard-focus]:focus) {
outline: 2px solid var(--v2-border-border-focus);
outline-offset: 2px;
}
@media (forced-colors: active) {
[data-component="home-session-search-row"][aria-selected="true"] {

View file

@ -25,7 +25,6 @@ import { Menu } from "@opencode/ui/menu"
import { MenuScroll } from "@opencode/ui/menu-scroll"
import { Tooltip } from "@opencode/ui/tooltip"
import { useLanguage } from "@/runtime/i18n/language"
import { createFieldFocus } from "@opencode/ui/context/field-focus"
import { ServerConnection } from "@/runtime/server/registry"
import { SessionTabAvatarView } from "@/shell/layout/session-tab-avatar"
import { showToast } from "@/shell/notifications/toast"
@ -436,8 +435,6 @@ function HomeSessionSearch(
) {
const scope = children(() => props.searchScope)
const keyboardFocus = createFieldFocus()
return (
<div class="w-full">
<div
@ -515,10 +512,6 @@ function HomeSessionSearch(
</Show>
<label
data-slot="home-session-search-field"
onPointerDown={keyboardFocus.pointer}
onClick={(event) => {
if (event.detail > 0) keyboardFocus.pointer()
}}
class={`
relative z-20 flex h-9 w-full items-center gap-2 rounded-[6px] py-1 ps-3 pe-2
bg-v2-background-bg-layer-02/60 text-v2-icon-icon-muted transition-[background-color,box-shadow]
@ -541,13 +534,7 @@ function HomeSessionSearch(
aria-activedescendant={
props.searchActive && props.searchOpen ? `home-session-search-option-${props.searchActive}` : undefined
}
data-field-focus
data-keyboard-focus={keyboardFocus.visible() || undefined}
onBlur={keyboardFocus.leave}
onFocus={(event) => {
keyboardFocus.enter(event.currentTarget)
props.onSearchFocus()
}}
onFocus={() => props.onSearchFocus()}
onInput={(event) => props.onSearchInput(event.currentTarget.value)}
onKeyDown={(event) => {
if (event.key === "Escape") {

View file

@ -106,23 +106,6 @@
);
}
/* The fade mask also erases the viewport's own ring, and the header and composer cover its top and bottom edges.
Draw it on the visible area instead, above the header, rounded like the session frame that clips its corners. */
[data-slot="session-timeline-scroll"] > .scroll-view__viewport:focus-visible {
outline: none;
}
[data-slot="session-timeline-scroll"]:has(> .scroll-view__viewport:focus-visible)
~ [data-slot="session-timeline-visible"]::after {
content: "";
position: absolute;
inset: 0;
z-index: 40;
border-radius: 10px;
outline: 2px solid var(--v2-border-border-focus);
outline-offset: -2px;
}
[data-slot="session-timeline-scroll"] > .scroll-view__viewport:has(> [data-slot="session-header-inset"]) {
scroll-padding-block-start: calc(var(--sticky-accordion-top, 0px) + 16px);
}

View file

@ -5,7 +5,7 @@ import { useLanguage } from "@/runtime/i18n/language"
import { projectSearchCommand } from "@/shell/titlebar/titlebar"
export function useNewSessionCommands(input: {
restoreFocus: (cursor?: number, visible?: boolean) => void
restoreFocus: (cursor?: number) => void
project: {
empty: () => boolean
open: () => void
@ -37,8 +37,7 @@ export function useNewSessionCommands(input: {
title: language.t("command.input.focus"),
category: language.t("command.category.view"),
keybind: "ctrl+l",
// A shortcut moved focus, so the ring shows.
onSelect: () => input.restoreFocus(undefined, true),
onSelect: () => input.restoreFocus(),
},
{
id: "session.location.cycle",

View file

@ -76,7 +76,7 @@ export default function NewSessionPage(props: { draftId: string }) {
// Search projects opened this draft; the picker returns focus to the composer when it closes.
if (layout.draft.projectSearch.take(props.draftId)) location()
else model.restoreFocus(undefined, false)
else model.restoreFocus()
}),
)
createEffect(() => {

View file

@ -1,6 +1,5 @@
import { createEffect, createMemo, createSignal, on, onMount, untrack, type Accessor } from "solid-js"
import { useDialog } from "@opencode/ui/context/dialog"
import { focusField, handoffRing } from "@opencode/ui/context/field-focus"
import type { ComposerControls } from "@/composer/adapter"
import { setCursorPosition } from "@/composer/editor/dom"
import { promptLength } from "@/composer/prompt-parts"
@ -48,10 +47,8 @@ export function createSessionComposerController(input: {
const target = editor()
if (!target) return
const visible = handoffRing(target)
requestAnimationFrame(() => {
if (visible === undefined) target.focus()
else focusField(target, visible)
target.focus()
setCursorPosition(target, cursor)
})
},

View file

@ -9,7 +9,6 @@ import {
type ParentProps,
} from "solid-js"
import { useDialog } from "@opencode/ui/context/dialog"
import { focusField } from "@opencode/ui/context/field-focus"
import { setCursorPosition } from "@/composer/editor/dom"
import {
createComposerFocusState,
@ -123,7 +122,7 @@ function createComposerFocus() {
// A control chosen while the session was loading owns focus now.
if (active && active !== document.body && active !== opener && !isTitlebarTabLink(active)) return "claimed"
focusField(element, false, { preventScroll: true })
element.focus({ preventScroll: true })
setCursorPosition(element, effect.cursor)
return "focused"

View file

@ -2,7 +2,6 @@ import type { SessionUserActions } from "@opencode/session-ui/message"
import type { ShellOutputInput } from "@opencode/client/promise"
import { getFilename, sameDirectory } from "@opencode/util/path"
import { useDialog } from "@opencode/ui/context/dialog"
import { focusField, handOffFocus } from "@opencode/ui/context/field-focus"
import { isScrollKeyTarget, scrollKey, scrollKeyOwner } from "@opencode/ui/scroll-view"
import { makeEventListener } from "@solid-primitives/event-listener"
import { useNavigate } from "@solidjs/router"
@ -317,9 +316,8 @@ export function createActiveSessionRegion(input: {
navigateMessageByOffset: input.timeline.actions.navigateMessage,
jumpToMessage: input.timeline.actions.jumpToMessage,
revert,
// A shortcut moved focus, so the ring shows.
focusInput: () => {
if (promptRef && !input.session.data.isChild()) focusField(promptRef, true)
if (promptRef && !input.session.data.isChild()) promptRef.focus()
},
model: () => {
const selection = controls().model.selection
@ -372,7 +370,7 @@ export function createActiveSessionRegion(input: {
const focusPrompt = () => {
if (!promptRef) return
handOffFocus(promptRef)
promptRef.focus()
setCursorPosition(promptRef, prompt.cursor() ?? promptLength(prompt.current()))
}

View file

@ -15,11 +15,6 @@
outline: none;
}
.scroll-view__viewport:focus-visible {
outline: 2px solid var(--v2-border-border-focus);
outline-offset: -2px;
}
.scroll-view[data-orientation="horizontal"] .scroll-view__viewport {
overflow-x: auto;
overflow-y: hidden;

View file

@ -29,11 +29,10 @@ import {
type DialogStackEffect,
type DialogStackEvent,
} from "./dialog-machine"
import { focusField } from "./field-focus"
type DialogElement = () => JSX.Element
export type FocusReturn = { element: HTMLElement; visible: boolean; fieldRing?: boolean; range?: Range }
export type FocusReturn = { element: HTMLElement; visible: boolean; range?: Range }
/** What an open mounts: its content, the owner it renders under, and who hears that it closed. */
type DialogRequest = { element: DialogElement; owner: Owner; onClose?: () => void }
@ -259,9 +258,10 @@ function init(container: () => HTMLElement | undefined) {
const first = state.status === "active" ? state.entries[0] : undefined
// A new open can happen during the exit animation, after the user is already back in the opener.
// A new open can happen during the exit animation, after the user is already back in the opener and has moved
// its caret.
const refreshFocus =
first?.status === "closing" && focus?.fieldRing !== undefined && focus.element === first.focus?.element
first?.status === "closing" && focus?.range !== undefined && focus.element === first.focus?.element
return dispatch({ type: "open", mode, id: id ?? uuid(), aborted, focus, refreshFocus, request })
},
@ -283,13 +283,11 @@ function captureFocus(): FocusReturn | undefined {
// Closing with Escape counts as keyboard use, so Chromium would ring a control the pointer had focused.
const visible = element.matches(":focus-visible")
const fieldRing = element.hasAttribute("data-field-focus") ? element.hasAttribute("data-keyboard-focus") : undefined
if (!element.isContentEditable || !selection?.rangeCount || !element.contains(selection.anchorNode)) {
return { element, visible, fieldRing }
return { element, visible }
}
return { element, visible, fieldRing, range: selection.getRangeAt(0).cloneRange() }
return { element, visible, range: selection.getRangeAt(0).cloneRange() }
}
/** Kobalte only returns focus to a dialog trigger, and these dialogs open without one. */
@ -299,17 +297,9 @@ function returnFocus(focus: FocusReturn | undefined, layer: HTMLElement | undefi
if (!focus?.element.isConnected) return
// Something outside the closed dialog already has focus, for example because the dialog's onClose moved it.
if (active && active !== document.body && !layer?.contains(active)) {
// An outside click can put focus back before the dialog's return runs.
if (active === focus.element && focus.fieldRing !== undefined) focusField(focus.element, focus.fieldRing)
if (active && active !== document.body && !layer?.contains(active)) return
return
}
const options = { preventScroll: true, focusVisible: focus.visible }
if (focus.fieldRing === undefined) focus.element.focus(options)
else focusField(focus.element, focus.fieldRing, options)
focus.element.focus({ preventScroll: true, focusVisible: focus.visible })
if (!focus.range || !focus.element.contains(focus.range.commonAncestorContainer)) return
const selection = document.getSelection()

View file

@ -1,76 +0,0 @@
import { createSignal, onCleanup } from "solid-js"
const restoring = new WeakMap<HTMLElement, boolean>()
const fieldRings = new WeakMap<HTMLElement, (visible: boolean) => void>()
export function focusField(element: HTMLElement, visible: boolean, options?: FocusOptions) {
if (document.activeElement === element) {
fieldRings.get(element)?.(visible)
return
}
restoring.set(element, visible)
try {
element.focus(options)
} finally {
restoring.delete(element)
}
}
// Focus moved into a field for a control the user acted on keeps that control's ring state: none after a click, a ring
// after the keyboard. Undefined when the field already has focus, so its own state stays.
export function handoffRing(element: HTMLElement | undefined) {
const active = document.activeElement
if (active && active === element) return undefined
return active instanceof HTMLElement && active.matches(":focus-visible")
}
export function handOffFocus(element: HTMLElement, options?: FocusOptions) {
const visible = handoffRing(element)
if (visible !== undefined) focusField(element, visible, options)
}
export function createFieldFocus() {
const [visible, setVisible] = createSignal(false)
let pointer = false
let returning = false
let timer: ReturnType<typeof setTimeout> | undefined
const clearPointer = () => {
clearTimeout(timer)
pointer = false
}
onCleanup(clearPointer)
return {
visible,
pointer: () => {
clearPointer()
pointer = true
// Native focus follows this event's default action. Don't carry the press into a later focus.
timer = setTimeout(clearPointer, 0)
setVisible(false)
},
enter: (element: HTMLElement) => {
fieldRings.set(element, setVisible)
setVisible(restoring.get(element) ?? (!pointer && !returning))
returning = false
clearPointer()
},
leave: (event: FocusEvent) => {
// Switching to another window blurs the field but leaves it the active element, and focus returns to it on the way
// back. That return isn't the user moving focus to the field, so it shows no ring.
returning = event.currentTarget === document.activeElement
setVisible(false)
clearPointer()
},
}
}

View file

@ -2,8 +2,6 @@
// event. Inside a focus scope ([data-focus-scope]: a list, a tab strip, a chip row), move it to the next item, or to the
// previous one when the last item went, and widen to the enclosing scope when the inner one has nothing left.
import { focusField } from "./field-focus"
const FOCUSABLE = [
'a[href]:not([tabindex="-1"])',
'button:not(:disabled):not([tabindex="-1"])',
@ -58,7 +56,12 @@ export function installFocusRescue() {
}
}
const useKeyboard = () => {
// A rescued control shows its ring only while the keyboard is moving focus. Typing, shortcuts and a key pressed on a
// control the pointer focused are not that.
const NAVIGATION = new Set(["Tab", "ArrowUp", "ArrowDown", "ArrowLeft", "ArrowRight", "Home", "End"])
const useKeyboard = (event: KeyboardEvent) => {
if (event.ctrlKey || event.altKey || event.metaKey || !NAVIGATION.has(event.key)) return
keyboard = true
}
@ -145,15 +148,14 @@ function rescue() {
if (!entry.spot) return
const target = pick(entry.spot)
// Fields such as the composer draw their own ring.
if (target) return focusField(target, ring, { focusVisible: ring })
if (target) return target.focus({ focusVisible: ring })
if (target === undefined) continue
// A scope left with nothing to focus, such as the last toast, hands focus back to what had it before.
const previous = entries.slice(index + 1).find((item) => !item.spot && usable(item.element))
if (previous) focusField(previous.element, ring, { focusVisible: ring })
if (previous) previous.element.focus({ focusVisible: ring })
return
}