might-cli
Version:
A no-code solution for performing frontend tests
74 lines (73 loc) • 2.55 kB
JavaScript
import jimp from 'jimp';
import { promisify } from 'util';
const pageDown = async (page) => {
await page.evaluate(() => window.scrollBy(0, window.innerHeight));
};
const merge = async (images) => {
const color = 0x00000000;
let width = 0, height = 0;
const processImg = async (img) => {
const j = await jimp.read(img);
const data = {
img: j,
width: j.getWidth(),
height: j.getHeight()
};
if (data.width > width)
width = data.width;
height = height + data.height;
return data;
};
const imagesData = await Promise.all(images.map(processImg));
const reducedImage = new jimp(width, height, color);
const x = 0;
let y = 0;
imagesData.forEach((obj) => {
reducedImage.composite(obj.img, x, y);
y = y + obj.height;
});
return reducedImage;
};
export default async (options) => {
options = options || {};
const page = options.page;
if (!options.full) {
return await page.screenshot({
path: options.path
});
}
const { pagesCount, extraPixels, viewport } = await page.evaluate(() => {
window.scrollTo(0, 0);
return {
pagesCount: Math.ceil(document.body.clientHeight / window.innerHeight),
extraPixels: document.body.clientHeight % window.innerHeight * window.devicePixelRatio,
viewport: { height: window.innerHeight * window.devicePixelRatio, width: window.innerWidth * window.devicePixelRatio }
};
});
if (pagesCount === 1) {
return await page.screenshot({
path: options.path
});
}
const images = [];
for (let i = 0; i < pagesCount; i++) {
const image = await page.screenshot();
images.push(image);
await pageDown(page);
}
const last = images.pop();
const cropped = await jimp.read(last)
.then(image => image.crop(0, viewport.height - extraPixels, viewport.width, extraPixels))
.then(image => image.getBufferAsync(jimp.MIME_PNG));
images.push(cropped);
const mergedImage = await merge(images);
if (options.path) {
mergedImage.write = mergedImage.write.bind(mergedImage);
const writeAsync = promisify(mergedImage.write);
await writeAsync(options.path);
return;
}
mergedImage.getBuffer = mergedImage.getBuffer.bind(mergedImage);
const getBufferAsync = promisify(mergedImage.getBuffer);
return await getBufferAsync(jimp.MIME_PNG);
};