/
image.ts
191 lines (162 loc) · 5.8 KB
/
image.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
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
import defu from 'defu'
import type { ImageOptions, ImageSizesOptions, CreateImageOptions, ResolvedImage, MapToStatic, ImageCTX, $Img } from '../types/image'
import { imageMeta } from './utils/meta'
import { parseSize } from './utils'
import { useStaticImageMap } from './utils/static-map'
export function createImage (globalOptions: CreateImageOptions, nuxtContext: any) {
const staticImageManifest: Record<string, string> = (process.client && process.static) ? useStaticImageMap(nuxtContext) : {}
const ctx: ImageCTX = {
options: globalOptions,
nuxtContext
}
const getImage: $Img['getImage'] = function (input: string, options = {}) {
const image = resolveImage(ctx, input, options)
if (image.isStatic) {
handleStaticImage(image, input)
}
return image
}
const $img = function $img (input, modifiers = {}, options = {}) {
return getImage(input, {
...options,
modifiers: defu(modifiers, options.modifiers || {})
}).url
} as $Img
function handleStaticImage (image: ResolvedImage, input: string) {
if (process.static) {
if (process.client && 'fetchPayload' in window.$nuxt) {
const mappedURL = staticImageManifest[image.url]
image.url = mappedURL || input
return image
}
if (process.server) {
const { ssrContext } = ctx.nuxtContext
if (ssrContext) {
const ssrState = ssrContext.nuxt || {}
const staticImages = ssrState._img = ssrState._img || {}
const mapToStatic: MapToStatic = ssrContext.image?.mapToStatic
if (typeof mapToStatic === 'function') {
const mappedURL = mapToStatic(image)
if (mappedURL) {
staticImages[image.url] = mappedURL
image.url = mappedURL
}
}
}
}
} else if (process.env.NODE_ENV === 'production') {
image.url = input
}
}
for (const presetName in globalOptions.presets) {
$img[presetName] = ((source, modifiers, options) =>
$img(source, modifiers, { ...globalOptions.presets[presetName], ...options })) as $Img[string]
}
$img.options = globalOptions
$img.getImage = getImage
$img.getMeta = ((input: string, options?: ImageOptions) => getMeta(ctx, input, options)) as $Img['getMeta']
$img.getSizes = ((input: string, options: ImageSizesOptions) => getSizes(ctx, input, options)) as $Img['getSizes']
ctx.$img = $img as $Img
return $img
}
async function getMeta (ctx: ImageCTX, input: string, options?: ImageOptions) {
const image = resolveImage(ctx, input, { ...options })
if (typeof image.getMeta === 'function') {
return await image.getMeta()
} else {
return await imageMeta(ctx, image.url)
}
}
function resolveImage (ctx: ImageCTX, input: string, options: ImageOptions): ResolvedImage {
if (typeof input !== 'string') {
throw new TypeError(`input must be a string (received ${typeof input}: ${JSON.stringify(input)})`)
}
if (input.startsWith('data:')) {
return {
url: input
}
}
const { provider, defaults } = getProvider(ctx, options.provider || ctx.options.provider)
const preset = getPreset(ctx, options.preset)
const _options: ImageOptions = defu(options, preset, defaults)
_options.modifiers = { ..._options.modifiers }
const expectedFormat = _options.modifiers.format
if (_options.modifiers?.width) {
_options.modifiers.width = parseSize(_options.modifiers.width)
}
if (_options.modifiers?.height) {
_options.modifiers.height = parseSize(_options.modifiers.height)
}
const image = provider.getImage(input, _options, ctx)
image.format = image.format || expectedFormat || ''
return image
}
function getProvider (ctx: ImageCTX, name: string): ImageCTX['options']['providers'][0] {
const provider = ctx.options.providers[name]
if (!provider) {
throw new Error('Unknown provider: ' + name)
}
return provider
}
function getPreset (ctx: ImageCTX, name?: string): ImageOptions {
if (!name) {
return {}
}
if (!ctx.options.presets[name]) {
throw new Error('Unknown preset: ' + name)
}
return ctx.options.presets[name]
}
function getSizes (ctx: ImageCTX, input: string, opts: ImageSizesOptions) {
const width = parseSize(opts.modifiers?.width)
const height = parseSize(opts.modifiers?.height)
const hwRatio = (width && height) ? height / width : 0
const variants = []
const sizes: Record<string, string> = {}
// string => object
if (typeof opts.sizes === 'string') {
for (const entry of opts.sizes.split(/[\s,]+/).filter(e => e)) {
const s = entry.split(':')
if (s.length !== 2) { continue }
sizes[s[0].trim()] = s[1].trim()
}
} else {
Object.assign(sizes, opts.sizes)
}
for (const key in sizes) {
const screenMaxWidth = (ctx.options.screens && ctx.options.screens[key]) || parseInt(key)
let size = String(sizes[key])
const isFluid = size.endsWith('vw')
if (!isFluid && /^\d+$/.test(size)) {
size = size + 'px'
}
if (!isFluid && !size.endsWith('px')) {
continue
}
let _cWidth = parseInt(size)
if (!screenMaxWidth || !_cWidth) {
continue
}
if (isFluid) {
_cWidth = Math.round((_cWidth / 100) * screenMaxWidth)
}
const _cHeight = hwRatio ? Math.round(_cWidth * hwRatio) : height
variants.push({
width: _cWidth,
size,
screenMaxWidth,
media: `(max-width: ${screenMaxWidth}px)`,
src: ctx.$img!(input, { ...opts.modifiers, width: _cWidth, height: _cHeight }, opts)
})
}
variants.sort((v1, v2) => v1.screenMaxWidth - v2.screenMaxWidth)
const defaultVar = variants[variants.length - 1]
if (defaultVar) {
defaultVar.media = ''
}
return {
sizes: variants.map(v => `${v.media ? v.media + ' ' : ''}${v.size}`).join(', '),
srcset: variants.map(v => `${v.src} ${v.width}w`).join(', '),
src: defaultVar?.src
}
}