Skip to content

Commit 479d78b

Browse files
committed
add a guide on social cards, group the guides, drop Deno Deploy and Vercel Edge
1 parent cc41e0f commit 479d78b

8 files changed

Lines changed: 134 additions & 5 deletions

‎README.md‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -21,8 +21,8 @@
2121
---
2222

2323
**ImageScript** decodes, edits and encodes images in pure TypeScript: no WebAssembly, no native binaries, and no
24-
runtime dependencies. It runs in Node.js 22.13+, Deno, Bun, browsers and edge runtimes (Cloudflare Workers, Vercel's
25-
Edge Runtime, Deno Deploy), works with `import` and, on supported Node.js versions, `require()`, and ships with type
24+
runtime dependencies. It runs in Node.js 22.13+, Deno, Bun, browsers and edge runtimes (such as Cloudflare
25+
Workers), works with `import` and, on supported Node.js versions, `require()`, and ships with type
2626
definitions (TypeScript 5.7 or newer; CommonJS projects need `module: nodenext` and 5.8 or newer to `import` it (`module: node16` can't). With older versions and `skipLibCheck`, the encoders' return types become `any`). Large AVIF and JPEG XL operations, and lossless WebP encoding, can use multiple CPU cores when the runtime
2727
supports it.
2828

‎guides/Choosing ImageScript.md‎

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,7 @@
1+
---
2+
group: Guides
3+
---
4+
15
# Choosing ImageScript
26

37
ImageScript decodes, edits and encodes images in TypeScript, with no WebAssembly, no native binaries and no
@@ -6,7 +10,7 @@ when you depend on it.
610

711
## When it fits
812

9-
- **Where native libraries can't run:** Cloudflare Workers, Vercel's Edge Runtime, Deno Deploy and browsers. There is
13+
- **Where native libraries can't run:** Cloudflare Workers and other edge runtimes, and browsers. There is
1014
nothing to compile, download at install time or match to the platform.
1115
- **Where installs should stay small and simple:** one package of 2.6 MB on disk, no install scripts, the same files
1216
on every operating system and CPU.
@@ -31,8 +35,7 @@ Every change runs the full test suite on:
3135

3236
- Node.js 22.13, 24 and 26 on Linux, and Node.js 26 on macOS and Windows
3337
- Deno and Bun
34-
- Cloudflare's workerd (through Miniflare, with and without Node.js compatibility) and Vercel's Edge Runtime, bundled
35-
the way they are deployed
38+
- Cloudflare's workerd (through Miniflare, with and without Node.js compatibility), bundled the way it is deployed
3639
- Chromium, bundled by Vite, with and without worker threads
3740

3841
The decoders are ports of the reference implementations (libjpeg, libwebp, dav1d, libjxl and jxl-oxide; HarfBuzz for

‎guides/Coming from Jimp.md‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,7 @@
1+
---
2+
group: Guides
3+
---
4+
15
# Coming from Jimp
26

37
ImageScript and Jimp solve the same problem the same way: images are decoded into an RGBA bitmap in JavaScript, edited

‎guides/Migrating to 4.0.md‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,7 @@
1+
---
2+
group: Guides
3+
---
4+
15
# Migrating to 4.0
26

37
ImageScript 4.0 removes everything 3.x deprecated, reshapes parts of the API, and changes eighteen behaviors. Most of the
Lines changed: 115 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,115 @@
1+
---
2+
group: Examples
3+
---
4+
5+
# Social cards for static sites
6+
7+
A link preview (the Open Graph image) is the picture a chat app or social network shows when someone shares a page.
8+
Generating one per page usually means a headless browser or a hosted service. ImageScript renders text, gradients and
9+
photos in plain TypeScript, so a card is a short build script: no browser, no native module, the same pixels on every
10+
machine, and nothing to install in CI besides `npm install`.
11+
12+
This is a card the script made:
13+
14+
![A link preview: the title, a summary and the site with the date, on a dark purple gradient](./social-card-example.png)
15+
16+
## The script
17+
18+
This script writes one 1200×630 card for every Markdown post in `content/posts`, using the `title`, `description` and
19+
`date` from the front matter. Save it as `scripts/social-cards.mjs`, put a font in `fonts/` (any TrueType, OpenType or
20+
WOFF file; a variable font such as Inter gives the bold weight from one file) and run `node scripts/social-cards.mjs`.
21+
22+
```js
23+
// One 1200×630 link preview per Markdown post: content/posts/<slug>.md -> public/og/<slug>.png
24+
import { mkdir, readdir, readFile, stat, writeFile } from 'node:fs/promises';
25+
import { Image } from 'imagescript';
26+
27+
const postsDir = 'content/posts';
28+
const outDir = 'public/og';
29+
const site = 'example.com';
30+
31+
// any TrueType, OpenType or WOFF font; a variable font gives the bold weight from the same file
32+
const font = await readFile('fonts/Inter.ttf');
33+
const width = 1200;
34+
const height = 630;
35+
const pad = 72;
36+
37+
// the background is the same for every card: make it once
38+
const stops = [0x141821ff, 0x2a2350ff];
39+
const background = Image.linearGradient(width, height, { stops, angle: 135 });
40+
41+
// front matter: the `key: value` lines between the two `---` lines at the top
42+
function frontMatter(source) {
43+
const block = /^---\r?\n([\s\S]*?)\r?\n---/.exec(source)?.[1] ?? '';
44+
const pairs = block.split(/\r?\n/).map((line) => /^(\w+):\s*(.*)$/.exec(line)).filter(Boolean);
45+
return Object.fromEntries(pairs.map(([, key, value]) => [key, value.replace(/^(["'])(.*)\1$/, '$2')]));
46+
}
47+
48+
async function card({ title, description, date }) {
49+
const image = background.clone();
50+
const footer = await Image.renderText(`${site}${date ? ` · ${date}` : ''}`, {
51+
font, size: 28, color: 0xf28db2ff, variations: { weight: 600 },
52+
});
53+
const summary = description && await Image.renderText(description, {
54+
font, size: 32, color: 0xb8bfd0ff, width: width - pad * 2, height: 100,
55+
});
56+
// the title in the largest size that leaves room for the summary and the footer
57+
const room = height - pad * 2 - footer.height - (summary ? summary.height + 28 : 0) - 28;
58+
let heading;
59+
for (let size = 72; size >= 40; size -= 4) {
60+
heading = await Image.renderText(title, {
61+
font, size, color: 0xffffffff, variations: { weight: 800 }, width: width - pad * 2,
62+
});
63+
if (heading.height <= room) break;
64+
}
65+
image.composite(heading, { x: pad, y: pad });
66+
if (summary) image.composite(summary, { x: pad, y: pad + heading.height + 28 });
67+
image.composite(footer, { x: pad, y: height - pad - footer.height });
68+
// compression level 1 is several times faster than the default, and only a little larger for flat graphics
69+
return image.encodePNG({ compression: 1 });
70+
}
71+
72+
await mkdir(outDir, { recursive: true });
73+
for (const file of (await readdir(postsDir)).filter((name) => name.endsWith('.md'))) {
74+
const slug = file.slice(0, -3);
75+
const target = `${outDir}/${slug}.png`;
76+
// keep the cards that are newer than their post
77+
const [post, existing] = await Promise.all([stat(`${postsDir}/${file}`), stat(target).catch(() => null)]);
78+
if (existing && existing.mtimeMs > post.mtimeMs) continue;
79+
const data = frontMatter(await readFile(`${postsDir}/${file}`, 'utf8'));
80+
const { title = slug, description, date } = data;
81+
await writeFile(target, await card({ title, description, date }));
82+
console.log('wrote', target);
83+
}
84+
```
85+
86+
A card takes about 30 milliseconds (Node.js 26 on a 2018 laptop CPU), so a site with hundreds of posts is done in
87+
seconds. Cards that are newer than their post are skipped, and the title shrinks until it fits the card.
88+
89+
## Using it
90+
91+
Run the script before your site's build, for example `"build": "node scripts/social-cards.mjs && <your build>"`, and
92+
point every page at its card:
93+
94+
```html
95+
<meta property="og:image" content="https://example.com/og/hello-world.png">
96+
<meta property="og:image:width" content="1200">
97+
<meta property="og:image:height" content="630">
98+
<meta name="twitter:card" content="summary_large_image">
99+
```
100+
101+
## Changing the design
102+
103+
- **A cover photo and an avatar:** decode them with {@link Image.decode}, size them with {@link Image.resize | resize}
104+
(`fit: 'cover'`), round them with {@link Image.roundCorners | roundCorners} or {@link Image.cropCircle | cropCircle}
105+
and place them with {@link Image.composite | composite}. The [Playground](https://try.imagescript.dev/) has this as the
106+
example "Open Graph Card", with a shadow and a glow behind the cover.
107+
- **Other scripts and emoji:** `font` takes a list; every character comes from the first font that has it, for example
108+
`font: [inter, notoArabic, notoEmoji]`. A character that no font has is drawn as a box.
109+
- **A logo:** render an SVG once with {@link Image.renderSVG} and composite it onto every card.
110+
111+
## At request time
112+
113+
The same `card()` function works in a request handler on any runtime that runs ImageScript. Mind the CPU time your
114+
platform allows per request: a card like this one needs about 30 milliseconds, which is more than the 10 milliseconds of
115+
Cloudflare Workers' free plan. For a static site, generating the cards at build time has no such limit.

‎guides/social-card-example.png‎

89.2 KB
Loading

‎src/index.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
* @packageDocumentation
33
* @document ../guides/Choosing ImageScript.md
44
* @document ../guides/Coming from Jimp.md
5+
* @document ../guides/Social cards for static sites.md
56
* @document ../guides/Migrating to 4.0.md
67
*/
78
// (the guide is attached to the entry module: as a project document it turned the docs into a module "index", every

‎typedoc.json‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,8 @@
1919
"includeGroups": true
2020
},
2121
"groupOrder": [
22+
"Guides",
23+
"Examples",
2224
"Classes",
2325
"Functions",
2426
"Interfaces",

0 commit comments

Comments
 (0)