diff --git a/app/components/Header.tsx b/app/components/Header.tsx new file mode 100644 index 0000000..d4cea35 --- /dev/null +++ b/app/components/Header.tsx @@ -0,0 +1,10 @@ +import React from 'react' + +export default function Header() { + return ( +
+

Suspense

+

Record your suspension settings

+
+ ) +} diff --git a/app/components/Profile.tsx b/app/components/Profile.tsx new file mode 100644 index 0000000..08d9cee --- /dev/null +++ b/app/components/Profile.tsx @@ -0,0 +1,21 @@ +import React from 'react' +import { ProfileModel } from '../types' +import Link from 'next/link' +export default function Profile(params: ProfileModel) { + return ( + + + {params.name} + + {params.forkPsi} + {params.forkSag}% + {params.shockPsi} + {params.shockSag}% + + Edit + Delete + + + ) +} + diff --git a/app/components/form/Label.tsx b/app/components/form/Label.tsx new file mode 100644 index 0000000..045b3b9 --- /dev/null +++ b/app/components/form/Label.tsx @@ -0,0 +1,16 @@ +import React from 'react' + +interface LabelProps extends React.HTMLAttributes { + fieldName: string; + labelText: string; +} + +export default function Label({fieldName, labelText}: LabelProps) { + const classNames = 'block text-gray-500 font-bold md:text-right mb-1 md:mb-0 pr-4'; + + return ( + + ) +} diff --git a/app/components/form/LabelAndTextField.tsx b/app/components/form/LabelAndTextField.tsx new file mode 100644 index 0000000..eb6394f --- /dev/null +++ b/app/components/form/LabelAndTextField.tsx @@ -0,0 +1,23 @@ +import React from 'react' +import Label from './Label' +import TextField from './TextField' + +interface LabelAndTextFieldProps extends React.HTMLAttributes { + fieldName: string; + fieldValue: string; + fieldSetter: React.Dispatch>; + labelText: string; +} + +export default function LabelAndTextField({fieldName, fieldValue, fieldSetter, labelText}: LabelAndTextFieldProps) { + return ( +
+
+
+
+ +
+
+ ) +} diff --git a/app/components/form/Submit.tsx b/app/components/form/Submit.tsx new file mode 100644 index 0000000..1aa2a40 --- /dev/null +++ b/app/components/form/Submit.tsx @@ -0,0 +1,9 @@ +import React from 'react' + +export default function Submit() { + return ( +
+ +
+ ) +} diff --git a/app/components/form/TextField.tsx b/app/components/form/TextField.tsx new file mode 100644 index 0000000..30b2e4e --- /dev/null +++ b/app/components/form/TextField.tsx @@ -0,0 +1,20 @@ +import React from 'react' +import { SyntheticEvent } from 'react' + +interface TextFieldProps extends React.HTMLAttributes { + fieldName: string; + fieldValue: string; + fieldSetter: React.Dispatch>; +} + +export default function TextField({fieldName, fieldValue, fieldSetter}: TextFieldProps) { + const classNames = 'bg-gray-200 appearance-none border-2 rounded w-full py-2 px-4 text-gray-700 leading-tight focus:outline-none focus:bg-white focus:border-blue-500'; + + const onChange = (e: React.ChangeEvent): void => { + fieldSetter(e.currentTarget.value); + } + + return ( + + ) +} diff --git a/app/components/suspense-table.tsx b/app/components/suspense-table.tsx deleted file mode 100644 index 1275b0f..0000000 --- a/app/components/suspense-table.tsx +++ /dev/null @@ -1,167 +0,0 @@ -'use client' - -import "ka-table/style.css"; - -import React, { useState } from 'react'; - -import { ITableProps, kaReducer, Table } from 'ka-table'; -import { ICellEditorProps, ICellTextProps, IHeadCellProps } from 'ka-table/props'; -import { deleteRow, hideNewRow, saveNewRow, showNewRow } from 'ka-table/actionCreators'; -import { DataType, EditingMode, SortingMode } from 'ka-table/enums'; -import { DispatchFunc } from 'ka-table/types'; - -import { useLocalStorage } from './../lib/useLocalStorage'; - -const LOCAL_STORAGE_KEY = 'SuspenseTableData'; - -const blankRow = { - profile: 'Bike name or profile', - forkLsc: '0', - forkHsc: '0', - forkLsr: '0', - forkHsr: '0', - shockLsc: '0', - shockHsc: '0', - shockLsr: '0', - shockHsr: '0', - id: 0, -}; - -const columns = [ - { key: 'profile', title: 'Profile', dataType: DataType.String, width: '30%' }, - { key: 'forkLsc', title: 'Fork LSC', dataType: DataType.String }, - { key: 'forkHsc', title: 'Fork HSC', dataType: DataType.String }, - { key: 'forkLsr', title: 'Fork LSR', dataType: DataType.String }, - { key: 'forkHsr', title: 'Fork HSR', dataType: DataType.String }, - { key: 'shockLsc', title: 'Shock LSC', dataType: DataType.String }, - { key: 'shockHsc', title: 'Shock HSC', dataType: DataType.String }, - { key: 'shockLsr', title: 'Shock LSR', dataType: DataType.String }, - { key: 'shockHsr', title: 'Shock HSR', dataType: DataType.String }, - { key: 'actions', style: {width: 80}}, -]; - -const SuspenseTable: React.FC = () => { - const [tableData, setTableData] = useLocalStorage(LOCAL_STORAGE_KEY, [blankRow]); - - let maxValue = Math.max(...tableData.map(i => i.id)); - const generateNewId = () => { - maxValue++; - return maxValue; - }; - const AddButton: React.FC = ({ - dispatch, - }) => { - return ( -
- Add New Row dispatch(showNewRow())} - /> -
- ); - }; - - const DeleteRow: React.FC = ({ - dispatch, rowKeyValue, - }) => { - return ( - dispatch(deleteRow(rowKeyValue))} - alt='' - /> - ); - }; - - const RemoveButton: React.FC = ({ - dispatch - }) => { - return ( - Cancel dispatch(hideNewRow())} - /> - ); - }; - - const SaveButton: React.FC = ({ - dispatch - }) => { - const saveNewData = () => { - const rowKeyValue = generateNewId(); - dispatch(saveNewRow(rowKeyValue, { - validate: true - })); - }; - return ( - Save - ); - }; - - const tablePropsInit: ITableProps = { - columns: columns, - data: tableData, - editingMode: EditingMode.Cell, - rowKeyField: 'id', - sortingMode: SortingMode.Single, - }; - - const [tableProps, changeTableProps] = useState(tablePropsInit); - - const dispatch: DispatchFunc = (action) => { - changeTableProps((prevState: ITableProps) => { - setTableData(kaReducer(prevState, action).data); - return kaReducer(prevState, action) - }); - }; - - return ( - { - if (props.column.key === 'actions'){ - return ( -
- - -
- ); - } - } - }, - cellText: { - content: (props) => { - if (props.column.key === 'actions') { - return ; - } - } - }, - headCell: { - content: (props) => { - if (props.column.key === 'actions'){ - return ; - } - } - } - }} - /> - ); -}; - -export default SuspenseTable; - diff --git a/app/components/title.tsx b/app/components/title.tsx deleted file mode 100644 index a9ad3d3..0000000 --- a/app/components/title.tsx +++ /dev/null @@ -1,16 +0,0 @@ -export default function Title({ - text, description -} : { - text: string, - description: string -}) { - return ( -
-

{text}

-
- {description} -
-
- ) -}; - diff --git a/app/globals.css b/app/globals.css index fd81e88..b5c61c9 100644 --- a/app/globals.css +++ b/app/globals.css @@ -1,27 +1,3 @@ @tailwind base; @tailwind components; @tailwind utilities; - -:root { - --foreground-rgb: 0, 0, 0; - --background-start-rgb: 214, 219, 220; - --background-end-rgb: 255, 255, 255; -} - -@media (prefers-color-scheme: dark) { - :root { - --foreground-rgb: 255, 255, 255; - --background-start-rgb: 0, 0, 0; - --background-end-rgb: 0, 0, 0; - } -} - -body { - color: rgb(var(--foreground-rgb)); - background: linear-gradient( - to bottom, - transparent, - rgb(var(--background-end-rgb)) - ) - rgb(var(--background-start-rgb)); -} diff --git a/app/layout.tsx b/app/layout.tsx index f37a270..7759301 100644 --- a/app/layout.tsx +++ b/app/layout.tsx @@ -1,6 +1,7 @@ -import './globals.css' +import '@/app/globals.css' import type { Metadata } from 'next' import { Inter } from 'next/font/google' +import Header from '@/app/components/Header' const inter = Inter({ subsets: ['latin'] }) @@ -16,7 +17,12 @@ export default function RootLayout({ }) { return ( - {children} + +
+
+ {children} +
+ ) } diff --git a/app/lib/index.ts b/app/lib/index.ts new file mode 100644 index 0000000..50b047c --- /dev/null +++ b/app/lib/index.ts @@ -0,0 +1 @@ +export const fetcher = (url: string) => fetch(url).then((res) => res.json()); diff --git a/app/lib/useLocalStorage.tsx b/app/lib/useLocalStorage.tsx deleted file mode 100644 index 74638df..0000000 --- a/app/lib/useLocalStorage.tsx +++ /dev/null @@ -1,42 +0,0 @@ -// credits to https://usehooks.com/useLocalStorage/ - -import { dequal as deepEqual } from 'dequal' -import { useCallback, useState } from 'react' - -export function useLocalStorage(key: string, initialValue: T): [T, (value: T) => void] { - // State to store our value - // Pass initial state function to useState so logic is only executed once - const [storedValue, setStoredValue] = useState(() => { - try { - // Get from local storage by key - const item = window.localStorage.getItem(key) - // Parse stored json or if none return initialValue - return item ? JSON.parse(item) : initialValue - } catch (error) { - // If error also return initialValue - console.log(error) - return initialValue - } - }) - - // Return a wrapped version of useState's setter function that ... - // ... persists the new value to localStorage. - const setValue = useCallback( - (value: T) => { - try { - if (!deepEqual(storedValue, value)) { - // Save state - setStoredValue(value) - // Save to local storage - window.localStorage.setItem(key, JSON.stringify(value)) - } - } catch (error) { - // A more advanced implementation would handle the error case - console.log(error) - } - }, - [key, storedValue] - ) - - return [storedValue, setValue] -} diff --git a/app/page.tsx b/app/page.tsx index 61ff6b1..e6dfef2 100644 --- a/app/page.tsx +++ b/app/page.tsx @@ -1,17 +1,7 @@ -import Image from 'next/image' -import Title from './components/title' -import dynamic from 'next/dynamic' -const SuspenseTable = dynamic(() => import('./components/suspense-table'), { ssr: false }); - +import Profiles from '@/app/profiles/page' export default function Home() { return ( -
-
- - </div> - <div className="z-10 max-w-10xl w-full items-center font-mono text-sm lg:flex"> - <SuspenseTable /> - </div> - </main> + <Profiles /> ) } + diff --git a/app/profiles/create/page.tsx b/app/profiles/create/page.tsx new file mode 100644 index 0000000..7893c8f --- /dev/null +++ b/app/profiles/create/page.tsx @@ -0,0 +1,78 @@ +"use client" +import React, {useState } from 'react' +import { useRouter } from 'next/navigation' +import LabelAndTextField from '@/app/components/form/LabelAndTextField' +import Submit from '@/app/components/form/Submit' + +export default function ProfileCreate() { + const router = useRouter() + const [name, setName] = useState<string>(''); + const [forkPsi, setForkPsi] = useState<string>(''); + const [forkSag, setForkSag] = useState<string>(''); + const [forkHsc, setForkHsc] = useState<string>(''); + const [forkLsc, setForkLsc] = useState<string>(''); + const [forkHsr, setForkHsr] = useState<string>(''); + const [forkLsr, setForkLsr] = useState<string>(''); + const [shockPsi, setShockPsi] = useState<string>(''); + const [shockSag, setShockSag] = useState<string>(''); + const [shockHsc, setShockHsc] = useState<string>(''); + const [shockLsc, setShockLsc] = useState<string>(''); + const [shockHsr, setShockHsr] = useState<string>(''); + const [shockLsr, setShockLsr] = useState<string>(''); + + const addProfile = async (e: any) => { + e.preventDefault() + if (name != "") { + const formData = { + name: name, + forkPsi: forkPsi, + forkSag: forkSag, + forkHsc: forkHsc, + forkLsc: forkLsc, + forkHsr: forkHsr, + forkLsr: forkLsr, + shockPsi: shockPsi, + shockSag: shockSag, + shockHsc: shockHsc, + shockLsc: shockLsc, + shockHsr: shockHsr, + shockLsr: shockLsr + } + const add = await fetch('/api/profiles', { + method: 'POST', + headers: { + 'Content-Type': 'application/json' + }, + body: JSON.stringify(formData) + }); + const content = await add.json(); + if(content.success > 0) { + router.push(`/profiles/read/${content.profile.id}`); + } + } + }; + + return ( + <form className="w-full bg-white shadow-md rounded px-8 pt-6 pb-8 mb-4" onSubmit={addProfile}> + + <div className="m-auto w-full text-center mb-10"> + <h1 className="text-xl font-bold">Add a new suspension profile</h1> + </div> + <LabelAndTextField fieldName={'name'} fieldValue={name} fieldSetter={setName} labelText={'Name'} /> + <LabelAndTextField fieldName={'forkPsi'} fieldValue={forkPsi} fieldSetter={setForkPsi} labelText={'Fork PSI'} /> + <LabelAndTextField fieldName={'forkSag'} fieldValue={forkSag} fieldSetter={setForkSag} labelText={'Fork sag'} /> + <LabelAndTextField fieldName={'forkHsc'} fieldValue={forkHsc} fieldSetter={setForkHsc} labelText={'Fork HSC'} /> + <LabelAndTextField fieldName={'forkLsc'} fieldValue={forkLsc} fieldSetter={setForkLsc} labelText={'Fork LSC'} /> + <LabelAndTextField fieldName={'forkHsr'} fieldValue={forkHsr} fieldSetter={setForkHsr} labelText={'Fork HSR'} /> + <LabelAndTextField fieldName={'forkLsr'} fieldValue={forkLsr} fieldSetter={setForkLsr} labelText={'Fork LSR'} /> + <LabelAndTextField fieldName={'shockPsi'} fieldValue={shockPsi} fieldSetter={setShockPsi} labelText={'Shock PSI'} /> + <LabelAndTextField fieldName={'shockSag'} fieldValue={shockSag} fieldSetter={setShockSag} labelText={'Shock sag'} /> + <LabelAndTextField fieldName={'shockHsc'} fieldValue={shockHsc} fieldSetter={setShockHsc} labelText={'Shock HSC'} /> + <LabelAndTextField fieldName={'shockLsc'} fieldValue={shockLsc} fieldSetter={setShockLsc} labelText={'Shock LSC'} /> + <LabelAndTextField fieldName={'shockHsr'} fieldValue={shockHsr} fieldSetter={setShockHsr} labelText={'Shock HSR'} /> + <LabelAndTextField fieldName={'shockLsr'} fieldValue={shockLsr} fieldSetter={setShockLsr} labelText={'Shock LSR'} /> + + <Submit /> + </form> + ) +} diff --git a/app/profiles/delete/[id]/page.tsx b/app/profiles/delete/[id]/page.tsx new file mode 100644 index 0000000..6021f4e --- /dev/null +++ b/app/profiles/delete/[id]/page.tsx @@ -0,0 +1,49 @@ +"use client" +import React, {useState,useEffect } from 'react' +import { useRouter } from 'next/navigation' +import { fetcher } from '@/app/lib' +import useSWR from 'swr' + +export default function ProfileDelete({params} :{params:{id:number}}) { + const router = useRouter() + const [name, setName] = useState<string>(''); + const {data : profile,isLoading, error} = useSWR(`/api/profiles/${params.id}`,fetcher) + + useEffect(()=>{ + if (profile) { + setName(profile.name); + } + },[profile, isLoading]) + + const deleteProfile = async (e: any) => { + e.preventDefault() + const res = await fetch(`/api/profiles/${params.id}`, { + method: 'DELETE', + headers: { + 'Content-Type': 'application/json' + }, + }); + const content = await res.json(); + if(content.success > 0) + { + router.push('/profiles'); + } + }; + + if (isLoading) return <div><span>Loading...</span></div> + if (!profile) return null; + + const labelClassNames = 'block text-gray-500 font-bold md:text-right mb-1 md:mb-0 pr-4'; + const inputClassNames = 'bg-gray-200 appearance-none border-2 rounded w-full py-2 px-4 text-gray-700 leading-tight focus:outline-none focus:bg-white focus:border-blue-500'; + + return ( + <form className="w-full bg-white shadow-md rounded px-8 pt-6 pb-8 mb-4" onSubmit={deleteProfile}> + <h1 className="text-xl font-bold">Are you sure you want to delete suspension profile {profile.name}?</h1> + + <div className='w-full py-2'> + <button className="w-20 p-2 text-white border-gray-200 border-[1px] rounded-sm bg-red-400">Delete</button> + </div> + </form> + ) +} + diff --git a/app/profiles/edit/[id]/page.tsx b/app/profiles/edit/[id]/page.tsx new file mode 100644 index 0000000..549573c --- /dev/null +++ b/app/profiles/edit/[id]/page.tsx @@ -0,0 +1,102 @@ +"use client" +import React, {useState,useEffect } from 'react' +import { useRouter } from 'next/navigation' +import { fetcher } from '@/app/lib' +import useSWR from 'swr' + +import LabelAndTextField from '@/app/components/form/LabelAndTextField'; +import Submit from '@/app/components/form/Submit'; + +export default function ProfileEdit({params} :{params:{id:number}}) { + const router = useRouter(); + const [name, setName] = useState<string>(''); + const [forkPsi, setForkPsi] = useState<string>(''); + const [forkSag, setForkSag] = useState<string>(''); + const [forkHsc, setForkHsc] = useState<string>(''); + const [forkLsc, setForkLsc] = useState<string>(''); + const [forkHsr, setForkHsr] = useState<string>(''); + const [forkLsr, setForkLsr] = useState<string>(''); + const [shockPsi, setShockPsi] = useState<string>(''); + const [shockSag, setShockSag] = useState<string>(''); + const [shockHsc, setShockHsc] = useState<string>(''); + const [shockLsc, setShockLsc] = useState<string>(''); + const [shockHsr, setShockHsr] = useState<string>(''); + const [shockLsr, setShockLsr] = useState<string>(''); + + const {data: profile, isLoading, error} = useSWR(`/api/profiles/${params.id}`,fetcher); + + useEffect(()=>{ + if (profile){ + setName(profile.name) + setForkPsi(profile.forkPsi) + setForkSag(profile.forkSag) + setForkHsc(profile.forkHsc) + setForkLsc(profile.forkLsc) + setForkHsr(profile.forkHsr) + setForkLsr(profile.forkLsr) + setShockPsi(profile.shockPsi) + setShockSag(profile.shockSag) + setShockHsc(profile.shockHsc) + setShockLsc(profile.shockLsc) + setShockHsr(profile.shockHsr) + setShockLsr(profile.shockLsr) + } + },[profile, isLoading]) + + const updateProfile = async (e: any) => { + e.preventDefault() + if (name != "" && forkPsi != "" && shockPsi != "") { + const formData = { + name: name, + forkPsi: forkPsi, + forkSag: forkSag, + forkHsc: forkHsc, + forkLsc: forkLsc, + forkHsr: forkHsr, + forkLsr: forkLsr, + shockPsi: shockPsi, + shockSag: shockSag, + shockHsc: shockHsc, + shockLsc: shockLsc, + shockHsr: shockHsr, + shockLsr: shockLsr + } + const res = await fetch(`/api/profiles/${params.id}`, { + method: 'PUT', + headers: { + 'Content-Type': 'application/json' + }, + body: JSON.stringify(formData) + }); + const content = await res.json(); + if(content.success > 0) + { + router.push('/profiles'); + } + + } + }; + if(isLoading) return <div><span>Loading...</span></div> + if (!profile) return null; + + return ( + <form className="w-full bg-white shadow-md rounded px-8 pt-6 pb-8 mb-4" onSubmit={updateProfile}> + <h1 className="text-xl font-bold">Edit profile</h1> + <LabelAndTextField fieldName={'name'} fieldValue={name} fieldSetter={setName} labelText={'Name'} /> + <LabelAndTextField fieldName={'forkPsi'} fieldValue={forkPsi} fieldSetter={setForkPsi} labelText={'Fork PSI'} /> + <LabelAndTextField fieldName={'forkSag'} fieldValue={forkSag} fieldSetter={setForkSag} labelText={'Fork sag'} /> + <LabelAndTextField fieldName={'forkHsc'} fieldValue={forkHsc} fieldSetter={setForkHsc} labelText={'Fork HSC'} /> + <LabelAndTextField fieldName={'forkLsc'} fieldValue={forkLsc} fieldSetter={setForkLsc} labelText={'Fork LSC'} /> + <LabelAndTextField fieldName={'forkHsr'} fieldValue={forkHsr} fieldSetter={setForkHsr} labelText={'Fork HSR'} /> + <LabelAndTextField fieldName={'forkLsr'} fieldValue={forkLsr} fieldSetter={setForkLsr} labelText={'Fork LSR'} /> + <LabelAndTextField fieldName={'shockPsi'} fieldValue={shockPsi} fieldSetter={setShockPsi} labelText={'Shock PSI'} /> + <LabelAndTextField fieldName={'shockSag'} fieldValue={shockSag} fieldSetter={setShockSag} labelText={'Shock sag'} /> + <LabelAndTextField fieldName={'shockHsc'} fieldValue={shockHsc} fieldSetter={setShockHsc} labelText={'Shock HSC'} /> + <LabelAndTextField fieldName={'shockLsc'} fieldValue={shockLsc} fieldSetter={setShockLsc} labelText={'Shock LSC'} /> + <LabelAndTextField fieldName={'shockHsr'} fieldValue={shockHsr} fieldSetter={setShockHsr} labelText={'Shock HSR'} /> + <LabelAndTextField fieldName={'shockLsr'} fieldValue={shockLsr} fieldSetter={setShockLsr} labelText={'Shock LSR'} /> + + <Submit /> + </form> + ) +} diff --git a/app/profiles/page.tsx b/app/profiles/page.tsx new file mode 100644 index 0000000..8cdb752 --- /dev/null +++ b/app/profiles/page.tsx @@ -0,0 +1,49 @@ +"use client"; +import React,{useEffect, useState} from "react"; +import useSWR from "swr"; +import { fetcher } from "@/app/lib"; +import Profile from "@/app/components/Profile"; +import { ProfileModel } from "@/app/types"; +import Link from "next/link"; + +export default function Profiles() { + const [profiles, setProfiles] = useState<ProfileModel[]>([]); + const { data, error, isLoading } = useSWR<any>(`/api/profiles`, fetcher); + + useEffect(() => { + if (data) { + setProfiles(data.profiles); + } + }, [data,isLoading]); + + if (error) return <div>Failed to load</div>; + if (isLoading) return <div>Loading...</div>; + if (!data) return null; + + return ( + <div className="w-full max-w-7xl m-auto"> + <table className="w-full border-collapse border border-slate-400"> + <thead> + <tr className="text-center"> + <th className="border border-slate-300">Name</th> + <th className="border border-slate-300">Fork PSI</th> + <th className="border border-slate-300">Fork Sag</th> + <th className="border border-slate-300">Shock PSI</th> + <th className="border border-slate-300">Shock Sag</th> + <th className="border border-slate-300">Action</th> + </tr> + </thead> + <tbody> + { + profiles && profiles.map((item : ProfileModel)=><Profile key={item.id} {...item} />) + } + <tr> + <td colSpan={6}> + <Link href={`/profiles/create`} className="bg-green-500 p-2 inline-block text-white">Create</Link> + </td> + </tr> + </tbody> + </table> + </div> + ); +} diff --git a/app/profiles/read/[id]/page.tsx b/app/profiles/read/[id]/page.tsx new file mode 100644 index 0000000..ccd82db --- /dev/null +++ b/app/profiles/read/[id]/page.tsx @@ -0,0 +1,70 @@ +'use client' +import { fetcher } from '@/app/lib' +import useSWR from 'swr' + +export default function Detail({params}: {params:{id :number}}) { + const {data: data, isLoading, error} = useSWR(`/api/profiles/${params.id}`,fetcher) + if(isLoading) return <div><span>Loading...</span></div> + if (!data || !data.profile) return null; + const profile = data.profile; + return ( + <div className='w-full'> + <h2 className='text-center font-bold text-3xl py-3'>{profile.name}</h2> + + <div className='w-full max-w-4xl m-auto border-[1px] p-3 border-gray-500 rounded-md'> + <dl className='divide-y divide-gray-100'> + <div className="px-4 py-6 sm:grid sm:grid-cols-3 sm:gap-4 sm:px-0"> + <dt className='font-bold'>Fork PSI</dt> + <dd className=' ml-3'>{profile.forkPsi}</dd> + </div> + <div className="px-4 py-6 sm:grid sm:grid-cols-3 sm:gap-4 sm:px-0"> + <dt className='font-bold '>Fork sag</dt> + <dd className=' ml-3'>{profile.forkSag}%</dd> + </div> + <div className="px-4 py-6 sm:grid sm:grid-cols-3 sm:gap-4 sm:px-0"> + <dt className='font-bold '>Fork HSC</dt> + <dd className=' ml-3'>{profile.forkHsc}</dd> + </div> + <div className="px-4 py-6 sm:grid sm:grid-cols-3 sm:gap-4 sm:px-0"> + <dt className='font-bold '>Fork LSC</dt> + <dd className=' ml-3'>{profile.forkLsc}</dd> + </div> + <div className="px-4 py-6 sm:grid sm:grid-cols-3 sm:gap-4 sm:px-0"> + <dt className='font-bold '>Fork HSR</dt> + <dd className=' ml-3'>{profile.forkHsr}</dd> + </div> + <div className="px-4 py-6 sm:grid sm:grid-cols-3 sm:gap-4 sm:px-0"> + <dt className='font-bold '>Fork LSR</dt> + <dd className=' ml-3'>{profile.forkLsr}</dd> + </div> + <div className="px-4 py-6 sm:grid sm:grid-cols-3 sm:gap-4 sm:px-0"> + <dt className='font-bold '>Shock PSI</dt> + <dd className=' ml-3'>{profile.shockPsi}</dd> + </div> + <div className="px-4 py-6 sm:grid sm:grid-cols-3 sm:gap-4 sm:px-0"> + <dt className='font-bold '>Shock sag</dt> + <dd className=' ml-3'>{profile.shockSag}</dd> + </div> + <div className="px-4 py-6 sm:grid sm:grid-cols-3 sm:gap-4 sm:px-0"> + <dt className='font-bold '>Shock HSC</dt> + <dd className=' ml-3'>{profile.shockHsc}</dd> + </div> + <div className="px-4 py-6 sm:grid sm:grid-cols-3 sm:gap-4 sm:px-0"> + <dt className='font-bold '>Shock LSC</dt> + <dd className=' ml-3'>{profile.shockLsc}</dd> + </div> + <div className="px-4 py-6 sm:grid sm:grid-cols-3 sm:gap-4 sm:px-0"> + <dt className='font-bold '>Shock HSR</dt> + <dd className=' ml-3'>{profile.shockHsr}</dd> + </div> + <div className="px-4 py-6 sm:grid sm:grid-cols-3 sm:gap-4 sm:px-0"> + <dt className='font-bold '>Shock LSR</dt> + <dd className=' ml-3'>{profile.shockLsr}</dd> + </div> + </dl> + </div> + </div> + ) +} + + diff --git a/app/types/index.ts b/app/types/index.ts new file mode 100644 index 0000000..5a61277 --- /dev/null +++ b/app/types/index.ts @@ -0,0 +1,18 @@ +export interface ProfileModel { + id: number, + name: string, + forkPsi: number, + forkHsc: number, + forkLsc: number, + forkHsr: number, + forkLsr: number, + forkSag: number, + shockPsi: number, + shockHsc: number, + shockLsc: number, + shockHsr: number, + shockLsr: number, + shockSag: number, + dateCreated: string, + dateUpdated: string +} diff --git a/data/profiles.json b/data/profiles.json new file mode 100644 index 0000000..fe51488 --- /dev/null +++ b/data/profiles.json @@ -0,0 +1 @@ +[] diff --git a/app/favicon.ico b/favicon.ico similarity index 100% rename from app/favicon.ico rename to favicon.ico diff --git a/index.tsx b/index.tsx new file mode 100644 index 0000000..f6f79f5 --- /dev/null +++ b/index.tsx @@ -0,0 +1,10 @@ +import Link from "next/link"; +export default function Home() { + return ( + <div> + <h1>Next.js 10 - CRUD Example with React Hook Form</h1> + <p>An example app showing how to list, add, edit and delete user records with Next.js 10 and the React Hook Form library.</p> + <p><Link href="/profiles">>> Manage Profiles</Link></p> + </div> + ); +} diff --git a/jsconfig.json b/jsconfig.json new file mode 100644 index 0000000..d056459 --- /dev/null +++ b/jsconfig.json @@ -0,0 +1,6 @@ +{ + "compilerOptions": { + // make all imports without a dot '.' prefix relative to the base url + "baseUrl": "." + } +} diff --git a/package-lock.json b/package-lock.json index 48e69e8..5dccfce 100644 --- a/package-lock.json +++ b/package-lock.json @@ -14,13 +14,15 @@ "autoprefixer": "10.4.15", "eslint": "8.49.0", "eslint-config-next": "13.4.19", - "ka-table": "8.3.2", "next": "13.4.19", "postcss": "8.4.29", "react": "18.2.0", "react-dom": "18.2.0", + "react-query": "3.39.3", + "swr": "2.2.4", "tailwindcss": "3.3.3", - "typescript": "5.2.2" + "typescript": "5.2.2", + "yup": "1.3.2" } }, "node_modules/@aashutoshrathi/word-wrap": { @@ -800,6 +802,14 @@ "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz", "integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==" }, + "node_modules/big-integer": { + "version": "1.6.51", + "resolved": "https://registry.npmjs.org/big-integer/-/big-integer-1.6.51.tgz", + "integrity": "sha512-GPEid2Y9QU1Exl1rpO9B2IPJGHPSupF5GnVIP0blYvNOMer2bTvSWs1jGOUg04hTmu67nmLsQ9TBo1puaotBHg==", + "engines": { + "node": ">=0.6" + } + }, "node_modules/binary-extensions": { "version": "2.2.0", "resolved": "https://registry.npmjs.org/binary-extensions/-/binary-extensions-2.2.0.tgz", @@ -828,6 +838,21 @@ "node": ">=8" } }, + "node_modules/broadcast-channel": { + "version": "3.7.0", + "resolved": "https://registry.npmjs.org/broadcast-channel/-/broadcast-channel-3.7.0.tgz", + "integrity": "sha512-cIAKJXAxGJceNZGTZSBzMxzyOn72cVgPnKx4dc6LRjQgbaJUQqhy5rzL3zbMxkMWsGKkv2hSFkPRMEXfoMZ2Mg==", + "dependencies": { + "@babel/runtime": "^7.7.2", + "detect-node": "^2.1.0", + "js-sha3": "0.8.0", + "microseconds": "0.2.0", + "nano-time": "1.0.0", + "oblivious-set": "1.0.0", + "rimraf": "3.0.2", + "unload": "2.2.0" + } + }, "node_modules/browserslist": { "version": "4.21.10", "resolved": "https://registry.npmjs.org/browserslist/-/browserslist-4.21.10.tgz", @@ -1095,6 +1120,11 @@ "node": ">=6" } }, + "node_modules/detect-node": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/detect-node/-/detect-node-2.1.0.tgz", + "integrity": "sha512-T0NIuQpnTvFDATNuHN5roPwSBG83rFsuO+MXXH9/3N1eFbn4wcPjttvjMLEPWJ0RGUYgQE7cGgS3tNxbqCGM7g==" + }, "node_modules/didyoumean": { "version": "1.2.2", "resolved": "https://registry.npmjs.org/didyoumean/-/didyoumean-1.2.2.tgz", @@ -2448,6 +2478,11 @@ "jiti": "bin/jiti.js" } }, + "node_modules/js-sha3": { + "version": "0.8.0", + "resolved": "https://registry.npmjs.org/js-sha3/-/js-sha3-0.8.0.tgz", + "integrity": "sha512-gF1cRrHhIzNfToc802P800N8PpXS+evLLXfsVpowqmAFR9uwbi89WvXg2QspOmXL8QL86J4T1EpFu+yUkwJY3Q==" + }, "node_modules/js-tokens": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz", @@ -2504,14 +2539,6 @@ "node": ">=4.0" } }, - "node_modules/ka-table": { - "version": "8.3.2", - "resolved": "https://registry.npmjs.org/ka-table/-/ka-table-8.3.2.tgz", - "integrity": "sha512-b08of5T1Kpna4Ahnx7BKPmlY5pOuAb516ESqDmNi4oIdnQH5okid5Ah5VswjCCSDXlFYaYrfuN07mm9LdpVcCg==", - "peerDependencies": { - "react": "^16.8.3 || ^17.0.0-0 || ^18.0.0-0" - } - }, "node_modules/keyv": { "version": "4.5.3", "resolved": "https://registry.npmjs.org/keyv/-/keyv-4.5.3.tgz", @@ -2599,6 +2626,15 @@ "node": ">=10" } }, + "node_modules/match-sorter": { + "version": "6.3.1", + "resolved": "https://registry.npmjs.org/match-sorter/-/match-sorter-6.3.1.tgz", + "integrity": "sha512-mxybbo3pPNuA+ZuCUhm5bwNkXrJTbsk5VWbR5wiwz/GC6LIiegBGn2w3O08UG/jdbYLinw51fSQ5xNU1U3MgBw==", + "dependencies": { + "@babel/runtime": "^7.12.5", + "remove-accents": "0.4.2" + } + }, "node_modules/merge2": { "version": "1.4.1", "resolved": "https://registry.npmjs.org/merge2/-/merge2-1.4.1.tgz", @@ -2619,6 +2655,11 @@ "node": ">=8.6" } }, + "node_modules/microseconds": { + "version": "0.2.0", + "resolved": "https://registry.npmjs.org/microseconds/-/microseconds-0.2.0.tgz", + "integrity": "sha512-n7DHHMjR1avBbSpsTBj6fmMGh2AGrifVV4e+WYc3Q9lO+xnSZ3NyhcBND3vzzatt05LFhoKFRxrIyklmLlUtyA==" + }, "node_modules/minimatch": { "version": "3.1.2", "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.2.tgz", @@ -2653,6 +2694,14 @@ "thenify-all": "^1.0.0" } }, + "node_modules/nano-time": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/nano-time/-/nano-time-1.0.0.tgz", + "integrity": "sha512-flnngywOoQ0lLQOTRNexn2gGSNuM9bKj9RZAWSzhQ+UJYaAFG9bac4DW9VHjUAzrOaIcajHybCTHe/bkvozQqA==", + "dependencies": { + "big-integer": "^1.6.16" + } + }, "node_modules/nanoid": { "version": "3.3.6", "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.6.tgz", @@ -2882,6 +2931,11 @@ "url": "https://github.com/sponsors/ljharb" } }, + "node_modules/oblivious-set": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/oblivious-set/-/oblivious-set-1.0.0.tgz", + "integrity": "sha512-z+pI07qxo4c2CulUHCDf9lcqDlMSo72N/4rLUpRXf6fu+q8vjt8y0xS+Tlf8NTJDdTXHbdeO1n3MlbctwEoXZw==" + }, "node_modules/once": { "version": "1.4.0", "resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz", @@ -3156,6 +3210,11 @@ "react-is": "^16.13.1" } }, + "node_modules/property-expr": { + "version": "2.0.6", + "resolved": "https://registry.npmjs.org/property-expr/-/property-expr-2.0.6.tgz", + "integrity": "sha512-SVtmxhRE/CGkn3eZY1T6pC8Nln6Fr/lu1mKSgRud0eC73whjGfoAogbn78LkD8aFL0zz3bAFerKSnOl7NlErBA==" + }, "node_modules/punycode": { "version": "2.3.0", "resolved": "https://registry.npmjs.org/punycode/-/punycode-2.3.0.tgz", @@ -3211,6 +3270,31 @@ "resolved": "https://registry.npmjs.org/react-is/-/react-is-16.13.1.tgz", "integrity": "sha512-24e6ynE2H+OKt4kqsOvNd8kBpV65zoxbA4BVsEOB3ARVWQki/DHzaUoC5KuON/BiccDaCCTZBuOcfZs70kR8bQ==" }, + "node_modules/react-query": { + "version": "3.39.3", + "resolved": "https://registry.npmjs.org/react-query/-/react-query-3.39.3.tgz", + "integrity": "sha512-nLfLz7GiohKTJDuT4us4X3h/8unOh+00MLb2yJoGTPjxKs2bc1iDhkNx2bd5MKklXnOD3NrVZ+J2UXujA5In4g==", + "dependencies": { + "@babel/runtime": "^7.5.5", + "broadcast-channel": "^3.4.1", + "match-sorter": "^6.0.2" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/tannerlinsley" + }, + "peerDependencies": { + "react": "^16.8.0 || ^17.0.0 || ^18.0.0" + }, + "peerDependenciesMeta": { + "react-dom": { + "optional": true + }, + "react-native": { + "optional": true + } + } + }, "node_modules/read-cache": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/read-cache/-/read-cache-1.0.0.tgz", @@ -3270,6 +3354,11 @@ "url": "https://github.com/sponsors/ljharb" } }, + "node_modules/remove-accents": { + "version": "0.4.2", + "resolved": "https://registry.npmjs.org/remove-accents/-/remove-accents-0.4.2.tgz", + "integrity": "sha512-7pXIJqJOq5tFgG1A2Zxti3Ht8jJF337m4sowbuHsW30ZnkQFnDzy9qBNhgzX8ZLW4+UBcXiiR7SwR6pokHsxiA==" + }, "node_modules/resolve": { "version": "1.22.4", "resolved": "https://registry.npmjs.org/resolve/-/resolve-1.22.4.tgz", @@ -3643,6 +3732,18 @@ "url": "https://github.com/sponsors/ljharb" } }, + "node_modules/swr": { + "version": "2.2.4", + "resolved": "https://registry.npmjs.org/swr/-/swr-2.2.4.tgz", + "integrity": "sha512-njiZ/4RiIhoOlAaLYDqwz5qH/KZXVilRLvomrx83HjzCWTfa+InyfAjv05PSFxnmLzZkNO9ZfvgoqzAaEI4sGQ==", + "dependencies": { + "client-only": "^0.0.1", + "use-sync-external-store": "^1.2.0" + }, + "peerDependencies": { + "react": "^16.11.0 || ^17.0.0 || ^18.0.0" + } + }, "node_modules/tailwindcss": { "version": "3.3.3", "resolved": "https://registry.npmjs.org/tailwindcss/-/tailwindcss-3.3.3.tgz", @@ -3711,6 +3812,11 @@ "node": ">=0.8" } }, + "node_modules/tiny-case": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/tiny-case/-/tiny-case-1.0.3.tgz", + "integrity": "sha512-Eet/eeMhkO6TX8mnUteS9zgPbUMQa4I6Kkp5ORiBD5476/m+PIRiumP5tmh5ioJpH7k51Kehawy2UDfsnxxY8Q==" + }, "node_modules/to-regex-range": { "version": "5.0.1", "resolved": "https://registry.npmjs.org/to-regex-range/-/to-regex-range-5.0.1.tgz", @@ -3722,6 +3828,11 @@ "node": ">=8.0" } }, + "node_modules/toposort": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/toposort/-/toposort-2.0.2.tgz", + "integrity": "sha512-0a5EOkAUp8D4moMi2W8ZF8jcga7BgZd91O/yabJCFY8az+XSzeGyTKs0Aoo897iV1Nj6guFq8orWDS96z91oGg==" + }, "node_modules/ts-api-utils": { "version": "1.0.3", "resolved": "https://registry.npmjs.org/ts-api-utils/-/ts-api-utils-1.0.3.tgz", @@ -3863,6 +3974,15 @@ "url": "https://github.com/sponsors/ljharb" } }, + "node_modules/unload": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/unload/-/unload-2.2.0.tgz", + "integrity": "sha512-B60uB5TNBLtN6/LsgAf3udH9saB5p7gqJwcFfbOEZ8BcBHnGwCf6G/TGiEqkRAxX7zAFIUtzdrXQSdL3Q/wqNA==", + "dependencies": { + "@babel/runtime": "^7.6.2", + "detect-node": "^2.0.4" + } + }, "node_modules/update-browserslist-db": { "version": "1.0.11", "resolved": "https://registry.npmjs.org/update-browserslist-db/-/update-browserslist-db-1.0.11.tgz", @@ -3900,6 +4020,14 @@ "punycode": "^2.1.0" } }, + "node_modules/use-sync-external-store": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/use-sync-external-store/-/use-sync-external-store-1.2.0.tgz", + "integrity": "sha512-eEgnFxGQ1Ife9bzYs6VLi8/4X6CObHMw9Qr9tPY43iKwsPw8xE8+EFsf/2cFZ5S3esXgpWgtSCtLNS41F+sKPA==", + "peerDependencies": { + "react": "^16.8.0 || ^17.0.0 || ^18.0.0" + } + }, "node_modules/util-deprecate": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz", @@ -4032,6 +4160,28 @@ "url": "https://github.com/sponsors/sindresorhus" } }, + "node_modules/yup": { + "version": "1.3.2", + "resolved": "https://registry.npmjs.org/yup/-/yup-1.3.2.tgz", + "integrity": "sha512-6KCM971iQtJ+/KUaHdrhVr2LDkfhBtFPRnsG1P8F4q3uUVQ2RfEM9xekpha9aA4GXWJevjM10eDcPQ1FfWlmaQ==", + "dependencies": { + "property-expr": "^2.0.5", + "tiny-case": "^1.0.3", + "toposort": "^2.0.2", + "type-fest": "^2.19.0" + } + }, + "node_modules/yup/node_modules/type-fest": { + "version": "2.19.0", + "resolved": "https://registry.npmjs.org/type-fest/-/type-fest-2.19.0.tgz", + "integrity": "sha512-RAH822pAdBgcNMAfWnCBU3CFZcfZ/i1eZjwFU/dsLKumyuuP3niueg2UAukXYF0E2AAoc82ZSSf9J0WQBinzHA==", + "engines": { + "node": ">=12.20" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, "node_modules/zod": { "version": "3.21.4", "resolved": "https://registry.npmjs.org/zod/-/zod-3.21.4.tgz", diff --git a/package.json b/package.json index 3a6668e..927191a 100644 --- a/package.json +++ b/package.json @@ -15,12 +15,14 @@ "autoprefixer": "10.4.15", "eslint": "8.49.0", "eslint-config-next": "13.4.19", - "ka-table": "8.3.2", "next": "13.4.19", "postcss": "8.4.29", "react": "18.2.0", "react-dom": "18.2.0", + "react-query": "3.39.3", + "swr": "2.2.4", "tailwindcss": "3.3.3", - "typescript": "5.2.2" + "typescript": "5.2.2", + "yup": "1.3.2" } } diff --git a/pages/api/profiles.ts b/pages/api/profiles.ts new file mode 100644 index 0000000..47bd927 --- /dev/null +++ b/pages/api/profiles.ts @@ -0,0 +1,31 @@ +import profilesRepo from './profilesRepo'; + +import type { NextApiRequest, NextApiResponse } from 'next' + +export default function handler( + req: NextApiRequest, + res: NextApiResponse +) { + const getProfiles = () => { + const profiles = profilesRepo.getAll(); + return res.status(200).json({profiles: profiles, success: 1}); + } + + const createProfile = () => { + try { + const profile = profilesRepo.create(req.body); + return res.status(200).json({success:1, id: profile.id}); + } catch (error: any) { + return res.status(400).json({ message: error }); + } + } + + switch (req.method) { + case 'GET': + return getProfiles(); + case 'POST': + return createProfile(); + default: + return res.status(405).end(`Method ${req.method} Not Allowed`) + } +} diff --git a/pages/api/profiles/[id].ts b/pages/api/profiles/[id].ts new file mode 100644 index 0000000..65ea7e4 --- /dev/null +++ b/pages/api/profiles/[id].ts @@ -0,0 +1,39 @@ +import profilesRepo from './../profilesRepo'; + +import type { NextApiRequest, NextApiResponse } from 'next' + +export default function handler( + req: NextApiRequest, + res: NextApiResponse +) { + + const getProfileById = () => { + const profile = profilesRepo.getById(Number(req.query.id)); + return res.status(200).json(profile); + } + + const updateProfile = () => { + try { + profilesRepo.update(Number(req.query.id), req.body); + return res.status(200).json({success:1}); + } catch (error) { + return res.status(400).json({ message: error }); + } + } + + const deleteProfile = () => { + profilesRepo.delete(Number(req.query.id)); + return res.status(200).json({success:1}); + } + + switch (req.method) { + case 'GET': + return getProfileById(); + case 'PUT': + return updateProfile(); + case 'DELETE': + return deleteProfile(); + default: + return res.status(405).end(`Method ${req.method} Not Allowed`) + } +} diff --git a/pages/api/profilesRepo.ts b/pages/api/profilesRepo.ts new file mode 100644 index 0000000..b2aecc0 --- /dev/null +++ b/pages/api/profilesRepo.ts @@ -0,0 +1,74 @@ +const fs = require('fs'); +import { ProfileModel } from '@/app/types/index'; +let profiles = require('@/data/profiles.json'); + +const getAll = () => { + return profiles; +} + +const getById = (id:number) => { + return profiles.find((x:ProfileModel) => x.id.toString() === id.toString()); +} + +const create = ({ name, forkPsi, forkSag, forkHsc, forkLsc, forkHsr, forkLsr, shockPsi, shockSag, shockHsc, shockLsc, shockHsr, shockLsr }:ProfileModel) => { + const id:number = profiles.length ? Math.max(...profiles.map((x:ProfileModel) => x.id)) + 1 : 1; + + const profile = <ProfileModel>{ + id, name, forkPsi, forkSag, forkHsc, forkLsc, forkHsr, forkLsr, + shockPsi, shockSag, shockHsc, shockLsc, shockHsr, shockLsr + }; + + // validate + if (profiles.find((x:ProfileModel) => x.name === profile.name)) + throw `Profile with the name ${profile.name} already exists`; + + // set date created and updated + profile.dateCreated = new Date().toISOString(); + profile.dateUpdated = new Date().toISOString(); + + // add and save profile + profiles.push(profile); + saveData(); + + return profile; +} + +const update = (id:number, { name, forkPsi, forkSag, forkHsc, forkLsc, forkHsr, forkLsr, shockPsi, shockSag, shockHsc, shockLsc, shockHsr, shockLsr }:ProfileModel) => { + const params = { name, forkPsi, forkSag, forkHsc, forkLsc, forkHsr, forkLsr, shockPsi, shockSag, shockHsc, shockLsc, shockHsr, shockLsr }; + const profile = profiles.find((x:ProfileModel) => x.id.toString() === id.toString()); + + // validate + if (params.name !== profile.name && profiles.find((x:ProfileModel) => x.name === params.name)) + throw `Profile with the name ${params.name} already exists`; + + // set date updated + profile.dateUpdated = new Date().toISOString(); + + // update and save + Object.assign(profile, params); + saveData(); +} + +// prefixed with underscore '_' because 'delete' is a reserved word in javascript +const _delete = (id:number) => { + // filter out deleted profile and save + profiles = profiles.filter((x:ProfileModel) => x.id.toString() !== id.toString()); + saveData(); + +} + +// private helper functions + +const saveData = () => { + fs.writeFileSync('data/profiles.json', JSON.stringify(profiles, null, 4)); +} + +const profilesRepo = { + getAll, + getById, + create, + update, + delete: _delete +}; + +export default profilesRepo;