Skip to content

The Open Standard for Generative UI

devtools: choose or drag the launcher and panel corner (#1497)

devin-ai-integration[bot]e2ae4f1de01c
diff --git a/.changeset/devtools-launcher-avoid-host-controls.md b/.changeset/devtools-launcher-avoid-host-controls.md
deleted file mode 100644
index f71930775..000000000
--- a/.changeset/devtools-launcher-avoid-host-controls.md
+++ /dev/null
@@ -1,5 +0,0 @@
----
-"@openuidev/devtools": patch
----
-
-Keep the devtools launcher off the host app's own controls. On narrow windows it could sit on top of a chat's Send button; it now moves just clear of any button, link or input underneath it.
diff --git a/.changeset/devtools-launcher-position-setting.md b/.changeset/devtools-launcher-position-setting.md
new file mode 100644
index 000000000..2dbfccc5b
--- /dev/null
+++ b/.changeset/devtools-launcher-position-setting.md
@@ -0,0 +1,5 @@
+---
+"@openuidev/devtools": patch
+---
+
+Add a Position setting to the Inspect settings menu to move the launcher and the Inspect and Debug panels to any corner of the screen. The launcher can also be dragged: a short drag toward another corner snaps it there. The choice is saved, and the `position` prop sets the default.
diff --git a/packages/devtools/src/OpenUIDevtoolsWidget.tsx b/packages/devtools/src/OpenUIDevtoolsWidget.tsx
index bd864c035..6d8f87c41 100644
--- a/packages/devtools/src/OpenUIDevtoolsWidget.tsx
+++ b/packages/devtools/src/OpenUIDevtoolsWidget.tsx
@@ -14,6 +14,7 @@ import {
import {
addOrReplaceEvent,
isLibraryEvent,
+ useCornerDrag,
useDevtoolsConfig,
useDevtoolsSingleton,
type DevtoolsConfig,
@@ -28,10 +29,16 @@ import {
type ThemeTokens,
} from "./theme";
import type { DevtoolsPosition, OpenUIDevtoolsWidgetProps } from "./types";
-import { ErrorBoundary, IconButton, INTER_FONT_FACE, ShiroLogo, ThemeSegmented } from "./ui";
+import {
+ ErrorBoundary,
+ IconButton,
+ INTER_FONT_FACE,
+ PositionSegmented,
+ ShiroLogo,
+ ThemeSegmented,
+} from "./ui";
import { DeployBanner, DeployHint } from "./ui/DeployHint";
import ReliabilityBanner from "./ui/ReliabilityBanner";
-import { useAvoidHostControls } from "./ui/avoidHostControls";
export type { DevtoolsPosition, OpenUIDevtoolsProps, OpenUIDevtoolsWidgetProps } from "./types";
@@ -39,9 +46,9 @@ export type { DevtoolsPosition, OpenUIDevtoolsProps, OpenUIDevtoolsWidgetProps }
const MENU_ROW_HEIGHT = 28;
/**
- * Tray geometry. The two trays together fill a block anchored to the bottom
- * right — 85% of the viewport, capped so it stops growing on very large
- * displays. Inspect keeps a fixed width and Debug takes whatever is left,
+ * Tray geometry. The two trays together fill a block anchored to the
+ * launcher's corner — 85% of the viewport, capped so it stops growing on very
+ * large displays. Inspect keeps a fixed width and Debug takes whatever is left,
* overlapping Inspect rather than collapsing once it hits its floor.
*/
const TRAY_EDGE = 12;
@@ -77,12 +84,13 @@ export function OpenUIDevtoolsWidget({
autoOpen: autoOpenOnError,
onlyErrors: errorsOnly,
theme: DEFAULT_COLOR_MODE,
+ position,
helpSeen: false,
editorPct: DEFAULT_EDITOR_PCT,
},
{ theme: themeProp },
);
- const { onlyErrors, theme: mode } = config;
+ const { onlyErrors, theme: mode, position: corner } = config;
const debug = useDebug({
theme: mode,
helpSeen: config.helpSeen,
@@ -90,6 +98,7 @@ export function OpenUIDevtoolsWidget({
setConfig,
});
const styles = uiStyles(theme(mode));
+ const drag = useCornerDrag(corner, (position) => setConfig({ position }));
// Read configRef inside the (stable) subscription without re-subscribing.
useEffect(() => {
@@ -115,34 +124,32 @@ export function OpenUIDevtoolsWidget({
return () => document.removeEventListener("keydown", onKeyDown);
}, [open, debug.trayOpen, debug.retract]);
- // Keep the launcher off the host app's own controls (e.g. a chat Send button
- // on a narrow window) by moving it along its anchored edge.
- const toggleRef = useRef<HTMLDivElement>(null);
- const anchor = position.startsWith("top") ? "top" : "bottom";
- const lift = useAvoidHostControls(toggleRef, anchor, isEnabled && isSingleton);
-
if (!isEnabled || !isSingleton) return null;
const errorCount = events.filter((event) => event.level === "error").length;
const visibleEvents = onlyErrors ? events.filter((event) => event.level !== "info") : events;
- // Inspect is pinned to the right edge; Debug fills the rest of the block and
- // slides over to reclaim Inspect's slot whenever Inspect is out.
+ // Inspect is pinned to the launcher's side; Debug fills the rest of the
+ // block and slides over to reclaim Inspect's slot whenever Inspect is out.
+ const side = corner.endsWith("left") ? "left" : "right";
+ const edge = corner.startsWith("top") ? "top" : "bottom";
const inspectSlot = open ? INSPECT_WIDTH + TRAY_GAP : 0;
const inspectTray: CSSProperties = {
- right: TRAY_EDGE,
- bottom: TRAY_EDGE,
+ [side]: TRAY_EDGE,
+ [edge]: TRAY_EDGE,
height: BLOCK_H,
width: `min(${INSPECT_WIDTH}px, calc(100vw - ${TRAY_EDGE * 2}px))`,
- transform: open ? "translateX(0)" : `translateX(calc(100% + ${TRAY_EDGE}px))`,
+ transform: open
+ ? "translateX(0)"
+ : `translateX(calc((100% + ${TRAY_EDGE}px) * ${side === "left" ? -1 : 1}))`,
};
// Debug is a workspace rather than a peek at the app behind it: it fills
// everything Inspect leaves (left/right edges rather than a width, so the
// inset matches top and bottom) and cuts straight in instead of sliding.
// Overrides the shared UI, so it is spread last.
const debugTray: CSSProperties = {
- right: TRAY_EDGE + inspectSlot,
- bottom: TRAY_EDGE,
+ [side]: TRAY_EDGE + inspectSlot,
+ [edge]: TRAY_EDGE,
height: BLOCK_H,
width: `max(${DEBUG_MIN_WIDTH}px, calc(${BLOCK_W} - ${inspectSlot}px))`,
transform: "none",
@@ -153,23 +160,22 @@ export function OpenUIDevtoolsWidget({
return (
<DevtoolsModeProvider mode={mode}>
<style>{INTER_FONT_FACE}</style>
- <DeployHint position={position} hidden={open || debug.trayOpen} />
+ <DeployHint position={corner} hidden={open || debug.trayOpen || drag.dragging} />
<div
- ref={toggleRef}
- style={{
- ...styles.toggleWrap,
- ...rootStyle(mode),
- ...positionStyles[position],
- ...(lift ? { [anchor]: 16 + lift } : null),
- }}
+ ref={drag.ref}
+ style={{ ...styles.toggleWrap, ...rootStyle(mode), ...positionStyles[corner] }}
>
<button
style={{
...styles.toggle,
...(errorCount > 0 ? styles.toggleError : null),
...(toggleHovered ? styles.toggleHover : null),
+ ...(drag.dragging ? styles.toggleDragging : null),
+ }}
+ {...drag.handlers}
+ onClick={() => {
+ if (!drag.consumeDrag()) setOpen(true);
}}
- onClick={() => setOpen(true)}
onMouseEnter={() => setToggleHovered(true)}
onMouseLeave={() => setToggleHovered(false)}
aria-label="Open OpenUI Inspect"
@@ -374,6 +380,14 @@ function SettingsMenu({
<span style={styles.menuLabel}>Theme</span>
<ThemeSegmented value={config.theme} onChange={(theme) => onChange({ theme })} />
</div>
+ <div style={styles.menuDivider} />
+ <div style={styles.menuRow}>
+ <span style={styles.menuLabel}>Position</span>
+ <PositionSegmented
+ value={config.position}
+ onChange={(position) => onChange({ position })}
+ />
+ </div>
</div>
) : null}
</div>
@@ -411,11 +425,16 @@ function uiStyles(t: ThemeTokens) {
boxShadow: t.toggleShadow,
fontFamily: FONT,
padding: 0,
+ touchAction: "none",
transition: "background 150ms ease, box-shadow 150ms ease, transform 150ms ease",
},
toggleHover: {
transform: "scale(1.08)",
},
+ toggleDragging: {
+ cursor: "grabbing",
+ transform: "scale(1.08)",
+ },
// Errors swap the mark for a count on a red disc, held inside a light puck so
// the number reads as a badge rather than flooding the whole button red.
toggleError: {
@@ -437,7 +456,7 @@ function uiStyles(t: ThemeTokens) {
fontWeight: 700,
lineHeight: 1,
},
- // Geometry (right/width/transform) is per-tray and set inline; this is the
+ // Geometry (side/width/transform) is per-tray and set inline; this is the
// shared UI. Each tray hides itself when closed so the other can stay open
// without a retracted tray remaining focusable.
drawer: {
@@ -458,13 +477,13 @@ function uiStyles(t: ThemeTokens) {
fontSize: 13,
visibility: "hidden",
transition:
- "transform 220ms cubic-bezier(0.32, 0.72, 0, 1), right 260ms cubic-bezier(0.32, 0.72, 0, 1), width 260ms cubic-bezier(0.32, 0.72, 0, 1), visibility 0s linear 220ms",
+ "transform 220ms cubic-bezier(0.32, 0.72, 0, 1), right 260ms cubic-bezier(0.32, 0.72, 0, 1), left 260ms cubic-bezier(0.32, 0.72, 0, 1), width 260ms cubic-bezier(0.32, 0.72, 0, 1), visibility 0s linear 220ms",
overflow: "hidden",
},
drawerOpen: {
visibility: "visible",
transition:
- "transform 220ms cubic-bezier(0.32, 0.72, 0, 1), right 260ms cubic-bezier(0.32, 0.72, 0, 1), width 260ms cubic-bezier(0.32, 0.72, 0, 1), visibility 0s",
+ "transform 220ms cubic-bezier(0.32, 0.72, 0, 1), right 260ms cubic-bezier(0.32, 0.72, 0, 1), left 260ms cubic-bezier(0.32, 0.72, 0, 1), width 260ms cubic-bezier(0.32, 0.72, 0, 1), visibility 0s",
},
debugHost: {
flex: 1,
diff --git a/packages/devtools/src/browser-shims/react.ts b/packages/devtools/src/browser-shims/react.ts
index ef7f14593..1c61380cc 100644
--- a/packages/devtools/src/browser-shims/react.ts
+++ b/packages/devtools/src/browser-shims/react.ts
@@ -5,6 +5,7 @@ const react = requireReact();
export const {
useState,
useEffect,
+ useLayoutEffect,
useCallback,
useMemo,
useRef,
diff --git a/packages/devtools/src/lib/index.ts b/packages/devtools/src/lib/index.ts
index 89beadca0..7df502652 100644
--- a/packages/devtools/src/lib/index.ts
+++ b/packages/devtools/src/lib/index.ts
@@ -10,4 +10,5 @@ export {
} from "./libraryRegistry";
export { withDevtoolsAttribution } from "./links";
export { useDevtoolsSingleton } from "./singleton";
+export { cornerToward, useCornerDrag } from "./useCornerDrag";
export { useDevtoolsConfig, type DevtoolsConfig } from "./useDevtoolsConfig";
diff --git a/packages/devtools/src/lib/useCornerDrag.test.ts b/packages/devtools/src/lib/useCornerDrag.test.ts
new file mode 100644
index 000000000..d226cf215
--- /dev/null
+++ b/packages/devtools/src/lib/useCornerDrag.test.ts
@@ -0,0 +1,26 @@
+import { describe, expect, it } from "vitest";
+import { cornerToward } from "./useCornerDrag";
+
+describe("cornerToward", () => {
+ it("switches the axis a short drag heads along", () => {
+ expect(cornerToward("bottom-right", -10, 0)).toBe("bottom-left");
+ expect(cornerToward("bottom-right", 0, -10)).toBe("top-right");
+ expect(cornerToward("top-left", 10, 0)).toBe("top-right");
+ expect(cornerToward("top-left", 0, 10)).toBe("bottom-left");
+ });
+
+ it("switches both axes on a diagonal drag", () => {
+ expect(cornerToward("bottom-right", -10, -10)).toBe("top-left");
+ expect(cornerToward("top-left", 10, 10)).toBe("bottom-right");
+ });
+
+ it("ignores the minor axis of a mostly straight drag", () => {
+ expect(cornerToward("bottom-right", -10, -3)).toBe("bottom-left");
+ expect(cornerToward("bottom-right", -3, -10)).toBe("top-right");
+ });
+
+ it("stays put when dragged toward the edge it is on", () => {
+ expect(cornerToward("bottom-right", 10, 10)).toBe("bottom-right");
+ expect(cornerToward("top-left", -5, -8)).toBe("top-left");
+ });
+});
diff --git a/packages/devtools/src/lib/useCornerDrag.ts b/packages/devtools/src/lib/useCornerDrag.ts
new file mode 100644
index 000000000..bf270219c
--- /dev/null
+++ b/packages/devtools/src/lib/useCornerDrag.ts
@@ -0,0 +1,143 @@
+import { useLayoutEffect, useRef, useState, type PointerEvent as ReactPointerEvent } from "react";
+import type { DevtoolsPosition } from "../types";
+
+/** Pointer travel (px) before a press on the launcher counts as a drag. */
+const DRAG_THRESHOLD = 4;
+const SNAP_TRANSITION = "transform 320ms cubic-bezier(0.22, 1, 0.36, 1)";
+
+/** Drags within this angle (22.5°) of an axis only switch that axis. */
+const AXIS_RATIO = Math.tan(Math.PI / 8);
+
+/**
+ * The corner a drag from `from` heads toward. Each axis switches side when
+ * the drag moves toward the other side, so a short flick is enough.
+ */
+export function cornerToward(from: DevtoolsPosition, dx: number, dy: number): DevtoolsPosition {
+ let vertical = from.startsWith("top") ? "top" : "bottom";
+ let horizontal = from.endsWith("left") ? "left" : "right";
+ if (Math.abs(dy) > Math.abs(dx) * AXIS_RATIO) {
+ if (dy > 0) vertical = "bottom";
+ else if (dy < 0) vertical = "top";
+ }
+ if (Math.abs(dx) > Math.abs(dy) * AXIS_RATIO) {
+ if (dx > 0) horizontal = "right";
+ else if (dx < 0) horizontal = "left";
+ }
+ return `${vertical}-${horizontal}` as DevtoolsPosition;
+}
+
+/**
+ * Drag-to-snap for the launcher. While dragging, the element behind `ref`
+ * follows the pointer (written straight to the DOM, so the widget doesn't
+ * re-render per move). On release it reports the corner it was dragged
+ * toward and glides from the drop point into that corner. A press that never passes
+ * the threshold stays a click; the click that ends a drag is swallowed.
+ */
+export function useCornerDrag(
+ corner: DevtoolsPosition,
+ onSnap: (corner: DevtoolsPosition) => void,
+) {
+ const ref = useRef<HTMLDivElement>(null);
+ const start = useRef<{
+ x: number;
+ y: number;
+ pressX: number;
+ pressY: number;
+ id: number;
+ } | null>(null);
+ const dragged = useRef(false);
+ const frame = useRef(0);
+ const dropRect = useRef<DOMRect | null>(null);
+ const [dragging, setDragging] = useState(false);
+
+ // After the drop re-render has moved the launcher to its new corner, start
+ // it back at the drop point and transition the difference away (FLIP).
+ useLayoutEffect(() => {
+ const el = ref.current;
+ const from = dropRect.current;
+ if (!el || !from) return;
+ dropRect.current = null;
+ el.style.transition = "none";
+ el.style.transform = "";
+ const to = el.getBoundingClientRect();
+ const dx = from.left - to.left;
+ const dy = from.top - to.top;
+ el.style.transform = `translate3d(${dx}px, ${dy}px, 0)`;
+ if (window.matchMedia?.("(prefers-reduced-motion: reduce)").matches) {
+ el.style.transform = "";
+ return;
+ }
+ void el.offsetWidth;
+ el.style.transition = SNAP_TRANSITION;
+ el.style.transform = "";
+ });
+
+ const onPointerDown = (event: ReactPointerEvent<HTMLElement>) => {
+ if (event.button !== 0) return;
+ start.current = {
+ x: event.clientX,
+ y: event.clientY,
+ pressX: event.clientX,
+ pressY: event.clientY,
+ id: event.pointerId,
+ };
+ dragged.current = false;
+ // Keep receiving moves once the pointer outruns the 40px button.
+ event.currentTarget.setPointerCapture(event.pointerId);
+ };
+
+ const onPointerMove = (event: ReactPointerEvent<HTMLElement>) => {
+ const origin = start.current;
+ const el = ref.current;
+ if (!origin || !el || origin.id !== event.pointerId) return;
+ if (!dragged.current) {
+ if (Math.hypot(event.clientX - origin.x, event.clientY - origin.y) < DRAG_THRESHOLD) return;
+ dragged.current = true;
+ setDragging(true);
+ // Pick it up from where it is on screen, even mid-glide.
+ const { m41, m42 } = new DOMMatrix(getComputedStyle(el).transform);
+ origin.x -= m41;
+ origin.y -= m42;
+ }
+ const x = event.clientX - origin.x;
+ const y = event.clientY - origin.y;
+ cancelAnimationFrame(frame.current);
+ frame.current = requestAnimationFrame(() => {
+ el.style.transition = "none";
+ el.style.transform = `translate3d(${x}px, ${y}px, 0)`;
+ });
+ };
+
+ const end = (event: ReactPointerEvent<HTMLElement>, snap: boolean) => {
+ const origin = start.current;
+ const el = ref.current;
+ if (!origin || origin.id !== event.pointerId) return;
+ start.current = null;
+ cancelAnimationFrame(frame.current);
+ if (!dragged.current || !el) return;
+ setDragging(false);
+ dropRect.current = el.getBoundingClientRect();
+ if (snap) {
+ onSnap(cornerToward(corner, event.clientX - origin.pressX, event.clientY - origin.pressY));
+ }
+ };
+
+ /** True (once) when the click being handled is the tail of a drag. */
+ const consumeDrag = () => {
+ const wasDrag = dragged.current;
+ dragged.current = false;
+ return wasDrag;
+ };
+
+ return {
+ ref,
+ dragging,
+ consumeDrag,
+ handlers: {
+ onPointerDown,
+ onPointerMove,
+ onPointerUp: (event: ReactPointerEvent<HTMLElement>) => end(event, true),
+ onPointerCancel: (event: ReactPointerEvent<HTMLElement>) => end(event, false),
+ },
+ };
+}
diff --git a/packages/devtools/src/lib/useDevtoolsConfig.ts b/packages/devtools/src/lib/useDevtoolsConfig.ts
index ad57ec705..347a4d86a 100644
--- a/packages/devtools/src/lib/useDevtoolsConfig.ts
+++ b/packages/devtools/src/lib/useDevtoolsConfig.ts
@@ -1,6 +1,7 @@
import { useCallback, useEffect, useRef, useState } from "react";
import { MAX_EDITOR_PCT, MIN_EDITOR_PCT } from "../debug/DebugUI";
import type { ColorMode } from "../theme";
+import type { DevtoolsPosition } from "../types";
const STORAGE_KEY = "openui.devtools.config";
@@ -8,6 +9,8 @@ export type DevtoolsConfig = {
autoOpen: boolean;
onlyErrors: boolean;
theme: ColorMode;
+ /** Corner the launcher sits in. */
+ position: DevtoolsPosition;
/** Set once the Debug help dialog has been dismissed, so it only greets once. */
helpSeen: boolean;
/** Editor column width in OpenUI Debug, as a percentage of the split. */
@@ -18,11 +21,21 @@ function isColorMode(value: unknown): value is ColorMode {
return value === "light" || value === "dark";
}
+function isPosition(value: unknown): value is DevtoolsPosition {
+ return (
+ value === "top-left" ||
+ value === "top-right" ||
+ value === "bottom-left" ||
+ value === "bottom-right"
+ );
+}
+
function sanitize(patch: Partial<DevtoolsConfig>): Partial<DevtoolsConfig> {
const next: Partial<DevtoolsConfig> = {};
if (typeof patch.autoOpen === "boolean") next.autoOpen = patch.autoOpen;
if (typeof patch.onlyErrors === "boolean") next.onlyErrors = patch.onlyErrors;
if (isColorMode(patch.theme)) next.theme = patch.theme;
+ if (isPosition(patch.position)) next.position = patch.position;
if (typeof patch.helpSeen === "boolean") next.helpSeen = patch.helpSeen;
if (typeof patch.editorPct === "number" && Number.isFinite(patch.editorPct)) {
next.editorPct = Math.min(MAX_EDITOR_PCT, Math.max(MIN_EDITOR_PCT, patch.editorPct));
diff --git a/packages/devtools/src/ui/PositionSegmented.tsx b/packages/devtools/src/ui/PositionSegmented.tsx
new file mode 100644
index 000000000..e936e1188
--- /dev/null
+++ b/packages/devtools/src/ui/PositionSegmented.tsx
@@ -0,0 +1,61 @@
+import { ArrowDownLeft, ArrowDownRight, ArrowUpLeft, ArrowUpRight } from "lucide-react";
+import type { CSSProperties } from "react";
+import { useStyles, type ThemeTokens } from "../theme";
+import type { DevtoolsPosition } from "../types";
+import { IconButton } from "./IconButton";
+
+const OPTIONS: { id: DevtoolsPosition; label: string; icon: typeof ArrowUpLeft }[] = [
+ { id: "top-left", label: "Top left", icon: ArrowUpLeft },
+ { id: "top-right", label: "Top right", icon: ArrowUpRight },
+ { id: "bottom-left", label: "Bottom left", icon: ArrowDownLeft },
+ { id: "bottom-right", label: "Bottom right", icon: ArrowDownRight },
+];
+
+/** Four icon buttons for the Inspect settings menu that pick the launcher's corner. */
+export function PositionSegmented({
+ value,
+ onChange,
+}: {
+ value: DevtoolsPosition;
+ onChange: (value: DevtoolsPosition) => void;
+}) {
+ const styles = useStyles(segmentedStyles);
+ return (
+ <div style={styles.segmented} role="radiogroup" aria-label="Position">
+ {OPTIONS.map((option) => {
+ const active = value === option.id;
+ const Icon = option.icon;
+ return (
+ <IconButton
+ key={option.id}
+ type="button"
+ role="radio"
+ aria-checked={active}
+ style={active ? styles.selected : undefined}
+ onClick={() => onChange(option.id)}
+ aria-label={option.label}
+ title={option.label}
+ >
+ <Icon size={14} />
+ </IconButton>
+ );
+ })}
+ </div>
+ );
+}
+
+function segmentedStyles(t: ThemeTokens) {
+ return {
+ segmented: {
+ display: "inline-flex",
+ alignItems: "center",
+ gap: 2,
+ flexShrink: 0,
+ },
+ selected: {
+ background: t.inverted,
+ color: t.invertedFg,
+ borderColor: t.inverted,
+ },
+ } satisfies Record<string, CSSProperties>;
+}
diff --git a/packages/devtools/src/ui/avoidHostControls.test.ts b/packages/devtools/src/ui/avoidHostControls.test.ts
deleted file mode 100644
index 3da2f8fde..000000000
--- a/packages/devtools/src/ui/avoidHostControls.test.ts
+++ /dev/null
@@ -1,43 +0,0 @@
-import { describe, expect, it } from "vitest";
-import { liftToClear, type Box } from "./avoidHostControls";
-
-// A 40px launcher 16px above the bottom of a 768px-tall window.
-const launcher: Box = { top: 712, bottom: 752, left: 712, right: 752 };
-
-const overlaps = (a: Box, b: Box) =>
- a.left < b.right && a.right > b.left && a.top < b.bottom && a.bottom > b.top;
-const controlsAt = (controls: Box[]) => (box: Box) =>
- controls.find((c) => overlaps(box, c)) ?? null;
-
-describe("liftToClear", () => {
- it("stays put when nothing is underneath", () => {
- expect(liftToClear(launcher, "bottom", controlsAt([]), 300)).toBe(0);
- });
-
- it("moves a bottom launcher just above a control it covers", () => {
- const send: Box = { top: 700, bottom: 736, left: 700, right: 736 };
- const lift = liftToClear(launcher, "bottom", controlsAt([send]), 300);
- expect(lift).toBe(752 - 700 + 8);
- const moved = { ...launcher, top: launcher.top - lift, bottom: launcher.bottom - lift };
- expect(overlaps(moved, send)).toBe(false);
- });
-
- it("clears controls stacked above each other", () => {
- const send: Box = { top: 700, bottom: 736, left: 700, right: 736 };
- const chip: Box = { top: 640, bottom: 680, left: 690, right: 760 };
- const lift = liftToClear(launcher, "bottom", controlsAt([send, chip]), 300);
- const moved = { ...launcher, top: launcher.top - lift, bottom: launcher.bottom - lift };
- expect(overlaps(moved, send) || overlaps(moved, chip)).toBe(false);
- });
-
- it("moves a top launcher down below a control", () => {
- const top: Box = { top: 16, bottom: 56, left: 712, right: 752 };
- const toggle: Box = { top: 12, bottom: 44, left: 720, right: 752 };
- expect(liftToClear(top, "top", controlsAt([toggle]), 300)).toBe(44 + 8 - 16);
- });
-
- it("gives up rather than moving further than the limit", () => {
- const tall: Box = { top: 100, bottom: 760, left: 700, right: 760 };
- expect(liftToClear(launcher, "bottom", controlsAt([tall]), 300)).toBe(0);
- });
-});
diff --git a/packages/devtools/src/ui/avoidHostControls.ts b/packages/devtools/src/ui/avoidHostControls.ts
deleted file mode 100644
index 8a33dbdd0..000000000
--- a/packages/devtools/src/ui/avoidHostControls.ts
+++ /dev/null
@@ -1,135 +0,0 @@
-import { useEffect, useState, type RefObject } from "react";
-
-export interface Box {
- top: number;
- bottom: number;
- left: number;
- right: number;
-}
-
-/** Gap kept between the launcher and the host control it moves clear of. */
-const GAP = 8;
-/** Never move the launcher more than this share of the viewport height. */
-const MAX_SHARE = 0.4;
-/** Throttle for re-checking after DOM changes (e.g. while a reply streams). */
-const RECHECK_MS = 250;
-
-const INTERACTIVE =
- 'button, a[href], input, textarea, select, [role="button"], [contenteditable="true"]';
-
-/**
- * How far to move a launcher at `base` so it no longer covers a host control.
- * `controlAt(box)` returns the box of a host control under `box`, or null.
- * Bottom-anchored launchers move up, top-anchored ones move down.
- */
-export function liftToClear(
- base: Box,
- anchor: "top" | "bottom",
- controlAt: (box: Box) => Box | null,
- maxLift: number,
-): number {
- let lift = 0;
- // A few rounds handle controls stacked above each other.
- for (let round = 0; round < 6; round++) {
- const box =
- anchor === "bottom"
- ? { ...base, top: base.top - lift, bottom: base.bottom - lift }
- : { ...base, top: base.top + lift, bottom: base.bottom + lift };
- const control = controlAt(box);
- if (!control) return lift;
- const next =
- anchor === "bottom" ? base.bottom - control.top + GAP : control.bottom + GAP - base.top;
- if (next <= lift || next > maxLift) return lift;
- lift = next;
- }
- return lift;
-}
-
-/** The host page's interactive element under `box`, ignoring the devtools' own UI. */
-function hostControlAt(box: Box, ownRoot: Element | null): Box | null {
- // Not available in every environment (e.g. jsdom); then just don't move.
- if (typeof document.elementsFromPoint !== "function") return null;
- const inset = 4;
- const points: Array<[number, number]> = [
- [(box.left + box.right) / 2, (box.top + box.bottom) / 2],
- [box.left + inset, box.top + inset],
- [box.right - inset, box.top + inset],
- [box.left + inset, box.bottom - inset],
- [box.right - inset, box.bottom - inset],
- ];
- for (const [x, y] of points) {
- for (const el of document.elementsFromPoint(x, y)) {
- if (ownRoot?.contains(el)) continue;
- const control = el.closest(INTERACTIVE);
- if (control && !ownRoot?.contains(control)) {
- const r = control.getBoundingClientRect();
- return { top: r.top, bottom: r.bottom, left: r.left, right: r.right };
- }
- }
- }
- return null;
-}
-
-/**
- * Keeps a fixed-position launcher off the host app's own controls (e.g. a chat
- * composer's Send button on a narrow window). Returns the extra offset to add
- * to the launcher's top/bottom inset.
- */
-export function useAvoidHostControls(
- ref: RefObject<HTMLElement | null>,
- anchor: "top" | "bottom",
- enabled = true,
-): number {
- const [lift, setLift] = useState(0);
-
- useEffect(() => {
- if (!enabled || typeof document === "undefined") return;
- let current = 0;
- let timer: ReturnType<typeof setTimeout> | null = null;
-
- const check = () => {
- timer = null;
- const el = ref.current;
- if (!el) return;
- const r = el.getBoundingClientRect();
- // Measure from the un-lifted position.
- const shift = anchor === "bottom" ? current : -current;
- const base = { top: r.top + shift, bottom: r.bottom + shift, left: r.left, right: r.right };
- // The devtools render into their own container appended to <body>.
- let ownRoot: Element = el;
- while (ownRoot.parentElement && ownRoot.parentElement !== document.body) {
- ownRoot = ownRoot.parentElement;
- }
- let next = current;
- try {
- next = liftToClear(
- base,
- anchor,
- (box) => hostControlAt(box, ownRoot),
- window.innerHeight * MAX_SHARE,
- );
- } catch {
- // Never let placement break the host page.
- }
- if (next !== current) {
- current = next;
- setLift(next);
- }
- };
- const schedule = () => {
- if (timer === null) timer = setTimeout(check, RECHECK_MS);
- };
-
- check();
- window.addEventListener("resize", schedule);
- const observer = new MutationObserver(schedule);
- observer.observe(document.body, { childList: true, subtree: true });
- return () => {
- if (timer !== null) clearTimeout(timer);
- window.removeEventListener("resize", schedule);
- observer.disconnect();
- };
- }, [ref, anchor, enabled]);
-
- return lift;
-}
diff --git a/packages/devtools/src/ui/index.ts b/packages/devtools/src/ui/index.ts
index 1c44376c2..c644399ff 100644
--- a/packages/devtools/src/ui/index.ts
+++ b/packages/devtools/src/ui/index.ts
@@ -1,5 +1,6 @@
export { ErrorBoundary, ISSUES_URL } from "./ErrorBoundary";
export { IconButton } from "./IconButton";
export { INTER_FAMILY, INTER_FONT_FACE } from "./inter";
+export { PositionSegmented } from "./PositionSegmented";
export { ShiroLogo } from "./ShiroLogo";
export { ThemeSegmented, ThemeToggle } from "./ThemeToggle";