Remove duplicate node logic, UI Update, flatten build output (#586)
* refactor nodes to getNodes fn. ui updates * fixed several styling issues * fix: message specific styling/overflow * added footer, fixed tests. styling * fix: added theme support back to app component * fix: hide emojis/reactions * fix: added more padding to content element * fix: fixed padding in content element * updated color scheme * fix: more dark mode styling improvements * fix: padding and alignment fixes * fix: prevent left sidebar collapse, added battery component * fix: change scrollbars to "tiny" style, improved message scrolling, fixed bug with message input * message store fixes, ui fixes * fix: disabled message persistance until after release
This commit is contained in:
@@ -0,0 +1,86 @@
|
||||
import React from 'react';
|
||||
import {
|
||||
PlugZapIcon,
|
||||
BatteryFullIcon,
|
||||
BatteryMediumIcon,
|
||||
BatteryLowIcon,
|
||||
} from 'lucide-react';
|
||||
import { Subtle } from "@components/UI/Typography/Subtle.tsx";
|
||||
|
||||
interface DeviceMetrics {
|
||||
batteryLevel?: number | null;
|
||||
voltage?: number | null;
|
||||
}
|
||||
|
||||
interface BatteryStatusProps {
|
||||
deviceMetrics?: DeviceMetrics | null;
|
||||
}
|
||||
|
||||
interface BatteryStateConfig {
|
||||
condition: (level: number) => boolean;
|
||||
Icon: React.ElementType;
|
||||
className: string;
|
||||
text: (level: number) => string;
|
||||
}
|
||||
|
||||
const batteryStates: BatteryStateConfig[] = [
|
||||
{
|
||||
condition: level => level > 100,
|
||||
Icon: PlugZapIcon,
|
||||
className: 'text-gray-500',
|
||||
text: () => 'Plugged in',
|
||||
},
|
||||
{
|
||||
condition: level => level > 80,
|
||||
Icon: BatteryFullIcon,
|
||||
className: 'text-green-500',
|
||||
text: level => `${level}% charging`,
|
||||
},
|
||||
{
|
||||
condition: level => level > 20,
|
||||
Icon: BatteryMediumIcon,
|
||||
className: 'text-yellow-500',
|
||||
text: level => `${level}% charging`,
|
||||
},
|
||||
{
|
||||
condition: () => true,
|
||||
Icon: BatteryLowIcon,
|
||||
className: 'text-red-500',
|
||||
text: level => `${level}% charging`,
|
||||
},
|
||||
];
|
||||
|
||||
const getBatteryState = (level: number) => {
|
||||
return batteryStates.find(state => state.condition(level));
|
||||
};
|
||||
|
||||
|
||||
const BatteryStatus: React.FC<BatteryStatusProps> = ({ deviceMetrics }) => {
|
||||
if (deviceMetrics?.batteryLevel === undefined || deviceMetrics?.batteryLevel === null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const { batteryLevel, voltage } = deviceMetrics;
|
||||
const currentState = getBatteryState(batteryLevel) ?? batteryStates[batteryStates.length - 1];
|
||||
|
||||
|
||||
const BatteryIcon = currentState.Icon;
|
||||
const iconClassName = currentState.className;
|
||||
const statusText = currentState.text(batteryLevel);
|
||||
|
||||
const voltageTitle = `${voltage?.toPrecision(3) ?? 'Unknown'} volts`;
|
||||
|
||||
return (
|
||||
<div
|
||||
className="flex items-center gap-1 mt-0.5 text-gray-500"
|
||||
title={voltageTitle}
|
||||
>
|
||||
<BatteryIcon size={22} className={iconClassName} />
|
||||
<Subtle aria-label="Battery">
|
||||
{statusText}
|
||||
</Subtle>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default BatteryStatus;
|
||||
@@ -60,7 +60,7 @@ export const CommandPalette = () => {
|
||||
setSelectedDevice,
|
||||
} = useAppStore();
|
||||
const { getDevices } = useDeviceStore();
|
||||
const { setDialogOpen, setActivePage, connection } = useDevice();
|
||||
const { setDialogOpen, setActivePage, getNode, connection } = useDevice();
|
||||
const { pinnedItems, togglePinnedItem } = usePinnedItems({ storageName: 'pinnedCommandMenuGroups' });
|
||||
|
||||
const groups: Group[] = [
|
||||
@@ -115,12 +115,12 @@ export const CommandPalette = () => {
|
||||
icon: ArrowLeftRightIcon,
|
||||
subItems: getDevices().map((device) => ({
|
||||
label:
|
||||
device.nodes.get(device.hardware.myNodeNum)?.user?.longName ??
|
||||
getNode(device.hardware.myNodeNum)?.user?.longName ??
|
||||
device.hardware.myNodeNum.toString(),
|
||||
icon: (
|
||||
<Avatar
|
||||
text={
|
||||
device.nodes.get(device.hardware.myNodeNum)?.user?.shortName ??
|
||||
getNode(device.hardware.myNodeNum)?.user?.shortName ??
|
||||
device.hardware.myNodeNum.toString()
|
||||
}
|
||||
/>
|
||||
@@ -222,7 +222,7 @@ export const CommandPalette = () => {
|
||||
label: "Clear All Stored Message",
|
||||
icon: EraserIcon,
|
||||
action() {
|
||||
setDialogOpen("clearMessages", true);
|
||||
setDialogOpen("deleteMessages", true);
|
||||
},
|
||||
},
|
||||
],
|
||||
@@ -262,7 +262,7 @@ export const CommandPalette = () => {
|
||||
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"
|
||||
"transition-all duration-300 scale-100 cursor-pointer p-2 focus:*:data-label:opacity-100"
|
||||
)}
|
||||
aria-description={
|
||||
pinnedItems.includes(group.label)
|
||||
|
||||
@@ -1,76 +0,0 @@
|
||||
import { DeviceSelectorButton } from "@components/DeviceSelectorButton.tsx";
|
||||
import ThemeSwitcher from "@components/ThemeSwitcher.tsx";
|
||||
import { Separator } from "@components/UI/Seperator.tsx";
|
||||
import { Code } from "@components/UI/Typography/Code.tsx";
|
||||
import { useAppStore } from "@core/stores/appStore.ts";
|
||||
import { useDeviceStore } from "@core/stores/deviceStore.ts";
|
||||
import { HomeIcon, PlusIcon, SearchIcon } from "lucide-react";
|
||||
import { Avatar } from "@components/UI/Avatar.tsx";
|
||||
|
||||
export const DeviceSelector = () => {
|
||||
const { getDevices } = useDeviceStore();
|
||||
const {
|
||||
selectedDevice,
|
||||
setSelectedDevice,
|
||||
setCommandPaletteOpen,
|
||||
setConnectDialogOpen,
|
||||
} = useAppStore();
|
||||
|
||||
return (
|
||||
<nav className="flex flex-col justify-between border-r-[0.5px] border-slate-300 pt-2 dark:border-slate-700">
|
||||
<div className="flex flex-col overflow-y-hidden">
|
||||
<ul className="flex w-20 grow flex-col items-center space-y-4 bg-transparent py-4 px-5">
|
||||
<DeviceSelectorButton
|
||||
active={selectedDevice === 0}
|
||||
onClick={() => {
|
||||
setSelectedDevice(0);
|
||||
}}
|
||||
>
|
||||
<HomeIcon />
|
||||
</DeviceSelectorButton>
|
||||
{getDevices().map((device) => (
|
||||
<DeviceSelectorButton
|
||||
key={device.id}
|
||||
onClick={() => {
|
||||
setSelectedDevice(device.id);
|
||||
}}
|
||||
active={selectedDevice === device.id}
|
||||
>
|
||||
<Avatar
|
||||
text={device.nodes
|
||||
.get(device.hardware.myNodeNum)
|
||||
?.user?.shortName.toString() ?? "UNK"}
|
||||
/>
|
||||
</DeviceSelectorButton>
|
||||
))}
|
||||
<Separator />
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setConnectDialogOpen(true)}
|
||||
className="transition-all duration-300"
|
||||
>
|
||||
<PlusIcon />
|
||||
</button>
|
||||
</ul>
|
||||
</div>
|
||||
<div className="flex w-20 flex-col items-center space-y-5 px-5 pb-5">
|
||||
<ThemeSwitcher />
|
||||
<button
|
||||
type="button"
|
||||
className="transition-all hover:text-accent"
|
||||
onClick={() => setCommandPaletteOpen(true)}
|
||||
>
|
||||
<SearchIcon />
|
||||
</button>
|
||||
{/* TODO: This is being commented out until its fixed */}
|
||||
{
|
||||
/* <button type="button" className="transition-all hover:text-accent">
|
||||
<LanguagesIcon />
|
||||
</button> */
|
||||
}
|
||||
<Separator />
|
||||
<Code>{import.meta.env.VITE_COMMIT_HASH}</Code>
|
||||
</div>
|
||||
</nav>
|
||||
);
|
||||
};
|
||||
@@ -1,25 +0,0 @@
|
||||
export interface DeviceSelectorButtonProps {
|
||||
active: boolean;
|
||||
onClick: () => void;
|
||||
children?: React.ReactNode;
|
||||
}
|
||||
|
||||
export const DeviceSelectorButton = ({
|
||||
onClick,
|
||||
children,
|
||||
}: DeviceSelectorButtonProps) => (
|
||||
<li
|
||||
className="aspect-w-1 aspect-h-1 relative w-full"
|
||||
onClick={onClick}
|
||||
onKeyDown={onClick}
|
||||
>
|
||||
{
|
||||
/* {active && (
|
||||
<div className="absolute -left-2 h-10 w-1.5 rounded-full bg-accent" />
|
||||
)} */
|
||||
}
|
||||
<div className="flex aspect-square cursor-pointer flex-col items-center justify-center">
|
||||
{children}
|
||||
</div>
|
||||
</li>
|
||||
);
|
||||
@@ -1,9 +1,10 @@
|
||||
import { render, screen, fireEvent } from '@testing-library/react';
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { useMessageStore } from "@core/stores/messageStore.ts";
|
||||
// Ensure the path is correct for import
|
||||
import { useMessageStore } from "../../../core/stores/messageStore/index.ts";
|
||||
import { DeleteMessagesDialog } from "@components/Dialog/DeleteMessagesDialog/DeleteMessagesDialog.tsx";
|
||||
|
||||
vi.mock('@core/stores/messageStore.ts', () => ({
|
||||
vi.mock('@core/stores/messageStore', () => ({
|
||||
useMessageStore: vi.fn(() => ({
|
||||
deleteAllMessages: vi.fn(),
|
||||
})),
|
||||
@@ -14,17 +15,36 @@ describe('DeleteMessagesDialog', () => {
|
||||
const mockClearAllMessages = vi.fn();
|
||||
|
||||
beforeEach(() => {
|
||||
vi.mocked(useMessageStore).mockReturnValue({ deleteAllMessages: mockClearAllMessages });
|
||||
mockOnOpenChange.mockClear();
|
||||
mockClearAllMessages.mockClear();
|
||||
|
||||
const mockedUseMessageStore = vi.mocked(useMessageStore);
|
||||
mockedUseMessageStore.mockImplementation(() => ({
|
||||
deleteAllMessages: mockClearAllMessages
|
||||
}));
|
||||
mockedUseMessageStore.mockClear();
|
||||
|
||||
});
|
||||
|
||||
it('calls onOpenChange with false when the close button (X) is clicked', () => {
|
||||
render(<DeleteMessagesDialog open={true} onOpenChange={mockOnOpenChange} />);
|
||||
const closeButton = screen.queryByTestId('dialog-close-button');
|
||||
if (!closeButton) {
|
||||
throw new Error("Dialog close button with data-testid='dialog-close-button' not found. Did you add it to the component?");
|
||||
}
|
||||
fireEvent.click(closeButton);
|
||||
expect(mockOnOpenChange).toHaveBeenCalledTimes(1);
|
||||
expect(mockOnOpenChange).toHaveBeenCalledWith(false);
|
||||
});
|
||||
|
||||
|
||||
|
||||
it('renders the dialog when open is true', () => {
|
||||
render(<DeleteMessagesDialog open={true} onOpenChange={mockOnOpenChange} />);
|
||||
expect(screen.getByText('Clear All Messages')).toBeVisible();
|
||||
expect(screen.getByText(/This action will clear all message history./)).toBeVisible();
|
||||
expect(screen.getByRole('button', { name: 'Dismiss' })).toBeVisible();
|
||||
expect(screen.getByRole('button', { name: 'Clear Messages' })).toBeVisible();
|
||||
expect(screen.getByText('Clear All Messages')).toBeInTheDocument();
|
||||
expect(screen.getByText(/This action will clear all message history./)).toBeInTheDocument();
|
||||
expect(screen.getByRole('button', { name: 'Dismiss' })).toBeInTheDocument();
|
||||
expect(screen.getByRole('button', { name: 'Clear Messages' })).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('does not render the dialog when open is false', () => {
|
||||
@@ -32,15 +52,10 @@ describe('DeleteMessagesDialog', () => {
|
||||
expect(screen.queryByText('Clear All Messages')).toBeNull();
|
||||
});
|
||||
|
||||
it('calls onOpenChange with false when the close button is clicked', () => {
|
||||
render(<DeleteMessagesDialog open={true} onOpenChange={mockOnOpenChange} />);
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Close' }));
|
||||
expect(mockOnOpenChange).toHaveBeenCalledWith(false);
|
||||
});
|
||||
|
||||
it('calls onOpenChange with false when the dismiss button is clicked', () => {
|
||||
render(<DeleteMessagesDialog open={true} onOpenChange={mockOnOpenChange} />);
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Dismiss' }));
|
||||
expect(mockOnOpenChange).toHaveBeenCalledTimes(1); // Add count check
|
||||
expect(mockOnOpenChange).toHaveBeenCalledWith(false);
|
||||
});
|
||||
|
||||
@@ -48,6 +63,7 @@ describe('DeleteMessagesDialog', () => {
|
||||
render(<DeleteMessagesDialog open={true} onOpenChange={mockOnOpenChange} />);
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Clear Messages' }));
|
||||
expect(mockClearAllMessages).toHaveBeenCalledTimes(1);
|
||||
expect(mockOnOpenChange).toHaveBeenCalledTimes(1); // Add count check
|
||||
expect(mockOnOpenChange).toHaveBeenCalledWith(false);
|
||||
});
|
||||
});
|
||||
@@ -10,7 +10,7 @@ import {
|
||||
DialogTitle,
|
||||
} from "@components/UI/Dialog.tsx";
|
||||
import { AlertTriangleIcon } from "lucide-react";
|
||||
import { useMessageStore } from "@core/stores/messageStore.ts";
|
||||
import { useMessageStore } from "../../../core/stores/messageStore/index.ts";
|
||||
|
||||
export interface DeleteMessagesDialogProps {
|
||||
open: boolean;
|
||||
@@ -29,7 +29,7 @@ export const DeleteMessagesDialog = ({
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent>
|
||||
<DialogClose onClick={handleCloseDialog} />
|
||||
<DialogClose data-testid="dialog-close-button" />
|
||||
<DialogHeader>
|
||||
<DialogTitle className="flex items-center gap-2">
|
||||
<AlertTriangleIcon className="h-5 w-5 text-warning" />
|
||||
|
||||
@@ -10,10 +10,11 @@ import {
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from "@components/UI/Dialog.tsx";
|
||||
import { Input } from "@components/UI/Input.tsx";
|
||||
import { Label } from "@components/UI/Label.tsx";
|
||||
import { Protobuf } from "@meshtastic/core";
|
||||
import { useForm } from "react-hook-form";
|
||||
import { GenericInput } from "@components/Form/FormInput.tsx";
|
||||
import { validateMaxByteLength } from "@core/utils/string.ts";
|
||||
|
||||
export interface User {
|
||||
longName: string;
|
||||
@@ -24,32 +25,44 @@ export interface DeviceNameDialogProps {
|
||||
open: boolean;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
}
|
||||
const MAX_LONG_NAME_BYTE_LENGTH = 40;
|
||||
const MAX_SHORT_NAME_BYTE_LENGTH = 4;
|
||||
|
||||
export const DeviceNameDialog = ({
|
||||
open,
|
||||
onOpenChange,
|
||||
}: DeviceNameDialogProps) => {
|
||||
const { hardware, nodes, connection } = useDevice();
|
||||
const { hardware, getNode, connection } = useDevice();
|
||||
const myNode = getNode(hardware.myNodeNum);
|
||||
|
||||
const myNode = nodes.get(hardware.myNodeNum);
|
||||
const defaultValues = {
|
||||
longName: myNode?.user?.longName ?? "Unknown",
|
||||
shortName: myNode?.user?.shortName ?? "??",
|
||||
};
|
||||
|
||||
const { register, handleSubmit } = useForm<User>({
|
||||
values: {
|
||||
longName: myNode?.user?.longName ?? "Unknown",
|
||||
shortName: myNode?.user?.shortName ?? "Unknown",
|
||||
},
|
||||
const { getValues, setValue, reset, control, handleSubmit } = useForm<User>({
|
||||
values: defaultValues,
|
||||
});
|
||||
|
||||
const { currentLength: currentLongNameLength } = validateMaxByteLength(getValues('longName'), MAX_LONG_NAME_BYTE_LENGTH);
|
||||
const { currentLength: currentShortNameLength } = validateMaxByteLength(getValues('shortName'), MAX_SHORT_NAME_BYTE_LENGTH);
|
||||
|
||||
const onSubmit = handleSubmit((data) => {
|
||||
connection?.setOwner(
|
||||
create(Protobuf.Mesh.UserSchema, {
|
||||
...myNode?.user,
|
||||
...(myNode?.user ?? {}),
|
||||
...data,
|
||||
}),
|
||||
);
|
||||
onOpenChange(false);
|
||||
});
|
||||
|
||||
const handleReset = () => {
|
||||
reset({ longName: "", shortName: "" });
|
||||
setValue("longName", "");
|
||||
setValue("shortName", "");
|
||||
};
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent>
|
||||
@@ -60,22 +73,51 @@ export const DeviceNameDialog = ({
|
||||
The Device will restart once the config is saved.
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
<div className="gap-4">
|
||||
<form onSubmit={onSubmit}>
|
||||
<Label>Long Name</Label>
|
||||
<Input className="dark:text-slte-900" {...register("longName")} />
|
||||
<Label>Short Name</Label>
|
||||
<Input
|
||||
className="dark:text-slte-900"
|
||||
maxLength={4}
|
||||
{...register("shortName")}
|
||||
<form onSubmit={onSubmit} className="flex flex-col gap-4">
|
||||
<div>
|
||||
<Label htmlFor="longName">Long Name</Label>
|
||||
<GenericInput
|
||||
control={control}
|
||||
field={{
|
||||
name: "longName",
|
||||
label: "Long Name",
|
||||
type: "text",
|
||||
properties: {
|
||||
className: 'text-slate-900 dark:text-slate-200',
|
||||
fieldLength: {
|
||||
currentValueLength: currentLongNameLength ?? 0,
|
||||
max: MAX_LONG_NAME_BYTE_LENGTH,
|
||||
showCharacterCount: true,
|
||||
},
|
||||
},
|
||||
}}
|
||||
/>
|
||||
</form>
|
||||
</div>
|
||||
<DialogFooter>
|
||||
<Button onClick={() => onSubmit()}>Save</Button>
|
||||
</DialogFooter>
|
||||
</div>
|
||||
<div>
|
||||
<Label htmlFor="shortName">Short Name</Label>
|
||||
<GenericInput
|
||||
control={control}
|
||||
field={{
|
||||
name: "shortName",
|
||||
label: "Short Name",
|
||||
type: "text",
|
||||
properties: {
|
||||
fieldLength: {
|
||||
currentValueLength: currentShortNameLength ?? 0,
|
||||
max: MAX_SHORT_NAME_BYTE_LENGTH,
|
||||
showCharacterCount: true,
|
||||
},
|
||||
},
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<DialogFooter>
|
||||
<Button type="button" variant="destructive" onClick={handleReset}>Reset</Button>
|
||||
<Button type="submit">Save</Button>
|
||||
</DialogFooter>
|
||||
</form>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
};
|
||||
};
|
||||
@@ -109,7 +109,6 @@ export const ImportDialog = ({
|
||||
<Input
|
||||
value={importDialogInput}
|
||||
suffix={validUrl ? "✅" : "❌"}
|
||||
className="dark:text-slate-900"
|
||||
onChange={(e) => {
|
||||
setImportDialogInput(e.target.value);
|
||||
}}
|
||||
|
||||
@@ -21,9 +21,9 @@ export const LocationResponseDialog = ({
|
||||
open,
|
||||
onOpenChange,
|
||||
}: LocationResponseDialogProps) => {
|
||||
const { nodes } = useDevice();
|
||||
const { getNode } = useDevice();
|
||||
|
||||
const from = nodes.get(location?.from ?? 0);
|
||||
const from = getNode(location?.from ?? 0);
|
||||
const longName = from?.user?.longName ??
|
||||
(from ? `!${numberToHexUnpadded(from?.num)}` : "Unknown");
|
||||
const shortName = from?.user?.shortName ??
|
||||
|
||||
@@ -1,12 +1,17 @@
|
||||
import { describe, it, vi, expect, beforeEach, Mock } from "vitest";
|
||||
import { describe, it, vi, expect, beforeEach } from "vitest";
|
||||
import { render, screen } from "@testing-library/react";
|
||||
import { NodeDetailsDialog } from "@components/Dialog/NodeDetailsDialog/NodeDetailsDialog.tsx";
|
||||
import { useDevice } from "@core/stores/deviceStore.ts";
|
||||
import { useAppStore } from "@core/stores/appStore.ts";
|
||||
import { Protobuf } from "@meshtastic/core";
|
||||
|
||||
vi.mock("@core/stores/deviceStore");
|
||||
vi.mock("@core/stores/appStore");
|
||||
|
||||
const mockUseDevice = vi.mocked(useDevice);
|
||||
const mockUseAppStore = vi.mocked(useAppStore);
|
||||
|
||||
|
||||
describe("NodeDetailsDialog", () => {
|
||||
const mockDevice = {
|
||||
num: 1234,
|
||||
@@ -29,17 +34,21 @@ describe("NodeDetailsDialog", () => {
|
||||
voltage: 4.2,
|
||||
uptimeSeconds: 3600,
|
||||
},
|
||||
};
|
||||
} as unknown as Protobuf.Mesh.NodeInfo;
|
||||
|
||||
beforeEach(() => {
|
||||
// Reset mocks before each test
|
||||
vi.resetAllMocks();
|
||||
|
||||
(useDevice as Mock).mockReturnValue({
|
||||
nodes: new Map([[1234, mockDevice]]),
|
||||
mockUseDevice.mockReturnValue({
|
||||
getNode: (nodeNum: number) => {
|
||||
if (nodeNum === 1234) {
|
||||
return mockDevice;
|
||||
}
|
||||
return undefined;
|
||||
},
|
||||
});
|
||||
|
||||
(useAppStore as unknown as Mock).mockReturnValue({
|
||||
mockUseAppStore.mockReturnValue({
|
||||
nodeNumDetails: 1234,
|
||||
});
|
||||
});
|
||||
@@ -47,27 +56,87 @@ describe("NodeDetailsDialog", () => {
|
||||
it("renders node details correctly", () => {
|
||||
render(<NodeDetailsDialog open={true} onOpenChange={() => { }} />);
|
||||
|
||||
expect(screen.getByText(/Node Details for Test Node/i)).toBeInTheDocument();
|
||||
expect(screen.getByText(/Node Details for Test Node \(TN\)/i)).toBeInTheDocument();
|
||||
|
||||
expect(screen.getByText("Node Number: 1234")).toBeInTheDocument();
|
||||
expect(screen.getByText(/Node Hex: !/i)).toBeInTheDocument();
|
||||
expect(screen.getByText(/Last Heard:/i)).toBeInTheDocument();
|
||||
|
||||
expect(screen.getByText(/Coordinates:/i)).toBeInTheDocument();
|
||||
const link = screen.getByRole('link', { name: /^45, -75$/ });
|
||||
|
||||
expect(link).toBeInTheDocument();
|
||||
expect(link).toHaveAttribute('href', expect.stringContaining('openstreetmap.org'));
|
||||
expect(screen.getByText(/Altitude: 200m/i)).toBeInTheDocument();
|
||||
|
||||
|
||||
expect(screen.getByText(/Air TX utilization: 50.12%/i)).toBeInTheDocument();
|
||||
expect(screen.getByText(/Channel utilization: 75.46%/i)).toBeInTheDocument();
|
||||
expect(screen.getByText(/Battery level: 88.79%/i)).toBeInTheDocument();
|
||||
expect(screen.getByText(/Voltage: 4.20V/i)).toBeInTheDocument();
|
||||
expect(screen.getByText(/Uptime:/i)).toBeInTheDocument();
|
||||
expect(screen.getByText(/Coordinates:/i)).toBeInTheDocument();
|
||||
expect(screen.getByText("45, -75")).toBeInTheDocument();
|
||||
expect(screen.getByText(/Altitude: 200m/i)).toBeInTheDocument();
|
||||
expect(screen.getByText(/Role:/i)).toBeInTheDocument();
|
||||
|
||||
expect(screen.getByText(/All Raw Metrics:/i)).toBeInTheDocument();
|
||||
|
||||
});
|
||||
|
||||
it("renders null if device is not found", () => {
|
||||
(useDevice as Mock).mockReturnValue({
|
||||
nodes: new Map(),
|
||||
const requestedNodeNum = 5678;
|
||||
|
||||
mockUseAppStore.mockReturnValue({
|
||||
nodeNumDetails: requestedNodeNum,
|
||||
});
|
||||
|
||||
render(<NodeDetailsDialog open={true} onOpenChange={() => { }} />);
|
||||
mockUseDevice.mockReturnValue({
|
||||
getNode: (nodeNum: number) => {
|
||||
if (nodeNum === requestedNodeNum) {
|
||||
return undefined;
|
||||
}
|
||||
if (nodeNum === 1234) {
|
||||
return mockDevice;
|
||||
}
|
||||
return undefined;
|
||||
},
|
||||
});
|
||||
|
||||
const { container } = render(<NodeDetailsDialog open={true} onOpenChange={() => { }} />);
|
||||
|
||||
expect(container.firstChild).toBeNull();
|
||||
expect(screen.queryByText(/Node Details for/i)).not.toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
it("renders correctly when position is missing", () => {
|
||||
const nodeWithoutPosition = { ...mockDevice, position: undefined };
|
||||
mockUseDevice.mockReturnValue({ getNode: () => nodeWithoutPosition });
|
||||
mockUseAppStore.mockReturnValue({ nodeNumDetails: 1234 });
|
||||
|
||||
render(<NodeDetailsDialog open={true} onOpenChange={() => { }} />);
|
||||
|
||||
expect(screen.queryByText(/Coordinates:/i)).not.toBeInTheDocument();
|
||||
expect(screen.queryByText(/Altitude:/i)).not.toBeInTheDocument();
|
||||
expect(screen.getByText(/Node Details for Test Node/i)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("renders correctly when deviceMetrics are missing", () => {
|
||||
const nodeWithoutMetrics = { ...mockDevice, deviceMetrics: undefined };
|
||||
mockUseDevice.mockReturnValue({ getNode: () => nodeWithoutMetrics });
|
||||
mockUseAppStore.mockReturnValue({ nodeNumDetails: 1234 });
|
||||
|
||||
render(<NodeDetailsDialog open={true} onOpenChange={() => { }} />);
|
||||
|
||||
expect(screen.queryByText(/Device Metrics:/i)).not.toBeInTheDocument();
|
||||
expect(screen.queryByText(/Air TX utilization:/i)).not.toBeInTheDocument();
|
||||
expect(screen.getByText(/Node Details for Test Node/i)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("renders 'Never' for lastHeard when timestamp is 0", () => {
|
||||
const nodeNeverHeard = { ...mockDevice, lastHeard: 0 };
|
||||
mockUseDevice.mockReturnValue({ getNode: () => nodeNeverHeard });
|
||||
mockUseAppStore.mockReturnValue({ nodeNumDetails: 1234 });
|
||||
|
||||
render(<NodeDetailsDialog open={true} onOpenChange={() => { }} />);
|
||||
|
||||
expect(screen.getByText(/Last Heard: Never/i)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
});
|
||||
@@ -29,10 +29,10 @@ export const NodeDetailsDialog = ({
|
||||
open,
|
||||
onOpenChange,
|
||||
}: NodeDetailsDialogProps) => {
|
||||
const { nodes } = useDevice();
|
||||
const { getNode } = useDevice();
|
||||
const { nodeNumDetails } = useAppStore();
|
||||
|
||||
const device = nodes.get(nodeNumDetails);
|
||||
const device = getNode(nodeNumDetails);
|
||||
|
||||
if (!device) return null;
|
||||
|
||||
@@ -131,7 +131,7 @@ export const NodeDetailsDialog = ({
|
||||
|
||||
{device.deviceMetrics && (
|
||||
<div className="text-slate-900 dark:text-slate-100 bg-slate-100 dark:bg-slate-800 p-3 rounded-lg mt-3">
|
||||
<p className="text-lg font-semibold text-slate-900 dark:text-slate-50">
|
||||
<p className="text-lg font-semibold text-slate-900 dark:text-slate-0">
|
||||
Device Metrics:
|
||||
</p>
|
||||
{deviceMetricsMap.map(
|
||||
|
||||
@@ -13,7 +13,7 @@ import { numberToHexUnpadded } from "@noble/curves/abstract/utils";
|
||||
import { TrashIcon } from "lucide-react";
|
||||
|
||||
import { Button } from "../UI/Button.tsx";
|
||||
import { MessageType, useMessageStore } from "@core/stores/messageStore.ts";
|
||||
import { MessageType, useMessageStore } from "../../core/stores/messageStore/index.ts";
|
||||
|
||||
export interface NodeOptionsDialogProps {
|
||||
node: Protobuf.Mesh.NodeInfo | undefined;
|
||||
|
||||
@@ -133,8 +133,8 @@ export const QRDialog = ({
|
||||
<Input
|
||||
value={qrCodeUrl}
|
||||
disabled
|
||||
className="dark:text-slate-900"
|
||||
action={{
|
||||
key: 'copy-value',
|
||||
icon: ClipboardIcon,
|
||||
onClick() {
|
||||
void navigator.clipboard.writeText(qrCodeUrl);
|
||||
|
||||
@@ -1,102 +1,97 @@
|
||||
import { render, screen, fireEvent } from "@testing-library/react";
|
||||
import { beforeEach, describe, expect, it, vi, Mock } from "vitest";
|
||||
import { render, screen } from "@testing-library/react";
|
||||
import { DeviceContext, useDeviceStore } from "@core/stores/deviceStore.ts";
|
||||
import { RefreshKeysDialog } from "./RefreshKeysDialog.tsx";
|
||||
import { useMessageStore } from "../../../core/stores/messageStore/index.ts";
|
||||
import { useRefreshKeysDialog } from "./useRefreshKeysDialog.ts";
|
||||
import { useMessageStore } from "@core/stores/messageStore.ts"; // Import for mocking
|
||||
import { useDevice } from "@core/stores/deviceStore.ts"; // Import for mocking
|
||||
import { expect, test, vi, beforeEach, afterEach } from 'vitest';
|
||||
import { Protobuf } from "@meshtastic/core";
|
||||
|
||||
vi.mock("@core/stores/messageStore");
|
||||
vi.mock("./useRefreshKeysDialog");
|
||||
|
||||
vi.mock("@core/stores/messageStore.ts", () => ({
|
||||
useMessageStore: vi.fn(),
|
||||
}));
|
||||
const mockUseMessageStore = vi.mocked(useMessageStore);
|
||||
const mockUseRefreshKeysDialog = vi.mocked(useRefreshKeysDialog);
|
||||
|
||||
const mockNodeWithError: Partial<Protobuf.Mesh.NodeInfo> = {
|
||||
user: { longName: "Test Node Long", shortName: "TNL", id: 456 },
|
||||
};
|
||||
const mockNodes = new Map([[456, mockNodeWithError]]);
|
||||
const mockNodeErrors = new Map([[123, { node: 456 }]]);
|
||||
const getInitialState = () => useDeviceStore.getInitialState?.() ?? { devices: new Map(), remoteDevices: new Map() };
|
||||
|
||||
vi.mock("@core/stores/deviceStore.ts", () => ({
|
||||
useDevice: vi.fn(),
|
||||
}));
|
||||
beforeEach(() => {
|
||||
useDeviceStore.setState(getInitialState(), true);
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
const mockHandleCloseDialog = vi.fn();
|
||||
const mockHandleNodeRemove = vi.fn();
|
||||
vi.mock("./useRefreshKeysDialog.ts", () => ({
|
||||
useRefreshKeysDialog: vi.fn(() => ({
|
||||
handleCloseDialog: mockHandleCloseDialog,
|
||||
handleNodeRemove: mockHandleNodeRemove,
|
||||
})),
|
||||
}));
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
describe("RefreshKeysDialog Component", () => {
|
||||
let onOpenChangeMock: Mock;
|
||||
test("renders dialog when there is a node error for the active chat", () => {
|
||||
const deviceId = 1;
|
||||
const nodeWithErrorNum = 12345;
|
||||
const activeChatNum = nodeWithErrorNum;
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
onOpenChangeMock = vi.fn();
|
||||
const deviceStore = useDeviceStore.getState().addDevice(deviceId);
|
||||
|
||||
vi.mocked(useMessageStore).mockReturnValue({ activeChat: 123 });
|
||||
vi.mocked(useDevice).mockReturnValue({
|
||||
nodeErrors: mockNodeErrors,
|
||||
nodes: mockNodes,
|
||||
});
|
||||
vi.mocked(useRefreshKeysDialog).mockReturnValue({
|
||||
handleCloseDialog: mockHandleCloseDialog,
|
||||
handleNodeRemove: mockHandleNodeRemove,
|
||||
});
|
||||
deviceStore.addNodeInfo({
|
||||
num: nodeWithErrorNum,
|
||||
user: {
|
||||
id: nodeWithErrorNum.toString(),
|
||||
publicKey: new Uint8Array(0),
|
||||
hwModel: Protobuf.Mesh.HardwareModel.HELTEC_V3,
|
||||
longName: "Problem Node Long",
|
||||
shortName: "ProbNode",
|
||||
isLicensed: false,
|
||||
macaddr: new Uint8Array(0)
|
||||
},
|
||||
lastHeard: Date.now() / 1000,
|
||||
snr: 10
|
||||
} as Protobuf.Mesh.NodeInfo);
|
||||
|
||||
deviceStore.setNodeError(activeChatNum, "PKI_MISMATCH");
|
||||
|
||||
const updatedDeviceState = useDeviceStore.getState().getDevice(deviceId);
|
||||
if (!updatedDeviceState) {
|
||||
throw new Error("Failed to get updated device state from store for provider");
|
||||
}
|
||||
|
||||
mockUseMessageStore.mockReturnValue({ activeChat: activeChatNum });
|
||||
const mockHandleClose = vi.fn();
|
||||
const mockHandleRemove = vi.fn();
|
||||
mockUseRefreshKeysDialog.mockReturnValue({
|
||||
handleCloseDialog: mockHandleClose,
|
||||
handleNodeRemove: mockHandleRemove,
|
||||
});
|
||||
|
||||
it("should render the dialog with dynamic content when open and data is available", () => {
|
||||
render(<RefreshKeysDialog open onOpenChange={onOpenChangeMock} />);
|
||||
render(
|
||||
<DeviceContext.Provider value={updatedDeviceState}>
|
||||
<RefreshKeysDialog open onOpenChange={vi.fn()} />
|
||||
</DeviceContext.Provider>
|
||||
);
|
||||
|
||||
expect(screen.getByText(`Keys Mismatch - ${mockNodeWithError?.user?.longName}`)).toBeInTheDocument();
|
||||
expect(screen.getByText(new RegExp(`${mockNodeWithError?.user?.longName}.*${mockNodeWithError?.user?.shortName}`))).toBeInTheDocument();
|
||||
expect(screen.getByRole('button', { name: /request new keys/i })).toBeInTheDocument();
|
||||
expect(screen.getByRole('button', { name: /dismiss/i })).toBeInTheDocument();
|
||||
expect(screen.getByRole('button', { name: /Close/i })).toBeInTheDocument();
|
||||
expect(screen.getByText(/Keys Mismatch - Problem Node Long/)).toBeInTheDocument();
|
||||
expect(screen.getByText(/Your node is unable to send a direct message to node: Problem Node Long \(ProbNode\)/)).toBeInTheDocument();
|
||||
expect(screen.getByRole("button", { name: "Request New Keys" })).toBeInTheDocument();
|
||||
expect(screen.getByRole("button", { name: "Dismiss" })).toBeInTheDocument();
|
||||
});
|
||||
|
||||
test("does not render dialog if no error exists for active chat", () => {
|
||||
const deviceId = 1;
|
||||
const activeChatNum = 54321;
|
||||
|
||||
useDeviceStore.getState().addDevice(deviceId);
|
||||
|
||||
const currentDeviceState = useDeviceStore.getState().getDevice(deviceId);
|
||||
if (!currentDeviceState) throw new Error("Device not found");
|
||||
|
||||
mockUseMessageStore.mockReturnValue({ activeChat: activeChatNum });
|
||||
mockUseRefreshKeysDialog.mockReturnValue({
|
||||
handleCloseDialog: vi.fn(),
|
||||
handleNodeRemove: vi.fn(),
|
||||
});
|
||||
|
||||
it("should call handleNodeRemove when 'Request New Keys' button is clicked", () => {
|
||||
render(<RefreshKeysDialog open onOpenChange={onOpenChangeMock} />);
|
||||
fireEvent.click(screen.getByRole('button', { name: /request new keys/i }));
|
||||
expect(mockHandleNodeRemove).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
const { container } = render(
|
||||
<DeviceContext.Provider value={currentDeviceState}>
|
||||
<RefreshKeysDialog open onOpenChange={vi.fn()} />
|
||||
</DeviceContext.Provider>
|
||||
);
|
||||
|
||||
it("should call handleCloseDialog when 'Dismiss' button is clicked", () => {
|
||||
render(<RefreshKeysDialog open onOpenChange={onOpenChangeMock} />);
|
||||
fireEvent.click(screen.getByRole('button', { name: /dismiss/i }));
|
||||
expect(mockHandleCloseDialog).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("should call handleCloseDialog when the explicit DialogClose button is clicked", () => {
|
||||
render(<RefreshKeysDialog open onOpenChange={onOpenChangeMock} />);
|
||||
fireEvent.click(screen.getByRole('button', { name: /close/i })); // Use the aria-label
|
||||
expect(mockHandleCloseDialog).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
|
||||
it("should not render the dialog when open is false", () => {
|
||||
render(<RefreshKeysDialog open={false} onOpenChange={onOpenChangeMock} />);
|
||||
expect(screen.queryByRole("dialog")).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("should render null if nodeErrorNum is not found for activeChat", () => {
|
||||
vi.mocked(useDevice).mockReturnValue({
|
||||
nodeErrors: new Map(),
|
||||
nodes: mockNodes,
|
||||
});
|
||||
const { container } = render(<RefreshKeysDialog open onOpenChange={onOpenChangeMock} />);
|
||||
expect(container.firstChild).toBeNull();
|
||||
});
|
||||
|
||||
it("should render null if nodeWithError is not found for nodeErrorNum.node", () => {
|
||||
vi.mocked(useDevice).mockReturnValue({
|
||||
nodeErrors: mockNodeErrors,
|
||||
nodes: new Map(),
|
||||
});
|
||||
const { container } = render(<RefreshKeysDialog open onOpenChange={onOpenChangeMock} />);
|
||||
expect(container.firstChild).toBeNull();
|
||||
});
|
||||
});
|
||||
expect(container.firstChild).toBeNull();
|
||||
});
|
||||
|
||||
@@ -9,7 +9,7 @@ import { Button } from "@components/UI/Button.tsx";
|
||||
import { LockKeyholeOpenIcon } from "lucide-react";
|
||||
import { useRefreshKeysDialog } from "./useRefreshKeysDialog.ts";
|
||||
import { useDevice } from "@core/stores/deviceStore.ts";
|
||||
import { useMessageStore } from "@core/stores/messageStore.ts";
|
||||
import { useMessageStore } from "../../../core/stores/messageStore/index.ts";
|
||||
|
||||
export interface RefreshKeysDialogProps {
|
||||
open: boolean;
|
||||
@@ -18,22 +18,16 @@ export interface RefreshKeysDialogProps {
|
||||
|
||||
export const RefreshKeysDialog = ({ open, onOpenChange }: RefreshKeysDialogProps) => {
|
||||
const { activeChat } = useMessageStore();
|
||||
const { nodeErrors, nodes } = useDevice();
|
||||
const { nodeErrors, getNode } = useDevice();
|
||||
const { handleCloseDialog, handleNodeRemove } = useRefreshKeysDialog();
|
||||
|
||||
const nodeErrorNum = nodeErrors.get(activeChat);
|
||||
|
||||
if (!nodeErrorNum) {
|
||||
console.error("Node with error not found");
|
||||
return null;
|
||||
}
|
||||
|
||||
const nodeWithError = nodes.get(nodeErrorNum?.node ?? 0);
|
||||
|
||||
if (!nodeWithError) {
|
||||
console.error("Node with error not found");
|
||||
return null;
|
||||
}
|
||||
const nodeWithError = getNode(nodeErrorNum.node);
|
||||
|
||||
const text = {
|
||||
title: `Keys Mismatch - ${nodeWithError?.user?.longName ?? ""}`,
|
||||
|
||||
@@ -2,12 +2,12 @@ import { renderHook, act } from "@testing-library/react";
|
||||
import { useRefreshKeysDialog } from "./useRefreshKeysDialog.ts";
|
||||
import { beforeEach, describe, expect, it, Mock, vi } from "vitest";
|
||||
import { useDevice } from "@core/stores/deviceStore.ts";
|
||||
import { useMessageStore } from "@core/stores/messageStore/index.ts";
|
||||
|
||||
vi.mock("@core/stores/messageStore.ts", () => ({
|
||||
vi.mock("@core/stores/messageStore", () => ({
|
||||
useMessageStore: vi.fn(() => ({ activeChat: "chat-123" })),
|
||||
}));
|
||||
|
||||
vi.mock("@core/stores/deviceStore.ts", () => ({
|
||||
vi.mock("@core/stores/deviceStore", () => ({
|
||||
useDevice: vi.fn(() => ({
|
||||
removeNode: vi.fn(),
|
||||
setDialogOpen: vi.fn(),
|
||||
@@ -23,46 +23,50 @@ describe("useRefreshKeysDialog Hook", () => {
|
||||
let clearNodeErrorMock: Mock;
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
|
||||
removeNodeMock = vi.fn();
|
||||
setDialogOpenMock = vi.fn();
|
||||
getNodeErrorMock = vi.fn();
|
||||
getNodeErrorMock = vi.fn().mockReturnValue(undefined);
|
||||
clearNodeErrorMock = vi.fn();
|
||||
|
||||
(useDevice as Mock).mockReturnValue({
|
||||
vi.mocked(useDevice).mockReturnValue({
|
||||
removeNode: removeNodeMock,
|
||||
setDialogOpen: setDialogOpenMock,
|
||||
getNodeError: getNodeErrorMock,
|
||||
clearNodeError: clearNodeErrorMock,
|
||||
});
|
||||
|
||||
vi.mocked(useMessageStore).mockReturnValue({
|
||||
activeChat: "chat-123"
|
||||
});
|
||||
});
|
||||
|
||||
it("handleNodeRemove should remove the node and update dialog if there is an error", () => {
|
||||
getNodeErrorMock.mockReturnValue({ node: "node-abc" });
|
||||
|
||||
const { result } = renderHook(() => useRefreshKeysDialog());
|
||||
act(() => { result.current.handleNodeRemove(); });
|
||||
|
||||
act(() => {
|
||||
result.current.handleNodeRemove();
|
||||
});
|
||||
|
||||
expect(getNodeErrorMock).toHaveBeenCalledTimes(1);
|
||||
expect(getNodeErrorMock).toHaveBeenCalledWith("chat-123");
|
||||
expect(clearNodeErrorMock).toHaveBeenCalledTimes(1);
|
||||
expect(clearNodeErrorMock).toHaveBeenCalledWith("chat-123");
|
||||
expect(removeNodeMock).toHaveBeenCalledTimes(1);
|
||||
expect(removeNodeMock).toHaveBeenCalledWith("node-abc");
|
||||
expect(setDialogOpenMock).toHaveBeenCalledTimes(1);
|
||||
expect(setDialogOpenMock).toHaveBeenCalledWith("refreshKeys", false);
|
||||
});
|
||||
|
||||
it("handleNodeRemove should do nothing if there is no error", () => {
|
||||
getNodeErrorMock.mockReturnValue(undefined);
|
||||
|
||||
const { result } = renderHook(() => useRefreshKeysDialog());
|
||||
act(() => { result.current.handleNodeRemove(); });
|
||||
|
||||
act(() => {
|
||||
result.current.handleNodeRemove();
|
||||
});
|
||||
|
||||
expect(getNodeErrorMock).toHaveBeenCalledTimes(1);
|
||||
expect(getNodeErrorMock).toHaveBeenCalledWith("chat-123");
|
||||
expect(clearNodeErrorMock).not.toHaveBeenCalled();
|
||||
expect(removeNodeMock).not.toHaveBeenCalled();
|
||||
expect(setDialogOpenMock).not.toHaveBeenCalled();
|
||||
expect(clearNodeErrorMock).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("handleCloseDialog should close the dialog", () => {
|
||||
@@ -72,6 +76,7 @@ describe("useRefreshKeysDialog Hook", () => {
|
||||
result.current.handleCloseDialog();
|
||||
});
|
||||
|
||||
expect(setDialogOpenMock).toHaveBeenCalledTimes(1);
|
||||
expect(setDialogOpenMock).toHaveBeenCalledWith("refreshKeys", false);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,28 +1,27 @@
|
||||
import { useCallback } from "react";
|
||||
import { useDevice } from "@core/stores/deviceStore.ts";
|
||||
import { useMessageStore } from "@core/stores/messageStore.ts";
|
||||
import { useMessageStore } from "@core/stores/messageStore/index.ts";
|
||||
|
||||
export function useRefreshKeysDialog() {
|
||||
const { removeNode, setDialogOpen, clearNodeError, getNodeError } = useDevice();
|
||||
const { activeChat } = useMessageStore();
|
||||
|
||||
const handleCloseDialog = useCallback(() => {
|
||||
setDialogOpen('refreshKeys', false);
|
||||
}, [setDialogOpen]);
|
||||
|
||||
const handleNodeRemove = useCallback(() => {
|
||||
const nodeWithError = getNodeError(activeChat);
|
||||
if (!nodeWithError) {
|
||||
return;
|
||||
}
|
||||
clearNodeError(activeChat);
|
||||
handleCloseDialog();;
|
||||
handleCloseDialog();
|
||||
return removeNode(nodeWithError?.node);
|
||||
}, [activeChat, clearNodeError, setDialogOpen, removeNode]);
|
||||
|
||||
const handleCloseDialog = useCallback(() => {
|
||||
setDialogOpen('refreshKeys', false);
|
||||
}, [setDialogOpen])
|
||||
}, [activeChat, clearNodeError, getNodeError, removeNode, handleCloseDialog]);
|
||||
|
||||
return {
|
||||
handleCloseDialog,
|
||||
handleNodeRemove
|
||||
};
|
||||
|
||||
}
|
||||
@@ -21,7 +21,7 @@ export const RemoveNodeDialog = ({
|
||||
open,
|
||||
onOpenChange,
|
||||
}: RemoveNodeDialogProps) => {
|
||||
const { connection, nodes, removeNode } = useDevice();
|
||||
const { connection, getNode, removeNode } = useDevice();
|
||||
const { nodeNumToBeRemoved } = useAppStore();
|
||||
|
||||
const onSubmit = () => {
|
||||
@@ -42,7 +42,7 @@ export const RemoveNodeDialog = ({
|
||||
</DialogHeader>
|
||||
<div className="gap-4">
|
||||
<form onSubmit={onSubmit}>
|
||||
<Label>{nodes.get(nodeNumToBeRemoved)?.user?.longName}</Label>
|
||||
<Label>{getNode(nodeNumToBeRemoved)?.user?.longName}</Label>
|
||||
</form>
|
||||
</div>
|
||||
<DialogFooter>
|
||||
|
||||
@@ -41,7 +41,6 @@ export const ShutdownDialog = ({
|
||||
type="number"
|
||||
value={time}
|
||||
onChange={(e) => setTime(Number.parseInt(e.target.value))}
|
||||
className="dark:text-slate-900"
|
||||
suffix="Minutes"
|
||||
/>
|
||||
<Button
|
||||
|
||||
@@ -23,17 +23,17 @@ export const TracerouteResponseDialog = ({
|
||||
open,
|
||||
onOpenChange,
|
||||
}: TracerouteResponseDialogProps) => {
|
||||
const { nodes } = useDevice();
|
||||
const { getNode } = useDevice();
|
||||
const route: number[] = traceroute?.data.route ?? [];
|
||||
const routeBack: number[] = traceroute?.data.routeBack ?? [];
|
||||
const snrTowards = (traceroute?.data.snrTowards ?? []).map(snr => snr / 4);
|
||||
const snrBack = (traceroute?.data.snrBack ?? []).map(snr => snr / 4);
|
||||
const from = nodes.get(traceroute?.from ?? 0);
|
||||
const from = getNode(traceroute?.from ?? 0);
|
||||
const longName = from?.user?.longName ??
|
||||
(from ? `!${numberToHexUnpadded(from?.num)}` : "Unknown");
|
||||
const shortName = from?.user?.shortName ??
|
||||
(from ? `${numberToHexUnpadded(from?.num).substring(0, 4)}` : "UNK");
|
||||
const to = nodes.get(traceroute?.to ?? 0);
|
||||
const to = getNode(traceroute?.to ?? 0);
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent>
|
||||
|
||||
@@ -6,6 +6,7 @@ import { Input } from "@components/UI/Input.tsx";
|
||||
import type { ChangeEventHandler } from "react";
|
||||
import { useState } from "react";
|
||||
import { useController, type FieldValues } from "react-hook-form";
|
||||
import { cn } from "@core/utils/cn.ts";
|
||||
|
||||
export interface InputFieldProps<T> extends BaseFormBuilderProps<T> {
|
||||
type: "text" | "number" | "password";
|
||||
@@ -15,6 +16,7 @@ export interface InputFieldProps<T> extends BaseFormBuilderProps<T> {
|
||||
prefix?: string;
|
||||
suffix?: string;
|
||||
step?: number;
|
||||
className?: string;
|
||||
fieldLength?: {
|
||||
min?: number;
|
||||
max?: number;
|
||||
@@ -63,6 +65,7 @@ export function GenericInput<T extends FieldValues>({
|
||||
onChange={handleInputChange}
|
||||
showCopyButton={field.properties?.showCopyButton}
|
||||
showPasswordToggle={field.properties?.showPasswordToggle || field.type === "password"}
|
||||
className={field.properties?.className}
|
||||
{...restProperties}
|
||||
disabled={disabled}
|
||||
/>
|
||||
|
||||
@@ -24,7 +24,7 @@ export const FieldWrapper = ({
|
||||
<div className="grid grid-cols-1 lg:grid-cols-[0.6fr_2fr_.1fr] sm:items-baseline gap-4">
|
||||
<Label htmlFor={fieldName}>{label}</Label>
|
||||
<div className="max-w-3xl">
|
||||
<p className="text-sm text-slate-400">{description}</p>
|
||||
<p className="text-sm text-slate-500 dark:text-slate-400">{description}</p>
|
||||
<p hidden={valid ?? true} className="text-sm text-red-500">
|
||||
{validationText}
|
||||
</p>
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { useAppStore } from "../../../core/stores/appStore.ts";
|
||||
import type { BluetoothValidation } from "@app/validation/config/bluetooth.tsx";
|
||||
import type { BluetoothValidation } from "@app/validation/config/bluetooth.ts";
|
||||
import { create } from "@bufbuild/protobuf";
|
||||
import { DynamicForm } from "@components/Form/DynamicForm.tsx";
|
||||
import { useDevice } from "@core/stores/deviceStore.ts";
|
||||
|
||||
@@ -270,11 +270,6 @@ export const Security = () => {
|
||||
properties: {
|
||||
value: state.adminKey,
|
||||
showCopyButton: true,
|
||||
action: {
|
||||
icon: state.adminKeyVisible ? EyeOff : Eye,
|
||||
onClick: () =>
|
||||
dispatch({ type: "TOGGLE_ADMIN_KEY_VISIBILITY" }),
|
||||
},
|
||||
},
|
||||
},
|
||||
],
|
||||
|
||||
@@ -7,7 +7,7 @@ import { subscribeAll } from "@core/subscriptions.ts";
|
||||
import { randId } from "@core/utils/randId.ts";
|
||||
import { BleConnection, ServiceUuid } from "@meshtastic/js";
|
||||
import { useCallback, useEffect, useState } from "react";
|
||||
import { useMessageStore } from "@core/stores/messageStore.ts";
|
||||
import { useMessageStore } from "../../../core/stores/messageStore/index.ts";
|
||||
|
||||
export const BLE = ({ setConnectionInProgress, closeDialog }: TabElementProps) => {
|
||||
const [bleDevices, setBleDevices] = useState<BluetoothDevice[]>([]);
|
||||
@@ -43,7 +43,7 @@ export const BLE = ({ setConnectionInProgress, closeDialog }: TabElementProps) =
|
||||
{bleDevices.map((device) => (
|
||||
<Button
|
||||
key={device.id}
|
||||
className="dark:bg-slate-900 dark:text-white"
|
||||
variant="default"
|
||||
onClick={() => {
|
||||
setConnectionInProgress(true);
|
||||
onConnect(device);
|
||||
@@ -57,8 +57,10 @@ export const BLE = ({ setConnectionInProgress, closeDialog }: TabElementProps) =
|
||||
)}
|
||||
</div>
|
||||
<Button
|
||||
className="dark:bg-slate-900 dark:text-white"
|
||||
variant="default"
|
||||
onClick={async () => {
|
||||
|
||||
|
||||
await navigator.bluetooth
|
||||
.requestDevice({
|
||||
filters: [{ services: [ServiceUuid] }],
|
||||
|
||||
@@ -13,7 +13,7 @@ import { TransportHTTP } from "@meshtastic/transport-http";
|
||||
import { useState } from "react";
|
||||
import { useForm, useController } from "react-hook-form";
|
||||
import { AlertTriangle } from "lucide-react";
|
||||
import { useMessageStore } from "@core/stores/messageStore.ts";
|
||||
import { useMessageStore } from "../../../core/stores/messageStore/index.ts";
|
||||
|
||||
interface FormData {
|
||||
ip: string;
|
||||
@@ -74,7 +74,7 @@ export const HTTP = ({ closeDialog, setConnectionInProgress, connectionInProgres
|
||||
<Input
|
||||
prefix={tlsValue ? "https://" : "http://"}
|
||||
placeholder="000.000.000.000 / meshtastic.local"
|
||||
className="text-slate-900 dark:text-slate-900"
|
||||
className="text-slate-900 dark:text-slate-100"
|
||||
{...register("ip")}
|
||||
/>
|
||||
</div>
|
||||
@@ -120,7 +120,7 @@ export const HTTP = ({ closeDialog, setConnectionInProgress, connectionInProgres
|
||||
</div>
|
||||
<Button
|
||||
type="submit"
|
||||
className="dark:bg-slate-900 dark:text-white"
|
||||
variant={"default"}
|
||||
>
|
||||
<span>{connectionInProgress ? "Connecting..." : "Connect"}</span>
|
||||
</Button>
|
||||
|
||||
@@ -8,7 +8,7 @@ import { randId } from "@core/utils/randId.ts";
|
||||
import { MeshDevice } from "@meshtastic/core";
|
||||
import { TransportWebSerial } from "@meshtastic/transport-web-serial";
|
||||
import { useCallback, useEffect, useState } from "react";
|
||||
import { useMessageStore } from "@core/stores/messageStore.ts";
|
||||
import { useMessageStore } from "../../../core/stores/messageStore/index.ts";
|
||||
|
||||
export const Serial = ({ setConnectionInProgress, closeDialog }: TabElementProps) => {
|
||||
const [serialPorts, setSerialPorts] = useState<SerialPort[]>([]);
|
||||
@@ -52,7 +52,7 @@ export const Serial = ({ setConnectionInProgress, closeDialog }: TabElementProps
|
||||
<Button
|
||||
key={`${usbVendorId ?? "UNK"}-${usbProductId ?? "UNK"}-${index}`}
|
||||
disabled={port.readable !== null}
|
||||
className="dark:bg-slate-900 dark:text-white"
|
||||
variant="default"
|
||||
onClick={async () => {
|
||||
setConnectionInProgress(true);
|
||||
await onConnect(port);
|
||||
@@ -68,7 +68,7 @@ export const Serial = ({ setConnectionInProgress, closeDialog }: TabElementProps
|
||||
)}
|
||||
</div>
|
||||
<Button
|
||||
className="dark:bg-slate-900 dark:text-white"
|
||||
variant="default"
|
||||
onClick={async () => {
|
||||
await navigator.serial.requestPort().then((port) => {
|
||||
setSerialPorts(serialPorts.concat(port));
|
||||
|
||||
@@ -7,12 +7,7 @@ import { Mono } from "@components/generic/Mono.tsx";
|
||||
import { TimeAgo } from "@components/generic/TimeAgo.tsx";
|
||||
import { Protobuf } from "@meshtastic/core";
|
||||
import type { Protobuf as ProtobufType } from "@meshtastic/core";
|
||||
import { numberToHexUnpadded } from "@noble/curves/abstract/utils";
|
||||
import {
|
||||
BatteryChargingIcon,
|
||||
BatteryFullIcon,
|
||||
BatteryLowIcon,
|
||||
BatteryMediumIcon,
|
||||
Dot,
|
||||
LockIcon,
|
||||
LockOpenIcon,
|
||||
@@ -28,7 +23,8 @@ import {
|
||||
TooltipTrigger,
|
||||
} from "@radix-ui/react-tooltip";
|
||||
import { useDevice } from "@core/stores/deviceStore.ts";
|
||||
import { MessageType, useMessageStore } from "@core/stores/messageStore.ts";
|
||||
import { MessageType, useMessageStore } from "../../../core/stores/messageStore/index.ts";
|
||||
import BatteryStatus from "@components/BatteryStatus.tsx";
|
||||
|
||||
export interface NodeDetailProps {
|
||||
node: ProtobufType.Mesh.NodeInfo;
|
||||
@@ -37,7 +33,7 @@ export interface NodeDetailProps {
|
||||
export const NodeDetail = ({ node }: NodeDetailProps) => {
|
||||
const { setChatType, setActiveChat } = useMessageStore();
|
||||
const { setActivePage } = useDevice();
|
||||
const name = node.user?.longName || `!${numberToHexUnpadded(node.num)}`;
|
||||
const name = node.user?.longName ?? `UNK`;
|
||||
const shortName = node.user?.shortName ?? "UNK";
|
||||
const hwModel = node.user?.hwModel ?? 0;
|
||||
const hardwareType =
|
||||
@@ -50,10 +46,10 @@ export const NodeDetail = ({ node }: NodeDetailProps) => {
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="dark:text-slate-900 p-1">
|
||||
<div className="p-1 text-slate-900">
|
||||
<div className="flex gap-2">
|
||||
<div className="flex flex-col items-center gap-2 min-w-6 pt-1">
|
||||
<Avatar text={shortName} />
|
||||
<Avatar text={shortName} size="sm" />
|
||||
|
||||
<div onFocusCapture={(e) => {
|
||||
// Required to prevent DM tooltip auto-appearing on creation
|
||||
@@ -113,24 +109,7 @@ export const NodeDetail = ({ node }: NodeDetailProps) => {
|
||||
{hardwareType !== "UNSET" && <Subtle>{hardwareType}</Subtle>}
|
||||
|
||||
{!!node.deviceMetrics?.batteryLevel && (
|
||||
<div
|
||||
className="flex items-center gap-1 mt-0.5"
|
||||
title={`${node.deviceMetrics?.voltage?.toPrecision(3) ?? "Unknown"
|
||||
} volts`}
|
||||
>
|
||||
{node.deviceMetrics?.batteryLevel > 100
|
||||
? <BatteryChargingIcon size={22} />
|
||||
: node.deviceMetrics?.batteryLevel > 80
|
||||
? <BatteryFullIcon size={22} />
|
||||
: node.deviceMetrics?.batteryLevel > 20
|
||||
? <BatteryMediumIcon size={22} />
|
||||
: <BatteryLowIcon size={22} />}
|
||||
<Subtle aria-label="Battery">
|
||||
{node.deviceMetrics?.batteryLevel > 100
|
||||
? "Charging"
|
||||
: `${node.deviceMetrics?.batteryLevel}%`}
|
||||
</Subtle>
|
||||
</div>
|
||||
<BatteryStatus deviceMetrics={node.deviceMetrics} />
|
||||
)}
|
||||
|
||||
<div className="flex gap-2 items-center">
|
||||
@@ -198,7 +177,7 @@ export const NodeDetail = ({ node }: NodeDetailProps) => {
|
||||
{!!node.deviceMetrics?.airUtilTx && (
|
||||
<div className="grow">
|
||||
<div>Airtime Util</div>
|
||||
<Mono>{node.deviceMetrics?.airUtilTx.toPrecision(3)}%</Mono>
|
||||
<Mono className="text-gray-500">{node.deviceMetrics?.airUtilTx.toPrecision(3)}%</Mono>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
@@ -206,7 +185,7 @@ export const NodeDetail = ({ node }: NodeDetailProps) => {
|
||||
{node.snr !== 0 && (
|
||||
<div className="mt-2">
|
||||
<div>SNR</div>
|
||||
<Mono className="flex items-center text-xs">
|
||||
<Mono className="flex items-center text-xs text-gray-500">
|
||||
{node.snr}db
|
||||
<Dot />
|
||||
{Math.min(Math.max((node.snr + 10) * 5, 0), 100)}%
|
||||
|
||||
@@ -1,72 +1,77 @@
|
||||
import { MessageItem } from "@components/PageComponents/Messages/MessageItem.tsx";
|
||||
import type { Message as MessageType } from "@core/stores/messageStore.ts";
|
||||
import { InboxIcon } from "lucide-react";
|
||||
import { useCallback, useEffect, useRef } from "react";
|
||||
import { Message } from "@core/stores/messageStore/types.ts";
|
||||
|
||||
export interface ChannelChatProps {
|
||||
messages?: MessageType[];
|
||||
messages?: Message[];
|
||||
}
|
||||
|
||||
const EmptyState = () => (
|
||||
<div className="flex flex-col place-content-center place-items-center p-8 text-gray-500 dark:text-gray-400">
|
||||
<InboxIcon className="h-8 w-8 mb-2" />
|
||||
<div className="flex flex-1 flex-col place-content-center place-items-center p-8 text-slate-500 dark:text-slate-400">
|
||||
<InboxIcon className="mb-2 h-8 w-8" />
|
||||
<span className="text-sm">No Messages</span>
|
||||
</div>
|
||||
);
|
||||
|
||||
export const ChannelChat = ({
|
||||
messages = [],
|
||||
}: ChannelChatProps) => {
|
||||
export const ChannelChat = ({ messages = [] }: ChannelChatProps) => {
|
||||
const messagesEndRef = useRef<HTMLDivElement>(null);
|
||||
const scrollContainerRef = useRef<HTMLDivElement>(null);
|
||||
const scrollContainerRef = useRef<HTMLUListElement>(null);
|
||||
const userScrolledUpRef = useRef(false);
|
||||
|
||||
const scrollToBottom = useCallback(() => {
|
||||
const scrollContainer = scrollContainerRef.current;
|
||||
if (scrollContainer) {
|
||||
const isNearBottom =
|
||||
scrollContainer.scrollHeight -
|
||||
scrollContainer.scrollTop -
|
||||
scrollContainer.clientHeight <
|
||||
100;
|
||||
|
||||
if (isNearBottom) {
|
||||
messagesEndRef.current?.scrollIntoView({ behavior: "smooth" });
|
||||
}
|
||||
}
|
||||
const scrollToBottom = useCallback((behavior: ScrollBehavior = 'smooth') => {
|
||||
requestAnimationFrame(() => {
|
||||
messagesEndRef.current?.scrollIntoView({ behavior });
|
||||
});
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
scrollToBottom();
|
||||
}, [scrollToBottom, messages]);
|
||||
const scrollContainer = scrollContainerRef.current;
|
||||
if (!scrollContainer) return;
|
||||
const isScrolledToBottom = scrollContainer.scrollHeight - scrollContainer.scrollTop - scrollContainer.clientHeight <= 10;
|
||||
|
||||
if (isScrolledToBottom || !userScrolledUpRef.current) {
|
||||
scrollToBottom('smooth');
|
||||
}
|
||||
}, [messages, scrollToBottom]);
|
||||
|
||||
useEffect(() => {
|
||||
const scrollContainer = scrollContainerRef.current;
|
||||
const handleScroll = () => {
|
||||
if (!scrollContainer) return;
|
||||
const isAtBottom = scrollContainer.scrollHeight - scrollContainer.scrollTop - scrollContainer.clientHeight <= 10;
|
||||
userScrolledUpRef.current = !isAtBottom;
|
||||
};
|
||||
scrollContainer?.addEventListener('scroll', handleScroll, { passive: true });
|
||||
return () => {
|
||||
scrollContainer?.removeEventListener('scroll', handleScroll);
|
||||
};
|
||||
}, []);
|
||||
|
||||
if (!messages?.length) {
|
||||
return (
|
||||
<div className="flex flex-col h-full">
|
||||
<div className="flex-1 flex items-center justify-center">
|
||||
<EmptyState />
|
||||
</div>
|
||||
<div className="flex flex-1 flex-col items-center justify-center">
|
||||
<EmptyState />
|
||||
<div ref={messagesEndRef} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex flex-col h-full">
|
||||
<div
|
||||
ref={scrollContainerRef}
|
||||
className="flex-1 overflow-y-auto py-4"
|
||||
>
|
||||
<div className="flex flex-col justify-end min-h-full space-y-4">
|
||||
{messages?.map((message) => {
|
||||
return (
|
||||
<MessageItem
|
||||
key={message?.messageId}
|
||||
message={message}
|
||||
/>
|
||||
);
|
||||
})}
|
||||
<div ref={messagesEndRef} className="h-0 w-full" />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<ul
|
||||
ref={scrollContainerRef}
|
||||
className="flex flex-col flex-grow overflow-y-auto px-3 py-2"
|
||||
>
|
||||
<div className="flex-grow" />
|
||||
|
||||
{messages?.map((message) => (
|
||||
<MessageItem
|
||||
key={message.messageId ?? `${message.from}-${message.date}`}
|
||||
message={message}
|
||||
/>
|
||||
))}
|
||||
|
||||
<div ref={messagesEndRef} className="h-px" />
|
||||
</ul>
|
||||
);
|
||||
};
|
||||
@@ -18,7 +18,7 @@ export const MessageActionsMenu = ({
|
||||
onReply
|
||||
}: MessageActionsMenuProps) => {
|
||||
const hoverIconBarClass = cn(
|
||||
"absolute top-2 right-4",
|
||||
"absolute top-2 right-2",
|
||||
"flex items-center gap-x-1",
|
||||
"bg-white dark:bg-zinc-800",
|
||||
"border border-gray-200 dark:border-zinc-600",
|
||||
|
||||
@@ -1,14 +1,11 @@
|
||||
import { render, screen, fireEvent, waitFor } from '@testing-library/react';
|
||||
import { render, screen, fireEvent, waitFor, act } from '@testing-library/react';
|
||||
import { vi, describe, it, expect, beforeEach } from 'vitest';
|
||||
import { MessageInput } from './MessageInput.tsx';
|
||||
import { useDevice } from '@core/stores/deviceStore.ts';
|
||||
import { useMessageStore } from '@core/stores/messageStore.ts';
|
||||
import { debounce } from '@core/utils/debounce.ts';
|
||||
import { Types } from "@meshtastic/core";
|
||||
import { MessageInput, MessageInputProps } from './MessageInput.tsx';
|
||||
import { Types } from '@meshtastic/core';
|
||||
|
||||
vi.mock('@components/UI/Button.tsx', () => ({
|
||||
Button: vi.fn(({ type, className, children, onClick, onSubmit }) => (
|
||||
<button type={type} className={className} onClick={onClick} onSubmit={onSubmit}>
|
||||
Button: vi.fn(({ type, className, children, onClick, onSubmit, variant, ...rest }) => (
|
||||
<button type={type} className={className} onClick={onClick} onSubmit={onSubmit} {...rest}>
|
||||
{children}
|
||||
</button>
|
||||
)),
|
||||
@@ -23,16 +20,21 @@ vi.mock('@components/UI/Input.tsx', () => ({
|
||||
placeholder={placeholder}
|
||||
value={value}
|
||||
onChange={onChange}
|
||||
data-testid="message-input-field"
|
||||
/>
|
||||
)),
|
||||
}));
|
||||
|
||||
vi.mock('@core/stores/deviceStore.ts', () => ({
|
||||
useDevice: vi.fn(),
|
||||
}));
|
||||
const mockSetDraft = vi.fn();
|
||||
const mockGetDraft = vi.fn();
|
||||
const mockClearDraft = vi.fn();
|
||||
|
||||
vi.mock('@core/stores/messageStore.ts', () => ({
|
||||
useMessageStore: vi.fn(),
|
||||
vi.mock('@core/stores/messageStore', () => ({
|
||||
useMessageStore: vi.fn(() => ({
|
||||
setDraft: mockSetDraft,
|
||||
getDraft: mockGetDraft,
|
||||
clearDraft: mockClearDraft,
|
||||
})),
|
||||
MessageState: {
|
||||
Ack: 'ack',
|
||||
Waiting: 'waiting',
|
||||
@@ -44,111 +46,177 @@ vi.mock('@core/stores/messageStore.ts', () => ({
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock('@core/utils/debounce.ts', () => ({
|
||||
debounce: vi.fn((fn) => fn),
|
||||
}));
|
||||
|
||||
vi.mock('lucide-react', () => ({
|
||||
SendIcon: vi.fn(() => <svg data-testid="send-icon" />),
|
||||
}));
|
||||
|
||||
describe('MessageInput', () => {
|
||||
const mockSetMessageState = vi.fn();
|
||||
const mockSetActiveChat = vi.fn();
|
||||
const mockSetDraft = vi.fn();
|
||||
const mockGetDraft = vi.fn();
|
||||
const mockClearDraft = vi.fn();
|
||||
const mockSendText = vi.fn();
|
||||
|
||||
beforeEach(() => {
|
||||
(useDevice as ReturnType<typeof vi.fn>).mockReturnValue({
|
||||
connection: {
|
||||
sendText: mockSendText,
|
||||
},
|
||||
});
|
||||
|
||||
(useMessageStore as unknown as ReturnType<typeof vi.fn>).mockReturnValue({
|
||||
setMessageState: mockSetMessageState,
|
||||
activeChat: 123,
|
||||
setDraft: mockSetDraft,
|
||||
getDraft: mockGetDraft,
|
||||
clearDraft: mockClearDraft,
|
||||
});
|
||||
|
||||
mockSetMessageState.mockClear();
|
||||
mockSetActiveChat.mockClear();
|
||||
mockSetDraft.mockClear();
|
||||
mockGetDraft.mockClear();
|
||||
mockClearDraft.mockClear();
|
||||
mockSendText.mockClear();
|
||||
(debounce as ReturnType<typeof vi.fn>).mockImplementation((fn) => fn);
|
||||
});
|
||||
|
||||
const renderComponent = (props: { to: Types.Destination; channel: Types.ChannelNumber; maxBytes: number }) => {
|
||||
render(<MessageInput {...props} />);
|
||||
const mockOnSend = vi.fn();
|
||||
const defaultProps: MessageInputProps = {
|
||||
onSend: mockOnSend,
|
||||
to: 123,
|
||||
maxBytes: 256,
|
||||
};
|
||||
|
||||
it.skip('sends text message and updates state to Ack on submit', async () => {
|
||||
renderComponent({ to: 2, channel: 3, maxBytes: 256 });
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
|
||||
mockGetDraft.mockReturnValue('');
|
||||
});
|
||||
|
||||
const renderComponent = (props: Partial<MessageInputProps> = {}) => {
|
||||
render(<MessageInput {...defaultProps} {...props} />);
|
||||
};
|
||||
|
||||
it('should render the input field, byte counter, and send button', () => {
|
||||
renderComponent();
|
||||
expect(screen.getByPlaceholderText('Enter Message')).toBeInTheDocument();
|
||||
expect(screen.getByTestId('byte-counter')).toBeInTheDocument();
|
||||
expect(screen.getByRole('button')).toBeInTheDocument();
|
||||
expect(screen.getByTestId('send-icon')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('should initialize with the draft from the store', () => {
|
||||
const initialDraft = 'Existing draft message';
|
||||
mockGetDraft.mockImplementation((key) => {
|
||||
return key === defaultProps.to ? initialDraft : '';
|
||||
});
|
||||
|
||||
renderComponent();
|
||||
|
||||
const inputElement = screen.getByPlaceholderText('Enter Message') as HTMLInputElement;
|
||||
fireEvent.change(inputElement, { target: { value: 'Hello' } });
|
||||
expect(inputElement.value).toBe(initialDraft);
|
||||
expect(mockGetDraft).toHaveBeenCalledWith(defaultProps.to);
|
||||
const expectedBytes = new Blob([initialDraft]).size;
|
||||
expect(screen.getByTestId('byte-counter')).toHaveTextContent(`${expectedBytes}/${defaultProps.maxBytes}`);
|
||||
});
|
||||
|
||||
it('should update input value, byte counter, and call setDraft on change within limits', () => {
|
||||
renderComponent();
|
||||
const inputElement = screen.getByPlaceholderText('Enter Message');
|
||||
const testMessage = 'Hello there!';
|
||||
const expectedBytes = new Blob([testMessage]).size;
|
||||
|
||||
fireEvent.change(inputElement, { target: { value: testMessage } });
|
||||
|
||||
expect((inputElement as HTMLInputElement).value).toBe(testMessage);
|
||||
expect(screen.getByTestId('byte-counter')).toHaveTextContent(`${expectedBytes}/${defaultProps.maxBytes}`);
|
||||
expect(mockSetDraft).toHaveBeenCalledTimes(1);
|
||||
expect(mockSetDraft).toHaveBeenCalledWith(defaultProps.to, testMessage);
|
||||
});
|
||||
|
||||
it('should NOT update input value or call setDraft if maxBytes is exceeded', () => {
|
||||
const smallMaxBytes = 5;
|
||||
renderComponent({ maxBytes: smallMaxBytes });
|
||||
const inputElement = screen.getByPlaceholderText('Enter Message');
|
||||
const initialValue = '12345';
|
||||
const excessiveValue = '123456';
|
||||
|
||||
fireEvent.change(inputElement, { target: { value: initialValue } });
|
||||
expect((inputElement as HTMLInputElement).value).toBe(initialValue);
|
||||
expect(mockSetDraft).toHaveBeenCalledWith(defaultProps.to, initialValue);
|
||||
mockSetDraft.mockClear();
|
||||
|
||||
fireEvent.change(inputElement, { target: { value: excessiveValue } });
|
||||
|
||||
expect((inputElement as HTMLInputElement).value).toBe(initialValue);
|
||||
expect(screen.getByTestId('byte-counter')).toHaveTextContent(`${smallMaxBytes}/${smallMaxBytes}`);
|
||||
expect(mockSetDraft).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('should call onSend, clear input, reset byte counter, and call clearDraft on valid submit', async () => {
|
||||
renderComponent();
|
||||
const inputElement = screen.getByPlaceholderText('Enter Message');
|
||||
const formElement = screen.getByRole('form');
|
||||
const testMessage = 'Send this message';
|
||||
|
||||
fireEvent.change(inputElement, { target: { value: testMessage } });
|
||||
fireEvent.submit(formElement);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(mockSendText).toHaveBeenCalledWith('Hello', 2, true, 3);
|
||||
expect(mockSetMessageState).toHaveBeenCalledWith({
|
||||
type: 'direct',
|
||||
key: 123,
|
||||
messageId: undefined,
|
||||
newState: 'ack',
|
||||
});
|
||||
expect(mockClearDraft).toHaveBeenCalledWith(2);
|
||||
expect(inputElement.value).toBe('');
|
||||
expect(screen.getByTestId('byte-counter')).toHaveTextContent('0/256');
|
||||
expect(mockOnSend).toHaveBeenCalledTimes(1);
|
||||
expect(mockOnSend).toHaveBeenCalledWith(testMessage);
|
||||
expect((inputElement as HTMLInputElement).value).toBe('');
|
||||
expect(screen.getByTestId('byte-counter')).toHaveTextContent(`0/${defaultProps.maxBytes}`);
|
||||
expect(mockClearDraft).toHaveBeenCalledTimes(1);
|
||||
expect(mockClearDraft).toHaveBeenCalledWith(defaultProps.to);
|
||||
});
|
||||
});
|
||||
|
||||
it.skip('sends broadcast message if to is "broadcast" and updates state to Ack', async () => {
|
||||
renderComponent({ to: 'broadcast', channel: 5, maxBytes: 256 });
|
||||
const inputElement = screen.getByPlaceholderText('Enter Message') as HTMLInputElement;
|
||||
fireEvent.change(inputElement, { target: { value: 'Broadcast message' } });
|
||||
it('should trim whitespace before calling onSend', async () => {
|
||||
renderComponent();
|
||||
const inputElement = screen.getByPlaceholderText('Enter Message');
|
||||
const formElement = screen.getByRole('form');
|
||||
const testMessageWithWhitespace = ' Trim me! ';
|
||||
const expectedTrimmedMessage = 'Trim me!';
|
||||
|
||||
fireEvent.change(inputElement, { target: { value: testMessageWithWhitespace } });
|
||||
fireEvent.submit(formElement);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(mockSendText).toHaveBeenCalledWith('Broadcast message', 'broadcast', true, 5);
|
||||
expect(mockSetMessageState).toHaveBeenCalledWith({
|
||||
type: 'broadcast',
|
||||
key: 123,
|
||||
messageId: undefined,
|
||||
newState: 'ack',
|
||||
});
|
||||
expect(mockClearDraft).toHaveBeenCalledWith('broadcast');
|
||||
expect(inputElement.value).toBe('');
|
||||
expect(screen.getByTestId('byte-counter')).toHaveTextContent('0/256');
|
||||
expect(mockOnSend).toHaveBeenCalledTimes(1);
|
||||
expect(mockOnSend).toHaveBeenCalledWith(expectedTrimmedMessage);
|
||||
expect(mockClearDraft).toHaveBeenCalledWith(defaultProps.to);
|
||||
});
|
||||
});
|
||||
|
||||
it('updates state to Failed if sendText throws an error', async () => {
|
||||
mockSendText.mockRejectedValue({ id: 456 });
|
||||
renderComponent({ to: 3, channel: 1, maxBytes: 256 });
|
||||
const inputElement = screen.getByPlaceholderText('Enter Message') as HTMLInputElement;
|
||||
fireEvent.change(inputElement, { target: { value: 'Error message' } });
|
||||
it('should not call onSend or clearDraft if input is empty on submit', async () => {
|
||||
renderComponent();
|
||||
const inputElement = screen.getByPlaceholderText('Enter Message');
|
||||
const formElement = screen.getByRole('form');
|
||||
|
||||
expect((inputElement as HTMLInputElement).value).toBe('');
|
||||
|
||||
fireEvent.submit(formElement);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(mockSendText).toHaveBeenCalledWith('Error message', 3, true, 1);
|
||||
expect(mockSetMessageState).toHaveBeenCalledWith({
|
||||
type: 'direct',
|
||||
key: 123,
|
||||
messageId: 456,
|
||||
newState: 'failed',
|
||||
});
|
||||
expect(mockClearDraft).toHaveBeenCalledWith(3);
|
||||
expect(inputElement.value).toBe('');
|
||||
expect(screen.getByTestId('byte-counter')).toHaveTextContent('0/256');
|
||||
await act(async () => {
|
||||
await new Promise(resolve => setTimeout(resolve, 50));
|
||||
});
|
||||
|
||||
expect(mockOnSend).not.toHaveBeenCalled();
|
||||
expect(mockClearDraft).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('should not call onSend or clearDraft if input contains only whitespace on submit', async () => {
|
||||
renderComponent();
|
||||
const inputElement = screen.getByTestId('message-input-field');
|
||||
const formElement = screen.getByRole('form');
|
||||
const whitespaceMessage = ' \t ';
|
||||
|
||||
fireEvent.change(inputElement, { target: { value: whitespaceMessage } });
|
||||
expect((inputElement as HTMLInputElement).value).toBe(whitespaceMessage);
|
||||
|
||||
fireEvent.submit(formElement);
|
||||
|
||||
await act(async () => {
|
||||
await new Promise(resolve => setTimeout(resolve, 50));
|
||||
});
|
||||
|
||||
expect(mockOnSend).not.toHaveBeenCalled();
|
||||
expect(mockClearDraft).not.toHaveBeenCalled();
|
||||
|
||||
expect((inputElement as HTMLInputElement).value).toBe(whitespaceMessage);
|
||||
});
|
||||
|
||||
it('should work with broadcast destination for drafts', () => {
|
||||
const broadcastDest: Types.Destination = 'broadcast';
|
||||
mockGetDraft.mockImplementation((key) => key === broadcastDest ? 'Broadcast draft' : '');
|
||||
|
||||
renderComponent({ to: broadcastDest });
|
||||
|
||||
expect(mockGetDraft).toHaveBeenCalledWith(broadcastDest);
|
||||
expect((screen.getByPlaceholderText('Enter Message') as HTMLInputElement).value).toBe('Broadcast draft');
|
||||
|
||||
const inputElement = screen.getByPlaceholderText('Enter Message');
|
||||
const formElement = screen.getByRole('form');
|
||||
const newMessage = 'New broadcast msg';
|
||||
|
||||
fireEvent.change(inputElement, { target: { value: newMessage } });
|
||||
expect(mockSetDraft).toHaveBeenCalledWith(broadcastDest, newMessage);
|
||||
|
||||
fireEvent.submit(formElement);
|
||||
|
||||
expect(mockOnSend).toHaveBeenCalledWith(newMessage);
|
||||
expect(mockClearDraft).toHaveBeenCalledWith(broadcastDest);
|
||||
});
|
||||
});
|
||||
@@ -1,54 +1,28 @@
|
||||
import { Button } from "@components/UI/Button.tsx";
|
||||
import { Input } from "@components/UI/Input.tsx";
|
||||
import { useDevice } from "@core/stores/deviceStore.ts";
|
||||
import type { Types } from "@meshtastic/core";
|
||||
import { SendIcon } from "lucide-react";
|
||||
import { startTransition, useCallback, useMemo, useState } from "react";
|
||||
import { MessageState, MessageType, useMessageStore } from "@core/stores/messageStore.ts";
|
||||
import { debounce } from "@core/utils/debounce.ts";
|
||||
import { startTransition, useState } from "react";
|
||||
import { useMessageStore } from "@core/stores/messageStore/index.ts";
|
||||
|
||||
export interface MessageInputProps {
|
||||
onSend: (message: string) => void;
|
||||
to: Types.Destination;
|
||||
channel: Types.ChannelNumber;
|
||||
maxBytes: number;
|
||||
}
|
||||
|
||||
export const MessageInput = ({
|
||||
onSend,
|
||||
to,
|
||||
channel,
|
||||
maxBytes,
|
||||
}: MessageInputProps) => {
|
||||
const { connection } = useDevice();
|
||||
const { setMessageState, activeChat, setDraft, getDraft, clearDraft } = useMessageStore();
|
||||
|
||||
const [localDraft, setLocalDraft] = useState(getDraft(to));
|
||||
const [messageBytes, setMessageBytes] = useState(0);
|
||||
|
||||
const debouncedSetMessageDraft = useMemo(
|
||||
() => debounce((value: string) => setDraft(to, value), 300),
|
||||
[setDraft, to]
|
||||
);
|
||||
const { setDraft, getDraft, clearDraft } = useMessageStore();
|
||||
|
||||
const calculateBytes = (text: string) => new Blob([text]).size;
|
||||
|
||||
const chatType = to === MessageType.Broadcast ? MessageType.Broadcast : MessageType.Direct;
|
||||
|
||||
const sendText = useCallback(async (message: string) => {
|
||||
try {
|
||||
const messageId = await connection?.sendText(message, to, true, channel);
|
||||
if (messageId !== undefined) {
|
||||
setMessageState({ type: chatType, key: activeChat, messageId, newState: MessageState.Ack });
|
||||
}
|
||||
// deno-lint-ignore no-explicit-any
|
||||
} catch (e: any) {
|
||||
setMessageState({
|
||||
type: chatType,
|
||||
key: activeChat,
|
||||
messageId: e?.id,
|
||||
newState: MessageState.Failed,
|
||||
});
|
||||
}
|
||||
}, [channel, connection, setMessageState, to, activeChat, chatType]);
|
||||
const initialDraft = getDraft(to);
|
||||
const [localDraft, setLocalDraft] = useState(initialDraft);
|
||||
const [messageBytes, setMessageBytes] = useState(() => calculateBytes(initialDraft));
|
||||
|
||||
const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
|
||||
const newValue = e.target.value;
|
||||
@@ -56,27 +30,28 @@ export const MessageInput = ({
|
||||
|
||||
if (byteLength <= maxBytes) {
|
||||
setLocalDraft(newValue);
|
||||
debouncedSetMessageDraft(newValue);
|
||||
setMessageBytes(byteLength);
|
||||
setDraft(to, newValue);
|
||||
}
|
||||
};
|
||||
|
||||
const handleSubmit = (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
if (!localDraft.trim()) return;
|
||||
// Reset bytes *before* sending (consider if onSend failure needs different handling)
|
||||
setMessageBytes(0);
|
||||
|
||||
startTransition(() => {
|
||||
sendText(localDraft.trim());
|
||||
onSend(localDraft.trim());
|
||||
setLocalDraft("");
|
||||
clearDraft(to);
|
||||
setMessageBytes(0);
|
||||
});
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="flex gap-2">
|
||||
<form className="w-full" action="#" name="messageInput" onSubmit={handleSubmit}>
|
||||
<div className="flex grow gap-2">
|
||||
<form className="w-full" name="messageInput" onSubmit={handleSubmit}>
|
||||
<div className="flex grow gap-1">
|
||||
<label className="w-full">
|
||||
<Input
|
||||
autoFocus
|
||||
@@ -88,13 +63,13 @@ export const MessageInput = ({
|
||||
/>
|
||||
</label>
|
||||
|
||||
<label data-testid="byte-counter" className="flex items-center w-24 p-2 place-content-end">
|
||||
<label data-testid="byte-counter" className="flex items-center w-20 p-1 text-sm place-content-end">
|
||||
{messageBytes}/{maxBytes}
|
||||
</label>
|
||||
|
||||
<Button
|
||||
type="submit"
|
||||
className="dark:bg-white dark:text-slate-900 dark:hover:bg-slate-400 dark:hover:text-white"
|
||||
variant="default"
|
||||
>
|
||||
<SendIcon size={16} />
|
||||
</Button>
|
||||
@@ -102,4 +77,4 @@ export const MessageInput = ({
|
||||
</form>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
};
|
||||
@@ -5,146 +5,138 @@ import {
|
||||
TooltipProvider,
|
||||
TooltipTrigger,
|
||||
} from "@components/UI/Tooltip.tsx";
|
||||
import { useDeviceStore } from "@core/stores/deviceStore.ts";
|
||||
import { useDevice } from "@core/stores/deviceStore.ts";
|
||||
import { cn } from "@core/utils/cn.ts";
|
||||
import { Avatar } from "@components/UI/Avatar.tsx";
|
||||
import { AlertCircle, CheckCircle2, CircleEllipsis } from "lucide-react";
|
||||
import type { LucideIcon } from "lucide-react";
|
||||
import { ReactNode, useMemo } from "react";
|
||||
import { Message, MessageState } from "@core/stores/messageStore.ts";
|
||||
import { Protobuf } from "@meshtastic/js";
|
||||
import { MessageActionsMenu } from "@components/PageComponents/Messages/MessageActionsMenu.tsx";
|
||||
import { MessageState, useMessageStore } from "@core/stores/messageStore/index.ts";
|
||||
import { Protobuf, Types } from "@meshtastic/js";
|
||||
import { Message } from "@core/stores/messageStore/types.ts";
|
||||
// import { MessageActionsMenu } from "@components/PageComponents/Messages/MessageActionsMenu.tsx"; // Uncomment if needed later
|
||||
|
||||
interface MessageProps {
|
||||
message: Message;
|
||||
// locale?: string; // locale
|
||||
}
|
||||
|
||||
interface MessageStatus {
|
||||
state: MessageState;
|
||||
interface MessageStatusInfo {
|
||||
displayText: string;
|
||||
icon: LucideIcon;
|
||||
ariaLabel: string;
|
||||
iconClassName?: string;
|
||||
}
|
||||
|
||||
const MESSAGE_STATUS: Record<MessageState, MessageStatus> = {
|
||||
[MessageState.Ack]: { state: MessageState.Ack, displayText: "Message delivered", icon: CheckCircle2, ariaLabel: "Message delivered" },
|
||||
[MessageState.Waiting]: { state: MessageState.Waiting, displayText: "Waiting for delivery", icon: CircleEllipsis, ariaLabel: "Sending message" },
|
||||
[MessageState.Failed]: { state: MessageState.Failed, displayText: "Delivery failed", icon: AlertCircle, ariaLabel: "Message delivery failed" },
|
||||
const MESSAGE_STATUS_MAP: Record<MessageState, MessageStatusInfo> = {
|
||||
[MessageState.Ack]: { displayText: "Message delivered", icon: CheckCircle2, ariaLabel: "Message delivered", iconClassName: "text-green-500" },
|
||||
[MessageState.Waiting]: { displayText: "Waiting for delivery", icon: CircleEllipsis, ariaLabel: "Sending message", iconClassName: "text-slate-400" },
|
||||
[MessageState.Failed]: { displayText: "Delivery failed", icon: AlertCircle, ariaLabel: "Message delivery failed", iconClassName: "text-red-500 dark:text-red-400" },
|
||||
};
|
||||
|
||||
const getMessageStatus = (state: MessageState): MessageStatus =>
|
||||
MESSAGE_STATUS[state] ?? { state: MessageState.Failed, displayText: "Unknown state", icon: AlertCircle, ariaLabel: "Message status unknown" };
|
||||
const UNKNOWN_STATUS: MessageStatusInfo = { displayText: "Unknown state", icon: AlertCircle, ariaLabel: "Message status unknown", iconClassName: "text-red-500 dark:text-red-400" };
|
||||
|
||||
const StatusTooltip = ({ status, children }: { status: MessageStatus; children: ReactNode }) => (
|
||||
const getMessageStatusInfo = (state: MessageState): MessageStatusInfo =>
|
||||
MESSAGE_STATUS_MAP[state] ?? UNKNOWN_STATUS;
|
||||
|
||||
const StatusTooltip = ({ statusInfo, children }: { statusInfo: MessageStatusInfo; children: ReactNode }) => (
|
||||
<TooltipProvider delayDuration={300}>
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>{children}</TooltipTrigger>
|
||||
<TooltipContent className="bg-gray-800 text-white px-2 py-1 rounded text-xs">
|
||||
{status.displayText}
|
||||
<TooltipArrow className="fill-gray-800" />
|
||||
<TooltipContent className="bg-slate-800 dark:bg-slate-600 text-white px-4 py-1 rounded text-xs">
|
||||
{statusInfo.displayText}
|
||||
<TooltipArrow className="fill-slate-800" />
|
||||
</TooltipContent>
|
||||
</Tooltip>
|
||||
</TooltipProvider>
|
||||
);
|
||||
|
||||
const StatusIcon = ({ status, className }: { status: MessageStatus; className?: string }) => {
|
||||
const Icon = status.icon;
|
||||
const iconClass = cn("w-3.5 h-3.5 shrink-0", className);
|
||||
return (
|
||||
<StatusTooltip status={status}>
|
||||
<span aria-label={status.ariaLabel} role="img">
|
||||
<Icon className={iconClass} aria-hidden="true" />
|
||||
</span>
|
||||
</StatusTooltip>
|
||||
);
|
||||
};
|
||||
interface MessageItemProps {
|
||||
message: Message;
|
||||
}
|
||||
|
||||
const TimeDisplay = ({ date, className }: { date: number; className?: string }) => {
|
||||
const _date = useMemo(() => new Date(date), [date]);
|
||||
const locale = 'en-US'; // TODO: Make dynamic
|
||||
const formattedTime = useMemo(() => _date.toLocaleTimeString(locale, { hour: 'numeric', minute: '2-digit', hour12: true }), [_date, locale]);
|
||||
const fullDate = useMemo(() => _date.toLocaleString(locale, { dateStyle: 'medium', timeStyle: 'short' }), [_date, locale]);
|
||||
export const MessageItem = ({ message }: MessageItemProps) => {
|
||||
const { getNode } = useDevice();
|
||||
const { getMyNodeNum } = useMessageStore()
|
||||
|
||||
return (
|
||||
<time dateTime={_date.toISOString()} className={cn("text-xs", className)}>
|
||||
<span aria-hidden="true">{formattedTime}</span>
|
||||
<span className="sr-only">{fullDate}</span>
|
||||
</time>
|
||||
);
|
||||
};
|
||||
const messageUser: Protobuf.Mesh.NodeInfo | null | undefined = useMemo(() => {
|
||||
return message.from != null ? getNode(message.from) : null;
|
||||
}, [getNode, message.from]);
|
||||
|
||||
export const MessageItem = ({ message }: MessageProps) => {
|
||||
const { getDevices } = useDeviceStore();
|
||||
|
||||
const messageUser: Protobuf.Mesh.NodeInfo | null = useMemo(() => {
|
||||
if (message?.from === null || message?.from === undefined) return null;
|
||||
const devices = getDevices();
|
||||
for (const device of devices) {
|
||||
if (device.nodes.has(message.from)) {
|
||||
return device.nodes.get(message.from) ?? null;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}, [getDevices, message.from]);
|
||||
|
||||
const { shortName, displayName } = useMemo(() => {
|
||||
const fallbackName = message.from
|
||||
const myNodeNum = useMemo(() => getMyNodeNum(), [getMyNodeNum]);
|
||||
const { displayName, shortName } = useMemo(() => {
|
||||
const userIdHex = message.from.toString(16).toUpperCase().padStart(2, '0');
|
||||
const last4 = userIdHex.slice(-4);
|
||||
const fallbackName = `Meshtastic ${last4}`
|
||||
const longName = messageUser?.user?.longName;
|
||||
const shortName = messageUser?.user?.shortName ?? fallbackName;
|
||||
const displayName = longName || fallbackName;
|
||||
return { shortName, displayName };
|
||||
const derivedShortName = messageUser?.user?.shortName || fallbackName;
|
||||
const derivedDisplayName = longName || derivedShortName;
|
||||
return { displayName: derivedDisplayName, shortName: derivedShortName };
|
||||
}, [messageUser, message.from]);
|
||||
|
||||
const messageStatus = getMessageStatus(message.state);
|
||||
const messageText = message?.message ?? "";
|
||||
const messageDate = message?.date;
|
||||
const isFailed = message.state === MessageState.Failed;
|
||||
const messageStatusInfo = getMessageStatusInfo(message.state);
|
||||
const StatusIconComponent = messageStatusInfo.icon;
|
||||
|
||||
const messageDate = useMemo(() => message.date ? new Date(message.date) : null, [message.date]);
|
||||
const locale = 'en-US'; // TODO: Make dynamic via props or context
|
||||
|
||||
const formattedTime = useMemo(() =>
|
||||
messageDate?.toLocaleTimeString(locale, { hour: 'numeric', minute: '2-digit', hour12: true }) ?? '',
|
||||
[messageDate, locale]);
|
||||
|
||||
const fullDateTime = useMemo(() =>
|
||||
messageDate?.toLocaleString(locale, { dateStyle: 'medium', timeStyle: 'short' }) ?? '',
|
||||
[messageDate, locale]);
|
||||
|
||||
const isSender = myNodeNum !== undefined && message.from === myNodeNum;
|
||||
const isOnPrimaryChannel = message.channel === Types.ChannelNumber.Primary; // Use the enum
|
||||
const shouldShowStatusIcon = isSender && isOnPrimaryChannel;
|
||||
|
||||
|
||||
const messageItemWrapperClass = cn(
|
||||
"group w-full px-4 py-2 relative list-none",
|
||||
"group w-full py-2 relative list-none",
|
||||
"rounded-md",
|
||||
"hover:bg-slate-300/15 dark:hover:bg-slate-600/20",
|
||||
"transition-colors duration-100 ease-in-out",
|
||||
);
|
||||
const dateTextStyle = "text-xs text-slate-500 dark:text-slate-400";
|
||||
|
||||
const avatarSizeClass = "size-11";
|
||||
const gridGapClass = "gap-x-4";
|
||||
|
||||
const baseTextStyle = "text-sm text-gray-800 dark:text-gray-200";
|
||||
const nameTextStyle = "font-medium text-gray-900 dark:text-gray-100 mr-2";
|
||||
const dateTextStyle = "text-gray-500 dark:text-gray-400";
|
||||
const statusIconBaseColor = "text-gray-400 dark:text-gray-500";
|
||||
const statusIconFailedColor = "text-red-500 dark:text-red-400";
|
||||
|
||||
return (
|
||||
<li className={messageItemWrapperClass}>
|
||||
<div className={cn("grid grid-cols-[auto_1fr]", gridGapClass)}>
|
||||
<Avatar size="sm" text={shortName} className={cn(avatarSizeClass, "pt-0.5")} />
|
||||
<div className="grid grid-cols-[auto_1fr] gap-x-2">
|
||||
<Avatar size="sm" text={shortName} className="pt-0.5" />
|
||||
|
||||
<div className="flex flex-col gap-1.5 min-w-0">
|
||||
{messageDate != null ? (
|
||||
<div className="flex items-center gap-1.5">
|
||||
<span className={nameTextStyle} aria-hidden="true">
|
||||
{displayName}
|
||||
</span>
|
||||
<TimeDisplay date={messageDate} className={dateTextStyle} />
|
||||
<StatusIcon
|
||||
status={messageStatus}
|
||||
className={cn(isFailed ? statusIconFailedColor : statusIconBaseColor)}
|
||||
/>
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
<div className={cn(baseTextStyle, "whitespace-pre-wrap")}>
|
||||
{messageText}
|
||||
<div className="flex flex-col gap-0.5 min-w-0">
|
||||
<div className="flex items-center gap-1.5">
|
||||
<span className="font-medium text-sm text-slate-900 dark:text-slate-100 truncate mr-1">
|
||||
{displayName}
|
||||
</span>
|
||||
{messageDate && (
|
||||
<time dateTime={messageDate.toISOString()} className={dateTextStyle}>
|
||||
<span aria-hidden="true">{formattedTime}</span>
|
||||
<span className="sr-only">{fullDateTime}</span>
|
||||
</time>
|
||||
)}
|
||||
{shouldShowStatusIcon && (
|
||||
<StatusTooltip statusInfo={messageStatusInfo}>
|
||||
<span aria-label={messageStatusInfo.ariaLabel} role="img">
|
||||
<StatusIconComponent
|
||||
className={cn("size-4 shrink-0", messageStatusInfo.iconClassName)}
|
||||
aria-hidden="true"
|
||||
/>
|
||||
</span>
|
||||
</StatusTooltip>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{message?.message && (
|
||||
<div className="text-sm text-slate-800 dark:text-slate-200 whitespace-pre-wrap break-words">
|
||||
{message.message}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
<MessageActionsMenu
|
||||
onReply={() => console.log("Reply to message:", message.messageId)}
|
||||
/>
|
||||
{/* Actions Menu Placeholder */}
|
||||
{/* <div className="absolute top-1 right-1">
|
||||
<MessageActionsMenu onReply={() => console.log("Reply")} />
|
||||
</div> */}
|
||||
</li>
|
||||
);
|
||||
};
|
||||
@@ -1,30 +1,33 @@
|
||||
import { describe, it, expect, vi, beforeEach, Mock } from "vitest";
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
import { render, screen } from "@testing-library/react";
|
||||
import { TraceRoute } from "@components/PageComponents/Messages/TraceRoute.tsx";
|
||||
import { useDevice } from "@core/stores/deviceStore.ts";
|
||||
import type { Protobuf } from "@meshtastic/core";
|
||||
|
||||
vi.mock("@core/stores/deviceStore");
|
||||
|
||||
describe("TraceRoute", () => {
|
||||
const mockNodes = new Map([
|
||||
const mockNodes = new Map<number, Protobuf.Mesh.NodeInfo>([
|
||||
[
|
||||
1,
|
||||
{ num: 1, user: { longName: "Node A" } },
|
||||
{ num: 1, user: { longName: "Node A" } } as Protobuf.Mesh.NodeInfo,
|
||||
],
|
||||
[
|
||||
2,
|
||||
{ num: 2, user: { longName: "Node B" } },
|
||||
{ num: 2, user: { longName: "Node B" } } as Protobuf.Mesh.NodeInfo,
|
||||
],
|
||||
[
|
||||
3,
|
||||
{ num: 3, user: { longName: "Node C" } },
|
||||
{ num: 3, user: { longName: "Node C" } } as Protobuf.Mesh.NodeInfo,
|
||||
],
|
||||
]);
|
||||
|
||||
beforeEach(() => {
|
||||
vi.resetAllMocks();
|
||||
(useDevice as Mock).mockReturnValue({
|
||||
nodes: mockNodes,
|
||||
vi.mocked(useDevice).mockReturnValue({
|
||||
getNode: (nodeNum: number): Protobuf.Mesh.NodeInfo | undefined => {
|
||||
return mockNodes.get(nodeNum);
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
@@ -38,17 +41,16 @@ describe("TraceRoute", () => {
|
||||
/>
|
||||
);
|
||||
|
||||
expect(screen.getByText("Route to destination:")).toBeInTheDocument();
|
||||
expect(screen.getAllByText("Source Node")).toHaveLength(1);
|
||||
expect(screen.getByText("Destination Node")).toBeInTheDocument();
|
||||
|
||||
expect(screen.getByText("Node A")).toBeInTheDocument();
|
||||
expect(screen.getByText("Node B")).toBeInTheDocument();
|
||||
|
||||
expect(screen.getAllByText(/↓/)).toHaveLength(3); // startNode + 2 hops
|
||||
expect(screen.getAllByText(/↓/)).toHaveLength(3);
|
||||
expect(screen.getByText("↓ 10dB")).toBeInTheDocument();
|
||||
expect(screen.getByText("↓ 20dB")).toBeInTheDocument();
|
||||
expect(screen.getByText("↓ 30dB")).toBeInTheDocument();
|
||||
expect(screen.getByText("Source Node")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("renders the route back when provided", () => {
|
||||
@@ -64,9 +66,20 @@ describe("TraceRoute", () => {
|
||||
);
|
||||
|
||||
expect(screen.getByText("Route back:")).toBeInTheDocument();
|
||||
|
||||
expect(screen.getAllByText("Source Node")).toHaveLength(2);
|
||||
|
||||
expect(screen.getAllByText("Destination Node")).toHaveLength(2);
|
||||
|
||||
expect(screen.getByText("Node C")).toBeInTheDocument();
|
||||
expect(screen.getByText("Node A")).toBeInTheDocument();
|
||||
|
||||
expect(screen.getByText("↓ 35dB")).toBeInTheDocument();
|
||||
expect(screen.getByText("↓ 45dB")).toBeInTheDocument();
|
||||
|
||||
expect(screen.getByText("↓ 15dB")).toBeInTheDocument();
|
||||
expect(screen.getByText("↓ 25dB")).toBeInTheDocument();
|
||||
|
||||
});
|
||||
|
||||
it("renders '??' for missing SNR values", () => {
|
||||
@@ -78,18 +91,22 @@ describe("TraceRoute", () => {
|
||||
/>
|
||||
);
|
||||
|
||||
expect(screen.getAllByText("↓ ??dB").length).toBeGreaterThan(0);
|
||||
expect(screen.getByText("Node A")).toBeInTheDocument();
|
||||
expect(screen.getAllByText("↓ ??dB")).toHaveLength(2);
|
||||
});
|
||||
|
||||
it("renders hop hex if node is not found", () => {
|
||||
render(
|
||||
<TraceRoute
|
||||
from={{ user: { longName: "Source" } } as any}
|
||||
to={{ user: { longName: "Dest" } } as any}
|
||||
from={{ user: { longName: "Source" } } as unknown}
|
||||
to={{ user: { longName: "Dest" } } as unknown}
|
||||
route={[99]}
|
||||
snrTowards={[5, 15]}
|
||||
/>
|
||||
);
|
||||
|
||||
expect(screen.getByText(/^!63$/)).toBeInTheDocument(); // 99 in hex
|
||||
expect(screen.getByText(/^!63$/)).toBeInTheDocument();
|
||||
expect(screen.getByText("↓ 5dB")).toBeInTheDocument();
|
||||
expect(screen.getByText("↓ 15dB")).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -20,16 +20,16 @@ interface RoutePathProps {
|
||||
}
|
||||
|
||||
const RoutePath = ({ title, startNode, endNode, path, snr }: RoutePathProps) => {
|
||||
const { nodes } = useDevice();
|
||||
const { getNode } = useDevice();
|
||||
|
||||
return (
|
||||
<span className="ml-4 border-l-2 border-l-background-primary pl-2 text-slate-900 dark:text-slate-900">
|
||||
<span id={title} className="ml-4 border-l-2 border-l-background-primary pl-2 text-slate-900 dark:text-slate-900">
|
||||
<p className="font-semibold">{title}</p>
|
||||
<p>{startNode?.user?.longName}</p>
|
||||
<p>↓ {snr?.[0] ?? "??"}dB</p>
|
||||
{path.map((hop, i) => (
|
||||
<span key={nodes.get(hop)?.num ?? hop}>
|
||||
<p>{nodes.get(hop)?.user?.longName ?? `!${numberToHexUnpadded(hop)}`}</p>
|
||||
<span key={getNode(hop)?.num ?? hop}>
|
||||
<p>{getNode(hop)?.user?.longName ?? `!${numberToHexUnpadded(hop)}`}</p>
|
||||
<p>↓ {snr?.[i + 1] ?? "??"}dB</p>
|
||||
</span>
|
||||
))}
|
||||
|
||||
@@ -1,77 +1,126 @@
|
||||
import React from 'react';
|
||||
import { cn } from "@core/utils/cn.ts";
|
||||
import { AlignLeftIcon, type LucideIcon } from "lucide-react";
|
||||
import { type LucideIcon } from "lucide-react";
|
||||
import Footer from "@components/UI/Footer.tsx";
|
||||
import { Spinner } from "@components/UI/Spinner.tsx";
|
||||
import { ErrorBoundary } from "react-error-boundary";
|
||||
import { ErrorPage } from "@components/UI/ErrorPage.tsx";
|
||||
|
||||
export interface ActionItem {
|
||||
key: string;
|
||||
icon: LucideIcon;
|
||||
iconClasses?: string;
|
||||
onClick: () => void;
|
||||
disabled?: boolean;
|
||||
isLoading?: boolean;
|
||||
ariaLabel?: string;
|
||||
}
|
||||
|
||||
export interface PageLayoutProps {
|
||||
label: string;
|
||||
noPadding?: boolean;
|
||||
actions?: ActionItem[];
|
||||
children: React.ReactNode;
|
||||
className?: string;
|
||||
actions?: {
|
||||
icon: LucideIcon;
|
||||
iconClasses?: string;
|
||||
onClick: () => void;
|
||||
disabled?: boolean;
|
||||
isLoading?: boolean;
|
||||
}[];
|
||||
leftBar?: React.ReactNode;
|
||||
rightBar?: React.ReactNode;
|
||||
noPadding?: boolean;
|
||||
leftBarClassName?: string;
|
||||
rightBarClassName?: string;
|
||||
topBarClassName?: string;
|
||||
contentClassName?: string;
|
||||
}
|
||||
|
||||
export const PageLayout = ({
|
||||
label,
|
||||
noPadding,
|
||||
actions,
|
||||
className,
|
||||
children,
|
||||
leftBar,
|
||||
rightBar,
|
||||
noPadding,
|
||||
leftBarClassName,
|
||||
rightBarClassName,
|
||||
topBarClassName,
|
||||
contentClassName
|
||||
}: PageLayoutProps) => {
|
||||
return (
|
||||
<ErrorBoundary FallbackComponent={ErrorPage}>
|
||||
<div className="relative flex h-full w-full flex-col">
|
||||
<div className="flex h-14 shrink-0 border-b-[0.5px] border-slate-300 dark:border-slate-700 md:h-16 md:px-4">
|
||||
<button
|
||||
type="button"
|
||||
className="pl-4 transition-all hover:text-accent md:hidden"
|
||||
<div className="flex flex-1 bg-background text-foreground overflow-hidden">
|
||||
{/* Left Sidebar */}
|
||||
{leftBar && (
|
||||
<aside
|
||||
className={cn(
|
||||
"px-2 pr-0 shrink-0 border-r-[0.5px] border-slate-300 dark:border-slate-700 ",
|
||||
leftBarClassName
|
||||
)}
|
||||
>
|
||||
<AlignLeftIcon />
|
||||
</button>
|
||||
<div className="flex flex-1 items-center justify-between px-4 md:px-0">
|
||||
<div className="flex w-full items-center">
|
||||
<span className="w-full text-lg font-medium">{label}</span>
|
||||
<div className="flex justify-end space-x-4">
|
||||
{leftBar}
|
||||
</aside>
|
||||
)}
|
||||
|
||||
<div className="flex flex-1 flex-col min-w-0">
|
||||
{/* Header */}
|
||||
<header
|
||||
className={cn(
|
||||
"flex h-14 shrink-0 mt-2 p-2 items-center border-b border-slate-300 dark:border-slate-700",
|
||||
topBarClassName
|
||||
)}
|
||||
>
|
||||
{/* Header Content */}
|
||||
<div className="flex flex-1 items-center justify-between min-w-0">
|
||||
<span className="text-lg font-medium text-foreground truncate px-2">
|
||||
{label}
|
||||
</span>
|
||||
<div className="flex items-center space-x-3 md:space-x-4 shrink-0">
|
||||
{actions?.map((action) => (
|
||||
<button
|
||||
key={action.icon.displayName}
|
||||
key={action.key}
|
||||
type="button"
|
||||
disabled={action?.disabled}
|
||||
className="transition-all hover:text-accent"
|
||||
disabled={action.disabled || action.isLoading}
|
||||
className="text-foreground transition-colors hover:text-accent disabled:opacity-50 disabled:cursor-not-allowed"
|
||||
onClick={action.onClick}
|
||||
aria-label={action.ariaLabel || `Action ${action.key}`}
|
||||
aria-disabled={action.disabled}
|
||||
aria-busy={action.isLoading}
|
||||
>
|
||||
{action?.isLoading ? <Spinner /> : (
|
||||
<action.icon
|
||||
className={action.iconClasses}
|
||||
aria-disabled={action.disabled}
|
||||
/>
|
||||
)}
|
||||
<div className="mr-6">
|
||||
{action.isLoading ? (
|
||||
<Spinner size="md" />
|
||||
) : (
|
||||
<action.icon
|
||||
className={cn("h-5 w-5", action.iconClasses)}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div
|
||||
className={cn(
|
||||
"flex h-full w-full flex-col overflow-y-auto",
|
||||
!noPadding && "pl-3 pr-3 ",
|
||||
className
|
||||
)}
|
||||
>
|
||||
{children}
|
||||
</header>
|
||||
|
||||
<main
|
||||
className={cn(
|
||||
"flex-1 flex flex-col",
|
||||
"overflow-hidden",
|
||||
!noPadding && "px-2",
|
||||
contentClassName
|
||||
)}
|
||||
>
|
||||
{children}
|
||||
</main>
|
||||
<Footer />
|
||||
</div>
|
||||
|
||||
{/* Right Sidebar */}
|
||||
{rightBar && (
|
||||
<aside
|
||||
className={cn(
|
||||
"w-48 lg:w-[270px] shrink-0 border-l border-slate-300 dark:border-slate-700 px-2 overflow-hidden",
|
||||
rightBarClassName
|
||||
)}
|
||||
>
|
||||
{rightBar}
|
||||
</aside>
|
||||
)}
|
||||
</div>
|
||||
</ErrorBoundary>
|
||||
);
|
||||
};
|
||||
};
|
||||
+196
-103
@@ -1,148 +1,241 @@
|
||||
import React from "react";
|
||||
import { SidebarSection } from "@components/UI/Sidebar/SidebarSection.tsx";
|
||||
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 { Avatar } from "@components/UI/Avatar.tsx";
|
||||
|
||||
import {
|
||||
BatteryMediumIcon,
|
||||
CircleChevronLeft,
|
||||
CpuIcon,
|
||||
EditIcon,
|
||||
LayersIcon,
|
||||
type LucideIcon,
|
||||
MapIcon,
|
||||
MessageSquareIcon,
|
||||
PenLine,
|
||||
SearchIcon,
|
||||
SettingsIcon,
|
||||
SidebarCloseIcon,
|
||||
SidebarOpenIcon,
|
||||
UsersIcon,
|
||||
ZapIcon,
|
||||
} from "lucide-react";
|
||||
import { useState } from "react";
|
||||
import { cn } from "@core/utils/cn.ts";
|
||||
import { useSidebar } from "@core/stores/sidebarStore.tsx";
|
||||
import ThemeSwitcher from "@components/ThemeSwitcher.tsx";
|
||||
import { useAppStore } from "@core/stores/appStore.ts";
|
||||
import BatteryStatus from "@components/BatteryStatus.tsx";
|
||||
import { SidebarButton } from "@components/UI/Sidebar/SidebarButton.tsx";
|
||||
|
||||
export interface SidebarProps {
|
||||
children?: React.ReactNode;
|
||||
}
|
||||
|
||||
export const Sidebar = ({ children }: SidebarProps) => {
|
||||
const { hardware, nodes, metadata } = useDevice();
|
||||
const myNode = nodes.get(hardware.myNodeNum);
|
||||
const myMetadata = metadata.get(0);
|
||||
const { activePage, setActivePage, setDialogOpen } = useDevice();
|
||||
const [showSidebar, setShowSidebar] = useState<boolean>(true);
|
||||
interface NavLink {
|
||||
name: string;
|
||||
icon: LucideIcon;
|
||||
page: Page;
|
||||
}
|
||||
|
||||
interface NavLink {
|
||||
name: string;
|
||||
icon: LucideIcon;
|
||||
page: Page;
|
||||
}
|
||||
const CollapseToggleButton = () => {
|
||||
const { isCollapsed, toggleSidebar } = useSidebar();
|
||||
const buttonLabel = isCollapsed ? "Open sidebar" : "Close sidebar";
|
||||
|
||||
return (
|
||||
<button
|
||||
type="button"
|
||||
aria-label={buttonLabel}
|
||||
onClick={toggleSidebar}
|
||||
className={cn(
|
||||
'absolute top-20 right-0 z-10 p-0.5 rounded-full transform translate-x-1/2',
|
||||
'transition-colors duration-300 ease-in-out',
|
||||
'border border-slate-300 dark:border-slate-200',
|
||||
'text-slate-500 dark:text-slate-200 hover:text-slate-400 dark:hover:text-slate-400',
|
||||
'focus:outline-none focus:ring-2 focus:ring-accent transition-transform'
|
||||
)}
|
||||
>
|
||||
<CircleChevronLeft
|
||||
size={24}
|
||||
className={cn(
|
||||
'transition-transform duration-300 ease-in-out',
|
||||
isCollapsed && 'rotate-180'
|
||||
)}
|
||||
/>
|
||||
</button>
|
||||
);
|
||||
}
|
||||
|
||||
export const Sidebar = ({ children }: SidebarProps) => {
|
||||
const { hardware, getNode, getNodesLength, metadata, activePage, setActivePage, setDialogOpen } = useDevice();
|
||||
const { setCommandPaletteOpen } = useAppStore();
|
||||
const myNode = getNode(hardware.myNodeNum);
|
||||
const { isCollapsed } = useSidebar();
|
||||
const myMetadata = metadata.get(0);
|
||||
|
||||
const pages: NavLink[] = [
|
||||
{ name: "Messages", icon: MessageSquareIcon, page: "messages" },
|
||||
{ name: "Map", icon: MapIcon, page: "map" },
|
||||
{ name: "Config", icon: SettingsIcon, page: "config" },
|
||||
{ name: "Channels", icon: LayersIcon, page: "channels" },
|
||||
{
|
||||
name: "Messages",
|
||||
icon: MessageSquareIcon,
|
||||
page: "messages",
|
||||
},
|
||||
{
|
||||
name: "Map",
|
||||
icon: MapIcon,
|
||||
page: "map",
|
||||
},
|
||||
{
|
||||
name: "Config",
|
||||
icon: SettingsIcon,
|
||||
page: "config",
|
||||
},
|
||||
{
|
||||
name: "Channels",
|
||||
icon: LayersIcon,
|
||||
page: "channels",
|
||||
},
|
||||
{
|
||||
name: `Nodes (${Math.max(nodes.size - 1, 0)})`,
|
||||
name: `Nodes (${Math.max(getNodesLength() - 1, 0)})`,
|
||||
icon: UsersIcon,
|
||||
page: "nodes",
|
||||
},
|
||||
];
|
||||
|
||||
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">
|
||||
return (
|
||||
<div
|
||||
className={cn(
|
||||
'relative border-slate-300 dark:border-slate-700',
|
||||
'transition-all duration-300 ease-in-out flex-shrink-0',
|
||||
isCollapsed ? 'w-24' : 'w-46 lg:w-64'
|
||||
)}
|
||||
>
|
||||
<CollapseToggleButton />
|
||||
|
||||
<div
|
||||
className={cn(
|
||||
'h-14 flex mt-2 gap-2 items-center flex-shrink-0 transition-all duration-300 ease-in-out',
|
||||
'border-b-[0.5px] border-slate-300 dark:border-slate-700',
|
||||
isCollapsed && 'justify-center px-0'
|
||||
|
||||
)}
|
||||
>
|
||||
<img
|
||||
src="Logo.svg"
|
||||
alt="Meshtastic Logo"
|
||||
className="size-10 flex-shrink-0 rounded-xl"
|
||||
/>
|
||||
<h2
|
||||
className={cn(
|
||||
'text-xl font-semibold text-gray-800 dark:text-gray-100 whitespace-nowrap',
|
||||
'transition-all duration-300 ease-in-out',
|
||||
isCollapsed
|
||||
? 'opacity-0 max-w-0 invisible ml-0'
|
||||
: 'opacity-100 max-w-xs visible ml-2'
|
||||
)}
|
||||
>
|
||||
Meshtastic
|
||||
</h2>
|
||||
</div>
|
||||
|
||||
<SidebarSection label="Navigation" className="mt-4 px-0">
|
||||
{pages.map((link) => (
|
||||
<SidebarButton
|
||||
key={link.name}
|
||||
label={link.name}
|
||||
Icon={link.icon}
|
||||
onClick={() => {
|
||||
if (myNode !== undefined) {
|
||||
setActivePage(link.page);
|
||||
}
|
||||
}}
|
||||
active={link.page === activePage}
|
||||
disabled={myNode === undefined}
|
||||
/>
|
||||
))}
|
||||
</SidebarSection>
|
||||
|
||||
<div className={cn(
|
||||
'flex-1 min-h-0',
|
||||
isCollapsed && 'overflow-hidden'
|
||||
)}
|
||||
>
|
||||
{children}
|
||||
</div>
|
||||
|
||||
<div className="pt-4 border-t-[0.5px] bg-background-primary border-slate-300 dark:border-slate-700 flex-shrink-0">
|
||||
{myNode === undefined ? (
|
||||
<div className="flex flex-col items-center justify-center px-8 py-6">
|
||||
<div className="flex flex-col items-center justify-center py-6">
|
||||
<Spinner />
|
||||
<Subtle className="mt-2">Loading device info...</Subtle>
|
||||
<Subtle
|
||||
className={cn(
|
||||
'mt-4 transition-opacity duration-300',
|
||||
isCollapsed ? 'opacity-0 invisible' : 'opacity-100 visible'
|
||||
)}
|
||||
>
|
||||
Loading...
|
||||
</Subtle>
|
||||
</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)}
|
||||
<div
|
||||
className={cn(
|
||||
'flex place-items-center gap-2',
|
||||
isCollapsed && 'justify-center'
|
||||
)}
|
||||
>
|
||||
<Avatar
|
||||
text={myNode.user?.shortName ?? myNode.num.toString()}
|
||||
className={cn("flex-shrink-0 ml-2",
|
||||
isCollapsed && "ml-0",
|
||||
)}
|
||||
size="sm"
|
||||
/>
|
||||
<p
|
||||
className={cn(
|
||||
'max-w-[20ch] text-wrap text-sm font-medium',
|
||||
'transition-all duration-300 ease-in-out overflow-hidden',
|
||||
isCollapsed
|
||||
? 'opacity-0 max-w-0 invisible'
|
||||
: 'opacity-100 max-w-full visible'
|
||||
)}
|
||||
>
|
||||
<EditIcon size={16} />
|
||||
</button>
|
||||
<button type="button" onClick={() => setShowSidebar(false)}>
|
||||
<SidebarCloseIcon size={24} />
|
||||
</button>
|
||||
{myNode.user?.longName}
|
||||
</p>
|
||||
</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
|
||||
className={cn(
|
||||
'flex flex-col gap-0.5 ml-2 mt-2',
|
||||
'transition-all duration-300 ease-in-out',
|
||||
isCollapsed
|
||||
? 'opacity-0 max-w-0 h-0 invisible'
|
||||
: 'opacity-100 max-w-xs h-auto visible'
|
||||
)}
|
||||
>
|
||||
<div className="inline-flex gap-2">
|
||||
<BatteryStatus deviceMetrics={myNode.deviceMetrics} />
|
||||
</div>
|
||||
<div className="flex items-center">
|
||||
<ZapIcon size={24} viewBox="0 0 36 24" />
|
||||
<Subtle>
|
||||
{myNode.deviceMetrics?.voltage?.toPrecision(3) ?? "UNK"} volts
|
||||
</Subtle>
|
||||
<div className="inline-flex gap-2">
|
||||
<ZapIcon size={18} className="text-gray-500 dark:text-gray-400 w-4 flex-shrink-0" />
|
||||
<Subtle>{myNode.deviceMetrics?.voltage?.toPrecision(3) ?? "UNK"} volts</Subtle>
|
||||
</div>
|
||||
<div className="flex items-center">
|
||||
<CpuIcon size={24} viewBox="0 0 36 24" />
|
||||
<div className="inline-flex gap-2">
|
||||
<CpuIcon size={18} className="text-gray-500 dark:text-gray-400 w-4 flex-shrink-0" />
|
||||
<Subtle>v{myMetadata?.firmwareVersion ?? "UNK"}</Subtle>
|
||||
</div>
|
||||
</div>
|
||||
<div
|
||||
className={cn(
|
||||
'flex items-center flex-shrink-0 ml-2',
|
||||
'transition-all duration-300 ease-in-out',
|
||||
isCollapsed
|
||||
? 'opacity-0 max-w-0 invisible pointer-events-none'
|
||||
: 'opacity-100 max-w-xs visible'
|
||||
)}
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
aria-label="Edit device name"
|
||||
className="p-1 rounded transition-colors hover:text-accent"
|
||||
onClick={() => setDialogOpen("deviceName", true)}
|
||||
>
|
||||
<PenLine size={22} />
|
||||
</button>
|
||||
<ThemeSwitcher />
|
||||
<button
|
||||
type="button"
|
||||
className="transition-all hover:text-accent"
|
||||
onClick={() => setCommandPaletteOpen(true)}
|
||||
>
|
||||
<SearchIcon />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
</>
|
||||
)}
|
||||
|
||||
<SidebarSection label="Navigation">
|
||||
{pages.map((link) => (
|
||||
<SidebarButton
|
||||
key={link.name}
|
||||
label={link.name}
|
||||
Icon={link.icon}
|
||||
onClick={() => {
|
||||
if (myNode !== undefined) {
|
||||
setActivePage(link.page);
|
||||
}
|
||||
}}
|
||||
active={link.page === activePage}
|
||||
disabled={myNode === undefined}
|
||||
/>
|
||||
))}
|
||||
</SidebarSection>
|
||||
{children}
|
||||
</div>
|
||||
)
|
||||
: (
|
||||
<div className="px-1 pt-8 border-r-[0.5px] border-slate-700">
|
||||
<button type="button" onClick={() => setShowSidebar(true)}>
|
||||
<SidebarOpenIcon size={24} />
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
</div>
|
||||
);
|
||||
};
|
||||
@@ -12,9 +12,9 @@ export default function ThemeSwitcher({
|
||||
const { theme, preference, setPreference } = useTheme();
|
||||
|
||||
const themeIcons = {
|
||||
light: <Sun className="size-5" />,
|
||||
dark: <Moon className="size-5" />,
|
||||
system: <Monitor className="size-5" />,
|
||||
light: <Sun className="size-6" />,
|
||||
dark: <Moon className="size-6" />,
|
||||
system: <Monitor className="size-6" />,
|
||||
};
|
||||
|
||||
const toggleTheme = () => {
|
||||
@@ -30,15 +30,15 @@ export default function ThemeSwitcher({
|
||||
<button
|
||||
type="button"
|
||||
className={cn(
|
||||
"transition-all duration-300 scale-100 cursor-pointer m-6 p-2 focus:*:data-label:opacity-100",
|
||||
"transition-all duration-300 scale-100 cursor-pointer m-3 p-2 focus:*:data-label:opacity-100",
|
||||
className,
|
||||
)}
|
||||
onClick={toggleTheme}
|
||||
aria-description={"Change current theme"}
|
||||
aria-description="Change current theme"
|
||||
>
|
||||
<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"
|
||||
className="transition-all block absolute w-full mb-auto mt-auto ml-0 mr-0 text-xs left-0 -top-3 opacity-0 rounded-lg"
|
||||
>
|
||||
{firstCharOfPreference.toLocaleUpperCase() +
|
||||
(restOfPreference ?? []).join("")}
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
import { cn } from "@core/utils/cn.ts";
|
||||
import { LockKeyholeOpenIcon } from 'lucide-react';
|
||||
import type React from "react";
|
||||
|
||||
type RGBColor = {
|
||||
r: number;
|
||||
@@ -16,7 +15,6 @@ interface AvatarProps {
|
||||
showError?: boolean;
|
||||
}
|
||||
|
||||
// biome-ignore lint/complexity/noStaticOnlyClass: stop being annoying Biome
|
||||
class ColorUtils {
|
||||
static hexToRgb(hex: number): RGBColor {
|
||||
return {
|
||||
@@ -42,47 +40,46 @@ class ColorUtils {
|
||||
}
|
||||
}
|
||||
|
||||
export const Avatar: React.FC<AvatarProps> = ({
|
||||
const getColorFromText = (text: string): RGBColor => {
|
||||
if (!text) {
|
||||
return { r: 0, g: 0, b: 0, a: 255 };
|
||||
}
|
||||
let hash = 0;
|
||||
for (let i = 0; i < text?.length; i++) {
|
||||
hash = text.charCodeAt(i) + ((hash << 5) - hash);
|
||||
hash |= 0;
|
||||
}
|
||||
|
||||
return {
|
||||
r: (hash & 0xff0000) >> 16,
|
||||
g: (hash & 0x00ff00) >> 8,
|
||||
b: hash & 0x0000ff,
|
||||
a: 255,
|
||||
};
|
||||
};
|
||||
|
||||
export const Avatar = ({
|
||||
text,
|
||||
size = "sm",
|
||||
showError = false,
|
||||
className,
|
||||
}) => {
|
||||
}: AvatarProps) => {
|
||||
const sizes = {
|
||||
sm: "size-11 text-xs",
|
||||
sm: "size-10 text-xs font-light",
|
||||
lg: "size-16 text-lg",
|
||||
};
|
||||
|
||||
// Pick a color based on the text provided to function
|
||||
const getColorFromText = (text: string): RGBColor => {
|
||||
let hash = 0;
|
||||
for (let i = 0; i < text.length; i++) {
|
||||
hash = text.charCodeAt(i) + ((hash << 5) - hash);
|
||||
}
|
||||
|
||||
return {
|
||||
r: (hash & 0xff0000) >> 16,
|
||||
g: (hash & 0x00ff00) >> 8,
|
||||
b: hash & 0x0000ff,
|
||||
a: 255,
|
||||
};
|
||||
};
|
||||
|
||||
const safeText = text?.toString().toUpperCase() ?? "UNK";
|
||||
const safeText = text?.toString().toUpperCase();
|
||||
const bgColor = getColorFromText(safeText);
|
||||
const isLight = ColorUtils.isLight(bgColor);
|
||||
const textColor = isLight ? "#000000" : "#FFFFFF";
|
||||
const initials = safeText.slice(0, 4) ?? "UNK";
|
||||
const initials = safeText?.slice(0, 4) ?? "UNK";
|
||||
|
||||
return (
|
||||
<div
|
||||
className={cn(
|
||||
`flex
|
||||
relative
|
||||
rounded-full
|
||||
items-center
|
||||
justify-center
|
||||
font-semibold`,
|
||||
`relative flex items-center justify-center rounded-full font-semibold
|
||||
`,
|
||||
sizes[size],
|
||||
className,
|
||||
)}
|
||||
@@ -91,8 +88,17 @@ export const Avatar: React.FC<AvatarProps> = ({
|
||||
color: textColor,
|
||||
}}
|
||||
>
|
||||
{showError ? <LockKeyholeOpenIcon className="size-4 absolute bottom-0 right-0 z-10 text-red-500 stroke-3" /> : null}
|
||||
<p className="p-1">{initials}</p>
|
||||
{showError ? (
|
||||
<LockKeyholeOpenIcon
|
||||
className="absolute bottom-0 right-0 z-10 size-4 text-red-500 stroke-3"
|
||||
aria-hidden="true"
|
||||
/>
|
||||
) : null}
|
||||
<p
|
||||
className="p-1"
|
||||
>
|
||||
{initials}
|
||||
</p>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
};
|
||||
@@ -8,13 +8,13 @@ const buttonVariants = cva(
|
||||
variants: {
|
||||
variant: {
|
||||
default:
|
||||
"bg-slate-900 text-white dark:bg-slate-900 hover:dark:bg-slate-700 dark:text-slate-100 hover:bg-slate-800 ",
|
||||
"bg-slate-900 text-white dark:bg-slate-50 hover:dark:bg-slate-200 dark:text-slate-900 hover:bg-slate-500",
|
||||
destructive:
|
||||
"bg-red-500 text-white hover:bg-red-600 dark:hover:bg-red-600",
|
||||
success:
|
||||
"bg-green-500 text-white hover:bg-green-600 dark:hover:bg-green-600",
|
||||
outline:
|
||||
"bg-transparent border border-slate-400 hover:bg-slate-100 dark:border-slate-400 dark:text-slate-500",
|
||||
"bg-transparent border border-slate-400 hover:text-slate-400 dark:hover:text-slate-300 dark:border-slate-400 dark:text-slate-100 ",
|
||||
subtle:
|
||||
"bg-slate-100 text-slate-700 hover:bg-slate-200 dark:bg-slate-500 dark:text-white dark:hover:bg-slate-400",
|
||||
ghost:
|
||||
|
||||
@@ -71,7 +71,7 @@ export function Checkbox({
|
||||
>
|
||||
{isChecked && (
|
||||
<div className="animate-fade-in scale-100 opacity-100">
|
||||
<Check className="w-4 h-4 text-slate-900 dark:text-slate-900" />
|
||||
<Check className="w-4 h-4 text-slate-900 dark:text-slate-200" />
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
@@ -88,7 +88,7 @@ const CommandGroup = React.forwardRef<
|
||||
<CommandPrimitive.Group
|
||||
ref={ref}
|
||||
className={cn(
|
||||
"overflow-hidden py-3 px-2 text-slate-700 dark:text-slate-400 [&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:pb-1.5 [&_[cmdk-group-heading]]:text-sm [&_[cmdk-group-heading]]:font-semibold [&_[cmdk-group-heading]]:text-slate-900 dark:[&_[cmdk-group-heading]]:text-slate-300",
|
||||
"overflow-hidden py-3 px-2 text-slate-700 dark:text-slate-200 [&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:pb-1.5 [&_[cmdk-group-heading]]:text-sm [&_[cmdk-group-heading]]:font-semibold [&_[cmdk-group-heading]]:text-slate-900 dark:[&_[cmdk-group-heading]]:text-slate-300",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
@@ -103,7 +103,7 @@ const CommandSeparator = React.forwardRef<
|
||||
>(({ className, ...props }, ref) => (
|
||||
<CommandPrimitive.Separator
|
||||
ref={ref}
|
||||
className={cn("-mx-1 h-px bg-slate-100 dark:bg-slate-700", className)}
|
||||
className={cn("-mx-1 h-px bg-slate-100 dark:bg-slate-200", className)}
|
||||
{...props}
|
||||
/>
|
||||
));
|
||||
|
||||
@@ -44,7 +44,7 @@ const DialogContent = React.forwardRef<
|
||||
<DialogPrimitive.Content
|
||||
ref={ref}
|
||||
className={cn(
|
||||
"fixed z-50 grid w-full bg-white max-w-[512px] max-h-[100vh] overflow-y-auto scale-100 gap-4 p-6 opacity-100 animate-in fade-in-90 slide-in-from-bottom-10 sm:max-w-lg sm:rounded-lg sm:zoom-in-90 sm:slide-in-from-bottom-0 dark:text-slate-900",
|
||||
"fixed z-50 grid w-full bg-white dark:bg-slate-800 dark:text-slate-200 text-slate-900 max-w-[512px] max-h-[100vh] overflow-y-auto scale-100 gap-4 p-6 opacity-100 animate-in fade-in-90 slide-in-from-bottom-10 sm:max-w-lg sm:rounded-lg sm:zoom-in-90 sm:slide-in-from-bottom-0",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
@@ -61,6 +61,7 @@ const DialogClose = ({
|
||||
}: DialogPrimitive.DialogCloseProps & React.RefAttributes<HTMLButtonElement> & { className?: string }) => (
|
||||
<DialogPrimitive.Close
|
||||
aria-label="Close"
|
||||
data-testid="dialog-close-button"
|
||||
className={cn(
|
||||
"absolute top-4 right-4 rounded-xs opacity-70 transition-opacity hover:opacity-100 focus:outline-hidden focus:ring-2 focus:ring-slate-400 focus:ring-offset-2 disabled:pointer-events-none data-[state=open]:bg-slate-100 dark:focus:ring-slate-400 dark:focus:ring-offset-slate-900",
|
||||
className,
|
||||
@@ -106,7 +107,7 @@ const DialogTitle = React.forwardRef<
|
||||
>(({ className, ...props }, ref) => (
|
||||
<DialogPrimitive.Title
|
||||
ref={ref}
|
||||
className={cn("text-lg font-semibold text-slate-900", className)}
|
||||
className={cn("text-lg font-semibold text-slate-900 dark:text-slate-100", className)}
|
||||
{...props}
|
||||
/>
|
||||
));
|
||||
@@ -118,7 +119,7 @@ const DialogDescription = React.forwardRef<
|
||||
>(({ className, ...props }, ref) => (
|
||||
<DialogPrimitive.Description
|
||||
ref={ref}
|
||||
className={cn("text-sm text-slate-700", className)}
|
||||
className={cn("text-sm text-slate-800 dark:text-slate-200", className)}
|
||||
{...props}
|
||||
/>
|
||||
));
|
||||
|
||||
@@ -7,7 +7,7 @@ type FooterProps = {
|
||||
const Footer = ({ className, ...props }: FooterProps) => {
|
||||
return (
|
||||
<footer
|
||||
className={cn("flex mt-auto justify-center p-2", className)}
|
||||
className={cn("flex mt-auto justify-center py-2 px-4 text-sm lg:text-md", className)}
|
||||
{...props}
|
||||
>
|
||||
<p>
|
||||
|
||||
+77
-55
@@ -1,16 +1,16 @@
|
||||
import * as React from "react";
|
||||
import { cn } from "@core/utils/cn.ts";
|
||||
import { cva, type VariantProps } from "class-variance-authority";
|
||||
import { Check, Copy, Eye, EyeOff, type LucideIcon } from "lucide-react";
|
||||
import { Check, Copy, Eye, EyeOff, X, type LucideIcon } from "lucide-react";
|
||||
import { useCopyToClipboard } from "@core/hooks/useCopyToClipboard.ts";
|
||||
import { usePasswordVisibilityToggle } from "@core/hooks/usePasswordVisibilityToggle.ts";
|
||||
|
||||
const inputVariants = cva(
|
||||
"flex h-10 w-full rounded-md border border-slate-300 bg-transparent py-2 px-3 text-sm placeholder:text-slate-400 focus:outline-none focus:ring-1 focus:ring-slate-400 disabled:cursor-not-allowed disabled:opacity-50 dark:border-slate-700 dark:text-slate-100 dark:focus:ring-slate-400 dark:focus:ring-offset-slate-600",
|
||||
"flex h-10 w-full rounded-md border border-slate-300 bg-transparent py-2 px-3 text-sm placeholder:text-slate-400 focus:outline-none focus:ring-1 focus:ring-slate-400 disabled:cursor-not-allowed disabled:opacity-50 dark:border-slate-500 dark:bg-transparet dark:text-slate-100 dark:focus:ring-slate-400 dark:focus:ring-offset-slate-600",
|
||||
{
|
||||
variants: {
|
||||
variant: {
|
||||
default: "border-slate-300 dark:border-slate-700",
|
||||
default: "border-slate-300 dark:border-slate-500",
|
||||
invalid:
|
||||
"border-red-500 dark:border-red-500 focus:ring-red-500 dark:focus:ring-red-500",
|
||||
},
|
||||
@@ -26,7 +26,8 @@ type InputActionType = {
|
||||
icon: LucideIcon;
|
||||
onClick: (e: React.MouseEvent<HTMLButtonElement>) => void;
|
||||
ariaLabel: string;
|
||||
tooltip?: string;
|
||||
tooltip?: string
|
||||
condition?: boolean;
|
||||
};
|
||||
|
||||
export interface InputProps
|
||||
@@ -36,6 +37,7 @@ export interface InputProps
|
||||
suffix?: React.ReactNode;
|
||||
showPasswordToggle?: boolean;
|
||||
showCopyButton?: boolean;
|
||||
showClearButton?: boolean;
|
||||
containerClassName?: string;
|
||||
}
|
||||
|
||||
@@ -50,7 +52,9 @@ const Input = React.forwardRef<HTMLInputElement, InputProps>(
|
||||
suffix,
|
||||
showPasswordToggle,
|
||||
showCopyButton,
|
||||
showClearButton,
|
||||
value,
|
||||
onChange,
|
||||
...props
|
||||
},
|
||||
ref
|
||||
@@ -58,10 +62,28 @@ const Input = React.forwardRef<HTMLInputElement, InputProps>(
|
||||
const { isVisible, toggleVisibility } = usePasswordVisibilityToggle();
|
||||
const { copy, isCopied } = useCopyToClipboard({ timeout: 1500 });
|
||||
|
||||
const actions: InputActionType[] = [];
|
||||
|
||||
if (showPasswordToggle && type === "password") {
|
||||
actions.push({
|
||||
const potentialActions: InputActionType[] = [
|
||||
{
|
||||
id: "clear-input",
|
||||
icon: X,
|
||||
onClick: (e) => {
|
||||
e.stopPropagation();
|
||||
if (onChange) {
|
||||
const event = {
|
||||
target: { value: "" },
|
||||
currentTarget: { value: "" },
|
||||
} as React.ChangeEvent<HTMLInputElement>;
|
||||
onChange(event);
|
||||
}
|
||||
if (ref && typeof ref !== "function" && ref.current) {
|
||||
ref.current.focus();
|
||||
}
|
||||
},
|
||||
ariaLabel: "Clear input",
|
||||
tooltip: "Clear input",
|
||||
condition: !!showClearButton && !!value,
|
||||
},
|
||||
{
|
||||
id: "toggle-visibility",
|
||||
icon: isVisible ? EyeOff : Eye,
|
||||
onClick: (e) => {
|
||||
@@ -70,10 +92,9 @@ const Input = React.forwardRef<HTMLInputElement, InputProps>(
|
||||
},
|
||||
ariaLabel: isVisible ? "Hide password" : "Show password",
|
||||
tooltip: isVisible ? "Hide password" : "Show password",
|
||||
});
|
||||
}
|
||||
if (showCopyButton) {
|
||||
actions.push({
|
||||
condition: !!showPasswordToggle && type === "password",
|
||||
},
|
||||
{
|
||||
id: "copy-value",
|
||||
icon: isCopied ? Check : Copy,
|
||||
onClick: (e) => {
|
||||
@@ -84,10 +105,14 @@ const Input = React.forwardRef<HTMLInputElement, InputProps>(
|
||||
},
|
||||
ariaLabel: isCopied ? "Copied!" : "Copy to clipboard",
|
||||
tooltip: isCopied ? "Copied!" : "Copy to clipboard",
|
||||
});
|
||||
}
|
||||
condition: !!showCopyButton,
|
||||
},
|
||||
];
|
||||
|
||||
const inputType = showPasswordToggle ? (isVisible ? "text" : "password") : type;
|
||||
const actions = potentialActions.filter(action => action.condition);
|
||||
|
||||
const inputType =
|
||||
showPasswordToggle ? (isVisible ? "text" : "password") : type;
|
||||
|
||||
const hasPrefix = !!prefix;
|
||||
const hasSuffix = !!suffix;
|
||||
@@ -95,16 +120,15 @@ const Input = React.forwardRef<HTMLInputElement, InputProps>(
|
||||
|
||||
const inputClassName = cn(
|
||||
inputVariants({ variant }),
|
||||
hasActions && !hasSuffix && "pr-10",
|
||||
hasPrefix && "rounded-l-none",
|
||||
(hasSuffix || hasActions) && "rounded-r-none border-r-0",
|
||||
className
|
||||
);
|
||||
|
||||
|
||||
return (
|
||||
<div className={cn("relative flex w-full items-stretch", containerClassName)}>
|
||||
{prefix && (
|
||||
<span className="inline-flex items-center rounded-l-md border border-slate-300 bg-slate-100/80 px-3 text-sm text-slate-600 dark:border-slate-700 dark:bg-slate-700 dark:text-slate-300">
|
||||
<span className="inline-flex items-center rounded-l-md border border-r-0 border-slate-300 bg-slate-100/80 px-3 text-sm text-slate-600 dark:border-slate-700 dark:bg-slate-200 dark:text-slate-700">
|
||||
{prefix}
|
||||
</span>
|
||||
)}
|
||||
@@ -114,46 +138,44 @@ const Input = React.forwardRef<HTMLInputElement, InputProps>(
|
||||
className={inputClassName}
|
||||
ref={ref}
|
||||
value={value}
|
||||
onChange={onChange}
|
||||
{...props}
|
||||
/>
|
||||
|
||||
{(hasSuffix || hasActions) && (
|
||||
<div className={cn(
|
||||
"flex items-stretch",
|
||||
!hasSuffix && hasActions && "border-y border-r border-slate-300 dark:border-slate-700 rounded-r-md"
|
||||
)}>
|
||||
{suffix && (
|
||||
<span className={cn(
|
||||
"inline-flex items-center border border-slate-300 bg-slate-100/80 px-3 text-sm text-slate-600 dark:border-slate-700 dark:bg-slate-700 dark:text-slate-300",
|
||||
!hasActions && "rounded-r-md"
|
||||
)}>
|
||||
{suffix}
|
||||
</span>
|
||||
)}
|
||||
{actions.length > 0 && (
|
||||
<div className={cn(
|
||||
"flex h-full items-center divide-x divide-slate-300 dark:divide-slate-700",
|
||||
!hasSuffix && "border-l border-slate-300 dark:border-slate-700"
|
||||
)}>
|
||||
{actions?.map((action) => (
|
||||
<button
|
||||
key={action.id}
|
||||
type="button"
|
||||
className={cn(
|
||||
"inline-flex h-full items-center justify-center px-2.5 text-slate-500 hover:bg-slate-100 hover:text-slate-700 focus:outline-none focus:ring-1 focus:ring-slate-400 focus:ring-offset-0 dark:text-slate-400 dark:hover:bg-slate-700 dark:hover:text-slate-200 dark:focus:ring-slate-500",
|
||||
action.id === 'copy-value' && isCopied && "text-green-600 dark:text-green-500"
|
||||
)}
|
||||
onClick={action.onClick}
|
||||
aria-label={action.ariaLabel}
|
||||
title={action.tooltip || action.ariaLabel}
|
||||
>
|
||||
<action.icon size={18} aria-hidden="true" />
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
<div className="absolute right-0 top-0 flex h-full items-stretch">
|
||||
{suffix && (
|
||||
<span className={cn(
|
||||
"inline-flex items-center border border-l-0 border-slate-300 bg-slate-100/80 px-3 text-sm text-slate-600 dark:border-slate-700 dark:bg-slate-700 dark:text-slate-300",
|
||||
!hasActions && "rounded-r-md"
|
||||
)}>
|
||||
{suffix}
|
||||
</span>
|
||||
)}
|
||||
|
||||
{hasActions && (
|
||||
<div className={cn(
|
||||
"flex items-center divide-x divide-slate-300 border border-l-0 border-slate-300 dark:divide-slate-700 dark:border-slate-700",
|
||||
!hasSuffix && "rounded-r-md",
|
||||
"bg-white dark:bg-slate-800"
|
||||
)}>
|
||||
{actions.map((action) => (
|
||||
<button
|
||||
key={action.id}
|
||||
type="button"
|
||||
className={cn(
|
||||
"inline-flex h-full items-center justify-center px-2.5 text-slate-500 hover:bg-slate-100 hover:text-slate-700 focus:outline-none focus:ring-1 focus:ring-slate-400 focus:ring-offset-0 dark:text-slate-400 dark:hover:bg-slate-700 dark:hover:text-slate-200 dark:focus:ring-slate-500 hover:rounded-md dark:hover:rounded-md",
|
||||
action.id === 'copy-value' && isCopied && "text-green-600 dark:text-green-500"
|
||||
)}
|
||||
onClick={action.onClick}
|
||||
aria-label={action.ariaLabel}
|
||||
title={action.tooltip || action.ariaLabel}
|
||||
>
|
||||
<action.icon size={18} aria-hidden="true" />
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,81 @@
|
||||
import React from "react";
|
||||
import { Button } from "@components/UI/Button.tsx";
|
||||
import type { LucideIcon } from "lucide-react";
|
||||
import { cn } from "@core/utils/cn.ts";
|
||||
import { useSidebar } from "@core/stores/sidebarStore.tsx";
|
||||
|
||||
export interface SidebarButtonProps {
|
||||
label: string;
|
||||
count?: number;
|
||||
active?: boolean;
|
||||
Icon?: LucideIcon;
|
||||
children?: React.ReactNode;
|
||||
onClick?: () => void;
|
||||
disabled?: boolean;
|
||||
preventCollapse?: boolean;
|
||||
}
|
||||
|
||||
export const SidebarButton = ({
|
||||
label,
|
||||
active,
|
||||
Icon,
|
||||
count,
|
||||
children,
|
||||
onClick,
|
||||
disabled = false,
|
||||
preventCollapse = false,
|
||||
}: SidebarButtonProps) => {
|
||||
const { isCollapsed: isSidebarCollapsed } = useSidebar();
|
||||
const isButtonCollapsed = isSidebarCollapsed && !preventCollapse;
|
||||
|
||||
return (
|
||||
<Button
|
||||
onClick={onClick}
|
||||
variant={active ? "subtle" : "ghost"}
|
||||
size="sm"
|
||||
className={cn(
|
||||
"flex w-full items-center text-wrap",
|
||||
isButtonCollapsed
|
||||
? 'justify-center gap-0 px-2 h-9'
|
||||
: 'justify-start gap-2 min-h-9'
|
||||
)}
|
||||
disabled={disabled}
|
||||
>
|
||||
{Icon && (
|
||||
<Icon
|
||||
size={isButtonCollapsed ? 20 : 18}
|
||||
className="flex-shrink-0"
|
||||
/>
|
||||
)}
|
||||
|
||||
{children}
|
||||
|
||||
<span
|
||||
className={cn(
|
||||
'flex flex-wrap justify-start text-left text-wrap break-all',
|
||||
'min-w-0',
|
||||
'px-1',
|
||||
'transition-all duration-300 ease-in-out',
|
||||
isButtonCollapsed
|
||||
? 'opacity-0 max-w-0 invisible w-0 overflow-hidden'
|
||||
: 'opacity-100 max-w-full visible flex-1 whitespace-normal'
|
||||
)}
|
||||
>
|
||||
{label}
|
||||
</span>
|
||||
|
||||
{!isButtonCollapsed && !active && count && count > 0 && (
|
||||
<div
|
||||
className={cn(
|
||||
"ml-auto flex-shrink-0 justify-end text-white text-xs rounded-full px-1.5 py-0.5 bg-red-600",
|
||||
"flex-shrink-0",
|
||||
"transition-opacity duration-300 ease-in-out",
|
||||
isButtonCollapsed ? 'opacity-0 invisible' : 'opacity-100 visible'
|
||||
)}
|
||||
>
|
||||
{count}
|
||||
</div>
|
||||
)}
|
||||
</Button>
|
||||
);
|
||||
};
|
||||
@@ -1,19 +1,42 @@
|
||||
import { Heading } from "../Typography/Heading.tsx";
|
||||
import React from "react";
|
||||
import { cn } from "@core/utils/cn.ts";
|
||||
import { Heading } from "@components/UI/Typography/Heading.tsx";
|
||||
import { useSidebar } from "@core/stores/sidebarStore.tsx";
|
||||
|
||||
export interface SidebarSectionProps {
|
||||
interface SidebarSectionProps {
|
||||
label: string;
|
||||
subheader?: string;
|
||||
children: React.ReactNode;
|
||||
className?: string;
|
||||
}
|
||||
|
||||
export const SidebarSection = ({
|
||||
label: title,
|
||||
label,
|
||||
children,
|
||||
}: SidebarSectionProps) => (
|
||||
<div className="px-4 py-2">
|
||||
<Heading as="h4" className="mb-3 ml-2">
|
||||
{title}
|
||||
</Heading>
|
||||
<div className="space-y-1">{children}</div>
|
||||
</div>
|
||||
);
|
||||
className,
|
||||
}: SidebarSectionProps) => {
|
||||
const { isCollapsed } = useSidebar();
|
||||
return (
|
||||
<div className={cn(
|
||||
"py-2",
|
||||
isCollapsed ? 'px-0' : 'px-4',
|
||||
className,
|
||||
)}>
|
||||
|
||||
<Heading as="h3" className={cn(
|
||||
'mb-2',
|
||||
'uppercase tracking-wider text-md',
|
||||
'transition-all duration-300 ease-in-out',
|
||||
'whitespace-nowrap overflow-hidden',
|
||||
isCollapsed
|
||||
? 'opacity-0 max-w-0 h-0 invisible px-0 mb-0'
|
||||
: 'opacity-100 max-w-xs h-auto visible px-1 mb-1'
|
||||
)}>
|
||||
{label}
|
||||
</Heading>
|
||||
|
||||
<div className="space-y-0.5">
|
||||
{children}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
@@ -1,5 +1,8 @@
|
||||
import React from "react";
|
||||
import { Button } from "@components/UI/Button.tsx";
|
||||
import type { LucideIcon } from "lucide-react";
|
||||
import { cn } from "@core/utils/cn.ts";
|
||||
import { useSidebar } from "@core/stores/sidebarStore.tsx";
|
||||
|
||||
export interface SidebarButtonProps {
|
||||
label: string;
|
||||
@@ -9,6 +12,7 @@ export interface SidebarButtonProps {
|
||||
children?: React.ReactNode;
|
||||
onClick?: () => void;
|
||||
disabled?: boolean;
|
||||
preventCollapse?: boolean;
|
||||
}
|
||||
|
||||
export const SidebarButton = ({
|
||||
@@ -19,17 +23,59 @@ export const SidebarButton = ({
|
||||
children,
|
||||
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} />}
|
||||
{children && children}
|
||||
<span className="flex flex-1 justify-start shrink-0">{label}</span>
|
||||
{count && count > 0 && !active && <div className="justify-end text-white rounded-[20%] px-[2%] bg-[rgb(195,0,0)]">{count}</div>}
|
||||
</Button>
|
||||
);
|
||||
preventCollapse = false,
|
||||
}: SidebarButtonProps) => {
|
||||
const { isCollapsed: isSidebarCollapsed } = useSidebar();
|
||||
const isButtonCollapsed = isSidebarCollapsed && !preventCollapse;
|
||||
|
||||
return (
|
||||
<Button
|
||||
onClick={onClick}
|
||||
variant={active ? "subtle" : "ghost"}
|
||||
size="sm"
|
||||
className={cn(
|
||||
"flex w-full items-center text-wrap",
|
||||
isButtonCollapsed
|
||||
? 'justify-center gap-0 px-2 h-9'
|
||||
: 'justify-start gap-2 min-h-9'
|
||||
)}
|
||||
disabled={disabled}
|
||||
>
|
||||
{Icon && (
|
||||
<Icon
|
||||
size={isButtonCollapsed ? 20 : 18}
|
||||
className="flex-shrink-0"
|
||||
/>
|
||||
)}
|
||||
|
||||
{children}
|
||||
|
||||
<span
|
||||
className={cn(
|
||||
'flex flex-wrap justify-start text-left text-wrap break-all',
|
||||
'min-w-0',
|
||||
'px-1',
|
||||
'transition-all duration-300 ease-in-out',
|
||||
isButtonCollapsed
|
||||
? 'opacity-0 max-w-0 invisible w-0 overflow-hidden'
|
||||
: 'opacity-100 max-w-full visible flex-1 whitespace-normal'
|
||||
)}
|
||||
>
|
||||
{label}
|
||||
</span>
|
||||
|
||||
{!isButtonCollapsed && !active && count && count > 0 && (
|
||||
<div
|
||||
className={cn(
|
||||
"ml-auto flex-shrink-0 justify-end text-white text-xs rounded-full px-1.5 py-0.5 bg-red-600",
|
||||
"flex-shrink-0",
|
||||
"transition-opacity duration-300 ease-in-out",
|
||||
isButtonCollapsed ? 'opacity-0 invisible' : 'opacity-100 visible'
|
||||
)}
|
||||
>
|
||||
{count}
|
||||
</div>
|
||||
)}
|
||||
</Button>
|
||||
);
|
||||
};
|
||||
@@ -12,7 +12,7 @@ const TabsList = React.forwardRef<
|
||||
<TabsPrimitive.List
|
||||
ref={ref}
|
||||
className={cn(
|
||||
"inline-flex flex-wrap items-center rounded-md p-1 mt-2 bg-slate-200 dark:bg-slate-200",
|
||||
"inline-flex flex-wrap items-center rounded-md p-1 mt-2 bg-slate-200 dark:bg-slate-100",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
|
||||
@@ -28,7 +28,7 @@ const toastVariants = cva(
|
||||
variants: {
|
||||
variant: {
|
||||
default:
|
||||
"border bg-backgound-primary text-foreground dark:bg-white dark:border-slate-600 dark:text-slate-900",
|
||||
"border bg-white text-slate-900 dark:text-slate-100 dark:bg-slate-800",
|
||||
destructive:
|
||||
"group destructive bg-red-600 text-white dark:border-red-900 dark:bg-red-900 dark:text-red-50",
|
||||
},
|
||||
|
||||
@@ -19,7 +19,7 @@ const TooltipContent = React.forwardRef<
|
||||
ref={ref}
|
||||
sideOffset={sideOffset}
|
||||
className={cn(
|
||||
"z-50 overflow-hidden rounded-md border border-slate-100 bg-white px-3 py-1.5 text-sm text-slate-700 shadow-md animate-in fade-in-50 data-[side=bottom]:slide-in-from-top-1 data-[side=left]:slide-in-from-right-1 data-[side=right]:slide-in-from-left-1 data-[side=top]:slide-in-from-bottom-1 dark:border-slate-800 dark:bg-slate-800 dark:text-slate-400",
|
||||
"z-50 overflow-hidden rounded-md border border-slate-100 bg-white px-3 py-1.5 text-sm text-slate-700 shadow-md animate-in fade-in-50 data-[side=bottom]:slide-in-from-top-1 data-[side=left]:slide-in-from-right-1 data-[side=right]:slide-in-from-left-1 data-[side=top]:slide-in-from-bottom-1 dark:border-slate-800 dark:bg-slate-800 dark:text-slate-200",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
|
||||
@@ -4,7 +4,7 @@ const headingStyles = {
|
||||
h1: "scroll-m-20 text-4xl font-extrabold tracking-tight lg:text-5xl",
|
||||
h2:
|
||||
"scroll-m-20 border-b border-b-slate-200 pb-2 text-3xl font-semibold tracking-tight transition-colors first:mt-0 dark:border-b-slate-700",
|
||||
h3: "scroll-m-20 text-2xl font-semibold tracking-tight",
|
||||
h3: "scroll-m-20 text-lg font-semibold tracking-tight",
|
||||
h4: "scroll-m-20 text-xl font-semibold tracking-tight",
|
||||
h5: "scroll-m-20 text-lg font-medium tracking-tight",
|
||||
};
|
||||
|
||||
@@ -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-900",
|
||||
"font-medium text-slate-900 underline underline-offset-4 dark:text-slate-200",
|
||||
className,
|
||||
)}
|
||||
>
|
||||
|
||||
@@ -1,11 +1,17 @@
|
||||
import { cn } from "@core/utils/cn.ts";
|
||||
|
||||
interface MonoProps extends React.HTMLAttributes<HTMLSpanElement> {
|
||||
children: React.ReactNode;
|
||||
className?: string;
|
||||
}
|
||||
export const Mono = ({
|
||||
children,
|
||||
className,
|
||||
...rest
|
||||
}: JSX.IntrinsicElements["span"]) => {
|
||||
}: MonoProps) => {
|
||||
return (
|
||||
<span
|
||||
className={`font-mono text-sm text-text-secondary ${className ?? ""}`}
|
||||
className={cn("font-mono text-sm text-text-secondary", className)}
|
||||
{...rest}
|
||||
>
|
||||
{children}
|
||||
|
||||
@@ -17,11 +17,11 @@ export interface Heading {
|
||||
* @returns number of hopsAway or `0` if hopsAway is 'Direct'
|
||||
*/
|
||||
function numericHops(hopsAway: string): number {
|
||||
if(hopsAway.match(/direct/i)){
|
||||
if (hopsAway.match(/direct/i)) {
|
||||
return 0;
|
||||
}
|
||||
if ( hopsAway.match(/\d+\s+hop/gi) ) {
|
||||
return Number( hopsAway.match(/(\d+)\s+hop/i)?.[1] );
|
||||
if (hopsAway.match(/\d+\s+hop/gi)) {
|
||||
return Number(hopsAway.match(/(\d+)\s+hop/i)?.[1]);
|
||||
}
|
||||
return Number.MAX_SAFE_INTEGER;
|
||||
}
|
||||
@@ -46,7 +46,6 @@ export const Table = ({ headings, rows }: TableProps) => {
|
||||
const aValue = a[columnIndex].props.children;
|
||||
const bValue = b[columnIndex].props.children;
|
||||
|
||||
// Custom comparison for 'Last Heard' column
|
||||
if (sortColumn === "Last Heard") {
|
||||
const aTimestamp = aValue.props.timestamp ?? 0;
|
||||
const bTimestamp = bValue.props.timestamp ?? 0;
|
||||
@@ -60,11 +59,10 @@ export const Table = ({ headings, rows }: TableProps) => {
|
||||
return 0;
|
||||
}
|
||||
|
||||
// Custom comparison for 'Connection' column
|
||||
if (sortColumn === "Connection") {
|
||||
const aNumHops = numericHops(aValue instanceof Array ? aValue[0] : aValue);
|
||||
const bNumHops = numericHops(bValue instanceof Array ? bValue[0] : bValue);
|
||||
|
||||
|
||||
if (aNumHops < bNumHops) {
|
||||
return sortOrder === "asc" ? -1 : 1;
|
||||
}
|
||||
@@ -74,7 +72,6 @@ export const Table = ({ headings, rows }: TableProps) => {
|
||||
return 0;
|
||||
}
|
||||
|
||||
// Default comparison for other columns
|
||||
if (aValue < bValue) {
|
||||
return sortOrder === "asc" ? -1 : 1;
|
||||
}
|
||||
@@ -86,17 +83,16 @@ export const Table = ({ headings, rows }: TableProps) => {
|
||||
|
||||
return (
|
||||
<table className="min-w-full">
|
||||
<thead className="bg-backgound-primary text-sm font-semibold text-text-primary">
|
||||
<thead className="text-xs font-semibold">
|
||||
<tr>
|
||||
{headings.map((heading) => (
|
||||
<th
|
||||
key={heading.title}
|
||||
scope="col"
|
||||
className={`py-2 pr-3 text-left ${
|
||||
heading.sortable
|
||||
? "cursor-pointer hover:brightness-hover active:brightness-press"
|
||||
: ""
|
||||
}`}
|
||||
className={`py-2 pr-3 text-left ${heading.sortable
|
||||
? "cursor-pointer hover:brightness-hover active:brightness-press"
|
||||
: ""
|
||||
}`}
|
||||
onClick={() => heading.sortable && headingSort(heading.title)}
|
||||
onKeyUp={() => heading.sortable && headingSort(heading.title)}
|
||||
>
|
||||
@@ -111,28 +107,29 @@ export const Table = ({ headings, rows }: TableProps) => {
|
||||
))}
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{sortedRows.map((row, index) => (
|
||||
<tbody className="max-w-fit">
|
||||
{sortedRows.map((row, index) => {
|
||||
// biome-ignore lint/suspicious/noArrayIndexKey: TODO: Once this table is sortable, this should get fixed.
|
||||
<tr key={index} className={`${index % 2 ? 'bg-white dark:bg-white/2' : 'bg-slate-50/50 dark:bg-slate-50/5'} border-b-1 border-slate-200 dark:border-slate-900`}>
|
||||
{row.map((item, index) => (
|
||||
index === 0 ?
|
||||
<th
|
||||
key={item.key ?? index}
|
||||
className="whitespace-nowrap py-2 text-sm text-text-secondary first:pl-2"
|
||||
scope="row"
|
||||
>
|
||||
{item}
|
||||
</th> :
|
||||
<td
|
||||
key={item.key ?? index}
|
||||
className="whitespace-nowrap py-2 text-sm text-text-secondary first:pl-2"
|
||||
>
|
||||
{item}
|
||||
</td>
|
||||
))}
|
||||
return (<tr key={index} className={`${index % 2 ? 'bg-white dark:bg-white/2' : 'bg-slate-50/50 dark:bg-slate-50/5'} border-b-1 border-slate-200 dark:border-slate-900`}>
|
||||
{row.map((item, index) => {
|
||||
return (index === 0 ?
|
||||
<th
|
||||
key={item.key ?? index}
|
||||
className="whitespace-nowrap py-2 text-sm text-text-secondary first:pl-2"
|
||||
scope="row"
|
||||
>
|
||||
{item}
|
||||
</th> :
|
||||
<td
|
||||
key={item.key ?? index}
|
||||
className="whitespace-nowrap py-2 text-sm text-text-secondary first:pl-2"
|
||||
>
|
||||
{item}
|
||||
</td>)
|
||||
})}
|
||||
</tr>
|
||||
))}
|
||||
);
|
||||
})}
|
||||
</tbody>
|
||||
</table>
|
||||
);
|
||||
|
||||
Reference in New Issue
Block a user