PliWould/components/LengthInput.tsx

86 lines
2.8 KiB
TypeScript
Raw Normal View History

import { Measure, Unit, length as en_length, area as en_area } from "enheter";
import { useState } from "react";
import { Button, StyleSheet, Text, TextInput, View } from "react-native";
import { SafeAreaView } from "react-native-safe-area-context";
2024-06-27 23:31:59 +02:00
export type t_length_unit = "foot" | "inch"
export type mode = "length" | "area"
export type LengthInputProps = {
2024-06-27 23:31:59 +02:00
onMeasurementSet?: (length: Measure<"length" | "area">) => any,
isArea?: boolean,
}
2024-06-27 23:31:59 +02:00
export function MeasurementInput(props: LengthInputProps) {
const [length, setLength] = useState(null as null | number);
const [width, setWidth] = useState(null as null | number);
const [unit, setUnit] = useState("foot" as t_length_unit);
function doSetLength(text: string) {
const value = parseFloat(text);
setLength(value);
if (!props.isArea) {
const len = en_length(unit, value)
2024-06-27 23:31:59 +02:00
props.onMeasurementSet && props.onMeasurementSet(len)
} else {
const en_unit = unit == "foot" ? "squareFoot" : "squareInch"
const ar = en_area(en_unit, value);
2024-06-27 23:31:59 +02:00
props.onMeasurementSet && props.onMeasurementSet(ar);
}
}
function doSetWidth(text: string) {
const value = parseFloat(text);
setLength(value);
const len = en_length(unit, value)
2024-06-27 23:31:59 +02:00
props.onMeasurementSet && props.onMeasurementSet(len)
}
return (
<SafeAreaView>
<View style={styles.inputRow}>
<TextInput
keyboardType="number-pad"
onTouchEnd={() => setLength(null)}
value={length?.toString() || ""}
onChangeText={doSetLength}
style={styles.textInput}
/>
{props.isArea &&
(<TextInput
keyboardType="number-pad"
onTouchEnd={() => setWidth(null)}
value={length?.toString() || ""}
onChangeText={doSetWidth}
style={styles.textInput}
/>)
}
<Text style={styles.valueHint}>{unit == "foot" ? "ft" : "in"}</Text>
<Button
title="Ft"
onPress={() => setUnit("foot")}
color={unit === "foot" ? "blue" : "gray"}
/>
<Button
title="In"
onPress={() => setUnit("inch")}
color={unit === "inch" ? "blue" : "gray"}
/>
</View>
</SafeAreaView>
)
}
const styles = StyleSheet.create({
textInput: {
flexGrow: 1,
},
inputRow: {
flexDirection: "row"
},
valueHint: {
color: "grey",
margin: 5,
}
})