edit/page: fix ckeditor [json] upload response
[minimedit.git] / edit / page.js
1 var pagebody;
2
3 function editorcontents() {
4         return document.getElementsByClassName('static')[0];
5 }
6
7 function editorsetup() {
8
9 CKEDITOR.disableAutoInline = true;
10
11 CKEDITOR.plugins.add('inlinesave', {
12         init: function(editor) {
13                 editor.addCommand( 'inlinesave', {
14                         exec: function (editor) {
15                                 var pagename = window.location.pathname;
16                                 var body = editor.getData();
17                                 // trim trailing whitespace in non-empty paragraphs
18                                 body = body.replace(/((?!<p>).{3})(?:\s|\u200B)+(?=<\/p>)/g, '$1');
19                                 // empty line is equivalent to a paragraph break
20                                 body = body.replace(/<br \/>\s*<br \/>/g, '<p>');
21                                 // keep names and preceding abbreviations together
22                                 body = body.replace(/\b((?:dhr|mw|me?vr|mr?s?)\.)\s+(?=[A-Z])/ig, '$1&nbsp;');
23                                 // wrap long line after each sentence
24                                 body = body.replace(/^(\t*).{73,}/mg, function (line, indent) {
25                                         var dots = '(?:.{24,72}|.{73,}?)'; // chars before punctuation
26                                         var wrap = new RegExp('('+dots+'[.:!?]) (?=[A-Z(<])', 'g'); // separate lines
27                                         return line.replace(wrap, '$1\n'+indent+'\t');
28                                 });
29                                 // treat standalone placeholders as block elements
30                                 body = body.replace(/<p>(\[\[.*\]\])<\/p>/g, '$1');
31                                 // strip redundant domain in relative urls
32                                 var hostlink = 'https?://' + window.location.hostname.replace(/\W/g, '\\$&');
33                                 hostlink = new RegExp('(<a [^>]*href="|<img [^>]*src=")' + hostlink + '(?=/)', 'gi');
34                                 body = body.replace(hostlink, '$1');
35
36                                 var data = 'body='+encodeURIComponent(body);
37                                 var ajaxpost = new XMLHttpRequest();
38                                 ajaxpost.open('POST', '/edit/page'+pagename, true);
39                                 ajaxpost.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
40                                 ajaxpost.onreadystatechange = function () {
41                                         if (ajaxpost.readyState != 4)
42                                                 return; // not done yet
43                                         if (ajaxpost.status == 200) {
44                                                 editor.resetDirty();
45                                                 new CKEDITOR.plugins.notification(editor, {
46                                                         message: 'Pagina is succesvol opgeslagen',
47                                                         type: 'success',
48                                                 }).show();
49                                         }
50                                         else {
51                                                 new CKEDITOR.plugins.notification(editor, {
52                                                         message: 'Foutcode '+ajaxpost.status+' bij opslaan: '+ajaxpost.responseText,
53                                                         type: 'warning',
54                                                 }).show();
55                                         }
56                                 };
57                                 ajaxpost.send(data);
58                         },
59                 });
60                 editor.setKeystroke(CKEDITOR.CTRL + 83 /*S*/, 'inlinesave');
61                 editor.ui.addButton( 'Inlinesave', {
62                         command: 'inlinesave',
63                         label: editor.lang.save.toolbar,
64                         icon: 'save',
65                 });
66         }
67 });
68
69 CKEDITOR.on('dialogDefinition', function (event) {
70         switch (event.data.name) {
71         case 'table':
72                 // override initial attribute values
73                 var infotab = event.data.definition.getContents('info');
74                 infotab.remove('txtWidth');
75                 infotab.remove('txtHeight');
76                 infotab.remove('txtBorder');
77                 infotab.remove('txtCellSpace');
78                 infotab.remove('txtCellPad');
79                 infotab.remove('cmbAlign');
80
81                 // horizontal repositioning of existing elements
82                 var hbox = {
83                         id: 'hboxDimensions',
84                         type: 'hbox',
85                         children: [ infotab.get('txtCols'), infotab.get('txtRows') ],
86                 };
87                 infotab.add(hbox, 'selHeaders');
88                 infotab.remove('txtCols');
89                 infotab.remove('txtRows');
90
91                 break;
92         case 'link':
93                 // hide unneeded widgets from the Link Info tab
94                 event.data.definition.getContents('info').get('linkType').hidden = true;
95                 let linktarget = event.data.definition.getContents('target').get('linkTargetType');
96                 linktarget.items = [ linktarget.items[0], linktarget.items[3] ]; // only _blank
97                 break;
98         }
99 });
100
101 CKEDITOR.on('instanceCreated', function (event) {
102         var editor = event.editor;
103         var pastefilter = 'h2 h3 p ul ol li blockquote em i strong b; a[!href]; img[alt,!src]';
104
105         editor.on('paste', function (e) {
106                 var html = e.data.dataValue;
107                 if (!/<[^>]* style="/.test(html) && !/<font/.test(html)) return;
108
109                 // force pasteFilter on contents containing styling attributes
110                 var filter = new CKEDITOR.filter(pastefilter),
111                         fragment = CKEDITOR.htmlParser.fragment.fromHtml(html),
112                         writer = new CKEDITOR.htmlParser.basicWriter();
113                 filter.applyTo(fragment);
114                 fragment.writeHtml(writer);
115                 e.data.dataValue = writer.getHtml();
116         });
117
118         editor.on('configLoaded', function () {
119                 var config = editor.config;
120                 config.language = 'nl';
121                 config.extraPlugins = 'inlinesave,placeholder,image2,uploadimage';
122                 config.allowedContent = true;
123                 config.entities = false; // keep unicode
124                 config.filebrowserImageUploadUrl = '/edit/page?output=ckjson';
125                 config.image2_alignClasses = ['left', 'center', 'right'];
126                 config.image2_disableResizer = true;
127                 config.stylesSet = [
128                         { name: 'Paginakop', element: 'h2' },
129                         { name: 'Paragraafkop', element: 'h3' },
130                         { name: 'Alineakop', element: 'h4' },
131
132                         { name: 'Gerelateerd', element: 'aside' },
133                         { name: 'Voetnoot', element: 'div', attributes: { 'class': 'right' } },
134                         { name: 'Kolom', element: 'div', attributes: { 'class': 'col' } },
135                         { name: 'Navigatie', element: 'p', attributes: { 'class': 'nav' } },
136                         { name: 'Waarschuwing', element: 'div', attributes: { 'class': 'warn' } },
137
138                         { name: 'Klein', element: 'small' },
139                         { name: 'Aanhaling', element: 'q' },
140                         { name: 'Doorstreept', element: 's' },
141                         { name: 'Gemarkeerd', element: 'mark' },
142                         { name: 'Rechts', element: 'span', attributes: { 'class': 'right' } },
143                         { name: 'Attributie', element: 'em', attributes: { 'class': 'right' } },
144                         { name: 'Ingelogd', element: 'span', attributes: { 'class': 'login' } },
145                         { name: 'Uitgelogd', element: 'span', attributes: { 'class': 'logout' } },
146                 ];
147                 config.pasteFilter = pastefilter;
148                 config.contentsCss = [...document.styleSheets].map(e => e.href).filter(Boolean);
149                 config.toolbar = [
150                         ['Inlinesave', '-', 'Undo', 'Redo'],
151                         ['Styles', 'Bold', 'Italic', 'Link'],
152                         ['BulletedList', 'NumberedList', 'Blockquote'],
153                         ['Table', 'CreateDiv'],
154                         ['Image', 'HorizontalRule', 'CreatePlaceholder'],
155 //                      ['Sourcedialog'],
156                         ['closebtn'],
157                 ];
158                 config.toolbarCanCollapse = true;
159                 config.floatSpacePreferRight = true;
160                 config.floatSpaceDockedOffsetY = 0;
161                 config.title = false;
162                 config.startupFocus = true;
163
164                 config.disableObjectResizing = true;
165                 document.execCommand('enableObjectResizing', false, false); // workaround in inline mode; ff bug?
166         });
167
168         window.onbeforeunload = function () {
169                 if (editor.checkDirty()) {
170                         return 'Pagina verlaten zonder wijzigingen op te slaan?'; // message ignored in modern browsers
171                 }
172         };
173 });
174
175 if (pagebody) {
176         // add edit link to menu
177         var editdiv = document.querySelector('header .login > p');
178         if (!editdiv) return;
179         var editlink = editdiv.appendChild(document.createElement('a'));
180         editlink.append('\u270D');
181         editlink.className = 'icon icon-edit';
182         editlink.href = '#edit';
183         editlink.onclick = function (e) {
184                 editlink.style.fontWeight = 'bold';
185                 editlink.href = '';
186                 editlink.onclick = undefined;
187                 document.body.replaceChild(pagebody, editorcontents());
188                 pagebody.setAttribute('contenteditable', true);
189                 pagebody.querySelectorAll('[data-dyn]').forEach(function (el) {
190                         let blockname = el.getAttribute('data-dyn');
191                         if (!blockname) {
192                                 el.remove();
193                                 return;
194                         }
195                         el.outerHTML = '[[' + blockname + ']]';
196                 });
197                 CKEDITOR.inline(pagebody, { customConfig: '' });
198                 document.body.className = 'edit';
199                 return false;
200         };
201         if (window.location.hash == '#edit') {
202                 editlink.onclick();
203         }
204 }
205
206 }
207
208 var ckesrc = document.currentScript.getAttribute('data-ckesrc');
209 document.addEventListener('DOMContentLoaded', function (e) {
210         pagebody = editorcontents().cloneNode(true);
211         var editorinc = document.createElement('script');
212         editorinc.addEventListener('load', editorsetup);
213         editorinc.src = ckesrc;
214         document.getElementsByTagName('head')[0].appendChild(editorinc);
215 });