'use client'; import { Button } from "@/components/ui/button"; import { ScrollArea } from "@/components/ui/scroll-area"; import { useExtensionWithDependency } from "@/hooks/useExtensionWithDependency"; import { useKeymapType } from "@/hooks/useKeymapType"; import { gutterWidthExtension } from "@/lib/extensions/gutterWidthExtension"; import { markMatches, searchResultHighlightExtension } from "@/lib/extensions/searchResultHighlightExtension"; import { ZoektMatch } from "@/lib/types"; import { defaultKeymap } from "@codemirror/commands"; import { javascript } from "@codemirror/lang-javascript"; import { search } from "@codemirror/search"; import { EditorView, keymap } from "@codemirror/view"; import { Cross1Icon, FileIcon } from "@radix-ui/react-icons"; import { Scrollbar } from "@radix-ui/react-scroll-area"; import { vim } from "@replit/codemirror-vim"; import CodeMirror, { ReactCodeMirrorRef } from '@uiw/react-codemirror'; import clsx from "clsx"; import { ArrowDown, ArrowUp } from "lucide-react"; import { useTheme } from "next-themes"; import { useCallback, useEffect, useMemo, useRef, useState } from "react"; export interface CodePreviewFile { content: string; filepath: string; link?: string; matches: ZoektMatch[]; } interface CodePreviewProps { file?: CodePreviewFile; selectedMatchIndex: number; onSelectedMatchIndexChange: (index: number) => void; onClose: () => void; } export const CodePreview = ({ file, selectedMatchIndex, onSelectedMatchIndexChange, onClose, }: CodePreviewProps) => { const editorRef = useRef(null); const { theme: _theme, systemTheme } = useTheme(); const [ keymapType ] = useKeymapType(); const theme = useMemo(() => { if (_theme === "system") { return systemTheme ?? "light"; } return _theme ?? "light"; }, [_theme, systemTheme]); const [gutterWidth, setGutterWidth] = useState(0); const keymapExtension = useExtensionWithDependency( editorRef.current?.view ?? null, () => { switch (keymapType) { case "default": return keymap.of(defaultKeymap); case "vim": return vim(); } }, [keymapType] ); const extensions = useMemo(() => { return [ keymapExtension, gutterWidthExtension, javascript(), searchResultHighlightExtension(), search({ top: true, }), EditorView.updateListener.of(update => { const width = update.view.plugin(gutterWidthExtension)?.width; if (width) { setGutterWidth(width); } }), ]; }, [keymapExtension]); useEffect(() => { if (!file || !editorRef.current?.view) { return; } markMatches(selectedMatchIndex, file.matches, editorRef.current.view); }, [file, file?.matches, selectedMatchIndex]); const onUpClicked = useCallback(() => { onSelectedMatchIndexChange(selectedMatchIndex - 1); }, [onSelectedMatchIndexChange, selectedMatchIndex]); const onDownClicked = useCallback(() => { onSelectedMatchIndexChange(selectedMatchIndex + 1); }, [onSelectedMatchIndexChange, selectedMatchIndex]); return (
{ if (file?.link) { window.open(file.link, "_blank"); } }} > {file?.filepath}

{`${selectedMatchIndex + 1} of ${file?.matches.length}`}

) }