@edux-design/buttons 0.1.3 → 0.1.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.
@@ -1,341 +0,0 @@
1
- import React, {
2
- forwardRef,
3
- useCallback,
4
- useEffect,
5
- useMemo,
6
- useRef,
7
- useState,
8
- } from "react";
9
- import { cx } from "@edux-design/utils";
10
-
11
- /**
12
- * ButtonCounter (stepper) component.
13
- *
14
- * Renders decrement/increment buttons with a central value display.
15
- * Supports the same size + variant flags as the main Button.
16
- *
17
- * @typedef {React.HTMLAttributes<HTMLDivElement> & {
18
- * value?: number,
19
- * defaultValue?: number,
20
- * onChange?: (value: number) => void,
21
- * min?: number,
22
- * max?: number,
23
- * step?: number,
24
- * children?: React.ReactNode,
25
- * size?: "small"|"medium"|"large",
26
- * isSecondary?: boolean,
27
- * isDanger?: boolean,
28
- * isBare?: boolean,
29
- * isStretched?: boolean,
30
- * disabled?: boolean,
31
- * isEditable?: boolean,
32
- * inputProps?: Omit<React.InputHTMLAttributes<HTMLInputElement>, "value"|"defaultValue"|"onChange"|"type">,
33
- * decrementIcon?: React.ReactNode,
34
- * incrementIcon?: React.ReactNode,
35
- * startIcon?: React.ReactNode,
36
- * endIcon?: React.ReactNode,
37
- * decrementButtonProps?: React.ButtonHTMLAttributes<HTMLButtonElement>,
38
- * incrementButtonProps?: React.ButtonHTMLAttributes<HTMLButtonElement>,
39
- * className?: string,
40
- * }} ButtonCounterProps
41
- */
42
-
43
- /**
44
- * @type {React.ForwardRefExoticComponent<ButtonCounterProps & React.RefAttributes<HTMLDivElement>>}
45
- */
46
- export const ButtonCounter = forwardRef(function ButtonCounter(
47
- {
48
- value,
49
- defaultValue = 1,
50
- onChange,
51
- min = Number.NEGATIVE_INFINITY,
52
- max = Number.POSITIVE_INFINITY,
53
- step = 1,
54
- children,
55
- size = "medium",
56
- isSecondary,
57
- isDanger,
58
- isBare,
59
- isStretched,
60
- disabled,
61
- isEditable = false,
62
- inputProps,
63
- decrementIcon,
64
- incrementIcon,
65
- startIcon,
66
- endIcon,
67
- decrementButtonProps,
68
- incrementButtonProps,
69
- className,
70
- ...rest
71
- },
72
- ref,
73
- ) {
74
- const isControlled = value !== undefined;
75
- const [internalValue, setInternalValue] = useState(defaultValue);
76
- const currentValue = isControlled ? value : internalValue;
77
-
78
- const clampedValue = useMemo(() => {
79
- const safe = Number.isFinite(currentValue) ? currentValue : defaultValue;
80
- return Math.min(max, Math.max(min, safe));
81
- }, [currentValue, defaultValue, max, min]);
82
-
83
- const commitValue = useCallback(
84
- (next) => {
85
- const clamped = Math.min(max, Math.max(min, next));
86
- if (!isControlled) setInternalValue(clamped);
87
- onChange?.(clamped);
88
- },
89
- [isControlled, max, min, onChange],
90
- );
91
-
92
- const decrementDisabled =
93
- !!disabled || !Number.isFinite(clampedValue) || clampedValue - step < min;
94
- const incrementDisabled =
95
- !!disabled || !Number.isFinite(clampedValue) || clampedValue + step > max;
96
-
97
- let variant = "primary";
98
- if (disabled) {
99
- variant = "disabled";
100
- } else if (isDanger && isBare) {
101
- variant = "dangerBare";
102
- } else if (isDanger) {
103
- variant = "danger";
104
- } else if (isSecondary) {
105
- variant = "secondary";
106
- } else if (isBare) {
107
- variant = "bare";
108
- }
109
-
110
- if (process.env.NODE_ENV !== "production") {
111
- const count = [isSecondary, isDanger, isBare].filter(Boolean).length;
112
- const hasAllowedCombo = isDanger && isBare && count === 2;
113
- if (count > 1 && !hasAllowedCombo) {
114
- console.warn(
115
- "[ButtonCounter]: Multiple variant props passed. Using the highest priority only.",
116
- );
117
- }
118
-
119
- if (step <= 0) {
120
- console.warn("[ButtonCounter]: step should be > 0.");
121
- }
122
- }
123
-
124
- const CONTROL_SIZES = {
125
- small: {
126
- button: "h-[36px] w-[36px] text-sm",
127
- display: "h-[36px] min-w-[48px] px-12 text-sm",
128
- },
129
- medium: {
130
- button: "h-[44px] w-[44px] text-base",
131
- display: "h-[44px] min-w-[56px] px-12 text-base",
132
- },
133
- large: {
134
- button: "h-[56px] w-[56px] text-lg",
135
- display: "h-[56px] min-w-[72px] px-16 text-lg",
136
- },
137
- };
138
-
139
- const defaultsButton =
140
- "flex justify-center items-center focus:shadow-focus focus-visible:shadow-focus outline-none transition-all duration-300 ease-in-out cursor-pointer";
141
-
142
- const defaultsDisplay =
143
- "flex items-center justify-center text-bold tracking-normal";
144
-
145
- const width = isStretched ? "w-full" : "w-fit-content";
146
-
147
- const variants = {
148
- primary: {
149
- button:
150
- "border-2 border-border-primary-emphasis bg-bg-primary-base text-white hover:bg-border-focus hover:text-fg-focus hover:border-border-emphasis hover:shadow-md active:bg-border-focus active:bg-bg-focus-overlay active:text-fg-focus",
151
- display:
152
- "border-y-2 border-x-2 border-border-primary-emphasis bg-bg-primary-base text-white",
153
- },
154
- secondary: {
155
- button:
156
- "border-2 border-border-primary-base bg-bg-base text-fg-primary-emphasis hover:shadow-md hover:bg-bg-primary-subtle active:bg-bg-primary-subtle-90",
157
- display:
158
- "border-y-2 border-x-2 border-border-primary-base bg-bg-base text-fg-primary-emphasis",
159
- },
160
- bare: {
161
- button:
162
- "bg-bg-base text-fg-primary-emphasis hover:bg-bg-minimal active:bg-bg-minimal-5",
163
- display: "bg-bg-base text-fg-primary-emphasis",
164
- },
165
- dangerBare: {
166
- button:
167
- "bg-bg-base text-fg-danger-emphasis hover:bg-bg-danger-subtle active:bg-bg-danger-subtle",
168
- display: "bg-bg-base text-fg-danger-emphasis",
169
- },
170
- danger: {
171
- button:
172
- "bg-bg-danger-base border-2 border-border-danger-emphasis text-white hover:bg-bg-danger-base-5 active:bg-bg-danger-base-10",
173
- display:
174
- "border-y-2 border-x-2 border-border-danger-emphasis bg-bg-danger-base text-white",
175
- },
176
- disabled: {
177
- button:
178
- "border-2 border-border-subtle bg-bg-inactive text-fg-inactive hover:no-underline cursor-not-allowed",
179
- display:
180
- "border-y-2 border-x-2 border-border-subtle bg-bg-inactive text-fg-inactive",
181
- },
182
- };
183
-
184
- const sizeStyles = CONTROL_SIZES[size] ?? CONTROL_SIZES.medium;
185
- const variantStyles = variants[variant] ?? variants.primary;
186
-
187
- const leftButtonStyles = cx(
188
- defaultsButton,
189
- sizeStyles.button,
190
- "rounded-l-lg",
191
- "relative z-10",
192
- variantStyles.button,
193
- variant !== "bare" && variant !== "dangerBare" ? "border-r-0" : null,
194
- );
195
-
196
- const rightButtonStyles = cx(
197
- defaultsButton,
198
- sizeStyles.button,
199
- "rounded-r-lg",
200
- variantStyles.button,
201
- variant !== "bare" && variant !== "dangerBare" ? "border-l-0" : null,
202
- );
203
-
204
- const displayStyles = cx(
205
- defaultsDisplay,
206
- sizeStyles.display,
207
- "relative z-0",
208
- variantStyles.display,
209
- isStretched ? "flex-1" : null,
210
- );
211
-
212
- const effectiveDecrementIcon = decrementIcon ?? startIcon ?? "-";
213
- const effectiveIncrementIcon = incrementIcon ?? endIcon ?? "+";
214
-
215
- const [draftValue, setDraftValue] = useState(String(clampedValue));
216
- const [isEditing, setIsEditing] = useState(false);
217
- const inputRef = useRef(null);
218
-
219
- useEffect(() => {
220
- if (isEditing) return;
221
- setDraftValue(String(clampedValue));
222
- }, [clampedValue, isEditing]);
223
-
224
- const commitDraft = useCallback(() => {
225
- const trimmed = String(draftValue).trim();
226
- if (trimmed === "") {
227
- setDraftValue(String(clampedValue));
228
- return;
229
- }
230
-
231
- const next = Number(trimmed);
232
- if (!Number.isFinite(next)) {
233
- setDraftValue(String(clampedValue));
234
- return;
235
- }
236
-
237
- commitValue(next);
238
- }, [clampedValue, commitValue, draftValue]);
239
-
240
- return (
241
- <div
242
- ref={ref}
243
- className={cx("inline-flex items-stretch", width, className)}
244
- {...rest}
245
- >
246
- <button
247
- {...decrementButtonProps}
248
- type="button"
249
- aria-label={decrementButtonProps?.["aria-label"] ?? "Decrease"}
250
- aria-disabled={decrementDisabled}
251
- disabled={decrementDisabled}
252
- className={cx(
253
- leftButtonStyles,
254
- decrementDisabled && variant !== "disabled"
255
- ? variants.disabled.button
256
- : null,
257
- decrementButtonProps?.className,
258
- )}
259
- onClick={(event) => {
260
- decrementButtonProps?.onClick?.(event);
261
- if (event.defaultPrevented) return;
262
- commitValue(clampedValue - step);
263
- }}
264
- >
265
- {effectiveDecrementIcon}
266
- </button>
267
-
268
- {isEditable && children == null ? (
269
- <input
270
- {...inputProps}
271
- ref={inputRef}
272
- type="number"
273
- inputMode="numeric"
274
- disabled={!!disabled}
275
- aria-label={inputProps?.["aria-label"] ?? "Value"}
276
- className={cx(
277
- displayStyles,
278
- "w-[44px] text-center outline-none bg-transparent text-fg-base",
279
- "[appearance:textfield] [&::-webkit-outer-spin-button]:appearance-none [&::-webkit-inner-spin-button]:appearance-none [&::-webkit-outer-spin-button]:m-0 [&::-webkit-inner-spin-button]:m-0",
280
- "focus:shadow-focus focus-visible:shadow-focus focus:z-15 focus-within:z-15",
281
- inputProps?.className,
282
- )}
283
- value={draftValue}
284
- onChange={(event) => {
285
- inputProps?.onChange?.(event);
286
- if (event.defaultPrevented) return;
287
- setDraftValue(event.target.value);
288
- }}
289
- onFocus={(event) => {
290
- inputProps?.onFocus?.(event);
291
- if (event.defaultPrevented) return;
292
- setIsEditing(true);
293
- }}
294
- onBlur={(event) => {
295
- inputProps?.onBlur?.(event);
296
- if (event.defaultPrevented) return;
297
- setIsEditing(false);
298
- commitDraft();
299
- }}
300
- onKeyDown={(event) => {
301
- inputProps?.onKeyDown?.(event);
302
- if (event.defaultPrevented) return;
303
- if (event.key === "Enter") {
304
- event.currentTarget.blur();
305
- }
306
- if (event.key === "Escape") {
307
- setDraftValue(String(clampedValue));
308
- event.currentTarget.blur();
309
- }
310
- }}
311
- />
312
- ) : (
313
- <div className={cx(displayStyles, "select-none")}>
314
- {children ?? clampedValue}
315
- </div>
316
- )}
317
-
318
- <button
319
- {...incrementButtonProps}
320
- type="button"
321
- aria-label={incrementButtonProps?.["aria-label"] ?? "Increase"}
322
- aria-disabled={incrementDisabled}
323
- disabled={incrementDisabled}
324
- className={cx(
325
- rightButtonStyles,
326
- incrementDisabled && variant !== "disabled"
327
- ? variants.disabled.button
328
- : null,
329
- incrementButtonProps?.className,
330
- )}
331
- onClick={(event) => {
332
- incrementButtonProps?.onClick?.(event);
333
- if (event.defaultPrevented) return;
334
- commitValue(clampedValue + step);
335
- }}
336
- >
337
- {effectiveIncrementIcon}
338
- </button>
339
- </div>
340
- );
341
- });
@@ -1,100 +0,0 @@
1
- import React from "react";
2
- import { fireEvent, render, screen } from "@testing-library/react";
3
- import { ButtonCounter } from "./ButtonCounter";
4
-
5
- describe("ButtonCounter", () => {
6
- it("renders defaultValue", () => {
7
- render(<ButtonCounter defaultValue={5} />);
8
- expect(screen.getByText("5")).toBeInTheDocument();
9
- });
10
-
11
- it("increments and decrements", () => {
12
- render(<ButtonCounter defaultValue={1} />);
13
-
14
- fireEvent.click(screen.getByRole("button", { name: "Increase" }));
15
- expect(screen.getByText("2")).toBeInTheDocument();
16
-
17
- fireEvent.click(screen.getByRole("button", { name: "Decrease" }));
18
- expect(screen.getByText("1")).toBeInTheDocument();
19
- });
20
-
21
- it("renders an editable input when isEditable=true", () => {
22
- const onChange = vi.fn();
23
- render(<ButtonCounter defaultValue={3} isEditable onChange={onChange} />);
24
-
25
- const input = screen.getByRole("spinbutton", { name: "Value" });
26
- expect(input).toHaveValue(3);
27
-
28
- fireEvent.change(input, { target: { value: "7" } });
29
- fireEvent.blur(input);
30
-
31
- expect(onChange).toHaveBeenCalledWith(7);
32
- expect(screen.getByRole("spinbutton", { name: "Value" })).toHaveValue(7);
33
- });
34
-
35
- it("applies medium size by default", () => {
36
- render(<ButtonCounter defaultValue={1} />);
37
- const buttons = screen.getAllByRole("button");
38
- expect(buttons[0].className).toMatch(/h-\[44px\]/);
39
- expect(buttons[1].className).toMatch(/h-\[44px\]/);
40
- });
41
-
42
- it("applies small and large sizes", () => {
43
- const { rerender } = render(<ButtonCounter size="small" defaultValue={1} />);
44
- expect(screen.getAllByRole("button")[0].className).toMatch(/h-\[36px\]/);
45
-
46
- rerender(<ButtonCounter size="large" defaultValue={1} />);
47
- expect(screen.getAllByRole("button")[0].className).toMatch(/h-\[56px\]/);
48
- });
49
-
50
- it("applies variants", () => {
51
- const { rerender } = render(<ButtonCounter defaultValue={1} />);
52
- expect(screen.getAllByRole("button")[0].className).toMatch(/bg-bg-primary-base/);
53
-
54
- rerender(<ButtonCounter isSecondary defaultValue={1} />);
55
- expect(screen.getAllByRole("button")[0].className).toMatch(/bg-bg-base/);
56
-
57
- rerender(<ButtonCounter isDanger defaultValue={1} />);
58
- expect(screen.getAllByRole("button")[0].className).toMatch(/bg-bg-danger-base/);
59
-
60
- rerender(<ButtonCounter isDanger isBare defaultValue={1} />);
61
- expect(screen.getAllByRole("button")[0].className).toMatch(/text-fg-danger-emphasis/);
62
- });
63
-
64
- it("applies disabled state", () => {
65
- render(<ButtonCounter disabled defaultValue={1} />);
66
- const buttons = screen.getAllByRole("button");
67
- expect(buttons[0]).toBeDisabled();
68
- expect(buttons[1]).toBeDisabled();
69
- expect(buttons[0].className).toMatch(/bg-bg-inactive/);
70
- });
71
-
72
- it("uses stretched width when isStretched=true", () => {
73
- const { container } = render(<ButtonCounter isStretched defaultValue={1} />);
74
- expect(container.firstChild.className).toMatch(/w-full/);
75
- });
76
-
77
- it("logs a warning in dev mode if multiple variants are passed", () => {
78
- const warnSpy = vi.spyOn(console, "warn").mockImplementation(() => {});
79
- process.env.NODE_ENV = "development";
80
-
81
- render(<ButtonCounter isSecondary isDanger defaultValue={1} />);
82
-
83
- expect(warnSpy).toHaveBeenCalledWith(
84
- "[ButtonCounter]: Multiple variant props passed. Using the highest priority only."
85
- );
86
-
87
- warnSpy.mockRestore();
88
- });
89
-
90
- it("does not warn for the danger bare combination", () => {
91
- const warnSpy = vi.spyOn(console, "warn").mockImplementation(() => {});
92
- process.env.NODE_ENV = "development";
93
-
94
- render(<ButtonCounter isDanger isBare defaultValue={1} />);
95
-
96
- expect(warnSpy).not.toHaveBeenCalled();
97
-
98
- warnSpy.mockRestore();
99
- });
100
- });