-
Notifications
You must be signed in to change notification settings - Fork 186
/
cms.ckeditor.js
511 lines (447 loc) · 20.2 KB
/
cms.ckeditor.js
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
(function ($, CMS) {
'use strict';
window.CKEDITOR_BASEPATH = $('[data-ckeditor-basepath]').attr('data-ckeditor-basepath');
// CMS.$ will be passed for $
/**
* CMS.CKEditor
*
* @description: Adds cms specific plugins to CKEditor
*/
CMS.CKEditor = {
options: {
// ckeditor default settings, will be overwritten by CKEDITOR_SETTINGS
language: 'en',
skin: 'moono-lisa',
toolbar_CMS: [
['Undo', 'Redo'],
['cmsplugins', 'cmswidget', '-', 'ShowBlocks'],
['Format', 'Styles'],
['TextColor', 'BGColor', '-', 'PasteText', 'PasteFromWord'],
['Scayt'],
['Maximize', ''],
'/',
['Bold', 'Italic', 'Underline', 'Strike', '-', 'Subscript', 'Superscript', '-', 'RemoveFormat'],
['JustifyLeft', 'JustifyCenter', 'JustifyRight', 'JustifyBlock'],
['HorizontalRule'],
['NumberedList', 'BulletedList'],
['Outdent', 'Indent', '-', 'Blockquote', '-', 'Link', 'Unlink', '-', 'Table'],
['Source']
],
toolbar_HTMLField: [
['Undo', 'Redo'],
['ShowBlocks'],
['Format', 'Styles'],
['TextColor', 'BGColor', '-', 'PasteText', 'PasteFromWord'],
['Scayt'],
['Maximize', ''],
'/',
['Bold', 'Italic', 'Underline', 'Strike', '-', 'Subscript', 'Superscript', '-', 'RemoveFormat'],
['JustifyLeft', 'JustifyCenter', 'JustifyRight', 'JustifyBlock'],
['HorizontalRule'],
['Link', 'Unlink'],
['NumberedList', 'BulletedList'],
['Outdent', 'Indent', '-', 'Blockquote', '-', 'Link', 'Unlink', '-', 'Table'],
['Source']
],
allowedContent: true,
toolbarCanCollapse: false,
removePlugins: 'resize',
extraPlugins: ''
},
// Meaningful default, overwritten by the backend
static_url: '/static/djangocms-text-ckeditor',
CSS: [],
editors: {},
init: function (element, mode, options, settings, callback) {
var container = $(element);
container.data('ckeditor-initialized', true);
container.attr('contenteditable', true);
// add additional settings to options
this.options.toolbar = settings.toolbar;
this.options = $.extend(false, {
settings: settings
}, this.options, options);
// add extra plugins that we absolutely must have
this.options.extraPlugins = this.options.extraPlugins +=
',cmsplugins,cmswidget,cmsdialog,cmsresize,widget';
document.createElement('cms-plugin');
CKEDITOR.dtd['cms-plugin'] = CKEDITOR.dtd.div;
CKEDITOR.dtd.$inline['cms-plugin'] = 1;
// has to be here, otherwise extra <p> tags appear
CKEDITOR.dtd.$nonEditable['cms-plugin'] = 1;
CKEDITOR.dtd.$transparent['cms-plugin'] = 1;
CKEDITOR.dtd.body['cms-plugin'] = 1;
// add additional plugins (autoloads plugins.js)
CKEDITOR.skin.addIcon('cmsplugins', settings.static_url +
'/ckeditor_plugins/cmsplugins/icons/cmsplugins.svg');
var editor;
if (mode === 'admin') {
// render ckeditor
editor = CKEDITOR.replace(container[0], this.options);
} else {
editor = CKEDITOR.inline(container[0], this.options);
}
CMS.CKEditor.editors[editor.id] = {
editor: editor,
options: options,
settings: settings,
container: container,
changed: false,
child_changed: false
};
editor.on('instanceReady', callback);
},
initInlineEditors: function () {
if (CMS._plugins === undefined) {
// no plugins -> no inline editors
return;
}
CMS.CKEditor.observer = CMS.CKEditor.observer || new IntersectionObserver(function (entries, opts) {
entries.forEach(function (entry) {
if (entry.isIntersecting) {
var target = $(entry.target);
var plugin_id = target.data('cms_plugin_id');
var url = target.data('cms_edit_url');
CMS.CKEditor.startInlineEditor(plugin_id, url);
}
});
}, {
root: null,
threshold: 0.05
});
CMS._plugins.forEach(function (plugin) {
if (plugin[1].plugin_type === 'TextPlugin') {
var url = plugin[1].urls.edit_plugin;
var id = plugin[1].plugin_id;
var elements = $('.cms-plugin.cms-plugin-' + id);
var wrapper;
if (elements.length > 0) {
if (elements.length === 1 && elements.prop('tagName') === 'DIV') { // already wrapped?
wrapper = elements.addClass('cms-ckeditor-inline-wrapper');
} else { // no, wrap now!
wrapper = elements
.wrapAll('<div class="cms-ckeditor-inline-wrapper wrapped"></div>')
.parent();
elements
.removeClass('cms-plugin')
.removeClass('cms-plugin-' + id);
wrapper.addClass('cms-plugin').addClass('cms-plugin-' + id);
}
wrapper.data('cms_edit_url', url);
wrapper.data('cms_plugin_id', id);
wrapper.on('dblclick.cms-ckeditor', function (event) {
// Double-click is needed by CKEditor
event.stopPropagation();
});
wrapper.on('pointerover.cms-ckeditor', function (event) {
// use time out to let other event handlers (CMS' !) run first.
setTimeout(function () {
// do not show tooltip on inline editing text fields.
CMS.API.Tooltip.displayToggle(false, event.target, '', id);
}, 0);
});
CMS.CKEditor.observer.observe(wrapper[0]);
}
}
});
$(window).on('beforeunload.cms-ckeditor', function () {
for (var editor_id in CMS.CKEditor.editors) {
if (CMS.CKEditor.editors.hasOwnProperty(editor_id) &&
CMS.CKEditor.editors[editor_id].changed) {
return 'Do you really want to leave this page?';
}
}
});
},
startInlineEditor: function (plugin_id, url) {
var options;
var settings = JSON.parse(document.getElementById('ck-cfg-' + plugin_id).textContent);
var wrapper = $('.cms-plugin.cms-plugin-' + plugin_id);
if (wrapper.data('ckeditor-initialized')) {
return;
}
settings.plugin_id = plugin_id;
settings.url = url;
options = settings.options;
delete settings.options;
CMS.CKEditor.init(
wrapper[0],
'inline',
options,
settings,
function (callback) {
callback.editor.element.removeAttribute('title');
callback.editor.on('change', function () {
CMS.CKEditor.editors[callback.editor.id].changed = true;
});
wrapper.on('blur.cms-ckeditor', function () {
setTimeout(function () {
// avoid save when clicking on editor dialogs or toolbar
if (!document.activeElement.classList.contains('cke_panel_frame') &&
!document.activeElement.classList.contains('cke_dialog_ui_button')) {
CMS.CKEditor.save_data(callback.editor.id);
}
}, 0);
});
wrapper.on('click.cms-ckeditor', function () {
// Highlight plugin in structure board
// Needs to be done manually, since the tooltip is suppressed and django CMS
// only automatically highlights the plugin if the tooltip is visible
CMS.CKEditor._highlight_Textplugin(plugin_id);
});
// store css that ckeditor loaded before save
CMS.CKEditor.storeCSSlinks();
}
);
},
save_data: function (editor_id, action) {
var instance = CMS.CKEditor.editors[editor_id];
if (instance && instance.changed) {
CMS.CKEditor.storeCSSlinks(); // store css that ckeditor loaded before save
var data = instance.editor.getData();
CMS.API.Toolbar.showLoader();
$.post(CMS.API.Helpers.updateUrlWithPath(instance.settings.url), { // send changes
csrfmiddlewaretoken: CMS.config.csrf,
body: data,
_save: 'Save'
}, function (response) {
instance.changed = false;
CMS.API.Toolbar.hideLoader();
if (action !== undefined) {
action(instance, response);
}
if (instance.child_changed) {
var scripts = $(response).find('script:not([src])').addClass('cms-ckeditor-result');
CMS.CKEditor._destroyAll();
scripts.each(function (item, element) {
$('body').append(element);
});
} else {
CMS.CKEditor.loadToolbar();
}
}).fail(function (error) {
instance.changed = true;
CMS.API.Messages.open({
message: error.message,
error: true
});
});
}
},
loadToolbar: function () {
if (CMS.settings && CMS.settings.version && this._toolbar_bug_version(CMS.settings.version)) {
// Before django CMS 3.10 a bug prevents the toolbar to be loaded correctly
// Refresh whole page instead
CMS.API.Helpers.reloadBrowser();
} else {
CMS.API.StructureBoard._loadToolbar()
.done(function (newToolbar) {
CMS.API.Toolbar._refreshMarkup($(newToolbar).find('.cms-toolbar'));
})
.fail(CMS.API.Helpers.reloadBrowser);
}
},
_toolbar_bug_version: function (version) {
var parts = version.split('.');
return parts[0] === '3' && parts[1].length < 2;
},
storeCSSlinks: function () {
$("link[rel='stylesheet'][type='text/css'][href*='ckeditor']").each(
function (index, element) {
if (!CMS.CKEditor.CSS.includes(element.href)) {
CMS.CKEditor.CSS.push(element.href);
}
}
);
},
// setup is called after ckeditor has been initialized
setupAdmin: function (editor) {
// auto maximize modal if alone in a modal
var that = this;
var win = window.parent || window;
// 70px is hardcoded to make it more performant. 20px + 20px - paddings, 30px label height
var TOOLBAR_HEIGHT_WITH_PADDINGS = 70;
if (this._isAloneInModal(CMS.CKEditor.editors[editor.id].container)) {
editor.resize('100%', win.CMS.$('.cms-modal-frame').height() - TOOLBAR_HEIGHT_WITH_PADDINGS);
editor.execCommand('maximize');
$(window).on('resize.ckeditor', function () {
that._repositionDialog(CKEDITOR.dialog.getCurrent(), win);
}).trigger('resize.ckeditor');
win.CMS.API.Helpers.addEventListener('modal-maximized modal-restored', function () {
try {
if (!$('.cke_maximized').length) {
editor.resize(
'100%',
win.CMS.$('.cms-modal-frame').height() - TOOLBAR_HEIGHT_WITH_PADDINGS
);
setTimeout(function () {
that._repositionDialog(CKEDITOR.dialog.getCurrent(), win);
}, 0);
}
} catch (e) {
// sometimes throws errors if modal with text plugin is closed too fast
}
});
}
// add css tweks to the editor
this.styles();
this._resizing();
},
styles: function () {
// add styling to source and fullscreen view
$('.cke_button__maximize, .cke_button__source').parent()
.css('margin-right', 0).parent()
.css('float', 'right');
},
_resizing: function () {
$(document).on('pointerdown', '.cms-ckeditor-resizer', function (e) {
e.preventDefault();
var event = new CMS.$.Event('mousedown');
$.extend(event, {
screenX: e.originalEvent.screenX,
screenY: e.originalEvent.screenY
});
$(this).trigger(event);
});
},
_isAloneInModal: function (container) {
var body = container.closest('body');
// return true if the ckeditor is alone in a modal popup
return body.is('.app-djangocms_text_ckeditor.model-text');
},
/**
* @method _repositionDialog
* @private
* @param {CKEDITOR.dialog} dialog instance
*/
_repositionDialog: function (dialog) {
var OFFSET = 80;
if (!dialog) {
return;
}
var size = dialog.getSize();
var position = dialog.getPosition();
var win = CKEDITOR.document.getWindow();
var viewSize = win.getViewPaneSize();
var winWidth = viewSize.width;
var winHeight = viewSize.height;
if (position.x < 0) {
dialog.move(0, position.y);
position.x = 0;
}
if (position.y < 0) {
dialog.move(position.x, 0);
position.y = 0;
}
if (position.y + size.height > winHeight) {
dialog.resize(size.width, winHeight - position.y - OFFSET);
}
if (position.x + size.width > winWidth) {
dialog.resize(winWidth - position.x, size.height);
}
},
initAdminEditors: function () {
window._cmsCKEditors = window._cmsCKEditors || [];
var dynamics = [];
var settings;
var options;
window._cmsCKEditors.forEach(function (editorConfig) {
var elementId = 'ck-cfg-' + (editorConfig[1] ? editorConfig[1] : editorConfig[0]);
settings = JSON.parse(document.getElementById(elementId).textContent);
options = settings.options;
delete settings.options;
if (editorConfig[0].match(/__prefix__/)) {
dynamics.push(editorConfig);
} else {
CMS.CKEditor.init(
document.getElementById(editorConfig[0]),
'admin',
options,
settings,
function (callback) {
return CMS.CKEditor.setupAdmin(callback.editor);
}
);
}
});
$('.add-row a').on('click', function () {
$('.CMS_CKEditor').each(function (i, el) {
var container = $(el);
if (container.data('ckeditor-initialized')) {
return;
}
var containerId = container.attr('id');
// in case there are multiple different inlines we need to check
// newly added one against all of them
dynamics.forEach(function (config) {
var selector = config[0].id;
var regex = new RegExp(selector.replace('__prefix__', '\\d+'));
if (containerId.match(regex)) {
CMS.CKEditor.init(
document.getElementById(containerId),
options,
settings
);
}
});
});
});
},
_highlight_Textplugin: function (pluginId) {
var HIGHLIGHT_TIMEOUT = 10;
var draggable = $('.cms-draggable-' + pluginId);
var doc = $(document);
var currentExpandmode = doc.data('expandmode');
// expand necessary parents
doc.data('expandmode', false);
draggable
.parents('.cms-draggable')
.find('> .cms-dragitem-collapsable:not(".cms-dragitem-expanded") > .cms-dragitem-text')
.each(function (i, el) {
$(el).triggerHandler(CMS.Plugin.click);
});
if (draggable.length > 0) { // Expanded elements available
setTimeout(function () {
doc.data('expandmode', currentExpandmode);
});
setTimeout(function () {
CMS.Plugin._highlightPluginStructure(draggable.find('.cms-dragitem:first'),
{successTimeout: 200, delay: 2000, seeThrough: true});
}, HIGHLIGHT_TIMEOUT);
}
},
_initAll: function () {
CMS.CKEditor.touchdevice = 'ontouchstart' in window || navigator.msMaxTouchPoints; // on touch device?
if (!CMS.CKEditor.touchdevice) { // no inline editing on touch devices to not interfere with scrolling
CMS.CKEditor.initInlineEditors();
$('div.cms a.cms-btn.cms-edit-toggle').show();
} else {
$('div.cms a.cms-btn.cms-edit-toggle').hide();
}
CMS.CKEditor.initAdminEditors();
},
_destroyAll: function () {
for (var id in CMS.CKEditor.editors) {
if (CMS.CKEditor.editors.hasOwnProperty(id)) {
CMS.CKEditor.editors[id].editor.destroy();
$(CMS.CKEditor.editors[id].container).off('.cms-ckeditor');
delete CMS.CKEditor.editors[id];
}
}
$(window).off('.cms-ckeditor');
},
_resetInlineEditors: function () {
CMS.CKEditor.CSS.forEach(function (stylefile) {
if ($("link[href='" + stylefile + "']").length === 0) {
$('head').append($("<link rel='stylesheet' type='text/css' href='" + stylefile + "'>"));
}
});
CMS.CKEditor._destroyAll();
CMS.CKEditor._initAll();
}
};
setTimeout(function init() {
CMS.CKEditor._initAll();
}, 0);
$(window).on('cms-content-refresh', CMS.CKEditor._resetInlineEditors);
})(window.CMS.$, window.CMS);