Aperçu : route /api/preview en lecture seule et visualiseurs côté client
- GET /api/preview?path= et /api/public/{jeton}/preview : liste blanche d'extensions, inline, nosniff, CSP stricte, texte plafonné à 2 Mo
- Visualiseurs : texte brut, CSV paginé (PapaParse), Markdown sans HTML brut (react-markdown + remark-gfm), code colorisé (highlight.js), PDF natif
- Le HTML s'affiche comme du code, jamais rendu ; RTF/DOC/DOCX hors périmètre
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
fe81055421
commit
d4da3db132
14 files changed
+2378
-39
No files matched your search
Generated
+1531
-6
File diff suppressed because it is too large.
Load diff
@@ -9,10 +9,15 @@
|
||||
"preview": "vite preview"
|
||||
},
|
||||
"dependencies": {
|
||||
"highlight.js": "^11.11.1",
|
||||
"papaparse": "^5.5.3",
|
||||
"react": "^19.1.0",
|
||||
"react-dom": "^19.1.0"
|
||||
"react-dom": "^19.1.0",
|
||||
"react-markdown": "^10.1.0",
|
||||
"remark-gfm": "^4.0.1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/papaparse": "^5.5.2",
|
||||
"@types/react": "^19.1.0",
|
||||
"@types/react-dom": "^19.1.0",
|
||||
"@vitejs/plugin-react": "^5.0.0",
|
||||
|
||||
@@ -593,7 +593,8 @@ export function Explorer({ me, refreshKey, goto, onDirChange, onMutated, toolbar
|
||||
modTime: e.modTime,
|
||||
src: api.downloadUrl(e.path, true),
|
||||
download: api.downloadUrl(e.path),
|
||||
text: () => api.readText(e.path),
|
||||
preview: api.previewUrl(e.path),
|
||||
text: () => api.readPreview(e.path),
|
||||
});
|
||||
const previewFiles = useMemo(() => (previewIndex >= 0 ? files.map(toPreview) : []), [previewIndex >= 0, files]); // eslint-disable-line react-hooks/exhaustive-deps
|
||||
|
||||
|
||||
+48
-10
@@ -1,9 +1,15 @@
|
||||
import { useEffect, useState } from "react";
|
||||
import { lazy, Suspense, useEffect, useState } from "react";
|
||||
import type { ReactNode } from "react";
|
||||
import { createPortal } from "react-dom";
|
||||
import { ChevronLeftIcon, ChevronRightIcon, CloseIcon, DownloadIcon, ExpandIcon } from "./icons";
|
||||
import { FileGlyph } from "./FileGlyph";
|
||||
import { kindOf, monospace, previewable, typeLabel } from "./filetypes";
|
||||
import { kindOf, monospace, previewable, previewMode, typeLabel } from "./filetypes";
|
||||
import type { PreviewText } from "./api";
|
||||
|
||||
// Visualiseurs riches (highlight.js, react-markdown, PapaParse) : module chargé à la première ouverture.
|
||||
const CodeViewer = lazy(() => import("./viewers").then((m) => ({ default: m.CodeViewer })));
|
||||
const MarkdownViewer = lazy(() => import("./viewers").then((m) => ({ default: m.MarkdownViewer })));
|
||||
const CsvViewer = lazy(() => import("./viewers").then((m) => ({ default: m.CsvViewer })));
|
||||
import { fmtDate, fmtSize } from "./format";
|
||||
|
||||
/** Fichier à prévisualiser : adresses d'affichage et de téléchargement fournies par l'appelant. */
|
||||
@@ -11,11 +17,13 @@ export interface PreviewFile {
|
||||
name: string;
|
||||
size: number;
|
||||
modTime: string;
|
||||
/** Adresse d'affichage en ligne (images, vidéo, PDF). */
|
||||
/** Adresse d'affichage en ligne (images, vidéo, audio). */
|
||||
src: string;
|
||||
/** Adresse /api/preview (PDF). */
|
||||
preview: string;
|
||||
download: string;
|
||||
/** Lit le début du contenu texte. */
|
||||
text: () => Promise<{ text: string; truncated: boolean }>;
|
||||
/** Lit le contenu texte via /api/preview (début seulement au-delà du plafond serveur). */
|
||||
text: () => Promise<PreviewText>;
|
||||
}
|
||||
|
||||
interface Props {
|
||||
@@ -126,14 +134,14 @@ function Viewer({ file }: { file: PreviewFile }) {
|
||||
</div>
|
||||
);
|
||||
case "pdf":
|
||||
return <iframe className="viewer-pdf" src={file.src} title={file.name} />;
|
||||
return <iframe className="viewer-pdf" src={file.preview} title={file.name} />;
|
||||
default:
|
||||
return <TextViewer file={file} onError={() => setError(true)} />;
|
||||
}
|
||||
}
|
||||
|
||||
function TextViewer({ file, onError }: { file: PreviewFile; onError: () => void }) {
|
||||
const [state, setState] = useState<{ text: string; truncated: boolean } | null>(null);
|
||||
const [state, setState] = useState<PreviewText | null>(null);
|
||||
useEffect(() => {
|
||||
let live = true;
|
||||
file
|
||||
@@ -146,10 +154,40 @@ function TextViewer({ file, onError }: { file: PreviewFile; onError: () => void
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [file.src]);
|
||||
if (!state) return <div className="preview-none muted">Chargement…</div>;
|
||||
const lines = state.text.split("\n");
|
||||
const footer = state.truncated && (
|
||||
<div className="notice">Aperçu limité au début du fichier ({fmtSize(file.size)} au total) : télécharger pour le lire en entier.</div>
|
||||
);
|
||||
const loading = <div className="preview-none muted">Chargement…</div>;
|
||||
switch (previewMode(file.name)) {
|
||||
case "code":
|
||||
return (
|
||||
<Suspense fallback={loading}>
|
||||
<CodeViewer name={file.name} text={state.text} footer={footer} />
|
||||
</Suspense>
|
||||
);
|
||||
case "markdown":
|
||||
return (
|
||||
<Suspense fallback={loading}>
|
||||
<MarkdownViewer text={state.text} footer={footer} />
|
||||
</Suspense>
|
||||
);
|
||||
case "csv":
|
||||
return (
|
||||
<Suspense fallback={loading}>
|
||||
<CsvViewer name={file.name} text={state.text} truncated={state.truncated} footer={footer} />
|
||||
</Suspense>
|
||||
);
|
||||
default:
|
||||
return <PlainViewer name={file.name} text={state.text} footer={footer} />;
|
||||
}
|
||||
}
|
||||
|
||||
/** Texte brut (.txt, .log...), lignes numérotées. */
|
||||
function PlainViewer({ name, text, footer }: { name: string; text: string; footer: ReactNode }) {
|
||||
const lines = text.split("\n");
|
||||
return (
|
||||
<div className="viewer-text">
|
||||
<pre className={monospace(file.name) ? "mono" : ""}>
|
||||
<pre className={monospace(name) ? "mono" : ""}>
|
||||
{lines.map((l, i) => (
|
||||
<span key={i} className="ln" data-n={i + 1}>
|
||||
{l || " "}
|
||||
@@ -157,7 +195,7 @@ function TextViewer({ file, onError }: { file: PreviewFile; onError: () => void
|
||||
</span>
|
||||
))}
|
||||
</pre>
|
||||
{state.truncated && <div className="notice">Aperçu limité au début du fichier ({fmtSize(512 * 1024)}) : télécharger pour le lire en entier.</div>}
|
||||
{footer}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -63,7 +63,8 @@ export function ShareView({ token }: { token: string }) {
|
||||
modTime: f.modTime,
|
||||
src: api.publicFileUrl(token, join(sub, f.name), true),
|
||||
download: api.publicFileUrl(token, join(sub, f.name)),
|
||||
text: async () => ({ text: await api.publicText(token, join(sub, f.name)), truncated: f.size > 512 * 1024 }),
|
||||
preview: api.publicPreviewUrl(token, join(sub, f.name)),
|
||||
text: () => api.publicPreview(token, join(sub, f.name)),
|
||||
}))
|
||||
: info?.name
|
||||
? [
|
||||
@@ -73,7 +74,8 @@ export function ShareView({ token }: { token: string }) {
|
||||
modTime: info.modTime,
|
||||
src: api.publicFileUrl(token, "", true),
|
||||
download: api.publicFileUrl(token, ""),
|
||||
text: async () => ({ text: await api.publicText(token, ""), truncated: info.size > 512 * 1024 }),
|
||||
preview: api.publicPreviewUrl(token, ""),
|
||||
text: () => api.publicPreview(token, ""),
|
||||
},
|
||||
]
|
||||
: [],
|
||||
|
||||
+19
-8
@@ -201,6 +201,17 @@ async function request(url: string, init?: RequestInit): Promise<Response> {
|
||||
}
|
||||
|
||||
const q = (p: string) => encodeURIComponent(p);
|
||||
|
||||
/** Texte renvoyé par /api/preview : truncated si le fichier dépasse le plafond du serveur. */
|
||||
export interface PreviewText {
|
||||
text: string;
|
||||
truncated: boolean;
|
||||
}
|
||||
|
||||
async function readPreview(url: string): Promise<PreviewText> {
|
||||
const res = await request(url);
|
||||
return { text: await res.text(), truncated: res.headers.get("X-Preview-Truncated") === "1" };
|
||||
}
|
||||
const json = (body: unknown, method = "POST"): RequestInit => ({
|
||||
method,
|
||||
headers: { "Content-Type": "application/json" },
|
||||
@@ -267,12 +278,11 @@ export const api = {
|
||||
restoreTrash: async (paths: string[]): Promise<MoveResult[]> =>
|
||||
(await request("/api/trash/restore", json({ paths }))).json(),
|
||||
|
||||
/** Contenu texte d'un fichier (les premiers octets seulement : max). */
|
||||
readText: async (path: string, max = 512 * 1024): Promise<{ text: string; truncated: boolean }> => {
|
||||
const res = await request(`/api/file?path=${q(path)}&inline=1`, { headers: { Range: `bytes=0-${max - 1}` } });
|
||||
const total = Number((res.headers.get("Content-Range") ?? "").split("/")[1]);
|
||||
return { text: await res.text(), truncated: res.status === 206 && total > max };
|
||||
},
|
||||
/** Aperçu texte d'un fichier (/api/preview : liste blanche, début du fichier au-delà du plafond serveur). */
|
||||
readPreview: (path: string): Promise<PreviewText> => readPreview(`/api/preview?path=${q(path)}`),
|
||||
|
||||
/** Adresse d'aperçu en ligne (PDF : visionneuse du navigateur). */
|
||||
previewUrl: (path: string) => `/api/preview?path=${q(path)}`,
|
||||
|
||||
/** Empreinte SHA-256 (calculée à la demande côté serveur). */
|
||||
hash: async (path: string): Promise<string> => (await request(`/api/hash?path=${q(path)}`)).json().then((j) => j.sha256),
|
||||
@@ -342,8 +352,9 @@ export const api = {
|
||||
|
||||
publicThumbUrl: (token: string, sub: string) => `/api/public/${q(token)}/thumb?sub=${q(sub)}`,
|
||||
|
||||
publicText: async (token: string, sub: string, max = 512 * 1024): Promise<string> =>
|
||||
(await request(`/api/public/${q(token)}/file?sub=${q(sub)}&inline=1`, { headers: { Range: `bytes=0-${max - 1}` } })).text(),
|
||||
publicPreview: (token: string, sub: string): Promise<PreviewText> => readPreview(`/api/public/${q(token)}/preview?sub=${q(sub)}`),
|
||||
|
||||
publicPreviewUrl: (token: string, sub: string) => `/api/public/${q(token)}/preview?sub=${q(sub)}`,
|
||||
|
||||
// --- Jetons d'API ------------------------------------------------------------
|
||||
tokens: async (): Promise<ApiToken[]> => (await request("/api/tokens")).json(),
|
||||
|
||||
@@ -9,7 +9,7 @@ const sets: Record<Exclude<Kind, "other">, string> = {
|
||||
audio: "mp3 ogg oga wav flac aac m4a opus wma aiff mid midi",
|
||||
pdf: "pdf",
|
||||
text: "txt md markdown rst log csv tsv json yaml yml toml ini conf cfg env srt tex bib nfo",
|
||||
code: "html htm css js mjs ts tsx jsx py go rs java c h cpp hpp cs php rb sh bash zsh ps1 sql tf lua xml vue svelte service gitignore",
|
||||
code: "html htm css scss less js mjs cjs ts tsx jsx jsonc py go rs java kt c h cpp hpp cs php rb sh bash zsh ps1 sql tf hcl lua xml vue svelte service properties diff patch gitignore",
|
||||
archive: "zip gz tgz bz2 xz 7z rar tar zst iso dmg jar deb rpm apk",
|
||||
doc: "doc docx odt rtf pages",
|
||||
sheet: "xls xlsx ods numbers",
|
||||
@@ -19,12 +19,54 @@ const sets: Record<Exclude<Kind, "other">, string> = {
|
||||
const byExt = new Map<string, Kind>();
|
||||
for (const [kind, list] of Object.entries(sets)) for (const e of list.split(" ")) byExt.set(e, kind as Kind);
|
||||
|
||||
const textNames = new Set(["dockerfile", "makefile", "readme", "license", "changelog"]);
|
||||
const textNames = new Set(["readme", "license", "changelog"]);
|
||||
const codeNames = new Set(["dockerfile", "containerfile", "makefile", "jenkinsfile", "vagrantfile", ".gitignore", ".dockerignore", ".env"]);
|
||||
const isDockerfile = (lower: string) => lower.startsWith("dockerfile.") || lower.startsWith("containerfile.");
|
||||
|
||||
export const kindOf = (name: string): Kind => {
|
||||
const lower = name.toLowerCase();
|
||||
if (codeNames.has(lower) || isDockerfile(lower)) return "code";
|
||||
const k = byExt.get(extOf(name));
|
||||
if (k) return k;
|
||||
return textNames.has(name.toLowerCase()) ? "text" : "other";
|
||||
return textNames.has(lower) ? "text" : "other";
|
||||
};
|
||||
|
||||
/** Rendu de l'aperçu (même liste blanche que /api/preview, voir internal/api/preview.go). */
|
||||
export type PreviewMode = "text" | "csv" | "markdown" | "code" | "pdf";
|
||||
|
||||
const plainExts = new Set(["txt", "log", "rst", "srt", "sub", "tex", "bib", "nfo"]);
|
||||
|
||||
export const previewMode = (name: string): PreviewMode | null => {
|
||||
const lower = name.toLowerCase();
|
||||
const e = extOf(name);
|
||||
if (e === "pdf") return "pdf";
|
||||
if (e === "csv" || e === "tsv") return "csv";
|
||||
if (e === "md" || e === "markdown") return "markdown";
|
||||
if (plainExts.has(e) || textNames.has(lower)) return "text";
|
||||
const k = kindOf(name);
|
||||
return k === "code" || k === "text" ? "code" : null;
|
||||
};
|
||||
|
||||
// Langage highlight.js par extension (ou nom de fichier) ; absent : texte brut.
|
||||
const langByExt: Record<string, string> = {
|
||||
json: "json", jsonc: "json",
|
||||
js: "javascript", mjs: "javascript", cjs: "javascript", jsx: "javascript",
|
||||
ts: "typescript", tsx: "typescript",
|
||||
yaml: "yaml", yml: "yaml",
|
||||
toml: "ini", ini: "ini", conf: "ini", cfg: "ini", properties: "properties", service: "ini", env: "bash",
|
||||
go: "go", py: "python", sh: "bash", bash: "bash", zsh: "bash", ps1: "powershell",
|
||||
xml: "xml", html: "xml", htm: "xml", vue: "xml", svelte: "xml",
|
||||
css: "css", scss: "scss", less: "less", sql: "sql",
|
||||
rs: "rust", java: "java", kt: "kotlin", c: "c", h: "c", cpp: "cpp", hpp: "cpp", cs: "csharp",
|
||||
php: "php", rb: "ruby", lua: "lua", diff: "diff", patch: "diff",
|
||||
};
|
||||
|
||||
export const codeLanguage = (name: string): string | null => {
|
||||
const lower = name.toLowerCase();
|
||||
if (lower === "dockerfile" || lower === "containerfile" || isDockerfile(lower)) return "dockerfile";
|
||||
if (lower === "makefile") return "makefile";
|
||||
if (lower === ".env") return "bash";
|
||||
return langByExt[extOf(name)] ?? null;
|
||||
};
|
||||
|
||||
/** Le serveur sait-il en faire une miniature (JPEG, PNG, GIF) ? */
|
||||
@@ -50,7 +92,7 @@ export const previewable = (name: string): boolean => {
|
||||
case "pdf":
|
||||
case "text":
|
||||
case "code":
|
||||
return true;
|
||||
return previewMode(name) !== null;
|
||||
default:
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -2006,3 +2006,210 @@ th.c-size .th-btn {
|
||||
display: none;
|
||||
}
|
||||
}
|
||||
|
||||
/* --- Aperçu : code colorisé, Markdown, CSV ------------------------------------ */
|
||||
:root {
|
||||
--hl-comment: #6a737d;
|
||||
--hl-keyword: #cf222e;
|
||||
--hl-string: #0a3069;
|
||||
--hl-number: #0550ae;
|
||||
--hl-title: #8250df;
|
||||
--hl-attr: #116329;
|
||||
--hl-meta: #953800;
|
||||
}
|
||||
:root[data-theme="dark"] {
|
||||
--hl-comment: #8b949e;
|
||||
--hl-keyword: #ff7b72;
|
||||
--hl-string: #a5d6ff;
|
||||
--hl-number: #79c0ff;
|
||||
--hl-title: #d2a8ff;
|
||||
--hl-attr: #7ee787;
|
||||
--hl-meta: #ffa657;
|
||||
}
|
||||
.viewer-code .code-grid {
|
||||
display: grid;
|
||||
grid-template-columns: auto 1fr;
|
||||
min-width: max-content;
|
||||
}
|
||||
.viewer-code pre {
|
||||
margin: 0;
|
||||
padding: 1rem 0;
|
||||
font-family: var(--mono);
|
||||
font-size: 13px;
|
||||
line-height: 1.5;
|
||||
white-space: pre;
|
||||
}
|
||||
.viewer-code .code-gutter {
|
||||
position: sticky;
|
||||
left: 0;
|
||||
padding: 1rem 0.8rem 1rem 0.6rem;
|
||||
min-width: 3.6rem;
|
||||
text-align: right;
|
||||
color: var(--muted);
|
||||
background: var(--panel);
|
||||
border-right: 1px solid var(--border);
|
||||
user-select: none;
|
||||
}
|
||||
.viewer-code .code-body {
|
||||
padding-left: 1rem;
|
||||
padding-right: 1rem;
|
||||
}
|
||||
.hljs-comment,
|
||||
.hljs-quote {
|
||||
color: var(--hl-comment);
|
||||
font-style: italic;
|
||||
}
|
||||
.hljs-keyword,
|
||||
.hljs-selector-tag,
|
||||
.hljs-literal,
|
||||
.hljs-doctag,
|
||||
.hljs-type {
|
||||
color: var(--hl-keyword);
|
||||
}
|
||||
.hljs-string,
|
||||
.hljs-regexp,
|
||||
.hljs-addition {
|
||||
color: var(--hl-string);
|
||||
}
|
||||
.hljs-number,
|
||||
.hljs-symbol,
|
||||
.hljs-bullet,
|
||||
.hljs-variable,
|
||||
.hljs-template-variable {
|
||||
color: var(--hl-number);
|
||||
}
|
||||
.hljs-title,
|
||||
.hljs-section,
|
||||
.hljs-built_in,
|
||||
.hljs-name {
|
||||
color: var(--hl-title);
|
||||
}
|
||||
.hljs-attr,
|
||||
.hljs-attribute,
|
||||
.hljs-selector-class,
|
||||
.hljs-selector-id,
|
||||
.hljs-tag {
|
||||
color: var(--hl-attr);
|
||||
}
|
||||
.hljs-meta,
|
||||
.hljs-deletion,
|
||||
.hljs-params {
|
||||
color: var(--hl-meta);
|
||||
}
|
||||
.hljs-emphasis {
|
||||
font-style: italic;
|
||||
}
|
||||
.hljs-strong {
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.viewer-md .md {
|
||||
max-width: 860px;
|
||||
margin: 0 auto;
|
||||
padding: 1.5rem 2rem 2rem;
|
||||
font-size: 15px;
|
||||
line-height: 1.6;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
.md h1,
|
||||
.md h2 {
|
||||
padding-bottom: 0.3em;
|
||||
border-bottom: 1px solid var(--border);
|
||||
}
|
||||
.md a {
|
||||
color: var(--accent);
|
||||
}
|
||||
.md code {
|
||||
font-family: var(--mono);
|
||||
font-size: 0.88em;
|
||||
padding: 0.1em 0.35em;
|
||||
border-radius: 4px;
|
||||
background: var(--panel-2);
|
||||
}
|
||||
.md pre {
|
||||
padding: 0.8rem 1rem;
|
||||
overflow: auto;
|
||||
border-radius: var(--radius-sm);
|
||||
background: var(--panel-2);
|
||||
}
|
||||
.md pre code {
|
||||
padding: 0;
|
||||
background: none;
|
||||
}
|
||||
.md blockquote {
|
||||
margin: 0;
|
||||
padding: 0 1rem;
|
||||
color: var(--muted);
|
||||
border-left: 3px solid var(--border);
|
||||
}
|
||||
.md table {
|
||||
border-collapse: collapse;
|
||||
display: block;
|
||||
overflow: auto;
|
||||
}
|
||||
.md th,
|
||||
.md td {
|
||||
padding: 0.35rem 0.7rem;
|
||||
border: 1px solid var(--border);
|
||||
}
|
||||
.md th {
|
||||
background: var(--panel-2);
|
||||
}
|
||||
.md img,
|
||||
.md .md-img {
|
||||
color: var(--muted);
|
||||
}
|
||||
.md input[type="checkbox"] {
|
||||
margin-right: 0.4rem;
|
||||
}
|
||||
|
||||
.viewer-csv {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
}
|
||||
.csv-bar {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
gap: 0.5rem 0.8rem;
|
||||
padding: 0.6rem 1rem;
|
||||
border-bottom: 1px solid var(--border);
|
||||
font-size: 13px;
|
||||
}
|
||||
.csv-header {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 0.3rem;
|
||||
}
|
||||
.csv-scroll {
|
||||
flex: 1;
|
||||
overflow: auto;
|
||||
}
|
||||
.csv-table {
|
||||
border-collapse: collapse;
|
||||
font-size: 13px;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.csv-table th,
|
||||
.csv-table td {
|
||||
padding: 0.3rem 0.7rem;
|
||||
border: 1px solid var(--border);
|
||||
max-width: 28rem;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
text-align: left;
|
||||
}
|
||||
.csv-table thead th {
|
||||
position: sticky;
|
||||
top: 0;
|
||||
background: var(--panel-2);
|
||||
font-weight: 600;
|
||||
}
|
||||
.csv-table .csv-n {
|
||||
color: var(--muted);
|
||||
text-align: right;
|
||||
background: var(--panel-2);
|
||||
}
|
||||
.csv-table tbody tr:hover td {
|
||||
background: var(--hover);
|
||||
}
|
||||
@@ -0,0 +1,202 @@
|
||||
// Visualiseurs riches de l'aperçu, chargés à la demande (React.lazy) :
|
||||
// code colorisé (highlight.js), Markdown (react-markdown + remark-gfm, sans
|
||||
// HTML brut), CSV paginé (PapaParse). Tout est rendu côté client à partir du
|
||||
// texte servi par /api/preview.
|
||||
import { useMemo, useState } from "react";
|
||||
import type { ReactNode } from "react";
|
||||
import Markdown from "react-markdown";
|
||||
import type { Components } from "react-markdown";
|
||||
import remarkGfm from "remark-gfm";
|
||||
import Papa from "papaparse";
|
||||
import hljs from "highlight.js/lib/core";
|
||||
import bash from "highlight.js/lib/languages/bash";
|
||||
import c from "highlight.js/lib/languages/c";
|
||||
import cpp from "highlight.js/lib/languages/cpp";
|
||||
import csharp from "highlight.js/lib/languages/csharp";
|
||||
import css from "highlight.js/lib/languages/css";
|
||||
import diff from "highlight.js/lib/languages/diff";
|
||||
import dockerfile from "highlight.js/lib/languages/dockerfile";
|
||||
import go from "highlight.js/lib/languages/go";
|
||||
import ini from "highlight.js/lib/languages/ini";
|
||||
import java from "highlight.js/lib/languages/java";
|
||||
import javascript from "highlight.js/lib/languages/javascript";
|
||||
import json from "highlight.js/lib/languages/json";
|
||||
import kotlin from "highlight.js/lib/languages/kotlin";
|
||||
import less from "highlight.js/lib/languages/less";
|
||||
import lua from "highlight.js/lib/languages/lua";
|
||||
import makefile from "highlight.js/lib/languages/makefile";
|
||||
import php from "highlight.js/lib/languages/php";
|
||||
import powershell from "highlight.js/lib/languages/powershell";
|
||||
import properties from "highlight.js/lib/languages/properties";
|
||||
import python from "highlight.js/lib/languages/python";
|
||||
import ruby from "highlight.js/lib/languages/ruby";
|
||||
import rust from "highlight.js/lib/languages/rust";
|
||||
import scss from "highlight.js/lib/languages/scss";
|
||||
import sql from "highlight.js/lib/languages/sql";
|
||||
import typescript from "highlight.js/lib/languages/typescript";
|
||||
import xml from "highlight.js/lib/languages/xml";
|
||||
import yaml from "highlight.js/lib/languages/yaml";
|
||||
import { codeLanguage } from "./filetypes";
|
||||
|
||||
const languages = {
|
||||
bash, c, cpp, csharp, css, diff, dockerfile, go, ini, java, javascript, json, kotlin, less, lua,
|
||||
makefile, php, powershell, properties, python, ruby, rust, scss, sql, typescript, xml, yaml,
|
||||
};
|
||||
for (const [name, def] of Object.entries(languages)) hljs.registerLanguage(name, def);
|
||||
// Alias des blocs de code Markdown (```yml, ```sh, ```html...).
|
||||
hljs.registerAliases(["yml"], { languageName: "yaml" });
|
||||
hljs.registerAliases(["sh", "shell", "zsh"], { languageName: "bash" });
|
||||
hljs.registerAliases(["html", "htm", "svg"], { languageName: "xml" });
|
||||
hljs.registerAliases(["js", "mjs"], { languageName: "javascript" });
|
||||
hljs.registerAliases(["ts"], { languageName: "typescript" });
|
||||
hljs.registerAliases(["py"], { languageName: "python" });
|
||||
hljs.registerAliases(["toml"], { languageName: "ini" });
|
||||
|
||||
/** Au-delà, pas de coloration (temps de calcul) : texte brut numéroté. */
|
||||
const MAX_HIGHLIGHT = 512 * 1024;
|
||||
|
||||
/** HTML coloré (échappé par highlight.js), ou null si le langage est inconnu. */
|
||||
function highlight(text: string, lang: string | null): string | null {
|
||||
if (!lang || !hljs.getLanguage(lang) || text.length > MAX_HIGHLIGHT) return null;
|
||||
try {
|
||||
return hljs.highlight(text, { language: lang, ignoreIllegals: true }).value;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/** Code numéroté et colorisé selon l'extension ; un fichier HTML s'affiche comme du code, jamais rendu. */
|
||||
export function CodeViewer({ name, text, footer }: { name: string; text: string; footer?: ReactNode }) {
|
||||
const lang = codeLanguage(name);
|
||||
const html = useMemo(() => highlight(text, lang), [text, lang]);
|
||||
// Un saut de ligne final n'ouvre pas de ligne supplémentaire.
|
||||
const count = useMemo(() => text.split("\n").length - (text.endsWith("\n") ? 1 : 0), [text]);
|
||||
const gutter = useMemo(() => Array.from({ length: count }, (_, i) => i + 1).join("\n"), [count]);
|
||||
return (
|
||||
<div className="viewer-text viewer-code">
|
||||
<div className="code-grid">
|
||||
<pre className="code-gutter" aria-hidden>
|
||||
{gutter}
|
||||
</pre>
|
||||
{html !== null ? (
|
||||
<pre className="code-body hljs" dangerouslySetInnerHTML={{ __html: html }} />
|
||||
) : (
|
||||
<pre className="code-body">{text}</pre>
|
||||
)}
|
||||
</div>
|
||||
{lang && html === null && text.length > MAX_HIGHLIGHT && <div className="notice">Fichier volumineux : affiché sans coloration.</div>}
|
||||
{footer}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// Markdown : pas de HTML brut (skipHtml), liens ouverts hors de l'application,
|
||||
// images non chargées (aucune requête vers un site tiers) : remplacées par un lien.
|
||||
const mdComponents: Components = {
|
||||
a: ({ href, children }) => (
|
||||
<a href={href} target="_blank" rel="noopener noreferrer nofollow">
|
||||
{children}
|
||||
</a>
|
||||
),
|
||||
img: ({ src, alt }) =>
|
||||
typeof src === "string" && /^https?:\/\//i.test(src) ? (
|
||||
<a href={src} target="_blank" rel="noopener noreferrer nofollow" className="md-img">
|
||||
[image : {alt || src}]
|
||||
</a>
|
||||
) : (
|
||||
<span className="md-img">[image : {alt || String(src ?? "")}]</span>
|
||||
),
|
||||
code: ({ className, children }) => {
|
||||
const lang = /language-([\w-]+)/.exec(className ?? "")?.[1] ?? null;
|
||||
const src = String(children ?? "");
|
||||
const html = lang ? highlight(src.replace(/\n$/, ""), lang) : null;
|
||||
return html !== null ? <code className={`hljs ${className ?? ""}`} dangerouslySetInnerHTML={{ __html: html }} /> : <code className={className}>{children}</code>;
|
||||
},
|
||||
};
|
||||
|
||||
export function MarkdownViewer({ text, footer }: { text: string; footer?: ReactNode }) {
|
||||
return (
|
||||
<div className="viewer-text viewer-md">
|
||||
<article className="md">
|
||||
<Markdown remarkPlugins={[remarkGfm]} skipHtml components={mdComponents}>
|
||||
{text}
|
||||
</Markdown>
|
||||
</article>
|
||||
{footer}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const PAGE = 100;
|
||||
|
||||
/** Tableau paginé ; séparateur détecté par PapaParse (virgule, point-virgule, tabulation...). */
|
||||
export function CsvViewer({ name, text, truncated, footer }: { name: string; text: string; truncated: boolean; footer?: ReactNode }) {
|
||||
const [page, setPage] = useState(0);
|
||||
const [header, setHeader] = useState(true);
|
||||
const parsed = useMemo(() => {
|
||||
const r = Papa.parse<string[]>(text, {
|
||||
skipEmptyLines: "greedy",
|
||||
delimiter: name.toLowerCase().endsWith(".tsv") ? "\t" : undefined,
|
||||
});
|
||||
const rows = r.data;
|
||||
if (truncated && rows.length > 1) rows.pop(); // dernière ligne coupée par le plafond
|
||||
return { rows, delimiter: r.meta.delimiter, errors: r.errors.length };
|
||||
}, [text, truncated, name]);
|
||||
|
||||
const head = header ? (parsed.rows[0] ?? []) : null;
|
||||
const body = header ? parsed.rows.slice(1) : parsed.rows;
|
||||
const pages = Math.max(1, Math.ceil(body.length / PAGE));
|
||||
const p = Math.min(page, pages - 1);
|
||||
const rows = body.slice(p * PAGE, (p + 1) * PAGE);
|
||||
const cols = Math.max(head?.length ?? 0, ...rows.map((r) => r.length));
|
||||
const delim = parsed.delimiter === "\t" ? "tabulation" : `« ${parsed.delimiter} »`;
|
||||
|
||||
return (
|
||||
<div className="viewer-text viewer-csv">
|
||||
<div className="csv-bar">
|
||||
<span className="muted">
|
||||
{body.length.toLocaleString("fr-FR")} ligne{body.length > 1 ? "s" : ""} · {cols} colonne{cols > 1 ? "s" : ""} · séparateur {delim}
|
||||
{parsed.errors > 0 && ` · ${parsed.errors} ligne${parsed.errors > 1 ? "s" : ""} mal formée${parsed.errors > 1 ? "s" : ""}`}
|
||||
</span>
|
||||
<label className="csv-header">
|
||||
<input type="checkbox" checked={header} onChange={(e) => (setHeader(e.target.checked), setPage(0))} /> Première ligne = en-tête
|
||||
</label>
|
||||
<span className="spacer" />
|
||||
<button className="ex-btn" disabled={p === 0} onClick={() => setPage(p - 1)}>
|
||||
Précédent
|
||||
</button>
|
||||
<span className="muted">
|
||||
Page {p + 1} / {pages}
|
||||
</span>
|
||||
<button className="ex-btn" disabled={p >= pages - 1} onClick={() => setPage(p + 1)}>
|
||||
Suivant
|
||||
</button>
|
||||
</div>
|
||||
<div className="csv-scroll">
|
||||
<table className="csv-table">
|
||||
{head && (
|
||||
<thead>
|
||||
<tr>
|
||||
<th className="csv-n">#</th>
|
||||
{Array.from({ length: cols }, (_, i) => (
|
||||
<th key={i}>{head[i] ?? ""}</th>
|
||||
))}
|
||||
</tr>
|
||||
</thead>
|
||||
)}
|
||||
<tbody>
|
||||
{rows.map((r, i) => (
|
||||
<tr key={p * PAGE + i}>
|
||||
<td className="csv-n">{p * PAGE + i + 1}</td>
|
||||
{Array.from({ length: cols }, (_, j) => (
|
||||
<td key={j}>{r[j] ?? ""}</td>
|
||||
))}
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
{footer}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
Reference in new issue
Block a user