Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a98960c0be | ||
|
|
377e06017d | ||
|
|
d8c9ce497a | ||
|
|
f5800e5e86 |
@@ -0,0 +1,6 @@
|
||||
node_modules
|
||||
.next
|
||||
.git
|
||||
.turbo
|
||||
*.log
|
||||
.DS_Store
|
||||
+41
@@ -0,0 +1,41 @@
|
||||
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
|
||||
|
||||
# dependencies
|
||||
/node_modules
|
||||
/.pnp
|
||||
.pnp.*
|
||||
.yarn/*
|
||||
!.yarn/patches
|
||||
!.yarn/plugins
|
||||
!.yarn/releases
|
||||
!.yarn/versions
|
||||
|
||||
# testing
|
||||
/coverage
|
||||
|
||||
# next.js
|
||||
/.next/
|
||||
/out/
|
||||
|
||||
# production
|
||||
/build
|
||||
|
||||
# misc
|
||||
.DS_Store
|
||||
*.pem
|
||||
|
||||
# debug
|
||||
npm-debug.log*
|
||||
yarn-debug.log*
|
||||
yarn-error.log*
|
||||
.pnpm-debug.log*
|
||||
|
||||
# env files (can opt-in for committing if needed)
|
||||
.env*
|
||||
|
||||
# vercel
|
||||
.vercel
|
||||
|
||||
# typescript
|
||||
*.tsbuildinfo
|
||||
next-env.d.ts
|
||||
@@ -0,0 +1,5 @@
|
||||
<!-- BEGIN:nextjs-agent-rules -->
|
||||
# This is NOT the Next.js you know
|
||||
|
||||
This version has breaking changes — APIs, conventions, and file structure may all differ from your training data. Read the relevant guide in `node_modules/next/dist/docs/` before writing any code. Heed deprecation notices.
|
||||
<!-- END:nextjs-agent-rules -->
|
||||
+49
@@ -0,0 +1,49 @@
|
||||
# Use Node 24 as the base image
|
||||
FROM node:24-trixie AS base
|
||||
ENV PNPM_HOME="/pnpm"
|
||||
ENV PATH="$PNPM_HOME:$PATH"
|
||||
RUN corepack enable
|
||||
|
||||
# 1. Install dependencies only when needed
|
||||
FROM base AS deps
|
||||
WORKDIR /app
|
||||
COPY package.json pnpm-lock.yaml ./
|
||||
RUN pnpm install --frozen-lockfile
|
||||
|
||||
# 2. Rebuild the source code only when needed
|
||||
FROM base AS builder
|
||||
WORKDIR /app
|
||||
COPY --from=deps /app/node_modules ./node_modules
|
||||
COPY . .
|
||||
# Disable telemetry for build
|
||||
ENV NEXT_TELEMETRY_DISABLED=1
|
||||
RUN pnpm run build
|
||||
|
||||
# 3. Production image, copy all the files and run next
|
||||
FROM base AS runner
|
||||
WORKDIR /app
|
||||
|
||||
ENV NODE_ENV=production
|
||||
ENV NEXT_TELEMETRY_DISABLED=1
|
||||
|
||||
RUN addgroup --system --gid 1001 nodejs
|
||||
RUN adduser --system --uid 1001 nextjs
|
||||
|
||||
# Set the correct permission for prerender cache
|
||||
RUN mkdir .next
|
||||
RUN chown nextjs:nodejs .next
|
||||
|
||||
# Automatically leverage output traces to reduce image size
|
||||
# https://nextjs.org/docs/advanced-features/output-file-tracing
|
||||
COPY --from=builder --chown=nextjs:nodejs /app/public ./public
|
||||
COPY --from=builder --chown=nextjs:nodejs /app/.next/standalone ./
|
||||
COPY --from=builder --chown=nextjs:nodejs /app/.next/static ./.next/static
|
||||
|
||||
USER nextjs
|
||||
|
||||
EXPOSE 3000
|
||||
ENV PORT=3000
|
||||
# set hostname to localhost
|
||||
ENV HOSTNAME="0.0.0.0"
|
||||
|
||||
CMD ["node", "server.js"]
|
||||
@@ -0,0 +1,36 @@
|
||||
This is a [Next.js](https://nextjs.org) project bootstrapped with [`create-next-app`](https://nextjs.org/docs/app/api-reference/cli/create-next-app).
|
||||
|
||||
## Getting Started
|
||||
|
||||
First, run the development server:
|
||||
|
||||
```bash
|
||||
npm run dev
|
||||
# or
|
||||
yarn dev
|
||||
# or
|
||||
pnpm dev
|
||||
# or
|
||||
bun dev
|
||||
```
|
||||
|
||||
Open [http://localhost:3000](http://localhost:3000) with your browser to see the result.
|
||||
|
||||
You can start editing the page by modifying `app/page.tsx`. The page auto-updates as you edit the file.
|
||||
|
||||
This project uses [`next/font`](https://nextjs.org/docs/app/building-your-application/optimizing/fonts) to automatically optimize and load [Geist](https://vercel.com/font), a new font family for Vercel.
|
||||
|
||||
## Learn More
|
||||
|
||||
To learn more about Next.js, take a look at the following resources:
|
||||
|
||||
- [Next.js Documentation](https://nextjs.org/docs) - learn about Next.js features and API.
|
||||
- [Learn Next.js](https://nextjs.org/learn) - an interactive Next.js tutorial.
|
||||
|
||||
You can check out [the Next.js GitHub repository](https://github.com/vercel/next.js) - your feedback and contributions are welcome!
|
||||
|
||||
## Deploy on Vercel
|
||||
|
||||
The easiest way to deploy your Next.js app is to use the [Vercel Platform](https://vercel.com/new?utm_medium=default-template&filter=next.js&utm_source=create-next-app&utm_campaign=create-next-app-readme) from the creators of Next.js.
|
||||
|
||||
Check out our [Next.js deployment documentation](https://nextjs.org/docs/app/building-your-application/deploying) for more details.
|
||||
@@ -0,0 +1,16 @@
|
||||
services:
|
||||
web:
|
||||
build:
|
||||
context: .
|
||||
dockerfile: Dockerfile
|
||||
container_name: ${POSTCARD_WEB_CONTAINER_NAME:-postcard-web}
|
||||
ports:
|
||||
- "${POSTCARD_WEB_HOST_PORT:-3000}:3000"
|
||||
environment:
|
||||
NODE_ENV: production
|
||||
PORT: 3000
|
||||
HOSTNAME: 0.0.0.0
|
||||
restart: unless-stopped
|
||||
# Optional: Podman specific security options
|
||||
# security_opt:
|
||||
# - no-new-privileges:true
|
||||
@@ -0,0 +1,18 @@
|
||||
import { defineConfig, globalIgnores } from "eslint/config";
|
||||
import nextVitals from "eslint-config-next/core-web-vitals";
|
||||
import nextTs from "eslint-config-next/typescript";
|
||||
|
||||
const eslintConfig = defineConfig([
|
||||
...nextVitals,
|
||||
...nextTs,
|
||||
// Override default ignores of eslint-config-next.
|
||||
globalIgnores([
|
||||
// Default ignores of eslint-config-next:
|
||||
".next/**",
|
||||
"out/**",
|
||||
"build/**",
|
||||
"next-env.d.ts",
|
||||
]),
|
||||
]);
|
||||
|
||||
export default eslintConfig;
|
||||
@@ -0,0 +1,11 @@
|
||||
import path from "node:path";
|
||||
import type { NextConfig } from "next";
|
||||
|
||||
const nextConfig: NextConfig = {
|
||||
output: "standalone",
|
||||
turbopack: {
|
||||
root: path.join(__dirname),
|
||||
},
|
||||
};
|
||||
|
||||
export default nextConfig;
|
||||
@@ -0,0 +1,39 @@
|
||||
{
|
||||
"name": "postcard-web",
|
||||
"version": "0.1.0",
|
||||
"private": true,
|
||||
"scripts": {
|
||||
"dev": "next dev --turbopack",
|
||||
"build": "next build --turbopack",
|
||||
"start": "next start",
|
||||
"lint": "eslint"
|
||||
},
|
||||
"dependencies": {
|
||||
"clsx": "^2.1.1",
|
||||
"dexie": "^4.3.0",
|
||||
"dexie-react-hooks": "^4.2.0",
|
||||
"lucide-react": "^0.577.0",
|
||||
"next": "16.2.1",
|
||||
"react": "19.2.4",
|
||||
"react-dom": "19.2.4",
|
||||
"tailwind-merge": "^3.5.0",
|
||||
"zustand": "^5.0.12"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@tailwindcss/postcss": "^4",
|
||||
"@types/node": "^20",
|
||||
"@types/react": "^19",
|
||||
"@types/react-dom": "^19",
|
||||
"eslint": "^9",
|
||||
"eslint-config-next": "16.2.1",
|
||||
"tailwindcss": "^4",
|
||||
"turbo": "^2.8.20",
|
||||
"typescript": "^5"
|
||||
},
|
||||
"pnpm": {
|
||||
"onlyBuiltDependencies": [
|
||||
"sharp",
|
||||
"unrs-resolver"
|
||||
]
|
||||
}
|
||||
}
|
||||
Generated
+4217
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,3 @@
|
||||
allowBuilds:
|
||||
sharp: true
|
||||
unrs-resolver: true
|
||||
@@ -0,0 +1,7 @@
|
||||
const config = {
|
||||
plugins: {
|
||||
"@tailwindcss/postcss": {},
|
||||
},
|
||||
};
|
||||
|
||||
export default config;
|
||||
@@ -0,0 +1 @@
|
||||
<svg fill="none" viewBox="0 0 16 16" xmlns="http://www.w3.org/2000/svg"><path d="M14.5 13.5V5.41a1 1 0 0 0-.3-.7L9.8.29A1 1 0 0 0 9.08 0H1.5v13.5A2.5 2.5 0 0 0 4 16h8a2.5 2.5 0 0 0 2.5-2.5m-1.5 0v-7H8v-5H3v12a1 1 0 0 0 1 1h8a1 1 0 0 0 1-1M9.5 5V2.12L12.38 5zM5.13 5h-.62v1.25h2.12V5zm-.62 3h7.12v1.25H4.5zm.62 3h-.62v1.25h7.12V11z" clip-rule="evenodd" fill="#666" fill-rule="evenodd"/></svg>
|
||||
|
After Width: | Height: | Size: 391 B |
@@ -0,0 +1 @@
|
||||
<svg fill="none" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16"><g clip-path="url(#a)"><path fill-rule="evenodd" clip-rule="evenodd" d="M10.27 14.1a6.5 6.5 0 0 0 3.67-3.45q-1.24.21-2.7.34-.31 1.83-.97 3.1M8 16A8 8 0 1 0 8 0a8 8 0 0 0 0 16m.48-1.52a7 7 0 0 1-.96 0H7.5a4 4 0 0 1-.84-1.32q-.38-.89-.63-2.08a40 40 0 0 0 3.92 0q-.25 1.2-.63 2.08a4 4 0 0 1-.84 1.31zm2.94-4.76q1.66-.15 2.95-.43a7 7 0 0 0 0-2.58q-1.3-.27-2.95-.43a18 18 0 0 1 0 3.44m-1.27-3.54a17 17 0 0 1 0 3.64 39 39 0 0 1-4.3 0 17 17 0 0 1 0-3.64 39 39 0 0 1 4.3 0m1.1-1.17q1.45.13 2.69.34a6.5 6.5 0 0 0-3.67-3.44q.65 1.26.98 3.1M8.48 1.5l.01.02q.41.37.84 1.31.38.89.63 2.08a40 40 0 0 0-3.92 0q.25-1.2.63-2.08a4 4 0 0 1 .85-1.32 7 7 0 0 1 .96 0m-2.75.4a6.5 6.5 0 0 0-3.67 3.44 29 29 0 0 1 2.7-.34q.31-1.83.97-3.1M4.58 6.28q-1.66.16-2.95.43a7 7 0 0 0 0 2.58q1.3.27 2.95.43a18 18 0 0 1 0-3.44m.17 4.71q-1.45-.12-2.69-.34a6.5 6.5 0 0 0 3.67 3.44q-.65-1.27-.98-3.1" fill="#666"/></g><defs><clipPath id="a"><path fill="#fff" d="M0 0h16v16H0z"/></clipPath></defs></svg>
|
||||
|
After Width: | Height: | Size: 1.0 KiB |
@@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 394 80"><path fill="#000" d="M262 0h68.5v12.7h-27.2v66.6h-13.6V12.7H262V0ZM149 0v12.7H94v20.4h44.3v12.6H94v21h55v12.6H80.5V0h68.7zm34.3 0h-17.8l63.8 79.4h17.9l-32-39.7 32-39.6h-17.9l-23 28.6-23-28.6zm18.3 56.7-9-11-27.1 33.7h17.8l18.3-22.7z"/><path fill="#000" d="M81 79.3 17 0H0v79.3h13.6V17l50.2 62.3H81Zm252.6-.4c-1 0-1.8-.4-2.5-1s-1.1-1.6-1.1-2.6.3-1.8 1-2.5 1.6-1 2.6-1 1.8.3 2.5 1a3.4 3.4 0 0 1 .6 4.3 3.7 3.7 0 0 1-3 1.8zm23.2-33.5h6v23.3c0 2.1-.4 4-1.3 5.5a9.1 9.1 0 0 1-3.8 3.5c-1.6.8-3.5 1.3-5.7 1.3-2 0-3.7-.4-5.3-1s-2.8-1.8-3.7-3.2c-.9-1.3-1.4-3-1.4-5h6c.1.8.3 1.6.7 2.2s1 1.2 1.6 1.5c.7.4 1.5.5 2.4.5 1 0 1.8-.2 2.4-.6a4 4 0 0 0 1.6-1.8c.3-.8.5-1.8.5-3V45.5zm30.9 9.1a4.4 4.4 0 0 0-2-3.3 7.5 7.5 0 0 0-4.3-1.1c-1.3 0-2.4.2-3.3.5-.9.4-1.6 1-2 1.6a3.5 3.5 0 0 0-.3 4c.3.5.7.9 1.3 1.2l1.8 1 2 .5 3.2.8c1.3.3 2.5.7 3.7 1.2a13 13 0 0 1 3.2 1.8 8.1 8.1 0 0 1 3 6.5c0 2-.5 3.7-1.5 5.1a10 10 0 0 1-4.4 3.5c-1.8.8-4.1 1.2-6.8 1.2-2.6 0-4.9-.4-6.8-1.2-2-.8-3.4-2-4.5-3.5a10 10 0 0 1-1.7-5.6h6a5 5 0 0 0 3.5 4.6c1 .4 2.2.6 3.4.6 1.3 0 2.5-.2 3.5-.6 1-.4 1.8-1 2.4-1.7a4 4 0 0 0 .8-2.4c0-.9-.2-1.6-.7-2.2a11 11 0 0 0-2.1-1.4l-3.2-1-3.8-1c-2.8-.7-5-1.7-6.6-3.2a7.2 7.2 0 0 1-2.4-5.7 8 8 0 0 1 1.7-5 10 10 0 0 1 4.3-3.5c2-.8 4-1.2 6.4-1.2 2.3 0 4.4.4 6.2 1.2 1.8.8 3.2 2 4.3 3.4 1 1.4 1.5 3 1.5 5h-5.8z"/></svg>
|
||||
|
After Width: | Height: | Size: 1.3 KiB |
@@ -0,0 +1 @@
|
||||
<svg fill="none" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1155 1000"><path d="m577.3 0 577.4 1000H0z" fill="#fff"/></svg>
|
||||
|
After Width: | Height: | Size: 128 B |
@@ -0,0 +1 @@
|
||||
<svg fill="none" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16"><path fill-rule="evenodd" clip-rule="evenodd" d="M1.5 2.5h13v10a1 1 0 0 1-1 1h-11a1 1 0 0 1-1-1zM0 1h16v11.5a2.5 2.5 0 0 1-2.5 2.5h-11A2.5 2.5 0 0 1 0 12.5zm3.75 4.5a.75.75 0 1 0 0-1.5.75.75 0 0 0 0 1.5M7 4.75a.75.75 0 1 1-1.5 0 .75.75 0 0 1 1.5 0m1.75.75a.75.75 0 1 0 0-1.5.75.75 0 0 0 0 1.5" fill="#666"/></svg>
|
||||
|
After Width: | Height: | Size: 385 B |
@@ -0,0 +1,20 @@
|
||||
import { MessageThread } from "@/components/chat/MessageThread";
|
||||
import { MessageInput } from "@/components/chat/MessageInput";
|
||||
import { TypingIndicator } from "@/components/chat/TypingIndicator";
|
||||
|
||||
export default async function ChatDetailPage({ params }: { params: Promise<{ id: string }> }) {
|
||||
const resolvedParams = await params;
|
||||
const { id } = resolvedParams;
|
||||
|
||||
return (
|
||||
<div className="flex h-full flex-col bg-white">
|
||||
<div className="flex items-center border-b border-gray-200 px-6 py-4 shadow-sm z-10 bg-white">
|
||||
<h2 className="text-lg font-semibold text-gray-900">Chat Session</h2>
|
||||
</div>
|
||||
|
||||
<MessageThread conversationId={id} />
|
||||
<TypingIndicator conversationId={id} />
|
||||
<MessageInput conversationId={id} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
export default function ChatPage() {
|
||||
return (
|
||||
<div className="flex h-full items-center justify-center text-gray-500">
|
||||
Select a conversation to start chatting
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
import { ConversationList } from "@/components/chat/ConversationList";
|
||||
import { logout } from "@/lib/auth";
|
||||
import { LogOut } from "lucide-react";
|
||||
|
||||
export default function AppLayout({
|
||||
children,
|
||||
}: Readonly<{
|
||||
children: React.ReactNode;
|
||||
}>) {
|
||||
return (
|
||||
<div className="flex h-screen overflow-hidden bg-white text-gray-900">
|
||||
<div className="flex w-80 flex-col border-r border-gray-200">
|
||||
<div className="flex-1 overflow-y-auto">
|
||||
<ConversationList />
|
||||
</div>
|
||||
<div className="border-t border-gray-200 p-4">
|
||||
<form action={logout}>
|
||||
<button
|
||||
type="submit"
|
||||
className="flex w-full items-center justify-center gap-2 rounded-md bg-gray-50 px-3 py-2 text-sm font-medium text-gray-700 hover:bg-gray-100 focus:outline-none focus:ring-2 focus:ring-blue-500"
|
||||
>
|
||||
<LogOut className="h-4 w-4" />
|
||||
Sign out
|
||||
</button>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex min-w-0 flex-1 flex-col bg-gray-50">
|
||||
{children}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 25 KiB |
@@ -0,0 +1,28 @@
|
||||
@import "tailwindcss";
|
||||
|
||||
:root {
|
||||
--background: #ffffff;
|
||||
--foreground: #171717;
|
||||
--font-sans: "Segoe UI", "Helvetica Neue", Helvetica, Arial, sans-serif;
|
||||
--font-mono: "SFMono-Regular", "Consolas", "Liberation Mono", monospace;
|
||||
}
|
||||
|
||||
@theme inline {
|
||||
--color-background: var(--background);
|
||||
--color-foreground: var(--foreground);
|
||||
--font-sans: var(--font-sans);
|
||||
--font-mono: var(--font-mono);
|
||||
}
|
||||
|
||||
@media (prefers-color-scheme: dark) {
|
||||
:root {
|
||||
--background: #0a0a0a;
|
||||
--foreground: #ededed;
|
||||
}
|
||||
}
|
||||
|
||||
body {
|
||||
background: var(--background);
|
||||
color: var(--foreground);
|
||||
font-family: var(--font-sans);
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
import type { Metadata } from "next";
|
||||
import "./globals.css";
|
||||
|
||||
export const metadata: Metadata = {
|
||||
title: "Create Next App",
|
||||
description: "Generated by create next app",
|
||||
};
|
||||
|
||||
export default function RootLayout({
|
||||
children,
|
||||
}: Readonly<{
|
||||
children: React.ReactNode;
|
||||
}>) {
|
||||
return (
|
||||
<html lang="en" className="h-full antialiased">
|
||||
<body className="min-h-full flex flex-col">{children}</body>
|
||||
</html>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
import { cookies } from "next/headers";
|
||||
import { redirect } from "next/navigation";
|
||||
import { LoginForm } from "@/components/auth/LoginForm";
|
||||
|
||||
export default async function HomePage() {
|
||||
const cookieStore = await cookies();
|
||||
const authToken = cookieStore.get("auth_token");
|
||||
|
||||
if (authToken) {
|
||||
redirect("/c");
|
||||
}
|
||||
|
||||
return <LoginForm />;
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
"use client";
|
||||
|
||||
import { useActionState } from "react";
|
||||
import { register } from "@/lib/auth";
|
||||
import Link from "next/link";
|
||||
import { Loader2 } from "lucide-react";
|
||||
|
||||
export default function RegisterPage() {
|
||||
const [state, formAction, isPending] = useActionState(register, null);
|
||||
|
||||
return (
|
||||
<div className="flex min-h-screen items-center justify-center bg-gray-50 p-4">
|
||||
<div className="w-full max-w-md space-y-8 rounded-xl bg-white p-8 shadow-sm ring-1 ring-gray-200">
|
||||
<div className="text-center">
|
||||
<h2 className="text-3xl font-bold tracking-tight text-gray-900">Create an account</h2>
|
||||
</div>
|
||||
<form action={formAction} className="mt-8 space-y-6">
|
||||
<div className="space-y-4">
|
||||
<div>
|
||||
<label htmlFor="username" className="sr-only">Username</label>
|
||||
<input
|
||||
id="username"
|
||||
name="username"
|
||||
type="text"
|
||||
required
|
||||
className="relative block w-full rounded-md border-0 py-1.5 px-3 text-gray-900 ring-1 ring-inset ring-gray-300 placeholder:text-gray-400 focus:z-10 focus:ring-2 focus:ring-inset focus:ring-blue-600 sm:text-sm sm:leading-6"
|
||||
placeholder="Username"
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<label htmlFor="displayName" className="sr-only">Display Name</label>
|
||||
<input
|
||||
id="displayName"
|
||||
name="displayName"
|
||||
type="text"
|
||||
required
|
||||
className="relative block w-full rounded-md border-0 py-1.5 px-3 text-gray-900 ring-1 ring-inset ring-gray-300 placeholder:text-gray-400 focus:z-10 focus:ring-2 focus:ring-inset focus:ring-blue-600 sm:text-sm sm:leading-6"
|
||||
placeholder="Display Name (e.g. John Doe)"
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<label htmlFor="password" className="sr-only">Password</label>
|
||||
<input
|
||||
id="password"
|
||||
name="password"
|
||||
type="password"
|
||||
required
|
||||
className="relative block w-full rounded-md border-0 py-1.5 px-3 text-gray-900 ring-1 ring-inset ring-gray-300 placeholder:text-gray-400 focus:z-10 focus:ring-2 focus:ring-inset focus:ring-blue-600 sm:text-sm sm:leading-6"
|
||||
placeholder="Password"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{state?.error && (
|
||||
<div className="text-sm text-red-500 text-center bg-red-50 p-2 rounded-md ring-1 ring-red-200">
|
||||
{state.error}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div>
|
||||
<button
|
||||
type="submit"
|
||||
disabled={isPending}
|
||||
className="group relative flex w-full justify-center rounded-md bg-blue-600 px-3 py-2 text-sm font-semibold text-white hover:bg-blue-500 focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-blue-600 disabled:opacity-70 disabled:cursor-not-allowed transition-all"
|
||||
>
|
||||
{isPending ? <Loader2 className="animate-spin h-5 w-5" /> : "Sign up"}
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
<div className="text-center text-sm">
|
||||
<span className="text-gray-500">Already have an account? </span>
|
||||
<Link href="/" className="font-semibold text-blue-600 hover:text-blue-500">
|
||||
Sign in
|
||||
</Link>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
"use client";
|
||||
|
||||
import Link from "next/link";
|
||||
import { useActionState } from "react";
|
||||
import { Loader2 } from "lucide-react";
|
||||
import { login } from "@/lib/auth";
|
||||
|
||||
export function LoginForm() {
|
||||
const [state, formAction, isPending] = useActionState(login, null);
|
||||
|
||||
return (
|
||||
<div className="flex min-h-screen items-center justify-center bg-gray-50 p-4">
|
||||
<div className="w-full max-w-md space-y-8 rounded-xl bg-white p-8 shadow-sm ring-1 ring-gray-200">
|
||||
<div className="text-center">
|
||||
<h2 className="text-3xl font-bold tracking-tight text-gray-900">Sign in to Postcard</h2>
|
||||
</div>
|
||||
<form action={formAction} className="mt-8 space-y-6">
|
||||
<div className="space-y-4">
|
||||
<div>
|
||||
<label htmlFor="username" className="sr-only">
|
||||
Username
|
||||
</label>
|
||||
<input
|
||||
id="username"
|
||||
name="username"
|
||||
type="text"
|
||||
required
|
||||
className="relative block w-full rounded-md border-0 px-3 py-1.5 text-gray-900 ring-1 ring-inset ring-gray-300 placeholder:text-gray-400 focus:z-10 focus:ring-2 focus:ring-inset focus:ring-blue-600 sm:text-sm sm:leading-6"
|
||||
placeholder="Username"
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<label htmlFor="password" className="sr-only">
|
||||
Password
|
||||
</label>
|
||||
<input
|
||||
id="password"
|
||||
name="password"
|
||||
type="password"
|
||||
required
|
||||
className="relative block w-full rounded-md border-0 px-3 py-1.5 text-gray-900 ring-1 ring-inset ring-gray-300 placeholder:text-gray-400 focus:z-10 focus:ring-2 focus:ring-inset focus:ring-blue-600 sm:text-sm sm:leading-6"
|
||||
placeholder="Password"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{state?.error && (
|
||||
<div className="rounded-md bg-red-50 p-2 text-center text-sm text-red-500 ring-1 ring-red-200">
|
||||
{state.error}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div>
|
||||
<button
|
||||
type="submit"
|
||||
disabled={isPending}
|
||||
className="group relative flex w-full justify-center rounded-md bg-blue-600 px-3 py-2 text-sm font-semibold text-white transition-all hover:bg-blue-500 focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-blue-600 disabled:cursor-not-allowed disabled:opacity-70"
|
||||
>
|
||||
{isPending ? <Loader2 className="h-5 w-5 animate-spin" /> : "Sign in"}
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
<div className="text-center text-sm">
|
||||
<span className="text-gray-500">Don't have an account? </span>
|
||||
<Link href="/register" className="font-semibold text-blue-600 hover:text-blue-500">
|
||||
Sign up
|
||||
</Link>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,105 @@
|
||||
"use client";
|
||||
|
||||
import { useChatStore } from "@/lib/store/chat";
|
||||
import clsx from "clsx";
|
||||
import Link from "next/link";
|
||||
import { useParams } from "next/navigation";
|
||||
import { useEffect } from "react";
|
||||
import { wsManager } from "@/lib/ws";
|
||||
|
||||
function formatTime(timestamp?: number) {
|
||||
if (!timestamp) return "";
|
||||
const date = new Date(timestamp);
|
||||
return new Intl.DateTimeFormat('default', { hour: 'numeric', minute: 'numeric' }).format(date);
|
||||
}
|
||||
|
||||
export function ConversationList() {
|
||||
const conversations = useChatStore((state) => Array.from(state.conversations.values()));
|
||||
const connectionStatus = useChatStore((state) => state.connection.status);
|
||||
const hydrateFromDb = useChatStore((state) => state.hydrateFromDb);
|
||||
const params = useParams();
|
||||
const currentConversationId = params.id as string | undefined;
|
||||
|
||||
// Hydrate store from Dexie and connect WebSocket on mount
|
||||
useEffect(() => {
|
||||
hydrateFromDb().then(() => {
|
||||
wsManager.connect();
|
||||
});
|
||||
|
||||
return () => {
|
||||
// Optional: disconnect on unmount if appropriate for the app lifecycle
|
||||
};
|
||||
}, [hydrateFromDb]);
|
||||
|
||||
// Sort by most recent
|
||||
const sorted = [...conversations].sort((a, b) => {
|
||||
return (b.lastMessageTimestamp || 0) - (a.lastMessageTimestamp || 0);
|
||||
});
|
||||
|
||||
return (
|
||||
<div className="flex h-full flex-col bg-white">
|
||||
<div className="flex items-center justify-between border-b border-gray-200 px-4 py-4">
|
||||
<h2 className="text-lg font-semibold text-gray-900">Chats</h2>
|
||||
<span className={clsx(
|
||||
"h-2 w-2 rounded-full",
|
||||
connectionStatus === "connected" ? "bg-green-500" :
|
||||
connectionStatus === "connecting" || connectionStatus === "syncing" ? "bg-yellow-500" :
|
||||
"bg-red-500"
|
||||
)} title={`Status: ${connectionStatus}`} />
|
||||
</div>
|
||||
<div className="flex-1 overflow-y-auto">
|
||||
{sorted.length === 0 ? (
|
||||
<div className="p-4 text-sm text-gray-500 text-center">
|
||||
No conversations yet.
|
||||
</div>
|
||||
) : (
|
||||
<ul className="divide-y divide-gray-100">
|
||||
{sorted.map((convo) => (
|
||||
<li key={convo.id}>
|
||||
<Link
|
||||
href={`/c/${convo.id}`}
|
||||
className={clsx(
|
||||
"block px-4 py-4 hover:bg-gray-50",
|
||||
currentConversationId === convo.id && "bg-blue-50"
|
||||
)}
|
||||
>
|
||||
<div className="flex items-center space-x-3">
|
||||
<div className="flex-shrink-0">
|
||||
{convo.participantAvatar ? (
|
||||
<img className="h-10 w-10 rounded-full object-cover" src={convo.participantAvatar} alt="" />
|
||||
) : (
|
||||
<div className="h-10 w-10 rounded-full bg-gray-300 flex items-center justify-center text-gray-600 font-bold">
|
||||
{convo.participantName.charAt(0).toUpperCase()}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="flex items-center justify-between">
|
||||
<p className="truncate text-sm font-medium text-gray-900">
|
||||
{convo.participantName}
|
||||
</p>
|
||||
<p className="text-xs text-gray-500">
|
||||
{formatTime(convo.lastMessageTimestamp)}
|
||||
</p>
|
||||
</div>
|
||||
<div className="flex items-center justify-between">
|
||||
<p className="truncate text-sm text-gray-500">
|
||||
{convo.lastMessagePreview || "No messages yet"}
|
||||
</p>
|
||||
{convo.unreadCount > 0 && (
|
||||
<span className="inline-flex items-center justify-center rounded-full bg-blue-600 px-2 py-0.5 text-xs font-medium text-white">
|
||||
{convo.unreadCount}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</Link>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,109 @@
|
||||
"use client";
|
||||
|
||||
import { useState, useRef } from "react";
|
||||
import { useChatStore } from "@/lib/store/chat";
|
||||
import { wsManager } from "@/lib/ws";
|
||||
import { Send, Mic } from "lucide-react";
|
||||
import { MediaUploader } from "../media/MediaUploader";
|
||||
import { StickerPicker } from "../media/StickerPicker";
|
||||
|
||||
export function MessageInput({ conversationId }: { conversationId: string }) {
|
||||
const [text, setText] = useState("");
|
||||
const typingRef = useRef<NodeJS.Timeout | null>(null);
|
||||
|
||||
const handleSend = (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
if (!text.trim()) return;
|
||||
|
||||
const messageId = crypto.randomUUID();
|
||||
const payload = {
|
||||
id: messageId,
|
||||
conversationId,
|
||||
senderId: "me", // Temporary stub for current user
|
||||
text: text.trim(),
|
||||
timestamp: Date.now(),
|
||||
sequence: Date.now(), // Optimistic sequence
|
||||
type: "text",
|
||||
status: "sending" as const
|
||||
};
|
||||
|
||||
// Optimistic update
|
||||
useChatStore.getState().upsertMessage(payload);
|
||||
|
||||
// Send to WS
|
||||
wsManager.send({
|
||||
type: "SendMessage",
|
||||
payload: {
|
||||
id: messageId,
|
||||
conversationId,
|
||||
text: text.trim(),
|
||||
type: "text"
|
||||
}
|
||||
});
|
||||
|
||||
setText("");
|
||||
|
||||
// Stop typing
|
||||
if (typingRef.current) clearTimeout(typingRef.current);
|
||||
wsManager.send({
|
||||
type: "TypingIndicator",
|
||||
payload: { conversationId, active: false }
|
||||
});
|
||||
};
|
||||
|
||||
const handleKeyDown = (e: React.KeyboardEvent) => {
|
||||
if (e.key === 'Enter' && !e.shiftKey) {
|
||||
e.preventDefault();
|
||||
handleSend(e);
|
||||
return;
|
||||
}
|
||||
|
||||
// Typing indicator logic
|
||||
if (typingRef.current) clearTimeout(typingRef.current);
|
||||
|
||||
wsManager.send({
|
||||
type: "TypingIndicator",
|
||||
payload: { conversationId, active: true }
|
||||
});
|
||||
|
||||
typingRef.current = setTimeout(() => {
|
||||
wsManager.send({
|
||||
type: "TypingIndicator",
|
||||
payload: { conversationId, active: false }
|
||||
});
|
||||
}, 3000);
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="border-t border-gray-200 bg-white p-4">
|
||||
<form onSubmit={handleSend} className="flex items-end space-x-3">
|
||||
<div className="flex space-x-1 pb-2 text-gray-400">
|
||||
<MediaUploader conversationId={conversationId} />
|
||||
<StickerPicker conversationId={conversationId} />
|
||||
<button type="button" className="hover:text-gray-600 rounded-full p-2 hover:bg-gray-100 transition-colors">
|
||||
<Mic className="h-5 w-5" />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div className="flex-1 rounded-2xl bg-gray-100 px-4 py-2 border border-transparent focus-within:border-gray-300 focus-within:bg-white transition-colors">
|
||||
<textarea
|
||||
value={text}
|
||||
onChange={(e) => setText(e.target.value)}
|
||||
onKeyDown={handleKeyDown}
|
||||
placeholder="Message..."
|
||||
rows={1}
|
||||
className="w-full bg-transparent outline-none placeholder:text-gray-500 text-sm resize-none max-h-32 pt-1"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<button
|
||||
type="submit"
|
||||
disabled={!text.trim()}
|
||||
className="flex h-10 w-10 items-center justify-center rounded-full bg-blue-600 text-white hover:bg-blue-500 disabled:bg-gray-200 disabled:text-gray-400 transition-colors mb-0.5 flex-shrink-0"
|
||||
>
|
||||
<Send className="h-4 w-4 ml-0.5" />
|
||||
</button>
|
||||
</form>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
"use client";
|
||||
|
||||
import { useChatStore } from "@/lib/store/chat";
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import clsx from "clsx";
|
||||
import { Check, CheckCheck, Clock } from "lucide-react";
|
||||
|
||||
export function MessageThread({ conversationId }: { conversationId: string }) {
|
||||
const messages = useChatStore((state) => state.messages.get(conversationId) || []);
|
||||
const bottomRef = useRef<HTMLDivElement>(null);
|
||||
const containerRef = useRef<HTMLDivElement>(null);
|
||||
const [isScrolledUp, setIsScrolledUp] = useState(false);
|
||||
|
||||
// Auto-scroll logic
|
||||
useEffect(() => {
|
||||
if (!isScrolledUp) {
|
||||
bottomRef.current?.scrollIntoView({ behavior: "smooth" });
|
||||
}
|
||||
}, [messages, isScrolledUp]);
|
||||
|
||||
const handleScroll = () => {
|
||||
if (!containerRef.current) return;
|
||||
const { scrollTop, scrollHeight, clientHeight } = containerRef.current;
|
||||
// Check if we are near the bottom (within 50px)
|
||||
const isNearBottom = scrollHeight - scrollTop - clientHeight < 50;
|
||||
setIsScrolledUp(!isNearBottom);
|
||||
};
|
||||
|
||||
return (
|
||||
<div
|
||||
ref={containerRef}
|
||||
onScroll={handleScroll}
|
||||
className="flex-1 overflow-y-auto p-4 space-y-4"
|
||||
>
|
||||
{messages.length === 0 ? (
|
||||
<div className="h-full flex items-center justify-center text-gray-500 text-sm">
|
||||
No messages yet. Send a message to start the conversation!
|
||||
</div>
|
||||
) : (
|
||||
messages.map((msg) => {
|
||||
// Temporarily assuming "me" is the current user. In a real app, this comes from an Auth Context.
|
||||
const isMine = msg.senderId === "me";
|
||||
|
||||
return (
|
||||
<div
|
||||
key={msg.id}
|
||||
className={clsx(
|
||||
"flex flex-col max-w-[75%]",
|
||||
isMine ? "ml-auto items-end" : "mr-auto items-start"
|
||||
)}
|
||||
>
|
||||
<div
|
||||
className={clsx(
|
||||
"rounded-2xl px-4 py-2",
|
||||
isMine ? "bg-blue-600 text-white rounded-br-sm" : "bg-white text-gray-900 shadow-sm ring-1 ring-gray-100 rounded-bl-sm"
|
||||
)}
|
||||
>
|
||||
{msg.type === "text" && <p className="text-sm">{msg.text}</p>}
|
||||
{msg.type === "image" && (
|
||||
<div className="relative">
|
||||
{msg.status === "sending" && !msg.mediaRef ? (
|
||||
<div className="w-32 h-32 bg-white/20 animate-pulse rounded-md" />
|
||||
) : (
|
||||
<img src={msg.mediaRef} alt="Image" className="max-w-[200px] rounded-md object-cover" />
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
{msg.type === "audio" && (
|
||||
<audio controls src={msg.mediaRef} className="h-8 max-w-[200px]" />
|
||||
)}
|
||||
{msg.type === "gif" && (
|
||||
<video autoPlay loop muted playsInline src={msg.mediaRef} className="max-w-[200px] rounded-md" />
|
||||
)}
|
||||
{msg.type === "sticker" && (
|
||||
<div className="text-[6rem] leading-none drop-shadow-sm">{msg.text}</div>
|
||||
)}
|
||||
</div>
|
||||
<div className="flex items-center mt-1 space-x-1 text-[10px] text-gray-500">
|
||||
<span>{new Intl.DateTimeFormat('default', { hour: 'numeric', minute: 'numeric' }).format(new Date(msg.timestamp))}</span>
|
||||
{isMine && (
|
||||
<span>
|
||||
{msg.status === "sending" && <Clock className="h-3 w-3" />}
|
||||
{msg.status === "sent" && <Check className="h-3 w-3" />}
|
||||
{msg.status === "delivered" && <CheckCheck className="h-3 w-3" />}
|
||||
{msg.status === "read" && <CheckCheck className="h-3 w-3 text-blue-500" />}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})
|
||||
)}
|
||||
<div ref={bottomRef} className="h-1" />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
"use client";
|
||||
|
||||
import { useChatStore } from "@/lib/store/chat";
|
||||
|
||||
export function TypingIndicator({ conversationId }: { conversationId: string }) {
|
||||
const isTyping = useChatStore((state) => state.typing.get(conversationId)?.active);
|
||||
const convo = useChatStore((state) => state.conversations.get(conversationId));
|
||||
|
||||
if (!isTyping || !convo) return null;
|
||||
|
||||
return (
|
||||
<div className="px-4 py-1.5 text-xs text-gray-500 bg-white border-t border-gray-100 italic flex items-center gap-2">
|
||||
<div className="flex space-x-1">
|
||||
<div className="w-1.5 h-1.5 bg-gray-400 rounded-full animate-bounce" style={{ animationDelay: '0ms' }} />
|
||||
<div className="w-1.5 h-1.5 bg-gray-400 rounded-full animate-bounce" style={{ animationDelay: '150ms' }} />
|
||||
<div className="w-1.5 h-1.5 bg-gray-400 rounded-full animate-bounce" style={{ animationDelay: '300ms' }} />
|
||||
</div>
|
||||
{convo.participantName} is typing...
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
"use client";
|
||||
|
||||
import { useRef, useState } from "react";
|
||||
import { Image as ImageIcon, Loader2 } from "lucide-react";
|
||||
import { useChatStore } from "@/lib/store/chat";
|
||||
import { wsManager } from "@/lib/ws";
|
||||
|
||||
export function MediaUploader({ conversationId }: { conversationId: string }) {
|
||||
const fileInputRef = useRef<HTMLInputElement>(null);
|
||||
const [isUploading, setIsUploading] = useState(false);
|
||||
|
||||
const handleFileChange = async (e: React.ChangeEvent<HTMLInputElement>) => {
|
||||
const file = e.target.files?.[0];
|
||||
if (!file) return;
|
||||
|
||||
setIsUploading(true);
|
||||
|
||||
try {
|
||||
const messageId = crypto.randomUUID();
|
||||
let type = "image";
|
||||
if (file.type.startsWith("audio/")) type = "audio";
|
||||
if (file.type === "image/gif") type = "gif";
|
||||
|
||||
// 1. Optimistic message with "sending" state and missing mediaRef
|
||||
useChatStore.getState().upsertMessage({
|
||||
id: messageId,
|
||||
conversationId,
|
||||
senderId: "me", // Temporary stub
|
||||
timestamp: Date.now(),
|
||||
sequence: Date.now(),
|
||||
type,
|
||||
status: "sending"
|
||||
});
|
||||
|
||||
// 2. Upload to REST API (Simulated with a timeout)
|
||||
// In a real implementation:
|
||||
// const formData = new FormData();
|
||||
// formData.append("file", file);
|
||||
// await fetch('/api/media/upload', ...)
|
||||
await new Promise(res => setTimeout(res, 1500));
|
||||
|
||||
// Simulate getting a CDN URL or media ref back from the server
|
||||
const mockMediaUrl = URL.createObjectURL(file);
|
||||
|
||||
// 3. Send SendMessage WS frame with the uploaded reference
|
||||
wsManager.send({
|
||||
type: "SendMessage",
|
||||
payload: {
|
||||
id: messageId,
|
||||
conversationId,
|
||||
type,
|
||||
mediaRef: mockMediaUrl
|
||||
}
|
||||
});
|
||||
|
||||
// Optimistically reconcile the mock media URL so it shows up immediately
|
||||
useChatStore.getState().upsertMessage({
|
||||
id: messageId,
|
||||
conversationId,
|
||||
senderId: "me",
|
||||
timestamp: Date.now(),
|
||||
sequence: Date.now(),
|
||||
type,
|
||||
mediaRef: mockMediaUrl,
|
||||
status: "sent"
|
||||
});
|
||||
|
||||
} catch (e) {
|
||||
console.error("Upload failed", e);
|
||||
} finally {
|
||||
setIsUploading(false);
|
||||
if (fileInputRef.current) fileInputRef.current.value = "";
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
<input
|
||||
type="file"
|
||||
ref={fileInputRef}
|
||||
className="hidden"
|
||||
accept="image/*,audio/*,video/mp4"
|
||||
onChange={handleFileChange}
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => fileInputRef.current?.click()}
|
||||
disabled={isUploading}
|
||||
className="hover:text-gray-600 rounded-full p-2 hover:bg-gray-100 transition-colors disabled:opacity-50"
|
||||
>
|
||||
{isUploading ? <Loader2 className="h-5 w-5 animate-spin" /> : <ImageIcon className="h-5 w-5" />}
|
||||
</button>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
"use client";
|
||||
|
||||
import { useState, useRef, useEffect } from "react";
|
||||
import { Smile } from "lucide-react";
|
||||
import { useChatStore } from "@/lib/store/chat";
|
||||
import { wsManager } from "@/lib/ws";
|
||||
|
||||
export function StickerPicker({ conversationId }: { conversationId: string }) {
|
||||
const [isOpen, setIsOpen] = useState(false);
|
||||
const menuRef = useRef<HTMLDivElement>(null);
|
||||
|
||||
// Mock sticker pack data
|
||||
const stickers = ["😀", "🎉", "🔥", "🚀", "❤️", "🌟", "😂", "👍", "👀", "🙌", "💯", "🎈"];
|
||||
|
||||
useEffect(() => {
|
||||
const handleClickOutside = (event: MouseEvent) => {
|
||||
if (menuRef.current && !menuRef.current.contains(event.target as Node)) {
|
||||
setIsOpen(false);
|
||||
}
|
||||
};
|
||||
if (isOpen) {
|
||||
document.addEventListener("mousedown", handleClickOutside);
|
||||
}
|
||||
return () => {
|
||||
document.removeEventListener("mousedown", handleClickOutside);
|
||||
};
|
||||
}, [isOpen]);
|
||||
|
||||
const sendSticker = (sticker: string) => {
|
||||
const messageId = crypto.randomUUID();
|
||||
|
||||
useChatStore.getState().upsertMessage({
|
||||
id: messageId,
|
||||
conversationId,
|
||||
senderId: "me",
|
||||
timestamp: Date.now(),
|
||||
sequence: Date.now(),
|
||||
type: "sticker",
|
||||
text: sticker,
|
||||
status: "sending"
|
||||
});
|
||||
|
||||
wsManager.send({
|
||||
type: "SendMessage",
|
||||
payload: {
|
||||
id: messageId,
|
||||
conversationId,
|
||||
type: "sticker",
|
||||
text: sticker
|
||||
}
|
||||
});
|
||||
|
||||
setIsOpen(false);
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="relative" ref={menuRef}>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setIsOpen(!isOpen)}
|
||||
className="hover:text-gray-600 rounded-full p-2 hover:bg-gray-100 transition-colors"
|
||||
>
|
||||
<Smile className="h-5 w-5" />
|
||||
</button>
|
||||
|
||||
{isOpen && (
|
||||
<div className="absolute bottom-full left-0 mb-2 w-56 bg-white border border-gray-200 rounded-lg shadow-lg p-2 grid grid-cols-4 gap-2 z-50">
|
||||
{stickers.map((s, i) => (
|
||||
<button
|
||||
key={i}
|
||||
type="button"
|
||||
onClick={() => sendSticker(s)}
|
||||
className="text-3xl hover:bg-gray-100 rounded-md p-1 flex items-center justify-center transition-colors"
|
||||
>
|
||||
{s}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
+161
@@ -0,0 +1,161 @@
|
||||
"use server";
|
||||
|
||||
import { cookies } from "next/headers";
|
||||
import { redirect } from "next/navigation";
|
||||
|
||||
const API_URL = process.env.API_URL || "http://localhost:8080";
|
||||
|
||||
type AuthActionState = {
|
||||
error?: string;
|
||||
} | null;
|
||||
|
||||
const isSecureCookie = process.env.NODE_ENV !== "development";
|
||||
|
||||
export async function login(prevState: AuthActionState, formData: FormData) {
|
||||
void prevState;
|
||||
const username = formData.get("username") as string;
|
||||
const password = formData.get("password") as string;
|
||||
|
||||
if (!username || !password) {
|
||||
return { error: "Username and password are required." };
|
||||
}
|
||||
|
||||
try {
|
||||
const res = await fetch(`${API_URL}/api/auth/login`, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ username, password }),
|
||||
});
|
||||
|
||||
if (!res.ok) {
|
||||
// Mock fallback if API is not yet ready, so we can test the UI
|
||||
if (process.env.NODE_ENV === "development" && res.status === 404) {
|
||||
console.warn("Mocking login because API endpoint is not found.");
|
||||
const mockJwt = "mock-jwt-token-for-" + username;
|
||||
const cookieStore = await cookies();
|
||||
cookieStore.set("auth_token", mockJwt, {
|
||||
httpOnly: true,
|
||||
secure: isSecureCookie,
|
||||
sameSite: "lax",
|
||||
path: "/",
|
||||
maxAge: 60 * 60 * 24 * 7, // 1 week
|
||||
});
|
||||
redirect("/c");
|
||||
}
|
||||
|
||||
const errorData = await res.json().catch(() => ({}));
|
||||
return { error: errorData.error || "Login failed" };
|
||||
}
|
||||
|
||||
const data = await res.json();
|
||||
const token = data.token; // Assuming the backend returns { token: "..." }
|
||||
|
||||
if (token) {
|
||||
const cookieStore = await cookies();
|
||||
cookieStore.set("auth_token", token, {
|
||||
httpOnly: true,
|
||||
secure: isSecureCookie,
|
||||
sameSite: "lax",
|
||||
path: "/",
|
||||
maxAge: 60 * 60 * 24 * 7, // 1 week
|
||||
});
|
||||
}
|
||||
|
||||
} catch {
|
||||
// Mock fallback if connection fails completely (e.g. backend down)
|
||||
if (process.env.NODE_ENV === "development") {
|
||||
console.warn("Mocking login because backend connection failed.");
|
||||
const mockJwt = "mock-jwt-token-for-" + username;
|
||||
const cookieStore = await cookies();
|
||||
cookieStore.set("auth_token", mockJwt, {
|
||||
httpOnly: true,
|
||||
secure: isSecureCookie,
|
||||
sameSite: "lax",
|
||||
path: "/",
|
||||
maxAge: 60 * 60 * 24 * 7, // 1 week
|
||||
});
|
||||
redirect("/c");
|
||||
}
|
||||
return { error: "Network error occurred." };
|
||||
}
|
||||
|
||||
redirect("/c");
|
||||
}
|
||||
|
||||
export async function register(prevState: AuthActionState, formData: FormData) {
|
||||
void prevState;
|
||||
const username = formData.get("username") as string;
|
||||
const password = formData.get("password") as string;
|
||||
const displayName = formData.get("displayName") as string;
|
||||
|
||||
if (!username || !password) {
|
||||
return { error: "Username and password are required." };
|
||||
}
|
||||
|
||||
try {
|
||||
const res = await fetch(`${API_URL}/api/auth/register`, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ username, password, display_name: displayName }),
|
||||
});
|
||||
|
||||
if (!res.ok) {
|
||||
// Mock fallback
|
||||
if (process.env.NODE_ENV === "development" && res.status === 404) {
|
||||
console.warn("Mocking register because API endpoint is not found.");
|
||||
const mockJwt = "mock-jwt-token-for-" + username;
|
||||
const cookieStore = await cookies();
|
||||
cookieStore.set("auth_token", mockJwt, {
|
||||
httpOnly: true,
|
||||
secure: isSecureCookie,
|
||||
sameSite: "lax",
|
||||
path: "/",
|
||||
maxAge: 60 * 60 * 24 * 7, // 1 week
|
||||
});
|
||||
redirect("/c");
|
||||
}
|
||||
|
||||
const errorData = await res.json().catch(() => ({}));
|
||||
return { error: errorData.error || "Registration failed" };
|
||||
}
|
||||
|
||||
const data = await res.json();
|
||||
const token = data.token;
|
||||
|
||||
if (token) {
|
||||
const cookieStore = await cookies();
|
||||
cookieStore.set("auth_token", token, {
|
||||
httpOnly: true,
|
||||
secure: isSecureCookie,
|
||||
sameSite: "lax",
|
||||
path: "/",
|
||||
maxAge: 60 * 60 * 24 * 7, // 1 week
|
||||
});
|
||||
}
|
||||
|
||||
} catch {
|
||||
// Mock fallback
|
||||
if (process.env.NODE_ENV === "development") {
|
||||
console.warn("Mocking register because backend connection failed.");
|
||||
const mockJwt = "mock-jwt-token-for-" + username;
|
||||
const cookieStore = await cookies();
|
||||
cookieStore.set("auth_token", mockJwt, {
|
||||
httpOnly: true,
|
||||
secure: isSecureCookie,
|
||||
sameSite: "lax",
|
||||
path: "/",
|
||||
maxAge: 60 * 60 * 24 * 7, // 1 week
|
||||
});
|
||||
redirect("/c");
|
||||
}
|
||||
return { error: "Network error occurred." };
|
||||
}
|
||||
|
||||
redirect("/c");
|
||||
}
|
||||
|
||||
export async function logout() {
|
||||
const cookieStore = await cookies();
|
||||
cookieStore.delete("auth_token");
|
||||
redirect("/");
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
import Dexie, { type EntityTable } from 'dexie';
|
||||
|
||||
export interface ConversationEntity {
|
||||
id: string;
|
||||
participantName: string;
|
||||
participantAvatar?: string;
|
||||
unreadCount: number;
|
||||
lastMessagePreview?: string;
|
||||
lastMessageTimestamp?: number;
|
||||
lastSequence?: number;
|
||||
}
|
||||
|
||||
export interface MessageEntity {
|
||||
id: string; // Message UUID
|
||||
conversationId: string;
|
||||
senderId: string;
|
||||
text?: string;
|
||||
timestamp: number;
|
||||
sequence: number;
|
||||
type: string;
|
||||
mediaRef?: string;
|
||||
status: 'sending' | 'sent' | 'delivered' | 'read';
|
||||
}
|
||||
|
||||
const db = new Dexie('PostcardDB') as Dexie & {
|
||||
conversations: EntityTable<ConversationEntity, 'id'>;
|
||||
messages: EntityTable<MessageEntity, 'id'>;
|
||||
};
|
||||
|
||||
// Schema declaration
|
||||
db.version(1).stores({
|
||||
conversations: 'id, lastMessageTimestamp',
|
||||
messages: 'id, conversationId, sequence, [conversationId+sequence]'
|
||||
});
|
||||
|
||||
export { db };
|
||||
@@ -0,0 +1,116 @@
|
||||
import { create } from 'zustand';
|
||||
import { ConversationEntity, MessageEntity, db } from '../db';
|
||||
|
||||
interface ChatState {
|
||||
conversations: Map<string, ConversationEntity>;
|
||||
messages: Map<string, MessageEntity[]>;
|
||||
typing: Map<string, { userId: string; active: boolean; timeout?: NodeJS.Timeout }>;
|
||||
presence: Map<string, { status: string; lastSeen: number }>;
|
||||
connection: { status: 'connecting' | 'connected' | 'disconnected' | 'syncing' };
|
||||
|
||||
// Actions
|
||||
setConnectionStatus: (status: ChatState['connection']['status']) => void;
|
||||
upsertConversation: (conversation: ConversationEntity) => void;
|
||||
upsertMessage: (message: MessageEntity) => void;
|
||||
setMessages: (conversationId: string, messages: MessageEntity[]) => void;
|
||||
setTyping: (conversationId: string, active: boolean) => void;
|
||||
setPresence: (userId: string, status: string, lastSeen: number) => void;
|
||||
hydrateFromDb: () => Promise<void>;
|
||||
}
|
||||
|
||||
export const useChatStore = create<ChatState>((set, get) => ({
|
||||
conversations: new Map(),
|
||||
messages: new Map(),
|
||||
typing: new Map(),
|
||||
presence: new Map(),
|
||||
connection: { status: 'disconnected' },
|
||||
|
||||
setConnectionStatus: (status) => set({ connection: { status } }),
|
||||
|
||||
upsertConversation: (conversation) => {
|
||||
set((state) => {
|
||||
const newMap = new Map(state.conversations);
|
||||
newMap.set(conversation.id, {
|
||||
...(newMap.get(conversation.id) || {}),
|
||||
...conversation
|
||||
});
|
||||
return { conversations: newMap };
|
||||
});
|
||||
// Persist
|
||||
db.conversations.put(conversation).catch(console.error);
|
||||
},
|
||||
|
||||
upsertMessage: (message) => {
|
||||
set((state) => {
|
||||
const newMap = new Map(state.messages);
|
||||
const convMessages = newMap.get(message.conversationId) || [];
|
||||
// Insert and keep sorted by sequence
|
||||
const existingIdx = convMessages.findIndex(m => m.id === message.id);
|
||||
if (existingIdx >= 0) {
|
||||
convMessages[existingIdx] = message;
|
||||
} else {
|
||||
convMessages.push(message);
|
||||
// Using sort for simplicity; for large arrays, inserting at right index is better
|
||||
convMessages.sort((a, b) => a.sequence - b.sequence);
|
||||
}
|
||||
newMap.set(message.conversationId, [...convMessages]);
|
||||
return { messages: newMap };
|
||||
});
|
||||
// Persist
|
||||
db.messages.put(message).catch(console.error);
|
||||
},
|
||||
|
||||
setMessages: (conversationId, messages) => {
|
||||
set((state) => {
|
||||
const newMap = new Map(state.messages);
|
||||
newMap.set(conversationId, messages);
|
||||
return { messages: newMap };
|
||||
});
|
||||
},
|
||||
|
||||
setTyping: (conversationId, active) => {
|
||||
set((state) => {
|
||||
const newTyping = new Map(state.typing);
|
||||
const current = newTyping.get(conversationId);
|
||||
if (current?.timeout) clearTimeout(current.timeout);
|
||||
|
||||
let timeout;
|
||||
if (active) {
|
||||
timeout = setTimeout(() => {
|
||||
get().setTyping(conversationId, false);
|
||||
}, 3000);
|
||||
}
|
||||
|
||||
newTyping.set(conversationId, { userId: conversationId, active, timeout });
|
||||
return { typing: newTyping };
|
||||
});
|
||||
},
|
||||
|
||||
setPresence: (userId, status, lastSeen) => {
|
||||
set((state) => {
|
||||
const newPresence = new Map(state.presence);
|
||||
newPresence.set(userId, { status, lastSeen });
|
||||
return { presence: newPresence };
|
||||
});
|
||||
},
|
||||
|
||||
hydrateFromDb: async () => {
|
||||
try {
|
||||
const convos = await db.conversations.toArray();
|
||||
const msgs = await db.messages.orderBy('sequence').toArray();
|
||||
|
||||
const convoMap = new Map();
|
||||
convos.forEach(c => convoMap.set(c.id, c));
|
||||
|
||||
const msgsMap = new Map();
|
||||
msgs.forEach(m => {
|
||||
if (!msgsMap.has(m.conversationId)) msgsMap.set(m.conversationId, []);
|
||||
msgsMap.get(m.conversationId).push(m);
|
||||
});
|
||||
|
||||
set({ conversations: convoMap, messages: msgsMap });
|
||||
} catch (e) {
|
||||
console.error("Failed to hydrate from DB", e);
|
||||
}
|
||||
}
|
||||
}));
|
||||
+163
@@ -0,0 +1,163 @@
|
||||
import { useChatStore } from './store/chat';
|
||||
|
||||
export class WebSocketManager {
|
||||
private ws: WebSocket | null = null;
|
||||
private reconnectAttempts = 0;
|
||||
private maxReconnectAttempts = 6; // 1s, 2s, 4s, 8s, 16s, 30s
|
||||
private pingInterval: NodeJS.Timeout | null = null;
|
||||
private url: string;
|
||||
private isIntentionalDisconnect = false;
|
||||
|
||||
constructor(url?: string) {
|
||||
if (url) {
|
||||
this.url = url;
|
||||
} else if (typeof window !== 'undefined') {
|
||||
const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
|
||||
const host = process.env.NEXT_PUBLIC_WS_URL || window.location.host;
|
||||
this.url = `${protocol}//${host}/ws`;
|
||||
} else {
|
||||
this.url = 'ws://localhost:8080/ws';
|
||||
}
|
||||
}
|
||||
|
||||
connect() {
|
||||
if (typeof window === 'undefined') return; // Do not connect during SSR
|
||||
if (this.ws?.readyState === WebSocket.OPEN || this.ws?.readyState === WebSocket.CONNECTING) return;
|
||||
|
||||
this.isIntentionalDisconnect = false;
|
||||
useChatStore.getState().setConnectionStatus('connecting');
|
||||
|
||||
try {
|
||||
this.ws = new WebSocket(this.url);
|
||||
|
||||
this.ws.onopen = this.handleOpen.bind(this);
|
||||
this.ws.onmessage = this.handleMessage.bind(this);
|
||||
this.ws.onclose = this.handleClose.bind(this);
|
||||
this.ws.onerror = this.handleError.bind(this);
|
||||
} catch (e) {
|
||||
console.error('WebSocket connection failed', e);
|
||||
this.scheduleReconnect();
|
||||
}
|
||||
}
|
||||
|
||||
disconnect() {
|
||||
this.isIntentionalDisconnect = true;
|
||||
if (this.pingInterval) clearInterval(this.pingInterval);
|
||||
if (this.ws) {
|
||||
this.ws.close();
|
||||
this.ws = null;
|
||||
}
|
||||
useChatStore.getState().setConnectionStatus('disconnected');
|
||||
}
|
||||
|
||||
send(payload: any) {
|
||||
if (this.ws?.readyState === WebSocket.OPEN) {
|
||||
this.ws.send(JSON.stringify(payload));
|
||||
} else {
|
||||
console.warn('Cannot send, WebSocket not open');
|
||||
}
|
||||
}
|
||||
|
||||
private handleOpen() {
|
||||
this.reconnectAttempts = 0;
|
||||
useChatStore.getState().setConnectionStatus('connected');
|
||||
|
||||
this.startPing();
|
||||
this.sync();
|
||||
}
|
||||
|
||||
private sync() {
|
||||
useChatStore.getState().setConnectionStatus('syncing');
|
||||
const state = useChatStore.getState();
|
||||
const syncState: Record<string, number> = {};
|
||||
|
||||
state.conversations.forEach((convo) => {
|
||||
if (convo.lastSequence !== undefined) {
|
||||
syncState[convo.id] = convo.lastSequence;
|
||||
}
|
||||
});
|
||||
|
||||
this.send({ type: 'Sync', payload: { state: syncState } });
|
||||
}
|
||||
|
||||
private handleMessage(event: MessageEvent) {
|
||||
try {
|
||||
const data = JSON.parse(event.data);
|
||||
const store = useChatStore.getState();
|
||||
|
||||
switch (data.type) {
|
||||
case 'NewMessage':
|
||||
store.upsertMessage(data.payload);
|
||||
// Update conversation preview and sequence
|
||||
const convo = store.conversations.get(data.payload.conversationId);
|
||||
if (convo) {
|
||||
store.upsertConversation({
|
||||
...convo,
|
||||
lastMessagePreview: data.payload.text || data.payload.type,
|
||||
lastMessageTimestamp: data.payload.timestamp,
|
||||
lastSequence: Math.max(convo.lastSequence || 0, data.payload.sequence),
|
||||
});
|
||||
}
|
||||
break;
|
||||
case 'TypingIndicator':
|
||||
store.setTyping(data.payload.conversationId, data.payload.active);
|
||||
break;
|
||||
case 'PresenceUpdate':
|
||||
store.setPresence(data.payload.userId, data.payload.status, data.payload.lastSeen);
|
||||
break;
|
||||
case 'SyncComplete':
|
||||
store.setConnectionStatus('connected');
|
||||
break;
|
||||
case 'MessageEcho':
|
||||
// Reconcile optimistic message
|
||||
store.upsertMessage({
|
||||
...data.payload,
|
||||
status: 'sent'
|
||||
});
|
||||
break;
|
||||
case 'Pong':
|
||||
// Optional: Handle latency metrics
|
||||
break;
|
||||
default:
|
||||
console.debug('Unhandled WS message type:', data.type);
|
||||
}
|
||||
} catch (e) {
|
||||
console.error('Error parsing WS message', e);
|
||||
}
|
||||
}
|
||||
|
||||
private handleClose(event: CloseEvent) {
|
||||
if (this.pingInterval) clearInterval(this.pingInterval);
|
||||
useChatStore.getState().setConnectionStatus('disconnected');
|
||||
|
||||
if (!this.isIntentionalDisconnect) {
|
||||
this.scheduleReconnect();
|
||||
}
|
||||
}
|
||||
|
||||
private handleError(error: Event) {
|
||||
console.error('WebSocket error', error);
|
||||
}
|
||||
|
||||
private scheduleReconnect() {
|
||||
if (this.reconnectAttempts >= this.maxReconnectAttempts) {
|
||||
console.error('Max reconnect attempts reached. Giving up.');
|
||||
return;
|
||||
}
|
||||
|
||||
const backoffTime = Math.min(Math.pow(2, this.reconnectAttempts) * 1000, 30000);
|
||||
this.reconnectAttempts++;
|
||||
|
||||
console.log(`Reconnecting in ${backoffTime}ms (Attempt ${this.reconnectAttempts})`);
|
||||
setTimeout(() => this.connect(), backoffTime);
|
||||
}
|
||||
|
||||
private startPing() {
|
||||
if (this.pingInterval) clearInterval(this.pingInterval);
|
||||
this.pingInterval = setInterval(() => {
|
||||
this.send({ type: 'Ping' });
|
||||
}, 25000);
|
||||
}
|
||||
}
|
||||
|
||||
export const wsManager = new WebSocketManager();
|
||||
@@ -0,0 +1,25 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import type { NextRequest } from "next/server";
|
||||
|
||||
export function proxy(request: NextRequest) {
|
||||
const authToken = request.cookies.get("auth_token");
|
||||
const { pathname } = request.nextUrl;
|
||||
|
||||
const isAuthRoute = pathname === "/" || pathname === "/register";
|
||||
|
||||
if (!authToken && !isAuthRoute) {
|
||||
return NextResponse.redirect(new URL("/", request.url));
|
||||
}
|
||||
|
||||
if (authToken && isAuthRoute) {
|
||||
return NextResponse.redirect(new URL("/c", request.url));
|
||||
}
|
||||
|
||||
return NextResponse.next();
|
||||
}
|
||||
|
||||
export const config = {
|
||||
matcher: [
|
||||
"/((?!api|_next/static|_next/image|favicon.ico|.*\\.(?:svg|png|jpg|jpeg|gif|webp)$).*)",
|
||||
],
|
||||
};
|
||||
@@ -0,0 +1,34 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"target": "ES2017",
|
||||
"lib": ["dom", "dom.iterable", "esnext"],
|
||||
"allowJs": true,
|
||||
"skipLibCheck": true,
|
||||
"strict": true,
|
||||
"noEmit": true,
|
||||
"esModuleInterop": true,
|
||||
"module": "esnext",
|
||||
"moduleResolution": "bundler",
|
||||
"resolveJsonModule": true,
|
||||
"isolatedModules": true,
|
||||
"jsx": "react-jsx",
|
||||
"incremental": true,
|
||||
"plugins": [
|
||||
{
|
||||
"name": "next"
|
||||
}
|
||||
],
|
||||
"paths": {
|
||||
"@/*": ["./src/*"]
|
||||
}
|
||||
},
|
||||
"include": [
|
||||
"next-env.d.ts",
|
||||
"**/*.ts",
|
||||
"**/*.tsx",
|
||||
".next/types/**/*.ts",
|
||||
".next/dev/types/**/*.ts",
|
||||
"**/*.mts"
|
||||
],
|
||||
"exclude": ["node_modules"]
|
||||
}
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
{
|
||||
"$schema": "https://turbo.build/schema.json",
|
||||
"tasks": {
|
||||
"build": {
|
||||
"dependsOn": ["^build"],
|
||||
"outputs": [".next/**", "!.next/cache/**"]
|
||||
},
|
||||
"lint": {
|
||||
"dependsOn": ["^lint"]
|
||||
},
|
||||
"dev": {
|
||||
"cache": false,
|
||||
"persistent": true
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user