Extract shared list and numeric input helpers
This commit is contained in:
27
client/src/input/listNavigation.ts
Normal file
27
client/src/input/listNavigation.ts
Normal file
@@ -0,0 +1,27 @@
|
||||
export function cycleIndex(currentIndex: number, length: number, direction: 'next' | 'prev'): number {
|
||||
if (length <= 0) return 0;
|
||||
if (direction === 'next') {
|
||||
return (currentIndex + 1) % length;
|
||||
}
|
||||
return (currentIndex - 1 + length) % length;
|
||||
}
|
||||
|
||||
export function findNextIndexByInitial<T>(
|
||||
entries: readonly T[],
|
||||
currentIndex: number,
|
||||
key: string,
|
||||
labelFor: (entry: T) => string,
|
||||
): number {
|
||||
if (entries.length === 0 || key.length !== 1 || !/[a-z]/i.test(key)) {
|
||||
return -1;
|
||||
}
|
||||
const target = key.toLowerCase();
|
||||
for (let step = 1; step <= entries.length; step += 1) {
|
||||
const candidateIndex = (currentIndex + step) % entries.length;
|
||||
const label = labelFor(entries[candidateIndex]).trim().toLowerCase();
|
||||
if (label.startsWith(target)) {
|
||||
return candidateIndex;
|
||||
}
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
19
client/src/input/numeric.ts
Normal file
19
client/src/input/numeric.ts
Normal file
@@ -0,0 +1,19 @@
|
||||
export function snapNumberToStep(value: number, step: number, anchor = 0): number {
|
||||
if (!(step > 0) || !Number.isFinite(value) || !Number.isFinite(anchor)) {
|
||||
return value;
|
||||
}
|
||||
const normalized = Math.round((value - anchor) / step) * step + anchor;
|
||||
const decimals = step >= 1 ? 0 : Math.min(6, Math.ceil(Math.abs(Math.log10(step))) + 1);
|
||||
return Number(normalized.toFixed(decimals));
|
||||
}
|
||||
|
||||
export function formatSteppedNumber(value: number, step: number): string {
|
||||
const decimals = step >= 1 ? 0 : Math.min(6, Math.ceil(Math.abs(Math.log10(step))) + 1);
|
||||
if (decimals <= 0) {
|
||||
return String(Math.round(value));
|
||||
}
|
||||
return value
|
||||
.toFixed(decimals)
|
||||
.replace(/(\.\d*?[1-9])0+$/u, '$1')
|
||||
.replace(/\.0+$/u, '');
|
||||
}
|
||||
Reference in New Issue
Block a user