]> BookStack Code Mirror - bookstack/blob - resources/js/wysiwyg/utils/images.ts
Tests: Updated comment test to account for new editor usage
[bookstack] / resources / js / wysiwyg / utils / images.ts
1 import {ImageManager} from "../../components";
2 import {$createImageNode} from "@lexical/rich-text/LexicalImageNode";
3 import {$createLinkNode, LinkNode} from "@lexical/link";
4
5 export type EditorImageData = {
6     id: string;
7     url: string;
8     thumbs?: {display: string};
9     name: string;
10 };
11
12 export function showImageManager(callback: (image: EditorImageData) => any) {
13     const imageManager: ImageManager = window.$components.first('image-manager') as ImageManager;
14     imageManager.show((image: EditorImageData) => {
15         callback(image);
16     }, 'gallery');
17 }
18
19 export function $createLinkedImageNodeFromImageData(image: EditorImageData): LinkNode {
20     const url = image.thumbs?.display || image.url;
21     const linkNode = $createLinkNode(url, {target: '_blank'});
22     const imageNode = $createImageNode(url, {
23         alt: image.name
24     });
25     linkNode.append(imageNode);
26     return linkNode;
27 }
28
29 /**
30  * Upload an image file to the server
31  */
32 export async function uploadImageFile(file: File, pageId: string): Promise<EditorImageData> {
33     if (file === null || file.type.indexOf('image') !== 0) {
34         throw new Error('Not an image file');
35     }
36
37     const remoteFilename = file.name || `image-${Date.now()}.png`;
38     const formData = new FormData();
39     formData.append('file', file, remoteFilename);
40     formData.append('uploaded_to', pageId);
41
42     const resp = await window.$http.post('/images/gallery', formData);
43     return resp.data as EditorImageData;
44 }