From 9a5230409f1fa84b52650c2127e600466e8f53ff Mon Sep 17 00:00:00 2001 From: Alesya Volosach Date: Tue, 17 Nov 2026 18:57:27 +0300 Subject: [PATCH 01/12] =?UTF-8?q?chore(tokens):=20=D0=BE=D0=B1=D0=BD=D0=BE?= =?UTF-8?q?=D0=B2=D0=BB=D0=B5=D0=BD=D1=8B=20=D1=82=D0=BE=D0=BA=D0=B5=D0=BD?= =?UTF-8?q?=D1=8B=20Tooltip?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- design-tokens/input/tokens.json | 18 ++++++++++++++---- src/theme/tokens/components/dark.json | 7 ++++--- src/theme/tokens/components/light.json | 5 +++-- .../tokens/semantic/colorScheme/dark.json | 4 ++++ .../tokens/semantic/colorScheme/light.json | 4 ++++ 5 files changed, 29 insertions(+), 9 deletions(-) diff --git a/design-tokens/input/tokens.json b/design-tokens/input/tokens.json index 9f73b18a..c646ca14 100644 --- a/design-tokens/input/tokens.json +++ b/design-tokens/input/tokens.json @@ -22,6 +22,7 @@ }, "black": { "40": "rgba(0, 0, 0, 0.0400)", + "50": "rgba(0, 0, 0, 0.05)", "100": "rgba(0, 0, 0, 0.1000)", "200": "rgba(0, 0, 0, 0.2000)", "300": "rgba(0, 0, 0, 0.3000)", @@ -737,6 +738,10 @@ }, "help": { "strong": "{colors.solid.purple.600}" } } + }, + "shadow": { + "default": "{colors.alpha.black.100}", + "subtle": "{colors.alpha.black.50}" } } }, @@ -1000,6 +1005,10 @@ }, "help": { "strong": "{colors.solid.purple.400}" } } + }, + "shadow": { + "default": "{colors.alpha.black.300}", + "subtle": "{colors.alpha.black.200}" } } } @@ -5213,15 +5222,16 @@ }, "dark": { "root": { - "background": "{color.bg.surface.canvas.default}", - "color": "{color.fg.default}" + "background": "{color.bg.neutral.strong.default}", + "color": "{color.fg.inverse.default}" } } }, "root": { - "maxWidth": "{dimension.size.2000}", + "maxWidth": "{dimension.size.1600}", "gutter": "{dimension.space.100}", - "shadow": "{effects.elevation.400}", + "shadow": "0 4px 8px {color.shadow.default}", + "subtleShadow": "0 0 2px {color.shadow.subtle}", "padding": "{dimension.space.200} {dimension.space.400}", "borderRadius": "{dimension.borderRadius.200}" } diff --git a/src/theme/tokens/components/dark.json b/src/theme/tokens/components/dark.json index 4e5adfc8..7ab2e9b1 100644 --- a/src/theme/tokens/components/dark.json +++ b/src/theme/tokens/components/dark.json @@ -2883,11 +2883,12 @@ "handle": { "borderRadius": 1600, "size": 16 } }, "tooltip": { - "colorScheme": { "root": { "background": "#2b2e33", "color": "#ffffff" } }, + "colorScheme": { "root": { "background": "#f0f0f1", "color": "#2b2e33" } }, "root": { - "maxWidth": 400, + "maxWidth": 240, "gutter": 4, - "shadow": "0 4px 8px rgba(0, 0, 0, 0.2000)", + "shadow": "0 4px 8px rgba(0, 0, 0, 0.3000)", + "subtleShadow": "0 0 2px rgba(0, 0, 0, 0.2000)", "paddingTop": 8, "paddingRight": 14, "paddingBottom": 8, diff --git a/src/theme/tokens/components/light.json b/src/theme/tokens/components/light.json index 560b47d7..e270047b 100644 --- a/src/theme/tokens/components/light.json +++ b/src/theme/tokens/components/light.json @@ -2885,9 +2885,10 @@ "tooltip": { "colorScheme": { "root": { "background": "#2b2e33", "color": "#ffffff" } }, "root": { - "maxWidth": 400, + "maxWidth": 240, "gutter": 4, - "shadow": "0 4px 8px rgba(0, 0, 0, 0.2000)", + "shadow": "0 4px 8px rgba(0, 0, 0, 0.1000)", + "subtleShadow": "0 0 2px rgba(0, 0, 0, 0.05)", "paddingTop": 8, "paddingRight": 14, "paddingBottom": 8, diff --git a/src/theme/tokens/semantic/colorScheme/dark.json b/src/theme/tokens/semantic/colorScheme/dark.json index fc75c005..9d26b889 100644 --- a/src/theme/tokens/semantic/colorScheme/dark.json +++ b/src/theme/tokens/semantic/colorScheme/dark.json @@ -225,6 +225,10 @@ "success": { "default": "#44e858", "strong": "#77f48a" }, "help": { "strong": "#c084fc" } } + }, + "shadow": { + "default": "rgba(0, 0, 0, 0.3000)", + "subtle": "rgba(0, 0, 0, 0.2000)" } } } diff --git a/src/theme/tokens/semantic/colorScheme/light.json b/src/theme/tokens/semantic/colorScheme/light.json index d1aaf7f7..6434e760 100644 --- a/src/theme/tokens/semantic/colorScheme/light.json +++ b/src/theme/tokens/semantic/colorScheme/light.json @@ -225,6 +225,10 @@ "success": { "default": "#44e858", "strong": "#1dc831" }, "help": { "strong": "#9333ea" } } + }, + "shadow": { + "default": "rgba(0, 0, 0, 0.1000)", + "subtle": "rgba(0, 0, 0, 0.05)" } } } From a092845d9e45f691b0e207a92adf61078b7539b8 Mon Sep 17 00:00:00 2001 From: Alesya Volosach Date: Thu, 19 Nov 2026 14:05:13 +0300 Subject: [PATCH 02/12] =?UTF-8?q?feat(tooltip):=20=D0=B4=D0=BE=D0=B1=D0=B0?= =?UTF-8?q?=D0=B2=D0=BB=D0=B5=D0=BD=D1=8B=20=D0=BA=D0=B0=D1=80=D1=82=D0=BE?= =?UTF-8?q?=D1=87=D0=BA=D0=B0=20=D0=B8=20=D1=81=D1=82=D1=80=D0=B5=D0=BB?= =?UTF-8?q?=D0=BA=D0=B0=20=D0=BF=D0=BE=D0=B4=D1=81=D0=BA=D0=B0=D0=B7=D0=BA?= =?UTF-8?q?=D0=B8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../Tooltip/internal/TooltipBubble.tsx | 145 ++++++++++++++++++ .../Tooltip/internal/assets/arrow.json | 5 + src/components/Tooltip/types.ts | 24 +++ 3 files changed, 174 insertions(+) create mode 100644 src/components/Tooltip/internal/TooltipBubble.tsx create mode 100644 src/components/Tooltip/internal/assets/arrow.json create mode 100644 src/components/Tooltip/types.ts diff --git a/src/components/Tooltip/internal/TooltipBubble.tsx b/src/components/Tooltip/internal/TooltipBubble.tsx new file mode 100644 index 00000000..35e2b513 --- /dev/null +++ b/src/components/Tooltip/internal/TooltipBubble.tsx @@ -0,0 +1,145 @@ +import { ScrollView, Text, View, type LayoutChangeEvent } from 'react-native' +import { SvgXml } from 'react-native-svg' +import { StyleSheet, useUnistyles } from 'react-native-unistyles' + +import type { TooltipPosition } from '../types' + +import arrowAsset from './assets/arrow.json' + +// Размеры исходного SVG из Figma, без масштабирования при повороте. +export const ARROW_WIDTH = arrowAsset.width +export const ARROW_DEPTH = arrowAsset.height + +interface TooltipBubbleProps { + readonly text: string + readonly position: TooltipPosition + readonly maxWidth: number + readonly maxHeight?: number + readonly arrowOffset?: number + readonly onLayout?: (event: LayoutChangeEvent) => void + readonly testID?: string + readonly isProbe?: boolean +} + +export const TooltipBubble = ({ + text, + position, + maxWidth, + maxHeight, + arrowOffset, + onLayout, + testID, + isProbe = false, +}: TooltipBubbleProps) => { + const { theme } = useUnistyles() + const vertical = position === 'top' || position === 'bottom' + const before = position === 'bottom' || position === 'right' + const rotation = { + top: '0deg', + bottom: '180deg', + left: '-90deg', + right: '90deg', + }[position] + const arrow = !isProbe && ( + + + + ) + + return ( + + {before ? arrow : null} + + {isProbe ? ( + + {text} + + ) : ( + + + + {text} + + + + )} + + {!before && arrow} + + ) +} + +const styles = StyleSheet.create(({ components, fonts }) => ({ + root: { alignSelf: 'flex-start', alignItems: 'flex-start' }, + vertical: { flexDirection: 'column' }, + horizontal: { flexDirection: 'row' }, + card: { + backgroundColor: components.tooltip.colorScheme.root.background, + borderRadius: components.tooltip.root.borderRadius, + boxShadow: `${components.tooltip.root.subtleShadow}, ${components.tooltip.root.shadow}`, + overflow: 'hidden', + paddingTop: components.tooltip.root.paddingTop, + paddingRight: components.tooltip.root.paddingRight, + paddingBottom: components.tooltip.root.paddingBottom, + paddingLeft: components.tooltip.root.paddingLeft, + flexShrink: 1, + }, + scroll: { flexGrow: 0, flexShrink: 1 }, + scrollContent: { flexGrow: 0 }, + text: { + color: components.tooltip.colorScheme.root.color, + fontFamily: fonts.fontFamily.base, + fontSize: fonts.fontSize[200], + fontWeight: fonts.fontWeight.regular, + lineHeight: fonts.lineHeight[300], + textAlign: 'center', + flexShrink: 1, + }, + arrowSlot: { alignItems: 'center', justifyContent: 'center' }, + centerArrow: { alignSelf: 'center' }, +})) diff --git a/src/components/Tooltip/internal/assets/arrow.json b/src/components/Tooltip/internal/assets/arrow.json new file mode 100644 index 00000000..ae0c2e67 --- /dev/null +++ b/src/components/Tooltip/internal/assets/arrow.json @@ -0,0 +1,5 @@ +{ + "width": 7.0, + "height": 3.5, + "xml": "\n\n\n" +} diff --git a/src/components/Tooltip/types.ts b/src/components/Tooltip/types.ts new file mode 100644 index 00000000..04f8063e --- /dev/null +++ b/src/components/Tooltip/types.ts @@ -0,0 +1,24 @@ +import type { RefObject } from 'react' +import type { View, ViewProps } from 'react-native' + +/** Предпочтительная сторона подсказки относительно якоря. */ +export type TooltipPosition = 'top' | 'bottom' | 'left' | 'right' + +export interface TooltipProps extends Pick { + /** Текст визуальной подсказки. */ + text: string + /** Ссылка на native View якоря. При отдельной обёртке задайте collapsable={false}. */ + anchorRef: RefObject + /** Управляет показом. */ + isVisible: boolean + /** + * Запрос закрытия при касании вне подсказки (включая начало свайпа) или Android Back. + * Обновите isVisible снаружи. + */ + onClose: () => void + /** + * Предпочтительная сторона, меняется при нехватке места. + * @default 'top' + */ + position?: TooltipPosition +} From 941318532db80eaf2f8cbf69a64fe1664d313df0 Mon Sep 17 00:00:00 2001 From: Alesya Volosach Date: Thu, 19 Nov 2026 14:05:36 +0300 Subject: [PATCH 03/12] =?UTF-8?q?feat(tooltip):=20=D0=B4=D0=BE=D0=B1=D0=B0?= =?UTF-8?q?=D0=B2=D0=BB=D0=B5=D0=BD=20=D1=80=D0=B0=D1=81=D1=87=D1=91=D1=82?= =?UTF-8?q?=20=D1=80=D0=B0=D0=B7=D0=BC=D0=B5=D1=89=D0=B5=D0=BD=D0=B8=D1=8F?= =?UTF-8?q?=20=D0=BF=D0=BE=D0=B4=D1=81=D0=BA=D0=B0=D0=B7=D0=BA=D0=B8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../Tooltip/__tests__/placement.test.ts | 146 +++++++++++++++ src/components/Tooltip/internal/placement.ts | 169 ++++++++++++++++++ 2 files changed, 315 insertions(+) create mode 100644 src/components/Tooltip/__tests__/placement.test.ts create mode 100644 src/components/Tooltip/internal/placement.ts diff --git a/src/components/Tooltip/__tests__/placement.test.ts b/src/components/Tooltip/__tests__/placement.test.ts new file mode 100644 index 00000000..907e568a --- /dev/null +++ b/src/components/Tooltip/__tests__/placement.test.ts @@ -0,0 +1,146 @@ +import { + getTooltipBounds, + getTooltipCoordinates, + getTooltipPlacement, + rectsIntersect, +} from '../internal/placement' +import type { TooltipPosition } from '../types' + +const bounds = { x: 12, y: 40, width: 336, height: 680 } +const anchor = { x: 150, y: 350, width: 60, height: 40 } +const size = { width: 100, height: 50 } +const options = { + bounds, + anchor, + size, + gutter: 4, + arrowDepth: 3.5, + arrowWidth: 7, + borderRadius: 8, +} + +const placeTooltip = ( + input: typeof options & { position: TooltipPosition } +) => { + const placement = getTooltipPlacement(input) + const size = { + width: Math.min(input.size.width, placement.maxWidth), + height: Math.min(input.size.height, placement.maxHeight), + } + + return { + ...placement, + ...getTooltipCoordinates({ ...input, position: placement.position, size }), + } +} + +describe('Tooltip — размещение', () => { + test.each(['top', 'bottom', 'left', 'right'] as const)( + 'сохраняет сторону %s при достаточном месте', + (position) => { + expect(placeTooltip({ ...options, position }).position).toBe(position) + } + ) + + test.each([ + { + name: 'сверху', + position: 'top', + anchor: { ...anchor, y: 40 }, + expected: 'bottom', + }, + { + name: 'снизу', + position: 'bottom', + anchor: { ...anchor, y: 680 }, + expected: 'top', + }, + { + name: 'слева', + position: 'left', + anchor: { ...anchor, x: 12 }, + expected: 'right', + }, + { + name: 'справа', + position: 'right', + anchor: { ...anchor, x: 288 }, + expected: 'left', + }, + ] as const)( + 'переворачивает подсказку у края $name', + ({ position, anchor, expected }) => { + expect(placeTooltip({ ...options, position, anchor }).position).toBe( + expected + ) + } + ) + + test.each([ + { name: 'левый верхний', x: 12, y: 40 }, + { name: 'правый верхний', x: 288, y: 40 }, + { name: 'левый нижний', x: 12, y: 680 }, + { name: 'правый нижний', x: 288, y: 680 }, + ])('удерживает карточку и стрелку внутри границ: $name угол', ({ x, y }) => { + const layout = placeTooltip({ + ...options, + position: 'top', + anchor: { ...anchor, x, y }, + }) + + expect(layout.x).toBeGreaterThanOrEqual(bounds.x) + expect(layout.y).toBeGreaterThanOrEqual(bounds.y) + expect(layout.x + layout.width).toBeLessThanOrEqual(bounds.x + bounds.width) + expect(layout.y + layout.height).toBeLessThanOrEqual( + bounds.y + bounds.height + ) + expect(layout.arrowOffset).toBeGreaterThanOrEqual(8) + expect(layout.arrowOffset + 7).toBeLessThanOrEqual(layout.width - 8) + }) + + test('выбирает доступную сторону и ограничивает огромный текст', () => { + const layout = placeTooltip({ + ...options, + position: 'left', + size: { width: 1000, height: 2000 }, + }) + + expect(layout.position).toBe('bottom') + expect(layout.width).toBeLessThanOrEqual(bounds.width) + expect(layout.height).toBeLessThanOrEqual(bounds.height) + expect(layout.y + layout.height).toBeLessThanOrEqual( + bounds.y + bounds.height + ) + }) + + test('учитывает изменившуюся безопасную область', () => { + const nextBounds = { x: 30, y: 70, width: 200, height: 250 } + const layout = placeTooltip({ + ...options, + position: 'right', + bounds: nextBounds, + }) + + expect(layout.x).toBeGreaterThanOrEqual(nextBounds.x) + expect(layout.y).toBeGreaterThanOrEqual(nextBounds.y) + expect(layout.x + layout.width).toBeLessThanOrEqual(230) + expect(layout.y + layout.height).toBeLessThanOrEqual(320) + }) + + test('отнимает safe area и отступ от размеров viewport', () => { + expect( + getTooltipBounds({ + viewport: { x: 0, y: 0, width: 360, height: 740 }, + window: { width: 360, height: 740 }, + insets: { top: 36, bottom: 16, left: 8, right: 8 }, + gutter: 4, + }) + ).toStrictEqual({ x: 12, y: 40, width: 336, height: 680 }) + }) + + test('отличает видимый якорь от полностью скрытого за краем', () => { + expect(rectsIntersect(bounds, anchor)).toBeTrue() + expect(rectsIntersect(bounds, { ...anchor, y: 800 })).toBeFalse() + expect(rectsIntersect(bounds, { ...anchor, x: -100 })).toBeFalse() + }) +}) diff --git a/src/components/Tooltip/internal/placement.ts b/src/components/Tooltip/internal/placement.ts new file mode 100644 index 00000000..fbecf940 --- /dev/null +++ b/src/components/Tooltip/internal/placement.ts @@ -0,0 +1,169 @@ +import type { TooltipPosition } from '../types' + +export interface Rect { + x: number + y: number + width: number + height: number +} + +export type Size = Pick + +interface GeometryOptions { + anchor: Rect + bounds: Rect + size: Size + position: TooltipPosition + gutter: number + arrowDepth: number +} + +interface CoordinateOptions extends GeometryOptions { + arrowWidth: number + borderRadius: number +} + +const opposite: Record = { + top: 'bottom', + bottom: 'top', + left: 'right', + right: 'left', +} + +const clamp = (value: number, min: number, max: number) => + Math.max(min, Math.min(value, max)) + +export const rectsIntersect = (bounds: Rect, anchor: Rect) => + anchor.x + anchor.width > bounds.x && + anchor.y + anchor.height > bounds.y && + anchor.x < bounds.x + bounds.width && + anchor.y < bounds.y + bounds.height + +export const getTooltipBounds = ({ + viewport, + window, + insets, + gutter, +}: { + viewport: Rect + window: Size + insets: Record<'top' | 'bottom' | 'left' | 'right', number> + gutter: number +}): Rect => { + const x = Math.max(0, insets.left - viewport.x) + gutter + const y = Math.max(0, insets.top - viewport.y) + gutter + const right = Math.min( + viewport.width, + window.width - insets.right - viewport.x + ) + const bottom = Math.min( + viewport.height, + window.height - insets.bottom - viewport.y + ) + + return { + x, + y, + width: Math.max(0, right - gutter - x), + height: Math.max(0, bottom - gutter - y), + } +} + +export const getTooltipPlacement = ({ + anchor, + bounds, + size, + position, + gutter, + arrowDepth, +}: GeometryOptions) => { + const space = { + top: Math.max(0, anchor.y - bounds.y - gutter), + bottom: Math.max( + 0, + bounds.y + bounds.height - anchor.y - anchor.height - gutter + ), + left: Math.max(0, anchor.x - bounds.x - gutter), + right: Math.max( + 0, + bounds.x + bounds.width - anchor.x - anchor.width - gutter + ), + } + const fits = (side: TooltipPosition) => + (side === 'top' || side === 'bottom' ? size.height : size.width) + + arrowDepth <= + space[side] + let side = position + + if (!fits(side)) { + side = fits(opposite[side]) + ? opposite[side] + : (Object.keys(space) as TooltipPosition[]).reduce( + (best, next) => (space[next] > space[best] ? next : best), + side + ) + } + + const vertical = side === 'top' || side === 'bottom' + const maxWidth = Math.max( + 0, + (vertical ? bounds.width : Math.min(bounds.width, space[side])) - + (vertical ? 0 : arrowDepth) + ) + const maxHeight = Math.max( + 0, + (vertical ? Math.min(bounds.height, space[side]) : bounds.height) - + (vertical ? arrowDepth : 0) + ) + + return { position: side, maxWidth, maxHeight } +} + +export const getTooltipCoordinates = ({ + anchor, + bounds, + size, + position, + gutter, + arrowDepth, + arrowWidth, + borderRadius, +}: CoordinateOptions) => { + const vertical = position === 'top' || position === 'bottom' + const width = size.width + (vertical ? 0 : arrowDepth) + const height = size.height + (vertical ? arrowDepth : 0) + const centerX = anchor.x + anchor.width / 2 + const centerY = anchor.y + anchor.height / 2 + let x = centerX - width / 2 + let y = centerY - height / 2 + + switch (position) { + case 'left': + x = anchor.x - gutter - width + break + + case 'right': + x = anchor.x + anchor.width + gutter + break + + case 'top': + y = anchor.y - gutter - height + break + + case 'bottom': + y = anchor.y + anchor.height + gutter + break + } + + x = clamp(x, bounds.x, bounds.x + bounds.width - width) + y = clamp(y, bounds.y, bounds.y + bounds.height - height) + const edge = vertical ? width : height + const inset = Math.min(borderRadius, Math.max(0, (edge - arrowWidth) / 2)) + const arrowOffset = clamp( + (vertical ? centerX - x : centerY - y) - arrowWidth / 2, + inset, + edge - inset - arrowWidth + ) + + return { x, y, width, height, arrowOffset } +} From 5ff083fa0fe842312d0c3f7b5608450c455252ef Mon Sep 17 00:00:00 2001 From: Alesya Volosach Date: Thu, 19 Nov 2026 14:06:43 +0300 Subject: [PATCH 04/12] =?UTF-8?q?feat(tooltip):=20=D0=B4=D0=BE=D0=B1=D0=B0?= =?UTF-8?q?=D0=B2=D0=BB=D0=B5=D0=BD=20=D0=BF=D0=BE=D0=BA=D0=B0=D0=B7=20?= =?UTF-8?q?=D0=BF=D0=BE=D0=B4=D1=81=D0=BA=D0=B0=D0=B7=D0=BA=D0=B8=20=D0=B2?= =?UTF-8?q?=D0=BE=D0=B7=D0=BB=D0=B5=20=D1=8F=D0=BA=D0=BE=D1=80=D1=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/components/Tooltip/Tooltip.tsx | 83 ++++++++ src/components/Tooltip/TooltipProvider.tsx | 100 +++++++++ .../Tooltip/__tests__/Tooltip.test.tsx | 190 ++++++++++++++++++ src/components/Tooltip/index.ts | 3 + .../Tooltip/internal/TooltipContext.ts | 43 ++++ .../Tooltip/internal/TooltipOverlay.tsx | 151 ++++++++++++++ .../Tooltip/internal/measureInViewport.ts | 12 ++ src/components/index.ts | 2 + 8 files changed, 584 insertions(+) create mode 100644 src/components/Tooltip/Tooltip.tsx create mode 100644 src/components/Tooltip/TooltipProvider.tsx create mode 100644 src/components/Tooltip/__tests__/Tooltip.test.tsx create mode 100644 src/components/Tooltip/index.ts create mode 100644 src/components/Tooltip/internal/TooltipContext.ts create mode 100644 src/components/Tooltip/internal/TooltipOverlay.tsx create mode 100644 src/components/Tooltip/internal/measureInViewport.ts diff --git a/src/components/Tooltip/Tooltip.tsx b/src/components/Tooltip/Tooltip.tsx new file mode 100644 index 00000000..0f53f78f --- /dev/null +++ b/src/components/Tooltip/Tooltip.tsx @@ -0,0 +1,83 @@ +import { useLayoutEffect, useState } from 'react' +import { useWindowDimensions } from 'react-native' + +import { TooltipPortal, useTooltipHost } from './internal/TooltipContext' +import { TooltipOverlay } from './internal/TooltipOverlay' +import { measureInViewport } from './internal/measureInViewport' +import { rectsIntersect, type Rect } from './internal/placement' +import type { TooltipProps } from './types' + +const VisibleTooltip = ({ + anchorRef, + text, + position = 'top', + onClose, + testID, +}: Omit) => { + const { fontScale } = useWindowDimensions() + const { viewport, bounds } = useTooltipHost() + const [measurement, setMeasurement] = useState<{ + anchor?: Rect + pending: boolean + }>({ pending: true }) + + useLayoutEffect(() => { + let active = true + const node = anchorRef.current + + if (!node || !viewport || !bounds) { + setMeasurement({ pending: false }) + + return + } + + setMeasurement((previous) => ({ ...previous, pending: true })) + measureInViewport(node, (rect) => { + if (active) + setMeasurement({ + anchor: rect.width > 0 && rect.height > 0 ? rect : undefined, + pending: false, + }) + }) + + return () => { + active = false + } + }, [anchorRef, text, position, viewport, bounds, fontScale]) + + const { anchor, pending } = measurement + + if ( + !anchor || + !viewport || + !bounds || + bounds.width <= 0 || + bounds.height <= 0 || + !rectsIntersect(bounds, { + ...anchor, + x: anchor.x - viewport.x, + y: anchor.y - viewport.y, + }) + ) + return null + + return ( + + + + ) +} + +/** Управляемая текстовая подсказка возле native View. Требует TooltipProvider. */ +export const Tooltip = ({ isVisible, ...props }: TooltipProps) => + isVisible ? : null diff --git a/src/components/Tooltip/TooltipProvider.tsx b/src/components/Tooltip/TooltipProvider.tsx new file mode 100644 index 00000000..e11bb8b1 --- /dev/null +++ b/src/components/Tooltip/TooltipProvider.tsx @@ -0,0 +1,100 @@ +import { + Fragment, + useCallback, + useLayoutEffect, + useMemo, + useRef, + useState, + type PropsWithChildren, + type ReactNode, +} from 'react' +import { View, useWindowDimensions } from 'react-native' +import { StyleSheet, useUnistyles } from 'react-native-unistyles' + +import { TooltipContext } from './internal/TooltipContext' +import { measureInViewport } from './internal/measureInViewport' +import { getTooltipBounds, type Rect } from './internal/placement' + +/** + * Слой подсказок поверх содержимого экрана. + * Размещайте вокруг экрана вне ScrollView. В native Modal нужен свой провайдер, + * Android Back обрабатывается через onRequestClose самой модалки. + */ +export const TooltipProvider = ({ children }: PropsWithChildren) => { + const rootRef = useRef(null) + const [viewport, setViewport] = useState() + const [overlays, setOverlays] = useState(() => new Map()) + const { width, height } = useWindowDimensions() + const { theme, rt } = useUnistyles() + const { top, bottom, left, right } = rt.insets + const gutter = theme.components.tooltip.root.gutter + + const measure = useCallback(() => { + const root = rootRef.current + + if (root) + measureInViewport(root, (rect) => { + setViewport((previous) => + previous?.x === rect.x && + previous?.y === rect.y && + previous?.width === rect.width && + previous?.height === rect.height + ? previous + : rect + ) + }) + }, []) + + useLayoutEffect(measure, [measure, width, height]) + + const update = useCallback((id: string, content: ReactNode) => { + setOverlays((previous) => new Map(previous).set(id, content)) + }, []) + const remove = useCallback((id: string) => { + setOverlays((previous) => { + const next = new Map(previous) + next.delete(id) + + return next + }) + }, []) + const bounds = useMemo( + () => + viewport && + getTooltipBounds({ + viewport, + window: { width, height }, + insets: { top, bottom, left, right }, + gutter, + }), + [viewport, width, height, top, bottom, left, right, gutter] + ) + const host = useMemo( + () => ({ viewport, bounds, update, remove }), + [viewport, bounds, update, remove] + ) + + return ( + + + {children} + + {Array.from(overlays, ([id, content]) => ( + {content} + ))} + + + + ) +} + +const styles = StyleSheet.create({ + root: { flex: 1 }, + layer: { position: 'absolute', top: 0, bottom: 0, left: 0, right: 0 }, +}) diff --git a/src/components/Tooltip/__tests__/Tooltip.test.tsx b/src/components/Tooltip/__tests__/Tooltip.test.tsx new file mode 100644 index 00000000..9edc71eb --- /dev/null +++ b/src/components/Tooltip/__tests__/Tooltip.test.tsx @@ -0,0 +1,190 @@ +import { act, fireEvent, render, screen } from '@testing-library/react-native' +import { BackHandler, Dimensions, Modal, View } from 'react-native' + +import { Tooltip, TooltipProvider } from '..' +import type { TooltipProps } from '../types' + +const measureViewport = (callback: Parameters[0]) => + callback(0, 0, 360, 740, 0, 0) +const layout = (width: number, height: number) => ({ + nativeEvent: { layout: { x: 0, y: 0, width, height } }, +}) +const measureContent = async () => { + fireEvent( + await screen.findByTestId('TooltipProbe'), + 'layout', + layout(120, 40) + ) +} + +const show = async () => { + await measureContent() + fireEvent(screen.getByTestId('TooltipBubble'), 'layout', layout(120, 40)) +} + +const setup = (props: Partial = {}) => { + const anchor: Pick = { + measure: (callback) => callback(0, 0, 60, 40, 150, 300), + } + const initialProps: TooltipProps = { + anchorRef: { current: anchor as View }, + isVisible: true, + onClose: jest.fn(), + text: 'Подсказка', + ...props, + } + const content = (next: Partial = {}) => ( + + + + ) + const result = render(content()) + + return { + ...result, + props: initialProps, + update: (next: Partial) => result.rerender(content(next)), + } +} + +describe('Tooltip', () => { + beforeEach(() => { + jest + .spyOn(Dimensions, 'get') + .mockReturnValue({ width: 360, height: 740, scale: 1, fontScale: 1 }) + jest.spyOn(View.prototype, 'measure').mockImplementation(measureViewport) + }) + + afterEach(() => jest.restoreAllMocks()) + + test('показывает текст после измерения и скрывает при обновлении isVisible', async () => { + const { update, UNSAFE_queryByType } = setup() + await measureContent() + + expect(screen.getByTestId('TooltipBubble')).not.toBeVisible() + + fireEvent(screen.getByTestId('TooltipBubble'), 'layout', layout(120, 40)) + + expect(screen.getByText('Подсказка')).toBeVisible() + expect(UNSAFE_queryByType(Modal)).toBeNull() + + update({ isVisible: false }) + + expect(screen.queryByText('Подсказка')).not.toBeOnTheScreen() + }) + + test('запрашивает закрытие при начале касания снаружи и ждёт обновления isVisible', async () => { + const { props, update } = setup() + await show() + const touch = { nativeEvent: { pageX: 10, pageY: 10 } } + fireEvent(screen.getByText('Подсказка'), 'pressIn', touch) + + expect(props.onClose).not.toHaveBeenCalled() + + fireEvent(screen.getByTestId('TooltipBackdrop'), 'pressIn', touch) + + expect(props.onClose).toHaveBeenCalledExactlyOnceWith() + expect(screen.getByText('Подсказка')).toBeVisible() + + fireEvent.press(screen.getByTestId('TooltipBackdrop'), touch) + + expect(props.onClose).toHaveBeenCalledOnce() + + update({ isVisible: false }) + + expect(screen.queryByTestId('TooltipViewport')).not.toBeOnTheScreen() + }) + + test('запрашивает закрытие по Android Back и удаляет подписку после скрытия', async () => { + const subscribe = jest.spyOn(BackHandler, 'addEventListener') + const { props, update } = setup() + await show() + + const back = subscribe.mock.calls.at(-1)?.[1] + let handled: boolean | null | undefined + act(() => { + handled = back?.() + }) + + expect(handled).toBeTrue() + expect(props.onClose).toHaveBeenCalledExactlyOnceWith() + expect(screen.getByText('Подсказка')).toBeVisible() + + const subscription = subscribe.mock.results.at(-1)?.value + const remove = jest.spyOn(subscription, 'remove') + update({ isVisible: false }) + + expect(screen.queryByTestId('TooltipViewport')).not.toBeOnTheScreen() + expect(remove).toHaveBeenCalledOnce() + }) + + test('не показывает подсказку при отсутствующем якоре', async () => { + setup({ anchorRef: { current: null } }) + await act(() => Promise.resolve()) + + expect(screen.queryByTestId('TooltipViewport')).not.toBeOnTheScreen() + }) + + test('не создаёт overlay для якоря за экраном', async () => { + const anchor: Pick = { + measure: (callback) => callback(0, 0, 40, 40, 100, 1000), + } + setup({ anchorRef: { current: anchor as View } }) + await act(() => Promise.resolve()) + + expect(screen.queryByTestId('TooltipViewport')).not.toBeOnTheScreen() + }) + + test('не создаёт overlay, пока закрыт', () => { + setup({ isVisible: false }) + + expect(screen.queryByTestId('TooltipViewport')).not.toBeOnTheScreen() + }) + + test('обновляет текст после повторного измерения', async () => { + const { update } = setup() + await show() + update({ text: 'Новый текст' }) + await measureContent() + + expect(screen.getByTestId('TooltipBubble')).not.toBeVisible() + + fireEvent(screen.getByTestId('TooltipBubble'), 'layout', layout(120, 40)) + + expect(screen.getByText('Новый текст')).toBeVisible() + expect(screen.queryByText('Подсказка')).not.toBeOnTheScreen() + }) + + test('размещает подсказку относительно смещённого провайдера в координатах viewport', async () => { + jest + .mocked(View.prototype.measure) + .mockImplementation((callback) => callback(0, 0, 300, 600, 24, 100)) + const measure = jest.fn< + ReturnType, + Parameters + >() + measure.mockImplementation((callback) => callback(0, 0, 60, 40, 150, 300)) + const measureInWindow = jest.fn< + ReturnType, + Parameters + >() + measureInWindow.mockImplementation((callback) => callback(150, 276, 60, 40)) + const anchor: Pick = { + measure, + measureInWindow, + } + setup({ + anchorRef: { current: anchor as View }, + testID: 'PositionedTooltip', + }) + await show() + + expect(measure).toHaveBeenCalledWith(expect.any(Function)) + expect(measureInWindow).not.toHaveBeenCalled() + expect(screen.getByTestId('PositionedTooltip')).toBeVisible() + expect(screen.getByTestId('PositionedTooltip')).toHaveStyle({ + left: 96, + top: 152.5, + }) + }) +}) diff --git a/src/components/Tooltip/index.ts b/src/components/Tooltip/index.ts new file mode 100644 index 00000000..f9e3eca2 --- /dev/null +++ b/src/components/Tooltip/index.ts @@ -0,0 +1,3 @@ +export { Tooltip } from './Tooltip' +export { TooltipProvider } from './TooltipProvider' +export type { TooltipProps, TooltipPosition } from './types' diff --git a/src/components/Tooltip/internal/TooltipContext.ts b/src/components/Tooltip/internal/TooltipContext.ts new file mode 100644 index 00000000..7deb3e8b --- /dev/null +++ b/src/components/Tooltip/internal/TooltipContext.ts @@ -0,0 +1,43 @@ +import { + createContext, + useContext, + useId, + useLayoutEffect, + type ReactNode, +} from 'react' + +import type { Rect } from './placement' + +interface TooltipHost { + viewport?: Rect + bounds?: Rect + update: (id: string, content: ReactNode) => void + remove: (id: string) => void +} + +export const TooltipContext = createContext(null) + +export const useTooltipHost = () => { + const host = useContext(TooltipContext) + + if (!host) throw new Error('Tooltip должен находиться внутри TooltipProvider') + + return host +} + +export const TooltipPortal = ({ + children, +}: { + readonly children: ReactNode +}) => { + const { update, remove } = useTooltipHost() + const id = useId() + + useLayoutEffect(() => { + update(id, children) + }, [id, children, update]) + + useLayoutEffect(() => () => remove(id), [id, remove]) + + return null +} diff --git a/src/components/Tooltip/internal/TooltipOverlay.tsx b/src/components/Tooltip/internal/TooltipOverlay.tsx new file mode 100644 index 00000000..ab90e701 --- /dev/null +++ b/src/components/Tooltip/internal/TooltipOverlay.tsx @@ -0,0 +1,151 @@ +import { useEffect, useLayoutEffect, useState } from 'react' +import { BackHandler, Pressable, View } from 'react-native' +import { StyleSheet, useUnistyles } from 'react-native-unistyles' + +import type { TooltipProps } from '../types' + +import { ARROW_DEPTH, ARROW_WIDTH, TooltipBubble } from './TooltipBubble' +import { + getTooltipCoordinates, + getTooltipPlacement, + type Rect, + type Size, +} from './placement' + +interface TooltipOverlayProps extends Pick< + TooltipProps, + 'text' | 'position' | 'testID' | 'onClose' +> { + readonly viewport: Rect + readonly bounds: Rect + readonly anchor: Rect + readonly fontScale: number + readonly isMeasuring: boolean +} + +const PositionedTooltip = ({ + anchor, + viewport, + bounds, + text, + position = 'top', + fontScale, + isMeasuring, + testID, +}: Omit) => { + const { theme } = useUnistyles() + const tokens = theme.components.tooltip.root + const maxWidth = Math.min(tokens.maxWidth, bounds.width) + const [naturalSize, setNaturalSize] = useState() + const [cardSize, setCardSize] = useState() + + useLayoutEffect(() => { + setNaturalSize(undefined) + setCardSize(undefined) + }, [text, position, fontScale, maxWidth, bounds.width, bounds.height]) + + const localAnchor = { + ...anchor, + x: anchor.x - viewport.x, + y: anchor.y - viewport.y, + } + const options = { + anchor: localAnchor, + bounds, + position, + gutter: tokens.gutter, + arrowDepth: ARROW_DEPTH, + } + const placement = + naturalSize && getTooltipPlacement({ ...options, size: naturalSize }) + const coordinates = + placement && + cardSize && + getTooltipCoordinates({ + ...options, + position: placement.position, + size: cardSize, + arrowWidth: ARROW_WIDTH, + borderRadius: tokens.borderRadius, + }) + + return ( + <> + {naturalSize ? null : ( + + + setNaturalSize({ width: layout.width, height: layout.height }) + } + /> + + )} + {placement ? ( + + { + setCardSize((previous) => + previous?.width === layout.width && + previous?.height === layout.height + ? previous + : { width: layout.width, height: layout.height } + ) + }} + /> + + ) : null} + + ) +} + +export const TooltipOverlay = ({ onClose, ...props }: TooltipOverlayProps) => { + useEffect(() => { + const subscription = BackHandler.addEventListener( + 'hardwareBackPress', + () => { + onClose() + + return true + } + ) + + return () => subscription.remove() + }, [onClose]) + + return ( + + onClose()} + /> + + + ) +} + +const styles = StyleSheet.create({ + backdrop: { position: 'absolute', top: 0, bottom: 0, left: 0, right: 0 }, + positioned: { position: 'absolute' }, + hidden: { opacity: 0 }, + probe: { position: 'absolute', opacity: 0 }, +}) diff --git a/src/components/Tooltip/internal/measureInViewport.ts b/src/components/Tooltip/internal/measureInViewport.ts new file mode 100644 index 00000000..cd7ee593 --- /dev/null +++ b/src/components/Tooltip/internal/measureInViewport.ts @@ -0,0 +1,12 @@ +import type { View } from 'react-native' + +import type { Rect } from './placement' + +export const measureInViewport = ( + view: View, + onMeasure: (rect: Rect) => void +) => { + view.measure((...[, , width, height, x, y]) => + onMeasure({ x, y, width, height }) + ) +} diff --git a/src/components/index.ts b/src/components/index.ts index 9775f1ef..462e61db 100644 --- a/src/components/index.ts +++ b/src/components/index.ts @@ -22,3 +22,5 @@ export * from './Tabs' export * from './List/Base' export * from './Accordion' export * from './Dialog' + +export * from './Tooltip' From 331a8aa4fbf719ed641b67346f47979795710bf8 Mon Sep 17 00:00:00 2001 From: Alesya Volosach Date: Thu, 19 Nov 2026 14:07:00 +0300 Subject: [PATCH 05/12] =?UTF-8?q?feat(tooltip):=20=D0=B4=D0=BE=D0=B1=D0=B0?= =?UTF-8?q?=D0=B2=D0=BB=D0=B5=D0=BD=D0=B0=20=D0=BF=D0=BE=D0=B4=D0=B4=D0=B5?= =?UTF-8?q?=D1=80=D0=B6=D0=BA=D0=B0=20=D0=BE=D1=82=D0=BA=D1=80=D1=8B=D1=82?= =?UTF-8?q?=D0=BE=D0=B9=20=D0=BA=D0=BB=D0=B0=D0=B2=D0=B8=D0=B0=D1=82=D1=83?= =?UTF-8?q?=D1=80=D1=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/components/Tooltip/TooltipProvider.tsx | 7 ++- .../Tooltip/__tests__/Tooltip.test.tsx | 52 ++++++++++++++++++- .../Tooltip/__tests__/placement.test.ts | 31 +++++++++++ .../Tooltip/internal/TooltipBubble.tsx | 3 +- .../Tooltip/internal/TooltipOverlay.tsx | 7 ++- src/components/Tooltip/internal/placement.ts | 12 ++++- .../Tooltip/internal/useKeyboardFrame.ts | 29 +++++++++++ src/components/Tooltip/types.ts | 1 + 8 files changed, 136 insertions(+), 6 deletions(-) create mode 100644 src/components/Tooltip/internal/useKeyboardFrame.ts diff --git a/src/components/Tooltip/TooltipProvider.tsx b/src/components/Tooltip/TooltipProvider.tsx index e11bb8b1..4d89f150 100644 --- a/src/components/Tooltip/TooltipProvider.tsx +++ b/src/components/Tooltip/TooltipProvider.tsx @@ -14,9 +14,10 @@ import { StyleSheet, useUnistyles } from 'react-native-unistyles' import { TooltipContext } from './internal/TooltipContext' import { measureInViewport } from './internal/measureInViewport' import { getTooltipBounds, type Rect } from './internal/placement' +import { useKeyboardFrame } from './internal/useKeyboardFrame' /** - * Слой подсказок поверх содержимого экрана. + * Слой подсказок поверх содержимого экрана, сохраняющий фокус и клавиатуру. * Размещайте вокруг экрана вне ScrollView. В native Modal нужен свой провайдер, * Android Back обрабатывается через onRequestClose самой модалки. */ @@ -28,6 +29,7 @@ export const TooltipProvider = ({ children }: PropsWithChildren) => { const { theme, rt } = useUnistyles() const { top, bottom, left, right } = rt.insets const gutter = theme.components.tooltip.root.gutter + const keyboard = useKeyboardFrame() const measure = useCallback(() => { const root = rootRef.current @@ -66,8 +68,9 @@ export const TooltipProvider = ({ children }: PropsWithChildren) => { window: { width, height }, insets: { top, bottom, left, right }, gutter, + keyboard, }), - [viewport, width, height, top, bottom, left, right, gutter] + [viewport, width, height, top, bottom, left, right, gutter, keyboard] ) const host = useMemo( () => ({ viewport, bounds, update, remove }), diff --git a/src/components/Tooltip/__tests__/Tooltip.test.tsx b/src/components/Tooltip/__tests__/Tooltip.test.tsx index 9edc71eb..2be9ac41 100644 --- a/src/components/Tooltip/__tests__/Tooltip.test.tsx +++ b/src/components/Tooltip/__tests__/Tooltip.test.tsx @@ -1,5 +1,12 @@ import { act, fireEvent, render, screen } from '@testing-library/react-native' -import { BackHandler, Dimensions, Modal, View } from 'react-native' +import { + BackHandler, + Dimensions, + Keyboard, + Modal, + View, + type KeyboardEvent, +} from 'react-native' import { Tooltip, TooltipProvider } from '..' import type { TooltipProps } from '../types' @@ -53,6 +60,7 @@ describe('Tooltip', () => { .spyOn(Dimensions, 'get') .mockReturnValue({ width: 360, height: 740, scale: 1, fontScale: 1 }) jest.spyOn(View.prototype, 'measure').mockImplementation(measureViewport) + jest.spyOn(Keyboard, 'metrics').mockReturnValue(undefined) }) afterEach(() => jest.restoreAllMocks()) @@ -155,6 +163,48 @@ describe('Tooltip', () => { expect(screen.queryByText('Подсказка')).not.toBeOnTheScreen() }) + test('учитывает уже открытую клавиатуру и её закрытие без изменения isVisible', async () => { + const frame = { screenX: 0, screenY: 500, width: 360, height: 240 } + const event: KeyboardEvent = { + duration: 0, + easing: 'keyboard', + startCoordinates: frame, + endCoordinates: frame, + } + jest.mocked(Keyboard.metrics).mockReturnValue(frame) + const subscribe = jest.spyOn(Keyboard, 'addListener') + const anchor: Pick = { + measure: (callback) => callback(0, 0, 60, 40, 150, 600), + } + const { props, unmount } = setup({ anchorRef: { current: anchor as View } }) + await act(() => Promise.resolve()) + + expect(screen.queryByTestId('TooltipViewport')).not.toBeOnTheScreen() + + const hide = subscribe.mock.calls.find( + ([event]) => event === 'keyboardDidHide' + )?.[1] + act(() => hide?.(event)) + await show() + + expect(screen.getByText('Подсказка')).toBeVisible() + + const showKeyboard = subscribe.mock.calls.find( + ([event]) => event === 'keyboardDidShow' + )?.[1] + act(() => showKeyboard?.(event)) + + expect(screen.queryByTestId('TooltipViewport')).not.toBeOnTheScreen() + expect(props.onClose).not.toHaveBeenCalled() + + const removals = subscribe.mock.results.map(({ value }) => + jest.spyOn(value, 'remove') + ) + unmount() + + for (const remove of removals) expect(remove).toHaveBeenCalledOnce() + }) + test('размещает подсказку относительно смещённого провайдера в координатах viewport', async () => { jest .mocked(View.prototype.measure) diff --git a/src/components/Tooltip/__tests__/placement.test.ts b/src/components/Tooltip/__tests__/placement.test.ts index 907e568a..9e4c0e82 100644 --- a/src/components/Tooltip/__tests__/placement.test.ts +++ b/src/components/Tooltip/__tests__/placement.test.ts @@ -138,6 +138,37 @@ describe('Tooltip — размещение', () => { ).toStrictEqual({ x: 12, y: 40, width: 336, height: 680 }) }) + test.each([ + { + name: 'полноэкранный слой', + viewport: { x: 0, y: 0, width: 360, height: 740 }, + expected: { x: 4, y: 40, width: 352, height: 456 }, + }, + { + name: 'слой ниже заголовка', + viewport: { x: 0, y: 100, width: 360, height: 640 }, + expected: { x: 4, y: 4, width: 352, height: 392 }, + }, + { + name: 'окно уже уменьшено клавиатурой', + viewport: { x: 0, y: 0, width: 360, height: 500 }, + expected: { x: 4, y: 40, width: 352, height: 456 }, + }, + ])( + 'ограничивает область над клавиатурой: $name', + ({ viewport, expected }) => { + expect( + getTooltipBounds({ + viewport, + window: { width: 360, height: 740 }, + insets: { top: 36, bottom: 16, left: 0, right: 0 }, + gutter: 4, + keyboard: { screenX: 0, screenY: 500, width: 360, height: 240 }, + }) + ).toStrictEqual(expected) + } + ) + test('отличает видимый якорь от полностью скрытого за краем', () => { expect(rectsIntersect(bounds, anchor)).toBeTrue() expect(rectsIntersect(bounds, { ...anchor, y: 800 })).toBeFalse() diff --git a/src/components/Tooltip/internal/TooltipBubble.tsx b/src/components/Tooltip/internal/TooltipBubble.tsx index 35e2b513..972c6980 100644 --- a/src/components/Tooltip/internal/TooltipBubble.tsx +++ b/src/components/Tooltip/internal/TooltipBubble.tsx @@ -98,10 +98,11 @@ export const TooltipBubble = ({ - + true}> {text} diff --git a/src/components/Tooltip/internal/TooltipOverlay.tsx b/src/components/Tooltip/internal/TooltipOverlay.tsx index ab90e701..8129d7be 100644 --- a/src/components/Tooltip/internal/TooltipOverlay.tsx +++ b/src/components/Tooltip/internal/TooltipOverlay.tsx @@ -131,7 +131,12 @@ export const TooltipOverlay = ({ onClose, ...props }: TooltipOverlayProps) => { }, [onClose]) return ( - + true} + > gutter: number + keyboard?: KeyboardMetrics }): Rect => { const x = Math.max(0, insets.left - viewport.x) + gutter const y = Math.max(0, insets.top - viewport.y) + gutter @@ -56,9 +60,15 @@ export const getTooltipBounds = ({ viewport.width, window.width - insets.right - viewport.x ) + const keyboardOverlaps = + keyboard && + keyboard.height > 0 && + keyboard.screenX < viewport.x + viewport.width && + keyboard.screenX + keyboard.width > viewport.x const bottom = Math.min( viewport.height, - window.height - insets.bottom - viewport.y + window.height - insets.bottom - viewport.y, + keyboardOverlaps ? keyboard.screenY - viewport.y : Infinity ) return { diff --git a/src/components/Tooltip/internal/useKeyboardFrame.ts b/src/components/Tooltip/internal/useKeyboardFrame.ts new file mode 100644 index 00000000..a9a8c815 --- /dev/null +++ b/src/components/Tooltip/internal/useKeyboardFrame.ts @@ -0,0 +1,29 @@ +import { useEffect, useState } from 'react' +import { Keyboard, Platform } from 'react-native' + +export const useKeyboardFrame = () => { + const [frame, setFrame] = useState(() => Keyboard.metrics()) + + useEffect(() => { + const show = Keyboard.addListener('keyboardDidShow', (event) => + setFrame(event.endCoordinates) + ) + const hide = Keyboard.addListener('keyboardDidHide', () => + setFrame(undefined) + ) + const change = + Platform.OS === 'ios' + ? Keyboard.addListener('keyboardWillChangeFrame', (event) => + setFrame(event.endCoordinates) + ) + : undefined + + return () => { + show.remove() + hide.remove() + change?.remove() + } + }, []) + + return frame +} diff --git a/src/components/Tooltip/types.ts b/src/components/Tooltip/types.ts index 04f8063e..eabc7d93 100644 --- a/src/components/Tooltip/types.ts +++ b/src/components/Tooltip/types.ts @@ -13,6 +13,7 @@ export interface TooltipProps extends Pick { isVisible: boolean /** * Запрос закрытия при касании вне подсказки (включая начало свайпа) или Android Back. + * На Android открытая клавиатура обрабатывает первое нажатие Back сама. * Обновите isVisible снаружи. */ onClose: () => void From 2b486340af576e8d7ee817af570e4d48e9015063 Mon Sep 17 00:00:00 2001 From: Alesya Volosach Date: Thu, 19 Nov 2026 14:07:17 +0300 Subject: [PATCH 06/12] =?UTF-8?q?feat(tooltip):=20=D0=B4=D0=BE=D0=B1=D0=B0?= =?UTF-8?q?=D0=B2=D0=BB=D0=B5=D0=BD=D1=8B=20=D0=B4=D0=BE=D1=81=D1=82=D1=83?= =?UTF-8?q?=D0=BF=D0=BD=D0=BE=D1=81=D1=82=D1=8C=20=D0=B8=20=D0=B4=D0=BE?= =?UTF-8?q?=D0=BA=D1=83=D0=BC=D0=B5=D0=BD=D1=82=D0=B0=D1=86=D0=B8=D1=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/components/Tooltip/Tooltip.md | 91 +++++++++++++++ src/components/Tooltip/Tooltip.tsx | 31 +++++- .../__tests__/Tooltip.accessibility.test.tsx | 105 ++++++++++++++++++ .../Tooltip/__tests__/Tooltip.test.tsx | 18 ++- .../internal/useScreenReaderEnabled.ts | 27 +++++ src/components/Tooltip/types.ts | 4 +- 6 files changed, 271 insertions(+), 5 deletions(-) create mode 100644 src/components/Tooltip/Tooltip.md create mode 100644 src/components/Tooltip/__tests__/Tooltip.accessibility.test.tsx create mode 100644 src/components/Tooltip/internal/useScreenReaderEnabled.ts diff --git a/src/components/Tooltip/Tooltip.md b/src/components/Tooltip/Tooltip.md new file mode 100644 index 00000000..7bfc8def --- /dev/null +++ b/src/components/Tooltip/Tooltip.md @@ -0,0 +1,91 @@ +# Tooltip + +Текстовая подсказка возле элемента с внешним управлением видимостью + +## Использование + +```tsx +import { useRef, useState } from 'react' +import type { View } from 'react-native' +import { Button, Tooltip, TooltipProvider } from '@cdek-it/react-native-ui-kit' + +export const Example = () => { + const anchorRef = useRef(null) + const [visible, setVisible] = useState(false) + const explanation = 'Сохраняет PDF на устройство' + + return ( + +