edit/page: nbsp after initials, not unrelated abbreviations
[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((?:[Dd]hr|[Mm](?:w|e?vr|r|r?ss?)|[A-Z])\.)\s+(?=[A-Zdtv])/g, '$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 + 'S'.charCodeAt(0), '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.removePlugins = 'image,exportpdf'; // conflicts with imag2
123                 config.allowedContent = {
124                         $1: {
125                                 elements: CKEDITOR.dtd,
126                                 attributes: true,
127                                 styles: true,
128                                 classes: true,
129                         },
130                 };
131                 config.disallowedContent = 'img[width,height]';
132                 config.entities = false; // keep unicode
133                 config.filebrowserImageUploadUrl = '/edit/page?output=ckjson';
134                 config.image2_alignClasses = ['left', 'center', 'right'];
135                 config.image2_prefillDimensions = false;
136                 config.image2_disableResizer = true;
137                 config.stylesSet = [
138                         { name: 'Paginakop', element: 'h2' },
139                         { name: 'Paragraafkop', element: 'h3' },
140                         { name: 'Alineakop', element: 'h4' },
141
142                         { name: 'Gerelateerd', element: 'aside' },
143                         { name: 'Voetnoot', element: 'div', attributes: { 'class': 'right' } },
144                         { name: 'Kolom', element: 'div', attributes: { 'class': 'col' } },
145                         { name: 'Navigatie', element: 'p', attributes: { 'class': 'nav' } },
146                         { name: 'Waarschuwing', element: 'div', attributes: { 'class': 'warn' } },
147
148                         { name: 'Klein', element: 'small' },
149                         { name: 'Aanhaling', element: 'q' },
150                         { name: 'Doorstreept', element: 's' },
151                         { name: 'Gemarkeerd', element: 'mark' },
152                         { name: 'Rechts', element: 'span', attributes: { 'class': 'right' } },
153                         { name: 'Attributie', element: 'em', attributes: { 'class': 'right' } },
154                         { name: 'Ingelogd', element: 'span', attributes: { 'class': 'login' } },
155                         { name: 'Uitgelogd', element: 'span', attributes: { 'class': 'logout' } },
156                 ];
157                 config.pasteFilter = pastefilter;
158                 config.contentsCss = [...document.styleSheets].map(e => e.href).filter(Boolean);
159                 config.toolbar = [
160                         ['Inlinesave', '-', 'Undo', 'Redo'],
161                         ['Styles', 'Bold', 'Italic', 'Link'],
162                         ['BulletedList', 'NumberedList', 'Blockquote'],
163                         ['Table', 'CreateDiv'],
164                         ['Image', 'HorizontalRule', 'CreatePlaceholder'],
165 //                      ['Sourcedialog'],
166                         ['closebtn'],
167                 ];
168                 config.toolbarCanCollapse = true;
169                 config.floatSpacePreferRight = true;
170                 config.floatSpaceDockedOffsetY = 0;
171                 config.title = false;
172                 config.startupFocus = true;
173
174                 config.disableObjectResizing = true;
175                 document.execCommand('enableObjectResizing', false, false); // workaround in inline mode; ff bug?
176         });
177
178         window.onbeforeunload = function () {
179                 if (editor.checkDirty()) {
180                         return 'Pagina verlaten zonder wijzigingen op te slaan?'; // message ignored in modern browsers
181                 }
182         };
183 });
184
185 if (pagebody) {
186         // add edit link to menu
187         var editdiv = document.querySelector('header .login > p');
188         if (!editdiv) return;
189         var editlink = editdiv.appendChild(document.createElement('a'));
190         editlink.append('\u270D');
191         editlink.className = 'icon icon-edit';
192         editlink.href = '#edit';
193         editlink.onclick = function (e) {
194                 editlink.style.fontWeight = 'bold';
195                 editlink.href = '';
196                 editlink.onclick = undefined;
197                 document.body.replaceChild(pagebody, editorcontents());
198                 pagebody.setAttribute('contenteditable', true);
199                 pagebody.querySelectorAll('[data-dyn]').forEach(function (el) {
200                         let blockname = el.getAttribute('data-dyn');
201                         if (!blockname) {
202                                 el.remove();
203                                 return;
204                         }
205                         el.outerHTML = '[[' + blockname + ']]';
206                 });
207                 CKEDITOR.inline(pagebody, { customConfig: '' });
208                 document.body.className = 'edit';
209                 return false;
210         };
211         if (window.location.hash == '#edit') {
212                 editlink.onclick();
213         }
214 }
215
216 }
217
218 var ckesrc = document.currentScript.getAttribute('data-ckesrc');
219 document.addEventListener('DOMContentLoaded', function (e) {
220         pagebody = editorcontents();
221         if (!pagebody) return;
222         pagebody = pagebody.cloneNode(true);
223         var editorinc = document.createElement('script');
224         editorinc.addEventListener('load', editorsetup);
225         editorinc.src = ckesrc;
226         document.getElementsByTagName('head')[0].appendChild(editorinc);
227 });