@cloud-ru/ds-tabs 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (106) hide show
  1. package/CHANGELOG.md +8 -0
  2. package/LICENSE +201 -0
  3. package/README.md +300 -0
  4. package/dist/cjs/components/ScrollButton/ScrollButton.d.ts +8 -0
  5. package/dist/cjs/components/ScrollButton/ScrollButton.js +19 -0
  6. package/dist/cjs/components/ScrollButton/index.d.ts +1 -0
  7. package/dist/cjs/components/ScrollButton/index.js +17 -0
  8. package/dist/cjs/components/ScrollButton/styles.module.css +50 -0
  9. package/dist/cjs/components/Tab/Tab.d.ts +25 -0
  10. package/dist/cjs/components/Tab/Tab.js +78 -0
  11. package/dist/cjs/components/Tab/index.d.ts +1 -0
  12. package/dist/cjs/components/Tab/index.js +17 -0
  13. package/dist/cjs/components/Tab/styles.module.css +105 -0
  14. package/dist/cjs/components/TabBar/TabBar.d.ts +30 -0
  15. package/dist/cjs/components/TabBar/TabBar.js +119 -0
  16. package/dist/cjs/components/TabBar/hooks.d.ts +18 -0
  17. package/dist/cjs/components/TabBar/hooks.js +103 -0
  18. package/dist/cjs/components/TabBar/index.d.ts +1 -0
  19. package/dist/cjs/components/TabBar/index.js +17 -0
  20. package/dist/cjs/components/TabBar/styles.module.css +187 -0
  21. package/dist/cjs/components/TabContent/TabContent.d.ts +8 -0
  22. package/dist/cjs/components/TabContent/TabContent.js +14 -0
  23. package/dist/cjs/components/TabContent/index.d.ts +1 -0
  24. package/dist/cjs/components/TabContent/index.js +17 -0
  25. package/dist/cjs/components/Tabs/Tabs.d.ts +21 -0
  26. package/dist/cjs/components/Tabs/Tabs.js +39 -0
  27. package/dist/cjs/components/Tabs/index.d.ts +1 -0
  28. package/dist/cjs/components/Tabs/index.js +17 -0
  29. package/dist/cjs/components/Tabs/styles.module.css +21 -0
  30. package/dist/cjs/components/index.d.ts +5 -0
  31. package/dist/cjs/components/index.js +21 -0
  32. package/dist/cjs/constants.d.ts +32 -0
  33. package/dist/cjs/constants.js +35 -0
  34. package/dist/cjs/context.d.ts +17 -0
  35. package/dist/cjs/context.js +12 -0
  36. package/dist/cjs/index.d.ts +5 -0
  37. package/dist/cjs/index.js +21 -0
  38. package/dist/cjs/package.json +3 -0
  39. package/dist/cjs/style.css +363 -0
  40. package/dist/cjs/types.d.ts +17 -0
  41. package/dist/cjs/types.js +2 -0
  42. package/dist/cjs/utils.d.ts +1 -0
  43. package/dist/cjs/utils.js +6 -0
  44. package/dist/esm/components/ScrollButton/ScrollButton.d.ts +8 -0
  45. package/dist/esm/components/ScrollButton/ScrollButton.js +13 -0
  46. package/dist/esm/components/ScrollButton/index.d.ts +1 -0
  47. package/dist/esm/components/ScrollButton/index.js +1 -0
  48. package/dist/esm/components/ScrollButton/styles.module.css +50 -0
  49. package/dist/esm/components/Tab/Tab.d.ts +25 -0
  50. package/dist/esm/components/Tab/Tab.js +72 -0
  51. package/dist/esm/components/Tab/index.d.ts +1 -0
  52. package/dist/esm/components/Tab/index.js +1 -0
  53. package/dist/esm/components/Tab/styles.module.css +105 -0
  54. package/dist/esm/components/TabBar/TabBar.d.ts +30 -0
  55. package/dist/esm/components/TabBar/TabBar.js +113 -0
  56. package/dist/esm/components/TabBar/hooks.d.ts +18 -0
  57. package/dist/esm/components/TabBar/hooks.js +99 -0
  58. package/dist/esm/components/TabBar/index.d.ts +1 -0
  59. package/dist/esm/components/TabBar/index.js +1 -0
  60. package/dist/esm/components/TabBar/styles.module.css +187 -0
  61. package/dist/esm/components/TabContent/TabContent.d.ts +8 -0
  62. package/dist/esm/components/TabContent/TabContent.js +11 -0
  63. package/dist/esm/components/TabContent/index.d.ts +1 -0
  64. package/dist/esm/components/TabContent/index.js +1 -0
  65. package/dist/esm/components/Tabs/Tabs.d.ts +21 -0
  66. package/dist/esm/components/Tabs/Tabs.js +33 -0
  67. package/dist/esm/components/Tabs/index.d.ts +1 -0
  68. package/dist/esm/components/Tabs/index.js +1 -0
  69. package/dist/esm/components/Tabs/styles.module.css +21 -0
  70. package/dist/esm/components/index.d.ts +5 -0
  71. package/dist/esm/components/index.js +5 -0
  72. package/dist/esm/constants.d.ts +32 -0
  73. package/dist/esm/constants.js +32 -0
  74. package/dist/esm/context.d.ts +17 -0
  75. package/dist/esm/context.js +7 -0
  76. package/dist/esm/index.d.ts +5 -0
  77. package/dist/esm/index.js +5 -0
  78. package/dist/esm/style.css +363 -0
  79. package/dist/esm/types.d.ts +17 -0
  80. package/dist/esm/types.js +1 -0
  81. package/dist/esm/utils.d.ts +1 -0
  82. package/dist/esm/utils.js +3 -0
  83. package/dist/tsconfig.cjs.tsbuildinfo +1 -0
  84. package/dist/tsconfig.esm.tsbuildinfo +1 -0
  85. package/package.json +48 -0
  86. package/src/components/ScrollButton/ScrollButton.tsx +42 -0
  87. package/src/components/ScrollButton/index.ts +1 -0
  88. package/src/components/ScrollButton/styles.module.scss +46 -0
  89. package/src/components/Tab/Tab.tsx +151 -0
  90. package/src/components/Tab/index.ts +1 -0
  91. package/src/components/Tab/styles.module.scss +135 -0
  92. package/src/components/TabBar/TabBar.tsx +269 -0
  93. package/src/components/TabBar/hooks.ts +139 -0
  94. package/src/components/TabBar/index.ts +1 -0
  95. package/src/components/TabBar/styles.module.scss +241 -0
  96. package/src/components/TabContent/TabContent.tsx +34 -0
  97. package/src/components/TabContent/index.ts +1 -0
  98. package/src/components/Tabs/Tabs.tsx +61 -0
  99. package/src/components/Tabs/index.ts +1 -0
  100. package/src/components/Tabs/styles.module.scss +25 -0
  101. package/src/components/index.ts +5 -0
  102. package/src/constants.ts +35 -0
  103. package/src/context.tsx +13 -0
  104. package/src/index.ts +5 -0
  105. package/src/types.ts +21 -0
  106. package/src/utils.ts +3 -0
package/package.json ADDED
@@ -0,0 +1,48 @@
1
+ {
2
+ "name": "@cloud-ru/ds-tabs",
3
+ "version": "1.0.0",
4
+ "description": "Пакет табов — compound-компонент Tabs c субкомпонентами TabBar, Tab и TabContent для горизонтальной и вертикальной навигации.",
5
+ "repository": {
6
+ "type": "git",
7
+ "url": "git+https://github.com/cloud-ru-tech/snack-v2.git",
8
+ "directory": "packages/tabs"
9
+ },
10
+ "homepage": "https://github.com/cloud-ru-tech/snack-v2/tree/master/packages/tabs",
11
+ "license": "Apache-2.0",
12
+ "author": "Nikita Ershov <niershov@cloud.ru>",
13
+ "type": "module",
14
+ "main": "./dist/cjs/index.js",
15
+ "module": "./dist/esm/index.js",
16
+ "types": "./dist/esm/index.d.ts",
17
+ "exports": {
18
+ ".": {
19
+ "source": "./src/index.ts",
20
+ "types": "./dist/esm/index.d.ts",
21
+ "import": "./dist/esm/index.js",
22
+ "require": "./dist/cjs/index.js"
23
+ }
24
+ },
25
+ "files": [
26
+ "dist",
27
+ "src",
28
+ "./CHANGELOG.md",
29
+ "./LICENSE"
30
+ ],
31
+ "sideEffects": [
32
+ "*.css",
33
+ "**/*.css"
34
+ ],
35
+ "dependencies": {
36
+ "classnames": "^2.5.1",
37
+ "react-indiana-drag-scroll": "^2.2.1",
38
+ "@cloud-ru/ds-button": "^1.0.0",
39
+ "@cloud-ru/ds-counter": "^1.0.0",
40
+ "@cloud-ru/ds-divider": "^1.0.0",
41
+ "@cloud-ru/ds-icons": "^1.0.0",
42
+ "@cloud-ru/ds-typography": "^1.0.0",
43
+ "@cloud-ru/ds-utils": "^1.0.0"
44
+ },
45
+ "publishConfig": {
46
+ "access": "public"
47
+ }
48
+ }
@@ -0,0 +1,42 @@
1
+ import { Button } from '@cloud-ru/ds-button';
2
+ import { ChevronDownSVG, ChevronLeftSVG, ChevronRightSVG, ChevronUpSVG } from '@cloud-ru/ds-icons/interface/system';
3
+ import { ReactElement } from 'react';
4
+
5
+ import { Direction, Orientation, Size } from '../../types';
6
+ import styles from './styles.module.scss';
7
+
8
+ const MAP_DIRECTION_TO_ICON: Record<Direction, ReactElement> = {
9
+ left: <ChevronLeftSVG />,
10
+ right: <ChevronRightSVG />,
11
+ top: <ChevronUpSVG />,
12
+ bottom: <ChevronDownSVG />,
13
+ };
14
+
15
+ export type ScrollButtonProps = {
16
+ size: Size;
17
+ direction: Direction;
18
+ orientation: Orientation;
19
+ onClick(): void;
20
+ };
21
+
22
+ export function ScrollButton({ size, onClick, direction, orientation }: ScrollButtonProps) {
23
+ return (
24
+ <div
25
+ className={styles.scrollButton}
26
+ data-direction={direction}
27
+ data-size={size}
28
+ data-orientation={orientation}
29
+ data-testid={`tabs__scroll-button-${direction}`}
30
+ >
31
+ <Button
32
+ tabIndex={-1}
33
+ icon={MAP_DIRECTION_TO_ICON[direction]}
34
+ size='s'
35
+ view='elevated'
36
+ appearance='neutral'
37
+ onClick={onClick}
38
+ aria-label={`Scroll ${direction}`}
39
+ />
40
+ </div>
41
+ );
42
+ }
@@ -0,0 +1 @@
1
+ export * from './ScrollButton';
@@ -0,0 +1,46 @@
1
+ @use '@cloud-ru/ds-figma-variables/build/scss/styles/styles.module' as base;
2
+ @use '@cloud-ru/ds-figma-variables/build/scss/components/tabs.module' as tabs;
3
+
4
+ .scrollButton {
5
+ position: absolute;
6
+ display: flex;
7
+ align-items: center;
8
+ justify-content: center;
9
+
10
+ // Паддинг только с той стороны, которой кнопка смотрит наружу, — как в макете.
11
+ @each $size in ('m', 'l') {
12
+ $padding: base.simple-var(tabs.$tabs, 'anatomy', 'size', $size, 'control', 'forward', 'padding');
13
+
14
+ &[data-size='#{$size}'] {
15
+ @each $direction, $side in ('left': 'left', 'right': 'right', 'top': 'top', 'bottom': 'bottom') {
16
+ &[data-direction='#{$direction}'] {
17
+ padding-#{$side}: $padding;
18
+ }
19
+ }
20
+ }
21
+ }
22
+
23
+ &[data-direction='left'] {
24
+ top: 0;
25
+ bottom: 0;
26
+ left: 0;
27
+ }
28
+
29
+ &[data-direction='right'] {
30
+ top: 0;
31
+ right: 0;
32
+ bottom: 0;
33
+ }
34
+
35
+ &[data-direction='top'] {
36
+ top: 0;
37
+ right: 0;
38
+ left: 0;
39
+ }
40
+
41
+ &[data-direction='bottom'] {
42
+ right: 0;
43
+ bottom: 0;
44
+ left: 0;
45
+ }
46
+ }
@@ -0,0 +1,151 @@
1
+ import { Counter, CounterProps } from '@cloud-ru/ds-counter';
2
+ import { Typography, TypographyProps } from '@cloud-ru/ds-typography';
3
+ import { extractSupportProps, WithSupportProps } from '@cloud-ru/ds-utils';
4
+ import cn from 'classnames';
5
+ import { FocusEvent, KeyboardEvent, MouseEvent, useCallback, useEffect, useRef } from 'react';
6
+
7
+ import { SIZE } from '../../constants';
8
+ import { useTabBarContext, useTabsContext } from '../../context';
9
+ import { Size } from '../../types';
10
+ import { getTabContentId } from '../../utils';
11
+ import styles from './styles.module.scss';
12
+
13
+ export type TabProps = WithSupportProps<{
14
+ /** Value вкладки */
15
+ value: string;
16
+ /** Заголовок вкладки */
17
+ label: string;
18
+ /** Деактивирована ли вкладка */
19
+ disabled?: boolean;
20
+ /** CSS-класс */
21
+ className?: string;
22
+ /** Счетчик, отображающийся внутри кнопки переключения */
23
+ counter?: {
24
+ /** Значение счетчика */
25
+ label: number;
26
+ /** Внешний вид */
27
+ appearance?: CounterProps['appearance'];
28
+ /** Роль, в которой применяется `appearance` счётчика */
29
+ roleAppearance?: CounterProps['roleAppearance'];
30
+ };
31
+ /** Колбек клика по кнопке переключения */
32
+ onClick?(event: MouseEvent<HTMLButtonElement>): void;
33
+ }>;
34
+
35
+ const MAP_SIZE_TO_PROPS: Record<
36
+ Size,
37
+ { typographyProps: Pick<TypographyProps, 'variant' | 'size'>; counterProps: Pick<CounterProps, 'size'> }
38
+ > = {
39
+ [SIZE.L]: {
40
+ typographyProps: {
41
+ variant: 'title',
42
+ size: 'm',
43
+ },
44
+ counterProps: {
45
+ size: 's',
46
+ },
47
+ },
48
+ [SIZE.M]: {
49
+ typographyProps: {
50
+ variant: 'title',
51
+ size: 's',
52
+ },
53
+ counterProps: {
54
+ size: 'xs',
55
+ },
56
+ },
57
+ };
58
+
59
+ export function Tab({ label, value, disabled = false, className, onClick, counter, ...otherProps }: TabProps) {
60
+ const ref = useRef<HTMLButtonElement>(null);
61
+ const { onSelect, size, orientation, focusedTab, onFocus } = useTabBarContext();
62
+ const { selectedTab, setSelectedTab } = useTabsContext();
63
+ const selected = value === selectedTab;
64
+
65
+ useEffect(() => {
66
+ const { current } = ref;
67
+
68
+ if (selected && current) {
69
+ onSelect?.(current);
70
+ }
71
+ }, [selected, onSelect]);
72
+
73
+ useEffect(() => {
74
+ const { current } = ref;
75
+ if (focusedTab === value && current) {
76
+ current.focus();
77
+ }
78
+ }, [value, focusedTab]);
79
+
80
+ const handleClick = useCallback(
81
+ (e: MouseEvent<HTMLButtonElement>) => {
82
+ if (disabled) {
83
+ e.preventDefault();
84
+ return;
85
+ }
86
+ setSelectedTab(value);
87
+ onClick?.(e);
88
+ },
89
+ [disabled, value, onClick, setSelectedTab],
90
+ );
91
+
92
+ const clickByEnterOrSpaceKey = useCallback(
93
+ (e: KeyboardEvent<HTMLButtonElement>) => {
94
+ if (e.key === 'Enter' || e.key === ' ') {
95
+ e.preventDefault();
96
+ if (disabled) return;
97
+ ref.current?.click();
98
+ }
99
+ },
100
+ [disabled],
101
+ );
102
+
103
+ const onFocusHandler = useCallback(
104
+ (e: FocusEvent<HTMLButtonElement>) => {
105
+ onFocus?.(e.target, value);
106
+ },
107
+ [onFocus, value],
108
+ );
109
+
110
+ if (!size) {
111
+ return null;
112
+ }
113
+
114
+ const { typographyProps, counterProps } = MAP_SIZE_TO_PROPS[size];
115
+
116
+ return (
117
+ <button
118
+ type='button'
119
+ role='tab'
120
+ data-testid={`tabs__tab-${value}`}
121
+ {...extractSupportProps(otherProps)}
122
+ id={value}
123
+ ref={ref}
124
+ aria-disabled={disabled}
125
+ data-disabled={disabled || undefined}
126
+ className={cn(styles.tab, className)}
127
+ aria-controls={getTabContentId(value)}
128
+ aria-selected={selected}
129
+ data-selected={selected || undefined}
130
+ data-size={size}
131
+ data-orientation={orientation}
132
+ onClick={handleClick}
133
+ onFocus={onFocusHandler}
134
+ onKeyDown={clickByEnterOrSpaceKey}
135
+ >
136
+ <Typography className={styles.container} as='div' {...typographyProps}>
137
+ {label}
138
+ {counter && (
139
+ <Counter
140
+ appearance={counter.appearance}
141
+ roleAppearance={counter.roleAppearance}
142
+ value={counter.label}
143
+ data-testid={`tabs__tab-counter-${value}`}
144
+ {...counterProps}
145
+ />
146
+ )}
147
+ <span data-state-layer aria-hidden data-state='emptyNeutralOnBackground' />
148
+ </Typography>
149
+ </button>
150
+ );
151
+ }
@@ -0,0 +1 @@
1
+ export * from './Tab';
@@ -0,0 +1,135 @@
1
+ @use '@cloud-ru/ds-figma-variables/build/scss/styles/styles.module' as base;
2
+ @use '@cloud-ru/ds-figma-variables/build/scss/components/tabs.module' as tabs;
3
+
4
+ $sizes: 'm', 'l';
5
+
6
+ // TODO: тут подключаем state-layer (но триггер должен быть на .tab)
7
+ @mixin internal-has-state-layer-as-child() {
8
+ & .container > [data-state-layer] {
9
+ position: absolute;
10
+ inset: 0;
11
+ border-radius: inherit;
12
+
13
+ &[data-state='emptyNeutralOnBackground'] {
14
+ background: base.$sn-theme-color-material-stateLayer-neutral-onBackground-defaultEmpty-filled;
15
+ }
16
+ }
17
+
18
+ @media (hover: hover) {
19
+ &:hover:not([data-disabled], [data-loading]) {
20
+ & .container > [data-state-layer] {
21
+ &[data-state='emptyNeutralOnBackground'] {
22
+ background: base.$sn-theme-color-material-stateLayer-neutral-onBackground-hovered-filled;
23
+ }
24
+ }
25
+ }
26
+ }
27
+
28
+ /* stylelint-disable-next-line order/order */
29
+ &[data-loading],
30
+ &:active:not([data-disabled], [data-loading]) {
31
+ & .container > [data-state-layer] {
32
+ &[data-state='emptyNeutralOnBackground'] {
33
+ background: base.$sn-theme-color-material-stateLayer-neutral-onBackground-pressed-filled;
34
+ }
35
+ }
36
+ }
37
+ }
38
+
39
+ .tab {
40
+ cursor: pointer;
41
+
42
+ position: relative;
43
+
44
+ display: inline-flex;
45
+ flex-direction: row;
46
+ align-items: center;
47
+
48
+ box-sizing: border-box;
49
+ padding: 0;
50
+ border-width: 0;
51
+
52
+ color: base.$sn-theme-color-available-version-textSecondary;
53
+
54
+ background-color: transparent;
55
+ outline: none;
56
+
57
+ @each $size in $sizes {
58
+ &[data-orientation='horizontal'][data-size='#{$size}'] {
59
+ @include base.composite-var(tabs.$tabs, 'anatomy', 'size', $size, 'tabsHorizontal', 'tabContainer');
60
+
61
+ .container {
62
+ @include base.composite-var(
63
+ tabs.$tabs,
64
+ 'anatomy',
65
+ 'size',
66
+ $size,
67
+ 'tabsHorizontal',
68
+ 'tabContainer',
69
+ 'textWrapper'
70
+ );
71
+ }
72
+ }
73
+
74
+ &[data-orientation='vertical'][data-size='#{$size}'] {
75
+ @include base.composite-var(tabs.$tabs, 'anatomy', 'size', $size, 'tabsVertical', 'tabContainer');
76
+
77
+ .container {
78
+ @include base.composite-var(
79
+ tabs.$tabs,
80
+ 'anatomy',
81
+ 'size',
82
+ $size,
83
+ 'tabsVertical',
84
+ 'tabContainer',
85
+ 'textWrapper'
86
+ );
87
+ }
88
+ }
89
+ }
90
+
91
+ // Приватный мастер и выгрузка дают для `l` значение 8, а композиция `tabsVerticalL`
92
+ // и живой рендер — 16; код следует композиции. Что считать эталоном, решает дизайн.
93
+ // TODO FF-8772: снять, когда мастер и композиция сойдутся.
94
+ &[data-orientation='vertical'][data-size='l'] {
95
+ padding-right: base.simple-var(
96
+ tabs.$tabs,
97
+ 'anatomy',
98
+ 'size',
99
+ 'm',
100
+ 'tabsVertical',
101
+ 'tabContainer',
102
+ 'padding-right'
103
+ );
104
+ padding-left: base.simple-var(tabs.$tabs, 'anatomy', 'size', 'm', 'tabsVertical', 'tabContainer', 'padding-left');
105
+ }
106
+
107
+ &[data-selected='true'],
108
+ &:focus-visible,
109
+ &:hover {
110
+ color: base.$sn-theme-color-available-version-textMain;
111
+ }
112
+
113
+ // В макете отключённый таб гасится целиком, а не только цветом текста: иначе счётчик остаётся ярким.
114
+ &[data-disabled] {
115
+ cursor: not-allowed;
116
+ opacity: base.$sn-theme-effect-opacity-disabled;
117
+ }
118
+
119
+ @include internal-has-state-layer-as-child();
120
+
121
+ .container {
122
+ position: relative;
123
+
124
+ display: flex;
125
+ align-items: center;
126
+ justify-content: center;
127
+
128
+ box-sizing: border-box;
129
+ }
130
+
131
+ &:focus-visible .container {
132
+ outline: base.$sn-primitive-strokeWeight-strokeSemiBold solid base.$sn-theme-color-available-complementary;
133
+ outline-offset: calc(0px - #{base.$sn-primitive-strokeWeight-strokeSemiBold});
134
+ }
135
+ }
@@ -0,0 +1,269 @@
1
+ import { Divider } from '@cloud-ru/ds-divider';
2
+ import { extractSupportProps, WithSupportProps } from '@cloud-ru/ds-utils';
3
+ import cn from 'classnames';
4
+ import {
5
+ Children,
6
+ KeyboardEvent,
7
+ ReactElement,
8
+ ReactNode,
9
+ RefObject,
10
+ useCallback,
11
+ useEffect,
12
+ useRef,
13
+ useState,
14
+ } from 'react';
15
+ import ScrollContainer from 'react-indiana-drag-scroll';
16
+
17
+ import { MARKER_POSITION, ORIENTATION, SIZE } from '../../constants';
18
+ import { TabBarContext, useTabsContext } from '../../context';
19
+ import { MarkerPosition, Orientation, Size } from '../../types';
20
+ import { ScrollButton } from '../ScrollButton';
21
+ import { TabProps } from '../Tab';
22
+ import { useFocusControl, useScrollContainer } from './hooks';
23
+ import styles from './styles.module.scss';
24
+
25
+ const SCROLL_CONTAINER_ORIENTATION_MAP: Record<Orientation, string> = {
26
+ [ORIENTATION.Horizontal]: styles.horizontalScrollContainer,
27
+ [ORIENTATION.Vertical]: styles.verticalScrollContainer,
28
+ };
29
+
30
+ export type TabBarProps = WithSupportProps<{
31
+ /** Контент (элементы Tabs.Tab) */
32
+ children: ReactElement<TabProps>[];
33
+ /**
34
+ * Слот действия: контент после списка табов — справа при горизонтальной
35
+ * ориентации, снизу при вертикальной. Разделитель под ним не продолжается.
36
+ */
37
+ slotActionButton?: ReactNode;
38
+ /** Ориентация */
39
+ orientation?: Orientation;
40
+ /**
41
+ * Позиция маркера относительно таб-бара.
42
+ *
43
+ * Значения ориентационно-нейтральны, в Figma та же ось названа сторонами:
44
+ * `before` = Figma `top` (horizontal) / `left` (vertical),
45
+ * `after` = Figma `bottom` (horizontal) / `right` (vertical).
46
+ */
47
+ markerPosition?: MarkerPosition;
48
+ /** Размер панели табов: L — верхнеуровневый, M — на уровне контента */
49
+ size?: Size;
50
+ /** Скрыть разделитель под/рядом с панелью табов */
51
+ disableDivider?: boolean;
52
+ /** CSS-класс */
53
+ className?: string;
54
+ }>;
55
+
56
+ type MarkerScrollPosition = {
57
+ left?: number;
58
+ width?: number;
59
+ height?: number;
60
+ top?: number;
61
+ };
62
+
63
+ export function TabBar({
64
+ children,
65
+ className,
66
+ size = SIZE.L,
67
+ orientation = ORIENTATION.Horizontal,
68
+ markerPosition = MARKER_POSITION.After,
69
+ slotActionButton,
70
+ disableDivider = false,
71
+ ...otherProps
72
+ }: TabBarProps) {
73
+ const scrollContainerRef = useRef<HTMLDivElement>(null);
74
+ const { selectedTab, setSelectedTab } = useTabsContext();
75
+ const { hasOverflow, scrollLeft, scrollRight, scrollTop, scrollBottom } = useScrollContainer(scrollContainerRef);
76
+ const selectedRef = useRef<HTMLButtonElement | null>(null);
77
+ const [markerScrollPosition, setMarkerScrollPosition] = useState<MarkerScrollPosition>({});
78
+ const [focusedTab, setFocusedTab] = useState<string | undefined>();
79
+
80
+ useEffect(() => {
81
+ if (!selectedTab) {
82
+ const firstEnabled = Children.map(children, child => child.props).find(
83
+ (props: { value: string; disabled?: boolean }) => !props.disabled,
84
+ );
85
+ if (firstEnabled) {
86
+ setSelectedTab(firstEnabled.value);
87
+ }
88
+ }
89
+ }, [children, selectedTab, setSelectedTab]);
90
+
91
+ const updateMarkPosition = useCallback(
92
+ (element: HTMLButtonElement) => {
93
+ if (orientation === 'horizontal') {
94
+ setMarkerScrollPosition({
95
+ left: element.offsetLeft,
96
+ width: element.offsetWidth,
97
+ });
98
+ } else {
99
+ setMarkerScrollPosition({
100
+ top: element.offsetTop,
101
+ height: element.offsetHeight,
102
+ });
103
+ }
104
+ selectedRef.current = element;
105
+ },
106
+ [orientation],
107
+ );
108
+
109
+ useEffect(() => {
110
+ if (!selectedRef.current) {
111
+ return;
112
+ }
113
+
114
+ const updatePosition = () => {
115
+ if (selectedRef.current) {
116
+ updateMarkPosition(selectedRef.current);
117
+ }
118
+ };
119
+ updatePosition();
120
+
121
+ const resizeObserver = new ResizeObserver(updatePosition);
122
+ resizeObserver.observe(selectedRef.current);
123
+
124
+ return () => {
125
+ resizeObserver.disconnect();
126
+ };
127
+ }, [children, size, updateMarkPosition]);
128
+
129
+ const scrollContainerToElement = useCallback(
130
+ (element: HTMLElement) => {
131
+ const container = scrollContainerRef.current;
132
+
133
+ if (element && container) {
134
+ if (orientation === 'vertical') {
135
+ const overflowTop = element.offsetTop < container.scrollTop;
136
+ const overflowBottom =
137
+ element.offsetTop + element.offsetHeight > container.scrollTop + container.offsetHeight;
138
+
139
+ if (overflowTop || overflowBottom) {
140
+ const count = element.offsetTop - container.offsetHeight / 2 + element.offsetHeight / 2;
141
+ container.scroll({ top: count, behavior: 'smooth' });
142
+ }
143
+ return;
144
+ }
145
+
146
+ const overflowLeft = element.offsetLeft < container.scrollLeft;
147
+ const overflowRight = element.offsetLeft + element.offsetWidth > container.scrollLeft + container.offsetWidth;
148
+
149
+ if (overflowLeft || overflowRight) {
150
+ const count = element.offsetLeft - container.offsetWidth / 2 + element.offsetWidth / 2;
151
+ container.scroll({ left: count, behavior: 'smooth' });
152
+ }
153
+ }
154
+ },
155
+ [orientation],
156
+ );
157
+
158
+ const onSelectHandler = useCallback(
159
+ (element: HTMLButtonElement) => {
160
+ updateMarkPosition(element);
161
+ scrollContainerToElement(element);
162
+ },
163
+ [scrollContainerToElement, updateMarkPosition],
164
+ );
165
+
166
+ const onFocusHandler = useCallback(
167
+ (element: HTMLButtonElement, value: string) => {
168
+ setFocusedTab(value);
169
+ scrollContainerToElement(element);
170
+ },
171
+ [scrollContainerToElement],
172
+ );
173
+
174
+ const [getPrev, getNext] = useFocusControl(children);
175
+
176
+ const handleKeyDown = useCallback(
177
+ (e: KeyboardEvent<HTMLDivElement>) => {
178
+ let newFocusTab: string | undefined;
179
+ if (e.key === 'ArrowRight') newFocusTab = getNext(focusedTab || selectedTab);
180
+ if (e.key === 'ArrowLeft') newFocusTab = getPrev(focusedTab || selectedTab);
181
+ if (e.key === 'ArrowUp') newFocusTab = getPrev(focusedTab || selectedTab);
182
+ if (e.key === 'ArrowDown') newFocusTab = getNext(focusedTab || selectedTab);
183
+ if (newFocusTab) {
184
+ e.preventDefault();
185
+ setFocusedTab(newFocusTab);
186
+ }
187
+ },
188
+ [getPrev, getNext, focusedTab, selectedTab],
189
+ );
190
+
191
+ return (
192
+ <div
193
+ className={cn(styles.tabBar, className)}
194
+ role='tablist'
195
+ data-orientation={orientation}
196
+ data-size={size}
197
+ {...extractSupportProps(otherProps)}
198
+ >
199
+ {/* Область списка: слот табов, кнопки прокрутки и линия. Слот действия (`slotActionButton`)
200
+ лежит снаружи — по макету линия под ним не продолжается. */}
201
+ <div className={styles.tabListWrapper} data-orientation={orientation}>
202
+ {!disableDivider && (
203
+ <div className={styles.divider} data-position={markerPosition}>
204
+ <Divider variant='regular' orientation={orientation} />
205
+ </div>
206
+ )}
207
+ <div className={styles.tabBarScrollZone} data-orientation={orientation}>
208
+ <div className={styles.tabBarMain} data-testid='tabs__bar-wrap' data-orientation={orientation}>
209
+ <ScrollContainer
210
+ className={cn(SCROLL_CONTAINER_ORIENTATION_MAP[orientation], styles.scrollArea)}
211
+ innerRef={scrollContainerRef as RefObject<HTMLElement>}
212
+ >
213
+ <div
214
+ className={styles.tabsRow}
215
+ data-size={size}
216
+ data-orientation={orientation}
217
+ onKeyDown={handleKeyDown}
218
+ role='presentation'
219
+ >
220
+ <TabBarContext.Provider
221
+ value={{
222
+ onSelect: onSelectHandler,
223
+ size,
224
+ orientation,
225
+ focusedTab,
226
+ onFocus: onFocusHandler,
227
+ }}
228
+ >
229
+ {children}
230
+ </TabBarContext.Provider>
231
+
232
+ <div
233
+ className={styles.marker}
234
+ style={markerScrollPosition}
235
+ data-position={markerPosition}
236
+ data-orientation={orientation}
237
+ />
238
+ </div>
239
+ </ScrollContainer>
240
+ </div>
241
+
242
+ {orientation === ORIENTATION.Horizontal && hasOverflow.left && (
243
+ <ScrollButton direction='left' onClick={scrollLeft} orientation={orientation} size={size} />
244
+ )}
245
+ {orientation === ORIENTATION.Horizontal && hasOverflow.right && (
246
+ <ScrollButton direction='right' onClick={scrollRight} orientation={orientation} size={size} />
247
+ )}
248
+ {orientation === ORIENTATION.Vertical && hasOverflow.top && (
249
+ <ScrollButton direction='top' onClick={scrollTop} orientation={orientation} size={size} />
250
+ )}
251
+ {orientation === ORIENTATION.Vertical && hasOverflow.bottom && (
252
+ <ScrollButton direction='bottom' onClick={scrollBottom} orientation={orientation} size={size} />
253
+ )}
254
+ </div>
255
+ </div>
256
+
257
+ {slotActionButton && (
258
+ <div
259
+ data-testid='tabs__bar__after'
260
+ data-orientation={orientation}
261
+ data-size={size}
262
+ className={styles.tabBarAfter}
263
+ >
264
+ {slotActionButton}
265
+ </div>
266
+ )}
267
+ </div>
268
+ );
269
+ }