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