Skillfarm / skills · skillfarm.ai / converted / pptx / scripts / apply_theme.js
| 1 | // Give a deck pptxgenjs wrote its own theme colors and theme name. pptxgenjs sets the theme's |
| 2 | // two fonts (pres.theme) but hard-codes Office's palette, so scheme colors resolve to Office |
| 3 | // blue and orange until the deck's colors are written into ppt/theme/theme1.xml. |
| 4 | // |
| 5 | // const { applyTheme } = require("<this skill's directory>/scripts/apply_theme.js"); |
| 6 | // await pres.writeFile({ fileName: "deck.pptx" }); |
| 7 | // await applyTheme("deck.pptx", { |
| 8 | // name: "Northwind", |
| 9 | // colors: { dk1, lt1, dk2, lt2, accent1, accent2, accent3, accent4, accent5, accent6, hlink, folHlink }, |
| 10 | // }); // extra keys (headFontFace, ...) are ignored, and the twelve colors may sit beside name instead |
| 11 | // |
| 12 | // node scripts/apply_theme.js deck.pptx theme.json [out.pptx] # the same, from a shell |
| 13 | // |
| 14 | // Colors are six hex digits, no "#". The deck is rewritten in place unless a third argument |
| 15 | // names another file. It throws, changing nothing, if a color anywhere in the deck is not six |
| 16 | // hex digits, which is what a scheme color passed to a hex-only option turns into. |
| 17 | // |
| 18 | // As the step that rewrites the deck after pres.writeFile(), it also handles two faults pptxgenjs writes |
| 19 | // that make PowerPoint offer to repair the deck: it mends <c:crossesAt val="autoZero"/>, and it |
| 20 | // throws on a line dash that is not a dash style. |
| 21 | const fs = require("fs"); |
| 22 | |
| 23 | // jszip comes with pptxgenjs but is not always installed where a bare require("jszip") finds |
| 24 | // it, so it is loaded from beside pptxgenjs. Both are found the way any require() in this file |
| 25 | // would find them: from this file's directory upward, then NODE_PATH and Node's global folders. |
| 26 | // No search starts at the working directory or the calling script's directory. |
| 27 | function loadJSZip() { |
| 28 | try { |
| 29 | return require(require.resolve("jszip", { paths: [require.resolve("pptxgenjs")] })); |
| 30 | } catch { |
| 31 | throw new Error(`pptxgenjs and the jszip that comes with it cannot be found from ${__filename}. If pptxgenjs is installed beside your own script, run node with NODE_PATH set to that node_modules folder. Nothing was changed.`); |
| 32 | } |
| 33 | } |
| 34 | |
| 35 | const SLOTS = ["dk1", "lt1", "dk2", "lt2", "accent1", "accent2", "accent3", "accent4", "accent5", "accent6", "hlink", "folHlink"]; |
| 36 | // A name or value from the deck, for an error a model reads: quoted, cut, and with nothing unprintable left raw. |
| 37 | const shown = (s) => JSON.stringify(String(s).slice(0, 80)).replace(/[\p{C}\u2028\u2029]/gu, (c) => "\\u{" + c.codePointAt(0).toString(16) + "}"); |
| 38 | const DASHES = ["solid", "dot", "dash", "lgDash", "dashDot", "lgDashDot", "lgDashDotDot", "sysDash", "sysDot", "sysDashDot", "sysDashDotDot"]; |
| 39 | |
| 40 | function themeXml(xml, theme) { |
| 41 | if (!theme || !theme.name) throw new Error("theme.name is required. Nothing was changed."); |
| 42 | // The name goes into XML attributes: drop control characters, escape & < > and the double quote. |
| 43 | const name = String(theme.name).replace(/[\x00-\x08\x0B\x0C\x0E-\x1F]/g, "").replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """); |
| 44 | const colors = theme.colors || theme; // { name, colors: {...} }, or flat { name, dk1, ... } |
| 45 | for (const k of SLOTS) { |
| 46 | if (!/^[0-9A-Fa-f]{6}$/.test(String(colors[k]))) throw new Error(`theme.colors.${k} is ${JSON.stringify(colors[k])}; it must be six hex digits with no "#" (slots: ${SLOTS.join(" ")}). Nothing was changed.`); |
| 47 | } |
| 48 | const scheme = `<a:clrScheme name="${name}">` + SLOTS.map((k) => `<a:${k}><a:srgbClr val="${String(colors[k]).toUpperCase()}"/></a:${k}>`).join("") + "</a:clrScheme>"; |
| 49 | // Function replacements, so a "$" in the name is not read as a replacement pattern. |
| 50 | // The theme, its color scheme and its font scheme each carry a name; none should still say Office. |
| 51 | const out = xml |
| 52 | .replace(/<a:clrScheme\b[\s\S]*?<\/a:clrScheme>/, () => scheme) |
| 53 | .replace(/(<a:(?:theme|fontScheme)\b[^>]*?\bname=")[^"]*"/g, (_, head) => `${head}${name}"`); |
| 54 | if (!out.includes(scheme)) throw new Error("ppt/theme/theme1.xml has no <a:clrScheme> to replace; this script expects the theme part pptxgenjs writes. Nothing was changed."); |
| 55 | return out; |
| 56 | } |
| 57 | |
| 58 | async function applyTheme(deckPath, theme, outPath = deckPath) { |
| 59 | const zip = await loadJSZip().loadAsync(fs.readFileSync(deckPath)); |
| 60 | const part = "ppt/theme/theme1.xml"; // the one theme part pptxgenjs writes; the slide master and the notes master share it |
| 61 | if (!zip.file(part)) throw new Error(`${deckPath} has no ${part}; this script is for decks pptxgenjs wrote. Nothing was changed.`); |
| 62 | zip.file(part, themeXml(await zip.file(part).async("string"), theme)); |
| 63 | |
| 64 | // A scheme color given to a hex-only option is written as <a:srgbClr val="bg2"/>, which is |
| 65 | // not a color. pptxgenjs does not warn; stop here instead. |
| 66 | for (const name of Object.keys(zip.files)) { |
| 67 | if (!name.endsWith(".xml")) continue; |
| 68 | const xml = await zip.file(name).async("string"); |
| 69 | const bad = xml.match(/<a:srgbClr val="((?![0-9A-Fa-f]{6}")[^"]*)"/); |
| 70 | if (bad) throw new Error(`${shown(name)} has an <a:srgbClr> whose val is ${shown(bad[1])}, not six hex digits. Usually a scheme color was given to an option that takes hex only (valGridLine.color, catGridLine.color, shadow.color, or chartColors / invertedColors on a one-series bar chart). Pass the six-digit hex from your theme object there and rebuild. Nothing was changed.`); |
| 71 | |
| 72 | // pptxgenjs writes a dash option through unchecked, and an array as "solid,dash". |
| 73 | const dash = [...xml.matchAll(/<a:prstDash val="([^"]*)"/g)].find((m) => !DASHES.includes(m[1].trim())); |
| 74 | if (dash) throw new Error(`${shown(name)} has an <a:prstDash> whose val is ${shown(dash[1])}, which is not a dash style, and PowerPoint would offer to repair the deck. Give line.dashType, a chart's lineDash (one word for the whole chart, not an array), catAxisLineStyle or valAxisLineStyle one of: ${DASHES.join(" ")}. Then rebuild. Nothing was changed.`); |
| 75 | |
| 76 | // pptxgenjs writes valAxisCrossesAt: 0 as <c:crossesAt val="autoZero"/>. <c:crossesAt> takes |
| 77 | // a number; the word belongs in <c:crosses>, where it means the same: cross at zero. |
| 78 | if (xml.includes('<c:crossesAt val="autoZero"/>')) zip.file(name, xml.replaceAll('<c:crossesAt val="autoZero"/>', '<c:crosses val="autoZero"/>')); |
| 79 | } |
| 80 | // A ZIP entry for a folder ("ppt/slides/") is not a part, and pptxgenjs writes one per folder. |
| 81 | // A cloud co-editing service reported issues editing decks that carry them. They are dropped |
| 82 | // here for that reason, not to save space. (zip.remove() would take the folder's files too.) |
| 83 | for (const name of Object.keys(zip.files)) if (zip.files[name].dir) delete zip.files[name]; |
| 84 | |
| 85 | fs.writeFileSync(outPath, await zip.generateAsync({ type: "nodebuffer", compression: "DEFLATE" })); |
| 86 | } |
| 87 | |
| 88 | module.exports = { applyTheme }; |
| 89 | |
| 90 | if (require.main === module) { |
| 91 | const [deck, themeFile, out] = process.argv.slice(2); |
| 92 | if (!deck || !themeFile) { |
| 93 | console.error("usage: node apply_theme.js deck.pptx theme.json [out.pptx]"); |
| 94 | process.exit(2); |
| 95 | } |
| 96 | let theme; |
| 97 | try { |
| 98 | theme = JSON.parse(fs.readFileSync(themeFile, "utf8")); |
| 99 | } catch (e) { |
| 100 | console.error(`Error: cannot read ${themeFile} as JSON (${e.message}). Nothing was changed.`); |
| 101 | process.exit(1); |
| 102 | } |
| 103 | applyTheme(deck, theme, out || deck).then( |
| 104 | () => console.log(`Theme written to ${out || deck}`), |
| 105 | (e) => { console.error(`Error: ${e.message}`); process.exit(1); } |
| 106 | ); |
| 107 | } |