dev feat(markcard, static): 实现书签卡片功能和静态资源获取

- 书签卡片相关的组件和页面
- 实现书签数据的获取、添加、编辑和删除功能
- 添加用户验证和权限控制
- 优化页面布局和样式
This commit is contained in:
ZZY 2024-12-22 15:21:07 +08:00
parent ed805d6344
commit 73917d6001
40 changed files with 2858 additions and 598 deletions

3
.env Normal file

@ -0,0 +1,3 @@
DATA_PATH=data
STATIC_FILE_PATH=$DATA_PATH/static
CARD_FILE_PATH=$DATA_PATH/card

1
.env.development Normal file

@ -0,0 +1 @@
MARKCARD_TOKEN=admin

0
.env.production Normal file

0
.env.test Normal file

7
.gitignore vendored

@ -31,7 +31,7 @@ yarn-error.log*
.pnpm-debug.log*
# env files (can opt-in for committing if needed)
.env*
.env*.local
# vercel
.vercel
@ -39,3 +39,8 @@ yarn-error.log*
# typescript
*.tsbuildinfo
next-env.d.ts
# dev project
/.vscode/
data/*
!data/.gitkeep

@ -0,0 +1,56 @@
import { NextRequest, NextResponse } from 'next/server'
import { MarkCardI, addCard, updateCard, getCards, getPath } from '@/lib/markcard/card'
import { notFound } from 'next/navigation'
async function getFilePath(params: Promise<{ file?: string[] }> ): Promise<string> {
const file = (await params).file
// console.log('file', file)
// const files = file ? file[0].split(',') : undefined
const filepath = await getPath(undefined, file)
if (filepath === null) {
return notFound()
}
return filepath
}
export async function GET(
req: NextRequest,
{ params }: { params: Promise<{ file: string[] }> }
) {
const filePath = await getFilePath(params)
const cards = await getCards(filePath)
if (cards === undefined) {
return notFound()
} else {
return NextResponse.json(cards, { status: 200 })
}
}
export async function POST(req: NextRequest,
{ params }: { params: Promise<{ file?: string[] }> }
) {
const card: MarkCardI = await req.json()
if (!card) {
return NextResponse.json({ error: 'Invalid card data' }, { status: 400 })
}
try {
const newcard = await addCard(card, await getFilePath(params))
return NextResponse.json(newcard, { status: 200 })
} catch (error) {
return NextResponse.json({ error }, { status: 400 })
}
}
export async function PATCH(req: NextRequest,
{ params }: { params: Promise<{ file?: string[] }> }
) {
const card: MarkCardI = await req.json()
if (!card) {
return NextResponse.json({ error: 'Invalid card data' }, { status: 400 })
}
const retcard = await updateCard(card, card.id, await getFilePath(params))
return NextResponse.json(retcard, { status: 200 })
}

@ -0,0 +1,12 @@
import env from '@/lib/env'
import { NextRequest, NextResponse } from 'next/server'
export async function POST(req: NextRequest) {
const { token, userId } = await req.json()
if (userId === undefined) {
if (token === env('MARKCARD_TOKEN')) {
return NextResponse.json({ validate: true }, { status: 200 })
}
}
return NextResponse.json({ validate: false }, { status: 401 })
}

Binary file not shown.

Before

Width: 256px  |  Height: 256px  |  Size: 25 KiB

After

Width: 300px  |  Height: 300px  |  Size: 6.6 KiB

@ -2,20 +2,71 @@
@tailwind components;
@tailwind utilities;
:root {
--background: #ffffff;
--foreground: #171717;
body {
font-family: Arial, Helvetica, sans-serif;
}
@media (prefers-color-scheme: dark) {
@layer base {
:root {
--background: #0a0a0a;
--foreground: #ededed;
--background: 0 0% 100%;
--foreground: 240 10% 3.9%;
--card: 0 0% 100%;
--card-foreground: 240 10% 3.9%;
--popover: 0 0% 100%;
--popover-foreground: 240 10% 3.9%;
--primary: 240 5.9% 10%;
--primary-foreground: 0 0% 98%;
--secondary: 240 4.8% 95.9%;
--secondary-foreground: 240 5.9% 10%;
--muted: 240 4.8% 95.9%;
--muted-foreground: 240 3.8% 46.1%;
--accent: 240 4.8% 95.9%;
--accent-foreground: 240 5.9% 10%;
--destructive: 0 84.2% 60.2%;
--destructive-foreground: 0 0% 98%;
--border: 240 5.9% 90%;
--input: 240 5.9% 90%;
--ring: 240 10% 3.9%;
--chart-1: 12 76% 61%;
--chart-2: 173 58% 39%;
--chart-3: 197 37% 24%;
--chart-4: 43 74% 66%;
--chart-5: 27 87% 67%;
--radius: 0.5rem;
}
.dark {
--background: 240 10% 3.9%;
--foreground: 0 0% 98%;
--card: 240 10% 3.9%;
--card-foreground: 0 0% 98%;
--popover: 240 10% 3.9%;
--popover-foreground: 0 0% 98%;
--primary: 0 0% 98%;
--primary-foreground: 240 5.9% 10%;
--secondary: 240 3.7% 15.9%;
--secondary-foreground: 0 0% 98%;
--muted: 240 3.7% 15.9%;
--muted-foreground: 240 5% 64.9%;
--accent: 240 3.7% 15.9%;
--accent-foreground: 0 0% 98%;
--destructive: 0 62.8% 30.6%;
--destructive-foreground: 0 0% 98%;
--border: 240 3.7% 15.9%;
--input: 240 3.7% 15.9%;
--ring: 240 4.9% 83.9%;
--chart-1: 220 70% 50%;
--chart-2: 160 60% 45%;
--chart-3: 30 80% 55%;
--chart-4: 280 65% 60%;
--chart-5: 340 75% 55%;
}
}
body {
color: var(--foreground);
background: var(--background);
font-family: Arial, Helvetica, sans-serif;
@layer base {
* {
@apply border-border;
}
body {
@apply bg-background text-foreground;
}
}

@ -1,16 +1,17 @@
import type { Metadata } from "next";
import { Geist, Geist_Mono } from "next/font/google";
// import { Geist, Geist_Mono } from "next/font/google";
import "./globals.css";
import AlertWeb from "@/components/AlertWeb";
const geistSans = Geist({
variable: "--font-geist-sans",
subsets: ["latin"],
});
// const geistSans = Geist({
// variable: "--font-geist-sans",
// subsets: ["latin"],
// });
const geistMono = Geist_Mono({
variable: "--font-geist-mono",
subsets: ["latin"],
});
// const geistMono = Geist_Mono({
// variable: "--font-geist-mono",
// subsets: ["latin"],
// });
export const metadata: Metadata = {
title: "Create Next App",
@ -25,8 +26,9 @@ export default function RootLayout({
return (
<html lang="en">
<body
className={`${geistSans.variable} ${geistMono.variable} antialiased`}
// className={`${geistSans.variable} ${geistMono.variable} antialiased`}
>
<AlertWeb/>
{children}
</body>
</html>

@ -0,0 +1,21 @@
import React, { Suspense } from 'react'
import MarkCards from '@/components/markcard/MarkCardsClient'
export default async function page({
params,
}: {
params: Promise<{ url?: string[] }>
}) {
const url = (await params).url
return (
<div className='space-y-4'>
<div className='text-3xl font-bold flex justify-center'>MarkCards</div>
<div className='flex justify-center'>
<Suspense fallback={<p>loading...</p>}>
<MarkCards fileUrl={url} canEdit={false}/>
</Suspense>
</div>
</div>
)
}

101
app/next/page.tsx Normal file

@ -0,0 +1,101 @@
import Image from "next/image";
export default function Home() {
return (
<div className="grid grid-rows-[20px_1fr_20px] items-center justify-items-center min-h-screen p-8 pb-20 gap-16 sm:p-20 font-[family-name:var(--font-geist-sans)]">
<main className="flex flex-col gap-8 row-start-2 items-center sm:items-start">
<Image
className="dark:invert"
src="/next.svg"
alt="Next.js logo"
width={180}
height={38}
priority
/>
<ol className="list-inside list-decimal text-sm text-center sm:text-left font-[family-name:var(--font-geist-mono)]">
<li className="mb-2">
Get started by editing{" "}
<code className="bg-black/[.05] dark:bg-white/[.06] px-1 py-0.5 rounded font-semibold">
app/page.tsx
</code>
.
</li>
<li>Save and see your changes instantly.</li>
</ol>
<div className="flex gap-4 items-center flex-col sm:flex-row">
<a
className="rounded-full border border-solid border-transparent transition-colors flex items-center justify-center bg-foreground text-background gap-2 hover:bg-[#383838] dark:hover:bg-[#ccc] text-sm sm:text-base h-10 sm:h-12 px-4 sm:px-5"
href="https://vercel.com/new?utm_source=create-next-app&utm_medium=appdir-template-tw&utm_campaign=create-next-app"
target="_blank"
rel="noopener noreferrer"
>
<Image
className="dark:invert"
src="/vercel.svg"
alt="Vercel logomark"
width={20}
height={20}
/>
Deploy now
</a>
<a
className="rounded-full border border-solid border-black/[.08] dark:border-white/[.145] transition-colors flex items-center justify-center hover:bg-[#f2f2f2] dark:hover:bg-[#1a1a1a] hover:border-transparent text-sm sm:text-base h-10 sm:h-12 px-4 sm:px-5 sm:min-w-44"
href="https://nextjs.org/docs?utm_source=create-next-app&utm_medium=appdir-template-tw&utm_campaign=create-next-app"
target="_blank"
rel="noopener noreferrer"
>
Read our docs
</a>
</div>
</main>
<footer className="row-start-3 flex gap-6 flex-wrap items-center justify-center">
<a
className="flex items-center gap-2 hover:underline hover:underline-offset-4"
href="https://nextjs.org/learn?utm_source=create-next-app&utm_medium=appdir-template-tw&utm_campaign=create-next-app"
target="_blank"
rel="noopener noreferrer"
>
<Image
aria-hidden
src="/file.svg"
alt="File icon"
width={16}
height={16}
/>
Learn
</a>
<a
className="flex items-center gap-2 hover:underline hover:underline-offset-4"
href="https://vercel.com/templates?framework=next.js&utm_source=create-next-app&utm_medium=appdir-template-tw&utm_campaign=create-next-app"
target="_blank"
rel="noopener noreferrer"
>
<Image
aria-hidden
src="/window.svg"
alt="Window icon"
width={16}
height={16}
/>
Examples
</a>
<a
className="flex items-center gap-2 hover:underline hover:underline-offset-4"
href="https://nextjs.org?utm_source=create-next-app&utm_medium=appdir-template-tw&utm_campaign=create-next-app"
target="_blank"
rel="noopener noreferrer"
>
<Image
aria-hidden
src="/globe.svg"
alt="Globe icon"
width={16}
height={16}
/>
Go to nextjs.org
</a>
</footer>
</div>
);
}

20
app/not-found.tsx Normal file

@ -0,0 +1,20 @@
import { Button } from '@/components/ui/button'
import Link from 'next/link'
export default function NotFound() {
return (
<div className="flex flex-col items-center
gap-4
justify-center min-h-screen bg-white text-black dark:bg-black dark:text-white">
<div className="text-6xl font-bold text-red-500">404</div>
<h2 className="text-xl font-semibold">Not Found</h2>
<p className="text-gray-600 dark:text-gray-400">Could not find requested resource</p>
<Button variant="secondary">
<Link href="/">
Return Home
</Link>
</Button>
</div>
// <div><style>body{color:#000;background:#fff;margin:0}.next-error-h1{border - right:1px solid rgba(0,0,0,.3)}@media (prefers-color-scheme:dark){body{color:#fff;background:#000}.next-error-h1{border - right:1px solid rgba(255,255,255,.3)}}</style><h1 class="next-error-h1" style="display: inline-block; margin: 0px 20px 0px 0px; padding: 0px 23px 0px 0px; font-size: 24px; font-weight: 500; vertical-align: top; line-height: 49px;">404</h1><div style="display: inline-block;"><h2 style="font-size: 14px; font-weight: 400; line-height: 49px; margin: 0px;">This page could not be found.</h2></div></div>
)
}

@ -1,101 +1,15 @@
import Image from "next/image";
import MarkCards from '@/components/markcard/MarkCardsServer'
import React from 'react'
import path from 'path'
import { redirect } from 'next/navigation'
export default function Home() {
export default function page() {
return (
<div className="grid grid-rows-[20px_1fr_20px] items-center justify-items-center min-h-screen p-8 pb-20 gap-16 sm:p-20 font-[family-name:var(--font-geist-sans)]">
<main className="flex flex-col gap-8 row-start-2 items-center sm:items-start">
<Image
className="dark:invert"
src="/next.svg"
alt="Next.js logo"
width={180}
height={38}
priority
/>
<ol className="list-inside list-decimal text-sm text-center sm:text-left font-[family-name:var(--font-geist-mono)]">
<li className="mb-2">
Get started by editing{" "}
<code className="bg-black/[.05] dark:bg-white/[.06] px-1 py-0.5 rounded font-semibold">
app/page.tsx
</code>
.
</li>
<li>Save and see your changes instantly.</li>
</ol>
<div className="flex gap-4 items-center flex-col sm:flex-row">
<a
className="rounded-full border border-solid border-transparent transition-colors flex items-center justify-center bg-foreground text-background gap-2 hover:bg-[#383838] dark:hover:bg-[#ccc] text-sm sm:text-base h-10 sm:h-12 px-4 sm:px-5"
href="https://vercel.com/new?utm_source=create-next-app&utm_medium=appdir-template-tw&utm_campaign=create-next-app"
target="_blank"
rel="noopener noreferrer"
>
<Image
className="dark:invert"
src="/vercel.svg"
alt="Vercel logomark"
width={20}
height={20}
/>
Deploy now
</a>
<a
className="rounded-full border border-solid border-black/[.08] dark:border-white/[.145] transition-colors flex items-center justify-center hover:bg-[#f2f2f2] dark:hover:bg-[#1a1a1a] hover:border-transparent text-sm sm:text-base h-10 sm:h-12 px-4 sm:px-5 sm:min-w-44"
href="https://nextjs.org/docs?utm_source=create-next-app&utm_medium=appdir-template-tw&utm_campaign=create-next-app"
target="_blank"
rel="noopener noreferrer"
>
Read our docs
</a>
</div>
</main>
<footer className="row-start-3 flex gap-6 flex-wrap items-center justify-center">
<a
className="flex items-center gap-2 hover:underline hover:underline-offset-4"
href="https://nextjs.org/learn?utm_source=create-next-app&utm_medium=appdir-template-tw&utm_campaign=create-next-app"
target="_blank"
rel="noopener noreferrer"
>
<Image
aria-hidden
src="/file.svg"
alt="File icon"
width={16}
height={16}
/>
Learn
</a>
<a
className="flex items-center gap-2 hover:underline hover:underline-offset-4"
href="https://vercel.com/templates?framework=next.js&utm_source=create-next-app&utm_medium=appdir-template-tw&utm_campaign=create-next-app"
target="_blank"
rel="noopener noreferrer"
>
<Image
aria-hidden
src="/window.svg"
alt="Window icon"
width={16}
height={16}
/>
Examples
</a>
<a
className="flex items-center gap-2 hover:underline hover:underline-offset-4"
href="https://nextjs.org?utm_source=create-next-app&utm_medium=appdir-template-tw&utm_campaign=create-next-app"
target="_blank"
rel="noopener noreferrer"
>
<Image
aria-hidden
src="/globe.svg"
alt="Globe icon"
width={16}
height={16}
/>
Go to nextjs.org
</a>
</footer>
</div>
);
redirect('/markcard')
// <div className='flex justify-center'>
// <div className='container flex justify-center'>
// <MarkCards canEdit={false} filePath={ path.join(process.cwd(), 'public', 'markcard.json') }/>
// </div>
// </div>
)
}

@ -0,0 +1,69 @@
import { NextRequest, NextResponse } from 'next/server'
import fs from 'fs/promises'
import path from 'path'
import env from '@/lib/env';
import resolveFilePath from '@/lib/file';
// 白名单:允许访问的文件扩展名
const allowedExtensions = ['.html', '.js', '.css', '.json', '.png', '.jpg', '.jpeg', '.gif', '.svg'];
const basePath = path.join(process.cwd(), env('STATIC_FILE_PATH'))
export async function GET(req: NextRequest,
{ params }: { params: Promise<{ path?: string[] }> }
) {
const fileseg = (await params).path
const filepath = resolveFilePath(fileseg, basePath, allowedExtensions, ['index.html'])
if (filepath === null) {
return NextResponse.json({ message: 'File not found' }, { status: 404 })
}
try {
// 获取文件扩展名以确定 MIME 类型
const extname = path.extname(filepath).toLowerCase();
if (!allowedExtensions.includes(extname)) {
return NextResponse.json({ error: 'Forbidden file type' }, { status: 403 });
}
// 设置响应头
let contentType = 'text/plain';
switch (extname) {
case '.html':
contentType = 'text/html';
break;
case '.js':
contentType = 'text/javascript';
break;
case '.css':
contentType = 'text/css';
break;
case '.json':
contentType = 'application/json';
break;
case '.png':
contentType = 'image/png';
break;
case '.jpg':
case '.jpeg':
contentType = 'image/jpeg';
break;
case '.gif':
contentType = 'image/gif';
break;
case '.svg':
contentType = 'image/svg+xml';
break;
default:
contentType = 'text/plain';
}
const responseHeaders = new Headers();
responseHeaders.set('Content-Type', contentType);
// 返回文件内容
return new NextResponse(await fs.readFile(filepath), { status: 200, headers: responseHeaders });
} catch (err) {
console.error(err);
return NextResponse.json({ error: 'Internal Server Error' }, { status: 500 });
}
}

21
components.json Normal file

@ -0,0 +1,21 @@
{
"$schema": "https://ui.shadcn.com/schema.json",
"style": "new-york",
"rsc": true,
"tsx": true,
"tailwind": {
"config": "tailwind.config.ts",
"css": "app/globals.css",
"baseColor": "zinc",
"cssVariables": true,
"prefix": ""
},
"aliases": {
"components": "@/components",
"utils": "@/lib/utils",
"ui": "@/components/ui",
"lib": "@/lib",
"hooks": "@/hooks"
},
"iconLibrary": "lucide"
}

23
components/AlertWeb.tsx Normal file

@ -0,0 +1,23 @@
import React from 'react'
import { AlertCircle } from "lucide-react"
import {
Alert,
AlertDescription,
AlertTitle,
} from "@/components/ui/alert"
export default function AlertWeb() {
return (
<div>
<Alert>
<AlertCircle className="h-4 w-4" />
<AlertTitle> Waring</AlertTitle>
<AlertDescription>
使
This website is for personal learning purposes only
</AlertDescription>
</Alert>
</div>
)
}

@ -0,0 +1,136 @@
'use client'
import { useState } from 'react'
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle, DialogFooter } from "@/components/ui/dialog"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Textarea } from "@/components/ui/textarea"
import { Label } from "@/components/ui/label"
import { MarkCardI } from '@/lib/markcard/card'
interface EditCardModalProps {
isOpen: boolean
onClose: () => void
cardData: MarkCardI
onSave: (updatedData: Partial<EditCardModalProps['cardData']>) => void
}
export default function EditCardModal({ isOpen, onClose, cardData, onSave }: EditCardModalProps) {
const [editedData, setEditedData] = useState(cardData)
const handleInputChange = (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => {
const { name, value } = e.target
setEditedData((prev) => ({ ...prev, [name]: value }))
}
const handleLinkChange = (index: number, field: 'title' | 'url', value: string) => {
setEditedData((prev) => ({
...prev,
links: prev.links.map((link, i) => (i === index ? { ...link, [field]: value } : link)),
}))
}
const handleAddLink = () => {
setEditedData((prev) => ({
...prev,
links: [...prev.links, { title: '', url: '' }],
}))
}
const handleRemoveLink = (index: number) => {
setEditedData((prev) => ({
...prev,
links: prev.links.filter((_, i) => i !== index),
}))
}
const handleSave = () => {
onSave(editedData)
}
return (
<Dialog open={isOpen} onOpenChange={onClose}>
<DialogContent className="sm:max-w-[425px] max-h-[90vh] overflow-y-auto">
<DialogHeader>
<DialogTitle>Edit Card</DialogTitle>
<DialogDescription>
Here you can modify the card details and links. Click `Save changes` after you are done.
</DialogDescription>
</DialogHeader>
<div className="grid gap-4 py-4">
<div className="grid grid-cols-4 items-center gap-4">
<Label htmlFor="title" className="text-right">
Title
</Label>
<Input
id="title"
name="title"
value={editedData.title}
onChange={handleInputChange}
className="col-span-3"
/>
</div>
<div className="grid grid-cols-4 items-center gap-4">
<Label htmlFor="shortDescription" className="text-right">
Short Description
</Label>
<Input
id="shortDescription"
name="shortDescription"
value={editedData.shortDescription}
onChange={handleInputChange}
className="col-span-3"
/>
</div>
<div className="grid grid-cols-4 items-center gap-4">
<Label htmlFor="detailedDescription" className="text-right">
Detailed Description
</Label>
<Textarea
id="detailedDescription"
name="detailedDescription"
value={editedData.detailedDescription}
onChange={handleInputChange}
className="col-span-3"
/>
</div>
<div className="overflow-y-auto max-h-[40vh]">
{editedData.links.map((link, index) => (
<div key={index} className="grid grid-cols-4 items-center gap-4">
<Label htmlFor={`link-${index}`} className="text-right">
Link {index + 1}
</Label>
<div className="col-span-3 grid gap-2">
<Input
id={`link-${index}-title`}
value={link.title}
onChange={(e) => handleLinkChange(index, 'title', e.target.value)}
placeholder="Link Title"
/>
<Input
id={`link-${index}-url`}
value={link.url}
onChange={(e) => handleLinkChange(index, 'url', e.target.value)}
placeholder="Link URL"
/>
<Button type="button" variant="destructive" onClick={() => handleRemoveLink(index)}>
Remove Link
</Button>
</div>
</div>
))}
</div>
<Button type="button" onClick={handleAddLink} className="mt-4">
Add Link
</Button>
</div>
<DialogFooter>
<Button type="submit" onClick={handleSave}>Save changes</Button>
</DialogFooter>
</DialogContent>
</Dialog>
)
}

@ -0,0 +1,86 @@
import React from "react"
import { Card, CardContent, CardDescription, CardFooter, CardHeader, CardTitle } from "@/components/ui/card"
import { Button } from "@/components/ui/button"
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from "@/components/ui/dropdown-menu"
import { ChevronDown, ExternalLink, Edit } from 'lucide-react'
import { MarkCardI, MarkLinkI, getBasePath } from '@/lib/markcard/card'
interface CardProps {
card: MarkCardI
canEdit: boolean
// userId?: string
baseUrl: string
onEdit?: (id: string, origin: MarkCardI) => void
}
export default function MarkCard({ card, canEdit, baseUrl, onEdit }: CardProps) {
const { id, title, shortDescription, detailedDescription, links, publicUrl } = card
// const baseUrl = await getBasePath(userId)
const realLinks = links.map(link => {
if (link.url.startsWith('$')) {
return { ...link, url: `${baseUrl}/${link.url.substring(1)}` }
}
return link
})
const getALink = (link: MarkLinkI) => {
return (
<a href={link.url} target={link.blank ? '_blank' : ''} rel="noopener noreferrer" className="flex items-center">
{link.title}
<ExternalLink className="ml-2 h-4 w-4" />
</a>
)
}
return (
<Card className="w-full max-w-md shadow-lg hover:shadow-xl transition-shadow duration-300">
<CardHeader>
<CardTitle className="text-2xl font-bold">{title}</CardTitle>
<CardDescription>{shortDescription}</CardDescription>
</CardHeader>
<CardContent>
{detailedDescription && <p className="text-sm text-gray-600 mb-4">{detailedDescription}</p>}
{publicUrl && (
<div className="mb-4">
<span className="text-sm font-semibold">Public URL: </span>
<a href={`${baseUrl}/${publicUrl}`} className="text-blue-500 hover:underline" target="_blank" rel="noopener noreferrer">
{`${baseUrl}/${publicUrl}`}
</a>
</div>
)}
</CardContent>
<CardFooter className="flex justify-between items-center">
<div className="flex space-x-2">
{ realLinks.length > 0 && (
<Button asChild variant="outline">
{getALink(realLinks[0])}
</Button>)}
{realLinks.length > 1 && (
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button variant="outline">
Open Link <ChevronDown className="ml-2 h-4 w-4" />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent>
{realLinks.slice(1).map((link, index) => (
<DropdownMenuItem key={index} asChild>
{getALink(link)}
</DropdownMenuItem>
))}
</DropdownMenuContent>
</DropdownMenu>
)}
</div>
{canEdit && onEdit && (
<Button variant="ghost" onClick={() => onEdit(id, card)}>
<Edit className="mr-2 h-4 w-4" />
Edit
</Button>
)}
</CardFooter>
</Card>
)
}

@ -0,0 +1,28 @@
import { MarkCardI } from '@/lib/markcard/card'
import MarkCard from './MarkCard'
import React from 'react'
interface CardGridProps {
cards: MarkCardI[]
canEdit: boolean
baseUrl: string
onEdit?: (id: string, origin: MarkCardI) => void
}
export default function MarkCardGrid({ cards, onEdit, baseUrl, canEdit}: CardGridProps) {
return (
<div>
{cards && <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
{cards.map((card) => (
<MarkCard
key={card.id}
card={card}
baseUrl={baseUrl}
canEdit={canEdit}
onEdit={onEdit}
/>
))}
</div>}
</div>
)
}

@ -0,0 +1,183 @@
'use client'
import { useEffect, useState } from 'react'
import { Button } from '@/components/ui/button'
import { PlusCircle } from 'lucide-react'
import { MarkCardI, MarkLinkI } from '@/lib/markcard/card'
import { Label } from "@/components/ui/label"
import { Input } from "@/components/ui/input"
import EditCardModal from './EditMarkCardModal'
import MarkCardGrid from './MarkCardGrid'
import { notFound } from 'next/navigation'
import path from 'path'
interface CardContainerProps {
userId?: string
canEdit?: boolean
fileUrl?: string[]
}
export default function MarkCards({ canEdit, userId, fileUrl }: CardContainerProps) {
const baseUrl = '/api/card'
const userUrl = `${baseUrl}${userId ? `/${userId}` : ''}`
const url = path.join(userUrl, ...(fileUrl || []))
const [validToken, setValidToken] = useState<boolean>(canEdit ? true : false)
const [token, setToken] = useState<string>('')
const [isEditModalOpen, setIsEditModalOpen] = useState<boolean>(false)
const [cards, setCards] = useState<MarkCardI[] | undefined>([])
const [card, setCard] = useState<{
id: string
card: MarkCardI
}>()
const fetchData = async () => {
console.log('fetching')
try {
const response = await fetch(url, {
method: 'GET'
})
if (!response.ok) {
setCards(undefined)
return notFound()
}
const retcards = await (response.json()) as MarkCardI[]
setCards(retcards)
} catch (error) {
console.error('Error fetching data:', error)
}
}
useEffect(() => {
fetchData()
}, [])
const onEditMarkCard = async (id: string, updatedData: Partial<MarkLinkI>) => {
try {
const response = await fetch(url, {
method: 'PATCH',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(updatedData),
})
if (!response.ok) {
throw new Error('Failed to update card')
}
setCards((prevCards) =>
prevCards?.map((card) => (card.id === id ? { ...card, ...updatedData } : card))
)
} catch (error) {
console.error('Error updating card:', error)
}
}
const onAddMarkCard = async () => {
const newCard: MarkCardI = {
id: '',
title: 'New Bookmark',
shortDescription: 'Add a description',
links: [{ title: 'Add a link', url: 'https://example.com' }],
}
try {
const response = await fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(newCard),
})
if (!response.ok) {
throw new Error('Failed to add card')
}
const realNewCard = await response.json()
setCards((prevCards) => [...prevCards ?? [], realNewCard])
} catch (error) {
console.error('Error adding card:', error)
}
}
const onVailidate = async (token: string, override?: boolean) => {
if (!override && validToken === true) {
return
}
try {
const response = await fetch('/api/card/validate', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ userId, token }),
})
if (!response.ok) {
setValidToken(false)
} else {
setValidToken((await response.json()).validate ?? false)
}
} catch {
setValidToken(false)
}
}
const onEdit = (id: string, origin: MarkCardI) => {
setCard({id, card: {...origin}})
console.log(id, origin)
setIsEditModalOpen(true)
}
return (
<div className="space-y-8 container">
<div className="flex justify-between space-x-4">
<div className='flex space-x-4'>
<Label
htmlFor='token-input'
className='flex items-center whitespace-nowrap text-xl font-bold'>
Card For
</Label>
<Input
className='flex border-none shadow-none max-w-[50vw]'
placeholder='TOKEN'
id='token-input'
value={token}
onChange={(e) => setToken(e.target.value)}
onBlur={(_) => onVailidate(token)}
/>
</div>
<div className='flex'>
{validToken && (
<div className="flex justify-end space-x-4">
<Button onClick={() => { setValidToken(false); setToken(''); fetchData()} }>Disable Edit</Button>
<Button onClick={onAddMarkCard}>
<PlusCircle className="mr-2 h-4 w-4" />
Add New Bookmark
</Button>
</div>
)}
</div>
</div>
{
cards === undefined ? notFound() :
<MarkCardGrid cards={cards} onEdit={onEdit} baseUrl={'/markcard'} canEdit={validToken} />
}
{validToken && card && (
<EditCardModal
isOpen={isEditModalOpen}
onClose={() => { setIsEditModalOpen(false); setCard(undefined) }}
cardData={card.card}
onSave={(updatedData) => {
onEditMarkCard(card.id, updatedData)
setCard(undefined)
setIsEditModalOpen(false)
}}
/>
)}
</div>
)
}

@ -0,0 +1,25 @@
'use server'
import { getBasePath, getCards, getPath, MarkCardI } from '@/lib/markcard/card'
import React from 'react'
import { notFound } from 'next/navigation'
import MarkCardGrid from './MarkCardGrid'
interface CardProps {
canEdit: boolean
onEdit?: (id: string, origin: MarkCardI) => void
userId?: string
fileUrl?: string[]
filePath?: string
}
export default async function MarkCards({ userId, fileUrl, canEdit, onEdit, filePath } : CardProps) {
const cards = await getCards(filePath ?? await getPath(userId, fileUrl) ?? notFound())
if (cards === undefined) {
return notFound()
}
return (
<MarkCardGrid cards={cards} canEdit={false} baseUrl={await getBasePath(userId)}/>
)
}

59
components/ui/alert.tsx Normal file

@ -0,0 +1,59 @@
import * as React from "react"
import { cva, type VariantProps } from "class-variance-authority"
import { cn } from "@/lib/utils"
const alertVariants = cva(
"relative w-full rounded-lg border px-4 py-3 text-sm [&>svg+div]:translate-y-[-3px] [&>svg]:absolute [&>svg]:left-4 [&>svg]:top-4 [&>svg]:text-foreground [&>svg~*]:pl-7",
{
variants: {
variant: {
default: "bg-background text-foreground",
destructive:
"border-destructive/50 text-destructive dark:border-destructive [&>svg]:text-destructive",
},
},
defaultVariants: {
variant: "default",
},
}
)
const Alert = React.forwardRef<
HTMLDivElement,
React.HTMLAttributes<HTMLDivElement> & VariantProps<typeof alertVariants>
>(({ className, variant, ...props }, ref) => (
<div
ref={ref}
role="alert"
className={cn(alertVariants({ variant }), className)}
{...props}
/>
))
Alert.displayName = "Alert"
const AlertTitle = React.forwardRef<
HTMLParagraphElement,
React.HTMLAttributes<HTMLHeadingElement>
>(({ className, ...props }, ref) => (
<h5
ref={ref}
className={cn("mb-1 font-medium leading-none tracking-tight", className)}
{...props}
/>
))
AlertTitle.displayName = "AlertTitle"
const AlertDescription = React.forwardRef<
HTMLParagraphElement,
React.HTMLAttributes<HTMLParagraphElement>
>(({ className, ...props }, ref) => (
<div
ref={ref}
className={cn("text-sm [&_p]:leading-relaxed", className)}
{...props}
/>
))
AlertDescription.displayName = "AlertDescription"
export { Alert, AlertTitle, AlertDescription }

57
components/ui/button.tsx Normal file

@ -0,0 +1,57 @@
import * as React from "react"
import { Slot } from "@radix-ui/react-slot"
import { cva, type VariantProps } from "class-variance-authority"
import { cn } from "@/lib/utils"
const buttonVariants = cva(
"inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0",
{
variants: {
variant: {
default:
"bg-primary text-primary-foreground shadow hover:bg-primary/90",
destructive:
"bg-destructive text-destructive-foreground shadow-sm hover:bg-destructive/90",
outline:
"border border-input bg-background shadow-sm hover:bg-accent hover:text-accent-foreground",
secondary:
"bg-secondary text-secondary-foreground shadow-sm hover:bg-secondary/80",
ghost: "hover:bg-accent hover:text-accent-foreground",
link: "text-primary underline-offset-4 hover:underline",
},
size: {
default: "h-9 px-4 py-2",
sm: "h-8 rounded-md px-3 text-xs",
lg: "h-10 rounded-md px-8",
icon: "h-9 w-9",
},
},
defaultVariants: {
variant: "default",
size: "default",
},
}
)
export interface ButtonProps
extends React.ButtonHTMLAttributes<HTMLButtonElement>,
VariantProps<typeof buttonVariants> {
asChild?: boolean
}
const Button = React.forwardRef<HTMLButtonElement, ButtonProps>(
({ className, variant, size, asChild = false, ...props }, ref) => {
const Comp = asChild ? Slot : "button"
return (
<Comp
className={cn(buttonVariants({ variant, size, className }))}
ref={ref}
{...props}
/>
)
}
)
Button.displayName = "Button"
export { Button, buttonVariants }

76
components/ui/card.tsx Normal file

@ -0,0 +1,76 @@
import * as React from "react"
import { cn } from "@/lib/utils"
const Card = React.forwardRef<
HTMLDivElement,
React.HTMLAttributes<HTMLDivElement>
>(({ className, ...props }, ref) => (
<div
ref={ref}
className={cn(
"rounded-xl border bg-card text-card-foreground shadow",
className
)}
{...props}
/>
))
Card.displayName = "Card"
const CardHeader = React.forwardRef<
HTMLDivElement,
React.HTMLAttributes<HTMLDivElement>
>(({ className, ...props }, ref) => (
<div
ref={ref}
className={cn("flex flex-col space-y-1.5 p-6", className)}
{...props}
/>
))
CardHeader.displayName = "CardHeader"
const CardTitle = React.forwardRef<
HTMLDivElement,
React.HTMLAttributes<HTMLDivElement>
>(({ className, ...props }, ref) => (
<div
ref={ref}
className={cn("font-semibold leading-none tracking-tight", className)}
{...props}
/>
))
CardTitle.displayName = "CardTitle"
const CardDescription = React.forwardRef<
HTMLDivElement,
React.HTMLAttributes<HTMLDivElement>
>(({ className, ...props }, ref) => (
<div
ref={ref}
className={cn("text-sm text-muted-foreground", className)}
{...props}
/>
))
CardDescription.displayName = "CardDescription"
const CardContent = React.forwardRef<
HTMLDivElement,
React.HTMLAttributes<HTMLDivElement>
>(({ className, ...props }, ref) => (
<div ref={ref} className={cn("p-6 pt-0", className)} {...props} />
))
CardContent.displayName = "CardContent"
const CardFooter = React.forwardRef<
HTMLDivElement,
React.HTMLAttributes<HTMLDivElement>
>(({ className, ...props }, ref) => (
<div
ref={ref}
className={cn("flex items-center p-6 pt-0", className)}
{...props}
/>
))
CardFooter.displayName = "CardFooter"
export { Card, CardHeader, CardFooter, CardTitle, CardDescription, CardContent }

122
components/ui/dialog.tsx Normal file

@ -0,0 +1,122 @@
"use client"
import * as React from "react"
import * as DialogPrimitive from "@radix-ui/react-dialog"
import { X } from "lucide-react"
import { cn } from "@/lib/utils"
const Dialog = DialogPrimitive.Root
const DialogTrigger = DialogPrimitive.Trigger
const DialogPortal = DialogPrimitive.Portal
const DialogClose = DialogPrimitive.Close
const DialogOverlay = React.forwardRef<
React.ElementRef<typeof DialogPrimitive.Overlay>,
React.ComponentPropsWithoutRef<typeof DialogPrimitive.Overlay>
>(({ className, ...props }, ref) => (
<DialogPrimitive.Overlay
ref={ref}
className={cn(
"fixed inset-0 z-50 bg-black/80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",
className
)}
{...props}
/>
))
DialogOverlay.displayName = DialogPrimitive.Overlay.displayName
const DialogContent = React.forwardRef<
React.ElementRef<typeof DialogPrimitive.Content>,
React.ComponentPropsWithoutRef<typeof DialogPrimitive.Content>
>(({ className, children, ...props }, ref) => (
<DialogPortal>
<DialogOverlay />
<DialogPrimitive.Content
ref={ref}
className={cn(
"fixed left-[50%] top-[50%] z-50 grid w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 border bg-background p-6 shadow-lg duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] sm:rounded-lg",
className
)}
{...props}
>
{children}
<DialogPrimitive.Close className="absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none data-[state=open]:bg-accent data-[state=open]:text-muted-foreground">
<X className="h-4 w-4" />
<span className="sr-only">Close</span>
</DialogPrimitive.Close>
</DialogPrimitive.Content>
</DialogPortal>
))
DialogContent.displayName = DialogPrimitive.Content.displayName
const DialogHeader = ({
className,
...props
}: React.HTMLAttributes<HTMLDivElement>) => (
<div
className={cn(
"flex flex-col space-y-1.5 text-center sm:text-left",
className
)}
{...props}
/>
)
DialogHeader.displayName = "DialogHeader"
const DialogFooter = ({
className,
...props
}: React.HTMLAttributes<HTMLDivElement>) => (
<div
className={cn(
"flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2",
className
)}
{...props}
/>
)
DialogFooter.displayName = "DialogFooter"
const DialogTitle = React.forwardRef<
React.ElementRef<typeof DialogPrimitive.Title>,
React.ComponentPropsWithoutRef<typeof DialogPrimitive.Title>
>(({ className, ...props }, ref) => (
<DialogPrimitive.Title
ref={ref}
className={cn(
"text-lg font-semibold leading-none tracking-tight",
className
)}
{...props}
/>
))
DialogTitle.displayName = DialogPrimitive.Title.displayName
const DialogDescription = React.forwardRef<
React.ElementRef<typeof DialogPrimitive.Description>,
React.ComponentPropsWithoutRef<typeof DialogPrimitive.Description>
>(({ className, ...props }, ref) => (
<DialogPrimitive.Description
ref={ref}
className={cn("text-sm text-muted-foreground", className)}
{...props}
/>
))
DialogDescription.displayName = DialogPrimitive.Description.displayName
export {
Dialog,
DialogPortal,
DialogOverlay,
DialogTrigger,
DialogClose,
DialogContent,
DialogHeader,
DialogFooter,
DialogTitle,
DialogDescription,
}

@ -0,0 +1,201 @@
"use client"
import * as React from "react"
import * as DropdownMenuPrimitive from "@radix-ui/react-dropdown-menu"
import { Check, ChevronRight, Circle } from "lucide-react"
import { cn } from "@/lib/utils"
const DropdownMenu = DropdownMenuPrimitive.Root
const DropdownMenuTrigger = DropdownMenuPrimitive.Trigger
const DropdownMenuGroup = DropdownMenuPrimitive.Group
const DropdownMenuPortal = DropdownMenuPrimitive.Portal
const DropdownMenuSub = DropdownMenuPrimitive.Sub
const DropdownMenuRadioGroup = DropdownMenuPrimitive.RadioGroup
const DropdownMenuSubTrigger = React.forwardRef<
React.ElementRef<typeof DropdownMenuPrimitive.SubTrigger>,
React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.SubTrigger> & {
inset?: boolean
}
>(({ className, inset, children, ...props }, ref) => (
<DropdownMenuPrimitive.SubTrigger
ref={ref}
className={cn(
"flex cursor-default gap-2 select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none focus:bg-accent data-[state=open]:bg-accent [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0",
inset && "pl-8",
className
)}
{...props}
>
{children}
<ChevronRight className="ml-auto" />
</DropdownMenuPrimitive.SubTrigger>
))
DropdownMenuSubTrigger.displayName =
DropdownMenuPrimitive.SubTrigger.displayName
const DropdownMenuSubContent = React.forwardRef<
React.ElementRef<typeof DropdownMenuPrimitive.SubContent>,
React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.SubContent>
>(({ className, ...props }, ref) => (
<DropdownMenuPrimitive.SubContent
ref={ref}
className={cn(
"z-50 min-w-[8rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-lg data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",
className
)}
{...props}
/>
))
DropdownMenuSubContent.displayName =
DropdownMenuPrimitive.SubContent.displayName
const DropdownMenuContent = React.forwardRef<
React.ElementRef<typeof DropdownMenuPrimitive.Content>,
React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.Content>
>(({ className, sideOffset = 4, ...props }, ref) => (
<DropdownMenuPrimitive.Portal>
<DropdownMenuPrimitive.Content
ref={ref}
sideOffset={sideOffset}
className={cn(
"z-50 min-w-[8rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-md",
"data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",
className
)}
{...props}
/>
</DropdownMenuPrimitive.Portal>
))
DropdownMenuContent.displayName = DropdownMenuPrimitive.Content.displayName
const DropdownMenuItem = React.forwardRef<
React.ElementRef<typeof DropdownMenuPrimitive.Item>,
React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.Item> & {
inset?: boolean
}
>(({ className, inset, ...props }, ref) => (
<DropdownMenuPrimitive.Item
ref={ref}
className={cn(
"relative flex cursor-default select-none items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&>svg]:size-4 [&>svg]:shrink-0",
inset && "pl-8",
className
)}
{...props}
/>
))
DropdownMenuItem.displayName = DropdownMenuPrimitive.Item.displayName
const DropdownMenuCheckboxItem = React.forwardRef<
React.ElementRef<typeof DropdownMenuPrimitive.CheckboxItem>,
React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.CheckboxItem>
>(({ className, children, checked, ...props }, ref) => (
<DropdownMenuPrimitive.CheckboxItem
ref={ref}
className={cn(
"relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",
className
)}
checked={checked}
{...props}
>
<span className="absolute left-2 flex h-3.5 w-3.5 items-center justify-center">
<DropdownMenuPrimitive.ItemIndicator>
<Check className="h-4 w-4" />
</DropdownMenuPrimitive.ItemIndicator>
</span>
{children}
</DropdownMenuPrimitive.CheckboxItem>
))
DropdownMenuCheckboxItem.displayName =
DropdownMenuPrimitive.CheckboxItem.displayName
const DropdownMenuRadioItem = React.forwardRef<
React.ElementRef<typeof DropdownMenuPrimitive.RadioItem>,
React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.RadioItem>
>(({ className, children, ...props }, ref) => (
<DropdownMenuPrimitive.RadioItem
ref={ref}
className={cn(
"relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",
className
)}
{...props}
>
<span className="absolute left-2 flex h-3.5 w-3.5 items-center justify-center">
<DropdownMenuPrimitive.ItemIndicator>
<Circle className="h-2 w-2 fill-current" />
</DropdownMenuPrimitive.ItemIndicator>
</span>
{children}
</DropdownMenuPrimitive.RadioItem>
))
DropdownMenuRadioItem.displayName = DropdownMenuPrimitive.RadioItem.displayName
const DropdownMenuLabel = React.forwardRef<
React.ElementRef<typeof DropdownMenuPrimitive.Label>,
React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.Label> & {
inset?: boolean
}
>(({ className, inset, ...props }, ref) => (
<DropdownMenuPrimitive.Label
ref={ref}
className={cn(
"px-2 py-1.5 text-sm font-semibold",
inset && "pl-8",
className
)}
{...props}
/>
))
DropdownMenuLabel.displayName = DropdownMenuPrimitive.Label.displayName
const DropdownMenuSeparator = React.forwardRef<
React.ElementRef<typeof DropdownMenuPrimitive.Separator>,
React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.Separator>
>(({ className, ...props }, ref) => (
<DropdownMenuPrimitive.Separator
ref={ref}
className={cn("-mx-1 my-1 h-px bg-muted", className)}
{...props}
/>
))
DropdownMenuSeparator.displayName = DropdownMenuPrimitive.Separator.displayName
const DropdownMenuShortcut = ({
className,
...props
}: React.HTMLAttributes<HTMLSpanElement>) => {
return (
<span
className={cn("ml-auto text-xs tracking-widest opacity-60", className)}
{...props}
/>
)
}
DropdownMenuShortcut.displayName = "DropdownMenuShortcut"
export {
DropdownMenu,
DropdownMenuTrigger,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuCheckboxItem,
DropdownMenuRadioItem,
DropdownMenuLabel,
DropdownMenuSeparator,
DropdownMenuShortcut,
DropdownMenuGroup,
DropdownMenuPortal,
DropdownMenuSub,
DropdownMenuSubContent,
DropdownMenuSubTrigger,
DropdownMenuRadioGroup,
}

22
components/ui/input.tsx Normal file

@ -0,0 +1,22 @@
import * as React from "react"
import { cn } from "@/lib/utils"
const Input = React.forwardRef<HTMLInputElement, React.ComponentProps<"input">>(
({ className, type, ...props }, ref) => {
return (
<input
type={type}
className={cn(
"flex h-9 w-full rounded-md border border-input bg-transparent px-3 py-1 text-base shadow-sm transition-colors file:border-0 file:bg-transparent file:text-sm file:font-medium file:text-foreground placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50 md:text-sm",
className
)}
ref={ref}
{...props}
/>
)
}
)
Input.displayName = "Input"
export { Input }

26
components/ui/label.tsx Normal file

@ -0,0 +1,26 @@
"use client"
import * as React from "react"
import * as LabelPrimitive from "@radix-ui/react-label"
import { cva, type VariantProps } from "class-variance-authority"
import { cn } from "@/lib/utils"
const labelVariants = cva(
"text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"
)
const Label = React.forwardRef<
React.ElementRef<typeof LabelPrimitive.Root>,
React.ComponentPropsWithoutRef<typeof LabelPrimitive.Root> &
VariantProps<typeof labelVariants>
>(({ className, ...props }, ref) => (
<LabelPrimitive.Root
ref={ref}
className={cn(labelVariants(), className)}
{...props}
/>
))
Label.displayName = LabelPrimitive.Root.displayName
export { Label }

@ -0,0 +1,22 @@
import * as React from "react"
import { cn } from "@/lib/utils"
const Textarea = React.forwardRef<
HTMLTextAreaElement,
React.ComponentProps<"textarea">
>(({ className, ...props }, ref) => {
return (
<textarea
className={cn(
"flex min-h-[60px] w-full rounded-md border border-input bg-transparent px-3 py-2 text-base shadow-sm placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50 md:text-sm",
className
)}
ref={ref}
{...props}
/>
)
})
Textarea.displayName = "Textarea"
export { Textarea }

0
data/.gitkeep Normal file

5
lib/env.ts Normal file

@ -0,0 +1,5 @@
export default function env(key: string): string {
const envVar = process.env[key]
if (envVar === undefined) throw new Error(`Environment variable ${key} is not set.`)
return envVar
}

52
lib/file.ts Normal file

@ -0,0 +1,52 @@
import fs from 'fs';
import path from 'path';
export default function resolveFilePath(
urlPath: string[] | undefined,
basePath: string,
missingExtname: string[] = [],
missingFilename: string[] = []
): string | null {
// If urlPath is undefined, set it to an empty array
const segments = urlPath || []
// Construct the base file path
let filePath: string = path.join(basePath, ...segments)
let find:boolean = false
do {
if (fs.existsSync(filePath) && fs.statSync(filePath).isFile()) {
break
}
for (const extend of missingExtname) {
const newPath = filePath + extend;
if (fs.existsSync(newPath) && fs.statSync(newPath).isFile()) {
filePath = newPath
find = true
break
}
}
if (find) break
if (fs.existsSync(filePath) && fs.statSync(filePath).isDirectory()) {
for (const extend of missingFilename) {
const newPath = path.join(filePath, extend);
if (fs.existsSync(newPath) && fs.statSync(newPath).isFile()) {
filePath = newPath
find = true
break
}
}
}
if (find) break
return null
} while(0)
if (!filePath.startsWith(basePath)) {
return null
}
return filePath
}

91
lib/markcard/card.ts Normal file

@ -0,0 +1,91 @@
'use server'
import fs from 'fs/promises'
import path from 'path'
import env from '@/lib/env'
import resolveFilePath from '@/lib/file'
export interface MarkLinkI {
title: string
url: string
blank?: boolean
}
export interface MarkCardI {
id: string
userId?: string
title: string
shortDescription: string
detailedDescription?: string
links: MarkLinkI[]
publicUrl?: string
}
const rootPath = path.join(process.cwd(), env('CARD_FILE_PATH'))
// Waring
export async function getBasePath(userId?: string) {
return path.join(userId ? userId : '', 'markcard')
}
export async function getPath(userId?: string, fileUrl?: string[]) {
return resolveFilePath(fileUrl, path.join(rootPath, await getBasePath(userId)), ['.json'], ['index.json'])
}
async function writeInFile(cards: MarkCardI[], filePath: string) {
const fileDir = path.dirname(filePath)
try {
await fs.access(fileDir)
} catch {
await fs.mkdir(fileDir, { recursive: true })
}
fs.writeFile(filePath, JSON.stringify(cards, null, 2), 'utf8')
}
async function readFromFile(filePath: string): Promise<MarkCardI[]> {
await fs.access(filePath)
return JSON.parse(await fs.readFile(filePath, 'utf8'))
}
export async function getCards(filePath:string): Promise<MarkCardI[] | undefined> {
try {
return await readFromFile(filePath)
} catch {
return undefined
}
}
export async function addCard(card: Omit<MarkCardI, 'id'>, filePath: string): Promise<MarkCardI> {
const cards = await getCards(filePath)
if (cards && cards.length > 20) {
throw new Error('Maximum number of cards reached')
}
const newCard = { ...card, id: String(cards ? cards.length + 1 : 0) }
if (!cards) {
writeInFile([newCard], filePath)
} else {
cards.push(newCard)
writeInFile(cards, filePath)
}
return newCard
}
export async function updateCard(updatedCard: Partial<MarkCardI>,
cardId: string,
filePath: string): Promise<MarkCardI | null> {
const cards = await getCards(filePath)
if (!cards) {
return null
}
const index = cards.findIndex(card => card.id === cardId)
if (index === -1) return null
cards[index] = { ...cards[index], ...updatedCard }
writeInFile(cards, filePath)
return cards[index]
}
// export function deleteCard(id: string): boolean {
// const initialLength = cards.length
// cards = cards.filter(card => card.id !== id)
// return cards.length < initialLength
// }

6
lib/utils.ts Normal file

@ -0,0 +1,6 @@
import { clsx, type ClassValue } from "clsx"
import { twMerge } from "tailwind-merge"
export function cn(...inputs: ClassValue[]) {
return twMerge(clsx(inputs))
}

@ -1,7 +1,28 @@
import type { NextConfig } from "next";
const nextConfig: NextConfig = {
/* config options here */
};
async headers() {
/** https://nextjs.org/docs/app/building-your-application/deploying#streaming-and-suspense
* The Next.js App Router supports streaming responses when self-hosting.
*
* If you are using Nginx or a similar proxy, you will need to configure it
* to disable buffering to enable streaming.
*
* For example, you can disable buffering in Nginx by setting X-Accel-Buffering to no:
*/
return [
{
source: '/:path*{/}?',
headers: [
{
key: 'X-Accel-Buffering',
value: 'no',
},
],
},
]
},
}
export default nextConfig;

1618
package-lock.json generated

File diff suppressed because it is too large Load Diff

@ -9,19 +9,28 @@
"lint": "next lint"
},
"dependencies": {
"@radix-ui/react-dialog": "^1.1.3",
"@radix-ui/react-dropdown-menu": "^2.1.3",
"@radix-ui/react-label": "^2.1.1",
"@radix-ui/react-slot": "^1.1.1",
"class-variance-authority": "^0.7.1",
"clsx": "^2.1.1",
"lucide-react": "^0.462.0",
"next": "^15.1.1",
"react": "^19.0.0",
"react-dom": "^19.0.0",
"next": "15.1.0"
"tailwind-merge": "^2.5.5",
"tailwindcss-animate": "^1.0.7"
},
"devDependencies": {
"typescript": "^5",
"@eslint/eslintrc": "^3",
"@types/node": "^20",
"@types/react": "^19",
"@types/react-dom": "^19",
"eslint": "^9",
"eslint-config-next": "^15.1.1",
"postcss": "^8",
"tailwindcss": "^3.4.1",
"eslint": "^9",
"eslint-config-next": "15.1.0",
"@eslint/eslintrc": "^3"
"typescript": "^5"
}
}

BIN
public/old_favicon.ico Normal file

Binary file not shown.

After

(image error) Size: 25 KiB

@ -1,18 +1,62 @@
import type { Config } from "tailwindcss";
export default {
content: [
darkMode: ["class"],
content: [
"./pages/**/*.{js,ts,jsx,tsx,mdx}",
"./components/**/*.{js,ts,jsx,tsx,mdx}",
"./app/**/*.{js,ts,jsx,tsx,mdx}",
],
theme: {
extend: {
colors: {
background: "var(--background)",
foreground: "var(--foreground)",
},
},
extend: {
colors: {
background: 'hsl(var(--background))',
foreground: 'hsl(var(--foreground))',
card: {
DEFAULT: 'hsl(var(--card))',
foreground: 'hsl(var(--card-foreground))'
},
popover: {
DEFAULT: 'hsl(var(--popover))',
foreground: 'hsl(var(--popover-foreground))'
},
primary: {
DEFAULT: 'hsl(var(--primary))',
foreground: 'hsl(var(--primary-foreground))'
},
secondary: {
DEFAULT: 'hsl(var(--secondary))',
foreground: 'hsl(var(--secondary-foreground))'
},
muted: {
DEFAULT: 'hsl(var(--muted))',
foreground: 'hsl(var(--muted-foreground))'
},
accent: {
DEFAULT: 'hsl(var(--accent))',
foreground: 'hsl(var(--accent-foreground))'
},
destructive: {
DEFAULT: 'hsl(var(--destructive))',
foreground: 'hsl(var(--destructive-foreground))'
},
border: 'hsl(var(--border))',
input: 'hsl(var(--input))',
ring: 'hsl(var(--ring))',
chart: {
'1': 'hsl(var(--chart-1))',
'2': 'hsl(var(--chart-2))',
'3': 'hsl(var(--chart-3))',
'4': 'hsl(var(--chart-4))',
'5': 'hsl(var(--chart-5))'
}
},
borderRadius: {
lg: 'var(--radius)',
md: 'calc(var(--radius) - 2px)',
sm: 'calc(var(--radius) - 4px)'
}
}
},
plugins: [],
plugins: [require("tailwindcss-animate")],
} satisfies Config;