From 75cae41f2aebd6343ce95cd0b6910870724ed374 Mon Sep 17 00:00:00 2001 From: Dhravya Date: Sat, 13 Apr 2024 09:14:37 -0700 Subject: [PATCH] merge --- apps/extension/package.json | 1 + apps/extension/src/SideBar.tsx | 175 ++++++------- apps/extension/src/background.ts | 46 +++- .../src/components/FilterCombobox.tsx | 175 +++++-------- .../src/components/ui/dropdown-menu.tsx | 204 +++++++++++++++ apps/web/src/actions/db.ts | 60 ++--- apps/web/src/app/page.tsx | 39 +-- .../components/Sidebar/AddMemoryDialog.tsx | 31 --- .../src/components/Sidebar/MemoriesBar.tsx | 232 +++++++++++------- apps/web/src/contexts/MemoryContext.tsx | 80 +++--- apps/web/src/server/db/schema.ts | 5 +- apps/web/src/server/db/test.ts | 6 + apps/web/types/memory.tsx | 58 +++-- 13 files changed, 675 insertions(+), 437 deletions(-) create mode 100644 apps/extension/src/components/ui/dropdown-menu.tsx create mode 100644 apps/web/src/server/db/test.ts diff --git a/apps/extension/package.json b/apps/extension/package.json index 4c12ef20..a7f34ea6 100644 --- a/apps/extension/package.json +++ b/apps/extension/package.json @@ -12,6 +12,7 @@ }, "dependencies": { "@radix-ui/react-dialog": "^1.0.5", + "@radix-ui/react-dropdown-menu": "^2.0.6", "@radix-ui/react-popover": "^1.0.7", "@radix-ui/react-tooltip": "^1.0.7", "cmdk": "^1.0.0", diff --git a/apps/extension/src/SideBar.tsx b/apps/extension/src/SideBar.tsx index 34992386..9704511b 100644 --- a/apps/extension/src/SideBar.tsx +++ b/apps/extension/src/SideBar.tsx @@ -7,19 +7,20 @@ import { TooltipProvider, TooltipTrigger, } from "./components/ui/tooltip"; -// import { FilterSpaces } from "./components/FilterCombobox"; -// import { -// Dialog, -// DialogContent, -// DialogHeader, -// DialogTitle, -// DialogDescription, -// DialogTrigger, -// DialogFooter, -// DialogClose, -// } from "./components/ui/dialog"; +import { FilterSpaces } from "./components/FilterCombobox"; +import { + Dialog, + DialogContent, + DialogHeader, + DialogTitle, + DialogDescription, + DialogTrigger, + DialogFooter, + DialogClose, +} from "./components/ui/dialog"; +import { Space } from "./types/memory"; -function sendUrlToAPI() { +function sendUrlToAPI(spaces: number[]) { // get the current URL const url = window.location.href; @@ -31,7 +32,7 @@ function sendUrlToAPI() { } else { // const content = Entire page content, but cleaned up for the LLM. No ads, no scripts, no styles, just the text. if article, just the importnat info abou tit. const content = document.documentElement.innerText; - chrome.runtime.sendMessage({ type: "urlChange", content, url }); + chrome.runtime.sendMessage({ type: "urlChange", content, url, spaces }); } } @@ -50,7 +51,9 @@ function SideBar({ jwt }: { jwt: string }) { const [isSendingData, setIsSendingData] = useState(false); - // const [selectedSpaces, setSelectedSpaces] = useState([0, 1]); + const [loading, setLoading] = useState(false); + const [spaces, setSpaces] = useState(); + const [selectedSpaces, setSelectedSpaces] = useState([]); const [isImportingTweets, setIsImportingTweets] = useState(false); @@ -73,6 +76,15 @@ function SideBar({ jwt }: { jwt: string }) { }); } + const fetchSpaces = async () => { + setLoading(true); + chrome.runtime.sendMessage({ type: "fetchSpaces" }, (resp) => { + console.log(resp); + setSpaces(resp); + setLoading(false); + }); + }; + const fetchBookmarks = () => { const tweets: TweetData[] = []; // Initialize an empty array to hold all tweet elements @@ -253,67 +265,58 @@ function SideBar({ jwt }: { jwt: string }) { ) : ( <> )} - {/* */} - - - {/* */} - - {/* */} - - -

- {savedWebsites.includes(window.location.href) - ? "Added to memory" - : "Add to memory"} -

-
-
- {/* + {savedWebsites.includes(window.location.href) ? ( + + + + + + ) : ( + + + + )} + + + + +

+ {savedWebsites.includes(window.location.href) + ? "Added to memory" + : "Add to memory"} +

+
+ + Add to Memory @@ -322,27 +325,33 @@ function SideBar({ jwt }: { jwt: string }) { - Add + { + sendUrlToAPI(selectedSpaces); + setIsSendingData(true); + setTimeout(() => { + setIsSendingData(false); + setSavedWebsites([ + ...savedWebsites, + window.location.href, + ]); + }, 1000); + }} + > + Add + Cancel -
*/} + diff --git a/apps/extension/src/background.ts b/apps/extension/src/background.ts index 7e12bba4..2c67936b 100644 --- a/apps/extension/src/background.ts +++ b/apps/extension/src/background.ts @@ -1,4 +1,5 @@ import { getEnv } from "./util"; +import { Space } from "./types/memory"; const backendUrl = getEnv() === "development" @@ -48,22 +49,51 @@ chrome.runtime.onMessage.addListener((request, sender, sendResponse) => { } else if (request.type === "urlChange") { const content = request.content; const url = request.url; - - (async () => { - chrome.storage.local.get(["jwt"], ({ jwt }) => { + const spaces = request.spaces( + // eslint-disable-next-line no-unexpected-multiline + async () => { + chrome.storage.local.get(["jwt"], ({ jwt }) => { + if (!jwt) { + console.error("No JWT found"); + return; + } + fetch(`${backendUrl}/api/store`, { + method: "POST", + headers: { + Authorization: `Bearer ${jwt}`, + }, + body: JSON.stringify({ pageContent: content, url, spaces }), + }).then((ers) => console.log(ers.status)); + }); + }, + )(); + return true; + } else if (request.type === "fetchSpaces") { + const run = () => + chrome.storage.local.get(["jwt"], async ({ jwt }) => { if (!jwt) { console.error("No JWT found"); return; } - fetch(`${backendUrl}/api/store`, { - method: "POST", + const resp = await fetch(`${backendUrl}/api/spaces`, { headers: { Authorization: `Bearer ${jwt}`, }, - body: JSON.stringify({ pageContent: content, url }), - }).then((ers) => console.log(ers.status)); + }); + + const data: { + message: "OK" | string; + data: Space[] | undefined; + } = await resp.json(); + + if (data.message === "OK" && data.data) { + sendResponse(data.data); + } }); - })(); + + run(); + + return true; } else if (request.type === "queryApi") { const input = request.input; const jwt = request.jwt; diff --git a/apps/extension/src/components/FilterCombobox.tsx b/apps/extension/src/components/FilterCombobox.tsx index 5467655b..ae9c45ae 100644 --- a/apps/extension/src/components/FilterCombobox.tsx +++ b/apps/extension/src/components/FilterCombobox.tsx @@ -1,152 +1,91 @@ import * as React from "react"; -import { Check, ChevronsUpDown, X } from "lucide-react"; - -import { cn } from "../lib/utils"; -import { - Command, - CommandEmpty, - CommandGroup, - CommandInput, - CommandItem, - CommandList, -} from "../components/ui/command"; -import { - Popover, - PopoverContent, - PopoverTrigger, -} from "../components/ui/popover"; +import { PlusCircleIcon, X } from "lucide-react"; import { Space } from "../types/memory"; +import { + DropdownMenu, + DropdownMenuContent, + DropdownMenuItem, +} from "./ui/dropdown-menu"; +import { DropdownMenuTrigger } from "@radix-ui/react-dropdown-menu"; export interface Props extends React.ButtonHTMLAttributes { - side?: "top" | "bottom"; - align?: "end" | "start" | "center"; - onClose?: () => void; selectedSpaces: number[]; setSelectedSpaces: ( spaces: number[] | ((prev: number[]) => number[]), ) => void; name: string; spaces: Space[]; + loading: boolean; } export function FilterSpaces({ - className, - side = "bottom", - align = "center", - onClose, + loading, selectedSpaces, setSelectedSpaces, - name, spaces, - ...props }: Props) { - const [open, setOpen] = React.useState(false); - console.log(selectedSpaces, spaces); - const sortedSpaces = spaces.sort(({ id: a }, { id: b }) => - selectedSpaces.includes(a) && !selectedSpaces.includes(b) - ? -1 - : selectedSpaces.includes(b) && !selectedSpaces.includes(a) - ? 1 - : 0, + const filteredSpaces = spaces.filter((space) => + selectedSpaces.includes(space.id), + ); + const leftSpaces = spaces.filter( + (space) => !selectedSpaces.includes(space.id), ); - React.useEffect(() => { - if (!open) { - onClose?.(); - } - }, [open]); + if (loading) { + return "Loading..."; + } return (
- {selectedSpaces.map((spaceid) => { - const space = spaces.find((s) => s.id === spaceid)!; - return ; - })} + {filteredSpaces.length < 1 && "Add to a space"} + {filteredSpaces.map((space) => ( + setSelectedSpaces(prev => prev.filter(s => s !== space.id))} + /> + ))} + {leftSpaces.length > 0 && ( + + + + + + {leftSpaces.map((space) => ( + <> + {loading && "Loading..."} + + setSelectedSpaces((prev) => [...prev, space.id]) + } + > + {space.name} + + + ))} + + + )}
); - - return ( - - - - - e.preventDefault()} - align={align} - side={side} - className="anycontext-w-[200px] anycontext-p-0" - > - - spaces - .find((s) => s.id.toString() === val) - ?.name.toLowerCase() - .includes(search.toLowerCase().trim()) - ? 1 - : 0 - } - > - - -
- Nothing found - - {sortedSpaces.map((space) => ( - { - setSelectedSpaces((prev: number[]) => - prev.includes(parseInt(val)) - ? prev.filter((v) => v !== parseInt(val)) - : [...prev, parseInt(val)], - ); - }} - asChild - > -
- {space.name} - -
-
- ))} -
-
-
-
-
-
- ); } function SpaceItem({ name }: Space) { return (
- {name} diff --git a/apps/extension/src/components/ui/dropdown-menu.tsx b/apps/extension/src/components/ui/dropdown-menu.tsx new file mode 100644 index 00000000..fcc1edb2 --- /dev/null +++ b/apps/extension/src/components/ui/dropdown-menu.tsx @@ -0,0 +1,204 @@ +import * as React from "react"; +import * as DropdownMenuPrimitive from "@radix-ui/react-dropdown-menu"; +import { Check, ChevronRight, Circle } from "lucide-react"; + +import { cn } from "../../lib/utils"; + +const DropdownMenu = DropdownMenuPrimitive.Root; + +const DropdownMenuTrigger = DropdownMenuPrimitive.Trigger; + +const DropdownMenuGroup = DropdownMenuPrimitive.Group; + +const DropdownMenuPortal = DropdownMenuPrimitive.Portal; + +const DropdownMenuSub = DropdownMenuPrimitive.Sub; + +const DropdownMenuRadioGroup = DropdownMenuPrimitive.RadioGroup; + +const DropdownMenuSubTrigger = React.forwardRef< + React.ElementRef, + React.ComponentPropsWithoutRef & { + inset?: boolean; + } +>(({ className, inset, children, ...props }, ref) => ( + + {children} + + +)); +DropdownMenuSubTrigger.displayName = + DropdownMenuPrimitive.SubTrigger.displayName; + +const DropdownMenuSubContent = React.forwardRef< + React.ElementRef, + React.ComponentPropsWithoutRef +>(({ className, ...props }, ref) => ( + +)); +DropdownMenuSubContent.displayName = + DropdownMenuPrimitive.SubContent.displayName; + +const DropdownMenuContent = React.forwardRef< + React.ElementRef, + React.ComponentPropsWithoutRef +>(({ className, sideOffset = 4, ...props }, ref) => ( + + + +)); +DropdownMenuContent.displayName = DropdownMenuPrimitive.Content.displayName; + +const DropdownMenuItem = React.forwardRef< + React.ElementRef, + React.ComponentPropsWithoutRef & { + inset?: boolean; + } +>(({ className, inset, ...props }, ref) => ( + +)); +DropdownMenuItem.displayName = DropdownMenuPrimitive.Item.displayName; + +const DropdownMenuCheckboxItem = React.forwardRef< + React.ElementRef, + React.ComponentPropsWithoutRef +>(({ className, children, checked, ...props }, ref) => ( + + + + + + + {children} + +)); +DropdownMenuCheckboxItem.displayName = + DropdownMenuPrimitive.CheckboxItem.displayName; + +const DropdownMenuRadioItem = React.forwardRef< + React.ElementRef, + React.ComponentPropsWithoutRef +>(({ className, children, ...props }, ref) => ( + + + + + + + {children} + +)); +DropdownMenuRadioItem.displayName = DropdownMenuPrimitive.RadioItem.displayName; + +const DropdownMenuLabel = React.forwardRef< + React.ElementRef, + React.ComponentPropsWithoutRef & { + inset?: boolean; + } +>(({ className, inset, ...props }, ref) => ( + +)); +DropdownMenuLabel.displayName = DropdownMenuPrimitive.Label.displayName; + +const DropdownMenuSeparator = React.forwardRef< + React.ElementRef, + React.ComponentPropsWithoutRef +>(({ className, ...props }, ref) => ( + +)); +DropdownMenuSeparator.displayName = DropdownMenuPrimitive.Separator.displayName; + +const DropdownMenuShortcut = ({ + className, + ...props +}: React.HTMLAttributes) => { + return ( + + ); +}; +DropdownMenuShortcut.displayName = "DropdownMenuShortcut"; + +export { + DropdownMenu, + DropdownMenuTrigger, + DropdownMenuContent, + DropdownMenuItem, + DropdownMenuCheckboxItem, + DropdownMenuRadioItem, + DropdownMenuLabel, + DropdownMenuSeparator, + DropdownMenuShortcut, + DropdownMenuGroup, + DropdownMenuPortal, + DropdownMenuSub, + DropdownMenuSubContent, + DropdownMenuSubTrigger, + DropdownMenuRadioGroup, +}; diff --git a/apps/web/src/actions/db.ts b/apps/web/src/actions/db.ts index 46e3ddf6..35ebe423 100644 --- a/apps/web/src/actions/db.ts +++ b/apps/web/src/actions/db.ts @@ -7,35 +7,40 @@ import { StoredContent, storedContent, users, - space + space, } from "@/server/db/schema"; import { like, eq, and, sql } from "drizzle-orm"; -import { union } from "drizzle-orm/sqlite-core" +import { union } from "drizzle-orm/sqlite-core"; import { auth as authOptions } from "@/server/auth"; +import { FormEvent } from "react"; +import { revalidatePath } from "next/cache"; // @todo: (future) pagination not yet needed export async function searchMemoriesAndSpaces(userId: string, query: string) { - const searchMemoriesQuery = db.select({ - type: sql`'memory'`, - space: sql`NULL`, - memory: storedContent as any - }).from(storedContent).where(and( - eq(storedContent.user, userId), - like(storedContent.title, `%${query}%`) - )) + const searchMemoriesQuery = db + .select({ + type: sql`'memory'`, + space: sql`NULL`, + memory: storedContent as any, + }) + .from(storedContent) + .where( + and( + eq(storedContent.user, userId), + like(storedContent.title, `%${query}%`), + ), + ); - const searchSpacesQuery = db.select({ - type: sql`'space'`, - space: space as any, - memory: sql`NULL`, - }).from(space).where( - and( - eq(space.user, userId), - like(space.name, `%${query}%`) - ) - ) + const searchSpacesQuery = db + .select({ + type: sql`'space'`, + space: space as any, + memory: sql`NULL`, + }) + .from(space) + .where(and(eq(space.user, userId), like(space.name, `%${query}%`))); - return await union(searchMemoriesQuery, searchSpacesQuery) + return await union(searchMemoriesQuery, searchSpacesQuery); } async function getUser() { @@ -46,7 +51,7 @@ async function getUser() { headers().get("Authorization")?.replace("Bearer ", ""); if (!token) { - return null + return null; } const session = await db @@ -55,7 +60,7 @@ async function getUser() { .where(eq(sessions.sessionToken, token!)); if (!session || session.length === 0) { - return null + return null; } const [userData] = await db @@ -65,17 +70,17 @@ async function getUser() { .limit(1); if (!userData) { - return null + return null; } - return userData + return userData; } export async function getMemory(title: string) { const user = await getUser(); if (!user) { - return null + return null; } return await db @@ -93,11 +98,10 @@ export async function addMemory( content: typeof storedContent.$inferInsert, spaces: number[], ) { - const user = await getUser(); if (!user) { - return null + return null; } content.user = user.id; diff --git a/apps/web/src/app/page.tsx b/apps/web/src/app/page.tsx index 419daa5a..3112e71e 100644 --- a/apps/web/src/app/page.tsx +++ b/apps/web/src/app/page.tsx @@ -1,5 +1,6 @@ import { db } from "@/server/db"; import { + ChachedSpaceContent, contentToSpace, sessions, space, @@ -18,6 +19,7 @@ import { import { MemoryProvider } from "@/contexts/MemoryContext"; import Content from "./content"; import { searchMemoriesAndSpaces } from "@/actions/db"; +import { getMetaData } from "@/server/helpers"; export const runtime = "edge"; @@ -56,36 +58,37 @@ export default async function Home() { const collectedSpaces = await db .select() .from(space) - .where(and(eq(space.user, userData.id), not(eq(space.name, "none")))); + .where(eq(space.user, userData.id)) + .all(); + + console.log(collectedSpaces); // Fetch only first 3 content of each spaces - let contents: (typeof storedContent.$inferSelect)[] = []; + let contents: ChachedSpaceContent[] = []; + + //console.log(await db.select().from(storedContent).) await Promise.all([ collectedSpaces.forEach(async (space) => { - contents = [ - ...contents, - ...(await fetchContentForSpace(space.id, { + console.log("fetching "); + const data = ( + await fetchContentForSpace(space.id, { offset: 0, limit: 3, - })), - ]; + }) + ).map((data) => ({ + ...data, + space: space.id, + })); + contents = [...contents, ...data]; }), ]); + console.log(contents); + // freeMemories const freeMemories = await fetchFreeMemories(userData.id); - - // @dhravya test these 3 functions - fetchFreeMemories; - fetchContentForSpace; - searchMemoriesAndSpaces; - - collectedSpaces.push({ - id: 1, - name: "Cool tech", - user: null, - }); + console.log("free", freeMemories); return ( void }) { } export function SpaceAddPage({ closeDialog }: { closeDialog: () => void }) { - const [selectedSpacesId, setSelectedSpacesId] = useState([]); - - const inputRef = useRef(null); - const [name, setName] = useState(""); - const [content, setContent] = useState(""); - const [loading, setLoading] = useState(false); - - function check(): boolean { - const data = { - name: name.trim(), - content, - }; - console.log(name); - if (!data.name || data.name.length < 1) { - if (!inputRef.current) { - alert("Please enter a name for the note"); - return false; - } - inputRef.current.value = ""; - inputRef.current.placeholder = "Please enter a title for the note"; - inputRef.current.dataset["error"] = "true"; - setTimeout(() => { - inputRef.current!.placeholder = "Title of the note"; - inputRef.current!.dataset["error"] = "false"; - }, 500); - inputRef.current.focus(); - return false; - } - return true; - } - return (
diff --git a/apps/web/src/components/Sidebar/MemoriesBar.tsx b/apps/web/src/components/Sidebar/MemoriesBar.tsx index 769e6296..f671b72f 100644 --- a/apps/web/src/components/Sidebar/MemoriesBar.tsx +++ b/apps/web/src/components/Sidebar/MemoriesBar.tsx @@ -23,7 +23,7 @@ import { DropdownMenuItem, DropdownMenuTrigger, } from "../ui/dropdown-menu"; -import { useEffect, useRef, useState } from "react"; +import { useEffect, useMemo, useRef, useState } from "react"; import { Variant, useAnimate, motion } from "framer-motion"; import { useMemory } from "@/contexts/MemoryContext"; import { SpaceIcon } from "@/assets/Memories"; @@ -42,11 +42,12 @@ import useTouchHold from "@/hooks/useTouchHold"; import { DialogTrigger } from "@radix-ui/react-dialog"; import { AddMemoryPage, NoteAddPage, SpaceAddPage } from "./AddMemoryDialog"; import { ExpandedSpace } from "./ExpandedSpace"; -import { StoredSpace } from "@/server/db/schema"; +import { StoredContent, StoredSpace } from "@/server/db/schema"; +import Image from "next/image"; export function MemoriesBar() { const [parent, enableAnimations] = useAutoAnimate(); - const { spaces, deleteSpace } = useMemory(); + const { spaces, deleteSpace, freeMemories } = useMemory(); const [isDropdownOpen, setIsDropdownOpen] = useState(false); const [addMemoryState, setAddMemoryState] = useState< @@ -124,12 +125,15 @@ export function MemoriesBar() { > {spaces.map((space) => ( deleteSpace(space.id)} + onDelete={() => {}} key={space.id} - onClick={() => setExpandedSpace(space.id)} + //onClick={() => setExpandedSpace(space.id)} {...space} /> ))} + {freeMemories.map((m) => ( + + ))}
); @@ -145,12 +149,28 @@ const SpaceExitVariant: Variant = { }, }; +export function MemoryItem({ id, title, image }: StoredContent) { + return ( +
+ + +
+ +
+
+ ); +} + export function SpaceItem({ name, id, onDelete, onClick, }: StoredSpace & { onDelete: () => void; onClick?: () => void }) { + const { cachedMemories } = useMemory(); + const [itemRef, animateItem] = useAnimate(); const { width } = useViewport(); @@ -162,6 +182,10 @@ export function SpaceItem({ }, }); + const spaceMemories = useMemo(() => { + return cachedMemories.filter((m) => m.space === id); + }, [cachedMemories]); + return ( { + onDelete(); + return; if (!itemRef.current || width < 768) { onDelete(); return; } - const trash = document.querySelector("#trash")! as HTMLDivElement; - const trashBin = document.querySelector("#trash-button")!; - const trashRect = trashBin.getBoundingClientRect(); - const scopeRect = itemRef.current.getBoundingClientRect(); - const el = document.createElement("div"); - el.style.position = "fixed"; - el.style.top = "0"; - el.style.left = "0"; - el.style.width = "15px"; - el.style.height = "15px"; - el.style.backgroundColor = "var(--gray-7)"; - el.style.zIndex = "60"; - el.style.borderRadius = "50%"; - el.style.transform = "scale(5)"; - el.style.opacity = "0"; - trash.dataset["open"] = "true"; - const initial = { - x: scopeRect.left + scopeRect.width / 2, - y: scopeRect.top + scopeRect.height / 2, - }; - const delta = { - x: - trashRect.left + - trashRect.width / 2 - - scopeRect.left + - scopeRect.width / 2, - y: - trashRect.top + - trashRect.height / 4 - - scopeRect.top + - scopeRect.height / 2, - }; - const end = { - x: trashRect.left + trashRect.width / 2, - y: trashRect.top + trashRect.height / 4, - }; - el.style.offsetPath = `path('M ${initial.x} ${initial.y} Q ${delta.x * 0.01} ${delta.y * 0.01} ${end.x} ${end.y}`; - animateItem(itemRef.current, SpaceExitVariant, { - duration: 0.2, - }).then(() => { - itemRef.current.style.scale = "0"; - onDelete(); - }); - document.body.appendChild(el); - el.animate( - { - transform: ["scale(5)", "scale(1)"], - opacity: [0, 0.3, 1], - }, - { - duration: 200, - easing: "cubic-bezier(0.64, 0.57, 0.67, 1.53)", - fill: "forwards", - }, - ); - el.animate( - { - offsetDistance: ["0%", "100%"], - }, - { - duration: 2000, - easing: "cubic-bezier(0.64, 0.57, 0.67, 1.53)", - fill: "forwards", - delay: 200, - }, - ).onfinish = () => { - el.animate( - { transform: "scale(0)", opacity: 0 }, - { duration: 200, fill: "forwards" }, - ).onfinish = () => { - el.remove(); - }; - }; + // const trash = document.querySelector("#trash")! as HTMLDivElement; + // const trashBin = document.querySelector("#trash-button")!; + // const trashRect = trashBin.getBoundingClientRect(); + // const scopeRect = itemRef.current.getBoundingClientRect(); + // const el = document.createElement("div"); + // el.style.position = "fixed"; + // el.style.top = "0"; + // el.style.left = "0"; + // el.style.width = "15px"; + // el.style.height = "15px"; + // el.style.backgroundColor = "var(--gray-7)"; + // el.style.zIndex = "60"; + // el.style.borderRadius = "50%"; + // el.style.transform = "scale(5)"; + // el.style.opacity = "0"; + // trash.dataset["open"] = "true"; + // const initial = { + // x: scopeRect.left + scopeRect.width / 2, + // y: scopeRect.top + scopeRect.height / 2, + // }; + // const delta = { + // x: + // trashRect.left + + // trashRect.width / 2 - + // scopeRect.left + + // scopeRect.width / 2, + // y: + // trashRect.top + + // trashRect.height / 4 - + // scopeRect.top + + // scopeRect.height / 2, + // }; + // const end = { + // x: trashRect.left + trashRect.width / 2, + // y: trashRect.top + trashRect.height / 4, + // }; + // el.style.offsetPath = `path('M ${initial.x} ${initial.y} Q ${delta.x * 0.01} ${delta.y * 0.01} ${end.x} ${end.y}`; + // animateItem(itemRef.current, SpaceExitVariant, { + // duration: 0.2, + // }).then(() => { + // itemRef.current.style.scale = "0"; + // onDelete(); + // }); + // document.body.appendChild(el); + // el.animate( + // { + // transform: ["scale(5)", "scale(1)"], + // opacity: [0, 0.3, 1], + // }, + // { + // duration: 200, + // easing: "cubic-bezier(0.64, 0.57, 0.67, 1.53)", + // fill: "forwards", + // }, + // ); + // el.animate( + // { + // offsetDistance: ["0%", "100%"], + // }, + // { + // duration: 2000, + // easing: "cubic-bezier(0.64, 0.57, 0.67, 1.53)", + // fill: "forwards", + // delay: 200, + // }, + // ).onfinish = () => { + // el.animate( + // { transform: "scale(0)", opacity: 0 }, + // { duration: 200, fill: "forwards" }, + // ).onfinish = () => { + // el.remove(); + // }; + // }; }} /> - {/* {content.length > 2 ? ( + {spaceMemories.length > 2 ? ( c.image).reverse() as string[]} + images={spaceMemories.map((c) => c.image).reverse() as string[]} /> - ) : content.length === 1 ? ( + ) : spaceMemories.length === 1 ? ( ) : ( c.image).reverse() as string[]} + images={spaceMemories.map((c) => c.image).reverse() as string[]} /> - )} */} + )} ); } @@ -288,7 +314,7 @@ export function SpaceMoreButton({ setIsOpen?: (open: boolean) => void; }) { return ( - <> + ); } diff --git a/apps/web/src/contexts/MemoryContext.tsx b/apps/web/src/contexts/MemoryContext.tsx index aa9cab81..0438d75e 100644 --- a/apps/web/src/contexts/MemoryContext.tsx +++ b/apps/web/src/contexts/MemoryContext.tsx @@ -1,15 +1,20 @@ "use client"; import React, { useCallback } from "react"; import { CollectedSpaces } from "../../types/memory"; -import { StoredContent, storedContent, StoredSpace } from "@/server/db/schema"; +import { + ChachedSpaceContent, + StoredContent, + storedContent, + StoredSpace, +} from "@/server/db/schema"; import { addMemory, searchMemoriesAndSpaces } from "@/actions/db"; import { User } from "next-auth"; export type SearchResult = { - type: "memory" | "space", - space: StoredSpace, - memory: StoredContent -} + type: "memory" | "space"; + space: StoredSpace; + memory: StoredContent; +}; // temperory (will change) export const MemoryContext = React.createContext<{ @@ -21,8 +26,8 @@ export const MemoryContext = React.createContext<{ memory: typeof storedContent.$inferInsert, spaces?: number[], ) => Promise; - cachedMemories: StoredContent[]; - search: (query: string) => Promise; + cachedMemories: ChachedSpaceContent[]; + search: (query: string) => Promise; }>({ spaces: [], freeMemories: [], @@ -30,57 +35,62 @@ export const MemoryContext = React.createContext<{ addSpace: async () => {}, deleteSpace: async () => {}, cachedMemories: [], - search: async () => [] + search: async () => [], }); export const MemoryProvider: React.FC< { spaces: StoredSpace[]; freeMemories: StoredContent[]; - cachedMemories: StoredContent[]; - user: User; + cachedMemories: ChachedSpaceContent[]; + user: User; } & React.PropsWithChildren -> = ({ children, user, spaces: initalSpaces, freeMemories: initialFreeMemories, cachedMemories: initialCachedMemories }) => { - +> = ({ + children, + user, + spaces: initalSpaces, + freeMemories: initialFreeMemories, + cachedMemories: initialCachedMemories, +}) => { const [spaces, setSpaces] = React.useState(initalSpaces); const [freeMemories, setFreeMemories] = React.useState(initialFreeMemories); - const [cachedMemories, setCachedMemories] = React.useState( - initialCachedMemories - ); + const [cachedMemories, setCachedMemories] = React.useState< + ChachedSpaceContent[] + >(initialCachedMemories); const addSpace = async (space: StoredSpace) => { - setSpaces((prev) => [...prev, space]); - } - - const deleteSpace = async (id: number) => { - setSpaces((prev) => prev.filter((s) => s.id !== id)); - } + setSpaces((prev) => [...prev, space]); + }; - const search = async (query: string) => { - if (!user.id) { - throw new Error('user id is not define') - } - const data = await searchMemoriesAndSpaces(user.id, query) - return data as SearchResult[] - } + const deleteSpace = async (id: number) => { + setSpaces((prev) => prev.filter((s) => s.id !== id)); + }; + + const search = async (query: string) => { + if (!user.id) { + throw new Error("user id is not define"); + } + const data = await searchMemoriesAndSpaces(user.id, query); + return data as SearchResult[]; + }; // const fetchMemories = useCallback(async (query: string) => { // const response = await fetch(`/api/memories?${query}`); // }, []); - const _addMemory = async ( - memory: typeof storedContent.$inferInsert, - spaces: number[] = [], - ) => { - const content = await addMemory(memory, spaces); - } + const _addMemory = async ( + memory: typeof storedContent.$inferInsert, + spaces: number[] = [], + ) => { + const content = await addMemory(memory, spaces); + }; return ( ({ accounts: many(accounts), @@ -134,3 +134,6 @@ export const space = createTable( export type StoredContent = Omit; export type StoredSpace = typeof space.$inferSelect; +export type ChachedSpaceContent = StoredContent & { + space: number; +}; diff --git a/apps/web/src/server/db/test.ts b/apps/web/src/server/db/test.ts new file mode 100644 index 00000000..37969e5e --- /dev/null +++ b/apps/web/src/server/db/test.ts @@ -0,0 +1,6 @@ +import { db } from "."; +import { space, user } from "./schema"; + +const user = await db.select(user).all(); + +await db.insert(space).values([{}]); diff --git a/apps/web/types/memory.tsx b/apps/web/types/memory.tsx index ff0dc94c..6bfda971 100644 --- a/apps/web/types/memory.tsx +++ b/apps/web/types/memory.tsx @@ -5,7 +5,7 @@ import { storedContent, StoredContent, } from "@/server/db/schema"; -import { asc, and, eq, inArray, notExists } from "drizzle-orm"; +import { asc, and, eq, inArray, notExists, sql, exists } from "drizzle-orm"; export async function fetchContentForSpace( spaceId: number, @@ -14,41 +14,55 @@ export async function fetchContentForSpace( limit: number; }, ) { - const query = db .select() .from(storedContent) .where( - inArray( - storedContent.id, - db.select().from(space).where(eq(space.id, spaceId)), + exists( + db + .select() + .from(contentToSpace) + .where( + and( + eq(contentToSpace.spaceId, spaceId), + eq(contentToSpace.contentId, storedContent.id), + ), + ), ), - ).orderBy(asc(storedContent.title)) + ) + .orderBy(asc(storedContent.title)); - return range ? await query.limit(range.limit).offset(range.offset) : await query.all() + return range + ? await query.limit(range.limit).offset(range.offset) + : await query.all(); } export async function fetchFreeMemories( - userId: string, - range?: { - offset: number; - limit: number; - } + userId: string, + range?: { + offset: number; + limit: number; + }, ) { - const query = db + const query = db .select() .from(storedContent) .where( - and( - notExists( - db.select().from(contentToSpace).where(eq(contentToSpace.contentId, storedContent.id)), - ), - eq(storedContent.user, userId), - ) - - ).orderBy(asc(storedContent.title)) + and( + notExists( + db + .select() + .from(contentToSpace) + .where(eq(contentToSpace.contentId, storedContent.id)), + ), + eq(storedContent.user, userId), + ), + ) + .orderBy(asc(storedContent.title)); - return range ? await query.limit(range.limit).offset(range.offset) : await query.all() + return range + ? await query.limit(range.limit).offset(range.offset) + : await query.all(); } export const transformContent = async (