Skip to content

Commit efa2136

Browse files
Rich text/Markdown viewer + in-app editor for text files
Viewing a text-like file now renders properly instead of a flat <pre>: - Markdown (.md/.markdown/.mdx) is rendered with GFM (tables, task lists, etc.) and syntax-highlighted code fences, with a Preview/Source toggle. Styled via a new .md-prose stylesheet + highlight.js github-dark theme. - Code/text files are syntax-highlighted (highlight.js, language inferred from extension, auto-detect fallback), capped at 200 KB for responsiveness. - An Edit button opens an in-app editor (monospace textarea) with Save: server files re-uploaded under the same name (kept as a new version); ZK vault files re-encrypted client-side and replaced in place via a new PUT /zk/files/:id endpoint (same id, quota adjusted by the size delta). New component TextDocument; ViewerSource gains onSave; api.upload takes a method for PUT; fileType gains isMarkdown/codeLanguage/isEditableText. FR/EN keys added (332 per language, parallel). Deps: react-markdown, remark-gfm, rehype-highlight, highlight.js. Test: ZK in-place replace keeps the id and tracks the quota delta. 44 tests pass; web build green.
1 parent 7f1455b commit efa2136

11 files changed

Lines changed: 1330 additions & 16 deletions

File tree

‎apps/api/src/routes/zk.ts‎

Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -142,6 +142,69 @@ export const zkRoutes: FastifyPluginAsync = async (app) => {
142142
}
143143
});
144144

145+
// PUT /zk/files/:id — replace a vault file's contents in place (in-app editor save).
146+
// Same multipart shape as upload, minus folderId; keeps the same file id and re-points it at
147+
// the new ciphertext, adjusting quota by the size delta.
148+
app.put('/files/:id', async (req, reply) => {
149+
const { id } = req.params as { id: string };
150+
const existing = await prisma.fileObject.findFirst({
151+
where: { id, ownerId: req.user!.id, encMode: 'ZK', deletedAt: null },
152+
});
153+
if (!existing) return reply.code(404).send({ error: 'File not found' });
154+
155+
const data = await req.file();
156+
if (!data) return reply.code(400).send({ error: 'No file provided' });
157+
const metaRaw = (data.fields?.meta as { value?: string } | undefined)?.value;
158+
let meta: { encryptedName?: unknown; iv?: unknown; wrappedKey?: unknown };
159+
try {
160+
meta = JSON.parse(metaRaw ?? '');
161+
} catch {
162+
data.file.resume();
163+
return reply.code(400).send({ error: 'Invalid meta JSON' });
164+
}
165+
if (typeof meta.encryptedName !== 'string' || typeof meta.iv !== 'string' || typeof meta.wrappedKey !== 'string') {
166+
data.file.resume();
167+
return reply.code(400).send({ error: 'Invalid ZK metadata' });
168+
}
169+
170+
// Replacing frees the old blob, so the new one may be up to (remaining + old size).
171+
const allowance = (await remainingAllowance(req.user!.id)) + Number(existing.sizeBytes);
172+
if (allowance <= 0) {
173+
data.file.resume();
174+
return reply.code(413).send({ error: 'Storage quota exhausted' });
175+
}
176+
177+
const newKey = newStorageKey();
178+
try {
179+
const { bytesWritten } = await app.ctx.storage.write(newKey, capStream(data.file, allowance));
180+
if (bytesWritten === 0) {
181+
await app.ctx.storage.delete(newKey).catch(() => {});
182+
return reply.code(400).send({ error: 'Empty file' });
183+
}
184+
const oldKey = existing.storageKey;
185+
await prisma.fileObject.update({
186+
where: { id },
187+
data: {
188+
storageKey: newKey,
189+
sizeBytes: BigInt(bytesWritten),
190+
zkEncryptedName: meta.encryptedName,
191+
zkIv: meta.iv,
192+
zkWrappedKey: meta.wrappedKey,
193+
},
194+
});
195+
await app.ctx.storage.delete(oldKey).catch(() => {});
196+
await adjustUsage(req.user!.id, bytesWritten - Number(existing.sizeBytes));
197+
await audit(req, 'zk.update', { target: id });
198+
return { ok: true };
199+
} catch (err) {
200+
await app.ctx.storage.delete(newKey).catch(() => {});
201+
if (err instanceof FileTooLargeError) {
202+
return reply.code(413).send({ error: 'Upload exceeds your available quota' });
203+
}
204+
throw err;
205+
}
206+
});
207+
145208
// GET /zk/files/:id/blob — stream the raw ciphertext for client-side decryption.
146209
app.get('/files/:id/blob', async (req, reply) => {
147210
const { id } = req.params as { id: string };

‎apps/api/test/integration.test.ts‎

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -283,6 +283,37 @@ runIf('API integration', () => {
283283
expect(Buffer.from(blob.rawPayload).equals(cipher)).toBe(true); // byte-for-byte round-trip
284284
});
285285

286+
it('replaces a ZK file in place (editor save) keeping the same id', async () => {
287+
const user = await createUser({ email: 'zked@test.local', password: 'correct-horse-battery' });
288+
const auth = await login(app, 'zked@test.local', 'correct-horse-battery');
289+
const vault = await app.inject({ method: 'POST', url: '/folders', headers: authHeaders(auth), payload: { name: 'vault', isZeroKnowledge: true } });
290+
const folderId = vault.json().folder.id as string;
291+
292+
const first = new FormData();
293+
first.append('meta', JSON.stringify({ folderId, encryptedName: 'a.b', iv: 'aXY=', wrappedKey: 'aXY=.d3I=', encMode: 'ZK' }));
294+
first.append('file', Buffer.from('short'), { filename: 'blob', contentType: 'application/octet-stream' });
295+
const up = await app.inject({ method: 'POST', url: '/zk/files', payload: first.getBuffer(), headers: { ...first.getHeaders(), ...authHeaders(auth) } });
296+
const id = up.json().id as string;
297+
const before = await prisma.user.findUniqueOrThrow({ where: { id: user.id } });
298+
expect(Number(before.usedBytes)).toBe(5);
299+
300+
const longer = Buffer.from('a much longer ciphertext payload');
301+
const put = new FormData();
302+
put.append('meta', JSON.stringify({ encryptedName: 'c.d', iv: 'enc=', wrappedKey: 'enc=.W=' }));
303+
put.append('file', longer, { filename: 'blob', contentType: 'application/octet-stream' });
304+
const res = await app.inject({ method: 'PUT', url: `/zk/files/${id}`, payload: put.getBuffer(), headers: { ...put.getHeaders(), ...authHeaders(auth) } });
305+
expect(res.statusCode).toBe(200);
306+
307+
const list = await app.inject({ method: 'GET', url: `/zk/files?folderId=${folderId}`, headers: { cookie: auth.cookie } });
308+
expect(list.json().files).toHaveLength(1); // still one file, same id
309+
expect(list.json().files[0].id).toBe(id);
310+
expect(list.json().files[0].iv).toBe('enc='); // metadata updated
311+
const blob = await app.inject({ method: 'GET', url: `/zk/files/${id}/blob`, headers: { cookie: auth.cookie } });
312+
expect(Buffer.from(blob.rawPayload).equals(longer)).toBe(true);
313+
const after = await prisma.user.findUniqueOrThrow({ where: { id: user.id } });
314+
expect(Number(after.usedBytes)).toBe(longer.length); // quota tracks the delta
315+
});
316+
286317
it('rejects a ZK upload that exceeds the quota', async () => {
287318
await createUser({ email: 'zkq@test.local', password: 'correct-horse-battery', quotaBytes: 8n });
288319
const auth = await login(app, 'zkq@test.local', 'correct-horse-battery');

‎apps/web/package.json‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,11 +13,15 @@
1313
},
1414
"dependencies": {
1515
"@opencoperlock/shared": "workspace:*",
16+
"highlight.js": "^11.11.1",
1617
"lucide-react": "^0.468.0",
1718
"next": "^15.1.3",
1819
"pdfjs-dist": "^4.10.38",
1920
"react": "^19.0.0",
20-
"react-dom": "^19.0.0"
21+
"react-dom": "^19.0.0",
22+
"react-markdown": "^10.1.0",
23+
"rehype-highlight": "^7.0.2",
24+
"remark-gfm": "^4.0.1"
2125
},
2226
"devDependencies": {
2327
"@types/node": "^22.10.2",

‎apps/web/src/app/(app)/drive/page.tsx‎

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -313,6 +313,13 @@ export default function EspacesPage() {
313313
mime: f.mimeType,
314314
sizeBytes: f.sizeBytes,
315315
url: api.url(`/files/${f.id}/download`),
316+
// Editing a text file re-uploads it under the same name → kept as a new version.
317+
onSave: async (text: string) => {
318+
const form = new FormData();
319+
form.append('file', new File([text], f.name, { type: f.mimeType || 'text/plain' }));
320+
await api.upload(`/files?folderId=${f.folderId ?? currentFolderId ?? ''}`, form);
321+
await reloadCurrent();
322+
},
316323
});
317324
}
318325

@@ -342,6 +349,16 @@ export default function EspacesPage() {
342349
sizeBytes: f.sizeBytes,
343350
blob,
344351
onDownload: () => saveBlob(blob, name),
352+
// Editing re-encrypts the new contents (same name) and replaces the vault file in place.
353+
onSave: async (text: string) => {
354+
if (!vaultKey) return;
355+
const enc = await encryptFile(vaultKey, new File([text], name, { type: 'text/plain' }));
356+
const form = new FormData();
357+
form.append('meta', JSON.stringify({ encryptedName: enc.encryptedName, iv: enc.iv, wrappedKey: enc.wrappedKey }));
358+
form.append('file', enc.blob, 'blob');
359+
await api.upload(`/zk/files/${f.id}`, form, 'PUT');
360+
await reloadCurrent();
361+
},
345362
});
346363
} catch {
347364
toast(t('drive.decryptFailed'), 'error');

‎apps/web/src/app/globals.css‎

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
@import 'highlight.js/styles/github-dark.css';
2+
13
@tailwind base;
24
@tailwind components;
35
@tailwind utilities;
@@ -6,6 +8,59 @@
68
color-scheme: dark;
79
}
810

11+
/* ── In-app Markdown preview ──────────────────────────────────────────────── */
12+
.md-prose {
13+
color: rgb(228 228 231);
14+
line-height: 1.7;
15+
font-size: 0.9rem;
16+
word-wrap: break-word;
17+
}
18+
.md-prose > :first-child { margin-top: 0; }
19+
.md-prose > :last-child { margin-bottom: 0; }
20+
.md-prose h1, .md-prose h2, .md-prose h3, .md-prose h4 {
21+
color: rgb(244 244 245);
22+
font-weight: 600;
23+
line-height: 1.3;
24+
margin: 1.4em 0 0.6em;
25+
}
26+
.md-prose h1 { font-size: 1.6em; border-bottom: 1px solid rgb(255 255 255 / 0.1); padding-bottom: 0.3em; }
27+
.md-prose h2 { font-size: 1.35em; border-bottom: 1px solid rgb(255 255 255 / 0.08); padding-bottom: 0.25em; }
28+
.md-prose h3 { font-size: 1.15em; }
29+
.md-prose p, .md-prose ul, .md-prose ol, .md-prose blockquote, .md-prose table, .md-prose pre { margin: 0.7em 0; }
30+
.md-prose ul, .md-prose ol { padding-left: 1.5em; }
31+
.md-prose ul { list-style: disc; }
32+
.md-prose ol { list-style: decimal; }
33+
.md-prose li { margin: 0.25em 0; }
34+
.md-prose li > input[type='checkbox'] { margin-right: 0.5em; }
35+
.md-prose a { color: rgb(196 181 253); text-decoration: underline; text-underline-offset: 2px; }
36+
.md-prose a:hover { color: rgb(216 207 255); }
37+
.md-prose strong { color: rgb(244 244 245); font-weight: 600; }
38+
.md-prose blockquote {
39+
border-left: 3px solid rgb(139 92 246 / 0.5);
40+
padding-left: 1em;
41+
color: rgb(161 161 170);
42+
}
43+
.md-prose hr { border: 0; border-top: 1px solid rgb(255 255 255 / 0.1); margin: 1.5em 0; }
44+
.md-prose code {
45+
background: rgb(255 255 255 / 0.07);
46+
padding: 0.15em 0.4em;
47+
border-radius: 0.3em;
48+
font-size: 0.85em;
49+
font-family: var(--font-mono, ui-monospace, monospace);
50+
}
51+
.md-prose pre {
52+
background: rgb(13 13 18);
53+
border: 1px solid rgb(255 255 255 / 0.08);
54+
border-radius: 0.6em;
55+
padding: 1em;
56+
overflow-x: auto;
57+
}
58+
.md-prose pre code { background: transparent; padding: 0; font-size: 0.85em; }
59+
.md-prose table { border-collapse: collapse; display: block; overflow-x: auto; }
60+
.md-prose th, .md-prose td { border: 1px solid rgb(255 255 255 / 0.12); padding: 0.45em 0.7em; }
61+
.md-prose th { background: rgb(255 255 255 / 0.04); font-weight: 600; }
62+
.md-prose img { max-width: 100%; border-radius: 0.5em; }
63+
964
html,
1065
body {
1166
height: 100%;

‎apps/web/src/components/FileViewer.tsx‎

Lines changed: 20 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -10,8 +10,10 @@
1010
import { useEffect, useState } from 'react';
1111
import { createPortal } from 'react-dom';
1212
import { Download, Loader2, X } from 'lucide-react';
13-
import { fileVisual, previewKind } from '@/lib/fileType';
13+
import { fileVisual, isEditableText, previewKind } from '@/lib/fileType';
1414
import { PdfCanvas } from '@/components/PdfCanvas';
15+
import { TextDocument } from '@/components/TextDocument';
16+
import { useT } from '@/lib/i18n';
1517
import { formatBytes } from '@opencoperlock/shared/client';
1618

1719
export interface ViewerSource {
@@ -24,9 +26,12 @@ export interface ViewerSource {
2426
blob?: Blob;
2527
/** Optional explicit download handler (e.g. ZK decrypt-and-save). */
2628
onDownload?: () => void;
29+
/** When set, text files become editable; called with the new contents to persist. */
30+
onSave?: (text: string) => Promise<void>;
2731
}
2832

2933
export function FileViewer({ source, onClose }: { source: ViewerSource; onClose: () => void }) {
34+
const { t } = useT();
3035
const kind = previewKind(source.name, source.mime);
3136
const [objectUrl, setObjectUrl] = useState<string | null>(null);
3237
const [dataBlob, setDataBlob] = useState<Blob | null>(null);
@@ -58,7 +63,7 @@ export function FileViewer({ source, onClose }: { source: ViewerSource; onClose:
5863
}
5964
// PDFs are rendered from the Blob by <PdfCanvas> (no object URL / iframe).
6065
} catch {
61-
if (!cancelled) setError('Aperçu indisponible. Vous pouvez télécharger le fichier.');
66+
if (!cancelled) setError(t('viewer.unavailable'));
6267
} finally {
6368
if (!cancelled) setLoading(false);
6469
}
@@ -95,7 +100,7 @@ export function FileViewer({ source, onClose }: { source: ViewerSource; onClose:
95100
<button
96101
className="rounded-lg p-2 text-zinc-400 transition hover:bg-white/10 hover:text-zinc-100"
97102
onClick={onClose}
98-
title="Fermer"
103+
title={t('viewer.close')}
99104
>
100105
<X size={18} />
101106
</button>
@@ -118,23 +123,23 @@ export function FileViewer({ source, onClose }: { source: ViewerSource; onClose:
118123
<div className="h-full w-full self-stretch">
119124
<PdfCanvas
120125
blob={dataBlob}
121-
onFail={() => setError('Aperçu PDF indisponible. Vous pouvez télécharger le fichier.')}
126+
onFail={() => setError(t('viewer.pdfUnavailable'))}
122127
/>
123128
</div>
124129
) : kind === 'video' && objectUrl ? (
125130
<video src={objectUrl} controls autoPlay className="max-h-full max-w-full rounded-lg" />
126131
) : kind === 'audio' && objectUrl ? (
127132
<audio src={objectUrl} controls autoPlay className="w-full max-w-lg" />
128133
) : kind === 'text' && text !== null ? (
129-
<pre className="h-full w-full max-w-4xl overflow-auto rounded-lg border border-white/10 bg-ink-900 p-4 text-xs leading-relaxed text-zinc-300">
130-
{text}
131-
</pre>
132-
) : (
133-
<Fallback
134-
visual={visual}
135-
message="Aucun aperçu pour ce type de fichier. Téléchargez-le pour l’ouvrir."
136-
source={source}
134+
<TextDocument
135+
name={source.name}
136+
mime={source.mime}
137+
initialText={text}
138+
editable={!!source.onSave && isEditableText(source.name, source.mime)}
139+
onSave={source.onSave}
137140
/>
141+
) : (
142+
<Fallback visual={visual} message={t('viewer.noPreview')} source={source} />
138143
)}
139144
</div>
140145
</div>,
@@ -163,17 +168,18 @@ function Fallback({
163168
}
164169

165170
function DownloadButton({ source, primary }: { source: ViewerSource; primary?: boolean }) {
171+
const { t } = useT();
166172
const cls = primary ? 'btn-primary' : 'btn-ghost';
167173
if (source.onDownload) {
168174
return (
169175
<button className={cls} onClick={source.onDownload}>
170-
<Download size={16} /> Télécharger
176+
<Download size={16} /> {t('common.download')}
171177
</button>
172178
);
173179
}
174180
return (
175181
<a className={cls} href={source.url} download={source.name}>
176-
<Download size={16} /> Télécharger
182+
<Download size={16} /> {t('common.download')}
177183
</a>
178184
);
179185
}

0 commit comments

Comments
 (0)