fix(app): keep tab widths while closing tabs with the mouse (#66887)

This commit is contained in:
Aiden Cline 2026-11-27 16:01:41 -06:00 • committed by GitHub
parent 68ea328db1
commit 36bfb85cd1
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
5 changed files with 407 additions and 0 deletions

View file

@ -0,0 +1,78 @@
import { For, onCleanup } from "solid-js"
import { createStore } from "solid-js/store"
import { render } from "solid-js/web"
import { Icon } from "@opencode/ui/icon"
import { IconButton } from "@opencode/ui/icon-button"
import { Tabs } from "@opencode/ui/tabs"
import { createTabStripScroll } from "../src/runtime/plugin/tab-strip-scroll"
import { createTabStripWidths } from "../src/runtime/plugin/tab-strip-widths"
const [state, setState] = createStore<{ titles: string[]; width: number }>({ titles: [], width: 0 })
const host = document.createElement("div")
/** A side pane tab strip built as `PaneTabs` builds it, with the host's tab styles, close buttons and sticky "+". */
export function mountTabStrip(input: { titles: string[]; width: number; dir: "ltr" | "rtl" }) {
setState({ titles: input.titles, width: input.width })
host.dataset.testid = "tab-strip-fixture"
host.dir = input.dir
// Above the story, at a fixed place in the viewport, so pointer positions stay put.
host.style.cssText = "position: fixed; top: 200px; left: 20px; z-index: 1000"
document.body.appendChild(host)
render(() => {
const close = (title: string) => setState("titles", (titles) => titles.filter((item) => item !== title))
return (
<aside id="review-panel" class="relative flex" style={{ width: `${state.width}px` }}>
<Tabs value={state.titles[0] ?? ""}>
<div class="session-review-v2-tabs-bar sticky top-0 shrink-0 flex items-center">
<Tabs.List
ref={(el: HTMLDivElement) => {
onCleanup(createTabStripScroll({ el, lead: () => false }))
onCleanup(createTabStripWidths(el))
}}
>
<For each={state.titles}>
{(title) => (
<div data-pane-tab={title} class="h-full flex items-center">
<div class="relative min-w-0">
<Tabs.Trigger
value={title}
onMiddleClick={title.startsWith("pinned") ? undefined : () => close(title)}
closeButton={
<IconButton
size="small"
variant="ghost-muted"
onPointerDown={(event) => {
event.preventDefault()
event.stopPropagation()
}}
onClick={(event) => {
event.preventDefault()
event.stopPropagation()
close(title)
}}
icon={<Icon name="close" />}
aria-label={`Close ${title}`}
/>
}
hideCloseButton
>
<span class="truncate">{title}</span>
</Tabs.Trigger>
</div>
</div>
)}
</For>
<div class="h-full shrink-0 sticky end-0 z-10 flex items-center justify-center bg-v2-background-bg-base">
<IconButton icon={<Icon name="plus" />} variant="ghost-muted" size="large" aria-label="Add tab" />
</div>
</Tabs.List>
</div>
</Tabs>
</aside>
)
}, host)
}
export const setTabStripWidth = (width: number) => setState("width", width)

View file

@ -0,0 +1,165 @@
import type { Page } from "@playwright/test"
import { expect, sourceURL, story } from "../../stories/playwright/story"
const fixture = sourceURL(new URL("./tab-strip-widths.fixture.tsx", import.meta.url))
const long = (name: string) => `a-file-name-long-enough-to-truncate-${name}.md`
story.beforeEach(async ({ mount }) => {
// Any story loads the app's styles; the fixture mounts the strip beside it.
await mount("ui-line-comment--editor")
})
async function mountStrip(page: Page, input: { titles: string[]; width: number; dir?: "ltr" | "rtl" }) {
await page.evaluate(
async ({ fixture, input }) => {
const { mountTabStrip } = await import(fixture)
mountTabStrip({ dir: "ltr", ...input })
await document.fonts.ready
},
{ fixture, input },
)
await expect(strip(page).locator("[data-pane-tab]")).toHaveCount(input.titles.length)
}
const strip = (page: Page) => page.getByTestId("tab-strip-fixture").locator('[data-slot="tabs-list"]')
const closeButton = (page: Page, title: string) =>
strip(page).locator(`[data-pane-tab="${title}"] [data-slot="tabs-trigger-close-button"]`)
async function center(page: Page, title: string) {
const box = (await closeButton(page, title).boundingBox())!
return { x: box.x + box.width / 2, y: box.y + box.height / 2 }
}
// The tab whose close button is at the point.
const under = (page: Page, point: { x: number; y: number }) =>
page.evaluate(
(point) =>
document
.elementFromPoint(point.x, point.y)
?.closest('[data-slot="tabs-trigger-close-button"]')
?.closest<HTMLElement>("[data-pane-tab]")?.dataset.paneTab,
point,
)
const hold = (page: Page) => strip(page).evaluate((el) => el.style.paddingInlineEnd)
const tabWidth = async (page: Page, title: string) =>
(await strip(page).locator(`[data-pane-tab="${title}"]`).boundingBox())!.width
story(
"a mouse close keeps the next close button under the pointer until the pointer leaves the strip",
async ({ page }) => {
const titles = [long("alpha"), "a.md", long("beta"), long("gamma"), "b.md", long("delta")]
await mountStrip(page, { titles, width: 900 })
const width = await tabWidth(page, long("gamma"))
const middle = await center(page, long("beta"))
await page.mouse.click(middle.x, middle.y)
await expect(strip(page).locator(`[data-pane-tab="${long("beta")}"]`)).toHaveCount(0)
await expect.poll(() => under(page, middle)).toBe(long("gamma"))
// The short tab before the last one keeps its width, so the long ones fill the closed tab's place.
const last = await center(page, long("delta"))
await page.mouse.click(last.x, last.y)
await expect(strip(page).locator(`[data-pane-tab="${long("delta")}"]`)).toHaveCount(0)
await expect.poll(() => under(page, last)).toBe("b.md")
// The "+" stays a gap after the last tab, and the held strip shows no end fade.
const gap = await strip(page).evaluate((el) => {
const plus = el.lastElementChild!.getBoundingClientRect()
const tab = el.querySelector('[data-pane-tab="b.md"]')!.getBoundingClientRect()
return Math.round(plus.left - tab.right)
})
expect(gap).toBe(8)
expect(await strip(page).evaluate((el) => el.style.getPropertyValue("--tab-strip-fade-end"))).toBe("0px")
await page.mouse.move(middle.x, middle.y + 200)
await expect.poll(() => hold(page)).toBe("")
await expect.poll(() => tabWidth(page, long("gamma"))).toBeGreaterThan(width + 1)
},
)
story("a middle click close holds the strip, and resizing the strip releases it", async ({ page }) => {
const titles = [long("alpha"), long("beta"), long("gamma"), long("delta")]
await mountStrip(page, { titles, width: 700 })
const width = await tabWidth(page, long("gamma"))
await strip(page)
.locator(`[data-pane-tab="${long("beta")}"] [role="tab"]`)
.click({ button: "middle" })
await expect(strip(page).locator(`[data-pane-tab="${long("beta")}"]`)).toHaveCount(0)
await expect.poll(() => tabWidth(page, long("gamma"))).toBeCloseTo(width, 0)
// Held, the three tabs would shrink with the strip; released, they share the whole of it.
await page.evaluate(async (fixture) => {
const { setTabStripWidth } = await import(fixture)
setTabStripWidth(650)
}, fixture)
await expect.poll(() => tabWidth(page, long("gamma"))).toBeGreaterThan(width + 1)
expect(await hold(page)).toBe("")
})
story("closing from the keyboard, or a middle click that closes nothing, resizes the tabs", async ({ page }) => {
const titles = [long("alpha"), "pinned.md", long("beta"), long("gamma")]
await mountStrip(page, { titles, width: 700 })
const width = await tabWidth(page, long("gamma"))
// The middle click on a tab without a middle-click close arms nothing for the keyboard close that follows.
await strip(page).locator('[data-pane-tab="pinned.md"] [role="tab"]').click({ button: "middle" })
await closeButton(page, "pinned.md").getByRole("button").focus()
await page.keyboard.press("Enter")
await expect(strip(page).locator('[data-pane-tab="pinned.md"]')).toHaveCount(0)
await expect.poll(() => tabWidth(page, long("gamma"))).toBeGreaterThan(width + 1)
const next = await tabWidth(page, long("gamma"))
await closeButton(page, long("alpha")).getByRole("button").focus()
await page.keyboard.press("Enter")
await expect(strip(page).locator(`[data-pane-tab="${long("alpha")}"]`)).toHaveCount(0)
await expect.poll(() => tabWidth(page, long("gamma"))).toBeGreaterThan(next + 1)
})
story("in a right-to-left strip the next close button slides under the pointer", async ({ page }) => {
const titles = [long("alpha"), long("beta"), long("gamma"), long("delta")]
await mountStrip(page, { titles, width: 700, dir: "rtl" })
const middle = await center(page, long("beta"))
await page.mouse.click(middle.x, middle.y)
await expect(strip(page).locator(`[data-pane-tab="${long("beta")}"]`)).toHaveCount(0)
await expect.poll(() => under(page, middle)).toBe(long("gamma"))
})
story(
"an overflowing strip is never held, so closing its last tab keeps the other tabs at their width",
async ({ page }) => {
const titles = Array.from({ length: 8 }, (_, index) => long(String(index)))
await mountStrip(page, { titles, width: 400 })
expect(await strip(page).evaluate((el) => el.scrollWidth > el.clientWidth)).toBe(true)
const width = await tabWidth(page, titles[6])
await strip(page).evaluate((el) => (el.scrollLeft = el.scrollWidth))
const last = await center(page, titles[7])
await page.mouse.click(last.x, last.y)
await expect(strip(page).locator("[data-pane-tab]")).toHaveCount(7)
expect(await hold(page)).toBe("")
expect(await tabWidth(page, titles[6])).toBeCloseTo(width, 0)
},
)
story.describe("touch", () => {
story.use({ hasTouch: true })
story("a tap on a close button never holds the strip", async ({ page }) => {
const titles = [long("alpha"), long("beta"), long("gamma"), long("delta")]
await mountStrip(page, { titles, width: 700 })
const width = await tabWidth(page, long("gamma"))
await closeButton(page, long("beta")).getByRole("button").tap()
await expect(strip(page).locator(`[data-pane-tab="${long("beta")}"]`)).toHaveCount(0)
await expect.poll(() => tabWidth(page, long("gamma"))).toBeGreaterThan(width + 1)
})
})

View file

@ -275,6 +275,74 @@ test("tabs in a narrow side strip shrink to keep their close buttons, and a tab'
await expect(side.getByRole("tab", { name: "a.md", exact: true })).toHaveCount(0)
})
test("closing side tabs with the mouse keeps the next close button under the pointer until it leaves the strip", async ({
page,
}) => {
// Wide enough for every tab, narrow enough that they shrink below their titles.
await page.setViewportSize({ width: 1600, height: 700 })
const directory = "C:/OpenCode/CloseWidths"
const key = `local\u0000${base64Encode(directory)}/ses_closewidths`
// A short tab before the last one keeps its own width while the long ones fill the strip.
const files = [...Array.from({ length: 6 }, (_, index) => `notes-file-${index}.md`), "b.md", "notes-file-7.md"]
await openSession(page, {
name: "CloseWidths",
fileList: () => [],
fileContent: (path) => ({ type: "text", content: `contents:${path}` }),
seed: {
panes: { ses_closewidths: { review: true, sessionWidth: 640 } },
storage: {
"opencode.global.dat:layout": {
sessionTabs: { [key]: { all: files.map((file) => `file://${file}`), active: `file://${files[0]}` } },
},
},
},
})
const side = page.locator('[data-pane-content="side"]')
const tabs = side.locator('[data-pane-strip="side"] [data-pane-tab]')
const close = (file: string) =>
side.locator(`[data-pane-tab="file://${file}"] [data-slot="tabs-trigger-close-button"]`)
const center = async (file: string) => {
const box = (await close(file).boundingBox())!
return { x: box.x + box.width / 2, y: box.y + box.height / 2 }
}
const under = (point: { x: number; y: number }) =>
page.evaluate(
(point) =>
document
.elementFromPoint(point.x, point.y)
?.closest('[data-slot="tabs-trigger-close-button"]')
?.closest<HTMLElement>("[data-pane-tab]")?.dataset.paneTab,
point,
)
await expect(tabs).toHaveCount(files.length)
await expect(side.getByRole("tab", { name: files[0], exact: true })).toHaveAttribute("aria-selected", "true")
await page.evaluate(() => document.fonts.ready.then(() => undefined))
const width = (await tabs.nth(1).boundingBox())!.width
// The next tab slides under the pointer at its old width.
const middle = await center(files[2])
await page.mouse.click(middle.x, middle.y)
await expect(tabs).toHaveCount(files.length - 1)
await expect.poll(() => under(middle)).toBe(`file://${files[3]}`)
// Closing the last tab brings the one before it under the pointer.
const last = await center(files[7])
await page.mouse.click(last.x, last.y)
await expect(tabs).toHaveCount(files.length - 2)
await expect.poll(() => under(last)).toBe("file://b.md")
// Once the pointer leaves the strip, the tabs fill it again.
await page.mouse.move(middle.x, middle.y + 200)
await expect.poll(async () => (await tabs.nth(1).boundingBox())!.width).toBeGreaterThan(width + 1)
})
test("a reopened side tab returns to where it closed", async ({ page }) => {
await page.setViewportSize({ width: 1440, height: 900 })
const directory = "C:/OpenCode/ReopenPlace"

View file

@ -29,6 +29,7 @@ import { createSessionPanelMenuEntries, type SessionPanelMenuEntry } from "./pan
import { RegionContent, type Region, type RegionPane } from "./panels"
import { PluginSlot } from "./render"
import { createTabStripScroll } from "./tab-strip-scroll"
import { createTabStripWidths } from "./tab-strip-widths"
import { closedTabsModifier, type ClosedSideTab } from "./closed-tabs"
import { ClosedTabsSection, createDeferredMenu, NewTabButton } from "./closed-tabs-view"
import { selectDeferredMenuOpen } from "./deferred-menu-machine"
@ -310,6 +311,7 @@ export function PaneTabs(props: {
capture: true,
})
onCleanup(createTabStripScroll({ el, lead: props.pane.lead }))
onCleanup(createTabStripWidths(el))
}}
onContextMenu={(event: MouseEvent) => {
const key =

View file

@ -0,0 +1,94 @@
/**
* Closing a tab with the mouse holds the strip at the tabs' width while the pointer stays on it, as Chrome does, so
* the next tab's close button slides under the pointer. The hold is end padding that takes the closed tab's place;
* closing the last tab keeps it as it is, so the tabs before it fill that place and the new last close button lands
* under the pointer. Leaving the strip, resizing it, opening or moving a tab, or closing one any other way lets the
* tabs fill the strip again. An overflowing strip scrolls instead, so it is never held.
*/
export const createTabStripWidths = (el: HTMLElement) => {
let closing: { tab: Element; hold: number } | undefined
let timer: ReturnType<typeof setTimeout> | undefined
let width = el.offsetWidth
const release = () => {
closing = undefined
el.style.removeProperty("padding-inline-end")
}
// Measured before the close runs, while the closing tab is still laid out.
const onClick = (event: MouseEvent) => {
const target = event.target
// Only this click's close may apply a hold measured for it.
closing = undefined
if (!(target instanceof Element)) return
// Touch and pen leave the strip before their click, which would hold it until the next mouse visit.
if (event instanceof PointerEvent && event.pointerType !== "mouse") return
// A click the keyboard sent on a close button has no click count.
const close =
event.type === "auxclick"
? event.button === 1
: event.detail > 0 && !!target.closest('[data-slot="tabs-trigger-close-button"]')
if (!close || el.scrollWidth > el.clientWidth) return
// Every child but the sticky "+" is a tab.
const tabs = Array.from(el.children).filter((child) => !child.classList.contains("sticky"))
const tab = tabs.find((child) => child.contains(target))
if (!tab) return
const held = Number.parseFloat(el.style.paddingInlineEnd) || 0
const freed =
tab === tabs.at(-1)
? 0
: tab.getBoundingClientRect().width + (Number.parseFloat(getComputedStyle(el).columnGap) || 0)
closing = { tab, hold: Math.max(0, Math.floor(held + freed)) }
// A click that closes nothing, such as a middle click on a pinned tab, holds nothing. The close and its mutation
// record land before the next task.
clearTimeout(timer)
timer = setTimeout(() => (closing = undefined))
}
const observer = new MutationObserver((records) => {
const added = records.some((record) => Array.from(record.addedNodes).some((node) => node instanceof Element))
if (added || !closing || el.contains(closing.tab)) return release()
el.style.setProperty("padding-inline-end", `${closing.hold}px`)
closing = undefined
})
// The border box, so the hold's own padding never releases it.
const resize = new ResizeObserver(() => {
if (el.offsetWidth === width) return
width = el.offsetWidth
release()
})
el.addEventListener("click", onClick, { capture: true })
el.addEventListener("auxclick", onClick, { capture: true })
el.addEventListener("pointerleave", release)
el.addEventListener("pointercancel", release)
window.addEventListener("blur", release)
observer.observe(el, { childList: true })
resize.observe(el, { box: "border-box" })
return () => {
el.removeEventListener("click", onClick, { capture: true })
el.removeEventListener("auxclick", onClick, { capture: true })
el.removeEventListener("pointerleave", release)
el.removeEventListener("pointercancel", release)
window.removeEventListener("blur", release)
observer.disconnect()
resize.disconnect()
clearTimeout(timer)
release()
}
}