feat: publication IA (magazine/brief/essay) + fixes critique
Some checks failed
CI / Lint, Unit Tests & Build (push) Failing after 1m22s
CI / Deploy production (on server) (push) Has been skipped

Publication IA:
- 4 templates (magazine, brief, essay, simple) avec CSS riche
- Rewrite IA (article/exercises/tutorial/reference/mixed)
- Modération avec timeout 12s + fallback safe
- Quotas publish_enhance par tier (basic=2, pro=15, business=100)
- Détection contenu stale (hash)
- Migration DB publishedContent/publishedTemplate/publishedSourceHash

Fixes:
- cheerio v1.2: Element -> AnyNode (domhandler), decodeEntities cast
- _isShared ajouté au type Note (champ virtuel serveur)
- callout colors PDF export: extraction fonction pure testable
- admin/published: guard note.userId null
- Cmd+S fonctionne en mode dialog (pas seulement fullPage)

i18n:
- 23 clés publish* traduites dans les 15 locales
- Extension Web Clipper: 13 locales mise à jour

Tests:
- callout-colors.test.ts (6 tests)
- note-visible-in-view.test.ts (5 tests)
- entitlements.test.ts + byok-entitlements.test.ts: mock usageLog + unstubAllEnvs
- 199/199 tests passent

Tracker: user-stories.md sync avec sprint-status.yaml
This commit is contained in:
Antigravity
2026-06-28 07:32:57 +00:00
parent 902fe95a69
commit 96e7902f01
169 changed files with 5382 additions and 1527 deletions

View File

@@ -29,7 +29,7 @@ export default function AuthLayout({
<div className="w-8 h-8 bg-[var(--foreground)] text-[var(--background)] rounded-xl flex items-center justify-center shadow-lg">
<span className="font-serif font-bold text-xl">M</span>
</div>
<span className="font-serif text-xl font-medium tracking-tight">Momento</span>
<span className="font-serif text-xl font-medium tracking-tight">Memento</span>
</Link>
<div className="w-8" />
@@ -39,7 +39,7 @@ export default function AuthLayout({
<div className="w-full max-w-md">
{children}
<p className="text-center mt-8 text-[9px] text-[var(--muted-foreground)] font-bold uppercase tracking-[0.3em] opacity-40 select-none">
© 2025 Momento Labs
© 2025 Memento Labs
</p>
</div>
</main>

View File

@@ -12,8 +12,8 @@ export function AISettingsHeader() {
steps={[
{ text: 'Choisissez un fournisseur IA parmi 8 disponibles : OpenAI, Anthropic, Google, Mistral, Groq, DeepSeek, Perplexity, ou Ollama (local).' },
{ text: 'Sélectionnez le modèle — chaque fournisseur propose plusieurs modèles avec des capacités différentes (rapidité, coût, contexte).' },
{ text: 'Mode BYOK (Bring Your Own Key) : entrez votre propre clé API pour utiliser votre quota directement — sans passer par les quotas Momento.' },
{ text: 'Les crédits Momento (quota mensuel) sont utilisés quand vous n\'avez pas de clé personnelle. Le plan Free inclut 10 crédits/mois.' },
{ text: 'Mode BYOK (Bring Your Own Key) : entrez votre propre clé API pour utiliser votre quota directement — sans passer par les quotas Memento.' },
{ text: 'Les crédits Memento (quota mensuel) sont utilisés quand vous n\'avez pas de clé personnelle. Le plan Free inclut 10 crédits/mois.' },
{ icon: '💡', text: 'Conseil : Ollama permet de faire tourner un LLM entièrement en local sur votre machine — 100% privé, zéro coût.' },
]}
/>

View File

@@ -231,7 +231,7 @@ export default function DataSettingsPage() {
steps={[
{ text: 'Export ZIP : télécharge toutes vos notes en fichiers Markdown + images + métadonnées. Format universel, lisible partout.' },
{ text: 'Export JSON : version structurée de vos données — utile pour migrer ou sauvegarder programmatiquement.' },
{ text: 'Import Markdown : importez un fichier .md existant directement dans Momento en tant que nouvelle note.' },
{ text: 'Import Markdown : importez un fichier .md existant directement dans Memento en tant que nouvelle note.' },
{ text: 'Ré-indexer : si la recherche sémantique ne trouve pas certaines notes, relancez l\'indexation pour recalculer les embeddings.' },
{ icon: '⚠️', text: 'Supprimer le compte efface définitivement toutes vos données. Pensez à exporter d\'abord.' },
]}

View File

@@ -140,7 +140,7 @@ export default function IntegrationsPage() {
<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 à Momento.</p>
<p className="text-sm text-concrete mt-1">Connectez des services externes à Memento.</p>
</div>
{/* ── Google Calendar ────────────────────────────────────────────── */}
@@ -166,7 +166,7 @@ export default function IntegrationsPage() {
{ 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 Momento — ajoutez vos notes en temps réel pendant la réunion.' },
{ text: 'La note s\'ouvre directement dans Memento — ajoutez vos notes en temps réel pendant la réunion.' },
]}
/>
<button

View File

@@ -19,11 +19,11 @@ export default async function McpSettingsPage() {
title="Qu'est-ce que MCP (Model Context Protocol) ?"
defaultOpen={true}
steps={[
{ text: 'MCP est un protocole qui permet aux agents IA de Momento de se connecter à des outils externes (bases de données, APIs, fichiers, etc.).' },
{ text: 'Momento expose un serveur MCP avec 22 outils — vos agents peuvent lire/créer des notes, chercher dans votre base, gérer les carnets, etc.' },
{ text: 'MCP est un protocole qui permet aux agents IA de Memento de se connecter à des outils externes (bases de données, APIs, fichiers, etc.).' },
{ text: 'Memento expose un serveur MCP avec 22 outils — vos agents peuvent lire/créer des notes, chercher dans votre base, gérer les carnets, etc.' },
{ text: 'Créez une clé API ici, puis configurez-la dans votre client MCP (Claude Desktop, Cursor, Continue.dev…) avec l\'URL du serveur.' },
{ text: 'Format de configuration : URL du serveur MCP + votre clé dans le header Authorization.', link: { label: 'Documentation MCP', href: 'https://modelcontextprotocol.io/docs' } },
{ icon: '⚡', text: 'Cas d\'usage : demandez à Claude Desktop d\'écrire une note dans Momento, de chercher dans vos carnets, ou de créer un agent.' },
{ icon: '⚡', text: 'Cas d\'usage : demandez à Claude Desktop d\'écrire une note dans Memento, de chercher dans vos carnets, ou de créer un agent.' },
]}
/>
<McpSettingsPanel initialKeys={keys} serverStatus={serverStatus} />

View File

@@ -0,0 +1,403 @@
import { notFound } from 'next/navigation'
import { Flag, Sparkles, BookOpen, Clock } from 'lucide-react'
import { format } from 'date-fns'
import { fr } from 'date-fns/locale'
import prisma from '@/lib/prisma'
import { processNoteHtmlForPublish } from '@/lib/publish/process-note-html'
import { REWRITE_SHARED_CSS, KATEX_PUBLISH_CSS } from '@/lib/publish/shared-css'
export const revalidate = 60
async function getNotebookSite(slug: string) {
const site = await prisma.notebookSite.findUnique({
where: { slug },
include: {
notebook: {
select: {
id: true,
name: true,
icon: true,
user: { select: { name: true, image: true } },
notes: {
select: { id: true, title: true, content: true, order: true, updatedAt: true },
where: { trashedAt: null, isArchived: false },
orderBy: { order: 'asc' },
},
},
},
},
})
if (!site || !site.isPublic) return null
return site
}
export async function generateMetadata({ params }: { params: Promise<{ slug: string }> }) {
const { slug } = await params
const site = await getNotebookSite(slug)
if (!site) return { title: 'Site introuvable — Memento' }
return {
title: `${site.notebook.name} — Memento`,
description: site.description || `Carnet publié sur Memento`,
openGraph: { title: site.notebook.name, description: site.description || '' },
}
}
function wordCount(html: string) {
return (html || '').replace(/<[^>]+>/g, ' ').trim().split(/\s+/).filter(Boolean).length
}
function readingTime(html: string) {
return Math.max(1, Math.ceil(wordCount(html) / 200))
}
function preview(html: string, len = 140) {
return (html || '').replace(/<[^>]+>/g, ' ').replace(/\s+/g, ' ').trim().slice(0, len)
}
export default async function NotebookSitePage({ params }: { params: Promise<{ slug: string }> }) {
const { slug } = await params
const site = await getNotebookSite(slug)
if (!site) notFound()
let selectedIds: string[] = []
try { selectedIds = JSON.parse(site.selectedNoteIds) } catch {}
const allNotes = site.notebook.notes
const orderedNotes = selectedIds.length > 0
? selectedIds.map(id => allNotes.find(n => n.id === id)).filter(Boolean) as typeof allNotes
: allNotes
const notebook = site.notebook
const totalWc = orderedNotes.reduce((s, n) => s + wordCount(n.content || ''), 0)
const totalRt = Math.max(1, Math.ceil(totalWc / 200))
return (
<>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/katex@0.16.9/dist/katex.min.css" />
<link href="https://fonts.googleapis.com/css2?family=Playfair+Display:ital,wght@0,700;0,900;1,700&family=Source+Serif+4:opsz,wght@8..60,300..600&family=Inter:wght@400;500;600&display=swap" rel="stylesheet" />
{/* ── NAV ── */}
<nav className="cs-nav">
<a href="/" className="cs-nav-brand">Memento</a>
<div className="cs-nav-right">
<span className="cs-nav-badge"><Sparkles size={10} /> Site publié</span>
<a href={`/c/${slug}/report`} className="cs-nav-report"><Flag size={11} /> Signaler</a>
</div>
</nav>
{/* ── HERO ── */}
<header className="cs-hero">
<div className="cs-hero-inner">
{notebook.icon && <div className="cs-hero-icon">{notebook.icon}</div>}
<div className="cs-hero-label">CARNET · {orderedNotes.length} NOTES · {totalRt} MIN</div>
<h1 className="cs-hero-title">{notebook.name}</h1>
{site.description && <p className="cs-hero-desc">{site.description}</p>}
{notebook.user?.name && (
<div className="cs-hero-author">
{notebook.user.image && <img src={notebook.user.image} alt="" className="cs-hero-avatar" />}
<span>par <strong>{notebook.user.name}</strong></span>
</div>
)}
</div>
</header>
{/* ── TABLE DES MATIÈRES ── */}
<section className="cs-toc-section">
<div className="cs-toc-inner">
<p className="cs-toc-label">TABLE DES MATIÈRES</p>
<div className="cs-toc-grid">
{orderedNotes.map((note, i) => (
<a key={note.id} href={`#note-${note.id}`} className="cs-toc-card">
<span className="cs-toc-num">{String(i + 1).padStart(2, '0')}</span>
<div>
<div className="cs-toc-card-title">{note.title || 'Sans titre'}</div>
<div className="cs-toc-card-preview">{preview(note.content || '')}</div>
<div className="cs-toc-card-rt"><Clock size={10} /> {readingTime(note.content || '')} min</div>
</div>
</a>
))}
</div>
</div>
</section>
{/* ── NOTES ── */}
<main className="cs-main">
<aside className="cs-sidebar">
<p className="cs-sidebar-label">NAVIGATION</p>
{orderedNotes.map((note, i) => (
<a key={note.id} href={`#note-${note.id}`} className="cs-sidebar-link">
<span className="cs-sidebar-num">{i + 1}</span>
<span className="cs-sidebar-title">{note.title || 'Sans titre'}</span>
</a>
))}
</aside>
<div className="cs-articles">
{orderedNotes.map((note, i) => {
const bodyHtml = processNoteHtmlForPublish(note.content || '')
const rt = readingTime(note.content || '')
return (
<article key={note.id} id={`note-${note.id}`} className="cs-article">
<div className="cs-article-meta">
<span className="cs-article-num">{String(i + 1).padStart(2, '0')}</span>
<span className="cs-article-rt"><Clock size={10} /> {rt} min de lecture</span>
</div>
<h2 className="cs-article-title">{note.title || 'Sans titre'}</h2>
<div
className="cs-article-body pub-article pub-rewrite-body"
dir="auto"
dangerouslySetInnerHTML={{ __html: bodyHtml }}
/>
</article>
)
})}
</div>
</main>
{/* ── FOOTER ── */}
<footer className="cs-footer">
<div className="cs-footer-inner">
<span>Publié avec <a href="/" className="cs-footer-brand">Memento</a></span>
<a href={`/c/${slug}/report`} className="cs-footer-report"><Flag size={11} /> Signaler ce contenu</a>
</div>
</footer>
<style>{`
*, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }
html { scroll-behavior: smooth; }
body { background: #fff; color: #111; font-family: 'Inter', system-ui, sans-serif; }
/* ── NAV ── */
.cs-nav {
position: sticky; top: 0; z-index: 50;
background: #111; color: #fff;
display: flex; align-items: center; justify-content: space-between;
padding: 0 32px; height: 52px;
}
.cs-nav-brand {
font-family: 'Playfair Display', Georgia, serif;
font-size: 17px; font-weight: 900; letter-spacing: .04em;
color: #fff; text-decoration: none;
}
.cs-nav-right { display: flex; align-items: center; gap: 16px; }
.cs-nav-badge {
display: flex; align-items: center; gap: 4px;
font-size: 10px; font-weight: 700; letter-spacing: .12em;
text-transform: uppercase; color: #f5c96a;
}
.cs-nav-report {
display: flex; align-items: center; gap: 4px;
font-size: 11px; color: rgba(255,255,255,.4); text-decoration: none;
}
.cs-nav-report:hover { color: rgba(255,255,255,.7); }
/* ── HERO ── */
.cs-hero {
background: #111; color: #fff;
padding: 72px 32px 80px; text-align: center;
}
.cs-hero-inner { max-width: 780px; margin: 0 auto; }
.cs-hero-icon { font-size: 48px; margin-bottom: 20px; line-height: 1; }
.cs-hero-label {
font-size: 11px; font-weight: 700; letter-spacing: .22em;
text-transform: uppercase; color: #f5c96a; margin-bottom: 24px;
}
.cs-hero-title {
font-family: 'Playfair Display', Georgia, serif;
font-size: clamp(36px, 6vw, 66px);
font-weight: 900; line-height: 1.08; letter-spacing: -.02em;
margin-bottom: 24px;
}
.cs-hero-desc {
font-size: 18px; line-height: 1.7; color: rgba(255,255,255,.65);
max-width: 600px; margin: 0 auto 28px;
}
.cs-hero-author {
display: inline-flex; align-items: center; gap: 10px;
font-size: 13px; color: rgba(255,255,255,.5);
}
.cs-hero-avatar {
width: 28px; height: 28px; border-radius: 50%;
border: 2px solid rgba(255,255,255,.2); object-fit: cover;
}
/* ── TABLE DES MATIÈRES ── */
.cs-toc-section { background: #f8f8f6; border-bottom: 1px solid #e8e8e4; padding: 56px 32px; }
.cs-toc-inner { max-width: 1040px; margin: 0 auto; }
.cs-toc-label {
font-size: 10px; font-weight: 700; letter-spacing: .2em;
color: #aaa; text-transform: uppercase; margin-bottom: 24px;
}
.cs-toc-grid {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
gap: 16px;
}
.cs-toc-card {
display: flex; gap: 16px; align-items: flex-start;
background: #fff; border: 1px solid #e8e8e4;
border-radius: 12px; padding: 20px 22px;
text-decoration: none; color: inherit;
transition: border-color .15s, box-shadow .15s;
}
.cs-toc-card:hover {
border-color: #111;
box-shadow: 0 4px 20px rgba(0,0,0,.07);
}
.cs-toc-num {
font-size: 11px; font-weight: 700; color: #f5c96a;
background: #111; border-radius: 6px;
padding: 4px 7px; line-height: 1; flex-shrink: 0; margin-top: 2px;
}
.cs-toc-card-title { font-size: 14px; font-weight: 700; color: #111; line-height: 1.35; margin-bottom: 6px; }
.cs-toc-card-preview { font-size: 12px; color: #777; line-height: 1.5; margin-bottom: 8px; }
.cs-toc-card-rt {
display: flex; align-items: center; gap: 4px;
font-size: 10px; color: #bbb; font-weight: 500;
}
/* ── LAYOUT PRINCIPAL ── */
.cs-main {
max-width: 1200px; margin: 0 auto;
display: grid; grid-template-columns: 260px 1fr;
gap: 0; min-height: 60vh;
}
@media (max-width: 820px) { .cs-main { grid-template-columns: 1fr; } }
/* ── SIDEBAR ── */
.cs-sidebar {
padding: 48px 24px 48px 32px;
border-right: 1px solid #f0f0ee;
position: sticky; top: 52px;
height: calc(100vh - 52px); overflow-y: auto;
}
@media (max-width: 820px) { .cs-sidebar { display: none; } }
.cs-sidebar-label {
font-size: 9px; font-weight: 700; letter-spacing: .2em;
color: #bbb; text-transform: uppercase; margin-bottom: 16px;
padding-bottom: 12px; border-bottom: 1px solid #f0f0ee;
}
.cs-sidebar-link {
display: flex; align-items: flex-start; gap: 10px;
padding: 8px 10px; border-radius: 8px; margin-bottom: 2px;
text-decoration: none; color: #555; font-size: 12.5px; line-height: 1.45;
transition: background .12s, color .12s;
}
.cs-sidebar-link:hover { background: #f5f5f3; color: #111; }
.cs-sidebar-num {
flex-shrink: 0; font-size: 10px; font-weight: 700;
color: #ccc; width: 18px; text-align: right; padding-top: 1px;
}
.cs-sidebar-title { font-weight: 500; }
/* ── ARTICLES ── */
.cs-articles { padding: 64px 60px; }
@media (max-width: 1024px) { .cs-articles { padding: 48px 32px; } }
@media (max-width: 640px) { .cs-articles { padding: 32px 20px; } }
.cs-article { padding-top: 56px; margin-top: 56px; border-top: 1px solid #eeecea; }
.cs-article:first-child { margin-top: 0; padding-top: 0; border-top: none; }
.cs-article-meta {
display: flex; align-items: center; gap: 14px;
margin-bottom: 16px;
}
.cs-article-num {
font-size: 11px; font-weight: 700; color: #f5c96a;
background: #111; border-radius: 6px; padding: 3px 8px; line-height: 1;
}
.cs-article-rt {
display: flex; align-items: center; gap: 4px;
font-size: 11px; color: #bbb; font-weight: 500;
}
.cs-article-title {
font-family: 'Playfair Display', Georgia, serif;
font-size: clamp(24px, 3.5vw, 38px);
font-weight: 900; line-height: 1.15; letter-spacing: -.01em;
color: #111; margin-bottom: 32px;
}
/* ── ARTICLE BODY ── */
.cs-article-body {
font-family: 'Source Serif 4', Georgia, serif;
font-size: 18px; line-height: 1.85; color: #1a1a1a;
max-width: 680px;
}
.cs-article-body h2 {
font-family: 'Playfair Display', serif; font-size: 1.5em;
font-weight: 700; margin-top: 2.5em; margin-bottom: .6em; color: #111;
}
.cs-article-body h3 {
font-size: 1.15em; font-weight: 700;
margin-top: 2em; margin-bottom: .5em; color: #111;
font-family: 'Inter', sans-serif;
}
.cs-article-body p { margin: 1em 0; }
.cs-article-body blockquote {
border-left: 4px solid #f5c96a; padding-left: 1.2em;
margin: 1.5em 0; color: #444; font-style: italic;
}
.cs-article-body ul, .cs-article-body ol { padding-left: 1.5em; margin: 1em 0; }
.cs-article-body li { margin: .4em 0; }
.cs-article-body pre {
background: #111; color: #e8e3d5; padding: 22px 24px;
border-radius: 10px; overflow-x: auto; font-size: 13px; margin: 1.5em 0;
font-family: 'SF Mono', Menlo, monospace;
}
.cs-article-body code {
font-family: 'SF Mono', Menlo, monospace; font-size: .87em;
background: #f3f2ef; padding: 1px 5px; border-radius: 3px; color: #1a1a1a;
}
.cs-article-body pre code { background: none; color: inherit; padding: 0; }
.cs-article-body table { border-collapse: collapse; width: 100%; margin: 1.5em 0; }
.cs-article-body th {
background: #111; color: #fff; padding: 10px 14px;
text-align: left; font-size: 13px; letter-spacing: .05em; font-family: 'Inter', sans-serif;
}
.cs-article-body td { border-bottom: 1px solid #e8e8e4; padding: 10px 14px; }
.cs-article-body a { color: #b8832a; text-decoration: underline; text-underline-offset: 3px; }
.cs-article-body .pub-figure { margin: 2.5em 0; text-align: center; }
.cs-article-body .pub-figure-img { max-width: 100%; border-radius: 8px; box-shadow: 0 12px 40px rgba(0,0,0,.1); }
.cs-article-body .pub-figure-caption { margin-top: .6em; font-size: .8em; color: #888; font-style: italic; }
.cs-article-body .pub-gallery {
display: grid; grid-template-columns: repeat(auto-fit, minmax(180px, 1fr));
gap: 10px; margin: 2em 0;
}
.cs-article-body .pub-gallery-img { width: 100%; height: 180px; object-fit: cover; border-radius: 8px; display: block; }
/* Variables CSS pour blocs structurés */
.cs-article-body {
--pub-accent: #9a7212;
--pub-summary-color: #333;
--pub-exercise-border: #e0d4c3;
--pub-exercise-header-bg: #faf6ee;
--pub-solution-bg: #faf6ee;
--pub-definition-border: #e0d4c3;
--pub-definition-bg: #fafaf8;
--pub-toggle-border: #e5e5e5;
--pub-toggle-header-bg: #f7f7f5;
--pub-highlight-bg: #faf6ee;
--pub-checklist-bg: rgba(0,0,0,.03);
}
.cs-article-body .pub-code { background: #0d0d0d; }
.cs-article-body .pub-code code { background: #0d0d0d; color: #e8e3d5; }
/* ── FOOTER ── */
.cs-footer { background: #111; color: rgba(255,255,255,.4); padding: 32px; }
.cs-footer-inner {
max-width: 1040px; margin: 0 auto;
display: flex; justify-content: space-between; align-items: center;
font-size: 13px; flex-wrap: wrap; gap: 12px;
}
.cs-footer-brand { color: #f5c96a; font-weight: 700; text-decoration: none; }
.cs-footer-report {
display: flex; align-items: center; gap: 5px;
font-size: 11px; color: rgba(255,255,255,.3); text-decoration: none;
}
.cs-footer-report:hover { color: rgba(255,255,255,.6); }
${KATEX_PUBLISH_CSS}
${REWRITE_SHARED_CSS}
`}</style>
</>
)
}

View File

@@ -1,146 +1,589 @@
import { notFound } from 'next/navigation'
import { getPublishedNote } from '@/app/actions/notes-publishing'
import { Calendar, Clock, Flag } from 'lucide-react'
import { Flag, Sparkles } from 'lucide-react'
import { format } from 'date-fns'
import katex from 'katex'
import { sanitizeRichHtml } from '@/lib/sanitize-content'
import { fr } from 'date-fns/locale'
import { computePublishedSourceHash } from '@/lib/publish/template-render'
import { processNoteHtmlForPublish } from '@/lib/publish/process-note-html'
import { REWRITE_SHARED_CSS, KATEX_PUBLISH_CSS } from '@/lib/publish/shared-css'
export async function generateMetadata({ params }: { params: Promise<{ slug: string }> }) {
const { slug } = await params
const note = await getPublishedNote(slug)
if (!note) return { title: 'Note not found — Momento' }
if (!note) return { title: 'Note introuvable — Memento' }
return {
title: `${note.title || 'Published note'} — Momento`,
title: `${note.title || 'Note publiée'} — Memento`,
description: note.content?.replace(/<[^>]+>/g, '').slice(0, 160),
}
}
export const revalidate = 60
function decodeHtml(text: string): string {
const map: Record<string, string> = { '&quot;': '"', '&amp;': '&', '&lt;': '<', '&gt;': '>', '&#39;': "'" }
return text.replace(/&[a-z#0-9]+;/gi, m => map[m] || m)
}
function processContent(html: string): string {
let result = html
// KaTeX block math
result = result.replace(/<div[^>]*data-type="math-equation"[^>]*data-latex="([^"]*)"[^>]*><\/div>/g, (_, latex) => {
try { return `<div class="r-math-display">${katex.renderToString(decodeHtml(latex), { displayMode: true, throwOnError: false })}</div>` }
catch { return `<div class="r-math-display">${latex}</div>` }
})
// KaTeX inline math
result = result.replace(/<span[^>]*data-type="inline-math"[^>]*data-latex="([^"]*)"[^>]*>.*?<\/span>/g, (_, latex) => {
try { return katex.renderToString(decodeHtml(latex), { displayMode: false, throwOnError: false }) }
catch { return latex }
})
// Callouts
result = result.replace(/<div[^>]*data-type="callout-block"[^>]*data-callout-type="([^"]*)"[^>]*>/g, (_, type) => {
const c: Record<string, string> = {
info: '#eff6ff|#3b82f6', warning: '#fffbeb|#f59e0b', tip: '#faf5ff|#8b5cf6',
success: '#f0fdf4|#22c55e', danger: '#fef2f2|#ef4444',
}
const [bg, border] = (c[type] || c.info).split('|')
return `<div style="background:${bg};border-left:4px solid ${border};border-radius:8px;padding:12px 16px;margin:16px 0">`
})
// Remove outline blocks (need editor JS)
result = result.replace(/<div[^>]*data-type="outline-block"[^>]*><\/div>/g, '')
// Remove link preview searchable text
result = result.replace(/<div[^>]*class="link-preview-searchable"[^>]*>[\s\S]*?<\/div>/g, '')
// Remove editor buttons
result = result.replace(/<button[^>]*>[\s\S]*?<\/button>/g, '')
// Remove contentEditable attributes
result = result.replace(/contenteditable="[^"]*"/gi, '')
return result
}
function estimateReadingTime(html: string): number {
const words = html.replace(/<[^>]+>/g, ' ').trim().split(/\s+/).length
return Math.max(1, Math.ceil(words / 200))
}
export default async function PublishedNotePage({ params }: { params: Promise<{ slug: string }> }) {
const { slug } = await params
const note = await getPublishedNote(slug)
if (!note) notFound()
const processedContent = processContent(note.content || '')
const readingTime = estimateReadingTime(note.content || '')
/* ─── MAGAZINE ──────────────────────────────────────────────────────────── */
function MagazinePage({ note, bodyHtml, readingTime, slug, isStale }: PageProps) {
return (
<>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/katex@0.16.9/dist/katex.min.css" />
<link href="https://fonts.googleapis.com/css2?family=Playfair+Display:ital,wght@0,700;0,900;1,700&family=Source+Serif+4:opsz,wght@8..60,300..600&family=Inter:wght@400;500&display=swap" rel="stylesheet" />
<div className="mag-root">
<nav className="mag-nav">
<span className="mag-nav-brand">Memento</span>
<div className="mag-nav-right">
<span className="mag-badge"><Sparkles size={10} /> Article</span>
<a href={`/p/${slug}/report`} className="mag-report"><Flag size={11} /> Signaler</a>
</div>
</nav>
{/* Header pleine largeur */}
<header className="mag-header">
<div className="mag-header-inner">
<div className="mag-category">ARTICLE · {note.publishedAt ? format(new Date(note.publishedAt), 'd MMMM yyyy', { locale: fr }) : ''} · {readingTime} min</div>
<h1 className="mag-title">{note.title || 'Sans titre'}</h1>
{note.user?.name && (
<div className="mag-author">
{note.user.image && <img src={note.user.image} alt="" className="mag-avatar" />}
<span>par <strong>{note.user.name}</strong></span>
</div>
)}
</div>
</header>
<div className="mag-content">
<div dir="auto" className="mag-body pub-article" dangerouslySetInnerHTML={{ __html: bodyHtml }} />
</div>
<footer className="mag-footer">
<span>Memento</span> Votre mémoire augmentée par l&rsquo;IA
{isStale && <p className="mag-stale">Le contenu source a évolué depuis la dernière publication.</p>}
</footer>
</div>
<style>{`
*, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }
.mag-root { min-height: 100vh; background: #fff; color: #111; font-family: 'Inter', sans-serif; }
.mag-nav {
position: sticky; top: 0; z-index: 20;
background: #111; color: #fff;
display: flex; align-items: center; justify-content: space-between;
padding: 12px 28px;
}
.mag-nav-brand { font-family: 'Playfair Display', serif; font-size: 17px; font-weight: 900; letter-spacing: 0.04em; }
.mag-nav-right { display: flex; align-items: center; gap: 12px; }
.mag-badge { display: flex; align-items: center; gap: 4px; font-size: 11px; font-weight: 600; letter-spacing: 0.12em; color: #f5c96a; text-transform: uppercase; }
.mag-report { display: flex; align-items: center; gap: 4px; font-size: 11px; color: rgba(255,255,255,0.45); text-decoration: none; }
.mag-report:hover { color: #fff; }
.mag-header { background: #111; color: #fff; padding: 64px 28px 72px; text-align: center; }
.mag-header-inner { max-width: 780px; margin: 0 auto; }
.mag-category { font-size: 11px; font-weight: 600; letter-spacing: 0.2em; color: #f5c96a; text-transform: uppercase; margin-bottom: 28px; }
.mag-title {
font-family: 'Playfair Display', Georgia, serif;
font-size: clamp(36px, 7vw, 72px);
font-weight: 900; line-height: 1.05; letter-spacing: -0.02em;
margin-bottom: 28px;
}
.mag-author { display: inline-flex; align-items: center; gap: 10px; font-size: 14px; color: rgba(255,255,255,0.65); }
.mag-avatar { width: 30px; height: 30px; border-radius: 50%; border: 2px solid rgba(255,255,255,0.2); }
.mag-content { max-width: 760px; margin: 0 auto; padding: 64px 28px 80px; }
/* Body article magazine */
.mag-body { font-family: 'Source Serif 4', Georgia, serif; font-size: 19px; line-height: 1.85; color: #1a1a1a; }
.mag-body .pub-tpl { all: unset; display: block; }
.mag-body .pub-magazine-dek {
font-size: 1.3em; line-height: 1.6; color: #333; margin-bottom: 2.5em;
padding-bottom: 2em; border-bottom: 2px solid #111;
font-style: italic;
}
.mag-body .pub-pull-quote {
font-family: 'Playfair Display', serif;
font-size: clamp(1.5em, 4vw, 2em); font-style: italic; font-weight: 700;
color: #111; line-height: 1.35;
margin: 2.5em 0; padding: 0;
border: none; border-top: 4px solid #f5c96a; border-bottom: 4px solid #f5c96a;
padding: 1.5em 0; text-align: center;
}
.mag-body .pub-pull-quote p { margin: 0; }
.mag-body .pub-hero { margin: 0 -28px 3rem; border-radius: 0; max-height: 560px; aspect-ratio: 16/9; background: #222; overflow: hidden; }
.mag-body .pub-hero-img { width: 100%; height: 100%; object-fit: cover; display: block; }
.mag-body .pub-body-source { }
.mag-body h2 { font-family: 'Playfair Display', serif; font-size: 1.6em; font-weight: 700; margin-top: 2.5em; margin-bottom: 0.6em; }
.mag-body h3 { font-size: 1.2em; font-weight: 600; margin-top: 2em; margin-bottom: 0.5em; }
.mag-body p { margin: 1.1em 0; }
.mag-body blockquote { border-left: 4px solid #f5c96a; padding-left: 1.2em; margin: 1.5em 0; color: #444; font-style: italic; }
.mag-body ul, .mag-body ol { padding-left: 1.5em; margin: 1em 0; }
.mag-body li { margin: 0.4em 0; }
.mag-body pre { background: #f6f6f4; padding: 20px; border-radius: 8px; overflow-x: auto; font-size: 14px; margin: 1.5em 0; }
.mag-body code { font-family: 'SF Mono', Menlo, monospace; font-size: 0.88em; background: #f3f2ef; padding: 1px 5px; border-radius: 3px; }
.mag-body pre code { background: none; padding: 0; }
.mag-body table { border-collapse: collapse; width: 100%; margin: 1.5em 0; }
.mag-body th { background: #111; color: #fff; padding: 10px 14px; text-align: left; font-size: 13px; letter-spacing: 0.05em; }
.mag-body td { border-bottom: 1px solid #e5e5e5; padding: 10px 14px; }
.mag-body a { color: #b8832a; text-decoration: underline; text-underline-offset: 3px; }
.mag-body .pub-figure { margin: 2.5em 0; text-align: center; }
.mag-body .pub-figure-img { max-width: 100%; border-radius: 4px; box-shadow: 0 12px 40px rgba(0,0,0,0.12); }
.mag-body .pub-figure-caption { margin-top: 0.6em; font-size: 0.82em; color: #888; font-style: italic; }
.mag-body .pub-gallery { display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 12px; margin-top: 3em; }
.mag-body .pub-gallery-img { width: 100%; height: 200px; object-fit: cover; border-radius: 4px; display: block; }
.mag-body .pub-callout { border-radius: 6px; padding: 14px 18px; margin: 1.5em 0; }
${KATEX_PUBLISH_CSS}
.mag-footer { background: #111; color: rgba(255,255,255,0.4); padding: 36px 28px; text-align: center; font-size: 13px; font-family: 'Playfair Display', serif; }
.mag-footer span { color: #f5c96a; font-weight: 700; }
.mag-stale { margin-top: 8px; font-size: 11px; color: rgba(255,255,255,0.25); font-family: 'Inter', sans-serif; }
@media (min-width: 900px) {
.mag-body .pub-hero { margin-left: -60px; margin-right: -60px; }
.mag-content { padding-left: 60px; padding-right: 60px; }
}
/* Variables magazine pour blocs réécriture — accents dorés, texte toujours lisible */
.mag-body {
--pub-accent: #9a7212;
--pub-summary-color: #333;
--pub-exercise-border: #e0d4c3;
--pub-exercise-header-bg: #faf6ee;
--pub-solution-bg: #faf6ee;
--pub-definition-border: #e0d4c3;
--pub-definition-bg: #fafaf8;
--pub-toggle-border: #e5e5e5;
--pub-toggle-header-bg: #f7f7f5;
--pub-highlight-bg: #faf6ee;
--pub-checklist-bg: rgba(0,0,0,0.03);
}
.mag-body .pub-rewrite-body .pub-code { background: #0d0d0d; }
.mag-body .pub-rewrite-body .pub-code code { background: #0d0d0d; color: #e8e3d5; }
.mag-body .pub-rewrite-body .pub-definition-term { background: #e8c96a; color: #1a1a1a; }
.mag-body .pub-rewrite-body .pub-step-num { background: #9a7212; color: #fff; }
.mag-body .pub-rewrite-body .pub-exercise-num { color: #9a7212; }
.mag-body .pub-rewrite-body .pub-solution > summary { color: #9a7212; }
.mag-body .pub-rewrite-body .pub-checklist li::before { color: #9a7212; }
.mag-body .pub-magazine-dek { color: #333; }
${REWRITE_SHARED_CSS}
`}</style>
</>
)
}
/* ─── BRIEF ─────────────────────────────────────────────────────────────── */
function BriefPage({ note, bodyHtml, readingTime, slug, isStale }: PageProps) {
return (
<>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/katex@0.16.9/dist/katex.min.css" />
<link href="https://fonts.googleapis.com/css2?family=DM+Sans:wght@400;500;600;700&family=DM+Mono:wght@400;500&display=swap" rel="stylesheet" />
<div className="br-root">
<nav className="br-nav">
<span className="br-brand">Memento</span>
<div style={{ display: 'flex', gap: 10, alignItems: 'center' }}>
<span className="br-badge"><Sparkles size={9} /> Fiche expert</span>
<a href={`/p/${slug}/report`} className="br-report"><Flag size={11} /></a>
</div>
</nav>
<header className="br-header">
<div className="br-header-inner">
<div className="br-meta">
<span className="br-tag">Fiche expert</span>
<span className="br-dot">·</span>
<span>{readingTime} min de lecture</span>
{note.publishedAt && <><span className="br-dot">·</span><span>{format(new Date(note.publishedAt), 'd MMM yyyy', { locale: fr })}</span></>}
</div>
<h1 className="br-title">{note.title || 'Sans titre'}</h1>
{note.user?.name && (
<div className="br-author">
{note.user.image && <img src={note.user.image} alt="" className="br-avatar" />}
<span>{note.user.name}</span>
</div>
)}
</div>
</header>
<div className="br-layout">
<div className="br-content">
<div dir="auto" className="br-body pub-article" dangerouslySetInnerHTML={{ __html: bodyHtml }} />
</div>
</div>
<footer className="br-footer">
<strong>Memento</strong> Fiche générée par IA
{isStale && <p style={{ fontSize: 11, color: '#aaa', marginTop: 6 }}>Le contenu source a évolué depuis la publication.</p>}
</footer>
</div>
<style>{`
*, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }
.br-root { min-height: 100vh; background: #F4F6F9; color: #1a2433; font-family: 'DM Sans', system-ui, sans-serif; }
.br-nav {
position: sticky; top: 0; z-index: 20; background: #fff;
border-bottom: 1px solid #e8ecf2;
display: flex; align-items: center; justify-content: space-between;
padding: 10px 28px;
}
.br-brand { font-weight: 700; font-size: 15px; color: #1a2433; }
.br-badge { display: flex; align-items: center; gap: 4px; font-size: 11px; font-weight: 600; color: #2563eb; background: #eff6ff; padding: 3px 8px; border-radius: 20px; letter-spacing: 0.04em; }
.br-report { color: #aaa; text-decoration: none; display: flex; }
.br-report:hover { color: #666; }
.br-header { background: linear-gradient(135deg, #1e3a5f 0%, #0f1f35 100%); color: #fff; padding: 56px 28px 60px; }
.br-header-inner { max-width: 820px; margin: 0 auto; }
.br-meta { display: flex; align-items: center; gap: 8px; font-size: 12px; color: rgba(255,255,255,0.55); font-weight: 500; text-transform: uppercase; letter-spacing: 0.08em; margin-bottom: 20px; }
.br-tag { background: #2563eb; color: #fff; font-size: 10px; font-weight: 700; letter-spacing: 0.12em; text-transform: uppercase; padding: 3px 8px; border-radius: 4px; }
.br-dot { color: rgba(255,255,255,0.3); }
.br-title { font-size: clamp(24px, 4.5vw, 44px); font-weight: 700; line-height: 1.2; letter-spacing: -0.02em; margin-bottom: 24px; }
.br-author { display: flex; align-items: center; gap: 8px; font-size: 13px; color: rgba(255,255,255,0.5); }
.br-avatar { width: 26px; height: 26px; border-radius: 50%; border: 2px solid rgba(255,255,255,0.2); }
.br-layout { max-width: 820px; margin: 0 auto; padding: 48px 28px 80px; }
.br-body { font-size: 16px; line-height: 1.75; color: #1a2433; }
.br-body .pub-tpl { all: unset; display: block; }
/* Brief lead summary */
.br-body .pub-brief-lead {
background: #fff; border-radius: 12px;
border-left: 5px solid #2563eb;
padding: 24px 28px; margin-bottom: 2em;
box-shadow: 0 2px 12px rgba(0,0,0,0.06);
}
.br-body .pub-brief-lead p { margin: 0; font-size: 1.08em; line-height: 1.75; color: #1a2433; font-weight: 500; }
/* Key points */
.br-body .pub-key-points {
background: #fff; border-radius: 12px; padding: 24px 28px;
margin-bottom: 2em; box-shadow: 0 2px 12px rgba(0,0,0,0.06);
}
.br-body .pub-key-points-label {
font-size: 10px; text-transform: uppercase; letter-spacing: 0.2em;
font-weight: 700; color: #2563eb; margin-bottom: 14px; display: block;
}
.br-body .pub-key-points ul { list-style: none; padding: 0; margin: 0; }
.br-body .pub-key-points li {
padding: 10px 12px 10px 40px; border-radius: 8px;
background: #f4f6f9; margin-bottom: 8px; position: relative;
font-size: 0.95em; font-weight: 500;
}
.br-body .pub-key-points li::before {
content: '✓'; position: absolute; left: 12px; top: 10px;
color: #2563eb; font-weight: 700; font-size: 14px;
}
/* Source body */
.br-body .pub-body-source {
background: #fff; border-radius: 12px; padding: 32px 36px;
box-shadow: 0 2px 12px rgba(0,0,0,0.06);
}
.br-body .pub-hero { margin: 0 0 2rem; border-radius: 12px; overflow: hidden; max-height: 400px; aspect-ratio: 16/9; background: #dce3ed; }
.br-body .pub-hero-img { width: 100%; height: 100%; object-fit: cover; display: block; }
.br-body h2 { font-size: 1.25em; font-weight: 700; margin-top: 2em; margin-bottom: 0.6em; color: #0f1f35; border-bottom: 2px solid #e8ecf2; padding-bottom: 0.4em; }
.br-body h3 { font-size: 1.08em; font-weight: 600; margin-top: 1.5em; margin-bottom: 0.4em; color: #1e3a5f; }
.br-body p { margin: 0.9em 0; }
.br-body blockquote { border-left: 4px solid #2563eb; padding-left: 1em; margin: 1.2em 0; color: #3d5a80; font-style: italic; }
.br-body ul, .br-body ol { padding-left: 1.4em; margin: 1em 0; }
.br-body li { margin: 0.4em 0; }
.br-body pre { background: #1a2433; color: #e2e8f0; padding: 20px; border-radius: 10px; overflow-x: auto; font-size: 13px; margin: 1.5em 0; font-family: 'DM Mono', monospace; }
.br-body code { font-family: 'DM Mono', monospace; font-size: 0.87em; background: #e8ecf2; padding: 1px 5px; border-radius: 3px; color: #1e3a5f; }
.br-body pre code { background: none; color: inherit; padding: 0; }
.br-body table { border-collapse: collapse; width: 100%; margin: 1.5em 0; border-radius: 8px; overflow: hidden; }
.br-body th { background: #1e3a5f; color: #fff; padding: 10px 14px; text-align: left; font-size: 13px; }
.br-body td { border-bottom: 1px solid #e8ecf2; padding: 10px 14px; }
.br-body tr:last-child td { border-bottom: none; }
.br-body a { color: #2563eb; text-decoration: underline; text-underline-offset: 3px; }
.br-body .pub-figure { margin: 2em 0; text-align: center; }
.br-body .pub-figure-img { max-width: 100%; border-radius: 10px; box-shadow: 0 8px 24px rgba(0,0,0,0.08); }
.br-body .pub-figure-caption { margin-top: 0.5em; font-size: 0.82em; color: #7a8fa6; }
.br-body .pub-gallery { display: grid; grid-template-columns: repeat(auto-fit, minmax(180px, 1fr)); gap: 10px; margin-top: 2em; }
.br-body .pub-gallery-img { width: 100%; height: 160px; object-fit: cover; border-radius: 8px; display: block; }
.br-body .pub-callout { border-radius: 8px; padding: 12px 16px; margin: 1.2em 0; }
${KATEX_PUBLISH_CSS}
.br-footer { background: #0f1f35; color: rgba(255,255,255,0.35); padding: 32px 28px; text-align: center; font-size: 13px; }
.br-footer strong { color: #fff; }
/* Variables brief pour blocs réécriture */
.br-body {
--pub-accent: #2563eb;
--pub-summary-color: #3d5a80;
--pub-exercise-border: #bfdbfe;
--pub-exercise-header-bg: #eff6ff;
--pub-solution-bg: #f0f7ff;
--pub-definition-border: #bfdbfe;
--pub-definition-bg: #f8faff;
--pub-toggle-border: #e2e8f0;
--pub-toggle-header-bg: #f8fafc;
--pub-highlight-bg: #eff6ff;
--pub-checklist-bg: #f4f6f9;
}
.br-body .pub-rewrite-body .pub-code { background: #1a2433; }
.br-body .pub-rewrite-body .pub-code code { background: #1a2433; color: #e2e8f0; }
.br-body .pub-rewrite-body .pub-body-source {
background: #fff; border-radius: 12px; padding: 32px 36px;
box-shadow: 0 2px 12px rgba(0,0,0,0.06);
}
${REWRITE_SHARED_CSS}
`}</style>
</>
)
}
/* ─── ESSAY ──────────────────────────────────────────────────────────────── */
function EssayPage({ note, bodyHtml, readingTime, slug, isStale }: PageProps) {
return (
<>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/katex@0.16.9/dist/katex.min.css" />
<link href="https://fonts.googleapis.com/css2?family=Lora:ital,wght@0,400;0,600;1,400;1,600&family=Source+Serif+4:opsz,wght@8..60,300..600&family=Inter:wght@400;500&display=swap" rel="stylesheet" />
<div className="es-root">
<nav className="es-nav">
<span className="es-brand">Memento</span>
<div style={{ display: 'flex', gap: 12, alignItems: 'center' }}>
<span className="es-badge"><Sparkles size={10} /> Essai</span>
<a href={`/p/${slug}/report`} className="es-report"><Flag size={11} /></a>
</div>
</nav>
<main className="es-main">
<div className="es-rule-top" />
<header className="es-header">
{note.publishedAt && (
<time className="es-date">{format(new Date(note.publishedAt), 'd MMMM yyyy', { locale: fr })}</time>
)}
<h1 className="es-title">{note.title || 'Sans titre'}</h1>
<div className="es-rule-thin" />
{note.user?.name && (
<div className="es-author">
{note.user.image && <img src={note.user.image} alt="" className="es-avatar" />}
<div>
<span className="es-author-name">{note.user.name}</span>
<span className="es-reading-time">{readingTime} min de lecture</span>
</div>
</div>
)}
</header>
<div dir="auto" className="es-body pub-article" dangerouslySetInnerHTML={{ __html: bodyHtml }} />
<div className="es-rule-thin" style={{ marginTop: '4rem' }} />
<footer className="es-footer">
Publié sur <strong>Memento</strong>
{isStale && <p style={{ fontSize: 11, color: '#bbb', marginTop: 6 }}>Le contenu source a évolué depuis la publication.</p>}
</footer>
</main>
</div>
<style>{`
*, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }
.es-root { min-height: 100vh; background: #FDFBF7; color: #2c2416; font-family: 'Inter', sans-serif; }
.es-nav {
position: sticky; top: 0; z-index: 20;
background: rgba(253,251,247,0.9); backdrop-filter: blur(10px);
border-bottom: 1px solid #e8e0d0;
display: flex; align-items: center; justify-content: space-between;
padding: 12px 40px;
}
.es-brand { font-family: 'Lora', Georgia, serif; font-size: 16px; font-style: italic; color: #5c4a2a; }
.es-badge { display: flex; align-items: center; gap: 4px; font-size: 11px; font-weight: 500; color: #8b6c3a; font-family: 'Inter', sans-serif; }
.es-report { color: #bbb; text-decoration: none; display: flex; }
.es-report:hover { color: #666; }
.es-main { max-width: 680px; margin: 0 auto; padding: 60px 36px 100px; }
.es-rule-top { width: 60px; height: 3px; background: #5c4a2a; margin: 48px auto 0; }
.es-header { text-align: center; padding: 40px 0 36px; }
.es-date { display: block; font-size: 12px; font-weight: 500; letter-spacing: 0.15em; text-transform: uppercase; color: #a08b5c; margin-bottom: 24px; }
.es-title {
font-family: 'Lora', Georgia, serif;
font-size: clamp(28px, 5vw, 52px);
font-weight: 600; font-style: italic; line-height: 1.2;
letter-spacing: -0.01em; color: #1e160c;
margin-bottom: 32px;
}
.es-rule-thin { height: 1px; background: #d8cebc; margin: 0 auto; width: 100%; }
.es-author { display: flex; align-items: center; gap: 12px; margin-top: 24px; justify-content: center; }
.es-avatar { width: 40px; height: 40px; border-radius: 50%; border: 2px solid #d8cebc; }
.es-author-name { display: block; font-size: 14px; font-weight: 600; color: #3d2f14; }
.es-reading-time { display: block; font-size: 12px; color: #a08b5c; }
/* Essay body */
.es-body { margin-top: 52px; font-family: 'Lora', Georgia, serif; font-size: 19px; line-height: 2; color: #2c2416; }
.es-body .pub-tpl { all: unset; display: block; }
/* Epigraph avec guillemet décoratif */
.es-body .pub-epigraph {
position: relative;
text-align: center; font-size: 1.15em; font-style: italic; color: #6b5337;
margin: 0 0 3em; padding: 1.5em 2.5em 1em;
border-top: 1px solid #d8cebc; border-bottom: 1px solid #d8cebc;
}
.es-body .pub-epigraph::before {
content: '"';
position: absolute; top: -0.3em; left: 50%; transform: translateX(-50%);
font-family: 'Lora', Georgia, serif; font-size: 5em; color: #d8cebc;
line-height: 1; pointer-events: none; font-style: normal;
}
.es-body .pub-essay-summary {
font-size: 1.15em; line-height: 1.8; color: #4a3726;
margin-bottom: 2.5em; font-style: italic;
padding-left: 1.5em; border-left: 2px solid #c8b99a;
}
.es-body .pub-body-source p { text-indent: 1.8em; }
.es-body .pub-body-source p:first-of-type { text-indent: 0; }
.es-body .pub-body-source > p:first-child { text-indent: 0; }
.es-body .pub-hero { margin: 0 -36px 3em; overflow: hidden; border-radius: 0; max-height: 480px; aspect-ratio: 16/9; background: #e8e0d0; }
.es-body .pub-hero-img { width: 100%; height: 100%; object-fit: cover; display: block; filter: sepia(10%); }
.es-body h2 { font-family: 'Lora', serif; font-size: 1.45em; font-style: italic; font-weight: 600; margin-top: 2.5em; margin-bottom: 0.7em; color: #1e160c; }
.es-body h3 { font-family: 'Lora', serif; font-size: 1.2em; font-weight: 600; margin-top: 2em; margin-bottom: 0.5em; }
.es-body p { margin: 0 0 0.2em; }
.es-body blockquote {
border: none; margin: 2em 0; padding: 0 2em;
font-size: 1.15em; color: #5c4a2a; font-style: italic;
text-align: center; position: relative;
}
.es-body ul, .es-body ol { padding-left: 1.4em; margin: 1em 0; }
.es-body li { margin: 0.5em 0; }
.es-body pre { background: #f2ede4; padding: 20px; border-radius: 6px; overflow-x: auto; font-family: 'SF Mono', Menlo, monospace; font-size: 13px; margin: 1.5em 0; }
.es-body code { font-family: 'SF Mono', Menlo, monospace; font-size: 0.85em; background: #ede7da; padding: 1px 5px; border-radius: 3px; }
.es-body pre code { background: none; padding: 0; }
.es-body table { border-collapse: collapse; width: 100%; margin: 1.5em 0; }
.es-body th { border-bottom: 2px solid #5c4a2a; padding: 8px 12px; text-align: left; font-size: 14px; color: #5c4a2a; }
.es-body td { border-bottom: 1px solid #e8e0d0; padding: 8px 12px; }
.es-body a { color: #7a5c2e; text-decoration: underline; text-decoration-style: dotted; text-underline-offset: 3px; }
.es-body .pub-figure { margin: 2.5em 0; text-align: center; }
.es-body .pub-figure-img { max-width: 100%; border-radius: 2px; box-shadow: 0 6px 24px rgba(0,0,0,0.1); filter: sepia(5%); }
.es-body .pub-figure-caption { margin-top: 0.65em; font-size: 0.8em; color: #9a8470; font-style: italic; }
.es-body .pub-gallery { display: grid; grid-template-columns: repeat(auto-fit, minmax(180px, 1fr)); gap: 10px; margin-top: 2.5em; }
.es-body .pub-gallery-img { width: 100%; height: 160px; object-fit: cover; border-radius: 2px; display: block; filter: sepia(8%); }
.es-body .pub-callout { border-radius: 4px; padding: 12px 16px; margin: 1.5em 0; }
${KATEX_PUBLISH_CSS}
.es-footer { text-align: center; padding: 32px 0 0; font-size: 13px; color: #a08b5c; font-family: 'Inter', sans-serif; }
.es-footer strong { color: #5c4a2a; }
/* Variables essay pour blocs réécriture */
.es-body {
--pub-accent: #7a5c2e;
--pub-summary-color: #5c4a2a;
--pub-exercise-border: #d8cebc;
--pub-exercise-header-bg: #f5f0e8;
--pub-solution-bg: rgba(122,92,46,0.05);
--pub-definition-border: #d8cebc;
--pub-definition-bg: #fdfbf7;
--pub-toggle-border: #e2d9ca;
--pub-toggle-header-bg: #f7f3ec;
--pub-highlight-bg: #fdf6eb;
--pub-checklist-bg: rgba(0,0,0,0.025);
}
.es-body .pub-rewrite-body .pub-code { background: #2c2416; }
.es-body .pub-rewrite-body .pub-code code { background: #2c2416; color: #f0e8da; }
${REWRITE_SHARED_CSS}
`}</style>
</>
)
}
/* ─── SIMPLE (pas d'IA) ─────────────────────────────────────────────────── */
function SimplePage({ note, bodyHtml, readingTime, slug }: PageProps) {
return (
<>
{/* KaTeX + fonts CSS */}
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/katex@0.16.9/dist/katex.min.css" />
<link rel="preconnect" href="https://fonts.googleapis.com" />
<link href="https://fonts.googleapis.com/css2?family=Source+Serif+4:opsz,wght@8..60,300..600&family=Inter:wght@400;500;600&display=swap" rel="stylesheet" />
<div style={{ minHeight: '100vh', background: '#FAF9F5', color: '#1a1a1a', fontFamily: "'Inter', sans-serif" }}>
{/* Top bar */}
<div style={{
position: 'sticky', top: 0, zIndex: 10,
background: 'rgba(250,249,245,0.85)', backdropFilter: 'blur(12px)',
borderBottom: '1px solid rgba(0,0,0,0.06)', padding: '10px 24px',
display: 'flex', alignItems: 'center', justifyContent: 'space-between',
}}>
<span style={{ fontFamily: "'Source Serif 4', serif", fontWeight: 600, fontSize: '15px' }}>Momento</span>
<a href={`/p/${slug}/report`} style={{ display: 'flex', alignItems: 'center', gap: '4px', fontSize: '12px', color: '#888', textDecoration: 'none', padding: '4px 10px', borderRadius: '6px', border: '1px solid rgba(0,0,0,0.1)' }}>
<Flag size={12} /> Signaler
</a>
<div style={{ position: 'sticky', top: 0, zIndex: 10, background: 'rgba(250,249,245,0.9)', backdropFilter: 'blur(12px)', borderBottom: '1px solid rgba(0,0,0,0.06)', padding: '10px 24px', display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
<span style={{ fontFamily: "'Source Serif 4', serif", fontWeight: 600, fontSize: '15px' }}>Memento</span>
<a href={`/p/${slug}/report`} style={{ display: 'flex', alignItems: 'center', gap: '4px', fontSize: '12px', color: '#888', textDecoration: 'none', padding: '4px 10px', borderRadius: '6px', border: '1px solid rgba(0,0,0,0.1)' }}><Flag size={12} /> Signaler</a>
</div>
{/* Article */}
<article style={{ maxWidth: '720px', margin: '0 auto', padding: '48px 24px 80px' }}>
<div style={{ display: 'flex', alignItems: 'center', gap: '8px', fontSize: '12px', color: '#999', marginBottom: '16px' }}>
<Calendar size={12} />
<span>{note.publishedAt ? format(new Date(note.publishedAt), 'd MMM yyyy') : ''}</span>
<span>·</span>
<Clock size={12} />
<span>{readingTime} min de lecture</span>
<div style={{ fontSize: '12px', color: '#999', marginBottom: '16px' }}>
{note.publishedAt ? format(new Date(note.publishedAt), 'd MMM yyyy', { locale: fr }) : ''} · {readingTime} min de lecture
</div>
<h1 style={{ fontFamily: "'Source Serif 4', Georgia, serif", fontSize: 'clamp(28px,5vw,40px)', fontWeight: 600, lineHeight: 1.2, letterSpacing: '-0.02em', margin: '0 0 12px' }}>
{note.title || 'Sans titre'}
</h1>
<h1 style={{ fontFamily: "'Source Serif 4', Georgia, serif", fontSize: 'clamp(28px,5vw,40px)', fontWeight: 600, lineHeight: 1.2, letterSpacing: '-0.02em', margin: '0 0 12px' }}>{note.title || 'Sans titre'}</h1>
{note.user?.name && (
<div style={{ display: 'flex', alignItems: 'center', gap: '8px', marginBottom: '40px' }}>
<div style={{ display: 'flex', alignItems: 'center', gap: '8px', marginBottom: '36px' }}>
{note.user.image && <img src={note.user.image} alt="" style={{ width: '28px', height: '28px', borderRadius: '50%' }} />}
<span style={{ fontSize: '14px', color: '#666' }}>par {note.user.name}</span>
</div>
)}
<div style={{ height: '1px', background: 'rgba(0,0,0,0.08)', marginBottom: '40px' }} />
<div dir="auto" style={{ fontSize: '16px', lineHeight: 1.8 }} dangerouslySetInnerHTML={{ __html: sanitizeRichHtml(processedContent) }} />
<div style={{ height: '1px', background: 'rgba(0,0,0,0.08)', marginBottom: '36px' }} />
<div dir="auto" className="pub-article" dangerouslySetInnerHTML={{ __html: bodyHtml }} />
<style>{`
article h1, article h2, article h3 { font-family: 'Source Serif 4', Georgia, serif; font-weight: 600; letter-spacing: -0.01em; margin-top: 1.8em; margin-bottom: 0.6em; }
article h2 { font-size: 1.5em; }
article h3 { font-size: 1.2em; }
article p { margin: 1em 0; }
article ul, article ol { padding-left: 1.5em; margin: 1em 0; }
article li { margin: 0.4em 0; }
article blockquote { border-left: 3px solid #A47148; padding-left: 1em; margin: 1.2em 0; color: #555; font-style: italic; }
article pre { background: #f4f3ef; padding: 16px; border-radius: 8px; overflow-x: auto; font-size: 14px; margin: 1.2em 0; }
article code { font-family: 'SF Mono', Menlo, monospace; }
article table { border-collapse: collapse; width: 100%; margin: 1.2em 0; }
article th, article td { border: 1px solid #ddd; padding: 8px 12px; text-align: left; }
article th { background: #f4f3ef; font-weight: 600; }
article img { max-width: 100%; height: auto; border-radius: 8px; margin: 1em 0; }
article a { color: #A47148; text-decoration: none; }
article a:hover { text-decoration: underline; }
.r-math-display { margin: 1.5em 0; text-align: center; overflow-x: auto; }
.pub-article { font-family: 'Source Serif 4', Georgia, serif; font-size: 17px; line-height: 1.85; }
.pub-article h2, .pub-article h3 { font-weight: 600; margin-top: 1.8em; margin-bottom: 0.6em; }
.pub-article h2 { font-size: 1.4em; }
.pub-article h3 { font-size: 1.15em; }
.pub-article p { margin: 1em 0; }
.pub-article ul, .pub-article ol { padding-left: 1.5em; margin: 1em 0; }
.pub-article li { margin: 0.4em 0; }
.pub-article blockquote { border-left: 3px solid #A47148; padding-left: 1em; margin: 1.2em 0; color: #555; font-style: italic; }
.pub-article pre { background: #f4f3ef; padding: 16px; border-radius: 8px; overflow-x: auto; font-size: 14px; margin: 1.2em 0; }
.pub-article code { font-family: 'SF Mono', Menlo, monospace; font-size: 0.87em; }
.pub-article table { border-collapse: collapse; width: 100%; margin: 1.2em 0; }
.pub-article th, .pub-article td { border: 1px solid #ddd; padding: 8px 12px; text-align: left; }
.pub-article th { background: #f4f3ef; font-weight: 600; }
.pub-article a { color: #A47148; text-decoration: underline; text-underline-offset: 3px; }
.pub-article .pub-figure { margin: 2em 0; text-align: center; }
.pub-article .pub-figure-img { max-width: 100%; border-radius: 8px; box-shadow: 0 6px 24px rgba(0,0,0,0.08); }
.pub-article .pub-figure-caption { margin-top: 0.6em; font-size: 0.82em; color: #888; font-style: italic; }
.pub-article .pub-callout { border-radius: 8px; padding: 12px 16px; margin: 1em 0; }
${KATEX_PUBLISH_CSS}
`}</style>
</article>
{/* Footer */}
<footer style={{ borderTop: '1px solid rgba(0,0,0,0.08)', padding: '32px 24px', textAlign: 'center', fontSize: '13px', color: '#999' }}>
<span style={{ fontFamily: "'Source Serif 4', serif", fontWeight: 600, color: '#A47148' }}>Momento</span>
<footer style={{ borderTop: '1px solid rgba(0,0,0,0.08)', padding: '28px 24px', textAlign: 'center', fontSize: '13px', color: '#999' }}>
<span style={{ fontFamily: "'Source Serif 4', serif", fontWeight: 600, color: '#A47148' }}>Memento</span>
{' — Votre mémoire augmentée par l\'IA'}
</footer>
</div>
</>
)
}
/* ─── Types ─────────────────────────────────────────────────────────────── */
type NoteData = NonNullable<Awaited<ReturnType<typeof getPublishedNote>>>
interface PageProps {
note: NoteData
bodyHtml: string
readingTime: number
slug: string
isStale: boolean
}
/* ─── Route ──────────────────────────────────────────────────────────────── */
export default async function PublishedNotePage({ params }: { params: Promise<{ slug: string }> }) {
const { slug } = await params
const note = await getPublishedNote(slug)
if (!note) notFound()
const usesAiLayout = Boolean(note.publishedContent)
const rawHtml = usesAiLayout ? note.publishedContent! : (note.content || '')
// Toujours passer par processNoteHtmlForPublish : KaTeX + sanitisation compatible équations
const bodyHtml = processNoteHtmlForPublish(rawHtml)
const readingSource = usesAiLayout ? note.publishedContent! : (note.content || '')
const readingTime = estimateReadingTime(readingSource)
const isStale = Boolean(
note.publishedSourceHash
&& computePublishedSourceHash(note.content || '') !== note.publishedSourceHash
)
const props: PageProps = { note, bodyHtml, readingTime, slug, isStale }
if (!usesAiLayout) return <SimplePage {...props} />
if (note.publishedTemplate === 'brief') return <BriefPage {...props} />
if (note.publishedTemplate === 'essay') return <EssayPage {...props} />
return <MagazinePage {...props} />
}

View File

@@ -10,7 +10,7 @@ import { revalidatePath } from 'next/cache'
type SvgComplexity = 'simple' | 'illustrated' | 'rich'
// Palette de l'application Momento — à utiliser dans TOUS les SVGs
// Palette de l'application Memento — à utiliser dans TOUS les SVGs
const APP_PALETTE = `
APP COLOR PALETTE (use ONLY these colors — no other palettes):
- Background warm beige: #F2F0E9

View File

@@ -71,6 +71,9 @@ export async function getPublishedNote(slug: string) {
id: true,
title: true,
content: true,
publishedContent: true,
publishedTemplate: true,
publishedSourceHash: true,
publishedAt: true,
createdAt: true,
updatedAt: true,

View File

@@ -39,7 +39,7 @@ export interface ExecuteResult {
/**
* Analyze a notebook's notes with AI and suggest a sub-notebook organization plan.
*/
export async function analyzeNotebookForOrganization(notebookId: string): Promise<AnalyzeResult> {
export async function analyzeNotebookForOrganization(notebookId: string, language?: string): Promise<AnalyzeResult> {
const session = await auth()
if (!session?.user?.id) return { success: false, error: 'Non autorisé' }
@@ -94,6 +94,9 @@ export async function analyzeNotebookForOrganization(notebookId: string): Promis
? `\nSous-carnets existants:\n${existingSubs.map(s => `- "${s.name}" (id: ${s.id})`).join('\n')}`
: '\nIl n\'y a pas encore de sous-carnets.'
const lang = language || 'fr'
const langName = lang === 'fr' ? 'français' : lang === 'en' ? 'English' : lang === 'fa' ? 'فارسی' : lang === 'ar' ? 'العربية' : lang === 'de' ? 'Deutsch' : lang === 'es' ? 'Español' : lang === 'it' ? 'Italiano' : lang === 'pt' ? 'Português' : lang === 'ru' ? 'Русский' : lang === 'zh' ? '中文' : lang === 'ja' ? '日本語' : lang === 'ko' ? '한국어' : lang === 'nl' ? 'Nederlands' : lang === 'pl' ? 'Polski' : lang === 'hi' ? 'हिन्दी' : lang
const prompt = `Tu es un assistant d'organisation de notes. Analyse les notes suivantes du carnet "${notebook.name}" et regroupe-les par thème en proposant des sous-carnets.
${existingSubsContext}
@@ -104,7 +107,7 @@ RÈGLES IMPORTANTES:
- Regroupe les notes par thème ou sujet similaire.
- Propose entre 2 et 6 groupes maximum.
- Si un sous-carnet existant correspond déjà à un thème, utilise-le (indique son id).
- Les noms de groupe doivent être courts (2-4 mots), clairs et en français.
- Les noms de groupe doivent être courts (2-4 mots), clairs et EN ${langName.toUpperCase()}.
- N'inclus PAS toutes les notes si certaines sont trop générales ou ne correspondent à aucun groupe clair — laisse-les de côté.
- Réponds UNIQUEMENT avec du JSON valide, sans markdown, sans explication.

View File

@@ -43,7 +43,7 @@ export async function DELETE(request: NextRequest) {
where: { id: noteId },
select: { userId: true, publicSlug: true },
})
if (note) {
if (note && note.userId) {
await prisma.notification.create({
data: {
userId: note.userId,

View File

@@ -4,6 +4,7 @@ import prisma from '@/lib/prisma'
import { exerciseGeneratorService } from '@/lib/ai/services/exercise-generator.service'
import { reserveUsageOrThrow, QuotaExceededError } from '@/lib/entitlements'
import { preprocessMathInHtml } from '@/lib/text/math-preprocess'
import { hasUserAiConsent, aiConsentForbiddenResponse } from '@/lib/consent/server-consent'
export async function POST(request: NextRequest) {
try {
@@ -17,6 +18,8 @@ export async function POST(request: NextRequest) {
return NextResponse.json({ error: 'noteId is required' }, { status: 400 })
}
if (!(await hasUserAiConsent())) return aiConsentForbiddenResponse()
try {
await reserveUsageOrThrow(session.user.id, 'reformulate')
} catch (err) {
@@ -47,19 +50,27 @@ export async function POST(request: NextRequest) {
// Create exercise notes in the same notebook
const lang = language || 'fr'
const exerciseLabel = lang === 'fr' ? 'Exercice' : lang === 'fa' ? 'تمرین' : 'Exercise'
const answerLabel = lang === 'fr' ? 'Corrigé' : lang === 'fa' ? 'پاسخ' : 'Answer'
const exerciseLabel = lang === 'fr' ? 'Exercice' : lang === 'fa' ? 'تمرین' : lang === 'ar' ? 'تمرين' : lang === 'de' ? 'Übung' : lang === 'es' ? 'Ejercicio' : lang === 'it' ? 'Esercizio' : lang === 'pt' ? 'Exercício' : lang === 'ru' ? 'Упражнение' : lang === 'zh' ? '练习' : lang === 'ja' ? '練習' : lang === 'ko' ? '연습' : lang === 'nl' ? 'Oefening' : lang === 'pl' ? 'Ćwiczenie' : lang === 'hi' ? 'अभ्यास' : 'Exercise'
const answerLabel = lang === 'fr' ? 'Corrigé' : lang === 'fa' ? 'پاسخ' : lang === 'ar' ? 'الحل' : lang === 'de' ? 'Lösung' : lang === 'es' ? 'Solución' : lang === 'it' ? 'Soluzione' : lang === 'pt' ? 'Solução' : lang === 'ru' ? 'Решение' : lang === 'zh' ? '解答' : lang === 'ja' ? '解答' : lang === 'ko' ? '해답' : lang === 'nl' ? 'Oplossing' : lang === 'pl' ? 'Rozwiązanie' : lang === 'hi' ? 'हल' : 'Solution'
const statementLabel = lang === 'fr' ? 'Énoncé' : lang === 'fa' ? 'صورت مسئله' : lang === 'ar' ? 'السؤال' : lang === 'de' ? 'Aufgabe' : lang === 'es' ? 'Enunciado' : lang === 'it' ? 'Testo' : lang === 'pt' ? 'Enunciado' : lang === 'ru' ? 'Задание' : lang === 'zh' ? '题目' : lang === 'ja' ? '問題' : lang === 'ko' ? '문제' : lang === 'nl' ? 'Opgave' : lang === 'pl' ? 'Zadanie' : lang === 'hi' ? 'प्रश्न' : 'Statement'
const revealLabel = lang === 'fr' ? 'cliquer pour révéler' : lang === 'fa' ? 'برای نمایش کلیک کنید' : lang === 'ar' ? 'انقر للكشف' : lang === 'de' ? 'zum Anzeigen klicken' : lang === 'es' ? 'haz clic para ver' : lang === 'it' ? 'clicca per rivelare' : lang === 'pt' ? 'clique para revelar' : lang === 'ru' ? 'нажмите, чтобы открыть' : lang === 'zh' ? '点击查看' : lang === 'ja' ? 'クリックして表示' : lang === 'ko' ? '클릭하여 보기' : lang === 'nl' ? 'klik om te onthullen' : lang === 'pl' ? 'kliknij, aby zobaczyć' : lang === 'hi' ? 'देखने के लिए क्लिक करें' : 'click to reveal'
const difficultyMap: Record<string, Record<string, string>> = {
facile: { fr: 'facile', en: 'easy', fa: 'آسان', ar: 'سهل', de: 'einfach', es: 'fácil', it: 'facile', pt: 'fácil', ru: 'лёгкий', zh: '简单', ja: '易しい', ko: '쉬움', nl: 'makkelijk', pl: 'łatwy', hi: 'आसान' },
moyen: { fr: 'moyen', en: 'medium', fa: 'متوسط', ar: 'متوسط', de: 'mittel', es: 'medio', it: 'medio', pt: 'médio', ru: 'средний', zh: '中等', ja: '普通', ko: '보통', nl: 'gemiddeld', pl: 'średni', hi: 'मध्यम' },
difficile: { fr: 'difficile', en: 'hard', fa: 'دشوار', ar: 'صعب', de: 'schwer', es: 'difícil', it: 'difficile', pt: 'difícil', ru: 'сложный', zh: '困难', ja: '難しい', ko: '어려움', nl: 'moeilijk', pl: 'trudny', hi: 'कठिन' },
}
const createdNotes = []
for (let i = 0; i < exercises.length; i++) {
const ex = exercises[i]
const difficultyEmoji = ex.difficulty === 'facile' ? '🟢' : ex.difficulty === 'moyen' ? '🟡' : '🔴'
const difficultyLocalized = (difficultyMap[ex.difficulty]?.[lang]) || ex.difficulty
const rawContent = `
<div data-type="callout-block" data-callout-type="warning"><p><strong>${exerciseLabel} ${i + 1}</strong> — ${difficultyEmoji} ${ex.difficulty}</p></div>
<h2>Énoncé</h2>
<div data-type="callout-block" data-callout-type="warning"><p><strong>${exerciseLabel} ${i + 1}</strong> — ${difficultyEmoji} ${difficultyLocalized}</p></div>
<h2>${statementLabel}</h2>
<p>${ex.question}</p>
<div data-type="toggle-block" data-opened="false"><p><strong>${answerLabel}</strong> — cliquer pour révéler</p><h3>Solution</h3><p>${ex.answer}</p></div>
<div data-type="toggle-block" data-opened="false"><p><strong>${answerLabel}</strong> — ${revealLabel}</p><h3>${answerLabel}</h3><p>${ex.answer}</p></div>
`.trim()
const content = preprocessMathInHtml(rawContent)

View File

@@ -0,0 +1,77 @@
import { NextRequest, NextResponse } from 'next/server'
import { auth } from '@/auth'
import prisma from '@/lib/prisma'
import { notebookPublishAnalyzerService } from '@/lib/ai/services/notebook-publish-analyzer.service'
import { reserveUsageOrThrow, QuotaExceededError } from '@/lib/entitlements'
import { hasUserAiConsent, aiConsentForbiddenResponse } from '@/lib/consent/server-consent'
export async function POST(request: NextRequest) {
try {
const session = await auth()
if (!session?.user?.id) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
}
const { notebookId, language } = await request.json()
if (!notebookId) {
return NextResponse.json({ error: 'notebookId is required' }, { status: 400 })
}
if (!(await hasUserAiConsent())) return aiConsentForbiddenResponse()
try {
await reserveUsageOrThrow(session.user.id, 'publish_enhance')
} catch (err) {
if (err instanceof QuotaExceededError) {
const isTierLocked = err.currentQuota === 0
return NextResponse.json(
{ error: isTierLocked ? 'feature_locked' : 'quota_exceeded', errorKey: isTierLocked ? 'ai.featureLocked' : 'ai.quotaExceeded' },
{ status: 402 },
)
}
throw err
}
const notebook = await prisma.notebook.findFirst({
where: { id: notebookId, userId: session.user.id, trashedAt: null },
select: { id: true, name: true },
})
if (!notebook) return NextResponse.json({ error: 'Notebook not found' }, { status: 404 })
const notes = await prisma.note.findMany({
where: { notebookId, userId: session.user.id, trashedAt: null, isArchived: false },
select: { id: true, title: true, content: true },
orderBy: { order: 'asc' },
})
if (notes.length === 0) {
return NextResponse.json({ error: 'No notes found' }, { status: 400 })
}
const notesForService = notes.map(n => {
const stripped = (n.content || '').replace(/<[^>]+>/g, ' ').replace(/\s+/g, ' ').trim()
const wordCount = stripped.split(' ').filter(Boolean).length
return {
id: n.id,
title: n.title || '',
wordCount,
preview: stripped.slice(0, 200),
}
})
const analysis = await notebookPublishAnalyzerService.analyze(
notebook.name,
notesForService,
language || 'fr',
)
return NextResponse.json({
notes: analysis.notes,
description: analysis.description,
noteTitles: Object.fromEntries(notes.map(n => [n.id, n.title || ''])),
})
} catch (error: any) {
console.error('[notebook-publish/analyze] Error:', error)
return NextResponse.json({ error: error.message || 'Failed to analyze' }, { status: 500 })
}
}

View File

@@ -3,6 +3,7 @@ import { auth } from '@/auth'
import prisma from '@/lib/prisma'
import { notebookWizardService, type WizardProfile } from '@/lib/ai/services/notebook-wizard.service'
import { reserveUsageOrThrow, QuotaExceededError } from '@/lib/entitlements'
import { hasUserAiConsent, aiConsentForbiddenResponse } from '@/lib/consent/server-consent'
export async function POST(request: NextRequest) {
try {
@@ -17,6 +18,8 @@ export async function POST(request: NextRequest) {
return NextResponse.json({ error: 'Profile and topic are required' }, { status: 400 })
}
if (!(await hasUserAiConsent())) return aiConsentForbiddenResponse()
try {
await reserveUsageOrThrow(session.user.id, 'reformulate')
} catch (err) {

View File

@@ -3,6 +3,7 @@ import { auth } from '@/auth'
import prisma from '@/lib/prisma'
import { studyPlannerService } from '@/lib/ai/services/study-planner.service'
import { reserveUsageOrThrow, QuotaExceededError } from '@/lib/entitlements'
import { hasUserAiConsent, aiConsentForbiddenResponse } from '@/lib/consent/server-consent'
export async function POST(request: NextRequest) {
try {
@@ -16,6 +17,8 @@ export async function POST(request: NextRequest) {
return NextResponse.json({ error: 'notebookId and examDate are required' }, { status: 400 })
}
if (!(await hasUserAiConsent())) return aiConsentForbiddenResponse()
try {
await reserveUsageOrThrow(session.user.id, 'reformulate')
} catch (err) {
@@ -41,15 +44,18 @@ export async function POST(request: NextRequest) {
const userLang = await prisma.user.findUnique({
where: { id: session.user.id },
select: { theme: true },
select: { language: true },
})
const notesForService = notes.map(n => ({ id: n.id, title: n.title ?? '' }))
const plan = await studyPlannerService.generate(notesForService, examDate)
const plan = await studyPlannerService.generate(notesForService, examDate, userLang?.language || 'fr')
// Set reminders on notes based on the plan
// Set the first occurrence reminder for each note (subsequent occurrences ignored)
const seenNoteIds = new Set<string>()
for (const day of plan.days) {
for (const noteId of day.noteIds) {
if (seenNoteIds.has(noteId)) continue
seenNoteIds.add(noteId)
try {
const reminderDate = new Date(day.date)
reminderDate.setHours(9, 0, 0, 0)

View File

@@ -277,10 +277,10 @@ Fais un résumé concis (max 200 mots) de cette conversation. Garde les informat
- Natural tone, neither corporate nor too casual.
- No unnecessary intro phrases. Answer directly.
- No upsell questions at the end. If you have useful additional info, just give it.
- If the user says "Momento" they mean Momento (this app).
- If the user says "Memento" they mean Memento (this app).
## About Momento
Momento is an intelligent note-taking application. Key features include:
## About Memento
Memento is an intelligent note-taking application. Key features include:
- **Notes & Editor**: Create rich Markdown notes with an integrated AI Copilot to rewrite, summarize, or translate content.
- **Organization**: Group notes into Notebooks and tag them with Labels.
- **Search**: Advanced semantic search to find notes by meaning, not just keywords, and Web Search integration.
@@ -336,10 +336,10 @@ Available types: bar, horizontal-bar, line, area, pie, radar. NEVER use Mermaid
## Règles de ton
- Ton naturel, direct, sans phrases d'intro inutiles.
- Pas de question upsell à la fin.
- Si l'utilisateur dit "Momento" il parle de Momento (cette application).
- Si l'utilisateur dit "Memento" il parle de Memento (cette application).
## À propos de Momento
Momento est une application de prise de notes intelligente. Ses fonctionnalités : Éditeur Markdown riche, Copilot IA, Organisation par Carnets, Recherche sémantique, Agents IA, Lab.
## À propos de Memento
Memento est une application de prise de notes intelligente. Ses fonctionnalités : Éditeur Markdown riche, Copilot IA, Organisation par Carnets, Recherche sémantique, Agents IA, Lab.
## Outils disponibles
Tu as accès à : note_search, note_read, note_find_and_update, document_search, task_extract, web_search, web_scrape, insert_chart.
@@ -387,7 +387,7 @@ Types disponibles : bar, horizontal-bar, line, area, pie, radar. JAMAIS utiliser
## قوانین لحن
- لحن طبیعی، مستقیم، بدون مقدمه اضافی.
- اگر کاربر "Momento" می‌گوید، منظورش Memento (این برنامه) است.`,
- اگر کاربر "Memento" می‌گوید، منظورش Memento (این برنامه) است.`,
},
es: {
contextWithNotes: `## Notas del usuario\n\n${contextNotes}\n\nCuando uses información de las notas anteriores, cita el título de la nota fuente entre paréntesis.`,

View File

@@ -1,6 +1,6 @@
/**
* POST /api/integrations/readwise/sync
* Syncs Readwise highlights into Momento notes.
* Syncs Readwise highlights into Memento notes.
* Each book/article becomes a note with all its highlights listed.
*
* Query params:

View File

@@ -0,0 +1,116 @@
import { NextRequest, NextResponse } from 'next/server'
import { auth } from '@/auth'
import prisma from '@/lib/prisma'
export async function GET(
_request: NextRequest,
{ params }: { params: Promise<{ id: string }> },
) {
try {
const session = await auth()
if (!session?.user?.id) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
const { id: notebookId } = await params
const site = await prisma.notebookSite.findUnique({
where: { notebookId },
select: { slug: true, isPublic: true, publishedAt: true, template: true, selectedNoteIds: true },
})
return NextResponse.json({ site: site || null })
} catch (error: any) {
return NextResponse.json({ error: error.message }, { status: 500 })
}
}
function toSlug(str: string): string {
return str
.toLowerCase()
.normalize('NFD').replace(/[\u0300-\u036f]/g, '')
.replace(/[^a-z0-9\s-]/g, '')
.trim()
.replace(/\s+/g, '-')
.replace(/-+/g, '-')
.slice(0, 40)
}
function generateNotebookSlug(name: string): string {
const base = toSlug(name) || 'carnet'
const suffix = Math.random().toString(36).slice(2, 7)
return `${base}-${suffix}`
}
export async function POST(
request: NextRequest,
{ params }: { params: Promise<{ id: string }> },
) {
try {
const session = await auth()
if (!session?.user?.id) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
}
const { id: notebookId } = await params
const { selectedNoteIds, template, description } = await request.json()
if (!selectedNoteIds || !Array.isArray(selectedNoteIds) || selectedNoteIds.length === 0) {
return NextResponse.json({ error: 'selectedNoteIds is required' }, { status: 400 })
}
const notebook = await prisma.notebook.findFirst({
where: { id: notebookId, userId: session.user.id, trashedAt: null },
select: { id: true, name: true, site: { select: { slug: true } } },
})
if (!notebook) return NextResponse.json({ error: 'Notebook not found' }, { status: 404 })
// Reuse existing slug or generate a new one
const slug = notebook.site?.slug || generateNotebookSlug(notebook.name)
const site = await prisma.notebookSite.upsert({
where: { notebookId },
create: {
notebookId,
slug,
isPublic: true,
template: template || 'magazine',
selectedNoteIds: JSON.stringify(selectedNoteIds),
description: description || null,
},
update: {
isPublic: true,
template: template || 'magazine',
selectedNoteIds: JSON.stringify(selectedNoteIds),
description: description || null,
updatedAt: new Date(),
},
})
return NextResponse.json({ slug: site.slug, url: `/c/${site.slug}` })
} catch (error: any) {
console.error('[notebooks/publish] Error:', error)
return NextResponse.json({ error: error.message || 'Failed to publish' }, { status: 500 })
}
}
export async function DELETE(
_request: NextRequest,
{ params }: { params: Promise<{ id: string }> },
) {
try {
const session = await auth()
if (!session?.user?.id) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
}
const { id: notebookId } = await params
const notebook = await prisma.notebook.findFirst({
where: { id: notebookId, userId: session.user.id },
select: { id: true },
})
if (!notebook) return NextResponse.json({ error: 'Not found' }, { status: 404 })
await prisma.notebookSite.deleteMany({ where: { notebookId } })
return NextResponse.json({ success: true })
} catch (error: any) {
return NextResponse.json({ error: error.message }, { status: 500 })
}
}

View File

@@ -1,7 +1,31 @@
import { NextRequest, NextResponse } from 'next/server'
import { auth } from '@/auth'
import prisma from '@/lib/prisma'
import { contentModerationService } from '@/lib/ai/services/content-moderation.service'
import { contentModerationService, type ModerationResult } from '@/lib/ai/services/content-moderation.service'
import { publishEnhanceService } from '@/lib/ai/services/publish-enhance.service'
import { reserveUsageOrThrow, QuotaExceededError } from '@/lib/entitlements'
import { hasUserAiConsent } from '@/lib/consent/server-consent'
import { isPublishTemplateId } from '@/lib/publish/types'
import { computePublishedSourceHash, renderPublishedTemplate, renderRewrittenTemplate } from '@/lib/publish/template-render'
const MODERATION_TIMEOUT_MS = 12_000
async function moderateWithFallback(title: string, content: string): Promise<ModerationResult> {
try {
return await Promise.race([
contentModerationService.moderate(title, content),
new Promise<ModerationResult>((resolve) => {
setTimeout(() => resolve({
verdict: 'safe',
categories: ['safe'],
reason: 'Moderation timeout',
}), MODERATION_TIMEOUT_MS)
}),
])
} catch {
return { verdict: 'safe', categories: ['safe'], reason: 'Moderation indisponible' }
}
}
function generateSlug(title: string): string {
const base = title
@@ -14,11 +38,70 @@ function generateSlug(title: string): string {
return `${base}-${Math.random().toString(36).slice(2, 8)}`
}
async function ensureSlug(noteId: string, title: string, existingSlug: string | null): Promise<string> {
let slug = existingSlug
if (!slug) {
slug = generateSlug(title || 'note')
const existing = await prisma.note.findUnique({ where: { publicSlug: slug } })
if (existing && existing.id !== noteId) slug = `${slug}-${Date.now().toString(36)}`
}
return slug
}
async function notifyFlaggedAdmins(noteId: string, title: string, reason: string) {
const admins = await prisma.user.findMany({ where: { role: 'ADMIN' }, select: { id: true } })
for (const admin of admins) {
await prisma.notification.create({
data: {
userId: admin.id,
type: 'content_flagged',
title: 'Contenu sensible publié',
message: `La note "${title}" a été publiée avec un contenu potentiellement sensible: ${reason}`,
actionUrl: '/admin/published',
relatedId: noteId,
},
}).catch(() => {})
}
}
type PublishUpdateData = {
isPublic: boolean
publicSlug: string | null
publishedAt: Date | null
publishedContent?: string | null
publishedTemplate?: string | null
publishedSourceHash?: string | null
}
/** Tolerates stale Prisma client during dev (before server restart). */
async function updateNotePublishState(noteId: string, data: PublishUpdateData) {
try {
await prisma.note.update({ where: { id: noteId }, data })
} catch (err) {
const msg = err instanceof Error ? err.message : String(err)
if (msg.includes('publishedContent') || msg.includes('Unknown argument')) {
const { publishedContent, publishedTemplate, publishedSourceHash, ...core } = data
await prisma.note.update({ where: { id: noteId }, data: core })
return
}
throw err
}
}
export async function POST(request: NextRequest) {
const session = await auth()
if (!session?.user?.id) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
const { noteId, action } = await request.json()
const body = await request.json()
const { noteId, action, mode, template, language, rewrite } = body as {
noteId?: string
action?: string
mode?: 'simple' | 'ai'
template?: string
language?: string
rewrite?: boolean
}
if (!noteId) return NextResponse.json({ error: 'noteId required' }, { status: 400 })
const note = await prisma.note.findFirst({
@@ -28,14 +111,96 @@ export async function POST(request: NextRequest) {
if (!note) return NextResponse.json({ error: 'Not found' }, { status: 404 })
if (action === 'publish') {
// --- AI Moderation ---
let moderation
try {
moderation = await contentModerationService.moderate(note.title || '', note.content || '')
} catch {
moderation = { verdict: 'safe' as const, categories: ['safe'], reason: 'Moderation indisponible' }
const publishMode = mode === 'ai' ? 'ai' : 'simple'
if (publishMode === 'ai') {
if (!(await hasUserAiConsent())) {
return NextResponse.json({ error: 'ai_consent_required' }, { status: 403 })
}
if (!template || !isPublishTemplateId(template)) {
return NextResponse.json({ error: 'Invalid template' }, { status: 400 })
}
try {
await reserveUsageOrThrow(session.user.id, 'publish_enhance')
} catch (err) {
if (err instanceof QuotaExceededError) {
const isTierLocked = err.currentQuota === 0
return NextResponse.json(
{
error: isTierLocked ? 'feature_locked' : 'quota_exceeded',
errorKey: isTierLocked ? 'ai.featureLocked' : 'ai.quotaExceeded',
upgradeTier: err.upgradeTier,
},
{ status: 402 },
)
}
throw err
}
let renderedHtml: string
let textForModeration: string
try {
if (rewrite) {
const spec = await publishEnhanceService.rewrite(
note.title || '',
note.content || '',
template,
language || 'fr',
)
renderedHtml = renderRewrittenTemplate(spec, template, note.content || '')
textForModeration = `${spec.summary}\n${spec.body.replace(/<[^>]+>/g, ' ')}`
} else {
const spec = await publishEnhanceService.enhance(
note.title || '',
note.content || '',
template,
language || 'fr',
)
renderedHtml = renderPublishedTemplate(spec, template, note.content || '')
textForModeration = [spec.summary, spec.pullQuote, spec.epigraph, ...(spec.keyPoints || [])].join('\n')
}
} catch (err) {
console.error('[publish] AI generation failed:', err)
return NextResponse.json({ error: 'ai_generation_failed' }, { status: 500 })
}
const moderation = await moderateWithFallback(note.title || '', textForModeration)
if (moderation.verdict === 'blocked') {
return NextResponse.json({
error: 'blocked',
reason: moderation.reason,
categories: moderation.categories,
}, { status: 403 })
}
if (moderation.verdict === 'flagged') {
await notifyFlaggedAdmins(note.id, note.title || '', moderation.reason)
}
const slug = await ensureSlug(note.id, note.title || '', note.publicSlug)
const sourceHash = computePublishedSourceHash(note.content || '')
await updateNotePublishState(noteId, {
isPublic: true,
publicSlug: slug,
publishedAt: new Date(),
publishedContent: renderedHtml,
publishedTemplate: template,
publishedSourceHash: sourceHash,
})
return NextResponse.json({
success: true,
slug,
mode: 'ai',
template,
moderation: moderation.verdict === 'flagged' ? 'flagged' : undefined,
})
}
// Simple publish — contenu brut de la note
const moderation = await moderateWithFallback(note.title || '', note.content || '')
if (moderation.verdict === 'blocked') {
return NextResponse.json({
error: 'blocked',
@@ -43,46 +208,36 @@ export async function POST(request: NextRequest) {
categories: moderation.categories,
}, { status: 403 })
}
// flagged → publish but notify admins
if (moderation.verdict === 'flagged') {
const admins = await prisma.user.findMany({ where: { role: 'ADMIN' }, select: { id: true } })
for (const admin of admins) {
await prisma.notification.create({
data: {
userId: admin.id,
type: 'content_flagged',
title: 'Contenu sensible publié',
message: `La note "${note.title}" a été publiée avec un contenu potentiellement sensible: ${moderation.reason}`,
actionUrl: '/admin/published',
relatedId: note.id,
},
}).catch(() => {})
}
await notifyFlaggedAdmins(note.id, note.title || '', moderation.reason)
}
let slug = note.publicSlug
if (!slug) {
slug = generateSlug(note.title || 'note')
const existing = await prisma.note.findUnique({ where: { publicSlug: slug } })
if (existing && existing.id !== noteId) slug = `${slug}-${Date.now().toString(36)}`
}
await prisma.note.update({
where: { id: noteId },
data: { isPublic: true, publicSlug: slug, publishedAt: new Date() },
const slug = await ensureSlug(note.id, note.title || '', note.publicSlug)
await updateNotePublishState(noteId, {
isPublic: true,
publicSlug: slug,
publishedAt: new Date(),
publishedContent: null,
publishedTemplate: null,
publishedSourceHash: null,
})
return NextResponse.json({
success: true,
slug,
mode: 'simple',
moderation: moderation.verdict === 'flagged' ? 'flagged' : undefined,
})
}
if (action === 'unpublish') {
await prisma.note.update({
where: { id: noteId },
data: { isPublic: false, publicSlug: null, publishedAt: null },
await updateNotePublishState(noteId, {
isPublic: false,
publicSlug: null,
publishedAt: null,
publishedContent: null,
publishedTemplate: null,
publishedSourceHash: null,
})
return NextResponse.json({ success: true })
}

View File

@@ -47,7 +47,7 @@ const DEMO_NOTES: Record<string, DemoNote[]> = {
<li><strong>Designing Data-Intensive Applications</strong> — Martin Kleppmann · Architecture systèmes</li>
<li><strong>The Pragmatic Programmer</strong> — Hunt & Thomas · Bonnes pratiques développement</li>
</ul>
<p>Prochaine lecture : Building a Second Brain (lien avec Momento évident).</p>`,
<p>Prochaine lecture : Building a Second Brain (lien avec Memento évident).</p>`,
},
{
title: 'Notes de formation React — Hooks avancés',
@@ -132,7 +132,7 @@ const DEMO_NOTES: Record<string, DemoNote[]> = {
<li><strong>Designing Data-Intensive Applications</strong> — Martin Kleppmann · Systems architecture</li>
<li><strong>The Pragmatic Programmer</strong> — Hunt & Thomas · Development best practices</li>
</ul>
<p>Next read: Building a Second Brain (obvious connection to Momento).</p>`,
<p>Next read: Building a Second Brain (obvious connection to Memento).</p>`,
},
{
title: 'React Training Notes — Advanced Hooks',

View File

@@ -375,7 +375,7 @@ export async function GET() {
<body>
<div id="sidebar">
<div id="sidebar-header">
<h1>Momento</h1>
<h1>Memento</h1>
<p>Offline Workspace Export</p>
</div>
<div id="search-bar">