mirror of
https://github.com/mastodon/mastodon.git
synced 2026-03-21 18:05:23 -05:00
66 lines
1.5 KiB
TypeScript
66 lines
1.5 KiB
TypeScript
import { useMemo } from 'react';
|
|
|
|
import { FormattedMessage } from 'react-intl';
|
|
|
|
import classNames from 'classnames';
|
|
|
|
import { polymorphicForwardRef } from '@/types/polymorphic';
|
|
|
|
import classes from './styles.module.scss';
|
|
|
|
interface CharacterCounterProps {
|
|
currentString: string;
|
|
maxLength: number;
|
|
recommended?: boolean;
|
|
}
|
|
|
|
const segmenter = new Intl.Segmenter();
|
|
|
|
export const CharacterCounter = polymorphicForwardRef<
|
|
'span',
|
|
CharacterCounterProps
|
|
>(
|
|
(
|
|
{
|
|
currentString,
|
|
maxLength,
|
|
as: Component = 'span',
|
|
recommended = false,
|
|
className,
|
|
...props
|
|
},
|
|
ref,
|
|
) => {
|
|
const currentLength = useMemo(
|
|
() => [...segmenter.segment(currentString)].length,
|
|
[currentString],
|
|
);
|
|
return (
|
|
<Component
|
|
{...props}
|
|
ref={ref}
|
|
className={classNames(
|
|
className,
|
|
classes.counter,
|
|
currentLength > maxLength && !recommended && classes.counterError,
|
|
)}
|
|
>
|
|
{recommended ? (
|
|
<FormattedMessage
|
|
id='character_counter.recommended'
|
|
defaultMessage='{currentLength}/{maxLength} recommended characters'
|
|
values={{ currentLength, maxLength }}
|
|
/>
|
|
) : (
|
|
<FormattedMessage
|
|
id='character_counter.required'
|
|
defaultMessage='{currentLength}/{maxLength} characters'
|
|
values={{ currentLength, maxLength }}
|
|
/>
|
|
)}
|
|
</Component>
|
|
);
|
|
},
|
|
);
|
|
CharacterCounter.displayName = 'CharCounter';
|