forked from CopilotKit/CopilotKit
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtailored-content.tsx
More file actions
256 lines (236 loc) · 8.2 KB
/
Copy pathtailored-content.tsx
File metadata and controls
256 lines (236 loc) · 8.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
"use client";
import React, {
ReactNode,
Suspense,
useCallback,
useEffect,
useMemo,
useRef,
} from "react";
import { useRouter, useSearchParams } from "next/navigation";
// Local className-joining helper so this component has no external dep.
// Mirrors the subset of `classnames` behavior used below (strings + falsy values).
function cn(...values: Array<string | false | null | undefined>): string {
return values.filter(Boolean).join(" ");
}
type TailoredContentOptionProps = {
title: string;
description: string;
icon: ReactNode;
children: ReactNode;
id: string;
};
/**
* Declarative child marker for `TailoredContent`. This component intentionally
* renders nothing; the parent reads its props (including `children`) directly
* and renders the selected option's content itself.
*/
export function TailoredContentOption(_props: TailoredContentOptionProps) {
return null;
}
type TailoredContentProps = {
children: ReactNode;
header?: ReactNode;
className?: string;
defaultOptionIndex?: number;
id: string;
};
type IconElement = React.ReactElement<{ className?: string }>;
function TailoredContentInner({
children,
className,
defaultOptionIndex = 0,
id,
header,
}: TailoredContentProps) {
// All hooks must run unconditionally to satisfy the Rules of Hooks.
const router = useRouter();
const searchParams = useSearchParams();
const tabRefs = useRef<Array<HTMLDivElement | null>>([]);
const warnedKeyRef = useRef<string | null>(null);
// Memoize derived arrays so downstream hook deps have stable identities.
const options = useMemo(
() =>
React.Children.toArray(children).filter((child) =>
React.isValidElement(child),
) as React.ReactElement<TailoredContentOptionProps>[],
[children],
);
const optionIds = useMemo(
() => options.map((option) => option.props.id),
[options],
);
// Warn (dev-mode friendly) when duplicate option ids would cause ambiguous
// URL <-> selection mapping. Runs only when ids change; warnedKeyRef guards
// against duplicate warns for the same set (e.g. StrictMode double-invoke).
useEffect(() => {
const seen = new Set<string>();
const duplicates: string[] = [];
for (const oid of optionIds) {
if (seen.has(oid) && !duplicates.includes(oid)) {
duplicates.push(oid);
}
seen.add(oid);
}
if (duplicates.length === 0) return;
const warnKey = duplicates.join(",");
if (warnedKeyRef.current === warnKey) return;
warnedKeyRef.current = warnKey;
// eslint-disable-next-line no-console
console.warn(
`TailoredContent(id=${id}): duplicate option id(s) detected: ${duplicates
.map((d) => `"${d}"`)
.join(", ")}. Option ids must be unique.`,
);
}, [optionIds, id]);
const updateSelection = useCallback(
(index: number) => {
if (index < 0 || index >= options.length) return;
const newParams = new URLSearchParams(searchParams.toString());
newParams.set(id, optionIds[index]);
// Update URL without reload; derived selectedIndex will follow.
router.replace(`?${newParams.toString()}`, { scroll: false });
},
[router, searchParams, id, optionIds, options.length],
);
// No hooks below this point — safe to short-circuit when there are no options.
if (options.length === 0) return null;
// Clamp defaultOptionIndex to the valid range.
const clampedDefault = Math.min(
Math.max(0, defaultOptionIndex),
options.length - 1,
);
// Derive selectedIndex from the URL on every render so state stays in sync
// with navigation (back/forward, external updates to the search param).
const urlParam = searchParams.get(id);
const indexFromUrl = urlParam ? optionIds.indexOf(urlParam) : -1;
const selectedIndex = indexFromUrl >= 0 ? indexFromUrl : clampedDefault;
const focusTab = (index: number) => {
const el = tabRefs.current[index];
if (el) el.focus();
};
const onKeyDown = (e: React.KeyboardEvent<HTMLDivElement>, index: number) => {
switch (e.key) {
case "Enter":
case " ":
case "Spacebar":
e.preventDefault();
updateSelection(index);
return;
case "ArrowRight": {
e.preventDefault();
const next = (index + 1) % options.length;
updateSelection(next);
focusTab(next);
return;
}
case "ArrowLeft": {
e.preventDefault();
const prev = (index - 1 + options.length) % options.length;
updateSelection(prev);
focusTab(prev);
return;
}
case "Home": {
e.preventDefault();
updateSelection(0);
focusTab(0);
return;
}
case "End": {
e.preventDefault();
const last = options.length - 1;
updateSelection(last);
focusTab(last);
return;
}
default:
return;
}
};
const itemCn =
"border p-3 pl-4 rounded-md flex-1 flex md:block md:space-y-0.5 items-center md:items-start gap-4 cursor-pointer bg-white dark:bg-secondary relative overflow-hidden group transition-all";
const selectedCn =
"shadow-lg ring-1 ring-indigo-400 selected bg-gradient-to-r from-slate-50 to-indigo-50/30 dark:from-slate-800/40 dark:to-indigo-950/20";
const iconCn =
"w-8 h-8 mb-2 top-0 transition-all opacity-20 group-[.selected]:text-indigo-500 group-[.selected]:opacity-60 dark:group-[.selected]:text-indigo-400 dark:group-[.selected]:opacity-60 dark:text-gray-400";
const tablistId = `tailored-content-tablist-${id}`;
const tabId = (optId: string) => `tailored-content-tab-${id}-${optId}`;
const panelId = (optId: string) => `tailored-content-panel-${id}-${optId}`;
const selectedOption = options[selectedIndex];
return (
<div>
<div className={cn("tailored-content-wrapper mt-4", className)}>
{header}
<div
id={tablistId}
role="tablist"
aria-orientation="horizontal"
className="flex flex-col md:flex-row gap-3 my-2 w-full"
>
{options.map((option, index) => {
const isSelected = selectedIndex === index;
return (
<div
key={option.props.id}
ref={(el) => {
tabRefs.current[index] = el;
}}
id={tabId(option.props.id)}
className={cn(itemCn, isSelected && selectedCn)}
onClick={() => updateSelection(index)}
onKeyDown={(e) => onKeyDown(e, index)}
role="tab"
aria-selected={isSelected}
aria-controls={panelId(option.props.id)}
tabIndex={isSelected ? 0 : -1}
>
<div className="my-0">
{React.isValidElement(option.props.icon) ? (
(() => {
const icon = option.props.icon as IconElement;
return React.cloneElement(icon, {
className: cn(icon.props?.className, iconCn, "my-0"),
});
})()
) : (
<span className={cn(iconCn, "my-0")} />
)}
</div>
<div>
<p className="font-semibold text-base">{option.props.title}</p>
<p className="text-xs md:text-sm">{option.props.description}</p>
</div>
</div>
);
})}
</div>
</div>
{selectedOption && (
<div
role="tabpanel"
id={panelId(selectedOption.props.id)}
aria-labelledby={tabId(selectedOption.props.id)}
>
{selectedOption.props.children}
</div>
)}
</div>
);
}
/**
* `TailoredContent` renders a set of tab-like options and the currently
* selected option's content. The selection is persisted in the URL via
* `?<id>=<optionId>` so links are shareable.
*
* Next.js App Router requires `useSearchParams()` to be wrapped in a
* `<Suspense>` boundary. The exported component wraps the inner
* implementation so consumers don't need to do that themselves.
*/
export function TailoredContent(props: TailoredContentProps) {
return (
<Suspense fallback={null}>
<TailoredContentInner {...props} />
</Suspense>
);
}