@orsetra/shared-ui 1.10.26 → 1.10.28

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,33 +1,6 @@
1
1
  import React from 'react';
2
- import { Input } from '../../ui/input';
2
+ import QuantitySelect, { type QuantitySelectProps } from '../QuantitySelect';
3
3
 
4
- type Props = {
5
- value?: any;
6
- id: string;
7
- onChange: (value: any) => void;
8
- disabled: boolean;
9
- };
10
-
11
- const CPUNumber: React.FC<Props> = ({ value, id, onChange, disabled }) => {
12
- const initValue = value ? parseFloat(value) : undefined;
13
-
14
- const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
15
- onChange(e.target.value);
16
- };
17
-
18
- return (
19
- <div className="flex items-center gap-2">
20
- <Input
21
- id={id}
22
- type="number"
23
- disabled={disabled}
24
- onChange={handleChange}
25
- value={initValue}
26
- className="flex-1"
27
- />
28
- <span className="text-sm text-ibm-gray-70">Core</span>
29
- </div>
30
- );
31
- };
4
+ const CPUNumber: React.FC<QuantitySelectProps> = props => <QuantitySelect {...props} kind="cpu" />;
32
5
 
33
6
  export default CPUNumber;
@@ -1,34 +1,6 @@
1
1
  import React from 'react';
2
- import { Input } from '../../ui/input';
2
+ import QuantitySelect, { type QuantitySelectProps } from '../QuantitySelect';
3
3
 
4
- type Props = {
5
- id: string;
6
- onChange: (value: any) => void;
7
- value?: any;
8
- disabled: boolean;
9
- };
10
-
11
- const DiskNumber: React.FC<Props> = ({ value, id, onChange, disabled }) => {
12
- const initValue = value ? parseInt(value.replace('Gi', ''), 10) : undefined;
13
-
14
- const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
15
- onChange(e.target.value + 'Gi');
16
- };
17
-
18
- return (
19
- <div className="flex items-center gap-2">
20
- <Input
21
- id={id}
22
- type="number"
23
- min="0"
24
- disabled={disabled}
25
- onChange={handleChange}
26
- value={initValue}
27
- className="flex-1"
28
- />
29
- <span className="text-sm text-ibm-gray-70">Gi</span>
30
- </div>
31
- );
32
- };
4
+ const DiskNumber: React.FC<QuantitySelectProps> = props => <QuantitySelect {...props} kind="disk" />;
33
5
 
34
6
  export default DiskNumber;
@@ -1,34 +1,6 @@
1
1
  import React from 'react';
2
- import { Input } from '../../ui/input';
2
+ import QuantitySelect, { type QuantitySelectProps } from '../QuantitySelect';
3
3
 
4
- type Props = {
5
- id: string;
6
- onChange: (value: any) => void;
7
- value?: any;
8
- disabled: boolean;
9
- };
10
-
11
- const MemoryNumber: React.FC<Props> = ({ value, id, onChange, disabled }) => {
12
- const initValue = value ? parseInt(value.replace('Mi', ''), 10) : undefined;
13
-
14
- const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
15
- onChange(e.target.value + 'Mi');
16
- };
17
-
18
- return (
19
- <div className="flex items-center gap-2">
20
- <Input
21
- id={id}
22
- type="number"
23
- min="0"
24
- disabled={disabled}
25
- onChange={handleChange}
26
- value={initValue}
27
- className="flex-1"
28
- />
29
- <span className="text-sm text-ibm-gray-70">Mi</span>
30
- </div>
31
- );
32
- };
4
+ const MemoryNumber: React.FC<QuantitySelectProps> = props => <QuantitySelect {...props} kind="memory" />;
33
5
 
34
6
  export default MemoryNumber;
@@ -0,0 +1,66 @@
1
+ import React, { useEffect, useRef, useState } from 'react';
2
+ import { Input } from '../../ui/input';
3
+ import { formatQuantity, parseQuantity, unitsFor, type QuantityUnit } from '../../../lib/quantity';
4
+
5
+ export type QuantityInputProps = {
6
+ id: string;
7
+ value?: any;
8
+ onChange: (value: any) => void;
9
+ disabled?: boolean;
10
+ className?: string;
11
+ };
12
+
13
+ type Props = QuantityInputProps & {
14
+ units: QuantityUnit[];
15
+ step?: string;
16
+ };
17
+
18
+ const QuantityInput: React.FC<Props> = ({ id, value, onChange, disabled, className, units, step = 'any' }) => {
19
+ const parsed = parseQuantity(value, units);
20
+ const [amount, setAmount] = useState(parsed.amount);
21
+ const [suffix, setSuffix] = useState(parsed.unit.suffix);
22
+ const lastEmitted = useRef<any>(value);
23
+
24
+ useEffect(() => {
25
+ if (value === lastEmitted.current) return;
26
+ lastEmitted.current = value;
27
+ const next = parseQuantity(value, units);
28
+ setAmount(next.amount);
29
+ if (next.amount !== '') setSuffix(next.unit.suffix);
30
+ // eslint-disable-next-line react-hooks/exhaustive-deps
31
+ }, [value]);
32
+
33
+ const emit = (nextAmount: string, nextSuffix: string) => {
34
+ const quantity = formatQuantity(nextAmount, nextSuffix);
35
+ lastEmitted.current = quantity;
36
+ onChange(quantity);
37
+ };
38
+
39
+ return (
40
+ <div className="flex items-stretch">
41
+ <Input
42
+ id={id}
43
+ type="number"
44
+ min="0"
45
+ step={step}
46
+ disabled={disabled}
47
+ value={amount}
48
+ onChange={event => { setAmount(event.target.value); emit(event.target.value, suffix); }}
49
+ className={`flex-1 rounded-none ${className ?? ''}`}
50
+ />
51
+ <select
52
+ aria-label="Unit"
53
+ disabled={disabled}
54
+ value={suffix}
55
+ onChange={event => { setSuffix(event.target.value); emit(amount, event.target.value); }}
56
+ className="w-32 -ml-px border border-ibm-gray-30 bg-ibm-gray-10 px-2 text-sm text-ibm-gray-100 rounded-none focus:outline-none focus:border-ibm-blue-60 disabled:opacity-50"
57
+ >
58
+ {unitsFor(value, units).map(unit => (
59
+ <option key={unit.suffix} value={unit.suffix}>{unit.label}</option>
60
+ ))}
61
+ </select>
62
+ </div>
63
+ );
64
+ };
65
+
66
+ export default QuantityInput;
@@ -0,0 +1,50 @@
1
+ import React from 'react';
2
+ import { SelectInput } from '../../ui/select-input';
3
+ import {
4
+ QUANTITY_CHOICES, choicesWith, describeQuantity, matchingChoice,
5
+ type QuantityChoice, type QuantityKind,
6
+ } from '../../../lib/quantity';
7
+
8
+ export type QuantitySelectProps = {
9
+ id: string;
10
+ value?: any;
11
+ onChange: (value: any) => void;
12
+ disabled?: boolean;
13
+ className?: string;
14
+ /** The amounts a form offers in place of the usual ones; a label left out is written from the value. */
15
+ options?: Array<{ value: string; label?: string }>;
16
+ };
17
+
18
+ type Props = QuantitySelectProps & {
19
+ kind: QuantityKind;
20
+ };
21
+
22
+ function offeredBy(options: QuantitySelectProps['options'], kind: QuantityKind): QuantityChoice[] {
23
+ const named = (options ?? []).filter(option => option && typeof option.value === 'string' && option.value !== '');
24
+ if (named.length === 0) return QUANTITY_CHOICES[kind];
25
+ return named.map(option => ({ value: option.value, label: option.label || describeQuantity(option.value, kind) }));
26
+ }
27
+
28
+ /**
29
+ * An amount of CPU, memory or disk, picked among a few rather than typed with a unit: a
30
+ * typed amount is easy to get wrong by a thousand, and hard to hold against a limit.
31
+ */
32
+ const QuantitySelect: React.FC<Props> = ({ id, value, onChange, disabled, className, options, kind }) => {
33
+ const offered = offeredBy(options, kind);
34
+ const shown = choicesWith(value, offered, kind);
35
+ const selected = matchingChoice(value, shown, kind)?.value ?? '';
36
+
37
+ return (
38
+ <SelectInput
39
+ id={id}
40
+ value={selected}
41
+ onChange={onChange}
42
+ options={shown}
43
+ disabled={disabled}
44
+ className={className}
45
+ placeholder="Select an amount"
46
+ />
47
+ );
48
+ };
49
+
50
+ export default QuantitySelect;
@@ -15,6 +15,8 @@ export { default as KV } from './KV'
15
15
  export { default as MemoryNumber } from './MemoryNumber'
16
16
  export { default as Numbers } from './Numbers'
17
17
  export { default as PVCSelect } from './PVCSelect'
18
+ export { default as QuantityInput } from './QuantityInput'
19
+ export { default as QuantitySelect } from './QuantitySelect'
18
20
  export { default as PolicySelect } from './PolicySelect'
19
21
  export { default as SecretKeySelect } from './SecretKeySelect'
20
22
  export { default as SecretSelect } from './SecretSelect'
@@ -0,0 +1,126 @@
1
+ export interface QuantityUnit {
2
+ suffix: string
3
+ label: string
4
+ }
5
+
6
+ export const CPU_UNITS: QuantityUnit[] = [
7
+ { suffix: "m", label: "millicores" },
8
+ { suffix: "", label: "cores" },
9
+ ]
10
+
11
+ export const MEMORY_UNITS: QuantityUnit[] = [
12
+ { suffix: "Mi", label: "Mi" },
13
+ { suffix: "Gi", label: "Gi" },
14
+ ]
15
+
16
+ export const DISK_UNITS: QuantityUnit[] = [
17
+ { suffix: "Gi", label: "Gi" },
18
+ { suffix: "Mi", label: "Mi" },
19
+ { suffix: "Ti", label: "Ti" },
20
+ ]
21
+
22
+ export interface ParsedQuantity {
23
+ amount: string
24
+ unit: QuantityUnit
25
+ }
26
+
27
+ const QUANTITY = /^([0-9]*\.?[0-9]+)\s*([A-Za-z]*)$/
28
+
29
+ export function parseQuantity(value: unknown, units: QuantityUnit[]): ParsedQuantity {
30
+ const fallback = units[0]
31
+ if (value === undefined || value === null || value === "") return { amount: "", unit: fallback }
32
+
33
+ const match = QUANTITY.exec(String(value).trim())
34
+ if (!match) return { amount: "", unit: fallback }
35
+
36
+ const [, amount, suffix] = match
37
+ const unit = units.find(candidate => candidate.suffix === suffix) ?? { suffix, label: suffix }
38
+ return { amount, unit }
39
+ }
40
+
41
+ export function formatQuantity(amount: string, suffix: string): string {
42
+ const text = (amount ?? "").trim()
43
+ if (text === "" || Number.isNaN(Number(text))) return ""
44
+ return `${Number(text)}${suffix}`
45
+ }
46
+
47
+ export function unitsFor(value: unknown, units: QuantityUnit[]): QuantityUnit[] {
48
+ const { unit } = parseQuantity(value, units)
49
+ return units.some(candidate => candidate.suffix === unit.suffix) ? units : [...units, unit]
50
+ }
51
+
52
+ export type QuantityKind = "cpu" | "memory" | "disk"
53
+
54
+ export interface QuantityChoice {
55
+ value: string
56
+ label: string
57
+ }
58
+
59
+ const BINARY_UNITS: Record<string, number> = { Ki: 1 / 1024, Mi: 1, Gi: 1024, Ti: 1024 * 1024 }
60
+
61
+ /**
62
+ * An amount in the one unit its kind is counted in — thousandths of a CPU, or MiB — so that
63
+ * two ways of writing the same amount compare equal: "1" and "1000m", "1Gi" and "1024Mi".
64
+ * NaN for what is not an amount of that kind.
65
+ */
66
+ export function amountOf(value: unknown, kind: QuantityKind): number {
67
+ if (value === undefined || value === null) return Number.NaN
68
+ const match = QUANTITY.exec(String(value).trim())
69
+ if (!match) return Number.NaN
70
+ const number = Number(match[1])
71
+ const suffix = match[2]
72
+ if (kind === "cpu") {
73
+ if (suffix === "m") return number
74
+ return suffix === "" ? number * 1000 : Number.NaN
75
+ }
76
+ const factor = BINARY_UNITS[suffix]
77
+ return factor === undefined ? Number.NaN : number * factor
78
+ }
79
+
80
+ function rounded(number: number): string {
81
+ return String(Math.round(number * 1000) / 1000)
82
+ }
83
+
84
+ /** An amount said the way the forms say it: "0.5 CPU", "512 MB", "2 GB". */
85
+ export function describeQuantity(value: unknown, kind: QuantityKind): string {
86
+ const amount = amountOf(value, kind)
87
+ if (Number.isNaN(amount)) return String(value ?? "")
88
+ if (kind === "cpu") return `${rounded(amount / 1000)} CPU`
89
+ if (amount >= 1024 * 1024) return `${rounded(amount / (1024 * 1024))} TB`
90
+ if (amount >= 1024) return `${rounded(amount / 1024)} GB`
91
+ return `${rounded(amount)} MB`
92
+ }
93
+
94
+ function choices(values: string[], kind: QuantityKind): QuantityChoice[] {
95
+ return values.map(value => ({ value, label: describeQuantity(value, kind) }))
96
+ }
97
+
98
+ /** What a CPU, memory or disk field offers when its form names no choices of its own. */
99
+ export const QUANTITY_CHOICES: Record<QuantityKind, QuantityChoice[]> = {
100
+ cpu: choices(["100m", "125m", "200m", "250m", "500m", "750m", "1000m", "1500m", "2000m", "4000m"], "cpu"),
101
+ memory: choices(["128Mi", "256Mi", "512Mi", "1Gi", "2Gi", "4Gi", "8Gi"], "memory"),
102
+ disk: choices(["100Mi", "500Mi", "1Gi", "2Gi", "5Gi", "10Gi", "20Gi", "50Gi", "100Gi"], "disk"),
103
+ }
104
+
105
+ /** The choice that is the same amount as a value, however the value is written. */
106
+ export function matchingChoice(value: unknown, offered: QuantityChoice[], kind: QuantityKind): QuantityChoice | undefined {
107
+ const amount = amountOf(value, kind)
108
+ if (Number.isNaN(amount)) return offered.find(choice => choice.value === value)
109
+ return offered.find(choice => amountOf(choice.value, kind) === amount)
110
+ }
111
+
112
+ /**
113
+ * The choices a field shows. A value already stored that is none of them is kept as a
114
+ * choice of its own, marked as such, in its place by size: opening a form never changes
115
+ * what is stored, and an amount that was typed by mistake is seen for what it is.
116
+ */
117
+ export function choicesWith(value: unknown, offered: QuantityChoice[], kind: QuantityKind): QuantityChoice[] {
118
+ const text = value === undefined || value === null ? "" : String(value).trim()
119
+ if (text === "" || matchingChoice(text, offered, kind)) return offered
120
+
121
+ const current: QuantityChoice = { value: text, label: `${describeQuantity(text, kind)} (current value)` }
122
+ const amount = amountOf(text, kind)
123
+ if (Number.isNaN(amount)) return [...offered, current]
124
+ const after = offered.findIndex(choice => amountOf(choice.value, kind) > amount)
125
+ return after < 0 ? [...offered, current] : [...offered.slice(0, after), current, ...offered.slice(after)]
126
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@orsetra/shared-ui",
3
- "version": "1.10.26",
3
+ "version": "1.10.28",
4
4
  "description": "Shared UI components for Orsetra platform",
5
5
  "main": "./index.ts",
6
6
  "types": "./index.ts",
@@ -104,10 +104,18 @@
104
104
  "zod": "^3.24.1"
105
105
  },
106
106
  "devDependencies": {
107
+ "@swc/core": "^1.16.18",
108
+ "@swc/jest": "^0.2.39",
109
+ "@types/jest": "^30.0.0",
107
110
  "@types/js-yaml": "^4.0.9",
108
111
  "@types/lodash": "^4.17.24",
109
112
  "@types/react": "^19",
113
+ "jest": "^30.5.2",
114
+ "jest-environment-node": "^30.5.2",
110
115
  "next": "^16.0.7",
111
116
  "typescript": "^5"
117
+ },
118
+ "scripts": {
119
+ "test": "jest"
112
120
  }
113
121
  }