Skip to content

Commit

Permalink
[Autocomplete] Allow configuring TomSelect’s labelField
Browse files Browse the repository at this point in the history
  • Loading branch information
MatTheCat committed Nov 15, 2024
1 parent 89c7fa9 commit 8782509
Showing 1 changed file with 13 additions and 7 deletions.
20 changes: 13 additions & 7 deletions src/Autocomplete/assets/src/controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -177,26 +177,32 @@ export default class extends Controller {
}

#createAutocompleteWithHtmlContents(): TomSelect {
const config = this.#mergeObjects(this.#getCommonConfig(), {
const commonConfig = this.#getCommonConfig();
const labelField = commonConfig.labelField ?? 'text';

const config = this.#mergeObjects(commonConfig, {
maxOptions: this.getMaxOptions(),
score: (search: string) => {
const scoringFunction = this.tomSelect.getScoreFunction(search);
return (item: any) => {
// strip HTML tags from each option's searchable text
return scoringFunction({ ...item, text: this.#stripTags(item.text) });
return scoringFunction({ ...item, text: this.#stripTags(item[labelField]) });
};
},
render: {
item: (item: any) => `<div>${item.text}</div>`,
option: (item: any) => `<div>${item.text}</div>`,
item: (item: any) => `<div>${item[labelField]}</div>`,
option: (item: any) => `<div>${item[labelField]}</div>`,
},
});

return this.#createTomSelect(config);
}

#createAutocompleteWithRemoteData(autocompleteEndpointUrl: string, minCharacterLength: number | null): TomSelect {
const config: RecursivePartial<TomSettings> = this.#mergeObjects(this.#getCommonConfig(), {
const commonConfig = this.#getCommonConfig();
const labelField = commonConfig.labelField ?? 'text';

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

Expand Down Expand Up @@ -241,8 +247,8 @@ export default class extends Controller {
// avoid extra filtering after results are returned
score: (search: string) => (item: any) => 1,
render: {
option: (item: any) => `<div>${item.text}</div>`,
item: (item: any) => `<div>${item.text}</div>`,
option: (item: any) => `<div>${item[labelField]}</div>`,
item: (item: any) => `<div>${item[labelField]}</div>`,
loading_more: (): string => {
return `<div class="loading-more-results">${this.loadingMoreTextValue}</div>`;
},
Expand Down

0 comments on commit 8782509

Please sign in to comment.