import type React from "react"; import { useEffect, useState } from "react"; import { fromByteArray, toByteArray } from "base64-js"; import { Controller, useForm } from "react-hook-form"; import { toast } from "react-hot-toast"; import { ChannelSettingsValidation } from "@app/validation/channelSettings.js"; import { Form } from "@components/form/Form"; import { Input } from "@components/form/Input.js"; import { Select } from "@components/form/Select.js"; import { Toggle } from "@components/form/Toggle.js"; import { useDevice } from "@core/providers/useDevice.js"; import { ArrowPathIcon, EyeIcon, EyeSlashIcon } from "@heroicons/react/24/outline"; import { classValidatorResolver } from "@hookform/resolvers/class-validator"; import { Protobuf } from "@meshtastic/meshtasticjs"; export interface SettingsPanelProps { channel: Protobuf.Channel; } export const Channel = ({ channel }: SettingsPanelProps): JSX.Element => { const { connection, addChannel } = useDevice(); const [keySize, setKeySize] = useState<128 | 256>(256); const [pskHidden, setPskHidden] = useState(true); const { register, handleSubmit, formState: { errors, isDirty }, reset, control, setValue } = useForm({ defaultValues: { enabled: [ Protobuf.Channel_Role.SECONDARY, Protobuf.Channel_Role.PRIMARY ].find((role) => role === channel?.role) ? true : false, ...channel?.settings, psk: fromByteArray(channel?.settings?.psk ?? new Uint8Array(0)) }, resolver: classValidatorResolver(ChannelSettingsValidation) }); useEffect(() => { reset({ enabled: [ Protobuf.Channel_Role.SECONDARY, Protobuf.Channel_Role.PRIMARY ].find((role) => role === channel?.role) ? true : false, ...channel?.settings, psk: fromByteArray(channel?.settings?.psk ?? new Uint8Array(0)) }); }, [channel, reset]); const onSubmit = handleSubmit((data) => { if (connection) { void toast.promise( connection .setChannel({ channel: { role: channel?.role === Protobuf.Channel_Role.PRIMARY ? Protobuf.Channel_Role.PRIMARY : data.enabled ? Protobuf.Channel_Role.SECONDARY : Protobuf.Channel_Role.DISABLED, index: channel?.index, settings: { ...data, psk: toByteArray(data.psk ?? "") } } }) .then(() => addChannel({ config: { index: channel.index, role: channel.role, settings: { ...data, psk: toByteArray(data.psk ?? "") } }, lastInterraction: new Date(), messages: [] }) ), { loading: "Saving...", success: "Saved Channel", error: "No response received" } ); } }); return (
reset({ enabled: [ Protobuf.Channel_Role.SECONDARY, Protobuf.Channel_Role.PRIMARY ].find((role) => role === channel?.role) ? true : false, ...channel?.settings, psk: fromByteArray(channel?.settings?.psk ?? new Uint8Array(0)) }) } dirty={isDirty} onSubmit={onSubmit} > {channel?.index !== 0 && ( <> ( )} /> )} ) : ( ), action: () => { setPskHidden(!pskHidden); } }} error={errors.psk?.message} {...register("psk")} /> ( )} /> ( )} /> ); };