forked from symfony/ux
-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcontroller.js
389 lines (381 loc) · 16.7 KB
/
controller.js
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
import { Controller } from '@hotwired/stimulus';
import TomSelect from 'tom-select';
/******************************************************************************
Copyright (c) Microsoft Corporation.
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
***************************************************************************** */
/* global Reflect, Promise, SuppressedError, Symbol */
function __classPrivateFieldGet(receiver, state, kind, f) {
if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
}
typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {
var e = new Error(message);
return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
};
var _default_1_instances, _default_1_getCommonConfig, _default_1_createAutocomplete, _default_1_createAutocompleteWithHtmlContents, _default_1_createAutocompleteWithRemoteData, _default_1_stripTags, _default_1_mergeObjects, _default_1_createTomSelect;
class default_1 extends Controller {
constructor() {
super(...arguments);
_default_1_instances.add(this);
this.isObserving = false;
this.hasLoadedChoicesPreviously = false;
this.originalOptions = [];
}
initialize() {
if (!this.mutationObserver) {
this.mutationObserver = new MutationObserver((mutations) => {
this.onMutations(mutations);
});
}
}
connect() {
if (this.selectElement) {
this.originalOptions = this.createOptionsDataStructure(this.selectElement);
}
this.initializeTomSelect();
}
initializeTomSelect() {
if (this.selectElement) {
this.selectElement.setAttribute('data-skip-morph', '');
}
if (this.urlValue) {
this.tomSelect = __classPrivateFieldGet(this, _default_1_instances, "m", _default_1_createAutocompleteWithRemoteData).call(this, this.urlValue, this.hasMinCharactersValue ? this.minCharactersValue : null);
return;
}
if (this.optionsAsHtmlValue) {
this.tomSelect = __classPrivateFieldGet(this, _default_1_instances, "m", _default_1_createAutocompleteWithHtmlContents).call(this);
return;
}
this.tomSelect = __classPrivateFieldGet(this, _default_1_instances, "m", _default_1_createAutocomplete).call(this);
this.startMutationObserver();
}
disconnect() {
this.stopMutationObserver();
let currentSelectedValues = [];
if (this.selectElement) {
if (this.selectElement.multiple) {
currentSelectedValues = Array.from(this.selectElement.options)
.filter((option) => option.selected)
.map((option) => option.value);
}
else {
currentSelectedValues = [this.selectElement.value];
}
}
this.tomSelect.destroy();
if (this.selectElement) {
if (this.selectElement.multiple) {
Array.from(this.selectElement.options).forEach((option) => {
option.selected = currentSelectedValues.includes(option.value);
});
}
else {
this.selectElement.value = currentSelectedValues[0];
}
}
}
urlValueChanged() {
this.resetTomSelect();
}
getMaxOptions() {
return this.selectElement ? this.selectElement.options.length : 50;
}
get selectElement() {
if (!(this.element instanceof HTMLSelectElement)) {
return null;
}
return this.element;
}
get formElement() {
if (!(this.element instanceof HTMLInputElement) && !(this.element instanceof HTMLSelectElement)) {
throw new Error('Autocomplete Stimulus controller can only be used on an <input> or <select>.');
}
return this.element;
}
dispatchEvent(name, payload) {
this.dispatch(name, { detail: payload, prefix: 'autocomplete' });
}
get preload() {
if (!this.hasPreloadValue) {
return 'focus';
}
if (this.preloadValue === 'false') {
return false;
}
if (this.preloadValue === 'true') {
return true;
}
return this.preloadValue;
}
resetTomSelect() {
if (this.tomSelect) {
this.dispatchEvent('before-reset', { tomSelect: this.tomSelect });
this.stopMutationObserver();
const currentHtml = this.element.innerHTML;
const currentValue = this.tomSelect.getValue();
this.tomSelect.destroy();
this.element.innerHTML = currentHtml;
this.initializeTomSelect();
this.tomSelect.setValue(currentValue);
}
}
changeTomSelectDisabledState(isDisabled) {
this.stopMutationObserver();
if (isDisabled) {
this.tomSelect.disable();
}
else {
this.tomSelect.enable();
}
this.startMutationObserver();
}
startMutationObserver() {
if (!this.isObserving && this.mutationObserver) {
this.mutationObserver.observe(this.element, {
childList: true,
subtree: true,
attributes: true,
characterData: true,
attributeOldValue: true,
});
this.isObserving = true;
}
}
stopMutationObserver() {
if (this.isObserving && this.mutationObserver) {
this.mutationObserver.disconnect();
this.isObserving = false;
}
}
onMutations(mutations) {
let changeDisabledState = false;
let requireReset = false;
mutations.forEach((mutation) => {
switch (mutation.type) {
case 'attributes':
if (mutation.target === this.element && mutation.attributeName === 'disabled') {
changeDisabledState = true;
break;
}
if (mutation.target === this.element && mutation.attributeName === 'multiple') {
const isNowMultiple = this.element.hasAttribute('multiple');
const wasMultiple = mutation.oldValue === 'multiple';
if (isNowMultiple !== wasMultiple) {
requireReset = true;
}
break;
}
break;
}
});
const newOptions = this.selectElement ? this.createOptionsDataStructure(this.selectElement) : [];
const areOptionsEquivalent = this.areOptionsEquivalent(newOptions);
if (!areOptionsEquivalent || requireReset) {
this.originalOptions = newOptions;
this.resetTomSelect();
}
if (changeDisabledState) {
this.changeTomSelectDisabledState(this.formElement.disabled);
}
}
createOptionsDataStructure(selectElement) {
return Array.from(selectElement.options).map((option) => {
return {
value: option.value,
text: option.text,
};
});
}
areOptionsEquivalent(newOptions) {
const filteredOriginalOptions = this.originalOptions.filter((option) => option.value !== '');
const filteredNewOptions = newOptions.filter((option) => option.value !== '');
const originalPlaceholderOption = this.originalOptions.find((option) => option.value === '');
const newPlaceholderOption = newOptions.find((option) => option.value === '');
if (originalPlaceholderOption &&
newPlaceholderOption &&
originalPlaceholderOption.text !== newPlaceholderOption.text) {
return false;
}
if (filteredOriginalOptions.length !== filteredNewOptions.length) {
return false;
}
const normalizeOption = (option) => `${option.value}-${option.text}`;
const originalOptionsSet = new Set(filteredOriginalOptions.map(normalizeOption));
const newOptionsSet = new Set(filteredNewOptions.map(normalizeOption));
return (originalOptionsSet.size === newOptionsSet.size &&
[...originalOptionsSet].every((option) => newOptionsSet.has(option)));
}
}
_default_1_instances = new WeakSet(), _default_1_getCommonConfig = function _default_1_getCommonConfig() {
const plugins = {};
const isMultiple = !this.selectElement || this.selectElement.multiple;
if (!this.formElement.disabled && !isMultiple) {
plugins.clear_button = { title: '' };
}
if (isMultiple) {
plugins.remove_button = { title: '' };
}
if (this.urlValue) {
plugins.virtual_scroll = {};
}
const render = {
no_results: () => {
return `<div class="no-results">${this.noResultsFoundTextValue}</div>`;
},
option_create: (data, escapeData) => {
return `<div class="create">${this.createOptionTextValue.replace('%placeholder%', `<strong>${escapeData(data.input)}</strong>`)}</div>`;
},
};
const config = {
render,
plugins,
onItemAdd: () => {
this.tomSelect.setTextboxValue('');
},
closeAfterSelect: true,
onOptionAdd: (value, data) => {
let parentElement = this.tomSelect.input;
let optgroupData = null;
const optgroup = data[this.tomSelect.settings.optgroupField];
if (optgroup && this.tomSelect.optgroups) {
optgroupData = this.tomSelect.optgroups[optgroup];
if (optgroupData) {
const optgroupElement = parentElement.querySelector(`optgroup[label="${optgroupData.label}"]`);
if (optgroupElement) {
parentElement = optgroupElement;
}
}
}
const optionElement = document.createElement('option');
optionElement.value = value;
optionElement.text = data[this.tomSelect.settings.labelField];
const optionOrder = data.$order;
let orderedOption = null;
for (const [, tomSelectOption] of Object.entries(this.tomSelect.options)) {
if (tomSelectOption.$order === optionOrder) {
orderedOption = parentElement.querySelector(`:scope > option[value="${tomSelectOption[this.tomSelect.settings.valueField]}"]`);
break;
}
}
if (orderedOption) {
orderedOption.insertAdjacentElement('afterend', optionElement);
}
else if (optionOrder >= 0) {
parentElement.append(optionElement);
}
else {
parentElement.prepend(optionElement);
}
},
};
if (!this.selectElement && !this.urlValue) {
config.shouldLoad = () => false;
}
return __classPrivateFieldGet(this, _default_1_instances, "m", _default_1_mergeObjects).call(this, config, this.tomSelectOptionsValue);
}, _default_1_createAutocomplete = function _default_1_createAutocomplete() {
const config = __classPrivateFieldGet(this, _default_1_instances, "m", _default_1_mergeObjects).call(this, __classPrivateFieldGet(this, _default_1_instances, "m", _default_1_getCommonConfig).call(this), {
maxOptions: this.getMaxOptions(),
});
return __classPrivateFieldGet(this, _default_1_instances, "m", _default_1_createTomSelect).call(this, config);
}, _default_1_createAutocompleteWithHtmlContents = function _default_1_createAutocompleteWithHtmlContents() {
const commonConfig = __classPrivateFieldGet(this, _default_1_instances, "m", _default_1_getCommonConfig).call(this);
const labelField = commonConfig.labelField ?? 'text';
const config = __classPrivateFieldGet(this, _default_1_instances, "m", _default_1_mergeObjects).call(this, commonConfig, {
maxOptions: this.getMaxOptions(),
score: (search) => {
const scoringFunction = this.tomSelect.getScoreFunction(search);
return (item) => {
return scoringFunction({ ...item, text: __classPrivateFieldGet(this, _default_1_instances, "m", _default_1_stripTags).call(this, item[labelField]) });
};
},
render: {
item: (item) => `<div>${item[labelField]}</div>`,
option: (item) => `<div>${item[labelField]}</div>`,
},
});
return __classPrivateFieldGet(this, _default_1_instances, "m", _default_1_createTomSelect).call(this, config);
}, _default_1_createAutocompleteWithRemoteData = function _default_1_createAutocompleteWithRemoteData(autocompleteEndpointUrl, minCharacterLength) {
const commonConfig = __classPrivateFieldGet(this, _default_1_instances, "m", _default_1_getCommonConfig).call(this);
const labelField = commonConfig.labelField ?? 'text';
const config = __classPrivateFieldGet(this, _default_1_instances, "m", _default_1_mergeObjects).call(this, commonConfig, {
firstUrl: (query) => {
const separator = autocompleteEndpointUrl.includes('?') ? '&' : '?';
return `${autocompleteEndpointUrl}${separator}query=${encodeURIComponent(query)}`;
},
load: function (query, callback) {
const url = this.getUrl(query);
fetch(url)
.then((response) => response.json())
.then((json) => {
this.setNextUrl(query, json.next_page);
callback(json.results.options || json.results, json.results.optgroups || []);
})
.catch(() => callback([], []));
},
shouldLoad: (query) => {
if (null !== minCharacterLength) {
return query.length >= minCharacterLength;
}
if (this.hasLoadedChoicesPreviously) {
return true;
}
if (query.length > 0) {
this.hasLoadedChoicesPreviously = true;
}
return query.length >= 3;
},
optgroupField: 'group_by',
score: (search) => (item) => 1,
render: {
option: (item) => `<div>${item[labelField]}</div>`,
item: (item) => `<div>${item[labelField]}</div>`,
loading_more: () => {
return `<div class="loading-more-results">${this.loadingMoreTextValue}</div>`;
},
no_more_results: () => {
return `<div class="no-more-results">${this.noMoreResultsTextValue}</div>`;
},
no_results: () => {
return `<div class="no-results">${this.noResultsFoundTextValue}</div>`;
},
option_create: (data, escapeData) => {
return `<div class="create">${this.createOptionTextValue.replace('%placeholder%', `<strong>${escapeData(data.input)}</strong>`)}</div>`;
},
},
preload: this.preload,
});
return __classPrivateFieldGet(this, _default_1_instances, "m", _default_1_createTomSelect).call(this, config);
}, _default_1_stripTags = function _default_1_stripTags(string) {
return string.replace(/(<([^>]+)>)/gi, '');
}, _default_1_mergeObjects = function _default_1_mergeObjects(object1, object2) {
return { ...object1, ...object2 };
}, _default_1_createTomSelect = function _default_1_createTomSelect(options) {
const preConnectPayload = { options };
this.dispatchEvent('pre-connect', preConnectPayload);
const tomSelect = new TomSelect(this.formElement, options);
const connectPayload = { tomSelect, options };
this.dispatchEvent('connect', connectPayload);
return tomSelect;
};
default_1.values = {
url: String,
optionsAsHtml: Boolean,
loadingMoreText: String,
noResultsFoundText: String,
noMoreResultsText: String,
createOptionText: String,
minCharacters: Number,
tomSelectOptions: Object,
preload: String,
};
export { default_1 as default };