mirror of
https://github.com/netbirdio/netbird.git
synced 2026-09-19 21:29:09 +02:00
[client] UI refactor (#6069)
Refactor UI --------- Co-authored-by: Eduard Gert <kontakt@eduardgert.de> Co-authored-by: braginini <bangvalo@gmail.com> Co-authored-by: Pascal Fischer <32096965+pascal-fischer@users.noreply.github.com> Co-authored-by: Claude <noreply@anthropic.com> Co-authored-by: riccardom <riccardomanfrin@gmail.com>
This commit is contained in:
co-authored by
Eduard Gert
braginini
Pascal Fischer
Claude
riccardom
parent
679c7182a4
commit
8b7ce337d8
@@ -0,0 +1,60 @@
|
||||
import { useLayoutEffect, useRef } from "react";
|
||||
import { Window } from "@wailsio/runtime";
|
||||
import i18next from "@/lib/i18n";
|
||||
import { isLinux } from "@/lib/platform";
|
||||
|
||||
// Sizes the current Wails window to the measured content height (keeping `width`),
|
||||
// then shows it. Re-applies on content resize and language change.
|
||||
export function useAutoSizeWindow<T extends HTMLElement>(width: number, ready: boolean = true) {
|
||||
const ref = useRef<T | null>(null);
|
||||
useLayoutEffect(() => {
|
||||
const el = ref.current;
|
||||
if (!el) return;
|
||||
let shown = false;
|
||||
let raf1 = 0;
|
||||
let raf2 = 0;
|
||||
const showOnce = () => {
|
||||
if (shown) return;
|
||||
shown = true;
|
||||
Window.Show().catch(() => {});
|
||||
Window.Focus().catch(() => {});
|
||||
};
|
||||
const apply = async () => {
|
||||
if (!ready) return;
|
||||
const h = Math.ceil(el.getBoundingClientRect().height);
|
||||
if (h <= 0) return;
|
||||
try {
|
||||
// Window.SetSize takes the frame size, so add the OS title-bar height or content clips.
|
||||
const frame = await Window.Size();
|
||||
const targetH = h + Math.max(0, frame.height - window.innerHeight);
|
||||
// Linux: SetSize no-ops on a mapped non-resizable window (X11), so pin via min/max instead.
|
||||
if (isLinux()) {
|
||||
await Window.SetMinSize(width, targetH);
|
||||
await Window.SetMaxSize(width, targetH);
|
||||
}
|
||||
await Window.SetSize(width, targetH);
|
||||
showOnce();
|
||||
} catch {
|
||||
// window gone / not ready — ignore
|
||||
}
|
||||
};
|
||||
const scheduleApply = () => {
|
||||
cancelAnimationFrame(raf1);
|
||||
cancelAnimationFrame(raf2);
|
||||
raf1 = requestAnimationFrame(() => {
|
||||
raf2 = requestAnimationFrame(apply);
|
||||
});
|
||||
};
|
||||
apply();
|
||||
const ro = new ResizeObserver(apply);
|
||||
ro.observe(el);
|
||||
i18next.on("languageChanged", scheduleApply);
|
||||
return () => {
|
||||
ro.disconnect();
|
||||
cancelAnimationFrame(raf1);
|
||||
cancelAnimationFrame(raf2);
|
||||
i18next.off("languageChanged", scheduleApply);
|
||||
};
|
||||
}, [width, ready]);
|
||||
return ref;
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
import { useEffect, useState } from "react";
|
||||
|
||||
// Tracks the user's current input modality (keyboard vs pointer) at module
|
||||
// scope, mirroring what @react-aria/interactions does. Radix programmatically
|
||||
// focuses elements like Tabs triggers and Select triggers, which makes the
|
||||
// browser's :focus-visible heuristic light up on mouse-driven interactions too.
|
||||
// Gating focus styles on this hook lets us only paint a focus ring when the
|
||||
// user is actually navigating with the keyboard.
|
||||
// See react-aria's useFocusVisible for context.
|
||||
|
||||
type Modality = "keyboard" | "pointer";
|
||||
|
||||
let currentModality: Modality = "pointer";
|
||||
const subscribers = new Set<(m: Modality) => void>();
|
||||
|
||||
const setModality = (m: Modality) => {
|
||||
if (m === currentModality) return;
|
||||
currentModality = m;
|
||||
subscribers.forEach((cb) => cb(m));
|
||||
};
|
||||
|
||||
const isKeyboardEvent = (e: KeyboardEvent) => {
|
||||
if (e.metaKey || e.ctrlKey || e.altKey) return false;
|
||||
return e.key === "Tab" || e.key === "Escape" || e.key.startsWith("Arrow");
|
||||
};
|
||||
|
||||
if (globalThis.window !== undefined) {
|
||||
globalThis.addEventListener(
|
||||
"keydown",
|
||||
(e) => {
|
||||
if (isKeyboardEvent(e)) setModality("keyboard");
|
||||
},
|
||||
true,
|
||||
);
|
||||
globalThis.addEventListener("pointerdown", () => setModality("pointer"), true);
|
||||
}
|
||||
|
||||
export const useFocusVisible = (): boolean => {
|
||||
const [visible, setVisible] = useState(currentModality === "keyboard");
|
||||
useEffect(() => {
|
||||
setVisible(currentModality === "keyboard");
|
||||
const cb = (m: Modality) => setVisible(m === "keyboard");
|
||||
subscribers.add(cb);
|
||||
return () => {
|
||||
subscribers.delete(cb);
|
||||
};
|
||||
}, []);
|
||||
return visible;
|
||||
};
|
||||
@@ -0,0 +1,46 @@
|
||||
import { useEffect } from "react";
|
||||
import { isMacOS } from "@/lib/platform";
|
||||
|
||||
export type Shortcut = {
|
||||
key: string;
|
||||
cmd?: boolean;
|
||||
shift?: boolean;
|
||||
alt?: boolean;
|
||||
preventDefault?: boolean;
|
||||
};
|
||||
|
||||
export const useKeyboardShortcut = (shortcut: Shortcut, callback: () => void, enabled = true) => {
|
||||
useEffect(() => {
|
||||
if (!enabled) return;
|
||||
const onKey = (e: KeyboardEvent) => {
|
||||
if (e.key.toLowerCase() !== shortcut.key.toLowerCase()) return;
|
||||
const mod = e.metaKey || e.ctrlKey;
|
||||
if (!!shortcut.cmd !== mod) return;
|
||||
if (!!shortcut.shift !== e.shiftKey) return;
|
||||
if (!!shortcut.alt !== e.altKey) return;
|
||||
if (shortcut.preventDefault !== false) e.preventDefault();
|
||||
callback();
|
||||
};
|
||||
globalThis.addEventListener("keydown", onKey);
|
||||
return () => globalThis.removeEventListener("keydown", onKey);
|
||||
}, [
|
||||
shortcut.key,
|
||||
shortcut.cmd,
|
||||
shortcut.shift,
|
||||
shortcut.alt,
|
||||
shortcut.preventDefault,
|
||||
callback,
|
||||
enabled,
|
||||
]);
|
||||
};
|
||||
|
||||
export const formatShortcut = (shortcut: Shortcut): string => {
|
||||
// navigator.platform is empty on some WebView2 builds → misrenders ⌘ as Ctrl on Mac.
|
||||
const mac = isMacOS();
|
||||
const parts: string[] = [];
|
||||
if (shortcut.cmd) parts.push(mac ? "⌘" : "Ctrl");
|
||||
if (shortcut.shift) parts.push(mac ? "⇧" : "Shift");
|
||||
if (shortcut.alt) parts.push(mac ? "⌥" : "Alt");
|
||||
parts.push(shortcut.key.length === 1 ? shortcut.key.toUpperCase() : shortcut.key);
|
||||
return parts.join(mac ? "" : "+");
|
||||
};
|
||||
@@ -0,0 +1,143 @@
|
||||
import { useEffect, useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { useSettings } from "@/contexts/SettingsContext.tsx";
|
||||
import { useConfirm } from "@/contexts/DialogContext.tsx";
|
||||
|
||||
export const CLOUD_MANAGEMENT_URL = "https://api.netbird.io:443";
|
||||
const CLOUD_MANAGEMENT_URLS = new Set([
|
||||
CLOUD_MANAGEMENT_URL,
|
||||
"https://api.wiretrustee.com:443", // legacy cloud endpoint
|
||||
]);
|
||||
|
||||
export function isNetbirdCloud(url: string): boolean {
|
||||
if (!url || url.trim() === "") return true;
|
||||
return CLOUD_MANAGEMENT_URLS.has(url);
|
||||
}
|
||||
|
||||
// Matches http(s)://host[:port][/path][?query][#fragment]; host = domain, localhost, or IPv4.
|
||||
// Syntactic validation only — reachability is checked via checkManagementUrlReachable.
|
||||
export const URL_PATTERN = new RegExp(
|
||||
String.raw`^(https?:\/\/)?` +
|
||||
String.raw`((([a-z\d]([a-z\d-]*[a-z\d])?)\.)+[a-z]{2,}|localhost|` +
|
||||
String.raw`((\d{1,3}\.){3}\d{1,3}))` +
|
||||
String.raw`(\:\d+)?(\/[-a-z\d%_.~+]*)*` +
|
||||
String.raw`(\?[;&a-z\d%_.~+=-]*)?` +
|
||||
String.raw`(\#[-a-z\d_]*)?$`,
|
||||
"i",
|
||||
);
|
||||
|
||||
export function normalizeManagementUrl(input: string): string {
|
||||
const trimmed = input.trim();
|
||||
if (!trimmed) return "";
|
||||
if (/^https?:\/\//i.test(trimmed)) return trimmed;
|
||||
return `https://${trimmed}`;
|
||||
}
|
||||
|
||||
export function isValidManagementUrl(input: string): boolean {
|
||||
const trimmed = input.trim();
|
||||
if (!trimmed) return false;
|
||||
return URL_PATTERN.test(trimmed);
|
||||
}
|
||||
|
||||
// Can false-negative for self-hosted behind internal DNS / self-signed certs — treat as a soft warning, not a hard block.
|
||||
export async function checkManagementUrlReachable(
|
||||
url: string,
|
||||
timeoutMs: number = 5000,
|
||||
): Promise<boolean> {
|
||||
const target = normalizeManagementUrl(url);
|
||||
if (!target) return false;
|
||||
const controller = new AbortController();
|
||||
const timer = setTimeout(() => controller.abort(), timeoutMs);
|
||||
try {
|
||||
await fetch(target, { method: "GET", mode: "no-cors", signal: controller.signal });
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
} finally {
|
||||
clearTimeout(timer);
|
||||
}
|
||||
}
|
||||
|
||||
export enum ManagementMode {
|
||||
Cloud = "cloud",
|
||||
SelfHosted = "selfhosted",
|
||||
}
|
||||
|
||||
function modeFromUrl(url: string): ManagementMode {
|
||||
return isNetbirdCloud(url) ? ManagementMode.Cloud : ManagementMode.SelfHosted;
|
||||
}
|
||||
|
||||
export function useManagementUrl() {
|
||||
const { t } = useTranslation();
|
||||
const confirm = useConfirm();
|
||||
const { config, saveField } = useSettings();
|
||||
const [modeState, setModeState] = useState<ManagementMode>(modeFromUrl(config.managementUrl));
|
||||
const [url, setUrl] = useState(
|
||||
isNetbirdCloud(config.managementUrl) ? "" : config.managementUrl,
|
||||
);
|
||||
const [checking, setChecking] = useState(false);
|
||||
const [unreachable, setUnreachable] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
setModeState(modeFromUrl(config.managementUrl));
|
||||
if (!isNetbirdCloud(config.managementUrl)) {
|
||||
setUrl(config.managementUrl);
|
||||
}
|
||||
}, [config.managementUrl]);
|
||||
|
||||
useEffect(() => {
|
||||
setUnreachable(false);
|
||||
}, [url, modeState]);
|
||||
|
||||
const setMode = async (next: ManagementMode) => {
|
||||
if (next === ManagementMode.Cloud && !isNetbirdCloud(config.managementUrl)) {
|
||||
const ok = await confirm({
|
||||
title: t("settings.general.management.switchCloudTitle"),
|
||||
description: t("settings.general.management.switchCloudMessage"),
|
||||
confirmLabel: t("settings.general.management.switchCloudConfirm"),
|
||||
});
|
||||
if (!ok) return;
|
||||
setModeState(ManagementMode.Cloud);
|
||||
saveField("managementUrl", CLOUD_MANAGEMENT_URL).catch((err: unknown) =>
|
||||
console.error("save managementUrl failed", err),
|
||||
);
|
||||
return;
|
||||
}
|
||||
setModeState(next);
|
||||
};
|
||||
|
||||
const normalizedUrl = normalizeManagementUrl(url);
|
||||
const urlValid = isValidManagementUrl(url);
|
||||
const targetUrl = modeState === ManagementMode.Cloud ? CLOUD_MANAGEMENT_URL : normalizedUrl;
|
||||
const dirty = targetUrl !== config.managementUrl;
|
||||
const showError = modeState === ManagementMode.SelfHosted && url.trim() !== "" && !urlValid;
|
||||
const canSave = dirty && (modeState === ManagementMode.Cloud || urlValid);
|
||||
const displayUrl = modeState === ManagementMode.Cloud ? CLOUD_MANAGEMENT_URL : url;
|
||||
|
||||
const save = async () => {
|
||||
if (modeState === ManagementMode.SelfHosted && !unreachable) {
|
||||
setChecking(true);
|
||||
const reachable = await checkManagementUrlReachable(targetUrl);
|
||||
setChecking(false);
|
||||
if (!reachable) {
|
||||
setUnreachable(true);
|
||||
return;
|
||||
}
|
||||
}
|
||||
await saveField("managementUrl", targetUrl);
|
||||
setUnreachable(false);
|
||||
};
|
||||
|
||||
return {
|
||||
mode: modeState,
|
||||
setMode,
|
||||
url,
|
||||
setUrl,
|
||||
displayUrl,
|
||||
showError,
|
||||
canSave,
|
||||
save,
|
||||
checking,
|
||||
unreachable,
|
||||
};
|
||||
}
|
||||
Reference in New Issue
Block a user