Partpicker: key-events auch in chrome getestet
[kivitendo-erp.git] / js / autocomplete_part.js
1 namespace('kivi', function(k){
2   k.PartPicker = function($real, options) {
3     // short circuit in case someone double inits us
4     if ($real.data("part_picker"))
5       return $real.data("part_picker");
6
7     var KEY = {
8       ESCAPE: 27,
9       ENTER:  13,
10       TAB:    9,
11     };
12     var o = $.extend({
13       limit: 20,
14       delay: 50,
15     }, options);
16     var STATES = {
17       UNIQUE: 1,
18       UNDEFINED: 0,
19     }
20     var real_id = $real.attr('id');
21     var $dummy  = $('#' + real_id + '_name');
22     var $type   = $('#' + real_id + '_type');
23     var $unit   = $('#' + real_id + '_unit');
24     var $convertible_unit = $('#' + real_id + '_convertible_unit');
25     var $column = $('#' + real_id + '_column');
26     var state   = STATES.PICKED;
27     var last_real = $real.val();
28     var last_dummy = $dummy.val();
29     var open_dialog = function(){
30       open_jqm_window({
31         url: 'controller.pl?action=Part/part_picker_search',
32         data: $.extend({
33           real_id: real_id,
34         }, ajax_data($dummy.val())),
35         id: 'part_selection',
36       });
37       return true;
38     };
39
40     function ajax_data(term) {
41       var data = {
42         'filter.all:substr::ilike': term,
43         'filter.obsolete': 0,
44         'filter.unit_obj.convertible_to': $convertible_unit && $convertible_unit.val() ? $convertible_unit.val() : '',
45         column:   $column && $column.val() ? $column.val() : '',
46         current:  $real.val(),
47       };
48
49       if ($type && $type.val())
50         data['filter.type'] = $type.val().split(',');
51
52       if ($unit && $unit.val())
53         data['filter.unit'] = $unit.val().split(',');
54
55       return data;
56     }
57
58     function set_item (item) {
59       if (item.id) {
60         $real.val(item.id);
61         // autocomplete ui has name, ajax items have description
62         $dummy.val(item.name ? item.name : item.description);
63       } else {
64         $real.val('');
65         $dummy.val('');
66       }
67       state = STATES.PICKED;
68       last_real = $real.val();
69       last_dummy = $dummy.val();
70       $real.trigger('change');
71     }
72
73     function make_defined_state () {
74       if (state == STATES.PICKED)
75         return true
76       else if (state == STATES.UNDEFINED && $dummy.val() == '')
77         set_item({})
78       else
79         set_item({ id: last_real, name: last_dummy })
80     }
81
82     function update_results () {
83       $.ajax({
84         url: 'controller.pl?action=Part/part_picker_result',
85         data: $.extend({
86             'real_id': $real.val(),
87         }, ajax_data(function(){ var val = $('#part_picker_filter').val(); return val === undefined ? '' : val })),
88         success: function(data){ $('#part_picker_result').html(data) }
89       });
90     };
91
92     function close_popup() {
93       $('#part_selection').jqmClose()
94     };
95
96     $dummy.autocomplete({
97       source: function(req, rsp) {
98         $.ajax($.extend(o, {
99           url:      'controller.pl?action=Part/ajax_autocomplete',
100           dataType: "json",
101           data:     ajax_data(req.term),
102           success:  function (data){ rsp(data) }
103         }));
104       },
105       select: function(event, ui) {
106         set_item(ui.item);
107       },
108     });
109     /*  In case users are impatient and want to skip ahead:
110      *  Capture <enter> key events and check if it's a unique hit.
111      *  If it is, go ahead and assume it was selected. If it wasn't don't do
112      *  anything so that autocompletion kicks in.  For <tab> don't prevent
113      *  propagation. It would be nice to catch it, but javascript is too stupid
114      *  to fire a tab event later on, so we'd have to reimplement the "find
115      *  next active element in tabindex order and focus it".
116      */
117     /* note:
118      *  event.which does not contain tab events in keypressed in firefox but will report 0
119      *  chrome does not fire keypressed at all on tab or escape
120      *  TODO: users expect tab to work on keydown but enter to trigger on keyup,
121      *        should be handled seperately
122      */
123     $dummy.keydown(function(event){
124       if (event.which == KEY.ENTER || event.which == KEY.TAB) { // enter or tab or tab
125         // if string is empty assume they want to delete
126         if ($dummy.val() == '') {
127           set_item({});
128           return true;
129         } else if (state == STATES.PICKED) {
130           return true;
131         }
132         $.ajax({
133           url: 'controller.pl?action=Part/ajax_autocomplete',
134           dataType: "json",
135           data: $.extend( ajax_data($dummy.val()), { prefer_exact: 1 } ),
136           success: function (data){
137             if (data.length == 1) {
138               set_item(data[0]);
139               if (event.which == KEY.ENTER)
140                 $('#update_button').click();
141             } else if (data.length > 1) {
142              if (event.which == KEY.ENTER)
143                 open_dialog();
144               else
145                 make_defined_state();
146             } else {
147               if (event.which == KEY.TAB)
148                 make_defined_state();
149             }
150           }
151         });
152         if (event.which == KEY.ENTER)
153           return false;
154       } else {
155         state = STATES.UNDEFINED;
156       }
157     });
158
159 //    $dummy.blur(make_defined_state);  // blur triggers also on open_jqm_dialog
160
161     // now add a picker div after the original input
162     var pcont  = $('<span>').addClass('position-absolute');
163     var picker = $('<div>');
164     $dummy.after(pcont);
165     pcont.append(picker);
166     picker.addClass('icon16 CRM--Schnellsuche').click(open_dialog);
167
168     var pp = {
169       real:           function() { return $real },
170       dummy:          function() { return $dummy },
171       type:           function() { return $type },
172       unit:           function() { return $unit },
173       convertible_unit: function() { return $convertible_unit },
174       column:         function() { return $column },
175       update_results: update_results,
176       set_item:       set_item,
177       reset:          make_defined_state,
178       init_results:    function () {
179         $('div.part_picker_part').each(function(){
180           $(this).click(function(){
181             set_item({
182               name: $(this).children('input.part_picker_description').val(),
183               id:   $(this).children('input.part_picker_id').val(),
184             });
185             close_popup();
186             return true;
187           });
188         });
189         $('#part_selection').keydown(function(e){
190            if (e.which == KEY.ESCAPE) {
191              close_popup();
192              $dummy.focus();
193            }
194         });
195       }
196     }
197     $real.data('part_picker', pp);
198     return pp;
199   }
200 });
201
202 $(function(){
203   $('input.part_autocomplete').each(function(i,real){
204     kivi.PartPicker($(real));
205   })
206 });