edit/page: common retrieval of contents element
[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
32                                 var data = 'body='+encodeURIComponent(body);
33                                 var ajaxpost = new XMLHttpRequest();
34                                 ajaxpost.open('POST', '/edit/page'+pagename, true);
35                                 ajaxpost.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
36                                 ajaxpost.onreadystatechange = function () {
37                                         if (ajaxpost.readyState != 4)
38                                                 return; // not done yet
39                                         if (ajaxpost.status == 200) {
40                                                 editor.resetDirty();
41                                                 new CKEDITOR.plugins.notification(editor, {
42                                                         message: 'Pagina is succesvol opgeslagen',
43                                                         type: 'success',
44                                                 }).show();
45                                         }
46                                         else {
47                                                 new CKEDITOR.plugins.notification(editor, {
48                                                         message: 'Foutcode '+ajaxpost.status+' bij opslaan: '+ajaxpost.responseText,
49                                                         type: 'warning',
50                                                 }).show();
51                                         }
52                                 };
53                                 ajaxpost.send(data);
54                         },
55                 });
56                 editor.setKeystroke(CKEDITOR.CTRL + 83 /*S*/, 'inlinesave');
57                 editor.ui.addButton( 'Inlinesave', {
58                         command: 'inlinesave',
59                         label: editor.lang.save.toolbar,
60                         icon: 'save',
61                 });
62         }
63 });
64
65 CKEDITOR.on('dialogDefinition', function (event) {
66         switch (event.data.name) {
67         case 'table':
68                 // override initial attribute values
69                 var infotab = event.data.definition.getContents('info');
70                 infotab.remove('txtWidth');
71                 infotab.remove('txtHeight');
72                 infotab.remove('txtBorder');
73                 infotab.remove('txtCellSpace');
74                 infotab.remove('txtCellPad');
75                 infotab.remove('cmbAlign');
76
77                 // horizontal repositioning of existing elements
78                 var hbox = {
79                         id: 'hboxDimensions',
80                         type: 'hbox',
81                         children: [ infotab.get('txtCols'), infotab.get('txtRows') ],
82                 };
83                 infotab.add(hbox, 'selHeaders');
84                 infotab.remove('txtCols');
85                 infotab.remove('txtRows');
86
87                 break;
88         case 'link':
89                 // hide unneeded widgets from the Link Info tab
90                 event.data.definition.getContents('info').get('linkType').hidden = true;
91                 let linktarget = event.data.definition.getContents('target').get('linkTargetType');
92                 linktarget.items = [ linktarget.items[0], linktarget.items[3] ]; // only _blank
93                 break;
94         }
95 });
96
97 CKEDITOR.on('instanceCreated', function (event) {
98         var editor = event.editor;
99         var pastefilter = 'h2 h3 p ul ol li blockquote em i strong b; a[!href]; img[alt,!src]';
100
101         editor.on('paste', function (e) {
102                 var html = e.data.dataValue;
103                 if (!/<[^>]* style="/.test(html) && !/<font/.test(html)) return;
104
105                 // force pasteFilter on contents containing styling attributes
106                 var filter = new CKEDITOR.filter(pastefilter),
107                         fragment = CKEDITOR.htmlParser.fragment.fromHtml(html),
108                         writer = new CKEDITOR.htmlParser.basicWriter();
109                 filter.applyTo(fragment);
110                 fragment.writeHtml(writer);
111                 e.data.dataValue = writer.getHtml();
112         });
113
114         editor.on('configLoaded', function () {
115                 var config = editor.config;
116                 config.language = 'nl';
117                 config.extraPlugins = 'inlinesave,placeholder,image2,uploadimage';
118                 config.format_tags = 'h2;h3;h4;p';
119                 config.allowedContent = true;
120                 config.entities = false; // keep unicode
121                 config.filebrowserImageUploadUrl = '/edit/page?output=ckescript';
122                 config.uploadUrl = '/edit/page?output=ckjson';
123                 config.image2_alignClasses = ['left', 'center', 'right'];
124                 config.image2_disableResizer = true;
125                 config.stylesSet = [
126                         { name: 'Klein', element: 'small' },
127                         { name: 'Zijkant', element: 'span', attributes: { 'class': 'right' } },
128                         { name: 'Attributie', element: 'em', attributes: { 'class': 'right' } },
129                         { name: 'Quote', element: 'q' },
130                         { name: 'Gemarkeerd', element: 'span', styles: { 'background-color': 'Yellow' } },
131
132                         { name: 'Kadertekst', element: 'aside' },
133                         { name: 'Uitgelijnd', element: 'div', attributes: { 'class': 'right' } },
134                         { name: 'Kolom', element: 'div', attributes: { 'class': 'col' } },
135                         { name: 'Waarschuwing', element: 'div', attributes: { 'class': 'warn' } },
136                 ];
137                 config.pasteFilter = pastefilter;
138                 config.contentsCss = document.styleSheets[0].href;
139                 config.toolbar = [
140                         ['Inlinesave', '-', 'Undo', 'Redo'],
141                         ['Format', 'Styles'],
142                         ['Bold', 'Italic', 'Link'],
143                         ['BulletedList', 'NumberedList', 'Blockquote'],
144                         ['Table', 'CreateDiv'],
145                         ['Image', 'HorizontalRule', 'CreatePlaceholder'],
146 //                      ['Sourcedialog'],
147                         ['closebtn'],
148                 ];
149                 config.toolbarCanCollapse = true;
150                 config.floatSpacePreferRight = true;
151                 config.floatSpaceDockedOffsetY = 0;
152                 config.title = false;
153                 config.startupFocus = true;
154
155                 config.disableObjectResizing = true;
156                 document.execCommand('enableObjectResizing', false, false); // workaround in inline mode; ff bug?
157         });
158
159         window.onbeforeunload = function () {
160                 if (editor.checkDirty()) {
161                         return 'Pagina verlaten zonder wijzigingen op te slaan?'; // message ignored in modern browsers
162                 }
163         };
164 });
165
166 if (pagebody) {
167         // add edit link to menu
168         var editlink = document.querySelector('a[href="#edit"]');
169         if (editlink)
170         editlink.onclick = function (e) {
171                 editlink.style.fontWeight = 'bold';
172                 editlink.href = '';
173                 editlink.onclick = undefined;
174                 document.body.replaceChild(pagebody, editorcontents());
175                 pagebody.setAttribute('contenteditable', true);
176                 pagebody.querySelectorAll('[data-dyn]').forEach(function (el) {
177                         let blockname = el.getAttribute('data-dyn');
178                         if (!blockname) {
179                                 el.remove();
180                                 return;
181                         }
182                         el.outerHTML = '[[' + blockname + ']]';
183                 });
184                 CKEDITOR.inline(pagebody, { customConfig: '' });
185                 document.body.className = 'edit';
186                 return false;
187         };
188         if (window.location.hash == '#edit') {
189                 editlink.onclick();
190         }
191 }
192
193 }
194
195 document.addEventListener('DOMContentLoaded', function (e) {
196         pagebody = editorcontents().cloneNode(true);
197         var editorinc = document.createElement('script');
198         editorinc.addEventListener('load', editorsetup);
199         editorinc.src = ckesrc;
200         document.getElementsByTagName('head')[0].appendChild(editorinc);
201 });