@vendure-io/ui 3.0.0-next.2 → 3.0.0-next.4

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.
@@ -0,0 +1,341 @@
1
+ 'use client';
2
+
3
+ import { mergeProps } from '@base-ui/react/merge-props';
4
+ import { useRender } from '@base-ui/react/use-render';
5
+ import { Progress } from '@vendure-io/ui/components/atoms/progress';
6
+ import { toneIcons } from '@vendure-io/ui/lib/tone-icons';
7
+ import { cn } from '@vendure-io/ui/lib/utils';
8
+ import * as React from 'react';
9
+
10
+ // Compound, like Timeline: the root sets the orientation and the marker kind,
11
+ // each step takes a state, and callers place a title, a description and, in a
12
+ // vertical guide, any content under it. The step draws its own marker (and, in
13
+ // a horizontal track, its own bar) from its state, so the look of a state is
14
+ // the same in every flow.
15
+ //
16
+ // An ordered flow, not a to-do list: the user moves through the steps in
17
+ // order, or the system runs them in order. Tasks the user ticks off in any
18
+ // order are a Checklist.
19
+
20
+ /**
21
+ * Where a step stands in the flow.
22
+ *
23
+ * - `upcoming`: not reached yet.
24
+ * - `current`: the step the flow is on, waiting for the user or for the
25
+ * system. No spinner: a waiting step can wait for days.
26
+ * - `running`: work on this step is happening now (a build, a deploy). Only
27
+ * this state spins.
28
+ * - `done`: finished.
29
+ * - `failed`: the flow stopped here.
30
+ */
31
+ type StepState = 'upcoming' | 'current' | 'running' | 'done' | 'failed';
32
+
33
+ type StepStateLabels = Record<StepState, string>;
34
+
35
+ const defaultStateLabels: StepStateLabels = {
36
+ upcoming: 'not started',
37
+ current: 'current step',
38
+ running: 'in progress',
39
+ done: 'done',
40
+ failed: 'failed',
41
+ };
42
+
43
+ type StepIndicatorContextValue = {
44
+ orientation: 'horizontal' | 'vertical';
45
+ marker: 'number' | 'icon';
46
+ stateLabels: StepStateLabels;
47
+ };
48
+
49
+ const StepIndicatorContext = React.createContext<StepIndicatorContextValue>({
50
+ orientation: 'horizontal',
51
+ marker: 'number',
52
+ stateLabels: defaultStateLabels,
53
+ });
54
+
55
+ const StepContext = React.createContext<StepState>('upcoming');
56
+
57
+ interface StepIndicatorProps extends React.ComponentProps<'ol'> {
58
+ /**
59
+ * `'horizontal'` (default): a progress track, one bar per step, the steps
60
+ * side by side (signup, the build and deploy steps of a deployment).
61
+ * `'vertical'`: a guide, the steps one under the other on a rail, with room
62
+ * for content under each step (a first-run guide).
63
+ */
64
+ orientation?: 'horizontal' | 'vertical';
65
+ /**
66
+ * `'number'` (default): each step shows its number until it is done,
67
+ * running or failed. `'icon'`: each step shows a state icon only, for steps
68
+ * the system runs, where the number adds nothing.
69
+ */
70
+ marker?: 'number' | 'icon';
71
+ /**
72
+ * What a screen reader hears after each step's title, so the state never
73
+ * depends on colour or shape alone. Pass translations here.
74
+ */
75
+ stateLabels?: Partial<StepStateLabels>;
76
+ }
77
+
78
+ /**
79
+ * The steps of an ordered flow and where the flow stands: signup, the build
80
+ * and deploy steps of a deployment, a first-run guide. Renders an `<ol>`; give
81
+ * it an `aria-label` ("Signup steps").
82
+ *
83
+ * Nothing moves on the first render. When a step changes state later, its
84
+ * marker eases to the new state and, in a horizontal track, its bar fills.
85
+ */
86
+ function StepIndicator({
87
+ className,
88
+ orientation = 'horizontal',
89
+ marker = 'number',
90
+ stateLabels,
91
+ ...props
92
+ }: StepIndicatorProps) {
93
+ // Set after the first render: the state entrances below run only once it
94
+ // is there, so a page that loads mid-flow shows its steps at rest.
95
+ const [ready, setReady] = React.useState(false);
96
+ React.useEffect(() => setReady(true), []);
97
+ const labels = React.useMemo(() => ({ ...defaultStateLabels, ...stateLabels }), [stateLabels]);
98
+ const context = React.useMemo(
99
+ () => ({ orientation, marker, stateLabels: labels }),
100
+ [orientation, marker, labels],
101
+ );
102
+ return (
103
+ <StepIndicatorContext.Provider value={context}>
104
+ <ol
105
+ data-slot="step-indicator"
106
+ data-orientation={orientation}
107
+ data-ready={ready ? '' : undefined}
108
+ className={cn(
109
+ 'group/step-indicator [counter-reset:step]',
110
+ // A horizontal track gives each step an equal column of at least
111
+ // 7rem, so the names stay readable; on a narrow screen the steps
112
+ // wrap to a second row rather than cut every name short.
113
+ orientation === 'horizontal'
114
+ ? 'grid grid-cols-[repeat(auto-fit,minmax(min(100%,7rem),1fr))] gap-x-3 gap-y-4'
115
+ : 'flex flex-col',
116
+ className,
117
+ )}
118
+ {...props}
119
+ />
120
+ </StepIndicatorContext.Provider>
121
+ );
122
+ }
123
+
124
+ // The vertical rail: a 1px `input` line from 4px under this step's marker to
125
+ // 4px above the next one, centred on the 20px marker column, on the start
126
+ // edge so it moves to the right in right-to-left. The last step draws none.
127
+ const VERTICAL_RAIL =
128
+ "not-last:pb-6 not-last:after:absolute not-last:after:start-[9.5px] not-last:after:top-6 not-last:after:bottom-1 not-last:after:w-px not-last:after:bg-input not-last:after:content-['']";
129
+
130
+ // The bar of each state on a horizontal track. A done step fills green and a
131
+ // failed one red, as Progress does. A current step fills with a soft blue
132
+ // tint: it is on, not finished. A running step adds the moving band on the
133
+ // same tint. An upcoming step is the empty track.
134
+ const barProps: Record<StepState, Pick<React.ComponentProps<typeof Progress>, 'value' | 'tone'>> = {
135
+ upcoming: { value: 0, tone: 'neutral' },
136
+ current: { value: null, tone: 'progress' },
137
+ running: { value: null, tone: 'progress' },
138
+ done: { value: 100, tone: 'success' },
139
+ failed: { value: 100, tone: 'critical' },
140
+ };
141
+
142
+ // Progress grows its fill from 0 when it mounts. The track shows the flow as
143
+ // it is on load, so the fill starts at its value; it still grows when a step
144
+ // moves on. A current step keeps the tint of the indeterminate bar without
145
+ // its moving band.
146
+ const BAR =
147
+ 'col-span-full mb-2.5 [&_[data-slot=progress-indicator]]:starting:scale-x-(--progress-scale,1)!';
148
+ const BAR_STILL = '[&_[data-slot=progress-indicator]]:after:hidden';
149
+
150
+ interface StepIndicatorStepProps extends React.ComponentProps<'li'> {
151
+ /** Where this step stands. Default `upcoming`. */
152
+ state?: StepState;
153
+ }
154
+
155
+ /**
156
+ * One step: its marker, then a StepIndicatorTitle, an optional
157
+ * StepIndicatorDescription and, in a vertical guide, any StepIndicatorContent.
158
+ * The current and the running step carry `aria-current="step"`.
159
+ */
160
+ function StepIndicatorStep({
161
+ className,
162
+ state = 'upcoming',
163
+ children,
164
+ ...props
165
+ }: StepIndicatorStepProps) {
166
+ const { orientation } = React.useContext(StepIndicatorContext);
167
+ const horizontal = orientation === 'horizontal';
168
+ return (
169
+ <StepContext.Provider value={state}>
170
+ <li
171
+ data-slot="step-indicator-step"
172
+ data-state={state}
173
+ aria-current={state === 'current' || state === 'running' ? 'step' : undefined}
174
+ className={cn(
175
+ 'group/step relative grid min-w-0 content-start [counter-increment:step]',
176
+ horizontal
177
+ ? 'grid-cols-[20px_minmax(0,1fr)] gap-x-2'
178
+ : cn('grid-cols-[20px_minmax(0,1fr)] gap-x-3', VERTICAL_RAIL),
179
+ className,
180
+ )}
181
+ {...props}
182
+ >
183
+ {horizontal ? (
184
+ <Progress
185
+ aria-hidden
186
+ {...barProps[state]}
187
+ className={cn(BAR, state === 'current' && BAR_STILL)}
188
+ />
189
+ ) : null}
190
+ <StepIndicatorMarker state={state} />
191
+ {children}
192
+ </li>
193
+ </StepContext.Provider>
194
+ );
195
+ }
196
+
197
+ // A glyph that takes the place of another, when a step changes state after
198
+ // the first render, scales up from 85% and fades in, in `normal` on the
199
+ // strong ease-out. Reduced motion keeps the fade.
200
+ const ENTER =
201
+ 'transition-[opacity,scale] duration-normal ease-out group-data-ready/step-indicator:starting:opacity-0 motion-safe:group-data-ready/step-indicator:starting:scale-85 motion-reduce:transition-opacity';
202
+
203
+ // Each state's glyph: the tone icon of the state dictionary, so done, failed
204
+ // and running look as they do in a StatusBadge. The icons are 16px in an
205
+ // icon track and fill the 20px marker in a numbered one, where they take the
206
+ // place of the numbered circle.
207
+ const DoneIcon = toneIcons.success;
208
+ const FailedIcon = toneIcons.critical;
209
+ const RunningIcon = toneIcons.progress;
210
+ const UpcomingIcon = toneIcons.neutral;
211
+
212
+ function StepIndicatorMarker({ state }: { state: StepState }) {
213
+ const { marker } = React.useContext(StepIndicatorContext);
214
+ const iconSize = marker === 'number' ? 'size-5' : 'size-4';
215
+ let glyph: React.ReactNode;
216
+ // The key changes with the glyph, so a new glyph mounts and plays ENTER,
217
+ // while the numbered circle stays and eases its colours from upcoming to
218
+ // current.
219
+ if (state === 'done') {
220
+ glyph = <DoneIcon key="done" className={cn(iconSize, 'text-success-text', ENTER)} />;
221
+ } else if (state === 'failed') {
222
+ glyph = <FailedIcon key="failed" className={cn(iconSize, 'text-destructive-text', ENTER)} />;
223
+ } else if (state === 'running') {
224
+ glyph = (
225
+ <span key="running" className={cn('flex', ENTER)}>
226
+ <RunningIcon
227
+ className={cn(iconSize, 'text-info-text animate-spin-slow motion-reduce:animate-none')}
228
+ />
229
+ </span>
230
+ );
231
+ } else if (marker === 'number') {
232
+ glyph = (
233
+ <span
234
+ key="number"
235
+ className={cn(
236
+ 'flex size-5 items-center justify-center rounded-full border text-xs leading-none font-medium tabular-nums',
237
+ 'before:content-[counter(step)]',
238
+ 'transition-[color,border-color] duration-normal ease-soft',
239
+ state === 'current'
240
+ ? 'border-info-text text-info-text'
241
+ : 'border-input text-muted-foreground',
242
+ )}
243
+ />
244
+ );
245
+ } else if (state === 'current') {
246
+ // A waiting step: blue, and no icon that could read as loading.
247
+ glyph = <span key="current" className={cn('size-2 rounded-full bg-info-text', ENTER)} />;
248
+ } else {
249
+ glyph = (
250
+ <UpcomingIcon key="upcoming" className={cn(iconSize, 'text-muted-foreground', ENTER)} />
251
+ );
252
+ }
253
+ return (
254
+ <span
255
+ aria-hidden
256
+ data-slot="step-indicator-marker"
257
+ data-marker={marker}
258
+ className="flex size-5 items-center justify-center [&_svg]:stroke-[1.75]"
259
+ >
260
+ {glyph}
261
+ </span>
262
+ );
263
+ }
264
+
265
+ /**
266
+ * The name of the step, in 14px on a 20px line beside the marker. A screen
267
+ * reader hears the step's state after it ("Build, done"). An upcoming step's
268
+ * title is muted. Renders a `p`; pass `render={<h3 />}` when the steps of a
269
+ * guide belong in the page outline.
270
+ */
271
+ function StepIndicatorTitle({
272
+ className,
273
+ render,
274
+ children,
275
+ ...props
276
+ }: useRender.ComponentProps<'p'>) {
277
+ const { orientation, stateLabels } = React.useContext(StepIndicatorContext);
278
+ const state = React.useContext(StepContext);
279
+ return useRender({
280
+ defaultTagName: 'p',
281
+ render,
282
+ props: mergeProps<'p'>(
283
+ {
284
+ className: cn(
285
+ 'col-start-2 text-sm leading-5 font-medium transition-colors duration-normal ease-soft',
286
+ state === 'upcoming' ? 'text-muted-foreground' : 'text-foreground',
287
+ orientation === 'horizontal' && 'truncate',
288
+ className,
289
+ ),
290
+ children: (
291
+ <>
292
+ {children}
293
+ <span className="sr-only">, {stateLabels[state]}</span>
294
+ </>
295
+ ),
296
+ },
297
+ props,
298
+ ),
299
+ state: { slot: 'step-indicator-title' },
300
+ });
301
+ }
302
+
303
+ /**
304
+ * The line under the title: what the step does, or the time it took. Muted,
305
+ * with tabular figures so a running time stays steady.
306
+ */
307
+ function StepIndicatorDescription({ className, ...props }: React.ComponentProps<'p'>) {
308
+ return (
309
+ <p
310
+ data-slot="step-indicator-description"
311
+ className={cn(
312
+ 'col-start-2 mt-0.5 text-sm text-muted-foreground tabular-nums text-pretty',
313
+ className,
314
+ )}
315
+ {...props}
316
+ />
317
+ );
318
+ }
319
+
320
+ /**
321
+ * Content under a step of a vertical guide: the actions of the current step,
322
+ * a command to run, a note.
323
+ */
324
+ function StepIndicatorContent({ className, ...props }: React.ComponentProps<'div'>) {
325
+ return (
326
+ <div
327
+ data-slot="step-indicator-content"
328
+ className={cn('col-start-2 mt-3 min-w-0', className)}
329
+ {...props}
330
+ />
331
+ );
332
+ }
333
+
334
+ export {
335
+ StepIndicator,
336
+ StepIndicatorContent,
337
+ StepIndicatorDescription,
338
+ StepIndicatorStep,
339
+ StepIndicatorTitle,
340
+ };
341
+ export type { StepIndicatorProps, StepIndicatorStepProps, StepState, StepStateLabels };
@@ -0,0 +1,50 @@
1
+ import * as React from 'react';
2
+
3
+ type UserToggleMotion = {
4
+ /** The `checked` value seen on the last render. */
5
+ checked: boolean;
6
+ /** The user changed the value since the last `checked` change. */
7
+ userToggled: boolean;
8
+ /** The last `checked` change came from the user. */
9
+ animate: boolean;
10
+ };
11
+
12
+ /**
13
+ * Settles one render. A `checked` value that changed after the user toggled
14
+ * the control moves with motion. A change with no user toggle before it (data
15
+ * that loads, a form reset, another control) does not. Until the first change
16
+ * there is nothing to move from, so `animate` stays false.
17
+ */
18
+ export function settleUserToggleMotion(
19
+ state: UserToggleMotion,
20
+ checked: boolean,
21
+ ): UserToggleMotion {
22
+ if (state.checked === checked) return state;
23
+ return { checked, userToggled: false, animate: state.userToggled };
24
+ }
25
+
26
+ /**
27
+ * Tells a Switch whether a `checked` change should move. Only a change the
28
+ * user makes (pointer or keyboard) does. A controlled value that the page sets
29
+ * from code is shown at once.
30
+ *
31
+ * Call `markUserToggled` from `onCheckedChange`: it runs before the page sets
32
+ * the new `checked`, so the next render sees the toggle first. An uncontrolled
33
+ * control (`checked` is undefined) only changes by the user, so it always moves.
34
+ */
35
+ export function useUserToggleMotion(checked: boolean | undefined) {
36
+ const controlled = checked !== undefined;
37
+ const state = React.useRef<UserToggleMotion>({
38
+ checked: checked ?? false,
39
+ userToggled: false,
40
+ animate: false,
41
+ });
42
+ state.current = settleUserToggleMotion(state.current, checked ?? false);
43
+ const markUserToggled = React.useCallback(() => {
44
+ state.current = { ...state.current, userToggled: true };
45
+ }, []);
46
+ return {
47
+ animate: !controlled || state.current.animate,
48
+ markUserToggled,
49
+ };
50
+ }
package/src/lib/env.ts ADDED
@@ -0,0 +1,9 @@
1
+ // The build mode, read in one place. The design system ships its source, and a
2
+ // consumer type-checks it without Node types (the Console's app-shell package,
3
+ // for one). So `process` is declared here for this module only. Keep the
4
+ // literal `process.env.NODE_ENV`: bundlers replace it, so a production build
5
+ // drops the development-only checks.
6
+ declare const process: { env: { NODE_ENV?: string } };
7
+
8
+ /** True outside a production build: development warnings and checks run. */
9
+ export const isDevelopment = process.env.NODE_ENV !== 'production';
@@ -1,4 +1,5 @@
1
1
  import type { ReactNode } from 'react';
2
+ import { isDevelopment } from './env.ts';
2
3
 
3
4
  /**
4
5
  * The state dictionary — the mechanism that makes the same entity state look
@@ -26,7 +27,8 @@ export interface StateEntry {
26
27
  /**
27
28
  * A shape that says more than the tone's own icon, e.g. `<TruckIcon />` for
28
29
  * Shipped. Pass it to StatusBadge's `icon` through `iconFor`. Leave it out
29
- * for the tone's own icon.
30
+ * for the tone's own icon. `false` means no icon: `pending` is the `progress`
31
+ * tone without its spinner.
30
32
  */
31
33
  icon?: ReactNode;
32
34
  }
@@ -43,7 +45,7 @@ export interface StateMap<S extends string> {
43
45
  entries: Record<S, StateEntry>;
44
46
  toneFor(state: string): Tone;
45
47
  labelFor(state: string): string;
46
- /** The entry's own icon, or `undefined` for the tone's icon. */
48
+ /** The entry's own icon, `false` for no icon, or `undefined` for the tone's icon. */
47
49
  iconFor(state: string): ReactNode | undefined;
48
50
  }
49
51
 
@@ -71,8 +73,6 @@ export function stateNameToWords(state: string): string {
71
73
  return sentence.charAt(0).toUpperCase() + sentence.slice(1);
72
74
  }
73
75
 
74
- const isDev = process.env.NODE_ENV !== 'production';
75
-
76
76
  /**
77
77
  * Declare a domain's state→tone map. The `Record<S, StateEntry>` argument is
78
78
  * exhaustive over `S`, so typing the call as `defineStateEntries<DeploymentStatus>`
@@ -93,7 +93,7 @@ export function defineStateEntries<S extends string>(entries: Record<S, StateEnt
93
93
  const entry = index.get(key);
94
94
  // Dedup on the lowercased key so casing variants of the same unknown state
95
95
  // ("Foo" / "foo") warn once — matching the lookup semantics.
96
- if (!entry && isDev && !warned.has(key)) {
96
+ if (!entry && isDevelopment && !warned.has(key)) {
97
97
  warned.add(key);
98
98
  console.warn(
99
99
  `[state-dictionary] Unmapped state "${state}" — rendering as neutral. ` +
@@ -120,10 +120,11 @@ export function defineStateEntries<S extends string>(entries: Record<S, StateEnt
120
120
  * `critical` is for failures and refusals (`failed`, `error`, `rejected`).
121
121
  * - A dormant state is `neutral` (`disabled`, `inactive`); its live
122
122
  * counterpart is `success` (`enabled`, `active`).
123
- * - `pending` is `progress`: it waits on a step that the system or another
124
- * party completes, and it will change without the viewer acting. A domain
125
- * where pending means "waiting for this user" declares its own `warning`
126
- * entry in its own map.
123
+ * - `pending` is `progress` without an icon (`icon: false`): it waits on a step
124
+ * that the system or another party completes, and it will change without
125
+ * the viewer acting. Only work that runs right now spins. A domain where
126
+ * pending means "waiting for this user" declares its own `warning` entry in
127
+ * its own map.
127
128
  *
128
129
  * `running` is deliberately absent: it has no single tone (a running job is
129
130
  * `progress`, a running service is `success`), so every domain must decide it
@@ -134,7 +135,7 @@ export const commonStates = defineStateEntries({
134
135
  disabled: { tone: 'neutral', defaultLabel: 'Disabled' },
135
136
  active: { tone: 'success', defaultLabel: 'Active' },
136
137
  inactive: { tone: 'neutral', defaultLabel: 'Inactive' },
137
- pending: { tone: 'progress', defaultLabel: 'Pending' },
138
+ pending: { tone: 'progress', defaultLabel: 'Pending', icon: false },
138
139
  completed: { tone: 'success', defaultLabel: 'Completed' },
139
140
  failed: { tone: 'critical', defaultLabel: 'Failed' },
140
141
  cancelled: { tone: 'neutral', defaultLabel: 'Cancelled' },