init_tinymce.js 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. 'use strict';
  2. {
  3. function initTinyMCE(el) {
  4. if (el.closest('.empty-form') === null) { // Don't do empty inlines
  5. var mce_conf = JSON.parse(el.dataset.mceConf);
  6. // There is no way to pass a JavaScript function as an option
  7. // because all options are serialized as JSON.
  8. const fns = [
  9. 'color_picker_callback',
  10. 'file_browser_callback',
  11. 'file_picker_callback',
  12. 'images_dataimg_filter',
  13. 'images_upload_handler',
  14. 'paste_postprocess',
  15. 'paste_preprocess',
  16. 'setup',
  17. 'urlconverter_callback',
  18. 'media_url_resolver',
  19. ];
  20. fns.forEach((fn_name) => {
  21. if (typeof mce_conf[fn_name] != 'undefined') {
  22. if (mce_conf[fn_name].includes('(')) {
  23. mce_conf[fn_name] = eval('(' + mce_conf[fn_name] + ')');
  24. }
  25. else {
  26. mce_conf[fn_name] = window[mce_conf[fn_name]];
  27. }
  28. }
  29. });
  30. // replace default prefix of 'empty-form' if used in selector
  31. if (mce_conf.selector && mce_conf.selector.includes('__prefix__')) {
  32. mce_conf.selector = `#${el.id}`;
  33. }
  34. else if (!('selector' in mce_conf)) {
  35. mce_conf['target'] = el;
  36. }
  37. if (el.dataset.mceGzConf) {
  38. tinyMCE_GZ.init(JSON.parse(el.dataset.mceGzConf));
  39. }
  40. if (!tinyMCE.get(el.id)) {
  41. tinyMCE.init(mce_conf);
  42. }
  43. }
  44. }
  45. // Call function fn when the DOM is loaded and ready. If it is already
  46. // loaded, call the function now.
  47. function ready(fn) {
  48. if (document.readyState !== 'loading') {
  49. fn();
  50. } else {
  51. document.addEventListener('DOMContentLoaded', fn);
  52. }
  53. }
  54. function initializeTinyMCE(element, formsetName) {
  55. Array.from(element.querySelectorAll('.tinymce')).forEach(area => initTinyMCE(area));
  56. }
  57. ready(function() {
  58. if (!tinyMCE) {
  59. throw 'tinyMCE is not loaded. If you customized TINYMCE_JS_URL, double-check its content.';
  60. }
  61. // initialize the TinyMCE editors on load
  62. initializeTinyMCE(document);
  63. // initialize the TinyMCE editor after adding an inline in the django admin context.
  64. if (typeof(django) !== 'undefined' && typeof(django.jQuery) !== 'undefined') {
  65. django.jQuery(document).on('formset:added', (event, $row, formsetName) => {
  66. if (event.detail && event.detail.formsetName) {
  67. // Django >= 4.1
  68. initializeTinyMCE(event.target);
  69. } else {
  70. // Django < 4.1, use $row
  71. initializeTinyMCE($row.get(0));
  72. }
  73. });
  74. }
  75. });
  76. }