Skip to content

Commit 9db404f

Browse files
authored
fix: uppercase custom function example per latest messageformat@next (#46)
* Param types fixed (first arg is `context: MessageFunctionContext`, not `locales: string[]`) * Return type fixed — only including `toString` doesn't work with `format` or `formatToParts` * Use `toLocaleUpperCase` with the locales available in the context, rather than locale-less `toUpperCase` It seems like building on top of the built-in `DefaultFunctions.string` is the simplest way to implement a custom `string -> string` function that correctly implements the contract expected by `format` and `formatToParts`. The returned object for input `"{messageformat :uppercase}"` looks roughly like this: ```ts { type: "string", source: "|messageformat|", dir: "auto", selectKey: (keys) => (keys.has(selStr) ? selStr : null), toParts: () => [{ type: "string", source: "|messageformat|", locale: "en", value: "MESSAGEFORMAT" }], toString: () => "MESSAGEFORMAT", valueOf: () => "MESSAGEFORMAT" } ```
1 parent 376fff2 commit 9db404f

File tree

1 file changed

+11
-7
lines changed

1 file changed

+11
-7
lines changed

docs/integration/js.md

Lines changed: 11 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -182,20 +182,24 @@ providing definitions for custom functions. To start with, let's write code for
182182
a simple custom function:
183183

184184
```js
185-
/**
186-
* @params {string[]} locales
187-
* @params {Record<string, unknown>} options
188-
* @params {string} value
189-
*/
190-
function uppercase(locales, options, value) {
191-
return { toString: () => value.toUpperCase() };
185+
import { DefaultFunctions, asString } from "messageformat@next/functions";
186+
187+
/** @type {typeof DefaultFunctions.string} */
188+
function uppercase(context, options, input) {
189+
return DefaultFunctions.string(
190+
context,
191+
options,
192+
asString(input).toLocaleUpperCase(context.locales),
193+
);
192194
}
193195
```
194196

195197
Now that this function is defined, we can pass it to the `MessageFormat`
196198
constructor as part of the third argument:
197199

198200
```js
201+
import { MessageFormat } from "messageformat@next";
202+
199203
const mf = new MessageFormat(
200204
["en"],
201205
"{messageformat :uppercase}",

0 commit comments

Comments
 (0)