Vorlage fuer eigene Ableger-Installationen: Website + CMS-Code
Bereinigt von Pilot-Spezifika (echte Inhalte, Erzbistum-Hamburg-Bezuege, Domain-Werte) - install.env und hugo.toml [params] mit generischen Platzhaltern. docs/ komplett entfernt: Konzept, Manifest, Installations- anleitungen leben jetzt auf der Projekt-Website statt redundant im Repo, README verweist dorthin. Decap-CMS-Version von einer floatenden ^3.0.0 auf ein festes 3.15.1 gepinnt.
This commit is contained in:
@@ -0,0 +1,607 @@
|
||||
/* Methoden-Set: collect variant links, sort them, and download as
|
||||
zip/markdown/Word. Merge/sort/page-break/outline logic modeled on the
|
||||
"Mappe erstellen" tab from tobias_ebh/pandoc_ebh_paket (same author, same
|
||||
basic idea: order several markdown pieces via drag & drop, page-break
|
||||
toggle per transition, outline preview) - rewritten here for automatic
|
||||
fetching from this website instead of manual file upload.
|
||||
Details/rationale: the Methoden-Set chapter on the project website. */
|
||||
(function () {
|
||||
"use strict";
|
||||
|
||||
const linkForm = document.getElementById("link-form");
|
||||
const linkInput = document.getElementById("link-input");
|
||||
const itemList = document.getElementById("item-list");
|
||||
const outline = document.getElementById("outline");
|
||||
const titelInput = document.getElementById("titel-input");
|
||||
const formatRadios = document.querySelectorAll('input[name="format"]');
|
||||
const vorlageListe = document.getElementById("vorlage-liste");
|
||||
const btnZip = document.getElementById("btn-zip");
|
||||
const btnMd = document.getElementById("btn-md");
|
||||
const btnDokument = document.getElementById("btn-dokument");
|
||||
const status = document.getElementById("status");
|
||||
|
||||
function currentFormat() {
|
||||
return document.querySelector('input[name="format"]:checked').value; // "docx" or "odt"
|
||||
}
|
||||
|
||||
let items = []; // { id, url, titel, body, pageBreakBefore, pageBreakAfter, error }
|
||||
let idCounter = 0;
|
||||
|
||||
function setStatus(msg, state) {
|
||||
status.textContent = msg || "";
|
||||
if (state) status.dataset.state = state; else delete status.dataset.state;
|
||||
}
|
||||
|
||||
function el(tag, attrs, children) {
|
||||
const node = document.createElement(tag);
|
||||
for (const key in attrs || {}) {
|
||||
if (key === "text") node.textContent = attrs[key];
|
||||
else if (key === "html") node.innerHTML = attrs[key];
|
||||
// setAttribute("className", ...) would create a no-op "classname"
|
||||
// attribute instead of the real class property (DOM setAttribute
|
||||
// doesn't know "className", only "class") - hence mapped
|
||||
// specifically to the property instead of setAttribute.
|
||||
else if (key === "className") node.className = attrs[key];
|
||||
else if (attrs[key] !== undefined && attrs[key] !== false) node.setAttribute(key, attrs[key]);
|
||||
}
|
||||
for (const child of children || []) node.appendChild(child);
|
||||
return node;
|
||||
}
|
||||
|
||||
// --- Parse the frontmatter of the markdown response ---------------------
|
||||
// Generated by hugo/layouts/partials/methoden-set-dokument.html (variant
|
||||
// and method URLs return the same format) - fields are always written
|
||||
// via Hugo's "jsonify" (valid JSON = valid YAML flow scalar) - so a
|
||||
// simple regex + JSON.parse is enough, no custom YAML implementation
|
||||
// needed. "fehler" only comes from method URLs with 0 or >1 variants
|
||||
// (_default/single.md) - then without a usable body.
|
||||
function parseFrontMatter(text) {
|
||||
const match = /^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/.exec(text);
|
||||
if (!match) return null;
|
||||
const [, header, body] = match;
|
||||
const titelMatch = /^titel:\s*(".*")\s*$/m.exec(header);
|
||||
const quelleMatch = /^quelle:\s*(".*")\s*$/m.exec(header);
|
||||
const fehlerMatch = /^fehler:\s*(".*")\s*$/m.exec(header);
|
||||
if (!titelMatch || !quelleMatch) return null;
|
||||
try {
|
||||
return {
|
||||
titel: JSON.parse(titelMatch[1]),
|
||||
quelle: JSON.parse(quelleMatch[1]),
|
||||
fehler: fehlerMatch ? JSON.parse(fehlerMatch[1]) : null,
|
||||
body: body.replace(/^\s+/, "")
|
||||
};
|
||||
} catch (e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
const FEHLER_TEXT = {
|
||||
mehrere_varianten: "Diese Methode hat mehrere Varianten. Bitte auf der Methoden-Seite die gewünschte Variante öffnen und deren eigenen Link einfügen.",
|
||||
keine_variante: "Diese Methode hat noch keine veröffentlichte Variante."
|
||||
};
|
||||
|
||||
// --- Add link --------------------------------------------------------
|
||||
|
||||
function normalizeMarkdownUrl(raw) {
|
||||
let url;
|
||||
try {
|
||||
url = new URL(raw, window.location.href);
|
||||
} catch (e) {
|
||||
throw new Error("Das ist keine gültige Internetadresse.");
|
||||
}
|
||||
if (url.origin !== window.location.origin) {
|
||||
throw new Error("Nur Links auf diese Ableger-Instanz werden akzeptiert.");
|
||||
}
|
||||
if (!url.pathname.endsWith("/")) url.pathname += "/";
|
||||
url.pathname += "index.md";
|
||||
url.search = "";
|
||||
url.hash = "";
|
||||
return url;
|
||||
}
|
||||
|
||||
async function addLink(raw) {
|
||||
const id = ++idCounter;
|
||||
const item = { id, url: raw, titel: raw, body: "", pageBreakBefore: false, pageBreakAfter: false, error: "Wird geladen …" };
|
||||
items.push(item);
|
||||
render();
|
||||
try {
|
||||
const mdUrl = normalizeMarkdownUrl(raw);
|
||||
const response = await fetch(mdUrl.toString());
|
||||
if (!response.ok) {
|
||||
throw new Error(
|
||||
response.status === 404
|
||||
? "Das ist kein Link auf eine Methode oder Variante dieser Website (Seite existiert nicht)."
|
||||
: "Konnte nicht geladen werden (Status " + response.status + ")."
|
||||
);
|
||||
}
|
||||
const text = await response.text();
|
||||
const parsed = parseFrontMatter(text);
|
||||
if (!parsed) throw new Error("Antwort hatte nicht das erwartete Format.");
|
||||
if (parsed.fehler) throw new Error(FEHLER_TEXT[parsed.fehler] || parsed.fehler);
|
||||
item.titel = parsed.titel;
|
||||
item.quelle = parsed.quelle;
|
||||
item.body = parsed.body;
|
||||
item.error = null;
|
||||
} catch (err) {
|
||||
item.error = err && err.message ? err.message : String(err);
|
||||
}
|
||||
render();
|
||||
}
|
||||
|
||||
// Enter (without Shift) in the text field triggers immediate adding as
|
||||
// usual, instead of inserting a line break - Shift+Enter and pasting
|
||||
// from the clipboard remain free for adding several lines at once.
|
||||
linkInput.addEventListener("keydown", (e) => {
|
||||
if (e.key === "Enter" && !e.shiftKey) {
|
||||
e.preventDefault();
|
||||
linkForm.requestSubmit();
|
||||
}
|
||||
});
|
||||
|
||||
linkForm.addEventListener("submit", (e) => {
|
||||
e.preventDefault();
|
||||
const zeilen = linkInput.value.split(/\r?\n/).map((z) => z.trim()).filter(Boolean);
|
||||
if (!zeilen.length) return;
|
||||
linkInput.value = "";
|
||||
zeilen.forEach(addLink);
|
||||
});
|
||||
|
||||
// --- Render list: drag & drop, page-break conflict check ---------------
|
||||
// Same pattern as renderMappeList() in pandoc_ebh_paket/src/app.html.tmpl.
|
||||
|
||||
function render() {
|
||||
itemList.innerHTML = "";
|
||||
if (!items.length) {
|
||||
itemList.appendChild(el("div", { className: "hint", text: "Noch keine Links eingefügt." }));
|
||||
renderOutline();
|
||||
return;
|
||||
}
|
||||
items.forEach((item, index) => {
|
||||
const isFirst = index === 0;
|
||||
const isLast = index === items.length - 1;
|
||||
const prevItem = index > 0 ? items[index - 1] : null;
|
||||
const nextItem = index < items.length - 1 ? items[index + 1] : null;
|
||||
|
||||
let beforeDisabledReason = "";
|
||||
if (isFirst) beforeDisabledReason = "Nicht möglich vor der ersten Datei.";
|
||||
else if (prevItem.pageBreakAfter) beforeDisabledReason = "Nicht möglich: die vorherige Methode hat bereits „Seitenumbruch danach“ gesetzt.";
|
||||
|
||||
let afterDisabledReason = "";
|
||||
if (isLast) afterDisabledReason = "Nicht möglich nach der letzten Datei.";
|
||||
else if (nextItem.pageBreakBefore) afterDisabledReason = "Nicht möglich: die nächste Methode hat bereits „Seitenumbruch davor“ gesetzt.";
|
||||
|
||||
if (beforeDisabledReason) item.pageBreakBefore = false;
|
||||
if (afterDisabledReason) item.pageBreakAfter = false;
|
||||
|
||||
const row = el("div", { className: "item-row" + (item.error ? " error" : ""), draggable: !item.error }, []);
|
||||
row.dataset.id = String(item.id);
|
||||
|
||||
const removeBtn = el("button", { type: "button", className: "icon-btn", title: "entfernen", text: "✕" });
|
||||
removeBtn.addEventListener("click", () => {
|
||||
items = items.filter((it) => it.id !== item.id);
|
||||
render();
|
||||
});
|
||||
|
||||
const main = el("div", { className: "item-row__main" }, [
|
||||
el("span", { className: "drag-handle", text: "⠿" }),
|
||||
el("span", { className: "item-name", title: item.error ? item.url : item.titel, text: item.error ? item.url : item.titel }),
|
||||
removeBtn
|
||||
]);
|
||||
row.appendChild(main);
|
||||
|
||||
if (item.error) {
|
||||
row.appendChild(el("div", { className: "item-row__error", text: item.error }));
|
||||
} else {
|
||||
// Toggle buttons instead of checkbox+label: a larger, unambiguous
|
||||
// click target (native checkboxes are tiny and hard to hit on
|
||||
// narrow viewports).
|
||||
const beforeBtn = el("button", {
|
||||
type: "button", className: "pb-toggle", "aria-pressed": String(item.pageBreakBefore),
|
||||
disabled: Boolean(beforeDisabledReason), title: beforeDisabledReason || undefined, text: "Umbruch davor"
|
||||
});
|
||||
beforeBtn.addEventListener("click", () => { item.pageBreakBefore = !item.pageBreakBefore; render(); });
|
||||
|
||||
const afterBtn = el("button", {
|
||||
type: "button", className: "pb-toggle", "aria-pressed": String(item.pageBreakAfter),
|
||||
disabled: Boolean(afterDisabledReason), title: afterDisabledReason || undefined, text: "Umbruch danach"
|
||||
});
|
||||
afterBtn.addEventListener("click", () => { item.pageBreakAfter = !item.pageBreakAfter; render(); });
|
||||
|
||||
row.appendChild(el("div", { className: "item-row__controls" }, [beforeBtn, afterBtn]));
|
||||
}
|
||||
|
||||
row.addEventListener("dragstart", (e) => {
|
||||
e.dataTransfer.setData("text/plain", String(item.id));
|
||||
e.dataTransfer.effectAllowed = "move";
|
||||
row.classList.add("dragging");
|
||||
});
|
||||
row.addEventListener("dragend", () => row.classList.remove("dragging"));
|
||||
row.addEventListener("dragover", (e) => { e.preventDefault(); e.dataTransfer.dropEffect = "move"; });
|
||||
row.addEventListener("drop", (e) => {
|
||||
e.preventDefault();
|
||||
const draggedId = Number(e.dataTransfer.getData("text/plain"));
|
||||
if (draggedId === item.id) return;
|
||||
const fromIndex = items.findIndex((it) => it.id === draggedId);
|
||||
const toIndex = items.findIndex((it) => it.id === item.id);
|
||||
if (fromIndex === -1 || toIndex === -1) return;
|
||||
const [moved] = items.splice(fromIndex, 1);
|
||||
items.splice(toIndex, 0, moved);
|
||||
render();
|
||||
});
|
||||
|
||||
itemList.appendChild(row);
|
||||
});
|
||||
renderOutline();
|
||||
}
|
||||
|
||||
// --- Outline preview -----------------------------------------------------
|
||||
|
||||
function extractHeadings(text) {
|
||||
const headings = [];
|
||||
const lines = text.split(/\r?\n/);
|
||||
let inFence = false;
|
||||
let fenceChar = "";
|
||||
for (const line of lines) {
|
||||
const fenceMatch = /^ {0,3}(`{3,}|~{3,})/.exec(line);
|
||||
if (fenceMatch) {
|
||||
if (!inFence) { inFence = true; fenceChar = fenceMatch[1][0]; }
|
||||
else if (fenceMatch[1][0] === fenceChar) inFence = false;
|
||||
continue;
|
||||
}
|
||||
if (inFence) continue;
|
||||
const m = /^(#{1,6})\s+(.+?)\s*#*\s*$/.exec(line);
|
||||
if (m) headings.push({ level: m[1].length, text: m[2].trim() });
|
||||
}
|
||||
return headings;
|
||||
}
|
||||
|
||||
function renderOutline() {
|
||||
outline.innerHTML = "";
|
||||
const usable = items.filter((it) => !it.error);
|
||||
const entries = [];
|
||||
for (const item of usable) {
|
||||
for (const h of extractHeadings(item.body)) entries.push({ level: h.level, text: h.text, source: item.titel });
|
||||
}
|
||||
if (!entries.length) {
|
||||
outline.appendChild(el("div", { className: "hint", text: "Noch keine Überschriften erkannt." }));
|
||||
return;
|
||||
}
|
||||
const baseLevel = Math.min(...entries.map((e) => e.level));
|
||||
const counters = [0, 0, 0, 0, 0, 0];
|
||||
for (const e of entries) {
|
||||
counters[e.level - 1] += 1;
|
||||
for (let i = e.level; i < 6; i++) counters[i] = 0;
|
||||
e.number = counters.slice(baseLevel - 1, e.level).join(".");
|
||||
}
|
||||
for (const e of entries) {
|
||||
outline.appendChild(el("div", { className: "outline-row", style: "padding-left:" + (e.level - baseLevel) * 1.1 + "rem;" }, [
|
||||
el("span", { className: "outline-number", text: e.number }),
|
||||
el("span", { text: e.text }),
|
||||
el("span", { className: "outline-source", text: e.source })
|
||||
]));
|
||||
}
|
||||
}
|
||||
|
||||
// --- Images: fetch same-origin references and rename them locally -------
|
||||
// Only relevant for zip/Word: Word (Pandoc WASM) can't fetch https images
|
||||
// itself (no network access from the WASM sandbox), and a zip should be
|
||||
// browsable offline. The plain markdown file, on the other hand,
|
||||
// deliberately keeps the absolute URLs (works anywhere the file
|
||||
// currently has an internet connection, without separately bundled
|
||||
// images).
|
||||
|
||||
const IMAGE_RE = /!\[([^\]]*)\]\(([^)\s]+)(?:\s+"[^"]*")?\)/g;
|
||||
|
||||
function sanitizeFileName(name) {
|
||||
return name.replace(/[\\/:*?"<>|]+/g, "_");
|
||||
}
|
||||
|
||||
async function collectAssets(usableItems) {
|
||||
const urlToLocalName = new Map();
|
||||
const files = new Map(); // localName -> Blob
|
||||
const used = new Set();
|
||||
|
||||
for (const item of usableItems) {
|
||||
IMAGE_RE.lastIndex = 0;
|
||||
let m;
|
||||
while ((m = IMAGE_RE.exec(item.body))) {
|
||||
const src = m[2];
|
||||
let parsed;
|
||||
try { parsed = new URL(src, window.location.href); } catch (e) { continue; }
|
||||
if (parsed.origin !== window.location.origin) continue;
|
||||
if (urlToLocalName.has(parsed.href)) continue;
|
||||
|
||||
let base = sanitizeFileName(decodeURIComponent(parsed.pathname.split("/").pop() || "bild"));
|
||||
let candidate = base;
|
||||
let n = 1;
|
||||
while (used.has(candidate)) { candidate = base.replace(/(\.[^.]*)?$/, "_" + (++n) + "$1"); }
|
||||
used.add(candidate);
|
||||
urlToLocalName.set(parsed.href, candidate);
|
||||
|
||||
try {
|
||||
const res = await fetch(parsed.href);
|
||||
if (res.ok) files.set(candidate, await res.blob());
|
||||
} catch (e) {
|
||||
// Image stays unreachable - the reference is rewritten anyway,
|
||||
// it just ends up missing in the result (analogous to the known
|
||||
// limitation in pandoc_ebh_paket, see its README).
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function rewrite(body, pathPrefix) {
|
||||
return body.replace(IMAGE_RE, (whole, alt, src) => {
|
||||
let parsed;
|
||||
try { parsed = new URL(src, window.location.href); } catch (e) { return whole; }
|
||||
const local = urlToLocalName.get(parsed.href);
|
||||
if (!local) return whole;
|
||||
return "";
|
||||
});
|
||||
}
|
||||
|
||||
return { files, rewrite };
|
||||
}
|
||||
|
||||
// --- Download: trigger via an invisible link -----------------------------
|
||||
|
||||
function triggerDownload(blob, filename) {
|
||||
const url = URL.createObjectURL(blob);
|
||||
const a = el("a", { href: url, download: filename });
|
||||
document.body.appendChild(a);
|
||||
a.click();
|
||||
a.remove();
|
||||
setTimeout(() => URL.revokeObjectURL(url), 10000);
|
||||
}
|
||||
|
||||
function safeBaseName() {
|
||||
const base = (titelInput.value || "methoden-set").trim() || "methoden-set";
|
||||
return sanitizeFileName(base);
|
||||
}
|
||||
|
||||
function usable() {
|
||||
return items.filter((it) => !it.error && it.body);
|
||||
}
|
||||
|
||||
// --- As a folder (.zip) ---------------------------------------------------
|
||||
|
||||
btnZip.addEventListener("click", async () => {
|
||||
const list = usable();
|
||||
if (!list.length) { setStatus("Bitte mindestens eine gültig geladene Variante einfügen.", "error"); return; }
|
||||
btnZip.disabled = true;
|
||||
setStatus("Zip wird zusammengestellt …", "busy");
|
||||
try {
|
||||
const { files, rewrite } = await collectAssets(list);
|
||||
const entries = [];
|
||||
list.forEach((item, index) => {
|
||||
const name = String(index + 1).padStart(2, "0") + "-" + sanitizeFileName(item.titel).slice(0, 60) + ".md";
|
||||
const content = rewrite(item.body, "bilder/");
|
||||
entries.push({ path: name, data: new TextEncoder().encode(content) });
|
||||
});
|
||||
for (const [name, blob] of files) {
|
||||
entries.push({ path: "bilder/" + name, data: new Uint8Array(await blob.arrayBuffer()) });
|
||||
}
|
||||
const zipBlob = AblegerZip.write(entries);
|
||||
triggerDownload(zipBlob, safeBaseName() + ".zip");
|
||||
setStatus("Fertig – Download gestartet.", "ok");
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
setStatus("Fehler: " + (err && err.message ? err.message : err), "error");
|
||||
} finally {
|
||||
btnZip.disabled = false;
|
||||
}
|
||||
});
|
||||
|
||||
// --- As markdown (one file) ------------------------------------------------
|
||||
|
||||
btnMd.addEventListener("click", () => {
|
||||
const list = usable();
|
||||
if (!list.length) { setStatus("Bitte mindestens eine gültig geladene Variante einfügen.", "error"); return; }
|
||||
const parts = [
|
||||
"# " + (titelInput.value || "Methoden-Set").trim(),
|
||||
...list.map((item) => item.body.trim())
|
||||
];
|
||||
const blob = new Blob([parts.join("\n\n---\n\n")], { type: "text/markdown;charset=utf-8" });
|
||||
triggerDownload(blob, safeBaseName() + ".md");
|
||||
setStatus("Fertig – Download gestartet.", "ok");
|
||||
});
|
||||
|
||||
// --- As Word (.docx) via Pandoc WASM ----------------------------------------
|
||||
// Loads pandoc.wasm + the loader patched for offline capability only on
|
||||
// demand (not on page load) - see methoden-set/vendor/.
|
||||
|
||||
let pandocInstancePromise = null;
|
||||
|
||||
function loadPandocCoreModule() {
|
||||
const base = new URL("vendor/wasi-shim/", window.location.href);
|
||||
return Promise.all([
|
||||
fetch(new URL("wasi_defs.js", base)).then((r) => r.text()),
|
||||
fetch(new URL("debug.js", base)).then((r) => r.text()),
|
||||
fetch(new URL("fd.js", base)).then((r) => r.text()),
|
||||
fetch(new URL("fs_mem.js", base)).then((r) => r.text()),
|
||||
fetch(new URL("wasi.js", base)).then((r) => r.text()),
|
||||
fetch(new URL("pandoc-core-adapted.js", base)).then((r) => r.text())
|
||||
]).then(([defsSrc, debugSrc, fdSrc, fsMemSrc, wasiSrc, coreSrc]) => {
|
||||
const defsUrl = URL.createObjectURL(new Blob([defsSrc], { type: "text/javascript" }));
|
||||
const debugUrl = URL.createObjectURL(new Blob([debugSrc], { type: "text/javascript" }));
|
||||
|
||||
const fdPatched = fdSrc.split('"./wasi_defs.js"').join('"' + defsUrl + '"');
|
||||
const fdUrl = URL.createObjectURL(new Blob([fdPatched], { type: "text/javascript" }));
|
||||
|
||||
const fsMemPatched = fsMemSrc
|
||||
.split('"./debug.js"').join('"' + debugUrl + '"')
|
||||
.split('"./wasi_defs.js"').join('"' + defsUrl + '"')
|
||||
.split('"./fd.js"').join('"' + fdUrl + '"');
|
||||
const fsMemUrl = URL.createObjectURL(new Blob([fsMemPatched], { type: "text/javascript" }));
|
||||
|
||||
const wasiPatched = wasiSrc
|
||||
.split('"./wasi_defs.js"').join('"' + defsUrl + '"')
|
||||
.split('"./debug.js"').join('"' + debugUrl + '"');
|
||||
const wasiUrl = URL.createObjectURL(new Blob([wasiPatched], { type: "text/javascript" }));
|
||||
|
||||
const corePatched = coreSrc
|
||||
.split('"__WASI_SHIM_FS_MEM_URL__"').join('"' + fsMemUrl + '"')
|
||||
.split('"__WASI_SHIM_WASI_URL__"').join('"' + wasiUrl + '"');
|
||||
const coreUrl = URL.createObjectURL(new Blob([corePatched], { type: "text/javascript" }));
|
||||
|
||||
return import(/* webpackIgnore: true */ coreUrl);
|
||||
});
|
||||
}
|
||||
|
||||
function loadPandoc() {
|
||||
if (pandocInstancePromise) return pandocInstancePromise;
|
||||
pandocInstancePromise = (async () => {
|
||||
setStatus("Pandoc wird geladen (einmalig, ca. 58 MB, kann etwas dauern) …", "busy");
|
||||
const [core, wasmResponse] = await Promise.all([
|
||||
loadPandocCoreModule(),
|
||||
fetch(new URL("vendor/pandoc.wasm", window.location.href))
|
||||
]);
|
||||
const wasmBytes = await wasmResponse.arrayBuffer();
|
||||
return core.createPandocInstance(wasmBytes);
|
||||
})();
|
||||
return pandocInstancePromise;
|
||||
}
|
||||
|
||||
// --- Template selection: from vorlagen/vorlagen-manifest.json -----------
|
||||
// Generated on every deploy from the actual contents of methoden-set/
|
||||
// vorlagen/ on the server (scripts/generate-vorlagen-manifest.rb, see
|
||||
// the Methoden-Set chapter on the project website) - also captures templates someone copied onto
|
||||
// the server manually, not just the ones from this repo. If the file is
|
||||
// missing (e.g. in a local preview without the deploy hook), the app
|
||||
// falls back to the two known default templates instead of staying
|
||||
// empty.
|
||||
let vorlagenManifest = null;
|
||||
|
||||
async function ladeVorlagenManifest() {
|
||||
if (vorlagenManifest) return vorlagenManifest;
|
||||
try {
|
||||
const res = await fetch(new URL("vorlagen/vorlagen-manifest.json", window.location.href));
|
||||
if (!res.ok) throw new Error("Status " + res.status);
|
||||
vorlagenManifest = await res.json();
|
||||
} catch (e) {
|
||||
vorlagenManifest = [
|
||||
{ datei: "ableger-standard.docx", format: "docx", label: "Ableger Standard" },
|
||||
{ datei: "ableger-standard.odt", format: "odt", label: "Ableger Standard" }
|
||||
];
|
||||
}
|
||||
return vorlagenManifest;
|
||||
}
|
||||
|
||||
function aktualisiereDateiFeld() {
|
||||
const datei = document.getElementById("vorlage-datei");
|
||||
if (!datei) return;
|
||||
datei.disabled = document.querySelector('input[name="vorlage"]:checked').value !== "eigen";
|
||||
}
|
||||
|
||||
async function renderVorlagenListe() {
|
||||
const format = currentFormat();
|
||||
const manifest = await ladeVorlagenManifest();
|
||||
const passend = manifest.filter((e) => e.format === format);
|
||||
|
||||
vorlageListe.innerHTML = "";
|
||||
passend.forEach((eintrag, index) => {
|
||||
const radio = el("input", { type: "radio", name: "vorlage", value: eintrag.datei, checked: index === 0 });
|
||||
vorlageListe.appendChild(el("label", {}, [radio, document.createTextNode(" " + eintrag.label)]));
|
||||
radio.addEventListener("change", aktualisiereDateiFeld);
|
||||
});
|
||||
|
||||
const eigenRadio = el("input", { type: "radio", name: "vorlage", value: "eigen", checked: !passend.length });
|
||||
vorlageListe.appendChild(el("label", {}, [eigenRadio, document.createTextNode(" Eigene Vorlage hochladen")]));
|
||||
eigenRadio.addEventListener("change", aktualisiereDateiFeld);
|
||||
|
||||
const dateiInput = el("input", { type: "file", id: "vorlage-datei", accept: "." + format, disabled: passend.length > 0 });
|
||||
vorlageListe.appendChild(dateiInput);
|
||||
}
|
||||
|
||||
// Reference templates are format-bound (a .docx template doesn't work
|
||||
// for odt output and vice versa) - the template list and button label
|
||||
// therefore adapt to the format choice.
|
||||
function aktualisiereFormatUI() {
|
||||
btnDokument.textContent = currentFormat() === "odt" ? "OpenDocument erstellen" : "Word-Dokument erstellen";
|
||||
renderVorlagenListe();
|
||||
}
|
||||
formatRadios.forEach((radio) => radio.addEventListener("change", aktualisiereFormatUI));
|
||||
aktualisiereFormatUI();
|
||||
|
||||
async function currentReferenceDoc(format) {
|
||||
const gewaehlt = document.querySelector('input[name="vorlage"]:checked').value;
|
||||
const dateiInput = document.getElementById("vorlage-datei");
|
||||
if (gewaehlt === "eigen") {
|
||||
if (!dateiInput || !dateiInput.files[0]) throw new Error("Bitte eine eigene Vorlage-Datei auswählen.");
|
||||
return dateiInput.files[0];
|
||||
}
|
||||
const res = await fetch(new URL("vorlagen/" + gewaehlt, window.location.href));
|
||||
return res.blob();
|
||||
}
|
||||
|
||||
btnDokument.addEventListener("click", async () => {
|
||||
const list = usable();
|
||||
if (!list.length) { setStatus("Bitte mindestens eine gültig geladene Variante einfügen.", "error"); return; }
|
||||
const format = currentFormat();
|
||||
btnDokument.disabled = true;
|
||||
try {
|
||||
const instance = await loadPandoc();
|
||||
setStatus("Dokument wird erstellt …", "busy");
|
||||
|
||||
const { files, rewrite } = await collectAssets(list);
|
||||
const pageBreak = '```{=openxml}\n<w:p><w:r><w:br w:type="page"/></w:r></w:p>\n```';
|
||||
const body = list
|
||||
.map((item, index) => {
|
||||
let chunk = rewrite(item.body, "").trim();
|
||||
if (item.pageBreakBefore && index > 0) chunk = pageBreak + "\n\n" + chunk;
|
||||
if (item.pageBreakAfter && index < list.length - 1) chunk = chunk + "\n\n" + pageBreak;
|
||||
return chunk;
|
||||
})
|
||||
.join("\n\n");
|
||||
|
||||
const titel = (titelInput.value || "Methoden-Set").trim();
|
||||
const fullMarkdown = "---\ntitle: " + JSON.stringify(titel) + "\n---\n\n" + body;
|
||||
|
||||
const referenceBlob = await currentReferenceDoc(format);
|
||||
const referenceFileName = "reference." + format;
|
||||
|
||||
const filesForConvert = { [referenceFileName]: referenceBlob };
|
||||
for (const [name, blob] of files) filesForConvert[name] = blob;
|
||||
|
||||
const options = {
|
||||
from: "markdown",
|
||||
to: format,
|
||||
standalone: true,
|
||||
"reference-doc": referenceFileName,
|
||||
"output-file": "output." + format
|
||||
};
|
||||
if (document.getElementById("toc-checkbox").checked) {
|
||||
options["table-of-contents"] = true;
|
||||
options.metadata = { "toc-title": "Inhalt" };
|
||||
}
|
||||
if (document.getElementById("numsections-checkbox").checked) {
|
||||
options["number-sections"] = true;
|
||||
}
|
||||
|
||||
const result = await instance.convert(options, fullMarkdown, filesForConvert);
|
||||
if (result.stderr) console.warn("[pandoc stderr]", result.stderr);
|
||||
|
||||
const missingImages = Array.from(new Set(
|
||||
(result.warnings || [])
|
||||
.filter((w) => w.type === "CouldNotFetchResource" && w.path)
|
||||
.map((w) => w.path)
|
||||
));
|
||||
if (missingImages.length) {
|
||||
setStatus("Fertig, aber diese Bilder fehlen im Dokument: " + missingImages.join(", "), "error");
|
||||
} else {
|
||||
setStatus("Fertig – Download gestartet.", "ok");
|
||||
}
|
||||
|
||||
const outputBlob = result.files["output." + format];
|
||||
if (!outputBlob || !outputBlob.size) throw new Error("Pandoc hat keine Ausgabedatei erzeugt. Details siehe Browser-Konsole.");
|
||||
triggerDownload(outputBlob, safeBaseName() + "." + format);
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
setStatus("Fehler: " + (err && err.message ? err.message : err), "error");
|
||||
} finally {
|
||||
btnDokument.disabled = false;
|
||||
}
|
||||
});
|
||||
|
||||
render();
|
||||
setStatus("Bereit.", "ok");
|
||||
})();
|
||||
@@ -0,0 +1,155 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="de">
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||
<title>Ableger – Methoden-Set</title>
|
||||
<!-- Same stylesheet as the Hugo website (site-header/site-title/
|
||||
site-nav, color variables) - see admin/index.html for the same pattern. -->
|
||||
<link rel="stylesheet" href="/css/style.css">
|
||||
<style>
|
||||
#methoden-set { max-width: 46rem; margin: 0 auto; padding: 1.5rem 1.25rem 4rem; }
|
||||
#methoden-set h1 { font-size: 1.5rem; margin: 0 0 0.25rem; }
|
||||
#methoden-set .lead { color: var(--color-muted); margin: 0 0 2rem; }
|
||||
#methoden-set h2 { font-size: 1.1rem; border-bottom: 1px solid var(--color-border); padding-bottom: 0.25rem; margin: 2rem 0 1rem; }
|
||||
#methoden-set .schritt-nr {
|
||||
display: inline-flex; align-items: center; justify-content: center;
|
||||
width: 1.6rem; height: 1.6rem; border-radius: 50%;
|
||||
background: var(--color-accent); color: var(--color-accent-contrast);
|
||||
font-size: 0.85rem; font-weight: 700; margin-right: 0.5rem;
|
||||
}
|
||||
#methoden-set .hint { color: var(--color-muted); font-size: 0.875rem; margin: 0.35rem 0 0.75rem; }
|
||||
#methoden-set textarea,
|
||||
#methoden-set input[type="text"],
|
||||
#methoden-set input[type="url"],
|
||||
#methoden-set select {
|
||||
width: 100%; box-sizing: border-box; padding: 0.55rem 0.7rem;
|
||||
border: 1px solid var(--color-border); border-radius: var(--radius);
|
||||
background: var(--color-card-bg); color: var(--color-text); font: inherit;
|
||||
}
|
||||
#methoden-set textarea:focus-visible,
|
||||
#methoden-set input:focus-visible,
|
||||
#methoden-set select:focus-visible { outline: 3px solid var(--color-accent); outline-offset: 1px; }
|
||||
#methoden-set button {
|
||||
font: inherit; cursor: pointer; border-radius: var(--radius);
|
||||
padding: 0.55rem 1rem; border: 1px solid var(--color-border);
|
||||
background: var(--color-card-bg); color: var(--color-text);
|
||||
}
|
||||
#methoden-set button:hover { border-color: var(--color-accent); }
|
||||
#methoden-set button:disabled { opacity: 0.5; cursor: not-allowed; }
|
||||
#methoden-set button.primary { background: var(--color-accent); color: var(--color-accent-contrast); border-color: var(--color-accent); }
|
||||
#methoden-set .link-form { display: flex; gap: 0.5rem; align-items: flex-start; }
|
||||
#methoden-set .link-form textarea { flex: 1; resize: vertical; min-height: 2.6rem; font-family: inherit; }
|
||||
#methoden-set .item-list { display: flex; flex-direction: column; gap: 0.5rem; margin: 0.75rem 0; }
|
||||
#methoden-set .item-row {
|
||||
display: flex; flex-direction: column; gap: 0.5rem; padding: 0.65rem 0.75rem;
|
||||
border: 1px solid var(--color-border); border-radius: var(--radius); background: var(--color-card-bg);
|
||||
}
|
||||
#methoden-set .item-row[draggable="true"] { cursor: grab; }
|
||||
#methoden-set .item-row.dragging { opacity: 0.4; }
|
||||
#methoden-set .item-row.error { border-color: #b3261e; }
|
||||
#methoden-set .item-row__main { display: flex; align-items: center; gap: 0.6rem; min-width: 0; }
|
||||
#methoden-set .drag-handle { color: var(--color-muted); flex: none; }
|
||||
#methoden-set .item-name { flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
#methoden-set .item-row__error { color: #b3261e; font-size: 0.85rem; padding-left: 1.6rem; }
|
||||
#methoden-set .item-row__controls { display: flex; gap: 0.5rem; flex-wrap: wrap; padding-left: 1.6rem; }
|
||||
#methoden-set .pb-toggle {
|
||||
font-size: 0.78rem; padding: 0.4rem 0.75rem; border-radius: 999px;
|
||||
border: 1px solid var(--color-border); background: transparent; color: var(--color-muted);
|
||||
display: inline-flex; align-items: center; gap: 0.35rem; min-height: 2rem;
|
||||
}
|
||||
#methoden-set .pb-toggle::before { content: ""; width: 0.7rem; height: 0.7rem; border-radius: 50%; border: 1px solid currentColor; flex: none; }
|
||||
#methoden-set .pb-toggle[aria-pressed="true"] { background: var(--color-accent); color: var(--color-accent-contrast); border-color: var(--color-accent); }
|
||||
#methoden-set .pb-toggle[aria-pressed="true"]::before { background: currentColor; }
|
||||
#methoden-set .pb-toggle:disabled { opacity: 0.4; cursor: not-allowed; }
|
||||
#methoden-set .icon-btn { border: none; background: none; padding: 0.3rem 0.5rem; flex: none; font-size: 1rem; }
|
||||
#methoden-set .outline { font-size: 0.875rem; }
|
||||
#methoden-set .outline-row { padding: 0.15rem 0; display: flex; gap: 0.5rem; }
|
||||
#methoden-set .outline-number { color: var(--color-muted); min-width: 2.5rem; }
|
||||
#methoden-set .outline-source { color: var(--color-muted); margin-left: auto; font-size: 0.78rem; }
|
||||
#methoden-set .download-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(11rem, 1fr)); gap: 0.75rem; margin-top: 1rem; }
|
||||
#methoden-set .vorlage-wahl { display: flex; flex-direction: column; gap: 0.5rem; margin: 0.75rem 0 1.25rem; }
|
||||
#methoden-set .vorlage-wahl label { display: flex; align-items: center; gap: 0.5rem; font-size: 0.9rem; }
|
||||
#methoden-set #status { margin-top: 1rem; font-size: 0.9rem; min-height: 1.3em; }
|
||||
#methoden-set #status[data-state="busy"] { color: var(--color-muted); }
|
||||
#methoden-set #status[data-state="error"] { color: #b3261e; }
|
||||
#methoden-set #status[data-state="ok"] { color: var(--color-accent); }
|
||||
#methoden-set .feld { margin: 0 0 1rem; }
|
||||
#methoden-set .feld label { display: block; font-size: 0.85rem; font-weight: 600; margin-bottom: 0.3rem; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<header class="site-header">
|
||||
<a class="site-title" href="/">
|
||||
<img src="/img/logo.svg" alt="" class="site-logo" width="32" height="32">
|
||||
Ableger
|
||||
</a>
|
||||
<nav class="site-nav">
|
||||
<a href="/">← Zur Website</a>
|
||||
</nav>
|
||||
</header>
|
||||
<main id="methoden-set">
|
||||
<h1>Methoden-Set zusammenstellen</h1>
|
||||
<p class="lead">
|
||||
Mehrere Methoden von der Ableger-Website zu einer eigenen Sammlung
|
||||
zusammenfassen und als Ordner, als eine Markdown-Datei oder als
|
||||
Word-Dokument herunterladen. Läuft vollständig in diesem Browser -
|
||||
nichts wird irgendwohin übertragen.
|
||||
</p>
|
||||
|
||||
<h2><span class="schritt-nr">1</span>Links einfügen</h2>
|
||||
<p class="hint">
|
||||
Links auf einzelne Methoden oder Varianten dieser Website - keine
|
||||
fremden Adressen. Bei Methoden mit mehreren Varianten bitte den Link
|
||||
der gewünschten Variante einfügen (auf der Methoden-Seite verlinkt).
|
||||
Mehrere Links auf einmal: einen pro Zeile einfügen.
|
||||
</p>
|
||||
<form class="link-form" id="link-form">
|
||||
<label for="link-input" class="visually-hidden">Links, einer pro Zeile</label>
|
||||
<textarea id="link-input" rows="1" placeholder="https://…/name-der-variante/" required></textarea>
|
||||
<button type="submit" class="primary">Hinzufügen</button>
|
||||
</form>
|
||||
|
||||
<h2><span class="schritt-nr">2</span>Reihenfolge festlegen</h2>
|
||||
<p class="hint">Per Ziehen sortieren. Seitenumbruch-Regler wirken sich nur auf den Word-Export aus.</p>
|
||||
<div class="item-list" id="item-list"></div>
|
||||
|
||||
<details>
|
||||
<summary class="hint" style="cursor:pointer;">Gliederungsvorschau</summary>
|
||||
<div class="outline" id="outline"></div>
|
||||
</details>
|
||||
|
||||
<h2><span class="schritt-nr">3</span>Herunterladen</h2>
|
||||
|
||||
<div class="feld">
|
||||
<label for="titel-input">Titel des Sets</label>
|
||||
<input type="text" id="titel-input" value="Methoden-Set">
|
||||
</div>
|
||||
|
||||
<div class="vorlage-wahl">
|
||||
<label><input type="radio" name="format" value="docx" checked> Word (.docx)</label>
|
||||
<label><input type="radio" name="format" value="odt"> OpenDocument (.odt)</label>
|
||||
</div>
|
||||
|
||||
<div class="vorlage-wahl" id="vorlage-liste">
|
||||
<!-- filled by app.js from vorlagen/vorlagen-manifest.json (see the Methoden-Set chapter on the project website) -->
|
||||
</div>
|
||||
|
||||
<div class="vorlage-wahl">
|
||||
<label><input type="checkbox" id="toc-checkbox" checked> Inhaltsverzeichnis</label>
|
||||
<label><input type="checkbox" id="numsections-checkbox"> Kapitelnummerierung</label>
|
||||
</div>
|
||||
<p class="hint">Format, Vorlage, Inhaltsverzeichnis und Kapitelnummerierung wirken sich nur auf den Dokument-Export aus.</p>
|
||||
|
||||
<div class="download-grid">
|
||||
<button type="button" id="btn-zip">Als Ordner (.zip)</button>
|
||||
<button type="button" id="btn-md">Als Markdown</button>
|
||||
<button type="button" id="btn-dokument" class="primary">Dokument erstellen</button>
|
||||
</div>
|
||||
|
||||
<p id="status" role="status" aria-live="polite"></p>
|
||||
</main>
|
||||
<script src="/methoden-set/zip-writer.js"></script>
|
||||
<script src="/methoden-set/app.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
Vendored
BIN
Binary file not shown.
+1
@@ -0,0 +1 @@
|
||||
let Debug=class Debug{enable(enabled){this.log=createLogger(enabled===undefined?true:enabled,this.prefix)}get enabled(){return this.isEnabled}constructor(isEnabled){this.isEnabled=isEnabled;this.prefix="wasi:";this.enable(isEnabled)}};function createLogger(enabled,prefix){if(enabled){const a=console.log.bind(console,"%c%s","color: #265BA0",prefix);return a}else{return()=>{}}}export const debug=new Debug(false);
|
||||
Vendored
+1
@@ -0,0 +1 @@
|
||||
import*as wasi from"./wasi_defs.js";export class Fd{fd_allocate(offset,len){return wasi.ERRNO_NOTSUP}fd_close(){return 0}fd_fdstat_get(){return{ret:wasi.ERRNO_NOTSUP,fdstat:null}}fd_fdstat_set_flags(flags){return wasi.ERRNO_NOTSUP}fd_fdstat_set_rights(fs_rights_base,fs_rights_inheriting){return wasi.ERRNO_NOTSUP}fd_filestat_get(){return{ret:wasi.ERRNO_NOTSUP,filestat:null}}fd_filestat_set_size(size){return wasi.ERRNO_NOTSUP}fd_filestat_set_times(atim,mtim,fst_flags){return wasi.ERRNO_NOTSUP}fd_pread(size,offset){return{ret:wasi.ERRNO_NOTSUP,data:new Uint8Array}}fd_prestat_get(){return{ret:wasi.ERRNO_NOTSUP,prestat:null}}fd_pwrite(data,offset){return{ret:wasi.ERRNO_NOTSUP,nwritten:0}}fd_read(size){return{ret:wasi.ERRNO_NOTSUP,data:new Uint8Array}}fd_readdir_single(cookie){return{ret:wasi.ERRNO_NOTSUP,dirent:null}}fd_seek(offset,whence){return{ret:wasi.ERRNO_NOTSUP,offset:0n}}fd_sync(){return 0}fd_tell(){return{ret:wasi.ERRNO_NOTSUP,offset:0n}}fd_write(data){return{ret:wasi.ERRNO_NOTSUP,nwritten:0}}path_create_directory(path){return wasi.ERRNO_NOTSUP}path_filestat_get(flags,path){return{ret:wasi.ERRNO_NOTSUP,filestat:null}}path_filestat_set_times(flags,path,atim,mtim,fst_flags){return wasi.ERRNO_NOTSUP}path_link(path,inode,allow_dir){return wasi.ERRNO_NOTSUP}path_unlink(path){return{ret:wasi.ERRNO_NOTSUP,inode_obj:null}}path_lookup(path,dirflags){return{ret:wasi.ERRNO_NOTSUP,inode_obj:null}}path_open(dirflags,path,oflags,fs_rights_base,fs_rights_inheriting,fd_flags){return{ret:wasi.ERRNO_NOTDIR,fd_obj:null}}path_readlink(path){return{ret:wasi.ERRNO_NOTSUP,data:null}}path_remove_directory(path){return wasi.ERRNO_NOTSUP}path_rename(old_path,new_fd,new_path){return wasi.ERRNO_NOTSUP}path_unlink_file(path){return wasi.ERRNO_NOTSUP}}export class Inode{static issue_ino(){return Inode.next_ino++}static root_ino(){return 0n}constructor(){this.ino=Inode.issue_ino()}}Inode.next_ino=1n;
|
||||
+1
File diff suppressed because one or more lines are too long
@@ -0,0 +1,396 @@
|
||||
/* pandoc-wasm: Core pandoc logic (environment-agnostic)
|
||||
|
||||
This file contains all the pandoc conversion logic but doesn't handle
|
||||
WASM loading. The WASM binary must be provided by the caller.
|
||||
|
||||
Unveraendert aus pandoc-wasm@1.1.0 src/core.js uebernommen - einzige
|
||||
Aenderung ist der Import-Block direkt darunter: statt vom bare-specifier
|
||||
"@bjorn3/browser_wasi_shim" (der einen Bundler braucht) wird von zwei
|
||||
Platzhaltern importiert, die die App zur Laufzeit durch echte Blob-URLs
|
||||
ersetzt (siehe loadPandocCoreModule() im App-Code) - dieselbe, bereits
|
||||
getestete Technik wie in tobias_ebh/pandoc_ebh_paket, hier erneut gegen
|
||||
frisch von npm bezogene Dateien angewendet statt aus dessen Vendor-Ordner
|
||||
uebernommen (siehe das Methoden-Set-Kapitel auf der Projekt-Website).
|
||||
*/
|
||||
|
||||
import {
|
||||
ConsoleStdout,
|
||||
Directory,
|
||||
File,
|
||||
OpenFile,
|
||||
PreopenDirectory
|
||||
} from "__WASI_SHIM_FS_MEM_URL__"
|
||||
import WASI from "__WASI_SHIM_WASI_URL__"
|
||||
|
||||
// Initialize and export the pandoc instance creator
|
||||
export function createPandocInstance(wasmBinary) {
|
||||
// Initialize WASM module
|
||||
const args = ["pandoc.wasm", "+RTS", "-H64m", "-RTS"]
|
||||
const env = []
|
||||
const fileSystem = new Map()
|
||||
const fds = [
|
||||
new OpenFile(new File(new Uint8Array(), {readonly: true})),
|
||||
ConsoleStdout.lineBuffered(msg => console.log(`[WASI stdout] ${msg}`)),
|
||||
ConsoleStdout.lineBuffered(msg => console.warn(`[WASI stderr] ${msg}`)),
|
||||
new PreopenDirectory("/", fileSystem)
|
||||
]
|
||||
const options = {debug: false}
|
||||
const wasi = new WASI(args, env, fds, options)
|
||||
|
||||
// Instantiate WASM
|
||||
return WebAssembly.instantiate(wasmBinary, {
|
||||
wasi_snapshot_preview1: wasi.wasiImport
|
||||
}).then(({instance}) => {
|
||||
wasi.initialize(instance)
|
||||
instance.exports.__wasm_call_ctors()
|
||||
|
||||
function memory_data_view() {
|
||||
return new DataView(instance.exports.memory.buffer)
|
||||
}
|
||||
|
||||
const argc_ptr = instance.exports.malloc(4)
|
||||
memory_data_view().setUint32(argc_ptr, args.length, true)
|
||||
const argv = instance.exports.malloc(4 * (args.length + 1))
|
||||
for (let i = 0; i < args.length; ++i) {
|
||||
const arg = instance.exports.malloc(args[i].length + 1)
|
||||
new TextEncoder().encodeInto(
|
||||
args[i],
|
||||
new Uint8Array(
|
||||
instance.exports.memory.buffer,
|
||||
arg,
|
||||
args[i].length
|
||||
)
|
||||
)
|
||||
memory_data_view().setUint8(arg + args[i].length, 0)
|
||||
memory_data_view().setUint32(argv + 4 * i, arg, true)
|
||||
}
|
||||
memory_data_view().setUint32(argv + 4 * args.length, 0, true)
|
||||
const argv_ptr = instance.exports.malloc(4)
|
||||
memory_data_view().setUint32(argv_ptr, argv, true)
|
||||
|
||||
instance.exports.hs_init_with_rtsopts(argc_ptr, argv_ptr)
|
||||
|
||||
// Helper function to add file to filesystem
|
||||
// Accepts either a Blob or a string
|
||||
async function addFile(filename, data, readonly) {
|
||||
let uint8Array
|
||||
if (typeof data === "string") {
|
||||
// Convert string to Uint8Array
|
||||
uint8Array = new TextEncoder().encode(data)
|
||||
} else {
|
||||
// Assume it's a Blob
|
||||
const buffer = await data.arrayBuffer()
|
||||
uint8Array = new Uint8Array(buffer)
|
||||
}
|
||||
const file = new File(uint8Array, {readonly: readonly})
|
||||
fileSystem.set(filename, file)
|
||||
}
|
||||
|
||||
// Main API: query function
|
||||
function query(options) {
|
||||
const opts_str = JSON.stringify(options)
|
||||
const encoded = new TextEncoder().encode(opts_str)
|
||||
// Allocate memory based on byte length, not character count
|
||||
const opts_ptr = instance.exports.malloc(encoded.length)
|
||||
new TextEncoder().encodeInto(
|
||||
opts_str,
|
||||
new Uint8Array(
|
||||
instance.exports.memory.buffer,
|
||||
opts_ptr,
|
||||
encoded.length
|
||||
)
|
||||
)
|
||||
|
||||
// Setup filesystem
|
||||
fileSystem.clear()
|
||||
const out_file = new File(new Uint8Array(), {readonly: false})
|
||||
const err_file = new File(new Uint8Array(), {readonly: false})
|
||||
fileSystem.set("stdout", out_file)
|
||||
fileSystem.set("stderr", err_file)
|
||||
|
||||
instance.exports.query(opts_ptr, encoded.length)
|
||||
|
||||
const err_text = new TextDecoder("utf-8", {fatal: true}).decode(
|
||||
err_file.data
|
||||
)
|
||||
if (err_text) {
|
||||
console.log(err_text)
|
||||
}
|
||||
const out_text = new TextDecoder("utf-8", {fatal: true}).decode(
|
||||
out_file.data
|
||||
)
|
||||
return JSON.parse(out_text)
|
||||
}
|
||||
|
||||
// Main API: convert function
|
||||
async function convert(options, stdin, files) {
|
||||
const opts_str = JSON.stringify(options)
|
||||
|
||||
const encoded = new TextEncoder().encode(opts_str)
|
||||
const opts_ptr = instance.exports.malloc(encoded.length)
|
||||
new TextEncoder().encodeInto(
|
||||
opts_str,
|
||||
new Uint8Array(
|
||||
instance.exports.memory.buffer,
|
||||
opts_ptr,
|
||||
encoded.length
|
||||
)
|
||||
)
|
||||
|
||||
// Clone files object to avoid mutating the input parameter
|
||||
files = {...files}
|
||||
|
||||
// Setup filesystem
|
||||
fileSystem.clear()
|
||||
const in_file = new File(new Uint8Array(), {readonly: true})
|
||||
const out_file = new File(new Uint8Array(), {readonly: false})
|
||||
const err_file = new File(new Uint8Array(), {readonly: false})
|
||||
const warnings_file = new File(new Uint8Array(), {readonly: false})
|
||||
fileSystem.set("stdin", in_file)
|
||||
fileSystem.set("stdout", out_file)
|
||||
fileSystem.set("stderr", err_file)
|
||||
fileSystem.set("warnings", warnings_file)
|
||||
|
||||
// Track known files to detect newly created media files
|
||||
// We track system files, input files, output files, and extract-media archives
|
||||
const knownFiles = new Set([
|
||||
"stdin",
|
||||
"stdout",
|
||||
"stderr",
|
||||
"warnings"
|
||||
])
|
||||
|
||||
// Add input files (can be Blobs or strings)
|
||||
for (const filename in files) {
|
||||
await addFile(filename, files[filename], true)
|
||||
knownFiles.add(filename)
|
||||
}
|
||||
|
||||
// Track output file and extract-media separately
|
||||
// These should NOT be included in mediaFiles (only extracted media should be)
|
||||
const outputFileName = options["output-file"] || null
|
||||
const extractMediaPath = options["extract-media"] || null
|
||||
|
||||
// Add output file placeholder if specified
|
||||
if (outputFileName) {
|
||||
await addFile(outputFileName, new Blob(), false)
|
||||
knownFiles.add(outputFileName)
|
||||
}
|
||||
|
||||
// Add placeholder file for extract-media zip archives. For
|
||||
// directory targets nothing is pre-created: pandoc creates the
|
||||
// directory itself, and a file placeholder at that path would
|
||||
// make it fail with ENOTDIR.
|
||||
if (extractMediaPath && extractMediaPath.endsWith(".zip")) {
|
||||
await addFile(extractMediaPath, new Blob(), false)
|
||||
knownFiles.add(extractMediaPath)
|
||||
}
|
||||
|
||||
// Set stdin content
|
||||
if (stdin) {
|
||||
in_file.data = new TextEncoder().encode(stdin)
|
||||
}
|
||||
|
||||
// Run conversion
|
||||
instance.exports.convert(opts_ptr, encoded.length)
|
||||
|
||||
// Collect output file if generated
|
||||
if (options["output-file"]) {
|
||||
const outputFile = fileSystem.get(options["output-file"])
|
||||
if (
|
||||
outputFile &&
|
||||
outputFile.data &&
|
||||
outputFile.data.length > 0
|
||||
) {
|
||||
files[options["output-file"]] = new Blob([outputFile.data])
|
||||
}
|
||||
}
|
||||
|
||||
// Collect extracted media if generated
|
||||
if (options["extract-media"]) {
|
||||
const mediaFile = fileSystem.get(options["extract-media"])
|
||||
if (mediaFile && mediaFile.data && mediaFile.data.length > 0) {
|
||||
files[options["extract-media"]] = new Blob(
|
||||
[mediaFile.data],
|
||||
{
|
||||
type: "application/zip"
|
||||
}
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
// Collect any newly created files (e.g., extracted media images).
|
||||
// Media extracted to a directory is nested (e.g. docx media lands
|
||||
// at "<extract-media>/media/image1.png"), so walk directories
|
||||
// recursively. mediaFiles should ONLY contain extracted media,
|
||||
// NOT the output file or extract-media zip archive (both are
|
||||
// tracked in knownFiles).
|
||||
const mediaFiles = {}
|
||||
const collectNewFiles = (map, prefix) => {
|
||||
for (const [name, entry] of map.entries()) {
|
||||
const path = prefix ? `${prefix}/${name}` : name
|
||||
if (entry instanceof Directory) {
|
||||
collectNewFiles(entry.contents, path)
|
||||
} else if (
|
||||
!knownFiles.has(path) &&
|
||||
entry.data &&
|
||||
entry.data.length > 0
|
||||
) {
|
||||
const blob = new Blob([entry.data])
|
||||
files[path] = blob
|
||||
mediaFiles[path] = blob
|
||||
}
|
||||
}
|
||||
}
|
||||
collectNewFiles(fileSystem, "")
|
||||
|
||||
// Parse warnings
|
||||
const rawWarnings = new TextDecoder("utf-8", {fatal: true}).decode(
|
||||
warnings_file.data
|
||||
)
|
||||
let warnings = []
|
||||
if (rawWarnings) {
|
||||
try {
|
||||
warnings = JSON.parse(rawWarnings)
|
||||
} catch (e) {
|
||||
console.warn("Failed to parse warnings:", e)
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
stdout: new TextDecoder("utf-8", {fatal: true}).decode(
|
||||
out_file.data
|
||||
),
|
||||
stderr: new TextDecoder("utf-8", {fatal: true}).decode(
|
||||
err_file.data
|
||||
),
|
||||
warnings: warnings,
|
||||
files: files,
|
||||
mediaFiles: mediaFiles
|
||||
}
|
||||
}
|
||||
|
||||
// Helper function to convert data to Uint8Array
|
||||
async function toUint8Array(inData) {
|
||||
let uint8Array
|
||||
|
||||
if (typeof inData === "string") {
|
||||
const encoder = new TextEncoder()
|
||||
uint8Array = encoder.encode(inData)
|
||||
} else if (inData instanceof Blob) {
|
||||
const arrayBuffer = await inData.arrayBuffer()
|
||||
uint8Array = new Uint8Array(arrayBuffer)
|
||||
} else {
|
||||
throw new Error(
|
||||
"Unsupported type: inData must be a string or a Blob"
|
||||
)
|
||||
}
|
||||
|
||||
return uint8Array
|
||||
}
|
||||
|
||||
const textDecoder = new TextDecoder("utf-8", {fatal: true})
|
||||
|
||||
function convertData(data) {
|
||||
let outData
|
||||
try {
|
||||
// Attempt to decode as UTF-8 text
|
||||
outData = textDecoder.decode(data)
|
||||
} catch (_e) {
|
||||
// If decoding fails, return as Blob
|
||||
outData = new Blob([data])
|
||||
}
|
||||
return outData
|
||||
}
|
||||
|
||||
// Legacy API: pandoc function (for backward compatibility)
|
||||
async function pandoc(args_str, inData, resources = []) {
|
||||
// Parse command line arguments into options object
|
||||
const argParts = args_str.trim().split(/\s+/)
|
||||
const options = {}
|
||||
const files = {}
|
||||
|
||||
let i = 0
|
||||
while (i < argParts.length) {
|
||||
const arg = argParts[i]
|
||||
|
||||
if (arg === "-f" || arg === "--from") {
|
||||
options.from = argParts[++i]
|
||||
} else if (arg === "-t" || arg === "--to") {
|
||||
options.to = argParts[++i]
|
||||
} else if (arg === "-o" || arg === "--output") {
|
||||
options["output-file"] = argParts[++i]
|
||||
} else if (arg === "-s" || arg === "--standalone") {
|
||||
options.standalone = true
|
||||
} else if (arg === "--extract-media") {
|
||||
options["extract-media"] = argParts[++i]
|
||||
} else if (arg === "--toc" || arg === "--table-of-contents") {
|
||||
options["table-of-contents"] = true
|
||||
}
|
||||
i++
|
||||
}
|
||||
|
||||
// Add resource files (convert to string or keep as Blob)
|
||||
for (const resource of resources) {
|
||||
// If contents is a string, keep it as string
|
||||
// Otherwise, convert to Blob
|
||||
if (typeof resource.contents === "string") {
|
||||
files[resource.filename] = resource.contents
|
||||
} else {
|
||||
const contents = await toUint8Array(resource.contents)
|
||||
files[resource.filename] = new Blob([contents])
|
||||
}
|
||||
}
|
||||
|
||||
// Convert stdin to string
|
||||
let stdin = null
|
||||
if (inData) {
|
||||
if (typeof inData === "string") {
|
||||
stdin = inData
|
||||
} else {
|
||||
const uint8Array = await toUint8Array(inData)
|
||||
stdin = new TextDecoder("utf-8").decode(uint8Array)
|
||||
}
|
||||
}
|
||||
|
||||
// Call convert
|
||||
const result = await convert(options, stdin, files)
|
||||
|
||||
// Convert mediaFiles from Object to Map for legacy API compatibility
|
||||
const mediaFiles = new Map()
|
||||
for (const [name, blob] of Object.entries(result.mediaFiles)) {
|
||||
mediaFiles.set(
|
||||
name,
|
||||
convertData(new Uint8Array(await blob.arrayBuffer()))
|
||||
)
|
||||
}
|
||||
|
||||
// Return in legacy format
|
||||
let out
|
||||
if (
|
||||
options["output-file"] &&
|
||||
result.files[options["output-file"]]
|
||||
) {
|
||||
out = convertData(
|
||||
new Uint8Array(
|
||||
await result.files[options["output-file"]].arrayBuffer()
|
||||
)
|
||||
)
|
||||
} else {
|
||||
out = result.stdout
|
||||
}
|
||||
|
||||
return {
|
||||
out: out,
|
||||
mediaFiles: mediaFiles
|
||||
}
|
||||
}
|
||||
|
||||
// Return the API
|
||||
return {
|
||||
convert,
|
||||
query,
|
||||
pandoc
|
||||
}
|
||||
})
|
||||
}
|
||||
+1
File diff suppressed because one or more lines are too long
+1
File diff suppressed because one or more lines are too long
Binary file not shown.
Binary file not shown.
@@ -0,0 +1,116 @@
|
||||
/* Minimal ZIP writer (only "stored", no compression) - no external library
|
||||
loaded for the zip download, consistent with the principle followed
|
||||
throughout the project of not pulling in CDN/third-party dependencies
|
||||
(see the Methoden-Set chapter on the project website). Uncompressed is unproblematic for a
|
||||
manageable amount of text/image files - correctness over file size. */
|
||||
(function (global) {
|
||||
"use strict";
|
||||
|
||||
const CRC_TABLE = (function () {
|
||||
const table = new Uint32Array(256);
|
||||
for (let n = 0; n < 256; n++) {
|
||||
let c = n;
|
||||
for (let k = 0; k < 8; k++) {
|
||||
c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1;
|
||||
}
|
||||
table[n] = c >>> 0;
|
||||
}
|
||||
return table;
|
||||
})();
|
||||
|
||||
function crc32(bytes) {
|
||||
let crc = 0xffffffff;
|
||||
for (let i = 0; i < bytes.length; i++) {
|
||||
crc = CRC_TABLE[(crc ^ bytes[i]) & 0xff] ^ (crc >>> 8);
|
||||
}
|
||||
return (crc ^ 0xffffffff) >>> 0;
|
||||
}
|
||||
|
||||
function dosDateTime(date) {
|
||||
const time =
|
||||
((date.getHours() & 0x1f) << 11) |
|
||||
((date.getMinutes() & 0x3f) << 5) |
|
||||
((date.getSeconds() >> 1) & 0x1f);
|
||||
const dateVal =
|
||||
(((date.getFullYear() - 1980) & 0x7f) << 9) |
|
||||
(((date.getMonth() + 1) & 0xf) << 5) |
|
||||
(date.getDate() & 0x1f);
|
||||
return { time, date: dateVal };
|
||||
}
|
||||
|
||||
function utf8Bytes(str) {
|
||||
return new TextEncoder().encode(str);
|
||||
}
|
||||
|
||||
/* entries: Array<{ path: string, data: Uint8Array }> - path with "/" as
|
||||
the folder separator, relative to the zip root. Returns a Blob. */
|
||||
function write(entries) {
|
||||
const now = dosDateTime(new Date());
|
||||
const chunks = [];
|
||||
const central = [];
|
||||
let offset = 0;
|
||||
|
||||
for (const entry of entries) {
|
||||
const nameBytes = utf8Bytes(entry.path);
|
||||
const data = entry.data;
|
||||
const crc = crc32(data);
|
||||
|
||||
const local = new DataView(new ArrayBuffer(30));
|
||||
local.setUint32(0, 0x04034b50, true);
|
||||
local.setUint16(4, 20, true); // Version
|
||||
local.setUint16(6, 0x0800, true); // Flags: UTF-8 filenames
|
||||
local.setUint16(8, 0, true); // Method: 0 = stored
|
||||
local.setUint16(10, now.time, true);
|
||||
local.setUint16(12, now.date, true);
|
||||
local.setUint32(14, crc, true);
|
||||
local.setUint32(18, data.length, true);
|
||||
local.setUint32(22, data.length, true);
|
||||
local.setUint16(26, nameBytes.length, true);
|
||||
local.setUint16(28, 0, true);
|
||||
|
||||
chunks.push(new Uint8Array(local.buffer), nameBytes, data);
|
||||
|
||||
const centralHeader = new DataView(new ArrayBuffer(46));
|
||||
centralHeader.setUint32(0, 0x02014b50, true);
|
||||
centralHeader.setUint16(4, 20, true);
|
||||
centralHeader.setUint16(6, 20, true);
|
||||
centralHeader.setUint16(8, 0x0800, true);
|
||||
centralHeader.setUint16(10, 0, true);
|
||||
centralHeader.setUint16(12, now.time, true);
|
||||
centralHeader.setUint16(14, now.date, true);
|
||||
centralHeader.setUint32(16, crc, true);
|
||||
centralHeader.setUint32(20, data.length, true);
|
||||
centralHeader.setUint32(24, data.length, true);
|
||||
centralHeader.setUint16(28, nameBytes.length, true);
|
||||
centralHeader.setUint16(30, 0, true);
|
||||
centralHeader.setUint16(32, 0, true);
|
||||
centralHeader.setUint16(34, 0, true);
|
||||
centralHeader.setUint16(36, 0, true);
|
||||
centralHeader.setUint32(38, 0, true);
|
||||
centralHeader.setUint32(42, offset, true);
|
||||
central.push(new Uint8Array(centralHeader.buffer), nameBytes);
|
||||
|
||||
offset += 30 + nameBytes.length + data.length;
|
||||
}
|
||||
|
||||
const centralStart = offset;
|
||||
let centralSize = 0;
|
||||
for (const part of central) centralSize += part.length;
|
||||
|
||||
const end = new DataView(new ArrayBuffer(22));
|
||||
end.setUint32(0, 0x06054b50, true);
|
||||
end.setUint16(4, 0, true);
|
||||
end.setUint16(6, 0, true);
|
||||
end.setUint16(8, entries.length, true);
|
||||
end.setUint16(10, entries.length, true);
|
||||
end.setUint32(12, centralSize, true);
|
||||
end.setUint32(16, centralStart, true);
|
||||
end.setUint16(20, 0, true);
|
||||
|
||||
return new Blob([...chunks, ...central, new Uint8Array(end.buffer)], {
|
||||
type: "application/zip"
|
||||
});
|
||||
}
|
||||
|
||||
global.AblegerZip = { write };
|
||||
})(window);
|
||||
Reference in New Issue
Block a user