Skip to content

Commit

Permalink
feat: add react components interpolation
Browse files Browse the repository at this point in the history
  • Loading branch information
hugocxl committed Oct 24, 2023
1 parent 4c1c523 commit 005860d
Show file tree
Hide file tree
Showing 3 changed files with 20 additions and 4 deletions.
5 changes: 3 additions & 2 deletions packages/react/src/core/client/setup.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -15,9 +15,10 @@ import {
} from '@legendapp/state/persist'

// Types
import type { Dictionaries, Locale } from '@koi18n/types'
import type { ReactNode } from 'react'
import type { CreateSetupOptions, GetTsProps } from '../types'
import type { SetupReactOptions, TsReactRenderProps } from '../types'
import type { Dictionaries, Locale } from '@koi18n/types'

export type SetupClient = ReturnType<typeof createSetupClient>
export type SetupClientOptions = SetupReactOptions & {
Expand Down Expand Up @@ -57,7 +58,7 @@ export function createSetupClient({ getLocale }: CreateSetupOptions) {
}

return useCallback(
createTs<string, TsReactRenderProps>(props =>
createTs<string | ReactNode, TsReactRenderProps>(props =>
tsRender({
...props,
locale,
Expand Down
3 changes: 2 additions & 1 deletion packages/react/src/core/server/setup.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import { createTs } from '@koi18n/ts'
import { tsRender } from '../ts-render'

// Types
import type { ReactNode } from 'react'
import type {
SetupReactOptions,
TsReactRenderProps,
Expand All @@ -26,7 +27,7 @@ export function createSetupServer({ getLocale }: CreateSetupOptions) {
const getTs = async ({ chunkId }: GetTsProps = {}) => {
const locale = getLocale()
const dictionary = await loader(locale, chunkId ?? locale)
return createTs<string, TsReactRenderProps>(props =>
return createTs<string | ReactNode, TsReactRenderProps>(props =>
tsRender({
...props,
locale,
Expand Down
16 changes: 15 additions & 1 deletion packages/react/src/core/ts-render.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { interpolate } from '@koi18n/formatter'
// Types
import type { TsReactRenderProps } from './types'
import type { Locale, Dictionary } from '@koi18n/types'
import { interpolateComponents } from '.'

export type TsOutputProps = TsReactRenderProps & {
locale: Locale
Expand All @@ -16,7 +17,8 @@ export function tsRender({
rawMessage,
variables,
dictionary,
format
format,
components
}: TsOutputProps) {
const message = dictionary?.[id] ?? rawMessage
const interpolatedMessage = interpolate(
Expand All @@ -28,5 +30,17 @@ export function tsRender({
{ format }
)

if (!isEmpty(components)) {
return interpolateComponents({
message: interpolatedMessage,
locale,
components
})
}

return interpolatedMessage
}

const isEmpty = (obj: TsOutputProps['components']) => {
return Object.keys(obj).length === 0
}

0 comments on commit 005860d

Please sign in to comment.