@discord/intl 0.16.0 → 0.17.0-canary.18e68ab
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.
- package/dist/data-formatters/cache.d.ts +21 -0
- package/dist/data-formatters/cache.js +47 -0
- package/dist/data-formatters/config.d.ts +81 -0
- package/dist/{format-config.js → data-formatters/config.js} +16 -5
- package/dist/data-formatters/index.d.ts +26 -0
- package/dist/data-formatters/index.js +54 -0
- package/dist/format.d.ts +4 -4
- package/dist/format.js +22 -18
- package/dist/formatters/index.d.ts +1 -1
- package/dist/formatters/react.d.ts +30 -1
- package/dist/formatters/react.js +2 -3
- package/dist/index.d.ts +3 -19
- package/dist/index.js +4 -2
- package/dist/intl-manager.d.ts +17 -8
- package/dist/intl-manager.js +13 -13
- package/package.json +3 -2
- package/src/data-formatters/cache.ts +60 -0
- package/src/data-formatters/config.ts +98 -0
- package/src/data-formatters/index.ts +103 -0
- package/src/format.ts +36 -22
- package/src/formatters/index.ts +2 -0
- package/src/formatters/react.ts +42 -7
- package/src/index.ts +3 -22
- package/src/intl-manager.ts +29 -19
- package/dist/format-config.d.ts +0 -17
- package/src/format-config.ts +0 -72
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@discord/intl",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.17.0-canary.18e68ab",
|
|
4
4
|
"license": "MIT",
|
|
5
5
|
"description": "Client runtime for managing messages and translations in a React project.",
|
|
6
6
|
"main": "./dist/index.js",
|
|
@@ -23,9 +23,10 @@
|
|
|
23
23
|
"@formatjs/intl": "^2.10.1",
|
|
24
24
|
"@intrnl/xxhash64": "^0.1.2",
|
|
25
25
|
"intl-messageformat": "^10.5.11",
|
|
26
|
-
"@discord/intl-ast": "0.
|
|
26
|
+
"@discord/intl-ast": "0.17.0"
|
|
27
27
|
},
|
|
28
28
|
"devDependencies": {
|
|
29
|
+
"@formatjs/intl-durationformat": "^0.7.3",
|
|
29
30
|
"@swc/cli": "^0.3.12",
|
|
30
31
|
"@swc/core": "^1.4.11",
|
|
31
32
|
"typescript": "*"
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
import type { DurationFormat as FormatJsDurationFormat } from '@formatjs/intl-durationformat';
|
|
2
|
+
|
|
3
|
+
type Cache<Value> = Map<string, Value>;
|
|
4
|
+
|
|
5
|
+
type TemporaryIntlDurationFormat = typeof FormatJsDurationFormat;
|
|
6
|
+
|
|
7
|
+
class FormatterCache {
|
|
8
|
+
dateTime: Cache<Intl.DateTimeFormat> = new Map();
|
|
9
|
+
duration: Cache<TemporaryIntlDurationFormat> = new Map();
|
|
10
|
+
list: Cache<Intl.ListFormat> = new Map();
|
|
11
|
+
number: Cache<Intl.NumberFormat> = new Map();
|
|
12
|
+
pluralRules: Cache<Intl.PluralRules> = new Map();
|
|
13
|
+
relativeTime: Cache<Intl.RelativeTimeFormat> = new Map();
|
|
14
|
+
|
|
15
|
+
getDateTimeFormatter(...args: ConstructorParameters<typeof Intl.DateTimeFormat>) {
|
|
16
|
+
return this._getCached(this.dateTime, args, (args) => new Intl.DateTimeFormat(...args));
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
getDurationFormatter(...args: ConstructorParameters<TemporaryIntlDurationFormat>) {
|
|
20
|
+
return this._getCached(
|
|
21
|
+
this.duration,
|
|
22
|
+
args,
|
|
23
|
+
// @ts-expect-error DurationFormat is _not_ included in typescript
|
|
24
|
+
// https://github.com/microsoft/TypeScript/issues/60608
|
|
25
|
+
(args) => new Intl.DurationFormat(...args),
|
|
26
|
+
);
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
getListFormatter(...args: ConstructorParameters<typeof Intl.ListFormat>) {
|
|
30
|
+
return this._getCached(this.list, args, (args) => new Intl.ListFormat(...args));
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
getNumberFormatter(...args: ConstructorParameters<typeof Intl.NumberFormat>) {
|
|
34
|
+
return this._getCached(this.number, args, (args) => new Intl.NumberFormat(...args));
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
getPluralRules(...args: ConstructorParameters<typeof Intl.PluralRules>) {
|
|
38
|
+
return this._getCached(this.pluralRules, args, (args) => new Intl.PluralRules(...args));
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
getRelativeTimeFormatter(...args: ConstructorParameters<typeof Intl.RelativeTimeFormat>) {
|
|
42
|
+
return this._getCached(this.relativeTime, args, (args) => new Intl.RelativeTimeFormat(...args));
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
_getCached<T, Args>(cache: Cache<T>, args: Args, constructor: (args: Args) => T): T {
|
|
46
|
+
const key = this._getKey(args);
|
|
47
|
+
const cached = cache.get(key);
|
|
48
|
+
if (cached) return cached;
|
|
49
|
+
|
|
50
|
+
const created = constructor(args);
|
|
51
|
+
cache.set(key, created);
|
|
52
|
+
return created;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
_getKey(...args: any): string {
|
|
56
|
+
return JSON.stringify(args);
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
export const dataFormatterCache = new FormatterCache();
|
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
import type { DurationFormatOptions, DurationInput } from '@formatjs/intl-durationformat/src/types';
|
|
2
|
+
|
|
3
|
+
export type TemporaryDurationInput = DurationInput;
|
|
4
|
+
export type TemporaryDurationFormatOptions = DurationFormatOptions;
|
|
5
|
+
|
|
6
|
+
export interface FormatConfigType {
|
|
7
|
+
date: Record<string, Intl.DateTimeFormatOptions>;
|
|
8
|
+
duration: Record<string, TemporaryDurationFormatOptions>;
|
|
9
|
+
list: Record<string, Intl.ListFormatOptions>;
|
|
10
|
+
number: Record<string, Intl.NumberFormatOptions>;
|
|
11
|
+
relativeTime: Record<string, Intl.RelativeTimeFormatOptions>;
|
|
12
|
+
time: Record<string, Intl.DateTimeFormatOptions>;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
export function resolveFormatConfigOptions<T extends object, const K extends string>(
|
|
16
|
+
config: Record<K, T>,
|
|
17
|
+
style?: T & { format?: K },
|
|
18
|
+
): T {
|
|
19
|
+
if (typeof style?.format === 'string') {
|
|
20
|
+
return {
|
|
21
|
+
...config[style.format],
|
|
22
|
+
...style,
|
|
23
|
+
};
|
|
24
|
+
}
|
|
25
|
+
return style;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export const DEFAULT_FORMAT_CONFIG = {
|
|
29
|
+
// These have no known defaults, so they can't be applied easily.
|
|
30
|
+
duration: {},
|
|
31
|
+
list: {},
|
|
32
|
+
relativeTime: {},
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* Default formatting configuration options for common date, time, and number formats. This is
|
|
36
|
+
* taken almost directly from FormatJS's defaults here, for the sake of compatibility.
|
|
37
|
+
* https://github.com/formatjs/formatjs/blob/c30975bfbe2db7eb62f4dbe6c8ad6ca5e786dcb3/packages/intl-messageformat/src/core.ts#L229-L296
|
|
38
|
+
*/
|
|
39
|
+
number: {
|
|
40
|
+
integer: { maximumFractionDigits: 0 },
|
|
41
|
+
currency: { style: 'currency' },
|
|
42
|
+
percent: { style: 'percent' },
|
|
43
|
+
},
|
|
44
|
+
|
|
45
|
+
date: {
|
|
46
|
+
short: {
|
|
47
|
+
month: 'numeric',
|
|
48
|
+
day: 'numeric',
|
|
49
|
+
year: '2-digit',
|
|
50
|
+
},
|
|
51
|
+
|
|
52
|
+
medium: {
|
|
53
|
+
month: 'short',
|
|
54
|
+
day: 'numeric',
|
|
55
|
+
year: 'numeric',
|
|
56
|
+
},
|
|
57
|
+
|
|
58
|
+
long: {
|
|
59
|
+
month: 'long',
|
|
60
|
+
day: 'numeric',
|
|
61
|
+
year: 'numeric',
|
|
62
|
+
},
|
|
63
|
+
|
|
64
|
+
full: {
|
|
65
|
+
weekday: 'long',
|
|
66
|
+
month: 'long',
|
|
67
|
+
day: 'numeric',
|
|
68
|
+
year: 'numeric',
|
|
69
|
+
},
|
|
70
|
+
},
|
|
71
|
+
|
|
72
|
+
time: {
|
|
73
|
+
short: {
|
|
74
|
+
hour: 'numeric',
|
|
75
|
+
minute: 'numeric',
|
|
76
|
+
},
|
|
77
|
+
|
|
78
|
+
medium: {
|
|
79
|
+
hour: 'numeric',
|
|
80
|
+
minute: 'numeric',
|
|
81
|
+
second: 'numeric',
|
|
82
|
+
},
|
|
83
|
+
|
|
84
|
+
long: {
|
|
85
|
+
hour: 'numeric',
|
|
86
|
+
minute: 'numeric',
|
|
87
|
+
second: 'numeric',
|
|
88
|
+
timeZoneName: 'short',
|
|
89
|
+
},
|
|
90
|
+
|
|
91
|
+
full: {
|
|
92
|
+
hour: 'numeric',
|
|
93
|
+
minute: 'numeric',
|
|
94
|
+
second: 'numeric',
|
|
95
|
+
timeZoneName: 'short',
|
|
96
|
+
},
|
|
97
|
+
},
|
|
98
|
+
} satisfies FormatConfigType;
|
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
import {
|
|
2
|
+
FormatConfigType,
|
|
3
|
+
resolveFormatConfigOptions,
|
|
4
|
+
TemporaryDurationFormatOptions,
|
|
5
|
+
TemporaryDurationInput,
|
|
6
|
+
} from './config';
|
|
7
|
+
import { dataFormatterCache } from './cache';
|
|
8
|
+
|
|
9
|
+
export interface DataFormatters<FormatConfig extends FormatConfigType> {
|
|
10
|
+
formatDate(
|
|
11
|
+
value: number | Date,
|
|
12
|
+
style?: Intl.DateTimeFormatOptions | { format?: keyof FormatConfig['date'] & string },
|
|
13
|
+
): string;
|
|
14
|
+
formatDuration(
|
|
15
|
+
value: TemporaryDurationInput,
|
|
16
|
+
style?: TemporaryDurationFormatOptions | { format?: keyof FormatConfig['duration'] & string },
|
|
17
|
+
): string;
|
|
18
|
+
formatNumber(
|
|
19
|
+
value: number,
|
|
20
|
+
style?: Intl.NumberFormatOptions | { format?: keyof FormatConfig['number'] & string },
|
|
21
|
+
): string;
|
|
22
|
+
formatList(
|
|
23
|
+
values: any[],
|
|
24
|
+
style?: Intl.ListFormatOptions | { format?: keyof FormatConfig['list'] & string },
|
|
25
|
+
): string;
|
|
26
|
+
formatListToParts<T>(
|
|
27
|
+
values: T[],
|
|
28
|
+
style?: Intl.ListFormatOptions | { format?: keyof FormatConfig['list'] & string },
|
|
29
|
+
): Array<T | string>;
|
|
30
|
+
formatRelativeTime(
|
|
31
|
+
value: number,
|
|
32
|
+
unit: Intl.RelativeTimeFormatUnit,
|
|
33
|
+
style?:
|
|
34
|
+
| Intl.RelativeTimeFormatOptions
|
|
35
|
+
| { format?: keyof FormatConfig['relativeTime'] & string },
|
|
36
|
+
): string;
|
|
37
|
+
formatTime(
|
|
38
|
+
value: number | Date,
|
|
39
|
+
style?: Intl.DateTimeFormatOptions | { format?: keyof FormatConfig['time'] & string },
|
|
40
|
+
): string;
|
|
41
|
+
getPluralRules(options: Intl.PluralRulesOptions): Intl.PluralRules;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
export function makeDataFormatters<const FormatConfig extends FormatConfigType>(
|
|
45
|
+
locales: string[],
|
|
46
|
+
formatConfig: FormatConfig,
|
|
47
|
+
): DataFormatters<FormatConfig> {
|
|
48
|
+
return {
|
|
49
|
+
formatDate(value, style) {
|
|
50
|
+
const options = resolveFormatConfigOptions(formatConfig.date, style);
|
|
51
|
+
return dataFormatterCache.getDateTimeFormatter(locales, options).format(value);
|
|
52
|
+
},
|
|
53
|
+
|
|
54
|
+
formatDuration(value, style) {
|
|
55
|
+
const options = resolveFormatConfigOptions(formatConfig.time, style);
|
|
56
|
+
return dataFormatterCache.getDurationFormatter(locales, options).format(value);
|
|
57
|
+
},
|
|
58
|
+
|
|
59
|
+
formatNumber(value, style) {
|
|
60
|
+
const options = resolveFormatConfigOptions(formatConfig.number, style);
|
|
61
|
+
return dataFormatterCache.getNumberFormatter(locales, options).format(value);
|
|
62
|
+
},
|
|
63
|
+
|
|
64
|
+
formatList(values, style) {
|
|
65
|
+
const options = resolveFormatConfigOptions(formatConfig.list, style);
|
|
66
|
+
return dataFormatterCache.getListFormatter(locales, options).format(values);
|
|
67
|
+
},
|
|
68
|
+
|
|
69
|
+
formatListToParts(values, style) {
|
|
70
|
+
const options = resolveFormatConfigOptions(formatConfig.list, style);
|
|
71
|
+
// Intl.ListFormat only accepts string arguments, even for `formatToParts`,
|
|
72
|
+
// but we want to support formatting of complex values like React nodes as
|
|
73
|
+
// part of a list (think an "and more" link at the end of a list).
|
|
74
|
+
//
|
|
75
|
+
// To enable that, we make placeholders with hopefully-unusable sentinel
|
|
76
|
+
// values that can be passed to `formatToParts`, then after the formatting
|
|
77
|
+
// we map the original values back into the parts.
|
|
78
|
+
const placeholders = {};
|
|
79
|
+
for (const index in values) {
|
|
80
|
+
placeholders['$+/-$placeholder.' + index] = values[index];
|
|
81
|
+
}
|
|
82
|
+
const parts = dataFormatterCache
|
|
83
|
+
.getListFormatter(locales, options)
|
|
84
|
+
.formatToParts(Object.keys(placeholders));
|
|
85
|
+
|
|
86
|
+
return parts.map((part) => (part.value = placeholders[part.value] ?? part.value));
|
|
87
|
+
},
|
|
88
|
+
|
|
89
|
+
formatRelativeTime(value, unit, style) {
|
|
90
|
+
const options = resolveFormatConfigOptions(formatConfig.relativeTime, style);
|
|
91
|
+
return dataFormatterCache.getRelativeTimeFormatter(locales, options).format(value, unit);
|
|
92
|
+
},
|
|
93
|
+
|
|
94
|
+
formatTime(value, style) {
|
|
95
|
+
const options = resolveFormatConfigOptions(formatConfig.time, style);
|
|
96
|
+
return dataFormatterCache.getDateTimeFormatter(locales, options).format(value);
|
|
97
|
+
},
|
|
98
|
+
|
|
99
|
+
getPluralRules(options) {
|
|
100
|
+
return dataFormatterCache.getPluralRules(locales, options);
|
|
101
|
+
},
|
|
102
|
+
};
|
|
103
|
+
}
|
package/src/format.ts
CHANGED
|
@@ -24,9 +24,9 @@ import {
|
|
|
24
24
|
} from '@formatjs/icu-skeleton-parser';
|
|
25
25
|
|
|
26
26
|
import { AstNode, AstNodeIndices, FormatJsNodeType } from '@discord/intl-ast';
|
|
27
|
-
import { Formatters, MissingValueError } from 'intl-messageformat';
|
|
28
|
-
import type { FormatConfig } from './format-config';
|
|
29
27
|
import type { RichTextTagNames } from './types';
|
|
28
|
+
import { FormatConfigType } from './data-formatters/config';
|
|
29
|
+
import { DataFormatters } from './data-formatters';
|
|
30
30
|
|
|
31
31
|
/**
|
|
32
32
|
* Returns true if the tag name should be considered a rich text tag that
|
|
@@ -43,17 +43,30 @@ export abstract class FormatBuilder<Result, ObjectType = Result extends object ?
|
|
|
43
43
|
abstract finish(): Result[];
|
|
44
44
|
}
|
|
45
45
|
|
|
46
|
+
class MissingValueError extends Error {
|
|
47
|
+
constructor(
|
|
48
|
+
public variableName: string,
|
|
49
|
+
public originalMessage: string,
|
|
50
|
+
public nodeType: FormatJsNodeType,
|
|
51
|
+
) {
|
|
52
|
+
super(
|
|
53
|
+
`No value for variable '${variableName}' was provided for the localized message '${originalMessage}'`,
|
|
54
|
+
);
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
|
|
46
58
|
export type FormatBuilderConstructor<Result> = new () => FormatBuilder<Result>;
|
|
47
59
|
|
|
48
60
|
export function bindFormatValuesWithBuilder<
|
|
49
61
|
T,
|
|
50
62
|
ObjectType,
|
|
51
63
|
Builder extends FormatBuilder<T, ObjectType>,
|
|
64
|
+
FormatConfig extends FormatConfigType,
|
|
52
65
|
>(
|
|
53
66
|
builder: Builder,
|
|
54
67
|
nodes: AstNode[],
|
|
55
68
|
locales: string | string[],
|
|
56
|
-
formatters:
|
|
69
|
+
formatters: DataFormatters<FormatConfig>,
|
|
57
70
|
formatConfig: FormatConfig,
|
|
58
71
|
values: Record<string, string | object> = {},
|
|
59
72
|
currentPluralValue?: number,
|
|
@@ -65,6 +78,7 @@ export function bindFormatValuesWithBuilder<
|
|
|
65
78
|
return;
|
|
66
79
|
}
|
|
67
80
|
|
|
81
|
+
let keyIndex = 0;
|
|
68
82
|
for (const node of nodes) {
|
|
69
83
|
if (typeof node === 'string') {
|
|
70
84
|
builder.pushLiteralText(node);
|
|
@@ -77,7 +91,7 @@ export function bindFormatValuesWithBuilder<
|
|
|
77
91
|
// numeric values are replaced, otherwise the value is completed ignored?
|
|
78
92
|
// Behavior copied from FormatJS directly.
|
|
79
93
|
if (typeof currentPluralValue === 'number') {
|
|
80
|
-
const value = formatters.
|
|
94
|
+
const value = formatters.formatNumber(currentPluralValue);
|
|
81
95
|
builder.pushLiteralText(value);
|
|
82
96
|
}
|
|
83
97
|
continue;
|
|
@@ -87,7 +101,7 @@ export function bindFormatValuesWithBuilder<
|
|
|
87
101
|
// Enforce that all required values are provided by the caller, even if the
|
|
88
102
|
// actual value is falsy/undefined.
|
|
89
103
|
if (!(variableName in values) && !isRichTextTag(variableName)) {
|
|
90
|
-
throw new MissingValueError(variableName, originalMessage);
|
|
104
|
+
throw new MissingValueError(variableName, originalMessage, nodeType);
|
|
91
105
|
}
|
|
92
106
|
|
|
93
107
|
const value = values[variableName];
|
|
@@ -117,9 +131,8 @@ export function bindFormatValuesWithBuilder<
|
|
|
117
131
|
? formatConfig.date[nodeStyle]
|
|
118
132
|
: nodeStyle != null
|
|
119
133
|
? parseDateTimeSkeleton(nodeStyle)
|
|
120
|
-
:
|
|
121
|
-
|
|
122
|
-
builder.pushLiteralText(formatters.getDateTimeFormat(locales, style).format(value));
|
|
134
|
+
: undefined;
|
|
135
|
+
builder.pushLiteralText(formatters.formatDate(value as number | Date, style));
|
|
123
136
|
break;
|
|
124
137
|
}
|
|
125
138
|
case FormatJsNodeType.Time: {
|
|
@@ -131,11 +144,8 @@ export function bindFormatValuesWithBuilder<
|
|
|
131
144
|
? formatConfig.time[nodeStyle]
|
|
132
145
|
: nodeStyle != null
|
|
133
146
|
? parseDateTimeSkeleton(nodeStyle)
|
|
134
|
-
: undefined;
|
|
135
|
-
builder.pushLiteralText(
|
|
136
|
-
// @ts-expect-error Cast string values to dates properly.
|
|
137
|
-
formatters.getDateTimeFormat(locales, style).format(value),
|
|
138
|
-
);
|
|
147
|
+
: undefined;
|
|
148
|
+
builder.pushLiteralText(formatters.formatTime(value as number | Date, style));
|
|
139
149
|
break;
|
|
140
150
|
}
|
|
141
151
|
case FormatJsNodeType.Number: {
|
|
@@ -146,12 +156,14 @@ export function bindFormatValuesWithBuilder<
|
|
|
146
156
|
nodeStyle in formatConfig.number
|
|
147
157
|
? formatConfig.number[nodeStyle]
|
|
148
158
|
: nodeStyle != null
|
|
149
|
-
? parseNumberSkeleton(
|
|
159
|
+
? (parseNumberSkeleton(
|
|
160
|
+
parseNumberSkeletonFromString(nodeStyle),
|
|
161
|
+
) as Intl.NumberFormatOptions)
|
|
150
162
|
: undefined;
|
|
151
163
|
const scaledValue =
|
|
152
164
|
// @ts-expect-error This is a weird cast that's not accurate, but works in the short term.
|
|
153
165
|
typeof value !== 'number' ? (value as number) : (value as number) * (style?.scale ?? 1);
|
|
154
|
-
builder.pushLiteralText(formatters.
|
|
166
|
+
builder.pushLiteralText(formatters.formatNumber(scaledValue, style));
|
|
155
167
|
break;
|
|
156
168
|
}
|
|
157
169
|
|
|
@@ -189,7 +201,7 @@ export function bindFormatValuesWithBuilder<
|
|
|
189
201
|
if (typeof value !== 'function') {
|
|
190
202
|
throw `expected a function type for a Tag formatting value, ${variableName}. got ${typeof value}: ${value}`;
|
|
191
203
|
}
|
|
192
|
-
let chunks = value(appliedChildren);
|
|
204
|
+
let chunks = value(appliedChildren, `${keyIndex++}`);
|
|
193
205
|
chunks = Array.isArray(chunks) ? chunks : [chunks];
|
|
194
206
|
for (const chunk of chunks) {
|
|
195
207
|
if (typeof chunk === 'string') {
|
|
@@ -220,16 +232,18 @@ export function bindFormatValuesWithBuilder<
|
|
|
220
232
|
const option = (() => {
|
|
221
233
|
const exactSelector = `=${value}`;
|
|
222
234
|
if (exactSelector in options) return options[exactSelector];
|
|
223
|
-
|
|
224
|
-
|
|
235
|
+
|
|
236
|
+
const rule = formatters.getPluralRules({ type: pluralType }).select(
|
|
225
237
|
// @ts-expect-error Assert this `as number` properly.
|
|
226
|
-
|
|
238
|
+
(value as number) - (offset ?? 0),
|
|
239
|
+
);
|
|
227
240
|
return options[rule] ?? options.other;
|
|
228
241
|
})();
|
|
229
242
|
|
|
230
243
|
if (option == null) {
|
|
231
244
|
throw `${value} is not a known option for plural value ${variableName}. Valid options are ${Object.keys(options).join(', ')}`;
|
|
232
245
|
}
|
|
246
|
+
|
|
233
247
|
bindFormatValuesWithBuilder(
|
|
234
248
|
builder,
|
|
235
249
|
option,
|
|
@@ -246,11 +260,11 @@ export function bindFormatValuesWithBuilder<
|
|
|
246
260
|
}
|
|
247
261
|
}
|
|
248
262
|
|
|
249
|
-
export function bindFormatValues<Result>(
|
|
263
|
+
export function bindFormatValues<Result, FormatConfig extends FormatConfigType>(
|
|
250
264
|
Builder: FormatBuilderConstructor<Result>,
|
|
251
265
|
nodes: string | AstNode[],
|
|
252
266
|
locales: string | string[],
|
|
253
|
-
|
|
267
|
+
dataFormatters: DataFormatters<FormatConfig>,
|
|
254
268
|
formatConfig: FormatConfig,
|
|
255
269
|
values: Record<string, string | object> = {},
|
|
256
270
|
currentPluralValue?: number,
|
|
@@ -264,7 +278,7 @@ export function bindFormatValues<Result>(
|
|
|
264
278
|
builder,
|
|
265
279
|
nodes,
|
|
266
280
|
locales,
|
|
267
|
-
|
|
281
|
+
dataFormatters,
|
|
268
282
|
formatConfig,
|
|
269
283
|
values,
|
|
270
284
|
currentPluralValue,
|
package/src/formatters/index.ts
CHANGED
package/src/formatters/react.ts
CHANGED
|
@@ -76,9 +76,46 @@ function createReactBuilder(richTextElements: RichTextFormattingMap<ReactFunctio
|
|
|
76
76
|
};
|
|
77
77
|
}
|
|
78
78
|
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
79
|
+
/**
|
|
80
|
+
* A type representing any message that has been formatted using one of the
|
|
81
|
+
* default React formatting methods in the `@discord/intl` system. Use this
|
|
82
|
+
* type when you don't care about whether a message is static or contains rich
|
|
83
|
+
* text or has dynamically-formatted values, when you need to handle both in
|
|
84
|
+
* tandem, or when you need a generic return type for a function returning "any
|
|
85
|
+
* already-formatted React message".
|
|
86
|
+
*
|
|
87
|
+
* Generally, this is like `React.ReactNode`, accepting both strings and rich
|
|
88
|
+
* `ReactElement`s, but it is more specific to disallow nullish values and
|
|
89
|
+
* other special React elements like `ReactPortal`. Seeing this type, you can
|
|
90
|
+
* be confident that the value is intended to be the result of formatting an
|
|
91
|
+
* intl message, even if the actual value comes from elsewhere (like a
|
|
92
|
+
* user-generated string).
|
|
93
|
+
*/
|
|
94
|
+
export type ReactIntlMessage =
|
|
95
|
+
// This is _not_ a branded string for the sake of compatibility in end-user code. Because these
|
|
96
|
+
// are plain strings, there's still no risk of users providing arbitrary nodes here (unless they
|
|
97
|
+
// forcibly or mistakenly downcast to `strings` themselves.
|
|
98
|
+
// In the future, this could become `ReactIntlPlainString` instead.
|
|
99
|
+
| string
|
|
100
|
+
// This is explicitly `ReactElement | string` and _not_ `ReactNode`, because nullish values and
|
|
101
|
+
// all other types it accepts (boolean, number, etc.) are _not_ valid children of a message.
|
|
102
|
+
| ReactIntlRichText;
|
|
103
|
+
|
|
104
|
+
/**
|
|
105
|
+
* A branded type representing a plain string that has been rendered by the React formatter. This
|
|
106
|
+
* type should generally _not_ be used as a type constraint unless _absolute certainty_ that a
|
|
107
|
+
* message was formatted is desirable. Instead, accept plain `string`, and this will be compatible.
|
|
108
|
+
*/
|
|
109
|
+
export type ReactIntlPlainString = string & { __brand: 'discord-intl' };
|
|
110
|
+
|
|
111
|
+
/**
|
|
112
|
+
* While `ReactIntlMessage` represents the result of rendering _any_ message with the React
|
|
113
|
+
* formatter, `ReactIntlRichText` specifically represents a message that was rendered and contains
|
|
114
|
+
* rich text, meaning the result contains React nodes itself and represents a CST of the message.
|
|
115
|
+
*/
|
|
116
|
+
export type ReactIntlRichText = Array<React.ReactElement | string> & {
|
|
117
|
+
__brand: 'discord-intl';
|
|
118
|
+
};
|
|
82
119
|
|
|
83
120
|
export function formatReact(
|
|
84
121
|
this: IntlManager,
|
|
@@ -86,12 +123,10 @@ export function formatReact(
|
|
|
86
123
|
values: object,
|
|
87
124
|
Builder: FormatBuilderConstructor<React.ReactElement>,
|
|
88
125
|
): ReactIntlMessage {
|
|
89
|
-
if (typeof message === 'string')
|
|
90
|
-
return [message] as ReactIntlMessage;
|
|
91
|
-
}
|
|
126
|
+
if (typeof message === 'string') return message as ReactIntlPlainString;
|
|
92
127
|
|
|
93
128
|
const parts = this.bindFormatValues(Builder, message, values);
|
|
94
|
-
return parts as
|
|
129
|
+
return parts as ReactIntlRichText;
|
|
95
130
|
}
|
|
96
131
|
|
|
97
132
|
/**
|
package/src/index.ts
CHANGED
|
@@ -1,8 +1,6 @@
|
|
|
1
|
-
|
|
2
|
-
import { RichTextNode } from './formatters';
|
|
3
|
-
|
|
4
|
-
export * from './formatters';
|
|
1
|
+
export { type DataFormatters, makeDataFormatters } from './data-formatters';
|
|
5
2
|
export { FormatBuilder, FormatBuilderConstructor, bindFormatValues } from './format';
|
|
3
|
+
export * from './formatters';
|
|
6
4
|
export { runtimeHashMessageKey } from './hash';
|
|
7
5
|
export { IntlManager, DEFAULT_LOCALE, type FormatFunction } from './intl-manager';
|
|
8
6
|
export {
|
|
@@ -13,24 +11,6 @@ export {
|
|
|
13
11
|
} from './message-loader';
|
|
14
12
|
export type * from './types.d.ts';
|
|
15
13
|
|
|
16
|
-
/**
|
|
17
|
-
* A type representing any message that has been formatted using one of the
|
|
18
|
-
* default formatting methods in the `@discord/intl` system. Use this type
|
|
19
|
-
* when you don't care about whether a message is static or contains rich text
|
|
20
|
-
* or has dynamically-formatted values, when you need to handle both in tandem,
|
|
21
|
-
* or when you need a generic return type for a function returning "any
|
|
22
|
-
* any-already formatted message".
|
|
23
|
-
*
|
|
24
|
-
* Generally, this is like `React.ReactNode`, accepting both strings and rich
|
|
25
|
-
* `ReactElement`s, but it is more specific to disallow nullish values and
|
|
26
|
-
* other special React elements like `ReactPortal`. Seeing this type, you can
|
|
27
|
-
* be confident that the value is intended to be the result of formatting an
|
|
28
|
-
* intl message, even if the actual value comes from elsewhere (like a
|
|
29
|
-
* user-generated string).
|
|
30
|
-
*/
|
|
31
|
-
// TODO: Replace this with ReactIntlMessage from `formatters/react`.
|
|
32
|
-
export type ReactIntlMessage = string | React.ReactElement | Array<string | React.ReactElement>;
|
|
33
|
-
|
|
34
14
|
/**
|
|
35
15
|
* The return value of `formatToParts` from `@discord/intl`, this type
|
|
36
16
|
* represents any AST structure for a message rendered using this system.
|
|
@@ -41,4 +21,5 @@ export type ReactIntlMessage = string | React.ReactElement | Array<string | Reac
|
|
|
41
21
|
* from a call to `formatToParts`, meaning they are intended to be fully static
|
|
42
22
|
* structures passed around for custom rendering functions to use.
|
|
43
23
|
*/
|
|
24
|
+
import { type RichTextNode } from './formatters';
|
|
44
25
|
export type IntlMessageAst = RichTextNode;
|
package/src/intl-manager.ts
CHANGED
|
@@ -1,6 +1,5 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
3
|
-
|
|
1
|
+
import { DEFAULT_FORMAT_CONFIG, type FormatConfigType } from './data-formatters/config';
|
|
2
|
+
import { bindFormatValues, FormatBuilderConstructor } from './format';
|
|
4
3
|
import type {
|
|
5
4
|
FormatterImplementation,
|
|
6
5
|
IntlMessageGetter,
|
|
@@ -8,8 +7,7 @@ import type {
|
|
|
8
7
|
TypedIntlMessageGetter,
|
|
9
8
|
} from './types';
|
|
10
9
|
import { InternalIntlMessage } from './message';
|
|
11
|
-
import {
|
|
12
|
-
import { DEFAULT_FORMAT_CONFIG, FormatConfig } from './format-config';
|
|
10
|
+
import { DataFormatters, makeDataFormatters } from './data-formatters';
|
|
13
11
|
|
|
14
12
|
/**
|
|
15
13
|
* Fallback locale used for all internationalization when an operation in the
|
|
@@ -37,7 +35,7 @@ type ThisWithFormatters<
|
|
|
37
35
|
[K in keyof T]: FormatFunction<T[K]>;
|
|
38
36
|
};
|
|
39
37
|
|
|
40
|
-
export interface IntlManagerOptions {
|
|
38
|
+
export interface IntlManagerOptions<FormatConfig> {
|
|
41
39
|
/**
|
|
42
40
|
* The locale to initially have this manager use. Useful to set when information about the user's
|
|
43
41
|
* likely locale is available sooner than when that information is definitely known (at which
|
|
@@ -53,28 +51,40 @@ export interface IntlManagerOptions {
|
|
|
53
51
|
* @default DEFAULT_LOCALE
|
|
54
52
|
*/
|
|
55
53
|
defaultLocale?: string;
|
|
54
|
+
/**
|
|
55
|
+
* Configuration for the different kinds of data dataFormatters that can be used both inside of
|
|
56
|
+
* messages and in their own functions (like `intl.formatDate`) as shorthands for common sets of
|
|
57
|
+
* options. For example, with the default config, this enables `intl.formatDate(now, 'short')`
|
|
58
|
+
* rather than having to specify the exact properties of each style every time.
|
|
59
|
+
*
|
|
60
|
+
* @default DEFAULT_FORMATTER_CONFIG
|
|
61
|
+
*/
|
|
62
|
+
formatConfig?: FormatConfig;
|
|
56
63
|
}
|
|
57
64
|
|
|
58
|
-
export class IntlManager
|
|
65
|
+
export class IntlManager<
|
|
66
|
+
const FormatConfig extends FormatConfigType = typeof DEFAULT_FORMAT_CONFIG,
|
|
67
|
+
> {
|
|
59
68
|
defaultLocale: string;
|
|
60
69
|
currentLocale: string;
|
|
61
|
-
intl: IntlShape;
|
|
62
70
|
formatConfig: FormatConfig;
|
|
63
71
|
|
|
72
|
+
data: DataFormatters<FormatConfig>;
|
|
73
|
+
|
|
64
74
|
_localeSubscriptions: Set<(locale: string) => void>;
|
|
65
75
|
|
|
66
76
|
constructor({
|
|
67
77
|
initialLocale = DEFAULT_LOCALE,
|
|
68
78
|
defaultLocale = DEFAULT_LOCALE,
|
|
69
|
-
|
|
79
|
+
// @ts-expect-error If it's not given, formatConfig defaults to the same
|
|
80
|
+
// value as the type parameters, but typescript things this should be
|
|
81
|
+
// overwritten
|
|
82
|
+
formatConfig = DEFAULT_FORMAT_CONFIG,
|
|
83
|
+
}: IntlManagerOptions<FormatConfig>) {
|
|
70
84
|
this.currentLocale = initialLocale;
|
|
71
85
|
this.defaultLocale = defaultLocale;
|
|
72
|
-
this.formatConfig =
|
|
73
|
-
this.
|
|
74
|
-
formats: DEFAULT_FORMAT_CONFIG,
|
|
75
|
-
defaultLocale,
|
|
76
|
-
locale: defaultLocale,
|
|
77
|
-
});
|
|
86
|
+
this.formatConfig = formatConfig;
|
|
87
|
+
this.data = makeDataFormatters([this.currentLocale, this.defaultLocale], this.formatConfig);
|
|
78
88
|
|
|
79
89
|
this._localeSubscriptions = new Set();
|
|
80
90
|
}
|
|
@@ -84,9 +94,9 @@ export class IntlManager {
|
|
|
84
94
|
* property
|
|
85
95
|
*/
|
|
86
96
|
withFormatters<const T extends Record<string, FormatterImplementation<any, any>>>(
|
|
87
|
-
|
|
97
|
+
dataFormatters: T,
|
|
88
98
|
): ThisWithFormatters<this, T> {
|
|
89
|
-
for (const [name, formatter] of Object.entries(
|
|
99
|
+
for (const [name, formatter] of Object.entries(dataFormatters)) {
|
|
90
100
|
this[name] = this.makeFormatFunction(formatter);
|
|
91
101
|
}
|
|
92
102
|
|
|
@@ -115,7 +125,7 @@ export class IntlManager {
|
|
|
115
125
|
*/
|
|
116
126
|
setLocale(locale: string) {
|
|
117
127
|
this.currentLocale = locale;
|
|
118
|
-
this.
|
|
128
|
+
this.data = makeDataFormatters([this.currentLocale, this.defaultLocale], this.formatConfig);
|
|
119
129
|
this.emitLocaleChange(locale);
|
|
120
130
|
}
|
|
121
131
|
|
|
@@ -168,7 +178,7 @@ export class IntlManager {
|
|
|
168
178
|
Builder,
|
|
169
179
|
message.ast,
|
|
170
180
|
[this.currentLocale, this.defaultLocale],
|
|
171
|
-
this.
|
|
181
|
+
this.data,
|
|
172
182
|
this.formatConfig,
|
|
173
183
|
values,
|
|
174
184
|
);
|