mirror of
https://github.com/anomalyco/opencode.git
synced 2026-11-21 04:12:08 +03:00
fix(ui): drive the dialog stack through one state machine (#61903)
This commit is contained in:
committed by
GitHub
Unverified
parent
c579f9ab7c
commit
5eeb906b27
@@ -1,5 +1,5 @@
|
||||
import type { PluginInfo, SessionMessageInfo } from "@opencode/client/promise"
|
||||
import { DialogProvider } from "@opencode/ui/context/dialog"
|
||||
import { DialogProvider, useDialog } from "@opencode/ui/context/dialog"
|
||||
import { Menu } from "@opencode/ui/menu"
|
||||
import { Toast } from "@opencode/ui/toast"
|
||||
import {
|
||||
@@ -82,7 +82,7 @@ type Captured = { apis?: ReturnType<typeof createHostApis> }
|
||||
/** A value the fixture's storage holds as JSON. */
|
||||
type Json = string | number | boolean | null | readonly Json[] | { readonly [key: string]: Json }
|
||||
|
||||
export { createComponent, createMemo, createRoot, createSignal, getOwner, onCleanup, runWithOwner }
|
||||
export { createComponent, createMemo, createRoot, createSignal, getOwner, onCleanup, runWithOwner, useDialog }
|
||||
|
||||
const layout: BuiltinLayout = {
|
||||
narrow: () => false,
|
||||
|
||||
@@ -179,6 +179,66 @@ story("a dialog handle closes its own dialog, and a dialog closes with the scope
|
||||
})
|
||||
})
|
||||
|
||||
story("Escape closes the top dialog while a dialog below it plays its exit animation", async ({ page }) => {
|
||||
const result = await page.evaluate(async (fixture) => {
|
||||
const { mountPluginHost, until } = await import(fixture)
|
||||
const host = mountPluginHost()
|
||||
const text = (value: string) => () => Object.assign(document.createElement("p"), { textContent: value })
|
||||
const shown = () => ["below", "middle", "top"].filter((value) => document.body.textContent?.includes(value))
|
||||
const handles: DialogHandle[] = []
|
||||
host.load((ctx: Context) => {
|
||||
handles.push(ctx.dialogs.open(text("below")), ctx.dialogs.open(text("middle")), ctx.dialogs.open(text("top")))
|
||||
}, 0)
|
||||
await until(() => shown().length === 3)
|
||||
handles[1]?.close()
|
||||
// In the same tick, so the middle dialog is still playing its exit animation.
|
||||
document.dispatchEvent(new KeyboardEvent("keydown", { key: "Escape", bubbles: true }))
|
||||
await until(() => shown().length === 1)
|
||||
const outcome = shown()
|
||||
host.unmount()
|
||||
|
||||
return outcome
|
||||
}, fixture)
|
||||
|
||||
expect(result).toEqual(["below"])
|
||||
})
|
||||
|
||||
story("a dialog closes itself while the dialog above it exits, and a double close never reaches below", async ({
|
||||
page,
|
||||
}) => {
|
||||
const result = await page.evaluate(async (fixture) => {
|
||||
const { mountPluginHost, until, useDialog } = await import(fixture)
|
||||
const host = mountPluginHost()
|
||||
const shown = () => ["base", "middle", "top"].filter((value) => document.body.textContent?.includes(value))
|
||||
const own = { close: () => {} }
|
||||
host.load((ctx: Context) => {
|
||||
ctx.dialogs.open(() => Object.assign(document.createElement("p"), { textContent: "base" }))
|
||||
// A Cancel button inside the middle dialog: a plain close() from its own layer.
|
||||
ctx.dialogs.open(() => {
|
||||
const dialog = useDialog()
|
||||
own.close = () => dialog.close()
|
||||
|
||||
return Object.assign(document.createElement("p"), { textContent: "middle" })
|
||||
})
|
||||
ctx.dialogs.open(() => Object.assign(document.createElement("p"), { textContent: "top" }))
|
||||
}, 0)
|
||||
await until(() => shown().length === 3)
|
||||
document.dispatchEvent(new KeyboardEvent("keydown", { key: "Escape", bubbles: true }))
|
||||
// In the same tick, while the top dialog is still playing its exit animation; twice, as a double click would.
|
||||
own.close()
|
||||
own.close()
|
||||
await until(() => shown().length === 1)
|
||||
// Past every exit animation, so a close that reached the base dialog would have removed it by now.
|
||||
await new Promise((resolve) => setTimeout(resolve, 300))
|
||||
const outcome = shown()
|
||||
host.unmount()
|
||||
|
||||
return outcome
|
||||
}, fixture)
|
||||
|
||||
expect(result).toEqual(["base"])
|
||||
})
|
||||
|
||||
story("a dialog pushed in the same tick as a reload never mounts", async ({ page }) => {
|
||||
const shown = await page.evaluate(async (fixture) => {
|
||||
const { mountPluginHost } = await import(fixture)
|
||||
|
||||
@@ -25,6 +25,8 @@ export type ServerConnectControllerOptions =
|
||||
readonly removeTabs: (key: ServerConnection.Key) => void
|
||||
/** Closes the dialog. `saved` is the server a successful save stored. */
|
||||
readonly onClose: (saved: ServerConnection.Http | undefined) => void
|
||||
/** True once the dialog starts closing, so a check that finishes during its exit animation saves nothing. */
|
||||
readonly closing?: Accessor<boolean>
|
||||
}
|
||||
|
||||
export function createServerConnectController(options: ServerConnectControllerOptions) {
|
||||
@@ -144,6 +146,13 @@ export function createServerConnectController(options: ServerConnectControllerOp
|
||||
if (options.surface === "dialog" && options.original)
|
||||
createEffect(on(options.original, (original) => dispatch({ type: "original.synced", original })))
|
||||
|
||||
if (options.surface === "dialog" && options.closing) {
|
||||
const closing = options.closing
|
||||
createEffect(() => {
|
||||
if (closing()) dispatch({ type: "disposed" })
|
||||
})
|
||||
}
|
||||
|
||||
onCleanup(() => dispatch({ type: "disposed" }))
|
||||
|
||||
const view = createMemo(() =>
|
||||
|
||||
@@ -53,6 +53,7 @@ export const DialogServer: Component<{
|
||||
target: edited ? { kind: "edit", original: untrack(original) ?? originalOf(edited) } : { kind: "add" },
|
||||
original,
|
||||
removeTabs: (key) => tabs.removeServer(key),
|
||||
closing: () => dialog.closing,
|
||||
// Close first: onSave may open the next dialog, such as the folder picker an interrupted action continues with.
|
||||
onClose: (saved) => {
|
||||
dialog.close()
|
||||
|
||||
@@ -0,0 +1,295 @@
|
||||
import { describe, expect, test } from "bun:test"
|
||||
import {
|
||||
createDialogStackState,
|
||||
selectLayerClosing,
|
||||
selectLayerIndex,
|
||||
selectLayerModal,
|
||||
selectTopDialog,
|
||||
transitionDialogStack,
|
||||
type DialogStackEffect,
|
||||
type DialogStackEvent,
|
||||
type DialogStackState,
|
||||
} from "./dialog-machine"
|
||||
|
||||
type Event = DialogStackEvent<string, string>
|
||||
|
||||
// Focus is where it was when the open was asked for; the request names the content the driver would mount.
|
||||
const open = (mode: "show" | "push", id: string, aborted = false): Event => ({
|
||||
type: "open",
|
||||
mode,
|
||||
id,
|
||||
aborted,
|
||||
focus: `before ${id}`,
|
||||
request: id,
|
||||
})
|
||||
|
||||
const push = (id: string) => open("push", id)
|
||||
|
||||
const show = (id: string) => open("show", id)
|
||||
|
||||
function run(state: DialogStackState<string>, ...events: Event[]) {
|
||||
return events.reduce<{ state: DialogStackState<string>; effects: readonly DialogStackEffect<string, string>[] }>(
|
||||
(result, event) => transitionDialogStack(result.state, event),
|
||||
{ state, effects: [] },
|
||||
)
|
||||
}
|
||||
|
||||
function closed(attempt: number, delayMs: number, focus?: string): DialogStackEffect<string, string>[] {
|
||||
return [
|
||||
{ type: "timer.start", attempt, delayMs },
|
||||
{ type: "notify.close", attempt },
|
||||
...(focus ? [{ type: "focus.return" as const, attempt, focus }] : []),
|
||||
]
|
||||
}
|
||||
|
||||
const statuses = (state: DialogStackState<string>) =>
|
||||
state.status === "active" ? state.entries.map((entry) => `${entry.id}:${entry.status}`) : []
|
||||
|
||||
describe("closing a lower dialog by id", () => {
|
||||
// A at the bottom plays the image preview's 960 ms flight out; B on top must close at once, however it is closed.
|
||||
const below = run(
|
||||
createDialogStackState(),
|
||||
push("a"),
|
||||
{ type: "layer.exit-duration", attempt: 1, exitMs: 960 },
|
||||
push("b"),
|
||||
{ type: "close", id: "a" },
|
||||
)
|
||||
|
||||
test("starts only that dialog's exit and leaves focus with the top dialog", () => {
|
||||
expect(below.effects).toEqual(closed(1, 960))
|
||||
expect(statuses(below.state)).toEqual(["a:closing", "b:open"])
|
||||
expect(selectTopDialog(below.state)?.id).toBe("b")
|
||||
})
|
||||
|
||||
test.each<[string, Event]>([
|
||||
["Escape", { type: "dismiss" }],
|
||||
["a backdrop click", { type: "backdrop.click", attempt: 2 }],
|
||||
["its close button", { type: "layer.dismiss", attempt: 2 }],
|
||||
["an un-keyed close", { type: "close" }],
|
||||
["a dismissal by id", { type: "dismiss", id: "b" }],
|
||||
])("does not block %s on the top dialog", (_, event) => {
|
||||
const next = transitionDialogStack(below.state, event)
|
||||
|
||||
expect(next.effects).toEqual(closed(2, 100, "before b"))
|
||||
expect(statuses(next.state)).toEqual(["a:closing", "b:closing"])
|
||||
})
|
||||
})
|
||||
|
||||
describe("while the top dialog plays its exit animation", () => {
|
||||
const exiting = run(createDialogStackState(), push("a"), push("b"), { type: "dismiss" })
|
||||
|
||||
test("the dialog below is the top dialog and owns the focus trap", () => {
|
||||
expect(selectTopDialog(exiting.state)?.id).toBe("a")
|
||||
expect(selectLayerModal(exiting.state, 1, false)).toBe(true)
|
||||
expect(selectLayerModal(exiting.state, 2, false)).toBe(false)
|
||||
expect(selectLayerModal(exiting.state, 1, true)).toBe(false)
|
||||
})
|
||||
|
||||
test.each<[string, Event]>([
|
||||
["its close button", { type: "layer.dismiss", attempt: 2 }],
|
||||
["its backdrop", { type: "backdrop.click", attempt: 2 }],
|
||||
["a dismissal by its id", { type: "dismiss", id: "b" }],
|
||||
["a second un-keyed close", { type: "close" }],
|
||||
["a second close from inside it", { type: "close", layer: 2 }],
|
||||
])("%s does nothing more", (_, event) => {
|
||||
const next = transitionDialogStack(exiting.state, event)
|
||||
|
||||
expect(next.state).toBe(exiting.state)
|
||||
expect(next.effects).toEqual([])
|
||||
})
|
||||
|
||||
test.each<[string, Event]>([
|
||||
["Escape", { type: "dismiss" }],
|
||||
["a dismissal by its id", { type: "dismiss", id: "a" }],
|
||||
["its close button", { type: "layer.dismiss", attempt: 1 }],
|
||||
["its backdrop", { type: "backdrop.click", attempt: 1 }],
|
||||
["a close by its id", { type: "close", id: "a" }],
|
||||
["its own Cancel (a close from inside it)", { type: "close", layer: 1 }],
|
||||
])("%s closes the dialog below at once", (_, event) => {
|
||||
const next = transitionDialogStack(exiting.state, event)
|
||||
|
||||
expect(next.effects).toEqual(closed(1, 100, "before a"))
|
||||
expect(statuses(next.state)).toEqual(["a:closing", "b:closing"])
|
||||
})
|
||||
|
||||
test("an un-keyed close from outside every dialog waits for the exit, then closes the dialog below", () => {
|
||||
const next = run(exiting.state, { type: "exit.completed", attempt: 2 }, { type: "close" })
|
||||
|
||||
expect(next.effects).toEqual(closed(1, 100, "before a"))
|
||||
})
|
||||
})
|
||||
|
||||
describe("a close without an id from inside a dialog", () => {
|
||||
const stacked = run(createDialogStackState(), push("a"), push("b"))
|
||||
|
||||
test("closes that dialog, not the one on top, and leaves focus with the top dialog", () => {
|
||||
const next = transitionDialogStack(stacked.state, { type: "close", layer: 1 })
|
||||
|
||||
expect(next.effects).toEqual(closed(1, 100))
|
||||
expect(statuses(next.state)).toEqual(["a:closing", "b:open"])
|
||||
})
|
||||
|
||||
test("closes only itself on a double click, never the dialog below", () => {
|
||||
const first = transitionDialogStack(stacked.state, { type: "close", layer: 2 })
|
||||
const second = transitionDialogStack(first.state, { type: "close", layer: 2 })
|
||||
|
||||
expect(first.effects).toEqual(closed(2, 100, "before b"))
|
||||
expect(second.state).toBe(first.state)
|
||||
expect(second.effects).toEqual([])
|
||||
})
|
||||
|
||||
test("from a dialog a show replaced, closes the replacement, along a chain of replacements", () => {
|
||||
const replaced = run(stacked.state, show("c"))
|
||||
|
||||
expect(transitionDialogStack(replaced.state, { type: "close", layer: 1 }).effects).toEqual(closed(3, 100, "before a"))
|
||||
|
||||
const again = run(replaced.state, show("d"))
|
||||
|
||||
expect(transitionDialogStack(again.state, { type: "close", layer: 1 }).effects).toEqual(closed(4, 100, "before a"))
|
||||
expect(transitionDialogStack(again.state, { type: "close", layer: 3 }).effects).toEqual(closed(4, 100, "before a"))
|
||||
})
|
||||
|
||||
test.each<[string, Event[]]>([
|
||||
// Escape closed it, its exit ended, and another dialog opened before its async work called close().
|
||||
["closed and gone", [push("a"), { type: "dismiss" }, { type: "exit.completed", attempt: 1 }, push("b")]],
|
||||
["closed, then torn down by a show", [push("a"), push("x"), { type: "close", id: "a" }, show("b")]],
|
||||
])("from a dialog already %s, closes nothing", (_, events) => {
|
||||
const before = run(createDialogStackState(), ...events)
|
||||
const next = transitionDialogStack(before.state, { type: "close", layer: 1 })
|
||||
|
||||
expect(next.state).toBe(before.state)
|
||||
expect(next.effects).toEqual([])
|
||||
})
|
||||
})
|
||||
|
||||
test("a layer reads closing as soon as its close starts, before its exit animation ends", () => {
|
||||
const opened = run(createDialogStackState(), push("a"))
|
||||
const closing = run(opened.state, { type: "dismiss" })
|
||||
|
||||
expect(selectLayerClosing(opened.state, 1)).toBe(false)
|
||||
expect(selectLayerClosing(closing.state, 1)).toBe(true)
|
||||
// Escape stops being captured, though the dialog stays mounted for its exit animation.
|
||||
expect(selectTopDialog(closing.state)).toBeUndefined()
|
||||
expect(statuses(closing.state)).toEqual(["a:closing"])
|
||||
|
||||
const gone = run(closing.state, { type: "exit.completed", attempt: 1 })
|
||||
|
||||
expect(gone.effects).toEqual([{ type: "dispose", attempt: 1, notify: false }])
|
||||
expect(statuses(gone.state)).toEqual([])
|
||||
})
|
||||
|
||||
test("an id reused while its earlier dialog exits names only the new dialog", () => {
|
||||
const reused = run(createDialogStackState(), push("x"), { type: "close", id: "x" }, push("x"))
|
||||
|
||||
expect(selectTopDialog(reused.state)?.attempt).toBe(2)
|
||||
expect(selectLayerClosing(reused.state, 1)).toBe(true)
|
||||
expect(selectLayerClosing(reused.state, 2)).toBe(false)
|
||||
|
||||
const exited = run(reused.state, { type: "exit.completed", attempt: 1 })
|
||||
|
||||
expect(exited.effects).toEqual([{ type: "dispose", attempt: 1, notify: false }])
|
||||
expect(statuses(exited.state)).toEqual(["x:open"])
|
||||
expect(selectLayerIndex(exited.state, 2)).toBe(0)
|
||||
expect(run(exited.state, { type: "close", id: "x" }).effects).toEqual(closed(2, 100, "before x"))
|
||||
})
|
||||
|
||||
describe("a dialog that opts out of backdrop dismissal", () => {
|
||||
const kept = run(createDialogStackState(), push("a"), { type: "layer.backdrop-dismiss", attempt: 1, enabled: false })
|
||||
|
||||
test("stays open on a backdrop click", () => {
|
||||
const next = transitionDialogStack(kept.state, { type: "backdrop.click", attempt: 1 })
|
||||
|
||||
expect(next.state).toBe(kept.state)
|
||||
expect(next.effects).toEqual([])
|
||||
})
|
||||
|
||||
test.each<[string, Event]>([
|
||||
["Escape", { type: "dismiss" }],
|
||||
["its close button", { type: "layer.dismiss", attempt: 1 }],
|
||||
["an un-keyed close", { type: "close" }],
|
||||
])("still closes on %s", (_, event) => {
|
||||
expect(transitionDialogStack(kept.state, event).effects).toEqual(closed(1, 100, "before a"))
|
||||
})
|
||||
|
||||
test("an unchanged setting writes nothing", () => {
|
||||
const next = transitionDialogStack(kept.state, { type: "layer.backdrop-dismiss", attempt: 1, enabled: false })
|
||||
|
||||
expect(next.state).toBe(kept.state)
|
||||
})
|
||||
})
|
||||
|
||||
test("a replacing dialog returns focus to the origin and never notifies a closing dialog again", () => {
|
||||
const before = run(createDialogStackState(), push("a"), push("b"), { type: "close", id: "b" })
|
||||
const next = transitionDialogStack(before.state, show("c"))
|
||||
|
||||
expect(next.effects).toEqual([
|
||||
{ type: "dispose", attempt: 1, notify: true },
|
||||
{ type: "timer.stop", attempt: 2 },
|
||||
{ type: "dispose", attempt: 2, notify: false },
|
||||
{ type: "mount", attempt: 3, id: "c", request: "c" },
|
||||
])
|
||||
expect(statuses(next.state)).toEqual(["c:open"])
|
||||
expect(run(next.state, { type: "dismiss" }).effects).toEqual(closed(3, 100, "before a"))
|
||||
})
|
||||
|
||||
test("an open whose signal aborted neither mounts nor replaces, and its caller hears onClose", () => {
|
||||
const before = run(createDialogStackState(), push("a"))
|
||||
const next = transitionDialogStack(before.state, open("show", "b", true))
|
||||
|
||||
expect(next.state).toBe(before.state)
|
||||
expect(next.effects).toEqual([{ type: "discard", request: "b", notify: true }])
|
||||
})
|
||||
|
||||
describe("exit timers and disposal", () => {
|
||||
test.each<[string, Event[]]>([
|
||||
["an open dialog", [push("a")]],
|
||||
["a dialog already gone", [push("a"), { type: "dismiss" }, { type: "exit.completed", attempt: 1 }]],
|
||||
["a replaced dialog", [push("a"), { type: "dismiss" }, show("b")]],
|
||||
])("ignore a late exit for %s", (_, events) => {
|
||||
const before = run(createDialogStackState(), ...events)
|
||||
const next = transitionDialogStack(before.state, { type: "exit.completed", attempt: 1 })
|
||||
|
||||
expect(next.state).toBe(before.state)
|
||||
expect(next.effects).toEqual([])
|
||||
})
|
||||
|
||||
test("a longer exit asked for after the close starts does not change the running timer", () => {
|
||||
const before = run(createDialogStackState(), push("a"), { type: "dismiss" })
|
||||
const next = transitionDialogStack(before.state, { type: "layer.exit-duration", attempt: 1, exitMs: 960 })
|
||||
|
||||
expect(next.state).toBe(before.state)
|
||||
})
|
||||
|
||||
test("the provider going away stops exit timers, disposes every dialog silently and ignores what follows", () => {
|
||||
const before = run(createDialogStackState(), push("a"), push("b"), { type: "dismiss" })
|
||||
const gone = transitionDialogStack(before.state, { type: "disposed" })
|
||||
|
||||
expect(gone.effects).toEqual([
|
||||
{ type: "dispose", attempt: 1, notify: false },
|
||||
{ type: "timer.stop", attempt: 2 },
|
||||
{ type: "dispose", attempt: 2, notify: false },
|
||||
])
|
||||
expect(selectTopDialog(gone.state)).toBeUndefined()
|
||||
expect(selectLayerClosing(gone.state, 1)).toBe(true)
|
||||
|
||||
const late = [
|
||||
{ type: "dismiss" },
|
||||
{ type: "close" },
|
||||
{ type: "exit.completed", attempt: 2 },
|
||||
{ type: "disposed" },
|
||||
] satisfies Event[]
|
||||
|
||||
late.forEach((event) => {
|
||||
const next = transitionDialogStack(gone.state, event)
|
||||
|
||||
expect(next.state).toBe(gone.state)
|
||||
expect(next.effects).toEqual([])
|
||||
})
|
||||
expect(transitionDialogStack(gone.state, push("c")).effects).toEqual([
|
||||
{ type: "discard", request: "c", notify: false },
|
||||
])
|
||||
expect(transitionDialogStack(gone.state, open("push", "c", true)).effects).toEqual([
|
||||
{ type: "discard", request: "c", notify: true },
|
||||
])
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,280 @@
|
||||
/** How long a dialog stays mounted once it starts closing, unless its layer asks for longer. */
|
||||
export const DIALOG_EXIT_MS = 100
|
||||
|
||||
/**
|
||||
* `attempt` identifies one mount, so a reused caller `id` never collides with a layer that is still closing. `focus` is
|
||||
* where focus returns: where it was before this dialog opened, or before the dialogs it replaced opened. `replaced`
|
||||
* holds the attempts of the open dialogs this one replaced through `show`, and theirs in turn, so a close from inside
|
||||
* one of them closes this dialog.
|
||||
*/
|
||||
export type DialogOpenEntry<F = unknown> = {
|
||||
readonly status: "open"
|
||||
readonly attempt: number
|
||||
readonly id: string
|
||||
readonly exitMs: number
|
||||
readonly backdropDismiss: boolean
|
||||
readonly focus: F | undefined
|
||||
readonly replaced: readonly number[]
|
||||
}
|
||||
|
||||
/** Waits for its exit animation. It keeps `focus` so a `show` that replaces it still returns focus to the origin. */
|
||||
export type DialogClosingEntry<F = unknown> = {
|
||||
readonly status: "closing"
|
||||
readonly attempt: number
|
||||
readonly id: string
|
||||
readonly focus: F | undefined
|
||||
readonly replaced: readonly number[]
|
||||
}
|
||||
|
||||
export type DialogEntry<F = unknown> = DialogOpenEntry<F> | DialogClosingEntry<F>
|
||||
|
||||
export type DialogStackState<F = unknown> =
|
||||
| { readonly status: "active"; readonly issued: number; readonly entries: readonly DialogEntry<F>[] }
|
||||
| { readonly status: "disposed"; readonly issued: number }
|
||||
|
||||
/** `request` is the driver's content for the open; the machine only hands it back in `mount` or `discard`. */
|
||||
export type DialogStackEvent<F = unknown, R = unknown> =
|
||||
| {
|
||||
readonly type: "open"
|
||||
readonly mode: "show" | "push"
|
||||
readonly id: string
|
||||
readonly aborted: boolean
|
||||
readonly focus: F | undefined
|
||||
readonly request: R
|
||||
}
|
||||
/**
|
||||
* With `id`, closes the newest open dialog with that id. Without one, `layer` is the attempt of the dialog that asked:
|
||||
* that dialog closes itself, even under a dialog that is still exiting, or the dialog that replaced it through `show`.
|
||||
* Once that dialog is gone, a late close (after an await) closes nothing. A close from outside every dialog closes the
|
||||
* newest dialog. Both close one at a time: while the target plays its exit animation, a second close (a double click,
|
||||
* a callback closing again) closes nothing below it.
|
||||
*/
|
||||
| { readonly type: "close"; readonly id?: string; readonly layer?: number }
|
||||
/** Escape, or a dismissal that applies only while `id` is the top open dialog. */
|
||||
| { readonly type: "dismiss"; readonly id?: string }
|
||||
/** A click on one layer's backdrop. */
|
||||
| { readonly type: "backdrop.click"; readonly attempt: number }
|
||||
/** Kobalte asking one layer to close, as its close button does. */
|
||||
| { readonly type: "layer.dismiss"; readonly attempt: number }
|
||||
| { readonly type: "layer.backdrop-dismiss"; readonly attempt: number; readonly enabled: boolean }
|
||||
| { readonly type: "layer.exit-duration"; readonly attempt: number; readonly exitMs: number }
|
||||
| { readonly type: "exit.completed"; readonly attempt: number }
|
||||
| { readonly type: "disposed" }
|
||||
|
||||
export type DialogStackEffect<F = unknown, R = unknown> =
|
||||
| { readonly type: "mount"; readonly attempt: number; readonly id: string; readonly request: R }
|
||||
| { readonly type: "discard"; readonly request: R; readonly notify: boolean }
|
||||
| { readonly type: "timer.start"; readonly attempt: number; readonly delayMs: number }
|
||||
| { readonly type: "timer.stop"; readonly attempt: number }
|
||||
| { readonly type: "notify.close"; readonly attempt: number }
|
||||
| { readonly type: "focus.return"; readonly attempt: number; readonly focus: F | undefined }
|
||||
| { readonly type: "dispose"; readonly attempt: number; readonly notify: boolean }
|
||||
|
||||
export type DialogStackTransition<F = unknown, R = unknown> = {
|
||||
readonly state: DialogStackState<F>
|
||||
readonly effects: readonly DialogStackEffect<F, R>[]
|
||||
}
|
||||
|
||||
export function createDialogStackState<F = unknown>(): DialogStackState<F> {
|
||||
return { status: "active", issued: 0, entries: [] }
|
||||
}
|
||||
|
||||
export function transitionDialogStack<F, R>(
|
||||
state: DialogStackState<F>,
|
||||
event: DialogStackEvent<F, R>,
|
||||
): DialogStackTransition<F, R> {
|
||||
if (event.type === "open") return open(state, event)
|
||||
|
||||
if (state.status === "disposed") return { state, effects: [] }
|
||||
|
||||
if (event.type === "disposed") {
|
||||
return {
|
||||
state: { status: "disposed", issued: state.issued },
|
||||
effects: state.entries.flatMap((entry) => teardown<F, R>(entry, false)),
|
||||
}
|
||||
}
|
||||
|
||||
if (event.type === "exit.completed") {
|
||||
const entry = state.entries.find((item) => item.attempt === event.attempt)
|
||||
|
||||
if (entry?.status !== "closing") return { state, effects: [] }
|
||||
|
||||
return {
|
||||
state: { ...state, entries: state.entries.filter((item) => item !== entry) },
|
||||
effects: [{ type: "dispose", attempt: entry.attempt, notify: false }],
|
||||
}
|
||||
}
|
||||
|
||||
if (event.type === "layer.backdrop-dismiss") {
|
||||
return update(state, event.attempt, (entry) =>
|
||||
entry.backdropDismiss === event.enabled ? entry : { ...entry, backdropDismiss: event.enabled },
|
||||
)
|
||||
}
|
||||
|
||||
if (event.type === "layer.exit-duration") {
|
||||
const exitMs = Math.max(0, event.exitMs)
|
||||
|
||||
return update(state, event.attempt, (entry) => (entry.exitMs === exitMs ? entry : { ...entry, exitMs }))
|
||||
}
|
||||
|
||||
const target = closeTarget(state, event)
|
||||
|
||||
if (!target) return { state, effects: [] }
|
||||
|
||||
return beginClose(state, target)
|
||||
}
|
||||
|
||||
/** The top dialog that is open. One that started closing no longer counts, though it waits to be disposed. */
|
||||
export function selectTopDialog<F>(state: DialogStackState<F>) {
|
||||
if (state.status === "disposed") return undefined
|
||||
|
||||
return state.entries.findLast((entry): entry is DialogOpenEntry<F> => entry.status === "open")
|
||||
}
|
||||
|
||||
/** True from the moment a layer starts closing, through its exit animation, and once it is gone. */
|
||||
export function selectLayerClosing<F>(state: DialogStackState<F>, attempt: number) {
|
||||
if (state.status === "disposed") return true
|
||||
|
||||
return state.entries.find((entry) => entry.attempt === attempt)?.status !== "open"
|
||||
}
|
||||
|
||||
/** Stacked dialogs render as sibling portals, so only the top open layer may own the focus trap. */
|
||||
export function selectLayerModal<F>(state: DialogStackState<F>, attempt: number, contained: boolean) {
|
||||
return !contained && selectTopDialog(state)?.attempt === attempt
|
||||
}
|
||||
|
||||
/** The layer's place in the stack, so a newer dialog always renders above. */
|
||||
export function selectLayerIndex<F>(state: DialogStackState<F>, attempt: number) {
|
||||
if (state.status === "disposed") return 0
|
||||
|
||||
return Math.max(
|
||||
0,
|
||||
state.entries.findIndex((entry) => entry.attempt === attempt),
|
||||
)
|
||||
}
|
||||
|
||||
function open<F, R>(
|
||||
state: DialogStackState<F>,
|
||||
event: Extract<DialogStackEvent<F, R>, { type: "open" }>,
|
||||
): DialogStackTransition<F, R> {
|
||||
// An open whose signal aborted neither mounts nor replaces anything; its caller hears onClose as a replaced one would.
|
||||
if (event.aborted) return { state, effects: [{ type: "discard", request: event.request, notify: true }] }
|
||||
|
||||
// A deferred open must not mount after the provider is gone.
|
||||
if (state.status === "disposed") return { state, effects: [{ type: "discard", request: event.request, notify: false }] }
|
||||
const attempt = state.issued + 1
|
||||
const replace = event.mode === "show"
|
||||
const first = state.entries[0]
|
||||
|
||||
const entry: DialogOpenEntry<F> = {
|
||||
status: "open",
|
||||
attempt,
|
||||
id: event.id,
|
||||
exitMs: DIALOG_EXIT_MS,
|
||||
backdropDismiss: true,
|
||||
// A replacement returns focus to where the dialogs it replaces would have, not to their now-removed content.
|
||||
focus: replace && first ? first.focus : event.focus,
|
||||
// A dialog that had already started closing was not replaced: a late close from inside it still closes nothing.
|
||||
replaced: replace
|
||||
? state.entries.flatMap((item) => (item.status === "open" ? [item.attempt, ...item.replaced] : []))
|
||||
: [],
|
||||
}
|
||||
|
||||
const mount: DialogStackEffect<F, R> = { type: "mount", attempt, id: event.id, request: event.request }
|
||||
|
||||
if (!replace) return { state: { ...state, issued: attempt, entries: [...state.entries, entry] }, effects: [mount] }
|
||||
|
||||
return {
|
||||
state: { ...state, issued: attempt, entries: [entry] },
|
||||
effects: [...state.entries.flatMap((item) => teardown<F, R>(item, true)), mount],
|
||||
}
|
||||
}
|
||||
|
||||
function closeTarget<F>(
|
||||
state: Extract<DialogStackState<F>, { status: "active" }>,
|
||||
event: Extract<
|
||||
DialogStackEvent<F>,
|
||||
{ type: "close" } | { type: "dismiss" } | { type: "backdrop.click" } | { type: "layer.dismiss" }
|
||||
>,
|
||||
) {
|
||||
const top = selectTopDialog(state)
|
||||
|
||||
if (event.type === "close") {
|
||||
if (event.id !== undefined) {
|
||||
return state.entries.findLast(
|
||||
(entry): entry is DialogOpenEntry<F> => entry.status === "open" && entry.id === event.id,
|
||||
)
|
||||
}
|
||||
|
||||
const layer = event.layer
|
||||
|
||||
const target =
|
||||
layer === undefined
|
||||
? state.entries.at(-1)
|
||||
: state.entries.find((entry) => entry.attempt === layer || entry.replaced.includes(layer))
|
||||
|
||||
return target?.status === "open" ? target : undefined
|
||||
}
|
||||
|
||||
if (event.type === "dismiss") return event.id === undefined || top?.id === event.id ? top : undefined
|
||||
|
||||
if (top?.attempt !== event.attempt) return undefined
|
||||
|
||||
if (event.type === "backdrop.click" && !top.backdropDismiss) return undefined
|
||||
|
||||
return top
|
||||
}
|
||||
|
||||
/** The exit timer starts first, so the dialog still goes away when its onClose throws. */
|
||||
function beginClose<F, R>(
|
||||
state: Extract<DialogStackState<F>, { status: "active" }>,
|
||||
target: DialogOpenEntry<F>,
|
||||
): DialogStackTransition<F, R> {
|
||||
// Only the top open dialog holds focus. It returns after onClose, so focus that onClose moved elsewhere stays there,
|
||||
// and before close() returns, as a native dialog's does, so an action that runs after closing can move it on.
|
||||
const top = selectTopDialog(state)?.attempt === target.attempt
|
||||
|
||||
const closing: DialogClosingEntry<F> = {
|
||||
status: "closing",
|
||||
attempt: target.attempt,
|
||||
id: target.id,
|
||||
focus: target.focus,
|
||||
replaced: target.replaced,
|
||||
}
|
||||
|
||||
return {
|
||||
state: { ...state, entries: state.entries.map((entry) => (entry === target ? closing : entry)) },
|
||||
effects: [
|
||||
{ type: "timer.start", attempt: target.attempt, delayMs: target.exitMs },
|
||||
{ type: "notify.close", attempt: target.attempt },
|
||||
...(top ? [{ type: "focus.return" as const, attempt: target.attempt, focus: target.focus }] : []),
|
||||
],
|
||||
}
|
||||
}
|
||||
|
||||
/** A dialog that is already closing heard onClose when it started to; it does not hear it again. */
|
||||
function teardown<F, R>(entry: DialogEntry<F>, notify: boolean): DialogStackEffect<F, R>[] {
|
||||
if (entry.status === "open") return [{ type: "dispose", attempt: entry.attempt, notify }]
|
||||
|
||||
return [
|
||||
{ type: "timer.stop", attempt: entry.attempt },
|
||||
{ type: "dispose", attempt: entry.attempt, notify: false },
|
||||
]
|
||||
}
|
||||
|
||||
function update<F, R>(
|
||||
state: Extract<DialogStackState<F>, { status: "active" }>,
|
||||
attempt: number,
|
||||
change: (entry: DialogOpenEntry<F>) => DialogOpenEntry<F>,
|
||||
): DialogStackTransition<F, R> {
|
||||
const entry = state.entries.find(
|
||||
(item): item is DialogOpenEntry<F> => item.attempt === attempt && item.status === "open",
|
||||
)
|
||||
|
||||
if (!entry) return { state, effects: [] }
|
||||
const next = change(entry)
|
||||
|
||||
if (next === entry) return { state, effects: [] }
|
||||
|
||||
return { state: { ...state, entries: state.entries.map((item) => (item === entry ? next : item)) }, effects: [] }
|
||||
}
|
||||
+167
-176
@@ -1,6 +1,8 @@
|
||||
import {
|
||||
type Accessor,
|
||||
createContext,
|
||||
createEffect,
|
||||
createMemo,
|
||||
createRoot,
|
||||
createSignal,
|
||||
getOwner,
|
||||
@@ -8,6 +10,7 @@ import {
|
||||
type Owner,
|
||||
type ParentProps,
|
||||
runWithOwner,
|
||||
untrack,
|
||||
useContext,
|
||||
type JSX,
|
||||
startTransition,
|
||||
@@ -15,23 +18,32 @@ import {
|
||||
} from "solid-js"
|
||||
import { Dialog as Kobalte } from "@kobalte/core/dialog"
|
||||
import { makeEventListener } from "@solid-primitives/event-listener"
|
||||
import { uuid } from "@opencode/util/uuid"
|
||||
import {
|
||||
createDialogStackState,
|
||||
selectLayerClosing,
|
||||
selectLayerIndex,
|
||||
selectLayerModal,
|
||||
selectTopDialog,
|
||||
transitionDialogStack,
|
||||
type DialogStackEffect,
|
||||
type DialogStackEvent,
|
||||
} from "./dialog-machine"
|
||||
|
||||
type DialogElement = () => JSX.Element
|
||||
|
||||
type FocusReturn = { element: HTMLElement; visible: boolean; range?: Range }
|
||||
export type FocusReturn = { element: HTMLElement; visible: boolean; range?: Range }
|
||||
|
||||
type Active = {
|
||||
id: string
|
||||
/** What an open mounts: its content, the owner it renders under, and who hears that it closed. */
|
||||
type DialogRequest = { element: DialogElement; owner: Owner; onClose?: () => void }
|
||||
|
||||
type Layer = {
|
||||
attempt: number
|
||||
node: JSX.Element
|
||||
dispose: () => void
|
||||
owner: Owner
|
||||
onClose?: () => void
|
||||
setClosing: (closing: boolean) => void
|
||||
/** How long the dialog stays mounted once it starts closing, so its exit animation can finish. */
|
||||
exit: () => number
|
||||
/** Where focus was before this dialog opened, or before the dialogs it replaced opened. */
|
||||
focus?: FocusReturn
|
||||
returnFocus: () => void
|
||||
dispose: () => void
|
||||
ref: () => HTMLDivElement | undefined
|
||||
}
|
||||
|
||||
const Context = createContext<ReturnType<typeof init>>()
|
||||
@@ -39,6 +51,11 @@ const Context = createContext<ReturnType<typeof init>>()
|
||||
// Lets the dialog rendered in a layer opt out of closing on a backdrop click, or ask for a longer exit animation. A
|
||||
// contained layer also says which element holds it, so presses outside that element leave the dialog open.
|
||||
const LayerContext = createContext<{
|
||||
readonly id: string
|
||||
/** This layer's mount, which a `close()` from inside it targets. */
|
||||
readonly attempt: number
|
||||
/** True from the moment this dialog starts closing, through its exit animation. */
|
||||
readonly closing: Accessor<boolean>
|
||||
setBackdropDismiss: (value: boolean) => void
|
||||
setExitDuration: (ms: number) => void
|
||||
container?: HTMLElement
|
||||
@@ -49,154 +66,136 @@ export function useDialogLayer() {
|
||||
}
|
||||
|
||||
function init(container: () => HTMLElement | undefined) {
|
||||
const [stack, setStack] = createSignal<Active[]>([])
|
||||
// A dialog is closing from the moment its close starts until its exit animation ends and it is disposed.
|
||||
const closing = new Map<string, ReturnType<typeof setTimeout> | undefined>()
|
||||
// The same ids, reactive, so the top dialog that stays open owns the focus trap during an exit animation.
|
||||
const [exiting, setExiting] = createSignal<ReadonlySet<string>>(new Set())
|
||||
// The top dialog that stays open. A dialog without an exit animation leaves the DOM as soon as it starts closing, so
|
||||
// it stops being the active dialog then, not when it is disposed.
|
||||
const top = () => stack().findLast((item) => !exiting().has(item.id))
|
||||
const lock = { value: false }
|
||||
const state = { disposed: false }
|
||||
const [machine, setMachine] = createSignal(createDialogStackState<FocusReturn>())
|
||||
const [layers, setLayers] = createSignal<Layer[]>([])
|
||||
const timers = new Map<number, ReturnType<typeof setTimeout>>()
|
||||
// Events an effect raises synchronously (a dialog closing as it renders or disposes) wait behind it.
|
||||
const queue: DialogStackEvent<FocusReturn, DialogRequest>[] = []
|
||||
|
||||
// Detach the stack before disposing, so cleanups that close dialogs find nothing to admit. Every dialog is
|
||||
// drained even when one throws. A replaced dialog that was not already closing still hears onClose.
|
||||
const disposeAll = (notify: boolean) => {
|
||||
const items = stack()
|
||||
const exited = new Set(closing.keys())
|
||||
setStack([])
|
||||
closing.forEach((timer) => clearTimeout(timer))
|
||||
closing.clear()
|
||||
setExiting(new Set<string>())
|
||||
items.forEach((item) => {
|
||||
if (notify && !exited.has(item.id)) isolate(() => item.onClose?.())
|
||||
isolate(item.dispose)
|
||||
})
|
||||
const dispatch = (event: DialogStackEvent<FocusReturn, DialogRequest>) => {
|
||||
queue.push(event)
|
||||
|
||||
if (queue.length === 1) untrack(drain)
|
||||
}
|
||||
|
||||
onCleanup(() => {
|
||||
state.disposed = true
|
||||
disposeAll(false)
|
||||
})
|
||||
const drain = () => {
|
||||
const event = queue[0]
|
||||
|
||||
const finish = (current: Active) => {
|
||||
// Scheduled first, so the dialog still goes away when a callback throws.
|
||||
closing.set(
|
||||
current.id,
|
||||
setTimeout(() => {
|
||||
closing.delete(current.id)
|
||||
if (!event) return
|
||||
|
||||
if (closing.size === 0) lock.value = false
|
||||
setExiting((ids) => new Set([...ids].filter((id) => id !== current.id)))
|
||||
setStack((items) => items.filter((item) => item.id !== current.id))
|
||||
current.dispose()
|
||||
}, current.exit()),
|
||||
)
|
||||
setExiting((ids) => new Set([...ids, current.id]))
|
||||
isolate(() => current.onClose?.())
|
||||
current.setClosing(true)
|
||||
try {
|
||||
const prev = machine()
|
||||
const next = transitionDialogStack(prev, event)
|
||||
|
||||
// Only the top open dialog holds focus. It returns before close() does, as a native dialog's does, so an
|
||||
// action that runs after closing, such as a palette command that opens the terminal, can move it on.
|
||||
if (stack().findLast((item) => item === current || !closing.has(item.id)) === current) current.returnFocus()
|
||||
// Committed before the effects, so a closing layer's Kobalte dialog has closed by the time focus returns. A reader
|
||||
// of the state or an effect that throws must not stop the queue or skip the other effects.
|
||||
if (next.state !== prev) isolate(() => setMachine(next.state))
|
||||
next.effects.forEach((effect) => isolate(() => run(effect)))
|
||||
} finally {
|
||||
queue.shift()
|
||||
drain()
|
||||
}
|
||||
}
|
||||
|
||||
/** Programmatic close. Without an id it closes the top dialog, one at a time; with an id it never waits. */
|
||||
const close = (id?: string) => {
|
||||
const current = id ? stack().find((item) => item.id === id) : stack().at(-1)
|
||||
const run = (effect: DialogStackEffect<FocusReturn, DialogRequest>) => {
|
||||
if (effect.type === "mount") return mount(effect)
|
||||
|
||||
if (!current || closing.has(current.id) || (!id && lock.value)) return
|
||||
closing.set(current.id, undefined)
|
||||
lock.value = true
|
||||
finish(current)
|
||||
if (effect.type === "discard") return void (effect.notify && effect.request.onClose?.())
|
||||
|
||||
if (effect.type === "timer.start") {
|
||||
clearTimeout(timers.get(effect.attempt))
|
||||
timers.set(
|
||||
effect.attempt,
|
||||
setTimeout(() => dispatch({ type: "exit.completed", attempt: effect.attempt }), effect.delayMs),
|
||||
)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
if (effect.type === "timer.stop") {
|
||||
clearTimeout(timers.get(effect.attempt))
|
||||
timers.delete(effect.attempt)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
const layer = layers().find((item) => item.attempt === effect.attempt)
|
||||
|
||||
if (effect.type === "notify.close") return layer?.onClose?.()
|
||||
|
||||
if (effect.type === "focus.return") {
|
||||
const ref = layer?.ref()
|
||||
|
||||
// A close inside a reactive update unmounts the dialog, and its focus trap, only when the update ends.
|
||||
if (ref?.contains(document.activeElement)) return queueMicrotask(() => returnFocus(effect.focus, ref))
|
||||
|
||||
return returnFocus(effect.focus, ref)
|
||||
}
|
||||
|
||||
timers.delete(effect.attempt)
|
||||
setLayers((items) => items.filter((item) => item.attempt !== effect.attempt))
|
||||
|
||||
if (effect.notify) isolate(() => layer?.onClose?.())
|
||||
layer?.dispose()
|
||||
}
|
||||
|
||||
/** Escape, a backdrop click, or Kobalte dismissing: only the top dialog, and one per exit animation. */
|
||||
const dismiss = (id?: string) => {
|
||||
const current = stack().at(-1)
|
||||
onCleanup(() => dispatch({ type: "disposed" }))
|
||||
|
||||
if (!current || (id && current.id !== id) || closing.has(current.id) || lock.value) return
|
||||
closing.set(current.id, undefined)
|
||||
lock.value = true
|
||||
finish(current)
|
||||
// Escape is captured only while a dialog is open, not while the last one plays its exit animation.
|
||||
const open = createMemo(() => !!selectTopDialog(machine()))
|
||||
|
||||
const onKeyDown = (event: KeyboardEvent) => {
|
||||
if (event.key !== "Escape") return
|
||||
|
||||
// Escape in the page around a contained stack belongs to the page.
|
||||
const within = container()
|
||||
|
||||
if (within && event.target instanceof Node && !within.contains(event.target)) return
|
||||
|
||||
// A control that cancels its own edit on Escape, such as an inline rename, keeps the dialog open.
|
||||
if (event.target instanceof Element && event.target.closest("[data-owns-escape]")) return
|
||||
dispatch({ type: "dismiss" })
|
||||
event.preventDefault()
|
||||
event.stopPropagation()
|
||||
}
|
||||
|
||||
createEffect(() => {
|
||||
if (stack().length === 0) return
|
||||
|
||||
const onKeyDown = (event: KeyboardEvent) => {
|
||||
if (event.key !== "Escape") return
|
||||
|
||||
// Escape in the page around a contained stack belongs to the page.
|
||||
const within = container()
|
||||
|
||||
if (within && event.target instanceof Node && !within.contains(event.target)) return
|
||||
|
||||
// A control that cancels its own edit on Escape, such as an inline rename, keeps the dialog open.
|
||||
if (event.target instanceof Element && event.target.closest("[data-owns-escape]")) return
|
||||
dismiss()
|
||||
event.preventDefault()
|
||||
event.stopPropagation()
|
||||
}
|
||||
if (!open()) return
|
||||
|
||||
makeEventListener(window, "keydown", onKeyDown, { capture: true })
|
||||
})
|
||||
|
||||
const mount = (
|
||||
element: DialogElement,
|
||||
owner: Owner,
|
||||
onClose: (() => void) | undefined,
|
||||
key: string | undefined,
|
||||
focus: FocusReturn | undefined,
|
||||
) => {
|
||||
// A deferred open (e.g. from a focus callback) must not mount after the provider is gone.
|
||||
if (state.disposed) return
|
||||
const id = key ?? Math.random().toString(36).slice(2)
|
||||
|
||||
// The layer follows the dialog's current place in the stack, so a new top dialog always renders above.
|
||||
const layer = () =>
|
||||
Math.max(
|
||||
0,
|
||||
stack().findIndex((item) => item.id === id),
|
||||
)
|
||||
|
||||
const zIndex = () => String(50 + layer() * 10)
|
||||
const mount = (effect: Extract<DialogStackEffect<FocusReturn, DialogRequest>, { type: "mount" }>) => {
|
||||
const attempt = effect.attempt
|
||||
const zIndex = () => String(50 + selectLayerIndex(machine(), attempt) * 10)
|
||||
// A function, not an inline `&&`: the compiler wraps an inline condition in a memo on every read of the prop, and
|
||||
// Kobalte reads it outside any owner, from outside-pointer handlers and while the closing dialog unmounts.
|
||||
const modal = () => !container() && top()?.id === id
|
||||
let dispose: (() => void) | undefined
|
||||
let setClosing: ((closing: boolean) => void) | undefined
|
||||
let layerRef: HTMLDivElement | undefined
|
||||
let exit = 100
|
||||
const modal = () => selectLayerModal(machine(), attempt, !!container())
|
||||
let ref: HTMLDivElement | undefined
|
||||
let dispose = () => {}
|
||||
|
||||
// Stacked dialogs render as sibling portals, so only the top layer may own the focus trap.
|
||||
const node = runWithOwner(owner, () =>
|
||||
const node = runWithOwner(effect.request.owner, () =>
|
||||
createRoot((d: () => void) => {
|
||||
dispose = d
|
||||
const [closing, setClosingSignal] = createSignal(false)
|
||||
const [backdropDismiss, setBackdropDismiss] = createSignal(true)
|
||||
setClosing = setClosingSignal
|
||||
const closing = createMemo(() => selectLayerClosing(machine(), attempt))
|
||||
|
||||
return (
|
||||
<Kobalte
|
||||
modal={modal()}
|
||||
open={!closing()}
|
||||
onOpenChange={(open: boolean) => {
|
||||
if (!open) dismiss(id)
|
||||
if (!open) dispatch({ type: "layer.dismiss", attempt })
|
||||
}}
|
||||
>
|
||||
<Kobalte.Portal mount={container()}>
|
||||
<Kobalte.Overlay
|
||||
data-component="dialog-overlay"
|
||||
style={{ "z-index": zIndex() }}
|
||||
onClick={() => {
|
||||
if (backdropDismiss()) dismiss(id)
|
||||
}}
|
||||
onClick={() => dispatch({ type: "backdrop.click", attempt })}
|
||||
/>
|
||||
<div
|
||||
ref={layerRef}
|
||||
data-dialog-layer={layer()}
|
||||
ref={ref}
|
||||
data-dialog-layer={selectLayerIndex(machine(), attempt)}
|
||||
style={{
|
||||
position: "fixed",
|
||||
inset: "0",
|
||||
@@ -208,9 +207,16 @@ function init(container: () => HTMLElement | undefined) {
|
||||
}}
|
||||
>
|
||||
<LayerContext.Provider
|
||||
value={{ setBackdropDismiss, setExitDuration: (ms) => (exit = ms), container: container() }}
|
||||
value={{
|
||||
id: effect.id,
|
||||
attempt,
|
||||
closing,
|
||||
setBackdropDismiss: (enabled) => dispatch({ type: "layer.backdrop-dismiss", attempt, enabled }),
|
||||
setExitDuration: (exitMs) => dispatch({ type: "layer.exit-duration", attempt, exitMs }),
|
||||
container: container(),
|
||||
}}
|
||||
>
|
||||
{element()}
|
||||
{effect.request.element()}
|
||||
</LayerContext.Provider>
|
||||
</div>
|
||||
</Kobalte.Portal>
|
||||
@@ -219,56 +225,33 @@ function init(container: () => HTMLElement | undefined) {
|
||||
}),
|
||||
)
|
||||
|
||||
if (!dispose || !setClosing) return
|
||||
|
||||
const active: Active = {
|
||||
id,
|
||||
node,
|
||||
dispose,
|
||||
owner,
|
||||
onClose,
|
||||
setClosing,
|
||||
exit: () => exit,
|
||||
focus,
|
||||
returnFocus: () => {
|
||||
// A close inside a reactive update unmounts the dialog, and its focus trap, only when the update ends.
|
||||
if (layerRef?.contains(document.activeElement)) return queueMicrotask(() => returnFocus(focus, layerRef))
|
||||
returnFocus(focus, layerRef)
|
||||
setLayers((items) => [
|
||||
...items,
|
||||
{
|
||||
attempt,
|
||||
node,
|
||||
owner: effect.request.owner,
|
||||
onClose: effect.request.onClose,
|
||||
dispose,
|
||||
ref: () => ref,
|
||||
},
|
||||
}
|
||||
|
||||
setStack((items) => [...items, active])
|
||||
}
|
||||
|
||||
const push = (element: DialogElement, owner: Owner, onClose?: () => void, id?: string) => {
|
||||
lock.value = false
|
||||
mount(element, owner, onClose, id, captureFocus())
|
||||
}
|
||||
|
||||
const show = (element: DialogElement, owner: Owner, onClose?: () => void, id?: string) => {
|
||||
// A replacement returns focus to where the dialogs it replaces would have, not to their now-removed content.
|
||||
const focus = stack().length > 0 ? stack()[0].focus : captureFocus()
|
||||
disposeAll(true)
|
||||
lock.value = false
|
||||
mount(element, owner, onClose, id, focus)
|
||||
])
|
||||
}
|
||||
|
||||
return {
|
||||
stack,
|
||||
top,
|
||||
close,
|
||||
show,
|
||||
push,
|
||||
dispatch,
|
||||
active: () => selectTopDialog(machine()),
|
||||
/** Stacked dialogs render under the owner of the dialog below, so they see the same context. */
|
||||
base: () => layers().at(-1)?.owner,
|
||||
open: (mode: "show" | "push", request: DialogRequest, id: string | undefined, aborted: boolean) =>
|
||||
dispatch({ type: "open", mode, id: id ?? uuid(), aborted, focus: captureFocus(), request }),
|
||||
layers,
|
||||
}
|
||||
}
|
||||
|
||||
/** Runs a dialog callback so its throw is reported without stopping the caller's cleanup. */
|
||||
function isolate(fn: () => void) {
|
||||
try {
|
||||
fn()
|
||||
} catch (error) {
|
||||
console.error("[dialog]", error)
|
||||
}
|
||||
void Promise.try(fn).catch((cause: unknown) => console.error("[dialog]", cause))
|
||||
}
|
||||
|
||||
/** Remembers the focused element and, in editable content, the caret, which focusing alone does not restore. */
|
||||
@@ -314,7 +297,7 @@ export function DialogProvider(props: ParentProps<{ container?: HTMLElement }>)
|
||||
<Context.Provider value={ctx}>
|
||||
{props.children}
|
||||
<div data-component="dialog-stack">
|
||||
<For each={ctx.stack()}>{(item) => item.node}</For>
|
||||
<For each={ctx.layers()}>{(item) => item.node}</For>
|
||||
</div>
|
||||
</Context.Provider>
|
||||
)
|
||||
@@ -322,6 +305,7 @@ export function DialogProvider(props: ParentProps<{ container?: HTMLElement }>)
|
||||
|
||||
export function useDialog() {
|
||||
const ctx = useContext(Context)
|
||||
const layer = useContext(LayerContext)
|
||||
const owner = getOwner()
|
||||
|
||||
if (!owner) {
|
||||
@@ -335,30 +319,37 @@ export function useDialog() {
|
||||
return {
|
||||
/** The top dialog that is open. One that has started closing no longer counts, though it waits to be disposed. */
|
||||
get active() {
|
||||
return ctx.top()
|
||||
return ctx.active()
|
||||
},
|
||||
/** Inside a dialog, true from the moment that dialog starts closing; outside every dialog, false. */
|
||||
get closing() {
|
||||
return layer?.closing() ?? false
|
||||
},
|
||||
/**
|
||||
* id lets the caller close this dialog later rather than whichever is on top. Opening is deferred; once
|
||||
* signal aborts, the open neither mounts nor replaces anything and onClose runs as for a replaced dialog.
|
||||
*/
|
||||
show(element: DialogElement, onClose?: () => void, id?: string, signal?: AbortSignal) {
|
||||
const base = ctx.stack().at(-1)?.owner ?? owner
|
||||
const base = ctx.base() ?? owner
|
||||
|
||||
return startTransition(() => {
|
||||
if (signal?.aborted) return isolate(() => onClose?.())
|
||||
ctx.show(element, base, onClose, id)
|
||||
})
|
||||
return startTransition(() => ctx.open("show", { element, owner: base, onClose }, id, !!signal?.aborted))
|
||||
},
|
||||
push(element: DialogElement, onClose?: () => void, id?: string, signal?: AbortSignal) {
|
||||
const base = ctx.stack().at(-1)?.owner ?? owner
|
||||
const base = ctx.base() ?? owner
|
||||
|
||||
return startTransition(() => {
|
||||
if (signal?.aborted) return isolate(() => onClose?.())
|
||||
ctx.push(element, base, onClose, id)
|
||||
})
|
||||
return startTransition(() => ctx.open("push", { element, owner: base, onClose }, id, !!signal?.aborted))
|
||||
},
|
||||
/**
|
||||
* Programmatic close. With an id it closes that dialog at once. Without one, called inside a dialog, it closes that
|
||||
* dialog, or the dialog that replaced it through `show`, and nothing once it is gone; outside every dialog it closes
|
||||
* the top one. Either way one at a time, so a double click closes one dialog.
|
||||
*/
|
||||
close(id?: string) {
|
||||
ctx.close(id)
|
||||
ctx.dispatch({ type: "close", id, layer: layer?.attempt })
|
||||
},
|
||||
/** Dismisses the top open dialog, as Escape does; with an id, only while that dialog is on top. */
|
||||
dismiss(id?: string) {
|
||||
ctx.dispatch({ type: "dismiss", id })
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
import { Overlay, Portal, Root, Trigger } from "@kobalte/core/dialog"
|
||||
import { Dialog, DialogBody, DialogFooter, DialogHeader, DialogTitle, DialogTitleGroup } from "./dialog"
|
||||
import { Button } from "@opencode/ui/button"
|
||||
import { useDialog } from "@opencode/ui/context/dialog"
|
||||
import { onMount, type JSX } from "solid-js"
|
||||
import { useDialog, useDialogLayer } from "@opencode/ui/context/dialog"
|
||||
import { onMount, type JSX, type ParentProps } from "solid-js"
|
||||
|
||||
const docs = `### Overview
|
||||
Dialog content wrapper built on Kobalte's dialog primitive with v2 styling.
|
||||
@@ -229,3 +229,57 @@ function OpenFromButton() {
|
||||
export const OpenedFromButton = {
|
||||
render: () => <OpenFromButton />,
|
||||
}
|
||||
|
||||
// Stays mounted as long as an image preview's flight out, so its exit outlasts the dialogs above it.
|
||||
function SlowExit(props: ParentProps) {
|
||||
useDialogLayer()?.setExitDuration(960)
|
||||
|
||||
return props.children
|
||||
}
|
||||
|
||||
function StackedDialogs() {
|
||||
const dialog = useDialog()
|
||||
|
||||
const open = () => {
|
||||
void dialog.show(() => (
|
||||
<Dialog size="x-large">
|
||||
{dialogHeader("Below", "The first dialog in the stack")}
|
||||
<DialogBody>Stays open throughout.</DialogBody>
|
||||
</Dialog>
|
||||
))
|
||||
void dialog.push(
|
||||
() => (
|
||||
<SlowExit>
|
||||
<Dialog size="large">
|
||||
{dialogHeader("Middle", "Takes 960 ms to leave, as an image preview does")}
|
||||
<DialogBody>Closed by its id while it is not on top.</DialogBody>
|
||||
</Dialog>
|
||||
</SlowExit>
|
||||
),
|
||||
undefined,
|
||||
"middle",
|
||||
)
|
||||
void dialog.push(() => (
|
||||
<Dialog fit>
|
||||
{dialogHeader("Top", "Close the middle dialog, then press Escape")}
|
||||
<DialogFooter>
|
||||
<Button variant="neutral" onClick={() => dialog.close("middle")}>
|
||||
Close middle
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</Dialog>
|
||||
))
|
||||
}
|
||||
|
||||
onMount(open)
|
||||
|
||||
return (
|
||||
<Button variant="neutral" onClick={open}>
|
||||
Open stacked dialogs
|
||||
</Button>
|
||||
)
|
||||
}
|
||||
|
||||
export const Stacked = {
|
||||
render: () => <StackedDialogs />,
|
||||
}
|
||||
|
||||
@@ -6,6 +6,7 @@ import {
|
||||
Show,
|
||||
children,
|
||||
createEffect,
|
||||
onCleanup,
|
||||
splitProps,
|
||||
} from "solid-js"
|
||||
import { useDialogLayer } from "../../context/dialog"
|
||||
@@ -113,7 +114,9 @@ export function Dialog(props: DialogProps) {
|
||||
])
|
||||
|
||||
const layer = useDialogLayer()
|
||||
let focusTimer: ReturnType<typeof setTimeout> | undefined
|
||||
createEffect(() => layer?.setBackdropDismiss(!local.preventBackdropDismiss))
|
||||
onCleanup(() => clearTimeout(focusTimer))
|
||||
|
||||
return (
|
||||
<div
|
||||
@@ -147,7 +150,10 @@ export function Dialog(props: DialogProps) {
|
||||
// Kobalte attaches its focus trap after this event, so focusing now would leave the trap with no element
|
||||
// to return to. Deferring, as Kobalte's own autofocus does, also lets children that focus themselves on
|
||||
// mount keep that focus.
|
||||
setTimeout(() => {
|
||||
clearTimeout(focusTimer)
|
||||
focusTimer = setTimeout(() => {
|
||||
// A dialog that closed in the meantime must not pull focus back from where its close returned it.
|
||||
if (layer?.closing() || !content.isConnected) return
|
||||
const autofocus = content.querySelector<HTMLElement>("[autofocus]")
|
||||
const active = document.activeElement
|
||||
|
||||
|
||||
Reference in New Issue
Block a user