Skip to content

Commit

Permalink
Merge pull request #1615 from datadesk/fallback-patch-fix
Browse files Browse the repository at this point in the history
[PATCH]: 11-5-2024 Patches embed filepaths
  • Loading branch information
jperezlatimes authored Nov 6, 2024
2 parents 46910b1 + 09a8332 commit 3df8303
Showing 1 changed file with 72 additions and 65 deletions.
137 changes: 72 additions & 65 deletions lib/index.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
// native
import EventEmitter from 'events';
import { join, resolve } from 'path';
import { readdir } from 'fs';
import path, { join, resolve } from 'path';

// packages
import chokidar from 'chokidar';
Expand Down Expand Up @@ -190,10 +191,7 @@ export class Baker extends EventEmitter {
this.nunjucks.addCustomTag('inject', injectBlock);

// create our static tag
const staticBlock = createStaticBlock(
this.input,
[this.assets, this.sass]
);
const staticBlock = createStaticBlock(this.input, [this.assets, this.sass]);

// save a reference to our static block function for use elsewhere
// TODO: refactor away in v1
Expand Down Expand Up @@ -295,7 +293,7 @@ export class Baker extends EventEmitter {
prepareCrosswalk(crossWalkRows) {
const preppedData = {
assets: {},
additionalData: []
additionalData: [],
};

return crossWalkRows.reduce((acc, crosswalkRow) => {
Expand All @@ -304,11 +302,7 @@ export class Baker extends EventEmitter {
return acc;
}

const {
assetName,
assetType,
...assetSources
} = crosswalkRow;
const { assetName, assetType, ...assetSources } = crosswalkRow;

const normalizedAssetName = assetName.toLowerCase();
const normalizedAssetType = assetType.toLowerCase();
Expand All @@ -320,7 +314,9 @@ export class Baker extends EventEmitter {
}

if (!assetName) {
throw new Error('Crosswalk: Unable to process crowsswalk tsv/csv. Missing required \'assetName\' column.')
throw new Error(
"Crosswalk: Unable to process crowsswalk tsv/csv. Missing required 'assetName' column."
);
}

if (
Expand Down Expand Up @@ -349,19 +345,18 @@ export class Baker extends EventEmitter {
preppedData.assets[normalizedAssetType] = {};
preppedData.assets[normalizedAssetType][normalizedAssetName] = {};

Object.entries(assetSources)
.forEach(([ext, path]) => {
const allowedExtensions = CROSSWALK_ALLOWED_EXTS[normalizedAssetType];
if (!allowedExtensions.includes(ext)) {
console.warn(
`Attribute: ${ext} not allowed for asset type: ${normalizedAssetType}. Skipping.`
);
return;
}

preppedData.assets[normalizedAssetType][normalizedAssetName][ext] =
this.getStaticPath(path);
});
Object.entries(assetSources).forEach(([ext, path]) => {
const allowedExtensions = CROSSWALK_ALLOWED_EXTS[normalizedAssetType];
if (!allowedExtensions.includes(ext)) {
console.warn(
`Attribute: ${ext} not allowed for asset type: ${normalizedAssetType}. Skipping.`
);
return;
}

preppedData.assets[normalizedAssetType][normalizedAssetName][ext] =
this.getStaticPath(path);
});

return acc;
}, preppedData);
Expand All @@ -372,15 +367,24 @@ export class Baker extends EventEmitter {
* @param {string} baseUrl The local server's base URL
* @returns {Promise<void>}
*/

async buildEmbedFallbacks(baseUrl) {
const distDir = this.output.split('/').slice(0, -1).join('/');
const embedFilePattern = path.join(distDir, '_dist', 'embeds');

/**
* An array of file paths representing embed files.
* @type {string[]}
*/
const embedFiles = Object.values(this.nunjucks.manifest).filter((path) =>
path.includes('embeds')
);
const embedFiles = await new Promise((resolve, reject) => {
readdir(embedFilePattern, (err, files) => {
//handling error
if (err) {
reject('Unable to scan directory: ' + err);
}

resolve(files);
});
});

if (!embedFiles.length) return;

Expand All @@ -389,47 +393,50 @@ export class Baker extends EventEmitter {
args: ['--no-sandbox', '--disable-setuid-sandbox'],
});

for (const embedName of embedFiles) {
try {
const embedPath = `embeds/${embedName}/index.html`;
const screenshotLocalUrl = `${baseUrl}/${embedPath}`;
console.log(`Taking screenshot of: ${screenshotLocalUrl}`);

const page = await browser.newPage();
await page.goto(screenshotLocalUrl, {
waitUntil: 'networkidle0',
});

for (const embedFilePath of embedFiles) {
const screenshotLocalUrl = `${baseUrl}/${embedFilePath}`;
console.log(`Taking screenshot of: ${screenshotLocalUrl}`);

const page = await browser.newPage();
await page.goto(screenshotLocalUrl, {
waitUntil: 'networkidle0',
});

// set the viewport to the content height
const contentHeight = await page.evaluate(() => {
return Math.max(
document.body.scrollHeight,
document.documentElement.scrollHeight,
document.body.offsetHeight,
document.documentElement.offsetHeight,
document.body.clientHeight,
document.documentElement.clientHeight
);
});
await page.setViewport({
width: FIXED_FALLBACK_SCREENSHOT_WIDTH,
height: contentHeight,
deviceScaleFactor: 2,
});
// set the viewport to the content height
const contentHeight = await page.evaluate(() => {
return Math.max(
document.body.scrollHeight,
document.documentElement.scrollHeight,
document.body.offsetHeight,
document.documentElement.offsetHeight,
document.body.clientHeight,
document.documentElement.clientHeight
);
});
await page.setViewport({
width: FIXED_FALLBACK_SCREENSHOT_WIDTH,
height: contentHeight,
deviceScaleFactor: 2,
});

await page.waitForNetworkIdle();
await page.waitForNetworkIdle();

// store the fallback image in the _dist directory
const screenshotEmbedDir = join(this.output, embedFilePath)
.split('/')
.slice(0, -1)
.join('/')
.replace('_screenshot', '_dist');
const screenshotStoragePath = join(screenshotEmbedDir, 'fallback.png');
console.log(`Storing the fallback image at: ${screenshotStoragePath}.`);
// store the fallback image in the _dist directory
const screenshotEmbedDir = join(this.output, embedPath)
.split('/')
.slice(0, -1)
.join('/')
.replace('_screenshot', '_dist');
const screenshotStoragePath = join(screenshotEmbedDir, 'fallback.png');
console.log(`Storing the fallback image at: ${screenshotStoragePath}.`);

await page.screenshot({ path: screenshotStoragePath, fullPage: true });
await page.close();
await page.screenshot({ path: screenshotStoragePath, fullPage: true });
await page.close();
} catch (err) {
console.error(`Failed to process ${embedName}: ${err.message}`);
}
}

await browser.close();
Expand Down

0 comments on commit 3df8303

Please sign in to comment.