Skip to content

Commit

Permalink
feat: move default message property
Browse files Browse the repository at this point in the history
  • Loading branch information
pret-a-porter committed Nov 18, 2024
1 parent a19c788 commit f689960
Show file tree
Hide file tree
Showing 11 changed files with 42 additions and 86 deletions.
2 changes: 1 addition & 1 deletion packages/core/src/__tests__/on_error.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ describe('Handle missing id', () => {
const translator = new Translator();
translator.onError = onError;

translator.translate('test', {
translator.translate('test', undefined, {
onError,
});

Expand Down
16 changes: 10 additions & 6 deletions packages/core/src/__tests__/select_other.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,15 +23,19 @@ const locales: Locale[] = [
test('should use select other case as fallback', () => {
const { translate } = new Translator('en', locales);

expect(translate('hello', { gender: 'male' })).toBe('hello man');
expect(translate('hello', { gender: 'female' })).toBe('hello woman');
expect(translate('hello', { gender: 'other' })).toBe('hello');
expect(translate('hello', { gender: 'prefer-not-to' })).toBe('hello');
expect(translate('hello', undefined, { gender: 'male' })).toBe('hello man');
expect(translate('hello', undefined, { gender: 'female' })).toBe(
'hello woman',
);
expect(translate('hello', undefined, { gender: 'other' })).toBe('hello');
expect(translate('hello', undefined, { gender: 'prefer-not-to' })).toBe(
'hello',
);
});

test('should use select other case as fallback for Arabic language', () => {
const { translate } = new Translator('ar', locales);

expect(translate('minute', { count: 1 })).toBe('min 1');
expect(translate('minute', { count: 2 })).toBe('min 2');
expect(translate('minute', undefined, { count: 1 })).toBe('min 1');
expect(translate('minute', undefined, { count: 2 })).toBe('min 2');
});
4 changes: 1 addition & 3 deletions packages/core/src/model/FormatMessageOptions.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1 @@
export interface FormatMessageOptions extends Record<string, any> {
defaultMessage?: string;
}
export type FormatMessageOptions = Record<string, any>;
3 changes: 2 additions & 1 deletion packages/core/src/parser/parser.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
import { FormatMessageOptions } from '../model';
import { TokenType, Token, TokenStream } from './token_stream';

export function getTranslationParts(
language: string,
message: string,
params: Record<string, any>,
params: FormatMessageOptions = {},
): any[] {
const tokenStream = new TokenStream(message);
let result: any[] = [];
Expand Down
8 changes: 6 additions & 2 deletions packages/core/src/translator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,8 +27,12 @@ export class Translator {
return new Intl.NumberFormat(this.language, options).format(value);
};

translate = (id: string, options: FormatMessageOptions = {}): string => {
const message = this.getMessageById(id, options.defaultMessage);
translate = (
id: string,
defaultMessage?: string,
options?: FormatMessageOptions,
): string => {
const message = this.getMessageById(id, defaultMessage);

if (typeof message === 'string') {
try {
Expand Down
7 changes: 4 additions & 3 deletions packages/preact/src/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -102,21 +102,22 @@ export const Numeric: FunctionalComponent<NumericProps> = ({
};

export interface TextProps extends FormatMessageOptions {
defaultMessage?: string;
html?: boolean;
id: string;

tagName?: string;
html?: boolean;
}

export const Text: FunctionalComponent<TextProps> = ({
children,
defaultMessage,
html,
id,
tagName = 'span',
...values
}) => {
const context = useContext(TranslationsContext);
const result = context.translator.translate(id, values);
const result = context.translator.translate(id, defaultMessage, values);

if (html) {
return h(tagName, {
Expand Down
4 changes: 3 additions & 1 deletion packages/react-native/src/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -85,15 +85,17 @@ export const Numeric: FC<NumericProps> = ({
};

export interface TranslationProps extends FormatMessageOptions {
defaultMessage?: string;
id: string;
}

export const Translation: FC<TranslationProps> = ({
children,
defaultMessage,
id,
...values
}) => {
return useTranslator().translate(id, values);
return useTranslator().translate(id, defaultMessage, values);
};

export interface TranslationsContextProps {
Expand Down
10 changes: 0 additions & 10 deletions packages/react/src/__tests__/html.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -47,14 +47,4 @@ describe('EOLocaleHtml', () => {

expect(strong?.textContent).toEqual('мир');
});

it('Should render formatted message for en', () => {
const { getByTestId } = render(
<TestWrapper>
<Text html id='hello' name={<Numeric value={1000} />} />
</TestWrapper>,
);

expect(getByTestId('translation')?.textContent).toEqual('Hello 1,000!');
});
});
2 changes: 1 addition & 1 deletion packages/react/src/__tests__/on_error.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,6 @@ describe('On error handler', () => {
</TestWrapper>,
);

expect(onError).toBeCalledTimes(1);
expect(onError).toHaveBeenCalledTimes(1);
});
});
12 changes: 1 addition & 11 deletions packages/react/src/__tests__/text.test.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { render } from '@testing-library/react';
import * as React from 'react';
import { Numeric, Text } from '../components';
import { Text } from '../components';
import { TestWrapper } from './test_wrapper';

describe('Text', () => {
Expand All @@ -24,16 +24,6 @@ describe('Text', () => {
expect(getByTestId('translation')).toHaveTextContent('test');
});

it('Should render formatted message for en', () => {
const { getByTestId } = render(
<TestWrapper>
<Text id='hello' name={<Numeric value={1000} />} />
</TestWrapper>,
);

expect(getByTestId('translation')).toHaveTextContent('Hello 1,000!');
});

it('Should render formatted message for ru', () => {
const { getByTestId } = render(
<TestWrapper language='ru'>
Expand Down
60 changes: 13 additions & 47 deletions packages/react/src/components/Text.tsx
Original file line number Diff line number Diff line change
@@ -1,16 +1,12 @@
import {
FormatMessageOptions,
getTranslationParts,
TranslationError,
} from '@eo-locale/core';
import React, { FC, Fragment, PropsWithChildren } from 'react';
import { renderToStaticMarkup } from 'react-dom/server';
import { FormatMessageOptions } from '@eo-locale/core';
import React, { createElement, FC, PropsWithChildren } from 'react';
import { useTranslator } from '../hooks';

interface Props extends FormatMessageOptions {
defaultMessage?: string;
html?: boolean;
id: string;
tagName?: keyof React.ReactHTML;
html?: boolean;
}

export const Text: FC<PropsWithChildren<Props>> = ({
Expand All @@ -22,45 +18,15 @@ export const Text: FC<PropsWithChildren<Props>> = ({
...values
}) => {
const translator = useTranslator();
const message = translator.getMessageById(id, defaultMessage);

if (typeof message === 'string') {
try {
const parts: React.ReactNode[] = getTranslationParts(
translator.language,
message,
values,
).map((part, index) => {
if (React.isValidElement(part)) {
if (html) {
return renderToStaticMarkup(part);
}

return React.cloneElement(part, {
key: index,
});
}

if (html) {
return part;
}

return <Fragment key={index}>{part}</Fragment>;
});

if (html) {
return React.createElement(tagName, {
dangerouslySetInnerHTML: {
__html: parts.join(''),
},
});
}

return <Fragment>{parts}</Fragment>;
} catch (error) {
translator.onError(new TranslationError(id, translator.language));
}
const result = translator.translate(id, defaultMessage, values);

if (html) {
return createElement(tagName, {
dangerouslySetInnerHTML: {
__html: result,
},
});
}

return <Fragment>{String(message)}</Fragment>;
return result;
};

0 comments on commit f689960

Please sign in to comment.