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