reinit
This commit is contained in:
commit
ad8c238e78
53 changed files with 10091 additions and 0 deletions
52
.air.toml
Normal file
52
.air.toml
Normal file
|
@ -0,0 +1,52 @@
|
||||||
|
root = "."
|
||||||
|
testdata_dir = "testdata"
|
||||||
|
tmp_dir = "tmp"
|
||||||
|
|
||||||
|
[build]
|
||||||
|
args_bin = []
|
||||||
|
bin = "./tmp/main"
|
||||||
|
cmd = "go build -o ./tmp/main ."
|
||||||
|
delay = 1000
|
||||||
|
exclude_dir = ["assets", "tmp", "vendor", "testdata"]
|
||||||
|
exclude_file = []
|
||||||
|
exclude_regex = ["_test.go"]
|
||||||
|
exclude_unchanged = false
|
||||||
|
follow_symlink = false
|
||||||
|
full_bin = ""
|
||||||
|
include_dir = []
|
||||||
|
include_ext = ["go", "tpl", "tmpl", "html"]
|
||||||
|
include_file = []
|
||||||
|
kill_delay = "0s"
|
||||||
|
log = "build-errors.log"
|
||||||
|
poll = false
|
||||||
|
poll_interval = 0
|
||||||
|
post_cmd = []
|
||||||
|
pre_cmd = []
|
||||||
|
rerun = false
|
||||||
|
rerun_delay = 500
|
||||||
|
send_interrupt = false
|
||||||
|
stop_on_error = false
|
||||||
|
|
||||||
|
[color]
|
||||||
|
app = ""
|
||||||
|
build = "yellow"
|
||||||
|
main = "magenta"
|
||||||
|
runner = "green"
|
||||||
|
watcher = "cyan"
|
||||||
|
|
||||||
|
[log]
|
||||||
|
main_only = false
|
||||||
|
silent = false
|
||||||
|
time = false
|
||||||
|
|
||||||
|
[misc]
|
||||||
|
clean_on_exit = false
|
||||||
|
|
||||||
|
[proxy]
|
||||||
|
app_port = 8080
|
||||||
|
enabled = false
|
||||||
|
proxy_port = 8090
|
||||||
|
|
||||||
|
[screen]
|
||||||
|
clear_on_rebuild = false
|
||||||
|
keep_scroll = true
|
44
.dockerignore
Normal file
44
.dockerignore
Normal file
|
@ -0,0 +1,44 @@
|
||||||
|
# Git
|
||||||
|
.git
|
||||||
|
.gitignore
|
||||||
|
|
||||||
|
# Docker
|
||||||
|
Dockerfile*
|
||||||
|
docker-compose*.yml
|
||||||
|
.dockerignore
|
||||||
|
|
||||||
|
# Development
|
||||||
|
dev.sh
|
||||||
|
dev-docker.sh
|
||||||
|
tmp/
|
||||||
|
*.log
|
||||||
|
|
||||||
|
# Node.js
|
||||||
|
frontend/node_modules/
|
||||||
|
frontend/dist/
|
||||||
|
frontend/.vite/
|
||||||
|
|
||||||
|
# Go
|
||||||
|
*.exe
|
||||||
|
*.exe~
|
||||||
|
*.dll
|
||||||
|
*.so
|
||||||
|
*.dylib
|
||||||
|
*.test
|
||||||
|
*.out
|
||||||
|
go.work
|
||||||
|
|
||||||
|
# OS
|
||||||
|
.DS_Store
|
||||||
|
Thumbs.db
|
||||||
|
|
||||||
|
# IDE
|
||||||
|
.vscode/
|
||||||
|
.idea/
|
||||||
|
*.swp
|
||||||
|
*.swo
|
||||||
|
*~
|
||||||
|
|
||||||
|
# Build artifacts
|
||||||
|
build/
|
||||||
|
dist/
|
5
.gitignore
vendored
Normal file
5
.gitignore
vendored
Normal file
|
@ -0,0 +1,5 @@
|
||||||
|
data/
|
||||||
|
gocheck
|
||||||
|
tmp/
|
||||||
|
backend/frontend/
|
||||||
|
backend/data/
|
93
CLAUDE.md
Normal file
93
CLAUDE.md
Normal file
|
@ -0,0 +1,93 @@
|
||||||
|
# CLAUDE.md
|
||||||
|
|
||||||
|
This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
|
||||||
|
|
||||||
|
## Architecture Overview
|
||||||
|
|
||||||
|
GoCheck is a real-time collaborative checklist application with an **SSE-first architecture**:
|
||||||
|
- **Backend**: Go server with SQLite (one DB per checklist) - located in `backend/` directory
|
||||||
|
- **Frontend**: React TypeScript SPA with Radix UI and Tailwind CSS - located in `frontend/` directory
|
||||||
|
- **Real-time**: All data flows through Server-Sent Events - no polling or API calls for data retrieval
|
||||||
|
- **Embedded**: Frontend is built and embedded into the Go binary for single-file deployment
|
||||||
|
|
||||||
|
## Common Development Commands
|
||||||
|
|
||||||
|
### Backend (Go)
|
||||||
|
```bash
|
||||||
|
# Build the complete application (frontend + backend)
|
||||||
|
./build.sh
|
||||||
|
|
||||||
|
# Run the server
|
||||||
|
./gocheck
|
||||||
|
|
||||||
|
# Development with hot reload (requires Air)
|
||||||
|
cd backend && air
|
||||||
|
|
||||||
|
# Full dev environment (backend + frontend hot reload)
|
||||||
|
./dev.sh
|
||||||
|
```
|
||||||
|
|
||||||
|
### Frontend (React/TypeScript)
|
||||||
|
```bash
|
||||||
|
# Install dependencies
|
||||||
|
cd frontend && npm install
|
||||||
|
|
||||||
|
# Development server (proxies to backend on :8080)
|
||||||
|
cd frontend && npm run dev
|
||||||
|
|
||||||
|
# Build for production
|
||||||
|
cd frontend && npm run build
|
||||||
|
|
||||||
|
# Lint code
|
||||||
|
cd frontend && npm run lint
|
||||||
|
|
||||||
|
# Type checking
|
||||||
|
cd frontend && npm run build # TypeScript checking is part of build
|
||||||
|
```
|
||||||
|
|
||||||
|
### Container Operations
|
||||||
|
```bash
|
||||||
|
# Build and push multi-arch container
|
||||||
|
./build-and-push.sh
|
||||||
|
|
||||||
|
# Docker development environment
|
||||||
|
./dev-docker.sh
|
||||||
|
```
|
||||||
|
|
||||||
|
## Key Architecture Patterns
|
||||||
|
|
||||||
|
### SSE-First Data Flow
|
||||||
|
The application **never** uses REST endpoints for data retrieval. All checklist data flows through SSE:
|
||||||
|
1. Client connects to `/api/checklists/{uuid}/sse`
|
||||||
|
2. Server sends complete state on connection
|
||||||
|
3. All updates broadcast via SSE events
|
||||||
|
4. Frontend maintains state purely from SSE messages
|
||||||
|
|
||||||
|
### Database Design
|
||||||
|
- Each checklist has its own SQLite database in `backend/data/{uuid}.db`
|
||||||
|
- Schema includes: `checklist_info`, `items`, and `dependencies` tables
|
||||||
|
- Item dependencies and date constraints are core features
|
||||||
|
|
||||||
|
### API Endpoints
|
||||||
|
All endpoints return consistent JSON with `success` and `message` fields:
|
||||||
|
- `POST /api/checklists` - Create checklist
|
||||||
|
- `POST /api/checklists/{uuid}/items` - Add item
|
||||||
|
- `PATCH /api/checklists/{uuid}/items/{id}` - Update item
|
||||||
|
- `DELETE /api/checklists/{uuid}/items/{id}` - Delete item
|
||||||
|
- `POST /api/checklists/{uuid}/items/{id}/lock` - Lock item
|
||||||
|
- `GET /api/checklists/{uuid}/sse` - SSE stream (primary data source)
|
||||||
|
|
||||||
|
### Frontend Structure
|
||||||
|
- `frontend/src/pages/`: Home and Checklist pages
|
||||||
|
- `frontend/src/components/`: Reusable components (ChecklistItem, DependencyManager, etc.)
|
||||||
|
- `frontend/src/hooks/`: Custom hooks including `useSSE` for real-time updates
|
||||||
|
- Uses React Router for navigation
|
||||||
|
- Uses Radix UI for accessible, modern UI components
|
||||||
|
- Local storage for saving checklist UUIDs
|
||||||
|
|
||||||
|
### Development Notes
|
||||||
|
- No test suite currently exists
|
||||||
|
- ESLint configured with no-semicolon style
|
||||||
|
- Frontend uses Vite for fast development
|
||||||
|
- Backend embeds frontend dist for production deployment
|
||||||
|
- Container builds support multi-arch (amd64/arm64)
|
53
Containerfile
Normal file
53
Containerfile
Normal file
|
@ -0,0 +1,53 @@
|
||||||
|
FROM node:22-alpine AS frontend-builder
|
||||||
|
|
||||||
|
WORKDIR /app
|
||||||
|
|
||||||
|
COPY frontend /app
|
||||||
|
|
||||||
|
RUN npm install
|
||||||
|
|
||||||
|
RUN npm run build
|
||||||
|
|
||||||
|
# Multi-stage build for GoCheck application
|
||||||
|
# Stage 1: Build the Go binary
|
||||||
|
FROM golang:1.24-alpine AS builder
|
||||||
|
|
||||||
|
# Install git, ca-certificates, and build tools for CGO
|
||||||
|
RUN apk add --no-cache git ca-certificates gcc musl-dev
|
||||||
|
|
||||||
|
# Set working directory
|
||||||
|
WORKDIR /app
|
||||||
|
|
||||||
|
# Copy go mod files
|
||||||
|
COPY backend/go.mod backend/go.sum ./
|
||||||
|
|
||||||
|
# Download dependencies
|
||||||
|
RUN go mod download
|
||||||
|
|
||||||
|
# Copy backend source code
|
||||||
|
COPY backend/ ./
|
||||||
|
|
||||||
|
# Create frontend directory and copy dist files
|
||||||
|
RUN mkdir -p frontend
|
||||||
|
COPY --from=frontend-builder /app/dist /app/frontend/dist
|
||||||
|
|
||||||
|
# Build the binary with embedded static files
|
||||||
|
RUN CGO_ENABLED=1 GOOS=linux go build -a -installsuffix cgo -ldflags="-s -w" -o gocheck .
|
||||||
|
|
||||||
|
# Stage 2: Create minimal runtime container
|
||||||
|
FROM alpine:latest
|
||||||
|
|
||||||
|
# Install runtime dependencies for SQLite
|
||||||
|
RUN apk add --no-cache ca-certificates sqlite
|
||||||
|
|
||||||
|
# Copy the binary from builder stage
|
||||||
|
COPY --from=builder /app/gocheck /app/gocheck
|
||||||
|
|
||||||
|
# Set working directory
|
||||||
|
WORKDIR /app
|
||||||
|
|
||||||
|
# Expose default port (can be overridden via PORT env var)
|
||||||
|
EXPOSE 8080
|
||||||
|
|
||||||
|
# Run the binary
|
||||||
|
ENTRYPOINT ["/app/gocheck"]
|
70
Dockerfile.dev
Normal file
70
Dockerfile.dev
Normal file
|
@ -0,0 +1,70 @@
|
||||||
|
# Development Dockerfile with hot reload support
|
||||||
|
FROM golang:1.24-alpine
|
||||||
|
|
||||||
|
# Install development dependencies
|
||||||
|
RUN apk add --no-cache \
|
||||||
|
git \
|
||||||
|
ca-certificates \
|
||||||
|
gcc \
|
||||||
|
musl-dev \
|
||||||
|
nodejs \
|
||||||
|
npm \
|
||||||
|
sqlite \
|
||||||
|
# For file watching
|
||||||
|
inotify-tools
|
||||||
|
|
||||||
|
# Set working directory
|
||||||
|
WORKDIR /app
|
||||||
|
|
||||||
|
# Install Air for Go hot reloading
|
||||||
|
RUN go install github.com/air-verse/air@latest
|
||||||
|
|
||||||
|
# Create backend directory
|
||||||
|
RUN mkdir -p /app/backend
|
||||||
|
|
||||||
|
# Copy backend go mod files first for better caching
|
||||||
|
COPY backend/go.mod backend/go.sum /app/backend/
|
||||||
|
|
||||||
|
# Download Go dependencies
|
||||||
|
WORKDIR /app/backend
|
||||||
|
RUN go mod download
|
||||||
|
|
||||||
|
# Copy Air configuration
|
||||||
|
COPY backend/.air.toml /app/backend/
|
||||||
|
|
||||||
|
# Go back to app root
|
||||||
|
WORKDIR /app
|
||||||
|
|
||||||
|
# Copy the entire project
|
||||||
|
COPY . .
|
||||||
|
|
||||||
|
# Install frontend dependencies
|
||||||
|
WORKDIR /app/frontend
|
||||||
|
RUN npm install
|
||||||
|
|
||||||
|
# Go back to app root
|
||||||
|
WORKDIR /app
|
||||||
|
|
||||||
|
# Expose ports for both backend and frontend
|
||||||
|
EXPOSE 8080 5173
|
||||||
|
|
||||||
|
# Create a development startup script
|
||||||
|
RUN echo '#!/bin/sh\n\
|
||||||
|
echo "🚀 Starting development environment..."\n\
|
||||||
|
echo "📡 Backend will be available at http://localhost:8080"\n\
|
||||||
|
echo "🎨 Frontend will be available at http://localhost:5173"\n\
|
||||||
|
echo ""\n\
|
||||||
|
# Start frontend in background\n\
|
||||||
|
cd /app/frontend && npm run dev &\n\
|
||||||
|
FRONTEND_PID=$!\n\
|
||||||
|
\n\
|
||||||
|
# Start backend with Air\n\
|
||||||
|
cd /app/backend && air\n\
|
||||||
|
\n\
|
||||||
|
# Cleanup on exit\n\
|
||||||
|
trap "kill $FRONTEND_PID" EXIT\n\
|
||||||
|
wait\n\
|
||||||
|
' > /app/dev-start.sh && chmod +x /app/dev-start.sh
|
||||||
|
|
||||||
|
# Set the development startup script as entrypoint
|
||||||
|
ENTRYPOINT ["/app/dev-start.sh"]
|
217
README.md
Normal file
217
README.md
Normal file
|
@ -0,0 +1,217 @@
|
||||||
|
# GoCheck - Collaborative Checklist Application
|
||||||
|
|
||||||
|
A real-time collaborative checklist application built with Go and React, featuring Server-Sent Events (SSE) for live updates and SQLite for data persistence.
|
||||||
|
|
||||||
|
## Features
|
||||||
|
|
||||||
|
- Create and manage checklists
|
||||||
|
- Add, update, and delete checklist items
|
||||||
|
- Real-time collaboration with Server-Sent Events
|
||||||
|
- Item locking mechanism to prevent conflicts
|
||||||
|
- **Item dependencies**: Define prerequisites for completing items
|
||||||
|
- **Date constraints**: Set "not before" and "not after" times for item completion
|
||||||
|
- Modern web frontend with React, TypeScript, and Radix UI
|
||||||
|
- Real-time updates across multiple browser tabs/windows
|
||||||
|
- SSE-first architecture: All data flows through Server-Sent Events
|
||||||
|
- Export/Import checklists as JSON
|
||||||
|
|
||||||
|
## Architecture
|
||||||
|
|
||||||
|
### Project Structure
|
||||||
|
|
||||||
|
```
|
||||||
|
gocheck/
|
||||||
|
├── backend/ # Go server code
|
||||||
|
│ ├── main.go
|
||||||
|
│ ├── go.mod
|
||||||
|
│ ├── database/ # SQLite database handling
|
||||||
|
│ ├── handlers/ # HTTP and SSE handlers
|
||||||
|
│ ├── models/ # Data models
|
||||||
|
│ ├── sse/ # Server-Sent Events implementation
|
||||||
|
│ └── static/ # Static file serving
|
||||||
|
├── frontend/ # React TypeScript application
|
||||||
|
│ ├── src/
|
||||||
|
│ ├── package.json
|
||||||
|
│ └── vite.config.ts
|
||||||
|
├── build.sh # Build script for production
|
||||||
|
├── dev.sh # Development script with hot reload
|
||||||
|
└── Containerfile # Multi-stage container build
|
||||||
|
```
|
||||||
|
|
||||||
|
### SSE-First Design
|
||||||
|
|
||||||
|
This application follows an **SSE-first architecture** where all checklist data flows through Server-Sent Events:
|
||||||
|
|
||||||
|
- **No polling**: The frontend never polls for data updates
|
||||||
|
- **Real-time state management**: The frontend maintains state purely through SSE events
|
||||||
|
- **Immediate updates**: Changes appear instantly across all connected clients
|
||||||
|
|
||||||
|
## Prerequisites
|
||||||
|
|
||||||
|
- Go 1.24 or later
|
||||||
|
- Node.js 22+ and npm
|
||||||
|
- SQLite3 (included with Go)
|
||||||
|
|
||||||
|
## Setup and Development
|
||||||
|
|
||||||
|
### Quick Start
|
||||||
|
|
||||||
|
1. **Clone the repository**
|
||||||
|
```bash
|
||||||
|
git clone <repository-url>
|
||||||
|
cd gocheck
|
||||||
|
```
|
||||||
|
|
||||||
|
2. **Development mode** (with hot reload):
|
||||||
|
```bash
|
||||||
|
./dev.sh
|
||||||
|
```
|
||||||
|
This starts both backend (port 8080) and frontend (port 5173) with hot reloading.
|
||||||
|
|
||||||
|
3. **Production build**:
|
||||||
|
```bash
|
||||||
|
./build.sh
|
||||||
|
./gocheck
|
||||||
|
```
|
||||||
|
The server will start on `http://localhost:8080`
|
||||||
|
|
||||||
|
### Manual Development Setup
|
||||||
|
|
||||||
|
#### Backend
|
||||||
|
```bash
|
||||||
|
cd backend
|
||||||
|
go mod download
|
||||||
|
air # For hot reload (requires Air to be installed)
|
||||||
|
# or
|
||||||
|
go run main.go
|
||||||
|
```
|
||||||
|
|
||||||
|
#### Frontend
|
||||||
|
```bash
|
||||||
|
cd frontend
|
||||||
|
npm install
|
||||||
|
npm run dev # Development server on port 5173
|
||||||
|
npm run build # Production build
|
||||||
|
npm run lint # Check code quality
|
||||||
|
```
|
||||||
|
|
||||||
|
## Deployment
|
||||||
|
|
||||||
|
### Binary Deployment
|
||||||
|
|
||||||
|
The application builds as a single binary with embedded static files:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Build for current platform
|
||||||
|
./build.sh
|
||||||
|
|
||||||
|
# Cross-platform builds
|
||||||
|
cd backend
|
||||||
|
GOOS=linux GOARCH=amd64 go build -o gocheck-linux
|
||||||
|
GOOS=windows GOARCH=amd64 go build -o gocheck.exe
|
||||||
|
GOOS=darwin GOARCH=amd64 go build -o gocheck-macos
|
||||||
|
```
|
||||||
|
|
||||||
|
### Container Deployment
|
||||||
|
|
||||||
|
Build and run with Podman or Docker:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Using the build script
|
||||||
|
./build-and-push.sh
|
||||||
|
|
||||||
|
# Manual build
|
||||||
|
podman build -t gocheck -f Containerfile .
|
||||||
|
podman run -d --name gocheck -p 8080:8080 -v gocheck-data:/app/backend/data gocheck
|
||||||
|
|
||||||
|
# With custom port
|
||||||
|
podman run -d --name gocheck -p 3000:8080 -e PORT=8080 -v gocheck-data:/app/backend/data gocheck
|
||||||
|
```
|
||||||
|
|
||||||
|
## API Endpoints
|
||||||
|
|
||||||
|
All endpoints return consistent JSON responses:
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"success": true,
|
||||||
|
"message": "Operation completed",
|
||||||
|
"data": {}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### Endpoints
|
||||||
|
|
||||||
|
- `POST /api/checklists` - Create a new checklist
|
||||||
|
- `PATCH /api/checklists/{uuid}/name` - Update checklist name
|
||||||
|
- `POST /api/checklists/{uuid}/items` - Add an item
|
||||||
|
- `PATCH /api/checklists/{uuid}/items/{id}` - Update an item
|
||||||
|
- `DELETE /api/checklists/{uuid}/items/{id}` - Delete an item
|
||||||
|
- `POST /api/checklists/{uuid}/items/{id}/lock` - Lock an item for editing
|
||||||
|
- `GET /api/checklists/{uuid}/sse` - SSE stream for real-time updates
|
||||||
|
|
||||||
|
## Frontend Features
|
||||||
|
|
||||||
|
Built with modern web technologies:
|
||||||
|
- **React 18** with TypeScript
|
||||||
|
- **Radix UI** for accessible, customizable components
|
||||||
|
- **Tailwind CSS** for styling
|
||||||
|
- **Vite** for fast development and building
|
||||||
|
- **React Router** for client-side routing
|
||||||
|
|
||||||
|
### Key Features
|
||||||
|
|
||||||
|
- **Home Page**: Create new checklists and manage saved ones
|
||||||
|
- **Checklist Page**: Real-time collaborative editing
|
||||||
|
- **Local Storage**: Automatically saves checklist references
|
||||||
|
- **Export/Import**: Save and load checklists as JSON files
|
||||||
|
- **Mobile Friendly**: Responsive design with native date/time inputs
|
||||||
|
|
||||||
|
## Database
|
||||||
|
|
||||||
|
SQLite databases are stored in `backend/data/` with one database per checklist:
|
||||||
|
|
||||||
|
- `checklist_info` - Checklist metadata
|
||||||
|
- `items` - Checklist items with dependencies and date constraints
|
||||||
|
- `dependencies` - Item dependency relationships
|
||||||
|
|
||||||
|
## Item Dependencies
|
||||||
|
|
||||||
|
Items can depend on other items being completed first:
|
||||||
|
|
||||||
|
1. Click the link icon (🔗) on any item
|
||||||
|
2. Select which items must be completed first
|
||||||
|
3. Items with unmet dependencies cannot be checked off
|
||||||
|
4. Visual indicators show dependency status
|
||||||
|
|
||||||
|
## Date Constraints
|
||||||
|
|
||||||
|
Set time windows for when items can be completed:
|
||||||
|
|
||||||
|
1. Click the clock icon (🕐) on any item
|
||||||
|
2. Set "not before" and/or "not after" times
|
||||||
|
3. Quick select buttons for common timeframes
|
||||||
|
4. Items cannot be completed outside their time window
|
||||||
|
|
||||||
|
## Development Tools
|
||||||
|
|
||||||
|
### Scripts
|
||||||
|
|
||||||
|
- `./dev.sh` - Start development environment with hot reload
|
||||||
|
- `./build.sh` - Build production binary
|
||||||
|
- `./build-and-push.sh` - Build and push container images
|
||||||
|
|
||||||
|
### Environment Variables
|
||||||
|
|
||||||
|
- `PORT` - Server port (default: 8080)
|
||||||
|
|
||||||
|
## Contributing
|
||||||
|
|
||||||
|
1. Follow the existing code style
|
||||||
|
2. Use ESLint for frontend code (no semicolons)
|
||||||
|
3. Test changes in both development and production modes
|
||||||
|
4. Ensure cross-platform compatibility
|
||||||
|
|
||||||
|
## License
|
||||||
|
|
||||||
|
[Add your license here]
|
52
backend/.air.toml
Normal file
52
backend/.air.toml
Normal file
|
@ -0,0 +1,52 @@
|
||||||
|
root = "."
|
||||||
|
testdata_dir = "testdata"
|
||||||
|
tmp_dir = "tmp"
|
||||||
|
|
||||||
|
[build]
|
||||||
|
args_bin = []
|
||||||
|
bin = "./tmp/main"
|
||||||
|
cmd = "go build -o ./tmp/main ."
|
||||||
|
delay = 1000
|
||||||
|
exclude_dir = ["assets", "tmp", "vendor", "testdata"]
|
||||||
|
exclude_file = []
|
||||||
|
exclude_regex = ["_test.go"]
|
||||||
|
exclude_unchanged = false
|
||||||
|
follow_symlink = false
|
||||||
|
full_bin = ""
|
||||||
|
include_dir = []
|
||||||
|
include_ext = ["go", "tpl", "tmpl", "html"]
|
||||||
|
include_file = []
|
||||||
|
kill_delay = "0s"
|
||||||
|
log = "build-errors.log"
|
||||||
|
poll = false
|
||||||
|
poll_interval = 0
|
||||||
|
post_cmd = []
|
||||||
|
pre_cmd = []
|
||||||
|
rerun = false
|
||||||
|
rerun_delay = 500
|
||||||
|
send_interrupt = false
|
||||||
|
stop_on_error = false
|
||||||
|
|
||||||
|
[color]
|
||||||
|
app = ""
|
||||||
|
build = "yellow"
|
||||||
|
main = "magenta"
|
||||||
|
runner = "green"
|
||||||
|
watcher = "cyan"
|
||||||
|
|
||||||
|
[log]
|
||||||
|
main_only = false
|
||||||
|
silent = false
|
||||||
|
time = false
|
||||||
|
|
||||||
|
[misc]
|
||||||
|
clean_on_exit = false
|
||||||
|
|
||||||
|
[proxy]
|
||||||
|
app_port = 8080
|
||||||
|
enabled = false
|
||||||
|
proxy_port = 8090
|
||||||
|
|
||||||
|
[screen]
|
||||||
|
clear_on_rebuild = false
|
||||||
|
keep_scroll = true
|
447
backend/database/database.go
Normal file
447
backend/database/database.go
Normal file
|
@ -0,0 +1,447 @@
|
||||||
|
package database
|
||||||
|
|
||||||
|
import (
|
||||||
|
"database/sql"
|
||||||
|
"fmt"
|
||||||
|
"log"
|
||||||
|
"os"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/google/uuid"
|
||||||
|
_ "github.com/mattn/go-sqlite3"
|
||||||
|
|
||||||
|
"gocheck/models"
|
||||||
|
)
|
||||||
|
|
||||||
|
func GetChecklistDB(uuid string) (*sql.DB, error) {
|
||||||
|
// Ensure data directory exists
|
||||||
|
if err := os.MkdirAll("data", 0755); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
dbPath := fmt.Sprintf("data/%s.db", uuid)
|
||||||
|
db, err := sql.Open("sqlite3", dbPath)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// Setup schema for this checklist
|
||||||
|
queries := []string{
|
||||||
|
`CREATE TABLE IF NOT EXISTS checklist_info (
|
||||||
|
uuid TEXT PRIMARY KEY,
|
||||||
|
name TEXT NOT NULL
|
||||||
|
);`,
|
||||||
|
`CREATE TABLE IF NOT EXISTS items (
|
||||||
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||||
|
content TEXT NOT NULL,
|
||||||
|
checked INTEGER NOT NULL,
|
||||||
|
parent_id INTEGER,
|
||||||
|
not_before TEXT,
|
||||||
|
not_after TEXT,
|
||||||
|
FOREIGN KEY(parent_id) REFERENCES items(id)
|
||||||
|
);`,
|
||||||
|
`CREATE TABLE IF NOT EXISTS dependencies (
|
||||||
|
item_id INTEGER NOT NULL,
|
||||||
|
dependency_id INTEGER NOT NULL,
|
||||||
|
PRIMARY KEY (item_id, dependency_id),
|
||||||
|
FOREIGN KEY(item_id) REFERENCES items(id) ON DELETE CASCADE,
|
||||||
|
FOREIGN KEY(dependency_id) REFERENCES items(id) ON DELETE CASCADE,
|
||||||
|
CHECK(item_id != dependency_id)
|
||||||
|
);`,
|
||||||
|
}
|
||||||
|
for _, q := range queries {
|
||||||
|
if _, err := db.Exec(q); err != nil {
|
||||||
|
db.Close()
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return db, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func LoadItemDependencies(db *sql.DB, itemID int) ([]int, error) {
|
||||||
|
rows, err := db.Query(`SELECT dependency_id FROM dependencies WHERE item_id = ?`, itemID)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
defer rows.Close()
|
||||||
|
|
||||||
|
var deps []int
|
||||||
|
for rows.Next() {
|
||||||
|
var depID int
|
||||||
|
err = rows.Scan(&depID)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
deps = append(deps, depID)
|
||||||
|
}
|
||||||
|
return deps, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// EnsureChecklistExists creates a checklist if it doesn't exist
|
||||||
|
func EnsureChecklistExists(uuid string) error {
|
||||||
|
db, err := GetChecklistDB(uuid)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
defer db.Close()
|
||||||
|
|
||||||
|
// Check if checklist_info table has any data
|
||||||
|
var count int
|
||||||
|
err = db.QueryRow(`SELECT COUNT(*) FROM checklist_info`).Scan(&count)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
// If no checklist exists, create one with a default name
|
||||||
|
if count == 0 {
|
||||||
|
_, err = db.Exec(`INSERT INTO checklist_info (uuid, name) VALUES (?, ?)`, uuid, "Untitled Checklist")
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func LoadChecklistName(uuid string) (string, error) {
|
||||||
|
db, err := GetChecklistDB(uuid)
|
||||||
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
defer db.Close()
|
||||||
|
|
||||||
|
rows, err := db.Query(`SELECT name FROM checklist_info WHERE uuid = ?`, uuid)
|
||||||
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
defer rows.Close()
|
||||||
|
if rows.Next() {
|
||||||
|
var name string
|
||||||
|
err = rows.Scan(&name)
|
||||||
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
return name, nil
|
||||||
|
}
|
||||||
|
return "", fmt.Errorf("not found")
|
||||||
|
}
|
||||||
|
|
||||||
|
func LoadChecklistItems(uuid string, itemLocks map[int]*models.ItemLock) ([]models.ChecklistItem, error) {
|
||||||
|
db, err := GetChecklistDB(uuid)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
defer db.Close()
|
||||||
|
|
||||||
|
rows, err := db.Query(`SELECT id, content, checked, parent_id, not_before, not_after FROM items`)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
defer rows.Close()
|
||||||
|
var items []models.ChecklistItem
|
||||||
|
for rows.Next() {
|
||||||
|
var it models.ChecklistItem
|
||||||
|
var checked int
|
||||||
|
var parentID sql.NullInt64
|
||||||
|
var notBefore sql.NullString
|
||||||
|
var notAfter sql.NullString
|
||||||
|
err = rows.Scan(&it.ID, &it.Content, &checked, &parentID, ¬Before, ¬After)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
it.Checked = checked != 0
|
||||||
|
if parentID.Valid {
|
||||||
|
v := int(parentID.Int64)
|
||||||
|
it.ParentID = &v
|
||||||
|
}
|
||||||
|
if notBefore.Valid {
|
||||||
|
if t, err := time.Parse(time.RFC3339, notBefore.String); err == nil {
|
||||||
|
it.NotBefore = &t
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if notAfter.Valid {
|
||||||
|
if t, err := time.Parse(time.RFC3339, notAfter.String); err == nil {
|
||||||
|
it.NotAfter = &t
|
||||||
|
}
|
||||||
|
}
|
||||||
|
it.Checklist = uuid
|
||||||
|
|
||||||
|
// Load dependencies for this item
|
||||||
|
deps, err := LoadItemDependencies(db, it.ID)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
it.Dependencies = deps
|
||||||
|
|
||||||
|
// Attach lock info if present
|
||||||
|
if lock, ok := itemLocks[it.ID]; ok && lock.Expires.After(time.Now()) {
|
||||||
|
it.LockedBy = &lock.LockedBy
|
||||||
|
t := lock.Expires
|
||||||
|
it.LockUntil = &t
|
||||||
|
}
|
||||||
|
|
||||||
|
items = append(items, it)
|
||||||
|
}
|
||||||
|
return items, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func AddChecklist(name string) (string, error) {
|
||||||
|
uuidStr := generateUUID()
|
||||||
|
db, err := GetChecklistDB(uuidStr)
|
||||||
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
defer db.Close()
|
||||||
|
|
||||||
|
_, err = db.Exec(`INSERT INTO checklist_info (uuid, name) VALUES (?, ?)`, uuidStr, name)
|
||||||
|
return uuidStr, err
|
||||||
|
}
|
||||||
|
|
||||||
|
func UpdateChecklistName(uuid string, name string) error {
|
||||||
|
db, err := GetChecklistDB(uuid)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
defer db.Close()
|
||||||
|
|
||||||
|
_, err = db.Exec(`UPDATE checklist_info SET name = ? WHERE uuid = ?`, name, uuid)
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
func AddItem(uuid, content string, parentID *int, notBefore *time.Time, notAfter *time.Time) (models.ChecklistItem, error) {
|
||||||
|
db, err := GetChecklistDB(uuid)
|
||||||
|
if err != nil {
|
||||||
|
return models.ChecklistItem{}, err
|
||||||
|
}
|
||||||
|
defer db.Close()
|
||||||
|
|
||||||
|
var notBeforeStr, notAfterStr *string
|
||||||
|
if notBefore != nil {
|
||||||
|
s := notBefore.Format(time.RFC3339)
|
||||||
|
notBeforeStr = &s
|
||||||
|
}
|
||||||
|
if notAfter != nil {
|
||||||
|
s := notAfter.Format(time.RFC3339)
|
||||||
|
notAfterStr = &s
|
||||||
|
}
|
||||||
|
|
||||||
|
res, err := db.Exec(`INSERT INTO items (content, checked, parent_id, not_before, not_after) VALUES (?, 0, ?, ?, ?)`,
|
||||||
|
content, parentID, notBeforeStr, notAfterStr)
|
||||||
|
if err != nil {
|
||||||
|
return models.ChecklistItem{}, err
|
||||||
|
}
|
||||||
|
id, _ := res.LastInsertId()
|
||||||
|
return models.ChecklistItem{
|
||||||
|
ID: int(id),
|
||||||
|
Content: content,
|
||||||
|
Checked: false,
|
||||||
|
ParentID: parentID,
|
||||||
|
NotBefore: notBefore,
|
||||||
|
NotAfter: notAfter,
|
||||||
|
Checklist: uuid,
|
||||||
|
}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func UpdateItem(uuid string, id int, content *string, checked *bool, parentID *int, dependencies *[]int, notBefore *time.Time, notAfter *time.Time) (models.ChecklistItem, error) {
|
||||||
|
log.Printf("updateItem called with uuid: %s, id: %d", uuid, id)
|
||||||
|
log.Printf("Parameters: content=%v, checked=%v, parentID=%v, dependencies=%v", content, checked, parentID, dependencies)
|
||||||
|
|
||||||
|
db, err := GetChecklistDB(uuid)
|
||||||
|
if err != nil {
|
||||||
|
log.Printf("Failed to get database: %v", err)
|
||||||
|
return models.ChecklistItem{}, err
|
||||||
|
}
|
||||||
|
defer db.Close()
|
||||||
|
|
||||||
|
log.Printf("Database connection successful for uuid: %s", uuid)
|
||||||
|
|
||||||
|
// If trying to check an item, validate dependencies and date constraints first
|
||||||
|
if checked != nil && *checked {
|
||||||
|
log.Printf("Validating dependencies for item %d", id)
|
||||||
|
deps, err := LoadItemDependencies(db, id)
|
||||||
|
if err != nil {
|
||||||
|
log.Printf("Failed to load dependencies: %v", err)
|
||||||
|
return models.ChecklistItem{}, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check if all dependencies are completed
|
||||||
|
for _, depID := range deps {
|
||||||
|
var depChecked int
|
||||||
|
err = db.QueryRow(`SELECT checked FROM items WHERE id = ?`, depID).Scan(&depChecked)
|
||||||
|
if err != nil {
|
||||||
|
log.Printf("Failed to check dependency %d: %v", depID, err)
|
||||||
|
return models.ChecklistItem{}, err
|
||||||
|
}
|
||||||
|
if depChecked == 0 {
|
||||||
|
return models.ChecklistItem{}, fmt.Errorf("cannot complete item: dependency %d is not completed", depID)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Validate date constraints
|
||||||
|
now := time.Now()
|
||||||
|
var notBeforeStr, notAfterStr sql.NullString
|
||||||
|
err = db.QueryRow(`SELECT not_before, not_after FROM items WHERE id = ?`, id).Scan(¬BeforeStr, ¬AfterStr)
|
||||||
|
if err != nil {
|
||||||
|
log.Printf("Failed to get date constraints: %v", err)
|
||||||
|
return models.ChecklistItem{}, err
|
||||||
|
}
|
||||||
|
|
||||||
|
if notBeforeStr.Valid {
|
||||||
|
if notBefore, err := time.Parse(time.RFC3339, notBeforeStr.String); err == nil {
|
||||||
|
if now.Before(notBefore) {
|
||||||
|
return models.ChecklistItem{}, fmt.Errorf("cannot complete item: not before %s", notBefore.Format("2006-01-02 15:04:05"))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if notAfterStr.Valid {
|
||||||
|
if notAfter, err := time.Parse(time.RFC3339, notAfterStr.String); err == nil {
|
||||||
|
if now.After(notAfter) {
|
||||||
|
return models.ChecklistItem{}, fmt.Errorf("cannot complete item: not after %s", notAfter.Format("2006-01-02 15:04:05"))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
log.Printf("Skipping dependency and date validation - checked is %v", checked)
|
||||||
|
}
|
||||||
|
|
||||||
|
log.Printf("About to check dependencies parameter")
|
||||||
|
// Update dependencies if provided
|
||||||
|
if dependencies != nil {
|
||||||
|
log.Printf("Updating dependencies for item %d: %v", id, *dependencies)
|
||||||
|
// Delete existing dependencies
|
||||||
|
_, err = db.Exec(`DELETE FROM dependencies WHERE item_id = ?`, id)
|
||||||
|
if err != nil {
|
||||||
|
log.Printf("Failed to delete existing dependencies: %v", err)
|
||||||
|
return models.ChecklistItem{}, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// Add new dependencies
|
||||||
|
for _, depID := range *dependencies {
|
||||||
|
log.Printf("Adding dependency %d for item %d", depID, id)
|
||||||
|
_, err = db.Exec(`INSERT INTO dependencies (item_id, dependency_id) VALUES (?, ?)`, id, depID)
|
||||||
|
if err != nil {
|
||||||
|
log.Printf("Failed to add dependency %d: %v", depID, err)
|
||||||
|
return models.ChecklistItem{}, err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
log.Printf("Dependencies updated successfully")
|
||||||
|
} else {
|
||||||
|
log.Printf("No dependencies to update")
|
||||||
|
}
|
||||||
|
|
||||||
|
log.Printf("About to build SQL update query")
|
||||||
|
set := []string{}
|
||||||
|
args := []interface{}{}
|
||||||
|
if content != nil {
|
||||||
|
set = append(set, "content = ?")
|
||||||
|
args = append(args, *content)
|
||||||
|
}
|
||||||
|
if checked != nil {
|
||||||
|
set = append(set, "checked = ?")
|
||||||
|
if *checked {
|
||||||
|
args = append(args, 1)
|
||||||
|
} else {
|
||||||
|
args = append(args, 0)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if parentID != nil {
|
||||||
|
set = append(set, "parent_id = ?")
|
||||||
|
args = append(args, *parentID)
|
||||||
|
}
|
||||||
|
if notBefore != nil {
|
||||||
|
set = append(set, "not_before = ?")
|
||||||
|
args = append(args, notBefore.Format(time.RFC3339))
|
||||||
|
}
|
||||||
|
if notAfter != nil {
|
||||||
|
set = append(set, "not_after = ?")
|
||||||
|
args = append(args, notAfter.Format(time.RFC3339))
|
||||||
|
}
|
||||||
|
if len(set) > 0 {
|
||||||
|
q := "UPDATE items SET " + strings.Join(set, ", ") + " WHERE id = ?"
|
||||||
|
args = append(args, id)
|
||||||
|
log.Printf("SQL query: %s with args: %v", q, args)
|
||||||
|
_, err = db.Exec(q, args...)
|
||||||
|
if err != nil {
|
||||||
|
log.Printf("Failed to execute SQL update: %v", err)
|
||||||
|
return models.ChecklistItem{}, err
|
||||||
|
}
|
||||||
|
log.Printf("SQL update executed successfully")
|
||||||
|
} else {
|
||||||
|
log.Printf("No fields to update in SQL, skipping update query")
|
||||||
|
}
|
||||||
|
|
||||||
|
// Return updated item
|
||||||
|
log.Printf("Querying updated item %d", id)
|
||||||
|
rows, err := db.Query(`SELECT id, content, checked, parent_id, not_before, not_after FROM items WHERE id = ?`, id)
|
||||||
|
if err != nil {
|
||||||
|
log.Printf("Failed to query updated item: %v", err)
|
||||||
|
return models.ChecklistItem{}, err
|
||||||
|
}
|
||||||
|
defer rows.Close()
|
||||||
|
if rows.Next() {
|
||||||
|
log.Printf("Found item %d in database", id)
|
||||||
|
var it models.ChecklistItem
|
||||||
|
var checkedInt int
|
||||||
|
var parentID sql.NullInt64
|
||||||
|
var notBefore sql.NullString
|
||||||
|
var notAfter sql.NullString
|
||||||
|
err = rows.Scan(&it.ID, &it.Content, &checkedInt, &parentID, ¬Before, ¬After)
|
||||||
|
if err != nil {
|
||||||
|
log.Printf("Failed to scan updated item: %v", err)
|
||||||
|
return models.ChecklistItem{}, err
|
||||||
|
}
|
||||||
|
it.Checked = checkedInt != 0
|
||||||
|
if parentID.Valid {
|
||||||
|
v := int(parentID.Int64)
|
||||||
|
it.ParentID = &v
|
||||||
|
}
|
||||||
|
if notBefore.Valid {
|
||||||
|
if t, err := time.Parse(time.RFC3339, notBefore.String); err == nil {
|
||||||
|
it.NotBefore = &t
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if notAfter.Valid {
|
||||||
|
if t, err := time.Parse(time.RFC3339, notAfter.String); err == nil {
|
||||||
|
it.NotAfter = &t
|
||||||
|
}
|
||||||
|
}
|
||||||
|
it.Checklist = uuid
|
||||||
|
|
||||||
|
// Load dependencies
|
||||||
|
deps, err := LoadItemDependencies(db, it.ID)
|
||||||
|
if err != nil {
|
||||||
|
log.Printf("Failed to load dependencies for return: %v", err)
|
||||||
|
return models.ChecklistItem{}, err
|
||||||
|
}
|
||||||
|
it.Dependencies = deps
|
||||||
|
|
||||||
|
log.Printf("Successfully updated item %d", id)
|
||||||
|
return it, nil
|
||||||
|
}
|
||||||
|
log.Printf("Item %d not found in database", id)
|
||||||
|
return models.ChecklistItem{}, fmt.Errorf("not found")
|
||||||
|
}
|
||||||
|
|
||||||
|
func DeleteItem(uuid string, id int) error {
|
||||||
|
db, err := GetChecklistDB(uuid)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
defer db.Close()
|
||||||
|
|
||||||
|
// Delete dependencies that reference this item
|
||||||
|
_, err = db.Exec(`DELETE FROM dependencies WHERE dependency_id = ?`, id)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
// Delete the item itself
|
||||||
|
_, err = db.Exec(`DELETE FROM items WHERE id = ?`, id)
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
// generateUUID generates a new UUID
|
||||||
|
func generateUUID() string {
|
||||||
|
return uuid.New().String()
|
||||||
|
}
|
8
backend/go.mod
Normal file
8
backend/go.mod
Normal file
|
@ -0,0 +1,8 @@
|
||||||
|
module gocheck
|
||||||
|
|
||||||
|
go 1.24.0
|
||||||
|
|
||||||
|
require (
|
||||||
|
github.com/google/uuid v1.6.0
|
||||||
|
github.com/mattn/go-sqlite3 v1.14.28
|
||||||
|
)
|
4
backend/go.sum
Normal file
4
backend/go.sum
Normal file
|
@ -0,0 +1,4 @@
|
||||||
|
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
|
||||||
|
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
|
||||||
|
github.com/mattn/go-sqlite3 v1.14.28 h1:ThEiQrnbtumT+QMknw63Befp/ce/nUPgBPMlRFEum7A=
|
||||||
|
github.com/mattn/go-sqlite3 v1.14.28/go.mod h1:Uh1q+B4BYcTPb+yiD3kU8Ct7aC0hY9fxUwlHK0RXw+Y=
|
363
backend/handlers/handlers.go
Normal file
363
backend/handlers/handlers.go
Normal file
|
@ -0,0 +1,363 @@
|
||||||
|
package handlers
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
"log"
|
||||||
|
"net/http"
|
||||||
|
"strings"
|
||||||
|
"sync"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"gocheck/database"
|
||||||
|
"gocheck/models"
|
||||||
|
"gocheck/sse"
|
||||||
|
)
|
||||||
|
|
||||||
|
var (
|
||||||
|
itemLocks = make(map[int]*models.ItemLock) // item ID → lock
|
||||||
|
itemLocksMutex sync.Mutex
|
||||||
|
)
|
||||||
|
|
||||||
|
// GetItemLocks returns the current item locks
|
||||||
|
func GetItemLocks() map[int]*models.ItemLock {
|
||||||
|
return itemLocks
|
||||||
|
}
|
||||||
|
|
||||||
|
// StartLockExpiryDaemon starts the lock expiry daemon
|
||||||
|
func StartLockExpiryDaemon() {
|
||||||
|
go lockExpiryDaemon()
|
||||||
|
}
|
||||||
|
|
||||||
|
func lockExpiryDaemon() {
|
||||||
|
for {
|
||||||
|
time.Sleep(1 * time.Second)
|
||||||
|
now := time.Now()
|
||||||
|
|
||||||
|
// Collect expired locks first
|
||||||
|
var expiredLocks []struct {
|
||||||
|
id int
|
||||||
|
uuid string
|
||||||
|
}
|
||||||
|
|
||||||
|
itemLocksMutex.Lock()
|
||||||
|
for id, lock := range itemLocks {
|
||||||
|
if lock.Expires.Before(now) {
|
||||||
|
expiredLocks = append(expiredLocks, struct {
|
||||||
|
id int
|
||||||
|
uuid string
|
||||||
|
}{id: id, uuid: lock.ChecklistUUID})
|
||||||
|
delete(itemLocks, id)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
itemLocksMutex.Unlock()
|
||||||
|
|
||||||
|
// Broadcast unlock events after releasing the mutex
|
||||||
|
for _, expired := range expiredLocks {
|
||||||
|
sse.Broadcast(expired.uuid, map[string]interface{}{
|
||||||
|
"type": "item_unlocked",
|
||||||
|
"id": expired.id,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func HandleGetItems(w http.ResponseWriter, r *http.Request) {
|
||||||
|
uuid := strings.TrimPrefix(r.URL.Path, "/api/checklists/")
|
||||||
|
uuid = uuid[:36]
|
||||||
|
|
||||||
|
// Ensure checklist exists
|
||||||
|
if err := database.EnsureChecklistExists(uuid); err != nil {
|
||||||
|
http.Error(w, "Failed to ensure checklist exists", 500)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
itemLocksMutex.Lock()
|
||||||
|
items, err := database.LoadChecklistItems(uuid, itemLocks)
|
||||||
|
itemLocksMutex.Unlock()
|
||||||
|
|
||||||
|
if err != nil {
|
||||||
|
http.Error(w, "Failed to load items", 500)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
w.Header().Set("Content-Type", "application/json")
|
||||||
|
json.NewEncoder(w).Encode(map[string]interface{}{
|
||||||
|
"success": true,
|
||||||
|
"message": "Items loaded successfully",
|
||||||
|
"items": items,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func HandleCreateChecklist(w http.ResponseWriter, r *http.Request) {
|
||||||
|
type Req struct {
|
||||||
|
Name string `json:"name"`
|
||||||
|
}
|
||||||
|
var req Req
|
||||||
|
if err := json.NewDecoder(r.Body).Decode(&req); err != nil || strings.TrimSpace(req.Name) == "" {
|
||||||
|
http.Error(w, "Missing name", 400)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
uuid, err := database.AddChecklist(req.Name)
|
||||||
|
if err != nil {
|
||||||
|
http.Error(w, "Failed to create checklist", 500)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
w.Header().Set("Content-Type", "application/json")
|
||||||
|
resp := map[string]interface{}{
|
||||||
|
"success": true,
|
||||||
|
"message": "Checklist created successfully",
|
||||||
|
"uuid": uuid,
|
||||||
|
}
|
||||||
|
json.NewEncoder(w).Encode(resp)
|
||||||
|
}
|
||||||
|
|
||||||
|
func HandleAddItem(w http.ResponseWriter, r *http.Request) {
|
||||||
|
uuid := strings.TrimPrefix(r.URL.Path, "/api/checklists/")
|
||||||
|
uuid = uuid[:36]
|
||||||
|
|
||||||
|
// Ensure checklist exists
|
||||||
|
if err := database.EnsureChecklistExists(uuid); err != nil {
|
||||||
|
http.Error(w, "Failed to ensure checklist exists", 500)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
type Req struct {
|
||||||
|
Content string `json:"content"`
|
||||||
|
ParentID *int `json:"parent_id"`
|
||||||
|
NotBefore *time.Time `json:"not_before"`
|
||||||
|
NotAfter *time.Time `json:"not_after"`
|
||||||
|
}
|
||||||
|
var req Req
|
||||||
|
if err := json.NewDecoder(r.Body).Decode(&req); err != nil || strings.TrimSpace(req.Content) == "" {
|
||||||
|
http.Error(w, "Missing content", 400)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
item, err := database.AddItem(uuid, req.Content, req.ParentID, req.NotBefore, req.NotAfter)
|
||||||
|
if err != nil {
|
||||||
|
http.Error(w, "Failed to add item", 500)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
// broadcast
|
||||||
|
sse.Broadcast(uuid, map[string]interface{}{"type": "item_added", "item": item})
|
||||||
|
w.Header().Set("Content-Type", "application/json")
|
||||||
|
w.WriteHeader(201)
|
||||||
|
json.NewEncoder(w).Encode(map[string]interface{}{
|
||||||
|
"success": true,
|
||||||
|
"message": "Item added successfully",
|
||||||
|
"item": item,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func HandleUpdateItem(w http.ResponseWriter, r *http.Request) {
|
||||||
|
log.Printf("handleUpdateItem called with path: %s", r.URL.Path)
|
||||||
|
parts := strings.Split(r.URL.Path, "/")
|
||||||
|
|
||||||
|
if len(parts) < 6 {
|
||||||
|
http.Error(w, "Invalid path", 400)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
uuid := parts[3]
|
||||||
|
id := 0
|
||||||
|
fmt.Sscanf(parts[5], "%d", &id)
|
||||||
|
|
||||||
|
// Ensure checklist exists
|
||||||
|
if err := database.EnsureChecklistExists(uuid); err != nil {
|
||||||
|
http.Error(w, "Failed to ensure checklist exists", 500)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
type Req struct {
|
||||||
|
Content *string `json:"content"`
|
||||||
|
Checked *bool `json:"checked"`
|
||||||
|
ParentID *int `json:"parent_id"`
|
||||||
|
Dependencies *[]int `json:"dependencies"`
|
||||||
|
NotBefore *time.Time `json:"not_before"`
|
||||||
|
NotAfter *time.Time `json:"not_after"`
|
||||||
|
}
|
||||||
|
var req Req
|
||||||
|
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
||||||
|
http.Error(w, "Bad body", 400)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
item, err := database.UpdateItem(uuid, id, req.Content, req.Checked, req.ParentID, req.Dependencies, req.NotBefore, req.NotAfter)
|
||||||
|
if err != nil {
|
||||||
|
if strings.Contains(err.Error(), "cannot complete item:") {
|
||||||
|
http.Error(w, err.Error(), 400)
|
||||||
|
} else {
|
||||||
|
http.Error(w, "Not found", 404)
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
sse.Broadcast(uuid, map[string]interface{}{"type": "item_updated", "item": item})
|
||||||
|
w.Header().Set("Content-Type", "application/json")
|
||||||
|
json.NewEncoder(w).Encode(map[string]interface{}{
|
||||||
|
"success": true,
|
||||||
|
"message": "Item updated successfully",
|
||||||
|
"item": item,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func HandleDeleteItem(w http.ResponseWriter, r *http.Request) {
|
||||||
|
parts := strings.Split(r.URL.Path, "/")
|
||||||
|
uuid := parts[3]
|
||||||
|
id := 0
|
||||||
|
fmt.Sscanf(parts[5], "%d", &id)
|
||||||
|
|
||||||
|
// Ensure checklist exists
|
||||||
|
if err := database.EnsureChecklistExists(uuid); err != nil {
|
||||||
|
http.Error(w, "Failed to ensure checklist exists", 500)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := database.DeleteItem(uuid, id); err != nil {
|
||||||
|
http.Error(w, "Delete failed", 500)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
sse.Broadcast(uuid, map[string]interface{}{"type": "item_deleted", "id": id})
|
||||||
|
w.Header().Set("Content-Type", "application/json")
|
||||||
|
json.NewEncoder(w).Encode(map[string]interface{}{
|
||||||
|
"success": true,
|
||||||
|
"message": "Item deleted successfully",
|
||||||
|
"id": id,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func HandleLockItem(w http.ResponseWriter, r *http.Request) {
|
||||||
|
parts := strings.Split(r.URL.Path, "/")
|
||||||
|
uuid := parts[3]
|
||||||
|
id := 0
|
||||||
|
fmt.Sscanf(parts[5], "%d", &id)
|
||||||
|
|
||||||
|
// Ensure checklist exists
|
||||||
|
if err := database.EnsureChecklistExists(uuid); err != nil {
|
||||||
|
http.Error(w, "Failed to ensure checklist exists", 500)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
type Req struct {
|
||||||
|
User string `json:"user"`
|
||||||
|
}
|
||||||
|
var req Req
|
||||||
|
if err := json.NewDecoder(r.Body).Decode(&req); err != nil || strings.TrimSpace(req.User) == "" {
|
||||||
|
http.Error(w, "Missing user", 400)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
expiry := time.Now().Add(15 * time.Second) // e.g. 30 sec lock
|
||||||
|
|
||||||
|
itemLocksMutex.Lock()
|
||||||
|
itemLocks[id] = &models.ItemLock{LockedBy: req.User, Expires: expiry, ChecklistUUID: uuid}
|
||||||
|
itemLocksMutex.Unlock()
|
||||||
|
|
||||||
|
// Broadcast lock
|
||||||
|
sse.Broadcast(uuid, map[string]interface{}{"type": "item_locked", "id": id, "locked_by": req.User, "expires": expiry})
|
||||||
|
w.Header().Set("Content-Type", "application/json")
|
||||||
|
json.NewEncoder(w).Encode(map[string]interface{}{
|
||||||
|
"success": true,
|
||||||
|
"message": "Item locked successfully",
|
||||||
|
"id": id,
|
||||||
|
"locked_by": req.User,
|
||||||
|
"expires": expiry,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func HandleUpdateChecklistName(w http.ResponseWriter, r *http.Request) {
|
||||||
|
parts := strings.Split(r.URL.Path, "/")
|
||||||
|
uuid := parts[3]
|
||||||
|
log.Printf("handleUpdateChecklistName called for uuid: %s", uuid)
|
||||||
|
|
||||||
|
// Ensure checklist exists
|
||||||
|
if err := database.EnsureChecklistExists(uuid); err != nil {
|
||||||
|
log.Printf("Failed to ensure checklist exists: %v", err)
|
||||||
|
http.Error(w, "Failed to ensure checklist exists", 500)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
type Req struct {
|
||||||
|
Name string `json:"name"`
|
||||||
|
}
|
||||||
|
var req Req
|
||||||
|
if err := json.NewDecoder(r.Body).Decode(&req); err != nil || strings.TrimSpace(req.Name) == "" {
|
||||||
|
log.Printf("Invalid request body: %v", err)
|
||||||
|
http.Error(w, "Missing or empty name", 400)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
log.Printf("Updating checklist name to: %s", req.Name)
|
||||||
|
if err := database.UpdateChecklistName(uuid, req.Name); err != nil {
|
||||||
|
log.Printf("Failed to update checklist name: %v", err)
|
||||||
|
http.Error(w, "Failed to update checklist name", 500)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
log.Printf("Checklist name updated successfully, broadcasting...")
|
||||||
|
// Broadcast name update
|
||||||
|
sse.Broadcast(uuid, map[string]interface{}{"type": "checklist_name_updated", "name": req.Name})
|
||||||
|
w.Header().Set("Content-Type", "application/json")
|
||||||
|
json.NewEncoder(w).Encode(map[string]interface{}{
|
||||||
|
"success": true,
|
||||||
|
"message": "Checklist name updated successfully",
|
||||||
|
"name": req.Name,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func HandleSSE(w http.ResponseWriter, r *http.Request) {
|
||||||
|
uuid := strings.TrimPrefix(r.URL.Path, "/api/checklists/")
|
||||||
|
uuid = uuid[:36]
|
||||||
|
|
||||||
|
// Ensure checklist exists
|
||||||
|
if err := database.EnsureChecklistExists(uuid); err != nil {
|
||||||
|
http.Error(w, "Failed to ensure checklist exists", 500)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
flusher, ok := w.(http.Flusher)
|
||||||
|
if !ok {
|
||||||
|
http.Error(w, "Streaming unsupported", http.StatusInternalServerError)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
w.Header().Set("Content-Type", "text/event-stream")
|
||||||
|
w.Header().Set("Cache-Control", "no-cache")
|
||||||
|
w.Header().Set("Connection", "keep-alive")
|
||||||
|
|
||||||
|
ch := make(chan string, 20)
|
||||||
|
// Register client
|
||||||
|
sse.RegisterClient(uuid, ch)
|
||||||
|
defer func() {
|
||||||
|
sse.UnregisterClient(uuid, ch)
|
||||||
|
close(ch)
|
||||||
|
}()
|
||||||
|
|
||||||
|
// Send full state on connect
|
||||||
|
itemLocksMutex.Lock()
|
||||||
|
items, err := database.LoadChecklistItems(uuid, itemLocks)
|
||||||
|
itemLocksMutex.Unlock()
|
||||||
|
|
||||||
|
name, err2 := database.LoadChecklistName(uuid)
|
||||||
|
if err == nil && err2 == nil {
|
||||||
|
msg, _ := json.Marshal(map[string]interface{}{
|
||||||
|
"type": "full_state",
|
||||||
|
"items": items,
|
||||||
|
})
|
||||||
|
fmt.Fprintf(w, "data: %s\n\n", msg)
|
||||||
|
flusher.Flush()
|
||||||
|
msg, _ = json.Marshal(map[string]interface{}{
|
||||||
|
"type": "checklist_name",
|
||||||
|
"name": name,
|
||||||
|
})
|
||||||
|
fmt.Fprintf(w, "data: %s\n\n", msg)
|
||||||
|
flusher.Flush()
|
||||||
|
}
|
||||||
|
|
||||||
|
// Forward events
|
||||||
|
for {
|
||||||
|
select {
|
||||||
|
case ev := <-ch:
|
||||||
|
fmt.Fprintf(w, "data: %s\n\n", ev)
|
||||||
|
flusher.Flush()
|
||||||
|
case <-r.Context().Done():
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
83
backend/main.go
Normal file
83
backend/main.go
Normal file
|
@ -0,0 +1,83 @@
|
||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"embed"
|
||||||
|
"log"
|
||||||
|
"net/http"
|
||||||
|
"os"
|
||||||
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
"gocheck/handlers"
|
||||||
|
"gocheck/static"
|
||||||
|
)
|
||||||
|
|
||||||
|
//go:embed all:frontend/dist
|
||||||
|
var staticFiles embed.FS
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
// Ensure data directory exists
|
||||||
|
if err := os.MkdirAll("data", 0755); err != nil {
|
||||||
|
log.Fatalf("Failed to create data directory: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Start the lock expiry daemon
|
||||||
|
handlers.StartLockExpiryDaemon()
|
||||||
|
|
||||||
|
// Register API handlers first
|
||||||
|
http.HandleFunc("/api/checklists", func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
if r.Method == "POST" {
|
||||||
|
handlers.HandleCreateChecklist(w, r)
|
||||||
|
} else {
|
||||||
|
http.NotFound(w, r)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
http.HandleFunc("/api/checklists/", func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
path := r.URL.Path
|
||||||
|
log.Printf("API request: %s %s", r.Method, path)
|
||||||
|
|
||||||
|
switch {
|
||||||
|
case strings.HasSuffix(path, "/name") && r.Method == "PATCH":
|
||||||
|
log.Printf("Handling PATCH checklist name")
|
||||||
|
handlers.HandleUpdateChecklistName(w, r)
|
||||||
|
case strings.HasSuffix(path, "/items") && r.Method == "GET":
|
||||||
|
log.Printf("Handling GET items")
|
||||||
|
handlers.HandleGetItems(w, r)
|
||||||
|
case strings.HasSuffix(path, "/items") && r.Method == "POST":
|
||||||
|
log.Printf("Handling POST items")
|
||||||
|
handlers.HandleAddItem(w, r)
|
||||||
|
case strings.Contains(path, "/items/") && strings.HasSuffix(path, "/lock") && r.Method == "POST":
|
||||||
|
log.Printf("Handling lock item")
|
||||||
|
handlers.HandleLockItem(w, r)
|
||||||
|
case strings.Contains(path, "/items/") && r.Method == "PATCH":
|
||||||
|
log.Printf("Handling PATCH item")
|
||||||
|
handlers.HandleUpdateItem(w, r)
|
||||||
|
case strings.Contains(path, "/items/") && r.Method == "DELETE":
|
||||||
|
log.Printf("Handling DELETE item")
|
||||||
|
handlers.HandleDeleteItem(w, r)
|
||||||
|
case strings.HasSuffix(path, "/sse") && r.Method == "GET":
|
||||||
|
log.Printf("Handling SSE")
|
||||||
|
handlers.HandleSSE(w, r)
|
||||||
|
default:
|
||||||
|
log.Printf("No handler found for %s %s", r.Method, path)
|
||||||
|
http.NotFound(w, r)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
// Serve static files from embedded filesystem (register last)
|
||||||
|
http.Handle("/", static.CompressionFileServer(staticFiles))
|
||||||
|
|
||||||
|
port := strings.TrimSpace(os.Getenv("PORT"))
|
||||||
|
if port == "" {
|
||||||
|
port = "8080"
|
||||||
|
}
|
||||||
|
parsedPort, err := strconv.Atoi(port)
|
||||||
|
if err != nil {
|
||||||
|
log.Fatalf("Invalid PORT environment variable: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
log.Printf("Listening on :%d", parsedPort)
|
||||||
|
log.Printf("Frontend available at: http://localhost:%d", parsedPort)
|
||||||
|
log.Fatal(http.ListenAndServe(":"+port, nil))
|
||||||
|
}
|
27
backend/models/models.go
Normal file
27
backend/models/models.go
Normal file
|
@ -0,0 +1,27 @@
|
||||||
|
package models
|
||||||
|
|
||||||
|
import "time"
|
||||||
|
|
||||||
|
type Checklist struct {
|
||||||
|
UUID string `json:"uuid"`
|
||||||
|
Name string `json:"name"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type ChecklistItem struct {
|
||||||
|
ID int `json:"id"`
|
||||||
|
Content string `json:"content"`
|
||||||
|
Checked bool `json:"checked"`
|
||||||
|
ParentID *int `json:"parent_id"`
|
||||||
|
LockedBy *string `json:"locked_by,omitempty"`
|
||||||
|
LockUntil *time.Time `json:"lock_until,omitempty"`
|
||||||
|
Checklist string `json:"checklist_uuid"`
|
||||||
|
Dependencies []int `json:"dependencies,omitempty"`
|
||||||
|
NotBefore *time.Time `json:"not_before,omitempty"`
|
||||||
|
NotAfter *time.Time `json:"not_after,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type ItemLock struct {
|
||||||
|
LockedBy string
|
||||||
|
Expires time.Time
|
||||||
|
ChecklistUUID string
|
||||||
|
}
|
48
backend/sse/sse.go
Normal file
48
backend/sse/sse.go
Normal file
|
@ -0,0 +1,48 @@
|
||||||
|
package sse
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"log"
|
||||||
|
"sync"
|
||||||
|
)
|
||||||
|
|
||||||
|
var (
|
||||||
|
clients = make(map[string]map[chan string]bool) // checklist uuid → set of client channels
|
||||||
|
clientsMutex sync.Mutex
|
||||||
|
)
|
||||||
|
|
||||||
|
// RegisterClient registers a new SSE client
|
||||||
|
func RegisterClient(uuid string, ch chan string) {
|
||||||
|
clientsMutex.Lock()
|
||||||
|
if clients[uuid] == nil {
|
||||||
|
clients[uuid] = make(map[chan string]bool)
|
||||||
|
}
|
||||||
|
clients[uuid][ch] = true
|
||||||
|
clientsMutex.Unlock()
|
||||||
|
}
|
||||||
|
|
||||||
|
// UnregisterClient removes an SSE client
|
||||||
|
func UnregisterClient(uuid string, ch chan string) {
|
||||||
|
clientsMutex.Lock()
|
||||||
|
delete(clients[uuid], ch)
|
||||||
|
clientsMutex.Unlock()
|
||||||
|
}
|
||||||
|
|
||||||
|
// Broadcast sends a message to all SSE clients for a checklist
|
||||||
|
func Broadcast(uuid string, msg interface{}) {
|
||||||
|
js, _ := json.Marshal(msg)
|
||||||
|
log.Printf("Broadcasting to %s: %s", uuid, string(js))
|
||||||
|
clientsMutex.Lock()
|
||||||
|
clientCount := len(clients[uuid])
|
||||||
|
log.Printf("Number of SSE clients for %s: %d", uuid, clientCount)
|
||||||
|
for ch := range clients[uuid] {
|
||||||
|
select {
|
||||||
|
case ch <- string(js):
|
||||||
|
log.Printf("Message sent to client")
|
||||||
|
default:
|
||||||
|
log.Printf("Channel full, skipping message")
|
||||||
|
// skip if channel is full (consider logging in prod!)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
clientsMutex.Unlock()
|
||||||
|
}
|
115
backend/static/static.go
Normal file
115
backend/static/static.go
Normal file
|
@ -0,0 +1,115 @@
|
||||||
|
package static
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"io/fs"
|
||||||
|
"net/http"
|
||||||
|
"path"
|
||||||
|
"strings"
|
||||||
|
)
|
||||||
|
|
||||||
|
// CompressionFileServer serves static files with compression support
|
||||||
|
func CompressionFileServer(fsys fs.FS) http.Handler {
|
||||||
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
// Check if this is a UUID path (starts with / followed by 36 characters)
|
||||||
|
isUUIDPath := len(r.URL.Path) == 37 && r.URL.Path[0] == '/' &&
|
||||||
|
!strings.Contains(r.URL.Path[1:], "/")
|
||||||
|
|
||||||
|
if r.URL.Path == "/" || isUUIDPath {
|
||||||
|
// Serve index.html at root or for routes with /{uuid}
|
||||||
|
content, err := fs.ReadFile(fsys, "frontend/dist/index.html")
|
||||||
|
if err != nil {
|
||||||
|
http.Error(w, "Not found", 404)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
w.Header().Set("Content-Type", "text/html")
|
||||||
|
w.Write(content)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// Get the requested file path relative to frontend/dist
|
||||||
|
filePath := strings.TrimPrefix(r.URL.Path, "/")
|
||||||
|
if filePath == "" {
|
||||||
|
filePath = "index.html"
|
||||||
|
}
|
||||||
|
fullPath := "frontend/dist/" + filePath
|
||||||
|
|
||||||
|
// Check if client accepts compression
|
||||||
|
acceptEncoding := r.Header.Get("Accept-Encoding")
|
||||||
|
acceptsGzip := strings.Contains(acceptEncoding, "gzip")
|
||||||
|
acceptsBrotli := strings.Contains(acceptEncoding, "br")
|
||||||
|
|
||||||
|
// Try to serve compressed version if client supports it
|
||||||
|
if acceptsBrotli {
|
||||||
|
if compressedContent, err := fs.ReadFile(fsys, fullPath+".br"); err == nil {
|
||||||
|
w.Header().Set("Content-Encoding", "br")
|
||||||
|
w.Header().Set("Content-Length", fmt.Sprintf("%d", len(compressedContent)))
|
||||||
|
w.Header().Set("Vary", "Accept-Encoding")
|
||||||
|
// Set appropriate content type based on file extension
|
||||||
|
setContentType(w, filePath)
|
||||||
|
w.Write(compressedContent)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if acceptsGzip {
|
||||||
|
if compressedContent, err := fs.ReadFile(fsys, fullPath+".gz"); err == nil {
|
||||||
|
w.Header().Set("Content-Encoding", "gzip")
|
||||||
|
w.Header().Set("Content-Length", fmt.Sprintf("%d", len(compressedContent)))
|
||||||
|
w.Header().Set("Vary", "Accept-Encoding")
|
||||||
|
// Set appropriate content type based on file extension
|
||||||
|
setContentType(w, filePath)
|
||||||
|
w.Write(compressedContent)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Fall back to uncompressed file
|
||||||
|
if content, err := fs.ReadFile(fsys, fullPath); err == nil {
|
||||||
|
w.Header().Set("Vary", "Accept-Encoding")
|
||||||
|
// Set appropriate content type based on file extension
|
||||||
|
setContentType(w, filePath)
|
||||||
|
w.Write(content)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// File not found
|
||||||
|
http.NotFound(w, r)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// setContentType sets the appropriate Content-Type header based on file extension
|
||||||
|
func setContentType(w http.ResponseWriter, filePath string) {
|
||||||
|
ext := strings.ToLower(path.Ext(filePath))
|
||||||
|
switch ext {
|
||||||
|
case ".html":
|
||||||
|
w.Header().Set("Content-Type", "text/html; charset=utf-8")
|
||||||
|
case ".css":
|
||||||
|
w.Header().Set("Content-Type", "text/css; charset=utf-8")
|
||||||
|
case ".js":
|
||||||
|
w.Header().Set("Content-Type", "application/javascript; charset=utf-8")
|
||||||
|
case ".json":
|
||||||
|
w.Header().Set("Content-Type", "application/json; charset=utf-8")
|
||||||
|
case ".svg":
|
||||||
|
w.Header().Set("Content-Type", "image/svg+xml")
|
||||||
|
case ".png":
|
||||||
|
w.Header().Set("Content-Type", "image/png")
|
||||||
|
case ".jpg", ".jpeg":
|
||||||
|
w.Header().Set("Content-Type", "image/jpeg")
|
||||||
|
case ".gif":
|
||||||
|
w.Header().Set("Content-Type", "image/gif")
|
||||||
|
case ".ico":
|
||||||
|
w.Header().Set("Content-Type", "image/x-icon")
|
||||||
|
case ".woff":
|
||||||
|
w.Header().Set("Content-Type", "font/woff")
|
||||||
|
case ".woff2":
|
||||||
|
w.Header().Set("Content-Type", "font/woff2")
|
||||||
|
case ".ttf":
|
||||||
|
w.Header().Set("Content-Type", "font/ttf")
|
||||||
|
case ".eot":
|
||||||
|
w.Header().Set("Content-Type", "application/vnd.ms-fontobject")
|
||||||
|
default:
|
||||||
|
// Default to octet-stream for unknown types
|
||||||
|
w.Header().Set("Content-Type", "application/octet-stream")
|
||||||
|
}
|
||||||
|
}
|
115
build-and-push.sh
Executable file
115
build-and-push.sh
Executable file
|
@ -0,0 +1,115 @@
|
||||||
|
#!/usr/bin/env bash
|
||||||
|
|
||||||
|
# Build and push multi-arch container images
|
||||||
|
# Supports both Podman and Docker
|
||||||
|
|
||||||
|
set -e
|
||||||
|
|
||||||
|
# Configuration
|
||||||
|
MANIFEST=git.hannover.ccc.de/lubiana/cheekylist
|
||||||
|
AMD=${MANIFEST}:amd64
|
||||||
|
ARM=${MANIFEST}:arm64
|
||||||
|
|
||||||
|
# Colors for output
|
||||||
|
RED='\033[0;31m'
|
||||||
|
GREEN='\033[0;32m'
|
||||||
|
YELLOW='\033[1;33m'
|
||||||
|
BLUE='\033[0;34m'
|
||||||
|
NC='\033[0m' # No Color
|
||||||
|
|
||||||
|
# Detect container runtime
|
||||||
|
CONTAINER_CMD=""
|
||||||
|
|
||||||
|
if command -v podman &> /dev/null; then
|
||||||
|
CONTAINER_CMD="podman"
|
||||||
|
elif command -v docker &> /dev/null; then
|
||||||
|
CONTAINER_CMD="docker"
|
||||||
|
else
|
||||||
|
echo -e "${RED}❌ Neither Podman nor Docker found. Please install one of them.${NC}"
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
echo -e "${BLUE}🚀 Building multi-arch images with ${CONTAINER_CMD}...${NC}"
|
||||||
|
|
||||||
|
# Check if runtime is available
|
||||||
|
if ! $CONTAINER_CMD info > /dev/null 2>&1; then
|
||||||
|
echo -e "${RED}❌ ${CONTAINER_CMD} is not running or not properly configured.${NC}"
|
||||||
|
if [ "$CONTAINER_CMD" = "podman" ]; then
|
||||||
|
echo -e "${YELLOW}💡 Try running: podman machine start${NC}"
|
||||||
|
else
|
||||||
|
echo -e "${YELLOW}💡 Please start Docker Desktop${NC}"
|
||||||
|
fi
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
# Handle manifest differently for Docker vs Podman
|
||||||
|
if [ "$CONTAINER_CMD" = "docker" ]; then
|
||||||
|
# Docker uses buildx for multi-arch builds
|
||||||
|
if ! docker buildx version > /dev/null 2>&1; then
|
||||||
|
echo -e "${RED}❌ Docker buildx not found. Please update Docker.${NC}"
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
# Create or use existing buildx instance
|
||||||
|
BUILDER_NAME="gocheck-builder"
|
||||||
|
if ! docker buildx ls | grep -q "$BUILDER_NAME"; then
|
||||||
|
echo -e "${YELLOW}📦 Creating buildx instance...${NC}"
|
||||||
|
docker buildx create --name "$BUILDER_NAME" --use
|
||||||
|
else
|
||||||
|
docker buildx use "$BUILDER_NAME"
|
||||||
|
fi
|
||||||
|
|
||||||
|
# Build and push multi-arch image
|
||||||
|
echo -e "${YELLOW}📦 Building and pushing multi-arch image...${NC}"
|
||||||
|
docker buildx build \
|
||||||
|
--platform linux/amd64,linux/arm64 \
|
||||||
|
--tag "$MANIFEST:latest" \
|
||||||
|
--tag "$MANIFEST:$(date +%Y%m%d)" \
|
||||||
|
--push \
|
||||||
|
-f Containerfile \
|
||||||
|
.
|
||||||
|
|
||||||
|
echo -e "${GREEN}✅ Multi-arch image pushed to $MANIFEST${NC}"
|
||||||
|
|
||||||
|
else
|
||||||
|
# Podman approach
|
||||||
|
# Remove existing manifest if it exists
|
||||||
|
$CONTAINER_CMD manifest exists $MANIFEST 2>/dev/null && $CONTAINER_CMD manifest rm $MANIFEST
|
||||||
|
|
||||||
|
# Create new manifest
|
||||||
|
echo -e "${YELLOW}📦 Creating manifest...${NC}"
|
||||||
|
$CONTAINER_CMD manifest create $MANIFEST
|
||||||
|
|
||||||
|
# Build AMD64
|
||||||
|
echo -e "${YELLOW}📦 Building AMD64 image...${NC}"
|
||||||
|
$CONTAINER_CMD build --arch=amd64 -t $AMD -f Containerfile .
|
||||||
|
|
||||||
|
# Build ARM64
|
||||||
|
echo -e "${YELLOW}📦 Building ARM64 image...${NC}"
|
||||||
|
$CONTAINER_CMD build --arch=arm64 -t $ARM -f Containerfile .
|
||||||
|
|
||||||
|
# Add to manifest
|
||||||
|
echo -e "${YELLOW}📦 Adding images to manifest...${NC}"
|
||||||
|
$CONTAINER_CMD manifest add $MANIFEST $AMD
|
||||||
|
$CONTAINER_CMD manifest add $MANIFEST $ARM
|
||||||
|
|
||||||
|
# Push manifest
|
||||||
|
echo -e "${YELLOW}📦 Pushing manifest...${NC}"
|
||||||
|
$CONTAINER_CMD manifest push $MANIFEST
|
||||||
|
|
||||||
|
# Also tag and push as latest
|
||||||
|
$CONTAINER_CMD tag $MANIFEST $MANIFEST:latest
|
||||||
|
$CONTAINER_CMD manifest push $MANIFEST:latest
|
||||||
|
|
||||||
|
# Tag with date
|
||||||
|
DATE_TAG=$MANIFEST:$(date +%Y%m%d)
|
||||||
|
$CONTAINER_CMD tag $MANIFEST $DATE_TAG
|
||||||
|
$CONTAINER_CMD manifest push $DATE_TAG
|
||||||
|
|
||||||
|
echo -e "${GREEN}✅ Multi-arch manifest pushed to $MANIFEST${NC}"
|
||||||
|
fi
|
||||||
|
|
||||||
|
echo -e "${GREEN}✅ Build and push completed successfully!${NC}"
|
||||||
|
echo -e "${BLUE}📋 Images available at:${NC}"
|
||||||
|
echo -e " - ${MANIFEST}:latest"
|
||||||
|
echo -e " - ${MANIFEST}:$(date +%Y%m%d)"
|
29
build.sh
Executable file
29
build.sh
Executable file
|
@ -0,0 +1,29 @@
|
||||||
|
#!/bin/bash
|
||||||
|
|
||||||
|
# Build script for GoCheck
|
||||||
|
|
||||||
|
echo "🏗️ Building GoCheck..."
|
||||||
|
|
||||||
|
# Build frontend
|
||||||
|
echo "📦 Building frontend..."
|
||||||
|
cd frontend
|
||||||
|
npm install
|
||||||
|
npm run build
|
||||||
|
cd ..
|
||||||
|
|
||||||
|
# Copy frontend dist to backend for embedding
|
||||||
|
echo "📋 Copying frontend dist to backend..."
|
||||||
|
rm -rf backend/frontend
|
||||||
|
mkdir -p backend/frontend
|
||||||
|
cp -r frontend/dist backend/frontend/
|
||||||
|
|
||||||
|
# Build backend
|
||||||
|
echo "🔨 Building backend..."
|
||||||
|
cd backend
|
||||||
|
go build -o gocheck
|
||||||
|
cd ..
|
||||||
|
|
||||||
|
# Move binary to root
|
||||||
|
mv backend/gocheck .
|
||||||
|
|
||||||
|
echo "✅ Build complete! Binary is at ./gocheck"
|
112
dev-docker.sh
Executable file
112
dev-docker.sh
Executable file
|
@ -0,0 +1,112 @@
|
||||||
|
#!/bin/bash
|
||||||
|
|
||||||
|
# Development script using Podman/Docker with hot reload support
|
||||||
|
# This script builds and runs the development container
|
||||||
|
|
||||||
|
set -e
|
||||||
|
|
||||||
|
# Colors for output
|
||||||
|
RED='\033[0;31m'
|
||||||
|
GREEN='\033[0;32m'
|
||||||
|
YELLOW='\033[1;33m'
|
||||||
|
BLUE='\033[0;34m'
|
||||||
|
NC='\033[0m' # No Color
|
||||||
|
|
||||||
|
# Detect container runtime
|
||||||
|
CONTAINER_RUNTIME=""
|
||||||
|
COMPOSE_COMMAND=""
|
||||||
|
|
||||||
|
# Check for podman first (preferred)
|
||||||
|
if command -v podman &> /dev/null; then
|
||||||
|
CONTAINER_RUNTIME="podman"
|
||||||
|
# Check for podman-compose
|
||||||
|
if command -v podman-compose &> /dev/null; then
|
||||||
|
COMPOSE_COMMAND="podman-compose"
|
||||||
|
# Check if docker-compose works with podman
|
||||||
|
elif command -v docker-compose &> /dev/null; then
|
||||||
|
# Test if docker-compose can work with podman
|
||||||
|
if docker-compose version &> /dev/null; then
|
||||||
|
COMPOSE_COMMAND="docker-compose"
|
||||||
|
fi
|
||||||
|
fi
|
||||||
|
# Check for docker
|
||||||
|
elif command -v docker &> /dev/null; then
|
||||||
|
CONTAINER_RUNTIME="docker"
|
||||||
|
if command -v docker-compose &> /dev/null; then
|
||||||
|
COMPOSE_COMMAND="docker-compose"
|
||||||
|
elif docker compose version &> /dev/null 2>&1; then
|
||||||
|
COMPOSE_COMMAND="docker compose"
|
||||||
|
fi
|
||||||
|
else
|
||||||
|
echo -e "${RED}❌ Neither Podman nor Docker found. Please install one of them.${NC}"
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
# Check if compose command was found
|
||||||
|
if [ -z "$COMPOSE_COMMAND" ]; then
|
||||||
|
echo -e "${RED}❌ No compose command found (podman-compose or docker-compose).${NC}"
|
||||||
|
if [ "$CONTAINER_RUNTIME" = "podman" ]; then
|
||||||
|
echo -e "${YELLOW}💡 Install podman-compose with: pip install podman-compose${NC}"
|
||||||
|
fi
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
# Function to cleanup
|
||||||
|
cleanup() {
|
||||||
|
echo -e "\n${YELLOW}🛑 Shutting down development container...${NC}"
|
||||||
|
$COMPOSE_COMMAND -f docker-compose.dev.yml down
|
||||||
|
echo -e "${GREEN}✅ Development environment stopped${NC}"
|
||||||
|
exit 0
|
||||||
|
}
|
||||||
|
|
||||||
|
# Set up signal handlers
|
||||||
|
trap cleanup SIGINT SIGTERM
|
||||||
|
|
||||||
|
echo -e "${BLUE}🚀 Starting GoCheck development environment with ${CONTAINER_RUNTIME}...${NC}"
|
||||||
|
echo -e "${GREEN}📋 Using: $COMPOSE_COMMAND${NC}"
|
||||||
|
|
||||||
|
# Check if container runtime is running
|
||||||
|
if [ "$CONTAINER_RUNTIME" = "podman" ]; then
|
||||||
|
if ! podman info > /dev/null 2>&1; then
|
||||||
|
echo -e "${RED}❌ Podman is not running or not properly configured.${NC}"
|
||||||
|
echo -e "${YELLOW}💡 Try running: podman machine start${NC}"
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
else
|
||||||
|
if ! docker info > /dev/null 2>&1; then
|
||||||
|
echo -e "${RED}❌ Docker is not running. Please start Docker and try again.${NC}"
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
fi
|
||||||
|
|
||||||
|
# For Podman, we might need to set DOCKER_HOST if not already set
|
||||||
|
if [ "$CONTAINER_RUNTIME" = "podman" ] && [ -z "$DOCKER_HOST" ]; then
|
||||||
|
# Check if podman machine is running and get socket path
|
||||||
|
if podman machine list --format "{{.Name}}\t{{.VMType}}\t{{.Running}}" | grep -q "true"; then
|
||||||
|
# Try to get the podman socket path
|
||||||
|
PODMAN_SOCKET=$(podman machine inspect --format "{{.ConnectionInfo.PodmanSocket.Path}}" 2>/dev/null || echo "")
|
||||||
|
if [ -n "$PODMAN_SOCKET" ]; then
|
||||||
|
export DOCKER_HOST="unix://$PODMAN_SOCKET"
|
||||||
|
echo -e "${YELLOW}📌 Set DOCKER_HOST=$DOCKER_HOST${NC}"
|
||||||
|
fi
|
||||||
|
fi
|
||||||
|
fi
|
||||||
|
|
||||||
|
# Build and start the development container
|
||||||
|
echo -e "${YELLOW}📦 Building development container...${NC}"
|
||||||
|
|
||||||
|
# Add platform flag for better compatibility
|
||||||
|
PLATFORM_FLAG=""
|
||||||
|
if [ "$CONTAINER_RUNTIME" = "podman" ]; then
|
||||||
|
# Podman typically handles platform detection automatically
|
||||||
|
PLATFORM_FLAG=""
|
||||||
|
elif [ "$(uname -m)" = "arm64" ] || [ "$(uname -m)" = "aarch64" ]; then
|
||||||
|
# For Docker on ARM64 (M1/M2 Macs)
|
||||||
|
PLATFORM_FLAG="--platform linux/amd64"
|
||||||
|
fi
|
||||||
|
|
||||||
|
# Run the compose command
|
||||||
|
$COMPOSE_COMMAND -f docker-compose.dev.yml up --build $PLATFORM_FLAG
|
||||||
|
|
||||||
|
# The container will keep running until interrupted
|
||||||
|
# When interrupted, the cleanup function will be called
|
65
dev.sh
Executable file
65
dev.sh
Executable file
|
@ -0,0 +1,65 @@
|
||||||
|
#!/bin/bash
|
||||||
|
|
||||||
|
# Function to cleanup processes
|
||||||
|
cleanup() {
|
||||||
|
echo ""
|
||||||
|
echo "🛑 Shutting down processes..."
|
||||||
|
|
||||||
|
# Kill child processes
|
||||||
|
if [ ! -z "$AIR_PID" ]; then
|
||||||
|
echo " Stopping Air server (PID: $AIR_PID)..."
|
||||||
|
kill $AIR_PID 2>/dev/null || true
|
||||||
|
fi
|
||||||
|
|
||||||
|
if [ ! -z "$VITE_PID" ]; then
|
||||||
|
echo " Stopping Vite server (PID: $VITE_PID)..."
|
||||||
|
kill $VITE_PID 2>/dev/null || true
|
||||||
|
fi
|
||||||
|
|
||||||
|
# Kill any remaining processes
|
||||||
|
pkill -f "gocheck" 2>/dev/null || true
|
||||||
|
pkill -f "vite" 2>/dev/null || true
|
||||||
|
pkill -f "esbuild" 2>/dev/null || true
|
||||||
|
pkill -f "air" 2>/dev/null || true
|
||||||
|
|
||||||
|
echo "✅ All processes stopped"
|
||||||
|
exit 0
|
||||||
|
}
|
||||||
|
|
||||||
|
# Set up signal handlers
|
||||||
|
trap cleanup SIGINT SIGTERM
|
||||||
|
|
||||||
|
# Kill any existing processes
|
||||||
|
echo "🔄 Cleaning up existing processes..."
|
||||||
|
pkill -f "gocheck" 2>/dev/null || true
|
||||||
|
pkill -f "vite" 2>/dev/null || true
|
||||||
|
pkill -f "esbuild" 2>/dev/null || true
|
||||||
|
pkill -f "air" 2>/dev/null || true
|
||||||
|
sleep 1
|
||||||
|
|
||||||
|
# Verify processes are killed
|
||||||
|
if pgrep -f "gocheck\|vite\|esbuild\|air" > /dev/null; then
|
||||||
|
echo "⚠️ Some processes are still running. Force killing..."
|
||||||
|
pkill -9 -f "gocheck" 2>/dev/null || true
|
||||||
|
pkill -9 -f "vite" 2>/dev/null || true
|
||||||
|
pkill -9 -f "esbuild" 2>/dev/null || true
|
||||||
|
pkill -9 -f "air" 2>/dev/null || true
|
||||||
|
sleep 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
echo "✅ Process cleanup completed"
|
||||||
|
|
||||||
|
# Run the server
|
||||||
|
echo "🚀 Starting Go server with Air..."
|
||||||
|
cd backend && air &
|
||||||
|
AIR_PID=$!
|
||||||
|
|
||||||
|
# Run the frontend
|
||||||
|
echo "🎨 Starting frontend development server..."
|
||||||
|
sleep 2
|
||||||
|
(cd frontend && npm run dev) &
|
||||||
|
VITE_PID=$!
|
||||||
|
|
||||||
|
# Wait for both processes
|
||||||
|
echo "📡 Development servers running. Press Ctrl+C to stop."
|
||||||
|
wait
|
41
docker-compose.dev.yml
Normal file
41
docker-compose.dev.yml
Normal file
|
@ -0,0 +1,41 @@
|
||||||
|
version: '3.8'
|
||||||
|
|
||||||
|
services:
|
||||||
|
gocheck-dev:
|
||||||
|
build:
|
||||||
|
context: .
|
||||||
|
dockerfile: Dockerfile.dev
|
||||||
|
container_name: gocheck-dev
|
||||||
|
ports:
|
||||||
|
- "8080:8080" # Backend port
|
||||||
|
- "5173:5173" # Frontend port
|
||||||
|
volumes:
|
||||||
|
# Mount source code for hot reloading
|
||||||
|
- .:/app
|
||||||
|
# Exclude node_modules to avoid conflicts
|
||||||
|
- /app/frontend/node_modules
|
||||||
|
# Exclude backend Go modules to avoid conflicts
|
||||||
|
- /app/backend/go.sum
|
||||||
|
- /app/backend/go.mod
|
||||||
|
# Persist data directory
|
||||||
|
- gocheck-dev-data:/app/backend/data
|
||||||
|
environment:
|
||||||
|
- NODE_ENV=development
|
||||||
|
- GO_ENV=development
|
||||||
|
# Enable Vite host binding for external access
|
||||||
|
- VITE_HOST=0.0.0.0
|
||||||
|
networks:
|
||||||
|
- gocheck-dev-network
|
||||||
|
# Enable interactive mode for better development experience
|
||||||
|
stdin_open: true
|
||||||
|
tty: true
|
||||||
|
# Restart policy for development
|
||||||
|
restart: unless-stopped
|
||||||
|
|
||||||
|
networks:
|
||||||
|
gocheck-dev-network:
|
||||||
|
driver: bridge
|
||||||
|
|
||||||
|
volumes:
|
||||||
|
gocheck-dev-data:
|
||||||
|
driver: local
|
31
docker-compose.yml
Normal file
31
docker-compose.yml
Normal file
|
@ -0,0 +1,31 @@
|
||||||
|
version: '3.8'
|
||||||
|
|
||||||
|
services:
|
||||||
|
gocheck:
|
||||||
|
build:
|
||||||
|
context: .
|
||||||
|
dockerfile: Containerfile
|
||||||
|
args:
|
||||||
|
USER_ID: 1000
|
||||||
|
GROUP_ID: 1000
|
||||||
|
container_name: gocheck-container
|
||||||
|
ports:
|
||||||
|
- "${PORT:-8080}:8080"
|
||||||
|
environment:
|
||||||
|
- PORT=8080
|
||||||
|
volumes:
|
||||||
|
- gocheck-data:/app/backend/data
|
||||||
|
restart: unless-stopped
|
||||||
|
# Rootless Podman compatibility
|
||||||
|
security_opt:
|
||||||
|
- no-new-privileges:true
|
||||||
|
healthcheck:
|
||||||
|
test: [ "CMD", "wget", "--no-verbose", "--tries=1", "--spider", "http://localhost:8080/" ]
|
||||||
|
interval: 30s
|
||||||
|
timeout: 10s
|
||||||
|
retries: 3
|
||||||
|
start_period: 10s
|
||||||
|
|
||||||
|
volumes:
|
||||||
|
gocheck-data:
|
||||||
|
driver: local
|
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?
|
69
frontend/README.md
Normal file
69
frontend/README.md
Normal file
|
@ -0,0 +1,69 @@
|
||||||
|
# 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/) 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
|
||||||
|
|
||||||
|
## 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 tseslint.config([
|
||||||
|
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 tseslint.config([
|
||||||
|
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 { globalIgnores } from 'eslint/config'
|
||||||
|
|
||||||
|
export default tseslint.config([
|
||||||
|
globalIgnores(['dist']),
|
||||||
|
{
|
||||||
|
files: ['**/*.{ts,tsx}'],
|
||||||
|
extends: [
|
||||||
|
js.configs.recommended,
|
||||||
|
tseslint.configs.recommended,
|
||||||
|
reactHooks.configs['recommended-latest'],
|
||||||
|
reactRefresh.configs.vite,
|
||||||
|
],
|
||||||
|
languageOptions: {
|
||||||
|
ecmaVersion: 2020,
|
||||||
|
globals: globals.browser,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
])
|
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="/favicon.svg" />
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||||
|
<title>Cheekylist</title>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<div id="root"></div>
|
||||||
|
<script type="module" src="/src/main.tsx"></script>
|
||||||
|
</body>
|
||||||
|
</html>
|
5672
frontend/package-lock.json
generated
Normal file
5672
frontend/package-lock.json
generated
Normal file
File diff suppressed because it is too large
Load diff
44
frontend/package.json
Normal file
44
frontend/package.json
Normal file
|
@ -0,0 +1,44 @@
|
||||||
|
{
|
||||||
|
"name": "frontend",
|
||||||
|
"private": true,
|
||||||
|
"version": "0.0.0",
|
||||||
|
"type": "module",
|
||||||
|
"scripts": {
|
||||||
|
"dev": "vite",
|
||||||
|
"build": "tsc -b && vite build",
|
||||||
|
"lint": "eslint .",
|
||||||
|
"preview": "vite preview"
|
||||||
|
},
|
||||||
|
"dependencies": {
|
||||||
|
"@radix-ui/colors": "^3.0.0",
|
||||||
|
"@radix-ui/react-checkbox": "^1.3.2",
|
||||||
|
"@radix-ui/react-dialog": "^1.1.14",
|
||||||
|
"@radix-ui/react-dropdown-menu": "^2.1.15",
|
||||||
|
"@radix-ui/react-icons": "^1.3.2",
|
||||||
|
"@radix-ui/react-select": "^2.2.5",
|
||||||
|
"@radix-ui/react-switch": "^1.2.5",
|
||||||
|
"@radix-ui/react-tooltip": "^1.2.7",
|
||||||
|
"@radix-ui/themes": "^3.2.1",
|
||||||
|
"@tailwindcss/vite": "^4.1.11",
|
||||||
|
"@types/react-datepicker": "^6.2.0",
|
||||||
|
"react": "^19.1.0",
|
||||||
|
"react-datepicker": "^8.4.0",
|
||||||
|
"react-dom": "^19.1.0",
|
||||||
|
"react-router-dom": "^7.7.0",
|
||||||
|
"tailwindcss": "^4.1.11"
|
||||||
|
},
|
||||||
|
"devDependencies": {
|
||||||
|
"@eslint/js": "^9.30.1",
|
||||||
|
"@types/react": "^19.1.8",
|
||||||
|
"@types/react-dom": "^19.1.6",
|
||||||
|
"@vitejs/plugin-react-swc": "^3.10.2",
|
||||||
|
"eslint": "^9.30.1",
|
||||||
|
"eslint-plugin-react-hooks": "^5.2.0",
|
||||||
|
"eslint-plugin-react-refresh": "^0.4.20",
|
||||||
|
"globals": "^16.3.0",
|
||||||
|
"typescript": "~5.8.3",
|
||||||
|
"typescript-eslint": "^8.35.1",
|
||||||
|
"vite": "^7.0.4",
|
||||||
|
"vite-plugin-compression2": "^2.2.0"
|
||||||
|
}
|
||||||
|
}
|
3
frontend/public/favicon.svg
Normal file
3
frontend/public/favicon.svg
Normal file
|
@ -0,0 +1,3 @@
|
||||||
|
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100">
|
||||||
|
<text x="50" y="70" font-family="Arial, sans-serif" font-size="60" text-anchor="middle" fill="#000000">📝</text>
|
||||||
|
</svg>
|
After Width: | Height: | Size: 187 B |
18
frontend/src/App.tsx
Normal file
18
frontend/src/App.tsx
Normal file
|
@ -0,0 +1,18 @@
|
||||||
|
import { BrowserRouter as Router, Routes, Route } from 'react-router-dom'
|
||||||
|
import Home from './pages/Home'
|
||||||
|
import Checklist from './pages/Checklist'
|
||||||
|
|
||||||
|
function App() {
|
||||||
|
return (
|
||||||
|
<Router>
|
||||||
|
<div className="App">
|
||||||
|
<Routes>
|
||||||
|
<Route path="/" element={<Home />} />
|
||||||
|
<Route path="/:uuid" element={<Checklist />} />
|
||||||
|
</Routes>
|
||||||
|
</div>
|
||||||
|
</Router>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export default App
|
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 KiB |
388
frontend/src/components/ChecklistItem.tsx
Normal file
388
frontend/src/components/ChecklistItem.tsx
Normal file
|
@ -0,0 +1,388 @@
|
||||||
|
import { useState, useRef, useEffect } from 'react'
|
||||||
|
import type { ChecklistItem as ChecklistItemType } from '../types'
|
||||||
|
import DependencyManager from './DependencyManager'
|
||||||
|
import { DateConstraintManager } from './DateConstraintManager'
|
||||||
|
import { Checkbox, Flex, Box, Text, IconButton, Badge, Tooltip } from '@radix-ui/themes'
|
||||||
|
import { LockClosedIcon, TrashIcon, ClockIcon, LinkBreak2Icon } from '@radix-ui/react-icons'
|
||||||
|
|
||||||
|
interface ChecklistItemProps {
|
||||||
|
item: ChecklistItemType
|
||||||
|
onUpdate: (id: number, updates: Partial<ChecklistItemType>) => Promise<void>
|
||||||
|
onDelete: (id: number) => Promise<void>
|
||||||
|
onLock: (id: number, user: string) => Promise<void>
|
||||||
|
depth?: number
|
||||||
|
children?: ChecklistItemType[]
|
||||||
|
allItems?: ChecklistItemType[]
|
||||||
|
}
|
||||||
|
|
||||||
|
export default function ChecklistItem({
|
||||||
|
item,
|
||||||
|
onUpdate,
|
||||||
|
onDelete,
|
||||||
|
onLock,
|
||||||
|
depth = 0,
|
||||||
|
children = [],
|
||||||
|
allItems = []
|
||||||
|
}: ChecklistItemProps) {
|
||||||
|
const [isEditing, setIsEditing] = useState(false)
|
||||||
|
const [isDeleting, setIsDeleting] = useState(false)
|
||||||
|
const [isDependencyModalOpen, setIsDependencyModalOpen] = useState(false)
|
||||||
|
const [isDateConstraintModalOpen, setIsDateConstraintModalOpen] = useState(false)
|
||||||
|
const [userName, setUserName] = useState('')
|
||||||
|
const contentRef = useRef<HTMLDivElement>(null)
|
||||||
|
|
||||||
|
const isLocked = item.locked_by && item.lock_until && new Date(item.lock_until) > new Date()
|
||||||
|
const isLockedByMe = isLocked && item.locked_by === userName
|
||||||
|
|
||||||
|
// Check if all dependencies are completed
|
||||||
|
const dependenciesCompleted = item.dependencies?.every(depId => {
|
||||||
|
const depItem = allItems.find(i => i.id === depId)
|
||||||
|
return depItem?.checked
|
||||||
|
}) ?? true
|
||||||
|
|
||||||
|
// Check date constraints
|
||||||
|
const now = new Date()
|
||||||
|
const notBeforeDate = item.not_before ? new Date(item.not_before) : null
|
||||||
|
const notAfterDate = item.not_after ? new Date(item.not_after) : null
|
||||||
|
const dateConstraintsMet = (!notBeforeDate || now >= notBeforeDate) && (!notAfterDate || now <= notAfterDate)
|
||||||
|
|
||||||
|
// Check if item can be completed (all dependencies met and date constraints met)
|
||||||
|
const canComplete = (dependenciesCompleted && dateConstraintsMet) || item.checked
|
||||||
|
|
||||||
|
// Get dependency items for display
|
||||||
|
const dependencyItems = item.dependencies?.map(depId =>
|
||||||
|
allItems.find(i => i.id === depId)
|
||||||
|
).filter(Boolean) ?? []
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
// Generate a random user name if not set
|
||||||
|
if (!userName) {
|
||||||
|
const randomName = `user_${Math.random().toString(36).substr(2, 9)}`
|
||||||
|
setUserName(randomName)
|
||||||
|
}
|
||||||
|
}, [userName])
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (isEditing && contentRef.current) {
|
||||||
|
contentRef.current.focus()
|
||||||
|
// Select all text when entering edit mode
|
||||||
|
const range = document.createRange()
|
||||||
|
range.selectNodeContents(contentRef.current)
|
||||||
|
const selection = window.getSelection()
|
||||||
|
selection?.removeAllRanges()
|
||||||
|
selection?.addRange(range)
|
||||||
|
}
|
||||||
|
}, [isEditing])
|
||||||
|
|
||||||
|
const handleEdit = async () => {
|
||||||
|
if (isLocked && !isLockedByMe) {
|
||||||
|
alert('This item is being edited by someone else')
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!isLockedByMe) {
|
||||||
|
try {
|
||||||
|
await onLock(item.id, userName)
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Failed to lock item:', error)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
setIsEditing(true)
|
||||||
|
}
|
||||||
|
|
||||||
|
const handleSave = async () => {
|
||||||
|
const newContent = contentRef.current?.textContent?.trim() || ''
|
||||||
|
if (newContent === '') return
|
||||||
|
|
||||||
|
try {
|
||||||
|
await onUpdate(item.id, { content: newContent })
|
||||||
|
setIsEditing(false)
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Failed to update item:', error)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const handleCancel = () => {
|
||||||
|
if (contentRef.current) {
|
||||||
|
contentRef.current.textContent = item.content
|
||||||
|
}
|
||||||
|
setIsEditing(false)
|
||||||
|
}
|
||||||
|
|
||||||
|
const handleDelete = async () => {
|
||||||
|
if (confirm('Are you sure you want to delete this item?')) {
|
||||||
|
try {
|
||||||
|
setIsDeleting(true)
|
||||||
|
await onDelete(item.id)
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Failed to delete item:', error)
|
||||||
|
} finally {
|
||||||
|
setIsDeleting(false)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const handleToggleCheck = async () => {
|
||||||
|
// Don't allow unchecking if already checked
|
||||||
|
if (item.checked) {
|
||||||
|
try {
|
||||||
|
await onUpdate(item.id, { checked: false })
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Failed to uncheck item:', error)
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check if dependencies are met before allowing completion
|
||||||
|
if (!dependenciesCompleted) {
|
||||||
|
alert(`Cannot complete this item. The following dependencies must be completed first:\n\n${dependencyItems.map(dep => `• ${dep?.content}`).join('\n')}`)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check if date constraints are met
|
||||||
|
if (!dateConstraintsMet) {
|
||||||
|
let message = 'Cannot complete this item due to date constraints:\n\n'
|
||||||
|
if (notBeforeDate && now < notBeforeDate) {
|
||||||
|
message += `• Cannot complete before ${notBeforeDate.toLocaleString()}\n`
|
||||||
|
}
|
||||||
|
if (notAfterDate && now > notAfterDate) {
|
||||||
|
message += `• Cannot complete after ${notAfterDate.toLocaleString()}\n`
|
||||||
|
}
|
||||||
|
alert(message)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
await onUpdate(item.id, { checked: true })
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Failed to toggle item:', error)
|
||||||
|
if (error instanceof Error && error.message.includes('cannot complete item:')) {
|
||||||
|
alert(error.message)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const handleKeyDown = (e: React.KeyboardEvent) => {
|
||||||
|
if (e.key === 'Enter') {
|
||||||
|
e.preventDefault()
|
||||||
|
handleSave()
|
||||||
|
} else if (e.key === 'Escape') {
|
||||||
|
e.preventDefault()
|
||||||
|
handleCancel()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const handleBlur = () => {
|
||||||
|
// Small delay to allow for button clicks
|
||||||
|
setTimeout(() => {
|
||||||
|
if (isEditing) {
|
||||||
|
handleSave()
|
||||||
|
}
|
||||||
|
}, 100)
|
||||||
|
}
|
||||||
|
|
||||||
|
const handleDateConstraintSave = async (notBefore?: string, notAfter?: string) => {
|
||||||
|
try {
|
||||||
|
await onUpdate(item.id, { not_before: notBefore, not_after: notAfter })
|
||||||
|
setIsDateConstraintModalOpen(false)
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Failed to update date constraints:', error)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Box asChild>
|
||||||
|
<li style={{ listStyle: 'none' }}>
|
||||||
|
<Flex
|
||||||
|
gap="3"
|
||||||
|
align="start"
|
||||||
|
p="3"
|
||||||
|
className="group rounded-lg hover:bg-gray-50 dark:hover:bg-gray-800/50 transition-all duration-200 border border-transparent hover:border-gray-200 dark:hover:border-gray-700"
|
||||||
|
>
|
||||||
|
<Box mt="1">
|
||||||
|
<Checkbox
|
||||||
|
checked={item.checked}
|
||||||
|
onCheckedChange={handleToggleCheck}
|
||||||
|
disabled={Boolean(isLocked && !isLockedByMe) || (!item.checked && !canComplete)}
|
||||||
|
size="2"
|
||||||
|
/>
|
||||||
|
</Box>
|
||||||
|
|
||||||
|
<Box style={{ flex: 1, minWidth: 0 }}>
|
||||||
|
{isEditing ? (
|
||||||
|
<Box
|
||||||
|
ref={contentRef}
|
||||||
|
contentEditable={true}
|
||||||
|
suppressContentEditableWarning={true}
|
||||||
|
onKeyDown={handleKeyDown}
|
||||||
|
onBlur={handleBlur}
|
||||||
|
className="px-3 py-2 border-2 border-blue-500 rounded-md focus:ring-2 focus:ring-blue-200 dark:focus:ring-blue-800 bg-white dark:bg-gray-800 shadow-sm outline-none"
|
||||||
|
style={{ minHeight: '28px' }}
|
||||||
|
>
|
||||||
|
{item.content}
|
||||||
|
</Box>
|
||||||
|
) : (
|
||||||
|
<Text
|
||||||
|
size="2"
|
||||||
|
onClick={handleEdit}
|
||||||
|
className={`cursor-pointer hover:text-blue-600 dark:hover:text-blue-400 ${
|
||||||
|
item.checked ? 'line-through opacity-75' : ''
|
||||||
|
} ${
|
||||||
|
!item.checked && !canComplete ? 'opacity-60' : ''
|
||||||
|
}`}
|
||||||
|
color={item.checked ? "gray" : undefined}
|
||||||
|
>
|
||||||
|
{item.content}
|
||||||
|
</Text>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* Consolidated status indicators - only show when item cannot be completed */}
|
||||||
|
{!item.checked && !canComplete && (
|
||||||
|
<Flex gap="1" mt="1" align="center">
|
||||||
|
{/* Single consolidated status indicator */}
|
||||||
|
<Badge
|
||||||
|
color="orange"
|
||||||
|
variant="soft"
|
||||||
|
size="1"
|
||||||
|
className="flex items-center gap-1 opacity-80"
|
||||||
|
>
|
||||||
|
<span className="text-xs">⚠️</span>
|
||||||
|
<span className="text-xs font-medium">
|
||||||
|
{dependencyItems.length > 0 && !dateConstraintsMet
|
||||||
|
? `${dependencyItems.length} deps + time locked`
|
||||||
|
: dependencyItems.length > 0
|
||||||
|
? `${dependencyItems.length} deps`
|
||||||
|
: 'Time locked'
|
||||||
|
}
|
||||||
|
</span>
|
||||||
|
</Badge>
|
||||||
|
</Flex>
|
||||||
|
)}
|
||||||
|
</Box>
|
||||||
|
|
||||||
|
<Flex gap="2" align="center" className="sm:opacity-0 sm:group-hover:opacity-100 transition-opacity duration-200">
|
||||||
|
{/* Only show essential status indicators in hover area */}
|
||||||
|
{!item.checked && !canComplete && (
|
||||||
|
<Tooltip content={
|
||||||
|
<Box p="3" className="max-w-xs">
|
||||||
|
<Flex direction="column" gap="2">
|
||||||
|
<Text size="2" weight="medium" color="gray">
|
||||||
|
Cannot complete this item:
|
||||||
|
</Text>
|
||||||
|
{dependencyItems.length > 0 && (
|
||||||
|
<Flex gap="2" align="center">
|
||||||
|
<span className="text-orange-500">🔗</span>
|
||||||
|
<Text size="1" color="orange">
|
||||||
|
Depends on: {dependencyItems.map(dep => dep?.content).join(', ')}
|
||||||
|
</Text>
|
||||||
|
</Flex>
|
||||||
|
)}
|
||||||
|
{!dateConstraintsMet && (
|
||||||
|
<Flex gap="2" align="center">
|
||||||
|
<span className="text-red-500">🕐</span>
|
||||||
|
<Text size="1" color="red">
|
||||||
|
{notBeforeDate && now < notBeforeDate
|
||||||
|
? `Cannot complete before ${notBeforeDate.toLocaleString()}`
|
||||||
|
: notAfterDate && now > notAfterDate
|
||||||
|
? `Cannot complete after ${notAfterDate.toLocaleString()}`
|
||||||
|
: 'Date constraint not met'
|
||||||
|
}
|
||||||
|
</Text>
|
||||||
|
</Flex>
|
||||||
|
)}
|
||||||
|
</Flex>
|
||||||
|
</Box>
|
||||||
|
}>
|
||||||
|
<Badge
|
||||||
|
color="orange"
|
||||||
|
variant="soft"
|
||||||
|
size="1"
|
||||||
|
className="cursor-help hover:opacity-80 transition-opacity"
|
||||||
|
>
|
||||||
|
<span className="text-xs">⚠️</span>
|
||||||
|
</Badge>
|
||||||
|
</Tooltip>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{isLocked && !isLockedByMe && (
|
||||||
|
<Badge color="red" variant="surface" size="1">
|
||||||
|
<LockClosedIcon width="12" height="12" />
|
||||||
|
{item.locked_by}
|
||||||
|
</Badge>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{!isEditing && (
|
||||||
|
<>
|
||||||
|
<Tooltip content="Manage dependencies">
|
||||||
|
<IconButton
|
||||||
|
size="1"
|
||||||
|
variant="ghost"
|
||||||
|
onClick={() => setIsDependencyModalOpen(true)}
|
||||||
|
>
|
||||||
|
<LinkBreak2Icon width="16" height="16" />
|
||||||
|
</IconButton>
|
||||||
|
</Tooltip>
|
||||||
|
<Tooltip content="Manage date constraints">
|
||||||
|
<IconButton
|
||||||
|
size="1"
|
||||||
|
variant="ghost"
|
||||||
|
onClick={() => setIsDateConstraintModalOpen(true)}
|
||||||
|
>
|
||||||
|
<ClockIcon width="16" height="16" />
|
||||||
|
</IconButton>
|
||||||
|
</Tooltip>
|
||||||
|
<Tooltip content="Delete item">
|
||||||
|
<IconButton
|
||||||
|
size="1"
|
||||||
|
variant="ghost"
|
||||||
|
color="red"
|
||||||
|
onClick={handleDelete}
|
||||||
|
disabled={isDeleting}
|
||||||
|
>
|
||||||
|
<TrashIcon width="16" height="16" />
|
||||||
|
</IconButton>
|
||||||
|
</Tooltip>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</Flex>
|
||||||
|
</Flex>
|
||||||
|
|
||||||
|
{children.length > 0 && (
|
||||||
|
<Box ml="8" mt="2" pl="4" className="space-y-2 border-l-2 border-gray-200 dark:border-gray-700">
|
||||||
|
{children.map(child => (
|
||||||
|
<ChecklistItem
|
||||||
|
key={child.id}
|
||||||
|
item={child}
|
||||||
|
onUpdate={onUpdate}
|
||||||
|
onDelete={onDelete}
|
||||||
|
onLock={onLock}
|
||||||
|
depth={depth + 1}
|
||||||
|
allItems={allItems}
|
||||||
|
/>
|
||||||
|
))}
|
||||||
|
</Box>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* Dependency Manager Modal */}
|
||||||
|
<DependencyManager
|
||||||
|
item={item}
|
||||||
|
allItems={allItems}
|
||||||
|
onUpdate={onUpdate}
|
||||||
|
onClose={() => setIsDependencyModalOpen(false)}
|
||||||
|
isOpen={isDependencyModalOpen}
|
||||||
|
/>
|
||||||
|
|
||||||
|
{/* Date Constraint Manager Modal */}
|
||||||
|
{isDateConstraintModalOpen && (
|
||||||
|
<DateConstraintManager
|
||||||
|
item={item}
|
||||||
|
onSave={handleDateConstraintSave}
|
||||||
|
onCancel={() => setIsDateConstraintModalOpen(false)}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
</li>
|
||||||
|
</Box>
|
||||||
|
)
|
||||||
|
}
|
132
frontend/src/components/CreateChecklist.tsx
Normal file
132
frontend/src/components/CreateChecklist.tsx
Normal file
|
@ -0,0 +1,132 @@
|
||||||
|
import { useState, useRef } from 'react'
|
||||||
|
import { useNavigate } from 'react-router-dom'
|
||||||
|
import { importChecklistFromJSON } from '../hooks/useLocalStorage'
|
||||||
|
import { Card, Heading, Text, TextField, Button, Flex, Box, Separator } from '@radix-ui/themes'
|
||||||
|
import { UploadIcon } from '@radix-ui/react-icons'
|
||||||
|
|
||||||
|
interface CreateChecklistProps {
|
||||||
|
className?: string
|
||||||
|
}
|
||||||
|
|
||||||
|
export default function CreateChecklist({ className = '' }: CreateChecklistProps) {
|
||||||
|
const [checklistName, setChecklistName] = useState('')
|
||||||
|
const [isCreating, setIsCreating] = useState(false)
|
||||||
|
const [isImporting, setIsImporting] = useState(false)
|
||||||
|
const fileInputRef = useRef<HTMLInputElement>(null)
|
||||||
|
const navigate = useNavigate()
|
||||||
|
|
||||||
|
const createChecklist = async () => {
|
||||||
|
if (!checklistName.trim()) return
|
||||||
|
|
||||||
|
setIsCreating(true)
|
||||||
|
try {
|
||||||
|
const response = await fetch('/api/checklists', {
|
||||||
|
method: 'POST',
|
||||||
|
headers: {
|
||||||
|
'Content-Type': 'application/json',
|
||||||
|
},
|
||||||
|
body: JSON.stringify({ name: checklistName.trim() }),
|
||||||
|
})
|
||||||
|
|
||||||
|
if (response.ok) {
|
||||||
|
const data = await response.json()
|
||||||
|
|
||||||
|
// Navigate to the new checklist
|
||||||
|
navigate(`/${data.uuid}`)
|
||||||
|
} else {
|
||||||
|
alert('Failed to create checklist')
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error creating checklist:', error)
|
||||||
|
alert('Failed to create checklist')
|
||||||
|
} finally {
|
||||||
|
setIsCreating(false)
|
||||||
|
setChecklistName('')
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const handleKeyDown = (e: React.KeyboardEvent) => {
|
||||||
|
if (e.key === 'Enter') {
|
||||||
|
createChecklist()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const handleImportChecklist = async (event: React.ChangeEvent<HTMLInputElement>) => {
|
||||||
|
const file = event.target.files?.[0]
|
||||||
|
if (!file) return
|
||||||
|
|
||||||
|
setIsImporting(true)
|
||||||
|
try {
|
||||||
|
const newUuid = await importChecklistFromJSON(file)
|
||||||
|
navigate(`/${newUuid}`)
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error importing checklist:', error)
|
||||||
|
alert('Failed to import checklist. Please check the file format.')
|
||||||
|
} finally {
|
||||||
|
setIsImporting(false)
|
||||||
|
// Reset the file input
|
||||||
|
if (fileInputRef.current) {
|
||||||
|
fileInputRef.current.value = ''
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const triggerFileInput = () => {
|
||||||
|
fileInputRef.current?.click()
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Card size="3" className={className}>
|
||||||
|
<Heading size="5" mb="5">Create New Checklist</Heading>
|
||||||
|
|
||||||
|
<Flex direction={{ initial: 'column', sm: 'row' }} gap="3" mb="5">
|
||||||
|
<Box style={{ flex: 1 }}>
|
||||||
|
<TextField.Root
|
||||||
|
size="3"
|
||||||
|
placeholder="Enter checklist name..."
|
||||||
|
value={checklistName}
|
||||||
|
onChange={(e) => setChecklistName(e.target.value)}
|
||||||
|
onKeyDown={handleKeyDown}
|
||||||
|
disabled={isCreating || isImporting}
|
||||||
|
/>
|
||||||
|
</Box>
|
||||||
|
<Button
|
||||||
|
onClick={createChecklist}
|
||||||
|
disabled={isCreating || isImporting || !checklistName.trim()}
|
||||||
|
size="3"
|
||||||
|
>
|
||||||
|
{isCreating ? 'Creating...' : 'Create'}
|
||||||
|
</Button>
|
||||||
|
</Flex>
|
||||||
|
|
||||||
|
<Separator size="4" />
|
||||||
|
|
||||||
|
<Box pt="5">
|
||||||
|
<Heading size="4" mb="3">Import Checklist</Heading>
|
||||||
|
<Flex direction={{ initial: 'column', sm: 'row' }} gap="3" align={{ sm: 'end' }}>
|
||||||
|
<Box style={{ flex: 1 }}>
|
||||||
|
<Text size="2" color="gray">
|
||||||
|
Import a previously exported checklist JSON file
|
||||||
|
</Text>
|
||||||
|
<input
|
||||||
|
ref={fileInputRef}
|
||||||
|
type="file"
|
||||||
|
accept=".json"
|
||||||
|
onChange={handleImportChecklist}
|
||||||
|
className="hidden"
|
||||||
|
/>
|
||||||
|
</Box>
|
||||||
|
<Button
|
||||||
|
onClick={triggerFileInput}
|
||||||
|
disabled={isCreating || isImporting}
|
||||||
|
size="3"
|
||||||
|
color="green"
|
||||||
|
>
|
||||||
|
<UploadIcon />
|
||||||
|
{isImporting ? 'Importing...' : 'Import JSON'}
|
||||||
|
</Button>
|
||||||
|
</Flex>
|
||||||
|
</Box>
|
||||||
|
</Card>
|
||||||
|
)
|
||||||
|
}
|
232
frontend/src/components/DateConstraintManager.tsx
Normal file
232
frontend/src/components/DateConstraintManager.tsx
Normal file
|
@ -0,0 +1,232 @@
|
||||||
|
import React, { useState, useEffect } from 'react'
|
||||||
|
import type { ChecklistItem } from '../types'
|
||||||
|
import { Dialog, Flex, Text, Button, Heading, Card, Box, IconButton } from '@radix-ui/themes'
|
||||||
|
import { Cross2Icon, CalendarIcon, ClockIcon } from '@radix-ui/react-icons'
|
||||||
|
|
||||||
|
interface DateConstraintManagerProps {
|
||||||
|
item: ChecklistItem
|
||||||
|
onSave: (notBefore?: string, notAfter?: string) => void
|
||||||
|
onCancel: () => void
|
||||||
|
}
|
||||||
|
|
||||||
|
export const DateConstraintManager: React.FC<DateConstraintManagerProps> = ({
|
||||||
|
item,
|
||||||
|
onSave,
|
||||||
|
onCancel
|
||||||
|
}) => {
|
||||||
|
// Parse existing dates to local datetime format for inputs
|
||||||
|
const formatDateTimeLocal = (date: Date | null): string => {
|
||||||
|
if (!date) return ''
|
||||||
|
const year = date.getFullYear()
|
||||||
|
const month = String(date.getMonth() + 1).padStart(2, '0')
|
||||||
|
const day = String(date.getDate()).padStart(2, '0')
|
||||||
|
const hours = String(date.getHours()).padStart(2, '0')
|
||||||
|
const minutes = String(date.getMinutes()).padStart(2, '0')
|
||||||
|
return `${year}-${month}-${day}T${hours}:${minutes}`
|
||||||
|
}
|
||||||
|
|
||||||
|
const [notBeforeValue, setNotBeforeValue] = useState<string>(
|
||||||
|
item.not_before ? formatDateTimeLocal(new Date(item.not_before)) : ''
|
||||||
|
)
|
||||||
|
const [notAfterValue, setNotAfterValue] = useState<string>(
|
||||||
|
item.not_after ? formatDateTimeLocal(new Date(item.not_after)) : ''
|
||||||
|
)
|
||||||
|
|
||||||
|
// Get current datetime in local format for min attribute
|
||||||
|
const now = new Date()
|
||||||
|
const minDateTime = formatDateTimeLocal(now)
|
||||||
|
|
||||||
|
const handleSave = () => {
|
||||||
|
const notBeforeDate = notBeforeValue ? new Date(notBeforeValue).toISOString() : undefined
|
||||||
|
const notAfterDate = notAfterValue ? new Date(notAfterValue).toISOString() : undefined
|
||||||
|
onSave(notBeforeDate, notAfterDate)
|
||||||
|
}
|
||||||
|
|
||||||
|
const handleClear = () => {
|
||||||
|
setNotBeforeValue('')
|
||||||
|
setNotAfterValue('')
|
||||||
|
}
|
||||||
|
|
||||||
|
// Update min value for notAfter when notBefore changes
|
||||||
|
useEffect(() => {
|
||||||
|
if (notBeforeValue && notAfterValue) {
|
||||||
|
const notBeforeDate = new Date(notBeforeValue)
|
||||||
|
const notAfterDate = new Date(notAfterValue)
|
||||||
|
if (notBeforeDate > notAfterDate) {
|
||||||
|
setNotAfterValue(notBeforeValue)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}, [notBeforeValue, notAfterValue])
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Dialog.Root open={true} onOpenChange={onCancel}>
|
||||||
|
<Dialog.Content style={{ maxWidth: 450 }}>
|
||||||
|
<Dialog.Title>Manage Date Constraints</Dialog.Title>
|
||||||
|
<Dialog.Description size="2" mb="4">
|
||||||
|
Set when this item can be completed. Leave empty to remove constraints.
|
||||||
|
</Dialog.Description>
|
||||||
|
|
||||||
|
<Flex direction="column" gap="4">
|
||||||
|
<Box>
|
||||||
|
<Flex align="center" gap="2" mb="2">
|
||||||
|
<CalendarIcon />
|
||||||
|
<Text size="2" weight="medium">
|
||||||
|
Not Before (Earliest completion time)
|
||||||
|
</Text>
|
||||||
|
</Flex>
|
||||||
|
<Box position="relative">
|
||||||
|
<input
|
||||||
|
type="datetime-local"
|
||||||
|
value={notBeforeValue}
|
||||||
|
onChange={(e) => setNotBeforeValue(e.target.value)}
|
||||||
|
min={minDateTime}
|
||||||
|
className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent bg-white dark:bg-gray-700 text-gray-900 dark:text-white"
|
||||||
|
style={{
|
||||||
|
colorScheme: 'dark',
|
||||||
|
WebkitAppearance: 'none',
|
||||||
|
MozAppearance: 'none'
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
{notBeforeValue && (
|
||||||
|
<IconButton
|
||||||
|
size="1"
|
||||||
|
variant="ghost"
|
||||||
|
color="gray"
|
||||||
|
onClick={() => setNotBeforeValue('')}
|
||||||
|
style={{
|
||||||
|
position: 'absolute',
|
||||||
|
right: '8px',
|
||||||
|
top: '50%',
|
||||||
|
transform: 'translateY(-50%)'
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<Cross2Icon />
|
||||||
|
</IconButton>
|
||||||
|
)}
|
||||||
|
</Box>
|
||||||
|
</Box>
|
||||||
|
|
||||||
|
<Box>
|
||||||
|
<Flex align="center" gap="2" mb="2">
|
||||||
|
<ClockIcon />
|
||||||
|
<Text size="2" weight="medium">
|
||||||
|
Not After (Latest completion time)
|
||||||
|
</Text>
|
||||||
|
</Flex>
|
||||||
|
<Box position="relative">
|
||||||
|
<input
|
||||||
|
type="datetime-local"
|
||||||
|
value={notAfterValue}
|
||||||
|
onChange={(e) => setNotAfterValue(e.target.value)}
|
||||||
|
min={notBeforeValue || minDateTime}
|
||||||
|
className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent bg-white dark:bg-gray-700 text-gray-900 dark:text-white"
|
||||||
|
style={{
|
||||||
|
colorScheme: 'dark',
|
||||||
|
WebkitAppearance: 'none',
|
||||||
|
MozAppearance: 'none'
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
{notAfterValue && (
|
||||||
|
<IconButton
|
||||||
|
size="1"
|
||||||
|
variant="ghost"
|
||||||
|
color="gray"
|
||||||
|
onClick={() => setNotAfterValue('')}
|
||||||
|
style={{
|
||||||
|
position: 'absolute',
|
||||||
|
right: '8px',
|
||||||
|
top: '50%',
|
||||||
|
transform: 'translateY(-50%)'
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<Cross2Icon />
|
||||||
|
</IconButton>
|
||||||
|
)}
|
||||||
|
</Box>
|
||||||
|
</Box>
|
||||||
|
|
||||||
|
{/* Quick select buttons for common time periods */}
|
||||||
|
<Box>
|
||||||
|
<Text size="2" weight="medium" mb="2">
|
||||||
|
Quick select:
|
||||||
|
</Text>
|
||||||
|
<Flex gap="2" wrap="wrap">
|
||||||
|
<Button
|
||||||
|
size="1"
|
||||||
|
variant="soft"
|
||||||
|
onClick={() => {
|
||||||
|
const tomorrow = new Date()
|
||||||
|
tomorrow.setDate(tomorrow.getDate() + 1)
|
||||||
|
tomorrow.setHours(9, 0, 0, 0)
|
||||||
|
setNotBeforeValue(formatDateTimeLocal(tomorrow))
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
Tomorrow 9AM
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
size="1"
|
||||||
|
variant="soft"
|
||||||
|
onClick={() => {
|
||||||
|
const nextWeek = new Date()
|
||||||
|
nextWeek.setDate(nextWeek.getDate() + 7)
|
||||||
|
nextWeek.setHours(9, 0, 0, 0)
|
||||||
|
setNotBeforeValue(formatDateTimeLocal(nextWeek))
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
Next week
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
size="1"
|
||||||
|
variant="soft"
|
||||||
|
onClick={() => {
|
||||||
|
const endOfWeek = new Date()
|
||||||
|
const daysUntilFriday = (5 - endOfWeek.getDay() + 7) % 7 || 7
|
||||||
|
endOfWeek.setDate(endOfWeek.getDate() + daysUntilFriday)
|
||||||
|
endOfWeek.setHours(17, 0, 0, 0)
|
||||||
|
setNotAfterValue(formatDateTimeLocal(endOfWeek))
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
End of week
|
||||||
|
</Button>
|
||||||
|
</Flex>
|
||||||
|
</Box>
|
||||||
|
</Flex>
|
||||||
|
|
||||||
|
{(notBeforeValue || notAfterValue) && (
|
||||||
|
<Card size="2" mt="4">
|
||||||
|
<Heading size="2" mb="2">Preview:</Heading>
|
||||||
|
<Flex direction="column" gap="1">
|
||||||
|
{notBeforeValue && (
|
||||||
|
<Text size="2" color="gray">✅ Can complete after: {new Date(notBeforeValue).toLocaleString()}</Text>
|
||||||
|
)}
|
||||||
|
{notAfterValue && (
|
||||||
|
<Text size="2" color="gray">✅ Can complete before: {new Date(notAfterValue).toLocaleString()}</Text>
|
||||||
|
)}
|
||||||
|
{notBeforeValue && notAfterValue && (
|
||||||
|
<Text size="2" color="blue" weight="medium">
|
||||||
|
Time window: {Math.round((new Date(notAfterValue).getTime() - new Date(notBeforeValue).getTime()) / (1000 * 60 * 60 * 24))} days
|
||||||
|
</Text>
|
||||||
|
)}
|
||||||
|
</Flex>
|
||||||
|
</Card>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<Flex gap="3" mt="4" justify="between">
|
||||||
|
<Button variant="ghost" onClick={handleClear}>
|
||||||
|
Clear All
|
||||||
|
</Button>
|
||||||
|
<Flex gap="2">
|
||||||
|
<Dialog.Close>
|
||||||
|
<Button variant="soft" color="gray">
|
||||||
|
Cancel
|
||||||
|
</Button>
|
||||||
|
</Dialog.Close>
|
||||||
|
<Button onClick={handleSave}>
|
||||||
|
Save
|
||||||
|
</Button>
|
||||||
|
</Flex>
|
||||||
|
</Flex>
|
||||||
|
</Dialog.Content>
|
||||||
|
</Dialog.Root>
|
||||||
|
)
|
||||||
|
}
|
118
frontend/src/components/DependencyManager.tsx
Normal file
118
frontend/src/components/DependencyManager.tsx
Normal file
|
@ -0,0 +1,118 @@
|
||||||
|
import { useState, useEffect } from 'react'
|
||||||
|
import type { ChecklistItem } from '../types'
|
||||||
|
import { Dialog, Flex, Text, Button, Checkbox, ScrollArea, Badge, Separator } from '@radix-ui/themes'
|
||||||
|
|
||||||
|
interface DependencyManagerProps {
|
||||||
|
item: ChecklistItem
|
||||||
|
allItems: ChecklistItem[]
|
||||||
|
onUpdate: (id: number, updates: Partial<ChecklistItem>) => Promise<void>
|
||||||
|
onClose: () => void
|
||||||
|
isOpen: boolean
|
||||||
|
}
|
||||||
|
|
||||||
|
export default function DependencyManager({
|
||||||
|
item,
|
||||||
|
allItems,
|
||||||
|
onUpdate,
|
||||||
|
onClose,
|
||||||
|
isOpen
|
||||||
|
}: DependencyManagerProps) {
|
||||||
|
const [selectedDependencies, setSelectedDependencies] = useState<number[]>([])
|
||||||
|
const [isUpdating, setIsUpdating] = useState(false)
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (isOpen) {
|
||||||
|
setSelectedDependencies(item.dependencies || [])
|
||||||
|
}
|
||||||
|
}, [isOpen, item.dependencies])
|
||||||
|
|
||||||
|
const handleSave = async () => {
|
||||||
|
setIsUpdating(true)
|
||||||
|
try {
|
||||||
|
await onUpdate(item.id, { dependencies: selectedDependencies })
|
||||||
|
onClose()
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Failed to update dependencies:', error)
|
||||||
|
} finally {
|
||||||
|
setIsUpdating(false)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const toggleDependency = (depId: number) => {
|
||||||
|
setSelectedDependencies(prev =>
|
||||||
|
prev.includes(depId)
|
||||||
|
? prev.filter(id => id !== depId)
|
||||||
|
: [...prev, depId]
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
const availableItems = allItems.filter(otherItem =>
|
||||||
|
otherItem.id !== item.id &&
|
||||||
|
!otherItem.dependencies?.includes(item.id) // Prevent circular dependencies
|
||||||
|
)
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Dialog.Root open={isOpen} onOpenChange={onClose}>
|
||||||
|
<Dialog.Content style={{ maxWidth: 450 }}>
|
||||||
|
<Dialog.Title>Manage Dependencies</Dialog.Title>
|
||||||
|
<Dialog.Description size="2" mb="4">
|
||||||
|
Select items that must be completed before "{item.content}" can be completed:
|
||||||
|
</Dialog.Description>
|
||||||
|
|
||||||
|
<ScrollArea type="auto" scrollbars="vertical" style={{ height: 300 }}>
|
||||||
|
{availableItems.length === 0 ? (
|
||||||
|
<Flex align="center" justify="center" p="4">
|
||||||
|
<Text color="gray">No available items to depend on</Text>
|
||||||
|
</Flex>
|
||||||
|
) : (
|
||||||
|
<Flex direction="column" gap="1">
|
||||||
|
{availableItems.map((otherItem, index) => (
|
||||||
|
<div key={otherItem.id}>
|
||||||
|
<Flex
|
||||||
|
align="center"
|
||||||
|
gap="3"
|
||||||
|
p="3"
|
||||||
|
className="hover:bg-gray-50 dark:hover:bg-gray-800 cursor-pointer rounded-md"
|
||||||
|
onClick={() => toggleDependency(otherItem.id)}
|
||||||
|
>
|
||||||
|
<Checkbox
|
||||||
|
checked={selectedDependencies.includes(otherItem.id)}
|
||||||
|
onCheckedChange={() => toggleDependency(otherItem.id)}
|
||||||
|
/>
|
||||||
|
<Text
|
||||||
|
size="2"
|
||||||
|
style={{
|
||||||
|
textDecoration: otherItem.checked ? 'line-through' : 'none',
|
||||||
|
opacity: otherItem.checked ? 0.6 : 1,
|
||||||
|
flex: 1
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{otherItem.content}
|
||||||
|
</Text>
|
||||||
|
{otherItem.checked && (
|
||||||
|
<Badge color="green" size="1">
|
||||||
|
✓ Done
|
||||||
|
</Badge>
|
||||||
|
)}
|
||||||
|
</Flex>
|
||||||
|
{index < availableItems.length - 1 && <Separator size="4" />}
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</Flex>
|
||||||
|
)}
|
||||||
|
</ScrollArea>
|
||||||
|
|
||||||
|
<Flex gap="3" mt="4" justify="end">
|
||||||
|
<Dialog.Close>
|
||||||
|
<Button variant="soft" color="gray">
|
||||||
|
Cancel
|
||||||
|
</Button>
|
||||||
|
</Dialog.Close>
|
||||||
|
<Button onClick={handleSave} disabled={isUpdating}>
|
||||||
|
{isUpdating ? 'Saving...' : 'Save'}
|
||||||
|
</Button>
|
||||||
|
</Flex>
|
||||||
|
</Dialog.Content>
|
||||||
|
</Dialog.Root>
|
||||||
|
)
|
||||||
|
}
|
109
frontend/src/components/EditableTitle.tsx
Normal file
109
frontend/src/components/EditableTitle.tsx
Normal file
|
@ -0,0 +1,109 @@
|
||||||
|
import React, { useState, useRef, useEffect } from 'react'
|
||||||
|
import { TextField, Button, Flex, Text } from '@radix-ui/themes'
|
||||||
|
import { Pencil1Icon } from '@radix-ui/react-icons'
|
||||||
|
|
||||||
|
interface EditableTitleProps {
|
||||||
|
title: string
|
||||||
|
onSave: (newTitle: string) => Promise<void>
|
||||||
|
className?: string
|
||||||
|
}
|
||||||
|
|
||||||
|
export const EditableTitle: React.FC<EditableTitleProps> = ({
|
||||||
|
title,
|
||||||
|
onSave,
|
||||||
|
className = ''
|
||||||
|
}) => {
|
||||||
|
const [isEditing, setIsEditing] = useState(false)
|
||||||
|
const [editValue, setEditValue] = useState(title)
|
||||||
|
const [isSaving, setIsSaving] = useState(false)
|
||||||
|
const inputRef = useRef<HTMLInputElement>(null)
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
setEditValue(title)
|
||||||
|
}, [title])
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (isEditing && inputRef.current) {
|
||||||
|
inputRef.current.focus()
|
||||||
|
inputRef.current.select()
|
||||||
|
}
|
||||||
|
}, [isEditing])
|
||||||
|
|
||||||
|
const handleStartEdit = () => {
|
||||||
|
setIsEditing(true)
|
||||||
|
setEditValue(title)
|
||||||
|
}
|
||||||
|
|
||||||
|
const handleSave = async () => {
|
||||||
|
const trimmedValue = editValue.trim()
|
||||||
|
if (trimmedValue === title || trimmedValue === '') {
|
||||||
|
setIsEditing(false)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
setIsSaving(true)
|
||||||
|
try {
|
||||||
|
await onSave(trimmedValue)
|
||||||
|
setIsEditing(false)
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Failed to save title:', error)
|
||||||
|
// Reset to original value on error
|
||||||
|
setEditValue(title)
|
||||||
|
} finally {
|
||||||
|
setIsSaving(false)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const handleCancel = () => {
|
||||||
|
setIsEditing(false)
|
||||||
|
setEditValue(title)
|
||||||
|
}
|
||||||
|
|
||||||
|
const handleKeyDown = (e: React.KeyboardEvent) => {
|
||||||
|
if (e.key === 'Enter') {
|
||||||
|
e.preventDefault()
|
||||||
|
handleSave()
|
||||||
|
} else if (e.key === 'Escape') {
|
||||||
|
e.preventDefault()
|
||||||
|
handleCancel()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (isEditing) {
|
||||||
|
return (
|
||||||
|
<Flex align="center" gap="2" className={className}>
|
||||||
|
<TextField.Root
|
||||||
|
ref={inputRef}
|
||||||
|
size="2"
|
||||||
|
value={editValue}
|
||||||
|
onChange={(e) => setEditValue(e.target.value)}
|
||||||
|
onKeyDown={handleKeyDown}
|
||||||
|
onBlur={handleSave}
|
||||||
|
disabled={isSaving}
|
||||||
|
style={{ fontWeight: 'bold' }}
|
||||||
|
maxLength={100}
|
||||||
|
/>
|
||||||
|
{isSaving && (
|
||||||
|
<Text size="2" color="gray">
|
||||||
|
Saving...
|
||||||
|
</Text>
|
||||||
|
)}
|
||||||
|
</Flex>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Button
|
||||||
|
onClick={handleStartEdit}
|
||||||
|
variant="ghost"
|
||||||
|
size="2"
|
||||||
|
className={`group ${className}`}
|
||||||
|
title="Click to edit title"
|
||||||
|
>
|
||||||
|
<Text weight="bold" size="3">
|
||||||
|
{title}
|
||||||
|
</Text>
|
||||||
|
<Pencil1Icon className="opacity-0 group-hover:opacity-100 transition-opacity duration-200" />
|
||||||
|
</Button>
|
||||||
|
)
|
||||||
|
}
|
109
frontend/src/components/SavedChecklists.tsx
Normal file
109
frontend/src/components/SavedChecklists.tsx
Normal file
|
@ -0,0 +1,109 @@
|
||||||
|
import { Link } from 'react-router-dom'
|
||||||
|
import { loadSavedChecklists, exportChecklistToJSON } from '../hooks/useLocalStorage'
|
||||||
|
import { useState } from 'react'
|
||||||
|
import { Card, Heading, Text, Button, Flex, Box } from '@radix-ui/themes'
|
||||||
|
import { Share1Icon, DownloadIcon, TrashIcon } from '@radix-ui/react-icons'
|
||||||
|
|
||||||
|
interface SavedChecklistsProps {
|
||||||
|
className?: string
|
||||||
|
}
|
||||||
|
|
||||||
|
export default function SavedChecklists({ className = '' }: SavedChecklistsProps) {
|
||||||
|
const [savedChecklists, setSavedChecklists] = useState<{ uuid: string; name: string; lastOpened?: string }[]>(loadSavedChecklists())
|
||||||
|
const [exportingChecklist, setExportingChecklist] = useState<string | null>(null)
|
||||||
|
|
||||||
|
const handleForgetCheckList = (uuid: string): void => {
|
||||||
|
const updatedChecklists = savedChecklists.filter((checklist: { uuid: string }) => checklist.uuid !== uuid)
|
||||||
|
localStorage.setItem('gocheck-saved-checklists', JSON.stringify(updatedChecklists))
|
||||||
|
setSavedChecklists(updatedChecklists)
|
||||||
|
}
|
||||||
|
|
||||||
|
const handleExportChecklist = async (uuid: string, name: string): Promise<void> => {
|
||||||
|
setExportingChecklist(uuid)
|
||||||
|
try {
|
||||||
|
await exportChecklistToJSON(uuid, name)
|
||||||
|
} catch {
|
||||||
|
alert('Failed to export checklist')
|
||||||
|
} finally {
|
||||||
|
setExportingChecklist(null)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
if (savedChecklists.length === 0) {
|
||||||
|
return (
|
||||||
|
<Card size="3" className={className}>
|
||||||
|
<Flex direction="column" align="center" justify="center" py="9">
|
||||||
|
<Text size="9" color="gray" mb="4">📋</Text>
|
||||||
|
<Heading size="5" mb="2">No checklists yet</Heading>
|
||||||
|
<Text color="gray">Create your first checklist above to get started!</Text>
|
||||||
|
</Flex>
|
||||||
|
</Card>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Card size="3" className={className}>
|
||||||
|
<Heading size="5" mb="5">Your Checklists</Heading>
|
||||||
|
<Flex direction="column" gap="3">
|
||||||
|
{savedChecklists.map((checklist) => (
|
||||||
|
<Card key={checklist.uuid} size="2">
|
||||||
|
<Flex direction={{ initial: 'column', sm: 'row' }} justify="between" gap="3">
|
||||||
|
<Box>
|
||||||
|
<Heading size="3" mb="1">{checklist.name}</Heading>
|
||||||
|
<Text size="2" color="gray">
|
||||||
|
Last opened: {checklist.lastOpened ? new Date(checklist.lastOpened).toLocaleString() : 'Never'}
|
||||||
|
</Text>
|
||||||
|
</Box>
|
||||||
|
<Flex gap="2" wrap="wrap">
|
||||||
|
<Link to={`/${checklist.uuid}`}>
|
||||||
|
<Button size="2">
|
||||||
|
Open
|
||||||
|
</Button>
|
||||||
|
</Link>
|
||||||
|
<Button
|
||||||
|
size="2"
|
||||||
|
color="green"
|
||||||
|
onClick={() => {
|
||||||
|
const url = `${window.location.origin}/${checklist.uuid}`
|
||||||
|
navigator.clipboard.writeText(url).then(() => {
|
||||||
|
alert('Checklist link copied to clipboard! ' + url)
|
||||||
|
}).catch(() => {
|
||||||
|
const textArea = document.createElement('textarea')
|
||||||
|
textArea.value = url
|
||||||
|
document.body.appendChild(textArea)
|
||||||
|
textArea.select()
|
||||||
|
document.execCommand('copy')
|
||||||
|
document.body.removeChild(textArea)
|
||||||
|
alert('Checklist link copied to clipboard!')
|
||||||
|
})
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<Share1Icon />
|
||||||
|
Share
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
size="2"
|
||||||
|
color="violet"
|
||||||
|
onClick={() => handleExportChecklist(checklist.uuid, checklist.name)}
|
||||||
|
disabled={exportingChecklist === checklist.uuid}
|
||||||
|
>
|
||||||
|
<DownloadIcon />
|
||||||
|
{exportingChecklist === checklist.uuid ? 'Exporting...' : 'Export'}
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
size="2"
|
||||||
|
color="red"
|
||||||
|
onClick={() => handleForgetCheckList(checklist.uuid)}
|
||||||
|
>
|
||||||
|
<TrashIcon />
|
||||||
|
Forget
|
||||||
|
</Button>
|
||||||
|
</Flex>
|
||||||
|
</Flex>
|
||||||
|
</Card>
|
||||||
|
))}
|
||||||
|
</Flex>
|
||||||
|
</Card>
|
||||||
|
)
|
||||||
|
}
|
204
frontend/src/hooks/useLocalStorage.ts
Normal file
204
frontend/src/hooks/useLocalStorage.ts
Normal file
|
@ -0,0 +1,204 @@
|
||||||
|
import type { SavedChecklist, ChecklistItem } from '../types'
|
||||||
|
|
||||||
|
const STORAGE_KEY = 'gocheck-saved-checklists'
|
||||||
|
|
||||||
|
export function saveChecklist(checklist: SavedChecklist) {
|
||||||
|
try {
|
||||||
|
const existingChecklists = loadSavedChecklists()
|
||||||
|
const existingIndex = existingChecklists.findIndex(c => c.uuid === checklist.uuid);
|
||||||
|
|
||||||
|
if (existingIndex > -1) {
|
||||||
|
// Update lastOpened timestamp if checklist already exists
|
||||||
|
existingChecklists[existingIndex].lastOpened = new Date().toISOString();
|
||||||
|
existingChecklists[existingIndex].name = checklist.name;
|
||||||
|
} else {
|
||||||
|
// Add new checklist with lastOpened timestamp
|
||||||
|
existingChecklists.push({ ...checklist, lastOpened: new Date().toISOString() });
|
||||||
|
}
|
||||||
|
|
||||||
|
// Sort by lastOpened date in descending order
|
||||||
|
existingChecklists.sort((a, b) => {
|
||||||
|
if (!a.lastOpened) return 1;
|
||||||
|
if (!b.lastOpened) return -1;
|
||||||
|
return new Date(b.lastOpened).getTime() - new Date(a.lastOpened).getTime();
|
||||||
|
});
|
||||||
|
|
||||||
|
localStorage.setItem(STORAGE_KEY, JSON.stringify(existingChecklists));
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error saving checklist:', error);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export const loadSavedChecklists = (): SavedChecklist[] => {
|
||||||
|
const saved = localStorage.getItem(STORAGE_KEY)
|
||||||
|
if (saved) {
|
||||||
|
try {
|
||||||
|
const parsed = JSON.parse(saved);
|
||||||
|
if (Array.isArray(parsed)) {
|
||||||
|
return parsed as SavedChecklist[];
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error parsing saved checklists:', error);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return []
|
||||||
|
}
|
||||||
|
|
||||||
|
export const exportChecklistToJSON = async (uuid: string, name: string): Promise<void> => {
|
||||||
|
try {
|
||||||
|
const response = await fetch(`/api/checklists/${uuid}/items`)
|
||||||
|
if (!response.ok) {
|
||||||
|
throw new Error('Failed to fetch checklist data')
|
||||||
|
}
|
||||||
|
|
||||||
|
const data = await response.json()
|
||||||
|
if (!data.success || !data.items) {
|
||||||
|
throw new Error('Invalid response format')
|
||||||
|
}
|
||||||
|
|
||||||
|
const exportData = {
|
||||||
|
name: name,
|
||||||
|
uuid: uuid,
|
||||||
|
exportedAt: new Date().toISOString(),
|
||||||
|
items: data.items as ChecklistItem[]
|
||||||
|
}
|
||||||
|
|
||||||
|
const jsonString = JSON.stringify(exportData, null, 2)
|
||||||
|
const blob = new Blob([jsonString], { type: 'application/json' })
|
||||||
|
const url = URL.createObjectURL(blob)
|
||||||
|
|
||||||
|
const link = document.createElement('a')
|
||||||
|
link.href = url
|
||||||
|
link.download = `${name.replace(/[^a-z0-9]/gi, '_').toLowerCase()}_${uuid}.json`
|
||||||
|
document.body.appendChild(link)
|
||||||
|
link.click()
|
||||||
|
document.body.removeChild(link)
|
||||||
|
URL.revokeObjectURL(url)
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error exporting checklist:', error)
|
||||||
|
throw error
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
interface ImportData {
|
||||||
|
name: string
|
||||||
|
uuid?: string
|
||||||
|
exportedAt?: string
|
||||||
|
items: ChecklistItem[]
|
||||||
|
}
|
||||||
|
|
||||||
|
export const importChecklistFromJSON = async (file: File): Promise<string> => {
|
||||||
|
try {
|
||||||
|
// Read the file
|
||||||
|
const text = await file.text()
|
||||||
|
const importData: ImportData = JSON.parse(text)
|
||||||
|
|
||||||
|
// Validate the import data
|
||||||
|
if (!importData.name || !importData.items || !Array.isArray(importData.items)) {
|
||||||
|
throw new Error('Invalid import file format')
|
||||||
|
}
|
||||||
|
|
||||||
|
// Create a new checklist
|
||||||
|
const createResponse = await fetch('/api/checklists', {
|
||||||
|
method: 'POST',
|
||||||
|
headers: {
|
||||||
|
'Content-Type': 'application/json',
|
||||||
|
},
|
||||||
|
body: JSON.stringify({ name: importData.name }),
|
||||||
|
})
|
||||||
|
|
||||||
|
if (!createResponse.ok) {
|
||||||
|
throw new Error('Failed to create checklist')
|
||||||
|
}
|
||||||
|
|
||||||
|
const createData = await createResponse.json()
|
||||||
|
if (!createData.success || !createData.uuid) {
|
||||||
|
throw new Error('Invalid response from checklist creation')
|
||||||
|
}
|
||||||
|
|
||||||
|
const newUuid = createData.uuid
|
||||||
|
|
||||||
|
// Create a mapping from old item IDs to new item IDs
|
||||||
|
const idMapping = new Map<number, number>()
|
||||||
|
|
||||||
|
// First pass: Add all items and build the ID mapping
|
||||||
|
for (const item of importData.items) {
|
||||||
|
const addItemResponse = await fetch(`/api/checklists/${newUuid}/items`, {
|
||||||
|
method: 'POST',
|
||||||
|
headers: {
|
||||||
|
'Content-Type': 'application/json',
|
||||||
|
},
|
||||||
|
body: JSON.stringify({
|
||||||
|
content: item.content,
|
||||||
|
parent_id: null, // We'll handle parent relationships in the second pass
|
||||||
|
not_before: item.not_before,
|
||||||
|
not_after: item.not_after,
|
||||||
|
}),
|
||||||
|
})
|
||||||
|
|
||||||
|
if (!addItemResponse.ok) {
|
||||||
|
throw new Error(`Failed to add item: ${item.content}`)
|
||||||
|
}
|
||||||
|
|
||||||
|
const addItemData = await addItemResponse.json()
|
||||||
|
if (!addItemData.success || !addItemData.item) {
|
||||||
|
throw new Error(`Invalid response when adding item: ${item.content}`)
|
||||||
|
}
|
||||||
|
|
||||||
|
const newItemId = addItemData.item.id
|
||||||
|
idMapping.set(item.id, newItemId)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Second pass: Update parent relationships and dependencies
|
||||||
|
for (const item of importData.items) {
|
||||||
|
const newItemId = idMapping.get(item.id)
|
||||||
|
if (!newItemId) continue
|
||||||
|
|
||||||
|
const updates: Partial<ChecklistItem> = {}
|
||||||
|
|
||||||
|
// Handle parent relationships
|
||||||
|
if (item.parent_id !== null) {
|
||||||
|
const newParentId = idMapping.get(item.parent_id)
|
||||||
|
if (newParentId) {
|
||||||
|
updates.parent_id = newParentId
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Handle dependencies
|
||||||
|
if (item.dependencies && item.dependencies.length > 0) {
|
||||||
|
const newDependencies = item.dependencies
|
||||||
|
.map(oldDepId => idMapping.get(oldDepId))
|
||||||
|
.filter(newDepId => newDepId !== undefined) as number[]
|
||||||
|
|
||||||
|
if (newDependencies.length > 0) {
|
||||||
|
updates.dependencies = newDependencies
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Update item if it was checked in the original
|
||||||
|
if (item.checked) {
|
||||||
|
updates.checked = true
|
||||||
|
}
|
||||||
|
|
||||||
|
// Apply updates if there are any
|
||||||
|
if (Object.keys(updates).length > 0) {
|
||||||
|
const updateResponse = await fetch(`/api/checklists/${newUuid}/items/${newItemId}`, {
|
||||||
|
method: 'PATCH',
|
||||||
|
headers: {
|
||||||
|
'Content-Type': 'application/json',
|
||||||
|
},
|
||||||
|
body: JSON.stringify(updates),
|
||||||
|
})
|
||||||
|
|
||||||
|
if (!updateResponse.ok) {
|
||||||
|
console.warn(`Failed to update item: ${item.content}`)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return newUuid
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error importing checklist:', error)
|
||||||
|
throw error
|
||||||
|
}
|
||||||
|
}
|
126
frontend/src/hooks/useSSE.ts
Normal file
126
frontend/src/hooks/useSSE.ts
Normal file
|
@ -0,0 +1,126 @@
|
||||||
|
import { useEffect, useRef, useState } from 'react'
|
||||||
|
import type { SSEEvent, ChecklistItem } from '../types'
|
||||||
|
import { saveChecklist } from '../hooks/useLocalStorage'
|
||||||
|
|
||||||
|
export function useSSE(uuid: string) {
|
||||||
|
const [items, setItems] = useState<ChecklistItem[]>([])
|
||||||
|
const [checkListName, setCheckListName] = useState('')
|
||||||
|
const [isConnected, setIsConnected] = useState(false)
|
||||||
|
const [error, setError] = useState<string | null>(null)
|
||||||
|
const eventSourceRef = useRef<EventSource | null>(null)
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!uuid) return
|
||||||
|
|
||||||
|
const connectSSE = () => {
|
||||||
|
try {
|
||||||
|
const eventSource = new EventSource(`/api/checklists/${uuid}/sse`)
|
||||||
|
eventSourceRef.current = eventSource
|
||||||
|
|
||||||
|
eventSource.onopen = () => {
|
||||||
|
setIsConnected(true)
|
||||||
|
setError(null)
|
||||||
|
}
|
||||||
|
|
||||||
|
eventSource.onmessage = (event) => {
|
||||||
|
try {
|
||||||
|
const data: SSEEvent = JSON.parse(event.data)
|
||||||
|
|
||||||
|
switch (data.type) {
|
||||||
|
case 'checklist_name':
|
||||||
|
case 'checklist_name_updated':
|
||||||
|
if (data.name) {
|
||||||
|
saveChecklist({
|
||||||
|
uuid,
|
||||||
|
name: data.name,
|
||||||
|
createdAt: new Date().toISOString(),
|
||||||
|
})
|
||||||
|
setCheckListName(data.name)
|
||||||
|
}
|
||||||
|
break
|
||||||
|
case 'full_state':
|
||||||
|
if (data.items) {
|
||||||
|
setItems(data.items)
|
||||||
|
}
|
||||||
|
break
|
||||||
|
case 'item_added':
|
||||||
|
if (data.item) {
|
||||||
|
setItems(prev => [...prev, data.item!])
|
||||||
|
}
|
||||||
|
break
|
||||||
|
case 'item_updated':
|
||||||
|
if (data.item) {
|
||||||
|
setItems(prev =>
|
||||||
|
prev.map(item =>
|
||||||
|
item.id === data.item!.id ? data.item! : item
|
||||||
|
)
|
||||||
|
)
|
||||||
|
}
|
||||||
|
break
|
||||||
|
case 'item_deleted':
|
||||||
|
if (data.id) {
|
||||||
|
setItems(prev => prev.filter(item => item.id !== data.id))
|
||||||
|
}
|
||||||
|
break
|
||||||
|
case 'item_locked':
|
||||||
|
if (data.id && data.locked_by && data.expires) {
|
||||||
|
setItems(prev =>
|
||||||
|
prev.map(item =>
|
||||||
|
item.id === data.id
|
||||||
|
? {
|
||||||
|
...item,
|
||||||
|
locked_by: data.locked_by,
|
||||||
|
lock_until: data.expires
|
||||||
|
}
|
||||||
|
: item
|
||||||
|
)
|
||||||
|
)
|
||||||
|
}
|
||||||
|
break
|
||||||
|
case 'item_unlocked':
|
||||||
|
if (data.id) {
|
||||||
|
setItems(prev =>
|
||||||
|
prev.map(item =>
|
||||||
|
item.id === data.id
|
||||||
|
? { ...item, locked_by: undefined, lock_until: undefined }
|
||||||
|
: item
|
||||||
|
)
|
||||||
|
)
|
||||||
|
}
|
||||||
|
break
|
||||||
|
}
|
||||||
|
} catch (parseError) {
|
||||||
|
console.error('Error parsing SSE message:', parseError)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
eventSource.onerror = (error) => {
|
||||||
|
console.error('SSE Error:', error)
|
||||||
|
setError('Connection lost. Trying to reconnect...')
|
||||||
|
setIsConnected(false)
|
||||||
|
|
||||||
|
// Close and attempt to reconnect after a delay
|
||||||
|
eventSource.close()
|
||||||
|
setTimeout(connectSSE, 3000)
|
||||||
|
}
|
||||||
|
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error connecting to SSE:', error)
|
||||||
|
setError('Failed to connect to server')
|
||||||
|
setIsConnected(false)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
connectSSE()
|
||||||
|
|
||||||
|
return () => {
|
||||||
|
if (eventSourceRef.current) {
|
||||||
|
eventSourceRef.current.close()
|
||||||
|
eventSourceRef.current = null
|
||||||
|
}
|
||||||
|
setIsConnected(false)
|
||||||
|
}
|
||||||
|
}, [uuid])
|
||||||
|
|
||||||
|
return { items, checkListName, isConnected, error }
|
||||||
|
}
|
64
frontend/src/index.css
Normal file
64
frontend/src/index.css
Normal file
|
@ -0,0 +1,64 @@
|
||||||
|
@import "tailwindcss";
|
||||||
|
|
||||||
|
/* Remove list styling from checklist items */
|
||||||
|
li {
|
||||||
|
list-style: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Radix UI Theme adjustments */
|
||||||
|
.radix-themes {
|
||||||
|
--default-font-family: system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Custom scrollbar for Radix ScrollArea */
|
||||||
|
[data-radix-scroll-area-viewport] {
|
||||||
|
scrollbar-width: thin;
|
||||||
|
scrollbar-color: var(--gray-a6) transparent;
|
||||||
|
}
|
||||||
|
|
||||||
|
[data-radix-scroll-area-viewport]::-webkit-scrollbar {
|
||||||
|
width: 8px;
|
||||||
|
height: 8px;
|
||||||
|
}
|
||||||
|
|
||||||
|
[data-radix-scroll-area-viewport]::-webkit-scrollbar-track {
|
||||||
|
background: transparent;
|
||||||
|
}
|
||||||
|
|
||||||
|
[data-radix-scroll-area-viewport]::-webkit-scrollbar-thumb {
|
||||||
|
background-color: var(--gray-a6);
|
||||||
|
border-radius: 4px;
|
||||||
|
}
|
||||||
|
|
||||||
|
[data-radix-scroll-area-viewport]::-webkit-scrollbar-thumb:hover {
|
||||||
|
background-color: var(--gray-a8);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Native datetime input styling */
|
||||||
|
input[type="datetime-local"] {
|
||||||
|
position: relative;
|
||||||
|
font-family: inherit;
|
||||||
|
}
|
||||||
|
|
||||||
|
input[type="datetime-local"]::-webkit-calendar-picker-indicator {
|
||||||
|
cursor: pointer;
|
||||||
|
opacity: 0.6;
|
||||||
|
filter: invert(0.8);
|
||||||
|
}
|
||||||
|
|
||||||
|
input[type="datetime-local"]::-webkit-calendar-picker-indicator:hover {
|
||||||
|
opacity: 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
.dark input[type="datetime-local"]::-webkit-calendar-picker-indicator {
|
||||||
|
filter: invert(0.8);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Ensure good mobile tap targets */
|
||||||
|
@media (max-width: 640px) {
|
||||||
|
input[type="datetime-local"] {
|
||||||
|
font-size: 16px; /* Prevents zoom on iOS */
|
||||||
|
min-height: 44px; /* Apple's recommended touch target size */
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
14
frontend/src/main.tsx
Normal file
14
frontend/src/main.tsx
Normal file
|
@ -0,0 +1,14 @@
|
||||||
|
import { StrictMode } from 'react'
|
||||||
|
import { createRoot } from 'react-dom/client'
|
||||||
|
import '@radix-ui/themes/styles.css'
|
||||||
|
import './index.css'
|
||||||
|
import { Theme } from '@radix-ui/themes'
|
||||||
|
import App from './App.tsx'
|
||||||
|
|
||||||
|
createRoot(document.getElementById('root')!).render(
|
||||||
|
<StrictMode>
|
||||||
|
<Theme accentColor="violet" grayColor="sand" radius="medium" scaling="100%">
|
||||||
|
<App />
|
||||||
|
</Theme>
|
||||||
|
</StrictMode>,
|
||||||
|
)
|
431
frontend/src/pages/Checklist.tsx
Normal file
431
frontend/src/pages/Checklist.tsx
Normal file
|
@ -0,0 +1,431 @@
|
||||||
|
import { useState } from 'react'
|
||||||
|
import { useParams, Link } from 'react-router-dom'
|
||||||
|
import { useSSE } from '../hooks/useSSE'
|
||||||
|
import ChecklistItem from '../components/ChecklistItem'
|
||||||
|
import { EditableTitle } from '../components/EditableTitle'
|
||||||
|
import { exportChecklistToJSON } from '../hooks/useLocalStorage'
|
||||||
|
import type { ChecklistItem as ChecklistItemType } from '../types'
|
||||||
|
import { Flex, Box, Text, Button, TextField, Heading, Badge, Card, IconButton } from '@radix-ui/themes'
|
||||||
|
import { ArrowLeftIcon, DownloadIcon, ChevronDownIcon, ChevronUpIcon } from '@radix-ui/react-icons'
|
||||||
|
|
||||||
|
interface ItemGroup {
|
||||||
|
title: string
|
||||||
|
items: ChecklistItemType[]
|
||||||
|
isCollapsible?: boolean
|
||||||
|
isCollapsed?: boolean
|
||||||
|
onToggleCollapse?: () => void
|
||||||
|
}
|
||||||
|
|
||||||
|
export default function Checklist() {
|
||||||
|
const { uuid } = useParams<{ uuid: string }>()
|
||||||
|
const { items, checkListName, isConnected, error } = useSSE(uuid || '')
|
||||||
|
const [newItemContent, setNewItemContent] = useState('')
|
||||||
|
const [isAddingItem, setIsAddingItem] = useState(false)
|
||||||
|
const [completedItemsCollapsed, setCompletedItemsCollapsed] = useState(false)
|
||||||
|
const [isExporting, setIsExporting] = useState(false)
|
||||||
|
|
||||||
|
|
||||||
|
const buildItemTree = (items: ChecklistItemType[]): ChecklistItemType[] => {
|
||||||
|
const itemMap = new Map<number, ChecklistItemType>()
|
||||||
|
const rootItems: ChecklistItemType[] = []
|
||||||
|
|
||||||
|
// Create a map of all items
|
||||||
|
items.forEach(item => {
|
||||||
|
itemMap.set(item.id, { ...item, children: [] })
|
||||||
|
})
|
||||||
|
|
||||||
|
// Build the tree structure
|
||||||
|
items.forEach(item => {
|
||||||
|
if (item.parent_id === null) {
|
||||||
|
rootItems.push(itemMap.get(item.id)!)
|
||||||
|
} else {
|
||||||
|
const parent = itemMap.get(item.parent_id)
|
||||||
|
if (parent) {
|
||||||
|
if (!parent.children) parent.children = []
|
||||||
|
parent.children.push(itemMap.get(item.id)!)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
return rootItems
|
||||||
|
}
|
||||||
|
|
||||||
|
const categorizeItems = (items: ChecklistItemType[]): ItemGroup[] => {
|
||||||
|
const now = new Date()
|
||||||
|
|
||||||
|
// Helper function to check if an item can be completed
|
||||||
|
const canComplete = (item: ChecklistItemType): boolean => {
|
||||||
|
// Check dependencies
|
||||||
|
const dependenciesCompleted = item.dependencies?.every(depId => {
|
||||||
|
const depItem = items.find(i => i.id === depId)
|
||||||
|
return depItem?.checked
|
||||||
|
}) ?? true
|
||||||
|
|
||||||
|
// Check date constraints
|
||||||
|
const notBeforeDate = item.not_before ? new Date(item.not_before) : null
|
||||||
|
const notAfterDate = item.not_after ? new Date(item.not_after) : null
|
||||||
|
const dateConstraintsMet = (!notBeforeDate || now >= notBeforeDate) && (!notAfterDate || now <= notAfterDate)
|
||||||
|
|
||||||
|
return dependenciesCompleted && dateConstraintsMet
|
||||||
|
}
|
||||||
|
|
||||||
|
// Helper function to check if an item is locked by constraints
|
||||||
|
const isLockedByConstraints = (item: ChecklistItemType): boolean => {
|
||||||
|
if (item.checked) return false
|
||||||
|
|
||||||
|
// Check dependencies
|
||||||
|
const dependenciesCompleted = item.dependencies?.every(depId => {
|
||||||
|
const depItem = items.find(i => i.id === depId)
|
||||||
|
return depItem?.checked
|
||||||
|
}) ?? true
|
||||||
|
|
||||||
|
// Check date constraints
|
||||||
|
const notBeforeDate = item.not_before ? new Date(item.not_before) : null
|
||||||
|
const notAfterDate = item.not_after ? new Date(item.not_after) : null
|
||||||
|
const dateConstraintsMet = (!notBeforeDate || now >= notBeforeDate) && (!notAfterDate || now <= notAfterDate)
|
||||||
|
|
||||||
|
return !dependenciesCompleted || !dateConstraintsMet
|
||||||
|
}
|
||||||
|
|
||||||
|
const completedItems = items.filter(item => item.checked)
|
||||||
|
const availableItems = items.filter(item => !item.checked && canComplete(item))
|
||||||
|
const lockedItems = items.filter(item => !item.checked && isLockedByConstraints(item))
|
||||||
|
|
||||||
|
const groups: ItemGroup[] = []
|
||||||
|
|
||||||
|
// Completed items (collapsible)
|
||||||
|
if (completedItems.length > 0) {
|
||||||
|
groups.push({
|
||||||
|
title: `Completed (${completedItems.length})`,
|
||||||
|
items: completedItems,
|
||||||
|
isCollapsible: true,
|
||||||
|
isCollapsed: completedItemsCollapsed,
|
||||||
|
onToggleCollapse: () => setCompletedItemsCollapsed(!completedItemsCollapsed)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// Available items (can be completed)
|
||||||
|
if (availableItems.length > 0) {
|
||||||
|
groups.push({
|
||||||
|
title: `Available (${availableItems.length})`,
|
||||||
|
items: availableItems
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// Locked items (cannot be completed due to constraints)
|
||||||
|
if (lockedItems.length > 0) {
|
||||||
|
groups.push({
|
||||||
|
title: `Locked by Constraints (${lockedItems.length})`,
|
||||||
|
items: lockedItems
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
return groups
|
||||||
|
}
|
||||||
|
|
||||||
|
const addItem = async (content: string, parentId?: number) => {
|
||||||
|
if (!content.trim() || !uuid) return
|
||||||
|
|
||||||
|
setIsAddingItem(true)
|
||||||
|
try {
|
||||||
|
const response = await fetch(`/api/checklists/${uuid}/items`, {
|
||||||
|
method: 'POST',
|
||||||
|
headers: {
|
||||||
|
'Content-Type': 'application/json',
|
||||||
|
},
|
||||||
|
body: JSON.stringify({
|
||||||
|
content: content.trim(),
|
||||||
|
parent_id: parentId || null
|
||||||
|
}),
|
||||||
|
})
|
||||||
|
|
||||||
|
if (!response.ok) {
|
||||||
|
throw new Error('Failed to add item')
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error adding item:', error)
|
||||||
|
alert('Failed to add item')
|
||||||
|
} finally {
|
||||||
|
setIsAddingItem(false)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const updateItem = async (id: number, updates: Partial<ChecklistItemType>) => {
|
||||||
|
if (!uuid) return
|
||||||
|
|
||||||
|
try {
|
||||||
|
const response = await fetch(`/api/checklists/${uuid}/items/${id}`, {
|
||||||
|
method: 'PATCH',
|
||||||
|
headers: {
|
||||||
|
'Content-Type': 'application/json',
|
||||||
|
},
|
||||||
|
body: JSON.stringify(updates),
|
||||||
|
})
|
||||||
|
|
||||||
|
if (!response.ok) {
|
||||||
|
throw new Error('Failed to update item')
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error updating item:', error)
|
||||||
|
throw error
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const deleteItem = async (id: number) => {
|
||||||
|
if (!uuid) return
|
||||||
|
|
||||||
|
try {
|
||||||
|
const response = await fetch(`/api/checklists/${uuid}/items/${id}`, {
|
||||||
|
method: 'DELETE',
|
||||||
|
})
|
||||||
|
|
||||||
|
if (!response.ok) {
|
||||||
|
throw new Error('Failed to delete item')
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error deleting item:', error)
|
||||||
|
throw error
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const lockItem = async (id: number, user: string) => {
|
||||||
|
if (!uuid) return
|
||||||
|
|
||||||
|
try {
|
||||||
|
const response = await fetch(`/api/checklists/${uuid}/items/${id}/lock`, {
|
||||||
|
method: 'POST',
|
||||||
|
headers: {
|
||||||
|
'Content-Type': 'application/json',
|
||||||
|
},
|
||||||
|
body: JSON.stringify({ user }),
|
||||||
|
})
|
||||||
|
|
||||||
|
if (!response.ok) {
|
||||||
|
throw new Error('Failed to lock item')
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error locking item:', error)
|
||||||
|
throw error
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const updateChecklistName = async (newName: string) => {
|
||||||
|
if (!uuid) throw new Error('No checklist UUID')
|
||||||
|
|
||||||
|
const response = await fetch(`/api/checklists/${uuid}/name`, {
|
||||||
|
method: 'PATCH',
|
||||||
|
headers: {
|
||||||
|
'Content-Type': 'application/json',
|
||||||
|
},
|
||||||
|
body: JSON.stringify({ name: newName }),
|
||||||
|
})
|
||||||
|
|
||||||
|
if (!response.ok) {
|
||||||
|
throw new Error('Failed to update checklist name')
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const handleAddItem = async () => {
|
||||||
|
await addItem(newItemContent)
|
||||||
|
setNewItemContent('')
|
||||||
|
}
|
||||||
|
|
||||||
|
const handleKeyPress = (e: React.KeyboardEvent) => {
|
||||||
|
if (e.key === 'Enter') {
|
||||||
|
handleAddItem()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const handleExportChecklist = async () => {
|
||||||
|
if (!uuid || !checkListName) return
|
||||||
|
|
||||||
|
setIsExporting(true)
|
||||||
|
try {
|
||||||
|
await exportChecklistToJSON(uuid, checkListName)
|
||||||
|
} catch {
|
||||||
|
alert('Failed to export checklist')
|
||||||
|
} finally {
|
||||||
|
setIsExporting(false)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
const renderGroupedItems = (allItems: ChecklistItemType[]) => {
|
||||||
|
const itemTree = buildItemTree(allItems)
|
||||||
|
|
||||||
|
if (itemTree.length === 0) {
|
||||||
|
return (
|
||||||
|
<Flex direction="column" align="center" justify="center" py="9">
|
||||||
|
<Text size="9" color="gray" mb="3">📝</Text>
|
||||||
|
<Text size="3" weight="medium" color="gray">No items yet</Text>
|
||||||
|
<Text size="2" color="gray" mt="1">Add your first item above to get started!</Text>
|
||||||
|
</Flex>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
const groups = categorizeItems(allItems)
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Flex direction="column" gap="5">
|
||||||
|
{groups.map((group, groupIndex) => (
|
||||||
|
<Box key={groupIndex}>
|
||||||
|
<Flex align="center" justify="between" pb="2" className="border-b border-gray-200 dark:border-gray-700">
|
||||||
|
<Heading
|
||||||
|
size="2"
|
||||||
|
color={group.title.includes('Completed') ? "green" : group.title.includes('Available') ? "blue" : "orange"}
|
||||||
|
>
|
||||||
|
{group.title}
|
||||||
|
</Heading>
|
||||||
|
{group.isCollapsible && (
|
||||||
|
<IconButton
|
||||||
|
size="1"
|
||||||
|
variant="ghost"
|
||||||
|
onClick={group.onToggleCollapse}
|
||||||
|
>
|
||||||
|
{group.isCollapsed ? <ChevronDownIcon /> : <ChevronUpIcon />}
|
||||||
|
</IconButton>
|
||||||
|
)}
|
||||||
|
</Flex>
|
||||||
|
|
||||||
|
{(!group.isCollapsible || !group.isCollapsed) && (
|
||||||
|
<Box
|
||||||
|
mt="3"
|
||||||
|
style={{
|
||||||
|
opacity: group.title.includes('Completed') ? 0.75 : 1
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<Flex direction="column" gap="2">
|
||||||
|
{group.items.map(item => {
|
||||||
|
const findItemWithChildren = (items: ChecklistItemType[], targetId: number): ChecklistItemType | null => {
|
||||||
|
for (const item of items) {
|
||||||
|
if (item.id === targetId) {
|
||||||
|
return item
|
||||||
|
}
|
||||||
|
if (item.children) {
|
||||||
|
const found = findItemWithChildren(item.children, targetId)
|
||||||
|
if (found) return found
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
|
||||||
|
const itemWithChildren = findItemWithChildren(itemTree, item.id)
|
||||||
|
|
||||||
|
return (
|
||||||
|
<ChecklistItem
|
||||||
|
key={item.id}
|
||||||
|
item={item}
|
||||||
|
onUpdate={updateItem}
|
||||||
|
onDelete={deleteItem}
|
||||||
|
onLock={lockItem}
|
||||||
|
children={itemWithChildren?.children || []}
|
||||||
|
allItems={allItems}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
})}
|
||||||
|
</Flex>
|
||||||
|
</Box>
|
||||||
|
)}
|
||||||
|
</Box>
|
||||||
|
))}
|
||||||
|
</Flex>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!uuid) {
|
||||||
|
return (
|
||||||
|
<Flex align="center" justify="center" style={{ minHeight: '100vh' }}>
|
||||||
|
<Text size="4" color="red" weight="medium">Invalid checklist ID</Text>
|
||||||
|
</Flex>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Box style={{ minHeight: '100vh' }} className="bg-gray-50 dark:bg-gray-900">
|
||||||
|
<Box className="bg-white dark:bg-gray-800 shadow-sm border-b border-gray-200 dark:border-gray-700">
|
||||||
|
<Box style={{ maxWidth: '1024px' }} mx="auto" p="3">
|
||||||
|
<Flex direction={{ initial: 'column', sm: 'row' }} align="center" justify="between" gap="3">
|
||||||
|
<Flex align="center" gap="3">
|
||||||
|
<Link to="/">
|
||||||
|
<Button variant="ghost" size="2">
|
||||||
|
<ArrowLeftIcon />
|
||||||
|
Back
|
||||||
|
</Button>
|
||||||
|
</Link>
|
||||||
|
<EditableTitle
|
||||||
|
title={checkListName}
|
||||||
|
onSave={updateChecklistName}
|
||||||
|
className="text-base"
|
||||||
|
/>
|
||||||
|
</Flex>
|
||||||
|
<Flex align="center" gap="2">
|
||||||
|
<Button
|
||||||
|
onClick={handleExportChecklist}
|
||||||
|
disabled={isExporting || !isConnected}
|
||||||
|
size="2"
|
||||||
|
color="violet"
|
||||||
|
>
|
||||||
|
<DownloadIcon />
|
||||||
|
{isExporting ? 'Exporting...' : 'Export'}
|
||||||
|
</Button>
|
||||||
|
<Badge
|
||||||
|
color={isConnected ? "green" : "red"}
|
||||||
|
variant="surface"
|
||||||
|
size="2"
|
||||||
|
>
|
||||||
|
<Box
|
||||||
|
width="8px"
|
||||||
|
height="8px"
|
||||||
|
className={`rounded-full ${isConnected ? 'bg-green-500' : 'bg-red-500'}`}
|
||||||
|
/>
|
||||||
|
{isConnected ? 'Connected' : 'Disconnected'}
|
||||||
|
</Badge>
|
||||||
|
</Flex>
|
||||||
|
</Flex>
|
||||||
|
</Box>
|
||||||
|
</Box>
|
||||||
|
|
||||||
|
{error && (
|
||||||
|
<Box style={{ maxWidth: '1024px' }} mx="auto" px="2" py="2">
|
||||||
|
<Card size="2" style={{ backgroundColor: 'var(--red-a3)', borderColor: 'var(--red-a6)' }}>
|
||||||
|
<Flex align="center" gap="2">
|
||||||
|
<Text color="red">⚠️</Text>
|
||||||
|
<Text color="red" weight="medium">{error}</Text>
|
||||||
|
</Flex>
|
||||||
|
</Card>
|
||||||
|
</Box>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<Box style={{ maxWidth: '1024px' }} mx="auto" px="3" py="4">
|
||||||
|
<Box mb="4">
|
||||||
|
<Flex direction={{ initial: 'column', sm: 'row' }} gap="2">
|
||||||
|
<Box style={{ flex: 1 }}>
|
||||||
|
<TextField.Root
|
||||||
|
size="3"
|
||||||
|
placeholder="Add a new item..."
|
||||||
|
value={newItemContent}
|
||||||
|
onChange={(e) => setNewItemContent(e.target.value)}
|
||||||
|
onKeyDown={handleKeyPress}
|
||||||
|
disabled={isAddingItem || !isConnected}
|
||||||
|
/>
|
||||||
|
</Box>
|
||||||
|
<Button
|
||||||
|
onClick={handleAddItem}
|
||||||
|
disabled={isAddingItem || !newItemContent.trim() || !isConnected}
|
||||||
|
size="3"
|
||||||
|
>
|
||||||
|
{isAddingItem ? 'Adding...' : 'Add'}
|
||||||
|
</Button>
|
||||||
|
</Flex>
|
||||||
|
</Box>
|
||||||
|
|
||||||
|
<Box>
|
||||||
|
{renderGroupedItems(items)}
|
||||||
|
</Box>
|
||||||
|
</Box>
|
||||||
|
</Box>
|
||||||
|
)
|
||||||
|
}
|
16
frontend/src/pages/Home.tsx
Normal file
16
frontend/src/pages/Home.tsx
Normal file
|
@ -0,0 +1,16 @@
|
||||||
|
import CreateChecklist from '../components/CreateChecklist'
|
||||||
|
import SavedChecklists from '../components/SavedChecklists'
|
||||||
|
import { Box, Container } from '@radix-ui/themes'
|
||||||
|
|
||||||
|
function Home() {
|
||||||
|
return (
|
||||||
|
<Box style={{ minHeight: '100vh' }} className="bg-gray-50 dark:bg-gray-900">
|
||||||
|
<Container size="3" py="6">
|
||||||
|
<CreateChecklist className="mb-8" />
|
||||||
|
<SavedChecklists />
|
||||||
|
</Container>
|
||||||
|
</Box>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export default Home
|
36
frontend/src/types.ts
Normal file
36
frontend/src/types.ts
Normal file
|
@ -0,0 +1,36 @@
|
||||||
|
export interface ChecklistItem {
|
||||||
|
id: number
|
||||||
|
content: string
|
||||||
|
checked: boolean
|
||||||
|
parent_id: number | null
|
||||||
|
locked_by?: string
|
||||||
|
lock_until?: string
|
||||||
|
checklist_uuid: string
|
||||||
|
children?: ChecklistItem[]
|
||||||
|
dependencies?: number[]
|
||||||
|
not_before?: string
|
||||||
|
not_after?: string
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface SavedChecklist {
|
||||||
|
uuid: string
|
||||||
|
name: string
|
||||||
|
createdAt: string
|
||||||
|
lastOpened?: string
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface SSEEvent {
|
||||||
|
type: 'full_state' | 'item_added' | 'item_updated' | 'item_deleted' | 'item_locked' | 'item_unlocked' | 'checklist_name' | 'checklist_name_updated'
|
||||||
|
name?: string
|
||||||
|
items?: ChecklistItem[]
|
||||||
|
item?: ChecklistItem
|
||||||
|
id?: number
|
||||||
|
locked_by?: string
|
||||||
|
expires?: string
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ApiResponse<T = unknown> {
|
||||||
|
success: boolean
|
||||||
|
message: string
|
||||||
|
[key: string]: T | boolean | string
|
||||||
|
}
|
1
frontend/src/vite-env.d.ts
vendored
Normal file
1
frontend/src/vite-env.d.ts
vendored
Normal file
|
@ -0,0 +1 @@
|
||||||
|
/// <reference types="vite/client" />
|
27
frontend/tsconfig.app.json
Normal file
27
frontend/tsconfig.app.json
Normal file
|
@ -0,0 +1,27 @@
|
||||||
|
{
|
||||||
|
"compilerOptions": {
|
||||||
|
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.app.tsbuildinfo",
|
||||||
|
"target": "ES2022",
|
||||||
|
"useDefineForClassFields": true,
|
||||||
|
"lib": ["ES2022", "DOM", "DOM.Iterable"],
|
||||||
|
"module": "ESNext",
|
||||||
|
"skipLibCheck": true,
|
||||||
|
|
||||||
|
/* Bundler mode */
|
||||||
|
"moduleResolution": "bundler",
|
||||||
|
"allowImportingTsExtensions": true,
|
||||||
|
"verbatimModuleSyntax": true,
|
||||||
|
"moduleDetection": "force",
|
||||||
|
"noEmit": true,
|
||||||
|
"jsx": "react-jsx",
|
||||||
|
|
||||||
|
/* Linting */
|
||||||
|
"strict": true,
|
||||||
|
"noUnusedLocals": true,
|
||||||
|
"noUnusedParameters": true,
|
||||||
|
"erasableSyntaxOnly": true,
|
||||||
|
"noFallthroughCasesInSwitch": true,
|
||||||
|
"noUncheckedSideEffectImports": true
|
||||||
|
},
|
||||||
|
"include": ["src"]
|
||||||
|
}
|
7
frontend/tsconfig.json
Normal file
7
frontend/tsconfig.json
Normal file
|
@ -0,0 +1,7 @@
|
||||||
|
{
|
||||||
|
"files": [],
|
||||||
|
"references": [
|
||||||
|
{ "path": "./tsconfig.app.json" },
|
||||||
|
{ "path": "./tsconfig.node.json" }
|
||||||
|
]
|
||||||
|
}
|
25
frontend/tsconfig.node.json
Normal file
25
frontend/tsconfig.node.json
Normal file
|
@ -0,0 +1,25 @@
|
||||||
|
{
|
||||||
|
"compilerOptions": {
|
||||||
|
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.node.tsbuildinfo",
|
||||||
|
"target": "ES2023",
|
||||||
|
"lib": ["ES2023"],
|
||||||
|
"module": "ESNext",
|
||||||
|
"skipLibCheck": true,
|
||||||
|
|
||||||
|
/* Bundler mode */
|
||||||
|
"moduleResolution": "bundler",
|
||||||
|
"allowImportingTsExtensions": true,
|
||||||
|
"verbatimModuleSyntax": true,
|
||||||
|
"moduleDetection": "force",
|
||||||
|
"noEmit": true,
|
||||||
|
|
||||||
|
/* Linting */
|
||||||
|
"strict": true,
|
||||||
|
"noUnusedLocals": true,
|
||||||
|
"noUnusedParameters": true,
|
||||||
|
"erasableSyntaxOnly": true,
|
||||||
|
"noFallthroughCasesInSwitch": true,
|
||||||
|
"noUncheckedSideEffectImports": true
|
||||||
|
},
|
||||||
|
"include": ["vite.config.ts"]
|
||||||
|
}
|
19
frontend/vite.config.ts
Normal file
19
frontend/vite.config.ts
Normal file
|
@ -0,0 +1,19 @@
|
||||||
|
import { defineConfig } from 'vite'
|
||||||
|
import react from '@vitejs/plugin-react-swc'
|
||||||
|
import tailwindcss from '@tailwindcss/vite'
|
||||||
|
import { compression } from 'vite-plugin-compression2'
|
||||||
|
|
||||||
|
// https://vite.dev/config/
|
||||||
|
export default defineConfig({
|
||||||
|
plugins: [react(), tailwindcss(), compression()],
|
||||||
|
server: {
|
||||||
|
host: '0.0.0.0', // Allow external access for Docker
|
||||||
|
port: 5173,
|
||||||
|
proxy: {
|
||||||
|
'/api': {
|
||||||
|
target: 'http://localhost:8080',
|
||||||
|
changeOrigin: true,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
})
|
6
package-lock.json
generated
Normal file
6
package-lock.json
generated
Normal file
|
@ -0,0 +1,6 @@
|
||||||
|
{
|
||||||
|
"name": "gocheck",
|
||||||
|
"lockfileVersion": 3,
|
||||||
|
"requires": true,
|
||||||
|
"packages": {}
|
||||||
|
}
|
1
package.json
Normal file
1
package.json
Normal file
|
@ -0,0 +1 @@
|
||||||
|
{}
|
38
podman-compose.yml
Normal file
38
podman-compose.yml
Normal file
|
@ -0,0 +1,38 @@
|
||||||
|
services:
|
||||||
|
gocheck:
|
||||||
|
build:
|
||||||
|
context: .
|
||||||
|
dockerfile: Containerfile
|
||||||
|
args:
|
||||||
|
USER_ID: 1000
|
||||||
|
GROUP_ID: 1000
|
||||||
|
container_name: gocheck-container
|
||||||
|
ports:
|
||||||
|
- "${PORT:-8080}:8080"
|
||||||
|
environment:
|
||||||
|
- PORT=8080
|
||||||
|
volumes:
|
||||||
|
- gocheck-data:/app/backend/data
|
||||||
|
restart: unless-stopped
|
||||||
|
# Rootless Podman compatibility
|
||||||
|
security_opt:
|
||||||
|
- no-new-privileges:true
|
||||||
|
# Use host networking for better rootless compatibility
|
||||||
|
network_mode: host
|
||||||
|
healthcheck:
|
||||||
|
test: [
|
||||||
|
"CMD",
|
||||||
|
"wget",
|
||||||
|
"--no-verbose",
|
||||||
|
"--tries=1",
|
||||||
|
"--spider",
|
||||||
|
"http://localhost:8080/",
|
||||||
|
]
|
||||||
|
interval: 30s
|
||||||
|
timeout: 10s
|
||||||
|
retries: 3
|
||||||
|
start_period: 10s
|
||||||
|
|
||||||
|
volumes:
|
||||||
|
gocheck-data:
|
||||||
|
driver: local
|
47
test-checklist.json
Normal file
47
test-checklist.json
Normal file
|
@ -0,0 +1,47 @@
|
||||||
|
{
|
||||||
|
"name": "Test Import Checklist",
|
||||||
|
"uuid": "test-uuid-123",
|
||||||
|
"exportedAt": "2024-01-01T12:00:00.000Z",
|
||||||
|
"items": [
|
||||||
|
{
|
||||||
|
"id": 1,
|
||||||
|
"content": "First item",
|
||||||
|
"checked": false,
|
||||||
|
"parent_id": null,
|
||||||
|
"checklist_uuid": "test-uuid-123",
|
||||||
|
"dependencies": [],
|
||||||
|
"not_before": null,
|
||||||
|
"not_after": null
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": 2,
|
||||||
|
"content": "Second item (depends on first)",
|
||||||
|
"checked": false,
|
||||||
|
"parent_id": null,
|
||||||
|
"checklist_uuid": "test-uuid-123",
|
||||||
|
"dependencies": [1],
|
||||||
|
"not_before": null,
|
||||||
|
"not_after": null
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": 3,
|
||||||
|
"content": "Child item",
|
||||||
|
"checked": true,
|
||||||
|
"parent_id": 1,
|
||||||
|
"checklist_uuid": "test-uuid-123",
|
||||||
|
"dependencies": [],
|
||||||
|
"not_before": null,
|
||||||
|
"not_after": null
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": 4,
|
||||||
|
"content": "Item with date constraints",
|
||||||
|
"checked": false,
|
||||||
|
"parent_id": null,
|
||||||
|
"checklist_uuid": "test-uuid-123",
|
||||||
|
"dependencies": [2],
|
||||||
|
"not_before": "2024-01-01T10:00:00Z",
|
||||||
|
"not_after": "2024-01-01T14:00:00Z"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
Loading…
Add table
Add a link
Reference in a new issue