]> Untitled Git - lemmy-ui.git/blob - src/shared/components/common/pictrs-image.tsx
Merge branch 'main' into fix-button-click-area
[lemmy-ui.git] / src / shared / components / common / pictrs-image.tsx
1 import classNames from "classnames";
2 import { Component } from "inferno";
3
4 const iconThumbnailSize = 96;
5 const thumbnailSize = 256;
6
7 interface PictrsImageProps {
8   src: string;
9   alt?: string;
10   icon?: boolean;
11   banner?: boolean;
12   thumbnail?: boolean;
13   nsfw?: boolean;
14   iconOverlay?: boolean;
15   pushup?: boolean;
16 }
17
18 export class PictrsImage extends Component<PictrsImageProps, any> {
19   constructor(props: any, context: any) {
20     super(props, context);
21   }
22
23   render() {
24     return (
25       <picture>
26         <source srcSet={this.src("webp")} type="image/webp" />
27         <source srcSet={this.props.src} />
28         <source srcSet={this.src("jpg")} type="image/jpeg" />
29         <img
30           src={this.props.src}
31           alt={this.alt()}
32           loading="lazy"
33           className={classNames({
34             "img-fluid": !this.props.icon && !this.props.iconOverlay,
35             banner: this.props.banner,
36             "thumbnail rounded":
37               this.props.thumbnail && !this.props.icon && !this.props.banner,
38             "img-expanded slight-radius":
39               !this.props.thumbnail && !this.props.icon,
40             "img-blur": this.props.thumbnail && this.props.nsfw,
41             "rounded-circle img-cover img-icon mr-2": this.props.icon,
42             "ml-2 mb-0 rounded-circle img-cover avatar-overlay":
43               this.props.iconOverlay,
44             "avatar-pushup": this.props.pushup,
45           })}
46         />
47       </picture>
48     );
49   }
50
51   src(format: string): string {
52     // sample url:
53     // http://localhost:8535/pictrs/image/file.png?thumbnail=256&format=jpg
54
55     const split = this.props.src.split("/pictrs/image/");
56
57     // If theres not multiple, then its not a pictrs image
58     if (split.length == 1) {
59       return this.props.src;
60     }
61
62     const host = split[0];
63     const path = split[1];
64
65     const params = { format };
66
67     if (this.props.thumbnail) {
68       params["thumbnail"] = thumbnailSize;
69     } else if (this.props.icon) {
70       params["thumbnail"] = iconThumbnailSize;
71     }
72
73     const paramsStr = new URLSearchParams(params).toString();
74     const out = `${host}/pictrs/image/${path}?${paramsStr}`;
75
76     return out;
77   }
78
79   alt(): string {
80     if (this.props.icon) {
81       return "";
82     }
83     return this.props.alt || "";
84   }
85 }