This commit is contained in:
yxshv 2024-04-11 16:37:46 +05:30
commit 539f50367d
35 changed files with 5923 additions and 4486 deletions

View file

@ -4,4 +4,13 @@ interface Env {
SECURITY_KEY: string;
OPENAI_API_KEY: string;
GOOGLE_AI_API_KEY: string;
MY_QUEUE: Queue<TweetData>;
}
interface TweetData {
tweetText: string;
postUrl: string;
authorName: string;
handle: string;
time: string;
}

View file

@ -30,7 +30,7 @@ export async function POST(request: Request, store: CloudflareVectorizeStore) {
},
],
{
ids: [`${body.url}`],
ids: [`${body.url}-${body.user}`],
},
);

View file

@ -60,8 +60,9 @@ export async function POST(request: Request, _: CloudflareVectorizeStore, embedd
// if (responses.count === 0) {
// return new Response(JSON.stringify({ message: "No Results Found" }), { status: 404 });
// }
console.log(responses.matches);
const highScoreIds = responses.matches.filter(({ score }) => score > 0.35).map(({ id }) => id);
const highScoreIds = responses.matches.filter(({ score }) => score > 0.3).map(({ id }) => id);
if (sourcesOnly === 'true') {
return new Response(JSON.stringify({ ids: highScoreIds }), { status: 200 });

View file

@ -9,6 +9,10 @@ index_name = "any-vector"
[ai]
binding = "AI"
[[queues.producers]]
queue = "batch-vector-queue"
binding = "MY_QUEUE"
# Variable bindings. These are arbitrary, plaintext strings (similar to environment variables)
# Note: Use secrets to store sensitive data.
# Docs: https://developers.cloudflare.com/workers/platform/environment-variables

View file

@ -13,7 +13,7 @@ function App() {
null,
);
const doStuff = () => {
const getUserData = () => {
chrome.runtime.sendMessage({ type: "getJwt" }, (response) => {
const jwt = response.jwt;
const loginButton = document.getElementById("login");
@ -41,9 +41,69 @@ function App() {
};
useEffect(() => {
doStuff();
getUserData();
}, []);
// TODO: Implement getting bookmarks from API directly
// const [status, setStatus] = useState('');
// const [bookmarks, setBookmarks] = useState<TweetData[]>([]);
// const fetchBookmarks = (e: React.MouseEvent<HTMLButtonElement>) => {
// e.preventDefault();
// chrome.tabs.query({ active: true, currentWindow: true }, function (tabs) {
// chrome.tabs.sendMessage(tabs[0].id!, { action: 'showProgressIndicator' });
// });
// chrome.tabs.create(
// { url: 'https://twitter.com/i/bookmarks/all' },
// function (tab) {
// chrome.tabs.onUpdated.addListener(function listener(tabId, info) {
// if (tabId === tab.id && info.status === 'complete') {
// chrome.tabs.onUpdated.removeListener(listener);
// chrome.runtime.sendMessage(
// { action: 'getAuthData' },
// function (response) {
// const authorizationHeader = response.authorizationHeader;
// const csrfToken = response.csrfToken;
// const cookies = response.cookies;
// if (authorizationHeader && csrfToken && cookies) {
// fetchAllBookmarks(authorizationHeader, csrfToken, cookies)
// .then((bookmarks) => {
// console.log('Bookmarks data:', bookmarks);
// setBookmarks(bookmarks);
// chrome.tabs.sendMessage(tabId, {
// action: 'hideProgressIndicator',
// });
// setStatus(
// `Fetched ${bookmarks.length} bookmarked tweets.`,
// );
// })
// .catch((error) => {
// console.error('Error:', error);
// chrome.tabs.sendMessage(tabId, {
// action: 'hideProgressIndicator',
// });
// setStatus(
// 'Error fetching bookmarks. Please check the console for details.',
// );
// });
// } else {
// chrome.tabs.sendMessage(tabId, {
// action: 'hideProgressIndicator',
// });
// setStatus('Missing authentication data');
// }
// },
// );
// }
// });
// },
// );
// };
return (
<div className="p-8">
<button
@ -69,6 +129,19 @@ function App() {
<h3>{userData.data.user.name}</h3>
<p>{userData.data.user.email}</p>
</div>
{/* TODO: Implement getting bookmarks from API directly */}
{/* <button onClick={(e) => fetchBookmarks(e)}>Fetch Bookmarks</button>
<div>{status}</div>
<div>
{bookmarks.map((bookmark) => (
<div key={bookmark.tweet_id}>
<p>{bookmark.author}</p>
<p>{bookmark.date}</p>
<p>{bookmark.full_text}</p>
</div>
))}
</div> */}
</div>
)}
</div>
@ -76,4 +149,160 @@ function App() {
);
}
// TODO: Implement getting bookmarks from API directly
// async function fetchAllBookmarks(
// authorizationHeader: string,
// csrfToken: string,
// cookies: string,
// ): Promise<TweetData[]> {
// const baseUrl =
// 'https://twitter.com/i/api/graphql/uJEL6XARgGmo2EAsO2Pfkg/Bookmarks';
// const params = new URLSearchParams({
// variables: JSON.stringify({
// count: 100,
// includePromotedContent: true,
// }),
// features: JSON.stringify({
// graphql_timeline_v2_bookmark_timeline: true,
// rweb_tipjar_consumption_enabled: false,
// responsive_web_graphql_exclude_directive_enabled: true,
// verified_phone_label_enabled: true,
// creator_subscriptions_tweet_preview_api_enabled: true,
// responsive_web_graphql_timeline_navigation_enabled: true,
// responsive_web_graphql_skip_user_profile_image_extensions_enabled: false,
// communities_web_enable_tweet_community_results_fetch: true,
// c9s_tweet_anatomy_moderator_badge_enabled: true,
// tweetypie_unmention_optimization_enabled: true,
// responsive_web_edit_tweet_api_enabled: true,
// graphql_is_translatable_rweb_tweet_is_translatable_enabled: true,
// view_counts_everywhere_api_enabled: true,
// longform_notetweets_consumption_enabled: true,
// responsive_web_twitter_article_tweet_consumption_enabled: true,
// tweet_awards_web_tipping_enabled: false,
// creator_subscriptions_quote_tweet_preview_enabled: false,
// freedom_of_speech_not_reach_fetch_enabled: true,
// standardized_nudges_misinfo: true,
// tweet_with_visibility_results_prefer_gql_limited_actions_policy_enabled:
// true,
// tweet_with_visibility_results_prefer_gql_media_interstitial_enabled:
// false,
// rweb_video_timestamps_enabled: true,
// longform_notetweets_rich_text_read_enabled: true,
// longform_notetweets_inline_media_enabled: true,
// responsive_web_enhance_cards_enabled: false,
// }),
// });
// const requestUrl = `${baseUrl}?${params}`;
// const headers = {
// Authorization: authorizationHeader,
// 'X-Csrf-Token': csrfToken,
// Cookie: cookies,
// };
// const bookmarks: TweetData[] = [];
// let nextCursor = null;
// let requestCount = 0;
// const maxRequestsPerWindow = 450;
// const windowDuration = 15 * 60 * 1000; // 15 minutes in milliseconds
// let windowStartTime = Date.now();
// do {
// if (nextCursor) {
// params.set(
// 'variables',
// JSON.stringify({
// count: 100,
// cursor: nextCursor,
// includePromotedContent: true,
// }),
// );
// }
// // Check if the rate limit is exceeded
// if (requestCount >= maxRequestsPerWindow) {
// const elapsedTime = Date.now() - windowStartTime;
// if (elapsedTime < windowDuration) {
// const waitTime = windowDuration - elapsedTime;
// await new Promise((resolve) => setTimeout(resolve, waitTime));
// }
// requestCount = 0;
// windowStartTime = Date.now();
// }
// try {
// const response = await fetch(requestUrl, {
// method: 'GET',
// headers: headers,
// });
// requestCount++;
// if (!response.ok) {
// throw new Error(`HTTP error! status: ${response.status}`);
// }
// const data = await response.json();
// const timeline = data.data.bookmark_timeline_v2.timeline;
// timeline.instructions.forEach(
// (instruction: {
// type: string;
// entries: {
// content: {
// entryType: string;
// itemContent: {
// tweet_results: {
// result: {
// legacy: {
// full_text: string;
// created_at: string;
// };
// core: {
// user_results: {
// result: {
// legacy: {
// screen_name: string;
// };
// };
// };
// };
// rest_id: string;
// };
// };
// };
// };
// }[];
// }) => {
// if (instruction.type === 'TimelineAddEntries') {
// instruction.entries.forEach((entry) => {
// if (entry.content.entryType === 'TimelineTimelineItem') {
// const tweet = entry.content.itemContent.tweet_results.result;
// const tweetData = {
// full_text: tweet.legacy.full_text,
// url: `https://twitter.com/${tweet.core.user_results.result.legacy.screen_name}/status/${tweet.rest_id}`,
// author: tweet.core.user_results.result.legacy.screen_name,
// date: tweet.legacy.created_at,
// tweet_id: tweet.rest_id,
// };
// bookmarks.push(tweetData);
// }
// });
// }
// },
// );
// nextCursor = timeline.instructions.find(
// (instruction: { type: string }) =>
// instruction.type === 'TimelineTerminateTimeline',
// )?.direction?.cursor;
// } catch (error) {
// console.error('Error fetching bookmarks:', error);
// throw error;
// }
// } while (nextCursor);
// return bookmarks;
// }
export default App;

View file

@ -25,20 +25,176 @@ function sendUrlToAPI() {
}
function SideBar() {
// TODO: Implement getting bookmarks from API directly
// chrome.runtime.onMessage.addListener(function (request) {
// if (request.action === 'showProgressIndicator') {
// // TODO: SHOW PROGRESS INDICATOR
// // showProgressIndicator();
// } else if (request.action === 'hideProgressIndicator') {
// // hideProgressIndicator();
// }
// });
const [savedWebsites, setSavedWebsites] = useState<string[]>([]);
const [isSendingData, setIsSendingData] = useState(false);
interface TweetData {
tweetText: string;
postUrl: string;
authorName: string;
handle: string;
time: string;
}
const fetchBookmarks = () => {
const tweets: TweetData[] = []; // Initialize an empty array to hold all tweet elements
const scrollInterval = 1000;
const scrollStep = 5000; // Pixels to scroll on each step
let previousTweetCount = 0;
let unchangedCount = 0;
const scrollToEndIntervalID = setInterval(() => {
window.scrollBy(0, scrollStep);
const currentTweetCount = tweets.length;
if (currentTweetCount === previousTweetCount) {
unchangedCount++;
if (unchangedCount >= 2) {
// Stop if the count has not changed 5 times
console.log("Scraping complete");
console.log("Total tweets scraped: ", tweets.length);
console.log("Downloading tweets as JSON...");
clearInterval(scrollToEndIntervalID); // Stop scrolling
observer.disconnect(); // Stop observing DOM changes
downloadTweetsAsJson(tweets); // Download the tweets list as a JSON file
}
} else {
unchangedCount = 0; // Reset counter if new tweets were added
}
previousTweetCount = currentTweetCount; // Update previous count for the next check
}, scrollInterval);
function updateTweets() {
document
.querySelectorAll('article[data-testid="tweet"]')
.forEach((tweetElement) => {
const authorName = (
tweetElement.querySelector(
'[data-testid="User-Name"]',
) as HTMLElement
)?.innerText;
const handle = (
tweetElement.querySelector('[role="link"]') as HTMLLinkElement
).href
.split("/")
.pop();
const tweetText = (
tweetElement.querySelector(
'[data-testid="tweetText"]',
) as HTMLElement
)?.innerText;
const time = (
tweetElement.querySelector("time") as HTMLTimeElement
).getAttribute("datetime");
const postUrl = (
tweetElement.querySelector(
".css-175oi2r.r-18u37iz.r-1q142lx a",
) as HTMLLinkElement
)?.href;
const isTweetNew = !tweets.some((tweet) => tweet.postUrl === postUrl);
if (isTweetNew) {
tweets.push({
authorName,
handle: handle ?? "",
tweetText,
time: time ?? "",
postUrl,
});
console.log("Tweets capturados: ", tweets.length);
}
});
}
// Initially populate the tweets array
updateTweets();
// Create a MutationObserver to observe changes in the DOM
const observer = new MutationObserver((mutations) => {
mutations.forEach((mutation) => {
if (mutation.addedNodes.length) {
updateTweets(); // Call updateTweets whenever new nodes are added to the DOM
}
});
});
// Start observing the document body for child list changes
observer.observe(document.body, { childList: true, subtree: true });
function downloadTweetsAsJson(tweetsArray: TweetData[]) {
const jsonData = JSON.stringify(tweetsArray); // Convert the array to JSON
// TODO: SEND jsonData to server
console.log(jsonData);
}
};
return (
<>
<TooltipProvider>
<div className="anycontext-flex anycontext-flex-col anycontext-gap-2 anycontext-fixed anycontext-bottom-12 anycontext-right-0 anycontext-z-[99999] anycontext-font-sans">
{/* <Tooltip delayDuration={300}>
<TooltipContent side="left">
<p>Open Sidebar</p>
</TooltipContent>
</Tooltip> */}
<div className="anycontext-flex anycontext-group anycontext-flex-col anycontext-gap-2 anycontext-fixed anycontext-bottom-12 anycontext-right-0 anycontext-z-[99999] anycontext-font-sans">
{window.location.href.includes("twitter.com") ||
window.location.href.includes("x.com") ? (
<Tooltip delayDuration={300}>
<TooltipTrigger
className="anycontext-bg-transparent
anycontext-border-none anycontext-m-0 anycontext-p-0"
>
<button
onClick={() => {
if (window.location.href.endsWith("/i/bookmarks/all")) {
fetchBookmarks();
} else {
window.location.href =
"https://twitter.com/i/bookmarks/all";
setTimeout(() => {
fetchBookmarks();
}, 2500);
}
}}
className="anycontext-open-button disabled:anycontext-opacity-30 anycontext-bg-transparent
anycontext-border-none anycontext-m-0 anycontext-p-0"
>
<svg
xmlns="http://www.w3.org/2000/svg"
fill="none"
viewBox="0 0 24 24"
strokeWidth={1.5}
stroke="currentColor"
className="anycontext-w-6 anycontext-h-6"
>
<path
strokeLinecap="round"
strokeLinejoin="round"
d="M17.593 3.322c1.1.128 1.907 1.077 1.907 2.185V21L12 17.25 4.5 21V5.507c0-1.108.806-2.057 1.907-2.185a48.507 48.507 0 0 1 11.186 0Z"
/>
</svg>
</button>
</TooltipTrigger>
<TooltipContent className="anycontext-p-0" side="left">
<p className="anycontext-p-0 anycontext-m-0">
Import twitter bookmarks
</p>
</TooltipContent>
</Tooltip>
) : (
<></>
)}
<Tooltip delayDuration={300}>
<TooltipTrigger
className="anycontext-bg-transparent

View file

@ -5,6 +5,30 @@ const backendUrl =
? "http://localhost:3000"
: "https://supermemory.dhr.wtf";
// TODO: Implement getting bookmarks from API directly
// let authorizationHeader: string | null = null;
// let csrfToken: string | null = null;
// let cookies: string | null = null;
// chrome.webRequest.onBeforeSendHeaders.addListener(
// (details) => {
// for (let i = 0; i < details.requestHeaders!.length; ++i) {
// const header = details.requestHeaders![i];
// if (header.name.toLowerCase() === 'authorization') {
// authorizationHeader = header.value || null;
// } else if (header.name.toLowerCase() === 'x-csrf-token') {
// csrfToken = header.value || null;
// } else if (header.name.toLowerCase() === 'cookie') {
// cookies = header.value || null;
// }
// console.log(header, authorizationHeader, csrfToken, cookies)
// }
// },
// { urls: ['https://twitter.com/*', 'https://x.com/*'] },
// ['requestHeaders']
// );
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
if (request.type === "getJwt") {
chrome.storage.local.get(["jwt"], ({ jwt }) => {
@ -73,4 +97,12 @@ chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
return true;
})();
}
// TODO: Implement getting bookmarks from API directly
// else if (request.action === 'getAuthData') {
// sendResponse({
// authorizationHeader: authorizationHeader,
// csrfToken: csrfToken,
// cookies: cookies
// });
// }
});

View file

@ -34,7 +34,7 @@ CREATE TABLE `session` (
--> statement-breakpoint
CREATE TABLE `space` (
`id` integer PRIMARY KEY AUTOINCREMENT NOT NULL,
`name` text DEFAULT 'all' NOT NULL,
`name` text DEFAULT 'none' NOT NULL,
`user` text(255),
FOREIGN KEY (`user`) REFERENCES `user`(`id`) ON UPDATE no action ON DELETE no action
);
@ -47,6 +47,7 @@ CREATE TABLE `storedContent` (
`url` text NOT NULL,
`savedAt` integer NOT NULL,
`baseUrl` text(255),
`type` text DEFAULT 'page',
`image` text(255),
`user` text(255),
FOREIGN KEY (`user`) REFERENCES `user`(`id`) ON UPDATE no action ON DELETE no action
@ -69,6 +70,7 @@ CREATE TABLE `verificationToken` (
--> statement-breakpoint
CREATE INDEX `account_userId_idx` ON `account` (`userId`);--> statement-breakpoint
CREATE INDEX `session_userId_idx` ON `session` (`userId`);--> statement-breakpoint
CREATE UNIQUE INDEX `space_name_unique` ON `space` (`name`);--> statement-breakpoint
CREATE INDEX `spaces_name_idx` ON `space` (`name`);--> statement-breakpoint
CREATE INDEX `spaces_user_idx` ON `space` (`user`);--> statement-breakpoint
CREATE INDEX `storedContent_url_idx` ON `storedContent` (`url`);--> statement-breakpoint

View file

@ -27,10 +27,13 @@
"framer-motion": "^11.0.24",
"lucide-react": "^0.338.0",
"next": "14.1.0",
"novel": "0.1.22",
"react": "^18",
"react-dom": "^18",
"tailwind-merge": "^2.2.1",
"tailwindcss": "^3.4.3",
"tailwindcss-animate": "^1.0.7",
"tiptap-markdown": "^0.8.10",
"vaul": "^0.9.0"
},
"devDependencies": {
@ -45,7 +48,6 @@
"eslint-plugin-next-on-pages": "^1.11.0",
"postcss": "^8",
"tailwind-scrollbar": "^3.1.0",
"tailwindcss": "^3.3.0",
"typescript": "^5",
"vercel": "^33.6.2",
"wrangler": "^3.41.0"

8861
apps/web/pnpm-lock.yaml generated

File diff suppressed because it is too large Load diff

Binary file not shown.

After

Width:  |  Height:  |  Size: 87 KiB

View file

Before

Width:  |  Height:  |  Size: 3.1 KiB

After

Width:  |  Height:  |  Size: 3.1 KiB

Before After
Before After

Binary file not shown.

After

Width:  |  Height:  |  Size: 41 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 213 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 88 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 141 KiB

View file

@ -1 +0,0 @@
<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 394 80"><path fill="#000" d="M262 0h68.5v12.7h-27.2v66.6h-13.6V12.7H262V0ZM149 0v12.7H94v20.4h44.3v12.6H94v21h55v12.6H80.5V0h68.7zm34.3 0h-17.8l63.8 79.4h17.9l-32-39.7 32-39.6h-17.9l-23 28.6-23-28.6zm18.3 56.7-9-11-27.1 33.7h17.8l18.3-22.7z"/><path fill="#000" d="M81 79.3 17 0H0v79.3h13.6V17l50.2 62.3H81Zm252.6-.4c-1 0-1.8-.4-2.5-1s-1.1-1.6-1.1-2.6.3-1.8 1-2.5 1.6-1 2.6-1 1.8.3 2.5 1a3.4 3.4 0 0 1 .6 4.3 3.7 3.7 0 0 1-3 1.8zm23.2-33.5h6v23.3c0 2.1-.4 4-1.3 5.5a9.1 9.1 0 0 1-3.8 3.5c-1.6.8-3.5 1.3-5.7 1.3-2 0-3.7-.4-5.3-1s-2.8-1.8-3.7-3.2c-.9-1.3-1.4-3-1.4-5h6c.1.8.3 1.6.7 2.2s1 1.2 1.6 1.5c.7.4 1.5.5 2.4.5 1 0 1.8-.2 2.4-.6a4 4 0 0 0 1.6-1.8c.3-.8.5-1.8.5-3V45.5zm30.9 9.1a4.4 4.4 0 0 0-2-3.3 7.5 7.5 0 0 0-4.3-1.1c-1.3 0-2.4.2-3.3.5-.9.4-1.6 1-2 1.6a3.5 3.5 0 0 0-.3 4c.3.5.7.9 1.3 1.2l1.8 1 2 .5 3.2.8c1.3.3 2.5.7 3.7 1.2a13 13 0 0 1 3.2 1.8 8.1 8.1 0 0 1 3 6.5c0 2-.5 3.7-1.5 5.1a10 10 0 0 1-4.4 3.5c-1.8.8-4.1 1.2-6.8 1.2-2.6 0-4.9-.4-6.8-1.2-2-.8-3.4-2-4.5-3.5a10 10 0 0 1-1.7-5.6h6a5 5 0 0 0 3.5 4.6c1 .4 2.2.6 3.4.6 1.3 0 2.5-.2 3.5-.6 1-.4 1.8-1 2.4-1.7a4 4 0 0 0 .8-2.4c0-.9-.2-1.6-.7-2.2a11 11 0 0 0-2.1-1.4l-3.2-1-3.8-1c-2.8-.7-5-1.7-6.6-3.2a7.2 7.2 0 0 1-2.4-5.7 8 8 0 0 1 1.7-5 10 10 0 0 1 4.3-3.5c2-.8 4-1.2 6.4-1.2 2.3 0 4.4.4 6.2 1.2 1.8.8 3.2 2 4.3 3.4 1 1.4 1.5 3 1.5 5h-5.8z"/></svg>

Before

Width:  |  Height:  |  Size: 1.3 KiB

View file

@ -1 +0,0 @@
<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 283 64"><path fill="black" d="M141 16c-11 0-19 7-19 18s9 18 20 18c7 0 13-3 16-7l-7-5c-2 3-6 4-9 4-5 0-9-3-10-7h28v-3c0-11-8-18-19-18zm-9 15c1-4 4-7 9-7s8 3 9 7h-18zm117-15c-11 0-19 7-19 18s9 18 20 18c6 0 12-3 16-7l-8-5c-2 3-5 4-8 4-5 0-9-3-11-7h28l1-3c0-11-8-18-19-18zm-10 15c2-4 5-7 10-7s8 3 9 7h-19zm-39 3c0 6 4 10 10 10 4 0 7-2 9-5l8 5c-3 5-9 8-17 8-11 0-19-7-19-18s8-18 19-18c8 0 14 3 17 8l-8 5c-2-3-5-5-9-5-6 0-10 4-10 10zm83-29v46h-9V5h9zM37 0l37 64H0L37 0zm92 5-27 48L74 5h10l18 30 17-30h10zm59 12v10l-3-1c-6 0-10 4-10 10v15h-9V17h9v9c0-5 6-9 13-9z"/></svg>

Before

Width:  |  Height:  |  Size: 629 B

View file

@ -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;
}

View file

@ -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({

View file

@ -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;
}

View file

@ -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>

View file

@ -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;
}

View file

@ -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();
}}

View file

@ -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;

View file

@ -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>
);
};

View file

@ -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>
);
}

View file

@ -30,19 +30,20 @@ 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 }) =>
@ -65,6 +66,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 +75,124 @@ 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}
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 }) =>
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}

View file

@ -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>
);
}

View file

@ -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>
);

View file

@ -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;

View file

@ -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>
);

View file

@ -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);
}

View file

@ -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) => ({

View file

@ -44,12 +44,24 @@ const config: Config = {
opacity: "1",
},
},
"input-error": {
"0%": {
color: "var(--gray-11)",
},
"50%": {
color: "red",
},
"100%": {
color: "var(--gray-11)",
},
},
},
animation: {
"scale-in": "scale-in 0.2s cubic-bezier(0.16, 1, 0.3, 1)",
"scale-out": "scale-out 0.2s cubic-bezier(0.16, 1, 0.3, 1)",
"fade-in": "fade-in 0.2s 0.5s forwards cubic-bezier(0.16, 1, 0.3, 1)",
"from-top": "from-top 0.2s ease-in-out",
"input-error": "input-error 5s",
},
backgroundImage: {
"gradient-radial": "radial-gradient(var(--tw-gradient-stops))",