2ba5a1c90971f11b7422d71384acba321eceb20a
[redakcja.git] / src / catalogue / static / catalogue / wikidata_admin.js
1 (function($) {
2     $(function() {
3     
4         let model = $('body').attr('class').match(/model-([^\s]*)/)[1];
5         $("#id_wikidata").each(show_wikidata_hints).on('change', show_wikidata_hints);
6
7         function show_wikidata_hints() {
8             $(".wikidata-hint").remove();
9             $wdinput = $(this);
10             let qid = $wdinput.val();
11             $wdinput.addClass('wikidata-processing');
12             $.ajax(
13                 '/catalogue/wikidata/' + model + '/' + qid,
14                 {
15                     success: function(result) {
16                         for (att in result) {
17                             let val = result[att];
18                             let $input = $("#id_" + att);
19                             if (val && val != $input.val()) {
20                                 let el = $('<span class="wikidata-hint">');
21                                 if (val.wd) {
22                                     el.on('click', function() {
23                                         set_value_from_wikidata_id(
24                                             $input, val.model, val.wd,
25                                             function() {
26                                                 $(this).remove();
27                                             }
28                                         );
29                                     });
30                                     el.text(val.label);
31                                 } else {
32                                     el.on('click', function() {
33                                         $input.val(val);
34                                         $(this).remove();
35                                     });
36                                     el.text(val);
37                                 }
38                                 $input.parent().append(el);
39                             }
40                         };
41
42                         $wdinput.removeClass('wikidata-processing');
43                     },
44                 }
45             );
46         }
47
48         function set_value_from_wikidata_id($input, model, wikidata_id, callback) {
49             $.post({
50                 url: '/catalogue/wikidata/' + model + '/' + wikidata_id,
51                 data: {
52                     csrfmiddlewaretoken: $('[name=csrfmiddlewaretoken]').val(),
53                 },
54                 success: function(result) {
55                     $input.val(result.id);
56                     callback();
57                 },
58             })
59         }
60     });
61 })(jQuery);