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