From a11ac2246d3064c23ee2187a5cfaeba5b9e3974b Mon Sep 17 00:00:00 2001 From: Mist Date: Sat, 24 Feb 2024 18:07:41 +0800 Subject: [PATCH] [Feat] distinguish dev and prod in server and client (#19) --- snap-client/src/app.tsx | 3 ++- snap-client/src/utils/addr.ts | 4 ++++ snap-client/src/utils/index.ts | 1 + snap-server/src/port.rs | 8 ++++++++ 4 files changed, 15 insertions(+), 1 deletion(-) create mode 100644 snap-client/src/utils/addr.ts create mode 100644 snap-client/src/utils/index.ts diff --git a/snap-client/src/app.tsx b/snap-client/src/app.tsx index 94c68f5..61e3ac5 100644 --- a/snap-client/src/app.tsx +++ b/snap-client/src/app.tsx @@ -4,12 +4,13 @@ import { ControlBar, Editor, Frame, Panel } from "./components"; import { useConfig, useEvent } from "./hooks"; import { toPng, toBlob } from "html-to-image"; import download from "downloadjs"; +import { getWebsocketHost } from "./utils"; const CODE_EMPTY_PLACEHOLDER = `print "Hello, CodeSnap.nvim!"`; const WATER_MARK_PLACEHOLDER = "CodeSnap.nvim"; function App() { - const [socketUrl] = useState(`ws://${window.location.host}/ws`); + const [socketUrl] = useState(`ws://${getWebsocketHost()}/ws`); const { sendMessage, lastMessage, readyState } = useWebSocket(socketUrl); const event = useEvent(lastMessage); const config = useConfig(event?.config_setup); diff --git a/snap-client/src/utils/addr.ts b/snap-client/src/utils/addr.ts new file mode 100644 index 0000000..1a39c17 --- /dev/null +++ b/snap-client/src/utils/addr.ts @@ -0,0 +1,4 @@ +export const getWebsocketHost = () => + process.env.NODE_ENV === "development" + ? "localhost:8080" + : window.location.host; diff --git a/snap-client/src/utils/index.ts b/snap-client/src/utils/index.ts new file mode 100644 index 0000000..c60b26a --- /dev/null +++ b/snap-client/src/utils/index.ts @@ -0,0 +1 @@ +export * from "./addr"; diff --git a/snap-server/src/port.rs b/snap-server/src/port.rs index ac99dd7..b38e2b5 100644 --- a/snap-server/src/port.rs +++ b/snap-server/src/port.rs @@ -1,6 +1,14 @@ use std::net::TcpListener; pub fn get_available_port() -> Option { + if cfg!(debug_assertions) { + Some(8080) + } else { + find_available_port() + } +} + +fn find_available_port() -> Option { (8000..10000).find(|port| port_is_available(*port)) }