BlueGit

timfa filemanager

Pretty-print and syntax-highlight text/script file previews

timfa Tim Falken · pushed by timfa

Authored 2026-05-03 · 6 months ago

Hash
7b957c4df21e34850148fccc34654afa4bff410d
Parent
b054c31b
3 files changed +157 −2
.github/technical-reference.md +3 −0
@@ -35,6 +35,9 @@
35 35 - showOverwrite(filename) - In-page overwrite-decision dialog for file conflicts; returns Promise<'yes'|'no'|'all'|'none'>.
36 36 - loadThumbnails() - Loads per-file image thumbnails into file SVG icons after grid rendering.
37 37 - loadOneThumbnail(iconEl) - Fetches authenticated image blob and injects clipped thumbnail into a file icon SVG.
38 - detectCodeLanguage(name, mime) - Determines preview language for text/script files by MIME and extension.
39 - prettyPrintCode(raw, lang) - Best-effort formatter for JSON/markup/script previews before rendering.
40 - highlightCode(raw, lang) - Escapes and syntax-highlights preview text into HTML spans.
38 41 - fetchFileBlob(item) - Downloads a file as Blob with auth headers for preview/download flows.
39 42 - downloadOrView(item) - Opens the in-app file-preview overlay and attaches bottom download action.
40 43 - renderPreviewBody(item, blob, objectUrl) - Renders preview content (image/video/audio/pdf/text) or unsupported message.
@@ -35,6 +35,9 @@
35- showOverwrite(filename) - In-page overwrite-decision dialog for file conflicts; returns Promise<'yes'|'no'|'all'|'none'>.
35- showOverwrite(filename) - In-page overwrite-decision dialog for file conflicts; returns Promise<'yes'|'no'|'all'|'none'>.
36- loadThumbnails() - Loads per-file image thumbnails into file SVG icons after grid rendering.
36- loadThumbnails() - Loads per-file image thumbnails into file SVG icons after grid rendering.
37- loadOneThumbnail(iconEl) - Fetches authenticated image blob and injects clipped thumbnail into a file icon SVG.
37- loadOneThumbnail(iconEl) - Fetches authenticated image blob and injects clipped thumbnail into a file icon SVG.
38- detectCodeLanguage(name, mime) - Determines preview language for text/script files by MIME and extension.
39- prettyPrintCode(raw, lang) - Best-effort formatter for JSON/markup/script previews before rendering.
40- highlightCode(raw, lang) - Escapes and syntax-highlights preview text into HTML spans.
38- fetchFileBlob(item) - Downloads a file as Blob with auth headers for preview/download flows.
41- fetchFileBlob(item) - Downloads a file as Blob with auth headers for preview/download flows.
39- downloadOrView(item) - Opens the in-app file-preview overlay and attaches bottom download action.
42- downloadOrView(item) - Opens the in-app file-preview overlay and attaches bottom download action.
40- renderPreviewBody(item, blob, objectUrl) - Renders preview content (image/video/audio/pdf/text) or unsupported message.
43- renderPreviewBody(item, blob, objectUrl) - Renders preview content (image/video/audio/pdf/text) or unsupported message.
public/app.js +133 −2
@@ -1040,6 +1040,135 @@ function isTextLikeBlob (blob, name)
1040 1040 return CODE_EXTS.has(ext);
1041 1041 }
1042 1042
1043 function detectCodeLanguage (name, mime)
1044 {
1045 const ext = extOf(name || '');
1046 const m = String(mime || '').toLowerCase();
1047 if (m.includes('json') || ext === 'json') return 'json';
1048 if (m.includes('xml') || ext === 'xml') return 'xml';
1049 if (m.includes('html') || ext === 'html' || ext === 'htm') return 'html';
1050 if (m.includes('css') || ext === 'css') return 'css';
1051 if (m.includes('javascript') || ['js', 'jsx', 'mjs', 'cjs'].includes(ext)) return 'js';
1052 if (m.includes('typescript') || ['ts', 'tsx'].includes(ext)) return 'ts';
1053 if (['sh', 'bash', 'zsh'].includes(ext)) return 'sh';
1054 if (['md', 'txt', 'log', 'ini', 'toml', 'yaml', 'yml'].includes(ext)) return 'plain';
1055 return CODE_EXTS.has(ext) ? 'js' : 'plain';
1056 }
1057
1058 function prettyPrintMarkup (raw)
1059 {
1060 const src = String(raw || '')
1061 .replace(/>\s+</g, '><')
1062 .replace(/\r\n/g, '\n');
1063
1064 const lines = src.replace(/></g, '>\n<').split('\n');
1065 let indent = 0;
1066 const out = [];
1067
1068 for (const ln of lines)
1069 {
1070 const line = ln.trim();
1071 if (!line) continue;
1072 const isClose = /^<\//.test(line);
1073 const isSelf = /\/>$/.test(line) || /^<[^!?][^>]*>[^<]*<\/[^>]+>$/.test(line);
1074 const isOpen = /^<[^!?/][^>]*>$/.test(line);
1075
1076 if (isClose) indent = Math.max(0, indent - 1);
1077 out.push(' '.repeat(indent) + line);
1078 if (isOpen && !isSelf) indent += 1;
1079 }
1080
1081 return out.join('\n');
1082 }
1083
1084 function prettyPrintBraces (raw)
1085 {
1086 const lines = String(raw || '')
1087 .replace(/\r\n/g, '\n')
1088 .split('\n');
1089 let indent = 0;
1090 const out = [];
1091
1092 for (const ln of lines)
1093 {
1094 const line = ln.trim();
1095 if (!line)
1096 {
1097 out.push('');
1098 continue;
1099 }
1100 if (/^[}\])]/.test(line)) indent = Math.max(0, indent - 1);
1101 out.push(' '.repeat(indent) + line);
1102 if (/[{[(]$/.test(line) || /[{[(]\s*(\/\/.*)?$/.test(line)) indent += 1;
1103 }
1104 return out.join('\n');
1105 }
1106
1107 function prettyPrintCode (raw, lang)
1108 {
1109 const text = String(raw || '').replace(/\r\n/g, '\n');
1110 if (lang === 'json')
1111 {
1112 try { return JSON.stringify(JSON.parse(text), null, 2); } catch { return text; }
1113 }
1114 if (lang === 'xml' || lang === 'html') return prettyPrintMarkup(text);
1115 if (lang === 'js' || lang === 'ts' || lang === 'css') return prettyPrintBraces(text);
1116 return text;
1117 }
1118
1119 function escapeHtml (s)
1120 {
1121 return String(s)
1122 .replace(/&/g, '&amp;')
1123 .replace(/</g, '&lt;')
1124 .replace(/>/g, '&gt;');
1125 }
1126
1127 function highlightCode (raw, lang)
1128 {
1129 if (lang === 'plain') return escapeHtml(raw);
1130
1131 let html = escapeHtml(raw);
1132 const stash = [];
1133 const keep = (regex, cls) =>
1134 {
1135 html = html.replace(regex, (m) =>
1136 {
1137 const idx = stash.push(`<span class="tok-${cls}">${m}</span>`) - 1;
1138 return `@@TOK${idx}@@`;
1139 });
1140 };
1141
1142 if (lang === 'json')
1143 {
1144 html = html
1145 .replace(/("(?:\\.|[^"\\])*")\s*:/g, '<span class="tok-key">$1</span>:')
1146 .replace(/: ("(?:\\.|[^"\\])*")/g, ': <span class="tok-string">$1</span>')
1147 .replace(/\b(true|false|null)\b/g, '<span class="tok-keyword">$1</span>')
1148 .replace(/\b(-?\d+(?:\.\d+)?(?:e[+\-]?\d+)?)\b/gi, '<span class="tok-number">$1</span>');
1149 return html;
1150 }
1151
1152 if (lang === 'xml' || lang === 'html')
1153 {
1154 html = html
1155 .replace(/(&lt;\/?)([a-zA-Z0-9:_-]+)/g, '$1<span class="tok-keyword">$2</span>')
1156 .replace(/([a-zA-Z0-9:_-]+)=(&quot;[^&]*&quot;|"[^"]*")/g, '<span class="tok-key">$1</span>=<span class="tok-string">$2</span>');
1157 return html;
1158 }
1159
1160 if (lang === 'sh') keep(/(^|\s)#.*$/gm, 'comment');
1161 else keep(/\/\*[\s\S]*?\*\/|\/\/[^\n]*/g, 'comment');
1162 keep(/"(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'|`(?:\\.|[^`\\])*`/g, 'string');
1163
1164 html = html
1165 .replace(/\b(function|return|if|else|for|while|switch|case|break|continue|const|let|var|class|new|import|from|export|default|try|catch|finally|throw|await|async|true|false|null|undefined)\b/g, '<span class="tok-keyword">$1</span>')
1166 .replace(/\b(-?\d+(?:\.\d+)?(?:e[+\-]?\d+)?)\b/gi, '<span class="tok-number">$1</span>');
1167
1168 html = html.replace(/@@TOK(\d+)@@/g, (_, idx) => stash[Number(idx)] || '');
1169 return html;
1170 }
1171
1043 1172 function clearPreviewObjectUrl ()
1044 1173 {
1045 1174 if (!STATE.previewObjectUrl) return;
@@ -1145,9 +1274,11 @@ async function renderPreviewBody (item, blob, objectUrl)
1145 1274 if (isTextLikeBlob(blob, item.name))
1146 1275 {
1147 1276 const text = await blob.text();
1277 const lang = detectCodeLanguage(item.name, mime);
1278 const formatted = prettyPrintCode(text, lang);
1148 1279 const pre = document.createElement('pre');
1149 pre.className = 'preview-text';
1150 pre.textContent = text;
1280 pre.className = 'preview-text preview-code';
1281 pre.innerHTML = highlightCode(formatted, lang);
1151 1282 body.appendChild(pre);
1152 1283 return;
1153 1284 }
@@ -1040,6 +1040,135 @@ function isTextLikeBlob (blob, name)
1040 return CODE_EXTS.has(ext);
1040 return CODE_EXTS.has(ext);
1041}
1041}
1042
1042
1043function detectCodeLanguage (name, mime)
1044{
1045 const ext = extOf(name || '');
1046 const m = String(mime || '').toLowerCase();
1047 if (m.includes('json') || ext === 'json') return 'json';
1048 if (m.includes('xml') || ext === 'xml') return 'xml';
1049 if (m.includes('html') || ext === 'html' || ext === 'htm') return 'html';
1050 if (m.includes('css') || ext === 'css') return 'css';
1051 if (m.includes('javascript') || ['js', 'jsx', 'mjs', 'cjs'].includes(ext)) return 'js';
1052 if (m.includes('typescript') || ['ts', 'tsx'].includes(ext)) return 'ts';
1053 if (['sh', 'bash', 'zsh'].includes(ext)) return 'sh';
1054 if (['md', 'txt', 'log', 'ini', 'toml', 'yaml', 'yml'].includes(ext)) return 'plain';
1055 return CODE_EXTS.has(ext) ? 'js' : 'plain';
1056}
1057
1058function prettyPrintMarkup (raw)
1059{
1060 const src = String(raw || '')
1061 .replace(/>\s+</g, '><')
1062 .replace(/\r\n/g, '\n');
1063
1064 const lines = src.replace(/></g, '>\n<').split('\n');
1065 let indent = 0;
1066 const out = [];
1067
1068 for (const ln of lines)
1069 {
1070 const line = ln.trim();
1071 if (!line) continue;
1072 const isClose = /^<\//.test(line);
1073 const isSelf = /\/>$/.test(line) || /^<[^!?][^>]*>[^<]*<\/[^>]+>$/.test(line);
1074 const isOpen = /^<[^!?/][^>]*>$/.test(line);
1075
1076 if (isClose) indent = Math.max(0, indent - 1);
1077 out.push(' '.repeat(indent) + line);
1078 if (isOpen && !isSelf) indent += 1;
1079 }
1080
1081 return out.join('\n');
1082}
1083
1084function prettyPrintBraces (raw)
1085{
1086 const lines = String(raw || '')
1087 .replace(/\r\n/g, '\n')
1088 .split('\n');
1089 let indent = 0;
1090 const out = [];
1091
1092 for (const ln of lines)
1093 {
1094 const line = ln.trim();
1095 if (!line)
1096 {
1097 out.push('');
1098 continue;
1099 }
1100 if (/^[}\])]/.test(line)) indent = Math.max(0, indent - 1);
1101 out.push(' '.repeat(indent) + line);
1102 if (/[{[(]$/.test(line) || /[{[(]\s*(\/\/.*)?$/.test(line)) indent += 1;
1103 }
1104 return out.join('\n');
1105}
1106
1107function prettyPrintCode (raw, lang)
1108{
1109 const text = String(raw || '').replace(/\r\n/g, '\n');
1110 if (lang === 'json')
1111 {
1112 try { return JSON.stringify(JSON.parse(text), null, 2); } catch { return text; }
1113 }
1114 if (lang === 'xml' || lang === 'html') return prettyPrintMarkup(text);
1115 if (lang === 'js' || lang === 'ts' || lang === 'css') return prettyPrintBraces(text);
1116 return text;
1117}
1118
1119function escapeHtml (s)
1120{
1121 return String(s)
1122 .replace(/&/g, '&amp;')
1123 .replace(/</g, '&lt;')
1124 .replace(/>/g, '&gt;');
1125}
1126
1127function highlightCode (raw, lang)
1128{
1129 if (lang === 'plain') return escapeHtml(raw);
1130
1131 let html = escapeHtml(raw);
1132 const stash = [];
1133 const keep = (regex, cls) =>
1134 {
1135 html = html.replace(regex, (m) =>
1136 {
1137 const idx = stash.push(`<span class="tok-${cls}">${m}</span>`) - 1;
1138 return `@@TOK${idx}@@`;
1139 });
1140 };
1141
1142 if (lang === 'json')
1143 {
1144 html = html
1145 .replace(/("(?:\\.|[^"\\])*")\s*:/g, '<span class="tok-key">$1</span>:')
1146 .replace(/: ("(?:\\.|[^"\\])*")/g, ': <span class="tok-string">$1</span>')
1147 .replace(/\b(true|false|null)\b/g, '<span class="tok-keyword">$1</span>')
1148 .replace(/\b(-?\d+(?:\.\d+)?(?:e[+\-]?\d+)?)\b/gi, '<span class="tok-number">$1</span>');
1149 return html;
1150 }
1151
1152 if (lang === 'xml' || lang === 'html')
1153 {
1154 html = html
1155 .replace(/(&lt;\/?)([a-zA-Z0-9:_-]+)/g, '$1<span class="tok-keyword">$2</span>')
1156 .replace(/([a-zA-Z0-9:_-]+)=(&quot;[^&]*&quot;|"[^"]*")/g, '<span class="tok-key">$1</span>=<span class="tok-string">$2</span>');
1157 return html;
1158 }
1159
1160 if (lang === 'sh') keep(/(^|\s)#.*$/gm, 'comment');
1161 else keep(/\/\*[\s\S]*?\*\/|\/\/[^\n]*/g, 'comment');
1162 keep(/"(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'|`(?:\\.|[^`\\])*`/g, 'string');
1163
1164 html = html
1165 .replace(/\b(function|return|if|else|for|while|switch|case|break|continue|const|let|var|class|new|import|from|export|default|try|catch|finally|throw|await|async|true|false|null|undefined)\b/g, '<span class="tok-keyword">$1</span>')
1166 .replace(/\b(-?\d+(?:\.\d+)?(?:e[+\-]?\d+)?)\b/gi, '<span class="tok-number">$1</span>');
1167
1168 html = html.replace(/@@TOK(\d+)@@/g, (_, idx) => stash[Number(idx)] || '');
1169 return html;
1170}
1171
1043function clearPreviewObjectUrl ()
1172function clearPreviewObjectUrl ()
1044{
1173{
1045 if (!STATE.previewObjectUrl) return;
1174 if (!STATE.previewObjectUrl) return;
@@ -1145,9 +1274,11 @@ async function renderPreviewBody (item, blob, objectUrl)
1145 if (isTextLikeBlob(blob, item.name))
1274 if (isTextLikeBlob(blob, item.name))
1146 {
1275 {
1147 const text = await blob.text();
1276 const text = await blob.text();
1277 const lang = detectCodeLanguage(item.name, mime);
1278 const formatted = prettyPrintCode(text, lang);
1148 const pre = document.createElement('pre');
1279 const pre = document.createElement('pre');
1149 pre.className = 'preview-text';
1280 pre.className = 'preview-text preview-code';
1150 pre.textContent = text;
1281 pre.innerHTML = highlightCode(formatted, lang);
1151 body.appendChild(pre);
1282 body.appendChild(pre);
1152 return;
1283 return;
1153 }
1284 }
public/style.css +21 −0
@@ -729,6 +729,27 @@ button.danger:hover {
729 729 white-space: pre;
730 730 }
731 731
732 .preview-code .tok-comment {
733 color: #6f7f9a;
734 }
735
736 .preview-code .tok-string {
737 color: #9ee37d;
738 }
739
740 .preview-code .tok-number {
741 color: #f8c46a;
742 }
743
744 .preview-code .tok-keyword {
745 color: #8bb4ff;
746 font-weight: 600;
747 }
748
749 .preview-code .tok-key {
750 color: #59c8ff;
751 }
752
732 753 .preview-unsupported {
733 754 color: var(--text-muted);
734 755 font-size: 0.95rem;
@@ -729,6 +729,27 @@ button.danger:hover {
729 white-space: pre;
729 white-space: pre;
730}
730}
731
731
732.preview-code .tok-comment {
733 color: #6f7f9a;
734}
735
736.preview-code .tok-string {
737 color: #9ee37d;
738}
739
740.preview-code .tok-number {
741 color: #f8c46a;
742}
743
744.preview-code .tok-keyword {
745 color: #8bb4ff;
746 font-weight: 600;
747}
748
749.preview-code .tok-key {
750 color: #59c8ff;
751}
752
732.preview-unsupported {
753.preview-unsupported {
733 color: var(--text-muted);
754 color: var(--text-muted);
734 font-size: 0.95rem;
755 font-size: 0.95rem;