-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathimage.ts
More file actions
49 lines (39 loc) · 1.42 KB
/
image.ts
File metadata and controls
49 lines (39 loc) · 1.42 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
import { MarkEdit } from 'markedit-api';
import { blobToBase64, generateFileName, insertSnippet, insertText } from './util';
export async function handleImagePaste(event: ClipboardEvent) {
const images = Array.from(event.clipboardData?.items ?? [])
.map(item => item.getAsFile())
.filter(file => file?.type.startsWith('image/')) as File[];
// Fall back to file names if no images
if (images.length === 0) {
return handleFileNames(event);
}
await Promise.all(images.map(pasteImage));
event.preventDefault();
event.stopPropagation();
}
async function pasteImage(file: File) {
const basePath = (await MarkEdit.getFileInfo())?.parentPath;
if (basePath === undefined) {
return;
}
const imageData = (await blobToBase64(file)).replace(/^data:.+;base64,/, '');
const existingNames = (await MarkEdit.listFiles(basePath)) ?? [];
const newFileName = generateFileName(file.name, existingNames);
MarkEdit.createFile({
path: `${basePath}/${newFileName}`,
data: imageData,
});
insertSnippet(``);
}
function handleFileNames(event: ClipboardEvent) {
const clipboardData = event.clipboardData;
const plainText = clipboardData?.getData('text/plain') ?? '';
if (plainText.length > 0) {
return;
}
const files = Array.from(clipboardData?.files ?? []);
insertText(files.map(file => file.name).join('\n'));
event.preventDefault();
event.stopPropagation();
}