1 import { clx, Input, Text } from "@medusajs/ui"
2 import { ComponentPropsWithoutRef, ElementRef, forwardRef } from "react"
3
4 type QuantityInputProps = Omit<
5 ComponentPropsWithoutRef<typeof Input>,
6 "type"
7 > & {
8 /**
9 * The unit the quantity is counted in, e.g. `lb`. When omitted the input is
10 * rendered unchanged.
11 */
12 unitOfMeasure?: string | null
13 }
14
15 /**
16 * A number input that renders an inventory item's unit of measure as a suffix,
17 * so a fractional quantity reads as `0.25 | lb`.
18 *
19 * The unit is a sibling of the input rather than an overlay on top of it:
20 * padding the input to make room would shrink its content box, and browsers
21 * anchor the native number stepper to that box, leaving the stepper floating
22 * short of the separator.
23 */
24 export const QuantityInput = forwardRef<
25 ElementRef<typeof Input>,
26 QuantityInputProps
27 >(({ unitOfMeasure, className, size = "base", ...props }, ref) => {
28 if (!unitOfMeasure) {
29 return (
30 <Input
31 ref={ref}
32 type="number"
33 size={size}
34 className={className}
35 {...props}
36 />
37 )
38 }
39
40 const isInvalid =
41 props["aria-invalid"] === true || props["aria-invalid"] === "true"
42
43 return (
44 <div
45 className={clx(
46 "bg-ui-bg-field shadow-borders-base transition-fg flex w-full items-center overflow-hidden rounded-md",
47 "hover:bg-ui-bg-field-hover",
48 "focus-within:shadow-borders-interactive-with-active",
49 size === "small" ? "h-7" : "h-8",
50 isInvalid && "!shadow-borders-error",
51 className
52 )}
53 >
54 <input
55 ref={ref}
56 type="number"
57 className={clx(
58 "txt-compact-small text-ui-fg-base placeholder-ui-fg-muted",
59 "size-full min-w-0 flex-1 appearance-none bg-transparent px-2 outline-none",
60 "disabled:text-ui-fg-disabled disabled:cursor-not-allowed",
61 size === "small" ? "py-1" : "py-1.5"
62 )}
63 {...props}
64 />
65 <div className="flex h-full max-w-16 shrink-0 items-center border-l px-2">
66 <Text
67 className="text-ui-fg-muted truncate"
68 size="small"
69 leading="compact"
70 weight="plus"
71 >
72 {unitOfMeasure}
73 </Text>
74 </div>
75 </div>
76 )
77 })
78 QuantityInput.displayName = "QuantityInput"