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

feat: component updates #302

Closed
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16,188 changes: 10,281 additions & 5,907 deletions package-lock.json

Large diffs are not rendered by default.

7 changes: 5 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "basis",
"version": "1.71.0",
"version": "1.72.0",
"description": "Basis Design System",
"main": "dist/index.js",
"module": "dist/esm/index.js",
Expand All @@ -14,6 +14,7 @@
"build-basis:cjs": "cross-env NODE_ENV=production BABEL_ENV=cjs babel src -d dist --ignore \"src/**/*.test.js\"",
"build-basis:esm": "cross-env NODE_ENV=production BABEL_ENV=esm babel src -d dist/esm --ignore \"src/**/*.test.js\"",
"build-basis": "npm run build-basis:cjs && npm run build-basis:esm",
"build-basis:watch": "nodemon --watch . --ignore ./dist --exec \"npm run build-basis:cjs\"",
"prebuild": "rimraf public",
"build": "cd website && npm run build && mv public .. && cd ..",
"prepublishOnly": "npm run build-basis",
Expand All @@ -29,7 +30,8 @@
"mem": "6.1.1",
"nanoid": "3.1.22",
"polished": "3.7.1",
"react-keyed-flatten-children": "1.3.0"
"react-keyed-flatten-children": "1.3.0",
"react-otp-input": "^3.0.4"
},
"peerDependencies": {
"@emotion/core": "^10.0.28",
Expand Down Expand Up @@ -67,6 +69,7 @@
"inquirer": "^8.1.5",
"jest": "26.6.3",
"mq-polyfill": "1.1.8",
"nodemon": "^3.0.1",
"prettier": "2.2.1",
"prop-types": "15.7.2",
"react": "16.14.0",
Expand Down
12 changes: 6 additions & 6 deletions src/components/Form.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ const DEFAULT_PROPS = {
};

function getParentFieldName(target) {
return target.dataset.parentName ?? target.name;
return target?.dataset?.parentName ?? target.name;
}

Form.DEFAULT_PROPS = DEFAULT_PROPS;
Expand Down Expand Up @@ -73,7 +73,7 @@ function Form(_props) {
lastMouseDownInputElement.current = null;
}

/*
/*
We use setTimeout in order to differentiate between onBlur to another field within
the same parent (e.g. DatePicker) and onBlur out of the parent.
*/
Expand Down Expand Up @@ -146,12 +146,12 @@ function Form(_props) {
const getFieldErrors = useCallback((values, name) => {
const value = getPath(values, name);
/*
Note:
`getFieldErrors` is called by `useEffect` below when `namesToValidate` change,
and we set `namesToValidate` inside `setTimeout` in `onBlur`. This means that
Note:
`getFieldErrors` is called by `useEffect` below when `namesToValidate` change,
and we set `namesToValidate` inside `setTimeout` in `onBlur`. This means that
`getFieldErrors` will be called with a little delay.
This opens the door for `unregisterField` being called BEFORE `getFieldErrors` is called.
Think about an input field being focused and then the user clicks on a Next button which
Think about an input field being focused and then the user clicks on a Next button which
unmounts the current form and mounts the next form page.
In this case, `getFieldErrors` will be called with a `name` that doesn't exist in `fields.current`
anymore since `unregisterField` deleted it.
Expand Down
6 changes: 5 additions & 1 deletion src/components/Frequency.js
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,7 @@ const DEFAULT_PROPS = {
disabled: false,
selectPlaceholder: InternalSelect.DEFAULT_PROPS.placeholder,
optional: false,
commaSeparated: false,
validate: (value, { isInputEmpty, isFrequencyEmpty }) => {
const errors = [];

Expand Down Expand Up @@ -94,6 +95,7 @@ function Frequency(props) {
typeof amountPrefix === "string" && amountPrefix.length > 0,
disabled: (disabled) => typeof disabled === "boolean",
optional: (optional) => typeof optional === "boolean",
commaSeparated: (commaSeparated) => typeof commaSeparated === "boolean",
}
);
const {
Expand All @@ -113,6 +115,7 @@ function Frequency(props) {
helpText,
disabled,
optional,
commaSeparated,
validate,
validateData,
testId,
Expand Down Expand Up @@ -183,7 +186,7 @@ function Frequency(props) {
<InternalInput
name={`${name}.amount`}
parentName={name}
variant="numeric"
variant={commaSeparated ? "commaNumeric" : "numeric"}
data={data}
prefix={amountPrefix}
color={props.color}
Expand Down Expand Up @@ -276,6 +279,7 @@ Frequency.propTypes = {
helpText: PropTypes.node,
disabled: PropTypes.bool,
optional: PropTypes.bool,
commaSeparated: PropTypes.bool,
validate: PropTypes.oneOfType([PropTypes.func, PropTypes.bool]),
validateData: PropTypes.any,
testId: PropTypes.string,
Expand Down
5 changes: 4 additions & 1 deletion src/components/Input.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,10 @@ const DEFAULT_PROPS = {
return "Required";
}

if (variant === "numeric" && NUMERIC_REGEX.test(value) === false) {
if (
["numeric", "commaNumeric"].includes(variant) &&
NUMERIC_REGEX.test(value) === false
) {
return "Only 0-9 are allowed";
}

Expand Down
213 changes: 213 additions & 0 deletions src/components/OtpInput.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,213 @@
import React, { useState, useCallback, useMemo } from "react";
import PropTypes from "prop-types";
import { nanoid } from "nanoid";
import useField from "../hooks/internal/useField";
import { mergeProps } from "../utils/component";
import Field from "./internal/Field";
import OTPInput from "react-otp-input";
import useTheme from "../hooks/useTheme";
import useBackground from "../hooks/useBackground";
import useResponsivePropsCSS from "../hooks/useResponsivePropsCSS";

const DEFAULT_PROPS = {
codeLength: 6,
disabled: false,
optional: false,
color: "grey.t05",
shouldAutoFocus: true,
validate: (value, { isEmpty }) => {
if (isEmpty(value)) {
return "Required";
}

if (value.length !== 6) {
return "Must be 6 digits";
}

return null;
},
};

export default function OtpInput(props) {
const mergedProps = mergeProps(
props,
DEFAULT_PROPS,
{},
{
codeLength: (codeLength) => typeof codeLength === "number",
disabled: (disabled) => typeof disabled === "boolean",
optional: (optional) => typeof optional === "boolean",
shouldAutoFocus: (shouldAutoFocus) =>
typeof shouldAutoFocus === "boolean",
value: (value) => typeof value === "string",
}
);

const {
name,
codeLength,
disabled,
optional,
onChange: onChangeProp,
label,
helpText,
testId,
validate,
validateData,
} = mergedProps;
const isEmpty = useCallback((value) => value.trim() === "", []);
const validationData = useMemo(
() => ({
isEmpty,
...(validateData && { data: validateData }),
}),
[isEmpty, validateData]
);

const [otpInputId] = useState(() => `otp-input-${nanoid()}`);
const [auxId] = useState(() => `otp-input-aux-${nanoid()}`);

const {
value,
errors,
hasErrors,
onFocus,
onBlur,
onChange: fieldOnChange,
} = useField("OtpInput", {
name,
disabled,
optional,
validate,
data: validationData,
});

const onChange = useCallback(
(otpValue) => {
fieldOnChange({ target: { value: otpValue, name } });
onChangeProp && onChangeProp(otpValue);
},
[fieldOnChange, onChangeProp, name]
);

return (
<Field
optional={optional}
disabled={disabled}
label={label}
labelFor={otpInputId}
auxId={auxId}
helpText={helpText}
errors={errors}
testId={testId}
>
<OTPInput
id={otpInputId}
value={value}
onChange={onChange}
numInputs={codeLength}
containerStyle={{ gap: "4px" }}
renderInput={(inputProps, index) => {
return (
<InternalInput
name={name}
inputProps={inputProps}
hasErrors={hasErrors}
disabled={disabled}
onFocus={onFocus}
onBlur={onBlur}
index={index}
/>
);
}}
/>
</Field>
);
}

OtpInput.DEFAULT_PROPS = DEFAULT_PROPS;

OtpInput.propTypes = {
name: PropTypes.string.isRequired,
color: PropTypes.string,
codeLength: PropTypes.number,
isDisabled: PropTypes.bool,
shouldAutoFocus: PropTypes.bool,
value: PropTypes.string,
onChange: PropTypes.func,
validate: PropTypes.oneOfType([PropTypes.func, PropTypes.bool]),
validateData: PropTypes.any,
label: PropTypes.string.isRequired,
helpText: PropTypes.node,
testId: PropTypes.string,
};

function InternalInput(props) {
const {
hasErrors,
onFocus,
onBlur,
index,
name,
disabled,
inputProps: { style, ...otpInputProps },
} = props;
const theme = useTheme();
const { inputColorMap } = useBackground();
const inputCSS = useResponsivePropsCSS(props, DEFAULT_PROPS, {
color: (propsAtBreakpoint, theme, bp) => {
const color = props.color ?? inputColorMap[bp];

return theme.otpInput.getCSS({
targetElement: "input",
color,
});
},
});

const internalOnFocus = useCallback(
(event) => {
otpInputProps.onFocus(event);
onFocus(event);
},
[otpInputProps, onFocus]
);

const internalOnBlur = useCallback(
(event) => {
otpInputProps.onBlur(event);
onBlur(event);
},
[otpInputProps, onBlur]
);

return (
<div
css={theme.input.getCSS({
targetElement: "inputContainer",
})}
>
<input
aria-invalid={hasErrors ? "true" : null}
{...otpInputProps}
css={inputCSS}
disabled={disabled}
name={name}
onFocus={internalOnFocus}
onBlur={internalOnBlur}
index={index}
/>
</div>
);
}

InternalInput.propTypes = {
name: PropTypes.string.isRequired,
disabled: PropTypes.bool,
color: PropTypes.string,
hasErrors: PropTypes.bool.isRequired,
onFocus: PropTypes.func.isRequired,
onBlur: PropTypes.func.isRequired,
index: PropTypes.number.isRequired,
inputProps: PropTypes.object.isRequired,
};
56 changes: 56 additions & 0 deletions src/components/OtpInput.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
import React from "react";
import { render, screen, waitFor, fireEvent } from "../utils/test";
import "@testing-library/jest-dom/extend-expect";
import Form from "./Form";
import OtpInput from "./OtpInput";

function FormWithOtpInput(props) {
const initialValues = {
otp: "",
};

return (
<Form initialValues={initialValues}>
<OtpInput name="otp" {...props} />
</Form>
);
}

describe("OtpInput", () => {
it("renders correctly", () => {
render(<FormWithOtpInput label="Enter OTP" testId="otp" />);
expect(screen.getByTestId("otp")).toBeInTheDocument();
});

it("renders default number of inputs", () => {
render(<FormWithOtpInput label="Enter OTP" />);
const inputs = screen.getAllByRole("textbox");
expect(inputs.length).toBe(6);
});

it("becomes disabled when the disabled prop is true", () => {
render(<FormWithOtpInput label="Enter OTP" disabled />);
const inputs = screen.getAllByRole("textbox");
inputs.forEach((input) => {
expect(input).toBeDisabled();
});
});

it("calls onChange when value changes", () => {
const onChange = jest.fn();
render(<FormWithOtpInput label="Enter OTP" onChange={onChange} />);
const firstInput = screen.getAllByRole("textbox")[0];
fireEvent.change(firstInput, { target: { value: "1" } });
expect(onChange).toHaveBeenCalledWith("1");
});

it("displays an error message for invalid input", async () => {
render(<FormWithOtpInput label="Enter OTP" />);
const firstInput = screen.getAllByRole("textbox")[0];
fireEvent.change(firstInput, { target: { value: "1" } });
fireEvent.blur(firstInput);
await waitFor(() => {
expect(screen.getByText("Must be 6 digits")).toBeInTheDocument();
});
});
});
Loading
Loading