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