### GlobalLoader Static Methods Example Source: https://github.com/skbkontur/retail-ui/blob/master/packages/react-ui/components/GlobalLoader/__docs__/GlobalLoader.mdx Demonstrates the usage of static methods to control the GlobalLoader's state: start, done, reject, and accept. ```jsx ``` -------------------------------- ### Input Validation Example Source: https://github.com/skbkontur/retail-ui/blob/master/packages/react-ui/components/Input/__docs__/Input.mdx An example showcasing how to implement input validation using the React UI Validations package. This snippet requires the validation package to be installed and configured. ```jsx ``` -------------------------------- ### Install Kontur UI Source: https://context7.com/skbkontur/retail-ui/llms.txt Install the Kontur UI library using npm or yarn. Ensure you have React and ReactDOM as peer dependencies. ```bash npm install @skbkontur/react-ui # or yarn add @skbkontur/react-ui ``` -------------------------------- ### Modal Mobile Appearance Example Source: https://github.com/skbkontur/retail-ui/blob/master/packages/react-ui/components/Modal/__docs__/Modal.mdx Demonstrates the mobile appearance of the Modal component using the `mobileAppearance` prop. This example shows how to configure the modal's layout on smaller viewports. ```jsx ``` -------------------------------- ### GlobalLoader Mount Example Source: https://github.com/skbkontur/retail-ui/blob/master/packages/react-ui/components/GlobalLoader/__docs__/GlobalLoader.mdx Shows how to control the GlobalLoader component using its props instead of static methods. ```jsx ``` -------------------------------- ### Autocomplete with Validation Example Source: https://github.com/skbkontur/retail-ui/blob/master/packages/react-ui/components/Autocomplete/__docs__/Autocomplete.mdx Demonstrates how to integrate the Autocomplete component with React UI Validations. Ensure you have the validation package installed and configured. ```jsx ``` -------------------------------- ### Install jscodeshift for Codemod Migrations Source: https://context7.com/skbkontur/retail-ui/llms.txt Install the jscodeshift CLI globally to run codemod scripts. This is the first step before applying automated migrations. ```bash # Install jscodeshift npm install -g jscodeshift ``` -------------------------------- ### Import Kebab Component Source: https://github.com/skbkontur/retail-ui/blob/master/packages/react-ui/components/Kebab/__docs__/Kebab.mdx Import the Kebab component from the '@skbkontur/react-ui' package. This is a basic setup step. ```jsx import { Kebab } from '@skbkontur/react-ui'; ``` -------------------------------- ### Select Component Validation Example Source: https://github.com/skbkontur/retail-ui/blob/master/packages/react-ui/components/Select/__docs__/Select.mdx Demonstrates how to implement validation for the Select component using the React UI Validations package. Ensure the React UI Validations package is installed and configured. ```tsx import * as SelectExamples from './SelectValidation.docs.stories.tsx'; ``` -------------------------------- ### GlobalLoader in Modal Example Source: https://github.com/skbkontur/retail-ui/blob/master/packages/react-ui/components/GlobalLoader/__docs__/GlobalLoader.mdx Illustrates how to use the GlobalLoader within a modal window, where it will cover the modal's overlay. ```jsx ``` -------------------------------- ### FileUploader Localization Interface and Examples Source: https://github.com/skbkontur/retail-ui/blob/master/packages/react-ui/components/FileUploader/__docs__/FileUploader.mdx Defines the structure for FileUploader localization and provides example implementations for Russian (ru_RU) and British English (en_GB). Use LocaleContext to override these defaults. ```typescript interface FileUploaderLocale { chooseFile: string; choosedFile: string; orDragHere: string; requestErrorText: string; errors: string[]; warnings: string[]; } const ru_RU = { chooseFile: 'Выберите файл', choosedFile: 'Выбран файл', orDragHere: 'или перетащите сюда', requestErrorText: 'Файл не удалось загрузить на сервер, повторите попытку позже', errors: ['ошибка', 'ошибки', 'ошибок'], warnings: ['предупреждение', 'предупреждения', 'предупреждений'], }; const en_GB = { chooseFile: 'Select a file', choosedFile: 'File selected', orDragHere: 'or drag here', requestErrorText: 'The file could not be uploaded to the server, please try again later', errors: ['error', 'errors', 'errors'], warnings: ['warning', 'warnings', 'warnings'], }; ``` -------------------------------- ### GlobalLoader Customize Color Example Source: https://github.com/skbkontur/retail-ui/blob/master/packages/react-ui/components/GlobalLoader/__docs__/GlobalLoader.mdx Demonstrates how to customize the GlobalLoader's appearance, such as changing the indicator color, using theme variables. ```jsx ``` -------------------------------- ### Tabs Component Setup Source: https://context7.com/skbkontur/retail-ui/llms.txt Shows how to implement a tabbed interface using the Tabs and Tab components. The `value` prop controls the active tab, and `onValueChange` handles tab switching. ```tsx import { Tabs } from '@skbkontur/react-ui/components/Tabs'; import React, { useState } from 'react'; const { Tab } = Tabs; function SettingsTabs() { const [tab, setTab] = useState('profile'); return ( <> Profile Security Notifications {tab === 'profile' &&
Profile settings…
} {tab === 'security' &&
Security settings…
} {tab === 'notifications' &&
Notifications settings…
} ); } ``` -------------------------------- ### Import Modal Component Source: https://github.com/skbkontur/retail-ui/blob/master/packages/react-ui/components/Modal/__docs__/Modal.mdx Import the Modal component from the react-ui library. This is a basic setup for using the component. ```jsx import { Modal } from '@skbkontur/react-ui'; ``` -------------------------------- ### ValidationContainer validate() Example Source: https://github.com/skbkontur/retail-ui/blob/master/packages/react-ui-validations/docs/Pages_NEW/Api.mdx This example shows how to validate the form and conditionally proceed with an action, like saving data, based on the validation result. It also triggers focus on invalid controls. ```jsx async handleSubmit() { const isValid = await this.refs.container.validate(); if (isValid) { await this.save(); } } render() { return ( // ... ); } ``` -------------------------------- ### Import Autocomplete Component Source: https://github.com/skbkontur/retail-ui/blob/master/packages/react-ui/components/Autocomplete/__docs__/Autocomplete.mdx Import the Autocomplete component from the react-ui package. This is a basic setup required before using the component. ```jsx import { Autocomplete } from '@skbkontur/react-ui'; ``` -------------------------------- ### Import Link Component Source: https://github.com/skbkontur/retail-ui/blob/master/packages/react-ui/components/Link/__docs__/Link.mdx Import the Link component from the react-ui library. This is a common setup step for using the component. ```jsx import { Link } from '@skbkontur/react-ui'; ``` -------------------------------- ### Import Paging Component Source: https://github.com/skbkontur/retail-ui/blob/master/packages/react-ui/components/Paging/__docs__/Paging.mdx Import the Paging component from the react-ui library. This is the basic setup required to use the component. ```jsx import { Paging } from '@skbkontur/react-ui'; ``` -------------------------------- ### Import Toggle Component Source: https://github.com/skbkontur/retail-ui/blob/master/packages/react-ui/components/Toggle/__docs__/Toggle.mdx Import the Toggle component from the react-ui library. This is a basic setup for using the component. ```jsx import { Toggle } from '@skbkontur/react-ui'; ``` -------------------------------- ### ComboBox with Validation Example Source: https://github.com/skbkontur/retail-ui/blob/master/packages/react-ui/components/ComboBox/__docs__/ComboBox.mdx Demonstrates how to integrate the ComboBox component with the React UI Validations package. Refer to the React UI Validations documentation for detailed configuration options. ```jsx ``` -------------------------------- ### Import RadioGroup Component Source: https://github.com/skbkontur/retail-ui/blob/master/packages/react-ui/components/RadioGroup/__docs__/RadioGroup.mdx Import the RadioGroup component from the react-ui package. This is a basic setup step for using the component. ```jsx import { RadioGroup } from '@skbkontur/react-ui'; ``` -------------------------------- ### TokenInput with Validation Source: https://github.com/skbkontur/retail-ui/blob/master/packages/react-ui/components/TokenInput/__docs__/TokenInput.mdx Example demonstrating complex validation for the TokenInput component using React UI Validations. This includes required field validation, checking for spaces within tokens, and custom token validation via `createValidator` and `renderToken`. ```jsx import { TokenInput } from '@skbkontur/react-ui'; import { createValidator } from '@skbkontur/react-ui-validations'; // ... other imports and setup const ExampleValidation = () => { // ... component logic return ( ); }; export default ExampleValidation; ``` -------------------------------- ### RadioGroup with Validation Example Source: https://github.com/skbkontur/retail-ui/blob/master/packages/react-ui/components/RadioGroup/__docs__/RadioGroup.mdx Demonstrates how to integrate RadioGroup with React UI Validations for form input validation. Refer to the React UI Validations documentation for detailed configuration options. ```jsx ``` -------------------------------- ### MaskedInput with Validation Source: https://github.com/skbkontur/retail-ui/blob/master/packages/react-ui/components/MaskedInput/__docs__/MaskedInput.mdx Example demonstrating how to use MaskedInput with validation from React UI Validations. Refer to the React UI Validations documentation for detailed configuration of validation types, levels, and error message formats. ```jsx ``` -------------------------------- ### ValidationContainer submit() Example Source: https://github.com/skbkontur/retail-ui/blob/master/packages/react-ui-validations/docs/Pages_NEW/Api.mdx Use this snippet to trigger validation and focus on invalid controls within the ValidationContainer. It's typically called when a form is submitted. ```jsx // ... ``` -------------------------------- ### Textarea Validation Example Source: https://github.com/skbkontur/retail-ui/blob/master/packages/react-ui/components/Textarea/__docs__/Textarea.mdx Demonstrates how to add validation to the Textarea component using React UI Validations. Refer to the React UI Validations documentation for details on configuring validation types, error message formats, and other behaviors. ```tsx import { Story } from '@storybook/blocks'; import * as TextareaExamples from './TextareaValidation.docs.stories.tsx'; ``` -------------------------------- ### Custom Theme Creation and Application Source: https://context7.com/skbkontur/retail-ui/llms.txt Illustrates how to create a custom theme by overriding base theme variables using `ThemeFactory.create` and apply it to a React subtree using `ThemeContext.Provider`. Global overrides are also possible with `ThemeFactory.overrideBaseTheme`. ```tsx import { ThemeContext } from '@skbkontur/react-ui/lib/theming/ThemeContext'; import { ThemeFactory } from '@skbkontur/react-ui/lib/theming/ThemeFactory'; import { Button } from '@skbkontur/react-ui/components/Button'; // Create a custom theme extending the default const myTheme = ThemeFactory.create({ btnAccentBg: '#0070F3', btnAccentHoverBg: '#005CC5', btnBorderRadius: '8px', fontSizeMedium: '15px', }); // Apply to a subtree function App() { return ( ); } // Or override globally before any renders (e.g. in app entry point) ThemeFactory.overrideBaseTheme(myTheme); ``` -------------------------------- ### Modal Dialog with Header, Body, and Footer Source: https://context7.com/skbkontur/retail-ui/llms.txt Shows how to implement a modal dialog using Modal.Header, Modal.Body, and Modal.Footer. Supports dismissal via ESC key or background click, and various display modes. ```tsx import { Modal } from '@skbkontur/react-ui/components/Modal'; import { Button } from '@skbkontur/react-ui/components/Button'; import React, { useState } from 'react'; function ConfirmDialog() { const [open, setOpen] = useState(false); return ( <> {open && ( setOpen(false)}> Confirm action Are you sure you want to delete this record? )} ); } ``` -------------------------------- ### Basic Button Usage in React Source: https://context7.com/skbkontur/retail-ui/llms.txt Demonstrates various styles, sizes, and states for the Button component. Use the `component` prop to render as a different HTML element. ```tsx import { Button } from '@skbkontur/react-ui/components/Button'; import { OkIcon } from '@skbkontur/icons'; // Primary action button // Destructive action with icon // Loading state // Disabled // Rendered as an anchor component="a" href="/home" use="text" size="small"> Go home // Arrow button ``` -------------------------------- ### ResponsiveLayout with Custom Media Queries Source: https://context7.com/skbkontur/retail-ui/llms.txt Configure ResponsiveLayout with custom media queries to define additional layout breakpoints. The `onLayoutChange` callback provides the current state of all defined breakpoints. ```tsx console.log({ isMobile, isTablet })} > {({ isMobile, isTablet }) => {isMobile ? 'mobile' : isTablet ? 'tablet' : 'desktop'}} ``` -------------------------------- ### Import Input Component Source: https://github.com/skbkontur/retail-ui/blob/master/packages/react-ui/components/Input/__docs__/Input.mdx Import the Input component from the react-ui library. This is a common first step when using the component. ```jsx import { Input } from '@skbkontur/react-ui'; ``` -------------------------------- ### Import CurrencyInput Source: https://github.com/skbkontur/retail-ui/blob/master/packages/react-ui/components/CurrencyInput/__docs__/CurrencyInput.mdx Import the CurrencyInput component from the react-ui package. ```jsx import { CurrencyInput } from '@skbkontur/react-ui'; ``` -------------------------------- ### Import CurrencyLabel Source: https://github.com/skbkontur/retail-ui/blob/master/packages/react-ui/components/CurrencyLabel/__docs__/CurrencyLabel.mdx Import the CurrencyLabel component from the react-ui library. ```jsx import { CurrencyLabel } from '@skbkontur/react-ui'; ``` -------------------------------- ### Input Component with Icons and States Source: https://context7.com/skbkontur/retail-ui/llms.txt Shows how to use the Input component with left/right icons, a clear button, placeholder, and error states. The `showClearIcon` prop controls the visibility of the clear button. ```tsx import { Input } from '@skbkontur/react-ui/components/Input'; import { SearchIcon } from '@skbkontur/icons'; import React, { useState } from 'react'; function SearchBox() { const [value, setValue] = useState(''); return ( } placeholder="Search..." size="medium" showClearIcon="auto" // shows ✕ on hover/focus when non-empty width={300} /> ); } // Error state // Password with toggle handled externally ``` -------------------------------- ### Async ComboBox with Custom Rendering Source: https://context7.com/skbkontur/retail-ui/llms.txt Demonstrates an autocomplete ComboBox that fetches items asynchronously. It supports custom rendering for items and values, and handles unexpected user input. ```tsx import { ComboBox } from '@skbkontur/react-ui/components/ComboBox'; import React, { useState } from 'react'; interface City { id: number; name: string } const fetchCities = async (query: string): Promise => { const res = await fetch(`/api/cities?q=${encodeURIComponent(query)}`); return res.json(); }; function CityPicker() { const [city, setCity] = useState(null); return ( value={city} getItems={fetchCities} onValueChange={setCity} onUnexpectedInput={() => null} // clear on unrecognized input renderItem={(c) => c.name} renderValue={(c) => c.name} valueToString={(c) => c.name} placeholder="Type a city name…" size="medium" drawArrow /> ); } ``` -------------------------------- ### ResponsiveLayout with Render-Prop API Source: https://context7.com/skbkontur/retail-ui/llms.txt Use ResponsiveLayout with a render-prop to conditionally render content based on screen size. It exposes an `isMobile` flag to its children. ```tsx import { ResponsiveLayout } from '@skbkontur/react-ui/components/ResponsiveLayout'; // Render-prop API function AdaptivePanel() { return ( {({ isMobile }) => (
{isMobile ? : }
)}
); } ``` -------------------------------- ### Import Dropdown Component Source: https://github.com/skbkontur/retail-ui/blob/master/packages/react-ui/components/Dropdown/__docs__/Dropdown.mdx Import the Dropdown component from the react-ui library. ```jsx import { Dropdown } from '@skbkontur/react-ui'; ``` -------------------------------- ### Import FxInput Component Source: https://github.com/skbkontur/retail-ui/blob/master/packages/react-ui/components/FxInput/__docs__/FxInput.mdx Import the FxInput component from the react-ui package. This is a prerequisite for using the component in your application. ```jsx import { FxInput } from '@skbkontur/react-ui'; ``` -------------------------------- ### Labeling Input Fields Source: https://github.com/skbkontur/retail-ui/blob/master/packages/react-ui/components/Input/__docs__/Input.mdx Demonstrates how to associate a label with an input field using `htmlFor` and `id` attributes. This is crucial for accessibility. ```html ``` -------------------------------- ### Tooltip with Hover, Click, and Manual Triggers Source: https://context7.com/skbkontur/retail-ui/llms.txt Illustrates Tooltip usage with various trigger modes including hover, click, and manual control. Supports custom positioning and content rendering. ```tsx import { Tooltip } from '@skbkontur/react-ui/components/Tooltip'; import { Button } from '@skbkontur/react-ui/components/Button'; // Hover tooltip 'This action cannot be undone'} trigger="hover" pos="top center"> // Click-triggered tooltip with close button Copied to clipboard!} trigger="click" pos="bottom left" closeButton onCloseRequest={() => console.log('closed')} > // Programmatic control const ref = React.createRef(); 'Hint text'} trigger="manual"> // Later: ref.current?.show(); ref.current?.hide(); ``` -------------------------------- ### Import TokenInput Component Source: https://github.com/skbkontur/retail-ui/blob/master/packages/react-ui/components/TokenInput/__docs__/TokenInput.mdx Import the TokenInput component from the react-ui library. ```jsx import { TokenInput } from '@skbkontur/react-ui'; ``` -------------------------------- ### Migrate react-ui 4.x to 5.0 using Codemod Source: https://context7.com/skbkontur/retail-ui/llms.txt Execute the all-transforms codemod for migrating from react-ui version 4.x to 5.0. This command should be run against your project's source directory. ```bash # Migrate from react-ui 4.x to 5.0 jscodeshift -t node_modules/@skbkontur/react-ui-codemod/react-ui-5.0/all-transforms.js src/ ``` -------------------------------- ### DatePicker Component Usage Source: https://context7.com/skbkontur/retail-ui/llms.txt Demonstrates how to use the DatePicker component with specific date bounds, holiday markers, and the 'Today' button. Ensure the date format is 'dd.mm.yyyy'. ```tsx import { DatePicker } from '@skbkontur/react-ui/components/DatePicker'; import React, { useState } from 'react'; function BirthDateField() { const [date, setDate] = useState(''); const isHoliday = ({ date, isWeekend }: { date: Date; isWeekend: boolean }) => isWeekend; return ( ); } ``` -------------------------------- ### Import Tab Component Source: https://github.com/skbkontur/retail-ui/blob/master/packages/react-ui/components/Tabs/__docs__/Tab.mdx Import the Tab component from the react-ui library. This is a common first step when using the component. ```jsx import { Tab } from '@skbkontur/react-ui'; ``` -------------------------------- ### Import Token Component Source: https://github.com/skbkontur/retail-ui/blob/master/packages/react-ui/components/Token/__docs__/Token.mdx Import the Token component from the react-ui library to use it in your application. ```jsx import { Token } from '@skbkontur/react-ui'; ``` -------------------------------- ### Import PasswordInput Source: https://github.com/skbkontur/retail-ui/blob/master/packages/react-ui/components/PasswordInput/__docs__/PasswordInput.mdx Import the PasswordInput component from the react-ui package. ```jsx import { PasswordInput } from '@skbkontur/react-ui'; ``` -------------------------------- ### Import Spinner Component Source: https://github.com/skbkontur/retail-ui/blob/master/packages/react-ui/components/Spinner/__docs__/Spinner.mdx Import the Spinner component from the react-ui library. ```jsx import { Spinner } from '@skbkontur/react-ui'; ``` -------------------------------- ### Spinner with Accessibility Features Source: https://github.com/skbkontur/retail-ui/blob/master/packages/react-ui/components/Spinner/__docs__/Spinner.mdx Demonstrates how to implement accessibility for the Spinner component using ARIA live regions. This ensures screen readers announce loading status changes. ```jsx const [active, setActive] = React.useState(false); <>
Загрузка {active ? ' началась' : ' закончилась'} {active && }
``` -------------------------------- ### Import MaskedInput Source: https://github.com/skbkontur/retail-ui/blob/master/packages/react-ui/components/MaskedInput/__docs__/MaskedInput.mdx Import the MaskedInput component from the react-ui package. ```jsx import { MaskedInput } from '@skbkontur/react-ui'; ``` -------------------------------- ### Import GlobalLoader Source: https://github.com/skbkontur/retail-ui/blob/master/packages/react-ui/components/GlobalLoader/__docs__/GlobalLoader.mdx Import the GlobalLoader component from the react-ui library. ```jsx import { GlobalLoader } from '@skbkontur/react-ui'; ``` -------------------------------- ### Import Button Component Source: https://github.com/skbkontur/retail-ui/blob/master/packages/react-ui/components/Button/__docs__/Button.mdx Import the Button component from the react-ui library. ```jsx import { Button } from '@skbkontur/react-ui'; ``` -------------------------------- ### FileUploader Component Configuration Source: https://context7.com/skbkontur/retail-ui/llms.txt Configures the FileUploader for multiple file uploads with specific accept types and a custom upload request handler. The `request` prop should be an async function that processes the uploaded files. ```tsx import { FileUploader } from '@skbkontur/react-ui/components/FileUploader'; import React, { useState } from 'react'; import type { FileUploaderAttachedFile } from '@skbkontur/react-ui/components/FileUploader'; function DocumentUpload() { const [files, setFiles] = useState([]); const handleUpload = async (files: FileUploaderAttachedFile[]) => { for (const f of files) { const formData = new FormData(); formData.append('file', f.originalFile); await fetch('/api/upload', { method: 'POST', body: formData }); } }; return ( ); } ``` -------------------------------- ### Imperative Toast Notifications Source: https://context7.com/skbkontur/retail-ui/llms.txt Demonstrates using the Toast component imperatively to display notifications. Supports different styles (default, error), action buttons, and configurable display durations. ```tsx import { Toast } from '@skbkontur/react-ui/components/Toast'; import { Button } from '@skbkontur/react-ui/components/Button'; import React, { useRef } from 'react'; function NotificationsDemo() { const toastRef = useRef(null); const showSuccess = () => { toastRef.current?.push('File saved successfully!', { showTime: 3000 }); }; const showError = () => { toastRef.current?.push('Upload failed', { use: 'error', action: { label: 'Retry', handler: () => console.log('retry') }, }); }; return ( <> ); } ``` -------------------------------- ### Migrate react-ui 5.x to 6.0 using Codemod Source: https://context7.com/skbkontur/retail-ui/llms.txt Apply the react-ui 6.0 codemod to automatically migrate Button component usage from `use="primary"` to `use="accent"`. Run this command against your source directory. ```bash # Migrate from react-ui 5.x to 6.0 (e.g., rename use="primary" → use="accent") jscodeshift -t node_modules/@skbkontur/react-ui-codemod/react-ui-6.0/Button.js src/ ``` -------------------------------- ### Import ComboBox Component Source: https://github.com/skbkontur/retail-ui/blob/master/packages/react-ui/components/ComboBox/__docs__/ComboBox.mdx Import the ComboBox component from the react-ui library. ```jsx import { ComboBox } from '@skbkontur/react-ui'; ``` -------------------------------- ### Input with aria-labeledby Source: https://github.com/skbkontur/retail-ui/blob/master/packages/react-ui/components/Input/__docs__/Input.mdx Illustrates using `aria-labeledby` to associate an input field with an external label element when direct wrapping is not possible. ```html ``` -------------------------------- ### Locale Context for Internationalization Source: https://context7.com/skbkontur/retail-ui/llms.txt Shows how to set the locale for Kontur UI components within a subtree using `LocaleContext.Provider`. Supports built-in language codes ('ru', 'en') and allows granular overrides for specific components. ```tsx import { LocaleContext } from '@skbkontur/react-ui/lib/locale/LocaleContext'; import { DatePicker } from '@skbkontur/react-ui/components/DatePicker'; import { Select } from '@skbkontur/react-ui/components/Select'; function EnglishSection() { return ( {/* DatePicker now shows English month names, EN date order, etc. */} {}} enableTodayLink /> {}} error disabled /> ``` -------------------------------- ### MaskedInput Usage Source: https://github.com/skbkontur/retail-ui/blob/master/packages/react-ui/components/MaskedInput/__docs__/MaskedInput.mdx Import and use the MaskedInput component from the react-ui library. ```APIDOC ## Import ```jsx import { MaskedInput } from '@skbkontur/react-ui'; ``` ## Description Use MaskedInput when you need to ensure a strict data format from the user, such as a phone number, card number, or standard identifiers. Avoid using it for free-form text input or complex scenarios with many exceptions. The component inherits some basic props from the Input component, such as size, width, and input icons. These are detailed in the PropsTable. For examples of basic prop usage, refer to the [Input component documentation](https://tech.skbkontur.ru/kontur-ui/?path=/docs/react-ui_input-data-input--docs). Some props from Input are excluded for MaskedInput as they are not applicable, and the list of possible values for the `type` prop is also reduced. ``` -------------------------------- ### ValidationContainer submit() Overloads Source: https://github.com/skbkontur/retail-ui/blob/master/packages/react-ui-validations/docs/Pages_NEW/Api.mdx Demonstrates the different ways to call the submit method, allowing control over focus behavior. ```typescript submit(withoutFocus?: boolean): Promise submit(validationSettings: ValidationSettings): Promise ``` -------------------------------- ### Import Tabs Component Source: https://github.com/skbkontur/retail-ui/blob/master/packages/react-ui/components/Tabs/__docs__/Tabs.mdx Import the Tabs component from the react-ui library. This is a prerequisite for using the component in your application. ```jsx import { Tabs } from '@skbkontur/react-ui'; ``` -------------------------------- ### Disabled Input with aria-disabled Source: https://github.com/skbkontur/retail-ui/blob/master/packages/react-ui/components/Input/__docs__/Input.mdx Demonstrates how to visually and interactively disable an input field while maintaining accessibility for screen readers using `aria-disabled`. ```html ``` -------------------------------- ### Form Validation with ValidationContainer and ValidationWrapper Source: https://context7.com/skbkontur/retail-ui/llms.txt Implement form validation using ValidationContainer for the form and ValidationWrapper for individual inputs. ValidationWrapper accepts a `validationInfo` object to display errors or warnings. ```tsx import { ValidationContainer } from '@skbkontur/react-ui-validations'; import { ValidationWrapper } from '@skbkontur/react-ui-validations'; import type { ValidationInfo } from '@skbkontur/react-ui-validations'; import { Input } from '@skbkontur/react-ui/components/Input'; import { Button } from '@skbkontur/react-ui/components/Button'; import React, { useRef, useState } from 'react'; function RegistrationForm() { const containerRef = useRef(null); const [name, setName] = useState(''); const [email, setEmail] = useState(''); const getNameValidation = (): ValidationInfo | null => { if (!name) return { message: 'Name is required', type: 'submit' }; if (name.length < 2) return { message: 'At least 2 characters', type: 'lostfocus' }; return null; }; const getEmailValidation = (): ValidationInfo | null => { if (!email) return { message: 'Email is required', type: 'submit' }; if (!email.includes('@')) return { message: 'Enter a valid email', type: 'lostfocus', level: 'warning' }; return null; }; const handleSubmit = async () => { const isValid = await containerRef.current?.validate(); if (isValid) { console.log('Form is valid, submitting…', { name, email }); } }; return ( ); } ``` -------------------------------- ### Input with aria-label Source: https://github.com/skbkontur/retail-ui/blob/master/packages/react-ui/components/Input/__docs__/Input.mdx Shows how to provide an accessible name for an input field when a visible label is not present, using the `aria-label` attribute. ```html ``` -------------------------------- ### ValidationWrapper tooltip() Helper Source: https://github.com/skbkontur/retail-ui/blob/master/packages/react-ui-validations/docs/Pages_NEW/Api.mdx Provides a helper function to render error messages as tooltips with customizable positions. ```typescript tooltip(pos: string): RenderErrorMessage ``` -------------------------------- ### ValidationWrapper renderMessage Customization Source: https://github.com/skbkontur/retail-ui/blob/master/packages/react-ui-validations/docs/Pages_NEW/Api.mdx Illustrates how to customize the error message display within a ValidationWrapper using the `tooltip` function for positioning. ```jsx // ... // ... ``` -------------------------------- ### Icon Button with Aria Label Source: https://github.com/skbkontur/retail-ui/blob/master/packages/react-ui/components/Button/__docs__/Button.mdx Use an icon button with an aria-label for accessibility. The aria-label should provide a concise description of the button's action, ideally provided by a designer. ```jsx import { Button } from '@skbkontur/react-ui'; import { PlusIcon16Regular } from '@skbkontur/icons/16/PlusIcon16Regular'; ``` -------------------------------- ### ValidationWrapper Source: https://github.com/skbkontur/retail-ui/blob/master/packages/react-ui-validations/docs/Pages_NEW/Api.mdx A wrapper component for individual form controls that manages validation-related properties and displays validation messages. ```APIDOC ## ValidationWrapper Обертка для контрола, осуществляет управление свойствами контрола, ответственными за валидацию. ### `children: React.Node` Дочерний компонент должен быть ровно один. ValidationWrapper контролирует его поведение путём передачи prop-ов, используя соглашения react-ui. Для отрисовки tooltip-а используется стандартный Tooltip. Для работы с компонентом используется [React.cloneElement()](https://facebook.github.io/react/docs/react-api.html#cloneelement); ### `validationInfo: ?ValidationInfo` где ```jsx static type ValidationInfo = { type?: 'immediate' | 'lostfocus' | 'submit'; message: string; }; ``` способ передать результат валидаций в ValidationWrapper. Если значение определено, контрол считается невалидным. Поле `type` используется для задания поведения валидации (значение по умолчанию: `lostfocus`). ### `renderMessage?: RenderErrorMessage` где ```jsx static type RenderErrorMessage = ( control: React.Node, hasError: boolean, validation: ?Validation ) => React.Node; ``` Способ кастомизации отображения сообщения об ошибке (не путать с [подсветкой контрола](https://guides.kontur.ru/principles/validation/#13)). Для задания определённых в Контур.Гайдах способа отображения ошибок используйте функции `tooltip` и `text` (значение по умолчанию: `tooltip('right middle')`). Например, ```jsx static // ... // ... ``` ### `tooltip(pos: string): RenderErrorMessage` Возвращает функцию для рендеринга сообщения об ошибке в виде тултипа. Используется для передачи в renderMessage. Аргументы: - `pos`: строка передаваемая в соответствующий prop react-ui Tooltip-а. ### `text(pos: 'right' | 'bottom'): RenderErrorMessage` Возвращает функцию для рендеринга сообщения об ошибке в виде текстового блока рядом с контролом. Используется для передачи в renderMessage. Аргументы: - `pos`: управляет положением текста и принимает значения 'right' или 'bottom' для отображения сообщения справа или внизу соответственно. ### `data-tid?: string` Позволяет задать кастомный `data-tid`, для доступа к содержимому ошибок. ``` -------------------------------- ### ValidationWrapper text() Helper Source: https://github.com/skbkontur/retail-ui/blob/master/packages/react-ui-validations/docs/Pages_NEW/Api.mdx Offers a helper function to render error messages as text blocks next to the control, with options for positioning. ```typescript text(pos: 'right' | 'bottom'): RenderErrorMessage ``` -------------------------------- ### ValidationContainer Source: https://github.com/skbkontur/retail-ui/blob/master/packages/react-ui-validations/docs/Pages_NEW/Api.mdx A container for form elements that manages validation. It provides methods to submit the form for validation and to check its validity. ```APIDOC ## ValidationContainer Контейнер, внутри которого находятся валидируемые контролы. ### `submit(): Promise` При вызове этой функции загораются все невалидные контролы. Необходимо для реализации сценария [валидации при отправке формы](https://guides.kontur.ru/principles/validation/#07). ```jsx static // ... ``` Аргументы: ```jsx static submit(withoutFocus?: boolean): Promise submit(validationSettings: ValidationSettings): Promise ``` где ```jsx static interface ValidationSettings { focusMode: FocusMode; } enum FocusMode { Errors, ErrorsAndWarnings, None, } ``` - `withoutFocus`: отключает автофокус невалидных контролов. - `validationSettings.focusMode` - позволяет указать уровень валидации для автофокуса. Дефолтное значение - `FocusMode.Errors` ### `validate(): Promise` При вызове этой функции загораются все невалидные контролы так же как и при вызове функции `submit()`. Кроме того функция возвращает признак валидности формы. ```jsx static async handleSubmit() { const isValid = await this.refs.container.validate(); if (isValid) { await this.save(); } } render() { return ( // ... ); } ``` Аргументы аналогичны `submit()` - смотри выше. ### `children` Предполагается, что в дочерних узлах содержатся контролы, поведением которыми будет управлять контейнер. В контекст добавляется объект, в котором регистрируется дочерние контролы и реагируют на вызовы функций submit и validate. Так же через контекст осуществляется управление [поведением баллунов](https://guides.kontur.ru/principles/validation/#16). ### `onValidationUpdated?: (isValid: boolean) => void` Данный callback вызывается в случае изменения состояния валидности дочерних контролов. ``` -------------------------------- ### MaskedInput Validation Source: https://github.com/skbkontur/retail-ui/blob/master/packages/react-ui/components/MaskedInput/__docs__/MaskedInput.mdx Integrate validation for the MaskedInput component using the React UI Validations package. ```APIDOC ## Validation Validation can be added to the MaskedInput component using the [React UI Validations](https://tech.skbkontur.ru/kontur-ui/?path=/docs/react-ui-validations_api-reference) package. For details on configuring validation type, level, error message format, and other behavior parameters, see the documentation for the [React UI Validations](https://tech.skbkontur.ui/kontur-ui/?path=/docs/react-ui-validations_displaying-getting-started--docs) package. ``` -------------------------------- ### Basic Lostfocus Validation Source: https://github.com/skbkontur/retail-ui/blob/master/packages/react-ui-validations/docs/Pages_NEW/Validator/Independent/Independent.mdx This snippet shows a basic validation function that checks if a value is empty and returns a 'lostfocus' validation info if it is. This is the default behavior for dependent validations. ```jsx const validate = (value: string): Nullable => { if (!value) return { message: 'Не должно быть пустым', type: 'lostfocus' }; return null; }; ``` -------------------------------- ### Independent Object Validation Source: https://github.com/skbkontur/retail-ui/blob/master/packages/react-ui-validations/docs/Pages_NEW/Validator/Independent/Independent.mdx This snippet shows how to create an independent validation for an object's property using the `createValidator` helper. The 'lostfocus' validation is marked as independent. ```jsx const validateObject = createValidator((b) => { b.prop( (x) => x.value, (b) => { b.invalid((x) => !x, { message: 'Не должно быть пустым', type: 'lostfocus', independent: true, }); }, ); }); ``` -------------------------------- ### Independent Lostfocus Validation Source: https://github.com/skbkontur/retail-ui/blob/master/packages/react-ui-validations/docs/Pages_NEW/Validator/Independent/Independent.mdx This snippet demonstrates how to make a 'lostfocus' validation independent by setting the 'independent' property to true in the validation info. Independent validations only trigger for the field they are attached to. ```jsx const validate = (value: string): Nullable => { if (!value) return { message: 'Неправильный номер', type: 'lostfocus', independent: true }; return null; }; ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.