Merge branch 'better-modal-formatting' into 'v3'

Format values in value confirmation modal to prevent overflow.

Closes #545

See merge request openflexure/openflexure-microscope-server!384
This commit is contained in:
Julian Stirling 2025-09-08 12:23:30 +00:00 committed by GitLab
commit d6e8a9a9b3
No known key found for this signature in database
2 changed files with 52 additions and 1 deletions

View file

@ -11,6 +11,7 @@
</template>
<script>
import { formatValue } from "@/js_utils/formatter.mjs";
import InputFromSchema from "./inputFromSchema.vue";
export default {
@ -105,7 +106,7 @@ export default {
} else {
this.animate = true;
await this.modalNotify(
`Set ${this.label} to ${newVal} (closest valid value to requested ${requestedValue}).`
`Set ${this.label} to ${formatValue(newVal)} (closest valid value to requested ${formatValue(requestedValue)}).`
);
}
} else {

View file

@ -0,0 +1,50 @@
// Generic functions for formatting
/**
* Format a single number into a human-readable string.
* Uses exponential notation for very large/small numbers.
*
* @param {number} num - The number to format.
* @param {number} [maxDigits=4] - Maximum number of digits in of the formatted string.
* @returns {string} - Formatted number as a string.
*/
export function formatNumber(num, maxDigits = 4) {
if (typeof num !== "number" || isNaN(num)) return String(num);
// First convert to just a number
const normal = String(num);
// Use toPrecision to handle rounding and turnign to exponential
const rounded = num.toPrecision(maxDigits);
// Return whichever string is shorter, preventing trailing zeros on decimals
return rounded.length < normal.length ? rounded : normal;
}
/**
* Recursively format numbers inside arrays or objects.
*
* @param {any} value - Value to format (number, array, object, or other).
* @param {number} [maxDigits=4] - Maximum number of digits in each number of the formatted string.
* @returns {string} - A formatted display string.
*/
export function formatValue(value, maxDigits = 4) {
if (Array.isArray(value)) {
const items = value.map(val => formatValue(val, maxDigits));
return `[${items.join(", ")}]`;
}
if (typeof value === "object" && value !== null) {
const entries = Object.entries(value).map(([key, val]) => {
return `${key}: ${formatValue(val, maxDigits)}`;
});
return `{${entries.join(", ")}}`;
}
// Attempt to coerce to number as numbers in input boxes may be represented as strings
let asNum = Number(value);
if (!Number.isNaN(asNum)) {
return formatNumber(asNum, maxDigits);
}
// Only if the string will not coerce to a number do we output the value.
return value;
}