Skip to content

Commit

Permalink
Merge pull request #1011 from aralroca/canary
Browse files Browse the repository at this point in the history
2.0.3
  • Loading branch information
aralroca authored Mar 23, 2023
2 parents 455eb17 + 042da00 commit bd22635
Show file tree
Hide file tree
Showing 5 changed files with 86 additions and 21 deletions.
52 changes: 52 additions & 0 deletions __tests__/useTranslation.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -1170,6 +1170,58 @@ describe('useTranslation', () => {

const expected = 'This is a default translation with a count: 3'

const { container } = render(
<I18nProvider lang="en" namespaces={{}}>
<Inner />
</I18nProvider>
)
expect(container.textContent).toBe(expected)
})
test('should allow default object translation with interpolation', () => {
const Inner = () => {
const { t } = useTranslation()
const text = t(
'ns:no-translation',
{ count: 3 },
{
default: {
example: 'This is a default translation with a count: {{count}}'
},
returnObjects: true,
fallback: 'ns:no-translation2',
}
)
return <>{text.example}</>
}

const expected = 'This is a default translation with a count: 3'

const { container } = render(
<I18nProvider lang="en" namespaces={{}}>
<Inner />
</I18nProvider>
)
expect(container.textContent).toBe(expected)
})
test('should allow default array translation with interpolation', () => {
const Inner = () => {
const { t } = useTranslation()
const text = t(
'ns:no-translation',
{ count: 3 },
{
default: [
'This is a default translation with a count: {{count}}'
],
returnObjects: true,
fallback: 'ns:no-translation2',
}
)
return <>{text[0]}</>
}

const expected = 'This is a default translation with a count: 3'

const { container } = render(
<I18nProvider lang="en" namespaces={{}}>
<Inner />
Expand Down
2 changes: 1 addition & 1 deletion src/Trans.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ export default function Trans({
* Memoize the transformation
*/
const result = useMemo(() => {
const text = t(i18nKey, values, { fallback, default: defaultTrans })
const text = t<string>(i18nKey, values, { fallback, default: defaultTrans })

if (!components || components.length === 0) return text

Expand Down
13 changes: 11 additions & 2 deletions src/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,22 @@ export interface TranslationQuery {
[name: string]: any
}

export type Translate = <T = string>(

export interface NestedStringObject {
[key:string]: string | NestedStringObject | NestedStringArray
}
type ValueOrArray<T> = T | ValueOrArray<T>[];
type NestedStringArray = ValueOrArray<string | NestedStringObject>;

export type TranslateValue = string | NestedStringObject | NestedStringArray

export type Translate = <T extends TranslateValue = string>(
i18nKey: string | TemplateStringsArray,
query?: TranslationQuery | null,
options?: {
returnObjects?: boolean
fallback?: string | string[]
default?: string
default?: T | string
ns?: string
}
) => T
Expand Down
38 changes: 21 additions & 17 deletions src/transCore.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import {
I18nDictionary,
LoaderConfig,
LoggerProps,
TranslateValue,
TranslationQuery,
} from '.'
import { Translate } from './index'
Expand Down Expand Up @@ -37,6 +38,21 @@ export default function transCore({
allowEmptyStrings = true,
} = config

const interpolateUnknown = (value: TranslateValue, query?: TranslationQuery | null): TranslateValue => {
if (Array.isArray(value)) {
return value.map(val => interpolateUnknown(val, query));
}
if (value instanceof Object) {
return objectInterpolation({
obj: value as Record<string, unknown>,
query,
config,
lang,
})
}
return interpolation({ text: value as string, query, config, lang })
}

const t: Translate = (key = '', query, options) => {
const k = Array.isArray(key) ? key[0] : key
const { nsSeparator = ':', loggerEnvironment = 'browser' } = config
Expand Down Expand Up @@ -81,27 +97,18 @@ export default function transCore({
}
}

if (empty && options?.default && fallbacks?.length == 0) {
return interpolation({ text: options?.default, query, config, lang })
if (empty && options?.default && !fallbacks?.length) {
return interpolateUnknown(options.default, query)
}

// no need to try interpolation
if (empty) {
return k
}

if (value instanceof Object) {
return objectInterpolation({
obj: value as Record<string, unknown>,
query,
config,
lang,
})
}

// this can return an empty string if either value was already empty
// or it contained only an interpolation (e.g. "{{name}}") and the query param was empty
return interpolation({ text: value as string, query, config, lang })
return interpolateUnknown(value, query)
}

return t
Expand All @@ -117,7 +124,7 @@ function getDicValue(
options: { returnObjects?: boolean; fallback?: string | string[] } = {
returnObjects: false,
}
): string | undefined | object {
): TranslateValue | undefined {
const { keySeparator = '.' } = config || {}
const keyParts = keySeparator ? key.split(keySeparator) : [key]

Expand All @@ -141,7 +148,7 @@ function getDicValue(
typeof value === 'string' ||
((value as unknown) instanceof Object && options.returnObjects)
) {
return value
return value as TranslateValue
}

return undefined
Expand Down Expand Up @@ -203,8 +210,6 @@ function interpolation({
const regexEnd =
suffix === '' ? '' : `(?:[\\s,]+([\\w-]*))?\\s*${escapeRegex(suffix)}`
return Object.keys(query).reduce((all, varKey) => {
if (typeof all !== 'string') return all

const regex = new RegExp(
`${escapeRegex(prefix)}\\s*${varKey}${regexEnd}`,
'gm'
Expand Down Expand Up @@ -232,7 +237,6 @@ function objectInterpolation({
lang?: string
}): any {
if (!query || Object.keys(query).length === 0) return obj

Object.keys(obj).forEach((key) => {
if (obj[key] instanceof Object)
objectInterpolation({
Expand Down
2 changes: 1 addition & 1 deletion yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -5537,4 +5537,4 @@ yargs@^16.2.0:
require-directory "^2.1.1"
string-width "^4.2.0"
y18n "^5.0.5"
yargs-parser "^20.2.2"
yargs-parser "^20.2.2"

0 comments on commit bd22635

Please sign in to comment.