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