import type { IntlShape } from 'react-intl' export type CounterShow = 'always' | 'auto' export type CounterProps = { /** * If a max-length is in use, this prop controls showing a visible and accessible counter * * @deprecated Use limit property instead */ showCounter?: boolean /** * Max length of field * * @deprecated Use limit property instead */ maxLength?: number /** * Configure length limit of this field, will by default show counter when * user is close to limit. Can be used to configure additional behaviors * or handle when the field is truncated. * * The value can either be a number or an object that can set the following: * * * **value**: number * * **show?**: 'always' or 'auto' (default) * * **truncate?**: true (default) or false * * **onPasteTruncated?**: a callback that fires when pasting text into * a field will cause the pasted content to be truncated * * ```ts * { * value: number * show?: 'always' | 'auto' * truncate?: boolean * onPasteTruncated?: () => void * } * ``` */ limit?: number | LimitConfig } export type LimitConfig = { value: number show?: CounterShow truncate?: boolean onPasteTruncated?: () => void } const MAX_CHARACTERS_SHOW = 500 const MIN_CHARACTERS_SHOW = 10 const MAX_CHARACTERS_WARN = 200 const MIN_CHARACTERS_WARN = 2 export const getLimit = ( length: number, { maxLength, showCounter, limit }: CounterProps, intl?: IntlShape ) => { const baseDefault = maxLength const showDefault: CounterShow | 'never' = showCounter ? 'always' : maxLength == null ? 'auto' : 'never' const { value = baseDefault, show = showDefault, truncate = true, onPasteTruncated = undefined, } = typeof limit === 'number' ? { value: limit, show: 'auto' } : limit ?? {} if (!value || show === 'never') { return { limit: value ?? 0, showCounter: false, truncate, onPasteTruncated, count: '', overCount: false, nearCount: false, } } const withinCounterRange = Math.min( MAX_CHARACTERS_SHOW, Math.max(0.25 * value, MIN_CHARACTERS_SHOW) ) const withinWarningRange = Math.min( MAX_CHARACTERS_WARN, Math.max(0.1 * value, MIN_CHARACTERS_WARN) ) const shouldShowCounter = show === 'always' || (!!length && length > value - withinCounterRange) const overCount = shouldShowCounter && length > value const nearCount = shouldShowCounter && length > value - withinWarningRange const count = shouldShowCounter ? intl ? `${intl.formatNumber(length)}/${intl.formatNumber(value)}` : `${length}/${value}` : '' return { limit: value ?? 0, showCounter: shouldShowCounter, truncate, onPasteTruncated, count, overCount, nearCount, } }