From 1536b495c788614f13646195cc387995332d639e Mon Sep 17 00:00:00 2001 From: Stefano Pigozzi Date: Sun, 30 Jul 2023 02:21:29 +0200 Subject: [PATCH] Create initial board viewer page --- todoblue/src/app/board/[board]/page.tsx | 15 +++++++++++ todoblue/src/app/board/[board]/useBoard.tsx | 16 +++++++++++ todoblue/src/app/board/[board]/useWs.tsx | 30 +++++++++++++++++++++ 3 files changed, 61 insertions(+) create mode 100644 todoblue/src/app/board/[board]/page.tsx create mode 100644 todoblue/src/app/board/[board]/useBoard.tsx create mode 100644 todoblue/src/app/board/[board]/useWs.tsx diff --git a/todoblue/src/app/board/[board]/page.tsx b/todoblue/src/app/board/[board]/page.tsx new file mode 100644 index 0000000..ce08b60 --- /dev/null +++ b/todoblue/src/app/board/[board]/page.tsx @@ -0,0 +1,15 @@ +'use client'; +import {default as React} from "react"; +import {useBoard} from "@/app/board/[board]/useBoard" + + +export default function Page({params: {board}}: {params: {board: string}}) { + const wsUrl = React.useMemo(() => `ws://127.0.0.1:8080/board/${board}/ws`, [board]) + useBoard(wsUrl); + + return ( +

+ TODO +

+ ) +} diff --git a/todoblue/src/app/board/[board]/useBoard.tsx b/todoblue/src/app/board/[board]/useBoard.tsx new file mode 100644 index 0000000..dfb4b0c --- /dev/null +++ b/todoblue/src/app/board/[board]/useBoard.tsx @@ -0,0 +1,16 @@ +'use client'; +import {default as React} from "react"; +import {useWs} from "@/app/board/[board]/useWs" + + +export function useBoard(url: string) { + const socket = useWs(url, { + onopen: React.useCallback(() => { + console.debug("[useBoard] Connected to the server!"); + }, []), + onmessage: React.useCallback((event: MessageEvent) => { + const data = JSON.parse(event.data); + console.debug("[useBoard] Received ServerOperation: ", data); + }, []) + }); +} diff --git a/todoblue/src/app/board/[board]/useWs.tsx b/todoblue/src/app/board/[board]/useWs.tsx new file mode 100644 index 0000000..51ccc1b --- /dev/null +++ b/todoblue/src/app/board/[board]/useWs.tsx @@ -0,0 +1,30 @@ +'use client'; +import {default as React} from "react"; + + +export interface UseWsHandlers { + onclose?: (event: CloseEvent) => void, + onerror?: (event: Event) => void, + onmessage?: (event: MessageEvent) => void, + onopen?: (event: Event) => void, +} + + +export function useWs(url: string, {onclose, onerror, onmessage, onopen}: UseWsHandlers) { + const [websocket, setWebsocket] = React.useState(null) + + React.useEffect(() => { + const sock = new WebSocket(url); + sock.onclose = onclose ?? null; + sock.onerror = onerror ?? null; + sock.onmessage = onmessage ?? null; + sock.onopen = onopen ?? null; + setWebsocket(sock); + return () => { + sock.close(); + setWebsocket(null); + } + }, [url, onclose, onerror, onmessage, onopen]) + + return websocket +}