forked from microsoft/BotFramework-WebChat
-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathImageAttachment.tsx
More file actions
59 lines (50 loc) · 1.91 KB
/
ImageAttachment.tsx
File metadata and controls
59 lines (50 loc) · 1.91 KB
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
import { validateProps } from '@msinternal/botframework-webchat-react-valibot';
import React, { memo } from 'react';
import { custom, object, optional, pipe, readonly, safeParse, string, union, type InferInput } from 'valibot';
import readDataURIToBlob from '../Utils/readDataURIToBlob';
import ImageContent from './ImageContent';
import { type WebChatAttachment } from './private/types/WebChatAttachment';
const imageAttachmentPropsSchema = pipe(
object({
attachment: custom<WebChatAttachment>(
value =>
safeParse(
union([
object({
contentUrl: string(),
name: optional(string()),
thumbnailUrl: optional(string())
}),
object({
contentUrl: optional(string()),
name: optional(string()),
thumbnailUrl: string()
})
]),
value
).success
)
}),
readonly()
);
type ImageAttachmentProps = InferInput<typeof imageAttachmentPropsSchema>;
// React component is better with standard function than arrow function.
// eslint-disable-next-line prefer-arrow-callback
const ImageAttachment = memo(function ImageAttachment(props: ImageAttachmentProps) {
const { attachment } = validateProps(imageAttachmentPropsSchema, props);
let imageURL = attachment.thumbnailUrl || attachment.contentUrl;
// To support Content Security Policy, data URI cannot be used.
// We need to parse the data URI into a blob: URL.
const blob = readDataURIToBlob(imageURL);
if (blob) {
// Only allow image/* for image, otherwise, treat it as binary.
// eslint-disable-next-line no-restricted-properties
imageURL = URL.createObjectURL(
new Blob([blob], {
type: blob.type.startsWith('image/') ? blob.type : 'application/octet-stream'
})
);
}
return <ImageContent alt={attachment.name} src={imageURL} />;
});
export default ImageAttachment;