initial commit
This commit is contained in:
5
frontend/.dockerignore
Normal file
5
frontend/.dockerignore
Normal file
@ -0,0 +1,5 @@
|
||||
node_modules
|
||||
dist
|
||||
tasks.db
|
||||
.git
|
||||
.DS_Store
|
||||
10
frontend/.env
Normal file
10
frontend/.env
Normal file
@ -0,0 +1,10 @@
|
||||
# Uncomment the line corresponding to the backend you want to use
|
||||
|
||||
# 1. Fake backend (server.ts) - Default
|
||||
# VITE_API_BASE_URL=
|
||||
|
||||
# 2. Local backend
|
||||
VITE_API_BASE_URL=http://localhost:3000
|
||||
|
||||
# 3. Production backend
|
||||
# VITE_API_BASE_URL=https://rubble.se/householdmanager
|
||||
24
frontend/.gitignore
vendored
Normal file
24
frontend/.gitignore
vendored
Normal file
@ -0,0 +1,24 @@
|
||||
# Logs
|
||||
logs
|
||||
*.log
|
||||
npm-debug.log*
|
||||
yarn-debug.log*
|
||||
yarn-error.log*
|
||||
pnpm-debug.log*
|
||||
lerna-debug.log*
|
||||
|
||||
node_modules
|
||||
dist
|
||||
dist-ssr
|
||||
*.local
|
||||
|
||||
# Editor directories and files
|
||||
.vscode/*
|
||||
!.vscode/extensions.json
|
||||
.idea
|
||||
.DS_Store
|
||||
*.suo
|
||||
*.ntvs*
|
||||
*.njsproj
|
||||
*.sln
|
||||
*.sw?
|
||||
48
frontend/Dockerfile
Normal file
48
frontend/Dockerfile
Normal file
@ -0,0 +1,48 @@
|
||||
# Build stage
|
||||
FROM node:22-slim AS builder
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
# Copy package files
|
||||
COPY package.json package-lock.json ./
|
||||
|
||||
# Install all dependencies
|
||||
RUN npm ci
|
||||
|
||||
# Copy the rest of the source
|
||||
COPY . .
|
||||
|
||||
# Build the frontend (creates the 'dist' folder)
|
||||
RUN npm run build
|
||||
|
||||
# Runtime stage
|
||||
FROM node:22-slim
|
||||
|
||||
# Install sqlite3 runtime dependencies
|
||||
RUN apt-get update && apt-get install -y python3 make g++ && rm -rf /var/lib/apt/lists/*
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
# Copy package files
|
||||
COPY package.json package-lock.json ./
|
||||
|
||||
# Install only production dependencies (better-sqlite3 needs compilation)
|
||||
RUN npm ci --only=production && npm install -g tsx
|
||||
|
||||
# Copy built frontend from builder stage
|
||||
COPY --from=builder /app/dist ./dist
|
||||
|
||||
# Copy the server file and other necessary source
|
||||
COPY server.ts ./
|
||||
# (If there are other source files needed by server.ts, they should be copied too)
|
||||
# Looking at server.ts, it doesn't seem to import other local files besides 'vite'
|
||||
# but wait, it uses 'path' and 'url' (built-in).
|
||||
|
||||
# Expose the port the app runs on
|
||||
EXPOSE 3000
|
||||
|
||||
# Set environment to production
|
||||
ENV NODE_ENV=production
|
||||
|
||||
# Command to run the server
|
||||
CMD ["tsx", "server.ts"]
|
||||
73
frontend/README.md
Normal file
73
frontend/README.md
Normal file
@ -0,0 +1,73 @@
|
||||
# React + TypeScript + Vite
|
||||
|
||||
This template provides a minimal setup to get React working in Vite with HMR and some ESLint rules.
|
||||
|
||||
Currently, two official plugins are available:
|
||||
|
||||
- [@vitejs/plugin-react](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react) uses [Babel](https://babeljs.io/) (or [oxc](https://oxc.rs) when used in [rolldown-vite](https://vite.dev/guide/rolldown)) for Fast Refresh
|
||||
- [@vitejs/plugin-react-swc](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react-swc) uses [SWC](https://swc.rs/) for Fast Refresh
|
||||
|
||||
## React Compiler
|
||||
|
||||
The React Compiler is not enabled on this template because of its impact on dev & build performances. To add it, see [this documentation](https://react.dev/learn/react-compiler/installation).
|
||||
|
||||
## Expanding the ESLint configuration
|
||||
|
||||
If you are developing a production application, we recommend updating the configuration to enable type-aware lint rules:
|
||||
|
||||
```js
|
||||
export default defineConfig([
|
||||
globalIgnores(['dist']),
|
||||
{
|
||||
files: ['**/*.{ts,tsx}'],
|
||||
extends: [
|
||||
// Other configs...
|
||||
|
||||
// Remove tseslint.configs.recommended and replace with this
|
||||
tseslint.configs.recommendedTypeChecked,
|
||||
// Alternatively, use this for stricter rules
|
||||
tseslint.configs.strictTypeChecked,
|
||||
// Optionally, add this for stylistic rules
|
||||
tseslint.configs.stylisticTypeChecked,
|
||||
|
||||
// Other configs...
|
||||
],
|
||||
languageOptions: {
|
||||
parserOptions: {
|
||||
project: ['./tsconfig.node.json', './tsconfig.app.json'],
|
||||
tsconfigRootDir: import.meta.dirname,
|
||||
},
|
||||
// other options...
|
||||
},
|
||||
},
|
||||
])
|
||||
```
|
||||
|
||||
You can also install [eslint-plugin-react-x](https://github.com/Rel1cx/eslint-react/tree/main/packages/plugins/eslint-plugin-react-x) and [eslint-plugin-react-dom](https://github.com/Rel1cx/eslint-react/tree/main/packages/plugins/eslint-plugin-react-dom) for React-specific lint rules:
|
||||
|
||||
```js
|
||||
// eslint.config.js
|
||||
import reactX from 'eslint-plugin-react-x'
|
||||
import reactDom from 'eslint-plugin-react-dom'
|
||||
|
||||
export default defineConfig([
|
||||
globalIgnores(['dist']),
|
||||
{
|
||||
files: ['**/*.{ts,tsx}'],
|
||||
extends: [
|
||||
// Other configs...
|
||||
// Enable lint rules for React
|
||||
reactX.configs['recommended-typescript'],
|
||||
// Enable lint rules for React DOM
|
||||
reactDom.configs.recommended,
|
||||
],
|
||||
languageOptions: {
|
||||
parserOptions: {
|
||||
project: ['./tsconfig.node.json', './tsconfig.app.json'],
|
||||
tsconfigRootDir: import.meta.dirname,
|
||||
},
|
||||
// other options...
|
||||
},
|
||||
},
|
||||
])
|
||||
```
|
||||
23
frontend/eslint.config.js
Normal file
23
frontend/eslint.config.js
Normal file
@ -0,0 +1,23 @@
|
||||
import js from '@eslint/js'
|
||||
import globals from 'globals'
|
||||
import reactHooks from 'eslint-plugin-react-hooks'
|
||||
import reactRefresh from 'eslint-plugin-react-refresh'
|
||||
import tseslint from 'typescript-eslint'
|
||||
import { defineConfig, globalIgnores } from 'eslint/config'
|
||||
|
||||
export default defineConfig([
|
||||
globalIgnores(['dist']),
|
||||
{
|
||||
files: ['**/*.{ts,tsx}'],
|
||||
extends: [
|
||||
js.configs.recommended,
|
||||
tseslint.configs.recommended,
|
||||
reactHooks.configs.flat.recommended,
|
||||
reactRefresh.configs.vite,
|
||||
],
|
||||
languageOptions: {
|
||||
ecmaVersion: 2020,
|
||||
globals: globals.browser,
|
||||
},
|
||||
},
|
||||
])
|
||||
9
frontend/frontend.iml
Normal file
9
frontend/frontend.iml
Normal file
@ -0,0 +1,9 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<module type="WEB_MODULE" version="4">
|
||||
<component name="NewModuleRootManager" inherit-compiler-output="true">
|
||||
<exclude-output />
|
||||
<content url="file://$MODULE_DIR$" />
|
||||
<orderEntry type="inheritedJdk" />
|
||||
<orderEntry type="sourceFolder" forTests="false" />
|
||||
</component>
|
||||
</module>
|
||||
13
frontend/index.html
Normal file
13
frontend/index.html
Normal file
@ -0,0 +1,13 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<link rel="icon" type="image/svg+xml" href="/vite.svg" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>my-app</title>
|
||||
</head>
|
||||
<body>
|
||||
<div id="root"></div>
|
||||
<script type="module" src="/src/main.tsx"></script>
|
||||
</body>
|
||||
</html>
|
||||
6675
frontend/package-lock.json
generated
Normal file
6675
frontend/package-lock.json
generated
Normal file
File diff suppressed because it is too large
Load Diff
43
frontend/package.json
Normal file
43
frontend/package.json
Normal file
@ -0,0 +1,43 @@
|
||||
{
|
||||
"name": "my-app",
|
||||
"private": true,
|
||||
"version": "0.0.0",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "tsx server.ts",
|
||||
"build": "tsc && vite build",
|
||||
"lint": "eslint .",
|
||||
"preview": "vite preview",
|
||||
"start": "node server.ts"
|
||||
},
|
||||
"dependencies": {
|
||||
"@tailwindcss/vite": "^4.2.1",
|
||||
"axios": "^1.7.2",
|
||||
"better-sqlite3": "^12.6.2",
|
||||
"express": "^5.2.1",
|
||||
"http-proxy-middleware": "^3.0.5",
|
||||
"lucide-react": "^0.575.0",
|
||||
"motion": "^12.34.3",
|
||||
"react": "^19.2.0",
|
||||
"react-dom": "^19.2.0",
|
||||
"react-markdown": "^10.1.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@eslint/js": "^9.39.1",
|
||||
"@types/better-sqlite3": "^7.6.13",
|
||||
"@types/express": "^5.0.6",
|
||||
"@types/http-proxy-middleware": "^0.19.3",
|
||||
"@types/node": "^24.10.1",
|
||||
"@types/react": "^19.2.7",
|
||||
"@types/react-dom": "^19.2.3",
|
||||
"@vitejs/plugin-react": "^5.1.4",
|
||||
"eslint": "^9.39.1",
|
||||
"eslint-plugin-react-hooks": "^7.0.1",
|
||||
"eslint-plugin-react-refresh": "^0.4.24",
|
||||
"globals": "^16.5.0",
|
||||
"tsx": "^4.21.0",
|
||||
"typescript": "~5.9.3",
|
||||
"typescript-eslint": "^8.48.0",
|
||||
"vite": "^7.3.1"
|
||||
}
|
||||
}
|
||||
1
frontend/public/vite.svg
Normal file
1
frontend/public/vite.svg
Normal file
@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" class="iconify iconify--logos" width="31.88" height="32" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 257"><defs><linearGradient id="IconifyId1813088fe1fbc01fb466" x1="-.828%" x2="57.636%" y1="7.652%" y2="78.411%"><stop offset="0%" stop-color="#41D1FF"></stop><stop offset="100%" stop-color="#BD34FE"></stop></linearGradient><linearGradient id="IconifyId1813088fe1fbc01fb467" x1="43.376%" x2="50.316%" y1="2.242%" y2="89.03%"><stop offset="0%" stop-color="#FFEA83"></stop><stop offset="8.333%" stop-color="#FFDD35"></stop><stop offset="100%" stop-color="#FFA800"></stop></linearGradient></defs><path fill="url(#IconifyId1813088fe1fbc01fb466)" d="M255.153 37.938L134.897 252.976c-2.483 4.44-8.862 4.466-11.382.048L.875 37.958c-2.746-4.814 1.371-10.646 6.827-9.67l120.385 21.517a6.537 6.537 0 0 0 2.322-.004l117.867-21.483c5.438-.991 9.574 4.796 6.877 9.62Z"></path><path fill="url(#IconifyId1813088fe1fbc01fb467)" d="M185.432.063L96.44 17.501a3.268 3.268 0 0 0-2.634 3.014l-5.474 92.456a3.268 3.268 0 0 0 3.997 3.378l24.777-5.718c2.318-.535 4.413 1.507 3.936 3.838l-7.361 36.047c-.495 2.426 1.782 4.5 4.151 3.78l15.304-4.649c2.372-.72 4.652 1.36 4.15 3.788l-11.698 56.621c-.732 3.542 3.979 5.473 5.943 2.437l1.313-2.028l72.516-144.72c1.215-2.423-.88-5.186-3.54-4.672l-25.505 4.922c-2.396.462-4.435-1.77-3.759-4.114l16.646-57.705c.677-2.35-1.37-4.583-3.769-4.113Z"></path></svg>
|
||||
|
After Width: | Height: | Size: 1.5 KiB |
139
frontend/server.ts
Normal file
139
frontend/server.ts
Normal file
@ -0,0 +1,139 @@
|
||||
import express from "express";
|
||||
import { createServer as createViteServer } from "vite";
|
||||
import { createProxyMiddleware } from "http-proxy-middleware";
|
||||
import Database from "better-sqlite3";
|
||||
import path from "path";
|
||||
import { fileURLToPath } from "url";
|
||||
|
||||
const __filename = fileURLToPath(import.meta.url);
|
||||
const __dirname = path.dirname(__filename);
|
||||
|
||||
const db = new Database("tasks.db");
|
||||
|
||||
// Initiera databasen
|
||||
db.exec(`
|
||||
CREATE TABLE IF NOT EXISTS users (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
name TEXT NOT NULL UNIQUE,
|
||||
color TEXT NOT NULL,
|
||||
avatar TEXT DEFAULT 'UserIcon'
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS tasks (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
title TEXT NOT NULL,
|
||||
description TEXT,
|
||||
status TEXT NOT NULL CHECK (status IN ('pending', 'in_progress', 'completed')),
|
||||
points INTEGER DEFAULT 0,
|
||||
user_id INTEGER,
|
||||
is_recurring BOOLEAN DEFAULT 0,
|
||||
recurrence_period TEXT,
|
||||
due_date DATETIME,
|
||||
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
|
||||
FOREIGN KEY (user_id) REFERENCES users(id)
|
||||
);
|
||||
`);
|
||||
|
||||
// Migreringar (för säkerhets skull)
|
||||
try { db.prepare("ALTER TABLE tasks ADD COLUMN recurrence_period TEXT").run(); } catch (e) {}
|
||||
try { db.prepare("ALTER TABLE users ADD COLUMN avatar TEXT DEFAULT 'UserIcon'").run(); } catch (e) {}
|
||||
|
||||
async function startServer() {
|
||||
const app = express();
|
||||
|
||||
const BACKEND_URL = process.env.VITE_API_BASE_URL;
|
||||
|
||||
if (BACKEND_URL) {
|
||||
console.log(`Proxying /api requests to ${BACKEND_URL}`);
|
||||
app.use(createProxyMiddleware({
|
||||
target: BACKEND_URL,
|
||||
changeOrigin: true,
|
||||
pathFilter: "/api",
|
||||
}));
|
||||
}
|
||||
|
||||
app.use(express.json());
|
||||
|
||||
// API-rutter
|
||||
app.get("/api/users", (req, res) => {
|
||||
const users = db.prepare("SELECT * FROM users").all();
|
||||
res.json(users);
|
||||
});
|
||||
|
||||
app.post("/api/users", (req, res) => {
|
||||
const { name, color, avatar } = req.body;
|
||||
try {
|
||||
const info = db.prepare("INSERT INTO users (name, color, avatar) VALUES (?, ?, ?)").run(name, color, avatar || 'UserIcon');
|
||||
res.json({ id: info.lastInsertRowid, name, color, avatar: avatar || 'UserIcon' });
|
||||
} catch (e) {
|
||||
res.status(400).json({ error: "Användaren finns redan" });
|
||||
}
|
||||
});
|
||||
|
||||
app.get("/api/tasks", (req, res) => {
|
||||
const tasks = db.prepare(`
|
||||
SELECT tasks.*, users.name as user_name, users.color as user_color, users.avatar as user_avatar
|
||||
FROM tasks
|
||||
LEFT JOIN users ON tasks.user_id = users.id
|
||||
`).all();
|
||||
res.json(tasks);
|
||||
});
|
||||
|
||||
app.post("/api/tasks", (req, res) => {
|
||||
const { title, description, status, points, user_id, is_recurring, recurrence_period, due_date } = req.body;
|
||||
const info = db.prepare(`
|
||||
INSERT INTO tasks (title, description, status, points, user_id, is_recurring, recurrence_period, due_date)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
|
||||
`).run(title, description, status || 'pending', points || 0, user_id || null, is_recurring ? 1 : 0, recurrence_period || null, due_date || null);
|
||||
res.json({ id: info.lastInsertRowid, ...req.body });
|
||||
});
|
||||
|
||||
app.patch("/api/tasks/:id", (req, res) => {
|
||||
const { id } = req.params;
|
||||
const { status, user_id } = req.body;
|
||||
const existingTask = db.prepare("SELECT * FROM tasks WHERE id = ?").get(id) as any;
|
||||
if (!existingTask) return res.status(404).json({ error: "Hittade inte uppgiften" });
|
||||
|
||||
const updates = Object.keys(req.body).map(key => `${key} = ?`).join(", ");
|
||||
const values = Object.values(req.body);
|
||||
db.prepare(`UPDATE tasks SET ${updates} WHERE id = ?`).run(...values, id);
|
||||
|
||||
if (status === 'completed' && existingTask.is_recurring && existingTask.recurrence_period && existingTask.due_date) {
|
||||
const nextDueDate = new Date(existingTask.due_date);
|
||||
if (existingTask.recurrence_period === 'daily') nextDueDate.setDate(nextDueDate.getDate() + 1);
|
||||
else if (existingTask.recurrence_period === 'weekly') nextDueDate.setDate(nextDueDate.getDate() + 7);
|
||||
else if (existingTask.recurrence_period === 'biweekly') nextDueDate.setDate(nextDueDate.getDate() + 14);
|
||||
else if (existingTask.recurrence_period === 'monthly') nextDueDate.setMonth(nextDueDate.getMonth() + 1);
|
||||
|
||||
db.prepare(`
|
||||
INSERT INTO tasks (title, description, status, points, user_id, is_recurring, recurrence_period, due_date)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
|
||||
`).run(existingTask.title, existingTask.description, 'pending', existingTask.points, null, 1, existingTask.recurrence_period, nextDueDate.toISOString());
|
||||
}
|
||||
res.json({ success: true });
|
||||
});
|
||||
|
||||
app.delete("/api/tasks/:id", (req, res) => {
|
||||
db.prepare("DELETE FROM tasks WHERE id = ?").run(req.params.id);
|
||||
res.json({ success: true });
|
||||
});
|
||||
|
||||
// Vite integration
|
||||
if (process.env.NODE_ENV !== "production") {
|
||||
const vite = await createViteServer({
|
||||
server: { middlewareMode: true },
|
||||
appType: "spa",
|
||||
});
|
||||
app.use(vite.middlewares);
|
||||
} else {
|
||||
app.use(express.static(path.join(__dirname, "dist")));
|
||||
app.get("/{*path}", (req: any, res: any) => res.sendFile(path.join(__dirname, "dist", "index.html")));
|
||||
}
|
||||
|
||||
const PORT = 3000;
|
||||
app.listen(PORT, "0.0.0.0", () => {
|
||||
console.log(`Server körs på http://localhost:${PORT}`);
|
||||
});
|
||||
}
|
||||
|
||||
startServer();
|
||||
42
frontend/src/App.css
Normal file
42
frontend/src/App.css
Normal file
@ -0,0 +1,42 @@
|
||||
#root {
|
||||
max-width: 1280px;
|
||||
margin: 0 auto;
|
||||
padding: 2rem;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.logo {
|
||||
height: 6em;
|
||||
padding: 1.5em;
|
||||
will-change: filter;
|
||||
transition: filter 300ms;
|
||||
}
|
||||
.logo:hover {
|
||||
filter: drop-shadow(0 0 2em #646cffaa);
|
||||
}
|
||||
.logo.react:hover {
|
||||
filter: drop-shadow(0 0 2em #61dafbaa);
|
||||
}
|
||||
|
||||
@keyframes logo-spin {
|
||||
from {
|
||||
transform: rotate(0deg);
|
||||
}
|
||||
to {
|
||||
transform: rotate(360deg);
|
||||
}
|
||||
}
|
||||
|
||||
@media (prefers-reduced-motion: no-preference) {
|
||||
a:nth-of-type(2) .logo {
|
||||
animation: logo-spin infinite 20s linear;
|
||||
}
|
||||
}
|
||||
|
||||
.card {
|
||||
padding: 2em;
|
||||
}
|
||||
|
||||
.read-the-docs {
|
||||
color: #888;
|
||||
}
|
||||
29
frontend/src/App.jsx
Normal file
29
frontend/src/App.jsx
Normal file
@ -0,0 +1,29 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import apiClient from './api/client';
|
||||
|
||||
function App() {
|
||||
const [currentUser, setCurrentUser] = useState(null);
|
||||
|
||||
useEffect(() => {
|
||||
const verifySession = async () => {
|
||||
try {
|
||||
// Anrop till ett endpoint som returnerar nuvarande användare (t.ex. /users/me)
|
||||
const response = await apiClient.get('/users/me');
|
||||
setCurrentUser(response.data);
|
||||
} catch (err) {
|
||||
// Om detta misslyckas (t.ex. 401), kommer vår interceptor
|
||||
// att hantera utloggningen automatiskt.
|
||||
setCurrentUser(null);
|
||||
}
|
||||
};
|
||||
|
||||
if (localStorage.getItem('user')) {
|
||||
verifySession();
|
||||
}
|
||||
}, []);
|
||||
|
||||
return (
|
||||
/* Din övriga app-kod */
|
||||
<div>{currentUser ? `Inloggad som: ${currentUser.username}` : 'Ej inloggad'}</div>
|
||||
);
|
||||
}
|
||||
885
frontend/src/App.tsx
Normal file
885
frontend/src/App.tsx
Normal file
@ -0,0 +1,885 @@
|
||||
/**
|
||||
* @license
|
||||
* SPDX-License-Identifier: Apache-2.0
|
||||
*/
|
||||
|
||||
import React, { useState, useEffect, useCallback } from 'react';
|
||||
import {
|
||||
Plus,
|
||||
Trash2,
|
||||
User as UserIcon,
|
||||
CheckCircle2,
|
||||
Clock,
|
||||
PlayCircle,
|
||||
X,
|
||||
UserPlus,
|
||||
RefreshCw,
|
||||
Trophy,
|
||||
LogOut,
|
||||
Calendar,
|
||||
Search,
|
||||
Smile,
|
||||
Heart,
|
||||
Star,
|
||||
Zap,
|
||||
Coffee,
|
||||
Ghost,
|
||||
Cat,
|
||||
Dog,
|
||||
Gamepad2,
|
||||
Music,
|
||||
Camera,
|
||||
Pizza,
|
||||
ChevronDown,
|
||||
ChevronUp
|
||||
} from 'lucide-react';
|
||||
import { motion, AnimatePresence } from 'motion/react';
|
||||
import { API_BASE_URL } from './config';
|
||||
import Leaderboard from './components/Leaderboard';
|
||||
|
||||
type Status = 'pending' | 'in_progress' | 'completed';
|
||||
|
||||
interface User {
|
||||
id: number;
|
||||
name: string;
|
||||
color: string;
|
||||
avatar: string;
|
||||
}
|
||||
|
||||
const AVATARS = [
|
||||
{ name: 'UserIcon', icon: UserIcon },
|
||||
{ name: 'Smile', icon: Smile },
|
||||
{ name: 'Heart', icon: Heart },
|
||||
{ name: 'Star', icon: Star },
|
||||
{ name: 'Zap', icon: Zap },
|
||||
{ name: 'Coffee', icon: Coffee },
|
||||
{ name: 'Ghost', icon: Ghost },
|
||||
{ name: 'Cat', icon: Cat },
|
||||
{ name: 'Dog', icon: Dog },
|
||||
{ name: 'Gamepad2', icon: Gamepad2 },
|
||||
{ name: 'Music', icon: Music },
|
||||
{ name: 'Camera', icon: Camera },
|
||||
{ name: 'Pizza', icon: Pizza },
|
||||
];
|
||||
|
||||
const AvatarRenderer = ({ name, size = 24, className = "" }: { name: string, size?: number, className?: string }) => {
|
||||
const avatar = AVATARS.find(a => a.name === name) || AVATARS[0];
|
||||
const Icon = avatar.icon;
|
||||
return <Icon size={size} className={className} />;
|
||||
};
|
||||
|
||||
interface Task {
|
||||
id: number;
|
||||
title: string;
|
||||
description: string;
|
||||
status: Status;
|
||||
points: number;
|
||||
user_id: number | null;
|
||||
user_name: string | null;
|
||||
user_color: string | null;
|
||||
user_avatar: string | null;
|
||||
is_recurring: boolean;
|
||||
recurrence_period: string | null;
|
||||
due_date: string | null;
|
||||
}
|
||||
|
||||
const COLORS = [
|
||||
'bg-blue-500', 'bg-emerald-500', 'bg-violet-500',
|
||||
'bg-amber-500', 'bg-rose-500', 'bg-indigo-500',
|
||||
'bg-cyan-500', 'bg-orange-500'
|
||||
];
|
||||
|
||||
export default function App() {
|
||||
const [tasks, setTasks] = useState<Task[]>([]);
|
||||
const [users, setUsers] = useState<User[]>([]);
|
||||
const [currentUser, setCurrentUser] = useState<User | null>(() => {
|
||||
const saved = localStorage.getItem('hemkoll_user');
|
||||
return saved ? JSON.parse(saved) : null;
|
||||
});
|
||||
const [isTaskModalOpen, setIsTaskModalOpen] = useState(false);
|
||||
const [isUserModalOpen, setIsUserModalOpen] = useState(false);
|
||||
const [isLeaderboardOpen, setIsLeaderboardOpen] = useState(false);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [searchQuery, setSearchQuery] = useState('');
|
||||
const [expandedTasks, setExpandedTasks] = useState<Set<number>>(new Set());
|
||||
|
||||
const toggleTaskExpansion = (taskId: number) => {
|
||||
setExpandedTasks(prev => {
|
||||
const next = new Set(prev);
|
||||
if (next.has(taskId)) {
|
||||
next.delete(taskId);
|
||||
} else {
|
||||
next.add(taskId);
|
||||
}
|
||||
return next;
|
||||
});
|
||||
};
|
||||
|
||||
// Custom modal states
|
||||
const [confirmModal, setConfirmModal] = useState<{
|
||||
isOpen: boolean;
|
||||
title: string;
|
||||
message: string;
|
||||
onConfirm: () => void;
|
||||
}>({ isOpen: false, title: '', message: '', onConfirm: () => {} });
|
||||
|
||||
const [alertModal, setAlertModal] = useState<{
|
||||
isOpen: boolean;
|
||||
title: string;
|
||||
message: string;
|
||||
}>({ isOpen: false, title: '', message: '' });
|
||||
|
||||
const showAlert = (title: string, message: string) => {
|
||||
setAlertModal({ isOpen: true, title, message });
|
||||
};
|
||||
|
||||
const showConfirm = (title: string, message: string, onConfirm: () => void) => {
|
||||
setConfirmModal({ isOpen: true, title, message, onConfirm });
|
||||
};
|
||||
|
||||
const getTaskCardColor = (task: Task) => {
|
||||
if (task.status === 'completed' || !task.due_date) return 'bg-white border-black/5';
|
||||
|
||||
const dueDate = new Date(task.due_date);
|
||||
const now = new Date();
|
||||
const diffTime = dueDate.getTime() - now.getTime();
|
||||
const diffDays = diffTime / (1000 * 60 * 60 * 24);
|
||||
|
||||
if (diffTime < 0) return 'bg-red-50 border-red-200';
|
||||
if (diffDays <= 2) return 'bg-orange-50 border-orange-200';
|
||||
|
||||
return 'bg-white border-black/5';
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
if (currentUser) {
|
||||
localStorage.setItem('hemkoll_user', JSON.stringify(currentUser));
|
||||
} else {
|
||||
localStorage.removeItem('hemkoll_user');
|
||||
}
|
||||
}, [currentUser]);
|
||||
|
||||
// New task form state
|
||||
const [newTask, setNewTask] = useState({
|
||||
title: '',
|
||||
description: '',
|
||||
points: 5,
|
||||
user_id: null as number | null,
|
||||
is_recurring: false,
|
||||
recurrence_period: 'weekly',
|
||||
due_date: ''
|
||||
});
|
||||
|
||||
// New user form state
|
||||
const [newUserName, setNewUserName] = useState('');
|
||||
const [newUserAvatar, setNewUserAvatar] = useState('UserIcon');
|
||||
|
||||
const fetchData = useCallback(async () => {
|
||||
try {
|
||||
const [tasksRes, usersRes] = await Promise.all([
|
||||
fetch(`${API_BASE_URL}/api/tasks`),
|
||||
fetch(`${API_BASE_URL}/api/users`)
|
||||
]);
|
||||
const tasksData = await tasksRes.json();
|
||||
const usersData = await usersRes.json();
|
||||
setTasks(tasksData);
|
||||
setUsers(usersData);
|
||||
} catch (error) {
|
||||
console.error("Failed to fetch data", error);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
fetchData();
|
||||
}, [fetchData]);
|
||||
|
||||
const handleCreateTask = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
if (!newTask.title) return;
|
||||
|
||||
if (newTask.is_recurring && !newTask.due_date) {
|
||||
showAlert("Obs!", "En återkommande uppgift måste ha ett förfallodatum.");
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const res = await fetch(`${API_BASE_URL}/api/tasks`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
...newTask,
|
||||
status: 'pending',
|
||||
due_date: newTask.due_date || null,
|
||||
recurrence_period: newTask.is_recurring ? newTask.recurrence_period : null
|
||||
})
|
||||
});
|
||||
if (res.ok) {
|
||||
setIsTaskModalOpen(false);
|
||||
setNewTask({ title: '', description: '', points: 5, user_id: null, is_recurring: false, recurrence_period: 'weekly', due_date: '' });
|
||||
fetchData();
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Failed to create task", error);
|
||||
}
|
||||
};
|
||||
|
||||
const handleCreateUser = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
if (!newUserName) return;
|
||||
|
||||
const color = COLORS[Math.floor(Math.random() * COLORS.length)];
|
||||
try {
|
||||
const res = await fetch(`${API_BASE_URL}/api/users`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ name: newUserName, color, avatar: newUserAvatar })
|
||||
});
|
||||
if (res.ok) {
|
||||
setIsUserModalOpen(false);
|
||||
setNewUserName('');
|
||||
setNewUserAvatar('UserIcon');
|
||||
fetchData();
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Failed to create user", error);
|
||||
}
|
||||
};
|
||||
|
||||
const updateTaskStatus = async (taskId: number, newStatus: Status, userId?: number | null) => {
|
||||
const task = tasks.find(t => t.id === taskId);
|
||||
if (!task) return;
|
||||
|
||||
const effectiveUserId = userId !== undefined ? userId : task.user_id;
|
||||
|
||||
if (newStatus === 'in_progress' && !effectiveUserId) {
|
||||
showAlert("Obs!", "En pågående uppgift måste ha en ansvarig användare!");
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const res = await fetch(`${API_BASE_URL}/api/tasks/${taskId}`, {
|
||||
method: 'PATCH',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ status: newStatus, user_id: effectiveUserId })
|
||||
});
|
||||
if (res.ok) {
|
||||
fetchData();
|
||||
} else {
|
||||
const err = await res.json();
|
||||
showAlert("Ett fel uppstod", err.error || "Kunde inte uppdatera uppgift");
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Failed to update task", error);
|
||||
}
|
||||
};
|
||||
|
||||
const deleteTask = async (e: React.MouseEvent, id: number) => {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
|
||||
showConfirm(
|
||||
"Radera uppgift",
|
||||
"Är du säker på att du vill radera denna uppgift? Detta går inte att ångra.",
|
||||
async () => {
|
||||
try {
|
||||
const res = await fetch(`${API_BASE_URL}/api/tasks/${id}`, { method: 'DELETE' });
|
||||
if (res.ok) {
|
||||
fetchData();
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Failed to delete task", error);
|
||||
}
|
||||
}
|
||||
);
|
||||
};
|
||||
|
||||
const onDragStart = (e: React.DragEvent, taskId: number) => {
|
||||
e.dataTransfer.setData('taskId', taskId.toString());
|
||||
e.dataTransfer.effectAllowed = 'move';
|
||||
|
||||
// Add a ghost image or styling if needed, but standard is fine
|
||||
// We can also add a class to the body to help with styling during drag
|
||||
document.body.classList.add('is-dragging');
|
||||
};
|
||||
|
||||
const onDragEnd = () => {
|
||||
document.body.classList.remove('is-dragging');
|
||||
};
|
||||
|
||||
const onDrop = (e: React.DragEvent, newStatus: Status) => {
|
||||
e.preventDefault();
|
||||
const taskIdStr = e.dataTransfer.getData('taskId');
|
||||
if (!taskIdStr) return;
|
||||
|
||||
const taskId = parseInt(taskIdStr);
|
||||
if (isNaN(taskId)) return;
|
||||
|
||||
updateTaskStatus(taskId, newStatus);
|
||||
};
|
||||
|
||||
const onDragOver = (e: React.DragEvent) => {
|
||||
e.preventDefault();
|
||||
};
|
||||
|
||||
if (!currentUser && !loading) {
|
||||
if (users.length > 0) {
|
||||
return (
|
||||
<div className="min-h-screen bg-[#F5F5F4] flex items-center justify-center p-4 font-sans">
|
||||
<div className="bg-white p-8 rounded-3xl shadow-sm border border-black/5 w-full max-w-md">
|
||||
<h1 className="text-3xl font-semibold tracking-tight mb-6 text-center">Vem är du?</h1>
|
||||
<div className="grid grid-cols-2 gap-4 mb-6">
|
||||
{users.map(user => (
|
||||
<button
|
||||
key={user.id}
|
||||
onClick={() => setCurrentUser(user)}
|
||||
className="flex flex-col items-center p-4 rounded-2xl hover:bg-black/5 transition-colors border border-transparent hover:border-black/10"
|
||||
>
|
||||
<div className={`w-12 h-12 ${user.color} rounded-full flex items-center justify-center text-white mb-2 shadow-sm`}>
|
||||
<AvatarRenderer name={user.avatar} size={24} />
|
||||
</div>
|
||||
<span className="font-medium text-sm">{user.name}</span>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
<button
|
||||
onClick={() => setIsUserModalOpen(true)}
|
||||
className="w-full py-3 rounded-xl border-2 border-dashed border-black/10 text-black/40 hover:text-black/60 hover:border-black/20 transition-all flex items-center justify-center gap-2"
|
||||
>
|
||||
<UserPlus size={20} />
|
||||
<span>Lägg till användare</span>
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<AnimatePresence>
|
||||
{isUserModalOpen && (
|
||||
<div className="fixed inset-0 bg-black/40 backdrop-blur-sm flex items-center justify-center p-4 z-50">
|
||||
<motion.div
|
||||
initial={{ opacity: 0, scale: 0.95 }}
|
||||
animate={{ opacity: 1, scale: 1 }}
|
||||
exit={{ opacity: 0, scale: 0.95 }}
|
||||
className="bg-white p-6 rounded-3xl shadow-xl w-full max-w-sm"
|
||||
>
|
||||
<div className="flex justify-between items-center mb-4">
|
||||
<h2 className="text-xl font-bold">Ny Användare</h2>
|
||||
<button onClick={() => setIsUserModalOpen(false)} className="p-2 hover:bg-black/5 rounded-full"><X size={20} /></button>
|
||||
</div>
|
||||
<form onSubmit={handleCreateUser}>
|
||||
<div className="mb-4">
|
||||
<label className="block text-[10px] font-bold uppercase tracking-widest text-black/40 mb-2">Namn</label>
|
||||
<input
|
||||
autoFocus
|
||||
type="text"
|
||||
placeholder="Namn"
|
||||
className="w-full p-3 rounded-xl bg-black/5 border-none focus:ring-2 focus:ring-black/10"
|
||||
value={newUserName}
|
||||
onChange={e => setNewUserName(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="mb-6">
|
||||
<label className="block text-[10px] font-bold uppercase tracking-widest text-black/40 mb-2">Välj Ikon</label>
|
||||
<div className="grid grid-cols-5 gap-2 max-h-40 overflow-y-auto p-1">
|
||||
{AVATARS.map(avatar => (
|
||||
<button
|
||||
key={avatar.name}
|
||||
type="button"
|
||||
onClick={() => setNewUserAvatar(avatar.name)}
|
||||
className={`p-2 rounded-xl flex items-center justify-center transition-all ${newUserAvatar === avatar.name ? 'bg-black text-white scale-110 shadow-md' : 'bg-black/5 text-black/40 hover:bg-black/10'}`}
|
||||
>
|
||||
<avatar.icon size={20} />
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<button type="submit" className="w-full py-3 bg-black text-white rounded-xl font-medium hover:bg-black/80 transition-colors">
|
||||
Skapa
|
||||
</button>
|
||||
</form>
|
||||
</motion.div>
|
||||
</div>
|
||||
)}
|
||||
</AnimatePresence>
|
||||
</div>
|
||||
);
|
||||
} else {
|
||||
return (
|
||||
<div className="min-h-screen bg-[#F5F5F4] flex items-center justify-center p-4">
|
||||
<div className="bg-white p-8 rounded-3xl shadow-sm border border-black/5 w-full max-w-md text-center">
|
||||
<div className="w-16 h-16 bg-black/5 rounded-full flex items-center justify-center mx-auto mb-4">
|
||||
<UserPlus size={32} className="text-black/40" />
|
||||
</div>
|
||||
<h1 className="text-2xl font-bold mb-2">Välkommen till HemKoll</h1>
|
||||
<p className="text-black/60 mb-6">Börja med att skapa den första användaren för att komma igång.</p>
|
||||
<form onSubmit={handleCreateUser}>
|
||||
<div className="mb-4 text-left">
|
||||
<label className="block text-[10px] font-bold uppercase tracking-widest text-black/40 mb-2">Ditt namn</label>
|
||||
<input
|
||||
autoFocus
|
||||
type="text"
|
||||
placeholder="Ditt namn"
|
||||
className="w-full p-3 rounded-xl bg-black/5 border-none focus:ring-2 focus:ring-black/10"
|
||||
value={newUserName}
|
||||
onChange={e => setNewUserName(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="mb-6 text-left">
|
||||
<label className="block text-[10px] font-bold uppercase tracking-widest text-black/40 mb-2">Välj din ikon</label>
|
||||
<div className="grid grid-cols-5 gap-2 p-1">
|
||||
{AVATARS.map(avatar => (
|
||||
<button
|
||||
key={avatar.name}
|
||||
type="button"
|
||||
onClick={() => setNewUserAvatar(avatar.name)}
|
||||
className={`p-2 rounded-xl flex items-center justify-center transition-all ${newUserAvatar === avatar.name ? 'bg-black text-white scale-110 shadow-md' : 'bg-black/5 text-black/40 hover:bg-black/10'}`}
|
||||
>
|
||||
<avatar.icon size={20} />
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<button type="submit" className="w-full py-3 bg-black text-white rounded-xl font-medium hover:bg-black/80 transition-colors">
|
||||
Skapa Användare
|
||||
</button>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
const columns: { id: Status; title: string; icon: any; color: string }[] = [
|
||||
{ id: 'pending', title: 'Väntande', icon: Clock, color: 'text-amber-500' },
|
||||
{ id: 'in_progress', title: 'Pågående', icon: PlayCircle, color: 'text-blue-500' },
|
||||
{ id: 'completed', title: 'Klart', icon: CheckCircle2, color: 'text-emerald-500' },
|
||||
];
|
||||
|
||||
return (
|
||||
<div className="min-h-screen bg-[#F5F5F4] text-[#1A1A1A] font-sans">
|
||||
<header className="bg-white border-b border-black/5 px-6 py-4 flex items-center justify-between sticky top-0 z-30">
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="w-10 h-10 bg-black rounded-xl flex items-center justify-center text-white">
|
||||
<Trophy size={20} />
|
||||
</div>
|
||||
<div>
|
||||
<h1 className="font-bold text-lg leading-tight">HemKoll</h1>
|
||||
<p className="text-xs text-black/40 uppercase tracking-wider font-semibold">Dashboard</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-4 flex-1 max-w-md mx-8">
|
||||
<div className="relative w-full">
|
||||
<Search className="absolute left-3 top-1/2 -translate-y-1/2 text-black/20" size={16} />
|
||||
<input
|
||||
type="text"
|
||||
placeholder="Sök uppgifter..."
|
||||
className="w-full pl-10 pr-4 py-2 bg-black/5 border-none rounded-xl text-sm focus:ring-2 focus:ring-black/10 transition-all"
|
||||
value={searchQuery}
|
||||
onChange={e => setSearchQuery(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-4">
|
||||
<button
|
||||
onClick={() => setIsTaskModalOpen(true)}
|
||||
className="bg-black text-white px-4 py-2 rounded-xl flex items-center gap-2 text-sm font-medium hover:bg-black/80 transition-all active:scale-95"
|
||||
>
|
||||
<Plus size={18} />
|
||||
<span className="hidden sm:inline">Ny Uppgift</span>
|
||||
</button>
|
||||
|
||||
<div className="h-8 w-px bg-black/10 mx-2" />
|
||||
|
||||
<button
|
||||
onClick={() => setIsLeaderboardOpen(true)}
|
||||
className="flex items-center gap-2 p-1.5 pr-4 rounded-full hover:bg-yellow-50 text-black/60 hover:text-yellow-600 transition-all group border border-transparent hover:border-yellow-100"
|
||||
title="Leaderboard"
|
||||
>
|
||||
<Trophy size={20} />
|
||||
</button>
|
||||
|
||||
<button
|
||||
onClick={() => setCurrentUser(null)}
|
||||
className="flex items-center gap-2 p-1.5 pr-4 rounded-full hover:bg-red-50 text-black/60 hover:text-red-600 transition-all group border border-transparent hover:border-red-100"
|
||||
title="Logga ut"
|
||||
>
|
||||
<div className={`w-8 h-8 ${currentUser?.color} rounded-full flex items-center justify-center text-white shadow-sm`}>
|
||||
<AvatarRenderer name={currentUser?.avatar || 'UserIcon'} size={16} />
|
||||
</div>
|
||||
<div className="flex flex-col items-start">
|
||||
<span className="text-xs font-bold leading-none">{currentUser?.name}</span>
|
||||
<span className="text-[10px] font-medium opacity-50 group-hover:opacity-100 flex items-center gap-0.5">
|
||||
<LogOut size={10} />
|
||||
Logga ut
|
||||
</span>
|
||||
</div>
|
||||
</button>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<main className="p-6">
|
||||
<div className="grid grid-cols-1 md:grid-cols-3 gap-6 h-[calc(100vh-140px)]">
|
||||
{columns.map(col => (
|
||||
<div
|
||||
key={col.id}
|
||||
className="flex flex-col h-full"
|
||||
onDragOver={onDragOver}
|
||||
onDrop={(e) => onDrop(e, col.id)}
|
||||
>
|
||||
<div className="flex items-center justify-between mb-4 px-2">
|
||||
<div className="flex items-center gap-2">
|
||||
<col.icon size={18} className={col.color} />
|
||||
<h2 className="font-bold text-sm uppercase tracking-widest text-black/60">{col.title}</h2>
|
||||
<span className="bg-black/5 text-black/40 text-[10px] font-bold px-2 py-0.5 rounded-full">
|
||||
{tasks.filter(t => t.status === col.id).length}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex-1 bg-black/[0.02] rounded-3xl p-3 overflow-y-auto border border-black/5">
|
||||
<div className="space-y-3">
|
||||
{tasks
|
||||
.filter(t => t.status === col.id)
|
||||
.filter(t => t.title.toLowerCase().includes(searchQuery.toLowerCase()) || t.description.toLowerCase().includes(searchQuery.toLowerCase()))
|
||||
.sort((a, b) => {
|
||||
if (!a.due_date) return 1;
|
||||
if (!b.due_date) return -1;
|
||||
return new Date(a.due_date).getTime() - new Date(b.due_date).getTime();
|
||||
})
|
||||
.map(task => (
|
||||
<motion.div
|
||||
layoutId={`task-${task.id}`}
|
||||
key={task.id}
|
||||
draggable
|
||||
onDragStart={(e) => onDragStart(e as any, task.id)}
|
||||
onDragEnd={onDragEnd}
|
||||
className={`${getTaskCardColor(task)} p-4 rounded-2xl shadow-sm border cursor-grab active:cursor-grabbing hover:shadow-md transition-all group relative overflow-hidden`}
|
||||
>
|
||||
<div className="flex justify-between items-center gap-2">
|
||||
<div className="flex items-center gap-2 flex-1 min-w-0">
|
||||
<h3 className="font-semibold text-sm leading-snug truncate">{task.title}</h3>
|
||||
{!expandedTasks.has(task.id) && task.user_id && (
|
||||
<div className={`w-5 h-5 ${task.user_color} rounded-full flex items-center justify-center text-white shadow-sm flex-shrink-0`}>
|
||||
<AvatarRenderer name={task.user_avatar || 'UserIcon'} size={10} />
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<div className="flex items-center gap-1">
|
||||
{expandedTasks.has(task.id) && (
|
||||
<button
|
||||
onClick={(e) => deleteTask(e, task.id)}
|
||||
className="text-black/20 hover:text-red-500 transition-colors p-1 rounded-lg hover:bg-red-50"
|
||||
>
|
||||
<Trash2 size={14} />
|
||||
</button>
|
||||
)}
|
||||
<button
|
||||
onClick={(e) => { e.stopPropagation(); toggleTaskExpansion(task.id); }}
|
||||
className="text-black/20 hover:text-black/60 p-1 rounded-lg hover:bg-black/5 transition-all"
|
||||
>
|
||||
{expandedTasks.has(task.id) ? <ChevronUp size={16} /> : <ChevronDown size={16} />}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<AnimatePresence>
|
||||
{expandedTasks.has(task.id) && (
|
||||
<motion.div
|
||||
initial={{ height: 0, opacity: 0 }}
|
||||
animate={{ height: 'auto', opacity: 1 }}
|
||||
exit={{ height: 0, opacity: 0 }}
|
||||
className="overflow-hidden"
|
||||
>
|
||||
<div className="pt-3 border-t border-black/5 mt-3">
|
||||
{task.description && (
|
||||
<p className="text-xs text-black/50 mb-3">
|
||||
{task.description}
|
||||
</p>
|
||||
)}
|
||||
|
||||
{task.due_date && (
|
||||
<div className="flex items-center gap-1 text-[10px] text-black/40 mb-3">
|
||||
{(() => {
|
||||
const dateStr = task.due_date;
|
||||
|
||||
if (!dateStr) return null;
|
||||
const date = new Date(dateStr);
|
||||
|
||||
return (
|
||||
<>
|
||||
<Calendar size={12} className={date < new Date() && task.status !== 'completed' ? 'text-red-500' : ''} />
|
||||
<span className={date < new Date() && task.status !== 'completed' ? 'text-red-500 font-bold' : ''}>
|
||||
{date.toLocaleString('sv-SE', {
|
||||
month: 'short',
|
||||
day: 'numeric'
|
||||
})}
|
||||
</span>
|
||||
</>
|
||||
);
|
||||
})()}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="flex items-center justify-between mt-auto">
|
||||
<div className="flex items-center gap-1.5">
|
||||
<div className="bg-black/5 px-2 py-1 rounded-lg flex items-center gap-1">
|
||||
<Trophy size={10} className="text-amber-500" />
|
||||
<span className="text-[10px] font-bold">{task.points}</span>
|
||||
</div>
|
||||
{task.is_recurring && (
|
||||
<div className="bg-blue-50 text-blue-500 px-2 py-1 rounded-lg flex items-center gap-1">
|
||||
<RefreshCw size={10} />
|
||||
<span className="text-[10px] font-bold">
|
||||
{task.recurrence_period === 'daily' && 'Dagligen'}
|
||||
{task.recurrence_period === 'weekly' && 'Veckovis'}
|
||||
{task.recurrence_period === 'biweekly' && 'Varannan vecka'}
|
||||
{task.recurrence_period === 'monthly' && 'Månadsvis'}
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{task.user_id ? (
|
||||
<div className="flex items-center gap-1.5">
|
||||
<span className="text-[10px] font-medium text-black/40">
|
||||
{task.user_name}
|
||||
</span>
|
||||
<div className={`w-6 h-6 ${task.user_color} rounded-full flex items-center justify-center text-white shadow-sm`}>
|
||||
<AvatarRenderer name={task.user_avatar || 'UserIcon'} size={12} />
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<button
|
||||
onClick={(e) => { e.stopPropagation(); updateTaskStatus(task.id, task.status, currentUser?.id); }}
|
||||
className="text-[10px] font-bold text-black/30 hover:text-black/60 flex items-center gap-1"
|
||||
>
|
||||
<UserPlus size={12} />
|
||||
<span>Ta uppgift</span>
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</motion.div>
|
||||
)}
|
||||
</AnimatePresence>
|
||||
</motion.div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</main>
|
||||
|
||||
<AnimatePresence>
|
||||
{isTaskModalOpen && (
|
||||
<div className="fixed inset-0 bg-black/40 backdrop-blur-sm flex items-center justify-center p-4 z-50">
|
||||
<motion.div
|
||||
initial={{ opacity: 0, y: 20 }}
|
||||
animate={{ opacity: 1, y: 0 }}
|
||||
exit={{ opacity: 0, y: 20 }}
|
||||
className="bg-white p-8 rounded-[32px] shadow-2xl w-full max-w-lg border border-black/5"
|
||||
>
|
||||
<div className="flex justify-between items-center mb-6">
|
||||
<h2 className="text-2xl font-bold tracking-tight">Skapa ny uppgift</h2>
|
||||
<button onClick={() => setIsTaskModalOpen(false)} className="p-2 hover:bg-black/5 rounded-full transition-colors">
|
||||
<X size={24} />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<form onSubmit={handleCreateTask} className="space-y-6">
|
||||
<div>
|
||||
<label className="block text-[10px] font-bold uppercase tracking-widest text-black/40 mb-2">Titel</label>
|
||||
<input
|
||||
autoFocus
|
||||
required
|
||||
type="text"
|
||||
placeholder="Vad behöver göras?"
|
||||
className="w-full p-4 rounded-2xl bg-black/5 border-none focus:ring-2 focus:ring-black/10 text-lg"
|
||||
value={newTask.title}
|
||||
onChange={e => setNewTask({...newTask, title: e.target.value})}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label className="block text-[10px] font-bold uppercase tracking-widest text-black/40 mb-2">Beskrivning (valfritt)</label>
|
||||
<textarea
|
||||
placeholder="Mer detaljer..."
|
||||
className="w-full p-4 rounded-2xl bg-black/5 border-none focus:ring-2 focus:ring-black/10 min-h-[100px] resize-none"
|
||||
value={newTask.description}
|
||||
onChange={e => setNewTask({...newTask, description: e.target.value})}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-2 gap-6">
|
||||
<div>
|
||||
<label className="block text-[10px] font-bold uppercase tracking-widest text-black/40 mb-2">Poäng (1-100)</label>
|
||||
<div className="flex items-center gap-3">
|
||||
<input
|
||||
type="range"
|
||||
min="1"
|
||||
max="100"
|
||||
className="flex-1 accent-black"
|
||||
value={newTask.points}
|
||||
onChange={e => setNewTask({...newTask, points: parseInt(e.target.value)})}
|
||||
/>
|
||||
<span className="font-mono font-bold text-lg w-10">{newTask.points}</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label className="block text-[10px] font-bold uppercase tracking-widest text-black/40 mb-2">Tilldela</label>
|
||||
<select
|
||||
className="w-full p-3 rounded-xl bg-black/5 border-none focus:ring-2 focus:ring-black/10 text-sm"
|
||||
value={newTask.user_id || ''}
|
||||
onChange={e => setNewTask({...newTask, user_id: e.target.value ? parseInt(e.target.value) : null})}
|
||||
>
|
||||
<option value="">Ingen</option>
|
||||
{users.map(u => <option key={u.id} value={u.id}>{u.name}</option>)}
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label className="block text-[10px] font-bold uppercase tracking-widest text-black/40 mb-2">Deadline (valfritt)</label>
|
||||
<input
|
||||
type="date"
|
||||
className="w-full p-4 rounded-2xl bg-black/5 border-none focus:ring-2 focus:ring-black/10 text-sm"
|
||||
value={newTask.due_date}
|
||||
onChange={e => setNewTask({...newTask, due_date: e.target.value})}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="space-y-4">
|
||||
<div className="flex items-center gap-3 p-4 rounded-2xl bg-black/5">
|
||||
<input
|
||||
type="checkbox"
|
||||
id="recurring"
|
||||
className="w-5 h-5 accent-black rounded-lg"
|
||||
checked={newTask.is_recurring}
|
||||
onChange={e => setNewTask({...newTask, is_recurring: e.target.checked})}
|
||||
/>
|
||||
<label htmlFor="recurring" className="text-sm font-medium cursor-pointer">Återkommande uppgift</label>
|
||||
</div>
|
||||
|
||||
<AnimatePresence>
|
||||
{newTask.is_recurring && (
|
||||
<motion.div
|
||||
initial={{ height: 0, opacity: 0 }}
|
||||
animate={{ height: 'auto', opacity: 1 }}
|
||||
exit={{ height: 0, opacity: 0 }}
|
||||
className="overflow-hidden"
|
||||
>
|
||||
<div className="p-4 rounded-2xl bg-black/5 space-y-3">
|
||||
<label className="block text-[10px] font-bold uppercase tracking-widest text-black/40">Periodicitet</label>
|
||||
<select
|
||||
className="w-full p-3 rounded-xl bg-white border-none focus:ring-2 focus:ring-black/10 text-sm"
|
||||
value={newTask.recurrence_period}
|
||||
onChange={e => setNewTask({...newTask, recurrence_period: e.target.value})}
|
||||
>
|
||||
<option value="daily">Dagligen</option>
|
||||
<option value="weekly">Veckovis</option>
|
||||
<option value="biweekly">Varannan vecka</option>
|
||||
<option value="monthly">Månadsvis</option>
|
||||
</select>
|
||||
<p className="text-[10px] text-black/40 italic">En ny uppgift skapas automatiskt när denna markeras som klar.</p>
|
||||
</div>
|
||||
</motion.div>
|
||||
)}
|
||||
</AnimatePresence>
|
||||
</div>
|
||||
|
||||
<button type="submit" className="w-full py-4 bg-black text-white rounded-2xl font-bold text-lg hover:bg-black/80 transition-all active:scale-[0.98] shadow-lg shadow-black/10">
|
||||
Skapa Uppgift
|
||||
</button>
|
||||
</form>
|
||||
</motion.div>
|
||||
</div>
|
||||
)}
|
||||
</AnimatePresence>
|
||||
|
||||
{/* Leaderboard Modal */}
|
||||
<AnimatePresence>
|
||||
{isLeaderboardOpen && (
|
||||
<div className="fixed inset-0 bg-black/40 backdrop-blur-sm flex items-center justify-center p-4 z-[100]">
|
||||
<motion.div
|
||||
initial={{ opacity: 0, scale: 0.95 }}
|
||||
animate={{ opacity: 1, scale: 1 }}
|
||||
exit={{ opacity: 0, scale: 0.95 }}
|
||||
className="bg-white p-6 rounded-3xl shadow-2xl w-full max-w-sm border border-black/5 max-h-[80vh] overflow-y-auto"
|
||||
>
|
||||
<div className="flex justify-between items-center mb-4">
|
||||
<button onClick={() => setIsLeaderboardOpen(false)} className="p-2 hover:bg-black/5 rounded-full ml-auto">
|
||||
<X size={20} />
|
||||
</button>
|
||||
</div>
|
||||
<Leaderboard />
|
||||
</motion.div>
|
||||
</div>
|
||||
)}
|
||||
</AnimatePresence>
|
||||
|
||||
{/* Custom Alert Modal */}
|
||||
<AnimatePresence>
|
||||
{alertModal.isOpen && (
|
||||
<div className="fixed inset-0 bg-black/40 backdrop-blur-sm flex items-center justify-center p-4 z-[100]">
|
||||
<motion.div
|
||||
initial={{ opacity: 0, scale: 0.95 }}
|
||||
animate={{ opacity: 1, scale: 1 }}
|
||||
exit={{ opacity: 0, scale: 0.95 }}
|
||||
className="bg-white p-6 rounded-3xl shadow-2xl w-full max-w-sm border border-black/5"
|
||||
>
|
||||
<h3 className="text-xl font-bold mb-2">{alertModal.title}</h3>
|
||||
<p className="text-black/60 mb-6">{alertModal.message}</p>
|
||||
<button
|
||||
onClick={() => setAlertModal({ ...alertModal, isOpen: false })}
|
||||
className="w-full py-3 bg-black text-white rounded-xl font-bold hover:bg-black/80 transition-all"
|
||||
>
|
||||
Okej
|
||||
</button>
|
||||
</motion.div>
|
||||
</div>
|
||||
)}
|
||||
</AnimatePresence>
|
||||
|
||||
{/* Custom Confirm Modal */}
|
||||
<AnimatePresence>
|
||||
{confirmModal.isOpen && (
|
||||
<div className="fixed inset-0 bg-black/40 backdrop-blur-sm flex items-center justify-center p-4 z-[100]">
|
||||
<motion.div
|
||||
initial={{ opacity: 0, scale: 0.95 }}
|
||||
animate={{ opacity: 1, scale: 1 }}
|
||||
exit={{ opacity: 0, scale: 0.95 }}
|
||||
className="bg-white p-6 rounded-3xl shadow-2xl w-full max-w-sm border border-black/5"
|
||||
>
|
||||
<h3 className="text-xl font-bold mb-2">{confirmModal.title}</h3>
|
||||
<p className="text-black/60 mb-6">{confirmModal.message}</p>
|
||||
<div className="flex gap-3">
|
||||
<button
|
||||
onClick={() => setConfirmModal({ ...confirmModal, isOpen: false })}
|
||||
className="flex-1 py-3 bg-black/5 text-black rounded-xl font-bold hover:bg-black/10 transition-all"
|
||||
>
|
||||
Avbryt
|
||||
</button>
|
||||
<button
|
||||
onClick={() => {
|
||||
confirmModal.onConfirm();
|
||||
setConfirmModal({ ...confirmModal, isOpen: false });
|
||||
}}
|
||||
className="flex-1 py-3 bg-red-500 text-white rounded-xl font-bold hover:bg-red-600 transition-all shadow-lg shadow-red-500/20"
|
||||
>
|
||||
Radera
|
||||
</button>
|
||||
</div>
|
||||
</motion.div>
|
||||
</div>
|
||||
)}
|
||||
</AnimatePresence>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
27
frontend/src/api/client.js
Normal file
27
frontend/src/api/client.js
Normal file
@ -0,0 +1,27 @@
|
||||
import axios from 'axios';
|
||||
|
||||
const apiClient = axios.create({
|
||||
baseURL: import.meta.env.VITE_API_BASE_URL + '/api',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'Cache-Control': 'no-cache, no-store, must-revalidate',
|
||||
'Pragma': 'no-cache',
|
||||
'Expires': '0',
|
||||
},
|
||||
});
|
||||
|
||||
// Interceptor för att fånga upp om sessionen är ogiltig (t.ex. efter backend-omstart)
|
||||
apiClient.interceptors.response.use(
|
||||
(response) => response,
|
||||
(error) => {
|
||||
if (error.response && error.response.status === 401) {
|
||||
// Om backenden säger att vi inte är inloggade, rensa lokal state
|
||||
localStorage.removeItem('user');
|
||||
localStorage.removeItem('token');
|
||||
window.location.href = '/login';
|
||||
}
|
||||
return Promise.reject(error);
|
||||
}
|
||||
);
|
||||
|
||||
export default apiClient;
|
||||
1
frontend/src/assets/react.svg
Normal file
1
frontend/src/assets/react.svg
Normal file
@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" class="iconify iconify--logos" width="35.93" height="32" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 228"><path fill="#00D8FF" d="M210.483 73.824a171.49 171.49 0 0 0-8.24-2.597c.465-1.9.893-3.777 1.273-5.621c6.238-30.281 2.16-54.676-11.769-62.708c-13.355-7.7-35.196.329-57.254 19.526a171.23 171.23 0 0 0-6.375 5.848a155.866 155.866 0 0 0-4.241-3.917C100.759 3.829 77.587-4.822 63.673 3.233C50.33 10.957 46.379 33.89 51.995 62.588a170.974 170.974 0 0 0 1.892 8.48c-3.28.932-6.445 1.924-9.474 2.98C17.309 83.498 0 98.307 0 113.668c0 15.865 18.582 31.778 46.812 41.427a145.52 145.52 0 0 0 6.921 2.165a167.467 167.467 0 0 0-2.01 9.138c-5.354 28.2-1.173 50.591 12.134 58.266c13.744 7.926 36.812-.22 59.273-19.855a145.567 145.567 0 0 0 5.342-4.923a168.064 168.064 0 0 0 6.92 6.314c21.758 18.722 43.246 26.282 56.54 18.586c13.731-7.949 18.194-32.003 12.4-61.268a145.016 145.016 0 0 0-1.535-6.842c1.62-.48 3.21-.974 4.76-1.488c29.348-9.723 48.443-25.443 48.443-41.52c0-15.417-17.868-30.326-45.517-39.844Zm-6.365 70.984c-1.4.463-2.836.91-4.3 1.345c-3.24-10.257-7.612-21.163-12.963-32.432c5.106-11 9.31-21.767 12.459-31.957c2.619.758 5.16 1.557 7.61 2.4c23.69 8.156 38.14 20.213 38.14 29.504c0 9.896-15.606 22.743-40.946 31.14Zm-10.514 20.834c2.562 12.94 2.927 24.64 1.23 33.787c-1.524 8.219-4.59 13.698-8.382 15.893c-8.067 4.67-25.32-1.4-43.927-17.412a156.726 156.726 0 0 1-6.437-5.87c7.214-7.889 14.423-17.06 21.459-27.246c12.376-1.098 24.068-2.894 34.671-5.345a134.17 134.17 0 0 1 1.386 6.193ZM87.276 214.515c-7.882 2.783-14.16 2.863-17.955.675c-8.075-4.657-11.432-22.636-6.853-46.752a156.923 156.923 0 0 1 1.869-8.499c10.486 2.32 22.093 3.988 34.498 4.994c7.084 9.967 14.501 19.128 21.976 27.15a134.668 134.668 0 0 1-4.877 4.492c-9.933 8.682-19.886 14.842-28.658 17.94ZM50.35 144.747c-12.483-4.267-22.792-9.812-29.858-15.863c-6.35-5.437-9.555-10.836-9.555-15.216c0-9.322 13.897-21.212 37.076-29.293c2.813-.98 5.757-1.905 8.812-2.773c3.204 10.42 7.406 21.315 12.477 32.332c-5.137 11.18-9.399 22.249-12.634 32.792a134.718 134.718 0 0 1-6.318-1.979Zm12.378-84.26c-4.811-24.587-1.616-43.134 6.425-47.789c8.564-4.958 27.502 2.111 47.463 19.835a144.318 144.318 0 0 1 3.841 3.545c-7.438 7.987-14.787 17.08-21.808 26.988c-12.04 1.116-23.565 2.908-34.161 5.309a160.342 160.342 0 0 1-1.76-7.887Zm110.427 27.268a347.8 347.8 0 0 0-7.785-12.803c8.168 1.033 15.994 2.404 23.343 4.08c-2.206 7.072-4.956 14.465-8.193 22.045a381.151 381.151 0 0 0-7.365-13.322Zm-45.032-43.861c5.044 5.465 10.096 11.566 15.065 18.186a322.04 322.04 0 0 0-30.257-.006c4.974-6.559 10.069-12.652 15.192-18.18ZM82.802 87.83a323.167 323.167 0 0 0-7.227 13.238c-3.184-7.553-5.909-14.98-8.134-22.152c7.304-1.634 15.093-2.97 23.209-3.984a321.524 321.524 0 0 0-7.848 12.897Zm8.081 65.352c-8.385-.936-16.291-2.203-23.593-3.793c2.26-7.3 5.045-14.885 8.298-22.6a321.187 321.187 0 0 0 7.257 13.246c2.594 4.48 5.28 8.868 8.038 13.147Zm37.542 31.03c-5.184-5.592-10.354-11.779-15.403-18.433c4.902.192 9.899.29 14.978.29c5.218 0 10.376-.117 15.453-.343c-4.985 6.774-10.018 12.97-15.028 18.486Zm52.198-57.817c3.422 7.8 6.306 15.345 8.596 22.52c-7.422 1.694-15.436 3.058-23.88 4.071a382.417 382.417 0 0 0 7.859-13.026a347.403 347.403 0 0 0 7.425-13.565Zm-16.898 8.101a358.557 358.557 0 0 1-12.281 19.815a329.4 329.4 0 0 1-23.444.823c-7.967 0-15.716-.248-23.178-.732a310.202 310.202 0 0 1-12.513-19.846h.001a307.41 307.41 0 0 1-10.923-20.627a310.278 310.278 0 0 1 10.89-20.637l-.001.001a307.318 307.318 0 0 1 12.413-19.761c7.613-.576 15.42-.876 23.31-.876H128c7.926 0 15.743.303 23.354.883a329.357 329.357 0 0 1 12.335 19.695a358.489 358.489 0 0 1 11.036 20.54a329.472 329.472 0 0 1-11 20.722Zm22.56-122.124c8.572 4.944 11.906 24.881 6.52 51.026c-.344 1.668-.73 3.367-1.15 5.09c-10.622-2.452-22.155-4.275-34.23-5.408c-7.034-10.017-14.323-19.124-21.64-27.008a160.789 160.789 0 0 1 5.888-5.4c18.9-16.447 36.564-22.941 44.612-18.3ZM128 90.808c12.625 0 22.86 10.235 22.86 22.86s-10.235 22.86-22.86 22.86s-22.86-10.235-22.86-22.86s10.235-22.86 22.86-22.86Z"></path></svg>
|
||||
|
After Width: | Height: | Size: 4.0 KiB |
24
frontend/src/components/Dashboard.jsx
Normal file
24
frontend/src/components/Dashboard.jsx
Normal file
@ -0,0 +1,24 @@
|
||||
import React from 'react';
|
||||
import LeaderboardOverlay from './LeaderboardOverlay';
|
||||
|
||||
const Dashboard = () => {
|
||||
return (
|
||||
<div style={{ padding: '2rem', maxWidth: '800px', margin: '0 auto' }}>
|
||||
<header style={{ marginBottom: '2rem' }}>
|
||||
<h1>Hushålls-Dashboard</h1>
|
||||
<p>Välkommen till din översikt av sysslor.</p>
|
||||
</header>
|
||||
|
||||
<main>
|
||||
{/* Här skulle din lista med Tasks ligga */}
|
||||
<div style={{ padding: '2rem', background: '#f9f9f9', borderRadius: '8px' }}>
|
||||
<p>Här visas dina aktiva uppgifter...</p>
|
||||
</div>
|
||||
</main>
|
||||
|
||||
<LeaderboardOverlay />
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default Dashboard;
|
||||
64
frontend/src/components/Leaderboard.jsx
Normal file
64
frontend/src/components/Leaderboard.jsx
Normal file
@ -0,0 +1,64 @@
|
||||
import React, { useEffect, useState } from 'react';
|
||||
import { getLeaderboard } from '../services/userService';
|
||||
|
||||
const Leaderboard = () => {
|
||||
const [scores, setScores] = useState([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState(null);
|
||||
|
||||
useEffect(() => {
|
||||
const fetchLeaderboard = async () => {
|
||||
try {
|
||||
const data = await getLeaderboard();
|
||||
// Sortera fallande baserat på poäng (om backenden inte redan gjort det)
|
||||
const sortedData = data.sort((a, b) => b.totalPoints - a.totalPoints);
|
||||
setScores(sortedData);
|
||||
} catch (err) {
|
||||
setError('Kunde inte hämta topplistan.');
|
||||
console.error(err);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
fetchLeaderboard();
|
||||
}, []);
|
||||
|
||||
if (loading) return <p>Laddar topplistan...</p>;
|
||||
if (error) return <p style={{ color: 'red' }}>{error}</p>;
|
||||
|
||||
return (
|
||||
<div className="leaderboard-container" style={{ padding: '0' }}>
|
||||
<h2>Topplista - Flest poäng</h2>
|
||||
<table style={{ width: '100%', borderCollapse: 'collapse', marginTop: '1rem' }}>
|
||||
<thead>
|
||||
<tr style={{ borderBottom: '2px solid #ccc', textAlign: 'left' }}>
|
||||
<th style={{ padding: '8px' }}>Rank</th>
|
||||
<th style={{ padding: '8px' }}>Användare</th>
|
||||
<th style={{ padding: '8px' }}>Totala Poäng</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{scores.map((entry, index) => (
|
||||
<tr
|
||||
key={entry.username}
|
||||
style={{
|
||||
borderBottom: '1px solid #eee',
|
||||
backgroundColor: index === 0 ? '#fffef0' : 'transparent' // Guld-aktig för vinnaren
|
||||
}}
|
||||
>
|
||||
<td style={{ padding: '8px', fontWeight: index < 3 ? 'bold' : 'normal' }}>
|
||||
{index === 0 ? '🥇' : index === 1 ? '🥈' : index === 2 ? '🥉' : index + 1}
|
||||
</td>
|
||||
<td style={{ padding: '8px' }}>{entry.username}</td>
|
||||
<td style={{ padding: '8px', fontWeight: 'bold' }}>{entry.totalPoints} p</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
{scores.length === 0 && <p>Inga poäng registrerade ännu!</p>}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default Leaderboard;
|
||||
96
frontend/src/components/LeaderboardOverlay.jsx
Normal file
96
frontend/src/components/LeaderboardOverlay.jsx
Normal file
@ -0,0 +1,96 @@
|
||||
import React, { useState } from 'react';
|
||||
import Leaderboard from './Leaderboard';
|
||||
|
||||
const LeaderboardOverlay = () => {
|
||||
const [isOpen, setIsOpen] = useState(false);
|
||||
|
||||
const toggleModal = () => setIsOpen(!isOpen);
|
||||
|
||||
// Stil för modal-overlay (bakgrunden)
|
||||
const overlayStyle = {
|
||||
position: 'fixed',
|
||||
top: 0,
|
||||
left: 0,
|
||||
width: '100vw',
|
||||
height: '100vh',
|
||||
backgroundColor: 'rgba(0, 0, 0, 0.7)',
|
||||
display: 'flex',
|
||||
justifyContent: 'center',
|
||||
alignItems: 'center',
|
||||
zIndex: 1000,
|
||||
};
|
||||
|
||||
// Stil för själva modal-fönstret
|
||||
const modalStyle = {
|
||||
backgroundColor: 'white',
|
||||
padding: '2rem',
|
||||
borderRadius: '12px',
|
||||
position: 'relative',
|
||||
width: '90%',
|
||||
maxWidth: '500px',
|
||||
boxShadow: '0 4px 20px rgba(0,0,0,0.3)',
|
||||
maxHeight: '80vh',
|
||||
overflowY: 'auto'
|
||||
};
|
||||
|
||||
// Stil för stäng-knappen
|
||||
const closeButtonStyle = {
|
||||
position: 'absolute',
|
||||
top: '10px',
|
||||
right: '10px',
|
||||
border: 'none',
|
||||
background: 'none',
|
||||
fontSize: '1.5rem',
|
||||
cursor: 'pointer',
|
||||
color: '#666'
|
||||
};
|
||||
|
||||
// Stil för pokal-ikonen
|
||||
const iconButtonStyle = {
|
||||
background: '#f0f0f0',
|
||||
border: 'none',
|
||||
borderRadius: '50%',
|
||||
width: '50px',
|
||||
height: '50px',
|
||||
display: 'flex',
|
||||
justifyContent: 'center',
|
||||
alignItems: 'center',
|
||||
cursor: 'pointer',
|
||||
fontSize: '1.5rem',
|
||||
boxShadow: '0 2px 5px rgba(0,0,0,0.1)',
|
||||
transition: 'transform 0.2s',
|
||||
position: 'fixed',
|
||||
bottom: '30px',
|
||||
right: '30px',
|
||||
zIndex: 900,
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
{/* Pokal-ikon som fungerar som knapp */}
|
||||
<button
|
||||
onClick={toggleModal}
|
||||
style={iconButtonStyle}
|
||||
onMouseOver={(e) => e.currentTarget.style.transform = 'scale(1.1)'}
|
||||
onMouseOut={(e) => e.currentTarget.style.transform = 'scale(1)'}
|
||||
title="Visa Topplista"
|
||||
>
|
||||
🏆
|
||||
</button>
|
||||
|
||||
{/* Själva modalen */}
|
||||
{isOpen && (
|
||||
<div style={overlayStyle} onClick={toggleModal}>
|
||||
<div style={modalStyle} onClick={(e) => e.stopPropagation()}>
|
||||
<button style={closeButtonStyle} onClick={toggleModal}>
|
||||
×
|
||||
</button>
|
||||
<Leaderboard />
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
export default LeaderboardOverlay;
|
||||
9
frontend/src/config.ts
Normal file
9
frontend/src/config.ts
Normal file
@ -0,0 +1,9 @@
|
||||
/**
|
||||
* Configuration for the application.
|
||||
*
|
||||
* VITE_API_BASE_URL can be set in .env files to point to different backends.
|
||||
* - If empty (default), it uses relative paths (works with server.ts fake backend).
|
||||
* - Set to 'http://localhost:3000' for a local backend running separately.
|
||||
* - Set to 'https://rubble.se/householdmanager' for production.
|
||||
*/
|
||||
export const API_BASE_URL = import.meta.env.VITE_API_BASE_URL || '';
|
||||
10
frontend/src/index.css
Normal file
10
frontend/src/index.css
Normal file
@ -0,0 +1,10 @@
|
||||
@import url('https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap');
|
||||
@import "tailwindcss";
|
||||
|
||||
@theme {
|
||||
--font-sans: "Inter", ui-sans-serif, system-ui, sans-serif;
|
||||
}
|
||||
|
||||
body {
|
||||
@apply antialiased text-slate-900;
|
||||
}
|
||||
10
frontend/src/main.tsx
Normal file
10
frontend/src/main.tsx
Normal file
@ -0,0 +1,10 @@
|
||||
import { StrictMode } from 'react'
|
||||
import { createRoot } from 'react-dom/client'
|
||||
import './index.css'
|
||||
import App from './App.tsx'
|
||||
|
||||
createRoot(document.getElementById('root')!).render(
|
||||
<StrictMode>
|
||||
<App />
|
||||
</StrictMode>,
|
||||
)
|
||||
30
frontend/src/services/userService.js
Normal file
30
frontend/src/services/userService.js
Normal file
@ -0,0 +1,30 @@
|
||||
import apiClient from '../api/client';
|
||||
|
||||
export const registerUser = async (userData) => {
|
||||
localStorage.clear();
|
||||
sessionStorage.clear();
|
||||
|
||||
const response = await apiClient.post('/users/register', userData);
|
||||
return response.data;
|
||||
};
|
||||
|
||||
export const loginUser = async (credentials) => {
|
||||
// Rensa allt innan login för att tvinga bort "spökanvändare"
|
||||
localStorage.clear();
|
||||
sessionStorage.clear();
|
||||
|
||||
const response = await apiClient.post('/auth/login', credentials);
|
||||
|
||||
// Spara den NYA användaren direkt i localStorage så att den finns vid omladdning
|
||||
localStorage.setItem('user', JSON.stringify(response.data));
|
||||
|
||||
// Tips: Om du märker att UI:t inte uppdateras, kan du avkommentera raden nedan
|
||||
// window.location.href = '/'; // Tvingar en total rensning av JS-minnet
|
||||
|
||||
return response.data;
|
||||
};
|
||||
|
||||
export const getLeaderboard = async () => {
|
||||
const response = await apiClient.get('/users/leaderboard');
|
||||
return response.data;
|
||||
};
|
||||
BIN
frontend/tasks.db
Normal file
BIN
frontend/tasks.db
Normal file
Binary file not shown.
28
frontend/tsconfig.json
Normal file
28
frontend/tsconfig.json
Normal file
@ -0,0 +1,28 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"target": "ES2022",
|
||||
"experimentalDecorators": true,
|
||||
"useDefineForClassFields": false,
|
||||
"module": "ESNext",
|
||||
"lib": [
|
||||
"ES2022",
|
||||
"DOM",
|
||||
"DOM.Iterable"
|
||||
],
|
||||
"skipLibCheck": true,
|
||||
"moduleResolution": "bundler",
|
||||
"isolatedModules": true,
|
||||
"moduleDetection": "force",
|
||||
"allowJs": true,
|
||||
"jsx": "react-jsx",
|
||||
"paths": {
|
||||
"@/*": [
|
||||
"./*"
|
||||
]
|
||||
},
|
||||
"allowImportingTsExtensions": true,
|
||||
"types": ["vite/client"],
|
||||
"noEmit": true
|
||||
}
|
||||
}
|
||||
|
||||
11
frontend/vite.config.ts
Normal file
11
frontend/vite.config.ts
Normal file
@ -0,0 +1,11 @@
|
||||
import { defineConfig } from 'vite'
|
||||
import react from '@vitejs/plugin-react'
|
||||
import tailwindcss from '@tailwindcss/vite'
|
||||
|
||||
export default defineConfig({
|
||||
plugins: [react(), tailwindcss()],
|
||||
server: {
|
||||
port: 3000,
|
||||
host: '0.0.0.0'
|
||||
}
|
||||
})
|
||||
Reference in New Issue
Block a user