theseus/bundled-addons/docx-editor/index.js

398 lines
17 KiB
JavaScript
Raw Normal View History

feat(docx-editor): edit Word documents without quietly eating what Word put in them A .docx editor is easy to write badly: read the file into HTML, let someone edit it, write a fresh document back, and hand them a file that lost its headers, its page size and half its formatting without ever saying so. Three things keep this one honest. The reader doesn't use mammoth's HTML. mammoth's converter is deliberately semantic, and HTML has nowhere to put a run's colour or a paragraph's line spacing, so it drops them — and those are controls this editor puts in the ribbon. Taking its parsed document model instead means what the ribbon offers is what the file can actually carry. Six properties mammoth's model didn't keep are added by build-time patches, each asserting its anchor so an upgrade that moves the code fails the build rather than shipping a lossy reader. The writer rebuilds the body but carries the rest of the package across: headers, footers, footnotes, endnotes, the document's own style catalogue, its theme and its page setup, with relationship ids and content types re-wired. Word features the editor can't model are still lost, so they are detected when the file opens and named in a banner before anyone edits. Tracked changes get their own gate. mammoth renders insertions as ordinary text and drops deletions, so saving would accept every pending revision without Word ever asking. Such a document opens read-only until the user says that is what they want. Verified over 66 real documents: 65 round-trip with an identical model and a structurally valid package, the one exception being a 7 MB WMF picture, which no browser can display and the writer cannot emit. Also driven end to end through a real Theseus over CDP — sidebar, ribbon, typing, save, reopen.
2026-09-20 20:46:29 +02:00
// Word editor — the add-on half. All the document work happens in the
// editor tab; this side owns the sidebar panel, the scratch folder and the
// ring of recently-opened documents.
//
// Flow:
// panel picks a file (<input type=file>, or a drop) → invokes "stash" with
// the bytes → we write them to the scratch dir and push them onto the
// recent ring → panel invokes "openEditor" → we park a pointer under
// storage.__pending and openTab("editor.html") → the editor drains
// __pending on its first paint and pulls the bytes with "getBytes".
//
// Only a pointer goes through storage, never the document: add-on storage is
// a single JSON file rewritten in full on every set, and a few megabytes of
// base64 in there would make every unrelated write expensive.
const fs = require("node:fs");
const path = require("node:path");
const MAX_RECENT = 8; // documents kept in the ring
const SCRATCH_DIR = "docx-scratch";
const MAX_BYTES = 64 * 1024 * 1024; // refuse absurd inputs early
module.exports = {
activate(api) {
feat(docx-editor): Save as…, PDF export, and a mark of our own Three gaps, one theme: the editor could produce a file but not decide where it went, what format it was in, or look like anything in the dock. **Save as…** opens a real file dialog, and the extension typed there picks the format. Save then writes to that file instead of dropping another copy in Downloads every time. The renderer never names a path: the dialog returns an opaque token, and the add-on will only write to a path a dialog actually returned. An extension page is the least trusted thing in the add-on, and "write these bytes anywhere" is not a capability it needs. **PDF** goes through Chromium's own print pipeline in a hidden window — the same engine as Ctrl+P — on the paper size read out of the document's own sectPr. For that to match what the user was looking at, the page's typography had to stop living in editor.css, which the export window can't reach: it moves to lib/doc-css.js and both surfaces read the one string. The result embeds subsetted fonts, keeps images, and turns hyperlinks into real PDF link annotations. **The icon** is ours. Microsoft's Word mark is a trademark and borrowing it to look official is not something a browser that talks about sovereignty should do. icon.svg says "text document" in its own words — a turned corner, a heading rule, body lines, a pilcrow badge in Silent Mode green — and `npm run icons` derives the PNGs and addon.json's copy from it, so there is one drawing rather than several that drift. Also: the scratch folder follows the profile rename to extensions-data/ via the api.dataDir the host now provides, instead of creating a stale addons-data/ beside it.
2026-09-21 03:35:55 +02:00
// The dock button takes the panel's icon, the catalogue card takes the
// manifest's. Reading it back out of addon.json keeps those the same
// drawing — and addon.json's copy is itself generated from icon.svg by
// addon-build/docx-editor/make-icons.mjs, so there is exactly one.
let icon = "";
try { icon = JSON.parse(fs.readFileSync(path.join(api.folder, "addon.json"), "utf8")).icon || ""; }
catch (e) { api.log("couldn't read the icon from addon.json:", e?.message); }
feat(docx-editor): edit Word documents without quietly eating what Word put in them A .docx editor is easy to write badly: read the file into HTML, let someone edit it, write a fresh document back, and hand them a file that lost its headers, its page size and half its formatting without ever saying so. Three things keep this one honest. The reader doesn't use mammoth's HTML. mammoth's converter is deliberately semantic, and HTML has nowhere to put a run's colour or a paragraph's line spacing, so it drops them — and those are controls this editor puts in the ribbon. Taking its parsed document model instead means what the ribbon offers is what the file can actually carry. Six properties mammoth's model didn't keep are added by build-time patches, each asserting its anchor so an upgrade that moves the code fails the build rather than shipping a lossy reader. The writer rebuilds the body but carries the rest of the package across: headers, footers, footnotes, endnotes, the document's own style catalogue, its theme and its page setup, with relationship ids and content types re-wired. Word features the editor can't model are still lost, so they are detected when the file opens and named in a banner before anyone edits. Tracked changes get their own gate. mammoth renders insertions as ordinary text and drops deletions, so saving would accept every pending revision without Word ever asking. Such a document opens read-only until the user says that is what they want. Verified over 66 real documents: 65 round-trip with an identical model and a structurally valid package, the one exception being a 7 MB WMF picture, which no browser can display and the writer cannot emit. Also driven end to end through a real Theseus over CDP — sidebar, ribbon, typing, save, reopen.
2026-09-20 20:46:29 +02:00
api.registerSidebarPanel({
id: "main",
title: "Word editor",
feat(docx-editor): Save as…, PDF export, and a mark of our own Three gaps, one theme: the editor could produce a file but not decide where it went, what format it was in, or look like anything in the dock. **Save as…** opens a real file dialog, and the extension typed there picks the format. Save then writes to that file instead of dropping another copy in Downloads every time. The renderer never names a path: the dialog returns an opaque token, and the add-on will only write to a path a dialog actually returned. An extension page is the least trusted thing in the add-on, and "write these bytes anywhere" is not a capability it needs. **PDF** goes through Chromium's own print pipeline in a hidden window — the same engine as Ctrl+P — on the paper size read out of the document's own sectPr. For that to match what the user was looking at, the page's typography had to stop living in editor.css, which the export window can't reach: it moves to lib/doc-css.js and both surfaces read the one string. The result embeds subsetted fonts, keeps images, and turns hyperlinks into real PDF link annotations. **The icon** is ours. Microsoft's Word mark is a trademark and borrowing it to look official is not something a browser that talks about sovereignty should do. icon.svg says "text document" in its own words — a turned corner, a heading rule, body lines, a pilcrow badge in Silent Mode green — and `npm run icons` derives the PNGs and addon.json's copy from it, so there is one drawing rather than several that drift. Also: the scratch folder follows the profile rename to extensions-data/ via the api.dataDir the host now provides, instead of creating a stale addons-data/ beside it.
2026-09-21 03:35:55 +02:00
icon,
feat(docx-editor): edit Word documents without quietly eating what Word put in them A .docx editor is easy to write badly: read the file into HTML, let someone edit it, write a fresh document back, and hand them a file that lost its headers, its page size and half its formatting without ever saying so. Three things keep this one honest. The reader doesn't use mammoth's HTML. mammoth's converter is deliberately semantic, and HTML has nowhere to put a run's colour or a paragraph's line spacing, so it drops them — and those are controls this editor puts in the ribbon. Taking its parsed document model instead means what the ribbon offers is what the file can actually carry. Six properties mammoth's model didn't keep are added by build-time patches, each asserting its anchor so an upgrade that moves the code fails the build rather than shipping a lossy reader. The writer rebuilds the body but carries the rest of the package across: headers, footers, footnotes, endnotes, the document's own style catalogue, its theme and its page setup, with relationship ids and content types re-wired. Word features the editor can't model are still lost, so they are detected when the file opens and named in a banner before anyone edits. Tracked changes get their own gate. mammoth renders insertions as ordinary text and drops deletions, so saving would accept every pending revision without Word ever asking. Such a document opens read-only until the user says that is what they want. Verified over 66 real documents: 65 round-trip with an identical model and a structurally valid package, the one exception being a 7 MB WMF picture, which no browser can display and the writer cannot emit. Also driven end to end through a real Theseus over CDP — sidebar, ribbon, typing, save, reopen.
2026-09-20 20:46:29 +02:00
page: "panel.html",
});
feat(docx-editor): Save as…, PDF export, and a mark of our own Three gaps, one theme: the editor could produce a file but not decide where it went, what format it was in, or look like anything in the dock. **Save as…** opens a real file dialog, and the extension typed there picks the format. Save then writes to that file instead of dropping another copy in Downloads every time. The renderer never names a path: the dialog returns an opaque token, and the add-on will only write to a path a dialog actually returned. An extension page is the least trusted thing in the add-on, and "write these bytes anywhere" is not a capability it needs. **PDF** goes through Chromium's own print pipeline in a hidden window — the same engine as Ctrl+P — on the paper size read out of the document's own sectPr. For that to match what the user was looking at, the page's typography had to stop living in editor.css, which the export window can't reach: it moves to lib/doc-css.js and both surfaces read the one string. The result embeds subsetted fonts, keeps images, and turns hyperlinks into real PDF link annotations. **The icon** is ours. Microsoft's Word mark is a trademark and borrowing it to look official is not something a browser that talks about sovereignty should do. icon.svg says "text document" in its own words — a turned corner, a heading rule, body lines, a pilcrow badge in Silent Mode green — and `npm run icons` derives the PNGs and addon.json's copy from it, so there is one drawing rather than several that drift. Also: the scratch folder follows the profile rename to extensions-data/ via the api.dataDir the host now provides, instead of creating a stale addons-data/ beside it.
2026-09-21 03:35:55 +02:00
// Per-extension scratch dir under <userData>/extensions-data/, same
// arrangement as the screenshot add-on: never write inside the extension
// folder itself, where it would confuse anyone reading the shipped source.
// api.dataDir is the host-provided folder; the fallback rebuilds it for
// hosts that predate that field.
feat(docx-editor): edit Word documents without quietly eating what Word put in them A .docx editor is easy to write badly: read the file into HTML, let someone edit it, write a fresh document back, and hand them a file that lost its headers, its page size and half its formatting without ever saying so. Three things keep this one honest. The reader doesn't use mammoth's HTML. mammoth's converter is deliberately semantic, and HTML has nowhere to put a run's colour or a paragraph's line spacing, so it drops them — and those are controls this editor puts in the ribbon. Taking its parsed document model instead means what the ribbon offers is what the file can actually carry. Six properties mammoth's model didn't keep are added by build-time patches, each asserting its anchor so an upgrade that moves the code fails the build rather than shipping a lossy reader. The writer rebuilds the body but carries the rest of the package across: headers, footers, footnotes, endnotes, the document's own style catalogue, its theme and its page setup, with relationship ids and content types re-wired. Word features the editor can't model are still lost, so they are detected when the file opens and named in a banner before anyone edits. Tracked changes get their own gate. mammoth renders insertions as ordinary text and drops deletions, so saving would accept every pending revision without Word ever asking. Such a document opens read-only until the user says that is what they want. Verified over 66 real documents: 65 round-trip with an identical model and a structurally valid package, the one exception being a 7 MB WMF picture, which no browser can display and the writer cannot emit. Also driven end to end through a real Theseus over CDP — sidebar, ribbon, typing, save, reopen.
2026-09-20 20:46:29 +02:00
const dataParent = path.dirname(path.join(api.folder, ".."));
feat(docx-editor): Save as…, PDF export, and a mark of our own Three gaps, one theme: the editor could produce a file but not decide where it went, what format it was in, or look like anything in the dock. **Save as…** opens a real file dialog, and the extension typed there picks the format. Save then writes to that file instead of dropping another copy in Downloads every time. The renderer never names a path: the dialog returns an opaque token, and the add-on will only write to a path a dialog actually returned. An extension page is the least trusted thing in the add-on, and "write these bytes anywhere" is not a capability it needs. **PDF** goes through Chromium's own print pipeline in a hidden window — the same engine as Ctrl+P — on the paper size read out of the document's own sectPr. For that to match what the user was looking at, the page's typography had to stop living in editor.css, which the export window can't reach: it moves to lib/doc-css.js and both surfaces read the one string. The result embeds subsetted fonts, keeps images, and turns hyperlinks into real PDF link annotations. **The icon** is ours. Microsoft's Word mark is a trademark and borrowing it to look official is not something a browser that talks about sovereignty should do. icon.svg says "text document" in its own words — a turned corner, a heading rule, body lines, a pilcrow badge in Silent Mode green — and `npm run icons` derives the PNGs and addon.json's copy from it, so there is one drawing rather than several that drift. Also: the scratch folder follows the profile rename to extensions-data/ via the api.dataDir the host now provides, instead of creating a stale addons-data/ beside it.
2026-09-21 03:35:55 +02:00
const scratchDir = path.join(api.dataDir || path.join(dataParent, "extensions-data"), SCRATCH_DIR);
feat(docx-editor): edit Word documents without quietly eating what Word put in them A .docx editor is easy to write badly: read the file into HTML, let someone edit it, write a fresh document back, and hand them a file that lost its headers, its page size and half its formatting without ever saying so. Three things keep this one honest. The reader doesn't use mammoth's HTML. mammoth's converter is deliberately semantic, and HTML has nowhere to put a run's colour or a paragraph's line spacing, so it drops them — and those are controls this editor puts in the ribbon. Taking its parsed document model instead means what the ribbon offers is what the file can actually carry. Six properties mammoth's model didn't keep are added by build-time patches, each asserting its anchor so an upgrade that moves the code fails the build rather than shipping a lossy reader. The writer rebuilds the body but carries the rest of the package across: headers, footers, footnotes, endnotes, the document's own style catalogue, its theme and its page setup, with relationship ids and content types re-wired. Word features the editor can't model are still lost, so they are detected when the file opens and named in a banner before anyone edits. Tracked changes get their own gate. mammoth renders insertions as ordinary text and drops deletions, so saving would accept every pending revision without Word ever asking. Such a document opens read-only until the user says that is what they want. Verified over 66 real documents: 65 round-trip with an identical model and a structurally valid package, the one exception being a 7 MB WMF picture, which no browser can display and the writer cannot emit. Also driven end to end through a real Theseus over CDP — sidebar, ribbon, typing, save, reopen.
2026-09-20 20:46:29 +02:00
try { fs.mkdirSync(scratchDir, { recursive: true }); }
catch (e) { api.log("scratch mkdir failed:", e?.message); }
function stamp() {
const d = new Date();
const p = (n) => String(n).padStart(2, "0");
return `${d.getFullYear()}${p(d.getMonth() + 1)}${p(d.getDate())}-${p(d.getHours())}${p(d.getMinutes())}${p(d.getSeconds())}`;
}
// A scratch filename that can't escape the folder however the original
// was named. The display name is kept separately in the ring.
function scratchName(displayName) {
const base = String(displayName || "document")
.replace(/\.docx$/i, "")
.replace(/[^\w.\- ]+/g, "_")
.replace(/\s+/g, " ")
.trim()
.slice(0, 60) || "document";
return `${stamp()}-${base}.docx`;
}
function pruneRecent(recent) {
const alive = recent.filter((r) => { try { fs.accessSync(r.path); return true; } catch { return false; } });
const keep = alive.slice(0, MAX_RECENT);
for (const gone of alive.slice(MAX_RECENT)) { try { fs.unlinkSync(gone.path); } catch {} }
return keep;
}
function readRecent() {
let recent = api.storage.get("recent", []);
return Array.isArray(recent) ? recent : [];
}
function findRecent(id) {
return readRecent().find((r) => r.id === id) || null;
}
function pathOf(id) {
// Belt and braces: the id came from a renderer, so re-derive the path
// from the ring rather than joining whatever string arrived.
const hit = findRecent(id);
if (!hit) throw new Error(`no document "${id}" in the recent list`);
const abs = path.resolve(hit.path);
if (path.dirname(abs) !== path.resolve(scratchDir)) {
throw new Error("document path escapes the scratch folder");
}
return abs;
}
// Write bytes to the scratch folder and put them at the head of the ring.
// `kind` distinguishes what the user opened from what the editor saved
// back, so the panel can say which is which.
function stash({ name, base64, kind, replaces }) {
const buf = Buffer.from(String(base64 || ""), "base64");
if (!buf.length) throw new Error("no document bytes");
if (buf.length > MAX_BYTES) throw new Error(`document is too large (${(buf.length / 1048576).toFixed(0)} MB)`);
// Every .docx is a zip; catching this here beats a confusing parse
// error three layers deeper in the editor.
if (!(buf[0] === 0x50 && buf[1] === 0x4b)) {
throw new Error("that doesn't look like a .docx file");
}
const id = scratchName(name);
const file = path.join(scratchDir, id);
fs.writeFileSync(file, buf);
let recent = readRecent();
if (replaces) recent = recent.filter((r) => r.id !== replaces);
recent.unshift({
id,
name: String(name || "document.docx"),
path: file,
bytes: buf.length,
at: Date.now(),
kind: kind === "saved" ? "saved" : "opened",
});
recent = pruneRecent(recent);
api.storage.set("recent", recent);
api.log(`stashed ${id} (${buf.length} bytes, ${kind || "opened"})`);
return { id, name: String(name || "document.docx"), bytes: buf.length };
}
api.onMessage("stash", (payload) => stash(payload || {}));
feat(docx-editor): documents are tabs, each with its own close button and menu Opening a second .docx used to mean a second browser tab: a whole ribbon, banner and footer repeated, with one ✕ at the far end of a row that also held the file's name. The name looked like a tab and nothing about it behaved like one. Now the editor holds documents the way the browser holds pages. A strip under the toolbar carries one tab per open document — icon, name, unsaved dot, its own ✕ — plus a + to open another. Middle-click closes, Ctrl+W closes, Ctrl+Tab cycles, and right-click (or the caret on the tab under the pointer) drops a menu: Duplicate, Open in the default app, Show in folder, Close others, Close. The gestures are the browser's because that is the tab strip every user of this editor already knows. Under it, one ProseMirror view is handed a different state per document rather than one view per tab, and the module-level "current document" variables are marshalled in and out on a switch. That keeps the change out of every function that touches the current document, at the price of one list — DOC_FIELDS in captureActive/adoptDoc — that has to stay complete. A variable missed there leaks one document's state into another, which would look like the editor corrupting a file, so it is called out in a comment. Closing the last document closes the editor tab, the way closing a browser's last tab closes the window; an empty ribbon staring at the user is not a state worth having. The add-on hands a newly opened document to the editor that is already up and fronts it, falling back to opening a tab if no editor acknowledges within 900ms — so a crashed or closed editor degrades to exactly the old behaviour rather than swallowing the document.
2026-09-22 08:35:06 +02:00
// --- handing a document to the editor -------------------------------
//
// The editor holds several documents at once, so a second file should
// become a tab inside the editor that is already open rather than a
// second browser tab full of ribbon. There is no way to ask "is my page
// still alive?", so the page says so itself: it announces on load and
// acknowledges each document it accepts. If no acknowledgement arrives
// the editor is gone (crashed, closed, reloaded) and we open a tab as
// before — the failure mode is the old behaviour, not a lost document.
let editorLive = false;
const acks = new Map(); // document id -> resolve()
api.onMessage("editorHello", () => { editorLive = true; api.log("an editor tab is open"); return { ok: true }; });
api.onMessage("editorBye", () => { editorLive = false; api.log("the editor tab is gone"); return { ok: true }; });
api.onMessage("docOpened", (payload) => {
const id = String(payload && payload.id || "");
const done = acks.get(id);
if (done) { acks.delete(id); done(); }
return { ok: true };
});
function handOff(id, name) {
return new Promise((resolve) => {
const timer = setTimeout(() => { acks.delete(id); resolve(false); }, 900);
acks.set(id, () => { clearTimeout(timer); resolve(true); });
api.emit("open-doc", { id, name, at: Date.now() });
});
}
api.onMessage("openEditor", async (payload) => {
feat(docx-editor): edit Word documents without quietly eating what Word put in them A .docx editor is easy to write badly: read the file into HTML, let someone edit it, write a fresh document back, and hand them a file that lost its headers, its page size and half its formatting without ever saying so. Three things keep this one honest. The reader doesn't use mammoth's HTML. mammoth's converter is deliberately semantic, and HTML has nowhere to put a run's colour or a paragraph's line spacing, so it drops them — and those are controls this editor puts in the ribbon. Taking its parsed document model instead means what the ribbon offers is what the file can actually carry. Six properties mammoth's model didn't keep are added by build-time patches, each asserting its anchor so an upgrade that moves the code fails the build rather than shipping a lossy reader. The writer rebuilds the body but carries the rest of the package across: headers, footers, footnotes, endnotes, the document's own style catalogue, its theme and its page setup, with relationship ids and content types re-wired. Word features the editor can't model are still lost, so they are detected when the file opens and named in a banner before anyone edits. Tracked changes get their own gate. mammoth renders insertions as ordinary text and drops deletions, so saving would accept every pending revision without Word ever asking. Such a document opens read-only until the user says that is what they want. Verified over 66 real documents: 65 round-trip with an identical model and a structurally valid package, the one exception being a 7 MB WMF picture, which no browser can display and the writer cannot emit. Also driven end to end through a real Theseus over CDP — sidebar, ribbon, typing, save, reopen.
2026-09-20 20:46:29 +02:00
const id = payload && payload.id ? String(payload.id) : "";
feat(docx-editor): documents are tabs, each with its own close button and menu Opening a second .docx used to mean a second browser tab: a whole ribbon, banner and footer repeated, with one ✕ at the far end of a row that also held the file's name. The name looked like a tab and nothing about it behaved like one. Now the editor holds documents the way the browser holds pages. A strip under the toolbar carries one tab per open document — icon, name, unsaved dot, its own ✕ — plus a + to open another. Middle-click closes, Ctrl+W closes, Ctrl+Tab cycles, and right-click (or the caret on the tab under the pointer) drops a menu: Duplicate, Open in the default app, Show in folder, Close others, Close. The gestures are the browser's because that is the tab strip every user of this editor already knows. Under it, one ProseMirror view is handed a different state per document rather than one view per tab, and the module-level "current document" variables are marshalled in and out on a switch. That keeps the change out of every function that touches the current document, at the price of one list — DOC_FIELDS in captureActive/adoptDoc — that has to stay complete. A variable missed there leaks one document's state into another, which would look like the editor corrupting a file, so it is called out in a comment. Closing the last document closes the editor tab, the way closing a browser's last tab closes the window; an empty ribbon staring at the user is not a state worth having. The add-on hands a newly opened document to the editor that is already up and fronts it, falling back to opening a tab if no editor acknowledges within 900ms — so a crashed or closed editor degrades to exactly the old behaviour rather than swallowing the document.
2026-09-22 08:35:06 +02:00
const hit = id ? findRecent(id) : null;
if (id && !hit) throw new Error(`no document "${id}" in the recent list`);
if (editorLive && id) {
if (await handOff(id, hit.name)) {
api.log(`handed ${id} to the open editor`);
return { ok: true, id, reused: true };
}
editorLive = false; // it didn't answer; assume it's gone
api.log("the open editor didn't answer — opening a new tab");
feat(docx-editor): edit Word documents without quietly eating what Word put in them A .docx editor is easy to write badly: read the file into HTML, let someone edit it, write a fresh document back, and hand them a file that lost its headers, its page size and half its formatting without ever saying so. Three things keep this one honest. The reader doesn't use mammoth's HTML. mammoth's converter is deliberately semantic, and HTML has nowhere to put a run's colour or a paragraph's line spacing, so it drops them — and those are controls this editor puts in the ribbon. Taking its parsed document model instead means what the ribbon offers is what the file can actually carry. Six properties mammoth's model didn't keep are added by build-time patches, each asserting its anchor so an upgrade that moves the code fails the build rather than shipping a lossy reader. The writer rebuilds the body but carries the rest of the package across: headers, footers, footnotes, endnotes, the document's own style catalogue, its theme and its page setup, with relationship ids and content types re-wired. Word features the editor can't model are still lost, so they are detected when the file opens and named in a banner before anyone edits. Tracked changes get their own gate. mammoth renders insertions as ordinary text and drops deletions, so saving would accept every pending revision without Word ever asking. Such a document opens read-only until the user says that is what they want. Verified over 66 real documents: 65 round-trip with an identical model and a structurally valid package, the one exception being a 7 MB WMF picture, which no browser can display and the writer cannot emit. Also driven end to end through a real Theseus over CDP — sidebar, ribbon, typing, save, reopen.
2026-09-20 20:46:29 +02:00
}
feat(docx-editor): documents are tabs, each with its own close button and menu Opening a second .docx used to mean a second browser tab: a whole ribbon, banner and footer repeated, with one ✕ at the far end of a row that also held the file's name. The name looked like a tab and nothing about it behaved like one. Now the editor holds documents the way the browser holds pages. A strip under the toolbar carries one tab per open document — icon, name, unsaved dot, its own ✕ — plus a + to open another. Middle-click closes, Ctrl+W closes, Ctrl+Tab cycles, and right-click (or the caret on the tab under the pointer) drops a menu: Duplicate, Open in the default app, Show in folder, Close others, Close. The gestures are the browser's because that is the tab strip every user of this editor already knows. Under it, one ProseMirror view is handed a different state per document rather than one view per tab, and the module-level "current document" variables are marshalled in and out on a switch. That keeps the change out of every function that touches the current document, at the price of one list — DOC_FIELDS in captureActive/adoptDoc — that has to stay complete. A variable missed there leaks one document's state into another, which would look like the editor corrupting a file, so it is called out in a comment. Closing the last document closes the editor tab, the way closing a browser's last tab closes the window; an empty ribbon staring at the user is not a state worth having. The add-on hands a newly opened document to the editor that is already up and fronts it, falling back to opening a tab if no editor acknowledges within 900ms — so a crashed or closed editor degrades to exactly the old behaviour rather than swallowing the document.
2026-09-22 08:35:06 +02:00
// The pointer under __pending is what a fresh editor drains on its
// first paint; the query string carries the same id so a reload of the
// tab still finds its document.
api.storage.set("__pending", id ? { id, name: hit.name, at: Date.now() } : null);
feat(docx-editor): edit Word documents without quietly eating what Word put in them A .docx editor is easy to write badly: read the file into HTML, let someone edit it, write a fresh document back, and hand them a file that lost its headers, its page size and half its formatting without ever saying so. Three things keep this one honest. The reader doesn't use mammoth's HTML. mammoth's converter is deliberately semantic, and HTML has nowhere to put a run's colour or a paragraph's line spacing, so it drops them — and those are controls this editor puts in the ribbon. Taking its parsed document model instead means what the ribbon offers is what the file can actually carry. Six properties mammoth's model didn't keep are added by build-time patches, each asserting its anchor so an upgrade that moves the code fails the build rather than shipping a lossy reader. The writer rebuilds the body but carries the rest of the package across: headers, footers, footnotes, endnotes, the document's own style catalogue, its theme and its page setup, with relationship ids and content types re-wired. Word features the editor can't model are still lost, so they are detected when the file opens and named in a banner before anyone edits. Tracked changes get their own gate. mammoth renders insertions as ordinary text and drops deletions, so saving would accept every pending revision without Word ever asking. Such a document opens read-only until the user says that is what they want. Verified over 66 real documents: 65 round-trip with an identical model and a structurally valid package, the one exception being a 7 MB WMF picture, which no browser can display and the writer cannot emit. Also driven end to end through a real Theseus over CDP — sidebar, ribbon, typing, save, reopen.
2026-09-20 20:46:29 +02:00
api.openTab("editor.html", id ? { query: { doc: id } } : undefined);
api.log(id ? `opening editor for ${id}` : "opening editor with a blank document");
feat(docx-editor): documents are tabs, each with its own close button and menu Opening a second .docx used to mean a second browser tab: a whole ribbon, banner and footer repeated, with one ✕ at the far end of a row that also held the file's name. The name looked like a tab and nothing about it behaved like one. Now the editor holds documents the way the browser holds pages. A strip under the toolbar carries one tab per open document — icon, name, unsaved dot, its own ✕ — plus a + to open another. Middle-click closes, Ctrl+W closes, Ctrl+Tab cycles, and right-click (or the caret on the tab under the pointer) drops a menu: Duplicate, Open in the default app, Show in folder, Close others, Close. The gestures are the browser's because that is the tab strip every user of this editor already knows. Under it, one ProseMirror view is handed a different state per document rather than one view per tab, and the module-level "current document" variables are marshalled in and out on a switch. That keeps the change out of every function that touches the current document, at the price of one list — DOC_FIELDS in captureActive/adoptDoc — that has to stay complete. A variable missed there leaks one document's state into another, which would look like the editor corrupting a file, so it is called out in a comment. Closing the last document closes the editor tab, the way closing a browser's last tab closes the window; an empty ribbon staring at the user is not a state worth having. The add-on hands a newly opened document to the editor that is already up and fronts it, falling back to opening a tab if no editor acknowledges within 900ms — so a crashed or closed editor degrades to exactly the old behaviour rather than swallowing the document.
2026-09-22 08:35:06 +02:00
return { ok: true, id, reused: false };
});
// "Open in default app" from a document tab's menu — the scratch copy is
// what the user opened (or the last autosave of it), which is the nearest
// thing to "the file" that this add-on has.
api.onMessage("openExternally", (payload) => {
const { shell } = api.require("electron");
const id = String(payload && payload.id || "");
const hit = findRecent(id);
if (!hit) throw new Error("that document is no longer in the recent list");
shell.openPath(pathOf(id));
return { ok: true, name: hit.name };
feat(docx-editor): edit Word documents without quietly eating what Word put in them A .docx editor is easy to write badly: read the file into HTML, let someone edit it, write a fresh document back, and hand them a file that lost its headers, its page size and half its formatting without ever saying so. Three things keep this one honest. The reader doesn't use mammoth's HTML. mammoth's converter is deliberately semantic, and HTML has nowhere to put a run's colour or a paragraph's line spacing, so it drops them — and those are controls this editor puts in the ribbon. Taking its parsed document model instead means what the ribbon offers is what the file can actually carry. Six properties mammoth's model didn't keep are added by build-time patches, each asserting its anchor so an upgrade that moves the code fails the build rather than shipping a lossy reader. The writer rebuilds the body but carries the rest of the package across: headers, footers, footnotes, endnotes, the document's own style catalogue, its theme and its page setup, with relationship ids and content types re-wired. Word features the editor can't model are still lost, so they are detected when the file opens and named in a banner before anyone edits. Tracked changes get their own gate. mammoth renders insertions as ordinary text and drops deletions, so saving would accept every pending revision without Word ever asking. Such a document opens read-only until the user says that is what they want. Verified over 66 real documents: 65 round-trip with an identical model and a structurally valid package, the one exception being a 7 MB WMF picture, which no browser can display and the writer cannot emit. Also driven end to end through a real Theseus over CDP — sidebar, ribbon, typing, save, reopen.
2026-09-20 20:46:29 +02:00
});
api.onMessage("listRecent", () => {
const recent = pruneRecent(readRecent());
api.storage.set("recent", recent);
return recent.map((r) => ({ id: r.id, name: r.name, bytes: r.bytes, at: r.at, kind: r.kind }));
});
api.onMessage("getBytes", (payload) => {
const id = String(payload && payload.id || "");
const hit = findRecent(id);
if (!hit) throw new Error(`no document "${id}" in the recent list`);
const buf = fs.readFileSync(pathOf(id));
return { id, name: hit.name, base64: buf.toString("base64"), bytes: buf.length, at: hit.at, kind: hit.kind };
});
// Autosave. The editor calls this as the user works; each document keeps
// one autosave entry rather than filling the ring with its own history.
api.onMessage("autosave", (payload) => {
const p = payload || {};
const res = stash({
name: String(p.name || "document.docx"),
base64: p.base64,
kind: "saved",
replaces: p.replaces ? String(p.replaces) : "",
});
return res;
});
api.onMessage("clearRecent", (payload) => {
const id = payload && payload.id ? String(payload.id) : "";
let recent = readRecent();
if (id) {
const hit = recent.find((r) => r.id === id);
if (hit) { try { fs.unlinkSync(hit.path); } catch {} }
recent = recent.filter((r) => r.id !== id);
} else {
for (const r of recent) { try { fs.unlinkSync(r.path); } catch {} }
recent = [];
}
api.storage.set("recent", recent);
return { ok: true };
});
feat(docx-editor): Save as…, PDF export, and a mark of our own Three gaps, one theme: the editor could produce a file but not decide where it went, what format it was in, or look like anything in the dock. **Save as…** opens a real file dialog, and the extension typed there picks the format. Save then writes to that file instead of dropping another copy in Downloads every time. The renderer never names a path: the dialog returns an opaque token, and the add-on will only write to a path a dialog actually returned. An extension page is the least trusted thing in the add-on, and "write these bytes anywhere" is not a capability it needs. **PDF** goes through Chromium's own print pipeline in a hidden window — the same engine as Ctrl+P — on the paper size read out of the document's own sectPr. For that to match what the user was looking at, the page's typography had to stop living in editor.css, which the export window can't reach: it moves to lib/doc-css.js and both surfaces read the one string. The result embeds subsetted fonts, keeps images, and turns hyperlinks into real PDF link annotations. **The icon** is ours. Microsoft's Word mark is a trademark and borrowing it to look official is not something a browser that talks about sovereignty should do. icon.svg says "text document" in its own words — a turned corner, a heading rule, body lines, a pilcrow badge in Silent Mode green — and `npm run icons` derives the PNGs and addon.json's copy from it, so there is one drawing rather than several that drift. Also: the scratch folder follows the profile rename to extensions-data/ via the api.dataDir the host now provides, instead of creating a stale addons-data/ beside it.
2026-09-21 03:35:55 +02:00
// --- Save as… -------------------------------------------------------
//
// Two calls rather than one, because the format depends on the extension
// the user types into the dialog, and we'd rather not build a .docx and
// a .pdf speculatively just to throw one away.
//
// The renderer never gets to name a path. `pickSavePath` hands back an
// opaque token for the path the USER chose in a native dialog, and
// `writeChosen` will only write to a path that came out of that dialog.
// An extension page is the least trusted thing in this add-on, and
// "write these bytes to any path you like" is not a capability it needs.
const chosenPaths = new Map(); // token -> absolute path
const everChosen = new Set(); // every path a dialog has ever returned
let tokenSeq = 0;
api.onMessage("pickSavePath", async (payload) => {
const { dialog } = api.require("electron");
const p = payload || {};
const suggested = String(p.name || "document.docx").replace(/[/\\]/g, "_");
const res = await dialog.showSaveDialog({
title: "Save as",
defaultPath: path.join(app_downloads(), suggested),
filters: [
{ name: "Word document", extensions: ["docx"] },
{ name: "PDF document", extensions: ["pdf"] },
],
properties: ["createDirectory", "showOverwriteConfirmation"],
});
if (res.canceled || !res.filePath) return { cancelled: true };
const token = `t${++tokenSeq}-${Date.now()}`;
chosenPaths.set(token, res.filePath);
everChosen.add(res.filePath);
// One token, one write; nothing accumulates across a session.
if (chosenPaths.size > 8) chosenPaths.delete(chosenPaths.keys().next().value);
const ext = path.extname(res.filePath).toLowerCase().replace(".", "") || "docx";
api.log(`save-as target chosen (.${ext})`);
return { token, format: ext === "pdf" ? "pdf" : "docx", name: path.basename(res.filePath) };
});
// Re-reserve a path the user already picked, so a second Ctrl+S can write
// to the same file without a second dialog. Only a path this add-on has
// already handed out can be re-reserved — it is not a way to name a new
// one from the renderer.
api.onMessage("reserveSavePath", (payload) => {
const target = String(payload && payload.path || "");
if (!everChosen.has(target)) throw new Error("that path was never chosen in a dialog");
const token = `t${++tokenSeq}-${Date.now()}`;
chosenPaths.set(token, target);
return { token, name: path.basename(target) };
});
api.onMessage("writeChosen", (payload) => {
const p = payload || {};
const target = chosenPaths.get(String(p.token || ""));
if (!target) throw new Error("no such save target — pick a location first");
chosenPaths.delete(String(p.token));
const buf = Buffer.from(String(p.base64 || ""), "base64");
if (!buf.length) throw new Error("nothing to write");
fs.writeFileSync(target, buf);
api.log(`wrote ${buf.length} bytes to a user-chosen path`);
return { ok: true, path: target, name: path.basename(target), bytes: buf.length };
});
function app_downloads() {
try { return api.require("electron").app.getPath("downloads"); }
catch { return scratchDir; }
}
// --- PDF ------------------------------------------------------------
//
// The editor hands over a self-contained HTML page (its own document
// CSS, images already inlined as data URLs) and the page geometry it
// read out of the .docx. We load that in a hidden window and let
// Chromium's own print pipeline make the PDF — the same engine behind
// Ctrl+P, so what the user previewed is what they get.
//
// A temp file rather than a data: URL: a document with a few photographs
// in it runs to megabytes, and long data: URLs get truncated.
feat(docx-editor): the page fills the window, and two fonts ship with it The page sat marooned in the middle of a wide window with dark space either side of it. It is now drawn at the size the document actually claims — A4 stays A4, margins come from its own sectPr — and CSS `zoom` scales that to fit, defaulting to Fit width with a control in the footer and Ctrl +/-/0. Scaling rather than widening is deliberate. A page stretched to the window would break every line somewhere different from where the printed page breaks it, and an editor whose whole claim is that it shows you the document should not lie about where the lines end. `zoom` also beats a transform here: it affects layout, so the board scrolls correctly and ProseMirror's coordinate maths keeps working. Ubuntu and Fraunces now ship in fonts/, because Windows has neither and a font offered in the ribbon that the machine lacks is a font the user picks and then cannot see. Fetched once by `npm run fonts` and committed, never at runtime: an extension in a browser built around not phoning home should not ask a font CDN what a document looks like every time one is opened. Two things had to be worked around. On file:// Chromium registers @font-face rules and then refuses to fetch the files — the family appears in document.fonts and every glyph still renders in the fallback — so the add-on reads the woff2 and hands the page a stylesheet with them inlined as data URLs. The PDF export needed the same treatment for a different reason: its print window runs from a temp folder, where a relative url() resolves to nothing, which would have quietly undone the one-stylesheet-for-both promise that lib/doc-css.js exists to keep. If either path fails, the ribbon labels those families "(not available)" rather than implying otherwise. About 700 KB, most of it Ubuntu's Cyrillic and Greek — kept because the documents this is used on are not all English. Licences ship alongside.
2026-09-22 19:12:56 +02:00
// The bundled webfonts, as @font-face rules with the woff2 inlined.
// The print page is loaded from a temp folder, so a relative url() would
// resolve to nothing there — and a PDF whose text falls back to a
// different typeface is exactly the drift the shared stylesheet was
// meant to prevent. Read once, kept for the session.
let inlinedFontCss = null;
function fontCss() {
if (inlinedFontCss !== null) return inlinedFontCss;
try {
const css = fs.readFileSync(path.join(api.folder, "fonts.css"), "utf8");
inlinedFontCss = css.replace(/url\('fonts\/([^']+)'\)/g, (whole, file) => {
try {
const b64 = fs.readFileSync(path.join(api.folder, "fonts", file)).toString("base64");
return `url('data:font/woff2;base64,${b64}')`;
} catch { return whole; }
});
} catch (e) {
api.log("no bundled fonts to inline:", e?.message);
inlinedFontCss = "";
}
return inlinedFontCss;
}
api.onMessage("fontCss", () => ({ css: fontCss() }));
feat(docx-editor): Save as…, PDF export, and a mark of our own Three gaps, one theme: the editor could produce a file but not decide where it went, what format it was in, or look like anything in the dock. **Save as…** opens a real file dialog, and the extension typed there picks the format. Save then writes to that file instead of dropping another copy in Downloads every time. The renderer never names a path: the dialog returns an opaque token, and the add-on will only write to a path a dialog actually returned. An extension page is the least trusted thing in the add-on, and "write these bytes anywhere" is not a capability it needs. **PDF** goes through Chromium's own print pipeline in a hidden window — the same engine as Ctrl+P — on the paper size read out of the document's own sectPr. For that to match what the user was looking at, the page's typography had to stop living in editor.css, which the export window can't reach: it moves to lib/doc-css.js and both surfaces read the one string. The result embeds subsetted fonts, keeps images, and turns hyperlinks into real PDF link annotations. **The icon** is ours. Microsoft's Word mark is a trademark and borrowing it to look official is not something a browser that talks about sovereignty should do. icon.svg says "text document" in its own words — a turned corner, a heading rule, body lines, a pilcrow badge in Silent Mode green — and `npm run icons` derives the PNGs and addon.json's copy from it, so there is one drawing rather than several that drift. Also: the scratch folder follows the profile rename to extensions-data/ via the api.dataDir the host now provides, instead of creating a stale addons-data/ beside it.
2026-09-21 03:35:55 +02:00
api.onMessage("renderPdf", async (payload) => {
const { BrowserWindow } = api.require("electron");
const p = payload || {};
feat(docx-editor): the page fills the window, and two fonts ship with it The page sat marooned in the middle of a wide window with dark space either side of it. It is now drawn at the size the document actually claims — A4 stays A4, margins come from its own sectPr — and CSS `zoom` scales that to fit, defaulting to Fit width with a control in the footer and Ctrl +/-/0. Scaling rather than widening is deliberate. A page stretched to the window would break every line somewhere different from where the printed page breaks it, and an editor whose whole claim is that it shows you the document should not lie about where the lines end. `zoom` also beats a transform here: it affects layout, so the board scrolls correctly and ProseMirror's coordinate maths keeps working. Ubuntu and Fraunces now ship in fonts/, because Windows has neither and a font offered in the ribbon that the machine lacks is a font the user picks and then cannot see. Fetched once by `npm run fonts` and committed, never at runtime: an extension in a browser built around not phoning home should not ask a font CDN what a document looks like every time one is opened. Two things had to be worked around. On file:// Chromium registers @font-face rules and then refuses to fetch the files — the family appears in document.fonts and every glyph still renders in the fallback — so the add-on reads the woff2 and hands the page a stylesheet with them inlined as data URLs. The PDF export needed the same treatment for a different reason: its print window runs from a temp folder, where a relative url() resolves to nothing, which would have quietly undone the one-stylesheet-for-both promise that lib/doc-css.js exists to keep. If either path fails, the ribbon labels those families "(not available)" rather than implying otherwise. About 700 KB, most of it Ubuntu's Cyrillic and Greek — kept because the documents this is used on are not all English. Licences ship alongside.
2026-09-22 19:12:56 +02:00
let html = String(p.html || "");
feat(docx-editor): Save as…, PDF export, and a mark of our own Three gaps, one theme: the editor could produce a file but not decide where it went, what format it was in, or look like anything in the dock. **Save as…** opens a real file dialog, and the extension typed there picks the format. Save then writes to that file instead of dropping another copy in Downloads every time. The renderer never names a path: the dialog returns an opaque token, and the add-on will only write to a path a dialog actually returned. An extension page is the least trusted thing in the add-on, and "write these bytes anywhere" is not a capability it needs. **PDF** goes through Chromium's own print pipeline in a hidden window — the same engine as Ctrl+P — on the paper size read out of the document's own sectPr. For that to match what the user was looking at, the page's typography had to stop living in editor.css, which the export window can't reach: it moves to lib/doc-css.js and both surfaces read the one string. The result embeds subsetted fonts, keeps images, and turns hyperlinks into real PDF link annotations. **The icon** is ours. Microsoft's Word mark is a trademark and borrowing it to look official is not something a browser that talks about sovereignty should do. icon.svg says "text document" in its own words — a turned corner, a heading rule, body lines, a pilcrow badge in Silent Mode green — and `npm run icons` derives the PNGs and addon.json's copy from it, so there is one drawing rather than several that drift. Also: the scratch folder follows the profile rename to extensions-data/ via the api.dataDir the host now provides, instead of creating a stale addons-data/ beside it.
2026-09-21 03:35:55 +02:00
if (!html) throw new Error("no document to render");
feat(docx-editor): the page fills the window, and two fonts ship with it The page sat marooned in the middle of a wide window with dark space either side of it. It is now drawn at the size the document actually claims — A4 stays A4, margins come from its own sectPr — and CSS `zoom` scales that to fit, defaulting to Fit width with a control in the footer and Ctrl +/-/0. Scaling rather than widening is deliberate. A page stretched to the window would break every line somewhere different from where the printed page breaks it, and an editor whose whole claim is that it shows you the document should not lie about where the lines end. `zoom` also beats a transform here: it affects layout, so the board scrolls correctly and ProseMirror's coordinate maths keeps working. Ubuntu and Fraunces now ship in fonts/, because Windows has neither and a font offered in the ribbon that the machine lacks is a font the user picks and then cannot see. Fetched once by `npm run fonts` and committed, never at runtime: an extension in a browser built around not phoning home should not ask a font CDN what a document looks like every time one is opened. Two things had to be worked around. On file:// Chromium registers @font-face rules and then refuses to fetch the files — the family appears in document.fonts and every glyph still renders in the fallback — so the add-on reads the woff2 and hands the page a stylesheet with them inlined as data URLs. The PDF export needed the same treatment for a different reason: its print window runs from a temp folder, where a relative url() resolves to nothing, which would have quietly undone the one-stylesheet-for-both promise that lib/doc-css.js exists to keep. If either path fails, the ribbon labels those families "(not available)" rather than implying otherwise. About 700 KB, most of it Ubuntu's Cyrillic and Greek — kept because the documents this is used on are not all English. Licences ship alongside.
2026-09-22 19:12:56 +02:00
const fonts = fontCss();
if (fonts) html = html.replace("</head>", `<style>${fonts}</style></head>`);
feat(docx-editor): Save as…, PDF export, and a mark of our own Three gaps, one theme: the editor could produce a file but not decide where it went, what format it was in, or look like anything in the dock. **Save as…** opens a real file dialog, and the extension typed there picks the format. Save then writes to that file instead of dropping another copy in Downloads every time. The renderer never names a path: the dialog returns an opaque token, and the add-on will only write to a path a dialog actually returned. An extension page is the least trusted thing in the add-on, and "write these bytes anywhere" is not a capability it needs. **PDF** goes through Chromium's own print pipeline in a hidden window — the same engine as Ctrl+P — on the paper size read out of the document's own sectPr. For that to match what the user was looking at, the page's typography had to stop living in editor.css, which the export window can't reach: it moves to lib/doc-css.js and both surfaces read the one string. The result embeds subsetted fonts, keeps images, and turns hyperlinks into real PDF link annotations. **The icon** is ours. Microsoft's Word mark is a trademark and borrowing it to look official is not something a browser that talks about sovereignty should do. icon.svg says "text document" in its own words — a turned corner, a heading rule, body lines, a pilcrow badge in Silent Mode green — and `npm run icons` derives the PNGs and addon.json's copy from it, so there is one drawing rather than several that drift. Also: the scratch folder follows the profile rename to extensions-data/ via the api.dataDir the host now provides, instead of creating a stale addons-data/ beside it.
2026-09-21 03:35:55 +02:00
const tmp = path.join(scratchDir, `print-${Date.now()}.html`);
fs.writeFileSync(tmp, html, "utf8");
let win = null;
try {
win = new BrowserWindow({
show: false,
webPreferences: {
// Nothing in the print page needs to run, reach the network or
// talk to the add-on — it is markup and inline styles.
javascript: false,
sandbox: true,
contextIsolation: true,
nodeIntegration: false,
webSecurity: true,
},
});
await win.loadFile(tmp);
// loadFile resolves on did-finish-load; give layout a beat to settle
// before asking for the PDF, or the first page can come out short.
await new Promise((r) => setTimeout(r, 250));
const opts = {
printBackground: true,
// The page box comes from the @page rule the editor wrote out of
// the document's own sectPr, so Chromium uses the real paper size
// rather than defaulting to Letter.
preferCSSPageSize: true,
generateTaggedPDF: true,
};
const pdf = await win.webContents.printToPDF(opts);
api.log(`rendered a ${(pdf.length / 1024).toFixed(0)} KB PDF`);
return { ok: true, base64: Buffer.from(pdf).toString("base64"), bytes: pdf.length };
} finally {
try { if (win && !win.isDestroyed()) win.destroy(); } catch {}
try { fs.unlinkSync(tmp); } catch {}
}
});
feat(docx-editor): edit Word documents without quietly eating what Word put in them A .docx editor is easy to write badly: read the file into HTML, let someone edit it, write a fresh document back, and hand them a file that lost its headers, its page size and half its formatting without ever saying so. Three things keep this one honest. The reader doesn't use mammoth's HTML. mammoth's converter is deliberately semantic, and HTML has nowhere to put a run's colour or a paragraph's line spacing, so it drops them — and those are controls this editor puts in the ribbon. Taking its parsed document model instead means what the ribbon offers is what the file can actually carry. Six properties mammoth's model didn't keep are added by build-time patches, each asserting its anchor so an upgrade that moves the code fails the build rather than shipping a lossy reader. The writer rebuilds the body but carries the rest of the package across: headers, footers, footnotes, endnotes, the document's own style catalogue, its theme and its page setup, with relationship ids and content types re-wired. Word features the editor can't model are still lost, so they are detected when the file opens and named in a banner before anyone edits. Tracked changes get their own gate. mammoth renders insertions as ordinary text and drops deletions, so saving would accept every pending revision without Word ever asking. Such a document opens read-only until the user says that is what they want. Verified over 66 real documents: 65 round-trip with an identical model and a structurally valid package, the one exception being a 7 MB WMF picture, which no browser can display and the writer cannot emit. Also driven end to end through a real Theseus over CDP — sidebar, ribbon, typing, save, reopen.
2026-09-20 20:46:29 +02:00
api.onMessage("openFolder", (payload) => {
const { shell } = api.require("electron");
const id = payload && payload.id ? String(payload.id) : "";
if (id) {
const hit = findRecent(id);
if (hit) { shell.showItemInFolder(hit.path); return { ok: true, path: hit.path }; }
}
shell.openPath(scratchDir);
return { ok: true, path: scratchDir };
});
api.log("registered docx-editor sidebar panel");
},
};