|
| 1 | +import { MessageError, MessageResolutionError } from '../errors.js'; |
| 2 | +import type { MessageFunctionContext } from './index.js'; |
| 3 | +import type { MessageNumber, MessageNumberOptions } from './number.js'; |
| 4 | +import { getMessageNumber, readNumericOperand } from './number.js'; |
| 5 | +import { asPositiveInteger, asString } from './utils.js'; |
| 6 | + |
| 7 | +/** |
| 8 | + * `unit` accepts as input numerical values as well as |
| 9 | + * objects wrapping a numerical value that also include a `unit` property. |
| 10 | + * |
| 11 | + * @beta |
| 12 | + */ |
| 13 | +export function unit( |
| 14 | + ctx: MessageFunctionContext, |
| 15 | + exprOpt: Record<string | symbol, unknown>, |
| 16 | + operand?: unknown |
| 17 | +): MessageNumber { |
| 18 | + const { source } = ctx; |
| 19 | + const input = readNumericOperand(operand, source); |
| 20 | + const options: MessageNumberOptions = Object.assign({}, input.options, { |
| 21 | + localeMatcher: ctx.localeMatcher, |
| 22 | + style: 'unit' |
| 23 | + } as const); |
| 24 | + |
| 25 | + for (const [name, optval] of Object.entries(exprOpt)) { |
| 26 | + if (optval === undefined) continue; |
| 27 | + try { |
| 28 | + switch (name) { |
| 29 | + case 'signDisplay': |
| 30 | + case 'roundingMode': |
| 31 | + case 'roundingPriority': |
| 32 | + case 'trailingZeroDisplay': |
| 33 | + case 'unit': |
| 34 | + case 'unitDisplay': |
| 35 | + case 'useGrouping': |
| 36 | + // @ts-expect-error Let Intl.NumberFormat construction fail |
| 37 | + options[name] = asString(optval); |
| 38 | + break; |
| 39 | + case 'minimumIntegerDigits': |
| 40 | + case 'minimumFractionDigits': |
| 41 | + case 'maximumFractionDigits': |
| 42 | + case 'minimumSignificantDigits': |
| 43 | + case 'maximumSignificantDigits': |
| 44 | + case 'roundingIncrement': |
| 45 | + // @ts-expect-error TS types don't know about roundingIncrement |
| 46 | + options[name] = asPositiveInteger(optval); |
| 47 | + break; |
| 48 | + } |
| 49 | + } catch (error) { |
| 50 | + if (error instanceof MessageError) { |
| 51 | + ctx.onError(error); |
| 52 | + } else { |
| 53 | + const msg = `Value ${optval} is not valid for :currency option ${name}`; |
| 54 | + ctx.onError(new MessageResolutionError('bad-option', msg, source)); |
| 55 | + } |
| 56 | + } |
| 57 | + } |
| 58 | + |
| 59 | + if (!options.unit) { |
| 60 | + const msg = 'A unit identifier is required for :unit'; |
| 61 | + throw new MessageResolutionError('bad-operand', msg, source); |
| 62 | + } |
| 63 | + |
| 64 | + return getMessageNumber(ctx, input.value, options, false); |
| 65 | +} |
0 commit comments