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

Optional context #111

Draft
wants to merge 7 commits into
base: main
Choose a base branch
from
Draft
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
29 changes: 29 additions & 0 deletions .github/workflows/pkg.pr.new.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
name: PKG PR New
on:
workflow_dispatch:
pull_request:
types: [opened, synchronize, ready_for_review]
push:
branches:
- main

jobs:
build:
runs-on: ubuntu-latest

steps:
- name: Checkout code
uses: actions/checkout@v4

- uses: actions/setup-node@v4
with:
node-version: 20

- run: yarn --frozen-lockfile

# append the git commit to the package.json version.
# We do this because some cache mechanisms (like nextjs) don't work well with the same version and ignore the changes
# until you manually delete the cache
- run: jq '.version = .version + "-" + env.GITHUB_SHA' package.json > package.json.tmp && mv package.json.tmp package.json

- run: npx pkg-pr-new publish
4 changes: 2 additions & 2 deletions src/lib/AsyncTypeaheadInput.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import { useFormContext } from "./context/FormContext";
import TypeheadRef from "react-bootstrap-typeahead/types/core/Typeahead";
import { LabelValueOption } from "./types/LabelValueOption";

interface AsyncTypeaheadProps<T extends FieldValues> extends CommonTypeaheadProps<T> {
type AsyncTypeaheadProps<T extends FieldValues> = CommonTypeaheadProps<T> & {
queryFn: (query: string) => Promise<TypeaheadOptions>;
reactBootstrapTypeaheadProps?: Partial<UseAsyncProps>;
}
Expand Down Expand Up @@ -38,7 +38,7 @@ const AsyncTypeaheadInput = <T extends FieldValues>(props: AsyncTypeaheadProps<T
inputRef,
useGroupBy = false,
} = props;
const { name, id } = useSafeNameId(props.name, props.id);
const { name, id } = useSafeNameId(props?.name ?? "", props.id);
const ref = useRef<TypeheadRef | null>(null);

const {
Expand Down
4 changes: 2 additions & 2 deletions src/lib/DatePickerInput.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ interface DatePickerRenderAddonProps {
toggleDatePicker: () => void;
}

interface DatePickerInputProps<T extends FieldValues> extends Omit<CommonInputProps<T, DatePickerRenderAddonProps>, "onChange" | "style"> {
type DatePickerInputProps<T extends FieldValues> = Omit<CommonInputProps<T, DatePickerRenderAddonProps>, "onChange" | "style"> & {
/**
* The props for the date picker component: https://reactdatepicker.com/
*/
Expand Down Expand Up @@ -68,7 +68,7 @@ const DatePickerInput = <T extends FieldValues>(props: DatePickerInputProps<T>)
hideValidationMessage = false,
} = props;

const { id, name } = useSafeNameId(initialName, initialId);
const { id, name } = useSafeNameId(initialName ?? "", initialId);
const { control, getValues, setValue, disabled: formDisabled } = useFormContext();
const internalDatePickerRef = useRef<DatePicker>();
const formGroupId = useRef(guidGen());
Expand Down
23 changes: 10 additions & 13 deletions src/lib/FormGroupLayout.tsx
Original file line number Diff line number Diff line change
@@ -1,25 +1,25 @@
/* eslint-disable complexity */
import { PropsWithChildren, ReactNode, CSSProperties, useMemo } from "react";
import { FieldError, FieldValues, get } from "react-hook-form";
import { FormGroup, FormFeedback, FormText, InputGroup } from "reactstrap";
import { useSafeNameId } from "src/lib/hooks/useSafeNameId";
import { CommonInputProps, MergedAddonProps } from "./types/CommonInputProps";
import "./styles/FormGroupLayout.css";
import { FormGroupLayoutLabel } from "./FormGroupLayoutLabel";
import { useFormContext } from "./context/FormContext";
import { UnknownType, useFormContextInternal } from "./context/FormContext";

interface FormGroupLayoutProps<T extends FieldValues, TRenderAddon>
extends PropsWithChildren<
Pick<CommonInputProps<T>, "helpText" | "label" | "name" | "id" | "labelToolTip" | "inputOnly" | "hideValidationMessage">
> {
type FormGroupLayoutProps<T extends FieldValues = UnknownType, TRenderAddon = unknown> = PropsWithChildren<
Pick<CommonInputProps<T>, "helpText" | "label" | "name" | "id" | "labelToolTip" | "inputOnly" | "hideValidationMessage">
> & {
layout?: "checkbox" | "switch";
addonLeft?: ReactNode | ((props: TRenderAddon) => ReactNode);
addonRight?: ReactNode | ((props: TRenderAddon) => ReactNode);
addonProps?: MergedAddonProps<TRenderAddon>;
inputGroupStyle?: CSSProperties;
formGroupId?: string;
}
};

const FormGroupLayout = <T extends FieldValues, TRenderAddon = unknown>(props: FormGroupLayoutProps<T, TRenderAddon>) => {
const FormGroupLayout = <T extends FieldValues = UnknownType, TRenderAddon = unknown>(props: FormGroupLayoutProps<T, TRenderAddon>) => {
const {
label,
helpText,
Expand All @@ -34,13 +34,10 @@ const FormGroupLayout = <T extends FieldValues, TRenderAddon = unknown>(props: F
addonProps,
hideValidationMessage = false,
} = props;
const { name, id } = useSafeNameId(props.name, props.id);
const {
formState: { errors },
hideValidationMessages,
} = useFormContext();
const { name, id } = useSafeNameId(props?.name ?? "", props.id);
const { formState, hideValidationMessages = false } = useFormContextInternal() ?? {};

const fieldError = get(errors, name) as FieldError | undefined;
const fieldError = formState ? (get(formState.errors, name) as FieldError | undefined) : undefined;
const errorMessage = String(fieldError?.message);

const switchLayout = layout === "switch";
Expand Down
15 changes: 8 additions & 7 deletions src/lib/FormGroupLayoutLabel.tsx
Original file line number Diff line number Diff line change
@@ -1,19 +1,20 @@
import { ReactNode } from "react";
import { useFormContext } from "./context/FormContext";
import { FieldPath, FieldValues } from "react-hook-form";
import { UnknownType, useFormContextInternal } from "./context/FormContext";
import { FieldValues, Path } from "react-hook-form";
import { Label, UncontrolledTooltip } from "reactstrap";
import { CommonInputProps } from "./types/CommonInputProps";

interface FormGroupLayoutLabelProps<T extends FieldValues> {
interface FormGroupLayoutLabelProps<T extends FieldValues = UnknownType> {
label: ReactNode;
tooltip?: ReactNode;
fieldName: FieldPath<T>;
fieldName: CommonInputProps<T>["name"];
fieldId: string;
layout?: "checkbox" | "switch";
}

const FormGroupLayoutLabel = <T extends FieldValues>(props: FormGroupLayoutLabelProps<T>) => {
const FormGroupLayoutLabel = <T extends FieldValues = UnknownType>(props: FormGroupLayoutLabelProps<T>) => {
const { label, tooltip, fieldName, layout, fieldId } = props;
const { requiredFields } = useFormContext<T>();
const { requiredFields = [] } = useFormContextInternal<T>() ?? {};

if (!label && !!tooltip) {
throw new Error("You can't have a tooltip without a label");
Expand All @@ -23,7 +24,7 @@ const FormGroupLayoutLabel = <T extends FieldValues>(props: FormGroupLayoutLabel
return null;
}

const fieldIsRequired = typeof label == "string" && requiredFields.includes(fieldName);
const fieldIsRequired = typeof label == "string" && requiredFields.includes(fieldName as Path<T>);
const finalLabel = fieldIsRequired ? `${String(label)} *` : label;

const switchLayout = layout === "switch";
Expand Down
152 changes: 98 additions & 54 deletions src/lib/FormattedInput.tsx
Original file line number Diff line number Diff line change
@@ -1,24 +1,20 @@
import classnames from "classnames";
import { Controller, FieldValues } from "react-hook-form";
import { Controller, ControllerRenderProps, FieldValues } from "react-hook-form";
import { NumericFormat, NumericFormatProps, PatternFormat, PatternFormatProps } from "react-number-format";
import { useSafeNameId } from "src/lib/hooks/useSafeNameId";
import { FormGroupLayout } from "./FormGroupLayout";
import { CommonInputProps } from "./types/CommonInputProps";
import { useMarkOnFocusHandler } from "./hooks/useMarkOnFocusHandler";
import { useFormContext } from "./context/FormContext";

interface FormattedInputProps<T extends FieldValues> extends CommonInputProps<T> {
patternFormat?: PatternFormatProps;
numericFormat?: NumericFormatProps;
}

const FormattedInput = <T extends FieldValues>(props: FormattedInputProps<T>) => {
if (props.patternFormat && props.numericFormat) {
throw new Error("FormattedInput cannot have both patternFormat and numericFormat");
}
import { UnknownType, useFormContextInternal } from "./context/FormContext";

type FormattedInputInternalProps<T extends FieldValues = UnknownType> = Omit<FormattedInputProps<T>, "name" | "disabled"> & {
name: string;
isDisabled?: boolean;
commonProps?: NumericFormatProps;
fieldOnChange?: ControllerRenderProps<FieldValues, string>["onChange"];
};
const FormattedInputInternal = <T extends FieldValues = UnknownType>(props: FormattedInputInternalProps<T>) => {
const {
disabled,
label,
helpText,
numericFormat,
Expand All @@ -33,14 +29,94 @@ const FormattedInput = <T extends FieldValues>(props: FormattedInputProps<T>) =>
addonRight,
className = "",
hideValidationMessage = false,
defaultValue,
name,
id,
isDisabled,
commonProps,
fieldOnChange,
} = props;
const { name, id } = useSafeNameId(props.name, props.id);
const { control, disabled: formDisabled } = useFormContext();

const focusHandler = useMarkOnFocusHandler(markAllOnFocus);
const commonPropsInternal = commonProps ?? {
onBlur: (e) => {
if (propsOnBlur) {
propsOnBlur(e);
}
},
disabled: isDisabled,
className: classnames("form-control", className),
};

return (
<FormGroupLayout
helpText={helpText}
name={name}
id={id}
label={label}
labelToolTip={labelToolTip}
inputGroupStyle={inputGroupStyle}
addonLeft={addonLeft}
addonRight={addonRight}
addonProps={{
isDisabled,
}}
hideValidationMessage={hideValidationMessage}
>
<>
{numericFormat && (
<NumericFormat
defaultValue={defaultValue}
{...numericFormat}
{...commonPropsInternal}
valueIsNumericString={true}
onChange={(e) => {
if (propsOnChange) propsOnChange(e);
}}
onValueChange={(values) => {
fieldOnChange && fieldOnChange(values.value);
}}
onFocus={focusHandler}
style={style}
></NumericFormat>
)}

{patternFormat && (
<PatternFormat
{...patternFormat}
{...commonPropsInternal}
onChange={fieldOnChange}
style={style}
onFocus={focusHandler}
></PatternFormat>
)}
</>
</FormGroupLayout>
);
};

type FormattedInputProps<T extends FieldValues = UnknownType> = CommonInputProps<T> & {
patternFormat?: PatternFormatProps;
numericFormat?: NumericFormatProps;
};

const FormattedInput = <T extends FieldValues = UnknownType>(props: FormattedInputProps<T>) => {
if (props.patternFormat && props.numericFormat) {
throw new Error("FormattedInput cannot have both patternFormat and numericFormat");
}

const {
disabled,
onBlur: propsOnBlur,
className = "",
} = props;

const { name, id } = useSafeNameId(props?.name ?? "", props.id);
const { control, disabled: formDisabled = false } = useFormContextInternal() ?? {};

const isDisabled = formDisabled || disabled;

return (
return control ? (
<Controller
control={control}
name={name}
Expand All @@ -57,49 +133,17 @@ const FormattedInput = <T extends FieldValues>(props: FormattedInputProps<T>) =>
if (propsOnBlur) propsOnBlur(e);
onBlur();
},
onValueChange: (values) => {
onChange(values.value);
},
disabled: isDisabled,
};

return (
<FormGroupLayout
helpText={helpText}
name={name}
id={id}
label={label}
labelToolTip={labelToolTip}
inputGroupStyle={inputGroupStyle}
addonLeft={addonLeft}
addonRight={addonRight}
addonProps={{
isDisabled,
}}
hideValidationMessage={hideValidationMessage}
>
<>
{numericFormat && (
<NumericFormat
{...numericFormat}
{...commonProps}
valueIsNumericString={true}
onChange={(e) => {
if (propsOnChange) propsOnChange(e);
}}
onValueChange={(values) => {
onChange(values.value);
}}
onFocus={focusHandler}
style={style}
></NumericFormat>
)}

{patternFormat && (
<PatternFormat {...patternFormat} {...commonProps} onChange={onChange} style={style} onFocus={focusHandler}></PatternFormat>
)}
</>
</FormGroupLayout>
);
return <FormattedInputInternal {...props} isDisabled={isDisabled} name={name} fieldOnChange={onChange} commonProps={commonProps} />;
}}
/>
) : (
<FormattedInputInternal {...props} isDisabled={isDisabled} name={name} />
);
};

Expand Down
13 changes: 6 additions & 7 deletions src/lib/Input.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,12 @@ import { FormGroupLayout } from "./FormGroupLayout";
import { InputInternal } from "./InputInternal";
import { CommonInputProps } from "./types/CommonInputProps";
import { LabelValueOption } from "./types/LabelValueOption";
import { useFormContext } from "./context/FormContext";
import { UnknownType, useFormContextInternal } from "./context/FormContext";
import { MutableRefObject } from "react";

const invalidAddonTypes = ["switch", "radio", "checkbox"];

interface InputProps<T extends FieldValues> extends CommonInputProps<T> {
type InputProps<T extends FieldValues = UnknownType> = CommonInputProps<T> & {
type?: InputType;
options?: LabelValueOption[];
multiple?: boolean;
Expand All @@ -26,7 +26,7 @@ interface InputProps<T extends FieldValues> extends CommonInputProps<T> {
innerRef?: MutableRefObject<HTMLInputElement | HTMLTextAreaElement | null>;
}

const Input = <T extends FieldValues>(props: InputProps<T>) => {
const Input = <T extends FieldValues = UnknownType>(props: InputProps<T>) => {
const { type, options, addonLeft, name, addonRight, rangeMin, rangeMax, textAreaRows, multiple, id, value, disabled, step } = props;

if (type === "radio" && !options) {
Expand Down Expand Up @@ -67,9 +67,8 @@ const Input = <T extends FieldValues>(props: InputProps<T>) => {
return undefined;
})();

const { id: safeId } = useSafeNameId(name, id);
const { disabled: formDisabled } = useFormContext<T>();

const { id: safeId } = useSafeNameId(name ?? "", id);
const { disabled: formDisabled = false } = useFormContextInternal<T>() ?? {};
const isDisabled = formDisabled || disabled;

return (
Expand Down Expand Up @@ -102,7 +101,7 @@ const Input = <T extends FieldValues>(props: InputProps<T>) => {
</>
) : (
<>
<InputInternal {...props} />
<InputInternal {...props as InputProps} />
</>
)}
</FormGroupLayout>
Expand Down
Loading