Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 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 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 | 2x 29x 29x 29x 29x 29x 29x 29x 29x 6x 5x 5x 5x 5x 1x 4x 4x 2x 5x 1x 1x 5x 6x 5x 1x 1x 29x 6x 6x 1x 1x 1x 1x 1x 1x 1x 6x 6x 6x 29x 13x 8x 8x 8x 5x 9x 9x 6x 5x 5x 5x 5x 5x 5x 9x 9x 9x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 29x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 2x 3x 29x 4x 18x 18x 27x 18x 23x 23x 27x 27x 27x 23x 10x 3x 18x 18x 6x 1x 1x 5x 5x 4x 4x 4x 18x 18x 18x 36x 23x 23x 23x 6x 13x 13x 13x 13x 4x 2x 10x | import { useState, useEffect, useRef } from "react";
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { Button } from "@/components/ui/button";
import { BookOpen, ChevronRight } from "lucide-react";
import { useToast } from "@/hooks/use-toast";
interface Example {
id: string;
title: string;
category: string;
source: "builtin" | "external";
files: Array<{ name: string; path: string }>;
}
interface ExampleDetail {
files: Array<{ name: string; content: string }>;
}
interface ExamplesMenuProps {
readonly onLoadExample: (files: Array<{ name: string; content: string }>, title: string) => void;
readonly backendReachable?: boolean;
}
const KEEP_EXAMPLES_MENU_OPEN_KEY = "unoKeepExamplesMenuOpen";
export function ExamplesMenu({
onLoadExample,
backendReachable = true,
}: ExamplesMenuProps) {
const [examples, setExamples] = useState<Example[]>([]);
const [isLoading, setIsLoading] = useState(true);
const [loadingExampleId, setLoadingExampleId] = useState<string | null>(null);
const [open, setOpen] = useState(false);
const [keyboardNavActive, setKeyboardNavActive] = useState(false);
const focusedIndexRef = useRef<number>(-1);
const { toast } = useToast();
useEffect(() => {
const loadExamples = async () => {
try {
setIsLoading(true);
// Fetch the list of examples from the server
const response = await fetch("/api/examples");
if (!response.ok) {
throw new Error("Failed to fetch examples list");
}
const payload = (await response.json()) as {
examples?: Example[];
};
const loadedExamples = (payload.examples ?? []).toSorted((a, b) =>
`${a.source}/${a.category}/${a.title}`.localeCompare(
`${b.source}/${b.category}/${b.title}`,
),
);
setExamples(loadedExamples);
} catch (error) {
console.error("Failed to load examples:", error);
toast({
title: "Failed to Load Examples",
description: "Could not load example files",
variant: "destructive",
});
} finally {
setIsLoading(false);
}
};
// Only load if backend is reachable
if (backendReachable) {
loadExamples();
} else {
// Clear examples if backend is unreachable
setExamples([]);
setIsLoading(false);
}
}, [backendReachable, toast]);
// Global shortcut Meta+E to toggle examples menu
useEffect(() => {
const isMac = /Mac|Macintosh/.test(navigator.userAgent);
const onKey = (e: KeyboardEvent) => {
const isExamplesKey =
(isMac ? e.metaKey : e.ctrlKey) && !e.shiftKey && e.code === "KeyE";
Eif (isExamplesKey) {
// Prevent other handlers (Monaco, browser) from acting on this shortcut
e.preventDefault();
e.stopPropagation();
try {
e.stopImmediatePropagation();
} catch {}
setOpen((v) => !v);
}
};
document.addEventListener("keydown", onKey, { capture: true });
return () =>
document.removeEventListener("keydown", onKey, { capture: true });
}, []);
// Keyboard navigation when menu open: arrow keys + enter
useEffect(() => {
if (!open) {
focusedIndexRef.current = -1;
setKeyboardNavActive(false);
return;
}
const getVisibleItems = () => {
const all = Array.from<HTMLElement>(
document.querySelectorAll<HTMLElement>(
'[data-role="example-source"], [data-role="example-folder"], [data-role="example-item"]',
),
);
return all.filter(
(el) =>
!!(el.offsetWidth || el.offsetHeight || el.getClientRects().length),
);
};
const clearHighlight = () => {
// Clear from all items including those not currently visible
const allItems = document.querySelectorAll<HTMLElement>(
'[data-role="example-source"], [data-role="example-folder"], [data-role="example-item"]',
);
allItems.forEach((it) => {
it.classList.remove(
"bg-accent",
"text-accent-foreground",
"rounded-sm",
);
it.dataset.keyboardFocused = "false";
});
};
const highlightItem = (items: HTMLElement[], idx: number) => {
clearHighlight();
setKeyboardNavActive(true);
if (items[idx]) {
items[idx].classList.add(
"bg-accent",
"text-accent-foreground",
"rounded-sm",
);
items[idx].dataset.keyboardFocused = "true";
items[idx].focus();
}
};
// Handle mouse movement - clear keyboard highlight and re-enable hover
const onMouseMove = (e: MouseEvent) => {
const target = (e.target as HTMLElement).closest<HTMLElement>(
'[data-role="example-source"], [data-role="example-folder"], [data-role="example-item"]',
);
if (target?.dataset.keyboardFocused === "true") {
clearHighlight();
focusedIndexRef.current = -1;
}
// Re-enable hover effects when mouse moves
setKeyboardNavActive(false);
};
// Auto-focus the first visible item when menu opens — defer until the
// DropdownMenuContent has mounted and laid out (RAF).
const focusFirstVisible = () => {
const visible = getVisibleItems();
Iif (visible.length > 0) {
focusedIndexRef.current = 0;
highlightItem(visible, 0);
return true;
}
return false;
};
// Try twice with RAF to allow Radix to mount content into the portal.
requestAnimationFrame(() => {
Eif (!focusFirstVisible()) {
requestAnimationFrame(() => focusFirstVisible());
}
});
const onKey = (e: KeyboardEvent) => {
const items = getVisibleItems();
if (items.length === 0) return;
if (e.key === "ArrowDown") {
e.preventDefault();
e.stopPropagation();
const i = focusedIndexRef.current;
const next = i + 1 >= items.length ? 0 : i + 1;
focusedIndexRef.current = next;
highlightItem(items, next);
} else if (e.key === "ArrowUp") {
e.preventDefault();
e.stopPropagation();
const i = focusedIndexRef.current;
const next = i - 1 < 0 ? items.length - 1 : i - 1;
focusedIndexRef.current = next;
highlightItem(items, next);
} else if (e.key === "Enter") {
e.preventDefault();
e.stopPropagation();
const idx = Math.max(0, focusedIndexRef.current);
items[idx]?.click();
} else if (e.key === "Escape") {
setOpen(false);
}
};
// Add mouse move listener
globalThis.addEventListener("mousemove", onMouseMove);
globalThis.addEventListener("keydown", onKey, { capture: true });
return () => {
globalThis.removeEventListener("mousemove", onMouseMove);
globalThis.removeEventListener("keydown", onKey, { capture: true });
clearHighlight();
};
}, [open]);
const handleLoadExample = async (example: Example) => {
Iif (loadingExampleId) return;
setLoadingExampleId(example.id);
try {
const response = await fetch(`/api/examples/${encodeURIComponent(example.id)}`);
Iif (!response.ok) throw new Error("Failed to fetch example");
const detail = (await response.json()) as ExampleDetail;
Iif (!Array.isArray(detail.files) || detail.files.length === 0) {
throw new Error("Example contains no files");
}
onLoadExample(detail.files, example.title);
toast({
title: "Example Loaded",
description: `${example.title} has been loaded into the editor`,
});
// Close menu after loading example unless "keep open" setting is enabled
try {
if (globalThis.localStorage.getItem(KEEP_EXAMPLES_MENU_OPEN_KEY) !== "1") {
setOpen(false);
}
} catch {
setOpen(false);
}
} catch (error) {
console.error(`Failed to load example ${example.id}:`, error);
toast({
title: "Failed to Load Example",
description: "Could not load the selected example",
variant: "destructive",
});
} finally {
setLoadingExampleId(null);
}
};
return (
<DropdownMenu open={open} onOpenChange={(v) => setOpen(!!v)}>
<DropdownMenuTrigger asChild>
<Button
variant="outline"
size="sm"
className="h-[var(--ui-button-height)] w-[var(--ui-button-height)] p-0 flex items-center justify-center"
disabled={isLoading}
aria-label="Examples"
title="Examples (Cmd/Ctrl+E)"
>
<BookOpen className="h-4 w-4" />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent
align="end"
className="w-56 max-h-96 overflow-y-scroll scrollbar-hide p-0"
data-keyboard-nav={keyboardNavActive}
>
<div className="px-2 py-1.5">
<div className="text-ui-xs font-semibold mb-1">Load Example</div>
</div>
<div className="border-t" />
{examples.length === 0 && !isLoading && (
<div className="px-2 py-1.5 text-ui-xs text-muted-foreground">
No examples available
</div>
)}
{isLoading && (
<div className="px-2 py-1.5 text-ui-xs text-muted-foreground">
Loading examples...
</div>
)}
{!isLoading && examples.length > 0 && (
<ExamplesTree examples={examples} onLoadExample={handleLoadExample} />
)}
</DropdownMenuContent>
</DropdownMenu>
);
}
interface ExamplesTreeProps {
readonly examples: Example[];
readonly onLoadExample: (example: Example) => void;
}
type ExampleSource = Example["source"];
function groupExamplesBySource(items: Example[]): Record<ExampleSource, Example[]> {
const grouped: Record<ExampleSource, Example[]> = {
builtin: [],
external: [],
};
items.forEach((item) => {
grouped[item.source].push(item);
});
return grouped;
}
function groupExamplesByCategory(items: Example[]): Record<string, Example[]> {
const grouped: Record<string, Example[]> = {};
items.forEach((item) => {
const category = item.category || "Other";
if (!grouped[category]) grouped[category] = [];
grouped[category].push(item);
});
return grouped;
}
interface ExampleItemProps {
readonly example: Example;
readonly onLoadExample: (example: Example) => void;
}
function ExampleItem({ example, onLoadExample }: ExampleItemProps) {
return (
<Button
variant="ghost"
size="sm"
onClick={() => onLoadExample(example)}
data-role="example-item"
tabIndex={0}
className="w-full px-8 py-1 text-ui-xs text-left flex items-center justify-start gap-2 focus:outline-none focus:ring-0 focus-visible:outline-none focus-visible:ring-0 [*[data-keyboard-nav='true']_&]:hover:bg-transparent [*[data-keyboard-nav='true']_&]:hover:text-current"
>
<span className="text-muted-foreground">•</span>
<span className="text-ui-xs leading-tight w-full">{example.title}</span>
</Button>
);
}
function ExamplesTree({ examples, onLoadExample }: ExamplesTreeProps) {
const [expandedSource, setExpandedSource] = useState<ExampleSource | null>(null);
const [expandedCategory, setExpandedCategory] = useState<string | null>(null);
function toggleSource(source: ExampleSource) {
if (expandedSource === source) {
setExpandedSource(null);
setExpandedCategory(null);
} else {
setExpandedSource(source);
setExpandedCategory(null);
}
}
function toggleCategory(source: ExampleSource, category: string) {
const categoryKey = `${source}:${category}`;
setExpandedCategory((current) =>
current === categoryKey ? null : categoryKey,
);
}
const sourceLabels: Record<ExampleSource, string> = {
builtin: "Built-in",
external: "External",
};
const groupedBySource = groupExamplesBySource(examples);
return (
<div className="py-1">
{(["builtin", "external"] as const)
.filter((source) => groupedBySource[source].length > 0)
.map((source) => {
const isSourceExpanded = expandedSource === source;
const groupedByCategory = groupExamplesByCategory(groupedBySource[source]);
return (
<div key={source}>
<Button
variant="ghost"
size="sm"
onClick={() => toggleSource(source)}
data-role="example-source"
data-source={source}
tabIndex={0}
className="w-full px-2 py-1.5 text-ui-xs text-left flex items-center justify-start gap-1 focus:outline-none focus:ring-0 focus-visible:outline-none focus-visible:ring-0 [*[data-keyboard-nav='true']_&]:hover:bg-transparent [*[data-keyboard-nav='true']_&]:hover:text-current"
>
<ChevronRight
className={`h-4 w-4 transition-transform ${isSourceExpanded ? "rotate-90" : ""}`}
/>
<span className="font-medium text-ui-xs leading-tight w-full">
{sourceLabels[source]}
</span>
</Button>
{isSourceExpanded && (
<div className="bg-muted/10">
{Object.entries(groupedByCategory)
.toSorted(([a], [b]) => a.localeCompare(b))
.map(([category, items]) => {
const categoryKey = `${source}:${category}`;
const isCategoryExpanded = expandedCategory === categoryKey;
const cleanCategoryName = category.replace(/^\d+-/, "");
return (
<div key={categoryKey}>
<Button
variant="ghost"
size="sm"
onClick={() => toggleCategory(source, category)}
data-role="example-folder"
data-folder={categoryKey}
tabIndex={0}
className="w-full px-4 py-1.5 text-ui-xs text-left flex items-center justify-start gap-1 focus:outline-none focus:ring-0 focus-visible:outline-none focus-visible:ring-0 [*[data-keyboard-nav='true']_&]:hover:bg-transparent [*[data-keyboard-nav='true']_&]:hover:text-current"
>
<ChevronRight
className={`h-4 w-4 transition-transform ${isCategoryExpanded ? "rotate-90" : ""}`}
/>
<span className="font-normal text-ui-xs leading-tight w-full">
{cleanCategoryName}
</span>
</Button>
{isCategoryExpanded && (
<div className="bg-muted/30">
{items
.toSorted((a, b) => a.title.localeCompare(b.title))
.map((example) => (
<ExampleItem
key={example.id}
example={example}
onLoadExample={onLoadExample}
/>
))}
</div>
)}
</div>
);
})}
</div>
)}
</div>
);
})}
</div>
);
}
|