Browse Source

Merge pull request #555 from meshtastic/master

Merge Master into Stable
pull/593/head
Dan Ditomaso 1 year ago
committed by GitHub
parent
commit
59a72bc282
No known key found for this signature in database GPG Key ID: B5690EEEBB952194
  1. 2
      .dockerignore
  2. 2
      .github/workflows/nightly.yml
  3. 2
      .github/workflows/release.yml
  4. 10
      Containerfile
  5. 26
      README.md
  6. 1457
      deno.lock
  7. 2
      infra/.dockerignore
  8. 15
      infra/Containerfile
  9. 42
      infra/default.conf
  10. 50
      package.json
  11. 2
      src/App.tsx
  12. 108
      src/components/CommandPalette/index.tsx
  13. 7
      src/components/Dialog/DialogManager.tsx
  14. 12
      src/components/Dialog/NewDeviceDialog.tsx
  15. 114
      src/components/Dialog/RebootOTADialog.test.tsx
  16. 104
      src/components/Dialog/RebootOTADialog.tsx
  17. 77
      src/components/Form/FormInput.tsx
  18. 4
      src/components/Form/FormSelect.tsx
  19. 5
      src/components/KeyBackupReminder.tsx
  20. 5
      src/components/PageComponents/Channel.tsx
  21. 13
      src/components/PageComponents/Config/Device/index.tsx
  22. 283
      src/components/PageComponents/Config/Network/Network.test.tsx
  23. 35
      src/components/PageComponents/Config/Network/index.tsx
  24. 8
      src/components/PageComponents/Config/Position.tsx
  25. 67
      src/components/PageComponents/Map/NodeDetail.tsx
  26. 96
      src/components/Sidebar.tsx
  27. 4
      src/components/Toaster.tsx
  28. 2
      src/components/UI/Command.tsx
  29. 3
      src/components/UI/Sidebar/sidebarButton.tsx
  30. 117
      src/core/hooks/useKeyBackupReminder.tsx
  31. 52
      src/core/hooks/useLocalStorage.test.ts
  32. 65
      src/core/hooks/usePinnedItems.test.ts
  33. 19
      src/core/hooks/usePinnedItems.ts
  34. 81
      src/core/hooks/useToast.test.tsx
  35. 2
      src/core/hooks/useToast.ts
  36. 3
      src/core/stores/deviceStore.ts
  37. 10
      src/core/utils/ip.ts
  38. 3
      src/pages/Config/DeviceConfig.tsx
  39. 90
      src/pages/Nodes.tsx
  40. 82
      src/validation/config/network.ts
  41. 13
      src/validation/validate.ts
  42. 2
      vitest.config.ts

2
.dockerignore

@ -1,2 +0,0 @@
dist/build.tar
dist/output

2
.github/workflows/nightly.yml

@ -46,7 +46,7 @@ jobs:
uses: redhat-actions/buildah-build@v2
with:
containerfiles: |
./Containerfile
./infra/Containerfile
image: ${{github.event.repository.full_name}}
tags: nightly ${{ github.sha }}
oci: true

2
.github/workflows/release.yml

@ -46,7 +46,7 @@ jobs:
uses: redhat-actions/buildah-build@v2
with:
containerfiles: |
./Containerfile
./infra/Containerfile
image: ${{github.event.repository.full_name}}
tags: latest ${{ github.sha }}
oci: true

10
Containerfile

@ -1,10 +0,0 @@
FROM nginx:1.27.2-alpine
RUN rm -r /usr/share/nginx/html \
&& mkdir /usr/share/nginx/html
WORKDIR /usr/share/nginx/html
ADD dist .
CMD nginx -g "daemon off;"

26
README.md

@ -138,3 +138,29 @@ reasons:
environments.
- **Web Standard APIs**: Uses browser-compatible APIs, making code more portable
between server and client environments.
### Contributing
We welcome contributions! Here’s how the deployment flow works for pull
requests:
- **Preview Deployments:**\
Every pull request automatically generates a preview deployment on Vercel.
This allows you and reviewers to easily preview changes before merging.
- **Staging Environment (`client-test`):**\
Once your PR is merged, your changes will be available on our staging site:
[client-test.meshtastic.org](https://client-test.meshtastic.org/).\
This environment supports rapid feature iteration and testing without
impacting the production site.
- **Production Releases:**\
At regular intervals, stable and fully tested releases are promoted to our
production site: [client.meshtastic.org](https://client.meshtastic.org/).\
This is the primary interface used by the public to connect with their
Meshtastic nodes.
Please review our
[Contribution Guidelines](https://github.com/meshtastic/web/blob/master/CONTRIBUTING.md)
before submitting a pull request. We appreciate your help in making the project
better!

1457
deno.lock

File diff suppressed because it is too large

2
infra/.dockerignore

@ -0,0 +1,2 @@
../dist/build.tar
../dist/output

15
infra/Containerfile

@ -0,0 +1,15 @@
FROM nginx:1.27-alpine
RUN rm -r /usr/share/nginx/html \
&& mkdir -p /usr/share/nginx/html \
&& mkdir -p /etc/nginx/conf.d
WORKDIR /usr/share/nginx/html
ADD dist .
COPY ./infra/default.conf /etc/nginx/conf.d/default.conf
EXPOSE 8080
CMD ["nginx", "-g", "daemon off;"]

42
infra/default.conf

@ -0,0 +1,42 @@
server {
listen 8080;
server_name localhost;
root /usr/share/nginx/html;
index index.html index.htm;
location / {
try_files $uri $uri/ =404;
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
internal;
}
location ~ /\.ht {
deny all;
}
gzip on;
gzip_disable "msie6";
gzip_vary on;
gzip_proxied any;
gzip_comp_level 6;
gzip_buffers 16 8k;
gzip_http_version 1.1;
gzip_types
text/plain
text/css
text/xml
text/javascript
application/javascript
application/x-javascript
application/json
application/xml
application/xml+rss
font/ttf
font/otf
image/svg+xml;
}

50
package.json

@ -1,6 +1,6 @@
{
"name": "meshtastic-web",
"version": "2.3.3-0",
"version": "2.6.0-0",
"type": "module",
"description": "Meshtastic web client",
"license": "GPL-3.0-only",
@ -34,11 +34,12 @@
},
"homepage": "https://meshtastic.org",
"dependencies": {
"@bufbuild/protobuf": "^2.2.3",
"@meshtastic/core": "npm:@jsr/[email protected]",
"@meshtastic/core": "npm:@jsr/[email protected]",
"@meshtastic/js": "npm:@jsr/[email protected]",
"@meshtastic/transport-http": "npm:@jsr/meshtastic__transport-http",
"@meshtastic/transport-web-bluetooth": "npm:@jsr/meshtastic__transport-web-bluetooth",
"@meshtastic/transport-web-serial": "npm:@jsr/meshtastic__transport-web-serial",
"@bufbuild/protobuf": "^2.2.5",
"@noble/curves": "^1.8.1",
"@radix-ui/react-accordion": "^1.2.3",
"@radix-ui/react-checkbox": "^1.1.4",
@ -59,49 +60,50 @@
"class-validator": "^0.14.1",
"class-variance-authority": "^0.7.1",
"clsx": "^2.1.1",
"cmdk": "^1.0.4",
"cmdk": "^1.1.1",
"crypto-random-string": "^5.0.0",
"immer": "^10.1.1",
"js-cookie": "^3.0.5",
"lucide-react": "^0.477.0",
"maplibre-gl": "5.1.1",
"react": "^19.0.0",
"react-dom": "^19.0.0",
"lucide-react": "^0.486.0",
"maplibre-gl": "5.3.0",
"react": "^19.1.0",
"react-dom": "^19.1.0",
"react-error-boundary": "^5.0.0",
"react-hook-form": "^7.54.2",
"react-map-gl": "8.0.1",
"react-hook-form": "^7.55.0",
"react-map-gl": "8.0.2",
"react-qrcode-logo": "^3.0.0",
"rfc4648": "^1.5.4",
"vite-plugin-node-polyfills": "^0.23.0",
"zod": "^3.24.2",
"zustand": "5.0.3"
},
"devDependencies": {
"@tailwindcss/postcss": "^4.0.9",
"@tailwindcss/postcss": "^4.1.0",
"@testing-library/jest-dom": "^6.6.3",
"@testing-library/react": "^16.2.0",
"@testing-library/user-event": "^14.6.1",
"@types/chrome": "^0.0.307",
"@types/chrome": "^0.0.313",
"@types/js-cookie": "^3.0.6",
"@types/node": "^22.13.7",
"@types/react": "^19.0.10",
"@types/node": "^22.13.17",
"@types/react": "^19.0.12",
"@types/react-dom": "^19.0.4",
"@types/serviceworker": "^0.0.123",
"@types/serviceworker": "^0.0.127",
"@types/w3c-web-serial": "^1.0.8",
"@types/web-bluetooth": "^0.0.21",
"@vitejs/plugin-react": "^4.3.4",
"autoprefixer": "^10.4.20",
"gzipper": "^8.2.0",
"happy-dom": "^17.2.2",
"autoprefixer": "^10.4.21",
"gzipper": "^8.2.1",
"happy-dom": "^17.4.4",
"postcss": "^8.5.3",
"simple-git-hooks": "^2.11.1",
"tailwind-merge": "^3.0.2",
"tailwindcss": "^4.0.9",
"simple-git-hooks": "^2.12.1",
"tailwind-merge": "^3.1.0",
"tailwindcss": "^4.1.0",
"tailwindcss-animate": "^1.0.7",
"tar": "^7.4.3",
"testing-library": "^0.0.2",
"typescript": "^5.8.2",
"vite": "^6.2.0",
"vitest": "^3.0.7",
"vite-plugin-pwa": "^0.21.1"
"vite": "^6.2.4",
"vitest": "^3.1.1",
"vite-plugin-pwa": "^1.0.0"
}
}

2
src/App.tsx

@ -1,6 +1,5 @@
import { DeviceWrapper } from "@app/DeviceWrapper.tsx";
import { PageRouter } from "@app/PageRouter.tsx";
import { CommandPalette } from "@components/CommandPalette.tsx";
import { DeviceSelector } from "@components/DeviceSelector.tsx";
import { DialogManager } from "@components/Dialog/DialogManager.tsx";
import { NewDeviceDialog } from "@components/Dialog/NewDeviceDialog.tsx";
@ -14,6 +13,7 @@ import type { JSX } from "react";
import { ErrorBoundary } from "react-error-boundary";
import { ErrorPage } from "@components/UI/ErrorPage.tsx";
import { MapProvider } from "react-map-gl/maplibre";
import { CommandPalette } from "@components/CommandPalette/index.tsx";
export const App = (): JSX.Element => {

108
src/components/CommandPalette.tsx → src/components/CommandPalette/index.tsx

@ -1,4 +1,3 @@
import { Avatar } from "./UI/Avatar.tsx";
import {
CommandDialog,
CommandEmpty,
@ -18,7 +17,6 @@ import {
FactoryIcon,
LayersIcon,
LinkIcon,
type LucideIcon,
MapIcon,
MessageSquareIcon,
PlusIcon,
@ -29,9 +27,13 @@ import {
SmartphoneIcon,
TrashIcon,
UsersIcon,
XCircleIcon,
Pin,
type LucideIcon,
} from "lucide-react";
import { useEffect } from "react";
import { Avatar } from "@components/UI/Avatar.tsx";
import { cn } from "@core/utils/cn.ts";
import { usePinnedItems } from "@core/hooks/usePinnedItems.ts";
export interface Group {
label: string;
@ -45,7 +47,6 @@ export interface Command {
subItems?: SubItem[];
tags?: string[];
}
export interface SubItem {
label: string;
icon: React.ReactNode;
@ -57,11 +58,10 @@ export const CommandPalette = () => {
commandPaletteOpen,
setCommandPaletteOpen,
setSelectedDevice,
removeDevice,
selectedDevice,
} = useAppStore();
const { getDevices } = useDeviceStore();
const { setDialogOpen, setActivePage, connection } = useDevice();
const { pinnedItems, togglePinnedItem } = usePinnedItems({ storageName: 'pinnedCommandMenuGroups' });
const groups: Group[] = [
{
@ -113,22 +113,22 @@ export const CommandPalette = () => {
{
label: "Switch Node",
icon: ArrowLeftRightIcon,
subItems: getDevices().map((device) => {
return {
label:
device.nodes.get(device.hardware.myNodeNum)?.user?.longName ??
device.hardware.myNodeNum.toString(),
icon: (
<Avatar
text={device.nodes.get(device.hardware.myNodeNum)?.user
?.shortName ?? device.hardware.myNodeNum.toString()}
/>
),
action() {
setSelectedDevice(device.id);
},
};
}),
subItems: getDevices().map((device) => ({
label:
device.nodes.get(device.hardware.myNodeNum)?.user?.longName ??
device.hardware.myNodeNum.toString(),
icon: (
<Avatar
text={
device.nodes.get(device.hardware.myNodeNum)?.user?.shortName ??
device.hardware.myNodeNum.toString()
}
/>
),
action() {
setSelectedDevice(device.id);
},
})),
},
{
label: "Connect New Node",
@ -163,15 +163,6 @@ export const CommandPalette = () => {
},
],
},
{
label: "Disconnect",
icon: XCircleIcon,
action() {
void connection?.disconnect();
setSelectedDevice(0);
removeDevice(selectedDevice ?? 0);
},
},
{
label: "Schedule Shutdown",
icon: PowerIcon,
@ -186,6 +177,13 @@ export const CommandPalette = () => {
setDialogOpen("reboot", true);
},
},
{
label: "Reboot To OTA Mode",
icon: RefreshCwIcon,
action() {
setDialogOpen("rebootOTA", true);
},
},
{
label: "Reset Nodes",
icon: TrashIcon,
@ -231,6 +229,12 @@ export const CommandPalette = () => {
},
];
const sortedGroups = [...groups].sort((a, b) => {
const aPinned = pinnedItems.includes(a.label) ? 1 : 0;
const bPinned = pinnedItems.includes(b.label) ? 1 : 0;
return bPinned - aPinned;
});
useEffect(() => {
const handleKeydown = (e: KeyboardEvent) => {
if (e.key === "k" && (e.metaKey || e.ctrlKey)) {
@ -244,15 +248,45 @@ export const CommandPalette = () => {
}, [setCommandPaletteOpen]);
return (
<CommandDialog
open={commandPaletteOpen}
onOpenChange={setCommandPaletteOpen}
>
<CommandDialog open={commandPaletteOpen} onOpenChange={setCommandPaletteOpen}>
<CommandInput placeholder="Type a command or search..." />
<CommandList>
<CommandEmpty>No results found.</CommandEmpty>
{groups.map((group) => (
<CommandGroup key={group.label} heading={group.label}>
{sortedGroups.map((group) => (
<CommandGroup
key={group.label}
heading={
<div className="flex items-center justify-between">
<span>{group.label}</span>
<button
type="button"
onClick={() => togglePinnedItem(group.label)}
className={cn(
"transition-all duration-300 scale-100 cursor-pointer m-0.5 p-2 focus:*:data-label:opacity-100"
)}
aria-description={
pinnedItems.includes(group.label)
? "Unpin command group"
: "Pin command group"
}
>
<span
data-label
className="transition-all block absolute w-full mb-auto mt-auto ml-0 mr-0 text-xs left-0 -top-5 opacity-0 rounded-lg"
/>
<Pin
size={16}
className={cn(
"transition-opacity",
pinnedItems.includes(group.label)
? "opacity-100 text-red-500"
: "opacity-40 hover:opacity-70"
)}
/>
</button>
</div>
}
>
{group.commands.map((command) => (
<div key={command.label}>
<CommandItem

7
src/components/Dialog/DialogManager.tsx

@ -9,6 +9,7 @@ import { ShutdownDialog } from "@components/Dialog/ShutdownDialog.tsx";
import { NodeDetailsDialog } from "@components/Dialog/NodeDetailsDialog/NodeDetailsDialog.tsx";
import { UnsafeRolesDialog } from "@components/Dialog/UnsafeRolesDialog/UnsafeRolesDialog.tsx";
import { RefreshKeysDialog } from "@components/Dialog/RefreshKeysDialog/RefreshKeysDialog.tsx";
import { RebootOTADialog } from "@components/Dialog/RebootOTADialog.tsx";
export const DialogManager = () => {
const { channels, config, dialog, setDialogOpen } = useDevice();
@ -77,6 +78,12 @@ export const DialogManager = () => {
setDialogOpen("refreshKeys", open);
}}
/>
<RebootOTADialog
open={dialog.rebootOTA}
onOpenChange={(open) => {
setDialogOpen("rebootOTA", open);
}}
/>
</>
);
};

12
src/components/Dialog/NewDeviceDialog.tsx

@ -53,7 +53,7 @@ const links: { [key: string]: string } = {
const listFormatter = new Intl.ListFormat("en", {
style: "long",
type: "conjunction",
type: "disjunction",
});
const ErrorMessage = ({ missingFeatures }: FeatureErrorProps) => {
@ -79,16 +79,16 @@ const ErrorMessage = ({ missingFeatures }: FeatureErrorProps) => {
};
return (
<Subtle className="flex flex-col items-start gap-2 text-slate-900 bg-red-200/80 p-4 rounded-md">
<Subtle className="flex flex-col items-start gap-2 bg-red-500 p-4 rounded-md">
<div className="flex items-center gap-2 w-full">
<AlertCircle size={40} className="mr-2 shrink-0" />
<AlertCircle size={40} className="mr-2 shrink-0 text-white" />
<div className="flex flex-col gap-3">
<p className="text-sm">
<p className="text-sm text-white">
{browserFeatures.length > 0 && (
<>
This application requires{" "}
This connection type requires{" "}
{formatFeatureList(browserFeatures)}. Please use a
Chromium-based browser like Chrome or Edge.
supported browser, like Chrome or Edge.
</>
)}
{needsSecureContext && (

114
src/components/Dialog/RebootOTADialog.test.tsx

@ -0,0 +1,114 @@
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import { render, screen, fireEvent, waitFor } from '@testing-library/react';
import { RebootOTADialog } from './RebootOTADialog.tsx';
import { ReactNode } from "react";
const rebootOtaMock = vi.fn();
let mockConnection: { rebootOta: (delay: number) => void } | undefined = {
rebootOta: rebootOtaMock,
};
vi.mock('@core/stores/deviceStore.ts', () => ({
useDevice: () => ({
connection: mockConnection,
}),
}));
vi.mock('@components/UI/Button.tsx', async () => {
const actual = await vi.importActual('@components/UI/Button.tsx');
return {
...actual,
Button: (props: any) => <button {...props} />,
};
});
vi.mock('@components/UI/Input.tsx', async () => {
const actual = await vi.importActual('@components/UI/Input.tsx');
return {
...actual,
Input: (props: any) => <input {...props} />,
};
});
vi.mock('@components/UI/Dialog.tsx', () => {
return {
Dialog: ({ children }: { children: ReactNode }) => <div>{children}</div>,
DialogContent: ({ children }: { children: ReactNode }) => <div>{children}</div>,
DialogHeader: ({ children }: { children: ReactNode }) => <div>{children}</div>,
DialogTitle: ({ children }: { children: ReactNode }) => <h1>{children}</h1>,
DialogDescription: ({ children }: { children: ReactNode }) => <p>{children}</p>,
DialogClose: () => null,
};
});
describe('RebootOTADialog', () => {
beforeEach(() => {
vi.useFakeTimers();
rebootOtaMock.mockClear();
});
afterEach(() => {
vi.useRealTimers();
});
it('renders dialog with default input value', () => {
render(<RebootOTADialog open={true} onOpenChange={() => { }} />);
expect(screen.getByPlaceholderText(/enter delay/i)).toHaveValue(5);
expect(screen.getByText(/schedule reboot/i)).toBeInTheDocument();
expect(screen.getByText(/reboot to ota mode now/i)).toBeInTheDocument();
});
it('schedules a reboot with delay and calls rebootOta', async () => {
const onOpenChangeMock = vi.fn();
render(<RebootOTADialog open={true} onOpenChange={onOpenChangeMock} />);
fireEvent.change(screen.getByPlaceholderText(/enter delay/i), {
target: { value: '3' },
});
fireEvent.click(screen.getByText(/schedule reboot/i));
expect(screen.getByText(/reboot has been scheduled/i)).toBeInTheDocument();
vi.advanceTimersByTime(3000);
await waitFor(() => {
expect(rebootOtaMock).toHaveBeenCalledWith(0);
expect(onOpenChangeMock).toHaveBeenCalledWith(false);
});
});
it('triggers an instant reboot', async () => {
const onOpenChangeMock = vi.fn();
render(<RebootOTADialog open={true} onOpenChange={onOpenChangeMock} />);
fireEvent.click(screen.getByText(/reboot to ota mode now/i));
await waitFor(() => {
expect(rebootOtaMock).toHaveBeenCalledWith(5);
expect(onOpenChangeMock).toHaveBeenCalledWith(false);
});
});
it('does not call reboot if connection is undefined', async () => {
const onOpenChangeMock = vi.fn();
// simulate no connection
mockConnection = undefined;
render(<RebootOTADialog open={true} onOpenChange={onOpenChangeMock} />);
fireEvent.click(screen.getByText(/schedule reboot/i));
vi.advanceTimersByTime(5000);
await waitFor(() => {
expect(rebootOtaMock).not.toHaveBeenCalled();
expect(onOpenChangeMock).not.toHaveBeenCalled();
});
// reset connection for other tests
mockConnection = { rebootOta: rebootOtaMock };
});
});

104
src/components/Dialog/RebootOTADialog.tsx

@ -0,0 +1,104 @@
import { useState } from "react";
import { ClockIcon, RefreshCwIcon } from "lucide-react";
import { Button } from "@components/UI/Button.tsx";
import {
Dialog,
DialogClose,
DialogContent,
DialogDescription,
DialogHeader,
DialogTitle,
} from "@components/UI/Dialog.tsx";
import { Input } from "@components/UI/Input.tsx";
import { useDevice } from "@core/stores/deviceStore.ts";
export interface RebootOTADialogProps {
open: boolean;
onOpenChange: (open: boolean) => void;
}
const DEFAULT_REBOOT_DELAY = 5; // seconds
export const RebootOTADialog = ({ open, onOpenChange }: RebootOTADialogProps) => {
const { connection } = useDevice();
const [time, setTime] = useState<number>(DEFAULT_REBOOT_DELAY);
const [isScheduled, setIsScheduled] = useState(false);
const [inputValue, setInputValue] = useState(DEFAULT_REBOOT_DELAY.toString());
const handleSetTime = (e: React.ChangeEvent<HTMLInputElement>) => {
if (!e.target.validity.valid) {
e.preventDefault();
return
};
const val = e.target.value;
setInputValue(val);
const parsed = Number(val);
if (!isNaN(parsed) && parsed > 0) {
setTime(parsed);
}
};
const handleRebootWithTimeout = async () => {
if (!connection) return;
setIsScheduled(true);
const delay = time > 0 ? time : DEFAULT_REBOOT_DELAY;
await new Promise<void>((resolve) => {
setTimeout(() => {
console.log("Rebooting...");
resolve();
}, delay * 1000);
}).finally(() => {
setIsScheduled(false);
onOpenChange(false);
setInputValue(DEFAULT_REBOOT_DELAY.toString());
});
connection.rebootOta(0);
};
const handleInstantReboot = async () => {
if (!connection) return;
await connection.rebootOta(DEFAULT_REBOOT_DELAY);
onOpenChange(false);
};
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent>
<DialogClose />
<DialogHeader>
<DialogTitle>Reboot to OTA Mode</DialogTitle>
<DialogDescription>
Reboot the connected node after a delay into OTA (Over-the-Air) mode.
</DialogDescription>
</DialogHeader>
<div className="flex gap-2 p-2 items-center relative">
<Input
type="number"
min={1}
max={86400}
className="dark:text-slate-900 appearance-none"
value={inputValue}
onChange={handleSetTime}
placeholder="Enter delay (sec)"
/>
<Button onClick={() => handleRebootWithTimeout()} className="w-9/12">
<ClockIcon className="mr-2" size={18} />
{isScheduled ? 'Reboot has been scheduled' : 'Schedule Reboot'}
</Button>
</div>
<Button variant="destructive" onClick={() => handleInstantReboot()}>
<RefreshCwIcon className="mr-2" size={16} />
Reboot to OTA Mode Now
</Button>
</DialogContent>
</Dialog>
);
};

77
src/components/Form/FormInput.tsx

@ -7,7 +7,7 @@ import type { LucideIcon } from "lucide-react";
import { Eye, EyeOff } from "lucide-react";
import type { ChangeEventHandler } from "react";
import { useState } from "react";
import { Controller, type FieldValues } from "react-hook-form";
import { useController, type FieldValues } from "react-hook-form";
export interface InputFieldProps<T> extends BaseFormBuilderProps<T> {
type: "text" | "number" | "password";
@ -17,6 +17,12 @@ export interface InputFieldProps<T> extends BaseFormBuilderProps<T> {
prefix?: string;
suffix?: string;
step?: number;
fieldLength?: {
min?: number;
max?: number;
currentValueLength?: number;
showCharacterCount?: boolean;
},
action?: {
icon: LucideIcon;
onClick: () => void;
@ -29,42 +35,59 @@ export function GenericInput<T extends FieldValues>({
disabled,
field,
}: GenericFormElementProps<T, InputFieldProps<T>>) {
const { fieldLength, ...restProperties } = field.properties || {};
const [passwordShown, setPasswordShown] = useState(false);
const [currentLength, setCurrentLength] = useState<number>(fieldLength?.currentValueLength || 0);
const { field: controllerField } = useController({
name: field.name,
control,
});
const togglePasswordVisiblity = () => {
setPasswordShown(!passwordShown);
};
const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
const newValue = e.target.value;
if (field.properties?.fieldLength?.max && newValue.length > field.properties?.fieldLength?.max) {
return;
}
setCurrentLength(newValue.length);
if (field.inputChange) field.inputChange(e);
controllerField.onChange(field.type === "number" ? Number.parseFloat(newValue).toString() : newValue);
};
return (
<Controller
name={field.name}
control={control}
render={({ field: { value, onChange, ...rest } }) => (
<Input
type={field.type === "password" && passwordShown
? "text"
: field.type}
action={field.type === "password"
<div className="relative w-full">
<Input
type={field.type === "password" && passwordShown ? "text" : field.type}
action={
field.type === "password"
? {
icon: passwordShown ? EyeOff : Eye,
onClick: togglePasswordVisiblity,
}
: undefined}
step={field.properties?.step}
value={field.type === "number" ? Number.parseFloat(value) : value}
id={field.name}
onChange={(e) => {
if (field.inputChange) field.inputChange(e);
onChange(
field.type === "number"
? Number.parseFloat(e.target.value)
: e.target.value,
);
}}
{...field.properties}
{...rest}
disabled={disabled}
/>
: undefined
}
step={field.properties?.step}
value={field.type === "number" ? String(controllerField.value) : controllerField.value}
id={field.name}
onChange={handleInputChange}
{...restProperties}
disabled={disabled}
/>
{fieldLength?.showCharacterCount && fieldLength?.max && (
<div className="absolute inset-y-0 right-0 flex items-center pr-3 text-sm text-slate-500 dark:text-slate-400">
{currentLength ?? fieldLength?.currentValueLength}/{fieldLength?.max}
</div>
)}
/>
</div>
);
}

4
src/components/Form/FormSelect.tsx

@ -10,13 +10,14 @@ import {
SelectValue,
} from "@components/UI/Select.tsx";
import { useController, type FieldValues } from "react-hook-form";
import { computeHeadingLevel } from "@core/utils/test.tsx";
export interface SelectFieldProps<T> extends BaseFormBuilderProps<T> {
type: "select";
selectChange?: (e: string, name: string) => void;
validate?: (newValue: string) => Promise<boolean>;
defaultValue?: string;
properties: BaseFormBuilderProps<T>["properties"] & {
defaultValue?: T;
enumValue: {
[s: string]: string | number;
};
@ -70,7 +71,6 @@ export function SelectInput<T extends FieldValues>({
onChange(Number.parseInt(newValue));
};
return (
<Select
onValueChange={handleValueChange}

5
src/components/KeyBackupReminder.tsx

@ -5,15 +5,10 @@ export const KeyBackupReminder = () => {
const { setDialogOpen } = useDevice();
useBackupReminder({
reminderInDays: 7,
message:
"We recommend backing up your key data regularly. Would you like to back up now?",
onAccept: () => setDialogOpen("pkiBackup", true),
enabled: true,
cookieOptions: {
secure: true,
sameSite: "strict",
},
});
// deno-lint-ignore jsx-no-useless-fragment
return <></>;

5
src/components/PageComponents/Channel.tsx

@ -34,9 +34,10 @@ export const Channel = ({ channel }: SettingsPanelProps) => {
settings: {
...data.settings,
psk: toByteArray(pass),
moduleSettings: {...data.settings.moduleSettings,
moduleSettings: create(Protobuf.Channel.ModuleSettingsSchema, {
...data.settings.moduleSettings,
positionPrecision: data.settings.moduleSettings.positionPrecision,
},
}),
},
});
connection?.setChannel(channel).then(() => {

13
src/components/PageComponents/Config/Device/index.tsx

@ -82,6 +82,19 @@ export const Device = () => {
label: "Disable Triple Click",
description: "Disable triple click",
},
{
type: 'text',
name: 'tzdef',
label: 'POSIX Timezone',
description: 'The POSIX timezone string for the device',
properties: {
fieldLength: {
max: 64,
currentValueLength: config.device?.tzdef?.length,
showCharacterCount: true,
}
},
},
{
type: "toggle",
name: "ledHeartbeatDisabled",

283
src/components/PageComponents/Config/Network/Network.test.tsx

@ -0,0 +1,283 @@
// import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
// import { render, screen, fireEvent, waitFor } from '@testing-library/react';
// import { Network } from '@components/PageComponents/Config/Network/index.tsx';
// import { useDevice } from "@core/stores/deviceStore.ts";
// import { Protobuf } from "@meshtastic/core";
// vi.mock('@core/stores/deviceStore', () => ({
// useDevice: vi.fn()
// }));
// vi.mock('@components/Form/DynamicForm', () => ({
// DynamicForm: vi.fn(({ onSubmit }) => {
// return (
// <div data-testid="dynamic-form">
// <select
// data-testid="role-select"
// onChange={(e) => {
// const mockData = { role: e.target.value };
// onSubmit(mockData);
// }}
// >
// {Object.entries(Protobuf.Config.Config_DeviceConfig_Role).map(([key, value]) => (
// <option key={key} value={value}>
// {key}
// </option>
// ))}
// </select>
// <button type="submit"
// data-testid="submit-button"
// onClick={() => onSubmit({ role: "CLIENT" })}
// >
// Submit
// </button>
// </div>
// );
// })
// }));
// describe('Network component', () => {
// const setWorkingConfigMock = vi.fn();
// const mockDeviceConfig = {
// role: "CLIENT",
// buttonGpio: 0,
// buzzerGpio: 0,
// rebroadcastMode: "ALL",
// nodeInfoBroadcastSecs: 300,
// doubleTapAsButtonPress: false,
// disableTripleClick: false,
// ledHeartbeatDisabled: false,
// };
// beforeEach(() => {
// vi.resetAllMocks();
// (useDevice as any).mockReturnValue({
// config: {
// device: mockDeviceConfig
// },
// setWorkingConfig: setWorkingConfigMock
// });
// });
// afterEach(() => {
// vi.clearAllMocks();
// });
// it('should render the Network form', () => {
// render(<Network />);
// expect(screen.getByTestId('dynamic-form')).toBeInTheDocument();
// });
// it('should call setWorkingConfig when form is submitted', async () => {
// render(<Network />);
// fireEvent.click(screen.getByTestId('submit-button'));
// await waitFor(() => {
// expect(setWorkingConfigMock).toHaveBeenCalledWith(
// expect.objectContaining({
// payloadVariant: {
// case: "device",
// value: expect.objectContaining({ role: "CLIENT" })
// }
// })
// );
// });
// });
// it('should create config with proper structure', async () => {
// render(<Network />);
// // Simulate form submission
// fireEvent.click(screen.getByTestId('submit-button'));
// await waitFor(() => {
// expect(setWorkingConfigMock).toHaveBeenCalledWith(
// expect.objectContaining({
// payloadVariant: {
// case: "network",
// value: expect.any(Object)
// }
// })
// );
// });
// });
// });
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import { render, screen, fireEvent, waitFor } from '@testing-library/react';
import { Network } from '@components/PageComponents/Config/Network/index.tsx';
import { useDevice } from "@core/stores/deviceStore.ts";
import { Protobuf } from "@meshtastic/core";
vi.mock('@core/stores/deviceStore', () => ({
useDevice: vi.fn()
}));
vi.mock('@components/Form/DynamicForm', async () => {
const React = await import('react');
const { useState } = React;
return {
DynamicForm: ({ onSubmit, defaultValues }: any) => {
const [wifiEnabled, setWifiEnabled] = useState(defaultValues.wifiEnabled ?? false);
const [ssid, setSsid] = useState(defaultValues.wifiSsid ?? '');
const [psk, setPsk] = useState(defaultValues.wifiPsk ?? '');
return (
<form
onSubmit={(e) => {
e.preventDefault();
onSubmit({
...defaultValues,
wifiEnabled,
wifiSsid: ssid,
wifiPsk: psk,
});
}}
data-testid="dynamic-form"
>
<input
type="checkbox"
aria-label="WiFi Enabled"
checked={wifiEnabled}
onChange={(e) => setWifiEnabled(e.target.checked)}
/>
<input
aria-label="SSID"
value={ssid}
onChange={(e) => setSsid(e.target.value)}
disabled={!wifiEnabled}
/>
<input
aria-label="PSK"
value={psk}
onChange={(e) => setPsk(e.target.value)}
disabled={!wifiEnabled}
/>
<button type="submit" data-testid="submit-button">
Submit
</button>
</form>
);
},
};
});
;
describe('Network component', () => {
const setWorkingConfigMock = vi.fn();
const mockNetworkConfig = {
wifiEnabled: false,
wifiSsid: '',
wifiPsk: '',
ntpServer: '',
ethEnabled: false,
addressMode: Protobuf.Config.Config_NetworkConfig_AddressMode.DHCP,
ipv4Config: {
ip: 0,
gateway: 0,
subnet: 0,
dns: 0,
},
enabledProtocols:
Protobuf.Config.Config_NetworkConfig_ProtocolFlags.NO_BROADCAST,
rsyslogServer: '',
};
beforeEach(() => {
vi.resetAllMocks();
(useDevice as any).mockReturnValue({
config: {
network: mockNetworkConfig
},
setWorkingConfig: setWorkingConfigMock
});
});
afterEach(() => {
vi.clearAllMocks();
});
it('should render the Network form', () => {
render(<Network />);
expect(screen.getByTestId('dynamic-form')).toBeInTheDocument();
});
it('should disable SSID and PSK fields when wifi is off', () => {
render(<Network />);
expect(screen.getByLabelText("SSID")).toBeDisabled();
expect(screen.getByLabelText("PSK")).toBeDisabled();
});
it('should enable SSID and PSK when wifi is toggled on', async () => {
render(<Network />);
const toggle = screen.getByLabelText("WiFi Enabled");
screen.debug()
fireEvent.click(toggle); // turns wifiEnabled = true
await waitFor(() => {
expect(screen.getByLabelText("SSID")).not.toBeDisabled();
expect(screen.getByLabelText("PSK")).not.toBeDisabled();
});
});
it('should call setWorkingConfig with the right structure on submit', async () => {
render(<Network />);
fireEvent.click(screen.getByTestId("submit-button"));
await waitFor(() => {
expect(setWorkingConfigMock).toHaveBeenCalledWith(
expect.objectContaining({
payloadVariant: {
case: "network",
value: expect.objectContaining({
wifiEnabled: false,
wifiSsid: '',
wifiPsk: '',
ntpServer: '',
ethEnabled: false,
rsyslogServer: '',
})
}
})
);
});
});
it('should submit valid data after enabling wifi and entering SSID and PSK', async () => {
render(<Network />);
fireEvent.click(screen.getByLabelText("WiFi Enabled"));
fireEvent.change(screen.getByLabelText("SSID"), {
target: { value: "MySSID" }
});
fireEvent.change(screen.getByLabelText("PSK"), {
target: { value: "MySecretPSK" }
});
fireEvent.click(screen.getByTestId("submit-button"));
await waitFor(() => {
expect(setWorkingConfigMock).toHaveBeenCalledWith(
expect.objectContaining({
payloadVariant: {
case: "network",
value: expect.objectContaining({
wifiEnabled: true,
wifiSsid: "MySSID",
wifiPsk: "MySecretPSK"
})
}
})
);
});
});
});

35
src/components/PageComponents/Config/Network.tsx → src/components/PageComponents/Config/Network/index.tsx

@ -1,4 +1,4 @@
import type { NetworkValidation } from "@app/validation/config/network.tsx";
import { NetworkValidationSchema, type NetworkValidation } from "@app/validation/config/network.ts";
import { create } from "@bufbuild/protobuf";
import { DynamicForm } from "@components/Form/DynamicForm.tsx";
import { useDevice } from "@core/stores/deviceStore.ts";
@ -7,11 +7,18 @@ import {
convertIpAddressToInt,
} from "@core/utils/ip.ts";
import { Protobuf } from "@meshtastic/core";
import { validateSchema } from "@app/validation/validate.ts";
export const Network = () => {
const { config, setWorkingConfig } = useDevice();
const onSubmit = (data: NetworkValidation) => {
const result = validateSchema(NetworkValidationSchema, data);
if (!result.success) {
console.error("Validation errors:", result.errors);
}
setWorkingConfig(
create(Protobuf.Config.ConfigSchema, {
payloadVariant: {
@ -21,10 +28,10 @@ export const Network = () => {
ipv4Config: create(
Protobuf.Config.Config_NetworkConfig_IpV4ConfigSchema,
{
ip: convertIpAddressToInt(data.ipv4Config.ip) ?? 0,
gateway: convertIpAddressToInt(data.ipv4Config.gateway) ?? 0,
subnet: convertIpAddressToInt(data.ipv4Config.subnet) ?? 0,
dns: convertIpAddressToInt(data.ipv4Config.dns) ?? 0,
ip: convertIpAddressToInt(data.ipv4Config?.ip ?? ""),
gateway: convertIpAddressToInt(data.ipv4Config?.gateway ?? ""),
subnet: convertIpAddressToInt(data.ipv4Config?.subnet ?? ""),
dns: convertIpAddressToInt(data.ipv4Config?.dns ?? ""),
},
),
},
@ -48,6 +55,8 @@ export const Network = () => {
),
dns: convertIntToIpAddress(config.network?.ipv4Config?.dns ?? 0),
},
enabledProtocols: config.network?.enabledProtocols ?? Protobuf.Config.Config_NetworkConfig_ProtocolFlags.NO_BROADCAST
}}
fieldGroups={[
{
@ -165,6 +174,22 @@ export const Network = () => {
},
],
},
{
label: "UDP Config",
description: "UDP over Mesh configuration",
fields: [
{
type: "select",
name: "enabledProtocols",
label: "Mesh via UDP",
properties: {
enumValue:
Protobuf.Config.Config_NetworkConfig_ProtocolFlags,
formatEnumName: true,
}
},
],
},
{
label: "NTP Config",
description: "NTP configuration",

8
src/components/PageComponents/Config/Position.tsx

@ -1,8 +1,8 @@
import {
type FlagName,
usePositionFlags,
} from "../../../core/hooks/usePositionFlags.ts";
import type { PositionValidation } from "@app/validation/config/position.tsx";
} from "@core/hooks/usePositionFlags.ts";
import type { PositionValidation } from "@app/validation/config/position.ts";
import { create } from "@bufbuild/protobuf";
import { DynamicForm } from "@components/Form/DynamicForm.tsx";
import { useDevice } from "@core/stores/deviceStore.ts";
@ -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) => {
@ -74,7 +74,7 @@ export const Position = () => {
name: "positionFlags",
value: activeFlags,
isChecked: (name: string) =>
activeFlags.includes(name as FlagName),
activeFlags?.includes(name as FlagName) ?? false,
onValueChange: onPositonFlagChange,
label: "Position Flags",
placeholder: "Select position flags...",

67
src/components/PageComponents/Map/NodeDetail.tsx

@ -16,31 +16,53 @@ import {
Dot,
LockIcon,
LockOpenIcon,
MessageSquareIcon,
MountainSnow,
Star,
} from "lucide-react";
import {
Tooltip,
TooltipContent,
TooltipPortal,
TooltipProvider,
TooltipTrigger,
} from "@radix-ui/react-tooltip";
import { useAppStore } from "@core/stores/appStore.ts";
import { useDevice } from "@core/stores/deviceStore.ts";
export interface NodeDetailProps {
node: ProtobufType.Mesh.NodeInfo;
}
export const NodeDetail = ({ node }: NodeDetailProps) => {
const { setChatType, setActiveChat } = useAppStore();
const { setActivePage } = useDevice();
const name = node.user?.longName || `!${numberToHexUnpadded(node.num)}`;
const shortName = node.user?.shortName ?? "UNK";
const hwModel = node.user?.hwModel ?? 0;
const hardwareType =
Protobuf.Mesh.HardwareModel[hwModel]?.replaceAll("_", " ") ?? `${hwModel}`;
function handleDirectMessage() {
setChatType("direct");
setActiveChat(node.num);
setActivePage("messages");
}
return (
<div className="dark:text-slate-900 p-1">
<div className="flex gap-2">
<div className="flex flex-col items-center gap-2 min-w-6 pt-1">
<Avatar text={node.user?.shortName ?? "UNK"} />
<Avatar text={shortName} />
<div>
<div onFocusCapture={(e) => {
// Required to prevent DM tooltip auto-appearing on creation
e.stopPropagation();
}}>
{node.user?.publicKey && node.user?.publicKey.length > 0
? (
<LockIcon
className="text-green-600"
className="text-green-600 mb-1.5"
size={12}
strokeWidth={3}
aria-label="Public Key Enabled"
@ -48,19 +70,42 @@ export const NodeDetail = ({ node }: NodeDetailProps) => {
)
: (
<LockOpenIcon
className="text-yellow-500"
className="text-yellow-500 mb-1.5"
size={12}
strokeWidth={3}
aria-label="No Public Key"
/>
)}
</div>
<Star
fill={node.isFavorite ? "black" : "none"}
size={15}
aria-label={node.isFavorite ? "Favorite" : "Not a Favorite"}
/>
<TooltipProvider>
<Tooltip>
<TooltipTrigger>
<MessageSquareIcon
size={14}
onClick={handleDirectMessage}
className="cursor-pointer hover:text-blue-500"
title="Send Message"
/>
</TooltipTrigger>
<TooltipPortal>
<TooltipContent
className="rounded-md bg-slate-800 px-3 py-1.5 text-sm text-white shadow-md animate-in fade-in-0 zoom-in-95"
side="top"
align="center"
sideOffset={5}
>
Direct Message {shortName}
</TooltipContent>
</TooltipPortal>
</Tooltip>
</TooltipProvider>
<Star
fill={node.isFavorite ? "black" : "none"}
size={15}
aria-label={node.isFavorite ? "Favorite" : "Not a Favorite"}
/>
</div>
</div>
<div>
@ -70,7 +115,7 @@ export const NodeDetail = ({ node }: NodeDetailProps) => {
{!!node.deviceMetrics?.batteryLevel && (
<div
className="flex items-center gap-1"
className="flex items-center gap-1 mt-0.5"
title={`${node.deviceMetrics?.voltage?.toPrecision(3) ?? "Unknown"
} volts`}
>

96
src/components/Sidebar.tsx

@ -3,6 +3,8 @@ import { SidebarButton } from "@components/UI/Sidebar/sidebarButton.tsx";
import { Subtle } from "@components/UI/Typography/Subtle.tsx";
import { useDevice } from "@core/stores/deviceStore.ts";
import type { Page } from "@core/stores/deviceStore.ts";
import { Spinner } from "@components/UI/Spinner.tsx";
import {
BatteryMediumIcon,
CpuIcon,
@ -58,7 +60,7 @@ export const Sidebar = ({ children }: SidebarProps) => {
page: "channels",
},
{
name: `Nodes (${nodes.size})`,
name: `Nodes (${nodes.size - 1})`,
icon: UsersIcon,
page: "nodes",
},
@ -67,46 +69,55 @@ export const Sidebar = ({ children }: SidebarProps) => {
return showSidebar
? (
<div className="min-w-[280px] max-w-min flex-col overflow-y-auto border-r-[0.5px] bg-background-primary border-slate-300 dark:border-slate-400">
<div className="flex justify-between px-8 pt-6">
<div>
<span className="text-lg font-medium">
{myNode?.user?.shortName ?? "UNK"}
</span>
<Subtle>{myNode?.user?.longName ?? "UNK"}</Subtle>
</div>
<button
type="button"
className="transition-all hover:text-accent"
onClick={() => setDialogOpen("deviceName", true)}
>
<EditIcon size={16} />
</button>
<button type="button" onClick={() => setShowSidebar(false)}>
<SidebarCloseIcon size={24} />
</button>
</div>
<div className="px-8 pb-6">
<div className="flex items-center">
<BatteryMediumIcon size={24} viewBox="0 0 28 24" />
<Subtle>
{myNode?.deviceMetrics?.batteryLevel
? myNode?.deviceMetrics?.batteryLevel > 100
? "Charging"
: `${myNode?.deviceMetrics?.batteryLevel}%`
: "UNK"}
</Subtle>
</div>
<div className="flex items-center">
<ZapIcon size={24} viewBox="0 0 36 24" />
<Subtle>
{myNode?.deviceMetrics?.voltage?.toPrecision(3) ?? "UNK"} volts
</Subtle>
</div>
<div className="flex items-center">
<CpuIcon size={24} viewBox="0 0 36 24" />
<Subtle>v{myMetadata?.firmwareVersion ?? "UNK"}</Subtle>
{myNode === undefined ? (
<div className="flex flex-col items-center justify-center px-8 py-6">
<Spinner />
<Subtle className="mt-2">Loading device info...</Subtle>
</div>
</div>
) : (
<>
<div className="flex justify-between px-8 pt-6">
<div>
<span className="text-lg font-medium">
{myNode.user?.shortName ?? "UNK"}
</span>
<Subtle>{myNode.user?.longName ?? "UNK"}</Subtle>
</div>
<button
type="button"
className="transition-all hover:text-accent"
onClick={() => setDialogOpen("deviceName", true)}
>
<EditIcon size={16} />
</button>
<button type="button" onClick={() => setShowSidebar(false)}>
<SidebarCloseIcon size={24} />
</button>
</div>
<div className="px-8 pb-6">
<div className="flex items-center">
<BatteryMediumIcon size={24} viewBox="0 0 28 24" />
<Subtle>
{myNode.deviceMetrics?.batteryLevel
? myNode.deviceMetrics.batteryLevel > 100
? "Charging"
: `${myNode.deviceMetrics.batteryLevel}%`
: "UNK"}
</Subtle>
</div>
<div className="flex items-center">
<ZapIcon size={24} viewBox="0 0 36 24" />
<Subtle>
{myNode.deviceMetrics?.voltage?.toPrecision(3) ?? "UNK"} volts
</Subtle>
</div>
<div className="flex items-center">
<CpuIcon size={24} viewBox="0 0 36 24" />
<Subtle>v{myMetadata?.firmwareVersion ?? "UNK"}</Subtle>
</div>
</div>
</>
)}
<SidebarSection label="Navigation">
{pages.map((link) => (
@ -115,9 +126,12 @@ export const Sidebar = ({ children }: SidebarProps) => {
label={link.name}
Icon={link.icon}
onClick={() => {
setActivePage(link.page);
if (myNode !== undefined) {
setActivePage(link.page);
}
}}
active={link.page === activePage}
disabled={myNode === undefined}
/>
))}
</SidebarSection>

4
src/components/Toaster.tsx

@ -5,8 +5,8 @@ import {
ToastProvider,
ToastTitle,
ToastViewport,
} from "./UI/Toast.tsx";
import { useToast } from "../core/hooks/useToast.ts";
} from "@components/UI/Toast.tsx";
import { useToast } from "@core/hooks/useToast.ts";
export function Toaster() {
const { toasts } = useToast();

2
src/components/UI/Command.tsx

@ -116,7 +116,7 @@ const CommandItem = React.forwardRef<
<CommandPrimitive.Item
ref={ref}
className={cn(
"relative flex cursor-default select-none items-center rounded-md py-1.5 px-2 text-sm font-medium outline-hidden aria-selected:bg-slate-100 data-[disabled='true']:pointer-events-none data-[disabled='true']:opacity-50 dark:aria-selected:bg-slate-700",
"relative flex cursor-default select-none items-center rounded-md py-1.5 px-2 text-sm font-medium outline-hidden aria-selected:bg-slate-100 data-[disabled='true']:pointer-events-none data-[disabled='true']:opacity-50 dark:aria-selected:bg-slate-700 dark:text-white ",
className,
)}
{...props}

3
src/components/UI/Sidebar/sidebarButton.tsx

@ -7,6 +7,7 @@ export interface SidebarButtonProps {
Icon?: LucideIcon;
element?;
onClick?: () => void;
disabled?: boolean;
}
export const SidebarButton = ({
@ -15,12 +16,14 @@ export const SidebarButton = ({
Icon,
element,
onClick,
disabled = false,
}: SidebarButtonProps) => (
<Button
onClick={onClick}
variant={active ? "subtle" : "ghost"}
size="sm"
className="flex gap-2 w-full"
disabled={disabled}
>
{Icon && <Icon size={16} />}
{element && element}

117
src/core/hooks/useKeyBackupReminder.tsx

@ -1,71 +1,58 @@
import { Button } from "../../components/UI/Button.tsx";
import type { CookieAttributes } from "js-cookie";
import { Button } from "@components/UI/Button.tsx";
import { useCallback, useEffect, useRef } from "react";
import useCookie from "./useCookie.ts";
import { useToast } from "./useToast.ts";
import { useToast } from "@core/hooks/useToast.ts";
import useLocalStorage from "@core/hooks/useLocalStorage.ts";
interface UseBackupReminderOptions {
reminderInDays?: number;
message: string;
onAccept?: () => void | Promise<void>;
enabled: boolean;
cookieOptions?: CookieAttributes;
}
interface ReminderState {
suppressed: boolean;
lastShown: string;
expires: string;
}
const TOAST_APPEAR_DELAY = 10_000; // 10 seconds;
const TOAST_DURATION = 30_000; // 30 seconds;:
const TOAST_APPEAR_DELAY = 10_000; // 10 seconds
const TOAST_DURATION = 30_000; // 30 seconds
const REMINDER_DAYS_ONE_WEEK = 7;
const REMINDER_DAYS_ONE_YEAR = 365;
const REMINDER_DAYS_FOREVER = 3650;
const STORAGE_KEY = "key_backup_reminder";
// remind user in 1 year to backup keys again, if they accept the reminder;
const ON_ACCEPT_REMINDER_DAYS = 365;
function isReminderExpired(expires?: string): boolean {
if (!expires) return true;
const expiryDate = new Date(expires);
if (isNaN(expiryDate.getTime())) return true; // Invalid date passed
function isReminderExpired(lastShown: string): boolean {
const lastShownDate = new Date(lastShown);
const now = new Date();
const daysSinceLastShown = (now.getTime() - lastShownDate.getTime()) /
(1000 * 60 * 60 * 24);
return daysSinceLastShown >= 7;
return now.getTime() >= expiryDate.getTime();
}
export function useBackupReminder({
reminderInDays = 7,
enabled,
message,
onAccept = () => {},
cookieOptions,
onAccept = () => { },
reminderInDays = REMINDER_DAYS_ONE_WEEK,
}: UseBackupReminderOptions) {
const { toast } = useToast();
const toastShownRef = useRef(false);
const { value: reminderCookie, setCookie } = useCookie<ReminderState>(
"key_backup_reminder",
const [reminderState, setReminderState] = useLocalStorage<ReminderState | null>(
STORAGE_KEY,
null
);
const suppressReminder = useCallback(
(days: number) => {
const expiryDate = new Date();
expiryDate.setDate(expiryDate.getDate() + days);
setCookie(
{
suppressed: true,
lastShown: new Date().toISOString(),
},
{ ...cookieOptions, expires: expiryDate },
);
},
[setCookie, cookieOptions],
);
const setReminderExpiry = useCallback((days: number) => {
const expiryDate = new Date();
expiryDate.setDate(expiryDate.getDate() + days);
setReminderState({ expires: expiryDate.toISOString() });
}, [setReminderState]);
useEffect(() => {
if (!enabled || toastShownRef.current) return;
const shouldShowReminder = !reminderCookie?.suppressed ||
isReminderExpired(reminderCookie.lastShown);
if (!shouldShowReminder) return;
if (!isReminderExpired(reminderState?.expires)) return;
toastShownRef.current = true;
@ -75,44 +62,52 @@ export function useBackupReminder({
delay: TOAST_APPEAR_DELAY,
description: message,
action: (
<div className="flex gap-2">
<div className="flex flex-col gap-2">
<div className="flex gap-2">
<Button
type="button"
variant="outline"
className="p-1"
onClick={() => {
dismiss();
setReminderExpiry(reminderInDays);
}}
>
Remind me in {reminderInDays} day{reminderInDays > 1 ? 's' : ''}
</Button>
<Button
type="button"
variant="outline"
className="p-1"
onClick={() => {
dismiss();
setReminderExpiry(REMINDER_DAYS_FOREVER);
}}
>
Never remind me
</Button>
</div>
<Button
type="button"
variant="default"
className="w-full"
onClick={() => {
onAccept();
dismiss();
suppressReminder(ON_ACCEPT_REMINDER_DAYS);
setReminderExpiry(REMINDER_DAYS_ONE_YEAR);
}}
>
Back up now
</Button>
<Button
type="button"
variant="outline"
onClick={() => {
dismiss();
suppressReminder(reminderInDays);
}}
>
Remind me in {reminderInDays} days
</Button>
</div>
),
});
return () => {
if (!toastShownRef.current) {
dismiss();
}
};
return () => dismiss();
}, [
enabled,
message,
onAccept,
reminderInDays,
suppressReminder,
toast,
reminderCookie,
]);
}
};

52
src/core/hooks/useLocalStorage.test.ts

@ -0,0 +1,52 @@
import { renderHook, act } from '@testing-library/react'
import useLocalStorage from './useLocalStorage'
import { beforeEach, describe, expect, it } from "vitest";
describe('useLocalStorage', () => {
const key = 'test-key'
beforeEach(() => {
localStorage.clear()
})
it('should initialize with initial value if localStorage is empty', () => {
const { result } = renderHook(() => useLocalStorage(key, 'initial'))
const [value] = result.current
expect(value).toBe('initial')
})
it('should read existing value from localStorage', () => {
localStorage.setItem(key, JSON.stringify('stored'))
const { result } = renderHook(() => useLocalStorage(key, 'initial'))
const [value] = result.current
expect(value).toBe('stored')
})
it('should update localStorage when setValue is called', () => {
const { result } = renderHook(() => useLocalStorage(key, 'initial'))
const [, setValue] = result.current
act(() => {
setValue('updated')
})
expect(localStorage.getItem(key)).toBe(JSON.stringify('updated'))
expect(result.current[0]).toBe('updated')
})
it('should remove value from localStorage when removeValue is called', () => {
const { result } = renderHook(() => useLocalStorage(key, 'initial'))
const [, setValue, removeValue] = result.current
act(() => {
setValue('to-be-removed')
})
act(() => {
removeValue()
})
expect(localStorage.getItem(key)).toBeNull()
expect(result.current[0]).toBe('initial')
})
})

65
src/core/hooks/usePinnedItems.test.ts

@ -0,0 +1,65 @@
import { renderHook, act } from "@testing-library/react";
import { describe, it, expect, vi, beforeEach } from "vitest";
import { usePinnedItems } from "./usePinnedItems.ts";
const mockSetPinnedItems = vi.fn();
const mockUseLocalStorage = vi.fn();
vi.mock("@core/hooks/useLocalStorage.ts", () => ({
default: (...args: any[]) => mockUseLocalStorage(...args),
}));
describe("usePinnedItems", () => {
beforeEach(() => {
vi.clearAllMocks();
});
it("returns default pinnedItems and togglePinnedItem", () => {
mockUseLocalStorage.mockReturnValue([[], mockSetPinnedItems]);
const { result } = renderHook(() =>
usePinnedItems({ storageName: "test-storage" })
);
expect(result.current.pinnedItems).toEqual([]);
expect(typeof result.current.togglePinnedItem).toBe("function");
});
it("adds an item if it's not already pinned", () => {
mockUseLocalStorage.mockReturnValue([["item1"], mockSetPinnedItems]);
const { result } = renderHook(() =>
usePinnedItems({ storageName: "test-storage" })
);
act(() => {
result.current.togglePinnedItem("item2");
});
expect(mockSetPinnedItems).toHaveBeenCalledWith(expect.any(Function));
const updater = mockSetPinnedItems.mock.calls[0][0];
const updated = updater(["item1"]);
expect(updated).toEqual(["item1", "item2"]);
});
it("removes an item if it's already pinned", () => {
mockUseLocalStorage.mockReturnValue([["item1", "item2"], mockSetPinnedItems]);
const { result } = renderHook(() =>
usePinnedItems({ storageName: "test-storage" })
);
act(() => {
result.current.togglePinnedItem("item1");
});
expect(mockSetPinnedItems).toHaveBeenCalledWith(expect.any(Function));
const updater = mockSetPinnedItems.mock.calls[0][0];
const updated = updater(["item1", "item2"]);
expect(updated).toEqual(["item2"]);
});
});

19
src/core/hooks/usePinnedItems.ts

@ -0,0 +1,19 @@
import useLocalStorage from "@core/hooks/useLocalStorage.ts";
import { useCallback } from "react";
export function usePinnedItems({ storageName }: { storageName: string }) {
const [pinnedItems, setPinnedItems] = useLocalStorage<string[]>(storageName, []);
const togglePinnedItem = useCallback((label: string) => {
setPinnedItems((prev) =>
prev.includes(label)
? prev.filter((g) => g !== label)
: [...prev, label]
);
}, []);
return {
pinnedItems,
togglePinnedItem,
};
}

81
src/core/hooks/useToast.test.tsx

@ -0,0 +1,81 @@
import { renderHook, act } from '@testing-library/react'
import { useToast } from "@core/hooks/useToast.ts"
import { Button } from '@components/UI/Button.tsx'
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
describe('useToast', () => {
beforeEach(() => {
// Reset toast memory state before each test
// our hook uses global memory to store toasts
// @ts-expect-error - internal test reset
globalThis.memoryState = { toasts: [] }
vi.useFakeTimers()
})
afterEach(() => {
vi.useRealTimers()
})
it('should create a toast with title, description, and action', () => {
const { result } = renderHook(() => useToast())
act(() => {
result.current.toast({
title: 'Backup Reminder',
description: 'Don\'t forget to backup!',
action: <Button>Backup Now</Button>
})
vi.runAllTimers()
})
const toast = result.current.toasts[0]
expect(result.current.toasts.length).toBe(1)
expect(toast.title).toBe('Backup Reminder')
expect(toast.description).toBe('Don\'t forget to backup!')
expect(toast.action).toBeTruthy()
expect(toast.open).toBe(true)
})
it('should dismiss a toast using returned dismiss function', () => {
const { result } = renderHook(() => useToast())
vi.useFakeTimers()
let toastRef: { id: string, dismiss: () => void }
act(() => {
toastRef = result.current.toast({ title: 'Dismiss Me' })
vi.runAllTimers() // Flush ADD_TOAST
})
act(() => {
toastRef.dismiss()
})
const toast = result.current.toasts.find(t => t.id === toastRef.id)
expect(toast?.open).toBe(false)
vi.useRealTimers()
})
it('should allow dismiss via hook dismiss function', () => {
const { result } = renderHook(() => useToast())
vi.useFakeTimers()
let toastRef: { id: string }
act(() => {
toastRef = result.current.toast({ title: 'Manual Dismiss' })
vi.runAllTimers()
})
act(() => {
result.current.dismiss(toastRef.id)
})
const toast = result.current.toasts.find(t => t.id === toastRef.id)
expect(toast?.open).toBe(false)
vi.useRealTimers()
})
})

2
src/core/hooks/useToast.ts

@ -155,7 +155,7 @@ function toast({ delay = 0, ...props }: Toast) {
...props,
id,
open: true,
onOpenChange: (open) => {
onOpenChange: (open: boolean) => {
if (!open) dismiss();
},
},

3
src/core/stores/deviceStore.ts

@ -23,6 +23,7 @@ export type DialogVariant =
| "QR"
| "shutdown"
| "reboot"
| "rebootOTA"
| "deviceName"
| "nodeRemoval"
| "pkiBackup"
@ -73,6 +74,7 @@ export interface Device {
QR: boolean;
shutdown: boolean;
reboot: boolean;
rebootOTA: boolean;
deviceName: boolean;
nodeRemoval: boolean;
pkiBackup: boolean;
@ -175,6 +177,7 @@ export const useDeviceStore = createStore<DeviceState>((set, get) => ({
nodeDetails: false,
unsafeRoles: false,
refreshKeys: false,
rebootOTA: false,
},
pendingSettingsChanges: false,
messageDraft: "",

10
src/core/utils/ip.ts

@ -1,10 +1,12 @@
export function convertIntToIpAddress(int: number): string {
return `${int & 0xff}.${(int >> 8) & 0xff}.${(int >> 16) & 0xff}.${
(int >> 24) & 0xff
}`;
return `${int & 0xff}.${(int >> 8) & 0xff}.${(int >> 16) & 0xff}.${(int >> 24) & 0xff
}`;
}
export function convertIpAddressToInt(ip: string): number | null {
export function convertIpAddressToInt(ip: string): number | undefined {
if (!ip) {
return undefined;
}
return (
ip
.split(".")

3
src/pages/Config/DeviceConfig.tsx

@ -2,7 +2,7 @@ import { Bluetooth } from "@components/PageComponents/Config/Bluetooth.tsx";
import { Device } from "../../components/PageComponents/Config/Device/index.tsx";
import { Display } from "@components/PageComponents/Config/Display.tsx";
import { LoRa } from "@components/PageComponents/Config/LoRa.tsx";
import { Network } from "@components/PageComponents/Config/Network.tsx";
import { Network } from "../../components/PageComponents/Config/Network/index.tsx";
import { Position } from "@components/PageComponents/Config/Position.tsx";
import { Power } from "@components/PageComponents/Config/Power.tsx";
import { Security } from "../../components/PageComponents/Config/Security/Security.tsx";
@ -31,7 +31,6 @@ export const DeviceConfig = () => {
{
label: "Network",
element: Network,
// disabled: !metadata.get(0)?.hasWifi,
},
{
label: "Display",

90
src/pages/Nodes.tsx

@ -19,12 +19,17 @@ export interface DeleteNoteDialogProps {
onOpenChange: (open: boolean) => void;
}
function shortNameFromNode(node: ReturnType<useDevice>["nodes"][number]): string {
const shortNameOfNode = node.user?.shortName ?? (node.user?.macaddr
? `${base16
.stringify(node.user?.macaddr.subarray(4, 6) ?? [])
.toLowerCase()}`
: `${numberToHexUnpadded(node.num).slice(-4)}`);
function shortNameFromNode(
node: ReturnType<useDevice>["nodes"][number],
): string {
const shortNameOfNode = node.user?.shortName ??
(node.user?.macaddr
? `${
base16
.stringify(node.user?.macaddr.subarray(4, 6) ?? [])
.toLowerCase()
}`
: `${numberToHexUnpadded(node.num).slice(-4)}`);
return String(shortNameOfNode);
}
@ -70,7 +75,6 @@ const NodesPage = (): JSX.Element => {
};
}, [connection]);
const handleLocation = useCallback(
(location: Types.PacketMetadata<Protobuf.Mesh.Position>) => {
if (location.to.valueOf() !== hardware.myNodeNum) return;
@ -97,12 +101,12 @@ const NodesPage = (): JSX.Element => {
headings={[
{ title: "", type: "blank", sortable: false },
{ title: "Long Name", type: "normal", sortable: true },
{ title: "Model", type: "normal", sortable: true },
{ title: "MAC Address", type: "normal", sortable: true },
{ title: "Connection", type: "normal", sortable: true },
{ title: "Last Heard", type: "normal", sortable: true },
{ title: "SNR", type: "normal", sortable: true },
{ title: "Encryption", type: "normal", sortable: false },
{ title: "Connection", type: "normal", sortable: true },
{ title: "SNR", type: "normal", sortable: true },
{ title: "Model", type: "normal", sortable: true },
{ title: "MAC Address", type: "normal", sortable: true },
]}
rows={filteredNodes.map((node) => [
<div key={node.num}>
@ -111,55 +115,55 @@ const NodesPage = (): JSX.Element => {
<h1
key="longName"
onMouseDown={() => setSelectedNode(node)}
onKeyUp={(evt)=>{ evt.key === "Enter" && setSelectedNode(node) }}
onKeyUp={(evt) => {
evt.key === "Enter" && setSelectedNode(node);
}}
className="cursor-pointer underline"
tabIndex={0}
role="button"
>
{node.user?.longName ??
(node.user?.macaddr
? `Meshtastic ${base16
.stringify(node.user?.macaddr.subarray(4, 6) ?? [])
.toLowerCase()}`
? `Meshtastic ${
base16
.stringify(node.user?.macaddr.subarray(4, 6) ?? [])
.toLowerCase()
}`
: `!${numberToHexUnpadded(node.num)}`)}
</h1>,
<Mono key="model">
{Protobuf.Mesh.HardwareModel[node.user?.hwModel ?? 0]}
</Mono>,
<Mono key="addr">
{base16
.stringify(node.user?.macaddr ?? [])
.match(/.{1,2}/g)
?.join(":") ?? "UNK"}
<Mono key="hops">
{node.lastHeard !== 0
? node.viaMqtt === false && node.hopsAway === 0
? "Direct"
: `${node.hopsAway?.toString()} ${
node.hopsAway > 1 ? "hops" : "hop"
} away`
: "-"}
{node.viaMqtt === true ? ", via MQTT" : ""}
</Mono>,
<Mono key="lastHeard">
{node.lastHeard === 0 ? (
<p>Never</p>
) : (
<TimeAgo timestamp={node.lastHeard * 1000} />
)}
{node.lastHeard === 0
? <p>Never</p>
: <TimeAgo timestamp={node.lastHeard * 1000} />}
</Mono>,
<Mono key="pki">
{node.user?.publicKey && node.user?.publicKey.length > 0
? <LockIcon className="text-green-600 mx-auto" />
: <LockOpenIcon className="text-yellow-300 mx-auto" />}
</Mono>,
<Mono key="snr">
{node.snr}db/
{Math.min(Math.max((node.snr + 10) * 5, 0), 100)}%/
{(node.snr + 10) * 5}raw
</Mono>,
<Mono key="pki">
{node.user?.publicKey && node.user?.publicKey.length > 0 ? (
<LockIcon className="text-green-600 mx-auto" />
) : (
<LockOpenIcon className="text-yellow-300 mx-auto" />
)}
<Mono key="model">
{Protobuf.Mesh.HardwareModel[node.user?.hwModel ?? 0]}
</Mono>,
<Mono key="hops">
{node.lastHeard !== 0
? node.viaMqtt === false && node.hopsAway === 0
? "Direct"
: `${node.hopsAway?.toString()} ${node.hopsAway > 1 ? "hops" : "hop"
} away`
: "-"}
{node.viaMqtt === true ? ", via MQTT" : ""}
<Mono key="addr">
{base16
.stringify(node.user?.macaddr ?? [])
.match(/.{1,2}/g)
?.join(":") ?? "UNK"}
</Mono>,
])}
/>

82
src/validation/config/network.ts

@ -1,61 +1,27 @@
import type { Message } from "@bufbuild/protobuf";
import { z } from "zod";
import { Protobuf } from "@meshtastic/core";
import {
IsBoolean,
IsEnum,
IsIP,
IsOptional,
IsString,
Length,
} from "class-validator";
export class NetworkValidation
implements
Omit<Protobuf.Config.Config_NetworkConfig, keyof Message | "ipv4Config"> {
@IsBoolean()
wifiEnabled: boolean;
const AddressModeEnum = z.nativeEnum(Protobuf.Config.Config_NetworkConfig_AddressMode);
const ProtocolFlagsEnum = z.nativeEnum(Protobuf.Config.Config_NetworkConfig_ProtocolFlags);
export const NetworkValidationIpV4ConfigSchema = z.object({
ip: z.string().ip(),
gateway: z.string().ip(),
subnet: z.string().ip(),
dns: z.string().ip(),
});
export const NetworkValidationSchema = z.object({
wifiEnabled: z.boolean(),
wifiSsid: z.string().min(0).max(33).optional(),
wifiPsk: z.string().min(0).max(64).optional(),
ntpServer: z.string().min(2).max(30),
ethEnabled: z.boolean(),
addressMode: AddressModeEnum,
ipv4Config: NetworkValidationIpV4ConfigSchema.optional(),
enabledProtocols: ProtocolFlagsEnum,
rsyslogServer: z.string(),
});
export type NetworkValidation = z.infer<typeof NetworkValidationSchema>;
@Length(1, 33)
@IsOptional({})
wifiSsid: string;
@Length(8, 64)
@IsOptional()
wifiPsk: string;
@Length(2, 30)
ntpServer: string;
@IsBoolean()
ethEnabled: boolean;
@IsEnum(Protobuf.Config.Config_NetworkConfig_AddressMode)
addressMode: Protobuf.Config.Config_NetworkConfig_AddressMode;
ipv4Config: NetworkValidationIpV4Config;
@IsString()
rsyslogServer: string;
}
export class NetworkValidationIpV4Config implements
Omit<
Protobuf.Config.Config_NetworkConfig_IpV4Config,
keyof Message | "ip" | "gateway" | "subnet" | "dns"
> {
@IsIP()
@IsOptional()
ip: string;
@IsIP()
@IsOptional()
gateway: string;
@IsIP()
@IsOptional()
subnet: string;
@IsIP()
@IsOptional()
dns: string;
}

13
src/validation/validate.ts

@ -0,0 +1,13 @@
import { ZodError, ZodSchema } from "zod";
export function validateSchema<T>(
schema: ZodSchema<T>,
data: unknown
): { success: true; data: T } | { success: false; errors: ZodError["issues"] } {
const result = schema.safeParse(data);
if (result.success) {
return { success: true, data: result.data };
} else {
return { success: false, errors: result.error.issues };
}
}

2
vitest.config.ts

@ -9,9 +9,9 @@ export default defineConfig({
resolve: {
alias: {
'@app': path.resolve(process.cwd(), './src'),
'@core': path.resolve(process.cwd(), './src/core'),
'@pages': path.resolve(process.cwd(), './src/pages'),
'@components': path.resolve(process.cwd(), './src/components'),
'@core': path.resolve(process.cwd(), './src/core'),
'@layouts': path.resolve(process.cwd(), './src/layouts'),
},
},

Loading…
Cancel
Save