]> Untitled Git - lemmy-ui.git/blob - src/shared/components/common/pictrs-image.tsx
Fixing nav-link
[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           loading="lazy"
31           className={`
32         ${!this.props.icon && !this.props.iconOverlay && "img-fluid "}
33         ${
34           this.props.thumbnail && !this.props.icon
35             ? "thumbnail rounded "
36             : "img-expanded "
37         }
38         ${this.props.thumbnail && this.props.nsfw && "img-blur "}
39         ${this.props.icon && "rounded-circle img-icon mr-2 "}
40         ${this.props.iconOverlay && "ml-2 mb-0 rounded-circle avatar-overlay "}
41         ${this.props.pushup && "avatar-pushup "}
42         `}
43         />
44       </picture>
45     );
46   }
47
48   src(format: string): string {
49     // sample url:
50     // http://localhost:8535/pictrs/image/file.png?thumbnail=256&format=jpg
51
52     let split = this.props.src.split("/pictrs/image/");
53
54     // If theres not multiple, then its not a pictrs image
55     if (split.length == 1) {
56       return this.props.src;
57     }
58
59     let host = split[0];
60     let path = split[1];
61
62     let params = { format };
63
64     if (this.props.thumbnail) {
65       params["thumbnail"] = thumbnailSize;
66     } else if (this.props.icon) {
67       params["thumbnail"] = iconThumbnailSize;
68     } else {
69       params["thumbnail"] = maxImageSize;
70     }
71
72     let paramsStr = `?${new URLSearchParams(params).toString()}`;
73     let out = `${host}/pictrs/image/${path}${paramsStr}`;
74
75     return out;
76   }
77
78   alt(): string {
79     if (this.props.icon) {
80       return "";
81     }
82     return this.props.alt || "";
83   }
84 }