@cloud-ru/ds-dropdown 1.0.0

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 (72) hide show
  1. package/CHANGELOG.md +8 -0
  2. package/LICENSE +201 -0
  3. package/README.md +218 -0
  4. package/dist/cjs/Dropdown.d.ts +7 -0
  5. package/dist/cjs/Dropdown.js +16 -0
  6. package/dist/cjs/constants.d.ts +10 -0
  7. package/dist/cjs/constants.js +13 -0
  8. package/dist/cjs/helperComponents/DesktopDropdown/DesktopDropdown.d.ts +6 -0
  9. package/dist/cjs/helperComponents/DesktopDropdown/DesktopDropdown.js +24 -0
  10. package/dist/cjs/helperComponents/DesktopDropdown/index.d.ts +1 -0
  11. package/dist/cjs/helperComponents/DesktopDropdown/index.js +17 -0
  12. package/dist/cjs/helperComponents/DropdownBody/DropdownBody.d.ts +6 -0
  13. package/dist/cjs/helperComponents/DropdownBody/DropdownBody.js +54 -0
  14. package/dist/cjs/helperComponents/DropdownBody/index.d.ts +1 -0
  15. package/dist/cjs/helperComponents/DropdownBody/index.js +17 -0
  16. package/dist/cjs/helperComponents/MobileDropdown/MobileDropdown.d.ts +7 -0
  17. package/dist/cjs/helperComponents/MobileDropdown/MobileDropdown.js +38 -0
  18. package/dist/cjs/helperComponents/MobileDropdown/index.d.ts +1 -0
  19. package/dist/cjs/helperComponents/MobileDropdown/index.js +17 -0
  20. package/dist/cjs/helperComponents/index.d.ts +3 -0
  21. package/dist/cjs/helperComponents/index.js +19 -0
  22. package/dist/cjs/index.d.ts +4 -0
  23. package/dist/cjs/index.js +20 -0
  24. package/dist/cjs/locale/index.d.ts +71 -0
  25. package/dist/cjs/locale/index.js +40 -0
  26. package/dist/cjs/package.json +3 -0
  27. package/dist/cjs/style.css +274 -0
  28. package/dist/cjs/styles.module.css +274 -0
  29. package/dist/cjs/types.d.ts +68 -0
  30. package/dist/cjs/types.js +2 -0
  31. package/dist/esm/Dropdown.d.ts +7 -0
  32. package/dist/esm/Dropdown.js +13 -0
  33. package/dist/esm/constants.d.ts +10 -0
  34. package/dist/esm/constants.js +10 -0
  35. package/dist/esm/helperComponents/DesktopDropdown/DesktopDropdown.d.ts +6 -0
  36. package/dist/esm/helperComponents/DesktopDropdown/DesktopDropdown.js +18 -0
  37. package/dist/esm/helperComponents/DesktopDropdown/index.d.ts +1 -0
  38. package/dist/esm/helperComponents/DesktopDropdown/index.js +1 -0
  39. package/dist/esm/helperComponents/DropdownBody/DropdownBody.d.ts +6 -0
  40. package/dist/esm/helperComponents/DropdownBody/DropdownBody.js +48 -0
  41. package/dist/esm/helperComponents/DropdownBody/index.d.ts +1 -0
  42. package/dist/esm/helperComponents/DropdownBody/index.js +1 -0
  43. package/dist/esm/helperComponents/MobileDropdown/MobileDropdown.d.ts +7 -0
  44. package/dist/esm/helperComponents/MobileDropdown/MobileDropdown.js +35 -0
  45. package/dist/esm/helperComponents/MobileDropdown/index.d.ts +1 -0
  46. package/dist/esm/helperComponents/MobileDropdown/index.js +1 -0
  47. package/dist/esm/helperComponents/index.d.ts +3 -0
  48. package/dist/esm/helperComponents/index.js +3 -0
  49. package/dist/esm/index.d.ts +4 -0
  50. package/dist/esm/index.js +4 -0
  51. package/dist/esm/locale/index.d.ts +71 -0
  52. package/dist/esm/locale/index.js +37 -0
  53. package/dist/esm/style.css +274 -0
  54. package/dist/esm/styles.module.css +274 -0
  55. package/dist/esm/types.d.ts +68 -0
  56. package/dist/esm/types.js +1 -0
  57. package/dist/tsconfig.cjs.tsbuildinfo +1 -0
  58. package/dist/tsconfig.esm.tsbuildinfo +1 -0
  59. package/package.json +60 -0
  60. package/src/Dropdown.tsx +16 -0
  61. package/src/constants.ts +11 -0
  62. package/src/helperComponents/DesktopDropdown/DesktopDropdown.tsx +81 -0
  63. package/src/helperComponents/DesktopDropdown/index.ts +1 -0
  64. package/src/helperComponents/DropdownBody/DropdownBody.tsx +107 -0
  65. package/src/helperComponents/DropdownBody/index.ts +1 -0
  66. package/src/helperComponents/MobileDropdown/MobileDropdown.tsx +91 -0
  67. package/src/helperComponents/MobileDropdown/index.ts +1 -0
  68. package/src/helperComponents/index.ts +3 -0
  69. package/src/index.ts +4 -0
  70. package/src/locale/index.ts +41 -0
  71. package/src/styles.module.scss +92 -0
  72. package/src/types.ts +90 -0
package/CHANGELOG.md ADDED
@@ -0,0 +1,8 @@
1
+ # Change Log
2
+
3
+ All notable changes to this project will be documented in this file.
4
+ See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
5
+
6
+ # 1.0.0 (2026-08-18)
7
+
8
+ Initial stable release under the `@cloud-ru/ds-*` scope.
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,218 @@
1
+ # Dropdown
2
+
3
+ `@cloud-ru/ds-dropdown` — Выпадающий блок с произвольным контентом и встроенными состояниями loading / not-found / no-data / data-error.
4
+
5
+ Выпадающий блок над триггером: произвольный контент (меню, фильтры, справочная информация) + встроенные состояния `loading / not-found / no-data / data-error` через `state`. Поверх `PopoverPrivate` — те же пропсы позиционирования, плюс готовая визуальная обработка асинхронных случаев.
6
+
7
+ ## Когда использовать
8
+ - Меню действий над кнопкой (экспорт, фильтры, настройки).
9
+ - Асинхронные подсказки и suggestions — встроенный `state` скрывает ручное ветвление UI.
10
+ - Композитные виджеты: селекторы, комбобоксы, авторасшифровки.
11
+
12
+ Когда **не** нужен `Dropdown`: для одиночного подсказывающего текста используйте `Tooltip`, для модального выбора — `Modal` или `Popover`.
13
+
14
+ ## Анатомия
15
+
16
+ ### State
17
+ Встроенные состояния контента, позволяющие не ветвить UI вручную: `loading` — идёт запрос (скелетон/спиннер), `no-data` — у источника пусто (первая загрузка), `not-found` — пользователь ввёл фильтр и ничего не нашлось, `data-error` — запрос упал (с опцией повтора).
18
+
19
+ ### Высота и прокрутка
20
+ Компонент высоту не ограничивает и своей прокрутки не даёт: содержимое dropdown произвольное, поэтому предел высоты проектируется вместе с ним. Для типового случая — списка опций — есть готовый `Droplist` из `@cloud-ru/ds-list`: он сам ограничивает высоту (256 / 320 / 384px по размеру) и включает прокрутку через `limitedScrollHeight`.
21
+
22
+ ### Width strategy (default `gte`)
23
+ Ширина dropdown относительно триггера:
24
+
25
+ - `auto` — по содержимому, триггер не учитывается.
26
+ - `eq` — ровно по триггеру: `width` фиксируется его шириной, содержимое сжимается или обрезается.
27
+ - `gte` — не уже триггера: ширина по содержимому, но `min-width` равна ширине триггера.
28
+
29
+ Разница между `gte` и `eq` видна, когда содержимое **шире** триггера: `eq` сожмёт список до ширины триггера, `gte` даст ему растянуться. Когда содержимое уже триггера, оба дают одинаковый результат — при триггере 96 и содержимом 40 `auto` даёт 40, `eq` и `gte` — по 96.
30
+
31
+ Значения `gte` в макетах нет: Figma рисует только «по содержимому» и «по триггеру». Это осознанное расширение API — промежуточный случай встречается в продукте чаще остальных, поэтому он и стоит дефолтом.
32
+
33
+ ## Установка
34
+ ```bash
35
+ pnpm add @cloud-ru/ds-dropdown
36
+ ```
37
+
38
+ ```ts
39
+ import { Dropdown, STATE } from '@cloud-ru/ds-dropdown'
40
+ ```
41
+
42
+ ## Примеры использования
43
+ ### Базовый Dropdown
44
+
45
+ ```tsx
46
+ import { Button } from '@cloud-ru/ds-button';
47
+ import { Dropdown } from '@cloud-ru/ds-dropdown';
48
+
49
+ export function Basic() {
50
+ return (
51
+ <Dropdown content={<div style={{ padding: 12 }}>Контент меню</div>}>
52
+ <Button label='Открыть' />
53
+ </Dropdown>
54
+ );
55
+ }
56
+ ```
57
+
58
+ ### Открытое меню для визуальной сверки
59
+
60
+ Управляемый режим — open
61
+
62
+ ```tsx
63
+ import { Button } from '@cloud-ru/ds-button';
64
+ import { Dropdown } from '@cloud-ru/ds-dropdown';
65
+
66
+ export function OpenForReview() {
67
+ return (
68
+ <Dropdown content={<div style={{ padding: 12 }}>Видимое содержимое</div>}>
69
+ <Button label='Триггер' />
70
+ </Dropdown>
71
+ );
72
+ }
73
+ ```
74
+
75
+ ### Состояние loading
76
+
77
+ ```tsx
78
+ import { Button } from '@cloud-ru/ds-button';
79
+ import { Dropdown, STATE } from '@cloud-ru/ds-dropdown';
80
+
81
+ export function Loading() {
82
+ return (
83
+ <Dropdown state={{ type: STATE.Loading }} content={null}>
84
+ <Button label='Загрузка' />
85
+ </Dropdown>
86
+ );
87
+ }
88
+ ```
89
+
90
+ ### Состояние not-found с действием
91
+
92
+ ```tsx
93
+ import { Button } from '@cloud-ru/ds-button';
94
+ import { Dropdown, STATE } from '@cloud-ru/ds-dropdown';
95
+
96
+ export function NotFound() {
97
+ return (
98
+ <Dropdown
99
+ state={{
100
+ type: STATE.NotFound,
101
+ content: 'Ничего не нашли',
102
+ actionLabel: 'Сбросить фильтры',
103
+ onActionClick: () => {},
104
+ }}
105
+ content={null}
106
+ >
107
+ <Button label='Поиск' />
108
+ </Dropdown>
109
+ );
110
+ }
111
+ ```
112
+
113
+ ## Props
114
+ **DropdownProps**
115
+
116
+ | Prop | Type | Default | Description |
117
+ |------|------|---------|-------------|
118
+ | `bodyPadding` | `boolean` | `true` | Паддинги body. `false` — убрать (контент во всю ширину; на mobile прокидывается в `BottomSheet`). |
119
+ | `children` | `string \| number \| boolean \| ReactElement<any, string \| JSXElementConstructor<any>> \| Iterable<ReactNode> \| ReactPortal \| null \| undefined` | — | |
120
+ | `className` | `string` | — | CSS-класс |
121
+ | `closeOnEscapeKey` | `boolean` | `true` | Закрывать ли по нажатию на кнопку `Esc` |
122
+ | `closeOnPopstate` | `boolean` | — | Закрывать ли поповер при переходе по истории браузера |
123
+ | `container` | `RefObject<HTMLElement \| null>` | — | Контейнер портала (ref). Переопределяет `PortalContext` для этого инстанса — <br/> по аналогии с `container` у Modal/Drawer. По умолчанию берётся из `PortalContextProvider`. |
124
+ | `content` | `ReactNode` | — | Содержимое внутри поповера (body) |
125
+ | `data-test-id` | `string` | — | |
126
+ | `defaultSnapIndex` | `number` | — | Только mobile: индекс snap'а по умолчанию (см. `BottomSheet`). |
127
+ | `disableSpanWrapper` | `boolean` | — | Отключает для `isValidElement` внешнюю обертку триггера <br/> Пригодится для элементов с `position: absolute` <br/> Работает для триггеров, которые умеют отдать свою DOM-ноду: нативные элементы, `forwardRef`-компоненты <br/> и компоненты, помеченные `withInnerRefSupport` из `@cloud-ru/ds-utils`. Остальные всё равно получают `<span>` — <br/> без ноды поповеру не от чего считать позицию; в dev-режиме об этом печатается предупреждение. |
128
+ | `fallbackPlacements` | `Placement` | — | Цепочка расположений которая будет применяться к поповеру от первого к последнему если при текущем он не влезает. |
129
+ | `footer` | `ReactNode` | — | Слот футера (bottomBar) |
130
+ | `footerDivider` | `boolean` | — | Divider между body и футером |
131
+ | `headerDivider` | `boolean` | — | Divider между шапкой и body |
132
+ | `hoverDelayClose` | `number` | — | Задержка закрытия по ховеру |
133
+ | `hoverDelayOpen` | `number` | — | Задержка открытия по ховеру |
134
+ | `offset` | `number` | `0` | Отступ поповера от его триггер-элемента (в пикселях). |
135
+ | `onOpenChange` | `((isOpen: boolean) => void)` | — | Колбек отображения компонента. Срабатывает при изменении состояния open. |
136
+ | `open` | `boolean` | — | Управляет состоянием показан/не показан. |
137
+ | `outsideClick` | `OutsideClickHandler` | — | Закрывать ли при клике вне поповера |
138
+ | `placement` | `"bottom"` \| `"bottom-end"` \| `"bottom-start"` \| `"left"` \| `"left-end"` \| `"left-start"` \| `"right"` \| `"right-end"` \| `"right-start"` \| `"top"` \| `"top-end"` \| `"top-start"` | `top` | Положение поповера относительно своего триггера (children). |
139
+ | `search` | `ReactNode` | — | Слот поиска в шапке (topBar) |
140
+ | `slotAfterTitle` | `ReactNode` | — | Подсказка-иконка рядом с заголовком (потребитель собирает, напр. `<QuestionTooltip />`) |
141
+ | `snapPoints` | `SnapPoint` | `['fit-content']` | Только mobile: snap-точки `BottomSheet`'а (высота листа). На desktop игнорируется. |
142
+ | `state` | `ActionButtonProps` \| `BlockProps` \| `BlockPropsWithIcon` \| `DropdownState` | — | Состояние |
143
+ | `stopPropagation` | `StopPropagationHandlers` | `{ onClick: true, onMouseDown: true, onMouseUp: true, onTouchStart: true, onTouchEnd: true, onTouchMove: true }` | Гасить всплытие pointer/touch-событий с floating-контейнера (`stopPropagation`). <br/> По умолчанию все хендлеры включены. Для drag&drop внутри поповера отключите <br/> `onMouseUp` / `onTouchEnd`, чтобы они дошли до `document`. |
144
+ | `title` | `ReactNode` | — | Заголовок в шапке (topBar) |
145
+ | `trigger` | `"click"` \| `"clickAndFocusVisible"` \| `"focus"` \| `"focusVisible"` \| `"hover"` \| `"hoverAndFocus"` \| `"hoverAndFocusVisible"` | — | Условие отображения поповера: <br/> - `click` - открывать по клику <br/> - `hover` - открывать по ховеру <br/> - `focusVisible` - открывать по focus-visible <br/> - `focus` - открывать по фокусу <br/> - `hoverAndFocusVisible` - открывать по ховеру и focus-visible <br/> - `hoverAndFocus` - открывать по ховеру и фокусу <br/> - `clickAndFocusVisible` - открывать по клику и focus-visible |
146
+ | `triggerClassName` | `string` | — | CSS-класс триггера |
147
+ | `triggerClickByKeys` | `boolean` | `true` | Вызывается ли попоповер по нажатию клавиш Enter/Space (при trigger = `click`) |
148
+ | `triggerRef` | `ForwardedRef<HTMLElement \| ReferenceType \| null>` | — | Ref ссылка на триггер |
149
+ | `widthStrategy` | `"auto"` \| `"eq"` \| `"gte"` | `auto` | Стратегия управления шириной контейнера поповера <br/> - `auto` - соответствует ширине контента, <br/> - `gte` - Great Than or Equal, равен ширине таргета или больше ее, если контент в поповере шире, <br/> - `eq` - Equal, строго равен ширине таргета. |
150
+
151
+ #### Related types
152
+
153
+ **ActionButtonProps**
154
+
155
+ | Prop | Type | Default | Description |
156
+ |------|------|---------|-------------|
157
+ | `actionLabel` | `string \| undefined` | — | Лейбл кнопки-действия |
158
+ | `onActionClick` | `(() => void) \| undefined` | — | Действие при клике по кнопке |
159
+
160
+ **BlockProps**
161
+
162
+ | Prop | Type | Default | Description |
163
+ |------|------|---------|-------------|
164
+ | `content` | `string \| number \| boolean \| ReactElement<any, string \| JSXElementConstructor<any>> \| Iterable<ReactNode> \| ReactPortal \| null \| undefined` | — | Подзаголовок |
165
+
166
+ **BlockPropsWithIcon**
167
+
168
+ | Prop | Type | Default | Description |
169
+ |------|------|---------|-------------|
170
+ | `content` | `string \| number \| boolean \| ReactElement<any, string \| JSXElementConstructor<any>> \| Iterable<ReactNode> \| ReactPortal \| null \| undefined` | — | Подзаголовок |
171
+ | `icon` | `IconPredefinedProps` | — | Иконка |
172
+
173
+ - `DropdownState` = `{ type: typeof STATE.Loading; } | ({ type: typeof STATE.NotFound; } & ActionButtonProps & BlockProps) | ({ type: typeof STATE.NoData; } & ActionButtonProps & BlockPropsWithIcon) | ({ type: typeof STATE.DataError; } & ActionButtonProps & BlockPropsWithIcon)`
174
+
175
+ ## Адаптивность
176
+
177
+ `Dropdown` — адаптивный компонент с переключением поверхности (surface-swap). Раскладку он берёт из `AdaptiveProvider` (контекст `@cloud-ru/ds-adaptive`); публичный API единый для обеих платформ:
178
+
179
+ - **desktop** (по умолчанию) — popover над триггером с позиционированием через floating-ui.
180
+ - **mobile** — контент рендерится в `BottomSheet` из `@cloud-ru/ds-bottom-sheet` (панель снизу со свайпом для закрытия).
181
+
182
+ Верстайте под desktop и поставьте один `<AdaptiveProvider>` в корне приложения — mobile-поверхность включается автоматически (desktop-first). Пропа `layoutType` у компонента нет: источник раскладки — только контекст.
183
+
184
+ ### Как форсировать платформу
185
+
186
+ Форс — только контекстом, не пропом:
187
+
188
+ - Поддерево — вложенный провайдер:
189
+ ```tsx
190
+ import { AdaptiveProvider } from '@cloud-ru/ds-adaptive'
191
+
192
+ <AdaptiveProvider layoutType='mobile'>
193
+ <Dropdown content={…}>…</Dropdown>
194
+ </AdaptiveProvider>
195
+ ```
196
+ - Отдельный компонент — `withLayoutType` (module-scope, сахар над провайдером):
197
+ ```tsx
198
+ import { withLayoutType } from '@cloud-ru/ds-adaptive'
199
+ import { Dropdown } from '@cloud-ru/ds-dropdown'
200
+
201
+ const MobileDropdown = withLayoutType(Dropdown, 'mobile')
202
+ ```
203
+
204
+ ### Платформенные пропы
205
+
206
+ Часть пропов управляет позиционированием desktop-popover'а и на mobile молча игнорируется (у `BottomSheet` своё позиционирование снизу). Таблица синхронизирована с type-level JSDoc у `DropdownProps`.
207
+
208
+ | Пропы | desktop | mobile |
209
+ |-------|---------|--------|
210
+ | `placement`, `widthStrategy`, `offset`, `fallbackPlacements` | используется | игнорируется |
211
+ | `hoverDelayOpen`, `hoverDelayClose`, `closeOnEscapeKey`, `triggerClickByKeys`, `outsideClick` | используется | игнорируется |
212
+ | `disableSpanWrapper`, `triggerClassName`, `triggerRef`, `container` | используется | игнорируется |
213
+ | `content`, `title`, `slotAfterTitle`, `search`, `footer`, `headerDivider`, `footerDivider` | используется | используется |
214
+ | `state`, `open`, `onOpenChange`, `closeOnPopstate`, `className` | используется | используется |
215
+
216
+ На mobile портал `BottomSheet` берётся из `@cloud-ru/ds-portal-context`, поэтому `container` не действует.
217
+
218
+ Подробнее о модели адаптивности — **Adaptive**.
@@ -0,0 +1,7 @@
1
+ import { DropdownProps } from './types';
2
+ /**
3
+ * Адаптивный Dropdown. Раскладку берёт из `AdaptiveProvider` (контекст): на `mobile` рендерит
4
+ * `BottomSheet`, иначе — desktop-popover. Публичный API единый; форс платформы — через
5
+ * `<AdaptiveProvider layoutType=…>` / `withLayoutType` (см. `@cloud-ru/ds-adaptive`), пропа `layoutType` нет.
6
+ */
7
+ export declare function Dropdown(props: DropdownProps): import("react/jsx-runtime").JSX.Element;
@@ -0,0 +1,16 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.Dropdown = Dropdown;
4
+ const jsx_runtime_1 = require("react/jsx-runtime");
5
+ const adaptive_1 = require("@cloud-ru/ds-adaptive");
6
+ const DesktopDropdown_1 = require("./helperComponents/DesktopDropdown");
7
+ const MobileDropdown_1 = require("./helperComponents/MobileDropdown");
8
+ /**
9
+ * Адаптивный Dropdown. Раскладку берёт из `AdaptiveProvider` (контекст): на `mobile` рендерит
10
+ * `BottomSheet`, иначе — desktop-popover. Публичный API единый; форс платформы — через
11
+ * `<AdaptiveProvider layoutType=…>` / `withLayoutType` (см. `@cloud-ru/ds-adaptive`), пропа `layoutType` нет.
12
+ */
13
+ function Dropdown(props) {
14
+ const { layoutType } = (0, adaptive_1.useAdaptiveLayout)();
15
+ return (0, adaptive_1.isMobileLayout)(layoutType) ? (0, jsx_runtime_1.jsx)(MobileDropdown_1.MobileDropdown, { ...props }) : (0, jsx_runtime_1.jsx)(DesktopDropdown_1.DesktopDropdown, { ...props });
16
+ }
@@ -0,0 +1,10 @@
1
+ export declare const STATE: {
2
+ readonly Loading: "loading";
3
+ readonly NotFound: "not-found";
4
+ readonly NoData: "no-data";
5
+ readonly DataError: "data-error";
6
+ };
7
+ export declare const TEST_IDS: {
8
+ readonly root: "dropdown";
9
+ readonly trigger: "dropdown-trigger";
10
+ };
@@ -0,0 +1,13 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.TEST_IDS = exports.STATE = void 0;
4
+ exports.STATE = {
5
+ Loading: 'loading',
6
+ NotFound: 'not-found',
7
+ NoData: 'no-data',
8
+ DataError: 'data-error',
9
+ };
10
+ exports.TEST_IDS = {
11
+ root: 'dropdown',
12
+ trigger: 'dropdown-trigger',
13
+ };
@@ -0,0 +1,6 @@
1
+ import { DropdownProps } from '../../types';
2
+ /**
3
+ * Desktop-поверхность Dropdown'а: popover (`PopoverPrivate`) с topBar / body / bottomBar.
4
+ * Internal — наружу не реэкспортится; рендерится адаптивным `Dropdown` по контексту раскладки.
5
+ */
6
+ export declare function DesktopDropdown({ className, children, content, title, slotAfterTitle, search, footer, headerDivider, footerDivider, state, bodyPadding, trigger, placement, triggerRef, widthStrategy, triggerClassName, ...rest }: DropdownProps): import("react/jsx-runtime").JSX.Element | null;
@@ -0,0 +1,24 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.DesktopDropdown = DesktopDropdown;
7
+ const jsx_runtime_1 = require("react/jsx-runtime");
8
+ const divider_1 = require("@cloud-ru/ds-divider");
9
+ const popover_private_1 = require("@cloud-ru/ds-popover-private");
10
+ const utils_1 = require("@cloud-ru/ds-utils");
11
+ const classnames_1 = __importDefault(require("classnames"));
12
+ const styles_module_scss_1 = __importDefault(require('../../styles.module.css'));
13
+ const DropdownBody_1 = require("../DropdownBody");
14
+ /**
15
+ * Desktop-поверхность Dropdown'а: popover (`PopoverPrivate`) с topBar / body / bottomBar.
16
+ * Internal — наружу не реэкспортится; рендерится адаптивным `Dropdown` по контексту раскладки.
17
+ */
18
+ function DesktopDropdown({ className, children, content, title, slotAfterTitle, search, footer, headerDivider, footerDivider, state, bodyPadding, trigger = 'click', placement = 'bottom-start', triggerRef, widthStrategy = 'gte', triggerClassName, ...rest }) {
19
+ if (!children && !triggerRef) {
20
+ return null;
21
+ }
22
+ const hasTopBar = Boolean(title || slotAfterTitle || search);
23
+ return ((0, jsx_runtime_1.jsx)(popover_private_1.PopoverPrivate, { placement: placement, popoverContent: (0, jsx_runtime_1.jsxs)("div", { className: (0, classnames_1.default)(styles_module_scss_1.default.root, className), ...(0, utils_1.extractSupportProps)(rest), "data-acrylic-appearance": 'neutral', "data-acrylic-level": '2Level', children: [(0, jsx_runtime_1.jsx)("div", { className: styles_module_scss_1.default.acrylic }), (0, jsx_runtime_1.jsxs)("div", { className: styles_module_scss_1.default.dropdownContent, children: [hasTopBar && ((0, jsx_runtime_1.jsxs)("div", { className: styles_module_scss_1.default.topBar, children: [(title || slotAfterTitle) && ((0, jsx_runtime_1.jsxs)("div", { className: styles_module_scss_1.default.headlineWrapper, children: [title, slotAfterTitle] })), search] })), hasTopBar && headerDivider && (0, jsx_runtime_1.jsx)(divider_1.Divider, { className: styles_module_scss_1.default.dividerWrapper }), (0, jsx_runtime_1.jsx)(DropdownBody_1.DropdownBody, { state: state, bodyPadding: bodyPadding, children: content }), footer && footerDivider && (0, jsx_runtime_1.jsx)(divider_1.Divider, { className: styles_module_scss_1.default.dividerWrapper }), footer && (0, jsx_runtime_1.jsx)("div", { className: styles_module_scss_1.default.bottomBar, children: footer })] })] }), trigger: trigger, triggerRef: triggerRef, hasArrow: false, widthStrategy: widthStrategy, triggerClassName: (0, classnames_1.default)(styles_module_scss_1.default.defaultTriggerClassName, triggerClassName), ...(0, utils_1.excludeSupportProps)(rest), children: children }));
24
+ }
@@ -0,0 +1 @@
1
+ export * from './DesktopDropdown';
@@ -0,0 +1,17 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ __exportStar(require("./DesktopDropdown"), exports);
@@ -0,0 +1,6 @@
1
+ import { DropdownProps } from '../../types';
2
+ /**
3
+ * Тело Dropdown'а (body) — общее для desktop-popover и mobile-bottom-sheet поверхностей:
4
+ * рендерит контент либо одно из состояний (loading / notFound / noData / dataError).
5
+ */
6
+ export declare function DropdownBody({ state, children, bodyPadding, }: Pick<DropdownProps, 'children' | 'state' | 'bodyPadding'>): import("react/jsx-runtime").JSX.Element;
@@ -0,0 +1,54 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.DropdownBody = DropdownBody;
7
+ const jsx_runtime_1 = require("react/jsx-runtime");
8
+ const button_1 = require("@cloud-ru/ds-button");
9
+ const system_1 = require("@cloud-ru/ds-icons/interface/system");
10
+ const info_block_1 = require("@cloud-ru/ds-info-block");
11
+ const loader_1 = require("@cloud-ru/ds-loader");
12
+ const constants_1 = require("../../constants");
13
+ const locale_1 = require("../../locale");
14
+ const styles_module_scss_1 = __importDefault(require('../../styles.module.css'));
15
+ /**
16
+ * Тело Dropdown'а (body) — общее для desktop-popover и mobile-bottom-sheet поверхностей:
17
+ * рендерит контент либо одно из состояний (loading / notFound / noData / dataError).
18
+ */
19
+ function DropdownBody({ state, children, bodyPadding = true, }) {
20
+ const { t } = locale_1.dropdownLocale.useTranslations();
21
+ switch (state?.type) {
22
+ case constants_1.STATE.Loading:
23
+ return ((0, jsx_runtime_1.jsx)("div", { className: styles_module_scss_1.default.loaderWrapper, children: (0, jsx_runtime_1.jsx)(loader_1.Spinner, { size: 'm' }) }));
24
+ case constants_1.STATE.NotFound:
25
+ return ((0, jsx_runtime_1.jsx)(info_block_1.InfoBlock, { className: styles_module_scss_1.default.infoBlock, content: state.content || t('states.notFound.title'), footer: state.onActionClick ? ((0, jsx_runtime_1.jsx)(button_1.ButtonGroup, { size: 's', tertiaryAction: {
26
+ label: state.actionLabel || t('states.notFound.action'),
27
+ view: 'simple',
28
+ appearance: 'neutral',
29
+ icon: (0, jsx_runtime_1.jsx)(system_1.UpdateSVG, {}),
30
+ iconPosition: 'after',
31
+ onClick: state.onActionClick,
32
+ } })) : null }));
33
+ case constants_1.STATE.NoData:
34
+ return ((0, jsx_runtime_1.jsx)(info_block_1.InfoBlock, { className: styles_module_scss_1.default.infoBlock, content: state.content || t('states.noData.title'), icon: state.icon, footer: state.onActionClick ? ((0, jsx_runtime_1.jsx)(button_1.ButtonGroup, { size: 's', tertiaryAction: {
35
+ label: state.actionLabel || t('states.noData.action'),
36
+ view: 'simple',
37
+ appearance: 'neutral',
38
+ icon: (0, jsx_runtime_1.jsx)(system_1.UpdateSVG, {}),
39
+ iconPosition: 'after',
40
+ onClick: state.onActionClick,
41
+ } })) : null }));
42
+ case constants_1.STATE.DataError:
43
+ return ((0, jsx_runtime_1.jsx)(info_block_1.InfoBlock, { className: styles_module_scss_1.default.infoBlock, content: state.content || t('states.dataError.title'), icon: state.icon, footer: state.onActionClick ? ((0, jsx_runtime_1.jsx)(button_1.ButtonGroup, { size: 's', tertiaryAction: {
44
+ label: state.actionLabel || t('states.dataError.action'),
45
+ view: 'simple',
46
+ appearance: 'neutral',
47
+ icon: (0, jsx_runtime_1.jsx)(system_1.UpdateSVG, {}),
48
+ iconPosition: 'after',
49
+ onClick: state.onActionClick,
50
+ } })) : null }));
51
+ default:
52
+ return ((0, jsx_runtime_1.jsx)("div", { className: styles_module_scss_1.default.bodyWrapper, "data-no-padding": bodyPadding === false || undefined, children: children }));
53
+ }
54
+ }
@@ -0,0 +1 @@
1
+ export * from './DropdownBody';
@@ -0,0 +1,17 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ __exportStar(require("./DropdownBody"), exports);
@@ -0,0 +1,7 @@
1
+ import { DropdownProps } from '../../types';
2
+ /**
3
+ * Mobile-поверхность Dropdown'а: контент уезжает в `BottomSheet` из `@cloud-ru/ds-bottom-sheet`.
4
+ * Триггер (`children`) клонируется для открытия sheet'а; `open`/`onOpenChange` поддерживают
5
+ * controlled-режим. Internal — наружу не реэкспортится; рендерится адаптивным `Dropdown` по контексту.
6
+ */
7
+ export declare function MobileDropdown({ children, content, title, slotAfterTitle, search, footer, headerDivider, footerDivider, state, bodyPadding, className, closeOnPopstate, snapPoints, defaultSnapIndex, open: openProp, onOpenChange, ...rest }: DropdownProps): import("react/jsx-runtime").JSX.Element;