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 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 | 46x 46x 46x 46x 46x 46x 46x 46x 46x 46x 46x 46x 46x 46x 18x 18x 18x 18x 18x 7x 7x 7x 7x 7x 7x 7x 6x 6x 16x 11x 6x 1x 1x 1x 7x 7x 7x 7x 7x 46x 8x 8x 1x 1x 1x 1x 1x 1x 1x 1x 8x 8x 8x 46x 18x 11x 11x 11x 7x 14x 14x 8x 7x 7x 7x 7x 7x 7x 14x 14x 14x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 46x 3x 3x 3x 3x 3x 3x 1x 1x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 46x 6x 17x 17x 43x 17x 22x 22x 43x 43x 43x 22x 65x 58x 58x 20x 3x 17x 17x 7x 1x 1x 6x 6x 2x 2x 2x 17x 17x 17x 34x 22x 22x 22x 7x 11x 17x 5x 5x 5x 5x 2x 3x | 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";
import {
ExternalExamplesError,
refreshExternalExamplesCatalog,
setActiveExternalExampleContext,
useExternalExamples,
} from "@/lib/external-examples";
import { getServerCapabilities, type ServerCapabilities } from "@/lib/server-capabilities";
interface Example {
id: string;
title: string;
category: string;
source: "builtin" | "external";
files: Array<{ name: string; path: string }>;
repository?: string;
ref?: string;
revision?: string;
}
interface ExampleDetail {
files: Array<{ name: string; path?: string; content: string }>;
}
interface ExamplesMenuProps {
readonly onLoadExample: (
files: Array<{ name: string; path?: string; content: string }>,
title: string,
) => void;
readonly capabilities?: ServerCapabilities;
}
export function ExamplesMenu({
onLoadExample,
capabilities = getServerCapabilities(true),
}: ExamplesMenuProps) {
const [examples, setExamples] = useState<Example[]>([]);
const [isLoading, setIsLoading] = useState(false);
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();
const { override } = useExternalExamples();
const loadGeneration = useRef(0);
const capabilitiesRef = useRef(capabilities);
const previousOpenRef = useRef(false);
const previousOverrideRef = useRef(override);
capabilitiesRef.current = capabilities;
useEffect(() => {
const opened = open && !previousOpenRef.current;
const overrideChanged = previousOverrideRef.current !== override;
previousOpenRef.current = open;
previousOverrideRef.current = override;
if (!open || (!opened && !overrideChanged)) return;
Iif (!capabilitiesRef.current.canUseServerExamples) return;
const generation = ++loadGeneration.current;
let cancelled = false;
const loadExamples = async () => {
try {
setIsLoading(true);
const payload = await refreshExternalExamplesCatalog();
Iif (
cancelled ||
generation !== loadGeneration.current ||
!capabilitiesRef.current.canUseServerExamples
) return;
const loadedExamples = payload.examples
.map((example) => ({
...example,
...(example.source === "external" &&
payload.source.mode === "repository-ref"
? {
repository: payload.source.repository!,
ref: payload.source.ref!,
revision: payload.source.revision!,
}
: {}),
}))
.toSorted((a, b) =>
`${a.source}/${a.category}/${a.title}`.localeCompare(
`${b.source}/${b.category}/${b.title}`,
),
);
setExamples(loadedExamples);
} catch (error) {
Iif (error instanceof DOMException && error.name === "AbortError")
return;
console.error("Failed to load examples:", error);
toast({
title: "Failed to Load Examples",
description:
error instanceof ExternalExamplesError
? error.message
: "Could not load example files",
variant: "destructive",
});
} finally {
Eif (!cancelled && generation === loadGeneration.current)
setIsLoading(false);
}
};
loadExamples();
return () => {
cancelled = true;
};
}, [open, override, 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 {}
Iif (!capabilitiesRef.current.canUseServerExamples) return;
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 (!capabilitiesRef.current.canUseServerExamples) return;
Iif (loadingExampleId) return;
setLoadingExampleId(example.id);
try {
let query = "";
if (example.source === "external") {
Iif (!example.repository || !example.revision) {
throw new Error("Example catalog has no revision context");
}
query = `?repository=${encodeURIComponent(example.repository)}&revision=${encodeURIComponent(example.revision)}`;
}
const response = await fetch(
`/api/examples/${encodeURIComponent(example.id)}${query}`,
);
Iif (!response.ok) throw new Error("Failed to fetch example");
const detail = (await response.json()) as ExampleDetail;
Iif (!capabilitiesRef.current.canUseServerExamples) return;
Iif (!Array.isArray(detail.files) || detail.files.length === 0) {
throw new Error("Example contains no files");
}
const displayName = getExampleDisplayName(example);
setActiveExternalExampleContext(example.source === "external" && example.repository && example.ref && example.revision
? { repository: example.repository, ref: example.ref, revision: example.revision, exampleId: example.id }
: null);
onLoadExample(detail.files, displayName);
toast({
title: "Example Loaded",
description: `${displayName} has been loaded into the editor`,
});
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="icon"
aria-label="Examples"
title={capabilities.canUseServerExamples ? "Examples (Cmd/Ctrl+E)" : "Server connection required"}
disabled={!capabilities.canUseServerExamples}
>
<BookOpen className="h-4 w-4" />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent
align="end"
className="w-72 max-w-[calc(100vw-1rem)] overflow-y-auto p-0"
style={{
maxHeight:
"calc(var(--radix-dropdown-menu-content-available-height) - 10px)",
}}
data-keyboard-nav={keyboardNavActive}
>
{!capabilities.canUseServerExamples && (
<output className="px-2 py-1.5 ui-type-menu-item text-muted-foreground" aria-live="polite">
Server connection required
</output>
)}
<div className="px-2 py-1.5">
<div className="ui-type-menu-title font-semibold mb-1">
Load Example
</div>
</div>
<div className="border-t" />
{examples.length === 0 && !isLoading && (
<div className="px-2 py-1.5 ui-type-menu-item text-muted-foreground">
No examples available
</div>
)}
{isLoading && (
<div className="px-2 py-1.5 ui-type-menu-item text-muted-foreground">
Loading examples...
</div>
)}
{!isLoading && examples.length > 0 && (
<ExamplesTree
examples={examples}
onLoadExample={handleLoadExample}
canUseServerExamples={capabilities.canUseServerExamples}
/>
)}
</DropdownMenuContent>
</DropdownMenu>
);
}
interface ExamplesTreeProps {
readonly examples: Example[];
readonly onLoadExample: (example: Example) => void;
readonly canUseServerExamples: boolean;
}
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;
}
function getExampleDisplayName(example: Example): string {
if (example.source !== "builtin") return example.title;
return (
example.files.find((file) => file.name.toLowerCase().endsWith(".ino"))
?.name ?? example.title
);
}
interface ExampleItemProps {
readonly example: Example;
readonly onLoadExample: (example: Example) => void;
readonly canUseServerExamples: boolean;
readonly compact?: boolean;
}
function ExampleItem({
example,
onLoadExample,
canUseServerExamples,
compact = false,
}: ExampleItemProps) {
return (
<Button
variant="ghost"
size="sm"
onClick={() => onLoadExample(example)}
disabled={!canUseServerExamples}
data-role="example-item"
tabIndex={0}
className={
compact
? "ui-type-menu-item w-full h-7 min-h-7 px-4 py-1 text-left flex items-center justify-start gap-2 focus:outline-hidden focus:ring-0 focus-visible:outline-hidden focus-visible:ring-0 [*[data-keyboard-nav='true']_&]:hover:bg-transparent [*[data-keyboard-nav='true']_&]:hover:text-current"
: "ui-type-menu-item w-full px-8 py-1 text-left flex items-center justify-start gap-2 focus:outline-hidden focus:ring-0 focus-visible:outline-hidden focus-visible:ring-0 [*[data-keyboard-nav='true']_&]:hover:bg-transparent [*[data-keyboard-nav='true']_&]:hover:text-current"
}
title={getExampleDisplayName(example)}
>
<span
className={
compact
? "flex h-4 w-4 shrink-0 items-center justify-center text-muted-foreground"
: "text-muted-foreground"
}
>
•
</span>
<span
className={
compact ? "min-w-0 flex-1 truncate whitespace-nowrap" : "w-full"
}
>
{getExampleDisplayName(example)}
</span>
</Button>
);
}
function ExamplesTree({ examples, onLoadExample, canUseServerExamples }: 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 ui-type-section-header text-left flex items-center justify-start gap-1 focus:outline-hidden focus:ring-0 focus-visible:outline-hidden 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 w-full">
{sourceLabels[source]}
</span>
</Button>
{isSourceExpanded && (
<div>
{source === "builtin"
? groupedBySource[source]
.toSorted((a, b) =>
getExampleDisplayName(a).localeCompare(
getExampleDisplayName(b),
),
)
.map((example) => (
<ExampleItem
key={example.id}
example={example}
onLoadExample={onLoadExample}
canUseServerExamples={canUseServerExamples}
compact
/>
))
: 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 ui-type-section-header text-left flex items-center justify-start gap-1 focus:outline-hidden focus:ring-0 focus-visible:outline-hidden 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 w-full">
{cleanCategoryName}
</span>
</Button>
{isCategoryExpanded && (
<div>
{items
.toSorted((a, b) =>
a.title.localeCompare(b.title),
)
.map((example) => (
<ExampleItem
key={example.id}
example={example}
onLoadExample={onLoadExample}
canUseServerExamples={canUseServerExamples}
/>
))}
</div>
)}
</div>
);
})}
</div>
)}
</div>
);
})}
</div>
);
}
|