add support for locales

Signed-off-by: Stephen Glass <stephen@stephen.glass>
This commit is contained in:
Stephen Glass
2024-09-22 15:14:38 -04:00
parent b829833344
commit 088101722c
2 changed files with 50 additions and 17 deletions
@@ -13,26 +13,48 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { renderInTestApp } from '@backstage/test-utils';
import React from 'react';
import { CreatedAtColumn } from './CreatedAtColumn';
import { DateTime } from 'luxon';
import { renderInTestApp } from '@backstage/test-utils';
describe('<CreatedAtColumn />', () => {
it('should render the column with the time', async () => {
const props = {
createdAt: DateTime.now().toISO(),
};
const testDate = '2024-09-22T13:30:00Z';
const formattedTime = DateTime.fromISO(props.createdAt).toLocaleString(
DateTime.DATETIME_SHORT_WITH_SECONDS,
const mockNavigatorLanguage = (language: string) => {
jest.spyOn(window.navigator, 'language', 'get').mockReturnValue(language);
};
afterEach(() => {
jest.restoreAllMocks();
});
it('should render the column using mocked locale (de-DE)', async () => {
mockNavigatorLanguage('de-DE');
const { getByText } = await renderInTestApp(
<CreatedAtColumn createdAt={testDate} />,
);
expect(getByText('22.9.2024, 13:30:00')).toBeDefined();
});
const { getByText } = await renderInTestApp(<CreatedAtColumn {...props} />);
it('should render the column with the default locale (en-US)', async () => {
mockNavigatorLanguage('');
const { getByText } = await renderInTestApp(
<CreatedAtColumn createdAt={testDate} />,
);
expect(getByText('9/22/2024, 1:30:00 PM')).toBeDefined();
});
const text = getByText(formattedTime);
expect(text).toBeDefined();
it('should render the column with a specified locale (fr-FR)', async () => {
const { getByText } = await renderInTestApp(
<CreatedAtColumn createdAt={testDate} locale="fr-FR" />,
);
expect(getByText('22/09/2024 13:30:00')).toBeDefined();
});
it('should render the column with a specified locale (en-DE)', async () => {
const { getByText } = await renderInTestApp(
<CreatedAtColumn createdAt={testDate} locale="en-DE" />,
);
expect(getByText('22/09/2024, 13:30:00')).toBeDefined();
});
});
@@ -17,11 +17,22 @@ import { DateTime } from 'luxon';
import React from 'react';
import Typography from '@material-ui/core/Typography';
export const CreatedAtColumn = ({ createdAt }: { createdAt: string }) => {
interface CreatedAtColumnProps {
createdAt: string;
locale?: string;
}
export const CreatedAtColumn: React.FC<CreatedAtColumnProps> = ({
createdAt,
locale,
}) => {
const createdAtTime = DateTime.fromISO(createdAt);
const formatted = createdAtTime.toLocaleString(
DateTime.DATETIME_SHORT_WITH_SECONDS,
);
const userLocale = locale || window.navigator.language || 'en-US';
const formatted = createdAtTime.setLocale(userLocale).toLocaleString({
...DateTime.DATETIME_SHORT_WITH_SECONDS,
});
return <Typography paragraph>{formatted}</Typography>;
};