Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions packages/intl/.size-limit.json
Original file line number Diff line number Diff line change
Expand Up @@ -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)",
Expand All @@ -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"
}
]
21 changes: 19 additions & 2 deletions packages/intl/src/format/markup.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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) => `<a>${chunks}</a>`,
strong: (chunks: string) => `<strong>${chunks}</strong>`
Expand Down Expand Up @@ -59,7 +63,7 @@ describe('intl', () => {
expect(format(ctx, 'Read <link>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()
}))
Expand Down Expand Up @@ -88,6 +92,19 @@ describe('intl', () => {
name: 'Ada'
})).toBe('By <strong>Ada</strong>')
})

it('should choose a plural form with the preformat', () => {
const format = markup(tags, params({
count: number()
}, plural('count')))

expect(format(ctx, {
one: '<strong>{count}</strong> plant',
other: '<strong>{count}</strong> plants'
})({
count: 1284
})).toBe('<strong>1,284</strong> plants')
})
})
})
})
34 changes: 18 additions & 16 deletions packages/intl/src/format/markup.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,37 +31,39 @@ export function markup(
): Format<string | undefined, string>

/**
* 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<P>(
export function markup<P, I = string | undefined>(
tags: MarkupTags,
preformat: RichPreformat<P>
): Format<string | undefined, (params: P) => string | undefined>
preformat: RichPreformat<P, I>
): Format<I, (params: P) => 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<P>(
export function markup<P, I = string | undefined>(
fallback: string,
tags: MarkupTags,
preformat: RichPreformat<P>
): Format<string | undefined, (params: P) => string>
preformat: RichPreformat<P, I>
): Format<I, (params: P) => string>

/* @__NO_SIDE_EFFECTS__ */
export function markup<P>(
export function markup<P, I = string | undefined>(
fallbackOrTags: string | MarkupTags,
tagsOrPreformat?: MarkupTags | RichPreformat<P>,
maybePreformat?: RichPreformat<P>
): Format<string | undefined, string | ((params: P) => string | undefined) | undefined> {
tagsOrPreformat?: MarkupTags | RichPreformat<P, I>,
maybePreformat?: RichPreformat<P, I>
): Format<I, string | ((params: P) => string | undefined) | undefined> {
let fallback: string | undefined
let tags = fallbackOrTags as MarkupTags
let preformat = maybePreformat
Expand Down
14 changes: 14 additions & 0 deletions packages/intl/src/format/match.spec.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import {
describe,
expect,
expectTypeOf,
it
} from 'vitest'
import type { FormatContext } from '../types.js'
Expand All @@ -14,6 +15,7 @@ import {
other,
match
} from './match.js'
import { rich } from './rich.js'

const ctx: FormatContext = {
$locale: () => 'en-US'
Expand Down Expand Up @@ -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()
})
})
})
})
18 changes: 11 additions & 7 deletions packages/intl/src/format/match.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@ import {
import type { FormatContext } from '../types.js'
import type {
AnyFormat,
FnWithAnyParams,
FnWithParams,
Format,
FormatsInput,
Expand Down Expand Up @@ -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<string | undefined | FnWithParams<any>>

type GetKey = (
param: any,
locale: string,
Expand All @@ -56,7 +58,7 @@ type GetKey = (
/* @__NO_SIDE_EFFECTS__ */
export function cases<
const K extends string,
const B extends Partial<Record<string, AnyFormat>>
const B extends Partial<Record<string, CaseFormat>>
>(
cases: B
): CasesFn<K, B> {
Expand Down Expand Up @@ -139,7 +141,7 @@ export function match<
FormatsInput<B> | string,
MatchFn<K, B>
> {
const valuePattern = new RegExp(`{${param}}`, 'g')
const valuePattern = new RegExp(`{${param}}`, 'gi')
let cases: CasesFn<K, B> | undefined
let getKey: GetKey

Expand All @@ -153,8 +155,10 @@ export function match<
return (ctx, input: FormatsInput<B> | 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<string, string | undefined | FnWithAnyParams>
let resolvedCases = (input ?? {}) as Record<string, string | undefined | FnWithParams<unknown>>

if (cases && !isString) {
resolvedCases = {
Expand All @@ -164,12 +168,12 @@ export function match<
cases(ctx, input, resolvedCases)
}

return (params, formats?: Record<string, unknown>) => {
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)
}
Expand Down
52 changes: 51 additions & 1 deletion packages/intl/src/format/params.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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'
Expand Down Expand Up @@ -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 => `<strong>${chunks}</strong>`
}, plural('count')))

expect(format(ctx, {
one: '<strong>{count}</strong> item',
other: '<strong>{count}</strong> items'
})({
count: 1284
})).toBe('<strong>1,284</strong> 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()
Expand Down
18 changes: 12 additions & 6 deletions packages/intl/src/format/params.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ import {
} from '@nano_kit/store'
import type { FormatContext } from '../types.js'
import type {
FnWithAnyParams,
Format,
FormatInput,
FormatOutput,
Expand All @@ -32,7 +31,7 @@ export type ParamsValues<P extends ParamsFormats> = {

export type ParamsFn<P extends ParamsFormats> = FnWithParams<ParamsValues<P>>

type PreformatOutput = string | undefined | FnWithAnyParams
type PreformatOutput = string | undefined | FnWithParams<any>

type ComposedParamsFn<P extends ParamsFormats, O> = FnWithParams<ParamsValues<P> & UnionToIntersection<ParamsOf<O>>>

Expand All @@ -50,7 +49,7 @@ export function params<const P extends ParamsFormats>(
/**
* 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<
Expand Down Expand Up @@ -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) {
Expand All @@ -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
Expand Down
19 changes: 18 additions & 1 deletion packages/intl/src/format/plural.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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')
})
})
})
})
Loading