Fix caret positioning outside editable.
[redakcja.git] / src / redakcja / static / js / wiki / view_properties.js
1 (function($){
2
3     let w = function() {};
4     w = console.log;
5     
6     const elementDefs = {
7         "ilustr": {
8             "attributes": [
9                 {
10                     "name": "src",
11                     "type": "media",
12                 },
13                 {
14                     "name": "alt",
15                     "type": "text",
16                 },
17                 {
18                     "name": "szer",
19                     "type": "percent",
20                 },
21                 {
22                     "name": "wyrownanie",
23                     "type": "select",
24                     "options": ["lewo", "srodek", "prawo"],
25                 },
26                 {
27                     "name": "oblew",
28                     "type": "bool",
29                 },
30             ],
31         },
32         "ref": {
33             "attributes": [
34                 {
35                     "name": "href",
36                 },
37             ],
38         }
39     };
40
41     function PropertiesPerspective(options) {
42         let oldCallback = options.callback || function() {};
43         this.vsplitbar = 'WŁAŚCIWOŚCI';
44
45         options.callback = function() {
46             let self = this;
47
48             self.$pane = $("#side-properties");
49             
50             $("#simple-editor").on('click', '[x-node]', function(e) {
51                 if (!e.redakcja_edited) {
52                     e.redakcja_edited = true;
53                     self.edit(this);
54                 }
55             });
56
57             self.$pane.on('click', '#parents li', function(e) {
58                 self.edit($(this).data('node'));
59             });
60
61             $(document).on('click', '#bubbles .badge', function(e) {
62                 self.edit($(this).data('node'));
63             });
64
65             self.$pane.on('change', '.form-control', function() {
66                 let $input = $(this);
67
68                 let inputval;
69                 if ($input.attr('type') == 'checkbox') {
70                     inputval = $input.is(':checked');
71                 } else {
72                     inputval = $input.val();
73                 }
74                 
75                 if ($input.data("edited")) {
76                     if ($input.data("edited-attr")) {
77                         $input.data("edited").attr($input.data("edited-attr"), inputval);
78                     } else {
79                         $input.data("edited").text(inputval);
80                     }
81                     return;
82                 }
83                 
84                 html2text({
85                     element: self.$edited[0],
86                     success: function(xml) {
87                         w(222)
88                         let $xmlelem = $($.parseXML(xml));
89                         w(333, $xmlelem)
90                         w($input.data('property'), $input.val());
91                         $xmlelem.contents().attr($input.data('property'), inputval);
92                         w(444, $xmlelem)
93                         let newxml = (new XMLSerializer()).serializeToString($xmlelem[0]);
94                         w(555, newxml)
95                         xml2html({
96                             xml: newxml,
97                             base: self.doc.getBase(),
98                             success: function(html) {
99                                 let htmlElem = $(html);
100                                 self.$edited.replaceWith(htmlElem);
101                                 self.edit(htmlElem);
102                             }
103                         });
104                     },
105                     error: function(e) {console.log(e);},
106                 });
107                 self.$edited;
108             });
109
110             
111             self.$pane.on('click', '.meta-add', function() {
112                 // create a metadata item
113                 let $fg = $(this).parent();
114                 let ns = $fg.data('ns');
115                 let tag = $fg.data('tag');
116                 let field = $fg.data('field');
117                 let span = $('<span/>');
118                 span.attr('x-node', tag);
119                 span.attr('x-ns', ns)
120                 if (field.value_type.hasLanguage) {
121                     span.attr('x-a-xml-lang', 'pl');
122                 }
123
124                 rdf = $("> [x-node='RDF']", self.$edited);
125                 if (!rdf.length) {
126                     rdf = $("<span x-node='RDF' x-ns='http://www.w3.org/1999/02/22-rdf-syntax-ns#'>");
127                     self.$edited.prepend(rdf); 
128                     self.$edited.prepend('\n  ');
129                    
130                 }
131                 rdfdesc = $("> [x-node='Description']", rdf);
132                 if (!rdfdesc.length) {
133                     rdfdesc = $("<span x-node='Description' x-ns='http://www.w3.org/1999/02/22-rdf-syntax-ns#' x-a-rdf-about='" + self.doc.fullUri + "'>");
134                     rdf.prepend(rdfdesc);
135                     rdf.prepend('\n    ');
136                     rdfdesc.append('\n    ');
137                     rdf.append('\n  ');
138                 }
139                 span.appendTo(rdfdesc);
140                 rdfdesc.append('\n    ');
141
142                 self.displayMetaProperty($fg);
143                 
144                 return false;
145             });
146             
147             self.$pane.on('click', '.meta-delete', function() {
148                 let $fg = $(this).closest('.form-group'); 
149                 $('input', $fg).data('edited').remove();
150                 self.displayMetaProperty($fg);
151                 return false;
152             });
153
154
155             $('#media-chooser').on('show.bs.modal', function (event) {
156                 var input = $("input", $(event.relatedTarget).parent());
157                 var modal = $(this);
158                 modal.data('target-input', input);
159                 var imglist = modal.find('.modal-body');
160                 $.each(self.doc.galleryImages, (i, imgItem) => {
161                     img = $("<img>").attr("src", imgItem.thumb).attr('title', imgItem.url).data('url', imgItem.url).on('click', function() {
162                         imglist.find('img').removeClass('active');
163                         $(this).addClass('active');
164                     });
165                     imglist.append(img);
166                 });
167             })
168             $('#media-chooser .ctrl-ok').on('click', function (event) {
169                 $('#media-chooser').data('target-input')
170                     .val(
171                         (new URL($('#media-chooser .active').data('url'), document.baseURI)).href
172                     ).trigger('change');
173                 $('#media-chooser').modal('hide');
174             });
175             
176             self.$pane.on('click', '.current-convert', function() {
177                 self.convert($(this).attr('data-to'));
178             });
179             self.$pane.on('click', '#current-delete', function() {
180                 self.delete();
181             });
182             
183             
184             oldCallback.call(this);
185         };
186
187         $.wiki.SidebarPerspective.call(this, options);
188     }
189
190     PropertiesPerspective.prototype = new $.wiki.SidebarPerspective();
191
192     PropertiesPerspective.prototype.edit = function(element) {
193         let self = this;
194
195         $("#parents", self.$pane).empty();
196         $("#bubbles").empty();
197
198         $f = $("#properties-form", self.$pane);
199         $f.empty();
200
201         if (element === null) {
202             self.$edited = null;
203             return;
204         }
205
206         let $node = $(element);
207         let b = $("<div class='badge badge-primary'></div>").text($node.attr('x-node'));
208         b.data('node', element);
209         $("#bubbles").append(b);
210
211         $node.parents('[x-node]').each(function() {
212             let a = $("<li class='breadcrumb-item'>").text($(this).attr('x-node'));
213             a.data('node', this);
214             $("#parents", self.$pane).prepend(a)
215
216             let b = $("<div class='badge badge-info'></div>").text($(this).attr('x-node'));
217             b.data('node', this);
218             $("#bubbles").append(b);
219         })
220
221         // It's a tag.
222         node = $(element).attr('x-node');
223         $("h1", self.$pane).text(node);
224
225         self.$edited = $(element);
226
227         let nodeDef = elementDefs[node];
228         if (nodeDef && nodeDef.attributes) {
229             $.each(nodeDef.attributes, function(i, a) {
230                 self.addEditField(a, $(element).attr('x-a-wl-' + a.name)); // ...
231             })
232         }
233
234         // Only utwor can has matadata now.
235         if (node == 'utwor') {
236             $('<hr>').appendTo($("#properties-form", self.$pane))
237             META_FIELDS.forEach(function(field) {
238                 let $fg = $("<div class='form-group'>");
239                 $("<label/>").text(field.name).appendTo($fg);
240
241                 // if multiple?
242                 $("<button class='meta-add float-right btn btn-primary'>+</button>").appendTo($fg);
243
244                 let match = field.uri.match(/({(.*)})?(.*)/);
245                 ns = match[2];
246                 tag = match[3];
247
248                 let cont = $('<div class="c">');
249
250                 $fg.data('ns', ns);
251                 $fg.data('tag', tag);
252                 $fg.data('field', field);
253                 cont.appendTo($fg);
254
255                 self.displayMetaProperty($fg);
256
257                 $fg.appendTo( $("#properties-form", self.$pane));
258             });
259         }
260
261         // check node type, find relevant tags
262         if ($node[0].nodeName == 'DIV') {
263             $("#current-convert").attr("data-current-type", "div");
264         } else if ($node[0].nodeName == 'EM') {
265             $("#current-convert").attr("data-current-type", "span");
266         }
267     };
268
269     PropertiesPerspective.prototype.addMetaInput = function(cont, field, element) {
270         let self = this;
271
272         let ig = $('<div class="input-group">');
273         //ig.data('edited', element);
274         ig.appendTo(cont);
275
276         if (field.value_type.hasLanguage) {
277             let pp = $("<div class='input-group-prepend'>");
278             let lang_input = $("<input class='form-control' size='1' class='lang'>");
279             lang_input.data('edited', $(element));
280             lang_input.data('edited-attr', 'x-a-xml-lang');
281             lang_input.val(
282                 $(element).attr('x-a-xml-lang')
283             );
284             lang_input.appendTo(pp);
285             pp.appendTo(ig);
286         }
287
288         let $aninput;
289         if (field.value_type.widget == 'select') {
290             $aninput = $("<select class='form-control'>");
291             $.each(field.value_type.options, function() {
292                 $("<option>").text(this).appendTo($aninput);
293             })
294         } else {
295             $aninput = $("<input class='form-control'>");
296             if (field.value_type.autocomplete) {
297                 let autoOptions = field.value_type.autocomplete;
298                 $aninput.autocomplete(autoOptions).autocomplete('instance')._renderItem = function(ul, item) {
299                     let t = item.label;
300                     if (item.name) t += '<br><small><strong>' + item.name + '</strong></small>';
301                     if (item.description) t += '<br><small><em>' + item.description + '</em></small>';
302                     return $( "<li>" )
303                         .append( "<div>" + t + "</div>" )
304                         .appendTo( ul );
305                 };
306             }
307         }
308         $aninput.data('edited', $(element))
309         $aninput.val(
310             $(element).text()
311         );
312         $aninput.appendTo(ig);
313
314         let ap = $("<div class='input-group-append'>");
315         ap.appendTo(ig);
316         $("<button class='meta-delete btn btn-outline-secondary'>x</button>").appendTo(ap);
317         
318         // lang
319     };
320     
321
322     PropertiesPerspective.prototype.displayMetaProperty = function($fg) {
323         let self = this;
324         let ns = $fg.data('ns');
325         let tag = $fg.data('tag');
326         let field = $fg.data('field');
327
328         //  clear container
329         $('.c', $fg).empty();
330
331         let selector = "> [x-node='RDF'] > [x-node='Description'] > [x-node='"+tag+"']";
332         if (ns) {
333             selector += "[x-ns='"+ns+"']";
334         }
335         $(selector, self.$edited).each(function() {
336             self.addMetaInput(
337                 $('.c', $fg),
338                 field,
339                 this);
340         });
341
342         count = $('.c > .input-group', $fg).length;
343         if (field.required) {
344             if (!count) {
345                 $('<div class="text-warning">WYMAGANE</div>').appendTo($('.c', $fg));
346             }
347         }
348     };
349     
350
351
352     PropertiesPerspective.prototype.addEditField = function(defn, value, elem) {
353         let self = this;
354         let $form = $("#properties-form", self.$pane);
355
356         let $fg = $("<div class='form-group'>");
357         $("<label/>").attr("for", "property-" + defn.name).text(defn.name).appendTo($fg);
358         let $input, $inputCnt;
359         switch (defn.type) {
360         case 'text':
361             $inputCnt =$input = $("<textarea>");
362             break;
363         case 'select':
364             $inputCnt = $input = $("<select>");
365             $.each(defn.options, function(i, e) {
366                 $("<option>").text(e).appendTo($input);
367             });
368             break;
369         case 'bool':
370             $inputCnt = $input = $("<input type='checkbox'>");
371             break;
372         case 'media':
373             $inputCnt = $("<div class='media-input input-group'>");
374             $input = $("<input type='text'>");
375             $inputCnt.append($input);
376             $inputCnt.append($("<button type='button' class='ctrl-media-choose btn btn-primary' data-toggle='modal' data-target='#media-chooser'>…</button>"));
377             break;
378         default:
379             $inputCnt = $input = $("<input>");
380         }
381
382         $input.addClass("form-control").attr("id", "property-" + defn.name).data("property", defn.name);
383         if ($input.attr('type') == 'checkbox') {
384             $input.prop('checked', value == 'true');
385         } else {
386             $input.val(value);
387         }
388         
389         if (elem) {
390             $input.data("edited", elem);
391         }
392         $inputCnt.appendTo($fg);
393
394         $fg.appendTo($form);
395     }
396
397     PropertiesPerspective.prototype.convert = function(newtag) {
398         this.$edited.attr('x-node', newtag);
399         // TODO: take care of attributes?
400     }
401
402     PropertiesPerspective.prototype.delete = function(newtag) {
403         p = this.$edited.parent();
404         this.$edited.remove();
405         this.edit(p);
406     }
407
408     PropertiesPerspective.prototype.onEnter = function(success, failure){
409         var self = this;
410         $.wiki.SidebarPerspective.prototype.onEnter.call(this);
411
412         if ($.wiki.activePerspective() != 'VisualPerspective')
413             $.wiki.switchToTab('#VisualPerspective');
414
415         if (self.$edited === null) {
416             self.edit($('[x-node="utwor"]')[0]);
417         }
418     };
419
420     $.wiki.PropertiesPerspective = PropertiesPerspective;
421
422 })(jQuery);
423