forked from openedx/frontend-app-authoring
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhooks.ts
More file actions
549 lines (505 loc) · 19 KB
/
hooks.ts
File metadata and controls
549 lines (505 loc) · 19 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
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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
import {
useState,
useRef,
useCallback,
useEffect,
} from 'react';
import { getConfig } from '@edx/frontend-platform';
import { getLocale, isRtl } from '@edx/frontend-platform/i18n';
import { a11ycheckerCss } from 'frontend-components-tinymce-advanced-plugins';
import { isEmpty } from 'lodash';
import tinyMCEStyles from '../../data/constants/tinyMCEStyles';
import { StrictDict } from '../../utils';
import pluginConfig from './pluginConfig';
import * as tinyMCE from '../../data/constants/tinyMCE';
import { getRelativeUrl, getStaticUrl, parseAssetName } from './utils';
import { isLibraryKey } from '../../../generic/key-utils';
export const state = StrictDict({
// eslint-disable-next-line react-hooks/rules-of-hooks
isImageModalOpen: (val) => useState(val),
// eslint-disable-next-line react-hooks/rules-of-hooks
isSourceCodeModalOpen: (val) => useState(val),
// eslint-disable-next-line react-hooks/rules-of-hooks
imageSelection: (val) => useState(val),
// eslint-disable-next-line react-hooks/rules-of-hooks
refReady: (val) => useState(val),
});
/**
* const imageMatchRegex
*
* Image urls and ids used in the TinyMceEditor vary wildly, with different base urls,
* different lengths and constituent parts, and replacement of some "/" with "@".
* Common are the keys "asset-v1", "type", and "block", each holding a value after some separator.
* This regex captures only the values for these keys using capture groups, which can be used for matching.
*/
export const imageMatchRegex = /asset-v1.(.*).type.(.*).block.(.*)/;
/**
* function matchImageStringsByIdentifiers
*
* matches two strings by comparing their regex capture groups using the `imageMatchRegex`
*/
export const matchImageStringsByIdentifiers = (a, b) => {
if (!a || !b || !(typeof a === 'string') || !(typeof b === 'string')) { return null; }
const matchA = JSON.stringify(a.match(imageMatchRegex)?.slice?.(1));
const matchB = JSON.stringify(b.match(imageMatchRegex)?.slice?.(1));
return matchA && matchA === matchB;
};
export const stringToFragment = (htmlString) => document.createRange().createContextualFragment(htmlString);
export function getImageFromHtmlString(htmlString, imageSrc) {
const images = stringToFragment(htmlString)?.querySelectorAll('img') || [];
return Array.from(images).find((img) => matchImageStringsByIdentifiers(img.src || '', imageSrc));
}
export const addImagesAndDimensionsToRef = ({ imagesRef, images, editorContentHtml }) => {
const imagesWithDimensions = Object.values(images).map((image: any) => {
const imageFragment = getImageFromHtmlString(editorContentHtml, image.url);
return { ...image, width: imageFragment?.width, height: imageFragment?.height };
});
// eslint-disable-next-line no-param-reassign
imagesRef.current = imagesWithDimensions;
};
export const useImages = ({ images, editorContentHtml }) => {
const imagesRef = useRef([]);
useEffect(() => {
addImagesAndDimensionsToRef({ imagesRef, images, editorContentHtml });
}, [images]);
return { imagesRef };
};
export const parseContentForLabels = ({ editor, updateContent }) => {
let content = editor.getContent();
if (content && content?.length > 0) {
const parsedLabels = content.split(/<label>|<\/label>/gm);
let updatedContent;
parsedLabels.forEach((label, i) => {
if (!label.startsWith('<') && !label.endsWith('>')) {
let previousLabel = parsedLabels[i - 1];
let nextLabel = parsedLabels[i + 1];
if (!previousLabel.endsWith('<p>')) {
previousLabel = `${previousLabel}</p><p>`;
updatedContent = content.replace(parsedLabels[i - 1], previousLabel);
content = updatedContent;
updateContent(content);
}
if (!nextLabel.startsWith('</p>')) {
nextLabel = `</p><p>${nextLabel}`;
updatedContent = content.replace(parsedLabels[i + 1], nextLabel);
content = updatedContent;
updateContent(content);
}
}
});
} else {
updateContent(content);
}
};
export const replaceStaticWithAsset = ({
initialContent,
learningContextId,
editorType,
lmsEndpointUrl,
}) => {
let content = initialContent;
let hasChanges = false;
const srcs = content.split(/(src="|src="|href="|href=")/g).filter(
src => src.startsWith('/static') || src.startsWith('/asset'),
);
if (!isEmpty(srcs)) {
srcs.forEach(src => {
const currentContent = content;
let staticFullUrl;
const isStatic = src.startsWith('/static/');
const assetSrc = src.substring(0, src.indexOf('"'));
const staticName = assetSrc.substring(8);
const assetName = parseAssetName(src);
const displayName = isStatic ? staticName : assetName;
const isCorrectAssetFormat = assetSrc.startsWith('/asset') && assetSrc.match(/\/asset-v1:\S+[+]\S+[@]\S+[+]\S+[@]/g)?.length >= 1;
// assets in expandable text areas do not support relative urls so all assets must have the lms
// endpoint prepended to the relative url
if (isLibraryKey(learningContextId)) {
// We are removing the initial "/" in a "/static/foo.png" link, and then
// set the base URL to an endpoint serving the draft version of an asset by
// its path.
/* istanbul ignore next */
if (isStatic) {
staticFullUrl = assetSrc.substring(1);
}
} else if (editorType === 'expandable') {
if (isCorrectAssetFormat) {
staticFullUrl = `${lmsEndpointUrl}${assetSrc}`;
} else {
staticFullUrl = `${lmsEndpointUrl}${getRelativeUrl({ courseId: learningContextId, displayName })}`;
}
} else if (!isCorrectAssetFormat) {
staticFullUrl = getRelativeUrl({ courseId: learningContextId, displayName });
}
if (staticFullUrl) {
const currentSrc = src.substring(0, src.indexOf('"'));
content = currentContent.replace(currentSrc, staticFullUrl);
hasChanges = true;
}
});
if (hasChanges) { return content; }
}
return false;
};
/**
* function updateImageDimensions
*
* Updates one images' dimensions in an array by identifying one image via a url string match
* that includes asset-v1, type, and block. Returns a new array.
*
* @param {Object[]} images - [{ id, ...other }]
* @param {string} url
* @param {number} width
* @param {number} height
*
* @returns {Object} { result, foundMatch }
*/
export function updateImageDimensions({
images, url, width, height,
}) {
let foundMatch = false;
const result = images.map((image) => {
const imageIdentifier = image.id || image.url || image.src || image.externalUrl;
const isMatch = matchImageStringsByIdentifiers(imageIdentifier, url);
if (isMatch) {
foundMatch = true;
return { ...image, width, height };
}
return image;
});
return { result, foundMatch };
}
export const getImageResizeHandler = ({ editor, imagesRef, setImage }) => () => {
const {
src, alt, width, height,
} = editor.selection.getNode();
// eslint-disable-next-line no-param-reassign
imagesRef.current = updateImageDimensions({
images: imagesRef.current, url: src, width, height,
}).result;
setImage({
externalUrl: src,
altText: alt,
width,
height,
});
};
/**
* Fix TinyMCE editors used in Paragon modals, by re-parenting their modal <div>
* from the body to the Paragon modal container.
*
* This fixes a problem where clicking on any modal/popup within TinyMCE (e.g.
* the emoji inserter, the link inserter, the floating format toolbar -
* quickbars, etc.) would cause the parent Paragon modal to close, because
* Paragon sees it as a "click outside" event. Also fixes some hover effects by
* ensuring the layering of the divs is correct.
*
* This could potentially cause problems if there are TinyMCE editors being used
* both on the parent page and inside a Paragon modal popup, but I don't think
* we have that situation.
*
* Note: we can't just do this on init, because the quickbars plugin used by
* ExpandableTextEditors creates its modal DIVs later. Ideally we could listen
* for some kind of "modal open" event, but I haven't been able to find anything
* like that so for now we do this quite frequently, every time there is a
* "selectionchange" event (which is pretty often).
*/
export const reparentTinyMceModals = /* istanbul ignore next */ () => {
const modalLayer = document.querySelector('.pgn__modal-layer');
if (!modalLayer) {
return;
}
const tinymceAuxDivs = document.querySelectorAll('.tox.tox-tinymce-aux');
for (const tinymceAux of tinymceAuxDivs) {
if (tinymceAux.parentElement !== modalLayer) {
// Move this tinyMCE modal div into the paragon modal layer.
modalLayer.appendChild(tinymceAux);
}
}
};
export const detectImageMatchingError = ({ matchingImages, tinyMceHTML }) => {
if (!matchingImages.length) { return true; }
if (matchingImages.length > 1) { return true; }
if (!matchImageStringsByIdentifiers(matchingImages[0].id, tinyMceHTML.src)) { return true; }
if (!matchingImages[0].width || !matchingImages[0].height) { return true; }
if (matchingImages[0].width !== tinyMceHTML.width) { return true; }
if (matchingImages[0].height !== tinyMceHTML.height) { return true; }
return false;
};
export const openModalWithSelectedImage = ({
editor, images, setImage, openImgModal,
}) => () => {
const tinyMceHTML = editor.selection.getNode();
const { src: mceSrc } = tinyMceHTML;
const matchingImages = images.current.filter(image => matchImageStringsByIdentifiers(image.id, mceSrc));
const imageMatchingErrorDetected = detectImageMatchingError({ tinyMceHTML, matchingImages });
const width = imageMatchingErrorDetected ? null : matchingImages[0]?.width;
const height = imageMatchingErrorDetected ? null : matchingImages[0]?.height;
setImage({
externalUrl: tinyMceHTML.src,
altText: tinyMceHTML.alt,
width,
height,
});
openImgModal();
};
export const setupCustomBehavior = ({
updateContent,
openImgModal,
openSourceCodeModal,
editorType,
images,
setImage,
lmsEndpointUrl,
learningContextId,
}) => (editor) => {
// image upload button
editor.ui.registry.addButton(tinyMCE.buttons.imageUploadButton, {
icon: 'image',
tooltip: 'Add Image',
onAction: openImgModal,
});
// editing an existing image
editor.ui.registry.addButton(tinyMCE.buttons.editImageSettings, {
icon: 'image',
tooltip: 'Edit Image Settings',
onAction: openModalWithSelectedImage({
editor, images, setImage, openImgModal,
}),
});
// overriding the code plugin's icon with 'HTML' text
editor.ui.registry.addButton(tinyMCE.buttons.code, {
text: 'HTML',
tooltip: 'Source code',
onAction: openSourceCodeModal,
});
// add a custom simple inline code block formatter.
const setupCodeFormatting = (api) => {
editor.formatter.formatChanged(
'code',
(active) => api.setActive(active),
);
};
const toggleCodeFormatting = () => {
editor.formatter.toggle('code');
editor.undoManager.add();
editor.focus();
};
editor.ui.registry.addToggleButton(tinyMCE.buttons.codeBlock, {
icon: 'sourcecode',
tooltip: 'Code Block',
onAction: toggleCodeFormatting,
onSetup: setupCodeFormatting,
});
// add a custom simple inline label formatter.
const toggleLabelFormatting = () => {
editor.execCommand('mceToggleFormat', false, 'label');
};
editor.ui.registry.addIcon('textToSpeech', tinyMCE.textToSpeechIcon);
editor.ui.registry.addButton('customLabelButton', {
icon: 'textToSpeech',
text: 'Label',
tooltip: 'Apply a "Question" label to specific text, recognized by screen readers. Recommended to improve accessibility.',
onAction: toggleLabelFormatting,
});
if (editorType === 'expandable') {
editor.on('init', () => {
const initialContent = editor.getContent();
const newContent = replaceStaticWithAsset({
initialContent,
editorType,
lmsEndpointUrl,
learningContextId,
});
// istanbul ignore if
if (newContent) {
// update content but mark as not dirty as user did not change anything
updateContent(newContent, false);
editor.setDirty(false);
}
});
}
editor.on('init', /* istanbul ignore next */ () => {
// Check if this editor is inside a (Paragon) modal.
// The way we get the editor's root <div> depends on whether or not this particular editor is using an iframe:
const editorDiv = editor.bodyElement ?? editor.container;
if (editorDiv?.closest('.pgn__modal')) {
// This editor is inside a Paragon modal. Use this hack to avoid interference with TinyMCE's own modal popups:
reparentTinyMceModals();
editor.on('selectionchange', reparentTinyMceModals);
}
});
editor.on('ExecCommand', /* istanbul ignore next */ (e) => {
if (editorType === 'text' && e.command === 'mceFocus') {
const initialContent = editor.getContent();
// @ts-ignore Some parameters like 'lmsEndpointUrl' were missing here. Fix me?
const newContent = replaceStaticWithAsset({
initialContent,
learningContextId,
});
if (newContent) { editor.setContent(newContent); }
}
if (e.command === 'RemoveFormat') {
editor.formatter.remove('blockquote');
editor.formatter.remove('label');
}
});
// after resizing an image in the editor, synchronize React state and ref
editor.on('ObjectResized', getImageResizeHandler({ editor, imagesRef: images, setImage }));
};
// imagetools_cors_hosts needs a protocol-sanatized url
export const removeProtocolFromUrl = (url) => url.replace(/^https?:\/\//, '');
export const editorConfig = ({
editorType,
setEditorRef,
editorContentHtml,
images,
placeholder,
initializeEditor,
openImgModal,
openSourceCodeModal,
setSelection,
updateContent,
content,
minHeight,
maxHeight,
learningContextId,
staticRootUrl,
enableImageUpload,
}) => {
const lmsEndpointUrl = getConfig().LMS_BASE_URL;
const studioEndpointUrl = getConfig().STUDIO_BASE_URL;
const baseURL = staticRootUrl || lmsEndpointUrl;
const {
toolbar,
config,
plugins,
imageToolbar,
quickbarsInsertToolbar,
quickbarsSelectionToolbar,
} = pluginConfig({ placeholder, editorType, enableImageUpload });
const isLocaleRtl = isRtl(getLocale());
return {
onInit: (_evt, editor) => {
setEditorRef(editor);
if (editorType === 'text') {
initializeEditor();
}
},
initialValue: editorContentHtml || '',
init: {
...config,
skin: false,
content_css: false,
content_style: tinyMCEStyles + a11ycheckerCss,
min_height: minHeight,
max_height: maxHeight,
contextmenu: 'link table',
directionality: isLocaleRtl ? 'rtl' as const : 'ltr' as const,
document_base_url: baseURL,
imagetools_cors_hosts: [removeProtocolFromUrl(lmsEndpointUrl), removeProtocolFromUrl(studioEndpointUrl)],
imagetools_toolbar: imageToolbar,
formats: { label: { inline: 'label' } },
setup: setupCustomBehavior({
editorType,
updateContent,
openImgModal,
openSourceCodeModal,
lmsEndpointUrl,
setImage: setSelection,
// @ts-ignore FIXME: 'content' is not an accepted parameter of setupCustomBehavior()
content,
images,
learningContextId,
}),
quickbars_insert_toolbar: quickbarsInsertToolbar,
quickbars_selection_toolbar: quickbarsSelectionToolbar,
quickbars_image_toolbar: false,
toolbar,
plugins,
valid_children: '+body[style]',
valid_elements: '*[*]',
// FIXME: this is passing 'utf-8', which is not a valid entity_encoding value. It should be 'named' etc.
entity_encoding: 'utf-8' as any,
// Protect self-closing <script /> tags from being mangled,
// to preserve backwards compatibility with content that relied on this behavior
protect: [/<script[^>]*\/>/g],
},
};
};
export const prepareEditorRef = () => {
// eslint-disable-next-line react-hooks/rules-of-hooks
const editorRef = useRef(null);
// eslint-disable-next-line react-hooks/rules-of-hooks
const setEditorRef = useCallback((ref) => {
editorRef.current = ref;
}, []);
const [refReady, setRefReady] = state.refReady(false);
// eslint-disable-next-line react-hooks/rules-of-hooks
useEffect(() => setRefReady(true), []);
return { editorRef, refReady, setEditorRef };
};
export const imgModalToggle = () => {
const [isImgOpen, setIsOpen] = state.isImageModalOpen(false);
return {
isImgOpen,
openImgModal: () => setIsOpen(true),
closeImgModal: () => setIsOpen(false),
};
};
export const sourceCodeModalToggle = (editorRef) => {
const [isSourceCodeOpen, setIsOpen] = state.isSourceCodeModalOpen(false);
return {
isSourceCodeOpen,
openSourceCodeModal: () => setIsOpen(true),
closeSourceCodeModal: () => {
setIsOpen(false);
editorRef.current.focus();
},
};
};
export const setAssetToStaticUrl = ({ editorValue, lmsEndpointUrl }) => {
/* For assets to remain usable across course instances, we convert their url to be course-agnostic.
* For example, /assets/course/<asset hash>/filename gets converted to /static/filename. This is
* important for rerunning courses and importing/exporting course as the /static/ part of the url
* allows the asset to be mapped to the new course run.
*/
// TODO: should probably move this to when the assets are being looped through in the off chance that
// some of the text in the editor contains the lmsEndpointUrl
const regExLmsEndpointUrl = RegExp(lmsEndpointUrl, 'g');
let content = editorValue.replace(regExLmsEndpointUrl, '');
const assetSrcs = typeof content === 'string' ? content.split(/(src="|src="|href="|href=")/g) : [];
assetSrcs.filter(src => src.startsWith('/asset')).forEach(src => {
const nameFromEditorSrc = parseAssetName(src);
const portableUrl = getStaticUrl({ displayName: nameFromEditorSrc });
const currentSrc = src.substring(0, src.search(/("|")/));
const updatedContent = content.replace(currentSrc, portableUrl);
content = updatedContent;
});
const updatedStaticUrls: string[] = [];
assetSrcs.filter(src => src.startsWith('static/')).forEach(src => {
// Before storing assets we make sure that library static assets points again to
// `/static/dummy.jpg` instead of using the relative url `static/dummy.jpg`
const nameFromEditorSrc = parseAssetName(src);
const portableUrl = `/${nameFromEditorSrc}`;
if (updatedStaticUrls.includes(portableUrl)) {
// If same image is used multiple times in the same src,
// replace all occurence once and do not process them again.
return;
}
// track updated urls to process only once.
updatedStaticUrls.push(portableUrl);
const currentSrc = src.substring(0, src.search(/("|")/));
const updatedContent = content.replaceAll(currentSrc, portableUrl);
content = updatedContent;
});
return content;
};
export const selectedImage = (val) => {
const [selection, setSelection] = state.imageSelection(val);
return {
clearSelection: () => setSelection(null),
selection,
setSelection,
};
};