4 var website = openerp.website;
6 website.templates.push('/website/static/src/xml/website.editor.xml');
7 website.dom_ready.done(function () {
8 // $.fn.data automatically parses value, '0'|'1' -> 0|1
9 website.is_editable = $(document.documentElement).data('editable');
10 var is_smartphone = $(document.body)[0].clientWidth < 767;
12 if (website.is_editable && !is_smartphone) {
13 website.ready().then(website.init_editor);
17 function link_dialog(editor) {
18 return new website.editor.LinkDialog(editor).appendTo(document.body);
20 function image_dialog(editor) {
21 return new website.editor.ImageDialog(editor).appendTo(document.body);
24 website.init_editor = function () {
25 CKEDITOR.plugins.add('customdialogs', {
26 requires: 'link,image',
27 init: function (editor) {
28 editor.on('doubleclick', function (evt) {
29 if (evt.data.dialog === 'link') {
30 delete evt.data.dialog;
32 } else if(evt.data.dialog === 'image') {
33 delete evt.data.dialog;
36 // priority should be smaller than dialog (999) but bigger
37 // than link or image (default=10)
40 editor.addCommand('link', {
41 exec: function (editor, data) {
48 editor.addCommand('image', {
49 exec: function (editor, data) {
58 CKEDITOR.plugins.add( 'tablebutton', {
59 requires: 'panelbutton,floatpanel',
60 init: function( editor ) {
63 editor.ui.add('TableButton', CKEDITOR.UI_PANELBUTTON, {
66 // use existing 'table' icon
68 modes: { wysiwyg: true },
70 // panel opens in iframe, @css is CSS file <link>-ed within
71 // frame document, @attributes are set on iframe itself.
73 css: '/website/static/src/css/editor.css',
74 attributes: { 'role': 'listbox', 'aria-label': label, },
77 onBlock: function (panel, block) {
78 block.autoSize = true;
79 block.element.setHtml(openerp.qweb.render('website.editor.table.panel', {
84 var $table = $(block.element.$).on('mouseenter', 'td', function (e) {
86 var y = $e.index() + 1;
87 var x = $e.closest('tr').index() + 1;
90 .find('td').removeClass('selected').end()
91 .find('tr:lt(' + String(x) + ')')
92 .children().filter(function () { return $(this).index() < y; })
93 .addClass('selected');
94 }).on('click', 'td', function (e) {
97 var table = new CKEDITOR.dom.element(
98 $(openerp.qweb.render('website.editor.table', {
99 rows: $e.closest('tr').index() + 1,
100 cols: $e.index() + 1,
103 editor.insertElement(table);
104 setTimeout(function () {
105 var firstCell = new CKEDITOR.dom.element(table.$.rows[0].cells[0]);
106 var range = editor.createRange();
107 range.moveToPosition(firstCell, CKEDITOR.POSITION_AFTER_START);
112 block.element.getDocument().getBody().setStyle('overflow', 'hidden');
113 CKEDITOR.ui.fire('ready', this);
119 var editor = new website.EditorBar();
120 var $body = $(document.body);
121 editor.prependTo($body).then(function () {
122 if (location.search.indexOf("unable_editor") >= 0) {
126 $body.css('padding-top', '50px'); // Not working properly: editor.$el.outerHeight());
128 /* ----- TOP EDITOR BAR FOR ADMIN ---- */
129 website.EditorBar = openerp.Widget.extend({
130 template: 'website.editorbar',
132 'click button[data-action=edit]': 'edit',
133 'click button[data-action=save]': 'save',
134 'click button[data-action=cancel]': 'cancel',
137 customize_setup: function() {
139 var view_name = $(document.documentElement).data('view-xmlid');
140 var menu = $('#customize-menu');
141 this.$('#customize-menu-button').click(function(event) {
143 openerp.jsonRpc('/website/customize_template_get', 'call', { 'xml_id': view_name }).then(
145 _.each(result, function (item) {
147 menu.append('<li class="dropdown-header">' + item.name + '</li>');
149 menu.append(_.str.sprintf('<li role="presentation"><a href="#" data-view-id="%s" role="menuitem"><strong class="icon-check%s"></strong> %s</a></li>',
150 item.id, item.active ? '' : '-empty', item.name));
153 // Adding Static Menus
154 menu.append('<li class="divider"></li><li><a href="/page/website.themes">Change Theme</a></li>');
155 menu.append('<li class="divider"></li><li><a data-action="ace" href="#">Advanced view editor</a></li>');
159 menu.on('click', 'a[data-action!=ace]', function (event) {
160 var view_id = $(event.currentTarget).data('view-id');
161 openerp.jsonRpc('/website/customize_template_toggle', 'call', {
163 }).then( function(result) {
164 window.location.reload();
171 this.saving_mutex = new openerp.Mutex();
173 this.$('#website-top-edit').hide();
174 this.$('#website-top-view').show();
176 $('.dropdown-toggle').dropdown();
177 this.customize_setup();
180 edit: this.$('button[data-action=edit]'),
181 save: this.$('button[data-action=save]'),
182 cancel: this.$('button[data-action=cancel]'),
185 this.rte = new website.RTE(this);
186 this.rte.on('change', this, this.proxy('rte_changed'));
189 this._super.apply(this, arguments),
190 this.rte.prependTo(this.$('#website-top-edit .nav.pull-right'))
195 this.$buttons.edit.prop('disabled', true);
196 this.$('#website-top-view').hide();
197 this.$('#website-top-edit').show();
198 $('.css_non_editable_mode_hidden').removeClass("css_non_editable_mode_hidden");
200 var $editables = $('[data-oe-model]')
202 // FIXME: propagation should make "meta" blocks non-editable in the first place...
203 .not('.oe_snippets,.oe_snippet, .oe_snippet *')
204 .prop('contentEditable', true)
205 .addClass('oe_editable');
206 var $rte_ables = $editables.not('[data-oe-type]');
207 var $raw_editables = $editables.not($rte_ables);
209 // temporary: on raw editables, links are still active so an
210 // editable link, containing a link or within a link becomes very
211 // hard to edit. Disable linking for these.
212 $raw_editables.parents('a')
213 .add($raw_editables.find('a'))
214 .on('click', function (e) {
218 this.rte.start_edition($rte_ables);
219 $raw_editables.each(function () {
220 observer.observe(this, OBSERVER_CONFIG);
221 }).one('content_changed', function () {
222 $(this).addClass('oe_dirty');
226 rte_changed: function () {
227 this.$buttons.save.prop('disabled', false);
232 observer.disconnect();
233 $('.oe_dirty').each(function (i, v) {
235 // TODO: Add a queue with concurrency limit in webclient
236 // https://github.com/medikoo/deferred/blob/master/lib/ext/function/gate.js
237 var def = self.saving_mutex.exec(function () {
238 return self.saveElement($el).then(function () {
239 $el.removeClass('oe_dirty');
240 }).fail(function () {
241 var data = $el.data();
242 console.error(_.str.sprintf('Could not save %s#%d#%s', data.oeModel, data.oeId, data.oeField));
247 return $.when.apply(null, defs).then(function () {
248 window.location.href = window.location.href.replace(/unable_editor(=[^&]*)?|#.*/g, '');
251 saveElement: function ($el) {
252 var data = $el.data();
253 var html = $el.html();
254 var xpath = data.oeXpath;
256 var $w = $el.clone();
257 $w.removeClass('oe_dirty');
258 _.each(['model', 'id', 'field', 'xpath'], function(d) {$w.removeAttr('data-oe-' + d);});
260 .removeClass('oe_editable')
261 .prop('contentEditable', false);
262 html = $w.wrap('<div>').parent().html();
264 return openerp.jsonRpc('/web/dataset/call', 'call', {
267 args: [data.oeModel, data.oeId, data.oeField, html, xpath, website.get_context()]
270 cancel: function () {
271 window.location.href = window.location.href.replace(/unable_editor(=[^&]*)?|#.*/g, '');
275 /* ----- RICH TEXT EDITOR ---- */
276 website.RTE = openerp.Widget.extend({
278 id: 'oe_rte_toolbar',
279 className: 'oe_right oe_rte_toolbar',
280 // editor.ui.items -> possible commands &al
281 // editor.applyStyle(new CKEDITOR.style({element: "span",styles: {color: "#(color)"},overrides: [{element: "font",attributes: {color: null}}]}, {color: '#ff0000'}));
283 init: function (EditorBar) {
284 this.EditorBar = EditorBar;
285 this._super.apply(this, arguments);
288 start_edition: function ($elements) {
291 .not('span, [data-oe-type]')
295 var editor = CKEDITOR.inline(this, self._config());
296 editor.on('instanceReady', function () {
297 self.trigger('instanceReady');
298 observer.observe(node, OBSERVER_CONFIG);
300 $node.one('content_changed', function () {
301 $node.addClass('oe_dirty');
302 self.trigger('change');
307 _current_editor: function () {
308 return CKEDITOR.currentInstance;
310 _config: function () {
311 var removed_plugins = [
312 // remove custom context menu
313 'contextmenu,tabletools,liststyle',
314 // magicline captures mousein/mouseout => draggable does not work
318 // Disable auto-generated titles
319 // FIXME: accessibility, need to generate user-sensible title, used for @title and @aria-label
321 removePlugins: removed_plugins.join(','),
323 // Ensure no config file is loaded
326 allowedContent: true,
327 // Don't insert paragraphs around content in e.g. <li>
328 autoParagraph: false,
329 filebrowserImageUploadUrl: "/website/attach",
330 // Support for sharedSpaces in 4.x
331 extraPlugins: 'sharedspace,customdialogs,tablebutton',
332 // Place toolbar in controlled location
333 sharedSpaces: { top: 'oe_rte_toolbar' },
335 name: 'clipboard', items: [
338 name: 'basicstyles', items: [
339 "Bold", "Italic", "Underline", "Strike", "Subscript",
340 "Superscript", "TextColor", "BGColor", "RemoveFormat"
342 name: 'span', items: [
343 "Link", "Unlink", "Blockquote", "BulletedList",
344 "NumberedList", "Indent", "Outdent"
346 name: 'justify', items: [
347 "JustifyLeft", "JustifyCenter", "JustifyRight", "JustifyBlock"
349 name: 'special', items: [
350 "Image", "TableButton"
352 name: 'styles', items: [
356 // styles dropdown in toolbar
358 {name: "Normal", element: 'p'},
359 {name: "Heading 1", element: 'h1'},
360 {name: "Heading 2", element: 'h2'},
361 {name: "Heading 3", element: 'h3'},
362 {name: "Heading 4", element: 'h4'},
363 {name: "Heading 5", element: 'h5'},
364 {name: "Heading 6", element: 'h6'},
365 {name: "Formatted", element: 'pre'},
366 {name: "Address", element: 'address'},
368 {name: "Muted", element: 'span', attributes: {'class': 'text-muted'}},
369 {name: "Primary", element: 'span', attributes: {'class': 'text-primary'}},
370 {name: "Warning", element: 'span', attributes: {'class': 'text-warning'}},
371 {name: "Danger", element: 'span', attributes: {'class': 'text-danger'}},
372 {name: "Success", element: 'span', attributes: {'class': 'text-success'}},
373 {name: "Info", element: 'span', attributes: {'class': 'text-info'}}
379 website.editor = { };
380 website.editor.Dialog = openerp.Widget.extend({
382 'hidden.bs.modal': 'destroy',
383 'click button.save': 'save',
385 init: function (editor) {
387 this.editor = editor;
390 var sup = this._super();
395 this.$el.modal('hide');
399 website.editor.LinkDialog = website.editor.Dialog.extend({
400 template: 'website.editor.dialog.link',
401 events: _.extend({}, website.editor.Dialog.prototype.events, {
402 'change .url-source': function (e) { this.changed($(e.target)); },
403 'mousedown': function (e) {
404 var $target = $(e.target).closest('.list-group-item');
405 if (!$target.length || $target.hasClass('active')) {
406 // clicked outside groups, or clicked in active groups
412 .siblings().removeClass('active')
413 .addBack().removeClass('has-error');
416 init: function (editor) {
418 // url -> name mapping for existing pages
419 this.pages = Object.create(null);
423 if ((element = this.get_selected_link()) && element.hasAttribute('href')) {
424 this.editor.getSelection().selectElement(element);
426 this.element = element;
429 this.fetch_pages().done(this.proxy('fill_pages')),
431 ).done(this.proxy('bind_data'));
434 * Greatly simplified version of CKEDITOR's
435 * plugins.link.dialogs.link.onOk.
437 * @param {String} url
438 * @param {Boolean} [new_window=false]
439 * @param {String} [label=null]
441 make_link: function (url, new_window, label) {
442 var attributes = {href: url, 'data-cke-saved-href': url};
445 attributes['target'] = '_blank';
447 to_remove.push('target');
451 this.element.setAttributes(attributes);
452 this.element.removeAttributes(to_remove);
454 var selection = this.editor.getSelection();
455 var range = selection.getRanges(true)[0];
457 if (range.collapsed) {
458 var text = new CKEDITOR.dom.text(label || url);
459 range.insertNode(text);
460 range.selectNodeContents(text);
464 type: CKEDITOR.STYLE_INLINE,
466 attributes: attributes,
467 }).applyToRange(range);
469 // focus dance between RTE & dialog blow up the stack in Safari
470 // and Chrome, so defer select() until dialog has been closed
471 setTimeout(function () {
477 var self = this, _super = this._super.bind(this);
478 var $e = this.$('.list-group-item.active .url-source');
481 $e.closest('.form-group').addClass('has-error');
486 if ($e.hasClass('email-address')) {
487 this.make_link('mailto:' + val, false, val);
488 } else if ($e.hasClass('existing')) {
489 self.make_link(val, false, this.pages[val]);
490 } else if ($e.hasClass('pages')) {
491 // Create the page, get the URL back
492 done = $.get(_.str.sprintf(
493 '/pagenew/%s?noredirect', encodeURIComponent(val)))
494 .then(function (response) {
495 self.make_link(response, false, val);
498 this.make_link(val, this.$('input.window-new').prop('checked'));
502 bind_data: function () {
503 var href = this.element && (this.element.data( 'cke-saved-href')
504 || this.element.getAttribute('href'));
505 if (!href) { return; }
508 if (match = /(mailto):(.+)/.exec(href)) {
509 $control = this.$('input.email-address').val(match[2]);
510 } else if(href in this.pages) {
511 $control = this.$('select.existing').val(href);
514 $control = this.$('input.url').val(href);
517 this.changed($control);
519 this.$('input.window-new').prop(
520 'checked', this.element.getAttribute('target') === '_blank');
522 changed: function ($e) {
523 this.$('.url-source').not($e).val('');
526 * CKEDITOR.plugins.link.getSelectedLink ignores the editor's root,
527 * if the editor is set directly on a link it will thus not work.
529 get_selected_link: function () {
530 var sel = this.editor.getSelection(),
531 el = sel.getSelectedElement();
532 if (el && el.is('a')) { return el; }
534 var range = sel.getRanges(true)[0];
535 if (!range) { return null; }
537 range.shrink(CKEDITOR.SHRINK_TEXT);
538 return this.editor.elementPath(range.getCommonAncestor())
542 fetch_pages: function () {
543 return openerp.jsonRpc('/web/dataset/call_kw', 'call', {
545 method: 'list_pages',
548 context: website.get_context()
552 fill_pages: function (results) {
554 var pages = this.$('select.existing')[0];
555 _(results).each(function (result) {
556 self.pages[result.url] = result.name;
558 pages.options[pages.options.length] =
559 new Option(result.name, result.url);
563 website.editor.ImageDialog = website.editor.Dialog.extend({
564 template: 'website.editor.dialog.image',
565 events: _.extend({}, website.editor.Dialog.prototype.events, {
566 'change .url-source': function (e) { this.changed($(e.target)); },
567 'click button.filepicker': function () {
568 this.$('input[type=file]').click();
570 'change input[type=file]': 'file_selection',
571 'change input.url': 'preview_image',
572 'click .existing-attachments a': 'select_existing',
575 var selection = this.editor.getSelection();
576 var el = selection && selection.getSelectedElement();
578 if (el && el.is('img')) {
580 this.set_image(el.getAttribute('src'));
585 this.fetch_existing().then(this.proxy('fetched_existing')));
588 var url = this.$('input.url').val();
589 var element, editor = this.editor;
590 if (!(element = this.element)) {
591 element = editor.document.createElement('img');
592 // focus event handler interactions between bootstrap (modal)
593 // and ckeditor (RTE) lead to blowing the stack in Safari and
594 // Chrome (but not FF) when this is done synchronously =>
595 // defer insertion so modal has been hidden & destroyed before
597 setTimeout(function () {
598 editor.insertElement(element);
601 element.setAttribute('src', url);
606 * Sets the provided image url as the dialog's value-to-save and
607 * refreshes the preview element to use it.
609 set_image: function (url) {
610 this.$('input.url').val(url);
611 this.preview_image();
614 file_selection: function (e) {
615 this.$('button.filepicker').removeClass('btn-danger btn-success');
618 var callback = _.uniqueId('func_');
619 this.$('input[name=func]').val(callback);
621 window[callback] = function (url, error) {
622 delete window[callback];
623 self.file_selected(url, error);
625 this.$('form').submit();
627 file_selected: function(url, error) {
628 var $button = this.$('button.filepicker');
630 $button.addClass('btn-danger');
633 $button.addClass('btn-success');
636 preview_image: function () {
637 var image = this.$('input.url').val();
638 if (!image) { return; }
640 this.$('img.image-preview').attr('src', image);
643 fetch_existing: function () {
644 // FIXME: lazy load attachments?
645 return openerp.jsonRpc('/web/dataset/call_kw', 'call', {
646 model: 'ir.attachment',
647 method: 'search_read',
651 domain: [['res_model', '=', 'ir.ui.view']],
653 context: website.get_context(),
657 fetched_existing: function (records) {
658 // Create rows of 3 records
659 var rows = _(records).chain()
660 .groupBy(function (_, index) { return Math.floor(index / 3); })
663 this.$('.existing-attachments').replaceWith(
664 openerp.qweb.render('website.editor.dialog.image.existing', {rows: rows}));
666 select_existing: function (e) {
668 this.set_image(e.currentTarget.getAttribute('href'));
673 var Observer = window.MutationObserver || window.WebkitMutationObserver || window.JsMutationObserver;
674 var OBSERVER_CONFIG = {
679 attributeOldValue: true,
681 var observer = new Observer(function (mutations) {
682 // NOTE: Webkit does not fire DOMAttrModified => webkit browsers
683 // relying on JsMutationObserver shim (Chrome < 18, Safari < 6)
684 // will not mark dirty on attribute changes (@class, img/@src,
687 .filter(function (m) {
689 case 'attributes': // ignore .cke_focus being added or removed
690 // if attribute is not a class, can't be .cke_focus change
691 if (m.attributeName !== 'class') { return true; }
693 // find out what classes were added or removed
694 var oldClasses = m.oldValue.split(/\s+/);
695 var newClasses = m.target.className.split(/\s+/);
696 var change = _.union(_.difference(oldClasses, newClasses),
697 _.difference(newClasses, oldClasses));
698 // ignore mutation if the *only* change is .cke_focus
699 return change.length !== 1 || change[0] === 'cke_focus';
701 // <br type="_moz"> appears when focusing RTE in FF, ignore
702 return m.addedNodes.length !== 1 || m.addedNodes[0].nodeName !== 'BR';
709 while (node && !$(node).hasClass('oe_editable')) {
710 node = node.parentNode;
716 .each(function (node) { $(node).trigger('content_changed'); })