parse hex and binary numbers, allow ids to be entered as hex or binary

This commit is contained in:
Rachel Powers
2024-04-16 16:35:00 -07:00
parent ad55b65755
commit fdec8c7639
2 changed files with 37 additions and 3 deletions

View File

@@ -175,5 +175,38 @@ export function parseNumber(s: string): number {
case 'epsilon':
return Number.EPSILON;
}
if (/^%[01]+$/.test(s)) {
return parseInt(s.slice(1), 2)
}
if (/^\$[0-9A-Fa-f]+$/.test(s)) {
return parseInt(s.slice(1), 16)
}
const hex = parseHex(s);
if (!isNaN(hex)) {
return hex;
}
return parseFloat(s);
}
export function parseHex(h: string) : number {
var val = parseInt(h, 16);
if (val.toString(16) === h.toLowerCase()) {
return val;
} else {
return NaN;
}
}
export function parseIntWithHexOrBinary(s: string): number {
if (/^%[01]+$/.test(s)) {
return parseInt(s.slice(1), 2)
}
if (/^\$[0-9A-Fa-f]+$/.test(s)) {
return parseInt(s.slice(1), 16)
}
const hex = parseHex(s);
if (!isNaN(hex)) {
return hex;
}
return parseInt(s);
}

View File

@@ -34,7 +34,7 @@ import "@shoelace-style/shoelace/dist/components/drawer/drawer.js";
import "@shoelace-style/shoelace/dist/components/icon/icon.js";
import SlInput from "@shoelace-style/shoelace/dist/components/input/input.js";
import { parseNumber, structuralEqual } from "../utils";
import { parseIntWithHexOrBinary, parseNumber, structuralEqual } from "../utils";
import SlSelect from "@shoelace-style/shoelace/dist/components/select/select.js";
import SlDrawer from "@shoelace-style/shoelace/dist/components/drawer/drawer.js";
import { DeviceDB, DeviceDBEntry } from "./device_db";
@@ -339,7 +339,7 @@ export class VMDeviceCard extends VMDeviceMixin(BaseElement) {
_handleChangeID(e: CustomEvent) {
const input = e.target as SlInput;
const val = input.valueAsNumber;
const val = parseIntWithHexOrBinary(input.value);
if (!isNaN(val)) {
window.VM.changeDeviceId(this.deviceID, val);
} else {
@@ -349,7 +349,8 @@ export class VMDeviceCard extends VMDeviceMixin(BaseElement) {
_handleChangeName(e: CustomEvent) {
const input = e.target as SlInput;
window.VM?.setDeviceName(this.deviceID, input.value);
const name = input.value.length === 0 ? undefined : input.value;
window.VM?.setDeviceName(this.deviceID, name);
this.updateDevice();
}