-
Notifications
You must be signed in to change notification settings - Fork 375
Expand file tree
/
Copy pathbuildGalleryOfSingleImage.ts
More file actions
98 lines (81 loc) · 2.33 KB
/
buildGalleryOfSingleImage.ts
File metadata and controls
98 lines (81 loc) · 2.33 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
import type { Attachment } from 'stream-chat';
import { buildThumbnail } from './buildThumbnail';
import type { GallerySizeAndThumbnailGrid, GallerySizeConfig } from './types';
import { ChatConfigContextValue } from '../../../../contexts/chatConfigContext/ChatConfigContext';
import { getAspectRatio } from '../getAspectRatio';
/**
* Bound a number to a range.
* @param number The number to bound.
* @param min The minimum value.
* @param max The maximum value.
*
* @returns The bounded number.
*/
function clamp(number: number, min: number, max: number) {
return Math.min(Math.max(number, min), max);
}
function getContainerSize({
image,
sizeConfig,
}: {
image: Attachment;
sizeConfig: GallerySizeConfig;
}) {
const { original_height: height, original_width: width } = image;
const { gridHeight, gridWidth, maxHeight, maxWidth, minHeight, minWidth } = sizeConfig;
if (!height || !width) {
return { height: gridHeight, width: gridWidth };
}
const aspectRatio = getAspectRatio(image);
if (aspectRatio <= 1) {
const containerHeight = clamp(height, minHeight, maxHeight);
const containerWidth = clamp(containerHeight * aspectRatio, minWidth, maxWidth);
if (containerWidth === maxWidth) {
return {
height: clamp(containerWidth / aspectRatio, minHeight, maxHeight),
width: containerWidth,
};
}
return {
height: containerHeight,
width: containerWidth,
};
}
const containerWidth = clamp(width, minWidth, maxWidth);
const containerHeight = clamp(containerWidth / aspectRatio, minHeight, maxHeight);
if (containerHeight === maxHeight) {
return {
height: containerHeight,
width: clamp(containerHeight * aspectRatio, minHeight, maxHeight),
};
}
return {
height: containerHeight,
width: containerWidth,
};
}
export function buildGalleryOfSingleImage({
image,
resizableCDNHosts,
sizeConfig,
}: Pick<ChatConfigContextValue, 'resizableCDNHosts'> & {
image: Attachment;
sizeConfig: GallerySizeConfig;
}): GallerySizeAndThumbnailGrid {
const container = getContainerSize({
image,
sizeConfig,
});
const thumbnail = buildThumbnail({
image,
resizableCDNHosts,
flex: 1,
resizeMode: 'cover',
...container,
});
const column = [thumbnail];
return {
...container,
thumbnailGrid: [column],
};
}