From 8d58567f810bd0fb86a856fadd31211602f3d76c Mon Sep 17 00:00:00 2001 From: Jan Tuomi Date: Mon, 11 Jul 2022 22:55:11 +0300 Subject: Add mustache templating --- build.js | 45 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 45 insertions(+) create mode 100644 build.js (limited to 'build.js') diff --git a/build.js b/build.js new file mode 100644 index 0000000..c7b8f39 --- /dev/null +++ b/build.js @@ -0,0 +1,45 @@ +const fs = require("fs"); +const path = require('path'); +const M = require("mustache"); + +// https://stackabuse.com/how-to-split-an-array-into-even-chunks-in-javascript/ +function sliceIntoChunks(arr, chunkSize) { + const res = []; + for (let i = 0; i < arr.length; i += chunkSize) { + const chunk = arr.slice(i, i + chunkSize); + res.push(chunk); + } + return res; +} + +// https://stackoverflow.com/questions/17428587/transposing-a-2d-array-in-javascript +function transpose(matrix) { + return matrix[0].map((col, i) => matrix.map(row => row[i])); +} + +const GALLERY_DIR = "_gallery"; +const SRC_DIR = "src"; +const DIST_DIR = "dist"; +const HTML_TEMP_PATH = path.join(SRC_DIR, "index.html.mustache"); +const HTML_OUT_PATH = path.join(DIST_DIR, "index.html"); + +fs.rmSync(DIST_DIR, { recursive: true, force: true }); +fs.cpSync(SRC_DIR, DIST_DIR, { recursive: true }); + +const htmlTemplate = fs.readFileSync(HTML_TEMP_PATH, "utf-8"); + +const galleryJsonList = fs.readdirSync(GALLERY_DIR); +const galleryViews = galleryJsonList + .map((fileName) => fs.readFileSync(path.join(GALLERY_DIR, fileName), "utf-8")) + .map(JSON.parse) + .map((gallery) => { + const rows = sliceIntoChunks(gallery["images"], gallery["column_count"]); + const columns = transpose(rows); + return { + ...gallery, + columns, + }; + }); + +const renderedHtml = M.render(htmlTemplate, { galleries: galleryViews} ); +fs.writeFileSync(HTML_OUT_PATH, renderedHtml); -- cgit v1.3