@cosxai/ui 1.0.0-alpha.1 → 1.0.0-alpha.10
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.
- package/CHANGELOG.md +89 -0
- package/package.json +10 -4
- package/src/brand.css +1 -1
- package/src/components/ActionBar.tsx +607 -0
- package/src/components/ActivityTimeline.tsx +77 -0
- package/src/components/AsyncSelect.tsx +205 -0
- package/src/components/AuthLayout.tsx +127 -0
- package/src/components/BrandLoader.tsx +122 -0
- package/src/components/Breadcrumb.tsx +129 -0
- package/src/components/Button.tsx +48 -40
- package/src/components/ChoiceCards.tsx +68 -0
- package/src/components/CodeInput.tsx +150 -0
- package/src/components/CommandPalette.tsx +228 -0
- package/src/components/ConfirmDialog.tsx +294 -0
- package/src/components/CopyField.tsx +104 -0
- package/src/components/DateInput.tsx +366 -0
- package/src/components/Dialog.tsx +27 -3
- package/src/components/Dropzone.tsx +187 -0
- package/src/components/FileCard.tsx +233 -0
- package/src/components/FileRow.tsx +159 -0
- package/src/components/FolderTree.tsx +377 -0
- package/src/components/ListToolbar.tsx +177 -0
- package/src/components/MentionInput.tsx +233 -0
- package/src/components/Menu.tsx +109 -0
- package/src/components/PageHeader.tsx +62 -0
- package/src/components/PageState.tsx +84 -0
- package/src/components/Progress.tsx +97 -0
- package/src/components/PulseDot.tsx +31 -0
- package/src/components/RecipientsInput.tsx +252 -0
- package/src/components/SearchField.tsx +137 -0
- package/src/components/SegmentedControl.tsx +95 -0
- package/src/components/SidePanel.tsx +130 -0
- package/src/components/Skeleton.tsx +73 -0
- package/src/components/StageProgress.tsx +51 -0
- package/src/components/Steps.tsx +58 -0
- package/src/components/SyncStatus.tsx +56 -0
- package/src/components/ThemeSwitch.tsx +99 -0
- package/src/components/Toast.tsx +45 -8
- package/src/components/UploadCheck.tsx +118 -0
- package/src/components/UploadList.tsx +176 -0
- package/src/components/VirtualList.tsx +90 -0
- package/src/components/WindowDrop.tsx +131 -0
- package/src/components/WorkspaceRow.tsx +80 -0
- package/src/components/inputs-aria.ts +5 -0
- package/src/components/inputs-date.ts +92 -0
- package/src/components/inputs-listbox.tsx +154 -0
- package/src/components/inputs-search.ts +60 -0
- package/src/components/status-files.ts +124 -0
- package/src/components/status-motion.ts +30 -0
- package/src/components/useSelection.ts +142 -0
- package/src/index.ts +45 -1
- package/src/theme-base.css +123 -0
- package/src/theme-reset.css +14 -0
- package/src/theme.css +2 -125
- package/src/components/core.test.tsx +0 -242
- package/src/components/forms.test.tsx +0 -280
- package/src/components/overlays.test.tsx +0 -245
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { Slot } from '@radix-ui/react-slot';
|
|
2
2
|
import { cva } from 'class-variance-authority';
|
|
3
3
|
import { Check } from 'lucide-react';
|
|
4
|
-
import {
|
|
4
|
+
import type { ComponentProps, ReactNode } from 'react';
|
|
5
5
|
|
|
6
6
|
import { cn } from '../lib/cn';
|
|
7
7
|
import { Spinner } from './Spinner';
|
|
@@ -17,7 +17,9 @@ const button = cva(
|
|
|
17
17
|
'rounded-md border border-transparent font-sans font-semibold leading-none',
|
|
18
18
|
'transition-[background-color,border-color,color] duration-[120ms] ease-standard',
|
|
19
19
|
'cursor-pointer outline-none focus-visible:shadow-(--focus-ring)',
|
|
20
|
-
|
|
20
|
+
// Disabled sinks: the well with grey text (3.0 readme and design.cosx.co;
|
|
21
|
+
// the 3.0 Button source used opacity). "!" so hover never lifts it back.
|
|
22
|
+
'disabled:cursor-not-allowed aria-disabled:cursor-not-allowed',
|
|
21
23
|
],
|
|
22
24
|
{
|
|
23
25
|
variants: {
|
|
@@ -45,6 +47,17 @@ const button = cva(
|
|
|
45
47
|
// Focus ring follows the ground.
|
|
46
48
|
{ ground: 'yellow', class: 'focus-visible:shadow-[0_0_0_3px_var(--yellow),0_0_0_5px_var(--ink)]' },
|
|
47
49
|
{ ground: 'ink', class: 'focus-visible:shadow-[0_0_0_3px_var(--ink),0_0_0_5px_var(--yellow)]' },
|
|
50
|
+
// Disabled: filled types sink into the well; outlined and text-only turn grey.
|
|
51
|
+
{
|
|
52
|
+
variant: ['primary', 'yellow', 'ink', 'danger'],
|
|
53
|
+
class:
|
|
54
|
+
'disabled:border-transparent! disabled:bg-well! disabled:text-fg-secondary! aria-disabled:border-transparent! aria-disabled:bg-well! aria-disabled:text-fg-secondary!',
|
|
55
|
+
},
|
|
56
|
+
{
|
|
57
|
+
variant: ['secondary', 'ghost'],
|
|
58
|
+
class:
|
|
59
|
+
'disabled:bg-transparent! disabled:text-fg-secondary! aria-disabled:bg-transparent! aria-disabled:text-fg-secondary! disabled:hover:border-[rgba(17,17,17,.18)] aria-disabled:hover:border-[rgba(17,17,17,.18)]',
|
|
60
|
+
},
|
|
48
61
|
],
|
|
49
62
|
defaultVariants: { size: 'md', variant: 'primary', ground: 'auto' },
|
|
50
63
|
},
|
|
@@ -63,7 +76,7 @@ export type ButtonProps = Omit<ComponentProps<'button'>, 'disabled'> & {
|
|
|
63
76
|
shortcut?: string | undefined;
|
|
64
77
|
/** A count at the end (Comments 12). Hidden at zero, 99+ above 99. */
|
|
65
78
|
count?: number | undefined;
|
|
66
|
-
/** Async state: busy
|
|
79
|
+
/** Async state: busy shows a spinner, done confirms in place; the width never changes. See useButtonAction. */
|
|
67
80
|
state?: ButtonState | undefined;
|
|
68
81
|
/** Label shown while state="done". @default the children */
|
|
69
82
|
doneLabel?: ReactNode;
|
|
@@ -106,15 +119,6 @@ export function Button({
|
|
|
106
119
|
ref,
|
|
107
120
|
...rest
|
|
108
121
|
}: ButtonProps) {
|
|
109
|
-
const inner = useRef<HTMLButtonElement | null>(null);
|
|
110
|
-
const [lockedWidth, setLockedWidth] = useState<number | null>(null);
|
|
111
|
-
|
|
112
|
-
// Lock the idle width so busy / done never resize the button.
|
|
113
|
-
useLayoutEffect(() => {
|
|
114
|
-
if (state === 'idle') setLockedWidth(null);
|
|
115
|
-
else if (lockedWidth === null && inner.current) setLockedWidth(inner.current.getBoundingClientRect().width);
|
|
116
|
-
}, [state, lockedWidth]);
|
|
117
|
-
|
|
118
122
|
const classes = cn(button({ variant, size, ground: ground ?? 'auto' }), className);
|
|
119
123
|
if (asChild) {
|
|
120
124
|
return (
|
|
@@ -125,23 +129,22 @@ export function Button({
|
|
|
125
129
|
}
|
|
126
130
|
|
|
127
131
|
const busy = state === 'busy';
|
|
132
|
+
// Busy and done keep the idle content in place (hidden) and draw on top of
|
|
133
|
+
// it, so the button never resizes — also when it first renders busy.
|
|
134
|
+
const overlaid = state !== 'idle';
|
|
128
135
|
const blocked = Boolean(disabledReason) && disabled;
|
|
129
136
|
const shownCount = count === undefined ? null : formatCount(count);
|
|
130
|
-
const setRefs = (el: HTMLButtonElement | null) => {
|
|
131
|
-
inner.current = el;
|
|
132
|
-
if (typeof ref === 'function') ref(el);
|
|
133
|
-
else if (ref) ref.current = el;
|
|
134
|
-
};
|
|
135
|
-
|
|
136
137
|
return (
|
|
137
138
|
<button
|
|
138
139
|
type="button"
|
|
139
140
|
{...rest}
|
|
140
|
-
ref={
|
|
141
|
+
ref={ref}
|
|
141
142
|
className={classes}
|
|
142
|
-
style={
|
|
143
|
+
style={style}
|
|
143
144
|
disabled={disabled && !disabledReason ? true : undefined}
|
|
144
|
-
|
|
145
|
+
// Busy is not disabled (spec: "busy and disabled are different states"):
|
|
146
|
+
// it keeps its look; aria-busy says so and repeat clicks are ignored below.
|
|
147
|
+
aria-disabled={blocked ? true : undefined}
|
|
145
148
|
aria-busy={busy || undefined}
|
|
146
149
|
title={blocked ? disabledReason : rest.title}
|
|
147
150
|
onClick={(e) => {
|
|
@@ -152,27 +155,32 @@ export function Button({
|
|
|
152
155
|
onClick?.(e);
|
|
153
156
|
}}
|
|
154
157
|
>
|
|
155
|
-
{
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
{
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
158
|
+
<span className={cn('contents', overlaid && 'invisible')} aria-hidden={overlaid || undefined} data-button-content="">
|
|
159
|
+
{iconLeft}
|
|
160
|
+
{children}
|
|
161
|
+
{iconRight}
|
|
162
|
+
{shownCount && <span className="font-medium tabular-nums opacity-70">{shownCount}</span>}
|
|
163
|
+
{shortcut && (
|
|
164
|
+
<kbd className="ml-0.5 font-sans text-[12px] font-medium opacity-60" aria-hidden>
|
|
165
|
+
{shortcut}
|
|
166
|
+
</kbd>
|
|
167
|
+
)}
|
|
168
|
+
</span>
|
|
169
|
+
{overlaid && (
|
|
170
|
+
<span className="absolute inset-0 flex items-center justify-center gap-2" data-button-overlay="">
|
|
171
|
+
{busy ? (
|
|
172
|
+
<>
|
|
173
|
+
<Spinner />
|
|
174
|
+
<span className="sr-only">{children}</span>
|
|
175
|
+
</>
|
|
176
|
+
) : (
|
|
177
|
+
<>
|
|
178
|
+
<Check size={14} strokeWidth={2} aria-hidden />
|
|
179
|
+
{doneLabel ?? children}
|
|
180
|
+
</>
|
|
172
181
|
)}
|
|
173
|
-
|
|
182
|
+
</span>
|
|
174
183
|
)}
|
|
175
|
-
{busy && <span className="sr-only">{children}</span>}
|
|
176
184
|
</button>
|
|
177
185
|
);
|
|
178
186
|
}
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
import * as RadioPrimitive from '@radix-ui/react-radio-group';
|
|
2
|
+
import { useState, type ReactNode } from 'react';
|
|
3
|
+
|
|
4
|
+
import { cn } from '../lib/cn';
|
|
5
|
+
import { definedAria } from './inputs-aria';
|
|
6
|
+
|
|
7
|
+
export type Choice = {
|
|
8
|
+
value: string;
|
|
9
|
+
title: ReactNode;
|
|
10
|
+
description?: ReactNode;
|
|
11
|
+
/** A glyph at the start (an Icon). */
|
|
12
|
+
icon?: ReactNode;
|
|
13
|
+
disabled?: boolean | undefined;
|
|
14
|
+
};
|
|
15
|
+
|
|
16
|
+
export type ChoiceCardsProps = {
|
|
17
|
+
choices: Choice[];
|
|
18
|
+
value?: string | undefined;
|
|
19
|
+
defaultValue?: string | undefined;
|
|
20
|
+
onChange?: ((value: string) => void) | undefined;
|
|
21
|
+
/** Cards per row on wide screens; they stack on phones. @default 2 */
|
|
22
|
+
columns?: 2 | 3 | undefined;
|
|
23
|
+
'aria-label'?: string | undefined;
|
|
24
|
+
'aria-labelledby'?: string | undefined;
|
|
25
|
+
className?: string | undefined;
|
|
26
|
+
};
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* ChoiceCards — a few weighty options, each a card with a title and a
|
|
30
|
+
* sentence (Add a person · Add an organisation). Radio semantics; the
|
|
31
|
+
* chosen card sits on the brand colour with an ink edge.
|
|
32
|
+
*/
|
|
33
|
+
export function ChoiceCards({ choices, value, defaultValue, onChange, columns = 2, className, ...aria }: ChoiceCardsProps) {
|
|
34
|
+
const [own, setOwn] = useState(defaultValue);
|
|
35
|
+
const current = value ?? own;
|
|
36
|
+
return (
|
|
37
|
+
<RadioPrimitive.Root
|
|
38
|
+
value={current ?? ''}
|
|
39
|
+
onValueChange={(v) => {
|
|
40
|
+
if (value === undefined) setOwn(v);
|
|
41
|
+
onChange?.(v);
|
|
42
|
+
}}
|
|
43
|
+
loop
|
|
44
|
+
{...definedAria(aria)}
|
|
45
|
+
className={cn('grid grid-cols-1 gap-3', columns === 3 ? 'sm:grid-cols-3' : 'sm:grid-cols-2', className)}
|
|
46
|
+
>
|
|
47
|
+
{choices.map((c) => (
|
|
48
|
+
<RadioPrimitive.Item
|
|
49
|
+
key={c.value}
|
|
50
|
+
value={c.value}
|
|
51
|
+
disabled={c.disabled}
|
|
52
|
+
className={cn(
|
|
53
|
+
'group flex cursor-pointer items-start gap-3 rounded-lg border border-rule bg-page p-4 text-left font-sans text-fg outline-none',
|
|
54
|
+
'transition-[background-color,border-color] duration-[120ms] ease-standard hover:border-fg focus-visible:shadow-(--focus-ring)',
|
|
55
|
+
'data-[state=checked]:border-fg data-[state=checked]:bg-hover',
|
|
56
|
+
'disabled:cursor-not-allowed disabled:opacity-40 disabled:hover:border-rule',
|
|
57
|
+
)}
|
|
58
|
+
>
|
|
59
|
+
{c.icon && <span className="mt-0.5 flex shrink-0">{c.icon}</span>}
|
|
60
|
+
<span className="flex min-w-0 flex-1 flex-col gap-1">
|
|
61
|
+
<span className="text-ui font-medium">{c.title}</span>
|
|
62
|
+
{c.description && <span className="text-meta leading-normal text-fg-secondary">{c.description}</span>}
|
|
63
|
+
</span>
|
|
64
|
+
</RadioPrimitive.Item>
|
|
65
|
+
))}
|
|
66
|
+
</RadioPrimitive.Root>
|
|
67
|
+
);
|
|
68
|
+
}
|
|
@@ -0,0 +1,150 @@
|
|
|
1
|
+
import { useEffect, useRef, useState, type ReactNode } from 'react';
|
|
2
|
+
|
|
3
|
+
import { cn } from '../lib/cn';
|
|
4
|
+
import { useField } from './Field';
|
|
5
|
+
|
|
6
|
+
export type CodeInputProps = {
|
|
7
|
+
/** Number of cells. @default 6 */
|
|
8
|
+
length?: number | undefined;
|
|
9
|
+
value?: string | undefined;
|
|
10
|
+
onChange?: ((code: string) => void) | undefined;
|
|
11
|
+
/** Called once every cell is filled — typing the last digit or pasting the whole code. */
|
|
12
|
+
onComplete?: ((code: string) => void) | undefined;
|
|
13
|
+
/** Digits only (default) or letters and digits. */
|
|
14
|
+
mode?: 'numeric' | 'alphanumeric' | undefined;
|
|
15
|
+
invalid?: boolean | undefined;
|
|
16
|
+
disabled?: boolean | undefined;
|
|
17
|
+
/** Seconds until the code can be sent again; the countdown runs here. */
|
|
18
|
+
resendIn?: number | undefined;
|
|
19
|
+
onResend?: (() => void) | undefined;
|
|
20
|
+
/** @default (s) => `Resend in ${s} s` */
|
|
21
|
+
formatCountdown?: ((seconds: number) => ReactNode) | undefined;
|
|
22
|
+
/** @default "Send a new code" */
|
|
23
|
+
resendLabel?: string | undefined;
|
|
24
|
+
/** Name of the group for screen readers when there is no Field label. @default "Verification code" */
|
|
25
|
+
'aria-label'?: string | undefined;
|
|
26
|
+
className?: string | undefined;
|
|
27
|
+
};
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* CodeInput — one cell per character of a one-time code. Typing moves on,
|
|
31
|
+
* Backspace moves back, arrows move; pasting the whole code fills every
|
|
32
|
+
* cell and completes. The first cell carries autocomplete=one-time-code
|
|
33
|
+
* so phones offer the code from the message.
|
|
34
|
+
*/
|
|
35
|
+
export function CodeInput({
|
|
36
|
+
length = 6,
|
|
37
|
+
value,
|
|
38
|
+
onChange,
|
|
39
|
+
onComplete,
|
|
40
|
+
mode = 'numeric',
|
|
41
|
+
invalid,
|
|
42
|
+
disabled,
|
|
43
|
+
resendIn,
|
|
44
|
+
onResend,
|
|
45
|
+
formatCountdown = (s) => `Resend in ${s} s`,
|
|
46
|
+
resendLabel = 'Send a new code',
|
|
47
|
+
'aria-label': ariaLabel = 'Verification code',
|
|
48
|
+
className,
|
|
49
|
+
}: CodeInputProps) {
|
|
50
|
+
const field = useField();
|
|
51
|
+
const [own, setOwn] = useState('');
|
|
52
|
+
const code = (value ?? own).slice(0, length);
|
|
53
|
+
const cells = useRef<Array<HTMLInputElement | null>>([]);
|
|
54
|
+
const allowed = mode === 'numeric' ? /\d/ : /[a-z0-9]/i;
|
|
55
|
+
const bad = Boolean(invalid || field?.invalid);
|
|
56
|
+
const off = Boolean(disabled || field?.disabled);
|
|
57
|
+
|
|
58
|
+
const [left, setLeft] = useState(resendIn ?? 0);
|
|
59
|
+
useEffect(() => setLeft(resendIn ?? 0), [resendIn]);
|
|
60
|
+
useEffect(() => {
|
|
61
|
+
if (left <= 0) return;
|
|
62
|
+
const t = setTimeout(() => setLeft((s) => s - 1), 1000);
|
|
63
|
+
return () => clearTimeout(t);
|
|
64
|
+
}, [left]);
|
|
65
|
+
|
|
66
|
+
const set = (next: string) => {
|
|
67
|
+
const clean = next.slice(0, length);
|
|
68
|
+
if (value === undefined) setOwn(clean);
|
|
69
|
+
onChange?.(clean);
|
|
70
|
+
if (clean.length === length && !clean.includes(' ')) onComplete?.(clean);
|
|
71
|
+
};
|
|
72
|
+
const focus = (i: number) => cells.current[Math.max(0, Math.min(length - 1, i))]?.focus();
|
|
73
|
+
const chars = Array.from({ length }, (_, i) => code[i] ?? '');
|
|
74
|
+
|
|
75
|
+
const put = (i: number, raw: string) => {
|
|
76
|
+
const typed = [...raw].filter((c) => allowed.test(c)).map((c) => c.toUpperCase());
|
|
77
|
+
if (!typed.length) return;
|
|
78
|
+
const next = [...chars];
|
|
79
|
+
typed.forEach((c, k) => {
|
|
80
|
+
if (i + k < length) next[i + k] = c;
|
|
81
|
+
});
|
|
82
|
+
// Empty cells are a space inside; the value has no trailing spaces.
|
|
83
|
+
set(next.map((c) => c || ' ').join('').trimEnd());
|
|
84
|
+
focus(i + typed.length);
|
|
85
|
+
};
|
|
86
|
+
|
|
87
|
+
return (
|
|
88
|
+
<div className={cn('flex flex-col gap-2 font-sans', className)}>
|
|
89
|
+
<div role="group" aria-label={field?.labelId ? undefined : ariaLabel} aria-labelledby={field?.labelId} className="flex gap-2">
|
|
90
|
+
{chars.map((c, i) => (
|
|
91
|
+
<input
|
|
92
|
+
key={i}
|
|
93
|
+
ref={(el) => {
|
|
94
|
+
cells.current[i] = el;
|
|
95
|
+
}}
|
|
96
|
+
id={i === 0 ? field?.id : undefined}
|
|
97
|
+
value={c.trim()}
|
|
98
|
+
inputMode={mode === 'numeric' ? 'numeric' : 'text'}
|
|
99
|
+
autoComplete={i === 0 ? 'one-time-code' : 'off'}
|
|
100
|
+
maxLength={length}
|
|
101
|
+
disabled={off}
|
|
102
|
+
aria-label={`${i + 1} of ${length}`}
|
|
103
|
+
aria-invalid={bad || undefined}
|
|
104
|
+
aria-describedby={field?.describedBy}
|
|
105
|
+
onFocus={(e) => e.currentTarget.select()}
|
|
106
|
+
onChange={(e) => put(i, e.target.value)}
|
|
107
|
+
onPaste={(e) => {
|
|
108
|
+
e.preventDefault();
|
|
109
|
+
put(0, e.clipboardData.getData('text'));
|
|
110
|
+
}}
|
|
111
|
+
onKeyDown={(e) => {
|
|
112
|
+
if (e.key === 'Backspace') {
|
|
113
|
+
e.preventDefault();
|
|
114
|
+
const next = [...chars];
|
|
115
|
+
const at = c.trim() ? i : i - 1;
|
|
116
|
+
if (at < 0) return;
|
|
117
|
+
next[at] = ' ';
|
|
118
|
+
set(next.map((ch) => ch || ' ').join('').trimEnd());
|
|
119
|
+
focus(at);
|
|
120
|
+
} else if (e.key === 'ArrowLeft') {
|
|
121
|
+
e.preventDefault();
|
|
122
|
+
focus(i - 1);
|
|
123
|
+
} else if (e.key === 'ArrowRight') {
|
|
124
|
+
e.preventDefault();
|
|
125
|
+
focus(i + 1);
|
|
126
|
+
}
|
|
127
|
+
}}
|
|
128
|
+
className={cn(
|
|
129
|
+
'h-[52px] w-11 rounded-md border bg-sunk text-center font-sans text-[20px] font-medium text-fg tabular-nums outline-none',
|
|
130
|
+
'transition-[border-color] duration-[120ms] ease-standard focus:border-fg focus:shadow-(--focus-ring)',
|
|
131
|
+
bad ? 'border-transparent bg-error-wash focus:border-error' : 'border-transparent',
|
|
132
|
+
off && 'cursor-not-allowed bg-well text-fg-secondary',
|
|
133
|
+
)}
|
|
134
|
+
/>
|
|
135
|
+
))}
|
|
136
|
+
</div>
|
|
137
|
+
{resendIn !== undefined && (
|
|
138
|
+
<div className="text-meta text-fg-secondary" aria-live="polite">
|
|
139
|
+
{left > 0 ? (
|
|
140
|
+
formatCountdown(left)
|
|
141
|
+
) : (
|
|
142
|
+
<button type="button" onClick={onResend} className="cursor-pointer rounded-xs font-medium text-fg underline underline-offset-3 outline-none focus-visible:shadow-(--focus-ring)">
|
|
143
|
+
{resendLabel}
|
|
144
|
+
</button>
|
|
145
|
+
)}
|
|
146
|
+
</div>
|
|
147
|
+
)}
|
|
148
|
+
</div>
|
|
149
|
+
);
|
|
150
|
+
}
|
|
@@ -0,0 +1,228 @@
|
|
|
1
|
+
import * as DialogPrimitive from '@radix-ui/react-dialog';
|
|
2
|
+
import { Command } from 'cmdk';
|
|
3
|
+
import { Search } from 'lucide-react';
|
|
4
|
+
import { useEffect, useRef, useState, type ReactNode } from 'react';
|
|
5
|
+
|
|
6
|
+
import { cn } from '../lib/cn';
|
|
7
|
+
import { Spinner } from './Spinner';
|
|
8
|
+
|
|
9
|
+
export type CommandItem = {
|
|
10
|
+
id: string;
|
|
11
|
+
title: ReactNode;
|
|
12
|
+
/** Where it lives: "Series A / Legal". */
|
|
13
|
+
subtitle?: ReactNode;
|
|
14
|
+
/** Right-aligned: a page ("p. 14"), a shortcut. */
|
|
15
|
+
meta?: ReactNode;
|
|
16
|
+
/** A line of matched text (full-text results). */
|
|
17
|
+
excerpt?: ReactNode;
|
|
18
|
+
icon?: ReactNode;
|
|
19
|
+
onSelect: () => void;
|
|
20
|
+
};
|
|
21
|
+
|
|
22
|
+
export type CommandSource = {
|
|
23
|
+
id: string;
|
|
24
|
+
/** Section heading: "Documents · titles", "Full text". */
|
|
25
|
+
label: string;
|
|
26
|
+
/** Results for the query. Aborted when the query changes. Throwing marks the source failed (it stops counting as pending). */
|
|
27
|
+
search: (query: string, signal: AbortSignal) => Promise<CommandItem[]>;
|
|
28
|
+
/** Characters needed before it runs. @default 1 */
|
|
29
|
+
minQuery?: number | undefined;
|
|
30
|
+
};
|
|
31
|
+
|
|
32
|
+
export type CommandPaletteLabels = {
|
|
33
|
+
/** @default "Search or run an action" */
|
|
34
|
+
placeholder?: string;
|
|
35
|
+
/** @default (q) => `Nothing matches “${q}”.` */
|
|
36
|
+
empty?: (query: string) => ReactNode;
|
|
37
|
+
/** Heading hint while a slower source has not returned. @default "arriving" */
|
|
38
|
+
arriving?: string;
|
|
39
|
+
/** @default "Actions" */
|
|
40
|
+
actions?: string;
|
|
41
|
+
/** Accessible name of the palette. @default "Command palette" */
|
|
42
|
+
title?: string;
|
|
43
|
+
};
|
|
44
|
+
|
|
45
|
+
export type CommandPaletteProps = {
|
|
46
|
+
open: boolean;
|
|
47
|
+
onOpenChange: (open: boolean) => void;
|
|
48
|
+
/** Searched in parallel; each section appears as its source returns, in this order. */
|
|
49
|
+
sources: CommandSource[];
|
|
50
|
+
/** Actions for the query ("Ask the Agent about “cap table”"), always listed after the results. */
|
|
51
|
+
actions?: ((query: string) => CommandItem[]) | undefined;
|
|
52
|
+
labels?: CommandPaletteLabels | undefined;
|
|
53
|
+
/** ms after typing before sources run. @default 150 */
|
|
54
|
+
debounce?: number | undefined;
|
|
55
|
+
};
|
|
56
|
+
|
|
57
|
+
const GROUP = '[&_[cmdk-group-heading]]:px-3 [&_[cmdk-group-heading]]:pt-2.5 [&_[cmdk-group-heading]]:pb-1 [&_[cmdk-group-heading]]:text-meta [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-fg-secondary';
|
|
58
|
+
|
|
59
|
+
type SourceState = { status: 'pending' | 'done' | 'failed'; items: CommandItem[] };
|
|
60
|
+
|
|
61
|
+
/**
|
|
62
|
+
* CommandPalette — ⌘K. Fast sources (titles) show at once, slower ones
|
|
63
|
+
* (full text with page and excerpt) fill in below; a spinner shows while
|
|
64
|
+
* any is out, and "nothing matches" only once every source has returned.
|
|
65
|
+
* Arrows, Enter, Esc (cmdk + Radix Dialog). Pair with useCommandPaletteHotkey.
|
|
66
|
+
*/
|
|
67
|
+
export function CommandPalette({ open, onOpenChange, sources, actions, labels = {}, debounce = 150 }: CommandPaletteProps) {
|
|
68
|
+
const [query, setQuery] = useState('');
|
|
69
|
+
const [results, setResults] = useState<Record<string, SourceState>>({});
|
|
70
|
+
// The highlighted row. Follows the first result as sections arrive,
|
|
71
|
+
// until the person moves with the arrows.
|
|
72
|
+
const [selected, setSelected] = useState('');
|
|
73
|
+
const moved = useRef(false);
|
|
74
|
+
const sourcesRef = useRef(sources);
|
|
75
|
+
sourcesRef.current = sources;
|
|
76
|
+
|
|
77
|
+
useEffect(() => {
|
|
78
|
+
if (!open) {
|
|
79
|
+
setQuery('');
|
|
80
|
+
setResults({});
|
|
81
|
+
}
|
|
82
|
+
}, [open]);
|
|
83
|
+
useEffect(() => {
|
|
84
|
+
moved.current = false;
|
|
85
|
+
}, [query]);
|
|
86
|
+
|
|
87
|
+
useEffect(() => {
|
|
88
|
+
const q = query.trim();
|
|
89
|
+
const active = sourcesRef.current.filter((s) => q.length >= (s.minQuery ?? 1));
|
|
90
|
+
if (!q || active.length === 0) {
|
|
91
|
+
setResults({});
|
|
92
|
+
return;
|
|
93
|
+
}
|
|
94
|
+
setResults(Object.fromEntries(active.map((s) => [s.id, { status: 'pending', items: [] } satisfies SourceState])));
|
|
95
|
+
const controller = new AbortController();
|
|
96
|
+
const timer = setTimeout(() => {
|
|
97
|
+
for (const s of active) {
|
|
98
|
+
s.search(q, controller.signal).then(
|
|
99
|
+
(items) => !controller.signal.aborted && setResults((r) => ({ ...r, [s.id]: { status: 'done', items } })),
|
|
100
|
+
() => !controller.signal.aborted && setResults((r) => ({ ...r, [s.id]: { status: 'failed', items: [] } })),
|
|
101
|
+
);
|
|
102
|
+
}
|
|
103
|
+
}, debounce);
|
|
104
|
+
return () => {
|
|
105
|
+
clearTimeout(timer);
|
|
106
|
+
controller.abort();
|
|
107
|
+
};
|
|
108
|
+
}, [query, debounce]);
|
|
109
|
+
|
|
110
|
+
const q = query.trim();
|
|
111
|
+
const states = Object.values(results);
|
|
112
|
+
const pending = states.some((s) => s.status === 'pending');
|
|
113
|
+
const found = states.some((s) => s.items.length > 0);
|
|
114
|
+
const actionItems = q && actions ? actions(q) : [];
|
|
115
|
+
const order = [
|
|
116
|
+
...sourcesRef.current.flatMap((s) => (results[s.id]?.items ?? []).map((i) => `${s.id}:${i.id}`)),
|
|
117
|
+
...actionItems.map((i) => `action:${i.id}`),
|
|
118
|
+
];
|
|
119
|
+
const first = order[0] ?? '';
|
|
120
|
+
useEffect(() => {
|
|
121
|
+
if (!moved.current) setSelected(first);
|
|
122
|
+
}, [first]);
|
|
123
|
+
const run = (item: CommandItem) => {
|
|
124
|
+
onOpenChange(false);
|
|
125
|
+
item.onSelect();
|
|
126
|
+
};
|
|
127
|
+
|
|
128
|
+
return (
|
|
129
|
+
<DialogPrimitive.Root open={open} onOpenChange={onOpenChange}>
|
|
130
|
+
<DialogPrimitive.Portal>
|
|
131
|
+
<DialogPrimitive.Overlay className="fixed inset-0 z-50 bg-scrim" />
|
|
132
|
+
<DialogPrimitive.Content
|
|
133
|
+
aria-describedby={undefined}
|
|
134
|
+
className="fixed top-[12vh] left-1/2 z-50 w-[calc(100%-32px)] max-w-[640px] -translate-x-1/2 overflow-hidden rounded-lg border border-rule bg-page font-sans text-fg outline-none"
|
|
135
|
+
>
|
|
136
|
+
<DialogPrimitive.Title className="sr-only">{labels.title ?? 'Command palette'}</DialogPrimitive.Title>
|
|
137
|
+
<Command
|
|
138
|
+
shouldFilter={false}
|
|
139
|
+
loop
|
|
140
|
+
label={labels.title ?? 'Command palette'}
|
|
141
|
+
value={selected}
|
|
142
|
+
onValueChange={setSelected}
|
|
143
|
+
onKeyDown={(e) => {
|
|
144
|
+
if (e.key === 'ArrowDown' || e.key === 'ArrowUp' || e.key === 'Home' || e.key === 'End') moved.current = true;
|
|
145
|
+
}}
|
|
146
|
+
>
|
|
147
|
+
<div className="flex items-center gap-2.5 border-b border-rule px-4">
|
|
148
|
+
<Search size={16} aria-hidden className="shrink-0 text-fg-secondary" />
|
|
149
|
+
<Command.Input
|
|
150
|
+
value={query}
|
|
151
|
+
onValueChange={setQuery}
|
|
152
|
+
placeholder={labels.placeholder ?? 'Search or run an action'}
|
|
153
|
+
className="h-12 min-w-0 flex-1 border-0 bg-transparent font-sans text-[15px] text-fg outline-none placeholder:text-fg-secondary"
|
|
154
|
+
/>
|
|
155
|
+
{pending && <Spinner label="Searching" className="text-fg-secondary" />}
|
|
156
|
+
</div>
|
|
157
|
+
<Command.List className="max-h-[min(420px,60vh)] overflow-y-auto p-1.5">
|
|
158
|
+
{sourcesRef.current.map((s) => {
|
|
159
|
+
const st = results[s.id];
|
|
160
|
+
if (!st || (st.status !== 'pending' && st.items.length === 0)) return null;
|
|
161
|
+
return (
|
|
162
|
+
<Command.Group
|
|
163
|
+
key={s.id}
|
|
164
|
+
className={GROUP}
|
|
165
|
+
heading={
|
|
166
|
+
<span className="flex items-center gap-1.5">
|
|
167
|
+
{s.label}
|
|
168
|
+
{st.status === 'pending' && <span className="font-normal">· {labels.arriving ?? 'arriving'}</span>}
|
|
169
|
+
</span>
|
|
170
|
+
}
|
|
171
|
+
>
|
|
172
|
+
{st.items.map((item) => (
|
|
173
|
+
<PaletteItem key={`${s.id}:${item.id}`} value={`${s.id}:${item.id}`} item={item} onRun={run} />
|
|
174
|
+
))}
|
|
175
|
+
</Command.Group>
|
|
176
|
+
);
|
|
177
|
+
})}
|
|
178
|
+
{q && !pending && !found && (
|
|
179
|
+
<div role="status" className="px-3 py-3 text-ui text-fg-secondary">
|
|
180
|
+
{labels.empty ? labels.empty(q) : `Nothing matches “${q}”.`}
|
|
181
|
+
</div>
|
|
182
|
+
)}
|
|
183
|
+
{actionItems.length > 0 && (
|
|
184
|
+
<Command.Group className={GROUP} heading={labels.actions ?? 'Actions'}>
|
|
185
|
+
{actionItems.map((item) => (
|
|
186
|
+
<PaletteItem key={`action:${item.id}`} value={`action:${item.id}`} item={item} onRun={run} />
|
|
187
|
+
))}
|
|
188
|
+
</Command.Group>
|
|
189
|
+
)}
|
|
190
|
+
</Command.List>
|
|
191
|
+
</Command>
|
|
192
|
+
</DialogPrimitive.Content>
|
|
193
|
+
</DialogPrimitive.Portal>
|
|
194
|
+
</DialogPrimitive.Root>
|
|
195
|
+
);
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
function PaletteItem({ item, value, onRun }: { item: CommandItem; value: string; onRun: (item: CommandItem) => void }) {
|
|
199
|
+
return (
|
|
200
|
+
<Command.Item
|
|
201
|
+
value={value}
|
|
202
|
+
onSelect={() => onRun(item)}
|
|
203
|
+
className={cn('flex cursor-pointer items-start gap-2.5 rounded-md px-3 py-2 outline-none', 'data-[selected=true]:bg-hover')}
|
|
204
|
+
>
|
|
205
|
+
{item.icon && <span className="mt-0.5 grid size-4 shrink-0 place-items-center text-fg-secondary">{item.icon}</span>}
|
|
206
|
+
<span className="flex min-w-0 flex-1 flex-col gap-0.5">
|
|
207
|
+
<span className="truncate text-ui">{item.title}</span>
|
|
208
|
+
{item.subtitle && <span className="truncate text-meta text-fg-secondary">{item.subtitle}</span>}
|
|
209
|
+
{item.excerpt && <span className="line-clamp-2 text-small text-fg-secondary">{item.excerpt}</span>}
|
|
210
|
+
</span>
|
|
211
|
+
{item.meta && <span className="mt-0.5 shrink-0 text-meta text-fg-secondary tabular-nums">{item.meta}</span>}
|
|
212
|
+
</Command.Item>
|
|
213
|
+
);
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
/** ⌘K / Ctrl+K toggles the palette (also from inside inputs). */
|
|
217
|
+
export function useCommandPaletteHotkey(setOpen: (update: (open: boolean) => boolean) => void) {
|
|
218
|
+
useEffect(() => {
|
|
219
|
+
const onKey = (e: KeyboardEvent) => {
|
|
220
|
+
if ((e.metaKey || e.ctrlKey) && !e.altKey && !e.shiftKey && e.key.toLowerCase() === 'k') {
|
|
221
|
+
e.preventDefault();
|
|
222
|
+
setOpen((o) => !o);
|
|
223
|
+
}
|
|
224
|
+
};
|
|
225
|
+
document.addEventListener('keydown', onKey);
|
|
226
|
+
return () => document.removeEventListener('keydown', onKey);
|
|
227
|
+
}, [setOpen]);
|
|
228
|
+
}
|