@open-document/core 0.13.3 → 0.14.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (67) hide show
  1. package/dist/{build-CvsOak5B.js → build-CyBlmrjS.js} +1 -1
  2. package/dist/{check-CbUBwYmf.js → check-DUKDEem-.js} +3 -3
  3. package/dist/cli/bin.js +10 -21
  4. package/dist/{config-BWtOZ1jc.d.ts → config-cAV1OCuY.d.ts} +9 -1
  5. package/dist/{config-CltJJVsw.js → config-cNpYUpF6.js} +2746 -369
  6. package/dist/{context-CWgfsHoE.js → context-BPApOW9n.js} +1 -1
  7. package/dist/{dev-B8H2qT6G.js → dev-DrnOvsX3.js} +1 -1
  8. package/dist/{diff-BvIjjgnc.js → diff-BPMD2Knh.js} +2 -2
  9. package/dist/{export-DX30_s2q.js → export-DeVtL8aX.js} +3 -3
  10. package/dist/{import-DgsdJT5e.js → import-WAgWsuOv.js} +3 -2
  11. package/dist/index.d.ts +2 -2
  12. package/dist/ops/index.d.ts +3 -1
  13. package/dist/ops/index.js +2 -2
  14. package/dist/{ops-CSR5RlrE.js → ops-raK6424A.js} +2 -854
  15. package/dist/{preview-DYMUNjXL.js → preview-B8Vw9QCh.js} +1 -1
  16. package/dist/rolldown-runtime-D7D4PA-g.js +13 -0
  17. package/dist/{templates-B5Tz0AKb.js → templates-D9jAFJ8R.js} +3 -3
  18. package/dist/vite/index.d.ts +1 -1
  19. package/dist/vite/index.js +1 -1
  20. package/package.json +1 -1
  21. package/skills/create-doc/SKILL.md +1 -1
  22. package/skills/doc-authoring/SKILL.md +6 -0
  23. package/src/app/app.tsx +2 -0
  24. package/src/app/components/agent/agent-dock.tsx +75 -0
  25. package/src/app/components/agent/agent-markdown.tsx +45 -0
  26. package/src/app/components/agent/agent-panel.tsx +690 -0
  27. package/src/app/components/agent/agent-presence.tsx +74 -0
  28. package/src/app/components/agent/composer.tsx +120 -0
  29. package/src/app/components/agent/connect-view.tsx +183 -0
  30. package/src/app/components/agent/history-view.tsx +134 -0
  31. package/src/app/components/agent/provider-logo.tsx +23 -0
  32. package/src/app/components/agent/transcript.tsx +609 -0
  33. package/src/app/components/comments/comments-panel.tsx +26 -2
  34. package/src/app/components/inspector/inspector.tsx +17 -0
  35. package/src/app/components/note-markdown.tsx +85 -0
  36. package/src/app/components/page-error-boundary.tsx +84 -0
  37. package/src/app/components/page-frame.tsx +2 -1
  38. package/src/app/components/panel/resize-handle.tsx +129 -0
  39. package/src/app/components/ui/button.tsx +97 -0
  40. package/src/app/components/ui/popover.tsx +144 -0
  41. package/src/app/components/ui/tooltip.tsx +123 -0
  42. package/src/app/lib/agent/use-agent.ts +543 -0
  43. package/src/app/lib/diagnostics.ts +13 -0
  44. package/src/app/lib/export-dom.ts +2 -1
  45. package/src/app/lib/export-pdf.ts +2 -1
  46. package/src/app/lib/i18n-ja/agent-panel.ts +107 -0
  47. package/src/app/lib/i18n-ja/agent.ts +9 -0
  48. package/src/app/lib/i18n-ja/index.ts +9 -1
  49. package/src/app/lib/i18n-ko/agent-panel.ts +106 -0
  50. package/src/app/lib/i18n-ko/agent.ts +9 -0
  51. package/src/app/lib/i18n-ko/index.ts +9 -1
  52. package/src/app/lib/i18n-zh-cn/agent-panel.ts +105 -0
  53. package/src/app/lib/i18n-zh-cn/agent.ts +9 -0
  54. package/src/app/lib/i18n-zh-cn/index.ts +9 -1
  55. package/src/app/lib/i18n-zh-tw/agent-panel.ts +105 -0
  56. package/src/app/lib/i18n-zh-tw/agent.ts +9 -0
  57. package/src/app/lib/i18n-zh-tw/index.ts +9 -1
  58. package/src/app/lib/note-markdown.ts +116 -0
  59. package/src/app/lib/toast.ts +50 -0
  60. package/src/app/lib/use-auto-grow.ts +15 -0
  61. package/src/app/lib/use-doc-titles.ts +28 -0
  62. package/src/app/lib/use-locale.ts +144 -0
  63. package/src/app/lib/utils.ts +4 -0
  64. package/src/app/routes/doc-preview.tsx +103 -0
  65. package/src/app/routes/doc.tsx +118 -11
  66. package/src/app/routes/home.tsx +43 -8
  67. package/src/app/styles.css +193 -0
@@ -0,0 +1,85 @@
1
+ import { Fragment, type ReactNode, useMemo } from 'react';
2
+ import { type NoteBlock, type NoteInline, parseNoteMarkdown } from '@/lib/note-markdown';
3
+
4
+ const CODE_CLASS = 'rounded-[3px] bg-foreground/12 px-[0.3em] py-[0.1em] font-mono text-[0.9em]';
5
+
6
+ function renderInline(nodes: NoteInline[]): ReactNode {
7
+ return nodes.map((node, i) => {
8
+ switch (node.type) {
9
+ case 'text':
10
+ // biome-ignore lint/suspicious/noArrayIndexKey: static parse output, never reordered
11
+ return <Fragment key={i}>{node.text}</Fragment>;
12
+ case 'strong':
13
+ return (
14
+ // biome-ignore lint/suspicious/noArrayIndexKey: static parse output, never reordered
15
+ <strong key={i} className="font-semibold">
16
+ {renderInline(node.children)}
17
+ </strong>
18
+ );
19
+ case 'em':
20
+ return (
21
+ // biome-ignore lint/suspicious/noArrayIndexKey: static parse output, never reordered
22
+ <em key={i}>{renderInline(node.children)}</em>
23
+ );
24
+ case 'code':
25
+ return (
26
+ // biome-ignore lint/suspicious/noArrayIndexKey: static parse output, never reordered
27
+ <code key={i} className={CODE_CLASS}>
28
+ {node.text}
29
+ </code>
30
+ );
31
+ default:
32
+ return node satisfies never;
33
+ }
34
+ });
35
+ }
36
+
37
+ const HEADING_SIZES = { 1: 'text-[1.25em]', 2: 'text-[1.12em]', 3: 'text-[1.05em]' } as const;
38
+
39
+ function renderBlock(block: NoteBlock, key: number): ReactNode {
40
+ switch (block.type) {
41
+ case 'heading': {
42
+ // h4–h6 so note headings stay below the app's own UI headings in the
43
+ // presenter window's document outline.
44
+ const Tag = `h${block.level + 3}` as 'h4' | 'h5' | 'h6';
45
+ return (
46
+ <Tag key={key} className={`font-semibold ${HEADING_SIZES[block.level]}`}>
47
+ {renderInline(block.children)}
48
+ </Tag>
49
+ );
50
+ }
51
+ case 'list': {
52
+ const Tag = block.ordered ? 'ol' : 'ul';
53
+ return (
54
+ <Tag
55
+ key={key}
56
+ className={`space-y-[0.2em] pl-[1.4em] ${block.ordered ? 'list-decimal' : 'list-disc'}`}
57
+ >
58
+ {block.items.map((item, i) => (
59
+ // biome-ignore lint/suspicious/noArrayIndexKey: static parse output, never reordered
60
+ <li key={i}>{renderInline(item)}</li>
61
+ ))}
62
+ </Tag>
63
+ );
64
+ }
65
+ case 'paragraph':
66
+ return (
67
+ <p key={key}>
68
+ {block.lines.map((line, i) => (
69
+ // biome-ignore lint/suspicious/noArrayIndexKey: static parse output, never reordered
70
+ <Fragment key={i}>
71
+ {i > 0 && <br />}
72
+ {renderInline(line)}
73
+ </Fragment>
74
+ ))}
75
+ </p>
76
+ );
77
+ default:
78
+ return block satisfies never;
79
+ }
80
+ }
81
+
82
+ export function NoteMarkdown({ text }: { text: string }) {
83
+ const blocks = useMemo(() => parseNoteMarkdown(text), [text]);
84
+ return <div className="space-y-[0.65em] whitespace-pre-wrap">{blocks.map(renderBlock)}</div>;
85
+ }
@@ -0,0 +1,84 @@
1
+ import { Component, type ErrorInfo, type ReactNode } from 'react';
2
+ import { useT } from '../lib/i18n';
3
+
4
+ type Labels = { title: string; hint: string };
5
+ type Props = { index: number; labels: Labels; children: ReactNode };
6
+ type State = { error: Error | null; children: ReactNode };
7
+
8
+ /**
9
+ * A sheet whose document code throws while it renders. Without this, React
10
+ * takes the whole viewer down with it — the rail, the toolbar, the agent
11
+ * panel — and a save half-way through an edit (an agent's or the reader's:
12
+ * the use before the import) leaves a blank window that no later save brings
13
+ * back. Here the sheet says what broke, and the next reload of the document,
14
+ * which brings new page content, tries it again.
15
+ */
16
+ class Boundary extends Component<Props, State> {
17
+ state: State = { error: null, children: this.props.children };
18
+
19
+ static getDerivedStateFromError(error: Error): Partial<State> {
20
+ return { error };
21
+ }
22
+
23
+ static getDerivedStateFromProps(props: Props, state: State): Partial<State> | null {
24
+ // Page content is a new element only when the document reloaded.
25
+ if (props.children !== state.children) return { error: null, children: props.children };
26
+ return null;
27
+ }
28
+
29
+ componentDidCatch(error: Error, info: ErrorInfo): void {
30
+ console.error(`[open-doc] page ${this.props.index + 1} failed to render`, error, info);
31
+ }
32
+
33
+ render() {
34
+ const { error } = this.state;
35
+ if (!error) return this.props.children;
36
+ // Drawn on the paper, not in the chrome: plain colours, no theme tokens.
37
+ return (
38
+ <div
39
+ role="alert"
40
+ data-od-page-error=""
41
+ style={{
42
+ margin: 48,
43
+ padding: '16px 18px',
44
+ border: '1px solid #f1c4c0',
45
+ borderRadius: 6,
46
+ background: '#fdf3f2',
47
+ color: '#7a271a',
48
+ fontFamily: 'ui-sans-serif, system-ui, sans-serif',
49
+ fontSize: 13,
50
+ lineHeight: 1.5,
51
+ }}
52
+ >
53
+ <div style={{ fontWeight: 600 }}>{this.props.labels.title}</div>
54
+ <div
55
+ data-od-page-error-message=""
56
+ style={{
57
+ marginTop: 6,
58
+ fontFamily: 'ui-monospace, SFMono-Regular, Menlo, monospace',
59
+ fontSize: 12,
60
+ whiteSpace: 'pre-wrap',
61
+ }}
62
+ >
63
+ {error.message}
64
+ </div>
65
+ <div style={{ marginTop: 8, color: '#9a4a3d', fontSize: 12 }}>{this.props.labels.hint}</div>
66
+ </div>
67
+ );
68
+ }
69
+ }
70
+
71
+ export function PageErrorBoundary({ index, children }: { index: number; children?: ReactNode }) {
72
+ const t = useT();
73
+ return (
74
+ <Boundary
75
+ index={index}
76
+ labels={{
77
+ title: t('This page could not be drawn'),
78
+ hint: t('It is drawn again as soon as the source is saved.'),
79
+ }}
80
+ >
81
+ {children}
82
+ </Boundary>
83
+ );
84
+ }
@@ -4,6 +4,7 @@ import { type DesignSystem, designToCssVars } from '../lib/design';
4
4
  import { PAGE_ATTR, PAGE_INDEX_ATTR } from '../lib/outline';
5
5
  import { DocPageProvider } from '../lib/page-context';
6
6
  import type { PageGeometry } from '../lib/sdk';
7
+ import { PageErrorBoundary } from './page-error-boundary';
7
8
 
8
9
  type Props = {
9
10
  index: number;
@@ -107,7 +108,7 @@ export function PageFrame({
107
108
  }
108
109
  >
109
110
  <DocPageProvider index={index} total={total}>
110
- {children}
111
+ <PageErrorBoundary index={index}>{children}</PageErrorBoundary>
111
112
  <SheetWatermark text={watermark} />
112
113
  </DocPageProvider>
113
114
  </div>
@@ -0,0 +1,129 @@
1
+ import { useEffect, useRef, useState } from 'react';
2
+ import { clamp, cn } from '@/lib/utils';
3
+
4
+ export function useStoredWidth(key: string, fallback: number, min: number, max: number) {
5
+ const [width, setWidth] = useState<number>(() => {
6
+ try {
7
+ const parsed = Number(window.localStorage.getItem(key) ?? Number.NaN);
8
+ return Number.isFinite(parsed) ? clamp(parsed, min, max) : fallback;
9
+ } catch {
10
+ return fallback;
11
+ }
12
+ });
13
+ useEffect(() => {
14
+ try {
15
+ window.localStorage.setItem(key, String(width));
16
+ } catch {}
17
+ }, [key, width]);
18
+ return [width, setWidth] as const;
19
+ }
20
+
21
+ // A vertical splitter on one edge of a panel. `edge` is the side of the panel
22
+ // it sits on, so dragging away from the panel always makes it wider.
23
+ export function ResizeHandle({
24
+ width,
25
+ min,
26
+ max,
27
+ defaultWidth,
28
+ edge,
29
+ label,
30
+ onResize,
31
+ onResizingChange,
32
+ className,
33
+ }: {
34
+ width: number;
35
+ min: number;
36
+ max: number;
37
+ defaultWidth: number;
38
+ edge: 'left' | 'right';
39
+ label: string;
40
+ onResize: (width: number) => void;
41
+ onResizingChange?: (resizing: boolean) => void;
42
+ className?: string;
43
+ }) {
44
+ const [resizing, setResizing] = useState(false);
45
+ const dragRef = useRef<{ startX: number; startWidth: number } | null>(null);
46
+ const direction = edge === 'right' ? 1 : -1;
47
+
48
+ useEffect(() => {
49
+ onResizingChange?.(resizing);
50
+ if (!resizing) return;
51
+ const prev = {
52
+ cursor: document.body.style.cursor,
53
+ userSelect: document.body.style.userSelect,
54
+ };
55
+ document.body.style.cursor = 'col-resize';
56
+ document.body.style.userSelect = 'none';
57
+ return () => {
58
+ document.body.style.cursor = prev.cursor;
59
+ document.body.style.userSelect = prev.userSelect;
60
+ };
61
+ }, [resizing, onResizingChange]);
62
+
63
+ const onPointerDown = (e: React.PointerEvent<HTMLDivElement>) => {
64
+ e.preventDefault();
65
+ e.currentTarget.setPointerCapture(e.pointerId);
66
+ dragRef.current = { startX: e.clientX, startWidth: width };
67
+ setResizing(true);
68
+ };
69
+
70
+ const onPointerMove = (e: React.PointerEvent<HTMLDivElement>) => {
71
+ if (!dragRef.current) return;
72
+ const delta = (e.clientX - dragRef.current.startX) * direction;
73
+ onResize(clamp(dragRef.current.startWidth + delta, min, max));
74
+ };
75
+
76
+ const onPointerUp = (e: React.PointerEvent<HTMLDivElement>) => {
77
+ if (e.currentTarget.hasPointerCapture(e.pointerId)) {
78
+ e.currentTarget.releasePointerCapture(e.pointerId);
79
+ }
80
+ dragRef.current = null;
81
+ setResizing(false);
82
+ };
83
+
84
+ const onKeyDown = (e: React.KeyboardEvent<HTMLDivElement>) => {
85
+ const step = (e.shiftKey ? 32 : 8) * direction;
86
+ let next: number | null = null;
87
+ if (e.key === 'ArrowLeft') next = width - step;
88
+ else if (e.key === 'ArrowRight') next = width + step;
89
+ else if (e.key === 'Home') next = defaultWidth;
90
+ if (next === null) return;
91
+ e.preventDefault();
92
+ e.stopPropagation();
93
+ onResize(clamp(next, min, max));
94
+ };
95
+
96
+ return (
97
+ // biome-ignore lint/a11y/useSemanticElements: focusable resize handle (splitter pattern), not a static <hr>
98
+ <div
99
+ role="separator"
100
+ aria-orientation="vertical"
101
+ aria-label={label}
102
+ aria-valuenow={width}
103
+ aria-valuemin={min}
104
+ aria-valuemax={max}
105
+ tabIndex={0}
106
+ onPointerDown={onPointerDown}
107
+ onPointerMove={onPointerMove}
108
+ onPointerUp={onPointerUp}
109
+ onPointerCancel={onPointerUp}
110
+ onKeyDown={onKeyDown}
111
+ onDoubleClick={() => onResize(defaultWidth)}
112
+ className={cn(
113
+ 'group/resize absolute inset-y-0 z-20 w-1.5 cursor-col-resize touch-none outline-none',
114
+ 'focus-visible:bg-brand/20',
115
+ className,
116
+ )}
117
+ >
118
+ <span
119
+ aria-hidden
120
+ className={cn(
121
+ 'pointer-events-none absolute inset-y-0 w-px bg-brand opacity-0 transition-opacity duration-150',
122
+ edge === 'right' ? 'left-1/2 -translate-x-1/2' : 'left-0',
123
+ 'group-hover/resize:opacity-100 group-focus-visible/resize:opacity-100',
124
+ resizing && 'opacity-100',
125
+ )}
126
+ />
127
+ </div>
128
+ );
129
+ }
@@ -0,0 +1,97 @@
1
+ import type * as React from 'react';
2
+ import { cn } from '@/lib/utils';
3
+
4
+ /*
5
+ * Editorial button. Tight square-ish radius, hairline borders instead of
6
+ * shadcn's default ring/shadow stack. The default variant is the strongest
7
+ * affordance — solid ink with subtle inner highlight on hover so the press
8
+ * feels physical without glow.
9
+ */
10
+ const BASE = [
11
+ 'group/button relative inline-flex shrink-0 items-center justify-center',
12
+ 'rounded-[6px] text-[13px] font-medium whitespace-nowrap select-none',
13
+ 'outline-none transition-[background-color,color,border-color,box-shadow,transform] duration-100',
14
+ 'focus-visible:ring-2 focus-visible:ring-ring/40 focus-visible:ring-offset-1 focus-visible:ring-offset-background',
15
+ 'active:not-aria-[haspopup]:translate-y-px',
16
+ 'disabled:pointer-events-none disabled:opacity-45',
17
+ 'aria-invalid:border-destructive aria-invalid:ring-destructive/30',
18
+ "[&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-3.5",
19
+ ].join(' ');
20
+
21
+ const VARIANTS = {
22
+ default: [
23
+ 'bg-foreground text-background',
24
+ 'shadow-[inset_0_1px_0_oklch(1_0_0/0.12),0_1px_0_oklch(0_0_0/0.12)]',
25
+ 'hover:bg-foreground/90',
26
+ 'aria-expanded:bg-foreground/85',
27
+ ].join(' '),
28
+ brand: [
29
+ 'bg-brand text-brand-foreground',
30
+ 'shadow-[inset_0_1px_0_oklch(1_0_0/0.18),0_1px_0_oklch(0_0_0/0.16)]',
31
+ 'hover:brightness-105 active:brightness-95',
32
+ ].join(' '),
33
+ outline: [
34
+ 'border border-border bg-card text-foreground',
35
+ 'hover:bg-muted/60 hover:border-foreground/20',
36
+ 'aria-expanded:bg-muted aria-expanded:border-foreground/25',
37
+ 'data-pressed:bg-foreground data-pressed:text-background data-pressed:border-foreground',
38
+ ].join(' '),
39
+ secondary:
40
+ 'bg-secondary text-secondary-foreground hover:bg-secondary/80 aria-expanded:bg-secondary/90',
41
+ ghost: [
42
+ 'text-foreground/75 hover:text-foreground hover:bg-muted',
43
+ 'aria-expanded:bg-muted aria-expanded:text-foreground',
44
+ ].join(' '),
45
+ destructive: [
46
+ 'bg-destructive text-white',
47
+ 'shadow-[inset_0_1px_0_oklch(1_0_0/0.16),0_1px_0_oklch(0_0_0/0.12)]',
48
+ 'hover:brightness-105 active:brightness-95',
49
+ 'focus-visible:ring-destructive/35',
50
+ ].join(' '),
51
+ link: 'text-foreground underline decoration-foreground/30 decoration-1 underline-offset-[3px] hover:decoration-foreground/70 [&_svg]:hidden',
52
+ } as const;
53
+
54
+ const SIZES = {
55
+ default: 'h-8 gap-1.5 px-3',
56
+ xs: 'h-6 gap-1 rounded-[5px] px-2 text-[11.5px]',
57
+ sm: 'h-7 gap-1.5 rounded-[5px] px-2.5 text-[12px]',
58
+ lg: 'h-9 gap-1.5 px-3.5 text-[13.5px]',
59
+ icon: 'size-8',
60
+ 'icon-xs': 'size-6 rounded-[5px]',
61
+ 'icon-sm': 'size-7 rounded-[5px]',
62
+ 'icon-lg': 'size-9',
63
+ } as const;
64
+
65
+ type ButtonVariant = keyof typeof VARIANTS;
66
+ type ButtonSize = keyof typeof SIZES;
67
+
68
+ // The variants of open-slide's button, without a variant library: the runtime
69
+ // ships to users, so the chrome keeps its dependencies to what it already has.
70
+ function buttonVariants(opts: { variant?: ButtonVariant; size?: ButtonSize; className?: string }) {
71
+ return cn(
72
+ BASE,
73
+ VARIANTS[opts.variant ?? 'default'],
74
+ SIZES[opts.size ?? 'default'],
75
+ opts.className,
76
+ );
77
+ }
78
+
79
+ function Button({
80
+ className,
81
+ variant = 'default',
82
+ size = 'default',
83
+ ...props
84
+ }: React.ComponentProps<'button'> & { variant?: ButtonVariant; size?: ButtonSize }) {
85
+ return (
86
+ <button
87
+ type="button"
88
+ data-slot="button"
89
+ data-variant={variant}
90
+ data-size={size}
91
+ className={buttonVariants({ variant, size, className })}
92
+ {...props}
93
+ />
94
+ );
95
+ }
96
+
97
+ export { Button, buttonVariants };
@@ -0,0 +1,144 @@
1
+ import {
2
+ type ComponentProps,
3
+ createContext,
4
+ type ReactNode,
5
+ type RefObject,
6
+ useContext,
7
+ useEffect,
8
+ useLayoutEffect,
9
+ useRef,
10
+ useState,
11
+ } from 'react';
12
+ import { cn } from '@/lib/utils';
13
+
14
+ /**
15
+ * The popover the agent panel's model menu opens, without a headless-component
16
+ * library: an anchored panel that closes on an outside press, Escape, a scroll
17
+ * or a resize — the same contract as `Menu`.
18
+ */
19
+
20
+ type PopoverState = {
21
+ open: boolean;
22
+ setOpen: (open: boolean) => void;
23
+ triggerRef: RefObject<HTMLButtonElement>;
24
+ };
25
+
26
+ const PopoverContext = createContext<PopoverState | null>(null);
27
+
28
+ function usePopover(): PopoverState {
29
+ const state = useContext(PopoverContext);
30
+ if (!state) throw new Error('Popover parts must sit inside <Popover>');
31
+ return state;
32
+ }
33
+
34
+ export function Popover({
35
+ open,
36
+ onOpenChange,
37
+ children,
38
+ }: {
39
+ open: boolean;
40
+ onOpenChange: (open: boolean) => void;
41
+ children: ReactNode;
42
+ }) {
43
+ const triggerRef = useRef<HTMLButtonElement>(null);
44
+ return (
45
+ <PopoverContext.Provider value={{ open, setOpen: onOpenChange, triggerRef }}>
46
+ {children}
47
+ </PopoverContext.Provider>
48
+ );
49
+ }
50
+
51
+ export function PopoverTrigger({ onClick, ...props }: ComponentProps<'button'>) {
52
+ const { open, setOpen, triggerRef } = usePopover();
53
+ return (
54
+ <button
55
+ ref={triggerRef}
56
+ aria-haspopup="dialog"
57
+ aria-expanded={open}
58
+ onClick={(event) => {
59
+ onClick?.(event);
60
+ setOpen(!open);
61
+ }}
62
+ {...props}
63
+ />
64
+ );
65
+ }
66
+
67
+ export function PopoverContent({
68
+ align = 'center',
69
+ className,
70
+ style,
71
+ ...props
72
+ }: ComponentProps<'div'> & { align?: 'start' | 'center' | 'end' }) {
73
+ const { open, setOpen, triggerRef } = usePopover();
74
+ const panelRef = useRef<HTMLDivElement>(null);
75
+ const [coords, setCoords] = useState<{ top: number; left: number } | null>(null);
76
+
77
+ useLayoutEffect(() => {
78
+ if (!open) {
79
+ setCoords(null);
80
+ return;
81
+ }
82
+ const anchor = triggerRef.current;
83
+ const panel = panelRef.current;
84
+ if (!anchor || !panel) return;
85
+ const a = anchor.getBoundingClientRect();
86
+ const p = panel.getBoundingClientRect();
87
+ const gap = 4;
88
+ let left =
89
+ align === 'start'
90
+ ? a.left
91
+ : align === 'end'
92
+ ? a.right - p.width
93
+ : a.left + (a.width - p.width) / 2;
94
+ let top = a.bottom + gap;
95
+ if (top + p.height > window.innerHeight - 8) top = a.top - gap - p.height;
96
+ left = Math.max(8, Math.min(left, window.innerWidth - p.width - 8));
97
+ top = Math.max(8, Math.min(top, window.innerHeight - p.height - 8));
98
+ setCoords({ top, left });
99
+ }, [open, align, triggerRef]);
100
+
101
+ useEffect(() => {
102
+ if (!open) return;
103
+ const close = () => setOpen(false);
104
+ const onPointerDown = (e: MouseEvent) => {
105
+ const target = e.target as Node;
106
+ if (panelRef.current?.contains(target) || triggerRef.current?.contains(target)) return;
107
+ close();
108
+ };
109
+ const onKeyDown = (e: KeyboardEvent) => {
110
+ if (e.key !== 'Escape') return;
111
+ close();
112
+ triggerRef.current?.focus();
113
+ };
114
+ const onScroll = (e: Event) => {
115
+ if (panelRef.current?.contains(e.target as Node)) return;
116
+ close();
117
+ };
118
+ document.addEventListener('mousedown', onPointerDown);
119
+ document.addEventListener('keydown', onKeyDown);
120
+ window.addEventListener('resize', close);
121
+ window.addEventListener('scroll', onScroll, true);
122
+ return () => {
123
+ document.removeEventListener('mousedown', onPointerDown);
124
+ document.removeEventListener('keydown', onKeyDown);
125
+ window.removeEventListener('resize', close);
126
+ window.removeEventListener('scroll', onScroll, true);
127
+ };
128
+ }, [open, setOpen, triggerRef]);
129
+
130
+ if (!open) return null;
131
+ return (
132
+ <div
133
+ ref={panelRef}
134
+ role="dialog"
135
+ className={cn(
136
+ 'fixed z-50 rounded-[8px] border border-hairline bg-popover text-popover-foreground shadow-floating outline-none',
137
+ coords ? 'visible' : 'invisible',
138
+ className,
139
+ )}
140
+ style={{ ...style, top: coords?.top ?? 0, left: coords?.left ?? 0 }}
141
+ {...props}
142
+ />
143
+ );
144
+ }
@@ -0,0 +1,123 @@
1
+ import {
2
+ cloneElement,
3
+ createContext,
4
+ type MutableRefObject,
5
+ type ReactElement,
6
+ type ReactNode,
7
+ useContext,
8
+ useId,
9
+ useLayoutEffect,
10
+ useRef,
11
+ useState,
12
+ } from 'react';
13
+ import { cn } from '@/lib/utils';
14
+
15
+ /**
16
+ * A hover-and-focus tooltip for the agent panel, without a headless-component
17
+ * library: shown while the trigger is hovered or focused, placed under it.
18
+ */
19
+
20
+ type TooltipState = {
21
+ open: boolean;
22
+ setOpen: (open: boolean) => void;
23
+ triggerRef: MutableRefObject<HTMLElement | null>;
24
+ id: string;
25
+ };
26
+
27
+ const TooltipContext = createContext<TooltipState | null>(null);
28
+
29
+ function useTooltip(): TooltipState {
30
+ const state = useContext(TooltipContext);
31
+ if (!state) throw new Error('Tooltip parts must sit inside <Tooltip>');
32
+ return state;
33
+ }
34
+
35
+ export function Tooltip({ children }: { children: ReactNode }) {
36
+ const [open, setOpen] = useState(false);
37
+ const triggerRef = useRef<HTMLElement | null>(null);
38
+ const id = useId();
39
+ return (
40
+ <TooltipContext.Provider value={{ open, setOpen, triggerRef, id }}>
41
+ {children}
42
+ </TooltipContext.Provider>
43
+ );
44
+ }
45
+
46
+ type TriggerProps = {
47
+ ref?: (node: HTMLElement | null) => void;
48
+ 'aria-describedby'?: string;
49
+ onMouseEnter?: () => void;
50
+ onMouseLeave?: () => void;
51
+ onFocus?: () => void;
52
+ onBlur?: () => void;
53
+ };
54
+
55
+ export function TooltipTrigger({ render }: { render: ReactElement<TriggerProps> }) {
56
+ const { open, setOpen, triggerRef, id } = useTooltip();
57
+ return cloneElement(render, {
58
+ ref: (node: HTMLElement | null) => {
59
+ triggerRef.current = node;
60
+ },
61
+ 'aria-describedby': open ? id : undefined,
62
+ onMouseEnter: () => setOpen(true),
63
+ onMouseLeave: () => setOpen(false),
64
+ onFocus: () => setOpen(true),
65
+ onBlur: () => setOpen(false),
66
+ });
67
+ }
68
+
69
+ export function TooltipContent({
70
+ side = 'bottom',
71
+ align = 'center',
72
+ sideOffset = 4,
73
+ className,
74
+ children,
75
+ }: {
76
+ side?: 'top' | 'bottom';
77
+ align?: 'start' | 'center' | 'end';
78
+ sideOffset?: number;
79
+ className?: string;
80
+ children: ReactNode;
81
+ }) {
82
+ const { open, triggerRef, id } = useTooltip();
83
+ const panelRef = useRef<HTMLDivElement>(null);
84
+ const [coords, setCoords] = useState<{ top: number; left: number } | null>(null);
85
+
86
+ useLayoutEffect(() => {
87
+ if (!open) {
88
+ setCoords(null);
89
+ return;
90
+ }
91
+ const anchor = triggerRef.current;
92
+ const panel = panelRef.current;
93
+ if (!anchor || !panel) return;
94
+ const a = anchor.getBoundingClientRect();
95
+ const p = panel.getBoundingClientRect();
96
+ let left =
97
+ align === 'start'
98
+ ? a.left
99
+ : align === 'end'
100
+ ? a.right - p.width
101
+ : a.left + (a.width - p.width) / 2;
102
+ const top = side === 'top' ? a.top - sideOffset - p.height : a.bottom + sideOffset;
103
+ left = Math.max(8, Math.min(left, window.innerWidth - p.width - 8));
104
+ setCoords({ top, left });
105
+ }, [open, side, align, sideOffset, triggerRef]);
106
+
107
+ if (!open) return null;
108
+ return (
109
+ <div
110
+ ref={panelRef}
111
+ id={id}
112
+ role="tooltip"
113
+ className={cn(
114
+ 'pointer-events-none fixed z-50 rounded-[6px] bg-foreground px-2 py-1 text-[11.5px] text-background shadow-floating',
115
+ coords ? 'visible' : 'invisible',
116
+ className,
117
+ )}
118
+ style={{ top: coords?.top ?? 0, left: coords?.left ?? 0 }}
119
+ >
120
+ {children}
121
+ </div>
122
+ );
123
+ }