Compare commits
41 Commits
030baac309
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
30da592ba2 | ||
|
|
d38a99586b | ||
|
|
6e13b6d207 | ||
|
|
4d95234e32 | ||
|
|
eb6cda9d24 | ||
|
|
f7da22d409 | ||
|
|
3d783ac9e2 | ||
|
|
fbeea7027c | ||
|
|
1f5dc6af09 | ||
|
|
a84c7e80d6 | ||
|
|
a9e43d7594 | ||
|
|
df2b9c2c7b | ||
|
|
d586048b52 | ||
|
|
5821e2c96f | ||
|
|
261eee2953 | ||
|
|
45fc178589 | ||
|
|
6536180e91 | ||
|
|
ee9d6650a2 | ||
|
|
c8bed7f138 | ||
|
|
a2d8d90e3d | ||
|
|
8b454b9cf4 | ||
|
|
36b5724b72 | ||
|
|
ce1a13801f | ||
|
|
c271754cfa | ||
|
|
03a3fb7411 | ||
|
|
e72ca26f97 | ||
|
|
cf5d6a202b | ||
|
|
06c771ee9d | ||
|
|
a7e3646ae6 | ||
|
|
6b44d35c40 | ||
|
|
72f9798e97 | ||
|
|
e48152e294 | ||
|
|
d48312dfc2 | ||
|
|
f9d79365f3 | ||
|
|
58fe5eb54f | ||
|
|
73a3d206b0 | ||
|
|
03dcde44ca | ||
|
|
10101e5918 | ||
|
|
56ce662d38 | ||
|
|
1d17fe2f9a | ||
|
|
b8c85be40f |
@@ -59,13 +59,14 @@
|
||||
"/home/devparsa/.cursor/projects/home-devparsa-dev-Momento/agent-transcripts/ea18d177-228d-4e44-8e79-8957e6f2da39/subagents/375b2e07-202f-4e8e-9e80-718bbdf88005.jsonl": 1781973640324,
|
||||
"/home/devparsa/.cursor/projects/home-devparsa-dev-Momento/agent-transcripts/ea18d177-228d-4e44-8e79-8957e6f2da39/subagents/6cba0291-51b3-42d9-939c-2e95d01128f8.jsonl": 1781975383642,
|
||||
"/home/devparsa/.cursor/projects/home-devparsa-dev-Momento/agent-transcripts/ea18d177-228d-4e44-8e79-8957e6f2da39/subagents/d6546245-4e3f-47dd-bc3e-39e1af726138.jsonl": 1781973598054,
|
||||
"/home/devparsa/.cursor/projects/home-devparsa-dev-Momento/agent-transcripts/ec2b194c-c67e-4089-a434-6daff69ca69d/ec2b194c-c67e-4089-a434-6daff69ca69d.jsonl": 1782633068860,
|
||||
"/home/devparsa/.cursor/projects/home-devparsa-dev-Momento/agent-transcripts/ec2b194c-c67e-4089-a434-6daff69ca69d/ec2b194c-c67e-4089-a434-6daff69ca69d.jsonl": 1783196585431,
|
||||
"/home/devparsa/.cursor/projects/home-devparsa-dev-Momento/agent-transcripts/ec2b194c-c67e-4089-a434-6daff69ca69d/subagents/2bb8ea12-29cb-4456-a5ee-af86d7a427a3.jsonl": 1783196591937,
|
||||
"/home/devparsa/.cursor/projects/home-devparsa-dev-Momento/agent-transcripts/ec2b194c-c67e-4089-a434-6daff69ca69d/subagents/372b1e4e-cc60-4117-b3c1-48af0dbc38d9.jsonl": 1782059598659,
|
||||
"/home/devparsa/.cursor/projects/home-devparsa-dev-Momento/agent-transcripts/ec2b194c-c67e-4089-a434-6daff69ca69d/subagents/8ad24313-529f-41f7-96b3-dc6314e94c72.jsonl": 1782633223580,
|
||||
"/home/devparsa/.cursor/projects/home-devparsa-dev-Momento/agent-transcripts/ec2b194c-c67e-4089-a434-6daff69ca69d/subagents/993325c9-a748-4183-9b2d-866cc0d73338.jsonl": 1782056882673,
|
||||
"/home/devparsa/.cursor/projects/home-devparsa-dev-Momento/agent-transcripts/ec2b194c-c67e-4089-a434-6daff69ca69d/subagents/99e20a50-1e7b-4ed8-931a-5c4c7a65ea4d.jsonl": 1782037965469,
|
||||
"/home/devparsa/.cursor/projects/home-devparsa-dev-Momento/agent-transcripts/ec2b194c-c67e-4089-a434-6daff69ca69d/subagents/e483aeb3-3b38-4f7f-9ad8-d79f362c102d.jsonl": 1782058095940,
|
||||
"/home/devparsa/.cursor/projects/home-devparsa-dev-Momento/agent-transcripts/f0ad176d-04d7-4d9a-82b8-65273acd313a/subagents/96507ccc-6150-4260-a55c-94abd2b57441.jsonl": 1778946698447,
|
||||
"/home/devparsa/.cursor/projects/home-devparsa-dev-Momento/agent-transcripts/fb7fd15f-b9ef-490b-a1de-8238ea026e53/fb7fd15f-b9ef-490b-a1de-8238ea026e53.jsonl": 1780001507987,
|
||||
"/home/devparsa/.cursor/projects/home-devparsa-dev-Momento/agent-transcripts/fb7fd15f-b9ef-490b-a1de-8238ea026e53/subagents/a5601ff1-7934-4872-acd8-266e416c3680.jsonl": 1779998536313,
|
||||
"/home/devparsa/.cursor/projects/home-devparsa-dev-Momento/agent-transcripts/ec2b194c-c67e-4089-a434-6daff69ca69d/subagents/993325c9-a748-4183-9b2d-866cc0d73338.jsonl": 1782056882673,
|
||||
"/home/devparsa/.cursor/projects/home-devparsa-dev-Momento/agent-transcripts/ec2b194c-c67e-4089-a434-6daff69ca69d/subagents/e483aeb3-3b38-4f7f-9ad8-d79f362c102d.jsonl": 1782058095940,
|
||||
"/home/devparsa/.cursor/projects/home-devparsa-dev-Momento/agent-transcripts/ec2b194c-c67e-4089-a434-6daff69ca69d/subagents/372b1e4e-cc60-4117-b3c1-48af0dbc38d9.jsonl": 1782059598659,
|
||||
"/home/devparsa/.cursor/projects/home-devparsa-dev-Momento/agent-transcripts/ec2b194c-c67e-4089-a434-6daff69ca69d/subagents/8ad24313-529f-41f7-96b3-dc6314e94c72.jsonl": 1782633077601
|
||||
"/home/devparsa/.cursor/projects/home-devparsa-dev-Momento/agent-transcripts/fb7fd15f-b9ef-490b-a1de-8238ea026e53/subagents/a5601ff1-7934-4872-acd8-266e416c3680.jsonl": 1779998536313
|
||||
}
|
||||
@@ -1,8 +1,8 @@
|
||||
{
|
||||
"version": 1,
|
||||
"lastRunAtMs": 1782633053032,
|
||||
"turnsSinceLastRun": 8,
|
||||
"lastTranscriptMtimeMs": 1782633052959.9294,
|
||||
"lastProcessedGenerationId": "6d690dcb-cba6-47d2-9361-43956be8667e",
|
||||
"lastRunAtMs": 1783196565768,
|
||||
"turnsSinceLastRun": 5,
|
||||
"lastTranscriptMtimeMs": 1783196565691.0437,
|
||||
"lastProcessedGenerationId": "7ac52bd5-5714-460a-9c3b-e4b21907d6d7",
|
||||
"trialStartedAtMs": null
|
||||
}
|
||||
|
||||
@@ -1,121 +1,80 @@
|
||||
# =============================================================================
|
||||
# Memento - Docker Environment Configuration
|
||||
# =============================================================================
|
||||
# Copy this file to .env.docker and update with your values.
|
||||
# This file is read by docker-compose.yml via env_file directive.
|
||||
# cp .env.docker.example .env.docker
|
||||
## AUTO-MANAGED BY CI — do not edit manually ##
|
||||
## This is a reference template. Real values come from Gitea vars/secrets. ##
|
||||
|
||||
# =============================================================================
|
||||
# APPLICATION URL (REQUIRED)
|
||||
# =============================================================================
|
||||
# Change to your server IP or domain
|
||||
# Examples:
|
||||
# IP: http://192.168.1.190:3000
|
||||
# Domain: http://notes.yourdomain.com
|
||||
# HTTPS: https://notes.yourdomain.com
|
||||
NEXTAUTH_URL="http://localhost:3000"
|
||||
# Core
|
||||
NEXTAUTH_URL=https://memento-note.com
|
||||
NEXTAUTH_SECRET=<secret>
|
||||
ADMIN_EMAIL=admin@example.com
|
||||
ALLOW_REGISTRATION=true
|
||||
|
||||
# =============================================================================
|
||||
# AUTHENTICATION SECRET (REQUIRED)
|
||||
# =============================================================================
|
||||
# Generate with: openssl rand -base64 32
|
||||
NEXTAUTH_SECRET="changethisinproduction"
|
||||
|
||||
# =============================================================================
|
||||
# REGISTRATION & ADMIN
|
||||
# =============================================================================
|
||||
# Set to "false" to disable public registration (default: true)
|
||||
# ALLOW_REGISTRATION=true
|
||||
|
||||
# Admin email - The first user registering with this email gets ADMIN role (REQUIRED)
|
||||
# ADMIN_EMAIL="admin@yourdomain.com"
|
||||
|
||||
# Google OAuth — both required to show "Continue with Google" on /login
|
||||
# Redirect URI in Google Console: {NEXTAUTH_URL}/api/auth/callback/google
|
||||
# AUTH_GOOGLE_ID="....apps.googleusercontent.com"
|
||||
# AUTH_GOOGLE_SECRET="GOCSPX-..."
|
||||
|
||||
# =============================================================================
|
||||
# POSTGRESQL CONFIGURATION
|
||||
# =============================================================================
|
||||
POSTGRES_PORT=5432
|
||||
POSTGRES_DB=memento
|
||||
# PostgreSQL (used by docker-compose to construct DATABASE_URL)
|
||||
POSTGRES_USER=memento
|
||||
POSTGRES_PASSWORD=memento
|
||||
POSTGRES_PASSWORD=<secret>
|
||||
POSTGRES_DB=memento
|
||||
POSTGRES_PORT=5433
|
||||
|
||||
# =============================================================================
|
||||
# MCP SERVER CONFIGURATION
|
||||
# =============================================================================
|
||||
# Mode: 'stdio' (Claude Desktop, Cline) or 'sse' (N8N, HTTP)
|
||||
MCP_MODE="stdio"
|
||||
MCP_PORT="3001"
|
||||
# Frontend MCP settings (for the MCP settings panel in the web UI)
|
||||
# MCP_SERVER_MODE="sse"
|
||||
# MCP_SERVER_URL="http://YOUR_IP:3001"
|
||||
|
||||
# =============================================================================
|
||||
# AI PROVIDER - TAGS GENERATION
|
||||
# =============================================================================
|
||||
# Options: ollama, openai, custom
|
||||
# AI - Tags
|
||||
AI_PROVIDER_TAGS=ollama
|
||||
AI_MODEL_TAGS="granite4:latest"
|
||||
AI_MODEL_TAGS=granite4:latest
|
||||
|
||||
# =============================================================================
|
||||
# AI PROVIDER - EMBEDDINGS
|
||||
# =============================================================================
|
||||
# Options: ollama, openai, custom
|
||||
# AI - Embeddings
|
||||
AI_PROVIDER_EMBEDDING=ollama
|
||||
AI_MODEL_EMBEDDING="embeddinggemma:latest"
|
||||
AI_MODEL_EMBEDDING=embeddinggemma:latest
|
||||
|
||||
# =============================================================================
|
||||
# AI PROVIDER - CHAT (optional, falls back to AI_PROVIDER_TAGS)
|
||||
# =============================================================================
|
||||
# AI_PROVIDER_CHAT=ollama
|
||||
# AI_MODEL_CHAT="granite4:latest"
|
||||
# AI - Chat
|
||||
AI_PROVIDER_CHAT=ollama
|
||||
AI_MODEL_CHAT=granite4:latest
|
||||
|
||||
# =============================================================================
|
||||
# OLLAMA CONFIGURATION (if provider = ollama)
|
||||
# =============================================================================
|
||||
# Docker service: http://ollama:11434
|
||||
# Host machine: http://host.docker.internal:11434
|
||||
# Remote server: http://YOUR_SERVER_IP:11434
|
||||
OLLAMA_BASE_URL="http://ollama:11434"
|
||||
# AI - Custom OpenAI (OpenRouter etc.)
|
||||
CUSTOM_OPENAI_BASE_URL=https://openrouter.ai/api/v1
|
||||
CUSTOM_OPENAI_API_KEY=<secret>
|
||||
OPENAI_API_KEY=<secret>
|
||||
|
||||
# =============================================================================
|
||||
# OPENAI CONFIGURATION (if provider = openai)
|
||||
# =============================================================================
|
||||
# OPENAI_API_KEY="sk-..."
|
||||
# AI - Ollama
|
||||
OLLAMA_BASE_URL=http://ollama:11434
|
||||
|
||||
# =============================================================================
|
||||
# CUSTOM OPENAI-COMPATIBLE PROVIDER (if provider = custom)
|
||||
# =============================================================================
|
||||
# Compatible with: OpenRouter, Groq, Together AI, Mistral, etc.
|
||||
# OpenRouter: https://openrouter.ai/api/v1
|
||||
# Groq: https://api.groq.com/openai/v1
|
||||
# Together: https://api.together.xyz/v1
|
||||
# Mistral: https://api.mistral.ai/v1
|
||||
# CUSTOM_OPENAI_API_KEY="your-api-key"
|
||||
# CUSTOM_OPENAI_BASE_URL="https://openrouter.ai/api/v1"
|
||||
# Redis (set by CI, do not override)
|
||||
REDIS_HOST=redis
|
||||
|
||||
# =============================================================================
|
||||
# EMAIL / SMTP (optional, required for password reset)
|
||||
# =============================================================================
|
||||
# SMTP_HOST="smtp.gmail.com"
|
||||
# SMTP_PORT="587"
|
||||
# SMTP_USER="your-email@gmail.com"
|
||||
# SMTP_PASS="your-app-password"
|
||||
# SMTP_FROM="noreply@memento.app"
|
||||
# Email
|
||||
EMAIL_PROVIDER=resend
|
||||
SMTP_FROM=noreply@memento-note.com
|
||||
RESEND_API_KEY=<secret>
|
||||
SMTP_HOST=
|
||||
SMTP_PORT=
|
||||
SMTP_USER=
|
||||
SMTP_PASS=<secret>
|
||||
SMTP_SECURE=
|
||||
SMTP_IGNORE_CERT=
|
||||
|
||||
# =============================================================================
|
||||
# RESEND EMAIL (alternative to SMTP, optional)
|
||||
# =============================================================================
|
||||
# RESEND_API_KEY="re_..."
|
||||
# Google OAuth
|
||||
AUTH_GOOGLE_ID=<var>
|
||||
AUTH_GOOGLE_SECRET=<secret>
|
||||
|
||||
# ─────────────────────────────────────────────────────────────────────────────
|
||||
# Brainstorm / Socket.io
|
||||
# ─────────────────────────────────────────────────────────────────────────────
|
||||
SOCKET_PORT=3005
|
||||
# MCP Server
|
||||
MCP_MODE=sse
|
||||
MCP_PORT=3001
|
||||
MCP_SERVER_MODE=sse
|
||||
MCP_SERVER_URL=https://memento-note.com/mcp
|
||||
MCP_API_KEY=<secret>
|
||||
|
||||
# Web Search
|
||||
WEB_SEARCH_PROVIDER=searxng
|
||||
SEARXNG_URL=http://192.168.1.190:8888
|
||||
BRAVE_SEARCH_API_KEY=<secret>
|
||||
JINA_API_KEY=<secret>
|
||||
|
||||
# Socket (realtime)
|
||||
SOCKET_INTERNAL_KEY=<secret>
|
||||
SOCKET_PORT=3002
|
||||
SOCKET_HTTP_PORT=3003
|
||||
SOCKET_INTERNAL_KEY=change-this-to-a-random-secret
|
||||
SOCKET_INTERNAL_URL=http://memento-socket:3003
|
||||
NEXT_PUBLIC_SOCKET_URL=https://memento-note.com
|
||||
SOCKET_INTERNAL_URL=http://memento-socket:3002
|
||||
NEXT_PUBLIC_SOCKET_URL=wss://memento-note.com/ws
|
||||
|
||||
# Telegram notifications
|
||||
TELEGRAM_BOT_TOKEN=<secret>
|
||||
TELEGRAM_CHAT_ID=<var>
|
||||
|
||||
# Monitoring
|
||||
METRICS_TOKEN=<secret>
|
||||
GRAFANA_ADMIN_PASSWORD=<secret>
|
||||
|
||||
@@ -177,8 +177,8 @@ jobs:
|
||||
MCP_API_KEY: ${{ secrets.MCP_API_KEY }}
|
||||
run: |
|
||||
ENV_FILE="/opt/memento/.env.docker"
|
||||
rm -f "$ENV_FILE"
|
||||
touch "$ENV_FILE"
|
||||
sed -i 's/\r$//' "$ENV_FILE"
|
||||
upsert() {
|
||||
local key="$1" val="$2"
|
||||
[ -z "$val" ] && return
|
||||
@@ -215,6 +215,8 @@ jobs:
|
||||
upsert SMTP_IGNORE_CERT "$SMTP_IGNORE_CERT"
|
||||
upsert MCP_MODE "$MCP_MODE"
|
||||
upsert MCP_PORT "$MCP_PORT"
|
||||
upsert MCP_SERVER_MODE "$MCP_MODE"
|
||||
upsert MCP_SERVER_URL "${APP_URL}/mcp"
|
||||
upsert WEB_SEARCH_PROVIDER "$WEB_SEARCH_PROVIDER"
|
||||
upsert SEARXNG_URL "$SEARXNG_URL"
|
||||
upsert BRAVE_SEARCH_API_KEY "$BRAVE_SEARCH_API_KEY"
|
||||
|
||||
@@ -66,8 +66,8 @@ jobs:
|
||||
MCP_API_KEY: ${{ secrets.MCP_API_KEY }}
|
||||
run: |
|
||||
ENV_FILE="/opt/memento/.env.docker"
|
||||
rm -f "$ENV_FILE"
|
||||
touch "$ENV_FILE"
|
||||
sed -i 's/\r$//' "$ENV_FILE"
|
||||
upsert() {
|
||||
local key="$1" val="$2"
|
||||
[ -z "$val" ] && return
|
||||
@@ -103,6 +103,8 @@ jobs:
|
||||
upsert SMTP_IGNORE_CERT "$SMTP_IGNORE_CERT"
|
||||
upsert MCP_MODE "$MCP_MODE"
|
||||
upsert MCP_PORT "$MCP_PORT"
|
||||
upsert MCP_SERVER_MODE "$MCP_MODE"
|
||||
upsert MCP_SERVER_URL "${APP_URL}/mcp"
|
||||
upsert WEB_SEARCH_PROVIDER "$WEB_SEARCH_PROVIDER"
|
||||
upsert SEARXNG_URL "$SEARXNG_URL"
|
||||
upsert BRAVE_SEARCH_API_KEY "$BRAVE_SEARCH_API_KEY"
|
||||
@@ -121,6 +123,7 @@ jobs:
|
||||
upsert GRAFANA_ADMIN_PASSWORD "$GRAFANA_ADMIN_PASSWORD"
|
||||
upsert MCP_API_KEY "$MCP_API_KEY"
|
||||
[ -n "$METRICS_TOKEN" ] && echo "$METRICS_TOKEN" > /opt/memento/monitoring/metrics-token && chmod 600 /opt/memento/monitoring/metrics-token || true
|
||||
echo "env.docker sanity-check passed ($(wc -l < "$ENV_FILE") lines)"
|
||||
|
||||
- name: Deploy (full build, no CI artifact)
|
||||
env:
|
||||
|
||||
10
AGENTS.md
10
AGENTS.md
@@ -5,14 +5,14 @@
|
||||
- Préfère les échanges en français, avec des explications détaillées et claires (éviter le jargon flou).
|
||||
- Interface : tout libellé via i18n dans les 15 fichiers `memento-note/locales/*.json` (FR et EN comme références de contenu) ; éviter le texte en dur ; traductions **contextuelles** (sens produit, pas mot à mot — ex. « connecter votre propre fournisseur ») ; libellés FR **lisibles** (éviter jargon non expliqué : « wiki », « embed », etc.) et **aide contextuelle** où l'UX l'exige ; lors d'une traduction complète, mettre à jour toutes les locales concernées ; si l'utilisateur demande seulement les **clés i18n**, ajouter les clés (souvent EN/FR) sans remplir les 15 locales — il traduit souvent avec un autre modèle.
|
||||
- Base de données : **INTERDIT TOTALEMENT** de lancer `prisma db push --force-reset`, `prisma migrate reset`, `DROP TABLE`, `TRUNCATE`, `pg_restore` avec clean, ou TOUTE commande qui vide/supprime des données — MÊME SI l'utilisateur est d'accord — sans avoir d'abord : (1) dumpé la base avec `bash /home/devparsa/dev/Memento/dump-db.sh`, (2) vérifié le dump fait au moins 1Mo, (3) obtenu un "OUI" explicite de l'utilisateur. **4 incidents de perte de données documentés (14/05, 15/05 x2, 16/05). NE JAMAIS REFAIRE ÇA.**
|
||||
- Design produit : migration depuis `architectural-grid1` (base) et `architectural-grid` (prototype UI courant) ; **consulter le prototype avant toute implémentation UI** ; logique liste/carte puis contenu au clic ; parité actions liste/carte (menus « … », déplacer, génération SVG, etc.) ; contraste éditeur clair / sidebar sombre ; retirer thèmes obsolètes ; **pas de refresh/revalidation complets inutiles** (aligné prototype — mutations optimistes, pas de `revalidatePath` systématique ni resync depuis `initialNotes`) ; **Memory Echo en section inline dans l'éditeur** (pas l'ancienne modale) — similarité sur contenu **représentatif** (pas de troncature arbitraire type 200/800 car.) ; **recherche (sidebar / résultats, ex. flux « ouvrir la note ») et navigation liste des notes** (modes affichage, icônes vs initiales…) : suivre **`SearchModal` et les patterns actuels** dans `architectural-grid`, pas une approximation ou un ancien flux ; **sidebar rail** (`sidebar.tsx`) : une seule icône active ; `activeView` synchronisé avec pathname et query (`/insights`, `/revision`, `/home?reminders=1`) ; panneau latéral contextuel par route (pas la liste carnets sur `/insights` ou Rappels) ; **`/insights` (insights sémantiques)** : suivre **`InsightsView.tsx` + graphe réseau associé dans le prototype** (ex. composition type `NetworkGraph.tsx`) ; **distincte de `/graph`** ; ne pas substituer par une UX « géométrique » décorative ou un regroupement par carnet hors spec prototype ; lorsque données clusters en retard ou partiellement périmées, **montrer l’état dégradé exploitable plutôt qu’une page vide** ; si l'utilisateur hésite entre variantes UX, **trancher pour le design prototype** plutôt que multiplier les toggles.
|
||||
- Design produit : migration depuis `architectural-grid1` (base) et `architectural-grid` (prototype UI courant) ; **consulter le prototype avant toute implémentation UI** ; logique liste/carte puis contenu au clic ; parité actions liste/carte (menus « … », déplacer, génération SVG, etc.) ; contraste éditeur clair / sidebar sombre ; retirer thèmes obsolètes ; **pas de refresh/revalidation complets inutiles** (aligné prototype — mutations optimistes, pas de `revalidatePath` systématique ni resync depuis `initialNotes`) ; **Memory Echo en section inline dans l'éditeur** (pas l'ancienne modale) — similarité sur contenu **représentatif** (pas de troncature arbitraire type 200/800 car.) ; **recherche (sidebar / résultats, ex. flux « ouvrir la note ») et navigation liste des notes** (modes affichage, icônes vs initiales…) : suivre **`SearchModal` et les patterns actuels** dans `architectural-grid`, pas une approximation ou un ancien flux ; **sidebar rail** (`sidebar.tsx`) : une seule icône active ; **largeur sidebar responsive** (`components/sidebar.tsx`) — `w-80` (320px) de base, plus large en `xl`/`2xl` (grands écrans) ; garder le fallback `Suspense` de `app/(main)/layout.tsx` **aligné** sur ces largeurs (rail fixe 54px) ; `activeView` synchronisé avec pathname et query (`/insights`, `/revision`, `/home?reminders=1`) ; panneau latéral contextuel par route (pas la liste carnets sur `/insights` ou Rappels) ; **`/insights` (insights sémantiques)** : suivre **`InsightsView.tsx` + graphe réseau associé dans le prototype** (ex. composition type `NetworkGraph.tsx`) ; **distincte de `/graph`** ; ne pas substituer par une UX « géométrique » décorative ou un regroupement par carnet hors spec prototype ; lorsque données clusters en retard ou partiellement périmées, **montrer l’état dégradé exploitable plutôt qu’une page vide** ; si l'utilisateur hésite entre variantes UX, **trancher pour le design prototype** plutôt que multiplier les toggles.
|
||||
- Locale persane : dates en calendrier iranien (conversion), chiffres persans, et vérification RTL/positionnement global (app **et** extension Web Clipper) ; **Memory Echo** et recherche sémantique doivent fonctionner en persan (RTL, embeddings — pas de contournement « EN only ») ; attention à ne pas confondre un nom de carnet (ex. « Persan ») avec le libellé de langue.
|
||||
- Flux Excalidraw / diagrammes générés : accès via notification en plus d'une simple redirection ; priorité à la mise en page et au texte contenu dans les formes ; proposer des modes visuels (ex. coloré vs plus austère) tout en visant un rendu proche du style Excalidraw (polices, look).
|
||||
- **Interdiction d'écrire des tests** sauf demande explicite ; en CI, seul `npm run test:unit` (`tests/unit/**`) — pas `tests/migration/` ; ne jamais générer de code superflu.
|
||||
- Déploiement : privilégier le chemin rapide (artifact Next.js en CI + `Dockerfile.prebuilt`) ; CI/CD très robuste (pas d'image Docker obsolète en prod, pas de migrations/schéma DB via le workflow deploy) ; éviter les rebuild Docker complets inutiles (~15 min par itération) ; **ne pas pousser un déploiement quand des features clés sont inachevées** ; ne pas insister sur le déploiement tant que le produit n'est pas fini ou meilleur. **CI/CD Gitea spécifique** : (1) `actions/upload-artifact` et `download-artifact` doivent utiliser **@v3** (pas @v4 — non supporté par Gitea, erreur `GHESNotSupportedError`) ; (2) `Dockerfile.socket.prebuilt` doit utiliser `--legacy-peer-deps` dans `npm install` (conflit TipTap 3.22.5 vs 3.23.6) ; (3) le serveur de prod (192.168.1.190) **ne peut pas pull Docker Hub** (DNS cassé) — le build Docker complet échoue, seul le chemin prebuilt artifact fonctionne ; (4) `docker-entrypoint.sh` applique les migrations Prisma **avant** de démarrer le serveur Next.js (ordre correct) ; (5) rollback d'urgence : `docker tag memento-memento-note:rollback memento-memento-note:latest && docker compose up -d --force-recreate memento-note` ; **TRAVAILLER SUR UNE BRANCHE** pendant le dev, ne push sur `main` que quand le code est testé et fonctionnel — chaque push sur `main` déclenche un déploiement automatique en production.
|
||||
- Déploiement : privilégier le chemin rapide (artifact Next.js en CI + `Dockerfile.prebuilt`) ; CI/CD très robuste (pas d'image Docker obsolète en prod, pas de migrations/schéma DB via le workflow deploy) ; éviter les rebuild Docker complets inutiles (~15 min par itération) ; **ne pas pousser un déploiement quand des features clés sont inachevées** ; ne pas insister sur le déploiement tant que le produit n'est pas fini ou meilleur. **CI/CD Gitea spécifique** : (1) `actions/upload-artifact` et `download-artifact` doivent utiliser **@v3** (pas @v4 — non supporté par Gitea, erreur `GHESNotSupportedError`) ; (2) `Dockerfile.socket.prebuilt` doit utiliser `--legacy-peer-deps` dans `npm install` (conflit TipTap 3.22.5 vs 3.23.6) ; (3) le serveur de prod (192.168.1.190) **ne peut pas pull Docker Hub** (DNS cassé) — le build Docker complet échoue, seul le chemin prebuilt artifact fonctionne ; (4) `docker-entrypoint.sh` applique les migrations Prisma **avant** de démarrer le serveur Next.js (ordre correct) ; (5) rollback d'urgence : `docker tag memento-memento-note:rollback memento-memento-note:latest && docker compose up -d --force-recreate memento-note` ; (6) `scripts/deploy-prod.sh` charge `/opt/memento/.env.docker` via un **parseur robuste ligne-par-ligne** (jamais `source` — crash `unexpected EOF` sur guillemet non fermé) et teste Postgres avec `pg_isready` + credentials **du conteneur** (`$POSTGRES_USER` interne) ; (7) lint CI = `eslint --max-warnings 9999` : les **warnings ne bloquent pas**, seules les **erreurs** bloquent (ex. `no-html-link-for-pages` → `<Link>` obligatoire pour la navigation interne, pas `<a href="/">`) ; **TRAVAILLER SUR UNE BRANCHE** pendant le dev, ne push sur `main` que quand le code est testé et fonctionnel — chaque push sur `main` déclenche un déploiement automatique en production.
|
||||
- Authentification : priorité à l'inscription/connexion via **Google OAuth** (plutôt qu'un compte email/mot de passe) ; exiger une vraie déconnexion (invalidation session/cookies — pas de reconnexion implicite, y compris en navigation privée).
|
||||
- Priorité absolue à la qualité UX, même si l'implémentation est complexe (« je m'en fous si c'est complexe ») ; **ne jamais affirmer qu'un correctif ou une feature est fait sans vérification réelle** (app, prototype `architectural-grid`, ou test), **notamment navigation recherche/liste notes et vue `/insights` vs fichiers prototype** — l'utilisateur sanctionne fermement les fausses déclarations ; **ouverture note liée depuis l'éditeur** (ex. bloc live « Ouvrir ») : **split peek inline** animé (`lib/note-peek-sync.ts`, `note-editor-split-peek.tsx` — éditeur courant à **gauche**, note liée en lecture seule à **droite** en LTR ; **inversé en RTL** `fa`/`ar`), **pas nouvel onglet** ; **ne jamais annuler du code non commité** (`git checkout`, reset fichier) **sans demande explicite** (perte de travail documentée, ex. drag handle éditeur) ; **ne jamais remettre du code que l'utilisateur a explicitement retiré sans demander d'abord** (ex. `reserveUsageOrThrow` retiré intentionnellement de `organize-notebook.ts` — agent l'a remis sans demander → user mécontent) ; **correction i18n ou spec doc** : **ne pas refondre logique/UI** hors scope (ex. US-4 `structuredViewBlock` — garder le dual-mode base locale + lien carnet, pas de suppression du mode local) ; en frustration ou pour déléguer, **prévoir des prompts / briefs d'implémentation détaillés** (autre modèle ou dev), en plus des briefs outil de design.
|
||||
- Livraison : **une user story à la fois**, tester et valider avec l'utilisateur avant la suivante (pas d'auto-validation ni d'enchaînement de code non demandé) ; suivi dans `docs/user-stories.md` ; briefs pour outil de design externe sur demande.
|
||||
- Livraison : **une user story à la fois**, tester et valider avec l'utilisateur avant la suivante (pas d'auto-validation ni d'enchaînement de code non demandé) ; suivi dans `docs/user-stories.md` ; briefs pour outil de design externe sur demande ; **avant de développer une story, vérifier d'abord dans le code si la feature existe déjà** — les docs de stories (`docs/story-nextgen-editor.md`, `docs/user-stories.md`) sont **souvent périmés** (features livrées mais marquées « à faire »).
|
||||
- **Facturation & quotas IA** : limites mensuelles, tiers (BASIC/PRO/BUSINESS/ENTERPRISE) et Price IDs Stripe via **Admin > Facturation & quotas** (`/admin/billing`) — pas via `.env` pour le métier ; secrets Stripe (`STRIPE_SECRET_KEY`, webhook) restent en env serveur ; doc `memento-note/docs/admin-billing-quotas-guide.md`.
|
||||
|
||||
## Learned Workspace Facts
|
||||
@@ -26,6 +26,6 @@
|
||||
- Production : dépôt `/opt/memento` sur `192.168.1.190`, conteneur `memento-note` sur le port **3000**, URL publique **https://memento-note.com** (nginx + Cloudflare ; ancien domaine note.parsanet.org) ; `NEXTAUTH_URL` aligné sur ce domaine ; email sortant via **Resend** (`SMTP_FROM` ex. `noreply@memento-note.com`, domaine vérifié sur resend.com) ; deploy (`deploy.yaml` / `deploy-prod.sh`) **sans toucher Postgres** (pas de `postgresql-client`, pas de migrations auto en prod).
|
||||
- CI/CD Gitea : `.gitea/workflows/ci.yaml` — CI sur `ubuntu-24.04`, deploy sur runner **`docker-host`** (sur le serveur) ; deploy manuel via `.gitea/workflows/deploy.yaml` ou `bash scripts/deploy-prod.sh`.
|
||||
- Migrations prebuilt + vérif deploy : `docker compose exec memento-note node ./node_modules/prisma/build/index.js migrate deploy` (pas `npx prisma`) ; helper `scripts/migrate-docker.sh` ; `GET /api/build-info` (SHA Git) ; comparer `127.0.0.1:3000` et domaine Cloudflare — purger cache si versions divergent ; 403 `/api/manifest` côté domaine = souvent Cloudflare.
|
||||
- Éditeur riche : `rich-text-editor.tsx` — `immediatelyRender: false` ; activer **`shouldRerenderOnTransaction: false`** (quick win perf TipTap 2.5) ; **drag handle / menu bloc** via **`@tiptap/extension-drag-handle-react`** (spec officielle — pas de double plugin `DragHandleExtension` + composant React, pas de repositionnement maison) ; poignée dans **colonne gutter fixe** du wrapper (padding + `getReferencedVirtualElement`), pas sur le bord des listes/numéros ; CSS : **pas `opacity:0` sur `.drag-handle`** (visibilité gérée par le plugin) ; config/callbacks **stables hors composant** ; fondation blocs : `tiptap-unique-id-extension.ts` / **`data-id` persisté à la sauvegarde** (références « Copier la référence ») ; **Smart Paste** : `lib/editor/smart-paste-extension.ts` ; **peek split** note source : `lib/note-peek-sync.ts` + `note-editor-split-peek.tsx` ; **US-4 `structuredViewBlock`** (`tiptap-structured-view-block-extension.tsx`, `structured-view-block-embed.tsx`) : **dual-mode** — base locale autonome par défaut (`/database`, `/vue`, `isLocal: true`) + option « Lier à un carnet » (Structured Views) ; i18n `structuredViewBlock.*` ; **rejeté** : ancien `databaseBlock` « Auteurs & Œuvres » et spec embed-only `docs/story-nextgen-editor-us4-redesign.md` ; epic active `docs/story-nextgen-editor.md` — priorité **PERF > NEXTGEN > UX > MOBILE > MARKDOWN**.
|
||||
- Éditeur riche : `rich-text-editor.tsx` — `immediatelyRender: false` ; activer **`shouldRerenderOnTransaction: false`** (quick win perf TipTap 2.5) ; **drag handle / menu bloc** via **`@tiptap/extension-drag-handle-react`** (spec officielle — pas de double plugin `DragHandleExtension` + composant React, pas de repositionnement maison) ; poignée dans **colonne gutter fixe** du wrapper (padding + `getReferencedVirtualElement`), pas sur le bord des listes/numéros ; CSS : **pas `opacity:0` sur `.drag-handle`** (visibilité gérée par le plugin) ; config/callbacks **stables hors composant** ; fondation blocs : `tiptap-unique-id-extension.ts` / **`data-id` persisté à la sauvegarde** (références « Copier la référence ») ; **Smart Paste** : `lib/editor/smart-paste-extension.ts` ; **peek split** note source : `lib/note-peek-sync.ts` + `note-editor-split-peek.tsx` ; **conversion markdown → texte enrichi** : un **seul** convertisseur `lib/markdown-to-html.ts` (`markdownToHtml`, gfm+breaks) + une **action atomique** `convertToRichText(html)` dans `note-editor-context.tsx` (applique le HTML **immédiatement** via `setContentImmediate` — pas le `setContent` débouncé 800ms — et bascule `isMarkdown=false`) ; toolbar (`handleConvertToRichtext`) **et** chat IA contextuel (`contextual-ai-chat.tsx`, action `toRichText` → `/api/ai/convert-markdown`) passent par cette action unique (ne pas dupliquer la conversion ni oublier de basculer `isMarkdown`) ; **US-4 `structuredViewBlock`** (`tiptap-structured-view-block-extension.tsx`, `structured-view-block-embed.tsx`) : **dual-mode** — base locale autonome par défaut (`/database`, `/vue`, `isLocal: true`) + option « Lier à un carnet » (Structured Views) ; i18n `structuredViewBlock.*` ; **rejeté** : ancien `databaseBlock` « Auteurs & Œuvres » et spec embed-only `docs/story-nextgen-editor-us4-redesign.md` ; epic active `docs/story-nextgen-editor.md` — priorité **PERF > NEXTGEN > UX > MOBILE > MARKDOWN**.
|
||||
- Sync mutations notes entre composants : `memento-note/lib/note-change-sync.ts` (`emitNoteChange`, événement `NOTE_CHANGE_EVENT`) ; tracking quotas IA : événement `ai-usage-changed` (window) — doit être dispatché depuis **tous** les points d'appel IA (recherche sémantique, auto-tag, auto-title, chat, reformulation, analyse carnet, etc.) ; UI quotas : `usage-meter.tsx` (polling 5s + écoute événement).
|
||||
- Roadmap / écart prototype vs prod : Web Clipper — **`ClipperSimulator.tsx` = référence design uniquement** (pas de simulateur en prod) ; extension **`memento-note/extension/`** v0.3 **Side Panel** (clip page/sélection/lien ; popup Chrome se ferme au clic page — Side Panel pour la sélection) ; i18n extension **15 langues** (`_locales/`, détection locale navigateur ; script `extension/i18n/generate-translations.cjs`) ; **`host_permissions`** incl. LAN ; **URL serveur configurable en dev**, adresse prod figée en release ; cookies/session alignés avec l'instance cible ; **Flashcards IA SM-2 livrées** : `/revision`, `/api/flashcards/*`, génération depuis l'éditeur (GraduationCap) — réf. prototype `RevisionView.tsx` ; **Structured Views partiellement livrées** : schéma par carnet, Table/Kanban, champs partagés et valeurs par note (`/home` + toolbar carnet) — **suivi de tâches par carnet via Kanban structuré** (pas de vue agrégée Notes/Tâches sur la home ; cases à cocher inline dans les notes) ; **Living Blocks partiellement livrées** : `data-id`, Smart Paste, nœud `liveBlock`, détacher/supprimer, peek split — **US-NEXTGEN-EDITOR** en cours (`docs/story-nextgen-editor.md`, **US-TEMPORAL reporté**) ; encore en gap : transclusion bidirectionnelle complète, graphe knowledge enrichi (`GraphKnowledgeMap.tsx`), **insights sémantiques** (`InsightsView.tsx`, **`/insights` ≠ `/graph`**) ; publication **Chrome Web Store** : icônes 16/48/128, privacy policy, `host_permissions` prod restreints vs build dev ; **Wizards** : `NotebookOrganizerDialog` (tags/doublons) branché via bouton "Tags IA" dans `home-client.tsx` — `StructuredViewsWizard` encore **orphelin** (pas de point d'entrée UI) ; **Publication web** (`note-editor-toolbar.tsx`) : deux modes — simple (copie directe) + IA (2-3 templates, reformulation adaptée au contenu, KaTeX pour équations, images incluses) — quota IA consommé uniquement sur publication IA ; **champs DB publication** sur modèle `Note` : `publicSlug` (pas `publishedSlug`), `publishedContent` (pas `publishedHtml`) — `publishMode` est paramètre API uniquement (`mode: 'simple' | 'ai'`), **pas** un champ en base.
|
||||
- Roadmap / écart prototype vs prod : Web Clipper — **`ClipperSimulator.tsx` = référence design uniquement** (pas de simulateur en prod) ; extension **`memento-note/extension/`** v0.3 **Side Panel** (clip page/sélection/lien ; popup Chrome se ferme au clic page — Side Panel pour la sélection) ; i18n extension **15 langues** (`_locales/`, détection locale navigateur ; script `extension/i18n/generate-translations.cjs`) ; **`host_permissions`** incl. LAN ; **URL serveur configurable en dev**, adresse prod figée en release ; cookies/session alignés avec l'instance cible ; **Flashcards IA SM-2 livrées** : `/revision`, `/api/flashcards/*`, génération depuis l'éditeur (GraduationCap) — réf. prototype `RevisionView.tsx` ; **Structured Views partiellement livrées** : schéma par carnet, Table/Kanban, champs partagés et valeurs par note (`/home` + toolbar carnet) — **suivi de tâches par carnet via Kanban structuré** (pas de vue agrégée Notes/Tâches sur la home ; cases à cocher inline dans les notes) ; **Éditeur Next-Gen livré** (doc `docs/story-nextgen-editor.md` **périmé** — vérifier le code) : US-1 poignée gutter unique (`editor-block-drag-handle.tsx` + `lib/editor/global-drag-handle-extension.ts`, extension Novel `tiptap-extension-global-drag-handle`), US-2 menu action bloc (`block-action-menu.tsx`), US-3 Smart Paste transclusion (`smart-paste-extension.ts` + `smart-paste-menu.tsx`), US-4 database inline (`structuredViewBlock`), plus `data-id` / `liveBlock` / peek split ; **`/insights` livré** : `app/(main)/insights/page.tsx` + `network-graph.tsx` (clusters sémantiques, bridge notes ; **≠ `/graph`**) ; **US-TEMPORAL reporté** ; encore en gap : transclusion bidirectionnelle complète, graphe knowledge enrichi (`GraphKnowledgeMap.tsx`) ; publication **Chrome Web Store** : icônes 16/48/128, privacy policy, `host_permissions` prod restreints vs build dev ; **Wizards** : `NotebookOrganizerDialog` (tags/doublons) branché via bouton "Tags IA" dans `home-client.tsx` — `StructuredViewsWizard` encore **orphelin** (pas de point d'entrée UI) ; **Publication web** (`note-editor-toolbar.tsx`) : deux modes — simple (copie directe) + IA (2-3 templates, reformulation adaptée au contenu, KaTeX pour équations, images incluses) — quota IA consommé uniquement sur publication IA ; **champs DB publication** sur modèle `Note` : `publicSlug` (pas `publishedSlug`), `publishedContent` (pas `publishedHtml`) — `publishMode` est paramètre API uniquement (`mode: 'simple' | 'ai'`), **pas** un champ en base.
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { Tabs } from 'expo-router'
|
||||
import { BookOpen, Search, Home, User, GraduationCap } from 'lucide-react-native'
|
||||
import { C } from '@/lib/theme'
|
||||
import { t } from '@/lib/i18n'
|
||||
|
||||
export default function TabsLayout() {
|
||||
return (
|
||||
@@ -13,11 +14,11 @@ export default function TabsLayout() {
|
||||
tabBarLabelStyle: { fontSize: 10, fontWeight: '600', marginTop: -2 },
|
||||
}}
|
||||
>
|
||||
<Tabs.Screen name="home" options={{ title: 'Accueil', tabBarIcon: ({ color, size }) => <Home size={size} color={color} /> }} />
|
||||
<Tabs.Screen name="notebooks" options={{ title: 'Carnets', tabBarIcon: ({ color, size }) => <BookOpen size={size} color={color} /> }} />
|
||||
<Tabs.Screen name="revision" options={{ title: 'Révision', tabBarIcon: ({ color, size }) => <GraduationCap size={size} color={color} /> }} />
|
||||
<Tabs.Screen name="search" options={{ title: 'Recherche', tabBarIcon: ({ color, size }) => <Search size={size} color={color} /> }} />
|
||||
<Tabs.Screen name="profile" options={{ title: 'Profil', tabBarIcon: ({ color, size }) => <User size={size} color={color} /> }} />
|
||||
<Tabs.Screen name="home" options={{ title: t('tab.home'), tabBarIcon: ({ color, size }) => <Home size={size} color={color} /> }} />
|
||||
<Tabs.Screen name="notebooks" options={{ title: t('tab.notebooks'), tabBarIcon: ({ color, size }) => <BookOpen size={size} color={color} /> }} />
|
||||
<Tabs.Screen name="revision" options={{ title: t('tab.revision'), tabBarIcon: ({ color, size }) => <GraduationCap size={size} color={color} /> }} />
|
||||
<Tabs.Screen name="search" options={{ title: t('tab.search'), tabBarIcon: ({ color, size }) => <Search size={size} color={color} /> }} />
|
||||
<Tabs.Screen name="profile" options={{ title: t('tab.profile'), tabBarIcon: ({ color, size }) => <User size={size} color={color} /> }} />
|
||||
</Tabs>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -158,7 +158,6 @@ export default function NoteScreen() {
|
||||
const handleEdit = () => {
|
||||
if (!note) return
|
||||
setEditTitle(note.title)
|
||||
setEditContent(htmlToPlainText(note.content ?? ''))
|
||||
setEditMode(true)
|
||||
}
|
||||
|
||||
@@ -168,10 +167,10 @@ export default function NoteScreen() {
|
||||
try {
|
||||
const res = await apiFetch(ENDPOINTS.note(note.id), {
|
||||
method: 'PUT',
|
||||
body: JSON.stringify({ title: editTitle.trim(), content: editContent }),
|
||||
body: JSON.stringify({ title: editTitle.trim() }),
|
||||
})
|
||||
if (!res.ok) throw new Error('Erreur de sauvegarde')
|
||||
setNote((prev) => prev ? { ...prev, title: editTitle.trim(), content: editContent } : prev)
|
||||
setNote((prev) => prev ? { ...prev, title: editTitle.trim() } : prev)
|
||||
setEditMode(false)
|
||||
} catch (e: any) {
|
||||
Alert.alert('Erreur', e.message)
|
||||
@@ -188,7 +187,12 @@ export default function NoteScreen() {
|
||||
|
||||
const handleShare = async () => {
|
||||
if (!note) return
|
||||
await Share.share({ title: note.title, message: `${note.title}\nhttps://memento-note.com` })
|
||||
const publicUrl = note.publicSlug ? `https://memento-note.com/p/${note.publicSlug}` : null
|
||||
const plain = note.content?.replace(/<[^>]+>/g, ' ').replace(/\s+/g, ' ').trim().slice(0, 200) || ''
|
||||
const message = publicUrl
|
||||
? `${note.title}\n\n${plain}...\n\nLire: ${publicUrl}`
|
||||
: `${note.title}\n\n${plain}${plain.length === 200 ? '...' : ''}`
|
||||
await Share.share({ title: note.title, message })
|
||||
}
|
||||
|
||||
const handleDelete = () => {
|
||||
@@ -257,20 +261,21 @@ export default function NoteScreen() {
|
||||
/>
|
||||
)}
|
||||
|
||||
{/* Mode édition */}
|
||||
{/* Mode édition — titre uniquement, contenu preserve HTML */}
|
||||
{note && editMode && (
|
||||
<View style={{ flex: 1 }}>
|
||||
<TextInput value={editTitle} onChangeText={setEditTitle} style={s.editTitle} placeholder="Titre…" placeholderTextColor={C.border} />
|
||||
<TextInput value={editTitle} onChangeText={setEditTitle} style={s.editTitle} placeholder="Titre…" placeholderTextColor={C.border} autoFocus />
|
||||
<View style={s.editDivider} />
|
||||
<TextInput value={editContent} onChangeText={setEditContent} style={s.editContent} placeholder="Contenu…" placeholderTextColor={C.concrete} multiline textAlignVertical="top" scrollEnabled />
|
||||
<View style={{ flex: 1, justifyContent: 'center', alignItems: 'center', paddingHorizontal: 20 }}>
|
||||
<Text style={{ fontSize: 14, color: C.concrete, textAlign: 'center', lineHeight: 22 }}>
|
||||
Le contenu enrichi ne peut pas être édité depuis mobile.{`\n\n`}Utilisez la version web pour modifier le texte.
|
||||
</Text>
|
||||
</View>
|
||||
{/* Barre outils */}
|
||||
<View style={s.toolbar}>
|
||||
<MicButton state={audioState} onPress={handleMic} />
|
||||
{audioState === 'recording'
|
||||
? <Text style={s.recordHint}>● Enregistrement… Appuyez pour arrêter</Text>
|
||||
: <TouchableOpacity onPress={() => setAiSheetOpen(true)} disabled={!editContent.trim()} style={[s.aiBtn, !editContent.trim() && { opacity: 0.35 }]} activeOpacity={0.8}>
|
||||
<Text style={s.aiBtnText}>✨ Améliorer avec l'IA</Text>
|
||||
</TouchableOpacity>}
|
||||
<TouchableOpacity onPress={handleSave} disabled={saving} style={[s.aiBtn, { flex: 1, justifyContent: 'center' }]} activeOpacity={0.8}>
|
||||
<Text style={s.aiBtnText}>{saving ? 'Sauvegarde…' : 'Enregistrer le titre'}</Text>
|
||||
</TouchableOpacity>
|
||||
</View>
|
||||
</View>
|
||||
)}
|
||||
|
||||
@@ -27,7 +27,7 @@ export function TitleSheet({ visible, onClose, content, onSelect }: Props) {
|
||||
if (visible && content.trim()) {
|
||||
fetchTitles()
|
||||
}
|
||||
}, [visible])
|
||||
}, [visible, content])
|
||||
|
||||
const fetchTitles = async () => {
|
||||
setLoading(true)
|
||||
|
||||
176
memento-mobile/lib/i18n.ts
Normal file
176
memento-mobile/lib/i18n.ts
Normal file
@@ -0,0 +1,176 @@
|
||||
import { getLocales } from 'expo-localization'
|
||||
import { I18nManager } from 'react-native'
|
||||
|
||||
export type MobileLang = 'fr' | 'en' | 'fa'
|
||||
|
||||
const translations: Record<MobileLang, Record<string, string>> = {
|
||||
fr: {
|
||||
'tab.home': 'Accueil',
|
||||
'tab.notebooks': 'Carnets',
|
||||
'tab.revision': 'Révision',
|
||||
'tab.search': 'Recherche',
|
||||
'tab.profile': 'Profil',
|
||||
'common.error': 'Erreur',
|
||||
'common.loading': 'Chargement…',
|
||||
'common.save': 'Enregistrer',
|
||||
'common.delete': 'Supprimer',
|
||||
'common.cancel': 'Annuler',
|
||||
'common.search': 'Rechercher',
|
||||
'common.settings': 'Paramètres',
|
||||
'common.logout': 'Déconnexion',
|
||||
'note.title': 'Titre…',
|
||||
'note.contentPlaceholder': 'Contenu…',
|
||||
'note.deleteTitle': 'Supprimer la note',
|
||||
'note.deleteConfirm': 'Voulez-vous vraiment supprimer cette note ?',
|
||||
'note.saveError': 'Erreur de sauvegarde',
|
||||
'note.deleteError': 'Impossible de supprimer la note',
|
||||
'note.dayNote': 'Note du jour',
|
||||
'note.dayNoteError': 'Impossible de charger la note du jour.',
|
||||
'note.editTitleOnly': "Le contenu enrichi ne peut pas être édité depuis mobile. Utilisez la version web pour modifier le texte.",
|
||||
'note.saveTitle': 'Enregistrer le titre',
|
||||
'note.saving': 'Sauvegarde…',
|
||||
'auth.loginFailed': 'Connexion échouée',
|
||||
'auth.googleFailed': 'Connexion Google échouée',
|
||||
'auth.serverError': 'Erreur serveur',
|
||||
'auth.unauthorized': 'Non autorisé',
|
||||
'auth.emailPlaceholder': 'Email',
|
||||
'auth.passwordPlaceholder': 'Mot de passe',
|
||||
'auth.loginButton': 'Se connecter',
|
||||
'auth.orGoogle': 'ou',
|
||||
'revision.title': 'Révision',
|
||||
'revision.empty': 'Aucune carte à réviser',
|
||||
'revision.loadingError': 'Erreur de chargement',
|
||||
'revision.difficult': 'Difficile',
|
||||
'revision.hard': 'Dur',
|
||||
'revision.good': 'Bien',
|
||||
'revision.easy': 'Facile',
|
||||
'profile.title': 'Profil',
|
||||
'search.placeholder': 'Rechercher des notes…',
|
||||
'search.noResults': 'Aucun résultat',
|
||||
'ai.improve': "✨ Améliorer avec l'IA",
|
||||
},
|
||||
en: {
|
||||
'tab.home': 'Home',
|
||||
'tab.notebooks': 'Notebooks',
|
||||
'tab.revision': 'Review',
|
||||
'tab.search': 'Search',
|
||||
'tab.profile': 'Profile',
|
||||
'common.error': 'Error',
|
||||
'common.loading': 'Loading…',
|
||||
'common.save': 'Save',
|
||||
'common.delete': 'Delete',
|
||||
'common.cancel': 'Cancel',
|
||||
'common.search': 'Search',
|
||||
'common.settings': 'Settings',
|
||||
'common.logout': 'Log out',
|
||||
'note.title': 'Title…',
|
||||
'note.contentPlaceholder': 'Content…',
|
||||
'note.deleteTitle': 'Delete note',
|
||||
'note.deleteConfirm': 'Are you sure you want to delete this note?',
|
||||
'note.saveError': 'Save error',
|
||||
'note.deleteError': 'Could not delete the note',
|
||||
'note.dayNote': 'Note of the day',
|
||||
'note.dayNoteError': 'Could not load the note of the day.',
|
||||
'note.editTitleOnly': 'Rich content cannot be edited from mobile. Use the web version to modify the text.',
|
||||
'note.saveTitle': 'Save title',
|
||||
'note.saving': 'Saving…',
|
||||
'auth.loginFailed': 'Login failed',
|
||||
'auth.googleFailed': 'Google sign-in failed',
|
||||
'auth.serverError': 'Server error',
|
||||
'auth.unauthorized': 'Unauthorized',
|
||||
'auth.emailPlaceholder': 'Email',
|
||||
'auth.passwordPlaceholder': 'Password',
|
||||
'auth.loginButton': 'Sign in',
|
||||
'auth.orGoogle': 'or',
|
||||
'revision.title': 'Review',
|
||||
'revision.empty': 'No cards to review',
|
||||
'revision.loadingError': 'Loading error',
|
||||
'revision.difficult': 'Hard',
|
||||
'revision.hard': 'Difficult',
|
||||
'revision.good': 'Good',
|
||||
'revision.easy': 'Easy',
|
||||
'profile.title': 'Profile',
|
||||
'search.placeholder': 'Search notes…',
|
||||
'search.noResults': 'No results',
|
||||
'ai.improve': '✨ Improve with AI',
|
||||
},
|
||||
fa: {
|
||||
'tab.home': 'خانه',
|
||||
'tab.notebooks': 'دفترچهها',
|
||||
'tab.revision': 'مرور',
|
||||
'tab.search': 'جستجو',
|
||||
'tab.profile': 'پروفایل',
|
||||
'common.error': 'خطا',
|
||||
'common.loading': 'در حال بارگذاری…',
|
||||
'common.save': 'ذخیره',
|
||||
'common.delete': 'حذف',
|
||||
'common.cancel': 'انصراف',
|
||||
'common.search': 'جستجو',
|
||||
'common.settings': 'تنظیمات',
|
||||
'common.logout': 'خروج',
|
||||
'note.title': 'عنوان…',
|
||||
'note.contentPlaceholder': 'محتوا…',
|
||||
'note.deleteTitle': 'حذف یادداشت',
|
||||
'note.deleteConfirm': 'آیا از حذف این یادداشت مطمئن هستید؟',
|
||||
'note.saveError': 'خطای ذخیرهسازی',
|
||||
'note.deleteError': 'حذف یادداشت امکانپذیر نیست',
|
||||
'note.dayNote': 'یادداشت روز',
|
||||
'note.dayNoteError': 'بارگذاری یادداشت روز امکانپذیر نیست.',
|
||||
'note.editTitleOnly': 'محتوای غنی از موبایل قابل ویرایش نیست. برای ویرایش متن از نسخه وب استفاده کنید.',
|
||||
'note.saveTitle': 'ذخیره عنوان',
|
||||
'note.saving': 'در حال ذخیره…',
|
||||
'auth.loginFailed': 'ورود ناموفق',
|
||||
'auth.googleFailed': 'ورود با گوگل ناموفق',
|
||||
'auth.serverError': 'خطای سرور',
|
||||
'auth.unauthorized': 'غیر مجاز',
|
||||
'auth.emailPlaceholder': 'ایمیل',
|
||||
'auth.passwordPlaceholder': 'رمز عبور',
|
||||
'auth.loginButton': 'ورود',
|
||||
'auth.orGoogle': 'یا',
|
||||
'revision.title': 'مرور',
|
||||
'revision.empty': 'کارت مروری موجود نیست',
|
||||
'revision.loadingError': 'خطای بارگذاری',
|
||||
'revision.difficult': 'سخت',
|
||||
'revision.hard': 'دشوار',
|
||||
'revision.good': 'خوب',
|
||||
'revision.easy': 'آسان',
|
||||
'profile.title': 'پروفایل',
|
||||
'search.placeholder': 'جستجوی یادداشت…',
|
||||
'search.noResults': 'نتیجهای یافت نشد',
|
||||
'ai.improve': '✨ بهبود با هوش مصنوعی',
|
||||
},
|
||||
}
|
||||
|
||||
const RTL_LANGS: MobileLang[] = ['fa', 'ar']
|
||||
|
||||
function detectLang(): MobileLang {
|
||||
try {
|
||||
const locales = getLocales()
|
||||
const lang = locales[0]?.languageCode ?? 'fr'
|
||||
if (lang === 'fa') return 'fa'
|
||||
if (lang === 'en') return 'en'
|
||||
return 'fr'
|
||||
} catch {
|
||||
return 'fr'
|
||||
}
|
||||
}
|
||||
|
||||
let currentLang: MobileLang = detectLang()
|
||||
|
||||
export function setLang(lang: MobileLang) {
|
||||
currentLang = lang
|
||||
const isRtl = RTL_LANGS.includes(lang)
|
||||
I18nManager.forceRTL(isRtl)
|
||||
}
|
||||
|
||||
export function isRTL(): boolean {
|
||||
return RTL_LANGS.includes(currentLang)
|
||||
}
|
||||
|
||||
export function getLang(): MobileLang {
|
||||
return currentLang
|
||||
}
|
||||
|
||||
export function t(key: string): string {
|
||||
return translations[currentLang]?.[key] ?? translations.fr[key] ?? translations.en[key] ?? key
|
||||
}
|
||||
@@ -43,6 +43,7 @@ export const useAuthStore = create<AuthState>((set) => ({
|
||||
},
|
||||
|
||||
logout: async () => {
|
||||
try { await apiFetch(ENDPOINTS.logout, { method: 'POST' }) } catch {}
|
||||
await clearToken()
|
||||
set({ user: null })
|
||||
},
|
||||
|
||||
@@ -6,7 +6,13 @@ export const C = {
|
||||
concrete: '#8A8A82',
|
||||
border: '#E8E6E0',
|
||||
white: '#FFFFFF',
|
||||
surface: '#F5F4F0',
|
||||
rose: '#e11d48',
|
||||
roseBg: '#fff1f2',
|
||||
roseBorder: '#fecdd3',
|
||||
emerald: '#10b981',
|
||||
emeraldBg: '#ecfdf5',
|
||||
blue: '#3b82f6',
|
||||
amber: '#f59e0b',
|
||||
purple: '#8b5cf6',
|
||||
}
|
||||
|
||||
@@ -25,6 +25,7 @@ import {
|
||||
} from 'lucide-react'
|
||||
import { toast } from 'sonner'
|
||||
import Link from 'next/link'
|
||||
import { useNotePeek, NotePeekPanel } from '@/components/note-peek'
|
||||
|
||||
const NetworkGraph = dynamic(
|
||||
() => import('@/components/network-graph').then(m => ({ default: m.NetworkGraph })),
|
||||
@@ -99,6 +100,7 @@ export default function InsightsPage() {
|
||||
const [viewMode, setViewMode] = useState<'graph' | 'dashboard'>('dashboard')
|
||||
const [graphMode, setGraphMode] = useState<'visual' | 'list'>('visual')
|
||||
const [lastSyncTime, setLastSyncTime] = useState<string>('')
|
||||
const peek = useNotePeek()
|
||||
const prefersReducedMotion = useReducedMotion()
|
||||
|
||||
useEffect(() => {
|
||||
@@ -258,9 +260,11 @@ export default function InsightsPage() {
|
||||
}
|
||||
|
||||
const handleNoteClick = (noteId: string) => {
|
||||
router.push(`/home?openNote=${noteId}`)
|
||||
peek.open(noteId)
|
||||
}
|
||||
|
||||
const isRtl = locale === 'fa' || locale === 'ar'
|
||||
|
||||
const motionConfig = prefersReducedMotion
|
||||
? { initial: false as const, animate: { opacity: 1, y: 0 }, transition: { duration: 0 } }
|
||||
: {}
|
||||
@@ -274,9 +278,9 @@ export default function InsightsPage() {
|
||||
<div className="p-6 sm:p-8 border-b border-border/20 flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between sticky top-0 bg-[#F9F8F6]/80 dark:bg-[#0D0D0D]/80 backdrop-blur-md z-30 shrink-0">
|
||||
<div className="flex items-center gap-4">
|
||||
<button
|
||||
className="lg:hidden p-2 -ms-1 text-foreground hover:bg-foreground/5 rounded-lg transition-colors shrink-0 cursor-pointer focus-visible:ring-2 focus-visible:ring-ochre/50 focus-visible:outline-none"
|
||||
onClick={() => window.dispatchEvent(new CustomEvent('open-mobile-sidebar'))}
|
||||
aria-label={t('sidebar.openNavigation') || 'Open navigation'}
|
||||
className="p-2 -ms-1 text-foreground hover:bg-foreground/5 rounded-lg transition-colors shrink-0 cursor-pointer focus-visible:ring-2 focus-visible:ring-ochre/50 focus-visible:outline-none"
|
||||
onClick={() => window.dispatchEvent(new CustomEvent('toggle-insights-sidebar'))}
|
||||
aria-label="Toggle sidebar"
|
||||
>
|
||||
<Menu size={22} />
|
||||
</button>
|
||||
@@ -868,6 +872,16 @@ export default function InsightsPage() {
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* ── Peek panel (factorisé) ── */}
|
||||
<NotePeekPanel
|
||||
note={peek.note}
|
||||
blockId={peek.blockId}
|
||||
loading={peek.loading}
|
||||
mode="overlay"
|
||||
onClose={peek.close}
|
||||
onOpenFully={(n) => { router.push(`/home?openNote=${n.id}`); peek.close() }}
|
||||
/>
|
||||
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -37,11 +37,14 @@ export default async function MainLayout({
|
||||
>
|
||||
{/* No top-bar header — sidebar-only navigation (architectural-grid design) */}
|
||||
<div className="flex h-screen overflow-hidden bg-memento-desk dark:bg-background">
|
||||
<Suspense fallback={<div className="hidden w-80 shrink-0 md:block" />}>
|
||||
<Suspense fallback={<div className="hidden w-80 md:w-[26rem] 2xl:w-[30rem] shrink-0 md:block h-full self-stretch" />}>
|
||||
<Sidebar user={session?.user} />
|
||||
</Suspense>
|
||||
|
||||
<main className="flex min-h-0 flex-1 flex-col overflow-y-auto scroll-smooth bg-memento-paper dark:bg-background">
|
||||
<main className="flex min-h-0 flex-1 flex-col overflow-y-auto scroll-smooth bg-memento-paper dark:bg-background" id="main-content">
|
||||
<a href="#main-content" className="sr-only focus:not-sr-only focus:absolute focus:z-[9999] focus:top-2 focus:left-2 focus:bg-brand-accent focus:text-white focus:px-4 focus:py-2 focus:rounded-lg focus:text-sm focus:font-bold">
|
||||
Skip to content
|
||||
</a>
|
||||
{children}
|
||||
</main>
|
||||
|
||||
|
||||
@@ -1,11 +1,13 @@
|
||||
'use client'
|
||||
|
||||
import { useState, useEffect } from 'react'
|
||||
import { BookOpen, Loader2, Check, X, RefreshCw, Trash2, CalendarDays } from 'lucide-react'
|
||||
import { BookOpen, Loader2, Check, X, RefreshCw, Trash2, CalendarDays, Mail } from 'lucide-react'
|
||||
import { toast } from 'sonner'
|
||||
import { SettingsHelpBox } from '@/components/settings/settings-help-box'
|
||||
import { useLanguage } from '@/lib/i18n'
|
||||
|
||||
export default function IntegrationsPage() {
|
||||
const { t } = useLanguage()
|
||||
// ── Readwise ───────────────────────────────────────────────────────────
|
||||
const [rwToken, setRwToken] = useState('')
|
||||
const [rwConnected, setRwConnected] = useState(false)
|
||||
@@ -19,32 +21,47 @@ export default function IntegrationsPage() {
|
||||
const [calEvents, setCalEvents] = useState<any[]>([])
|
||||
const [calFetching, setCalFetching] = useState(false)
|
||||
|
||||
// ── Gmail ────────────────────────────────────────────────────────────
|
||||
const [gmailConnected, setGmailConnected] = useState(false)
|
||||
const [gmailLoading, setGmailLoading] = useState(true)
|
||||
const [gmailRecent, setGmailRecent] = useState(0)
|
||||
const [gmailScanning, setGmailScanning] = useState(false)
|
||||
|
||||
const [loading, setLoading] = useState(true)
|
||||
|
||||
useEffect(() => {
|
||||
Promise.all([
|
||||
fetch('/api/integrations/readwise').then((r) => r.json()),
|
||||
fetch('/api/integrations/calendar').then((r) => r.json()),
|
||||
]).then(([rw, cal]) => {
|
||||
fetch('/api/integrations/gmail').then((r) => r.json()),
|
||||
]).then(([rw, cal, gmail]) => {
|
||||
setRwConnected(rw.connected)
|
||||
setCalConnected(cal.connected)
|
||||
setGmailConnected(gmail.connected)
|
||||
setGmailRecent(gmail.recentCaptures ?? 0)
|
||||
}).finally(() => {
|
||||
setLoading(false)
|
||||
setCalLoading(false)
|
||||
setGmailLoading(false)
|
||||
})
|
||||
|
||||
// Handle redirect params
|
||||
const params = new URLSearchParams(window.location.search)
|
||||
if (params.get('connected') === 'calendar') {
|
||||
setCalConnected(true)
|
||||
toast.success('Google Calendar connecté !')
|
||||
toast.success(t('integrations.calendarConnected'))
|
||||
window.history.replaceState({}, '', '/settings/integrations')
|
||||
}
|
||||
if (params.get('connected') === 'gmail') {
|
||||
setGmailConnected(true)
|
||||
toast.success(t('integrations.gmail.connected'))
|
||||
window.history.replaceState({}, '', '/settings/integrations')
|
||||
}
|
||||
if (params.get('error')) {
|
||||
toast.error(`Erreur: ${params.get('error')}`)
|
||||
toast.error(t('integrations.errorWith', { error: params.get('error') || '' }))
|
||||
window.history.replaceState({}, '', '/settings/integrations')
|
||||
}
|
||||
}, [])
|
||||
}, [t])
|
||||
|
||||
// ── Readwise handlers ──────────────────────────────────────────────────
|
||||
const handleRwConnect = async () => {
|
||||
@@ -57,12 +74,12 @@ export default function IntegrationsPage() {
|
||||
body: JSON.stringify({ token: rwToken.trim() }),
|
||||
})
|
||||
const data = await res.json()
|
||||
if (!res.ok) { toast.error(data.error || 'Erreur Readwise'); return }
|
||||
if (!res.ok) { toast.error(data.error || t('integrations.readwiseError')); return }
|
||||
setRwConnected(true)
|
||||
setRwToken('')
|
||||
setRwLastSync({ created: data.created, updated: data.updated })
|
||||
toast.success(`Readwise connecté — ${data.created} notes créées, ${data.updated} mises à jour`)
|
||||
} catch { toast.error('Erreur de connexion Readwise') } finally { setRwConnecting(false) }
|
||||
toast.success(t('integrations.readwiseConnected', { created: data.created, updated: data.updated }))
|
||||
} catch { toast.error(t('integrations.readwiseConnectError')) } finally { setRwConnecting(false) }
|
||||
}
|
||||
|
||||
const handleRwSync = async () => {
|
||||
@@ -74,16 +91,16 @@ export default function IntegrationsPage() {
|
||||
body: JSON.stringify({}),
|
||||
})
|
||||
const data = await res.json()
|
||||
if (!res.ok) { toast.error(data.error || 'Erreur de sync'); return }
|
||||
if (!res.ok) { toast.error(data.error || t('integrations.syncError')); return }
|
||||
setRwLastSync({ created: data.created, updated: data.updated })
|
||||
toast.success(`Sync Readwise — ${data.created} créées, ${data.updated} mises à jour`)
|
||||
} catch { toast.error('Erreur de synchronisation') } finally { setRwSyncing(false) }
|
||||
toast.success(t('integrations.readwiseSynced', { created: data.created, updated: data.updated }))
|
||||
} catch { toast.error(t('integrations.syncFailed')) } finally { setRwSyncing(false) }
|
||||
}
|
||||
|
||||
const handleRwDisconnect = async () => {
|
||||
await fetch('/api/integrations/readwise', { method: 'DELETE' })
|
||||
setRwConnected(false)
|
||||
toast.success('Readwise déconnecté')
|
||||
toast.success(t('integrations.readwiseDisconnected'))
|
||||
}
|
||||
|
||||
// ── Calendar handlers ──────────────────────────────────────────────────
|
||||
@@ -96,10 +113,10 @@ export default function IntegrationsPage() {
|
||||
try {
|
||||
const res = await fetch('/api/integrations/calendar?events=1')
|
||||
const data = await res.json()
|
||||
if (!res.ok) { toast.error(data.error || 'Erreur'); return }
|
||||
if (!res.ok) { toast.error(data.error || t('common.error')); return }
|
||||
setCalEvents(data.events ?? [])
|
||||
if (data.events.length === 0) toast.info('Aucun événement aujourd\'hui')
|
||||
} catch { toast.error('Erreur de chargement des événements') } finally { setCalFetching(false) }
|
||||
if (data.events.length === 0) toast.info(t('integrations.noEvents'))
|
||||
} catch { toast.error(t('integrations.eventsLoadError')) } finally { setCalFetching(false) }
|
||||
}
|
||||
|
||||
const handleCreateMeetingNote = async (event: any) => {
|
||||
@@ -110,11 +127,11 @@ export default function IntegrationsPage() {
|
||||
})
|
||||
const data = await res.json()
|
||||
if (data.success) {
|
||||
toast.success(`Note de réunion créée : ${event.summary}`, {
|
||||
action: { label: 'Ouvrir', onClick: () => window.location.href = `/home?openNote=${data.note.id}` },
|
||||
toast.success(t('integrations.meetingNoteCreated', { summary: event.summary }), {
|
||||
action: { label: t('integrations.open'), onClick: () => window.location.href = `/home?openNote=${data.note.id}` },
|
||||
})
|
||||
} else {
|
||||
toast.error('Erreur lors de la création de la note')
|
||||
toast.error(t('integrations.createNoteError'))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -122,25 +139,114 @@ export default function IntegrationsPage() {
|
||||
await fetch('/api/integrations/calendar', { method: 'DELETE' })
|
||||
setCalConnected(false)
|
||||
setCalEvents([])
|
||||
toast.success('Google Calendar déconnecté')
|
||||
toast.success(t('integrations.calendarDisconnected'))
|
||||
}
|
||||
|
||||
// ── Gmail handlers ─────────────────────────────────────────────────────
|
||||
const handleGmailConnect = () => {
|
||||
window.location.href = '/api/integrations/gmail?connect=1'
|
||||
}
|
||||
|
||||
const handleGmailScan = async () => {
|
||||
setGmailScanning(true)
|
||||
try {
|
||||
const res = await fetch('/api/integrations/gmail?scan=1')
|
||||
const data = await res.json()
|
||||
if (!res.ok) { toast.error(data.error || t('common.error')); return }
|
||||
setGmailRecent(prev => prev + (data.created ?? 0))
|
||||
toast.success(t('integrations.gmail.scanDone', { created: data.created ?? 0 }))
|
||||
} catch {
|
||||
toast.error(t('integrations.gmailScanError'))
|
||||
} finally {
|
||||
setGmailScanning(false)
|
||||
}
|
||||
}
|
||||
|
||||
const handleGmailDisconnect = async () => {
|
||||
await fetch('/api/integrations/gmail', { method: 'DELETE' })
|
||||
setGmailConnected(false)
|
||||
setGmailRecent(0)
|
||||
toast.success(t('integrations.gmail.disconnected'))
|
||||
}
|
||||
|
||||
const StatusBadge = ({ connected }: { connected: boolean }) =>
|
||||
connected ? (
|
||||
<span className="flex items-center gap-1.5 text-[11px] font-semibold text-emerald-700 dark:text-emerald-300 bg-emerald-50 dark:bg-emerald-950/40 border border-emerald-200 dark:border-emerald-800/50 rounded-full px-2.5 py-1">
|
||||
<Check size={11} /> Connecté
|
||||
<Check size={11} /> {t('integrations.connected')}
|
||||
</span>
|
||||
) : (
|
||||
<span className="flex items-center gap-1.5 text-[11px] font-semibold text-concrete bg-border/20 border border-border/40 rounded-full px-2.5 py-1">
|
||||
<X size={11} /> Non connecté
|
||||
<X size={11} /> {t('integrations.notConnected')}
|
||||
</span>
|
||||
)
|
||||
|
||||
return (
|
||||
<div className="space-y-8">
|
||||
<div>
|
||||
<h2 className="text-2xl font-serif font-medium text-ink italic tracking-tight">Intégrations</h2>
|
||||
<p className="text-sm text-concrete mt-1">Connectez des services externes à Memento.</p>
|
||||
<h2 className="text-2xl font-serif font-medium text-ink italic tracking-tight">{t('settings.integrationsTitle')}</h2>
|
||||
<p className="text-sm text-concrete mt-1">{t('settings.integrationsDesc')}</p>
|
||||
</div>
|
||||
|
||||
{/* ── Gmail ──────────────────────────────────────────────────────── */}
|
||||
<div className="border border-border/40 rounded-2xl p-6 bg-paper space-y-4">
|
||||
<div className="flex items-start justify-between gap-4">
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="w-10 h-10 rounded-xl bg-red-100 dark:bg-red-900/30 flex items-center justify-center">
|
||||
<Mail size={20} className="text-red-600 dark:text-red-400" />
|
||||
</div>
|
||||
<div>
|
||||
<h3 className="font-semibold text-ink text-sm">{t('integrations.gmail.title')}</h3>
|
||||
<p className="text-[12px] text-concrete">{t('integrations.gmail.description')}</p>
|
||||
</div>
|
||||
</div>
|
||||
{gmailLoading ? <Loader2 size={16} className="animate-spin text-concrete mt-2" /> : <StatusBadge connected={gmailConnected} />}
|
||||
</div>
|
||||
|
||||
{!gmailConnected ? (
|
||||
<div className="space-y-3">
|
||||
<SettingsHelpBox
|
||||
title={t('integrations.gmail.helpTitle')}
|
||||
steps={[
|
||||
{ text: t('integrations.gmail.helpStep1') },
|
||||
{ text: t('integrations.gmail.helpStep2') },
|
||||
{ text: t('integrations.gmail.helpStep3') },
|
||||
{ text: t('integrations.gmail.helpStep4') },
|
||||
]}
|
||||
/>
|
||||
<button
|
||||
onClick={handleGmailConnect}
|
||||
className="px-4 py-2 text-sm font-semibold bg-ink text-paper rounded-xl hover:bg-ink/80 transition-all flex items-center gap-2"
|
||||
>
|
||||
<Mail size={14} />
|
||||
{t('integrations.gmail.connect')}
|
||||
</button>
|
||||
</div>
|
||||
) : (
|
||||
<div className="space-y-3">
|
||||
<div className="flex flex-wrap gap-2">
|
||||
<button
|
||||
onClick={handleGmailScan}
|
||||
disabled={gmailScanning}
|
||||
className="flex items-center gap-2 px-4 py-2 text-sm font-semibold border border-border/40 rounded-xl hover:bg-ink/5 transition-all disabled:opacity-50"
|
||||
>
|
||||
{gmailScanning ? <Loader2 size={14} className="animate-spin" /> : <RefreshCw size={14} />}
|
||||
{t('integrations.gmail.scanNow')}
|
||||
</button>
|
||||
<button
|
||||
onClick={handleGmailDisconnect}
|
||||
className="flex items-center gap-2 px-4 py-2 text-sm font-semibold text-rose-600 dark:text-rose-400 border border-rose-200 dark:border-rose-800/40 rounded-xl hover:bg-rose-50 dark:hover:bg-rose-950/20 transition-all"
|
||||
>
|
||||
<Trash2 size={14} />
|
||||
{t('integrations.gmail.disconnect')}
|
||||
</button>
|
||||
</div>
|
||||
{gmailRecent > 0 && (
|
||||
<p className="text-[11px] text-concrete">
|
||||
{t('integrations.gmail.recentCaptures', { count: gmailRecent })}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* ── Google Calendar ────────────────────────────────────────────── */}
|
||||
@@ -152,7 +258,7 @@ export default function IntegrationsPage() {
|
||||
</div>
|
||||
<div>
|
||||
<h3 className="font-semibold text-ink text-sm">Google Calendar</h3>
|
||||
<p className="text-[12px] text-concrete">Accédez à vos événements et créez des notes de réunion</p>
|
||||
<p className="text-[12px] text-concrete">{t('integrations.calendarDesc')}</p>
|
||||
</div>
|
||||
</div>
|
||||
{calLoading ? <Loader2 size={16} className="animate-spin text-concrete mt-2" /> : <StatusBadge connected={calConnected} />}
|
||||
@@ -161,12 +267,12 @@ export default function IntegrationsPage() {
|
||||
{!calConnected ? (
|
||||
<div className="space-y-3">
|
||||
<SettingsHelpBox
|
||||
title="Comment fonctionne Google Calendar ?"
|
||||
title={t('integrations.calendarInfo')}
|
||||
steps={[
|
||||
{ text: 'Cliquez "Connecter Google Calendar" — vous serez redirigé vers Google pour autoriser l\'accès.' },
|
||||
{ text: 'Une fois connecté, revenez ici et cliquez "Événements aujourd\'hui" pour voir votre agenda.' },
|
||||
{ text: 'Sur chaque événement, cliquez "+ Note" pour créer automatiquement une note de réunion avec template (Ordre du jour / Notes / Actions).' },
|
||||
{ text: 'La note s\'ouvre directement dans Memento — ajoutez vos notes en temps réel pendant la réunion.' },
|
||||
{ text: t('integrations.calendarHelpStep1') },
|
||||
{ text: t('integrations.calendarHelpStep2') },
|
||||
{ text: t('integrations.calendarHelpStep3') },
|
||||
{ text: t('integrations.calendarHelpStep4') },
|
||||
]}
|
||||
/>
|
||||
<button
|
||||
@@ -174,7 +280,7 @@ export default function IntegrationsPage() {
|
||||
className="px-4 py-2 text-sm font-semibold bg-ink text-paper rounded-xl hover:bg-ink/80 transition-all flex items-center gap-2"
|
||||
>
|
||||
<CalendarDays size={14} />
|
||||
Connecter Google Calendar
|
||||
{t('integrations.connectCalendar')}
|
||||
</button>
|
||||
</div>
|
||||
) : (
|
||||
@@ -186,14 +292,14 @@ export default function IntegrationsPage() {
|
||||
className="flex items-center gap-2 px-4 py-2 text-sm font-semibold border border-border/40 rounded-xl hover:bg-ink/5 transition-all disabled:opacity-50"
|
||||
>
|
||||
{calFetching ? <Loader2 size={14} className="animate-spin" /> : <CalendarDays size={14} />}
|
||||
Événements aujourd'hui
|
||||
{t('integrations.todayEvents')}
|
||||
</button>
|
||||
<button
|
||||
onClick={handleCalDisconnect}
|
||||
className="flex items-center gap-2 px-4 py-2 text-sm font-semibold text-rose-600 dark:text-rose-400 border border-rose-200 dark:border-rose-800/40 rounded-xl hover:bg-rose-50 dark:hover:bg-rose-950/20 transition-all"
|
||||
>
|
||||
<Trash2 size={14} />
|
||||
Déconnecter
|
||||
{t('integrations.disconnect')}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
@@ -211,7 +317,7 @@ export default function IntegrationsPage() {
|
||||
onClick={() => handleCreateMeetingNote(ev)}
|
||||
className="shrink-0 text-[11px] font-semibold px-3 py-1.5 border border-border/40 rounded-full hover:bg-ink/5 transition-all"
|
||||
>
|
||||
+ Note
|
||||
{t('integrations.addNote')}
|
||||
</button>
|
||||
</div>
|
||||
))}
|
||||
@@ -230,20 +336,20 @@ export default function IntegrationsPage() {
|
||||
</div>
|
||||
<div>
|
||||
<h3 className="font-semibold text-ink text-sm">Readwise</h3>
|
||||
<p className="text-[12px] text-concrete">Importez vos surlignages de livres, articles et Kindle</p>
|
||||
<p className="text-[12px] text-concrete">{t('integrations.readwiseDesc')}</p>
|
||||
</div>
|
||||
</div>
|
||||
{loading ? <Loader2 size={16} className="animate-spin text-concrete mt-2" /> : <StatusBadge connected={rwConnected} />}
|
||||
</div>
|
||||
|
||||
<SettingsHelpBox
|
||||
title="Comment fonctionne Readwise ?"
|
||||
title={t('integrations.readwiseInfo')}
|
||||
steps={[
|
||||
{ text: 'Copiez votre token d\'accès Readwise.', link: { label: 'readwise.io/access_token', href: 'https://readwise.io/access_token' } },
|
||||
{ text: 'Collez-le dans le champ ci-dessous et cliquez "Connecter". La première synchronisation importe tous vos livres et articles.' },
|
||||
{ text: 'Chaque livre devient une note dans un carnet "Readwise 📚" — avec tous vos surlignages organisés.' },
|
||||
{ text: 'Pour mettre à jour avec de nouveaux surlignages, revenez ici et cliquez "Synchroniser maintenant".' },
|
||||
{ icon: '💡', text: 'Astuce : créez des flashcards IA depuis une note Readwise (bouton 🎓 dans l\'éditeur) pour réviser vos lectures.' },
|
||||
{ text: t('integrations.readwiseHelpStep1'), link: { label: 'readwise.io/access_token', href: 'https://readwise.io/access_token' } },
|
||||
{ text: t('integrations.readwiseHelpStep2') },
|
||||
{ text: t('integrations.readwiseHelpStep3') },
|
||||
{ text: t('integrations.readwiseHelpStep4') },
|
||||
{ icon: '💡', text: t('integrations.readwiseHelpStep5') },
|
||||
]}
|
||||
/>
|
||||
|
||||
@@ -254,7 +360,7 @@ export default function IntegrationsPage() {
|
||||
type="password"
|
||||
value={rwToken}
|
||||
onChange={(e) => setRwToken(e.target.value)}
|
||||
placeholder="Token Readwise…"
|
||||
placeholder={t('integrations.readwiseTokenPlaceholder')}
|
||||
className="flex-1 text-sm border border-border/40 rounded-xl px-3 py-2 bg-paper text-ink placeholder:text-concrete/50 focus:outline-none focus:ring-1 focus:ring-brand-accent/40"
|
||||
onKeyDown={(e) => e.key === 'Enter' && handleRwConnect()}
|
||||
/>
|
||||
@@ -264,7 +370,7 @@ export default function IntegrationsPage() {
|
||||
className="px-4 py-2 text-sm font-semibold bg-ink text-paper rounded-xl hover:bg-ink/80 transition-all disabled:opacity-50 flex items-center gap-2"
|
||||
>
|
||||
{rwConnecting ? <Loader2 size={14} className="animate-spin" /> : null}
|
||||
Connecter
|
||||
{t('integrations.connect')}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
@@ -278,28 +384,28 @@ export default function IntegrationsPage() {
|
||||
className="flex items-center gap-2 px-4 py-2 text-sm font-semibold border border-border/40 rounded-xl hover:bg-ink/5 transition-all disabled:opacity-50"
|
||||
>
|
||||
{rwSyncing ? <Loader2 size={14} className="animate-spin" /> : <RefreshCw size={14} />}
|
||||
Synchroniser maintenant
|
||||
{t('integrations.syncNow')}
|
||||
</button>
|
||||
<button
|
||||
onClick={handleRwDisconnect}
|
||||
className="flex items-center gap-2 px-4 py-2 text-sm font-semibold text-rose-600 dark:text-rose-400 border border-rose-200 dark:border-rose-800/40 rounded-xl hover:bg-rose-50 dark:hover:bg-rose-950/20 transition-all"
|
||||
>
|
||||
<Trash2 size={14} />
|
||||
Déconnecter
|
||||
{t('integrations.disconnect')}
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{rwLastSync && (
|
||||
<p className="text-[11px] text-concrete">
|
||||
Dernière sync : <strong>{rwLastSync.created}</strong> notes créées, <strong>{rwLastSync.updated}</strong> mises à jour
|
||||
{t('integrations.lastSync')} <strong>{rwLastSync.created}</strong> {t('integrations.createdLabel')}, <strong>{rwLastSync.updated}</strong> {t('integrations.updatedLabel')}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Placeholder */}
|
||||
<div className="border border-dashed border-border/40 rounded-2xl p-6 text-center">
|
||||
<p className="text-sm text-concrete italic">D'autres intégrations arrivent bientôt — Zapier, GitHub, Notion import…</p>
|
||||
<p className="text-sm text-concrete italic">{t('integrations.moreComing')}</p>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
|
||||
@@ -17,7 +17,6 @@ import {
|
||||
} from 'lucide-react'
|
||||
import { Note, Notebook } from '@/lib/types'
|
||||
import { restoreNote, permanentDeleteNote, emptyTrash } from '@/app/actions/notes'
|
||||
import { restoreNotebook, permanentDeleteNotebook } from '@/context/notebooks-context'
|
||||
import { useLanguage } from '@/lib/i18n'
|
||||
import { toast } from 'sonner'
|
||||
import { useNotebooks } from '@/context/notebooks-context'
|
||||
|
||||
@@ -101,7 +101,7 @@ export async function updateAISettings(settings: UserAISettingsData) {
|
||||
revalidatePath('/settings/ai', 'page')
|
||||
revalidatePath('/settings/appearance', 'page')
|
||||
revalidatePath('/', 'layout')
|
||||
revalidateTag('ai-settings')
|
||||
revalidateTag('ai-settings', 'default')
|
||||
|
||||
return { success: true }
|
||||
} catch (error) {
|
||||
|
||||
@@ -472,7 +472,6 @@ export async function createNote(data: {
|
||||
const autoLabelingEnabled = userAISettings.autoLabeling !== false
|
||||
const autoLabelingConfidence = await getConfigNumber('AUTO_LABELING_CONFIDENCE_THRESHOLD', 70)
|
||||
|
||||
// console.log('[BG] Auto-labeling check: enabled=', autoLabelingEnabled, 'confidence=', autoLabelingConfidence, 'notebookId=', notebookId)
|
||||
|
||||
if (autoLabelingEnabled) {
|
||||
// Detect user's language from their existing notes for localized prompts
|
||||
@@ -497,7 +496,6 @@ export async function createNote(data: {
|
||||
userLang
|
||||
)
|
||||
|
||||
// console.log('[BG] Auto-labeling suggestions:', suggestions.length, suggestions.map(s => s.label))
|
||||
|
||||
const appliedLabels = suggestions
|
||||
.filter(s => s.confidence >= autoLabelingConfidence)
|
||||
@@ -531,7 +529,6 @@ export async function createNote(data: {
|
||||
console.error('[BG] Auto-labeling failed:', error)
|
||||
}
|
||||
} else {
|
||||
// console.log('[BG] Auto-labeling skipped: hasUserLabels=', hasUserLabels, 'notebookId=', notebookId)
|
||||
}
|
||||
})().catch(e => console.error('[BG] Uncaught background error:', e))
|
||||
|
||||
@@ -632,14 +629,12 @@ export async function updateNote(id: string, data: {
|
||||
updateData.contentUpdatedAt = new Date()
|
||||
}
|
||||
|
||||
// console.log('[updateNote] Attempting update, id:', id, 'userId:', session.user.id)
|
||||
let note
|
||||
try {
|
||||
note = await prisma.note.update({
|
||||
where: { id, userId: session.user.id },
|
||||
data: updateData
|
||||
})
|
||||
// console.log('[updateNote] Succeeded, note id:', note?.id)
|
||||
} catch (dbError: any) {
|
||||
console.error('[updateNote] FAILED:', dbError.code, dbError.message)
|
||||
throw dbError
|
||||
@@ -693,7 +688,6 @@ export async function updateNote(id: string, data: {
|
||||
const structuralFields = ['isPinned', 'isArchived', 'labels', 'notebookId']
|
||||
const isStructuralChange = structuralFields.some(field => field in data)
|
||||
|
||||
// console.log('[updateNote] Structural check — data fields:', Object.keys(data), '| isStructural:', isStructuralChange)
|
||||
|
||||
if (!options?.skipRevalidation) {
|
||||
try { revalidatePath(`/note/${id}`) } catch {}
|
||||
@@ -952,17 +946,25 @@ export async function syncAllEmbeddings() {
|
||||
userId,
|
||||
trashedAt: null,
|
||||
noteEmbedding: { is: null }
|
||||
}
|
||||
},
|
||||
take: 200,
|
||||
})
|
||||
for (const note of notesToSync) {
|
||||
if (!note.content) continue;
|
||||
|
||||
const BATCH_SIZE = 5;
|
||||
for (let i = 0; i < notesToSync.length; i += BATCH_SIZE) {
|
||||
const batch = notesToSync.slice(i, i + BATCH_SIZE);
|
||||
await Promise.allSettled(batch.map(async (note) => {
|
||||
if (!note.content) return;
|
||||
try {
|
||||
const { embedding } = await embeddingService.generateNoteEmbedding(note.title, note.content)
|
||||
if (embedding) {
|
||||
await upsertNoteEmbedding(note.id, embedding)
|
||||
updatedCount++;
|
||||
}
|
||||
} catch (e) { }
|
||||
} catch (e) {
|
||||
console.error(`[syncEmbeddings] Failed for note ${note.id}:`, e)
|
||||
}
|
||||
}));
|
||||
}
|
||||
return { success: true, count: updatedCount }
|
||||
} catch (error: any) {
|
||||
@@ -1080,6 +1082,27 @@ export async function getRecentNotes(limit: number = 3) {
|
||||
}
|
||||
}
|
||||
|
||||
// Get count of unassigned notes (Inbox count) — notes without a notebook
|
||||
export async function getInboxCount() {
|
||||
const session = await auth()
|
||||
if (!session?.user?.id) return 0
|
||||
|
||||
try {
|
||||
const count = await prisma.note.count({
|
||||
where: {
|
||||
userId: session.user.id,
|
||||
notebookId: null,
|
||||
isArchived: false,
|
||||
trashedAt: null,
|
||||
},
|
||||
})
|
||||
return count
|
||||
} catch (error) {
|
||||
console.error('Error counting inbox notes:', error)
|
||||
return 0
|
||||
}
|
||||
}
|
||||
|
||||
// Dismiss a note from Recent section
|
||||
export async function dismissFromRecent(id: string) {
|
||||
const session = await auth();
|
||||
|
||||
@@ -205,11 +205,6 @@ export async function executeNotebookOrganization(plan: OrganizationPlan): Promi
|
||||
})
|
||||
if (!notebook) return { success: false, created: 0, moved: 0, error: 'Carnet introuvable' }
|
||||
|
||||
console.log('[organize-notebook] Executing plan:', JSON.stringify({
|
||||
notebookId: plan.notebookId,
|
||||
groups: plan.groups.map(g => ({ name: g.name, isNew: g.isNew, existingId: g.existingId, noteCount: g.notes.length }))
|
||||
}))
|
||||
|
||||
let created = 0
|
||||
let moved = 0
|
||||
|
||||
@@ -254,7 +249,6 @@ export async function executeNotebookOrganization(plan: OrganizationPlan): Promi
|
||||
userId: session.user.id,
|
||||
},
|
||||
})
|
||||
console.log(`[organize-notebook] Created sub-notebook "${newSub.name}" (id: ${newSub.id}) under ${plan.notebookId}`)
|
||||
targetNotebookId = newSub.id
|
||||
created++
|
||||
}
|
||||
@@ -269,7 +263,6 @@ export async function executeNotebookOrganization(plan: OrganizationPlan): Promi
|
||||
},
|
||||
data: { notebookId: targetNotebookId },
|
||||
})
|
||||
console.log(`[organize-notebook] Moved ${result.count} notes to "${group.name}"`)
|
||||
moved += result.count
|
||||
}
|
||||
}
|
||||
|
||||
21
memento-note/app/api/agents/suggestions/[id]/accept/route.ts
Normal file
21
memento-note/app/api/agents/suggestions/[id]/accept/route.ts
Normal file
@@ -0,0 +1,21 @@
|
||||
import { NextRequest, NextResponse } from 'next/server'
|
||||
import { auth } from '@/auth'
|
||||
import { agentSuggestionService } from '@/lib/ai/services/agent-suggestion.service'
|
||||
|
||||
export async function POST(
|
||||
_request: NextRequest,
|
||||
{ params }: { params: Promise<{ id: string }> },
|
||||
) {
|
||||
const session = await auth()
|
||||
if (!session?.user?.id) {
|
||||
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
|
||||
}
|
||||
|
||||
const { id } = await params
|
||||
const result = await agentSuggestionService.accept(session.user.id, id)
|
||||
if (!result) {
|
||||
return NextResponse.json({ error: 'Suggestion introuvable' }, { status: 404 })
|
||||
}
|
||||
|
||||
return NextResponse.json({ success: true, agentId: result.agentId })
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
import { NextRequest, NextResponse } from 'next/server'
|
||||
import { auth } from '@/auth'
|
||||
import { agentSuggestionService } from '@/lib/ai/services/agent-suggestion.service'
|
||||
|
||||
export async function POST(
|
||||
_request: NextRequest,
|
||||
{ params }: { params: Promise<{ id: string }> },
|
||||
) {
|
||||
const session = await auth()
|
||||
if (!session?.user?.id) {
|
||||
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
|
||||
}
|
||||
|
||||
const { id } = await params
|
||||
const result = await agentSuggestionService.dismiss(session.user.id, id)
|
||||
if (!result) {
|
||||
return NextResponse.json({ error: 'Suggestion introuvable' }, { status: 404 })
|
||||
}
|
||||
|
||||
return NextResponse.json({ success: true })
|
||||
}
|
||||
30
memento-note/app/api/agents/suggestions/route.ts
Normal file
30
memento-note/app/api/agents/suggestions/route.ts
Normal file
@@ -0,0 +1,30 @@
|
||||
import { NextResponse } from 'next/server'
|
||||
import { auth } from '@/auth'
|
||||
import { agentSuggestionService } from '@/lib/ai/services/agent-suggestion.service'
|
||||
|
||||
export async function GET() {
|
||||
const session = await auth()
|
||||
if (!session?.user?.id) {
|
||||
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
|
||||
}
|
||||
|
||||
const suggestions = await agentSuggestionService.getPending(session.user.id, 3)
|
||||
return NextResponse.json({
|
||||
suggestions: suggestions.map(s => ({
|
||||
id: s.id,
|
||||
topic: s.topic,
|
||||
reason: s.reason,
|
||||
suggestedType: s.suggestedType,
|
||||
suggestedFrequency: s.suggestedFrequency,
|
||||
relatedNoteCount: (() => {
|
||||
try {
|
||||
return JSON.parse(s.relatedNoteIds).length
|
||||
} catch {
|
||||
return 0
|
||||
}
|
||||
})(),
|
||||
clusterId: s.clusterId,
|
||||
createdAt: s.createdAt.toISOString(),
|
||||
})),
|
||||
})
|
||||
}
|
||||
@@ -1,3 +1,4 @@
|
||||
import { rateLimit } from '@/lib/rate-limit'
|
||||
import { NextRequest, NextResponse } from 'next/server'
|
||||
import { auth } from '@/auth'
|
||||
import { autoLabelCreationService } from '@/lib/ai/services'
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { rateLimit } from '@/lib/rate-limit'
|
||||
import { NextRequest, NextResponse } from 'next/server'
|
||||
import { auth } from '@/auth'
|
||||
import { markdownToHtml } from '@/lib/markdown-to-html'
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { rateLimit } from '@/lib/rate-limit'
|
||||
import { NextRequest, NextResponse } from 'next/server'
|
||||
import { auth } from '@/auth'
|
||||
import { notebookSummaryService } from '@/lib/ai/services'
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { rateLimit } from '@/lib/rate-limit'
|
||||
import { NextRequest, NextResponse } from 'next/server'
|
||||
import { auth } from '@/auth'
|
||||
import { searchOverviewService } from '@/lib/ai/services/search-overview.service'
|
||||
|
||||
@@ -42,13 +42,8 @@ export async function POST(request: NextRequest) {
|
||||
return NextResponse.json({ error: 'No notes found in notebook' }, { status: 400 })
|
||||
}
|
||||
|
||||
const userLang = await prisma.user.findUnique({
|
||||
where: { id: session.user.id },
|
||||
select: { language: true },
|
||||
})
|
||||
|
||||
const notesForService = notes.map(n => ({ id: n.id, title: n.title ?? '' }))
|
||||
const plan = await studyPlannerService.generate(notesForService, examDate, userLang?.language || 'fr')
|
||||
const plan = await studyPlannerService.generate(notesForService, examDate, 'fr')
|
||||
|
||||
// Set the first occurrence reminder for each note (subsequent occurrences ignored)
|
||||
const seenNoteIds = new Set<string>()
|
||||
|
||||
@@ -28,10 +28,10 @@ interface SuggestChartsResponse {
|
||||
analyzedText: string
|
||||
detectedData: string
|
||||
hasData: boolean
|
||||
error?: string
|
||||
}
|
||||
|
||||
export async function POST(req: Request) {
|
||||
console.log('[suggest-charts] ===== REQUEST START =====')
|
||||
|
||||
// 1. Auth check
|
||||
const session = await auth()
|
||||
@@ -47,16 +47,13 @@ export async function POST(req: Request) {
|
||||
})
|
||||
}
|
||||
const userId = session.user.id
|
||||
console.log('[suggest-charts] userId:', userId)
|
||||
|
||||
// 1.5 Quota check
|
||||
try {
|
||||
const sysConfigEarly = await getSystemConfig()
|
||||
const { usedByok: willUseByok } = await willUseByokForLane('chat', sysConfigEarly, userId)
|
||||
console.log('[suggest-charts] BYOK:', willUseByok)
|
||||
if (!willUseByok) {
|
||||
await reserveUsageOrThrow(userId, 'suggest_charts')
|
||||
console.log('[suggest-charts] Quota OK')
|
||||
}
|
||||
} catch (err) {
|
||||
console.error('[suggest-charts] QUOTA ERROR:', err)
|
||||
@@ -84,7 +81,6 @@ export async function POST(req: Request) {
|
||||
} satisfies SuggestChartsResponse, { status: 400 })
|
||||
}
|
||||
const { content, selection, noteId } = body
|
||||
console.log('[suggest-charts] contentLen:', content?.length, 'selectionLen:', selection?.length)
|
||||
|
||||
if (!content || content.trim().length === 0) {
|
||||
console.error('[suggest-charts] EMPTY CONTENT')
|
||||
@@ -98,7 +94,6 @@ export async function POST(req: Request) {
|
||||
}
|
||||
|
||||
const textToAnalyze = selection && selection.trim() ? selection.trim() : content.trim()
|
||||
console.log('[suggest-charts] analyzeLen:', textToAnalyze.length, 'preview:', textToAnalyze.substring(0, 100))
|
||||
|
||||
// 3. Build AI context
|
||||
let provider, model
|
||||
@@ -106,7 +101,6 @@ export async function POST(req: Request) {
|
||||
const sysConfig = await getSystemConfig()
|
||||
provider = getChatProvider(sysConfig)
|
||||
model = provider.getModel()
|
||||
console.log('[suggest-charts] AI model:', model)
|
||||
} catch (e) {
|
||||
console.error('[suggest-charts] AI ROUTE ERROR:', e)
|
||||
return Response.json({
|
||||
@@ -154,7 +148,6 @@ Response format (COPY this structure):
|
||||
})
|
||||
|
||||
// 5. Parse AI response - be very lenient
|
||||
console.log('[suggest-charts] AI response:', text.substring(0, 500))
|
||||
|
||||
let parsed: SuggestChartsResponse
|
||||
try {
|
||||
@@ -227,7 +220,7 @@ Response format (COPY this structure):
|
||||
if (baseSuggestion) {
|
||||
const types = ['bar', 'line', 'pie'].filter(t => t !== baseSuggestion.type)
|
||||
while (parsed.suggestions.length < 3 && types.length > 0) {
|
||||
parsed.suggestions.push({ ...baseSuggestion, type: types.shift()! })
|
||||
parsed.suggestions.push({ ...baseSuggestion, type: types.shift() as any })
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { rateLimit } from '@/lib/rate-limit'
|
||||
import { NextRequest, NextResponse } from 'next/server';
|
||||
import { auth } from '@/auth';
|
||||
import { contextualAutoTagService } from '@/lib/ai/services/contextual-auto-tag.service';
|
||||
@@ -56,7 +57,6 @@ export async function POST(req: NextRequest) {
|
||||
// If notebookId is provided, use contextual suggestions (IA2)
|
||||
if (notebookId) {
|
||||
try {
|
||||
console.log('[/api/ai/tags] contextual request — notebookId:', notebookId, 'content length:', content.length)
|
||||
const suggestions = await contextualAutoTagService.suggestLabels(
|
||||
content,
|
||||
notebookId,
|
||||
@@ -64,7 +64,6 @@ export async function POST(req: NextRequest) {
|
||||
language
|
||||
);
|
||||
|
||||
console.log('[/api/ai/tags] suggestions:', suggestions.length, suggestions.map(s => `${s.label}(${s.confidence})`))
|
||||
|
||||
const convertedTags = suggestions.map(s => ({
|
||||
tag: s.label,
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { rateLimit } from '@/lib/rate-limit'
|
||||
import { NextRequest, NextResponse } from 'next/server'
|
||||
import { runLaneWithBillingUser, willUseByokForLane } from '@/lib/ai/provider-for-user'
|
||||
import { getSystemConfig } from '@/lib/config'
|
||||
|
||||
@@ -153,7 +153,9 @@ export async function POST(
|
||||
}
|
||||
}
|
||||
|
||||
await prisma.$transaction(tagPromises)
|
||||
await prisma.$transaction(async () => {
|
||||
await Promise.all(tagPromises)
|
||||
})
|
||||
|
||||
await logActivity(sessionId, 'idea_converted', session.user.id, { ideaTitle: idea.title, ideaId: idea.id, noteId: note.id })
|
||||
|
||||
|
||||
@@ -75,7 +75,9 @@ export async function POST(
|
||||
}
|
||||
|
||||
if (updatePromises.length > 0) {
|
||||
await prisma.$transaction(updatePromises)
|
||||
await prisma.$transaction(async () => {
|
||||
await Promise.all(updatePromises)
|
||||
})
|
||||
}
|
||||
|
||||
const fruitful = Array.from(noteImpactMap.values()).filter(n => n.acceptedCount > 0).length
|
||||
|
||||
204
memento-note/app/api/briefing/paths/route.ts
Normal file
204
memento-note/app/api/briefing/paths/route.ts
Normal file
@@ -0,0 +1,204 @@
|
||||
import { NextResponse } from 'next/server'
|
||||
import { auth } from '@/auth'
|
||||
import prisma from '@/lib/prisma'
|
||||
import { agentSuggestionService } from '@/lib/ai/services/agent-suggestion.service'
|
||||
import { bridgeNotesService } from '@/lib/ai/services/bridge-notes.service'
|
||||
import { buildDashboardPaths, buildOpenLoops } from '@/lib/dashboard/paths.service'
|
||||
import { hasUserAiConsent } from '@/lib/consent/server-consent'
|
||||
import { getSystemConfig } from '@/lib/config'
|
||||
import { getChatProvider } from '@/lib/ai/factory'
|
||||
|
||||
function excerptNoteContent(content: string | null | undefined, max = 200): string {
|
||||
if (!content) return ''
|
||||
const plain = content.replace(/<[^>]+>/g, ' ').replace(/ /g, ' ').replace(/\s+/g, ' ').trim()
|
||||
if (plain.length <= max) return plain
|
||||
return `${plain.slice(0, max)}…`
|
||||
}
|
||||
|
||||
interface PathsBriefingSnapshot {
|
||||
recentNote?: {
|
||||
id: string
|
||||
title: string | null
|
||||
content: string
|
||||
notebookId: string | null
|
||||
} | null
|
||||
inboxCount?: number
|
||||
dueFlashcards?: number
|
||||
insights?: Array<{
|
||||
id: string
|
||||
insight: string
|
||||
score: number
|
||||
viewed: boolean
|
||||
note1: { id: string; title: string | null }
|
||||
note2: { id: string; title: string | null }
|
||||
note1Excerpt?: string
|
||||
note2Excerpt?: string
|
||||
}>
|
||||
bridgeSuggestions?: Array<{
|
||||
clusterAId: number
|
||||
clusterBId: number
|
||||
clusterAName: string
|
||||
clusterBName: string
|
||||
suggestedTitle: string
|
||||
suggestedContent: string
|
||||
justification: string
|
||||
}>
|
||||
agentSuggestions?: Array<{
|
||||
id: string
|
||||
topic: string
|
||||
reason: string
|
||||
clusterId: number | null
|
||||
}>
|
||||
includeOpenLoops?: boolean
|
||||
}
|
||||
|
||||
async function resolvePathsPayload(userId: string, snapshot?: PathsBriefingSnapshot | null) {
|
||||
const now = new Date()
|
||||
const hasSnapshot = !!snapshot?.recentNote
|
||||
|
||||
const needsAgents = !snapshot?.agentSuggestions
|
||||
const needsBridges = !snapshot?.bridgeSuggestions
|
||||
const needsInsights = !snapshot?.insights
|
||||
const needsCounts = snapshot?.inboxCount === undefined || snapshot?.dueFlashcards === undefined
|
||||
const needsFocusNote = !snapshot?.recentNote
|
||||
|
||||
const [
|
||||
aiConsent,
|
||||
aiSettings,
|
||||
systemConfig,
|
||||
recentNotes,
|
||||
inboxCount,
|
||||
dueFlashcards,
|
||||
unviewedInsights,
|
||||
agentSuggestions,
|
||||
bridgeSuggestions,
|
||||
] = await Promise.all([
|
||||
hasUserAiConsent(),
|
||||
prisma.userAISettings.findUnique({
|
||||
where: { userId },
|
||||
select: { memoryEcho: true },
|
||||
}),
|
||||
getSystemConfig(),
|
||||
needsFocusNote
|
||||
? prisma.note.findMany({
|
||||
where: { userId, trashedAt: null, isArchived: false },
|
||||
select: { id: true, title: true, content: true, notebookId: true, updatedAt: true },
|
||||
orderBy: { updatedAt: 'desc' },
|
||||
take: 1,
|
||||
})
|
||||
: Promise.resolve([]),
|
||||
needsCounts
|
||||
? prisma.note.count({
|
||||
where: { userId, notebookId: null, isArchived: false, trashedAt: null },
|
||||
})
|
||||
: Promise.resolve(snapshot!.inboxCount!),
|
||||
needsCounts
|
||||
? prisma.flashcard.count({
|
||||
where: { deck: { userId }, nextReviewAt: { lte: now } },
|
||||
})
|
||||
: Promise.resolve(snapshot!.dueFlashcards!),
|
||||
needsInsights
|
||||
? prisma.memoryEchoInsight.findMany({
|
||||
where: { userId, dismissed: false },
|
||||
select: {
|
||||
id: true, insight: true, similarityScore: true, viewed: true,
|
||||
note1: { select: { id: true, title: true, content: true } },
|
||||
note2: { select: { id: true, title: true, content: true } },
|
||||
},
|
||||
orderBy: { insightDate: 'desc' },
|
||||
take: 5,
|
||||
}).catch(() => [])
|
||||
: Promise.resolve([]),
|
||||
needsAgents
|
||||
? agentSuggestionService.getPending(userId, 3).catch(() => [])
|
||||
: Promise.resolve([]),
|
||||
needsBridges
|
||||
? bridgeNotesService.getBridgeSuggestions(userId).catch(() => [])
|
||||
: Promise.resolve([]),
|
||||
])
|
||||
|
||||
const aiProviderReady = !!getChatProvider(systemConfig)
|
||||
const memoryEchoEnabled = aiSettings?.memoryEcho ?? true
|
||||
const aiActive = aiConsent && aiProviderReady && memoryEchoEnabled
|
||||
|
||||
const focusNotes = hasSnapshot && snapshot?.recentNote
|
||||
? [{
|
||||
...snapshot.recentNote,
|
||||
updatedAt: now,
|
||||
}]
|
||||
: recentNotes
|
||||
|
||||
const insights = snapshot?.insights ?? unviewedInsights.map(i => ({
|
||||
id: i.id,
|
||||
insight: i.insight,
|
||||
score: i.similarityScore,
|
||||
viewed: i.viewed,
|
||||
note1: { id: i.note1.id, title: i.note1.title },
|
||||
note2: { id: i.note2.id, title: i.note2.title },
|
||||
note1Excerpt: excerptNoteContent(i.note1.content),
|
||||
note2Excerpt: excerptNoteContent(i.note2.content),
|
||||
}))
|
||||
|
||||
const resolvedBridges = snapshot?.bridgeSuggestions
|
||||
?? bridgeSuggestions.slice(0, 3).map(s => ({
|
||||
clusterAId: s.clusterAId,
|
||||
clusterBId: s.clusterBId,
|
||||
clusterAName: s.clusterAName,
|
||||
clusterBName: s.clusterBName,
|
||||
suggestedTitle: s.suggestedTitle,
|
||||
suggestedContent: s.suggestedContent,
|
||||
justification: s.justification,
|
||||
}))
|
||||
|
||||
const resolvedAgents = snapshot?.agentSuggestions
|
||||
?? agentSuggestions.map(s => ({
|
||||
id: s.id,
|
||||
topic: s.topic,
|
||||
reason: s.reason,
|
||||
clusterId: s.clusterId,
|
||||
}))
|
||||
|
||||
const paths = await buildDashboardPaths({
|
||||
userId,
|
||||
aiActive,
|
||||
recentNotes: focusNotes,
|
||||
inboxCount: needsCounts ? inboxCount : snapshot!.inboxCount!,
|
||||
dueFlashcards: needsCounts ? dueFlashcards : snapshot!.dueFlashcards!,
|
||||
insights,
|
||||
bridgeSuggestions: resolvedBridges,
|
||||
agentSuggestions: resolvedAgents,
|
||||
}).catch(() => [])
|
||||
|
||||
const openLoops = snapshot?.includeOpenLoops === false
|
||||
? []
|
||||
: await buildOpenLoops(userId).catch(() => [])
|
||||
|
||||
return { paths, openLoops }
|
||||
}
|
||||
|
||||
/**
|
||||
* GET /api/briefing/paths — pistes enrichies (fallback sans snapshot client).
|
||||
*/
|
||||
export async function GET() {
|
||||
const session = await auth()
|
||||
if (!session?.user?.id) {
|
||||
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
|
||||
}
|
||||
|
||||
const payload = await resolvePathsPayload(session.user.id)
|
||||
return NextResponse.json(payload)
|
||||
}
|
||||
|
||||
/**
|
||||
* POST /api/briefing/paths — enrichissement avec snapshot briefing (évite re-fetch agents/ponts).
|
||||
*/
|
||||
export async function POST(request: Request) {
|
||||
const session = await auth()
|
||||
if (!session?.user?.id) {
|
||||
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
|
||||
}
|
||||
|
||||
const snapshot = await request.json().catch(() => null) as PathsBriefingSnapshot | null
|
||||
const payload = await resolvePathsPayload(session.user.id, snapshot)
|
||||
return NextResponse.json(payload)
|
||||
}
|
||||
240
memento-note/app/api/briefing/route.ts
Normal file
240
memento-note/app/api/briefing/route.ts
Normal file
@@ -0,0 +1,240 @@
|
||||
import { NextResponse } from 'next/server'
|
||||
import { auth } from '@/auth'
|
||||
import prisma from '@/lib/prisma'
|
||||
import { agentSuggestionService } from '@/lib/ai/services/agent-suggestion.service'
|
||||
import { bridgeNotesService } from '@/lib/ai/services/bridge-notes.service'
|
||||
import { gmailScannerService } from '@/lib/integrations/gmail-scanner.service'
|
||||
import { hasUserAiConsent } from '@/lib/consent/server-consent'
|
||||
import { getSystemConfig } from '@/lib/config'
|
||||
import { getChatProvider } from '@/lib/ai/factory'
|
||||
|
||||
function excerptNoteContent(content: string | null | undefined, max = 200): string {
|
||||
if (!content) return ''
|
||||
const plain = content.replace(/<[^>]+>/g, ' ').replace(/ /g, ' ').replace(/\s+/g, ' ').trim()
|
||||
if (plain.length <= max) return plain
|
||||
return `${plain.slice(0, max)}…`
|
||||
}
|
||||
|
||||
async function fetchWritingActivity(userId: string, since: Date) {
|
||||
const rows = await prisma.$queryRaw<Array<{ date: string; count: number }>>`
|
||||
SELECT to_char("updatedAt" AT TIME ZONE 'UTC', 'YYYY-MM-DD') AS date,
|
||||
COUNT(*)::int AS count
|
||||
FROM "Note"
|
||||
WHERE "userId" = ${userId}
|
||||
AND "trashedAt" IS NULL
|
||||
AND "updatedAt" >= ${since}
|
||||
GROUP BY 1
|
||||
ORDER BY 1 ASC
|
||||
`
|
||||
return rows.map(r => ({ date: r.date, count: Number(r.count) }))
|
||||
}
|
||||
|
||||
/**
|
||||
* GET /api/briefing — agrégat rapide pour le tableau de bord.
|
||||
* Pas de génération IA synchrone ; les pistes sont dans GET /api/briefing/paths.
|
||||
*/
|
||||
export async function GET() {
|
||||
const session = await auth()
|
||||
if (!session?.user?.id) {
|
||||
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
|
||||
}
|
||||
|
||||
const userId = session.user.id
|
||||
const now = new Date()
|
||||
const ninetyDaysAgo = new Date(now)
|
||||
ninetyDaysAgo.setDate(ninetyDaysAgo.getDate() - 90)
|
||||
|
||||
const [aiConsent, aiSettings, systemConfig] = await Promise.all([
|
||||
hasUserAiConsent(),
|
||||
prisma.userAISettings.findUnique({
|
||||
where: { userId },
|
||||
select: { memoryEcho: true },
|
||||
}),
|
||||
getSystemConfig(),
|
||||
])
|
||||
const aiProviderReady = !!getChatProvider(systemConfig)
|
||||
const memoryEchoEnabled = aiSettings?.memoryEcho ?? true
|
||||
const aiActive = aiConsent && aiProviderReady && memoryEchoEnabled
|
||||
|
||||
const [
|
||||
recentNotes,
|
||||
inboxCount,
|
||||
dueFlashcards,
|
||||
upcomingReminders,
|
||||
unviewedInsights,
|
||||
recentAgentActions,
|
||||
pinnedNotes,
|
||||
writingActivity,
|
||||
gmailStatus,
|
||||
agentSuggestions,
|
||||
bridgeSuggestions,
|
||||
] = await Promise.all([
|
||||
prisma.note.findMany({
|
||||
where: { userId, trashedAt: null, isArchived: false },
|
||||
select: {
|
||||
id: true, title: true, content: true, color: true,
|
||||
notebookId: true, updatedAt: true, createdAt: true,
|
||||
},
|
||||
orderBy: { updatedAt: 'desc' },
|
||||
take: 6,
|
||||
}),
|
||||
|
||||
prisma.note.count({
|
||||
where: { userId, notebookId: null, isArchived: false, trashedAt: null },
|
||||
}),
|
||||
|
||||
prisma.flashcard.count({
|
||||
where: { deck: { userId }, nextReviewAt: { lte: now } },
|
||||
}),
|
||||
|
||||
prisma.note.findMany({
|
||||
where: {
|
||||
userId, reminder: { gte: now }, isReminderDone: false, trashedAt: null,
|
||||
},
|
||||
select: { id: true, title: true, reminder: true, notebookId: true },
|
||||
orderBy: { reminder: 'asc' },
|
||||
take: 5,
|
||||
}),
|
||||
|
||||
prisma.memoryEchoInsight.findMany({
|
||||
where: { userId, viewed: false, dismissed: false },
|
||||
select: {
|
||||
id: true, insight: true, similarityScore: true,
|
||||
insightDate: true, viewed: true,
|
||||
note1: { select: { id: true, title: true, content: true } },
|
||||
note2: { select: { id: true, title: true, content: true } },
|
||||
},
|
||||
orderBy: { insightDate: 'desc' },
|
||||
take: 5,
|
||||
}).catch(() => []),
|
||||
|
||||
prisma.agentAction.findMany({
|
||||
where: {
|
||||
agent: { userId },
|
||||
status: 'completed',
|
||||
createdAt: { gte: new Date(now.getTime() - 48 * 60 * 60 * 1000) },
|
||||
},
|
||||
select: {
|
||||
id: true, result: true, createdAt: true,
|
||||
agent: { select: { id: true, name: true, type: true } },
|
||||
},
|
||||
orderBy: { createdAt: 'desc' },
|
||||
take: 3,
|
||||
}).catch(() => []),
|
||||
|
||||
prisma.note.findMany({
|
||||
where: { userId, isPinned: true, trashedAt: null, isArchived: false },
|
||||
select: { id: true, title: true, notebookId: true, updatedAt: true },
|
||||
orderBy: { updatedAt: 'desc' },
|
||||
take: 5,
|
||||
}),
|
||||
|
||||
fetchWritingActivity(userId, ninetyDaysAgo).catch(() => []),
|
||||
|
||||
gmailScannerService.getStatus(userId).catch(() => ({
|
||||
connected: false,
|
||||
recentCaptures: 0,
|
||||
})),
|
||||
|
||||
agentSuggestionService.getPending(userId, 3).catch(() => []),
|
||||
|
||||
bridgeNotesService.getBridgeSuggestions(userId).catch(() => []),
|
||||
])
|
||||
|
||||
let insightRows = unviewedInsights
|
||||
if (insightRows.length < 5) {
|
||||
const viewedRecent = await prisma.memoryEchoInsight.findMany({
|
||||
where: {
|
||||
userId,
|
||||
dismissed: false,
|
||||
viewed: true,
|
||||
id: { notIn: insightRows.map(i => i.id) },
|
||||
},
|
||||
select: {
|
||||
id: true, insight: true, similarityScore: true,
|
||||
insightDate: true, viewed: true,
|
||||
note1: { select: { id: true, title: true, content: true } },
|
||||
note2: { select: { id: true, title: true, content: true } },
|
||||
},
|
||||
orderBy: { insightDate: 'desc' },
|
||||
take: 5 - insightRows.length,
|
||||
}).catch(() => [])
|
||||
insightRows = [...insightRows, ...viewedRecent]
|
||||
}
|
||||
|
||||
const notebookIds = [...new Set(recentNotes.map(n => n.notebookId).filter(Boolean))] as string[]
|
||||
const notebooks = notebookIds.length > 0
|
||||
? await prisma.notebook.findMany({
|
||||
where: { id: { in: notebookIds } },
|
||||
select: { id: true, name: true, color: true, icon: true },
|
||||
})
|
||||
: []
|
||||
const notebookMap = new Map(notebooks.map(n => [n.id, n]))
|
||||
|
||||
return NextResponse.json({
|
||||
recentNotes: recentNotes.map(n => ({
|
||||
...n,
|
||||
notebook: n.notebookId ? notebookMap.get(n.notebookId) || null : null,
|
||||
})),
|
||||
inboxCount,
|
||||
dueFlashcards,
|
||||
upcomingReminders: upcomingReminders.map(r => ({
|
||||
id: r.id,
|
||||
title: r.title,
|
||||
reminder: r.reminder?.toISOString() || null,
|
||||
notebookId: r.notebookId,
|
||||
})),
|
||||
insights: insightRows.map(i => ({
|
||||
id: i.id,
|
||||
insight: i.insight,
|
||||
score: i.similarityScore,
|
||||
date: i.insightDate.toISOString(),
|
||||
viewed: i.viewed,
|
||||
note1: { id: i.note1.id, title: i.note1.title },
|
||||
note2: { id: i.note2.id, title: i.note2.title },
|
||||
note1Excerpt: excerptNoteContent(i.note1.content),
|
||||
note2Excerpt: excerptNoteContent(i.note2.content),
|
||||
})),
|
||||
bridgeSuggestions: bridgeSuggestions.slice(0, 3).map(s => ({
|
||||
clusterAId: s.clusterAId,
|
||||
clusterBId: s.clusterBId,
|
||||
clusterAName: s.clusterAName,
|
||||
clusterBName: s.clusterBName,
|
||||
suggestedTitle: s.suggestedTitle,
|
||||
suggestedContent: s.suggestedContent,
|
||||
justification: s.justification,
|
||||
})),
|
||||
ai: {
|
||||
consent: aiConsent,
|
||||
memoryEchoEnabled,
|
||||
providerReady: aiProviderReady,
|
||||
active: aiActive,
|
||||
},
|
||||
agentActions: recentAgentActions.map(a => ({
|
||||
id: a.id,
|
||||
agentName: a.agent?.name || 'Agent',
|
||||
agentType: a.agent?.type || 'custom',
|
||||
result: a.result ? String(a.result).slice(0, 200) : null,
|
||||
createdAt: a.createdAt.toISOString(),
|
||||
})),
|
||||
gmail: gmailStatus,
|
||||
pinnedNotes: pinnedNotes.map(n => ({
|
||||
id: n.id,
|
||||
title: n.title,
|
||||
notebookId: n.notebookId,
|
||||
updatedAt: n.updatedAt.toISOString(),
|
||||
})),
|
||||
writingActivity,
|
||||
agentSuggestions: agentSuggestions.map(s => ({
|
||||
id: s.id,
|
||||
topic: s.topic,
|
||||
reason: s.reason,
|
||||
suggestedType: s.suggestedType,
|
||||
suggestedFrequency: s.suggestedFrequency,
|
||||
relatedNoteCount: (() => {
|
||||
try { return JSON.parse(s.relatedNoteIds).length } catch { return 0 }
|
||||
})(),
|
||||
clusterId: s.clusterId,
|
||||
})),
|
||||
})
|
||||
}
|
||||
87
memento-note/app/api/briefing/sentiment/route.ts
Normal file
87
memento-note/app/api/briefing/sentiment/route.ts
Normal file
@@ -0,0 +1,87 @@
|
||||
import { NextResponse } from 'next/server'
|
||||
import { auth } from '@/auth'
|
||||
import prisma from '@/lib/prisma'
|
||||
import { getChatProvider } from '@/lib/ai/factory'
|
||||
import { getSystemConfig } from '@/lib/config'
|
||||
import { redis } from '@/lib/redis'
|
||||
import { detectUserLanguage } from '@/lib/i18n/detect-user-language'
|
||||
|
||||
const CACHE_TTL_SEC = 3600
|
||||
|
||||
/**
|
||||
* GET /api/briefing/sentiment
|
||||
* Analyzes the emotional tone of recent notes (last 7 days) using LLM.
|
||||
*/
|
||||
export async function GET() {
|
||||
const session = await auth()
|
||||
if (!session?.user?.id) {
|
||||
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
|
||||
}
|
||||
|
||||
const userId = session.user.id
|
||||
const locale = await detectUserLanguage()
|
||||
const cacheKey = `briefing:sentiment:${userId}:${locale}`
|
||||
|
||||
try {
|
||||
const cached = await redis.get(cacheKey)
|
||||
if (cached) return NextResponse.json(JSON.parse(cached))
|
||||
} catch {}
|
||||
|
||||
const weekAgo = new Date()
|
||||
weekAgo.setDate(weekAgo.getDate() - 7)
|
||||
|
||||
const recentNotes = await prisma.note.findMany({
|
||||
where: {
|
||||
userId,
|
||||
trashedAt: null,
|
||||
isArchived: false,
|
||||
updatedAt: { gte: weekAgo },
|
||||
},
|
||||
select: { title: true, content: true },
|
||||
take: 20,
|
||||
orderBy: { updatedAt: 'desc' },
|
||||
})
|
||||
|
||||
if (recentNotes.length < 3) {
|
||||
return NextResponse.json({
|
||||
available: false,
|
||||
reason: 'Not enough notes this week',
|
||||
})
|
||||
}
|
||||
|
||||
const snippets = recentNotes.map(n => {
|
||||
const text = n.content.replace(/<[^>]+>/g, ' ').replace(/ /g, ' ').replace(/\s+/g, ' ').trim()
|
||||
return `${n.title || ''}: ${text.slice(0, 200)}`
|
||||
}).join('\n---\n')
|
||||
|
||||
try {
|
||||
const config = await getSystemConfig()
|
||||
const provider = getChatProvider(config)
|
||||
if (!provider) {
|
||||
return NextResponse.json({ available: false, reason: 'No AI provider' })
|
||||
}
|
||||
|
||||
const localeLabel = locale === 'fr' ? 'French' : locale === 'en' ? 'English' : locale
|
||||
const prompt = `Analyze the emotional patterns in these notes from the past week. Return ONLY valid JSON (no markdown, no code fences).
|
||||
Write "summary" and "topTopic" in ${localeLabel} (locale code: ${locale}). Keep dominantEmotion keys in English as listed.
|
||||
|
||||
{"dominantEmotion":"focused|curious|enthusiastic|frustrated|calm|anxious|creative|reflective","sentimentScore":number from -1 to 1,"emotions":{"focused":number,"curious":number,"enthusiastic":number,"frustrated":number,"calm":number,"anxious":number,"creative":number,"reflective":number},"summary":"one sentence describing the emotional pattern","topTopic":"most discussed topic"}
|
||||
|
||||
Notes:
|
||||
${snippets.slice(0, 3000)}`
|
||||
|
||||
const result = await provider.generateText(prompt)
|
||||
const jsonMatch = result.match(/\{[\s\S]*\}/)
|
||||
if (!jsonMatch) {
|
||||
return NextResponse.json({ available: false, reason: 'Parse error' })
|
||||
}
|
||||
|
||||
const parsed = JSON.parse(jsonMatch[0])
|
||||
const payload = { available: true, ...parsed }
|
||||
try { await redis.setex(cacheKey, CACHE_TTL_SEC, JSON.stringify(payload)) } catch {}
|
||||
return NextResponse.json(payload)
|
||||
} catch (error) {
|
||||
console.error('[briefing/sentiment]', error)
|
||||
return NextResponse.json({ available: false, reason: 'Analysis failed' })
|
||||
}
|
||||
}
|
||||
@@ -75,7 +75,6 @@ async function buildPptx(spec: any): Promise<Buffer> {
|
||||
}
|
||||
|
||||
case 'bullets': {
|
||||
console.log('[PPTX] Rendering bullets slide:', slide.title, 'items:', slide.items?.length)
|
||||
s.background = { color: p.bg }
|
||||
s.addShape(pptx.ShapeType.rect, {
|
||||
x: 0, y: 0, w: 0.06, h: H,
|
||||
@@ -90,7 +89,6 @@ async function buildPptx(spec: any): Promise<Buffer> {
|
||||
fill: { color: p.accent }, line: { type: 'none' },
|
||||
})
|
||||
const items = slide.items ?? []
|
||||
console.log('[PPTX] Bullet items:', items.length, items[0])
|
||||
// Use simpler bullet format - each item as separate text call with bullet option
|
||||
items.forEach((item: string, i: number) => {
|
||||
s.addText(item, {
|
||||
|
||||
@@ -4,10 +4,8 @@ import { prisma } from '@/lib/prisma'
|
||||
export async function GET(req: NextRequest) {
|
||||
try {
|
||||
const canvasId = req.nextUrl.searchParams.get('id')
|
||||
console.log('[Slides API] Request for id:', canvasId)
|
||||
|
||||
if (!canvasId) {
|
||||
console.log('[Slides API] ERROR: Missing id')
|
||||
return new Response(JSON.stringify({ error: 'Missing id' }), {
|
||||
status: 400,
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
@@ -19,39 +17,31 @@ export async function GET(req: NextRequest) {
|
||||
})
|
||||
|
||||
if (!canvas) {
|
||||
console.log('[Slides API] ERROR: Canvas not found for id:', canvasId)
|
||||
return new Response(JSON.stringify({ error: 'Not found' }), {
|
||||
status: 404,
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
})
|
||||
}
|
||||
|
||||
console.log('[Slides API] Canvas found:', canvas.name, '| data length:', canvas.data?.length)
|
||||
console.log('[Slides API] Raw data start:', canvas.data?.substring(0, 200))
|
||||
|
||||
let parsed: any
|
||||
try {
|
||||
parsed = JSON.parse(canvas.data)
|
||||
} catch (parseErr) {
|
||||
console.log('[Slides API] ERROR: JSON parse failed:', parseErr)
|
||||
return new Response(JSON.stringify({ error: 'Invalid data' }), {
|
||||
status: 500,
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
})
|
||||
}
|
||||
|
||||
console.log('[Slides API] Parsed type:', parsed.type, '| has html:', !!parsed.html, '| html length:', parsed.html?.length)
|
||||
console.log('[Slides API] HTML start:', parsed.html?.substring(0, 150))
|
||||
|
||||
if (parsed.type !== 'slides' || !parsed.html) {
|
||||
console.log('[Slides API] ERROR: Not a slides canvas. type:', parsed.type, 'html exists:', !!parsed.html)
|
||||
return new Response(JSON.stringify({ error: 'Not a slides canvas' }), {
|
||||
status: 400,
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
})
|
||||
}
|
||||
|
||||
console.log('[Slides API] SUCCESS: Returning HTML, length:', parsed.html.length)
|
||||
|
||||
return new Response(parsed.html, {
|
||||
status: 200,
|
||||
|
||||
@@ -15,6 +15,7 @@ import { trackFeatureUsage } from '@/lib/usage-tracker'
|
||||
import { readFile } from 'fs/promises'
|
||||
import path from 'path'
|
||||
import { logAuditEvent, getClientIp } from '@/lib/audit-log'
|
||||
import { rateLimit } from '@/lib/rate-limit'
|
||||
|
||||
export const maxDuration = 60
|
||||
|
||||
@@ -53,6 +54,14 @@ export async function POST(req: Request) {
|
||||
}
|
||||
const userId = session.user.id
|
||||
|
||||
const rl = await rateLimit(userId, 'chat', 15, 60)
|
||||
if (!rl.allowed) {
|
||||
return new Response(JSON.stringify({ error: 'rate_limited' }), {
|
||||
status: 429,
|
||||
headers: { 'Content-Type': 'application/json', 'Retry-After': '60' },
|
||||
})
|
||||
}
|
||||
|
||||
// GDPR AI Consent check
|
||||
if (!(await hasUserAiConsent())) {
|
||||
return new Response(JSON.stringify({ error: 'ai_consent_required' }), {
|
||||
@@ -153,14 +162,14 @@ Fais un résumé concis (max 200 mots) de cette conversation. Garde les informat
|
||||
})
|
||||
|
||||
messagesForModel = [
|
||||
{ role: 'system' as const, content: `Contexte de la conversation précédente:\n${newSummary.slice(0, 1000)}` },
|
||||
{ role: 'system', content: `Contexte de la conversation précédente:\n${newSummary.slice(0, 1000)}` },
|
||||
...incomingMessages.slice(-RECENT_KEEP),
|
||||
]
|
||||
] as any
|
||||
} else if (conversation.summary) {
|
||||
messagesForModel = [
|
||||
{ role: 'system' as const, content: `Contexte de la conversation précédente:\n${conversation.summary}` },
|
||||
{ role: 'system', content: `Contexte de la conversation précédente:\n${conversation.summary}` },
|
||||
...incomingMessages.slice(-RECENT_KEEP),
|
||||
]
|
||||
] as any
|
||||
}
|
||||
} catch (e) {
|
||||
console.error('[Chat] Summary generation failed, using full context:', e)
|
||||
|
||||
@@ -20,8 +20,54 @@ export async function GET(request: NextRequest) {
|
||||
|
||||
// Check for stored results (even if stale/périmés)
|
||||
const stored = await clusteringService.getStoredClusters(userId)
|
||||
const lite = request.nextUrl.searchParams.get('lite') === '1'
|
||||
|
||||
if (stored) {
|
||||
const cached = stored.clusters
|
||||
|
||||
if (lite) {
|
||||
const [bridgeNotesData, totalNotes] = await Promise.all([
|
||||
prisma.bridgeNote.findMany({
|
||||
where: { userId },
|
||||
orderBy: { bridgeScore: 'desc' },
|
||||
take: 5,
|
||||
select: { noteId: true, bridgeScore: true, clustersConnected: true },
|
||||
}),
|
||||
prisma.note.count({ where: { userId, trashedAt: null } }),
|
||||
])
|
||||
|
||||
let enrichedBridgeNotes: object[] = []
|
||||
if (bridgeNotesData.length > 0) {
|
||||
const bridgeNoteDetails = await prisma.note.findMany({
|
||||
where: { id: { in: bridgeNotesData.map(b => b.noteId) } },
|
||||
select: { id: true, title: true },
|
||||
})
|
||||
const bridgeNoteDetailsMap = new Map(bridgeNoteDetails.map(n => [n.id, n]))
|
||||
|
||||
enrichedBridgeNotes = bridgeNotesData.map(b => {
|
||||
const clustersConnected = JSON.parse(b.clustersConnected) as number[]
|
||||
return {
|
||||
noteId: b.noteId,
|
||||
bridgeScore: b.bridgeScore,
|
||||
clustersConnected,
|
||||
clusterNames: clustersConnected.map(
|
||||
cid => cached.find(c => c.clusterId === cid)?.name || `Cluster ${cid}`,
|
||||
),
|
||||
note: bridgeNoteDetailsMap.get(b.noteId),
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
return NextResponse.json({
|
||||
clusters: cached,
|
||||
bridgeNotes: enrichedBridgeNotes,
|
||||
cached: true,
|
||||
stale: stored.stale,
|
||||
lastCalculated: stored.lastCalculated,
|
||||
totalNotes,
|
||||
})
|
||||
}
|
||||
|
||||
// Fetch notes with their cluster assignments
|
||||
const notes = await prisma.note.findMany({
|
||||
where: { userId, trashedAt: null },
|
||||
|
||||
41
memento-note/app/api/cron/agent-suggestions/route.ts
Normal file
41
memento-note/app/api/cron/agent-suggestions/route.ts
Normal file
@@ -0,0 +1,41 @@
|
||||
import { NextRequest, NextResponse } from 'next/server'
|
||||
import prisma from '@/lib/prisma'
|
||||
import { agentSuggestionService } from '@/lib/ai/services/agent-suggestion.service'
|
||||
|
||||
export const dynamic = 'force-dynamic'
|
||||
|
||||
function authorizeCron(request: NextRequest): boolean {
|
||||
const cronSecret = process.env.CRON_SECRET
|
||||
if (!cronSecret) return false
|
||||
const authHeader = request.headers.get('authorization')
|
||||
const bearer = authHeader?.startsWith('Bearer ') ? authHeader.slice(7) : null
|
||||
const querySecret = new URL(request.url).searchParams.get('secret')
|
||||
return bearer === cronSecret || querySecret === cronSecret
|
||||
}
|
||||
|
||||
/**
|
||||
* POST /api/cron/agent-suggestions
|
||||
* Génère des suggestions d'agents à partir des clusters sémantiques existants.
|
||||
*/
|
||||
export async function POST(request: NextRequest) {
|
||||
if (!authorizeCron(request)) {
|
||||
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
|
||||
}
|
||||
|
||||
const users = await prisma.user.findMany({
|
||||
where: { noteClusters: { some: {} } },
|
||||
select: { id: true },
|
||||
take: 30,
|
||||
})
|
||||
|
||||
let total = 0
|
||||
for (const user of users) {
|
||||
try {
|
||||
total += await agentSuggestionService.generateForUser(user.id)
|
||||
} catch (err) {
|
||||
console.error('[CronAgentSuggestions] user', user.id, err)
|
||||
}
|
||||
}
|
||||
|
||||
return NextResponse.json({ success: true, users: users.length, suggestionsUpserted: total })
|
||||
}
|
||||
@@ -47,14 +47,12 @@ export async function POST(request: NextRequest) {
|
||||
return NextResponse.json({ success: true, executed: 0 })
|
||||
}
|
||||
|
||||
console.log(`[CronAgents] Found ${dueAgents.length} due agent(s): ${dueAgents.map(a => a.id).join(', ')}`)
|
||||
|
||||
const results: { id: string; success: boolean; error?: string }[] = []
|
||||
|
||||
// Execute agents sequentially (max 3 per cycle)
|
||||
for (const agent of dueAgents.slice(0, 3)) {
|
||||
try {
|
||||
console.log(`[CronAgents] Executing agent ${agent.id} (${agent.frequency})`)
|
||||
const { executeAgent } = await import('@/lib/ai/services/agent-executor.service')
|
||||
const result = await executeAgent(agent.id, agent.userId)
|
||||
|
||||
@@ -66,7 +64,6 @@ export async function POST(request: NextRequest) {
|
||||
timezone: agent.timezone,
|
||||
})
|
||||
|
||||
console.log(`[CronAgents] Agent ${agent.id} done. success=${result.success}, nextRun=${nextRun?.toISOString() ?? 'null'}`)
|
||||
|
||||
await prisma.agent.update({
|
||||
where: { id: agent.id },
|
||||
|
||||
49
memento-note/app/api/cron/gmail/route.ts
Normal file
49
memento-note/app/api/cron/gmail/route.ts
Normal file
@@ -0,0 +1,49 @@
|
||||
import { NextRequest, NextResponse } from 'next/server'
|
||||
import prisma from '@/lib/prisma'
|
||||
import { gmailScannerService } from '@/lib/integrations/gmail-scanner.service'
|
||||
|
||||
export const dynamic = 'force-dynamic'
|
||||
|
||||
function authorize(request: NextRequest): boolean {
|
||||
const cronSecret = process.env.CRON_SECRET
|
||||
if (!cronSecret) return false
|
||||
const authHeader = request.headers.get('authorization')
|
||||
const bearer = authHeader?.startsWith('Bearer ') ? authHeader.slice(7) : null
|
||||
return bearer === cronSecret
|
||||
}
|
||||
|
||||
/** POST /api/cron/gmail — scan Gmail for connected users (1×/jour en prod via entrypoint) */
|
||||
export async function POST(request: NextRequest) {
|
||||
if (!authorize(request)) {
|
||||
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
|
||||
}
|
||||
|
||||
const users = await prisma.userAISettings.findMany({
|
||||
select: { userId: true, integrationTokens: true },
|
||||
take: 200,
|
||||
})
|
||||
|
||||
const connected = users.filter(u => {
|
||||
if (!u.integrationTokens) return false
|
||||
try {
|
||||
const meta = typeof u.integrationTokens === 'string'
|
||||
? JSON.parse(u.integrationTokens)
|
||||
: u.integrationTokens
|
||||
return !!(meta?.gmailAccessToken && meta?.gmailRefreshToken)
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
})
|
||||
|
||||
let totalCreated = 0
|
||||
for (const row of connected) {
|
||||
try {
|
||||
const { created } = await gmailScannerService.scanUser(row.userId)
|
||||
totalCreated += created
|
||||
} catch (err) {
|
||||
console.error('[CronGmail]', row.userId, err)
|
||||
}
|
||||
}
|
||||
|
||||
return NextResponse.json({ success: true, users: connected.length, notesCreated: totalCreated })
|
||||
}
|
||||
49
memento-note/app/api/dashboard/layout/route.ts
Normal file
49
memento-note/app/api/dashboard/layout/route.ts
Normal file
@@ -0,0 +1,49 @@
|
||||
import { NextRequest, NextResponse } from 'next/server'
|
||||
import { Prisma } from '@prisma/client'
|
||||
import { auth } from '@/auth'
|
||||
import prisma from '@/lib/prisma'
|
||||
import {
|
||||
getDefaultDashboardLayout,
|
||||
normalizeDashboardLayout,
|
||||
type DashboardLayout,
|
||||
} from '@/lib/dashboard/layout'
|
||||
|
||||
export async function GET() {
|
||||
const session = await auth()
|
||||
if (!session?.user?.id) {
|
||||
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
|
||||
}
|
||||
|
||||
const settings = await prisma.userAISettings.findUnique({
|
||||
where: { userId: session.user.id },
|
||||
select: { dashboardLayout: true },
|
||||
})
|
||||
|
||||
const layout = normalizeDashboardLayout(settings?.dashboardLayout ?? getDefaultDashboardLayout())
|
||||
return NextResponse.json({ layout })
|
||||
}
|
||||
|
||||
export async function PUT(request: NextRequest) {
|
||||
const session = await auth()
|
||||
if (!session?.user?.id) {
|
||||
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
|
||||
}
|
||||
|
||||
let body: { layout?: DashboardLayout }
|
||||
try {
|
||||
body = await request.json()
|
||||
} catch {
|
||||
return NextResponse.json({ error: 'Invalid JSON' }, { status: 400 })
|
||||
}
|
||||
|
||||
const layout = normalizeDashboardLayout(body.layout ?? getDefaultDashboardLayout())
|
||||
const layoutJson = layout as unknown as Prisma.InputJsonValue
|
||||
|
||||
await prisma.userAISettings.upsert({
|
||||
where: { userId: session.user.id },
|
||||
create: { userId: session.user.id, dashboardLayout: layoutJson },
|
||||
update: { dashboardLayout: layoutJson },
|
||||
})
|
||||
|
||||
return NextResponse.json({ layout, ok: true })
|
||||
}
|
||||
@@ -56,6 +56,8 @@ export async function GET(request: NextRequest) {
|
||||
labelRelations: { select: { id: true } },
|
||||
notebook: { select: { id: true, name: true } },
|
||||
},
|
||||
take: 500,
|
||||
orderBy: { updatedAt: 'desc' },
|
||||
})
|
||||
|
||||
if (notes.length === 0) return NextResponse.json({ nodes: [], edges: [] })
|
||||
|
||||
38
memento-note/app/api/integrations/gmail/callback/route.ts
Normal file
38
memento-note/app/api/integrations/gmail/callback/route.ts
Normal file
@@ -0,0 +1,38 @@
|
||||
import { NextRequest, NextResponse } from 'next/server'
|
||||
import { getGoogleOAuthCredentials, readIntegrationMeta, writeIntegrationMeta } from '@/lib/integrations/google-integration-tokens'
|
||||
|
||||
export async function GET(req: NextRequest) {
|
||||
const url = new URL(req.url)
|
||||
const code = url.searchParams.get('code')
|
||||
const userId = url.searchParams.get('state')
|
||||
const error = url.searchParams.get('error')
|
||||
|
||||
if (error || !code || !userId) {
|
||||
return NextResponse.redirect(`${url.origin}/settings/integrations?error=gmail_auth_failed`)
|
||||
}
|
||||
|
||||
const { clientId, clientSecret } = getGoogleOAuthCredentials()
|
||||
const tokenRes = await fetch('https://oauth2.googleapis.com/token', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
|
||||
body: new URLSearchParams({
|
||||
client_id: clientId,
|
||||
client_secret: clientSecret,
|
||||
code,
|
||||
redirect_uri: `${url.origin}/api/integrations/gmail/callback`,
|
||||
grant_type: 'authorization_code',
|
||||
}),
|
||||
})
|
||||
|
||||
const tokenData = await tokenRes.json()
|
||||
if (!tokenData.access_token) {
|
||||
return NextResponse.redirect(`${url.origin}/settings/integrations?error=gmail_token_failed`)
|
||||
}
|
||||
|
||||
const meta = await readIntegrationMeta(userId)
|
||||
meta.gmailAccessToken = tokenData.access_token
|
||||
if (tokenData.refresh_token) meta.gmailRefreshToken = tokenData.refresh_token
|
||||
await writeIntegrationMeta(userId, meta)
|
||||
|
||||
return NextResponse.redirect(`${url.origin}/settings/integrations?connected=gmail`)
|
||||
}
|
||||
67
memento-note/app/api/integrations/gmail/route.ts
Normal file
67
memento-note/app/api/integrations/gmail/route.ts
Normal file
@@ -0,0 +1,67 @@
|
||||
/**
|
||||
* Google Gmail Integration (OAuth + scan trigger)
|
||||
*/
|
||||
|
||||
import { NextRequest, NextResponse } from 'next/server'
|
||||
import { auth } from '@/auth'
|
||||
import {
|
||||
getGoogleOAuthCredentials,
|
||||
getGoogleTokens,
|
||||
readIntegrationMeta,
|
||||
writeIntegrationMeta,
|
||||
} from '@/lib/integrations/google-integration-tokens'
|
||||
import { gmailScannerService } from '@/lib/integrations/gmail-scanner.service'
|
||||
|
||||
const GMAIL_SCOPE = 'https://www.googleapis.com/auth/gmail.readonly'
|
||||
const GOOGLE_AUTH_URL = 'https://accounts.google.com/o/oauth2/v2/auth'
|
||||
|
||||
function redirectUri(origin: string) {
|
||||
return `${origin}/api/integrations/gmail/callback`
|
||||
}
|
||||
|
||||
export async function GET(req: NextRequest) {
|
||||
const session = await auth()
|
||||
if (!session?.user?.id) {
|
||||
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
|
||||
}
|
||||
|
||||
const url = new URL(req.url)
|
||||
const userId = session.user.id
|
||||
|
||||
if (url.searchParams.get('connect') === '1') {
|
||||
const { clientId } = getGoogleOAuthCredentials()
|
||||
if (!clientId) {
|
||||
return NextResponse.json({ error: 'Google OAuth not configured' }, { status: 503 })
|
||||
}
|
||||
const authUrl = new URL(GOOGLE_AUTH_URL)
|
||||
authUrl.searchParams.set('client_id', clientId)
|
||||
authUrl.searchParams.set('redirect_uri', redirectUri(url.origin))
|
||||
authUrl.searchParams.set('response_type', 'code')
|
||||
authUrl.searchParams.set('scope', GMAIL_SCOPE)
|
||||
authUrl.searchParams.set('access_type', 'offline')
|
||||
authUrl.searchParams.set('prompt', 'consent')
|
||||
authUrl.searchParams.set('state', userId)
|
||||
return NextResponse.redirect(authUrl.toString())
|
||||
}
|
||||
|
||||
if (url.searchParams.get('scan') === '1') {
|
||||
const result = await gmailScannerService.scanUser(userId)
|
||||
return NextResponse.json(result)
|
||||
}
|
||||
|
||||
const status = await gmailScannerService.getStatus(userId)
|
||||
return NextResponse.json(status)
|
||||
}
|
||||
|
||||
export async function DELETE() {
|
||||
const session = await auth()
|
||||
if (!session?.user?.id) {
|
||||
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
|
||||
}
|
||||
|
||||
const meta = await readIntegrationMeta(session.user.id)
|
||||
delete meta.gmailAccessToken
|
||||
delete meta.gmailRefreshToken
|
||||
await writeIntegrationMeta(session.user.id, meta)
|
||||
return NextResponse.json({ success: true })
|
||||
}
|
||||
@@ -1,17 +1,64 @@
|
||||
import { NextRequest, NextResponse } from 'next/server'
|
||||
import { auth } from '@/auth'
|
||||
import { redis } from '@/lib/redis'
|
||||
|
||||
export async function GET(req: NextRequest) {
|
||||
const session = await auth()
|
||||
if (!session?.user?.id) {
|
||||
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
|
||||
}
|
||||
|
||||
const url = req.nextUrl.searchParams.get('url')
|
||||
if (!url) {
|
||||
return NextResponse.json({ error: 'Missing url' }, { status: 400 })
|
||||
}
|
||||
|
||||
const cacheKey = `linkpreview:${session.user.id}:${Buffer.from(url).toString('base64url').slice(0, 80)}`
|
||||
try {
|
||||
const cached = await redis.get(cacheKey)
|
||||
if (cached) {
|
||||
return NextResponse.json(JSON.parse(cached), {
|
||||
headers: { 'Cache-Control': 'public, s-maxage=86400' },
|
||||
})
|
||||
}
|
||||
} catch {}
|
||||
|
||||
try {
|
||||
const parsed = new URL(url)
|
||||
if (!['http:', 'https:'].includes(parsed.protocol)) {
|
||||
return NextResponse.json({ error: 'Invalid protocol' }, { status: 400 })
|
||||
}
|
||||
|
||||
const hostname = parsed.hostname
|
||||
if (
|
||||
hostname === 'localhost' ||
|
||||
hostname === '127.0.0.1' ||
|
||||
hostname.startsWith('10.') ||
|
||||
hostname.startsWith('192.168.') ||
|
||||
hostname.startsWith('169.254.') ||
|
||||
hostname.startsWith('172.16.') ||
|
||||
hostname.startsWith('172.17.') ||
|
||||
hostname.startsWith('172.18.') ||
|
||||
hostname.startsWith('172.19.') ||
|
||||
hostname.startsWith('172.20.') ||
|
||||
hostname.startsWith('172.21.') ||
|
||||
hostname.startsWith('172.22.') ||
|
||||
hostname.startsWith('172.23.') ||
|
||||
hostname.startsWith('172.24.') ||
|
||||
hostname.startsWith('172.25.') ||
|
||||
hostname.startsWith('172.26.') ||
|
||||
hostname.startsWith('172.27.') ||
|
||||
hostname.startsWith('172.28.') ||
|
||||
hostname.startsWith('172.29.') ||
|
||||
hostname.startsWith('172.30.') ||
|
||||
hostname.startsWith('172.31.') ||
|
||||
hostname === '0.0.0.0' ||
|
||||
hostname.endsWith('.local') ||
|
||||
hostname.endsWith('.internal')
|
||||
) {
|
||||
return NextResponse.json({ error: 'Blocked' }, { status: 403 })
|
||||
}
|
||||
|
||||
const controller = new AbortController()
|
||||
const timeout = setTimeout(() => controller.abort(), 8000)
|
||||
|
||||
@@ -33,6 +80,8 @@ export async function GET(req: NextRequest) {
|
||||
const html = await res.text()
|
||||
const data = extractMetadata(html, parsed)
|
||||
|
||||
try { await redis.setex(cacheKey, 300, JSON.stringify(data)) } catch {}
|
||||
|
||||
return NextResponse.json(data, {
|
||||
headers: { 'Cache-Control': 'public, s-maxage=86400' },
|
||||
})
|
||||
|
||||
@@ -7,13 +7,14 @@ export const dynamic = 'force-dynamic'
|
||||
export async function GET(req: Request) {
|
||||
// Secure endpoint with bearer token (METRICS_TOKEN env var)
|
||||
const metricsToken = process.env.METRICS_TOKEN
|
||||
if (metricsToken) {
|
||||
if (!metricsToken) {
|
||||
return new NextResponse('Unauthorized', { status: 401 })
|
||||
}
|
||||
const authHeader = req.headers.get('authorization') ?? ''
|
||||
const token = authHeader.startsWith('Bearer ') ? authHeader.slice(7) : ''
|
||||
if (token !== metricsToken) {
|
||||
return new NextResponse('Unauthorized', { status: 401 })
|
||||
}
|
||||
}
|
||||
|
||||
const lines: string[] = []
|
||||
|
||||
|
||||
@@ -11,7 +11,7 @@ const MODE_MAP: Record<string, 'clarify' | 'shorten' | 'improveStyle' | 'fix_gra
|
||||
}
|
||||
|
||||
export async function POST(req: NextRequest) {
|
||||
const userId = getMobileUserId(req)
|
||||
const userId = await getMobileUserId(req)
|
||||
if (!userId) return NextResponse.json({ error: 'Non autorisé' }, { status: 401 })
|
||||
|
||||
const { text, mode = 'improve' } = await req.json().catch(() => ({}))
|
||||
|
||||
@@ -5,7 +5,7 @@ import { getSystemConfig } from '@/lib/config'
|
||||
import { reserveUsageOrThrow, QuotaExceededError } from '@/lib/entitlements'
|
||||
|
||||
export async function POST(req: NextRequest) {
|
||||
const userId = getMobileUserId(req)
|
||||
const userId = await getMobileUserId(req)
|
||||
if (!userId) return NextResponse.json({ error: 'Non autorisé' }, { status: 401 })
|
||||
|
||||
const { content } = await req.json().catch(() => ({}))
|
||||
|
||||
@@ -3,7 +3,7 @@ import { getMobileUserId } from '@/lib/mobile-auth'
|
||||
import { getSystemConfig } from '@/lib/config'
|
||||
|
||||
export async function POST(req: NextRequest) {
|
||||
const userId = getMobileUserId(req)
|
||||
const userId = await getMobileUserId(req)
|
||||
if (!userId) return NextResponse.json({ error: 'Non autorisé' }, { status: 401 })
|
||||
|
||||
const formData = await req.formData().catch(() => null)
|
||||
|
||||
19
memento-note/app/api/mobile/auth/logout/route.ts
Normal file
19
memento-note/app/api/mobile/auth/logout/route.ts
Normal file
@@ -0,0 +1,19 @@
|
||||
import { NextResponse } from 'next/server'
|
||||
import { getMobileUserId } from '@/lib/mobile-auth'
|
||||
import { redis } from '@/lib/redis'
|
||||
|
||||
export async function POST(req: Request) {
|
||||
const userId = await getMobileUserId(req)
|
||||
if (!userId) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
|
||||
|
||||
const auth = req.headers.get('Authorization') ?? ''
|
||||
const token = auth.startsWith('Bearer ') ? auth.slice(7) : ''
|
||||
|
||||
if (token) {
|
||||
try {
|
||||
await redis.setex(`mobile:revoked:${token}`, 90 * 24 * 60 * 60, '1')
|
||||
} catch {}
|
||||
}
|
||||
|
||||
return NextResponse.json({ success: true })
|
||||
}
|
||||
@@ -3,7 +3,7 @@ import prisma from '@/lib/prisma'
|
||||
import { getMobileUserId } from '@/lib/mobile-auth'
|
||||
|
||||
export async function GET(req: NextRequest) {
|
||||
const userId = getMobileUserId(req)
|
||||
const userId = await getMobileUserId(req)
|
||||
if (!userId) return NextResponse.json({ error: 'Non autorisé' }, { status: 401 })
|
||||
|
||||
const user = await prisma.user.findUnique({
|
||||
|
||||
@@ -3,7 +3,7 @@ import prisma from '@/lib/prisma'
|
||||
import { getMobileUserId } from '@/lib/mobile-auth'
|
||||
|
||||
export async function GET(req: NextRequest) {
|
||||
const userId = getMobileUserId(req)
|
||||
const userId = await getMobileUserId(req)
|
||||
if (!userId) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
|
||||
|
||||
const now = new Date()
|
||||
|
||||
@@ -6,7 +6,7 @@ import { stripHtmlToText } from '@/lib/flashcards/deck-utils'
|
||||
import { reserveUsageOrThrow, QuotaExceededError } from '@/lib/entitlements'
|
||||
|
||||
export async function POST(req: NextRequest) {
|
||||
const userId = getMobileUserId(req)
|
||||
const userId = await getMobileUserId(req)
|
||||
if (!userId) return NextResponse.json({ error: 'Non autorisé' }, { status: 401 })
|
||||
|
||||
const body = await req.json().catch(() => ({}))
|
||||
|
||||
@@ -4,7 +4,7 @@ import { getMobileUserId } from '@/lib/mobile-auth'
|
||||
import { computeSm2Update } from '@/lib/flashcards/sm2'
|
||||
|
||||
export async function POST(req: NextRequest) {
|
||||
const userId = getMobileUserId(req)
|
||||
const userId = await getMobileUserId(req)
|
||||
if (!userId) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
|
||||
|
||||
const body = await req.json()
|
||||
|
||||
@@ -3,7 +3,7 @@ import prisma from '@/lib/prisma'
|
||||
import { getMobileUserId } from '@/lib/mobile-auth'
|
||||
|
||||
export async function GET(req: NextRequest) {
|
||||
const userId = getMobileUserId(req)
|
||||
const userId = await getMobileUserId(req)
|
||||
if (!userId) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
|
||||
|
||||
const { searchParams } = new URL(req.url)
|
||||
|
||||
@@ -3,7 +3,7 @@ import prisma from '@/lib/prisma'
|
||||
import { getMobileUserId } from '@/lib/mobile-auth'
|
||||
|
||||
export async function GET(req: NextRequest) {
|
||||
const userId = getMobileUserId(req)
|
||||
const userId = await getMobileUserId(req)
|
||||
if (!userId) return NextResponse.json({ error: 'Non autorisé' }, { status: 401 })
|
||||
|
||||
const notebooks = await prisma.notebook.findMany({
|
||||
|
||||
@@ -6,7 +6,7 @@ export async function GET(
|
||||
req: NextRequest,
|
||||
{ params }: { params: Promise<{ id: string }> }
|
||||
) {
|
||||
const userId = getMobileUserId(req)
|
||||
const userId = await getMobileUserId(req)
|
||||
if (!userId) return NextResponse.json({ error: 'Non autorisé' }, { status: 401 })
|
||||
|
||||
const { id } = await params
|
||||
@@ -33,7 +33,7 @@ export async function PUT(
|
||||
req: NextRequest,
|
||||
{ params }: { params: Promise<{ id: string }> }
|
||||
) {
|
||||
const userId = getMobileUserId(req)
|
||||
const userId = await getMobileUserId(req)
|
||||
if (!userId) return NextResponse.json({ error: 'Non autorisé' }, { status: 401 })
|
||||
|
||||
const { id } = await params
|
||||
@@ -61,7 +61,7 @@ export async function DELETE(
|
||||
req: NextRequest,
|
||||
{ params }: { params: Promise<{ id: string }> }
|
||||
) {
|
||||
const userId = getMobileUserId(req)
|
||||
const userId = await getMobileUserId(req)
|
||||
if (!userId) return NextResponse.json({ error: 'Non autorisé' }, { status: 401 })
|
||||
|
||||
const { id } = await params
|
||||
|
||||
@@ -19,7 +19,7 @@ function getTodayContent(title: string): string {
|
||||
}
|
||||
|
||||
export async function GET(req: NextRequest) {
|
||||
const userId = getMobileUserId(req)
|
||||
const userId = await getMobileUserId(req)
|
||||
if (!userId) return NextResponse.json({ error: 'Non autorisé' }, { status: 401 })
|
||||
|
||||
const todayKey = getTodayKey()
|
||||
|
||||
@@ -3,7 +3,7 @@ import prisma from '@/lib/prisma'
|
||||
import { getMobileUserId } from '@/lib/mobile-auth'
|
||||
|
||||
export async function GET(req: NextRequest) {
|
||||
const userId = getMobileUserId(req)
|
||||
const userId = await getMobileUserId(req)
|
||||
if (!userId) return NextResponse.json({ error: 'Non autorisé' }, { status: 401 })
|
||||
|
||||
const { searchParams } = new URL(req.url)
|
||||
@@ -43,7 +43,7 @@ export async function GET(req: NextRequest) {
|
||||
}
|
||||
|
||||
export async function POST(req: NextRequest) {
|
||||
const userId = getMobileUserId(req)
|
||||
const userId = await getMobileUserId(req)
|
||||
if (!userId) return NextResponse.json({ error: 'Non autorisé' }, { status: 401 })
|
||||
|
||||
const { title, content, notebookId } = await req.json().catch(() => ({}))
|
||||
|
||||
@@ -3,7 +3,7 @@ import prisma from '@/lib/prisma'
|
||||
import { getMobileUserId } from '@/lib/mobile-auth'
|
||||
|
||||
export async function GET(req: NextRequest) {
|
||||
const userId = getMobileUserId(req)
|
||||
const userId = await getMobileUserId(req)
|
||||
if (!userId) return NextResponse.json({ error: 'Non autorisé' }, { status: 401 })
|
||||
|
||||
const { searchParams } = new URL(req.url)
|
||||
|
||||
@@ -91,7 +91,7 @@ export async function PATCH(
|
||||
if (color !== undefined) updateData.color = color
|
||||
if (order !== undefined) updateData.order = order
|
||||
if (trashedAt !== undefined) updateData.trashedAt = trashedAt ? new Date(trashedAt) : null
|
||||
if (parentId !== undefined) updateData.parentId = parentId
|
||||
if (parentId !== undefined) updateData.parent = parentId ? { connect: { id: parentId } } : { disconnect: true }
|
||||
|
||||
if (trashedAt !== undefined) {
|
||||
const descendantIds = await getDescendantIds(id)
|
||||
|
||||
@@ -66,13 +66,13 @@ export async function GET(
|
||||
console.error('[network] NoteLink query failed:', err)
|
||||
}
|
||||
|
||||
const mapBacklink = (bl: (typeof backlinks)[number]) => ({
|
||||
const mapBacklink = (bl: any) => ({
|
||||
id: bl.id,
|
||||
note: bl.sourceNote,
|
||||
contextSnippet: bl.contextSnippet,
|
||||
createdAt: bl.createdAt,
|
||||
})
|
||||
const mapOutbound = (ol: (typeof outbound)[number]) => ({
|
||||
const mapOutbound = (ol: any) => ({
|
||||
id: ol.id,
|
||||
note: ol.targetNote,
|
||||
contextSnippet: ol.contextSnippet,
|
||||
|
||||
@@ -160,7 +160,7 @@ export async function POST(req: NextRequest) {
|
||||
links: n.links ?? undefined,
|
||||
trashedAt: parseDate(n.trashedAt),
|
||||
notebookId: n.notebookId ?? null,
|
||||
contentUpdatedAt: parseDate(n.contentUpdatedAt),
|
||||
contentUpdatedAt: parseDate(n.contentUpdatedAt) ?? undefined,
|
||||
updatedAt: new Date(),
|
||||
labelRelations: {
|
||||
set: validLabelIds.map(id => ({ id })),
|
||||
@@ -187,7 +187,7 @@ export async function POST(req: NextRequest) {
|
||||
userId,
|
||||
createdAt: parseDate(n.createdAt) ?? new Date(),
|
||||
updatedAt: parseDate(n.updatedAt) ?? new Date(),
|
||||
contentUpdatedAt: parseDate(n.contentUpdatedAt),
|
||||
contentUpdatedAt: parseDate(n.contentUpdatedAt) ?? undefined,
|
||||
labelRelations: {
|
||||
connect: validLabelIds.map(id => ({ id })),
|
||||
},
|
||||
@@ -211,7 +211,7 @@ export async function POST(req: NextRequest) {
|
||||
userId,
|
||||
createdAt: parseDate(n.createdAt) ?? new Date(),
|
||||
updatedAt: parseDate(n.updatedAt) ?? new Date(),
|
||||
contentUpdatedAt: parseDate(n.contentUpdatedAt),
|
||||
contentUpdatedAt: parseDate(n.contentUpdatedAt) ?? undefined,
|
||||
},
|
||||
})
|
||||
stats.notes++
|
||||
|
||||
@@ -17,7 +17,7 @@ export async function POST(request: NextRequest) {
|
||||
// Store as a notification to the note owner + admin
|
||||
await prisma.notification.create({
|
||||
data: {
|
||||
userId: note.userId,
|
||||
userId: note.userId!,
|
||||
type: 'content_report',
|
||||
title: `Signalement : ${reason}`,
|
||||
message: details || `Un visiteur a signalé votre note publiée pour: ${reason}`,
|
||||
|
||||
@@ -149,8 +149,8 @@ export async function PUT(request: NextRequest) {
|
||||
if (content !== undefined) updateData.content = content
|
||||
if (color !== undefined) updateData.color = color
|
||||
if (type !== undefined) updateData.type = type
|
||||
if (checkItems !== undefined) updateData.checkItems = checkItems ?? null
|
||||
if (labels !== undefined) updateData.labels = labels ?? null
|
||||
if (checkItems !== undefined) updateData.checkItems = checkItems != null ? JSON.stringify(checkItems) : null
|
||||
if (labels !== undefined) updateData.labels = labels != null ? JSON.stringify(labels) : null
|
||||
if (isPinned !== undefined) updateData.isPinned = isPinned
|
||||
if (isArchived !== undefined) updateData.isArchived = isArchived
|
||||
if (images !== undefined) updateData.images = images ?? null
|
||||
|
||||
@@ -45,7 +45,6 @@ export async function GET(request: NextRequest) {
|
||||
try {
|
||||
const result: FetchModelsResult = await fetchLiveModelsForProvider(provider, apiKey, baseUrl);
|
||||
|
||||
console.log(`[verify] ${provider}: fromApi=${result.fromApi}, models=${result.models.length}`, result.models);
|
||||
|
||||
// Only consider key valid if we got models from the REAL API (not fallbacks)
|
||||
// Exception: Anthropic/Google/custom don't guarantee public /models endpoints, so we accept fallbacks for them
|
||||
|
||||
@@ -161,7 +161,7 @@ export async function GET() {
|
||||
})),
|
||||
brainstorms: brainstorms.map((b) => ({
|
||||
id: b.id,
|
||||
title: b.title,
|
||||
title: b.seedIdea,
|
||||
createdAt: b.createdAt,
|
||||
ideasCount: b.ideas.length,
|
||||
})),
|
||||
@@ -196,9 +196,9 @@ export async function GET() {
|
||||
|
||||
const canvasFolder = zip.folder('canvases')!
|
||||
for (const brainstorm of brainstorms) {
|
||||
const fileBase = uniqueBaseName(brainstorm.title || 'Untitled Brainstorm', brainstorm.id)
|
||||
const fileBase = uniqueBaseName(brainstorm.seedIdea || 'Untitled Brainstorm', brainstorm.id)
|
||||
|
||||
let canvasMd = `# Brainstorm Canvas: ${brainstorm.title || 'Untitled'}\n\n`
|
||||
let canvasMd = `# Brainstorm Canvas: ${brainstorm.seedIdea || 'Untitled'}\n\n`
|
||||
canvasMd += `- **Created At:** ${brainstorm.createdAt.toISOString()}\n`
|
||||
canvasMd += `- **Updated At:** ${brainstorm.updatedAt.toISOString()}\n`
|
||||
canvasMd += `- **Ideas Count:** ${brainstorm.ideas.length}\n\n`
|
||||
@@ -232,7 +232,7 @@ export async function GET() {
|
||||
}))
|
||||
|
||||
const offlineCanvases = brainstorms.map((b) => ({
|
||||
title: b.title || 'Untitled Brainstorm',
|
||||
title: b.seedIdea || 'Untitled Brainstorm',
|
||||
createdAt: b.createdAt.toISOString(),
|
||||
ideas: b.ideas.map((i) => ({
|
||||
title: i.title,
|
||||
@@ -499,7 +499,7 @@ export async function GET() {
|
||||
const zipBuffer = await zip.generateAsync({ type: 'nodebuffer' })
|
||||
|
||||
const dateString = new Date().toISOString().split('T')[0]
|
||||
return new NextResponse(zipBuffer, {
|
||||
return new NextResponse(new Uint8Array(zipBuffer) as BodyInit, {
|
||||
headers: {
|
||||
'Content-Type': 'application/zip',
|
||||
'Content-Disposition': `attachment; filename="memento-workspace-export-${dateString}.zip"`,
|
||||
|
||||
@@ -6,6 +6,25 @@
|
||||
|
||||
@custom-variant dark (&:is(.dark *));
|
||||
|
||||
/* ── Global UX fixes (UI/UX Pro Max audit) ────────────────────────────── */
|
||||
|
||||
/* CRITICAL: prefers-reduced-motion — désactive toutes les animations */
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
*, *::before, *::after {
|
||||
animation-duration: 0.01ms !important;
|
||||
animation-iteration-count: 1 !important;
|
||||
transition-duration: 0.01ms !important;
|
||||
scroll-behavior: auto !important;
|
||||
}
|
||||
}
|
||||
|
||||
/* CRITICAL: focus-visible ring global sur tous les éléments interactifs */
|
||||
:focus-visible {
|
||||
outline: 2px solid var(--color-brand-accent);
|
||||
outline-offset: 2px;
|
||||
border-radius: 4px;
|
||||
}
|
||||
|
||||
/* Custom breakpoints for desktop design (matching code.html reference) */
|
||||
@theme {
|
||||
/* Desktop breakpoints: 1024px (min), 1440px (large), 1920px (ultra-wide) */
|
||||
|
||||
@@ -97,7 +97,7 @@ export default async function RootLayout({
|
||||
data-server-accent={serverAccent}
|
||||
style={htmlStyle}
|
||||
>
|
||||
<body className={`${inter.className} ${inter.variable} ${manrope.variable} ${playfair.variable} ${jetbrainsMono.variable}`}>
|
||||
<body className={`${inter.className} ${inter.variable} ${manrope.variable} ${playfair.variable} ${jetbrainsMono.variable} h-screen overflow-hidden`}>
|
||||
<Script id="theme-init" src="/scripts/theme-init.js" strategy="beforeInteractive" />
|
||||
<Script id="direction-init" src="/scripts/direction-init.js" strategy="beforeInteractive" />
|
||||
<Script id="sw-cleanup" src="/scripts/sw-cleanup.js" strategy="afterInteractive" />
|
||||
@@ -107,7 +107,7 @@ export default async function RootLayout({
|
||||
<ThemeInitializer theme={userSettings.theme} fontSize={aiSettings.fontSize} fontFamily={aiSettings.fontFamily} accentColor={userSettings.accentColor} />
|
||||
{children}
|
||||
<LanguageProvider initialLanguage="en">
|
||||
<CookieConsentRoot initialAnonymousAnalytics={aiSettings?.anonymousAnalytics} />
|
||||
<CookieConsentRoot />
|
||||
</LanguageProvider>
|
||||
<Toaster />
|
||||
</SessionProviderWrapper>
|
||||
|
||||
@@ -24,14 +24,14 @@ const PROVIDER_INFO: Record<string, { name: string; hint: string }> = {
|
||||
minimax: { name: 'MiniMax', hint: 'MiniMax-M2.7, M2.5' },
|
||||
google: { name: 'Google AI', hint: 'Gemini 1.5 Flash, Pro' },
|
||||
deepseek: { name: 'DeepSeek', hint: 'DeepSeek Chat, Reasoner' },
|
||||
openrouter: { name: 'OpenRouter', hint: 'Accès multi-fournisseurs' },
|
||||
openrouter: { name: 'OpenRouter', hint: 'Multi-provider access' },
|
||||
mistral: { name: 'Mistral AI', hint: 'Mistral Small, Large' },
|
||||
glm: { name: 'GLM (Zhipu)', hint: 'GLM-4, GLM-4-Flash' },
|
||||
zai: { name: 'Zuki Journey', hint: 'Proxy OpenAI/Anthropic' },
|
||||
anthropic_custom: { name: 'Anthropic (custom)', hint: 'Proxy compatible Anthropic' },
|
||||
custom_openai: { name: 'Compatible OpenAI', hint: 'Tout proxy compatible OpenAI' },
|
||||
custom_anthropic: { name: 'Compatible Anthropic', hint: 'Tout proxy compatible Anthropic' },
|
||||
custom: { name: 'API personnalisée', hint: 'Votre propre endpoint' },
|
||||
zai: { name: 'Zuki Journey', hint: 'OpenAI/Anthropic proxy' },
|
||||
anthropic_custom: { name: 'Anthropic (custom)', hint: 'Anthropic-compatible proxy' },
|
||||
custom_openai: { name: 'Compatible OpenAI', hint: 'Any OpenAI-compatible proxy' },
|
||||
custom_anthropic: { name: 'Compatible Anthropic', hint: 'Any Anthropic-compatible proxy' },
|
||||
custom: { name: 'Custom API', hint: 'Your own endpoint' },
|
||||
}
|
||||
|
||||
function displayName(provider: string): string {
|
||||
@@ -59,7 +59,7 @@ type SavedKey = {
|
||||
|
||||
async function loadKeys(): Promise<{ keys: SavedKey[]; allowedProviders: string[] }> {
|
||||
const res = await fetch('/api/user/api-keys')
|
||||
if (!res.ok) throw new Error('Erreur de chargement')
|
||||
if (!res.ok) throw new Error('Failed to load')
|
||||
return res.json()
|
||||
}
|
||||
|
||||
@@ -92,6 +92,8 @@ function EditKeyForm({
|
||||
const [testing, setTesting] = useState(false)
|
||||
const [testResult, setTestResult] = useState<{ ok: boolean; latency?: number; reply?: string; error?: string } | null>(null)
|
||||
|
||||
const { t } = useLanguage()
|
||||
|
||||
const needsUrl = NEEDS_BASE_URL.has(savedKey.provider)
|
||||
const manualModel = MANUAL_MODEL_PROVIDERS.has(savedKey.provider)
|
||||
|
||||
@@ -118,10 +120,10 @@ function EditKeyForm({
|
||||
body: JSON.stringify(payload),
|
||||
})
|
||||
const body = await res.json().catch(() => ({}))
|
||||
if (!res.ok) throw new Error(body.message ?? body.error ?? 'Échec')
|
||||
if (!res.ok) throw new Error(body.message ?? body.error ?? t('common.error'))
|
||||
},
|
||||
onSuccess: () => {
|
||||
toast.success(`${displayName(savedKey.provider)} mis à jour ✓`)
|
||||
toast.success(t('byok.updated', { name: displayName(savedKey.provider) }))
|
||||
onInvalidate()
|
||||
onDone()
|
||||
},
|
||||
@@ -132,7 +134,7 @@ function EditKeyForm({
|
||||
const keyToUse = newKey.length >= 8 ? newKey : ''
|
||||
if (!keyToUse && !model) return
|
||||
if (!keyToUse) {
|
||||
toast.info('Pour tester, entrez la clé API dans le champ "Nouvelle clé"')
|
||||
toast.info(t('byok.testHint'))
|
||||
return
|
||||
}
|
||||
setTesting(true)
|
||||
@@ -143,7 +145,7 @@ function EditKeyForm({
|
||||
const res = await fetch(`/api/user/api-keys/test-model?${q}`)
|
||||
setTestResult(await res.json())
|
||||
} catch {
|
||||
setTestResult({ ok: false, error: 'Impossible de contacter le serveur' })
|
||||
setTestResult({ ok: false, error: t('byok.contactError') })
|
||||
} finally {
|
||||
setTesting(false)
|
||||
}
|
||||
@@ -155,18 +157,18 @@ function EditKeyForm({
|
||||
return (
|
||||
<div className="mt-2 border border-violet-500/20 rounded-xl bg-violet-500/5 p-4 space-y-3">
|
||||
<p className="text-[10px] font-bold uppercase tracking-widest text-violet-600 dark:text-violet-400">
|
||||
Modifier — {displayName(savedKey.provider)}
|
||||
{t('byok.editLabel', { name: displayName(savedKey.provider) })}
|
||||
</p>
|
||||
|
||||
{/* Alias */}
|
||||
<div className="grid gap-3 sm:grid-cols-2">
|
||||
<div className="space-y-1">
|
||||
<Label htmlFor={`edit-alias-${savedKey.provider}`} className="text-[9px] font-semibold uppercase tracking-widest text-concrete">Alias</Label>
|
||||
<Input id={`edit-alias-${savedKey.provider}`} value={alias} onChange={(e) => setAlias(e.target.value)} placeholder="ex. Ma clé pro" />
|
||||
<Label htmlFor={`edit-alias-${savedKey.provider}`} className="text-[9px] font-semibold uppercase tracking-widest text-concrete">{t('byok.aliasLabel')}</Label>
|
||||
<Input id={`edit-alias-${savedKey.provider}`} value={alias} onChange={(e) => setAlias(e.target.value)} placeholder={t('byok.aliasPlaceholder')} />
|
||||
</div>
|
||||
{needsUrl && (
|
||||
<div className="space-y-1">
|
||||
<Label htmlFor={`edit-baseurl-${savedKey.provider}`} className="text-[9px] font-semibold uppercase tracking-widest text-concrete">URL de l'API</Label>
|
||||
<Label htmlFor={`edit-baseurl-${savedKey.provider}`} className="text-[9px] font-semibold uppercase tracking-widest text-concrete">{t('byok.apiUrl')}</Label>
|
||||
<Input id={`edit-baseurl-${savedKey.provider}`} value={baseUrl} onChange={(e) => setBaseUrl(e.target.value.trim())} placeholder="https://api.example.com/v1" />
|
||||
</div>
|
||||
)}
|
||||
@@ -174,21 +176,21 @@ function EditKeyForm({
|
||||
|
||||
{/* Model */}
|
||||
<div className="space-y-1">
|
||||
<Label htmlFor={`edit-model-${savedKey.provider}`} className="text-[9px] font-semibold uppercase tracking-widest text-concrete">Modèle</Label>
|
||||
<Label htmlFor={`edit-model-${savedKey.provider}`} className="text-[9px] font-semibold uppercase tracking-widest text-concrete">{t('byok.model')}</Label>
|
||||
{showModelDropdown ? (
|
||||
<Select value={model} onValueChange={setModel}>
|
||||
<SelectTrigger id={`edit-model-${savedKey.provider}`}><SelectValue placeholder="Choisir..." /></SelectTrigger>
|
||||
<SelectTrigger id={`edit-model-${savedKey.provider}`}><SelectValue placeholder={t('byok.choose')} /></SelectTrigger>
|
||||
<SelectContent>{models.map((m) => <SelectItem key={m} value={m}>{m}</SelectItem>)}</SelectContent>
|
||||
</Select>
|
||||
) : showModelInput ? (
|
||||
<Input id={`edit-model-${savedKey.provider}`} value={model} onChange={(e) => setModel(e.target.value)} placeholder="ex. MiniMax-M2.7" />
|
||||
) : <div className="flex items-center gap-2 text-xs text-concrete py-1"><Loader2 className="h-3 w-3 animate-spin" />Chargement...</div>}
|
||||
) : <div className="flex items-center gap-2 text-xs text-concrete py-1"><Loader2 className="h-3 w-3 animate-spin" />{t('common.loading')}</div>}
|
||||
</div>
|
||||
|
||||
{/* Key rotation (optional) */}
|
||||
<div className="space-y-1">
|
||||
<Label htmlFor={`edit-key-${savedKey.provider}`} className="text-[9px] font-semibold uppercase tracking-widest text-concrete">
|
||||
Nouvelle clé API <span className="normal-case font-normal text-concrete">(laisser vide pour conserver l'actuelle)</span>
|
||||
{t('byok.newKey')} <span className="normal-case font-normal text-concrete">{t('byok.newKeyHint')}</span>
|
||||
</Label>
|
||||
<Input
|
||||
id={`edit-key-${savedKey.provider}`}
|
||||
@@ -196,7 +198,7 @@ function EditKeyForm({
|
||||
autoComplete="off"
|
||||
value={newKey}
|
||||
onChange={(e) => { setNewKey(e.target.value); setTestResult(null) }}
|
||||
placeholder="sk-... (optionnel)"
|
||||
placeholder={t('byok.keyPlaceholder')}
|
||||
/>
|
||||
</div>
|
||||
|
||||
@@ -209,8 +211,8 @@ function EditKeyForm({
|
||||
{testResult.ok ? <CheckCircle2 size={12} className="shrink-0 mt-0.5" /> : <XCircle size={12} className="shrink-0 mt-0.5" />}
|
||||
<span>
|
||||
{testResult.ok
|
||||
? `✓ Opérationnel${testResult.latency ? ` (${testResult.latency}ms)` : ''}${testResult.reply ? ` · ${testResult.reply}` : ''}`
|
||||
: testResult.error ?? 'Échec'
|
||||
? `${t('byok.operational')}${testResult.latency ? ` (${testResult.latency}ms)` : ''}${testResult.reply ? ` · ${testResult.reply}` : ''}`
|
||||
: testResult.error ?? t('common.error')
|
||||
}
|
||||
</span>
|
||||
</div>
|
||||
@@ -225,7 +227,7 @@ function EditKeyForm({
|
||||
className="flex items-center gap-1.5 px-3 py-2 rounded-lg text-[9px] font-bold uppercase tracking-[0.1em] border border-border bg-white dark:bg-white/5 hover:border-violet-400 transition-colors disabled:opacity-40 disabled:pointer-events-none"
|
||||
>
|
||||
{testing ? <Loader2 size={11} className="animate-spin" /> : <FlaskConical size={11} />}
|
||||
Tester
|
||||
{t('byok.test')}
|
||||
</button>
|
||||
<Button
|
||||
type="button"
|
||||
@@ -233,7 +235,7 @@ function EditKeyForm({
|
||||
onClick={() => saveMutation.mutate()}
|
||||
className="flex-1 py-2 rounded-lg text-[9px] font-bold uppercase tracking-[0.12em] bg-ink text-paper shadow hover:scale-[1.01] active:scale-[0.99] transition-all disabled:opacity-40"
|
||||
>
|
||||
{saveMutation.isPending ? <Loader2 className="h-3.5 w-3.5 animate-spin" /> : 'Enregistrer les modifications'}
|
||||
{saveMutation.isPending ? <Loader2 className="h-3.5 w-3.5 animate-spin" /> : t('byok.saveChanges')}
|
||||
</Button>
|
||||
<button
|
||||
type="button"
|
||||
@@ -305,7 +307,7 @@ export function ByokSettingsPanel() {
|
||||
|
||||
async function verifyKey() {
|
||||
if (!provider || apiKey.length < 8) return
|
||||
if (NEEDS_BASE_URL.has(provider) && !baseUrl) { toast.error("Veuillez renseigner l'URL de l'API"); return }
|
||||
if (NEEDS_BASE_URL.has(provider) && !baseUrl) { toast.error(t('byok.baseUrlRequired')); return }
|
||||
setVerifying(true)
|
||||
setTestResult(null)
|
||||
try {
|
||||
@@ -316,12 +318,12 @@ export function ByokSettingsPanel() {
|
||||
if (res.ok && body.valid) {
|
||||
setKeyOk(true)
|
||||
if (Array.isArray(body.models) && body.models.length > 0) { setModels(body.models); if (!model) setModel(body.models[0]) }
|
||||
toast.success('Clé API valide ✓')
|
||||
toast.success(t('byok.keyValid'))
|
||||
} else {
|
||||
setKeyOk(false)
|
||||
toast.error(body.message ?? 'Clé API invalide')
|
||||
toast.error(body.message ?? t('byok.keyInvalid'))
|
||||
}
|
||||
} catch { setKeyOk(false); toast.error('Erreur de vérification') }
|
||||
} catch { setKeyOk(false); toast.error(t('byok.verifyError')) }
|
||||
finally { setVerifying(false) }
|
||||
}
|
||||
|
||||
@@ -334,7 +336,7 @@ export function ByokSettingsPanel() {
|
||||
if (NEEDS_BASE_URL.has(provider) && baseUrl) q.append('baseUrl', baseUrl)
|
||||
const res = await fetch(`/api/user/api-keys/test-model?${q}`)
|
||||
setTestResult(await res.json())
|
||||
} catch { setTestResult({ ok: false, error: 'Impossible de contacter le serveur' }) }
|
||||
} catch { setTestResult({ ok: false, error: t('byok.contactError') }) }
|
||||
finally { setTesting(false) }
|
||||
}
|
||||
|
||||
@@ -352,10 +354,10 @@ export function ByokSettingsPanel() {
|
||||
body: JSON.stringify(payload),
|
||||
})
|
||||
const body = await res.json().catch(() => ({}))
|
||||
if (!res.ok) throw new Error(body.message ?? body.error ?? 'Échec')
|
||||
if (!res.ok) throw new Error(body.message ?? body.error ?? t('common.error'))
|
||||
},
|
||||
onSuccess: () => {
|
||||
toast.success(`Clé ${displayName(provider)} enregistrée ✓`)
|
||||
toast.success(t('byok.keySaved', { name: displayName(provider) }))
|
||||
setProvider(''); setApiKey(''); setAlias(''); setBaseUrl('')
|
||||
setModel(''); setModels([]); setKeyOk(false); setTestResult(null)
|
||||
invalidate()
|
||||
@@ -369,7 +371,7 @@ export function ByokSettingsPanel() {
|
||||
method: 'PATCH', headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ isActive }),
|
||||
})
|
||||
if (!res.ok) throw new Error('Erreur')
|
||||
if (!res.ok) throw new Error(t('common.error'))
|
||||
},
|
||||
onSuccess: invalidate,
|
||||
onError: () => toast.error(t('byokSettings.error')),
|
||||
@@ -378,9 +380,9 @@ export function ByokSettingsPanel() {
|
||||
const deleteMutation = useMutation({
|
||||
mutationFn: async (p: string) => {
|
||||
const res = await fetch(`/api/user/api-keys/${encodeURIComponent(p)}`, { method: 'DELETE' })
|
||||
if (!res.ok) throw new Error('Erreur')
|
||||
if (!res.ok) throw new Error(t('common.error'))
|
||||
},
|
||||
onSuccess: () => { toast.success('Clé supprimée'); invalidate() },
|
||||
onSuccess: () => { toast.success(t('byok.keyDeleted')); invalidate() },
|
||||
onError: () => toast.error(t('byokSettings.error')),
|
||||
})
|
||||
|
||||
@@ -417,9 +419,9 @@ export function ByokSettingsPanel() {
|
||||
: 'bg-amber-500/10 text-amber-700 dark:text-amber-400 border-amber-500/20'
|
||||
)}>
|
||||
{activeKey ? (
|
||||
<><Zap size={14} className="shrink-0" /><span>BYOK actif · <strong>{displayName(activeKey.provider)}</strong>{activeKey.model && <> · <code className="font-mono text-[10px]">{activeKey.model}</code></>}{activeKey.alias && <> · {activeKey.alias}</>}</span></>
|
||||
<><Zap size={14} className="shrink-0" /><span>{t('byok.byokActive')} · <strong>{displayName(activeKey.provider)}</strong>{activeKey.model && <> · <code className="font-mono text-[10px]">{activeKey.model}</code></>}{activeKey.alias && <> · {activeKey.alias}</>}</span></>
|
||||
) : (
|
||||
<><Shield size={14} className="shrink-0" /><span>Aucune clé active — utilisation des quotas Memento</span></>
|
||||
<><Shield size={14} className="shrink-0" /><span>{t('byok.noActiveKey')}</span></>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
@@ -431,7 +433,7 @@ export function ByokSettingsPanel() {
|
||||
{/* Saved keys */}
|
||||
{keys.length > 0 && (
|
||||
<div className="space-y-2">
|
||||
<p className="text-[10px] font-bold uppercase tracking-widest text-concrete">Clés enregistrées</p>
|
||||
<p className="text-[10px] font-bold uppercase tracking-widest text-concrete">{t('byok.savedKeys')}</p>
|
||||
<ul className="space-y-1">
|
||||
{keys.map((key) => (
|
||||
<li key={key.provider}>
|
||||
@@ -448,7 +450,7 @@ export function ByokSettingsPanel() {
|
||||
{key.model && <code className="text-[9px] font-mono text-brand-accent bg-brand-accent/10 px-1.5 py-0.5 rounded">{key.model}</code>}
|
||||
{key.alias && <span className="text-[9px] text-concrete">{key.alias}</span>}
|
||||
<span className={cn('text-[9px] font-medium', key.isActive ? 'text-emerald-600 dark:text-emerald-400' : 'text-concrete')}>
|
||||
{key.isActive ? '● Actif' : '○ Inactif'}
|
||||
{key.isActive ? t('byok.activeStatus') : t('byok.inactiveStatus')}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
@@ -481,7 +483,7 @@ export function ByokSettingsPanel() {
|
||||
type="button"
|
||||
className="h-7 w-7 rounded-lg flex items-center justify-center text-destructive/50 hover:text-destructive hover:bg-rose-50 dark:hover:bg-rose-500/10 transition-colors"
|
||||
disabled={deleteMutation.isPending}
|
||||
onClick={() => { if (confirm(`Supprimer la clé ${displayName(key.provider)} ?`)) deleteMutation.mutate(key.provider) }}
|
||||
onClick={() => { if (confirm(t('byok.confirmDelete', { name: displayName(key.provider) }))) deleteMutation.mutate(key.provider) }}
|
||||
>
|
||||
<Trash2 size={12} />
|
||||
</button>
|
||||
@@ -507,14 +509,14 @@ export function ByokSettingsPanel() {
|
||||
{/* Add key form */}
|
||||
<div className="space-y-4 border border-border/60 rounded-2xl p-5">
|
||||
<p className="text-[10px] font-bold uppercase tracking-widest text-concrete">
|
||||
{keys.length > 0 ? 'Ajouter / remplacer une clé' : 'Connecter votre fournisseur IA'}
|
||||
{keys.length > 0 ? t('byok.addOrReplace') : t('byok.connectProvider')}
|
||||
</p>
|
||||
|
||||
<div className="grid gap-4 sm:grid-cols-2">
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor="byok-provider" className="text-[10px] font-semibold uppercase tracking-widest text-concrete">Fournisseur</Label>
|
||||
<Label htmlFor="byok-provider" className="text-[10px] font-semibold uppercase tracking-widest text-concrete">{t('byokSettings.provider')}</Label>
|
||||
<Select value={provider} onValueChange={onProviderChange} disabled={saveMutation.isPending}>
|
||||
<SelectTrigger id="byok-provider"><SelectValue placeholder="Choisir un fournisseur..." /></SelectTrigger>
|
||||
<SelectTrigger id="byok-provider"><SelectValue placeholder={t('byok.chooseProvider')} /></SelectTrigger>
|
||||
<SelectContent>
|
||||
{allowed.map((p) => (
|
||||
<SelectItem key={p} value={p}>
|
||||
@@ -526,20 +528,20 @@ export function ByokSettingsPanel() {
|
||||
</Select>
|
||||
</div>
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor="byok-alias" className="text-[10px] font-semibold uppercase tracking-widest text-concrete">Alias <span className="normal-case font-normal">(optionnel)</span></Label>
|
||||
<Input id="byok-alias" value={alias} onChange={(e) => setAlias(e.target.value)} placeholder="ex. Ma clé pro" disabled={saveMutation.isPending} />
|
||||
<Label htmlFor="byok-alias" className="text-[10px] font-semibold uppercase tracking-widest text-concrete">{t('byok.aliasLabel')} <span className="normal-case font-normal">{t('byok.optional')}</span></Label>
|
||||
<Input id="byok-alias" value={alias} onChange={(e) => setAlias(e.target.value)} placeholder={t('byok.aliasPlaceholder')} disabled={saveMutation.isPending} />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{NEEDS_BASE_URL.has(provider) && (
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor="byok-baseurl" className="text-[10px] font-semibold uppercase tracking-widest text-concrete">URL de l'API</Label>
|
||||
<Label htmlFor="byok-baseurl" className="text-[10px] font-semibold uppercase tracking-widest text-concrete">{t('byok.apiUrl')}</Label>
|
||||
<Input id="byok-baseurl" value={baseUrl} onChange={(e) => setBaseUrl(e.target.value.trim())} placeholder="https://api.example.com/v1" disabled={saveMutation.isPending} />
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor="byok-key" className="text-[10px] font-semibold uppercase tracking-widest text-concrete">Clé API</Label>
|
||||
<Label htmlFor="byok-key" className="text-[10px] font-semibold uppercase tracking-widest text-concrete">{t('byok.apiKey')}</Label>
|
||||
<div className="flex gap-2">
|
||||
<div className="relative flex-1">
|
||||
<Input
|
||||
@@ -555,19 +557,19 @@ export function ByokSettingsPanel() {
|
||||
className={cn('shrink-0 px-4 py-2 rounded-xl text-[10px] font-bold uppercase tracking-[0.1em] transition-all border disabled:opacity-40 disabled:pointer-events-none',
|
||||
keyOk ? 'bg-emerald-500/10 border-emerald-500/40 text-emerald-700 dark:text-emerald-400' : 'bg-white dark:bg-white/5 border-border hover:border-violet-400')}
|
||||
>
|
||||
{verifying ? <Loader2 className="h-4 w-4 animate-spin" /> : keyOk ? <CheckCircle2 className="h-4 w-4" /> : 'Vérifier'}
|
||||
{verifying ? <Loader2 className="h-4 w-4 animate-spin" /> : keyOk ? <CheckCircle2 className="h-4 w-4" /> : t('byok.verify')}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{provider && (
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor="byok-model" className="text-[10px] font-semibold uppercase tracking-widest text-concrete">Modèle</Label>
|
||||
<Label htmlFor="byok-model" className="text-[10px] font-semibold uppercase tracking-widest text-concrete">{t('byok.model')}</Label>
|
||||
{loadingModels ? (
|
||||
<div className="flex items-center gap-2 text-xs text-concrete py-2"><Loader2 className="h-3 w-3 animate-spin" />Récupération des modèles...</div>
|
||||
<div className="flex items-center gap-2 text-xs text-concrete py-2"><Loader2 className="h-3 w-3 animate-spin" />{t('byok.fetchingModels')}</div>
|
||||
) : showModelDropdown ? (
|
||||
<Select value={model} onValueChange={(v) => { setModel(v); setTestResult(null) }} disabled={saveMutation.isPending}>
|
||||
<SelectTrigger id="byok-model"><SelectValue placeholder="Choisir un modèle..." /></SelectTrigger>
|
||||
<SelectTrigger id="byok-model"><SelectValue placeholder={t('byok.chooseModel')} /></SelectTrigger>
|
||||
<SelectContent>{models.map((m) => <SelectItem key={m} value={m}>{m}</SelectItem>)}</SelectContent>
|
||||
</Select>
|
||||
) : showModelInput ? (
|
||||
@@ -582,8 +584,8 @@ export function ByokSettingsPanel() {
|
||||
{testResult.ok ? <CheckCircle2 size={14} className="shrink-0 mt-0.5" /> : <XCircle size={14} className="shrink-0 mt-0.5" />}
|
||||
<div className="space-y-0.5">
|
||||
{testResult.ok ? (
|
||||
<><p className="font-semibold">Modèle opérationnel ✓{testResult.latency && <span className="font-normal ml-1">({testResult.latency}ms)</span>}</p>{testResult.reply && <p className="opacity-70 font-mono text-[10px]">Réponse : {testResult.reply}</p>}</>
|
||||
) : <p className="font-semibold">{testResult.error ?? 'Échec du test'}</p>}
|
||||
<><p className="font-semibold">{t('byok.modelOperational')}{testResult.latency && <span className="font-normal ml-1">({testResult.latency}ms)</span>}</p>{testResult.reply && <p className="opacity-70 font-mono text-[10px]">{t('byok.reply')} {testResult.reply}</p>}</>
|
||||
) : <p className="font-semibold">{testResult.error ?? t('byok.testFailed')}</p>}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
@@ -593,7 +595,7 @@ export function ByokSettingsPanel() {
|
||||
type="button" disabled={!canTest || testing || saveMutation.isPending} onClick={testModel}
|
||||
className="flex items-center gap-2 px-4 py-2.5 rounded-xl text-[10px] font-bold uppercase tracking-[0.1em] transition-all border bg-white dark:bg-white/5 border-border hover:border-violet-400 disabled:opacity-40 disabled:pointer-events-none"
|
||||
>
|
||||
{testing ? <Loader2 className="h-3.5 w-3.5 animate-spin" /> : <FlaskConical size={13} />}Tester
|
||||
{testing ? <Loader2 className="h-3.5 w-3.5 animate-spin" /> : <FlaskConical size={13} />}{t('byok.test')}
|
||||
</button>
|
||||
<Button
|
||||
type="button" disabled={saveDisabled} onClick={() => saveMutation.mutate()}
|
||||
@@ -601,7 +603,7 @@ export function ByokSettingsPanel() {
|
||||
>
|
||||
<div className="flex items-center justify-center gap-2">
|
||||
{saveMutation.isPending && <Loader2 className="h-4 w-4 animate-spin" />}
|
||||
{provider ? `Enregistrer — ${displayName(provider)}` : 'Enregistrer'}
|
||||
{provider ? t('byok.saveWithName', { name: displayName(provider) }) : t('byok.save')}
|
||||
</div>
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
import { useState, useEffect, useMemo } from 'react'
|
||||
import { motion, AnimatePresence } from 'framer-motion'
|
||||
import { Search, Sparkles, Link2, X, Folder } from 'lucide-react'
|
||||
import { useLanguage } from '@/lib/i18n'
|
||||
|
||||
export interface BlockSuggestion {
|
||||
blockId: string
|
||||
@@ -22,6 +23,7 @@ interface BlockPickerProps {
|
||||
}
|
||||
|
||||
export function BlockPicker({ isOpen, onClose, currentNoteId, onSelectBlock }: BlockPickerProps) {
|
||||
const { t } = useLanguage()
|
||||
const [activeTab, setActiveTab] = useState<'suggestions' | 'search'>('suggestions')
|
||||
const [searchQuery, setSearchQuery] = useState('')
|
||||
const [suggestions, setSuggestions] = useState<BlockSuggestion[]>([])
|
||||
@@ -134,7 +136,7 @@ export function BlockPicker({ isOpen, onClose, currentNoteId, onSelectBlock }: B
|
||||
type="text"
|
||||
value={searchQuery}
|
||||
onChange={e => setSearchQuery(e.target.value)}
|
||||
placeholder="Rechercher un extrait de note..."
|
||||
placeholder={t('blockPicker.searchPlaceholder')}
|
||||
className="w-full bg-white dark:bg-zinc-850 border border-[#D5D2CD] dark:border-neutral-800 rounded-xl pl-9 pr-4 py-2 text-xs outline-none focus:border-blue-500 focus:ring-1 focus:ring-blue-500/20 transition-all font-sans"
|
||||
autoFocus
|
||||
/>
|
||||
|
||||
@@ -40,7 +40,7 @@ function getActionLabel(action: string, t: (key: string) => string | undefined):
|
||||
function timeAgo(dateStr: string, t: (key: string) => string | undefined): string {
|
||||
const diff = Date.now() - new Date(dateStr).getTime()
|
||||
const mins = Math.floor(diff / 60000)
|
||||
if (mins < 1) return t('brainstorm.justNow')
|
||||
if (mins < 1) return t('brainstorm.justNow') || ''
|
||||
if (mins < 60) return `${mins}m`
|
||||
const hours = Math.floor(mins / 60)
|
||||
if (hours < 24) return `${hours}h`
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
'use client'
|
||||
|
||||
import { useState, useEffect } from 'react'
|
||||
import { useLanguage } from '@/lib/i18n'
|
||||
import { motion } from 'motion/react'
|
||||
import { Zap, Lightbulb, Trophy } from 'lucide-react'
|
||||
|
||||
@@ -32,6 +33,7 @@ interface BridgeNotesDashboardProps {
|
||||
}
|
||||
|
||||
export function BridgeNotesDashboard({ onNoteClick, clusters }: BridgeNotesDashboardProps) {
|
||||
const { t } = useLanguage()
|
||||
const [bridgeNotes, setBridgeNotes] = useState<BridgeNote[]>([])
|
||||
const [suggestions, setSuggestions] = useState<BridgeSuggestion[]>([])
|
||||
const [loading, setLoading] = useState(true)
|
||||
@@ -109,14 +111,14 @@ export function BridgeNotesDashboard({ onNoteClick, clusters }: BridgeNotesDashb
|
||||
<div className="p-5 rounded-2xl bg-white dark:bg-white/5 border border-border shadow-sm">
|
||||
<div className="flex items-center gap-2 text-indigo-500 mb-2">
|
||||
<Trophy size={14} />
|
||||
<span className="text-[10px] font-bold uppercase tracking-widest">Bridges</span>
|
||||
<span className="text-[10px] font-bold uppercase tracking-widest">{t('bridgeNotes.bridges')}</span>
|
||||
</div>
|
||||
<div className="text-3xl font-memento-serif font-medium text-ink dark:text-dark-ink">{bridgeNotes.length}</div>
|
||||
</div>
|
||||
<div className="p-5 rounded-2xl bg-white dark:bg-white/5 border border-border shadow-sm">
|
||||
<div className="flex items-center gap-2 text-ochre mb-2">
|
||||
<Lightbulb size={14} />
|
||||
<span className="text-[10px] font-bold uppercase tracking-widest">Suggestions</span>
|
||||
<span className="text-[10px] font-bold uppercase tracking-widest">{t('bridgeNotes.suggestions')}</span>
|
||||
</div>
|
||||
<div className="text-3xl font-memento-serif font-medium text-ink dark:text-dark-ink">{suggestions.length}</div>
|
||||
</div>
|
||||
@@ -126,7 +128,7 @@ export function BridgeNotesDashboard({ onNoteClick, clusters }: BridgeNotesDashb
|
||||
<section>
|
||||
<div className="flex items-center gap-2 mb-6 px-1">
|
||||
<Zap size={16} className="text-ochre" />
|
||||
<h3 className="text-sm font-bold uppercase tracking-widest text-ink dark:text-dark-ink">Powerful Bridge Notes</h3>
|
||||
<h3 className="text-sm font-bold uppercase tracking-widest text-ink dark:text-dark-ink">{t('bridgeNotes.powerfulTitle')}</h3>
|
||||
</div>
|
||||
<div className="space-y-3">
|
||||
{bridgeNotes.map((bridge) => (
|
||||
@@ -138,10 +140,10 @@ export function BridgeNotesDashboard({ onNoteClick, clusters }: BridgeNotesDashb
|
||||
>
|
||||
<div className="flex items-center justify-between mb-2">
|
||||
<h4 className="text-sm font-medium text-ink dark:text-dark-ink truncate flex-1">
|
||||
{bridge.note?.title || 'Untitled'}
|
||||
{bridge.note?.title || t('common.untitled')}
|
||||
</h4>
|
||||
<span className="text-[10px] font-bold text-ochre bg-ochre/10 px-2 py-0.5 rounded-full">
|
||||
Score: {(bridge.bridgeScore * 100).toFixed(0)}%
|
||||
{t('bridgeNotes.score')}: {(bridge.bridgeScore * 100).toFixed(0)}%
|
||||
</span>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
@@ -158,7 +160,7 @@ export function BridgeNotesDashboard({ onNoteClick, clusters }: BridgeNotesDashb
|
||||
</motion.div>
|
||||
))}
|
||||
{bridgeNotes.length === 0 && (
|
||||
<div className="text-xs text-concrete italic p-4">No significant bridge notes found yet. Deepen your research to find new connections.</div>
|
||||
<div className="text-xs text-concrete italic p-4">{t('bridgeNotes.empty')}</div>
|
||||
)}
|
||||
</div>
|
||||
</section>
|
||||
@@ -167,7 +169,7 @@ export function BridgeNotesDashboard({ onNoteClick, clusters }: BridgeNotesDashb
|
||||
<section>
|
||||
<div className="flex items-center gap-2 mb-6 px-1">
|
||||
<Lightbulb size={16} className="text-indigo-500" />
|
||||
<h3 className="text-sm font-bold uppercase tracking-widest text-ink dark:text-dark-ink">Missing Links (AI Generated)</h3>
|
||||
<h3 className="text-sm font-bold uppercase tracking-widest text-ink dark:text-dark-ink">{t('bridgeNotes.missingLinks')}</h3>
|
||||
</div>
|
||||
<div className="space-y-4">
|
||||
{suggestions.map((s, idx) => (
|
||||
@@ -180,7 +182,7 @@ export function BridgeNotesDashboard({ onNoteClick, clusters }: BridgeNotesDashb
|
||||
<div className="w-6 h-6 rounded-full border-2 border-paper bg-ochre flex items-center justify-center text-[10px] text-white">B</div>
|
||||
</div>
|
||||
<span className="text-[9px] font-bold uppercase tracking-widest text-indigo-500/60">
|
||||
Bridging {s.clusterAName} & {s.clusterBName}
|
||||
{t('bridgeNotes.bridging')} {s.clusterAName} & {s.clusterBName}
|
||||
</span>
|
||||
</div>
|
||||
<h4 className="text-base font-memento-serif font-medium text-ink dark:text-dark-ink mb-2">{s.suggestedTitle}</h4>
|
||||
@@ -193,7 +195,7 @@ export function BridgeNotesDashboard({ onNoteClick, clusters }: BridgeNotesDashb
|
||||
<button
|
||||
onClick={() => dismissSuggestion(s.clusterAId, s.clusterBId)}
|
||||
className="ml-4 p-2 text-concrete hover:text-ink dark:hover:text-dark-ink hover:bg-concrete/10 rounded-lg transition-colors"
|
||||
title="Dismiss suggestion"
|
||||
title={t('bridgeNotes.dismiss')}
|
||||
>
|
||||
×
|
||||
</button>
|
||||
@@ -203,13 +205,13 @@ export function BridgeNotesDashboard({ onNoteClick, clusters }: BridgeNotesDashb
|
||||
{suggestions.length === 0 && !loading && (
|
||||
<div className="text-center py-8 text-concrete">
|
||||
<Lightbulb size={24} className="mx-auto mb-3 opacity-50" />
|
||||
<p className="text-sm">No connection suggestions yet</p>
|
||||
<p className="text-xs mt-1">All your clusters may already be connected!</p>
|
||||
<p className="text-sm">{t('bridgeNotes.noSuggestions')}</p>
|
||||
<p className="text-xs mt-1">{t('bridgeNotes.allConnected')}</p>
|
||||
<button
|
||||
onClick={generateNewSuggestions}
|
||||
className="mt-4 px-4 py-2 bg-indigo-500 text-white text-xs rounded-lg hover:bg-indigo-600 transition-colors"
|
||||
>
|
||||
Generate Suggestions
|
||||
{t('bridgeNotes.generate')}
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
@@ -6,6 +6,7 @@ import { NoteChart } from './note-chart'
|
||||
import { suggestCharts, chartSuggestionToMarkdown, type ChartSuggestion, type SuggestChartsResponse } from '@/lib/ai/services/chart-suggestion.service'
|
||||
import { BarChart3, X, Search, AlertCircle, Sparkles } from 'lucide-react'
|
||||
import { cn } from '@/lib/utils'
|
||||
import { useLanguage } from '@/lib/i18n'
|
||||
|
||||
// Chart type to color mapping for visual variety
|
||||
const CHART_TYPE_COLORS: Record<string, string> = {
|
||||
@@ -36,6 +37,7 @@ export function ChartSuggestionsDialog({
|
||||
onClose,
|
||||
onSelectChart,
|
||||
}: ChartSuggestionsDialogProps) {
|
||||
const { t } = useLanguage()
|
||||
const [response, setResponse] = useState<SuggestChartsResponse | null>(null)
|
||||
const [loading, setLoading] = useState(false)
|
||||
const [selectedIndex, setSelectedIndex] = useState<number | null>(null)
|
||||
@@ -127,12 +129,12 @@ export function ChartSuggestionsDialog({
|
||||
{loading ? (
|
||||
<span className="flex items-center gap-2">
|
||||
<Search className="w-3 h-3 animate-spin" />
|
||||
Analyzing {isAnalyzingSelection ? 'selection' : 'note'} ({wordCount} words)...
|
||||
{isAnalyzingSelection ? t('chart.analyzingSelection') : t('chart.analyzingNote')} ({wordCount} {t('chart.words')})...
|
||||
</span>
|
||||
) : response?.hasData ? (
|
||||
`Found ${response?.detectedData || 'data'}`
|
||||
`${t('chart.found')} ${response?.detectedData || ''}`
|
||||
) : (
|
||||
'No data detected'
|
||||
t('chart.noDataDetected')
|
||||
)}
|
||||
</p>
|
||||
</div>
|
||||
@@ -140,7 +142,7 @@ export function ChartSuggestionsDialog({
|
||||
<button
|
||||
onClick={onClose}
|
||||
className="p-2 hover:bg-muted rounded-lg transition-colors"
|
||||
aria-label="Close"
|
||||
aria-label={t('common.close')}
|
||||
>
|
||||
<X className="w-5 h-5" />
|
||||
</button>
|
||||
@@ -152,7 +154,7 @@ export function ChartSuggestionsDialog({
|
||||
<div className="flex items-center justify-center py-12">
|
||||
<div className="text-center">
|
||||
<Search className="w-12 h-12 mx-auto mb-4 text-muted-foreground animate-pulse" />
|
||||
<p className="text-muted-foreground">Analyzing your content for chart data...</p>
|
||||
<p className="text-muted-foreground">{t('chart.analyzing')}</p>
|
||||
</div>
|
||||
</div>
|
||||
) : response?.quotaExceeded ? (
|
||||
@@ -167,7 +169,7 @@ export function ChartSuggestionsDialog({
|
||||
className="px-4 py-2 bg-blue-500 text-white rounded-lg hover:bg-blue-600 transition-colors"
|
||||
onClick={() => (window.location.href = '/settings/billing')}
|
||||
>
|
||||
Upgrade Plan
|
||||
{t('ai.featureLocked')}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
@@ -175,10 +177,10 @@ export function ChartSuggestionsDialog({
|
||||
<div className="flex items-center justify-center py-12">
|
||||
<div className="text-center max-w-md">
|
||||
<AlertCircle className="w-12 h-12 mx-auto mb-4 text-destructive" />
|
||||
<h3 className="text-lg font-semibold mb-2">Error</h3>
|
||||
<h3 className="text-lg font-semibold mb-2">{t('common.error')}</h3>
|
||||
<p className="text-sm text-muted-foreground mb-2">{response.error}</p>
|
||||
<details className="text-left text-xs text-muted-foreground mt-4">
|
||||
<summary className="cursor-pointer hover:text-foreground">Debug info</summary>
|
||||
<summary className="cursor-pointer hover:text-foreground">{t('chart.debugInfo')}</summary>
|
||||
<pre className="mt-2 bg-muted p-2 rounded overflow-auto max-h-32">
|
||||
analyzedText: {response.analyzedText}
|
||||
{'\n'}detectedData: {response.detectedData}
|
||||
@@ -190,20 +192,20 @@ export function ChartSuggestionsDialog({
|
||||
<div className="flex items-center justify-center py-12">
|
||||
<div className="text-center max-w-md">
|
||||
<AlertCircle className="w-12 h-12 mx-auto mb-4 text-muted-foreground" />
|
||||
<h3 className="text-lg font-semibold mb-2">No Data Detected</h3>
|
||||
<h3 className="text-lg font-semibold mb-2">{t('chart.noDataDetected')}</h3>
|
||||
<p className="text-muted-foreground mb-4">
|
||||
Try adding numerical data to your note. Charts work best with:
|
||||
{t('chart.noDataHint')}
|
||||
</p>
|
||||
<ul className="text-sm text-muted-foreground text-left inline-block">
|
||||
<li>• Sales figures, metrics, or measurements</li>
|
||||
<li>• Lists with values (e.g., "Jan: 5000, Feb: 7500")</li>
|
||||
<li>• Percentages or proportions</li>
|
||||
<li>• Time-series data</li>
|
||||
<li>{t('chart.dataHint1')}</li>
|
||||
<li>{t('chart.dataHint2')}</li>
|
||||
<li>{t('chart.dataHint3')}</li>
|
||||
<li>{t('chart.dataHint4')}</li>
|
||||
</ul>
|
||||
<div className="mt-4 pt-4 border-t border-border/50">
|
||||
<details className="text-left">
|
||||
<summary className="text-xs text-muted-foreground cursor-pointer hover:text-foreground">
|
||||
Debug: Show what was analyzed
|
||||
{t('chart.debugShowAnalyzed')}
|
||||
</summary>
|
||||
<pre className="mt-2 text-xs bg-muted p-2 rounded overflow-auto max-h-32">
|
||||
{textToAnalyze.substring(0, 500)}
|
||||
@@ -276,7 +278,7 @@ export function ChartSuggestionsDialog({
|
||||
{/* Data preview */}
|
||||
<div className="mt-2 pt-2 border-t border-border/50">
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{suggestion.data.length} data points
|
||||
{suggestion.data.length} {t('chart.dataPoints')}
|
||||
</p>
|
||||
</div>
|
||||
</button>
|
||||
@@ -286,9 +288,9 @@ export function ChartSuggestionsDialog({
|
||||
|
||||
{/* Keyboard hint */}
|
||||
<div className="flex items-center justify-center gap-4 pt-4 text-xs text-muted-foreground">
|
||||
<span>← → Navigate</span>
|
||||
<span>↵ Select</span>
|
||||
<span>Esc Cancel</span>
|
||||
<span>{t('chart.navigateHint')}</span>
|
||||
<span>{t('chart.selectHint')}</span>
|
||||
<span>{t('chart.escCancel')}</span>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
'use client'
|
||||
|
||||
import { useEffect, useState, useCallback } from 'react'
|
||||
import { useLanguage } from '@/lib/i18n'
|
||||
import ReactFlow, {
|
||||
Node,
|
||||
Edge,
|
||||
@@ -47,6 +48,7 @@ export function ClusterVisualization({
|
||||
bridgeNotes,
|
||||
onNodeClick
|
||||
}: ClusterVisualizationProps) {
|
||||
const { t } = useLanguage()
|
||||
const [nodes, setNodes, onNodesChange] = useNodesState([])
|
||||
const [edges, setEdges, onEdgesChange] = useEdgesState([])
|
||||
const [selectedCluster, setSelectedCluster] = useState<number | null>(null)
|
||||
@@ -79,8 +81,8 @@ export function ClusterVisualization({
|
||||
data: {
|
||||
label: (
|
||||
<div className="px-3 py-1 rounded-full text-sm font-medium" style={{ backgroundColor: color }}>
|
||||
{cluster.name || `Cluster ${cluster.clusterId}`}
|
||||
<span className="ml-2 text-xs opacity-75">({cluster.noteIds.length} notes)</span>
|
||||
{cluster.name || t('clusters.clusterLabel', { id: cluster.clusterId })}
|
||||
<span className="ml-2 text-xs opacity-75">({cluster.noteIds.length} {t('clusters.notes')})</span>
|
||||
</div>
|
||||
)
|
||||
},
|
||||
@@ -174,8 +176,8 @@ export function ClusterVisualization({
|
||||
<svg className="w-16 h-16 mx-auto mb-4 opacity-50" fill="none" viewBox="0 0 24 24" stroke="currentColor">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1} d="M19 11H5m14 0a2 2 0 012 2v6a2 2 0 01-2 2H5a2 2 0 01-2-2v-6a2 2 0 012-2m14 0V9a2 2 0 00-2-2M5 11V9a2 2 0 012-2m0 0V5a2 2 0 012-2h6a2 2 0 012 2v2M7 7h10" />
|
||||
</svg>
|
||||
<p>No clusters to display</p>
|
||||
<p className="text-sm mt-2">Create more notes to generate clusters</p>
|
||||
<p>{t('clusters.empty')}</p>
|
||||
<p className="text-sm mt-2">{t('clusters.emptyHint')}</p>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
@@ -200,10 +202,10 @@ export function ClusterVisualization({
|
||||
{selectedCluster !== null && (
|
||||
<div className="absolute bottom-4 left-4 bg-white rounded-lg shadow-lg p-4 max-w-xs">
|
||||
<h3 className="font-semibold mb-2">
|
||||
{clusters.find(c => c.clusterId === selectedCluster)?.name || `Cluster ${selectedCluster}`}
|
||||
{clusters.find(c => c.clusterId === selectedCluster)?.name || t('clusters.clusterLabel', { id: selectedCluster })}
|
||||
</h3>
|
||||
<p className="text-sm text-gray-600">
|
||||
{clusters.find(c => c.clusterId === selectedCluster)?.noteIds.length || 0} notes
|
||||
{clusters.find(c => c.clusterId === selectedCluster)?.noteIds.length || 0} {t('clusters.notes')}
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
@@ -212,11 +214,11 @@ export function ClusterVisualization({
|
||||
<div className="flex items-center gap-4 text-sm">
|
||||
<div className="flex items-center gap-2">
|
||||
<div className="w-4 h-4 rounded-full bg-yellow-400 border-2 border-yellow-600"></div>
|
||||
<span>Bridge note</span>
|
||||
<span>{t('clusters.bridgeNote')}</span>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<div className="w-4 h-4 rounded-full bg-blue-500"></div>
|
||||
<span>Regular note</span>
|
||||
<span>{t('clusters.regularNote')}</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -18,6 +18,7 @@ import {
|
||||
Tag as TagIcon, RefreshCw,
|
||||
} from 'lucide-react'
|
||||
import { motion, AnimatePresence } from 'motion/react'
|
||||
import DOMPurify from 'dompurify'
|
||||
import { exportExcalidrawSceneToPngBlob } from '@/lib/client/excalidraw-export-image'
|
||||
import { useLanguage } from '@/lib/i18n'
|
||||
import { MarkdownContent } from '@/components/markdown-content'
|
||||
@@ -123,8 +124,10 @@ interface ContextualAIChatProps {
|
||||
noteContent?: string
|
||||
noteImages?: string[]
|
||||
noteId?: string
|
||||
/** Called when an action result should be injected into the note */
|
||||
onApplyToNote?: (newContent: string) => void
|
||||
/** Called when an action result should be injected into the note.
|
||||
* `options.asRichText` signals that newContent is HTML and the note should
|
||||
* switch out of markdown mode. */
|
||||
onApplyToNote?: (newContent: string, options?: { asRichText?: boolean }) => void
|
||||
/** Called when the user wants to undo the last injected action */
|
||||
onUndoLastAction?: () => void
|
||||
/** Whether the last action has been applied (so we can show undo) */
|
||||
@@ -213,7 +216,7 @@ export function ContextualAIChat({
|
||||
|
||||
// Action state
|
||||
const [actionLoading, setActionLoading] = useState<string | null>(null)
|
||||
const [actionPreview, setActionPreview] = useState<{ label: string; text: string } | null>(null)
|
||||
const [actionPreview, setActionPreview] = useState<{ label: string; text: string; asRichText?: boolean } | null>(null)
|
||||
const [showLangPicker, setShowLangPicker] = useState(false)
|
||||
const [translateTarget, setTranslateTarget] = useState('')
|
||||
|
||||
@@ -377,7 +380,7 @@ export function ContextualAIChat({
|
||||
const data = await res.json()
|
||||
if (!res.ok) throw new Error(data.error || t('ai.genericError'))
|
||||
const result = data[action.resultKey] || ''
|
||||
setActionPreview({ label: t(action.i18nKey), text: result })
|
||||
setActionPreview({ label: t(action.i18nKey), text: result, asRichText: action.id === 'toRichText' })
|
||||
} catch (e: any) {
|
||||
mToast.error(e.message || t('ai.actionError'))
|
||||
} finally {
|
||||
@@ -387,7 +390,7 @@ export function ContextualAIChat({
|
||||
|
||||
const handleApplyPreview = () => {
|
||||
if (!actionPreview || !onApplyToNote) return
|
||||
onApplyToNote(actionPreview.text)
|
||||
onApplyToNote(actionPreview.text, { asRichText: actionPreview.asRichText })
|
||||
setActionPreview(null)
|
||||
mToast.success(t('ai.appliedToNote'))
|
||||
}
|
||||
@@ -712,7 +715,15 @@ export function ContextualAIChat({
|
||||
</div>
|
||||
<div className="flex-1 overflow-y-auto p-6 custom-scrollbar">
|
||||
<div className="bg-white/60 dark:bg-white/5 border border-border p-6 rounded-2xl leading-relaxed text-sm">
|
||||
{actionPreview.asRichText ? (
|
||||
<div
|
||||
className="prose prose-sm dark:prose-invert max-w-none"
|
||||
dir="auto"
|
||||
dangerouslySetInnerHTML={{ __html: DOMPurify.sanitize(actionPreview.text) }}
|
||||
/>
|
||||
) : (
|
||||
<MarkdownContent content={actionPreview.text} />
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
<div className="p-6 border-t border-border flex gap-3 shrink-0">
|
||||
@@ -957,7 +968,7 @@ export function ContextualAIChat({
|
||||
</motion.button>
|
||||
)}
|
||||
<div className="grid grid-cols-2 gap-3">
|
||||
{ACTION_IDS.filter(a => a.id !== 'markdown').map((action, i) => {
|
||||
{ACTION_IDS.filter(a => a.id !== 'markdown' && a.id !== 'toRichText').map((action, i) => {
|
||||
const loading = actionLoading === action.id
|
||||
const isActive = action.id === 'translate' && showLangPicker
|
||||
const Icon = action.icon
|
||||
|
||||
126
memento-note/components/dashboard-action-strip.tsx
Normal file
126
memento-note/components/dashboard-action-strip.tsx
Normal file
@@ -0,0 +1,126 @@
|
||||
'use client'
|
||||
|
||||
import { motion } from 'motion/react'
|
||||
import { Inbox, GraduationCap, Bell, Sparkles, Layers } from 'lucide-react'
|
||||
import { useLanguage } from '@/lib/i18n'
|
||||
|
||||
export interface DashboardActionStripProps {
|
||||
inboxCount: number
|
||||
dueFlashcards: number
|
||||
reminderCount: number
|
||||
discoveryCount: number
|
||||
themeCount: number
|
||||
inboxPulse?: number
|
||||
onInbox: () => void
|
||||
onReview: () => void
|
||||
onReminders: () => void
|
||||
onDiscoveries: () => void
|
||||
onThemes: () => void
|
||||
prefersReducedMotion?: boolean
|
||||
}
|
||||
|
||||
export function DashboardActionStrip({
|
||||
inboxCount,
|
||||
dueFlashcards,
|
||||
reminderCount,
|
||||
discoveryCount,
|
||||
themeCount,
|
||||
inboxPulse = 0,
|
||||
onInbox,
|
||||
onReview,
|
||||
onReminders,
|
||||
onDiscoveries,
|
||||
onThemes,
|
||||
prefersReducedMotion,
|
||||
}: DashboardActionStripProps) {
|
||||
const { t } = useLanguage()
|
||||
|
||||
const items = [
|
||||
{
|
||||
key: 'inbox',
|
||||
icon: Inbox,
|
||||
label: t('homeDashboard.inbox'),
|
||||
value: inboxCount,
|
||||
onClick: onInbox,
|
||||
accent: inboxCount > 0,
|
||||
pulse: inboxPulse > 0,
|
||||
},
|
||||
{
|
||||
key: 'review',
|
||||
icon: GraduationCap,
|
||||
label: t('homeDashboard.review'),
|
||||
value: dueFlashcards,
|
||||
onClick: onReview,
|
||||
accent: dueFlashcards > 0,
|
||||
},
|
||||
{
|
||||
key: 'reminders',
|
||||
icon: Bell,
|
||||
label: t('homeDashboard.reminders'),
|
||||
value: reminderCount,
|
||||
onClick: onReminders,
|
||||
accent: reminderCount > 0,
|
||||
},
|
||||
{
|
||||
key: 'discoveries',
|
||||
icon: Sparkles,
|
||||
label: t('homeDashboard.aiFound'),
|
||||
value: discoveryCount,
|
||||
onClick: onDiscoveries,
|
||||
accent: discoveryCount > 0,
|
||||
},
|
||||
{
|
||||
key: 'themes',
|
||||
icon: Layers,
|
||||
label: t('homeDashboard.themes'),
|
||||
value: themeCount,
|
||||
onClick: onThemes,
|
||||
accent: themeCount > 0,
|
||||
},
|
||||
]
|
||||
|
||||
return (
|
||||
<div className="flex gap-2 overflow-x-auto custom-scrollbar pb-0.5 -mx-0.5 px-0.5">
|
||||
{items.map(item => {
|
||||
const Icon = item.icon
|
||||
const Wrapper = item.pulse && !prefersReducedMotion ? motion.button : 'button'
|
||||
const motionProps = item.pulse && !prefersReducedMotion
|
||||
? {
|
||||
key: `inbox-pulse-${inboxPulse}`,
|
||||
animate: { scale: [1, 1.03, 1] },
|
||||
transition: { duration: 0.45 },
|
||||
}
|
||||
: {}
|
||||
return (
|
||||
<Wrapper
|
||||
key={item.key}
|
||||
type="button"
|
||||
onClick={item.onClick}
|
||||
{...motionProps}
|
||||
className={`shrink-0 flex items-center gap-2.5 px-3.5 py-2.5 rounded-xl border transition-all text-start min-w-[108px] ${
|
||||
item.accent
|
||||
? 'border-brand-accent/30 bg-brand-accent/[0.06] hover:border-brand-accent/50 hover:bg-brand-accent/10 shadow-sm'
|
||||
: 'border-border/25 bg-white/60 dark:bg-zinc-900/40 hover:border-border/50'
|
||||
}`}
|
||||
>
|
||||
<div className={`w-7 h-7 rounded-lg flex items-center justify-center shrink-0 ${
|
||||
item.accent ? 'bg-brand-accent/15 text-brand-accent' : 'bg-stone-100 dark:bg-zinc-800 text-concrete'
|
||||
}`}>
|
||||
<Icon size={13} strokeWidth={2} />
|
||||
</div>
|
||||
<div className="min-w-0">
|
||||
<p className={`text-lg font-serif font-bold leading-none ${
|
||||
item.accent ? 'text-ink dark:text-dark-ink' : 'text-concrete/80'
|
||||
}`}>
|
||||
{item.value}
|
||||
</p>
|
||||
<p className="text-[8px] font-mono font-bold uppercase tracking-wider text-concrete truncate mt-0.5">
|
||||
{item.label}
|
||||
</p>
|
||||
</div>
|
||||
</Wrapper>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
158
memento-note/components/dashboard-agent-carousel.tsx
Normal file
158
memento-note/components/dashboard-agent-carousel.tsx
Normal file
@@ -0,0 +1,158 @@
|
||||
'use client'
|
||||
|
||||
import { useState } from 'react'
|
||||
import { motion, AnimatePresence } from 'motion/react'
|
||||
import { Search, Bot, ChevronLeft, ChevronRight, Loader2 } from 'lucide-react'
|
||||
import { useLanguage } from '@/lib/i18n'
|
||||
import { DashboardWidgetTitleRow } from '@/components/dashboard-widget-title-row'
|
||||
|
||||
export interface AgentSuggestion {
|
||||
id: string
|
||||
topic: string
|
||||
reason: string
|
||||
relatedNoteCount: number
|
||||
suggestedFrequency: string
|
||||
}
|
||||
|
||||
export interface DashboardAgentCarouselProps {
|
||||
suggestions: AgentSuggestion[]
|
||||
loading?: boolean
|
||||
actingId: string | null
|
||||
formatFrequency: (f: string) => string
|
||||
onAccept: (id: string) => void
|
||||
onDismiss: (id: string) => void
|
||||
prefersReducedMotion?: boolean
|
||||
}
|
||||
|
||||
export function DashboardAgentCarousel({
|
||||
suggestions,
|
||||
loading,
|
||||
actingId,
|
||||
formatFrequency,
|
||||
onAccept,
|
||||
onDismiss,
|
||||
prefersReducedMotion,
|
||||
}: DashboardAgentCarouselProps) {
|
||||
const { t } = useLanguage()
|
||||
const [idx, setIdx] = useState(0)
|
||||
|
||||
const navActions = suggestions.length > 1 ? (
|
||||
<div className="flex items-center gap-1">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setIdx(i => Math.max(0, i - 1))}
|
||||
disabled={idx === 0}
|
||||
className="p-1 rounded border border-border/30 disabled:opacity-25"
|
||||
aria-label={t('homeDashboard.intelPrev')}
|
||||
>
|
||||
<ChevronLeft size={12} />
|
||||
</button>
|
||||
<span className="text-[8px] font-mono text-concrete px-1">
|
||||
{idx + 1}/{suggestions.length}
|
||||
</span>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setIdx(i => Math.min(suggestions.length - 1, i + 1))}
|
||||
disabled={idx >= suggestions.length - 1}
|
||||
className="p-1 rounded border border-border/30 disabled:opacity-25"
|
||||
aria-label={t('homeDashboard.intelNext')}
|
||||
>
|
||||
<ChevronRight size={12} />
|
||||
</button>
|
||||
</div>
|
||||
) : null
|
||||
|
||||
if (loading) {
|
||||
return <div className="h-[140px] rounded-2xl bg-stone-50 dark:bg-zinc-950/30 animate-pulse" />
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="rounded-2xl border border-border/30 bg-white dark:bg-zinc-900 p-4">
|
||||
<DashboardWidgetTitleRow
|
||||
widgetId="agents"
|
||||
icon={<Bot size={12} className="text-brand-accent" />}
|
||||
title={t('homeDashboard.suggestedResearch')}
|
||||
actions={navActions}
|
||||
/>
|
||||
|
||||
{suggestions.length === 0 ? (
|
||||
<p className="text-[11px] text-concrete italic leading-relaxed py-2">
|
||||
{t('homeDashboard.agentsEmpty')}
|
||||
</p>
|
||||
) : (
|
||||
<AgentSlide
|
||||
current={suggestions[idx]}
|
||||
actingId={actingId}
|
||||
formatFrequency={formatFrequency}
|
||||
onAccept={onAccept}
|
||||
onDismiss={onDismiss}
|
||||
prefersReducedMotion={prefersReducedMotion}
|
||||
t={t}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function AgentSlide({
|
||||
current,
|
||||
actingId,
|
||||
formatFrequency,
|
||||
onAccept,
|
||||
onDismiss,
|
||||
prefersReducedMotion,
|
||||
t,
|
||||
}: {
|
||||
current: AgentSuggestion
|
||||
actingId: string | null
|
||||
formatFrequency: (f: string) => string
|
||||
onAccept: (id: string) => void
|
||||
onDismiss: (id: string) => void
|
||||
prefersReducedMotion?: boolean
|
||||
t: (key: string) => string
|
||||
}) {
|
||||
const slide = prefersReducedMotion
|
||||
? { initial: {}, animate: {}, exit: {} }
|
||||
: { initial: { opacity: 0, y: 8 }, animate: { opacity: 1, y: 0 }, exit: { opacity: 0, y: -8 } }
|
||||
|
||||
return (
|
||||
<AnimatePresence mode="wait">
|
||||
<motion.div
|
||||
key={current.id}
|
||||
initial={slide.initial}
|
||||
animate={slide.animate}
|
||||
exit={slide.exit}
|
||||
transition={{ duration: prefersReducedMotion ? 0 : 0.18 }}
|
||||
className="p-3.5 rounded-xl border border-border/25 bg-stone-50/60 dark:bg-zinc-950/40"
|
||||
>
|
||||
<div className="flex items-start gap-2 mb-2">
|
||||
<Search size={12} className="text-brand-accent shrink-0 mt-0.5" />
|
||||
<p className="text-sm font-semibold text-ink dark:text-dark-ink leading-snug">{current.topic}</p>
|
||||
</div>
|
||||
<p className="text-[11px] text-concrete leading-relaxed line-clamp-2 mb-3">{current.reason}</p>
|
||||
<p className="text-[8px] font-mono uppercase text-concrete mb-3">
|
||||
{current.relatedNoteCount} {t('homeDashboard.notes')} · {formatFrequency(current.suggestedFrequency)}
|
||||
</p>
|
||||
<div className="flex gap-2">
|
||||
<button
|
||||
type="button"
|
||||
disabled={actingId === current.id}
|
||||
onClick={() => onDismiss(current.id)}
|
||||
className="text-[9px] font-mono uppercase px-2.5 py-1.5 rounded-lg border border-border/40 text-concrete hover:text-ink transition-colors disabled:opacity-40"
|
||||
>
|
||||
{t('homeDashboard.dismiss')}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
disabled={actingId === current.id}
|
||||
onClick={() => onAccept(current.id)}
|
||||
className="flex-1 inline-flex items-center justify-center gap-1 text-[9px] font-mono uppercase px-2.5 py-1.5 rounded-lg bg-ink text-white dark:bg-white dark:text-black font-bold hover:opacity-90 disabled:opacity-40"
|
||||
>
|
||||
{actingId === current.id ? <Loader2 size={10} className="animate-spin" /> : null}
|
||||
{t('homeDashboard.createAgent')}
|
||||
</button>
|
||||
</div>
|
||||
</motion.div>
|
||||
</AnimatePresence>
|
||||
)
|
||||
}
|
||||
371
memento-note/components/dashboard-catalog-widgets.tsx
Normal file
371
memento-note/components/dashboard-catalog-widgets.tsx
Normal file
@@ -0,0 +1,371 @@
|
||||
'use client'
|
||||
|
||||
import { Inbox, GraduationCap, Mail, Pin, Bot, BarChart3 } from 'lucide-react'
|
||||
import { useLanguage } from '@/lib/i18n'
|
||||
import { RevisionHeatmap } from '@/components/flashcards/revision-heatmap'
|
||||
import { UsageMeter } from '@/components/usage-meter'
|
||||
import { DashboardWidgetTitleRow } from '@/components/dashboard-widget-title-row'
|
||||
import type { DashboardWidgetId } from '@/lib/dashboard/layout'
|
||||
|
||||
interface DashboardWidgetShellProps {
|
||||
widgetId: DashboardWidgetId
|
||||
icon: React.ReactNode
|
||||
title: string
|
||||
children: React.ReactNode
|
||||
compact?: boolean
|
||||
headerActions?: React.ReactNode
|
||||
}
|
||||
|
||||
export function DashboardWidgetShell({
|
||||
widgetId,
|
||||
icon,
|
||||
title,
|
||||
children,
|
||||
compact,
|
||||
headerActions,
|
||||
}: DashboardWidgetShellProps) {
|
||||
return (
|
||||
<div className={`rounded-2xl border border-border/30 bg-white dark:bg-zinc-900 h-full ${
|
||||
compact ? 'p-3' : 'p-4'
|
||||
}`}>
|
||||
<DashboardWidgetTitleRow
|
||||
widgetId={widgetId}
|
||||
icon={icon}
|
||||
title={title}
|
||||
actions={headerActions}
|
||||
className={compact ? 'mb-2' : 'mb-3'}
|
||||
/>
|
||||
{children}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export function DashboardInboxWidget({
|
||||
count,
|
||||
loading,
|
||||
onOpen,
|
||||
}: {
|
||||
count: number
|
||||
loading: boolean
|
||||
onOpen: () => void
|
||||
}) {
|
||||
const { t } = useLanguage()
|
||||
return (
|
||||
<DashboardWidgetShell
|
||||
widgetId="inbox"
|
||||
icon={<Inbox size={12} className="text-brand-accent" />}
|
||||
title={t('homeDashboard.inbox')}
|
||||
compact
|
||||
>
|
||||
{loading ? (
|
||||
<div className="h-10 rounded-lg bg-stone-50 animate-pulse" />
|
||||
) : (
|
||||
<button
|
||||
type="button"
|
||||
onClick={onOpen}
|
||||
className="w-full flex items-center justify-between gap-3 p-3 rounded-xl border border-border/20 hover:border-brand-accent/30 hover:bg-brand-accent/[0.03] transition-all text-start"
|
||||
>
|
||||
<div>
|
||||
<p className="text-2xl font-serif font-bold text-ink dark:text-dark-ink leading-none">{count}</p>
|
||||
<p className="text-[10px] text-concrete mt-1">{t('homeDashboard.toOrganize')}</p>
|
||||
</div>
|
||||
<span className="text-[9px] font-mono uppercase font-bold text-brand-accent">{t('homeDashboard.widgetOpen')} →</span>
|
||||
</button>
|
||||
)}
|
||||
</DashboardWidgetShell>
|
||||
)
|
||||
}
|
||||
|
||||
export function DashboardRevisionWidget({
|
||||
dueCount,
|
||||
loading,
|
||||
onOpen,
|
||||
}: {
|
||||
dueCount: number
|
||||
loading: boolean
|
||||
onOpen: () => void
|
||||
}) {
|
||||
const { t } = useLanguage()
|
||||
return (
|
||||
<DashboardWidgetShell
|
||||
widgetId="revision"
|
||||
icon={<GraduationCap size={12} className="text-brand-accent" />}
|
||||
title={t('homeDashboard.review')}
|
||||
compact
|
||||
>
|
||||
{loading ? (
|
||||
<div className="h-10 rounded-lg bg-stone-50 animate-pulse" />
|
||||
) : (
|
||||
<button
|
||||
type="button"
|
||||
onClick={onOpen}
|
||||
className="w-full flex items-center justify-between gap-3 p-3 rounded-xl border border-border/20 hover:border-brand-accent/30 hover:bg-brand-accent/[0.03] transition-all text-start"
|
||||
>
|
||||
<div>
|
||||
<p className="text-2xl font-serif font-bold text-ink dark:text-dark-ink leading-none">{dueCount}</p>
|
||||
<p className="text-[10px] text-concrete mt-1">{t('homeDashboard.cardsDue')}</p>
|
||||
</div>
|
||||
<span className="text-[9px] font-mono uppercase font-bold text-brand-accent">{t('homeDashboard.widgetOpen')} →</span>
|
||||
</button>
|
||||
)}
|
||||
</DashboardWidgetShell>
|
||||
)
|
||||
}
|
||||
|
||||
export function DashboardStatsWidget({
|
||||
clusterCount,
|
||||
bridgeCount,
|
||||
noteCount,
|
||||
loading,
|
||||
onOpen,
|
||||
}: {
|
||||
clusterCount: number
|
||||
bridgeCount: number
|
||||
noteCount: number
|
||||
loading: boolean
|
||||
onOpen: () => void
|
||||
}) {
|
||||
const { t } = useLanguage()
|
||||
return (
|
||||
<DashboardWidgetShell
|
||||
widgetId="stats"
|
||||
icon={<BarChart3 size={12} className="text-brand-accent" />}
|
||||
title={t('homeDashboard.widgets.stats')}
|
||||
compact
|
||||
>
|
||||
{loading ? (
|
||||
<div className="grid grid-cols-3 gap-2">
|
||||
{[0, 1, 2].map(i => <div key={i} className="h-12 rounded-lg bg-stone-50 animate-pulse" />)}
|
||||
</div>
|
||||
) : (
|
||||
<button type="button" onClick={onOpen} className="w-full text-start">
|
||||
<div className="grid grid-cols-3 gap-2">
|
||||
{[
|
||||
{ label: t('homeDashboard.themes'), value: clusterCount },
|
||||
{ label: t('homeDashboard.widgetStatsBridges'), value: bridgeCount },
|
||||
{ label: t('homeDashboard.widgetStatsNotes'), value: noteCount },
|
||||
].map(item => (
|
||||
<div key={item.label} className="p-2 rounded-xl border border-border/20 bg-stone-50/50 dark:bg-zinc-950/30 text-center">
|
||||
<p className="text-lg font-serif font-bold text-ink dark:text-dark-ink leading-none">{item.value}</p>
|
||||
<p className="text-[8px] font-mono uppercase text-concrete mt-1 truncate">{item.label}</p>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</button>
|
||||
)}
|
||||
</DashboardWidgetShell>
|
||||
)
|
||||
}
|
||||
|
||||
export function DashboardAgentActivityWidget({
|
||||
actions,
|
||||
loading,
|
||||
onOpen,
|
||||
}: {
|
||||
actions: { id: string; agentName: string; result: string | null; createdAt: string }[]
|
||||
loading: boolean
|
||||
onOpen: () => void
|
||||
}) {
|
||||
const { t } = useLanguage()
|
||||
return (
|
||||
<DashboardWidgetShell
|
||||
widgetId="agent-activity"
|
||||
icon={<Bot size={12} className="text-brand-accent" />}
|
||||
title={t('homeDashboard.widgets.agent-activity')}
|
||||
compact
|
||||
>
|
||||
{loading ? (
|
||||
<div className="space-y-2">
|
||||
<div className="h-8 rounded-lg bg-stone-50 animate-pulse" />
|
||||
<div className="h-8 rounded-lg bg-stone-50 animate-pulse" />
|
||||
</div>
|
||||
) : actions.length === 0 ? (
|
||||
<p className="text-[10px] text-concrete italic py-2">{t('homeDashboard.widgetAgentActivityEmpty')}</p>
|
||||
) : (
|
||||
<div className="space-y-1.5">
|
||||
{actions.slice(0, 3).map(a => (
|
||||
<button
|
||||
key={a.id}
|
||||
type="button"
|
||||
onClick={onOpen}
|
||||
className="w-full p-2 rounded-xl border border-border/20 hover:border-brand-accent/25 text-start transition-all"
|
||||
>
|
||||
<p className="text-[10px] font-mono font-bold text-ink dark:text-dark-ink truncate">{a.agentName}</p>
|
||||
<p className="text-[9px] text-concrete truncate mt-0.5">
|
||||
{(a.result || t('homeDashboard.intelAgentNoResult')).slice(0, 80)}
|
||||
</p>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</DashboardWidgetShell>
|
||||
)
|
||||
}
|
||||
|
||||
export function DashboardGmailWidget({
|
||||
connected,
|
||||
recentCaptures,
|
||||
loading,
|
||||
onOpen,
|
||||
}: {
|
||||
connected: boolean
|
||||
recentCaptures: number
|
||||
loading: boolean
|
||||
onOpen: () => void
|
||||
}) {
|
||||
const { t } = useLanguage()
|
||||
return (
|
||||
<DashboardWidgetShell
|
||||
widgetId="gmail"
|
||||
icon={<Mail size={12} className="text-brand-accent" />}
|
||||
title={t('homeDashboard.gmailCaptures')}
|
||||
compact
|
||||
>
|
||||
{loading ? (
|
||||
<div className="h-10 rounded-lg bg-stone-50 animate-pulse" />
|
||||
) : connected ? (
|
||||
<button
|
||||
type="button"
|
||||
onClick={onOpen}
|
||||
className="w-full flex items-center justify-between gap-2 p-2.5 rounded-xl border border-border/20 hover:border-brand-accent/25 transition-all text-start"
|
||||
>
|
||||
<span className="text-[10px] text-ink dark:text-dark-ink">{t('homeDashboard.gmailRecent', { count: recentCaptures })}</span>
|
||||
<span className="text-[8px] font-mono font-bold text-brand-accent bg-brand-accent/10 px-1.5 py-0.5 rounded shrink-0">Gmail</span>
|
||||
</button>
|
||||
) : (
|
||||
<button
|
||||
type="button"
|
||||
onClick={onOpen}
|
||||
className="w-full text-[10px] font-mono uppercase tracking-wider text-concrete hover:text-brand-accent transition-colors text-start py-2"
|
||||
>
|
||||
{t('homeDashboard.gmailConnect')} →
|
||||
</button>
|
||||
)}
|
||||
</DashboardWidgetShell>
|
||||
)
|
||||
}
|
||||
|
||||
export function DashboardPinnedWidget({
|
||||
notes,
|
||||
loading,
|
||||
onSelect,
|
||||
}: {
|
||||
notes: { id: string; title: string | null; notebookId: string | null }[]
|
||||
loading: boolean
|
||||
onSelect: (id: string, notebookId: string | null) => void
|
||||
}) {
|
||||
const { t } = useLanguage()
|
||||
return (
|
||||
<DashboardWidgetShell
|
||||
widgetId="pinned"
|
||||
icon={<Pin size={12} className="text-brand-accent" />}
|
||||
title={t('homeDashboard.widgets.pinned')}
|
||||
compact
|
||||
>
|
||||
{loading ? (
|
||||
<div className="space-y-2">
|
||||
<div className="h-8 rounded-lg bg-stone-50 animate-pulse" />
|
||||
</div>
|
||||
) : notes.length === 0 ? (
|
||||
<p className="text-[10px] text-concrete italic py-2">{t('homeDashboard.widgetPinnedEmpty')}</p>
|
||||
) : (
|
||||
<div className="space-y-1">
|
||||
{notes.map(n => (
|
||||
<button
|
||||
key={n.id}
|
||||
type="button"
|
||||
onClick={() => onSelect(n.id, n.notebookId)}
|
||||
className="w-full text-[10px] text-ink dark:text-dark-ink truncate text-start p-2 rounded-lg hover:bg-brand-accent/[0.04] transition-colors"
|
||||
>
|
||||
{n.title || t('homeDashboard.untitled')}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</DashboardWidgetShell>
|
||||
)
|
||||
}
|
||||
|
||||
export function DashboardActivityWidget({
|
||||
data,
|
||||
loading,
|
||||
}: {
|
||||
data: { date: string; count: number }[]
|
||||
loading: boolean
|
||||
}) {
|
||||
const { t } = useLanguage()
|
||||
return (
|
||||
<DashboardWidgetShell
|
||||
widgetId="activity"
|
||||
icon={<BarChart3 size={12} className="text-brand-accent" />}
|
||||
title={t('homeDashboard.widgets.activity')}
|
||||
>
|
||||
{loading ? (
|
||||
<div className="h-24 rounded-lg bg-stone-50 animate-pulse" />
|
||||
) : (
|
||||
<RevisionHeatmap data={data} />
|
||||
)}
|
||||
<p className="text-[9px] text-concrete mt-2">{t('homeDashboard.widgetActivityHint')}</p>
|
||||
</DashboardWidgetShell>
|
||||
)
|
||||
}
|
||||
|
||||
export function DashboardUsageWidget() {
|
||||
const { t } = useLanguage()
|
||||
return (
|
||||
<DashboardWidgetShell
|
||||
widgetId="usage"
|
||||
icon={<BarChart3 size={12} className="text-brand-accent" />}
|
||||
title={t('homeDashboard.widgets.usage')}
|
||||
compact
|
||||
>
|
||||
<UsageMeter className="px-0 py-0" />
|
||||
<p className="text-[9px] text-concrete mt-2">{t('homeDashboard.widgetUsageHint')}</p>
|
||||
</DashboardWidgetShell>
|
||||
)
|
||||
}
|
||||
|
||||
export function DashboardFlashcardsProgressWidget({
|
||||
retentionRate,
|
||||
streak,
|
||||
totalCards,
|
||||
loading,
|
||||
onOpen,
|
||||
}: {
|
||||
retentionRate: number
|
||||
streak: number
|
||||
totalCards: number
|
||||
loading?: boolean
|
||||
onOpen: () => void
|
||||
}) {
|
||||
const { t } = useLanguage()
|
||||
return (
|
||||
<DashboardWidgetShell
|
||||
widgetId="flashcards-progress"
|
||||
icon={<GraduationCap size={12} className="text-brand-accent" />}
|
||||
title={t('homeDashboard.widgets.flashcards-progress')}
|
||||
compact
|
||||
>
|
||||
{loading ? (
|
||||
<div className="h-14 rounded-lg bg-stone-50 animate-pulse" />
|
||||
) : (
|
||||
<button type="button" onClick={onOpen} className="w-full text-start">
|
||||
<div className="grid grid-cols-3 gap-2">
|
||||
<div className="text-center p-2 rounded-xl border border-border/20">
|
||||
<p className="text-lg font-serif font-bold text-ink dark:text-dark-ink">{retentionRate}%</p>
|
||||
<p className="text-[8px] font-mono uppercase text-concrete">{t('homeDashboard.flashRetention')}</p>
|
||||
</div>
|
||||
<div className="text-center p-2 rounded-xl border border-border/20">
|
||||
<p className="text-lg font-serif font-bold text-ink dark:text-dark-ink">{streak}</p>
|
||||
<p className="text-[8px] font-mono uppercase text-concrete">{t('homeDashboard.flashStreak')}</p>
|
||||
</div>
|
||||
<div className="text-center p-2 rounded-xl border border-border/20">
|
||||
<p className="text-lg font-serif font-bold text-ink dark:text-dark-ink">{totalCards}</p>
|
||||
<p className="text-[8px] font-mono uppercase text-concrete">{t('homeDashboard.flashTotal')}</p>
|
||||
</div>
|
||||
</div>
|
||||
</button>
|
||||
)}
|
||||
</DashboardWidgetShell>
|
||||
)
|
||||
}
|
||||
139
memento-note/components/dashboard-mind-orbit.tsx
Normal file
139
memento-note/components/dashboard-mind-orbit.tsx
Normal file
@@ -0,0 +1,139 @@
|
||||
'use client'
|
||||
|
||||
import { motion } from 'motion/react'
|
||||
import { Layers, Zap, ArrowUpRight } from 'lucide-react'
|
||||
import { useLanguage } from '@/lib/i18n'
|
||||
import { DashboardWidgetTitleRow } from '@/components/dashboard-widget-title-row'
|
||||
|
||||
interface Cluster {
|
||||
clusterId: number
|
||||
name?: string
|
||||
noteIds: string[]
|
||||
}
|
||||
|
||||
interface BridgeNote {
|
||||
noteId: string
|
||||
bridgeScore: number
|
||||
clusterNames?: string[]
|
||||
note?: { id: string; title: string | null }
|
||||
}
|
||||
|
||||
const CLUSTER_COLORS = ['#F87171', '#60A5FA', '#34D399', '#FBBF24', '#A78BFA', '#F472B6', '#2DD4BF']
|
||||
|
||||
export interface DashboardMindOrbitProps {
|
||||
clusters: Cluster[]
|
||||
bridgeNotes: BridgeNote[]
|
||||
loading?: boolean
|
||||
onOpenInsights: () => void
|
||||
onNoteSelect: (id: string) => void
|
||||
prefersReducedMotion?: boolean
|
||||
}
|
||||
|
||||
export function DashboardMindOrbit({
|
||||
clusters,
|
||||
bridgeNotes,
|
||||
loading,
|
||||
onOpenInsights,
|
||||
onNoteSelect,
|
||||
prefersReducedMotion,
|
||||
}: DashboardMindOrbitProps) {
|
||||
const { t } = useLanguage()
|
||||
const topClusters = [...clusters]
|
||||
.sort((a, b) => b.noteIds.length - a.noteIds.length)
|
||||
.slice(0, 5)
|
||||
const maxCount = topClusters[0]?.noteIds.length || 1
|
||||
const topBridge = bridgeNotes[0]
|
||||
|
||||
if (loading) {
|
||||
return <div className="h-[180px] rounded-2xl bg-stone-50 dark:bg-zinc-950/30 animate-pulse" />
|
||||
}
|
||||
|
||||
if (topClusters.length === 0) {
|
||||
return (
|
||||
<button
|
||||
type="button"
|
||||
onClick={onOpenInsights}
|
||||
className="w-full h-[180px] rounded-2xl border border-dashed border-border/35 bg-white/50 dark:bg-zinc-900/50 flex flex-col items-center justify-center gap-2 p-6 text-center hover:border-brand-accent/30 transition-all"
|
||||
>
|
||||
<Layers size={22} className="text-concrete/35" />
|
||||
<p className="text-xs text-concrete italic max-w-[220px]">{t('homeDashboard.mindMapEmpty')}</p>
|
||||
<span className="text-[9px] font-mono uppercase font-bold text-brand-accent">{t('homeDashboard.mindMapOpen')}</span>
|
||||
</button>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="rounded-2xl border border-border/30 bg-white dark:bg-zinc-900 p-4">
|
||||
<DashboardWidgetTitleRow
|
||||
widgetId="mind-map"
|
||||
icon={<Layers size={12} className="text-brand-accent" />}
|
||||
title={t('homeDashboard.mindMap')}
|
||||
actions={(
|
||||
<button
|
||||
type="button"
|
||||
onClick={onOpenInsights}
|
||||
className="inline-flex items-center gap-0.5 text-[8px] font-mono uppercase font-bold text-brand-accent hover:underline"
|
||||
>
|
||||
{t('homeDashboard.fullMap')}
|
||||
<ArrowUpRight size={10} />
|
||||
</button>
|
||||
)}
|
||||
/>
|
||||
|
||||
<div className="flex flex-wrap items-center justify-center gap-3 min-h-[100px] py-2">
|
||||
{topClusters.map((cluster, idx) => {
|
||||
const color = CLUSTER_COLORS[cluster.clusterId % CLUSTER_COLORS.length]
|
||||
const scale = 0.65 + (cluster.noteIds.length / maxCount) * 0.55
|
||||
const size = Math.round(56 * scale)
|
||||
const label = cluster.name || `${t('homeDashboard.theme')} ${cluster.clusterId + 1}`
|
||||
return (
|
||||
<motion.button
|
||||
key={cluster.clusterId}
|
||||
type="button"
|
||||
whileHover={prefersReducedMotion ? undefined : { scale: 1.06 }}
|
||||
whileTap={prefersReducedMotion ? undefined : { scale: 0.97 }}
|
||||
onClick={onOpenInsights}
|
||||
className="relative flex flex-col items-center gap-1.5 group"
|
||||
style={{ width: size + 16 }}
|
||||
>
|
||||
<div
|
||||
className="rounded-full border-2 flex items-center justify-center font-mono font-bold text-white shadow-sm group-hover:shadow-md transition-shadow"
|
||||
style={{
|
||||
width: size,
|
||||
height: size,
|
||||
backgroundColor: `${color}cc`,
|
||||
borderColor: `${color}40`,
|
||||
fontSize: Math.max(9, size * 0.22),
|
||||
}}
|
||||
>
|
||||
{cluster.noteIds.length}
|
||||
</div>
|
||||
<span className="text-[8px] font-medium text-ink/80 dark:text-dark-ink/80 text-center line-clamp-2 leading-tight max-w-[72px] group-hover:text-brand-accent transition-colors">
|
||||
{label}
|
||||
</span>
|
||||
</motion.button>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
|
||||
{topBridge?.note && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => onNoteSelect(topBridge.noteId)}
|
||||
className="w-full mt-2 p-2.5 rounded-xl border border-brand-accent/20 bg-brand-accent/[0.04] hover:bg-brand-accent/[0.08] transition-all text-start flex items-center gap-2 group"
|
||||
>
|
||||
<Zap size={11} className="text-brand-accent shrink-0" />
|
||||
<div className="min-w-0 flex-1">
|
||||
<p className="text-[10px] font-semibold text-ink dark:text-dark-ink truncate group-hover:text-brand-accent transition-colors">
|
||||
{topBridge.note.title || t('homeDashboard.untitled')}
|
||||
</p>
|
||||
<p className="text-[8px] font-mono uppercase text-concrete">{t('homeDashboard.bridgeNote')}</p>
|
||||
</div>
|
||||
<span className="text-[8px] font-mono font-bold text-brand-accent bg-brand-accent/10 px-1.5 py-0.5 rounded-full shrink-0">
|
||||
{Math.round(topBridge.bridgeScore * 100)}%
|
||||
</span>
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
165
memento-note/components/dashboard-next-paths.tsx
Normal file
165
memento-note/components/dashboard-next-paths.tsx
Normal file
@@ -0,0 +1,165 @@
|
||||
'use client'
|
||||
|
||||
import { motion } from 'motion/react'
|
||||
import { Loader2 } from 'lucide-react'
|
||||
import {
|
||||
ArrowRight, GitBranch, Lightbulb, Link2, BookOpen, Inbox,
|
||||
GraduationCap, Compass, Plus, Sparkles, PenLine,
|
||||
} from 'lucide-react'
|
||||
import type { LucideIcon } from 'lucide-react'
|
||||
import { useLanguage } from '@/lib/i18n'
|
||||
import { DashboardWidgetTitleRow } from '@/components/dashboard-widget-title-row'
|
||||
import type { DashboardPath, DashboardPathType } from '@/lib/dashboard/path-types'
|
||||
|
||||
const TYPE_META: Record<DashboardPathType, { Icon: LucideIcon; accent: string }> = {
|
||||
continue: { Icon: PenLine, accent: 'text-ink' },
|
||||
connect: { Icon: Link2, accent: 'text-brand-accent' },
|
||||
'add-link': { Icon: Plus, accent: 'text-emerald-600' },
|
||||
bridge: { Icon: GitBranch, accent: 'text-violet-600' },
|
||||
research: { Icon: Sparkles, accent: 'text-sky-600' },
|
||||
explore: { Icon: Compass, accent: 'text-amber-600' },
|
||||
organize: { Icon: Inbox, accent: 'text-brand-accent' },
|
||||
review: { Icon: GraduationCap, accent: 'text-brand-accent' },
|
||||
resurface: { Icon: Lightbulb, accent: 'text-brand-accent' },
|
||||
daily: { Icon: BookOpen, accent: 'text-concrete' },
|
||||
}
|
||||
|
||||
export interface DashboardNextPathsProps {
|
||||
paths: DashboardPath[]
|
||||
loading?: boolean
|
||||
enriching?: boolean
|
||||
focusNoteTitle?: string | null
|
||||
onAction: (path: DashboardPath) => void
|
||||
prefersReducedMotion?: boolean
|
||||
}
|
||||
|
||||
export function DashboardNextPaths({
|
||||
paths,
|
||||
loading,
|
||||
enriching,
|
||||
focusNoteTitle,
|
||||
onAction,
|
||||
prefersReducedMotion,
|
||||
}: DashboardNextPathsProps) {
|
||||
const { t } = useLanguage()
|
||||
|
||||
if (loading) {
|
||||
return (
|
||||
<div className="rounded-2xl border border-brand-accent/20 bg-gradient-to-br from-white via-white to-brand-accent/[0.04] dark:from-zinc-900 dark:via-zinc-900 dark:to-brand-accent/[0.06] shadow-sm overflow-hidden">
|
||||
<div className="px-5 pt-4 pb-3 border-b border-border/15">
|
||||
<DashboardWidgetTitleRow
|
||||
widgetId="next-paths"
|
||||
title={t('homeDashboard.pathsTitle')}
|
||||
className="mb-0"
|
||||
/>
|
||||
{focusNoteTitle && (
|
||||
<p className="text-[11px] text-concrete mt-1">
|
||||
{t('homeDashboard.pathsFromNote', { title: focusNoteTitle })}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
<div className="flex flex-col items-center justify-center gap-3 px-5 py-10">
|
||||
<Loader2 size={22} className="text-brand-accent animate-spin" strokeWidth={2} />
|
||||
<p className="text-[11px] text-concrete text-center leading-relaxed max-w-[240px]">
|
||||
{t('homeDashboard.pathsLoading')}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
if (paths.length === 0) {
|
||||
return (
|
||||
<div className="rounded-2xl border border-border/25 bg-white/60 dark:bg-zinc-900/60 p-5">
|
||||
<DashboardWidgetTitleRow
|
||||
widgetId="next-paths"
|
||||
title={t('homeDashboard.pathsTitle')}
|
||||
className="mb-2"
|
||||
/>
|
||||
<p className="text-[10px] text-concrete italic">{t('homeDashboard.pathsEmpty')}</p>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
const hero = paths[0]
|
||||
const rest = paths.slice(1, 5)
|
||||
const HeroIcon = TYPE_META[hero.type].Icon
|
||||
|
||||
return (
|
||||
<div className="rounded-2xl border border-brand-accent/20 bg-gradient-to-br from-white via-white to-brand-accent/[0.04] dark:from-zinc-900 dark:via-zinc-900 dark:to-brand-accent/[0.06] shadow-sm overflow-hidden">
|
||||
<div className="px-5 pt-4 pb-3 border-b border-border/15">
|
||||
<DashboardWidgetTitleRow
|
||||
widgetId="next-paths"
|
||||
title={t('homeDashboard.pathsTitle')}
|
||||
className="mb-0"
|
||||
actions={enriching ? (
|
||||
<span className="inline-flex items-center gap-1.5 text-[8px] font-mono uppercase text-concrete">
|
||||
<Loader2 size={10} className="text-brand-accent animate-spin" />
|
||||
{t('homeDashboard.pathsEnriching')}
|
||||
</span>
|
||||
) : undefined}
|
||||
/>
|
||||
{focusNoteTitle && (
|
||||
<p className="text-[11px] text-concrete mt-1">
|
||||
{t('homeDashboard.pathsFromNote', { title: focusNoteTitle })}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<motion.button
|
||||
type="button"
|
||||
onClick={() => onAction(hero)}
|
||||
whileHover={prefersReducedMotion ? undefined : { y: -1 }}
|
||||
className="w-full text-start px-5 py-4 hover:bg-brand-accent/[0.03] transition-colors border-b border-border/10"
|
||||
>
|
||||
<div className="flex items-start gap-3">
|
||||
<div className={`w-9 h-9 rounded-xl bg-brand-accent/10 flex items-center justify-center shrink-0 ${TYPE_META[hero.type].accent}`}>
|
||||
<HeroIcon size={16} strokeWidth={1.75} />
|
||||
</div>
|
||||
<div className="min-w-0 flex-1">
|
||||
<p className="text-[8px] font-mono font-bold uppercase tracking-wider text-concrete mb-0.5">
|
||||
{t(`homeDashboard.pathTypes.${hero.type}`)}
|
||||
{hero.score ? ` · ${hero.score}%` : ''}
|
||||
</p>
|
||||
<p className="text-sm font-serif font-semibold text-ink dark:text-dark-ink leading-snug">
|
||||
{hero.title}
|
||||
</p>
|
||||
<p className="text-[11px] text-concrete leading-relaxed mt-1 line-clamp-2">
|
||||
{hero.description}
|
||||
</p>
|
||||
</div>
|
||||
<span className="shrink-0 inline-flex items-center gap-1 text-[9px] font-mono font-bold uppercase text-brand-accent mt-1">
|
||||
{t(`homeDashboard.pathActions.${hero.actionKey}`)}
|
||||
<ArrowRight size={10} />
|
||||
</span>
|
||||
</div>
|
||||
</motion.button>
|
||||
|
||||
{rest.length > 0 && (
|
||||
<div className="divide-y divide-border/10">
|
||||
{rest.map(path => {
|
||||
const meta = TYPE_META[path.type]
|
||||
const Icon = meta.Icon
|
||||
return (
|
||||
<button
|
||||
key={path.id}
|
||||
type="button"
|
||||
onClick={() => onAction(path)}
|
||||
className="w-full flex items-center gap-3 px-5 py-3 text-start hover:bg-stone-50/80 dark:hover:bg-zinc-950/40 transition-colors"
|
||||
>
|
||||
<Icon size={13} className={`shrink-0 ${meta.accent}`} />
|
||||
<div className="min-w-0 flex-1">
|
||||
<p className="text-[11px] font-medium text-ink dark:text-dark-ink truncate">{path.title}</p>
|
||||
<p className="text-[9px] text-concrete truncate">{path.description}</p>
|
||||
</div>
|
||||
<span className="text-[8px] font-mono uppercase text-brand-accent shrink-0">
|
||||
{t(`homeDashboard.pathActions.${path.actionKey}`)}
|
||||
</span>
|
||||
</button>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
258
memento-note/components/dashboard-path-widgets.tsx
Normal file
258
memento-note/components/dashboard-path-widgets.tsx
Normal file
@@ -0,0 +1,258 @@
|
||||
'use client'
|
||||
|
||||
import { CheckCircle2, Circle } from 'lucide-react'
|
||||
import { useLanguage } from '@/lib/i18n'
|
||||
import { DashboardWidgetShell } from '@/components/dashboard-catalog-widgets'
|
||||
|
||||
export interface DailyReviewItem {
|
||||
key: string
|
||||
label: string
|
||||
done: boolean
|
||||
count?: number
|
||||
onClick: () => void
|
||||
}
|
||||
|
||||
export function DashboardDailyReview({
|
||||
items,
|
||||
loading,
|
||||
}: {
|
||||
items: DailyReviewItem[]
|
||||
loading?: boolean
|
||||
}) {
|
||||
const { t } = useLanguage()
|
||||
|
||||
return (
|
||||
<DashboardWidgetShell
|
||||
widgetId="daily-review"
|
||||
icon={<CheckCircle2 size={12} className="text-brand-accent" />}
|
||||
title={t('homeDashboard.widgets.daily-review')}
|
||||
compact
|
||||
>
|
||||
{loading ? (
|
||||
<div className="space-y-2">
|
||||
{[0, 1, 2].map(i => <div key={i} className="h-8 rounded-lg bg-stone-50 animate-pulse" />)}
|
||||
</div>
|
||||
) : (
|
||||
<ul className="space-y-1.5">
|
||||
{items.map(item => (
|
||||
<li key={item.key}>
|
||||
<button
|
||||
type="button"
|
||||
onClick={item.onClick}
|
||||
className="w-full flex items-center gap-2.5 p-2 rounded-xl hover:bg-brand-accent/[0.04] transition-colors text-start"
|
||||
>
|
||||
{item.done ? (
|
||||
<CheckCircle2 size={14} className="text-brand-accent shrink-0" />
|
||||
) : (
|
||||
<Circle size={14} className="text-concrete/50 shrink-0" />
|
||||
)}
|
||||
<span className={`text-[10px] flex-1 ${item.done ? 'text-concrete line-through' : 'text-ink dark:text-dark-ink'}`}>
|
||||
{item.label}
|
||||
{item.count !== undefined && item.count > 0 ? ` (${item.count})` : ''}
|
||||
</span>
|
||||
</button>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
<p className="text-[9px] text-concrete mt-2 leading-relaxed">{t('homeDashboard.dailyReviewHint')}</p>
|
||||
</DashboardWidgetShell>
|
||||
)
|
||||
}
|
||||
|
||||
export function DashboardOpenLoops({
|
||||
loops,
|
||||
loading,
|
||||
onSelect,
|
||||
}: {
|
||||
loops: Array<{ id: string; title: string | null; notebookId: string | null; daysStale: number }>
|
||||
loading?: boolean
|
||||
onSelect: (id: string, notebookId: string | null) => void
|
||||
}) {
|
||||
const { t } = useLanguage()
|
||||
|
||||
return (
|
||||
<DashboardWidgetShell
|
||||
widgetId="open-loops"
|
||||
icon={<Circle size={12} className="text-brand-accent" />}
|
||||
title={t('homeDashboard.widgets.open-loops')}
|
||||
compact
|
||||
>
|
||||
{loading ? (
|
||||
<div className="h-16 rounded-lg bg-stone-50 animate-pulse" />
|
||||
) : loops.length === 0 ? (
|
||||
<p className="text-[10px] text-concrete italic py-2">{t('homeDashboard.openLoopsEmpty')}</p>
|
||||
) : (
|
||||
<div className="space-y-1">
|
||||
{loops.map(loop => (
|
||||
<button
|
||||
key={loop.id}
|
||||
type="button"
|
||||
onClick={() => onSelect(loop.id, loop.notebookId)}
|
||||
className="w-full flex items-center justify-between gap-2 p-2 rounded-lg hover:bg-brand-accent/[0.04] text-start transition-colors"
|
||||
>
|
||||
<span className="text-[10px] text-ink dark:text-dark-ink truncate flex-1">
|
||||
{loop.title || t('homeDashboard.untitled')}
|
||||
</span>
|
||||
<span className="text-[8px] font-mono text-concrete shrink-0">
|
||||
{t('homeDashboard.openLoopsStale', { days: loop.daysStale })}
|
||||
</span>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</DashboardWidgetShell>
|
||||
)
|
||||
}
|
||||
|
||||
export function DashboardDailyNoteWidget({
|
||||
loading,
|
||||
onOpen,
|
||||
}: {
|
||||
loading?: boolean
|
||||
onOpen: () => void
|
||||
}) {
|
||||
const { t } = useLanguage()
|
||||
|
||||
return (
|
||||
<DashboardWidgetShell
|
||||
widgetId="daily-note"
|
||||
icon={<CheckCircle2 size={12} className="text-brand-accent" />}
|
||||
title={t('homeDashboard.widgets.daily-note')}
|
||||
compact
|
||||
>
|
||||
{loading ? (
|
||||
<div className="h-10 rounded-lg bg-stone-50 animate-pulse" />
|
||||
) : (
|
||||
<button
|
||||
type="button"
|
||||
onClick={onOpen}
|
||||
className="w-full p-3 rounded-xl border border-border/20 hover:border-brand-accent/30 text-start transition-all"
|
||||
>
|
||||
<p className="text-[11px] font-serif font-semibold text-ink dark:text-dark-ink">
|
||||
{new Date().toLocaleDateString(undefined, { weekday: 'long', day: 'numeric', month: 'long' })}
|
||||
</p>
|
||||
<p className="text-[9px] font-mono uppercase text-brand-accent mt-1">{t('homeDashboard.dailyNoteOpen')} →</p>
|
||||
</button>
|
||||
)}
|
||||
</DashboardWidgetShell>
|
||||
)
|
||||
}
|
||||
|
||||
export function DashboardLinkSuggestions({
|
||||
paths,
|
||||
loading,
|
||||
onAction,
|
||||
}: {
|
||||
paths: Array<{ id: string; title: string; description: string; score?: number }>
|
||||
loading?: boolean
|
||||
onAction: (id: string) => void
|
||||
}) {
|
||||
const { t } = useLanguage()
|
||||
|
||||
return (
|
||||
<DashboardWidgetShell
|
||||
widgetId="link-suggestions"
|
||||
icon={<Circle size={12} className="text-emerald-600" />}
|
||||
title={t('homeDashboard.widgets.link-suggestions')}
|
||||
>
|
||||
{loading ? (
|
||||
<div className="space-y-2">
|
||||
<div className="h-12 rounded-lg bg-stone-50 animate-pulse" />
|
||||
</div>
|
||||
) : paths.length === 0 ? (
|
||||
<p className="text-[10px] text-concrete italic">{t('homeDashboard.linkSuggestionsEmpty')}</p>
|
||||
) : (
|
||||
<div className="space-y-2">
|
||||
{paths.map(p => (
|
||||
<button
|
||||
key={p.id}
|
||||
type="button"
|
||||
onClick={() => onAction(p.id)}
|
||||
className="w-full p-3 rounded-xl border border-border/20 hover:border-emerald-500/30 text-start transition-all"
|
||||
>
|
||||
<div className="flex items-center justify-between gap-2 mb-1">
|
||||
<p className="text-[11px] font-mono font-bold text-ink dark:text-dark-ink truncate">{p.title}</p>
|
||||
{p.score ? (
|
||||
<span className="text-[8px] font-mono text-emerald-600 shrink-0">{p.score}%</span>
|
||||
) : null}
|
||||
</div>
|
||||
<p className="text-[10px] text-concrete line-clamp-2">{p.description}</p>
|
||||
<p className="text-[8px] font-mono uppercase text-emerald-600 mt-2">{t('homeDashboard.pathActions.addLink')} →</p>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</DashboardWidgetShell>
|
||||
)
|
||||
}
|
||||
|
||||
export function DashboardBridgesWidget({
|
||||
suggestions,
|
||||
loading,
|
||||
actingKey,
|
||||
onCreate,
|
||||
onDismiss,
|
||||
}: {
|
||||
suggestions: Array<{
|
||||
clusterAId: number
|
||||
clusterBId: number
|
||||
clusterAName: string
|
||||
clusterBName: string
|
||||
suggestedTitle: string
|
||||
justification: string
|
||||
}>
|
||||
loading?: boolean
|
||||
actingKey?: string | null
|
||||
onCreate: (s: { clusterAId: number; clusterBId: number; clusterAName: string; clusterBName: string; suggestedTitle: string; suggestedContent: string; justification: string }) => void
|
||||
onDismiss: (s: { clusterAId: number; clusterBId: number }) => void
|
||||
}) {
|
||||
const { t } = useLanguage()
|
||||
|
||||
return (
|
||||
<DashboardWidgetShell
|
||||
widgetId="bridges"
|
||||
icon={<Circle size={12} className="text-violet-600" />}
|
||||
title={t('homeDashboard.widgets.bridges')}
|
||||
>
|
||||
{loading ? (
|
||||
<div className="h-20 rounded-lg bg-stone-50 animate-pulse" />
|
||||
) : suggestions.length === 0 ? (
|
||||
<p className="text-[10px] text-concrete italic">{t('homeDashboard.bridgesEmpty')}</p>
|
||||
) : (
|
||||
<div className="space-y-2">
|
||||
{suggestions.slice(0, 3).map(s => {
|
||||
const key = `${s.clusterAId}-${s.clusterBId}`
|
||||
return (
|
||||
<div key={key} className="p-3 rounded-xl border border-border/20 bg-stone-50/40 dark:bg-zinc-950/30">
|
||||
<p className="text-[10px] font-mono font-bold text-ink dark:text-dark-ink">{s.suggestedTitle}</p>
|
||||
<p className="text-[9px] text-concrete mt-1">
|
||||
{t('homeDashboard.suggestedBridge', { clusterA: s.clusterAName, clusterB: s.clusterBName })}
|
||||
</p>
|
||||
<p className="text-[10px] text-concrete mt-1 line-clamp-2">{s.justification}</p>
|
||||
<div className="flex gap-2 mt-2">
|
||||
<button
|
||||
type="button"
|
||||
disabled={actingKey === key}
|
||||
onClick={() => onCreate({ ...s, suggestedContent: s.justification })}
|
||||
className="text-[8px] font-mono uppercase font-bold text-brand-accent hover:underline disabled:opacity-50"
|
||||
>
|
||||
{t('homeDashboard.createBridgeNote')}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
disabled={actingKey === key}
|
||||
onClick={() => onDismiss(s)}
|
||||
className="text-[8px] font-mono uppercase text-concrete hover:text-rose-500 disabled:opacity-50"
|
||||
>
|
||||
{t('homeDashboard.dismissConnection')}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
</DashboardWidgetShell>
|
||||
)
|
||||
}
|
||||
123
memento-note/components/dashboard-resume-hero.tsx
Normal file
123
memento-note/components/dashboard-resume-hero.tsx
Normal file
@@ -0,0 +1,123 @@
|
||||
'use client'
|
||||
|
||||
import { motion } from 'motion/react'
|
||||
import { Clock, ChevronRight, Play } from 'lucide-react'
|
||||
import { useLanguage } from '@/lib/i18n'
|
||||
import { DashboardWidgetTitleRow } from '@/components/dashboard-widget-title-row'
|
||||
|
||||
export interface ResumeNote {
|
||||
id: string
|
||||
title: string | null
|
||||
excerpt: string
|
||||
notebookName: string
|
||||
notebookColor: string
|
||||
updatedAt: string
|
||||
notebookId: string | null
|
||||
}
|
||||
|
||||
export interface DashboardResumeHeroProps {
|
||||
notes: ResumeNote[]
|
||||
loading?: boolean
|
||||
onSelect: (id: string, notebookId: string | null) => void
|
||||
formatRelativeTime: (date: string) => string
|
||||
prefersReducedMotion?: boolean
|
||||
}
|
||||
|
||||
export function DashboardResumeHero({
|
||||
notes,
|
||||
loading,
|
||||
onSelect,
|
||||
formatRelativeTime,
|
||||
prefersReducedMotion,
|
||||
}: DashboardResumeHeroProps) {
|
||||
const { t } = useLanguage()
|
||||
const hero = notes[0]
|
||||
const rest = notes.slice(1, 4)
|
||||
|
||||
if (loading) {
|
||||
return (
|
||||
<div className="rounded-2xl border border-border/30 bg-white dark:bg-zinc-900 p-5 min-h-[200px] animate-pulse">
|
||||
<div className="h-4 w-32 bg-stone-100 dark:bg-zinc-800 rounded mb-4" />
|
||||
<div className="h-6 w-3/4 bg-stone-100 dark:bg-zinc-800 rounded mb-3" />
|
||||
<div className="h-12 bg-stone-50 dark:bg-zinc-950 rounded-xl" />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
if (!hero) {
|
||||
return (
|
||||
<div className="rounded-2xl border border-dashed border-border/40 bg-white/50 dark:bg-zinc-900/50 p-8 text-center">
|
||||
<Clock size={24} className="mx-auto text-concrete/30 mb-3" strokeWidth={1.25} />
|
||||
<p className="text-xs text-concrete italic">{t('homeDashboard.noRecentNotes')}</p>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="rounded-2xl border border-border/30 bg-white dark:bg-zinc-900 overflow-hidden">
|
||||
<div className="px-5 pt-4">
|
||||
<DashboardWidgetTitleRow
|
||||
widgetId="resume"
|
||||
icon={<Play size={11} className="text-brand-accent" fill="currentColor" />}
|
||||
title={t('homeDashboard.continue')}
|
||||
className="mb-2"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<motion.button
|
||||
type="button"
|
||||
whileHover={prefersReducedMotion ? undefined : { y: -1 }}
|
||||
onClick={() => onSelect(hero.id, hero.notebookId)}
|
||||
className="w-full text-start px-5 pb-5 group cursor-pointer"
|
||||
>
|
||||
<div
|
||||
className="p-4 rounded-xl border border-border/25 bg-gradient-to-br from-stone-50/80 to-white dark:from-zinc-950/50 dark:to-zinc-900/80 group-hover:border-brand-accent/35 group-hover:shadow-md transition-all"
|
||||
>
|
||||
<div className="flex items-start justify-between gap-3 mb-2">
|
||||
<span
|
||||
className="text-[8px] font-mono font-bold uppercase px-2 py-0.5 rounded text-white shrink-0"
|
||||
style={{ backgroundColor: hero.notebookColor }}
|
||||
>
|
||||
{hero.notebookName}
|
||||
</span>
|
||||
<span className="text-[9px] font-mono text-concrete/70 shrink-0">
|
||||
{formatRelativeTime(hero.updatedAt)}
|
||||
</span>
|
||||
</div>
|
||||
<h3 className="text-base sm:text-lg font-serif font-semibold text-ink dark:text-dark-ink group-hover:text-brand-accent transition-colors leading-snug mb-2 line-clamp-2">
|
||||
{hero.title || t('homeDashboard.untitled')}
|
||||
</h3>
|
||||
{hero.excerpt && (
|
||||
<p className="text-[11px] text-concrete leading-relaxed line-clamp-3">
|
||||
{hero.excerpt}
|
||||
</p>
|
||||
)}
|
||||
<div className="flex items-center gap-1 mt-3 text-[9px] font-mono font-bold uppercase text-brand-accent opacity-0 group-hover:opacity-100 transition-opacity">
|
||||
{t('homeDashboard.resumeOpen')}
|
||||
<ChevronRight size={12} />
|
||||
</div>
|
||||
</div>
|
||||
</motion.button>
|
||||
|
||||
{rest.length > 0 && (
|
||||
<div className="flex gap-2 px-5 pb-4 overflow-x-auto custom-scrollbar">
|
||||
{rest.map(note => (
|
||||
<button
|
||||
key={note.id}
|
||||
type="button"
|
||||
onClick={() => onSelect(note.id, note.notebookId)}
|
||||
className="shrink-0 max-w-[200px] p-2.5 rounded-xl border border-border/20 bg-stone-50/50 dark:bg-zinc-950/30 hover:border-brand-accent/30 transition-all text-start group"
|
||||
>
|
||||
<p className="text-[10px] font-semibold text-ink dark:text-dark-ink truncate group-hover:text-brand-accent transition-colors">
|
||||
{note.title || t('homeDashboard.untitled')}
|
||||
</p>
|
||||
<p className="text-[8px] font-mono text-concrete/60 mt-0.5">
|
||||
{formatRelativeTime(note.updatedAt)}
|
||||
</p>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
113
memento-note/components/dashboard-sentiment-chip.tsx
Normal file
113
memento-note/components/dashboard-sentiment-chip.tsx
Normal file
@@ -0,0 +1,113 @@
|
||||
'use client'
|
||||
|
||||
import { Heart } from 'lucide-react'
|
||||
import type { LucideIcon } from 'lucide-react'
|
||||
import { useLanguage } from '@/lib/i18n'
|
||||
import { DashboardWidgetTitleRow } from '@/components/dashboard-widget-title-row'
|
||||
|
||||
interface EmotionMeta {
|
||||
Icon: LucideIcon
|
||||
color: string
|
||||
}
|
||||
|
||||
export interface DashboardSentimentChipProps {
|
||||
available: boolean
|
||||
loading?: boolean
|
||||
dominantEmotion?: string
|
||||
summary?: string
|
||||
emotions?: Record<string, number>
|
||||
emotionMeta: Record<string, EmotionMeta>
|
||||
}
|
||||
|
||||
export function DashboardSentimentChip({
|
||||
available,
|
||||
loading,
|
||||
dominantEmotion,
|
||||
summary,
|
||||
emotions,
|
||||
emotionMeta,
|
||||
}: DashboardSentimentChipProps) {
|
||||
const { t } = useLanguage()
|
||||
|
||||
if (loading) {
|
||||
return (
|
||||
<div className="rounded-2xl border border-border/30 bg-white dark:bg-zinc-900 p-4">
|
||||
<div className="h-24 rounded-xl bg-stone-50 dark:bg-zinc-950/30 animate-pulse" />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="rounded-2xl border border-border/30 bg-white dark:bg-zinc-900 p-4 min-h-[140px]">
|
||||
<DashboardWidgetTitleRow
|
||||
widgetId="sentiment"
|
||||
icon={<Heart size={12} className="text-brand-accent" />}
|
||||
title={t('homeDashboard.sentiment')}
|
||||
/>
|
||||
|
||||
{!available || !dominantEmotion ? (
|
||||
<p className="text-[11px] text-concrete italic leading-relaxed">
|
||||
{t('homeDashboard.notEnoughNotes')}
|
||||
</p>
|
||||
) : (
|
||||
<div className="space-y-3">
|
||||
<div className="flex items-center gap-3">
|
||||
{(() => {
|
||||
const meta = emotionMeta[dominantEmotion] || emotionMeta.reflective
|
||||
const Icon = meta?.Icon
|
||||
return (
|
||||
<div
|
||||
className="w-10 h-10 rounded-xl flex items-center justify-center shrink-0"
|
||||
style={{ backgroundColor: `${meta.color}18`, color: meta.color }}
|
||||
>
|
||||
{Icon && <Icon size={18} strokeWidth={1.75} />}
|
||||
</div>
|
||||
)
|
||||
})()}
|
||||
<div className="min-w-0">
|
||||
<p className="text-lg font-serif font-semibold text-ink dark:text-dark-ink">
|
||||
{t(`homeDashboard.emotions.${dominantEmotion}`)}
|
||||
</p>
|
||||
<p className="text-[9px] font-mono uppercase tracking-wider text-concrete">
|
||||
{t('homeDashboard.sentimentDominant')}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{summary && (
|
||||
<p className="text-[11px] text-concrete leading-relaxed border-s-2 border-brand-accent/30 ps-3">
|
||||
{summary}
|
||||
</p>
|
||||
)}
|
||||
|
||||
{emotions && (
|
||||
<div className="space-y-2 pt-1">
|
||||
{Object.entries(emotions)
|
||||
.sort(([, a], [, b]) => b - a)
|
||||
.slice(0, 4)
|
||||
.map(([key, val]) => {
|
||||
const em = emotionMeta[key]
|
||||
return (
|
||||
<div key={key} className="flex items-center gap-2">
|
||||
<span className="text-[8px] font-mono uppercase text-concrete w-16 truncate">
|
||||
{t(`homeDashboard.emotions.${key}`)}
|
||||
</span>
|
||||
<div className="flex-1 h-1.5 rounded-full bg-stone-100 dark:bg-zinc-800 overflow-hidden">
|
||||
<div
|
||||
className="h-full rounded-full"
|
||||
style={{
|
||||
width: `${Math.min(val * 100, 100)}%`,
|
||||
backgroundColor: em?.color || 'var(--color-brand-accent)',
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
1052
memento-note/components/dashboard-view.tsx
Normal file
1052
memento-note/components/dashboard-view.tsx
Normal file
File diff suppressed because it is too large
Load Diff
402
memento-note/components/dashboard-widget-grid.tsx
Normal file
402
memento-note/components/dashboard-widget-grid.tsx
Normal file
@@ -0,0 +1,402 @@
|
||||
'use client'
|
||||
|
||||
import { useCallback, useEffect, useRef, useState } from 'react'
|
||||
import {
|
||||
DndContext,
|
||||
closestCenter,
|
||||
PointerSensor,
|
||||
TouchSensor,
|
||||
useSensor,
|
||||
useSensors,
|
||||
type DragEndEvent,
|
||||
} from '@dnd-kit/core'
|
||||
import {
|
||||
SortableContext,
|
||||
rectSortingStrategy,
|
||||
useSortable,
|
||||
verticalListSortingStrategy,
|
||||
} from '@dnd-kit/sortable'
|
||||
import { CSS } from '@dnd-kit/utilities'
|
||||
import { GripVertical, X, Plus, RotateCcw, Check, LayoutGrid, Eye, EyeOff } from 'lucide-react'
|
||||
import { useLanguage } from '@/lib/i18n'
|
||||
import {
|
||||
getDefaultDashboardLayout,
|
||||
resetDashboardLayout,
|
||||
DASHBOARD_CATEGORY_ORDER,
|
||||
DASHBOARD_WIDGET_META,
|
||||
catalogByCategory,
|
||||
hiddenWidgetIds,
|
||||
isWidgetVisible,
|
||||
normalizeDashboardLayout,
|
||||
reorderWidgets,
|
||||
setWidgetVisibility,
|
||||
visibleWidgetsInZone,
|
||||
type DashboardLayout,
|
||||
type DashboardWidgetId,
|
||||
type DashboardWidgetPlacement,
|
||||
type DashboardWidgetZone,
|
||||
} from '@/lib/dashboard/layout'
|
||||
import { toast } from 'sonner'
|
||||
|
||||
interface DashboardWidgetGridProps {
|
||||
renderWidget: (id: DashboardWidgetId) => React.ReactNode
|
||||
}
|
||||
|
||||
function SortableWidget({
|
||||
placement,
|
||||
editMode,
|
||||
onHide,
|
||||
children,
|
||||
}: {
|
||||
placement: DashboardWidgetPlacement
|
||||
editMode: boolean
|
||||
onHide: (id: DashboardWidgetId) => void
|
||||
children: React.ReactNode
|
||||
}) {
|
||||
const { t } = useLanguage()
|
||||
const meta = DASHBOARD_WIDGET_META[placement.id]
|
||||
const {
|
||||
attributes,
|
||||
listeners,
|
||||
setNodeRef,
|
||||
transform,
|
||||
transition,
|
||||
isDragging,
|
||||
} = useSortable({ id: placement.id, disabled: !editMode })
|
||||
|
||||
const style = {
|
||||
transform: CSS.Transform.toString(transform),
|
||||
transition,
|
||||
zIndex: isDragging ? 20 : undefined,
|
||||
}
|
||||
|
||||
return (
|
||||
<div
|
||||
ref={setNodeRef}
|
||||
style={style}
|
||||
className={`relative w-full ${
|
||||
isDragging ? 'opacity-90 scale-[1.01]' : ''
|
||||
} ${editMode ? 'ring-2 ring-brand-accent/25 ring-offset-2 ring-offset-[#F9F8F6] dark:ring-offset-[#0D0D0D] rounded-2xl' : ''}`}
|
||||
>
|
||||
{editMode && (
|
||||
<div className="absolute top-2 end-2 z-20 flex items-center gap-1">
|
||||
<button
|
||||
type="button"
|
||||
className="p-1.5 rounded-lg bg-white/95 dark:bg-zinc-900/95 border border-border/40 shadow-sm cursor-grab active:cursor-grabbing text-concrete hover:text-ink"
|
||||
aria-label={t('homeDashboard.widgetDrag')}
|
||||
{...attributes}
|
||||
{...listeners}
|
||||
>
|
||||
<GripVertical size={12} />
|
||||
</button>
|
||||
{!meta.required && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => onHide(placement.id)}
|
||||
className="p-1.5 rounded-lg bg-white/95 dark:bg-zinc-900/95 border border-border/40 shadow-sm text-concrete hover:text-rose-500"
|
||||
aria-label={t('homeDashboard.widgetHide')}
|
||||
>
|
||||
<X size={12} />
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
{children}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function ZoneColumn({
|
||||
zone,
|
||||
placements,
|
||||
editMode,
|
||||
onHide,
|
||||
renderWidget,
|
||||
}: {
|
||||
zone: DashboardWidgetZone
|
||||
placements: DashboardWidgetPlacement[]
|
||||
editMode: boolean
|
||||
onHide: (id: DashboardWidgetId) => void
|
||||
renderWidget: (id: DashboardWidgetId) => React.ReactNode
|
||||
}) {
|
||||
if (placements.length === 0) return null
|
||||
|
||||
return (
|
||||
<SortableContext items={placements.map(w => w.id)} strategy={verticalListSortingStrategy}>
|
||||
<div className="flex flex-col gap-4">
|
||||
{placements.map(placement => (
|
||||
<SortableWidget
|
||||
key={placement.id}
|
||||
placement={placement}
|
||||
editMode={editMode}
|
||||
onHide={onHide}
|
||||
>
|
||||
{renderWidget(placement.id)}
|
||||
</SortableWidget>
|
||||
))}
|
||||
</div>
|
||||
</SortableContext>
|
||||
)
|
||||
}
|
||||
|
||||
export function DashboardWidgetGrid({ renderWidget }: DashboardWidgetGridProps) {
|
||||
const { t } = useLanguage()
|
||||
const [layout, setLayout] = useState<DashboardLayout>(() => getDefaultDashboardLayout())
|
||||
const [editMode, setEditMode] = useState(false)
|
||||
const [catalogOpen, setCatalogOpen] = useState(false)
|
||||
const [loaded, setLoaded] = useState(false)
|
||||
const saveTimer = useRef<ReturnType<typeof setTimeout> | null>(null)
|
||||
|
||||
useEffect(() => {
|
||||
fetch('/api/dashboard/layout', { cache: 'no-store' })
|
||||
.then(r => r.ok ? r.json() : null)
|
||||
.then(json => {
|
||||
if (json?.layout) setLayout(normalizeDashboardLayout(json.layout))
|
||||
})
|
||||
.catch(() => {})
|
||||
.finally(() => setLoaded(true))
|
||||
}, [])
|
||||
|
||||
const persistLayout = useCallback((next: DashboardLayout, immediate = false) => {
|
||||
if (saveTimer.current) clearTimeout(saveTimer.current)
|
||||
const save = () => {
|
||||
fetch('/api/dashboard/layout', {
|
||||
method: 'PUT',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ layout: next }),
|
||||
}).catch(() => {})
|
||||
}
|
||||
if (immediate) save()
|
||||
else saveTimer.current = setTimeout(save, 600)
|
||||
}, [])
|
||||
|
||||
const applyLayout = useCallback((next: DashboardLayout, immediate = false) => {
|
||||
const normalized = normalizeDashboardLayout(next)
|
||||
setLayout(normalized)
|
||||
persistLayout(normalized, immediate)
|
||||
}, [persistLayout])
|
||||
|
||||
const sensors = useSensors(
|
||||
useSensor(PointerSensor, { activationConstraint: { distance: 8 } }),
|
||||
useSensor(TouchSensor, { activationConstraint: { delay: 180, tolerance: 8 } }),
|
||||
)
|
||||
|
||||
const handleDragEnd = useCallback((event: DragEndEvent) => {
|
||||
const { active, over } = event
|
||||
if (!over || active.id === over.id) return
|
||||
applyLayout(reorderWidgets(layout, active.id as DashboardWidgetId, over.id as DashboardWidgetId))
|
||||
}, [applyLayout, layout])
|
||||
|
||||
const handleHide = useCallback((id: DashboardWidgetId) => {
|
||||
applyLayout(setWidgetVisibility(layout, id, false))
|
||||
}, [applyLayout, layout])
|
||||
|
||||
const handleToggle = useCallback((id: DashboardWidgetId) => {
|
||||
const visible = isWidgetVisible(layout, id)
|
||||
if (visible) {
|
||||
applyLayout(setWidgetVisibility(layout, id, false))
|
||||
} else {
|
||||
const maxOrder = Math.max(...layout.widgets.map(w => w.order), 0)
|
||||
applyLayout({
|
||||
...layout,
|
||||
widgets: layout.widgets.map(w =>
|
||||
w.id === id ? { ...w, visible: true, order: maxOrder + 1 } : w,
|
||||
),
|
||||
})
|
||||
}
|
||||
}, [applyLayout, layout])
|
||||
|
||||
const handleReset = useCallback(() => {
|
||||
const fresh = resetDashboardLayout()
|
||||
setLayout(fresh)
|
||||
persistLayout(fresh, true)
|
||||
setCatalogOpen(false)
|
||||
toast.success(t('homeDashboard.widgetResetDone'))
|
||||
}, [persistLayout, t])
|
||||
|
||||
const fullWidgets = visibleWidgetsInZone(layout, 'full')
|
||||
const mainWidgets = visibleWidgetsInZone(layout, 'main')
|
||||
const sideWidgets = visibleWidgetsInZone(layout, 'side')
|
||||
const hidden = hiddenWidgetIds(layout)
|
||||
const catalog = catalogByCategory(layout)
|
||||
const hasVisibleWidgets = fullWidgets.length + mainWidgets.length + sideWidgets.length > 0
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className="space-y-4">
|
||||
{loaded ? (
|
||||
hasVisibleWidgets ? (
|
||||
<DndContext sensors={sensors} collisionDetection={closestCenter} onDragEnd={handleDragEnd}>
|
||||
{fullWidgets.length > 0 && (
|
||||
<SortableContext items={fullWidgets.map(w => w.id)} strategy={rectSortingStrategy}>
|
||||
<div className="flex flex-col gap-4">
|
||||
{fullWidgets.map(placement => (
|
||||
<SortableWidget
|
||||
key={placement.id}
|
||||
placement={placement}
|
||||
editMode={editMode}
|
||||
onHide={handleHide}
|
||||
>
|
||||
{renderWidget(placement.id)}
|
||||
</SortableWidget>
|
||||
))}
|
||||
</div>
|
||||
</SortableContext>
|
||||
)}
|
||||
|
||||
{(mainWidgets.length > 0 || sideWidgets.length > 0) && (
|
||||
<div className="grid grid-cols-12 gap-4 items-start">
|
||||
{mainWidgets.length > 0 && (
|
||||
<div className="col-span-12 lg:col-span-8">
|
||||
<ZoneColumn
|
||||
zone="main"
|
||||
placements={mainWidgets}
|
||||
editMode={editMode}
|
||||
onHide={handleHide}
|
||||
renderWidget={renderWidget}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
{sideWidgets.length > 0 && (
|
||||
<div className="col-span-12 lg:col-span-4">
|
||||
<ZoneColumn
|
||||
zone="side"
|
||||
placements={sideWidgets}
|
||||
editMode={editMode}
|
||||
onHide={handleHide}
|
||||
renderWidget={renderWidget}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</DndContext>
|
||||
) : (
|
||||
<div className="rounded-2xl border border-dashed border-border/40 bg-white/60 dark:bg-zinc-900/60 p-8 text-center">
|
||||
<p className="text-sm font-serif text-ink dark:text-dark-ink mb-2">{t('homeDashboard.layoutEmptyTitle')}</p>
|
||||
<p className="text-[11px] text-concrete mb-4 max-w-md mx-auto">{t('homeDashboard.layoutEmptyHint')}</p>
|
||||
<button
|
||||
type="button"
|
||||
onClick={handleReset}
|
||||
className="inline-flex items-center gap-2 px-4 py-2 rounded-xl bg-brand-accent text-white text-[10px] font-mono uppercase font-bold hover:bg-brand-accent/90 transition-colors"
|
||||
>
|
||||
<RotateCcw size={12} />
|
||||
{t('homeDashboard.widgetReset')}
|
||||
</button>
|
||||
</div>
|
||||
)
|
||||
) : (
|
||||
<div className="grid grid-cols-12 gap-5">
|
||||
<div className="col-span-12 h-20 rounded-2xl bg-stone-50 dark:bg-zinc-950/30 animate-pulse" />
|
||||
<div className="col-span-12 lg:col-span-8 h-48 rounded-2xl bg-stone-50 dark:bg-zinc-950/30 animate-pulse" />
|
||||
<div className="col-span-12 lg:col-span-4 h-48 rounded-2xl bg-stone-50 dark:bg-zinc-950/30 animate-pulse" />
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="fixed bottom-6 left-1/2 -translate-x-1/2 z-40 flex items-center gap-2 px-3 py-2 rounded-2xl bg-ink/92 dark:bg-zinc-900/95 text-white shadow-xl border border-white/10 backdrop-blur-md">
|
||||
{editMode ? (
|
||||
<>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setCatalogOpen(v => !v)}
|
||||
className="inline-flex items-center gap-1.5 text-[10px] font-mono uppercase font-bold px-3 py-2 rounded-xl bg-white/10 hover:bg-white/15 transition-colors"
|
||||
>
|
||||
<Plus size={12} />
|
||||
{t('homeDashboard.widgetCatalog')}
|
||||
{hidden.length > 0 && (
|
||||
<span className="px-1.5 py-0.5 rounded-md bg-brand-accent/90 text-[9px]">{hidden.length}</span>
|
||||
)}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={handleReset}
|
||||
className="inline-flex items-center gap-1.5 text-[10px] font-mono uppercase font-bold px-3 py-2 rounded-xl bg-white/10 hover:bg-white/15 transition-colors"
|
||||
>
|
||||
<RotateCcw size={12} />
|
||||
{t('homeDashboard.widgetReset')}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => { setEditMode(false); setCatalogOpen(false) }}
|
||||
className="inline-flex items-center gap-1.5 text-[10px] font-mono uppercase font-bold px-3 py-2 rounded-xl bg-brand-accent text-white hover:bg-brand-accent/90 transition-colors"
|
||||
>
|
||||
<Check size={12} />
|
||||
{t('homeDashboard.widgetDone')}
|
||||
</button>
|
||||
</>
|
||||
) : (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setEditMode(true)}
|
||||
className="inline-flex items-center gap-1.5 text-[10px] font-mono uppercase font-bold px-4 py-2 rounded-xl bg-white/10 hover:bg-white/15 transition-colors"
|
||||
>
|
||||
<LayoutGrid size={12} />
|
||||
{t('homeDashboard.widgetCustomize')}
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{editMode && catalogOpen && (
|
||||
<div className="fixed bottom-20 left-1/2 -translate-x-1/2 z-40 w-[min(520px,calc(100vw-2rem))] max-h-[min(60vh,480px)] overflow-y-auto custom-scrollbar p-4 rounded-2xl bg-white dark:bg-zinc-900 border border-border/40 shadow-2xl">
|
||||
<p className="text-[9px] font-mono font-bold uppercase tracking-wider text-concrete mb-3">
|
||||
{t('homeDashboard.widgetCatalogTitle')}
|
||||
</p>
|
||||
<div className="space-y-4">
|
||||
{DASHBOARD_CATEGORY_ORDER.map(category => {
|
||||
const ids = catalog[category]
|
||||
if (ids.length === 0) return null
|
||||
return (
|
||||
<div key={category}>
|
||||
<p className="text-[8px] font-mono font-bold uppercase tracking-[0.15em] text-brand-accent mb-2">
|
||||
{t(`homeDashboard.widgetCategories.${category}`)}
|
||||
</p>
|
||||
<div className="space-y-1.5">
|
||||
{ids.map(id => {
|
||||
const meta = DASHBOARD_WIDGET_META[id]
|
||||
const active = isWidgetVisible(layout, id)
|
||||
return (
|
||||
<button
|
||||
key={id}
|
||||
type="button"
|
||||
onClick={() => !meta.required && handleToggle(id)}
|
||||
disabled={meta.required}
|
||||
className={`w-full flex items-start gap-3 p-2.5 rounded-xl border text-start transition-colors ${
|
||||
active
|
||||
? 'border-brand-accent/30 bg-brand-accent/[0.04]'
|
||||
: 'border-border/25 bg-stone-50/80 dark:bg-zinc-950/40 hover:border-brand-accent/25'
|
||||
} ${meta.required ? 'opacity-80 cursor-default' : 'cursor-pointer'}`}
|
||||
>
|
||||
<div className={`mt-0.5 shrink-0 w-6 h-6 rounded-lg flex items-center justify-center ${
|
||||
active ? 'bg-brand-accent/15 text-brand-accent' : 'bg-stone-200/60 dark:bg-zinc-800 text-concrete'
|
||||
}`}>
|
||||
{active ? <Eye size={11} /> : <EyeOff size={11} />}
|
||||
</div>
|
||||
<div className="min-w-0 flex-1">
|
||||
<p className="text-[11px] font-mono font-bold uppercase tracking-wide text-ink dark:text-dark-ink">
|
||||
{t(`homeDashboard.widgets.${id}`)}
|
||||
</p>
|
||||
<p className="text-[10px] text-concrete leading-snug mt-0.5">
|
||||
{t(`homeDashboard.widgetDescriptions.${id}`)}
|
||||
</p>
|
||||
</div>
|
||||
{!meta.required && (
|
||||
<span className={`shrink-0 text-[9px] font-mono font-bold uppercase px-2 py-1 rounded-lg ${
|
||||
active ? 'text-concrete' : 'text-brand-accent bg-brand-accent/10'
|
||||
}`}>
|
||||
{active ? t('homeDashboard.widgetActive') : t('homeDashboard.widgetAddShort')}
|
||||
</span>
|
||||
)}
|
||||
</button>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
)
|
||||
}
|
||||
57
memento-note/components/dashboard-widget-help.tsx
Normal file
57
memento-note/components/dashboard-widget-help.tsx
Normal file
@@ -0,0 +1,57 @@
|
||||
'use client'
|
||||
|
||||
import { useState } from 'react'
|
||||
import { HelpCircle, X } from 'lucide-react'
|
||||
import { useLanguage } from '@/lib/i18n'
|
||||
import type { DashboardWidgetId } from '@/lib/dashboard/layout'
|
||||
|
||||
interface DashboardWidgetHelpProps {
|
||||
widgetId: DashboardWidgetId
|
||||
className?: string
|
||||
}
|
||||
|
||||
export function DashboardWidgetHelp({ widgetId, className = '' }: DashboardWidgetHelpProps) {
|
||||
const { t } = useLanguage()
|
||||
const [open, setOpen] = useState(false)
|
||||
const helpKey = `homeDashboard.widgetHelp.${widgetId}`
|
||||
const text = t(helpKey)
|
||||
|
||||
if (text === helpKey) return null
|
||||
|
||||
return (
|
||||
<div className={`relative ${className}`}>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setOpen(v => !v)}
|
||||
className={`p-1 rounded-full border transition-colors ${
|
||||
open
|
||||
? 'border-brand-accent/40 bg-brand-accent/10 text-brand-accent'
|
||||
: 'border-border/30 bg-white/90 dark:bg-zinc-900/90 text-concrete hover:text-brand-accent hover:border-brand-accent/30'
|
||||
}`}
|
||||
aria-label={t('homeDashboard.widgetHelpLabel')}
|
||||
aria-expanded={open}
|
||||
>
|
||||
<HelpCircle size={12} strokeWidth={2} />
|
||||
</button>
|
||||
|
||||
{open && (
|
||||
<div className="absolute top-full end-0 mt-1.5 z-30 w-[min(280px,calc(100vw-3rem))] p-3 rounded-xl border border-brand-accent/20 bg-white dark:bg-zinc-900 shadow-lg">
|
||||
<div className="flex items-start justify-between gap-2 mb-1">
|
||||
<p className="text-[8px] font-mono font-bold uppercase tracking-wider text-brand-accent">
|
||||
{t(`homeDashboard.widgets.${widgetId}`)}
|
||||
</p>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setOpen(false)}
|
||||
className="text-concrete hover:text-ink shrink-0"
|
||||
aria-label={t('homeDashboard.widgetHelpClose')}
|
||||
>
|
||||
<X size={10} />
|
||||
</button>
|
||||
</div>
|
||||
<p className="text-[10px] text-concrete leading-relaxed">{text}</p>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
37
memento-note/components/dashboard-widget-title-row.tsx
Normal file
37
memento-note/components/dashboard-widget-title-row.tsx
Normal file
@@ -0,0 +1,37 @@
|
||||
'use client'
|
||||
|
||||
import type { ReactNode } from 'react'
|
||||
import { DashboardWidgetHelp } from '@/components/dashboard-widget-help'
|
||||
import type { DashboardWidgetId } from '@/lib/dashboard/layout'
|
||||
|
||||
interface DashboardWidgetTitleRowProps {
|
||||
widgetId: DashboardWidgetId
|
||||
icon?: ReactNode
|
||||
title: string
|
||||
actions?: ReactNode
|
||||
className?: string
|
||||
}
|
||||
|
||||
/** Titre widget : actions d’abord, aide « ? » en dernier — ne masque jamais la navigation. */
|
||||
export function DashboardWidgetTitleRow({
|
||||
widgetId,
|
||||
icon,
|
||||
title,
|
||||
actions,
|
||||
className = 'mb-3',
|
||||
}: DashboardWidgetTitleRowProps) {
|
||||
return (
|
||||
<div className={`flex items-center justify-between gap-2 ${className}`}>
|
||||
<div className="flex items-center gap-2 min-w-0 flex-1">
|
||||
{icon}
|
||||
<h2 className="text-[10px] font-mono font-bold uppercase tracking-widest text-ink dark:text-dark-ink truncate">
|
||||
{title}
|
||||
</h2>
|
||||
</div>
|
||||
<div className="flex items-center gap-1.5 shrink-0">
|
||||
{actions}
|
||||
<DashboardWidgetHelp widgetId={widgetId} />
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -21,7 +21,7 @@ import {
|
||||
import { NotebookSuggestionToast } from '@/components/notebook-suggestion-toast'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Plus, ArrowUpDown, Search, Sparkles, FileText, FolderOpen, ChevronRight, ChevronDown, Tag as TagIcon, X, Menu, LayoutGrid, List, Table, Columns3, CalendarDays, Wand2, Download, Upload, Globe } from 'lucide-react'
|
||||
import { emitNoteChange } from '@/lib/note-change-sync'
|
||||
import { emitNoteChange, NOTE_CHANGE_EVENT, type NoteChangeEvent } from '@/lib/note-change-sync'
|
||||
import { useReminderCheck } from '@/hooks/use-reminder-check'
|
||||
import { useAutoLabelSuggestion } from '@/hooks/use-auto-label-suggestion'
|
||||
import { useNotebooks } from '@/context/notebooks-context'
|
||||
@@ -34,6 +34,7 @@ import { StudyPlannerDialog } from '@/components/wizard/study-planner-dialog'
|
||||
import { NotebookOrganizerDialog } from '@/components/wizard/notebook-organizer-dialog'
|
||||
import { toast } from 'sonner'
|
||||
import { AnimatePresence, motion } from 'motion/react'
|
||||
import { isDashboardHomeRoute } from '@/lib/dashboard/home-route'
|
||||
|
||||
|
||||
type SortOrder = 'newest' | 'oldest' | 'alpha' | 'manual'
|
||||
@@ -58,6 +59,10 @@ const OrganizeNotebookDialog = dynamic(
|
||||
() => import('@/components/organize-notebook-dialog').then(m => ({ default: m.OrganizeNotebookDialog })),
|
||||
{ ssr: false }
|
||||
)
|
||||
const DashboardView = dynamic(
|
||||
() => import('@/components/dashboard-view').then(m => ({ default: m.DashboardView })),
|
||||
{ ssr: false }
|
||||
)
|
||||
const NotebookSiteDialog = dynamic(
|
||||
() => import('@/components/wizard/notebook-site-dialog').then(m => ({ default: m.NotebookSiteDialog })),
|
||||
{ ssr: false }
|
||||
@@ -225,15 +230,12 @@ export function HomeClient({
|
||||
}, [])
|
||||
|
||||
// Sidebar carnet / inbox: fermer l'éditeur plein écran (comme la ref. architectural-grid)
|
||||
// On GARDE forceList dans l'URL pour distinguer "liste" du "dashboard"
|
||||
useEffect(() => {
|
||||
if (searchParams.get('forceList') === '1') {
|
||||
setEditingNote(null)
|
||||
const params = new URLSearchParams(searchParams.toString())
|
||||
params.delete('forceList')
|
||||
const newUrl = params.toString() ? `/home?${params.toString()}` : '/home'
|
||||
router.replace(newUrl, { scroll: false })
|
||||
}
|
||||
}, [searchParams, router])
|
||||
}, [searchParams])
|
||||
|
||||
const fetchNotesForCurrentView = useCallback(
|
||||
async (options?: { silent?: boolean }) => {
|
||||
@@ -611,6 +613,25 @@ export function HomeClient({
|
||||
})
|
||||
}, [patchNoteInList])
|
||||
|
||||
// Écoute les mutations externes (versioning activé depuis éditeur, etc.)
|
||||
useEffect(() => {
|
||||
const onNoteChange = (e: Event) => {
|
||||
const detail = (e as CustomEvent<NoteChangeEvent>).detail
|
||||
if (!detail) return
|
||||
if (detail.type === 'updated') {
|
||||
patchNoteInList(detail.note.id, detail.note)
|
||||
setPinnedNotes(prev => prev.map(n => n.id === detail.note.id ? { ...n, ...detail.note } : n))
|
||||
} else if (detail.type === 'deleted') {
|
||||
removeNoteFromList(detail.noteId)
|
||||
setPinnedNotes(prev => prev.filter(n => n.id !== detail.noteId))
|
||||
} else if (detail.type === 'created' && detail.note) {
|
||||
setNotes(prev => [detail.note, ...prev])
|
||||
}
|
||||
}
|
||||
window.addEventListener(NOTE_CHANGE_EVENT, onNoteChange)
|
||||
return () => window.removeEventListener(NOTE_CHANGE_EVENT, onNoteChange)
|
||||
}, [patchNoteInList])
|
||||
|
||||
const handleGridReorder = useCallback(
|
||||
async (orderedIds: string[]) => {
|
||||
setSortOrder('manual')
|
||||
@@ -802,6 +823,16 @@ export function HomeClient({
|
||||
emitNoteChange({ type: 'updated', note: savedNote })
|
||||
}, [])
|
||||
|
||||
// Show dashboard when no active filter/view params
|
||||
const showDashboard = !editingNote && isDashboardHomeRoute('/home', searchParams)
|
||||
|
||||
const handleDashboardNoteSelect = useCallback((noteId: string, notebookId: string | null) => {
|
||||
const params = new URLSearchParams()
|
||||
params.set('openNote', noteId)
|
||||
if (notebookId) params.set('notebook', notebookId)
|
||||
router.push(`/home?${params.toString()}`)
|
||||
}, [router])
|
||||
|
||||
return (
|
||||
<div
|
||||
className={cn(
|
||||
@@ -819,6 +850,8 @@ export function HomeClient({
|
||||
fullPage
|
||||
/>
|
||||
</div>
|
||||
) : showDashboard ? (
|
||||
<DashboardView onNoteSelect={handleDashboardNoteSelect} />
|
||||
) : (
|
||||
<div className="flex-1 overflow-y-auto min-h-0 bg-memento-paper dark:bg-background flex flex-col">
|
||||
<div
|
||||
|
||||
729
memento-note/components/intelligence-hub.tsx
Normal file
729
memento-note/components/intelligence-hub.tsx
Normal file
@@ -0,0 +1,729 @@
|
||||
'use client'
|
||||
|
||||
import { useCallback, useEffect, useMemo, useState } from 'react'
|
||||
import { useRouter } from 'next/navigation'
|
||||
import { motion, AnimatePresence } from 'motion/react'
|
||||
import {
|
||||
Sparkles, Zap, Lightbulb, Bot, ChevronLeft, ChevronRight,
|
||||
ExternalLink, GitCompare, X, RefreshCw, Loader2, Link2, Brain, ArrowRight,
|
||||
} from 'lucide-react'
|
||||
import { useLanguage } from '@/lib/i18n'
|
||||
import { DashboardWidgetTitleRow } from '@/components/dashboard-widget-title-row'
|
||||
import { MEMORY_ECHO_LEGACY_EN_FALLBACKS } from '@/lib/ai/memory-echo-i18n'
|
||||
|
||||
// ─── Types ─────────────────────────────────────────────
|
||||
|
||||
export interface IntelBriefingInsight {
|
||||
id: string
|
||||
insight: string
|
||||
score: number
|
||||
date: string
|
||||
viewed: boolean
|
||||
note1: { id: string; title: string | null }
|
||||
note2: { id: string; title: string | null }
|
||||
note1Excerpt?: string
|
||||
note2Excerpt?: string
|
||||
}
|
||||
|
||||
export interface IntelBridgeNote {
|
||||
noteId: string
|
||||
bridgeScore: number
|
||||
clusterNames?: string[]
|
||||
note?: { id: string; title: string | null; content?: string }
|
||||
}
|
||||
|
||||
export interface IntelBridgeSuggestion {
|
||||
clusterAId: number
|
||||
clusterBId: number
|
||||
clusterAName: string
|
||||
clusterBName: string
|
||||
suggestedTitle: string
|
||||
suggestedContent: string
|
||||
justification: string
|
||||
}
|
||||
|
||||
export interface IntelAgentAction {
|
||||
id: string
|
||||
agentName: string
|
||||
result: string | null
|
||||
createdAt: string
|
||||
}
|
||||
|
||||
type IntelFilter = 'all' | 'connections' | 'bridges' | 'ideas' | 'agents'
|
||||
|
||||
type IntelItem =
|
||||
| { kind: 'insight'; id: string; priority: number; insight: IntelBriefingInsight }
|
||||
| { kind: 'bridge'; id: string; priority: number; bridge: IntelBridgeNote }
|
||||
| { kind: 'suggestion'; id: string; priority: number; suggestion: IntelBridgeSuggestion }
|
||||
| { kind: 'agent'; id: string; priority: number; agent: IntelAgentAction }
|
||||
|
||||
const CLUSTER_COLORS = ['#F87171', '#60A5FA', '#34D399', '#FBBF24', '#A78BFA', '#F472B6', '#2DD4BF']
|
||||
|
||||
const FILTER_KINDS: Record<IntelFilter, IntelItem['kind'][] | null> = {
|
||||
all: null,
|
||||
connections: ['insight'],
|
||||
bridges: ['bridge'],
|
||||
ideas: ['suggestion'],
|
||||
agents: ['agent'],
|
||||
}
|
||||
|
||||
function stripHtml(html: string): string {
|
||||
return html.replace(/<[^>]+>/g, ' ').replace(/ /g, ' ').replace(/\s+/g, ' ').trim()
|
||||
}
|
||||
|
||||
function formatRelativeTime(
|
||||
dateStr: string,
|
||||
t: (key: string, params?: Record<string, string | number>) => string,
|
||||
): string {
|
||||
const diff = Date.now() - new Date(dateStr).getTime()
|
||||
const mins = Math.floor(diff / 60000)
|
||||
const hours = Math.floor(diff / 3600000)
|
||||
const days = Math.floor(diff / 86400000)
|
||||
if (mins < 1) return t('time.justNow')
|
||||
if (mins < 60) return t('time.minutesAgo', { count: mins })
|
||||
if (hours < 24) return t('time.hoursAgo', { count: hours })
|
||||
return t('time.daysAgo', { count: days })
|
||||
}
|
||||
|
||||
// ─── Visual: lien entre deux notes ─────────────────────
|
||||
|
||||
function ConnectionDiagram({
|
||||
note1Title,
|
||||
note2Title,
|
||||
score,
|
||||
color = '#6366F1',
|
||||
}: {
|
||||
note1Title: string
|
||||
note2Title: string
|
||||
score: number
|
||||
color?: string
|
||||
}) {
|
||||
return (
|
||||
<div className="flex items-center gap-2 py-3">
|
||||
<div
|
||||
className="flex-1 min-w-0 p-2.5 rounded-xl border border-border/30 bg-white/80 dark:bg-zinc-900/60 text-start"
|
||||
style={{ borderColor: `${color}30` }}
|
||||
>
|
||||
<p className="text-[10px] font-semibold text-ink dark:text-dark-ink truncate leading-tight">
|
||||
{note1Title}
|
||||
</p>
|
||||
</div>
|
||||
<div className="shrink-0 flex flex-col items-center gap-0.5 px-1">
|
||||
<div className="w-8 h-px" style={{ background: `linear-gradient(90deg, transparent, ${color}, transparent)` }} />
|
||||
<span
|
||||
className="text-[9px] font-mono font-bold px-2 py-0.5 rounded-full"
|
||||
style={{ color, backgroundColor: `${color}14`, border: `1px solid ${color}25` }}
|
||||
>
|
||||
{Math.round(score * 100)}%
|
||||
</span>
|
||||
<div className="w-8 h-px" style={{ background: `linear-gradient(90deg, transparent, ${color}, transparent)` }} />
|
||||
</div>
|
||||
<div
|
||||
className="flex-1 min-w-0 p-2.5 rounded-xl border border-border/30 bg-white/80 dark:bg-zinc-900/60 text-start"
|
||||
style={{ borderColor: `${color}30` }}
|
||||
>
|
||||
<p className="text-[10px] font-semibold text-ink dark:text-dark-ink truncate leading-tight">
|
||||
{note2Title}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
// ─── Props ─────────────────────────────────────────────
|
||||
|
||||
export interface IntelligenceHubProps {
|
||||
loading: boolean
|
||||
aiActive: boolean
|
||||
hasAiConsent: boolean
|
||||
providerReady: boolean
|
||||
memoryEchoEnabled: boolean
|
||||
insights: IntelBriefingInsight[]
|
||||
bridgeNotes: IntelBridgeNote[]
|
||||
bridgeSuggestions: IntelBridgeSuggestion[]
|
||||
agentActions: IntelAgentAction[]
|
||||
onNoteSelect: (noteId: string) => void
|
||||
onRefreshEcho: () => void
|
||||
onEnableAi: () => void
|
||||
echoRefreshing: boolean
|
||||
onDismissInsight: (insight: IntelBriefingInsight) => void
|
||||
onDismissBridgeSuggestion: (s: IntelBridgeSuggestion) => void
|
||||
onCreateBridgeSuggestion: (s: IntelBridgeSuggestion) => void
|
||||
onOpenInsightNote: (insight: IntelBriefingInsight, noteId: string) => void
|
||||
dismissingInsightId: string | null
|
||||
actingBridgeSuggestionKey: string | null
|
||||
prefersReducedMotion: boolean
|
||||
}
|
||||
|
||||
// ─── Component ─────────────────────────────────────────
|
||||
|
||||
export function IntelligenceHub({
|
||||
loading,
|
||||
aiActive,
|
||||
hasAiConsent,
|
||||
providerReady,
|
||||
memoryEchoEnabled,
|
||||
insights,
|
||||
bridgeNotes,
|
||||
bridgeSuggestions,
|
||||
agentActions,
|
||||
onNoteSelect,
|
||||
onRefreshEcho,
|
||||
onEnableAi,
|
||||
echoRefreshing,
|
||||
onDismissInsight,
|
||||
onDismissBridgeSuggestion,
|
||||
onCreateBridgeSuggestion,
|
||||
onOpenInsightNote,
|
||||
dismissingInsightId,
|
||||
actingBridgeSuggestionKey,
|
||||
prefersReducedMotion,
|
||||
}: IntelligenceHubProps) {
|
||||
const router = useRouter()
|
||||
const { t } = useLanguage()
|
||||
const [filter, setFilter] = useState<IntelFilter>('all')
|
||||
const [activeIndex, setActiveIndex] = useState(0)
|
||||
|
||||
const localizeInsightText = useCallback((insight: IntelBriefingInsight) => {
|
||||
const text = insight.insight.trim()
|
||||
if (MEMORY_ECHO_LEGACY_EN_FALLBACKS.has(text)) {
|
||||
if (insight.note1Excerpt && insight.note2Excerpt) {
|
||||
return t('homeDashboard.connectionBetween', {
|
||||
note1: insight.note1.title || insight.note1Excerpt.slice(0, 50),
|
||||
note2: insight.note2.title || insight.note2Excerpt.slice(0, 50),
|
||||
})
|
||||
}
|
||||
return t('memoryEcho.defaultInsight')
|
||||
}
|
||||
return text
|
||||
}, [t])
|
||||
|
||||
const allItems = useMemo(() => {
|
||||
const insightNoteIds = new Set<string>()
|
||||
for (const i of insights) {
|
||||
insightNoteIds.add(i.note1.id)
|
||||
insightNoteIds.add(i.note2.id)
|
||||
}
|
||||
|
||||
const items: IntelItem[] = []
|
||||
|
||||
for (const insight of insights) {
|
||||
items.push({
|
||||
kind: 'insight',
|
||||
id: `insight-${insight.id}`,
|
||||
priority: (insight.viewed ? 40 : 100) + insight.score * 10,
|
||||
insight,
|
||||
})
|
||||
}
|
||||
|
||||
for (const bridge of bridgeNotes) {
|
||||
if (insightNoteIds.has(bridge.noteId)) continue
|
||||
items.push({
|
||||
kind: 'bridge',
|
||||
id: `bridge-${bridge.noteId}`,
|
||||
priority: 60 + bridge.bridgeScore * 10,
|
||||
bridge,
|
||||
})
|
||||
}
|
||||
|
||||
for (const suggestion of bridgeSuggestions) {
|
||||
items.push({
|
||||
kind: 'suggestion',
|
||||
id: `suggestion-${suggestion.clusterAId}-${suggestion.clusterBId}`,
|
||||
priority: 80,
|
||||
suggestion,
|
||||
})
|
||||
}
|
||||
|
||||
for (const agent of agentActions) {
|
||||
items.push({
|
||||
kind: 'agent',
|
||||
id: `agent-${agent.id}`,
|
||||
priority: 30,
|
||||
agent,
|
||||
})
|
||||
}
|
||||
|
||||
return items.sort((a, b) => b.priority - a.priority).slice(0, 10)
|
||||
}, [insights, bridgeNotes, bridgeSuggestions, agentActions])
|
||||
|
||||
const counts = useMemo(() => ({
|
||||
all: allItems.length,
|
||||
connections: allItems.filter(i => i.kind === 'insight').length,
|
||||
bridges: allItems.filter(i => i.kind === 'bridge').length,
|
||||
ideas: allItems.filter(i => i.kind === 'suggestion').length,
|
||||
agents: allItems.filter(i => i.kind === 'agent').length,
|
||||
}), [allItems])
|
||||
|
||||
const filteredItems = useMemo(() => {
|
||||
const kinds = FILTER_KINDS[filter]
|
||||
if (!kinds) return allItems
|
||||
return allItems.filter(i => kinds.includes(i.kind))
|
||||
}, [allItems, filter])
|
||||
|
||||
useEffect(() => {
|
||||
setActiveIndex(0)
|
||||
}, [filter])
|
||||
|
||||
useEffect(() => {
|
||||
if (activeIndex >= filteredItems.length && filteredItems.length > 0) {
|
||||
setActiveIndex(filteredItems.length - 1)
|
||||
}
|
||||
}, [activeIndex, filteredItems.length])
|
||||
|
||||
const activeItem = filteredItems[activeIndex] ?? null
|
||||
const newCount = insights.filter(i => !i.viewed).length
|
||||
|
||||
const goPrev = () => setActiveIndex(i => Math.max(0, i - 1))
|
||||
const goNext = () => setActiveIndex(i => Math.min(filteredItems.length - 1, i + 1))
|
||||
|
||||
const filters: { key: IntelFilter; label: string }[] = [
|
||||
{ key: 'all', label: t('homeDashboard.intelFilterAll') },
|
||||
{ key: 'connections', label: t('homeDashboard.intelFilterConnections') },
|
||||
{ key: 'bridges', label: t('homeDashboard.intelFilterBridges') },
|
||||
{ key: 'ideas', label: t('homeDashboard.intelFilterIdeas') },
|
||||
{ key: 'agents', label: t('homeDashboard.intelFilterAgents') },
|
||||
]
|
||||
|
||||
const slideVariants = prefersReducedMotion
|
||||
? { initial: {}, animate: {}, exit: {} }
|
||||
: {
|
||||
initial: { opacity: 0, x: 24, scale: 0.98 },
|
||||
animate: { opacity: 1, x: 0, scale: 1 },
|
||||
exit: { opacity: 0, x: -24, scale: 0.98 },
|
||||
}
|
||||
|
||||
const renderSpotlight = (item: IntelItem) => {
|
||||
switch (item.kind) {
|
||||
case 'insight': {
|
||||
const { insight } = item
|
||||
const text = localizeInsightText(insight)
|
||||
const excerpt = insight.note1Excerpt || insight.note2Excerpt
|
||||
return (
|
||||
<div className="flex flex-col h-full">
|
||||
<div className="flex items-center gap-2 mb-3">
|
||||
<Sparkles size={12} className="text-indigo-500" />
|
||||
<span className="text-[9px] font-mono font-bold uppercase tracking-wider text-indigo-600 dark:text-indigo-400">
|
||||
{t('homeDashboard.semanticConnection')}
|
||||
</span>
|
||||
{!insight.viewed && (
|
||||
<span className="w-1.5 h-1.5 rounded-full bg-ochre animate-pulse" />
|
||||
)}
|
||||
</div>
|
||||
<ConnectionDiagram
|
||||
note1Title={insight.note1.title || t('homeDashboard.untitled')}
|
||||
note2Title={insight.note2.title || t('homeDashboard.untitled')}
|
||||
score={insight.score}
|
||||
/>
|
||||
<p className="text-[11px] text-ink/75 dark:text-dark-ink/75 font-serif italic leading-relaxed line-clamp-3 px-1">
|
||||
« {text} »
|
||||
</p>
|
||||
{excerpt && (
|
||||
<p className="text-[9px] text-concrete/80 line-clamp-2 mt-2 px-1 border-s-2 border-indigo-500/20 ps-2">
|
||||
{excerpt}
|
||||
</p>
|
||||
)}
|
||||
<div className="flex items-center gap-1.5 mt-auto pt-3 flex-wrap">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => onOpenInsightNote(insight, insight.note1.id)}
|
||||
className="inline-flex items-center gap-1 text-[8.5px] font-mono uppercase font-bold px-2.5 py-1.5 rounded-lg bg-indigo-600 text-white hover:bg-indigo-700 transition-colors"
|
||||
>
|
||||
<ExternalLink size={9} />
|
||||
{t('homeDashboard.intelOpenNote')}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => onOpenInsightNote(insight, insight.note2.id)}
|
||||
className="inline-flex items-center gap-1 text-[8.5px] font-mono uppercase font-bold px-2.5 py-1.5 rounded-lg border border-border/40 hover:border-indigo-400/40 transition-colors"
|
||||
>
|
||||
<GitCompare size={9} />
|
||||
{t('homeDashboard.intelCompare')}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
disabled={dismissingInsightId === insight.id}
|
||||
onClick={() => onDismissInsight(insight)}
|
||||
className="p-1.5 rounded-lg border border-border/30 text-concrete hover:text-rose-500 ms-auto disabled:opacity-40"
|
||||
title={t('homeDashboard.dismissConnection')}
|
||||
>
|
||||
{dismissingInsightId === insight.id
|
||||
? <Loader2 size={10} className="animate-spin" />
|
||||
: <X size={10} />}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
case 'bridge': {
|
||||
const { bridge } = item
|
||||
const title = bridge.note?.title || t('homeDashboard.untitled')
|
||||
const excerpt = bridge.note?.content ? stripHtml(bridge.note.content).slice(0, 160) : ''
|
||||
const names = bridge.clusterNames ?? []
|
||||
return (
|
||||
<div className="flex flex-col h-full">
|
||||
<div className="flex items-center justify-between gap-2 mb-3">
|
||||
<div className="flex items-center gap-2">
|
||||
<Zap size={12} className="text-ochre" />
|
||||
<span className="text-[9px] font-mono font-bold uppercase tracking-wider text-ochre">
|
||||
{t('homeDashboard.bridgeNote')}
|
||||
</span>
|
||||
</div>
|
||||
<span className="text-[9px] font-mono font-bold text-ochre bg-ochre/10 px-2 py-0.5 rounded-full">
|
||||
{Math.round(bridge.bridgeScore * 100)}%
|
||||
</span>
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => onNoteSelect(bridge.noteId)}
|
||||
className="text-start group flex-1"
|
||||
>
|
||||
<p className="text-sm font-semibold text-ink dark:text-dark-ink group-hover:text-ochre transition-colors mb-2 leading-snug">
|
||||
{title}
|
||||
</p>
|
||||
{excerpt && (
|
||||
<p className="text-[10px] text-concrete leading-relaxed line-clamp-3 mb-3">{excerpt}</p>
|
||||
)}
|
||||
{names.length > 0 && (
|
||||
<div className="flex flex-wrap gap-1.5">
|
||||
{names.map((name, i) => (
|
||||
<span
|
||||
key={`${bridge.noteId}-${name}`}
|
||||
className="inline-flex items-center gap-1 px-2 py-1 rounded-full border border-border/25 bg-white/70 dark:bg-zinc-900/50"
|
||||
>
|
||||
<span
|
||||
className="w-1.5 h-1.5 rounded-full"
|
||||
style={{ backgroundColor: CLUSTER_COLORS[i % CLUSTER_COLORS.length] }}
|
||||
/>
|
||||
<span className="text-[8px] font-mono uppercase text-concrete">{name}</span>
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => onNoteSelect(bridge.noteId)}
|
||||
className="mt-3 inline-flex items-center gap-1 text-[8.5px] font-mono uppercase font-bold px-2.5 py-1.5 rounded-lg bg-ochre/90 text-white hover:bg-ochre transition-colors w-fit"
|
||||
>
|
||||
<ExternalLink size={9} />
|
||||
{t('homeDashboard.intelOpenNote')}
|
||||
</button>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
case 'suggestion': {
|
||||
const { suggestion } = item
|
||||
const key = `${suggestion.clusterAId}-${suggestion.clusterBId}`
|
||||
const busy = actingBridgeSuggestionKey === key
|
||||
return (
|
||||
<div className="flex flex-col h-full">
|
||||
<div className="flex items-center gap-2 mb-3">
|
||||
<Lightbulb size={12} className="text-violet-500" />
|
||||
<span className="text-[9px] font-mono font-bold uppercase tracking-wider text-violet-600 dark:text-violet-400 truncate">
|
||||
{t('homeDashboard.intelMissingLink')}
|
||||
</span>
|
||||
</div>
|
||||
<div className="flex items-center gap-2 mb-3">
|
||||
<span className="px-2 py-1 rounded-lg bg-violet-500/10 text-[9px] font-mono font-bold text-violet-700 dark:text-violet-300 truncate max-w-[45%]">
|
||||
{suggestion.clusterAName}
|
||||
</span>
|
||||
<div className="flex-1 h-px bg-gradient-to-r from-violet-400/40 via-ochre/60 to-violet-400/40" />
|
||||
<span className="px-2 py-1 rounded-lg bg-ochre/10 text-[9px] font-mono font-bold text-ochre truncate max-w-[45%]">
|
||||
{suggestion.clusterBName}
|
||||
</span>
|
||||
</div>
|
||||
<p className="text-sm font-semibold text-ink dark:text-dark-ink mb-1.5">{suggestion.suggestedTitle}</p>
|
||||
<p className="text-[10px] text-concrete leading-relaxed line-clamp-2 flex-1">{suggestion.suggestedContent}</p>
|
||||
<div className="flex items-center gap-1.5 mt-3 pt-3 border-t border-border/15">
|
||||
<button
|
||||
type="button"
|
||||
disabled={busy}
|
||||
onClick={() => onCreateBridgeSuggestion(suggestion)}
|
||||
className="inline-flex items-center gap-1 text-[8.5px] font-mono uppercase font-bold px-2.5 py-1.5 rounded-lg bg-violet-600 text-white hover:bg-violet-700 transition-colors disabled:opacity-40"
|
||||
>
|
||||
{busy ? <Loader2 size={9} className="animate-spin" /> : <Link2 size={9} />}
|
||||
{t('homeDashboard.createBridgeNote')}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
disabled={busy}
|
||||
onClick={() => onDismissBridgeSuggestion(suggestion)}
|
||||
className="text-[8.5px] font-mono uppercase px-2 py-1.5 rounded-lg border border-border/30 text-concrete hover:text-rose-500 disabled:opacity-40"
|
||||
>
|
||||
{t('homeDashboard.dismiss')}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
case 'agent': {
|
||||
const { agent } = item
|
||||
return (
|
||||
<div className="flex flex-col h-full">
|
||||
<div className="flex items-center gap-2 mb-3">
|
||||
<Bot size={12} className="text-ochre" />
|
||||
<span className="text-[9px] font-mono font-bold uppercase tracking-wider text-ochre">
|
||||
{agent.agentName}
|
||||
</span>
|
||||
<span className="text-[8px] font-mono text-concrete/60 ms-auto">
|
||||
{formatRelativeTime(agent.createdAt, t)}
|
||||
</span>
|
||||
</div>
|
||||
{agent.result ? (
|
||||
<p className="text-[11px] text-concrete leading-relaxed line-clamp-4 flex-1">
|
||||
{agent.result}
|
||||
</p>
|
||||
) : (
|
||||
<p className="text-[11px] text-concrete/60 italic flex-1">{t('homeDashboard.intelAgentNoResult')}</p>
|
||||
)}
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => router.push('/agents')}
|
||||
className="mt-3 inline-flex items-center gap-1 text-[8.5px] font-mono uppercase font-bold px-2.5 py-1.5 rounded-lg border border-ochre/30 text-ochre hover:bg-ochre/10 transition-colors w-fit"
|
||||
>
|
||||
{t('homeDashboard.intelViewAgent')}
|
||||
<ArrowRight size={9} />
|
||||
</button>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const spotlightAccent = (item: IntelItem | null) => {
|
||||
if (!item) return 'from-stone-100/50 to-transparent border-border/30'
|
||||
switch (item.kind) {
|
||||
case 'insight': return 'from-indigo-500/[0.06] via-transparent to-transparent border-indigo-400/25'
|
||||
case 'bridge': return 'from-ochre/[0.06] via-transparent to-transparent border-ochre/25'
|
||||
case 'suggestion': return 'from-violet-500/[0.06] via-transparent to-transparent border-violet-400/25'
|
||||
case 'agent': return 'from-ochre/[0.04] via-transparent to-transparent border-border/30'
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<section className="p-5 rounded-2xl bg-white dark:bg-zinc-900 border border-border/30 flex flex-col">
|
||||
{/* Header */}
|
||||
<DashboardWidgetTitleRow
|
||||
widgetId="intelligence"
|
||||
icon={(
|
||||
<div className="w-5 h-5 rounded bg-brand-accent/10 flex items-center justify-center text-brand-accent shrink-0">
|
||||
<Sparkles size={12} />
|
||||
</div>
|
||||
)}
|
||||
title={t('homeDashboard.aiFound')}
|
||||
actions={(
|
||||
<>
|
||||
{newCount > 0 && (
|
||||
<span className="text-[8px] font-mono font-bold text-brand-accent bg-brand-accent/10 px-2 py-0.5 rounded uppercase">
|
||||
{newCount} {t('homeDashboard.new')}
|
||||
</span>
|
||||
)}
|
||||
{aiActive && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={onRefreshEcho}
|
||||
disabled={echoRefreshing}
|
||||
title={t('homeDashboard.analyzeNotes')}
|
||||
className="p-1.5 rounded-lg border border-border/30 hover:border-brand-accent/40 hover:bg-brand-accent/5 transition-all disabled:opacity-40"
|
||||
>
|
||||
{echoRefreshing
|
||||
? <Loader2 size={11} className="animate-spin text-brand-accent" />
|
||||
: <RefreshCw size={11} className="text-concrete hover:text-brand-accent" />}
|
||||
</button>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
/>
|
||||
|
||||
{loading ? (
|
||||
<div className="h-[220px] rounded-2xl bg-stone-50 dark:bg-zinc-950/30 animate-pulse" />
|
||||
) : !aiActive ? (
|
||||
<div className="p-5 rounded-2xl border border-dashed border-border/40 bg-stone-50/50 dark:bg-zinc-950/30 text-center space-y-3 min-h-[180px] flex flex-col justify-center">
|
||||
<p className="text-xs text-concrete leading-relaxed">
|
||||
{!hasAiConsent
|
||||
? t('homeDashboard.aiConsentRequired')
|
||||
: !providerReady
|
||||
? t('homeDashboard.aiProviderUnavailable')
|
||||
: t('homeDashboard.memoryEchoDisabled')}
|
||||
</p>
|
||||
{!hasAiConsent && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={onEnableAi}
|
||||
className="text-[9px] font-mono uppercase font-bold px-3 py-1.5 rounded-lg bg-ink text-white dark:bg-white dark:text-black hover:opacity-90 transition-opacity mx-auto"
|
||||
>
|
||||
{t('homeDashboard.enableAi')}
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
) : allItems.length === 0 ? (
|
||||
<div className="p-5 rounded-2xl border border-dashed border-border/40 bg-stone-50/50 dark:bg-zinc-950/30 text-center space-y-3 min-h-[180px] flex flex-col justify-center">
|
||||
<Brain size={22} className="mx-auto text-concrete/40" strokeWidth={1.25} />
|
||||
<p className="text-xs text-concrete leading-relaxed">{t('homeDashboard.noConnections')}</p>
|
||||
<button
|
||||
type="button"
|
||||
onClick={onRefreshEcho}
|
||||
disabled={echoRefreshing}
|
||||
className="inline-flex items-center gap-1.5 text-[9px] font-mono uppercase font-bold px-3 py-1.5 rounded-lg border border-ochre/30 text-ochre hover:bg-ochre/10 transition-all disabled:opacity-40 mx-auto"
|
||||
>
|
||||
{echoRefreshing ? <Loader2 size={11} className="animate-spin" /> : <Sparkles size={11} />}
|
||||
{t('homeDashboard.analyzeNotes')}
|
||||
</button>
|
||||
</div>
|
||||
) : (
|
||||
<>
|
||||
{/* Filtres */}
|
||||
<div className="flex gap-1 overflow-x-auto custom-scrollbar pb-1 -mx-0.5 px-0.5 mb-3">
|
||||
{filters.map(f => {
|
||||
const count = counts[f.key]
|
||||
if (f.key !== 'all' && count === 0) return null
|
||||
const active = filter === f.key
|
||||
return (
|
||||
<button
|
||||
key={f.key}
|
||||
type="button"
|
||||
onClick={() => setFilter(f.key)}
|
||||
className={`shrink-0 inline-flex items-center gap-1.5 px-2.5 py-1 rounded-full text-[8.5px] font-mono font-bold uppercase tracking-wider transition-all ${
|
||||
active
|
||||
? 'bg-ink text-white dark:bg-white dark:text-black shadow-sm'
|
||||
: 'bg-stone-100 dark:bg-zinc-800 text-concrete hover:text-ink dark:hover:text-dark-ink'
|
||||
}`}
|
||||
>
|
||||
{f.label}
|
||||
{count > 0 && (
|
||||
<span className={`text-[7px] px-1 py-px rounded-full ${active ? 'bg-white/20' : 'bg-black/5 dark:bg-white/10'}`}>
|
||||
{count}
|
||||
</span>
|
||||
)}
|
||||
</button>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
|
||||
{filteredItems.length === 0 ? (
|
||||
<p className="text-xs text-concrete italic text-center py-8">{t('homeDashboard.intelFilterEmpty')}</p>
|
||||
) : (
|
||||
<>
|
||||
{/* Spotlight carousel */}
|
||||
<div className="relative">
|
||||
{filteredItems.length > 1 && (
|
||||
<>
|
||||
<button
|
||||
type="button"
|
||||
onClick={goPrev}
|
||||
disabled={activeIndex === 0}
|
||||
className="absolute start-0 top-1/2 -translate-y-1/2 -translate-x-1 z-10 p-1 rounded-full border border-border/40 bg-white/90 dark:bg-zinc-900/90 shadow-sm disabled:opacity-25 hover:border-ochre/40 transition-all"
|
||||
aria-label={t('homeDashboard.intelPrev')}
|
||||
>
|
||||
<ChevronLeft size={14} />
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={goNext}
|
||||
disabled={activeIndex >= filteredItems.length - 1}
|
||||
className="absolute end-0 top-1/2 -translate-y-1/2 translate-x-1 z-10 p-1 rounded-full border border-border/40 bg-white/90 dark:bg-zinc-900/90 shadow-sm disabled:opacity-25 hover:border-ochre/40 transition-all"
|
||||
aria-label={t('homeDashboard.intelNext')}
|
||||
>
|
||||
<ChevronRight size={14} />
|
||||
</button>
|
||||
</>
|
||||
)}
|
||||
|
||||
<div
|
||||
className={`min-h-[200px] mx-5 p-4 rounded-2xl border bg-gradient-to-br ${spotlightAccent(activeItem)} transition-colors`}
|
||||
>
|
||||
<AnimatePresence mode="wait">
|
||||
{activeItem && (
|
||||
<motion.div
|
||||
key={activeItem.id}
|
||||
initial={slideVariants.initial}
|
||||
animate={slideVariants.animate}
|
||||
exit={slideVariants.exit}
|
||||
transition={{ duration: prefersReducedMotion ? 0 : 0.22, ease: 'easeOut' }}
|
||||
className="min-h-[180px] flex flex-col"
|
||||
>
|
||||
{renderSpotlight(activeItem)}
|
||||
</motion.div>
|
||||
)}
|
||||
</AnimatePresence>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Navigation dots + position */}
|
||||
{filteredItems.length > 1 && (
|
||||
<div className="flex items-center justify-center gap-3 mt-3">
|
||||
<div className="flex items-center gap-1.5">
|
||||
{filteredItems.map((item, idx) => (
|
||||
<button
|
||||
key={item.id}
|
||||
type="button"
|
||||
onClick={() => setActiveIndex(idx)}
|
||||
className={`rounded-full transition-all ${
|
||||
idx === activeIndex
|
||||
? 'w-5 h-1.5 bg-ochre'
|
||||
: 'w-1.5 h-1.5 bg-concrete/25 hover:bg-concrete/50'
|
||||
}`}
|
||||
aria-label={t('homeDashboard.intelGoTo', { index: idx + 1 })}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
<span className="text-[8px] font-mono text-concrete/60 uppercase">
|
||||
{t('homeDashboard.intelPosition', { current: activeIndex + 1, total: filteredItems.length })}
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* File d'attente compacte */}
|
||||
{filteredItems.length > 1 && (
|
||||
<div className="flex gap-1.5 mt-3 overflow-x-auto custom-scrollbar pt-1">
|
||||
{filteredItems.map((item, idx) => {
|
||||
const isActive = idx === activeIndex
|
||||
let label = ''
|
||||
let Icon = Sparkles
|
||||
let accent = 'text-indigo-500'
|
||||
if (item.kind === 'insight') {
|
||||
label = item.insight.note1.title?.slice(0, 28) || t('homeDashboard.untitled')
|
||||
Icon = Sparkles
|
||||
accent = 'text-indigo-500'
|
||||
} else if (item.kind === 'bridge') {
|
||||
label = item.bridge.note?.title?.slice(0, 28) || t('homeDashboard.untitled')
|
||||
Icon = Zap
|
||||
accent = 'text-ochre'
|
||||
} else if (item.kind === 'suggestion') {
|
||||
label = item.suggestion.suggestedTitle.slice(0, 28)
|
||||
Icon = Lightbulb
|
||||
accent = 'text-violet-500'
|
||||
} else {
|
||||
label = item.agent.agentName
|
||||
Icon = Bot
|
||||
accent = 'text-ochre'
|
||||
}
|
||||
return (
|
||||
<button
|
||||
key={item.id}
|
||||
type="button"
|
||||
onClick={() => setActiveIndex(idx)}
|
||||
className={`shrink-0 flex items-center gap-1.5 px-2 py-1.5 rounded-lg border text-start max-w-[130px] transition-all ${
|
||||
isActive
|
||||
? 'border-ochre/40 bg-ochre/5 shadow-sm'
|
||||
: 'border-border/25 bg-stone-50/50 dark:bg-zinc-950/30 hover:border-border/50'
|
||||
}`}
|
||||
>
|
||||
<Icon size={9} className={`shrink-0 ${accent}`} />
|
||||
<span className="text-[8px] font-medium text-ink dark:text-dark-ink truncate">{label}</span>
|
||||
</button>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</section>
|
||||
)
|
||||
}
|
||||
@@ -10,6 +10,12 @@ import type { AppState, BinaryFiles } from '@excalidraw/excalidraw/types'
|
||||
import type { ExcalidrawImperativeAPI } from '@excalidraw/excalidraw/types'
|
||||
import '@excalidraw/excalidraw/index.css'
|
||||
import type { PresentationSpec } from '@/lib/types/presentation'
|
||||
import { useLanguage } from '@/lib/i18n'
|
||||
|
||||
function SlidesLoadingFallback() {
|
||||
const { t } = useLanguage()
|
||||
return <div className="absolute inset-0 flex items-center justify-center bg-zinc-950 text-white/40 text-sm">{t('lab.loadingSlides')}</div>
|
||||
}
|
||||
|
||||
const Excalidraw = dynamic(
|
||||
async () => (await import('@excalidraw/excalidraw')).Excalidraw,
|
||||
@@ -18,7 +24,7 @@ const Excalidraw = dynamic(
|
||||
|
||||
const SlidesRenderer = dynamic(
|
||||
() => import('./slides-renderer').then(m => ({ default: m.SlidesRenderer })),
|
||||
{ ssr: false, loading: () => <div className="absolute inset-0 flex items-center justify-center bg-zinc-950 text-white/40 text-sm">Chargement des slides…</div> }
|
||||
{ ssr: false, loading: () => <SlidesLoadingFallback /> }
|
||||
)
|
||||
|
||||
interface CanvasBoardProps {
|
||||
@@ -62,6 +68,7 @@ function parseCanvasScene(initialData?: string): {
|
||||
}
|
||||
|
||||
function PptxViewer({ data, name }: { data: PptxPayload; name: string }) {
|
||||
const { t } = useLanguage()
|
||||
const handleDownload = () => {
|
||||
try {
|
||||
const byteCharacters = atob(data.base64)
|
||||
@@ -83,7 +90,7 @@ function PptxViewer({ data, name }: { data: PptxPayload; name: string }) {
|
||||
URL.revokeObjectURL(url)
|
||||
} catch (e) {
|
||||
console.error('[PptxViewer] Download failed:', e)
|
||||
toast.error('Failed to download presentation')
|
||||
toast.error(t('lab.downloadFailed'))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -106,7 +113,7 @@ function PptxViewer({ data, name }: { data: PptxPayload; name: string }) {
|
||||
className="flex items-center gap-2 px-6 py-3 bg-primary text-primary-foreground rounded-xl hover:bg-primary/90 transition-colors font-medium shadow-sm"
|
||||
>
|
||||
<Download className="w-5 h-5" />
|
||||
Download .pptx
|
||||
{t('lab.exportPpt')}
|
||||
</button>
|
||||
<p className="text-xs text-muted-foreground max-w-sm text-center">
|
||||
This file can be opened in Microsoft PowerPoint, Google Slides, or Keynote.
|
||||
@@ -117,6 +124,7 @@ function PptxViewer({ data, name }: { data: PptxPayload; name: string }) {
|
||||
}
|
||||
|
||||
function SlidesViewer({ data, name, canvasId }: { data: SlidesPayload; name: string; canvasId?: string | null }) {
|
||||
const { t } = useLanguage()
|
||||
const iframeRef = useRef<HTMLIFrameElement>(null)
|
||||
const [currentSlide, setCurrentSlide] = useState(1)
|
||||
const [isLoaded, setIsLoaded] = useState(!!data.spec) // spec → React renderer, no iframe loading
|
||||
@@ -194,27 +202,27 @@ function SlidesViewer({ data, name, canvasId }: { data: SlidesPayload; name: str
|
||||
href={`/api/canvas/slides/pptx?id=${canvasId}`}
|
||||
download
|
||||
className="flex items-center gap-1.5 px-3 py-1.5 bg-white/10 hover:bg-white/20 rounded-lg text-white/70 hover:text-white text-xs font-medium transition-all"
|
||||
title="Exporter en PowerPoint"
|
||||
title={t('lab.exportPpt')}
|
||||
>
|
||||
<Download className="w-3.5 h-3.5" />
|
||||
Export PPTX
|
||||
{t('lab.exportPpt')}
|
||||
</a>
|
||||
)}
|
||||
<button
|
||||
onClick={downloadHtml}
|
||||
className="flex items-center gap-1.5 px-3 py-1.5 bg-white/10 hover:bg-white/20 rounded-lg text-white/70 hover:text-white text-xs font-medium transition-all"
|
||||
title="Télécharger le HTML"
|
||||
title={t('lab.downloadHtml')}
|
||||
>
|
||||
<Download className="w-3.5 h-3.5" />
|
||||
Export HTML
|
||||
{t('lab.downloadHtml')}
|
||||
</button>
|
||||
<button
|
||||
onClick={openFullscreen}
|
||||
className="flex items-center gap-1.5 px-3 py-1.5 bg-white/10 hover:bg-white/20 rounded-lg text-white/70 hover:text-white text-xs font-medium transition-all"
|
||||
title="Ouvrir en plein écran"
|
||||
title={t('lab.openFullscreen')}
|
||||
>
|
||||
<Maximize2 className="w-3.5 h-3.5" />
|
||||
Plein écran
|
||||
{t('lab.openFullscreen')}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
@@ -228,7 +236,7 @@ function SlidesViewer({ data, name, canvasId }: { data: SlidesPayload; name: str
|
||||
{!isLoaded && (
|
||||
<div className="absolute inset-0 z-20 flex flex-col items-center justify-center bg-zinc-950 gap-3">
|
||||
<div className="w-8 h-8 rounded-full border-2 border-white/10 border-t-white/60 animate-spin" />
|
||||
<span className="text-xs text-white/30">Chargement de la présentation…</span>
|
||||
<span className="text-xs text-white/30">{t('lab.loadingPresentation')}</span>
|
||||
</div>
|
||||
)}
|
||||
<iframe
|
||||
@@ -244,7 +252,7 @@ function SlidesViewer({ data, name, canvasId }: { data: SlidesPayload; name: str
|
||||
<button
|
||||
onClick={() => navigate(-1)}
|
||||
className="absolute left-2 top-1/2 -translate-y-1/2 z-10 w-9 h-9 flex items-center justify-center rounded-full bg-black/40 hover:bg-black/70 backdrop-blur-sm border border-white/10 text-white/40 hover:text-white transition-all opacity-0 group-hover:opacity-100"
|
||||
aria-label="Slide précédent"
|
||||
aria-label={t('lab.previousSlide')}
|
||||
>
|
||||
<ChevronLeft className="w-5 h-5" />
|
||||
</button>
|
||||
@@ -252,7 +260,7 @@ function SlidesViewer({ data, name, canvasId }: { data: SlidesPayload; name: str
|
||||
<button
|
||||
onClick={() => navigate(1)}
|
||||
className="absolute right-2 top-1/2 -translate-y-1/2 z-10 w-9 h-9 flex items-center justify-center rounded-full bg-black/40 hover:bg-black/70 backdrop-blur-sm border border-white/10 text-white/40 hover:text-white transition-all opacity-0 group-hover:opacity-100"
|
||||
aria-label="Slide suivant"
|
||||
aria-label={t('lab.nextSlide')}
|
||||
>
|
||||
<ChevronRight className="w-5 h-5" />
|
||||
</button>
|
||||
|
||||
@@ -11,10 +11,16 @@ import {
|
||||
XAxis, YAxis, CartesianGrid, Tooltip, Legend, ResponsiveContainer,
|
||||
FunnelChart, Funnel, LabelList,
|
||||
} from 'recharts'
|
||||
import { useLanguage } from '@/lib/i18n'
|
||||
|
||||
function MermaidLoadingFallback() {
|
||||
const { t } = useLanguage()
|
||||
return <div style={{ color: 'rgba(255,255,255,0.3)', padding: 24 }}>{t('common.loading')}</div>
|
||||
}
|
||||
|
||||
const MermaidDiagram = dynamic(
|
||||
() => import('./mermaid-diagram').then(m => ({ default: m.MermaidDiagram })),
|
||||
{ ssr: false, loading: () => <div style={{ color: 'rgba(255,255,255,0.3)', padding: 24 }}>Chargement…</div> }
|
||||
{ ssr: false, loading: () => <MermaidLoadingFallback /> }
|
||||
)
|
||||
|
||||
// ── Constants ──────────────────────────────────────────────────────────────────
|
||||
@@ -688,6 +694,7 @@ export interface SlidesRendererProps {
|
||||
}
|
||||
|
||||
export function SlidesRenderer({ spec }: SlidesRendererProps) {
|
||||
const { t } = useLanguage()
|
||||
const [current, setCurrent] = useState(0)
|
||||
const [showNotes, setShowNotes] = useState(false)
|
||||
const containerRef = useRef<HTMLDivElement>(null)
|
||||
@@ -795,12 +802,12 @@ export function SlidesRenderer({ spec }: SlidesRendererProps) {
|
||||
|
||||
{/* Navigation buttons */}
|
||||
{current > 0 && (
|
||||
<button style={navBtn(true)} onClick={prev} aria-label="Précédent">
|
||||
<button style={navBtn(true)} onClick={prev} aria-label={t('lab.previous')}>
|
||||
<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round"><polyline points="15 18 9 12 15 6" /></svg>
|
||||
</button>
|
||||
)}
|
||||
{current < total - 1 && (
|
||||
<button style={navBtn(false)} onClick={next} aria-label="Suivant">
|
||||
<button style={navBtn(false)} onClick={next} aria-label={t('lab.next')}>
|
||||
<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round"><polyline points="9 6 15 12 9 18" /></svg>
|
||||
</button>
|
||||
)}
|
||||
@@ -830,12 +837,12 @@ export function SlidesRenderer({ spec }: SlidesRendererProps) {
|
||||
>
|
||||
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 8 }}>
|
||||
<span style={{ fontSize: 10, fontWeight: 700, letterSpacing: '0.12em', textTransform: 'uppercase', color: palette.accent }}>
|
||||
Notes de présentation
|
||||
{t('lab.notes')}
|
||||
</span>
|
||||
<button
|
||||
onClick={() => setShowNotes(false)}
|
||||
style={{ background: 'none', border: 'none', color: isDark ? '#94a3b8' : '#64748b', cursor: 'pointer', fontSize: 13, padding: 4 }}
|
||||
title="Masquer les notes"
|
||||
title={t('lab.hideNotes')}
|
||||
>
|
||||
✕
|
||||
</button>
|
||||
@@ -860,10 +867,10 @@ export function SlidesRenderer({ spec }: SlidesRendererProps) {
|
||||
display: 'flex', alignItems: 'center', gap: 6, transition: 'all 0.2s',
|
||||
backdropFilter: 'blur(4px)',
|
||||
}}
|
||||
title="Bascule des notes de présentation (Raccourci: N)"
|
||||
title={t('lab.toggleNotes')}
|
||||
>
|
||||
<span>📝</span>
|
||||
<span>Notes</span>
|
||||
<span>{t('lab.notes')}</span>
|
||||
</button>
|
||||
)}
|
||||
<div style={{ fontSize: 12, fontWeight: 600, color: isDark ? 'rgba(255,255,255,0.4)' : 'rgba(0,0,0,0.35)', background: isDark ? 'rgba(0,0,0,0.4)' : 'rgba(255,255,255,0.8)', padding: '3px 10px', borderRadius: 100, backdropFilter: 'blur(4px)', border: `1px solid ${isDark ? 'rgba(255,255,255,0.06)' : 'rgba(0,0,0,0.04)'}` }}>
|
||||
|
||||
@@ -7,6 +7,7 @@ import {
|
||||
Box
|
||||
} from 'lucide-react'
|
||||
import { useRouter } from 'next/navigation'
|
||||
import Image from 'next/image'
|
||||
import { useLanguage } from '@/lib/i18n'
|
||||
import { useState } from 'react'
|
||||
|
||||
@@ -44,7 +45,7 @@ export function LandingPage() {
|
||||
return (
|
||||
<div className="min-h-screen bg-paper text-ink font-sans selection:bg-ochre/30 selection:text-ink">
|
||||
{/* Navigation */}
|
||||
<nav className="fixed top-0 left-0 right-0 z-[100] bg-paper/80 backdrop-blur-md border-b border-border px-8 py-4 flex items-center justify-between">
|
||||
<nav className="fixed top-0 left-0 right-0 z-[100] bg-paper/80 backdrop-blur-md border-b border-border px-4 sm:px-8 py-4 flex items-center justify-between">
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="w-10 h-10 bg-ink flex items-center justify-center rounded-xl shadow-lg rotate-3 group hover:rotate-0 transition-transform cursor-pointer">
|
||||
<span className="text-paper font-serif text-2xl font-bold">M</span>
|
||||
@@ -104,7 +105,7 @@ export function LandingPage() {
|
||||
{/* App Preview Mockup */}
|
||||
<motion.div initial={{ opacity: 0, y: 100 }} animate={{ opacity: 1, y: 0 }} transition={{ duration: 1, delay: 0.2, ease: [0.23, 1, 0.32, 1] }} className="mt-24 relative">
|
||||
<div className="relative mx-auto max-w-5xl aspect-[16/10] bg-white rounded-[32px] shadow-[0_40px_100px_-20px_rgba(0,0,0,0.15)] border border-border p-4 overflow-hidden group">
|
||||
<img src="/images/workspace-hero.jpg" alt="Memento Workspace" className="w-full h-full object-cover rounded-2xl filter saturate-[0.8]" />
|
||||
<Image src="/images/workspace-hero.jpg" alt="Memento Workspace" width={1200} height={750} className="w-full h-full object-cover rounded-2xl filter saturate-[0.8]" priority />
|
||||
<div className="absolute inset-0 bg-ink/10 group-hover:bg-ink/0 transition-colors duration-500" />
|
||||
|
||||
<div className="absolute top-10 right-10 w-64 bg-paper/90 backdrop-blur-xl border border-border p-6 rounded-2xl shadow-2xl">
|
||||
|
||||
@@ -86,7 +86,7 @@ export function LoginForm({
|
||||
|
||||
<form action={dispatch} className="space-y-4">
|
||||
<div className="space-y-1.5">
|
||||
<label className="text-[10px] uppercase tracking-widest font-bold text-[var(--muted-foreground)] px-4">
|
||||
<label htmlFor="email" className="text-[10px] uppercase tracking-widest font-bold text-[var(--muted-foreground)] px-4">
|
||||
{t('auth.email')}
|
||||
</label>
|
||||
<div className="relative group">
|
||||
@@ -98,6 +98,7 @@ export function LoginForm({
|
||||
id="email"
|
||||
type="email"
|
||||
name="email"
|
||||
autoComplete="email"
|
||||
placeholder={t('auth.emailPlaceholder')}
|
||||
required
|
||||
/>
|
||||
@@ -106,7 +107,7 @@ export function LoginForm({
|
||||
|
||||
<div className="space-y-1.5">
|
||||
<div className="flex justify-between items-center px-4">
|
||||
<label className="text-[10px] uppercase tracking-widest font-bold text-[var(--muted-foreground)]">
|
||||
<label htmlFor="password" className="text-[10px] uppercase tracking-widest font-bold text-[var(--muted-foreground)]">
|
||||
{t('auth.password')}
|
||||
</label>
|
||||
<Link
|
||||
@@ -125,6 +126,7 @@ export function LoginForm({
|
||||
id="password"
|
||||
type="password"
|
||||
name="password"
|
||||
autoComplete="current-password"
|
||||
placeholder="••••••••"
|
||||
required
|
||||
minLength={6}
|
||||
|
||||
@@ -47,7 +47,7 @@ export function MobileActionSheet({
|
||||
const end = $pos.end(1)
|
||||
|
||||
editor.chain().focus().setTextSelection({ from: start, to: end }).run()
|
||||
toast.success(t('richTextEditor.blockSelected') || 'Bloc sélectionné en entier')
|
||||
toast.success(t('richTextEditor.blockSelected'))
|
||||
onClose()
|
||||
}
|
||||
|
||||
@@ -62,7 +62,7 @@ export function MobileActionSheet({
|
||||
const nodeText = editor.state.doc.slice(start, end)
|
||||
|
||||
editor.chain().focus().insertContentAt(end, nodeText.content.toJSON()).run()
|
||||
toast.success(t('richTextEditor.blockDuplicated') || 'Bloc dupliqué')
|
||||
toast.success(t('richTextEditor.blockDuplicated'))
|
||||
onClose()
|
||||
}
|
||||
|
||||
@@ -75,7 +75,7 @@ export function MobileActionSheet({
|
||||
const start = $pos.before(1)
|
||||
const end = $pos.after(1)
|
||||
editor.chain().focus().deleteRange({ from: start, to: end }).run()
|
||||
toast.success(t('richTextEditor.blockDeleted') || 'Bloc supprimé')
|
||||
toast.success(t('richTextEditor.blockDeleted'))
|
||||
onClose()
|
||||
}
|
||||
|
||||
@@ -85,7 +85,7 @@ export function MobileActionSheet({
|
||||
onClose()
|
||||
const tab = action === 'improve' ? 'actions' : 'chat'
|
||||
window.dispatchEvent(new CustomEvent('memento-open-ai', { detail: { tab, scroll: action } }))
|
||||
toast.info(t('richTextEditor.aiActionStarted') || 'IA Note sollicitée...')
|
||||
toast.info(t('richTextEditor.aiActionStarted'))
|
||||
}
|
||||
|
||||
return createPortal(
|
||||
@@ -101,26 +101,26 @@ export function MobileActionSheet({
|
||||
<div className="mobile-action-sheet-body">
|
||||
{/* Section 1 : Actions de bloc */}
|
||||
<div className="mobile-action-sheet-section">
|
||||
<h4 className="section-title">{t('mobile.blockActions') || 'Actions sur le bloc'}</h4>
|
||||
<h4 className="section-title">{t('mobile.blockActions')}</h4>
|
||||
<div className="grid grid-cols-3 gap-2">
|
||||
<button type="button" className="action-tile-btn" onClick={handleSelectAllBlock}>
|
||||
<FileText size={20} className="text-blue-500" />
|
||||
<span>{t('mobile.selectAll') || 'Sélectionner tout'}</span>
|
||||
<span>{t('mobile.selectAll')}</span>
|
||||
</button>
|
||||
<button type="button" className="action-tile-btn" onClick={handleDuplicateBlock}>
|
||||
<Copy size={20} className="text-emerald-500" />
|
||||
<span>{t('mobile.duplicate') || 'Dupliquer'}</span>
|
||||
<span>{t('mobile.duplicate')}</span>
|
||||
</button>
|
||||
<button type="button" className="action-tile-btn text-rose-500" onClick={handleDeleteBlock}>
|
||||
<Trash2 size={20} className="text-rose-500" />
|
||||
<span>{t('mobile.delete') || 'Supprimer'}</span>
|
||||
<span>{t('mobile.delete')}</span>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Section 2 : IA Note */}
|
||||
<div className="mobile-action-sheet-section">
|
||||
<h4 className="section-title">{t('mobile.aiNote') || 'IA Note'}</h4>
|
||||
<h4 className="section-title">{t('mobile.aiNote')}</h4>
|
||||
<div className="grid grid-cols-4 gap-2">
|
||||
<button type="button" className="action-tile-btn" onClick={() => handleAiAction('improve')}>
|
||||
<Wand2 size={18} className="text-purple-500 animate-pulse" />
|
||||
@@ -143,42 +143,42 @@ export function MobileActionSheet({
|
||||
|
||||
{/* Section 3 : Format de bloc */}
|
||||
<div className="mobile-action-sheet-section">
|
||||
<h4 className="section-title">{t('mobile.convertFormat') || 'Convertir le format'}</h4>
|
||||
<h4 className="section-title">{t('mobile.convertFormat')}</h4>
|
||||
<div className="flex gap-2 overflow-x-auto pb-2 scrollbar-none">
|
||||
<button
|
||||
type="button"
|
||||
className="format-pill-btn"
|
||||
onClick={() => { editor.chain().focus().setParagraph().run(); onClose() }}
|
||||
>
|
||||
{t('mobile.paragraph') || 'Paragraphe'}
|
||||
{t('mobile.paragraph')}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className="format-pill-btn"
|
||||
onClick={() => { editor.chain().focus().toggleHeading({ level: 1 }).run(); onClose() }}
|
||||
>
|
||||
<Heading1 size={14} className="inline mr-1" /> {t('notes.heading1') || 'Titre 1'}
|
||||
<Heading1 size={14} className="inline mr-1" /> {t('notes.heading1')}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className="format-pill-btn"
|
||||
onClick={() => { editor.chain().focus().toggleHeading({ level: 2 }).run(); onClose() }}
|
||||
>
|
||||
<Heading2 size={14} className="inline mr-1" /> {t('notes.heading2') || 'Titre 2'}
|
||||
<Heading2 size={14} className="inline mr-1" /> {t('notes.heading2')}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className="format-pill-btn"
|
||||
onClick={() => { editor.chain().focus().toggleHeading({ level: 3 }).run(); onClose() }}
|
||||
>
|
||||
<Heading3 size={14} className="inline mr-1" /> {t('notes.heading3') || 'Titre 3'}
|
||||
<Heading3 size={14} className="inline mr-1" /> {t('notes.heading3')}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className="format-pill-btn"
|
||||
onClick={() => { editor.chain().focus().toggleBlockquote().run(); onClose() }}
|
||||
>
|
||||
<Quote size={14} className="inline mr-1" /> {t('mobile.quote') || 'Citation'}
|
||||
<Quote size={14} className="inline mr-1" /> {t('mobile.quote')}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -7,6 +7,7 @@ import {
|
||||
Heading, Code, Sparkles, MessageSquare, Quote, AlignLeft
|
||||
} from 'lucide-react'
|
||||
import { cn } from '@/lib/utils'
|
||||
import { useLanguage } from '@/lib/i18n'
|
||||
|
||||
export type MobileEditorToolbarProps = {
|
||||
editor: Editor | null
|
||||
@@ -19,6 +20,7 @@ export function MobileEditorToolbar({
|
||||
onOpenActionSheet,
|
||||
onInsertImage,
|
||||
}: MobileEditorToolbarProps) {
|
||||
const { t } = useLanguage()
|
||||
if (!editor) return null
|
||||
|
||||
// Format states
|
||||
@@ -61,7 +63,7 @@ export function MobileEditorToolbar({
|
||||
type="button"
|
||||
className={cn('mobile-toolbar-btn', isBold && 'active')}
|
||||
onClick={() => editor.chain().focus().toggleBold().run()}
|
||||
aria-label="Bold"
|
||||
aria-label={t('editor.bold')}
|
||||
>
|
||||
<Bold size={18} />
|
||||
</button>
|
||||
@@ -70,7 +72,7 @@ export function MobileEditorToolbar({
|
||||
type="button"
|
||||
className={cn('mobile-toolbar-btn', isItalic && 'active')}
|
||||
onClick={() => editor.chain().focus().toggleItalic().run()}
|
||||
aria-label="Italic"
|
||||
aria-label={t('editor.italic')}
|
||||
>
|
||||
<Italic size={18} />
|
||||
</button>
|
||||
@@ -79,7 +81,7 @@ export function MobileEditorToolbar({
|
||||
type="button"
|
||||
className={cn('mobile-toolbar-btn', isHighlight && 'active')}
|
||||
onClick={() => editor.chain().focus().toggleHighlight().run()}
|
||||
aria-label="Highlight"
|
||||
aria-label={t('editor.highlight')}
|
||||
>
|
||||
<Highlighter size={18} />
|
||||
</button>
|
||||
@@ -88,7 +90,7 @@ export function MobileEditorToolbar({
|
||||
type="button"
|
||||
className={cn('mobile-toolbar-btn', isLink && 'active')}
|
||||
onClick={handleLinkPress}
|
||||
aria-label="Link"
|
||||
aria-label={t('editor.link')}
|
||||
>
|
||||
<Link2 size={18} />
|
||||
</button>
|
||||
@@ -97,7 +99,7 @@ export function MobileEditorToolbar({
|
||||
type="button"
|
||||
className={cn('mobile-toolbar-btn', isBulletList && 'active')}
|
||||
onClick={() => editor.chain().focus().toggleBulletList().run()}
|
||||
aria-label="Bullet List"
|
||||
aria-label={t('editor.bulletList')}
|
||||
>
|
||||
<List size={18} />
|
||||
</button>
|
||||
@@ -106,7 +108,7 @@ export function MobileEditorToolbar({
|
||||
type="button"
|
||||
className={cn('mobile-toolbar-btn', isTaskList && 'active')}
|
||||
onClick={() => editor.chain().focus().toggleTaskList().run()}
|
||||
aria-label="Task List"
|
||||
aria-label={t('editor.taskList')}
|
||||
>
|
||||
<CheckSquare size={18} />
|
||||
</button>
|
||||
@@ -115,7 +117,7 @@ export function MobileEditorToolbar({
|
||||
type="button"
|
||||
className={cn('mobile-toolbar-btn', isHeading && 'active')}
|
||||
onClick={toggleHeadingCycle}
|
||||
aria-label="Heading"
|
||||
aria-label={t('editor.heading')}
|
||||
>
|
||||
<Heading size={18} />
|
||||
</button>
|
||||
@@ -124,7 +126,7 @@ export function MobileEditorToolbar({
|
||||
type="button"
|
||||
className={cn('mobile-toolbar-btn', isCodeBlock && 'active')}
|
||||
onClick={() => editor.chain().focus().toggleCodeBlock().run()}
|
||||
aria-label="Code Block"
|
||||
aria-label={t('editor.codeBlock')}
|
||||
>
|
||||
<Code size={18} />
|
||||
</button>
|
||||
@@ -133,7 +135,7 @@ export function MobileEditorToolbar({
|
||||
type="button"
|
||||
className="mobile-toolbar-btn highlight-btn"
|
||||
onClick={onOpenActionSheet}
|
||||
aria-label="Plus"
|
||||
aria-label={t('editor.plus')}
|
||||
>
|
||||
<Sparkles size={18} className="text-amber-500 animate-pulse" />
|
||||
</button>
|
||||
|
||||
@@ -60,7 +60,7 @@ export function MoveToNotebookPicker({
|
||||
close()
|
||||
}
|
||||
|
||||
const child = React.cloneElement(children, {
|
||||
const child = React.cloneElement(children as any, {
|
||||
ref: (node: HTMLElement | null) => {
|
||||
triggerRef.current = node
|
||||
const childRef = (children as React.ReactElement & { ref?: React.Ref<HTMLElement> }).ref
|
||||
@@ -71,7 +71,7 @@ export function MoveToNotebookPicker({
|
||||
},
|
||||
onClick: (e: React.MouseEvent) => {
|
||||
e.stopPropagation()
|
||||
children.props.onClick?.(e)
|
||||
;(children as any).props.onClick?.(e)
|
||||
setOpen((prev) => !prev)
|
||||
},
|
||||
})
|
||||
|
||||
@@ -362,22 +362,27 @@ export function NetworkGraph({
|
||||
|
||||
return (
|
||||
<div ref={containerRef} className="w-full h-full bg-paper dark:bg-[#121212] rounded-3xl overflow-hidden border border-border/40 relative">
|
||||
{/* Pastilles de cluster — cliquables pour activer le focus */}
|
||||
<div className="absolute top-6 left-6 z-10 flex flex-wrap gap-2 max-w-[90%]">
|
||||
{clusters.map(c => {
|
||||
{/* Pastilles de cluster — triées par taille, avec compteurs */}
|
||||
<div className="absolute top-6 left-6 z-10 flex flex-wrap gap-1.5 max-w-[85%]">
|
||||
{[...clusters]
|
||||
.sort((a, b) => b.noteIds.length - a.noteIds.length)
|
||||
.map(c => {
|
||||
const isSelected = String(c.id) === selectedClusterId
|
||||
return (
|
||||
<button
|
||||
key={c.id}
|
||||
onClick={() => onClusterSelect?.(isSelected ? null : String(c.id))}
|
||||
className={`flex items-center gap-1.5 px-3 py-1.5 rounded-full border shadow-sm transition-all text-[9px] font-bold uppercase tracking-wider ${
|
||||
className={`flex items-center gap-1.5 px-2.5 py-1 rounded-full border transition-all text-[9px] font-bold uppercase tracking-wider cursor-pointer focus-visible:ring-2 focus-visible:ring-ochre/50 focus-visible:outline-none ${
|
||||
isSelected
|
||||
? 'bg-ink text-white dark:bg-white dark:text-black border-ink dark:border-white scale-105 shadow-md'
|
||||
: 'bg-white/90 dark:bg-black/80 text-concrete hover:text-ink hover:border-concrete/40 border-border'
|
||||
: 'bg-white/90 dark:bg-black/80 text-concrete hover:text-ink hover:border-concrete/40 border-border shadow-sm'
|
||||
}`}
|
||||
>
|
||||
<div className="w-1.5 h-1.5 rounded-full" style={{ backgroundColor: c.color }} />
|
||||
<span>{c.name ?? String(c.id)}</span>
|
||||
<div className="w-2 h-2 rounded-full shrink-0" style={{ backgroundColor: c.color }} />
|
||||
<span className="truncate max-w-[120px]">{c.name ?? String(c.id)}</span>
|
||||
<span className={`text-[8px] px-1 rounded-full shrink-0 ${isSelected ? 'bg-white/20' : 'bg-black/5 dark:bg-white/10'}`}>
|
||||
{c.noteIds.length}
|
||||
</span>
|
||||
</button>
|
||||
)
|
||||
})}
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user