All files / client/src/components/features examples-menu.tsx

0.67% Statements 1/148
0% Branches 0/65
0% Functions 0/32
0.69% Lines 1/143

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                                          1x                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          
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 {
  name: string;
  filename: string;
  content: string;
}
 
interface ExamplesMenuProps {
  onLoadExample: (filename: string, content: string) => void;
  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 [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 fileList: string[] = await response.json();
        const loadedExamples: Example[] = [];
 
        // Load each example file
        for (const filename of fileList) {
          try {
            const fileResponse = await fetch(`/examples/${filename}`);
            if (fileResponse.ok) {
              const content = await fileResponse.text();
              // Extract display name: remove leading numbers and hyphens
              const displayName =
                filename.split("/").pop()?.replace(/^\d+-/, "") || filename;
 
              loadedExamples.push({
                name: displayName,
                filename: filename,
                content: content,
              });
            }
          } catch (error) {
            console.error(`Failed to load example ${filename}:`, error);
          }
        }
 
        // Sort examples by filename
        loadedExamples.sort((a, b) => a.filename.localeCompare(b.filename));
        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 = navigator.platform.toUpperCase().includes("MAC");
    const onKey = (e: KeyboardEvent) => {
      const isExamplesKey =
        (isMac ? e.metaKey : e.ctrlKey) && !e.shiftKey && e.code === "KeyE";
      if (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(
        document.querySelectorAll(
          '[data-role="example-folder"], [data-role="example-item"]',
        ),
      ) as HTMLElement[];
      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(
        '[data-role="example-folder"], [data-role="example-item"]',
      );
      allItems.forEach((it) => {
        it.classList.remove(
          "bg-accent",
          "text-accent-foreground",
          "rounded-sm",
        );
        it.setAttribute("data-keyboard-focused", "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].setAttribute("data-keyboard-focused", "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(
        '[data-role="example-folder"], [data-role="example-item"]',
      ) as HTMLElement;
      if (target && target.getAttribute("data-keyboard-focused") === "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();
      if (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(() => {
      if (!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 = focusedIndexRef.current >= 0 ? focusedIndexRef.current : 0;
        items[idx]?.click();
      } else if (e.key === "Escape") {
        setOpen(false);
      }
    };
 
    // Add mouse move listener
    window.addEventListener("mousemove", onMouseMove);
    window.addEventListener("keydown", onKey, { capture: true });
    return () => {
      window.removeEventListener("mousemove", onMouseMove);
      window.removeEventListener("keydown", onKey, { capture: true });
      clearHighlight();
    };
  }, [open]);
 
  const handleLoadExample = (example: Example) => {
    onLoadExample(example.filename, example.content);
    toast({
      title: "Example Loaded",
      description: `${example.filename} has been loaded into the editor`,
    });
 
    // Close menu after loading example unless "keep open" setting is enabled
    try {
      if (window.localStorage.getItem(KEEP_EXAMPLES_MENU_OPEN_KEY) !== "1") {
        setOpen(false);
      }
    } catch {
      setOpen(false);
    }
  };
 
  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 {
  examples: Example[];
  onLoadExample: (example: Example) => void;
}
 
function ExamplesTree({ examples, onLoadExample }: ExamplesTreeProps) {
  const [expandedFolder, setExpandedFolder] = useState<string | null>(null);
 
  function groupExamplesByFolder(items: Example[]): Record<string, Example[]> {
    const grouped: Record<string, Example[]> = {};
    items.forEach((item) => {
      const parts = item.filename.split("/");
      const folder = parts.length > 1 ? parts[0] : "Other";
      if (!grouped[folder]) grouped[folder] = [];
      grouped[folder].push(item);
    });
    return grouped;
  }
 
  function toggleFolder(folder: string) {
    // Close the folder if it's already open, otherwise open it and close others
    if (expandedFolder === folder) {
      setExpandedFolder(null);
    } else {
      setExpandedFolder(folder);
    }
  }
 
  const grouped = groupExamplesByFolder(examples);
 
  return (
    <div className="py-1">
      {Object.entries(grouped)
        .sort(([a], [b]) => a.localeCompare(b))
        .map(([folder, items]) => {
          const isExpanded = expandedFolder === folder;
          const cleanFolderName = folder.replace(/^\d+-/, "");
 
          return (
            <div key={folder}>
              <Button
                variant="ghost"
                size="sm"
                onClick={() => toggleFolder(folder)}
                data-role="example-folder"
                data-folder={folder}
                tabIndex={0}
                className="w-full px-2 py-1.5 text-ui-sm 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 ${isExpanded ? "rotate-90" : ""}`}
                />
                <span className="font-medium text-ui-xs w-full">
                  {cleanFolderName}
                </span>
              </Button>
 
              {isExpanded && (
                <div className="bg-muted/30">
                  {items
                    .sort((a, b) => a.filename.localeCompare(b.filename))
                    .map((example) => (
                      <Button
                        key={example.filename}
                        variant="ghost"
                        size="sm"
                        onClick={() => onLoadExample(example)}
                        data-role="example-item"
                        tabIndex={0}
                        className="w-full px-4 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="w-full">{example.name}</span>
                      </Button>
                    ))}
                </div>
              )}
            </div>
          );
        })}
    </div>
  );
}