2023-01-11 17:57:42 +00:00
|
|
|
import { makeT } from 'app/client/lib/localization';
|
2021-08-26 16:35:11 +00:00
|
|
|
import {ACSelectItem, buildACSelect} from "app/client/lib/ACSelect";
|
|
|
|
import {Computed, IDisposableOwner, Observable} from "grainjs";
|
|
|
|
import {ACIndexImpl} from "app/client/lib/ACIndex";
|
|
|
|
import {testId} from 'app/client/ui2018/cssVars';
|
|
|
|
import {currencies} from 'app/common/Locales';
|
|
|
|
|
2023-01-11 17:57:42 +00:00
|
|
|
const t = makeT('CurrencyPicker');
|
|
|
|
|
2021-08-26 16:35:11 +00:00
|
|
|
interface CurrencyPickerOptions {
|
|
|
|
// The label to use in the select menu for the default option.
|
|
|
|
defaultCurrencyLabel: string;
|
2022-10-14 10:07:19 +00:00
|
|
|
disabled?: Observable<boolean>;
|
2021-08-26 16:35:11 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
export function buildCurrencyPicker(
|
|
|
|
owner: IDisposableOwner,
|
|
|
|
currency: Observable<string|undefined>,
|
|
|
|
onSave: (value: string|undefined) => void,
|
2022-10-14 10:07:19 +00:00
|
|
|
{defaultCurrencyLabel, disabled}: CurrencyPickerOptions
|
2021-08-26 16:35:11 +00:00
|
|
|
) {
|
|
|
|
const currencyItems: ACSelectItem[] = currencies
|
|
|
|
.map(item => ({
|
|
|
|
value: item.code,
|
|
|
|
label: `${item.code} ${item.name}`,
|
|
|
|
cleanText: `${item.code} ${item.name}`.trim().toLowerCase(),
|
|
|
|
}));
|
|
|
|
|
|
|
|
// Add default currency label option to the very front.
|
|
|
|
currencyItems.unshift({
|
|
|
|
label : defaultCurrencyLabel,
|
|
|
|
value : defaultCurrencyLabel,
|
|
|
|
cleanText : defaultCurrencyLabel.toLowerCase(),
|
|
|
|
});
|
|
|
|
// Create a computed that will display 'Local currency' as a value and label
|
|
|
|
// when `currency` is undefined.
|
|
|
|
const valueObs = Computed.create(owner, (use) => use(currency) || defaultCurrencyLabel);
|
|
|
|
const acIndex = new ACIndexImpl<ACSelectItem>(currencyItems, 200, true);
|
|
|
|
return buildACSelect(owner,
|
|
|
|
{
|
|
|
|
acIndex, valueObs,
|
2022-10-14 10:07:19 +00:00
|
|
|
disabled,
|
2021-08-26 16:35:11 +00:00
|
|
|
save(_, item: ACSelectItem | undefined) {
|
|
|
|
// Save only if we have found a match
|
|
|
|
if (!item) {
|
2023-01-11 17:57:42 +00:00
|
|
|
throw new Error(t("Invalid currency"));
|
2021-08-26 16:35:11 +00:00
|
|
|
}
|
|
|
|
// For default value, return undefined to use default currency for document.
|
|
|
|
onSave(item.value === defaultCurrencyLabel ? undefined : item.value);
|
|
|
|
}
|
|
|
|
},
|
|
|
|
testId("currency-autocomplete")
|
|
|
|
);
|
|
|
|
}
|