UNPKG

@zendeskgarden/container-field

Version:

Containers relating to field in the Garden Design System

119 lines (113 loc) 3.15 kB
/** * 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. */ 'use strict'; var React = require('react'); var containerUtilities = require('@zendeskgarden/container-utilities'); var PropTypes = require('prop-types'); const useField = _ref => { let { idPrefix, hasHint, hasMessage } = _ref; const prefix = containerUtilities.useId(idPrefix); const inputId = `${prefix}--input`; const labelId = `${prefix}--label`; const hintId = `${prefix}--hint`; const messageId = `${prefix}--message`; const getLabelProps = React.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 = React.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 = React.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 = React.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 React.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 }; exports.FieldContainer = FieldContainer; exports.useField = useField;