From f2c23b5217ff91653a24f1f75248e67f9dacd9e1 Mon Sep 17 00:00:00 2001 From: dangreen Date: Sun, 22 Nov 2026 19:54:39 +0400 Subject: [PATCH] feat(intl): let `rich` and `markup` take `plural` and `match` as the preformat `rich(tags, plural('count'))` and `rich(tags, params({ count: number() }, plural('count')))` rendered nothing: the preformat got one text piece at a time, while `plural` and `match` choose from the whole message. The preformat of `rich` and `markup` now gets the whole message, and the tags of the translation are marked before values go in, so a value is still never read as a tag. Other combinations of formats that compiled but rendered wrong now work or fail to compile: - `uppercase`, `lowercase` and `capitalize` transform the text of a message function, like `params(...)`. - A surrounding `params` formats the value of `plural` and `match` inside `wrap`, `markup` and text transforms too. - Placeholders match regardless of case, so a translation transformed by `uppercase(text())` keeps them. - `wrap` takes back the values of a param that both `params` and `plural` list. - `forms(...)` and `cases(...)` take only formats that render text, so tags go around `plural` and `match`. --- packages/intl/.size-limit.json | 6 +- packages/intl/src/format/markup.spec.ts | 21 +++- packages/intl/src/format/markup.ts | 34 +++--- packages/intl/src/format/match.spec.ts | 14 +++ packages/intl/src/format/match.ts | 18 +-- packages/intl/src/format/params.spec.ts | 52 ++++++++- packages/intl/src/format/params.ts | 18 ++- packages/intl/src/format/plural.spec.ts | 19 +++- packages/intl/src/format/rich.spec.ts | 140 +++++++++++++++++++++++- packages/intl/src/format/rich.ts | 126 ++++++++++++++------- packages/intl/src/format/text.spec.ts | 38 +++++++ packages/intl/src/format/text.ts | 81 ++++++++++---- packages/intl/src/format/types.ts | 3 - packages/intl/src/format/wrap.spec.ts | 18 +++ packages/intl/src/format/wrap.ts | 6 +- packages/intl/src/types.ts | 4 + skills/nano-kit-intl/DOCS.md | 51 ++++++++- skills/nano-kit-intl/SKILL.md | 2 +- website/src/content/docs/intl/api.mdx | 51 ++++++++- 19 files changed, 595 insertions(+), 107 deletions(-) diff --git a/packages/intl/.size-limit.json b/packages/intl/.size-limit.json index ac33c2c7..ad8b4577 100644 --- a/packages/intl/.size-limit.json +++ b/packages/intl/.size-limit.json @@ -4,13 +4,13 @@ "gzip": true, "path": "dist/index.production.js", "import": "*", - "limit": "2.50 kB" + "limit": "2.55 kB" }, { "name": "All publics (Brotli)", "path": "dist/index.production.js", "import": "*", - "limit": "2.30 kB" + "limit": "2.35 kB" }, { "name": "Minimal set (Gzip)", @@ -36,6 +36,6 @@ "name": "Basic set (Brotli)", "path": "dist/index.production.js", "import": "{ intl, text, number, datetime, params, plural, match, cases }", - "limit": "1.00 kB" + "limit": "1.05 kB" } ] diff --git a/packages/intl/src/format/markup.spec.ts b/packages/intl/src/format/markup.spec.ts index 1a056b04..4ebe7b6e 100644 --- a/packages/intl/src/format/markup.spec.ts +++ b/packages/intl/src/format/markup.spec.ts @@ -5,10 +5,14 @@ import { } from 'vitest' import type { FormatContext } from '../types.js' import { markup } from './markup.js' +import { number } from './number.js' import { params } from './params.js' +import { plural } from './plural.js' import { text } from './text.js' -const ctx = {} as FormatContext +const ctx: FormatContext = { + $locale: () => 'en-US' +} const tags = { link: (chunks: string) => `${chunks}`, strong: (chunks: string) => `${chunks}` @@ -59,7 +63,7 @@ describe('intl', () => { expect(format(ctx, 'Read guidelines.')).toBe('Read guidelines.') }) - it('should format each text piece with the preformat', () => { + it('should fill values into the message with the preformat', () => { const format = markup(tags, params({ name: text() })) @@ -88,6 +92,19 @@ describe('intl', () => { name: 'Ada' })).toBe('By Ada') }) + + it('should choose a plural form with the preformat', () => { + const format = markup(tags, params({ + count: number() + }, plural('count'))) + + expect(format(ctx, { + one: '{count} plant', + other: '{count} plants' + })({ + count: 1284 + })).toBe('1,284 plants') + }) }) }) }) diff --git a/packages/intl/src/format/markup.ts b/packages/intl/src/format/markup.ts index 25d31647..9330a08d 100644 --- a/packages/intl/src/format/markup.ts +++ b/packages/intl/src/format/markup.ts @@ -31,37 +31,39 @@ export function markup( ): Format /** - * Creates a markup formatter that formats each text piece before the tag handlers get it. - * Values filled in by the preformat are never parsed as tags. + * Creates a markup formatter that fills values into the message through a preformat. + * The preformat gets the whole message, so it can be `params`, `plural`, `match` or a composition of them. + * Only the tags of the message are mapped: values filled in by the preformat are never parsed as tags. * @param tags - Tag handlers used to map markup tags to strings. - * @param preformat - Formatter of each text piece between the tags, like `params`. + * @param preformat - Formatter of the message, like `params`, `plural` or `match`. * @returns Formatter that returns a message function of the preformat parameters. */ -export function markup

( +export function markup( tags: MarkupTags, - preformat: RichPreformat

-): Format string | undefined> + preformat: RichPreformat +): Format string | undefined> /** - * Creates a markup formatter with a fallback message that formats each text piece before the tag handlers get it. - * Values filled in by the preformat are never parsed as tags. + * Creates a markup formatter with a fallback message that fills values into the message through a preformat. + * The preformat gets the whole message, so it can be `params`, `plural`, `match` or a composition of them. + * Only the tags of the message are mapped: values filled in by the preformat are never parsed as tags. * @param fallback - Message used when the input is `undefined` or `null`. * @param tags - Tag handlers used to map markup tags to strings. - * @param preformat - Formatter of each text piece between the tags, like `params`. + * @param preformat - Formatter of the message, like `params`, `plural` or `match`. * @returns Formatter that returns a message function of the preformat parameters. */ -export function markup

( +export function markup( fallback: string, tags: MarkupTags, - preformat: RichPreformat

-): Format string> + preformat: RichPreformat +): Format string> /* @__NO_SIDE_EFFECTS__ */ -export function markup

( +export function markup( fallbackOrTags: string | MarkupTags, - tagsOrPreformat?: MarkupTags | RichPreformat

, - maybePreformat?: RichPreformat

-): Format string | undefined) | undefined> { + tagsOrPreformat?: MarkupTags | RichPreformat, + maybePreformat?: RichPreformat +): Format string | undefined) | undefined> { let fallback: string | undefined let tags = fallbackOrTags as MarkupTags let preformat = maybePreformat diff --git a/packages/intl/src/format/match.spec.ts b/packages/intl/src/format/match.spec.ts index 5f4a544e..1f2bb70a 100644 --- a/packages/intl/src/format/match.spec.ts +++ b/packages/intl/src/format/match.spec.ts @@ -1,6 +1,7 @@ import { describe, expect, + expectTypeOf, it } from 'vitest' import type { FormatContext } from '../types.js' @@ -14,6 +15,7 @@ import { other, match } from './match.js' +import { rich } from './rich.js' const ctx: FormatContext = { $locale: () => 'en-US' @@ -247,6 +249,18 @@ describe('intl', () => { role: 'guest' })).toBe('Area of guest') }) + + it('should take only cases that render text', () => { + const tags = { + strong: (chunks: unknown[]) => chunks + } + + expectTypeOf(cases({ + admin: text(), + // @ts-expect-error tags of a rich message map around the whole message, `rich(tags, match(...))` + member: rich(tags) + })).toBeFunction() + }) }) }) }) diff --git a/packages/intl/src/format/match.ts b/packages/intl/src/format/match.ts index beea5ae2..57f67b05 100644 --- a/packages/intl/src/format/match.ts +++ b/packages/intl/src/format/match.ts @@ -7,7 +7,6 @@ import { import type { FormatContext } from '../types.js' import type { AnyFormat, - FnWithAnyParams, FnWithParams, Format, FormatsInput, @@ -42,6 +41,9 @@ export type CasesFn< s: true } +// A case renders text: tags of a rich message are mapped around the whole message, `rich(tags, match(...))` +type CaseFormat = AnyFormat> + type GetKey = ( param: any, locale: string, @@ -56,7 +58,7 @@ type GetKey = ( /* @__NO_SIDE_EFFECTS__ */ export function cases< const K extends string, - const B extends Partial> + const B extends Partial> >( cases: B ): CasesFn { @@ -139,7 +141,7 @@ export function match< FormatsInput | string, MatchFn > { - const valuePattern = new RegExp(`{${param}}`, 'g') + const valuePattern = new RegExp(`{${param}}`, 'gi') let cases: CasesFn | undefined let getKey: GetKey @@ -153,8 +155,10 @@ export function match< return (ctx, input: FormatsInput | string | undefined) => { const locale = ctx.$locale() const isString = typeof input === 'string' + // A surrounding `params` that lists the param replaces its placeholder itself + const filled = ctx.f?.[param] // A string never reaches the lookups below, so it is stored as is. - let resolvedCases = (input ?? {}) as Record + let resolvedCases = (input ?? {}) as Record> if (cases && !isString) { resolvedCases = { @@ -164,12 +168,12 @@ export function match< cases(ctx, input, resolvedCases) } - return (params, formats?: Record) => { + return (params) => { const value = $get(typeof params === 'object' ? params[param] : params) const resolvedCase = isString ? input : resolvedCases[getKey(value, locale, resolvedCases)] - const message = isFunction(resolvedCase) ? resolvedCase(params, formats) : resolvedCase + const message = isFunction(resolvedCase) ? resolvedCase(params) : resolvedCase - return formats && param in formats + return filled ? message : message?.replace(valuePattern, value as string) } diff --git a/packages/intl/src/format/params.spec.ts b/packages/intl/src/format/params.spec.ts index 45e4f27c..720c5ee6 100644 --- a/packages/intl/src/format/params.spec.ts +++ b/packages/intl/src/format/params.spec.ts @@ -14,8 +14,14 @@ import { forms, plural } from './plural.js' -import { text } from './text.js' +import { + lowercase, + text, + uppercase +} from './text.js' +import { markup } from './markup.js' import { params } from './params.js' +import { wrap } from './wrap.js' const ctx: FormatContext = { $locale: () => 'en-US' @@ -205,6 +211,50 @@ describe('intl', () => { })).toBe('She has 1,284 items') }) + it('should fill in the param of a plural formatter inside wrap', () => { + const format = params({ + count: number() + }, wrap(plural('count'), (message, values) => message(values))) + + expect(format(ctx, { + one: '{count} item', + other: '{count} items' + })({ + count: 1284 + })).toBe('1,284 items') + }) + + it('should fill in the param of a plural formatter inside markup', () => { + const format = params({ + count: number() + }, markup({ + strong: chunks => `${chunks}` + }, plural('count'))) + + expect(format(ctx, { + one: '{count} item', + other: '{count} items' + })({ + count: 1284 + })).toBe('1,284 items') + }) + + it('should replace placeholders of a translation with transformed case', () => { + const upper = params({ + name: text() + }, uppercase(text())) + const lower = params({ + userName: text() + }, lowercase(text())) + + expect(upper(ctx, 'Hello {name}')({ + name: 'Ada' + })).toBe('HELLO Ada') + expect(lower(ctx, 'Hello {userName}')({ + userName: 'Ada' + })).toBe('hello Ada') + }) + it('should fill in the param of a match formatter', () => { const format = params({ status: text() diff --git a/packages/intl/src/format/params.ts b/packages/intl/src/format/params.ts index 1be77297..4d1dfe10 100644 --- a/packages/intl/src/format/params.ts +++ b/packages/intl/src/format/params.ts @@ -5,7 +5,6 @@ import { } from '@nano_kit/store' import type { FormatContext } from '../types.js' import type { - FnWithAnyParams, Format, FormatInput, FormatOutput, @@ -32,7 +31,7 @@ export type ParamsValues

= { export type ParamsFn

= FnWithParams> -type PreformatOutput = string | undefined | FnWithAnyParams +type PreformatOutput = string | undefined | FnWithParams type ComposedParamsFn

= FnWithParams & UnionToIntersection>> @@ -50,7 +49,7 @@ export function params( /** * Creates a parameter interpolation formatter that first applies another formatter. * @param params - Parameter formatters keyed by placeholder name. - * @param preformat - Formatter applied before replacing placeholders. `match` and `plural` leave the placeholders of the parameters listed here to be replaced by these formatters. + * @param preformat - Formatter applied before replacing placeholders. `match` and `plural` inside it leave the placeholders of the parameters listed here to be replaced by these formatters. * @returns Formatter that replaces `{key}` placeholders using provided parameter values. */ export function params< @@ -88,7 +87,7 @@ export function params< } } - const re = new RegExp(`{${key}}`, 'g') + const re = new RegExp(`{${key}}`, 'gi') const replace: Replace = (ctx, text, params) => text.replace(re, () => format(ctx, $get(params[key])) as string) if (replaceAll) { @@ -101,11 +100,18 @@ export function params< } return (ctx: FormatContext, input?: F) => { - const preformatted = (preformat ? preformat(ctx, input) : input) as PreformatOutput + const preformatted = ( + preformat + ? preformat({ + ...ctx, + f: params + }, input) + : input + ) as PreformatOutput if (isFunction(preformatted)) { return (values) => { - const text = preformatted(values, params) + const text = preformatted(values) if (text === undefined || !replaceAll) { return text diff --git a/packages/intl/src/format/plural.spec.ts b/packages/intl/src/format/plural.spec.ts index 7e8d6f4e..78aeb795 100644 --- a/packages/intl/src/format/plural.spec.ts +++ b/packages/intl/src/format/plural.spec.ts @@ -4,7 +4,10 @@ import { it } from 'vitest' import type { FormatContext } from '../types.js' -import { text } from './text.js' +import { + text, + uppercase +} from './text.js' import { match, cases @@ -234,6 +237,20 @@ describe('intl', () => { count: 1 })).toBe('1 going') }) + + it('should fill in the value of forms with transformed case', () => { + const format = plural('count', forms({ + one: uppercase(text()), + other: uppercase(text()) + })) + + expect(format(ctx, { + one: '{count} item', + other: '{count} items' + })({ + count: 3 + })).toBe('3 ITEMS') + }) }) }) }) diff --git a/packages/intl/src/format/rich.spec.ts b/packages/intl/src/format/rich.spec.ts index a2a5c931..5d25252c 100644 --- a/packages/intl/src/format/rich.spec.ts +++ b/packages/intl/src/format/rich.spec.ts @@ -8,10 +8,18 @@ import { mapTags, rich } from './rich.js' +import { + cases, + match +} from './match.js' +import { number } from './number.js' import { params } from './params.js' +import { plural } from './plural.js' import { text } from './text.js' -const ctx = {} as FormatContext +const ctx: FormatContext = { + $locale: () => 'en-US' +} interface Node { type: string @@ -214,7 +222,7 @@ describe('intl', () => { ]) }) - it('should format each text piece with the preformat', () => { + it('should fill values into the message with the preformat', () => { const format = rich(tags, params({ name: text(), count: text() @@ -273,6 +281,134 @@ describe('intl', () => { name: 'Ada' })).toBeUndefined() }) + + it('should choose a plural form with the preformat', () => { + const format = rich(tags, plural('count')) + const message = format(ctx, { + one: '{count} plant', + other: '{count} plants' + }) + const plants = [ + { + type: 'strong', + children: ['3'] + }, + ' plants' + ] + + expect(message({ + count: 3 + })).toEqual(plants) + expect(message(3)).toEqual(plants) + }) + + it('should format the value of a plural form with params', () => { + const format = rich(tags, params({ + count: number() + }, plural('count'))) + + expect(format(ctx, { + one: '{count} plant', + other: '{count} plants' + })({ + count: 1284 + })).toEqual([ + { + type: 'strong', + children: ['1,284'] + }, + ' plants' + ]) + }) + + it('should choose a case with the preformat', () => { + const format = rich(tags, params({ + name: text() + }, match('role'))) + + expect(format(ctx, { + admin: '{name} runs the garden', + member: '{name} tends the garden' + })({ + name: 'Ada', + role: 'member' + })).toEqual([ + { + type: 'strong', + children: ['Ada'] + }, + ' tends the garden' + ]) + }) + + it('should choose nested cases and plural forms with the preformat', () => { + const format = rich(tags, match('role', cases({ + admin: plural('count'), + member: plural('count') + }))) + + expect(format(ctx, { + admin: { + one: 'Admin of {count} garden', + other: 'Admin of {count} gardens' + }, + member: { + one: 'Member of {count} garden', + other: 'Member of {count} gardens' + } + })({ + role: 'member', + count: 2 + })).toEqual([ + { + type: 'strong', + children: ['Member'] + }, + ' of 2 gardens' + ]) + }) + + it('should keep tags in values of a plural form as text', () => { + const format = rich(tags, params({ + name: text() + }, plural('count'))) + + expect(format(ctx, { + one: '{name} has {count} plant', + other: '{name} has {count} plants' + })({ + name: 'Tom Jerry', + count: 2 + })).toEqual([ + { + type: 'strong', + children: ['Tom Jerry'] + }, + ' has 2 plants' + ]) + }) + + it('should choose a plural form of a fallback message', () => { + const format = rich('{count} items', tags, plural('count')) + + expect(format(ctx)({ + count: 2 + })).toEqual([ + { + type: 'strong', + children: ['2'] + }, + ' items' + ]) + }) + + it('should return undefined from the message of a missing plural form', () => { + const format = rich(tags, plural('count')) + + expect(format(ctx, { + one: '{count} plant' + })(2)).toBeUndefined() + }) }) }) }) diff --git a/packages/intl/src/format/rich.ts b/packages/intl/src/format/rich.ts index 865d6adf..5ab96b95 100644 --- a/packages/intl/src/format/rich.ts +++ b/packages/intl/src/format/rich.ts @@ -10,7 +10,7 @@ export type RichTag = (chunks: RichChunks, index: number) => T export type RichTags = Record> -export type RichPreformat

= Format> +export type RichPreformat = Format> /** * Creates a rich-text formatter. @@ -33,50 +33,52 @@ export function rich( ): Format> /** - * Creates a rich-text formatter that formats each text piece before the tag handlers get it. - * Values filled in by the preformat are never parsed as tags. + * Creates a rich-text formatter that fills values into the message through a preformat. + * The preformat gets the whole message, so it can be `params`, `plural`, `match` or a composition of them. + * Only the tags of the message are mapped: values filled in by the preformat are never parsed as tags. * @param tags - Tag handlers used to map rich-text tags to output chunks. - * @param preformat - Formatter of each text piece between the tags, like `params`. + * @param preformat - Formatter of the message, like `params`, `plural` or `match`. * @returns Formatter that returns a message function of the preformat parameters. */ -export function rich( +export function rich( tags: RichTags, - preformat: RichPreformat

-): Format RichChunks | undefined> + preformat: RichPreformat +): Format RichChunks | undefined> /** - * Creates a rich-text formatter with a fallback message that formats each text piece before the tag handlers get it. - * Values filled in by the preformat are never parsed as tags. + * Creates a rich-text formatter with a fallback message that fills values into the message through a preformat. + * The preformat gets the whole message, so it can be `params`, `plural`, `match` or a composition of them. + * Only the tags of the message are mapped: values filled in by the preformat are never parsed as tags. * @param fallback - Message used when the input is `undefined` or `null`. * @param tags - Tag handlers used to map rich-text tags to output chunks. - * @param preformat - Formatter of each text piece between the tags, like `params`. + * @param preformat - Formatter of the message, like `params`, `plural` or `match`. * @returns Formatter that returns a message function of the preformat parameters. */ -export function rich( +export function rich( fallback: string, tags: RichTags, - preformat: RichPreformat

-): Format RichChunks> + preformat: RichPreformat +): Format RichChunks> /** * Creates a rich-text formatter. * @param fallbackOrTags - Fallback message or tag handlers. * @param tagsOrPreformat - Tag handlers used when fallback is provided, or the preformat. - * @param maybePreformat - Formatter of each text piece used when fallback is provided. + * @param maybePreformat - Formatter of the message used when fallback is provided. * @returns Formatter that returns mapped chunks, a message function of them or `undefined`. */ -export function rich( +export function rich( fallbackOrTags: string | RichTags | undefined, - tagsOrPreformat?: RichTags | RichPreformat

, - maybePreformat?: RichPreformat

-): Format | ((params: P) => RichChunks | undefined) | undefined> + tagsOrPreformat?: RichTags | RichPreformat, + maybePreformat?: RichPreformat +): Format | ((params: P) => RichChunks | undefined) | undefined> /* @__NO_SIDE_EFFECTS__ */ -export function rich( +export function rich( fallbackOrTags: string | RichTags | undefined, - tagsOrPreformat?: RichTags | RichPreformat

, - maybePreformat?: RichPreformat

-): Format | ((params: P) => RichChunks | undefined) | undefined> { + tagsOrPreformat?: RichTags | RichPreformat, + maybePreformat?: RichPreformat +): Format | ((params: P) => RichChunks | undefined) | undefined> { let fallback: string | undefined let tags = fallbackOrTags as RichTags let preformat = maybePreformat @@ -89,21 +91,25 @@ export function rich( } return (ctx, input) => { - const text = input ?? fallback + const text = markTags(input ?? fallback) if (preformat) { - return params => ( - text === undefined - ? text - : mapTags(text, tags, piece => preformat(ctx, piece)(params) as string) - ) + const message = preformat(ctx, text as I) + + return (params) => { + const filled = message(params) + + return filled === undefined ? filled : parseTags(filled, tags) + } } - return text === undefined ? text : mapTags(text, tags) + return text === undefined ? text : parseTags(text as string, tags) } } -const tagRegex = /<(\/?)([A-Za-z][\w.-]*)\s*(\/?)>/g +// Finds tags. `markTags` puts NUL before the tags of a message, so the message filled with values tells its own tags from the text of the values +// oxlint-disable-next-line eslint/no-control-regex +const tagRegex = /(\0?)<(\/?)([A-Za-z][\w.-]*)\s*(\/?)>/g interface RichFrame { tag: string @@ -111,17 +117,38 @@ interface RichFrame { } /** - * Maps rich-text tags in a string to chunks using provided tag handlers. - * Each handler call receives an unique index, usable as a key for framework nodes. - * Self-closing tags are mapped with empty chunks. - * Unknown or malformed tags are ignored as markup and only their text content is kept. - * @param input - Rich-text input string. + * Marks the tags of a message, nested in forms and cases at any depth, before values are filled into it. + * @param input - Message, or forms and cases of messages. + * @returns Message with marked tags. + */ +/* @__NO_SIDE_EFFECTS__ */ +function markTags(input: unknown): unknown { + if (typeof input === 'string') { + return input.replace(tagRegex, '\0$&') + } + + if (input && typeof input === 'object') { + const marked: Record = {} + + for (const key in input as Record) { + marked[key] = markTags((input as Record)[key]) + } + + return marked + } + + return input +} + +/** + * Maps the marked tags of a message to chunks. Other tags stay text. + * @param input - Message with marked tags. * @param tags - Tag handlers used to map known tags. * @param formatText - Formatter of each text piece between the tags, applied before the tag handlers get it. * @returns Mapped chunks. */ /* @__NO_SIDE_EFFECTS__ */ -export function mapTags( +function parseTags( input: string, tags: RichTags, formatText: (text: string) => string = String @@ -139,7 +166,13 @@ export function mapTags( tagRegex.lastIndex = 0 while (match = tagRegex.exec(input)) { - const [, closing, tag, selfClosing] = match + const [, marked, closing, tag, selfClosing] = match + + // A tag in a filled in value is its text + if (!marked) { + continue + } + const current = stack[stack.length - 1] if (match.index > lastIndex) { @@ -182,3 +215,22 @@ export function mapTags( return root.chunks } + +/** + * Maps rich-text tags in a string to chunks using provided tag handlers. + * Each handler call receives an unique index, usable as a key for framework nodes. + * Self-closing tags are mapped with empty chunks. + * Unknown or malformed tags are ignored as markup and only their text content is kept. + * @param input - Rich-text input string. + * @param tags - Tag handlers used to map known tags. + * @param formatText - Formatter of each text piece between the tags, applied before the tag handlers get it. + * @returns Mapped chunks. + */ +/* @__NO_SIDE_EFFECTS__ */ +export function mapTags( + input: string, + tags: RichTags, + formatText?: (text: string) => string +): RichChunks { + return parseTags(markTags(input) as string, tags, formatText) +} diff --git a/packages/intl/src/format/text.spec.ts b/packages/intl/src/format/text.spec.ts index c7c295a9..11e48569 100644 --- a/packages/intl/src/format/text.spec.ts +++ b/packages/intl/src/format/text.spec.ts @@ -10,6 +10,9 @@ import { text, uppercase } from './text.js' +import { number } from './number.js' +import { params } from './params.js' +import { plural } from './plural.js' const ctx: FormatContext = { $locale: () => 'en-US' @@ -59,6 +62,41 @@ describe('intl', () => { expect(format(ctx)).toBeUndefined() }) + + it('should transform the text of a message function', () => { + const upper = uppercase(params({ + name: text() + })) + const lower = lowercase(params({ + count: number() + }, plural('count'))) + const capital = capitalize(params({ + name: text() + })) + + expect(upper(ctx, 'Hello {name}')({ + name: 'Ada' + })).toBe('HELLO ADA') + expect(lower(ctx, { + one: '{count} ITEM', + other: '{count} ITEMS' + })({ + count: 1284 + })).toBe('1,284 items') + expect(capital(ctx, '{name} joined')({ + name: 'ada' + })).toBe('Ada joined') + }) + + it('should preserve undefined text of a message function', () => { + const format = capitalize(params({ + name: text() + })) + + expect(format(ctx)({ + name: 'Ada' + })).toBeUndefined() + }) }) }) }) diff --git a/packages/intl/src/format/text.ts b/packages/intl/src/format/text.ts index c55875c5..24e2afc5 100644 --- a/packages/intl/src/format/text.ts +++ b/packages/intl/src/format/text.ts @@ -1,4 +1,8 @@ -import type { Format } from './types.js' +import { isFunction } from '@nano_kit/store' +import type { + FnWithParams, + Format +} from './types.js' import { raw } from './raw.js' /** @@ -19,9 +23,32 @@ export function text(fallback?: string): Format { return raw(fallback) } +type Transform = (message: string | undefined, locale: string) => string | undefined + +/** + * Applies a text transform to the output of a formatter, or to the text of the message function it returns. + * @param format - Formatter to transform. + * @param fn - Text transform. + * @returns Formatter with transformed output. + */ +/* @__NO_SIDE_EFFECTS__ */ +function transform( + format: Format>, + fn: Transform +): Format> { + return (ctx, input) => { + const message = format(ctx, input) + const locale = ctx.$locale() + + return isFunction(message) + ? params => fn(message(params), locale) + : fn(message, locale) + } +} + /** - * Creates a formatter that uppercases another text formatter output. - * @param format - Text formatter to transform. + * Creates a formatter that uppercases the text of another formatter. + * @param format - Formatter of a text, or of a message function like `params` or `plural`. * @returns Formatter with uppercased output. */ export function uppercase( @@ -32,16 +59,20 @@ export function uppercase( format: Format ): Format +export function uppercase( + format: Format> +): Format> + /* @__NO_SIDE_EFFECTS__ */ export function uppercase( - format: Format -): Format { - return (ctx, input) => format(ctx, input)?.toLocaleUpperCase(ctx.$locale()) + format: Format> +): Format> { + return transform(format, (message, locale) => message?.toLocaleUpperCase(locale)) } /** - * Creates a formatter that lowercases another text formatter output. - * @param format - Text formatter to transform. + * Creates a formatter that lowercases the text of another formatter. + * @param format - Formatter of a text, or of a message function like `params` or `plural`. * @returns Formatter with lowercased output. */ export function lowercase( @@ -52,22 +83,20 @@ export function lowercase( format: Format ): Format +export function lowercase( + format: Format> +): Format> + /* @__NO_SIDE_EFFECTS__ */ export function lowercase( - format: Format -): Format { - return (ctx, input) => format(ctx, input)?.toLocaleLowerCase(ctx.$locale()) -} - -function toCapitalize(message: string | undefined, locale: string) { - return message === undefined - ? message - : message.charAt(0).toLocaleUpperCase(locale) + message.slice(1) + format: Format> +): Format> { + return transform(format, (message, locale) => message?.toLocaleLowerCase(locale)) } /** - * Creates a formatter that capitalizes another text formatter output. - * @param format - Text formatter to transform. + * Creates a formatter that capitalizes the text of another formatter. + * @param format - Formatter of a text, or of a message function like `params` or `plural`. * @returns Formatter with the first character uppercased. */ export function capitalize( @@ -78,9 +107,17 @@ export function capitalize( format: Format ): Format +export function capitalize( + format: Format> +): Format> + /* @__NO_SIDE_EFFECTS__ */ export function capitalize( - format: Format -): Format { - return (ctx, input) => toCapitalize(format(ctx, input), ctx.$locale()) + format: Format> +): Format> { + return transform(format, (message, locale) => ( + message === undefined + ? message + : message.charAt(0).toLocaleUpperCase(locale) + message.slice(1) + )) } diff --git a/packages/intl/src/format/types.ts b/packages/intl/src/format/types.ts index 12ec6cfb..895221bb 100644 --- a/packages/intl/src/format/types.ts +++ b/packages/intl/src/format/types.ts @@ -28,9 +28,6 @@ export type FormatsInput>> = Pa export type FnWithParams

= (params: P) => string | undefined -// `formats` are the params a surrounding `params` fills in itself -export type FnWithAnyParams = (params: any, formats?: Record) => string | undefined - export interface IntlFormat { format(value: T, ...args: unknown[]): string } diff --git a/packages/intl/src/format/wrap.spec.ts b/packages/intl/src/format/wrap.spec.ts index 8b7f3eb9..37e88c3a 100644 --- a/packages/intl/src/format/wrap.spec.ts +++ b/packages/intl/src/format/wrap.spec.ts @@ -7,6 +7,7 @@ import { import type { FormatContext } from '../types.js' import { datetime } from './datetime.js' import { format } from './format.js' +import { number } from './number.js' import { forms, plural @@ -107,6 +108,23 @@ describe('intl', () => { })).toBe('Ada has 2 plants') }) + it('should pass back the values of a param formatted for plural', () => { + const format = wrap(params({ + count: number() + }, plural('count')), (message, values) => (values.count === 0 ? 'No plants' : message(values))) + const message = format(ctx, { + one: '{count} plant', + other: '{count} plants' + }) + + expect(message({ + count: 1284 + })).toBe('1,284 plants') + expect(message({ + count: 0 + })).toBe('No plants') + }) + it('should pass a date of a call made with the value itself as is', () => { const formatDate = wrap(format(datetime({ dateStyle: 'medium', diff --git a/packages/intl/src/format/wrap.ts b/packages/intl/src/format/wrap.ts index f984577d..052d4e73 100644 --- a/packages/intl/src/format/wrap.ts +++ b/packages/intl/src/format/wrap.ts @@ -1,6 +1,5 @@ import { type Accessor, - type SignalishValue, isFunction } from '@nano_kit/store' import { read } from '../utils.js' @@ -9,11 +8,14 @@ import type { Format } from './types.js' +// A value read from a signal or an accessor. Unlike `SignalishValue`, it keeps a param typed by both `params` and `plural` as their common type +type ReadValue = Exclude> + export type WrapValues = A extends Accessor ? V : A extends Record ? { - [K in keyof A]: SignalishValue + [K in keyof A]: ReadValue } : A diff --git a/packages/intl/src/types.ts b/packages/intl/src/types.ts index d41afdbd..cc3547f0 100644 --- a/packages/intl/src/types.ts +++ b/packages/intl/src/types.ts @@ -73,6 +73,10 @@ export type UnionToIntersection = ( export interface FormatContext { $locale: Accessor + /** + * Formats of the params a surrounding `params` replaces itself: `match` and `plural` inside it leave their placeholders. + */ + f?: Record } export type Bound = Omit & { diff --git a/skills/nano-kit-intl/DOCS.md b/skills/nano-kit-intl/DOCS.md index 0aa8d8a1..b254d153 100644 --- a/skills/nano-kit-intl/DOCS.md +++ b/skills/nano-kit-intl/DOCS.md @@ -413,6 +413,27 @@ $t().title // 'Hello' ``` +A message function, like one of `params` or `plural`, is transformed as it renders, values included. + +```ts +const translations = { + home: { + greeting: 'Hello, {name}' + } +} + +const [$t] = messages('home', { + greeting: uppercase(params({ + name: text() + })) +}) + +$t().greeting({ + name: 'Ada' +}) +// 'HELLO, ADA' +``` + ## Parameterized Messages ### `params(params, preformat?)` @@ -864,7 +885,7 @@ $t().message // ['Read ', the docs,
, 'today'] ``` -With a preformat, like `params`, `rich` fills values into the message. It formats each text piece between the tags before the tag handlers get it, so a value is never read as a tag: `` in a name stays text. +With a preformat, like `params`, `rich` fills values into the message. Tags are read from the message before the values go in, so a value is never read as a tag: `` in a name stays text. ```ts const translations = { @@ -887,7 +908,33 @@ $t().welcome({ // ['Welcome back, ', Ada, '!'] ``` -The preformat sees one piece at a time, so `plural` and `match`, which choose from the whole message, do not fit there. +The preformat gets the whole message, so plural forms and cases fit there too: `plural`, `match` or `params` around them. + +```ts +const translations = { + garden: { + plants: { + one: '{count} plant', + other: '{count} plants' + } + } +} + +const [$t] = messages('garden', { + plants: rich({ + b: (chunks, i) => {chunks} + }, params({ + count: number() + }, plural('count'))) +}) + +$t().plants({ + count: 1284 +}) +// [1,284, ' plants'] +``` + +Tags map around the whole message, so `forms(...)` and `cases(...)` hold text formats and `rich` stays outside them. ### `markup(tags)` / `markup(fallback, tags)` diff --git a/skills/nano-kit-intl/SKILL.md b/skills/nano-kit-intl/SKILL.md index da03c42c..fbe9d43a 100644 --- a/skills/nano-kit-intl/SKILL.md +++ b/skills/nano-kit-intl/SKILL.md @@ -46,7 +46,7 @@ metadata: - Logic deciding how a message renders from its parameters, like a template that applies only when every part is present, belongs in the scheme through `wrap(...)`, not in helpers at the call sites: every call site then renders the same and keeps the inferred message type. Variants that translators word differently stay `match` or `plural` cases. - `format(...)` messages format application values and take a value argument; `params(...)` messages fill placeholders in translated text and take an object of parameters. Do not mix them up. Pass application state to a `format()` message as the signal itself, `$t.eventDate($startsAt)`: the message follows it, and `null` formats like a missing value while the data loads. - `plural` and `match` fill in their value as it is. A count with thousands takes `params({ count: number() }, plural('count'))`: `plural` picks the form by the value, and `params` fills in the placeholder. A message wrapped this way takes an object, not the bare value. -- A rich message with values takes `params` as its preformat, `rich(tags, params({ ... }))`: each text piece is formatted before the tag handlers get it, so values never turn into tags. `params(..., rich(...))` does not work: `params` fills strings and `rich` returns chunks. +- A rich message with values, plural forms or cases takes them as its preformat: `rich(tags, params({ ... }))`, `rich(tags, plural('count'))` or `rich(tags, params({ count: number() }, plural('count')))`. Tags are read before values go in, so values never turn into tags. Tags go around the whole message: `params(..., rich(...))` and `rich` inside `forms(...)` or `cases(...)` do not work, as they fill text and `rich` returns chunks. - A value shown in one of several formats depending on the value itself, like a recent time as relative and an older one as a date, is `choose(formats, (t, value) => ...)`: the function calls the format it picks. `match` with a computed key does not fit: it reads translations and takes a `Date` for an object of parameters. ## Locale diff --git a/website/src/content/docs/intl/api.mdx b/website/src/content/docs/intl/api.mdx index d83ae2c2..a02ad0e9 100644 --- a/website/src/content/docs/intl/api.mdx +++ b/website/src/content/docs/intl/api.mdx @@ -75,6 +75,27 @@ $t().title // 'Hello' ``` +A message function, like one of `params` or `plural`, is transformed as it renders, values included. + +```ts +const translations = { + home: { + greeting: 'Hello, {name}' + } +} + +const [$t] = messages('home', { + greeting: uppercase(params({ + name: text() + })) +}) + +$t().greeting({ + name: 'Ada' +}) +// 'HELLO, ADA' +``` + ## Parameterized Messages ### `params(params, preformat?)` @@ -526,7 +547,7 @@ $t().message // ['Read ', the docs,
, 'today'] ``` -With a preformat, like `params`, `rich` fills values into the message. It formats each text piece between the tags before the tag handlers get it, so a value is never read as a tag: `` in a name stays text. +With a preformat, like `params`, `rich` fills values into the message. Tags are read from the message before the values go in, so a value is never read as a tag: `` in a name stays text. ```ts const translations = { @@ -549,7 +570,33 @@ $t().welcome({ // ['Welcome back, ', Ada, '!'] ``` -The preformat sees one piece at a time, so `plural` and `match`, which choose from the whole message, do not fit there. +The preformat gets the whole message, so plural forms and cases fit there too: `plural`, `match` or `params` around them. + +```ts +const translations = { + garden: { + plants: { + one: '{count} plant', + other: '{count} plants' + } + } +} + +const [$t] = messages('garden', { + plants: rich({ + b: (chunks, i) => {chunks} + }, params({ + count: number() + }, plural('count'))) +}) + +$t().plants({ + count: 1284 +}) +// [1,284, ' plants'] +``` + +Tags map around the whole message, so `forms(...)` and `cases(...)` hold text formats and `rich` stays outside them. ### `markup(tags)` / `markup(fallback, tags)`