import type React from 'react'; import { useEffect, useState } from 'react'; import { fromByteArray, toByteArray } from 'base64-js'; import { useForm } from 'react-hook-form'; import { FiSave } from 'react-icons/fi'; import { MdRefresh, MdVisibility, MdVisibilityOff } from 'react-icons/md'; import { IconButton } from '@components/generic/button/IconButton'; import { Checkbox } from '@components/generic/form/Checkbox'; import { Form } from '@components/generic/form/Form'; import { Input } from '@components/generic/form/Input'; import { Select } from '@components/generic/form/Select'; import { connection } from '@core/connection'; import { Protobuf } from '@meshtastic/meshtasticjs'; export interface SettingsPanelProps { channel: Protobuf.Channel; } export const SettingsPanel = ({ channel }: SettingsPanelProps): JSX.Element => { const [loading, setLoading] = useState(false); const [keySize, setKeySize] = useState<128 | 256>(256); const [pskHidden, setPskHidden] = useState(true); const { register, handleSubmit, setValue, formState, reset } = useForm< Omit & { psk: string; enabled: boolean } >({ 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)), }, }); 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(async (data) => { setLoading(true); const channelData = Protobuf.Channel.create({ 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 ?? ''), }, }); await connection.setChannel(channelData, (): Promise => { reset({ ...data }); setLoading(false); return Promise.resolve(); }); }); return (
{channel?.index !== 0 && ( <> )} { setPskHidden(!pskHidden); }} icon={pskHidden ? : } /> { const key = new Uint8Array(keySize); crypto.getRandomValues(key); setValue('psk', fromByteArray(key)); }} icon={} /> } {...register('psk')} />
=> { await onSubmit(); }} icon={} />
); };