aboutsummaryrefslogtreecommitdiff
path: root/apps/web/src
diff options
context:
space:
mode:
authoryxshv <[email protected]>2024-04-11 16:37:46 +0530
committeryxshv <[email protected]>2024-04-11 16:37:46 +0530
commit539f50367d2964579dbb6aa62876fab973b17840 (patch)
treea071ab8c30d2448207bc68c92a57d5663dd73724 /apps/web/src
parentmerge pls (diff)
parentMerge branch 'main' of https://github.com/Dhravya/supermemory (diff)
downloadsupermemory-539f50367d2964579dbb6aa62876fab973b17840.tar.xz
supermemory-539f50367d2964579dbb6aa62876fab973b17840.zip
Merge branch 'main' of https://github.com/dhravya/supermemory
Diffstat (limited to 'apps/web/src')
-rw-r--r--apps/web/src/actions/db.ts52
-rw-r--r--apps/web/src/app/api/store/route.ts2
-rw-r--r--apps/web/src/app/globals.css63
-rw-r--r--apps/web/src/app/layout.tsx5
-rw-r--r--apps/web/src/components/ChatMessage.tsx16
-rw-r--r--apps/web/src/components/Main.tsx53
-rw-r--r--apps/web/src/components/QueryAI.tsx139
-rw-r--r--apps/web/src/components/Sidebar.tsx145
-rw-r--r--apps/web/src/components/Sidebar/AddMemoryDialog.tsx213
-rw-r--r--apps/web/src/components/Sidebar/FilterCombobox.tsx125
-rw-r--r--apps/web/src/components/Sidebar/MemoriesBar.tsx181
-rw-r--r--apps/web/src/components/Sidebar/index.tsx9
-rw-r--r--apps/web/src/components/WordMark.tsx12
-rw-r--r--apps/web/src/contexts/MemoryContext.tsx48
-rw-r--r--apps/web/src/lib/utils.ts5
-rw-r--r--apps/web/src/server/db/schema.ts5
16 files changed, 642 insertions, 431 deletions
diff --git a/apps/web/src/actions/db.ts b/apps/web/src/actions/db.ts
new file mode 100644
index 00000000..3b640c96
--- /dev/null
+++ b/apps/web/src/actions/db.ts
@@ -0,0 +1,52 @@
+"use server";
+import { db } from "@/server/db";
+import {
+ contentToSpace,
+ StoredContent,
+ storedContent,
+} from "@/server/db/schema";
+import { like, eq, and } from "drizzle-orm";
+import { auth as authOptions } from "@/server/auth";
+import { getSession } from "next-auth/react";
+
+export async function getMemory(title: string) {
+ const session = await getSession();
+
+ console.log(session?.user?.name);
+
+ if (!session || !session.user) {
+ return null;
+ }
+
+ return await db
+ .select()
+ .from(storedContent)
+ .where(
+ and(
+ eq(storedContent.user, session.user.id!),
+ like(storedContent.title, `%${title}%`),
+ ),
+ );
+}
+
+export async function addMemory(
+ content: typeof storedContent.$inferInsert,
+ spaces: number[],
+) {
+ const session = await getSession();
+
+ if (!session || !session.user) {
+ return null;
+ }
+ content.user = session.user.id;
+
+ const _content = (
+ await db.insert(storedContent).values(content).returning()
+ )[0];
+ await Promise.all(
+ spaces.map((spaceId) =>
+ db.insert(contentToSpace).values({ contentId: _content.id, spaceId }),
+ ),
+ );
+ return _content;
+}
diff --git a/apps/web/src/app/api/store/route.ts b/apps/web/src/app/api/store/route.ts
index ebe23077..ca6921c4 100644
--- a/apps/web/src/app/api/store/route.ts
+++ b/apps/web/src/app/api/store/route.ts
@@ -67,7 +67,7 @@ export async function POST(req: NextRequest) {
let storeToSpace = data.space;
if (!storeToSpace) {
- storeToSpace = "all";
+ storeToSpace = "none";
}
const storedContentId = await db.insert(storedContent).values({
diff --git a/apps/web/src/app/globals.css b/apps/web/src/app/globals.css
index f5d09a67..b09627ba 100644
--- a/apps/web/src/app/globals.css
+++ b/apps/web/src/app/globals.css
@@ -20,7 +20,7 @@
}
body {
- @apply bg-rgray-2 text-rgray-11 max-h-screen overflow-y-hidden;
+ @apply text-rgray-11 max-h-screen overflow-y-hidden bg-white;
/* color: rgb(var(--foreground-rgb));
background: linear-gradient(
to bottom,
@@ -57,8 +57,12 @@ body {
padding-bottom: 15dvh;
}
-.chat-answer pre {
- @apply bg-rgray-3 border-rgray-5 my-5 rounded-md border p-3 text-sm;
+.chat-answer pre {
+ @apply bg-rgray-3 rounded-md border border-rgray-5 p-3 text-sm my-5;
+}
+
+.novel-editor pre {
+ @apply bg-rgray-3 rounded-md border border-rgray-5 p-4 text-sm text-rgray-11;
}
.chat-answer h1 {
@@ -66,5 +70,56 @@ body {
}
.chat-answer img {
- @apply my-5 rounded-md font-medium;
+ @apply rounded-md font-medium my-5;
+}
+
+.tippy-box {
+ @apply bg-rgray-3 text-rgray-11 border border-rgray-5 rounded-md py-0;
+}
+
+.tippy-content #slash-command {
+ @apply text-rgray-11 bg-transparent border-none;
+}
+
+#slash-command button {
+ @apply text-rgray-11 py-2;
+}
+
+#slash-command button div:first-child {
+ @apply text-rgray-11 bg-rgray-4 border-rgray-5 ;
+}
+
+#slash-command button.novel-bg-stone-100 {
+ @apply bg-rgray-1;
+}
+
+.novel-editor [data-type=taskList] > li {
+ @apply my-0;
+}
+
+.novel-editor input[type=checkbox] {
+ @apply accent-rgray-4 rounded-md;
+
+ background: var(--gray-4) !important;
+ border: 1px solid var(--gray-10) !important;
}
+
+.novel-editor .is-empty::before {
+ content: 'Press \'/\' for commands' !important;
+}
+
+.novel-editor h1 {
+ @apply text-2xl;
+}
+
+.novel-editor h2 {
+ @apply text-xl;
+}
+
+.novel-editor h3 {
+ @apply text-lg;
+}
+
+.novel-editor .drag-handle {
+ @apply hidden;
+} \ No newline at end of file
diff --git a/apps/web/src/app/layout.tsx b/apps/web/src/app/layout.tsx
index 1b204dec..42485461 100644
--- a/apps/web/src/app/layout.tsx
+++ b/apps/web/src/app/layout.tsx
@@ -1,8 +1,9 @@
import type { Metadata } from "next";
-import { Roboto } from "next/font/google";
+import { Roboto, Inter } from "next/font/google";
import "./globals.css";
const roboto = Roboto({ weight: ["300", "400", "500"], subsets: ["latin"] });
+const inter = Inter({ weight: ["300", "400", "500"], subsets: ["latin"] });
export const metadata: Metadata = {
title: "Create Next App",
@@ -16,7 +17,7 @@ export default function RootLayout({
}>) {
return (
<html lang="en" className="dark">
- <body className={roboto.className}>
+ <body className={inter.className}>
<div vaul-drawer-wrapper="" className="min-w-screen overflow-x-hidden">
{children}
</div>
diff --git a/apps/web/src/components/ChatMessage.tsx b/apps/web/src/components/ChatMessage.tsx
index d25c9c48..db0778c4 100644
--- a/apps/web/src/components/ChatMessage.tsx
+++ b/apps/web/src/components/ChatMessage.tsx
@@ -37,7 +37,7 @@ export function ChatAnswer({
href={source}
>
<Globe className="h-4 w-4" />
- {source}
+ {cleanUrl(source)}
</a>
))}
</div>
@@ -103,3 +103,17 @@ function MessageSkeleton() {
</div>
);
}
+
+function cleanUrl(url: string) {
+ if (url.startsWith("https://")) {
+ url = url.slice(8);
+ } else if (url.startsWith("http://")) {
+ url = url.slice(7);
+ }
+
+ if (url.endsWith("/")) {
+ url = url.slice(0, -1);
+ }
+
+ return url;
+}
diff --git a/apps/web/src/components/Main.tsx b/apps/web/src/components/Main.tsx
index 09703c2f..c7bb3f1e 100644
--- a/apps/web/src/components/Main.tsx
+++ b/apps/web/src/components/Main.tsx
@@ -1,17 +1,19 @@
"use client";
import { useCallback, useEffect, useRef, useState } from "react";
-import { FilterCombobox } from "./Sidebar/FilterCombobox";
+import { FilterSpaces } from "./Sidebar/FilterCombobox";
import { Textarea2 } from "./ui/textarea";
import { ArrowRight, ArrowUp } from "lucide-react";
import { MemoryDrawer } from "./MemoryDrawer";
import useViewport from "@/hooks/useViewport";
import { AnimatePresence, motion } from "framer-motion";
-import { cn, countLines } from "@/lib/utils";
+import { cn, countLines, getIdsFromSource } from "@/lib/utils";
import { ChatHistory } from "../../types/memory";
import { ChatAnswer, ChatMessage, ChatQuestion } from "./ChatMessage";
import { useRouter, useSearchParams } from "next/navigation";
import { useMemory } from "@/contexts/MemoryContext";
+import Image from "next/image";
+
function supportsDVH() {
try {
return CSS.supports("height: 100dvh");
@@ -20,30 +22,6 @@ function supportsDVH() {
}
}
-const failResponse = `Lorem ipsum dolor sit amet, consectetur adipiscing elit. In volutpat bibendum ligula, nec consectetur purus iaculis eu. Sed venenatis magna at lacus efficitur, vel faucibus sem lobortis. Sed sit amet imperdiet eros, nec vestibulum ante. Integer ut eros pulvinar, tempus augue a, blandit nisl. Nulla ut ligula molestie, tincidunt ligula vitae, rhoncus tellus. Vestibulum molestie, orci nec scelerisque finibus, mauris eros convallis urna, vitae vehicula metus nisi id urna. Phasellus non metus et lectus sollicitudin convallis a sit amet turpis. Donec id lacinia sapien.
-
-Donec eget eros diam. Ut enim nunc, placerat vitae augue vel, rutrum dapibus felis. Nulla et ultrices ex. In sed arcu eget lectus scelerisque semper. Nullam aliquam luctus ultrices. Morbi finibus nec dolor vitae mattis. Quisque ligula dui, ullamcorper sed blandit et, maximus vel quam. Nunc id eros id sapien tempor feugiat sit amet sed mi. Quisque feugiat hendrerit libero non cursus. Praesent convallis, diam eget ullamcorper bibendum, est tellus blandit velit, vel cursus diam turpis sed nisi.
-
-Cras dictum tortor ex, id ullamcorper nibh mollis quis. Fusce mollis, massa vel sodales consectetur, lorem mi vehicula erat, id tincidunt lorem libero at augue. Suspendisse vitae enim varius, molestie augue ut, lobortis ipsum. Nam lobortis leo eget velit auctor, ac consequat nisl malesuada. Donec sed dapibus nunc. Curabitur euismod erat a erat viverra vestibulum lacinia quis nisl. Aenean rhoncus suscipit maximus. Aliquam vitae lectus est.
-
-Sed rhoncus sem sapien, at posuere libero imperdiet eget. Maecenas in egestas quam. Duis non faucibus eros, nec sodales sem. Proin felis urna, dapibus eget ante vitae, porttitor bibendum nunc. Integer nec augue eget diam pulvinar vestibulum. Nulla lobortis libero tellus, eu commodo elit ullamcorper in. Sed semper ultricies turpis ac dignissim. Morbi at ligula non urna mollis interdum vitae sed nisi. Quisque mattis arcu eu nisl placerat ullamcorper. Cras aliquet risus sed hendrerit faucibus. Donec vitae ex quis magna cursus ultricies ut nec urna.
-
-Integer molestie nulla interdum enim suscipit malesuada. Nullam eget ipsum et elit sagittis imperdiet sed dignissim sem. Fusce vitae tellus ligula. Donec eget mi varius, consequat eros sed, consectetur urna. Suspendisse potenti. Praesent posuere ullamcorper tincidunt. Donec bibendum, magna nec mollis posuere, nisi risus dictum mauris, sed gravida metus sapien vel ipsum. Etiam ultrices nulla tincidunt erat lacinia, sit amet bibendum libero posuere. Vestibulum vehicula lectus dolor, sit amet vehicula arcu ultricies nec. Proin blandit risus diam, vel finibus erat efficitur in. Suspendisse lacinia eros luctus posuere fermentum. Etiam sed lacus aliquam, vulputate est sed, venenatis ex. Aenean at nulla rhoncus, sollicitudin elit quis, auctor tortor. Donec semper, augue lacinia pharetra imperdiet, metus purus bibendum ex, et venenatis enim purus vitae nulla. Duis eu felis porta ligula laoreet viverra.
-Answer
-It seems like you've used placeholder text commonly known as "Lorem Ipsum," which is often used in design and publishing to simulate the appearance of written text. If you have any specific questions or need assistance with something related to this text, feel free to ask!
-what is its purpose?
-Sources
-solopress.com favicon
-typingpal.com favicon
-View 2 more
-Answer
-The purpose of Lorem Ipsum, a commonly used placeholder text in design and publishing, is to create a natural-looking block of text that doesn't distract from the layout. It allows designers to visualize how text will appear in a design without the need for actual content to be written and approved. Lorem Ipsum helps in planning out where the content will sit on a page, focusing on the design rather than the specific content. This practice is particularly useful when the main emphasis is on the visual layout, allowing designers and clients to review templates without being distracted by the actual copy on the page
-4
-5
-.
-hello
-`;
-
export default function Main({ sidebarOpen }: { sidebarOpen: boolean }) {
const searchParams = useSearchParams();
const router = useRouter();
@@ -220,7 +198,7 @@ export default function Main({ sidebarOpen }: { sidebarOpen: boolean }) {
...lastMessage,
answer: {
parts: lastMessage.answer.parts,
- sources: sourcesInJson.ids ?? [],
+ sources: getIdsFromSource(sourcesInJson.ids) ?? [],
},
},
];
@@ -289,12 +267,19 @@ export default function Main({ sidebarOpen }: { sidebarOpen: boolean }) {
data-sidebar-open={sidebarOpen}
ref={main}
className={cn(
- "sidebar flex w-full flex-col items-end justify-center gap-5 px-5 pt-5 transition-[padding-left,padding-top,padding-right] delay-200 duration-200 md:items-center md:gap-10 md:px-72 [&[data-sidebar-open='true']]:pr-10 [&[data-sidebar-open='true']]:delay-0 md:[&[data-sidebar-open='true']]:pl-[calc(2.5rem+30vw)]",
+ "sidebar relative flex w-full flex-col items-end justify-center gap-5 px-5 pt-5 transition-[padding-left,padding-top,padding-right] delay-200 duration-200 md:items-center md:gap-10 md:px-72 [&[data-sidebar-open='true']]:pr-10 [&[data-sidebar-open='true']]:delay-0 md:[&[data-sidebar-open='true']]:pl-[calc(2.5rem+30vw)]",
hide ? "" : "main-hidden",
)}
>
- <h1 className="text-rgray-11 mt-auto w-full text-center text-3xl md:mt-0">
- Ask your Second brain
+ <Image
+ className="absolute right-10 top-10 rounded-md"
+ src="/icons/logo_bw_without_bg.png"
+ alt="Smort logo"
+ width={50}
+ height={50}
+ />
+ <h1 className="text-rgray-11 mt-auto w-full text-center text-3xl font-bold tracking-tight md:mt-0">
+ Ask your second brain
</h1>
<Textarea2
@@ -308,7 +293,7 @@ export default function Main({ sidebarOpen }: { sidebarOpen: boolean }) {
duration: 0.2,
}}
textAreaProps={{
- placeholder: "Ask your SuperMemory...",
+ placeholder: "Ask your second brain...",
className:
"h-auto overflow-auto md:h-full md:resize-none text-lg py-0 px-2 pt-2 md:py-0 md:p-5 resize-y text-rgray-11 w-full min-h-[1em]",
value,
@@ -322,7 +307,8 @@ export default function Main({ sidebarOpen }: { sidebarOpen: boolean }) {
}}
>
<div className="text-rgray-11/70 flex h-full w-fit items-center justify-center pl-0 md:w-full md:p-2">
- <FilterCombobox
+ <FilterSpaces
+ name={"Filter"}
onClose={() => {
textArea.current?.querySelector("textarea")?.focus();
}}
@@ -397,7 +383,8 @@ export function Chat({
className="absolute flex w-full items-center justify-center"
>
<div className="animate-from-top fixed bottom-10 mt-auto flex w-[50%] flex-col items-start justify-center gap-2">
- <FilterCombobox
+ <FilterSpaces
+ name={"Filter"}
onClose={() => {
textArea.current?.querySelector("textarea")?.focus();
}}
diff --git a/apps/web/src/components/QueryAI.tsx b/apps/web/src/components/QueryAI.tsx
deleted file mode 100644
index 894b5d2d..00000000
--- a/apps/web/src/components/QueryAI.tsx
+++ /dev/null
@@ -1,139 +0,0 @@
-"use client";
-
-import { Label } from "./ui/label";
-import React, { useEffect, useState } from "react";
-import { Input } from "./ui/input";
-import { Button } from "./ui/button";
-import SearchResults from "./SearchResults";
-
-function QueryAI() {
- const [searchResults, setSearchResults] = useState<string[]>([]);
- const [isAiLoading, setIsAiLoading] = useState(false);
-
- const [aiResponse, setAIResponse] = useState("");
- const [input, setInput] = useState("");
- const [toBeParsed, setToBeParsed] = useState("");
-
- const handleStreamData = (newChunk: string) => {
- // Append the new chunk to the existing data to be parsed
- setToBeParsed((prev) => prev + newChunk);
- };
-
- useEffect(() => {
- // Define a function to try parsing the accumulated data
- const tryParseAccumulatedData = () => {
- // Attempt to parse the "toBeParsed" state as JSON
- try {
- // Split the accumulated data by the known delimiter "\n\n"
- const parts = toBeParsed.split("\n\n");
- let remainingData = "";
-
- // Process each part to extract JSON objects
- parts.forEach((part, index) => {
- try {
- const parsedPart = JSON.parse(part.replace("data: ", "")); // Try to parse the part as JSON
-
- // If the part is the last one and couldn't be parsed, keep it to accumulate more data
- if (index === parts.length - 1 && !parsedPart) {
- remainingData = part;
- } else if (parsedPart && parsedPart.response) {
- // If the part is parsable and has the "response" field, update the AI response state
- setAIResponse((prev) => prev + parsedPart.response);
- }
- } catch (error) {
- // If parsing fails and it's not the last part, it's a malformed JSON
- if (index !== parts.length - 1) {
- console.error("Malformed JSON part: ", part);
- } else {
- // If it's the last part, it may be incomplete, so keep it
- remainingData = part;
- }
- }
- });
-
- // Update the toBeParsed state to only contain the unparsed remainder
- if (remainingData !== toBeParsed) {
- setToBeParsed(remainingData);
- }
- } catch (error) {
- console.error("Error parsing accumulated data: ", error);
- }
- };
-
- // Call the parsing function if there's data to be parsed
- if (toBeParsed) {
- tryParseAccumulatedData();
- }
- }, [toBeParsed]);
-
- const getSearchResults = async (e: React.FormEvent<HTMLFormElement>) => {
- e.preventDefault();
- setIsAiLoading(true);
-
- const sourcesResponse = await fetch(
- `/api/query?sourcesOnly=true&q=${input}`,
- );
-
- const sourcesInJson = (await sourcesResponse.json()) as {
- ids: string[];
- };
-
- setSearchResults(sourcesInJson.ids);
-
- const response = await fetch(`/api/query?q=${input}`);
-
- if (response.status !== 200) {
- setIsAiLoading(false);
- return;
- }
-
- if (response.body) {
- let reader = response.body.getReader();
- let decoder = new TextDecoder("utf-8");
- let result = "";
-
- // @ts-ignore
- reader.read().then(function processText({ done, value }) {
- if (done) {
- // setSearchResults(JSON.parse(result.replace('data: ', '')));
- // setIsAiLoading(false);
- return;
- }
-
- handleStreamData(decoder.decode(value));
-
- return reader.read().then(processText);
- });
- }
- };
-
- return (
- <div className="mx-auto w-full max-w-2xl">
- <form onSubmit={async (e) => await getSearchResults(e)} className="mt-8">
- <Label htmlFor="searchInput">Ask your SuperMemory</Label>
- <div className="flex flex-col space-y-2 md:w-full md:flex-row md:items-center md:space-x-2 md:space-y-0">
- <Input
- value={input}
- onChange={(e) => setInput(e.target.value)}
- placeholder="Search using AI... ✨"
- id="searchInput"
- />
- <Button
- disabled={isAiLoading}
- className="max-w-min md:w-full"
- type="submit"
- variant="default"
- >
- Ask AI
- </Button>
- </div>
- </form>
-
- {searchResults && (
- <SearchResults aiResponse={aiResponse} sources={searchResults} />
- )}
- </div>
- );
-}
-
-export default QueryAI;
diff --git a/apps/web/src/components/Sidebar.tsx b/apps/web/src/components/Sidebar.tsx
deleted file mode 100644
index bdc9d600..00000000
--- a/apps/web/src/components/Sidebar.tsx
+++ /dev/null
@@ -1,145 +0,0 @@
-"use client";
-import { StoredContent } from "@/server/db/schema";
-import {
- Plus,
- MoreHorizontal,
- ArrowUpRight,
- Edit3,
- Trash2,
-} from "lucide-react";
-import {
- DropdownMenu,
- DropdownMenuContent,
- DropdownMenuItem,
- DropdownMenuTrigger,
-} from "./ui/dropdown-menu";
-
-import { useState, useEffect, useRef } from "react";
-
-export default function Sidebar() {
- const websites: StoredContent[] = [
- {
- id: 1,
- content: "",
- title: "Visual Studio Code",
- url: "https://code.visualstudio.com",
- description: "",
- image: "https://code.visualstudio.com/favicon.ico",
- baseUrl: "https://code.visualstudio.com",
- savedAt: new Date(),
- },
- {
- id: 1,
- content: "",
- title: "yxshv/vscode: An unofficial remake of vscode's landing page",
- url: "https://github.com/yxshv/vscode",
- description: "",
- image: "https://github.com/favicon.ico",
- baseUrl: "https://github.com",
- savedAt: new Date(),
- },
- ];
-
- return (
- <aside className="bg-rgray-3 flex h-screen w-[25%] flex-col items-start justify-between py-5 pb-[50vh] font-light">
- <div className="flex items-center justify-center gap-1 px-5 text-xl font-normal">
- <img src="/brain.png" alt="logo" className="h-10 w-10" />
- SuperMemory
- </div>
- <div className="flex w-full flex-col items-start justify-center p-2">
- <h1 className="mb-1 flex w-full items-center justify-center px-3 font-normal">
- Websites
- <button className="ml-auto ">
- <Plus className="h-4 w-4 min-w-4" />
- </button>
- </h1>
- {websites.map((item) => (
- <ListItem key={item.id} item={item} />
- ))}
- </div>
- </aside>
- );
-}
-
-export const ListItem: React.FC<{ item: StoredContent }> = ({ item }) => {
- const [isEditing, setIsEditing] = useState(false);
- const editInputRef = useRef<HTMLInputElement>(null);
-
- useEffect(() => {
- if (isEditing) {
- setTimeout(() => {
- editInputRef.current?.focus();
- }, 500);
- }
- }, [isEditing]);
-
- return (
- <div className="hover:bg-rgray-5 focus-within:bg-rgray-5 flex w-full items-center rounded-full py-1 pl-3 pr-2 transition [&:hover>a>[data-upright-icon]]:block [&:hover>a>img]:hidden [&:hover>button]:opacity-100">
- <a
- href={item.url}
- target="_blank"
- onClick={(e) => isEditing && e.preventDefault()}
- className="flex w-[90%] items-center gap-2 focus:outline-none"
- >
- {isEditing ? (
- <Edit3 className="h-4 w-4" strokeWidth={1.5} />
- ) : (
- <>
- <img
- src={item.image ?? "/brain.png"}
- alt={item.title ?? "Untitiled website"}
- className="h-4 w-4"
- />
- <ArrowUpRight
- data-upright-icon
- className="hidden h-4 w-4 min-w-4 scale-125"
- strokeWidth={1.5}
- />
- </>
- )}
- {isEditing ? (
- <input
- ref={editInputRef}
- autoFocus
- className="text-rgray-12 w-full bg-transparent focus:outline-none"
- placeholder={item.title ?? "Untitled website"}
- onBlur={(e) => setIsEditing(false)}
- onKeyDown={(e) => e.key === "Escape" && setIsEditing(false)}
- />
- ) : (
- <span className="w-full truncate text-nowrap">
- {item.title ?? "Untitled website"}
- </span>
- )}
- </a>
- <DropdownMenu>
- <DropdownMenuTrigger asChild>
- <button className="ml-auto w-4 min-w-4 rounded-[0.15rem] opacity-0 focus:opacity-100 focus:outline-none">
- <MoreHorizontal className="h-4 w-4 min-w-4" />
- </button>
- </DropdownMenuTrigger>
- <DropdownMenuContent className="w-5">
- <DropdownMenuItem onClick={() => window.open(item.url)}>
- <ArrowUpRight
- className="mr-2 h-4 w-4 scale-125"
- strokeWidth={1.5}
- />
- Open
- </DropdownMenuItem>
- <DropdownMenuItem
- onClick={(e) => {
- setIsEditing(true);
- }}
- >
- <Edit3 className="mr-2 h-4 w-4 " strokeWidth={1.5} />
- Edit
- </DropdownMenuItem>
- <DropdownMenuItem className="focus:bg-red-100 focus:text-red-400 dark:focus:bg-red-100/10">
- <Trash2 className="mr-2 h-4 w-4 " strokeWidth={1.5} />
- Delete
- </DropdownMenuItem>
- </DropdownMenuContent>
- </DropdownMenu>
- </div>
- );
-};
diff --git a/apps/web/src/components/Sidebar/AddMemoryDialog.tsx b/apps/web/src/components/Sidebar/AddMemoryDialog.tsx
new file mode 100644
index 00000000..886507ff
--- /dev/null
+++ b/apps/web/src/components/Sidebar/AddMemoryDialog.tsx
@@ -0,0 +1,213 @@
+import { Editor } from "novel";
+import {
+ DialogClose,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+} from "../ui/dialog";
+import { Input } from "../ui/input";
+import { Label } from "../ui/label";
+import { Markdown } from "tiptap-markdown";
+import { useEffect, useRef, useState } from "react";
+import { FilterSpaces } from "./FilterCombobox";
+import { useMemory } from "@/contexts/MemoryContext";
+
+export function AddMemoryPage() {
+ const { addMemory } = useMemory();
+
+ const [url, setUrl] = useState("");
+ const [selectedSpacesId, setSelectedSpacesId] = useState<number[]>([]);
+
+ return (
+ <form className="md:w-[40vw]">
+ <DialogHeader>
+ <DialogTitle>Add a web page to memory</DialogTitle>
+ <DialogDescription>
+ This will take you the web page you are trying to add to memory, where
+ the extension will save the page to memory
+ </DialogDescription>
+ </DialogHeader>
+ <Label className="mt-5 block">URL</Label>
+ <Input
+ placeholder="Enter the URL of the page"
+ type="url"
+ data-modal-autofocus
+ className="bg-rgray-4 mt-2 w-full"
+ value={url}
+ onChange={(e) => setUrl(e.target.value)}
+ />
+ <DialogFooter>
+ <FilterSpaces
+ selectedSpaces={selectedSpacesId}
+ setSelectedSpaces={setSelectedSpacesId}
+ className="hover:bg-rgray-5 mr-auto bg-white/5"
+ name={"Spaces"}
+ />
+ <button
+ type={"submit"}
+ onClick={async () => {
+ // @Dhravya this is adding a memory with insufficient information fix pls
+ await addMemory(
+ {
+ title: url,
+ content: "",
+ type: "page",
+ url: url,
+ image: "/icons/logo_without_bg.png",
+ savedAt: new Date(),
+ },
+ selectedSpacesId,
+ );
+ }}
+ className="bg-rgray-4 hover:bg-rgray-5 focus-visible:bg-rgray-5 focus-visible:ring-rgray-7 rounded-md px-4 py-2 ring-transparent transition focus-visible:outline-none focus-visible:ring-2"
+ >
+ Add
+ </button>
+ <DialogClose className="hover:bg-rgray-4 focus-visible:bg-rgray-4 focus-visible:ring-rgray-7 rounded-md px-3 py-2 ring-transparent transition focus-visible:outline-none focus-visible:ring-2">
+ Cancel
+ </DialogClose>
+ </DialogFooter>
+ </form>
+ );
+}
+
+export function NoteAddPage({ closeDialog }: { closeDialog: () => void }) {
+ const [selectedSpacesId, setSelectedSpacesId] = useState<number[]>([]);
+
+ const inputRef = useRef<HTMLInputElement>(null);
+ const [name, setName] = useState("");
+ const [content, setContent] = useState("");
+ const [loading, setLoading] = useState(false);
+
+ function check(): boolean {
+ const data = {
+ name: name.trim(),
+ content,
+ };
+ 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 (
+ <div>
+ <Input
+ ref={inputRef}
+ data-error="false"
+ className="w-full border-none p-0 text-xl ring-0 placeholder:text-white/30 placeholder:transition placeholder:duration-500 focus-visible:ring-0 data-[error=true]:placeholder:text-red-400"
+ placeholder="Title of the note"
+ data-modal-autofocus
+ value={name}
+ onChange={(e) => setName(e.target.value)}
+ />
+ <Editor
+ disableLocalStorage
+ defaultValue={""}
+ onUpdate={(editor) => {
+ if (!editor) return;
+ setContent(editor.storage.markdown.getMarkdown());
+ }}
+ extensions={[Markdown]}
+ className="novel-editor bg-rgray-4 border-rgray-7 dark mt-5 max-h-[60vh] min-h-[40vh] w-[50vw] overflow-y-auto rounded-lg border [&>div>div]:p-5"
+ />
+ <DialogFooter>
+ <FilterSpaces
+ selectedSpaces={selectedSpacesId}
+ setSelectedSpaces={setSelectedSpacesId}
+ className="hover:bg-rgray-5 mr-auto bg-white/5"
+ name={"Spaces"}
+ />
+ <button
+ onClick={() => {
+ if (check()) {
+ closeDialog();
+ }
+ }}
+ className="bg-rgray-4 hover:bg-rgray-5 focus-visible:bg-rgray-5 focus-visible:ring-rgray-7 rounded-md px-4 py-2 ring-transparent transition focus-visible:outline-none focus-visible:ring-2"
+ >
+ Add
+ </button>
+ <DialogClose
+ type={undefined}
+ className="hover:bg-rgray-4 focus-visible:bg-rgray-4 focus-visible:ring-rgray-7 rounded-md px-3 py-2 ring-transparent transition focus-visible:outline-none focus-visible:ring-2"
+ >
+ Cancel
+ </DialogClose>
+ </DialogFooter>
+ </div>
+ );
+}
+
+export function SpaceAddPage({ closeDialog }: { closeDialog: () => void }) {
+ const [selectedSpacesId, setSelectedSpacesId] = useState<number[]>([]);
+
+ const inputRef = useRef<HTMLInputElement>(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 (
+ <div className="md:w-[40vw]">
+ <DialogHeader>
+ <DialogTitle>Add a space</DialogTitle>
+ </DialogHeader>
+ <Label className="mt-5 block">Name</Label>
+ <Input
+ placeholder="Enter the name of the space"
+ type="url"
+ data-modal-autofocus
+ className="bg-rgray-4 mt-2 w-full"
+ />
+ <Label className="mt-5 block">Memories</Label>
+ <DialogFooter>
+ <DialogClose
+ type={undefined}
+ className="bg-rgray-4 hover:bg-rgray-5 focus-visible:bg-rgray-5 focus-visible:ring-rgray-7 rounded-md px-4 py-2 ring-transparent transition focus-visible:outline-none focus-visible:ring-2"
+ >
+ Add
+ </DialogClose>
+ <DialogClose className="hover:bg-rgray-4 focus-visible:bg-rgray-4 focus-visible:ring-rgray-7 rounded-md px-3 py-2 ring-transparent transition focus-visible:outline-none focus-visible:ring-2">
+ Cancel
+ </DialogClose>
+ </DialogFooter>
+ </div>
+ );
+}
diff --git a/apps/web/src/components/Sidebar/FilterCombobox.tsx b/apps/web/src/components/Sidebar/FilterCombobox.tsx
index a8e3a1e5..0a93ee55 100644
--- a/apps/web/src/components/Sidebar/FilterCombobox.tsx
+++ b/apps/web/src/components/Sidebar/FilterCombobox.tsx
@@ -30,19 +30,137 @@ export interface Props extends React.ButtonHTMLAttributes<HTMLButtonElement> {
setSelectedSpaces: (
spaces: number[] | ((prev: number[]) => number[]),
) => void;
+ name: string;
}
-export function FilterCombobox({
+export function FilterSpaces({
className,
side = "bottom",
align = "center",
onClose,
selectedSpaces,
setSelectedSpaces,
+ name,
...props
}: Props) {
- const { spaces, addSpace } = useMemory();
+ const { spaces } = useMemory();
+ const [open, setOpen] = React.useState(false);
+
+ const sortedSpaces = spaces.sort(({ id: a }, { id: b }) =>
+ selectedSpaces.includes(a) && !selectedSpaces.includes(b)
+ ? -1
+ : selectedSpaces.includes(b) && !selectedSpaces.includes(a)
+ ? 1
+ : 0,
+ );
+
+ React.useEffect(() => {
+ if (!open) {
+ onClose?.();
+ }
+ }, [open]);
+ return (
+ <AnimatePresence mode="popLayout">
+ <LayoutGroup>
+ <Popover open={open} onOpenChange={setOpen}>
+ <PopoverTrigger asChild>
+ <button
+ type={undefined}
+ data-state-on={open}
+ className={cn(
+ "text-rgray-11/70 on:bg-rgray-3 focus-visible:ring-rgray-8 hover:bg-rgray-3 relative flex items-center justify-center gap-1 rounded-md px-3 py-1.5 ring-2 ring-transparent focus-visible:outline-none",
+ className,
+ )}
+ {...props}
+ >
+ <SpaceIcon className="mr-1 h-5 w-5" />
+ {name}
+ <ChevronsUpDown className="h-4 w-4" />
+ <div
+ data-state-on={selectedSpaces.length > 0}
+ className="on:flex text-rgray-11 border-rgray-6 bg-rgray-2 absolute left-0 top-0 hidden aspect-[1] h-4 w-4 -translate-x-1/3 -translate-y-1/3 items-center justify-center rounded-full border text-center text-[9px]"
+ >
+ {selectedSpaces.length}
+ </div>
+ </button>
+ </PopoverTrigger>
+ <PopoverContent
+ onCloseAutoFocus={(e) => e.preventDefault()}
+ align={align}
+ side={side}
+ className="w-[200px] p-0"
+ >
+ <Command
+ filter={(val, search) =>
+ spaces
+ .find((s) => s.id.toString() === val)
+ ?.title.toLowerCase()
+ .includes(search.toLowerCase().trim())
+ ? 1
+ : 0
+ }
+ >
+ <CommandInput placeholder="Filter spaces..." />
+ <CommandList asChild>
+ <motion.div layoutScroll>
+ <CommandEmpty>Nothing found</CommandEmpty>
+ <CommandGroup>
+ {sortedSpaces.map((space) => (
+ <CommandItem
+ key={space.id}
+ value={space.id.toString()}
+ onSelect={(val) => {
+ setSelectedSpaces((prev: number[]) =>
+ prev.includes(parseInt(val))
+ ? prev.filter((v) => v !== parseInt(val))
+ : [...prev, parseInt(val)],
+ );
+ }}
+ asChild
+ >
+ <motion.div
+ initial={{ opacity: 0 }}
+ animate={{ opacity: 1, transition: { delay: 0.05 } }}
+ transition={{ duration: 0.15 }}
+ layout
+ layoutId={`space-combobox-${space.id}`}
+ className="text-rgray-11"
+ >
+ <SpaceIcon className="mr-2 h-4 w-4" />
+ {space.title}
+ {selectedSpaces.includes(space.id)}
+ <Check
+ data-state-on={selectedSpaces.includes(space.id)}
+ className={cn(
+ "on:opacity-100 ml-auto h-4 w-4 opacity-0",
+ )}
+ />
+ </motion.div>
+ </CommandItem>
+ ))}
+ </CommandGroup>
+ </motion.div>
+ </CommandList>
+ </Command>
+ </PopoverContent>
+ </Popover>
+ </LayoutGroup>
+ </AnimatePresence>
+ );
+}
+
+export function FilterMemories({
+ className,
+ side = "bottom",
+ align = "center",
+ onClose,
+ selectedSpaces,
+ setSelectedSpaces,
+ name,
+ ...props
+}: Props) {
+ const { spaces } = useMemory();
const [open, setOpen] = React.useState(false);
const sortedSpaces = spaces.sort(({ id: a }, { id: b }) =>
@@ -65,6 +183,7 @@ export function FilterCombobox({
<Popover open={open} onOpenChange={setOpen}>
<PopoverTrigger asChild>
<button
+ type={undefined}
data-state-on={open}
className={cn(
"text-rgray-11/70 on:bg-rgray-3 focus-visible:ring-rgray-8 hover:bg-rgray-3 relative flex items-center justify-center gap-1 rounded-md px-3 py-1.5 ring-2 ring-transparent focus-visible:outline-none",
@@ -73,7 +192,7 @@ export function FilterCombobox({
{...props}
>
<SpaceIcon className="mr-1 h-5 w-5" />
- Filter
+ {name}
<ChevronsUpDown className="h-4 w-4" />
<div
data-state-on={selectedSpaces.length > 0}
diff --git a/apps/web/src/components/Sidebar/MemoriesBar.tsx b/apps/web/src/components/Sidebar/MemoriesBar.tsx
index d7d8b5b5..66c3138b 100644
--- a/apps/web/src/components/Sidebar/MemoriesBar.tsx
+++ b/apps/web/src/components/Sidebar/MemoriesBar.tsx
@@ -1,3 +1,4 @@
+import { Editor } from "novel";
import { useAutoAnimate } from "@formkit/auto-animate/react";
import {
MemoryWithImage,
@@ -22,7 +23,7 @@ import {
DropdownMenuItem,
DropdownMenuTrigger,
} from "../ui/dropdown-menu";
-import { useState } from "react";
+import { useEffect, useRef, useState } from "react";
import { Variant, useAnimate, motion } from "framer-motion";
import { useMemory } from "@/contexts/MemoryContext";
import { SpaceIcon } from "@/assets/Memories";
@@ -38,6 +39,8 @@ import {
import { Label } from "../ui/label";
import useViewport from "@/hooks/useViewport";
import useTouchHold from "@/hooks/useTouchHold";
+import { DialogTrigger } from "@radix-ui/react-dialog";
+import { AddMemoryPage, NoteAddPage, SpaceAddPage } from "./AddMemoryDialog";
export function MemoriesBar() {
const [parent, enableAnimations] = useAutoAnimate();
@@ -59,38 +62,49 @@ export function MemoriesBar() {
/>
</div>
<div className="mt-2 flex w-full px-8">
- <DropdownMenu open={isDropdownOpen} onOpenChange={setIsDropdownOpen}>
- <DropdownMenuTrigger asChild>
- <button className="focus-visible:bg-rgray-4 focus-visible:ring-rgray-7 hover:bg-rgray-4 ml-auto flex items-center justify-center rounded-md px-3 py-2 transition focus-visible:outline-none focus-visible:ring-2">
- <Plus className="mr-2 h-5 w-5" />
- Add
- </button>
- </DropdownMenuTrigger>
- <DropdownMenuContent>
- <DropdownMenuItem
- onClick={() => {
- setIsDropdownOpen(false);
- setAddMemoryState("page");
- }}
- >
- <Sparkles className="mr-2 h-4 w-4" />
- Page to Memory
- </DropdownMenuItem>
- <DropdownMenuItem>
- <Text className="mr-2 h-4 w-4" />
- Note
- </DropdownMenuItem>
- <DropdownMenuItem>
- <SpaceIcon className="mr-2 h-4 w-4" />
- Space
- </DropdownMenuItem>
- </DropdownMenuContent>
- </DropdownMenu>
+ <AddMemoryModal type={addMemoryState}>
+ <DropdownMenu open={isDropdownOpen} onOpenChange={setIsDropdownOpen}>
+ <DropdownMenuTrigger asChild>
+ <button className="focus-visible:bg-rgray-4 focus-visible:ring-rgray-7 hover:bg-rgray-4 ml-auto flex items-center justify-center rounded-md px-3 py-2 transition focus-visible:outline-none focus-visible:ring-2">
+ <Plus className="mr-2 h-5 w-5" />
+ Add
+ </button>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent onCloseAutoFocus={(e) => e.preventDefault()}>
+ <DialogTrigger className="block w-full">
+ <DropdownMenuItem
+ onClick={() => {
+ setAddMemoryState("page");
+ }}
+ >
+ <Sparkles className="mr-2 h-4 w-4" />
+ Page to Memory
+ </DropdownMenuItem>
+ </DialogTrigger>
+ <DialogTrigger className="block w-full">
+ <DropdownMenuItem
+ onClick={() => {
+ setAddMemoryState("note");
+ }}
+ >
+ <Text className="mr-2 h-4 w-4" />
+ Note
+ </DropdownMenuItem>
+ </DialogTrigger>
+ <DialogTrigger className="block w-full">
+ <DropdownMenuItem
+ onClick={() => {
+ setAddMemoryState("space");
+ }}
+ >
+ <SpaceIcon className="mr-2 h-4 w-4" />
+ Space
+ </DropdownMenuItem>
+ </DialogTrigger>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ </AddMemoryModal>
</div>
- <AddMemoryModal
- state={addMemoryState}
- onStateChange={setAddMemoryState}
- />
<div
ref={parent}
className="grid w-full grid-flow-row grid-cols-3 gap-1 px-2 py-5"
@@ -295,69 +309,52 @@ export function SpaceMoreButton({
}
export function AddMemoryModal({
- state,
- onStateChange,
+ type,
+ children,
}: {
- state: "page" | "note" | "space" | null;
- onStateChange: (state: "page" | "note" | "space" | null) => void;
+ type: "page" | "note" | "space" | null;
+ children?: React.ReactNode | React.ReactNode[];
}) {
+ const [isDialogOpen, setIsDialogOpen] = useState(false);
+
return (
- <>
- <Dialog
- open={state === "page"}
- onOpenChange={(open) => onStateChange(open ? "page" : null)}
+ <Dialog open={isDialogOpen} onOpenChange={setIsDialogOpen}>
+ {children}
+ <DialogContent
+ onOpenAutoFocus={(e) => {
+ e.preventDefault();
+ const novel = document.querySelector('[contenteditable="true"]') as
+ | HTMLDivElement
+ | undefined;
+ if (novel) {
+ novel.autofocus = false;
+ novel.onfocus = () => {
+ (
+ document.querySelector("[data-modal-autofocus]") as
+ | HTMLInputElement
+ | undefined
+ )?.focus();
+ novel.onfocus = null;
+ };
+ }
+ (
+ document.querySelector("[data-modal-autofocus]") as
+ | HTMLInputElement
+ | undefined
+ )?.focus();
+ }}
+ className="w-max max-w-[auto]"
>
- <DialogContent>
- <DialogHeader>
- <DialogTitle>Add a web page to memory</DialogTitle>
- <DialogDescription>
- This will take you the web page you are trying to add to memory,
- where the extension will save the page to memory
- </DialogDescription>
- </DialogHeader>
- <Label className="mt-5">URL</Label>
- <Input
- autoFocus
- placeholder="Enter the URL of the page"
- type="url"
- className="bg-rgray-4 mt-2 w-full"
- />
- <DialogFooter>
- <DialogClose className="bg-rgray-4 hover:bg-rgray-5 focus-visible:bg-rgray-5 focus-visible:ring-rgray-7 rounded-md px-4 py-2 ring-transparent transition focus-visible:outline-none focus-visible:ring-2">
- Add
- </DialogClose>
- <DialogClose className="hover:bg-rgray-4 focus-visible:bg-rgray-4 focus-visible:ring-rgray-7 rounded-md px-3 py-2 ring-transparent transition focus-visible:outline-none focus-visible:ring-2">
- Cancel
- </DialogClose>
- </DialogFooter>
- </DialogContent>
- </Dialog>
- <Dialog open={state === "note"}>
- <DialogContent>
- <DialogHeader>
- <DialogTitle>Add a web page to memory</DialogTitle>
- <DialogDescription>
- This will take you the web page you are trying to add to memory,
- where the extension will save the page to memory
- </DialogDescription>
- </DialogHeader>
- <Label className="mt-5">URL</Label>
- <Input
- autoFocus
- placeholder="Enter the URL of the page"
- type="url"
- className="bg-rgray-4 mt-2 w-full"
- />
- <DialogFooter>
- <DialogClose className="bg-rgray-4 hover:bg-rgray-5 focus-visible:bg-rgray-5 focus-visible:ring-rgray-7 rounded-md px-4 py-2 ring-transparent transition focus-visible:outline-none focus-visible:ring-2">
- Add
- </DialogClose>
- <DialogClose className="hover:bg-rgray-4 focus-visible:bg-rgray-4 focus-visible:ring-rgray-7 rounded-md px-3 py-2 ring-transparent transition focus-visible:outline-none focus-visible:ring-2">
- Cancel
- </DialogClose>
- </DialogFooter>
- </DialogContent>
- </Dialog>
- </>
+ {type === "page" ? (
+ <AddMemoryPage />
+ ) : type === "note" ? (
+ <NoteAddPage closeDialog={() => setIsDialogOpen(false)} />
+ ) : type === "space" ? (
+ <SpaceAddPage closeDialog={() => setIsDialogOpen(false)} />
+ ) : (
+ <></>
+ )}
+ </DialogContent>
+ </Dialog>
);
}
diff --git a/apps/web/src/components/Sidebar/index.tsx b/apps/web/src/components/Sidebar/index.tsx
index 965455e6..1487e113 100644
--- a/apps/web/src/components/Sidebar/index.tsx
+++ b/apps/web/src/components/Sidebar/index.tsx
@@ -13,6 +13,7 @@ export type MenuItem = {
icon: React.ReactNode | React.ReactNode[];
label: string;
content?: React.ReactNode;
+ labelDisplay?: React.ReactNode;
};
export default function Sidebar({
@@ -73,7 +74,7 @@ export default function Sidebar({
return (
<>
<div className="relative hidden h-screen max-h-screen w-max flex-col items-center text-sm font-light md:flex">
- <div className="bg-rgray-2 border-r-rgray-6 relative z-[50] flex h-full w-full flex-col items-center justify-center border-r px-2 py-5 ">
+ <div className="bg-rgray-3 border-r-rgray-6 relative z-[50] flex h-full w-full flex-col items-center justify-center border-r px-2 py-5 ">
<MenuItem
item={{
label: "Memories",
@@ -83,9 +84,7 @@ export default function Sidebar({
selectedItem={selectedItem}
setSelectedItem={setSelectedItem}
/>
-
<div className="mt-auto" />
-
<MenuItem
item={{
label: "Trash",
@@ -131,7 +130,7 @@ export default function Sidebar({
}
const MenuItem = ({
- item: { icon, label },
+ item: { icon, label, labelDisplay },
selectedItem,
setSelectedItem,
...props
@@ -147,7 +146,7 @@ const MenuItem = ({
{...props}
>
{icon}
- <span className="">{label}</span>
+ <span className="">{labelDisplay ?? label}</span>
</button>
);
diff --git a/apps/web/src/components/WordMark.tsx b/apps/web/src/components/WordMark.tsx
new file mode 100644
index 00000000..eb55647c
--- /dev/null
+++ b/apps/web/src/components/WordMark.tsx
@@ -0,0 +1,12 @@
+import { cn } from "@/lib/utils";
+import React from "react";
+
+function WordMark({ className }: { className?: string }) {
+ return (
+ <span className={cn(`text-xl font-bold tracking-tight ${className}`)}>
+ smort.
+ </span>
+ );
+}
+
+export default WordMark;
diff --git a/apps/web/src/contexts/MemoryContext.tsx b/apps/web/src/contexts/MemoryContext.tsx
index eab1e4fe..68a22434 100644
--- a/apps/web/src/contexts/MemoryContext.tsx
+++ b/apps/web/src/contexts/MemoryContext.tsx
@@ -1,22 +1,37 @@
"use client";
import React, { useCallback } from "react";
import { CollectedSpaces } from "../../types/memory";
+import { StoredContent, storedContent } from "@/server/db/schema";
+import { useSession } from "next-auth/react";
+import { addMemory } from "@/actions/db";
// temperory (will change)
export const MemoryContext = React.createContext<{
spaces: CollectedSpaces[];
deleteSpace: (id: number) => Promise<void>;
+ freeMemories: StoredContent[];
addSpace: (space: CollectedSpaces) => Promise<void>;
+ addMemory: (
+ memory: typeof storedContent.$inferInsert,
+ spaces?: number[],
+ ) => Promise<void>;
}>({
spaces: [],
- addSpace: async (space) => {},
- deleteSpace: async (id) => {},
+ freeMemories: [],
+ addMemory: async () => {},
+ addSpace: async () => {},
+ deleteSpace: async () => {},
});
export const MemoryProvider: React.FC<
- { spaces: CollectedSpaces[] } & React.PropsWithChildren
-> = ({ children, spaces: initalSpaces }) => {
+ {
+ spaces: CollectedSpaces[];
+ freeMemories: StoredContent[];
+ } & React.PropsWithChildren
+> = ({ children, spaces: initalSpaces, freeMemories: initialFreeMemories }) => {
const [spaces, setSpaces] = React.useState<CollectedSpaces[]>(initalSpaces);
+ const [freeMemories, setFreeMemories] =
+ React.useState<StoredContent[]>(initialFreeMemories);
const addSpace = useCallback(
async (space: CollectedSpaces) => {
@@ -31,8 +46,31 @@ export const MemoryProvider: React.FC<
[spaces],
);
+ // const fetchMemories = useCallback(async (query: string) => {
+ // const response = await fetch(`/api/memories?${query}`);
+ // }, []);
+
+ const _addMemory = useCallback(
+ async (
+ memory: typeof storedContent.$inferInsert,
+ spaces: number[] = [],
+ ) => {
+ const content = await addMemory(memory, spaces);
+ console.log(content);
+ },
+ [freeMemories, spaces],
+ );
+
return (
- <MemoryContext.Provider value={{ spaces, addSpace, deleteSpace }}>
+ <MemoryContext.Provider
+ value={{
+ spaces,
+ addSpace,
+ deleteSpace,
+ freeMemories,
+ addMemory: _addMemory,
+ }}
+ >
{children}
</MemoryContext.Provider>
);
diff --git a/apps/web/src/lib/utils.ts b/apps/web/src/lib/utils.ts
index 5eca08cc..4f34e990 100644
--- a/apps/web/src/lib/utils.ts
+++ b/apps/web/src/lib/utils.ts
@@ -18,6 +18,11 @@ export function cleanUrl(url: string) {
: url;
}
+export function getIdsFromSource(sourceIds: string[]) {
+ // This function converts an id from a form of `websiteURL-userID` to just the websiteURL
+ return sourceIds.map((id) => id.split("-").slice(0, -1).join("-"));
+}
+
export function generateId() {
return Math.random().toString(36).slice(2, 9);
}
diff --git a/apps/web/src/server/db/schema.ts b/apps/web/src/server/db/schema.ts
index e0ddbdbc..ea90e5e9 100644
--- a/apps/web/src/server/db/schema.ts
+++ b/apps/web/src/server/db/schema.ts
@@ -88,6 +88,9 @@ export const storedContent = createTable(
url: text("url").notNull(),
savedAt: int("savedAt", { mode: "timestamp" }).notNull(),
baseUrl: text("baseUrl", { length: 255 }),
+ type: text("type", { enum: ["note", "page", "twitter-bookmark"] }).default(
+ "page",
+ ),
image: text("image", { length: 255 }),
user: text("user", { length: 255 }).references(() => users.id),
},
@@ -118,7 +121,7 @@ export const space = createTable(
"space",
{
id: integer("id").notNull().primaryKey({ autoIncrement: true }),
- name: text("name").notNull().default("all"),
+ name: text("name").notNull().unique().default("none"),
user: text("user", { length: 255 }).references(() => users.id),
},
(space) => ({