@cloud-ru/uikit-product-fields-predefined 0.13.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (65) hide show
  1. package/CHANGELOG.md +935 -0
  2. package/LICENSE +201 -0
  3. package/README.md +151 -0
  4. package/package.json +63 -0
  5. package/src/components/AIDisclaimer/AIDisclaimer.tsx +18 -0
  6. package/src/components/AIDisclaimer/index.ts +1 -0
  7. package/src/components/AIDisclaimer/styles.module.scss +19 -0
  8. package/src/components/FieldAi/FieldAi.tsx +145 -0
  9. package/src/components/FieldAi/components/CheckItem/CheckItem.tsx +44 -0
  10. package/src/components/FieldAi/components/CheckItem/index.ts +1 -0
  11. package/src/components/FieldAi/components/CheckItem/styles.module.scss +28 -0
  12. package/src/components/FieldAi/components/MobileFieldAi/MobileFieldAi.tsx +57 -0
  13. package/src/components/FieldAi/components/MobileFieldAi/index.ts +1 -0
  14. package/src/components/FieldAi/components/MobileFieldAi/styles.module.scss +81 -0
  15. package/src/components/FieldAi/components/PasswordValidation/PasswordValidation.tsx +78 -0
  16. package/src/components/FieldAi/components/PasswordValidation/index.ts +1 -0
  17. package/src/components/FieldAi/components/PasswordValidation/styles.module.scss +32 -0
  18. package/src/components/FieldAi/components/TextArea/TextArea.tsx +113 -0
  19. package/src/components/FieldAi/components/TextArea/index.ts +1 -0
  20. package/src/components/FieldAi/components/TextArea/styles.module.scss +35 -0
  21. package/src/components/FieldAi/components/WithPasswordValidation/WithPasswordValidation.tsx +51 -0
  22. package/src/components/FieldAi/components/WithPasswordValidation/index.ts +1 -0
  23. package/src/components/FieldAi/components/WithPasswordValidation/styles.module.scss +7 -0
  24. package/src/components/FieldAi/index.ts +1 -0
  25. package/src/components/FieldAi/styles.module.scss +33 -0
  26. package/src/components/FieldAi/utils.ts +25 -0
  27. package/src/components/FieldChat/FieldChat.tsx +101 -0
  28. package/src/components/FieldChat/components/Attachments/Attachments.tsx +32 -0
  29. package/src/components/FieldChat/components/Attachments/index.ts +1 -0
  30. package/src/components/FieldChat/components/Attachments/styles.module.scss +9 -0
  31. package/src/components/FieldChat/index.ts +1 -0
  32. package/src/components/FieldChat/styles.module.scss +13 -0
  33. package/src/components/FieldPhone/FieldPhone.tsx +226 -0
  34. package/src/components/FieldPhone/__tests__/constants.ts +26 -0
  35. package/src/components/FieldPhone/__tests__/formatPhoneNumber.spec.ts +15 -0
  36. package/src/components/FieldPhone/__tests__/matchMedia.ts +15 -0
  37. package/src/components/FieldPhone/constants.ts +1 -0
  38. package/src/components/FieldPhone/countries.tsx +1755 -0
  39. package/src/components/FieldPhone/hooks/index.ts +2 -0
  40. package/src/components/FieldPhone/hooks/useCountries.ts +40 -0
  41. package/src/components/FieldPhone/hooks/useMapCountryToOptions.ts +25 -0
  42. package/src/components/FieldPhone/index.ts +7 -0
  43. package/src/components/FieldPhone/styles.module.scss +9 -0
  44. package/src/components/FieldPhone/types.ts +32 -0
  45. package/src/components/FieldPhone/utils.ts +71 -0
  46. package/src/components/SelectCreate/SelectCreate.tsx +122 -0
  47. package/src/components/SelectCreate/SelectFooter/SelectFooter.tsx +29 -0
  48. package/src/components/SelectCreate/SelectFooter/index.ts +1 -0
  49. package/src/components/SelectCreate/SelectFooter/styles.module.scss +9 -0
  50. package/src/components/SelectCreate/index.ts +1 -0
  51. package/src/components/SelectCreate/types.ts +35 -0
  52. package/src/components/SelectCreate/useSelectDataStates.tsx +53 -0
  53. package/src/components/index.ts +5 -0
  54. package/src/helperComponents/FieldSubmitButton/FieldSubmitButton.tsx +42 -0
  55. package/src/helperComponents/FieldSubmitButton/index.ts +1 -0
  56. package/src/helperComponents/TextAreaActionsFooter/TextAreaActionsFooter.tsx +18 -0
  57. package/src/helperComponents/TextAreaActionsFooter/index.ts +1 -0
  58. package/src/helperComponents/TextAreaActionsFooter/styles.module.scss +23 -0
  59. package/src/helpers/capitalize.ts +3 -0
  60. package/src/helpers/getSymbolsRangeFromMask.ts +17 -0
  61. package/src/helpers/index.ts +3 -0
  62. package/src/helpers/isTouchDevice.ts +5 -0
  63. package/src/hooks/index.ts +1 -0
  64. package/src/hooks/useOpen.ts +22 -0
  65. package/src/index.ts +3 -0
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2023 Cloud technology Limited (Ltd.)
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,151 @@
1
+ # Fields Predefined
2
+
3
+ ## Installation
4
+
5
+ `npm i @cloud-ru/uikit-product-fields-predefined`
6
+
7
+ [//]: DOCUMENTATION_SECTION_START
8
+ [//]: THIS_SECTION_IS_AUTOGENERATED_PLEASE_DONT_EDIT_IT
9
+ ## getSymbolsRangeFromMask
10
+ `helper`
11
+
12
+ Возвращает кол-во символов для маски - со скобками и без
13
+ ## FieldPhone
14
+ ### Props
15
+ | name | type | default value | description |
16
+ |------|------|---------------|-------------|
17
+ | layoutType* | enum LayoutType: `"mobile"`, `"tablet"`, `"desktop"`, `"desktopSmall"` | - | |
18
+ | value | `string` | - | Значение input |
19
+ | onChange | `((value: string, e?: ChangeEvent<HTMLInputElement>) => void) & ((value: string) => void)` | - | Колбек смены значения |
20
+ | id | `string` | - | Значение html-атрибута id |
21
+ | name | `string` | - | Значение html-атрибута name |
22
+ | disabled | `boolean` | false | Является ли поле деактивированным |
23
+ | readonly | `boolean` | false | Является ли поле доступным только для чтения |
24
+ | onFocus | `FocusEventHandler<HTMLInputElement>` | - | Колбек обработки получения фокуса |
25
+ | onBlur | `FocusEventHandler<HTMLInputElement>` | - | Колбек обработки потери фокуса |
26
+ | autoComplete | `string \| boolean` | false | Включен ли автокомплит для поля |
27
+ | autoFocus | `boolean` | false | Включен ли авто-фокус для поля |
28
+ | onPaste | `ClipboardEventHandler<HTMLInputElement>` | - | Колбек обработки вставки значения |
29
+ | spellCheck | `boolean` | true | Значение атрибута spellcheck (проверка орфографии) |
30
+ | pattern | `string` | - | Регулярное выражение валидного инпута |
31
+ | className | `string` | - | CSS-класс |
32
+ | label | `string` | - | Лейбл |
33
+ | labelTooltip | `ReactNode` | - | Всплывающая подсказка лейбла |
34
+ | required | `boolean` | - | Является ли поле обязательным |
35
+ | caption | `string` | - | Подпись справа от лейбла |
36
+ | hint | `string` | - | Подсказка внизу |
37
+ | showHintIcon | `boolean` | - | Отображать иконку подсказки |
38
+ | size | enum Size: `"s"`, `"m"`, `"l"` | - | Размер |
39
+ | validationState | enum ValidationState: `"error"`, `"default"`, `"warning"`, `"success"` | - | Состояние валидации |
40
+ | labelTooltipPlacement | enum Placement: `"left"`, `"left-start"`, `"left-end"`, `"right"`, `"right-start"`, `"right-end"`, `"top"`, `"top-start"`, `"top-end"`, `"bottom"`, `"bottom-start"`, `"bottom-end"` | top | Расположение подсказки лейбла |
41
+ | error | `string` | - | |
42
+ | type | "text" \| "tel" \| "email" | - | |
43
+ | showCopyButton | `boolean` | - | Отображение кнопки Копировать для поля (актуально только для `readonly = true`) |
44
+ | onCopyButtonClick | `() => void` | - | Колбек клика по кнопке Копировать для поля |
45
+ | showClearButton | `boolean` | true | Отображение кнопки очистки поля |
46
+ | scrollList | `boolean` | - | Включить скролл для основной части списка стран |
47
+ | searchPlaceholder | `string` | - | |
48
+ | onChangeCountry | `(country: FieldPhoneOptionsProps) => void` | - | |
49
+ | options | `CountrySettings` | - | options — объект конфигурации для изменения стандартного списка стран |
50
+ | ref | `LegacyRef<HTMLInputElement>` | - | Allows getting a ref to the component instance. Once the component unmounts, React will set `ref.current` to `null` (or call the ref with `null` if you passed a callback ref). @see {@link https://react.dev/learn/referencing-values-with-refs#refs-and-the-dom React Docs} |
51
+ | key | `Key` | - | |
52
+ ## useCountries
53
+ ### Props
54
+ | name | type | default value | description |
55
+ |------|------|---------------|-------------|
56
+ | overriddenOptions | `FieldPhoneOptionsProps[]` | - | Список элементов выпадающего списка со странами, который будет передан в селект-компонент и переопределит список объявленных стран внутри пакета |
57
+ | includedCountries | `({ readonly value: "russia"; readonly iso2: "RU"; readonly mask: "XXX XXX-XX-XX"; readonly caption: "+7"; readonly beforeContent: Element; readonly enabled: true; } \| { readonly value: "abkhazia"; ... 4 more ...; readonly enabled: true; } \| ... 156 more ... \| { ...; })[]` | - | Список стран, которые должны отображаться в селекторе (будут выбраны из перечня стран, объявленных внутри пакета) |
58
+ | excludedCountries | `({ readonly value: "russia"; readonly iso2: "RU"; readonly mask: "XXX XXX-XX-XX"; readonly caption: "+7"; readonly beforeContent: Element; readonly enabled: true; } \| { readonly value: "abkhazia"; ... 4 more ...; readonly enabled: true; } \| ... 156 more ... \| { ...; })[]` | - | Список стран, которые будут исключены из списка объявленных стран внутри пакета |
59
+ ## SelectCreate
60
+ ### Props
61
+ | name | type | default value | description |
62
+ |------|------|---------------|-------------|
63
+ | selectProps* | `FieldSelectProps` | - | Пропсы прокидываемые в селект |
64
+ | submitHandler* | `() => Promise<string \| void>` | - | Коллбек создания новой опции, при успешном выполнении возвращает value новой опции |
65
+ | entityName* | `EntityName` | - | Тип объекта для создания новой опции (в единственном числе вин.падеже для кнопки Создать <entityName> и множественном числе) |
66
+ | createLayoutProps* | `CreateLayoutModalProps \| CreateLayoutDrawerProps` | - | Пропсы передаваемые в модалку или дровер создания новой опции |
67
+ | createLayoutType* | "modal" \| "drawer" | - | По клику на кнопку создания открывать модальное окно или дровер |
68
+ | layoutType* | enum LayoutType: `"mobile"`, `"tablet"`, `"desktop"`, `"desktopSmall"` | - | |
69
+ | onRefetch | `VoidFunction` | - | Коллбек рефетча запроса на получение списка опций в случае ошибки (при передаче dataError в selectProps). |
70
+ | className | `string` | - | CSS-класс |
71
+ | afterClose | `VoidFunction` | - | Коллбек после закрытия модального окна/дровера |
72
+ | entityIcon | `JSXElementConstructor<{ size?: number; className?: string; }>` | - | Иконка сервиса |
73
+ | permission | "none" \| "canRead" \| "canCreate" | - | Управление состоянием компонента в зависимости от прав пользователя (по дефолту permission = 'canCreate') |
74
+ ## FieldAi
75
+ ### Props
76
+ | name | type | default value | description |
77
+ |------|------|---------------|-------------|
78
+ | layoutType* | enum LayoutType: `"mobile"`, `"tablet"`, `"desktop"`, `"desktopSmall"` | - | |
79
+ | onSubmit* | `(value: string) => void` | - | Колбек действия при отправке |
80
+ | value | `string` | - | HTML-аттрибут value |
81
+ | onChange | `(value: string, e?: ChangeEvent<HTMLTextAreaElement>) => void` | - | Колбек смены значения |
82
+ | inputMode | enum InputMode: `"none"`, `"text"`, `"tel"`, `"email"`, `"search"`, `"decimal"`, `"numeric"`, `"url"` | - | Режим работы экранной клавиатуры |
83
+ | id | `string` | - | HTML-аттрибут id |
84
+ | name | `string` | - | HTML-аттрибут name |
85
+ | maxLength | `number` | - | Максимальное кол-во символов |
86
+ | disabled | `boolean` | - | Является ли поле деактивированным |
87
+ | readonly | `boolean` | - | Является ли поле доступным только на чтение |
88
+ | onFocus | `FocusEventHandler<HTMLTextAreaElement>` | - | Колбек получения фокуса |
89
+ | onBlur | `FocusEventHandler<HTMLTextAreaElement>` | - | Колбек потери фокуса |
90
+ | autoFocus | `boolean` | - | Включен ли авто-фокус |
91
+ | onKeyDown | `KeyboardEventHandler<HTMLTextAreaElement>` | - | Колбек нажатия клавиши клавиатуры |
92
+ | className | `string` | - | CSS-класс |
93
+ | caption | `string` | - | Подпись справа от лейбла |
94
+ | hint | `string` | - | Подсказка внизу |
95
+ | showHintIcon | `boolean` | - | Отображать иконку подсказки |
96
+ | validationState | enum ValidationState: `"error"`, `"default"`, `"warning"`, `"success"` | - | Состояние валидации |
97
+ | labelTooltipPlacement | enum Placement: `"left"`, `"left-start"`, `"left-end"`, `"right"`, `"right-start"`, `"right-end"`, `"top"`, `"top-start"`, `"top-end"`, `"bottom"`, `"bottom-start"`, `"bottom-end"` | top | Расположение подсказки лейбла |
98
+ | error | `string` | - | |
99
+ | allowMoreThanMaxLength | `boolean` | - | Можно ли вводить больше разрешённого кол-ва символов |
100
+ | showCopyButton | `boolean` | - | Отображение кнопки Копировать для поля (актуально только для `readonly = true`) |
101
+ | onCopyButtonClick | `() => void` | - | Колбек клика по кнопке Копировать для поля |
102
+ | showClearButton | `boolean` | true | Отображение кнопки очистки поля |
103
+ | minRows | `number` | 3 | Минимальное кол-во строк, до которого размер поля может быть увеличен |
104
+ | maxRows | `number` | 1000 | Максимальное кол-во строк, до которого размер поля может быть увеличен |
105
+ | resizable | `boolean` | - | Может ли ли пользователь изменять размеры поля (если св-во не включено, поле автоматически меняет свой размер) |
106
+ | secure | `boolean \| "password"` | - | Режим ввода sensitive данных (пароля, API ключей, токенов, etc) |
107
+ | onResetContextClick | `() => void` | - | Действие при клике по кнопке сброса контекста |
108
+ | ref | `LegacyRef<HTMLTextAreaElement>` | - | Allows getting a ref to the component instance. Once the component unmounts, React will set `ref.current` to `null` (or call the ref with `null` if you passed a callback ref). @see {@link https://react.dev/learn/referencing-values-with-refs#refs-and-the-dom React Docs} |
109
+ | key | `Key` | - | |
110
+ ## FieldChat
111
+ ### Props
112
+ | name | type | default value | description |
113
+ |------|------|---------------|-------------|
114
+ | layoutType* | enum LayoutType: `"mobile"`, `"tablet"`, `"desktop"`, `"desktopSmall"` | - | |
115
+ | handleSubmit* | `(value: string) => void` | - | Колбек действия при отправке |
116
+ | value | `string` | - | HTML-аттрибут value |
117
+ | onChange | `(value: string, e?: ChangeEvent<HTMLTextAreaElement>) => void` | - | Колбек смены значения |
118
+ | inputMode | enum InputMode: `"none"`, `"text"`, `"tel"`, `"email"`, `"search"`, `"decimal"`, `"numeric"`, `"url"` | - | Режим работы экранной клавиатуры |
119
+ | id | `string` | - | HTML-аттрибут id |
120
+ | name | `string` | - | HTML-аттрибут name |
121
+ | maxLength | `number` | - | Максимальное кол-во символов |
122
+ | disabled | `boolean` | - | Является ли поле деактивированным |
123
+ | readonly | `boolean` | - | Является ли поле доступным только на чтение |
124
+ | onFocus | `FocusEventHandler<HTMLTextAreaElement>` | - | Колбек получения фокуса |
125
+ | onBlur | `FocusEventHandler<HTMLTextAreaElement>` | - | Колбек потери фокуса |
126
+ | autoFocus | `boolean` | - | Включен ли авто-фокус |
127
+ | onKeyDown | `KeyboardEventHandler<HTMLTextAreaElement>` | - | Колбек нажатия клавиши клавиатуры |
128
+ | className | `string` | - | CSS-класс |
129
+ | caption | `string` | - | Подпись справа от лейбла |
130
+ | showHintIcon | `boolean` | - | Отображать иконку подсказки |
131
+ | validationState | enum ValidationState: `"error"`, `"default"`, `"warning"`, `"success"` | - | Состояние валидации |
132
+ | labelTooltipPlacement | enum Placement: `"left"`, `"left-start"`, `"left-end"`, `"right"`, `"right-start"`, `"right-end"`, `"top"`, `"top-start"`, `"top-end"`, `"bottom"`, `"bottom-start"`, `"bottom-end"` | top | Расположение подсказки лейбла |
133
+ | error | `string` | - | |
134
+ | allowMoreThanMaxLength | `boolean` | - | Можно ли вводить больше разрешённого кол-ва символов |
135
+ | showCopyButton | `boolean` | - | Отображение кнопки Копировать для поля (актуально только для `readonly = true`) |
136
+ | onCopyButtonClick | `() => void` | - | Колбек клика по кнопке Копировать для поля |
137
+ | showClearButton | `boolean` | true | Отображение кнопки очистки поля |
138
+ | minRows | `number` | 3 | Минимальное кол-во строк, до которого размер поля может быть увеличен |
139
+ | maxRows | `number` | 1000 | Максимальное кол-во строк, до которого размер поля может быть увеличен |
140
+ | resizable | `boolean` | - | Может ли ли пользователь изменять размеры поля (если св-во не включено, поле автоматически меняет свой размер) |
141
+ | attachment | `Pick<FileUploadProps, "onFilesUpload" \| "accept"> & { files?: File[]; onFileDelete: (file?: File) => void; }` | - | |
142
+ ## AIDisclaimer
143
+ ### Props
144
+ | name | type | default value | description |
145
+ |------|------|---------------|-------------|
146
+ | layoutType* | enum LayoutType: `"mobile"`, `"tablet"`, `"desktop"`, `"desktopSmall"` | - | |
147
+
148
+
149
+ [//]: DOCUMENTATION_SECTION_END
150
+
151
+ [Changelog](./CHANGELOG.md)
package/package.json ADDED
@@ -0,0 +1,63 @@
1
+ {
2
+ "name": "@cloud-ru/uikit-product-fields-predefined",
3
+ "title": "Fields Predefined",
4
+ "version": "0.13.3",
5
+ "sideEffects": [
6
+ "*.css",
7
+ "*.woff",
8
+ "*.woff2"
9
+ ],
10
+ "description": "",
11
+ "main": "./dist/esm/index.js",
12
+ "module": "./dist/esm/index.js",
13
+ "homepage": "https://gitverse.ru/cloud-ru-tech/uikit-product/-/tree/master/packages/fields-predefined",
14
+ "repository": {
15
+ "type": "git",
16
+ "url": "https://gitverse.ru/cloud-ru-tech/uikit-product.git",
17
+ "directory": "packages/fields-predefined"
18
+ },
19
+ "author": {
20
+ "name": "Akhremenko Grigorii",
21
+ "url": "https://github.com/AGrigorii"
22
+ },
23
+ "files": [
24
+ "dist",
25
+ "src",
26
+ "./CHANGELOG.md",
27
+ "./LICENSE"
28
+ ],
29
+ "license": "Apache-2.0",
30
+ "publishConfig": {
31
+ "access": "public"
32
+ },
33
+ "scripts": {},
34
+ "dependencies": {
35
+ "@cloud-ru/uikit-product-icons": "15.1.1",
36
+ "@cloud-ru/uikit-product-mobile-dropdown": "0.9.21",
37
+ "@cloud-ru/uikit-product-mobile-fields": "0.11.24",
38
+ "@cloud-ru/uikit-product-mobile-modal": "0.9.18",
39
+ "@cloud-ru/uikit-product-mobile-tooltip": "0.4.65",
40
+ "@cloud-ru/uikit-product-utils": "7.0.0",
41
+ "@snack-uikit/attachment": "0.4.10",
42
+ "@snack-uikit/button": "0.19.11",
43
+ "@snack-uikit/drop-zone": "0.9.6",
44
+ "@snack-uikit/icon-predefined": "0.7.3",
45
+ "@snack-uikit/input-private": "4.8.1",
46
+ "@snack-uikit/scroll": "0.10.1",
47
+ "@snack-uikit/tooltip": "0.17.4",
48
+ "@snack-uikit/typography": "0.8.7",
49
+ "@snack-uikit/utils": "3.7.0",
50
+ "awesome-phonenumber": "7.5.0",
51
+ "classnames": "2.5.1",
52
+ "merge-refs": "1.2.2",
53
+ "react-imask": "7.6.1",
54
+ "react-textarea-autosize": "8.5.9"
55
+ },
56
+ "devDependencies": {
57
+ "@types/merge-refs": "1.0.0"
58
+ },
59
+ "peerDependencies": {
60
+ "@cloud-ru/uikit-product-locale": "*"
61
+ },
62
+ "gitHead": "e8bd79bc92b26a8f52611972eec98a867536ccd3"
63
+ }
@@ -0,0 +1,18 @@
1
+ import { useLocale } from '@cloud-ru/uikit-product-locale';
2
+ import { WithLayoutType } from '@cloud-ru/uikit-product-utils';
3
+
4
+ import styles from './styles.module.scss';
5
+
6
+ type AIDisclaimerProps = WithLayoutType;
7
+
8
+ export function AIDisclaimer({ layoutType }: AIDisclaimerProps) {
9
+ const { t } = useLocale('FieldsPredefined');
10
+
11
+ return (
12
+ <div className={styles.disclaimer}>
13
+ <span className={styles.hintText} data-layout-type={layoutType}>
14
+ {t('FieldAi.hint.text')}
15
+ </span>
16
+ </div>
17
+ );
18
+ }
@@ -0,0 +1 @@
1
+ export * from './AIDisclaimer';
@@ -0,0 +1,19 @@
1
+ @use '@sbercloud/figma-tokens-cloud-platform/build/scss/components/styles-tokens-fields' as ste;
2
+
3
+ .disclaimer {
4
+ display: inline-flex;
5
+ flex-direction: row;
6
+ align-items: center;
7
+ justify-content: center;
8
+ gap: ste.$dimension-050m;
9
+
10
+ color: ste.$sys-neutral-text-light;
11
+ }
12
+
13
+ .tooltip {
14
+ max-width: 258px;
15
+ }
16
+
17
+ .hintText {
18
+ @include ste.composite-var(ste.$light-label-s);
19
+ }
@@ -0,0 +1,145 @@
1
+ import cn from 'classnames';
2
+ import { forwardRef, KeyboardEventHandler, useMemo, useState } from 'react';
3
+
4
+ import { EyeClosedSVG, EyeSVG } from '@cloud-ru/uikit-product-icons';
5
+ import { useLocale } from '@cloud-ru/uikit-product-locale';
6
+ import {
7
+ AdaptiveFieldTextArea,
8
+ FieldTextAreaProps,
9
+ getAdaptiveFieldProps,
10
+ } from '@cloud-ru/uikit-product-mobile-fields';
11
+ import { WithLayoutType } from '@cloud-ru/uikit-product-utils';
12
+ import { ButtonFunction, ButtonOutline } from '@snack-uikit/button';
13
+ import { Tooltip } from '@snack-uikit/tooltip';
14
+
15
+ import { FieldSubmitButton } from '../../helperComponents/FieldSubmitButton';
16
+ import { TextAreaActionsFooter } from '../../helperComponents/TextAreaActionsFooter';
17
+ import { isTouchDevice as isTouchDeviceHelper } from '../../helpers';
18
+ import { AIDisclaimer } from '../AIDisclaimer/AIDisclaimer';
19
+ import { MobileFieldAi } from './components/MobileFieldAi';
20
+ import { WithPasswordValidation } from './components/WithPasswordValidation';
21
+ import styles from './styles.module.scss';
22
+ import { getValidationPassword } from './utils';
23
+
24
+ export type FieldAiProps = WithLayoutType<
25
+ Omit<FieldTextAreaProps, 'placeholder' | 'labelTooltip' | 'label' | 'required' | 'size' | 'spellCheck' | 'footer'> & {
26
+ /** Режим ввода sensitive данных (пароля, API ключей, токенов, etc) */
27
+ secure?: boolean | 'password';
28
+ /** Колбек действия при отправке */
29
+ onSubmit(value: string): void;
30
+ /** Действие при клике по кнопке сброса контекста */
31
+ onResetContextClick?(): void;
32
+ }
33
+ >;
34
+
35
+ export const FieldAi = forwardRef<HTMLTextAreaElement, FieldAiProps>(
36
+ ({ secure = false, onSubmit: handleSubmitProp, value, onResetContextClick, disabled, className, ...props }, ref) => {
37
+ const { layoutType, validationState } = props;
38
+ const { t } = useLocale('FieldsPredefined');
39
+ const isTouchDevice = isTouchDeviceHelper(layoutType);
40
+
41
+ const [isValueHidden, setIsValueHidden] = useState<boolean>(true);
42
+
43
+ const isValueValid = typeof value === 'string' && value.trim().length > 0;
44
+ const isPasswordMode = secure === 'password';
45
+
46
+ const passwordValidation = useMemo(() => getValidationPassword(value), [value]);
47
+ const isPasswordValid = isPasswordMode ? Object.values(passwordValidation).every(Boolean) : true;
48
+ const showPasswordError = !isPasswordValid && secure && value;
49
+
50
+ const handleSubmit = () => {
51
+ if (isValueValid && isPasswordValid) {
52
+ handleSubmitProp(value);
53
+ }
54
+ };
55
+
56
+ const handleKeyDown: KeyboardEventHandler<HTMLTextAreaElement> = e => {
57
+ if (isTouchDevice) {
58
+ return;
59
+ }
60
+
61
+ if (e.key === 'Enter' && !e.shiftKey) {
62
+ e.preventDefault();
63
+
64
+ if (!disabled) {
65
+ handleSubmit();
66
+ }
67
+
68
+ return;
69
+ }
70
+ };
71
+
72
+ if (isTouchDevice && !secure) {
73
+ return (
74
+ <MobileFieldAi
75
+ {...props}
76
+ {...getAdaptiveFieldProps(props)}
77
+ onSubmit={handleSubmit}
78
+ submitEnabled={isValueValid && !disabled}
79
+ ref={ref}
80
+ value={value}
81
+ />
82
+ );
83
+ }
84
+
85
+ return (
86
+ <div className={cn(styles.wrapper, className)}>
87
+ <WithPasswordValidation
88
+ showValidation={isPasswordMode}
89
+ passwordValidation={passwordValidation}
90
+ layoutType={layoutType}
91
+ >
92
+ <AdaptiveFieldTextArea
93
+ {...props}
94
+ ref={ref}
95
+ value={value}
96
+ size='m'
97
+ minRows={secure ? 1 : 2}
98
+ maxRows={secure ? 1 : 4}
99
+ placeholder={secure ? t('FieldAi.secret.placeholder') : t('FieldAi.regular.placeholder')}
100
+ className={secure && isValueHidden ? styles.secured : undefined}
101
+ onKeyDown={handleKeyDown}
102
+ spellCheck={!secure}
103
+ validationState={showPasswordError ? 'error' : validationState}
104
+ footer={
105
+ <TextAreaActionsFooter
106
+ left={
107
+ secure && (
108
+ <ButtonFunction
109
+ size='xs'
110
+ icon={isValueHidden ? <EyeSVG /> : <EyeClosedSVG />}
111
+ onClick={() => setIsValueHidden(prev => !prev)}
112
+ />
113
+ )
114
+ }
115
+ right={
116
+ <>
117
+ {secure && onResetContextClick && (
118
+ <Tooltip tip={t('FieldAi.resetContext.tooltip')} hoverDelayOpen={600}>
119
+ <ButtonOutline
120
+ size='xs'
121
+ label={t('FieldAi.resetContext.label')}
122
+ onClick={onResetContextClick}
123
+ appearance='destructive'
124
+ />
125
+ </Tooltip>
126
+ )}
127
+ <FieldSubmitButton
128
+ showTooltip={!isTouchDevice}
129
+ className={isTouchDevice ? styles.mobileSubmitButton : undefined}
130
+ active={isValueValid && !disabled && isPasswordValid}
131
+ handleClick={handleSubmit}
132
+ size={isTouchDevice ? 's' : 'xs'}
133
+ />
134
+ </>
135
+ }
136
+ />
137
+ }
138
+ />
139
+ </WithPasswordValidation>
140
+
141
+ {!isPasswordMode && <AIDisclaimer layoutType={layoutType} />}
142
+ </div>
143
+ );
144
+ },
145
+ );
@@ -0,0 +1,44 @@
1
+ import { useEffect, useState } from 'react';
2
+
3
+ import { CheckSVG } from '@cloud-ru/uikit-product-icons';
4
+ import { WithLayoutType } from '@cloud-ru/uikit-product-utils';
5
+ import { Typography } from '@snack-uikit/typography';
6
+
7
+ import styles from './styles.module.scss';
8
+
9
+ type CheckItemProps = WithLayoutType<{
10
+ label: string;
11
+ checked: boolean;
12
+ shouldHide?: boolean;
13
+ }>;
14
+
15
+ const CHECKED_ITEM_DISAPPEAR_TIMEOUT = 500;
16
+
17
+ export function CheckItem({ label, checked, layoutType, shouldHide = false }: CheckItemProps) {
18
+ const [visible, setVisible] = useState(checked);
19
+
20
+ useEffect(() => {
21
+ if (checked) {
22
+ const timeoutId = setTimeout(() => {
23
+ setVisible(false);
24
+ }, CHECKED_ITEM_DISAPPEAR_TIMEOUT);
25
+
26
+ return () => clearTimeout(timeoutId);
27
+ }
28
+
29
+ setVisible(true);
30
+ }, [checked]);
31
+
32
+ if (shouldHide && !visible) {
33
+ return null;
34
+ }
35
+
36
+ return (
37
+ <div className={styles.checkItem} data-layout-type={layoutType}>
38
+ <CheckSVG size={20} className={styles.icon} data-checked={checked} />
39
+ <Typography.SansBodyM className={styles.label} data-checked={checked}>
40
+ {label}
41
+ </Typography.SansBodyM>
42
+ </div>
43
+ );
44
+ }
@@ -0,0 +1 @@
1
+ export * from './CheckItem';