Skip to content

Open-source Grok Bot alternative with a virtual machine that bots can use

Menus open on press in 100 ms and close at once; dialogs cut in; rows hover without a fade (#8266)

Milind Soni7ed6116390d0
diff --git a/src/components/ApprovalModeSelector.tsx b/src/components/ApprovalModeSelector.tsx
index 5ee75c39d5..f59da07e98 100644
--- a/src/components/ApprovalModeSelector.tsx
+++ b/src/components/ApprovalModeSelector.tsx
@@ -4,6 +4,7 @@ import { Check, ChevronDown, ListChecks } from "lucide-react";
import { approvalModeFor, type ApprovalMode } from "../../shared/approval-mode";
import { cn } from "@/lib/cn";
import { useMenuMotion } from "./MenuMotion";
+import { useMenuPress } from "./menu-press";
import { MENU_ITEM_SEPARATOR, MENU_SHEET } from "./menu-recipe";
import { APPROVAL_LEVELS_URL, openExternalLink } from "@/lib/app-links";
import { t } from "@/lib/i18n";
@@ -50,6 +51,7 @@ export function ApprovalModeSelector({
}) {
const [open, setOpen] = useState(false);
const motion = useMenuMotion(open);
+ const press = useMenuPress(() => setOpen((value) => !value));
const wrapperRef = useRef<HTMLDivElement>(null);
const triggerRef = useRef<HTMLButtonElement>(null);
const mode = shownApprovalMode(driverKind, approvalModeFor({ approvalMode, autoApprove }));
@@ -106,7 +108,7 @@ export function ApprovalModeSelector({
aria-expanded={open}
aria-label={t("approvalMode.triggerAria", { mode: current.label, provider: providerName })}
title={wide ? undefined : current.chip}
- onClick={() => setOpen((value) => !value)}
+ {...press.triggerProps}
className={cn(
wide
? "flex h-10 w-full items-center justify-between rounded-lg border border-hairline/40 bg-inset px-3.5 text-[13px] text-ink hover:bg-raised"
diff --git a/src/components/CallView.live-mode.test.ts b/src/components/CallView.live-mode.test.ts
index 954894b8f7..ce1c8759b9 100644
--- a/src/components/CallView.live-mode.test.ts
+++ b/src/components/CallView.live-mode.test.ts
@@ -118,7 +118,7 @@ describe("call modes", () => {
// no plan to buy and no key field: the key goes in Settings → API keys
for (const gone of ["Pro plan", "Start free trial", 'type="password"']) expect(header).not.toContain(gone);
expect(header).toMatch(/aria-expanded="true" aria-controls="[^"]+"[^>]*aria-label="Live call with Atlas"/);
- const popup = /<div id="([^"]+)" class="animate-pop-in/.exec(header);
+ const popup = /<div id="([^"]+)" class="animate-menu-in/.exec(header);
expect(popup).not.toBeNull();
expect(header).toContain(`aria-controls="${popup![1]}"`);
const composer = render(createElement(CallButton, { bot, placement: "composer" }));
diff --git a/src/components/CallView.tsx b/src/components/CallView.tsx
index b06e08667c..a37edf61ce 100644
--- a/src/components/CallView.tsx
+++ b/src/components/CallView.tsx
@@ -375,7 +375,7 @@ export function CallTargetButton({
<div
ref={keyRef}
id={keyId}
- className={cn("animate-pop-in absolute right-0 z-30 max-h-[calc(100dvh-80px)] w-[340px] max-w-[90vw] overflow-y-auto overscroll-contain rounded-xl shadow-2xl", composer ? "bottom-full mb-1.5" : "top-full mt-1.5")}
+ className={cn("animate-menu-in absolute right-0 z-30 max-h-[calc(100dvh-80px)] w-[340px] max-w-[90vw] overflow-y-auto overscroll-contain rounded-xl shadow-2xl", composer ? "bottom-full mb-1.5" : "top-full mt-1.5")}
>
<LiveKeyNeeded override={liveOverride} />
</div>
@@ -466,7 +466,7 @@ export function CallModeMenu({ id, mode, onChoose, onClose, placement = "header"
if (event.key === "Tab") onClose();
else navigateThreadMenu(event);
}}
- className={cn("animate-pop-in absolute right-0 z-30 w-[280px] text-left", MENU_SHEET, placement === "composer" ? "bottom-full mb-1.5" : "top-full mt-1.5")}
+ className={cn("animate-menu-in absolute right-0 z-30 w-[280px] text-left", MENU_SHEET, placement === "composer" ? "bottom-full mb-1.5" : "top-full mt-1.5")}
>
{CALL_MODES.map((entry) => {
const unavailable = entry.id === "turns" ? turnsUnavailable : null;
diff --git a/src/components/ComposerContextMenu.tsx b/src/components/ComposerContextMenu.tsx
index 520fd5c49a..3f4ed6d673 100644
--- a/src/components/ComposerContextMenu.tsx
+++ b/src/components/ComposerContextMenu.tsx
@@ -225,7 +225,7 @@ export function ComposerContextMenu({ bot, group, members, className, handle }:
</button>
{open && (
<div ref={panel} role="dialog" tabIndex={-1} aria-label={t("contextMenu.title")} data-context-panel
- className={cn("animate-pop-in absolute bottom-full end-0 z-50 mb-2 max-h-[min(28rem,calc(100dvh-8rem))] w-72 max-w-[calc(100vw-1.5rem)] overflow-y-auto overscroll-contain outline-none", MENU_SHEET)}>
+ className={cn("animate-menu-in absolute bottom-full end-0 z-50 mb-2 max-h-[min(28rem,calc(100dvh-8rem))] w-72 max-w-[calc(100vw-1.5rem)] overflow-y-auto overscroll-contain outline-none", MENU_SHEET)}>
{group ? <RoomContext group={group} members={members ?? []} detailed={advanced} /> : bot && <ChatContext bot={bot} reading={fullest ?? null} breakdown={breakdown} detailed={advanced} onDone={close} />}
</div>
)}
diff --git a/src/components/ComposerPlusMenu.tsx b/src/components/ComposerPlusMenu.tsx
index 08677343a7..23f9232905 100644
--- a/src/components/ComposerPlusMenu.tsx
+++ b/src/components/ComposerPlusMenu.tsx
@@ -21,6 +21,7 @@ import { t } from "@/lib/i18n";
import { useDesktopCapabilities } from "./DesktopCapabilities";
import { liveLineHeldElsewhere } from "./LiveCallBar";
import { useMenuMotion } from "./MenuMotion";
+import { returnMenuFocus, useMenuPress } from "./menu-press";
import { nextMenuIndex, SidebarPopoverMenu, type SidebarMenuItem } from "./SidebarPopoverMenu";
import type { ApprovalChoice } from "./thread-approval";
import { SIMPLE_CONTROL } from "./composer-simple";
@@ -243,9 +244,15 @@ function ComposerMenu({ items, renderTrigger }: { items: SidebarMenuItem[]; rend
const triggerRef = useRef<HTMLButtonElement>(null);
const menuRef = useRef<HTMLDivElement>(null);
const menuId = useId();
+ // The mouse opens it on the press; a tap, Enter and Space on the click. A key press lands on the first row.
+ const press = useMenuPress((how) => {
+ const opening = !open;
+ setOpen(opening);
+ if (opening && how === "keyboard") requestAnimationFrame(() => rows()[0]?.focus());
+ });
const close = (refocus: boolean) => {
setOpen(false);
- if (refocus) triggerRef.current?.focus();
+ if (refocus) returnMenuFocus(triggerRef.current, press.last.current, menuRef.current);
};
useEffect(() => {
if (!open) return;
@@ -279,12 +286,7 @@ function ComposerMenu({ items, renderTrigger }: { items: SidebarMenuItem[]; rend
aria-controls={open ? menuId : undefined}
aria-label={t("common.add")}
title={t("common.add")}
- onClick={(event) => {
- const opening = !open;
- setOpen(opening);
- // A keyboard press lands on the first row, as every menu here does.
- if (opening && event.detail === 0) requestAnimationFrame(() => rows()[0]?.focus());
- }}
+ {...press.triggerProps}
className="flex shrink-0 rounded-full"
>
{renderTrigger(open)}
@@ -298,7 +300,7 @@ function ComposerMenu({ items, renderTrigger }: { items: SidebarMenuItem[]; rend
data-composer-menu
{...motion.exitProps}
className={cn(
- "popover-surface absolute bottom-full start-0 z-40 mb-2 w-max min-w-[200px] max-w-[280px] origin-bottom-left rounded-[12px] border-[0.5px] border-ink/10 bg-menu p-1",
+ "popover-surface absolute bottom-full start-0 z-40 mb-2 w-max min-w-[200px] max-w-[280px] origin-bottom-left rtl:origin-bottom-right rounded-[12px] border-[0.5px] border-ink/10 bg-menu p-1",
motion.className,
)}
>
@@ -313,7 +315,7 @@ function ComposerMenu({ items, renderTrigger }: { items: SidebarMenuItem[]; rend
close(false);
item.onSelect();
}}
- className="flex h-8 w-full items-center gap-2 rounded-md px-2 py-1.5 text-start text-[14px] leading-5 text-ink transition-colors hover:bg-menu-hover focus-visible:bg-menu-hover focus-visible:outline-none disabled:opacity-50"
+ className="flex h-8 w-full items-center gap-2 rounded-md px-2 py-1.5 text-start text-[14px] leading-5 text-ink hover:bg-menu-hover focus-visible:bg-menu-hover focus-visible:outline-none disabled:opacity-50"
>
<span className={cn("flex size-4 shrink-0 items-center justify-center [&_svg]:size-4", item.active ? "text-accent" : "text-ink-secondary")} aria-hidden="true">{item.icon}</span>
<span className="min-w-0 flex-1 truncate">{item.label}</span>
diff --git a/src/components/ExportTranscriptMenu.tsx b/src/components/ExportTranscriptMenu.tsx
index 353dfab263..54e4472ba8 100644
--- a/src/components/ExportTranscriptMenu.tsx
+++ b/src/components/ExportTranscriptMenu.tsx
@@ -3,6 +3,7 @@ import { Check, Copy, Download, Share } from "lucide-react";
import { cn } from "@/lib/cn";
import { useMenuMotion } from "./MenuMotion";
+import { useMenuPress } from "./menu-press";
import { t } from "@/lib/i18n";
import {
copyTranscriptToClipboard,
@@ -30,6 +31,7 @@ export function ExportTranscriptMenu({
}: ExportTranscriptMenuProps) {
const [open, setOpen] = useState(false);
const motion = useMenuMotion(open);
+ const press = useMenuPress(() => setOpen((prev) => !prev));
const [copied, setCopied] = useState(false);
const [copyFailed, setCopyFailed] = useState(false);
const menuRef = useRef<HTMLDivElement>(null);
@@ -98,7 +100,7 @@ export function ExportTranscriptMenu({
<div className="relative" ref={menuRef}>
<button
type="button"
- onClick={() => setOpen((prev) => !prev)}
+ {...press.triggerProps}
aria-label={t("chat.export.label")}
aria-haspopup="menu"
aria-expanded={open}
diff --git a/src/components/MenuMotion.test.ts b/src/components/MenuMotion.test.ts
index e1e54cd57d..d4273dafe6 100644
--- a/src/components/MenuMotion.test.ts
+++ b/src/components/MenuMotion.test.ts
@@ -1,128 +1,43 @@
-import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { readFileSync } from "node:fs";
+import { describe, expect, it } from "vitest";
+import { HOVER_MS, MENU_ENTER, MENU_ENTER_MS, MENU_EXIT_MS, PILL_HOVER_MS, useHeldMenuMotion, useMenuMotion } from "./MenuMotion";
-// No DOM here: state is held by call order, layout effects run after each render when their deps change, and a state
-// change renders again.
-const react = vi.hoisted(() => {
- const slots: unknown[] = [];
- const effects: Array<{ deps: unknown[]; cleanup: void | (() => void) }> = [];
- let queued: Array<() => void> = [];
- let cursor = 0;
- let effectCursor = 0;
- let changed = false;
- return {
- reset() {
- for (const effect of effects) if (typeof effect.cleanup === "function") effect.cleanup();
- slots.length = 0;
- effects.length = 0;
- },
- render<T>(hook: () => T): T {
- let result: T;
- let passes = 0;
- do {
- if (++passes > 10) throw new Error("hook never settled");
- changed = false;
- cursor = 0;
- effectCursor = 0;
- queued = [];
- result = hook();
- for (const run of queued) run();
- } while (changed);
- return result;
- },
- useState(initial: unknown) {
- const index = cursor++;
- if (!(index in slots)) slots[index] = initial;
- return [slots[index], (next: unknown) => {
- const value = typeof next === "function" ? (next as (current: unknown) => unknown)(slots[index]) : next;
- if (Object.is(value, slots[index])) return;
- slots[index] = value;
- changed = true;
- }];
- },
- useRef(initial: unknown) {
- const index = cursor++;
- if (!(index in slots)) slots[index] = { current: initial };
- return slots[index];
- },
- useLayoutEffect(effect: () => void | (() => void), deps: unknown[]) {
- const index = effectCursor++;
- const previous = effects[index];
- if (previous && deps.every((dep, at) => Object.is(dep, previous.deps[at]))) return;
- queued.push(() => {
- if (typeof previous?.cleanup === "function") previous.cleanup();
- effects[index] = { deps, cleanup: effect() };
- });
- },
- get changed() { return changed; },
- };
-});
-vi.mock("react", async (importOriginal) => ({
- ...(await importOriginal<typeof import("react")>()),
- useState: react.useState,
- useRef: react.useRef,
- useLayoutEffect: react.useLayoutEffect,
-}));
-
-const { MENU_MOTION_MS, useHeldMenuMotion, useMenuMotion } = await import("./MenuMotion");
-
-let reduced = false;
-beforeEach(() => {
- vi.useFakeTimers();
- reduced = false;
- vi.stubGlobal("window", {
- setTimeout: (run: () => void, ms: number) => setTimeout(run, ms),
- clearTimeout: (id: ReturnType<typeof setTimeout>) => clearTimeout(id),
- matchMedia: () => ({ matches: reduced }),
- });
- vi.stubGlobal("document", { documentElement: { dataset: {} } });
-});
-afterEach(() => {
- react.reset();
- vi.useRealTimers();
- vi.unstubAllGlobals();
-});
+const css = readFileSync(new URL("../styles.css", import.meta.url), "utf8");
+const token = (name: string) => new RegExp(`--${name}:\\s*([^;]+);`).exec(css)?.[1]?.trim();
describe("menu motion", () => {
- it("shows a menu on the render it opens and pops it in", () => {
- expect(react.render(() => useMenuMotion(false))).toMatchObject({ shown: false, closing: false });
- const open = react.render(() => useMenuMotion(true));
- expect(open).toMatchObject({ shown: true, closing: false, className: "animate-pop-in", exitProps: {} });
+ it("shows a menu on the render it opens, entering from its trigger", () => {
+ expect(useMenuMotion(false)).toMatchObject({ shown: false, closing: false, className: "" });
+ expect(useMenuMotion(true)).toEqual({ shown: true, closing: false, className: MENU_ENTER, exitProps: {} });
});
- it("keeps a closing menu on screen for the pop, but out of reach and out of the accessibility tree", () => {
- react.render(() => useMenuMotion(true));
- const closing = react.render(() => useMenuMotion(false));
- expect(closing.shown).toBe(true);
- expect(closing.closing).toBe(true);
- expect(closing.className).toBe("animate-pop-out pointer-events-none");
- expect(closing.exitProps).toEqual({ inert: true, "aria-hidden": true });
- vi.advanceTimersByTime(MENU_MOTION_MS - 1);
- expect(react.render(() => useMenuMotion(false)).shown).toBe(true);
- vi.advanceTimersByTime(1);
- expect(react.changed).toBe(true);
- expect(react.render(() => useMenuMotion(false))).toMatchObject({ shown: false, closing: false, exitProps: {} });
+ it("removes a menu on the render it closes: no exit animation, nothing left inert on screen", () => {
+ expect(MENU_EXIT_MS).toBe(0);
+ expect(useMenuMotion(false)).toEqual({ shown: false, closing: false, className: "", exitProps: {} });
});
- it("closes at once under reduced motion", () => {
- reduced = true;
- react.render(() => useMenuMotion(true));
- expect(react.render(() => useMenuMotion(false))).toMatchObject({ shown: false, closing: false, exitProps: {} });
+ it("puts a context menu up on one frame and holds its payload only while open", () => {
+ const anchor = { x: 10, y: 20 };
+ expect(useHeldMenuMotion(anchor)).toEqual({ shown: true, closing: false, className: "", exitProps: {}, value: anchor });
+ expect(useHeldMenuMotion<typeof anchor>(null)).toMatchObject({ shown: false, value: null });
+ expect(useMenuMotion(true, "instant").className).toBe("");
});
- it("reopens a menu that is still closing as a live menu", () => {
- react.render(() => useMenuMotion(true));
- react.render(() => useMenuMotion(false));
- const reopened = react.render(() => useMenuMotion(true));
- expect(reopened).toMatchObject({ shown: true, closing: false, className: "animate-pop-in", exitProps: {} });
- vi.advanceTimersByTime(MENU_MOTION_MS * 2);
- expect(react.render(() => useMenuMotion(true)).shown).toBe(true);
+ it("names the same timings styles.css draws with", () => {
+ expect(token("motion-menu-enter")).toBe(`${MENU_ENTER_MS}ms`);
+ expect(token("motion-hover")).toBe(`${HOVER_MS}ms`);
+ expect(token("motion-pill-hover")).toBe(`${PILL_HOVER_MS}ms`);
+ expect(token("animate-menu-in")).toBe("menu-in var(--motion-menu-enter) var(--motion-menu-ease) both");
+ // A dialog cuts in on one frame.
+ expect(token("animate-pop-in")).toBe("none");
+ // The first painted frame of a menu is already 40% there, and only transform and opacity move.
+ const keyframes = /@keyframes menu-in \{([\s\S]*?)\n\}/.exec(css)?.[1] ?? "";
+ expect(keyframes).toMatch(/from \{ transform: scale\(0\.96\); opacity: 0\.4; \}/);
+ expect(keyframes.replace(/transform|opacity|scale|from|to/g, "")).not.toMatch(/[a-z]{3,}:/);
});
- it("holds the last payload while a positioned menu closes", () => {
- const anchor = { x: 10, y: 20 };
- react.render(() => useHeldMenuMotion(anchor));
- const closing = react.render(() => useHeldMenuMotion<typeof anchor>(null));
- expect(closing).toMatchObject({ shown: true, closing: true, value: anchor });
- expect(closing.exitProps).toEqual({ inert: true, "aria-hidden": true });
+ it("is still under reduced motion", () => {
+ expect(css).toContain(".animate-pop-in, .animate-pop-out, .animate-menu-in { animation: none; }");
+ expect(css).toContain(':root[data-reduced-motion="true"] .animate-menu-in,');
});
});
diff --git a/src/components/MenuMotion.tsx b/src/components/MenuMotion.tsx
index ec3ab6a2af..8f74909af2 100644
--- a/src/components/MenuMotion.tsx
+++ b/src/components/MenuMotion.tsx
@@ -1,7 +1,14 @@
-import { useLayoutEffect, useRef, useState } from "react";
+/** The app's menu timings, named once; styles.css carries the same values as `--motion-*` on :root.
+ * A menu or popover enters over MENU_ENTER_MS (`animate-menu-in`: 40% opacity and 96% scale to full, a strong
+ * ease-out, transform and opacity only); a context menu and a dialog cut in on one frame; nothing animates out. */
+export const MENU_ENTER_MS = 100;
+export const MENU_EXIT_MS = 0;
+/** A row's hover fill: a hard cut. A header pill's tint: a short ease-out. */
+export const HOVER_MS = 0;
+export const PILL_HOVER_MS = 80;
-/** Same length as `--animate-pop-in` in styles.css. */
-export const MENU_MOTION_MS = 200;
+/** The class a menu or popover enters with, for one that is not drawn through useMenuMotion. */
+export const MENU_ENTER = "animate-menu-in";
export function reducedMotion(): boolean {
if (typeof document === "undefined") return false;
@@ -11,42 +18,21 @@ export function reducedMotion(): boolean {
export interface MenuMotion {
shown: boolean;
+ /** Always false: a menu leaves on the frame it closes (MENU_EXIT_MS). Kept so callers read one shape. */
closing: boolean;
className: string;
exitProps: { inert?: boolean; "aria-hidden"?: boolean };
}
-export function useMenuMotion(open: boolean): MenuMotion {
- const [mounted, setMounted] = useState(open);
+const NO_EXIT: MenuMotion["exitProps"] = {};
- useLayoutEffect(() => {
- if (open) {
- setMounted(true);
- return;
- }
- if (!mounted) return;
- if (reducedMotion()) {
- setMounted(false);
- return;
- }
- const timer = window.setTimeout(() => setMounted(false), MENU_MOTION_MS);
- return () => window.clearTimeout(timer);
- }, [open, mounted]);
-
- // Read `open` itself, not only the trailing state, so the menu shows on the render its trigger flips and goes inert
- // on the render it closes.
- const closing = !open && mounted;
- return {
- shown: open || mounted,
- closing,
- className: closing ? "animate-pop-out pointer-events-none" : "animate-pop-in",
- exitProps: closing ? { inert: true, "aria-hidden": true } : {},
- };
+/** A menu or popover opened from a trigger: shown on the render it opens, gone on the render it closes.
+ * `instant` is a context menu's: it appears on one frame. Reduced motion is handled in styles.css. */
+export function useMenuMotion(open: boolean, enter: "menu" | "instant" = "menu"): MenuMotion {
+ return { shown: open, closing: false, className: open && enter === "menu" ? MENU_ENTER : "", exitProps: NO_EXIT };
}
+/** A menu placed at a point (a context menu, a row's actions): it appears on one frame and leaves on one. */
export function useHeldMenuMotion<T>(value: T | null): MenuMotion & { value: T | null } {
- const motion = useMenuMotion(value != null);
- const held = useRef<T | null>(value);
- if (value != null) held.current = value;
- return { ...motion, value: value ?? held.current };
+ return { ...useMenuMotion(value != null, "instant"), value };
}
diff --git a/src/components/ModelPicker.tsx b/src/components/ModelPicker.tsx
index 651a4a404f..584e080f8f 100644
--- a/src/components/ModelPicker.tsx
+++ b/src/components/ModelPicker.tsx
@@ -22,6 +22,7 @@ import { ChatGptPlanStatus } from "./ChatGptPlanStatus";
import { approvalModeFor, modelSwitchNeedsAsk } from "../../shared/approval-mode";
import { cn } from "@/lib/cn";
import { useMenuMotion } from "./MenuMotion";
+import { returnMenuFocus, useMenuPress } from "./menu-press";
import { SimpleModelMenu, type SimpleThinking } from "./SimpleModelMenu";
import { apiKeysLabel, ClaudeAccountSelect, engineStatus, FollowBotModelRow, ModelEngineRail, ModelRow, ModelSearch } from "./ModelPickerFull";
import { MENU_LABEL, MENU_LINE, MENU_ROW, MENU_SEPARATOR, MENU_TRAILING } from "./menu-recipe";
@@ -344,8 +345,10 @@ export function ModelPicker({
const close = (refocus: boolean) => {
setOpen(false);
- if (refocus) triggerRef.current?.focus({ preventScroll: true });
+ if (refocus) returnMenuFocus(triggerRef.current, press.last.current, null, { preventScroll: true });
};
+ // The mouse opens the picker on the press; a tap, Enter and Space on the click (menu-press.ts).
+ const press = useMenuPress(() => (open ? close(false) : openMenu()), { focusesMenu: true, open });
const resetList = () => {
setQuery("");
@@ -537,7 +540,10 @@ export function ModelPicker({
const onMenuKey = (event: ReactKeyboardEvent<HTMLDivElement>) => {
if (event.nativeEvent.isComposing || event.defaultPrevented || !(event.target instanceof HTMLElement)) return;
- if (event.key !== "Escape") return modelMenuKey(event, { query, typed, close: () => close(true) });
+ if (event.key !== "Escape") {
+ press.last.current = "keyboard";
+ return modelMenuKey(event, { query, typed, close: () => close(true) });
+ }
event.preventDefault();
event.stopPropagation();
if (query) {
@@ -568,14 +574,15 @@ export function ModelPicker({
"data-tour": "model",
type: "button" as const,
disabled: locked,
- onClick: () => (open ? close(false) : openMenu()),
+ ...press.triggerProps,
onKeyDown: (event: ReactKeyboardEvent<HTMLButtonElement>) => {
if (event.key === "Escape" && open) {
event.preventDefault();
event.stopPropagation();
- close(false);
+ close(true);
} else if ((event.key === "ArrowDown" || event.key === "ArrowUp") && !open) {
event.preventDefault();
+ press.last.current = "keyboard";
openMenu();
}
},
diff --git a/src/components/ModelPickerTrigger.tsx b/src/components/ModelPickerTrigger.tsx
index 4aa90a0b37..559ad482f3 100644
--- a/src/components/ModelPickerTrigger.tsx
+++ b/src/components/ModelPickerTrigger.tsx
@@ -32,7 +32,7 @@ export function SimpleModelTrigger({ active, selection, attention, contained, si
className={cn(
"group flex items-center rounded-full text-[13px] leading-[18px] text-ink-secondary disabled:cursor-not-allowed disabled:text-ink-tertiary",
contained
- ? "min-w-0 max-w-[72%] transition-colors duration-150 hover:bg-ink/[0.06] hover:text-ink aria-expanded:bg-ink/[0.08] aria-expanded:text-ink disabled:hover:bg-transparent"
+ ? "min-w-0 max-w-[72%] transition-colors duration-(--motion-pill-hover) ease-out hover:bg-ink/[0.06] hover:text-ink aria-expanded:bg-ink/[0.08] aria-expanded:text-ink disabled:hover:bg-transparent"
: cn("shrink-0", ELEVATED_FLOAT, ELEVATED_HOVER, "hover:text-ink aria-expanded:text-ink disabled:hover:bg-composer"),
size === "sm" ? "h-7 pl-2 pr-1.5" : contained ? "h-8 pl-2.5 pr-2" : "h-9 min-w-9 justify-center pl-3 pr-2.5",
className,
diff --git a/src/components/PinnedMessagesMenu.tsx b/src/components/PinnedMessagesMenu.tsx
index 0aa32c7fc8..3b4580128c 100644
--- a/src/components/PinnedMessagesMenu.tsx
+++ b/src/components/PinnedMessagesMenu.tsx
@@ -8,6 +8,7 @@ import { citationPreviewText } from "@/lib/citations";
import { isTypeaheadKey, typeaheadMatch, typeaheadText, type Typeahead } from "@/lib/menu-keys";
import { usePopoverDismiss } from "@/hooks/use-popover-dismiss";
import { useMenuMotion } from "./MenuMotion";
+import { returnMenuFocus, useMenuPress } from "./menu-press";
import { MENU_LABEL, MENU_SHEET, SIMPLE_MENU_META, SIMPLE_MENU_ROW } from "./menu-recipe";
import { nextMenuIndex } from "./SidebarPopoverMenu";
@@ -30,11 +31,12 @@ export function PinnedMessagesMenu({ pins, onJump, onUnpin, triggerClassName }:
}) {
const [open, setOpen] = useState(false);
const motion = useMenuMotion(open);
+ const press = useMenuPress(() => setOpen((shown) => !shown), { focusesMenu: true, open });
const root = useRef<HTMLDivElement>(null);
const trigger = useRef<HTMLButtonElement>(null);
const menu = useRef<HTMLDivElement>(null);
const typed = useRef<Typeahead | null>(null);
- const close = () => { setOpen(false); trigger.current?.focus(); };
+ const close = () => { setOpen(false); returnMenuFocus(trigger.current, press.last.current); };
usePopoverDismiss(open, root, close);
useEffect(() => {
if (open) menu.current?.querySelector<HTMLElement>("[role=menuitem]")?.focus();
@@ -80,7 +82,7 @@ export function PinnedMessagesMenu({ pins, onJump, onUnpin, triggerClassName }:
<button
ref={trigger}
type="button"
- onClick={() => setOpen((shown) => !shown)}
+ {...press.triggerProps}
aria-label={t("chat.pinnedMessages")}
title={t("chat.pinnedMessages")}
aria-haspopup="menu"
diff --git a/src/components/PlaceChip.tsx b/src/components/PlaceChip.tsx
index 82ecf63731..fc27b0c3a2 100644
--- a/src/components/PlaceChip.tsx
+++ b/src/components/PlaceChip.tsx
@@ -2,6 +2,7 @@ import { Check } from "lucide-react";
import { useEffect, useRef, useState } from "react";
import { cn } from "@/lib/cn";
import { useMenuMotion } from "./MenuMotion";
+import { useMenuPress } from "./menu-press";
import { MENU_HEADING, MENU_SHEET } from "./menu-recipe";
import { t } from "@/lib/i18n";
import { instanceSupportsLocalComputer, localComputerDisabledReason, localComputerSelectable, pageOnRemoteServer } from "@/lib/local-computer";
@@ -118,6 +119,7 @@ export function PlaceChip({ bot, task, live, disabled = false, onPin }: {
}) {
const [open, setOpen] = useState(false);
const motion = useMenuMotion(open);
+ const press = useMenuPress(() => setOpen((value) => !value));
const wrapperRef = useRef<HTMLDivElement>(null);
const places = usePlaceViews(bot);
const effective = effectivePlace(bot, task);
@@ -151,7 +153,7 @@ export function PlaceChip({ bot, task, live, disabled = false, onPin }: {
disabled={disabled || off}
title={off || disabled ? title : `${label} — ${title}`}
data-testid="place-chip"
- onClick={() => setOpen((value) => !value)}
+ {...press.triggerProps}
className={cn(
"relative flex size-8 shrink-0 items-center justify-center rounded-full text-ink-secondary hover:bg-control hover:text-ink",
pinned && "text-accent hover:text-accent",
diff --git a/src/components/Reactions.test.ts b/src/components/Reactions.test.ts
index 72ae834917..694dcb9ee8 100644
--- a/src/components/Reactions.test.ts
+++ b/src/components/Reactions.test.ts
@@ -210,7 +210,7 @@ describe("reaction chips under a message", () => {
it("pops in only a reaction made just now, not every reaction a transcript loads", async () => {
const message: Message = { ...ASKED, reactions: [{ emoji: "👍", by: "p_bob", at: Date.now() }, { emoji: "❤️", by: "p_ada", at: 1 }, { emoji: "🎉", by: "p_cy" }] };
await render(createElement(ReactionChips, { threadId: "t1", message }));
- expect(chips().map((chip) => chip.classList.contains("animate-pop-in"))).toEqual([true, false, false]);
+ expect(chips().map((chip) => chip.classList.contains("animate-menu-in"))).toEqual([true, false, false]);
});
it("counts 👍 and 👎 side by side, and takes the viewer's own 👎 back with a tap", async () => {
diff --git a/src/components/Reactions.tsx b/src/components/Reactions.tsx
index 28eab69959..1e6ac799df 100644
--- a/src/components/Reactions.tsx
+++ b/src/components/Reactions.tsx
@@ -131,7 +131,7 @@ export function ReactAction({ threadId, message }: { threadId: string; message:
aria-label={t("chat.reactions")}
onKeyDown={onKey}
className={cn(
- "popover-surface absolute bottom-full z-40 mb-1 flex animate-pop-in items-center gap-0.5 rounded-full border border-hairline/50 bg-menu p-1 shadow-2xl shadow-black/40",
+ "popover-surface absolute bottom-full z-40 mb-1 flex animate-menu-in items-center gap-0.5 rounded-full border border-hairline/50 bg-menu p-1 shadow-2xl shadow-black/40",
end ? "end-0" : "start-0",
)}
>
@@ -186,7 +186,7 @@ function Chips({ threadId, message, bots = [], align = "start", canReact = true
const label = t("chat.reaction.chip", { reaction: labelOf(emoji), people: people.join(", ") });
const chip = cn(
"flex items-center gap-1 rounded-full border px-2 py-0.5 text-[13px] leading-5",
- fresh && "animate-pop-in",
+ fresh && "animate-menu-in",
mine === emoji ? "border-accent/50 bg-accent/15" : "border-hairline/40 bg-panel",
);
const face = (
diff --git a/src/components/RenameTitle.tsx b/src/components/RenameTitle.tsx
index 8f40118172..908e657f5b 100644
--- a/src/components/RenameTitle.tsx
+++ b/src/components/RenameTitle.tsx
@@ -126,7 +126,7 @@ export function RenameTitle({
return (
<span
- className={cn("cursor-text", className)}
+ className={className}
title={title ?? t("rename.doubleClick")}
tabIndex={0}
role="button"
diff --git a/src/components/SidebarActiveThreads.tsx b/src/components/SidebarActiveThreads.tsx
index 9cc4c13476..2481491127 100644
--- a/src/components/SidebarActiveThreads.tsx
+++ b/src/components/SidebarActiveThreads.tsx
@@ -8,17 +8,19 @@ import { setAttentionPinned, useAttentionPinned } from "./inbox/attention-pinned
import { MENU_SHEET } from "./menu-recipe";
import { attentionHasRunningWork, attentionJumpAction, attentionTriggerLabel, AttentionThreadRows, type AttentionThread } from "./SidebarBotActivity";
import { useMenuMotion } from "./MenuMotion";
+import { useMenuPress } from "./menu-press";
import { usePopoverDismiss } from "@/hooks/use-popover-dismiss";
export function SidebarActiveThreads({ entries, icons, phone, dispatch }: { entries: AttentionThread[]; icons: boolean; phone: boolean; dispatch: Dispatch<Action> }) {
const [open, setOpen] = useState(false);
const motion = useMenuMotion(open);
+ const press = useMenuPress(() => setOpen((value) => !value));
const pinned = useAttentionPinned();
const menu = useRef<HTMLDivElement>(null);
usePopoverDismiss(open, menu, () => setOpen(false));
return (
<div ref={menu} className={icons ? "relative" : "contents"}>
- <button type="button" onClick={() => setOpen((value) => !value)} aria-label={attentionTriggerLabel(entries.length)} title={attentionTriggerLabel(entries.length)}
+ <button type="button" {...press.triggerProps} aria-label={attentionTriggerLabel(entries.length)} title={attentionTriggerLabel(entries.length)}
className={cn("relative flex items-center justify-center text-ink-secondary transition-colors hover:bg-ink/[0.06] hover:text-ink focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-focus",
icons ? "size-[46px] shrink-0 rounded-xl" : phone ? "size-10 shrink-0 rounded-full border border-hairline bg-card text-ink" : "size-8 rounded-full")}>
<Activity size={icons ? 20 : 18} />
diff --git a/src/components/SidebarBotMenu.tsx b/src/components/SidebarBotMenu.tsx
index d7ec77ab95..c9fc3007cc 100644
--- a/src/components/SidebarBotMenu.tsx
+++ b/src/components/SidebarBotMenu.tsx
@@ -298,7 +298,7 @@ export function BotContextMenu({
navigateThreadMenu(event);
}}
style={{ top: shown.y, left: shown.x }}
- className={cn("fixed z-40 max-h-[calc(100dvh-16px)] w-max min-w-[180px] max-w-[calc(100vw-16px)] animate-pop-in overflow-y-auto overscroll-contain", MENU_SHEET)}
+ className={cn("fixed z-40 max-h-[calc(100dvh-16px)] w-max min-w-[180px] max-w-[calc(100vw-16px)] overflow-y-auto overscroll-contain", MENU_SHEET)}
>
{rows[flyout]}
</div>,
diff --git a/src/components/SidebarPopoverMenu.anchored.test.ts b/src/components/SidebarPopoverMenu.anchored.test.ts
index d0c9e989fc..4bdc863e42 100644
--- a/src/components/SidebarPopoverMenu.anchored.test.ts
+++ b/src/components/SidebarPopoverMenu.anchored.test.ts
@@ -254,6 +254,94 @@ describe("the anchored menu in a document", () => {
});
});
+ describe("opens on the mouse's press", () => {
+ const press = (target: Element, pointerType = "mouse", button = 0) =>
+ act(async () => { target.dispatchEvent(new PointerEvent("pointerdown", { bubbles: true, cancelable: true, pointerType, button })); });
+ // One Escape, as the browser sends it: the window sees it only if nothing handled it first.
+ const escape = (target: Element) => act(async () => {
+ const event = new KeyboardEvent("keydown", { key: "Escape", bubbles: true, cancelable: true });
+ target.dispatchEvent(event);
+ if (!event.defaultPrevented) window.dispatchEvent(new KeyboardEvent("keydown", { key: "Escape", cancelable: true }));
+ });
+ const release = (target: Element, detail = 1) =>
+ act(async () => { target.dispatchEvent(new MouseEvent("click", { bubbles: true, cancelable: true, detail })); });
+
+ it("opens on the press, and the click that ends the same press leaves it open", async () => {
+ await press(trigger());
+ expect(sheet()).not.toBeNull();
+ await release(trigger());
+ expect(sheet()).not.toBeNull();
+ expect(trigger().getAttribute("aria-expanded")).toBe("true");
+ });
+
+ it("closes on the next press of its trigger, and that press's click does not reopen it", async () => {
+ await press(trigger());
+ await release(trigger());
+ await press(trigger());
+ expect(sheet()).toBeNull();
+ await release(trigger());
+ expect(sheet()).toBeNull();
+ });
+
+ it("leaves touch, pen and a secondary button to the tap", async () => {
+ await press(trigger(), "touch");
+ expect(sheet()).toBeNull();
+ await release(trigger());
+ expect(sheet()).not.toBeNull();
+ await release(trigger());
+ await press(trigger(), "mouse", 2);
+ expect(sheet()).toBeNull();
+ });
+
+ it("still opens from Enter or Space on the first item, after a press that was released somewhere else", async () => {
+ await press(trigger());
+ await press(document.body);
+ expect(sheet()).toBeNull();
+ await release(trigger(), 0);
+ await flush();
+ expect(document.activeElement).toBe(sheet()!.querySelector('[role="menuitem"]'));
+ });
+
+ it("closes on a press outside after a press opened it", async () => {
+ await press(trigger());
+ await release(trigger());
+ await act(async () => document.body.dispatchEvent(new PointerEvent("pointerdown", { bubbles: true, pointerType: "mouse" })));
+ expect(sheet()).toBeNull();
+ });
+
+ it("hands focus back on Escape without the keyboard ring after the mouse opened it", async () => {
+ trigger().focus();
+ await press(trigger());
+ await release(trigger());
+ await escape(trigger());
+ expect(sheet()).toBeNull();
+ expect(document.activeElement).toBe(trigger());
+ expect(trigger().hasAttribute("data-quiet-focus")).toBe(true);
+ // The next key is the keyboard's: the ring is back.
+ await key(trigger(), "Tab");
+ expect(trigger().hasAttribute("data-quiet-focus")).toBe(false);
+ });
+
+ it("keeps the ring on Escape after the keyboard opened it", async () => {
+ await key(trigger(), "ArrowDown");
+ await flush();
+ await escape(sheet()!.querySelector('[role="menuitem"]')!);
+ expect(document.activeElement).toBe(trigger());
+ expect(trigger().hasAttribute("data-quiet-focus")).toBe(false);
+ });
+
+ it("keeps the ring when the mouse opened it but the arrows went into it", async () => {
+ await press(trigger());
+ await release(trigger());
+ await key(trigger(), "ArrowDown");
+ const first = sheet()!.querySelector<HTMLElement>('[role="menuitem"]')!;
+ first.focus();
+ await escape(first);
+ expect(document.activeElement).toBe(trigger());
+ expect(trigger().hasAttribute("data-quiet-focus")).toBe(false);
+ });
+ });
+
it("closes on a press outside, but not on a press inside the portalled sheet", async () => {
await act(async () => trigger().click());
await act(async () => sheet()!.dispatchEvent(new PointerEvent("pointerdown", { bubbles: true })));
diff --git a/src/components/SidebarPopoverMenu.tsx b/src/components/SidebarPopoverMenu.tsx
index f68046ca90..ba63825abd 100644
--- a/src/components/SidebarPopoverMenu.tsx
+++ b/src/components/SidebarPopoverMenu.tsx
@@ -2,7 +2,8 @@ import { useCallback, useEffect, useId, useLayoutEffect, useRef, useState, type
import { createPortal } from "react-dom";
import { ChevronRight } from "lucide-react";
import { cn } from "@/lib/cn";
-import { useMenuMotion } from "./MenuMotion";
+import { MENU_ENTER, useMenuMotion } from "./MenuMotion";
+import { returnMenuFocus, useMenuPress } from "./menu-press";
import { popoverClosesOnKey, usePopoverDismiss } from "@/hooks/use-popover-dismiss";
import { submenuIntent, type Point, type SubmenuIntent } from "@/lib/submenu-intent";
import { MENU_HEADING, MENU_ITEM_SEPARATOR, MENU_SHEET } from "./menu-recipe";
@@ -206,7 +207,7 @@ export function SidebarPopoverMenu({
const [open, setOpen] = useState(false);
const [pinned, setPinned] = useState(false);
const [submenu, setSubmenu] = useState<string | null>(null);
- const [position, setPosition] = useState<{ left: number; top: number; fit?: number } | null>(null);
+ const [position, setPosition] = useState<{ left: number; top: number; fit?: number; origin?: string } | null>(null);
const [subPosition, setSubPosition] = useState<{ left: number; top: number } | null>(null);
const rootRef = useRef<HTMLDivElement>(null);
const triggerRef = useRef<HTMLButtonElement>(null);
@@ -232,6 +233,19 @@ export function SidebarPopoverMenu({
const menuId = useId();
const motion = useMenuMotion(open);
const anchored = placement === "above";
+ // The mouse opens the menu on the press; a tap, Enter and Space on the click (menu-press.ts).
+ const press = useMenuPress((how) => {
+ clearTimers();
+ if (open && (pinned || !openOnHover)) close();
+ else {
+ // A click from Enter or Space lands on the first item.
+ focusFirst.current = anchored && how === "keyboard";
+ setPinned(true);
+ setOpen(true);
+ }
+ });
+ const pressRef = useRef(press);
+ pressRef.current = press;
const reportOpen = useRef(onOpenChange);
reportOpen.current = onOpenChange;
useEffect(() => { reportOpen.current?.(open); }, [open]);
@@ -261,7 +275,7 @@ export function SidebarPopoverMenu({
setOpen(false);
setSubmenu(null);
setEngaged(false);
- if (refocus) triggerRef.current?.focus();
+ if (refocus) returnMenuFocus(triggerRef.current, pressRef.current.last.current, menuRef.current);
}, []);
const insideRef = useRef({
@@ -292,7 +306,10 @@ export function SidebarPopoverMenu({
if (left + width > edge) fit = Math.max(240, edge - left);
}
}
- setPosition({ ...at, left, fit });
+ // It grows out of the trigger: from its edge nearest the trigger, on the trigger's side.
+ const box = trigger.getBoundingClientRect();
+ const origin = `${at.top < box.top ? "bottom" : "top"} ${(align === "end") !== isRtl(trigger) ? "right" : "left"}`;
+ setPosition({ ...at, left, fit, origin });
}
const sub = subRef.current, row = subRowRef.current;
if (sub && row) {
@@ -386,11 +403,11 @@ export function SidebarPopoverMenu({
onKeyDown={(event) => onMenuKey(event, false)}
onPointerMove={(event) => intent.move({ x: event.clientX, y: event.clientY }, Boolean(submenu && subRowRef.current?.contains(event.target as Node)))}
onPointerLeave={() => intent.leaveMenu()}
- style={anchored ? { position: "fixed", left: position?.left ?? 0, top: position?.top ?? 0, minWidth: width ? undefined : MENU_MIN_WIDTH, width: width ? `min(${position?.fit ?? width}px, calc(100vw - var(--rail-beside, 0px) - ${EDGE_MARGIN * 2}px))` : "max-content", maxWidth: width ? undefined : `min(${MENU_MAX_WIDTH}px, calc(100vw - ${EDGE_MARGIN * 2}px))`, maxHeight: `calc(100vh - ${EDGE_MARGIN * 2}px)`, visibility: position ? undefined : "hidden" } : undefined}
+ style={anchored ? { position: "fixed", left: position?.left ?? 0, top: position?.top ?? 0, minWidth: width ? undefined : MENU_MIN_WIDTH, width: width ? `min(${position?.fit ?? width}px, calc(100vw - var(--rail-beside, 0px) - ${EDGE_MARGIN * 2}px))` : "max-content", maxWidth: width ? undefined : `min(${MENU_MAX_WIDTH}px, calc(100vw - ${EDGE_MARGIN * 2}px))`, maxHeight: `calc(100vh - ${EDGE_MARGIN * 2}px)`, visibility: position ? undefined : "hidden", transformOrigin: position?.origin } : undefined}
className={cn(
sheetClass,
anchored ? "z-[60] overflow-y-auto" : "absolute z-40",
- placement === "below" && "top-full right-0 mt-1 w-72 max-w-[calc(100vw-2rem)]",
+ placement === "below" && "top-full right-0 mt-1 w-72 max-w-[calc(100vw-2rem)] origin-top-right",
motion.className,
)}
>
@@ -421,7 +438,7 @@ export function SidebarPopoverMenu({
onFocus={() => setEngaged(true)}
onBlur={(event) => { if (!(event.relatedTarget instanceof Node && event.currentTarget.contains(event.relatedTarget))) setEngaged(false); }}
style={{ position: "fixed", left: subPosition?.left ?? 0, top: subPosition?.top ?? 0, minWidth: 200, width: dense ? 240 : "max-content", maxWidth: `min(${MENU_MAX_WIDTH}px, calc(100vw - ${EDGE_MARGIN * 2}px))`, maxHeight: `calc(100vh - ${EDGE_MARGIN * 2}px)`, visibility: subPosition ? undefined : "hidden" }}
- className={cn(sheetClass, "z-[61] animate-pop-in overflow-y-auto")}
+ className={cn(sheetClass, "z-[61] overflow-y-auto", MENU_ENTER)}
>
<MenuRows
dense={dense}
@@ -455,16 +472,7 @@ export function SidebarPopoverMenu({
aria-label={triggerLabel ?? ariaLabel}
title={triggerTitle}
data-tour={triggerTour}
- onClick={(event) => {
- clearTimers();
- if (open && (pinned || !openOnHover)) close();
- else {
- // event.detail is 0 for a click from Enter or Space: land on the first item.
- focusFirst.current = anchored && event.detail === 0;
- setPinned(true);
- setOpen(true);
- }
- }}
+ {...press.triggerProps}
onKeyDown={(event) => {
if (open && closesOnEscape(event)) {
// A menu opened with the mouse leaves focus here; Escape closes it before anything around it.
@@ -475,6 +483,7 @@ export function SidebarPopoverMenu({
}
if (!anchored || open || (event.key !== "ArrowUp" && event.key !== "ArrowDown")) return;
event.preventDefault();
+ press.last.current = "keyboard";
focusFirst.current = true;
setPinned(true);
setOpen(true);
diff --git a/src/components/SidebarThreadRow.tsx b/src/components/SidebarThreadRow.tsx
index 4f2bc500b1..6115dbaabf 100644
--- a/src/components/SidebarThreadRow.tsx
+++ b/src/components/SidebarThreadRow.tsx
@@ -379,7 +379,7 @@ export const SidebarThreadRow = memo(function SidebarThreadRow({ task, ownerId,
</button>}
{advanced && task.link && <a href={task.link} target="_blank" rel="noreferrer" dir="ltr" title={task.link} aria-label={t("task.openLink", { link: threadLinkLabel(task.link) ?? task.link })}
className={cn("shrink-0 rounded px-1 font-mono text-[12px] text-ink-secondary hover:bg-raised hover:text-ink outline-none focus-visible:ring-1 focus-visible:ring-accent/60 [unicode-bidi:isolate]", panel && "mt-2.5")}>{threadLinkLabel(task.link) ?? t("task.link")}</a>}
- {!renaming && <span className={cn("flex shrink-0 items-center gap-2 px-1", panel && "pt-2.5 empty:hidden")} onClick={choose} onContextMenu={contextMenu}>
+ {!renaming && <span className={cn("flex shrink-0 cursor-pointer select-none items-center gap-2 px-1", panel && "pt-2.5 empty:hidden")} onClick={choose} onContextMenu={contextMenu}>
{updatedLabel && !panel && <time dateTime={new Date(updatedAt).toISOString()} className="shrink-0 tabular-nums text-[12px] font-medium leading-4 text-ink-secondary">{updatedLabel}</time>}
{task.pinned === true && <Pin size={11} className="shrink-0 text-ink-secondary" aria-label={t("sidebar.bot.pin")} />}
{task.activity === "waiting-on-you" ? <span className="shrink-0 text-[12px] font-medium leading-4 text-warning">{t("task.waiting")}</span> : isWaitingOnTeammate(task) ? <Clock3 size={11} className="shrink-0 text-ink-secondary" aria-label={t("task.waitingOnTeammate")} /> : isWorking(task) && !panel ? <Loader2 size={11} className="shrink-0 animate-spin text-success" aria-label={activityLabel ?? t("chat.activity.working")} /> : task.queued ? <span className="shrink-0 text-[10px] text-ink-secondary">{t("task.queued")}</span> : null}
diff --git a/src/components/TeamCanvas.tsx b/src/components/TeamCanvas.tsx
index f16381f709..8801f75dc1 100644
--- a/src/components/TeamCanvas.tsx
+++ b/src/components/TeamCanvas.tsx
@@ -470,7 +470,7 @@ export function TeamCanvas({ sections, canManage, onMove, onInstructions, onMemo
}
}}>
<summary aria-label={t("canvas.manageTeam", { name: section.name })} className={cn(iconButton, "cursor-pointer list-none [&::-webkit-details-marker]:hidden")}><MoreHorizontal size={17} /></summary>
- <div className={cn("absolute right-0 z-30 w-[220px] animate-pop-in rounded-xl border border-hairline bg-panel p-1.5 shadow-xl", menuAbove === section.key ? "bottom-10" : "top-10")} onClick={(event) => {
+ <div className={cn("absolute right-0 z-30 w-[220px] animate-menu-in rounded-xl border border-hairline bg-panel p-1.5 shadow-xl", menuAbove === section.key ? "bottom-10" : "top-10")} onClick={(event) => {
const menu = event.currentTarget.closest("details");
menu?.querySelector("summary")?.focus();
menu?.removeAttribute("open");
diff --git a/src/components/TeamOwner.tsx b/src/components/TeamOwner.tsx
index fa74923721..ed01a6ce7e 100644
--- a/src/components/TeamOwner.tsx
+++ b/src/components/TeamOwner.tsx
@@ -12,6 +12,7 @@ import { askingWhom, ownerChanged, ownerOf, pictureOf, refreshNeedsYou, useTeamP
import type { NeedsYouItem } from "../../shared/today";
import { useInboxSupport } from "@/state/inbox";
import { useHeldMenuMotion } from "./MenuMotion";
+import { useMenuPress } from "./menu-press";
import { MENU_HEADING, MENU_SHEET } from "./menu-recipe";
export type OwnerPickerTarget = { botId: string; current: string | null; x: number; y: number };
@@ -154,6 +155,7 @@ export function NeedsYouButton({ compact = false }: { compact?: boolean }) {
const team = useTeamPeople();
const support = useInboxSupport();
const [open, setOpen] = useState(false);
+ const press = useMenuPress(() => setOpen((value) => !value));
useEffect(() => {
if (!open) return;
const onDown = (event: MouseEvent) => { if (!(event.target instanceof Element) || !event.target.closest("[data-needs-you]")) setOpen(false); };
@@ -165,7 +167,7 @@ export function NeedsYouButton({ compact = false }: { compact?: boolean }) {
const label = t("needsYou.count", { count: items.length });
return (
<div data-needs-you className={cn("relative", compact ? "px-1" : "px-2 pb-1")}>
- <button type="button" aria-expanded={open} aria-haspopup="menu" aria-label={label} title={label} onClick={() => setOpen((value) => !value)}
+ <button type="button" aria-expanded={open} aria-haspopup="menu" aria-label={label} title={label} {...press.triggerProps}
className="flex w-full items-center gap-2 rounded-lg px-2 py-1.5 text-left text-[13px] font-medium text-warning hover:bg-raised/60">
<Bell size={15} aria-hidden="true" className="shrink-0" />
{!compact && <span className="min-w-0 flex-1 truncate">{t("needsYou.title")}</span>}
diff --git a/src/components/elevated.ts b/src/components/elevated.ts
index ba229da154..67e0f33049 100644
--- a/src/components/elevated.ts
+++ b/src/components/elevated.ts
@@ -5,7 +5,7 @@ export const ELEVATED_FLOAT = `${ELEVATED_CARD} shadow-(--shadow-float)`;
/** The composer: the floating surface on its own softer lift. Daylight drops the 0.5px ring at rest (styles.css). */
export const ELEVATED_COMPOSER = `${ELEVATED_CARD} composer-shell shadow-(--shadow-composer)`;
/** The hover tint alone, for a control whose aria-expanded is not a menu of its own. */
-export const ELEVATED_TINT = "transition-colors duration-[120ms] hover:bg-[color-mix(in_srgb,var(--color-composer),var(--color-ink)_7%)]";
+export const ELEVATED_TINT = "transition-colors duration-(--motion-pill-hover) ease-out hover:bg-[color-mix(in_srgb,var(--color-composer),var(--color-ink)_7%)]";
export const ELEVATED_HOVER = `${ELEVATED_TINT} aria-expanded:bg-[color-mix(in_srgb,var(--color-composer),var(--color-ink)_7%)]`;
/** The hover tint as a plain fill, for a trigger whose aria-expanded sits on a wrapping button. */
export const ELEVATED_OPEN = "bg-[color-mix(in_srgb,var(--color-composer),var(--color-ink)_7%)]";
diff --git a/src/components/menu-press.dom.test.ts b/src/components/menu-press.dom.test.ts
new file mode 100644
index 0000000000..c462b52435
--- /dev/null
+++ b/src/components/menu-press.dom.test.ts
@@ -0,0 +1,113 @@
+// @vitest-environment happy-dom
+import { act, createElement, useState } from "react";
+import { createRoot, type Root } from "react-dom/client";
+import { afterEach, beforeEach, describe, expect, it } from "vitest";
+import { opensOnPress, returnMenuFocus, useMenuPress, type MenuPress } from "./menu-press";
+
+(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
+
+const toggles: MenuPress[] = [];
+function Trigger() {
+ const [open, setOpen] = useState(false);
+ const press = useMenuPress((how) => { toggles.push(how); setOpen((value) => !value); });
+ return createElement("button", { type: "button", "aria-expanded": open, ...press.triggerProps }, "Add");
+}
+
+let host: HTMLDivElement;
+let root: Root;
+const button = () => host.querySelector("button")!;
+const down = (pointerType = "mouse", extra: PointerEventInit = {}) =>
+ act(async () => { button().dispatchEvent(new PointerEvent("pointerdown", { bubbles: true, pointerType, button: 0, ...extra })); });
+const click = (detail = 1) => act(async () => { button().dispatchEvent(new MouseEvent("click", { bubbles: true, detail })); });
+
+beforeEach(async () => {
+ toggles.length = 0;
+ host = document.createElement("div");
+ document.body.append(host);
+ root = createRoot(host);
+ await act(async () => root.render(createElement(Trigger)));
+});
+afterEach(async () => {
+ await act(async () => root.unmount());
+ host.remove();
+});
+
+describe("a menu trigger's press", () => {
+ it("toggles on a mouse press and spends that press's click", async () => {
+ await down();
+ expect(button().getAttribute("aria-expanded")).toBe("true");
+ await click();
+ expect(button().getAttribute("aria-expanded")).toBe("true");
+ expect(toggles).toEqual(["pointer"]);
+ });
+
+ it("toggles on the click for a tap, a pen, a modified press, or a click with no press", async () => {
+ for (const init of [{ pointerType: "touch" }, { pointerType: "pen" }, { pointerType: "mouse", ctrlKey: true }]) {
+ await down(init.pointerType, init);
+ await click();
+ }
+ await click();
+ expect(toggles).toEqual(["click", "click", "click", "click"]);
+ });
+
+ it("reports Enter and Space (a click with detail 0) as the keyboard, even after a press that never clicked", async () => {
+ await down();
+ await click(0);
+ expect(toggles).toEqual(["pointer", "keyboard"]);
+ });
+
+ it("keeps the mouse's focus change off the trigger only for the press that opens a menu which focuses itself", async () => {
+ function Focusing() {
+ const [open, setOpen] = useState(false);
+ const press = useMenuPress(() => setOpen((value) => !value), { focusesMenu: true, open });
+ return createElement("button", { type: "button", "aria-expanded": open, ...press.triggerProps }, "Model");
+ }
+ await act(async () => root.render(createElement(Focusing)));
+ const mousedown = () => {
+ const event = new MouseEvent("mousedown", { bubbles: true, cancelable: true });
+ button().dispatchEvent(event);
+ return event.defaultPrevented;
+ };
+ await down();
+ expect(mousedown()).toBe(true);
+ await click();
+ await down();
+ expect(button().getAttribute("aria-expanded")).toBe("false");
+ expect(mousedown()).toBe(false);
+ });
+
+ it("only takes a plain primary mouse press", () => {
+ const base = { pointerType: "mouse", button: 0, ctrlKey: false, metaKey: false, shiftKey: false, altKey: false };
+ expect(opensOnPress(base)).toBe(true);
+ expect(opensOnPress({ ...base, button: 2 })).toBe(false);
+ expect(opensOnPress({ ...base, metaKey: true })).toBe(false);
+ expect(opensOnPress({ ...base, pointerType: "touch" })).toBe(false);
+ });
+});
+
+describe("focus back on the trigger", () => {
+ it("keeps the ring off after the mouse, until the next key or blur", () => {
+ returnMenuFocus(button(), "pointer");
+ expect(document.activeElement).toBe(button());
+ expect(button().hasAttribute("data-quiet-focus")).toBe(true);
+ button().dispatchEvent(new KeyboardEvent("keydown", { key: "Tab", bubbles: true }));
+ expect(button().hasAttribute("data-quiet-focus")).toBe(false);
+ returnMenuFocus(button(), "click");
+ button().blur();
+ expect(button().hasAttribute("data-quiet-focus")).toBe(false);
+ });
+
+ it("leaves the ring after the keyboard, or when focus had gone into the menu", () => {
+ returnMenuFocus(button(), "keyboard");
+ expect(button().hasAttribute("data-quiet-focus")).toBe(false);
+ const menu = document.createElement("div");
+ const row = document.createElement("button");
+ menu.append(row);
+ document.body.append(menu);
+ row.focus();
+ returnMenuFocus(button(), "pointer", menu);
+ expect(document.activeElement).toBe(button());
+ expect(button().hasAttribute("data-quiet-focus")).toBe(false);
+ menu.remove();
+ });
+});
diff --git a/src/components/menu-press.ts b/src/components/menu-press.ts
new file mode 100644
index 0000000000..8386756d49
--- /dev/null
+++ b/src/components/menu-press.ts
@@ -0,0 +1,80 @@
+import { useRef, type MouseEvent as ReactMouseEvent, type PointerEvent as ReactPointerEvent } from "react";
+
+/** How a menu's trigger was last pressed: a mouse press, a click with no press before it (a tap, a test), or a key. */
+export type MenuPress = "pointer" | "click" | "keyboard";
+
+/** A mouse's plain primary press opens a menu at once. Touch and pen keep the tap, and a modified press is left to the
+ * browser (Control-click is the context menu on a Mac). */
+export function opensOnPress(event: Pick<PointerEvent, "pointerType" | "button" | "ctrlKey" | "metaKey" | "shiftKey" | "altKey">): boolean {
+ return event.pointerType === "mouse" && event.button === 0 && !event.ctrlKey && !event.metaKey && !event.shiftKey && !event.altKey;
+}
+
+/** A menu trigger's press handlers: the mouse opens (or closes) the menu on the press, and the click that ends the
+ * same press is spent. A click with no press before it still toggles, so a tap, Enter and Space (a click with detail 0)
+ * behave as before. A press released somewhere else leaves no click behind; the next press or key clears it. */
+export function useMenuPress(toggle: (how: MenuPress) => void, options: {
+ /** The menu moves focus into itself when it opens: the press that opens it must not then focus the trigger (the
+ * mouse's own focus change comes after the press). Needs `open`, the menu's state before the press. */
+ focusesMenu?: boolean;
+ open?: boolean;
+} = {}) {
+ const pressed = useRef(false);
+ const keepFocus = useRef(false);
+ const last = useRef<MenuPress>("click");
+ const latest = useRef(toggle);
+ latest.current = toggle;
+ const settings = useRef(options);
+ settings.current = options;
+ return {
+ /** How the menu was last opened or closed from its trigger. */
+ last,
+ triggerProps: {
+ onPointerDown: (event: ReactPointerEvent<HTMLElement>) => {
+ pressed.current = false;
+ keepFocus.current = false;
+ if (!opensOnPress(event) || event.currentTarget.matches(":disabled")) return;
+ pressed.current = true;
+ keepFocus.current = Boolean(settings.current.focusesMenu && !settings.current.open);
+ last.current = "pointer";
+ latest.current("pointer");
+ },
+ onMouseDown: (event: ReactMouseEvent<HTMLElement>) => {
+ if (!keepFocus.current) return;
+ keepFocus.current = false;
+ event.preventDefault();
+ },
+ // A click called with no event (from code) counts as a plain click.
+ onClick: (event?: ReactMouseEvent<HTMLElement>) => {
+ const detail = event?.detail ?? 1;
+ const spent = pressed.current && detail !== 0;
+ pressed.current = false;
+ if (spent) return;
+ last.current = detail === 0 ? "keyboard" : "click";
+ latest.current(last.current);
+ },
+ },
+ };
+}
+
+/** Focus back on a menu's trigger when the menu closes. If the person used the mouse (the menu came from a press or a
+ * tap and focus never went into it), the trigger is marked so the Escape that closed it does not draw the keyboard
+ * ring; the mark goes at the trigger's next key or blur. */
+export function returnMenuFocus(trigger: HTMLElement | null | undefined, how: MenuPress, menu?: Element | null, options?: FocusOptions): void {
+ if (!trigger) return;
+ const keyboard = how === "keyboard" || Boolean(menu && document.activeElement && menu.contains(document.activeElement));
+ if (!keyboard) quietFocus(trigger);
+ trigger.focus(options);
+}
+
+/** Keep the focus ring off `element` until its next key or blur. */
+export function quietFocus(element: HTMLElement): void {
+ if (element.hasAttribute("data-quiet-focus")) return;
+ element.setAttribute("data-quiet-focus", "");
+ const clear = () => {
+ element.removeAttribute("data-quiet-focus");
+ element.removeEventListener("keydown", clear);
+ element.removeEventListener("blur", clear);
+ };
+ element.addEventListener("keydown", clear);
+ element.addEventListener("blur", clear);
+}
diff --git a/src/components/settings/SettingsNav.tsx b/src/components/settings/SettingsNav.tsx
index 9e44991d87..fc1b861856 100644
--- a/src/components/settings/SettingsNav.tsx
+++ b/src/components/settings/SettingsNav.tsx
@@ -22,7 +22,7 @@ import { isMacPlatform } from "@/lib/keyboard-shortcuts";
import { keySection, type KeyEntry } from "../keys/key-catalog";
import { HELP_CENTER_URL, desktopAppVersion } from "@/lib/app-links";
-export const NAV_ITEM = "relative flex h-8 w-full shrink-0 cursor-pointer items-center gap-2 rounded-lg px-[9px] py-[7px] text-left text-[13px] leading-5 text-ink transition-colors motion-reduce:transition-none focus-visible:outline-2 focus-visible:-outline-offset-2 focus-visible:outline-focus";
+export const NAV_ITEM = "relative flex h-8 w-full shrink-0 cursor-pointer items-center gap-2 rounded-lg px-[9px] py-[7px] text-left text-[13px] leading-5 text-ink focus-visible:outline-2 focus-visible:-outline-offset-2 focus-visible:outline-focus";
/** A place's badge as its rail circle draws it; with no colour of its own (This computer, or a Cloud in a browser) it is a
* quiet filled tile with an edge, so it never vanishes on the sheet. */
@@ -90,7 +90,7 @@ function IdentityRow({ page, current, badge, name, line, onOpen, narrow }: {
}) {
return (
<button type="button" data-settings-page={page} data-settings-section={page} data-settings-identity="" aria-current={current ? "page" : undefined} onClick={onOpen}
- className={cn("flex w-full shrink-0 cursor-pointer items-center gap-2 rounded-lg px-2 py-1 text-left", narrow ? "h-12" : "h-11", " transition-colors motion-reduce:transition-none focus-visible:outline-2 focus-visible:-outline-offset-2 focus-visible:outline-focus",
+ className={cn("flex w-full shrink-0 cursor-pointer items-center gap-2 rounded-lg px-2 py-1 text-left", narrow ? "h-12" : "h-11", "focus-visible:outline-2 focus-visible:-outline-offset-2 focus-visible:outline-focus",
current ? "bg-menu-active" : "hover:bg-menu-hover")}>
<span className="flex size-6 shrink-0 items-center justify-center overflow-hidden rounded-[6px]">{badge}</span>
<span className="flex min-w-0 flex-1 flex-col">
diff --git a/src/components/widget/WidgetTimePicker.tsx b/src/components/widget/WidgetTimePicker.tsx
index ebb1199f65..b4b79cbb64 100644
--- a/src/components/widget/WidgetTimePicker.tsx
+++ b/src/components/widget/WidgetTimePicker.tsx
@@ -228,7 +228,7 @@ export function WidgetTimePicker({ node, bare }: { node: WidgetNode; bare: boole
// preventDefault on mousedown keeps the focus on the trigger.
onMouseDown={(event) => event.preventDefault()}
style={{ position: "fixed", ...place, visibility: place ? undefined : "hidden" }}
- className="popover-surface z-[70] animate-pop-in overflow-y-auto overscroll-contain rounded-xl border border-hairline/50 bg-menu py-1 shadow-2xl shadow-black/50"
+ className="popover-surface z-[70] animate-menu-in overflow-y-auto overscroll-contain rounded-xl border border-hairline/50 bg-menu py-1 shadow-2xl shadow-black/50"
>
{slots.map((slot, index) => (
<div
diff --git a/src/styles.css b/src/styles.css
index d158c77d06..94157a6749 100644
--- a/src/styles.css
+++ b/src/styles.css
@@ -132,7 +132,10 @@
--animate-panel-beside-in: panel-beside-in 0.24s cubic-bezier(0.22, 1, 0.36, 1);
--animate-sheet-in: sheet-in 0.26s cubic-bezier(0.22, 1, 0.36, 1);
--animate-workspace-in: workspace-in 0.18s cubic-bezier(0.22, 1, 0.36, 1);
- --animate-pop-in: pop-in 0.2s cubic-bezier(0.22, 1, 0.36, 1);
+ /* A dialog cuts in on one frame: no entrance (the --motion-* tokens on :root). */
+ --animate-pop-in: none;
+ /* A menu or popover from its trigger: 100ms, transform and opacity only. */
+ --animate-menu-in: menu-in var(--motion-menu-enter) var(--motion-menu-ease) both;
--animate-pop-out: pop-out 0.2s cubic-bezier(0.22, 1, 0.36, 1) forwards;
--animate-caret: caret-blink 1s step-end infinite;
--animate-msg-in: msg-in 0.18s cubic-bezier(0.22, 1, 0.36, 1);
@@ -234,6 +237,14 @@
--chat-column-max: 60rem;
/* Menus; a phone rounds them like its sheets. */
--radius-menu: 12px;
+ /* One set of timings for menus, popovers, dialogs and hover (MenuMotion.tsx). A menu or popover enters over
+ 100ms on a strong ease-out from 40% opacity, so its first painted frame is already mostly there; a context menu
+ and a dialog cut in on one frame; nothing animates out; a row's hover fill is a hard cut and a pill's tint is
+ a short ease-out. */
+ --motion-menu-enter: 100ms;
+ --motion-menu-ease: cubic-bezier(0.16, 1, 0.3, 1);
+ --motion-hover: 0ms;
+ --motion-pill-hover: 80ms;
}
:root[data-font] {
--tracking-ui: 0;
@@ -1691,14 +1702,18 @@ body {
}
/* The sidebar's bot rows and pinned bots give under the pointer like a button (98% over 50ms), but not while a
- button inside the row is the one pressed. The colour fade the rows already had is repeated here, because this
- transition replaces theirs. */
+ button inside the row is the one pressed. Their hover fill is a hard cut (--motion-hover); this transition replaces
+ the rows' own colour fade. */
[data-sidebar-bot-row] {
transition-property: color, background-color, border-color, outline-color, fill, stroke, scale;
- transition-duration: 150ms, 150ms, 150ms, 150ms, 150ms, 150ms, 50ms;
+ transition-duration: var(--motion-hover), var(--motion-hover), var(--motion-hover), var(--motion-hover), var(--motion-hover), var(--motion-hover), 50ms;
transition-timing-function: cubic-bezier(0.4, 0, 0.2, 1), cubic-bezier(0.4, 0, 0.2, 1), cubic-bezier(0.4, 0, 0.2, 1),
cubic-bezier(0.4, 0, 0.2, 1), cubic-bezier(0.4, 0, 0.2, 1), cubic-bezier(0.4, 0, 0.2, 1), cubic-bezier(0.165, 0.84, 0.44, 1);
}
+/* A sidebar row is a control, not text: a drag across it never selects its labels. A rename field inside keeps its
+ own selection. */
+:is([data-sidebar-bot-row], [data-sidebar-thread-row]) { user-select: none; }
+:is([data-sidebar-bot-row], [data-sidebar-thread-row]) :is(input, textarea) { user-select: text; }
@media (prefers-reduced-motion: no-preference) {
:root:not([data-reduced-motion="true"]) [data-sidebar-bot-row]:active:not(:has(button:active)) {
scale: 0.98;
@@ -1717,7 +1732,7 @@ body {
A transition takes its timing from the state it goes to, so each state below carries the timing that reaches it. */
[data-model-pill] {
transition-property: color, background-color, padding;
- transition-duration: 120ms, 120ms, 240ms;
+ transition-duration: var(--motion-pill-hover), var(--motion-pill-hover), 240ms;
transition-timing-function: ease-out, ease-out, cubic-bezier(0.22, 1, 0.36, 1);
}
[data-model-pill][data-folded] { padding-inline: 0; }
@@ -2240,6 +2255,11 @@ body {
}
/* A whole-row button in a card takes the card's corners, so its inset ring never cuts across a rounded corner. */
[data-settings-look] [data-settings-rows] > button:focus-visible { border-radius: 12px; }
+/* A menu's trigger gets focus back when the menu closes. After a menu the mouse opened, the Escape that closed it
+ would make Chromium draw the keyboard ring there; menu-press.ts marks the trigger until its next key or blur. */
+[data-quiet-focus]:focus-visible {
+ outline: none;
+}
/* A menu row shows keyboard focus as its hover fill. */
[role="menu"] :is(button, [role^="menuitem"]):focus-visible {
outline: none;
@@ -2352,9 +2372,9 @@ body {
from { opacity: 0.92; }
to { opacity: 1; }
}
-@keyframes pop-in {
- from { transform: scale(0.96) translateY(6px); opacity: 0; }
- to { transform: scale(1) translateY(0); opacity: 1; }
+@keyframes menu-in {
+ from { transform: scale(0.96); opacity: 0.4; }
+ to { transform: scale(1); opacity: 1; }
}
@keyframes pop-out {
from { transform: scale(1) translateY(0); opacity: 1; }
@@ -2643,7 +2663,7 @@ html[data-cloud-intent-morph] [data-tour="composer"] { view-transition-name: clo
@media (prefers-reduced-motion: reduce) {
.turn-now-card { animation: none; }
.turn-now-chevron { transition: none; }
- .animate-caret, .animate-msg-in, .animate-pop-in, .animate-pop-out { animation: none; }
+ .animate-caret, .animate-msg-in, .animate-pop-in, .animate-pop-out, .animate-menu-in { animation: none; }
.animate-status-pulse { animation: none; opacity: 0.6; }
.thinking-sheen { display: none; }
.turn-phrase-in { animation: none; }
@@ -2663,6 +2683,7 @@ html[data-cloud-intent-morph] [data-tour="composer"] { view-transition-name: clo
:root[data-reduced-motion="true"] .animate-spot-in,
:root[data-reduced-motion="true"] .animate-pop-in,
:root[data-reduced-motion="true"] .animate-pop-out,
+:root[data-reduced-motion="true"] .animate-menu-in,
:root[data-reduced-motion="true"] .md\:animate-panel-beside-in,
:root[data-reduced-motion="true"] .step-open,
:root[data-reduced-motion="true"] .check-in,