import { Components } from '@formio/js'; import _ from 'lodash'; import moment from 'moment'; import { SelectComponent as CoreSelectComponent } from '../../types'; import { choicesAccessibilityTemplates, stripDropdownAriaExpanded } from './choicesAccessibility'; const Select = Components.components.select; interface ChoiceItem { label: string; active: boolean; rank: number; id: string | number; choiceEl?: HTMLElement; [key: string]: unknown; } interface SearchResult { item: ChoiceItem; score: number; rank: number; } interface ChoicesInstance { _isSearching: boolean; _currentValue: string; _store: { choices: ChoiceItem[]; dispatch(action: { type: string; active?: boolean; results?: SearchResult[] }): void; }; _searchChoices?: (needle: string) => number | null; _clearNotice?: () => void; _stopSearch?: () => void; setChoices?: ( choices: unknown[], value: string, label: string, replaceChoices?: boolean, clearSearchFlag?: boolean ) => unknown; input?: { element?: HTMLInputElement }; } interface ReferenceItem { id?: string | number; label?: string; [key: string]: unknown; } type SelectValue = ReferenceItem | string | number | null | undefined; const MOMENT_FORMAT_TOKEN = /\{\{\s*moment\(\s*(item(?:\??\.[\w$]+)*)\s*\)\s*\.format\(\s*(['"])((?:(?!\2).)*)\2\s*\)\s*;?\s*\}\}/g; /** * Resolves `{{ moment(item.x).format('...') }}`, which formio 5's `noeval` * interpolation renders as "undefined". Output is HTML-escaped. Values are passed * to `moment()` unguarded, as in formio 4. */ function resolveMomentTokens( template: string, item: ReferenceItem, record?: Record ): string { return template.replace( MOMENT_FORMAT_TOKEN, (_match: string, path: string, _quote: string, format: string): string => { const cleanPath = path.replace(/\?\./g, '.'); const value: unknown = _.get({ item }, cleanPath); if (record) { _.set(record, cleanPath, value); } return _.escape(moment(value as moment.MomentInput).format(format)); } ); } function isUsersEmailsUrl(url: unknown): boolean { if (typeof url !== 'string') { return false; } const path = url.split(/[?#]/)[0]; return /(^|\/)users\/emails\/?$/.test(path); } function emailOf(item: unknown): string { if (typeof item === 'string') { return item; } const email = (item as ReferenceItem | null | undefined)?.email; return typeof email === 'string' ? email : ''; } const DEFAULT_WINDOW_SIZE = 50; function positiveOr(value: unknown, fallback: number): number { return typeof value === 'number' && value > 0 ? value : fallback; } export default class GDSSelect extends Select { declare component: CoreSelectComponent; protected _gdsSearchPatchedChoices?: ChoicesInstance; protected _gdsFilterKey?: string; // True when searching client-side; no initialiser, so it keeps the value set by init() in super() protected _gdsClientSideSearch?: boolean; protected _gdsAllItems?: unknown[]; protected _gdsSearchIndex?: string[]; protected _gdsWindowReplaced?: boolean; // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types constructor(component?: any, options?: any, data?: any) { super(component, options, data); } // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types normalizeSingleValue(value: any): any { if (this.component.dataType === 'object' && value === '[object Object]') { return this.emptyValue; } return super.normalizeSingleValue(value); } // eslint-disable-next-line @typescript-eslint/no-explicit-any init(): any { const url = (this.component.data as { url?: unknown } | undefined)?.url; const isReferenceData = typeof url === 'string' && url.includes('/v2/entities/'); const isClientSideSearchUrl = isUsersEmailsUrl(url) || (typeof url === 'string' && !url.includes('/v2/entities/') && Boolean(this.component.searchField)); if (isReferenceData || isClientSideSearchUrl) { this._gdsClientSideSearch = true; if (this.component.searchField) { this.component.searchField = ''; } if ((this.component.limit ?? 100) < 1000) { this.component.disableLimit = true; } } return super.init(); } protected _patchChoicesSearch(): void { const url = (this.component.data as { url?: unknown } | undefined)?.url; const isReferenceData = typeof url === 'string' && url.includes('/v2/entities/'); if (!isReferenceData && !this._gdsClientSideSearch) { return; } const choices = (this as unknown as { choices: ChoicesInstance }).choices; if (!choices || choices === this._gdsSearchPatchedChoices) { return; } this._gdsSearchPatchedChoices = choices; const isWindowed = isUsersEmailsUrl(url); if (isWindowed) { this._gdsWindowReplaced = false; // _stopSearch re-activates the store, which holds search results, so restore the window const originalStopSearch = choices._stopSearch?.bind(choices); if (originalStopSearch) { choices._stopSearch = (): void => { originalStopSearch(); if (this._gdsWindowReplaced) { this._gdsRestoreWindow(choices); } }; } } (choices as unknown as Record)._searchChoices = (needle: string): number | null => { if (isWindowed) { return this._gdsWindowedSearch(choices, needle); } if (!needle) { choices._isSearching = false; choices._currentValue = ''; choices._store.dispatch({ type: 'ACTIVATE_CHOICES', active: true }); return 0; } const normalizedNeedle = needle.trim().toLowerCase().replace(/\s{2,}/g, ' '); if (!normalizedNeedle || normalizedNeedle === choices._currentValue) { return null; } const words = normalizedNeedle.split(/\s+/).filter(Boolean); const allChoices: ChoiceItem[] = choices._store.choices; const matched: SearchResult[] = []; const prefix: ChoiceItem[] = []; const contains: ChoiceItem[] = []; for (const choice of allChoices) { const renderedLabel = choice.choiceEl?.textContent || ''; const label = [choice.label, renderedLabel, choice.value] .map((value) => String(value ?? '').toLowerCase()) .join(' '); const allMatch = words.every((w) => label.includes(w)); if (!allMatch) { choice.active = false; choice.rank = 0; continue; } if (label.startsWith(normalizedNeedle)) { prefix.push(choice); } else { contains.push(choice); } } prefix.sort((a, b) => a.label.localeCompare(b.label)); contains.sort((a, b) => a.label.localeCompare(b.label)); [...prefix, ...contains].forEach((choice, index) => { matched.push({ item: choice, score: 0, rank: index + 1, }); }); choices._isSearching = true; choices._currentValue = normalizedNeedle; // Replaces Choices.js' _searchChoices, which cleared the notice. if (matched.length) { choices._clearNotice?.(); } choices._store.dispatch({ type: 'FILTER_CHOICES', results: matched }); return matched.length; }; } protected _gdsWindowSizes(): { idle: number; search: number } { const options = this.choicesOptions(); return { idle: positiveOr(options.renderChoiceLimit, DEFAULT_WINDOW_SIZE), search: positiveOr(options.searchResultLimit, DEFAULT_WINDOW_SIZE), }; } protected _gdsWindowItems(items: unknown[]): unknown[] { if (items !== this._gdsAllItems) { const keyed = items.map((item) => ({ item, key: emailOf(item).toLowerCase() })); keyed.sort((a, b) => (a.key < b.key ? -1 : a.key > b.key ? 1 : 0)); this._gdsAllItems = keyed.map((entry) => entry.item); this._gdsSearchIndex = keyed.map((entry) => entry.key); } return (this._gdsAllItems as unknown[]).slice(0, this._gdsWindowSizes().idle); } protected _gdsRestoreWindow(choices: ChoicesInstance): void { choices._isSearching = false; choices._currentValue = ''; if (!this._gdsWindowReplaced || !choices.setChoices) { choices._store.dispatch({ type: 'ACTIVATE_CHOICES', active: true }); return; } this._gdsWindowReplaced = false; const selectOptions = (this as unknown as { selectOptions: unknown[] }).selectOptions; choices.setChoices(selectOptions, 'value', 'label', true, true); } /** * Searches the full /users/emails list by email text and shows the best matches, * prefix matches first. Relies on private Choices.js members (checked against 11.2.4). */ protected _gdsWindowedSearch(choices: ChoicesInstance, needle: string): number | null { if (!needle) { this._gdsRestoreWindow(choices); return 0; } const normalizedNeedle = needle.trim().toLowerCase().replace(/\s{2,}/g, ' '); if (!normalizedNeedle || normalizedNeedle === choices._currentValue) { return null; } const all = this._gdsAllItems ?? []; const index = this._gdsSearchIndex ?? []; const limit = this._gdsWindowSizes().search; const words = normalizedNeedle.split(/\s+/).filter(Boolean); const prefix: unknown[] = []; const contains: unknown[] = []; for (let i = 0; i < all.length; i++) { const text = index[i]; if (!words.every((word) => text.includes(word))) { continue; } if (text.startsWith(normalizedNeedle)) { prefix.push(all[i]); if (prefix.length >= limit) { break; } } else if (contains.length < limit) { contains.push(all[i]); } } const matched = [...prefix, ...contains].slice(0, limit); if (!choices.setChoices) { return null; } const selectValueAndLabel = (this as unknown as { selectValueAndLabel(item: unknown): { value: unknown; label: string }; }).selectValueAndLabel.bind(this); const entries = matched.map((item) => selectValueAndLabel(item)); choices._isSearching = true; choices.setChoices(entries, 'value', 'label', true, false); // Choices only renders ranked choices while searching. Rank by label; // duplicate labels take ranks in turn. const ranks = new Map(); entries.forEach((entry, position) => { const queue = ranks.get(entry.label) ?? []; queue.push(position + 1); ranks.set(entry.label, queue); }); const results: SearchResult[] = []; for (const choice of choices._store.choices) { const rank = ranks.get(choice.label)?.shift(); if (rank !== undefined) { results.push({ item: choice, score: 0, rank }); } } choices._currentValue = normalizedNeedle; // setChoices re-renders before ranks exist, leaving a stale notice. if (results.length) { choices._clearNotice?.(); } choices._store.dispatch({ type: 'FILTER_CHOICES', results }); this._gdsWindowReplaced = true; return results.length; } protected get _gdsHasDynamicFilter(): boolean { return typeof this.component.filter === 'string' && this.component.filter.includes('{{'); } protected _gdsCurrentFilterKey(): string { return this._gdsHasDynamicFilter ? this.interpolate(this.component.filter as string) : ''; } setItems(items: unknown, fromSearch?: boolean): void { if (!fromSearch && Array.isArray(items) && isUsersEmailsUrl((this.component.data as { url?: unknown } | undefined)?.url)) { super.setItems(this._gdsWindowItems(items), fromSearch); this.disableInfiniteScroll(); } else { super.setItems(items, fromSearch); } if (!fromSearch) { this._gdsFilterKey = this._gdsCurrentFilterKey(); } this._patchChoicesSearch(); } attach(element: HTMLElement): Promise { const result = super.attach(element); this._patchChoicesSearch(); stripDropdownAriaExpanded((this as unknown as { choices?: { dropdown?: Parameters[0] } }).choices?.dropdown); return Promise.resolve(result); } // Form.io does not re-fetch a visible select when its interpolated filter changes, // leaving stale options. Compare the filter on every data change and reload. // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types checkComponentConditions(data: any, flags: any, row: any): boolean { const visible = super.checkComponentConditions(data, flags, row); // `_gdsFilterKey` is set only after loading, so lazyLoad selects are not fetched early. // `active` is not checked, as it can be false for a loaded lazyLoad select. if ( visible && this.component.dataSrc === 'url' && this._gdsHasDynamicFilter && this._gdsFilterKey !== undefined && !this.loading ) { const filterKey = this._gdsCurrentFilterKey(); if (filterKey !== this._gdsFilterKey) { this._gdsFilterKey = filterKey; this.triggerUpdate?.(null, true); } } return visible; } // Avoids a re-fetch on redraw/activate when items are cached, but still repopulates // choices.js so the loading spinner is replaced. Forced updates (refreshOn) bypass this. // eslint-disable-next-line @typescript-eslint/no-explicit-any updateItems(searchInput: unknown, forceUpdate: boolean): any { const choices = (this as unknown as { choices?: ChoicesInstance }).choices; const isSearching = choices?._isSearching ?? false; if ( !forceUpdate && !searchInput && !isSearching && this.component.dataSrc === 'url' && this._gdsFilterKey === this._gdsCurrentFilterKey() && Array.isArray(this.downloadedResources) && this.downloadedResources.length > 0 && !this.loading ) { this.setItems(this._gdsAllItems ?? this.downloadedResources, false); return; } return super.updateItems(searchInput, forceUpdate); } /** * Escapes item values with `_.escape()` before interpolation, replacing the * slow DOMPurify pass in the base class. * * Safe for text-content templates only. It does not protect values placed in * attributes or URLs (e.g. `href`), so revisit this if a schema does that. */ getOptionTemplate(data: ReferenceItem, value: SelectValue, index?: number): string { if (!this.component.template) { return String(data.label ?? ''); } const options = { noeval: true, data: {} as Record }; const escapedData: ReferenceItem = _.mapValues( data as Record, (v): unknown => (typeof v === 'string' ? _.escape(v) : v) ) as ReferenceItem; const template: string = this.component.template ? this.interpolate( resolveMomentTokens(this.component.template, data, options.data), { item: escapedData }, options ) : String(data.label ?? ''); // eslint-disable-next-line @typescript-eslint/no-explicit-any const isReference = Boolean((this.component as any).reference); const rawId = (value as { _id?: unknown } | null | undefined)?._id; const templateValue: SelectValue = isReference && rawId != null ? String(rawId) : value; if ( templateValue != null && !_.isObject(templateValue) && (options.data as Record).item ) { this.templateData[templateValue as string] = (options.data as Record).item; } if (_.isNumber(index)) { this.templateData[index] = (options.data as Record).item; } return template; } /** * Skips the outer `sanitize()` for object data with a template, as * `getOptionTemplate` already escapes values. Other cases use `super`. */ // eslint-disable-next-line @typescript-eslint/no-explicit-any itemTemplate(data: ReferenceItem | string | number | unknown[], value: SelectValue, index?: number): any { if ( typeof data === 'object' && data !== null && !Array.isArray(data) && this.component.template ) { const template = this.getOptionTemplate(data as ReferenceItem, value, index); if (!template) { return this.sanitize(JSON.stringify(data), this.shouldSanitizeValue); } const label = template.replace(/<\/?[^>]+(>|$)/g, ''); if (!label) return template; return template.replace(label, this.t(label, { _userInput: true })); } // eslint-disable-next-line @typescript-eslint/no-explicit-any return super.itemTemplate(data as any, value, index); } // eslint-disable-next-line @typescript-eslint/no-explicit-any choicesOptions(): Record { const options = super.choicesOptions(); // A remove button inside a single select's item is a nested interactive control. if (!this.component.multiple && !(this.component.customOptions as Record | undefined)?.removeItemButton) { options.removeItemButton = false; } const baseTemplates = options.callbackOnCreateTemplates; options.callbackOnCreateTemplates = function (this: unknown, ...args: unknown[]): Record { const base = typeof baseTemplates === 'function' ? baseTemplates.apply(this, args) : {}; return { ...base, ...choicesAccessibilityTemplates.call(this as never) }; }; const url = (this.component.data as { url?: unknown } | undefined)?.url; const isReferenceData = typeof url === 'string' && url.includes('/v2/entities/'); if (isReferenceData || this._gdsClientSideSearch) { options.searchChoices = true; options.searchFloor = 0; options.searchFields = ['label', 'value']; } if (isUsersEmailsUrl(url)) { // Do not raise these to `limit`, which would defeat the window options.renderChoiceLimit = positiveOr(options.renderChoiceLimit, DEFAULT_WINDOW_SIZE); options.searchResultLimit = positiveOr(options.searchResultLimit, DEFAULT_WINDOW_SIZE); } else { const itemLimit: number = this.component.limit || 100; if (typeof options.searchResultLimit === 'number' && options.searchResultLimit < itemLimit) { options.searchResultLimit = itemLimit; } if (typeof options.renderChoiceLimit === 'number' && options.renderChoiceLimit < itemLimit) { options.renderChoiceLimit = itemLimit; } } options.valueComparer = (a: unknown, b: unknown): boolean => { if (a === b) return true; if (a == null || b == null) return false; if (typeof a === 'object' && typeof b === 'object') { const aId = (a as Record).id; const bId = (b as Record).id; if (aId !== undefined && bId !== undefined) { return aId === bId; } } return _.isEqual(a, b); }; return options; } }