Files
VirtWeb/virtweb_frontend/src/widgets/forms/MACInput.tsx

47 lines
1.0 KiB
TypeScript

import { TextInput } from "./TextInput";
export function MACInput(p: {
label: string;
editable: boolean;
value?: string;
onValueChange?: (newVal: string | undefined) => void;
}): React.ReactElement {
const { onValueChange, ...props } = p;
return (
<TextInput
onValueChange={(v) => {
onValueChange?.(sanitizeMacAddress(v));
}}
{...props}
/>
);
}
function sanitizeMacAddress(s: string | undefined): string | undefined {
if (s === "" || s === undefined) return s;
const split = s.split(":");
if (split.length > 6) split.splice(6);
let needAnotherIteration = false;
const res = split
.map((e) => {
if (e === "") return e;
const num = parseInt(e, 16);
if (isNaN(num)) return "0";
let s = num.toString(16).padStart(2, "0");
if (num > 0xff) {
needAnotherIteration = true;
return s.slice(0, 2) + ":" + s.slice(2);
}
return s;
})
.join(":");
return needAnotherIteration ? sanitizeMacAddress(res) : res;
}