feat: added are you sure dialog

This commit is contained in:
Dan Ditomaso
2025-03-09 12:57:37 -04:00
parent 39f26f475b
commit eca5d780c1
26 changed files with 669 additions and 147 deletions
+10 -4
View File
@@ -1,13 +1,13 @@
import { useDevice } from "@core/stores/deviceStore.ts";
import { RemoveNodeDialog } from "@components/Dialog/RemoveNodeDialog.tsx";
import { DeviceNameDialog } from "@components/Dialog/DeviceNameDialog.tsx";
import { ImportDialog } from "@components/Dialog/ImportDialog.tsx";
import { PkiBackupDialog } from "./PKIBackupDialog.tsx";
import { PkiBackupDialog } from "@components/Dialog/PKIBackupDialog.tsx";
import { QRDialog } from "@components/Dialog/QRDialog.tsx";
import { RebootDialog } from "@components/Dialog/RebootDialog.tsx";
import { ShutdownDialog } from "@components/Dialog/ShutdownDialog.tsx";
import { useDevice } from "@core/stores/deviceStore.ts";
import { NodeDetailsDialog } from "./NodeDetailsDialog.tsx";
import { NodeDetailsDialog } from "@components/Dialog/NodeDetailsDialog.tsx";
import { UnsafeRolesDialog } from "@components/Dialog/UnsafeRolesDialog/UnsafeRolesDialog.tsx";
export const DialogManager = () => {
const { channels, config, dialog, setDialogOpen } = useDevice();
@@ -64,6 +64,12 @@ export const DialogManager = () => {
setDialogOpen("nodeDetails", open);
}}
/>
<UnsafeRolesDialog
open={dialog.unsafeRoles}
onOpenChange={(open) => {
setDialogOpen("unsafeRoles", open);
}}
/>
</>
);
};
+2 -2
View File
@@ -1,6 +1,6 @@
import { create, fromBinary } from "@bufbuild/protobuf";
import { Button } from "@components/UI/Button.tsx";
import { Checkbox } from "@components/UI/Checkbox.tsx";
import { Checkbox } from "../UI/Checkbox/index.tsx";
import {
Dialog,
DialogContent,
@@ -50,7 +50,7 @@ export const ImportDialog = ({
const paddedString = encodedChannelConfig
.padEnd(
encodedChannelConfig.length +
((4 - (encodedChannelConfig.length % 4)) % 4),
((4 - (encodedChannelConfig.length % 4)) % 4),
"=",
)
.replace(/-/g, "+")
+7 -9
View File
@@ -1,5 +1,5 @@
import { create, toBinary } from "@bufbuild/protobuf";
import { Checkbox } from "@components/UI/Checkbox.tsx";
import { Checkbox } from "../UI/Checkbox/index.tsx";
import {
Dialog,
DialogContent,
@@ -77,8 +77,8 @@ export const QRDialog = ({
{channel.settings?.name.length
? channel.settings.name
: channel.role === Protobuf.Channel.Channel_Role.PRIMARY
? "Primary"
: `Channel: ${channel.index}`}
? "Primary"
: `Channel: ${channel.index}`}
</Label>
<Checkbox
key={channel.index}
@@ -106,22 +106,20 @@ export const QRDialog = ({
<div className="flex justify-center">
<button
type="button"
className={`border-slate-900 border-t border-l border-b rounded-l h-10 px-7 py-2 text-sm font-medium focus:outline-hidden focus:ring-2 focus:ring-offset-2 ${
qrCodeAdd
className={`border-slate-900 border-t border-l border-b rounded-l h-10 px-7 py-2 text-sm font-medium focus:outline-hidden focus:ring-2 focus:ring-offset-2 ${qrCodeAdd
? "focus:ring-green-800 bg-green-800 text-white"
: "focus:ring-slate-400 bg-slate-400 hover:bg-green-600"
}`}
}`}
onClick={() => setQrCodeAdd(true)}
>
Add Channels
</button>
<button
type="button"
className={`border-slate-900 border-t border-r border-b rounded-r h-10 px-4 py-2 text-sm font-medium focus:outline-hidden focus:ring-2 focus:ring-offset-2 ${
!qrCodeAdd
className={`border-slate-900 border-t border-r border-b rounded-r h-10 px-4 py-2 text-sm font-medium focus:outline-hidden focus:ring-2 focus:ring-offset-2 ${!qrCodeAdd
? "focus:ring-green-800 bg-green-800 text-white"
: "focus:ring-slate-400 bg-slate-400 hover:bg-green-600"
}`}
}`}
onClick={() => setQrCodeAdd(false)}
>
Replace Channels
@@ -0,0 +1,51 @@
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
} from "@components/UI/Dialog.tsx";
import { Link } from "@components/UI/Typography/Link.tsx";
import { Checkbox } from "../../UI/Checkbox/index.tsx";
import { Label } from "@components/UI/Label.tsx";
import { Button } from "@components/UI/Button.tsx";
import { useUnsafeRoles } from "@components/Dialog/UnsafeRolesDialog/useUnsafeRoles.ts";
export interface RouterRoleDialogProps {
open: boolean;
onOpenChange: (open: boolean) => void;
}
export const UnsafeRolesDialog = ({ open, onOpenChange }: RouterRoleDialogProps) => {
const { getConfirmState, toggleConfirmState, handleCloseDialog } = useUnsafeRoles();
const deivceRoleLink = "https://meshtastic.org/docs/configuration/radio/device/";
const choosingTheRightDeviceRoleLink = "https://meshtastic.org/blog/choosing-the-right-device-role/";
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="max-w-8 flex flex-col">
<DialogHeader>
<DialogTitle>Are you sure?</DialogTitle>
</DialogHeader>
<DialogDescription className="text-md">
I have read the <Link href={deivceRoleLink} className="">Device Role Documentation</Link>{" "}
and the blog post about <Link href={choosingTheRightDeviceRoleLink}>Choosing The Right Device Role</Link> and understand the implications of changing the role.
</DialogDescription>
<div className="flex items-center gap-2">
<Checkbox id="routerRole" checked={getConfirmState()} onChange={toggleConfirmState}>
Yes, I know what I'm doing
</Checkbox>
</div>
<DialogFooter className="mt-6">
<Button variant="default" name="dismiss" onClick={() => handleCloseDialog("dismiss")}>
Dismiss
</Button>
<Button variant="default" name="confirm" disabled={!getConfirmState()} onClick={() => handleCloseDialog("confirm")}>
Confirm
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
);
};
@@ -0,0 +1,40 @@
import { useState, useCallback } from "react";
import { useDevice } from "@core/stores/deviceStore.ts";
import useLocalStorage from "@core/hooks/useLocalStorage.ts";
export const useUnsafeRoles = () => {
const [agreedToUnSafeRoles, setAgreedToUnsafeRoles] = useLocalStorage("agreeToUnsafeRole", false);
const [_confirmState, _setConfirmState] = useState(false);
const { setDialogOpen } = useDevice();
const toggleConfirmState = useCallback(() => {
setConfirmState(!_confirmState);
}, [_confirmState]);
const setConfirmState = useCallback((state: boolean) => {
_setConfirmState(state);
}, [_setConfirmState]);
const getConfirmState = useCallback(() => {
return _confirmState;
}, [_confirmState]);
const handleCloseDialog = useCallback((closeState: "dismiss" | "confirm") => {
if (closeState === "dismiss") {
setAgreedToUnsafeRoles(false);
setConfirmState(false);
}
if (closeState === "confirm") {
setAgreedToUnsafeRoles(true);
setConfirmState(false);
}
setDialogOpen("unsafeRoles", false);
}, [setDialogOpen, setAgreedToUnsafeRoles]);
return {
getConfirmState,
toggleConfirmState,
handleCloseDialog,
agreedToUnSafeRoles
};
};
+21 -17
View File
@@ -19,28 +19,32 @@ export interface MultiSelectFieldProps<T> extends BaseFormBuilderProps<T> {
};
}
const formatEnumDisplay = (name: string): string => {
return name
.replace(/_/g, " ")
.toLowerCase()
.split(" ")
.map((s) => s.charAt(0).toUpperCase() + s.substring(1))
.join(" ");
};
export function MultiSelectInput<T extends FieldValues>({
field,
}: GenericFormElementProps<T, MultiSelectFieldProps<T>>) {
const { enumValue, formatEnumName, ...remainingProperties } =
field.properties;
// Make sure to filter out the UNSET value, as it shouldn't be shown in the UI
const optionsEnumValues = enumValue
? Object.entries(enumValue)
.filter((value) => typeof value[1] === "number")
.filter((value) => value[0] !== "UNSET")
: [];
const valueToKeyMap: Record<string, string> = {};
const optionsEnumValues: [string, number][] = [];
const formatName = (name: string) => {
if (!formatEnumName) return name;
return name
.replace(/_/g, " ")
.toLowerCase()
.split(" ")
.map((s) => s.charAt(0).toUpperCase() + s.substring(1))
.join(" ");
};
if (enumValue) {
Object.entries(enumValue).forEach(([key, val]) => {
if (typeof val === "number" && key !== "UNSET") {
valueToKeyMap[val.toString()] = key;
optionsEnumValues.push([key, val as number]);
}
});
}
return (
<MultiSelect {...remainingProperties}>
@@ -52,9 +56,9 @@ export function MultiSelectInput<T extends FieldValues>({
checked={field.isChecked(name)}
onCheckedChange={() => field.onValueChange(name)}
>
{formatEnumName ? formatName(name) : name}
{formatEnumName ? formatEnumDisplay(name) : name}
</MultiSelectItem>
))}
</MultiSelect>
);
}
}
+77 -47
View File
@@ -9,11 +9,12 @@ import {
SelectTrigger,
SelectValue,
} from "@components/UI/Select.tsx";
import { Controller, type FieldValues } from "react-hook-form";
import { useController, type FieldValues } from "react-hook-form";
export interface SelectFieldProps<T> extends BaseFormBuilderProps<T> {
type: "select";
selectChange?: (e: string) => void;
selectChange?: (e: string, name: string) => void;
onBeforeChange?: (newValue: string, prevValue: string) => Promise<string | false>;
properties: BaseFormBuilderProps<T>["properties"] & {
enumValue: {
[s: string]: string | number;
@@ -22,56 +23,85 @@ export interface SelectFieldProps<T> extends BaseFormBuilderProps<T> {
};
}
const formatEnumDisplay = (name: string): string => {
return name
.replace(/_/g, " ")
.toLowerCase()
.split(" ")
.map((s) => s.charAt(0).toUpperCase() + s.substring(1))
.join(" ");
};
export function SelectInput<T extends FieldValues>({
control,
disabled,
field,
}: GenericFormElementProps<T, SelectFieldProps<T>>) {
const {
field: { value, onChange, ...rest },
} = useController({
name: field.name,
control,
});
const { enumValue, formatEnumName, ...remainingProperties } = field.properties;
const valueToKeyMap: Record<string, string> = {};
const keyToValueMap: Record<string, number> = {};
const optionsEnumValues: [string, number][] = [];
if (enumValue) {
Object.entries(enumValue).forEach(([key, val]) => {
if (typeof val === "number") {
valueToKeyMap[val.toString()] = key; // Map enum value to key
keyToValueMap[key] = val; // Map key to enum value
optionsEnumValues.push([key, val]);
}
});
}
const handleValueChange = async (newValue: string) => {
const selectedKey = valueToKeyMap[newValue];
if (!selectedKey) return;
if (field.onBeforeChange) {
try {
const result = await field.onBeforeChange(selectedKey, valueToKeyMap[value?.toString()]);
if (result === false) return;
const updatedValue = keyToValueMap[result];
if (updatedValue !== undefined) {
if (field.selectChange) field.selectChange(updatedValue.toString(), result);
onChange(updatedValue);
}
} catch (error) {
console.error("Error in onBeforeChange function:", error);
}
} else {
if (field.selectChange) field.selectChange(newValue, selectedKey);
onChange(Number.parseInt(newValue));
}
};
return (
<Controller
name={field.name}
control={control}
render={({ field: { value, onChange, ...rest } }) => {
const { enumValue, formatEnumName, ...remainingProperties } =
field.properties;
const optionsEnumValues = enumValue
? Object.entries(enumValue).filter(
(value) => typeof value[1] === "number",
)
: [];
return (
<Select
onValueChange={(e) => {
if (field.selectChange) field.selectChange(e);
onChange(Number.parseInt(e));
}}
disabled={disabled}
value={value?.toString()}
{...remainingProperties}
{...rest}
>
<SelectTrigger id={field.name}>
<SelectValue />
</SelectTrigger>
<SelectContent>
{optionsEnumValues.map(([name, value]) => (
<SelectItem key={name} value={value.toString()}>
{formatEnumName
? name
.replace(/_/g, " ")
.toLowerCase()
.split(" ")
.map((s) =>
s.charAt(0).toUpperCase() + s.substring(1)
)
.join(" ")
: name}
</SelectItem>
))}
</SelectContent>
</Select>
);
}}
/>
<Select
onValueChange={handleValueChange}
disabled={disabled}
value={value?.toString()}
{...remainingProperties}
{...rest}
>
<SelectTrigger id={field.name}>
<SelectValue />
</SelectTrigger>
<SelectContent>
{optionsEnumValues.map(([name, val]) => (
<SelectItem key={name} value={val.toString()}>
{formatEnumName ? formatEnumDisplay(name) : name}
</SelectItem>
))}
</SelectContent>
</Select>
);
}
+3 -2
View File
@@ -102,13 +102,13 @@ export const Channel = ({ channel }: SettingsPanelProps) => {
psk: pass,
positionEnabled:
channel?.settings?.moduleSettings?.positionPrecision !==
undefined &&
undefined &&
channel?.settings?.moduleSettings?.positionPrecision > 0,
preciseLocation:
channel?.settings?.moduleSettings?.positionPrecision === 32,
positionPrecision:
channel?.settings?.moduleSettings?.positionPrecision ===
undefined
undefined
? 10
: channel?.settings?.moduleSettings?.positionPrecision,
},
@@ -135,6 +135,7 @@ export const Channel = ({ channel }: SettingsPanelProps) => {
{
type: "passwordGenerator",
name: "settings.psk",
id: 'channel-psk',
label: "Pre-Shared Key",
description:
"Supported PSK lengths: 256-bit, 128-bit, 8-bit, Empty (0-bit)",
@@ -1,23 +1,44 @@
import type { DeviceValidation } from "@app/validation/config/device.tsx";
import type { DeviceValidation } from "@app/validation/config/device.ts";
import { create } from "@bufbuild/protobuf";
import { DynamicForm } from "@components/Form/DynamicForm.tsx";
import { useDevice } from "@core/stores/deviceStore.ts";
import { Protobuf } from "@meshtastic/core";
import { useUnsafeRoles } from "@components/Dialog/UnsafeRolesDialog/useUnsafeRoles.ts";
export const Device = () => {
const { config, setWorkingConfig } = useDevice();
const { config, setWorkingConfig, setDialogOpen } = useDevice();
const { agreedToUnSafeRoles } = useUnsafeRoles();
const onSubmit = (data: DeviceValidation) => {
setWorkingConfig(
create(Protobuf.Config.ConfigSchema, {
payloadVariant: {
case: "device",
value: data,
value: data
},
}),
);
};
// deno-lint-ignore require-await
async function handleOnBeforeChange(newValue: string) {
if (newValue === "ROUTER" || newValue === 'REPEATER') {
// Open the dialog to confirm the user wants to select an unsafe role
setDialogOpen('unsafeRoles', true);
// We checked the persisted value of agreedToUnSafeRoles in localStorage to see if the user has agreed to unsafe roles
if (agreedToUnSafeRoles) {
return newValue;
} else {
// If the user has not agreed to unsafe roles, we return false to prevent the role from being set
return false;
}
}
return newValue;
}
return (
<DynamicForm<DeviceValidation>
onSubmit={onSubmit}
@@ -32,23 +53,9 @@ export const Device = () => {
name: "role",
label: "Role",
description: "What role the device performs on the mesh",
onBeforeChange: handleOnBeforeChange,
properties: {
enumValue: {
Client: Protobuf.Config.Config_DeviceConfig_Role.CLIENT,
"Client Mute":
Protobuf.Config.Config_DeviceConfig_Role.CLIENT_MUTE,
Router: Protobuf.Config.Config_DeviceConfig_Role.ROUTER,
Repeater: Protobuf.Config.Config_DeviceConfig_Role.REPEATER,
Tracker: Protobuf.Config.Config_DeviceConfig_Role.TRACKER,
Sensor: Protobuf.Config.Config_DeviceConfig_Role.SENSOR,
TAK: Protobuf.Config.Config_DeviceConfig_Role.TAK,
"Client Hidden":
Protobuf.Config.Config_DeviceConfig_Role.CLIENT_HIDDEN,
"Lost and Found":
Protobuf.Config.Config_DeviceConfig_Role.LOST_AND_FOUND,
"TAK Tracker":
Protobuf.Config.Config_DeviceConfig_Role.TAK_TRACKER,
},
enumValue: Protobuf.Config.Config_DeviceConfig_Role,
formatEnumName: true,
},
},
@@ -106,4 +113,4 @@ export const Device = () => {
]}
/>
);
};
};
@@ -12,7 +12,7 @@ import { useCallback } from "react";
export const Position = () => {
const { config, setWorkingConfig } = useDevice();
const { flagsValue, activeFlags, toggleFlag, getAllFlags } = usePositionFlags(
config.position.positionFlags ?? 0,
config?.position.positionFlags ?? 0,
);
const onSubmit = (data: PositionValidation) => {
+8 -4
View File
@@ -40,16 +40,20 @@ export type ButtonVariant = VariantProps<typeof buttonVariants>["variant"];
export interface ButtonProps
extends
React.ButtonHTMLAttributes<HTMLButtonElement>,
VariantProps<typeof buttonVariants> {}
React.ButtonHTMLAttributes<HTMLButtonElement>,
VariantProps<typeof buttonVariants> { }
const Button = React.forwardRef<HTMLButtonElement, ButtonProps>(
({ className, variant, size, ...props }, ref) => {
({ className, variant, size, disabled, ...props }, ref) => {
return (
<button
type="button"
className={cn(buttonVariants({ variant, size, className }))}
className={cn(
buttonVariants({ variant, size, className }),
{ "cursor-not-allowed": disabled }
)}
ref={ref}
disabled={disabled}
{...props}
/>
);
-28
View File
@@ -1,28 +0,0 @@
import * as CheckboxPrimitive from "@radix-ui/react-checkbox";
import { Check } from "lucide-react";
import * as React from "react";
import { cn } from "@core/utils/cn.ts";
const Checkbox = React.forwardRef<
React.ElementRef<typeof CheckboxPrimitive.Root>,
React.ComponentPropsWithoutRef<typeof CheckboxPrimitive.Root>
>(({ className, ...props }, ref) => (
<CheckboxPrimitive.Root
ref={ref}
className={cn(
"peer h-4 w-4 shrink-0 rounded-xs border border-slate-300 focus:outline-hidden focus:ring-2 focus:ring-slate-400 focus:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 dark:border-slate-700 dark:text-slate-50 dark:focus:ring-slate-400 dark:focus:ring-offset-slate-900",
className,
)}
{...props}
>
<CheckboxPrimitive.Indicator
className={cn("flex items-center justify-center")}
>
<Check className="h-4 w-4" />
</CheckboxPrimitive.Indicator>
</CheckboxPrimitive.Root>
));
Checkbox.displayName = CheckboxPrimitive.Root.displayName;
export { Checkbox };
+93
View File
@@ -0,0 +1,93 @@
import { useState, useId } from "react";
import { Check } from "lucide-react";
import { Label } from "@components/UI/Label.tsx";
import { cn } from "@core/utils/cn.ts";
interface CheckboxProps {
checked?: boolean;
onChange?: (checked: boolean) => void;
className?: string;
labelClassName?: string;
id?: string;
children?: React.ReactNode;
disabled?: boolean;
required?: boolean;
name?: string;
}
export function Checkbox({
checked,
onChange,
className,
labelClassName,
id: propId,
children,
disabled = false,
required = false,
name,
...rest
}: CheckboxProps) {
const generatedId = useId();
const id = propId || generatedId;
const [isChecked, setIsChecked] = useState(checked || false);
const handleToggle = () => {
if (disabled) return;
const newChecked = !isChecked;
setIsChecked(newChecked);
onChange?.(newChecked);
};
return (
<div className={cn("flex items-center", className)}>
<div className="relative flex items-start">
<div className="flex items-center h-5">
<input
type="checkbox"
id={id}
checked={isChecked}
onChange={handleToggle}
disabled={disabled}
required={required}
name={name}
className="sr-only"
{...rest}
/>
<div
onClick={handleToggle}
role="presentation"
className={cn(
"w-6 h-6 border-2 border-gray-500 rounded-md flex items-center justify-center",
disabled ? "opacity-50 cursor-not-allowed" : "cursor-pointer focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2",
isChecked ? "" : ""
)}
>
{isChecked && (
<div className="animate-fade-in scale-100 opacity-100">
<Check className="w-4 h-4 text-slate-900 dark:text-slate-900" />
</div>
)}
</div>
</div>
{children && (
<div className="ml-3 text-sm">
<Label
htmlFor={id}
id={`${id}-label`}
className={cn(
"text-gray-900 dark:text-gray-900",
disabled ? "opacity-50 cursor-not-allowed" : "cursor-pointer",
labelClassName
)}
>
{children}
</Label>
</div>
)}
</div>
</div>
);
}
+6 -6
View File
@@ -1,8 +1,8 @@
import newGithubIssueUrl from "../../core/utils/github.ts";
import newGithubIssueUrl from "@core/utils/github.ts";
import { ExternalLink } from "lucide-react";
import { Heading } from "./Typography/Heading.tsx";
import { Link } from "./Typography/Link.tsx";
import { P } from "./Typography/P.tsx";
import { Heading } from "@components/UI/Typography/Heading.tsx";
import { Link } from "@components/UI/Typography/Link.tsx";
import { P } from "@components/UI/Typography/P.tsx";
export function ErrorPage({ error }: { error: Error }) {
@@ -11,8 +11,8 @@ export function ErrorPage({ error }: { error: Error }) {
}
return (
<article className="w-full overflow-y-auto">
<section className="flex shrink md:flex-row gap-16 mt-20 px-4 md:px-8 text-lg md:text-xl space-y-2 place-items-center">
<article className="w-full h-full overflow-y-auto dark:bg-background-primary dark:text-text-primary">
<section className="flex shrink md:flex-row gap-16 mt-20 px-4 md:px-8 text-lg md:text-xl space-y-2 place-items-center dark:bg-background-primary text-slate-900 dark:text-text-primary">
<div>
<Heading as="h2" className="text-text-primary">
This is a little embarrassing...
+1 -1
View File
@@ -12,7 +12,7 @@ export const Link = ({ href, children, className }: LinkProps) => (
target="_blank"
rel="noopener noreferrer"
className={cn(
"font-medium text-slate-900 underline underline-offset-4 dark:text-slate-50",
"font-medium text-slate-900 underline underline-offset-4 dark:text-slate-900",
className,
)}
>