a8aa51ee6489adffb100e214e061c457e52f35b1
[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             if (!qid) return;
12             $wdinput.addClass('wikidata-processing');
13             $.ajax(
14                 '/catalogue/wikidata/' + model + '/' + qid,
15                 {
16                     success: function(result) {
17                         for (att in result) {
18                             let val = result[att];
19                             let $input = $("#id_" + att);
20                             if (val && val != $input.val()) {
21                                 let el = $('<span class="wikidata-hint">');
22                                 if (val.wd) {
23                                     el.on('click', function() {
24                                         set_value_from_wikidata_id(
25                                             $input, val.model, val.wd,
26                                             function() {
27                                                 $(this).remove();
28                                             }
29                                         );
30                                     });
31                                     el.text(val.label);
32                                 } else {
33                                     el.on('click', function() {
34                                         $input.val(val);
35                                         $(this).remove();
36                                     });
37                                     el.text(val);
38                                 }
39                                 $input.parent().append(el);
40                             }
41                         };
42
43                     },
44                     complete: function() {
45                         $wdinput.removeClass('wikidata-processing');
46                     },
47                 }
48             );
49         }
50
51         function set_value_from_wikidata_id($input, model, wikidata_id, callback) {
52             $.post({
53                 url: '/catalogue/wikidata/' + model + '/' + wikidata_id,
54                 data: {
55                     csrfmiddlewaretoken: $('[name=csrfmiddlewaretoken]').val(),
56                 },
57                 success: function(result) {
58                     $input.val(result.id);
59                     callback();
60                 },
61             })
62         }
63     });
64 })(jQuery);