@discord/intl 0.0.6-rc.1 → 0.0.7

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.
@@ -1,6 +1,6 @@
1
1
  import { IntlShape } from '@formatjs/intl';
2
- import { LocaleImportMap, LocaleId, MessageLoader } from './message-loader';
3
- import type { TypedIntlMessageGetter, FormatValuesFor, RichTextElementMap } from './types';
2
+ import { LocaleId, LocaleImportMap, MessageLoader } from './message-loader';
3
+ import type { FormatValuesFor, RichTextElementMap, TypedIntlMessageGetter } from './types';
4
4
  /**
5
5
  * Fallback locale used for all internationalization when an operation in the
6
6
  * requested locale is not possible.
@@ -44,12 +44,31 @@ export declare class IntlManager<DefaultElements extends RichTextElementMap, Def
44
44
  */
45
45
  formatToParts<T extends TypedIntlMessageGetter<object | undefined>>(message: T): Array<string | any>;
46
46
  formatToParts<T extends TypedIntlMessageGetter<object | undefined>>(message: T, values: Omit<FormatValuesFor<T>, DefaultValues>): Array<string | any>;
47
+ /**
48
+ * For messages with no formatting values (i.e., plain strings, they can skip
49
+ * a majority of the processing work and just resolve the message itself for
50
+ * the current locale, then return the plain string directly.
51
+ *
52
+ * This is separate from `formatToPlainString`, which still allows for
53
+ * formatting variables and other elements but reduces the output to only
54
+ * include textual elements in a plain string.
55
+ */
56
+ string(message: TypedIntlMessageGetter<undefined>): string;
47
57
  /**
48
58
  * Format the given message with the provided values, removing any styling
49
59
  * and non-textual content from the message, returning a plain string.
50
60
  */
51
61
  formatToPlainString<T extends TypedIntlMessageGetter<object | undefined>>(message: T): string;
52
62
  formatToPlainString<T extends TypedIntlMessageGetter<object | undefined>>(message: T, values: Omit<FormatValuesFor<T>, DefaultValues>): string;
63
+ /**
64
+ * Similar to `formatToPlainString`, format the given message with the provided
65
+ * values, but convert all rich text formatting back to Markdown syntax rather
66
+ * than rendering the actual rich content. The result is a plain string that
67
+ * can be sent through a separate Markdown renderer to get an equivalent
68
+ * result to formatting this message directly.
69
+ */
70
+ formatToMarkdownString<T extends TypedIntlMessageGetter<object | undefined>>(message: T): string;
71
+ formatToMarkdownString<T extends TypedIntlMessageGetter<object | undefined>>(message: T, values: Omit<FormatValuesFor<T>, DefaultValues>): string;
53
72
  }
54
73
  /**
55
74
  * Create a new MessageLoader, which handles lazily loading messages for
@@ -115,6 +115,19 @@ var IntlManager = /** @class */ (function () {
115
115
  }
116
116
  return result;
117
117
  };
118
+ /**
119
+ * For messages with no formatting values (i.e., plain strings, they can skip
120
+ * a majority of the processing work and just resolve the message itself for
121
+ * the current locale, then return the plain string directly.
122
+ *
123
+ * This is separate from `formatToPlainString`, which still allows for
124
+ * formatting variables and other elements but reduces the output to only
125
+ * include textual elements in a plain string.
126
+ */
127
+ IntlManager.prototype.string = function (message) {
128
+ // TODO(faulty): Optimize this so that plain strings are hotpathed even faster.
129
+ return this.formatToPlainString(message);
130
+ };
118
131
  IntlManager.prototype.formatToPlainString = function (message, values) {
119
132
  if (typeof message === 'string')
120
133
  return message;
@@ -125,6 +138,17 @@ var IntlManager = /** @class */ (function () {
125
138
  // will be removed from the string anyway.
126
139
  return resolvedMessage.formatToPlainString(this.intl.formatters, this.intl.formats, values);
127
140
  };
141
+ IntlManager.prototype.formatToMarkdownString = function (message, values) {
142
+ // TODO(faulty): Implement the markdown syntax conversion here.
143
+ if (typeof message === 'string')
144
+ return message;
145
+ var resolvedMessage = message(this.currentLocale);
146
+ if (typeof resolvedMessage === 'string')
147
+ return resolvedMessage;
148
+ // No need to pass in `defaultRichTextElements`, since the stylistic tags
149
+ // will be removed from the string anyway.
150
+ return resolvedMessage.formatToPlainString(this.intl.formatters, this.intl.formats, values);
151
+ };
128
152
  return IntlManager;
129
153
  }());
130
154
  exports.IntlManager = IntlManager;
@@ -53,7 +53,7 @@ export declare class MessageLoader {
53
53
  *
54
54
  * @private
55
55
  */
56
- _debugKeyMap: Record<string, string>;
56
+ _debugKeyMap?: Record<string, string>;
57
57
  /**
58
58
  * Map of locale names to source file names, used to provide context for where messages are
59
59
  * imported from during development.
@@ -62,7 +62,7 @@ export declare class MessageLoader {
62
62
  *
63
63
  * @private
64
64
  */
65
- _localeFileMap: Record<string, string>;
65
+ _localeFileMap?: Record<string, string>;
66
66
  constructor(messageKeys: string[], localeImportMap: LocaleImportMap, defaultLocale: LocaleId);
67
67
  /**
68
68
  * Provide additional debug information to use during development, providing additional context
package/dist/react.d.ts CHANGED
@@ -10,7 +10,7 @@ export declare class IntlManagerReact<DefaultElements extends RichTextElementMap
10
10
  IntlMessage: <T extends TypedIntlMessageGetter<object | undefined>>(props: {
11
11
  message: T;
12
12
  values?: Omit<FormatValuesFor<T>, DefaultValues> | never;
13
- }) => React.FunctionComponentElement<{
13
+ }) => string | React.FunctionComponentElement<{
14
14
  children?: React.ReactNode | undefined;
15
15
  }>;
16
16
  /**
package/dist/react.js CHANGED
@@ -57,15 +57,18 @@ var IntlManagerReact = /** @class */ (function (_super) {
57
57
  // Use the locale from this point in the application, which may be
58
58
  // different from the global locale.
59
59
  var locale = React.useSyncExternalStore(_this.onLocaleChange, function () { return _this.currentLocale; });
60
- // Source the actual message to render for that locale from its loader.
61
60
  // TODO(faulty): This can and should be replaced by a
62
61
  // `use(messagesLoadedPromise)` once `use` is shipped to stable.
62
+ // Source the actual message to render for that locale from its loader.
63
63
  React.useSyncExternalStore(message.onChange, function () { return message(locale); });
64
64
  // If there are no object parts in the message, it has no formatting and can just be returned as
65
65
  // a plain string.
66
- return typeof message === 'string'
67
- ? message
68
- : React.createElement(React.Fragment, undefined, _this.formatToParts(message, values));
66
+ if (typeof message === 'string')
67
+ return message;
68
+ var parts = _this.formatToParts(message, values);
69
+ if (parts.length === 1 && typeof parts[0] === 'string')
70
+ return parts[0];
71
+ return React.createElement(React.Fragment, undefined, _this.formatToParts(message, values));
69
72
  };
70
73
  return _this;
71
74
  }
@@ -0,0 +1,137 @@
1
+ import type { InternalIntlMessage } from './message';
2
+ import type { IntlMessageGetterAdditions } from './message-loader';
3
+
4
+ /**
5
+ * Use this function to define messages as part of the `@discord/intl`
6
+ * system, with type checking support.
7
+ *
8
+ * This function does not actually exist, and gets compiled out as part
9
+ * of the bundling process both on web and mobile. See the
10
+ * `@discord/intl/README.md` for more information.
11
+ */
12
+ export declare function defineMessages(messages: object): object;
13
+
14
+ /**
15
+ * A map of tag names to render functions to apply when the tags are
16
+ * encountered while formatting a message. Each `IntlManager` can be
17
+ * constructed with a different map of these elements, for example to allow
18
+ * one manager to render React output while another renders accessibility text.
19
+ */
20
+ export type RichTextElementMap = Record<string, (chunks: any[]) => any>;
21
+
22
+ /**
23
+ * Messages with no rich formatting and no value interpolations are just plain
24
+ * strings, and are able to skip multiple formatting steps to work more
25
+ * efficiently. This type represents those messages distinctly.
26
+ */
27
+ type PlainIntlMessage = string;
28
+ /**
29
+ * A richly-formatted message that injects dynamic values while formatting,
30
+ * with the types of those values defined by the `FormatValues` object. All
31
+ * messages of this type must have at least one value in the object, otherwise
32
+ * the message should be typed as a `PlainIntlMessage`.
33
+ */
34
+ type TypedIntlMessage<FormatValues extends object> = InternalIntlMessage & {
35
+ values: FormatValues;
36
+ };
37
+
38
+ type AnyIntlMessage<FormatValues extends object | undefined = undefined> =
39
+ FormatValues extends undefined ? PlainIntlMessage : TypedIntlMessage<FormatValues>;
40
+
41
+ /**
42
+ * Getter function that retrieves a message that best matches the requested
43
+ * locale. `FormatValues` represents either an object containing all of the
44
+ * value types that are required to format the message, or `undefined` to
45
+ * represent that there are no values required and the message is a plain
46
+ * string.
47
+ */
48
+ export interface TypedIntlMessageGetter<FormatValues extends object | undefined>
49
+ extends IntlMessageGetterAdditions {
50
+ (locale: string): AnyIntlMessage<FormatValues>;
51
+ }
52
+
53
+ /**
54
+ * Common utility type for converting a union type to an intersection of all
55
+ * the types in that union.
56
+ */
57
+ type UnionToIntersection<U> = (U extends any ? (k: U) => void : never) extends (k: infer I) => void
58
+ ? I
59
+ : never;
60
+
61
+ /**
62
+ * Given a message getter of type `T` (which may be a union of multiple message
63
+ * types), return a combined type representing the intersection of all values
64
+ * needed to satisfy the mix of values defined in any of the messages.
65
+ *
66
+ * For example, given a variable representing one of two message getters, where
67
+ * one requires a single value to be formatted, but the other requires an
68
+ * additional value on top of that one:
69
+ *
70
+ * ```typescript
71
+ * // message1: "Hello {username}"
72
+ * // message2: "Hello {username}, it's {currentDate, date}"
73
+ * const message = someCondition ? message1 || message2;
74
+ * ```
75
+ *
76
+ * Attempting to format this message would require that both `username` _and_
77
+ * `currentDate` are supplied, so that all possible cases are covered, which is
78
+ * what this type resolves:
79
+ *
80
+ * ```typescript
81
+ * type ResolvedValuesTypes = FormatValuesFor<typeof message>;
82
+ * // => {username: string, currentDate: Date}
83
+ * ```
84
+ *
85
+ * This values type can then be used to enforce that all values are passed to
86
+ * functions that format the message, like `i18n.format`:
87
+ *
88
+ * ```typescript
89
+ * declare function format<T>(message: T, values: FormatValuesFor<T>): string;
90
+ * ```
91
+ *
92
+ * ## Mixed message types
93
+ *
94
+ * If T is a union of message types including both rich messages requiring
95
+ * values _and_ plain string messages with no values, this type will still
96
+ * properly resolve all of the required values, assuming that the getters for
97
+ * the plain messages use the convention of passing `undefined` as the generic
98
+ * argument, representing "no values should be passed for this message".
99
+ *
100
+ *
101
+ * ## Why this type?
102
+ *
103
+ * All "messages" are really defined as functions that return a specific
104
+ * value of the message for a requested locale, `(locale: string) => Message`.
105
+ * This is named `TypedIntlMessageGetter<T>`, where `T` is the definition of
106
+ * the values required to format the message.
107
+ *
108
+ * This type requires being passed the entire getter function rather than the
109
+ * returned message types, as narrowing to the returned type prevents
110
+ * TypeScript from distributing the union properly. This surfaces as error
111
+ * messages showing up on the _message_ type rather than the _value_ type when
112
+ * they don't match, which doesn't give the user any helpful information about
113
+ * what's wrong. This method ensures the value type is always the one being
114
+ * checked against the provided message types, and error messages will be
115
+ * accurate as a result.
116
+ */
117
+ type FormatValuesFor<T> =
118
+ // `[]` syntax forces TypeScript to not distribute the possible union of
119
+ // types, meaning this represents "_all_ values of T are an extension of
120
+ // the parent type", which in this case represents messages with no
121
+ // format values. If that condition is matched, then `FormatValues` _cannot_
122
+ // be supplied, represented by the `never`. This prevents accidentally
123
+ // passing an object, even an empty one, for those strings, and allows the
124
+ // formatter to optimize a little more on each call.
125
+ [T] extends [TypedIntlMessageGetter<undefined>]
126
+ ? never
127
+ : // The `never` condition needs to be repeated here, but this time _without_
128
+ // the `[]` syntax, so that only the union elements with actual values are
129
+ // included in the union. Without this, the `infer U` on the latter side
130
+ // fails to resolve and the type just becomes `never`.
131
+ UnionToIntersection<
132
+ T extends TypedIntlMessageGetter<undefined>
133
+ ? never
134
+ : T extends TypedIntlMessageGetter<infer U>
135
+ ? U
136
+ : never
137
+ >;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@discord/intl",
3
- "version": "0.0.6-rc.1",
3
+ "version": "0.0.7",
4
4
  "license": "MIT",
5
5
  "description": "Client runtime for managing messages and translations in a React project.",
6
6
  "main": "./dist/index.js",
@@ -38,6 +38,7 @@
38
38
  }
39
39
  },
40
40
  "scripts": {
41
- "build": "tsc"
41
+ "build": "tsc",
42
+ "build:release": "tsc && cp ./src/*.d.ts dist/"
42
43
  }
43
44
  }
@@ -1,14 +1,14 @@
1
- import { IntlShape, createIntl } from '@formatjs/intl';
1
+ import { createIntl, IntlShape } from '@formatjs/intl';
2
2
  import {
3
- PART_TYPE as FormatPartType,
4
3
  Formats,
5
4
  Formatters,
6
5
  IntlMessageFormat,
6
+ PART_TYPE as FormatPartType,
7
7
  } from 'intl-messageformat';
8
8
 
9
- import { LocaleImportMap, LocaleId, MessageLoader } from './message-loader';
9
+ import { LocaleId, LocaleImportMap, MessageLoader } from './message-loader';
10
10
 
11
- import type { TypedIntlMessageGetter, FormatValuesFor, RichTextElementMap } from './types';
11
+ import type { FormatValuesFor, RichTextElementMap, TypedIntlMessageGetter } from './types';
12
12
 
13
13
  /**
14
14
  * Fallback locale used for all internationalization when an operation in the
@@ -129,6 +129,20 @@ export class IntlManager<
129
129
  return result;
130
130
  }
131
131
 
132
+ /**
133
+ * For messages with no formatting values (i.e., plain strings, they can skip
134
+ * a majority of the processing work and just resolve the message itself for
135
+ * the current locale, then return the plain string directly.
136
+ *
137
+ * This is separate from `formatToPlainString`, which still allows for
138
+ * formatting variables and other elements but reduces the output to only
139
+ * include textual elements in a plain string.
140
+ */
141
+ string(message: TypedIntlMessageGetter<undefined>): string {
142
+ // TODO(faulty): Optimize this so that plain strings are hotpathed even faster.
143
+ return this.formatToPlainString(message);
144
+ }
145
+
132
146
  /**
133
147
  * Format the given message with the provided values, removing any styling
134
148
  * and non-textual content from the message, returning a plain string.
@@ -154,6 +168,36 @@ export class IntlManager<
154
168
  values,
155
169
  );
156
170
  }
171
+
172
+ /**
173
+ * Similar to `formatToPlainString`, format the given message with the provided
174
+ * values, but convert all rich text formatting back to Markdown syntax rather
175
+ * than rendering the actual rich content. The result is a plain string that
176
+ * can be sent through a separate Markdown renderer to get an equivalent
177
+ * result to formatting this message directly.
178
+ */
179
+ formatToMarkdownString<T extends TypedIntlMessageGetter<object | undefined>>(message: T): string;
180
+ formatToMarkdownString<T extends TypedIntlMessageGetter<object | undefined>>(
181
+ message: T,
182
+ values: Omit<FormatValuesFor<T>, DefaultValues>,
183
+ ): string;
184
+ formatToMarkdownString<T extends TypedIntlMessageGetter<object | undefined>>(
185
+ message: T,
186
+ values?: Omit<FormatValuesFor<T>, DefaultValues>,
187
+ ) {
188
+ // TODO(faulty): Implement the markdown syntax conversion here.
189
+ if (typeof message === 'string') return message;
190
+ const resolvedMessage = message(this.currentLocale);
191
+ if (typeof resolvedMessage === 'string') return resolvedMessage;
192
+
193
+ // No need to pass in `defaultRichTextElements`, since the stylistic tags
194
+ // will be removed from the string anyway.
195
+ return resolvedMessage.formatToPlainString(
196
+ this.intl.formatters as Formatters,
197
+ this.intl.formats as Formats,
198
+ values,
199
+ );
200
+ }
157
201
  }
158
202
 
159
203
  /**
@@ -64,7 +64,7 @@ export class MessageLoader {
64
64
  *
65
65
  * @private
66
66
  */
67
- _debugKeyMap: Record<string, string>;
67
+ _debugKeyMap?: Record<string, string>;
68
68
  /**
69
69
  * Map of locale names to source file names, used to provide context for where messages are
70
70
  * imported from during development.
@@ -73,7 +73,7 @@ export class MessageLoader {
73
73
  *
74
74
  * @private
75
75
  */
76
- _localeFileMap: Record<string, string>;
76
+ _localeFileMap?: Record<string, string>;
77
77
 
78
78
  constructor(messageKeys: string[], localeImportMap: LocaleImportMap, defaultLocale: LocaleId) {
79
79
  this.messageKeys = messageKeys;
package/src/react.ts CHANGED
@@ -21,19 +21,21 @@ export class IntlManagerReact<
21
21
  // Use the locale from this point in the application, which may be
22
22
  // different from the global locale.
23
23
  const locale = React.useSyncExternalStore(this.onLocaleChange, () => this.currentLocale);
24
- // Source the actual message to render for that locale from its loader.
25
24
  // TODO(faulty): This can and should be replaced by a
26
25
  // `use(messagesLoadedPromise)` once `use` is shipped to stable.
26
+ // Source the actual message to render for that locale from its loader.
27
27
  React.useSyncExternalStore(message.onChange, () => message(locale));
28
28
  // If there are no object parts in the message, it has no formatting and can just be returned as
29
29
  // a plain string.
30
- return typeof message === 'string'
31
- ? message
32
- : React.createElement(
33
- React.Fragment,
34
- undefined,
35
- this.formatToParts(message, values as Omit<FormatValuesFor<T>, DefaultValues>),
36
- );
30
+ if (typeof message === 'string') return message;
31
+
32
+ const parts = this.formatToParts(message, values as Omit<FormatValuesFor<T>, DefaultValues>);
33
+ if (parts.length === 1 && typeof parts[0] === 'string') return parts[0];
34
+ return React.createElement(
35
+ React.Fragment,
36
+ undefined,
37
+ this.formatToParts(message, values as Omit<FormatValuesFor<T>, DefaultValues>),
38
+ );
37
39
  };
38
40
 
39
41
  /**
package/src/types.d.ts CHANGED
@@ -36,7 +36,7 @@ type TypedIntlMessage<FormatValues extends object> = InternalIntlMessage & {
36
36
  };
37
37
 
38
38
  type AnyIntlMessage<FormatValues extends object | undefined = undefined> =
39
- FormatValues extends object ? TypedIntlMessage<FormatValues> : PlainIntlMessage;
39
+ FormatValues extends undefined ? PlainIntlMessage : TypedIntlMessage<FormatValues>;
40
40
 
41
41
  /**
42
42
  * Getter function that retrieves a message that best matches the requested
@@ -45,10 +45,10 @@ type AnyIntlMessage<FormatValues extends object | undefined = undefined> =
45
45
  * represent that there are no values required and the message is a plain
46
46
  * string.
47
47
  */
48
- export type TypedIntlMessageGetter<FormatValues extends object | undefined> =
49
- IntlMessageGetterAdditions & {
50
- (locale: string): AnyIntlMessage<FormatValues>;
51
- };
48
+ export interface TypedIntlMessageGetter<FormatValues extends object | undefined>
49
+ extends IntlMessageGetterAdditions {
50
+ (locale: string): AnyIntlMessage<FormatValues>;
51
+ }
52
52
 
53
53
  /**
54
54
  * Common utility type for converting a union type to an intersection of all