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 SITE_CONFIG_DIR = "_configuration"; 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"); const CONTACT_INFO_PATH = path.join(SITE_CONFIG_DIR, "contact_info.json"); const GALLERIES_PATH = path.join(SITE_CONFIG_DIR, "galleries.json"); 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 galleriesJson = fs.readFileSync(GALLERIES_PATH, "utf-8"); const galleriesView = JSON.parse(galleriesJson) const galleryViews = galleriesView["galleries"] .map((gallery) => { // If display_title is "-", do not render a title. Netlify CMS doesn't support optionals well. const display_title = gallery["display_title"].trim() !== "-" ? gallery["display_title"] : undefined; const images = gallery["images"]; const columnCount = gallery["column_count"]; while (images.length < columnCount) { images.push(null); } const rows = sliceIntoChunks(images, columnCount); const columns = transpose(rows); return { ...gallery, columns, display_title, }; }); const contactInfoJson = fs.readFileSync(CONTACT_INFO_PATH, "utf-8") const contactInfoView = JSON.parse(contactInfoJson); const view = { galleries: galleryViews, contact_info_title: contactInfoView["title"], contact_info_body: contactInfoView["body"], }; const renderedHtml = M.render(htmlTemplate, view); fs.writeFileSync(HTML_OUT_PATH, renderedHtml); console.log("Done.");