today and upcoming tasks

This commit is contained in:
marshennikovaolga
2024-10-01 18:36:17 +03:00
parent 14a8536583
commit 315f7bf38e
12 changed files with 465 additions and 125 deletions

View File

@@ -1,4 +1,126 @@
"use client"
// import { useState, useEffect, useRef } from "react"
// import { motion, AnimatePresence } from "framer-motion"
// import { ListOfTasks, Task } from "@/lib/schema/tasks"
// import { Input } from "@/components/ui/input"
// import { Button } from "@/components/ui/button"
// import { useAccount } from "@/lib/providers/jazz-provider"
// import { LaIcon } from "@/components/custom/la-icon"
// import { Checkbox } from "@/components/ui/checkbox"
// import { format } from "date-fns"
// import { DatePicker } from "@/components/ui/date-picker"
// interface TaskFormProps {
// filter?: "today" | "upcoming"
// }
// export const TaskForm: React.FC<TaskFormProps> = ({ filter }) => {
// const [title, setTitle] = useState("")
// const [dueDate, setDueDate] = useState<Date | undefined>(filter === "today" ? new Date() : undefined)
// const [inputVisible, setInputVisible] = useState(false)
// const { me } = useAccount({ root: {} })
// const inputRef = useRef<HTMLInputElement>(null)
// const handleSubmit = (e: React.FormEvent) => {
// e.preventDefault()
// if (title.trim() && (filter !== "upcoming" || dueDate)) {
// if (me?.root?.tasks === undefined) {
// if (!me) return
// me.root.tasks = ListOfTasks.create([], { owner: me })
// }
// const newTask = Task.create(
// {
// title,
// description: "",
// status: "todo",
// createdAt: new Date(),
// updatedAt: new Date(),
// dueDate: dueDate || null
// },
// { owner: me._owner }
// )
// me.root.tasks?.push(newTask)
// resetForm()
// }
// }
// const resetForm = () => {
// setTitle("")
// setDueDate(filter === "today" ? new Date() : undefined)
// setInputVisible(false)
// }
// const handleKeyDown = (e: React.KeyboardEvent) => {
// if (e.key === "Escape") {
// resetForm()
// } else if (e.key === "Backspace" && title.trim() === "") {
// resetForm()
// }
// }
// useEffect(() => {
// if (inputVisible && inputRef.current) {
// inputRef.current.focus()
// }
// }, [inputVisible])
// const formattedDate = dueDate ? format(dueDate, "EEE, MMMM do, yyyy") : "Select a date"
// return (
// <div className="flex items-center space-x-2">
// <AnimatePresence mode="wait">
// {!inputVisible ? (
// <motion.div
// key="add-button"
// initial={{ opacity: 0, width: 0 }}
// animate={{ opacity: 1, width: "auto" }}
// exit={{ opacity: 0, width: 0 }}
// transition={{ duration: 0.3 }}
// >
// <Button
// className="flex flex-row items-center gap-1"
// onClick={() => setInputVisible(true)}
// variant="outline"
// >
// <LaIcon name="Plus" />
// Add task
// </Button>
// </motion.div>
// ) : (
// <motion.form
// key="input-form"
// initial={{ width: 0, opacity: 0 }}
// animate={{ width: "100%", opacity: 1 }}
// exit={{ width: 0, opacity: 0 }}
// transition={{ duration: 0.3 }}
// onSubmit={handleSubmit}
// className="bg-result flex w-full items-center justify-between rounded-lg p-2 px-3"
// >
// <div className="flex flex-row items-center gap-3">
// <Checkbox checked={false} onCheckedChange={() => {}} />
// <Input
// autoFocus
// ref={inputRef}
// value={title}
// className="flex-grow border-none bg-transparent p-0 focus-visible:ring-0"
// onChange={e => setTitle(e.target.value)}
// onKeyDown={handleKeyDown}
// placeholder="Task title"
// />
// </div>
// <div className="flex items-center space-x-2">
// {filter === "upcoming" && (
// <DatePicker date={dueDate} onDateChange={(date: Date | undefined) => setDueDate(date)} />
// )}
// <span className="text-muted-foreground text-xs">{formattedDate}</span>
// </div>
// </motion.form>
// )}
// </AnimatePresence>
// </div>
// )
// }
import { useState, useEffect, useRef } from "react"
import { motion, AnimatePresence } from "framer-motion"
import { ListOfTasks, Task } from "@/lib/schema/tasks"
@@ -8,18 +130,22 @@ import { useAccount } from "@/lib/providers/jazz-provider"
import { LaIcon } from "@/components/custom/la-icon"
import { Checkbox } from "@/components/ui/checkbox"
import { format } from "date-fns"
import { DatePicker } from "@/components/ui/date-picker"
interface TaskFormProps {}
interface TaskFormProps {
filter?: "today" | "upcoming" | undefined
}
export const TaskForm: React.FC<TaskFormProps> = ({}) => {
export const TaskForm: React.FC<TaskFormProps> = ({ filter }) => {
const [title, setTitle] = useState("")
const [dueDate, setDueDate] = useState<Date | undefined>(filter === "today" ? new Date() : undefined)
const [inputVisible, setInputVisible] = useState(false)
const { me } = useAccount({ root: {} })
const inputRef = useRef<HTMLInputElement>(null)
const handleSubmit = (e: React.FormEvent) => {
e.preventDefault()
if (title.trim()) {
if (title.trim() && (filter === "today" || (filter === "upcoming" && dueDate))) {
if (me?.root?.tasks === undefined) {
if (!me) return
me.root.tasks = ListOfTasks.create([], { owner: me })
@@ -31,7 +157,8 @@ export const TaskForm: React.FC<TaskFormProps> = ({}) => {
description: "",
status: "todo",
createdAt: new Date(),
updatedAt: new Date()
updatedAt: new Date(),
dueDate: dueDate || (filter === "today" ? new Date() : null)
},
{ owner: me._owner }
)
@@ -42,6 +169,7 @@ export const TaskForm: React.FC<TaskFormProps> = ({}) => {
const resetForm = () => {
setTitle("")
setDueDate(filter === "today" ? new Date() : undefined)
setInputVisible(false)
}
@@ -59,55 +187,60 @@ export const TaskForm: React.FC<TaskFormProps> = ({}) => {
}
}, [inputVisible])
const formattedDate = format(new Date(), "EEE, MMMM do, yyyy")
const formattedDate = dueDate ? format(dueDate, "EEE, MMMM do, yyyy") : "Select a date"
return (
<div className="flex items-center space-x-2">
<AnimatePresence mode="wait">
{!inputVisible ? (
<motion.div
key="add-button"
initial={{ opacity: 0, width: 0 }}
animate={{ opacity: 1, width: "auto" }}
exit={{ opacity: 0, width: 0 }}
transition={{ duration: 0.3 }}
>
<Button
className="flex flex-row items-center gap-1"
onClick={() => setInputVisible(true)}
variant="outline"
{filter ? (
!inputVisible ? (
<motion.div
key="add-button"
initial={{ opacity: 0, width: 0 }}
animate={{ opacity: 1, width: "auto" }}
exit={{ opacity: 0, width: 0 }}
transition={{ duration: 0.3 }}
>
<LaIcon name="Plus" />
Add task
</Button>
</motion.div>
) : (
<motion.form
key="input-form"
initial={{ width: 0, opacity: 0 }}
animate={{ width: "100%", opacity: 1 }}
exit={{ width: 0, opacity: 0 }}
transition={{ duration: 0.3 }}
onSubmit={handleSubmit}
className="bg-result flex w-full items-center justify-between rounded-lg p-2 px-3"
>
<div className="flex flex-row items-center gap-3">
<Checkbox checked={false} onCheckedChange={() => {}} />
<Input
autoFocus
ref={inputRef}
value={title}
className="flex-grow border-none bg-transparent p-0 focus-visible:ring-0"
onChange={e => setTitle(e.target.value)}
onKeyDown={handleKeyDown}
// placeholder="Task title"
/>
</div>
<div className="flex items-center space-x-2">
<span className="text-muted-foreground text-xs">{formattedDate}</span>
</div>
</motion.form>
)}
<Button
className="flex flex-row items-center gap-1"
onClick={() => setInputVisible(true)}
variant="outline"
>
<LaIcon name="Plus" />
Add task
</Button>
</motion.div>
) : (
<motion.form
key="input-form"
initial={{ width: 0, opacity: 0 }}
animate={{ width: "100%", opacity: 1 }}
exit={{ width: 0, opacity: 0 }}
transition={{ duration: 0.3 }}
onSubmit={handleSubmit}
className="bg-result flex w-full items-center justify-between rounded-lg p-2 px-3"
>
<div className="flex flex-row items-center gap-3">
<Checkbox checked={false} onCheckedChange={() => {}} />
<Input
autoFocus
ref={inputRef}
value={title}
className="flex-grow border-none bg-transparent p-0 focus-visible:ring-0"
onChange={e => setTitle(e.target.value)}
onKeyDown={handleKeyDown}
placeholder="Task title"
/>
</div>
<div className="flex items-center space-x-2">
{filter === "upcoming" && (
<DatePicker date={dueDate} onDateChange={(date: Date | undefined) => setDueDate(date)} />
)}
<span className="text-muted-foreground text-xs">{formattedDate}</span>
</div>
</motion.form>
)
) : null}
</AnimatePresence>
</div>
)

View File

@@ -1,24 +1,78 @@
import { Task } from "@/lib/schema/tasks"
import { Checkbox } from "@/components/ui/checkbox"
import { format } from "date-fns"
import { useState, useRef, useEffect } from "react"
import { Input } from "@/components/ui/input"
interface TaskItemProps {
task: Task
onUpdateTask: (taskId: string, updates: Partial<Task>) => void
onDeleteTask: (taskId: string) => void
}
export const TaskItem: React.FC<TaskItemProps> = ({ task, onUpdateTask }) => {
export const TaskItem: React.FC<TaskItemProps> = ({ task, onUpdateTask, onDeleteTask }) => {
const [isEditing, setIsEditing] = useState(false)
const [editedTitle, setEditedTitle] = useState(task.title)
const inputRef = useRef<HTMLInputElement>(null)
useEffect(() => {
if (isEditing && inputRef.current) {
inputRef.current.focus()
}
}, [isEditing])
const statusChange = (checked: boolean) => {
onUpdateTask(task.id, { status: checked ? "done" : "todo" })
if (checked) {
onDeleteTask(task.id)
} else {
onUpdateTask(task.id, { status: "todo" })
}
}
const clickTitle = () => {
setIsEditing(true)
}
const titleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
setEditedTitle(e.target.value)
}
const titleBlur = () => {
setIsEditing(false)
if (editedTitle.trim() !== task.title) {
onUpdateTask(task.id, { title: editedTitle.trim() })
}
}
const handleKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {
if (e.key === "Enter") {
titleBlur()
}
}
const formattedDate = format(new Date(task.createdAt), "EEE, MMMM do, yyyy")
return (
<li className="bg-result transitiion-opacity flex items-center justify-between rounded-lg p-2 px-3 hover:opacity-60">
<div className="flex flex-row items-center gap-3">
<div className="flex flex-grow flex-row items-center gap-3">
<Checkbox checked={task.status === "done"} onCheckedChange={statusChange} />
<p className={task.status === "done" ? "text-foreground line-through" : ""}>{task.title}</p>
{isEditing ? (
<input
ref={inputRef}
value={editedTitle}
onChange={titleChange}
onBlur={titleBlur}
onKeyDown={handleKeyDown}
className="flex-grow border-none bg-transparent p-0 shadow-none outline-none focus:outline-none focus-visible:ring-0 focus-visible:ring-offset-0"
/>
) : (
<p
className={task.status === "done" ? "text-foreground flex-grow line-through" : "flex-grow"}
onClick={clickTitle}
>
{task.title}
</p>
)}
</div>
<span className="text-muted-foreground text-xs">{formattedDate}</span>
</li>

View File

@@ -1,20 +1,21 @@
import React from "react"
import { ListOfTasks, Task } from "@/lib/schema/tasks"
import { Task } from "@/lib/schema/tasks"
import { TaskItem } from "./TaskItem"
interface TaskListProps {
tasks?: ListOfTasks
tasks: Task[]
onUpdateTask: (taskId: string, updates: Partial<Task>) => void
onDeleteTask: (taskId: string) => void
}
export const TaskList: React.FC<TaskListProps> = ({ tasks, onUpdateTask }) => {
export const TaskList: React.FC<TaskListProps> = ({ tasks, onUpdateTask, onDeleteTask }) => {
return (
<ul className="flex flex-col gap-y-2">
{tasks?.map(
task =>
task?.id && (
<li key={task.id}>
<TaskItem task={task} onUpdateTask={onUpdateTask} />
<TaskItem task={task} onUpdateTask={onUpdateTask} onDeleteTask={onDeleteTask} />
</li>
)
)}

View File

@@ -5,11 +5,28 @@ import { Task } from "@/lib/schema/tasks"
import { TaskList } from "./TaskList"
import { TaskForm } from "./TaskForm"
import { LaIcon } from "@/components/custom/la-icon"
import { isToday, isFuture } from "date-fns"
import { useTaskActions } from "./new-task-actions"
import { ID } from "jazz-tools"
export const TaskRoute: React.FC = () => {
interface TaskRouteProps {
filter?: "today" | "upcoming"
}
export const TaskRoute: React.FC<TaskRouteProps> = ({ filter }) => {
const { me } = useAccount({ root: { tasks: [] } })
const tasks = me?.root.tasks
console.log(tasks, "tasks here")
const { deleteTask } = useTaskActions()
const filteredTasks = tasks?.filter(task => {
if (!task) return false
if (filter === "today") {
return task.status !== "done" && task.dueDate && isToday(task.dueDate)
} else if (filter === "upcoming") {
return task.status !== "done" && task.dueDate && isFuture(task.dueDate)
}
return true
})
const updateTask = (taskId: string, updates: Partial<Task>) => {
if (me?.root?.tasks) {
@@ -20,14 +37,26 @@ export const TaskRoute: React.FC = () => {
}
}
const onDeleteTask = (taskId: string) => {
if (me) {
deleteTask(me, taskId as ID<Task>)
}
}
return (
<div className="flex flex-col space-y-4 p-4">
<div className="flex flex-row items-center gap-1">
<LaIcon name="ListTodo" className="size-6" />
<h1 className="text-xl font-bold">Current Tasks</h1>
<h1 className="text-xl font-bold">
{filter === "today" ? "Today's Tasks" : filter === "upcoming" ? "Upcoming Tasks" : "All Tasks"}
</h1>
</div>
<TaskForm />
<TaskList tasks={tasks} onUpdateTask={updateTask} />
<TaskForm filter={filter} />
<TaskList
tasks={filteredTasks?.filter((task): task is Task => task !== null) || []}
onUpdateTask={updateTask}
onDeleteTask={onDeleteTask}
/>
</div>
)
}

View File

@@ -0,0 +1,15 @@
import { TaskRoute } from "@/components/routes/task/TaskRoute"
import { currentUser } from "@clerk/nextjs/server"
import { notFound } from "next/navigation"
import { get } from "ronin"
export default async function TodayTasksPage() {
const user = await currentUser()
const flag = await get.featureFlag.with.name("TASK")
if (!user?.emailAddresses.some(email => flag?.emails.includes(email.emailAddress))) {
notFound()
}
return <TaskRoute filter="today" />
}

View File

@@ -0,0 +1,15 @@
import { TaskRoute } from "@/components/routes/task/TaskRoute"
import { currentUser } from "@clerk/nextjs/server"
import { notFound } from "next/navigation"
import { get } from "ronin"
export default async function UpcomingTasksPage() {
const user = await currentUser()
const flag = await get.featureFlag.with.name("TASK")
if (!user?.emailAddresses.some(email => flag?.emails.includes(email.emailAddress))) {
notFound()
}
return <TaskRoute filter="upcoming" />
}

View File

@@ -0,0 +1,62 @@
import { useCallback } from "react"
import { toast } from "sonner"
import { LaAccount } from "@/lib/schema"
import { Task, ListOfTasks } from "@/lib/schema/tasks"
import { ID } from "jazz-tools"
export const useTaskActions = () => {
const newTask = useCallback((me: LaAccount): Task | null => {
if (!me.root) {
console.error("User root is not initialized")
return null
}
if (!me.root.tasks) {
me.root.tasks = ListOfTasks.create([], { owner: me })
}
const newTask = Task.create(
{
title: "",
description: "",
status: "todo",
createdAt: new Date(),
updatedAt: new Date()
},
{ owner: me._owner }
)
me.root.tasks.push(newTask)
return newTask
}, [])
const deleteTask = useCallback((me: LaAccount, taskId: ID<Task>): void => {
if (!me.root?.tasks) return
const index = me.root.tasks.findIndex(item => item?.id === taskId)
if (index === -1) {
toast.error("Task not found")
return
}
const task = me.root.tasks[index]
if (!task) {
toast.error("Task data is invalid")
return
}
try {
me.root.tasks.splice(index, 1)
toast.success("Task deleted", {
position: "bottom-right",
description: `${task.title} has been deleted.`
})
} catch (error) {
console.error("Failed to delete task", error)
toast.error("Failed to delete task")
}
}, [])
return { newTask, deleteTask }
}