-
Notifications
You must be signed in to change notification settings - Fork 5.4k
Expand file tree
/
Copy pathrehypeImg.ts
More file actions
222 lines (182 loc) · 6.63 KB
/
Copy pathrehypeImg.ts
File metadata and controls
222 lines (182 loc) · 6.63 KB
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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
import fs from "fs"
import path from "path"
import sizeOf from "image-size"
import { getPlaiceholder } from "plaiceholder"
import { visit } from "unist-util-visit"
import { getHashFromBuffer } from "@/lib/utils/crypto"
import {
checkIfImageIsTranslated,
getTranslatedImgPath,
} from "@/lib/utils/i18n"
import { DEFAULT_LOCALE, PLACEHOLDER_IMAGE_DIR } from "@/lib/constants"
import { toPosixPath } from "../utils/relativePath"
interface Options {
dir: string
srcPath: string
locale: string
}
type ImageNode = {
type: "element"
tagName: "img"
properties: {
src: string
height?: number
width?: number
aspectRatio?: number
blurDataURL?: string
placeholder?: "blur" | "empty"
}
}
type Path = string
type Placeholder = {
hash: string
base64: string
}
type PlaceholderData = Record<Path, Placeholder>
/**
* Handles:
* "//"
* "http://"
* "https://"
* "ftp://"
*/
const absolutePathRegex = /^(?:[a-z]+:)?\/\//
// Videos are sized by the renderer (see `MarkdownVideo`); recognized here only
// to skip image-only steps (dimension probing, blur placeholders)
const VIDEO_EXTENSIONS = [".mp4", ".webm", ".mov"]
const getImageSize = (src: string, dir: string) => {
if (absolutePathRegex.exec(src)) {
return
}
// Treat `/` as a relative path, according to the server
const shouldJoin = !path.isAbsolute(src) || src.startsWith("/")
if (dir && shouldJoin) {
src = path.join(dir, src)
}
return sizeOf(src)
}
/**
* Sets image placeholders for the given array of images.
*
* @param images - The array of images to set placeholders for.
* @param srcPath - The source page path for the images.
* @returns A promise that resolves to void.
*/
const setImagePlaceholders = async (
images: ImageNode[],
srcPath: string
): Promise<void> => {
// Generate kebab-case filename from srcPath, ie: /content/nft => content-nft-data.json
const FILENAME = toPosixPath(path.join(srcPath, "data.json"))
.replaceAll("/", "-")
.slice(1)
// The on-disk placeholder cache is a build-time optimization. When MDX is
// compiled on-demand in the serverless runtime the filesystem is read-only
// (and this dir isn't bundled), so treat cache I/O as best-effort and fall
// back to generating placeholders in memory.
let canWriteCache = true
// Make directory for current page if none exists
try {
if (!fs.existsSync(PLACEHOLDER_IMAGE_DIR))
fs.mkdirSync(PLACEHOLDER_IMAGE_DIR, { recursive: true })
} catch {
canWriteCache = false
}
const DATA_PATH = path.join(PLACEHOLDER_IMAGE_DIR, FILENAME)
const existsCache = fs.existsSync(DATA_PATH)
const placeholdersCached: PlaceholderData = existsCache
? JSON.parse(fs.readFileSync(DATA_PATH, "utf8"))
: {}
let isChanged = false
// Generate placeholder for internal images
for (const image of images) {
const { src } = image.properties
// Skip externally hosted images
if (src.startsWith("http")) continue
// Load image data from file system as buffer
const buffer: Buffer = fs.readFileSync(path.join("public", src))
// Get hash fingerprint of image data (no security implications; fast algorithm prioritized)
const hash = await getHashFromBuffer(buffer, {
algorithm: "SHA-1",
length: 8,
})
// Look for cached placeholder data with matching hash
const cachedPlaceholder: Placeholder | null =
placeholdersCached[src]?.hash === hash ? placeholdersCached[src] : null
// Get base64 from cached placeholder if available, else generate new placeholder
const { base64 } =
cachedPlaceholder || (await getPlaiceholder(buffer, { size: 16 }))
// Assign base64 placeholder data to image node `blurDataURL` property
image.properties.blurDataURL = base64
image.properties.placeholder = "blur"
// If cached value was not available, add newly generated placeholder data
if (!cachedPlaceholder) {
placeholdersCached[src] = { hash, base64 }
isChanged = true
}
}
// If cache is still empty, delete JSON file and return
if (Object.keys(placeholdersCached).length === 0) {
if (canWriteCache) fs.rmSync(DATA_PATH, { recursive: true, force: true })
return
}
// If cached value has not changed, return without writing to file system
if (!isChanged) return
// Write results to cache file (skipped when the FS is read-only at runtime)
if (canWriteCache)
fs.writeFileSync(DATA_PATH, JSON.stringify(placeholdersCached, null, 2))
}
/**
* NOTE: source code copied from the `rehype-img-size` plugin and adapted to our
* needs. https://github.com/ksoichiro/rehype-img-size
*
* Set local image size, aspect ratio, and full src path properties to img tags.
*
* @param options.dir Directory to resolve image file path
* @param options.srcDir Directory where the image src attr is going to point
*/
const rehypeImg = (options: Options) => {
const opts = options || {}
const dir = opts.dir
const srcPath = opts.srcPath
const locale = opts.locale
return async (tree) => {
// Instantiate an empty array for image nodes
const images: ImageNode[] = []
visit(tree, "element", (node) => {
if (node.tagName === "img" && node.properties) {
const src = node.properties.src as string
// Strip any `#WxH` dimensions fragment before deriving the extension
const ext = path.extname(src.split("#")[0]).toLowerCase()
const isVideo = VIDEO_EXTENSIONS.includes(ext)
// Videos still flow through (for src rewriting); only images are probed
const dimensions = isVideo ? undefined : getImageSize(src, dir)
// Skip non-video files that have no detectable dimensions
if (!dimensions && !isVideo) {
return
}
// Replace slashes from windows paths with forward slashes
const originalPath = path.join(srcPath, src).replace(/\\/g, "/")
const translatedImgPath = getTranslatedImgPath(originalPath, locale)
const imageIsTranslated = checkIfImageIsTranslated(translatedImgPath)
// If translated image exists and current locale is not 'en', use it instead of original
node.properties.src =
imageIsTranslated && locale !== DEFAULT_LOCALE
? translatedImgPath
: originalPath
if (dimensions) {
node.properties.width = dimensions.width
node.properties.height = dimensions.height
node.properties.aspectRatio =
(dimensions.width || 1) / (dimensions.height || 1)
}
// Only generate blur placeholders for images, not videos
if (!isVideo) {
images.push(node)
}
}
})
await setImagePlaceholders(images, srcPath)
}
}
export default rehypeImg