Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

Add dashboard search and integrate into navbar

Richie McIlroyad89cf3116e0
diff --git a/apps/web/app/(org)/dashboard/_components/Navbar/DashboardSearch.tsx b/apps/web/app/(org)/dashboard/_components/Navbar/DashboardSearch.tsx
new file mode 100644
index 000000000..bf8cee828
--- /dev/null
+++ b/apps/web/app/(org)/dashboard/_components/Navbar/DashboardSearch.tsx
@@ -0,0 +1,546 @@
+"use client";
+
+import {
+ Command,
+ CommandInput,
+ CommandItem,
+ CommandList,
+ Dialog,
+ DialogContent,
+ DialogTitle,
+} from "@cap/ui";
+import { useDetectPlatform } from "hooks/useDetectPlatform";
+import {
+ BarChart3,
+ Bell,
+ Building2,
+ CreditCard,
+ FileVideo,
+ FolderSearch,
+ Image,
+ Layers3,
+ Loader2,
+ type LucideIcon,
+ Radio,
+ Search,
+ Settings,
+ Sparkles,
+ Upload,
+ UserRound,
+ UsersRound,
+} from "lucide-react";
+import { useRouter } from "next/navigation";
+import { type ReactNode, useEffect, useMemo, useRef, useState } from "react";
+import {
+ canViewOrganizationSettings,
+ getEffectiveOrganizationRole,
+} from "@/lib/permissions/roles";
+import { useDashboardContext } from "../../Contexts";
+import type { Spaces } from "../../dashboard-data";
+import {
+ type DashboardVideoSearchResult,
+ searchDashboardVideos,
+} from "./search";
+
+const MAX_LOCAL_RESULTS = 6;
+const MAX_SPACE_RESULTS = 5;
+const MAX_VIDEO_CACHE_SIZE = 25;
+const MAX_SEARCH_QUERY_LENGTH = 80;
+const VIDEO_SEARCH_DEBOUNCE_MS = 180;
+const MIN_VIDEO_QUERY_LENGTH = 2;
+
+const videoDateFormatter = new Intl.DateTimeFormat("en", {
+ month: "short",
+ day: "numeric",
+ year: "numeric",
+});
+
+type SearchItem = {
+ id: string;
+ title: string;
+ subtitle: string;
+ href: string;
+ value: string;
+ icon: LucideIcon;
+ badge?: string;
+};
+
+const normalizeQuery = (query: string) =>
+ query.trim().replace(/\s+/g, " ").toLowerCase();
+
+const matchesQuery = (item: SearchItem, query: string) =>
+ item.value.toLowerCase().includes(query);
+
+const filterItems = (items: SearchItem[], query: string, limit: number) =>
+ (query ? items.filter((item) => matchesQuery(item, query)) : items).slice(
+ 0,
+ limit,
+ );
+
+const formatDuration = (duration: number | null) => {
+ if (!duration || duration <= 0) return null;
+ const totalSeconds = Math.round(duration);
+ const minutes = Math.floor(totalSeconds / 60);
+ const seconds = totalSeconds % 60;
+
+ if (minutes < 60) return `${minutes}:${seconds.toString().padStart(2, "0")}`;
+
+ const hours = Math.floor(minutes / 60);
+ const remainingMinutes = minutes % 60;
+ return `${hours}:${remainingMinutes.toString().padStart(2, "0")}:${seconds
+ .toString()
+ .padStart(2, "0")}`;
+};
+
+const formatVideoSubtitle = (video: DashboardVideoSearchResult) => {
+ const parts = [
+ video.isScreenshot ? "Screenshot" : "Video",
+ video.ownerName ? `by ${video.ownerName}` : null,
+ videoDateFormatter.format(new Date(video.createdAt)),
+ formatDuration(video.duration),
+ ].filter((part): part is string => Boolean(part));
+
+ return parts.join(" · ");
+};
+
+const createSpaceItem = (space: Spaces): SearchItem => ({
+ id: `space-${space.id}`,
+ title: space.name,
+ subtitle: `${space.videoCount} ${
+ space.videoCount === 1 ? "video" : "videos"
+ } · ${space.memberCount} ${space.memberCount === 1 ? "member" : "members"}`,
+ href: `/dashboard/spaces/${space.id}`,
+ value: `${space.name} ${space.description ?? ""} ${space.privacy} space`,
+ icon: space.primary ? Building2 : Layers3,
+ badge: space.primary ? "Org" : space.privacy,
+});
+
+export function DashboardSearch({
+ shortcutEnabled = true,
+}: {
+ shortcutEnabled?: boolean;
+} = {}) {
+ const router = useRouter();
+ const { activeOrganization, spacesData, user } = useDashboardContext();
+ const { platform } = useDetectPlatform();
+ const [open, setOpen] = useState(false);
+ const [query, setQuery] = useState("");
+ const [videoResults, setVideoResults] = useState<
+ DashboardVideoSearchResult[]
+ >([]);
+ const [videoLoading, setVideoLoading] = useState(false);
+ const inputRef = useRef<HTMLInputElement>(null);
+ const requestIdRef = useRef(0);
+ const videoCacheRef = useRef(new Map<string, DashboardVideoSearchResult[]>());
+ const shortcutKey = platform === "macos" ? "⌘K" : "Ctrl K";
+
+ const currentMember = activeOrganization?.members.find(
+ (member) => member.userId === user.id,
+ );
+ const currentRole = getEffectiveOrganizationRole({
+ userId: user.id,
+ ownerId: activeOrganization?.organization.ownerId,
+ memberRole: currentMember?.role,
+ });
+ const canViewSettings = canViewOrganizationSettings(currentRole);
+ const normalizedQuery = normalizeQuery(query);
+ const canSearchVideos = normalizedQuery.length >= MIN_VIDEO_QUERY_LENGTH;
+
+ const quickActions = useMemo<SearchItem[]>(
+ () => [
+ {
+ id: "my-caps",
+ title: "My Caps",
+ subtitle: "Open your video library",
+ href: "/dashboard/caps",
+ value: "my caps videos recordings library",
+ icon: FileVideo,
+ },
+ {
+ id: "record-cap",
+ title: "Record a Cap",
+ subtitle: "Start a new browser recording",
+ href: "/dashboard/caps/record",
+ value: "record cap screen video browser recorder",
+ icon: Radio,
+ },
+ {
+ id: "import-video",
+ title: "Import Video",
+ subtitle: "Bring an existing video into Cap",
+ href: "/dashboard/import",
+ value: "import upload loom video file",
+ icon: Upload,
+ },
+ {
+ id: "analytics",
+ title: "Analytics",
+ subtitle: "Review views and engagement",
+ href: "/dashboard/analytics",
+ value: "analytics stats views engagement",
+ icon: BarChart3,
+ },
+ {
+ id: "browse-spaces",
+ title: "Browse Spaces",
+ subtitle: "Find shared organization spaces",
+ href: "/dashboard/spaces/browse",
+ value: "browse spaces shared organization",
+ icon: FolderSearch,
+ },
+ ],
+ [],
+ );
+
+ const settingsItems = useMemo<SearchItem[]>(
+ () => [
+ {
+ id: "account-settings",
+ title: "Account Settings",
+ subtitle: "Profile, avatar, and personal details",
+ href: "/dashboard/settings/account",
+ value: "account settings profile avatar name personal",
+ icon: UserRound,
+ },
+ {
+ id: "notification-settings",
+ title: "Notification Settings",
+ subtitle: "Comments, views, replies, and reactions",
+ href: "/dashboard/settings/notifications",
+ value: "notification settings comments views replies reactions",
+ icon: Bell,
+ },
+ ...(canViewSettings
+ ? [
+ {
+ id: "organization-settings",
+ title: "Organization Settings",
+ subtitle: "General organization configuration",
+ href: "/dashboard/settings/organization",
+ value: "organization settings general workspace",
+ icon: Settings,
+ },
+ {
+ id: "organization-members",
+ title: "Organization Members",
+ subtitle: "Invite and manage teammates",
+ href: "/dashboard/settings/organization/members",
+ value: "organization members invites teammates seats",
+ icon: UsersRound,
+ },
+ {
+ id: "organization-billing",
+ title: "Billing",
+ subtitle: "Subscription, seats, and invoices",
+ href: "/dashboard/settings/organization/billing",
+ value: "billing subscription seats invoices organization",
+ icon: CreditCard,
+ },
+ {
+ id: "organization-preferences",
+ title: "Cap Settings",
+ subtitle: "Default summaries, captions, and viewer options",
+ href: "/dashboard/settings/organization/preferences",
+ value:
+ "cap settings preferences summaries captions chapters comments reactions transcript",
+ icon: Sparkles,
+ },
+ ]
+ : []),
+ ],
+ [canViewSettings],
+ );
+
+ const spaceItems = useMemo(
+ () => (spacesData ?? []).map(createSpaceItem),
+ [spacesData],
+ );
+
+ const actionResults = useMemo(
+ () => filterItems(quickActions, normalizedQuery, MAX_LOCAL_RESULTS),
+ [quickActions, normalizedQuery],
+ );
+ const spaceResults = useMemo(
+ () => filterItems(spaceItems, normalizedQuery, MAX_SPACE_RESULTS),
+ [spaceItems, normalizedQuery],
+ );
+ const settingsResults = useMemo(
+ () => filterItems(settingsItems, normalizedQuery, MAX_LOCAL_RESULTS),
+ [settingsItems, normalizedQuery],
+ );
+ const updateQuery = (value: string) => {
+ setQuery(value.slice(0, MAX_SEARCH_QUERY_LENGTH));
+ };
+
+ useEffect(() => {
+ if (!shortcutEnabled) return;
+
+ const handleKeyDown = (event: KeyboardEvent) => {
+ if (event.key.toLowerCase() === "k" && (event.metaKey || event.ctrlKey)) {
+ event.preventDefault();
+ setOpen((value) => !value);
+ }
+ };
+
+ window.addEventListener("keydown", handleKeyDown);
+ return () => window.removeEventListener("keydown", handleKeyDown);
+ }, [shortcutEnabled]);
+
+ useEffect(() => {
+ if (!open) return;
+ const animationFrame = window.requestAnimationFrame(() =>
+ inputRef.current?.focus(),
+ );
+
+ return () => window.cancelAnimationFrame(animationFrame);
+ }, [open]);
+
+ useEffect(() => {
+ if (!open || !canSearchVideos) {
+ requestIdRef.current += 1;
+ setVideoResults([]);
+ setVideoLoading(false);
+ return;
+ }
+
+ const cachedResults = videoCacheRef.current.get(normalizedQuery);
+ if (cachedResults) {
+ requestIdRef.current += 1;
+ setVideoResults(cachedResults);
+ setVideoLoading(false);
+ return;
+ }
+
+ const requestId = requestIdRef.current + 1;
+ requestIdRef.current = requestId;
+ setVideoLoading(true);
+
+ const timeout = window.setTimeout(() => {
+ searchDashboardVideos(normalizedQuery)
+ .then((results) => {
+ if (requestIdRef.current !== requestId) return;
+
+ videoCacheRef.current.set(normalizedQuery, results);
+ if (videoCacheRef.current.size > MAX_VIDEO_CACHE_SIZE) {
+ const firstKey = videoCacheRef.current.keys().next().value;
+ if (firstKey) videoCacheRef.current.delete(firstKey);
+ }
+ setVideoResults(results);
+ })
+ .catch(() => {
+ if (requestIdRef.current !== requestId) return;
+ setVideoResults([]);
+ })
+ .finally(() => {
+ if (requestIdRef.current === requestId) setVideoLoading(false);
+ });
+ }, VIDEO_SEARCH_DEBOUNCE_MS);
+
+ return () => {
+ requestIdRef.current += 1;
+ window.clearTimeout(timeout);
+ };
+ }, [canSearchVideos, normalizedQuery, open]);
+
+ const navigateTo = (href: string) => {
+ setOpen(false);
+ setQuery("");
+ router.push(href);
+ };
+
+ const hasLocalResults =
+ actionResults.length > 0 ||
+ spaceResults.length > 0 ||
+ settingsResults.length > 0;
+ const hasVideoResults = videoResults.length > 0;
+
+ return (
+ <>
+ <button
+ type="button"
+ onClick={() => setOpen(true)}
+ className="flex group gap-2.5 items-center px-3.5 w-full max-w-[720px] h-10 rounded-xl border transition-colors duration-200 bg-gray-3 border-gray-4 hover:bg-gray-4 hover:border-gray-5 focus:outline-none focus-visible:ring-2 focus-visible:ring-gray-6"
+ aria-label="Search dashboard"
+ >
+ <Search className="flex-shrink-0 size-4 transition-colors text-gray-10 group-hover:text-gray-11" />
+ <span className="flex-1 text-[13px] text-left truncate text-gray-10">
+ Search caps, spaces, settings…
+ </span>
+ <kbd className="hidden items-center px-1.5 h-5 text-[11px] font-medium rounded-md border select-none sm:inline-flex text-gray-10 border-gray-4 bg-gray-1">
+ {shortcutKey}
+ </kbd>
+ </button>
+ <Dialog open={open} onOpenChange={setOpen}>
+ <DialogContent
+ aria-describedby={undefined}
+ className="overflow-hidden p-0 w-[calc(100vw-2rem)] !max-w-2xl shadow-2xl outline-none"
+ >
+ <DialogTitle className="sr-only">Search the dashboard</DialogTitle>
+ <Command shouldFilter={false}>
+ <CommandInput
+ ref={inputRef}
+ value={query}
+ onValueChange={updateQuery}
+ placeholder="Search caps, spaces, settings…"
+ className="h-[52px] text-[15px] pr-12 outline-none"
+ />
+ <CommandList className="overflow-y-auto px-2 pt-1 pb-2 h-[min(60vh,440px)] max-h-[min(60vh,440px)]">
+ {canSearchVideos && (
+ <>
+ <SectionHeader>Videos</SectionHeader>
+ {videoLoading ? (
+ <div className="flex gap-3 items-center px-2.5 py-2 text-[13px] text-gray-10">
+ <Loader2 className="flex-shrink-0 animate-spin size-4" />
+ Searching videos…
+ </div>
+ ) : hasVideoResults ? (
+ videoResults.map((video) => (
+ <ResultRow
+ key={video.id}
+ icon={video.isScreenshot ? Image : FileVideo}
+ title={video.name}
+ subtitle={formatVideoSubtitle(video)}
+ value={`${video.name} ${video.ownerName ?? ""}`}
+ onSelect={() => navigateTo(`/s/${video.id}`)}
+ />
+ ))
+ ) : (
+ <p className="px-3 py-6 text-[13px] text-center text-gray-10">
+ No videos match{" "}
+ <span className="font-medium text-gray-12">
+ “{query.trim()}”
+ </span>
+ </p>
+ )}
+ </>
+ )}
+ {actionResults.length > 0 && (
+ <>
+ <SectionHeader>
+ {normalizedQuery ? "Navigation" : "Jump to"}
+ </SectionHeader>
+ {actionResults.map((item) => (
+ <ResultRow
+ key={item.id}
+ icon={item.icon}
+ title={item.title}
+ subtitle={item.subtitle}
+ value={item.value}
+ onSelect={() => navigateTo(item.href)}
+ />
+ ))}
+ </>
+ )}
+ {spaceResults.length > 0 && (
+ <>
+ <SectionHeader>Spaces</SectionHeader>
+ {spaceResults.map((item) => (
+ <ResultRow
+ key={item.id}
+ icon={item.icon}
+ title={item.title}
+ subtitle={item.subtitle}
+ badge={item.badge}
+ value={item.value}
+ onSelect={() => navigateTo(item.href)}
+ />
+ ))}
+ </>
+ )}
+ {settingsResults.length > 0 && (
+ <>
+ <SectionHeader>Settings</SectionHeader>
+ {settingsResults.map((item) => (
+ <ResultRow
+ key={item.id}
+ icon={item.icon}
+ title={item.title}
+ subtitle={item.subtitle}
+ value={item.value}
+ onSelect={() => navigateTo(item.href)}
+ />
+ ))}
+ </>
+ )}
+ {normalizedQuery && !canSearchVideos && !hasLocalResults && (
+ <p className="px-3 py-6 text-[13px] text-center text-gray-10">
+ Keep typing to search videos…
+ </p>
+ )}
+ </CommandList>
+ <div className="hidden gap-4 justify-end items-center px-3 h-10 border-t sm:flex border-gray-4 bg-gray-2">
+ <FooterHint keys={["↑", "↓"]} label="Navigate" />
+ <FooterHint keys={["↵"]} label="Open" />
+ <FooterHint keys={["esc"]} label="Close" />
+ </div>
+ </Command>
+ </DialogContent>
+ </Dialog>
+ </>
+ );
+}
+
+function SectionHeader({ children }: { children: ReactNode }) {
+ return (
+ <div className="px-2.5 pt-3 pb-1 text-[11px] font-medium text-gray-9">
+ {children}
+ </div>
+ );
+}
+
+function ResultRow({
+ icon: Icon,
+ title,
+ subtitle,
+ badge,
+ value,
+ onSelect,
+}: {
+ icon: LucideIcon;
+ title: string;
+ subtitle?: string;
+ badge?: string;
+ value: string;
+ onSelect: () => void;
+}) {
+ return (
+ <CommandItem
+ value={value}
+ onSelect={onSelect}
+ className="flex gap-3 items-center px-2.5 py-2 rounded-lg transition-colors cursor-pointer text-gray-12 aria-selected:bg-gray-3 data-[selected=true]:bg-gray-3"
+ >
+ <Icon className="flex-shrink-0 size-[18px] text-gray-10" />
+ <div className="flex flex-col flex-1 min-w-0">
+ <span className="text-[13px] font-medium truncate text-gray-12">
+ {title}
+ </span>
+ {subtitle && (
+ <span className="text-[11px] truncate text-gray-10">{subtitle}</span>
+ )}
+ </div>
+ {badge && (
+ <span className="flex-shrink-0 text-[10px] font-medium tracking-wide uppercase text-gray-9">
+ {badge}
+ </span>
+ )}
+ </CommandItem>
+ );
+}
+
+function FooterHint({ keys, label }: { keys: string[]; label: string }) {
+ return (
+ <span className="flex gap-1.5 items-center text-[11px] text-gray-10">
+ <span className="flex gap-1 items-center">
+ {keys.map((key) => (
+ <kbd
+ key={key}
+ className="inline-flex justify-center items-center px-1 h-5 text-[10px] font-medium rounded-[5px] border min-w-[20px] border-gray-4 bg-gray-1 text-gray-10"
+ >
+ {key}
+ </kbd>
+ ))}
+ </span>
+ {label}
+ </span>
+ );
+}
diff --git a/apps/web/app/(org)/dashboard/_components/Navbar/Mobile.tsx b/apps/web/app/(org)/dashboard/_components/Navbar/Mobile.tsx
index b996e13ea..2e2f5213e 100644
--- a/apps/web/app/(org)/dashboard/_components/Navbar/Mobile.tsx
+++ b/apps/web/app/(org)/dashboard/_components/Navbar/Mobile.tsx
@@ -7,8 +7,7 @@ import { X } from "lucide-react";
import Link from "next/link";
import { type MutableRefObject, useState } from "react";
-import { ThemeToggleIcon } from "@/components/theme-toggle-icon";
-import { useTheme } from "../../Contexts";
+import { DashboardSearch } from "./DashboardSearch";
import NavItems from "./Items";
export const AdminMobileNav = () => {
@@ -16,7 +15,7 @@ export const AdminMobileNav = () => {
const sidebarRef: MutableRefObject<HTMLDivElement> = useClickAway(() =>
setSidebarOpen(false),
);
- const { theme, setThemeHandler } = useTheme();
+
return (
<>
<AnimatePresence>
@@ -37,31 +36,28 @@ export const AdminMobileNav = () => {
exit={{ x: "100%" }}
className="relative flex-1 flex flex-col ml-auto max-w-xs w-[275px] border-l border-gray-3 pt-5 pb-4 px-4 bg-gray-2"
>
- <div
- className="flex justify-end items-center mb-6 w-full rounded-full"
- onClick={() => setSidebarOpen(false)}
- >
- <X className="text-gray-12 size-7" aria-hidden="true" />
+ <div className="flex justify-end items-center mb-6 w-full rounded-full">
+ <button
+ type="button"
+ aria-label="Close navigation menu"
+ onClick={() => setSidebarOpen(false)}
+ className="flex justify-center items-center rounded-full"
+ >
+ <X className="text-gray-12 size-7" aria-hidden="true" />
+ </button>
</div>
<NavItems toggleMobileNav={() => setSidebarOpen(false)} />
</motion.div>
</motion.div>
) : null}
</AnimatePresence>
- <div className="flex fixed z-[51] justify-between w-full h-16 border-b border-gray-3 bg-gray-1 lg:border-none lg:hidden">
- <div className="flex flex-shrink-0 items-center px-4 h-full lg:hidden">
- <Link className="block" href="/dashboard">
+ <div className="flex fixed z-[51] w-full h-16 border-b border-gray-3 bg-gray-1 lg:border-none lg:hidden">
+ <div className="flex gap-3 items-center px-4 w-full h-full">
+ <Link className="block flex-shrink-0" href="/dashboard">
<LogoBadge className="block w-auto h-8" />
</Link>
- </div>
- <div className="flex gap-4 items-center px-4 h-full">
- <div
- onClick={() => {
- setThemeHandler(theme === "light" ? "dark" : "light");
- }}
- className="flex justify-center items-center rounded-full border transition-colors cursor-pointer lg:hidden bg-gray-4 hover:border-gray-6 hover:bg-gray-5 size-9 border-gray-5"
- >
- <ThemeToggleIcon />
+ <div className="flex-1 min-w-0">
+ <DashboardSearch shortcutEnabled={false} />
</div>
</div>
</div>
diff --git a/apps/web/app/(org)/dashboard/_components/Navbar/Top.tsx b/apps/web/app/(org)/dashboard/_components/Navbar/Top.tsx
index bfe549d8a..32aef8f64 100644
--- a/apps/web/app/(org)/dashboard/_components/Navbar/Top.tsx
+++ b/apps/web/app/(org)/dashboard/_components/Navbar/Top.tsx
@@ -15,15 +15,17 @@ import { useMutation, useQueryClient } from "@tanstack/react-query";
import { useClickAway } from "@uidotdev/usehooks";
import clsx from "clsx";
import { AnimatePresence } from "framer-motion";
-import { MoreVertical } from "lucide-react";
+import { Moon, MoreVertical, Sun } from "lucide-react";
import Link from "next/link";
import { useParams, usePathname } from "next/navigation";
import { signOut } from "next-auth/react";
import {
cloneElement,
+ forwardRef,
type MutableRefObject,
memo,
type RefObject,
+ useImperativeHandle,
useMemo,
useRef,
useState,
@@ -31,7 +33,6 @@ import {
import { markAsRead } from "@/actions/notifications/mark-as-read";
import Notifications from "@/app/(org)/dashboard/_components/Notifications";
import { SignedImageUrl } from "@/components/SignedImageUrl";
-import { ThemeToggleIcon } from "@/components/theme-toggle-icon";
import { UpgradeModal } from "@/components/UpgradeModal";
import { useDashboardContext, useTheme } from "../../Contexts";
import {
@@ -45,13 +46,12 @@ import {
} from "../AnimatedIcons";
import type { DownloadIconHandle } from "../AnimatedIcons/Download";
import type { ReferIconHandle } from "../AnimatedIcons/Refer";
+import { DashboardSearch } from "./DashboardSearch";
const Top = () => {
- const { activeSpace, anyNewNotifications, isDeveloperSection } =
- useDashboardContext();
+ const { activeSpace, anyNewNotifications } = useDashboardContext();
const [toggleNotifications, setToggleNotifications] = useState(false);
- const bellRef = useRef<HTMLDivElement>(null);
- const { theme, setThemeHandler } = useTheme();
+ const bellRef = useRef<HTMLButtonElement>(null);
const queryClient = useQueryClient();
const pathname = usePathname();
@@ -108,7 +108,7 @@ const Top = () => {
"top-0 bg-gray-1",
)}
>
- <div className="flex flex-col gap-0.5">
+ <div className="flex flex-col gap-0.5 min-w-0 shrink">
{activeSpace && <span className="text-xs text-gray-11">Space</span>}
<div className="flex gap-1.5 items-center">
{activeSpace && (
@@ -124,47 +124,42 @@ const Top = () => {
</p>
</div>
</div>
- <div className="flex gap-4 items-center">
+ <div className="hidden flex-1 justify-start px-6 min-w-0 lg:flex">
+ <DashboardSearch />
+ </div>
+ <div className="flex gap-4 justify-end items-center shrink-0">
{buildEnv.NEXT_PUBLIC_IS_CAP && <ReferButton />}
- <div
- data-state={toggleNotifications ? "open" : "closed"}
- ref={bellRef}
- onClick={() => {
- if (anyNewNotifications) {
- markAllAsread.mutate();
- }
- setToggleNotifications(!toggleNotifications);
- }}
- onKeyDown={(e) => {
- if (e.key === "Enter" || e.key === " ") {
- e.preventDefault();
+ <div className="hidden relative lg:flex">
+ <button
+ type="button"
+ data-state={toggleNotifications ? "open" : "closed"}
+ ref={bellRef}
+ onClick={() => {
if (anyNewNotifications) {
markAllAsread.mutate();
}
setToggleNotifications(!toggleNotifications);
- }
- }}
- tabIndex={0}
- role="button"
- aria-label={`Notifications${
- anyNewNotifications ? " (new notifications available)" : ""
- }`}
- aria-expanded={toggleNotifications}
- className="hidden relative justify-center data-[state=open]:hover:bg-gray-5 items-center bg-gray-3
+ }}
+ aria-label={`Notifications${
+ anyNewNotifications ? " (new notifications available)" : ""
+ }`}
+ aria-expanded={toggleNotifications}
+ className="relative justify-center data-[state=open]:hover:bg-gray-5 items-center bg-gray-3
rounded-full transition-colors cursor-pointer lg:flex
hover:bg-gray-5 data-[state=open]:bg-gray-5
focus:outline-none
size-9"
- >
- {anyNewNotifications && (
- <div className="absolute right-0 top-1 z-10">
- <div className="relative">
- <div className="absolute inset-0 w-2 h-2 bg-red-400 rounded-full opacity-75 animate-ping" />
- <div className="relative w-2 h-2 bg-red-400 rounded-full" />
+ >
+ {anyNewNotifications && (
+ <div className="absolute right-0 top-1 z-10">
+ <div className="relative">
+ <div className="absolute inset-0 w-2 h-2 bg-red-400 rounded-full opacity-75 animate-ping" />
+ <div className="relative w-2 h-2 bg-red-400 rounded-full" />
+ </div>
</div>
- </div>
- )}
- <FontAwesomeIcon className="text-gray-12 size-3.5" icon={faBell} />
+ )}
+ <FontAwesomeIcon className="text-gray-12 size-3.5" icon={faBell} />
+ </button>
<AnimatePresence>
{toggleNotifications && (
<Notifications
@@ -174,22 +169,6 @@ const Top = () => {
)}
</AnimatePresence>
</div>
- {!isDeveloperSection && (
- <div
- onClick={() => {
- if (document.startViewTransition) {
- document.startViewTransition(() => {
- setThemeHandler(theme === "light" ? "dark" : "light");
- });
- } else {
- setThemeHandler(theme === "light" ? "dark" : "light");
- }
- }}
- className="hidden justify-center items-center rounded-full transition-colors cursor-pointer bg-gray-3 lg:flex hover:bg-gray-5 size-9"
- >
- <ThemeToggleIcon />
- </div>
- )}
<User />
</div>
</div>
@@ -200,6 +179,10 @@ const User = () => {
const [menuOpen, setMenuOpen] = useState(false);
const [upgradeModalOpen, setUpgradeModalOpen] = useState(false);
const { user } = useDashboardContext();
+ const { theme, setThemeHandler } = useTheme();
+ const nextTheme = theme === "light" ? "dark" : "light";
+ const themeLabel =
+ theme === "light" ? "Toggle Dark Mode" : "Toggle Light Mode";
const menuItems = useMemo(
() => [
@@ -229,14 +212,6 @@ const User = () => {
iconClassName: "text-gray-11 group-hover:text-gray-12",
showCondition: buildEnv.NEXT_PUBLIC_IS_CAP,
},
- {
- name: "Settings",
- icon: <SettingsGearIcon />,
- href: "/dashboard/settings/account",
- onClick: () => setMenuOpen(false),
- iconClassName: "text-gray-11 group-hover:text-gray-12",
- showCondition: true,
- },
{
name: "Chat Support",
icon: <MessageCircleMoreIcon />,
@@ -254,12 +229,39 @@ const User = () => {
{
name: "Sign Out",
icon: <LogoutIcon />,
- onClick: () => signOut(),
+ onClick: () => {
+ setMenuOpen(false);
+ signOut();
+ },
+ iconClassName: "text-gray-11 group-hover:text-gray-12",
+ showCondition: true,
+ },
+ {
+ name: "Settings",
+ icon: <SettingsGearIcon />,
+ href: "/dashboard/settings/account",
+ onClick: () => setMenuOpen(false),
+ iconClassName: "text-gray-11 group-hover:text-gray-12",
+ showCondition: true,
+ },
+ {
+ name: themeLabel,
+ icon: <ThemeMenuIcon />,
+ onClick: () => {
+ setMenuOpen(false);
+ if (document.startViewTransition) {
+ document.startViewTransition(() => {
+ setThemeHandler(nextTheme);
+ });
+ } else {
+ setThemeHandler(nextTheme);
+ }
+ },
iconClassName: "text-gray-11 group-hover:text-gray-12",
showCondition: true,
},
],
- [user.isPro],
+ [nextTheme, setThemeHandler, themeLabel, user.isPro],
);
return (
@@ -301,7 +303,7 @@ const User = () => {
key={index.toString()}
icon={item.icon}
name={item.name}
- href={item.href ?? "#"}
+ href={"href" in item ? item.href : undefined}
onClick={item.onClick}
iconClassName={item.iconClassName}
/>
@@ -328,6 +330,19 @@ interface Props {
const MenuItem = memo(({ icon, name, href, onClick, iconClassName }: Props) => {
const iconRef = useRef<DownloadIconHandle>(null);
+ const content = (
+ <>
+ <div className="flex flex-shrink-0 justify-center items-center w-3.5 h-3.5">
+ {cloneElement(icon, {
+ ref: iconRef,
+ className: iconClassName,
+ size: 14,
+ })}
+ </div>
+ <p className={clsx("text-sm text-gray-12")}>{name}</p>
+ </>
+ );
+
return (
<CommandItem
key={name}
@@ -340,32 +355,58 @@ const MenuItem = memo(({ icon, name, href, onClick, iconClassName }: Props) => {
iconRef.current?.stopAnimation();
}}
>
- <Link
- className="flex gap-2 items-center w-full"
- href={href ?? "#"}
- prefetch={true}
- onClick={onClick}
- >
- <div className="flex-shrink-0 flex items-center justify-center w-3.5 h-3.5">
- {cloneElement(icon, {
- ref: iconRef,
- className: iconClassName,
- size: 14,
- })}
- </div>
- <p className={clsx("text-sm text-gray-12")}>{name}</p>
- </Link>
+ {href ? (
+ <Link
+ className="flex gap-2 items-center w-full"
+ href={href}
+ prefetch={true}
+ onClick={onClick}
+ >
+ {content}
+ </Link>
+ ) : (
+ <div className="flex gap-2 items-center w-full">{content}</div>
+ )}
</CommandItem>
);
});
+const ThemeMenuIcon = forwardRef<
+ DownloadIconHandle,
+ { className?: string; size?: number }
+>(({ className, size = 14 }, ref) => {
+ const { theme } = useTheme();
+ const Icon = theme === "light" ? Moon : Sun;
+
+ useImperativeHandle(ref, () => ({
+ startAnimation: () => undefined,
+ stopAnimation: () => undefined,
+ }));
+
+ return <Icon className={className} size={size} />;
+});
+
+ThemeMenuIcon.displayName = "ThemeMenuIcon";
+
const ReferButton = () => {
const iconRef = useRef<ReferIconHandle>(null);
const { setReferClickedStateHandler, referClickedState } =
useDashboardContext();
return (
- <Link href="/dashboard/refer" className="hidden relative lg:block">
+ <Link
+ href="/dashboard/refer"
+ className="hidden relative lg:block"
+ onClick={() => {
+ setReferClickedStateHandler(true);
+ }}
+ onMouseEnter={() => {
+ iconRef.current?.startAnimation();
+ }}
+ onMouseLeave={() => {
+ iconRef.current?.stopAnimation();
+ }}
+ >
{!referClickedState && (
<div className="absolute right-0 top-1 z-10">
<div className="relative">
@@ -375,18 +416,7 @@ const ReferButton = () => {
</div>
)}
- <div
- onClick={() => {
- setReferClickedStateHandler(true);
- }}
- onMouseEnter={() => {
- iconRef.current?.startAnimation();
- }}
- onMouseLeave={() => {
- iconRef.current?.stopAnimation();
- }}
- className="flex justify-center items-center rounded-full transition-colors cursor-pointer bg-gray-3 hover:bg-gray-5 size-9"
- >
+ <div className="flex justify-center items-center rounded-full transition-colors cursor-pointer bg-gray-3 hover:bg-gray-5 size-9">
{cloneElement(<ReferIcon />, {
ref: iconRef,
className: "text-gray-12 size-3.5",
diff --git a/apps/web/app/(org)/dashboard/_components/Navbar/search.ts b/apps/web/app/(org)/dashboard/_components/Navbar/search.ts
new file mode 100644
index 000000000..2b4479f13
--- /dev/null
+++ b/apps/web/app/(org)/dashboard/_components/Navbar/search.ts
@@ -0,0 +1,124 @@
+"use server";
+
+import { db } from "@cap/database";
+import { getCurrentUser } from "@cap/database/auth/session";
+import {
+ organizationMembers,
+ organizations,
+ sharedVideos,
+ spaceMembers,
+ spaces,
+ spaceVideos,
+ users,
+ videos,
+} from "@cap/database/schema";
+import type { Video } from "@cap/web-domain";
+import { and, desc, eq, inArray, isNull, or, sql } from "drizzle-orm";
+
+const MAX_VIDEO_RESULTS = 8;
+const MIN_VIDEO_QUERY_LENGTH = 2;
+const MAX_QUERY_LENGTH = 80;
+const LIKE_ESCAPE = "!";
+
+export type DashboardVideoSearchResult = {
+ id: Video.VideoId;
+ name: string;
+ ownerName: string | null;
+ createdAt: string;
+ duration: number | null;
+ isScreenshot: boolean;
+};
+
+const normalizeSearchQuery = (query: string) =>
+ query.trim().replace(/\s+/g, " ").slice(0, MAX_QUERY_LENGTH);
+const escapeLikePattern = (value: string) =>
+ value.replace(/[!%_]/g, (match) => `${LIKE_ESCAPE}${match}`);
+
+export async function searchDashboardVideos(
+ query: string,
+): Promise<DashboardVideoSearchResult[]> {
+ const user = await getCurrentUser();
+ const activeOrganizationId = user?.activeOrganizationId;
+ const normalizedQuery = normalizeSearchQuery(query);
+
+ if (
+ !user ||
+ !activeOrganizationId ||
+ normalizedQuery.length < MIN_VIDEO_QUERY_LENGTH
+ ) {
+ return [];
+ }
+
+ const database = db();
+ const escapedQuery = escapeLikePattern(normalizedQuery);
+ const containsPattern = `%${escapedQuery}%`;
+ const startsWithPattern = `${escapedQuery}%`;
+ const organizationMembershipIds = database
+ .select({ organizationId: organizationMembers.organizationId })
+ .from(organizationMembers)
+ .where(eq(organizationMembers.userId, user.id));
+ const sharedVideoIds = database
+ .select({ videoId: sharedVideos.videoId })
+ .from(sharedVideos)
+ .where(eq(sharedVideos.organizationId, activeOrganizationId));
+ const accessibleSpaceVideoIds = database
+ .select({ videoId: spaceVideos.videoId })
+ .from(spaceVideos)
+ .innerJoin(spaces, eq(spaceVideos.spaceId, spaces.id))
+ .where(
+ and(
+ eq(spaces.organizationId, activeOrganizationId),
+ or(
+ eq(spaces.createdById, user.id),
+ eq(spaces.privacy, "Public"),
+ inArray(
+ spaces.id,
+ database
+ .select({ spaceId: spaceMembers.spaceId })
+ .from(spaceMembers)
+ .where(eq(spaceMembers.userId, user.id)),
+ ),
+ ),
+ ),
+ );
+
+ const rows = await database
+ .select({
+ id: videos.id,
+ name: videos.name,
+ ownerName: users.name,
+ createdAt: videos.createdAt,
+ duration: videos.duration,
+ isScreenshot: videos.isScreenshot,
+ })
+ .from(videos)
+ .innerJoin(organizations, eq(videos.orgId, organizations.id))
+ .leftJoin(users, eq(videos.ownerId, users.id))
+ .where(
+ and(
+ eq(videos.orgId, activeOrganizationId),
+ isNull(organizations.tombstoneAt),
+ or(
+ eq(organizations.ownerId, user.id),
+ inArray(organizations.id, organizationMembershipIds),
+ ),
+ sql`${videos.name} LIKE ${containsPattern} ESCAPE '!'`,
+ or(
+ eq(videos.ownerId, user.id),
+ inArray(videos.id, sharedVideoIds),
+ inArray(videos.id, accessibleSpaceVideoIds),
+ ),
+ ),
+ )
+ .orderBy(
+ sql`CASE WHEN ${videos.name} LIKE ${startsWithPattern} ESCAPE '!' THEN 0 ELSE 1 END`,
+ desc(videos.effectiveCreatedAt),
+ )
+ .limit(MAX_VIDEO_RESULTS);
+
+ return rows.map((row) => ({
+ ...row,
+ createdAt: row.createdAt.toISOString(),
+ duration: row.duration ?? null,
+ }));
+}