1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
|
odoo.define('web.SearchBar', function (require) {
"use strict";
const Domain = require('web.Domain');
const field_utils = require('web.field_utils');
const { useAutofocus } = require('web.custom_hooks');
const { useModel } = require('web/static/src/js/model.js');
const CHAR_FIELDS = ['char', 'html', 'many2many', 'many2one', 'one2many', 'text'];
const { Component, hooks } = owl;
const { useExternalListener, useRef, useState } = hooks;
let sourceId = 0;
/**
* Search bar
*
* This component has two main roles:
* 1) Display the current search facets
* 2) Create new search filters using an input and an autocompletion values
* generator.
*
* For the first bit, the core logic can be found in the XML template of this
* component, searchfacet components or in the ControlPanelModel itself.
*
* The autocompletion mechanic works with transient subobjects called 'sources'.
* Sources contain the information that will be used to generate new search facets.
* A source is generated either:
* a. From an undetermined user input: the user will give a string and select
* a field from the autocompletion dropdown > this will search the selected
* field records with the given pattern (with an 'ilike' operator);
* b. From a given selection: when given an input by the user, the searchbar
* will pre-fetch 'many2one' field records matching the input value and filter
* 'select' fields with the same value. If the user clicks on one of these
* fetched/filtered values, it will generate a matching search facet targeting
* records having this exact value.
* @extends Component
*/
class SearchBar extends Component {
constructor() {
super(...arguments);
this.focusOnUpdate = useAutofocus();
this.inputRef = useRef('search-input');
this.model = useModel('searchModel');
this.state = useState({
sources: [],
focusedItem: 0,
inputValue: "",
});
this.autoCompleteSources = this.model.get('filters', f => f.type === 'field').map(
filter => this._createSource(filter)
);
this.noResultItem = [null, this.env._t("(no result)")];
useExternalListener(window, 'click', this._onWindowClick);
useExternalListener(window, 'keydown', this._onWindowKeydown);
}
mounted() {
// 'search' will always patch the search bar, 'focus' will never.
this.env.searchModel.on('search', this, this.focusOnUpdate);
this.env.searchModel.on('focus-control-panel', this, () => {
this.inputRef.el.focus();
});
}
willUnmount() {
this.env.searchModel.off('search', this);
this.env.searchModel.off('focus-control-panel', this);
}
//---------------------------------------------------------------------
// Private
//---------------------------------------------------------------------
/**
* @private
*/
_closeAutoComplete() {
this.state.sources = [];
this.state.focusedItem = 0;
this.state.inputValue = "";
this.inputRef.el.value = "";
this.focusOnUpdate();
}
/**
* @private
* @param {Object} filter
* @returns {Object}
*/
_createSource(filter) {
const field = this.props.fields[filter.fieldName];
const type = field.type === "reference" ? "char" : field.type;
const source = {
active: true,
description: filter.description,
filterId: filter.id,
filterOperator: filter.operator,
id: sourceId ++,
operator: CHAR_FIELDS.includes(type) ? 'ilike' : '=',
parent: false,
type,
};
switch (type) {
case 'selection': {
source.active = false;
source.selection = field.selection || [];
break;
}
case 'boolean': {
source.active = false;
source.selection = [
[true, this.env._t("Yes")],
[false, this.env._t("No")],
];
break;
}
case 'many2one': {
source.expand = true;
source.expanded = false;
source.context = field.context;
source.relation = field.relation;
if (filter.domain) {
source.domain = filter.domain;
}
}
}
return source;
}
/**
* @private
* @param {Object} source
* @param {[any, string]} values
* @param {boolean} [active=true]
*/
_createSubSource(source, [value, label], active = true) {
const subSource = {
active,
filterId: source.filterId,
filterOperator: source.filterOperator,
id: sourceId ++,
label,
operator: '=',
parent: source,
value,
};
return subSource;
}
/**
* @private
* @param {Object} source
* @param {boolean} shouldExpand
*/
async _expandSource(source, shouldExpand) {
source.expanded = shouldExpand;
if (shouldExpand) {
let args = source.domain;
if (typeof args === 'string') {
try {
args = Domain.prototype.stringToArray(args);
} catch (err) {
args = [];
}
}
const results = await this.rpc({
kwargs: {
args,
context: source.context,
limit: 8,
name: this.state.inputValue.trim(),
},
method: 'name_search',
model: source.relation,
});
const options = results.map(result => this._createSubSource(source, result));
const parentIndex = this.state.sources.indexOf(source);
if (!options.length) {
options.push(this._createSubSource(source, this.noResultItem, false));
}
this.state.sources.splice(parentIndex + 1, 0, ...options);
} else {
this.state.sources = this.state.sources.filter(src => src.parent !== source);
}
}
/**
* @private
* @param {string} query
*/
_filterSources(query) {
return this.autoCompleteSources.reduce(
(sources, source) => {
// Field selection or boolean.
if (source.selection) {
const options = [];
source.selection.forEach(result => {
if (fuzzy.test(query, result[1].toLowerCase())) {
options.push(this._createSubSource(source, result));
}
});
if (options.length) {
sources.push(source, ...options);
}
// Any other type.
} else if (this._validateSource(query, source)) {
sources.push(source);
}
// Fold any expanded item.
if (source.expanded) {
source.expanded = false;
}
return sources;
},
[]
);
}
/**
* Focus the search facet at the designated index if any.
* @private
*/
_focusFacet(index) {
const facets = this.el.getElementsByClassName('o_searchview_facet');
if (facets.length) {
facets[index].focus();
}
}
/**
* Try to parse the given rawValue according to the type of the given
* source field type. The returned formatted value is the one that will
* supposedly be sent to the server.
* @private
* @param {string} rawValue
* @param {Object} source
* @returns {string}
*/
_parseWithSource(rawValue, { type }) {
const parser = field_utils.parse[type];
let parsedValue;
switch (type) {
case 'date':
case 'datetime': {
const parsedDate = parser(rawValue, { type }, { timezone: true });
const dateFormat = type === 'datetime' ? 'YYYY-MM-DD HH:mm:ss' : 'YYYY-MM-DD';
const momentValue = moment(parsedDate, dateFormat);
if (!momentValue.isValid()) {
throw new Error('Invalid date');
}
parsedValue = parsedDate.toJSON();
break;
}
case 'many2one': {
parsedValue = rawValue;
break;
}
default: {
parsedValue = parser(rawValue);
}
}
return parsedValue;
}
/**
* @private
* @param {Object} source
*/
_selectSource(source) {
// Inactive sources are:
// - Selection sources
// - "no result" items
if (source.active) {
const labelValue = source.label || this.state.inputValue;
this.model.dispatch('addAutoCompletionValues', {
filterId: source.filterId,
value: "value" in source ? source.value : this._parseWithSource(labelValue, source),
label: labelValue,
operator: source.filterOperator || source.operator,
});
}
this._closeAutoComplete();
}
/**
* @private
* @param {string} query
* @param {Object} source
* @returns {boolean}
*/
_validateSource(query, source) {
try {
this._parseWithSource(query, source);
} catch (err) {
return false;
}
return true;
}
//---------------------------------------------------------------------
// Handlers
//---------------------------------------------------------------------
/**
* @private
* @param {Object} facet
* @param {number} facetIndex
* @param {KeyboardEvent} ev
*/
_onFacetKeydown(facet, facetIndex, ev) {
switch (ev.key) {
case 'ArrowLeft':
if (facetIndex === 0) {
this.inputRef.el.focus();
} else {
this._focusFacet(facetIndex - 1);
}
break;
case 'ArrowRight':
const facets = this.el.getElementsByClassName('o_searchview_facet');
if (facetIndex === facets.length - 1) {
this.inputRef.el.focus();
} else {
this._focusFacet(facetIndex + 1);
}
break;
case 'Backspace':
this._onFacetRemove(facet);
break;
}
}
/**
* @private
* @param {Object} facet
*/
_onFacetRemove(facet) {
this.model.dispatch('deactivateGroup', facet.groupId);
}
/**
* @private
* @param {KeyboardEvent} ev
*/
_onSearchKeydown(ev) {
if (ev.isComposing) {
// This case happens with an IME for example: we let it handle all key events.
return;
}
const currentItem = this.state.sources[this.state.focusedItem] || {};
switch (ev.key) {
case 'ArrowDown':
ev.preventDefault();
if (Object.keys(this.state.sources).length) {
let nextIndex = this.state.focusedItem + 1;
if (nextIndex >= this.state.sources.length) {
nextIndex = 0;
}
this.state.focusedItem = nextIndex;
} else {
this.env.bus.trigger('focus-view');
}
break;
case 'ArrowLeft':
if (currentItem.expanded) {
// Priority 1: fold expanded item.
ev.preventDefault();
this._expandSource(currentItem, false);
} else if (currentItem.parent) {
// Priority 2: focus parent item.
ev.preventDefault();
this.state.focusedItem = this.state.sources.indexOf(currentItem.parent);
// Priority 3: Do nothing (navigation inside text).
} else if (ev.target.selectionStart === 0) {
// Priority 4: navigate to rightmost facet.
this._focusFacet(this.model.get("facets").length - 1);
}
break;
case 'ArrowRight':
if (ev.target.selectionStart === this.state.inputValue.length) {
// Priority 1: Do nothing (navigation inside text).
if (currentItem.expand) {
// Priority 2: go to first child or expand item.
ev.preventDefault();
if (currentItem.expanded) {
this.state.focusedItem ++;
} else {
this._expandSource(currentItem, true);
}
} else if (ev.target.selectionStart === this.state.inputValue.length) {
// Priority 3: navigate to leftmost facet.
this._focusFacet(0);
}
}
break;
case 'ArrowUp':
ev.preventDefault();
let previousIndex = this.state.focusedItem - 1;
if (previousIndex < 0) {
previousIndex = this.state.sources.length - 1;
}
this.state.focusedItem = previousIndex;
break;
case 'Backspace':
if (!this.state.inputValue.length) {
const facets = this.model.get("facets");
if (facets.length) {
this._onFacetRemove(facets[facets.length - 1]);
}
}
break;
case 'Enter':
if (!this.state.inputValue.length) {
this.model.dispatch('search');
break;
}
/* falls through */
case 'Tab':
if (this.state.inputValue.length) {
ev.preventDefault(); // keep the focus inside the search bar
this._selectSource(currentItem);
}
break;
case 'Escape':
if (this.state.sources.length) {
this._closeAutoComplete();
}
break;
}
}
/**
* @private
* @param {InputEvent} ev
*/
_onSearchInput(ev) {
this.state.inputValue = ev.target.value;
const wasVisible = this.state.sources.length;
const query = this.state.inputValue.trim().toLowerCase();
if (query.length) {
this.state.sources = this._filterSources(query);
} else if (wasVisible) {
this._closeAutoComplete();
}
}
/**
* Only handled if the user has moved its cursor at least once after the
* results are loaded and displayed.
* @private
* @param {number} resultIndex
*/
_onSourceMousemove(resultIndex) {
this.state.focusedItem = resultIndex;
}
/**
* @private
* @param {MouseEvent} ev
*/
_onWindowClick(ev) {
if (this.state.sources.length && !this.el.contains(ev.target)) {
this._closeAutoComplete();
}
}
/**
* @private
* @param {KeyboardEvent} ev
*/
_onWindowKeydown(ev) {
if (ev.key === 'Escape' && this.state.sources.length) {
ev.preventDefault();
ev.stopPropagation();
this._closeAutoComplete();
}
}
}
SearchBar.defaultProps = {
fields: {},
};
SearchBar.props = {
fields: Object,
};
SearchBar.template = 'web.SearchBar';
return SearchBar;
});
|