### Install Dependencies Source: https://github.com/cloud-ru-tech/uikit-product/blob/master/CONTRIBUTING.md Command to install all declared dependencies for the project using PNPM. This is a prerequisite for building and running the project. ```bash pnpm install ``` -------------------------------- ### Run Local Storybook Source: https://github.com/cloud-ru-tech/uikit-product/blob/master/CONTRIBUTING.md Start the local Storybook instance to check component functionality. Access it at http://localhost:6006/. ```bash storybook:ci ``` -------------------------------- ### Example Catalog Configuration Source: https://github.com/cloud-ru-tech/uikit-product/blob/master/packages/calculator/CALCULATOR_GUIDE.md Demonstrates how to configure a platform catalog with different categories, including popular items, free tier offerings, and storage products. It shows how to assign products to categories and include banners. ```typescript export const YOUR_PLATFORM_CATALOG: CatalogConfig['catalog'] = { [PLATFORM.YourPlatform]: [ { id: CATEGORY.Popular, label: 'Популярное', dataTestId: 'popular', visibleProducts: [ YOUR_PRODUCT.Product1, YOUR_PRODUCT.Product2, ], }, { id: CATEGORY.FreeTier, label: 'Free Tier', dataTestId: 'free-tier', visibleProducts: [ YOUR_PRODUCT.FreeProduct, ], banner: ( Free tier — это облачные ресурсы, за которые не надо платить. Подробнее в{' '} } /> ), }, { id: CATEGORY.Storage, label: 'Хранение', dataTestId: 'storage', visibleProducts: [ YOUR_PRODUCT.StorageProduct, ], }, ], }; ``` -------------------------------- ### Build Packages Source: https://github.com/cloud-ru-tech/uikit-product/blob/master/CONTRIBUTING.md Command to build all packages in the monorepository. This is required after installing dependencies or making changes to package code. ```bash pnpm build:packages ``` -------------------------------- ### Disk Configuration Utility Source: https://github.com/cloud-ru-tech/uikit-product/blob/master/packages/calculator/CALCULATOR_GUIDE.md Demonstrates how to use the `getDisk` utility function to configure disk properties, including space and specification. This utility simplifies the setup of disk-related controls within a form. ```typescript import { getDisk } from '../../../utils'; const systemDisk = getDisk({ space: { label: 'Объем диска', accessorKey: 'systemDisk.diskSpace', defaultValue: 10, uiProps: { min: 10, max: 4096, }, }, specification: { accessorKey: 'systemDisk.specification', defaultValue: 'SSD', }, }); ``` -------------------------------- ### UI Schema Example Source: https://github.com/cloud-ru-tech/uikit-product/blob/master/packages/calculator/CALCULATOR_GUIDE.md Illustrates how the `ui` array in `FormConfig` defines the layout of controls, allowing for single controls per row or multiple controls in a row. ```typescript ui: [ 'control1', // Один контрол на строку ['control2', 'control3'], // Два контрола в ряд ['control4'], // Один контрол (в массиве) 'alertControl', // Ещё один контрол ]; ``` -------------------------------- ### Accessor Key Examples Source: https://github.com/cloud-ru-tech/uikit-product/blob/master/packages/calculator/CALCULATOR_GUIDE.md Demonstrates the use of `accessorKey` to specify the path for storing form values, supporting simple fields, nested objects, array elements, and deep nesting. ```typescript accessorKey: 'simpleField'; // Простое поле accessorKey: 'nested.field'; // Вложенное поле accessorKey: 'array[0].field'; // Элемент массива accessorKey: 'evs.systemDisk.diskSpace'; // Глубокая вложенность ``` -------------------------------- ### Object Control for Grouping Controls Source: https://github.com/cloud-ru-tech/uikit-product/blob/master/packages/calculator/CALCULATOR_GUIDE.md Groups related controls within an object. This example shows how to group IP quantity controls and specifies that the object is initially hidden. ```typescript { type: CONTROL.Object, defaultValue: { ipQuantity: 1, bindingIpAddressesQuantity: 0, }, ui: [['ipQuantity', 'bindingIpAddressesQuantity']], controls: { ipQuantity: { type: CONTROL.Stepper, accessorKey: 'ipQuantity', // ... }, bindingIpAddressesQuantity: { type: CONTROL.Stepper, accessorKey: 'bindingIpAddressesQuantity', // ... }, }, visible: false, // Скрытый объект для служебных данных } ``` -------------------------------- ### Get Theme and Change Theme with useTheme (deprecated) Source: https://github.com/cloud-ru-tech/uikit-product/blob/master/packages/utils/README.md The useTheme hook provides the current theme and a function to change it. It requires a Config Provider to be mounted. Note: This hook is deprecated. ```typescript jsx import { useTheme } from '@cloud-ru/uikit-product-utils'; function Component() { const { theme, changeTheme } = useTheme(); } ``` -------------------------------- ### Get Brand and Change Brand with useBrand Source: https://github.com/cloud-ru-tech/uikit-product/blob/master/packages/utils/README.md The useBrand hook provides the current brand and a function to change it. It requires a Config Provider to be mounted. ```typescript jsx import { useBrand } from '@cloud-ru/uikit-product-utils'; function Component() { const { brand, changeBrand } = useBrand(); } ``` -------------------------------- ### Run Local Storybook (All Packages) Source: https://github.com/cloud-ru-tech/uikit-product/blob/master/CONTRIBUTING.md Command to launch a local Storybook instance that includes all packages. This is useful for viewing and testing components across the entire project. ```bash pnpm storybook:all ``` -------------------------------- ### Get Unique ID with useUniqueId Source: https://github.com/cloud-ru-tech/uikit-product/blob/master/packages/utils/README.md The useUniqueId hook returns a unique string identifier for use within a component. ```typescript jsx import { useUniqueId } from '@cloud-ru/uikit-product-utils'; function Component() { const id = useUniqueId(); } ``` -------------------------------- ### Build and Run Docker Image Source: https://github.com/cloud-ru-tech/uikit-product/blob/master/CONTRIBUTING.md Commands to build a Docker image for the UI kit and run it locally. Access the application via http://localhost:8080/. ```bash pnpm deps && pnpm build:packages ``` ```bash docker build -t uikit:0.0.1 . ``` ```bash docker run -t -p 8080:80 uikit:0.0.1 ``` -------------------------------- ### Get Language Code and Change Language with useLanguage Source: https://github.com/cloud-ru-tech/uikit-product/blob/master/packages/utils/README.md The useLanguage hook provides the current language code and a function to change it. It requires a Config Provider to be mounted. ```typescript jsx import { useLanguage } from '@cloud-ru/uikit-product-utils'; function Component() { const { languageCode, changeLanguage } = useLanguage(); } ``` -------------------------------- ### Run Local Storybook (Partial) Source: https://github.com/cloud-ru-tech/uikit-product/blob/master/CONTRIBUTING.md Command to launch a local Storybook instance with specific packages. This is useful for focusing on a subset of components. ```bash pnpm storybook:partial ``` -------------------------------- ### Import ConfigProvider for Styling Source: https://github.com/cloud-ru-tech/uikit-product/blob/master/README.md Import the ConfigProvider utility to wrap your application. The `theme` prop is deprecated, use `brand` for default branding. ```javascript import { ConfigProvider } from "@cloud-ru/uikit-product-utils"; ... ``` -------------------------------- ### Add New Package Source: https://github.com/cloud-ru-tech/uikit-product/blob/master/CONTRIBUTING.md Command to initiate the creation of a new package within the monorepository. Follow this with implementing the component or utility according to Conventional Commits. ```bash pnpm add-package ``` -------------------------------- ### Register Platform in Main Config Source: https://github.com/cloud-ru-tech/uikit-product/blob/master/packages/calculator/CALCULATOR_GUIDE.md Add a new platform to the main catalog configuration by importing its constants and spreading them into the respective arrays. ```typescript import { YOUR_PLATFORM, YOUR_PRODUCTS, YOUR_CATALOG } from './platforms/your-platform'; export const CATALOG_CONFIG: CatalogConfig = { platforms: [ EVOLUTION_PLATFORM, ADVANCED_PLATFORM, VM_WARE_PLATFORM, YOUR_PLATFORM, // Добавить новую платформу ], products: { ...EVOLUTION_PRODUCTS, ...ADVANCED_PRODUCTS, ...VM_WARE_PRODUCTS, ...YOUR_PRODUCTS, // Добавить продукты }, catalog: { ...EVOLUTION_CATALOG, ...ADVANCED_CATALOG, ...VM_WARE_CATALOG, ...YOUR_CATALOG, // Добавить каталог }, }; ``` -------------------------------- ### Register Product in CatalogConfig Source: https://github.com/cloud-ru-tech/uikit-product/blob/master/packages/calculator/CALCULATOR_GUIDE.md Define the product's properties, including its ID, platform, label, icon, and form configuration. This object is then added to the `products` section of the main `CATALOG_CONFIG`. ```typescript import { YourProductSVG } from '@cloud-ru/uikit-product-icons'; import { PLATFORM } from '../../../constants'; import { CatalogConfig } from '../../../types'; import { YOUR_PLATFORM_PRODUCT } from './constants'; import { YOUR_PRODUCT_FORM_CONFIG } from './product-config'; export const YOUR_PLATFORM_PRODUCTS: CatalogConfig['products'] = { [YOUR_PLATFORM_PRODUCT.YourProduct]: { id: YOUR_PLATFORM_PRODUCT.YourProduct, platform: PLATFORM.YourPlatform, label: 'Your Product Name', caption: 'Описание продукта', icon: YourProductSVG, dataTestId: 'yourProduct', formConfig: YOUR_PRODUCT_FORM_CONFIG, enableChangeProductQuantity: true, enableConnectToConsole: true, }, }; ``` -------------------------------- ### Project Package Structure Source: https://github.com/cloud-ru-tech/uikit-product/blob/master/CONTRIBUTING.md Illustrates the standard directory structure for packages within the monorepository. This includes the placement of source files, stories, and metadata files. ```text packages some-package src components Some index.ts Some.tsx styled.ts themes.ts constants.ts (опционально) index.ts stories Some.tsx package.json README.md CHANGELOG.md ``` -------------------------------- ### Product Form Configuration Source: https://github.com/cloud-ru-tech/uikit-product/blob/master/packages/calculator/CALCULATOR_GUIDE.md Define the form structure for a new product, including UI layout and control definitions. This configuration specifies how user input is collected for product settings. ```typescript import { CONTROL, FormConfig } from '../../../../components'; export const YOUR_PRODUCT_FORM_CONFIG: FormConfig = { ui: ['alertStart', 'productSetting', ['option1', 'option2']], controls: { alertStart: { type: CONTROL.Alert, uiProps: { appearance: 'info', outline: true, description: 'Информационное сообщение для пользователя', }, accessorKey: 'start', }, productSetting: { type: CONTROL.SelectSingle, decoratorProps: { label: 'Настройка продукта', labelTooltip: 'Подсказка о настройке', }, accessorKey: 'productSetting', defaultValue: 'value1', items: [ { value: 'value1', label: 'Вариант 1' }, { value: 'value2', label: 'Вариант 2' }, ], }, option1: { type: CONTROL.Stepper, decoratorProps: { label: 'Количество', }, accessorKey: 'option1', defaultValue: 1, uiProps: { min: 1, max: 100, postfix: 'шт', }, }, option2: { type: CONTROL.Toggle, defaultValue: false, accessorKey: 'option2', decoratorProps: { label: 'Дополнительная опция', }, }, }, }; ``` -------------------------------- ### Change Theme using useTheme Hook (Deprecated) Source: https://github.com/cloud-ru-tech/uikit-product/blob/master/README.md Import and use the `useTheme` hook for theme changes. Note that the `theme` prop in `ConfigProvider` is deprecated. Use `changeTheme` with the desired theme. ```javascript import { useTheme } from "@cloud-ru/uikit-product-utils"; const { changeTheme, Themes } = useTheme(); changeTheme(Themes.Purple); ``` -------------------------------- ### Add Product to Catalog Source: https://github.com/cloud-ru-tech/uikit-product/blob/master/packages/calculator/CALCULATOR_GUIDE.md Add the new product to a specific category within the platform's catalog. This makes the product visible and selectable in the UI. ```typescript import { CATEGORY, PLATFORM } from '../../../constants'; import { CatalogConfig } from '../../../types'; import { YOUR_PLATFORM_PRODUCT } from './constants'; export const YOUR_PLATFORM_CATALOG: CatalogConfig['catalog'] = { [PLATFORM.YourPlatform]: [ { id: CATEGORY.Popular, label: 'Популярное', dataTestId: 'popular', visibleProducts: [ YOUR_PLATFORM_PRODUCT.YourProduct, // ... другие продукты ], }, ], }; ``` -------------------------------- ### CONTROL.Stepper Configuration Source: https://github.com/cloud-ru-tech/uikit-product/blob/master/packages/calculator/CALCULATOR_GUIDE.md Configure a stepper control for numerical input with increment/decrement buttons. `uiProps` control min/max values, step, and postfix. ```typescript { type: CONTROL.Stepper, decoratorProps: { label: 'Количество', }, accessorKey: 'quantity', defaultValue: 1, uiProps: { min: 0, max: 100, step: 1, postfix: 'шт', // Постфикс (шт, ГБ, МБ и т.д.) showHint: true, // Показывать подсказку при наведении }, } ``` -------------------------------- ### CONTROL.ToggleCards Configuration Source: https://github.com/cloud-ru-tech/uikit-product/blob/master/packages/calculator/CALCULATOR_GUIDE.md Configure toggle cards for selecting a tariff type. `items` define the available card options with descriptions. ```typescript { type: CONTROL.ToggleCards, decoratorProps: { label: 'Тип тарифа', }, accessorKey: 'tariffType', defaultValue: 'basic', items: [ { value: 'basic', label: 'Базовый', description: 'Описание базового тарифа', }, { value: 'premium', label: 'Премиум', description: 'Описание премиум тарифа', }, ], } ``` -------------------------------- ### Add Product Constant Source: https://github.com/cloud-ru-tech/uikit-product/blob/master/packages/calculator/CALCULATOR_GUIDE.md Define a constant for the new product's identifier. This is used to reference the product throughout the application. ```typescript export const YOUR_PLATFORM_PRODUCT = { // ... существующие продукты YourProduct: 'yourProduct', } as const; ``` -------------------------------- ### useTheme Hook (deprecated) Source: https://github.com/cloud-ru-tech/uikit-product/blob/master/packages/utils/README.md Provides theme-related context, including the current theme and a function to change it. Requires the Config Provider to be mounted. This hook is deprecated. ```APIDOC ## useTheme Hook (deprecated) ### Description This hook provides access to the current theme and a function to change the theme. It must be used within a component wrapped by a Config Provider. Note: This hook is deprecated. ### Returns An object containing: - `theme` (string): The current theme identifier. - `changeTheme` (function): A function to change the current theme. ### Usage ```typescript jsx import { useTheme } from '@cloud-ru/uikit-product-utils'; function Component() { const { theme, changeTheme } = useTheme(); } ``` ``` -------------------------------- ### CONTROL.SelectSingle Configuration Source: https://github.com/cloud-ru-tech/uikit-product/blob/master/packages/calculator/CALCULATOR_GUIDE.md Configure a single-select dropdown control. `items` define the available options, and `uiProps` control features like searchability. ```typescript { type: CONTROL.SelectSingle, decoratorProps: { label: 'Выбор опции', labelTooltip: 'Подсказка', }, accessorKey: 'selectedOption', defaultValue: 'option1', items: [ { value: 'option1', label: 'Опция 1' }, { value: 'option2', label: 'Опция 2' }, ], uiProps: { searchable: true, // Поиск в списке showClearButton: true, // Кнопка очистки }, } ``` -------------------------------- ### CONTROL.SelectMultiple Configuration Source: https://github.com/cloud-ru-tech/uikit-product/blob/master/packages/calculator/CALCULATOR_GUIDE.md Configure a multiple-select control. `items` define the available options for selection. ```typescript { type: CONTROL.SelectMultiple, decoratorProps: { label: 'Выбор нескольких', }, accessorKey: 'selectedOptions', defaultValue: [], items: [ { value: 'opt1', label: 'Опция 1' }, { value: 'opt2', label: 'Опция 2' }, ], } ``` -------------------------------- ### Change Brand using useBrand Hook Source: https://github.com/cloud-ru-tech/uikit-product/blob/master/README.md Import and use the `useBrand` hook to manage brand changes. Pass a callback to `changeBrand` to update the application's brand. ```javascript import { useBrand } from "@cloud-ru/uikit-product-utils"; const { Brand, changeBrand } = useBrand(); changeBrand(Brand.MLSpace); ``` -------------------------------- ### CONTROL.Alert Configuration Source: https://github.com/cloud-ru-tech/uikit-product/blob/master/packages/calculator/CALCULATOR_GUIDE.md Configure an alert message control. `uiProps` define the appearance and content of the alert. ```typescript { type: CONTROL.Alert, uiProps: { appearance: 'info' | 'warning' | 'error', outline: true | false, description: ReactNode, // Текст сообщения }, accessorKey: 'alertKey', } ``` -------------------------------- ### Conventional Commits Explanation Source: https://github.com/cloud-ru-tech/uikit-product/blob/master/CONTRIBUTING.md Explains the structure and types of commits used in this project, following the Conventional Commits specification. This includes 'fix', 'feat', and 'BREAKING CHANGE' types, along with other recommended types. ```text The commit contains the following structural elements, to communicate intent to the consumers of your library: fix: a commit of the type fix patches a bug in your codebase (this correlates with PATCH in Semantic Versioning). feat: a commit of the type feat introduces a new feature to the codebase (this correlates with MINOR in Semantic Versioning). BREAKING CHANGE: a commit that has a footer BREAKING CHANGE:, or appends a ! after the type/scope, introduces a breaking API change (correlating with MAJOR in Semantic Versioning). A BREAKING CHANGE can be part of commits of any type. types other than fix: and feat: are allowed, for example @commitlint/config-conventional (based on the the Angular convention) recommends build:, chore:, ci:, docs:, style:, refactor:, perf:, test:, and others. footers other than BREAKING CHANGE: may be provided and follow a convention similar to git trailer format. ``` -------------------------------- ### Export Product Form Configuration Source: https://github.com/cloud-ru-tech/uikit-product/blob/master/packages/calculator/CALCULATOR_GUIDE.md Export the product form configuration from its module to make it available for import elsewhere. ```typescript export { YOUR_PRODUCT_FORM_CONFIG } from './YourProduct'; ``` -------------------------------- ### Создание констант продуктов для платформы Source: https://github.com/cloud-ru-tech/uikit-product/blob/master/packages/calculator/CALCULATOR_GUIDE.md Пример создания констант продуктов для новой платформы в файле `constants.ts`, использующий `as const` для строгой типизации. ```typescript export const YOUR_PLATFORM_PRODUCT = { YourProduct1: 'yourProduct1', YourProduct2: 'yourProduct2', } as const; ``` -------------------------------- ### Select Data Based on Theme Mode with useForThemeMode Source: https://github.com/cloud-ru-tech/uikit-product/blob/master/packages/utils/README.md The useForThemeMode hook allows you to select data, such as image sources, based on the current theme mode. It requires a Config Provider to be mounted. ```tsx const imageSrc = useForThemeMode({ light: 'assets/light-image.webp', dark: 'assets/dark-image.webp', }); {imgDescr} ``` -------------------------------- ### CONTROL.Toggle Configuration Source: https://github.com/cloud-ru-tech/uikit-product/blob/master/packages/calculator/CALCULATOR_GUIDE.md Configure a toggle switch (checkbox) control. `defaultValue` sets the initial state. ```typescript { type: CONTROL.Toggle, decoratorProps: { label: 'Включить опцию', }, accessorKey: 'enabled', defaultValue: false, } ``` -------------------------------- ### CONTROL.Carousel Configuration Source: https://github.com/cloud-ru-tech/uikit-product/blob/master/packages/calculator/CALCULATOR_GUIDE.md Configure a carousel control for selecting options with descriptions. `items` define the carousel cards. ```typescript { type: CONTROL.Carousel, decoratorProps: { label: 'Гарантированная доля vCPU', labelTooltip: 'Описание параметра', }, accessorKey: 'guaranteedPart', defaultValue: '10', items: [ { value: '10', label: '10% доля', description: 'Для тестирования', }, { value: '30', label: '30% доля', description: 'Для стандартной нагрузки', }, ], } ``` -------------------------------- ### Create Text Provider with createTextProvider Source: https://github.com/cloud-ru-tech/uikit-product/blob/master/packages/utils/README.md The createTextProvider function generates a text provider for managing localized text content. It requires a dictionary of texts and a package name. ```typescript jsx import { LanguageCodeType, createTextProvider } from '@cloud-ru/uikit-product-utils'; enum Texts { Hide = 'Hide', } const Dictionary: Partial>> = { [LanguageCodeType.ruRU]: { [Texts.Hide]: 'Скрыть', }, [LanguageCodeType.enGB]: { [Texts.Hide]: 'Hide', }, }; export const textProvider = createTextProvider(Dictionary, 'package-name'); ``` -------------------------------- ### Run Local Playwright Tests Source: https://github.com/cloud-ru-tech/uikit-product/blob/master/CONTRIBUTING.md Execute local Playwright tests to verify application behavior. This command opens a UI for test management and execution. ```bash test:local ``` -------------------------------- ### useForThemeMode Hook Source: https://github.com/cloud-ru-tech/uikit-product/blob/master/packages/utils/README.md A hook to pick data according to the current theme mode. Useful for selecting assets or configurations based on light or dark themes. ```APIDOC ## useForThemeMode Hook ### Description This hook returns a value based on the current theme mode. It's useful for selecting different assets or configurations for light and dark themes. ### Usage ```tsx const imageSrc = useForThemeMode({ light: 'assets/light-image.webp', dark: 'assets/dark-image.webp', }); {imgDescr} ``` ``` -------------------------------- ### Adapt to Theme/Brand Mode with ForThemeMode Source: https://github.com/cloud-ru-tech/uikit-product/blob/master/packages/utils/README.md Use ForThemeMode to render different JSX based on the current light or dark theme/brand mode. This component requires a Config Provider to be mounted. ```tsx } dark={} /> ``` -------------------------------- ### Evolution Cloud Server Form Configuration Source: https://github.com/cloud-ru-tech/uikit-product/blob/master/packages/calculator/CALCULATOR_GUIDE.md Defines the structure and controls for a complex cloud server form, including various input types like alerts, carousels, select, sliders, segmented controls, arrays, and toggles. It showcases dependency management between controls using `watchedControls` and `relateFn`. ```typescript export const EVOLUTION_CLOUD_SERVER_FORM_CONFIG: FormConfig = { ui: [ 'alertStart', 'guaranteedPart', ['os'], ['vCpuCoreCount', 'ramAmount'], ['systemDisk'], 'alertAdditional', ['additionalDisks'], 'networkIsNeeded', ], controls: { // Информационный алерт alertStart: { type: CONTROL.Alert, uiProps: { appearance: 'info', outline: true, description: 'Информация для пользователя', }, accessorKey: 'start', }, // Карусель выбора guaranteedPart: { decoratorProps: { label: 'Гарантированная доля vCPU', labelTooltip: 'Описание параметра', }, type: CONTROL.Carousel, accessorKey: 'guaranteedPart', defaultValue: '10', items: [ { value: '10', label: '10% доля', description: 'Для тестирования' }, { value: '30', label: '30% доля', description: 'Стандартная нагрузка' }, { value: '100', label: '100% доля', description: 'Высокая нагрузка' }, ], }, // Выбор операционной системы os: { type: CONTROL.SelectSingle, decoratorProps: { label: 'Операционная система', }, accessorKey: 'os', defaultValue: 'Ubuntu 22.04', items: [ { value: 'Ubuntu 22.04', label: 'Ubuntu 22.04' }, { value: 'CentOS 9', label: 'CentOS 9' }, ], }, // Слайдер с зависимостью vCpuCoreCount: { type: CONTROL.Slider, accessorKey: 'vCpuCoreCount', defaultValue: '1', items: [1, 2, 4, 8], decoratorProps: { label: 'Количество ядер vCPU', }, watchedControls: { guaranteedPart: 'guaranteedPart' }, relateFn: ({ guaranteedPart }) => { const items = guaranteedPartToVCpuMap?.[guaranteedPart]; if (items?.length > 0) { return { items: items }; } }, }, // Сегментированный контрол с двойной зависимостью ramAmount: { type: CONTROL.Segmented, decoratorProps: { label: 'Количество оперативной памяти (RAM)', }, defaultValue: '1', items: [ { value: '1', label: '1 ГБ' }, { value: '2', label: '2 ГБ' }, ], accessorKey: 'ramAmount', watchedControls: { guaranteedPart: 'guaranteedPart', vCpuCoreCount: 'vCpuCoreCount', }, relateFn: ({ guaranteedPart, vCpuCoreCount }) => { const items = guaranteedPartVCpuToRamMap?.[guaranteedPart]?.[vCpuCoreCount]; if (items?.length > 0) { return { items: generateRamItems(items), }; } }, }, // Объект с диском (используя утилиту) systemDisk: getDisk({ space: { label: 'Загрузочный диск', accessorKey: 'evs.systemDisk.diskSpace', defaultValue: 10, uiProps: { min: 10, max: 4096, }, }, specification: { accessorKey: 'evs.systemDisk.specification', defaultValue: 'SSD', uiProps: { disabled: true, }, }, }), // Массив дополнительных дисков additionalDisks: { type: CONTROL.Array, max: 7, accessorKey: 'evs.additionalDisks', defaultValue: [], addText: 'Добавить диск', ui: ['disk'], controls: { disk: getDisk({ space: { label: 'Дополнительный диск', accessorKey: 'diskSpace', defaultValue: 10, uiProps: { min: 10, max: 4096, }, }, specification: { accessorKey: 'specification', defaultValue: 'SSD', uiProps: { disabled: true, }, }, }), }, }, // Переключатель networkIsNeeded: { type: CONTROL.Toggle, defaultValue: false, accessorKey: 'networkIsNeeded', decoratorProps: { label: 'Аренда публичного IP', }, }, }, }; ``` -------------------------------- ### Fetch All Remote Branches and Prune Source: https://github.com/cloud-ru-tech/uikit-product/blob/master/CONTRIBUTING.md Fetches all remote branches and prunes any remote-tracking references that no longer exist on the remote. This ensures the local repository is up-to-date with the remote. ```bash git fetch --all --prune --prune-tags ``` -------------------------------- ### Generate Changelog Source: https://github.com/cloud-ru-tech/uikit-product/blob/master/CONTRIBUTING.md Command to generate a changelog for modified packages. This is typically used locally before releasing a new stable version to review commit contents and versions. ```bash pnpm changelog ``` -------------------------------- ### Структура директорий калькулятора продуктов Source: https://github.com/cloud-ru-tech/uikit-product/blob/master/packages/calculator/CALCULATOR_GUIDE.md Обзор структуры директорий пакета `@cloud-ru/uikit-product-calculator`, показывающий расположение UI компонентов, конфигураций, типов, сервисов, хуков и контекстов. ```tree packages/calculator/src/ ├── components/ # UI компоненты калькулятора │ ├── Calculator/ # Основной компонент калькулятора │ ├── Catalog/ # Компонент каталога │ ├── ProductPage/ # Страница продукта │ └── Controls/ # Контролы для форм │ ├── AlertControl/ │ ├── ArrayControl/ │ ├── CarouselControl/ │ ├── SelectControl/ │ ├── StepperControl/ │ └── ... ├── config/ # Конфигурации платформ и продуктов │ ├── config.tsx # Главный файл конфигурации │ ├── platforms/ # Конфигурации платформ │ │ ├── evolution/ │ │ ├── advanced/ │ │ └── vmware/ │ └── utils/ # Утилиты для конфигураций ├── types/ # TypeScript типы ├── services/ # Сервисы (API запросы, экспорт и т.д.) ├── hooks/ # React хуки └── contexts/ # React контексты ``` -------------------------------- ### Добавление константы платформы Source: https://github.com/cloud-ru-tech/uikit-product/blob/master/packages/calculator/CALCULATOR_GUIDE.md Пример добавления новой константы платформы в файл `src/constants.ts` для использования в калькуляторе продуктов. ```typescript export const PLATFORM = { Advanced: 'advanced', MlSpace: 'mlspace', VmWare: 'vmware', Evolution: 'evolution', Test: 'test', }; ``` -------------------------------- ### createTextProvider Source: https://github.com/cloud-ru-tech/uikit-product/blob/master/packages/utils/README.md A utility function to create a text provider for managing localized text content within the application. ```APIDOC ## createTextProvider ### Description Creates a text provider that manages localized text content based on a provided dictionary and package name. ### Parameters - `Dictionary` (Record>): An object mapping language codes to text keys and their string values. - `packageName` (string): The name of the package for which the text provider is created. ### Usage ```typescript jsx import { LanguageCodeType, createTextProvider } from '@cloud-ru/uikit-product-utils'; enum Texts { Hide = 'Hide', } const Dictionary: Partial>> = { [LanguageCodeType.ruRU]: { [Texts.Hide]: 'Скрыть', }, [LanguageCodeType.enGB]: { [Texts.Hide]: 'Hide', }, }; export const textProvider = createTextProvider(Dictionary, 'package-name'); ``` ``` -------------------------------- ### Public IP Form Configuration Source: https://github.com/cloud-ru-tech/uikit-product/blob/master/packages/calculator/CALCULATOR_GUIDE.md Defines the form configuration for managing public IP addresses, including direct and floating IP counts. It uses Stepper controls with specified min, max, and step values. ```typescript import { CONTROL, FormConfig } from '../../../../components'; export const EVOLUTION_PUBLIC_IP_FORM_CONFIG: FormConfig = { ui: [['directCount', 'floatingCount']], controls: { directCount: { type: CONTROL.Stepper, defaultValue: 0, accessorKey: 'directCount', decoratorProps: { label: 'Аренда прямого IP-адреса', labelTooltip: 'Описание прямого IP', }, uiProps: { min: 0, step: 1, max: 50, postfix: 'шт', }, }, floatingCount: { type: CONTROL.Stepper, accessorKey: 'floatingCount', defaultValue: 0, decoratorProps: { label: 'Аренда плавающего IP-адреса', labelTooltip: 'Описание плавающего IP', }, uiProps: { min: 0, step: 1, max: 50, postfix: 'шт', }, }, }, }; ``` -------------------------------- ### useBrand Hook Source: https://github.com/cloud-ru-tech/uikit-product/blob/master/packages/utils/README.md Provides brand-related context, including the current brand and a function to change it. Requires the Config Provider to be mounted. ```APIDOC ## useBrand Hook ### Description This hook provides access to the current brand and a function to change the brand. It must be used within a component wrapped by a Config Provider. ### Returns An object containing: - `brand` (string): The current brand identifier. - `changeBrand` (function): A function to change the current brand. ### Usage ```typescript jsx import { useBrand } from '@cloud-ru/uikit-product-utils'; function Component() { const { brand, changeBrand } = useBrand(); } ``` ``` -------------------------------- ### ForThemeMode Component Source: https://github.com/cloud-ru-tech/uikit-product/blob/master/packages/utils/README.md A tool component to adapt to current theme/brand modifications (light or dark). It renders different JSX based on the current mode. ```APIDOC ## ForThemeMode Component ### Description A component that conditionally renders its children based on the current theme mode (light or dark). ### Usage ```tsx } dark={} /> ``` ``` -------------------------------- ### CONTROL.Segmented Configuration Source: https://github.com/cloud-ru-tech/uikit-product/blob/master/packages/calculator/CALCULATOR_GUIDE.md Configure a segmented control (button group) for selection. `items` define the available segments. ```typescript { type: CONTROL.Segmented, decoratorProps: { label: 'Тип ресурса', }, accessorKey: 'resourceType', defaultValue: 'small', items: [ { value: 'small', label: 'Малый' }, { value: 'medium', label: 'Средний' }, { value: 'large', label: 'Большой' }, ], } ``` -------------------------------- ### useForceUpdateOnPageLoadedCompletely Hook Source: https://github.com/cloud-ru-tech/uikit-product/blob/master/packages/utils/README.md A hook that triggers a component re-render after the window's 'load' event has occurred. Useful for ensuring resources like CSS are fully loaded before rendering. ```APIDOC ## useForceUpdateOnPageLoadedCompletely Hook ### Description This hook ensures that a component re-renders only after the entire page, including all its resources, has been completely loaded. This can be helpful when the component's rendering depends on external assets like stylesheets. ### Usage ```typescript jsx import { useForceUpdateOnPageLoadedCompletely } from '@cloud-ru/uikit-product-utils'; function Component() { useForceUpdateOnPageLoadedCompletely(); } ``` ``` -------------------------------- ### Version Bump Source: https://github.com/cloud-ru-tech/uikit-product/blob/master/CONTRIBUTING.md Command to perform a version bump across packages using Lerna. This is part of the release process after generating the changelog and ensuring changes are accurate. ```bash lerna version --exact --message "Version bump" ``` -------------------------------- ### useLanguage Hook Source: https://github.com/cloud-ru-tech/uikit-product/blob/master/packages/utils/README.md Provides language-related context, including the current language code and a function to change it. Requires the Config Provider to be mounted. ```APIDOC ## useLanguage Hook ### Description This hook provides access to the current language code and a function to change the language. It must be used within a component wrapped by a Config Provider. ### Returns An object containing: - `languageCode` (string): The current language code. - `changeLanguage` (function): A function to change the current language. ### Usage ```typescript jsx import { useLanguage } from '@cloud-ru/uikit-product-utils'; function Component() { const { languageCode, changeLanguage } = useLanguage(); } ``` ``` -------------------------------- ### keyboardSelectHandler Source: https://github.com/cloud-ru-tech/uikit-product/blob/master/packages/utils/README.md A handler that allows keyboard events (Space or Enter) to trigger click-like behavior. ```APIDOC ## keyboardSelectHandler ### Description This utility function enhances accessibility by allowing keyboard interactions (Space or Enter key presses) to trigger the same action as a mouse click when an element is focused. ### Parameters - `callback` (function): The function to be called when the keyboard event is triggered. ### Usage ```typescript jsx import { keyboardSelectHandler } from '@cloud-ru/uikit-product-utils';
``` ``` -------------------------------- ### CONTROL.Slider Configuration Source: https://github.com/cloud-ru-tech/uikit-product/blob/master/packages/calculator/CALCULATOR_GUIDE.md Configure a slider control for selecting a value from a range. `items` define the available discrete values on the slider. ```typescript { type: CONTROL.Slider, decoratorProps: { label: 'Количество ядер vCPU', }, accessorKey: 'vCpuCoreCount', defaultValue: '1', items: [1, 2, 4, 8, 16], // Доступные значения } ``` -------------------------------- ### Создание конфигурации платформы Source: https://github.com/cloud-ru-tech/uikit-product/blob/master/packages/calculator/CALCULATOR_GUIDE.md Пример создания конфигурации платформы в файле `platform.tsx`, включая ID, иконку, название, описание и тип доступа. ```typescript import { YourPlatformSVG } from '@cloud-ru/uikit-product-icons'; import { PLATFORM } from '../../../constants'; import { Platform } from '../../../types'; export const YOUR_PLATFORM: Platform = { id: PLATFORM.YourPlatform, icon: , label: 'Your Platform Name', description: 'Описание платформы', access: 'public', // или 'request' или 'legal' dataTestId: 'calculator-catalog-platform-your-platform', ``` -------------------------------- ### FormConfig Structure Source: https://github.com/cloud-ru-tech/uikit-product/blob/master/packages/calculator/CALCULATOR_GUIDE.md Defines the overall structure of a form configuration, including UI layout, control definitions, default values, and dependency functions. ```typescript type FormConfig = { ui: FormRow[]; // Схема расположения контролов controls: Record; // Определения контролов defaultValue?: FormValues; // Начальные значения watchedControls?: Record; // Отслеживаемые поля relateFn?: (watchedValues: FormValues) => {...}; // Функция зависимостей visible?: boolean; // Видимость всей формы }; ``` -------------------------------- ### ButtonGigaMama Component Source: https://github.com/cloud-ru-tech/uikit-product/blob/master/packages/claudia/README.md The ButtonGigaMama component is a versatile button with options for links, icons, and loading states. It supports standard HTML attributes and event handlers. ```APIDOC ## ButtonGigaMama ### Description A button component with support for links, icons, loading states, and various event handlers. ### Props - **href** (string) - Ссылка - **target** (HTMLAttributeAnchorTarget) - Optional - HTML-аттрибут target. Defaults to "_blank". - **className** (string) - CSS-класс - **disabled** (boolean) - Флаг неактивности компонента - **icon** (ReactElement) - Иконка - **label** (string) - Текст кнопки - **loading** (boolean) - Флаг состояния загрузки - **onClick** (MouseEventHandler) - Колбек обработки клика - **onKeyDown** (KeyboardEventHandler) - Колбек обработки нажатия клавиши - **onFocus** (FocusEventHandler) - Колбек обработки фокуса - **onBlur** (FocusEventHandler) - Колбек обработки блюра - **type** ("submit" | "reset" | "button") - HTML-аттрибут type. Defaults to "button". - **tabIndex** (number) - HTML-аттрибут tab-index - **fullWidth** (boolean) - Сделать кнопку во всю ширину - **ref** (LegacyRef) - Allows getting a ref to the component instance. - **key** (Key) - ``` -------------------------------- ### HeroMain Component Props Source: https://github.com/cloud-ru-tech/uikit-product/blob/master/packages/site-hero/README.md The HeroMain component displays a primary hero section with various customization options for layout, content, and appearance. ```APIDOC ## HeroMain ### Props - **layoutType** (enum LayoutType: `"mobile"`, `"tablet"`, `"desktop"`, `"desktopSmall"`) - Required - Specifies the layout for different screen sizes. - **breadcrumbs** (Item[]) - Required - Breadcrumbs for the product. - **description** (string) - Required - Description of the product. - **title** (string) - Required - Title of the product. - **image** (string) - Optional - Link to an image. - **video** (ReactNode | VideoPlayerProps) - Optional - Video content. - **tags** (Pick[]) - Optional - Tags to display, defaults to []. - **platforms** (Platform[]) - Optional - Platforms associated with the product, defaults to []. - **handlePlatformClick** ((e: MouseEvent, platform: Platform) => void) - Optional - Handler for platform click events. - **backgroundColor** (enum HeroColor: `"neutral-background1-level"`, `"neutral-background"`, `"graphite-accent-default"`) - Optional - Background color, defaults to `neutral-background1-level`. - **buttons** ([Omit, Omit?, Omit<...>?]) - Optional - Array with settings for ButtonFilled. - **className** (string) - Optional - CSS class name. - **navbar** (Pick) - Optional - Navbar configuration. ``` -------------------------------- ### ToggleObject Control for On/Off Settings Source: https://github.com/cloud-ru-tech/uikit-product/blob/master/packages/calculator/CALCULATOR_GUIDE.md Implements an object control with a toggle switch for enabling/disabling additional settings. It defines the UI elements and their corresponding controls. ```typescript { type: CONTROL.ToggleObject, decoratorProps: { label: 'Дополнительные настройки', }, accessorKey: 'additionalSettings', defaultValue: false, // По умолчанию выключено ui: ['setting1', 'setting2'], controls: { setting1: { /* ... */ }, setting2: { /* ... */ }, }, } ``` -------------------------------- ### Array Control for Repeating Elements Source: https://github.com/cloud-ru-tech/uikit-product/blob/master/packages/calculator/CALCULATOR_GUIDE.md Configures an array control to manage repeating elements, such as additional disks. It supports a maximum number of elements and defines the schema for each item. ```typescript { type: CONTROL.Array, max: 7, // Максимальное количество элементов accessorKey: 'additionalDisks', defaultValue: [], addText: 'Добавить диск', ui: ['disk'], // Схема для каждого элемента массива controls: { disk: getDisk({ space: { label: 'Дополнительный диск', accessorKey: 'diskSpace', defaultValue: 10, uiProps: { min: 10, max: 4096, }, }, specification: { accessorKey: 'specification', defaultValue: 'SSD', }, }), }, } ``` -------------------------------- ### Control Dependency with watchedControls and relateFn Source: https://github.com/cloud-ru-tech/uikit-product/blob/master/packages/calculator/CALCULATOR_GUIDE.md Configure a control to depend on other controls' values. The `relateFn` calculates available options based on watched control values. ```typescript vCpuCoreCount: { type: CONTROL.Slider, accessorKey: 'vCpuCoreCount', defaultValue: '1', items: [1, 2, 4, 8], decoratorProps: { label: 'Количество ядер vCPU', }, watchedControls: { guaranteedPart: 'guaranteedPart' // Отслеживаем это поле }, relateFn: ({ guaranteedPart }) => { // Вычисляем доступные варианты на основе guaranteedPart const items = guaranteedToVCpuMap?.[guaranteedPart]; if (items?.length > 0) { return { items: items, // Обновляем список опций }; } }, } ``` -------------------------------- ### useForceUpdate Hook Source: https://github.com/cloud-ru-tech/uikit-product/blob/master/packages/utils/README.md A hook that provides a function to trigger a component re-render. Useful for manual state updates. ```APIDOC ## useForceUpdate Hook ### Description This hook returns a function that, when called, will force the component to re-render. This is useful for triggering updates when component state changes are not automatically detected. ### Returns A function `rerender` that, when called, causes the component to re-render. ### Usage ```typescript jsx import { useForceUpdate } from '@cloud-ru/uikit-product-utils'; function Component() { const rerender = useForceUpdate(); ... rerender(); // <- will lead to rerender } ``` ``` -------------------------------- ### useUniqueId Hook Source: https://github.com/cloud-ru-tech/uikit-product/blob/master/packages/utils/README.md A hook that returns a unique string identifier. Useful for generating unique IDs for DOM elements. ```APIDOC ## useUniqueId Hook ### Description This hook generates and returns a unique string identifier. It's commonly used for creating unique IDs for elements in the DOM, ensuring proper referencing and avoiding conflicts. ### Returns A unique string identifier. ### Usage ```typescript jsx import { useUniqueId } from '@cloud-ru/uikit-product-utils'; function Component() { const id = useUniqueId(); } ``` ``` -------------------------------- ### extractSupportProps Source: https://github.com/cloud-ru-tech/uikit-product/blob/master/packages/utils/README.md Extracts props from an object that match the '/^(data-test|aria)-/` regular expression. ```APIDOC ## extractSupportProps ### Description This function filters an object of props and returns only those that start with `data-test-` or `aria-`. ### Parameters - `props` (object): The object containing props to filter. ### Returns An object containing only the props that match the specified pattern. ### Usage ```typescript jsx import { extractSupportProps } from '@cloud-ru/uikit-product-utils'; const sampleProps = { ['data-test-id']: '1', ['aria-disabled']: true, ['data-disabled']: false, onClick: () => {}, value: '123' } extractSupportProps(sampleProps) // returns { ['data-test-id']: '1', ['aria-disabled']: true } ``` ```