From 8ded42142cb52e44bbd23c77825fa4d88702faf0 Mon Sep 17 00:00:00 2001 From: Alesya Volosach Date: Wed, 18 Nov 2026 15:38:30 +0300 Subject: [PATCH] =?UTF-8?q?feat(menu-item):=20=D0=BE=D0=B1=D0=BD=D0=BE?= =?UTF-8?q?=D0=B2=D0=BB=D0=B5=D0=BD=D1=8B=20=D1=86=D0=B2=D0=B5=D1=82=D0=BE?= =?UTF-8?q?=D0=B2=D1=8B=D0=B5=20=D1=81=D0=BE=D1=81=D1=82=D0=BE=D1=8F=D0=BD?= =?UTF-8?q?=D0=B8=D1=8F=20=D0=BF=D1=83=D0=BD=D0=BA=D1=82=D0=B0=20=D0=BC?= =?UTF-8?q?=D0=B5=D0=BD=D1=8E?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/components/MenuItem/MenuItemAccessory.tsx | 11 +- .../Template/MenuItemTemplate.stories.tsx | 29 +- .../MenuItem/Template/MenuItemTemplate.tsx | 187 ++++-- .../__tests__/MenuItemTemplate.test.tsx | 38 +- .../MenuItemTemplate.test.tsx.snap | 617 +++++++++--------- src/theme/assets/themeDark.json | 18 +- src/theme/assets/themeLight.json | 30 +- 7 files changed, 513 insertions(+), 417 deletions(-) diff --git a/src/components/MenuItem/MenuItemAccessory.tsx b/src/components/MenuItem/MenuItemAccessory.tsx index 958f8e44..5a04110b 100644 --- a/src/components/MenuItem/MenuItemAccessory.tsx +++ b/src/components/MenuItem/MenuItemAccessory.tsx @@ -1,7 +1,7 @@ import { IconLock } from '@tabler/icons-react-native' import { memo, useMemo } from 'react' -import { View } from 'react-native' +import { View, type ColorValue } from 'react-native' import { StyleSheet } from 'react-native-unistyles' @@ -12,13 +12,15 @@ export interface MenuItemAccessoryProps { readonly Icon: SvgSource /** Неактивное состояние. Если true, заменяет Icon на иконку замка. */ readonly disabled?: boolean + /** Цвет аксессуара для текущего состояния родительского пункта меню. */ + readonly color?: ColorValue } /** * Аксессуар элемента меню. Выводится в крайней левой или крайней правой позиции пункта меню. */ export const MenuItemAccessory = memo( - ({ Icon, disabled }) => { + ({ Icon, disabled, color }) => { const IconComponent = useMemo( () => (disabled ? IconLock : Icon), [Icon, disabled] @@ -27,11 +29,12 @@ export const MenuItemAccessory = memo( return ( ({ - color: theme.Menu.Item.menuitemIconColor, + color: color ?? theme.Menu.Item.menuitemIconColor, })} + width={styles.icon.width} /> ) diff --git a/src/components/MenuItem/Template/MenuItemTemplate.stories.tsx b/src/components/MenuItem/Template/MenuItemTemplate.stories.tsx index ceb4145e..59ca942d 100644 --- a/src/components/MenuItem/Template/MenuItemTemplate.stories.tsx +++ b/src/components/MenuItem/Template/MenuItemTemplate.stories.tsx @@ -23,11 +23,11 @@ const meta: Meta = { args: { title: 'Menu Item', Icon: undefined, - iconColor: 'rgba(0, 0, 0, 0.8000)', badgeSeverity: undefined, caption: 'Caption', separator: false, disabled: false, + selected: false, extra: undefined, }, argTypes: { @@ -42,16 +42,20 @@ const meta: Meta = { mapping: Icons, }, Icon: { control: 'select', options: Object.keys(Icons), mapping: Icons }, - iconColor: { control: { type: 'color' } }, badgeSeverity: { control: 'radio', options: ['undefined', 'basic', 'info', 'success', 'warning', 'danger'], }, title: { control: 'text' }, separator: { control: 'boolean' }, + selected: { + control: 'boolean', + description: 'Выбранный пункт меню, управляемый через selected', + }, extra: { control: 'select', options: Object.keys(Extras), mapping: Extras }, onPress: { action: 'pressed' }, }, + parameters: { controls: { exclude: ['iconColor'] } }, decorators: [ (Story) => ( @@ -66,26 +70,7 @@ export default meta type Story = StoryObj const MenuItemTemplateStory: Story = { - args: { title: 'Menu item template' }, + args: { title: 'MenuItemTemplate' }, argTypes: {}, - parameters: { - notes: ` - #### Элемент меню - полный набор свойств - - console.log("Menu item pressed)} - /> - `, - }, } export { MenuItemTemplateStory as MenuItemTemplate } diff --git a/src/components/MenuItem/Template/MenuItemTemplate.tsx b/src/components/MenuItem/Template/MenuItemTemplate.tsx index c868bbf1..b5d60729 100644 --- a/src/components/MenuItem/Template/MenuItemTemplate.tsx +++ b/src/components/MenuItem/Template/MenuItemTemplate.tsx @@ -1,4 +1,4 @@ -import { memo, useCallback, useMemo, type ReactNode } from 'react' +import { memo, useCallback, useState, type ReactNode } from 'react' import { View, Pressable, @@ -9,7 +9,7 @@ import { type ViewStyle, } from 'react-native' -import { StyleSheet } from 'react-native-unistyles' +import { StyleSheet, useUnistyles } from 'react-native-unistyles' import type { SvgSource } from '../../../utils/SvgUniversal' import type { BadgeSeverity } from '../../Badge/Badge' @@ -24,7 +24,10 @@ export interface MenuItemTemplateProps extends ViewProps { caption?: string /** SVG-иконка слева от заголовка */ Icon?: SvgSource - /** Цвет иконки. Если цвет не задан - применяется такой же цвет что и для аксессуаров (prefix, suffix) */ + /** + * @deprecated Цвет основной иконки определяется состоянием пункта меню, как у аксессуаров. + * Переданное значение игнорируется. + */ iconColor?: ColorValue /** Цвет бейджа (точки) в правом верхнем углу иконки. Бейдж может выводиться только при наличии иконки. */ badgeSeverity?: BadgeSeverity @@ -36,8 +39,17 @@ export interface MenuItemTemplateProps extends ViewProps { * Дополнительный контент пункта меню, выводится справа от текста. Может быть любым react компонентом. Важно! Размеры доплолнительного контента не контролируются пунктом меню и могут его растягивать. Использовать с осторожностью. */ extra?: ReactNode - /** Неактивное состояние. В неактивном состоянии отключается чувствительность к нажатиям, компонент становится полупрозрачным, а аксессуары заменяются иконкой с замком*/ + /** + * Отключает нажатия и визуальное выделение, применяет обычные цвета с непрозрачностью 60%. + * Аксессуары заменяются замками. Значение selected сохраняется в доступном состоянии. + */ disabled?: boolean + /** + * Выбранное состояние пункта, по умолчанию false. + * Управляется потребителем и не меняется автоматически при нажатии. + * Имеет приоритет над accessibilityState.selected и aria-selected. + */ + selected?: boolean /** Разделитель. Выводится как полоска сверху. Изменяет общую высоту элемента меню.*/ separator?: boolean /** Обработчик нажатия */ @@ -51,16 +63,20 @@ export interface MenuItemTemplateProps extends ViewProps { } /** - * Шаблон элемента меню. Содержит максимальное количество компонентов внутри пункта меню и используется как основа для создания пунктов меню любой возможной конфигурации. + * Шаблон пункта меню с иконками, подписью и дополнительным содержимым. + * Цвета текста, основной иконки и аксессуаров задаются темой по текущему состоянию. + * Отслеживает нативный фокус и отображает выбранность из selected. + * Нажатие вызывает onPress; accessibilityState.selected формируется из selected. * - * @link https://www.figma.com/design/4TYeki0MDLhfPGJstbIicf/UI-kit-PrimeFace-(DS)?node-id=937-6724&m=dev + * @see https://www.figma.com/design/HOLKdvQJ8jCLeX17s9d0Yf/UI-Kit--DS--v2.0?node-id=937-6724 */ export const MenuItemTemplate = memo( ({ title, caption, Icon, - iconColor, + // eslint-disable-next-line @typescript-eslint/no-deprecated -- исключаем устаревший проп из нативных props + iconColor: _iconColor, badgeSeverity, PrefixIcon, SuffixIcon, @@ -68,27 +84,53 @@ export const MenuItemTemplate = memo( separator, testID, onPress, + onFocus, + onBlur, disabled, + selected = false, + accessibilityState, style, ...rest }) => { - const iconStyle = useMemo( - () => ({ - width: styles.icon.width, - height: styles.icon.height, - color: iconColor || styles.icon.color, - }), - [iconColor] + const { theme } = useUnistyles() + const [focused, setFocused] = useState(false) + const item = theme.theme.Menu.Item + const handleFocus = useCallback>( + (event) => { + setFocused(true) + onFocus?.(event) + }, + [onFocus] + ) + const handleBlur = useCallback>( + (event) => { + setFocused(false) + onBlur?.(event) + }, + [onBlur] + ) + const getState = useCallback( + (pressed: boolean): MenuItemState => { + if (disabled) return 'default' + + if (selected) { + return pressed || focused ? 'selectedHighlighted' : 'selected' + } + + if (pressed) return 'pressed' + + return focused ? 'focused' : 'default' + }, + [disabled, focused, selected] ) const pressableStyle = useCallback( ({ pressed }: PressableStateCallbackType) => [ - styles.container, - pressed && styles.containerPressed, + styles.container(getState(pressed)), style, disabled && styles.containerDisabled, ], - [disabled, style] + [disabled, getState, style] ) return ( @@ -96,56 +138,95 @@ export const MenuItemTemplate = memo( - - {PrefixIcon ? ( - - ) : null} - - {Icon ? ( - - ) : null} - - {title} - {caption ? ( - {caption} + {({ pressed }) => { + const state = getState(pressed) + const stateIconColor = + item[`${tokensByState[state].color}IconColor`] + const iconStyle = { + width: styles.icon.width, + height: styles.icon.height, + color: stateIconColor, + } + + return ( + + {PrefixIcon ? ( + + ) : null} + + {Icon ? ( + + ) : null} + + + {title} + + {caption ? ( + {caption} + ) : null} + + + {extra} + {SuffixIcon ? ( + ) : null} - - {extra} - {SuffixIcon ? ( - - ) : null} - + ) + }} ) } ) +const tokensByState = { + default: { color: 'menuitem', background: 'menuitemBg' }, + pressed: { color: 'menuitemHover', background: 'menuitemHoverBg' }, + focused: { color: 'menuitemFocus', background: 'menuitemFocusBg' }, + selected: { color: 'menuitemActive', background: 'menuitemActiveBg' }, + selectedHighlighted: { + color: 'menuitemActive', + background: 'menuitemActiveHoverBg', + }, +} as const + +type MenuItemState = keyof typeof tokensByState + const styles = StyleSheet.create(({ theme, spacing, typography, border }) => ({ - container: { + container: (state: MenuItemState) => ({ borderColor: theme.Menu.Item.menuitemBorderColor, borderWidth: border.Width.border, borderRadius: theme.Menu.Item.menuitemBorderRadius, - backgroundColor: theme.Menu.Item.menuitemBg, - }, - containerPressed: { backgroundColor: theme.Menu.Item.menuitemHoverBg }, - containerDisabled: { - borderColor: theme.Button.Disabled.disabledButtonBorderColor, - backgroundColor: theme.Button.Disabled.disabledButtonBg, - opacity: 0.6, - }, + backgroundColor: theme.Menu.Item[tokensByState[state].background], + }), + containerDisabled: { opacity: 0.6 }, separator: { borderTopWidth: 1, borderTopColor: theme.Menu.Overlay.overlayMenuBorderColor, @@ -158,11 +239,10 @@ const styles = StyleSheet.create(({ theme, spacing, typography, border }) => ({ paddingHorizontal: theme.Menu.Item.menuitemPaddingLeftRight, paddingVertical: theme.Menu.Item.menuitemPaddingTopBottom, }, - accessory: { - color: theme.Menu.Item.menuitemIconColor, - width: theme.Menu.Item.menuitemSubmenuIconFontSize, - height: theme.Menu.Item.menuitemSubmenuIconFontSize, - }, + title: (state: MenuItemState) => ({ + color: theme.Menu.Item[`${tokensByState[state].color}TextColor`], + }), + caption: { color: theme.Menu.Common.menuTextColor }, templateContainer: { flexDirection: 'row', gap: spacing.Gap['gap-2'], @@ -171,7 +251,6 @@ const styles = StyleSheet.create(({ theme, spacing, typography, border }) => ({ icon: { width: typography.Size['text-xl'], height: typography.Size['text-xl'], - color: theme.Menu.Item.menuitemIconColor, }, textContainer: { gap: spacing.Gap['gap-1'], flex: 1 }, })) diff --git a/src/components/MenuItem/Template/__tests__/MenuItemTemplate.test.tsx b/src/components/MenuItem/Template/__tests__/MenuItemTemplate.test.tsx index b06260f6..c5aa1ff9 100644 --- a/src/components/MenuItem/Template/__tests__/MenuItemTemplate.test.tsx +++ b/src/components/MenuItem/Template/__tests__/MenuItemTemplate.test.tsx @@ -24,7 +24,7 @@ describe('MenuItemTemplate tests', () => { ], ['with icon', { title: 'Menu Item', Icon: IconUser }], [ - 'with colored icon', + 'не применяет устаревший iconColor', { title: 'Menu Item', Icon: IconUser, iconColor: 'red' }, ], [ @@ -68,20 +68,38 @@ describe('MenuItemTemplate tests', () => { /** * Behavioral tests */ - test('MenuItemTemplate press', () => { - let pressCount = 0 - const minimal = render( + test('вызывает onPress при нажатии', () => { + const onPress = jest.fn() + const { getByRole } = render( + + ) + + fireEvent.press(getByRole('button', { name: 'Menu item' })) + + expect(onPress).toHaveBeenCalledOnce() + }) + + test('отражает selected в доступном состоянии', () => { + const { getByRole, rerender } = render( { - pressCount += 1 - }} /> ) - const button = minimal.getByTestId('menuItemButton') - fireEvent.press(button) + expect(getByRole('button', { selected: false })).toBeOnTheScreen() + + rerender( + + ) - expect(pressCount).toBe(1) + expect(getByRole('button', { selected: true })).toBeOnTheScreen() }) }) diff --git a/src/components/MenuItem/Template/__tests__/__snapshots__/MenuItemTemplate.test.tsx.snap b/src/components/MenuItem/Template/__tests__/__snapshots__/MenuItemTemplate.test.tsx.snap index ba37c542..3590ab91 100644 --- a/src/components/MenuItem/Template/__tests__/__snapshots__/MenuItemTemplate.test.tsx.snap +++ b/src/components/MenuItem/Template/__tests__/__snapshots__/MenuItemTemplate.test.tsx.snap @@ -19,7 +19,7 @@ exports[`MenuItemTemplate tests MenuItemTemplate full disabled 1`] = ` "checked": undefined, "disabled": true, "expanded": undefined, - "selected": undefined, + "selected": false, } } accessibilityValue={ @@ -45,16 +45,13 @@ exports[`MenuItemTemplate tests MenuItemTemplate full disabled 1`] = ` style={ [ { - "backgroundColor": "rgba(255, 255, 255, 0.0001)", - "borderColor": "rgba(255, 255, 255, 0.0001)", + "backgroundColor": "#ffffff00", + "borderColor": "#ffffff00", "borderRadius": 7, "borderWidth": 1, }, - false, undefined, { - "backgroundColor": "#e2e2e4", - "borderColor": "#a2a5a9", "opacity": 0.6, }, ] @@ -102,7 +99,7 @@ exports[`MenuItemTemplate tests MenuItemTemplate full disabled 1`] = ` meetOrSlice={0} minX={0} minY={0} - stroke="#181a1f" + stroke="#2b2e33" strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} @@ -138,7 +135,7 @@ exports[`MenuItemTemplate tests MenuItemTemplate full disabled 1`] = ` } stroke={ { - "payload": 4279769631, + "payload": 4281019955, "type": 0, } } @@ -160,7 +157,7 @@ exports[`MenuItemTemplate tests MenuItemTemplate full disabled 1`] = ` } stroke={ { - "payload": 4279769631, + "payload": 4281019955, "type": 0, } } @@ -183,7 +180,7 @@ exports[`MenuItemTemplate tests MenuItemTemplate full disabled 1`] = ` } stroke={ { - "payload": 4279769631, + "payload": 4281019955, "type": 0, } } @@ -260,7 +257,9 @@ exports[`MenuItemTemplate tests MenuItemTemplate full disabled 1`] = ` undefined, undefined, undefined, - undefined, + { + "color": "#2b2e33", + }, ] } testID="Body" @@ -279,11 +278,13 @@ exports[`MenuItemTemplate tests MenuItemTemplate full disabled 1`] = ` "verticalAlign": "middle", }, { - "color": "#85888e", + "color": "#181a1f", }, undefined, undefined, - undefined, + { + "color": "#85888e", + }, ] } testID="CaptionText" @@ -405,7 +406,7 @@ exports[`MenuItemTemplate tests MenuItemTemplate full disabled 1`] = ` meetOrSlice={0} minX={0} minY={0} - stroke="#181a1f" + stroke="#2b2e33" strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} @@ -441,7 +442,7 @@ exports[`MenuItemTemplate tests MenuItemTemplate full disabled 1`] = ` } stroke={ { - "payload": 4279769631, + "payload": 4281019955, "type": 0, } } @@ -463,7 +464,7 @@ exports[`MenuItemTemplate tests MenuItemTemplate full disabled 1`] = ` } stroke={ { - "payload": 4279769631, + "payload": 4281019955, "type": 0, } } @@ -486,7 +487,7 @@ exports[`MenuItemTemplate tests MenuItemTemplate full disabled 1`] = ` } stroke={ { - "payload": 4279769631, + "payload": 4281019955, "type": 0, } } @@ -509,7 +510,7 @@ exports[`MenuItemTemplate tests MenuItemTemplate full disabled 1`] = ` } stroke={ { - "payload": 4279769631, + "payload": 4281019955, "type": 0, } } @@ -537,9 +538,9 @@ exports[`MenuItemTemplate tests MenuItemTemplate minimal config 1`] = ` { "busy": undefined, "checked": undefined, - "disabled": undefined, + "disabled": false, "expanded": undefined, - "selected": undefined, + "selected": false, } } accessibilityValue={ @@ -565,12 +566,11 @@ exports[`MenuItemTemplate tests MenuItemTemplate minimal config 1`] = ` style={ [ { - "backgroundColor": "rgba(255, 255, 255, 0.0001)", - "borderColor": "rgba(255, 255, 255, 0.0001)", + "backgroundColor": "#ffffff00", + "borderColor": "#ffffff00", "borderRadius": 7, "borderWidth": 1, }, - false, undefined, undefined, ] @@ -626,7 +626,9 @@ exports[`MenuItemTemplate tests MenuItemTemplate minimal config 1`] = ` undefined, undefined, undefined, - undefined, + { + "color": "#2b2e33", + }, ] } testID="Body" @@ -651,9 +653,9 @@ exports[`MenuItemTemplate tests MenuItemTemplate prefix,suffix = right 1`] = ` { "busy": undefined, "checked": undefined, - "disabled": undefined, + "disabled": false, "expanded": undefined, - "selected": undefined, + "selected": false, } } accessibilityValue={ @@ -679,12 +681,11 @@ exports[`MenuItemTemplate tests MenuItemTemplate prefix,suffix = right 1`] = ` style={ [ { - "backgroundColor": "rgba(255, 255, 255, 0.0001)", - "borderColor": "rgba(255, 255, 255, 0.0001)", + "backgroundColor": "#ffffff00", + "borderColor": "#ffffff00", "borderRadius": 7, "borderWidth": 1, }, - false, undefined, undefined, ] @@ -719,7 +720,7 @@ exports[`MenuItemTemplate tests MenuItemTemplate prefix,suffix = right 1`] = ` meetOrSlice={0} minX={0} minY={0} - stroke="#181a1f" + stroke="#2b2e33" strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} @@ -755,7 +756,7 @@ exports[`MenuItemTemplate tests MenuItemTemplate prefix,suffix = right 1`] = ` } stroke={ { - "payload": 4279769631, + "payload": 4281019955, "type": 0, } } @@ -777,7 +778,7 @@ exports[`MenuItemTemplate tests MenuItemTemplate prefix,suffix = right 1`] = ` } stroke={ { - "payload": 4279769631, + "payload": 4281019955, "type": 0, } } @@ -827,7 +828,9 @@ exports[`MenuItemTemplate tests MenuItemTemplate prefix,suffix = right 1`] = ` undefined, undefined, undefined, - undefined, + { + "color": "#2b2e33", + }, ] } testID="Body" @@ -846,11 +849,13 @@ exports[`MenuItemTemplate tests MenuItemTemplate prefix,suffix = right 1`] = ` "verticalAlign": "middle", }, { - "color": "#85888e", + "color": "#181a1f", }, undefined, undefined, - undefined, + { + "color": "#85888e", + }, ] } testID="CaptionText" @@ -876,7 +881,7 @@ exports[`MenuItemTemplate tests MenuItemTemplate prefix,suffix = right 1`] = ` meetOrSlice={0} minX={0} minY={0} - stroke="#181a1f" + stroke="#2b2e33" strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} @@ -912,7 +917,7 @@ exports[`MenuItemTemplate tests MenuItemTemplate prefix,suffix = right 1`] = ` } stroke={ { - "payload": 4279769631, + "payload": 4281019955, "type": 0, } } @@ -934,7 +939,7 @@ exports[`MenuItemTemplate tests MenuItemTemplate prefix,suffix = right 1`] = ` } stroke={ { - "payload": 4279769631, + "payload": 4281019955, "type": 0, } } @@ -951,7 +956,7 @@ exports[`MenuItemTemplate tests MenuItemTemplate prefix,suffix = right 1`] = ` `; -exports[`MenuItemTemplate tests MenuItemTemplate with colored icon 1`] = ` +exports[`MenuItemTemplate tests MenuItemTemplate with extra 1`] = ` @@ -962,9 +967,9 @@ exports[`MenuItemTemplate tests MenuItemTemplate with colored icon 1`] = ` { "busy": undefined, "checked": undefined, - "disabled": undefined, + "disabled": false, "expanded": undefined, - "selected": undefined, + "selected": false, } } accessibilityValue={ @@ -990,12 +995,11 @@ exports[`MenuItemTemplate tests MenuItemTemplate with colored icon 1`] = ` style={ [ { - "backgroundColor": "rgba(255, 255, 255, 0.0001)", - "borderColor": "rgba(255, 255, 255, 0.0001)", + "backgroundColor": "#ffffff00", + "borderColor": "#ffffff00", "borderRadius": 7, "borderWidth": 1, }, - false, undefined, undefined, ] @@ -1022,121 +1026,6 @@ exports[`MenuItemTemplate tests MenuItemTemplate with colored icon 1`] = ` } } > - - - - - - - - - - - Menu Item - - - - - - -`; - -exports[`MenuItemTemplate tests MenuItemTemplate with extra 1`] = ` - - - - - - + Menu Item + + + + + + +`; + +exports[`MenuItemTemplate tests MenuItemTemplate не применяет устаревший iconColor 1`] = ` + + + + + + + + + + + + + + + +