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

feat(ValidationContextWrapper): add virtualized wrapper #3578

Open
wants to merge 4 commits into
base: next
Choose a base branch
from
Open
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
2 changes: 2 additions & 0 deletions packages/react-ui-validations/.storybook/preview.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import styled from 'styled-components';
import { HandThumbDownIcon } from '@skbkontur/icons/icons/HandThumbDownIcon';
import { HandThumbUpIcon } from '@skbkontur/icons/icons/HandThumbUpIcon';
import ThumbUpIcon from '@skbkontur/react-icons/ThumbUp';
import { FixedSizeList as List } from 'react-window';

import * as Validations from '../src/index';
import * as ReactUI from '../../react-ui/index';
Expand Down Expand Up @@ -100,6 +101,7 @@ addons.setConfig({
HandThumbUpIcon,
ThumbUpIcon,
SpaceFiller,
List,
},
decorators: [ThemeDecorator, FeatureFlagsDecorator],
} as LiveConfig,
Expand Down
40 changes: 40 additions & 0 deletions packages/react-ui-validations/docs/Pages_NEW/Api.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -155,3 +155,43 @@ type RenderErrorMessage =
### `data-tid?: string`
Позволяет задать кастомный `data-tid`, для доступа к содержимому ошибок.
## ValidationListWrapper
Обертка для виртуализированного списка, осуществляет поиск валидаций в "неотрендеренных" контролах.
### `children: React.Node`
Дочерний компонент должен быть ровно один. ValidationListWrapper контролирует его поведение путём передачи
prop-ов ref и data-tid. Для работы с компонентом используется
[React.cloneElement()](https://facebook.github.io/react/docs/react-api.html#cloneelement);
### `validationInfos: ?ValidationReader<any[]>`
Результат возвращаемый из функции createValidator передает валидации в ValidationListWrapper. Если на любом уровне, вложенных в объект значений есть невалидное
- список считается невалидным.
### `onValidation?: (index: number | null, validation: Nullable<Validation>) => void`
Колбек для получения индекса невалидной строки и сообщения о невалидности
### `level?: ValidationLevel`
См. [Документацию](https://ui.gitlab-pages.kontur.host/storybook-documentation/?path=/docs/react_ui_validations_displaying-validation-level--docs)
### `behaviour?: ValidationBehaviour`
См. [Документацию](https://ui.gitlab-pages.kontur.host/storybook-documentation/?path=/docs/react_ui_validations_displaying-validation-type--docs)
### `independent?: boolean`
См. [Документацию](https://ui.gitlab-pages.kontur.host/storybook-documentation/?path=/docs/react_ui_validations_validator-independent--docs)
### `scrollToElement?: (index: number) => void`
Колбек, принимающий индекс невалидного элемента для возможности прокрутки к невалидному неотрендеренному элементу
### `data-tid?: string`
Позволяет задать кастомный `data-tid`, для доступа к содержимому ошибок.
Original file line number Diff line number Diff line change
@@ -0,0 +1,119 @@
import { Meta, Story } from '@skbkontur/react-ui/typings/stories';
import React from 'react';
import { Button } from '@skbkontur/react-ui/components/Button';
import { FixedSizeList as List } from 'react-window';
import { Token } from '@skbkontur/react-ui';

import { createValidator, ValidationContainer, ValidationListWrapper, ValidationWrapper } from '../../../../src';

export default {
title: 'Examples/Virtualized List example',
parameters: { creevey: { skip: true } },
} as Meta;

interface Data {
title: string;
value: {
subtitle: string;
value: number;
};
}

export const VirtualizedListExample: Story = () => {
const containerRef = React.useRef<ValidationContainer>(null);
const listRef = React.useRef<List | null>(null);
const [firstInvalidRow, setFirstInvalidRow] = React.useState<number | null>(null);

const data: Data[] = new Array(100).fill(0).map((_, i) => ({
title: `title ${i}`,
value: { subtitle: `subtitle ${i}`, value: i },
}));
const values = {
array: data,
};

const validator = createValidator<{ array: Data[] }>((b) => {
b.prop(
(x) => x.array,
(b) => {
b.array(
(x) => x,
(b) => {
b.prop(
(x) => x.value,
(b) => {
b.prop(
(x) => x.subtitle,
(b) => {
b.invalid(() => true, 'invlid sub');
},
);
b.prop(
(x) => x.value,
(b) => {
b.invalid((x) => x > 40, 'invalid', 'immediate');
},
);
},
);
},
);
},
);
});

const validationRules = validator(values);
const [isValid, setIsValid] = React.useState(true);
const handleValidate = async () => {
const result = await containerRef.current?.validate();
setIsValid(!!result);
};

return (
<ValidationContainer ref={containerRef}>
<div style={{ display: 'flex', width: '400px', flexDirection: 'column' }}>
<div style={{ display: 'flex', width: '400px', flexDirection: 'column' }}>
{firstInvalidRow ? `first invalid row is ${firstInvalidRow}` : null}
<ValidationListWrapper
validationInfos={validationRules.getNode((x) => x.array)}
onValidation={(index) => setFirstInvalidRow(index)}
scrollToElement={(index) => {
listRef.current?.scrollToItem(index, 'center');
}}
behaviour="submit"
>
<List
height={400}
itemCount={data.length}
itemSize={30}
width={400}
ref={listRef}
itemData={data}
children={({ index, style, data }) => {
return (
<div style={{ ...style, display: 'flex', alignItems: 'center', gap: 4 }}>
<div>строка {data[index].value.value}</div>
<div>
{data[index].title}
<ValidationWrapper
validationInfo={validationRules
.getNode((x) => x.array)
.getNodeByIndex(index)
.getNode((x) => x.value.value)
.get()}
>
<Token>{data[index].value.subtitle}</Token>
</ValidationWrapper>
</div>
</div>
);
}}
/>
</ValidationListWrapper>
</div>
<Button onClick={handleValidate}>validate</Button>
<span>isValid {isValid.toString()}</span>
</div>
</ValidationContainer>
);
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import { Story } from '@storybook/blocks';
import * as DocsStories from './VirtualizedList.docs.stories.tsx';
import { Meta } from '../../../../.storybook/Meta';

<Meta of={DocsStories} />

# Валидация массива

В примере показана валидация с виртуализированным списком

### Пример

<Story of={DocsStories.VirtualizedListExample} />
4 changes: 3 additions & 1 deletion packages/react-ui-validations/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -75,10 +75,10 @@
"@skbkontur/storybook-addon-live-examples": "0.0.11",
"@storybook/addon-a11y": "7.6.18",
"@storybook/addon-controls": "7.6.18",
"@storybook/addon-docs": "7.6.18",
"@storybook/addon-essentials": "7.6.18",
"@storybook/addon-interactions": "^7.6.18",
"@storybook/addon-links": "7.6.18",
"@storybook/addon-docs": "7.6.18",
"@storybook/blocks": "7.6.18",
"@storybook/react": "7.6.18",
"@storybook/react-webpack5": "7.6.18",
Expand All @@ -91,6 +91,7 @@
"@types/react-dom": "18.3.0",
"@types/react-helmet": "^6.1.11",
"@types/react-syntax-highlighter": "^15.5.13",
"@types/react-window": "1.8.8",
"@types/styled-components": "^5.1.34",
"@types/warning": "^3.0.0",
"babel-loader": "^9.1.3",
Expand Down Expand Up @@ -118,6 +119,7 @@
"react-hot-loader": "^4.13.1",
"react-router-dom": "^6.23.1",
"react-syntax-highlighter": "15.5.0",
"react-window": "1.8.10",
"rimraf": "^5.0.7",
"rollup": "^4.18.0",
"rollup-plugin-typescript2": "^0.36.0",
Expand Down
57 changes: 45 additions & 12 deletions packages/react-ui-validations/src/ValidationContextWrapper.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { ValidationWrapperInternal } from './ValidationWrapperInternal';
import type { ScrollOffset, ValidateArgumentType } from './ValidationContainer';
import { isNullable } from './utils/isNullable';
import { FocusMode } from './FocusMode';
import { ValidationListWrapperInternal } from './ValidationListWrapperInternal';

export interface ValidationContextSettings {
scrollOffset: ScrollOffset;
Expand All @@ -20,16 +21,20 @@ export interface ValidationContextWrapperProps {

export interface ValidationContextType {
register: (wrapper: ValidationWrapperInternal) => void;
registerVirtual: (reader: ValidationListWrapperInternal) => void;
unregister: (wrapper: ValidationWrapperInternal) => void;
unregisterVirtual: (reader: ValidationListWrapperInternal) => void;
instanceProcessBlur: (wrapper: ValidationWrapperInternal) => void;
onValidationUpdated: (wrapper: ValidationWrapperInternal, isValid: boolean) => void;
onValidationUpdated: (wrapper: ValidationWrapperInternal | ValidationListWrapperInternal, isValid: boolean) => void;
getSettings: () => ValidationContextSettings;
isAnyWrapperInChangingMode: () => boolean;
}

export const ValidationContext = React.createContext<ValidationContextType>({
register: () => undefined,
registerVirtual: () => undefined,
unregister: () => undefined,
unregisterVirtual: () => undefined,
instanceProcessBlur: () => undefined,
onValidationUpdated: () => undefined,
getSettings: () => ({
Expand All @@ -43,6 +48,7 @@ ValidationContext.displayName = 'ValidationContext';

export class ValidationContextWrapper extends React.Component<ValidationContextWrapperProps> {
public childWrappers: ValidationWrapperInternal[] = [];
public virtualWrappers: ValidationListWrapperInternal[] = [];

public getSettings(): ValidationContextSettings {
let scrollOffset: ScrollOffset = {};
Expand All @@ -67,34 +73,58 @@ export class ValidationContextWrapper extends React.Component<ValidationContextW
this.childWrappers.push(wrapper);
}

public registerVirtual(reader: ValidationListWrapperInternal) {
this.virtualWrappers.push(reader);
}

public unregister(wrapper: ValidationWrapperInternal) {
this.childWrappers.splice(this.childWrappers.indexOf(wrapper), 1);
this.onValidationRemoved();
}

public unregisterVirtual(reader: ValidationListWrapperInternal) {
this.virtualWrappers.splice(this.virtualWrappers.indexOf(reader), 1);
this.onVirtualValidationRemoved();
}

public instanceProcessBlur(instance: ValidationWrapperInternal) {
for (const wrapper of this.childWrappers.filter((x) => x !== instance && !x.isIndependent())) {
wrapper.processBlur();
}
}

public onValidationUpdated(wrapper: ValidationWrapperInternal, isValid?: boolean) {
public onValidationUpdated(wrapper: ValidationWrapperInternal | ValidationListWrapperInternal, isValid?: boolean) {
const { onValidationUpdated } = this.props;
if (onValidationUpdated) {
const isValidResult = !this.childWrappers.find((x) => {
if (x === wrapper) {
return !isValid;
}
return x.hasError();
});
onValidationUpdated(isValidResult);
const isValidResult =
!this.childWrappers.find((x) => {
if (x === wrapper) {
return !isValid;
}
return x.hasError();
}) ||
this.virtualWrappers.find((x) => {
if (x === wrapper) {
return !isValid;
}
return x.hasError();
});
onValidationUpdated(!!isValidResult);
}
}

public isAnyWrapperInChangingMode(): boolean {
return this.childWrappers.some((x) => x.isChanging);
}

public onVirtualValidationRemoved() {
const { onValidationUpdated } = this.props;
if (onValidationUpdated) {
const isValidResult = !this.virtualWrappers.find((x) => x.hasError());
onValidationUpdated(isValidResult);
}
}

public onValidationRemoved() {
const { onValidationUpdated } = this.props;
if (onValidationUpdated) {
Expand All @@ -103,8 +133,8 @@ export class ValidationContextWrapper extends React.Component<ValidationContextW
}
}

public getChildWrappersSortedByPosition(): ValidationWrapperInternal[] {
const wrappersWithPosition = [...this.childWrappers].map((x) => ({
public getChildWrappersSortedByPosition(): Array<ValidationWrapperInternal | ValidationListWrapperInternal> {
const wrappersWithPosition = [...this.childWrappers, ...this.virtualWrappers].map((x) => ({
target: x,
position: x.getControlPosition(),
}));
Expand Down Expand Up @@ -132,7 +162,10 @@ export class ValidationContextWrapper extends React.Component<ValidationContextW
public async validate(withoutFocusOrValidationSettings: ValidateArgumentType): Promise<boolean> {
const focusMode = ValidationContextWrapper.getFocusMode(withoutFocusOrValidationSettings);

await Promise.all(this.childWrappers.map((x) => x.processSubmit()));
await Promise.all([
...this.childWrappers.map((x) => x.processSubmit()),
...this.virtualWrappers.map((x) => x.processSubmit()),
]);

const childrenWrappersSortedByPosition = this.getChildWrappersSortedByPosition();
const firstError = childrenWrappersSortedByPosition.find((x) => x.hasError());
Expand Down
Loading