feat: option to edit image

Signed-off-by: Varun Raj <mailme@varunraj.in>
This commit is contained in:
Varun Raj committed 2024-08-17 23:03:39 +05:30
1 parent 75e5f9338c
commit a8bce40b3a
18 files changed
+724 -5

No files matched your search

BIN
View File
Binary file not shown.
+5
View File
@@ -9,11 +9,16 @@
"lint": "next lint"
},
"dependencies": {
"@radix-ui/react-avatar": "^1.1.0",
"@radix-ui/react-icons": "^1.3.0",
"@radix-ui/react-slot": "^1.1.0",
"@tanstack/react-table": "^8.20.1",
"@types/qs": "^6.9.15",
"axios": "^1.7.4",
"class-variance-authority": "^0.7.0",
"clsx": "^2.1.1",
"next": "14.2.5",
"qs": "^6.13.0",
"react": "^18",
"react-dom": "^18",
"sass": "^1.77.8",
+66
View File
@@ -0,0 +1,66 @@
import { listPeople } from "@/handlers/api/people.handler";
import { IListData } from "@/types/common";
import { IPerson } from "@/types/person";
import React, { useEffect, useState } from "react";
import Loader from "../ui/loader";
import PersonItem from "./PersonItem";
import { ColumnDef } from "@tanstack/react-table";
import { Table } from "../ui/table";
import PersonBirthdayCell from "./PersonBirthdayCell";
const columns: ColumnDef<IPerson>[] = [
{
header: "Name",
accessorKey: "name",
cell: ({ row }) => <PersonItem person={row.original} />,
},
{
header: "Birth Date",
accessorKey: "birthDate",
cell: ({ row }) => <PersonBirthdayCell person={row.original} />,
},
{
header: "Updated At",
accessorKey: "updatedAt",
cell: ({ row }) => <span>{new Date(
row.original.updatedAt
).toDateString()}</span>,
},
];
export default function PeopleList() {
const [people, setPeople] = useState<IPerson[]>([]);
const [loading, setLoading] = useState(false);
const [errorMessage, setErrorMessage] = useState<string | null>(null);
const fetchData = async () => {
return listPeople()
.then((response) => {
setPeople(response.people);
})
.catch((error) => {
setErrorMessage(error.message);
})
.finally(() => {
setLoading(false);
});
};
useEffect(() => {
fetchData();
}, []);
if (loading) return <Loader />;
if (errorMessage) return <div>{errorMessage}</div>;
return (
<div>
<div className="flex flex-col gap-2">
<Table<IPerson> columns={columns} data={people} />
</div>
</div>
);
}
@@ -0,0 +1,20 @@
import { IPerson } from '@/types/person'
import React from 'react'
interface IProps {
person: IPerson
}
export default function PersonBirthdayCell(
{ person }: IProps
) {
return (
<div>
{person.birthDate ? (
<span>{person.birthDate.toDateString()}</span>
) : (
<span>Unknown</span>
)}
</div>
)
}
+59
View File
@@ -0,0 +1,59 @@
import { IPerson } from "@/types/person";
import React, { useState } from "react";
import { Avatar } from "../ui/avatar";
import { updatePerson } from "@/handlers/api/people.handler";
interface IProps {
person: IPerson;
}
export default function PersonItem({ person }: IProps) {
const [editMode, setEditMode] = useState(false);
const [loading, setLoading] = useState(false);
const [formData, setFormData] = useState(person);
const handleEdit = () => {
setLoading(true);
return updatePerson(person.id, {
name: formData.name,
})
.then(() => {
setEditMode(!editMode);
})
.catch(() => {})
.finally(() => {
setLoading(false);
});
};
return (
<div className="flex items-center gap-2">
<Avatar
className="w-12 h-12"
src={person.thumbnailPath}
alt={person.name}
/>
{!editMode ? (
<h2
className="text-lg font-semibold"
onClick={() => {
setEditMode((prev) => !prev);
}}
>
{formData.name ? formData.name : <span className="text-gray-400">Unknown</span>}
</h2>
) : (
<input
type="text"
className="text-lg font-semibold"
defaultValue={formData.name}
autoFocus
onChange={(e) => {
setFormData({ ...formData, name: e.target.value });
}}
disabled={loading}
onBlur={handleEdit}
/>
)}
</div>
);
}
+63
View File
@@ -0,0 +1,63 @@
import * as React from "react"
import * as AvatarPrimitive from "@radix-ui/react-avatar"
import { cn } from "@/lib/utils"
const AvatarRoot = React.forwardRef<
React.ElementRef<typeof AvatarPrimitive.Root>,
React.ComponentPropsWithoutRef<typeof AvatarPrimitive.Root>
>(({ className, ...props }, ref) => (
<AvatarPrimitive.Root
ref={ref}
className={cn(
"relative flex h-10 w-10 shrink-0 overflow-hidden rounded-full",
className
)}
{...props}
/>
))
AvatarRoot.displayName = AvatarPrimitive.Root.displayName
const AvatarImage = React.forwardRef<
React.ElementRef<typeof AvatarPrimitive.Image>,
React.ComponentPropsWithoutRef<typeof AvatarPrimitive.Image>
>(({ className, ...props }, ref) => (
<AvatarPrimitive.Image
ref={ref}
className={cn("aspect-square h-full w-full", className)}
{...props}
/>
))
AvatarImage.displayName = AvatarPrimitive.Image.displayName
const AvatarFallback = React.forwardRef<
React.ElementRef<typeof AvatarPrimitive.Fallback>,
React.ComponentPropsWithoutRef<typeof AvatarPrimitive.Fallback>
>(({ className, ...props }, ref) => (
<AvatarPrimitive.Fallback
ref={ref}
className={cn(
"flex h-full w-full items-center justify-center rounded-full bg-muted",
className
)}
{...props}
/>
))
AvatarFallback.displayName = AvatarPrimitive.Fallback.displayName
interface AvatarProps {
src: string
alt: string
className?: string
}
const Avatar = (props: AvatarProps) => {
const { src, alt } = props
return (
<AvatarRoot {...props}>
{src && <AvatarImage src={src} alt={alt} />}
{alt && !src && <AvatarFallback>{alt[0]}</AvatarFallback>}
</AvatarRoot>
)
}
export { Avatar, AvatarRoot, AvatarImage, AvatarFallback }
+25
View File
@@ -0,0 +1,25 @@
import React from "react";
export default function Loader() {
return (
<div role="status">
<svg
aria-hidden="true"
className="w-8 h-8 text-gray-200 animate-spin dark:text-gray-600 fill-blue-600"
viewBox="0 0 100 101"
fill="none"
xmlns="http://www.w3.org/2000/svg"
>
<path
d="M100 50.5908C100 78.2051 77.6142 100.591 50 100.591C22.3858 100.591 0 78.2051 0 50.5908C0 22.9766 22.3858 0.59082 50 0.59082C77.6142 0.59082 100 22.9766 100 50.5908ZM9.08144 50.5908C9.08144 73.1895 27.4013 91.5094 50 91.5094C72.5987 91.5094 90.9186 73.1895 90.9186 50.5908C90.9186 27.9921 72.5987 9.67226 50 9.67226C27.4013 9.67226 9.08144 27.9921 9.08144 50.5908Z"
fill="currentColor"
/>
<path
d="M93.9676 39.0409C96.393 38.4038 97.8624 35.9116 97.0079 33.5539C95.2932 28.8227 92.871 24.3692 89.8167 20.348C85.8452 15.1192 80.8826 10.7238 75.2124 7.41289C69.5422 4.10194 63.2754 1.94025 56.7698 1.05124C51.7666 0.367541 46.6976 0.446843 41.7345 1.27873C39.2613 1.69328 37.813 4.19778 38.4501 6.62326C39.0873 9.04874 41.5694 10.4717 44.0505 10.1071C47.8511 9.54855 51.7191 9.52689 55.5402 10.0491C60.8642 10.7766 65.9928 12.5457 70.6331 15.2552C75.2735 17.9648 79.3347 21.5619 82.5849 25.841C84.9175 28.9121 86.7997 32.2913 88.1811 35.8758C89.083 38.2158 91.5421 39.6781 93.9676 39.0409Z"
fill="currentFill"
/>
</svg>
<span className="sr-only">Loading...</span>
</div>
);
}
+188
View File
@@ -0,0 +1,188 @@
import * as React from "react"
import { cn } from "@/lib/utils"
import { ColumnDef, flexRender, getCoreRowModel, getFilteredRowModel, getPaginationRowModel, getSortedRowModel, TableOptions, useReactTable } from "@tanstack/react-table"
const TableRoot = React.forwardRef<
HTMLTableElement,
React.HTMLAttributes<HTMLTableElement>
>(({ className, ...props }, ref) => (
<div className="relative w-full overflow-auto">
<table
ref={ref}
className={cn("w-full caption-bottom text-sm", className)}
{...props}
/>
</div>
))
TableRoot.displayName = "Table"
const TableHeader = React.forwardRef<
HTMLTableSectionElement,
React.HTMLAttributes<HTMLTableSectionElement>
>(({ className, ...props }, ref) => (
<thead ref={ref} className={cn("[&_tr]:border-b", className)} {...props} />
))
TableHeader.displayName = "TableHeader"
const TableBody = React.forwardRef<
HTMLTableSectionElement,
React.HTMLAttributes<HTMLTableSectionElement>
>(({ className, ...props }, ref) => (
<tbody
ref={ref}
className={cn("[&_tr:last-child]:border-0", className)}
{...props}
/>
))
TableBody.displayName = "TableBody"
const TableFooter = React.forwardRef<
HTMLTableSectionElement,
React.HTMLAttributes<HTMLTableSectionElement>
>(({ className, ...props }, ref) => (
<tfoot
ref={ref}
className={cn(
"border-t bg-muted/50 font-medium [&>tr]:last:border-b-0",
className
)}
{...props}
/>
))
TableFooter.displayName = "TableFooter"
const TableRow = React.forwardRef<
HTMLTableRowElement,
React.HTMLAttributes<HTMLTableRowElement>
>(({ className, ...props }, ref) => (
<tr
ref={ref}
className={cn(
"border-b transition-colors hover:bg-muted/50 data-[state=selected]:bg-muted",
className
)}
{...props}
/>
))
TableRow.displayName = "TableRow"
const TableHead = React.forwardRef<
HTMLTableCellElement,
React.ThHTMLAttributes<HTMLTableCellElement>
>(({ className, ...props }, ref) => (
<th
ref={ref}
className={cn(
"h-10 px-2 text-left align-middle font-medium text-muted-foreground [&:has([role=checkbox])]:pr-0 [&>[role=checkbox]]:translate-y-[2px]",
className
)}
{...props}
/>
))
TableHead.displayName = "TableHead"
const TableCell = React.forwardRef<
HTMLTableCellElement,
React.TdHTMLAttributes<HTMLTableCellElement>
>(({ className, ...props }, ref) => (
<td
ref={ref}
className={cn(
"p-2 align-middle [&:has([role=checkbox])]:pr-0 [&>[role=checkbox]]:translate-y-[2px]",
className
)}
{...props}
/>
))
TableCell.displayName = "TableCell"
const TableCaption = React.forwardRef<
HTMLTableCaptionElement,
React.HTMLAttributes<HTMLTableCaptionElement>
>(({ className, ...props }, ref) => (
<caption
ref={ref}
className={cn("mt-4 text-sm text-muted-foreground", className)}
{...props}
/>
))
TableCaption.displayName = "TableCaption"
interface ITableProps<T> extends Partial<TableOptions<T>> {
columns: ColumnDef<T>[]
data: T[]
}
const Table = <T, >(props: ITableProps<T>) => {
const table = useReactTable({
...props,
getCoreRowModel: getCoreRowModel(),
getFilteredRowModel: getFilteredRowModel(),
getSortedRowModel: getSortedRowModel(),
});
return (
<TableRoot>
<TableHeader>
{table.getHeaderGroups().map((headerGroup) => (
<TableRow key={headerGroup.id}>
{headerGroup.headers.map((header) => {
return (
<TableHead key={header.id}>
{header.isPlaceholder
? null
: flexRender(
header.column.columnDef.header,
header.getContext()
)}
</TableHead>
)
})}
</TableRow>
))}
</TableHeader>
<TableBody>
{table.getRowModel().rows?.length ? (
table.getRowModel().rows.map((row) => (
<TableRow
key={row.id}
data-state={row.getIsSelected() && "selected"}
>
{row.getVisibleCells().map((cell) => (
<TableCell key={cell.id}>
{flexRender(
cell.column.columnDef.cell,
cell.getContext()
)}
</TableCell>
))}
</TableRow>
))
) : (
<TableRow>
<TableCell
colSpan={props.columns.length}
className="h-24 text-center"
>
No results.
</TableCell>
</TableRow>
)}
</TableBody>
</TableRoot>
)
}
export {
Table,
TableRoot,
TableHeader,
TableBody,
TableFooter,
TableHead,
TableRow,
TableCell,
TableCaption,
}
+4
View File
@@ -0,0 +1,4 @@
export const ENV = {
IMMICH_URL: process.env.NEXT_PUBLIC_IMMICH_URL as string,
IMMICH_API_KEY: process.env.IMMICH_API_KEY as string
}
+5
View File
@@ -0,0 +1,5 @@
export const BASE_ENDPOINT = '/api/immich-proxy';
export const LIST_PEOPLE_PATH = BASE_ENDPOINT + "/people";
export const PERSON_THUBNAIL_PATH = (id: string) => BASE_ENDPOINT + "/thumbnail/" + id;
export const UPDATE_PERSON_PATH = (id: string) => BASE_ENDPOINT + "/people/" + id;
+17
View File
@@ -0,0 +1,17 @@
import { LIST_PEOPLE_PATH, UPDATE_PERSON_PATH } from "@/config/routes"
import { cleanUpPerson } from "@/helpers/person.helper";
import API from "@/lib/api"
import { IPeopleListResponse, IPerson } from "@/types/person"
export const listPeople = (): Promise<IPeopleListResponse> => {
return API.get(LIST_PEOPLE_PATH).then((response) => {
return {
...response,
people: response.people.map(cleanUpPerson),
}
});
}
export const updatePerson = (id: string, data: Partial<IPerson>) => {
return API.put(UPDATE_PERSON_PATH(id), data)
}
+11
View File
@@ -0,0 +1,11 @@
import { PERSON_THUBNAIL_PATH } from "@/config/routes"
import { IPerson } from "@/types/person"
export const cleanUpPerson = (person: IPerson): IPerson => {
return {
...person,
thumbnailPath: PERSON_THUBNAIL_PATH(person.id),
birthDate: person.birthDate ? new Date(person.birthDate) : null,
updatedAt: new Date(person.updatedAt),
}
}
+148
View File
@@ -0,0 +1,148 @@
import type { AxiosError, AxiosRequestConfig, Method } from 'axios'
import axios from 'axios'
import qs from 'qs'
// const handleErrors = (error: AxiosError | any) => {
// console.error('error_message', error.message)
// if (error.message === 'canceled') {
// const cancelledError = {
// code: 'ERR_CANCELED',
// message: 'Request canceled',
// }
// return Promise.reject(cancelledError)
// }
// let errorObject = {}
// if (error.response) {
// const { status } = error.response
// if (status === 401) {
// errorObject = {
// ...error.response.data,
// message: error.response.data.message,
// }
// if (typeof window !== 'undefined' && window.location) {
// // return resetSession().then(() => {
// // window.location.href = '/auth/signin'
// // return Promise.reject(errorObject)
// // })
// }
// } else if (status === 403) {
// errorObject = {
// ...error.response.data,
// message:
// 'You do not have access to this page. Please contact your administrator!',
// }
// if (typeof window !== 'undefined' && window.location) {
// // deleteLocalHashData()
// window.location.href = '/404'
// return Promise.reject(errorObject)
// }
// } else if (status === 422) {
// errorObject = {
// ...error.response.data,
// message: 'Unable to process this request, please try again later',
// }
// } else {
// errorObject = {
// ...error.response.data,
// }
// }
// return Promise.reject(errorObject)
// }
// errorObject = {
// message: 'Network Error. Please check your connection and try again!',
// }
// return Promise.reject(errorObject)
// }
export default class API {
static setBaseURL(url: string) {
if (url) {
axios.defaults.baseURL = url
}
}
static setHeader(headers: any = {}): any {
axios.defaults.headers.common = {
...axios.defaults.headers.common,
...headers,
}
return {
...axios.defaults.headers.common,
...headers,
}
}
static headers(contentType: string = 'application/json'): any {
return {
...axios.defaults.headers.common,
Accept: 'application/json',
'Content-Type': contentType,
}
}
static get(
route: string,
params: any = {},
headers: any = {},
otherOptions: any = {}
): Promise<any> {
return this.xhr(route, params, 'GET', undefined, headers, otherOptions)
}
static put(route: string, params: any = {}): Promise<any> {
return this.xhr(route, params, 'PUT')
}
static post(route: string, params: any = {}): Promise<any> {
return this.xhr(route, params, 'POST')
}
static postWithForm(route: string, params: any = {}): Promise<any> {
return this.xhr(
route,
qs.stringify(params),
'POST',
'application/x-www-form-urlencoded'
)
}
static postWithFiles(route: string, params: any = {}): Promise<any> {
return this.xhr(route, params, 'POST', 'multipart/form-data')
}
static putWithFiles(route: string, params: any = {}): Promise<any> {
return this.xhr(route, params, 'PUT', 'multipart/form-data')
}
static delete(route: string, params: any = {}): Promise<any> {
return this.xhr(route, params, 'DELETE')
}
static patch(route: string, params: any): Promise<any> {
return this.xhr(route, params, 'PATCH')
}
static xhr(
route: string,
params: any,
verb: Method,
contentType: string = 'application/json',
headers: any = {},
otherOptions: any = {}
) {
const dataOption: AxiosRequestConfig = {}
if (params && verb === 'GET') {
dataOption.params = params
} else {
dataOption.data = params
}
const options = { method: verb, url: route, ...dataOption, ...otherOptions }
options.headers = Object.assign(API.headers(contentType), headers)
return axios(options)
.then((responseJson) => responseJson.data)
// .catch(handleErrors)
}
}
+47
View File
@@ -0,0 +1,47 @@
// pages/api/proxy/[...path].ts
import { ENV } from '@/config/environment';
import { NextApiRequest, NextApiResponse } from 'next'
export default async function handler(req: NextApiRequest, res: NextApiResponse) {
const proxyPath = req.url?.replace('/api/immich-proxy', '');
const targetUrl = `${ENV.IMMICH_URL}/api${proxyPath}`;
console.log('targetUrl:', req.method)
try {
const response = await fetch(targetUrl, {
method: req.method,
headers: {
'x-api-key': ENV.IMMICH_API_KEY,
'Content-Type': 'application/json',
},
body: req.method !== 'GET' && req.method !== 'HEAD' ? JSON.stringify(req.body) : null,
})
// Forward the status code
res.status(response.status)
// Forward the headers
const responseHeaders = response.headers
responseHeaders.forEach((value, key) => {
res.setHeader(key, value)
})
// Stream the response body
const reader = response.body?.getReader()
if (reader) {
while (true) {
const { done, value } = await reader.read()
if (done) break
res.write(value)
}
}
res.end()
} catch (error) {
console.error('Proxy error:', error)
res.status(500).json({ error: 'Internal Server Error' })
}
}
@@ -0,0 +1,47 @@
// pages/api/proxy.js
import { ENV } from '@/config/environment';
import { NextApiRequest, NextApiResponse } from 'next'
export const config = {
api: {
bodyParser: false,
},
}
export default async function handler(req: NextApiRequest, res: NextApiResponse) {
if (req.method !== 'GET') {
return res.status(405).json({ message: 'Method Not Allowed' })
}
const { id } = req.query;
const targetUrl = `${ENV.IMMICH_URL}/api/people/${id}/thumbnail`;
try {
// Forward the request to the target API
const response = await fetch(targetUrl, {
method: 'GET',
headers: {
'Content-Type': 'application/octet-stream',
'x-api-key': ENV.IMMICH_API_KEY,
},
})
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`)
}
// Get the image data from the response
const imageBuffer = await response.arrayBuffer()
// Set the appropriate headers for the image response
res.setHeader('Content-Type', response.headers.get('Content-Type') || 'image/png')
res.setHeader('Content-Length', imageBuffer.byteLength)
// Send the image data
res.send(Buffer.from(imageBuffer))
} catch (error) {
console.error('Error:', error)
res.status(500).json({ message: 'Internal Server Error' })
}
}
+2 -5
View File
@@ -1,13 +1,10 @@
import Image from "next/image";
import { Inter } from "next/font/google";
import { Button } from "@/components/ui/button";
import PeopleList from "@/components/people/PeopleList";
const inter = Inter({ subsets: ["latin"] });
export default function Home() {
return (
<Button>
Hello
</Button>
<PeopleList />
);
}
+5
View File
@@ -0,0 +1,5 @@
export interface IListData {
hasNextPage: boolean,
total: number,
hidden: number,
}
+12
View File
@@ -0,0 +1,12 @@
export interface IPerson {
id: string;
name: string;
birthDate: Date | null;
thumbnailPath: string;
isHidden: boolean;
updatedAt: Date;
}
interface IPeopleListResponse extends IListData{
people: IPerson[]
}