-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathShareBox.tsx
99 lines (81 loc) · 2.75 KB
/
ShareBox.tsx
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
99
import html2canvas from 'html2canvas';
import { observable } from 'mobx';
import { observer } from 'mobx-react';
import { Component, createRef, HTMLAttributes, MouseEvent } from 'react';
import { Image } from 'react-bootstrap';
import { blobOf } from 'web-utility';
import { Loading } from './Loading';
export async function elementToImage(
element: HTMLElement,
type?: string,
quality?: number
) {
const canvas = await html2canvas(element, { useCORS: true });
return new Promise<string>((resolve, reject) =>
canvas.toBlob(
blob => (blob ? resolve(URL.createObjectURL(blob)) : reject()),
type,
quality
)
);
}
export type ShareBoxProps = HTMLAttributes<HTMLDivElement> & ShareData;
@observer
export class ShareBox extends Component<ShareBoxProps> {
static displayName = 'ShareBox';
root = createRef<HTMLDivElement>();
@observable
accessor loading = false;
@observable
accessor imageURI = '';
componentDidMount() {
globalThis.addEventListener?.('resize', this.generateImage);
}
componentWillUnmount() {
globalThis.removeEventListener?.('resize', this.generateImage);
}
generateImage = async () => {
if (this.imageURI) {
URL.revokeObjectURL(this.imageURI);
this.imageURI = '';
}
this.loading = true;
this.imageURI = await elementToImage(this.root.current!);
this.loading = false;
};
share = async (event: MouseEvent<HTMLImageElement>) => {
event.stopPropagation();
const image = await blobOf(this.imageURI);
const file = new File([image], `${this.props.title}.png`, {
type: image.type
});
await navigator.share?.({ files: [file], ...this.props });
};
render() {
const { className = '', children, ...props } = this.props,
{ loading, imageURI } = this;
return (
<>
{loading && <Loading />}
<div
{...props}
ref={this.root}
className={`position-relative ${className}`}
onMouseEnter={imageURI ? undefined : this.generateImage}
onTouchStart={imageURI ? undefined : this.generateImage}
>
{children}
{imageURI && (
<Image
className="position-absolute start-0 top-0 w-100 h-100"
src={imageURI}
alt="Share Image"
fluid
onClick={this.share}
/>
)}
</div>
</>
);
}
}