1c5817cc938776709e4cc7b02cbd51059a5daab5
[GitHub/WoltLab/WCF.git] / ts / WoltLabSuite / Core / Media / Manager / Editor.ts
1 /**
2 * Provides the media manager dialog for selecting media for Redactor editors.
3 *
4 * @author Matthias Schmidt
5 * @copyright 2001-2021 WoltLab GmbH
6 * @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php>
7 * @module WoltLabSuite/Core/Media/Manager/Editor
8 */
9
10 import MediaManager from "./Base";
11 import * as Core from "../../Core";
12 import { Media, MediaInsertType, MediaManagerEditorOptions, MediaUploadSuccessEventData } from "../Data";
13 import * as EventHandler from "../../Event/Handler";
14 import * as DomTraverse from "../../Dom/Traverse";
15 import * as Language from "../../Language";
16 import * as UiDialog from "../../Ui/Dialog";
17 import * as Clipboard from "../../Controller/Clipboard";
18 import { OnDropPayload } from "../../Ui/Redactor/DragAndDrop";
19 import DomUtil from "../../Dom/Util";
20
21 interface PasteFromClipboard {
22 blob: Blob;
23 }
24
25 class MediaManagerEditor extends MediaManager<MediaManagerEditorOptions> {
26 protected _activeButton;
27 protected readonly _buttons: HTMLCollectionOf<HTMLElement>;
28 protected _mediaToInsert: Map<number, Media>;
29 protected _mediaToInsertByClipboard: boolean;
30 protected _uploadData: OnDropPayload | PasteFromClipboard | null;
31 protected _uploadId: number | null;
32
33 constructor(options: Partial<MediaManagerEditorOptions>) {
34 options = Core.extend(
35 {
36 callbackInsert: null,
37 },
38 options,
39 );
40
41 super(options);
42
43 this._forceClipboard = true;
44 this._activeButton = null;
45 const context = this._options.editor ? this._options.editor.core.toolbar()[0] : undefined;
46 this._buttons = (context || window.document).getElementsByClassName(
47 this._options.buttonClass || "jsMediaEditorButton",
48 ) as HTMLCollectionOf<HTMLElement>;
49 Array.from(this._buttons).forEach((button) => {
50 button.addEventListener("click", (ev) => this._click(ev));
51 });
52 this._mediaToInsert = new Map<number, Media>();
53 this._mediaToInsertByClipboard = false;
54 this._uploadData = null;
55 this._uploadId = null;
56
57 if (this._options.editor && !this._options.editor.opts.woltlab.attachments) {
58 const editorId = this._options.editor.$editor[0].dataset.elementId as string;
59
60 const uuid1 = EventHandler.add("com.woltlab.wcf.redactor2", `dragAndDrop_${editorId}`, (data: OnDropPayload) =>
61 this._editorUpload(data),
62 );
63 const uuid2 = EventHandler.add(
64 "com.woltlab.wcf.redactor2",
65 `pasteFromClipboard_${editorId}`,
66 (data: OnDropPayload) => this._editorUpload(data),
67 );
68
69 EventHandler.add("com.woltlab.wcf.redactor2", `destroy_${editorId}`, () => {
70 EventHandler.remove("com.woltlab.wcf.redactor2", `dragAndDrop_${editorId}`, uuid1);
71 EventHandler.remove("com.woltlab.wcf.redactor2", `dragAndDrop_${editorId}`, uuid2);
72 });
73
74 EventHandler.add("com.woltlab.wcf.media.upload", "success", (data) => this._mediaUploaded(data));
75 }
76 }
77
78 protected _addButtonEventListeners(): void {
79 super._addButtonEventListeners();
80
81 if (!this._mediaManagerMediaList) {
82 return;
83 }
84
85 DomTraverse.childrenByTag(this._mediaManagerMediaList, "LI").forEach((listItem) => {
86 const insertIcon = listItem.querySelector(".jsMediaInsertButton");
87 if (insertIcon) {
88 insertIcon.classList.remove("jsMediaInsertButton");
89 insertIcon.addEventListener("click", (ev) => this._openInsertDialog(ev));
90 }
91 });
92 }
93
94 /**
95 * Builds the dialog to setup inserting media files.
96 */
97 protected _buildInsertDialog(): void {
98 let thumbnailOptions = "";
99
100 this._getThumbnailSizes().forEach((thumbnailSize) => {
101 thumbnailOptions +=
102 '<option value="' +
103 thumbnailSize +
104 '">' +
105 Language.get("wcf.media.insert.imageSize." + thumbnailSize) +
106 "</option>";
107 });
108 thumbnailOptions += '<option value="original">' + Language.get("wcf.media.insert.imageSize.original") + "</option>";
109
110 const dialog = `
111 <div class="section">
112 <dl class="thumbnailSizeSelection">
113 <dt>${Language.get("wcf.media.insert.imageSize")}</dt>
114 <dd>
115 <select name="thumbnailSize">
116 ${thumbnailOptions}
117 </select>
118 </dd>
119 </dl>
120 </div>
121 <div class="formSubmit">
122 <button class="buttonPrimary">${Language.get("wcf.global.button.insert")}</button>
123 </div>`;
124
125 UiDialog.open({
126 _dialogSetup: () => {
127 return {
128 id: this._getInsertDialogId(),
129 options: {
130 onClose: () => this._editorClose(),
131 onSetup: (content) => {
132 content.querySelector(".buttonPrimary")!.addEventListener("click", (ev) => this._insertMedia(ev));
133
134 DomUtil.show(content.querySelector(".thumbnailSizeSelection") as HTMLElement);
135 },
136 title: Language.get("wcf.media.insert"),
137 },
138 source: dialog,
139 };
140 },
141 });
142 }
143
144 protected _click(event: Event): void {
145 this._activeButton = event.currentTarget;
146
147 super._click(event);
148 }
149
150 protected _dialogShow(): void {
151 super._dialogShow();
152
153 // check if data needs to be uploaded
154 if (this._uploadData) {
155 const fileUploadData = this._uploadData as OnDropPayload;
156 if (fileUploadData.file) {
157 this._upload.uploadFile(fileUploadData.file);
158 } else {
159 const blobUploadData = this._uploadData as PasteFromClipboard;
160 this._uploadId = this._upload.uploadBlob(blobUploadData.blob);
161 }
162
163 this._uploadData = null;
164 }
165 }
166
167 /**
168 * Handles pasting and dragging and dropping files into the editor.
169 */
170 protected _editorUpload(data: OnDropPayload): void {
171 this._uploadData = data;
172
173 UiDialog.open(this);
174 }
175
176 /**
177 * Returns the id of the insert dialog based on the media files to be inserted.
178 */
179 protected _getInsertDialogId(): string {
180 return ["mediaInsert", ...this._mediaToInsert.keys()].join("-");
181 }
182
183 /**
184 * Returns the supported thumbnail sizes (excluding `original`) for all media images to be inserted.
185 */
186 protected _getThumbnailSizes(): string[] {
187 return ["small", "medium", "large"]
188 .map((size) => {
189 const sizeSupported = Array.from(this._mediaToInsert.values()).every((media) => {
190 return media[size + "ThumbnailType"] !== null;
191 });
192
193 if (sizeSupported) {
194 return size;
195 }
196
197 return null;
198 })
199 .filter((s) => s !== null) as string[];
200 }
201
202 /**
203 * Inserts media files into the editor.
204 */
205 protected _insertMedia(event?: Event | null, thumbnailSize?: string, closeEditor = false): void {
206 if (closeEditor === undefined) closeEditor = true;
207
208 // update insert options with selected values if method is called by clicking on 'insert' button
209 // in dialog
210 if (event) {
211 UiDialog.close(this._getInsertDialogId());
212
213 const dialogContent = (event.currentTarget as HTMLElement).closest(".dialogContent")!;
214 const thumbnailSizeSelect = dialogContent.querySelector("select[name=thumbnailSize]") as HTMLSelectElement;
215 thumbnailSize = thumbnailSizeSelect.value;
216 }
217
218 if (this._options.callbackInsert !== null) {
219 this._options.callbackInsert(this._mediaToInsert, MediaInsertType.Separate, thumbnailSize!);
220 } else {
221 this._options.editor!.buffer.set();
222 }
223
224 if (this._mediaToInsertByClipboard) {
225 Clipboard.unmark("com.woltlab.wcf.media", Array.from(this._mediaToInsert.keys()));
226 }
227
228 this._mediaToInsert = new Map<number, Media>();
229 this._mediaToInsertByClipboard = false;
230
231 // close manager dialog
232 if (closeEditor) {
233 UiDialog.close(this);
234 }
235 }
236
237 /**
238 * Inserts a single media item into the editor.
239 */
240 protected _insertMediaItem(thumbnailSize: string, media: Media): void {
241 if (media.isImage) {
242 let available = "";
243 ["small", "medium", "large", "original"].some((size) => {
244 if (media[size + "ThumbnailHeight"] != 0) {
245 available = size;
246
247 if (thumbnailSize == size) {
248 return true;
249 }
250 }
251
252 return false;
253 });
254
255 thumbnailSize = available;
256
257 if (!thumbnailSize) {
258 thumbnailSize = "original";
259 }
260
261 let link = media.link;
262 if (thumbnailSize !== "original") {
263 link = media[thumbnailSize + "ThumbnailLink"];
264 }
265
266 this._options.editor!.insert.html(
267 `<img src="${link}" class="woltlabSuiteMedia" data-media-id="${media.mediaID}" data-media-size="${thumbnailSize}">`,
268 );
269 } else {
270 this._options.editor!.insert.text(`[wsm='${media.mediaID}'][/wsm]`);
271 }
272 }
273
274 /**
275 * Is called after media files are successfully uploaded to insert copied media.
276 */
277 protected _mediaUploaded(data: MediaUploadSuccessEventData): void {
278 if (this._uploadId !== null && this._upload === data.upload) {
279 if (
280 this._uploadId === data.uploadId ||
281 (Array.isArray(this._uploadId) && this._uploadId.indexOf(data.uploadId) !== -1)
282 ) {
283 this._mediaToInsert = new Map<number, Media>(data.media.entries());
284 this._insertMedia(null, "medium", false);
285
286 this._uploadId = null;
287 }
288 }
289 }
290
291 /**
292 * Handles clicking on the insert button.
293 */
294 protected _openInsertDialog(event: Event): void {
295 const target = event.currentTarget as HTMLElement;
296
297 this.insertMedia([~~target.dataset.objectId!]);
298 }
299
300 /**
301 * Is called to insert the media files with the given ids into an editor.
302 */
303 public clipboardInsertMedia(mediaIds: number[]): void {
304 this.insertMedia(mediaIds, true);
305 }
306
307 /**
308 * Prepares insertion of the media files with the given ids.
309 */
310 public insertMedia(mediaIds: number[], insertedByClipboard?: boolean): void {
311 this._mediaToInsert = new Map<number, Media>();
312 this._mediaToInsertByClipboard = insertedByClipboard || false;
313
314 // open the insert dialog if all media files are images
315 let imagesOnly = true;
316 mediaIds.forEach((mediaId) => {
317 const media = this._media.get(mediaId)!;
318 this._mediaToInsert.set(media.mediaID, media);
319
320 if (!media.isImage) {
321 imagesOnly = false;
322 }
323 });
324
325 if (imagesOnly) {
326 const thumbnailSizes = this._getThumbnailSizes();
327 if (thumbnailSizes.length) {
328 UiDialog.close(this);
329 const dialogId = this._getInsertDialogId();
330 if (UiDialog.getDialog(dialogId)) {
331 UiDialog.openStatic(dialogId, null);
332 } else {
333 this._buildInsertDialog();
334 }
335 } else {
336 this._insertMedia(undefined, "original");
337 }
338 } else {
339 this._insertMedia();
340 }
341 }
342
343 public getMode(): string {
344 return "editor";
345 }
346
347 public setupMediaElement(media: Media, mediaElement: HTMLElement): void {
348 super.setupMediaElement(media, mediaElement);
349
350 // add media insertion icon
351 const buttons = mediaElement.querySelector("nav.buttonGroupNavigation > ul")!;
352
353 const listItem = document.createElement("li");
354 listItem.className = "jsMediaInsertButton";
355 listItem.dataset.objectId = media.mediaID.toString();
356 buttons.appendChild(listItem);
357
358 listItem.innerHTML = `
359 <a>
360 <span class="icon icon16 fa-plus jsTooltip" title="${Language.get("wcf.global.button.insert")}"></span>
361 <span class="invisible">${Language.get("wcf.global.button.insert")}</span>
362 </a>`;
363 }
364 }
365
366 Core.enableLegacyInheritance(MediaManagerEditor);
367
368 export = MediaManagerEditor;