@zendeskgarden/container-field
Version:
Containers relating to field in the Garden Design System
116 lines (111 loc) • 3.06 kB
JavaScript
/**
* Copyright Zendesk, Inc.
*
* Use of this source code is governed under the Apache License, Version 2.0
* found at http://www.apache.org/licenses/LICENSE-2.0.
*/
import React, { useCallback, useMemo } from 'react';
import { useId } from '@zendeskgarden/container-utilities';
import PropTypes from 'prop-types';
const useField = _ref => {
let {
idPrefix,
hasHint,
hasMessage
} = _ref;
const prefix = useId(idPrefix);
const inputId = `${prefix}--input`;
const labelId = `${prefix}--label`;
const hintId = `${prefix}--hint`;
const messageId = `${prefix}--message`;
const getLabelProps = useCallback(function (_temp) {
let {
id = labelId,
htmlFor = inputId,
...other
} = _temp === void 0 ? {} : _temp;
return {
'data-garden-container-id': 'containers.field.label',
'data-garden-container-version': '3.0.19',
id,
htmlFor,
...other
};
}, [labelId, inputId]);
const getHintProps = useCallback(function (_temp2) {
let {
id = hintId,
...other
} = _temp2 === void 0 ? {} : _temp2;
return {
'data-garden-container-id': 'containers.field.hint',
'data-garden-container-version': '3.0.19',
id,
...other
};
}, [hintId]);
const getInputProps = useCallback(function (_temp3) {
let {
id = inputId,
'aria-describedby': ariaDescribedBy,
...other
} = _temp3 === void 0 ? {} : _temp3;
const getDescribedBy = () => {
if (ariaDescribedBy) {
return ariaDescribedBy;
}
const describedBy = [];
if (hasHint) {
describedBy.push(hintId);
}
if (hasMessage) {
describedBy.push(messageId);
}
return describedBy.length > 0 ? describedBy.join(' ') : undefined;
};
return {
'data-garden-container-id': 'containers.field.input',
'data-garden-container-version': '3.0.19',
id,
'aria-labelledby': labelId,
'aria-describedby': getDescribedBy(),
...other
};
}, [inputId, labelId, hintId, messageId, hasHint, hasMessage]);
const getMessageProps = useCallback(function (_temp4) {
let {
id = messageId,
role = 'alert',
...other
} = _temp4 === void 0 ? {} : _temp4;
return {
'data-garden-container-id': 'containers.field.message',
'data-garden-container-version': '3.0.19',
role: role === null ? undefined : role,
id,
...other
};
}, [messageId]);
return useMemo(() => ({
getLabelProps,
getHintProps,
getInputProps,
getMessageProps
}), [getLabelProps, getHintProps, getInputProps, getMessageProps]);
};
const FieldContainer = _ref => {
let {
children,
render = children,
...options
} = _ref;
return React.createElement(React.Fragment, null, render(useField(options)));
};
FieldContainer.propTypes = {
children: PropTypes.func,
render: PropTypes.func,
idPrefix: PropTypes.string,
hasHint: PropTypes.bool,
hasMessage: PropTypes.bool
};
export { FieldContainer, useField };