mirror of
https://github.com/anomalyco/opencode.git
synced 2026-11-19 17:01:37 +03:00
fix(ui): drive tooltip open and popup suppression through one state machine (#61945)
This commit is contained in:
committed by
GitHub
Unverified
parent
ceb8288cf8
commit
438ca536a0
@@ -10,3 +10,40 @@ story("opens a neighbouring tooltip without the open delay", async ({ mount, pag
|
||||
await root.getByText("Compact", { exact: true }).hover()
|
||||
await expect(page.getByRole("tooltip", { name: "Compact tooltip" })).toBeVisible()
|
||||
})
|
||||
|
||||
story("keeps a menu trigger's tooltip hidden when the menu closes under a still pointer", async ({ mount, page }) => {
|
||||
const root = await mount("ui-tooltip--with-menu")
|
||||
await page.clock.install()
|
||||
const trigger = root.getByRole("button", { name: "Actions" })
|
||||
const tooltip = page.getByRole("tooltip", { name: "More actions" })
|
||||
await trigger.hover()
|
||||
await expect(tooltip).toBeVisible()
|
||||
await trigger.click()
|
||||
await expect(page.getByRole("menu")).toBeVisible()
|
||||
await expect(tooltip).toBeHidden()
|
||||
await page.keyboard.press("Escape")
|
||||
await expect(page.getByRole("menu")).toBeHidden()
|
||||
await expect(trigger).toBeFocused()
|
||||
// The menu's closing layer hands the still pointer a fresh pointerenter, which would open the tooltip 400 ms later.
|
||||
await page.clock.runFor(1000)
|
||||
await expect(tooltip).toBeHidden()
|
||||
await page.mouse.move(0, 0)
|
||||
await trigger.hover()
|
||||
await expect(tooltip).toBeVisible()
|
||||
})
|
||||
|
||||
story("opens a menu trigger's tooltip on the next hover after the menu closes", async ({ mount, page }) => {
|
||||
const root = await mount("ui-tooltip--with-menu")
|
||||
const trigger = root.getByRole("button", { name: "Actions" })
|
||||
const tooltip = page.getByRole("tooltip", { name: "More actions" })
|
||||
await trigger.hover()
|
||||
await expect(tooltip).toBeVisible()
|
||||
await trigger.click()
|
||||
await expect(page.getByRole("menu")).toBeVisible()
|
||||
await page.mouse.move(0, 0)
|
||||
await page.keyboard.press("Escape")
|
||||
await expect(page.getByRole("menu")).toBeHidden()
|
||||
await expect(trigger).toBeFocused()
|
||||
await trigger.hover()
|
||||
await expect(tooltip).toBeVisible()
|
||||
})
|
||||
|
||||
@@ -0,0 +1,219 @@
|
||||
import { describe, expect, test } from "bun:test"
|
||||
import {
|
||||
createTooltipState,
|
||||
DISPOSED_EVENT,
|
||||
FOCUSED,
|
||||
KOBALTE_CLOSED,
|
||||
KOBALTE_OPENED,
|
||||
LEAVE_SETTLED,
|
||||
POINTER_ENTERED,
|
||||
POINTER_INSIDE,
|
||||
POINTER_LEFT,
|
||||
POINTER_OUTSIDE,
|
||||
POPUP_COLLAPSED,
|
||||
POPUP_EXPANDED,
|
||||
PRESS_ENDED,
|
||||
selectTooltipForceOpen,
|
||||
selectTooltipMounted,
|
||||
selectTooltipOpen,
|
||||
selectTooltipPressing,
|
||||
selectTooltipTracking,
|
||||
syncPropsEvent,
|
||||
transitionTooltip,
|
||||
TRIGGER_PRESSED,
|
||||
type TooltipEvent,
|
||||
type TooltipState,
|
||||
type TooltipTransition,
|
||||
} from "./machine"
|
||||
|
||||
const UNCONTROLLED = syncPropsEvent(undefined, false)
|
||||
|
||||
function run(state: TooltipState, ...events: TooltipEvent[]) {
|
||||
return events.reduce<TooltipTransition>((result, event) => transitionTooltip(result.state, event), {
|
||||
state,
|
||||
effects: [],
|
||||
})
|
||||
}
|
||||
|
||||
// Hovered for the open delay: Kobalte heard the replayed pointerenter and asks to open.
|
||||
const hoveredOpen = () => run(createTooltipState(undefined, false), POINTER_ENTERED, KOBALTE_OPENED).state
|
||||
|
||||
describe("tooltip machine", () => {
|
||||
test("a press while the tooltip is closing does not swallow the next open", () => {
|
||||
// The press lands during the exit animation, when no click close follows to consume it.
|
||||
const state = run(hoveredOpen(), POINTER_LEFT, LEAVE_SETTLED, TRIGGER_PRESSED, POINTER_ENTERED, KOBALTE_OPENED)
|
||||
|
||||
expect(selectTooltipOpen(state.state)).toBe(true)
|
||||
})
|
||||
|
||||
test("opening a menu from an open tooltip ends the press, and the next hover opens it again", () => {
|
||||
const opened = run(hoveredOpen(), TRIGGER_PRESSED, POPUP_EXPANDED)
|
||||
|
||||
expect(opened.state).toEqual({ status: "suppressed", popup: "open", hovered: true, disabled: false })
|
||||
expect(selectTooltipPressing(opened.state)).toBe(false)
|
||||
|
||||
// The pointer leaves while the menu is open, Escape closes it, and the pointer comes back.
|
||||
const closed = run(opened.state, POINTER_OUTSIDE, POPUP_COLLAPSED)
|
||||
|
||||
expect(closed.state).toEqual({ status: "idle", hovered: false, disabled: false })
|
||||
expect(selectTooltipOpen(run(closed.state, POINTER_ENTERED, KOBALTE_OPENED).state)).toBe(true)
|
||||
})
|
||||
|
||||
test("a press while forceOpen is set does not swallow the next open after release", () => {
|
||||
const state = run(
|
||||
createTooltipState(true, false),
|
||||
TRIGGER_PRESSED,
|
||||
KOBALTE_CLOSED,
|
||||
UNCONTROLLED,
|
||||
POINTER_ENTERED,
|
||||
KOBALTE_OPENED,
|
||||
)
|
||||
|
||||
expect(selectTooltipOpen(state.state)).toBe(true)
|
||||
})
|
||||
|
||||
test("a press without a click still lets Escape close the tooltip", () => {
|
||||
const state = run(hoveredOpen(), TRIGGER_PRESSED, PRESS_ENDED, KOBALTE_CLOSED)
|
||||
|
||||
expect(state.state).toEqual({ status: "idle", hovered: true, disabled: false })
|
||||
})
|
||||
|
||||
test("the click that ends a press keeps the tooltip open once", () => {
|
||||
const clicked = run(hoveredOpen(), TRIGGER_PRESSED, KOBALTE_CLOSED)
|
||||
|
||||
expect(clicked.state).toEqual({ status: "open", hovered: true, pressing: false })
|
||||
expect(run(clicked.state, KOBALTE_CLOSED).state).toEqual({ status: "idle", hovered: true, disabled: false })
|
||||
})
|
||||
|
||||
test("a menu closed over a still pointer keeps the tooltip hidden until the pointer moves off", () => {
|
||||
// The menu's modal layer turns pointer events off, so the trigger hears a leave without the pointer moving, and an
|
||||
// enter when the menu closes.
|
||||
const closed = run(hoveredOpen(), TRIGGER_PRESSED, POPUP_EXPANDED, POINTER_LEFT, POPUP_COLLAPSED, POINTER_ENTERED)
|
||||
|
||||
expect(closed.state).toEqual({ status: "suppressed", popup: "closed", disabled: false })
|
||||
expect(selectTooltipOpen(run(closed.state, KOBALTE_OPENED, POINTER_INSIDE, KOBALTE_OPENED).state)).toBe(false)
|
||||
|
||||
const left = run(closed.state, POINTER_OUTSIDE)
|
||||
|
||||
expect(left.state).toEqual({ status: "idle", hovered: false, disabled: false })
|
||||
expect(selectTooltipOpen(run(left.state, POINTER_ENTERED, KOBALTE_OPENED).state)).toBe(true)
|
||||
})
|
||||
|
||||
test("a menu opened from the keyboard with the pointer elsewhere does not suppress the next hover", () => {
|
||||
const state = run(createTooltipState(undefined, false), FOCUSED, POPUP_EXPANDED, POPUP_COLLAPSED)
|
||||
|
||||
expect(state.state).toEqual({ status: "idle", hovered: false, disabled: false })
|
||||
})
|
||||
|
||||
test("focusing the trigger itself lifts suppression", () => {
|
||||
const closed = run(hoveredOpen(), POPUP_EXPANDED, POPUP_COLLAPSED)
|
||||
const state = run(closed.state, FOCUSED, KOBALTE_OPENED)
|
||||
|
||||
expect(closed.state.status).toBe("suppressed")
|
||||
expect(selectTooltipOpen(state.state)).toBe(true)
|
||||
})
|
||||
|
||||
test("the first hover or focus mounts Kobalte and replays the event", () => {
|
||||
const hovered = transitionTooltip(createTooltipState(undefined, false), POINTER_ENTERED)
|
||||
const focused = transitionTooltip(createTooltipState(undefined, false), FOCUSED)
|
||||
|
||||
expect(hovered).toEqual({ state: { status: "idle", hovered: true, disabled: false }, effects: ["replay"] })
|
||||
expect(focused).toEqual({ state: { status: "idle", hovered: false, disabled: false }, effects: ["replay"] })
|
||||
expect(selectTooltipMounted(hovered.state)).toBe(true)
|
||||
})
|
||||
|
||||
test("a popup already open when Kobalte mounts suppresses the replayed open", () => {
|
||||
const state = run(createTooltipState(undefined, false), FOCUSED, POPUP_EXPANDED, KOBALTE_OPENED)
|
||||
|
||||
expect(selectTooltipOpen(state.state)).toBe(false)
|
||||
expect(selectTooltipTracking(state.state)).toBe(true)
|
||||
})
|
||||
|
||||
test("leaving keeps the tooltip open until the microtask settles", () => {
|
||||
const left = run(hoveredOpen(), POINTER_LEFT)
|
||||
|
||||
expect(left.effects).toEqual(["schedule-leave"])
|
||||
expect(selectTooltipOpen(left.state)).toBe(true)
|
||||
expect(run(left.state, LEAVE_SETTLED).state).toEqual({ status: "idle", hovered: false, disabled: false })
|
||||
expect(selectTooltipOpen(run(left.state, POINTER_ENTERED, LEAVE_SETTLED).state)).toBe(true)
|
||||
})
|
||||
|
||||
test("disabled tooltips neither mount nor open, and disabling closes an open one", () => {
|
||||
const disabled = createTooltipState(undefined, true)
|
||||
|
||||
expect(transitionTooltip(disabled, POINTER_ENTERED).state).toBe(disabled)
|
||||
expect(transitionTooltip(disabled, FOCUSED).state).toBe(disabled)
|
||||
|
||||
const closed = run(hoveredOpen(), syncPropsEvent(undefined, true))
|
||||
|
||||
expect(closed.state).toEqual({ status: "idle", hovered: true, disabled: true })
|
||||
expect(transitionTooltip(closed.state, KOBALTE_OPENED).state).toBe(closed.state)
|
||||
})
|
||||
|
||||
test("forceOpen controls the tooltip and releasing it closes the tooltip", () => {
|
||||
const forced = run(createTooltipState(undefined, false), POINTER_ENTERED, syncPropsEvent(true, false))
|
||||
|
||||
expect(selectTooltipOpen(forced.state)).toBe(true)
|
||||
expect(selectTooltipForceOpen(forced.state)).toBe(true)
|
||||
expect(transitionTooltip(forced.state, KOBALTE_CLOSED).state).toBe(forced.state)
|
||||
expect(run(forced.state, UNCONTROLLED).state).toEqual({ status: "idle", hovered: true, disabled: false })
|
||||
expect(run(forced.state, POPUP_EXPANDED, UNCONTROLLED).state).toEqual({
|
||||
status: "suppressed",
|
||||
popup: "open",
|
||||
hovered: true,
|
||||
disabled: false,
|
||||
})
|
||||
})
|
||||
|
||||
test("disposal ends every state and ignores later events", () => {
|
||||
const disposed = transitionTooltip(hoveredOpen(), DISPOSED_EVENT).state
|
||||
|
||||
expect(disposed).toEqual({ status: "disposed" })
|
||||
expect(selectTooltipMounted(disposed)).toBe(false)
|
||||
expect(transitionTooltip(disposed, LEAVE_SETTLED).state).toBe(disposed)
|
||||
expect(transitionTooltip(disposed, PRESS_ENDED).state).toBe(disposed)
|
||||
})
|
||||
|
||||
test("every reachable state and transition is a frozen singleton", () => {
|
||||
const events = [
|
||||
POINTER_ENTERED,
|
||||
POINTER_LEFT,
|
||||
POINTER_INSIDE,
|
||||
POINTER_OUTSIDE,
|
||||
FOCUSED,
|
||||
TRIGGER_PRESSED,
|
||||
PRESS_ENDED,
|
||||
LEAVE_SETTLED,
|
||||
POPUP_EXPANDED,
|
||||
POPUP_COLLAPSED,
|
||||
KOBALTE_OPENED,
|
||||
KOBALTE_CLOSED,
|
||||
DISPOSED_EVENT,
|
||||
...[undefined, false, true].flatMap((forceOpen) =>
|
||||
[false, true].map((disabled) => syncPropsEvent(forceOpen, disabled)),
|
||||
),
|
||||
]
|
||||
|
||||
const reached = new Set(
|
||||
[undefined, false, true].flatMap((forceOpen) =>
|
||||
[false, true].map((disabled) => createTooltipState(forceOpen, disabled)),
|
||||
),
|
||||
)
|
||||
|
||||
for (const state of reached) {
|
||||
expect(Object.isFrozen(state)).toBe(true)
|
||||
|
||||
for (const event of events) {
|
||||
const transition = transitionTooltip(state, event)
|
||||
|
||||
expect(transitionTooltip(state, event)).toBe(transition)
|
||||
expect(Object.isFrozen(transition)).toBe(true)
|
||||
|
||||
if (transition.state === state) expect(transition.effects).toHaveLength(0)
|
||||
reached.add(transition.state)
|
||||
}
|
||||
}
|
||||
|
||||
expect(reached.size).toBe(33)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,303 @@
|
||||
/**
|
||||
* Every tooltip trigger runs this machine, so it never allocates: each reachable state, event and transition is a
|
||||
* frozen module singleton, and an event that changes nothing returns the state it was given.
|
||||
*/
|
||||
export type TooltipState =
|
||||
/** Kobalte is not mounted yet. Most triggers are never hovered, so it mounts on the first hover or focus. */
|
||||
| { readonly status: "unmounted"; readonly disabled: boolean }
|
||||
| { readonly status: "idle"; readonly hovered: boolean; readonly disabled: boolean }
|
||||
/** `pressing` lasts from a press on the trigger until that press ends, so its click keeps the tooltip open. */
|
||||
| { readonly status: "open"; readonly hovered: boolean; readonly pressing: boolean }
|
||||
/**
|
||||
* A popup the trigger opened (a menu, a popover) hides the tooltip. While it is open, a modal layer turns pointer
|
||||
* events off for the page, so the trigger's own enter and leave events lie and `hovered` follows the pointer's
|
||||
* position instead. Once it closes over a hovered trigger, the tooltip stays hidden until the pointer moves off the
|
||||
* trigger or the trigger itself takes focus.
|
||||
*/
|
||||
| { readonly status: "suppressed"; readonly popup: "open"; readonly hovered: boolean; readonly disabled: boolean }
|
||||
| { readonly status: "suppressed"; readonly popup: "closed"; readonly disabled: boolean }
|
||||
/** The caller sets `forceOpen`. `expanded` tracks the popup so releasing control can suppress the tooltip. */
|
||||
| {
|
||||
readonly status: "controlled"
|
||||
readonly open: boolean
|
||||
readonly hovered: boolean
|
||||
readonly expanded: boolean
|
||||
readonly disabled: boolean
|
||||
}
|
||||
| { readonly status: "disposed" }
|
||||
|
||||
export type TooltipEvent =
|
||||
| { readonly type: "props.synced"; readonly forceOpen: boolean | undefined; readonly disabled: boolean }
|
||||
/** The pointer entered or left the trigger. Touch never hovers. */
|
||||
| { readonly type: "pointer.entered" }
|
||||
| { readonly type: "pointer.left" }
|
||||
/** Where a pointer move landed while a popup suppresses the tooltip, measured against the trigger's box. */
|
||||
| { readonly type: "pointer.moved"; readonly inside: boolean }
|
||||
/** The trigger element itself took focus. */
|
||||
| { readonly type: "focused" }
|
||||
| { readonly type: "trigger.pressed" }
|
||||
/** The press ended, after the click it caused, if any. */
|
||||
| { readonly type: "press.ended" }
|
||||
/** The microtask after the pointer left, once Kobalte has seen the tooltip open and started its skip-delay window. */
|
||||
| { readonly type: "leave.settled" }
|
||||
| { readonly type: "popup.changed"; readonly expanded: boolean }
|
||||
| { readonly type: "kobalte.changed"; readonly open: boolean }
|
||||
| { readonly type: "disposed" }
|
||||
|
||||
/** `replay` forwards the mounting hover or focus to Kobalte, which attached its listeners too late to receive it. */
|
||||
export type TooltipEffect = "replay" | "schedule-leave"
|
||||
|
||||
export type TooltipTransition = {
|
||||
readonly state: TooltipState
|
||||
readonly effects: readonly TooltipEffect[]
|
||||
}
|
||||
|
||||
const settled = new Map<TooltipState, TooltipTransition>()
|
||||
|
||||
const NO_EFFECTS: readonly TooltipEffect[] = Object.freeze([])
|
||||
|
||||
function freeze<S extends TooltipState>(state: S) {
|
||||
Object.freeze(state)
|
||||
settled.set(state, Object.freeze({ state, effects: NO_EFFECTS }))
|
||||
|
||||
return state
|
||||
}
|
||||
|
||||
const bit = (value: boolean) => (value ? 1 : 0)
|
||||
|
||||
const UNMOUNTED = [false, true].map((disabled) => freeze({ status: "unmounted", disabled }))
|
||||
|
||||
const IDLE = [0, 1, 2, 3].map((key) => freeze({ status: "idle", hovered: !!(key & 1), disabled: !!(key & 2) }))
|
||||
|
||||
const OPEN = [0, 1, 2, 3].map((key) => freeze({ status: "open", hovered: !!(key & 1), pressing: !!(key & 2) }))
|
||||
|
||||
const POPUP_OPEN = [0, 1, 2, 3].map((key) =>
|
||||
freeze({ status: "suppressed", popup: "open", hovered: !!(key & 1), disabled: !!(key & 2) }),
|
||||
)
|
||||
|
||||
const POPUP_CLOSED = [false, true].map((disabled) => freeze({ status: "suppressed", popup: "closed", disabled }))
|
||||
|
||||
const CONTROLLED = Array.from({ length: 16 }, (_, key) =>
|
||||
freeze({
|
||||
status: "controlled",
|
||||
open: !!(key & 1),
|
||||
hovered: !!(key & 2),
|
||||
expanded: !!(key & 4),
|
||||
disabled: !!(key & 8),
|
||||
}),
|
||||
)
|
||||
|
||||
const DISPOSED = freeze({ status: "disposed" })
|
||||
|
||||
const unmounted = (disabled: boolean) => UNMOUNTED[bit(disabled)]
|
||||
|
||||
const idle = (hovered: boolean, disabled: boolean) => IDLE[bit(hovered) | (bit(disabled) << 1)]
|
||||
|
||||
const open = (hovered: boolean, pressing: boolean) => OPEN[bit(hovered) | (bit(pressing) << 1)]
|
||||
|
||||
const popupOpen = (hovered: boolean, disabled: boolean) => POPUP_OPEN[bit(hovered) | (bit(disabled) << 1)]
|
||||
|
||||
const popupClosed = (disabled: boolean) => POPUP_CLOSED[bit(disabled)]
|
||||
|
||||
const controlled = (open: boolean, hovered: boolean, expanded: boolean, disabled: boolean) =>
|
||||
CONTROLLED[bit(open) | (bit(hovered) << 1) | (bit(expanded) << 2) | (bit(disabled) << 3)]
|
||||
|
||||
const REPLAY: readonly TooltipEffect[] = Object.freeze(["replay"])
|
||||
|
||||
const REPLAY_HOVER: TooltipTransition = Object.freeze({ state: idle(true, false), effects: REPLAY })
|
||||
|
||||
const REPLAY_FOCUS: TooltipTransition = Object.freeze({ state: idle(false, false), effects: REPLAY })
|
||||
|
||||
const LEAVING: TooltipTransition = Object.freeze({
|
||||
state: open(false, false),
|
||||
effects: Object.freeze<TooltipEffect[]>(["schedule-leave"]),
|
||||
})
|
||||
|
||||
export const POINTER_ENTERED: TooltipEvent = Object.freeze({ type: "pointer.entered" })
|
||||
|
||||
export const POINTER_LEFT: TooltipEvent = Object.freeze({ type: "pointer.left" })
|
||||
|
||||
export const POINTER_INSIDE: TooltipEvent = Object.freeze({ type: "pointer.moved", inside: true })
|
||||
|
||||
export const POINTER_OUTSIDE: TooltipEvent = Object.freeze({ type: "pointer.moved", inside: false })
|
||||
|
||||
export const FOCUSED: TooltipEvent = Object.freeze({ type: "focused" })
|
||||
|
||||
export const TRIGGER_PRESSED: TooltipEvent = Object.freeze({ type: "trigger.pressed" })
|
||||
|
||||
export const PRESS_ENDED: TooltipEvent = Object.freeze({ type: "press.ended" })
|
||||
|
||||
export const LEAVE_SETTLED: TooltipEvent = Object.freeze({ type: "leave.settled" })
|
||||
|
||||
export const POPUP_EXPANDED: TooltipEvent = Object.freeze({ type: "popup.changed", expanded: true })
|
||||
|
||||
export const POPUP_COLLAPSED: TooltipEvent = Object.freeze({ type: "popup.changed", expanded: false })
|
||||
|
||||
export const KOBALTE_OPENED: TooltipEvent = Object.freeze({ type: "kobalte.changed", open: true })
|
||||
|
||||
export const KOBALTE_CLOSED: TooltipEvent = Object.freeze({ type: "kobalte.changed", open: false })
|
||||
|
||||
export const DISPOSED_EVENT: TooltipEvent = Object.freeze({ type: "disposed" })
|
||||
|
||||
const PROPS = [undefined, false, true].flatMap((forceOpen) =>
|
||||
[false, true].map((disabled): TooltipEvent => Object.freeze({ type: "props.synced", forceOpen, disabled })),
|
||||
)
|
||||
|
||||
export function syncPropsEvent(forceOpen: boolean | undefined, disabled: boolean) {
|
||||
return PROPS[(forceOpen === undefined ? 0 : forceOpen ? 4 : 2) + bit(disabled)]
|
||||
}
|
||||
|
||||
export function createTooltipState(forceOpen: boolean | undefined, disabled: boolean): TooltipState {
|
||||
if (forceOpen === undefined) return unmounted(disabled)
|
||||
|
||||
return controlled(forceOpen, false, false, disabled)
|
||||
}
|
||||
|
||||
export function transitionTooltip(state: TooltipState, event: TooltipEvent): TooltipTransition {
|
||||
const result = next(state, event)
|
||||
|
||||
if ("state" in result) return result
|
||||
|
||||
return settled.get(result)!
|
||||
}
|
||||
|
||||
/** Kobalte is mounted: the trigger owns its listeners and the popup observer runs. */
|
||||
export function selectTooltipMounted(state: TooltipState) {
|
||||
return state.status !== "unmounted" && state.status !== "disposed"
|
||||
}
|
||||
|
||||
export function selectTooltipOpen(state: TooltipState) {
|
||||
if (state.status === "open") return true
|
||||
|
||||
if (state.status === "controlled") return state.open
|
||||
|
||||
return false
|
||||
}
|
||||
|
||||
export function selectTooltipForceOpen(state: TooltipState) {
|
||||
return state.status === "controlled" ? state.open : undefined
|
||||
}
|
||||
|
||||
/** A press is in progress, so the driver listens for its end. */
|
||||
export function selectTooltipPressing(state: TooltipState) {
|
||||
return state.status === "open" && state.pressing
|
||||
}
|
||||
|
||||
/** A popup suppresses the tooltip, so the driver reports where the pointer moves. */
|
||||
export function selectTooltipTracking(state: TooltipState) {
|
||||
return state.status === "suppressed"
|
||||
}
|
||||
|
||||
function next(state: TooltipState, event: TooltipEvent): TooltipState | TooltipTransition {
|
||||
if (state.status === "disposed") return state
|
||||
|
||||
if (event.type === "disposed") return DISPOSED
|
||||
|
||||
if (event.type === "props.synced") return sync(state, event.forceOpen, event.disabled)
|
||||
|
||||
if (state.status === "unmounted") {
|
||||
if (state.disabled) return state
|
||||
|
||||
if (event.type === "pointer.entered") return REPLAY_HOVER
|
||||
|
||||
if (event.type === "focused") return REPLAY_FOCUS
|
||||
|
||||
return state
|
||||
}
|
||||
|
||||
if (state.status === "idle") {
|
||||
if (event.type === "pointer.entered") return idle(true, state.disabled)
|
||||
|
||||
if (event.type === "pointer.left") return idle(false, state.disabled)
|
||||
|
||||
if (event.type === "popup.changed" && event.expanded) return popupOpen(state.hovered, state.disabled)
|
||||
|
||||
if (event.type === "kobalte.changed" && event.open && !state.disabled) return open(state.hovered, false)
|
||||
|
||||
return state
|
||||
}
|
||||
|
||||
if (state.status === "open") {
|
||||
if (event.type === "pointer.entered") return open(true, state.pressing)
|
||||
|
||||
if (event.type === "pointer.left") return state.hovered || state.pressing ? LEAVING : state
|
||||
|
||||
if (event.type === "leave.settled") return state.hovered ? state : idle(false, false)
|
||||
|
||||
if (event.type === "trigger.pressed") return open(state.hovered, true)
|
||||
|
||||
if (event.type === "press.ended") return open(state.hovered, false)
|
||||
|
||||
if (event.type === "popup.changed" && event.expanded) return popupOpen(state.hovered, false)
|
||||
|
||||
// Kobalte closes the tooltip on every click of its trigger; the click that ends a press keeps it open.
|
||||
if (event.type === "kobalte.changed" && !event.open) {
|
||||
return state.pressing ? open(state.hovered, false) : idle(state.hovered, false)
|
||||
}
|
||||
|
||||
return state
|
||||
}
|
||||
|
||||
if (state.status === "suppressed") {
|
||||
if (event.type === "popup.changed" && event.expanded) {
|
||||
return popupOpen(state.popup === "closed" || state.hovered, state.disabled)
|
||||
}
|
||||
|
||||
if (state.popup === "open") {
|
||||
if (event.type === "pointer.moved") return popupOpen(event.inside, state.disabled)
|
||||
|
||||
if (event.type === "popup.changed") {
|
||||
return state.hovered ? popupClosed(state.disabled) : idle(false, state.disabled)
|
||||
}
|
||||
|
||||
return state
|
||||
}
|
||||
|
||||
if (event.type === "pointer.moved" && !event.inside) return idle(false, state.disabled)
|
||||
|
||||
if (event.type === "focused") return idle(true, state.disabled)
|
||||
|
||||
return state
|
||||
}
|
||||
|
||||
if (event.type === "pointer.entered") return controlled(state.open, true, state.expanded, state.disabled)
|
||||
|
||||
if (event.type === "pointer.left") return controlled(state.open, false, state.expanded, state.disabled)
|
||||
|
||||
if (event.type === "popup.changed") return controlled(state.open, state.hovered, event.expanded, state.disabled)
|
||||
|
||||
return state
|
||||
}
|
||||
|
||||
function sync(state: TooltipState, forceOpen: boolean | undefined, disabled: boolean) {
|
||||
if (state.status === "disposed") return state
|
||||
|
||||
if (forceOpen !== undefined) {
|
||||
if (state.status === "unmounted") return controlled(forceOpen, false, false, disabled)
|
||||
|
||||
if (state.status === "controlled") return controlled(forceOpen, state.hovered, state.expanded, disabled)
|
||||
|
||||
if (state.status === "suppressed" && state.popup === "open") {
|
||||
return controlled(forceOpen, state.hovered, true, disabled)
|
||||
}
|
||||
|
||||
if (state.status === "suppressed") return controlled(forceOpen, true, false, disabled)
|
||||
|
||||
return controlled(forceOpen, state.hovered, false, disabled)
|
||||
}
|
||||
|
||||
if (state.status === "unmounted") return unmounted(disabled)
|
||||
|
||||
if (state.status === "idle") return idle(state.hovered, disabled)
|
||||
|
||||
if (state.status === "open") return disabled ? idle(state.hovered, true) : state
|
||||
|
||||
if (state.status === "suppressed" && state.popup === "open") return popupOpen(state.hovered, disabled)
|
||||
|
||||
if (state.status === "suppressed") return popupClosed(disabled)
|
||||
|
||||
// Releasing control closes the tooltip; it opens again on the next hover or focus.
|
||||
if (state.expanded) return popupOpen(state.hovered, disabled)
|
||||
|
||||
return idle(state.hovered, disabled)
|
||||
}
|
||||
@@ -1,5 +1,7 @@
|
||||
import { Tooltip } from "./tooltip"
|
||||
import { Button } from "@opencode/ui/button"
|
||||
import { Keybind } from "@opencode/ui/keybind"
|
||||
import { Menu } from "@opencode/ui/menu"
|
||||
|
||||
const docs = `### Overview
|
||||
Floating tooltip built on Kobalte's tooltip primitive.
|
||||
@@ -73,6 +75,24 @@ export const WithKeybind = {
|
||||
),
|
||||
}
|
||||
|
||||
export const WithMenu = {
|
||||
render: () => (
|
||||
<div style={{ padding: "80px", display: "flex", "justify-content": "center" }}>
|
||||
<Tooltip value="More actions">
|
||||
<Menu gutter={6}>
|
||||
<Menu.Trigger as={Button}>Actions</Menu.Trigger>
|
||||
<Menu.Portal>
|
||||
<Menu.Content>
|
||||
<Menu.Item>Rename</Menu.Item>
|
||||
<Menu.Item>Delete</Menu.Item>
|
||||
</Menu.Content>
|
||||
</Menu.Portal>
|
||||
</Menu>
|
||||
</Tooltip>
|
||||
</div>
|
||||
),
|
||||
}
|
||||
|
||||
export const Path = {
|
||||
render: () => (
|
||||
<div style={{ padding: "80px", display: "flex", "justify-content": "center" }}>
|
||||
|
||||
@@ -1,8 +1,32 @@
|
||||
import { Content, Portal, Root, Trigger } from "@kobalte/core/tooltip"
|
||||
import { createComputed, createEffect, Match, onCleanup, Show, splitProps, Switch, untrack, type JSX } from "solid-js"
|
||||
import { createComputed, createSignal, onCleanup, onMount, Show, splitProps, untrack, type JSX } from "solid-js"
|
||||
import type { ComponentProps } from "solid-js"
|
||||
import { createStore } from "solid-js/store"
|
||||
import { spread } from "solid-js/web"
|
||||
import {
|
||||
createTooltipState,
|
||||
DISPOSED_EVENT,
|
||||
FOCUSED,
|
||||
KOBALTE_CLOSED,
|
||||
KOBALTE_OPENED,
|
||||
LEAVE_SETTLED,
|
||||
POINTER_ENTERED,
|
||||
POINTER_INSIDE,
|
||||
POINTER_LEFT,
|
||||
POINTER_OUTSIDE,
|
||||
POPUP_COLLAPSED,
|
||||
POPUP_EXPANDED,
|
||||
PRESS_ENDED,
|
||||
selectTooltipForceOpen,
|
||||
selectTooltipMounted,
|
||||
selectTooltipOpen,
|
||||
selectTooltipPressing,
|
||||
selectTooltipTracking,
|
||||
syncPropsEvent,
|
||||
transitionTooltip,
|
||||
TRIGGER_PRESSED,
|
||||
type TooltipEvent,
|
||||
type TooltipState,
|
||||
} from "./machine"
|
||||
import "./tooltip.css"
|
||||
|
||||
export interface TooltipProps extends ComponentProps<typeof Root> {
|
||||
@@ -21,19 +45,21 @@ type TriggerHandlers = {
|
||||
onFocus?: (event: FocusEvent) => void
|
||||
}
|
||||
|
||||
// Expanded panels still need tooltips; only an open popup suppresses its trigger's tooltip.
|
||||
const POPUP = '[aria-haspopup]:not([aria-haspopup="false"]):is([aria-expanded="true"], [data-expanded])'
|
||||
|
||||
export function Tooltip(props: TooltipProps) {
|
||||
return (
|
||||
<Show when={!props.inactive} fallback={props.children}>
|
||||
<ActiveTooltip {...props} />
|
||||
</Show>
|
||||
)
|
||||
}
|
||||
|
||||
function ActiveTooltip(props: TooltipProps) {
|
||||
let ref: HTMLDivElement | undefined
|
||||
let handlers: TriggerHandlers | undefined
|
||||
|
||||
const [state, setState] = createStore({
|
||||
open: false,
|
||||
block: false,
|
||||
expand: false,
|
||||
// Kobalte's tooltip costs dozens of computations and listeners per trigger, and most triggers (an action on every
|
||||
// timeline row, a copy button on every code block) are never hovered. It mounts on the first interaction that
|
||||
// could open it, or as soon as a caller controls it with forceOpen.
|
||||
mounted: false,
|
||||
})
|
||||
let observer: MutationObserver | undefined
|
||||
|
||||
const [local, others] = splitProps(props, [
|
||||
"children",
|
||||
@@ -48,80 +74,89 @@ export function Tooltip(props: TooltipProps) {
|
||||
"value",
|
||||
])
|
||||
|
||||
const close = () => setState("open", false)
|
||||
const controlled = () => local.forceOpen !== undefined
|
||||
// Kobalte's tooltip costs dozens of computations and listeners per trigger, and most triggers (an action on every
|
||||
// timeline row, a copy button on every code block) are never hovered. It mounts on the first interaction that could
|
||||
// open it, or as soon as a caller controls it with forceOpen.
|
||||
const [tooltip, setTooltip] = createSignal(createTooltipState(local.forceOpen, !!others.disabled))
|
||||
|
||||
const inside = () => {
|
||||
const active = document.activeElement
|
||||
const dispatch = (event: TooltipEvent, source?: PointerEvent | FocusEvent) => {
|
||||
const previous = untrack(tooltip)
|
||||
const transition = transitionTooltip(previous, event)
|
||||
|
||||
if (!ref || !active) return false
|
||||
if (transition.state !== previous) {
|
||||
setTooltip(transition.state)
|
||||
reconcile(previous, transition.state)
|
||||
}
|
||||
|
||||
return ref.contains(active)
|
||||
for (const effect of transition.effects) {
|
||||
if (effect === "schedule-leave") queueMicrotask(settleLeave)
|
||||
|
||||
// Kobalte attached its listeners while this event was being dispatched, too late to receive it.
|
||||
if (effect === "replay" && source instanceof PointerEvent) handlers?.onPointerEnter?.(source)
|
||||
|
||||
if (effect === "replay" && source instanceof FocusEvent) handlers?.onFocus?.(source)
|
||||
}
|
||||
}
|
||||
|
||||
const drop = (expand = state.expand) => {
|
||||
if (expand || !state.block) return
|
||||
// Kobalte's own pointerleave handler runs after this one and only starts the skip-delay window for neighbouring
|
||||
// tooltips if it still sees this one open.
|
||||
const settleLeave = () => dispatch(LEAVE_SETTLED)
|
||||
const syncPopup = () => dispatch(ref?.querySelector(POPUP) ? POPUP_EXPANDED : POPUP_COLLAPSED)
|
||||
// The press's click, if any, follows its pointerup in the same task.
|
||||
const onPressEnd = () => setTimeout(dispatch, 0, PRESS_ENDED)
|
||||
|
||||
if (ref?.matches(":hover")) return
|
||||
const onPointerMove = (event: PointerEvent) => {
|
||||
if (!ref) return
|
||||
const box = ref.getBoundingClientRect()
|
||||
|
||||
if (inside()) return
|
||||
setState("block", false)
|
||||
const inside =
|
||||
event.clientX >= box.left && event.clientX <= box.right && event.clientY >= box.top && event.clientY <= box.bottom
|
||||
|
||||
dispatch(inside ? POINTER_INSIDE : POINTER_OUTSIDE)
|
||||
}
|
||||
|
||||
const sync = () => {
|
||||
// Expanded panels still need tooltips; only an open popup suppresses its trigger's tooltip.
|
||||
const expand = !!ref?.querySelector(
|
||||
'[aria-haspopup]:not([aria-haspopup="false"]):is([aria-expanded="true"], [data-expanded])',
|
||||
)
|
||||
// Attaches the listeners and observer the state needs and detaches the rest.
|
||||
const reconcile = (previous: TooltipState, state: TooltipState) => {
|
||||
const pressing = selectTooltipPressing(state)
|
||||
|
||||
setState("expand", expand)
|
||||
if (pressing && !selectTooltipPressing(previous)) {
|
||||
window.addEventListener("pointerup", onPressEnd, true)
|
||||
window.addEventListener("pointercancel", onPressEnd, true)
|
||||
}
|
||||
|
||||
if (expand) {
|
||||
setState("block", true)
|
||||
close()
|
||||
if (!pressing && selectTooltipPressing(previous)) {
|
||||
window.removeEventListener("pointerup", onPressEnd, true)
|
||||
window.removeEventListener("pointercancel", onPressEnd, true)
|
||||
}
|
||||
|
||||
const tracking = selectTooltipTracking(state)
|
||||
|
||||
if (tracking && !selectTooltipTracking(previous)) {
|
||||
window.addEventListener("pointermove", onPointerMove, { capture: true, passive: true })
|
||||
}
|
||||
|
||||
if (!tracking && selectTooltipTracking(previous)) window.removeEventListener("pointermove", onPointerMove, true)
|
||||
|
||||
if (state.status === "disposed") {
|
||||
observer?.disconnect()
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
drop(expand)
|
||||
}
|
||||
|
||||
const leave = () => {
|
||||
// Kobalte's own pointerleave handler runs after this one and only starts the
|
||||
// skip-delay window for neighbouring tooltips if it still sees this one open.
|
||||
queueMicrotask(() => {
|
||||
if (!inside()) close()
|
||||
drop()
|
||||
})
|
||||
}
|
||||
|
||||
const mount = (event: PointerEvent | FocusEvent) => {
|
||||
if (state.mounted) return
|
||||
setState("mounted", true)
|
||||
|
||||
// Kobalte attached its listeners while this event was being dispatched, too late to receive it.
|
||||
if (event instanceof PointerEvent) handlers?.onPointerEnter?.(event)
|
||||
else handlers?.onFocus?.(event)
|
||||
}
|
||||
|
||||
createComputed(() => {
|
||||
if (controlled()) setState("mounted", true)
|
||||
})
|
||||
|
||||
createEffect(() => {
|
||||
if (!ref || !state.mounted) return
|
||||
untrack(sync)
|
||||
const obs = new MutationObserver(sync)
|
||||
obs.observe(ref, {
|
||||
if (!ref || observer || !selectTooltipMounted(state)) return
|
||||
observer = new MutationObserver(syncPopup)
|
||||
observer.observe(ref, {
|
||||
subtree: true,
|
||||
childList: true,
|
||||
attributes: true,
|
||||
attributeFilter: ["aria-expanded", "data-expanded", "aria-haspopup"],
|
||||
})
|
||||
onCleanup(() => obs.disconnect())
|
||||
})
|
||||
syncPopup()
|
||||
}
|
||||
|
||||
let justClickedTrigger = false
|
||||
createComputed(() => dispatch(syncPropsEvent(local.forceOpen, !!others.disabled)))
|
||||
onMount(() => reconcile(untrack(tooltip), untrack(tooltip)))
|
||||
onCleanup(() => dispatch(DISPOSED_EVENT))
|
||||
|
||||
// Kobalte's trigger takes over the element rendered below instead of rendering one, so mounting the tooltip leaves
|
||||
// the trigger and its children in place, with their focus and hover.
|
||||
@@ -138,78 +173,70 @@ export function Tooltip(props: TooltipProps) {
|
||||
}
|
||||
|
||||
return (
|
||||
<Switch>
|
||||
<Match when={local.inactive}>{local.children}</Match>
|
||||
<Match when={true}>
|
||||
<div
|
||||
ref={(el) => {
|
||||
ref = el
|
||||
// Kobalte's trigger sets this on the element it renders; it sets it again here once it mounts.
|
||||
el.setAttribute("type", "button")
|
||||
}}
|
||||
data-closed=""
|
||||
tabIndex={local.triggerTabIndex}
|
||||
data-component="tooltip-v2-trigger"
|
||||
class={local.class}
|
||||
onPointerEnter={mount}
|
||||
onFocus={mount}
|
||||
onFocusOut={() => requestAnimationFrame(() => drop())}
|
||||
<>
|
||||
{/* These listeners are attached before Kobalte's, so the machine sees each hover and focus first. */}
|
||||
<div
|
||||
ref={(el) => {
|
||||
ref = el
|
||||
// Kobalte's trigger sets this on the element it renders; it sets it again here once it mounts.
|
||||
el.setAttribute("type", "button")
|
||||
}}
|
||||
data-closed=""
|
||||
tabIndex={local.triggerTabIndex}
|
||||
data-component="tooltip-v2-trigger"
|
||||
class={local.class}
|
||||
onPointerEnter={(event) => {
|
||||
if (event.pointerType !== "touch") dispatch(POINTER_ENTERED, event)
|
||||
}}
|
||||
onFocus={(event) => dispatch(FOCUSED, event)}
|
||||
>
|
||||
{local.children}
|
||||
</div>
|
||||
<Show when={selectTooltipMounted(tooltip())}>
|
||||
<Root
|
||||
gutter={4}
|
||||
openDelay={400}
|
||||
skipDelayDuration={300}
|
||||
{...others}
|
||||
closeDelay={0}
|
||||
ignoreSafeArea={local.ignoreSafeArea ?? true}
|
||||
open={selectTooltipOpen(tooltip())}
|
||||
onOpenChange={(open) => dispatch(open ? KOBALTE_OPENED : KOBALTE_CLOSED)}
|
||||
>
|
||||
{local.children}
|
||||
</div>
|
||||
<Show when={state.mounted}>
|
||||
<Root
|
||||
gutter={4}
|
||||
openDelay={400}
|
||||
skipDelayDuration={300}
|
||||
{...others}
|
||||
closeDelay={0}
|
||||
ignoreSafeArea={local.ignoreSafeArea ?? true}
|
||||
open={controlled() ? local.forceOpen : state.open}
|
||||
onOpenChange={(open) => {
|
||||
if (controlled()) return
|
||||
|
||||
if (state.block && open) return
|
||||
|
||||
if (justClickedTrigger) {
|
||||
justClickedTrigger = false
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
setState("open", open)
|
||||
{/* Kobalte calls these inside its own listeners. As separate listeners, the leave microtask would close the
|
||||
tooltip before Kobalte's listener ran, which then skipped the skip-delay window. */}
|
||||
<Trigger
|
||||
as={adopt}
|
||||
onPointerDown={() => dispatch(TRIGGER_PRESSED)}
|
||||
onPointerLeave={(event: PointerEvent) => {
|
||||
if (event.pointerType !== "touch") dispatch(POINTER_LEFT)
|
||||
}}
|
||||
>
|
||||
{/* Kobalte calls leave inside its own pointerleave listener. As a separate listener, its microtask would
|
||||
close the tooltip before Kobalte's listener ran, which then skipped the skip-delay window. */}
|
||||
<Trigger as={adopt} onPointerLeave={leave} />
|
||||
<Portal>
|
||||
<Content
|
||||
ref={(el) => {
|
||||
const theme = ref?.closest("[data-theme]")?.getAttribute("data-theme")
|
||||
/>
|
||||
<Portal>
|
||||
<Content
|
||||
ref={(el) => {
|
||||
const theme = ref?.closest("[data-theme]")?.getAttribute("data-theme")
|
||||
|
||||
if (theme) el.setAttribute("data-theme", theme)
|
||||
}}
|
||||
data-component="tooltip-v2"
|
||||
data-appearance={local.appearance ?? "compact"}
|
||||
data-placement={props.placement}
|
||||
data-force-open={local.forceOpen}
|
||||
class={local.contentClass}
|
||||
style={local.contentStyle}
|
||||
onPointerDownOutside={(e) => {
|
||||
if (ref === e.target || (e.target instanceof Node && ref?.contains(e.target))) {
|
||||
justClickedTrigger = true
|
||||
}
|
||||
|
||||
e.preventDefault()
|
||||
}}
|
||||
>
|
||||
{local.value}
|
||||
</Content>
|
||||
</Portal>
|
||||
</Root>
|
||||
</Show>
|
||||
</Match>
|
||||
</Switch>
|
||||
if (theme) el.setAttribute("data-theme", theme)
|
||||
}}
|
||||
data-component="tooltip-v2"
|
||||
data-appearance={local.appearance ?? "compact"}
|
||||
data-placement={props.placement}
|
||||
data-force-open={selectTooltipForceOpen(tooltip())}
|
||||
class={local.contentClass}
|
||||
style={local.contentStyle}
|
||||
onPointerDownOutside={preventDismiss}
|
||||
>
|
||||
{local.value}
|
||||
</Content>
|
||||
</Portal>
|
||||
</Root>
|
||||
</Show>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
// A press on the trigger is outside the tooltip's layer; the machine decides whether it closes the tooltip.
|
||||
function preventDismiss(event: Event) {
|
||||
event.preventDefault()
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user