saleor-dashboard/src/hooks/useForm.ts

168 lines
3.6 KiB
TypeScript
Raw Normal View History

import { toggle } from "@saleor/utils/lists";
import isEqual from "lodash/isEqual";
import omit from "lodash/omit";
import React from "react";
2019-08-09 10:17:04 +00:00
import { useState } from "react";
import useStateFromProps from "./useStateFromProps";
export interface ChangeEvent<TData = any> {
target: {
name: string;
value: TData;
};
}
export type SubmitPromise = Promise<any[]>;
2019-08-09 10:17:04 +00:00
export type FormChange = (event: ChangeEvent, cb?: () => void) => void;
export type FormErrors<T> = {
[field in keyof T]?: string | React.ReactNode;
};
2019-08-09 10:17:04 +00:00
export interface UseFormResult<T> {
change: FormChange;
data: T;
hasChanged: boolean;
reset: () => void;
set: (data: Partial<T>) => void;
2019-08-09 10:17:04 +00:00
submit: () => void;
triggerChange: () => void;
toggleValue: FormChange;
errors: FormErrors<T>;
Add Gift Cards #1 (#1291) * Add gift cards section to menu and add empty list component * Update messages * Change styling of app wide page header to match design * Add gift cards list table wip * Update prop name for status chip component to make it more consistent with other components * Replace old trash icon with new one * Add Size type based on action dialog sizes to be used app wide * Add delete icon button * Add new sizes option to status chip component * Add / update gift cards list components * Add bulk actions type * Work on gift cards list WIP * Small refactor * Fix styling of gift cards table * Remove temp files * Remove unnecessary type * Add gift cards section to menu and add empty list component * Update schema and types * Add link to gift card update page to gift cards list and add route to gift cards index * Extract order page title with status chip into a separate generic component and use it in order page title * wip * Update money component * Add gift card details card balance section * Refactor gift card details * Add vertical spacer component * Update schema and types * Add gift card tag input component along with necessary queries * Add gift card tag input to gift card update page * Add gift card update details card expiry section WIP * Add time period select field WIP * Post rebase refactor * Add time period select field to gift card update view * Fixes after review * Update schema, types and gift cards query * Add getFullName util function and replace existing manual usages * Add text with select field component * Add gift card update info card and refactor * Fix import * Add displaying order link in gift card update * Refactor * Connect gift card list to api * refactor * Add gift card create dialog * Fix gift card list styles, change location for gift card list query, minor refactor * Fix menu structure data for gift cards * Add channel currencies type to shop * Refactor text with select field * Add gift card expiry select component * Add gift card error type and fragment * Update global types * Add default prop to getFormErrors function * Move gift card details provider to providers dir * Update global utils with mapSingleValueNodeToChoice function * Update gift card tag input * Move and refactor time period field * Update schema * move format money function to other money ulities * Update gift card urls * Add content or skeleton component * Add gift card create util for extracting expiry settings input data * Remove content or skeleton component and move displaying logic to existing skeleton * Move displaying logic of gift card create dialog to list * Refactor * Add hooks for gift card bulk actions and gift card list to be used instead of context directly * Fix types for text with select field + add parsing for number typed field * Add initial currency to gift card create form * Fix gift card create dialog closing animation * Add gift card update info card * Refactor gift card update details card * Add gift card balance dialog * Move gift card update form providers to providers dir * Connect gift card update page to api, add necessary contexts etc. * Refactor * Refactor * Add hooks to use instead of gift card contexts directly * Fix types * Fix text field target name missing in passed event in text with select field * Add minimal value option to text with select field, add to gift card inputs * Fix gift card update balance dialog not changing hasChanged prop after submit * Refactor * Fix update balance dialog crashing the app when enetered wrong amount * Fix gift card list table header styles * Add enable / disable section to gift card update * Refactor * Refactor * Refactor * Add metadata to gift card update * Update messages ids * Refactor * Refactor * Refactor * Refactor * Update types after rebase * Fix types * Fixes after qa * Fix tests
2021-08-16 13:44:00 +00:00
setChanged: (value: boolean) => void;
setError: (name: keyof T, error: string | React.ReactNode) => void;
clearErrors: (name?: keyof T | Array<keyof T>) => void;
2019-08-09 10:17:04 +00:00
}
type FormData = Record<string, any | any[]>;
function merge<T extends FormData>(prevData: T, prevState: T, data: T): T {
return Object.keys(prevState).reduce(
(acc, key) => {
if (!isEqual(data[key], prevData[key])) {
acc[key as keyof T] = data[key];
}
return acc;
},
{ ...prevState }
);
}
function handleRefresh<T extends FormData>(
data: T,
newData: T,
setChanged: (status: boolean) => void
) {
if (isEqual(data, newData)) {
setChanged(false);
}
}
function useForm<T extends FormData>(
initial: T,
onSubmit?: (data: T) => SubmitPromise | void
2019-08-09 10:17:04 +00:00
): UseFormResult<T> {
const [hasChanged, setChanged] = useState(false);
const [errors, setErrors] = useState<FormErrors<T>>({});
2019-08-09 10:17:04 +00:00
const [data, setData] = useStateFromProps(initial, {
mergeFunc: merge,
onRefresh: newData => handleRefresh(data, newData, setChanged)
});
function toggleValue(event: ChangeEvent, cb?: () => void) {
const { name, value } = event.target;
const field = data[name as keyof T];
if (Array.isArray(field)) {
if (!hasChanged) {
setChanged(true);
}
setData({
...data,
[name]: toggle(value, field, isEqual)
});
}
if (typeof cb === "function") {
cb();
}
}
function change(event: ChangeEvent) {
const { name, value } = event.target;
if (!(name in data)) {
console.error(`Unknown form field: ${name}`);
return;
} else {
if (data[name] !== value) {
setChanged(true);
}
setData(data => ({
...data,
[name]: value
}));
}
}
function reset() {
setData(initial);
}
Add channel shipping zones (#1015) * Add naked input option to SingleAutocompleteSelectField and update it's stories * Add new icons - chevron up, down & trash * Add deletable item component and stories * Add card add items footer component to be used in warehouses and product stocks assign * Update schema and types * Add shipping zones card components * Update channel details page form to also include shipping zones * Update makeTopLevelSearch hook files directory and add getSearchFetchMoreProps function to avoid extracting it manually every time * Update channels types & fragments * Move getDefaultNotifierSuccessErrorData function to useNotifier utils, update dir etc., also make order discount provider use it from the new dir * Add shippinh zone to channel update and create and add shipping zone search * Update messages * Fix types * Fix lint, types etc * Small refactor from review and quick fix styles of shipping zones card * Refactor a bit and update snapshots * Refactor a bit and update snapshots * Addd / refactor channels availability components * Add useChannelsWithProductVariants hook with utils and types * Add / refactor more channels availability components * Move avatar from table cell avatar to separate component for it to be usable outside of tables * Add channels with variants logic to product create and update pages & views * Refactor components to use updated channels availability components * Remove unnecessary comments * Update storybook * Update types * Update messages * Fix prices for variants / simple product not uodating properly * Post merge cleanup, update schema, types, etc. * Change shipping zone details warehouses card into settings card and add ability to assign channels to shipping zone * Update types * Update snapshots * Fix selecting / deselecting all channels in channels with variants modal * Fixes after review, some types changes etc. * Update snapshots * Small types fixes * Make price rates views use parent shipping method channels instead of all * Make price rates views use parent shipping method channels instead of all * Update types * Fix bugs * Fixes after review * Fix channels availability data submission * Fix lint * Fix variant pricing card showing not related channels * Fixes after review * Fix types * Hide unaviable variants in add products to draft order dialog * Fix channels with variants availability modal showing confirm button as enabled when it shouldn't * Fix types * Update semi checked icon to match old designs * Update types * Update channels icon in channels with variants availability * Fix product cypress test after product channels mutation changed * Fix trash and chevron down colors in dark mode * Fix shipping zones card footer not updating query after click away * Fix types in schema, add condition not to display shipping zones select in channel details if all zones have already been selected * Fix products adding in order draft dialog * Fix simple productupdate * Update snapshots after merge with master * Update messages * Fix product api request for cypress * Add missing test id * Fix selecting if product is simple -> form being submitted with empty data sometimes * Update snapshots, messages and add fix for invalid date at product update * Remove unnecessary imports * Fix failing test in saleor 2552 (#1061) * fix * fix * fix Co-authored-by: Jakub Majorek <majorek.jakub@gmail.com> Co-authored-by: Karolina <rakoczy.karolina@gmail.com>
2021-04-14 13:44:25 +00:00
function set(newData: Partial<T>, setHasChanged = true) {
2019-08-09 10:17:04 +00:00
setData(data => ({
...data,
...newData
}));
Add channel shipping zones (#1015) * Add naked input option to SingleAutocompleteSelectField and update it's stories * Add new icons - chevron up, down & trash * Add deletable item component and stories * Add card add items footer component to be used in warehouses and product stocks assign * Update schema and types * Add shipping zones card components * Update channel details page form to also include shipping zones * Update makeTopLevelSearch hook files directory and add getSearchFetchMoreProps function to avoid extracting it manually every time * Update channels types & fragments * Move getDefaultNotifierSuccessErrorData function to useNotifier utils, update dir etc., also make order discount provider use it from the new dir * Add shippinh zone to channel update and create and add shipping zone search * Update messages * Fix types * Fix lint, types etc * Small refactor from review and quick fix styles of shipping zones card * Refactor a bit and update snapshots * Refactor a bit and update snapshots * Addd / refactor channels availability components * Add useChannelsWithProductVariants hook with utils and types * Add / refactor more channels availability components * Move avatar from table cell avatar to separate component for it to be usable outside of tables * Add channels with variants logic to product create and update pages & views * Refactor components to use updated channels availability components * Remove unnecessary comments * Update storybook * Update types * Update messages * Fix prices for variants / simple product not uodating properly * Post merge cleanup, update schema, types, etc. * Change shipping zone details warehouses card into settings card and add ability to assign channels to shipping zone * Update types * Update snapshots * Fix selecting / deselecting all channels in channels with variants modal * Fixes after review, some types changes etc. * Update snapshots * Small types fixes * Make price rates views use parent shipping method channels instead of all * Make price rates views use parent shipping method channels instead of all * Update types * Fix bugs * Fixes after review * Fix channels availability data submission * Fix lint * Fix variant pricing card showing not related channels * Fixes after review * Fix types * Hide unaviable variants in add products to draft order dialog * Fix channels with variants availability modal showing confirm button as enabled when it shouldn't * Fix types * Update semi checked icon to match old designs * Update types * Update channels icon in channels with variants availability * Fix product cypress test after product channels mutation changed * Fix trash and chevron down colors in dark mode * Fix shipping zones card footer not updating query after click away * Fix types in schema, add condition not to display shipping zones select in channel details if all zones have already been selected * Fix products adding in order draft dialog * Fix simple productupdate * Update snapshots after merge with master * Update messages * Fix product api request for cypress * Add missing test id * Fix selecting if product is simple -> form being submitted with empty data sometimes * Update snapshots, messages and add fix for invalid date at product update * Remove unnecessary imports * Fix failing test in saleor 2552 (#1061) * fix * fix * fix Co-authored-by: Jakub Majorek <majorek.jakub@gmail.com> Co-authored-by: Karolina <rakoczy.karolina@gmail.com>
2021-04-14 13:44:25 +00:00
setChanged(setHasChanged);
2019-08-09 10:17:04 +00:00
}
2020-10-22 11:33:29 +00:00
async function submit() {
if (typeof onSubmit === "function" && !Object.keys(errors).length) {
2020-10-22 11:33:29 +00:00
const result = onSubmit(data);
if (result) {
const errors = await result;
if (errors?.length === 0) {
2020-10-22 11:33:29 +00:00
setChanged(false);
}
}
}
2019-08-09 10:17:04 +00:00
}
function triggerChange() {
setChanged(true);
}
const setError = (field: keyof T, error: string | React.ReactNode) =>
setErrors(e => ({ ...e, [field]: error }));
const clearErrors = (field?: keyof T | Array<keyof T>) => {
if (!field) {
setErrors({});
} else {
setErrors(errors =>
omit<FormErrors<T>>(errors, Array.isArray(field) ? field : [field])
);
}
};
2019-08-09 10:17:04 +00:00
return {
setError,
errors,
2019-08-09 10:17:04 +00:00
change,
clearErrors,
2019-08-09 10:17:04 +00:00
data,
hasChanged,
reset,
Add Gift Cards #1 (#1291) * Add gift cards section to menu and add empty list component * Update messages * Change styling of app wide page header to match design * Add gift cards list table wip * Update prop name for status chip component to make it more consistent with other components * Replace old trash icon with new one * Add Size type based on action dialog sizes to be used app wide * Add delete icon button * Add new sizes option to status chip component * Add / update gift cards list components * Add bulk actions type * Work on gift cards list WIP * Small refactor * Fix styling of gift cards table * Remove temp files * Remove unnecessary type * Add gift cards section to menu and add empty list component * Update schema and types * Add link to gift card update page to gift cards list and add route to gift cards index * Extract order page title with status chip into a separate generic component and use it in order page title * wip * Update money component * Add gift card details card balance section * Refactor gift card details * Add vertical spacer component * Update schema and types * Add gift card tag input component along with necessary queries * Add gift card tag input to gift card update page * Add gift card update details card expiry section WIP * Add time period select field WIP * Post rebase refactor * Add time period select field to gift card update view * Fixes after review * Update schema, types and gift cards query * Add getFullName util function and replace existing manual usages * Add text with select field component * Add gift card update info card and refactor * Fix import * Add displaying order link in gift card update * Refactor * Connect gift card list to api * refactor * Add gift card create dialog * Fix gift card list styles, change location for gift card list query, minor refactor * Fix menu structure data for gift cards * Add channel currencies type to shop * Refactor text with select field * Add gift card expiry select component * Add gift card error type and fragment * Update global types * Add default prop to getFormErrors function * Move gift card details provider to providers dir * Update global utils with mapSingleValueNodeToChoice function * Update gift card tag input * Move and refactor time period field * Update schema * move format money function to other money ulities * Update gift card urls * Add content or skeleton component * Add gift card create util for extracting expiry settings input data * Remove content or skeleton component and move displaying logic to existing skeleton * Move displaying logic of gift card create dialog to list * Refactor * Add hooks for gift card bulk actions and gift card list to be used instead of context directly * Fix types for text with select field + add parsing for number typed field * Add initial currency to gift card create form * Fix gift card create dialog closing animation * Add gift card update info card * Refactor gift card update details card * Add gift card balance dialog * Move gift card update form providers to providers dir * Connect gift card update page to api, add necessary contexts etc. * Refactor * Refactor * Add hooks to use instead of gift card contexts directly * Fix types * Fix text field target name missing in passed event in text with select field * Add minimal value option to text with select field, add to gift card inputs * Fix gift card update balance dialog not changing hasChanged prop after submit * Refactor * Fix update balance dialog crashing the app when enetered wrong amount * Fix gift card list table header styles * Add enable / disable section to gift card update * Refactor * Refactor * Refactor * Add metadata to gift card update * Update messages ids * Refactor * Refactor * Refactor * Refactor * Update types after rebase * Fix types * Fixes after qa * Fix tests
2021-08-16 13:44:00 +00:00
setChanged,
2019-08-09 10:17:04 +00:00
set,
submit,
toggleValue,
triggerChange
};
}
export default useForm;