Cleanup, comments, e2e

This commit is contained in:
Jesus Vasquez 2024-03-05 17:42:30 -05:00
parent 1e0594a488
commit 8faa5354a8
14 changed files with 288 additions and 232 deletions

View file

@ -1,31 +0,0 @@
import type { Meta, StoryObj } from "@storybook/react"
import { Button } from "./Button"
const meta: Meta<typeof Button> = {
title: "Button",
component: Button,
args: {
intent: "primary",
underline: false,
children: "Button",
size: "lg",
},
argTypes: {
intent: {
options: ["primary", "secondary"],
control: { type: "select" },
},
size: {
options: ["sm", "lg"],
control: { type: "select" },
},
},
}
type Story = StoryObj<typeof Button>
export const Default: Story = {
render: (args) => <Button {...args} />,
}
export default meta

View file

@ -1,47 +0,0 @@
import { cva, type VariantProps } from "class-variance-authority"
import { twMerge } from "tailwind-merge"
const button = cva(
[
"justify-center",
"inline-flex",
"items-center",
"rounded-xl",
"text-center",
"border",
"border-blue-400",
"transition-colors",
"delay-50",
],
{
variants: {
intent: {
primary: ["bg-blue-400", "text-white", "hover:enabled:bg-blue-700"],
secondary: ["bg-transparent", "text-blue-400", "hover:enabled:bg-blue-400", "hover:enabled:text-white"],
},
size: {
sm: ["min-w-20", "h-full", "min-h-10", "text-sm", "py-1.5", "px-4"],
lg: ["min-w-32", "h-full", "min-h-12", "text-lg", "py-2.5", "px-6"],
},
underline: { true: ["underline"], false: [] },
},
defaultVariants: {
intent: "primary",
size: "lg",
},
}
)
export interface ButtonProps extends React.ButtonHTMLAttributes<HTMLAnchorElement>, VariantProps<typeof button> {
underline?: boolean
href: string
}
export function Button({ className, intent, size, underline, ...props }: ButtonProps) {
return (
<a className={twMerge(button({ intent, size, className, underline }))} {...props}>
{props.children}
</a>
)
}

View file

@ -0,0 +1,50 @@
/**
* Button component that supports primary and secondary variants, as well as size customization.
* Utilizes 'class-variance-authority' for managing class variants and 'tailwind-merge' for class merging.
*/
import React from 'react';
import { cva, type VariantProps } from 'class-variance-authority';
import { twMerge } from 'tailwind-merge';
/**
* Configure base and variant classes using 'class-variance-authority'
* Variants:
* - 'primary': Blue background with white text, changes on hover.
* - 'secondary': Transparent background with amber border and text, changes on hover.
* Sizes:
* - 'sm': Small size button.
* - 'lg': Large size button (default).
*/
const button = cva(
"flex items-center justify-center rounded-md py-3 px-9 text-center text-sm font-bold transition-all md:min-w-[240px]",
{
variants: {
variant: {
primary: ["bg-blue-950 text-white", "hover:enabled:bg-blue-700"],
secondary: ["border-2 border-amber-500 text-amber-500", "hover:enabled:bg-amber-500 hover:enabled:text-white"],
},
size: {
sm: ["py-2 px-4", "text-xs"],
lg: ["py-3 px-9", "text-sm"],
},
},
defaultVariants: {
variant: "primary",
size: "lg",
},
}
);
// ButtonProps extends standard button attributes with variant and size customization options.
export interface ButtonProps extends React.ButtonHTMLAttributes<HTMLButtonElement>, VariantProps<typeof button> {}
// Button component: Renders a button with customizable variants, sizes, and additional passed props.
export const Button: React.FC<ButtonProps> = ({ className, variant, size, ...props }) => {
return (
<button className={twMerge(button({ variant, size }), className)} {...props}>
{props.children}
</button>
);
};

View file

@ -1,21 +1,34 @@
/**
* ClientField Component
*
* Renders a list of testing centers with associated client selection inputs.
* Each testing center allows for the selection of a client from a provided list.
*/
import { faClock } from "@fortawesome/free-regular-svg-icons"
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"
import React from "react"
import SelectInput from "./SelectInput"
import { Utils } from "./Utils"
// Define a type for your props to improve type-checking
/**
* Props for ClientField component.
*
* @param testingCenters Array of testing center names to be displayed.
* @param clients Array of client names available for selection.
*/
type ClientFieldProps = {
testingCenters: string[]
clients: string[]
}
// Destructure the props in the function parameter
const ClientField: React.FC<ClientFieldProps> = ({ testingCenters, clients }) => {
return (
<div className="flex flex-col gap-4 text-sm leading-tight">
{/* Render a selection input for each testing center, allowing a client to be chosen for each. */}
{testingCenters.map((testingCenter) => (
<div key={Utils.camelize(testingCenter)} className="flex items-center gap-14">
<div key={Utils.camelize(testingCenter)} className="flex items-center gap-4 md:gap-14">
<span>{testingCenter}</span>
<div className="flex items-center gap-2">
<SelectInput name={Utils.camelize(testingCenter)}>

View file

@ -1,8 +1,14 @@
/**
* ErrorMessage Component
*
* Displays an error message if a form field has been touched and an error exists.
*/
import React from "react"
const ErrorMessage = ({ touched, error }: { touched: boolean; error?: string }) => {
if (touched && error) {
return <p className="text-xs text-red-500">{error}</p>
return <p className="text-xs text-red-500" role="alert">{error}</p>
}
return null
}

View file

@ -1,3 +1,10 @@
/**
* FileInput Component
*
* Renders a file input with drag-and-drop support. Displays the selected file's name and size,
* and simulates file upload progress. Integrates with Formik for form state management.
*/
import { faFile } from "@fortawesome/free-solid-svg-icons";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { useField, useFormikContext } from "formik";
@ -17,10 +24,17 @@ const FileInput: React.FC<FileInputProps> = ({ label, ...props }) => {
const [field, meta] = useField(props);
const { setFieldValue } = useFormikContext();
const fileInputRef = useRef<HTMLInputElement>(null);
const [dragging, setDragging] = useState(false); // State to handle drag styling
const [fileInfo, setFileInfo] = useState<{ name: string; size: number } | null>(null); // State to store file info
// State to manage drag-over styling
const [dragging, setDragging] = useState(false);
// State to store information about the selected file
const [fileInfo, setFileInfo] = useState<{ name: string; size: number } | null>(null);
// State to simulate and display upload progress
const [uploadProgress, setUploadProgress] = useState(0);
// Simulates file upload progress
const simulateUpload = () => {
let progress = 0;
const interval = setInterval(() => {
@ -32,6 +46,7 @@ const FileInput: React.FC<FileInputProps> = ({ label, ...props }) => {
}, 20); // Adjust time interval to control speed of the animation
};
// Handles file selection via input change event
const handleChange = (event: React.ChangeEvent<HTMLInputElement>) => {
const { files } = event.target;
const file = files ? files[0] : null;
@ -43,12 +58,14 @@ const FileInput: React.FC<FileInputProps> = ({ label, ...props }) => {
}
};
// Opens the file input dialog
const handleClick = () => {
if (fileInputRef.current) {
fileInputRef.current.click();
}
};
// Handles file drop
const handleDrop = (event: React.DragEvent<HTMLDivElement>) => {
event.preventDefault();
event.stopPropagation();
@ -65,7 +82,7 @@ const FileInput: React.FC<FileInputProps> = ({ label, ...props }) => {
}
};
// Manages drag-over state for styling
const handleDragOver = (event: React.DragEvent<HTMLDivElement>) => {
event.preventDefault();
if (!dragging) {
@ -73,6 +90,7 @@ const FileInput: React.FC<FileInputProps> = ({ label, ...props }) => {
}
};
// Resets dragging state when dragging leaves the drop area
const handleDragLeave = (event: React.DragEvent<HTMLDivElement>) => {
event.preventDefault();
setDragging(false);

View file

@ -1,3 +1,10 @@
/**
* RadioGroupField Component
*
* Renders a group of radio buttons using Radix UI with Formik integration.
* Supports custom options, labels, and an optional separator.
*/
import * as RadioGroup from "@radix-ui/react-radio-group"
import { useField } from "formik"
import React from "react"
@ -5,22 +12,37 @@ import ErrorMessage from "./ErrorMessage"
import RequiredAsterisk from "./RequiredAsterisk"
import Separator from "./Separator"
const RadioGroupField = ({
/**
* Props for RadioGroupField.
*
* @param name The name attribute for the radio group, used for form submission.
* @param label Display label for the radio group.
* @param separator Optional boolean to render a visual separator above the radio group.
* @param options Array of option strings that the radio group will display.
* @param props Additional props passed to the radio group, including `required`.
*/
interface RadioGroupFieldProps {
name: string;
label: string;
separator?: boolean;
options: string[];
[key: string]: any; // This allows for additional props not explicitly defined in the interface.
}
const RadioGroupField: React.FC<RadioGroupFieldProps> = ({
name,
label,
separator,
options,
...props
}: {
name: string
label: string
separator?: boolean
options: string[]
[x: string]: any // Allow any other props
}) => {
const { required, ...restProps } = props
// State and helpers from Formik for managing radio group value
const [field, meta, helpers] = useField({ ...restProps, name })
// Handles radio option change, updating Formik's state
const handleChange = (value: string) => {
helpers.setValue(value)
}

View file

@ -4,6 +4,7 @@ import ErrorMessage from "./ErrorMessage"
import RequiredAsterisk from "./RequiredAsterisk"
const SelectInput = ({ label, ...props }: { label?: string; name: string; [x: string]: any }) => {
// Since `useField` only needs `name`, and optionally `type` and `value`, we destruct those from props
const { required, ...restProps } = props
const [field, meta] = useField(restProps)

View file

@ -1,21 +1,28 @@
/**
* StatusField Component
*
* Displays a status label with a customizable color. This component is typically used
* to indicate the status of a process or entity (e.g., success, error) within the application.
* Includes a visual separator and supports dynamic text and color customization through props.
*/
import React from "react"
import Separator from "./Separator"
const StatusField = ({
label,
statusLabel,
statusColor,
}: {
label: string
statusLabel: string
statusColor: string
}) => {
interface StatusFieldProps {
label: string;
statusLabel: string;
statusColor: string;
}
const StatusField: React.FC<StatusFieldProps> = ({ label, statusLabel, statusColor }) => {
return (
<div className="flex flex-col gap-2">
<div className="flex flex-col gap-4">
<Separator/>
<h4 className="font-bold text-sm leading-tight text-indigo-900">{label}</h4>
</div>
{/* Dynamically styled based on status */}
<span className={`text-sm leading-tight ${statusColor}`}>{statusLabel}</span>
</div>
)

View file

@ -1,3 +1,10 @@
/**
* ToggleField Component
*
* Renders a toggle switch using Radix UI, integrated with Formik for form state management.
* Supports custom child content and displays an error message if validation fails.
*/
import * as SwitchPrimitive from "@radix-ui/react-switch"
import { useField } from "formik"
import React, { useState } from "react"
@ -7,6 +14,14 @@ import Separator from "./Separator"
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"
import { faClock } from "@fortawesome/free-regular-svg-icons"
/**
* Props for ToggleField.
*
* @param children ReactNode - The content to be displayed alongside the toggle switch.
* @extends React.InputHTMLAttributes<HTMLInputElement> - Inherits standard input attributes.
*/
const ToggleField = ({
children,
...props
@ -14,9 +29,20 @@ const ToggleField = ({
children: React.ReactNode
} & React.InputHTMLAttributes<HTMLInputElement>) => {
const { required, ...restProps } = props
// Formik hook for managing form state and validation
const [field, meta] = useField({ ...(restProps as { name: string }), type: "checkbox" })
// Local state to manage the checked status of the switch
const [checked, setChecked] = useState(false)
// Handles checked state change, updates Formik's state accordingly
const handleCheckedChange = (isChecked: boolean) => {
setChecked(isChecked);
field.onChange({ target: { name: field.name, value: isChecked } });
};
return (
<div className="flex flex-col gap-4">
<div className="flex flex-col gap-4">
@ -30,14 +56,11 @@ const ToggleField = ({
<SwitchPrimitive.Root
className="relative h-[25px] w-[42px] cursor-default rounded-full bg-indigo-900 outline-none"
checked={checked}
onCheckedChange={(isChecked) => {
setChecked(isChecked)
field.onChange({ target: { name: field.name, value: isChecked } })
}}
onCheckedChange={(isChecked) => handleCheckedChange(isChecked)}
>
<SwitchPrimitive.Thumb className="block h-[21px] w-[21px] translate-x-0.5 rounded-full bg-white transition-transform duration-100 will-change-transform data-[state=checked]:translate-x-[19px]" />
</SwitchPrimitive.Root>
<div className="flex gap-4 items-center text-sm leading-tight">
<div className="flex gap-2 md:gap-4 items-center text-xs md:text-sm leading-tight">
<span>Toggle ON</span>
<span>|</span>
<span className="flex gap-2 items-center"><FontAwesomeIcon icon={faClock} />Select Tolerance Level</span>

View file

@ -1,45 +1,43 @@
"use client"
import axios from "axios"
import { Form, Formik, useFormikContext } from "formik"
import React, { useState } from "react"
// React and Formik imports
import React, { useState } from "react";
import { Form, Formik } from "formik";
import axios from "axios";
//Dependencies
// UI components and utilities
import { Button } from "./Button";
import ClientField from "./ClientField";
import FileInput from "./FileInput";
import RadioGroup from "./RadioGroup";
import SelectInput from "./SelectInput";
import StatusField from "./StatusField";
import ToggleField from "./ToggleField";
//Input fields
import ClientField from "./ClientField"
import { data } from "./data"
import FileInput from "./FileInput"
import { initialValues, validationSchema } from "./formSchemas"
import RadioGroup from "./RadioGroup"
import SelectInput from "./SelectInput"
import StatusField from "./StatusField"
import ToggleField from "./ToggleField"
// Data and schema and types
import { FormValues } from "./types";
import { data } from "./data";
import { initialValues, validationSchema } from "./formSchemas";
import { FormValues } from "./types"
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"
import { faXmark } from "@fortawesome/free-solid-svg-icons"
{/* Close button */}
const CloseButton: React.FC = () => {
const { resetForm,setFieldValue } = useFormikContext();
const handleReset = () => {
resetForm();
setFieldValue("manifestFile", "");
}
return (
<button className="flex h-10 w-10 items-center justify-center rounded-lg bg-blue-950 text-white" onClick={() => handleReset()}>
<FontAwesomeIcon icon={faXmark} className="h-6 w-6" />
</button>
)
};
// Icons
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { faXmark } from "@fortawesome/free-solid-svg-icons";
/**
* FormComponent: Main form component for document upload.
*
* This component handles the document upload form, including input fields for document details,
* file upload, and form submission. It uses Formik for form state management and validation,
* and Axios for submission to a backend endpoint.
*/
const FormComponent: React.FC = () => {
// State to track if the form has been successfully submitted
const [formSubmitted, setFormSubmitted] = useState(false);
// Function to handle form submission
const submitForm = (values: FormValues) => {
//TODO implement form submission
return axios.post(
`/api/submitForm`,
{
@ -56,7 +54,7 @@ const FormComponent: React.FC = () => {
return (
<>
{/* Formik setup for handling form state, validation, and submission */}
<Formik
initialValues={initialValues}
validationSchema={validationSchema}
@ -78,15 +76,18 @@ const FormComponent: React.FC = () => {
return (
<Form>
<CloseButton />
{/* Title */}
{/* Close button - allows resetting the form to initial state */}
<button type="button" className="hidden md:flex h-10 w-10 items-center justify-center rounded-lg bg-blue-950 text-white" onClick={() => formik.resetForm()}>
<FontAwesomeIcon icon={faXmark} className="h-6 w-6" />
</button>
{/* Title - provides context for the form's purpose */}
<div className="flex justify-center mb-12">
<h1 className="border-grey-300 w-fit border-b pb-4 font-bold text-3xl text-indigo-900">Document Upload</h1>
</div>
<div className="flex flex-col gap-12">
{/* Form layout */}
{/* Form layout - organizes the form fields into logical sections */}
<div className="flex flex-col gap-4 lg:flex-row lg:gap-16">
{/* Left Column */}
<div className="flex w-full flex-col lg:w-[500px] gap-5">
@ -122,26 +123,25 @@ const FormComponent: React.FC = () => {
</div>
</div>
{/* Form Footer */}
{/* Form Footer - contains actions for form submission and cancellation */}
<div className="flex flex-col gap-6">
<p className="text-lg leading-tight text-center">Data in the import file is correct. Please press Continue to import.</p>
<div className="flex gap-6 justify-center">
<button
className="flex items-center justify-center rounded-md py-3 px-9 text-center text-sm font-bold transition-all bg-blue-950 text-white min-w-[240px]"
type="submit"
disabled={formik.isSubmitting}
>
Continue Import
{formik.isSubmitting && <div className="ml-3 h-5 w-5 animate-spin rounded-full border-x-2 border-b-2"></div>}
</button>
<button
className="flex items-center justify-center rounded-md py-3 px-9 text-center text-sm font-bold transition-all border-2 border-amber-500 text-amber-500 min-w-[240px]"
>
Cancel
</button>
<Button
variant="primary"
type="submit"
disabled={formik.isSubmitting} >
Continue Import
</Button>
<Button
variant="secondary"
type="button"
onClick={() => formik.resetForm()}>
Cancel
</Button>
</div>
{formSubmitted && <div className="text-center text-green-500">Success</div>}
{/* Success message - Display a success message if the form has been submitted successfully */}
{formSubmitted && <div className="sucess-message text-center text-green-500">Success</div>}
</div>
</div>

View file

@ -1,75 +0,0 @@
"use client"
import * as RadixTooltip from "@radix-ui/react-tooltip"
import { cva, VariantProps } from "class-variance-authority"
import React from "react"
import { twMerge } from "tailwind-merge"
const tooltipContent = cva([], {
variants: {
intent: {
primary: ["rounded-0.5md", "bg-zinc-700", "font-open-sans", "text-white"],
},
size: {
md: ["px-4", "py-2.5", "text-2xs"],
},
},
defaultVariants: {
intent: "primary",
size: "md",
},
})
const tooltipArrow = cva([], {
variants: {
intent: {
primary: ["fill-zinc-700"],
},
size: {
md: ["w-4", "h-2"],
},
},
defaultVariants: {
intent: "primary",
size: "md",
},
})
export interface TooltipProps extends VariantProps<typeof tooltipContent>, RadixTooltip.TooltipProps {
explainer: React.ReactElement | string
children: React.ReactElement
className?: string
withArrow?: boolean
side?: "top" | "right" | "bottom" | "left"
}
export function Tooltip({
children,
explainer,
open,
defaultOpen,
onOpenChange,
intent,
size,
side = "top",
className,
withArrow,
}: TooltipProps) {
return (
<RadixTooltip.Provider>
<RadixTooltip.Root open={open} defaultOpen={defaultOpen} onOpenChange={onOpenChange} delayDuration={200}>
<RadixTooltip.Trigger asChild>{children}</RadixTooltip.Trigger>
<RadixTooltip.Portal>
<RadixTooltip.Content
side={side}
sideOffset={5}
className={twMerge(tooltipContent({ intent, size, className }))}
>
{explainer}
{withArrow ? <RadixTooltip.Arrow className={twMerge(tooltipArrow({ intent, size, className }))} /> : null}
</RadixTooltip.Content>
</RadixTooltip.Portal>
</RadixTooltip.Root>
</RadixTooltip.Provider>
)
}

68
e2e/form.spec.ts Normal file
View file

@ -0,0 +1,68 @@
//TODO Install playwright
import { expect, test } from "@playwright/test"
//Form load and initial state validation
test("form loads correctly with initial state", async ({ page }) => {
await page.goto("/"); //Home URL
// Check if specific fields are present and empty
await expect(page.locator('input[name="importName"]')).toBeEmpty();
await expect(page.locator('input[name="manifestFile"]')).toBeEmpty();
await expect(page.locator('input[name="toleranceWindow"]')).not.toBeChecked();
// Verify that no option is selected initially for "splitSchedule"
await expect(page.locator('input[name="splitSchedule"]:checked')).toHaveCount(0);
// Verify that no option is selected initially for "client"
await expect(page.locator('input[name="client"]:checked')).toHaveCount(0);
// Check for the presence of the submit button and that it's initially disabled
const submitButton = page.locator('button', { hasText: 'Continue Import' });
await expect(submitButton).toBeDisabled();
});
//File upload validation
test("handles file upload correctly", async ({ page }) => {
await page.goto("/");
// Simulate file upload
await page.setInputFiles('input[type="file"]', '/e2e/testFile.txt');
// Check if the file name is displayed correctly
await expect(page.locator('.file-info')).toHaveText(/testFile.txt/);
// Optionally, check for the upload progress bar to reach 100%
await expect(page.locator('.upload-progress')).toHaveCSS('width', '100%');
});
//Toggle and submit interactions
test("toggles a switch and submits the form", async ({ page }) => {
await page.goto("/");
// Toggle a switch
await page.locator('input[name="toleranceWindow"]').click();
await expect(page.locator('input[name="toleranceWindow"]')).toBeChecked();
// Fill in other required fields
// Select an option from "importName" dropdown
await page.locator('select[name="importName"]').selectOption({ label: "Import ABC" });
// Upload a file for "manifestFile"
await page.locator('input[name="manifestFile"]').setInputFiles('/e2e/testFile.txt');
// Select an option for "splitSchedule"
await page.locator('input[name="splitSchedule"][value="Yes"]').click();
// Select an option for "client"
await page.locator('input[name="client"][value="Single"]').click();
// Enable and click the submit button
const submitButton = page.locator('button', { hasText: 'Continue Import' });
await expect(submitButton).toBeEnabled();
await submitButton.click();
// Verify submission was successful
await expect(page.locator('.success-message')).toHaveText(/Success/);
});

1
e2e/testFile.txt Normal file
View file

@ -0,0 +1 @@
File to be used to test the file upload field