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