From 2e0dd3b98707126f2770bc8ee65ce6266bacf276 Mon Sep 17 00:00:00 2001 From: Nicolas Asanov <98969136+naasanov@users.noreply.github.com> Date: Mon, 4 Nov 2024 15:10:13 -0500 Subject: [PATCH] Refactored Table Components (#43) * Created mock/test table and resource page to see if implementation works * Fixed typing for TagsInput * cleaned up imports * Started moving data manipulation into Table * moved data manipulation logic into Table * added useTagsHandler custom hook to consolidate getTagColor and presetOptions state into one function * Fixed type errors for RowOpenAction * Refactored ServiceIndex * Refactored user table * Updated imports and client facing routes * added documentation for table components * Added documentation for TagsHandler * small changes for cleaner code * refactored typing for tables. More work needs to be done to ensure tables are overall working properly * added todo * updated client paths with new table props * alterned handleRowUpdate to only use setData * diverted responsibility of handleRowChange to Drawer instead of Table to remove repetition * updated documentation * added sorting util function to Table.tsx to reduce repetition * Edited sorting func to be more comaptible and edited hideData to be more concise * formatting * updated imports * updated tags for all tables * removed DataPoint dependecy from User, Service, and Resource models as it was unnecesary * Added inline documentation to table components * added documentation for DataPoint model * Update package-lock.json --- compass/app/admin/page.tsx | 4 +- compass/app/resource/page.tsx | 6 +- compass/app/service/page.tsx | 8 +- compass/components/Drawer/Drawer.tsx | 504 +++++++++-------- compass/components/Table/Index.tsx | 306 ---------- compass/components/Table/ResourceTable.tsx | 89 +++ compass/components/Table/RowOpenAction.tsx | 62 +- compass/components/Table/ServiceIndex.tsx | 312 ----------- compass/components/Table/ServiceTable.tsx | 108 ++++ .../Table/{ResourceIndex.tsx => Table.tsx} | 528 ++++++++---------- compass/components/Table/UserTable.tsx | 95 ++++ compass/components/TagsInput/Index.tsx | 6 +- compass/components/TagsInput/TagsArray.tsx | 2 +- compass/components/TagsInput/TagsHandler.tsx | 35 ++ compass/utils/models/DataPoint.ts | 9 + 15 files changed, 864 insertions(+), 1210 deletions(-) delete mode 100644 compass/components/Table/Index.tsx create mode 100644 compass/components/Table/ResourceTable.tsx delete mode 100644 compass/components/Table/ServiceIndex.tsx create mode 100644 compass/components/Table/ServiceTable.tsx rename compass/components/Table/{ResourceIndex.tsx => Table.tsx} (55%) create mode 100644 compass/components/Table/UserTable.tsx create mode 100644 compass/components/TagsInput/TagsHandler.tsx create mode 100644 compass/utils/models/DataPoint.ts diff --git a/compass/app/admin/page.tsx b/compass/app/admin/page.tsx index fede31d..abe2a8c 100644 --- a/compass/app/admin/page.tsx +++ b/compass/app/admin/page.tsx @@ -1,7 +1,7 @@ "use client"; import { PageLayout } from "@/components/PageLayout"; -import { Table } from "@/components/Table/Index"; +import UserTable from "@/components/Table/UserTable"; import User from "@/utils/models/User"; import { createClient } from "@/utils/supabase/client"; @@ -38,7 +38,7 @@ export default function Page() {
{/* icon + title */} }> - + ); diff --git a/compass/app/resource/page.tsx b/compass/app/resource/page.tsx index fc4df14..68a620f 100644 --- a/compass/app/resource/page.tsx +++ b/compass/app/resource/page.tsx @@ -1,8 +1,8 @@ "use client"; import { PageLayout } from "@/components/PageLayout"; -import { ResourceTable } from "@/components/Table/ResourceIndex"; import Resource from "@/utils/models/Resource"; +import ResourceTable from "@/components/Table/ResourceTable"; import { createClient } from "@/utils/supabase/client"; import { BookmarkIcon } from "@heroicons/react/24/solid"; @@ -27,7 +27,7 @@ export default function Page() { ); const resourcesAPI: Resource[] = await userListData.json(); - + setResources(resourcesAPI); } @@ -38,7 +38,7 @@ export default function Page() {
{/* icon + title */} }> - +
); diff --git a/compass/app/service/page.tsx b/compass/app/service/page.tsx index 8ebea4f..efe6337 100644 --- a/compass/app/service/page.tsx +++ b/compass/app/service/page.tsx @@ -1,7 +1,7 @@ "use client"; import { PageLayout } from "@/components/PageLayout"; -import { ServiceTable } from "@/components/Table/ServiceIndex"; +import ServiceTable from "@/components/Table/ServiceTable"; import Service from "@/utils/models/Service"; import { createClient } from "@/utils/supabase/client"; @@ -9,7 +9,7 @@ import { ClipboardIcon } from "@heroicons/react/24/solid"; import { useEffect, useState } from "react"; export default function Page() { - const [services, setUsers] = useState([]); + const [services, setServices] = useState([]); useEffect(() => { async function getServices() { @@ -27,7 +27,7 @@ export default function Page() { ); const servicesAPI: Service[] = await serviceListData.json(); - setUsers(servicesAPI); + setServices(servicesAPI); } getServices(); @@ -37,7 +37,7 @@ export default function Page() {
{/* icon + title */} }> - +
); diff --git a/compass/components/Drawer/Drawer.tsx b/compass/components/Drawer/Drawer.tsx index 6879f75..17b4557 100644 --- a/compass/components/Drawer/Drawer.tsx +++ b/compass/components/Drawer/Drawer.tsx @@ -1,247 +1,257 @@ -import { FunctionComponent, ReactNode } from "react"; -import React, { useState } from "react"; -import { ChevronDoubleLeftIcon } from "@heroicons/react/24/solid"; -import { - StarIcon as SolidStarIcon, - EnvelopeIcon, - UserIcon, -} from "@heroicons/react/24/solid"; -import { - ArrowsPointingOutIcon, - ArrowsPointingInIcon, - StarIcon as OutlineStarIcon, - ListBulletIcon, -} from "@heroicons/react/24/outline"; -import TagsInput from "../TagsInput/Index"; - -type DrawerProps = { - title: string; - children: ReactNode; - onClick?: (event: React.MouseEvent) => void; - type?: "button" | "submit" | "reset"; // specify possible values for type - disabled?: boolean; - editableContent?: any; - onSave?: (content: any) => void; - rowContent?: any; - onRowUpdate?: (content: any) => void; -}; - -interface EditContent { - content: string; - isEditing: boolean; -} - -const Drawer: FunctionComponent = ({ - title, - children, - onSave, - editableContent, - rowContent, - onRowUpdate, -}) => { - const [isOpen, setIsOpen] = useState(false); - const [isFull, setIsFull] = useState(false); - const [isFavorite, setIsFavorite] = useState(false); - const [tempRowContent, setTempRowContent] = useState(rowContent); - - const handleTempRowContentChange = (e) => { - const { name, value } = e.target; - console.log(name); - console.log(value); - setTempRowContent((prevContent) => ({ - ...prevContent, - [name]: value, - })); - }; - - const handleEnterPress = (e) => { - if (e.key === "Enter") { - e.preventDefault(); - // Update the rowContent with the temporaryRowContent - if (onRowUpdate) { - onRowUpdate(tempRowContent); - } - } - }; - - const toggleDrawer = () => { - setIsOpen(!isOpen); - if (isFull) { - setIsFull(!isFull); - } - }; - - const toggleDrawerFullScreen = () => setIsFull(!isFull); - - const toggleFavorite = () => setIsFavorite(!isFavorite); - - const drawerClassName = `fixed top-0 right-0 w-1/2 h-full bg-white transform ease-in-out duration-300 z-20 ${ - isOpen ? "translate-x-0 shadow-xl" : "translate-x-full" - } ${isFull ? "w-full" : "w-1/2"}`; - - const iconComponent = isFull ? ( - - ) : ( - - ); - - const favoriteIcon = isFavorite ? ( - - ) : ( - - ); - - const [presetOptions, setPresetOptions] = useState([ - "administrator", - "volunteer", - "employee", - ]); - const [rolePresetOptions, setRolePresetOptions] = useState([ - "domestic", - "community", - "economic", - ]); - const [tagColors, setTagColors] = useState(new Map()); - - const getTagColor = (tag: string) => { - if (!tagColors.has(tag)) { - const colors = [ - "bg-cyan-100", - "bg-blue-100", - "bg-green-100", - "bg-yellow-100", - "bg-purple-100", - ]; - const randomColor = - colors[Math.floor(Math.random() * colors.length)]; - setTagColors(new Map(tagColors).set(tag, randomColor)); - } - return tagColors.get(tag); - }; - - return ( -
- -
-
-
-
- - - -

- {rowContent.username} -

-
-
- - - -
-
-
-
- - -
-
- - - - - -
-
- - - - - -
-
- - - - - -
-
- - - - - -
- - Username - -
- - Role - -
- - Email - -
- - Type of Program - {/* {rowContent.program} */} - -
-
-
- - - ); -}; - -export default Drawer; +import { Dispatch, FunctionComponent, ReactNode, SetStateAction } from "react"; +import React, { useState } from "react"; +import { ChevronDoubleLeftIcon } from "@heroicons/react/24/solid"; +import { + StarIcon as SolidStarIcon, + EnvelopeIcon, + UserIcon, +} from "@heroicons/react/24/solid"; +import { + ArrowsPointingOutIcon, + ArrowsPointingInIcon, + StarIcon as OutlineStarIcon, + ListBulletIcon, +} from "@heroicons/react/24/outline"; +import TagsInput from "../TagsInput/Index"; + +type DrawerProps = { + title: string; + children: ReactNode; + onClick?: (event: React.MouseEvent) => void; + type?: "button" | "submit" | "reset"; // specify possible values for type + disabled?: boolean; + editableContent?: any; + onSave?: (content: any) => void; + rowContent?: any; + setData: Dispatch>; +}; + +interface EditContent { + content: string; + isEditing: boolean; +} + +const Drawer: FunctionComponent = ({ + title, + children, + onSave, + editableContent, + rowContent, + setData, +}) => { + const [isOpen, setIsOpen] = useState(false); + const [isFull, setIsFull] = useState(false); + const [isFavorite, setIsFavorite] = useState(false); + const [tempRowContent, setTempRowContent] = useState(rowContent); + + const onRowUpdate = (updatedRow: any) => { + setData((prevData: any) => ( + prevData.map((row: any) => ( + row.id === updatedRow.id + ? updatedRow + : row + )) + )) + }; + + const handleTempRowContentChange = (e) => { + const { name, value } = e.target; + console.log(name); + console.log(value); + setTempRowContent((prevContent) => ({ + ...prevContent, + [name]: value, + })); + }; + + const handleEnterPress = (e) => { + if (e.key === "Enter") { + e.preventDefault(); + // Update the rowContent with the temporaryRowContent + if (onRowUpdate) { + onRowUpdate(tempRowContent); + } + } + }; + + const toggleDrawer = () => { + setIsOpen(!isOpen); + if (isFull) { + setIsFull(!isFull); + } + }; + + const toggleDrawerFullScreen = () => setIsFull(!isFull); + + const toggleFavorite = () => setIsFavorite(!isFavorite); + + const drawerClassName = `fixed top-0 right-0 w-1/2 h-full bg-white transform ease-in-out duration-300 z-20 ${ + isOpen ? "translate-x-0 shadow-xl" : "translate-x-full" + } ${isFull ? "w-full" : "w-1/2"}`; + + const iconComponent = isFull ? ( + + ) : ( + + ); + + const favoriteIcon = isFavorite ? ( + + ) : ( + + ); + + const [presetOptions, setPresetOptions] = useState([ + "administrator", + "volunteer", + "employee", + ]); + const [rolePresetOptions, setRolePresetOptions] = useState([ + "domestic", + "community", + "economic", + ]); + const [tagColors, setTagColors] = useState(new Map()); + + const getTagColor = (tag: string) => { + if (!tagColors.has(tag)) { + const colors = [ + "bg-cyan-100", + "bg-blue-100", + "bg-green-100", + "bg-yellow-100", + "bg-purple-100", + ]; + const randomColor = + colors[Math.floor(Math.random() * colors.length)]; + setTagColors(new Map(tagColors).set(tag, randomColor)); + } + return tagColors.get(tag); + }; + + return ( +
+ +
+
+
+
+ + + +

+ {rowContent.username} +

+
+
+ + + +
+
+
+ + + +
+
+ + + + + +
+
+ + + + + +
+
+ + + + + +
+
+ + + + + +
+ + Username + +
+ + Role + +
+ + Email + +
+ + Type of Program + {/* {rowContent.program} */} + +
+
+
+
+
+ ); +}; + +export default Drawer; diff --git a/compass/components/Table/Index.tsx b/compass/components/Table/Index.tsx deleted file mode 100644 index 931b039..0000000 --- a/compass/components/Table/Index.tsx +++ /dev/null @@ -1,306 +0,0 @@ -// for showcasing to compass - -import users from "./users.json"; -import { - Cell, - ColumnDef, - Row, - createColumnHelper, - flexRender, - getCoreRowModel, - getFilteredRowModel, - sortingFns, - useReactTable, -} from "@tanstack/react-table"; -import { - ChangeEvent, - useState, - useEffect, - FunctionComponent, - useRef, - ChangeEventHandler, - Key, -} from "react"; -import { RowOptionMenu } from "./RowOptionMenu"; -import { RowOpenAction } from "./RowOpenAction"; -import { TableAction } from "./TableAction"; -import { - AtSymbolIcon, - Bars2Icon, - ArrowDownCircleIcon, - PlusIcon, -} from "@heroicons/react/24/solid"; -import TagsInput from "../TagsInput/Index"; -import { rankItem } from "@tanstack/match-sorter-utils"; -import User from "@/utils/models/User"; - -// For search -const fuzzyFilter = ( - row: Row, - columnId: string, - value: any, - addMeta: (meta: any) => void -) => { - // Rank the item - const itemRank = rankItem(row.getValue(columnId), value); - - // Store the ranking info - addMeta(itemRank); - - // Return if the item should be filtered in/out - return itemRank.passed; -}; - -export const Table = ({ users }: { users: User[] }) => { - const columnHelper = createColumnHelper(); - - useEffect(() => { - const sortedUsers = [...users].sort((a, b) => - a.visible === b.visible ? 0 : a.visible ? -1 : 1 - ); - setData(sortedUsers); - }, [users]); - - const deleteUser = (userId: number) => { - console.log(data); - setData((currentData) => - currentData.filter((user) => user.id !== userId) - ); - }; - - const hideUser = (userId: number) => { - console.log(`Toggling visibility for user with ID: ${userId}`); - setData((currentData) => { - const newData = currentData - .map((user) => { - if (user.id === userId) { - return { ...user, visible: !user.visible }; - } - return user; - }) - .sort((a, b) => - a.visible === b.visible ? 0 : a.visible ? -1 : 1 - ); - - console.log(newData); - return newData; - }); - }; - const [presetOptions, setPresetOptions] = useState([ - "administrator", - "volunteer", - "employee", - ]); - const [tagColors, setTagColors] = useState(new Map()); - - const getTagColor = (tag: string) => { - if (!tagColors.has(tag)) { - const colors = [ - "bg-cyan-100", - "bg-blue-100", - "bg-green-100", - "bg-yellow-100", - "bg-purple-100", - ]; - const randomColor = - colors[Math.floor(Math.random() * colors.length)]; - setTagColors(new Map(tagColors).set(tag, randomColor)); - } - return tagColors.get(tag); - }; - - const columns = [ - columnHelper.display({ - id: "options", - cell: (props) => ( - deleteUser(props.row.original.id)} - onHide={() => hideUser(props.row.original.id)} - /> - ), - }), - columnHelper.accessor("username", { - header: () => ( - <> - Username - - ), - cell: (info) => ( - - ), - }), - columnHelper.accessor("role", { - header: () => ( - <> - {" "} - Role - - ), - cell: (info) => ( - - ), - }), - columnHelper.accessor("email", { - header: () => ( - <> - Email - - ), - cell: (info) => ( - - {info.getValue()} - - ), - }), - columnHelper.accessor("program", { - header: () => ( - <> - {" "} - Program - - ), - cell: (info) => , - }), - ]; - - const [data, setData] = useState([...users]); - - const addUser = () => { - setData([...data]); - }; - - // Searching - const [query, setQuery] = useState(""); - const handleSearchChange = (e: ChangeEvent) => { - const target = e.target as HTMLInputElement; - setQuery(String(target.value)); - }; - - const handleCellChange = (e: ChangeEvent, key: Key) => { - const target = e.target as HTMLInputElement; - console.log(key); - }; - - // TODO: Filtering - - // TODO: Sorting - - // added this fn for editing rows - const handleRowUpdate = (updatedRow: User) => { - const dataIndex = data.findIndex((row) => row.id === updatedRow.id); - if (dataIndex !== -1) { - const updatedData = [...data]; - updatedData[dataIndex] = updatedRow; - setData(updatedData); - } - }; - - const table = useReactTable({ - columns, - data, - filterFns: { - fuzzy: fuzzyFilter, - }, - state: { - globalFilter: query, - }, - onGlobalFilterChange: setQuery, - globalFilterFn: fuzzyFilter, - getCoreRowModel: getCoreRowModel(), - }); - - const handleRowData = (row: any) => { - const rowData: any = {}; - row.cells.forEach((cell: any) => { - rowData[cell.column.id] = cell.value; - }); - // Use rowData object containing data from all columns for the current row - console.log(rowData); - return rowData; - }; - - return ( -
-
- -
- - - {table.getHeaderGroups().map((headerGroup) => ( - - {headerGroup.headers.map((header, i) => ( - - ))} - - ))} - - - {table.getRowModel().rows.map((row) => { - // Individual row - const isUserVisible = row.original.visible; - const rowClassNames = `text-gray-800 border-y lowercase hover:bg-gray-50 ${ - !isUserVisible ? "bg-gray-200 text-gray-500" : "" - }`; - return ( - - {row.getVisibleCells().map((cell, i) => ( - - ))} - - ); - })} - - - - - - -
- {header.isPlaceholder - ? null - : flexRender( - header.column.columnDef.header, - header.getContext() - )} -
- {flexRender( - cell.column.columnDef.cell, - cell.getContext() - )} -
- - - New - -
-
- ); -}; diff --git a/compass/components/Table/ResourceTable.tsx b/compass/components/Table/ResourceTable.tsx new file mode 100644 index 0000000..a02162a --- /dev/null +++ b/compass/components/Table/ResourceTable.tsx @@ -0,0 +1,89 @@ +import { Bars2Icon } from "@heroicons/react/24/solid"; +import { Dispatch, SetStateAction, useState } from "react"; +import useTagsHandler from "@/components/TagsInput/TagsHandler"; +import { ColumnDef, createColumnHelper } from "@tanstack/react-table"; +import { RowOpenAction } from "@/components/Table/RowOpenAction"; +import Table from "@/components/Table/Table"; +import TagsInput from "@/components/TagsInput/Index"; +import Resource from "@/utils/models/Resource"; + +type ResourceTableProps = { + data: Resource[], + setData: Dispatch> +} + +/** + * Table componenet used for displaying resources + * @param props.data Stateful list of resources to be displayed by the table + * @param props.setData State setter for the list of resources + */ +export default function ResourceTable({ data, setData }: ResourceTableProps ) { + const columnHelper = createColumnHelper(); + + // Set up tag handling + const programProps = useTagsHandler([ + "community", + "domestic", + "economic", + ]) + + // Define Tanstack columns + const columns: ColumnDef[] = [ + columnHelper.accessor("name", { + header: () => ( + <> + Name + + ), + cell: (info) => ( + + ), + }), + columnHelper.accessor("link", { + header: () => ( + <> + Link + + ), + cell: (info) => ( + + {info.getValue()} + + ), + }), + columnHelper.accessor("program", { + header: () => ( + <> + Program + + ), + cell: (info) => ( + + ), + }), + + columnHelper.accessor("summary", { + header: () => ( + <> + Summary + + ), + cell: (info) => ( + {info.getValue()} + ), + }), + ]; + + return +} diff --git a/compass/components/Table/RowOpenAction.tsx b/compass/components/Table/RowOpenAction.tsx index 9a7103c..3678630 100644 --- a/compass/components/Table/RowOpenAction.tsx +++ b/compass/components/Table/RowOpenAction.tsx @@ -1,28 +1,34 @@ -import Drawer from "@/components/Drawer/Drawer"; -import { ChangeEvent, useState } from "react"; - -export const RowOpenAction = ({ title, rowData, onRowUpdate }) => { - const [pageContent, setPageContent] = useState(""); - - const handleDrawerContentChange = (newContent) => { - setPageContent(newContent); - }; - - return ( -
- {title} - - {/* Added OnRowUpdate to drawer */} - - {pageContent} - - -
- ); -}; +import Drawer from "@/components/Drawer/Drawer"; +import DataPoint from "@/utils/models/DataPoint"; +import { Dispatch, SetStateAction, useState } from "react"; + +type RowOpenActionProps = { + title: string, + rowData: T, + setData: Dispatch> +} + +export function RowOpenAction({ title, rowData, setData }: RowOpenActionProps) { + const [pageContent, setPageContent] = useState(""); + + const handleDrawerContentChange = (newContent: string) => { + setPageContent(newContent); + }; + + return ( +
+ {title} + + + {pageContent} + + +
+ ); +}; diff --git a/compass/components/Table/ServiceIndex.tsx b/compass/components/Table/ServiceIndex.tsx deleted file mode 100644 index 6895984..0000000 --- a/compass/components/Table/ServiceIndex.tsx +++ /dev/null @@ -1,312 +0,0 @@ -// for showcasing to compass - -import users from "./users.json"; -import { - Cell, - ColumnDef, - Row, - createColumnHelper, - flexRender, - getCoreRowModel, - getFilteredRowModel, - sortingFns, - useReactTable, -} from "@tanstack/react-table"; -import { - ChangeEvent, - useState, - useEffect, - FunctionComponent, - useRef, - ChangeEventHandler, - Key, -} from "react"; -import { RowOptionMenu } from "./RowOptionMenu"; -import { RowOpenAction } from "./RowOpenAction"; -import { TableAction } from "./TableAction"; -import { - AtSymbolIcon, - Bars2Icon, - ArrowDownCircleIcon, - PlusIcon, -} from "@heroicons/react/24/solid"; -import TagsInput from "../TagsInput/Index"; -import { rankItem } from "@tanstack/match-sorter-utils"; -import Service from "@/utils/models/Service"; - -// For search -const fuzzyFilter = ( - row: Row, - columnId: string, - value: any, - addMeta: (meta: any) => void -) => { - // Rank the item - const itemRank = rankItem(row.getValue(columnId), value); - - // Store the ranking info - addMeta(itemRank); - - // Return if the item should be filtered in/out - return itemRank.passed; -}; - -// TODO: Rename everything to service -export const ServiceTable = ({ users }: { users: Service[] }) => { - const columnHelper = createColumnHelper(); - - useEffect(() => { - const sortedUsers = [...users].sort((a, b) => - a.visible === b.visible ? 0 : a.visible ? -1 : 1 - ); - setData(sortedUsers); - }, [users]); - - const deleteUser = (userId: number) => { - console.log(data); - setData((currentData) => - currentData.filter((user) => user.id !== userId) - ); - }; - - const hideUser = (userId: number) => { - console.log(`Toggling visibility for user with ID: ${userId}`); - setData((currentData) => { - const newData = currentData - .map((user) => { - if (user.id === userId) { - return { ...user, visible: !user.visible }; - } - return user; - }) - .sort((a, b) => - a.visible === b.visible ? 0 : a.visible ? -1 : 1 - ); - - console.log(newData); - return newData; - }); - }; - const [presetOptions, setPresetOptions] = useState([ - "administrator", - "volunteer", - "employee", - ]); - const [tagColors, setTagColors] = useState(new Map()); - - const getTagColor = (tag: string) => { - if (!tagColors.has(tag)) { - const colors = [ - "bg-cyan-100", - "bg-blue-100", - "bg-green-100", - "bg-yellow-100", - "bg-purple-100", - ]; - const randomColor = - colors[Math.floor(Math.random() * colors.length)]; - setTagColors(new Map(tagColors).set(tag, randomColor)); - } - return tagColors.get(tag); - }; - - const columns = [ - columnHelper.display({ - id: "options", - cell: (props) => ( - {}} - onHide={() => hideUser(props.row.original.id)} - /> - ), - }), - columnHelper.accessor("name", { - header: () => ( - <> - Name - - ), - cell: (info) => ( - - ), - }), - columnHelper.accessor("status", { - header: () => ( - <> - Status - - ), - cell: (info) => ( - {info.getValue()} - ), - }), - columnHelper.accessor("program", { - header: () => ( - <> - Program - - ), - cell: (info) => , - }), - columnHelper.accessor("requirements", { - header: () => ( - <> - Requirements - - ), - cell: (info) => ( - - ), - }), - - columnHelper.accessor("summary", { - header: () => ( - <> - Summary - - ), - cell: (info) => ( - {info.getValue()} - ), - }), - ]; - - const [data, setData] = useState([...users]); - - const addUser = () => { - setData([...data]); - }; - - // Searching - const [query, setQuery] = useState(""); - const handleSearchChange = (e: ChangeEvent) => { - const target = e.target as HTMLInputElement; - setQuery(String(target.value)); - }; - - const handleCellChange = (e: ChangeEvent, key: Key) => { - const target = e.target as HTMLInputElement; - console.log(key); - }; - - // TODO: Filtering - - // TODO: Sorting - - // added this fn for editing rows - const handleRowUpdate = (updatedRow: Service) => { - const dataIndex = data.findIndex((row) => row.id === updatedRow.id); - if (dataIndex !== -1) { - const updatedData = [...data]; - updatedData[dataIndex] = updatedRow; - setData(updatedData); - } - }; - - const table = useReactTable({ - columns, - data, - filterFns: { - fuzzy: fuzzyFilter, - }, - state: { - globalFilter: query, - }, - onGlobalFilterChange: setQuery, - globalFilterFn: fuzzyFilter, - getCoreRowModel: getCoreRowModel(), - }); - - const handleRowData = (row: any) => { - const rowData: any = {}; - row.cells.forEach((cell: any) => { - rowData[cell.column.id] = cell.value; - }); - // Use rowData object containing data from all columns for the current row - console.log(rowData); - return rowData; - }; - - return ( -
-
- -
-
- - {table.getHeaderGroups().map((headerGroup) => ( - - {headerGroup.headers.map((header, i) => ( - - ))} - - ))} - - - {table.getRowModel().rows.map((row) => { - // Individual row - const isUserVisible = row.original.visible; - const rowClassNames = `text-gray-800 border-y lowercase hover:bg-gray-50 ${ - !isUserVisible ? "bg-gray-200 text-gray-500" : "" - }`; - return ( - - {row.getVisibleCells().map((cell, i) => ( - - ))} - - ); - })} - - - - - - -
- {header.isPlaceholder - ? null - : flexRender( - header.column.columnDef.header, - header.getContext() - )} -
- {flexRender( - cell.column.columnDef.cell, - cell.getContext() - )} -
- - - New - -
- - ); -}; diff --git a/compass/components/Table/ServiceTable.tsx b/compass/components/Table/ServiceTable.tsx new file mode 100644 index 0000000..05e42b2 --- /dev/null +++ b/compass/components/Table/ServiceTable.tsx @@ -0,0 +1,108 @@ +import { Bars2Icon } from "@heroicons/react/24/solid"; +import { Dispatch, SetStateAction } from "react"; +import useTagsHandler from "@/components/TagsInput/TagsHandler"; +import { ColumnDef, createColumnHelper } from "@tanstack/react-table"; +import Table from "@/components/Table/Table"; +import { RowOpenAction } from "@/components/Table/RowOpenAction"; +import TagsInput from "@/components/TagsInput/Index"; +import Service from "@/utils/models/Service"; + +type ServiceTableProps = { + data: Service[], + setData: Dispatch> +} + +/** + * Table componenet used for displaying services + * @param props.data Stateful list of services to be displayed by the table + * @param props.setData State setter for the list of services + */ +export default function ServiceTable({ data, setData }: ServiceTableProps ) { + const columnHelper = createColumnHelper(); + + // Set up tag handling + const programProps = useTagsHandler([ + "community", + "domestic", + "economic", + ]) + + // TODO: Dynamically or statically get full list of preset requirement tag options + const requirementProps = useTagsHandler([ + 'anonymous', + 'confidential', + 'referral required', + 'safety assessment', + 'intake required', + 'income eligibility', + 'initial assessment', + ]) + + // Define Tanstack columns + const columns: ColumnDef[] = [ + columnHelper.accessor("name", { + header: () => ( + <> + Name + + ), + cell: (info) => ( + + ), + }), + columnHelper.accessor("status", { + header: () => ( + <> + Status + + ), + cell: (info) => ( + {info.getValue()} + ), + }), + columnHelper.accessor("program", { + header: () => ( + <> + Program + + ), + cell: (info) => ( + + ), + }), + columnHelper.accessor("requirements", { + header: () => ( + <> + Requirements + + ), + cell: (info) => ( + // TODO: Setup different tag handler for requirements + + ), + }), + + columnHelper.accessor("summary", { + header: () => ( + <> + Summary + + ), + cell: (info) => ( + {info.getValue()} + ), + }), + ]; + + return +}; diff --git a/compass/components/Table/ResourceIndex.tsx b/compass/components/Table/Table.tsx similarity index 55% rename from compass/components/Table/ResourceIndex.tsx rename to compass/components/Table/Table.tsx index a714836..ef0a002 100644 --- a/compass/components/Table/ResourceIndex.tsx +++ b/compass/components/Table/Table.tsx @@ -1,304 +1,224 @@ -// for showcasing to compass - -import users from "./users.json"; -import { - Cell, - ColumnDef, - Row, - createColumnHelper, - flexRender, - getCoreRowModel, - getFilteredRowModel, - sortingFns, - useReactTable, -} from "@tanstack/react-table"; -import { - ChangeEvent, - useState, - useEffect, - FunctionComponent, - useRef, - ChangeEventHandler, - Key, -} from "react"; -import { RowOptionMenu } from "./RowOptionMenu"; -import { RowOpenAction } from "./RowOpenAction"; -import { TableAction } from "./TableAction"; -import { - AtSymbolIcon, - Bars2Icon, - ArrowDownCircleIcon, - PlusIcon, -} from "@heroicons/react/24/solid"; -import TagsInput from "../TagsInput/Index"; -import { rankItem } from "@tanstack/match-sorter-utils"; -import Resource from "@/utils/models/Resource"; - -// For search -const fuzzyFilter = ( - row: Row, - columnId: string, - value: any, - addMeta: (meta: any) => void -) => { - // Rank the item - const itemRank = rankItem(row.getValue(columnId), value); - - // Store the ranking info - addMeta(itemRank); - - // Return if the item should be filtered in/out - return itemRank.passed; -}; - -// TODO: Rename everything to resources -export const ResourceTable = ({ users }: { users: Resource[] }) => { - const columnHelper = createColumnHelper(); - - useEffect(() => { - const sortedUsers = [...users].sort((a, b) => - a.visible === b.visible ? 0 : a.visible ? -1 : 1 - ); - setData(sortedUsers); - }, [users]); - - const deleteUser = (userId: number) => { - console.log(data); - setData((currentData) => - currentData.filter((user) => user.id !== userId) - ); - }; - - const hideUser = (userId: number) => { - console.log(`Toggling visibility for user with ID: ${userId}`); - setData((currentData) => { - const newData = currentData - .map((user) => { - if (user.id === userId) { - return { ...user, visible: !user.visible }; - } - return user; - }) - .sort((a, b) => - a.visible === b.visible ? 0 : a.visible ? -1 : 1 - ); - - console.log(newData); - return newData; - }); - }; - const [presetOptions, setPresetOptions] = useState([ - "administrator", - "volunteer", - "employee", - ]); - const [tagColors, setTagColors] = useState(new Map()); - - const getTagColor = (tag: string) => { - if (!tagColors.has(tag)) { - const colors = [ - "bg-cyan-100", - "bg-blue-100", - "bg-green-100", - "bg-yellow-100", - "bg-purple-100", - ]; - const randomColor = - colors[Math.floor(Math.random() * colors.length)]; - setTagColors(new Map(tagColors).set(tag, randomColor)); - } - return tagColors.get(tag); - }; - - const columns = [ - columnHelper.display({ - id: "options", - cell: (props) => ( - {}} - onHide={() => hideUser(props.row.original.id)} - /> - ), - }), - columnHelper.accessor("name", { - header: () => ( - <> - Name - - ), - cell: (info) => ( - - ), - }), - columnHelper.accessor("link", { - header: () => ( - <> - Link - - ), - cell: (info) => ( - - {info.getValue()} - - ), - }), - columnHelper.accessor("program", { - header: () => ( - <> - Program - - ), - cell: (info) => , - }), - - columnHelper.accessor("summary", { - header: () => ( - <> - Summary - - ), - cell: (info) => ( - {info.getValue()} - ), - }), - ]; - - const [data, setData] = useState([...users]); - - const addUser = () => { - setData([...data]); - }; - - // Searching - const [query, setQuery] = useState(""); - const handleSearchChange = (e: ChangeEvent) => { - const target = e.target as HTMLInputElement; - setQuery(String(target.value)); - }; - - const handleCellChange = (e: ChangeEvent, key: Key) => { - const target = e.target as HTMLInputElement; - console.log(key); - }; - - // TODO: Filtering - - // TODO: Sorting - - // added this fn for editing rows - const handleRowUpdate = (updatedRow: Resource) => { - const dataIndex = data.findIndex((row) => row.id === updatedRow.id); - if (dataIndex !== -1) { - const updatedData = [...data]; - updatedData[dataIndex] = updatedRow; - setData(updatedData); - } - }; - - const table = useReactTable({ - columns, - data, - filterFns: { - fuzzy: fuzzyFilter, - }, - state: { - globalFilter: query, - }, - onGlobalFilterChange: setQuery, - globalFilterFn: fuzzyFilter, - getCoreRowModel: getCoreRowModel(), - }); - - const handleRowData = (row: any) => { - const rowData: any = {}; - row.cells.forEach((cell: any) => { - rowData[cell.column.id] = cell.value; - }); - // Use rowData object containing data from all columns for the current row - console.log(rowData); - return rowData; - }; - - return ( -
-
- -
-
- - {table.getHeaderGroups().map((headerGroup) => ( - - {headerGroup.headers.map((header, i) => ( - - ))} - - ))} - - - {table.getRowModel().rows.map((row) => { - // Individual row - const isUserVisible = row.original.visible; - const rowClassNames = `text-gray-800 border-y lowercase hover:bg-gray-50 ${ - !isUserVisible ? "bg-gray-200 text-gray-500" : "" - }`; - return ( - - {row.getVisibleCells().map((cell, i) => ( - - ))} - - ); - })} - - - - - - -
- {header.isPlaceholder - ? null - : flexRender( - header.column.columnDef.header, - header.getContext() - )} -
- {flexRender( - cell.column.columnDef.cell, - cell.getContext() - )} -
- - - New - -
- - ); -}; +import { + Row, + ColumnDef, + useReactTable, + getCoreRowModel, + flexRender, + createColumnHelper + } from "@tanstack/react-table"; +import { + ChangeEvent, + useState, + useEffect, + Key, + Dispatch, + SetStateAction +} from "react"; +import { TableAction } from "./TableAction"; +import { PlusIcon } from "@heroicons/react/24/solid"; +import { rankItem } from "@tanstack/match-sorter-utils"; +import { RowOptionMenu } from "./RowOptionMenu"; +import DataPoint from "@/utils/models/DataPoint"; + +type TableProps = { + data: T[], + setData: Dispatch>, + columns: ColumnDef[] +}; + +/** Fuzzy search function */ +const fuzzyFilter = ( + row: Row, + columnId: string, + value: any, + addMeta: (meta: any) => void +) => { + // Rank the item + const itemRank = rankItem(row.getValue(columnId), value); + + // Store the ranking info + addMeta(itemRank); + + // Return if the item should be filtered in/out + return itemRank.passed; +}; + +/** + * General componenet that holds shared functionality for any data table component + * @param props.data Stateful list of data to be held in the table + * @param props.setData State setter for the list of data + * @param props.columns Column definitions made with Tanstack columnHelper +*/ +export default function Table({ data, setData, columns }: TableProps) { + const columnHelper = createColumnHelper(); + + /** Sorting function based on visibility */ + const visibilitySort = (a: T, b: T) => ( + a.visible === b.visible + ? 0 + : a.visible ? -1 : 1 + ) + + // Sort data on load + useEffect(() => { + setData(prevData => prevData.sort(visibilitySort)) + }, [setData]); + + // Data manipulation methods + // TODO: Connect data manipulation methods to the database (deleteData, hideData, addData) + const deleteData = (dataId: number) => { + console.log(data); + setData((currentData) => + currentData.filter((data) => data.id !== dataId) + ); + }; + + const hideData = (dataId: number) => { + console.log(`Toggling visibility for data with ID: ${dataId}`); + setData(currentData => { + const newData = currentData + .map(data => ( + data.id === dataId + ? { ...data, visible: !data.visible } + : data + )) + .sort(visibilitySort); + + console.log(newData); + return newData; + }); + }; + + const addData = () => { + setData([...data]); + }; + + // Add data manipulation options to the first column + columns.unshift( + columnHelper.display({ + id: "options", + cell: (props) => ( + deleteData(props.row.original.id)} + onHide={() => hideData(props.row.original.id)} + /> + ), + }) + ) + + // Searching + const [query, setQuery] = useState(""); + const handleSearchChange = (e: ChangeEvent) => { + const target = e.target as HTMLInputElement; + setQuery(String(target.value)); + }; + + const handleCellChange = (e: ChangeEvent, key: Key) => { + const target = e.target as HTMLInputElement; + console.log(key); + }; + + // TODO: Filtering + + // TODO: Sorting + + // Define Tanstack table + const table = useReactTable({ + columns, + data, + filterFns: { + fuzzy: fuzzyFilter, + }, + state: { + globalFilter: query, + }, + onGlobalFilterChange: setQuery, + globalFilterFn: fuzzyFilter, + getCoreRowModel: getCoreRowModel(), + }); + + const handleRowData = (row: any) => { + const rowData: any = {}; + row.cells.forEach((cell: any) => { + rowData[cell.column.id] = cell.value; + }); + // Use rowData object containing data from all columns for the current row + console.log(rowData); + return rowData; + }; + + return ( +
+
+ +
+ + + {table.getHeaderGroups().map((headerGroup) => ( + + {headerGroup.headers.map((header, i) => ( + + ))} + + ))} + + + {table.getRowModel().rows.map((row) => { + // Individual row + const isDataVisible = row.original.visible; + const rowClassNames = `text-gray-800 border-y lowercase hover:bg-gray-50 ${ + !isDataVisible ? "bg-gray-200 text-gray-500" : "" + }`; + return ( + + {row.getVisibleCells().map((cell, i) => ( + + ))} + + ); + })} + + + + + + +
+ {header.isPlaceholder + ? null + : flexRender( + header.column.columnDef.header, + header.getContext() + )} +
+ {flexRender( + cell.column.columnDef.cell, + cell.getContext() + )} +
+ + + New + +
+
+ ); +}; diff --git a/compass/components/Table/UserTable.tsx b/compass/components/Table/UserTable.tsx new file mode 100644 index 0000000..0f81d66 --- /dev/null +++ b/compass/components/Table/UserTable.tsx @@ -0,0 +1,95 @@ +import { ArrowDownCircleIcon, AtSymbolIcon, Bars2Icon } from "@heroicons/react/24/solid"; +import { Dispatch, SetStateAction } from "react"; +import useTagsHandler from "@/components/TagsInput/TagsHandler"; +import { ColumnDef, createColumnHelper } from "@tanstack/react-table"; +import Table from "@/components/Table/Table"; +import { RowOpenAction } from "@/components/Table/RowOpenAction"; +import TagsInput from "@/components/TagsInput/Index"; +import User from "@/utils/models/User"; + +type UserTableProps = { + data: User[], + setData: Dispatch> +} + +/** + * Table componenet used for displaying users + * @param props.data Stateful list of users to be displayed by the table + * @param props.setData State setter for the list of users + */ +export default function UserTable({ data, setData }: UserTableProps ) { + const columnHelper = createColumnHelper(); + + // Set up tag handling + const roleProps = useTagsHandler([ + "administrator", + "volunteer", + "employee", + ]) + + const programProps = useTagsHandler([ + "community", + "domestic", + "economic", + ]) + + // Define Tanstack columns + const columns: ColumnDef[] = [ + columnHelper.accessor("username", { + header: () => ( + <> + Username + + ), + cell: (info) => ( + + ), + }), + columnHelper.accessor("role", { + header: () => ( + <> + {" "} + Role + + ), + cell: (info) => ( + + ), + }), + columnHelper.accessor("email", { + header: () => ( + <> + Email + + ), + cell: (info) => ( + + {info.getValue()} + + ), + }), + columnHelper.accessor("program", { + header: () => ( + <> + {" "} + Program + + ), + cell: (info) => ( + + ), + }), + ]; + + return data={data} setData={setData} columns={columns}/> +} diff --git a/compass/components/TagsInput/Index.tsx b/compass/components/TagsInput/Index.tsx index 19c2a77..f4b021e 100644 --- a/compass/components/TagsInput/Index.tsx +++ b/compass/components/TagsInput/Index.tsx @@ -1,4 +1,4 @@ -import React, { useState, useRef } from "react"; +import React, { useState, useRef, Dispatch, SetStateAction } from "react"; import "tailwindcss/tailwind.css"; import { TagsArray } from "./TagsArray"; import { TagDropdown } from "./TagDropdown"; @@ -7,8 +7,8 @@ import { CreateNewTagAction } from "./CreateNewTagAction"; interface TagsInputProps { presetOptions: string[]; presetValue: string | string[]; - setPresetOptions: () => {}; - getTagColor: () => {}; + setPresetOptions: Dispatch>; + getTagColor(tag: string): string; } const TagsInput: React.FC = ({ diff --git a/compass/components/TagsInput/TagsArray.tsx b/compass/components/TagsInput/TagsArray.tsx index c014e7c..845e739 100644 --- a/compass/components/TagsInput/TagsArray.tsx +++ b/compass/components/TagsInput/TagsArray.tsx @@ -7,7 +7,7 @@ export interface Tags { } export const TagsArray = ({ tags, handleDelete, active = false }: Tags) => { - console.log(tags); + // console.log(tags); return (
diff --git a/compass/components/TagsInput/TagsHandler.tsx b/compass/components/TagsInput/TagsHandler.tsx new file mode 100644 index 0000000..e8fde75 --- /dev/null +++ b/compass/components/TagsInput/TagsHandler.tsx @@ -0,0 +1,35 @@ +import { useState } from 'react'; + +/** + * Custom hook used to handle the state of tag options and colors + * @param initialOptions Initial value for preset options + * @returns An object with three fields intended to be passed into a `TagsInput` component: + * - `presetOptions` - the current state of tag options + * - `setPresetOptions` - the state setter for presetOptions + * - `getTagColor` - function that retrieves the color for the given tag + */ +export default function useTagsHandler(initialOptions: string[]) { + const [presetOptions, setPresetOptions] = useState(initialOptions); + const [tagColors, setTagColors] = useState(new Map()); + + const getTagColor = (tag: string): string => { + if (!tagColors.has(tag)) { + const colors = [ + "bg-cyan-100", + "bg-blue-100", + "bg-green-100", + "bg-yellow-100", + "bg-purple-100", + ]; + const randomColor = + colors[Math.floor(Math.random() * colors.length)]; + setTagColors(new Map(tagColors).set(tag, randomColor)); + return randomColor; + } + // Since we populate any missing keys, .get will never return undefined, + // so we are safe to typecast to prevent a type error + return tagColors.get(tag) as string; + }; + + return { presetOptions, setPresetOptions, getTagColor } +} \ No newline at end of file diff --git a/compass/utils/models/DataPoint.ts b/compass/utils/models/DataPoint.ts new file mode 100644 index 0000000..b7dcacb --- /dev/null +++ b/compass/utils/models/DataPoint.ts @@ -0,0 +1,9 @@ +/** + * Represents metadata of the Resource, Service, and User models to be used in a table + */ +interface DataPoint { + id: number; + visible: boolean; +} + +export default DataPoint; \ No newline at end of file