fix: link (#115)

* start

* .

* seeding connections

* .

* wip

* wip: learning state

* wip: notes section

* wip: many

* topics

* chore: update schema

* update package

* update sidebar

* update page section

* feat: profile

* fix: remove z index

* fix: wrong type

* add avatar

* add avatar

* wip

* .

* store page section key

* remove atom page section

* fix rerender

* fix rerender

* fix rerender

* fix rerender

* fix link

* search light/dark mode

* bubble menu ui

* .

* fix: remove unecessary code

* chore: mark as old for old schema

* chore: adapt new schema

* fix: add topic schema but null for now

* fix: add icon on personal link

* fix: list item

* fix: set url fetched when editing

* fix: remove image

* feat: add icon to link

* feat: custom url zod validation

* fix: metadata test

* chore: update utils

* fix: link

* fix: url fetcher

* .

* .

* fix: add link, section

* chore: seeder

* .

* .

* .

* .

* fix: change checkbox to learning state

* fix: click outside editing form

* feat: constant

* chore: move to master folder

* chore: adapt new schema

* chore: cli for new schema

* fix: new schema for dev seed

* fix: seeding

* update package

* chore: forcegraph seed

* bottombar

* if isEdit delete icon

* showCreate X button

* .

* options

* chore: implement topic from public global group

* chore: update learning state

* fix: change implementation for outside click

* chore: implement new form param

* chore: update env example

* feat: link form refs exception

* new page button layout, link topic search fixed

* chore: enable topic

* chore: update seed

* profile

* chore: move framer motion package from root to web and add nuqs

* chore: add LearningStateValue

* chore: implement active state

* profile

* chore: use fancy switch and update const

* feat: filter implementation

* dropdown menu

* .

* sidebar topics

* topic selected color

* feat: topic detail

* fix: collapsible page

* pages - sorted by, layout, visible mode

* .

* .

* .

* topic status sidebar

* topic button and count

* fix: topic

* page delete/topic buttons

* search ui

* selected topic for page

* selected topic status sidebar

* removed footer

* update package

* .

---------

Co-authored-by: Nikita <github@nikiv.dev>
Co-authored-by: marshennikovaolga <marshennikova@gmail.com>
Co-authored-by: Kisuyo <ig.intr3st@gmail.com>
This commit is contained in:
Aslam
2024-08-26 19:35:00 +07:00
committed by GitHub
parent 7cbfcc705b
commit 2d270706a5
77 changed files with 3002 additions and 1327 deletions

View File

@@ -6,7 +6,7 @@ import { LinkManage } from "@/components/routes/link/form/manage"
import { useAtom } from "jotai"
import { linkEditIdAtom } from "@/store/link"
export function LinkWrapper() {
export function AuthHomeRoute() {
const [editId] = useAtom(linkEditIdAtom)
return (

View File

@@ -0,0 +1 @@
export * from "./manage"

View File

@@ -0,0 +1,253 @@
import * as React from "react"
import { useAccount, useCoState } from "@/lib/providers/jazz-provider"
import { PersonalLink, Topic } from "@/lib/schema"
import { useForm } from "react-hook-form"
import { zodResolver } from "@hookform/resolvers/zod"
import { toast } from "sonner"
import { createLinkSchema, LinkFormValues } from "./schema"
import { cn, generateUniqueSlug } from "@/lib/utils"
import { Form } from "@/components/ui/form"
import { Button } from "@/components/ui/button"
import { UrlInput } from "./partial/url-input"
import { UrlBadge } from "./partial/url-badge"
import { TitleInput } from "./partial/title-input"
import { NotesSection } from "./partial/notes-section"
import { TopicSelector } from "./partial/topic-selector"
import { DescriptionInput } from "./partial/description-input"
import { LearningStateSelector } from "./partial/learning-state-selector"
import { atom, useAtom } from "jotai"
import { linkLearningStateSelectorAtom, linkTopicSelectorAtom } from "@/store/link"
export const globalLinkFormExceptionRefsAtom = atom<React.RefObject<HTMLElement>[]>([])
interface LinkFormProps extends React.ComponentPropsWithoutRef<"form"> {
onClose?: () => void
onSuccess?: () => void
onFail?: () => void
personalLink?: PersonalLink
exceptionsRefs?: React.RefObject<HTMLElement>[]
}
const defaultValues: Partial<LinkFormValues> = {
url: "",
icon: "",
title: "",
description: "",
completed: false,
notes: "",
learningState: "wantToLearn",
topic: null
}
export const LinkForm: React.FC<LinkFormProps> = ({
onSuccess,
onFail,
personalLink,
onClose,
exceptionsRefs = []
}) => {
const [selectedTopic, setSelectedTopic] = React.useState<Topic | null>(null)
const [istopicSelectorOpen] = useAtom(linkTopicSelectorAtom)
const [islearningStateSelectorOpen] = useAtom(linkLearningStateSelectorAtom)
const [globalExceptionRefs] = useAtom(globalLinkFormExceptionRefsAtom)
const formRef = React.useRef<HTMLFormElement>(null)
const [isFetching, setIsFetching] = React.useState(false)
const [urlFetched, setUrlFetched] = React.useState<string | null>(null)
const { me } = useAccount()
const selectedLink = useCoState(PersonalLink, personalLink?.id)
const form = useForm<LinkFormValues>({
resolver: zodResolver(createLinkSchema),
defaultValues,
mode: "all"
})
const allExceptionRefs = React.useMemo(
() => [...exceptionsRefs, ...globalExceptionRefs],
[exceptionsRefs, globalExceptionRefs]
)
React.useEffect(() => {
const handleClickOutside = (event: MouseEvent) => {
const isClickInsideForm = formRef.current && formRef.current.contains(event.target as Node)
const isClickInsideExceptions = allExceptionRefs.some((ref, index) => {
const isInside = ref.current && ref.current.contains(event.target as Node)
return isInside
})
if (!isClickInsideForm && !istopicSelectorOpen && !islearningStateSelectorOpen && !isClickInsideExceptions) {
onClose?.()
}
}
document.addEventListener("mousedown", handleClickOutside)
return () => {
document.removeEventListener("mousedown", handleClickOutside)
}
}, [islearningStateSelectorOpen, istopicSelectorOpen, allExceptionRefs, onClose])
React.useEffect(() => {
if (selectedLink) {
setUrlFetched(selectedLink.url)
form.reset({
url: selectedLink.url,
icon: selectedLink.icon,
title: selectedLink.title,
description: selectedLink.description,
completed: selectedLink.completed,
notes: selectedLink.notes,
learningState: selectedLink.learningState
})
}
}, [selectedLink, form])
const fetchMetadata = async (url: string) => {
setIsFetching(true)
try {
const res = await fetch(`/api/metadata?url=${encodeURIComponent(url)}`, { cache: "no-cache" })
const data = await res.json()
setUrlFetched(data.url)
form.setValue("url", data.url, {
shouldValidate: true
})
form.setValue("icon", data.icon ?? "", {
shouldValidate: true
})
form.setValue("title", data.title, {
shouldValidate: true
})
if (!form.getValues("description"))
form.setValue("description", data.description, {
shouldValidate: true
})
form.setFocus("title")
console.log(form.formState.isValid, "form state after....")
} catch (err) {
console.error("Failed to fetch metadata", err)
} finally {
setIsFetching(false)
}
}
const onSubmit = (values: LinkFormValues) => {
if (isFetching) return
try {
const personalLinks = me.root?.personalLinks?.toJSON() || []
const slug = generateUniqueSlug(personalLinks, values.title)
if (selectedLink) {
selectedLink.applyDiff({ ...values, slug, topic: selectedTopic })
} else {
const newPersonalLink = PersonalLink.create(
{
...values,
slug,
topic: selectedTopic,
sequence: me.root?.personalLinks?.length || 1,
createdAt: new Date(),
updatedAt: new Date()
},
{ owner: me._owner }
)
me.root?.personalLinks?.push(newPersonalLink)
}
form.reset(defaultValues)
onSuccess?.()
} catch (error) {
onFail?.()
console.error("Failed to create/update link", error)
toast.error(personalLink ? "Failed to update link" : "Failed to create link")
}
}
const handleCancel = () => {
form.reset(defaultValues)
onClose?.()
}
const handleResetUrl = () => {
setUrlFetched(null)
form.setFocus("url")
form.reset({ url: "", title: "", icon: "", description: "" })
}
const canSubmit = form.formState.isValid && !form.formState.isSubmitting
return (
<div className="p-3 transition-all">
<div className={cn("bg-muted/30 relative rounded-md border", isFetching && "opacity-50")}>
<Form {...form}>
<form ref={formRef} onSubmit={form.handleSubmit(onSubmit)} className="relative min-w-0 flex-1">
{isFetching && <div className="absolute inset-0 z-10 bg-transparent" aria-hidden="true" />}
<div className="flex flex-col gap-1.5 p-3">
<div className="flex flex-row items-start justify-between">
<UrlInput urlFetched={urlFetched} fetchMetadata={fetchMetadata} isFetchingUrlMetadata={isFetching} />
{urlFetched && <TitleInput urlFetched={urlFetched} />}
<div className="flex flex-row items-center gap-2">
<LearningStateSelector />
<TopicSelector onSelect={topic => setSelectedTopic(topic)} />
</div>
</div>
<DescriptionInput />
<UrlBadge urlFetched={urlFetched} handleResetUrl={handleResetUrl} />
</div>
<div
className="flex flex-row items-center justify-between gap-2 rounded-b-md border-t px-3 py-2"
onClick={e => {
if (!(e.target as HTMLElement).closest("button")) {
const notesInput = e.currentTarget.querySelector("input")
if (notesInput) {
notesInput.focus()
}
}
}}
>
<NotesSection />
{isFetching ? (
<div className="flex w-auto items-center justify-end gap-x-2">
<span className="text-muted-foreground flex items-center text-sm">
<svg className="mr-2 h-4 w-4 animate-spin" viewBox="0 0 24 24">
<circle
className="opacity-25"
cx="12"
cy="12"
r="10"
stroke="currentColor"
strokeWidth="4"
fill="none"
/>
<path
className="opacity-75"
fill="currentColor"
d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"
/>
</svg>
Fetching metadata...
</span>
</div>
) : (
<div className="flex w-auto items-center justify-end gap-x-2">
<Button size="sm" type="button" variant="ghost" onClick={handleCancel}>
Cancel
</Button>
<Button size="sm" type="submit" disabled={!canSubmit}>
Save
</Button>
</div>
)}
</div>
</form>
</Form>
</div>
</div>
)
}
LinkForm.displayName = "LinkForm"

View File

@@ -1,446 +1,100 @@
"use client"
import React, { useState, useEffect, useRef } from "react"
import { useForm } from "react-hook-form"
import { zodResolver } from "@hookform/resolvers/zod"
import { useDebounce } from "react-use"
import { toast } from "sonner"
import Image from "next/image"
import { z } from "zod"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Textarea } from "@/components/ui/textarea"
import { Form, FormField, FormItem, FormLabel, FormControl } from "@/components/ui/form"
import { BoxIcon, PlusIcon, Trash2Icon, PieChartIcon, Bookmark, GraduationCap, Check } from "lucide-react"
import { cn, ensureUrlProtocol, generateUniqueSlug, isUrl as LibIsUrl } from "@/lib/utils"
import { useAccount, useCoState } from "@/lib/providers/jazz-provider"
import { LinkMetadata, PersonalLink } from "@/lib/schema/personal-link"
import { createLinkSchema } from "./schema"
import { TopicSelector } from "./partial/topic-section"
import { useAtom } from "jotai"
import { linkEditIdAtom, linkShowCreateAtom } from "@/store/link"
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuLabel,
DropdownMenuTrigger
} from "@/components/ui/dropdown-menu"
import { useAtom } from "jotai"
import React, { useEffect, useRef, useState } from "react"
import { useKey } from "react-use"
export type LinkFormValues = z.infer<typeof createLinkSchema>
const DEFAULT_FORM_VALUES: Partial<LinkFormValues> = {
title: "",
description: "",
topic: "",
isLink: false,
meta: null
}
import { globalLinkFormExceptionRefsAtom, LinkForm } from "./link-form"
import { LaIcon } from "@/components/custom/la-icon"
import LinkOptions from "@/components/LinkOptions"
// import { FloatingButton } from "./partial/floating-button"
const LinkManage: React.FC = () => {
const [showCreate, setShowCreate] = useAtom(linkShowCreateAtom)
const [, setEditId] = useAtom(linkEditIdAtom)
const formRef = useRef<HTMLFormElement>(null)
const [editId, setEditId] = useAtom(linkEditIdAtom)
const [, setGlobalExceptionRefs] = useAtom(globalLinkFormExceptionRefsAtom)
const [showOptions, setShowOptions] = useState(false)
const optionsRef = useRef<HTMLDivElement>(null)
const buttonRef = useRef<HTMLButtonElement>(null)
const toggleForm = (event: React.MouseEvent) => {
event.stopPropagation()
if (showCreate) return
setShowCreate(prev => !prev)
}
useEffect(() => {
const clickOptionsButton = (e: React.MouseEvent) => {
e.preventDefault()
setShowOptions(prev => !prev)
}
const handleFormClose = () => {
setShowCreate(false)
}
const handleFormFail = () => {}
// wipes the data from the form when the form is closed
React.useEffect(() => {
if (!showCreate) {
formRef.current?.reset()
setEditId(null)
}
}, [showCreate, setEditId])
useKey("Escape", handleFormClose)
useEffect(() => {
const handleOutsideClick = (event: MouseEvent) => {
if (
formRef.current &&
!formRef.current.contains(event.target as Node) &&
buttonRef.current &&
!buttonRef.current.contains(event.target as Node)
) {
setShowCreate(false)
const handleClickOutside = (event: MouseEvent) => {
if (optionsRef.current && !optionsRef.current.contains(event.target as Node)) {
setShowOptions(false)
}
}
if (showCreate) {
document.addEventListener("mousedown", handleOutsideClick)
if (showOptions) {
document.addEventListener("mousedown", handleClickOutside)
}
return () => {
document.removeEventListener("mousedown", handleOutsideClick)
document.removeEventListener("mousedown", handleClickOutside)
}
}, [showCreate, setShowCreate])
}, [showOptions])
useKey("Escape", () => {
setShowCreate(false)
})
/*
* This code means that when link form is opened, these refs will be added as an exception to the click outside handler
*/
React.useEffect(() => {
setGlobalExceptionRefs([optionsRef, buttonRef])
}, [setGlobalExceptionRefs])
return (
<>
{showCreate && (
<div className="z-50">
<LinkForm ref={formRef} onSuccess={() => setShowCreate(false)} onCancel={() => setShowCreate(false)} />
{showCreate && <LinkForm onClose={handleFormClose} onSuccess={handleFormClose} onFail={handleFormFail} />}
<div className="absolute bottom-0 m-0 flex w-full list-none bg-inherit p-2.5 text-center align-middle font-semibold leading-[13px] no-underline">
<div className="mx-auto flex flex-row items-center justify-center gap-2">
<Button
variant="ghost"
onClick={toggleForm}
className={editId || showCreate ? "text-red-500 hover:bg-red-500/50 hover:text-white" : ""}
>
<LaIcon name={showCreate ? "X" : editId ? "Trash" : "Plus"} />
</Button>
<div className="relative" ref={optionsRef}>
{showOptions && <LinkOptions />}
<Button ref={buttonRef} variant="ghost" onClick={clickOptionsButton}>
<LaIcon name="Ellipsis" />
</Button>
</div>
</div>
)}
<CreateButton ref={buttonRef} onClick={toggleForm} isOpen={showCreate} />
</div>
</>
)
}
const CreateButton = React.forwardRef<
HTMLButtonElement,
{
onClick: (event: React.MouseEvent) => void
isOpen: boolean
}
>(({ onClick, isOpen }, ref) => (
<Button
ref={ref}
className={cn(
"absolute bottom-4 right-4 size-12 rounded-full bg-[#274079] p-0 text-white transition-transform hover:bg-[#274079]/90",
{ "rotate-45 transform": isOpen }
)}
onClick={onClick}
>
<PlusIcon className="size-6" />
</Button>
))
CreateButton.displayName = "CreateButton"
interface LinkFormProps extends React.ComponentPropsWithoutRef<"form"> {
onSuccess?: () => void
onCancel?: () => void
personalLink?: PersonalLink
}
const LinkForm = React.forwardRef<HTMLFormElement, LinkFormProps>(({ onSuccess, onCancel, personalLink }, ref) => {
const [isFetching, setIsFetching] = useState(false)
const { me } = useAccount()
const form = useForm<LinkFormValues>({
resolver: zodResolver(createLinkSchema),
defaultValues: {
...DEFAULT_FORM_VALUES,
isLink: true
}
})
const selectedLink = useCoState(PersonalLink, personalLink?.id)
const title = form.watch("title")
const [inputValue, setInputValue] = useState("")
const [originalLink, setOriginalLink] = useState<string>("")
const [linkValidation, setLinkValidation] = useState<string | null>(null)
const [invalidLink, setInvalidLink] = useState(false)
const [showLink, setShowLink] = useState(false)
const [debouncedText, setDebouncedText] = useState<string>("")
useDebounce(() => setDebouncedText(title), 300, [title])
const [showStatusOptions, setShowStatusOptions] = useState(false)
const [selectedStatus, setSelectedStatus] = useState<string | null>(null)
const statusOptions = [
{
text: "To Learn",
icon: <Bookmark size={16} />,
color: "text-white/70"
},
{
text: "Learning",
icon: <GraduationCap size={16} />,
color: "text-[#D29752]"
},
{ text: "Learned", icon: <Check size={16} />, color: "text-[#708F51]" }
]
const statusSelect = (status: string) => {
setSelectedStatus(status === selectedStatus ? null : status)
setShowStatusOptions(false)
}
useEffect(() => {
if (selectedLink) {
form.setValue("title", selectedLink.title)
form.setValue("description", selectedLink.description ?? "")
form.setValue("isLink", selectedLink.isLink)
form.setValue("meta", selectedLink.meta)
}
}, [selectedLink, form])
const changeInput = (e: React.ChangeEvent<HTMLInputElement>) => {
const value = e.target.value
setInputValue(value)
form.setValue("title", value)
}
const pressEnter = (e: React.KeyboardEvent<HTMLInputElement>) => {
if (e.key === "Enter" && !showLink) {
e.preventDefault()
const trimmedValue = inputValue.trim().toLowerCase()
if (LibIsUrl(trimmedValue)) {
setShowLink(true)
setInvalidLink(false)
setLinkValidation(trimmedValue)
setInputValue(trimmedValue)
form.setValue("title", trimmedValue)
} else {
setInvalidLink(true)
setShowLink(true)
setLinkValidation(null)
}
}
}
useEffect(() => {
const fetchMetadata = async (url: string) => {
setIsFetching(true)
try {
const res = await fetch(`/api/metadata?url=${encodeURIComponent(url)}`, { cache: "force-cache" })
if (!res.ok) throw new Error("Failed to fetch metadata")
const data = await res.json()
form.setValue("isLink", true)
form.setValue("meta", data)
form.setValue("title", data.title)
form.setValue("description", data.description)
setOriginalLink(url)
} catch (err) {
form.setValue("isLink", false)
form.setValue("meta", null)
form.setValue("title", debouncedText)
form.setValue("description", "")
setOriginalLink("")
} finally {
setIsFetching(false)
}
}
if (showLink && !invalidLink && LibIsUrl(form.getValues("title").toLowerCase())) {
fetchMetadata(ensureUrlProtocol(form.getValues("title").toLowerCase()))
}
}, [showLink, invalidLink, form])
const onSubmit = (values: LinkFormValues) => {
if (isFetching) return
try {
let linkMetadata: LinkMetadata | undefined
const personalLinks = me.root?.personalLinks?.toJSON() || []
const slug = generateUniqueSlug(personalLinks, values.title)
if (values.isLink && values.meta) {
linkMetadata = LinkMetadata.create(values.meta, { owner: me._owner })
}
if (selectedLink) {
selectedLink.title = values.title
selectedLink.slug = slug
selectedLink.description = values.description ?? ""
selectedLink.isLink = values.isLink
if (values.isLink && values.meta) {
linkMetadata = LinkMetadata.create(values.meta, { owner: me._owner })
}
} else {
const newPersonalLink = PersonalLink.create(
{
title: values.title,
slug,
description: values.description,
sequence: me.root?.personalLinks?.length || 1,
completed: false,
isLink: values.isLink,
meta: linkMetadata
// topic: values.topic
},
{ owner: me._owner }
)
me.root?.personalLinks?.push(newPersonalLink)
}
form.reset(DEFAULT_FORM_VALUES)
onSuccess?.()
} catch (error) {
console.error("Failed to create/update link", error)
toast.error(personalLink ? "Failed to update link" : "Failed to create link")
}
}
const undoEditing: () => void = () => {
form.reset(DEFAULT_FORM_VALUES)
onCancel?.()
}
return (
<div className="p-3 transition-all">
<div className="rounded-md border bg-muted/50">
<Form {...form}>
<form onSubmit={form.handleSubmit(onSubmit)} className="relative min-w-0 flex-1" ref={ref}>
<div className="flex flex-row p-3">
<div className="flex flex-auto flex-col gap-1.5">
<div className="flex flex-row items-start justify-between">
<div className="flex grow flex-row items-center gap-1.5">
{/* <Button
type="button"
variant="secondary"
size="icon"
aria-label="Choose icon"
className="size-7 text-primary/60"
>
{form.watch("isLink") ? (
<Image
src={form.watch("meta")?.favicon || ""}
alt={form.watch("meta")?.title || ""}
className="size-5 rounded-md"
width={16}
height={16}
/>
) : (
<BoxIcon size={16} />
)}
</Button> */}
<FormField
control={form.control}
name="title"
render={({ field }) => (
<FormItem className="grow space-y-0">
<FormLabel className="sr-only">Text</FormLabel>
<FormControl>
<Input
{...field}
value={inputValue}
autoComplete="off"
maxLength={100}
autoFocus
placeholder="Paste a link or write a link"
className={cn(
"h-6 border-none p-1.5 font-medium placeholder:text-primary/40 focus-visible:outline-none focus-visible:ring-0",
invalidLink ? "text-red-500" : ""
)}
onKeyDown={pressEnter}
onChange={changeInput}
/>
</FormControl>
</FormItem>
)}
/>
{showLink && (
<span className={cn("mr-5 max-w-[200px] truncate text-xs", invalidLink ? "text-red-500" : "")}>
{invalidLink ? "Only links are allowed" : linkValidation || originalLink || ""}
</span>
)}
</div>
<div className="flex min-w-0 shrink-0 cursor-pointer select-none flex-row">
<DropdownMenu>
<DropdownMenuTrigger asChild></DropdownMenuTrigger>
<DropdownMenuContent align="end">
<DropdownMenuLabel>Actions</DropdownMenuLabel>
<DropdownMenuItem className="group">
<Trash2Icon size={16} className="mr-2 text-destructive group-hover:text-red-500" />
<span>Delete</span>
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
<div className="relative">
<Button
size="icon"
type="button"
variant="ghost"
className="size-7 gap-x-2 text-sm"
onClick={() => setShowStatusOptions(!showStatusOptions)}
>
{selectedStatus ? (
(() => {
const option = statusOptions.find(opt => opt.text === selectedStatus)
return option
? React.cloneElement(option.icon, {
size: 16,
className: option.color
})
: null
})()
) : (
<PieChartIcon size={16} className="text-primary/60" />
)}
</Button>
{showStatusOptions && (
<div className="absolute right-0 mt-1 w-40 rounded-md bg-neutral-800 shadow-lg">
{statusOptions.map(option => (
<Button
key={option.text}
onClick={() => statusSelect(option.text)}
className={`flex w-full items-center justify-start space-x-2 rounded-md px-3 py-2 text-sm font-medium hover:bg-neutral-700 ${option.color} bg-inherit`}
>
{React.cloneElement(option.icon, {
size: 16,
className: option.color
})}
<span>{option.text}</span>
</Button>
))}
</div>
)}
</div>
</div>
</div>
<div className="flex flex-row items-center gap-1.5 pl-8">
<FormField
control={form.control}
name="description"
render={({ field }) => (
<FormItem className="grow space-y-0">
<FormLabel className="sr-only">Description</FormLabel>
<FormControl>
<Textarea
{...field}
autoComplete="off"
placeholder="Description (optional)"
className="min-h-[24px] resize-none overflow-y-auto border-none p-1.5 text-xs font-medium shadow-none placeholder:text-primary/40 focus-visible:outline-none focus-visible:ring-0"
onInput={e => {
const target = e.target as HTMLTextAreaElement
target.style.height = "auto"
target.style.height = `${target.scrollHeight}px`
}}
/>
</FormControl>
</FormItem>
)}
/>
</div>
</div>
</div>
<div className="flex flex-auto flex-row items-center justify-between gap-2 rounded-b-md border border-t px-3 py-2">
<div className="flex flex-row items-center gap-0.5">
<div className="flex min-w-0 shrink-0 cursor-pointer select-none flex-row">
<TopicSelector />
</div>
</div>
<div className="flex w-auto items-center justify-end">
<div className="flex min-w-0 shrink-0 cursor-pointer select-none flex-row gap-x-2">
<Button size="sm" type="button" variant="ghost" onClick={undoEditing}>
Cancel
</Button>
<Button size="sm" type="submit" disabled={isFetching}>
Save
</Button>
</div>
</div>
</div>
</form>
</Form>
</div>
</div>
)
})
LinkManage.displayName = "LinkManage"
LinkForm.displayName = "LinkForm"
export { LinkManage, LinkForm }
export { LinkManage }
/* <FloatingButton ref={buttonRef} onClick={toggleForm} isOpen={showCreate} /> */

View File

@@ -0,0 +1,33 @@
import * as React from "react"
import { useFormContext } from "react-hook-form"
import { FormField, FormItem, FormControl, FormLabel } from "@/components/ui/form"
import { TextareaAutosize } from "@/components/custom/textarea-autosize"
import { LinkFormValues } from "../schema"
interface DescriptionInputProps {}
export const DescriptionInput: React.FC<DescriptionInputProps> = () => {
const form = useFormContext<LinkFormValues>()
return (
<div>
<FormField
control={form.control}
name="description"
render={({ field }) => (
<FormItem className="grow space-y-0">
<FormLabel className="sr-only">Description</FormLabel>
<FormControl>
<TextareaAutosize
{...field}
autoComplete="off"
placeholder="Description (optional)"
className="placeholder:text-muted-foreground/70 resize-none overflow-y-auto border-none p-1.5 text-[13px] font-medium shadow-none focus-visible:ring-0"
/>
</FormControl>
</FormItem>
)}
/>
</div>
)
}

View File

@@ -0,0 +1,28 @@
import React, { forwardRef } from "react"
import { cn } from "@/lib/utils"
import { LaIcon } from "@/components/custom/la-icon"
import { Button, ButtonProps } from "@/components/ui/button"
interface FloatingButtonProps extends ButtonProps {
isOpen: boolean
}
export const FloatingButton = forwardRef<HTMLButtonElement, FloatingButtonProps>(
({ isOpen, className, ...props }, ref) => (
<Button
ref={ref}
className={cn(
"absolute bottom-4 right-4 h-12 w-12 rounded-full bg-[#274079] p-0 text-white transition-transform hover:bg-[#274079]/90",
{ "rotate-45 transform": isOpen },
className
)}
{...props}
>
<LaIcon name="Plus" className="h-6 w-6" />
</Button>
)
)
FloatingButton.displayName = "FloatingButton"
export default FloatingButton

View File

@@ -0,0 +1,90 @@
import { Button } from "@/components/ui/button"
import { Command, CommandInput, CommandList, CommandItem, CommandGroup } from "@/components/ui/command"
import { FormField, FormItem, FormLabel, FormControl } from "@/components/ui/form"
import { Popover, PopoverTrigger, PopoverContent } from "@/components/ui/popover"
import { ScrollArea } from "@/components/ui/scroll-area"
import { useFormContext } from "react-hook-form"
import { cn } from "@/lib/utils"
import { LaIcon } from "@/components/custom/la-icon"
import { useAtom } from "jotai"
import { linkLearningStateSelectorAtom } from "@/store/link"
import { useMemo } from "react"
import { LinkFormValues } from "../schema"
import { LEARNING_STATES } from "@/lib/constants"
export const LearningStateSelector: React.FC = () => {
const [islearningStateSelectorOpen, setIslearningStateSelectorOpen] = useAtom(linkLearningStateSelectorAtom)
const form = useFormContext<LinkFormValues>()
const selectedLearningState = useMemo(
() => LEARNING_STATES.find(ls => ls.value === form.getValues("learningState")),
[form]
)
return (
<FormField
control={form.control}
name="learningState"
render={({ field }) => (
<FormItem className="space-y-0">
<FormLabel className="sr-only">Topic</FormLabel>
<Popover open={islearningStateSelectorOpen} onOpenChange={setIslearningStateSelectorOpen}>
<PopoverTrigger asChild>
<FormControl>
<Button size="sm" type="button" role="combobox" variant="secondary" className="gap-x-2 text-sm">
{selectedLearningState?.icon && (
<LaIcon
name={selectedLearningState.icon}
className={cn("h-4 w-4", selectedLearningState.className)}
/>
)}
<span className={cn("truncate", selectedLearningState?.className || "")}>
{selectedLearningState?.label || "Select state"}
</span>
<LaIcon name="ChevronDown" />
</Button>
</FormControl>
</PopoverTrigger>
<PopoverContent
className="w-52 rounded-lg p-0"
side="bottom"
align="end"
onCloseAutoFocus={e => e.preventDefault()}
>
<Command>
<CommandInput placeholder="Search state..." className="h-9" />
<CommandList>
<ScrollArea>
<CommandGroup>
{LEARNING_STATES.map(ls => (
<CommandItem
key={ls.value}
value={ls.value}
onSelect={value => {
field.onChange(value)
setIslearningStateSelectorOpen(false)
}}
>
<LaIcon name={ls.icon} className={cn("mr-2", ls.className)} />
<span className={ls.className}>{ls.label}</span>
<LaIcon
name="Check"
size={16}
className={cn(
"absolute right-3",
ls.value === field.value ? "text-primary" : "text-transparent"
)}
/>
</CommandItem>
))}
</CommandGroup>
</ScrollArea>
</CommandList>
</Command>
</PopoverContent>
</Popover>
</FormItem>
)}
/>
)
}

View File

@@ -0,0 +1,36 @@
import { FormField, FormItem, FormLabel, FormControl } from "@/components/ui/form"
import { useFormContext } from "react-hook-form"
import { Input } from "@/components/ui/input"
import { cn } from "@/lib/utils"
import { LaIcon } from "@/components/custom/la-icon"
import { LinkFormValues } from "../schema"
export const NotesSection: React.FC = () => {
const form = useFormContext<LinkFormValues>()
return (
<FormField
control={form.control}
name="notes"
render={({ field }) => (
<FormItem className="relative space-y-0">
<FormLabel className="sr-only">Note</FormLabel>
<FormControl>
<>
<div className="pointer-events-none absolute inset-y-0 left-0 flex items-center pl-3">
<LaIcon name="Pencil" aria-hidden="true" className="text-muted-foreground/70 size-3" />
</div>
<Input
{...field}
autoComplete="off"
placeholder="Take a notes..."
className={cn("placeholder:text-muted-foreground/70 border-none pl-8 shadow-none focus-visible:ring-0")}
/>
</>
</FormControl>
</FormItem>
)}
/>
)
}

View File

@@ -0,0 +1,36 @@
import * as React from "react"
import { useFormContext } from "react-hook-form"
import { FormField, FormItem, FormControl, FormLabel } from "@/components/ui/form"
import { Input } from "@/components/ui/input"
import { LinkFormValues } from "../schema"
interface TitleInputProps {
urlFetched: string | null
}
export const TitleInput: React.FC<TitleInputProps> = ({ urlFetched }) => {
const form = useFormContext<LinkFormValues>()
return (
<FormField
control={form.control}
name="title"
render={({ field }) => (
<FormItem className="grow space-y-0">
<FormLabel className="sr-only">Title</FormLabel>
<FormControl>
<Input
{...field}
type={urlFetched ? "text" : "hidden"}
autoComplete="off"
maxLength={100}
autoFocus
placeholder="Title"
className="placeholder:text-muted-foreground/70 h-8 border-none p-1.5 text-[15px] font-semibold shadow-none focus-visible:ring-0"
/>
</FormControl>
</FormItem>
)}
/>
)
}

View File

@@ -1,74 +0,0 @@
import { Button } from "@/components/ui/button"
import { Command, CommandInput, CommandList, CommandItem } from "@/components/ui/command"
import { FormField, FormItem, FormLabel, FormControl } from "@/components/ui/form"
import { Popover, PopoverTrigger, PopoverContent } from "@/components/ui/popover"
import { useState } from "react"
import { ScrollArea } from "@/components/ui/scroll-area"
import { CheckIcon, ChevronDownIcon } from "lucide-react"
import { useFormContext } from "react-hook-form"
import { LinkFormValues } from "../manage"
import { cn } from "@/lib/utils"
const TOPICS = [
{ id: "1", name: "Work" },
{ id: "2", name: "Personal" }
]
export const TopicSelector: React.FC = () => {
const form = useFormContext<LinkFormValues>()
const [open, setOpen] = useState(false)
const { setValue } = useFormContext()
return (
<FormField
control={form.control}
name="topic"
render={({ field }) => (
<FormItem>
<FormLabel className="sr-only">Topic</FormLabel>
<Popover open={open} onOpenChange={setOpen}>
<PopoverTrigger asChild>
<FormControl>
<Button size="sm" type="button" role="combobox" variant="secondary" className="!mt-0 gap-x-2 text-sm">
<span className="truncate">
{field.value ? TOPICS.find(topic => topic.name === field.value)?.name : "Select topic"}
</span>
<ChevronDownIcon size={16} />
</Button>
</FormControl>
</PopoverTrigger>
<PopoverContent className="w-52 rounded-lg p-0" side="right" align="start">
<Command>
<CommandInput placeholder="Search topic..." className="h-9" />
<CommandList>
<ScrollArea>
{TOPICS.map(topic => (
<CommandItem
className="cursor-pointer"
key={topic.id}
value={topic.name}
onSelect={value => {
setValue("topic", value)
setOpen(false)
}}
>
{topic.name}
<CheckIcon
size={16}
className={cn(
"absolute right-3",
topic.name === field.value ? "text-primary" : "text-transparent"
)}
/>
</CommandItem>
))}
</ScrollArea>
</CommandList>
</Command>
</PopoverContent>
</Popover>
</FormItem>
)}
/>
)
}

View File

@@ -0,0 +1,90 @@
import { Button } from "@/components/ui/button"
import { Command, CommandInput, CommandList, CommandItem, CommandGroup } from "@/components/ui/command"
import { Popover, PopoverTrigger, PopoverContent } from "@/components/ui/popover"
import { ScrollArea } from "@/components/ui/scroll-area"
import { CheckIcon } from "lucide-react"
import { useFormContext } from "react-hook-form"
import { cn } from "@/lib/utils"
import { useAtom } from "jotai"
import { linkTopicSelectorAtom } from "@/store/link"
import { LinkFormValues } from "../schema"
import { useCoState } from "@/lib/providers/jazz-provider"
import { PublicGlobalGroup } from "@/lib/schema/master/public-group"
import { ID } from "jazz-tools"
import { LaIcon } from "@/components/custom/la-icon"
import { Topic } from "@/lib/schema"
interface TopicSelectorProps {
onSelect?: (value: Topic) => void
}
export const TopicSelector: React.FC<TopicSelectorProps> = ({ onSelect }) => {
const globalGroup = useCoState(
PublicGlobalGroup,
process.env.NEXT_PUBLIC_JAZZ_GLOBAL_GROUP as ID<PublicGlobalGroup>,
{
root: {
topics: []
}
}
)
const [isTopicSelectorOpen, setIsTopicSelectorOpen] = useAtom(linkTopicSelectorAtom)
const form = useFormContext<LinkFormValues>()
const handleSelect = (value: string) => {
const topic = globalGroup?.root.topics.find(topic => topic?.name === value)
if (topic) {
onSelect?.(topic)
form?.setValue("topic", value)
}
setIsTopicSelectorOpen(false)
}
const selectedValue = form ? form.watch("topic") : null
return (
<Popover open={isTopicSelectorOpen} onOpenChange={setIsTopicSelectorOpen}>
<PopoverTrigger asChild>
<Button size="sm" type="button" role="combobox" variant="secondary" className="gap-x-2 text-sm">
<span className="truncate">
{selectedValue
? globalGroup?.root.topics.find(topic => topic?.id && topic.name === selectedValue)?.prettyName
: "Topic"}
</span>
<LaIcon name="ChevronDown" />
</Button>
</PopoverTrigger>
<PopoverContent
className="z-50 w-52 rounded-lg p-0"
side="bottom"
align="end"
onCloseAutoFocus={e => e.preventDefault()}
>
<Command>
<CommandInput placeholder="Search topic..." className="h-9" />
<CommandList>
<ScrollArea>
<CommandGroup>
{globalGroup?.root.topics.map(
topic =>
topic?.id && (
<CommandItem key={topic.id} value={topic.name} onSelect={handleSelect}>
{topic.prettyName}
<CheckIcon
size={16}
className={cn(
"absolute right-3",
topic.name === selectedValue ? "text-primary" : "text-transparent"
)}
/>
</CommandItem>
)
)}
</CommandGroup>
</ScrollArea>
</CommandList>
</Command>
</PopoverContent>
</Popover>
)
}

View File

@@ -0,0 +1,35 @@
import * as React from "react"
import { useFormContext } from "react-hook-form"
import { Badge } from "@/components/ui/badge"
import { Button } from "@/components/ui/button"
import { LaIcon } from "@/components/custom/la-icon"
import { LinkFormValues } from "../schema"
interface UrlBadgeProps {
urlFetched: string | null
handleResetUrl: () => void
}
export const UrlBadge: React.FC<UrlBadgeProps> = ({ urlFetched, handleResetUrl }) => {
const form = useFormContext<LinkFormValues>()
if (!urlFetched) return null
return (
<div className="flex items-center gap-1.5 py-1.5">
<div className="flex min-w-0 flex-row items-center gap-1.5">
<Badge variant="secondary" className="relative truncate py-1 text-xs">
{form.getValues("url")}
<Button
size="icon"
type="button"
onClick={handleResetUrl}
className="text-muted-foreground hover:text-foreground ml-2 size-4 rounded-full bg-transparent hover:bg-transparent"
>
<LaIcon name="X" className="size-3.5" />
</Button>
</Badge>
</div>
</div>
)
}

View File

@@ -0,0 +1,71 @@
import * as React from "react"
import { useFormContext } from "react-hook-form"
import { FormField, FormItem, FormControl, FormLabel, FormMessage } from "@/components/ui/form"
import { Input } from "@/components/ui/input"
import { cn } from "@/lib/utils"
import { LinkFormValues } from "../schema"
import { TooltipProvider, Tooltip, TooltipTrigger, TooltipContent } from "@/components/ui/tooltip"
import { TooltipArrow } from "@radix-ui/react-tooltip"
interface UrlInputProps {
urlFetched: string | null
fetchMetadata: (url: string) => Promise<void>
isFetchingUrlMetadata: boolean
}
export const UrlInput: React.FC<UrlInputProps> = ({ urlFetched, fetchMetadata, isFetchingUrlMetadata }) => {
const [isFocused, setIsFocused] = React.useState(false)
const form = useFormContext<LinkFormValues>()
const handleKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {
if (e.key === "Enter" && form.getValues("url")) {
e.preventDefault()
fetchMetadata(form.getValues("url"))
}
}
const shouldShowTooltip = isFocused && !form.formState.errors.url && !!form.getValues("url") && !urlFetched
return (
<FormField
control={form.control}
name="url"
render={({ field }) => (
<FormItem
className={cn("grow space-y-0", {
"hidden select-none": urlFetched
})}
>
<FormLabel className="sr-only">Url</FormLabel>
<FormControl>
<TooltipProvider delayDuration={0}>
<Tooltip open={shouldShowTooltip && !isFetchingUrlMetadata}>
<TooltipTrigger asChild>
<Input
{...field}
type={urlFetched ? "hidden" : "text"}
autoComplete="off"
maxLength={100}
autoFocus
placeholder="Paste a link or write a link"
className="placeholder:text-muted-foreground/70 h-8 border-none p-1.5 text-[15px] font-semibold shadow-none focus-visible:ring-0"
onKeyDown={handleKeyDown}
onFocus={() => setIsFocused(true)}
onBlur={() => setIsFocused(false)}
/>
</TooltipTrigger>
<TooltipContent align="center" side="top">
<TooltipArrow className="text-primary fill-current" />
<span>
Press <kbd className="px-1.5">Enter</kbd> to fetch metadata
</span>
</TooltipContent>
</Tooltip>
</TooltipProvider>
</FormControl>
<FormMessage className="px-1.5" />
</FormItem>
)}
/>
)
}

View File

@@ -1,20 +1,15 @@
import { urlSchema } from "@/lib/utils/schema"
import { z } from "zod"
import { isUrl } from "@/lib/utils"
export const createLinkSchema = z.object({
url: urlSchema,
icon: z.string().optional(),
title: z.string().min(1, { message: "Title can't be empty" }),
originalUrl: z.string().refine(isUrl, { message: "Only links are allowed" }),
description: z.string().optional(),
topic: z.string().optional(),
isLink: z.boolean().default(true),
meta: z
.object({
url: z.string(),
title: z.string(),
favicon: z.string(),
description: z.string().optional().nullable()
})
.optional()
.nullable(),
completed: z.boolean().default(false)
completed: z.boolean().default(false),
notes: z.string().optional(),
learningState: z.enum(["wantToLearn", "learning", "learned"]),
topic: z.string().nullable().optional()
})
export type LinkFormValues = z.infer<typeof createLinkSchema>

View File

@@ -3,7 +3,6 @@
import * as React from "react"
import { ListFilterIcon } from "lucide-react"
import { Button } from "@/components/ui/button"
import Link from "next/link"
import { ContentHeader, SidebarToggleButton } from "@/components/custom/content-header"
import { useMedia } from "react-use"
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover"
@@ -11,20 +10,23 @@ import { Label } from "@/components/ui/label"
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
import { useAtom } from "jotai"
import { linkSortAtom } from "@/store/link"
import { atom } from "jotai"
import { LEARNING_STATES } from "@/lib/constants"
import { useQueryState, parseAsStringLiteral } from "nuqs"
import { FancySwitch } from "@omit/react-fancy-switch"
import { cn } from "@/lib/utils"
interface TabItemProps {
url: string
label: string
}
const ALL_STATES = [{ label: "All", value: "all", icon: "List", className: "text-foreground" }, ...LEARNING_STATES]
const ALL_STATES_STRING = ALL_STATES.map(ls => ls.value)
const TABS = ["All", "Learning", "To Learn", "Learned"]
export const learningStateAtom = atom<string>("all")
export const LinkHeader = () => {
export const LinkHeader = React.memo(() => {
const isTablet = useMedia("(max-width: 1024px)")
return (
<>
<ContentHeader className="p-4">
<ContentHeader className="px-6 py-5 max-lg:px-4">
<div className="flex min-w-0 shrink-0 items-center gap-1.5">
<SidebarToggleButton />
<div className="flex min-h-0 items-center">
@@ -32,7 +34,7 @@ export const LinkHeader = () => {
</div>
</div>
{!isTablet && <Tabs />}
{!isTablet && <LearningTab />}
<div className="flex flex-auto"></div>
@@ -41,66 +43,66 @@ export const LinkHeader = () => {
{isTablet && (
<div className="border-b-primary/5 flex min-h-10 flex-row items-start justify-between border-b px-6 py-2 max-lg:pl-4">
<Tabs />
<LearningTab />
</div>
)}
</>
)
}
})
const Tabs = () => {
const [activeTab, setActiveTab] = React.useState(TABS[0])
LinkHeader.displayName = "LinkHeader"
const LearningTab = React.memo(() => {
const [activeTab, setActiveTab] = useAtom(learningStateAtom)
const [activeState, setActiveState] = useQueryState(
"state",
parseAsStringLiteral(Object.values(ALL_STATES_STRING)).withDefault(ALL_STATES_STRING[0])
)
const handleTabChange = React.useCallback(
(value: string) => {
setActiveTab(value)
setActiveState(value)
},
[setActiveTab, setActiveState]
)
React.useEffect(() => {
setActiveTab(activeState)
}, [activeState, setActiveTab])
return (
<div className="bg-secondary/50 flex items-baseline overflow-x-hidden rounded-md">
{TABS.map(tab => (
<TabItem key={tab} url="#" label={tab} isActive={activeTab === tab} onClick={() => setActiveTab(tab)} />
))}
</div>
<FancySwitch
value={activeTab}
onChange={value => {
handleTabChange(value as string)
}}
options={ALL_STATES}
className="bg-secondary flex rounded-lg"
highlighterClassName="bg-secondary-foreground/10 rounded-lg"
radioClassName={cn(
"relative mx-2 flex h-8 cursor-pointer items-center justify-center rounded-full px-1 text-sm text-secondary-foreground/60 data-[checked]:text-secondary-foreground font-medium transition-colors focus:outline-none"
)}
highlighterIncludeMargin={true}
/>
)
}
})
interface TabItemProps {
url: string
label: string
isActive: boolean
onClick: () => void
}
const TabItem = ({ url, label, isActive, onClick }: TabItemProps) => {
return (
<div tabIndex={-1} className="rounded-md">
<div className="flex flex-row">
<div aria-label={label}>
<Link href={url}>
<Button
size="sm"
type="button"
variant="ghost"
className={`gap-x-2 truncate text-sm ${isActive ? "bg-accent text-accent-foreground" : ""}`}
onClick={onClick}
>
{label}
</Button>
</Link>
</div>
</div>
</div>
)
}
const FilterAndSort = () => {
const FilterAndSort = React.memo(() => {
const [sort, setSort] = useAtom(linkSortAtom)
const [sortOpen, setSortOpen] = React.useState(false)
const getFilterText = () => {
const getFilterText = React.useCallback(() => {
return sort.charAt(0).toUpperCase() + sort.slice(1)
}
}, [sort])
const handleSortChange = (value: string) => {
setSort(value)
setSortOpen(false)
}
const handleSortChange = React.useCallback(
(value: string) => {
setSort(value)
setSortOpen(false)
},
[setSort]
)
return (
<div className="flex w-auto items-center justify-end">
@@ -134,4 +136,6 @@ const FilterAndSort = () => {
</div>
</div>
)
}
})
FilterAndSort.displayName = "FilterAndSort"

View File

@@ -1,17 +1,22 @@
"use client"
import * as React from "react"
import { Button } from "@/components/ui/button"
import { Checkbox } from "@/components/ui/checkbox"
import { LinkIcon, Trash2Icon } from "lucide-react"
import Link from "next/link"
import Image from "next/image"
import { useSortable } from "@dnd-kit/sortable"
import { CSS } from "@dnd-kit/utilities"
import { PersonalLink } from "@/lib/schema/personal-link"
import { cn } from "@/lib/utils"
import { LinkForm } from "./form/manage"
import { Button } from "@/components/ui/button"
import { useSortable } from "@dnd-kit/sortable"
import { CSS } from "@dnd-kit/utilities"
import { ConfirmOptions } from "@omit/react-confirm-dialog"
import { LinkIcon, Trash2Icon } from "lucide-react"
import Image from "next/image"
import Link from "next/link"
import * as React from "react"
import { LinkForm } from "./form/link-form"
import { Command, CommandInput, CommandList, CommandItem, CommandGroup } from "@/components/ui/command"
import { Popover, PopoverTrigger, PopoverContent } from "@/components/ui/popover"
import { ScrollArea } from "@/components/ui/scroll-area"
import { LaIcon } from "@/components/custom/la-icon"
import { LEARNING_STATES } from "@/lib/constants"
import { Badge } from "@/components/ui/badge"
interface ListItemProps {
@@ -25,6 +30,8 @@ interface ListItemProps {
setFocusedId: (id: string | null) => void
registerRef: (id: string, ref: HTMLLIElement | null) => void
onDelete?: (personalLink: PersonalLink) => void
showDeleteIconForLinkId: string | null
setShowDeleteIconForLinkId: (id: string | null) => void
}
export const ListItem: React.FC<ListItemProps> = ({
@@ -37,11 +44,11 @@ export const ListItem: React.FC<ListItemProps> = ({
isFocused,
setFocusedId,
registerRef,
onDelete
onDelete,
showDeleteIconForLinkId,
setShowDeleteIconForLinkId
}) => {
const { attributes, listeners, setNodeRef, transform, transition } = useSortable({ id: personalLink.id, disabled })
const formRef = React.useRef<HTMLFormElement>(null)
const [showDeleteIcon, setShowDeleteIcon] = React.useState(false)
const style = {
transform: CSS.Transform.toString(transform),
@@ -49,12 +56,6 @@ export const ListItem: React.FC<ListItemProps> = ({
pointerEvents: isDragging ? "none" : "auto"
}
React.useEffect(() => {
if (isEditing) {
formRef.current?.focus()
}
}, [isEditing])
const refCallback = React.useCallback(
(node: HTMLLIElement | null) => {
setNodeRef(node)
@@ -74,19 +75,17 @@ export const ListItem: React.FC<ListItemProps> = ({
setEditId(null)
}
const handleCancel = () => {
const handleOnClose = () => {
setEditId(null)
}
// const handleRowClick = () => {
// console.log("Row clicked", personalLink.id)
// setEditId(personalLink.id)
// }
const handleRowClick = () => {
setShowDeleteIcon(!showDeleteIcon)
}
const handleOnFail = () => {}
const handleDoubleClick = () => {
// const handleRowClick = () => {
// setShowDeleteIconForLinkId(personalLink.id)
// }
const handleRowDoubleClick = () => {
setEditId(personalLink.id)
}
@@ -116,8 +115,12 @@ export const ListItem: React.FC<ListItemProps> = ({
}
}
const selectedLearningState = LEARNING_STATES.find(ls => ls.value === personalLink.learningState)
if (isEditing) {
return <LinkForm ref={formRef} personalLink={personalLink} onSuccess={handleSuccess} onCancel={handleCancel} />
return (
<LinkForm onClose={handleOnClose} personalLink={personalLink} onSuccess={handleSuccess} onFail={handleOnFail} />
)
}
return (
@@ -128,27 +131,74 @@ export const ListItem: React.FC<ListItemProps> = ({
{...listeners}
tabIndex={0}
onFocus={() => setFocusedId(personalLink.id)}
onBlur={() => setFocusedId(null)}
onBlur={() => {
setFocusedId(null)
}}
onKeyDown={handleKeyDown}
className={cn("hover:bg-muted/50 relative flex h-14 cursor-default items-center outline-none xl:h-11", {
"bg-muted/50": isFocused
})}
onClick={handleRowClick}
onDoubleClick={handleDoubleClick}
// onClick={handleRowClick}
onDoubleClick={handleRowDoubleClick}
>
<div className="flex grow justify-between gap-x-6 px-6 max-lg:px-4">
<div className="flex min-w-0 items-center gap-x-4">
<Checkbox
{/* <Checkbox
checked={personalLink.completed}
onClick={e => e.stopPropagation()}
onCheckedChange={() => {
personalLink.completed = !personalLink.completed
}}
className="border-muted-foreground border"
/>
{personalLink.isLink && personalLink.meta && (
/> */}
<Popover>
<PopoverTrigger asChild>
<Button size="sm" type="button" role="combobox" variant="secondary" className="size-7 shrink-0 p-0">
{selectedLearningState?.icon && (
<LaIcon name={selectedLearningState.icon} className={cn(selectedLearningState.className)} />
)}
</Button>
</PopoverTrigger>
<PopoverContent
className="w-52 rounded-lg p-0"
side="bottom"
align="start"
onCloseAutoFocus={e => e.preventDefault()}
>
<Command>
<CommandInput placeholder="Search state..." className="h-9" />
<CommandList>
<ScrollArea>
<CommandGroup>
{LEARNING_STATES.map(ls => (
<CommandItem
key={ls.value}
value={ls.value}
onSelect={value => {
personalLink.learningState = value as "wantToLearn" | "learning" | "learned" | undefined
}}
>
<LaIcon name={ls.icon} className={cn("mr-2", ls.className)} />
<span className={ls.className}>{ls.label}</span>
<LaIcon
name="Check"
size={16}
className={cn(
"absolute right-3",
ls.value === personalLink.learningState ? "text-primary" : "text-transparent"
)}
/>
</CommandItem>
))}
</CommandGroup>
</ScrollArea>
</CommandList>
</Command>
</PopoverContent>
</Popover>
{personalLink.icon && (
<Image
src={personalLink.meta.favicon}
src={personalLink.icon}
alt={personalLink.title}
className="size-5 rounded-full"
width={16}
@@ -160,14 +210,14 @@ export const ListItem: React.FC<ListItemProps> = ({
<p className="text-primary hover:text-primary line-clamp-1 text-sm font-medium xl:truncate">
{personalLink.title}
</p>
{personalLink.isLink && personalLink.meta && (
{personalLink.url && (
<div className="group flex items-center gap-x-1">
<LinkIcon
aria-hidden="true"
className="text-muted-foreground group-hover:text-primary size-3 flex-none"
/>
<Link
href={personalLink.meta.url}
href={personalLink.url}
passHref
prefetch={false}
target="_blank"
@@ -176,7 +226,7 @@ export const ListItem: React.FC<ListItemProps> = ({
}}
className="text-muted-foreground hover:text-primary text-xs"
>
<span className="xl:truncate">{personalLink.meta.url}</span>
<span className="xl:truncate">{personalLink.url}</span>
</Link>
</div>
)}
@@ -185,12 +235,15 @@ export const ListItem: React.FC<ListItemProps> = ({
</div>
<div className="flex shrink-0 items-center gap-x-4">
<Badge variant="secondary">Topic Name</Badge>
{showDeleteIcon && (
{personalLink.topic && <Badge variant="secondary">{personalLink.topic.prettyName}</Badge>}
{showDeleteIconForLinkId === personalLink.id && (
<Button
size="icon"
className="text-destructive h-auto w-auto bg-transparent hover:bg-transparent hover:text-red-500"
onClick={e => handleDelete(e, personalLink)}
onClick={e => {
e.stopPropagation()
handleDelete(e, personalLink)
}}
>
<Trash2Icon size={16} />
</Button>

View File

@@ -19,8 +19,10 @@ import { useKey } from "react-use"
import { useConfirm } from "@omit/react-confirm-dialog"
import { ListItem } from "./list-item"
import { useRef, useState, useCallback, useEffect } from "react"
import { learningStateAtom } from "./header"
const LinkList = () => {
const [activeLearningState] = useAtom(learningStateAtom)
const confirm = useConfirm()
const { me } = useAccount({
root: { personalLinks: [] }
@@ -32,11 +34,17 @@ const LinkList = () => {
const [focusedId, setFocusedId] = useState<string | null>(null)
const [draggingId, setDraggingId] = useState<string | null>(null)
const linkRefs = useRef<{ [key: string]: HTMLLIElement | null }>({})
const [showDeleteIconForLinkId, setShowDeleteIconForLinkId] = useState<string | null>(null)
let filteredLinks = personalLinks.filter(link => {
if (activeLearningState === "all") return true
if (!link?.learningState) return false
return link.learningState === activeLearningState
})
let sortedLinks =
sort === "title" && personalLinks
? [...personalLinks].sort((a, b) => (a?.title || "").localeCompare(b?.title || ""))
: personalLinks
sort === "title" && filteredLinks
? [...filteredLinks].sort((a, b) => (a?.title || "").localeCompare(b?.title || ""))
: filteredLinks
sortedLinks = sortedLinks || []
const sensors = useSensors(
@@ -50,10 +58,6 @@ const LinkList = () => {
})
)
const overlayClick = () => {
setEditId(null)
}
const registerRef = useCallback((id: string, ref: HTMLLIElement | null) => {
linkRefs.current[id] = ref
}, [])
@@ -190,40 +194,39 @@ const LinkList = () => {
}
return (
<>
{editId && <div className="fixed inset-0 z-10" onClick={overlayClick} />}
<div className="relative z-20">
<DndContext
sensors={sensors}
collisionDetection={closestCenter}
onDragStart={handleDragStart}
onDragEnd={handleDragEnd}
>
<SortableContext items={sortedLinks.map(item => item?.id || "") || []} strategy={verticalListSortingStrategy}>
<ul role="list" className="divide-primary/5 divide-y">
{sortedLinks.map(
linkItem =>
linkItem && (
<ListItem
key={linkItem.id}
confirm={confirm}
isEditing={editId === linkItem.id}
setEditId={setEditId}
personalLink={linkItem}
disabled={sort !== "manual" || editId !== null}
registerRef={registerRef}
isDragging={draggingId === linkItem.id}
isFocused={focusedId === linkItem.id}
setFocusedId={setFocusedId}
onDelete={handleDelete}
/>
)
)}
</ul>
</SortableContext>
</DndContext>
</div>
</>
<div className="relative z-20">
<DndContext
sensors={sensors}
collisionDetection={closestCenter}
onDragStart={handleDragStart}
onDragEnd={handleDragEnd}
>
<SortableContext items={sortedLinks.map(item => item?.id || "") || []} strategy={verticalListSortingStrategy}>
<ul role="list" className="divide-primary/5 divide-y">
{sortedLinks.map(
linkItem =>
linkItem && (
<ListItem
key={linkItem.id}
confirm={confirm}
isEditing={editId === linkItem.id}
setEditId={setEditId}
personalLink={linkItem}
disabled={sort !== "manual" || editId !== null}
registerRef={registerRef}
isDragging={draggingId === linkItem.id}
isFocused={focusedId === linkItem.id}
setFocusedId={setFocusedId}
onDelete={handleDelete}
showDeleteIconForLinkId={showDeleteIconForLinkId}
setShowDeleteIconForLinkId={setShowDeleteIconForLinkId}
/>
)
)}
</ul>
</SortableContext>
</DndContext>
</div>
)
}