]> Untitled Git - lemmy-ui.git/blob - src/shared/components/common/pictrs-image.tsx
Improvements to post listings (#536)
[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": this.props.thumbnail && !this.props.icon && !this.props.banner,
37             "img-expanded slight-radius":
38               !this.props.thumbnail && !this.props.icon,
39             "img-blur": this.props.thumbnail && this.props.nsfw,
40             "rounded-circle img-icon mr-2": this.props.icon,
41             "ml-2 mb-0 rounded-circle avatar-overlay": this.props.iconOverlay,
42             "avatar-pushup": this.props.pushup,
43           })}
44         />
45       </picture>
46     );
47   }
48
49   src(format: string): string {
50     // sample url:
51     // http://localhost:8535/pictrs/image/file.png?thumbnail=256&format=jpg
52
53     let split = this.props.src.split("/pictrs/image/");
54
55     // If theres not multiple, then its not a pictrs image
56     if (split.length == 1) {
57       return this.props.src;
58     }
59
60     let host = split[0];
61     let path = split[1];
62
63     let params = { format };
64
65     if (this.props.thumbnail) {
66       params["thumbnail"] = thumbnailSize;
67     } else if (this.props.icon) {
68       params["thumbnail"] = iconThumbnailSize;
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 }