@codecademy/styleguide 79.2.2-alpha.e93e89.0 → 79.2.3-alpha.4b2908.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.
@@ -3,8 +3,9 @@ import * as React from 'react';
3
3
  import styled from '@emotion/styled';
4
4
 
5
5
  interface ImageWrapperProps {
6
- src: string;
7
6
  alt: string;
7
+ height: number | string;
8
+ src: string;
8
9
  }
9
10
 
10
11
  const StyledImage = styled.img`
@@ -15,12 +16,13 @@ const StyledImage = styled.img`
15
16
  export const ImageWrapper: React.FC<ImageWrapperProps & BoxProps> = ({
16
17
  src,
17
18
  alt,
19
+ height = '216px',
18
20
  ...props
19
21
  }) => {
20
22
  return (
21
23
  <Box
22
24
  width={'100%'}
23
- height="216px"
25
+ height={height}
24
26
  display="flex"
25
27
  justifyContent={'center'}
26
28
  alignItems="center"
package/CHANGELOG.md CHANGED
@@ -3,10 +3,16 @@
3
3
  All notable changes to this project will be documented in this file.
4
4
  See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
5
5
 
6
- ### [79.2.2-alpha.e93e89.0](https://github.com/Codecademy/gamut/compare/@codecademy/styleguide@79.2.1...@codecademy/styleguide@79.2.2-alpha.e93e89.0) (2026-03-18)
6
+ ### [79.2.3-alpha.4b2908.0](https://github.com/Codecademy/gamut/compare/@codecademy/styleguide@79.2.2...@codecademy/styleguide@79.2.3-alpha.4b2908.0) (2026-03-19)
7
7
 
8
8
  **Note:** Version bump only for package @codecademy/styleguide
9
9
 
10
+ ### [79.2.2](https://github.com/Codecademy/gamut/compare/@codecademy/styleguide@79.2.1...@codecademy/styleguide@79.2.2) (2026-03-19)
11
+
12
+ ### Bug Fixes
13
+
14
+ - **DataList:** Padding on first column and alignment for headers ([1b55acd](https://github.com/Codecademy/gamut/commit/1b55acdaba8c33be5e3cc7a19b0c9a3b50987ab5))
15
+
10
16
  ### [79.2.1](https://github.com/Codecademy/gamut/compare/@codecademy/styleguide@79.2.0...@codecademy/styleguide@79.2.1) (2026-03-17)
11
17
 
12
18
  ### Bug Fixes
package/package.json CHANGED
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "@codecademy/styleguide",
3
3
  "description": "Styleguide & Component library for codecademy.com",
4
- "version": "79.2.2-alpha.e93e89.0",
4
+ "version": "79.2.3-alpha.4b2908.0",
5
5
  "author": "Codecademy Engineering",
6
6
  "license": "MIT",
7
7
  "publishConfig": {
8
8
  "access": "public"
9
9
  },
10
10
  "repository": "git@github.com:Codecademy/gamut.git",
11
- "gitHead": "597c47b90e8bb7ebae7c00c214c0ef0887bcb8a5"
11
+ "gitHead": "b0054c3c7f2cee0410654e90f19ca350388a30f0"
12
12
  }
@@ -11,7 +11,7 @@ export const parameters = {
11
11
  type: 'figma',
12
12
  url: 'https://www.figma.com/file/ReGfRNillGABAj5SlITalN/branch/ayKNSg6QvZUjsgw0FFysW4/%F0%9F%93%90-Gamut?type=design&node-id=41538-55277&mode=design&t=fGkWf5GSl5cj5fQo-0',
13
13
  },
14
- status: 'updating',
14
+ status: 'current',
15
15
  source: {
16
16
  repo: 'gamut',
17
17
  githubLink:
@@ -0,0 +1,484 @@
1
+ import { Canvas, Controls, Meta } from '@storybook/blocks';
2
+
3
+ import {
4
+ Callout,
5
+ ComponentHeader,
6
+ ImageWrapper,
7
+ LinkTo,
8
+ } from '~styleguide/blocks';
9
+
10
+ import * as BarChartStories from './BarChart.stories';
11
+
12
+ export const parameters = {
13
+ title: 'BarChart',
14
+ subtitle: `A horizontal bar chart for visualizing comparative data`,
15
+ design: {
16
+ type: 'figma',
17
+ url: 'https://www.figma.com/design/ReGfRNillGABAj5SlITalN/%F0%9F%93%90-Gamut?node-id=55123-4176',
18
+ },
19
+ status: 'current',
20
+ source: {
21
+ repo: 'gamut',
22
+ githubLink:
23
+ 'https://github.com/Codecademy/gamut/blob/main/packages/gamut/src/BarChart',
24
+ },
25
+ };
26
+
27
+ <Meta of={BarChartStories} />
28
+
29
+ <ComponentHeader {...parameters} />
30
+
31
+ ## Usage
32
+
33
+ Use `BarChart` to display comparative data across categories, such as skills progress, XP earned, or any quantitative metrics that benefit from visual comparison.
34
+
35
+ ### Best practices:
36
+
37
+ - Use consistent units across all bars in a chart
38
+ - Limit the number of bars to maintain readability (5-10 is optimal)
39
+ - Consider using the stacked variant to show progress toward a goal
40
+ - Sort bars by value (descending) when ranking is important
41
+ - Ensure bar colors maintain at least a 3:1 contrast ratio with the background
42
+
43
+ ### When NOT to use:
44
+
45
+ - **Progress tracking** – for displaying the completion status of a task, use the <LinkTo id="Atoms/ProgressBar">ProgressBar</LinkTo> component.
46
+
47
+ ## Anatomy
48
+
49
+ <ImageWrapper
50
+ alt="The anatomy of the BarChart component, detailed below."
51
+ height="auto"
52
+ src="./organisms/barchart.png"
53
+ />
54
+
55
+ 1. **Bar row**
56
+
57
+ - Represents a single category and its values.
58
+
59
+ 2. **Category icon** (optional)
60
+
61
+ - Use to clarify or reinforce the category name.
62
+
63
+ 3. **Category label**
64
+
65
+ - Displays the category name on the y-axis (e.g. skill or metric name).
66
+
67
+ 4. **Scale / value axis**
68
+
69
+ - Displays gridlines and labels to indicate the scale of the data values.
70
+ - The number of dividers, as well as the minimum and maximum values on the value axis, are adjustable.
71
+ - The minimum value should always be 0.
72
+
73
+ 5. **Series one value**
74
+
75
+ - Displays the numerical value of the series one bar for clarity and precise data representation.
76
+
77
+ 6. **Series two value** (optional)
78
+
79
+ - Displays the numerical value of the series two bar for clarity and precise data representation.
80
+ - Include a second series value by using the stacked property. Stacked bar charts compare parts of a whole and are best suited for displaying discrete data segmented into meaningful categories.
81
+
82
+ 7. **Series one bar**
83
+
84
+ - A visual representation of the first value for the associated category.
85
+ - By default, the first series bars use the text color, however, it can be overridden to any color.
86
+ - Bars include a required border that uses white or navy, chosen automatically to ensure the highest contrast with the bar color.
87
+
88
+ 8. **Series two bar** _(bars with zero value)_
89
+
90
+ - A visual representation of the second value for the associated category.
91
+ - By default, the second series bars use the primary color, however, it can be overridden to any color.
92
+ - Bars include a required border that uses white or navy, chosen automatically to ensure the highest contrast with the bar color.
93
+
94
+ ## Variants
95
+
96
+ ### Simple (Non-stacked)
97
+
98
+ Use the simple variant when showing single values per category. Only `seriesOneValue` is provided.
99
+
100
+ <Canvas of={BarChartStories.Default} />
101
+
102
+ ### Stacked
103
+
104
+ Use the stacked variant when showing progress within a total. Provide both `seriesOneValue` (progress) and `seriesTwoValue` (total).
105
+
106
+ <Canvas of={BarChartStories.Stacked} />
107
+
108
+ ### With Icons
109
+
110
+ Add icons to labels for better visual identification of categories.
111
+
112
+ <Canvas of={BarChartStories.WithIcons} />
113
+
114
+ ### Animated
115
+
116
+ Enable entrance animations for a more engaging experience.
117
+
118
+ <Canvas of={BarChartStories.Animated} />
119
+
120
+ ### Interactive
121
+
122
+ Rows can be made interactive with `onClick` handlers or `href` links.
123
+
124
+ <Canvas of={BarChartStories.Interactive} />
125
+
126
+ ### With Links
127
+
128
+ When a bar has an `href` link, an `aria-label` is automatically generated from the bar's data and applied to the anchor. The label summarizes the bar's values (e.g., "100 XP in Python" for a simple bar, or "200 XP gained - now at 1500 XP in Python" for a stacked bar), so screen reader users get a clear, data-driven description without manual `aria-label` props.
129
+
130
+ <Canvas of={BarChartStories.WithLinks} />
131
+
132
+ ## Title and description
133
+
134
+ The BarChart component uses semantic HTML to provide context and accessibility. The chart is wrapped in a [`<figure>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/figure) element, and the description is displayed in a [`<figcaption>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/figcaption) element. This semantic structure helps screen readers and other assistive technologies understand the relationship between the chart and its description. **Visual title + description is the greatly preferred pattern** for accessibility and user experience.
135
+
136
+ **Preferred pattern: Visual title + description**
137
+
138
+ Provide both `title` and `description` props to make the chart's purpose and key takeaways clear to all users:
139
+
140
+ - `title`: A heading that identifies the chart. Can be a string or an object with `{ as?: 'h1' | 'h2' | 'h3' | 'h4' | 'h5' | 'h6', title: string, variant?: Text['variant'] }` to specify the heading level and optionally override the default styling with a <LinkTo id="Typography/Text">Text variant</LinkTo>.
141
+ - `description`: A summary of the information or the overall takeaway displayed in the `<figcaption>` element.
142
+
143
+ <Canvas of={BarChartStories.WithVisualTitleAndDescription} />
144
+
145
+ **Alternative patterns:**
146
+ `hideTitle` and `hideDescription` will keep the screenreader text but hide the visual descriptions.
147
+
148
+ <Canvas of={BarChartStories.WithHiddenTitleAndDescription} />
149
+
150
+ **External title with visual description:** Use `aria-labelledby` for the title when the title exists elsewhere but you want to display the description.
151
+
152
+ <Canvas of={BarChartStories.WithExternalTitle} />
153
+
154
+ **Best practices:**
155
+
156
+ - Always provide a `description` prop - it's required and should summarize the chart's key information
157
+ - Use semantic heading levels for titles (h1-h6) to maintain proper document structure
158
+ - When using `aria-labelledby`, ensure the referenced element exists and is properly labeled
159
+
160
+ ## Sorting
161
+
162
+ BarChart includes an optional sorting dropdown in the title area. The dropdown only renders when the `sortFns` prop is provided. You can control which sort options appear by including string literals or custom sort functions in the array.
163
+
164
+ **String Literals:**
165
+
166
+ - `'alphabetically'` - Adds both "Label (A-Z)" and "Label (Z-A)" options
167
+ - `'numerically'` - Adds both "Value (Low-High)" and "Value (High-Low)" options
168
+ - `'none'` - Adds "None" option (preserves original order)
169
+
170
+ **Custom Sort Functions:**
171
+ You can also provide custom sort functions as objects with:
172
+
173
+ - `label`: The text displayed in the dropdown
174
+ - `value`: A unique identifier for the sort option
175
+ - `sortFn`: A function that takes an array of bars and returns a sorted array
176
+
177
+ **Type Definition:**
178
+
179
+ ```typescript
180
+ type CustomSortOption<TBar extends BarProps = BarProps> = {
181
+ label: string;
182
+ value: string;
183
+ sortFn: (bars: TBar[]) => TBar[];
184
+ };
185
+
186
+ // sortFns prop accepts:
187
+ sortFns?: ('alphabetically' | 'numerically' | 'none' | CustomSortOption<TBar>)[]
188
+ ```
189
+
190
+ **Automatic Type Inference:**
191
+ TypeScript automatically infers the bar type from your `barValues` prop. This means custom properties (like `dateAdded`, `category`, etc.) are automatically typed in your sort functions - no type assertions needed!
192
+
193
+ ```typescript
194
+ const barsWithDates = [
195
+ {
196
+ categoryLabel: 'Python',
197
+ seriesOneValue: 1500,
198
+ dateAdded: new Date('2023-01-15'),
199
+ },
200
+ {
201
+ categoryLabel: 'JavaScript',
202
+ seriesOneValue: 2000,
203
+ dateAdded: new Date('2023-03-20'),
204
+ },
205
+ // ...
206
+ ];
207
+
208
+ <BarChart
209
+ barValues={barsWithDates}
210
+ sortFns={[
211
+ {
212
+ label: 'Recently Added',
213
+ value: 'recent',
214
+ sortFn: (bars) => {
215
+ // TypeScript automatically knows bars have dateAdded property!
216
+ return [...bars].sort((a, b) => {
217
+ const aDate = a.dateAdded as Date | undefined;
218
+ const bDate = b.dateAdded as Date | undefined;
219
+ if (!aDate || !bDate) return 0;
220
+ return bDate.getTime() - aDate.getTime();
221
+ });
222
+ },
223
+ },
224
+ ]}
225
+ />;
226
+ ```
227
+
228
+ **Note:** Since `BarProps` uses `Record<string, unknown>` for extensibility, custom properties are typed as `unknown` by default. You may need a simple type assertion (`as Date | undefined`) when accessing them, but the property names are fully type-checked.
229
+
230
+ <Canvas of={BarChartStories.WithSorting} />
231
+
232
+ **Example with Custom Sort Functions:**
233
+
234
+ Custom sort functions can access additional properties on `BarProps` for domain-specific sorting, such as sorting by dates or categories.
235
+
236
+ <Canvas of={BarChartStories.WithCustomSorting} />
237
+
238
+ ## Custom styling
239
+
240
+ BarChart supports custom color styling through the `styleConfig` prop, allowing you to customize the appearance of chart elements to match your design needs.
241
+
242
+ ### Style configuration options
243
+
244
+ The `styleConfig` prop accepts an object with the following optional properties:
245
+
246
+ - **`textColor`**: Color for text labels (y-axis labels). Defaults to `'text'`
247
+ - **`seriesOneBarColor`**: Color for the series one bar (seriesOneValue: overlay in stacked charts, only bar in simple charts). Defaults to `'text'`
248
+ - **`seriesTwoBarColor`**: Color for the series two bar (seriesTwoValue: full bar in stacked charts; unused in simple charts). Defaults to `'primary'`
249
+ - **`seriesOneLabel`**: Color for the series one value label (first right label when stacked, or displayValue when not stacked). Defaults to `'text-secondary'`
250
+ - **`seriesTwoLabel`**: Color for the series two value label (displayValue when stacked). Defaults to `'primary'`
251
+
252
+ All color values should be valid color tokens from the Gamut design system. When customizing colors, ensure they maintain at least a 3:1 contrast ratio with the background for accessibility.
253
+
254
+ ### Default values
255
+
256
+ If `styleConfig` is not provided, BarChart uses these default colors:
257
+
258
+ ```typescript
259
+ {
260
+ textColor: 'text',
261
+ seriesOneBarColor: 'text',
262
+ seriesTwoBarColor: 'primary',
263
+ seriesOneLabel: 'text-secondary',
264
+ seriesTwoLabel: 'primary',
265
+ }
266
+ ```
267
+
268
+ ### Example
269
+
270
+ <Canvas of={BarChartStories.CustomStyles} />
271
+
272
+ ## Custom scale
273
+
274
+ BarChart allows you to customize the x-axis scale interval using the `scaleInterval` prop, which controls the spacing and granularity of scale markers along the horizontal axis.
275
+
276
+ ### Scale configuration
277
+
278
+ The `scaleInterval` prop determines the interval between scale markers on the x-axis. By default, BarChart automatically calculates an appropriate scale interval based on the `maxScaleValue` value (the scale always starts at 0). However, you can override this with a custom interval to achieve more granular or specific scale markings.
279
+
280
+ **When to use custom scale:**
281
+
282
+ - When you need specific scale intervals (e.g., increments of 250, 500, or 1000)
283
+ - When the automatic scale calculation doesn't provide the desired granularity
284
+ - When you want to match scale intervals across multiple charts for consistency
285
+ - When you need scale markers at specific values for better data interpretation
286
+
287
+ **How it works:**
288
+
289
+ The `scaleInterval` value represents the interval between consecutive scale markers. For example:
290
+
291
+ - `scaleInterval: 250` creates markers at 0, 250, 500, 750, 1000, etc.
292
+ - `scaleInterval: 500` creates markers at 0, 500, 1000, 1500, 2000, etc.
293
+
294
+ The number of tick marks is automatically calculated as: `Math.ceil(maxScaleValue / scaleInterval) + 1`
295
+
296
+ ### Example
297
+
298
+ <Canvas of={BarChartStories.CustomScale} />
299
+
300
+ ## Color modes
301
+
302
+ BarChart automatically adapts to both light and dark color modes, ensuring proper contrast and readability in all themes. The component uses semantic color tokens that adjust based on the current color mode. The `styleConfig` prop should be provided by semantic color tokens to ensure the `BarChart` is accessible in all color modes.
303
+
304
+ ## Accessibility considerations
305
+
306
+ ### Chart and row labeling
307
+
308
+ **Chart-level labeling:**
309
+
310
+ - Always provide either `title` or `aria-labelledby` to describe the chart (see Title and description section below for details)
311
+ - The chart is wrapped in a semantic `<figure>` element for proper structure
312
+
313
+ **Row-level labeling:**
314
+
315
+ - For non-interactive bars: A hidden text element (visible only to screen readers) is automatically added as the first child of each list item, summarizing the bar's values (e.g., "100 XP in Python")
316
+ - For interactive bars (with `onClick` or `href`): An `aria-label` is automatically generated from the bar's data and applied to the button or link element, ensuring proper screen reader announcements
317
+ - All accessibility labels are automatically generated from the bar's data - no manual `aria-label` props are required
318
+
319
+ ## UX writing
320
+
321
+ - Keep y-axis labels concise (1-3 words)
322
+ - Use consistent unit labels (e.g., "XP", "hours", "points")
323
+ - Consider locale-aware number formatting for international audiences
324
+
325
+ ## Interactive states
326
+
327
+ BarChart supports both interactive and static bar rows, each with distinct visual states.
328
+
329
+ ### Static bars
330
+
331
+ When bars have neither `onClick` handlers nor `href` links, they are rendered as static, non-interactive elements.
332
+
333
+ <Canvas of={BarChartStories.Default} />
334
+
335
+ ### Interactive bars
336
+
337
+ When bars have `onClick` handlers or `href` links, they become interactive. Interactive bars are rendered as buttons or anchor elements, providing full keyboard accessibility and proper semantic HTML.
338
+
339
+ <Canvas of={BarChartStories.Interactive} />
340
+
341
+ ## Internationalization
342
+
343
+ <Callout text="We are currently updating global internationalization in Gamut, so the following features are subject to change." />
344
+
345
+ BarChart supports internationalization through the `translations` prop. You can customize user-facing strings (including sort dropdown and accessibility summaries) and configure locale-aware number formatting. The prop accepts `PartialBarChartTranslations`: override only the keys you need; nested `accessibility` and `sortOptions` are merged with defaults at runtime.
346
+
347
+ ### Translation structure
348
+
349
+ - **sortLabel**, **sortOptions**, and **locale** — Always strings. Control the sort dropdown label, option labels, and number-formatting locale.
350
+ - **Accessibility** — Two optional summary functions; when omitted, default English summaries are used. Each function receives context and returns the full summary string.
351
+ - **stackedBarSummary** — Used for stacked (two-value) rows. Context includes `seriesOneValue`, `seriesTwoValue`, **gained** (seriesTwoValue - seriesOneValue), `unit`, `locale`, `categoryLabel`.
352
+ - **singleValueBarSummary** — Used for all single-value rows. Context includes `value`, `unit`, `locale`, `categoryLabel`.
353
+
354
+ ### Where accessibility summaries appear
355
+
356
+ Each bar row gets one summary from either `stackedBarSummary` (stacked rows) or `singleValueBarSummary` (single-value rows). That string is then exposed as **`aria-label`** on the row's link or button when the row is interactive, or as **screenreader-only text** (visually hidden) when the row is not interactive.
357
+
358
+ <table>
359
+ <thead>
360
+ <tr>
361
+ <th>Key</th>
362
+ <th>Used for</th>
363
+ <th>Context (props)</th>
364
+ <th>Default English interpolation</th>
365
+ <th>Summary exposed as</th>
366
+ </tr>
367
+ </thead>
368
+ <tbody>
369
+ <tr>
370
+ <td>
371
+ <code>stackedBarSummary</code>
372
+ </td>
373
+ <td>Stacked rows (two values per row)</td>
374
+ <td>
375
+ <code>seriesOneValue</code>, <code>seriesTwoValue</code>,{' '}
376
+ <code>gained</code>, <code>unit</code>, <code>locale</code>,{' '}
377
+ <code>categoryLabel</code>
378
+ </td>
379
+ <td>
380
+ <code>
381
+ Starting value - &#123;seriesOneValue&#125;&#123;unit&#125;.
382
+ &#123;gained&#125;&#123;unit&#125; gained - now at
383
+ &#123;seriesTwoValue&#125;&#123;unit&#125; in
384
+ &#123;categoryLabel&#125;
385
+ </code>
386
+ </td>
387
+ <td>
388
+ <code>aria-label</code> (if link/button) or screenreader-only text
389
+ </td>
390
+ </tr>
391
+ <tr>
392
+ <td>
393
+ <code>singleValueBarSummary</code>
394
+ </td>
395
+ <td>Single-value rows</td>
396
+ <td>
397
+ <code>value</code>, <code>unit</code>, <code>locale</code>,{' '}
398
+ <code>categoryLabel</code>
399
+ </td>
400
+ <td>
401
+ <code>
402
+ &#123;value&#125;&#123;unit&#125; in &#123;categoryLabel&#125;
403
+ </code>
404
+ </td>
405
+ <td>
406
+ <code>aria-label</code> (if link/button) or screenreader-only text
407
+ </td>
408
+ </tr>
409
+ </tbody>
410
+ </table>
411
+
412
+ ### Basic usage
413
+
414
+ Provide only the translations you want to override; the rest fall back to default English.
415
+
416
+ ```tsx
417
+ <BarChart
418
+ barValues={barData}
419
+ description="Progreso de habilidades"
420
+ maxScaleValue={200}
421
+ sortFns={['alphabetically', 'none']}
422
+ title="Habilidades"
423
+ translations={{
424
+ accessibility: {
425
+ stackedBarSummary: (ctx) =>
426
+ `Valor inicial - ${ctx.seriesOneValue} ${ctx.unit}. ${ctx.gained} ${ctx.unit} ganado - ahora en ${ctx.seriesTwoValue} ${ctx.unit} en ${ctx.categoryLabel}`,
427
+ singleValueBarSummary: (ctx) =>
428
+ `${ctx.value} ${ctx.unit} en ${ctx.categoryLabel}`,
429
+ },
430
+ locale: 'es',
431
+ sortLabel: 'Ordenar por:',
432
+ sortOptions: {
433
+ labelAsc: 'Etiqueta (A-Z)',
434
+ labelDesc: 'Etiqueta (Z-A)',
435
+ none: 'Ninguno',
436
+ valueAsc: 'Valor (Bajo-Alto)',
437
+ valueDesc: 'Valor (Alto-Bajo)',
438
+ },
439
+ }}
440
+ />
441
+ ```
442
+
443
+ <Canvas of={BarChartStories.WithStringTranslations} />
444
+
445
+ ### Partial translations and locale
446
+
447
+ You can override a single key; the rest keep their defaults. The **locale** property controls number formatting (scale labels, value labels) via `Intl.NumberFormat`:
448
+
449
+ ```tsx
450
+ // Only change locale; sort and accessibility use defaults
451
+ translations={{ locale: 'de-DE' }}
452
+
453
+ // Override just sort label and locale
454
+ translations={{
455
+ locale: 'en-GB',
456
+ sortLabel: 'Sort by:',
457
+ }}
458
+ ```
459
+
460
+ <Canvas of={BarChartStories.WithFunctionTranslations} />
461
+
462
+ **Best practices:**
463
+
464
+ - Provide summary functions for the locales your app uses; use default behavior when the default English is acceptable.
465
+ - Use appropriate locale codes (e.g. `'en-US'`, `'es-ES'`, `'fr-FR'`) for number formatting.
466
+ - Test accessibility summaries with screen readers in the target language.
467
+ - Reuse translation objects across BarChart instances where possible.
468
+
469
+ ## Container query
470
+
471
+ BarChart uses CSS container queries to determine responsive behavior based on the **chart container width** rather than viewport width. This ensures optimal display when the chart is placed in constrained layouts like sidebars or narrow columns.
472
+
473
+ **Layout behavior:**
474
+
475
+ - **Narrow container (below 480px)**: Label and value appear together above the bar in a single row.
476
+ - **Wide container (480px and up, `c_xs` breakpoint)**: Label on the left, bar in the center, value on the right.
477
+
478
+ The chart establishes a size container via `containerType="inline-size"` on the figure wrapper, so the layout responds to the width of the BarChart’s parent. For more on container queries in Gamut, see <LinkTo id="Foundations/System/Responsive Properties">Responsive properties</LinkTo>.
479
+
480
+ ## Playground
481
+
482
+ <Canvas sourceState="shown" of={BarChartStories.Default} />
483
+
484
+ <Controls />
@@ -0,0 +1,352 @@
1
+ import {
2
+ BarChart,
3
+ BarProps,
4
+ Box,
5
+ PartialBarChartTranslations,
6
+ } from '@codecademy/gamut';
7
+ import {
8
+ BookFlipPageIcon,
9
+ DataScienceIcon,
10
+ TerminalIcon,
11
+ } from '@codecademy/gamut-icons';
12
+ import { action } from '@storybook/addon-actions';
13
+ import type { Meta, StoryObj } from '@storybook/react';
14
+
15
+ const meta: Meta<typeof BarChart> = {
16
+ component: BarChart,
17
+ args: {
18
+ description: 'Chart showing programming language experience levels',
19
+ maxScaleValue: 2000,
20
+ title: 'Skills experience chart',
21
+ unit: 'XP',
22
+ },
23
+ };
24
+
25
+ export default meta;
26
+ type Story = StoryObj<typeof BarChart>;
27
+
28
+ const simpleBarData: BarProps[] = [
29
+ { categoryLabel: 'Python', seriesOneValue: 1500 },
30
+ { categoryLabel: 'JavaScript', seriesOneValue: 2000 },
31
+ { categoryLabel: 'HTML/CSS', seriesOneValue: 800 },
32
+ { categoryLabel: 'SQL', seriesOneValue: 600 },
33
+ { categoryLabel: 'React', seriesOneValue: 450 },
34
+ ];
35
+
36
+ const stackedBarData: BarProps[] = [
37
+ { categoryLabel: 'Python', seriesOneValue: 200, seriesTwoValue: 1500 },
38
+ {
39
+ categoryLabel: 'JavaScript',
40
+ icon: TerminalIcon,
41
+ seriesOneValue: 1800,
42
+ seriesTwoValue: 2000,
43
+ },
44
+ { categoryLabel: 'HTML/CSS', seriesOneValue: 600, seriesTwoValue: 800 },
45
+ { categoryLabel: 'SQL', seriesOneValue: 550, seriesTwoValue: 600 },
46
+ { categoryLabel: 'React', seriesOneValue: 300, seriesTwoValue: 450 },
47
+ ];
48
+
49
+ const accessibilityBarData: BarProps[] = [
50
+ { categoryLabel: 'Python', seriesOneValue: 200, seriesTwoValue: 1500 },
51
+ {
52
+ categoryLabel: 'JavaScript',
53
+ seriesOneValue: 1800,
54
+ seriesTwoValue: 2000,
55
+ href: '/javascript',
56
+ },
57
+ { categoryLabel: 'HTML/CSS', seriesOneValue: 600, seriesTwoValue: 800 },
58
+ { categoryLabel: 'SQL', seriesOneValue: 550, href: '/sql' },
59
+ { categoryLabel: 'Rust', seriesOneValue: 400 },
60
+ { categoryLabel: 'React', seriesOneValue: 300, seriesTwoValue: 450 },
61
+ ];
62
+
63
+ const accessibilityTranslations: PartialBarChartTranslations = {
64
+ accessibility: {
65
+ stackedBarSummary: (ctx) =>
66
+ `${ctx.seriesOneValue} ${ctx.unit} gained — now at ${ctx.seriesTwoValue} ${ctx.unit} in ${ctx.categoryLabel}`,
67
+ singleValueBarSummary: (ctx) =>
68
+ `${ctx.value} ${ctx.unit} in ${ctx.categoryLabel}`,
69
+ },
70
+ locale: 'en',
71
+ };
72
+
73
+ const barDataWithIcons: BarProps[] = [
74
+ {
75
+ categoryLabel: 'Python',
76
+ seriesOneValue: 200,
77
+ seriesTwoValue: 1500,
78
+ icon: TerminalIcon,
79
+ },
80
+ {
81
+ categoryLabel: 'JavaScript',
82
+ seriesOneValue: 150,
83
+ seriesTwoValue: 2000,
84
+ icon: TerminalIcon,
85
+ },
86
+ {
87
+ categoryLabel: 'Data Science',
88
+ seriesOneValue: 100,
89
+ seriesTwoValue: 800,
90
+ icon: DataScienceIcon,
91
+ },
92
+ {
93
+ categoryLabel: 'Backend',
94
+ seriesOneValue: 50,
95
+ seriesTwoValue: 600,
96
+ icon: TerminalIcon,
97
+ },
98
+ {
99
+ categoryLabel: 'Reading',
100
+ seriesOneValue: 75,
101
+ seriesTwoValue: 450,
102
+ icon: BookFlipPageIcon,
103
+ },
104
+ ];
105
+
106
+ export const Default: Story = {
107
+ args: {
108
+ barValues: simpleBarData,
109
+ title: 'Skills experience chart',
110
+ description: 'Chart showing programming language experience levels',
111
+ },
112
+ };
113
+
114
+ export const Stacked: Story = {
115
+ args: {
116
+ barValues: stackedBarData,
117
+ title: 'Skills progress chart',
118
+ description: 'Progress toward total goals for each programming language',
119
+ },
120
+ };
121
+
122
+ export const WithIcons: Story = {
123
+ args: {
124
+ barValues: barDataWithIcons,
125
+ title: 'Skills progress with icons',
126
+ description: 'Skills progress with visual icons for each category',
127
+ },
128
+ };
129
+
130
+ export const Animated: Story = {
131
+ args: {
132
+ barValues: stackedBarData,
133
+ animate: true,
134
+ title: 'Animated skills chart',
135
+ description: 'Animated chart showing progress with entrance animations',
136
+ },
137
+ };
138
+
139
+ export const Interactive: Story = {
140
+ args: {
141
+ barValues: simpleBarData.map((bar) => ({
142
+ ...bar,
143
+ onClick: action(`Clicked ${bar.categoryLabel}`),
144
+ })),
145
+ title: 'Interactive skills chart',
146
+ description: 'Click on any row to view detailed course information',
147
+ },
148
+ };
149
+
150
+ export const WithLinks: Story = {
151
+ args: {
152
+ barValues: simpleBarData.map((bar) => ({
153
+ ...bar,
154
+ href: `#${bar.categoryLabel.toLowerCase().replace(/\s+/g, '-')}`,
155
+ })),
156
+ title: 'Skills chart with links',
157
+ description: 'Each row links to its corresponding course page',
158
+ },
159
+ };
160
+
161
+ export const WithVisualTitleAndDescription: Story = {
162
+ args: {
163
+ barValues: simpleBarData,
164
+ title: 'Programming Skills Overview',
165
+ description:
166
+ 'Experience points earned across different programming languages',
167
+ },
168
+ };
169
+
170
+ export const WithHiddenTitleAndDescription: Story = {
171
+ render: () => {
172
+ return (
173
+ <BarChart
174
+ barValues={simpleBarData}
175
+ description="Experience points earned across different programming languages"
176
+ hideDescription
177
+ hideTitle
178
+ maxScaleValue={2000}
179
+ title="Programming Skills Overview"
180
+ unit="XP"
181
+ />
182
+ );
183
+ },
184
+ };
185
+
186
+ export const WithExternalTitle: Story = {
187
+ render: () => {
188
+ return (
189
+ <>
190
+ <Box
191
+ as="h2"
192
+ bg="background-selected"
193
+ border={1}
194
+ borderRadius="lg"
195
+ id="external-chart-title"
196
+ p={16}
197
+ textAlign="right"
198
+ >
199
+ Programming Skills Overview
200
+ </Box>
201
+ <BarChart
202
+ aria-labelledby="external-chart-title"
203
+ barValues={simpleBarData}
204
+ description="Experience points earned across different programming languages"
205
+ hideDescription={false}
206
+ maxScaleValue={2000}
207
+ unit="XP"
208
+ />
209
+ </>
210
+ );
211
+ },
212
+ };
213
+
214
+ export const WithSorting: Story = {
215
+ args: {
216
+ barValues: simpleBarData,
217
+ sortFns: ['alphabetically', 'numerically', 'none'],
218
+ title: 'Skills experience chart',
219
+ description: 'Use the dropdown to sort bars by different criteria',
220
+ },
221
+ };
222
+
223
+ const customSortingBarValues = [
224
+ {
225
+ categoryLabel: 'Python',
226
+ seriesOneValue: 1500,
227
+ dateAdded: new Date('2023-01-15'),
228
+ },
229
+ {
230
+ categoryLabel: 'JavaScript',
231
+ seriesOneValue: 2000,
232
+ dateAdded: new Date('2023-03-20'),
233
+ },
234
+ {
235
+ categoryLabel: 'React',
236
+ seriesOneValue: 450,
237
+ dateAdded: new Date('2023-06-10'),
238
+ },
239
+ {
240
+ categoryLabel: 'TypeScript',
241
+ seriesOneValue: 300,
242
+ dateAdded: new Date('2023-08-05'),
243
+ },
244
+ {
245
+ categoryLabel: 'SQL',
246
+ seriesOneValue: 600,
247
+ dateAdded: new Date('2023-02-28'),
248
+ },
249
+ ];
250
+
251
+ export const WithCustomSorting: Story = {
252
+ args: {
253
+ barValues: customSortingBarValues,
254
+ sortFns: [
255
+ 'none',
256
+ {
257
+ label: 'Recently Added',
258
+ value: 'recent',
259
+ sortFn: (bars) => {
260
+ return [...bars].sort((a, b) => {
261
+ const aDate = a.dateAdded as Date | undefined;
262
+ const bDate = b.dateAdded as Date | undefined;
263
+ if (!aDate && !bDate) return 0;
264
+ if (!aDate) return 1;
265
+ if (!bDate) return -1;
266
+ return bDate.getTime() - aDate.getTime();
267
+ });
268
+ },
269
+ },
270
+ {
271
+ label: 'Oldest First',
272
+ value: 'oldest',
273
+ sortFn: (bars) => {
274
+ return [...bars].sort((a, b) => {
275
+ const aDate = a.dateAdded as Date | undefined;
276
+ const bDate = b.dateAdded as Date | undefined;
277
+ if (!aDate && !bDate) return 0;
278
+ if (!aDate) return 1;
279
+ if (!bDate) return -1;
280
+ return aDate.getTime() - bDate.getTime();
281
+ });
282
+ },
283
+ },
284
+ ],
285
+ title: 'Skills chart with date sorting',
286
+ description:
287
+ 'Custom sort functions can access additional properties on BarProps, such as dates',
288
+ },
289
+ };
290
+
291
+ export const CustomStyles: Story = {
292
+ args: {
293
+ barValues: stackedBarData,
294
+ styleConfig: {
295
+ seriesTwoBarColor: 'text',
296
+ seriesOneBarColor: 'primary',
297
+ textColor: 'primary',
298
+ seriesOneLabel: 'feedback-error',
299
+ seriesTwoLabel: 'feedback-success',
300
+ },
301
+ title: 'Custom styled skills chart',
302
+ description: 'Custom color scheme applied to chart elements',
303
+ },
304
+ };
305
+
306
+ export const CustomScale: Story = {
307
+ args: {
308
+ barValues: simpleBarData,
309
+ maxScaleValue: 2000,
310
+ scaleInterval: 250,
311
+ title: 'Skills chart with custom scale',
312
+ description: 'Custom scale intervals for more granular value display',
313
+ },
314
+ };
315
+
316
+ export const WithStringTranslations: Story = {
317
+ args: {
318
+ barValues: stackedBarData,
319
+ sortFns: ['alphabetically', 'numerically', 'none'],
320
+ title: 'Gráfico de habilidades',
321
+ description: 'Progreso hacia los objetivos totales por lenguaje',
322
+ unit: 'XP',
323
+ translations: {
324
+ locale: 'es',
325
+ sortLabel: 'Ordenar por:',
326
+ sortOptions: {
327
+ none: 'Ninguno',
328
+ labelAsc: 'Etiqueta (A-Z)',
329
+ labelDesc: 'Etiqueta (Z-A)',
330
+ valueAsc: 'Valor (Bajo-Alto)',
331
+ valueDesc: 'Valor (Alto-Bajo)',
332
+ },
333
+ accessibility: {
334
+ stackedBarSummary: (ctx) =>
335
+ `Valor inicial - ${ctx.seriesOneValue} ${ctx.unit}. ${ctx.gained} ${ctx.unit} ganado - ahora en ${ctx.seriesTwoValue} ${ctx.unit} en ${ctx.categoryLabel}`,
336
+ singleValueBarSummary: (ctx) =>
337
+ `${ctx.value} ${ctx.unit} en ${ctx.categoryLabel}`,
338
+ },
339
+ },
340
+ },
341
+ };
342
+
343
+ export const WithFunctionTranslations: Story = {
344
+ args: {
345
+ barValues: accessibilityBarData,
346
+ description:
347
+ 'Custom aria-label summaries via translation functions (stacked, link, and non-interactive bars)',
348
+ title: 'Skills experience (accessibility functions)',
349
+ translations: accessibilityTranslations,
350
+ unit: 'XP',
351
+ },
352
+ };
@@ -99,7 +99,7 @@ export const Table: Story = {
99
99
  export const Plain: Story = {
100
100
  args: { spacing: 'condensed', variant: 'plain' },
101
101
  render: (args) => (
102
- <Box bg="red" width={1}>
102
+ <Box width={1}>
103
103
  <ListExample {...args} />
104
104
  </Box>
105
105
  ),
@@ -1,26 +0,0 @@
1
- import { Canvas, Controls, Meta } from '@storybook/blocks';
2
-
3
- import { ComponentHeader } from '~styleguide/blocks';
4
-
5
- import * as CalendarStories from './Calendar.stories';
6
-
7
- export const parameters = {
8
- title: 'DatePicker/Calendar',
9
- subtitle: `Calendar grid with header (month/year + prev/next), body (day grid), and footer (Clear, Today, quick actions). Used inside DatePickerCalendar.`,
10
- status: 'current',
11
- source: {
12
- repo: 'gamut',
13
- githubLink:
14
- 'https://github.com/Codecademy/gamut/blob/main/packages/gamut/src/DatePicker/Calendar',
15
- },
16
- };
17
-
18
- <Meta of={CalendarStories} />
19
-
20
- <ComponentHeader {...parameters} />
21
-
22
- ## Playground
23
-
24
- <Canvas sourceState="shown" of={CalendarStories.Default} />
25
-
26
- <Controls />
@@ -1,53 +0,0 @@
1
- import {
2
- Calendar,
3
- CalendarBody,
4
- CalendarFooter,
5
- CalendarHeader,
6
- } from '@codecademy/gamut';
7
- import type { Meta, StoryObj } from '@storybook/react';
8
- import { useId, useState } from 'react';
9
-
10
- const meta: Meta<typeof Calendar> = {
11
- component: Calendar,
12
- title: 'Molecules/DatePicker/Calendar',
13
- };
14
-
15
- export default meta;
16
-
17
- type Story = StoryObj<typeof Calendar>;
18
-
19
- export const Default: Story = {
20
- render: function CalendarStory() {
21
- const headingId = useId();
22
- const [visibleDate, setVisibleDate] = useState(() => new Date());
23
- const [selectedDate, setSelectedDate] = useState<Date | null>(null);
24
- const [focusedDate, setFocusedDate] = useState<Date | null>(
25
- () => new Date()
26
- );
27
-
28
- return (
29
- <Calendar>
30
- <CalendarHeader
31
- currentMonthYear={visibleDate}
32
- headingId={headingId}
33
- locale="en-US"
34
- onCurrentMonthYearChange={setVisibleDate}
35
- />
36
- <CalendarBody
37
- focusedDate={focusedDate}
38
- labelledById={headingId}
39
- locale="en-US"
40
- selectedDate={selectedDate}
41
- visibleDate={visibleDate}
42
- onDateSelect={setSelectedDate}
43
- onFocusedDateChange={setFocusedDate}
44
- onVisibleDateChange={setVisibleDate}
45
- />
46
- <CalendarFooter
47
- onCurrentMonthYearChange={setVisibleDate}
48
- onSelectedDateChange={setSelectedDate}
49
- />
50
- </Calendar>
51
- );
52
- },
53
- };
@@ -1,122 +0,0 @@
1
- import {
2
- Box,
3
- DatePicker,
4
- DatePickerCalendar,
5
- DatePickerInput,
6
- PopoverContainer,
7
- useDatePicker,
8
- } from '@codecademy/gamut';
9
- import type { Meta, StoryObj } from '@storybook/react';
10
- import { useRef, useState } from 'react';
11
-
12
- const meta: Meta<typeof DatePicker> = {
13
- component: DatePicker,
14
- title: 'Molecules/DatePicker/DatePicker',
15
- };
16
-
17
- export default meta;
18
-
19
- type Story = StoryObj<typeof DatePicker>;
20
-
21
- export const Default: Story = {
22
- render: function DatePickerStory() {
23
- const [selectedDate, setSelectedDate] = useState<Date | null>(null);
24
- return (
25
- <Box>
26
- <DatePicker
27
- label="Date"
28
- locale="de-DE"
29
- selectedDate={selectedDate}
30
- setSelectedDate={setSelectedDate}
31
- translations={{ clear: 'Löschen' }}
32
- />
33
- </Box>
34
- );
35
- },
36
- };
37
-
38
- export const WithInitialDate: Story = {
39
- render: function DatePickerStory() {
40
- const [selectedDate, setSelectedDate] = useState<Date | null>(
41
- () => new Date(2026, 1, 15)
42
- );
43
- return (
44
- <DatePicker
45
- label="Date"
46
- selectedDate={selectedDate}
47
- setSelectedDate={setSelectedDate}
48
- />
49
- );
50
- },
51
- };
52
-
53
- /** Range mode: two inputs for start and end date. First calendar click sets start, second sets end. */
54
- export const Range: Story = {
55
- render: function DatePickerStory() {
56
- const [startDate, setStartDate] = useState<Date | null>(null);
57
- const [endDate, setEndDate] = useState<Date | null>(null);
58
- return (
59
- <Box>
60
- <DatePicker
61
- endDate={endDate}
62
- endLabel="End date"
63
- mode="range"
64
- setEndDate={setEndDate}
65
- setStartDate={setStartDate}
66
- startDate={startDate}
67
- startLabel="Start date"
68
- />
69
- </Box>
70
- );
71
- },
72
- };
73
-
74
- /**
75
- * Composed usage: DatePicker with children provides shared state via context.
76
- * The child uses useDatePicker() to get open/close and inputRef, then composes
77
- * DatePickerInput and DatePickerCalendar with a custom PopoverContainer layout.
78
- */
79
- export const ComposedWithContext: Story = {
80
- render: function DatePickerStory() {
81
- const [selectedDate, setSelectedDate] = useState<Date | null>(null);
82
- return (
83
- <Box p={32}>
84
- <DatePicker
85
- label="Start date"
86
- selectedDate={selectedDate}
87
- setSelectedDate={setSelectedDate}
88
- >
89
- <ComposedDatePickerLayout />
90
- </DatePicker>
91
- </Box>
92
- );
93
- },
94
- };
95
-
96
- function ComposedDatePickerLayout() {
97
- const { isCalendarOpen, openCalendar, closeCalendar, calendarDialogId } =
98
- useDatePicker();
99
- const inputRef = useRef<HTMLInputElement | null>(null);
100
-
101
- return (
102
- <>
103
- <Box width="fit-content" onClick={openCalendar}>
104
- <DatePickerInput ref={inputRef} />
105
- </Box>
106
- <PopoverContainer
107
- alignment="bottom-left"
108
- allowPageInteraction
109
- focusOnProps={{ autoFocus: false, focusLock: false }}
110
- invertAxis="x"
111
- isOpen={isCalendarOpen}
112
- offset={10}
113
- targetRef={inputRef}
114
- onRequestClose={closeCalendar}
115
- >
116
- <div aria-label="Choose date" id={calendarDialogId} role="dialog">
117
- <DatePickerCalendar dialogId={calendarDialogId} />
118
- </div>
119
- </PopoverContainer>
120
- </>
121
- );
122
- }