@cloud-ru/ds-ai-shimmer 1.0.1 → 1.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/AiShimmer.tsx CHANGED
@@ -1,6 +1,6 @@
1
- import { extractSupportProps, useLayoutEffect } from '@cloud-ru/ds-utils';
1
+ import { extractSupportProps } from '@cloud-ru/ds-utils';
2
2
  import cn from 'classnames';
3
- import { CSSProperties, useCallback, useEffect, useMemo, useRef, useState } from 'react';
3
+ import { CSSProperties, useCallback, useEffect, useId, useMemo, useRef, useState } from 'react';
4
4
 
5
5
  import {
6
6
  DEFAULT_ICON_SIZE,
@@ -8,9 +8,10 @@ import {
8
8
  DEFAULT_SIZE,
9
9
  DEFAULT_VARIANT,
10
10
  DEFAULT_WEIGHT,
11
- END_HEIGHT_EXTRA,
12
- fontMetricsForTypography,
13
11
  TEST_IDS,
12
+ WAVE_GRADIENT,
13
+ WAVE_STOPS,
14
+ waveStopColor,
14
15
  } from './constants';
15
16
  import styles from './styles.module.scss';
16
17
  import { AiShimmerProps } from './types';
@@ -20,67 +21,66 @@ export function AiShimmer({
20
21
  variant = DEFAULT_VARIANT,
21
22
  size = DEFAULT_SIZE,
22
23
  weight = DEFAULT_WEIGHT,
24
+ icon,
23
25
  iconMask,
24
26
  iconSize = DEFAULT_ICON_SIZE,
27
+ slotAfter,
25
28
  className,
26
29
  'data-test-id': dataTestId = TEST_IDS.root,
27
30
  ...rest
28
31
  }: AiShimmerProps) {
29
32
  const rootRef = useRef<HTMLDivElement>(null);
30
33
  const textRef = useRef<HTMLSpanElement>(null);
31
- const fallbackHeight = fontMetricsForTypography(variant, size, weight).lineHeight;
32
- const [contentHeight, setContentHeight] = useState(fallbackHeight);
34
+ const slotRef = useRef<HTMLSpanElement>(null);
33
35
  const [lineWidth, setLineWidth] = useState(DEFAULT_ROOT_WIDTH);
36
+ const [slotOffset, setSlotOffset] = useState(0);
37
+ const gradientId = useId();
38
+ const maskId = useId();
34
39
 
35
- const hasIcon = Boolean(iconMask);
40
+ const hasIconNode = icon != null && icon !== false;
41
+ const hasIcon = hasIconNode || Boolean(iconMask);
42
+ const hasSlotAfter = slotAfter != null && slotAfter !== false;
36
43
 
44
+ // Волна задана в пикселях строки, поэтому ширину и отступ слота нужно замерить.
37
45
  const measureLayout = useCallback(() => {
38
- const textNode = textRef.current;
46
+ const rootNode = rootRef.current;
39
47
 
40
- if (textNode) {
41
- const measuredContentHeight = Math.ceil(textNode.getBoundingClientRect().height);
42
- setContentHeight(prev => (Math.abs(prev - measuredContentHeight) > 0.5 ? measuredContentHeight : prev));
48
+ if (!rootNode) {
49
+ return;
43
50
  }
44
51
 
45
- const rootNode = rootRef.current;
52
+ const rootRect = rootNode.getBoundingClientRect();
53
+ const measuredWidth = Math.ceil(rootRect.width);
54
+ setLineWidth(prev => (measuredWidth > 0 && Math.abs(prev - measuredWidth) > 0.5 ? measuredWidth : prev));
55
+
56
+ const slotNode = slotRef.current;
46
57
 
47
- if (rootNode) {
48
- const measuredWidth = Math.ceil(rootNode.getBoundingClientRect().width);
49
- setLineWidth(prev => (measuredWidth > 0 && Math.abs(prev - measuredWidth) > 0.5 ? measuredWidth : prev));
58
+ if (slotNode) {
59
+ const measuredOffset = slotNode.getBoundingClientRect().left - rootRect.left;
60
+ setSlotOffset(prev => (Math.abs(prev - measuredOffset) > 0.5 ? measuredOffset : prev));
50
61
  }
51
62
  }, []);
52
63
 
53
- useLayoutEffect(() => {
54
- setContentHeight(fallbackHeight);
64
+ useEffect(() => {
55
65
  measureLayout();
56
66
 
57
- const frameId = requestAnimationFrame(() => {
58
- measureLayout();
59
- });
60
-
61
- return () => cancelAnimationFrame(frameId);
62
- }, [fallbackHeight, measureLayout, size, text, variant, weight]);
63
-
64
- useEffect(() => {
65
- const textNode = textRef.current;
66
- const parentNode = textRef.current?.parentElement ?? null;
67
+ const rootNode = rootRef.current;
67
68
 
68
- if (typeof ResizeObserver === 'undefined') {
69
+ if (typeof ResizeObserver === 'undefined' || !rootNode) {
69
70
  return undefined;
70
71
  }
71
72
 
72
73
  const observer = new ResizeObserver(() => measureLayout());
74
+ observer.observe(rootNode);
73
75
 
74
- if (textNode) {
75
- observer.observe(textNode);
76
- }
76
+ const slotNode = slotRef.current;
77
77
 
78
- if (parentNode) {
79
- observer.observe(parentNode);
78
+ if (slotNode) {
79
+ observer.observe(slotNode);
80
80
  }
81
81
 
82
82
  return () => observer.disconnect();
83
- }, [measureLayout]);
83
+ }, [measureLayout, hasSlotAfter]);
84
84
 
85
85
  useEffect(() => {
86
86
  if (typeof document === 'undefined' || !document.fonts?.ready) {
@@ -102,21 +102,48 @@ export function AiShimmer({
102
102
  };
103
103
  }, [measureLayout, size, text, variant, weight]);
104
104
 
105
- const spreadStartHeight = Math.max(contentHeight, fallbackHeight);
106
- const spreadEndHeight = spreadStartHeight + END_HEIGHT_EXTRA;
107
-
108
105
  const rootStyle = useMemo(
109
106
  (): CSSProperties => ({
110
- '--ai-shimmer-spread-start-height': `${spreadStartHeight}px`,
111
- '--ai-shimmer-spread-end-height': `${spreadEndHeight}px`,
112
- ...(hasIcon && {
113
- '--ai-shimmer-icon-size': `${iconSize}px`,
114
- '--ai-shimmer-line-width': `${lineWidth}px`,
115
- }),
107
+ '--ai-shimmer-wave-gradient': WAVE_GRADIENT,
108
+ '--ai-shimmer-wave-width': `${2 * lineWidth}px`,
109
+ ...(hasIcon && { '--ai-shimmer-icon-size': `${iconSize}px` }),
110
+ ...(hasSlotAfter && { '--ai-shimmer-slot-offset': `${slotOffset}px` }),
116
111
  }),
117
- [hasIcon, iconSize, lineWidth, spreadEndHeight, spreadStartHeight],
112
+ [hasIcon, hasSlotAfter, iconSize, lineWidth, slotOffset],
118
113
  );
119
114
 
115
+ let lead = null;
116
+
117
+ if (hasIconNode) {
118
+ lead = (
119
+ <svg className={styles.leadIcon} data-test-id={TEST_IDS.icon} aria-hidden>
120
+ <defs>
121
+ <linearGradient id={gradientId} x1='0' y1='0' x2='1' y2='0'>
122
+ {WAVE_STOPS.map(stop => (
123
+ <stop key={stop.offset} offset={stop.offset} stopColor={waveStopColor(stop)} stopOpacity={stop.opacity} />
124
+ ))}
125
+ </linearGradient>
126
+ <mask id={maskId} className={styles.leadMask} maskUnits='userSpaceOnUse' x='0' y='0' width='100%' height='100%'>
127
+ {icon}
128
+ </mask>
129
+ </defs>
130
+ <g mask={`url(#${maskId})`}>
131
+ <rect className={styles.leadBase} width='100%' height='100%' />
132
+ <rect className={styles.leadWave} height='100%' fill={`url(#${gradientId})`} />
133
+ </g>
134
+ </svg>
135
+ );
136
+ } else if (iconMask) {
137
+ lead = (
138
+ <span
139
+ className={styles.lead}
140
+ style={{ maskImage: iconMask, WebkitMaskImage: iconMask }}
141
+ data-test-id={TEST_IDS.icon}
142
+ aria-hidden
143
+ />
144
+ );
145
+ }
146
+
120
147
  return (
121
148
  <div
122
149
  ref={rootRef}
@@ -126,25 +153,19 @@ export function AiShimmer({
126
153
  data-size={size}
127
154
  data-weight={weight}
128
155
  data-has-icon={hasIcon || undefined}
156
+ data-has-slot={hasSlotAfter || undefined}
129
157
  data-test-id={dataTestId}
130
158
  {...extractSupportProps(rest)}
131
159
  >
132
- <span ref={textRef} className={cn(styles.text, styles.textGhost)} data-test-id={TEST_IDS.text}>
133
- {hasIcon && <span className={styles.lead} aria-hidden />}
160
+ <span ref={textRef} className={styles.text} data-test-id={TEST_IDS.text}>
161
+ {lead}
134
162
  {text}
135
163
  </span>
136
- <span className={styles.shimmer} data-test-id={TEST_IDS.shimmer} aria-hidden>
137
- <span className={cn(styles.text, styles.shimmerText)} data-test-id={TEST_IDS.spread}>
138
- {hasIcon && (
139
- <span
140
- className={cn(styles.lead, styles.shimmerIcon)}
141
- style={{ maskImage: iconMask, WebkitMaskImage: iconMask }}
142
- data-test-id={TEST_IDS.icon}
143
- />
144
- )}
145
- {text}
164
+ {hasSlotAfter && (
165
+ <span ref={slotRef} className={styles.slot} data-test-id={TEST_IDS.slot}>
166
+ {slotAfter}
146
167
  </span>
147
- </span>
168
+ )}
148
169
  </div>
149
170
  );
150
171
  }
package/src/constants.ts CHANGED
@@ -1,11 +1,10 @@
1
- import { AiShimmerFontMetrics, AiShimmerSize, AiShimmerVariant, AiShimmerWeight } from './types';
1
+ import { AiShimmerSize, AiShimmerVariant, AiShimmerWeight } from './types';
2
2
 
3
3
  export const TEST_IDS = {
4
4
  root: 'ai-shimmer',
5
5
  text: 'ai-shimmer__text',
6
- shimmer: 'ai-shimmer__shimmer',
7
- spread: 'ai-shimmer__spread',
8
6
  icon: 'ai-shimmer__icon',
7
+ slot: 'ai-shimmer__slot',
9
8
  } as const;
10
9
 
11
10
  /** Варианты типографики. */
@@ -43,48 +42,31 @@ export const DEFAULT_WEIGHT: AiShimmerWeight = WEIGHT.regular;
43
42
  /** Размер ведущей иконки по умолчанию (px), когда задан `iconMask`. */
44
43
  export const DEFAULT_ICON_SIZE = 16;
45
44
 
46
- const DEFAULT_FONT_METRICS: AiShimmerFontMetrics = {
47
- fontSize: 16,
48
- lineHeight: 24,
49
- fontWeight: '400',
50
- };
51
-
52
- /** Fallback-метрики body regular для расчёта высоты до замера DOM. */
53
- export const TYPOGRAPHY_FONT_METRICS: Partial<Record<string, AiShimmerFontMetrics>> = {
54
- 'regular-body-s': { fontSize: 14, lineHeight: 20, fontWeight: '400' },
55
- 'regular-body-m': DEFAULT_FONT_METRICS,
56
- 'regular-body-l': { fontSize: 20, lineHeight: 28, fontWeight: '400' },
57
- };
45
+ /** Ширина строки до первого замера DOM (SSR и первый рендер). */
46
+ export const DEFAULT_ROOT_WIDTH = 400;
58
47
 
59
- export function fontMetricsForTypography(
60
- variant: AiShimmerVariant = DEFAULT_VARIANT,
61
- size: AiShimmerSize = DEFAULT_SIZE,
62
- weight: AiShimmerWeight = DEFAULT_WEIGHT,
63
- ): AiShimmerFontMetrics {
64
- const key = `${weight}-${variant}-${size}`;
48
+ /**
49
+ * Стопы волны: единственный источник для CSS-градиента текста и SVG-градиента иконки.
50
+ * Цвета литералами — токенов под них в `@cloud-ru/ds-figma-variables` пока нет.
51
+ */
52
+ export const WAVE_STOPS = [
53
+ { offset: 0, rgb: [51, 140, 235], opacity: 0 },
54
+ { offset: 0.3, rgb: [51, 140, 235], opacity: 0 },
55
+ { offset: 0.4, rgb: [51, 140, 235], opacity: 1 },
56
+ { offset: 0.48, rgb: [59, 174, 209], opacity: 1 },
57
+ { offset: 0.54, rgb: [67, 208, 183], opacity: 1 },
58
+ { offset: 0.6, rgb: [52, 203, 151], opacity: 1 },
59
+ { offset: 0.68, rgb: [36, 198, 118], opacity: 1 },
60
+ { offset: 0.78, rgb: [36, 198, 118], opacity: 0 },
61
+ { offset: 1, rgb: [36, 198, 118], opacity: 0 },
62
+ ] as const;
65
63
 
66
- return TYPOGRAPHY_FONT_METRICS[key] ?? DEFAULT_FONT_METRICS;
64
+ /** Цвет стопа как CSS `rgb()`: без альфы для SVG `stop-color`, с альфой — для градиента. */
65
+ export function waveStopColor({ rgb: [r, g, b], opacity }: (typeof WAVE_STOPS)[number], withAlpha = false): string {
66
+ return withAlpha ? `rgb(${r} ${g} ${b} / ${opacity * 100}%)` : `rgb(${r} ${g} ${b})`;
67
67
  }
68
68
 
69
- /**
70
- * Геометрия SVG-маски shimmer: ширина/смещение маски, типографские метрики строк
71
- * и ограничения по высоте контейнера и "хвоста" анимации.
72
- */
73
- /** Ширина корня по умолчанию: используется до первого замера (SSR/первый рендер). */
74
- export const DEFAULT_ROOT_WIDTH = 400;
75
- /** Горизонтальное смещение маски относительно контейнера. */
76
- export const MASK_OFFSET_X = 0.6;
77
- /** Вертикальное смещение маски относительно контейнера. */
78
- export const MASK_OFFSET_Y = 3.892;
79
- /** Базовая линия первой текстовой строки в SVG. */
80
- export const BASELINE_FIRST_LINE = 9.24;
81
- /** Базовая высота маски для одной строки текста. */
82
- export const BASE_MASK_HEIGHT = 11.268;
83
- /** Дополнительная высота для конечной фазы spread-анимации. */
84
- export const END_HEIGHT_EXTRA = 40;
85
- /** Размер шрифта текста в SVG-маске. */
86
- export const MASK_TEXT_FONT_SIZE = 12;
87
- /** Межбуквенный интервал текста в SVG-маске. */
88
- export const MASK_TEXT_LETTER_SPACING = 0.1;
89
- /** Семейство шрифтов текста в SVG-маске. */
90
- export const MASK_TEXT_FONT_FAMILY = "'SB Sans Interface','Inter','Segoe UI',sans-serif";
69
+ /** Те же стопы как CSS `linear-gradient` — уходит в стили через `--ai-shimmer-wave-gradient`. */
70
+ export const WAVE_GRADIENT = `linear-gradient(90deg, ${WAVE_STOPS.map(
71
+ stop => `${waveStopColor(stop, true)} ${stop.offset * 100}%`,
72
+ ).join(', ')})`;
@@ -4,45 +4,51 @@ $weights: 'regular', 'thin', 'mono';
4
4
  $variants: 'display', 'headline', 'title', 'label', 'body';
5
5
  $sizes: 's', 'm', 'l';
6
6
 
7
- $spread-width: 108px;
8
- $spread-start-left: -124px;
9
- $spread-end-left: calc(100% + 124px);
10
- $default-line-width: 400px;
7
+ // Волна вдвое шире строки: проход слева направо 3 s, пауза 2 s. Позиция в пикселях, чтобы иконка,
8
+ // текст и слот шли одной полосой. Анимируется безразмерный прогресс, а не координата: кейфреймы
9
+ // с `var()` внутри Firefox для зарегистрированного свойства не интерполирует.
10
+ $wave-duration: 5s;
11
+ $default-wave-width: 800px;
12
+ $wave-width: var(--ai-shimmer-wave-width, #{$default-wave-width});
13
+ $wave-x: calc(var(--ai-shimmer-progress) * #{$wave-width});
14
+
15
+ @property --ai-shimmer-progress {
16
+ inherits: true;
17
+ initial-value: -0.75;
18
+ syntax: '<number>';
19
+ }
20
+
21
+ @mixin wave-motion {
22
+ animation: ai-shimmer-wave $wave-duration linear infinite;
23
+ }
24
+
25
+ // Градиент волны приходит из `WAVE_STOPS` (`constants.ts`) — один источник для текста и иконки.
26
+ @mixin wave-paint($base-color) {
27
+ @include wave-motion;
11
28
 
12
- /** Бегущий брендовый радиал-блик поверх приглушённой базы `$base-color`. */
13
- @mixin shimmer-paint($base-color) {
14
29
  background-image:
15
- radial-gradient(
16
- ellipse at 66% 22%,
17
- rgb(51 140 235 / 100%) 15%,
18
- rgb(59 174 209 / 100%) 30%,
19
- rgb(67 208 183 / 100%) 45%,
20
- rgb(52 203 151 / 100%) 55%,
21
- rgb(36 198 118 / 100%) 65%,
22
- rgb(36 198 118 / 0%) 100%
23
- ),
30
+ var(--ai-shimmer-wave-gradient),
24
31
  linear-gradient($base-color, $base-color);
25
32
  background-repeat: no-repeat;
26
33
  background-position:
27
- $spread-start-left 0,
34
+ #{$wave-x} 0,
28
35
  0 0;
29
36
  background-origin: border-box;
30
37
  background-size:
31
- $spread-width var(--ai-shimmer-spread-start-height),
38
+ #{$wave-width} 100%,
32
39
  100% 100%;
33
-
34
- animation: shimmer-text-move 3.75s linear infinite;
35
40
  }
36
41
 
37
- @property --ai-shimmer-x {
38
- inherits: true;
39
- initial-value: -124px;
40
- syntax: '<length>';
42
+ @mixin lead-box {
43
+ display: block;
44
+ flex-shrink: 0;
45
+
46
+ width: var(--ai-shimmer-icon-size, #{base.$sn-primitive-dimension-16});
47
+ height: var(--ai-shimmer-icon-size, #{base.$sn-primitive-dimension-16});
48
+ margin-right: base.$sn-primitive-dimension-4;
41
49
  }
42
50
 
43
51
  .root {
44
- position: relative;
45
-
46
52
  display: block;
47
53
 
48
54
  box-sizing: border-box;
@@ -52,14 +58,19 @@ $default-line-width: 400px;
52
58
  }
53
59
 
54
60
  .text {
61
+ @include wave-paint(base.$sn-theme-color-available-version-textSecondary);
62
+
55
63
  display: block;
56
64
 
57
65
  width: 100%;
58
66
  min-width: 0;
59
67
  max-width: 100%;
60
68
 
69
+ color: transparent;
61
70
  overflow-wrap: anywhere;
62
71
  white-space: pre-line;
72
+
73
+ background-clip: text;
63
74
  }
64
75
 
65
76
  @each $weight in $weights {
@@ -76,98 +87,136 @@ $default-line-width: 400px;
76
87
  }
77
88
  }
78
89
 
79
- .textGhost {
80
- color: transparent;
90
+ // Ведущая иконка силуэтом: `iconMask` как CSS-маска над фоном-волной.
91
+ .lead {
92
+ @include wave-paint(base.$sn-theme-color-available-version-textSecondary);
93
+ @include lead-box;
94
+
95
+ mask-repeat: no-repeat;
96
+ mask-position: center;
97
+ mask-size: var(--ai-shimmer-icon-size) var(--ai-shimmer-icon-size);
81
98
  }
82
99
 
83
- .shimmer {
84
- pointer-events: none;
85
- position: absolute;
86
- inset: 0;
100
+ // Ведущая иконка узлом: сам узел живёт в `<mask>`, под маской — прямоугольники базы и волны.
101
+ // Маска альфа-канальная, поэтому цвет иконки не важен — лишь бы он не был прозрачным.
102
+ .leadIcon {
103
+ @include lead-box;
104
+ @include wave-motion;
105
+
87
106
  overflow: hidden;
107
+ color: base.$sn-theme-color-available-version-textSecondary;
108
+ }
109
+
110
+ .leadMask {
111
+ mask-type: alpha;
88
112
  }
89
113
 
90
- .shimmerText {
91
- @include shimmer-paint(base.$sn-theme-color-available-version-textSecondary);
114
+ .leadBase {
115
+ fill: base.$sn-theme-color-available-version-textSecondary;
116
+ }
117
+
118
+ .leadWave {
119
+ transform: translateX(#{$wave-x});
120
+ width: $wave-width;
121
+ }
92
122
 
123
+ // Хвостовой слот — сосед текста, не потомок: внутри `.text` он получил бы вторую
124
+ // полупрозрачную базу и вышел бы темнее подписи. Свой бокс — своя поправка на отступ.
125
+ .slot {
126
+ @include wave-paint(base.$sn-theme-color-available-version-textTertiary);
127
+
128
+ flex-shrink: 0;
93
129
  color: transparent;
130
+ background-position:
131
+ calc(#{$wave-x} - var(--ai-shimmer-slot-offset, 0px)) 0,
132
+ 0 0;
94
133
  background-clip: text;
95
134
  }
96
135
 
97
- /** Ведущая иконка: спейсер в ghost-слое и засвеченный силуэт в shimmer-слое. */
98
- .lead {
99
- display: inline-block;
136
+ // С иконкой или слотом строка — плоский flex-ряд: иначе слот переносится на вторую строку.
137
+ .root[data-has-icon],
138
+ .root[data-has-slot] {
139
+ display: flex;
140
+ align-items: center;
141
+ width: fit-content;
142
+ max-width: 100%;
100
143
 
101
- width: var(--ai-shimmer-icon-size, 16px);
102
- height: var(--ai-shimmer-icon-size, 16px);
103
- margin-right: base.$sn-primitive-dimension-4;
144
+ .text {
145
+ display: flex;
146
+ align-items: center;
147
+
148
+ width: auto;
149
+ max-width: 100%;
104
150
 
105
- vertical-align: middle;
151
+ overflow-wrap: normal;
152
+ white-space: nowrap;
153
+ }
106
154
  }
107
155
 
108
- .shimmerIcon {
109
- // Иконка на тон светлее текста — как в DS (icon = tertiary, текст = secondary).
110
- @include shimmer-paint(base.$sn-theme-color-available-version-textTertiary);
156
+ @keyframes ai-shimmer-wave {
157
+ 0% {
158
+ --ai-shimmer-progress: -0.75;
159
+ }
111
160
 
112
- mask-repeat: no-repeat;
113
- mask-position: center;
114
- mask-size: var(--ai-shimmer-icon-size) var(--ai-shimmer-icon-size);
161
+ 60%,
162
+ 100% {
163
+ --ai-shimmer-progress: 0.25;
164
+ }
115
165
  }
116
166
 
117
- /**
118
- * С ведущей иконкой блик идёт сплошняком «иконка → конец строки». Иконка и текст
119
- * читают одну координату блика `--ai-shimmer-x` (в пикселях строки), поэтому полоса
120
- * не перезапускается на стыке. Вертикальный рост радиала не нужен — кейс однострочный.
121
- */
122
- .root[data-has-icon] {
123
- .shimmerText,
124
- .shimmerIcon {
125
- background-position:
126
- var(--ai-shimmer-x) 0,
127
- 0 0;
128
- background-size:
129
- $spread-width var(--ai-shimmer-spread-start-height),
130
- 100% 100%;
131
- animation-name: shimmer-line-move;
167
+ // Гасим движение по WCAG 2.3.3: волна снимается, остаётся ровная заливка базой.
168
+ @media (prefers-reduced-motion: reduce) {
169
+ .text,
170
+ .lead,
171
+ .leadIcon,
172
+ .slot {
173
+ animation: none;
132
174
  }
133
- }
134
175
 
135
- @keyframes shimmer-text-move {
136
- 0% {
137
- background-position:
138
- $spread-start-left 0,
139
- 0 0;
140
- background-size:
141
- $spread-width var(--ai-shimmer-spread-start-height),
142
- 100% 100%;
176
+ .text,
177
+ .lead {
178
+ background-image: linear-gradient(
179
+ base.$sn-theme-color-available-version-textSecondary,
180
+ base.$sn-theme-color-available-version-textSecondary
181
+ );
143
182
  }
144
183
 
145
- 50% {
146
- background-position:
147
- $spread-end-left 0,
148
- 0 0;
149
- background-size:
150
- $spread-width var(--ai-shimmer-spread-end-height),
151
- 100% 100%;
184
+ .slot {
185
+ background-image: linear-gradient(
186
+ base.$sn-theme-color-available-version-textTertiary,
187
+ base.$sn-theme-color-available-version-textTertiary
188
+ );
152
189
  }
153
190
 
154
- 100% {
155
- background-position:
156
- $spread-end-left 0,
157
- 0 0;
158
- background-size:
159
- $spread-width var(--ai-shimmer-spread-end-height),
160
- 100% 100%;
191
+ .leadWave {
192
+ display: none;
161
193
  }
162
194
  }
163
195
 
164
- @keyframes shimmer-line-move {
165
- 0% {
166
- --ai-shimmer-x: #{$spread-start-left};
196
+ // В режиме высокой контрастности `color: transparent` спрятал бы текст целиком.
197
+ @media (forced-colors: active) {
198
+ .text,
199
+ .slot {
200
+ color: CanvasText;
201
+ background-image: none;
202
+ animation: none;
167
203
  }
168
204
 
169
- 50%,
170
- 100% {
171
- --ai-shimmer-x: calc(var(--ai-shimmer-line-width, #{$default-line-width}) + 124px);
205
+ .lead {
206
+ background-color: CanvasText;
207
+ background-image: none;
208
+ animation: none;
209
+ }
210
+
211
+ .leadIcon {
212
+ animation: none;
213
+ }
214
+
215
+ .leadBase {
216
+ fill: CanvasText;
217
+ }
218
+
219
+ .leadWave {
220
+ display: none;
172
221
  }
173
222
  }
package/src/types.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  import { WithSupportProps } from '@cloud-ru/ds-utils';
2
+ import { ReactNode } from 'react';
2
3
 
3
4
  export type AiShimmerVariant = 'display' | 'headline' | 'title' | 'label' | 'body';
4
5
 
@@ -6,12 +7,6 @@ export type AiShimmerSize = 's' | 'm' | 'l';
6
7
 
7
8
  export type AiShimmerWeight = 'regular' | 'thin' | 'mono';
8
9
 
9
- export type AiShimmerFontMetrics = {
10
- fontSize: number;
11
- lineHeight: number;
12
- fontWeight: string;
13
- };
14
-
15
10
  export type AiShimmerProps = WithSupportProps<{
16
11
  /** Текст, по которому рендерится shimmer. Поддерживает переносы строк через `\n`. */
17
12
  text: string;
@@ -24,16 +19,25 @@ export type AiShimmerProps = WithSupportProps<{
24
19
  size?: AiShimmerSize;
25
20
  /** Начертание шрифта, как в `@cloud-ru/ds-typography`. Задаёт `data-weight`. */
26
21
  weight?: AiShimmerWeight;
22
+ /**
23
+ * Ведущая иконка узлом — любой компонент, рендерящий `<svg>`: иконка из `@cloud-ru/ds-icons`,
24
+ * `AiIconGiga`, `Sun` из `@cloud-ru/ds-loader`. Узел становится маской и заливается той же волной,
25
+ * что текст; его собственные цвета не важны, анимация внутри иконки сохраняется. Размер
26
+ * узла должен совпадать с `iconSize`. Имеет приоритет над `iconMask`.
27
+ */
28
+ icon?: ReactNode;
27
29
  /**
28
30
  * Силуэт ведущей иконки как CSS `mask-image` (обычно `url("data:image/svg+xml,…")`).
29
- * Если задан — перед текстом рисуется иконка, залитая тем же бегущим градиентом,
30
- * что и текст: блеск проходит сплошной полосой «иконка → конец строки», как будто
31
- * иконка — часть текста. Иконка не несёт собственного цвета, она наследует
32
- * shimmer-покрытие (приглушённая база + блик).
31
+ * Заливается той же волной, что текст. Используется, когда `icon` не передан.
33
32
  */
34
33
  iconMask?: string;
35
- /** Размер ведущей иконки в px (квадрат). Действует только с `iconMask`. По умолчанию `16`. */
34
+ /** Размер ведущей иконки в px (квадрат). Действует с `icon` или `iconMask`. По умолчанию `16`. */
36
35
  iconSize?: number;
36
+ /**
37
+ * Хвостовой слот справа от текста — например счётчик или длительность. Волна идёт
38
+ * по нему той же полосой; база слота на тон светлее текста. Свой цвет слоту не задавать.
39
+ */
40
+ slotAfter?: ReactNode;
37
41
  /** Дополнительный класс корневого контейнера. */
38
42
  className?: string;
39
43
  }>;