/* texrra web frontend. Served by texrra-engine at /app.js. */
"use strict";
const $ = selector => document.querySelector(selector);
const projectsView = $("#projects-view");
const workspace = $("#workspace");
const projectGrid = $("#project-grid");
const projectsEmpty = $("#projects-empty");
const fileTree = $("#file-tree");
const sourceEditor = $("#source");
const binaryNotice = $("#binary-notice");
const assetPreview = $("#asset-preview");
const pages = $("#pages");
const previewError = $("#preview-error");
const previewErrorText = $("#preview-error-text");
const previewStatus = $("#preview-status");
const engineButton = $("#toggle-engine");
const saveStatus = $("#save-status");
const openFilePath = $("#open-file-path");
const projectTitle = $("#project-title");
const filePanelFoot = $("#file-panel-foot");
const contextMenu = $("#context-menu");
const toastElement = $("#toast");
const IMAGE_EXTENSIONS = ["png", "jpg", "jpeg", "gif", "bmp", "webp", "svg"];
const TEXT_EXTENSIONS = ["tex", "sty", "cls", "bib", "bst", "txt", "md", "csv", "json", "yaml", "yml", "cfg", "dat", "tikz", "ltx"];
function initialEngine() {
const stored = localStorage.getItem("texrra-engine");
if (stored === "v1") return "v1";
if (stored === "route-d") return "route-d";
// Old boolean key: "0" meant v1, "1" or absent meant route-D.
return localStorage.getItem("texrra-route-d") === "0" ? "v1" : "route-d";
}
const state = {
projects: [],
project: null,
file: null,
fileIsBinary: false,
dirty: false,
saveTimer: 0,
previewTimer: 0,
previewController: null,
previewRequest: 0,
toastTimer: 0,
engine: initialEngine(),
};
function escapeHtml(value) {
return String(value).replace(/[&<>"']/g, character => ({
"&": "&", "<": "<", ">": ">", '"': """, "'": "'"
}[character]));
}
function extensionOf(path) {
const index = path.lastIndexOf(".");
return index === -1 ? "" : path.slice(index + 1).toLowerCase();
}
function isImage(path) {
return IMAGE_EXTENSIONS.includes(extensionOf(path));
}
function isText(path) {
const extension = extensionOf(path);
return extension === "" || TEXT_EXTENSIONS.includes(extension);
}
function triggersPreview(path) {
return ["tex", "sty", "cls", "bib"].includes(extensionOf(path));
}
function formatBytes(size) {
if (size < 1024) return `${size} B`;
if (size < 1024 * 1024) return `${(size / 1024).toFixed(1)} KB`;
return `${(size / (1024 * 1024)).toFixed(1)} MB`;
}
function formatDate(seconds) {
if (!seconds) return "";
const date = new Date(seconds * 1000);
const pad = value => String(value).padStart(2, "0");
return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())} ${pad(date.getHours())}:${pad(date.getMinutes())}`;
}
function toast(message, isError) {
toastElement.textContent = message;
toastElement.className = isError ? "error" : "";
toastElement.hidden = false;
clearTimeout(state.toastTimer);
state.toastTimer = setTimeout(() => { toastElement.hidden = true; }, isError ? 6000 : 3200);
}
async function api(path, options) {
const response = await fetch(path, options);
const type = response.headers.get("content-type") || "";
const payload = type.includes("application/json") ? await response.json() : await response.text();
if (!response.ok) {
const message = payload && payload.error ? payload.error : (payload && payload.message ? payload.message : payload);
throw new Error(typeof message === "string" && message ? message : `HTTP ${response.status}`);
}
return payload;
}
function projectPath(path) {
return `/api/projects/${encodeURIComponent(state.project.id)}${path}`;
}
function setSaveStatus(text) {
saveStatus.textContent = text || "";
}
function setPreviewStatus(text) {
previewStatus.textContent = text || "";
previewStatus.title = "";
}
function route() {
const hash = location.hash.replace(/^#/, "") || "/";
const match = hash.match(/^\/p\/([^/]+)$/);
if (match) {
openProject(decodeURIComponent(match[1]));
} else {
showProjects();
}
}
async function showProjects() {
state.project = null;
state.file = null;
workspace.hidden = true;
projectsView.hidden = false;
renderHeader();
try {
const payload = await api("/api/projects");
state.projects = payload.projects;
renderProjects();
} catch (error) {
toast(`无法加载项目:${error.message}`, true);
}
}
function renderHeader() {
const actions = $("#header-actions");
actions.textContent = "";
if (state.project) {
const back = document.createElement("button");
back.className = "btn";
back.textContent = "全部项目";
back.addEventListener("click", () => { location.hash = "#/"; });
actions.appendChild(back);
const download = document.createElement("button");
download.className = "btn";
download.textContent = "下载项目 ZIP";
download.addEventListener("click", () => downloadProject(state.project));
actions.appendChild(download);
}
}
function renderProjects() {
projectGrid.textContent = "";
projectsEmpty.hidden = state.projects.length > 0;
for (const project of state.projects) {
projectGrid.appendChild(projectCard(project));
}
}
function projectCard(project) {
const card = document.createElement("article");
card.className = "project-card";
const badge = document.createElement("div");
badge.className = "project-badge";
badge.textContent = "TEX";
card.appendChild(badge);
const body = document.createElement("div");
body.className = "project-body";
const title = document.createElement("h3");
title.textContent = project.name;
title.title = project.name;
body.appendChild(title);
const totalSize = project.files.reduce((sum, file) => sum + file.size, 0);
const meta = document.createElement("p");
meta.className = "project-meta";
meta.textContent = `${project.files.length} 个文件 · ${formatBytes(totalSize)} · ${formatDate(project.updatedAt)}`;
body.appendChild(meta);
const main = document.createElement("p");
main.className = "project-meta";
main.textContent = project.mainFile ? `主文件:${project.mainFile}` : "没有 TeX 文件";
body.appendChild(main);
const actions = document.createElement("div");
actions.className = "project-actions";
const open = document.createElement("button");
open.className = "btn primary";
open.textContent = "打开";
open.addEventListener("click", () => { location.hash = `#/p/${encodeURIComponent(project.id)}`; });
actions.appendChild(open);
const download = document.createElement("button");
download.className = "btn";
download.textContent = "下载";
download.addEventListener("click", () => downloadProject(project));
actions.appendChild(download);
const remove = document.createElement("button");
remove.className = "btn danger";
remove.textContent = "删除";
remove.addEventListener("click", () => deleteProject(project));
actions.appendChild(remove);
body.appendChild(actions);
card.appendChild(body);
return card;
}
async function uploadZip(file) {
if (!file) return;
if (!/\.zip$/i.test(file.name)) {
toast("请选择 .zip 压缩包", true);
return;
}
const name = file.name.replace(/\.zip$/i, "");
try {
const project = await api(`/api/projects?name=${encodeURIComponent(name)}`, {
method: "POST",
headers: { "Content-Type": "application/zip" },
body: file,
});
toast(`项目「${project.name}」已上传`);
location.hash = `#/p/${encodeURIComponent(project.id)}`;
} catch (error) {
toast(`上传失败:${error.message}`, true);
}
}
async function deleteProject(project) {
if (!confirm(`删除项目「${project.name}」?此操作不可恢复。`)) return;
try {
await api(`/api/projects/${encodeURIComponent(project.id)}`, { method: "DELETE" });
toast("项目已删除");
await refreshProjects();
} catch (error) {
toast(`删除失败:${error.message}`, true);
}
}
async function refreshProjects() {
const payload = await api("/api/projects");
state.projects = payload.projects;
renderProjects();
}
function downloadProject(project) {
const anchor = document.createElement("a");
anchor.href = `/api/projects/${encodeURIComponent(project.id)}/zip`;
anchor.download = `${project.id}.zip`;
document.body.appendChild(anchor);
anchor.click();
anchor.remove();
}
function downloadFile(path) {
const anchor = document.createElement("a");
anchor.href = projectPath(`/raw?download=1&path=${encodeURIComponent(path)}`);
anchor.download = path.split("/").pop();
document.body.appendChild(anchor);
anchor.click();
anchor.remove();
}
async function openProject(id) {
try {
const project = await api(`/api/projects/${encodeURIComponent(id)}`);
state.project = project;
state.file = null;
state.dirty = false;
projectsView.hidden = true;
workspace.hidden = false;
projectTitle.textContent = project.name;
renderHeader();
renderFileTree();
const initial = project.mainFile && project.files.some(file => file.path === project.mainFile)
? project.mainFile
: (project.files.find(file => file.path.endsWith(".tex")) || project.files[0] || {}).path;
if (initial) {
await openFile(initial);
} else {
clearEditor("这个项目还没有文件。");
}
} catch (error) {
toast(`无法打开项目:${error.message}`, true);
location.hash = "#/";
showProjects();
}
}
function fileBadge(path, isMain) {
const extension = extensionOf(path);
let className = "file-badge";
let label = extension ? extension.slice(0, 3).toUpperCase() : "FILE";
if (extension === "tex") className += " tex";
else if (IMAGE_EXTENSIONS.includes(extension)) { className += " img"; label = "IMG"; }
else if (extension === "bib") className += " bib";
else if (extension === "sty" || extension === "cls") className += " sty";
if (isMain) className += " main";
return `${escapeHtml(extension ? label : "")}`;
}
function renderFileTree() {
if (!state.project) return;
const root = { folders: new Map(), files: [] };
for (const file of state.project.files) {
const parts = file.path.split("/");
let node = root;
for (let index = 0; index < parts.length - 1; index += 1) {
if (!node.folders.has(parts[index])) {
node.folders.set(parts[index], { folders: new Map(), files: [] });
}
node = node.folders.get(parts[index]);
}
node.files.push({ path: file.path, name: parts[parts.length - 1], size: file.size });
}
fileTree.textContent = "";
fileTree.appendChild(renderTreeLevel(root, true));
const totalSize = state.project.files.reduce((sum, file) => sum + file.size, 0);
filePanelFoot.textContent = `${state.project.files.length} 个文件 · ${formatBytes(totalSize)}`;
}
function renderTreeLevel(node, isRoot) {
const container = document.createElement("div");
if (!isRoot) container.className = "tree-children";
for (const name of Array.from(node.folders.keys()).sort()) {
const folder = document.createElement("div");
folder.className = "tree-folder";
const row = document.createElement("div");
row.className = "tree-row";
row.innerHTML = `▾${escapeHtml(name)}`;
row.addEventListener("click", () => {
folder.classList.toggle("collapsed");
row.querySelector(".caret").textContent = folder.classList.contains("collapsed") ? "▸" : "▾";
});
folder.appendChild(row);
folder.appendChild(renderTreeLevel(node.folders.get(name), false));
container.appendChild(folder);
}
const sortedFiles = node.files.slice().sort((left, right) => left.name.localeCompare(right.name));
for (const file of sortedFiles) {
const row = document.createElement("div");
row.className = "tree-row file-row";
if (state.file === file.path) row.classList.add("active");
row.dataset.path = file.path;
row.innerHTML = `${fileBadge(file.path, state.project.mainFile === file.path)}${escapeHtml(file.name)}`;
row.title = `${file.path} · ${formatBytes(file.size)}`;
row.addEventListener("click", () => openFile(file.path));
row.addEventListener("contextmenu", event => showContextMenu(event, file.path));
container.appendChild(row);
}
return container;
}
function markActiveFile() {
for (const row of fileTree.querySelectorAll(".tree-row.file-row")) {
row.classList.toggle("active", row.dataset.path === state.file);
}
}
function clearEditor(message) {
sourceEditor.value = "";
sourceEditor.readOnly = true;
sourceEditor.hidden = true;
binaryNotice.hidden = false;
$("#binary-icon").textContent = "▤";
$("#binary-text").textContent = message;
$("#binary-download").hidden = true;
openFilePath.textContent = "未打开文件";
pages.textContent = "";
pages.hidden = false;
assetPreview.hidden = true;
setPreviewStatus("");
hidePreviewError();
state.file = null;
}
async function openFile(path) {
if (state.dirty) await saveFile();
state.file = path;
state.fileIsBinary = !isText(path);
openFilePath.textContent = path;
state.dirty = false;
markActiveFile();
hidePreviewError();
if (state.fileIsBinary) {
sourceEditor.hidden = true;
sourceEditor.readOnly = true;
binaryNotice.hidden = false;
$("#binary-icon").textContent = isImage(path) ? "▣" : "▤";
$("#binary-text").textContent = isImage(path) ? "图片文件,右侧显示预览。" : "这个文件是二进制文件,无法在编辑器中打开。";
$("#binary-download").hidden = false;
$("#binary-download").onclick = event => { event.preventDefault(); downloadFile(path); };
pages.textContent = "";
if (isImage(path)) {
pages.hidden = true;
assetPreview.hidden = false;
assetPreview.src = projectPath(`/raw?path=${encodeURIComponent(path)}&v=${Date.now()}`);
setPreviewStatus("图片预览");
} else {
pages.hidden = true;
assetPreview.hidden = true;
setPreviewStatus("二进制文件");
}
setSaveStatus("");
return;
}
try {
const response = await fetch(projectPath(`/raw?path=${encodeURIComponent(path)}`));
if (!response.ok) throw new Error(`HTTP ${response.status}`);
sourceEditor.value = await response.text();
sourceEditor.readOnly = false;
sourceEditor.hidden = false;
binaryNotice.hidden = true;
pages.hidden = false;
assetPreview.hidden = true;
setSaveStatus("已加载");
if (triggersPreview(path)) {
schedulePreview(10);
} else {
setPreviewStatus("当前文件不触发排版");
}
} catch (error) {
clearEditor(`无法读取 ${path}:${error.message}`);
}
}
async function saveFile() {
if (!state.project || !state.file || state.fileIsBinary) return;
const path = state.file;
try {
await api(projectPath(`/file?path=${encodeURIComponent(path)}`), {
method: "PUT",
headers: { "Content-Type": "text/plain; charset=utf-8" },
body: sourceEditor.value,
});
if (state.file === path) {
state.dirty = false;
setSaveStatus("已保存");
if (triggersPreview(path)) schedulePreview(10);
}
} catch (error) {
setSaveStatus("保存失败");
toast(`保存失败:${error.message}`, true);
}
}
function scheduleSave() {
clearTimeout(state.saveTimer);
state.saveTimer = setTimeout(saveFile, 450);
}
function engineQuery() {
return state.engine === "route-d" ? "?engine=route-d" : "?engine=v1";
}
function updateEngineButton() {
engineButton.textContent =
state.engine === "route-d" ? "引擎: Route-D (实验)" : "引擎: v1";
engineButton.classList.toggle("primary", state.engine === "route-d");
}
function schedulePreview(delay) {
clearTimeout(state.previewTimer);
state.previewTimer = setTimeout(refreshPreview, delay === undefined ? 90 : delay);
}
async function refreshPreview() {
if (!state.project || state.fileIsBinary) return;
const requestId = ++state.previewRequest;
if (state.previewController) state.previewController.abort();
const controller = new AbortController();
state.previewController = controller;
setPreviewStatus("排版中…");
try {
const requestedPatch = state.engine === "route-d";
const response = await fetch(
projectPath("/preview") +
engineQuery() +
"&buffer=1" +
(requestedPatch ? "&patch=1" : ""),
{
method: "POST",
headers: { "Content-Type": "text/plain; charset=utf-8" },
body: sourceEditor.value,
signal: controller.signal,
}
);
const actualEngine =
response.headers.get("X-Preview-Engine") ||
(state.engine === "route-d" ? "route-d" : "v1");
const patchMode = requestedPatch && actualEngine === "route-d";
if (requestId !== state.previewRequest) return;
const payload = await response.json();
if (requestId !== state.previewRequest) return;
if (payload.status === "ok") {
if (patchMode) {
applyPagePatches(payload);
} else {
applyPages(payload.pages);
}
hidePreviewError();
const count = payload.pageCount ?? payload.pages.length;
const warnings = Array.isArray(payload.warnings) ? payload.warnings : [];
const duration =
typeof payload.durationMs === "number"
? `${payload.durationMs.toFixed(1)} ms`
: "—";
const fallback = actualEngine !== state.engine ? ` · 实际 ${actualEngine}` : "";
const warningText = warnings.length ? ` · ${warnings.length} 条警告` : "";
setPreviewStatus(`${duration} · ${count} 页${warningText}${fallback}`);
previewStatus.title = warnings.join("\n");
} else if (payload.status === "fallback") {
applyPages([]);
showPreviewError(payload.message);
setPreviewStatus("需要 PDF 回退");
} else {
previewStatus.title = "";
showPreviewError(payload.message || "编译失败");
setPreviewStatus("编译错误");
}
} catch (error) {
if (requestId !== state.previewRequest || error.name === "AbortError") return;
setPreviewStatus("服务不可用");
showPreviewError(error.message);
}
}
function applyPages(list) {
pages.hidden = false;
while (pages.children.length > list.length) pages.lastElementChild.remove();
while (pages.children.length < list.length) {
const page = document.createElement("div");
page.className = "page";
pages.appendChild(page);
}
for (let index = 0; index < list.length; index += 1) {
const page = pages.children[index];
const next = list[index];
if (page.dataset.hash === next.hash) continue;
page.innerHTML = next.svg;
page.dataset.hash = next.hash;
}
}
function applyPagePatches(payload) {
pages.hidden = false;
const count = payload.pageCount ?? pages.children.length;
while (pages.children.length > count) pages.lastElementChild.remove();
while (pages.children.length < count) {
const page = document.createElement("div");
page.className = "page";
pages.appendChild(page);
}
for (const next of payload.pages) {
const index = Number(next.index);
if (!Number.isInteger(index) || index < 0 || index >= count) continue;
const page = pages.children[index];
if (page.dataset.hash === next.hash) continue;
page.innerHTML = next.svg;
page.dataset.hash = next.hash;
}
}
function showPreviewError(message) {
previewErrorText.textContent = message;
previewError.hidden = false;
}
function hidePreviewError() {
previewError.hidden = true;
}
function showContextMenu(event, path) {
event.preventDefault();
contextMenu.textContent = "";
const entries = [
["打开", () => openFile(path), false],
["下载文件", () => downloadFile(path), false],
null,
["删除文件", () => deleteFile(path), true],
];
for (const entry of entries) {
if (!entry) {
const separator = document.createElement("div");
separator.className = "sep";
contextMenu.appendChild(separator);
continue;
}
const [label, action, danger] = entry;
const button = document.createElement("button");
button.textContent = label;
if (danger) button.className = "danger";
button.addEventListener("click", () => { hideContextMenu(); action(); });
contextMenu.appendChild(button);
}
contextMenu.hidden = false;
const width = contextMenu.offsetWidth;
const height = contextMenu.offsetHeight;
const left = Math.min(event.clientX, window.innerWidth - width - 8);
const top = Math.min(event.clientY, window.innerHeight - height - 8);
contextMenu.style.left = `${Math.max(8, left)}px`;
contextMenu.style.top = `${Math.max(8, top)}px`;
}
function hideContextMenu() {
contextMenu.hidden = true;
}
async function deleteFile(path) {
if (!confirm(`删除文件 ${path}?`)) return;
try {
await api(projectPath(`/file?path=${encodeURIComponent(path)}`), { method: "DELETE" });
if (state.file === path) {
state.file = null;
clearEditor("文件已删除。");
}
await reloadProject();
toast("文件已删除");
} catch (error) {
toast(`删除失败:${error.message}`, true);
}
}
async function reloadProject() {
if (!state.project) return;
const project = await api(`/api/projects/${encodeURIComponent(state.project.id)}`);
state.project = project;
projectTitle.textContent = project.name;
renderFileTree();
}
async function uploadFiles(files) {
if (!state.project || !files || files.length === 0) return;
let uploaded = 0;
for (const file of files) {
try {
await api(projectPath(`/files?path=${encodeURIComponent(file.name)}`), {
method: "POST",
body: file,
});
uploaded += 1;
} catch (error) {
toast(`上传 ${file.name} 失败:${error.message}`, true);
}
}
if (uploaded > 0) {
await reloadProject();
toast(`${uploaded} 个文件已上传`);
if (!state.file && files[0]) openFile(files[0].name);
}
}
async function createFile() {
if (!state.project) return;
const path = prompt("新文件路径,例如 sections/intro.tex");
if (!path) return;
const trimmed = path.trim().replace(/^\/+/, "");
if (!trimmed || trimmed.includes("..") || trimmed.includes("\\")) {
toast("文件名不合法", true);
return;
}
try {
await api(projectPath(`/file?path=${encodeURIComponent(trimmed)}`), {
method: "PUT",
headers: { "Content-Type": "text/plain; charset=utf-8" },
body: "",
});
await reloadProject();
await openFile(trimmed);
toast("文件已创建");
} catch (error) {
toast(`创建失败:${error.message}`, true);
}
}
async function exportPdf() {
if (!state.project) return;
try {
const response = await fetch(projectPath("/pdf") + engineQuery(), { method: "POST" });
if (!response.ok) {
toast(`PDF 编译失败:${await response.text()}`, true);
return;
}
const actualEngine = response.headers.get("X-Preview-Engine");
if (actualEngine && actualEngine !== state.engine) {
toast(`PDF 由 ${actualEngine} 生成(已回退)`);
}
const blob = await response.blob();
const url = URL.createObjectURL(blob);
const anchor = document.createElement("a");
anchor.href = url;
anchor.download = `${state.project.id}.pdf`;
document.body.appendChild(anchor);
anchor.click();
anchor.remove();
setTimeout(() => URL.revokeObjectURL(url), 20000);
} catch (error) {
toast(`PDF 导出失败:${error.message}`, true);
}
}
sourceEditor.addEventListener("input", () => {
state.dirty = true;
setSaveStatus("未保存");
scheduleSave();
if (state.file && triggersPreview(state.file)) schedulePreview(40);
});
sourceEditor.addEventListener("keydown", event => {
if ((event.ctrlKey || event.metaKey) && event.key.toLowerCase() === "s") {
event.preventDefault();
clearTimeout(state.saveTimer);
saveFile();
return;
}
if (event.key === "Tab") {
event.preventDefault();
const start = sourceEditor.selectionStart;
sourceEditor.setRangeText(" ", start, sourceEditor.selectionEnd, "end");
state.dirty = true;
setSaveStatus("未保存");
scheduleSave();
}
});
document.addEventListener("click", event => {
if (!contextMenu.hidden && !contextMenu.contains(event.target)) hideContextMenu();
});
document.addEventListener("keydown", event => {
if (event.key === "Escape") hideContextMenu();
});
window.addEventListener("blur", hideContextMenu);
window.addEventListener("resize", hideContextMenu);
$("#brand").addEventListener("click", () => { location.hash = "#/"; });
$("#back-button").addEventListener("click", () => { location.hash = "#/"; });
$("#download-project").addEventListener("click", () => state.project && downloadProject(state.project));
$("#upload-files").addEventListener("click", () => $("#file-input").click());
$("#new-file").addEventListener("click", createFile);
$("#new-project").addEventListener("click", async () => {
const name = prompt("项目名称", "新项目");
if (!name) return;
try {
const project = await api(`/api/projects/new?name=${encodeURIComponent(name)}`, { method: "POST" });
location.hash = `#/p/${encodeURIComponent(project.id)}`;
} catch (error) {
toast(`创建失败:${error.message}`, true);
}
});
$("#upload-zip").addEventListener("click", () => $("#zip-input").click());
$("#zip-input").addEventListener("change", event => {
uploadZip(event.target.files[0]);
event.target.value = "";
});
$("#file-input").addEventListener("change", event => {
uploadFiles(Array.from(event.target.files));
event.target.value = "";
});
$("#export-pdf").addEventListener("click", exportPdf);
const dropZone = $("#drop-zone");
for (const target of [projectsView, dropZone]) {
target.addEventListener("dragover", event => {
event.preventDefault();
dropZone.classList.add("dragging");
});
target.addEventListener("dragleave", () => dropZone.classList.remove("dragging"));
target.addEventListener("drop", event => {
event.preventDefault();
dropZone.classList.remove("dragging");
const file = event.dataTransfer.files[0];
if (file) uploadZip(file);
});
}
workspace.addEventListener("dragover", event => {
if (event.dataTransfer && Array.from(event.dataTransfer.types).includes("Files")) {
event.preventDefault();
}
});
workspace.addEventListener("drop", event => {
if (!state.project) return;
event.preventDefault();
uploadFiles(Array.from(event.dataTransfer.files || []));
});
window.addEventListener("hashchange", route);
route();
engineButton.addEventListener("click", () => {
state.engine = state.engine === "route-d" ? "v1" : "route-d";
localStorage.setItem("texrra-engine", state.engine);
localStorage.removeItem("texrra-route-d");
updateEngineButton();
schedulePreview(0);
});
updateEngineButton();