-
Notifications
You must be signed in to change notification settings - Fork 34
/
imgix.tsx
81 lines (67 loc) · 2.15 KB
/
imgix.tsx
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
import { isEmpty } from 'lodash';
import { kitsuConfig } from 'kitsu/config/env';
import { coverImageDimensions } from 'kitsu/constants/app';
import { isKitsuUrl, parseURL } from 'kitsu/utils/url';
export const defaultImgixOptions = {
fit: 'crop',
crop: 'faces,edges',
auto: 'format',
};
/**
* Get the imgix image url from the given url.
*
* This will convert the url from kitsu to imgix and apply all the necessary filters.
* If it can't convert the url then the original url will be returned.
*
* @param {string} url The image url.
* @param {object} imageOptions Image options to pass to imgix.
*/
export function getImgixImage(url, imageOptions = {}) {
const options = {
...defaultImgixOptions,
...imageOptions,
};
if (isEmpty(url)) return null;
// Don't continue if it's not a kitsu image
if (!isKitsuUrl(url)) return url;
// Parse it
const parsed = parseURL(url);
if (!parsed) return url;
const { pathname } = parsed;
// Build the search params
const mappings = Object.keys(options)
.filter((k) => options[k])
.map((key) => `${key}=${options[key]}`);
const searchParams = mappings.join('&');
// Make the new url
return `https://${kitsuConfig.imgixBaseUrl}${pathname}?${searchParams}`;
}
export const defaultImgixCoverOptions = {
...defaultImgixOptions,
w: coverImageDimensions.width,
'max-h': coverImageDimensions.height,
};
/**
* Get the imgix cover image url from the given coverImages.
*
* This will convert the cover url from kitsu to imgix and apply all the necessary filters.
* If it can't convert the url then the original cover image will be returned.
*
* @param {object} coverImage An object containing coverImage urls.
* @param {object} imageOptions Image options to pass to imgix.
*/
export function getImgixCoverImage(coverImage, imageOptions = {}) {
const options = {
...defaultImgixCoverOptions,
...imageOptions,
};
if (isEmpty(coverImage) || typeof coverImage !== 'object') return null;
// Get the cover url
const coverURL =
coverImage.original ||
coverImage.large ||
coverImage.medium ||
coverImage.small ||
null;
return getImgixImage(coverURL, options);
}