Initial texrra web frontend

Split the inline CSS and JavaScript into styles.css and app.js. The static assets are served by texrra-engine. Use preview page dimensions for A4/Letter aspect ratios, refresh the UI screenshots, and document the API contract.
This commit is contained in:
gloamxun committed 2026-10-19 11:41:46 +08:00
commit c7c54c9511
11 files changed
+1026

No files matched your search

+2
View File
@@ -0,0 +1,2 @@
.DS_Store
Thumbs.db
+91
View File
@@ -0,0 +1,91 @@
# texrra web
Build-free editor frontend for the [texrra engine](https://git.iloveuulove.me/gloamxun/texrra-engine).
It is plain HTML, CSS, and JavaScript: there is no bundler and no dependency
install. The engine serves these files and provides the same-origin API.
![Projects dashboard](docs/screenshots/projects-dashboard.png)
The landing page manages uploaded projects; opening one switches to the editor.
![Project editor](docs/screenshots/project-editor.png)
## Features
- **Upload ZIP** creates a project from an archive. Extraction rejects absolute
paths and `..`, ignores directory entries, rejects encrypted and ZIP64
archives, and caps a project at 64 MB / 2000 files.
- **New project** creates a minimal `main.tex`.
- Each project card offers **open / download / delete**; the editor header also
downloads the project ZIP.
- The sidebar lists every project file with type badges and folders. Right-click
a file for **open / download / delete**.
- **Upload files** adds files to the project root (drag and drop works too);
**new file** creates nested paths such as `sections/intro.tex`.
- Text files open with debounced autosave and a live preview of the project's
main file. Images render in the preview pane; other binary files show a
download action.
- The preview keeps one `<div>` per page and replaces only pages whose content
hash changed, so typing does not reload the view or jump the scroll position.
- Page cards take their aspect ratio and width from the preview payload, so A4
and Letter documents are both displayed without distortion.
## Run
Clone both repositories as siblings and start the engine:
```sh
git clone https://git.iloveuulove.me/gloamxun/texrra-engine.git engine
git clone https://git.iloveuulove.me/gloamxun/texrra-web.git web
cd engine
cargo run --release -- serve examples/hello.tex 4174
```
Open <http://127.0.0.1:4174>. The engine discovers `../web` automatically;
`TEXRRA_WEB_DIR` can point at this checkout from elsewhere. The same files can
be edited in place while the engine is running and a browser reload picks them
up (the server sends `Cache-Control: no-cache`).
## Files
| Path | Purpose |
| --- | --- |
| `index.html` | Page shell and markup |
| `styles.css` | Layout, editor, preview, and context-menu styling |
| `app.js` | Project API client, editor state, autosave, preview diffing |
| `favicon.svg` | Browser icon |
| `docs/screenshots/` | UI screenshots used by this README |
## API contract
The frontend assumes the engine is the same origin and exposes:
| Endpoint | Purpose |
| --- | --- |
| `GET /api/projects` | Project list |
| `POST /api/projects?name=` | Create a project from a ZIP body |
| `POST /api/projects/new?name=` | Create an empty project |
| `GET /api/projects/<id>` | Project metadata and file list |
| `DELETE /api/projects/<id>` | Delete a project |
| `GET /api/projects/<id>/zip` | Download the project as a ZIP |
| `GET /api/projects/<id>/raw?path=` | Read a file (`download=1` downloads it) |
| `PUT /api/projects/<id>/file?path=` | Write a text file |
| `POST /api/projects/<id>/files?path=` | Upload a file |
| `DELETE /api/projects/<id>/file?path=` | Delete a file |
| `POST /api/projects/<id>/preview` | Live preview of the main file |
| `POST /api/projects/<id>/pdf` | PDF of the main file |
The preview response is a JSON object with `status`, `durationMs`,
`pageWidthMm`, `pageHeightMm`, and `pages` (one inline SVG and hash per page).
Font faces are loaded from `/fonts.css` and `/fonts/*.ttf`.
## Design notes
- No framework or build step: the shell is static and the editor is a
`<textarea>`; all document state is owned by the engine.
- The route is hash-based (`#/` and `#/p/<id>`), so the static server needs no
fallback routing.
- Autosave is debounced at 450 ms; previews are debounced at 90 ms and previous
preview requests are aborted when a newer edit arrives.
- The UI is intentionally dense and keyboard-friendly: `Ctrl`/`Cmd+S` saves,
`Tab` inserts two spaces, and `Esc` closes the context menu.
+730
View File
@@ -0,0 +1,730 @@
/* 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 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"];
const state = {
projects: [],
project: null,
file: null,
fileIsBinary: false,
dirty: false,
saveTimer: 0,
previewTimer: 0,
previewController: null,
previewRequest: 0,
toastTimer: 0,
};
function escapeHtml(value) {
return String(value).replace(/[&<>"']/g, character => ({
"&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;"
}[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 || "";
}
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 `<span class="${className}">${escapeHtml(extension ? label : "")}</span>`;
}
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 = `<span class="caret">▾</span><span class="file-name">${escapeHtml(name)}</span>`;
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 = `<span class="caret"></span>${fileBadge(file.path, state.project.mainFile === file.path)}<span class="file-name">${escapeHtml(file.name)}</span>`;
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 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 response = await fetch(projectPath("/preview"), {
method: "POST",
signal: controller.signal,
});
if (requestId !== state.previewRequest) return;
const payload = await response.json();
if (requestId !== state.previewRequest) return;
if (payload.status === "ok") {
applyPages(payload.pages);
hidePreviewError();
const count = payload.pages.length;
setPreviewStatus(`${payload.durationMs.toFixed(1)} ms · ${count} 页`);
} else if (payload.status === "fallback") {
applyPages([]);
showPreviewError(payload.message);
setPreviewStatus("需要 PDF 回退");
} else {
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 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"), { method: "POST" });
if (!response.ok) {
toast(`PDF 编译失败:${await response.text()}`, true);
return;
}
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();
});
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();
Binary file not shown.

After

Width:  |  Height:  |  Size: 88 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 129 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 126 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 70 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 34 KiB

+4
View File
@@ -0,0 +1,4 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64">
<rect width="64" height="64" rx="16" fill="#315fce"/>
<text x="32" y="46" text-anchor="middle" font-family="Georgia, serif" font-size="40" fill="#ffffff">T</text>
</svg>

After

Width:  |  Height:  |  Size: 236 B

+96
View File
@@ -0,0 +1,96 @@
<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>texrra</title>
<link rel="icon" href="/favicon.svg" type="image/svg+xml">
<link rel="stylesheet" href="/fonts.css">
<link rel="stylesheet" href="/styles.css">
</head>
<body>
<header>
<div class="brand" id="brand"><span class="brand-mark">T</span>texrra</div>
<div class="header-actions" id="header-actions"></div>
</header>
<main>
<section class="projects-view" id="projects-view" hidden>
<div class="projects-inner">
<div class="hero">
<div>
<h1>项目</h1>
<p>上传 zip 项目或新建空白项目,进入项目后可以编辑、预览和导出 PDF。</p>
</div>
<div class="hero-actions">
<button class="btn" id="upload-zip">上传 ZIP</button>
<button class="btn primary" id="new-project">新建项目</button>
</div>
</div>
<div class="drop-zone" id="drop-zone">把 <strong>.zip</strong> 拖到这里上传</div>
<div class="project-grid" id="project-grid"></div>
<div class="empty-state" id="projects-empty" hidden>还没有项目。上传一个 zip,或点“新建项目”。</div>
</div>
</section>
<section class="workspace" id="workspace" hidden>
<aside class="file-panel">
<div class="file-panel-head">
<button class="icon-btn" id="back-button" title="返回项目列表">←</button>
<span class="project-title" id="project-title"></span>
</div>
<div class="file-tools">
<button class="btn" id="upload-files">上传文件</button>
<button class="btn" id="new-file">新建文件</button>
<button class="btn" id="download-project">下载 ZIP</button>
</div>
<div class="file-tree" id="file-tree"></div>
<div class="file-panel-foot" id="file-panel-foot"></div>
</aside>
<div class="editor-panel">
<div class="panel-head">
<span class="path" id="open-file-path">未打开文件</span>
<span class="status" id="save-status"></span>
</div>
<textarea id="source" spellcheck="false" aria-label="文件内容"></textarea>
<div class="binary-notice" id="binary-notice" hidden>
<div class="big" id="binary-icon">▣</div>
<div id="binary-text">这个文件是二进制文件,无法在编辑器中打开。</div>
<a class="btn" id="binary-download" href="#">下载文件</a>
</div>
</div>
<div class="preview-panel">
<div class="panel-head">
<span>实时预览</span>
<span class="head-right">
<span class="status" id="preview-status"></span>
<button class="btn small" id="export-pdf">导出 PDF</button>
</span>
</div>
<div class="preview-scroll" id="preview-scroll">
<div id="preview-error" hidden><strong>编译失败</strong><pre id="preview-error-text"></pre></div>
<div id="pages"></div>
<img class="asset-preview" id="asset-preview" alt="" hidden>
</div>
</div>
</section>
</main>
<footer>
<span>texrra · Rust 排版引擎</span>
<span>·</span>
<span>项目保存在本地 <code>projects/</code> 目录</span>
<span>·</span>
<span>Ctrl/Cmd+S 保存</span>
</footer>
<input id="zip-input" type="file" accept=".zip,application/zip" hidden>
<input id="file-input" type="file" multiple hidden>
<div id="context-menu" hidden></div>
<div id="toast" hidden></div>
<script src="/app.js"></script>
</body>
</html>
+103
View File
@@ -0,0 +1,103 @@
/* texrra web frontend styles. Served by texrra-engine at /styles.css. */
:root { color-scheme: light; font-family: Inter, ui-sans-serif, system-ui, sans-serif; color: #1f2329; background: #f2f4f7; }
* { box-sizing: border-box; }
[hidden] { display: none !important; }
body { margin: 0; height: 100vh; display: flex; flex-direction: column; min-width: 720px; }
button { font: inherit; }
header { height: 54px; flex: none; display: flex; align-items: center; justify-content: space-between; padding: 0 20px; background: #fff; border-bottom: 1px solid #e3e6ea; }
.brand { display: flex; align-items: center; gap: 9px; font-size: 14px; font-weight: 650; letter-spacing: .01em; cursor: pointer; user-select: none; }
.brand-mark { display: inline-grid; place-items: center; width: 24px; height: 24px; border-radius: 7px; color: #fff; background: #315fce; font-family: Georgia, serif; font-size: 15px; }
.header-actions { display: flex; align-items: center; gap: 10px; }
.btn { height: 30px; padding: 0 12px; border: 1px solid #d5d9df; border-radius: 7px; background: #fff; color: #333a45; font-size: 12px; font-weight: 600; cursor: pointer; white-space: nowrap; }
.btn:hover { border-color: #b7bfca; background: #f7f8fa; }
.btn.primary { border-color: #315fce; background: #315fce; color: #fff; }
.btn.primary:hover { background: #2a53b5; }
.btn.danger { color: #b42318; border-color: #e8c5c1; }
.btn.danger:hover { background: #fff5f4; }
.btn:disabled { opacity: .55; cursor: progress; }
.icon-btn { width: 30px; height: 30px; display: inline-grid; place-items: center; border: 1px solid #d5d9df; border-radius: 7px; background: #fff; color: #333a45; cursor: pointer; font-size: 14px; }
.icon-btn:hover { background: #f7f8fa; }
main { flex: 1; min-height: 0; display: flex; flex-direction: column; }
.projects-view { flex: 1; min-height: 0; overflow: auto; padding: 32px 40px 60px; }
.projects-inner { max-width: 1080px; margin: 0 auto; }
.hero { display: flex; align-items: flex-end; justify-content: space-between; gap: 20px; margin-bottom: 22px; }
.hero h1 { margin: 0 0 6px; font-size: 24px; letter-spacing: -.01em; }
.hero p { margin: 0; color: #6b7280; font-size: 13px; }
.hero-actions { display: flex; gap: 10px; }
.drop-zone { margin-bottom: 22px; padding: 22px; border: 1.5px dashed #c6ccd6; border-radius: 12px; color: #6b7280; font-size: 13px; text-align: center; background: #fafbfc; transition: border-color .15s, background .15s; }
.drop-zone.dragging { border-color: #315fce; background: #f0f4ff; color: #315fce; }
.drop-zone strong { color: #333a45; }
.project-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(300px, 1fr)); gap: 14px; }
.project-card { display: flex; gap: 14px; padding: 16px; border: 1px solid #e3e6ea; border-radius: 12px; background: #fff; }
.project-card:hover { border-color: #cfd6e0; box-shadow: 0 6px 18px #1720330d; }
.project-badge { width: 42px; height: 42px; flex: none; display: grid; place-items: center; border-radius: 10px; background: #eef2ff; color: #315fce; font-size: 11px; font-weight: 800; letter-spacing: .04em; }
.project-body { min-width: 0; flex: 1; }
.project-body h3 { margin: 0 0 4px; font-size: 14px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.project-meta { margin: 0 0 6px; color: #7b828e; font-size: 11.5px; }
.project-actions { display: flex; gap: 8px; flex-wrap: wrap; margin-top: 10px; }
.empty-state { padding: 60px 20px; text-align: center; color: #7b828e; font-size: 13px; }
.workspace { flex: 1; min-height: 0; display: grid; grid-template-columns: 232px minmax(300px, 1fr) minmax(340px, 1fr); background: #e3e6ea; gap: 1px; }
.file-panel { min-height: 0; display: flex; flex-direction: column; background: #fff; }
.file-panel-head { display: flex; align-items: center; gap: 8px; padding: 10px 12px; border-bottom: 1px solid #eceef1; }
.project-title { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; font-size: 12.5px; font-weight: 650; }
.file-tools { display: flex; gap: 6px; padding: 8px 10px; border-bottom: 1px solid #eceef1; flex-wrap: wrap; }
.file-tools .btn { height: 26px; padding: 0 8px; font-size: 11px; }
.file-tree { flex: 1; min-height: 0; overflow: auto; padding: 6px 6px 16px; }
.tree-folder > .tree-row { color: #6b7280; font-weight: 600; }
.tree-row { display: flex; align-items: center; gap: 6px; height: 27px; padding: 0 8px; border-radius: 6px; font-size: 12.5px; cursor: pointer; user-select: none; white-space: nowrap; overflow: hidden; }
.tree-row:hover { background: #f3f5f8; }
.tree-row.active { background: #e8eefc; color: #22408c; }
.tree-row .caret { width: 10px; flex: none; color: #8a919c; font-size: 9px; }
.tree-row .file-name { overflow: hidden; text-overflow: ellipsis; }
.tree-folder.collapsed > .tree-children { display: none; }
.tree-children { margin-left: 12px; }
.file-badge { flex: none; width: 26px; text-align: center; border-radius: 4px; font-size: 8.5px; font-weight: 800; letter-spacing: .03em; color: #54607a; background: #eef1f5; padding: 2px 0; }
.file-badge.tex { color: #1d4ed8; background: #e8eefc; }
.file-badge.img { color: #0f766e; background: #e6f5f2; }
.file-badge.bib { color: #8a5a00; background: #fdf3dd; }
.file-badge.sty { color: #7c3aed; background: #f1e9fd; }
.file-panel-foot { padding: 8px 12px; border-top: 1px solid #eceef1; color: #8a919c; font-size: 11px; }
.editor-panel { min-height: 0; display: flex; flex-direction: column; background: #fff; }
.panel-head { height: 36px; flex: none; display: flex; align-items: center; justify-content: space-between; gap: 10px; padding: 0 14px; border-bottom: 1px solid #eceef1; color: #6b7280; font-size: 11px; font-weight: 650; letter-spacing: .05em; text-transform: uppercase; }
.panel-head .path { font-weight: 500; letter-spacing: 0; text-transform: none; color: #4b5563; font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; font-size: 11px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.panel-head .status { flex: none; letter-spacing: 0; text-transform: none; font-weight: 500; color: #8a919c; }
.panel-head .head-right { display: flex; align-items: center; gap: 10px; }
.btn.small { height: 24px; padding: 0 9px; font-size: 11px; border-radius: 6px; }
#source { flex: 1; min-height: 0; width: 100%; resize: none; border: 0; outline: 0; padding: 16px 18px; color: #1f2329; background: #fff; font: 13px/1.65 ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; tab-size: 2; }
#source[readonly] { background: #fbfbfc; color: #6b7280; }
.binary-notice { flex: 1; display: flex; flex-direction: column; align-items: center; justify-content: center; gap: 12px; padding: 30px; color: #6b7280; font-size: 13px; text-align: center; }
.binary-notice .big { font-size: 34px; }
.preview-panel { min-height: 0; display: flex; flex-direction: column; background: #eef0f3; }
.preview-panel .panel-head { background: #fff; }
.preview-scroll { flex: 1; min-height: 0; overflow: auto; padding: 18px; }
#pages { display: flex; flex-direction: column; align-items: center; gap: 16px; }
.page { width: min(100%, var(--page-width, 210mm)); aspect-ratio: var(--page-aspect, 210 / 297); flex: none; background: #fff; box-shadow: 0 1px 2px #1720331f, 0 12px 28px #17203312; }
.page > svg { display: block; width: 100%; height: 100%; }
.asset-preview { display: block; max-width: 100%; margin: 0 auto; border: 1px solid #dfe3e8; border-radius: 6px; background: #fff; }
#preview-error { position: sticky; top: 0; z-index: 2; margin: 0 0 14px; padding: 12px 16px; border: 1px solid #efc8c4; border-radius: 8px; color: #81251e; background: #fff8f7f2; box-shadow: 0 4px 18px #17203318; }
#preview-error strong { display: block; margin-bottom: 6px; font-size: 12px; }
#preview-error pre { margin: 0; max-height: 240px; overflow: auto; font: 11px/1.5 ui-monospace, monospace; white-space: pre-wrap; overflow-wrap: anywhere; }
#context-menu { position: fixed; z-index: 50; min-width: 160px; padding: 5px; border: 1px solid #d8dce2; border-radius: 8px; background: #fff; box-shadow: 0 10px 30px #17203324; }
#context-menu button { display: flex; width: 100%; align-items: center; gap: 8px; padding: 7px 10px; border: 0; border-radius: 5px; background: none; color: #333a45; font-size: 12.5px; text-align: left; cursor: pointer; }
#context-menu button:hover { background: #f2f4f8; }
#context-menu button.danger { color: #b42318; }
#context-menu .sep { height: 1px; margin: 4px 6px; background: #eceef1; }
#toast { position: fixed; left: 18px; bottom: 18px; z-index: 60; max-width: 420px; padding: 10px 14px; border-radius: 8px; background: #1f2937; color: #fff; font-size: 12.5px; box-shadow: 0 10px 30px #17203330; }
#toast.error { background: #8f1d14; }
footer { height: 28px; flex: none; display: flex; align-items: center; gap: 12px; padding: 0 16px; border-top: 1px solid #e3e6ea; background: #fff; color: #8a919c; font-size: 11px; }
@media (max-width: 980px) {
body { min-width: 0; }
.workspace { grid-template-columns: 200px minmax(280px, 1fr); grid-template-rows: 1fr 1fr; }
.preview-panel { grid-column: 1 / -1; }
.projects-view { padding: 24px 18px 40px; }
.hero { flex-direction: column; align-items: flex-start; }
}