@metamask-previews/perps-controller 22.3.0-preview-270326558 → 23.0.0-preview-c72f8b1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -14,6 +14,7 @@
14
14
  * only needs the `PerpsIntlFormatters` shape. Without `formatters`, an
15
15
  * `en-US` fallback keeps the legacy call signatures working.
16
16
  */
17
+ import { BASIS_POINTS_DIVISOR } from '../constants/hyperLiquidConfig.js';
17
18
  import { DECIMAL_PRECISION_CONFIG, FUNDING_RATE_CONFIG, PERPS_CONSTANTS, PERPS_DISPLAY_PRECISION, } from '../constants/perpsConfig.js';
18
19
  /**
19
20
  * `Intl.NumberFormat` cache of the `en-US` fallback, keyed by options.
@@ -175,6 +176,8 @@ function _roundsToWhole(amount, maximumFractionDigits) {
175
176
  * @param options.maximumFractionDigits - Maximum decimal digits.
176
177
  * @param options.strip - `fiat` drops an all-zero two-digit fraction (`.00`),
177
178
  * `all` drops every trailing fraction zero, `none` keeps them.
179
+ * @param options.symbol - `false` formats the number without the currency
180
+ * symbol, for chart labels (default `true`).
178
181
  * @returns Formatted currency string.
179
182
  */
180
183
  function _formatCurrency(formatters, amount, options) {
@@ -190,12 +193,57 @@ function _formatCurrency(formatters, amount, options) {
190
193
  maximumFractionDigits = 0;
191
194
  }
192
195
  }
196
+ if (options.symbol === false) {
197
+ return formatters.formatNumber(amount, {
198
+ minimumFractionDigits,
199
+ maximumFractionDigits,
200
+ });
201
+ }
193
202
  return formatters.formatCurrency(amount, options.currency, {
194
203
  currencyDisplay: 'narrowSymbol',
195
204
  minimumFractionDigits,
196
205
  maximumFractionDigits,
197
206
  });
198
207
  }
208
+ /**
209
+ * Formats a non-negative USD amount with fixed decimals and appends a
210
+ * magnitude suffix (`K`, `M`, `B`, `T`) right after the number, wherever the
211
+ * locale puts the currency symbol: `$1.23M`, `1,23M $`.
212
+ *
213
+ * The suffix is placed by finding the formatted number in the currency
214
+ * output, not through `formatToParts` or `notation: 'compact'`, which Hermes
215
+ * does not reliably support.
216
+ *
217
+ * @param formatters - Locale-bound formatters.
218
+ * @param amount - Non-negative amount, already divided by the scale.
219
+ * @param options - Formatting options.
220
+ * @param options.decimals - Fraction digits always shown.
221
+ * @param options.suffix - Magnitude suffix, or an empty string.
222
+ * @param options.symbol - `false` formats without the currency symbol.
223
+ * @returns The formatted amount.
224
+ */
225
+ function _formatScaledUsd(formatters, amount, options) {
226
+ const { decimals, suffix, symbol } = options;
227
+ if (!symbol) {
228
+ return `${_formatDecimal(formatters, amount, decimals, decimals, true)}${suffix}`;
229
+ }
230
+ const money = _formatCurrency(formatters, amount, {
231
+ currency: 'USD',
232
+ minimumFractionDigits: decimals,
233
+ maximumFractionDigits: decimals,
234
+ strip: 'none',
235
+ });
236
+ if (!suffix) {
237
+ return money;
238
+ }
239
+ const number = _formatDecimal(formatters, amount, decimals, decimals, true);
240
+ const index = money.indexOf(number);
241
+ if (index === -1) {
242
+ return `${money}${suffix}`;
243
+ }
244
+ const end = index + number.length;
245
+ return `${money.slice(0, end)}${suffix}${money.slice(end)}`;
246
+ }
199
247
  /**
200
248
  * Price threshold constants for PRICE_RANGES_UNIVERSAL
201
249
  * These define the boundaries between different formatting ranges
@@ -429,21 +477,26 @@ export const PRICE_RANGES_UNIVERSAL = [
429
477
  * @param options.currency - Currency code (default: 'USD').
430
478
  * @param options.stripTrailingZeros - Strip trailing zeros from output. `false` keeps them; otherwise the range decides (default: strip).
431
479
  * @param options.locale - Locale passed to a range's `customFormat` only (default `en-US`).
480
+ * @param options.symbol - `false` omits the currency symbol, for chart labels (default `true`).
432
481
  * @returns Formatted currency string, or `PERPS_CONSTANTS.FallbackPriceDisplay`
433
- * (`$---`) for a missing value.
482
+ * (`$---`) for a missing value (`PERPS_CONSTANTS.FallbackDataDisplay`, `--`,
483
+ * without the symbol).
434
484
  * @example
435
485
  * formatPerpsFiat(1234.56) => "$1,234.56"
436
486
  * formatPerpsFiat(1250) => "$1,250" // fiat-style stripping of .00
437
487
  * formatPerpsFiat(-0.004) => "-<$0.01" // below the range threshold
438
488
  * formatPerpsFiat(1234.5, { formatters: createFormatters({ locale: 'de' }) }) => "1.234,50 $"
439
489
  * formatPerpsFiat(12345.67, { ranges: PRICE_RANGES_UNIVERSAL }) => "$12,346"
490
+ * formatPerpsFiat(2480.37, { ranges: PRICE_RANGES_UNIVERSAL, symbol: false }) => "2,480.4"
440
491
  * formatPerpsFiat(undefined) => "$---"
441
492
  */
442
493
  export const formatPerpsFiat = (balance, options) => {
443
494
  const value = _parseDisplayNumber(balance);
444
495
  if (value === undefined) {
445
496
  // Placeholder for missing values to avoid confusion with actual $0 values
446
- return PERPS_CONSTANTS.FallbackPriceDisplay;
497
+ return options?.symbol === false
498
+ ? PERPS_CONSTANTS.FallbackDataDisplay
499
+ : PERPS_CONSTANTS.FallbackPriceDisplay;
447
500
  }
448
501
  const currency = options?.currency ?? 'USD';
449
502
  const ranges = options?.ranges ?? PRICE_RANGES_MINIMAL_VIEW;
@@ -485,6 +538,7 @@ export const formatPerpsFiat = (balance, options) => {
485
538
  minimumFractionDigits: minDecimals,
486
539
  maximumFractionDigits: maxDecimals,
487
540
  strip,
541
+ symbol: options?.symbol,
488
542
  });
489
543
  const isZero = !isBelowThreshold && _currencyShowsZero(amount, maxDecimals);
490
544
  return `${_signPrefix(value, isZero, options?.sign ?? 'auto')}${isBelowThreshold ? '<' : ''}${body}`;
@@ -577,7 +631,8 @@ export const formatPnl = (pnl, options = {}) => {
577
631
  * @param value - Raw percentage value (e.g., 5.25 for 5.25%, not 0.0525)
578
632
  * @param decimalsOrOptions - Decimal places (default:
579
633
  * `PERPS_DISPLAY_PRECISION.Percentage`, 2), or options: `decimals`,
580
- * `formatters` (default `en-US`) and `sign` (default `always`).
634
+ * `formatters` (default `en-US`), `sign` (default `always`) and
635
+ * `stripTrailingZeros` (default `false`).
581
636
  * @returns Format: "+X.XX%" or "-X.XX%", or
582
637
  * `PERPS_CONSTANTS.FallbackPercentageDisplay` (`--%`) for a missing value.
583
638
  * @example formatPercentage(5.25) => "+5.25%"
@@ -586,10 +641,11 @@ export const formatPnl = (pnl, options = {}) => {
586
641
  * @example formatPercentage(10.25, { decimals: PERPS_DISPLAY_PRECISION.RoePercent }) => "+10.3%"
587
642
  * @example formatPercentage(0.0021, { decimals: PERPS_DISPLAY_PRECISION.SlippageEstimatePercent, sign: 'never' }) => "0.0021%"
588
643
  * @example formatPercentage(-12345.67, { decimals: 1, formatters: createFormatters({ locale: 'es' }) }) => "-12.345,7%"
644
+ * @example formatPercentage(25, { decimals: PERPS_DISPLAY_PRECISION.TwapProgressPercent, stripTrailingZeros: true, sign: 'never' }) => "25%"
589
645
  * @example formatPercentage(undefined) => "--%"
590
646
  */
591
647
  export const formatPercentage = (value, decimalsOrOptions) => {
592
- const { formatters = _fallbackFormatters, decimals = PERPS_DISPLAY_PRECISION.Percentage, sign = 'always', } = typeof decimalsOrOptions === 'number'
648
+ const { formatters = _fallbackFormatters, decimals = PERPS_DISPLAY_PRECISION.Percentage, sign = 'always', stripTrailingZeros = false, } = typeof decimalsOrOptions === 'number'
593
649
  ? { decimals: decimalsOrOptions }
594
650
  : (decimalsOrOptions ?? {});
595
651
  const parsed = _parseDisplayNumber(value);
@@ -597,7 +653,7 @@ export const formatPercentage = (value, decimalsOrOptions) => {
597
653
  return PERPS_CONSTANTS.FallbackPercentageDisplay;
598
654
  }
599
655
  return `${_formatSignedDecimal(formatters, parsed, {
600
- minimumFractionDigits: decimals,
656
+ minimumFractionDigits: stripTrailingZeros ? 0 : decimals,
601
657
  maximumFractionDigits: decimals,
602
658
  useGrouping: true,
603
659
  sign,
@@ -640,4 +696,364 @@ export const formatFundingRate = (value, options = {}) => {
640
696
  sign,
641
697
  })}%`;
642
698
  };
699
+ /**
700
+ * Formats a fee rate in basis points with the locale's separators.
701
+ *
702
+ * @param rate - Fee rate as a decimal (0.00045 for 0.045%).
703
+ * @param options - `formatters` (default `en-US`), `decimals` (at most,
704
+ * default `PERPS_DISPLAY_PRECISION.FeeBps`, 2; trailing zeros are dropped) and
705
+ * `sign` (default `auto`).
706
+ * @returns Format: "X.XX bps", or `PERPS_CONSTANTS.FallbackDataDisplay` (`--`)
707
+ * for a missing rate.
708
+ * @example formatFeeBps(0.00045) => "4.5 bps"
709
+ * @example formatFeeBps(0.000144) => "1.44 bps"
710
+ * @example formatFeeBps(0.0007) => "7 bps"
711
+ * @example formatFeeBps(0.00045, { formatters: createFormatters({ locale: 'de' }) }) => "4,5 bps"
712
+ * @example formatFeeBps(undefined) => "--"
713
+ */
714
+ export const formatFeeBps = (rate, options = {}) => {
715
+ const { formatters = _fallbackFormatters, decimals = PERPS_DISPLAY_PRECISION.FeeBps, sign = 'auto', } = options;
716
+ const parsed = _parseDisplayNumber(rate);
717
+ if (parsed === undefined) {
718
+ return PERPS_CONSTANTS.FallbackDataDisplay;
719
+ }
720
+ return `${_formatSignedDecimal(formatters, parsed * BASIS_POINTS_DIVISOR, {
721
+ minimumFractionDigits: 0,
722
+ maximumFractionDigits: decimals,
723
+ useGrouping: true,
724
+ sign,
725
+ })} bps`;
726
+ };
727
+ /**
728
+ * Formats how far, in percent of the entry price, the price must move to
729
+ * reach the liquidation price.
730
+ *
731
+ * @param entryPrice - Entry (or mark) price.
732
+ * @param liquidationPrice - Liquidation price.
733
+ * @param options - `formatters` (default `en-US`), `decimals` (default
734
+ * `PERPS_DISPLAY_PRECISION.LiquidationDistancePercent`, 2) and `sign`
735
+ * (default `never`).
736
+ * @returns Format: "X.XX%", or `PERPS_CONSTANTS.FallbackPercentageDisplay`
737
+ * (`--%`) when either price is missing or not positive.
738
+ * @example formatLiquidationDistance(100, 70) => "30.00%"
739
+ * @example formatLiquidationDistance(100, '130') => "30.00%"
740
+ * @example formatLiquidationDistance(100, 70, { formatters: createFormatters({ locale: 'de' }) }) => "30,00%"
741
+ * @example formatLiquidationDistance(100, undefined) => "--%"
742
+ */
743
+ export const formatLiquidationDistance = (entryPrice, liquidationPrice, options = {}) => {
744
+ const entry = _parseDisplayNumber(entryPrice);
745
+ const liquidation = _parseDisplayNumber(liquidationPrice);
746
+ if (entry === undefined ||
747
+ liquidation === undefined ||
748
+ entry <= 0 ||
749
+ liquidation <= 0) {
750
+ return PERPS_CONSTANTS.FallbackPercentageDisplay;
751
+ }
752
+ return formatPercentage((Math.abs(entry - liquidation) / entry) * 100, {
753
+ formatters: options.formatters,
754
+ decimals: options.decimals ?? PERPS_DISPLAY_PRECISION.LiquidationDistancePercent,
755
+ sign: options.sign ?? 'never',
756
+ });
757
+ };
758
+ /** Each magnitude scale is this many times the next smaller one. */
759
+ const SCALE_STEP = 1000;
760
+ /** Magnitude scales of compact values, largest first. */
761
+ const COMPACT_SCALES = [
762
+ { divisor: 1_000_000_000_000, suffix: 'T' },
763
+ { divisor: 1_000_000_000, suffix: 'B' },
764
+ { divisor: 1_000_000, suffix: 'M' },
765
+ { divisor: SCALE_STEP, suffix: 'K' },
766
+ { divisor: 1, suffix: '' },
767
+ ];
768
+ /**
769
+ * Picks the magnitude scale of a non-negative amount and rounds it. A
770
+ * mantissa that rounds up to 1000 moves to the next scale, so 999999 shows as
771
+ * `1.00M`, not `1000K`.
772
+ *
773
+ * @param amount - Non-negative amount.
774
+ * @param decimalsFor - Fraction digits shown at a scale divisor.
775
+ * @returns The rounded mantissa, its decimals and suffix.
776
+ */
777
+ function _scaleCompact(amount, decimalsFor) {
778
+ let index = COMPACT_SCALES.findIndex(({ divisor }) => amount >= divisor);
779
+ if (index === -1) {
780
+ index = COMPACT_SCALES.length - 1;
781
+ }
782
+ for (;;) {
783
+ const { divisor, suffix } = COMPACT_SCALES[index];
784
+ const decimals = decimalsFor(divisor);
785
+ const mantissa = _roundedMagnitude(amount / divisor, decimals);
786
+ if (mantissa < SCALE_STEP || index === 0) {
787
+ return { mantissa, decimals, suffix };
788
+ }
789
+ index -= 1;
790
+ }
791
+ }
792
+ /**
793
+ * Formats a large number with a magnitude suffix (`K`, `M`, `B`, `T`), with
794
+ * the unit and precision of the field it shows.
795
+ *
796
+ * @param value - Raw value (USD for `volume` and `orderBookUsd`, base asset
797
+ * for `orderBookSize`).
798
+ * @param options - Formatting options.
799
+ * @param options.field - `volume`, `orderBookUsd` or `orderBookSize`.
800
+ * @param options.formatters - Locale-bound formatters, e.g. `createFormatters({ locale })` from `@metamask/client-utils` (default `en-US`).
801
+ * @param options.decimals - Decimals of abbreviated values, overriding the
802
+ * field's `PERPS_DISPLAY_PRECISION` (`VolumeCompact`, `VolumeCompactThousands`
803
+ * or `OrderBookCompact`).
804
+ * @param options.sign - Sign display (default `auto`).
805
+ * @param options.szDecimals - Asset size decimals for an `orderBookSize` value below 1,000.
806
+ * @returns The compact value, or `PERPS_CONSTANTS.FallbackPriceDisplay`
807
+ * (`$---`, `--` for `orderBookSize`) for a missing value.
808
+ * @example formatPerpsCompact(1234567, { field: 'volume' }) => "$1.23M"
809
+ * @example formatPerpsCompact(123456, { field: 'volume' }) => "$123K"
810
+ * @example formatPerpsCompact(999.5, { field: 'volume' }) => "$999.50"
811
+ * @example formatPerpsCompact(1234567, { field: 'volume', formatters: createFormatters({ locale: 'de' }) }) => "1,23M $"
812
+ * @example formatPerpsCompact(2100, { field: 'orderBookUsd' }) => "$2.1K"
813
+ * @example formatPerpsCompact(604900, { field: 'orderBookSize' }) => "604.9K"
814
+ */
815
+ export const formatPerpsCompact = (value, options) => {
816
+ const { field, formatters = _fallbackFormatters, decimals, sign = 'auto', szDecimals, } = options;
817
+ const isUsd = field !== 'orderBookSize';
818
+ const parsed = _parseDisplayNumber(value);
819
+ if (parsed === undefined) {
820
+ return isUsd
821
+ ? PERPS_CONSTANTS.FallbackPriceDisplay
822
+ : PERPS_CONSTANTS.FallbackDataDisplay;
823
+ }
824
+ const amount = Math.abs(parsed);
825
+ if (field !== 'volume' && amount < SCALE_STEP) {
826
+ return field === 'orderBookUsd'
827
+ ? formatPerpsFiat(parsed, {
828
+ ranges: PRICE_RANGES_UNIVERSAL,
829
+ formatters,
830
+ sign,
831
+ })
832
+ : formatPositionSize(parsed, { decimals: szDecimals, formatters, sign });
833
+ }
834
+ const scaled = _scaleCompact(amount, (divisor) => {
835
+ if (decimals !== undefined) {
836
+ return decimals;
837
+ }
838
+ if (field !== 'volume') {
839
+ return PERPS_DISPLAY_PRECISION.OrderBookCompact;
840
+ }
841
+ return divisor === SCALE_STEP
842
+ ? PERPS_DISPLAY_PRECISION.VolumeCompactThousands
843
+ : PERPS_DISPLAY_PRECISION.VolumeCompact;
844
+ });
845
+ return `${_signPrefix(parsed, scaled.mantissa === 0, sign)}${_formatScaledUsd(formatters, scaled.mantissa, { decimals: scaled.decimals, suffix: scaled.suffix, symbol: isUsd })}`;
846
+ };
847
+ /**
848
+ * Exact decimal places of a number, read from its exponential form so values
849
+ * such as `1e-7` and `0.002` do not depend on a rounded `Math.log10`.
850
+ *
851
+ * @param value - The number.
852
+ * @returns Its decimal places.
853
+ */
854
+ function _countDecimalPlaces(value) {
855
+ const [mantissa, exponent] = Math.abs(value).toExponential().split('e');
856
+ return Math.max(0, (mantissa.split('.')[1] ?? '').length - Number(exponent));
857
+ }
858
+ /**
859
+ * Formats an order book price with the ladder format from
860
+ * `getPerpsOrderBookPriceFormat`, keeping trailing zeros so every row has the
861
+ * same width.
862
+ *
863
+ * @param price - Raw price.
864
+ * @param format - Ladder format, or null for `PRICE_RANGES_UNIVERSAL`.
865
+ * @param options - `formatters` (default `en-US`) and `symbol` (default `true`).
866
+ * @returns The price, or `PERPS_CONSTANTS.FallbackPriceDisplay` (`$---`; `--`
867
+ * without the symbol) for a missing price.
868
+ * @example formatPerpsOrderBookPrice(87000, { divisor: 1000, suffix: 'K', decimals: 0 }) => "$87K"
869
+ * @example formatPerpsOrderBookPrice(33.1, { divisor: 1, suffix: '', decimals: 3 }) => "$33.100"
870
+ * @example formatPerpsOrderBookPrice(87000, { divisor: 1, suffix: '', decimals: 0 }, { symbol: false }) => "87,000"
871
+ */
872
+ export const formatPerpsOrderBookPrice = (price, format, options = {}) => {
873
+ const { formatters = _fallbackFormatters, symbol = true } = options;
874
+ const value = _parseDisplayNumber(price);
875
+ if (value === undefined) {
876
+ return symbol
877
+ ? PERPS_CONSTANTS.FallbackPriceDisplay
878
+ : PERPS_CONSTANTS.FallbackDataDisplay;
879
+ }
880
+ if (format === null) {
881
+ return formatPerpsFiat(value, {
882
+ ranges: PRICE_RANGES_UNIVERSAL,
883
+ formatters,
884
+ symbol,
885
+ });
886
+ }
887
+ const amount = Math.abs(value) / format.divisor;
888
+ return `${_signPrefix(value, _currencyShowsZero(amount, format.decimals), 'auto')}${_formatScaledUsd(formatters, amount, {
889
+ decimals: format.decimals,
890
+ suffix: format.suffix,
891
+ symbol,
892
+ })}`;
893
+ };
894
+ /**
895
+ * Resolves the one price format an order book ladder renders with, from the
896
+ * selected price grouping (tick) increment.
897
+ *
898
+ * Decimals match the grouping, capped at the asset's price precision
899
+ * (`PERPS_DISPLAY_PRECISION.MaxPriceDecimals − szDecimals`), so neighbouring
900
+ * levels never collapse into the same string and every row has the same
901
+ * width. The ladder is abbreviated (`$87K`) at the magnitude of `midPrice`
902
+ * only when that needs at most
903
+ * `PERPS_DISPLAY_PRECISION.OrderBookAbbreviatedPriceMax` decimals and is no
904
+ * longer than the plain form.
905
+ *
906
+ * @param grouping - Selected price grouping increment, or null when unknown.
907
+ * @param options - Ladder context.
908
+ * @param options.midPrice - Ladder mid price, which sets the magnitude.
909
+ * @param options.szDecimals - Asset size decimals from the market metadata.
910
+ * @returns The ladder format, or null to use `PRICE_RANGES_UNIVERSAL`.
911
+ * @example getPerpsOrderBookPriceFormat(1000, { midPrice: 87000, szDecimals: 5 }) => { divisor: 1000, suffix: 'K', decimals: 0 }
912
+ * @example getPerpsOrderBookPriceFormat(1, { midPrice: 87000, szDecimals: 5 }) => { divisor: 1, suffix: '', decimals: 0 }
913
+ * @example getPerpsOrderBookPriceFormat(0.001, { midPrice: 33.1, szDecimals: 2 }) => { divisor: 1, suffix: '', decimals: 3 }
914
+ */
915
+ export const getPerpsOrderBookPriceFormat = (grouping, options = {}) => {
916
+ const { midPrice, szDecimals } = options;
917
+ if (typeof grouping !== 'number' ||
918
+ !Number.isFinite(grouping) ||
919
+ grouping <= 0) {
920
+ return null;
921
+ }
922
+ const maxDecimals = typeof szDecimals === 'number' && Number.isFinite(szDecimals)
923
+ ? Math.max(0, PERPS_DISPLAY_PRECISION.MaxPriceDecimals - szDecimals)
924
+ : PERPS_DISPLAY_PRECISION.MaxPriceDecimals;
925
+ const plain = {
926
+ divisor: 1,
927
+ suffix: '',
928
+ decimals: Math.min(_countDecimalPlaces(grouping), maxDecimals),
929
+ };
930
+ if (typeof midPrice !== 'number' || !Number.isFinite(midPrice)) {
931
+ return plain;
932
+ }
933
+ const magnitude = Math.abs(midPrice);
934
+ const scale = COMPACT_SCALES.find(({ divisor }) => divisor > 1 && magnitude >= divisor && magnitude < divisor * SCALE_STEP);
935
+ if (!scale) {
936
+ return plain;
937
+ }
938
+ const decimals = _countDecimalPlaces(grouping / scale.divisor);
939
+ if (decimals > PERPS_DISPLAY_PRECISION.OrderBookAbbreviatedPriceMax) {
940
+ return plain;
941
+ }
942
+ const abbreviated = {
943
+ divisor: scale.divisor,
944
+ suffix: scale.suffix,
945
+ decimals,
946
+ };
947
+ return formatPerpsOrderBookPrice(midPrice, abbreviated).length <=
948
+ formatPerpsOrderBookPrice(midPrice, plain).length
949
+ ? abbreviated
950
+ : plain;
951
+ };
952
+ /** Most digits a USD input keeps exact when grouped through a number. */
953
+ const MAX_EXACT_INPUT_DIGITS = 15;
954
+ /** Separators and digits per formatter set, read once. */
955
+ const _localeSymbolsCache = new WeakMap();
956
+ /**
957
+ * Reads the decimal separator, grouping separator and digits of a locale from
958
+ * formatted samples, without `formatToParts`.
959
+ *
960
+ * @param formatters - Locale-bound formatters.
961
+ * @returns The locale's number symbols.
962
+ */
963
+ function _getLocaleNumberSymbols(formatters) {
964
+ let symbols = _localeSymbolsCache.get(formatters);
965
+ if (!symbols) {
966
+ // "1234567890" in the locale's digits: glyph of 1, 2, ..., 9, 0
967
+ const sample = Array.from(formatters.formatNumber(1234567890, { useGrouping: false }));
968
+ symbols = {
969
+ decimal: Array.from(formatters.formatNumber(1.5, {
970
+ minimumFractionDigits: 1,
971
+ maximumFractionDigits: 1,
972
+ }))
973
+ .slice(1, -1)
974
+ .join(''),
975
+ grouping: Array.from(formatters.formatNumber(10000))
976
+ .slice(2, -3)
977
+ .join(''),
978
+ digits: sample.length === 10
979
+ ? [sample[9], ...sample.slice(0, 9)]
980
+ : Array.from('0123456789'),
981
+ };
982
+ _localeSymbolsCache.set(formatters, symbols);
983
+ }
984
+ return symbols;
985
+ }
986
+ /**
987
+ * Masks a USD amount input: keeps digits and one decimal separator, drops
988
+ * leading zeros, caps the decimals and the number of digits, and groups the
989
+ * integer part for the locale. Passing `display` back in with the next
990
+ * keystroke returns the same amount.
991
+ *
992
+ * Typed text reads the locale's decimal separator as the decimal. A `.` also
993
+ * reads as the decimal where the locale uses `.` for neither (`fr`: `12.5` is
994
+ * 12.5); where `.` groups thousands (`de`, `es`), it stays a separator, so
995
+ * `1.2345` is 12345.
996
+ *
997
+ * @param input - Typed text, or a stored canonical value with `source: 'value'`.
998
+ * @param options - `formatters` (default `en-US`), `decimals` (default
999
+ * `PERPS_DISPLAY_PRECISION.UsdInput`, 2), `maxDigits` (default
1000
+ * `PERPS_DISPLAY_PRECISION.UsdInputMaxDigits`, 9) and `source` (default
1001
+ * `typed`).
1002
+ * @returns The canonical `value` and the locale `display`; both are empty for
1003
+ * input without digits.
1004
+ * @example formatPerpsUsdInput('0012.345') => { value: '12.34', display: '12.34' }
1005
+ * @example formatPerpsUsdInput('1234.') => { value: '1234.', display: '1,234.' }
1006
+ * @example formatPerpsUsdInput('1.2345', { formatters: createFormatters({ locale: 'de' }) }) => { value: '12345', display: '12.345' }
1007
+ * @example formatPerpsUsdInput('1234567.5', { formatters: createFormatters({ locale: 'de' }), source: 'value' }) => { value: '1234567.5', display: '1.234.567,5' }
1008
+ */
1009
+ export const formatPerpsUsdInput = (input, options = {}) => {
1010
+ const { formatters = _fallbackFormatters, decimals = PERPS_DISPLAY_PRECISION.UsdInput, maxDigits: requestedMaxDigits = PERPS_DISPLAY_PRECISION.UsdInputMaxDigits, source = 'typed', } = options;
1011
+ const maxDigits = Math.min(requestedMaxDigits, MAX_EXACT_INPUT_DIGITS);
1012
+ const symbols = _getLocaleNumberSymbols(formatters);
1013
+ const text = Array.from(input, (character) => {
1014
+ const digit = symbols.digits.indexOf(character);
1015
+ return digit === -1 ? character : String(digit);
1016
+ }).join('');
1017
+ let decimalSeparator;
1018
+ if (source === 'value') {
1019
+ decimalSeparator = '.';
1020
+ }
1021
+ else if (symbols.decimal && text.includes(symbols.decimal)) {
1022
+ decimalSeparator = symbols.decimal;
1023
+ }
1024
+ else if (symbols.grouping !== '.') {
1025
+ decimalSeparator = '.';
1026
+ }
1027
+ let integer = '';
1028
+ let fraction = '';
1029
+ let seenDecimal = false;
1030
+ for (const character of text) {
1031
+ if (character === decimalSeparator && !seenDecimal) {
1032
+ seenDecimal = true;
1033
+ }
1034
+ else if (character >= '0' && character <= '9') {
1035
+ if (seenDecimal) {
1036
+ fraction += character;
1037
+ }
1038
+ else {
1039
+ integer += character;
1040
+ }
1041
+ }
1042
+ }
1043
+ const hasDecimal = seenDecimal && decimals > 0;
1044
+ if (!integer && !hasDecimal) {
1045
+ return { value: '', display: '' };
1046
+ }
1047
+ integer = integer.replace(/^0+(?=\d)/u, '') || '0';
1048
+ integer = integer.slice(0, maxDigits);
1049
+ fraction = fraction.slice(0, Math.max(0, Math.min(decimals, maxDigits - integer.length)));
1050
+ const fractionText = hasDecimal ? `.${fraction}` : '';
1051
+ const localizedFraction = Array.from(fraction, (digit) => symbols.digits[Number(digit)]).join('');
1052
+ return {
1053
+ value: `${integer}${fractionText}`,
1054
+ display: `${formatters.formatNumber(Number(integer), {
1055
+ maximumFractionDigits: 0,
1056
+ })}${hasDecimal ? `${symbols.decimal}${localizedFraction}` : ''}`,
1057
+ };
1058
+ };
643
1059
  //# sourceMappingURL=perpsFormatters.js.map