0.5.17 • Published 3 years ago

tbc-panda-helpers v0.5.17

Weekly downloads
588
License
-
Repository
-
Last release
3 years ago

TBC Common React App Helpers Modules

Helpers for all Trinidad Benham Panda React apps, including:

  • CommonDropDown
  • Icons
  • LabeledInput
  • MultiSelect
  • CheckboxInput
  • DateTimeInput
  • EditSaveButton
  • ConfirmationButton
  • InputWithButton
  • NumericInput

Install

npm install --save tbc-panda-helpers

Styles

As of version 0.4.0, to use any of the components included in this module, the following style file will need to be imported/included into the main App.scss:

@import "tbc-panda-helpers/dist/styles/header.scss";

If the DateTimeInput is to be included in your app, add the following to index.js along with other third party style inclusions:

import "react-datepicker/dist/react-datepicker.css";

Components

CommonDropDown Component:

Common Drop Down takes a dictionary or array of data objects and returns a group of option tags (for use within a select).

import CommonDropDown from "tbc-panda-helpers/dist/CommonDropDown";

Within a select tag or React Component equivalent, place:

<CommonDropDown {...props} />

CommonDropDown props

PropTypeRequiredDefaultDescription
optionsArrayRequired*nullArray of data objects to be converted to a list. Either this or dictionary must be provided
dictionaryObjectRequired*nullObject of data objects to be converted to a list. Either this or options must be provided
sortByStringOptional"nm"Sets how the return options are sorted; by default this is by the "nm" key
optionValueCodeStringOptional"cd"By default the values of each option will be the data object's "cd"; use this prop if another key should be used instead
optionDisplayCodeStringOptional"nmBy default the display name for each option will be the data object's "nm"; use this prop if another key should be used instead
noBlankFirstLineBooleanOptionalfalseBy default a blank line will be provided at the top of the option list; set this flag if no blank line should be provided
ignoreActiveFlagBooleanOptionalfalseBy default, only data items with an "act" flag set to true will be displayed in the option list; use this flag to display all items, regardless of "act" flag
defaultValueObjectOptionalnullIf a defaultValue object is provided, this object will be displayed at the top of the option list, beneath the blank blank line (if applicable). The defaultValue object looks like {optionValueCode: "value", optionalDisplayCode: "Default Value"}
placeHolderTestStringOptionalnullText of a default placeholder value for drop downs; appears at top of list if enabled. Uses class placeHolder-text which can be defined in CSS for optional styling

Expected data format

options

CommonDropDown expects the options array to look like this:

[
    {
        cd: "CODE",
        nm: "Name",
        act: true,
        ...
    },    
    {
        cd: "INACT",
        nm: "Inactive Value",
        act: false,
        ...
    }
]

Other key/values can be provided, but these will not be used by the CommonDropDown unless set so by the props.

dictionary

CommonDropDown expect the dictionary object to look like this:

{
    CODE: {
        nm: "Name",
        act: true,
        ...
    },
    INACT: {
        nm: "Inactive Value",
        act: false,
        ...
    }
}

By default, the key of each item will be used as the value, although this can be modified via props, as can the display name.

Icons Component:

Icons component contains three pre-build dynamic icons.

import { RequiredIcon, WarningIcon, SavedIcon, YesNoIcon } from "tbc-panda-helpers/dist/Icons";

RequiredIcon:

This is a small icon that can be placed at the end of a field label for a required field; it has a tool tip stating "Required Field"

<RequiredIcon notRequired={!required} />
PropTypeRequiredDefaultDescription
notRequiredBooleanOptionalfalseFlag that determines if the required icon is not needed (if set to true, the RequiredIcon does not display). The purpose of this is to add a conditional flag to the icon to simplify conditional required

WarningIcon:

This is a small icon that can be placed where ever a warning can be placed.

<WarningIcon {...props} />
PropTypeRequiredDefaultDescription
showBooleanOptionalfalseFlag that determines if the warning icon should be displayed
toolTipStringOptional""Text of the tooltip (mouse over) of the icon
cssClassesStringOptional""Additional css classes that can be applied to the warning icon

SavedIcon:

This icon shows a red file or green upload icon depending on if the "saved" flag prop is provided.

<SavedIcon saved={saved} />
PropTypeRequiredDefaultDescription
savedBooleanOptionalfalseFlag that determines if the icon is in "unsaved" or "saved" mode

YesNoIcon:

This icon shows a red x in a circle for prop of false and a green check in a circle for prop of true.

<YesNoIcon boolean={boolean} />
PropTypeRequiredDefaultDescription
booleanBooleanOptionalfalseFlag that determines if the icon is in "yes" or "no" mode

LabeledInput Component:

This takes the potentially large and oft-repeated Formik field input and simplifies it into a single React component.

import LabeledInput from "tbc-panda-helpers/dist/LabeledInput";

 <LabeledInput
    name="title"
    title="Input Title"
    columnWidths={[6, 6]}
    formProps={formProps}
    {...props}
/>
PropTypeRequiredDefaultDescription
nameStringRequired""The field name, used by Formik
titleStringRequired*""Text of the input label
formPropsObjectRequired{}Formik props passed into its form
typeStringOptional"input"Type of input: "input" for text input field, and "select" for a drop down
childrenReact.ComponentOptionalnullIf "select" type is chosen, this is the list of drop down option tags, typically using the <CommonDropDown /> component
onChangeFunctionOptionalformProps.handleChange()Optional additional handleChange handler, beyond the one provided by Formik
columnWidthsArrayOptional6 , 6The Bootstrap column widths of Label and Input (respectively)
isDisabledBooleanOptionalfalseFlag; if true, input is disabled
disabledBooleanOptionalnullDEPRECIATED; alias for isDisabled Flag
isRequiredBooleanOptionalfalseFlag; if true, the <RequiredIcon /> is displayed within the label, and the field become required
requiredBooleanOptionalnullDEPRECIATED; alias for isRequird Flag;
warningMessageStringOptional""If provided, a <WarningIcon /> will be displayed in the label, with the message as its tooltip
validateFunctionOptionalnullIf required flag is set and the required validation is more than just whether or not a value is returned, this Function determines if requirements are met. Example: validate={() => isNumber(formProps.values.thisField())} If no validate function is provided, validation will be done on whether or not the field is populated.
hasValidationSchemaBooleanOptionalfalseFlag; if true, assumes parent Formik form is using validationSchema for validation; this validationSchema will take precedence over validate or required parameters; required parameter is still necessary for display of fields that are required (or have other validations)
fieldClassStringOptional""Optional class names applied to entire input component
classNameStringOptionalnullDEPRECIATED; alias for fieldClass parameter
inputFieldClassStringOptional""Optional class names applied only to input element
fieldClassNameStringOptionalnullDEPRECIATED; alias for inputFieldClass paramater
customErrorObjectObjectOptional{}Object used to define if tooltip error indicator is used instead of below-field Alert. Parameters are: useTooltip Boolean flag, customErrorClass String used to define which class(es) are applied to errored fields (defaults to internal class "default-error-border") , and placement String for Tooltip position (defaults to "left")

MultiSelect Component:

MultiSelect is a specialized input select component that allows for multiple items within a drop down to be selected and displayed. It uses react-select as a foundation.

import MultiSelect from "tbc-panda-helpers/dist/MultiSelect";

  <MultiSelect
    formProps={formProps}
    title="MultiSelect Values:"
    name="multiSelectValues"
    columnWidths={[12, 12]}
    optionList={options.map(item => {
      return { value: item.cd, label: item.nm };
    })}
    onChange={sel => {
      console.log("selection:", sel);
      formProps.setFieldValue("multiSelectValues", sel);
    }}
    closeMenuOnSelect
    isRequired
  />
PropTypeRequiredDefaultDescription
nameStringRequired""The field name, used by Formik
titleStringRequired*""Text of the input label
formPropsObjectRequired{}Formik props passed into its form
optionListArrayRequired**nullThe array of input option objects; option objects should look like { value: item.cd, label: item.nm }
onChangeFunctionOptionalnullonChange event (Formik default onChange event is not passed into MultiSelect)
closeMenuOnSelectBooleanOptionalfalseIf set to true, this flag causes the selection drop down to close upon a choice being made
fieldClassStringOptional""Any custom classes to be used by the MultiSelect component (overall)
inputFieldClassStringOptional""Any custom classes to be used in just the input element
isDisabledBooleanOptionalfalseDisabled flag
isRequiredBooleanOptionalfalseFlag; if true, the <RequiredIcon /> is displayed within the label, and the field become required
customErrorObjectObjectOptional{}Object used to define if tooltip error indicator is used instead of below-field Alert. Parameters are: useTooltip Boolean flag, customErrorClass String used to define which class(es) are applied to errored fields (defaults to internal class "default-error-border") , and placement String for Tooltip position (defaults to "left")

NOTE:

The values returned by MultiSelect is an array of { value: item.cd, label: item.nm } objects (same format as the optionsList input).

CheckboxInput Component:

CheckboxInput

This is similar to LabeledInput except it provides a label and checkbox

import CheckboxInput from "tbc-panda-helpers/dist/CheckboxInput";

 <CheckboxInput
    name="Checkbox"
    title="check"
    formProps={formProps}
    columnWidths={[6, 6]}
    isDisabled={isDisabled}
    isRequired={isRequired}
/>
PropTypeRequiredDefaultDescription
nameStringRequired""The field name, used by Formik
titleStringRequired""Text of the input label
formPropsObjectRequired{}Formik props passed into its form
columnWidthsArrayOptional6 , 6The Bootstrap column widths of Label and Input (respectively)
isDisabledBooleanOptionalfalseFlag; if true, input is disabled
isRequiredBooleanOptionalfalseFlag; if true, the <RequiredIcon /> is displayed within the label, and the field become required
fieldClassStringOptional""Optional class names applied to input field
onChangeFunctionOptionalformProps.handleChange()Optional additional handleChange handler, beyond the one provided by Formik
valueBooleanOptionalundefinedValue of checkbox; if none provided, will use formProps.values instead

Checkbox

This component also contains the stand-alone checkbox, which can be used separately from the label.

import { Checkbox } from "tbc-panda-helpers/dist/CheckboxInput";

 <Checkbox
    title="check"
    formProps={formProps}
    isDisabled={isDisabled}
/>
PropTypeRequiredDefaultDescription
titleStringRequired""Text of the input label
formPropsObjectRequired{}Formik props passed into its form
isDisabledBooleanOptionalfalseFlag; if true, input is disabled
onChangeFunctionOptionalnullonChange event (Formik default onChange event is not passed into MultiSelect)

DateTimeInput Component:

Date/Time input and label, using react-datepicker within Formik Field.

import DateTimeInput from "tbc-panda-helpers/dist/DateTimeInput";

 <DateTimeInput
    name="datetime"
    title="Date/Time"
    formProps={formProps}
    columnWidths={[6, 6]}
    placeHolderText="Select Date and Time"
    isDisabled={isDisabled}
    isRequired={isRequired}
    fieldClass=""
    calendarClass=""
    visualDateFormat="MMMM d, yyyy h:mm aa"
    dataDateFormat="MM/DD/YYYY hh:mm A"
    showTimeSelect={showTimeSelect}
    timeIntervals={15}
    timeFormat="HH:mm"
    timeCaption="Time"
  />
PropTypeRequiredDefaultDescription
nameStringRequired""The field name, used by Formik
titleStringRequired""Text of the input label
formPropsObjectRequired{}Formik props passed into its form
columnWidthsArrayOptional6 , 6The Bootstrap column widths of Label and Input (respectively)
placeHolderTextStringOptional""Text that will appear in field until values are entered
isDisabledBooleanOptionalfalseFlag; if true, input is disabled
isRequiredBooleanOptionalfalseFlag; if true, the <RequiredIcon /> is displayed within the label, and the field become required
fieldClassStringOptional""Optional class names applied to input field
calendarClassStringOptional""Optional class names applied to calendar popper
visualDateFormatStringOptional"MMMM d, yyyy h:mm aa"Optional format for date as displayed
dataDateFormatStringOptional"MM/DD/YYYY hh:mm A"Optional format for date used by data/form
showTimeSelectBooleanOptionaltrueFlag; if true, time selection is available
timeIntervalsNumberOptional15Optional increments used by time selection
timeFormatStringOptional"HH:mm"Optional format for time in selection
timeCaptionStringOptional"Time"Optional caption for time selection
customErrorObjectObjectOptional{}Object used to define if tooltip error indicator is used instead of below-field Alert. Parameters are: useTooltip Boolean flag, customErrorClass String used to define which class(es) are applied to errored fields (defaults to internal class "default-error-border") , and placement String for Tooltip position (defaults to "left")

NOTE: Additional props can be passed into DateTimeInput, and they will pass as is into DatePicker within.

Edit/Save Component:

A single component that replaces need for separate "Edit" and "Save" buttons (displayed based on state). Button component with two states: a single button with text "Edit" and a pair of buttons for "Save" and "Cancel".

import EditSaveButton from "tbc-panda-helpers/dist/EditSaveButton";

<EditSaveButton
  isDisabled={isDisabled}
  isSaveMode={toggleValue}
  toggleFunc={() => {
    toggleEditSave();
  }}
  saveFunc={() => {
    formProps.handleSubmit();
    toggleEditSave();
  }}
  cancelFunc={() => {
    formProps.handleReset();
    toggleEditSave();
  }}
  isSaveDisabled={isSaveDisabled}
  align={align}
/>
PropTypeRequiredDefaultDescription
isDisabledBooleanOptionalfalseflag; if "true" then "Edit" mode is disabled
isSaveModeBooleanRequiredfalseflag; if "true" then mode switches to "SaveCancel"
toggleFuncFunctionRequired() => {}Function fired when "Edit" is pressed, typically switching the value provided to the "isSaveMode" prop
saveFuncFunctionRequired() => {}Function fired when "Save" is pressed; NOTE: this does not automatically fire toggleFunc, so that should be provided separately if desired
cancelFuncFunctionOptionalsame as toggleFuncFunction fired when "Save" is pressed; NOTE: if nothing is provided, then toggleFunc will be fired, but toggleFunc isn't fired automatically if a function is provided to the cancelFunc prop
isSaveDisabledBooleanOptionalfalseflag; if "true" then "Save" button is disabled
alignStringOptional"right""right" or "left"; the alignment of the buttons
isIconOnlyBooleanOptionalfalseflag; if "true" then text is removed and only icons display; changes width from 160px to 70px
iconSizeStringOptional"lg"Used only if isIconOnly flag is true; sets icon size based on FontAwesome icon sizing convention ("lg", "2x", etc)
primaryButtonObjectOptional{class: "info", text: "Edit", icon: "far fa-edit"}Optional object containing "edit" button's class, text, and iconvalues

ConfirmationButton Component:

Button component with two states: a single button with customizable text and a pair of buttons for "Save" and "Cancel". Replaces the need for some confirmation modals.

import ConfirmationButton from "tbc-panda-helpers/dist/ConfirmationButton";

<ConfirmationButton
  primaryButton={{      
    class: "btn-main",
    text: "Edit",
    icon: "far fa-edit",
    isDisabled: false
  }}
  confirmedFunc={confirmedFunc}
  message="Are you sure?"
  align="right"
/>
PropTypeRequiredDefaultDescription
primaryButtonObjectRequired{}Object containing button class, text, icon, and isDisabled flag
confirmedFuncFunctionRequired() => {}Function fired upon confirmation
messageStringOptional"Confirm?"Tooltip message explaining why there is a confirmation
alignStringOptional"right""right" or "left"; the alignment of the buttons

InputWithButton Component:

Text input component with integration button.

import InputWithButton from "tbc-panda-helpers/dist/InputWithButton";

<InputWithButton
  title="Input:"
  name="input"
  formProps={formProps}
  columnWidths={[6, 6]}
  isRequired={isRequired}
  buttonIcon={"fas fa-search"}
  buttonClass={"btn-prime"}
  buttonPosition={"end"}
  isButtonDisabled={!formProps.values.input}
  buttonFunction={() => {
    setModalOpen(true);
  }}
/>
PropTypeRequiredDefaultDescription
nameStringRequired""The field name, used by Formik
titleStringRequired""Text of the input label
formPropsObjectRequired{}Formik props passed into its form
columnWidthsArrayOptional6 , 6The Bootstrap column widths of Label and Input (respectively)
fieldClassStringOptional""Optional class names applied to input field
isDisabledBooleanOptionalfalseFlag; if true, input is disabled
isRequiredBooleanOptionalfalseFlag; if true, the <RequiredIcon /> is displayed within the label, and the field become required
buttonIconStringOptional"fas fa-search"Icon used by Button
buttonClassStringOptional"btn-prime"Class used by Button (beyond "btn")
buttonPositionStringOptional"end"Is button before ("start") or after ("end") text input field
isButtonDisabledBooleanOptionalfalseflag; If true button is disabled
buttonFunctionFunctionRequired() => {}Function fired when button is pressed

NumericInput Component:

Input component for numeric input only.

NOTE: This is more robust than using type="number" within LabeledInput.

import NumericInput from "tbc-panda-helpers/dist/NumericInput";

<NumericInput
  name="number"
  title="Number:"
  formProps={formProps}
  columnWidths={[6, 6]}
  isDisabled={demoFlag}
/>
PropTypeRequiredDefaultDescription
nameStringRequired""The field name, used by Formik
titleStringRequired""Text of the input label
formPropsObjectRequired{}Formik props passed into its form
columnWidthsArrayOptional6 , 6The Bootstrap column widths of Label and Input (respectively)
fieldClassStringOptional""Optional class names applied to input field
isDisabledBooleanOptionalfalseFlag; if true, input is disabled
isRequiredBooleanOptionalfalseFlag; if true, the <RequiredIcon /> is displayed within the label, and the field become required
validationMessageStringOptional""If prop contains a value, message will be displayed beneath field (same styles as Required alert)
allowNegativeBooleanOptionaltrueFlag; if false, negative values are disallowed
showThousandSeparatorBooleanOptionaltrueFlag; if false then comma thousand separator is not displayed
isFixedDecimalScaleBooleanOptionalfalseFlag; if true then all values will contain number of significant digits as defined in decimalScale prop
decimalScaleNumberOptional0Number of significant digits any value in field will be rounded to
onChangeFunctionOptionalnullFunction called onChange; if nothing provided, then default formProps onChange will be called
unitsStringOptionalnullIf provided, then will be displayed as an addendum or prepended to input field
isPrependedUnitsBooleanOptionalfalseFlag; if true then units will be displayed before input field; otherwise, will be displayed after
customErrorObjectObjectOptional{}Object used to define if tooltip error indicator is used instead of below-field Alert. Parameters are: useTooltip Boolean flag, customErrorClass String used to define which class(es) are applied to errored fields (defaults to internal class "default-error-border") , and placement String for Tooltip position (defaults to "left")
valueBooleanNumberundefinedValue of field; if none provided, will use formProps.values instead

Required NPM Packages

npm install --save formik react-select react-datepicker lodash moment framer-motion react-number-format

Testing

For any unit test file that deep renders ("mounts") this imported component, add the following:

jest.mock("tbc-panda-helpers/dist/CommonDropDown", () => "div"); jest.mock("tbc-panda-helpers/dist/Icons", () => "div"); jest.mock("tbc-panda-helpers/dist/LabeledInput", () => "div"); jest.mock("tbc-panda-helpers/dist/MultiSelect", () => "div"); jest.mock("tbc-panda-helpers/dist/CheckboxInput", () => "div"); jest.mock("tbc-panda-helpers/dist/DateTimeInput", () => "div"); jest.mock("tbc-panda-helpers/dist/EditSaveButton", () => "div"); jest.mock("tbc-panda-helpers/dist/ConfirmationButton", () => "div"); jest.mock("tbc-panda-helpers/dist/InputWithButton", () => "div"); jest.mock("tbc-panda-helpers/dist/NumericInput", () => "div");

Changelog

  • 0.3.0: Addition of CheckboxInput, DateTimeInput, EditSaveButton, ConfirmationButton, InputWithButton components
  • 0.3.7: Updated Boolean naming convention in new components (to "isSomething" or "showSomething" instead of just "something")
  • 0.4.2: Added NumericInput
  • 0.5.0: Updated MultiSelect to match other inputs; improvements to NumericInput
  • 0.5.1: Added onChange prop option to CheckboxInput
  • 0.5.3: LabeledInput now functions with Formik/Yup validationSchema; uses both isRequired/isDisabled and required/disabled (depreciated) params
  • 0.5.6: Alternate error display option added (customErrorObject; generates Tooltip instead of Alert)
  • 0.5.9: Added isIconOnly flag to Save/Edit Button
  • 0.5.12: Added iconSize field to icon only Save/Edit button
  • 0.5.15: Added optional primaryButton param to Save/Edit button
  • 0.5.16: Allow 0 in NumericInput required fields; also disabled autocomplete in DateTimeInput
  • 0.5.17: Added placeHolderText to CommonDropDown