Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

💄 style(file-viewer): format minified JSON in the file preview (#22635)

Rdmclin218015be0c02a
diff --git a/src/features/FileViewer/Renderer/Code/formatJson.test.ts b/src/features/FileViewer/Renderer/Code/formatJson.test.ts
new file mode 100644
index 00000000000..31e8bef79fc
--- /dev/null
+++ b/src/features/FileViewer/Renderer/Code/formatJson.test.ts
@@ -0,0 +1,105 @@
+import { describe, expect, it } from 'vitest';
+
+import { formatJsonForPreview } from './formatJson';
+
+describe('formatJsonForPreview', () => {
+ it('indents a minified JSON document', () => {
+ const input =
+ '{"id":"speech-2.8-hd","type":"tts","pricing":{"units":[{"rate":100}]},"tags":[]}';
+
+ expect(formatJsonForPreview(input, 'json')).toBe(
+ [
+ '{',
+ ' "id": "speech-2.8-hd",',
+ ' "type": "tts",',
+ ' "pricing": {',
+ ' "units": [',
+ ' {',
+ ' "rate": 100',
+ ' }',
+ ' ]',
+ ' },',
+ ' "tags": []',
+ '}',
+ ].join('\n'),
+ );
+ });
+
+ it('matches JSON.stringify indentation for ordinary values', () => {
+ const value = { a: [1, true, null, { b: 'x' }], c: {}, d: -1.5e3, e: '' };
+ const input = JSON.stringify(value);
+
+ expect(formatJsonForPreview(input, 'json')).toBe(JSON.stringify(value, null, 2));
+ });
+
+ it('keeps structural characters and escapes inside strings untouched', () => {
+ const input = String.raw`{"text":"a, b: {c} [d] \"quoted\" \\","path":"C:\\dir"}`;
+
+ const output = formatJsonForPreview(input, 'json');
+
+ expect(output).toBe(
+ [
+ '{',
+ String.raw` "text": "a, b: {c} [d] \"quoted\" \\",`,
+ String.raw` "path": "C:\\dir"`,
+ '}',
+ ].join('\n'),
+ );
+ expect(JSON.parse(output)).toEqual(JSON.parse(input));
+ });
+
+ it('preserves number literals that JSON.stringify would rewrite', () => {
+ const input = '{"id":12345678901234567890,"ratio":1.0,"tiny":1E-7}';
+
+ expect(formatJsonForPreview(input, 'json')).toBe(
+ ['{', ' "id": 12345678901234567890,', ' "ratio": 1.0,', ' "tiny": 1E-7', '}'].join('\n'),
+ );
+ });
+
+ it('formats a minified document with a trailing newline and inner spaces', () => {
+ expect(formatJsonForPreview('{ "a" : [ 1 , 2 ] , "b" : { } }\n', 'json')).toBe(
+ ['{', ' "a": [', ' 1,', ' 2', ' ],', ' "b": {}', '}'].join('\n'),
+ );
+ });
+
+ it('returns invalid JSON unchanged', () => {
+ const input = '{"a":1,}';
+
+ expect(formatJsonForPreview(input, 'json')).toBe(input);
+ });
+
+ it('keeps multi-line JSON in the author layout', () => {
+ const input = '{\n "a": [1, 2, 3]\n}\n';
+
+ expect(formatJsonForPreview(input, 'json')).toBe(input);
+ });
+
+ it('leaves other languages and scalar documents alone', () => {
+ expect(formatJsonForPreview('{"a":1}', 'javascript')).toBe('{"a":1}');
+ expect(formatJsonForPreview('"plain"', 'json')).toBe('"plain"');
+ expect(formatJsonForPreview('', 'json')).toBe('');
+ });
+
+ it('keeps documents too large or too deeply nested to format raw', () => {
+ const large = JSON.stringify(Array.from({ length: 200_000 }, () => 1));
+ const deep = '['.repeat(100) + ']'.repeat(100);
+
+ expect(formatJsonForPreview(large, 'json')).toBe(large);
+ expect(formatJsonForPreview(deep, 'json')).toBe(deep);
+ });
+
+ it('keeps documents that would format into too many lines raw', () => {
+ const manyValues = JSON.stringify(Array.from({ length: 20_000 }, () => 0));
+
+ expect(manyValues.length).toBeLessThan(256 * 1024);
+ expect(formatJsonForPreview(manyValues, 'json')).toBe(manyValues);
+ });
+
+ it('keeps CR-only and CRLF multi-line JSON in the author layout', () => {
+ const crOnly = '{\r "a": 1\r}';
+ const crlf = '{\r\n "a": 1\r\n}';
+
+ expect(formatJsonForPreview(crOnly, 'json')).toBe(crOnly);
+ expect(formatJsonForPreview(crlf, 'json')).toBe(crlf);
+ });
+});
diff --git a/src/features/FileViewer/Renderer/Code/formatJson.ts b/src/features/FileViewer/Renderer/Code/formatJson.ts
new file mode 100644
index 00000000000..910359a2207
--- /dev/null
+++ b/src/features/FileViewer/Renderer/Code/formatJson.ts
@@ -0,0 +1,113 @@
+const INDENT = ' ';
+/** Larger documents stay raw without scanning them. */
+const MAX_FORMAT_LENGTH = 256 * 1024;
+/** Deeper nesting stays raw: indentation grows with depth, so pathological nesting would explode the output. */
+const MAX_FORMAT_DEPTH = 64;
+/** Output budget: past this many lines the highlighter no longer renders the preview smoothly. */
+const MAX_FORMAT_LINES = 10_000;
+
+const isWhitespace = (char: string) =>
+ char === ' ' || char === '\n' || char === '\r' || char === '\t';
+
+/**
+ * Re-indent valid JSON text without parsing its values.
+ *
+ * Use when:
+ * - The text is already known to be valid JSON.
+ *
+ * Returns:
+ * - The same tokens with two-space indentation; numbers, strings and escape
+ * sequences are copied verbatim, so large integers keep their precision.
+ * - `null` when nesting exceeds `MAX_FORMAT_DEPTH` or the output would exceed
+ * `MAX_FORMAT_LINES`; with both caps each line stays short, so the output is bounded.
+ */
+const reindentJson = (text: string): string | null => {
+ const out: string[] = [];
+ let depth = 0;
+ let lines = 1;
+ let i = 0;
+
+ const newline = () => {
+ lines += 1;
+ return `\n${INDENT.repeat(depth)}`;
+ };
+
+ while (i < text.length) {
+ const char = text[i];
+
+ if (char === '"') {
+ let end = i + 1;
+ while (end < text.length && text[end] !== '"') end += text[end] === '\\' ? 2 : 1;
+ out.push(text.slice(i, end + 1));
+ i = end + 1;
+ continue;
+ }
+
+ if (isWhitespace(char)) {
+ i += 1;
+ continue;
+ }
+
+ if (char === '{' || char === '[') {
+ let next = i + 1;
+ while (next < text.length && isWhitespace(text[next])) next += 1;
+ const close = char === '{' ? '}' : ']';
+ if (text[next] === close) {
+ out.push(char + close);
+ i = next + 1;
+ continue;
+ }
+ depth += 1;
+ if (depth > MAX_FORMAT_DEPTH) return null;
+ out.push(char, newline());
+ } else if (char === '}' || char === ']') {
+ depth -= 1;
+ out.push(newline(), char);
+ } else if (char === ',') {
+ out.push(',', newline());
+ } else if (char === ':') {
+ out.push(': ');
+ } else {
+ let end = i + 1;
+ while (end < text.length && !isWhitespace(text[end]) && !',:]}'.includes(text[end])) end += 1;
+ out.push(text.slice(i, end));
+ i = end;
+ continue;
+ }
+
+ if (lines > MAX_FORMAT_LINES) return null;
+ i += 1;
+ }
+
+ return out.join('');
+};
+
+/**
+ * Prepare JSON file text for the read-only code preview.
+ *
+ * Use when:
+ * - Rendering a file whose detected language is `json`.
+ *
+ * Expects:
+ * - The decoded file text and the language from `getLanguageFromFilename`.
+ *
+ * Returns:
+ * - Indented JSON for valid single-line (minified) documents; the original text
+ * for other languages, invalid JSON, files the author already laid out across
+ * several lines (LF, CRLF or CR), and documents too large, too deeply nested
+ * or producing too many lines to format.
+ */
+export const formatJsonForPreview = (text: string, language: string): string => {
+ if (language !== 'json') return text;
+
+ const trimmed = text.trim();
+ if (!trimmed || trimmed.length > MAX_FORMAT_LENGTH || /[\n\r]/.test(trimmed)) return text;
+
+ try {
+ JSON.parse(trimmed);
+ } catch {
+ return text;
+ }
+
+ return reindentJson(trimmed) ?? text;
+};
diff --git a/src/features/FileViewer/Renderer/Code/index.tsx b/src/features/FileViewer/Renderer/Code/index.tsx
index a799e016701..6b213a2393e 100644
--- a/src/features/FileViewer/Renderer/Code/index.tsx
+++ b/src/features/FileViewer/Renderer/Code/index.tsx
@@ -1,13 +1,14 @@
'use client';
import { Center, createStaticStyles, Flexbox, Highlighter, Spin } from '@lobehub/ui';
-import { memo } from 'react';
+import { memo, useMemo } from 'react';
import AsyncError from '@/components/AsyncError';
import { getLanguageFromFilename } from '@/utils/fileLanguage';
import { useTextFileLoader } from '../../hooks/useTextFileLoader';
import NotSupport from '../../NotSupport';
+import { formatJsonForPreview } from './formatJson';
const styles = createStaticStyles(({ css }) => ({
page: css`
@@ -26,6 +27,10 @@ interface CodeViewerProps {
const CodeViewer = memo<CodeViewerProps>(({ url, fileName }) => {
const { error, fileData, loading, tooLarge } = useTextFileLoader(url);
const language = getLanguageFromFilename(fileName);
+ const content = useMemo(
+ () => (fileData === null ? null : formatJsonForPreview(fileData, language)),
+ [fileData, language],
+ );
if (!loading && fileData === null)
return (
@@ -37,9 +42,9 @@ const CodeViewer = memo<CodeViewerProps>(({ url, fileName }) => {
return (
<Flexbox className={styles.page}>
- {!loading && fileData !== null ? (
+ {!loading && content !== null ? (
<Highlighter language={language} showLanguage={false} variant={'borderless'}>
- {fileData}
+ {content}
</Highlighter>
) : (
<Center height={'100%'}>