@cloud-ru/ds-card 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 (47) hide show
  1. package/CHANGELOG.md +8 -0
  2. package/LICENSE +201 -0
  3. package/README.md +214 -0
  4. package/dist/cjs/components/Card/Card.d.ts +6 -0
  5. package/dist/cjs/components/Card/Card.js +47 -0
  6. package/dist/cjs/components/Card/index.d.ts +1 -0
  7. package/dist/cjs/components/Card/index.js +5 -0
  8. package/dist/cjs/components/Card/styles.module.css +415 -0
  9. package/dist/cjs/components/index.d.ts +1 -0
  10. package/dist/cjs/components/index.js +17 -0
  11. package/dist/cjs/constants.d.ts +27 -0
  12. package/dist/cjs/constants.js +26 -0
  13. package/dist/cjs/context.d.ts +7 -0
  14. package/dist/cjs/context.js +13 -0
  15. package/dist/cjs/index.d.ts +5 -0
  16. package/dist/cjs/index.js +23 -0
  17. package/dist/cjs/package.json +3 -0
  18. package/dist/cjs/style.css +415 -0
  19. package/dist/cjs/types.d.ts +48 -0
  20. package/dist/cjs/types.js +2 -0
  21. package/dist/esm/components/Card/Card.d.ts +6 -0
  22. package/dist/esm/components/Card/Card.js +41 -0
  23. package/dist/esm/components/Card/index.d.ts +1 -0
  24. package/dist/esm/components/Card/index.js +1 -0
  25. package/dist/esm/components/Card/styles.module.css +415 -0
  26. package/dist/esm/components/index.d.ts +1 -0
  27. package/dist/esm/components/index.js +1 -0
  28. package/dist/esm/constants.d.ts +27 -0
  29. package/dist/esm/constants.js +23 -0
  30. package/dist/esm/context.d.ts +7 -0
  31. package/dist/esm/context.js +9 -0
  32. package/dist/esm/index.d.ts +5 -0
  33. package/dist/esm/index.js +5 -0
  34. package/dist/esm/style.css +415 -0
  35. package/dist/esm/types.d.ts +48 -0
  36. package/dist/esm/types.js +1 -0
  37. package/dist/tsconfig.cjs.tsbuildinfo +1 -0
  38. package/dist/tsconfig.esm.tsbuildinfo +1 -0
  39. package/package.json +45 -0
  40. package/src/components/Card/Card.tsx +101 -0
  41. package/src/components/Card/index.ts +1 -0
  42. package/src/components/Card/styles.module.scss +190 -0
  43. package/src/components/index.ts +1 -0
  44. package/src/constants.ts +26 -0
  45. package/src/context.tsx +18 -0
  46. package/src/index.ts +5 -0
  47. package/src/types.ts +53 -0
@@ -0,0 +1,101 @@
1
+ import { ACRYLIC_LEVEL, BACKGROUND_PREDEFINED_FILL, backgroundPredefinedFillToAcrylic } from '@cloud-ru/ds-materials';
2
+ import { Checkbox, SIZE as CHECKBOX_SIZE } from '@cloud-ru/ds-toggles';
3
+ import { extractSupportProps, withInnerRefSupport } from '@cloud-ru/ds-utils';
4
+ import cn from 'classnames';
5
+ import { ComponentPropsWithoutRef, ElementType, MouseEvent, ReactElement } from 'react';
6
+
7
+ import { RADIUS, TEST_IDS, VIEW } from '../../constants';
8
+ import { CardContext } from '../../context';
9
+ import { CardProps } from '../../types';
10
+ import styles from './styles.module.scss';
11
+
12
+ const TARGET_BLANK = '_blank';
13
+
14
+ export function Card<T extends ElementType = 'div'>({
15
+ radius = RADIUS.M,
16
+ view = VIEW.Simple,
17
+ backgroundPredefined = BACKGROUND_PREDEFINED_FILL.NeutralBackground1Level,
18
+ disabled = false,
19
+ checked,
20
+ multiSelect = false,
21
+ interactive = true,
22
+ children,
23
+ className,
24
+ as,
25
+ innerRef,
26
+ ...rest
27
+ }: CardProps<T>): ReactElement | null {
28
+ const Component: ElementType = as ?? 'div';
29
+ const supportProps = extractSupportProps(rest);
30
+ const { appearance, level } = backgroundPredefinedFillToAcrylic(backgroundPredefined);
31
+ const isAnchor = Component === 'a';
32
+ // Disabled по макету теряет уровень подложки — это уровень материала, а не фон поверх акрила.
33
+ const acrylicLevel = disabled ? ACRYLIC_LEVEL.Default : level;
34
+
35
+ // `<a>` нативно не реагирует на `disabled` — на disabled-anchor вешаем preventDefault,
36
+ // и санитизируем `rel` под `target='_blank'`. Остальные элементы пробрасывают `...rest` без обвязки.
37
+ let polymorphicProps: Record<string, unknown>;
38
+ if (isAnchor) {
39
+ const { href, target, onClick, ...anchorRest } = rest as ComponentPropsWithoutRef<'a'>;
40
+ polymorphicProps = {
41
+ ...anchorRest,
42
+ href: href ?? '#',
43
+ target,
44
+ rel: target === TARGET_BLANK ? 'noopener noreferrer' : undefined,
45
+ onClick: disabled
46
+ ? (e: MouseEvent<HTMLAnchorElement>) => {
47
+ e.preventDefault();
48
+ onClick?.(e);
49
+ }
50
+ : onClick,
51
+ };
52
+ } else {
53
+ polymorphicProps = rest as Record<string, unknown>;
54
+ }
55
+
56
+ return (
57
+ <CardContext.Provider value={{ radius, disabled }}>
58
+ <Component
59
+ ref={innerRef}
60
+ className={cn(styles.card, className)}
61
+ data-card
62
+ data-radius={radius}
63
+ data-view={view}
64
+ data-disabled={disabled || undefined}
65
+ data-checked={checked || undefined}
66
+ data-interactive={interactive || undefined}
67
+ data-acrylic-appearance={appearance}
68
+ data-acrylic-level={acrylicLevel}
69
+ tabIndex={interactive && !disabled ? 0 : -1}
70
+ aria-disabled={isAnchor && disabled ? true : undefined}
71
+ {...supportProps}
72
+ {...polymorphicProps}
73
+ >
74
+ {/* Порядок дочерних узлов важен: среди позиционированных братьев с z-index:auto
75
+ более поздний в DOM рисуется поверх. Сверху вниз painting:
76
+ acrylic (фон) → stateLayer (checked-overlay) → content → outlineBorder → checkBadge.
77
+ Border-слой намеренно после content — Figma `stateLayer/borderOnBackground` лежит
78
+ поверх контента, чтобы рисовался по краю независимо от padding'а content'а. */}
79
+ <span className={styles.acrylic} aria-hidden data-acrylic-background />
80
+ {/* State-layer только для checked: Figma использует activated-filled overlay;
81
+ в unchecked-состоянии stateLayer-слоя нет — hover там идёт через box-shadow. */}
82
+ {interactive && checked && (
83
+ <span className={styles.stateLayer} data-state='activatedOnBackground' aria-hidden />
84
+ )}
85
+ <div className={styles.content}>{children}</div>
86
+ {/* Border-слой (Figma: `stateLayer/borderOnBackground`) — overlay inset:0 поверх content'а;
87
+ цвет переключается по data-view/data-checked родителя (см. styles.module.scss). */}
88
+ {(view === VIEW.Outline || checked) && <span className={styles.outlineBorder} aria-hidden />}
89
+ {checked && multiSelect && (
90
+ <span className={styles.checkWrapper} aria-hidden>
91
+ <Checkbox checked size={CHECKBOX_SIZE.XS} tabIndex={-1} data-test-id={TEST_IDS.checkBadge} />
92
+ </span>
93
+ )}
94
+ </Component>
95
+ </CardContext.Provider>
96
+ );
97
+ }
98
+
99
+ Card.displayName = 'Card';
100
+
101
+ withInnerRefSupport(Card);
@@ -0,0 +1 @@
1
+ export { Card } from './Card';
@@ -0,0 +1,190 @@
1
+ @use '@cloud-ru/ds-figma-variables/build/scss/styles/styles.module' as base;
2
+ @use '@cloud-ru/ds-figma-variables/build/scss/components/card.module' as card;
3
+ @use '@cloud-ru/ds-materials' as m;
4
+
5
+ $radii: 's', 'm', 'l';
6
+ $radius-to-border-radius: (
7
+ 's': card.$sn-card-anatomy-radius-s-container-borderRadius,
8
+ 'm': card.$sn-card-anatomy-radius-m-container-borderRadius,
9
+ 'l': card.$sn-card-anatomy-radius-l-container-borderRadius,
10
+ );
11
+ $radius-to-border-width: (
12
+ 's': card.$sn-card-anatomy-radius-s-container-borderWidth,
13
+ 'm': card.$sn-card-anatomy-radius-m-container-borderWidth,
14
+ 'l': card.$sn-card-anatomy-radius-l-container-borderWidth,
15
+ );
16
+ $radius-to-badge-padding-left: (
17
+ 's': card.$sn-card-anatomy-radius-s-container-badge-paddingLeft,
18
+ 'm': card.$sn-card-anatomy-radius-m-container-badge-paddingLeft,
19
+ 'l': card.$sn-card-anatomy-radius-l-container-badge-paddingLeft,
20
+ );
21
+ $radius-to-badge-padding-top: (
22
+ 's': card.$sn-card-anatomy-radius-s-container-badge-paddingTop,
23
+ 'm': card.$sn-card-anatomy-radius-m-container-badge-paddingTop,
24
+ 'l': card.$sn-card-anatomy-radius-l-container-badge-paddingTop,
25
+ );
26
+
27
+ .acrylic {
28
+ pointer-events: none;
29
+ position: absolute;
30
+ inset: 0;
31
+ border-radius: inherit;
32
+ }
33
+
34
+ .outlineBorder {
35
+ // Слой рисуется поверх .content за счёт порядка узлов в JSX (см. Card.tsx) —
36
+ // z-index не нужен: среди позиционированных братьев с z-index:auto более поздний
37
+ // в DOM рисуется поверх.
38
+ pointer-events: none;
39
+
40
+ position: absolute;
41
+ inset: 0;
42
+
43
+ border-color: base.$sn-theme-color-material-stateLayer-neutral-border-default-borderColor;
44
+ border-style: solid;
45
+ border-radius: inherit;
46
+ }
47
+
48
+ .stateLayer {
49
+ visibility: initial;
50
+ }
51
+
52
+ .checkWrapper {
53
+ // Чек-бейдж — последний узел в JSX, поэтому рисуется поверх outlineBorder/content
54
+ // без z-index (порядок DOM решает).
55
+ pointer-events: none;
56
+
57
+ position: absolute;
58
+ top: 0;
59
+ left: 0;
60
+
61
+ display: flex;
62
+ align-items: center;
63
+ justify-content: center;
64
+ }
65
+
66
+ .card {
67
+ cursor: default;
68
+
69
+ isolation: isolate;
70
+ position: relative;
71
+
72
+ overflow: hidden;
73
+ display: flex;
74
+ flex-direction: column;
75
+
76
+ box-sizing: border-box;
77
+ max-width: 100%;
78
+ margin: 0;
79
+ padding: 0;
80
+
81
+ // Сброс стилей нативной ссылки
82
+ color: inherit;
83
+ text-decoration: none;
84
+
85
+ background: transparent;
86
+ outline: none;
87
+
88
+ &[data-interactive]:not([data-disabled]) {
89
+ cursor: pointer;
90
+ }
91
+
92
+ &[data-disabled] {
93
+ cursor: not-allowed;
94
+ }
95
+
96
+ // Аннотация Figma «фокус теперь внутри»: 2px `primary/accent` рамка ВНУТРИ карточки.
97
+ // Рисуем через `::after`, а не root-outline: позиционированные братья (acrylic,
98
+ // content, outlineBorder) с z-index:auto рисуются поверх собственного outline корня и
99
+ // перекрывают его прямые грани, оставляя видимыми только углы. `::after` — последний
100
+ // «ребёнок» в порядке рисования, поэтому кольцо ложится поверх всех оверлеев целиком.
101
+ &[data-interactive]:focus-visible::after {
102
+ pointer-events: none;
103
+ content: '';
104
+
105
+ position: absolute;
106
+ inset: 0;
107
+
108
+ border: base.$sn-primitive-strokeWeight-strokeSemiBold solid base.$sn-theme-color-primary-accent;
109
+ border-radius: inherit;
110
+ }
111
+
112
+ &[data-view='simple'],
113
+ &[data-view='outline'] {
114
+ box-shadow: none;
115
+ }
116
+
117
+ &[data-view='elevated'] {
118
+ box-shadow: base.$sn-boxShadow-elevation-level2;
119
+ }
120
+
121
+ &[data-interactive]:not([data-disabled]):active {
122
+ &[data-view='simple'],
123
+ &[data-view='outline'] {
124
+ box-shadow: none;
125
+ }
126
+
127
+ &[data-view='elevated'] {
128
+ box-shadow: base.$sn-boxShadow-elevation-level2;
129
+ }
130
+ }
131
+
132
+ &[data-checked] .outlineBorder {
133
+ border-color: base.$sn-theme-color-primary-accent;
134
+ }
135
+
136
+ @media (hover: hover) {
137
+ &[data-interactive]:not([data-disabled]):hover {
138
+ &[data-view='simple'] {
139
+ box-shadow: base.$sn-boxShadow-elevation-level3;
140
+ }
141
+
142
+ &[data-view='outline']:not([data-checked]) .outlineBorder {
143
+ border-color: base.$sn-theme-color-material-stateLayer-neutral-border-hovered-borderColor;
144
+ }
145
+
146
+ &[data-view='elevated'] {
147
+ box-shadow: base.$sn-boxShadow-elevation-level3;
148
+ }
149
+ }
150
+ }
151
+
152
+ @each $r in $radii {
153
+ &[data-view='outline'][data-radius='#{$r}'] .outlineBorder,
154
+ &[data-checked][data-radius='#{$r}'] .outlineBorder {
155
+ border-width: base.simple-var($radius-to-border-width, $r);
156
+ }
157
+ }
158
+
159
+ @each $r in $radii {
160
+ &[data-radius='#{$r}'] {
161
+ border-radius: base.simple-var($radius-to-border-radius, $r);
162
+
163
+ .checkWrapper {
164
+ padding-top: base.simple-var($radius-to-badge-padding-top, $r);
165
+ padding-left: base.simple-var($radius-to-badge-padding-left, $r);
166
+ }
167
+ }
168
+ }
169
+
170
+ @include m.with-material('acrylic', 'acrylic');
171
+ @include m.has-state-layer-as-child('stateLayer');
172
+ }
173
+
174
+ .content {
175
+ // position: relative нужен, чтобы content участвовал в painting'е как
176
+ // позиционированный брат (paint order: acrylic → stateLayer → content → outlineBorder).
177
+ // z-index не задаём — порядок узлов в JSX (см. Card.tsx) сам определяет stacking.
178
+ position: relative;
179
+
180
+ box-sizing: border-box;
181
+ width: 100%;
182
+ min-width: 0;
183
+ border-radius: inherit;
184
+ }
185
+
186
+ // Гаснет только контент: в мастере прозрачность 0.4 стоит на слое `element`,
187
+ // а не на самой карточке, поэтому подложка и рамка остаются в полную силу.
188
+ .card[data-disabled] .content {
189
+ opacity: base.$sn-theme-effect-opacity-disabled;
190
+ }
@@ -0,0 +1 @@
1
+ export * from './Card';
@@ -0,0 +1,26 @@
1
+ export const RADIUS = {
2
+ S: 's',
3
+ M: 'm',
4
+ L: 'l',
5
+ } as const;
6
+
7
+ /** Алиас `RADIUS` для обратной совместимости с Snack UI Kit Card API. */
8
+ export const SIZE = RADIUS;
9
+
10
+ export const VIEW = {
11
+ Simple: 'simple',
12
+ Outline: 'outline',
13
+ Elevated: 'elevated',
14
+ } as const;
15
+
16
+ export const TEST_IDS = {
17
+ root: 'card',
18
+ checkBadge: 'card__check-badge',
19
+ emblemPicture: 'card__header__emblem-picture',
20
+ emblemIcon: 'card__header__emblem-icon',
21
+ title: 'card__header__title',
22
+ description: 'card__header__description',
23
+ metadata: 'card__header__metadata',
24
+ functionBadge: 'card__function-badge',
25
+ droplist: 'card__function-badge-droplist',
26
+ } as const;
@@ -0,0 +1,18 @@
1
+ import { createContext, useContext } from 'react';
2
+
3
+ import { RADIUS } from './constants';
4
+ import { Radius } from './types';
5
+
6
+ export type CardContextValue = {
7
+ radius: Radius;
8
+ disabled: boolean;
9
+ };
10
+
11
+ export const CardContext = createContext<CardContextValue>({
12
+ radius: RADIUS.M,
13
+ disabled: false,
14
+ });
15
+
16
+ export function useCardContext() {
17
+ return useContext(CardContext);
18
+ }
package/src/index.ts ADDED
@@ -0,0 +1,5 @@
1
+ export * from './components';
2
+ export * from './constants';
3
+ export * from './context';
4
+ export * from './types';
5
+ export { setNonce } from '@cloud-ru/ds-tag';
package/src/types.ts ADDED
@@ -0,0 +1,53 @@
1
+ import { BackgroundPredefinedFill } from '@cloud-ru/ds-materials';
2
+ import { ValueOf } from '@cloud-ru/ds-utils';
3
+ import { ComponentPropsWithoutRef, ComponentPropsWithRef, ElementType, ReactNode } from 'react';
4
+
5
+ import { RADIUS, VIEW } from './constants';
6
+
7
+ export type Radius = ValueOf<typeof RADIUS>;
8
+ /** Алиас `Radius` для обратной совместимости с Snack UI Kit Card API. */
9
+ export type Size = Radius;
10
+ export type View = ValueOf<typeof VIEW>;
11
+
12
+ export type PolymorphicRef<T extends ElementType> = ComponentPropsWithRef<T>['ref'];
13
+
14
+ export type BaseCardProps = {
15
+ /** Радиус контейнера. */
16
+ radius?: Radius;
17
+ /** Визуальный режим карточки. */
18
+ view?: View;
19
+ /**
20
+ * Слой backgroundPredefined + acrylic (см. `BACKGROUND_PREDEFINED_FILL` в `@cloud-ru/ds-materials`).
21
+ * По умолчанию `material/neutralBackground1Level`.
22
+ */
23
+ backgroundPredefined?: BackgroundPredefinedFill;
24
+ /** Заблокированный режим: интерактив отключён, opacity снижен. */
25
+ disabled?: boolean;
26
+ /** Выбран (для multiSelect — показывает чек-бэйдж в углу). */
27
+ checked?: boolean;
28
+ /** Режим множественного выбора — добавляет чек-бэйдж в углу при `checked`. */
29
+ multiSelect?: boolean;
30
+ /**
31
+ * Включает интерактивные эффекты (hover/press state layer, cursor: pointer, focus-ring).
32
+ * Установи `false` для презентационной карточки без отклика на курсор.
33
+ * @default true
34
+ */
35
+ interactive?: boolean;
36
+ children?: ReactNode;
37
+ className?: string;
38
+ };
39
+
40
+ /**
41
+ * Полиморфный проп: рендер как `div` (по умолчанию), как `a` или как кастомный
42
+ * компонент (например `Link` из react-router-dom). Для `as='a'` поддерживается
43
+ * `href`/`target`/`rel`; для `as={Link}` — `to`, и т.д. — типы вытягиваются из
44
+ * `ComponentPropsWithoutRef<T>`.
45
+ */
46
+ export type CardProps<T extends ElementType = 'div'> = BaseCardProps & {
47
+ as?: T;
48
+ /**
49
+ * Ref на реальный DOM-элемент/инстанс, который рендерится через `as`.
50
+ * Используем явный проп, чтобы не зависеть от `forwardRef` и не тащить type-assertions на экспорт.
51
+ */
52
+ innerRef?: PolymorphicRef<T>;
53
+ } & Omit<ComponentPropsWithoutRef<T>, keyof BaseCardProps | 'as' | 'ref'>;