Skip to content
Draft
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
8 changes: 8 additions & 0 deletions index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,3 +23,11 @@ export { ExtractTemplateParams, params } from './params/index.js'
export { createProcessor } from './processor/index.js'
export { strings, transform, TranslationTransform } from './transforms/index.js'
export { translationsLoading } from './translations-loading/index.js'
export {
messageFormat,
getMessageFormatParts,
MessageFormatPart,
MessageFormatMarkupPart,
MessageFormatStringPart,
MessageFormatTextPart
} from './message-format/index.js'
1 change: 1 addition & 0 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,3 +10,4 @@ export { params } from './params/index.js'
export { createProcessor } from './processor/index.js'
export { strings, transform } from './transforms/index.js'
export { translationsLoading } from './translations-loading/index.js'
export { messageFormat, getMessageFormatParts } from './message-format/index.js'
154 changes: 154 additions & 0 deletions message-format/index.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,154 @@
import type { TranslationFunction } from '../create-i18n/index.js'

type ExtractTagName<
S extends string,
Name extends string = ''
> = S extends `${infer Character}${infer Rest}`
? Character extends '}' | '/'
? [Name, S]
: ExtractTagName<Rest, `${Name}${Character}`>
: [Name, '']

type HasConflict<T> = keyof T extends never
? false
: true extends {
[K in keyof T]: T[K] extends string | number
? T[K] extends (content: string) => string
? true
: false
: false
}[keyof T]
? true
: false

type Prettify<T> = {
[K in keyof T]: T[K] extends (...args: infer A) => infer R
? (...args: A) => R
: T[K]
} & {}

type Trim<S extends string> = S extends ` ${infer T}`
? Trim<T>
: S extends `${infer T} `
? Trim<T>
: S

type InternalExtract<S extends string> =
S extends `{$${infer Var}}${infer Post}`
? Var extends `${string} ${string}`
? InternalExtract<Post>
: { [K in Var]: string | number } & InternalExtract<Post>
: S extends `{#${infer Post}`
? ExtractTagName<Post> extends [
infer TagName extends string,
infer PostTagName
]
? TagName extends `${string} ${string}` | ''
? InternalExtract<Post>
: PostTagName extends `/${string}}${infer PostStandalone}`
? { [K in Trim<TagName>]: () => string } & InternalExtract<Post>
: PostTagName extends `}${infer ContentAndPost}`
? ContentAndPost extends `${infer Content}{/${TagName}}${infer PostTag}`
? {
[K in Trim<TagName>]: (content: string) => string
} & InternalExtract<Content> &
InternalExtract<PostTag>
: InternalExtract<ContentAndPost>
: InternalExtract<PostStandalone>
: InternalExtract<Post>
: S extends `${string}${infer Tail}`
? InternalExtract<Tail>
: object

type ExtractMessageParams<S extends string> =
HasConflict<InternalExtract<S>> extends true
? never
: Prettify<InternalExtract<S>>

interface MessageFormat {
/**
* Add parameters to translation strings using MessageFormat 2 (MF2) standard.
* @link https://messageformat.unicode.org/
*
* @example
* ```ts
* import { messageFormat } from '@nanostores/i18n'
* import { i18n } from '../stores/i18n'
*
* export const messages = i18n('component', {
* click: messageFormat('Click {#link}here{/link}'),
* greeting: messageFormat('Welcome {$user}! {#star/}')
* })
* ```
*
* @example
* ```js
* const t = useStore(messages)
* t.click({ link: (content) => `<a href='some_url'>${content}</a>` })
* t.greeting({ user: 'Jane', star: () => '⭐' })
* ```
*
* @param input MessageFormat template string.
* @returns Transform for translation.
*/
<Input extends string>(
input: Input
): ExtractMessageParams<Input> extends never
? never
: TranslationFunction<
keyof ExtractMessageParams<Input> extends never
? []
: [ExtractMessageParams<Input>],
string
>
}

export const messageFormat: MessageFormat

export type MessageFormatMarkupPart = {
type: 'markup'
kind: 'open' | 'close' | 'standalone'
name: string
}

export type MessageFormatTextPart = {
type: 'text'
value: string
}

export type MessageFormatStringPart = {
type: 'string'
name: string
}

export type MessageFormatPart =
| MessageFormatMarkupPart
| MessageFormatStringPart
| MessageFormatTextPart

/**
* Extract message parts from MessageFormat translation string.
* Useful for implementing custom rendering logic or framework adapters.
*
* @example
* ```jsx
* import { getMessageFormatParts } from '@nanostores/i18n'
* import Star from './components/Star.jsx'
*
* function FancyText({ children }) {
* return getMessageFormatParts(children).map(part => {
* if (part.type === 'markup' && part.name === 'star') return <Star />
* return <span>{part.value}</span>
* })
* }
*
* function App() {
* const translation = 'I am fancy! {#star/}'
* return <FancyText>{translation}</FancyText>
* }
* ```
*
* @param translation MessageFormat translation string.
* @returns Array of MessageFormat parts.
*/
export function getMessageFormatParts(translation: string): MessageFormatPart[]
42 changes: 42 additions & 0 deletions message-format/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
import { transform } from '../transforms/index.js'

const MF_MATCHER =
/(?<var>{\$\w+})|(?<open>{#\w+})|(?<close>{\/\w+})|(?<alone>{#\w+\/})/gm

export function getMessageFormatParts(translation) {
let matches = translation.matchAll(MF_MATCHER).toArray()
if (matches.length === 0) return [{ type: 'text', value: translation }]

let position = 0
let parts = []

for (let match of matches) {
if (match.index > position) {
parts.push({
type: 'text',
value: translation.slice(position, match.index)
})
}

if (match.groups?.var) {
parts.push({ type: 'string', name: match[0].slice(2, -1) })
} else if (match.groups?.open) {
parts.push({ type: 'markup', name: match[0].slice(2, -1), kind: 'open' })
} else if (match.groups?.close) {
parts.push({ type: 'markup', name: match[0].slice(2, -1), kind: 'close' })
} else {
parts.push({
type: 'markup',
name: match[0].slice(2, -2),
kind: 'standalone'
})
}

position = match.index + match[0].length
}

return parts
}

// oxlint-disable-next-line no-unused-vars <temp>
export const messageFormat = transform((locale, translation, params) => {})
38 changes: 38 additions & 0 deletions message-format/index.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
import { deepStrictEqual } from 'node:assert'
import { test } from 'node:test'

import { getMessageFormatParts } from '../index.js'

test('extracts message format parts', () => {
let translation =
'Welcome {$user}! {#bold}Check your {#link}{$item_count} items{/link} {#star/} {/bold}'
let parts = getMessageFormatParts(translation)

deepStrictEqual(parts, [
{ type: 'text', value: 'Welcome ' },
{ type: 'string', name: 'user' },
{ type: 'text', value: '! ' },
{ type: 'markup', kind: 'open', name: 'bold' },
{ type: 'text', value: 'Check your ' },
{ type: 'markup', kind: 'open', name: 'link' },
{ type: 'string', name: 'item_count' },
{ type: 'text', value: ' items' },
{ type: 'markup', kind: 'close', name: 'link' },
{ type: 'text', value: ' ' },
{ type: 'markup', kind: 'standalone', name: 'star' },
{ type: 'text', value: ' ' },
{ type: 'markup', kind: 'close', name: 'bold' }
])
})

test('extracts from plain text', () => {
let translation = 'I do not have any markup or variables.'
let parts = getMessageFormatParts(translation)

deepStrictEqual(parts, [{ type: 'text', value: translation }])
})

test('extracts parts from empty string', () => {
let parts = getMessageFormatParts('')
deepStrictEqual(parts, [{ type: 'text', value: '' }])
})
Loading
Loading