Skip to content

Commit d74f49e

Browse files
authored
Update usage of Intl.NumberFormat options (#1791)
# Pull Request ## 🀨 Rationale Fixes: #1442 ## πŸ‘©β€πŸ’» Implementation The options cited in the issue are: - `useGrouping: 'auto'` - We previously were setting this to `true`, which means "display grouping separators even if the locale prefers otherwise." Instead we want `"auto"`, which is "display grouping separators based on the locale preference." The default for this option is `"auto"` unless `notation` is `"compact"`. We never set `notation` to `"compact"`, so we can just leave `useGrouping` to use the default. - `signDisplay: 'negative'` - Though this option value has been [supported in all browsers since 8/23](https://caniuse.com/mdn-javascript_builtins_intl_numberformat_numberformat_options_signdisplay_parameter_negative), there does not seem to be a version of Typescript whose definition of `Intl.NumberFormatOptions` allows it. There is an [open issue for adding support](microsoft/TypeScript#56269). As a workaround, I've just added type assertions where necessary. - `roundingPriority: 'lessPrecision'` - Just like `signDisplay: 'negative'`, the `roundingPriority` option has been [supported in browsers since 8/23](https://caniuse.com/mdn-javascript_builtins_intl_numberformat_numberformat_options_roundingpriority_parameter), but Typescript doesn't have support yet. It is tracked by the same issue linked above, and our type assertion serves as a workaround for this, too. By using this option, we can get rid of the separate `leadingZeroFormatter` in `DefaultUnitFormat` and simplify the logic. ## πŸ§ͺ Testing Existing tests pass. ## βœ… Checklist - [x] I have updated the project documentation to reflect my changes or determined no changes are needed.
1 parent f2d6322 commit d74f49e

11 files changed

Lines changed: 123 additions & 179 deletions
Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
{
2+
"type": "patch",
3+
"comment": "Update usage of Intl.NumberFormat options",
4+
"packageName": "@ni/nimble-components",
5+
"email": "[email protected]",
6+
"dependentChangeType": "patch"
7+
}

β€Žpackages/nimble-components/src/dialog/index.tsβ€Ž

Lines changed: 1 addition & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -17,16 +17,6 @@ declare global {
1717
}
1818
}
1919

20-
/**
21-
* This is a workaround for an incomplete definition of the native dialog element. Remove when using Typescript >=4.8.3.
22-
* https://github.com/microsoft/TypeScript/issues/48267
23-
* @internal
24-
*/
25-
export interface ExtendedDialog extends HTMLDialogElement {
26-
showModal(): void;
27-
close(): void;
28-
}
29-
3020
/**
3121
* A nimble-styled dialog.
3222
*/
@@ -65,7 +55,7 @@ export class Dialog<CloseReason = void> extends FoundationElement {
6555
*
6656
* @internal
6757
*/
68-
public readonly dialogElement!: ExtendedDialog;
58+
public readonly dialogElement!: HTMLDialogElement;
6959

7060
/** @internal */
7161
@observable

β€Žpackages/nimble-components/src/dialog/tests/dialog.spec.tsβ€Ž

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import { html } from '@microsoft/fast-element';
22
import { fixture, Fixture } from '../../utilities/tests/fixture';
3-
import { Dialog, dialogTag, ExtendedDialog, UserDismissed } from '..';
3+
import { Dialog, dialogTag, UserDismissed } from '..';
44
import { waitForUpdatesAsync } from '../../testing/async-helpers';
55

66
// eslint-disable-next-line @typescript-eslint/no-invalid-void-type
@@ -19,10 +19,10 @@ async function setup<CloseReason = void>(
1919
}
2020

2121
describe('Dialog', () => {
22-
function nativeDialogElement(nimbleDialogElement: Dialog): ExtendedDialog {
23-
return nimbleDialogElement.shadowRoot!.querySelector(
24-
'dialog'
25-
) as ExtendedDialog;
22+
function nativeDialogElement(
23+
nimbleDialogElement: Dialog
24+
): HTMLDialogElement {
25+
return nimbleDialogElement.shadowRoot!.querySelector('dialog')!;
2626
}
2727

2828
it('should export its tag', () => {

β€Žpackages/nimble-components/src/drawer/index.tsβ€Ž

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,6 @@ import {
66
FoundationElement
77
} from '@microsoft/fast-foundation';
88
import { eventAnimationEnd } from '@microsoft/fast-web-utilities';
9-
import type { ExtendedDialog } from '../dialog';
109
import { UserDismissed } from '../patterns/dialog/types';
1110
import { styles } from './styles';
1211
import { template } from './template';
@@ -36,7 +35,7 @@ export class Drawer<CloseReason = void> extends FoundationElement {
3635
@attr({ attribute: 'prevent-dismiss', mode: 'boolean' })
3736
public preventDismiss = false;
3837

39-
public dialog!: ExtendedDialog;
38+
public dialog!: HTMLDialogElement;
4039
private closing = false;
4140

4241
private resolveShow?: (reason: CloseReason | UserDismissed) => void;
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
// This file has modifications to global types used for nimble-components builds:
2+
// - The types file should not be in the build output
3+
// - You should not see a file with these types created in the dist build
4+
// - Type additions added to this file should not appear in any public API definitions
5+
// - The fields added to global types should not be observable in any built .d.ts file by TypeScript. To verify you can do a text search of generated .d.ts files in the dist folder for the fields being added and verify they are not associated with the augmented types.
6+
// - This file should only impact the nimble-components library build and not users of nimble-components. Any type changes that impact clients should not be placed here.
7+
8+
/**
9+
* This is a workaround for an incomplete definition of the native dialog element. Remove when using Typescript >=4.8.3.
10+
* https://github.com/microsoft/TypeScript/issues/48267
11+
* @internal
12+
*/
13+
interface HTMLDialogElement {
14+
showModal(): void;
15+
close(returnValue?: string): void;
16+
}
17+
18+
declare namespace Intl {
19+
// roundingPriority has been supported by browsers since 8/23, but TypeScript still hasn't
20+
// added it to the type definition. See https://github.com/microsoft/TypeScript/issues/56269
21+
interface NumberFormatOptions {
22+
roundingPriority?:
23+
| 'auto'
24+
| 'morePrecision'
25+
| 'lessPrecision'
26+
| undefined;
27+
}
28+
}

β€Žpackages/nimble-components/src/table-column/number-text/tests/table-column-number-text-matrix.stories.tsβ€Ž

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,7 @@ const data = [
3030
},
3131
{
3232
id: '1',
33-
number: -9.54021
33+
number: -9.5402111111
3434
},
3535
{
3636
id: '2'

β€Žpackages/nimble-components/src/utilities/unit-format/decimal-unit-format.tsβ€Ž

Lines changed: 6 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,6 @@ export class DecimalUnitFormat extends UnitFormat<DecimalUnitFormatOptions> {
1818
private readonly maximumFractionDigits: number;
1919

2020
private readonly scaledUnitFormatters = new Map<number, ScaledUnitFormat>();
21-
private readonly tenPowDecimalDigits: number;
2221

2322
public constructor(
2423
locale: string,
@@ -33,10 +32,14 @@ export class DecimalUnitFormat extends UnitFormat<DecimalUnitFormatOptions> {
3332
}
3433
) {
3534
super();
35+
// Workaround to avoid a ts error about signDisplay not accepting the value 'negative'.
36+
// It has been supported by browsers since 8/23, but TypeScript still hasn't
37+
// added it to the type definitions. See https://github.com/microsoft/TypeScript/issues/56269
38+
const signDisplay = 'negative' as Intl.NumberFormatOptions['signDisplay'];
3639
const intlNumberFormatOptions = {
3740
maximumFractionDigits,
3841
minimumFractionDigits,
39-
useGrouping: true
42+
signDisplay
4043
};
4144
for (const scaledUnit of unitScale.supportedScaledUnits) {
4245
this.scaledUnitFormatters.set(
@@ -47,7 +50,6 @@ export class DecimalUnitFormat extends UnitFormat<DecimalUnitFormatOptions> {
4750
})
4851
);
4952
}
50-
this.tenPowDecimalDigits = 10 ** maximumFractionDigits;
5153
this.unitScale = unitScale;
5254
this.minimumFractionDigits = minimumFractionDigits;
5355
this.maximumFractionDigits = maximumFractionDigits;
@@ -63,19 +65,9 @@ export class DecimalUnitFormat extends UnitFormat<DecimalUnitFormatOptions> {
6365

6466
protected tryFormat(number: number): string {
6567
const { scaledValue, scaledUnit } = this.unitScale.scaleNumber(number);
66-
67-
const numberNormalized = this.willRoundToZero(scaledValue)
68-
? 0
69-
: scaledValue;
7068
const scaledUnitFormatter = this.scaledUnitFormatters.get(
7169
scaledUnit.scaleFactor
7270
)!;
73-
return scaledUnitFormatter.format(numberNormalized);
74-
}
75-
76-
private willRoundToZero(number: number): boolean {
77-
// Multiply the value by 10 raised to maximumFractionDigits so that Math.round can be used to emulate rounding to
78-
// maximumFractionDigits decimal places. If that rounded value is 0, then the value will be rendered with only 0s.
79-
return Math.round(number * this.tenPowDecimalDigits) === 0;
71+
return scaledUnitFormatter.format(scaledValue);
8072
}
8173
}

β€Žpackages/nimble-components/src/utilities/unit-format/default-unit-format.tsβ€Ž

Lines changed: 21 additions & 73 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,10 @@ import type { ScaledUnitFormat } from './scaled-unit-format/scaled-unit-format';
33
import type { UnitScale } from './unit-scale/unit-scale';
44
import { passthroughUnitScale } from './unit-scale/passthrough-unit-scale';
55

6-
type NumberStyle = 'default' | 'leadingZero' | 'exponential';
6+
// Workaround to avoid ts errors about signDisplay not accepting the value 'negative'.
7+
// It has been supported by browsers since 8/23, but TypeScript still hasn't
8+
// added it to the type definitions. See https://github.com/microsoft/TypeScript/issues/56269
9+
const signDisplay = 'negative' as Intl.NumberFormatOptions['signDisplay'];
710

811
// Allow consistent pattern for defining Options and ResolvedOptions
912
// eslint-disable-next-line @typescript-eslint/no-empty-interface
@@ -28,27 +31,15 @@ export class DefaultUnitFormat extends UnitFormat {
2831
private static readonly exponentialUpperBound = 999999.5;
2932

3033
private readonly unitScale: UnitScale;
31-
32-
// Format options to use by default. It renders the number with a maximum of 6 signficant digits.
34+
// Format options to use by default. It renders the number with a maximum of 6 signficant digits (including zero before decimal point).
3335
private readonly defaultIntlNumberFormatOptions: Intl.NumberFormatOptions = {
3436
maximumSignificantDigits: DefaultUnitFormat.maximumDigits,
35-
useGrouping: true
36-
};
37-
38-
private readonly defaultScaledUnitFormatters = new Map<
39-
number,
40-
ScaledUnitFormat
41-
>();
42-
43-
// Format options to use for numbers that have leading zeros. It limits the number of rendered
44-
// digits using 'maximumFractionDigits', which will result in less than 6 significant digits
45-
// in order to render no more than 6 total digits.
46-
private readonly leadingZeroIntlNumberFormatOptions: Intl.NumberFormatOptions = {
4737
maximumFractionDigits: DefaultUnitFormat.maximumDigits - 1,
48-
useGrouping: true
38+
roundingPriority: 'lessPrecision',
39+
signDisplay
4940
};
5041

51-
private readonly leadingZeroScaledUnitFormatters = new Map<
42+
private readonly defaultScaledUnitFormatters = new Map<
5243
number,
5344
ScaledUnitFormat
5445
>();
@@ -57,7 +48,8 @@ export class DefaultUnitFormat extends UnitFormat {
5748
// for numbers with magintudes over 'exponentialUpperBound' or under 'exponentialLowerBound'.
5849
private readonly exponentialIntlNumberFormatOptions: Intl.NumberFormatOptions = {
5950
maximumSignificantDigits: DefaultUnitFormat.maximumDigits,
60-
notation: 'scientific'
51+
notation: 'scientific',
52+
signDisplay
6153
};
6254

6355
private readonly exponentialScaledUnitFormatter: ScaledUnitFormat;
@@ -77,14 +69,6 @@ export class DefaultUnitFormat extends UnitFormat {
7769
intlNumberFormatOptions: this.defaultIntlNumberFormatOptions
7870
})
7971
);
80-
this.leadingZeroScaledUnitFormatters.set(
81-
unit.scaleFactor,
82-
unit.scaledUnitFormatFactory({
83-
locale,
84-
intlNumberFormatOptions:
85-
this.leadingZeroIntlNumberFormatOptions
86-
})
87-
);
8872
}
8973
this.exponentialScaledUnitFormatter = unitScale.baseScaledUnit.scaledUnitFormatFactory({
9074
locale,
@@ -100,52 +84,16 @@ export class DefaultUnitFormat extends UnitFormat {
10084
}
10185

10286
protected tryFormat(number: number): string {
103-
// Normalize +0 / -0 --> +0
104-
const numberNormalized = number === 0 ? 0 : number;
105-
106-
const { scaledValue, scaledUnit } = this.unitScale.scaleNumber(numberNormalized);
107-
108-
const numberStyle = this.resolveNumberStyle(scaledValue);
109-
switch (numberStyle) {
110-
case 'default': {
111-
const scaledUnitFormatter = this.defaultScaledUnitFormatters.get(
112-
scaledUnit.scaleFactor
113-
)!;
114-
return scaledUnitFormatter.format(scaledValue);
115-
}
116-
case 'leadingZero': {
117-
const scaledUnitFormatter = this.leadingZeroScaledUnitFormatters.get(
118-
scaledUnit.scaleFactor
119-
)!;
120-
return scaledUnitFormatter.format(scaledValue);
121-
}
122-
case 'exponential': {
123-
const scaledUnitFormatter = this.exponentialScaledUnitFormatter;
124-
return scaledUnitFormatter.format(numberNormalized);
125-
}
126-
default:
127-
throw new Error('Unexpected number format style');
128-
}
129-
}
130-
131-
private resolveNumberStyle(number: number): NumberStyle {
132-
if (number === 0) {
133-
return 'default';
134-
}
135-
136-
const absoluteValue = Math.abs(number);
137-
if (
138-
absoluteValue >= DefaultUnitFormat.exponentialUpperBound
139-
|| absoluteValue < DefaultUnitFormat.exponentialLowerBound
140-
) {
141-
return 'exponential';
142-
}
143-
// Ideally, we could set 'roundingPriority: "lessPrecision"' with a formatter that has both 'maximumSignificantDigits' and
144-
// 'maximumFractionDigits' configured instead of having two different formatters that we conditionally choose between. However,
145-
// 'roundingPrioirty' is not supported yet in all browsers.
146-
if (absoluteValue < 1) {
147-
return 'leadingZero';
148-
}
149-
return 'default';
87+
const { scaledValue, scaledUnit } = this.unitScale.scaleNumber(number);
88+
89+
const absoluteValue = Math.abs(scaledValue);
90+
const useExponential = absoluteValue !== 0
91+
&& (absoluteValue >= DefaultUnitFormat.exponentialUpperBound
92+
|| absoluteValue < DefaultUnitFormat.exponentialLowerBound);
93+
return useExponential
94+
? this.exponentialScaledUnitFormatter.format(number)
95+
: this.defaultScaledUnitFormatters
96+
.get(scaledUnit.scaleFactor)!
97+
.format(scaledValue);
15098
}
15199
}

0 commit comments

Comments
Β (0)