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