diff --git a/packages/search/.env.example b/packages/search/.env.example new file mode 100644 index 0000000..557ac82 --- /dev/null +++ b/packages/search/.env.example @@ -0,0 +1,2 @@ +VECTOR_STORE_ID= +MXBAI_API_KEY= \ No newline at end of file diff --git a/packages/search/.gitignore b/packages/search/.gitignore new file mode 100644 index 0000000..e72b4d6 --- /dev/null +++ b/packages/search/.gitignore @@ -0,0 +1,41 @@ +# See https://help.github.com/articles/ignoring-files/ for more about ignoring files. + +# dependencies +/node_modules +/.pnp +.pnp.* +.yarn/* +!.yarn/patches +!.yarn/plugins +!.yarn/releases +!.yarn/versions + +# testing +/coverage + +# next.js +/.next/ +/out/ + +# production +/build + +# misc +.DS_Store +*.pem + +# debug +npm-debug.log* +yarn-debug.log* +yarn-error.log* +.pnpm-debug.log* + +# env files (can opt-in for committing if needed) +.env + +# vercel +.vercel + +# typescript +*.tsbuildinfo +next-env.d.ts diff --git a/packages/search/README.md b/packages/search/README.md new file mode 100644 index 0000000..e215bc4 --- /dev/null +++ b/packages/search/README.md @@ -0,0 +1,36 @@ +This is a [Next.js](https://nextjs.org) project bootstrapped with [`create-next-app`](https://nextjs.org/docs/app/api-reference/cli/create-next-app). + +## Getting Started + +First, run the development server: + +```bash +npm run dev +# or +yarn dev +# or +pnpm dev +# or +bun dev +``` + +Open [http://localhost:3000](http://localhost:3000) with your browser to see the result. + +You can start editing the page by modifying `app/page.tsx`. The page auto-updates as you edit the file. + +This project uses [`next/font`](https://nextjs.org/docs/app/building-your-application/optimizing/fonts) to automatically optimize and load [Geist](https://vercel.com/font), a new font family for Vercel. + +## Learn More + +To learn more about Next.js, take a look at the following resources: + +- [Next.js Documentation](https://nextjs.org/docs) - learn about Next.js features and API. +- [Learn Next.js](https://nextjs.org/learn) - an interactive Next.js tutorial. + +You can check out [the Next.js GitHub repository](https://github.com/vercel/next.js) - your feedback and contributions are welcome! + +## Deploy on Vercel + +The easiest way to deploy your Next.js app is to use the [Vercel Platform](https://vercel.com/new?utm_medium=default-template&filter=next.js&utm_source=create-next-app&utm_campaign=create-next-app-readme) from the creators of Next.js. + +Check out our [Next.js deployment documentation](https://nextjs.org/docs/app/building-your-application/deploying) for more details. diff --git a/packages/search/components.json b/packages/search/components.json new file mode 100644 index 0000000..3289f23 --- /dev/null +++ b/packages/search/components.json @@ -0,0 +1,21 @@ +{ + "$schema": "https://ui.shadcn.com/schema.json", + "style": "new-york", + "rsc": true, + "tsx": true, + "tailwind": { + "config": "", + "css": "src/app/globals.css", + "baseColor": "neutral", + "cssVariables": true, + "prefix": "" + }, + "aliases": { + "components": "@/components", + "utils": "@/lib/utils", + "ui": "@/components/ui", + "lib": "@/lib", + "hooks": "@/hooks" + }, + "iconLibrary": "lucide" +} diff --git a/packages/search/next.config.ts b/packages/search/next.config.ts new file mode 100644 index 0000000..e9ffa30 --- /dev/null +++ b/packages/search/next.config.ts @@ -0,0 +1,7 @@ +import type { NextConfig } from "next"; + +const nextConfig: NextConfig = { + /* config options here */ +}; + +export default nextConfig; diff --git a/packages/search/package.json b/packages/search/package.json new file mode 100644 index 0000000..025de6e --- /dev/null +++ b/packages/search/package.json @@ -0,0 +1,44 @@ +{ + "name": "search", + "version": "0.1.0", + "private": true, + "scripts": { + "dev": "next dev --turbopack", + "build": "next build", + "start": "next start", + "lint": "biome lint --write .", + "format": "biome format --write .", + "check-types": "tsc --noEmit" + }, + "dependencies": { + "@mixedbread/sdk": "^0.24.0", + "@radix-ui/react-dialog": "^1.1.14", + "@radix-ui/react-scroll-area": "^1.2.9", + "@radix-ui/react-slot": "^1.2.3", + "@radix-ui/react-tabs": "^1.1.12", + "class-variance-authority": "^0.7.1", + "clsx": "^2.1.1", + "lucide-react": "^0.514.0", + "motion": "^12.17.3", + "next": "15.3.3", + "next-themes": "^0.4.6", + "react": "^19.0.0", + "react-dom": "^19.0.0", + "react-markdown": "^10.1.0", + "react-shiki": "^0.7.1", + "rehype-katex": "^7.0.1", + "remark-gfm": "^4.0.1", + "remark-math": "^6.0.0", + "tailwind-merge": "^3.3.1", + "zod": "^3.25.63" + }, + "devDependencies": { + "@tailwindcss/postcss": "^4", + "@types/node": "^20", + "@types/react": "^19", + "@types/react-dom": "^19", + "tailwindcss": "^4", + "tw-animate-css": "^1.3.4", + "typescript": "^5" + } +} diff --git a/packages/search/postcss.config.mjs b/packages/search/postcss.config.mjs new file mode 100644 index 0000000..c7bcb4b --- /dev/null +++ b/packages/search/postcss.config.mjs @@ -0,0 +1,5 @@ +const config = { + plugins: ["@tailwindcss/postcss"], +}; + +export default config; diff --git a/packages/search/public/file.svg b/packages/search/public/file.svg new file mode 100644 index 0000000..004145c --- /dev/null +++ b/packages/search/public/file.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/packages/search/public/globe.svg b/packages/search/public/globe.svg new file mode 100644 index 0000000..567f17b --- /dev/null +++ b/packages/search/public/globe.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/packages/search/public/next.svg b/packages/search/public/next.svg new file mode 100644 index 0000000..5174b28 --- /dev/null +++ b/packages/search/public/next.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/packages/search/public/vercel.svg b/packages/search/public/vercel.svg new file mode 100644 index 0000000..7705396 --- /dev/null +++ b/packages/search/public/vercel.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/packages/search/public/window.svg b/packages/search/public/window.svg new file mode 100644 index 0000000..b2b2a44 --- /dev/null +++ b/packages/search/public/window.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/packages/search/src/app/api/search/route.ts b/packages/search/src/app/api/search/route.ts new file mode 100644 index 0000000..f4c7a5d --- /dev/null +++ b/packages/search/src/app/api/search/route.ts @@ -0,0 +1,23 @@ +import { adapters } from "@/search/adapters"; + +interface SearchMetadata { + title?: string; + url?: string; + tag?: string; +} + +export const GET = adapters.nextAppHandler({ + transform: (results) => { + return results.map((result) => { + const metadata = result.chunks?.[0].generated_metadata as SearchMetadata; + + return { + id: result.id, + url: metadata.url || "#", + title: metadata.title || "Untitled", + tag: metadata.tag || "", + breadcrumb: [], + }; + }); + }, +}); diff --git a/packages/search/src/app/chat/page.tsx b/packages/search/src/app/chat/page.tsx new file mode 100644 index 0000000..a678d5c --- /dev/null +++ b/packages/search/src/app/chat/page.tsx @@ -0,0 +1,76 @@ +"use client"; + +import { useChatDemo } from "@/search/hooks/use-chat-demo"; +import { + Composer, + ComposerFooter, + ComposerForm, + ComposerInput, + ComposerSubmit, + ComposerSuggestionItem, + ComposerSuggestions, +} from "@/search/ui/composer"; +import { + Thread, + ThreadIf, + ThreadMessages, + ThreadScrollToBottom, + ThreadViewport, +} from "@/search/ui/thread"; + +export default function ChatDemoPage() { + const { thread, sendMessage, isLoading } = useChatDemo(); + + return ( +
+
+ + + + + + + + + + + How do I implement semantic search? + + + + + + What are the benefits of vector databases? + + + + + + Explain RAG architecture patterns + + + + + + Show me TypeScript best practices + + + + + + +
+ + + + + + + + +
+
+
+
+ ); +} diff --git a/packages/search/src/app/favicon.ico b/packages/search/src/app/favicon.ico new file mode 100644 index 0000000..718d6fe Binary files /dev/null and b/packages/search/src/app/favicon.ico differ diff --git a/packages/search/src/app/globals.css b/packages/search/src/app/globals.css new file mode 100644 index 0000000..5ac5471 --- /dev/null +++ b/packages/search/src/app/globals.css @@ -0,0 +1,131 @@ +@import "tailwindcss"; +@import "tw-animate-css"; + +@custom-variant dark (&:is(.dark *)); + +@theme inline { + --color-logo: var(--logo); + --color-background: var(--background); + --color-foreground: var(--foreground); + --font-sans: var(--font-geist-sans); + --font-mono: var(--font-geist-mono); + --color-sidebar-ring: var(--sidebar-ring); + --color-sidebar-border: var(--sidebar-border); + --color-sidebar-accent-foreground: var(--sidebar-accent-foreground); + --color-sidebar-accent: var(--sidebar-accent); + --color-sidebar-primary-foreground: var(--sidebar-primary-foreground); + --color-sidebar-primary: var(--sidebar-primary); + --color-sidebar-foreground: var(--sidebar-foreground); + --color-sidebar: var(--sidebar); + --color-chart-5: var(--chart-5); + --color-chart-4: var(--chart-4); + --color-chart-3: var(--chart-3); + --color-chart-2: var(--chart-2); + --color-chart-1: var(--chart-1); + --color-ring: var(--ring); + --color-input: var(--input); + --color-border: var(--border); + --color-destructive: var(--destructive); + --color-accent-foreground: var(--accent-foreground); + --color-accent: var(--accent); + --color-muted-foreground: var(--muted-foreground); + --color-muted: var(--muted); + --color-secondary-foreground: var(--secondary-foreground); + --color-secondary: var(--secondary); + --color-primary-foreground: var(--primary-foreground); + --color-primary: var(--primary); + --color-popover-foreground: var(--popover-foreground); + --color-popover: var(--popover); + --color-card-foreground: var(--card-foreground); + --color-card: var(--card); + --radius-sm: calc(var(--radius) - 4px); + --radius-md: calc(var(--radius) - 2px); + --radius-lg: var(--radius); + --radius-xl: calc(var(--radius) + 4px); +} + +:root { + --logo: oklch(0.64 0.2 39); + --radius: 0.625rem; + --background: oklch(1 0 0); + --foreground: oklch(0.145 0 0); + --card: oklch(1 0 0); + --card-foreground: oklch(0.145 0 0); + --popover: oklch(1 0 0); + --popover-foreground: oklch(0.145 0 0); + --primary: oklch(0.205 0 0); + --primary-foreground: oklch(0.985 0 0); + --secondary: oklch(0.97 0 0); + --secondary-foreground: oklch(0.205 0 0); + --muted: oklch(0.97 0 0); + --muted-foreground: oklch(0.556 0 0); + --accent: oklch(0.97 0 0); + --accent-foreground: oklch(0.205 0 0); + --destructive: oklch(0.577 0.245 27.325); + --border: oklch(0.922 0 0); + --input: oklch(0.922 0 0); + --ring: oklch(0.708 0 0); + --chart-1: oklch(0.646 0.222 41.116); + --chart-2: oklch(0.6 0.118 184.704); + --chart-3: oklch(0.398 0.07 227.392); + --chart-4: oklch(0.828 0.189 84.429); + --chart-5: oklch(0.769 0.188 70.08); + --sidebar: oklch(0.985 0 0); + --sidebar-foreground: oklch(0.145 0 0); + --sidebar-primary: oklch(0.205 0 0); + --sidebar-primary-foreground: oklch(0.985 0 0); + --sidebar-accent: oklch(0.97 0 0); + --sidebar-accent-foreground: oklch(0.205 0 0); + --sidebar-border: oklch(0.922 0 0); + --sidebar-ring: oklch(0.708 0 0); +} + +.dark { + --background: oklch(0.145 0 0); + --foreground: oklch(0.985 0 0); + --card: oklch(0.205 0 0); + --card-foreground: oklch(0.985 0 0); + --popover: oklch(0.205 0 0); + --popover-foreground: oklch(0.985 0 0); + --primary: oklch(0.922 0 0); + --primary-foreground: oklch(0.205 0 0); + --secondary: oklch(0.269 0 0); + --secondary-foreground: oklch(0.985 0 0); + --muted: oklch(0.269 0 0); + --muted-foreground: oklch(0.708 0 0); + --accent: oklch(0.269 0 0); + --accent-foreground: oklch(0.985 0 0); + --destructive: oklch(0.704 0.191 22.216); + --border: oklch(1 0 0 / 10%); + --input: oklch(1 0 0 / 15%); + --ring: oklch(0.556 0 0); + --chart-1: oklch(0.488 0.243 264.376); + --chart-2: oklch(0.696 0.17 162.48); + --chart-3: oklch(0.769 0.188 70.08); + --chart-4: oklch(0.627 0.265 303.9); + --chart-5: oklch(0.645 0.246 16.439); + --sidebar: oklch(0.205 0 0); + --sidebar-foreground: oklch(0.985 0 0); + --sidebar-primary: oklch(0.488 0.243 264.376); + --sidebar-primary-foreground: oklch(0.985 0 0); + --sidebar-accent: oklch(0.269 0 0); + --sidebar-accent-foreground: oklch(0.985 0 0); + --sidebar-border: oklch(1 0 0 / 10%); + --sidebar-ring: oklch(0.556 0 0); +} + +@layer base { + * { + @apply border-border outline-ring/50; + } + body { + @apply bg-background text-foreground; + } +} + +@layer base { + button:not(:disabled), + [role="button"]:not(:disabled) { + cursor: pointer; + } +} diff --git a/packages/search/src/app/layout.tsx b/packages/search/src/app/layout.tsx new file mode 100644 index 0000000..9f10924 --- /dev/null +++ b/packages/search/src/app/layout.tsx @@ -0,0 +1,51 @@ +import type { Metadata } from "next"; +import { Geist, Geist_Mono } from "next/font/google"; +import "./globals.css"; +import { SiteHeader } from "@/components/site-header"; +import { ThemeProvider } from "@/components/theme-provider"; +import { ScrollArea } from "@/components/ui/scroll-area"; + +const geistSans = Geist({ + variable: "--font-geist-sans", + subsets: ["latin"], +}); + +const geistMono = Geist_Mono({ + variable: "--font-geist-mono", + subsets: ["latin"], +}); + +export const metadata: Metadata = { + title: "Search", + description: "Search powered by Mixedbread", +}; + +export default function RootLayout({ + children, +}: Readonly<{ + children: React.ReactNode; +}>) { + return ( + + + +
+ +
+ + {children} + +
+
+
+ + + ); +} diff --git a/packages/search/src/app/page.tsx b/packages/search/src/app/page.tsx new file mode 100644 index 0000000..70f7d15 --- /dev/null +++ b/packages/search/src/app/page.tsx @@ -0,0 +1,13 @@ +import { SearchTrigger } from "@/components/search-trigger"; + +export default function Home() { + return ( +
+

+ Search Anything... +

+ + +
+ ); +} diff --git a/packages/search/src/app/search/page.tsx b/packages/search/src/app/search/page.tsx new file mode 100644 index 0000000..9fb8313 --- /dev/null +++ b/packages/search/src/app/search/page.tsx @@ -0,0 +1,9 @@ +import { CustomSearchPage } from "@/components/search-page"; + +export default function SearchPage() { + return ( +
+ +
+ ); +} diff --git a/packages/search/src/components/mxbai-logo-icon.tsx b/packages/search/src/components/mxbai-logo-icon.tsx new file mode 100644 index 0000000..90a02f7 --- /dev/null +++ b/packages/search/src/components/mxbai-logo-icon.tsx @@ -0,0 +1,275 @@ +import type { LucideProps } from "lucide-react"; + +export const MxbaiLogoIcon = (props: LucideProps) => ( + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +); diff --git a/packages/search/src/components/search-dialog.tsx b/packages/search/src/components/search-dialog.tsx new file mode 100644 index 0000000..40efd1b --- /dev/null +++ b/packages/search/src/components/search-dialog.tsx @@ -0,0 +1,212 @@ +"use client"; + +import { MessageSquareIcon } from "lucide-react"; +import { motion } from "motion/react"; +import { useEffect, useRef, useState } from "react"; +import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"; +import { mockResults } from "@/lib/utils"; +import { useChatDemo } from "@/search/hooks/use-chat-demo"; +import { useMeasure } from "@/search/hooks/use-measure"; +import { useSearch } from "@/search/hooks/use-search"; +import { + Composer, + ComposerFooter, + ComposerForm, + ComposerInput, + ComposerSubmit, + ComposerSuggestionItem, + ComposerSuggestions, +} from "@/search/ui/composer"; +import { + SearchDialog, + SearchDialogContent, + SearchDialogFooter, + SearchDialogHeader, + SearchDialogOverlay, +} from "@/search/ui/dialog"; +import { + Search, + SearchIndicatorIcon, + SearchInput, + SearchList, + SearchListItem, + SearchListItemTitle, +} from "@/search/ui/search"; +import { + Thread, + ThreadIf, + ThreadMessages, + ThreadScrollToBottom, + ThreadViewport, +} from "@/search/ui/thread"; +import { MxbaiLogoIcon } from "./mxbai-logo-icon"; + +export function CustomSearchDialog(props: { + open: boolean; + onOpenChange: (open: boolean) => void; +}) { + const { search, setSearch, results, isLoading } = useSearch(); + const { thread, sendMessage, isLoading: isChatLoading } = useChatDemo(); + const [activeTab, setActiveTab] = useState("search"); + + const [ref, dimensions] = useMeasure(); + + const searchInputRef = useRef(null); + const chatInputRef = useRef(null); + + const mockedResults = mockResults(results); + + useEffect(() => { + const timer = setTimeout(() => { + if (activeTab === "search") { + searchInputRef.current?.focus(); + } else { + chatInputRef.current?.focus(); + } + }, 100); + + return () => clearTimeout(timer); + }, [activeTab]); + + return ( + + + + + +
+ + + + {activeTab === "search" ? ( + <> + + + + ) : ( +
+ + Chat +
+ )} + + + Search + Chat + +
+ + + ( + + + + )} + /> + +
+ + + + + + + + + + + + How do I implement semantic search? + + + + + + What are the benefits of vector databases? + + + + + + Explain RAG architecture patterns + + + + + + Show me code examples + + + + + + +
+ + + + + + + + +
+
+
+
+ + +

+ Powered by{" "} + + + Mixedbread + +

+
+
+
+
+
+ ); +} diff --git a/packages/search/src/components/search-page.tsx b/packages/search/src/components/search-page.tsx new file mode 100644 index 0000000..86bdc41 --- /dev/null +++ b/packages/search/src/components/search-page.tsx @@ -0,0 +1,64 @@ +"use client"; + +import { useEffect, useRef } from "react"; +import { mockResults } from "@/lib/utils"; +import { useSearch } from "@/search/hooks/use-search"; +import { + Search, + SearchIf, + SearchIndicatorIcon, + SearchInput, + SearchList, + TagsList, +} from "@/search/ui/search"; + +export function CustomSearchPage() { + const { search, setSearch, results, isLoading } = useSearch(); + const inputRef = useRef(null); + + const mockedResults = mockResults(results); + + useEffect(() => { + if (inputRef.current) { + inputRef.current.focus(); + } + }, []); + + return ( + +
+
+ + +
+
+ + {mockedResults.length > 0 && ( +
+ + + + {mockedResults.length} Result{mockedResults.length !== 1 ? "s" : ""} + +
+ )} + + +
+ Search for something to see the results. +
+
+ + +
+ ); +} diff --git a/packages/search/src/components/search-trigger.tsx b/packages/search/src/components/search-trigger.tsx new file mode 100644 index 0000000..a90cfe8 --- /dev/null +++ b/packages/search/src/components/search-trigger.tsx @@ -0,0 +1,48 @@ +"use client"; + +import { Search } from "lucide-react"; +import { useEffect, useState } from "react"; +import { CustomSearchDialog } from "./search-dialog"; +import { Button } from "./ui/button"; +import { Kbd } from "./ui/kbd"; + +export function SearchTrigger() { + const [isOpen, setIsOpen] = useState(false); + const [isMac, setIsMac] = useState(false); + + // Detect if user is on Mac + useEffect(() => { + setIsMac(navigator.platform.toUpperCase().indexOf("MAC") >= 0); + }, []); + + // Handle keyboard shortcut + useEffect(() => { + const handleKeyDown = (event: KeyboardEvent) => { + if ((event.metaKey || event.ctrlKey) && event.key === "k") { + event.preventDefault(); + setIsOpen(true); + } + }; + + document.addEventListener("keydown", handleKeyDown); + return () => document.removeEventListener("keydown", handleKeyDown); + }, []); + + return ( + <> + + + + + ); +} diff --git a/packages/search/src/components/site-header.tsx b/packages/search/src/components/site-header.tsx new file mode 100644 index 0000000..5598fc4 --- /dev/null +++ b/packages/search/src/components/site-header.tsx @@ -0,0 +1,29 @@ +"use client"; + +import Link from "next/link"; +import { MxbaiLogoIcon } from "./mxbai-logo-icon"; +import { ThemeToggle } from "./theme-toggle"; + +export function SiteHeader() { + return ( +
+
+
+ + + + + + Search + + + + Chat + +
+ + +
+
+ ); +} diff --git a/packages/search/src/components/theme-provider.tsx b/packages/search/src/components/theme-provider.tsx new file mode 100644 index 0000000..82337f8 --- /dev/null +++ b/packages/search/src/components/theme-provider.tsx @@ -0,0 +1,8 @@ +"use client"; + +import type { ThemeProviderProps } from "next-themes"; +import { ThemeProvider as NextThemesProvider } from "next-themes"; + +export function ThemeProvider({ children, ...props }: ThemeProviderProps) { + return {children}; +} diff --git a/packages/search/src/components/theme-toggle.tsx b/packages/search/src/components/theme-toggle.tsx new file mode 100644 index 0000000..c1138db --- /dev/null +++ b/packages/search/src/components/theme-toggle.tsx @@ -0,0 +1,29 @@ +"use client"; + +import { MoonIcon, SunIcon } from "lucide-react"; +import { useTheme } from "next-themes"; +import { useEffect, useState } from "react"; +import { Button } from "@/components/ui/button"; + +export function ThemeToggle() { + const { setTheme, theme } = useTheme(); + const [mounted, setMounted] = useState(false); + + useEffect(() => { + setMounted(true); + }, []); + + if (!mounted) return null; + + return ( + + ); +} diff --git a/packages/search/src/components/ui/button.tsx b/packages/search/src/components/ui/button.tsx new file mode 100644 index 0000000..0f66d1c --- /dev/null +++ b/packages/search/src/components/ui/button.tsx @@ -0,0 +1,59 @@ +import { Slot } from "@radix-ui/react-slot"; +import { cva, type VariantProps } from "class-variance-authority"; +import type * as React from "react"; + +import { cn } from "@/lib/utils"; + +const buttonVariants = cva( + "inline-flex shrink-0 items-center justify-center gap-2 whitespace-nowrap rounded-md font-medium text-sm outline-none transition-all focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 disabled:pointer-events-none disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 [&_svg:not([class*='size-'])]:size-4 [&_svg]:pointer-events-none [&_svg]:shrink-0", + { + variants: { + variant: { + default: + "bg-primary text-primary-foreground shadow-xs hover:bg-primary/90", + destructive: + "bg-destructive text-white shadow-xs hover:bg-destructive/90 focus-visible:ring-destructive/20 dark:bg-destructive/60 dark:focus-visible:ring-destructive/40", + outline: + "border bg-background shadow-xs hover:bg-accent hover:text-accent-foreground dark:border-input dark:bg-input/30 dark:hover:bg-input/50", + secondary: + "bg-secondary text-secondary-foreground shadow-xs hover:bg-secondary/80", + ghost: + "hover:bg-accent hover:text-accent-foreground dark:hover:bg-accent/50", + link: "text-primary underline-offset-4 hover:underline", + }, + size: { + default: "h-9 px-4 py-2 has-[>svg]:px-3", + sm: "h-8 gap-1.5 rounded-md px-3 has-[>svg]:px-2.5", + lg: "h-10 rounded-md px-6 has-[>svg]:px-4", + icon: "size-9", + }, + }, + defaultVariants: { + variant: "default", + size: "default", + }, + } +); + +function Button({ + className, + variant, + size, + asChild = false, + ...props +}: React.ComponentProps<"button"> & + VariantProps & { + asChild?: boolean; + }) { + const Comp = asChild ? Slot : "button"; + + return ( + + ); +} + +export { Button, buttonVariants }; diff --git a/packages/search/src/components/ui/kbd.tsx b/packages/search/src/components/ui/kbd.tsx new file mode 100644 index 0000000..e1d628c --- /dev/null +++ b/packages/search/src/components/ui/kbd.tsx @@ -0,0 +1,54 @@ +import { cva, type VariantProps } from "class-variance-authority"; +import * as React from "react"; + +import { cn } from "@/lib/utils"; + +const kbdVariants = cva( + "select-none rounded border px-1.5 py-px font-normal font-sans text-[0.7rem] shadow-xs disabled:opacity-50", + { + variants: { + variant: { + default: "bg-accent text-accent-foreground", + outline: "bg-background text-foreground", + }, + }, + defaultVariants: { + variant: "default", + }, + } +); + +export interface KbdProps + extends React.ComponentPropsWithoutRef<"kbd">, + VariantProps { + /** + * The title of the `abbr` element inside the `kbd` element. + * @default undefined + * @type string | undefined + * @example title="Command" + */ + abbrTitle?: string; +} + +const Kbd = React.forwardRef( + ({ abbrTitle, children, className, variant, ...props }, ref) => { + return ( + + {abbrTitle ? ( + + {children} + + ) : ( + children + )} + + ); + } +); +Kbd.displayName = "Kbd"; + +export { Kbd }; diff --git a/packages/search/src/components/ui/scroll-area.tsx b/packages/search/src/components/ui/scroll-area.tsx new file mode 100644 index 0000000..1e8e281 --- /dev/null +++ b/packages/search/src/components/ui/scroll-area.tsx @@ -0,0 +1,70 @@ +"use client"; + +import * as ScrollAreaPrimitive from "@radix-ui/react-scroll-area"; +import type * as React from "react"; +import { cn } from "@/lib/utils"; + +function ScrollArea({ + className, + children, + ...props +}: React.ComponentProps) { + return ( + + + {children} + + + + + ); +} + +function ScrollBar({ + className, + orientation = "vertical", + ...props +}: React.ComponentProps) { + return ( + + + + ); +} + +function ScrollViewport({ + className, + ...props +}: React.ComponentProps) { + return ( + + ); +} + +export { ScrollArea, ScrollBar, ScrollViewport }; diff --git a/packages/search/src/components/ui/tabs.tsx b/packages/search/src/components/ui/tabs.tsx new file mode 100644 index 0000000..c1548ec --- /dev/null +++ b/packages/search/src/components/ui/tabs.tsx @@ -0,0 +1,66 @@ +"use client"; + +import * as TabsPrimitive from "@radix-ui/react-tabs"; +import type * as React from "react"; + +import { cn } from "@/lib/utils"; + +function Tabs({ + className, + ...props +}: React.ComponentProps) { + return ( + + ); +} + +function TabsList({ + className, + ...props +}: React.ComponentProps) { + return ( + + ); +} + +function TabsTrigger({ + className, + ...props +}: React.ComponentProps) { + return ( + + ); +} + +function TabsContent({ + className, + ...props +}: React.ComponentProps) { + return ( + + ); +} + +export { Tabs, TabsList, TabsTrigger, TabsContent }; diff --git a/packages/search/src/lib/utils.ts b/packages/search/src/lib/utils.ts new file mode 100644 index 0000000..f7ac93e --- /dev/null +++ b/packages/search/src/lib/utils.ts @@ -0,0 +1,28 @@ +import { type ClassValue, clsx } from "clsx"; +import { twMerge } from "tailwind-merge"; +import type { Result } from "@/search/lib/types"; + +export function cn(...inputs: ClassValue[]) { + return twMerge(clsx(inputs)); +} + +export const mockTags = ["Docs", "API Reference", "Components"]; + +export function mockResults(results: Result[]) { + return results.map((result, index) => { + let tag: string | undefined; + if (index < 4) { + tag = "Docs"; + } else { + const remainingTags = mockTags.slice(1); + const tagIndex = Math.floor((index - 4) / 2) % remainingTags.length; + tag = remainingTags[tagIndex]; + } + + return { + ...result, + breadcrumb: ["Documentation", "API Reference", "Components"], + tag, + }; + }); +} diff --git a/packages/search/src/search/adapters/index.ts b/packages/search/src/search/adapters/index.ts new file mode 100644 index 0000000..f9e1afa --- /dev/null +++ b/packages/search/src/search/adapters/index.ts @@ -0,0 +1,6 @@ +import { nextAppHandler, nextPagesHandler } from "./next"; + +export const adapters = { + nextAppHandler, + nextPagesHandler, +}; diff --git a/packages/search/src/search/adapters/next.ts b/packages/search/src/search/adapters/next.ts new file mode 100644 index 0000000..2e0ac80 --- /dev/null +++ b/packages/search/src/search/adapters/next.ts @@ -0,0 +1,76 @@ +import type { NextApiRequest, NextApiResponse } from "next"; +import { type NextRequest, NextResponse } from "next/server"; +import { BadRequestError, InternalServerError } from "../lib/errors"; +import { search } from "../lib/search"; +import type { TransformFunc } from "../lib/types"; + +export function nextAppHandler({ + transform, +}: { + transform?: TransformFunc; +} = {}) { + return async function GET(request: NextRequest) { + try { + const { searchParams } = new URL(request.url); + const params = Object.fromEntries(searchParams); + + const results = await search(params, transform); + + return NextResponse.json(results); + } catch (error) { + if (error instanceof BadRequestError) { + return NextResponse.json( + { error: error.message }, + { status: error.status } + ); + } + + if (error instanceof InternalServerError) { + return NextResponse.json( + { error: error.message }, + { status: error.status } + ); + } + + return NextResponse.json( + { error: "An unexpected error occurred" }, + { status: 500 } + ); + } + }; +} + +export function nextPagesHandler({ + transform, +}: { + transform?: TransformFunc; +} = {}) { + return async function handler( + request: NextApiRequest, + response: NextApiResponse + ) { + if (request.method !== "GET") { + return response.status(405).json({ error: "Method not allowed" }); + } + + try { + const params = request.query; + + const results = await search(params, transform); + + return response.json(results); + } catch (error) { + if (error instanceof BadRequestError) { + return response.status(error.status).json({ error: error.message }); + } + + if (error instanceof InternalServerError) { + return response.status(error.status).json({ error: error.message }); + } + + return response + .status(500) + .json({ error: "An unexpected error occurred" }); + } + }; +} diff --git a/packages/search/src/search/hooks/use-chat-demo.ts b/packages/search/src/search/hooks/use-chat-demo.ts new file mode 100644 index 0000000..4ba961f --- /dev/null +++ b/packages/search/src/search/hooks/use-chat-demo.ts @@ -0,0 +1,259 @@ +import { useCallback, useState } from "react"; +import type { Message } from "../lib/types"; + +const demoResponses: Record = { + hello: "Hello! How can I help you with the documentation today?", + hi: "Hi there! I'm here to help you navigate and understand the documentation. What would you like to know?", + help: `I can help you with: + +• **Finding specific documentation topics** +• **Explaining API concepts** +• **Providing code examples** +• **Answering technical questions** + +What would you like to explore?`, + search: `The search functionality allows you to: + +1. **Search through documentation** by keywords +2. **Filter results** by tags +3. **Navigate directly** to relevant sections + +You can use the search dialog or integrate search primitives into your own UI. + +### Example Usage +\`\`\`typescript +import { useSearch } from '@/search/hooks/use-search'; + +const { search, setSearch, results } = useSearch(); +\`\`\``, + api: `Our API provides several endpoints: + +| Endpoint | Description | +|----------|-------------| +| \`/embeddings\` | Generate text embeddings | +| \`/chat/completions\` | Chat with AI models | +| \`/files\` | Upload and manage files | +| \`/vector-stores\` | Create and query vector databases | + +Which endpoint would you like to learn more about?`, + code: `Here's a simple example of how to implement semantic search: + +\`\`\`typescript +import { MixedbreadClient } from '@mixedbread/sdk'; + +// Initialize the client +const client = new MixedbreadClient({ + apiKey: process.env.MIXEDBREAD_API_KEY +}); + +// Function to generate embeddings for text +async function generateEmbedding(text: string) { + try { + const response = await client.embeddings({ + model: 'mxbai-embed-large-v1', + input: text, + }); + + return response.data[0].embedding; + } catch (error) { + console.error('Error generating embedding:', error); + throw error; + } +} + +// Use the embeddings for similarity search +const query = 'What is semantic search?'; +const embedding = await generateEmbedding(query); +const results = await searchVector(embedding); +\`\`\` + +You can also work with multiple texts at once: + +\`\`\`javascript +const texts = [ + "Semantic search understands meaning", + "Traditional search matches keywords", + "Vector embeddings capture context" +]; + +const embeddings = await client.embeddings({ + model: 'mxbai-embed-large-v1', + input: texts +}); +\`\`\` + +> **Note:** Make sure to handle errors and implement proper rate limiting in production.`, + python: `Here's how to use the Mixedbread API with Python: + +\`\`\`python +from mixedbread import MixedbreadClient +import numpy as np + +# Initialize the client +client = MixedbreadClient(api_key="your-api-key") + +# Generate embeddings +response = client.embeddings( + model="mxbai-embed-large-v1", + input="What is semantic search?" +) + +# Extract the embedding vector +embedding = response.data[0].embedding +print(f"Embedding dimension: {len(embedding)}") + +# Calculate cosine similarity between embeddings +def cosine_similarity(a, b): + return np.dot(a, b) / (np.linalg.norm(a) * np.linalg.norm(b)) +\`\`\` + +The API supports batch processing for efficiency: + +\`\`\`python +texts = [ + "Semantic search uses meaning", + "Keyword search uses exact matches", + "Vector search uses embeddings" +] + +# Generate embeddings for multiple texts +response = client.embeddings( + model="mxbai-embed-large-v1", + input=texts +) + +embeddings = [item.embedding for item in response.data] +\`\`\``, + markdown: `## Markdown Support + +This chat interface supports **full markdown** rendering including: + +- **Bold** and *italic* text +- \`inline code\` snippets +- Lists (ordered and unordered) +- [Links](https://mixedbread.com) +- Code blocks with **syntax highlighting** +- Tables and more! + +> Blockquotes with *nested* formatting + +### Syntax Highlighting Examples + +We support many languages including TypeScript, Python, JavaScript, JSON, and more: + +\`\`\`json +{ + "name": "mixedbread-sdk", + "version": "1.0.0", + "features": ["embeddings", "search", "chat"] +} +\`\`\` + +Feel free to ask questions and I'll format my responses for better readability.`, + default: `I understand you're asking about the documentation. Could you be more specific about what you'd like to know? + +I can help with: +- **API references** +- **Integration guides** +- **Code examples** +- **Best practices**`, +}; + +function getResponse(input: string) { + const lowerInput = input.toLowerCase(); + + // Check for exact matches first + for (const [keyword, response] of Object.entries(demoResponses)) { + if (keyword !== "default" && lowerInput.includes(keyword)) { + return response; + } + } + + // Additional keyword checks for better matching + if ( + lowerInput.includes("typescript") || + lowerInput.includes("javascript") || + lowerInput.includes("example") + ) { + return demoResponses.code; + } + + if (lowerInput.includes("python")) { + return demoResponses.python; + } + + if ( + lowerInput.includes("format") || + lowerInput.includes("style") || + lowerInput.includes("syntax") + ) { + return demoResponses.markdown; + } + + return demoResponses.default; +} + +export function useChatDemo() { + const [thread, setThread] = useState<{ + id: string; + messages: Message[]; + }>({ + id: "1", + messages: [], + }); + const [isLoading, setIsLoading] = useState(false); + + const sendMessage = useCallback(async (content: string) => { + const userMessage: Message = { + status: "completed", + id: `user-${Date.now()}`, + role: "user", + content, + createdAt: new Date(), + }; + + const pendingMessageId = `assistant-${Date.now()}`; + + const pendingAssistantMessage: Message = { + status: "pending", + id: pendingMessageId, + role: "assistant", + content: "", + }; + + setThread((prev) => ({ + ...prev, + messages: [...prev.messages, userMessage, pendingAssistantMessage], + })); + + setIsLoading(true); + + setTimeout( + () => { + const assistantMessage: Message = { + status: "completed", + id: pendingMessageId, + role: "assistant", + content: getResponse(content), + createdAt: new Date(), + }; + + setThread((prev) => { + const updatedMessages = prev.messages.map((message) => + message.id === pendingMessageId ? assistantMessage : message + ); + + return { + ...prev, + messages: updatedMessages, + }; + }); + + setIsLoading(false); + }, + 800 + Math.random() * 400 + ); + }, []); + + return { thread, sendMessage, isLoading }; +} diff --git a/packages/search/src/search/hooks/use-measure.ts b/packages/search/src/search/hooks/use-measure.ts new file mode 100644 index 0000000..16eab75 --- /dev/null +++ b/packages/search/src/search/hooks/use-measure.ts @@ -0,0 +1,42 @@ +import { useCallback, useRef, useState } from "react"; + +export function useMeasure() { + const [dimensions, setDimensions] = useState<{ + width: number | undefined; + height: number | undefined; + }>({ + width: undefined, + height: undefined, + }); + + const previousObserver = useRef(null); + + const customRef = useCallback((node: T | null) => { + if (previousObserver.current) { + previousObserver.current.disconnect(); + previousObserver.current = null; + } + + if (node?.nodeType === Node.ELEMENT_NODE) { + const observer = new ResizeObserver(([entry]) => { + if (entry?.borderBoxSize?.[0]) { + const { inlineSize: width, blockSize: height } = + entry.borderBoxSize[0]; + + // Only update dimensions if they have actually changed + setDimensions((prev) => { + if (prev.width === width && prev.height === height) { + return prev; + } + return { width, height }; + }); + } + }); + + observer.observe(node); + previousObserver.current = observer; + } + }, []); + + return [customRef, dimensions] as const; +} diff --git a/packages/search/src/search/hooks/use-search.ts b/packages/search/src/search/hooks/use-search.ts new file mode 100644 index 0000000..371af9c --- /dev/null +++ b/packages/search/src/search/hooks/use-search.ts @@ -0,0 +1,196 @@ +import { useCallback, useEffect, useMemo, useRef, useState } from "react"; +import type { Result } from "../lib/types"; + +export interface UseSearchConfig { + /** + * API endpoint path + * @default "/api/search" + */ + apiPath?: string; + + /** + * Debounce delay in milliseconds + * @default 300 + */ + debounceMs?: number; + + /** + * Maximum number of results to return + * @default 10 + */ + topK?: number; +} + +export interface UseSearchReturn { + /** Current search query */ + search: string; + + /** Set search query */ + setSearch: (query: string) => void; + + /** Search results */ + results: Result[]; + + /** Loading state */ + isLoading: boolean; + + /** Error state */ + error: string | null; + + /** Reset search state */ + reset: () => void; +} + +/** + * Custom hook for implementing search functionality with mixedbread vector store + * + * @param config - Configuration options for the search + * @returns Search state and handlers + * + * @example + * ```tsx + * const { search, setSearch, results, isLoading, error } = useSearch({ + * apiPath: '/api/search', + * debounceMs: 300, + * topK: 10 + * }); + * ``` + */ +export function useSearch(config: UseSearchConfig = {}): UseSearchReturn { + const { apiPath = "/api/search", debounceMs = 300, topK = 10 } = config; + + const [search, setSearch] = useState(""); + const [results, setResults] = useState([]); + const [isLoading, setIsLoading] = useState(false); + const [error, setError] = useState(null); + + const abortControllerRef = useRef(null); + const timeoutRef = useRef(null); + + const performSearch = useCallback( + async (query: string) => { + // Cancel previous request + if (abortControllerRef.current) { + abortControllerRef.current.abort(); + } + + // Clear previous timeout + if (timeoutRef.current) { + clearTimeout(timeoutRef.current); + } + + // Don't search for empty queries + if (query.length === 0) { + setResults([]); + setIsLoading(false); + setError(null); + return; + } + + setIsLoading(true); + setError(null); + + // Create new abort controller + const controller = new AbortController(); + abortControllerRef.current = controller; + + try { + const searchParams = new URLSearchParams({ + query, + topK: topK.toString(), + }); + + const response = await fetch(`${apiPath}?${searchParams}`, { + method: "GET", + signal: controller.signal, + headers: { + "Content-Type": "application/json", + }, + }); + + if (!response.ok) { + throw new Error( + `Search failed: ${response.status} ${response.statusText}` + ); + } + + const data = (await response.json()) as Result[]; + + // Validate results structure + if (!Array.isArray(data)) { + throw new Error("API response is not an array"); + } + + setResults(data); + } catch (err) { + // Don't set error for aborted requests + if (err instanceof Error && err.name === "AbortError") { + return; + } + + const errorMessage = + err instanceof Error ? err.message : "An unknown error occurred"; + setError(errorMessage); + setResults([]); + } finally { + setIsLoading(false); + } + }, + [apiPath, topK] + ); + + // Debounced search effect + useEffect(() => { + if (timeoutRef.current) { + clearTimeout(timeoutRef.current); + } + + timeoutRef.current = setTimeout(() => { + performSearch(search); + }, debounceMs); + + return () => { + if (timeoutRef.current) { + clearTimeout(timeoutRef.current); + } + }; + }, [search, performSearch, debounceMs]); + + // Cleanup on unmount + useEffect(() => { + return () => { + if (abortControllerRef.current) { + abortControllerRef.current.abort(); + } + if (timeoutRef.current) { + clearTimeout(timeoutRef.current); + } + }; + }, []); + + const reset = useCallback(() => { + setSearch(""); + setResults([]); + setError(null); + setIsLoading(false); + + if (abortControllerRef.current) { + abortControllerRef.current.abort(); + } + if (timeoutRef.current) { + clearTimeout(timeoutRef.current); + } + }, []); + + return useMemo( + () => ({ + search, + setSearch, + results, + isLoading, + error, + reset, + }), + [search, results, isLoading, error, reset] + ); +} diff --git a/packages/search/src/search/lib/errors.ts b/packages/search/src/search/lib/errors.ts new file mode 100644 index 0000000..ef49417 --- /dev/null +++ b/packages/search/src/search/lib/errors.ts @@ -0,0 +1,17 @@ +export class BadRequestError extends Error { + status = 400; + + constructor(message: string = "Bad request") { + super(message); + this.name = "BadRequestError"; + } +} + +export class InternalServerError extends Error { + status = 500; + + constructor(message: string = "Internal server error") { + super(message); + this.name = "InternalServerError"; + } +} diff --git a/packages/search/src/search/lib/fumadocs.ts b/packages/search/src/search/lib/fumadocs.ts new file mode 100644 index 0000000..c29201b --- /dev/null +++ b/packages/search/src/search/lib/fumadocs.ts @@ -0,0 +1,90 @@ +import type Mixedbread from "@mixedbread/sdk"; +import type { VectorStoreSearchResponse } from "@mixedbread/sdk/resources/vector-stores"; +import type { SearchMetadata } from "./types"; + +export interface MixedbreadOptions { + /** + * The ID of the vector store to search in + */ + vectorStoreId: string; + + /** + * The Mixedbread SDK client instance + */ + client: Mixedbread; + + /** + * Filter results with specific tag. + */ + tag?: string; + + /** + * Filter by locale (unsupported at the moment) + */ + locale?: string; +} + +interface SortedResult { + id: string; + type: "page" | "text" | "heading"; + content: string; + url: string; +} + +type VectorStoreSearchResult = VectorStoreSearchResponse["data"][number] & { + generated_metadata: SearchMetadata; +}; + +export async function search( + query: string, + options: MixedbreadOptions +): Promise { + const { client, vectorStoreId, tag } = options; + + if (!query.trim()) { + return []; + } + + const res = await client.vectorStores.search({ + query, + vector_store_ids: [vectorStoreId], + top_k: 10, + search_options: { + return_metadata: true, + }, + }); + + const results = (res.data as VectorStoreSearchResult[]) + .filter((item) => { + const metadata = item.generated_metadata; + return !tag || metadata.tag === tag; + }) + .flatMap((item) => { + const metadata = item.generated_metadata; + + const url = metadata.url || "#"; + const title = metadata.title || "Untitled"; + + const results: SortedResult[] = [ + { + id: `${item.file_id}-${item.chunk_index}-page`, + type: "page", + content: title, + url, + }, + ]; + + if (metadata.description) { + results.push({ + id: `${item.file_id}-${item.chunk_index}-text`, + type: "text", + content: metadata.description, + url, + }); + } + + return results; + }); + + return results; +} diff --git a/packages/search/src/search/lib/mxbai.ts b/packages/search/src/search/lib/mxbai.ts new file mode 100644 index 0000000..2bdf065 --- /dev/null +++ b/packages/search/src/search/lib/mxbai.ts @@ -0,0 +1,5 @@ +import Mixedbread from "@mixedbread/sdk"; + +export const mxbai = new Mixedbread({ + apiKey: process.env.MXBAI_API_KEY ?? "", +}); diff --git a/packages/search/src/search/lib/search.ts b/packages/search/src/search/lib/search.ts new file mode 100644 index 0000000..35ac009 --- /dev/null +++ b/packages/search/src/search/lib/search.ts @@ -0,0 +1,51 @@ +import { BadRequestError, InternalServerError } from "./errors"; +import { mxbai } from "./mxbai"; +import type { Result, SearchMetadata, TransformFunc } from "./types"; +import { SearchQuerySchema } from "./validations"; + +export async function search( + rawParams: Record, + transform?: TransformFunc +): Promise { + if (!process.env.MXBAI_API_KEY || !process.env.VECTOR_STORE_ID) { + throw new InternalServerError("Environment setup failed"); + } + + // Validate parameters + const validation = SearchQuerySchema.safeParse(rawParams); + + if (!validation.success) { + throw new BadRequestError("Invalid request parameters"); + } + + const data = validation.data; + + const { query, topK } = data; + + const res = await mxbai.vectorStores.files.search({ + query, + vector_store_ids: [process.env.VECTOR_STORE_ID], + top_k: topK, + search_options: { + return_metadata: true, + return_chunks: true, + }, + }); + + if (transform) { + return transform(res.data); + } + + const results = res.data.map((item) => { + const metadata = item.metadata as SearchMetadata; + return { + id: item.id, + url: metadata?.url || "#", + title: metadata?.title || "Untitled", + tag: metadata?.tag || "all", + breadcrumb: metadata?.breadcrumb || [], + }; + }); + + return results; +} diff --git a/packages/search/src/search/lib/types.ts b/packages/search/src/search/lib/types.ts new file mode 100644 index 0000000..7a1b747 --- /dev/null +++ b/packages/search/src/search/lib/types.ts @@ -0,0 +1,53 @@ +import type { FileSearchResponse } from "@mixedbread/sdk/resources/vector-stores.mjs"; +import type { z } from "zod"; +import type { SearchQuerySchema } from "./validations"; + +export interface SearchMetadata { + title?: string; + description?: string; + url?: string; + tag?: string; + breadcrumb?: string[]; +} + +export interface Result { + id: string; + url: string; + title: string; + tag: string; + breadcrumb: string[]; + external?: boolean; +} + +export type SearchQuery = z.infer; + +export type TransformFunc = (results: FileSearchResponse["data"]) => Result[]; + +export type Message = + | { + status: "completed"; + id: string; + role: "user" | "assistant" | "system"; + content: string; + createdAt: Date; + } + | { + status: "pending"; + id: string; + role: "assistant"; + content: string; + }; + +export interface Thread { + id: string; + messages: Message[]; + isLoading?: boolean; + error?: Error; +} + +export interface ComposerState { + value: string; + isSubmitting: boolean; +} + +export type SendMessageFunc = (content: string) => Promise; diff --git a/packages/search/src/search/lib/utils.ts b/packages/search/src/search/lib/utils.ts new file mode 100644 index 0000000..9104233 --- /dev/null +++ b/packages/search/src/search/lib/utils.ts @@ -0,0 +1,7 @@ +export function getThreadScrollArea() { + const threadViewport = document.querySelector("[data-thread-viewport]"); + const threadScrollArea = threadViewport?.querySelector( + "[data-radix-scroll-area-viewport]" + ); + return threadScrollArea; +} diff --git a/packages/search/src/search/lib/validations.ts b/packages/search/src/search/lib/validations.ts new file mode 100644 index 0000000..1d97302 --- /dev/null +++ b/packages/search/src/search/lib/validations.ts @@ -0,0 +1,6 @@ +import { z } from "zod"; + +export const SearchQuerySchema = z.object({ + query: z.string().min(1, "Query is required").trim(), + topK: z.coerce.number().int().min(1).max(50).default(10), +}); diff --git a/packages/search/src/search/ui/composer.tsx b/packages/search/src/search/ui/composer.tsx new file mode 100644 index 0000000..4631df7 --- /dev/null +++ b/packages/search/src/search/ui/composer.tsx @@ -0,0 +1,246 @@ +import { ArrowUpIcon, LoaderCircleIcon } from "lucide-react"; +import { + type ComponentProps, + createContext, + useCallback, + useContext, + useMemo, + useRef, + useState, +} from "react"; +import { cn } from "@/lib/utils"; +import type { ComposerState, SendMessageFunc } from "../lib/types"; +import { useThread } from "./thread"; + +interface ComposerContextProps { + state: ComposerState; + setState: (value: string) => void; + submit: (value?: string) => Promise; + canSubmit: boolean; +} + +const ComposerContext = createContext(null); + +export type ComposerProps = Omit, "onSubmit"> & { + onSubmit: SendMessageFunc; +}; + +export function Composer({ + onSubmit, + className, + children, + ...props +}: ComposerProps) { + const [state, setState] = useState({ + value: "", + isSubmitting: false, + }); + + const setValue = useCallback((value: string) => { + setState((prev) => ({ ...prev, value })); + }, []); + + const submit = useCallback( + async (value?: string) => { + const submittedValue = value || state.value; + if (!submittedValue.trim() || state.isSubmitting) return; + + setState((prev) => ({ ...prev, isSubmitting: true })); + try { + await onSubmit(submittedValue); + setState({ value: "", isSubmitting: false }); + } catch { + setState((prev) => ({ ...prev, isSubmitting: false })); + } + }, + [state.value, state.isSubmitting, onSubmit] + ); + + const canSubmit = state.value.trim().length > 0 && !state.isSubmitting; + + const memoizedValue = useMemo( + () => ({ state, setState: setValue, submit, canSubmit }), + [state, setValue, submit, canSubmit] + ); + + return ( + +
+ {children} +
+
+ ); +} + +export type ComposerFormProps = ComponentProps<"form">; + +export function ComposerForm({ + className, + children, + ...props +}: ComposerFormProps) { + const { submit } = useComposer(); + + return ( +
submit()} + {...props} + > + {children} +
+ ); +} + +export type ComposerSuggestionsProps = ComponentProps<"div">; + +export function ComposerSuggestions({ + className, + children, + ...props +}: ComposerSuggestionsProps) { + return ( +
+ {children} +
+ ); +} + +export type ComposerSuggestionItemProps = ComponentProps<"button"> & { + value: string; +}; + +export function ComposerSuggestionItem({ + className, + value, + children, + ...props +}: ComposerSuggestionItemProps) { + const { sendMessage } = useThread(); + + return ( + + ); +} + +export type ComposerInputProps = Omit< + ComponentProps<"textarea">, + "value" | "onChange" +>; + +export function ComposerInput({ + className, + onKeyDown, + placeholder = "Ask a question...", + ...props +}: ComposerInputProps) { + const { state, setState, submit, canSubmit } = useComposer(); + const textareaRef = useRef(null); + + const handleKeyDown = useCallback( + (e: React.KeyboardEvent) => { + if (e.key === "Enter" && !e.shiftKey) { + e.preventDefault(); + if (canSubmit) { + submit().then(() => { + textareaRef.current?.focus(); + }); + } + } + onKeyDown?.(e); + }, + [canSubmit, submit, onKeyDown] + ); + + return ( +