@hh.ru/magritte-ui-bottom-sheet 9.4.48 → 9.4.49

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.
package/BottomSheet.js CHANGED
@@ -23,940 +23,1000 @@ import { Layer } from '@hh.ru/magritte-ui-layer';
23
23
  import { TextAreaGrowLimiter } from '@hh.ru/magritte-ui-textarea';
24
24
  import { ThemeWrapper } from '@hh.ru/magritte-ui-theme-wrapper';
25
25
  import { isValidTreeSelectorWrapper } from '@hh.ru/magritte-ui-tree-selector';
26
- import { s as styles } from './bottom-sheet-kKgvx4B-.js';
26
+ import { s as styles } from './bottom-sheet-DRUdtPUr.js';
27
27
 
28
- const CSS_VAR_ENTER_ANIMATION_DURATION = '--enter-animation-duration';
29
- const CSS_VAR_EXIT_ANIMATION_DURATION = '--exit-animation-duration';
30
- const CSS_VAR_HEIGHT_ANIMATION_DURATION = '--height-transition-duration';
31
- const CSS_VAR_VIRTUAL_KEYBOARD_TOP_OFFSET = '--virtual-keyboard-top-offset';
32
- const CSS_VAR_VIRTUAL_KEYBOARD_BOTTOM_OFFSET = '--virtual-keyboard-bottom-offset';
28
+ const CSS_VAR_ENTER_ANIMATION_DURATION = "--enter-animation-duration";
29
+ const CSS_VAR_EXIT_ANIMATION_DURATION = "--exit-animation-duration";
30
+ const CSS_VAR_HEIGHT_ANIMATION_DURATION = "--height-transition-duration";
31
+ const CSS_VAR_VIRTUAL_KEYBOARD_TOP_OFFSET = "--virtual-keyboard-top-offset";
32
+ const CSS_VAR_VIRTUAL_KEYBOARD_BOTTOM_OFFSET = "--virtual-keyboard-bottom-offset";
33
33
  const checkSafari = () => /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
34
34
  const hasSelectedText = () => {
35
- const selection = document.getSelection();
36
- return !!selection && !selection.isCollapsed;
35
+ const selection = document.getSelection();
36
+ return !!selection && !selection.isCollapsed;
37
37
  };
38
- const isContentSizedFullHeight = (children) => (isValidElement(children) &&
39
- typeof children.type === 'function' &&
40
- 'isFullHeightBottomSheetContent' in children.type &&
41
- children.props.fixedHeight !== true) ||
42
- Children.toArray(children).some(isValidTreeSelectorWrapper);
38
+ const isContentSizedFullHeight = (children) => isValidElement(children) && typeof children.type === "function" && "isFullHeightBottomSheetContent" in children.type && children.props.fixedHeight !== true || Children.toArray(children).some(isValidTreeSelectorWrapper);
43
39
  const toNumber = (value) => {
44
- const result = parseInt(value, 10);
45
- return Number.isInteger(result) ? result : 0;
40
+ const result = parseInt(value, 10);
41
+ return Number.isInteger(result) ? result : 0;
46
42
  };
47
- const textInputTypes = ['text', 'password', 'email', 'search', 'tel', 'url', 'number'];
43
+ const textInputTypes = ["text", "password", "email", "search", "tel", "url", "number"];
48
44
  const isTextInputElement = (element) => {
49
- if (element instanceof HTMLInputElement) {
50
- return textInputTypes.includes(element.type);
51
- }
52
- else if (element instanceof HTMLTextAreaElement) {
53
- return true;
54
- }
55
- return false;
45
+ if (element instanceof HTMLInputElement) {
46
+ return textInputTypes.includes(element.type);
47
+ } else if (element instanceof HTMLTextAreaElement) {
48
+ return true;
49
+ }
50
+ return false;
56
51
  };
57
52
  const translateY = (value) => `translate3d(0, ${value}px, 0)`;
58
53
  const makeInitialState = () => ({
59
- dividerVisible: false,
60
- grabberUnsafe: false,
61
- hasFocus: false,
62
- resizeRAFHandle: null,
63
- scrollOffset: 0,
64
- swipeOffset: 0,
65
- touchAction: null,
66
- exitHandlers: [],
67
- heightAnimationValue: null,
54
+ dividerVisible: false,
55
+ grabberUnsafe: false,
56
+ hasFocus: false,
57
+ resizeRAFHandle: null,
58
+ scrollOffset: 0,
59
+ swipeOffset: 0,
60
+ touchAction: null,
61
+ exitHandlers: [],
62
+ heightAnimationValue: null
68
63
  });
69
- /**
70
- * Внутренний `role="dialog"`-узел. Вынесен в отдельный компонент, потому что обязан жить **под**
71
- * `AccessibleRegionProvider`: только так `useAccessibleRegionProps` видит метки/описания,
72
- * зарегистрированные потомками (например, заголовком в `header`), и выставляет
73
- * `aria-labelledby` / `aria-describedby`. Явные `aria-*` пропы при этом всё перекрывают.
74
- */
75
64
  const BottomSheetDialog = ({ explicitAria, dialogRef, children, ...rest }) => {
76
- const aria = useAccessibleRegionProps(explicitAria);
77
- return (jsx("div", { ...rest, ...aria, role: "dialog", ref: dialogRef, children: children }));
65
+ const aria = useAccessibleRegionProps(explicitAria);
66
+ return /* @__PURE__ */ jsx("div", { ...rest, ...aria, role: "dialog", ref: dialogRef, children });
78
67
  };
79
- const BottomSheetRenderFunc = ({ allowScrollWhileFocused, children, footer, header, height = 'content', interceptClickHandlers = true, keyboardOverlaysFooter = true, onAppear, onBeforeExit, onAfterExit, onClose, showDivider = 'with-scroll', showOverlay = true, visible = false, withContentPaddings = true, withTopPadding = true, 'data-qa': dataQA, interceptTouchHandlers = true, id, 'aria-label': ariaLabel, 'aria-labelledby': ariaLabelledby, 'aria-describedby': ariaDescribedby, 'aria-description': ariaDescription, }, ref) => {
80
- const DOCUMENT_HEIGHT = useRef(0);
81
- const SWIPE_THRESHOLD = useRef({ max: Infinity });
82
- const VIEWPORT_HEIGHT = useRef(0);
83
- const contentRef = useRef(null);
84
- const headerWrapperRef = useRef(null);
85
- const contentOverlayRef = useRef(null);
86
- const cssVariablesContainerRef = useRef(null);
87
- const dividerRef = useRef(null);
88
- const focusedElementRef = useRef(null);
89
- const footerRef = useRef(null);
90
- const grabberRef = useRef(null);
91
- const overlayRef = useRef(null);
92
- const scrollContainerRef = useRef(null);
93
- const swipeContainerRef = useRef(null);
94
- const visualContainerRef = useRef(null);
95
- const bottomSheetRef = useMultipleRefs(ref, visualContainerRef);
96
- const scrollContextProviderRef = useRef(null);
97
- const GrowLimitWrapper = isContentSizedFullHeight(children) ? Fragment : TextAreaGrowLimiter;
98
- const growLimiterRef = useRef(null);
99
- const growLimiterContextValue = useState(() => {
100
- let height = 'auto';
101
- let limiterFlex = '1 0';
102
- return {
103
- containerRef: scrollContainerRef,
104
- preMeasurement: () => {
105
- if (!visualContainerRef.current || !growLimiterRef.current) {
106
- return;
107
- }
108
- height = visualContainerRef.current.style.height;
109
- limiterFlex = growLimiterRef.current.style.flex;
110
- visualContainerRef.current.style.height = 'auto';
111
- },
112
- postMeasurement: () => {
113
- visualContainerRef.current && (visualContainerRef.current.style.height = height);
114
- growLimiterRef.current && (growLimiterRef.current.style.flex = limiterFlex);
115
- },
116
- };
117
- })[0];
118
- const growLimiterProps = useMemo(() => GrowLimitWrapper === TextAreaGrowLimiter
119
- ? {
120
- ...growLimiterContextValue,
121
- ref: growLimiterRef,
122
- debounce: true,
123
- className: styles.growLimiter,
68
+ const BottomSheetRenderFunc = ({
69
+ allowScrollWhileFocused,
70
+ children,
71
+ footer,
72
+ header,
73
+ height = "content",
74
+ interceptClickHandlers = true,
75
+ keyboardOverlaysFooter = true,
76
+ onAppear,
77
+ onBeforeExit,
78
+ onAfterExit,
79
+ onClose,
80
+ showDivider = "with-scroll",
81
+ showOverlay = true,
82
+ visible = false,
83
+ withContentPaddings = true,
84
+ withTopPadding = true,
85
+ "data-qa": dataQA,
86
+ interceptTouchHandlers = true,
87
+ id,
88
+ "aria-label": ariaLabel,
89
+ "aria-labelledby": ariaLabelledby,
90
+ "aria-describedby": ariaDescribedby,
91
+ "aria-description": ariaDescription
92
+ }, ref) => {
93
+ const DOCUMENT_HEIGHT = useRef(0);
94
+ const SWIPE_THRESHOLD = useRef({ max: Infinity });
95
+ const VIEWPORT_HEIGHT = useRef(0);
96
+ const contentRef = useRef(null);
97
+ const headerWrapperRef = useRef(null);
98
+ const contentOverlayRef = useRef(null);
99
+ const cssVariablesContainerRef = useRef(null);
100
+ const dividerRef = useRef(null);
101
+ const focusedElementRef = useRef(null);
102
+ const footerRef = useRef(null);
103
+ const grabberRef = useRef(null);
104
+ const overlayRef = useRef(null);
105
+ const scrollContainerRef = useRef(null);
106
+ const swipeContainerRef = useRef(null);
107
+ const visualContainerRef = useRef(null);
108
+ const bottomSheetRef = useMultipleRefs(ref, visualContainerRef);
109
+ const scrollContextProviderRef = useRef(null);
110
+ const GrowLimitWrapper = isContentSizedFullHeight(children) ? Fragment : TextAreaGrowLimiter;
111
+ const growLimiterRef = useRef(null);
112
+ const growLimiterContextValue = useState(() => {
113
+ let height2 = "auto";
114
+ let limiterFlex = "1 0";
115
+ return {
116
+ containerRef: scrollContainerRef,
117
+ preMeasurement: () => {
118
+ if (!visualContainerRef.current || !growLimiterRef.current) {
119
+ return;
124
120
  }
125
- : {}, [GrowLimitWrapper, growLimiterContextValue]);
126
- const currentVisible = useBreakpoint().isMobile && visible;
127
- const onAppearRef = useRef(onAppear);
128
- onAppearRef.current = onAppear;
129
- const onCloseRef = useRef(onClose);
130
- onCloseRef.current = onClose;
131
- const stateRef = useRef(makeInitialState());
132
- const [animationTimeout, setAnimationTimeout] = useState(null);
133
- const [heightAnimationRunning, setHeightAnimationRunning] = useState(false);
134
- const bottomSheetContext = useMemo(() => {
135
- let keyboardResizeHandlers = [];
136
- return {
137
- keyboardResizeHandlers,
138
- value: {
139
- height,
140
- subscribeToKeyboardResize: (handler) => {
141
- keyboardResizeHandlers.push(handler);
142
- },
143
- unsubscribeFromKeyboardResize: (handlerToRemove) => {
144
- keyboardResizeHandlers = keyboardResizeHandlers.filter((handler) => handler !== handlerToRemove);
145
- },
146
- },
147
- };
148
- }, [height]);
149
- const virtualKeyboardOffsetsRef = useRef({ top: 0, bottom: 0 });
150
- const animationTimeoutExitRef = useRef(animationTimeout?.appear.exit || 0);
151
- animationTimeoutExitRef.current = animationTimeout?.appear.exit || 0;
152
- const [isSafari, setIsSafari] = useState(null);
153
- useEffect(() => setIsSafari(checkSafari()), [setIsSafari]);
154
- const [hasTouchSupport, setHasTouchSupport] = useState(null);
155
- const hasTouchSupportRef = useRef(null);
156
- useEffect(() => {
157
- if (!('matchMedia' in window)) {
158
- return void 0;
121
+ height2 = visualContainerRef.current.style.height;
122
+ limiterFlex = growLimiterRef.current.style.flex;
123
+ visualContainerRef.current.style.height = "auto";
124
+ },
125
+ postMeasurement: () => {
126
+ visualContainerRef.current && (visualContainerRef.current.style.height = height2);
127
+ growLimiterRef.current && (growLimiterRef.current.style.flex = limiterFlex);
128
+ }
129
+ };
130
+ })[0];
131
+ const growLimiterProps = useMemo(
132
+ () => GrowLimitWrapper === TextAreaGrowLimiter ? {
133
+ ...growLimiterContextValue,
134
+ ref: growLimiterRef,
135
+ debounce: true,
136
+ className: styles.growLimiter
137
+ } : {},
138
+ [GrowLimitWrapper, growLimiterContextValue]
139
+ );
140
+ const currentVisible = useBreakpoint().isMobile && visible;
141
+ const onAppearRef = useRef(onAppear);
142
+ onAppearRef.current = onAppear;
143
+ const onCloseRef = useRef(onClose);
144
+ onCloseRef.current = onClose;
145
+ const stateRef = useRef(makeInitialState());
146
+ const [animationTimeout, setAnimationTimeout] = useState(null);
147
+ const [heightAnimationRunning, setHeightAnimationRunning] = useState(false);
148
+ const bottomSheetContext = useMemo(() => {
149
+ let keyboardResizeHandlers = [];
150
+ return {
151
+ keyboardResizeHandlers,
152
+ value: {
153
+ height,
154
+ subscribeToKeyboardResize: (handler) => {
155
+ keyboardResizeHandlers.push(handler);
156
+ },
157
+ unsubscribeFromKeyboardResize: (handlerToRemove) => {
158
+ keyboardResizeHandlers = keyboardResizeHandlers.filter((handler) => handler !== handlerToRemove);
159
159
  }
160
- const mediaQuery = window.matchMedia('(pointer:coarse)');
161
- const handleMediaQueryChange = () => {
162
- hasTouchSupportRef.current = mediaQuery.matches;
163
- setHasTouchSupport(hasTouchSupportRef.current);
164
- };
165
- if (typeof mediaQuery.addEventListener === 'function') {
166
- mediaQuery.addEventListener('change', handleMediaQueryChange);
160
+ }
161
+ };
162
+ }, [height]);
163
+ const virtualKeyboardOffsetsRef = useRef({ top: 0, bottom: 0 });
164
+ const animationTimeoutExitRef = useRef(animationTimeout?.appear.exit || 0);
165
+ animationTimeoutExitRef.current = animationTimeout?.appear.exit || 0;
166
+ const [isSafari, setIsSafari] = useState(null);
167
+ useEffect(() => setIsSafari(checkSafari()), [setIsSafari]);
168
+ const [hasTouchSupport, setHasTouchSupport] = useState(null);
169
+ const hasTouchSupportRef = useRef(null);
170
+ useEffect(() => {
171
+ if (!("matchMedia" in window)) {
172
+ return void 0;
173
+ }
174
+ const mediaQuery = window.matchMedia("(pointer:coarse)");
175
+ const handleMediaQueryChange = () => {
176
+ hasTouchSupportRef.current = mediaQuery.matches;
177
+ setHasTouchSupport(hasTouchSupportRef.current);
178
+ };
179
+ if (typeof mediaQuery.addEventListener === "function") {
180
+ mediaQuery.addEventListener("change", handleMediaQueryChange);
181
+ } else {
182
+ mediaQuery.addListener(handleMediaQueryChange);
183
+ }
184
+ hasTouchSupportRef.current = mediaQuery.matches;
185
+ setHasTouchSupport(hasTouchSupportRef.current);
186
+ return () => {
187
+ if (typeof mediaQuery.removeEventListener === "function") {
188
+ mediaQuery.removeEventListener("change", handleMediaQueryChange);
189
+ } else {
190
+ mediaQuery.removeListener(handleMediaQueryChange);
191
+ }
192
+ };
193
+ }, [setHasTouchSupport]);
194
+ const bindEscapeToClose = useEscapeToClose(() => currentVisible && onCloseRef.current(null));
195
+ useEffect(() => {
196
+ bindEscapeToClose(document.body);
197
+ return () => bindEscapeToClose(null);
198
+ }, [bindEscapeToClose]);
199
+ const LayoutMetrics = useState(() => {
200
+ let cache = {};
201
+ return {
202
+ get scrollTop() {
203
+ return Math.max(-stateRef.current.scrollOffset, 0);
204
+ },
205
+ get bottomSheetHeight() {
206
+ if (!("bottomSheetHeight" in cache) && visualContainerRef.current !== null) {
207
+ cache.bottomSheetHeight = visualContainerRef.current.clientHeight;
167
208
  }
168
- else {
169
- mediaQuery.addListener(handleMediaQueryChange);
209
+ return cache.bottomSheetHeight ?? 0;
210
+ },
211
+ /**
212
+ * Высота контента
213
+ * Может превышать высоту контейнера из-за скролла
214
+ */
215
+ get contentHeight() {
216
+ if (!("contentHeight" in cache) && contentRef.current !== null) {
217
+ cache.contentHeight = contentRef.current.clientHeight;
170
218
  }
171
- hasTouchSupportRef.current = mediaQuery.matches;
172
- setHasTouchSupport(hasTouchSupportRef.current);
173
- return () => {
174
- if (typeof mediaQuery.removeEventListener === 'function') {
175
- mediaQuery.removeEventListener('change', handleMediaQueryChange);
176
- }
177
- else {
178
- mediaQuery.removeListener(handleMediaQueryChange);
179
- }
180
- };
181
- }, [setHasTouchSupport]);
182
- const bindEscapeToClose = useEscapeToClose(() => currentVisible && onCloseRef.current(null));
183
- useEffect(() => {
184
- bindEscapeToClose(document.body);
185
- return () => bindEscapeToClose(null);
186
- }, [bindEscapeToClose]);
187
- // TODO: replace by useInitOnce
188
- const LayoutMetrics = useState(() => {
189
- let cache = {};
190
- return {
191
- get scrollTop() {
192
- return Math.max(-stateRef.current.scrollOffset, 0);
193
- },
194
- get bottomSheetHeight() {
195
- if (!('bottomSheetHeight' in cache) && visualContainerRef.current !== null) {
196
- cache.bottomSheetHeight = visualContainerRef.current.clientHeight;
197
- }
198
- return cache.bottomSheetHeight ?? 0;
199
- },
200
- /**
201
- * Высота контента
202
- * Может превышать высоту контейнера из-за скролла
203
- */
204
- get contentHeight() {
205
- if (!('contentHeight' in cache) && contentRef.current !== null) {
206
- cache.contentHeight = contentRef.current.clientHeight;
207
- }
208
- return cache.contentHeight;
209
- },
210
- /**
211
- * Высота видимой части контента
212
- */
213
- get visibleContentHeight() {
214
- if (!('visibleContentHeight' in cache) && scrollContainerRef.current !== null) {
215
- cache.visibleContentHeight = scrollContainerRef.current.clientHeight - LayoutMetrics.headerHeight;
216
- }
217
- return cache.visibleContentHeight ?? 0;
218
- },
219
- /**
220
- * Положение верхнего края видимой части контента относительно вьюпорта
221
- */
222
- get contentTop() {
223
- if (!('contentTop' in cache) && visualContainerRef.current !== null && contentRef.current !== null) {
224
- cache.contentTop =
225
- contentRef.current.offsetTop - LayoutMetrics.scrollTop + visualContainerRef.current.offsetTop;
226
- }
227
- return cache.contentTop ?? 0;
228
- },
229
- get footerHeight() {
230
- if (!('footerHeight' in cache) && footerRef.current !== null) {
231
- cache.footerHeight = footerRef.current.clientHeight;
232
- }
233
- return cache.footerHeight ?? 0;
234
- },
235
- /**
236
- * Фактическая высота, которую header занимает в боттомшите
237
- * Может отличаться от видимой высоты header
238
- */
239
- get headerHeight() {
240
- if (!('headerHeight' in cache) && headerWrapperRef.current !== null) {
241
- cache.headerHeight = headerWrapperRef.current.offsetHeight;
242
- }
243
- return cache.headerHeight ?? 0;
244
- },
245
- get initialOffset() {
246
- if (!('initialOffset' in cache)) {
247
- if (height === 'half-screen' &&
248
- hasTouchSupportRef.current &&
249
- visualContainerRef.current !== null &&
250
- visualViewport !== null) {
251
- const halfScreenOffset = visualContainerRef.current.clientHeight - visualViewport.height / 2;
252
- cache.initialOffset = Math.max(Math.round(halfScreenOffset), 0);
253
- }
254
- else {
255
- cache.initialOffset = 0;
256
- }
257
- }
258
- return cache.initialOffset ?? 0;
259
- },
260
- get maxScrollTop() {
261
- return LayoutMetrics.contentHeight - LayoutMetrics.visibleContentHeight;
262
- },
263
- /**
264
- * Расстояние между верхним краем боттомшита и границей вьюпорта
265
- */
266
- get remainingAvailableHeight() {
267
- if (!('remainingAvailableHeight' in cache) && grabberRef.current !== null) {
268
- cache.remainingAvailableHeight = grabberRef.current.offsetTop;
269
- }
270
- return cache.remainingAvailableHeight ?? 0;
271
- },
272
- invalidateCache() {
273
- cache = {};
274
- },
275
- };
276
- })[0];
277
- const setCSSVariable = (name, value) => cssVariablesContainerRef.current !== null && cssVariablesContainerRef.current.style.setProperty(name, value);
278
- useEffect(() => {
279
- if (!currentVisible) {
280
- return void 0;
219
+ return cache.contentHeight;
220
+ },
221
+ /**
222
+ * Высота видимой части контента
223
+ */
224
+ get visibleContentHeight() {
225
+ if (!("visibleContentHeight" in cache) && scrollContainerRef.current !== null) {
226
+ cache.visibleContentHeight = scrollContainerRef.current.clientHeight - LayoutMetrics.headerHeight;
281
227
  }
282
- DOCUMENT_HEIGHT.current = document.documentElement.clientHeight;
283
- if (visualViewport !== null) {
284
- SWIPE_THRESHOLD.current = { max: Math.round(visualViewport.height * 0.8) };
285
- VIEWPORT_HEIGHT.current = visualViewport.height;
228
+ return cache.visibleContentHeight ?? 0;
229
+ },
230
+ /**
231
+ * Положение верхнего края видимой части контента относительно вьюпорта
232
+ */
233
+ get contentTop() {
234
+ if (!("contentTop" in cache) && visualContainerRef.current !== null && contentRef.current !== null) {
235
+ cache.contentTop = contentRef.current.offsetTop - LayoutMetrics.scrollTop + visualContainerRef.current.offsetTop;
286
236
  }
287
- if (!showOverlay) {
288
- const enableOverscroll = disableOverscroll();
289
- return enableOverscroll;
237
+ return cache.contentTop ?? 0;
238
+ },
239
+ get footerHeight() {
240
+ if (!("footerHeight" in cache) && footerRef.current !== null) {
241
+ cache.footerHeight = footerRef.current.clientHeight;
290
242
  }
291
- let enableScroll = disableScroll();
292
- return () => {
293
- enableScroll?.(animationTimeoutExitRef.current);
294
- enableScroll = undefined;
295
- };
296
- }, [currentVisible, showOverlay]);
297
- useEffect(() => {
298
- const animationTimeoutElement = document.createElement('div');
299
- animationTimeoutElement.classList.add(styles.animationTimeout);
300
- document.body.appendChild(animationTimeoutElement);
301
- const style = window.getComputedStyle(animationTimeoutElement);
302
- const enter = toNumber(style.getPropertyValue(CSS_VAR_ENTER_ANIMATION_DURATION));
303
- const exit = toNumber(style.getPropertyValue(CSS_VAR_EXIT_ANIMATION_DURATION));
304
- const height = toNumber(style.getPropertyValue(CSS_VAR_HEIGHT_ANIMATION_DURATION));
305
- document.body.removeChild(animationTimeoutElement);
306
- setAnimationTimeout({ appear: { enter, exit }, height: { enter: height, exit } });
307
- }, [setAnimationTimeout]);
308
- useEffect(() => {
309
- if (!currentVisible || isSafari) {
310
- return;
243
+ return cache.footerHeight ?? 0;
244
+ },
245
+ /**
246
+ * Фактическая высота, которую header занимает в боттомшите
247
+ * Может отличаться от видимой высоты header
248
+ */
249
+ get headerHeight() {
250
+ if (!("headerHeight" in cache) && headerWrapperRef.current !== null) {
251
+ cache.headerHeight = headerWrapperRef.current.offsetHeight;
311
252
  }
312
- // включаем настройку interactive-widget=resizes-content,
313
- // чтобы браузеры с поддержкой Virtual Keyboard API ресайзили Visual Viewport при появлении клавиатуры
314
- // в остальных браузерах (Safari и Chrome < 108) это поведение по умолчанию
315
- let meta = document.querySelector('meta[name="viewport"]');
316
- if (!meta) {
317
- meta = document.createElement('meta');
318
- meta.setAttribute('name', 'viewport');
319
- document.head.appendChild(meta);
253
+ return cache.headerHeight ?? 0;
254
+ },
255
+ get initialOffset() {
256
+ if (!("initialOffset" in cache)) {
257
+ if (height === "half-screen" && hasTouchSupportRef.current && visualContainerRef.current !== null && visualViewport !== null) {
258
+ const halfScreenOffset = visualContainerRef.current.clientHeight - visualViewport.height / 2;
259
+ cache.initialOffset = Math.max(Math.round(halfScreenOffset), 0);
260
+ } else {
261
+ cache.initialOffset = 0;
262
+ }
320
263
  }
321
- const attributesStr = meta.getAttribute('content');
322
- const attributes = (attributesStr !== null
323
- ? Object.fromEntries(attributesStr.split(',').map((keyValuePairStr) => keyValuePairStr.split('=')))
324
- : {});
325
- attributes['interactive-widget'] = 'resizes-content';
326
- const attributesStrUpdated = Object.entries(attributes)
327
- .map((keyValuePair) => keyValuePair.join('='))
328
- .join(',');
329
- meta.setAttribute('content', attributesStrUpdated);
330
- }, [currentVisible, isSafari]);
331
- const fixOverscroll = useCallback(() => {
332
- if (hasTouchSupport) {
333
- const isOverscrolled = LayoutMetrics.contentHeight + stateRef.current.scrollOffset < LayoutMetrics.visibleContentHeight;
334
- if (isOverscrolled) {
335
- stateRef.current.scrollOffset = LayoutMetrics.visibleContentHeight - LayoutMetrics.contentHeight;
336
- if (contentRef.current !== null) {
337
- contentRef.current.style.transform = translateY(stateRef.current.scrollOffset);
338
- }
339
- scrollContextProviderRef.current?.notifyScroll({
340
- scrollTop: -stateRef.current.scrollOffset,
341
- maxScrollTop: LayoutMetrics.maxScrollTop,
342
- });
343
- }
264
+ return cache.initialOffset ?? 0;
265
+ },
266
+ get maxScrollTop() {
267
+ return LayoutMetrics.contentHeight - LayoutMetrics.visibleContentHeight;
268
+ },
269
+ /**
270
+ * Расстояние между верхним краем боттомшита и границей вьюпорта
271
+ */
272
+ get remainingAvailableHeight() {
273
+ if (!("remainingAvailableHeight" in cache) && grabberRef.current !== null) {
274
+ cache.remainingAvailableHeight = grabberRef.current.offsetTop;
344
275
  }
345
- }, [hasTouchSupport, LayoutMetrics]);
346
- const resetScrollPosition = useCallback(() => {
347
- if (hasTouchSupport) {
348
- stateRef.current.scrollOffset = LayoutMetrics.initialOffset;
349
- stateRef.current.swipeOffset = 0;
350
- if (contentRef.current !== null) {
351
- contentRef.current.style.transform = translateY(0);
352
- }
353
- if (swipeContainerRef.current !== null) {
354
- swipeContainerRef.current.style.transform = translateY(LayoutMetrics.initialOffset);
355
- }
356
- }
357
- else {
358
- scrollContainerRef.current?.scrollTo({ top: 0 });
276
+ return cache.remainingAvailableHeight ?? 0;
277
+ },
278
+ invalidateCache() {
279
+ cache = {};
280
+ }
281
+ };
282
+ })[0];
283
+ const setCSSVariable = (name, value) => cssVariablesContainerRef.current !== null && cssVariablesContainerRef.current.style.setProperty(name, value);
284
+ useEffect(() => {
285
+ if (!currentVisible) {
286
+ return void 0;
287
+ }
288
+ DOCUMENT_HEIGHT.current = document.documentElement.clientHeight;
289
+ if (visualViewport !== null) {
290
+ SWIPE_THRESHOLD.current = { max: Math.round(visualViewport.height * 0.8) };
291
+ VIEWPORT_HEIGHT.current = visualViewport.height;
292
+ }
293
+ if (!showOverlay) {
294
+ const enableOverscroll = disableOverscroll();
295
+ return enableOverscroll;
296
+ }
297
+ let enableScroll = disableScroll();
298
+ return () => {
299
+ enableScroll?.(animationTimeoutExitRef.current);
300
+ enableScroll = void 0;
301
+ };
302
+ }, [currentVisible, showOverlay]);
303
+ useEffect(() => {
304
+ const animationTimeoutElement = document.createElement("div");
305
+ animationTimeoutElement.classList.add(styles.animationTimeout);
306
+ document.body.appendChild(animationTimeoutElement);
307
+ const style = window.getComputedStyle(animationTimeoutElement);
308
+ const enter = toNumber(style.getPropertyValue(CSS_VAR_ENTER_ANIMATION_DURATION));
309
+ const exit = toNumber(style.getPropertyValue(CSS_VAR_EXIT_ANIMATION_DURATION));
310
+ const height2 = toNumber(style.getPropertyValue(CSS_VAR_HEIGHT_ANIMATION_DURATION));
311
+ document.body.removeChild(animationTimeoutElement);
312
+ setAnimationTimeout({ appear: { enter, exit }, height: { enter: height2, exit } });
313
+ }, [setAnimationTimeout]);
314
+ useEffect(() => {
315
+ if (!currentVisible || isSafari) {
316
+ return;
317
+ }
318
+ let meta = document.querySelector('meta[name="viewport"]');
319
+ if (!meta) {
320
+ meta = document.createElement("meta");
321
+ meta.setAttribute("name", "viewport");
322
+ document.head.appendChild(meta);
323
+ }
324
+ const attributesStr = meta.getAttribute("content");
325
+ const attributes = attributesStr !== null ? Object.fromEntries(attributesStr.split(",").map((keyValuePairStr) => keyValuePairStr.split("="))) : {};
326
+ attributes["interactive-widget"] = "resizes-content";
327
+ const attributesStrUpdated = Object.entries(attributes).map((keyValuePair) => keyValuePair.join("=")).join(",");
328
+ meta.setAttribute("content", attributesStrUpdated);
329
+ }, [currentVisible, isSafari]);
330
+ const fixOverscroll = useCallback(() => {
331
+ if (hasTouchSupport) {
332
+ const isOverscrolled = LayoutMetrics.contentHeight + stateRef.current.scrollOffset < LayoutMetrics.visibleContentHeight;
333
+ if (isOverscrolled) {
334
+ stateRef.current.scrollOffset = LayoutMetrics.visibleContentHeight - LayoutMetrics.contentHeight;
335
+ if (contentRef.current !== null) {
336
+ contentRef.current.style.transform = translateY(stateRef.current.scrollOffset);
359
337
  }
360
- }, [hasTouchSupport, LayoutMetrics]);
361
- const recalcScrollFlags = useCallback(() => {
362
- const scrollOffset = hasTouchSupport
363
- ? stateRef.current.scrollOffset
364
- : -(scrollContainerRef.current?.scrollTop ?? 0);
365
- if (dividerRef.current !== null) {
366
- const prevDividerVisible = stateRef.current.dividerVisible;
367
- const isNotScrolledToEnd = LayoutMetrics.contentHeight + scrollOffset > LayoutMetrics.visibleContentHeight;
368
- stateRef.current.dividerVisible =
369
- showDivider === 'always' || (showDivider === 'with-scroll' && isNotScrolledToEnd);
370
- if (stateRef.current.dividerVisible !== prevDividerVisible) {
371
- dividerRef.current.classList.toggle(styles.dividerVisible, stateRef.current.dividerVisible);
372
- }
338
+ scrollContextProviderRef.current?.notifyScroll({
339
+ scrollTop: -stateRef.current.scrollOffset,
340
+ maxScrollTop: LayoutMetrics.maxScrollTop
341
+ });
342
+ }
343
+ }
344
+ }, [hasTouchSupport, LayoutMetrics]);
345
+ const resetScrollPosition = useCallback(() => {
346
+ if (hasTouchSupport) {
347
+ stateRef.current.scrollOffset = LayoutMetrics.initialOffset;
348
+ stateRef.current.swipeOffset = 0;
349
+ if (contentRef.current !== null) {
350
+ contentRef.current.style.transform = translateY(0);
351
+ }
352
+ if (swipeContainerRef.current !== null) {
353
+ swipeContainerRef.current.style.transform = translateY(LayoutMetrics.initialOffset);
354
+ }
355
+ } else {
356
+ scrollContainerRef.current?.scrollTo({ top: 0 });
357
+ }
358
+ }, [hasTouchSupport, LayoutMetrics]);
359
+ const recalcScrollFlags = useCallback(() => {
360
+ const scrollOffset = hasTouchSupport ? stateRef.current.scrollOffset : -(scrollContainerRef.current?.scrollTop ?? 0);
361
+ if (dividerRef.current !== null) {
362
+ const prevDividerVisible = stateRef.current.dividerVisible;
363
+ const isNotScrolledToEnd = LayoutMetrics.contentHeight + scrollOffset > LayoutMetrics.visibleContentHeight;
364
+ stateRef.current.dividerVisible = showDivider === "always" || showDivider === "with-scroll" && isNotScrolledToEnd;
365
+ if (stateRef.current.dividerVisible !== prevDividerVisible) {
366
+ dividerRef.current.classList.toggle(styles.dividerVisible, stateRef.current.dividerVisible);
367
+ }
368
+ }
369
+ if (grabberRef.current !== null && stateRef.current.touchAction === null) {
370
+ const prevGrabberUnsafe = stateRef.current.grabberUnsafe;
371
+ stateRef.current.grabberUnsafe = Math.round(Math.max(scrollOffset, 0) + stateRef.current.swipeOffset) === LayoutMetrics.remainingAvailableHeight;
372
+ if (stateRef.current.grabberUnsafe !== prevGrabberUnsafe) {
373
+ grabberRef.current.classList.toggle(styles.grabberEnsureSafe, stateRef.current.grabberUnsafe);
374
+ }
375
+ }
376
+ }, [hasTouchSupport, showDivider, LayoutMetrics]);
377
+ const recalcKeyboardOffsets = useCallback(() => {
378
+ if (!hasTouchSupport || !contentRef.current || !overlayRef.current || !swipeContainerRef.current || !visualViewport) {
379
+ return;
380
+ }
381
+ if (LayoutMetrics.initialOffset > 0 && stateRef.current.scrollOffset > 0) {
382
+ stateRef.current.scrollOffset = 0;
383
+ contentRef.current.style.transform = translateY(0);
384
+ swipeContainerRef.current.style.transform = translateY(0);
385
+ if (footerRef.current !== null) {
386
+ footerRef.current.style.transform = translateY(0);
387
+ }
388
+ }
389
+ LayoutMetrics.invalidateCache();
390
+ const isKeyboardVisible = visualViewport.height !== VIEWPORT_HEIGHT.current;
391
+ if (stateRef.current.hasFocus && focusedElementRef.current !== null && isKeyboardVisible) {
392
+ const overlayDOMRect = overlayRef.current.getBoundingClientRect();
393
+ const topOffset = Math.round(-overlayDOMRect.top);
394
+ let bottomOffset = 0;
395
+ if (isSafari) {
396
+ const visualViewportDiff = Math.round(overlayDOMRect.bottom - visualViewport.height);
397
+ if (visualViewportDiff > 0) {
398
+ bottomOffset = visualViewportDiff;
373
399
  }
374
- if (grabberRef.current !== null && stateRef.current.touchAction === null) {
375
- const prevGrabberUnsafe = stateRef.current.grabberUnsafe;
376
- stateRef.current.grabberUnsafe =
377
- Math.round(Math.max(scrollOffset, 0) + stateRef.current.swipeOffset) ===
378
- LayoutMetrics.remainingAvailableHeight;
379
- if (stateRef.current.grabberUnsafe !== prevGrabberUnsafe) {
380
- grabberRef.current.classList.toggle(styles.grabberEnsureSafe, stateRef.current.grabberUnsafe);
381
- }
400
+ }
401
+ if (keyboardOverlaysFooter && footerRef.current !== null) {
402
+ bottomOffset -= footerRef.current.clientHeight;
403
+ }
404
+ if (topOffset !== virtualKeyboardOffsetsRef.current.top || bottomOffset !== virtualKeyboardOffsetsRef.current.bottom) {
405
+ setCSSVariable(CSS_VAR_VIRTUAL_KEYBOARD_TOP_OFFSET, `${topOffset}px`);
406
+ setCSSVariable(CSS_VAR_VIRTUAL_KEYBOARD_BOTTOM_OFFSET, `${bottomOffset}px`);
407
+ }
408
+ LayoutMetrics.invalidateCache();
409
+ if (contentRef.current.contains(focusedElementRef.current)) {
410
+ let focusedElementOffset = 0;
411
+ for (let offsetElement = focusedElementRef.current.closest("[data-interactive]") ?? focusedElementRef.current; offsetElement !== contentRef.current && offsetElement !== null; offsetElement = offsetElement.offsetParent) {
412
+ focusedElementOffset += offsetElement.offsetTop;
382
413
  }
383
- }, [hasTouchSupport, showDivider, LayoutMetrics]);
384
- // терминология: https://developer.chrome.com/blog/viewport-resize-behavior/
385
- //
386
- // при открытии виртуальной клавиатуры браузеры двигают Visual Viewport и Layout Viewport
387
- // с помощью двух отступов делаем так, чтобы overlay боттомшита совпадал с видимой частью экрана
388
- const recalcKeyboardOffsets = useCallback(() => {
389
- if (!hasTouchSupport ||
390
- !contentRef.current ||
391
- !overlayRef.current ||
392
- !swipeContainerRef.current ||
393
- !visualViewport) {
394
- return;
414
+ const newScrollOffset = -Math.min(Math.max(focusedElementOffset - 10, 0), LayoutMetrics.maxScrollTop);
415
+ if (stateRef.current.scrollOffset !== newScrollOffset) {
416
+ stateRef.current.scrollOffset = newScrollOffset;
417
+ contentRef.current.style.transform = translateY(stateRef.current.scrollOffset);
418
+ scrollContextProviderRef.current?.notifyScroll({
419
+ scrollTop: -stateRef.current.scrollOffset,
420
+ maxScrollTop: LayoutMetrics.maxScrollTop
421
+ });
395
422
  }
396
- // разворачиваем боттомшит с height=half-screen на всю доступную высоту
397
- if (LayoutMetrics.initialOffset > 0 && stateRef.current.scrollOffset > 0) {
398
- stateRef.current.scrollOffset = 0;
399
- contentRef.current.style.transform = translateY(0);
400
- swipeContainerRef.current.style.transform = translateY(0);
401
- if (footerRef.current !== null) {
402
- footerRef.current.style.transform = translateY(0);
403
- }
423
+ }
424
+ recalcScrollFlags();
425
+ virtualKeyboardOffsetsRef.current.top = topOffset;
426
+ virtualKeyboardOffsetsRef.current.bottom = bottomOffset;
427
+ } else {
428
+ setCSSVariable(CSS_VAR_VIRTUAL_KEYBOARD_TOP_OFFSET, `0px`);
429
+ setCSSVariable(CSS_VAR_VIRTUAL_KEYBOARD_BOTTOM_OFFSET, `0px`);
430
+ LayoutMetrics.invalidateCache();
431
+ fixOverscroll();
432
+ recalcScrollFlags();
433
+ virtualKeyboardOffsetsRef.current.top = 0;
434
+ virtualKeyboardOffsetsRef.current.bottom = 0;
435
+ }
436
+ stateRef.current.skipHeightAnimation = true;
437
+ setTimeout(() => stateRef.current.skipHeightAnimation = false, 100);
438
+ bottomSheetContext.keyboardResizeHandlers.forEach((handler) => handler());
439
+ }, [
440
+ fixOverscroll,
441
+ hasTouchSupport,
442
+ isSafari,
443
+ keyboardOverlaysFooter,
444
+ recalcScrollFlags,
445
+ bottomSheetContext,
446
+ LayoutMetrics
447
+ ]);
448
+ const handleFocus = useCallback(
449
+ (event) => {
450
+ const focusedElement = event.target;
451
+ const initialViewportHeight = visualViewport?.height;
452
+ const resizeRAFStart = performance.now();
453
+ if (!isTextInputElement(focusedElement) || stateRef.current.resizeRAFHandle !== null) {
454
+ return;
455
+ }
456
+ const handleResize = () => {
457
+ if (stateRef.current.resizeRAFHandle !== null) {
458
+ cancelAnimationFrame(stateRef.current.resizeRAFHandle);
459
+ stateRef.current.resizeRAFHandle = null;
404
460
  }
405
- LayoutMetrics.invalidateCache();
406
- const isKeyboardVisible = visualViewport.height !== VIEWPORT_HEIGHT.current;
407
- if (stateRef.current.hasFocus && focusedElementRef.current !== null && isKeyboardVisible) {
408
- const overlayDOMRect = overlayRef.current.getBoundingClientRect();
409
- // любой браузер может сдвинуть Visual Viewport вверх, если фокусируемый инпут находится близко к нижней границе
410
- // из-за этого может возникнуть проблема, что ВЕРХНИЙ край контента уехал за границу Visual Viewport
411
- // сдвигаем ВЕРХНИЙ край контейнера ВНИЗ, чтобы он совпал с границей Visual Viewport
412
- const topOffset = Math.round(-overlayDOMRect.top);
413
- let bottomOffset = 0;
414
- if (isSafari) {
415
- const visualViewportDiff = Math.round(overlayDOMRect.bottom - visualViewport.height);
416
- if (visualViewportDiff > 0) {
417
- // сдвигаем НИЖНИЙ край контейнера ВВЕРХ, чтобы он совпал с границей Visual Viewport
418
- bottomOffset = visualViewportDiff;
419
- }
420
- }
421
- if (keyboardOverlaysFooter && footerRef.current !== null) {
422
- bottomOffset -= footerRef.current.clientHeight;
423
- }
424
- if (topOffset !== virtualKeyboardOffsetsRef.current.top ||
425
- bottomOffset !== virtualKeyboardOffsetsRef.current.bottom) {
426
- setCSSVariable(CSS_VAR_VIRTUAL_KEYBOARD_TOP_OFFSET, `${topOffset}px`);
427
- setCSSVariable(CSS_VAR_VIRTUAL_KEYBOARD_BOTTOM_OFFSET, `${bottomOffset}px`);
428
- }
429
- LayoutMetrics.invalidateCache();
430
- // если фокусируемый элемент лежит внутри скроллящегося контейнера и не виден, скроллим к нему
431
- if (contentRef.current.contains(focusedElementRef.current)) {
432
- let focusedElementOffset = 0;
433
- for (let offsetElement = focusedElementRef.current.closest('[data-interactive]') ?? focusedElementRef.current; offsetElement !== contentRef.current && offsetElement !== null; offsetElement = offsetElement.offsetParent) {
434
- focusedElementOffset += offsetElement.offsetTop;
435
- }
436
- const newScrollOffset = -Math.min(Math.max(focusedElementOffset - 10, 0), LayoutMetrics.maxScrollTop);
437
- if (stateRef.current.scrollOffset !== newScrollOffset) {
438
- stateRef.current.scrollOffset = newScrollOffset;
439
- contentRef.current.style.transform = translateY(stateRef.current.scrollOffset);
440
- scrollContextProviderRef.current?.notifyScroll({
441
- scrollTop: -stateRef.current.scrollOffset,
442
- maxScrollTop: LayoutMetrics.maxScrollTop,
443
- });
444
- }
445
- }
446
- recalcScrollFlags();
447
- virtualKeyboardOffsetsRef.current.top = topOffset;
448
- virtualKeyboardOffsetsRef.current.bottom = bottomOffset;
461
+ recalcKeyboardOffsets();
462
+ if (!stateRef.current.hasFocus) {
463
+ visualViewport?.removeEventListener("resize", handleResize);
464
+ visualViewport?.removeEventListener("scroll", handleResize);
449
465
  }
450
- else {
451
- setCSSVariable(CSS_VAR_VIRTUAL_KEYBOARD_TOP_OFFSET, `0px`);
452
- setCSSVariable(CSS_VAR_VIRTUAL_KEYBOARD_BOTTOM_OFFSET, `0px`);
453
- LayoutMetrics.invalidateCache();
454
- fixOverscroll();
455
- recalcScrollFlags();
456
- virtualKeyboardOffsetsRef.current.top = 0;
457
- virtualKeyboardOffsetsRef.current.bottom = 0;
466
+ };
467
+ const waitForResize = () => {
468
+ if (performance.now() - resizeRAFStart > 1e3 || visualViewport?.height !== initialViewportHeight) {
469
+ visualViewport?.removeEventListener("resize", handleResize);
470
+ visualViewport?.removeEventListener("scroll", handleResize);
471
+ stateRef.current.resizeRAFHandle = null;
472
+ recalcKeyboardOffsets();
473
+ } else {
474
+ stateRef.current.resizeRAFHandle = requestAnimationFrame(waitForResize);
458
475
  }
459
- stateRef.current.skipHeightAnimation = true;
460
- setTimeout(() => (stateRef.current.skipHeightAnimation = false), 100);
461
- bottomSheetContext.keyboardResizeHandlers.forEach((handler) => handler());
462
- }, [
463
- fixOverscroll,
464
- hasTouchSupport,
465
- isSafari,
466
- keyboardOverlaysFooter,
467
- recalcScrollFlags,
468
- bottomSheetContext,
469
- LayoutMetrics,
470
- ]);
471
- const handleFocus = useCallback((event) => {
472
- const focusedElement = event.target;
473
- const initialViewportHeight = visualViewport?.height;
474
- const resizeRAFStart = performance.now();
475
- if (!isTextInputElement(focusedElement) || stateRef.current.resizeRAFHandle !== null) {
476
- return;
476
+ };
477
+ const handleBlur = () => {
478
+ stateRef.current.hasFocus = false;
479
+ if (stateRef.current.resizeRAFHandle !== null) {
480
+ cancelAnimationFrame(stateRef.current.resizeRAFHandle);
481
+ stateRef.current.resizeRAFHandle = null;
477
482
  }
478
- const handleResize = () => {
479
- if (stateRef.current.resizeRAFHandle !== null) {
480
- cancelAnimationFrame(stateRef.current.resizeRAFHandle);
481
- stateRef.current.resizeRAFHandle = null;
482
- }
483
- recalcKeyboardOffsets();
484
- if (!stateRef.current.hasFocus) {
485
- visualViewport?.removeEventListener('resize', handleResize);
486
- visualViewport?.removeEventListener('scroll', handleResize);
487
- }
488
- };
489
- // если спамить фокус/блюр инпута, ивент visualViewport.resize может не долететь
490
- // поэтому проверяем изменение высоты в рекурсивном RAF
491
- const waitForResize = () => {
492
- if (performance.now() - resizeRAFStart > 1000 || visualViewport?.height !== initialViewportHeight) {
493
- visualViewport?.removeEventListener('resize', handleResize);
494
- visualViewport?.removeEventListener('scroll', handleResize);
495
- stateRef.current.resizeRAFHandle = null;
496
- recalcKeyboardOffsets();
497
- }
498
- else {
499
- stateRef.current.resizeRAFHandle = requestAnimationFrame(waitForResize);
500
- }
501
- };
502
- const handleBlur = () => {
503
- stateRef.current.hasFocus = false;
504
- if (stateRef.current.resizeRAFHandle !== null) {
505
- cancelAnimationFrame(stateRef.current.resizeRAFHandle);
506
- stateRef.current.resizeRAFHandle = null;
507
- }
508
- focusedElement.removeEventListener('blur', handleBlur);
509
- focusedElementRef.current = null;
510
- if (isSafari) {
511
- recalcKeyboardOffsets();
512
- }
513
- };
514
- stateRef.current.hasFocus = true;
515
- stateRef.current.resizeRAFHandle = requestAnimationFrame(waitForResize);
516
- visualViewport?.addEventListener('resize', handleResize);
517
- // событие scroll может прилететь, только если браузер сдвинул вьюпорт из-за появления виртуальной клавиатуры
518
- // пользовательский скролл не вызывает событие scroll, т.к. нативный скролл отключен
519
- // в Safari событие resize может прилететь до того как браузер сдвинул вьюпорт, поэтому слушаем scroll
483
+ focusedElement.removeEventListener("blur", handleBlur);
484
+ focusedElementRef.current = null;
520
485
  if (isSafari) {
521
- visualViewport?.addEventListener('scroll', handleResize);
522
- }
523
- focusedElement.addEventListener('blur', handleBlur);
524
- focusedElementRef.current = focusedElement;
525
- }, [isSafari, recalcKeyboardOffsets]);
526
- // contentOverlay совпадает по границам с контентом боттомшита, но лежит вне боттомшита,
527
- // чтобы чайлды contentOverlay не обрезались границами боттомшита
528
- // например, снекбар, лежащий внутри contentOverlay, при смахивании может оказаться в любом месте экрана
529
- // поэтому позицию contentOverlay нужно синхронизировать
530
- const recalcContentOverlayPosition = useCallback(() => {
531
- if (contentOverlayRef.current !== null &&
532
- scrollContainerRef.current !== null &&
533
- visualContainerRef.current !== null) {
534
- contentOverlayRef.current.style.top = `${LayoutMetrics.contentTop}px`;
535
- contentOverlayRef.current.style.height = `${LayoutMetrics.visibleContentHeight}px`;
536
- }
537
- }, [LayoutMetrics]);
538
- // помещает боттомшит в позицию вне экрана снизу, которая может быть начальной либо конечной точкой анимации
539
- const setTransformToInvisible = useCallback(() => {
540
- LayoutMetrics.invalidateCache();
541
- if (overlayRef.current !== null) {
542
- overlayRef.current.style.opacity = `0`;
486
+ recalcKeyboardOffsets();
543
487
  }
544
- if (swipeContainerRef.current !== null) {
545
- swipeContainerRef.current.style.transform = translateY(LayoutMetrics.bottomSheetHeight);
546
- }
547
- requestAnimationFrame(recalcContentOverlayPosition);
548
- requestAnimationFrame(recalcScrollFlags);
549
- }, [recalcContentOverlayPosition, recalcScrollFlags, LayoutMetrics]);
550
- // помещает боттомшит в дефолтную позицию на экране, которая может быть начальной либо конечной точкой анимации
551
- const setTransformToVisible = useCallback(() => {
552
- LayoutMetrics.invalidateCache();
553
- stateRef.current.scrollOffset = LayoutMetrics.initialOffset;
554
- if (overlayRef.current !== null) {
555
- overlayRef.current.style.opacity = `1`;
488
+ };
489
+ stateRef.current.hasFocus = true;
490
+ stateRef.current.resizeRAFHandle = requestAnimationFrame(waitForResize);
491
+ visualViewport?.addEventListener("resize", handleResize);
492
+ if (isSafari) {
493
+ visualViewport?.addEventListener("scroll", handleResize);
494
+ }
495
+ focusedElement.addEventListener("blur", handleBlur);
496
+ focusedElementRef.current = focusedElement;
497
+ },
498
+ [isSafari, recalcKeyboardOffsets]
499
+ );
500
+ const recalcContentOverlayPosition = useCallback(() => {
501
+ if (contentOverlayRef.current !== null && scrollContainerRef.current !== null && visualContainerRef.current !== null) {
502
+ contentOverlayRef.current.style.top = `${LayoutMetrics.contentTop}px`;
503
+ contentOverlayRef.current.style.height = `${LayoutMetrics.visibleContentHeight}px`;
504
+ }
505
+ }, [LayoutMetrics]);
506
+ const setTransformToInvisible = useCallback(() => {
507
+ LayoutMetrics.invalidateCache();
508
+ if (overlayRef.current !== null) {
509
+ overlayRef.current.style.opacity = `0`;
510
+ }
511
+ if (swipeContainerRef.current !== null) {
512
+ swipeContainerRef.current.style.transform = translateY(LayoutMetrics.bottomSheetHeight);
513
+ }
514
+ requestAnimationFrame(recalcContentOverlayPosition);
515
+ requestAnimationFrame(recalcScrollFlags);
516
+ }, [recalcContentOverlayPosition, recalcScrollFlags, LayoutMetrics]);
517
+ const setTransformToVisible = useCallback(() => {
518
+ LayoutMetrics.invalidateCache();
519
+ stateRef.current.scrollOffset = LayoutMetrics.initialOffset;
520
+ if (overlayRef.current !== null) {
521
+ overlayRef.current.style.opacity = `1`;
522
+ }
523
+ if (swipeContainerRef.current !== null) {
524
+ swipeContainerRef.current.style.transform = translateY(
525
+ LayoutMetrics.initialOffset + stateRef.current.swipeOffset
526
+ );
527
+ }
528
+ if (footerRef.current !== null) {
529
+ footerRef.current.style.transform = translateY(-LayoutMetrics.initialOffset);
530
+ }
531
+ requestAnimationFrame(recalcContentOverlayPosition);
532
+ requestAnimationFrame(recalcScrollFlags);
533
+ }, [recalcContentOverlayPosition, recalcScrollFlags, LayoutMetrics]);
534
+ const handleExitAnimationStart = useCallback(() => {
535
+ setTransformToVisible();
536
+ onBeforeExit?.();
537
+ }, [setTransformToVisible, onBeforeExit]);
538
+ const handleExitAnimationEnd = useCallback(() => {
539
+ setCSSVariable(CSS_VAR_VIRTUAL_KEYBOARD_TOP_OFFSET, `0px`);
540
+ setCSSVariable(CSS_VAR_VIRTUAL_KEYBOARD_BOTTOM_OFFSET, `0px`);
541
+ stateRef.current.resizeRAFHandle !== null && cancelAnimationFrame(stateRef.current.resizeRAFHandle);
542
+ stateRef.current.exitHandlers.forEach((handler) => handler());
543
+ stateRef.current = makeInitialState();
544
+ onAfterExit?.();
545
+ }, [onAfterExit]);
546
+ const handleHeightAnimationStart = useCallback(() => {
547
+ LayoutMetrics.invalidateCache();
548
+ if (stateRef.current.heightAnimationValue !== null && visualContainerRef.current !== null) {
549
+ visualContainerRef.current.style.height = `${stateRef.current.heightAnimationValue}px`;
550
+ }
551
+ }, [LayoutMetrics]);
552
+ const handleHeightAnimationEnd = useCallback(() => {
553
+ LayoutMetrics.invalidateCache();
554
+ if (visualContainerRef.current !== null) {
555
+ visualContainerRef.current.style.height = `${LayoutMetrics.bottomSheetHeight}px`;
556
+ }
557
+ stateRef.current.heightAnimationValue = null;
558
+ stateRef.current.heightAnimationCallback && requestAnimationFrame(stateRef.current.heightAnimationCallback);
559
+ stateRef.current.heightAnimationCallback = null;
560
+ setHeightAnimationRunning(false);
561
+ requestAnimationFrame(recalcContentOverlayPosition);
562
+ requestAnimationFrame(recalcScrollFlags);
563
+ scrollContextProviderRef.current?.notifyScroll({
564
+ scrollTop: 0,
565
+ maxScrollTop: LayoutMetrics.maxScrollTop
566
+ });
567
+ }, [setHeightAnimationRunning, recalcContentOverlayPosition, recalcScrollFlags, LayoutMetrics]);
568
+ const handleSwipeMove = useCallback(
569
+ (event) => {
570
+ if (stateRef.current.touchAction !== null && stateRef.current.touchAction !== "swipe" || hasSelectedText()) {
571
+ return;
572
+ }
573
+ let newSwipeOffset = stateRef.current.swipeOffset + event.deltaY;
574
+ if (Math.round(newSwipeOffset) <= 0) {
575
+ newSwipeOffset = 0;
576
+ if (stateRef.current.touchAction === "swipe") {
577
+ stateRef.current.touchAction = "complete";
556
578
  }
579
+ } else {
580
+ stateRef.current.touchAction = "swipe";
581
+ }
582
+ if (stateRef.current.swipeOffset !== newSwipeOffset) {
583
+ stateRef.current.swipeOffset = newSwipeOffset;
557
584
  if (swipeContainerRef.current !== null) {
558
- swipeContainerRef.current.style.transform = translateY(LayoutMetrics.initialOffset + stateRef.current.swipeOffset);
559
- }
560
- if (footerRef.current !== null) {
561
- footerRef.current.style.transform = translateY(-LayoutMetrics.initialOffset);
562
- }
563
- requestAnimationFrame(recalcContentOverlayPosition);
564
- requestAnimationFrame(recalcScrollFlags);
565
- }, [recalcContentOverlayPosition, recalcScrollFlags, LayoutMetrics]);
566
- const handleExitAnimationStart = useCallback(() => {
567
- setTransformToVisible();
568
- onBeforeExit?.();
569
- }, [setTransformToVisible, onBeforeExit]);
570
- const handleExitAnimationEnd = useCallback(() => {
571
- setCSSVariable(CSS_VAR_VIRTUAL_KEYBOARD_TOP_OFFSET, `0px`);
572
- setCSSVariable(CSS_VAR_VIRTUAL_KEYBOARD_BOTTOM_OFFSET, `0px`);
573
- stateRef.current.resizeRAFHandle !== null && cancelAnimationFrame(stateRef.current.resizeRAFHandle);
574
- stateRef.current.exitHandlers.forEach((handler) => handler());
575
- stateRef.current = makeInitialState();
576
- onAfterExit?.();
577
- }, [onAfterExit]);
578
- const handleHeightAnimationStart = useCallback(() => {
579
- LayoutMetrics.invalidateCache();
580
- if (stateRef.current.heightAnimationValue !== null && visualContainerRef.current !== null) {
581
- visualContainerRef.current.style.height = `${stateRef.current.heightAnimationValue}px`;
582
- }
583
- }, [LayoutMetrics]);
584
- const handleHeightAnimationEnd = useCallback(() => {
585
- LayoutMetrics.invalidateCache();
586
- if (visualContainerRef.current !== null) {
587
- visualContainerRef.current.style.height = `${LayoutMetrics.bottomSheetHeight}px`;
588
- }
589
- stateRef.current.heightAnimationValue = null;
590
- stateRef.current.heightAnimationCallback && requestAnimationFrame(stateRef.current.heightAnimationCallback);
591
- stateRef.current.heightAnimationCallback = null;
592
- setHeightAnimationRunning(false);
593
- requestAnimationFrame(recalcContentOverlayPosition);
594
- requestAnimationFrame(recalcScrollFlags);
595
- scrollContextProviderRef.current?.notifyScroll({
596
- scrollTop: 0,
597
- maxScrollTop: LayoutMetrics.maxScrollTop,
598
- });
599
- }, [setHeightAnimationRunning, recalcContentOverlayPosition, recalcScrollFlags, LayoutMetrics]);
600
- const handleSwipeMove = useCallback((event) => {
601
- if ((stateRef.current.touchAction !== null && stateRef.current.touchAction !== 'swipe') ||
602
- hasSelectedText()) {
603
- return;
604
- }
605
- // храним неокругленное значение для translateY, чтобы анимация была плавнее
606
- let newSwipeOffset = stateRef.current.swipeOffset + event.deltaY;
607
- if (Math.round(newSwipeOffset) <= 0) {
608
- // боттомшит уперся в верхний край экрана, не даем свайпать дальше
609
- newSwipeOffset = 0;
610
- if (stateRef.current.touchAction === 'swipe') {
611
- stateRef.current.touchAction = 'complete';
612
- }
585
+ swipeContainerRef.current.style.transform = translateY(
586
+ Math.max(stateRef.current.scrollOffset, 0) + newSwipeOffset
587
+ );
613
588
  }
614
- else {
615
- // свайп в процессе
616
- stateRef.current.touchAction = 'swipe';
617
- }
618
- if (stateRef.current.swipeOffset !== newSwipeOffset) {
619
- stateRef.current.swipeOffset = newSwipeOffset;
620
- if (swipeContainerRef.current !== null) {
621
- swipeContainerRef.current.style.transform = translateY(Math.max(stateRef.current.scrollOffset, 0) + newSwipeOffset);
622
- }
623
- recalcScrollFlags();
624
- }
625
- }, [recalcScrollFlags]);
626
- const handleSwipeCancel = useCallback(() => {
627
- if (stateRef.current.touchAction === 'swipe') {
628
- stateRef.current.swipeOffset = 0;
629
- stateRef.current.touchAction = null;
630
- if (swipeContainerRef.current !== null) {
631
- swipeContainerRef.current.classList.add(styles.swipeCancelAnimation);
632
- const swipeContainer = swipeContainerRef.current;
633
- setTimeout(() => swipeContainer.classList.remove(styles.swipeCancelAnimation), 100);
634
- swipeContainerRef.current.style.transform = translateY(Math.max(stateRef.current.scrollOffset, 0));
635
- }
636
- recalcScrollFlags();
589
+ recalcScrollFlags();
590
+ }
591
+ },
592
+ [recalcScrollFlags]
593
+ );
594
+ const handleSwipeCancel = useCallback(() => {
595
+ if (stateRef.current.touchAction === "swipe") {
596
+ stateRef.current.swipeOffset = 0;
597
+ stateRef.current.touchAction = null;
598
+ if (swipeContainerRef.current !== null) {
599
+ swipeContainerRef.current.classList.add(styles.swipeCancelAnimation);
600
+ const swipeContainer = swipeContainerRef.current;
601
+ setTimeout(() => swipeContainer.classList.remove(styles.swipeCancelAnimation), 100);
602
+ swipeContainerRef.current.style.transform = translateY(Math.max(stateRef.current.scrollOffset, 0));
603
+ }
604
+ recalcScrollFlags();
605
+ }
606
+ }, [recalcScrollFlags]);
607
+ const handleSwipeEnd = useCallback(() => {
608
+ if (stateRef.current.touchAction === "swipe") {
609
+ let onCloseCancelled = false;
610
+ const cancelCloseFunc = () => {
611
+ if (!onCloseCancelled) {
612
+ handleSwipeCancel();
613
+ onCloseCancelled = true;
637
614
  }
638
- }, [recalcScrollFlags]);
639
- const handleSwipeEnd = useCallback(() => {
640
- if (stateRef.current.touchAction === 'swipe') {
641
- let onCloseCancelled = false;
642
- const cancelCloseFunc = () => {
643
- if (!onCloseCancelled) {
644
- handleSwipeCancel();
645
- onCloseCancelled = true;
646
- }
647
- };
648
- onCloseRef.current(cancelCloseFunc);
615
+ };
616
+ onCloseRef.current(cancelCloseFunc);
617
+ }
618
+ }, [handleSwipeCancel]);
619
+ const swipeHandlers = useSwipeHandlers({
620
+ thresholdYRef: SWIPE_THRESHOLD,
621
+ onSwipeMove: handleSwipeMove,
622
+ onSwipeEnd: handleSwipeEnd,
623
+ onSwipeCancel: handleSwipeCancel
624
+ });
625
+ const handleScroll = useCallback(
626
+ (delta) => {
627
+ if (LayoutMetrics.initialOffset !== 0 || LayoutMetrics.contentHeight > LayoutMetrics.visibleContentHeight) {
628
+ let newScrollOffset = stateRef.current.scrollOffset + delta;
629
+ const roundedNewScrollOffset = Math.round(newScrollOffset);
630
+ if (roundedNewScrollOffset >= LayoutMetrics.initialOffset) {
631
+ newScrollOffset = LayoutMetrics.initialOffset;
632
+ if (stateRef.current.touchAction === "scroll") {
633
+ stateRef.current.touchAction = "complete";
634
+ }
635
+ } else if (LayoutMetrics.contentHeight + roundedNewScrollOffset <= LayoutMetrics.visibleContentHeight) {
636
+ newScrollOffset = LayoutMetrics.visibleContentHeight - LayoutMetrics.contentHeight;
637
+ if (stateRef.current.touchAction === "scroll") {
638
+ stateRef.current.touchAction = "complete";
639
+ }
640
+ } else {
641
+ stateRef.current.touchAction = "scroll";
649
642
  }
650
- }, [handleSwipeCancel]);
651
- const swipeHandlers = useSwipeHandlers({
652
- thresholdYRef: SWIPE_THRESHOLD,
653
- onSwipeMove: handleSwipeMove,
654
- onSwipeEnd: handleSwipeEnd,
655
- onSwipeCancel: handleSwipeCancel,
656
- });
657
- const handleScroll = useCallback((delta) => {
658
- if (LayoutMetrics.initialOffset !== 0 || LayoutMetrics.contentHeight > LayoutMetrics.visibleContentHeight) {
659
- // храним неокругленное значение для translateY, чтобы анимация была плавнее
660
- let newScrollOffset = stateRef.current.scrollOffset + delta;
661
- const roundedNewScrollOffset = Math.round(newScrollOffset);
662
- if (roundedNewScrollOffset >= LayoutMetrics.initialOffset) {
663
- // скролла нет (touchAction is null)
664
- // либо контент проскроллен в начало, тогда не даем скроллить дальше
665
- newScrollOffset = LayoutMetrics.initialOffset;
666
- if (stateRef.current.touchAction === 'scroll') {
667
- stateRef.current.touchAction = 'complete';
668
- }
669
- }
670
- else if (LayoutMetrics.contentHeight + roundedNewScrollOffset <= LayoutMetrics.visibleContentHeight) {
671
- // скролла нет (touchAction is null)
672
- // либо контент проскроллен до конца, тогда не даем скроллить дальше
673
- newScrollOffset = LayoutMetrics.visibleContentHeight - LayoutMetrics.contentHeight;
674
- if (stateRef.current.touchAction === 'scroll') {
675
- stateRef.current.touchAction = 'complete';
676
- }
677
- }
678
- else {
679
- // скролл в процессе
680
- stateRef.current.touchAction = 'scroll';
681
- }
682
- if (stateRef.current.scrollOffset !== newScrollOffset) {
683
- const offsetWasPositive = stateRef.current.scrollOffset > 0;
684
- stateRef.current.scrollOffset = newScrollOffset;
685
- if (contentRef.current !== null && swipeContainerRef.current !== null) {
686
- if (newScrollOffset > 0) {
687
- if (!offsetWasPositive) {
688
- contentRef.current.style.transform = translateY(0);
689
- }
690
- swipeContainerRef.current.style.transform = translateY(newScrollOffset);
691
- if (footerRef.current !== null) {
692
- footerRef.current.style.transform = translateY(-newScrollOffset);
693
- }
694
- }
695
- else {
696
- contentRef.current.style.transform = translateY(newScrollOffset);
697
- if (offsetWasPositive) {
698
- swipeContainerRef.current.style.transform = translateY(0);
699
- if (footerRef.current !== null) {
700
- footerRef.current.style.transform = translateY(0);
701
- }
702
- }
703
- }
643
+ if (stateRef.current.scrollOffset !== newScrollOffset) {
644
+ const offsetWasPositive = stateRef.current.scrollOffset > 0;
645
+ stateRef.current.scrollOffset = newScrollOffset;
646
+ if (contentRef.current !== null && swipeContainerRef.current !== null) {
647
+ if (newScrollOffset > 0) {
648
+ if (!offsetWasPositive) {
649
+ contentRef.current.style.transform = translateY(0);
650
+ }
651
+ swipeContainerRef.current.style.transform = translateY(newScrollOffset);
652
+ if (footerRef.current !== null) {
653
+ footerRef.current.style.transform = translateY(-newScrollOffset);
654
+ }
655
+ } else {
656
+ contentRef.current.style.transform = translateY(newScrollOffset);
657
+ if (offsetWasPositive) {
658
+ swipeContainerRef.current.style.transform = translateY(0);
659
+ if (footerRef.current !== null) {
660
+ footerRef.current.style.transform = translateY(0);
704
661
  }
705
- recalcScrollFlags();
706
- scrollContextProviderRef.current?.notifyScroll({
707
- scrollTop: Math.max(-stateRef.current.scrollOffset, 0),
708
- maxScrollTop: LayoutMetrics.maxScrollTop,
709
- });
662
+ }
710
663
  }
664
+ }
665
+ recalcScrollFlags();
666
+ scrollContextProviderRef.current?.notifyScroll({
667
+ scrollTop: Math.max(-stateRef.current.scrollOffset, 0),
668
+ maxScrollTop: LayoutMetrics.maxScrollTop
669
+ });
711
670
  }
712
- }, [LayoutMetrics, recalcScrollFlags]);
713
- const scrollContextProps = useState(() => ({
714
- getMaxScrollTop: () => LayoutMetrics.maxScrollTop,
715
- getScrollTop: () => LayoutMetrics.scrollTop,
716
- setScrollTop: (pos) => handleScroll(-(pos - LayoutMetrics.scrollTop)),
717
- }))[0];
718
- const initTransformHandlers = useCallback(() => {
719
- const visualContainer = visualContainerRef.current;
720
- if (!visualContainer) {
721
- return void 0;
722
- }
723
- let focusedElementTouchY = null;
724
- const onTouchMove = (event) => {
725
- if ((!allowScrollWhileFocused && stateRef.current.hasFocus) ||
726
- (stateRef.current.touchAction !== null && stateRef.current.touchAction !== 'scroll') ||
727
- hasSelectedText() ||
728
- (focusedElementRef.current !== null &&
729
- focusedElementTouchY !== null &&
730
- focusedElementRef.current.clientHeight !== focusedElementRef.current.scrollHeight)) {
731
- return;
732
- }
733
- handleScroll(event.delta);
734
- };
735
- const onTouchEnd = () => {
736
- if (focusedElementTouchY !== null) {
737
- focusedElementTouchY = null;
738
- }
739
- if (stateRef.current.touchAction === 'scroll') {
740
- stateRef.current.touchAction = null;
741
- }
742
- scrollContextProviderRef.current?.notifyTouchEnd();
743
- };
744
- const handleTouchStart = (event) => {
745
- if (stateRef.current.touchAction === 'complete') {
746
- stateRef.current.touchAction = null;
747
- }
748
- if (event.target === focusedElementRef.current && focusedElementRef.current !== null) {
749
- focusedElementTouchY = event.changedTouches[0].pageY;
750
- }
751
- else {
752
- focusedElementTouchY = null;
753
- swipeHandlers.onTouchStart(event);
754
- }
755
- visualContainer.classList.add(styles.noCaret);
756
- scrollContextProviderRef.current?.notifyTouchStart();
757
- };
758
- const handleTouchMove = (event) => {
759
- if (interceptTouchHandlers) {
760
- event.preventDefault();
761
- event.stopPropagation();
762
- }
763
- if (focusedElementRef.current !== null && focusedElementTouchY !== null) {
764
- focusedElementRef.current.scrollTop += focusedElementTouchY - event.changedTouches[0].pageY;
765
- focusedElementTouchY = event.changedTouches[0].pageY;
766
- }
767
- else {
768
- swipeHandlers.onTouchMove(event);
769
- }
770
- };
771
- const handleTouchEnd = (event) => {
772
- swipeHandlers.onTouchEnd(event);
773
- visualContainer.classList.remove(styles.noCaret);
774
- };
775
- const handleTouchCancel = (event) => {
776
- swipeHandlers.onTouchCancel(event);
777
- visualContainer.classList.remove(styles.noCaret);
778
- };
779
- const removeScrollHandlers = initScrollHandlers({
780
- axis: 'vertical',
781
- wrapperRef: visualContainerRef,
782
- onTouchMove,
783
- onTouchEnd,
784
- });
785
- visualContainer.addEventListener('touchstart', handleTouchStart);
786
- visualContainer.addEventListener('touchmove', handleTouchMove);
787
- visualContainer.addEventListener('touchend', handleTouchEnd);
788
- visualContainer.addEventListener('touchcancel', handleTouchCancel);
789
- return () => {
790
- removeScrollHandlers();
791
- visualContainer.removeEventListener('touchstart', handleTouchStart);
792
- visualContainer.removeEventListener('touchmove', handleTouchMove);
793
- visualContainer.removeEventListener('touchend', handleTouchEnd);
794
- visualContainer.removeEventListener('touchcancel', handleTouchCancel);
795
- };
796
- }, [allowScrollWhileFocused, swipeHandlers, interceptTouchHandlers, handleScroll]);
797
- // при изменении высоты контента анимируем ее
798
- // задаем боттомшиту фиксированную высоту и пересчитываем ее самостоятельно,
799
- // чтобы не было мерцания, когда новый контент отрисовался до срабатывания колбека ResizeObserver
800
- const initHeightObserver = useCallback(() => {
801
- const visualContainer = visualContainerRef.current;
802
- if (!visualContainer) {
803
- return void 0;
804
- }
805
- let prevContentHeight = 0;
806
- let prevHeaderHeight = 0;
807
- let prevFooterHeight = 0;
808
- let prevVisibleContentHeight = 0;
809
- let skipFirstResizeCallback = true;
810
- let resetAnimationOnNextResize = false;
811
- const handleHeightChange = () => {
812
- LayoutMetrics.invalidateCache();
813
- if (skipFirstResizeCallback || stateRef.current.skipHeightAnimation) {
814
- // записываем в инлайн-стили visualContainer собственную высоту
815
- // чтобы ее можно было анимировать изменением одного инлайн значения на другое
816
- visualContainer.style.height = skipFirstResizeCallback ? `${LayoutMetrics.bottomSheetHeight}px` : '';
817
- prevHeaderHeight = LayoutMetrics.headerHeight;
818
- prevContentHeight = LayoutMetrics.contentHeight;
819
- prevFooterHeight = LayoutMetrics.footerHeight;
820
- prevVisibleContentHeight = LayoutMetrics.visibleContentHeight;
821
- skipFirstResizeCallback = false;
822
- stateRef.current.skipHeightAnimation = false;
823
- return;
824
- }
825
- // без анимации сбрасываем высоту на вычисленную браузером
826
- if (resetAnimationOnNextResize) {
827
- visualContainer.style.height = ``;
828
- }
829
- else {
830
- const contentHeightDiff = LayoutMetrics.contentHeight - prevContentHeight;
831
- const containersHeightDiff = LayoutMetrics.headerHeight - prevHeaderHeight + LayoutMetrics.footerHeight - prevFooterHeight;
832
- // предположим, что scrollContainer останется таким же или станет меньше
833
- // тогда можем рассчитать минимальную видимую высоту контента как min(scrollContainer.height, contentHeight)
834
- const _prevVisibleContentHeight = Math.min(prevVisibleContentHeight, prevContentHeight);
835
- const newMinVisibleContentHeight = Math.min(prevVisibleContentHeight - containersHeightDiff, LayoutMetrics.contentHeight);
836
- const minVisibleContentHeightDiff = newMinVisibleContentHeight - _prevVisibleContentHeight;
837
- // предположим, что scrollContainer станет больше
838
- // тогда контент не может увеличиться больше, чем на расстояние между боттомшитом и верхним краем экрана
839
- const maxVisibleContentHeightDiff = LayoutMetrics.remainingAvailableHeight - containersHeightDiff;
840
- const visibleContentHeightDiff = Math.min(Math.max(contentHeightDiff, minVisibleContentHeightDiff), maxVisibleContentHeightDiff);
841
- if (visibleContentHeightDiff !== 0) {
842
- resetScrollPosition();
843
- }
844
- else {
845
- // если высота видимой части контента не изменилась,
846
- // но позиция скролла превысила максимально допустимую из-за уменьшения высоты контента,
847
- // сбрасываем позицию скролла на максимально допустимую
848
- fixOverscroll();
849
- }
850
- const heightAnimationDiff = visibleContentHeightDiff + containersHeightDiff;
851
- if (heightAnimationDiff !== 0) {
852
- // если предыдущая анимация не завершилась, добавляем вычисленное изменение к значению высоты
853
- // но делаем это только один раз, иначе алгоритм ломается
854
- if (stateRef.current.heightAnimationValue !== null) {
855
- stateRef.current.heightAnimationValue += heightAnimationDiff;
856
- visualContainer.style.height = `${stateRef.current.heightAnimationValue}px`;
857
- resetAnimationOnNextResize = true;
858
- }
859
- else {
860
- stateRef.current.heightAnimationValue = LayoutMetrics.bottomSheetHeight + heightAnimationDiff;
861
- }
862
- stateRef.current.heightAnimationCallback = () => {
863
- // запоминаем высоту visibleContentHeight после завершения анимации
864
- // до этого значение некорректно, т.к. новый контент уже был отрендерен,
865
- // но в инлайн-стилях боттомшита остается старая высота
866
- prevVisibleContentHeight = LayoutMetrics.visibleContentHeight;
867
- resetAnimationOnNextResize = false;
868
- };
869
- setHeightAnimationRunning(true);
870
- }
871
- else {
872
- prevVisibleContentHeight = LayoutMetrics.visibleContentHeight;
873
- recalcContentOverlayPosition();
874
- recalcScrollFlags();
875
- }
876
- }
877
- prevHeaderHeight = LayoutMetrics.headerHeight;
878
- prevContentHeight = LayoutMetrics.contentHeight;
879
- prevFooterHeight = LayoutMetrics.footerHeight;
880
- };
881
- const resizeObserver = new ResizeObserver(handleHeightChange);
882
- const content = contentRef.current;
883
- const footer = footerRef.current;
884
- const header = headerWrapperRef.current;
885
- content !== null && resizeObserver.observe(content);
886
- footer !== null && resizeObserver.observe(footer);
887
- header !== null && resizeObserver.observe(header);
888
- return () => resizeObserver.disconnect();
889
- }, [
890
- fixOverscroll,
891
- recalcContentOverlayPosition,
892
- recalcScrollFlags,
893
- resetScrollPosition,
894
- setHeightAnimationRunning,
895
- LayoutMetrics,
896
- ]);
897
- const handleAppearAnimationEnd = useCallback(() => {
898
- const removeHeightObserver = initHeightObserver();
899
- removeHeightObserver && stateRef.current.exitHandlers.push(removeHeightObserver);
900
- const removeTransformHandlers = hasTouchSupport && initTransformHandlers();
901
- removeTransformHandlers && stateRef.current.exitHandlers.push(removeTransformHandlers);
902
- onAppearRef.current?.();
903
- }, [hasTouchSupport, initHeightObserver, initTransformHandlers]);
904
- const { onTouchEnd, ...eventHandlersRaw } = useNoBubbling();
905
- const eventHandlers = interceptTouchHandlers
906
- ? eventHandlersRaw
907
- : { ...eventHandlersRaw, onTouchMove: undefined, onTouchStart: undefined, onTouchEnd: undefined };
908
- if (!animationTimeout) {
909
- return null;
671
+ }
672
+ },
673
+ [LayoutMetrics, recalcScrollFlags]
674
+ );
675
+ const scrollContextProps = useState(() => ({
676
+ getMaxScrollTop: () => LayoutMetrics.maxScrollTop,
677
+ getScrollTop: () => LayoutMetrics.scrollTop,
678
+ setScrollTop: (pos) => handleScroll(-(pos - LayoutMetrics.scrollTop))
679
+ }))[0];
680
+ const initTransformHandlers = useCallback(() => {
681
+ const visualContainer = visualContainerRef.current;
682
+ if (!visualContainer) {
683
+ return void 0;
910
684
  }
911
- const containerDataQa = `bottom-sheet-container${dataQA ? ` ${dataQA}` : ''}`;
912
- const explicitAria = {
913
- 'aria-label': ariaLabel,
914
- 'aria-labelledby': ariaLabelledby,
915
- 'aria-describedby': ariaDescribedby,
916
- 'aria-description': ariaDescription,
685
+ let focusedElementTouchY = null;
686
+ const onTouchMove = (event) => {
687
+ if (!allowScrollWhileFocused && stateRef.current.hasFocus || stateRef.current.touchAction !== null && stateRef.current.touchAction !== "scroll" || hasSelectedText() || focusedElementRef.current !== null && focusedElementTouchY !== null && focusedElementRef.current.clientHeight !== focusedElementRef.current.scrollHeight) {
688
+ return;
689
+ }
690
+ handleScroll(event.delta);
691
+ };
692
+ const onTouchEnd2 = () => {
693
+ if (focusedElementTouchY !== null) {
694
+ focusedElementTouchY = null;
695
+ }
696
+ if (stateRef.current.touchAction === "scroll") {
697
+ stateRef.current.touchAction = null;
698
+ }
699
+ scrollContextProviderRef.current?.notifyTouchEnd();
917
700
  };
918
- const renderFunc = (appearTransition, heightTransition) => {
919
- const content = (jsx("div", { className: classnames(styles.content, {
920
- [styles.contentFullScreen]: height === 'full-screen',
921
- [styles.contentWithPaddings]: withContentPaddings === true,
922
- [styles.contentWithTopPadding]: !header && withContentPaddings === 'top',
923
- [styles.contentSizedFullScreen]: isContentSizedFullHeight(children),
924
- }), ref: contentRef, children: jsx(BottomSheetContext.Provider, { value: bottomSheetContext.value, children: children }) }));
925
- const scrollContainer = hasTouchSupport ? (jsx(CustomScrollContextProvider, { ref: scrollContextProviderRef, wrapperRef: scrollContainerRef, ...scrollContextProps, children: jsx("div", { className: classnames(styles.scrollContainer, {
926
- [styles.scrollContainerWithTopPadding]: withTopPadding,
927
- }), onFocus: handleFocus, ref: scrollContainerRef, children: jsxs(GrowLimitWrapper, { ...growLimiterProps, children: [jsx("div", { className: styles.headerWrapper, ref: headerWrapperRef, children: header }), content] }) }) })) : (jsx("div", { className: classnames(styles.scrollContainer, styles.nativeScrollContainer, {
928
- [styles.scrollContainerWithTopPadding]: withTopPadding,
929
- }), onFocus: handleFocus, onScroll: recalcScrollFlags, ref: scrollContainerRef, children: jsxs(GrowLimitWrapper, { ...growLimiterProps, children: [jsx("div", { className: styles.headerWrapper, ref: headerWrapperRef, children: header }), content] }) }));
930
- const clonedFooter = footer && isActionBarComponent(footer)
931
- ? cloneElement(footer, {
932
- type: footer.props.type || BOTTOM_SHEET_ACTION_BAR_DEFAULTS.type,
933
- padding: footer.props.padding || BOTTOM_SHEET_ACTION_BAR_DEFAULTS.padding,
934
- showDivider: BOTTOM_SHEET_ACTION_BAR_DEFAULTS.showDivider,
935
- })
936
- : footer;
937
- return (jsx(Layer, { layer: "bottom-sheet", children: jsxs("div", { ...eventHandlers, className: styles.overlay, children: [jsx("div", { className: classnames(styles.overlayBackground, {
938
- [styles.overlayBackgroundVisible]: showOverlay,
939
- [styles.appearAnimation]: appearTransition === 'entering',
940
- [styles.disappearAnimation]: appearTransition === 'exiting',
941
- }), ...(appearTransition === 'entered'
942
- ? { 'data-qa': 'bottom-sheet-overlay', onClick: () => onCloseRef.current(null) }
943
- : {}), ref: overlayRef }), jsxs("div", { className: classnames(styles.swipeContainer, {
944
- [styles.appearAnimation]: appearTransition === 'entering',
945
- [styles.closeBySwipeAnimation]: appearTransition === 'exiting' && stateRef.current.touchAction === 'swipe',
946
- [styles.disappearAnimation]: appearTransition === 'exiting',
947
- }), "data-qa": appearTransition === 'entered' ? containerDataQa : undefined, ref: swipeContainerRef, children: [jsx("div", { className: classnames(styles.grabber, styles.grabberTransitionAnimation, {
948
- [styles.grabberEnsureSafe]: stateRef.current.grabberUnsafe,
949
- }), ref: grabberRef }), jsx(ContentOverlayRoot, { ref: contentOverlayRef, children: jsx(AccessibleRegionProvider, { children: jsxs(BottomSheetDialog, { explicitAria: explicitAria, dialogRef: bottomSheetRef, className: classnames(styles.visualContainer, {
950
- [styles.visualContainerFullScreen]: height === 'full-screen',
951
- [styles.heightTransitionAnimation]: heightTransition === 'entering',
952
- }), "data-qa": appearTransition === 'entered' ? 'bottom-sheet-content' : undefined, id: id, children: [scrollContainer, jsxs("div", { className: styles.footer, ref: footerRef, children: [footer && (jsx("div", { className: classnames(styles.divider, {
953
- [styles.dividerVisible]: stateRef.current.dividerVisible,
954
- }), ref: dividerRef, children: jsx(Divider, {}) })), interceptClickHandlers && hasTouchSupport ? (jsx(ClickInterceptor, { children: clonedFooter })) : (clonedFooter)] })] }) }) })] })] }) }));
701
+ const handleTouchStart = (event) => {
702
+ if (stateRef.current.touchAction === "complete") {
703
+ stateRef.current.touchAction = null;
704
+ }
705
+ if (event.target === focusedElementRef.current && focusedElementRef.current !== null) {
706
+ focusedElementTouchY = event.changedTouches[0].pageY;
707
+ } else {
708
+ focusedElementTouchY = null;
709
+ swipeHandlers.onTouchStart(event);
710
+ }
711
+ visualContainer.classList.add(styles.noCaret);
712
+ scrollContextProviderRef.current?.notifyTouchStart();
955
713
  };
956
- return createPortal(jsx(ThemeWrapper, { children: (themeClass) => (jsx("div", { className: classnames(styles.cssVariablesContainer, themeClass), "data-qa": "bottom-sheet-css-variables", ref: cssVariablesContainerRef, children: jsx(Transition, { appear: true, in: currentVisible, mountOnEnter: true, onEnter: setTransformToInvisible, onEntering: setTransformToVisible, onEntered: handleAppearAnimationEnd, onExit: handleExitAnimationStart, onExiting: setTransformToInvisible, onExited: handleExitAnimationEnd, timeout: animationTimeout.appear, unmountOnExit: true, nodeRef: contentRef, children: (appearTransition) => (jsx(Transition, { in: heightAnimationRunning, onEntering: handleHeightAnimationStart, onEntered: handleHeightAnimationEnd, timeout: animationTimeout.height, nodeRef: contentRef, children: (heightTransition) => renderFunc(appearTransition, heightTransition) })) }, `hasTouchSupport:${hasTouchSupport}`) })) }), document.body);
714
+ const handleTouchMove = (event) => {
715
+ if (interceptTouchHandlers) {
716
+ event.preventDefault();
717
+ event.stopPropagation();
718
+ }
719
+ if (focusedElementRef.current !== null && focusedElementTouchY !== null) {
720
+ focusedElementRef.current.scrollTop += focusedElementTouchY - event.changedTouches[0].pageY;
721
+ focusedElementTouchY = event.changedTouches[0].pageY;
722
+ } else {
723
+ swipeHandlers.onTouchMove(event);
724
+ }
725
+ };
726
+ const handleTouchEnd = (event) => {
727
+ swipeHandlers.onTouchEnd(event);
728
+ visualContainer.classList.remove(styles.noCaret);
729
+ };
730
+ const handleTouchCancel = (event) => {
731
+ swipeHandlers.onTouchCancel(event);
732
+ visualContainer.classList.remove(styles.noCaret);
733
+ };
734
+ const removeScrollHandlers = initScrollHandlers({
735
+ axis: "vertical",
736
+ wrapperRef: visualContainerRef,
737
+ onTouchMove,
738
+ onTouchEnd: onTouchEnd2
739
+ });
740
+ visualContainer.addEventListener("touchstart", handleTouchStart);
741
+ visualContainer.addEventListener("touchmove", handleTouchMove);
742
+ visualContainer.addEventListener("touchend", handleTouchEnd);
743
+ visualContainer.addEventListener("touchcancel", handleTouchCancel);
744
+ return () => {
745
+ removeScrollHandlers();
746
+ visualContainer.removeEventListener("touchstart", handleTouchStart);
747
+ visualContainer.removeEventListener("touchmove", handleTouchMove);
748
+ visualContainer.removeEventListener("touchend", handleTouchEnd);
749
+ visualContainer.removeEventListener("touchcancel", handleTouchCancel);
750
+ };
751
+ }, [allowScrollWhileFocused, swipeHandlers, interceptTouchHandlers, handleScroll]);
752
+ const initHeightObserver = useCallback(() => {
753
+ const visualContainer = visualContainerRef.current;
754
+ if (!visualContainer) {
755
+ return void 0;
756
+ }
757
+ let prevContentHeight = 0;
758
+ let prevHeaderHeight = 0;
759
+ let prevFooterHeight = 0;
760
+ let prevVisibleContentHeight = 0;
761
+ let skipFirstResizeCallback = true;
762
+ let resetAnimationOnNextResize = false;
763
+ const handleHeightChange = () => {
764
+ LayoutMetrics.invalidateCache();
765
+ if (skipFirstResizeCallback || stateRef.current.skipHeightAnimation) {
766
+ visualContainer.style.height = skipFirstResizeCallback ? `${LayoutMetrics.bottomSheetHeight}px` : "";
767
+ prevHeaderHeight = LayoutMetrics.headerHeight;
768
+ prevContentHeight = LayoutMetrics.contentHeight;
769
+ prevFooterHeight = LayoutMetrics.footerHeight;
770
+ prevVisibleContentHeight = LayoutMetrics.visibleContentHeight;
771
+ skipFirstResizeCallback = false;
772
+ stateRef.current.skipHeightAnimation = false;
773
+ return;
774
+ }
775
+ if (resetAnimationOnNextResize) {
776
+ visualContainer.style.height = ``;
777
+ } else {
778
+ const contentHeightDiff = LayoutMetrics.contentHeight - prevContentHeight;
779
+ const containersHeightDiff = LayoutMetrics.headerHeight - prevHeaderHeight + LayoutMetrics.footerHeight - prevFooterHeight;
780
+ const _prevVisibleContentHeight = Math.min(prevVisibleContentHeight, prevContentHeight);
781
+ const newMinVisibleContentHeight = Math.min(
782
+ prevVisibleContentHeight - containersHeightDiff,
783
+ LayoutMetrics.contentHeight
784
+ );
785
+ const minVisibleContentHeightDiff = newMinVisibleContentHeight - _prevVisibleContentHeight;
786
+ const maxVisibleContentHeightDiff = LayoutMetrics.remainingAvailableHeight - containersHeightDiff;
787
+ const visibleContentHeightDiff = Math.min(
788
+ Math.max(contentHeightDiff, minVisibleContentHeightDiff),
789
+ maxVisibleContentHeightDiff
790
+ );
791
+ if (visibleContentHeightDiff !== 0) {
792
+ resetScrollPosition();
793
+ } else {
794
+ fixOverscroll();
795
+ }
796
+ const heightAnimationDiff = visibleContentHeightDiff + containersHeightDiff;
797
+ if (heightAnimationDiff !== 0) {
798
+ if (stateRef.current.heightAnimationValue !== null) {
799
+ stateRef.current.heightAnimationValue += heightAnimationDiff;
800
+ visualContainer.style.height = `${stateRef.current.heightAnimationValue}px`;
801
+ resetAnimationOnNextResize = true;
802
+ } else {
803
+ stateRef.current.heightAnimationValue = LayoutMetrics.bottomSheetHeight + heightAnimationDiff;
804
+ }
805
+ stateRef.current.heightAnimationCallback = () => {
806
+ prevVisibleContentHeight = LayoutMetrics.visibleContentHeight;
807
+ resetAnimationOnNextResize = false;
808
+ };
809
+ setHeightAnimationRunning(true);
810
+ } else {
811
+ prevVisibleContentHeight = LayoutMetrics.visibleContentHeight;
812
+ recalcContentOverlayPosition();
813
+ recalcScrollFlags();
814
+ }
815
+ }
816
+ prevHeaderHeight = LayoutMetrics.headerHeight;
817
+ prevContentHeight = LayoutMetrics.contentHeight;
818
+ prevFooterHeight = LayoutMetrics.footerHeight;
819
+ };
820
+ const resizeObserver = new ResizeObserver(handleHeightChange);
821
+ const content = contentRef.current;
822
+ const footer2 = footerRef.current;
823
+ const header2 = headerWrapperRef.current;
824
+ content !== null && resizeObserver.observe(content);
825
+ footer2 !== null && resizeObserver.observe(footer2);
826
+ header2 !== null && resizeObserver.observe(header2);
827
+ return () => resizeObserver.disconnect();
828
+ }, [
829
+ fixOverscroll,
830
+ recalcContentOverlayPosition,
831
+ recalcScrollFlags,
832
+ resetScrollPosition,
833
+ setHeightAnimationRunning,
834
+ LayoutMetrics
835
+ ]);
836
+ const handleAppearAnimationEnd = useCallback(() => {
837
+ const removeHeightObserver = initHeightObserver();
838
+ removeHeightObserver && stateRef.current.exitHandlers.push(removeHeightObserver);
839
+ const removeTransformHandlers = hasTouchSupport && initTransformHandlers();
840
+ removeTransformHandlers && stateRef.current.exitHandlers.push(removeTransformHandlers);
841
+ onAppearRef.current?.();
842
+ }, [hasTouchSupport, initHeightObserver, initTransformHandlers]);
843
+ const { onTouchEnd, ...eventHandlersRaw } = useNoBubbling();
844
+ const eventHandlers = interceptTouchHandlers ? eventHandlersRaw : { ...eventHandlersRaw, onTouchMove: void 0, onTouchStart: void 0, onTouchEnd: void 0 };
845
+ if (!animationTimeout) {
846
+ return null;
847
+ }
848
+ const containerDataQa = `bottom-sheet-container${dataQA ? ` ${dataQA}` : ""}`;
849
+ const explicitAria = {
850
+ "aria-label": ariaLabel,
851
+ "aria-labelledby": ariaLabelledby,
852
+ "aria-describedby": ariaDescribedby,
853
+ "aria-description": ariaDescription
854
+ };
855
+ const renderFunc = (appearTransition, heightTransition) => {
856
+ const content = /* @__PURE__ */ jsx(
857
+ "div",
858
+ {
859
+ className: classnames(styles.content, {
860
+ [styles.contentFullScreen]: height === "full-screen",
861
+ [styles.contentWithPaddings]: withContentPaddings === true,
862
+ [styles.contentWithTopPadding]: !header && withContentPaddings === "top",
863
+ [styles.contentSizedFullScreen]: isContentSizedFullHeight(children)
864
+ }),
865
+ ref: contentRef,
866
+ children: /* @__PURE__ */ jsx(BottomSheetContext.Provider, { value: bottomSheetContext.value, children })
867
+ }
868
+ );
869
+ const scrollContainer = hasTouchSupport ? /* @__PURE__ */ jsx(
870
+ CustomScrollContextProvider,
871
+ {
872
+ ref: scrollContextProviderRef,
873
+ wrapperRef: scrollContainerRef,
874
+ ...scrollContextProps,
875
+ children: /* @__PURE__ */ jsx(
876
+ "div",
877
+ {
878
+ className: classnames(styles.scrollContainer, {
879
+ [styles.scrollContainerWithTopPadding]: withTopPadding
880
+ }),
881
+ onFocus: handleFocus,
882
+ ref: scrollContainerRef,
883
+ children: /* @__PURE__ */ jsxs(GrowLimitWrapper, { ...growLimiterProps, children: [
884
+ /* @__PURE__ */ jsx("div", { className: styles.headerWrapper, ref: headerWrapperRef, children: header }),
885
+ content
886
+ ] })
887
+ }
888
+ )
889
+ }
890
+ ) : /* @__PURE__ */ jsx(
891
+ "div",
892
+ {
893
+ className: classnames(styles.scrollContainer, styles.nativeScrollContainer, {
894
+ [styles.scrollContainerWithTopPadding]: withTopPadding
895
+ }),
896
+ onFocus: handleFocus,
897
+ onScroll: recalcScrollFlags,
898
+ ref: scrollContainerRef,
899
+ children: /* @__PURE__ */ jsxs(GrowLimitWrapper, { ...growLimiterProps, children: [
900
+ /* @__PURE__ */ jsx("div", { className: styles.headerWrapper, ref: headerWrapperRef, children: header }),
901
+ content
902
+ ] })
903
+ }
904
+ );
905
+ const clonedFooter = footer && isActionBarComponent(footer) ? cloneElement(footer, {
906
+ type: footer.props.type || BOTTOM_SHEET_ACTION_BAR_DEFAULTS.type,
907
+ padding: footer.props.padding || BOTTOM_SHEET_ACTION_BAR_DEFAULTS.padding,
908
+ showDivider: BOTTOM_SHEET_ACTION_BAR_DEFAULTS.showDivider
909
+ }) : footer;
910
+ return /* @__PURE__ */ jsx(Layer, { layer: "bottom-sheet", children: /* @__PURE__ */ jsxs("div", { ...eventHandlers, className: styles.overlay, children: [
911
+ /* @__PURE__ */ jsx(
912
+ "div",
913
+ {
914
+ className: classnames(styles.overlayBackground, {
915
+ [styles.overlayBackgroundVisible]: showOverlay,
916
+ [styles.appearAnimation]: appearTransition === "entering",
917
+ [styles.disappearAnimation]: appearTransition === "exiting"
918
+ }),
919
+ ...appearTransition === "entered" ? { "data-qa": "bottom-sheet-overlay", onClick: () => onCloseRef.current(null) } : {},
920
+ ref: overlayRef
921
+ }
922
+ ),
923
+ /* @__PURE__ */ jsxs(
924
+ "div",
925
+ {
926
+ className: classnames(styles.swipeContainer, {
927
+ [styles.appearAnimation]: appearTransition === "entering",
928
+ [styles.closeBySwipeAnimation]: appearTransition === "exiting" && stateRef.current.touchAction === "swipe",
929
+ [styles.disappearAnimation]: appearTransition === "exiting"
930
+ }),
931
+ "data-qa": appearTransition === "entered" ? containerDataQa : void 0,
932
+ ref: swipeContainerRef,
933
+ children: [
934
+ /* @__PURE__ */ jsx(
935
+ "div",
936
+ {
937
+ className: classnames(styles.grabber, styles.grabberTransitionAnimation, {
938
+ [styles.grabberEnsureSafe]: stateRef.current.grabberUnsafe
939
+ }),
940
+ ref: grabberRef
941
+ }
942
+ ),
943
+ /* @__PURE__ */ jsx(ContentOverlayRoot, { ref: contentOverlayRef, children: /* @__PURE__ */ jsx(AccessibleRegionProvider, { children: /* @__PURE__ */ jsxs(
944
+ BottomSheetDialog,
945
+ {
946
+ explicitAria,
947
+ dialogRef: bottomSheetRef,
948
+ className: classnames(styles.visualContainer, {
949
+ [styles.visualContainerFullScreen]: height === "full-screen",
950
+ [styles.heightTransitionAnimation]: heightTransition === "entering"
951
+ }),
952
+ "data-qa": appearTransition === "entered" ? "bottom-sheet-content" : void 0,
953
+ id,
954
+ children: [
955
+ scrollContainer,
956
+ /* @__PURE__ */ jsxs("div", { className: styles.footer, ref: footerRef, children: [
957
+ footer && /* @__PURE__ */ jsx(
958
+ "div",
959
+ {
960
+ className: classnames(styles.divider, {
961
+ [styles.dividerVisible]: stateRef.current.dividerVisible
962
+ }),
963
+ ref: dividerRef,
964
+ children: /* @__PURE__ */ jsx(Divider, {})
965
+ }
966
+ ),
967
+ interceptClickHandlers && hasTouchSupport ? /* @__PURE__ */ jsx(ClickInterceptor, { children: clonedFooter }) : clonedFooter
968
+ ] })
969
+ ]
970
+ }
971
+ ) }) })
972
+ ]
973
+ }
974
+ )
975
+ ] }) });
976
+ };
977
+ return createPortal(
978
+ /* @__PURE__ */ jsx(ThemeWrapper, { children: (themeClass) => /* @__PURE__ */ jsx(
979
+ "div",
980
+ {
981
+ className: classnames(styles.cssVariablesContainer, themeClass),
982
+ "data-qa": "bottom-sheet-css-variables",
983
+ ref: cssVariablesContainerRef,
984
+ children: /* @__PURE__ */ jsx(
985
+ Transition,
986
+ {
987
+ appear: true,
988
+ in: currentVisible,
989
+ mountOnEnter: true,
990
+ onEnter: setTransformToInvisible,
991
+ onEntering: setTransformToVisible,
992
+ onEntered: handleAppearAnimationEnd,
993
+ onExit: handleExitAnimationStart,
994
+ onExiting: setTransformToInvisible,
995
+ onExited: handleExitAnimationEnd,
996
+ timeout: animationTimeout.appear,
997
+ unmountOnExit: true,
998
+ nodeRef: contentRef,
999
+ children: (appearTransition) => /* @__PURE__ */ jsx(
1000
+ Transition,
1001
+ {
1002
+ in: heightAnimationRunning,
1003
+ onEntering: handleHeightAnimationStart,
1004
+ onEntered: handleHeightAnimationEnd,
1005
+ timeout: animationTimeout.height,
1006
+ nodeRef: contentRef,
1007
+ children: (heightTransition) => renderFunc(appearTransition, heightTransition)
1008
+ }
1009
+ )
1010
+ },
1011
+ `hasTouchSupport:${hasTouchSupport}`
1012
+ )
1013
+ }
1014
+ ) }),
1015
+ document.body
1016
+ );
957
1017
  };
958
1018
  const BottomSheetComponent = forwardRef(BottomSheetRenderFunc);
959
- BottomSheetComponent.displayName = 'BottomSheet';
1019
+ BottomSheetComponent.displayName = "BottomSheet";
960
1020
  const BottomSheet = BottomSheetComponent;
961
1021
  BottomSheet.Media = BottomSheetMedia;
962
1022