Skip to content

Build your personal knowledge base with Trilium Notes

feat(client): syntax-highlight text previews of files and attachments

Elian Doran2d705fac51b4
diff --git a/apps/client/src/widgets/type_widgets/Attachment.tsx b/apps/client/src/widgets/type_widgets/Attachment.tsx
index b13e2b6f5a..f98981383a 100644
--- a/apps/client/src/widgets/type_widgets/Attachment.tsx
+++ b/apps/client/src/widgets/type_widgets/Attachment.tsx
@@ -268,7 +268,7 @@ function AttachmentInfo({ attachment, isFullDetail, ownerNote, noteContext, view
</div>
{scheduledForErasureSince && <DeletionAlert utcDateScheduledForErasureSince={scheduledForErasureSince} />}
- {textContent && <TextPreview content={textContent} />}
+ {textContent && <TextPreview content={textContent} mime={attachment.mime} />}
{isZoomableImage ? (
<div key="image-viewer" ref={imageViewerWrapper} className="attachment-content-wrapper attachment-image-viewer">
<ImageViewer key={`${attachment.attachmentId}-${modified}`} src={imageSrc} alt={attachment.title} />
diff --git a/apps/client/src/widgets/type_widgets/File.css b/apps/client/src/widgets/type_widgets/File.css
index 54114fe231..e18aefc35b 100644
--- a/apps/client/src/widgets/type_widgets/File.css
+++ b/apps/client/src/widgets/type_widgets/File.css
@@ -16,14 +16,21 @@
overflow: hidden;
}
-.file-preview-content {
- background-color: var(--accented-background-color);
+/* Rendered by CodeBlock, so the same <pre> also carries .code-block; the element selector keeps
+ these layout rules winning that equal-specificity fight regardless of bundle order. */
+pre.file-preview-content {
padding: 15px;
height: 100%;
overflow: auto;
margin: 10px;
}
+/* Only when not highlighted: a highlighted block carries `hljs`, whose runtime-injected theme
+ stylesheet brings its own background (see CodeBlock.css). */
+pre.file-preview-content:not(.hljs) {
+ background-color: var(--accented-background-color);
+}
+
.note-detail-file > .pdf-preview {
width: 100%;
height: 100%;
diff --git a/apps/client/src/widgets/type_widgets/File.spec.tsx b/apps/client/src/widgets/type_widgets/File.spec.tsx
new file mode 100644
index 0000000000..6d0c2e6b8f
--- /dev/null
+++ b/apps/client/src/widgets/type_widgets/File.spec.tsx
@@ -0,0 +1,76 @@
+import { render } from "preact";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+const applySingleBlockSyntaxHighlight = vi.fn(async (_codeBlock: unknown, _normalizedMimeType: string) => {});
+const isSyntaxHighlightEnabled = vi.fn(() => true);
+
+vi.mock("../../services/syntax_highlight", () => ({
+ applySingleBlockSyntaxHighlight,
+ isSyntaxHighlightEnabled
+}));
+
+vi.mock("../../services/clipboard_ext", () => ({ copyTextWithToast: vi.fn() }));
+
+// ActionButton drags in tooltips and command wiring that are irrelevant here.
+vi.mock("../react/ActionButton", () => ({ default: () => <button class="code-block-copy" /> }));
+
+// Only TextPreview is under test; stub the sibling previews (and the blob hook they feed on)
+// so their service imports stay out of the module graph.
+vi.mock("../react/hooks", () => ({ useNoteBlob: vi.fn(() => null) }));
+vi.mock("./file/MediaPreview", () => ({ default: () => null }));
+vi.mock("./file/Pdf", () => ({ default: () => null }));
+
+const { TextPreview } = await import("./File");
+
+let container: HTMLDivElement;
+
+beforeEach(() => {
+ // TextPreview's CodeBlock hands the <code> element to jQuery before delegating to the
+ // highlighter; the identity wrapper is enough since the helper itself is mocked.
+ (globalThis as unknown as { $: (el: unknown) => unknown }).$ = (el) => el;
+ container = document.createElement("div");
+ document.body.appendChild(container);
+});
+
+afterEach(() => {
+ render(null, container);
+ container.remove();
+ vi.clearAllMocks();
+});
+
+describe("TextPreview", () => {
+ it("renders the content as text in a code block and highlights it with the normalized MIME type", async () => {
+ render(<TextPreview content={"<p>hello</p>"} mime="text/html" />, container);
+
+ const code = container.querySelector("pre.file-preview-content > code");
+ expect(code?.textContent).toBe("<p>hello</p>");
+ // Rendered verbatim rather than parsed — no element was created from it.
+ expect(container.querySelector("p")).toBeNull();
+
+ await vi.waitFor(() => expect(applySingleBlockSyntaxHighlight).toHaveBeenCalledTimes(1));
+ expect(applySingleBlockSyntaxHighlight.mock.calls[0][1]).toBe("text-html");
+ });
+
+ it("does not highlight without a MIME type, but still renders the content", () => {
+ render(<TextPreview content={"plain"} />, container);
+
+ expect(container.querySelector("pre.file-preview-content > code")?.textContent).toBe("plain");
+ expect(applySingleBlockSyntaxHighlight).not.toHaveBeenCalled();
+ });
+
+ it("truncates oversized content, shows the size warning and drops the copy button", () => {
+ render(<TextPreview content={"x".repeat(6000)} mime="text/plain" />, container);
+
+ expect(container.querySelector("pre.file-preview-content > code")?.textContent).toHaveLength(5000);
+ expect(container.querySelector(".alert")).not.toBeNull();
+ // Copying only the visible half of the file would read as copying all of it.
+ expect(container.querySelector(".code-block-copy")).toBeNull();
+ });
+
+ it("shows the copy button when the content fits the preview", () => {
+ render(<TextPreview content={"short"} mime="text/plain" />, container);
+
+ expect(container.querySelector(".alert")).toBeNull();
+ expect(container.querySelector(".code-block-copy")).not.toBeNull();
+ });
+});
diff --git a/apps/client/src/widgets/type_widgets/File.tsx b/apps/client/src/widgets/type_widgets/File.tsx
index eba2ad6a1b..30ccbfe4e9 100644
--- a/apps/client/src/widgets/type_widgets/File.tsx
+++ b/apps/client/src/widgets/type_widgets/File.tsx
@@ -2,6 +2,7 @@ import "./File.css";
import { t } from "../../services/i18n";
import Alert from "../react/Alert";
+import CodeBlock from "../react/CodeBlock";
import { useNoteBlob } from "../react/hooks";
import MediaPreview from "./file/MediaPreview";
import PdfPreview from "./file/Pdf";
@@ -13,7 +14,7 @@ export default function FileTypeWidget({ note, parentComponent, noteContext, isV
const blob = useNoteBlob(note, parentComponent?.componentId);
if (blob?.content) {
- return <TextPreview content={blob.content} />;
+ return <TextPreview content={blob.content} mime={note.mime} />;
} else if (note.mime === "application/pdf") {
return noteContext && <PdfPreview blob={blob} note={note} componentId={parentComponent?.componentId} noteContext={noteContext} />;
} else if (note.mime.startsWith("video/") || note.mime.startsWith("audio/")) {
@@ -23,7 +24,7 @@ export default function FileTypeWidget({ note, parentComponent, noteContext, isV
}
-export function TextPreview({ content }: { content: string }) {
+export function TextPreview({ content, mime }: { content: string, mime?: string }) {
const trimmedContent = content.substring(0, TEXT_MAX_NUM_CHARS);
const isTooLarge = trimmedContent.length !== content.length;
@@ -34,7 +35,14 @@ export function TextPreview({ content }: { content: string }) {
{t("file.too_big", { maxNumChars: TEXT_MAX_NUM_CHARS })}
</Alert>
)}
- <pre class="file-preview-content">{trimmedContent}</pre>
+ {/* The copy button is dropped for a truncated preview — it could only copy the visible
+ 5000 characters, which reads as copying the whole file. */}
+ <CodeBlock
+ className="file-preview-content"
+ code={trimmedContent}
+ mimeType={mime}
+ copyable={!isTooLarge}
+ />
</>
);
}