The platform for continuously improving AI agents.
// Adapted from AI SDK Agents selection-actions; see NOTICE.md.
import type { CSSProperties, FormEvent, ReactNode } from "react";
import { useCallback, useEffect, useLayoutEffect, useRef, useState } from "react";
import { createPortal } from "react-dom";
import { Icon as AppIcon } from "@/components/ui/icons";
import { cn } from "@/lib/utils";
import { ComponentIcon } from "./component-icon";
const ArrowUp02Icon = AppIcon.send;
export interface SelectionAction {
id: string;
label: string;
prompt?: string;
}
export interface SelectionActionEvent {
id: string;
text: string;
message: string;
}
export const quoteReply = (text: string, reply = ""): string => {
const quote = text
.trim()
.split("\n")
.map((line) => `> ${line}`.trimEnd())
.join("\n");
return `${quote}\n\n${reply}`;
};
export interface SelectionActionsClassNames {
root?: string;
toolbar?: string;
action?: string;
input?: string;
}
export interface SelectionActionsProps {
children: ReactNode;
actions?: readonly SelectionAction[];
onAction?: (event: SelectionActionEvent) => void;
onAsk?: (event: SelectionActionEvent & { question: string }) => void;
copy?: boolean;
onCopy?: (text: string) => void;
minLength?: number;
disabled?: boolean;
className?: string;
classNames?: SelectionActionsClassNames;
style?: CSSProperties;
}
const DEFAULT_ACTIONS: SelectionAction[] = [
{ id: "explain", label: "Explain", prompt: "Explain this in plain terms." },
{ id: "shorten", label: "Shorten", prompt: "Say this in fewer words." },
{ id: "quote", label: "Quote" },
];
const HIGHLIGHT_NAME = "selection-actions";
const GAP = 8;
const EDGE = 8;
const COPIED_MS = 900;
// It is placed by writing `left` and `top`, so it must not transition: a
// transition on those would slide it in from the corner of the page. The
// entrance is a keyframe instead: a short rise out of the selection.
const TOOLBAR_CLASS =
"fade-in-0 zoom-in-[0.97] fixed top-0 left-0 z-50 flex animate-in items-center gap-0.5 rounded-md border border-border bg-popover p-1 text-popover-foreground transition-none duration-150 ease-[cubic-bezier(0.19,1,0.22,1)] data-[side=bottom]:origin-top data-[side=bottom]:slide-in-from-top-1 data-[side=top]:origin-bottom data-[side=top]:slide-in-from-bottom-1 motion-reduce:animate-none ";
const FOCUS_CLASS = "focus-visible:ring-2 focus-visible:ring-ring/50 focus-visible:outline-none";
const ACTION_CLASS = cn(
"h-6 flex-none cursor-pointer rounded-md border-0 bg-transparent px-2 text-xs leading-none font-medium whitespace-nowrap text-popover-foreground transition-[background-color,transform] duration-150 ease-out hover:bg-accent active:scale-[0.96] motion-reduce:transition-none",
FOCUS_CLASS
);
interface Selected {
text: string;
range: Range;
}
const readSelection = (root: HTMLElement | null, minLength: number): Selected | null => {
const selection = document.getSelection();
if (!root || !selection || selection.isCollapsed || selection.rangeCount < 1) {
return null;
}
const range = selection.getRangeAt(0);
if (!root.contains(range.commonAncestorContainer)) {
return null;
}
const text = selection.toString().trim();
return text.length < minLength ? null : { range: range.cloneRange(), text };
};
const place = (toolbar: HTMLElement, range: Range, root: HTMLElement | null) => {
const rect = range.getBoundingClientRect();
const bounds = root?.getBoundingClientRect();
const offscreen =
rect.bottom < Math.max(0, bounds?.top ?? 0) ||
rect.top > Math.min(window.innerHeight, bounds?.bottom ?? window.innerHeight);
const { offsetHeight: height, offsetWidth: width } = toolbar;
// Touch screens put their own menu above a selection.
const coarse = window.matchMedia("(pointer: coarse)").matches;
const above = !coarse && rect.top - height - GAP >= EDGE;
const top = above ? rect.top - height - GAP : rect.bottom + GAP;
const left = Math.min(
Math.max(EDGE, rect.left + rect.width / 2 - width / 2),
Math.max(EDGE, window.innerWidth - width - EDGE)
);
const next = {
left: `${Math.round(left)}px`,
top: `${Math.round(top)}px`,
visibility: offscreen ? "hidden" : "visible",
};
// Written only on change, so an idle toolbar costs one measurement a frame.
if (toolbar.style.left !== next.left) {
toolbar.style.left = next.left;
}
if (toolbar.style.top !== next.top) {
toolbar.style.top = next.top;
}
// The side decides which way it rises, so set it before the first paint.
const side = above ? "top" : "bottom";
if (toolbar.dataset.side !== side) {
toolbar.dataset.side = side;
}
if (toolbar.style.visibility !== next.visibility) {
toolbar.style.visibility = next.visibility;
}
};
const useHeldHighlight = (range: Range | null) => {
useEffect(() => {
if (
!range ||
typeof CSS === "undefined" ||
typeof Highlight === "undefined" ||
!("highlights" in CSS)
) {
return;
}
CSS.highlights.set(HIGHLIGHT_NAME, new Highlight(range));
return () => {
CSS.highlights.delete(HIGHLIGHT_NAME);
};
}, [range]);
};
const AskField = ({
className,
onSubmit,
}: {
className?: string;
onSubmit: (question: string) => void;
}) => {
const [value, setValue] = useState("");
const field = useRef<HTMLInputElement>(null);
const question = value.trim();
useEffect(() => {
field.current?.focus();
}, []);
const submit = (event: FormEvent) => {
event.preventDefault();
if (question) {
onSubmit(question);
}
};
return (
<form
className="flex w-64 max-w-[calc(100vw-2rem)] animate-in items-center gap-1 duration-150 ease-out fade-in-0 motion-reduce:animate-none"
onSubmit={submit}
>
<input
aria-label="Ask about the selection"
className={cn(
"h-6 min-w-0 flex-1 border-0 bg-transparent px-2 text-xs leading-4 text-popover-foreground outline-none placeholder:text-muted-foreground",
className
)}
onChange={(event) => {
setValue(event.target.value);
}}
placeholder="Ask about this"
ref={field}
value={value}
/>
<button
aria-label="Add question to draft"
className={cn(
"flex size-6 flex-none cursor-pointer items-center justify-center rounded-sm border-0 bg-primary p-0 text-primary-foreground transition-[opacity,transform] duration-150 ease-out active:enabled:scale-[0.96] disabled:cursor-default disabled:opacity-40 motion-reduce:transition-none",
FOCUS_CLASS
)}
disabled={!question}
type="submit"
>
<ComponentIcon
aria-hidden="true"
className="size-3.5"
icon={ArrowUp02Icon}
strokeWidth={2}
/>
</button>
</form>
);
};
export const SelectionActions = ({
children,
actions = DEFAULT_ACTIONS,
onAction,
onAsk,
copy = false,
onCopy,
minLength = 2,
disabled = false,
className,
classNames,
style,
}: SelectionActionsProps) => {
const root = useRef<HTMLDivElement>(null);
const toolbar = useRef<HTMLDivElement>(null);
const dragging = useRef(false);
const [selected, setSelected] = useState<Selected | null>(null);
const [asking, setAsking] = useState(false);
const [copied, setCopied] = useState(false);
const askingRef = useRef(false);
askingRef.current = asking;
const close = useCallback(() => {
setSelected(null);
setAsking(false);
setCopied(false);
}, []);
const finish = useCallback(() => {
document.getSelection()?.removeAllRanges();
close();
}, [close]);
useEffect(() => {
if (disabled) {
setSelected(null);
setAsking(false);
return;
}
const sync = () => {
// The Ask field takes the selection with it. Keep what was picked.
if (askingRef.current) {
return;
}
setSelected(dragging.current ? null : readSelection(root.current, minLength));
};
const onPointerDown = (event: PointerEvent) => {
if (event.target instanceof Node && toolbar.current?.contains(event.target)) {
return;
}
dragging.current = true;
setAsking(false);
setSelected(null);
};
const onPointerUp = () => {
dragging.current = false;
// The selection settles after the pointer lifts.
setTimeout(sync, 0);
};
const onKeyDown = (event: KeyboardEvent) => {
if (event.key === "Escape") {
setSelected(null);
setAsking(false);
}
};
document.addEventListener("selectionchange", sync);
document.addEventListener("pointerdown", onPointerDown);
document.addEventListener("pointerup", onPointerUp);
document.addEventListener("keydown", onKeyDown);
return () => {
document.removeEventListener("selectionchange", sync);
document.removeEventListener("pointerdown", onPointerDown);
document.removeEventListener("pointerup", onPointerUp);
document.removeEventListener("keydown", onKeyDown);
};
}, [disabled, minLength]);
useLayoutEffect(() => {
const element = toolbar.current;
if (!selected || !element) {
return;
}
// The passage moves with scrolling, resizing, and content that streams in
// above it. Following it every frame covers all three.
let frame = 0;
const follow = () => {
place(element, selected.range, root.current);
frame = requestAnimationFrame(follow);
};
follow();
return () => {
cancelAnimationFrame(frame);
};
}, [selected]);
useEffect(() => {
if (!copied) {
return;
}
const timer = setTimeout(finish, COPIED_MS);
return () => {
clearTimeout(timer);
};
}, [copied, finish]);
useHeldHighlight(asking && selected ? selected.range : null);
const copyText = async (text: string) => {
try {
await navigator.clipboard.writeText(text);
setCopied(true);
onCopy?.(text);
} catch {
setCopied(false);
}
};
const hasToolbar = selected !== null && (Boolean(onAsk) || actions.length > 0 || copy);
return (
<div
className={cn(className, classNames?.root)}
data-slot="selection-actions"
onKeyDownCapture={(event) => {
if (selected && event.key === "Escape") {
event.preventDefault();
event.stopPropagation();
close();
}
}}
ref={root}
style={style}
>
{children}
{hasToolbar && selected
? createPortal(
<div
aria-label="Selection actions"
className={cn(TOOLBAR_CLASS, classNames?.toolbar)}
data-slot="selection-actions-toolbar"
// Pressing a button must not clear the selection it acts on.
onPointerDown={(event) => {
if (!(event.target instanceof HTMLInputElement)) {
event.preventDefault();
}
}}
ref={toolbar}
role="toolbar"
style={{ visibility: "hidden" }}
>
<style>{`::highlight(${HIGHLIGHT_NAME}){background-color:Highlight;color:HighlightText}`}</style>
{asking && onAsk ? (
<AskField
className={classNames?.input}
onSubmit={(question) => {
onAsk({
id: "ask",
message: quoteReply(selected.text, question),
question,
text: selected.text,
});
finish();
}}
/>
) : (
<>
{onAsk ? (
<button
className={cn(ACTION_CLASS, classNames?.action)}
data-slot="selection-actions-ask"
onClick={() => {
setAsking(true);
}}
type="button"
>
Ask
</button>
) : null}
{actions.map((action) => (
<button
className={cn(ACTION_CLASS, classNames?.action)}
data-slot="selection-actions-action"
key={action.id}
onClick={() => {
onAction?.({
id: action.id,
message: quoteReply(selected.text, action.prompt),
text: selected.text,
});
finish();
}}
type="button"
>
{action.label}
</button>
))}
{copy ? (
<button
className={cn(ACTION_CLASS, classNames?.action)}
data-slot="selection-actions-copy"
onClick={() => {
void copyText(selected.text);
}}
type="button"
>
{copied ? "Copied" : "Copy"}
</button>
) : null}
</>
)}
</div>,
document.body
)
: null}
</div>
);
};