diff --git a/src/profiles/web/src/App.tsx b/src/profiles/web/src/App.tsx index a2d9cc8..e2ee50f 100644 --- a/src/profiles/web/src/App.tsx +++ b/src/profiles/web/src/App.tsx @@ -32,7 +32,7 @@ import { DropConfigOverlay } from "./components/DropConfigOverlay"; import { FileListTable } from "./components/FileListTable"; import { HeaderBar } from "./components/HeaderBar"; import { InitErrorPanel } from "./components/InitErrorPanel"; -import { LanConfirmDialog } from "./components/LanConfirmDialog"; +import { LanModal } from "./components/LanModal"; import { SearchBar } from "./components/SearchBar"; import { LogViewerModal } from "./components/LogViewerModal"; import { ShortcutsModal } from "./components/ShortcutsModal"; @@ -96,8 +96,8 @@ export default function App() { const [propertiesFile, setPropertiesFile] = useState(null); const [showLogViewer, setShowLogViewer] = useState(false); const [showTimerModal, setShowTimerModal] = useState(false); - /** Pending LAN toggle (true/false) awaiting user confirmation. */ - const [lanPending, setLanPending] = useState(null); + /** LAN access modal visibility — one modal for enable and disable. */ + const [lanModalOpen, setLanModalOpen] = useState(false); // Workflow Modal state const [workflowLaunchParams, setWorkflowLaunchParams] = useState<{ @@ -121,9 +121,10 @@ export default function App() { const [showCameraScanner, setShowCameraScanner] = useState(false); const [singleMatchFile, setSingleMatchFile] = useState(null); - /** Open the in-app confirmation dialog for a LAN toggle request. */ - const toggleLan = (next: boolean) => { - setLanPending(next); + /** Open the LAN modal; it reflects the live bind state and offers the + * opposite action, so the requested direction from the header is unused. */ + const toggleLan = (_next: boolean) => { + setLanModalOpen(true); }; /** @@ -849,7 +850,8 @@ export default function App() { onProperties: handleProperties, onToggleTheme: () => toggleTheme({ persist: true }), setShowLogViewer, setShowShortcuts, setShowTimerModal, - setShowConfigEditor, setBarcodeMode, setShowCameraScanner, + setShowConfigEditor, setShowLanModal: setLanModalOpen, + setBarcodeMode, setShowCameraScanner, moveSelection, }); @@ -1171,13 +1173,14 @@ export default function App() { onCancel={() => setPendingDeleteFile(null)} /> - {/* LAN toggle confirmation */} - setLanPending(null)} + onClose={() => setLanModalOpen(false)} /> {/* Single Match Launch Confirmation */} diff --git a/src/profiles/web/src/components/LanConfirmDialog.test.tsx b/src/profiles/web/src/components/LanConfirmDialog.test.tsx deleted file mode 100644 index c44217a..0000000 --- a/src/profiles/web/src/components/LanConfirmDialog.test.tsx +++ /dev/null @@ -1,170 +0,0 @@ -// @vitest-environment jsdom -import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; -import { cleanup, render, screen, waitFor } from "@testing-library/react"; -import userEvent from "@testing-library/user-event"; -import { LanConfirmDialog } from "./LanConfirmDialog"; -import { fetchSystemInfo, setLanEnabled, waitForLanState } from "../api/client"; -import type { SystemInfo } from "../api/types"; - -vi.mock("../api/client", async (importOriginal) => { - // Keep the real module: the dialog only needs the three flow functions - // mocked (ConfigEditorModal precedent for direct-imported api clients). - const actual = await importOriginal(); - return { - ...actual, - setLanEnabled: vi.fn(), - waitForLanState: vi.fn(), - fetchSystemInfo: vi.fn(), - }; -}); - -const setLanSpy = vi.mocked(setLanEnabled); -const waitSpy = vi.mocked(waitForLanState); -const fetchSpy = vi.mocked(fetchSystemInfo); - -/** LAN-enabled machine fixture; realistic for the dialog's URLs. */ -function makeSystemInfo(overrides: Partial = {}): SystemInfo { - return { - hostname: "st-465", - ip: "172.16.41.65", - username: "operator", - os_release: "TestOS 1.0", - lan_enabled: true, - ...overrides, - }; -} - -function renderDialog( - overrides: { pending?: boolean | null; systemInfo?: SystemInfo | null } = {}, -) { - const props = { - pending: overrides.pending ?? null, - systemInfo: overrides.systemInfo ?? makeSystemInfo(), - showToast: vi.fn(), - onConfirmed: vi.fn(), - onCancel: vi.fn(), - }; - render(); - return props; -} - -beforeEach(() => { - setLanSpy.mockResolvedValue({ host: "st-465", lan_enabled: true, status: "ok" }); - waitSpy.mockResolvedValue(makeSystemInfo()); - fetchSpy.mockResolvedValue(makeSystemInfo()); -}); - -afterEach(() => { - cleanup(); - vi.restoreAllMocks(); -}); - -describe("LanConfirmDialog", () => { - it("renders nothing when pending is null", () => { - renderDialog({ pending: null }); - expect(screen.queryByRole("dialog")).toBeNull(); - }); - - it("renders the LAN-on message with copyable URLs when enabling", () => { - const sys = makeSystemInfo(); - renderDialog({ pending: true, systemInfo: sys }); - - expect(screen.getByText("Enable LAN access?")).toBeInTheDocument(); - expect(screen.getByRole("button", { name: "Enable LAN" })).toBeInTheDocument(); - expect(screen.getByText(/reachable by anyone on this network/)).toBeInTheDocument(); - // The hostname/IP URLs use the app port — same construction as App's - // message body (moved verbatim). - expect(screen.getByText(`http://${sys.hostname}:${window.location.port}`)).toBeInTheDocument(); - expect(screen.getByText(`http://${sys.ip}:${window.location.port}`)).toBeInTheDocument(); - expect(screen.getByRole("button", { name: "Copy hostname URL" })).toBeInTheDocument(); - expect(screen.getByRole("button", { name: "Copy IP URL" })).toBeInTheDocument(); - }); - - it("renders the restrict message when disabling", () => { - renderDialog({ pending: false }); - - expect(screen.getByText("Restrict to this machine?")).toBeInTheDocument(); - expect(screen.getByRole("button", { name: "Restrict" })).toBeInTheDocument(); - expect(screen.getByText("ProFiles will be reachable only on this machine.")).toBeInTheDocument(); - expect(screen.queryByRole("button", { name: "Copy hostname URL" })).toBeNull(); - expect(screen.queryByRole("button", { name: "Copy IP URL" })).toBeNull(); - }); - - it("confirm closes the dialog first and still completes the flow", async () => { - const sys = makeSystemInfo(); - waitSpy.mockResolvedValue(sys); - const user = userEvent.setup(); - const { onCancel, onConfirmed, showToast } = renderDialog({ pending: true }); - - await user.click(screen.getByRole("button", { name: "Enable LAN" })); - - // Dialog-closes-first quirk: the close action (onCancel) fires before - // the API call, yet the flow still completes behind the closed dialog. - expect(onCancel).toHaveBeenCalledTimes(1); - expect(setLanSpy).toHaveBeenCalledWith(true); - expect(onCancel.mock.invocationCallOrder[0]).toBeLessThan( - setLanSpy.mock.invocationCallOrder[0] - ); - await waitFor(() => expect(onConfirmed).toHaveBeenCalledWith(sys)); - expect(onConfirmed).toHaveBeenCalledTimes(1); - expect(showToast).toHaveBeenCalledWith("Updating LAN binding…", "info"); - expect(showToast).toHaveBeenCalledWith( - "ProFiles is now reachable on the local network.", - "info" - ); - }); - - it("waitForLanState disagreement toasts the still-active failure", async () => { - // The bind response said ok, but the observed state never caught up: - // the outcome branch reads waitForLanState's sys, not the response. - const stale = makeSystemInfo({ lan_enabled: false }); - waitSpy.mockResolvedValue(stale); - const user = userEvent.setup(); - const { onConfirmed, showToast } = renderDialog({ pending: true }); - - await user.click(screen.getByRole("button", { name: "Enable LAN" })); - - await waitFor(() => - expect(showToast).toHaveBeenCalledWith( - "Failed to update LAN binding — the previous address is still active.", - "error" - ) - ); - expect(onConfirmed).toHaveBeenCalledTimes(1); - expect(onConfirmed).toHaveBeenCalledWith(stale); - expect(fetchSpy).not.toHaveBeenCalled(); - expect(showToast).not.toHaveBeenCalledWith( - "ProFiles is now reachable on the local network.", - expect.anything() - ); - }); - - it("rejected setLanEnabled toasts the failure and refetches system info", async () => { - setLanSpy.mockRejectedValue(new Error("boom")); - const refetched = makeSystemInfo({ lan_enabled: false }); - fetchSpy.mockResolvedValue(refetched); - const user = userEvent.setup(); - const { onConfirmed, showToast } = renderDialog({ pending: true }); - - await user.click(screen.getByRole("button", { name: "Enable LAN" })); - - await waitFor(() => expect(onConfirmed).toHaveBeenCalledWith(refetched)); - expect(showToast).toHaveBeenCalledWith("Failed to update LAN binding: boom", "error"); - expect(fetchSpy).toHaveBeenCalledTimes(1); - // The transitional toast ships only after the awaited bind call — - // a rejection skips it entirely. - expect(showToast).not.toHaveBeenCalledWith("Updating LAN binding…", expect.anything()); - }); - - it("cancel calls onCancel", async () => { - const user = userEvent.setup(); - const { onCancel } = renderDialog({ pending: true }); - - await user.click(screen.getByRole("button", { name: "Cancel" })); - - expect(onCancel).toHaveBeenCalledTimes(1); - expect(setLanSpy).not.toHaveBeenCalled(); - expect(waitSpy).not.toHaveBeenCalled(); - expect(fetchSpy).not.toHaveBeenCalled(); - }); -}); diff --git a/src/profiles/web/src/components/LanConfirmDialog.tsx b/src/profiles/web/src/components/LanConfirmDialog.tsx deleted file mode 100644 index af5b512..0000000 --- a/src/profiles/web/src/components/LanConfirmDialog.tsx +++ /dev/null @@ -1,104 +0,0 @@ -import { setLanEnabled, waitForLanState, fetchSystemInfo } from "../api/client"; -import type { SystemInfo } from "../api/types"; -import { ConfirmDialog } from "./ConfirmDialog"; -import { CopyableUrl } from "./CopyableUrl"; - -export interface LanConfirmDialogProps { - /** Tri-state: null = closed, true = enabling LAN access, false = restricting. */ - pending: boolean | null; - systemInfo: SystemInfo | null; - showToast: (msg: string, kind?: "info" | "error") => void; - /** Called with the observed SystemInfo on both success and refetch paths. */ - onConfirmed: (sys: SystemInfo) => void; - onCancel: () => void; -} - -/** - * LAN-toggle confirmation dialog — owns the observe-and-verify flow moved - * verbatim from App.tsx: `setLanEnabled` → transitional toast → - * `waitForLanState` (the rebind runs after the response, so the *observed* - * state decides the outcome branch) → success/failure toast, or a rejected - * bind → error toast + refetch. The api client is imported directly - * (ConfigEditorModal precedent); toasts flow through the injected - * `showToast` and observed state is reported via `onConfirmed(sys)`. - * - * The dialog-closes-first quirk is preserved: the confirm flow calls - * `onCancel()` at its start — the same close action App already performs - * (`setLanPending(null)`) — so the dialog disappears before the async work - * and the flow still completes behind it. - */ -export function LanConfirmDialog({ - pending, - systemInfo, - showToast, - onConfirmed, - onCancel, -}: LanConfirmDialogProps) { - return ( - - ProFiles will be reachable by anyone on this network: - showToast("URL copied to clipboard.")} - onCopyError={() => showToast("Failed to copy URL.", "error")} - /> - showToast("URL copied to clipboard.")} - onCopyError={() => showToast("Failed to copy URL.", "error")} - /> - - ) : ( - "ProFiles will be reachable only on this machine." - ) - } - confirmLabel={pending ? "Enable LAN" : "Restrict"} - onConfirm={async () => { - const next = pending!; - // Dialog-closes-first: close through onCancel before the flow runs. - onCancel(); - try { - await setLanEnabled(next); - showToast( - next - ? "Updating LAN binding…" - : "Restricting ProFiles to this machine…", - "info" - ); - // The rebind runs after the response; observe the real outcome. - const sys = await waitForLanState(next); - if (sys) onConfirmed(sys); - if (sys?.lan_enabled === next) { - showToast( - next - ? "ProFiles is now reachable on the local network." - : "ProFiles is restricted to this machine.", - "info" - ); - } else { - showToast( - "Failed to update LAN binding — the previous address is still active.", - "error" - ); - } - } catch (err) { - const msg = err instanceof Error ? err.message : "Failed to update LAN binding"; - showToast(`Failed to update LAN binding: ${msg}`, "error"); - // Refetch to restore the actual state - const sys = await fetchSystemInfo(); - onConfirmed(sys); - } - }} - onCancel={onCancel} - /> - ); -} diff --git a/src/profiles/web/src/components/LanModal.test.tsx b/src/profiles/web/src/components/LanModal.test.tsx new file mode 100644 index 0000000..e14e906 --- /dev/null +++ b/src/profiles/web/src/components/LanModal.test.tsx @@ -0,0 +1,285 @@ +// @vitest-environment jsdom +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { cleanup, render, screen, waitFor } from "@testing-library/react"; +import userEvent from "@testing-library/user-event"; +import { LanModal } from "./LanModal"; +import { + fetchSystemInfo, + generateBarcode, + setLanEnabled, + waitForLanState, +} from "../api/client"; +import type { SystemInfo } from "../api/types"; + +vi.mock("../api/client", async (importOriginal) => { + // Keep the real module: the modal only needs the flow functions mocked + // (ConfigEditorModal precedent for direct-imported api clients). + const actual = await importOriginal(); + return { + ...actual, + setLanEnabled: vi.fn(), + waitForLanState: vi.fn(), + fetchSystemInfo: vi.fn(), + generateBarcode: vi.fn(), + }; +}); + +const setLanSpy = vi.mocked(setLanEnabled); +const waitSpy = vi.mocked(waitForLanState); +const fetchSpy = vi.mocked(fetchSystemInfo); +const qrSpy = vi.mocked(generateBarcode); + +const QR_IMAGE = "data:image/png;base64,FAKEQR"; + +/** LAN-enabled machine fixture; realistic for the modal's URLs. */ +function makeSystemInfo(overrides: Partial = {}): SystemInfo { + return { + hostname: "st-465", + ip: "172.16.41.65", + username: "operator", + os_release: "TestOS 1.0", + lan_enabled: false, + ...overrides, + }; +} + +/** Manually-resolved promise so in-flight timing is deterministic. */ +function deferred() { + let resolve!: (value: T) => void; + const promise = new Promise((res) => { + resolve = res; + }); + return { promise, resolve }; +} + +function renderModal( + overrides: { open?: boolean; systemInfo?: SystemInfo | null } = {}, +) { + const props = { + open: overrides.open ?? true, + systemInfo: + overrides.systemInfo !== undefined + ? overrides.systemInfo + : makeSystemInfo(), + showToast: vi.fn(), + onConfirmed: vi.fn(), + onClose: vi.fn(), + }; + const utils = render(); + return { ...props, rerender: utils.rerender }; +} + +beforeEach(() => { + setLanSpy.mockResolvedValue({ host: "st-465", lan_enabled: true, status: "ok" }); + waitSpy.mockResolvedValue(makeSystemInfo()); + fetchSpy.mockResolvedValue(makeSystemInfo()); + qrSpy.mockResolvedValue({ image: QR_IMAGE, content: "any" }); +}); + +afterEach(() => { + cleanup(); + vi.restoreAllMocks(); +}); + +describe("LanModal — visibility & state display", () => { + it("renders nothing when open is false and generates no QR", () => { + renderModal({ open: false }); + + expect(screen.queryByRole("dialog")).toBeNull(); + expect(qrSpy).not.toHaveBeenCalled(); + }); + + it("shows the restricted state with an Enable LAN footer button", () => { + renderModal({ systemInfo: makeSystemInfo({ lan_enabled: false }) }); + + // Header carries the status: stable title + color-coded subtitle. + expect(screen.getByText("LAN Access")).toBeInTheDocument(); + expect(screen.getByText("Restricted to the host machine")).toBeInTheDocument(); + // The security warning returns while restricted (user wording). + expect( + screen.getByText("If Enabled, ProFiles will be reachable by anyone on this network.") + ).toBeInTheDocument(); + expect(screen.getByRole("button", { name: "Enable LAN" })).toBeInTheDocument(); + expect(screen.getByRole("button", { name: "Cancel" })).toBeInTheDocument(); + expect(screen.getByRole("button", { name: "Close" })).toBeInTheDocument(); + // Same URLs either way — grouped, plus the loopback link (#199). + expect(screen.getByRole("button", { name: "Copy hostname URL" })).toBeInTheDocument(); + expect(screen.getByRole("button", { name: "Copy IP URL" })).toBeInTheDocument(); + expect(screen.getByRole("button", { name: "Copy loopback URL" })).toBeInTheDocument(); + expect(screen.getByRole("link", { name: /127\.0\.0\.1/ })).toBeInTheDocument(); + }); + + it("shows the enabled state with a Disable LAN footer button", () => { + renderModal({ systemInfo: makeSystemInfo({ lan_enabled: true }) }); + + expect(screen.getByText("Reachable on this network")).toBeInTheDocument(); + expect(screen.queryByText(/ProFiles is reachable/)).toBeNull(); + // The instruction line was removed (user review): the header + QR speak + // for themselves. The warning hides once LAN is actually on. + expect(screen.queryByText(/On another device on this network/)).toBeNull(); + expect(screen.queryByText(/reachable by anyone on this network/)).toBeNull(); + expect(screen.getByRole("button", { name: "Disable LAN" })).toBeInTheDocument(); + expect(screen.getByRole("button", { name: "Cancel" })).toBeInTheDocument(); + }); + + it("always displays the QR, even while LAN is disabled (issue #198 override)", async () => { + const sys = makeSystemInfo({ lan_enabled: false }); + renderModal({ systemInfo: sys }); + + const qr = await screen.findByRole("img", { name: /QR/i }); + expect(qr).toHaveAttribute("src", QR_IMAGE); + expect(qrSpy).toHaveBeenCalledWith({ + content: `http://${sys.ip}:${window.location.port}`, + }); + }); + + it("degrades to an inline message when QR generation fails", async () => { + qrSpy.mockRejectedValue(new Error("qr boom")); + renderModal(); + + expect(await screen.findByText(/qr boom/)).toBeInTheDocument(); + expect(screen.queryByRole("img", { name: /QR/i })).toBeNull(); + expect(screen.getByRole("button", { name: "Enable LAN" })).toBeEnabled(); + }); +}); + +describe("LanModal — enable flow (stays open)", () => { + it("runs in place and flips the modal to the enabled state", async () => { + const sys = makeSystemInfo({ lan_enabled: true }); + const gate = deferred(); + waitSpy.mockReturnValue(gate.promise); + const props = renderModal({ systemInfo: makeSystemInfo() }); + const user = userEvent.setup(); + + await user.click(screen.getByRole("button", { name: "Enable LAN" })); + + // No dialog-closes-first: the modal stays up, flow inside. + expect(props.onClose).not.toHaveBeenCalled(); + // In-flight progress is announced from the footer's left slot. + expect(screen.getByRole("status")).toHaveTextContent("Updating the LAN binding…"); + expect(screen.getByRole("button", { name: "Enable LAN" })).toBeDisabled(); + expect(screen.getByRole("button", { name: "Cancel" })).toBeEnabled(); + + gate.resolve(sys); + await waitFor(() => expect(props.onConfirmed).toHaveBeenCalledWith(sys)); + // App answers onConfirmed by updating systemInfo → the modal reflects it. + props.rerender(); + expect(screen.getByText("Reachable on this network")).toBeInTheDocument(); + expect(screen.getByRole("button", { name: "Disable LAN" })).toBeEnabled(); + // Inline outcome replaces toasts while the modal is open. + expect(props.showToast).not.toHaveBeenCalled(); + }); + + it("observed disagreement shows the failure inline, silent while open", async () => { + const stale = makeSystemInfo({ lan_enabled: false }); + waitSpy.mockResolvedValue(stale); + const user = userEvent.setup(); + const props = renderModal({ systemInfo: makeSystemInfo() }); + + await user.click(screen.getByRole("button", { name: "Enable LAN" })); + + expect(await screen.findByText(/previous address is still active/)).toBeInTheDocument(); + expect(props.onConfirmed).toHaveBeenCalledWith(stale); + expect(props.showToast).not.toHaveBeenCalled(); + expect(screen.getByRole("button", { name: "Enable LAN" })).toBeEnabled(); + }); + + it("rejected bind shows the failure inline and refetches system info", async () => { + setLanSpy.mockRejectedValue(new Error("boom")); + const refetched = makeSystemInfo({ lan_enabled: false }); + fetchSpy.mockResolvedValue(refetched); + const user = userEvent.setup(); + const props = renderModal({ systemInfo: makeSystemInfo() }); + + await user.click(screen.getByRole("button", { name: "Enable LAN" })); + + expect(await screen.findByText(/Failed to update LAN binding: boom/)).toBeInTheDocument(); + await waitFor(() => expect(props.onConfirmed).toHaveBeenCalledWith(refetched)); + expect(fetchSpy).toHaveBeenCalledTimes(1); + }); +}); + +describe("LanModal — disable flow (same UX, issue #197 override)", () => { + it("runs in place and flips the modal back to the restricted state", async () => { + const sys = makeSystemInfo({ lan_enabled: false }); + const gate = deferred(); + waitSpy.mockReturnValue(gate.promise); + const props = renderModal({ systemInfo: makeSystemInfo({ lan_enabled: true }) }); + const user = userEvent.setup(); + + await user.click(screen.getByRole("button", { name: "Disable LAN" })); + + expect(props.onClose).not.toHaveBeenCalled(); + expect(setLanSpy).toHaveBeenCalledWith(false); + expect(screen.getByText("Updating the LAN binding…")).toBeInTheDocument(); + + gate.resolve(sys); + await waitFor(() => expect(props.onConfirmed).toHaveBeenCalledWith(sys)); + props.rerender(); + expect(screen.getByText("Restricted to the host machine")).toBeInTheDocument(); + expect(screen.getByRole("button", { name: "Enable LAN" })).toBeEnabled(); + expect(props.showToast).not.toHaveBeenCalled(); + }); + + it("observed disagreement shows the failure inline", async () => { + const stale = makeSystemInfo({ lan_enabled: true }); + waitSpy.mockResolvedValue(stale); + const user = userEvent.setup(); + const props = renderModal({ systemInfo: makeSystemInfo({ lan_enabled: true }) }); + + await user.click(screen.getByRole("button", { name: "Disable LAN" })); + + expect(await screen.findByText(/previous address is still active/)).toBeInTheDocument(); + expect(props.onConfirmed).toHaveBeenCalledWith(stale); + expect(props.showToast).not.toHaveBeenCalled(); + }); +}); + +describe("LanModal — closing", () => { + it("❌ and Escape both close the modal", async () => { + const user = userEvent.setup(); + const props = renderModal(); + + const cancel = screen.getByRole("button", { name: "Cancel" }); + await waitFor(() => expect(cancel).toHaveFocus()); + await user.keyboard("{Escape}"); + expect(props.onClose).toHaveBeenCalledTimes(1); + + await user.click(screen.getByRole("button", { name: "Close" })); + expect(props.onClose).toHaveBeenCalledTimes(2); + }); + + it("cancel closes without touching the API when idle", async () => { + const user = userEvent.setup(); + const props = renderModal(); + + await user.click(screen.getByRole("button", { name: "Cancel" })); + + expect(props.onClose).toHaveBeenCalledTimes(1); + expect(setLanSpy).not.toHaveBeenCalled(); + expect(waitSpy).not.toHaveBeenCalled(); + expect(fetchSpy).not.toHaveBeenCalled(); + }); + + it("cancel mid-flow falls back to toasts when the flow completes", async () => { + const sys = makeSystemInfo({ lan_enabled: true }); + const gate = deferred(); + waitSpy.mockReturnValue(gate.promise); + const props = renderModal({ systemInfo: makeSystemInfo() }); + const user = userEvent.setup(); + + await user.click(screen.getByRole("button", { name: "Enable LAN" })); + await user.click(screen.getByRole("button", { name: "Cancel" })); + expect(props.onClose).toHaveBeenCalledTimes(1); + // App answers onClose by closing: the modal unmounts its content while + // the flow keeps running (same component instance, open false). + props.rerender(); + + gate.resolve(sys); + await waitFor(() => expect(props.onConfirmed).toHaveBeenCalledWith(sys)); + expect(props.showToast).toHaveBeenCalledWith( + "ProFiles is now reachable on the local network.", + "info" + ); + }); +}); diff --git a/src/profiles/web/src/components/LanModal.tsx b/src/profiles/web/src/components/LanModal.tsx new file mode 100644 index 0000000..6b907f1 --- /dev/null +++ b/src/profiles/web/src/components/LanModal.tsx @@ -0,0 +1,390 @@ +import { useEffect, useRef, useState } from "react"; +import { AlertTriangle, Copy, ExternalLink, Wifi, WifiOff, X } from "lucide-react"; + +import { + fetchSystemInfo, + generateBarcode, + setLanEnabled, + waitForLanState, +} from "../api/client"; +import type { SystemInfo } from "../api/types"; +import { CopyableUrl } from "./CopyableUrl"; +import { useModalA11y } from "../hooks/useModalA11y"; + +export interface LanModalProps { + /** Whether the modal is shown; the flow keeps running after a close. */ + open: boolean; + systemInfo: SystemInfo | null; + showToast: (msg: string, kind?: "info" | "error") => void; + /** Called with the observed SystemInfo on both success and refetch paths. */ + onConfirmed: (sys: SystemInfo) => void; + onClose: () => void; +} + +/** Direction of an in-flight bind change. */ +type Busy = "enable" | "disable" | null; + +/** + * LAN access modal (issues #197/#198/#199) — ONE modal for both directions, + * same UX for enabling and disabling (user decision on PR #200): it reflects + * the live `systemInfo.lan_enabled` and offers the opposite action in the + * footer ("Enable LAN" / "Disable LAN"), which runs in place — the modal + * stays open through the rebind and reports the outcome inline (busy status + * or failure box) instead of closing first. No direction is passed in: the + * modal derives everything from the observed state. + * + * Layout: the QR of the IP URL sits on the LEFT and is always displayed, + * even while LAN is disabled (user decision overriding #198's original + * gating) — it reuses `generateBarcode` / `POST /api/actions/barcode` like + * the files' "Generate QR Code", no client-side dependency. The header + * carries the live status — icon chip (Wifi / WifiOff) plus the stable + * "LAN Access" title over a color-coded subtitle (grey restricted / green + * reachable / amber "Updating the LAN binding…" while a rebind is in + * flight, so header and footer never disagree). The addresses are grouped + * by audience: "For other devices" (IP first — what the QR encodes — then + * the hostname) and "This machine" (loopback, #199, now copyable too), + * with the QR caption tying it to the IP. While restricted, a muted amber + * banner restores the security warning the old confirm dialog carried + * ("If Enabled, ProFiles will be reachable by anyone on this network."). + * ❌ (header) and Escape close at any time; footer buttons never + * disappear — the action disables while a rebind is in flight. + * + * Closing mid-flow falls back to the toast channel: the async flow keeps + * running and reports via `onConfirmed(sys)` + toasts, so App state stays in + * sync. A stale flow can never paint over a reopened modal (BarcodeModal's + * issue-#140 seq pattern). The api client is imported directly + * (ConfigEditorModal precedent); toasts flow through the injected + * `showToast` and observed state is reported via `onConfirmed(sys)`. + */ +export function LanModal({ + open, + systemInfo, + showToast, + onConfirmed, + onClose, +}: LanModalProps) { + const [busy, setBusy] = useState(null); + const [failureMessage, setFailureMessage] = useState(null); + const [qrImage, setQrImage] = useState(null); + const [qrError, setQrError] = useState(null); + const dialogRef = useRef(null); + const cancelRef = useRef(null); + /** Monotonic tag per action click — a slow stale flow must never paint + * over a reopened modal (BarcodeModal's issue-#140 pattern). */ + const seqRef = useRef(0); + /** Mirror of `open`, read by async completions to pick between inline + * state (open) and toasts (closed mid-flow). */ + const openRef = useRef(false); + + useEffect(() => { + openRef.current = open; + }, [open]); + + // A reopened modal clears transient state and invalidates any flow still + // in flight from a previous open. + useEffect(() => { + if (open) { + seqRef.current += 1; + setBusy(null); + setFailureMessage(null); + } + }, [open]); + + const port = window.location.port; + const hostnameUrl = systemInfo ? `http://${systemInfo.hostname}:${port}` : null; + const ipUrl = systemInfo ? `http://${systemInfo.ip}:${port}` : null; + const loopbackUrl = `http://127.0.0.1:${port}`; + const liveEnabled = systemInfo?.lan_enabled === true; + + // QR of the IP URL (#198): always displayed, so generate while open and + // the IP is known — the content does not depend on the bind state. + useEffect(() => { + if (!open || !ipUrl) return; + let cancelled = false; + setQrImage(null); + setQrError(null); + generateBarcode({ content: ipUrl }) + .then((res) => { + if (!cancelled) setQrImage(res.image); + }) + .catch((err) => { + if (!cancelled) + setQrError( + err instanceof Error ? err.message : "Failed to generate the QR code" + ); + }); + return () => { + cancelled = true; + }; + }, [open, ipUrl]); + + const handleDialogKeyDown = useModalA11y({ + isOpen: open, + onClose, + dialogRef, + initialFocusRef: cancelRef, + }); + + if (!open) return null; + + const copyLoopback = async () => { + try { + await navigator.clipboard.writeText(loopbackUrl); + showToast("URL copied to clipboard."); + } catch { + showToast("Failed to copy URL.", "error"); + } + }; + + /** Toggle the bind in place — same UX for both directions. */ + const runToggleFlow = async (next: boolean) => { + const seq = ++seqRef.current; + setFailureMessage(null); + setBusy(next ? "enable" : "disable"); + try { + await setLanEnabled(next); + // The rebind runs after the response; observe the real outcome. + const sys = await waitForLanState(next); + if (sys) onConfirmed(sys); + if (seq !== seqRef.current) return; // modal was reopened meanwhile + setBusy(null); + if (sys?.lan_enabled === next) { + if (!openRef.current) { + showToast( + next + ? "ProFiles is now reachable on the local network." + : "ProFiles is restricted to this machine.", + "info" + ); + } + } else { + setFailureMessage( + "Failed to update LAN binding — the previous address is still active." + ); + if (!openRef.current) { + showToast( + "Failed to update LAN binding — the previous address is still active.", + "error" + ); + } + } + } catch (err) { + const msg = err instanceof Error ? err.message : "Failed to update LAN binding"; + if (seq !== seqRef.current) return; + setBusy(null); + setFailureMessage(`Failed to update LAN binding: ${msg}`); + // Refetch to restore the actual state + const sys = await fetchSystemInfo(); + onConfirmed(sys); + if (!openRef.current) { + showToast(`Failed to update LAN binding: ${msg}`, "error"); + } + } + }; + + return ( +
+
e.stopPropagation()} + className="animate-modal-in w-[480px] max-w-full rounded-2xl border border-frame-line glass-panel p-5" + > +
+ + {busy === "disable" || (!liveEnabled && busy === null) ? ( + + ) : ( + + )} + +
+

+ LAN Access +

+

+ {busy !== null ? ( + <> +

+
+ +
+ +
+ {/* QR column — always displayed (user decision on PR #200). */} +
+
+ {qrImage ? ( + QR code of the LAN address + ) : qrError ? ( + + {qrError} + + ) : ( + + )} +
+

+ Scans the IP address +

+
+ + {/* Addresses column — grouped by audience (user review): the IP + first (what the QR encodes), the hostname second, the loopback + alone under "This machine". Explicit margins keep rows apart. */} +
+ {busy === null && failureMessage && ( +
+ {failureMessage} +
+ )} +

+ For other devices +

+ {ipUrl && ( + showToast("URL copied to clipboard.")} + onCopyError={() => showToast("Failed to copy URL.", "error")} + /> + )} + {hostnameUrl && ( + showToast("URL copied to clipboard.")} + onCopyError={() => showToast("Failed to copy URL.", "error")} + /> + )} +

+ This machine +

+ + +
+
+ + {/* Security warning — the one line the old confirm dialog carried, + back while restricted (user wording). Hidden once LAN is on or a + rebind is in flight. */} + {!liveEnabled && busy === null && ( +
+
+ )} + + {/* Footer buttons never disappear (#197 override): the action flips + with the live state and disables while a rebind is in flight — + its progress lives in the header subtitle (user review: no + duplicate in the footer). */} +
+ + +
+
+
+ ); +} diff --git a/src/profiles/web/src/components/ShortcutsModal.tsx b/src/profiles/web/src/components/ShortcutsModal.tsx index 8a5403e..bcbbbf4 100644 --- a/src/profiles/web/src/components/ShortcutsModal.tsx +++ b/src/profiles/web/src/components/ShortcutsModal.tsx @@ -27,6 +27,7 @@ export function ShortcutsModal({ isOpen, onClose }: ShortcutsModalProps) { { key: "Ctrl + F", desc: "Focus Filter / Search field" }, { key: "Ctrl + L", desc: "Focus File List" }, { key: "Ctrl + Shift + L", desc: "Open the log viewer" }, + { key: "Ctrl + K", desc: "Open the LAN access modal" }, { key: "Ctrl + ,", desc: "Open the config editor" }, { key: "Ctrl + Shift + T", desc: "Toggle theme (Dark / Light)" }, { key: "Ctrl + B", desc: "Toggle barcode scanner mode" }, diff --git a/src/profiles/web/src/hooks/useBarcodeMode.test.tsx b/src/profiles/web/src/hooks/useBarcodeMode.test.tsx index 3bd13cf..daebc15 100644 --- a/src/profiles/web/src/hooks/useBarcodeMode.test.tsx +++ b/src/profiles/web/src/hooks/useBarcodeMode.test.tsx @@ -395,6 +395,7 @@ describe("wedge/shortcuts isolation (issue #187)", () => { setShowShortcuts: vi.fn(), setShowTimerModal: vi.fn(), setShowConfigEditor: vi.fn(), + setShowLanModal: vi.fn(), setBarcodeMode: vi.fn(), setShowCameraScanner: vi.fn(), moveSelection: vi.fn(), diff --git a/src/profiles/web/src/hooks/useGlobalShortcuts.test.tsx b/src/profiles/web/src/hooks/useGlobalShortcuts.test.tsx index 98b05f5..1c857bd 100644 --- a/src/profiles/web/src/hooks/useGlobalShortcuts.test.tsx +++ b/src/profiles/web/src/hooks/useGlobalShortcuts.test.tsx @@ -57,6 +57,7 @@ function makeDeps(overrides: Partial = {}): GlobalShortcuts setShowShortcuts: vi.fn(), setShowTimerModal: vi.fn(), setShowConfigEditor: vi.fn(), + setShowLanModal: vi.fn(), setBarcodeMode: vi.fn(), setShowCameraScanner: vi.fn(), moveSelection: vi.fn(), @@ -264,6 +265,14 @@ describe("useGlobalShortcuts", () => { expect(deps.setShowConfigEditor).toHaveBeenCalledTimes(1); expect(deps.setShowConfigEditor).toHaveBeenCalledWith(true); + press("k", { ctrlKey: true }); + expect(deps.setShowLanModal).toHaveBeenCalledTimes(1); + expect(deps.setShowLanModal).toHaveBeenCalledWith(true); + + // Ctrl+Shift+K stays free (the disambiguation convention of this table). + press("k", { ctrlKey: true, shiftKey: true }); + expect(deps.setShowLanModal).toHaveBeenCalledTimes(1); + press("?"); expect(deps.setShowShortcuts).toHaveBeenCalledTimes(1); expect(deps.setShowShortcuts).toHaveBeenCalledWith(expect.any(Function)); diff --git a/src/profiles/web/src/hooks/useGlobalShortcuts.ts b/src/profiles/web/src/hooks/useGlobalShortcuts.ts index 27de8b9..5dfa90c 100644 --- a/src/profiles/web/src/hooks/useGlobalShortcuts.ts +++ b/src/profiles/web/src/hooks/useGlobalShortcuts.ts @@ -30,6 +30,7 @@ export interface GlobalShortcutsDeps { setShowShortcuts: Dispatch>; setShowTimerModal: Dispatch>; setShowConfigEditor: Dispatch>; + setShowLanModal: Dispatch>; setBarcodeMode: Dispatch>; setShowCameraScanner: Dispatch>; // Selection — functional-updater style; App writes selectedPathRef inside the updater. @@ -154,6 +155,16 @@ export function useGlobalShortcuts(deps: GlobalShortcutsDeps): void { return; } + // Ctrl + K: Open the LAN access modal (issues #197/#198/#199) — same + // entry point as the status-bar LAN button. Ctrl+N was the requested + // mnemonic, but browsers reserve it for "new window" and a page can + // never intercept it, so the LAN modal lands on Ctrl + K. + if (e.ctrlKey && !e.shiftKey && e.key.toLowerCase() === "k") { + e.preventDefault(); + d.setShowLanModal(true); + return; + } + // Ctrl + Shift + T: Cycle theme if (e.ctrlKey && e.shiftKey && e.key.toLowerCase() === "t") { e.preventDefault();