import type React from "react"; import { useEffect } from "react"; import { Controller, useForm, useWatch } from "react-hook-form"; import { toast } from "react-hot-toast"; import { BitwiseSelect } from "@app/components/form/BitwiseSelect.js"; import { FormSection } from "@app/components/form/FormSection.js"; import { Input } from "@app/components/form/Input.js"; import { Toggle } from "@app/components/form/Toggle.js"; import { PositionValidation } from "@app/validation/config/position.js"; import { Form } from "@components/form/Form"; import { useDevice } from "@core/providers/useDevice.js"; import { classValidatorResolver } from "@hookform/resolvers/class-validator"; import { Protobuf } from "@meshtastic/meshtasticjs"; export const Position = (): JSX.Element => { const { config, connection, nodes, hardware } = useDevice(); const myNode = nodes.find((n) => n.data.num === hardware.myNodeNum); const { register, handleSubmit, formState: { errors, isDirty }, reset, control } = useForm({ defaultValues: { fixedAlt: myNode?.data.position?.altitude, fixedLat: (myNode?.data.position?.latitudeI ?? 0) / 1e7, fixedLng: (myNode?.data.position?.longitudeI ?? 0) / 1e7, ...config.position }, resolver: classValidatorResolver(PositionValidation) }); const fixedPositionEnabled = useWatch({ control, name: "fixedPosition", defaultValue: false }); useEffect(() => { reset({ fixedAlt: myNode?.data.position?.altitude, fixedLat: (myNode?.data.position?.latitudeI ?? 0) / 1e7, fixedLng: (myNode?.data.position?.longitudeI ?? 0) / 1e7, ...config.position }); }, [reset, config.position, myNode?.data.position]); const onSubmit = handleSubmit((data) => { const { fixedAlt, fixedLat, fixedLng, ...rest } = data; const configHasChanged = !Protobuf.Config_PositionConfig.equals( config.position, Protobuf.Config_PositionConfig.create(rest) ); if (connection) { void toast.promise( connection .setPosition({ position: Protobuf.Position.create({ altitude: fixedAlt, latitudeI: fixedLat * 1e7, longitudeI: fixedLng * 1e7 }) }) .then(() => reset({ ...data })), { loading: "Saving...", success: "Saved Position Config, Restarting Node", error: "No response received" } ); if (configHasChanged) { void toast.promise( connection .setConfig({ config: { payloadVariant: { oneofKind: "position", position: rest } } }) .then(() => reset({ ...data })), { loading: "Saving...", success: "Saved Position Config, Restarting Node", error: "No response received" } ); } } }); return (
reset(config.position)} dirty={isDirty} onSubmit={onSubmit} > ( )} /> ( )} /> { const { value, onChange } = field; const { error } = fieldState; return ( ); }} /> ( )} /> {fixedPositionEnabled && ( <> )} ); };