Skip to content

Commit

Permalink
feat: allow to configure date and time format over i18n
Browse files Browse the repository at this point in the history
  • Loading branch information
MartinCupela committed Jun 11, 2024
1 parent ded8f05 commit 9511550
Show file tree
Hide file tree
Showing 26 changed files with 659 additions and 45 deletions.
182 changes: 182 additions & 0 deletions docusaurus/docs/React/guides/date-time-formatting.mdx
Original file line number Diff line number Diff line change
@@ -0,0 +1,182 @@
---
id: date-time-formatting
title: Date and time formatting
keywords: [date, time, datetime, timestamp, format, formatting]
---

In this guide we will learn how date a time formatting can be customized within SDK's components.

## SDK components displaying date & time

The following components provided by the SDK display datetime:

- `DateSeparator`- component separating groups of messages in message lists
- `EventComponent` - component that renders system messages (`message.type === 'system'`)
- `Timestamp` - component to display non-system message timestamp

## Format customization

The datetime format customization can be done on multiple levels:

1. Override the default component prop values
2. Supply custom formatting function
3. Format date via i18n

### Override the component props defaults

All the mentioned components accept timestamp formatter props:

```ts
export type TimestampFormatterOptions = {
/* If true, call the `Day.js` calendar function to get the date string to display (e.g. "Yesterday at 3:58 PM"). */
calendar?: boolean | null;
/* Object specifying date display formats for dates formatted with calendar extension. Active only if calendar prop enabled. */
calendarFormats?: Record<string, string> | null;
/* Overrides the default timestamp format if calendar is disabled. */
format?: string | null;
};
```

If calendar formatting is enabled, the dates are formatted with time-relative words ("yesterday at ...", "last ..."). The calendar strings can be further customized with `calendarFormats` object. It also means that the `format` prop would be ignored. On the other hand, if calendar is disabled, then `calendarFormats` is ignored and `format` string is applied.

All the components can be overridden through `Channel` component context

```tsx
import {
Channel,
DateSeparatorProps,
DateSeparator,
EventComponentProps,
EventComponent,
MessageTimestampProps,
MessageTimestamp,
} from 'stream-chat-react';

const CustomDateSeparator = (props: DateSeparatorProps) => (
<DateSeparator {...props} calendar={false} format={'YYYY'} /> // calendar is enabled by default
);

const SystemMessage = (props: EventComponentProps) => (
<EventComponent {...props} calendar={false} format={'YYYY'} /> // calendar is enabled by default
);

const CustomMessageTimestamp = (props: MessageTimestampProps) => (
<MessageTimestamp {...props} calendar={false} format={'YYYY-MM-DDTHH:mm:ss'} /> // calendar is enabled by default
);

const App = () => (
<Channel
DateSeparator={CustomDateSeparator}
MessageSystem={SystemMessage}
MessageTimestamp={CustomMessageTimestamp}
></Channel>
);
```

### Custom formatting function

Custom formatting function can be passed to `MessageList` or `VirtualizedMessageList` via prop `formatDate` (`(date: Date) => string;`). The `Message` component passes down the function to be consumed by the children via `MessageComponentContext`:

```jsx
import { useMessageContext } from 'stream-chat-react';
const CustomComponent = () => {
const { formatDate } = useMessageContext();
};
```

By default, the function is consumed by the `MessageTimestamp` component. This means the formatting via `formatDate` is reduced only to timestamp shown by a message in the message list. Components `DateSeparator`, `EventComponent` would ignore the custom formatting.

### Date & time formatting with i18n service

Until now, the datetime values could be customized within `Channel` at best. Formatting via i18n service allows for SDK wide configuration. The configuration is stored with other translations in JSON files. Formatting with i18n service has the following advantages:

- it is centralized
- it takes into consideration the locale out of the box
- allows for high granularity - formatting per string, not component (opposed to props approach)
- allows for high re-usability - apply the same configuration in multiple places via the same translation key
- allows for custom formatting logic

#### Change the default configuration

The default datetime formatting configuration is stored in the JSON translation files. The default translation keys are namespaced with prefix `timestamp/` followed by the component name. For example, the message date formatting can be targeted via `timestamp/MessageTimestamp`, because the underlying component is called `MessageTimestamp`.

##### Overriding the prop defaults

The default date and time rendering components in the SDK were created with default prop values that override the configuration parameters provided over JSON translations. Therefore, if we wanted to configure the formatting from JSON translation files, we need to nullify the prop defaults. An example follows:

```jsx
import {
DateSeparatorProps,
DateSeparator,
EventComponentProps,
EventComponent,
MessageTimestampProps,
MessageTimestamp,
} from 'stream-chat-react';

const CustomDateSeparator = (props: DateSeparatorProps) => (
<DateSeparator {...props} calendar={null} calendarFormats={null} format={null} />
);

const SystemMessage = (props: EventComponentProps) => (
<EventComponent {...props} calendar={null} calendarFormats={null} format={null} />
);

const CustomMessageTimestamp = (props: MessageTimestampProps) => (
<MessageTimestamp {...props} calendar={null} calendarFormats={null} format={null} />
);
```

Besides overriding the formatting parameters above, we can customize the translation key via `timestampTranslationKey` prop all the above components (`DateSeparator`, `EventComponent`, `Timestamp`).

```tsx
import { MessageTimestampProps, MessageTimestamp } from 'stream-chat-react';

const CustomMessageTimestamp = (props: MessageTimestampProps) => (
<MessageTimestamp {...props} timestampTranslationKey='customTimestampTranslationKey' />
);
```

##### Understanding the formatting syntax

Once the default prop values are nullified, we override the default formatting rules in the JSON translation value. We can take a look at an example:

```
"timestamp/SystemMessage": "{{ timestamp, timestampFormatter(calendar: true; calendarFormats: {\"sameElse\": \"dddd L\"}) }}",
```

Let's dissect the example:

- The curly brackets (`{{`, `}}`) indicate the place where a value will be interpolated (inserted) into the string.
- variable `timestamp` is the name of variable which value will be inserted into the string
- `timestampFormatter` is the name of the formatting function that is used to convert the `timestamp` value into desired format
- the `timestampFormatter` is can be passed the same parameters as the React components (`calendar`, `calendarFormats`, `format`) as if the function was called with these values. The values can be simple scalar values as well as objects (note `calendarFormats` should be an object)

:::note
The described rules follow the formatting rules required by the i18n library used under the hood - `i18next`. You can learn more about the rules in [the formatting section of the `i18next` documentation](https://www.i18next.com/translation-function/formatting#basic-usage).
:::

#### Custom datetime formatter functions

Besides overriding the configuration parameters, we can override the default `timestampFormatter` function by providing custom `Streami18n` instance:

```tsx
import { Chat, Streami18n, useCreateChatClient } from 'stream-chat-react';

const i18n = new Streami18n({
formatters: {
timestampFormatter: () => (val: string | Date) => {
return new Date(val).getTime() + '';
},
},
});

export const ChatApp = ({ apiKey, userId, userToken }) => {
const chatClient = useCreateChatClient({
apiKey,
tokenOrProvider: userToken,
userData: { id: userId },
});
return <Chat client={chatClient} i18nInstance={i18n}></Chat>;
};
```
21 changes: 17 additions & 4 deletions src/components/DateSeparator/DateSeparator.tsx
Original file line number Diff line number Diff line change
@@ -1,29 +1,42 @@
import React from 'react';

import { useTranslationContext } from '../../context/TranslationContext';
import { getDateString } from '../../i18n/utils';
import { getDateString, TimestampFormatterOptions } from '../../i18n/utils';

export type DateSeparatorProps = {
export type DateSeparatorProps = TimestampFormatterOptions & {
/** The date to format */
date: Date;
/** Override the default formatting of the date. This is a function that has access to the original date object. */
formatDate?: (date: Date) => string;
/** Set the position of the date in the separator, options are 'left', 'center', 'right', @default right */
position?: 'left' | 'center' | 'right';
/* Lookup key in the language corresponding translations sheet to perform date formatting */
timestampTranslationKey?: string;
/** If following messages are not new */
unread?: boolean;
};

const UnMemoizedDateSeparator = (props: DateSeparatorProps) => {
const { date: messageCreatedAt, formatDate, position = 'right', unread } = props;
const {
calendar = true,
date: messageCreatedAt,
formatDate,
position = 'right',
timestampTranslationKey = 'timestamp/DateSeparator',
unread,
...restTimestampFormatterOptions
} = props;

const { t, tDateTimeParser } = useTranslationContext('DateSeparator');

const formattedDate = getDateString({
calendar: true,
calendar,
...restTimestampFormatterOptions,
formatDate,
messageCreatedAt,
t,
tDateTimeParser,
timestampTranslationKey,
});

return (
Expand Down
6 changes: 3 additions & 3 deletions src/components/DateSeparator/__tests__/DateSeparator.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import React from 'react';
import renderer from 'react-test-renderer';
import Dayjs from 'dayjs';
import calendar from 'dayjs/plugin/calendar';
import { cleanup, render } from '@testing-library/react';
import { cleanup, render, screen } from '@testing-library/react';
import '@testing-library/jest-dom';

import { DateSeparator } from '../DateSeparator';
Expand Down Expand Up @@ -35,9 +35,9 @@ describe('DateSeparator', () => {

it('should render New text if unread prop is true', () => {
const { Component, t } = withContext({ date: now, unread: true });
const { queryByText } = render(Component);
render(Component);

expect(queryByText('New - 03/30/2020')).toBeInTheDocument();
expect(screen.getByText('New - 03/30/2020')).toBeInTheDocument();
expect(t).toHaveBeenCalledWith('New');
});

Expand Down
29 changes: 23 additions & 6 deletions src/components/EventComponent/EventComponent.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,15 +7,17 @@ import { useTranslationContext } from '../../context/TranslationContext';
import type { StreamMessage } from '../../context/ChannelStateContext';

import type { DefaultStreamChatGenerics } from '../../types/types';
import { getDateString } from '../../i18n/utils';
import { getDateString, TimestampFormatterOptions } from '../../i18n/utils';

export type EventComponentProps<
StreamChatGenerics extends DefaultStreamChatGenerics = DefaultStreamChatGenerics
> = {
> = TimestampFormatterOptions & {
/** Message object */
message: StreamMessage<StreamChatGenerics>;
/** Custom UI component to display user avatar, defaults to and accepts same props as: [Avatar](https://github.com/GetStream/stream-chat-react/blob/master/src/components/Avatar/Avatar.tsx) */
Avatar?: React.ComponentType<AvatarProps>;
/* Lookup key in the language corresponding translations sheet to perform date formatting */
timestampTranslationKey?: string;
};

/**
Expand All @@ -26,9 +28,16 @@ const UnMemoizedEventComponent = <
>(
props: EventComponentProps<StreamChatGenerics>,
) => {
const { Avatar = DefaultAvatar, message } = props;
const {
calendar = true,
calendarFormats = { sameElse: 'dddd L' },
format,
Avatar = DefaultAvatar,
message,
timestampTranslationKey = 'timestamp/SystemMessage',
} = props;

const { tDateTimeParser } = useTranslationContext('EventComponent');
const { t, tDateTimeParser } = useTranslationContext('EventComponent');
const { created_at = '', event, text, type } = message;
const getDateOptions = { messageCreatedAt: created_at.toString(), tDateTimeParser };

Expand All @@ -41,8 +50,16 @@ const UnMemoizedEventComponent = <
<div className='str-chat__message--system__line' />
</div>
<div className='str-chat__message--system__date'>
<strong>{getDateString({ ...getDateOptions, format: 'dddd' })} </strong>
at {getDateString({ ...getDateOptions, format: 'hh:mm A' })}
<strong>
{getDateString({
...getDateOptions,
calendar,
calendarFormats,
format,
t,
timestampTranslationKey,
})}
</strong>
</div>
</div>
);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -49,11 +49,8 @@ describe('EventComponent', () => {
className="str-chat__message--system__date"
>
<strong>
Friday
Friday 03/13/2020
</strong>
at
10:18 AM
</div>
</div>
`);
Expand Down
16 changes: 7 additions & 9 deletions src/components/Message/MessageTimestamp.tsx
Original file line number Diff line number Diff line change
@@ -1,25 +1,23 @@
import React from 'react';

import type { StreamMessage } from '../../context/ChannelStateContext';
import type { DefaultStreamChatGenerics } from '../../types/types';

import { useMessageContext } from '../../context/MessageContext';
import { Timestamp as DefaultTimestamp } from './Timestamp';
import { useComponentContext } from '../../context';

import type { StreamMessage } from '../../context/ChannelStateContext';
import type { DefaultStreamChatGenerics } from '../../types/types';
import type { TimestampFormatterOptions } from '../../i18n/utils';

export const defaultTimestampFormat = 'h:mmA';

export type MessageTimestampProps<
StreamChatGenerics extends DefaultStreamChatGenerics = DefaultStreamChatGenerics
> = {
/* If true, call the `Day.js` calendar function to get the date string to display. */
calendar?: boolean;
> = TimestampFormatterOptions & {
/* Adds a CSS class name to the component's outer `time` container. */
customClass?: string;
/* Overrides the default timestamp format */
format?: string;
/* The `StreamChat` message object, which provides necessary data to the underlying UI components (overrides the value from `MessageContext`) */
message?: StreamMessage<StreamChatGenerics>;
/* Lookup key in the language corresponding translations sheet to perform date formatting */
timestampTranslationKey?: string;
};

const UnMemoizedMessageTimestamp = <
Expand Down
Loading

0 comments on commit 9511550

Please sign in to comment.