All files / src/components/bind bind.tsx

94.48% Statements 137/145
87.93% Branches 51/58
100% Functions 26/26
94.16% Lines 129/137

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 4664x 4x 4x 4x               4x 4x 4x 4x                                                                                                                                                       4x                                                 182x 5x                                           5x 179x 179x 179x 11x     11x   168x     5x 3x 3x 3x     5x 140x 140x 140x     5x 22x 22x 22x 22x   22x             22x                 22x 22x     319x 319x     319x 319x 319x 319x 319x 319x   319x     394x   394x 394x 394x 394x   394x                                           179x 2x 2x 2x 1x   1x             179x 2x 2x 2x 1x   1x               179x 2x 2x 2x 1x   1x                   179x 2x 2x 1x   1x               179x 568x 568x 1x       567x                               179x 407x 407x 1x   406x                             179x 427x 427x 1x   426x                     179x 2x 2x 2x 1x   1x                     179x 14x 14x 14x 1x   13x           179x 1x 1x 1x       1x   1x         179x 1x 1x 1x       1x   1x                   179x 416x 416x                 416x         275x     416x     179x 136x 136x 136x       179x 1556x       179x           823x 823x                       5x   5x    
import * as React from 'react';
import { shallowEqual } from 'shallow-equal-object';
import * as deepEqual from 'fast-deep-equal';
import { omit, pick } from 'lodash';
 
import {
    ValidatorData,
    ValidatorRules,
    ValidatorMessageGenerator,
    Omit,
} from '../../types';
import { FormContext, FormApi, FormComponentState } from '../Form';
import { OutsideFormError } from '../../errors';
import { isCallable } from '../../utils';
const hoistNonReactStatics = require('hoist-non-react-statics');
 
export interface BoundComponentCommonProps {
    /** Unique form component identifier */
    name: string;
 
    /** Whether or not a value is required */
    required?: boolean;
 
    /** Whether or not the value has been modified */
    pristine?: boolean;
 
    /** Data which reflects the current validator state for the component. */
    validatorData?: ValidatorData;
 
    /** Current form component value */
    value?: any;
 
    /** Should be called when component has been blurred */
    onBlur?: (event: any) => void;
 
    /** Should be called when component has been focused */
    onFocus?: (event: any) => void;
}
 
export interface BoundComponentInjectedProps {
    /** Should be called when component value has changed */
    setValue?: BoundComponent['setValue'];
}
 
/** Props used by the HOC only. They are not passed to the wrapped component. */
export interface BoundComponentHOCProps {
    /** Validation rules which should be applied to the component */
    validatorRules?: ValidatorRules;
 
    /**  Custom validator messages for specific validator rules */
    validatorMessages?: {
        [ruleKey: string]: string | ValidatorMessageGenerator;
    };
 
    /** Triggers validator to execute on the specified component names when this component is modified */
    validatorTrigger?: string | string[];
 
    /** Default value to be applied if the component does not have a managed, state or initial value */
    defaultValue?: any;
}
 
export type BoundComponentProps = BoundComponentInjectedProps &
    BoundComponentCommonProps &
    BoundComponentHOCProps;
 
/**
 * Derived form component state from the nearest Form ancestor. This state data is
 * used instead of `this.state` & `this.setState` to avoid unnecessary renders and
 * duplicate component state, as the Form should always be the source of truth.
 */
export interface BoundComponentDerivedState {
    pristine?: boolean;
    validatorData?: ValidatorData;
    value?: any;
}
 
export interface BoundComponent extends React.Component<BoundComponentProps> {
    clear: () => Promise<void>;
    reset: () => Promise<void>;
    validate: () => Promise<void>;
    isValid: () => boolean;
    isPristine: () => boolean;
    getValidatorData: () => ValidatorData;
    getValue: () => any;
    setValidatorData: (data: ValidatorData) => Promise<void>;
    setValue: (value: any, pristine?: boolean) => Promise<void>;
    _update: (state: FormComponentState) => Promise<void>;
    _isRecursive: () => boolean;
}
 
export function bind<
    WrappedComponentProps extends BoundComponentProps,
    WrappedComponentStatics = {}
>(
    WrappedComponent: React.ComponentClass<WrappedComponentProps>,
): WrappedComponentStatics & {
    /**
     * Use explicit type for React.Component ref to allow consumers to pass a
     * React.RefObject<BoundComponentInstance>` to ref prop of their connected
     * component. Without explicitly typing this, the inferred type will be wrong.
     *
     * The custom ref prop is injected here instead of in the `ComponentProps`
     * interface so that consumers are able to provide a RefObject, but they're
     * not able to use it in their wrapped component.
     */
    new (props: WrappedComponentProps): Omit<
        React.Component<WrappedComponentProps>,
        'props'
    > & {
        props: WrappedComponentProps & {
            ref?: React.RefObject<BoundComponent>;
            unboundRef?: React.RefObject<any>;
        };
    };
} {
    class BoundComponent
        extends React.Component<
            WrappedComponentProps & {
                unboundRef?: React.RefObject<
                    React.ComponentClass<WrappedComponentProps>
                >;
            }
        >
        implements BoundComponent {
        //#region Private variables
        // tslint:disable:variable-name
        /**
         * Reference to the nearest Form ancestor provided via the context API
         */
        _formApi: FormApi;
 
        /**
         * Cached output from the most recent `this._getState()` call.
         */
        _state?: BoundComponentDerivedState;
        // tslint:enable:variable-name
        //#endregion
 
        public componentDidMount() {
            this.logCall('componentDidMount');
            const { name } = this.props;
            if (!this._formApi) {
                console.error(
                    `Bound "${name}" form component must be a descendant of a <Form/>.`,
                );
                return;
            }
            this._formApi.onComponentMount(name, this as any);
        }
 
        public componentWillUnmount() {
            this.logCall('componentWillUnmount');
            const { name } = this.props;
            return this._formApi && this._formApi.onComponentUnmount(name);
        }
 
        public componentDidUpdate() {
            this.logCall('componentDidUpdate');
            const { name } = this.props;
            return this._formApi && this._formApi.onComponentUpdate(name);
        }
 
        public shouldComponentUpdate(nextProps: WrappedComponentProps) {
            this.logCall('shouldComponentUpdate');
            const prevProps = this.props;
            const prevState = this._state;
            const nextState = this._getState();
 
            const validatorObjectKeys: (keyof WrappedComponentProps)[] = [
                'validatorData',
                'validatorRules',
                'validatorMessages',
            ];
 
            const propsChanged =
                !shallowEqual(
                    omit(prevProps, validatorObjectKeys),
                    omit(nextProps, validatorObjectKeys),
                ) ||
                !deepEqual(
                    pick(prevProps, validatorObjectKeys),
                    pick(prevProps, validatorObjectKeys),
                );
 
            const stateChanged = prevState !== nextState;
            return propsChanged || stateChanged;
        }
 
        public render() {
            this.logCall('render');
            const {
                // Omit these
                validatorRules,
                validatorMessages,
                validatorTrigger,
                unboundRef,
                ...restProps
            } = this.props as any;
 
            return (
                <FormContext.Consumer>
                    {(api: FormApi) => {
                        this._formApi = api;
                        const {
                            value,
                            pristine,
                            validatorData,
                        } = this._getState();
 
                        return (
                            <WrappedComponent
                                {...restProps}
                                value={value}
                                pristine={pristine}
                                validatorData={validatorData}
                                setValue={this.setValue}
                                onBlur={this._handleBlur}
                                onFocus={this._handleFocus}
                                ref={unboundRef}
                            />
                        );
                    }}
                </FormContext.Consumer>
            );
        }
 
        //#region Public commands
        /**
         * Clears the scomponent by setting its value to null.
         * @returns a promise which is resolved once the react component has been re-rendered
         */
        clear = () => {
            this.logCall('clear');
            const { name } = this.props;
            if (!this._formApi) {
                throw new OutsideFormError(`clear "${name}"`);
            }
            return this._formApi.clear(name);
        };
 
        /**
         * Resets the component by unsetting its value, validator and pristine state.
         * @returns a promise which is resolved once the react component has been re-rendered
         */
        reset = () => {
            this.logCall('reset');
            const { name } = this.props;
            if (!this._formApi) {
                throw new OutsideFormError(`reset "${name}"`);
            }
            return this._formApi.reset(name);
        };
 
        /**
         * Validates the component by executing the validator and updating the component
         * to reflect its new validator state. If no component names are provided,
         * @returns a promise which is resolved once the react component has been re-rendered.
         */
        validate = () => {
            this.logCall('validate');
            const { name } = this.props;
            if (!this._formApi) {
                throw new OutsideFormError(`validate "${name}"`);
            }
            return this._formApi.validate(name);
        };
        //#endregion
 
        //#region Public evaluators
        /**
         * Determines if the component is valid by executing the validator using the
         * components current value.
         * @returns a boolean flag to indicate whether the component is valid
         */
        isValid = () => {
            const { name } = this.props;
            if (!this._formApi) {
                throw new OutsideFormError(`determine if "${name}" is valid`);
            }
            return this._formApi.isValid(name);
        };
 
        /**
         * Determines if the component is pristine - the component has not been modified
         * by the user or by programatically calling setValue.
         * @returns a boolean flag to indicate whether the component is pristine
         */
        isPristine = () => {
            const { name } = this.props;
            if (!this._formApi) {
                throw new OutsideFormError(
                    `determine if "${name}" is pristine`,
                );
            }
            return this._formApi.isPristine(name);
        };
        //#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.
         *
         * @returns component validator data
         */
        getValidatorData = () => {
            const { name } = this.props;
            if (!this._formApi) {
                throw new OutsideFormError(`get validator data for "${name}"`);
            }
            return this._formApi.getValidatorData(name, this.props);
        };
 
        /**
         * Returns the value of the component. There are four ways a component value
         * can be provied (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
         *
         * @returns component value
         */
        getValue = () => {
            const { name } = this.props;
            if (!this._formApi) {
                throw new OutsideFormError(`get value for "${name}"`);
            }
            return this._formApi.getValue(name, this.props);
        };
        //#endregion
 
        //#region Public setters
        /**
         * Sets the component internally managed validatorData & updates the component
         * to reflect its new state.
         * @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.
         */
        setValidatorData = async (data: ValidatorData): Promise<void> => {
            this.logCall('setValidatorData', { data });
            const { name } = this.props;
            if (!this._formApi) {
                throw new OutsideFormError(`set validator data for "${name}"`);
            }
            return this._formApi.setValidatorData(name, 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 {any} value the new value to be stored in Form state
         * @param {boolean} pristine the new pristine state when setting this value (default: false).
         * @returns a promise which is resolved once the react component has been re-rendered.
         */
        setValue = async (value: any, pristine?: boolean) => {
            this.logCall('setValue', { value, pristine });
            const { name } = this.props;
            if (!this._formApi) {
                throw new OutsideFormError(`set value for "${name}"`);
            }
            return this._formApi.setValue(name, value, pristine);
        };
        //#endregion
 
        //#region Private functions
        // tslint:disable:variable-name
        _handleBlur = (event?: any) => {
            this.logCall('_handleBlur', { event });
            const { name, onBlur } = this.props;
            Iif (!this._formApi) {
                throw new OutsideFormError(`handle blur for "${name}"`);
            }
 
            this._formApi.onComponentBlur(name, event);
 
            Iif (isCallable(onBlur)) {
                onBlur(event);
            }
        };
 
        _handleFocus = (event?: any) => {
            this.logCall('_handleFocus', { event });
            const { name, onFocus } = this.props;
            Iif (!this._formApi) {
                throw new OutsideFormError(`handle focus for "${name}"`);
            }
 
            this._formApi.onComponentFocus(name, event);
 
            Iif (isCallable(onFocus)) {
                onFocus(event);
            }
        };
 
        /**
         * Retrieves the components derived state from the nearest form Ancestor. The
         * output is cached in between calls as `this._state`. If the object is shallow
         * equal to the previously calculated value, it will be returned instead.
         */
        _getState = (): BoundComponentDerivedState => {
            const prevState = this._state || {};
            const nextState = {
                pristine: this._formApi ? this.isPristine() : true,
                value: this._formApi ? this.getValue() : null,
                validatorData: this._formApi
                    ? this.getValidatorData()
                    : undefined,
            };
 
            // Cache next state if value has changed
            if (
                prevState.value !== nextState.value ||
                prevState.pristine !== nextState.pristine ||
                !shallowEqual(prevState.validatorData, nextState.validatorData)
            ) {
                this._state = nextState;
            }
 
            return this._state;
        };
 
        _update = (state: BoundComponentDerivedState): Promise<void> => {
            this.logCall('_update', { state });
            return new Promise((resolve) => {
                this.forceUpdate(resolve);
            });
        };
 
        _isRecursive = () => {
            return false;
        };
        // tslint:enable:variable-name
 
        private logCall = (
            functionName: string,
            args?: {
                [argName: string]: any;
            },
        ) => {
            Eif (!this._formApi || !this._formApi.debug) {
                return;
            }
 
            const logPrefix = `🟩 BoundComponent['${this.props.name}'].${functionName}`;
 
            if (args) {
                console.debug(`${logPrefix}:`, args);
            } else {
                console.debug(logPrefix);
            }
        };
        //#endregion
    }
 
    return hoistNonReactStatics(BoundComponent, WrappedComponent);
}