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

Illiar/feat/kyb validation poc (DRAFT) #2578

Open
wants to merge 5 commits into
base: dev
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 2 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
34 changes: 15 additions & 19 deletions apps/kyb-app/src/App.tsx
Original file line number Diff line number Diff line change
@@ -1,15 +1,9 @@
import { LoadingScreen } from '@/common/components/molecules/LoadingScreen';
import { APP_LANGUAGE_QUERY_KEY } from '@/common/consts/consts';
import { CustomerProviderFallback } from '@/components/molecules/CustomerProviderFallback';
import { AppLoadingContainer } from '@/components/organisms/AppLoadingContainer';
import { CustomerProvider } from '@/components/providers/CustomerProvider';
import { useCustomerQuery } from '@/hooks/useCustomerQuery';
import { useFlowContextQuery } from '@/hooks/useFlowContextQuery';
import { useUISchemasQuery } from '@/hooks/useUISchemasQuery';
import { router } from '@/router';
import { ValidatorPOC } from '@/ValidatorPOC';
import '@ballerine/ui/dist/style.css';
import * as Sentry from '@sentry/react';
import { RouterProvider } from 'react-router-dom';

export const App = () => {
// useLanguage uses react-router context
Expand All @@ -22,18 +16,20 @@ export const App = () => {
useFlowContextQuery(),
] as const;

return (
<Sentry.ErrorBoundary>
<AppLoadingContainer dependencies={dependancyQueries}>
<CustomerProvider
loadingPlaceholder={<LoadingScreen />}
fallback={CustomerProviderFallback}
>
<RouterProvider router={router} />
</CustomerProvider>
</AppLoadingContainer>
</Sentry.ErrorBoundary>
);
// return (
// <Sentry.ErrorBoundary>
// <AppLoadingContainer dependencies={dependancyQueries}>
// <CustomerProvider
// loadingPlaceholder={<LoadingScreen />}
// fallback={CustomerProviderFallback}
// >
// <RouterProvider router={router} />
// </CustomerProvider>
// </AppLoadingContainer>
// </Sentry.ErrorBoundary>
// );

return <ValidatorPOC />;
};

(window as any).toggleDevmode = () => {
Expand Down
103 changes: 103 additions & 0 deletions apps/kyb-app/src/ValidatorPOC.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,103 @@
//@ts-nocheck

import { Validator } from '@/components/providers/Validator';
import { pocDefinition } from '@/poc-definition';
import { FieldList } from '@/poc/FieldList';
import { SubmitButton } from '@/poc/SubmitButton';
import { TextInput } from '@/poc/TextInput';

const context = {
items: [
{
subItems: [{}, { subsubItems: [] }],
},
{},
],
};

export const ValidatorPOC = () => {
return (
<Validator elements={pocDefinition} context={context}>
<form
onSubmit={e => {
e.preventDefault();
alert('submitted');
}}
>
<TextInput context={context} element={pocDefinition[0]!} stack={[]} />
<TextInput context={context} element={pocDefinition[1]!} stack={[]} />
<div className="pl-8">
<FieldList context={context} element={pocDefinition[2]!}>
<div className="flex flex-col">
<TextInput context={context} element={pocDefinition[2]!.children[0]!} stack={[0]} />
<TextInput context={context} element={pocDefinition[2]!.children[1]!} stack={[0]} />
</div>
<div className="flex flex-col">
<TextInput context={context} element={pocDefinition[2]!.children[0]!} stack={[1]} />
<TextInput context={context} element={pocDefinition[2]!.children[1]!} stack={[1]} />
</div>
<div className="pl-8">
<FieldList context={context} element={pocDefinition[2]!.children[2]!} stack={[0]}>
<div className="flex flex-col">
<TextInput
context={context}
element={pocDefinition[2]!.children[2]!.children[0]!}
stack={[0, 0]}
/>
<TextInput
context={context}
element={pocDefinition[2]!.children[2]!.children[1]!}
stack={[0, 0]}
/>
</div>
<div className="flex flex-col">
<TextInput
context={context}
element={pocDefinition[2]!.children[2]!.children[0]!}
stack={[0, 1]}
/>
<TextInput
context={context}
element={pocDefinition[2]!.children[2]!.children[1]!}
stack={[0, 1]}
/>
</div>
<FieldList
context={context}
element={pocDefinition[2]!.children[2]!.children[2]!}
stack={[0, 1]}
>
<div className="flex flex-col">
<TextInput
context={context}
element={pocDefinition[2]!.children[2]!.children[2]!.children[0]!}
stack={[0, 0]}
/>
<TextInput
context={context}
element={pocDefinition[2]!.children[2]!.children[2]!.children[1]!}
stack={[0, 0]}
/>
</div>
<div className="flex flex-col">
<TextInput
context={context}
element={pocDefinition[2]!.children[2]!.children[2]!.children[0]!}
stack={[0, 1]}
/>
<TextInput
context={context}
element={pocDefinition[2]!.children[2]!.children[2]!.children[1]!}
stack={[0, 1]}
/>
</div>
</FieldList>
</FieldList>
</div>
</FieldList>
</div>
<SubmitButton />
</form>
</Validator>
);
};
41 changes: 41 additions & 0 deletions apps/kyb-app/src/components/providers/Validator/Validator.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
import { useValidate } from '@/components/providers/Validator/hooks/useValidate';
import { UIElement } from '@/components/providers/Validator/hooks/useValidate/ui-element';
import { UIElementV2 } from '@/components/providers/Validator/types';
import React, { FunctionComponent, useCallback, useMemo, useState } from 'react';
import { TValidationErrors, validatorContext } from './validator.context';

const { Provider } = validatorContext;

export interface IValidatorProps {
children: React.ReactNode | React.ReactNode[];
context: unknown;
elements: UIElementV2[];
}

export const Validator: FunctionComponent<IValidatorProps> = ({ children, elements, context }) => {
const validate = useValidate({ elements, context });
const [validationErrors, setValiationErrors] = useState<TValidationErrors>({});

const onValidate = useCallback(() => {
const errors = validate();
const validationErrors = errors.reduce((acc, error) => {
const element = new UIElement(error.element, context, error.stack);
acc[element.getId()] = error.message;

return acc;
}, {} as TValidationErrors);

setValiationErrors(validationErrors);

console.log({ errors, validationErrors });

return Boolean(errors.length);
}, [validate]);

const ctx = useMemo(
() => ({ validate: onValidate, errors: validationErrors }),
[validationErrors, onValidate],
);

return <Provider value={ctx}>{children}</Provider>;
Comment on lines +15 to +40
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fix the typo in the state setter function name.

The state setter function setValiationErrors should be setValidationErrors.

-  const [validationErrors, setValiationErrors] = useState<TValidationErrors>({});
+  const [validationErrors, setValidationErrors] = useState<TValidationErrors>({});
Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
export const Validator: FunctionComponent<IValidatorProps> = ({ children, elements, context }) => {
const validate = useValidate({ elements, context });
const [validationErrors, setValiationErrors] = useState<TValidationErrors>({});
const onValidate = useCallback(() => {
const errors = validate();
const validationErrors = errors.reduce((acc, error) => {
const element = new UIElement(error.element, context, error.stack);
acc[element.getId()] = error.message;
return acc;
}, {} as TValidationErrors);
setValiationErrors(validationErrors);
console.log({ errors, validationErrors });
return Boolean(errors.length);
}, [validate]);
const ctx = useMemo(
() => ({ validate: onValidate, errors: validationErrors }),
[validationErrors, onValidate],
);
return <Provider value={ctx}>{children}</Provider>;
export const Validator: FunctionComponent<IValidatorProps> = ({ children, elements, context }) => {
const validate = useValidate({ elements, context });
const [validationErrors, setValidationErrors] = useState<TValidationErrors>({});
const onValidate = useCallback(() => {
const errors = validate();
const validationErrors = errors.reduce((acc, error) => {
const element = new UIElement(error.element, context, error.stack);
acc[element.getId()] = error.message;
return acc;
}, {} as TValidationErrors);
setValidationErrors(validationErrors);
console.log({ errors, validationErrors });
return Boolean(errors.length);
}, [validate]);
const ctx = useMemo(
() => ({ validate: onValidate, errors: validationErrors }),
[validationErrors, onValidate],
);
return <Provider value={ctx}>{children}</Provider>;

};
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export * from './useValidate';
Original file line number Diff line number Diff line change
@@ -0,0 +1,116 @@
import { UIElementV2 } from '@/components/providers/Validator/types';
import {
IMinLengthValueValidatorParams,
MinLengthValueValidator,
} from '@/components/providers/Validator/value-validators/min-length.value.validator';
import {
IRequiredValueValidatorParams,
RequiredValueValidator,
} from '@/components/providers/Validator/value-validators/required.value-validator';
import get from 'lodash/get';

export class UIElement {
constructor(readonly element: UIElementV2, readonly context: unknown, readonly stack: number[]) {}

getId() {
return this.formatId(this.element.id);
}

getOriginId() {
return this.element.id;
}

private formatId(id: string) {
return `${id}${this.stack.join('.')}`;
}

getValueDestination() {
return this.formatValueDestination(this.element.valueDestination);
}

private formatValueDestination(valueDestination: string) {
return this.formatValueAndApplyStackIndexes(valueDestination);
}

private formatValueAndApplyStackIndexes(value: string) {
this.stack.forEach((stackValue, index) => {
value = value.replace(`$${index}`, String(stackValue));
});

return value;
}

getValue() {
const valueDestination = this.getValueDestination();

return get(this.context, valueDestination);
}

getValidatorsParams() {
const validatorKeys = Object.keys(this.element.validation);

return validatorKeys.map(key => ({
validator: key,
params: this.getValidatorParams(key),
}));
}

private getValidatorParams(key: string) {
switch (key) {
case 'minLength':
return this.getMinLengthParams();
case 'required':
return this.getRequiredParams();
default:
throw new Error('Invalid key');
}
}

private getMinLengthParams(): IMinLengthValueValidatorParams {
const _params = this.element.validation.minLength;

if (MinLengthValueValidator.isMinLengthParams(_params)) {
if (Array.isArray(_params)) {
return {
minLength: _params[0],
message: _params[1],
};
}

const minLength = _params;

const params: IMinLengthValueValidatorParams = {
minLength,
message: `Minimum length is ${minLength}.`,
};

return params;
}

throw new Error('Invalid params');
}

private getRequiredParams(): IRequiredValueValidatorParams {
const _params = this.element.validation.required;

if (RequiredValueValidator.isRequiredParams(_params)) {
if (Array.isArray(_params)) {
return {
required: _params[0],
message: _params[1],
};
}

const isRequired = _params;

const params: IRequiredValueValidatorParams = {
required: isRequired,
message: `Value is required.`,
};

return params;
}

throw new Error('Invalid params');
}
}
Loading
Loading