Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 | 4x 4x 4x 4x 4x 4x 4x 4x 117x 115x 115x 4x 154x 154x 154x 154x 154x 154x 154x 154x 154x 154x 154x 154x 154x 154x 154x 154x 154x 154x 115x 7x 7x 115x 2x 2x 2x 4x 8x 115x 2x 2x 4x 8x 7x 2x 115x 30x 30x 50x 89x 22x 100x 115x 29x 55x 11x 44x 44x 44x 29x 115x 621x 670x 23x 647x 647x 8x 639x 621x 115x 398x 398x 31x 367x 211x 156x 115x 2088x 1249x 1249x 1153x 1153x 1153x 1153x 1153x 3445x 1249x 1249x 115x 332x 658x 332x 332x 115x 53x 53x 53x 1x 52x 115x 164x 162x 112x 112x 1x 222x 173x 98x 111x 115x 38x 38x 74x 115x 2030x 2030x 115x 194x 194x 1x 1x 193x 193x 2x 115x 3x 3x 1x 1x 2x 2x 115x 18x 18x 1x 17x 115x 4x 4x 4x 4x 4x 115x 49x 49x 49x 22x 115x 8x 8x 1x 8x 8x 8x 5x 3x 8x 8x 6x 8x 115x 5x 5x 5x 4x 115x 3x 3x 3x 3x 2x 115x 194x 194x 194x 194x 115x 3x 3x 3x 3x 115x 251x 251x 502x 8x 251x 251x 251x 99x 115x 2x 2x 2x 2x 2x 2x 115x 2x 2x 2x 2x 2x 2x 115x 448x 115x 1028x 466x 562x 562x 562x 115x 4167x 115x 1993x 1993x 115x 259x 259x 259x 115x 502x 251x 8x 251x 8x 8x 8x 8x 115x 251x 251x 251x 8x 115x 167x 167x 167x 167x 167x 167x 115x 448x 448x 9x 115x 322x 204x 204x 204x 115x 1953x 1953x 4x | import * as React from 'react';
import update, { UpdateTransform } from 'update-immutable';
import {
ValidatorData,
ValueMap,
ValidatorContext,
Environment,
} from '../../types';
import { BoundComponent } from '../bind';
import { MirrorInstance, Mirror } from '../Mirror';
import { validate } from '../../validator';
import { isCallable, getEnvironment } from '../../utils';
export const FormContext = React.createContext(undefined as FormApi);
export interface FormApi {
clear: Form<any>['clear'];
reset: Form<any>['reset'];
validate: Form<any>['validate'];
isValid: Form<any>['isValid'];
isPristine: Form<any>['isPristine'];
getValidatorData: Form<any>['getValidatorData'];
getValue: Form<any>['getValue'];
getValues: Form<any>['getValues'];
setValidatorData: Form<any>['setValidatorData'];
setValue: Form<any>['setValue'];
setValues: Form<any>['setValues'];
onComponentMount: Form<any>['handleComponentMount'];
onComponentUnmount: Form<any>['handleComponentUnmount'];
onComponentUpdate: Form<any>['handleComponentUpdate'];
onComponentBlur: Form<any>['handleComponentBlur'];
onComponentFocus: Form<any>['handleComponentFocus'];
registerMirror: Form<any>['registerMirror'];
unregisterMirror: Form<any>['unregisterMirror'];
initialValues: FormProps<any>['initialValues'];
debug?: FormProps<any>['debug'];
}
export interface FormProps<FormFields extends ValueMap> {
/**
* Called when the value of a bound form component has been changed.
* @param {string} componentName name of the component
* @param {object} value new value
*/
onChange?: (componentName: keyof FormFields, value: any) => void;
/**
* Called when a bound form component has been blurred.
* @param {string} componentName name of the component
* @param {object} value current value
*/
onBlur?: (componentName: keyof FormFields, value: any, event: any) => void;
/**
* Called when a bound form component has been focused.
* @param {string} componentName name of the component
* @param {object} value current value
*/
onFocus?: (componentName: keyof FormFields, value: any, event: any) => void;
/**
* Called when a component updates
* @param {string} componentName name of the component
*/
onUpdate?: (componentName: keyof FormFields) => void;
/**
* Called when the form is programmatically submitted, or a button with type="submit" is clicked.
* @param {object} values name/value pairs for all bound form components.
*/
onSubmit?: (values: FormFields) => void;
/**
* Called after onSubmit if all bound form components are valid.
* @param {object} values name/value pairs for all bound form components.
*/
onValidSubmit?: (values: FormFields) => void;
/**
* Called after onSubmit at least 1 bound form component is invalid.x
* @param {object} values name/value pairs for all bound form components.
*/
onInvalidSubmit?: (values: FormFields) => void;
/**
* A transformer func which allows the final form value to be manipulated.
* The calculated value that `getValue` would normally return is provided
* as an argument to this transformer.
*
* The returned value will take precedence over the value normally returned
* by `getValue`. It will also be use for form validation and provided to
* bound components. If it is not necessary to modify the value, simply
* return the provided value and `getValue` will behave as normal.
*/
valueTransformer?: (componentName: keyof FormFields, value: any) => any;
/**
* If you don't want to modify the values, simply return the provided values.
*
* A transformer func which is used to manipulate the entire form values to
* be manipulated. It is calculated after any individual `valueTransformer`'s
* have been applied.
*
* The returned value will take precedence over the value normally returned by
* `getValues`. If it is not necessary to modify the value, simply return the
* provided value and `getValue` will behave as normal
*
*/
valuesTransformer?: (values: FormFields) => FormFields;
/**
* Whether a hidden submit should be rendered within the form. The existence of a
* `<button type="submit"/>` allows forms to be submitted when the enter key is pressed.
* However, if you a form which is being submitted programmatically, or it doesn't
* make sense to show a submit button, setting this to true will allow submit on enter
* to work.
* @note this prop has no effect when using `react-native`.
*/
withHiddenSubmit?: boolean;
/**
* If true, a the html form element will not be rendered.
* @note this prop has no effect when using `react-native`.
*/
virtual?: boolean;
/**
* Whether the form component values should be sticky and retain their value in
* between component unmounts and mounts. By default, form component state is
* lost when a component is unmounted.
*/
sticky?: boolean;
/**
* Initial values to be provided to the bound form components. This is useful for
* populating the form without having to manage all form values. It can be provided
* asynchronously. The values will be applied if the form components have not been
* modified. If you need to apply new values to the form, call reset on the form after
* updating the initialValues.
*/
initialValues?: FormFields;
/**
* Whether the form and its descendent components should log debug messages.
*/
debug?: boolean;
}
export interface FormComponentState {
name: string;
pristine: boolean;
value?: any;
validatorData?: ValidatorData;
instance?: BoundComponent;
}
export class Form<FormComponents extends ValueMap = {}> extends React.Component<
FormProps<FormComponents>
> {
static defaultProps: FormProps<any> = {
sticky: false,
initialValues: {},
};
private components: {
[ComponentName in keyof FormComponents]: FormComponentState;
};
private mirrors: {
[ComponentName in keyof FormComponents]: MirrorInstance[];
};
constructor(props: FormProps<FormComponents>) {
super(props as any);
this.components = {} as any;
this.mirrors = {} as any;
}
render() {
this.logCall('render');
const {
children,
withHiddenSubmit,
virtual,
// Omitted
onChange,
onBlur,
onFocus,
onSubmit,
onValidSubmit,
onInvalidSubmit,
debug,
initialValues,
sticky,
valueTransformer,
// Injected
...restProps
} = this.props;
const api: FormApi = {
debug,
initialValues,
clear: this.clear,
reset: this.reset,
validate: this.validate,
isValid: this.isValid,
isPristine: this.isPristine,
getValidatorData: this.getValidatorData,
setValidatorData: this.setValidatorData,
getValue: this.getValue,
getValues: this.getValues,
setValue: this.setValue,
setValues: this.setValues,
onComponentMount: this.handleComponentMount,
onComponentUnmount: this.handleComponentUnmount,
onComponentUpdate: this.handleComponentUpdate,
onComponentBlur: this.handleComponentBlur,
onComponentFocus: this.handleComponentFocus,
registerMirror: this.registerMirror,
unregisterMirror: this.unregisterMirror,
};
return (
<FormContext.Provider value={api}>
{/* Skip rendering dom element in react-native environments */}
{virtual || getEnvironment() === Environment.ReactNative ? (
children
) : (
<form
{...(restProps as any)}
onSubmit={this.handleFormSubmit}
>
{children}
{withHiddenSubmit && (
<button type="submit" style={{ display: 'none' }} />
)}
</form>
)}
</FormContext.Provider>
);
}
//#region Public commands
/**
* programmatically submit the form. If you don't want to manually call this, a button
* with type submit should be provided to the form. This can be provided in your form
* implementation, or automatically using the `withHiddenSubmit` prop on the Form.
* @returns an object with 2 properties:
* - isValid: whether the entire form was valid when submitting
* - values: all of the form values at the time of submission
*/
public submit = () => {
this.logCall('submit');
return this.handleFormSubmit();
};
/**
* Clears the specified component(s) by setting their value to null. If no component
* names are provided, all components within the form will be cleared.
* @param {string|string[]} componentName component name(s) to be cleared
* @returns a promise which is resolved once the react components have been re-rendered
*/
public clear = async (
componentName?: keyof FormComponents | (keyof FormComponents)[],
): Promise<void[]> => {
this.logCall('clear', { componentName });
return Promise.all(
this.getComponentNames(componentName).map(async (componentName) => {
await this.setValue(componentName, null);
}),
);
};
/**
* Resets the specified component(s) by unsetting their value, validator and pristine
* state. If no component names are provided, all components within the form will be
* reset.
* @param {string|string[]} componentName component name(s) to be reset
* @returns a promise which is resolved once the react components have been re-rendered
*/
public reset = (
componentName?: keyof FormComponents | (keyof FormComponents)[],
): Promise<void[]> => {
this.logCall('reset', { componentName });
return Promise.all(
this.getComponentNames(componentName).map(async (componentName) => {
await this.updateComponent(componentName, {
$unset: ['value', 'validatorData', 'pristine'],
});
// We need to explicitly call reset since the updateComponent $unset wont reset validatorData
if (this.isRecursiveComponent(componentName)) {
await this.getComponentInstance(componentName).reset();
}
}),
);
};
/**
* Validates specified component(s) by executing the validator and updating the
* components to reflect their validator state. If no component names are provided,
* all components within the form will be validated.
* @param {string|string[]} componentName component name(s) to be validated.
* @returns a promise which is resolved once the react components have been re-rendered.
*/
public validate = (
componentName?: keyof FormComponents | (keyof FormComponents)[],
): Promise<void[]> => {
this.logCall('validate', { componentName });
return Promise.all(
this.getComponentNames(componentName).map(async (componentName) => {
/** Recursive components require calling `validate` on them to
* recursively trigger validation logic on their form components.
*/
if (this.isRecursiveComponent(componentName)) {
await this.getComponentInstance(componentName).validate();
}
await this.setValidatorData(
componentName,
this.executeValidator(componentName),
);
}),
);
};
//#endregion
//#region Public evaluators
/**
* Determines if all the specified component(s) are valid by executing the validator
* using the components current value. If no component names are provided, all
* components within the form will be tested.
*
* Note: if validatorData is being managed, the provided validatorData.context will
* be used instead of executing the validator.
*
* @param {string|string[]} componentName component name(s) to be tested
* @returns a boolean flag to indicate whether all the components are valid
*/
public isValid = (
componentName?: keyof FormComponents | (keyof FormComponents)[],
): boolean => {
const results = this.getComponentNames(componentName).map(
(componentName) => {
/**
* Recursive components don't have validation rules, therefore we rely on
* recursively calling isValid.
*/
if (this.isRecursiveComponent(componentName)) {
return this.getComponentInstance(componentName).isValid();
}
const componentProps = this.getComponentProps(componentName);
// Use managed validatorData (if exists), otherwise execute validator
const { context } = componentProps.validatorData
? componentProps.validatorData
: this.executeValidator(componentName);
return context !== ValidatorContext.Danger;
},
);
return !results.includes(false);
};
/**
* Determines if all the specified component(s) are pristine - the component has not
* been modified by the user or by programmatically calling setValue. If no component
* names are provided, all components within the form will checked.
* @param {string|string[]} componentName component name(s) to be tested
* @returns a boolean flag to indicate whether all the components are pristine
*/
public isPristine = (
componentName?: keyof FormComponents | (keyof FormComponents)[],
): boolean => {
const results = this.getComponentNames(componentName).map(
(componentName) => {
if (this.isRecursiveComponent(componentName)) {
return this.getComponentInstance(
componentName,
).isPristine();
}
const props = this.getComponentProps(componentName);
if (props?.pristine !== undefined) {
return props.pristine;
}
return componentName in this.components
? this.components[componentName].pristine
: true;
},
);
return !results.includes(false);
};
// #endregion
//#region Public getters
/**
* Returns the components current validatorData. There are 2 ways a components
* validator data can be retrieved (in order of precedence):
* 1. *externally managed validatorData* prop provided to the component
* 2. *internally managed validatorData* state when the user changes input
*
* **Note**: If the component has no validatorData, then an object with undefined
* context & message will be returned.
*
* @param {string} componentName name of the component to get validator data for
* @param {object} componentProps component props to extract validator data from.
* It's not necessary to provide this prop as its intended to be used by the
* form library internally.
* @returns component validator data
*/
public getValidatorData = (
componentName: keyof FormComponents,
IcomponentProps: BoundComponent['props'] = this.getComponentProps(
componentName,
),
): ValidatorData => {
// Return user provided validatorData (if exists)
if (componentProps.validatorData) {
return componentProps.validatorData;
}
if (componentName in this.components) {
return this.components[componentName].validatorData;
}
return {
context: undefined,
message: undefined,
};
};
/**
* Returns the value of the specified component. There are four
* ways a component value can be provided (in order of precedence):
* 1. *externally managed* value prop provided to the component
* 2. *internally managed* state value when the user changes input
* 3. *initialValues* provided to the form component
* 4. *defaultValue* specified on individual form component
*
* **Note**: the form values should not be mutated
*
* @param {string} componentName name of the component to get value for
* @param {object} componentProps component props to extract value from. It's
* not necessary to provide this prop as its intended to be used by the
* form library internally.
* @returns component value
*/
public getValue = (
componentName: keyof FormComponents,
componentProps: BoundComponent['props'] = this.getComponentProps(
componentName,
),
): any => {
const { valueTransformer } = this.props;
/**
* Recursive component values can't be derived from props, therefore we rely on
* recursively calling getValue.
*/
const value = this.isRecursiveComponent(componentName)
? this.getComponentInstance(componentName).getValue()
: (() => {
const propValue = componentProps
? componentProps.value
: undefined;
const defaultValue = componentProps
? componentProps.defaultValue
: undefined;
const stateValue = this.components[componentName]
? this.components[componentName].value
: undefined;
const initialValue = this.props.initialValues
? this.props.initialValues[componentName]
: undefined;
return [
propValue,
stateValue,
initialValue,
defaultValue,
].find((v) => v !== undefined);
})();
const transformedValue = valueTransformer
? valueTransformer(componentName, value)
: value;
return transformedValue instanceof Object
? Object.freeze(transformedValue)
: transformedValue;
};
/**
* Gets the values of the provided component names using the same logic as
* `getValue`.
* @param {string} componentNames component names to retrieve values for
* @returns an object with componentName:value pairs
*/
public getValues = (
componentNames?: (keyof FormComponents)[],
): FormComponents => {
const values = this.getComponentNames(componentNames).reduce(
(values: FormComponents, componentName: keyof FormComponents) => ({
...values,
[componentName]: this.getValue(componentName),
}),
{} as FormComponents,
);
const { valuesTransformer } = this.props;
return valuesTransformer ? valuesTransformer(values) : values;
};
//#endregion
//#region Public setters
/**
* Sets the component internally managed validatorData & updates the component
* to reflect its new state.
* @param {string} componentName name of the component which should be updated
* @param {object} validatorData the new validator data to be stored in Form state
* @returns a promise which is resolved once the react component has been re-rendered.
*/
public setValidatorData = async (
componentName: keyof FormComponents,
data: ValidatorData,
): Promise<void> => {
this.logCall('setValidatorData', { componentName, data });
// Don't set data if component is unknown
if (!(componentName in this.components)) {
return;
}
return this.updateComponent(componentName, {
pristine: {
$set: false,
},
validatorData: {
$set: data,
},
});
};
/**
* Sets the component internally managed state value & updates the component
* validatorData using the provided value. By default, the components pristine state
* will be set to `false` to indicate that the component has been modified.
* @param {string} componentName name of the component to set value for
* @param {any} value the new value to be stored in Form state
* @param {boolean} pristine the new pristine state when setting this value (default: false).
* @param {boolean} internal if true, the handle form change will not be executed
* @returns a promise which is resolved once the react component has been re-rendered.
*/
public setValue = async (
componentName: keyof FormComponents,
value: any,
pristine: boolean = false,
internal: boolean = false,
): Promise<void> => {
this.logCall('setValue', { componentName, value, pristine, internal });
// Don't set value if component is unknown
if (!(componentName in this.components)) {
return;
}
await this.updateComponent(componentName, {
pristine: {
$set: pristine,
},
value: {
$set: value,
},
validatorData: {
$set: this.executeValidator(componentName, value),
},
});
if (!internal) {
await this.handleFormChange(componentName, value);
}
return Promise.resolve();
};
/**
* Sets the components internally managed state values & updates their component
* validatorData using the provided values. By default, the components pristine state
* will be set to `false` to indicate that the components have been modified.
* @param {object} values the values to be saved in Form state: componentName:value map
* @returns a promise which is resolved once the react components have been re-rendered.
*/
public setValues = (
values: { [ComponentName in keyof FormComponents]: any },
pristine?: boolean,
internal?: boolean,
): Promise<void[]> => {
this.logCall('setValues', { values, pristine, internal });
return Promise.all(
Object.keys(values).map((componentName: string) =>
this.setValue(
componentName,
values[componentName],
pristine,
internal,
),
),
);
};
//#endregion
//#region Private helpers
private isRecursiveComponent = (componentName: keyof FormComponents) => {
const instance = this.getComponentInstance(componentName);
return instance && instance._isRecursive();
};
//#endregion
//#region Private component registration/unregistration
/**
* Registers a component with the form, allowing it to be managed.
* @param {string} componentName name of the component
* @param {object} componentRef react component reference to be monitored
* @returns void
*/
private registerComponent = (
componentName: keyof FormComponents,
componentRef: BoundComponent,
) => {
this.logCall('registerComponent', { componentName, componentRef });
// Return early if a ref has already been registered
if (
componentName in this.components &&
!!this.components[componentName].instance
) {
console.error(
`Failed to register component: "${componentName}", a component with this name already exists.`,
);
return;
}
// Update component state
this.components = update(this.components, {
[componentName]: {
name: {
$set: componentName,
},
instance: {
$set: componentRef,
},
},
});
// Force validation if component is not initially pristine to populate validationData
if (!componentRef.isPristine()) {
this.validate(componentName);
}
};
/**
* Unregisters a component with the form, so it will no longer be managed
* @param {string} componentName name of the component
* @returns void
*/
private unregisterComponent = (componentName: keyof FormComponents) => {
this.logCall('unregisterComponent', { componentName });
if (
!(componentName in this.components) ||
!this.components[componentName].instance
) {
console.error(
`Failed to unregister ref for "${componentName}", not registered.`,
);
return;
}
Iif (this.props.sticky) {
// Remove instance without destroying associated data
this.components = update(this.components, {
[componentName]: {
$unset: 'instance',
},
});
} else {
// Else, remove component entirely
this.components = update(this.components, {
$unset: componentName,
});
}
};
/**
* Registers a mirror with the form, allowing it to reflect a component.
* @param {string} componentName name of the component to mirror
* @param {object} mirrorRef react mirror reference to be registered
* @returns void
*/
private registerMirror = (
componentName: keyof FormComponents,
mirrorRef: Mirror,
): void => {
this.logCall('registerMirror', { componentName, mirrorRef });
if (componentName in this.mirrors) {
this.mirrors[componentName].push(mirrorRef);
} else {
this.mirrors[componentName] = [mirrorRef];
}
};
/**
* Unregisters a mirror with the form, so it will no longer reflect
* @param {string} componentName name of the component to mirror
* @param {object} mirrorRef react mirror reference to be unregistered
* @returns void
*/
private unregisterMirror = (
componentName: keyof FormComponents,
mirrorRef: Mirror,
): void => {
this.logCall('unregisterMirror', { componentName, mirrorRef });
Eif (componentName in this.mirrors) {
const index = this.mirrors[componentName].indexOf(mirrorRef);
Eif (index > -1) {
this.mirrors[componentName].splice(index, 1);
}
}
};
//#endregion
//#region Private event handlers
private handleFormChange = (
componentName: keyof FormComponents,
value: any,
) => {
this.logCall('handleFormChange', { componentName, value });
const { onChange } = this.props;
if (isCallable(onChange)) {
onChange(componentName, value);
}
};
private handleFormSubmit = (event?: any) => {
this.logCall('handleFormSubmit', { event });
if (event) {
event.preventDefault();
}
const isValid = this.isValid();
const values = this.getValues();
if (isValid) {
this.handleFormValidSubmit(values);
} else {
this.handleFormInvalidSubmit(values);
}
const { onSubmit } = this.props;
if (isCallable(onSubmit)) {
onSubmit(values);
}
return {
isValid,
values,
};
};
private handleFormValidSubmit = (values: FormComponents) => {
this.logCall('handleFormValidSubmit', { values });
const { onValidSubmit } = this.props;
if (isCallable(onValidSubmit)) {
onValidSubmit(values);
}
};
private handleFormInvalidSubmit = (values: FormComponents) => {
this.logCall('handleFormInvalidSubmit', { values });
const { onInvalidSubmit } = this.props;
this.validate();
if (isCallable(onInvalidSubmit)) {
onInvalidSubmit(values);
}
};
private handleComponentMount = async (
componentName: keyof FormComponents,
componentRef: BoundComponent,
) => {
this.logCall('handleComponentMount', { componentName, componentRef });
this.registerComponent(componentName, componentRef);
this.reflectComponentMirrors(componentName);
};
private handleComponentUnmount = async (
componentName: keyof FormComponents,
) => {
this.logCall('handleComponentUnmount', { componentName });
this.unregisterComponent(componentName);
this.reflectComponentMirrors(componentName);
};
private handleComponentUpdate = async (
componentName: keyof FormComponents,
) => {
this.logCall('handleComponentUpdate', { componentName });
// Cross-validate if necessary
await Promise.all(
this.getRelatedComponentNames(componentName).map(
(relatedComponentName: string) => {
return this.validate(relatedComponentName);
},
),
);
// Reflect all mirrors
this.reflectComponentMirrors(componentName);
const { onUpdate } = this.props;
if (isCallable(onUpdate)) {
onUpdate(componentName);
}
};
private handleComponentBlur = (
componentName: keyof FormComponents,
event: any,
) => {
this.logCall('handleComponentBlur', { componentName, event });
const value = this.getValue(componentName);
const { onBlur } = this.props;
Eif (isCallable(onBlur)) {
onBlur(componentName, value, event);
}
return event;
};
private handleComponentFocus = (
componentName: keyof FormComponents,
event: any,
) => {
this.logCall('handleComponentFocus', { componentName, event });
const value = this.getValue(componentName);
const { onFocus } = this.props;
Eif (isCallable(onFocus)) {
onFocus(componentName, value, event);
}
return event;
};
//#endregion
//#region Private helpers
/**
* Returns an array of mirror instances that are currently reflecting the specified component.
* @param {string} componentName name of the component
* @returns array of mirror instances
*/
private getComponentMirrors = (
componentName: keyof FormComponents,
): MirrorInstance[] => {
return this.mirrors[componentName] || [];
};
/** Helper function for retrieving an array of component names. This is used by
* functions which can iterate over a single, multiple or all components within
* the form.
* * If a singular component name is provided, it will be returned as an array.
* * If multiple component names are provided, they will be returned unchanged.
* * If no component names are provided, all component names will be returned.
* @param {string|string[]} componentName component name(s)
* @returns array of component names
*/
private getComponentNames = (
componentName?: keyof FormComponents | (keyof FormComponents)[],
): (keyof FormComponents)[] => {
// If no component name(s) was provided, return all component names
if (!componentName) {
return Object.keys(this.components);
}
// If explicit component names were provided, return them instead
Iif (Array.isArray(componentName)) {
return componentName;
}
// If a singular component name was provided, return it as an array
Eif (typeof componentName === 'string') {
return [componentName];
}
return [];
};
/**
* Gets the react component instance for the specified component
* @param {string} componentName name of the component
* @returns react component instance
*/
private getComponentInstance = (
componentName: keyof FormComponents,
): BoundComponent => {
return componentName in this.components
? (this.components[componentName].instance as any)
: undefined;
};
/**
* Gets the react component props for the specified component
* @param {string} componentName name of the component
* @returns react component props
*/
private getComponentProps = (componentName: keyof FormComponents) => {
const instance = this.getComponentInstance(componentName);
return instance ? instance.props : undefined;
};
/**
* Get an array of component names which should be updated when the
* specified component is updated..
* @param {string} componentName name of the component
* @returns array of component names
*/
private getComponentValidatorTriggers = (
componentName: keyof FormComponents,
): (keyof FormComponents)[] => {
const props = this.getComponentProps(componentName);
const validatorTrigger = props?.validatorTrigger ?? [];
return Array.isArray(validatorTrigger)
? validatorTrigger
: [validatorTrigger];
};
/**
* Recursively builds a dependency map for components that are part of the
* validator trigger tree.
* @param {string[]} componentNames array of component names to check
* @param {object} mappedNames while recurseing, a mappedNames object is kept
* to ensure that a component is not included twice and to ensure that
* components cannot trigger each other.
* @returns array of component names which are dependent on the specified
* component names.
*/
private getComponentDependencyMap = (
componentNames: (keyof FormComponents)[],
EmappedNames: FormComponents = {} as any,
): (keyof FormComponents)[] => {
// tslint:disable-next-line:no-parameter-reassignment
mappedNames = componentNames.reduce(
(names: any, name: string) => ({ ...names, [name]: true }),
mappedNames,
);
return componentNames.reduce(
(dependencyMap: any, componentName: keyof FormComponents) => {
const validatorTrigger =
this.getComponentValidatorTriggers(componentName);
const namesToMap = validatorTrigger.filter(
(n: string) => !(n in mappedNames),
);
// Only recurse if necessary
Iif (namesToMap.length > 0) {
return {
...dependencyMap,
...this.getComponentDependencyMap(
namesToMap,
mappedNames,
),
};
}
return dependencyMap;
},
mappedNames,
);
};
/**
* Returns an array of component names that should be validated when validating
* a specific component. Determined using the validator trigger tree.
* @param {string} componentName name of the component to check
* @returns array of componentNames
*/
private getRelatedComponentNames = (
componentName: keyof FormComponents,
): (keyof FormComponents)[] => {
const component = this.components[componentName];
Eif (component) {
return Object.keys(
this.getComponentDependencyMap(
this.getComponentValidatorTriggers(componentName),
),
).filter(
(dependencyName: string) => dependencyName !== componentName,
);
}
return [];
};
/**
* Updates the form component state using an update-immutable transform. Once
* the state has been updated, the react component will be updated to reflect
* the change.
* @param {string} componentName name of the component which should be updated
* @param {object} transform the `update-immutable` transform object
* @returns a promise which is resolved once the react component has been re-rendered.
*/
private updateComponent = (
componentName: keyof FormComponents,
componentTransform: UpdateTransform,
): Promise<void> => {
this.logCall('updateComponent', { componentName, componentTransform });
Iif (!(componentName in this.components)) {
return;
}
this.components = update(this.components, {
[componentName]: componentTransform,
});
const component = this.components[componentName];
Eif (component && component.instance) {
return component.instance._update(component);
}
};
/**
* Update all the mirrors which are reflecting the specified component
* @param {string} componentName name of the component which should be reflected
* @returns a promise which is resolved once all the mirrors have been re-rendered
*/
private reflectComponentMirrors = (
componentName: keyof FormComponents,
): Promise<void[]> => {
this.logCall('reflectComponentMirrors', { componentName });
return Promise.all(
this.getComponentMirrors(componentName).map(
(mirror: MirrorInstance) => mirror.reflect(),
),
);
};
/**
* Executes validator for the specified component. If no custom value is provided,
* the current value will be retrieved from the form component.
* @param {string} componentName name of the component
* @param {any} value (optional) custom value to be used when validating
* @returns validator data: context, message
*/
private executeValidator = (
componentName: keyof FormComponents,
value: any = this.getValue(componentName),
): ValidatorData => {
this.logCall('executeValidator', { componentName, value });
const props = this.getComponentProps(componentName);
return validate(
componentName as string,
{
...this.getValues(),
...(value !== undefined
? {
[componentName]: value,
}
: {}),
},
{
required: props && props.required,
...((props && props.validatorRules) || {}),
},
(props && props.validatorMessages) || {},
);
};
//#endregion
logCall = (
functionName: string,
args?: {
[argName: string]: any;
},
) => {
// Return early if we're not debugging
Eif (!this.props.debug) {
return;
}
const logPrefix = this.props.virtual
? `🟨 VirtualForm.${functionName}`
: `🟥 ParentForm.${functionName}`;
if (args) {
console.debug(`${logPrefix}:`, args);
} else {
console.debug(logPrefix);
}
};
}
|