mirror of
https://github.com/anomalyco/opencode.git
synced 2026-11-20 01:08:31 +03:00
fix(app): make tab preview, crash page actions, notification focus lock and mobile tabs drawer explicit state machines (#62005)
This commit is contained in:
committed by
GitHub
Unverified
parent
fe19d9b799
commit
2ec6485737
@@ -2,8 +2,7 @@ import { TextField } from "@opencode/ui/text-field"
|
||||
import type { captureException } from "@sentry/solid"
|
||||
import { Logo } from "@opencode/ui/logo"
|
||||
import { Button } from "@opencode/ui/button"
|
||||
import { Component, createSignal, onCleanup, onMount, Show } from "solid-js"
|
||||
import { createStore } from "solid-js/store"
|
||||
import { Component, createEffect, createSignal, on, onCleanup, onMount, Show, untrack } from "solid-js"
|
||||
import { Predicate } from "effect"
|
||||
import { Updater } from "@opencode/plugin/gui/updater"
|
||||
import { usePlatform } from "@/runtime/platform/platform"
|
||||
@@ -11,6 +10,22 @@ import { useLanguage } from "@/runtime/i18n/language"
|
||||
import { createIpcClients } from "@/runtime/plugin/ipc"
|
||||
import { Icon } from "@opencode/ui/icon"
|
||||
import { errorDescriptionKey, errorStatus } from "./description"
|
||||
import {
|
||||
INITIAL_ERROR_PAGE_STATE,
|
||||
isUpdaterBusy,
|
||||
selectActionError,
|
||||
selectCanReport,
|
||||
selectCheckingUpdates,
|
||||
selectCheckUpdatesDisabled,
|
||||
selectExportDisabled,
|
||||
selectInstallUpdateDisabled,
|
||||
selectReportDisabled,
|
||||
selectReported,
|
||||
selectUpdateVersion,
|
||||
transitionErrorPage,
|
||||
type ErrorPageEffect,
|
||||
type ErrorPageEvent,
|
||||
} from "./machine"
|
||||
|
||||
type InitError = {
|
||||
name: unknown
|
||||
@@ -257,75 +272,132 @@ export const ErrorPage: Component<ErrorPageProps> = (props) => {
|
||||
const language = useLanguage()
|
||||
const formattedError = () => formatError(props.error, language.t)
|
||||
const status = () => errorStatus(props.error)
|
||||
let recordedFatalError: Promise<void> | undefined
|
||||
const [pageState, setPageState] = createSignal(INITIAL_ERROR_PAGE_STATE)
|
||||
let capture: typeof captureException | undefined
|
||||
// The crash record in flight, which Export Logs waits for instead of recording the crash twice.
|
||||
let recording: Promise<boolean> | undefined
|
||||
const timers = new Set<ReturnType<typeof setTimeout>>()
|
||||
|
||||
const [store, setStore] = createStore<{
|
||||
actionError: string | undefined
|
||||
captureException: typeof captureException | undefined
|
||||
}>({
|
||||
actionError: undefined,
|
||||
captureException: undefined,
|
||||
})
|
||||
// A crash can take the plugin root down with the app, so the page reaches the updater's
|
||||
// main-process Ipc over the bridge itself.
|
||||
const ipcs = createIpcClients(platform.plugins)
|
||||
const updater = () => ipcs.typed(Updater)
|
||||
|
||||
function ensureFatalErrorRecorded() {
|
||||
recordedFatalError ??=
|
||||
const dispatch = (event: ErrorPageEvent) => {
|
||||
const previous = untrack(pageState)
|
||||
const next = transitionErrorPage(previous, event)
|
||||
|
||||
if (next.state !== previous) setPageState(next.state)
|
||||
next.effects.forEach(run)
|
||||
}
|
||||
|
||||
function run(effect: ErrorPageEffect) {
|
||||
if (effect.type === "sentry.capture") return capture?.(props.error)
|
||||
|
||||
if (effect.type === "fatal.record") {
|
||||
const attempt = effect.attempt
|
||||
void record(attempt)
|
||||
later(effect.timeoutMs, () => dispatch({ type: "fatal.settled", attempt, recorded: false }))
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
const attempt = effect.attempt
|
||||
|
||||
// Each action resolves to its error message, or undefined when it succeeded.
|
||||
const settle = (work: Promise<string | undefined>) =>
|
||||
void work.then(
|
||||
(error) =>
|
||||
dispatch(
|
||||
error === undefined ? { type: "action.succeeded", attempt } : { type: "action.failed", attempt, error },
|
||||
),
|
||||
(cause) => dispatch({ type: "action.failed", attempt, error: formatError(cause, language.t) }),
|
||||
)
|
||||
|
||||
if (effect.type === "logs.export") {
|
||||
const recorded = effect.recordFirst ? (recording ?? record(effect.fatalAttempt)) : Promise.resolve(true)
|
||||
|
||||
// A crash that cannot be recorded still leaves the logs to export; the native save dialog has no time limit.
|
||||
return settle(
|
||||
within(recorded, effect.recordTimeoutMs)
|
||||
.then(() => platform.exportDebugLogs?.())
|
||||
.then(() => undefined),
|
||||
)
|
||||
}
|
||||
|
||||
later(effect.timeoutMs, () =>
|
||||
dispatch({ type: "action.timed-out", attempt, error: language.t("common.requestFailed") }),
|
||||
)
|
||||
|
||||
if (effect.type === "updater.install") return settle(Promise.try(() => updater()?.install()).then(() => undefined))
|
||||
|
||||
settle(
|
||||
Promise.try(() => updater()?.check()).then((state) => (state?.status === "error" ? state.message : undefined)),
|
||||
)
|
||||
}
|
||||
|
||||
function record(attempt: number) {
|
||||
const pending = Promise.try(() =>
|
||||
platform.recordFatalRendererError?.({
|
||||
error: formattedError(),
|
||||
url: location.href,
|
||||
version: platform.version,
|
||||
platform: platform.platform,
|
||||
os: platform.os,
|
||||
}) ?? Promise.resolve()
|
||||
}),
|
||||
).then(
|
||||
() => true,
|
||||
() => false,
|
||||
)
|
||||
|
||||
return recordedFatalError
|
||||
recording = pending
|
||||
void pending.then((recorded) => {
|
||||
if (recording === pending) recording = undefined
|
||||
dispatch({ type: "fatal.settled", attempt, recorded })
|
||||
})
|
||||
|
||||
return pending
|
||||
}
|
||||
|
||||
function later(ms: number, fn: () => void) {
|
||||
const timer = setTimeout(() => {
|
||||
timers.delete(timer)
|
||||
fn()
|
||||
}, ms)
|
||||
|
||||
timers.add(timer)
|
||||
}
|
||||
|
||||
function within(promise: Promise<unknown>, ms: number) {
|
||||
return new Promise<void>((resolve) => {
|
||||
later(ms, resolve)
|
||||
void promise.then(() => resolve())
|
||||
})
|
||||
}
|
||||
|
||||
createEffect(
|
||||
on(
|
||||
() => props.error,
|
||||
() => dispatch({ type: "error.presented" }),
|
||||
),
|
||||
)
|
||||
|
||||
onMount(() => {
|
||||
void ensureFatalErrorRecorded().catch(() => undefined)
|
||||
void import("@sentry/solid")
|
||||
.then(({ captureException, isEnabled }) => {
|
||||
if (isEnabled()) setStore("captureException", () => captureException)
|
||||
const enabled = isEnabled()
|
||||
|
||||
if (enabled) capture = captureException
|
||||
dispatch({ type: "sentry.loaded", enabled })
|
||||
})
|
||||
.catch(() => undefined)
|
||||
})
|
||||
|
||||
// A crash can take the plugin root down with the app, so the page reaches the updater's
|
||||
// main-process Ipc over the bridge itself.
|
||||
const ipcs = createIpcClients(platform.plugins)
|
||||
onCleanup(ipcs.dispose)
|
||||
const updater = () => ipcs.typed(Updater)
|
||||
|
||||
async function checkForUpdates() {
|
||||
const state = await updater()?.check()
|
||||
setStore("actionError", state?.status === "error" ? state.message : undefined)
|
||||
}
|
||||
|
||||
async function installUpdate() {
|
||||
await updater()
|
||||
?.install()
|
||||
.then(() => setStore("actionError", undefined))
|
||||
.catch((err) => {
|
||||
setStore("actionError", formatError(err, language.t))
|
||||
})
|
||||
}
|
||||
|
||||
const updateVersion = () => {
|
||||
const state = updater()?.state()
|
||||
|
||||
return state?.status === "ready" || state?.status === "download-required" ? state.version : undefined
|
||||
}
|
||||
|
||||
async function exportDebugLogs() {
|
||||
const exportLogs = platform.exportDebugLogs
|
||||
|
||||
if (!exportLogs) return
|
||||
await ensureFatalErrorRecorded()
|
||||
.then(() => exportLogs())
|
||||
.then(() => setStore("actionError", undefined))
|
||||
.catch((err) => {
|
||||
setStore("actionError", formatError(err, language.t))
|
||||
})
|
||||
}
|
||||
onCleanup(() => {
|
||||
ipcs.dispose()
|
||||
timers.forEach(clearTimeout)
|
||||
dispatch({ type: "disposed" })
|
||||
})
|
||||
|
||||
return (
|
||||
<div
|
||||
@@ -358,53 +430,65 @@ export const ErrorPage: Component<ErrorPageProps> = (props) => {
|
||||
{language.t(platform.platform === "web" ? "error.page.action.reload" : "error.page.action.restart")}
|
||||
</Button>
|
||||
<Show when={platform.platform === "desktop" && platform.exportDebugLogs}>
|
||||
<Button size="large" variant="ghost" onClick={exportDebugLogs}>
|
||||
<Button
|
||||
size="large"
|
||||
variant="ghost"
|
||||
disabled={selectExportDisabled(pageState())}
|
||||
onClick={() => dispatch({ type: "export.clicked", available: !!platform.exportDebugLogs })}
|
||||
>
|
||||
{language.t("error.page.action.exportLogs")}
|
||||
</Button>
|
||||
</Show>
|
||||
<Show when={store.captureException}>
|
||||
{(capture) => {
|
||||
const [reported, setReported] = createSignal(false)
|
||||
|
||||
return (
|
||||
<Button
|
||||
size="large"
|
||||
disabled={reported()}
|
||||
onClick={() => {
|
||||
capture()(props.error)
|
||||
setReported(true)
|
||||
}}
|
||||
>
|
||||
{language.t(reported() ? "error.page.action.reported" : "error.page.action.report")}
|
||||
</Button>
|
||||
)
|
||||
}}
|
||||
<Show when={selectCanReport(pageState())}>
|
||||
<Button
|
||||
size="large"
|
||||
disabled={selectReportDisabled(pageState())}
|
||||
onClick={() => dispatch({ type: "report.clicked" })}
|
||||
>
|
||||
{language.t(selectReported(pageState()) ? "error.page.action.reported" : "error.page.action.report")}
|
||||
</Button>
|
||||
</Show>
|
||||
<Show when={updater()}>
|
||||
<Show
|
||||
when={updateVersion()}
|
||||
when={selectUpdateVersion(updater()?.state())}
|
||||
fallback={
|
||||
<Button
|
||||
size="large"
|
||||
variant="ghost"
|
||||
onClick={checkForUpdates}
|
||||
disabled={["checking", "downloading", "installing"].includes(updater()?.state()?.status ?? "")}
|
||||
onClick={() =>
|
||||
dispatch({
|
||||
type: "check.clicked",
|
||||
available: !!updater(),
|
||||
busy: isUpdaterBusy(updater()?.state()),
|
||||
})
|
||||
}
|
||||
disabled={selectCheckUpdatesDisabled(pageState(), updater()?.state())}
|
||||
>
|
||||
{updater()?.state()?.status === "checking"
|
||||
{selectCheckingUpdates(pageState(), updater()?.state())
|
||||
? language.t("error.page.action.checking")
|
||||
: language.t("error.page.action.checkUpdates")}
|
||||
</Button>
|
||||
}
|
||||
>
|
||||
{(version) => (
|
||||
<Button size="large" onClick={installUpdate}>
|
||||
<Button
|
||||
size="large"
|
||||
disabled={selectInstallUpdateDisabled(pageState(), updater()?.state())}
|
||||
onClick={() =>
|
||||
dispatch({
|
||||
type: "install.clicked",
|
||||
available: !!updater(),
|
||||
busy: updater()?.state()?.status === "installing",
|
||||
})
|
||||
}
|
||||
>
|
||||
{language.t("error.page.action.updateTo", { version: version() })}
|
||||
</Button>
|
||||
)}
|
||||
</Show>
|
||||
</Show>
|
||||
</div>
|
||||
<Show when={store.actionError}>
|
||||
<Show when={selectActionError(pageState())}>
|
||||
{(message) => <p class="text-xs text-text-danger-base text-center max-w-2xl">{message()}</p>}
|
||||
</Show>
|
||||
<div class="flex flex-col items-center gap-2 text-xs text-center">
|
||||
|
||||
@@ -0,0 +1,178 @@
|
||||
import { describe, expect, test } from "bun:test"
|
||||
import {
|
||||
ERROR_ACTION_TIMEOUT_MS,
|
||||
FATAL_RECORD_TIMEOUT_MS,
|
||||
INITIAL_ERROR_PAGE_STATE,
|
||||
selectActionError,
|
||||
selectCheckUpdatesDisabled,
|
||||
selectExportDisabled,
|
||||
selectInstallUpdateDisabled,
|
||||
selectReportDisabled,
|
||||
selectReported,
|
||||
transitionErrorPage,
|
||||
type ErrorPageEffect,
|
||||
type ErrorPageEvent,
|
||||
type ErrorPageState,
|
||||
} from "./machine"
|
||||
|
||||
const replay = (events: ErrorPageEvent[], state = INITIAL_ERROR_PAGE_STATE) =>
|
||||
events.reduce<{ state: ErrorPageState; effects: ErrorPageEffect[] }>(
|
||||
(current, event) => {
|
||||
const next = transitionErrorPage(current.state, event)
|
||||
|
||||
return { state: next.state, effects: [...current.effects, ...next.effects] }
|
||||
},
|
||||
{ state, effects: [] },
|
||||
)
|
||||
|
||||
const presented: ErrorPageEvent = { type: "error.presented" }
|
||||
|
||||
const check: ErrorPageEvent = { type: "check.clicked", available: true, busy: false }
|
||||
|
||||
const install: ErrorPageEvent = { type: "install.clicked", available: true, busy: false }
|
||||
|
||||
const exportLogs: ErrorPageEvent = { type: "export.clicked", available: true }
|
||||
|
||||
describe("error page actions", () => {
|
||||
test("starting an action clears the previous action's error", () => {
|
||||
const failed = replay([presented, exportLogs, { type: "action.failed", attempt: 1, error: "Export failed" }]).state
|
||||
expect(selectActionError(failed)).toBe("Export failed")
|
||||
|
||||
const checking = transitionErrorPage(failed, check)
|
||||
expect(checking.state.status).toBe("checking")
|
||||
expect(selectActionError(checking.state)).toBeUndefined()
|
||||
expect(checking.effects).toEqual([{ type: "updater.check", attempt: 2, timeoutMs: ERROR_ACTION_TIMEOUT_MS }])
|
||||
})
|
||||
|
||||
test("a crash that failed to record does not block Export Logs", () => {
|
||||
const start = replay([presented])
|
||||
expect(start.effects).toEqual([{ type: "fatal.record", attempt: 1, timeoutMs: FATAL_RECORD_TIMEOUT_MS }])
|
||||
|
||||
const unrecorded = transitionErrorPage(start.state, { type: "fatal.settled", attempt: 1, recorded: false }).state
|
||||
const exporting = transitionErrorPage(unrecorded, exportLogs)
|
||||
expect(exporting.effects).toEqual([
|
||||
{
|
||||
type: "logs.export",
|
||||
attempt: 1,
|
||||
fatalAttempt: 1,
|
||||
recordFirst: true,
|
||||
recordTimeoutMs: FATAL_RECORD_TIMEOUT_MS,
|
||||
},
|
||||
])
|
||||
expect(transitionErrorPage(exporting.state, { type: "action.succeeded", attempt: 1 }).state.status).toBe("idle")
|
||||
})
|
||||
|
||||
test("a recorded crash exports at once, even when the record answered after its timeout", () => {
|
||||
const late = replay([
|
||||
presented,
|
||||
{ type: "fatal.settled", attempt: 1, recorded: false },
|
||||
{ type: "fatal.settled", attempt: 1, recorded: true },
|
||||
exportLogs,
|
||||
])
|
||||
|
||||
expect(late.effects.at(-1)).toMatchObject({ type: "logs.export", recordFirst: false })
|
||||
})
|
||||
|
||||
test("the first click claims the action and later clicks wait", () => {
|
||||
const exporting = replay([presented, exportLogs]).state
|
||||
expect(selectExportDisabled(exporting)).toBe(true)
|
||||
expect(selectCheckUpdatesDisabled(exporting, undefined)).toBe(true)
|
||||
|
||||
for (const event of [exportLogs, install, check]) {
|
||||
const again = transitionErrorPage(exporting, event)
|
||||
expect(again.state).toBe(exporting)
|
||||
expect(again.effects).toEqual([])
|
||||
}
|
||||
})
|
||||
|
||||
test("results of an earlier action are ignored", () => {
|
||||
const installing = replay([presented, check, { type: "action.succeeded", attempt: 1 }, install]).state
|
||||
expect(installing).toMatchObject({ status: "installing", attempt: 2 })
|
||||
|
||||
for (const event of [
|
||||
{ type: "action.succeeded", attempt: 1 },
|
||||
{ type: "action.failed", attempt: 1, error: "late" },
|
||||
{ type: "action.timed-out", attempt: 1, error: "late" },
|
||||
] satisfies ErrorPageEvent[])
|
||||
expect(transitionErrorPage(installing, event).state).toBe(installing)
|
||||
})
|
||||
|
||||
test("a busy or missing updater does not start an action", () => {
|
||||
const idle = replay([presented]).state
|
||||
expect(transitionErrorPage(idle, { type: "check.clicked", available: true, busy: true }).state).toBe(idle)
|
||||
expect(transitionErrorPage(idle, { type: "install.clicked", available: false, busy: false }).state).toBe(idle)
|
||||
expect(transitionErrorPage(idle, { type: "export.clicked", available: false }).state).toBe(idle)
|
||||
})
|
||||
|
||||
test("a check that never answers fails after the timeout and can be retried", () => {
|
||||
const timedOut = replay([presented, check, { type: "action.timed-out", attempt: 1, error: "Request failed" }])
|
||||
expect(selectActionError(timedOut.state)).toBe("Request failed")
|
||||
expect(selectCheckUpdatesDisabled(timedOut.state, undefined)).toBe(false)
|
||||
expect(transitionErrorPage(timedOut.state, check).state.status).toBe("checking")
|
||||
})
|
||||
|
||||
test("a new error resets the report and the action error, and records the new crash", () => {
|
||||
const reported = replay([
|
||||
presented,
|
||||
{ type: "sentry.loaded", enabled: true },
|
||||
{ type: "report.clicked" },
|
||||
check,
|
||||
{ type: "action.failed", attempt: 1, error: "Check failed" },
|
||||
])
|
||||
|
||||
expect(reported.effects).toContainEqual({ type: "sentry.capture" })
|
||||
expect(selectReported(reported.state)).toBe(true)
|
||||
expect(selectReportDisabled(reported.state)).toBe(true)
|
||||
|
||||
const next = transitionErrorPage(reported.state, presented)
|
||||
expect(next.state).toEqual({ status: "idle", attempt: 1, fatalAttempt: 2, fatal: "recording", report: "ready" })
|
||||
expect(selectActionError(next.state)).toBeUndefined()
|
||||
expect(next.effects).toEqual([{ type: "fatal.record", attempt: 2, timeoutMs: FATAL_RECORD_TIMEOUT_MS }])
|
||||
// The previous crash's record answers late.
|
||||
expect(transitionErrorPage(next.state, { type: "fatal.settled", attempt: 1, recorded: true }).state).toBe(
|
||||
next.state,
|
||||
)
|
||||
})
|
||||
|
||||
test("an action still running when a new error arrives keeps the page busy until it settles", () => {
|
||||
for (const start of [check, install, exportLogs]) {
|
||||
const busy = replay([presented, { type: "sentry.loaded", enabled: true }, { type: "report.clicked" }, start])
|
||||
const next = transitionErrorPage(busy.state, presented)
|
||||
|
||||
expect(next.state).toMatchObject({ status: busy.state.status, attempt: 1, fatalAttempt: 2, report: "ready" })
|
||||
expect(selectExportDisabled(next.state)).toBe(true)
|
||||
expect(selectCheckUpdatesDisabled(next.state, undefined)).toBe(true)
|
||||
expect(selectInstallUpdateDisabled(next.state, undefined)).toBe(true)
|
||||
|
||||
// A click meanwhile does not start a second action beside the first.
|
||||
for (const event of [check, install, exportLogs])
|
||||
expect(transitionErrorPage(next.state, event).state).toBe(next.state)
|
||||
|
||||
// The running action settles; its timeout and late duplicates then change nothing.
|
||||
const failed = transitionErrorPage(next.state, { type: "action.failed", attempt: 1, error: "Install failed" })
|
||||
expect(selectActionError(failed.state)).toBe("Install failed")
|
||||
expect(transitionErrorPage(failed.state, { type: "action.timed-out", attempt: 1, error: "late" }).state).toBe(
|
||||
failed.state,
|
||||
)
|
||||
expect(
|
||||
transitionErrorPage(next.state, { type: "action.timed-out", attempt: 1, error: "Request failed" }).state,
|
||||
).toMatchObject({ status: "failed", error: "Request failed" })
|
||||
}
|
||||
})
|
||||
|
||||
test("Report stays hidden until Sentry is enabled, and sends once", () => {
|
||||
const idle = replay([presented, { type: "sentry.loaded", enabled: false }]).state
|
||||
expect(transitionErrorPage(idle, { type: "report.clicked" }).effects).toEqual([])
|
||||
|
||||
const reported = replay([{ type: "sentry.loaded", enabled: true }, { type: "report.clicked" }], idle).state
|
||||
expect(transitionErrorPage(reported, { type: "report.clicked" }).effects).toEqual([])
|
||||
})
|
||||
|
||||
test("disposal ignores every later event", () => {
|
||||
const disposed = replay([presented, check, { type: "disposed" }]).state
|
||||
expect(disposed.status).toBe("disposed")
|
||||
|
||||
for (const event of [{ type: "action.succeeded", attempt: 2 }, presented, exportLogs] satisfies ErrorPageEvent[])
|
||||
expect(transitionErrorPage(disposed, event).state).toBe(disposed)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,217 @@
|
||||
import type { UpdaterState } from "@opencode/plugin/gui/updater"
|
||||
|
||||
// Main bounds its own update check; this covers a bridge that never answers after the crash.
|
||||
export const ERROR_ACTION_TIMEOUT_MS = 30_000
|
||||
|
||||
// Export Logs waits this long for the crash to reach the log before it exports anyway.
|
||||
export const FATAL_RECORD_TIMEOUT_MS = 2_000
|
||||
|
||||
/** Whether the crash reached the main-process log: `pending` until it has, so Export Logs records it first. */
|
||||
export type ErrorFatalStatus = "pending" | "recording" | "recorded"
|
||||
|
||||
/** `unavailable` while Sentry is off or still loading; `reported` once the user sent this error. */
|
||||
export type ErrorReportStatus = "unavailable" | "ready" | "reported"
|
||||
|
||||
type ErrorPageFields = {
|
||||
readonly attempt: number
|
||||
readonly fatalAttempt: number
|
||||
readonly fatal: ErrorFatalStatus
|
||||
readonly report: ErrorReportStatus
|
||||
}
|
||||
|
||||
/**
|
||||
* The crash page's actions. One action runs at a time; `failed` shows its error until the next action starts or
|
||||
* another error is shown.
|
||||
*/
|
||||
export type ErrorPageState =
|
||||
| (ErrorPageFields & { readonly status: "idle" })
|
||||
| (ErrorPageFields & { readonly status: "checking" })
|
||||
| (ErrorPageFields & { readonly status: "installing" })
|
||||
| (ErrorPageFields & { readonly status: "exporting" })
|
||||
| (ErrorPageFields & { readonly status: "failed"; readonly error: string })
|
||||
| { readonly status: "disposed" }
|
||||
|
||||
export type ErrorPageEvent =
|
||||
/** The page shows an error: on mount, and again when the boundary passes a new one. */
|
||||
| { readonly type: "error.presented" }
|
||||
| { readonly type: "fatal.settled"; readonly attempt: number; readonly recorded: boolean }
|
||||
| { readonly type: "sentry.loaded"; readonly enabled: boolean }
|
||||
| { readonly type: "report.clicked" }
|
||||
/** `available` is false without an updater; `busy` while the updater itself checks, downloads or installs. */
|
||||
| { readonly type: "check.clicked"; readonly available: boolean; readonly busy: boolean }
|
||||
| { readonly type: "install.clicked"; readonly available: boolean; readonly busy: boolean }
|
||||
| { readonly type: "export.clicked"; readonly available: boolean }
|
||||
| { readonly type: "action.succeeded"; readonly attempt: number }
|
||||
| { readonly type: "action.failed"; readonly attempt: number; readonly error: string }
|
||||
| { readonly type: "action.timed-out"; readonly attempt: number; readonly error: string }
|
||||
| { readonly type: "disposed" }
|
||||
|
||||
export type ErrorPageEffect =
|
||||
| { readonly type: "fatal.record"; readonly attempt: number; readonly timeoutMs: number }
|
||||
| { readonly type: "sentry.capture" }
|
||||
| { readonly type: "updater.check"; readonly attempt: number; readonly timeoutMs: number }
|
||||
| { readonly type: "updater.install"; readonly attempt: number; readonly timeoutMs: number }
|
||||
/** `recordFirst` records the crash first, bounded by `recordTimeoutMs`, so the exported log holds it. */
|
||||
| {
|
||||
readonly type: "logs.export"
|
||||
readonly attempt: number
|
||||
readonly fatalAttempt: number
|
||||
readonly recordFirst: boolean
|
||||
readonly recordTimeoutMs: number
|
||||
}
|
||||
|
||||
export type ErrorPageTransition = {
|
||||
readonly state: ErrorPageState
|
||||
readonly effects: readonly ErrorPageEffect[]
|
||||
}
|
||||
|
||||
export const INITIAL_ERROR_PAGE_STATE: ErrorPageState = Object.freeze({
|
||||
status: "idle",
|
||||
attempt: 0,
|
||||
fatalAttempt: 0,
|
||||
fatal: "pending",
|
||||
report: "unavailable",
|
||||
})
|
||||
|
||||
const DISPOSED: ErrorPageState = Object.freeze({ status: "disposed" })
|
||||
|
||||
const NONE: readonly ErrorPageEffect[] = []
|
||||
|
||||
export function transitionErrorPage(state: ErrorPageState, event: ErrorPageEvent): ErrorPageTransition {
|
||||
if (state.status === "disposed") return unchanged(state)
|
||||
|
||||
if (event.type === "disposed") return { state: DISPOSED, effects: NONE }
|
||||
|
||||
if (event.type === "error.presented") {
|
||||
// A new error gets its own record and report, and drops the previous action's error. An action still running
|
||||
// stays busy until it settles: it acts on the app, not on the error, and a second one must not start beside it.
|
||||
const attempt = state.fatalAttempt + 1
|
||||
|
||||
return {
|
||||
state: {
|
||||
status: state.status === "failed" ? "idle" : state.status,
|
||||
attempt: state.attempt,
|
||||
fatalAttempt: attempt,
|
||||
fatal: "recording",
|
||||
report: state.report === "unavailable" ? "unavailable" : "ready",
|
||||
},
|
||||
effects: [{ type: "fatal.record", attempt, timeoutMs: FATAL_RECORD_TIMEOUT_MS }],
|
||||
}
|
||||
}
|
||||
|
||||
if (event.type === "fatal.settled") {
|
||||
if (event.attempt !== state.fatalAttempt || state.fatal === "recorded") return unchanged(state)
|
||||
// A record that answers after its timeout still counts, so Export Logs does not record it twice.
|
||||
const fatal = event.recorded ? "recorded" : "pending"
|
||||
|
||||
return fatal === state.fatal ? unchanged(state) : { state: { ...state, fatal }, effects: NONE }
|
||||
}
|
||||
|
||||
if (event.type === "sentry.loaded")
|
||||
return event.enabled && state.report === "unavailable"
|
||||
? { state: { ...state, report: "ready" }, effects: NONE }
|
||||
: unchanged(state)
|
||||
|
||||
if (event.type === "report.clicked")
|
||||
return state.report === "ready"
|
||||
? { state: { ...state, report: "reported" }, effects: [{ type: "sentry.capture" }] }
|
||||
: unchanged(state)
|
||||
|
||||
if (event.type === "check.clicked" || event.type === "install.clicked" || event.type === "export.clicked")
|
||||
return start(state, event)
|
||||
|
||||
if (!isBusy(state) || event.attempt !== state.attempt) return unchanged(state)
|
||||
|
||||
if (event.type === "action.succeeded") return { state: { ...fields(state), status: "idle" }, effects: NONE }
|
||||
|
||||
return { state: { ...fields(state), status: "failed", error: event.error }, effects: NONE }
|
||||
}
|
||||
|
||||
export function selectCanReport(state: ErrorPageState) {
|
||||
return state.status !== "disposed" && state.report !== "unavailable"
|
||||
}
|
||||
|
||||
export function selectReported(state: ErrorPageState) {
|
||||
return state.status !== "disposed" && state.report === "reported"
|
||||
}
|
||||
|
||||
export function selectReportDisabled(state: ErrorPageState) {
|
||||
return state.status === "disposed" || state.report !== "ready"
|
||||
}
|
||||
|
||||
export function selectExportDisabled(state: ErrorPageState) {
|
||||
return state.status === "disposed" || isBusy(state)
|
||||
}
|
||||
|
||||
export function selectUpdateVersion(updater: UpdaterState | undefined) {
|
||||
return updater?.status === "ready" || updater?.status === "download-required" ? updater.version : undefined
|
||||
}
|
||||
|
||||
export function selectCheckingUpdates(state: ErrorPageState, updater: UpdaterState | undefined) {
|
||||
return state.status === "checking" || updater?.status === "checking"
|
||||
}
|
||||
|
||||
export function selectCheckUpdatesDisabled(state: ErrorPageState, updater: UpdaterState | undefined) {
|
||||
return state.status === "disposed" || isBusy(state) || isUpdaterBusy(updater)
|
||||
}
|
||||
|
||||
export function selectInstallUpdateDisabled(state: ErrorPageState, updater: UpdaterState | undefined) {
|
||||
return state.status === "disposed" || isBusy(state) || updater?.status === "installing"
|
||||
}
|
||||
|
||||
export function selectActionError(state: ErrorPageState) {
|
||||
return state.status === "failed" ? state.error : undefined
|
||||
}
|
||||
|
||||
export function isUpdaterBusy(updater: UpdaterState | undefined) {
|
||||
return updater?.status === "checking" || updater?.status === "downloading" || updater?.status === "installing"
|
||||
}
|
||||
|
||||
type LiveState = Exclude<ErrorPageState, { status: "disposed" }>
|
||||
|
||||
function start(
|
||||
state: LiveState,
|
||||
event: Extract<ErrorPageEvent, { type: "check.clicked" | "install.clicked" | "export.clicked" }>,
|
||||
): ErrorPageTransition {
|
||||
// The first click claims the action; a double click, or another action meanwhile, waits for it.
|
||||
if (isBusy(state) || !event.available || (event.type !== "export.clicked" && event.busy)) return unchanged(state)
|
||||
const attempt = state.attempt + 1
|
||||
const next = { ...fields(state), attempt }
|
||||
|
||||
if (event.type === "check.clicked")
|
||||
return {
|
||||
state: { ...next, status: "checking" },
|
||||
effects: [{ type: "updater.check", attempt, timeoutMs: ERROR_ACTION_TIMEOUT_MS }],
|
||||
}
|
||||
|
||||
if (event.type === "install.clicked")
|
||||
return {
|
||||
state: { ...next, status: "installing" },
|
||||
effects: [{ type: "updater.install", attempt, timeoutMs: ERROR_ACTION_TIMEOUT_MS }],
|
||||
}
|
||||
|
||||
return {
|
||||
state: { ...next, status: "exporting" },
|
||||
effects: [
|
||||
{
|
||||
type: "logs.export",
|
||||
attempt,
|
||||
fatalAttempt: state.fatalAttempt,
|
||||
recordFirst: state.fatal !== "recorded",
|
||||
recordTimeoutMs: FATAL_RECORD_TIMEOUT_MS,
|
||||
},
|
||||
],
|
||||
}
|
||||
}
|
||||
|
||||
function isBusy(state: ErrorPageState) {
|
||||
return state.status === "checking" || state.status === "installing" || state.status === "exporting"
|
||||
}
|
||||
|
||||
function fields(state: LiveState): ErrorPageFields {
|
||||
return { attempt: state.attempt, fatalAttempt: state.fatalAttempt, fatal: state.fatal, report: state.report }
|
||||
}
|
||||
|
||||
function unchanged(state: ErrorPageState): ErrorPageTransition {
|
||||
return { state, effects: NONE }
|
||||
}
|
||||
@@ -1,7 +1,6 @@
|
||||
import { onCleanup } from "solid-js"
|
||||
import { Predicate } from "effect"
|
||||
|
||||
type FocusLock = { pending: boolean; release?: VoidFunction }
|
||||
import { INITIAL_FOCUS_LOCK_STATE, transitionFocusLock, type FocusLockEvent } from "./focus-lock-machine"
|
||||
|
||||
const FOCUS_LOCK = "opencode:notification-focus"
|
||||
|
||||
@@ -14,43 +13,52 @@ export function createNotificationCoordinator() {
|
||||
|
||||
const claimed = new Set<string>()
|
||||
|
||||
const focus: FocusLock = { pending: false }
|
||||
if (typeof window !== "undefined" && locks) {
|
||||
let focusState = INITIAL_FOCUS_LOCK_STATE
|
||||
const releases = new Map<number, VoidFunction>()
|
||||
|
||||
const updateFocus = () => {
|
||||
if (typeof document === "undefined" || !document.hasFocus()) {
|
||||
focus.release?.()
|
||||
const dispatch = (event: FocusLockEvent) => {
|
||||
const next = transitionFocusLock(focusState, event)
|
||||
focusState = next.state
|
||||
next.effects.forEach((effect) => {
|
||||
const attempt = effect.attempt
|
||||
|
||||
return
|
||||
if (effect.type === "lock.release") {
|
||||
releases.get(attempt)?.()
|
||||
releases.delete(attempt)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
// A shared hold: every focused window keeps it, and an alert's exclusive request fails while any one does.
|
||||
locks
|
||||
.request(
|
||||
FOCUS_LOCK,
|
||||
{ mode: "shared" },
|
||||
() =>
|
||||
new Promise<void>((resolve) => {
|
||||
releases.set(attempt, resolve)
|
||||
dispatch({ type: "lock.acquired", attempt })
|
||||
}),
|
||||
)
|
||||
.catch(() => {
|
||||
releases.delete(attempt)
|
||||
dispatch({ type: "lock.failed", attempt })
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
if (!locks || focus.pending || focus.release) return
|
||||
const syncFocus = () => dispatch({ type: "focus.changed", focused: document.hasFocus() })
|
||||
|
||||
focus.pending = true
|
||||
void locks
|
||||
.request(FOCUS_LOCK, { mode: "shared" }, async () => {
|
||||
focus.pending = false
|
||||
|
||||
if (!document.hasFocus()) return
|
||||
await new Promise<void>((resolve) => {
|
||||
focus.release = resolve
|
||||
})
|
||||
focus.release = undefined
|
||||
})
|
||||
.catch(() => {
|
||||
focus.pending = false
|
||||
})
|
||||
}
|
||||
|
||||
if (typeof window !== "undefined") {
|
||||
window.addEventListener("focus", updateFocus)
|
||||
window.addEventListener("blur", updateFocus)
|
||||
document.addEventListener("visibilitychange", updateFocus)
|
||||
updateFocus()
|
||||
window.addEventListener("focus", syncFocus)
|
||||
window.addEventListener("blur", syncFocus)
|
||||
document.addEventListener("visibilitychange", syncFocus)
|
||||
syncFocus()
|
||||
onCleanup(() => {
|
||||
window.removeEventListener("focus", updateFocus)
|
||||
window.removeEventListener("blur", updateFocus)
|
||||
document.removeEventListener("visibilitychange", updateFocus)
|
||||
focus.release?.()
|
||||
window.removeEventListener("focus", syncFocus)
|
||||
window.removeEventListener("blur", syncFocus)
|
||||
document.removeEventListener("visibilitychange", syncFocus)
|
||||
dispatch({ type: "disposed" })
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,79 @@
|
||||
import { describe, expect, test } from "bun:test"
|
||||
import {
|
||||
INITIAL_FOCUS_LOCK_STATE,
|
||||
transitionFocusLock,
|
||||
type FocusLockEffect,
|
||||
type FocusLockEvent,
|
||||
type FocusLockState,
|
||||
} from "./focus-lock-machine"
|
||||
|
||||
const replay = (events: FocusLockEvent[], state = INITIAL_FOCUS_LOCK_STATE) =>
|
||||
events.reduce<{ state: FocusLockState; effects: FocusLockEffect[] }>(
|
||||
(current, event) => {
|
||||
const next = transitionFocusLock(current.state, event)
|
||||
|
||||
return { state: next.state, effects: [...current.effects, ...next.effects] }
|
||||
},
|
||||
{ state, effects: [] },
|
||||
)
|
||||
|
||||
const focus = (focused: boolean): FocusLockEvent => ({ type: "focus.changed", focused })
|
||||
|
||||
describe("notification focus lock", () => {
|
||||
test("a blur and an immediate refocus request the lock again", () => {
|
||||
const held = replay([focus(true), { type: "lock.acquired", attempt: 1 }]).state
|
||||
expect(held).toEqual({ status: "held", attempt: 1 })
|
||||
|
||||
// Both events land before the released lock callback resumes.
|
||||
const result = replay([focus(false), focus(true)], held)
|
||||
expect(result.effects).toEqual([
|
||||
{ type: "lock.release", attempt: 1 },
|
||||
{ type: "lock.acquire", attempt: 2 },
|
||||
])
|
||||
expect(result.state).toEqual({ status: "requesting", attempt: 2, focused: true })
|
||||
expect(replay([{ type: "lock.acquired", attempt: 2 }], result.state).state).toEqual({ status: "held", attempt: 2 })
|
||||
})
|
||||
|
||||
test("a grant after disposal is released", () => {
|
||||
const disposed = replay([focus(true), { type: "disposed" }])
|
||||
expect(disposed.state.status).toBe("disposed")
|
||||
expect(disposed.effects).toEqual([{ type: "lock.acquire", attempt: 1 }])
|
||||
|
||||
const late = transitionFocusLock(disposed.state, { type: "lock.acquired", attempt: 1 })
|
||||
expect(late.state).toBe(disposed.state)
|
||||
expect(late.effects).toEqual([{ type: "lock.release", attempt: 1 }])
|
||||
})
|
||||
|
||||
test("disposing while held releases the lock", () => {
|
||||
const result = replay([focus(true), { type: "lock.acquired", attempt: 1 }, { type: "disposed" }])
|
||||
expect(result.effects.at(-1)).toEqual({ type: "lock.release", attempt: 1 })
|
||||
expect(transitionFocusLock(result.state, focus(true)).effects).toEqual([])
|
||||
})
|
||||
|
||||
test("focus changes while requesting do not request twice", () => {
|
||||
const flicker = replay([focus(true), focus(false), focus(true)])
|
||||
expect(flicker.effects).toEqual([{ type: "lock.acquire", attempt: 1 }])
|
||||
expect(replay([{ type: "lock.acquired", attempt: 1 }], flicker.state).state).toEqual({ status: "held", attempt: 1 })
|
||||
|
||||
// Still unfocused when the grant arrives: release it at once.
|
||||
const blurred = replay([focus(true), focus(false), { type: "lock.acquired", attempt: 1 }])
|
||||
expect(blurred.state).toEqual({ status: "unfocused", attempt: 1 })
|
||||
expect(blurred.effects.at(-1)).toEqual({ type: "lock.release", attempt: 1 })
|
||||
})
|
||||
|
||||
test("a failed request lets the next focus try again", () => {
|
||||
const failed = replay([focus(true), { type: "lock.failed", attempt: 1 }])
|
||||
expect(failed.state).toEqual({ status: "unfocused", attempt: 1 })
|
||||
expect(transitionFocusLock(failed.state, focus(true)).effects).toEqual([{ type: "lock.acquire", attempt: 2 }])
|
||||
})
|
||||
|
||||
test("a stale grant is released and a stale failure is ignored", () => {
|
||||
const requesting = replay([focus(true), focus(false), focus(true)]).state
|
||||
const held = replay([{ type: "lock.acquired", attempt: 1 }], requesting).state
|
||||
const stale = transitionFocusLock(held, { type: "lock.acquired", attempt: 0 })
|
||||
expect(stale.state).toBe(held)
|
||||
expect(stale.effects).toEqual([{ type: "lock.release", attempt: 0 }])
|
||||
expect(transitionFocusLock(held, { type: "lock.failed", attempt: 0 }).state).toBe(held)
|
||||
expect(transitionFocusLock(held, focus(true)).state).toBe(held)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,76 @@
|
||||
/**
|
||||
* The shared Web Lock a focused window holds so other windows skip system notifications. `requesting` waits for the
|
||||
* grant and tracks focus meanwhile; a grant that arrives after the window lost focus is released at once.
|
||||
*/
|
||||
export type FocusLockState =
|
||||
| { readonly status: "unfocused"; readonly attempt: number }
|
||||
| { readonly status: "requesting"; readonly attempt: number; readonly focused: boolean }
|
||||
| { readonly status: "held"; readonly attempt: number }
|
||||
| { readonly status: "disposed" }
|
||||
|
||||
export type FocusLockEvent =
|
||||
| { readonly type: "focus.changed"; readonly focused: boolean }
|
||||
| { readonly type: "lock.acquired"; readonly attempt: number }
|
||||
| { readonly type: "lock.failed"; readonly attempt: number }
|
||||
| { readonly type: "disposed" }
|
||||
|
||||
export type FocusLockEffect =
|
||||
| { readonly type: "lock.acquire"; readonly attempt: number }
|
||||
| { readonly type: "lock.release"; readonly attempt: number }
|
||||
|
||||
export type FocusLockTransition = {
|
||||
readonly state: FocusLockState
|
||||
readonly effects: readonly FocusLockEffect[]
|
||||
}
|
||||
|
||||
export const INITIAL_FOCUS_LOCK_STATE: FocusLockState = Object.freeze({ status: "unfocused", attempt: 0 })
|
||||
|
||||
const DISPOSED: FocusLockState = Object.freeze({ status: "disposed" })
|
||||
|
||||
const NONE: readonly FocusLockEffect[] = []
|
||||
|
||||
export function transitionFocusLock(state: FocusLockState, event: FocusLockEvent): FocusLockTransition {
|
||||
// Every grant nobody wants is released, or the lock would be held until the window closes.
|
||||
const release: readonly FocusLockEffect[] =
|
||||
event.type === "lock.acquired" ? [{ type: "lock.release", attempt: event.attempt }] : NONE
|
||||
|
||||
if (state.status === "disposed") return { state, effects: release }
|
||||
|
||||
if (event.type === "disposed")
|
||||
return {
|
||||
state: DISPOSED,
|
||||
effects: state.status === "held" ? [{ type: "lock.release", attempt: state.attempt }] : NONE,
|
||||
}
|
||||
|
||||
if (event.type === "focus.changed") {
|
||||
if (state.status === "unfocused") {
|
||||
if (!event.focused) return unchanged(state)
|
||||
const attempt = state.attempt + 1
|
||||
|
||||
return { state: { status: "requesting", attempt, focused: true }, effects: [{ type: "lock.acquire", attempt }] }
|
||||
}
|
||||
|
||||
if (state.status === "requesting")
|
||||
return state.focused === event.focused
|
||||
? unchanged(state)
|
||||
: { state: { ...state, focused: event.focused }, effects: NONE }
|
||||
|
||||
if (event.focused) return unchanged(state)
|
||||
|
||||
return {
|
||||
state: { status: "unfocused", attempt: state.attempt },
|
||||
effects: [{ type: "lock.release", attempt: state.attempt }],
|
||||
}
|
||||
}
|
||||
|
||||
if (state.status !== "requesting" || state.attempt !== event.attempt) return { state, effects: release }
|
||||
|
||||
if (event.type === "lock.failed" || !state.focused)
|
||||
return { state: { status: "unfocused", attempt: state.attempt }, effects: release }
|
||||
|
||||
return { state: { status: "held", attempt: state.attempt }, effects: NONE }
|
||||
}
|
||||
|
||||
function unchanged(state: FocusLockState): FocusLockTransition {
|
||||
return { state, effects: NONE }
|
||||
}
|
||||
@@ -0,0 +1,105 @@
|
||||
import { describe, expect, test } from "bun:test"
|
||||
import {
|
||||
INITIAL_MOBILE_TABS_STATE,
|
||||
MOBILE_TABS_CLOSE_TIMEOUT_MS,
|
||||
selectMobileTabsOpen,
|
||||
transitionMobileTabs,
|
||||
type MobileTabsEffect,
|
||||
type MobileTabsEvent,
|
||||
type MobileTabsState,
|
||||
} from "./mobile-tabs-machine"
|
||||
|
||||
const replay = (events: MobileTabsEvent[], state = INITIAL_MOBILE_TABS_STATE) =>
|
||||
events.reduce<{ state: MobileTabsState; effects: MobileTabsEffect[] }>(
|
||||
(current, event) => {
|
||||
const next = transitionMobileTabs(current.state, event)
|
||||
|
||||
return { state: next.state, effects: [...current.effects, ...next.effects] }
|
||||
},
|
||||
{ state, effects: [] },
|
||||
)
|
||||
|
||||
const opened: MobileTabsEvent = { type: "drawer.changed", open: true }
|
||||
|
||||
const closedByDrawer: MobileTabsEvent = { type: "drawer.changed", open: false }
|
||||
|
||||
const gone: MobileTabsEvent = { type: "content.present", present: false }
|
||||
|
||||
const settings: MobileTabsEvent = { type: "settings.requested" }
|
||||
|
||||
const opensSettings = (effects: MobileTabsEffect[]) =>
|
||||
effects.filter((effect) => effect.type === "settings.open").length
|
||||
|
||||
describe("mobile tabs drawer", () => {
|
||||
test("Settings opens once the drawer has slid out", () => {
|
||||
const closing = replay([opened, settings])
|
||||
expect(closing.state).toEqual({ status: "closing-to-settings", attempt: 1 })
|
||||
expect(closing.effects).toEqual([{ type: "timer.start", attempt: 1, timeoutMs: MOBILE_TABS_CLOSE_TIMEOUT_MS }])
|
||||
expect(selectMobileTabsOpen(closing.state)).toBe(false)
|
||||
|
||||
// The drawer may report its own close while it slides out; Settings still waits for the end.
|
||||
const echoed = transitionMobileTabs(closing.state, closedByDrawer)
|
||||
expect(echoed.state).toBe(closing.state)
|
||||
|
||||
const done = transitionMobileTabs(closing.state, gone)
|
||||
expect(done.state).toEqual({ status: "closed", attempt: 1 })
|
||||
expect(done.effects).toEqual([{ type: "timer.clear" }, { type: "settings.open" }])
|
||||
})
|
||||
|
||||
test("reopening the drawer mid-close cancels Settings", () => {
|
||||
const result = replay([opened, settings, opened, closedByDrawer, gone])
|
||||
expect(result.effects).toContainEqual({ type: "timer.clear" })
|
||||
expect(opensSettings(result.effects)).toBe(0)
|
||||
expect(result.state.status).toBe("closed")
|
||||
})
|
||||
|
||||
test("picking a tab or navigating mid-close cancels Settings", () => {
|
||||
for (const cancel of [{ type: "close" }, { type: "route.changed" }] satisfies MobileTabsEvent[]) {
|
||||
const result = replay([opened, settings, cancel, gone, { type: "close.timed-out", attempt: 1 }])
|
||||
expect(result.state.status).toBe("closed")
|
||||
expect(opensSettings(result.effects)).toBe(0)
|
||||
}
|
||||
})
|
||||
|
||||
test("leaving the phone layout mid-close opens Settings at once", () => {
|
||||
const result = replay([opened, settings, { type: "viewport.changed", mobile: false }, gone])
|
||||
expect(result.state.status).toBe("closed")
|
||||
expect(opensSettings(result.effects)).toBe(1)
|
||||
})
|
||||
|
||||
test("an exit that never ends opens Settings after the timeout, once", () => {
|
||||
const result = replay([opened, settings, { type: "close.timed-out", attempt: 1 }, gone])
|
||||
expect(opensSettings(result.effects)).toBe(1)
|
||||
|
||||
// A later, unrelated close does not open Settings.
|
||||
expect(opensSettings(replay([opened, closedByDrawer, gone], result.state).effects)).toBe(0)
|
||||
})
|
||||
|
||||
test("a timeout from an earlier Settings request is ignored", () => {
|
||||
const closing = replay([opened, settings, opened, settings]).state
|
||||
expect(closing).toEqual({ status: "closing-to-settings", attempt: 2 })
|
||||
expect(transitionMobileTabs(closing, { type: "close.timed-out", attempt: 1 }).state).toBe(closing)
|
||||
})
|
||||
|
||||
test("route and viewport changes close an open drawer", () => {
|
||||
for (const event of [
|
||||
{ type: "route.changed" },
|
||||
{ type: "viewport.changed", mobile: false },
|
||||
] satisfies MobileTabsEvent[]) {
|
||||
const result = replay([opened, event])
|
||||
expect(result.state).toEqual({ status: "closed", attempt: 0 })
|
||||
expect(result.effects).toEqual([])
|
||||
}
|
||||
|
||||
const open = replay([opened]).state
|
||||
expect(transitionMobileTabs(open, { type: "viewport.changed", mobile: true }).state).toBe(open)
|
||||
expect(transitionMobileTabs(INITIAL_MOBILE_TABS_STATE, { type: "close" }).state).toBe(INITIAL_MOBILE_TABS_STATE)
|
||||
})
|
||||
|
||||
test("disposing mid-close clears the timer and ignores later events", () => {
|
||||
const result = replay([opened, settings, { type: "disposed" }])
|
||||
expect(result.effects.at(-1)).toEqual({ type: "timer.clear" })
|
||||
expect(transitionMobileTabs(result.state, gone).effects).toEqual([])
|
||||
expect(transitionMobileTabs(result.state, { type: "close.timed-out", attempt: 1 }).effects).toEqual([])
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,102 @@
|
||||
// The drawer's exit transition takes 200ms; Settings opens anyway if it never reports the end.
|
||||
export const MOBILE_TABS_CLOSE_TIMEOUT_MS = 500
|
||||
|
||||
/**
|
||||
* The phone tabs drawer. `closing-to-settings` lets the drawer slide out before Settings opens, so the two do not
|
||||
* fight over focus and history.
|
||||
*/
|
||||
export type MobileTabsState =
|
||||
| { readonly status: "closed"; readonly attempt: number }
|
||||
| { readonly status: "open"; readonly attempt: number }
|
||||
| { readonly status: "closing-to-settings"; readonly attempt: number }
|
||||
| { readonly status: "disposed" }
|
||||
|
||||
export type MobileTabsEvent =
|
||||
/** The drawer asks to open or close (trigger, swipe, outside tap, Escape). */
|
||||
| { readonly type: "drawer.changed"; readonly open: boolean }
|
||||
/** A tab, Home, New session or Help was picked. */
|
||||
| { readonly type: "close" }
|
||||
| { readonly type: "settings.requested" }
|
||||
| { readonly type: "content.present"; readonly present: boolean }
|
||||
| { readonly type: "close.timed-out"; readonly attempt: number }
|
||||
| { readonly type: "route.changed" }
|
||||
| { readonly type: "viewport.changed"; readonly mobile: boolean }
|
||||
| { readonly type: "disposed" }
|
||||
|
||||
export type MobileTabsEffect =
|
||||
| { readonly type: "timer.start"; readonly attempt: number; readonly timeoutMs: number }
|
||||
| { readonly type: "timer.clear" }
|
||||
| { readonly type: "settings.open" }
|
||||
|
||||
export type MobileTabsTransition = {
|
||||
readonly state: MobileTabsState
|
||||
readonly effects: readonly MobileTabsEffect[]
|
||||
}
|
||||
|
||||
export const INITIAL_MOBILE_TABS_STATE: MobileTabsState = Object.freeze({ status: "closed", attempt: 0 })
|
||||
|
||||
const DISPOSED: MobileTabsState = Object.freeze({ status: "disposed" })
|
||||
|
||||
const NONE: readonly MobileTabsEffect[] = []
|
||||
|
||||
const CLEAR: readonly MobileTabsEffect[] = [{ type: "timer.clear" }]
|
||||
|
||||
const OPEN_SETTINGS: readonly MobileTabsEffect[] = [{ type: "timer.clear" }, { type: "settings.open" }]
|
||||
|
||||
export function transitionMobileTabs(state: MobileTabsState, event: MobileTabsEvent): MobileTabsTransition {
|
||||
if (state.status === "disposed") return unchanged(state)
|
||||
const closing = state.status === "closing-to-settings"
|
||||
|
||||
if (event.type === "disposed") return { state: DISPOSED, effects: closing ? CLEAR : NONE }
|
||||
|
||||
if (event.type === "drawer.changed") {
|
||||
// A close the drawer reports while it slides out to Settings is the one already under way.
|
||||
if (event.open === (state.status === "open") || (closing && !event.open)) return unchanged(state)
|
||||
|
||||
return {
|
||||
state: { status: event.open ? "open" : "closed", attempt: state.attempt },
|
||||
effects: closing ? CLEAR : NONE,
|
||||
}
|
||||
}
|
||||
|
||||
if (event.type === "close" || event.type === "route.changed") {
|
||||
if (state.status === "closed") return unchanged(state)
|
||||
|
||||
return { state: { status: "closed", attempt: state.attempt }, effects: closing ? CLEAR : NONE }
|
||||
}
|
||||
|
||||
if (event.type === "settings.requested") {
|
||||
if (state.status !== "open") return unchanged(state)
|
||||
const attempt = state.attempt + 1
|
||||
|
||||
return {
|
||||
state: { status: "closing-to-settings", attempt },
|
||||
effects: [{ type: "timer.start", attempt, timeoutMs: MOBILE_TABS_CLOSE_TIMEOUT_MS }],
|
||||
}
|
||||
}
|
||||
|
||||
if (event.type === "content.present") {
|
||||
if (!closing || event.present) return unchanged(state)
|
||||
|
||||
return { state: { status: "closed", attempt: state.attempt }, effects: OPEN_SETTINGS }
|
||||
}
|
||||
|
||||
if (event.type === "close.timed-out") {
|
||||
if (!closing || event.attempt !== state.attempt) return unchanged(state)
|
||||
|
||||
return { state: { status: "closed", attempt: state.attempt }, effects: OPEN_SETTINGS }
|
||||
}
|
||||
|
||||
// Leaving the phone layout unmounts the drawer before it can report the end of its exit.
|
||||
if (event.mobile || state.status === "closed") return unchanged(state)
|
||||
|
||||
return { state: { status: "closed", attempt: state.attempt }, effects: closing ? OPEN_SETTINGS : NONE }
|
||||
}
|
||||
|
||||
export function selectMobileTabsOpen(state: MobileTabsState) {
|
||||
return state.status === "open"
|
||||
}
|
||||
|
||||
function unchanged(state: MobileTabsState): MobileTabsTransition {
|
||||
return { state, effects: NONE }
|
||||
}
|
||||
@@ -0,0 +1,132 @@
|
||||
import { describe, expect, test } from "bun:test"
|
||||
import {
|
||||
INITIAL_TAB_PREVIEW_STATE,
|
||||
selectTabPreviewFollowCard,
|
||||
selectTabPreviewInstant,
|
||||
selectTabPreviewOpenDelay,
|
||||
TAB_PREVIEW_OPEN_DELAY_MS,
|
||||
transitionTabPreview,
|
||||
type TabPreviewEffect,
|
||||
type TabPreviewEvent,
|
||||
type TabPreviewOwner,
|
||||
type TabPreviewState,
|
||||
} from "./tab-popover-machine"
|
||||
|
||||
type El = { readonly id: string }
|
||||
|
||||
const owner = (): TabPreviewOwner => ({ close: () => {} })
|
||||
|
||||
const el = (id: string): El => ({ id })
|
||||
|
||||
const replay = (events: TabPreviewEvent<El>[], state: TabPreviewState<El> = INITIAL_TAB_PREVIEW_STATE) =>
|
||||
events.reduce<{ state: TabPreviewState<El>; effects: TabPreviewEffect<El>[] }>(
|
||||
(current, event) => {
|
||||
const next = transitionTabPreview(current.state, event)
|
||||
|
||||
return { state: next.state, effects: [...current.effects, ...next.effects] }
|
||||
},
|
||||
{ state, effects: [] },
|
||||
)
|
||||
|
||||
const attach = (by: TabPreviewOwner, trigger: El, card: El, reducedMotion = false): TabPreviewEvent<El> => ({
|
||||
type: "follow.attached",
|
||||
owner: by,
|
||||
trigger,
|
||||
card,
|
||||
reducedMotion,
|
||||
})
|
||||
|
||||
describe("tab preview", () => {
|
||||
test("closing a following card stops following its row", () => {
|
||||
const a = owner()
|
||||
const row = el("row-a")
|
||||
const card = el("card-a")
|
||||
const open = replay([{ type: "preview.opened", owner: a }, attach(a, row, card)])
|
||||
expect(open.effects).toEqual([{ type: "follow.start", trigger: row, card }])
|
||||
expect(selectTabPreviewFollowCard(open.state, row)).toBe(card)
|
||||
|
||||
const closed = transitionTabPreview(open.state, { type: "preview.closed", owner: a })
|
||||
expect(closed.effects).toEqual([{ type: "follow.stop" }, { type: "warm.start", attempt: 1, delayMs: 500 }])
|
||||
// Pointer moves over the closed row no longer place a card.
|
||||
expect(selectTabPreviewFollowCard(closed.state, row)).toBeUndefined()
|
||||
})
|
||||
|
||||
test("a neighbouring tab takes over at once and closes the previous preview", () => {
|
||||
const a = owner()
|
||||
const b = owner()
|
||||
const rowA = el("row-a")
|
||||
const open = replay([{ type: "preview.opened", owner: a }, attach(a, rowA, el("card-a"))]).state
|
||||
expect(selectTabPreviewInstant(open)).toBe(false)
|
||||
expect(selectTabPreviewOpenDelay(open)).toBe(0)
|
||||
|
||||
const handoff = transitionTabPreview(open, { type: "preview.opened", owner: b })
|
||||
expect(handoff.effects).toEqual([{ type: "follow.stop" }, { type: "owner.close", owner: a }])
|
||||
expect(selectTabPreviewInstant(handoff.state)).toBe(true)
|
||||
expect(selectTabPreviewFollowCard(handoff.state, rowA)).toBeUndefined()
|
||||
|
||||
// The closed tab reports back; it no longer owns the preview.
|
||||
const stale = transitionTabPreview(handoff.state, { type: "preview.closed", owner: a })
|
||||
expect(stale.state).toBe(handoff.state)
|
||||
expect(stale.effects).toEqual([])
|
||||
// A follow from the previous card's late mount is ignored too.
|
||||
expect(transitionTabPreview(handoff.state, attach(a, rowA, el("card-a"))).state).toBe(handoff.state)
|
||||
})
|
||||
|
||||
test("the warm window skips the open delay until it expires", () => {
|
||||
const b = owner()
|
||||
const c = owner()
|
||||
|
||||
const warm = replay([
|
||||
{ type: "preview.opened", owner: b },
|
||||
{ type: "owner.disposed", owner: b },
|
||||
])
|
||||
|
||||
expect(warm.state).toEqual({ status: "warm", attempt: 1, instant: false })
|
||||
expect(selectTabPreviewOpenDelay(warm.state)).toBe(0)
|
||||
|
||||
const reopened = transitionTabPreview(warm.state, { type: "preview.opened", owner: c })
|
||||
expect(reopened.effects).toEqual([{ type: "warm.clear" }])
|
||||
expect(selectTabPreviewInstant(reopened.state)).toBe(true)
|
||||
// The first window's timer fires late.
|
||||
expect(transitionTabPreview(reopened.state, { type: "warm.expired", attempt: 1 }).state).toBe(reopened.state)
|
||||
|
||||
const rewarmed = transitionTabPreview(reopened.state, { type: "preview.closed", owner: c })
|
||||
expect(rewarmed.effects).toEqual([{ type: "warm.start", attempt: 2, delayMs: 500 }])
|
||||
expect(transitionTabPreview(rewarmed.state, { type: "warm.expired", attempt: 1 }).state).toBe(rewarmed.state)
|
||||
|
||||
const cold = transitionTabPreview(rewarmed.state, { type: "warm.expired", attempt: 2 })
|
||||
expect(cold.state.status).toBe("cold")
|
||||
expect(selectTabPreviewOpenDelay(cold.state)).toBe(TAB_PREVIEW_OPEN_DELAY_MS)
|
||||
expect(selectTabPreviewInstant(cold.state)).toBe(false)
|
||||
})
|
||||
|
||||
test("reduced motion keeps the card in place", () => {
|
||||
const a = owner()
|
||||
const row = el("row-a")
|
||||
const open = replay([{ type: "preview.opened", owner: a }, attach(a, row, el("card-a"), true)])
|
||||
expect(open.effects).toEqual([])
|
||||
expect(selectTabPreviewFollowCard(open.state, row)).toBeUndefined()
|
||||
})
|
||||
|
||||
test("the same card attaching again does not restart following", () => {
|
||||
const a = owner()
|
||||
const row = el("row-a")
|
||||
const card = el("card-a")
|
||||
const open = replay([{ type: "preview.opened", owner: a }, attach(a, row, card)]).state
|
||||
expect(transitionTabPreview(open, attach(a, row, card)).state).toBe(open)
|
||||
|
||||
const remounted = transitionTabPreview(open, attach(a, row, el("card-a2")))
|
||||
expect(remounted.effects).toEqual([
|
||||
{ type: "follow.stop" },
|
||||
{ type: "follow.start", trigger: row, card: { id: "card-a2" } },
|
||||
])
|
||||
})
|
||||
|
||||
test("closes and disposals of a tab that is not showing change nothing", () => {
|
||||
const a = owner()
|
||||
const cold = INITIAL_TAB_PREVIEW_STATE
|
||||
expect(transitionTabPreview(cold, { type: "preview.closed", owner: a }).state).toBe(cold)
|
||||
expect(transitionTabPreview(cold, { type: "owner.disposed", owner: a }).state).toBe(cold)
|
||||
expect(transitionTabPreview(cold, { type: "warm.expired", attempt: 0 }).state).toBe(cold)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,139 @@
|
||||
// Initial hover delay before the preview appears, per design.
|
||||
export const TAB_PREVIEW_OPEN_DELAY_MS = 750
|
||||
|
||||
// After a preview closes, hovering a neighbouring tab within this window skips the open delay, as the tooltip's
|
||||
// skipDelayDuration does, so moving across tabs doesn't re-wait the full delay each time.
|
||||
export const TAB_PREVIEW_SKIP_WINDOW_MS = 500
|
||||
|
||||
/** One tab's preview. `close` asks that tab to close its preview when another one takes over. */
|
||||
export type TabPreviewOwner = {
|
||||
readonly close: () => void
|
||||
}
|
||||
|
||||
/** The vertical row a card follows the pointer over, and the card itself. */
|
||||
export type TabPreviewFollow<El> = {
|
||||
readonly trigger: El
|
||||
readonly card: El
|
||||
}
|
||||
|
||||
/**
|
||||
* The one tab preview shared by every tab strip. `cold` waits the full open delay; `open` and `warm` (just closed)
|
||||
* open the next preview at once. `instant` marks a preview opened during such a streak, which shows without animating.
|
||||
*/
|
||||
export type TabPreviewState<El = HTMLElement> =
|
||||
| { readonly status: "cold"; readonly attempt: number }
|
||||
| {
|
||||
readonly status: "open"
|
||||
readonly attempt: number
|
||||
readonly owner: TabPreviewOwner
|
||||
readonly instant: boolean
|
||||
readonly follow: TabPreviewFollow<El> | undefined
|
||||
}
|
||||
| { readonly status: "warm"; readonly attempt: number; readonly instant: boolean }
|
||||
|
||||
export type TabPreviewEvent<El = HTMLElement> =
|
||||
| { readonly type: "preview.opened"; readonly owner: TabPreviewOwner }
|
||||
| { readonly type: "preview.closed"; readonly owner: TabPreviewOwner }
|
||||
| { readonly type: "owner.disposed"; readonly owner: TabPreviewOwner }
|
||||
| {
|
||||
readonly type: "follow.attached"
|
||||
readonly owner: TabPreviewOwner
|
||||
readonly trigger: El
|
||||
readonly card: El
|
||||
readonly reducedMotion: boolean
|
||||
}
|
||||
| { readonly type: "warm.expired"; readonly attempt: number }
|
||||
|
||||
export type TabPreviewEffect<El = HTMLElement> =
|
||||
| { readonly type: "owner.close"; readonly owner: TabPreviewOwner }
|
||||
| { readonly type: "follow.start"; readonly trigger: El; readonly card: El }
|
||||
| { readonly type: "follow.stop" }
|
||||
| { readonly type: "warm.start"; readonly attempt: number; readonly delayMs: number }
|
||||
| { readonly type: "warm.clear" }
|
||||
|
||||
export type TabPreviewTransition<El = HTMLElement> = {
|
||||
readonly state: TabPreviewState<El>
|
||||
readonly effects: readonly TabPreviewEffect<El>[]
|
||||
}
|
||||
|
||||
export const INITIAL_TAB_PREVIEW_STATE: TabPreviewState<never> = Object.freeze({ status: "cold", attempt: 0 })
|
||||
|
||||
const NONE: readonly never[] = []
|
||||
|
||||
const STOP: readonly TabPreviewEffect<never>[] = [{ type: "follow.stop" }]
|
||||
|
||||
export function transitionTabPreview<El>(
|
||||
state: TabPreviewState<El>,
|
||||
event: TabPreviewEvent<El>,
|
||||
): TabPreviewTransition<El> {
|
||||
if (event.type === "preview.opened") {
|
||||
if (state.status === "open" && state.owner === event.owner) return unchanged(state)
|
||||
|
||||
const next: TabPreviewState<El> = {
|
||||
status: "open",
|
||||
attempt: state.attempt,
|
||||
owner: event.owner,
|
||||
instant: state.status !== "cold",
|
||||
follow: undefined,
|
||||
}
|
||||
|
||||
if (state.status === "cold") return { state: next, effects: NONE }
|
||||
|
||||
if (state.status === "warm") return { state: next, effects: [{ type: "warm.clear" }] }
|
||||
|
||||
// Another tab's preview takes over at once and closes the one that was up.
|
||||
return { state: next, effects: [...stop(state), { type: "owner.close", owner: state.owner }] }
|
||||
}
|
||||
|
||||
if (event.type === "preview.closed" || event.type === "owner.disposed") {
|
||||
if (state.status !== "open" || state.owner !== event.owner) return unchanged(state)
|
||||
const attempt = state.attempt + 1
|
||||
|
||||
return {
|
||||
state: { status: "warm", attempt, instant: state.instant },
|
||||
effects: [...stop(state), { type: "warm.start", attempt, delayMs: TAB_PREVIEW_SKIP_WINDOW_MS }],
|
||||
}
|
||||
}
|
||||
|
||||
if (event.type === "follow.attached") {
|
||||
if (state.status !== "open" || state.owner !== event.owner) return unchanged(state)
|
||||
|
||||
if (event.reducedMotion)
|
||||
return state.follow ? { state: { ...state, follow: undefined }, effects: STOP } : unchanged(state)
|
||||
|
||||
if (state.follow?.trigger === event.trigger && state.follow.card === event.card) return unchanged(state)
|
||||
|
||||
return {
|
||||
state: { ...state, follow: { trigger: event.trigger, card: event.card } },
|
||||
effects: [...stop(state), { type: "follow.start", trigger: event.trigger, card: event.card }],
|
||||
}
|
||||
}
|
||||
|
||||
if (state.status !== "warm" || state.attempt !== event.attempt) return unchanged(state)
|
||||
|
||||
return { state: { status: "cold", attempt: state.attempt }, effects: NONE }
|
||||
}
|
||||
|
||||
/** Kobalte reads the open delay when the pointer enters a trigger, so a streak skips it. */
|
||||
export function selectTabPreviewOpenDelay(state: TabPreviewState<unknown>) {
|
||||
return state.status === "cold" ? TAB_PREVIEW_OPEN_DELAY_MS : 0
|
||||
}
|
||||
|
||||
export function selectTabPreviewInstant(state: TabPreviewState<unknown>) {
|
||||
return state.status !== "cold" && state.instant
|
||||
}
|
||||
|
||||
/** The card that follows the pointer over `trigger`, when `trigger` owns the open preview in the vertical strip. */
|
||||
export function selectTabPreviewFollowCard<El>(state: TabPreviewState<El>, trigger: El | undefined) {
|
||||
if (state.status !== "open" || state.follow === undefined || state.follow.trigger !== trigger) return
|
||||
|
||||
return state.follow.card
|
||||
}
|
||||
|
||||
function stop<El>(state: Extract<TabPreviewState<El>, { status: "open" }>): readonly TabPreviewEffect<El>[] {
|
||||
return state.follow ? STOP : NONE
|
||||
}
|
||||
|
||||
function unchanged<El>(state: TabPreviewState<El>): TabPreviewTransition<El> {
|
||||
return { state, effects: NONE }
|
||||
}
|
||||
@@ -1,27 +1,70 @@
|
||||
import { HoverCard } from "@kobalte/core/hover-card"
|
||||
import { prefersReducedMotion } from "@opencode/ui/motion"
|
||||
import { createEffect, createSignal, For, on, onCleanup, Show, type JSXElement } from "solid-js"
|
||||
import { createComputed, createSignal, For, onCleanup, Show, untrack, type JSXElement } from "solid-js"
|
||||
import { useLanguage } from "@/runtime/i18n/language"
|
||||
import { createMediaQuery } from "@solid-primitives/media"
|
||||
import {
|
||||
INITIAL_TAB_PREVIEW_STATE,
|
||||
selectTabPreviewFollowCard,
|
||||
selectTabPreviewInstant,
|
||||
selectTabPreviewOpenDelay,
|
||||
transitionTabPreview,
|
||||
type TabPreviewEffect,
|
||||
type TabPreviewEvent,
|
||||
type TabPreviewOwner,
|
||||
type TabPreviewState,
|
||||
} from "./tab-popover-machine"
|
||||
import "./tab-popover.css"
|
||||
|
||||
// Initial hover delay before the preview appears, per design.
|
||||
const OPEN_DELAY = 750
|
||||
|
||||
const CLOSE_DELAY = 0
|
||||
|
||||
// After a preview closes, hovering a neighbouring tab within this window skips
|
||||
// the open delay — mirrors the tooltip's skipDelayDuration so moving across
|
||||
// tabs doesn't re-wait the full delay each time.
|
||||
const SKIP_WINDOW = 500
|
||||
|
||||
let lastClosedAt = 0
|
||||
|
||||
let activePreview: (() => void) | undefined
|
||||
// One preview is up at a time across every tab strip, so the machine is shared.
|
||||
const [previewState, setPreviewState] = createSignal<TabPreviewState>(INITIAL_TAB_PREVIEW_STATE)
|
||||
|
||||
// In the vertical strip, the card follows the pointer's height over its row, clamped to the tabs, so moving down the
|
||||
// tabs reads as one card following the cursor.
|
||||
const follow: Follow = { pointerY: 0 }
|
||||
// tabs reads as one card following the cursor. The last pointer height over a row, and the rects the card clamps
|
||||
// against, measured once per card.
|
||||
let pointerY = 0
|
||||
|
||||
let rects: { row: DOMRect; bounds: DOMRect; card: number } | undefined
|
||||
|
||||
let measureFrame: number | undefined
|
||||
|
||||
let unwatch: (() => void) | undefined
|
||||
|
||||
let warmTimer: ReturnType<typeof setTimeout> | undefined
|
||||
|
||||
function dispatch(event: TabPreviewEvent) {
|
||||
const previous = untrack(previewState)
|
||||
const next = transitionTabPreview(previous, event)
|
||||
|
||||
if (next.state !== previous) setPreviewState(next.state)
|
||||
next.effects.forEach(run)
|
||||
}
|
||||
|
||||
function run(effect: TabPreviewEffect) {
|
||||
if (effect.type === "owner.close") return effect.owner.close()
|
||||
|
||||
if (effect.type === "follow.start") return follow(effect.trigger, effect.card)
|
||||
|
||||
if (effect.type === "follow.stop") {
|
||||
unwatch?.()
|
||||
unwatch = undefined
|
||||
|
||||
if (measureFrame !== undefined) cancelAnimationFrame(measureFrame)
|
||||
measureFrame = undefined
|
||||
rects = undefined
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
clearTimeout(warmTimer)
|
||||
warmTimer = undefined
|
||||
|
||||
if (effect.type === "warm.clear") return
|
||||
const attempt = effect.attempt
|
||||
warmTimer = setTimeout(() => dispatch({ type: "warm.expired", attempt }), effect.delayMs)
|
||||
}
|
||||
|
||||
export interface TabPreviewData {
|
||||
projectName?: string
|
||||
@@ -40,57 +83,16 @@ export function TabPreviewPopover(props: {
|
||||
const language = useLanguage()
|
||||
const mobile = createMediaQuery("(max-width: 767px)")
|
||||
let triggerEl: HTMLDivElement | undefined
|
||||
// When opened during a rapid tab-hopping streak, this preview appears and
|
||||
// disappears instantly (no repeated enter/exit animation) — only the first,
|
||||
// "cold" preview animates. Mirrors how browsers reuse one tab tooltip.
|
||||
const [instant, setInstant] = createSignal(false)
|
||||
|
||||
const warm = () => !!activePreview || Date.now() - lastClosedAt < SKIP_WINDOW
|
||||
const owner: TabPreviewOwner = { close: () => props.onOpenChange(false) }
|
||||
const open = () => props.open && !mobile()
|
||||
const close = () => props.onOpenChange(false)
|
||||
|
||||
// Observe accepted, controlled state, including drag/menu suppression in TabNav.
|
||||
createEffect(() => {
|
||||
if (open()) {
|
||||
if (activePreview !== close) activePreview?.()
|
||||
activePreview = close
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
if (activePreview !== close) return
|
||||
activePreview = undefined
|
||||
lastClosedAt = Date.now()
|
||||
// Observe accepted, controlled state, including drag/menu suppression in TabNav. A computed commits the preview
|
||||
// before Kobalte mounts the card, so the card's ref and `data-instant` already see it.
|
||||
createComputed(() => {
|
||||
const type = open() ? "preview.opened" : "preview.closed"
|
||||
untrack(() => dispatch({ type, owner }))
|
||||
})
|
||||
createEffect(
|
||||
on(
|
||||
open,
|
||||
(now, before) => {
|
||||
if (!before || now || !triggerEl || triggerEl !== follow.trigger) return
|
||||
unwatch()
|
||||
follow.card = undefined
|
||||
},
|
||||
{ defer: true },
|
||||
),
|
||||
)
|
||||
onCleanup(() => {
|
||||
if (follow.trigger === triggerEl) {
|
||||
unwatch()
|
||||
Object.assign(follow, { trigger: undefined, card: undefined })
|
||||
}
|
||||
|
||||
if (activePreview !== close) return
|
||||
activePreview = undefined
|
||||
lastClosedAt = Date.now()
|
||||
})
|
||||
// Kobalte reads openDelay lazily when the pointer enters the trigger, so this
|
||||
// resolves the skip window per-hover.
|
||||
const resolveOpenDelay = () => (warm() ? 0 : OPEN_DELAY)
|
||||
|
||||
const handleOpenChange = (open: boolean) => {
|
||||
if (open) setInstant(warm())
|
||||
props.onOpenChange(open)
|
||||
}
|
||||
onCleanup(() => dispatch({ type: "owner.disposed", owner }))
|
||||
|
||||
// Kept out of JSX: an inline nested ternary compiles to a memo created on every read, and Kobalte reads
|
||||
// placement from a ResizeObserver callback, where that memo has no owner and is never disposed.
|
||||
@@ -100,8 +102,9 @@ export function TabPreviewPopover(props: {
|
||||
return (
|
||||
<HoverCard
|
||||
open={open()}
|
||||
onOpenChange={handleOpenChange}
|
||||
openDelay={resolveOpenDelay()}
|
||||
onOpenChange={props.onOpenChange}
|
||||
// Kobalte reads openDelay when the pointer enters the trigger, so a streak skips it per hover.
|
||||
openDelay={selectTabPreviewOpenDelay(previewState())}
|
||||
closeDelay={CLOSE_DELAY}
|
||||
// Informational previews belong to their tab, not to a hoverable safe area.
|
||||
ignoreSafeArea
|
||||
@@ -114,9 +117,10 @@ export function TabPreviewPopover(props: {
|
||||
data-component="session-tab-popover-trigger"
|
||||
tabIndex={-1}
|
||||
onPointerMove={(event: PointerEvent) => {
|
||||
follow.pointerY = event.clientY
|
||||
pointerY = event.clientY
|
||||
const card = selectTabPreviewFollowCard(previewState(), triggerEl)
|
||||
|
||||
if (props.orientation === "vertical" && triggerEl === follow.trigger) place()
|
||||
if (card && triggerEl) place(triggerEl, card)
|
||||
}}
|
||||
>
|
||||
{props.trigger}
|
||||
@@ -130,10 +134,19 @@ export function TabPreviewPopover(props: {
|
||||
|
||||
if (theme) el.setAttribute("data-theme", theme)
|
||||
|
||||
if (triggerEl && props.orientation === "vertical") show(el, triggerEl)
|
||||
if (triggerEl && props.orientation === "vertical")
|
||||
dispatch({
|
||||
type: "follow.attached",
|
||||
owner,
|
||||
trigger: triggerEl,
|
||||
card: el,
|
||||
reducedMotion: prefersReducedMotion(),
|
||||
})
|
||||
}}
|
||||
data-component="session-tab-popover"
|
||||
data-instant={instant() || undefined}
|
||||
// During a rapid tab-hopping streak the preview appears and disappears without animating; only the first,
|
||||
// cold preview animates, as browsers reuse one tab tooltip.
|
||||
data-instant={selectTabPreviewInstant(previewState()) || undefined}
|
||||
>
|
||||
<div data-slot="header">
|
||||
<Show when={props.data.projectName}>
|
||||
@@ -171,78 +184,59 @@ export function TabPreviewPopover(props: {
|
||||
)
|
||||
}
|
||||
|
||||
function show(card: HTMLElement, trigger: HTMLElement) {
|
||||
Object.assign(follow, { card, trigger, rects: undefined })
|
||||
unwatch()
|
||||
|
||||
if (prefersReducedMotion()) return
|
||||
watch(trigger)
|
||||
place()
|
||||
function follow(trigger: HTMLElement, card: HTMLElement) {
|
||||
rects = undefined
|
||||
watch(trigger, card)
|
||||
place(trigger, card)
|
||||
|
||||
// The card has no height while it mounts, so clamp again once it's laid out.
|
||||
if (!follow.rects) requestAnimationFrame(place)
|
||||
if (rects) return
|
||||
measureFrame = requestAnimationFrame(() => {
|
||||
measureFrame = undefined
|
||||
place(trigger, card)
|
||||
})
|
||||
}
|
||||
|
||||
// Moves the card straight to the pointer, with no spring.
|
||||
function place() {
|
||||
const card = follow.card
|
||||
|
||||
if (!card?.isConnected || prefersReducedMotion()) return
|
||||
card.style.transform = `translateY(${cursorOffset()}px)`
|
||||
function place(trigger: HTMLElement, card: HTMLElement) {
|
||||
if (!card.isConnected || prefersReducedMotion()) return
|
||||
card.style.transform = `translateY(${cursorOffset(trigger, card)}px)`
|
||||
}
|
||||
|
||||
// Keeps the pointer level with the middle of the row-sized slot the card would sit in by default, so the offset is 0
|
||||
// at the row's centre and runs continuously across row boundaries, clamped to the sidebar.
|
||||
function cursorOffset() {
|
||||
const rects = follow.rects ?? measure()
|
||||
|
||||
if (!rects) return 0
|
||||
function cursorOffset(trigger: HTMLElement, card: HTMLElement) {
|
||||
const measured = rects ?? measure(trigger, card)
|
||||
|
||||
// The card has no height until it's attached, so a measurement taken as it mounts isn't kept.
|
||||
if (rects.card > 0) follow.rects = rects
|
||||
const top = follow.pointerY - rects.row.height / 2
|
||||
const clamped = Math.min(Math.max(top, rects.bounds.top), rects.bounds.bottom - rects.card)
|
||||
if (measured.card > 0) rects = measured
|
||||
const top = pointerY - measured.row.height / 2
|
||||
const clamped = Math.min(Math.max(top, measured.bounds.top), measured.bounds.bottom - measured.card)
|
||||
|
||||
return clamped - rects.row.top
|
||||
return clamped - measured.row.top
|
||||
}
|
||||
|
||||
function measure() {
|
||||
if (!follow.trigger || !follow.card) return
|
||||
const bounds = (follow.trigger.closest('[data-slot="vertical-tabs"]') ?? follow.trigger).getBoundingClientRect()
|
||||
function measure(trigger: HTMLElement, card: HTMLElement) {
|
||||
const bounds = (trigger.closest('[data-slot="vertical-tabs"]') ?? trigger).getBoundingClientRect()
|
||||
|
||||
return { row: follow.trigger.getBoundingClientRect(), bounds, card: follow.card.offsetHeight }
|
||||
return { row: trigger.getBoundingClientRect(), bounds, card: card.offsetHeight }
|
||||
}
|
||||
|
||||
// While a card is up, scrolling or resizing the tabs moves the rows under the cached rects, so measure again and
|
||||
// re-clamp the card even if the pointer stays still.
|
||||
function watch(trigger: HTMLElement) {
|
||||
function watch(trigger: HTMLElement, card: HTMLElement) {
|
||||
const refresh = () => {
|
||||
follow.rects = undefined
|
||||
place()
|
||||
rects = undefined
|
||||
place(trigger, card)
|
||||
}
|
||||
|
||||
const observer = new ResizeObserver(refresh)
|
||||
observer.observe(trigger.closest('[data-slot="vertical-tabs"]') ?? trigger)
|
||||
window.addEventListener("scroll", refresh, { capture: true, passive: true })
|
||||
window.addEventListener("resize", refresh, { passive: true })
|
||||
follow.unwatch = () => {
|
||||
unwatch = () => {
|
||||
observer.disconnect()
|
||||
window.removeEventListener("scroll", refresh, { capture: true })
|
||||
window.removeEventListener("resize", refresh)
|
||||
}
|
||||
}
|
||||
|
||||
function unwatch() {
|
||||
follow.unwatch?.()
|
||||
follow.unwatch = undefined
|
||||
}
|
||||
|
||||
type Follow = {
|
||||
// The row whose preview is up, or closed last.
|
||||
trigger?: HTMLElement
|
||||
card?: HTMLElement
|
||||
// The last pointer height over a row, and the rects the card clamps against, measured once per card.
|
||||
pointerY: number
|
||||
rects?: { row: DOMRect; bounds: DOMRect; card: number }
|
||||
unwatch?: () => void
|
||||
}
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
import { createEffect, createMemo, Match, onCleanup, Show, Switch } from "solid-js"
|
||||
import { createStore } from "solid-js/store"
|
||||
import { createEffect, createMemo, createSignal, Match, on, onCleanup, Show, Switch, untrack } from "solid-js"
|
||||
import { Portal } from "solid-js/web"
|
||||
import { useLocation } from "@solidjs/router"
|
||||
import { uuid } from "@opencode/util/uuid"
|
||||
@@ -37,6 +36,12 @@ import { RecentlyClosedTabsMenu } from "./recently-closed-tabs-menu"
|
||||
import { useSettingsDialog } from "@/settings/command"
|
||||
import { TitlebarItems, useTitlebarItems } from "@/runtime/plugin/titlebar-items"
|
||||
import { createRouteTabSync } from "./route-sync"
|
||||
import {
|
||||
INITIAL_MOBILE_TABS_STATE,
|
||||
selectMobileTabsOpen,
|
||||
transitionMobileTabs,
|
||||
type MobileTabsEvent,
|
||||
} from "./mobile-tabs-machine"
|
||||
|
||||
export const newTabCommand = { id: "tab.new", keybind: "mod+t,mod+n" }
|
||||
|
||||
@@ -486,7 +491,29 @@ export function Titlebar(props: { verticalTabs?: { mount?: HTMLElement } }) {
|
||||
},
|
||||
])
|
||||
|
||||
const [mobileTabs, setMobileTabs] = createStore({ open: false, settings: false })
|
||||
const [mobileTabsState, setMobileTabsState] = createSignal(INITIAL_MOBILE_TABS_STATE)
|
||||
let closeTimer: ReturnType<typeof setTimeout> | undefined
|
||||
|
||||
const dispatchMobileTabs = (event: MobileTabsEvent) => {
|
||||
const previous = untrack(mobileTabsState)
|
||||
const next = transitionMobileTabs(previous, event)
|
||||
|
||||
if (next.state !== previous) setMobileTabsState(next.state)
|
||||
next.effects.forEach((effect) => {
|
||||
if (effect.type === "settings.open") return openSettings()
|
||||
clearTimeout(closeTimer)
|
||||
closeTimer = undefined
|
||||
|
||||
if (effect.type === "timer.clear") return
|
||||
const attempt = effect.attempt
|
||||
closeTimer = setTimeout(
|
||||
() => dispatchMobileTabs({ type: "close.timed-out", attempt }),
|
||||
effect.timeoutMs,
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
const closeMobileTabs = () => dispatchMobileTabs({ type: "close" })
|
||||
|
||||
// The current tab's project avatar stays put; while it works, its activity ring shows beside the tab count.
|
||||
const currentStatus = useSessionTabAvatarState(
|
||||
@@ -518,11 +545,11 @@ export function Titlebar(props: { verticalTabs?: { mount?: HTMLElement } }) {
|
||||
)
|
||||
}
|
||||
|
||||
createEffect(() => {
|
||||
path()
|
||||
mobile()
|
||||
setMobileTabs("open", false)
|
||||
})
|
||||
createEffect(on(path, () => dispatchMobileTabs({ type: "route.changed" }), { defer: true }))
|
||||
createEffect(
|
||||
on(mobile, (value) => dispatchMobileTabs({ type: "viewport.changed", mobile: value }), { defer: true }),
|
||||
)
|
||||
onCleanup(() => dispatchMobileTabs({ type: "disposed" }))
|
||||
|
||||
return (
|
||||
<div
|
||||
@@ -555,13 +582,9 @@ export function Titlebar(props: { verticalTabs?: { mount?: HTMLElement } }) {
|
||||
when={!mobile()}
|
||||
fallback={
|
||||
<MobileDrawer
|
||||
open={mobileTabs.open}
|
||||
onOpenChange={(open) => setMobileTabs("open", open)}
|
||||
onContentPresentChange={(present) => {
|
||||
if (present || !mobileTabs.settings) return
|
||||
setMobileTabs("settings", false)
|
||||
openSettings()
|
||||
}}
|
||||
open={selectMobileTabsOpen(mobileTabsState())}
|
||||
onOpenChange={(open) => dispatchMobileTabs({ type: "drawer.changed", open })}
|
||||
onContentPresentChange={(present) => dispatchMobileTabs({ type: "content.present", present })}
|
||||
>
|
||||
<MobileDrawerTrigger
|
||||
data-slot="mobile-tabs-trigger"
|
||||
@@ -616,7 +639,7 @@ export function Titlebar(props: { verticalTabs?: { mount?: HTMLElement } }) {
|
||||
currentTab={currentTab()}
|
||||
onNavigate={(tab) => {
|
||||
tabs.select(tab)
|
||||
setMobileTabs("open", false)
|
||||
closeMobileTabs()
|
||||
}}
|
||||
onClose={(tab) => {
|
||||
const index = tabsStore.findIndex((item) => tabKey(item) === tabKey(tab))
|
||||
@@ -633,7 +656,7 @@ export function Titlebar(props: { verticalTabs?: { mount?: HTMLElement } }) {
|
||||
class="flex h-7 w-full shrink-0 items-center gap-2 rounded-[6px] px-2 text-[13px] leading-4 text-v2-text-text-base hover:bg-v2-background-bg-layer-02 focus-visible:outline-none focus-visible:bg-v2-background-bg-layer-02"
|
||||
onClick={() => {
|
||||
openNewTab()
|
||||
setMobileTabs("open", false)
|
||||
closeMobileTabs()
|
||||
}}
|
||||
>
|
||||
<Icon name="plus" />
|
||||
@@ -648,7 +671,7 @@ export function Titlebar(props: { verticalTabs?: { mount?: HTMLElement } }) {
|
||||
class="flex h-7 w-full items-center gap-2 rounded-[6px] px-2 text-[13px] leading-4 text-v2-text-text-faint data-[state=pressed]:text-v2-text-text-base focus-visible:outline-none"
|
||||
onClick={() => {
|
||||
if (layout.route().type !== "home") toggleHome()
|
||||
setMobileTabs("open", false)
|
||||
closeMobileTabs()
|
||||
}}
|
||||
>
|
||||
<Icon name="grid-plus" />
|
||||
@@ -659,7 +682,7 @@ export function Titlebar(props: { verticalTabs?: { mount?: HTMLElement } }) {
|
||||
type="button"
|
||||
data-action="mobile-tabs-settings"
|
||||
class="flex h-7 min-w-0 flex-1 items-center gap-2 rounded-[6px] px-2 text-[13px] leading-4 text-v2-text-text-faint hover:bg-v2-background-bg-layer-02 focus-visible:outline-none focus-visible:bg-v2-background-bg-layer-02"
|
||||
onClick={() => setMobileTabs({ open: false, settings: true })}
|
||||
onClick={() => dispatchMobileTabs({ type: "settings.requested" })}
|
||||
>
|
||||
<Icon name="settings-gear" size="small" />
|
||||
{language.t("sidebar.settings")}
|
||||
@@ -669,7 +692,7 @@ export function Titlebar(props: { verticalTabs?: { mount?: HTMLElement } }) {
|
||||
data-action="mobile-tabs-help"
|
||||
class="flex h-7 shrink-0 items-center gap-2 rounded-[6px] px-2 text-[13px] leading-4 text-v2-text-text-faint hover:bg-v2-background-bg-layer-02 focus-visible:outline-none focus-visible:bg-v2-background-bg-layer-02"
|
||||
onClick={() => {
|
||||
setMobileTabs("open", false)
|
||||
closeMobileTabs()
|
||||
platform.openExternal("https://opencode.ai/desktop-feedback")
|
||||
}}
|
||||
>
|
||||
|
||||
Reference in New Issue
Block a user