@vimeo/iris
Version:
Vimeo Design System
51 lines (48 loc) • 1.62 kB
JavaScript
import { _ as __read } from '../../../tslib.es6-7f0e734f.js';
import { useReducer, useCallback } from 'react';
import { reducer } from './useCharacterCount.state.esm.js';
/**
* Based on withCharacterCount, this provides handlers for a character count message to create a controlled component.
* Helpful to use in conjuction with custom inputs that need more control of input messages
*/
function useCharacterCount(_a) {
var _b = _a.maxCharacters, maxCharacters = _b === void 0 ? 10 : _b, _c = _a.warningThreshold, warningThreshold = _c === void 0 ? 5 : _c;
var _d = __read(useReducer(reducer, {
remainingCharacters: maxCharacters,
}), 2), state = _d[0], dispatch = _d[1];
function handleError() {
dispatch({
type: 'SET_ERROR',
});
}
function handleWarn() {
dispatch({
type: 'SET_WARNING',
});
}
var clean = useCallback(function () {
dispatch({
type: 'RESET_STATUS',
});
}, []);
var handleChange = useCallback(function (value) {
var remaining = maxCharacters - value.length;
if (remaining <= warningThreshold && remaining > 0)
handleWarn();
else if (remaining <= 0)
handleError();
else
clean();
dispatch({
type: 'SET_REMAINING_CHARACTERS',
payload: remaining,
});
}, [clean, maxCharacters, warningThreshold]);
return {
state: state,
dispatch: dispatch,
handleChange: handleChange,
clean: clean,
};
}
export { useCharacterCount };