Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Display min/max limits with field description #15424

Merged
merged 19 commits into from
Jan 24, 2023
Merged
Show file tree
Hide file tree
Changes from 8 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ import {
const InputUID = ({
attribute,
contentTypeUID,
description,
hint,
disabled,
error,
intlLabel,
Expand Down Expand Up @@ -54,13 +54,6 @@ const InputUID = ({
)
: name;

const hint = description
? formatMessage(
{ id: description.id, defaultMessage: description.defaultMessage },
{ ...description.values }
)
: '';

const formattedPlaceholder = placeholder
? formatMessage(
{ id: placeholder.id, defaultMessage: placeholder.defaultMessage },
Expand Down Expand Up @@ -251,11 +244,6 @@ InputUID.propTypes = {
required: PropTypes.bool,
}).isRequired,
contentTypeUID: PropTypes.string.isRequired,
description: PropTypes.shape({
id: PropTypes.string.isRequired,
defaultMessage: PropTypes.string.isRequired,
values: PropTypes.object,
}),
disabled: PropTypes.bool,
error: PropTypes.string,
intlLabel: PropTypes.shape({
Expand All @@ -273,16 +261,17 @@ InputUID.propTypes = {
values: PropTypes.object,
}),
required: PropTypes.bool,
hint: PropTypes.oneOfType([PropTypes.string, PropTypes.array]),
};

InputUID.defaultProps = {
description: undefined,
disabled: false,
error: undefined,
labelAction: undefined,
placeholder: undefined,
value: '',
required: false,
hint: '',
};

export default InputUID;
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ import {
connect,
generateOptions,
getInputType,
getMinMax,
getStep,
select,
VALIDATIONS_TO_OMIT,
Expand Down Expand Up @@ -258,6 +259,8 @@ function Inputs({
...customFieldInputs,
};

const { inputMaximum, inputMinimum } = getMinMax(fieldSchema);

return (
<GenericInput
attribute={fieldSchema}
Expand All @@ -266,6 +269,8 @@ function Inputs({
// in case the default value of the boolean is null, attribute.default doesn't exist
isNullable={inputType === 'bool' && [null, undefined].includes(fieldSchema.default)}
description={description ? { id: description, defaultMessage: description } : null}
minimum={inputMinimum}
maximum={inputMaximum}
disabled={shouldDisableField}
error={error}
labelAction={labelAction}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
/**
* Get the minimum and maximum limits for an input
* @type { (fieldSchema: { minLength?: number; maxLength?: number; max?: number; min?: number } ) => { inputMaximum: number; inputMinimum: number } }
*/
const getMinMax = (fieldSchema) => {
gu-stav marked this conversation as resolved.
Show resolved Hide resolved
const { minLength, maxLength, max, min } = fieldSchema;

let inputMinimum;
let inputMaximum;

if (typeof min === 'number') {
inputMinimum = min;
} else if (typeof minLength === 'number') {
inputMinimum = minLength;
}

if (typeof max === 'number') {
inputMaximum = max;
} else if (typeof maxLength === 'number') {
inputMaximum = maxLength;
}

return { inputMaximum, inputMinimum };
};

export default getMinMax;
Original file line number Diff line number Diff line change
Expand Up @@ -3,4 +3,5 @@ export { default as generateOptions } from './generateOptions';
export { default as getInputType } from './getInputType';
export { default as getStep } from './getStep';
export { default as select } from './select';
export { default as getMinMax } from './getMinMax';
export { default as VALIDATIONS_TO_OMIT } from './VALIDATIONS_TO_OMIT';
Original file line number Diff line number Diff line change
Expand Up @@ -36,8 +36,9 @@ function createDefaultMetadata(schema, name) {
editable: true,
};

if (isRelation(schema.attributes[name])) {
const { targetModel } = schema.attributes[name];
const fieldAttributes = schema.attributes[name];
if (isRelation(fieldAttributes)) {
const { targetModel } = fieldAttributes;

const targetSchema = getTargetSchema(targetModel);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import PropTypes from 'prop-types';
import parseISO from 'date-fns/parseISO';
import formatISO from 'date-fns/formatISO';
import { useIntl } from 'react-intl';

import {
Checkbox,
DatePicker,
Expand All @@ -24,7 +25,10 @@ import {
import { Option } from '@strapi/design-system/Select';
import EyeStriked from '@strapi/icons/EyeStriked';
import Eye from '@strapi/icons/Eye';

import NotSupported from './NotSupported';
import useFieldHint from '../../hooks/useFieldHint';
import { getFieldUnits } from './utils';

const GenericInput = ({
autoComplete,
Expand All @@ -43,9 +47,17 @@ const GenericInput = ({
type,
value: defaultValue,
isNullable,
minimum,
maximum,
...rest
}) => {
const { formatMessage } = useIntl();
const { hint } = useFieldHint({
description,
minimum,
maximum,
units: getFieldUnits(type, minimum, maximum),
});
const [showPassword, setShowPassword] = useState(false);

const CustomInput = customInputs ? customInputs[type] : null;
Expand Down Expand Up @@ -92,6 +104,7 @@ const GenericInput = ({
<CustomInput
{...rest}
description={description}
hint={hint}
disabled={disabled}
intlLabel={intlLabel}
labelAction={labelAction}
Expand All @@ -114,13 +127,6 @@ const GenericInput = ({
)
: name;

const hint = description
? formatMessage(
{ id: description.id, defaultMessage: description.defaultMessage },
{ ...description.values }
)
: '';

const formattedPlaceholder = placeholder
? formatMessage(
{ id: placeholder.id, defaultMessage: placeholder.defaultMessage },
Expand Down Expand Up @@ -210,7 +216,10 @@ const GenericInput = ({
required={required}
value={value && new Date(value)}
selectedDateLabel={(formattedDate) => `Date picker, current is ${formattedDate}`}
selectButtonTitle={formatMessage({ id: 'selectButtonTitle', defaultMessage: 'Select' })}
selectButtonTitle={formatMessage({
id: 'selectButtonTitle',
defaultMessage: 'Select',
})}
/>
);
}
Expand Down Expand Up @@ -451,6 +460,8 @@ GenericInput.defaultProps = {
options: [],
step: 1,
value: undefined,
minimum: undefined,
maximum: undefined,
};

GenericInput.propTypes = {
Expand Down Expand Up @@ -501,6 +512,8 @@ GenericInput.propTypes = {
step: PropTypes.number,
type: PropTypes.string.isRequired,
value: PropTypes.any,
minimum: PropTypes.number,
maximum: PropTypes.number,
};

export default GenericInput;
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
/**
* @param {String} type
* @param {Number} minimum
* @param {Number} maximum
* @returns {'' | 'characters' | 'character'}
*/
const getFieldUnits = (type, minimum, maximum) => {
gu-stav marked this conversation as resolved.
Show resolved Hide resolved
if (type === 'number') {
return '';
}
const plural = Math.max(minimum || 0, maximum || 0) > 1;

if (plural) {
return 'characters';
}

return 'character';
};

export default getFieldUnits;
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export { default as getFieldUnits } from './fieldUnits';
90 changes: 90 additions & 0 deletions packages/core/helper-plugin/lib/src/hooks/useFieldHint/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
import React, { useEffect, useState, useCallback } from 'react';
import { useIntl } from 'react-intl';

/**
* @description
* A hook for generating the hint for a field
* @param {Object} description - the description of the field
* @param {Number} minimum - the minimum length or value of the field
* @param {Number} maximum - the maximum length or value of the field
* @param {String} units
*/
const useFieldHint = ({ description, minimum, maximum, units }) => {
const { formatMessage } = useIntl();

const [hint, setHint] = useState([]);

/**
* @returns {String}
*/
const buildDescription = useCallback(
(desc) =>
desc
? formatMessage({ id: desc.id, defaultMessage: desc.defaultMessage }, { ...desc.values })
: '',
[formatMessage]
);

/**
* Constructs a suitable description of a field's minimum and maximum limits
* @param {Number} minimum - the minimum length or value of the field
* @param {Number} maximum - the maximum length or value of the field
* @param {String} units
* @returns {Array}
*/
const buildMinMaxHint = useCallback(
(min, max, units) => {
const minIsNumber = typeof min === 'number';
const maxIsNumber = typeof max === 'number';

if (!minIsNumber && !maxIsNumber) {
return [];
}
const minMaxDescription = [];

if (minIsNumber) {
minMaxDescription.push(`min. {min}`);
}
if (maxIsNumber) {
minMaxDescription.push(`max. {max}`);
}
let defaultMessage;

if (minMaxDescription.length === 0) {
defaultMessage = '';
} else {
defaultMessage = `${minMaxDescription.join(' / ')} {units}{br}`;
}

return formatMessage(
{
id: `content-manager.form.Input.minMaxDescription`,
gu-stav marked this conversation as resolved.
Show resolved Hide resolved
defaultMessage,
},
{
min,
max,
units,
br: <br />,
gu-stav marked this conversation as resolved.
Show resolved Hide resolved
}
);
},
[formatMessage]
);

useEffect(() => {
const newDescription = buildDescription(description);
const minMaxHint = buildMinMaxHint(minimum, maximum, units);

if (newDescription.length === 0 && minMaxHint.length === 0) {
setHint('');

return;
}
setHint([...minMaxHint, newDescription]);
}, [units, description, minimum, maximum, buildMinMaxHint, buildDescription]);

return { hint };
};

export default useFieldHint;
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
import React from 'react';
import { renderHook, act } from '@testing-library/react-hooks';
import { IntlProvider } from 'react-intl';

import useFieldHint from '../index';

const messages = { 'message.id': 'response' };
const description = { id: 'message.id', defaultMessage: '' };
const units = 'units';

// eslint-disable-next-line react/prop-types
export const IntlWrapper = ({ children }) => (
<IntlProvider locale="en" messages={messages} textComponent="span">
{children}
</IntlProvider>
);

function setup(args) {
return new Promise((resolve) => {
act(() => {
resolve(renderHook(() => useFieldHint(args), { wrapper: IntlWrapper }));
});
});
}

describe('useFieldHint', () => {
test('correctly generates the description', async () => {
gu-stav marked this conversation as resolved.
Show resolved Hide resolved
const minimum = 1;
const maximum = 5;

const { result } = await setup({
description,
minimum,
maximum,
units,
});

expect(result.current.hint).toContain(`min. ${minimum} / max. ${maximum} ${units}`);
expect(result.current.hint).toContain('response');
});
});