/** * Copyright Aquera Inc 2025 * * This source code is licensed under the BSD-3-Clause license found in the * LICENSE file in the root directory of this source tree. */ import type { VirtualOption } from './types.js'; export class VirtualSelectSelectionManager { static createVirtualOptionsFromValues( value: string | string[], data: any[], getDisplayText: (item: any) => string, getItemValue?: (item: any) => string, allowHtmlLabel?: boolean ): VirtualOption[] { if (!value || (Array.isArray(value) && value.length === 0)) { return []; } const values = Array.isArray(value) ? value : [value]; return values.map(valueItem => { // Use enhanced functions if available, otherwise fallback to basic logic const displayTextFn = getDisplayText; const valueFn = getItemValue || ((item: any) => item?.value || item); const item = data.find((item: any) => { const itemValue = valueFn(item); const itemDisplayText = displayTextFn(item); return String(itemValue) === String(valueItem) || String(itemDisplayText) === String(valueItem); }); const displayText = item ? displayTextFn(item) : valueItem; return { value: valueItem, selected: true, getTextLabel: () => { if(!allowHtmlLabel){ return displayText; } // If displayText contains HTML, strip tags if (typeof displayText === 'string' && /<[^>]+>/.test(displayText)) { const div = document.createElement('div'); div.innerHTML = displayText; return div.textContent || div.innerText || ''; } return displayText; }, getOptionPrefix: () => '', }; }); } static updateDisplayLabel(selectedOptions: VirtualOption[], placeholder: string, multiple: boolean, value: string | string[]): string { if (multiple) { if (placeholder && selectedOptions.length === 0) { return ''; } else { return selectedOptions.length + ' selected'; } } else { const currentValue = Array.isArray(value) ? value[0] : value; return selectedOptions[0]?.getTextLabel() ? selectedOptions[0].getTextLabel() : currentValue ?? ''; } } static updateValue(selectedOptions: VirtualOption[], multiple: boolean): string | string[] { if (multiple) { return selectedOptions.map(el => el.value); } else { return selectedOptions[0]?.value ?? ''; } } }