Skip to content

[Autocomplete] Ensure default plugins are nicely merged with user-defined plugins #2841

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jun 14, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 29 additions & 8 deletions src/Autocomplete/assets/dist/controller.js
Original file line number Diff line number Diff line change
Expand Up @@ -29,14 +29,28 @@ typeof SuppressedError === "function" ? SuppressedError : function (error, suppr
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;
var _default_1_instances, _default_1_getCommonConfig, _default_1_createAutocomplete, _default_1_createAutocompleteWithHtmlContents, _default_1_createAutocompleteWithRemoteData, _default_1_stripTags, _default_1_mergeConfigs, _default_1_normalizePluginsToHash, _default_1_createTomSelect;
class default_1 extends Controller {
constructor() {
super(...arguments);
_default_1_instances.add(this);
this.isObserving = false;
this.hasLoadedChoicesPreviously = false;
this.originalOptions = [];
_default_1_normalizePluginsToHash.set(this, (plugins) => {
if (Array.isArray(plugins)) {
return plugins.reduce((acc, plugin) => {
if (typeof plugin === 'string') {
acc[plugin] = {};
}
if (typeof plugin === 'object' && plugin.name) {
acc[plugin.name] = plugin.options || {};
}
return acc;
}, {});
}
return plugins;
});
}
initialize() {
if (!this.mutationObserver) {
Expand Down Expand Up @@ -223,7 +237,7 @@ class default_1 extends Controller {
[...originalOptionsSet].every((option) => newOptionsSet.has(option)));
}
}
_default_1_instances = new WeakSet(), _default_1_getCommonConfig = function _default_1_getCommonConfig() {
_default_1_normalizePluginsToHash = new WeakMap(), _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) {
Expand Down Expand Up @@ -288,16 +302,16 @@ _default_1_instances = new WeakSet(), _default_1_getCommonConfig = function _def
if (!this.selectElement && !this.urlValue) {
config.shouldLoad = () => false;
}
return __classPrivateFieldGet(this, _default_1_instances, "m", _default_1_mergeObjects).call(this, config, this.tomSelectOptionsValue);
return __classPrivateFieldGet(this, _default_1_instances, "m", _default_1_mergeConfigs).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), {
const config = __classPrivateFieldGet(this, _default_1_instances, "m", _default_1_mergeConfigs).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, {
const config = __classPrivateFieldGet(this, _default_1_instances, "m", _default_1_mergeConfigs).call(this, commonConfig, {
maxOptions: this.getMaxOptions(),
score: (search) => {
const scoringFunction = this.tomSelect.getScoreFunction(search);
Expand All @@ -314,7 +328,7 @@ _default_1_instances = new WeakSet(), _default_1_getCommonConfig = function _def
}, _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, {
const config = __classPrivateFieldGet(this, _default_1_instances, "m", _default_1_mergeConfigs).call(this, commonConfig, {
firstUrl: (query) => {
const separator = autocompleteEndpointUrl.includes('?') ? '&' : '?';
return `${autocompleteEndpointUrl}${separator}query=${encodeURIComponent(query)}`;
Expand Down Expand Up @@ -364,8 +378,15 @@ _default_1_instances = new WeakSet(), _default_1_getCommonConfig = function _def
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_mergeConfigs = function _default_1_mergeConfigs(config1, config2) {
return {
...config1,
...config2,
plugins: {
...__classPrivateFieldGet(this, _default_1_normalizePluginsToHash, "f").call(this, config1.plugins || {}),
...__classPrivateFieldGet(this, _default_1_normalizePluginsToHash, "f").call(this, config2.plugins || {}),
},
};
}, _default_1_createTomSelect = function _default_1_createTomSelect(options) {
const preConnectPayload = { options };
this.dispatchEvent('pre-connect', preConnectPayload);
Expand Down
41 changes: 35 additions & 6 deletions src/Autocomplete/assets/src/controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -214,11 +214,11 @@ export default class extends Controller {
config.shouldLoad = () => false;
}

return this.#mergeObjects(config, this.tomSelectOptionsValue);
return this.#mergeConfigs(config, this.tomSelectOptionsValue);
}

#createAutocomplete(): TomSelect {
const config = this.#mergeObjects(this.#getCommonConfig(), {
const config = this.#mergeConfigs(this.#getCommonConfig(), {
maxOptions: this.getMaxOptions(),
});

Expand All @@ -229,7 +229,7 @@ export default class extends Controller {
const commonConfig = this.#getCommonConfig();
const labelField = commonConfig.labelField ?? 'text';

const config = this.#mergeObjects(commonConfig, {
const config = this.#mergeConfigs(commonConfig, {
maxOptions: this.getMaxOptions(),
score: (search: string) => {
const scoringFunction = this.tomSelect.getScoreFunction(search);
Expand All @@ -251,7 +251,7 @@ export default class extends Controller {
const commonConfig = this.#getCommonConfig();
const labelField = commonConfig.labelField ?? 'text';

const config: RecursivePartial<TomSettings> = this.#mergeObjects(commonConfig, {
const config: RecursivePartial<TomSettings> = this.#mergeConfigs(commonConfig, {
firstUrl: (query: string) => {
const separator = autocompleteEndpointUrl.includes('?') ? '&' : '?';

Expand Down Expand Up @@ -325,10 +325,39 @@ export default class extends Controller {
return string.replace(/(<([^>]+)>)/gi, '');
}

#mergeObjects(object1: any, object2: any): any {
return { ...object1, ...object2 };
#mergeConfigs(config1: any, config2: any): any {
return {
...config1,
...config2,
// Plugins from both configs should be merged together.
plugins: {
...this.#normalizePluginsToHash(config1.plugins || {}),
...this.#normalizePluginsToHash(config2.plugins || {}),
},
Comment on lines +333 to +336
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Converting ['foo'] or [{ name: 'foo', options: {/* ... */} }] to { foo: {/* ... */} } helps us to merge the plugins configurations

};
}

/**
* Normalizes the plugins to a hash, so that we can merge them easily.
*/
#normalizePluginsToHash = (plugins: TomSettings['plugins']): TPluginHash => {
if (Array.isArray(plugins)) {
return plugins.reduce((acc, plugin) => {
if (typeof plugin === 'string') {
acc[plugin] = {};
}

if (typeof plugin === 'object' && plugin.name) {
acc[plugin.name] = plugin.options || {};
}

return acc;
}, {} as TPluginHash);
}

return plugins;
};

/**
* Returns the element, but only if it's a select element.
*/
Expand Down
61 changes: 61 additions & 0 deletions src/Autocomplete/assets/test/controller.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -138,6 +138,67 @@ describe('AutocompleteController', () => {
expect(fetchMock.requests()[1].url).toEqual('/path/to/autocomplete?query=foo');
});

it('connect with ajax URL on a select element, even when the user define custom TomSelect plugins', async () => {
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This test fails (as expected), when running on 2.x:

⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯ Unhandled Errors ⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯

Vitest caught 1 unhandled error during the test run.
This might cause false positive tests. Resolve unhandled errors to make sure your tests are not affected.

⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯ Uncaught Exception ⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯
TypeError: this.getUrl is not a function
 ❯ TomSelect.call src/controller.ts:264:34
    262|             // the 'this.XXX' calls inside this method fail
    263|             load: function (query: string, callback: TomLoadCallback) {
    264|                 const url = this.getUrl(query);
       |                                  ^
    265|                 fetch(url)
    266|                     .then((response) => response.json())
 ❯ Timeout._onTimeout ../../../node_modules/tom-select/src/utils.ts:59:7
 ❯ listOnTimeout node:internal/timers:594:17
 ❯ processTimers node:internal/timers:529:7

This error originated in "test/controller.test.ts" test file. It doesn't mean the error was thrown inside the file itself, but while it was running.
The latest test that might've caused the error is "connect with ajax URL on a select element, even when the user defined custom TomSelect plugin". It might mean one of the following:
- The error was thrown, while Vitest was running this test.
- If the error occurred after the test had been completed, this was the last documented test before it was thrown.

const { container, tomSelect } = await startAutocompleteTest(`
<label for="the-select">Items</label>
<select
id="the-select"
data-testid="main-element"
data-controller="autocomplete"
data-autocomplete-url-value="/path/to/autocomplete"
data-autocomplete-tom-select-options-value="{&quot;plugins&quot;:[&quot;input_autogrow&quot;]}"
></select>
`);

// initial Ajax request on focus
fetchMock.mockResponseOnce(
JSON.stringify({
results: [
{
value: 3,
text: 'salad',
},
],
})
);

fetchMock.mockResponseOnce(
JSON.stringify({
results: [
{
value: 1,
text: 'pizza',
},
{
value: 2,
text: 'popcorn',
},
],
})
);

const controlInput = tomSelect.control_input;

// wait for the initial Ajax request to finish
userEvent.click(controlInput);
await waitFor(() => {
expect(container.querySelectorAll('.option[data-selectable]')).toHaveLength(1);
});

// typing was not properly triggering, for some reason
//userEvent.type(controlInput, 'foo');
controlInput.value = 'foo';
controlInput.dispatchEvent(new Event('input'));

await waitFor(() => {
expect(container.querySelectorAll('.option[data-selectable]')).toHaveLength(2);
});

expect(fetchMock.requests().length).toEqual(2);
expect(fetchMock.requests()[0].url).toEqual('/path/to/autocomplete?query=');
expect(fetchMock.requests()[1].url).toEqual('/path/to/autocomplete?query=foo');
});

it('resets when ajax URL attribute on a select element changes', async () => {
const { container, tomSelect } = await startAutocompleteTest(`
<label for="the-select">Items</label>
Expand Down