Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 28 additions & 6 deletions apps/web/src/app/(dashboard)/bookmarks/new/action.ts
Original file line number Diff line number Diff line change
@@ -1,27 +1,49 @@
'use server'
import type { IdName } from '@/src/components/edit-pages-for-bookmark'
import { isWatchable } from '@/src/lib/utils/watchable'
import { addToWatchlist } from '@/src/lib/utils/watchlist'
import { createClient } from '@/src/utils/supabase/server'
import { revalidatePath } from 'next/cache'

export const save = async (name: string, url: string, tagIds: IdName[]) => {
const supabase = await createClient()

// Get the current user
const {
data: { user },
} = await supabase.auth.getUser()
if (!user) {
throw new Error('User not authenticated')
}

// Create new tags if needed
const tagNames = tagIds.filter(t => !t.id).map(t => ({ name: t.name }))
const { data: newTags } = await supabase.from('tags').insert(tagNames).select()

const { data: bookmarks } = await supabase
// Create the bookmark
const { data: bookmark, error: bookmarkError } = await supabase
.from('bookmarks')
.insert({
name: name,
url: url,
})
.insert({ name, url })
.select()
.single()

if (bookmarkError) {
throw bookmarkError
}

const bookmark = bookmarks![0]
if (!bookmark) {
throw new Error('Failed to create bookmark')
}

// Add bookmark-tag relations
const existingTags = tagIds.filter(t => t.id)
const relations = [...(newTags || []), ...existingTags].map(r => ({ tag_id: r.id!, bookmark_id: bookmark.id }))
await supabase.from('bookmarks_tags').insert(relations)

// If the URL is watchable, add it to the watchlist
if (isWatchable(url)) {
await addToWatchlist(supabase, bookmark.id)
}

revalidatePath('/bookmarks')
}
34 changes: 8 additions & 26 deletions apps/web/src/app/(dashboard)/bookmarks/new/component.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ import {
import { toast } from 'sonner'
import { EditPagesForBookmark } from '../../../../components/edit-pages-for-bookmark'
import { createClient } from '../../../../utils/supabase/client'
import { save } from './action'

const formId = 'create-new-bookmark'

Expand Down Expand Up @@ -56,34 +57,15 @@ export const NewBookmarkComponent = () => {
})

const onSubmit: SubmitHandler<z.infer<typeof NewBookmarkSchema>> = async values => {
const tagNames = values.tagIds.filter(t => !t.id).map(t => ({ name: t.name }))
const { data: newTags } = await supabase.from('tags').insert(tagNames).select()

const { data, error } = await supabase
.from('bookmarks')
.insert({
name: values.name,
url: values.url,
read: values.read,
try {
await save(values.name, values.url, values.tagIds)
toast.success('Bookmark created')
router.push('/bookmarks')
} catch (error) {
toast.error('Failed to create bookmark', {
description: error instanceof Error ? error.message : 'Please try again',
})
.select()

if (error || data.length !== 1) {
// TODO: handle this case
return
}
const bookmark = data[0]

const existingTags = values.tagIds.filter(t => t.id)
const relations = [...(newTags || []), ...existingTags].map(r => ({ tag_id: r.id!, bookmark_id: bookmark.id }))

await supabase.from('bookmarks_tags').delete().eq('bookmark_id', bookmark.id)
if (relations.length > 0) {
await supabase.from('bookmarks_tags').insert(relations)
}

toast.success('Bookmark created')
router.push(`/bookmarks`)
}

return (
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
import { BookmarkType } from '@/src/lib/supabase'
import { createClient } from '@/src/utils/supabase/client'
import { GetNextPageParamFunction, InfiniteData, useInfiniteQuery } from '@tanstack/react-query'

const queryKey = (searchQuery: string | null) => ['watchlist-bookmarks', { searchQuery }]

const PAGE_SIZE = 19

const queryFn = async ({
pageParam: skip,
queryKey,
}: {
pageParam: number
queryKey: (string | { searchQuery: string | null })[]
}) => {
let searchQuery: string | undefined = undefined
if (queryKey.length === 2 && typeof queryKey[1] !== 'string') {
searchQuery = queryKey[1].searchQuery || undefined
}

let query = createClient()
.from('watchlist')
.select(
`
bookmark:bookmarks!inner (
*
)
`,
{ count: 'exact' },
)

if (searchQuery && searchQuery.length > 0) {
query = query.ilike('bookmark.name', `%${searchQuery}%`)
}

const { data: watchlistItems, count } = await query
.order('created_at', { ascending: false })
// secondary sort by id to avoid pagination issues
.order('id', { ascending: false })
.range(skip, skip + PAGE_SIZE)
.throwOnError()

const data = watchlistItems?.map(item => ({
...item.bookmark,
}))

return { data, count } as { data: NonNullable<typeof data>; count: number }
}

const getNextPageParam: GetNextPageParamFunction<
number,
{
data: NonNullable<BookmarkType[]>
count: number
}
> = (_, pages) => {
const bookmarks = pages.flatMap(p => p.data)
return bookmarks.length
}

const selectData = (
data: InfiniteData<
{
data: NonNullable<BookmarkType[]>
count: number
},
number
>,
) => {
return { bookmarks: data.pages.flatMap(p => p.data), count: data.pages[0].count }
}

export const useListWatchlistBookmarksQuery = (searchQuery: string | null) => {
return useInfiniteQuery({
queryKey: queryKey(searchQuery),
queryFn: queryFn,
staleTime: 5000,
getNextPageParam: getNextPageParam,
initialPageParam: 0,
select: selectData,
})
}
29 changes: 29 additions & 0 deletions apps/web/src/app/(dashboard)/watchlist/page.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
'use server'

import { MainContentLayout } from '@/src/components/main-content-layout'
import { getQueryClient } from '@/src/lib/react-query-client'
import { checkAuthentication } from '@/src/lib/supabase'
import { HydrationBoundary, dehydrate } from '@tanstack/react-query'
import { Video } from 'lucide-react'
import { WatchlistBookmarks } from './watchlist-bookmarks'

const WatchlistPage = async () => {
await checkAuthentication('/watchlist')
const queryClient = getQueryClient()

return (
<HydrationBoundary state={dehydrate(queryClient)}>
<MainContentLayout>
<div className="flex">
<div className="flex h-full flex-1 items-center gap-2">
<Video size={20} className="pt-1" />
<h1 className="text-foreground flex-1 text-3xl font-semibold">Watchlist</h1>
</div>
</div>
<WatchlistBookmarks />
</MainContentLayout>
</HydrationBoundary>
)
}

export default WatchlistPage
12 changes: 12 additions & 0 deletions apps/web/src/app/(dashboard)/watchlist/watchlist-bookmarks.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
'use client'

import { Bookmarks } from '@/src/components/bookmarks'
import { useQueryState } from 'nuqs'
import { useListWatchlistBookmarksQuery } from './list-watchlist-bookmarks-query'

export function WatchlistBookmarks() {
const [searchQuery] = useQueryState('q')
const query = useListWatchlistBookmarksQuery(searchQuery)

return <Bookmarks {...query} />
}
8 changes: 7 additions & 1 deletion apps/web/src/components/app-sidebar/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ import {
SidebarMenuItem,
SidebarMenuSkeleton,
} from '@rememr/ui'
import { ChevronDown, Home, Inbox } from 'lucide-react'
import { ChevronDown, Home, Inbox, Video } from 'lucide-react'
import Link from 'next/link'
import { Suspense } from 'react'
import { createClient } from '../../utils/supabase/server'
Expand Down Expand Up @@ -55,6 +55,12 @@ export async function AppSidebar() {
<span>Reading list</span>
</SidebarMenuLink>
</SidebarMenuItem>
<SidebarMenuItem>
<SidebarMenuLink href="/watchlist">
<Video />
<span>Watchlist</span>
</SidebarMenuLink>
</SidebarMenuItem>
</SidebarMenu>
</SidebarGroupContent>
</SidebarGroup>
Expand Down
49 changes: 47 additions & 2 deletions apps/web/src/components/bookmark/bookmark.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
'use client'

import { BookmarkType } from '@/src/lib/supabase'
import { isWatchable } from '@/src/lib/utils/watchable'
import { addToWatchlist, isInWatchlist, removeFromWatchlist } from '@/src/lib/utils/watchlist'
import { createClient } from '@/src/utils/supabase/client'
import {
Button,
Card,
Expand All @@ -11,15 +14,19 @@ import {
DropdownMenuItem,
DropdownMenuTrigger,
} from '@rememr/ui'
import { EllipsisVertical, Pen, Trash2 } from 'lucide-react'
import { useState } from 'react'
import { EllipsisVertical, Pen, Trash2, Video } from 'lucide-react'
import { useEffect, useState } from 'react'
import { DeleteBookmarkDialog } from '../delete-bookmark'
import { EditBookmarkDialog } from '../edit-bookmark'
import { ChatSheet } from './chat-sheet'

const supabase = createClient()

export const Bookmark = (props: { bookmark: BookmarkType }) => {
const [editBookmarkDialogShown, setEditBookmarkDialogShown] = useState(false)
const [deleteBookmarkDialogShown, setDeleteBookmarkDialogShown] = useState(false)
const [isInWatchlistState, setIsInWatchlistState] = useState(false)
const [isLoading, setIsLoading] = useState(false)

const bookmark = props.bookmark
let hostname = ''
Expand All @@ -28,6 +35,32 @@ export const Bookmark = (props: { bookmark: BookmarkType }) => {
hostname = new URL(bookmark.url).hostname
} catch {}

const isBookmarkWatchable = isWatchable(bookmark.url)

useEffect(() => {
if (isBookmarkWatchable) {
isInWatchlist(supabase, bookmark.id).then(setIsInWatchlistState)
}
}, [bookmark.id, isBookmarkWatchable])

const handleWatchlistToggle = async () => {
if (isLoading) return
setIsLoading(true)
try {
if (isInWatchlistState) {
await removeFromWatchlist(supabase, bookmark.id)
setIsInWatchlistState(false)
} else {
await addToWatchlist(supabase, bookmark.id)
setIsInWatchlistState(true)
}
} catch (error) {
console.error('Error toggling watchlist:', error)
} finally {
setIsLoading(false)
}
}

return (
<Card className="group flex overflow-hidden px-6 py-4">
<div className="min-w-5 mr-5 mt-1">
Expand All @@ -50,6 +83,18 @@ export const Bookmark = (props: { bookmark: BookmarkType }) => {
</div>

<div className="flex gap-2">
{isBookmarkWatchable && (
<Button
size="icon"
variant={isInWatchlistState ? 'default' : 'outline'}
className="min-w-9"
onClick={handleWatchlistToggle}
disabled={isLoading}
>
<Video strokeWidth={2.5} className={isInWatchlistState ? 'text-white' : ''} />
</Button>
)}

<ChatSheet bookmarkTitle={bookmark.name} bookmarkUrl={bookmark.url} />

<DropdownMenu>
Expand Down
Loading