fix: Link, Pages, Topic, Hook and Others (#178)

* chore: remove useKeyDownListener

* chore: remove react-use, update jazz version and add query string

* chore: update jazz version

* chore: use simple mac or win utils code

* feat(util): add isTextInput

* feat(hooks): all needed hooks

* fix: link bunch stuff

* fix: page bunch stuff

* chore: bunch update for custom component

* chore: use throttle from internal hook

* chore: topic bunch stuff

* chore: update layout

* fix: truncate content header of topic detail
This commit is contained in:
Aslam
2024-09-23 23:16:02 +07:00
committed by GitHub
parent 21084cd3f3
commit 867478d55c
43 changed files with 616 additions and 466 deletions

View File

@@ -1,36 +1,20 @@
"use client"
import React, { useState } from "react"
import * as React from "react"
import { LinkHeader } from "@/components/routes/link/header"
import { LinkList } from "@/components/routes/link/list"
import { LinkManage } from "@/components/routes/link/manage"
import { useQueryState } from "nuqs"
import { atom } from "jotai"
import { LinkBottomBar } from "./bottom-bar"
import { useKey } from "react-use"
export const isDeleteConfirmShownAtom = atom(false)
export function LinkRoute(): React.ReactElement {
const [nuqsEditId, setNuqsEditId] = useQueryState("editId")
const [activeItemIndex, setActiveItemIndex] = useState<number | null>(null)
const [keyboardActiveIndex, setKeyboardActiveIndex] = useState<number | null>(null)
useKey("Escape", () => {
setNuqsEditId(null)
})
return (
<>
<LinkHeader />
<LinkManage />
<LinkList
key={nuqsEditId}
activeItemIndex={activeItemIndex}
setActiveItemIndex={setActiveItemIndex}
keyboardActiveIndex={keyboardActiveIndex}
setKeyboardActiveIndex={setKeyboardActiveIndex}
/>
<LinkList />
<LinkBottomBar />
</>
)

View File

@@ -1,11 +1,11 @@
"use client"
import React, { useCallback, useEffect, useMemo, useRef } from "react"
import * as React from "react"
import { motion, AnimatePresence } from "framer-motion"
import type { icons } from "lucide-react"
import { Button } from "@/components/ui/button"
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip"
import { cn, getShortcutKeys, isEditableElement } from "@/lib/utils"
import { cn, getShortcutKeys } from "@/lib/utils"
import { LaIcon } from "@/components/custom/la-icon"
import { useAtom } from "jotai"
import { parseAsBoolean, useQueryState } from "nuqs"
@@ -15,7 +15,6 @@ import { PersonalLink } from "@/lib/schema"
import { ID } from "jazz-tools"
import { globalLinkFormExceptionRefsAtom } from "./partials/form/link-form"
import { useLinkActions } from "./hooks/use-link-actions"
import { useKeydownListener } from "@/hooks/use-keydown-listener"
interface ToolbarButtonProps extends React.ComponentPropsWithoutRef<typeof Button> {
icon: keyof typeof icons
@@ -55,27 +54,27 @@ export const LinkBottomBar: React.FC = () => {
const { me } = useAccount({ root: { personalLinks: [] } })
const personalLink = useCoState(PersonalLink, editId as ID<PersonalLink>)
const cancelBtnRef = useRef<HTMLButtonElement>(null)
const confirmBtnRef = useRef<HTMLButtonElement>(null)
const overlayRef = useRef<HTMLDivElement>(null)
const contentRef = useRef<HTMLDivElement>(null)
const cancelBtnRef = React.useRef<HTMLButtonElement>(null)
const confirmBtnRef = React.useRef<HTMLButtonElement>(null)
const overlayRef = React.useRef<HTMLDivElement>(null)
const contentRef = React.useRef<HTMLDivElement>(null)
const deleteBtnRef = useRef<HTMLButtonElement>(null)
const editMoreBtnRef = useRef<HTMLButtonElement>(null)
const plusBtnRef = useRef<HTMLButtonElement>(null)
const plusMoreBtnRef = useRef<HTMLButtonElement>(null)
const deleteBtnRef = React.useRef<HTMLButtonElement>(null)
const editMoreBtnRef = React.useRef<HTMLButtonElement>(null)
const plusBtnRef = React.useRef<HTMLButtonElement>(null)
const plusMoreBtnRef = React.useRef<HTMLButtonElement>(null)
const { deleteLink } = useLinkActions()
const confirm = useConfirm()
const handleCreateMode = useCallback(() => {
const handleCreateMode = React.useCallback(() => {
setEditId(null)
requestAnimationFrame(() => {
setCreateMode(prev => !prev)
})
}, [setEditId, setCreateMode])
const exceptionRefs = useMemo(
const exceptionRefs = React.useMemo(
() => [
overlayRef,
contentRef,
@@ -89,7 +88,7 @@ export const LinkBottomBar: React.FC = () => {
[]
)
useEffect(() => {
React.useEffect(() => {
setGlobalLinkFormExceptionRefsAtom(exceptionRefs)
}, [setGlobalLinkFormExceptionRefsAtom, exceptionRefs])
@@ -124,21 +123,6 @@ export const LinkBottomBar: React.FC = () => {
}
}
const handleKeydown = useCallback(
(event: KeyboardEvent) => {
const isCreateShortcut = event.key === "c"
const target = event.target as HTMLElement
if (isCreateShortcut && !isEditableElement(target)) {
event.preventDefault()
handleCreateMode()
}
},
[handleCreateMode]
)
useKeydownListener(handleKeydown)
const shortcutText = getShortcutKeys(["c"])
return (

View File

@@ -1,10 +1,9 @@
"use client"
import * as React from "react"
import { ListFilterIcon } from "lucide-react"
import { Button } from "@/components/ui/button"
import { ContentHeader, SidebarToggleButton } from "@/components/custom/content-header"
import { useMedia } from "react-use"
import { useMedia } from "@/hooks/use-media"
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover"
import { Label } from "@/components/ui/label"
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
@@ -15,6 +14,7 @@ import { LEARNING_STATES } from "@/lib/constants"
import { useQueryState, parseAsStringLiteral } from "nuqs"
import { FancySwitch } from "@omit/react-fancy-switch"
import { cn } from "@/lib/utils"
import { LaIcon } from "@/components/custom/la-icon"
const ALL_STATES = [{ label: "All", value: "all", icon: "List", className: "text-foreground" }, ...LEARNING_STATES]
const ALL_STATES_STRING = ALL_STATES.map(ls => ls.value)
@@ -116,7 +116,7 @@ const FilterAndSort = React.memo(() => {
<Popover open={sortOpen} onOpenChange={setSortOpen}>
<PopoverTrigger asChild>
<Button size="sm" type="button" variant="secondary" className="min-w-8 gap-x-2 text-sm max-sm:p-0">
<ListFilterIcon size={16} className="text-primary/60" />
<LaIcon name="ListFilter" className="text-primary/60" />
<span className="hidden md:block">Filter: {getFilterText()}</span>
</Button>
</PopoverTrigger>

View File

@@ -1,4 +1,4 @@
import React, { useCallback, useMemo } from "react"
import * as React from "react"
import {
DndContext,
closestCenter,
@@ -19,25 +19,18 @@ import { useAccount } from "@/lib/providers/jazz-provider"
import { PersonalLinkLists } from "@/lib/schema/personal-link"
import { useAtom } from "jotai"
import { linkSortAtom } from "@/store/link"
import { useKey } from "react-use"
import { LinkItem } from "./partials/link-item"
import { parseAsBoolean, useQueryState } from "nuqs"
import { learningStateAtom } from "./header"
import { commandPaletteOpenAtom } from "@/components/custom/command-palette/command-palette"
import { useConfirm } from "@omit/react-confirm-dialog"
import { useLinkActions } from "./hooks/use-link-actions"
import { isDeleteConfirmShownAtom } from "./LinkRoute"
import { useActiveItemScroll } from "@/hooks/use-active-item-scroll"
import { useKeyboardManager } from "@/hooks/use-keyboard-manager"
import { useKeydownListener } from "@/hooks/use-keydown-listener"
import { useTouchSensor } from "@/hooks/use-touch-sensor"
import { useKeyDown } from "@/hooks/use-key-down"
import { isModKey } from "@/lib/utils"
interface LinkListProps {
activeItemIndex: number | null
setActiveItemIndex: React.Dispatch<React.SetStateAction<number | null>>
keyboardActiveIndex: number | null
setKeyboardActiveIndex: React.Dispatch<React.SetStateAction<number | null>>
}
interface LinkListProps {}
const measuring: MeasuringConfiguration = {
droppable: {
@@ -45,14 +38,11 @@ const measuring: MeasuringConfiguration = {
}
}
const LinkList: React.FC<LinkListProps> = ({
activeItemIndex,
setActiveItemIndex,
keyboardActiveIndex,
setKeyboardActiveIndex
}) => {
const LinkList: React.FC<LinkListProps> = () => {
const isTouchDevice = useTouchSensor()
const [isCommandPaletteOpen] = useAtom(commandPaletteOpenAtom)
const lastActiveIndexRef = React.useRef<number | null>(null)
const [activeItemIndex, setActiveItemIndex] = React.useState<number | null>(null)
const [keyboardActiveIndex, setKeyboardActiveIndex] = React.useState<number | null>(null)
const [, setIsDeleteConfirmShown] = useAtom(isDeleteConfirmShownAtom)
const [editId, setEditId] = useQueryState("editId")
const [createMode] = useQueryState("create", parseAsBoolean)
@@ -63,11 +53,10 @@ const LinkList: React.FC<LinkListProps> = ({
const { deleteLink } = useLinkActions()
const confirm = useConfirm()
const { me } = useAccount({ root: { personalLinks: [] } })
const { isKeyboardDisabled } = useKeyboardManager("XComponent")
const personalLinks = useMemo(() => me?.root?.personalLinks || [], [me?.root?.personalLinks])
const personalLinks = React.useMemo(() => me?.root?.personalLinks || [], [me?.root?.personalLinks])
const filteredLinks = useMemo(
const filteredLinks = React.useMemo(
() =>
personalLinks.filter(link => {
if (activeLearningState === "all") return true
@@ -77,7 +66,7 @@ const LinkList: React.FC<LinkListProps> = ({
[personalLinks, activeLearningState]
)
const sortedLinks = useMemo(
const sortedLinks = React.useMemo(
() =>
sort === "title"
? [...filteredLinks].sort((a, b) => (a?.title || "").localeCompare(b?.title || ""))
@@ -85,9 +74,21 @@ const LinkList: React.FC<LinkListProps> = ({
[filteredLinks, sort]
)
React.useEffect(() => {
if (editId !== null) {
const index = sortedLinks.findIndex(link => link?.id === editId)
if (index !== -1) {
lastActiveIndexRef.current = index
setActiveItemIndex(index)
setKeyboardActiveIndex(index)
}
}
}, [editId, setActiveItemIndex, setKeyboardActiveIndex, sortedLinks])
const sensors = useSensors(
useSensor(isTouchDevice ? TouchSensor : PointerSensor, {
activationConstraint: {
...(isTouchDevice ? { delay: 100, tolerance: 5 } : {}),
distance: 5
}
}),
@@ -96,7 +97,7 @@ const LinkList: React.FC<LinkListProps> = ({
})
)
const updateSequences = useCallback((links: PersonalLinkLists) => {
const updateSequences = React.useCallback((links: PersonalLinkLists) => {
links.forEach((link, index) => {
if (link) {
link.sequence = index
@@ -104,7 +105,7 @@ const LinkList: React.FC<LinkListProps> = ({
})
}, [])
const handleDeleteLink = useCallback(async () => {
const handleDeleteLink = React.useCallback(async () => {
if (activeItemIndex === null) return
setIsDeleteConfirmShown(true)
const activeLink = sortedLinks[activeItemIndex]
@@ -124,63 +125,31 @@ const LinkList: React.FC<LinkListProps> = ({
setIsDeleteConfirmShown(false)
}, [activeItemIndex, sortedLinks, me, confirm, deleteLink, setIsDeleteConfirmShown])
useKey(event => (event.metaKey || event.ctrlKey) && event.key === "Backspace", handleDeleteLink, { event: "keydown" })
useKeyDown(e => isModKey(e) && e.key === "Backspace", handleDeleteLink)
useKeydownListener((e: KeyboardEvent) => {
if (
isKeyboardDisabled ||
isCommandPaletteOpen ||
!me?.root?.personalLinks ||
sortedLinks.length === 0 ||
editId !== null ||
e.defaultPrevented
)
return
const next = () => Math.min((activeItemIndex ?? 0) + 1, sortedLinks.length - 1)
switch (e.key) {
case "ArrowUp":
const prev = () => Math.max((activeItemIndex ?? 0) - 1, 0)
const handleKeyDown = (ev: KeyboardEvent) => {
switch (ev.key) {
case "ArrowDown":
e.preventDefault()
setActiveItemIndex(prevIndex => {
if (prevIndex === null) return 0
const newIndex =
e.key === "ArrowUp" ? Math.max(0, prevIndex - 1) : Math.min(sortedLinks.length - 1, prevIndex + 1)
if (e.metaKey && sort === "manual") {
const linksArray = [...me.root.personalLinks]
const newLinks = arrayMove(linksArray, prevIndex, newIndex)
while (me.root.personalLinks.length > 0) {
me.root.personalLinks.pop()
}
newLinks.forEach(link => {
if (link) {
me.root.personalLinks.push(link)
}
})
updateSequences(me.root.personalLinks)
}
setKeyboardActiveIndex(newIndex)
return newIndex
})
break
case "Home":
e.preventDefault()
setActiveItemIndex(0)
break
case "End":
e.preventDefault()
setActiveItemIndex(sortedLinks.length - 1)
ev.preventDefault()
ev.stopPropagation()
setActiveItemIndex(next())
setKeyboardActiveIndex(next())
break
case "ArrowUp":
ev.preventDefault()
ev.stopPropagation()
setActiveItemIndex(prev())
setKeyboardActiveIndex(prev())
}
})
}
const handleDragStart = useCallback(
useKeyDown(() => true, handleKeyDown)
const handleDragStart = React.useCallback(
(event: DragStartEvent) => {
if (sort !== "manual") return
if (!me) return
@@ -199,7 +168,7 @@ const LinkList: React.FC<LinkListProps> = ({
[sort, me, setActiveItemIndex]
)
const handleDragCancel = useCallback(() => {
const handleDragCancel = React.useCallback(() => {
setDraggingId(null)
}, [])
@@ -249,7 +218,9 @@ const LinkList: React.FC<LinkListProps> = ({
setDraggingId(null)
}
const { setElementRef } = useActiveItemScroll<HTMLDivElement>({ activeIndex: keyboardActiveIndex })
const { setElementRef } = useActiveItemScroll<HTMLDivElement>({
activeIndex: keyboardActiveIndex
})
return (
<DndContext
@@ -261,7 +232,7 @@ const LinkList: React.FC<LinkListProps> = ({
measuring={measuring}
modifiers={[restrictToVerticalAxis]}
>
<div className="relative flex h-full grow items-stretch overflow-hidden">
<div className="relative flex h-full grow items-stretch overflow-hidden" tabIndex={-1}>
<SortableContext items={sortedLinks.map(item => item?.id || "") || []} strategy={verticalListSortingStrategy}>
<div className="relative flex h-full grow flex-col items-stretch overflow-hidden">
<div className="flex h-full w-[calc(100%+0px)] flex-col overflow-hidden pr-0">
@@ -274,9 +245,7 @@ const LinkList: React.FC<LinkListProps> = ({
isActive={activeItemIndex === index}
personalLink={linkItem}
editId={editId}
setEditId={setEditId}
disabled={sort !== "manual" || editId !== null}
setActiveItemIndex={setActiveItemIndex}
onPointerMove={() => {
if (editId !== null || draggingId !== null || createMode) {
return undefined
@@ -285,6 +254,12 @@ const LinkList: React.FC<LinkListProps> = ({
setKeyboardActiveIndex(null)
setActiveItemIndex(index)
}}
onFormClose={() => {
setEditId(null)
setActiveItemIndex(lastActiveIndexRef.current)
setKeyboardActiveIndex(lastActiveIndexRef.current)
console.log(keyboardActiveIndex)
}}
index={index}
onItemSelected={link => setEditId(link.id)}
data-keyboard-active={keyboardActiveIndex === index}

View File

@@ -1,7 +1,6 @@
"use client"
import React from "react"
import { useKey } from "react-use"
import { LinkForm } from "./partials/form/link-form"
import { motion, AnimatePresence } from "framer-motion"
import { parseAsBoolean, useQueryState } from "nuqs"
@@ -12,9 +11,6 @@ const LinkManage: React.FC<LinkManageProps> = () => {
const [createMode, setCreateMode] = useQueryState("create", parseAsBoolean)
const handleFormClose = () => setCreateMode(false)
const handleFormFail = () => {}
useKey("Escape", handleFormClose)
return (
<AnimatePresence>
@@ -25,7 +21,7 @@ const LinkManage: React.FC<LinkManageProps> = () => {
exit={{ height: 0, opacity: 0 }}
transition={{ duration: 0.1 }}
>
<LinkForm onClose={handleFormClose} onSuccess={handleFormClose} onFail={handleFormFail} />
<LinkForm onClose={handleFormClose} onSuccess={handleFormClose} />
</motion.div>
)}
</AnimatePresence>

View File

@@ -19,6 +19,7 @@ import { FormField, FormItem, FormLabel } from "@/components/ui/form"
import { LearningStateSelector } from "@/components/custom/learning-state-selector"
import { TopicSelector, topicSelectorAtom } from "@/components/custom/topic-selector"
import { JAZZ_GLOBAL_GROUP_ID } from "@/lib/constants"
import { useOnClickOutside } from "@/hooks/use-on-click-outside"
export const globalLinkFormExceptionRefsAtom = atom<React.RefObject<HTMLElement>[]>([])
@@ -78,26 +79,16 @@ export const LinkForm: React.FC<LinkFormProps> = ({
[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?.()
}
useOnClickOutside(formRef, event => {
if (
!istopicSelectorOpen &&
!islearningStateSelectorOpen &&
!allExceptionRefs.some(ref => ref.current?.contains(event.target as Node))
) {
console.log("clicking outside")
onClose?.()
}
document.addEventListener("mousedown", handleClickOutside)
return () => {
document.removeEventListener("mousedown", handleClickOutside)
}
}, [islearningStateSelectorOpen, istopicSelectorOpen, allExceptionRefs, onClose])
})
React.useEffect(() => {
if (selectedLink) {
@@ -193,7 +184,15 @@ export const LinkForm: React.FC<LinkFormProps> = ({
const canSubmit = form.formState.isValid && !form.formState.isSubmitting
return (
<div className="p-3 transition-all">
<div
tabIndex={-1}
className="p-3 transition-all"
onKeyDown={e => {
if (e.key === "Escape") {
handleCancel()
}
}}
>
<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">
@@ -213,7 +212,6 @@ export const LinkForm: React.FC<LinkFormProps> = ({
<LearningStateSelector
value={field.value}
onChange={value => {
// toggle, if already selected set undefined
form.setValue("learningState", field.value === value ? undefined : value)
}}
showSearch={false}

View File

@@ -1,4 +1,4 @@
import React, { useCallback, useMemo } from "react"
import * as React from "react"
import Image from "next/image"
import Link from "next/link"
import { useAtom } from "jotai"
@@ -19,22 +19,18 @@ interface LinkItemProps extends React.HTMLAttributes<HTMLDivElement> {
personalLink: PersonalLink
disabled?: boolean
editId: string | null
setEditId: (id: string | null) => void
isActive: boolean
setActiveItemIndex: (index: number | null) => void
index: number
onItemSelected?: (personalLink: PersonalLink) => void
onFormClose?: () => void
}
export const LinkItem = React.forwardRef<HTMLDivElement, LinkItemProps>(
(
{ personalLink, disabled, editId, setEditId, isActive, setActiveItemIndex, index, onItemSelected, ...props },
ref
) => {
({ personalLink, disabled, editId, isActive, index, onItemSelected, onFormClose, ...props }, ref) => {
const [openPopoverForId, setOpenPopoverForId] = useAtom(linkOpenPopoverForIdAtom)
const { attributes, listeners, setNodeRef, transform, transition } = useSortable({ id: personalLink.id, disabled })
const style = useMemo(
const style = React.useMemo(
() => ({
transform: CSS.Transform.toString(transform),
transition
@@ -42,15 +38,12 @@ export const LinkItem = React.forwardRef<HTMLDivElement, LinkItemProps>(
[transform, transition]
)
const handleSuccess = useCallback(() => setEditId(null), [setEditId])
const handleOnClose = useCallback(() => setEditId(null), [setEditId])
const selectedLearningState = useMemo(
const selectedLearningState = React.useMemo(
() => LEARNING_STATES.find(ls => ls.value === personalLink.learningState),
[personalLink.learningState]
)
const handleLearningStateSelect = useCallback(
const handleLearningStateSelect = React.useCallback(
(value: string) => {
const learningState = value as LearningStateValue
personalLink.learningState = personalLink.learningState === learningState ? undefined : learningState
@@ -59,10 +52,19 @@ export const LinkItem = React.forwardRef<HTMLDivElement, LinkItemProps>(
[personalLink, setOpenPopoverForId]
)
const handleKeyDown = React.useCallback(
(ev: React.KeyboardEvent<HTMLDivElement>) => {
if (ev.key === "Enter") {
ev.preventDefault()
ev.stopPropagation()
onItemSelected?.(personalLink)
}
},
[personalLink, onItemSelected]
)
if (editId === personalLink.id) {
return (
<LinkForm onClose={handleOnClose} personalLink={personalLink} onSuccess={handleSuccess} onFail={() => {}} />
)
return <LinkForm onClose={onFormClose} personalLink={personalLink} onSuccess={onFormClose} onFail={() => {}} />
}
return (
@@ -86,12 +88,7 @@ export const LinkItem = React.forwardRef<HTMLDivElement, LinkItemProps>(
data-disabled={disabled}
data-active={isActive}
className="w-full overflow-visible border-b-[0.5px] border-transparent outline-none data-[active='true']:bg-[var(--link-background-muted)] data-[keyboard-active='true']:focus-visible:shadow-[var(--link-shadow)_0px_0px_0px_1px_inset]"
onKeyDown={e => {
if (e.key === "Enter") {
e.preventDefault()
onItemSelected?.(personalLink)
}
}}
onKeyDown={handleKeyDown}
>
<div
className={cn(

View File

@@ -13,7 +13,7 @@ import { Editor } from "@tiptap/core"
import { generateUniqueSlug } from "@/lib/utils"
import { FocusClasses } from "@tiptap/extension-focus"
import { DetailPageHeader } from "./header"
import { useMedia } from "react-use"
import { useMedia } from "@/hooks/use-media"
import { TopicSelector } from "@/components/custom/topic-selector"
import { Button } from "@/components/ui/button"
import { LaIcon } from "@/components/custom/la-icon"

View File

@@ -1,4 +1,4 @@
import { useMedia } from "react-use"
import { useMedia } from "@/hooks/use-media"
export const useColumnStyles = () => {
const isTablet = useMedia("(max-width: 640px)")

View File

@@ -4,7 +4,7 @@ import { useAccount } from "@/lib/providers/jazz-provider"
import { useAtom } from "jotai"
import { commandPaletteOpenAtom } from "@/components/custom/command-palette/command-palette"
import { PageItem } from "./partials/page-item"
import { useMedia } from "react-use"
import { useMedia } from "@/hooks/use-media"
import { useColumnStyles } from "./hooks/use-column-styles"
import { PersonalPage, PersonalPageLists } from "@/lib/schema"
import { useRouter } from "next/navigation"

View File

@@ -3,7 +3,7 @@ import Link from "next/link"
import { cn } from "@/lib/utils"
import { PersonalPage } from "@/lib/schema"
import { Badge } from "@/components/ui/badge"
import { useMedia } from "react-use"
import { useMedia } from "@/hooks/use-media"
import { useColumnStyles } from "../hooks/use-column-styles"
import { format } from "date-fns"
import { Column } from "@/components/custom/column"

View File

@@ -1,9 +1,9 @@
import React, { useState, useRef, useCallback, useMemo, useEffect } from "react"
import * as React from "react"
import { Command, CommandGroup, CommandItem, CommandList } from "@/components/ui/command"
import { Command as CommandPrimitive } from "cmdk"
import { motion, AnimatePresence } from "framer-motion"
import { cn, searchSafeRegExp, shuffleArray } from "@/lib/utils"
import { useMountedState } from "react-use"
import { useIsMounted } from "@/hooks/use-is-mounted"
interface GraphNode {
name: string
@@ -18,16 +18,16 @@ interface AutocompleteProps {
}
export function Autocomplete({ topics = [], onSelect, onInputChange }: AutocompleteProps): JSX.Element {
const inputRef = useRef<HTMLInputElement>(null)
const [open, setOpen] = useState(false)
const isMounted = useMountedState()
const [inputValue, setInputValue] = useState("")
const [hasInteracted, setHasInteracted] = useState(false)
const [showDropdown, setShowDropdown] = useState(false)
const inputRef = React.useRef<HTMLInputElement>(null)
const [, setOpen] = React.useState(false)
const isMounted = useIsMounted()
const [inputValue, setInputValue] = React.useState("")
const [hasInteracted, setHasInteracted] = React.useState(false)
const [showDropdown, setShowDropdown] = React.useState(false)
const initialShuffledTopics = useMemo(() => shuffleArray(topics).slice(0, 5), [topics])
const initialShuffledTopics = React.useMemo(() => shuffleArray(topics).slice(0, 5), [topics])
const filteredTopics = useMemo(() => {
const filteredTopics = React.useMemo(() => {
if (!inputValue) {
return initialShuffledTopics
}
@@ -44,7 +44,7 @@ export function Autocomplete({ topics = [], onSelect, onInputChange }: Autocompl
.slice(0, 10)
}, [inputValue, topics, initialShuffledTopics])
const handleSelect = useCallback(
const handleSelect = React.useCallback(
(topic: GraphNode) => {
setOpen(false)
onSelect(topic.name)
@@ -52,7 +52,7 @@ export function Autocomplete({ topics = [], onSelect, onInputChange }: Autocompl
[onSelect]
)
const handleInputChange = useCallback(
const handleInputChange = React.useCallback(
(value: string) => {
setInputValue(value)
setShowDropdown(true)
@@ -62,34 +62,27 @@ export function Autocomplete({ topics = [], onSelect, onInputChange }: Autocompl
[onInputChange]
)
const handleFocus = useCallback(() => {
const handleFocus = React.useCallback(() => {
setHasInteracted(true)
}, [])
const handleClick = useCallback(() => {
const handleClick = React.useCallback(() => {
setShowDropdown(true)
setHasInteracted(true)
}, [])
const commandKey = useMemo(() => {
const commandKey = React.useMemo(() => {
return filteredTopics
.map(topic => `${topic.name}:${topic.prettyName}:${topic.connectedTopics.join(",")}`)
.join("__")
}, [filteredTopics])
useEffect(() => {
React.useEffect(() => {
if (inputRef.current && isMounted() && hasInteracted) {
inputRef.current.focus()
}
}, [commandKey, isMounted, hasInteracted])
const animationProps = {
initial: { opacity: 0, y: -10 },
animate: { opacity: 1, y: 0 },
exit: { opacity: 0, y: -10 },
transition: { duration: 0.1 }
}
return (
<Command
className={cn("relative mx-auto max-w-md overflow-visible shadow-md", {
@@ -109,7 +102,7 @@ export function Autocomplete({ topics = [], onSelect, onInputChange }: Autocompl
onClick={handleClick}
placeholder={filteredTopics[0]?.prettyName}
className={cn("placeholder:text-muted-foreground flex-1 bg-transparent px-2 outline-none")}
autoFocus // Add this line
autoFocus
/>
</div>
<div className="relative">

View File

@@ -8,6 +8,7 @@ import { useAccountOrGuest } from "@/lib/providers/jazz-provider"
import { LearningStateValue } from "@/lib/constants"
import { useClerk } from "@clerk/nextjs"
import { usePathname } from "next/navigation"
import { useMedia } from "@/hooks/use-media"
interface TopicDetailHeaderProps {
topic: Topic
@@ -16,6 +17,7 @@ interface TopicDetailHeaderProps {
export const TopicDetailHeader = React.memo(function TopicDetailHeader({ topic }: TopicDetailHeaderProps) {
const clerk = useClerk()
const pathname = usePathname()
const isMobile = useMedia("(max-width: 770px)")
const { me } = useAccountOrGuest({
root: {
topicsWantToLearn: [],
@@ -90,20 +92,19 @@ export const TopicDetailHeader = React.memo(function TopicDetailHeader({ topic }
return (
<ContentHeader className="px-6 py-5 max-lg:px-4">
<div className="flex min-w-0 shrink-0 items-center gap-1.5">
<div className="flex min-w-0 flex-1 items-center gap-1.5">
<SidebarToggleButton />
<div className="flex min-h-0 items-center">
<span className="truncate text-left font-bold lg:text-xl">{topic.prettyName}</span>
<div className="flex min-h-0 min-w-0 flex-1 items-center">
<h1 className="truncate text-left font-bold lg:text-xl">{topic.prettyName}</h1>
</div>
</div>
<div className="flex flex-auto"></div>
<LearningStateSelector
showSearch={false}
value={p?.learningState || ""}
onChange={handleAddToProfile}
defaultLabel="Add to my profile"
defaultLabel={isMobile ? "" : "Add to profile"}
defaultIcon="Circle"
/>
</ContentHeader>
)

View File

@@ -151,12 +151,7 @@ export const LinkItem = React.memo(
)}
</Button>
</PopoverTrigger>
<PopoverContent
className="w-52 rounded-lg p-0"
side="bottom"
align="start"
onCloseAutoFocus={e => e.preventDefault()}
>
<PopoverContent className="w-52 rounded-lg p-0" side="bottom" align="start">
<LearningStateSelectorContent
showSearch={false}
searchPlaceholder="Search state..."

View File

@@ -1,4 +1,4 @@
import { useMedia } from "react-use"
import { useMedia } from "@/hooks/use-media"
export const useColumnStyles = () => {
const isTablet = useMedia("(max-width: 640px)")

View File

@@ -4,7 +4,7 @@ import { useAccount } from "@/lib/providers/jazz-provider"
import { atom, useAtom } from "jotai"
import { commandPaletteOpenAtom } from "@/components/custom/command-palette/command-palette"
import { TopicItem } from "./partials/topic-item"
import { useMedia } from "react-use"
import { useMedia } from "@/hooks/use-media"
import { useRouter } from "next/navigation"
import { useActiveItemScroll } from "@/hooks/use-active-item-scroll"
import { Column } from "@/components/custom/column"

View File

@@ -139,7 +139,6 @@ export const TopicItem = React.forwardRef<HTMLDivElement, TopicItemProps>(({ top
side="bottom"
align="end"
onClick={e => e.stopPropagation()}
onCloseAutoFocus={e => e.preventDefault()}
>
<LearningStateSelectorContent
showSearch={false}