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