forked from dbohdan/classless-css
-
Notifications
You must be signed in to change notification settings - Fork 0
/
gen-screenshot.ts
executable file
·84 lines (72 loc) · 2.15 KB
/
gen-screenshot.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
#! /usr/bin/env -S deno run --allow-env --allow-net --allow-read --allow-run --allow-write --check
// Generate the screenshot and its thumbnail for a project.
// To install the dependencies on Debian/Ubuntu:
// $ sudo apt install imagemagick optipng
import puppeteer from "https://deno.land/x/[email protected]/mod.ts";
const templateFile = "screenshot-page.html";
const temporaryFile = "temp.html";
const slugify = (str: string) =>
str
.toLowerCase()
.replace(/[^a-z0-9.]+/g, "-")
.replace(/(^-|-$)/g, "");
const saveScreenshot = async (src: string, dest: string) => {
const browser = await puppeteer.launch({
defaultViewport: { width: 1024, height: 1024, deviceScaleFactor: 1 },
});
const page = await browser.newPage();
await page.goto(src);
await page.screenshot({ fullPage: true, path: dest });
await browser.close();
};
if (Deno.args.length < 1 || Deno.args.length > 2) {
console.error(
"usage: gen-screenshot.ts project-name [css-file]\n\n" +
"The image filename will be derived from the project name.",
);
Deno.exit(1);
}
const screenshotFile = `${slugify(Deno.args[0])}.png`;
const cssFile = Deno.args[1] || "";
try {
const htmlTemplate = await Deno.readTextFile(templateFile);
const css = cssFile === "" ? "" : await Deno.readTextFile(cssFile);
const html = htmlTemplate.replace(/%CSS_HERE%/, css);
await Deno.writeTextFile(temporaryFile, html);
const tempFilePath = await Deno.realPath(temporaryFile);
await saveScreenshot(
`file://${tempFilePath}`,
`screenshot/${screenshotFile}`,
);
await (new Deno.Command(
"convert",
{
args: [
"-resize",
"25%",
"-adaptive-sharpen",
"10",
`screenshot/${screenshotFile}`,
`thumbnail/${screenshotFile}`,
],
stderr: "inherit",
stdout: "inherit",
},
)).output();
await (new Deno.Command("optipng", {
args: [
"-o",
"5",
"-strip",
"all",
`screenshot/${screenshotFile}`,
`thumbnail/${screenshotFile}`,
],
stderr: "inherit",
stdout: "inherit",
})).output();
} catch (err) {
console.error(err);
} finally {
Deno.remove(temporaryFile);
}