add view socket

This commit is contained in:
Tomas Mirchev 2025-07-01 13:46:32 +00:00
parent 13bd7fdd75
commit 68a9c01027
4 changed files with 372 additions and 127 deletions

View File

@ -28,104 +28,10 @@ import {
VRuleIcon,
} from "./icons/Icons";
import ResourcePage from "./ResourcePage.jsx";
import NamePage from "./NamePage.jsx";
import io from "socket.io-client";
//const socket = io("http://localhost:3000");
import { ViewPage, EditViewPage } from "./ViewPage.jsx";
const DIVIDER_AT = 16;
//function SocketTest() {
// const [booleanArray, setBooleanArray] = useState(new Array(10).fill(false));
// const [isConnected, setIsConnected] = useState(false);
//
// useEffect(() => {
// // Connection status
// socket.on("connect", () => {
// setIsConnected(true);
// console.log("Connected to server");
// });
//
// socket.on("disconnect", () => {
// setIsConnected(false);
// console.log("Disconnected from server");
// });
//
// // Listen for array updates
// socket.on("arrayChanged", (newArray) => {
// setBooleanArray(newArray);
// });
//
// // Cleanup on unmount
// return () => {
// socket.off("connect");
// socket.off("disconnect");
// socket.off("arrayChanged");
// };
// }, []);
//
// const toggleValue = (index) => {
// const newValue = !booleanArray[index];
//
// // Emit update to server
// socket.emit("setArrayValue", { index, value: newValue });
// };
//
// const refreshArray = () => {
// socket.emit("getArray");
// };
//
// return (
// <div style={{ padding: "20px" }}>
// <h1>Socket.IO Boolean Array</h1>
//
// <div style={{ marginBottom: "20px" }}>
// Status:{" "}
// <span style={{ color: isConnected ? "green" : "red" }}>
// {isConnected ? "Connected" : "Disconnected"}
// </span>
// </div>
//
// <button onClick={refreshArray} style={{ marginBottom: "20px" }}>
// Refresh Array
// </button>
//
// <div style={{ display: "grid", gridTemplateColumns: "repeat(5, 100px)", gap: "10px" }}>
// {booleanArray.map((value, index) => (
// <button
// key={index}
// onClick={() => toggleValue(index)}
// style={{
// padding: "20px",
// backgroundColor: value ? "#4CAF50" : "#f44336",
// color: "white",
// border: "none",
// borderRadius: "4px",
// cursor: "pointer",
// }}
// >
// {index}: {value.toString()}
// </button>
// ))}
// </div>
//
// <div style={{ marginTop: "20px" }}>
// <h3>Current Array:</h3>
// <pre>{JSON.stringify(booleanArray)}</pre>
// </div>
// </div>
// );
//}
const contextClass = {
success: "bg-blue-600",
error: "bg-red-600",
info: "bg-gray-600",
warning: "bg-orange-400",
default: "bg-indigo-600",
dark: "bg-white-600 font-gray-300",
};
export function App() {
return (
<>
@ -143,7 +49,8 @@ export function App() {
<Route path=":topicId" element={<FileReader />} />
</Route>
<Route path="/edit" element={<ResourcePage />} />
<Route path="/name" element={<NamePage />} />
<Route path="/view" element={<ViewPage />} />
<Route path="/view-edit" element={<EditViewPage />} />
</Routes>
</BrowserRouter>
<ToastContainer />

323
reader/src/ViewPage.jsx Normal file
View File

@ -0,0 +1,323 @@
import { useState, useEffect, useMemo, useRef } from "react";
import io from "socket.io-client";
import { useStore } from "./store.js";
import { marked } from "marked";
import { TextIncreaseIcon, TextDecreaseIcon, HeartIcon } from "./icons/Icons.jsx";
const socket = io(import.meta.env.VITE_API_BASE_URL);
export function ViewPage() {
const iframeRef = useRef(null);
const config = useStore((state) => state.config);
const changeConfig = useStore((state) => state.changeConfig);
const [isConnected, setIsConnected] = useState(false);
const [data, setData] = useState(null);
const [selectedOptionId, setSelectedOptionId] = useState(null);
const [selectedIdx, setSelectedIdx] = useState(0);
const options = useMemo(() => {
return data?.options.map((option) => {
let fileContent = option.text || "**No Data!**";
fileContent = marked.parse(fileContent);
fileContent = `
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style>
body {
font-family: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif;
line-height: 1.5;
color: #333;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
height: 100%;
}
</style>
</head>
<body>
${fileContent}
</body>
</html>
`;
return { ...option, text: fileContent };
});
}, [data?.options]);
useEffect(() => {
socket.on("connect", () => setIsConnected(true));
socket.on("disconnect", () => setIsConnected(false));
socket.on("dataChanged", (newData) => {
setData(newData);
setSelectedOptionId(null);
setSelectedIdx(0);
});
return () => {
socket.off("connect");
socket.off("disconnect");
};
}, []);
useEffect(() => {
if (iframeRef.current && iframeRef.current.contentDocument) {
iframeRef.current.contentDocument.body.style.zoom = `${config.contentZoomLevel}%`;
}
}, [config.contentZoomLevel]);
if (!data) {
return (
<div className="h-full mx-auto flex justify-center items-center">
<div>
Status:{" "}
<span className={isConnected ? "text-green-500" : "text-red-500"}>
{isConnected ? "Connected" : "Disconnected"}
</span>
</div>
</div>
);
}
return (
<div className="mx-auto h-full relative flex flex-col">
<div
className="w-full px-4 py-2 font-medium text-large text-white bg-blue-600"
style={{ lineHeight: 1.2 }}
>
<span className="truncate">{data.title}</span>
</div>
<div className="flex-1 w-full">
<div className={`w-full h-full overflow-hidden`}>
<iframe
ref={iframeRef}
srcDoc={options[selectedIdx].text}
title="MD Content"
className="flex-1 min-h-full w-full border-none p-0"
allow="fullscreen"
onLoad={() => {
if (iframeRef.current?.contentDocument?.body) {
iframeRef.current.contentDocument.body.style.zoom = `${config.contentZoomLevel}%`;
}
}}
/>
</div>
</div>
<div className="absolute bottom-10 flex justify-end px-4 py-2 w-full z-999">
<div className="flex items-center">
<div className="text-sm text-gray-600 rounded bg-gray-300/30 backdrop-blur px-2">
{config.contentZoomLevel}%
</div>
<button
className={`cursor-pointer p-2 mx-1 rounded-full text-white bg-gray-100/30 backdrop-blur`}
onClick={() =>
changeConfig({ contentZoomLevel: Math.max(50, config.contentZoomLevel - 10) })
}
>
<TextDecreaseIcon className="fill-gray-600" />
</button>
<button
className={`cursor-pointer p-2 rounded-full text-white bg-gray-100/30 backdrop-blur`}
onClick={() => {
changeConfig({ contentZoomLevel: Math.min(150, config.contentZoomLevel + 10) });
}}
>
<TextIncreaseIcon className="fill-gray-600" />
</button>
<button
className={`cursor-pointer p-2 rounded-full text-white bg-gray-100/30 backdrop-blur`}
onClick={() => {
const id = options[selectedIdx].id;
if (selectedOptionId === id) {
setSelectedOptionId(null);
socket.emit("setSelectedOptionId", null);
} else {
setSelectedOptionId(id);
socket.emit("setSelectedOptionId", id);
}
}}
>
<HeartIcon
className={
options[selectedIdx].id === selectedOptionId ? "fill-red-500" : "fill-gray-500"
}
/>
</button>
</div>
</div>
<div className="border-t-2 border-gray-300 flex">
{options.map((option, optionIdx) => (
<button
key={option.id}
onClick={() => setSelectedIdx(optionIdx)}
className={`flex-1 border-r border-gray-200 text-sm px-4 py-2 hover:bg-blue-200 cursor-pointer flex align-center justify-center ${optionIdx === selectedIdx ? "bg-gray-300" : ""}`}
>
{option.title}
</button>
))}
</div>
</div>
);
}
function LEditViewPage() {
const [isConnected, setIsConnected] = useState(false);
const [options, setOptions] = useState([]);
const [selectedOptionId, setSelectedOptionId] = useState(null);
const topics = useStore((state) => state.topics);
const [selectedTopicIdx, setSelectedTopicIdx] = useState(0);
const selectedTopic = topics[selectedTopicIdx];
useEffect(() => {
socket.on("connect", () => setIsConnected(true));
socket.on("disconnect", () => setIsConnected(false));
socket.on("selectedOptionChanged", (id) => setSelectedOptionId(id));
return () => {
socket.off("connect");
socket.off("disconnect");
socket.off("selectedOptionChanged");
};
}, []);
function handleSend() {
const finalV = {
title: `${selectedTopic.seq}. ${selectedTopic.title}`,
options,
};
socket.emit("setData", finalV);
setSelectedOptionId(null);
}
return (
<div>
<div className="bg-white border-b border-b-2 border-gray-200 p-2 flex space-x-6">
<div className="flex items-center">
<label htmlFor="topicSelect" className="block mr-2 text-sm font-medium text-gray-700 ">
Избери тема:
</label>
<select
id="topicSelect"
value={selectedTopicIdx}
onChange={(event) => {
setSelectedTopicIdx(Number(event.target.value));
}}
className="disabled:bg-gray-50 disabled:text-gray-500 px-2 py-1 text-sm border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent bg-white"
>
{topics.map((topic, tIndex) => (
<option key={topic.id} value={tIndex}>
{topic.seq}.{" "}
{topic.title.length > 30 ? topic.title.substring(0, 30) + "..." : topic.title}
</option>
))}
</select>
</div>
<button
onClick={() =>
setOptions((prev) => {
const newOption = { id: Date.now().toString(), title: "", text: "" };
return [...prev, newOption];
})
}
className="text-sm px-3 py-1 border rounded-md cursor-pointer border-gray-300 hover:bg-gray-100"
>
Add option
</button>
<button
onClick={handleSend}
className="text-sm px-3 py-1 border rounded-md cursor-pointer border-gray-300 hover:bg-gray-100"
>
Send
</button>
</div>
<div className="p-2 flex flex-col space-y-4 h-full">
{options.map((option) => (
<div key={option.id} className="flex flex-col h-full">
<div className="flex h-full">
<input
type="text"
value={option.name}
className="border border-md outline-none"
onChange={(event) =>
setOptions((prev) =>
prev.map((opt) =>
opt.id === option.id ? { ...opt, title: event.target.value } : opt,
),
)
}
/>
<button
onClick={() => {
setOptions((prev) => prev.filter((opt) => opt.id !== option.id));
}}
className="ml-2 text-sm px-3 py-1 border rounded-md cursor-pointer border-gray-300 hover:bg-gray-100"
>
Delete
</button>
{selectedOptionId === option.id && <span className="ml-2 text-green-500">YES!</span>}
</div>
<textarea
id="content"
value={option.text}
rows={10}
onChange={(event) =>
setOptions((prev) =>
prev.map((opt) =>
opt.id === option.id ? { ...opt, text: event.target.value } : opt,
),
)
}
className="flex-1 h-[500px] p-2 bg-gray-100 border-r border-gray-300 outline-none font-mono text-sm"
placeholder="Въведете вашето Markdown съдържание тук..."
/>
</div>
))}
</div>
</div>
);
}
export function EditViewPage() {
return (
<LoadingWrapper>
<LEditViewPage />
</LoadingWrapper>
);
}
function LoadingWrapper({ children }) {
const isLoading = useStore((state) => state.isLoading);
if (isLoading) {
return null;
}
return children;
}
function Layout() {
const config = useStore((state) => state.config);
return (
<div className="max-w-7xl mx-auto h-full relative flex flex-col">
{config.displayTitle && (
<div
className="w-full px-4 py-2 font-medium text-large text-white bg-blue-600"
style={{ lineHeight: 1.2 }}
>
<span>{topic ? `${topic.seq}: ${topic.title}` : `Конспект за Държавен Изпит`}</span>
</div>
)}
<Outlet />
</div>
);
}

View File

@ -14,6 +14,25 @@ export function MyLocationIcon({ className }) {
);
}
export function HeartIcon({ className }) {
return (
<svg
xmlns="http://www.w3.org/2000/svg"
fill="inherit"
viewBox="0 0 24 24"
strokeWidth={1.5}
stroke="currentColor"
className={"size-6 " + className}
>
<path
strokeLinecap="round"
strokeLinejoin="round"
d="M21 8.25c0-2.485-2.099-4.5-4.688-4.5-1.935 0-3.597 1.126-4.312 2.733-.715-1.607-2.377-2.733-4.313-2.733C5.1 3.75 3 5.765 3 8.25c0 7.22 9 12 9 12s9-4.78 9-12Z"
/>
</svg>
);
}
export function TitleIcon({ className }) {
return (
<svg

View File

@ -20,9 +20,6 @@ getStructure({ refresh: true }).catch(console.error);
const app = express();
const server = createServer(app);
// Global boolean array
let booleanArray = new Array(10).fill(false);
// Socket.IO setup with CORS
const io = new Server(server, {
cors: {
@ -56,35 +53,34 @@ app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use(morgan("tiny"));
// Global
let data = null;
let selectedOptionId = null;
// Socket connection handling
//io.on("connection", (socket) => {
// console.log("Client connected:", socket.id);
//
// // Send current array state to newly connected client
// socket.emit("arrayChanged", booleanArray);
//
// // Handle array updates from client
// socket.on("setArrayValue", (data) => {
// const { index, value } = data;
//
// if (index >= 0 && index < booleanArray.length) {
// booleanArray[index] = value;
// console.log(`Updated index ${index} to ${value}`);
//
// // Broadcast updated array to all clients
// io.emit("arrayChanged", booleanArray);
// }
// });
//
// // Handle getting current array state
// socket.on("getArray", () => {
// socket.emit("arrayChanged", booleanArray);
// });
//
// socket.on("disconnect", () => {
// console.log("Client disconnected:", socket.id);
// });
//});
io.on("connection", (socket) => {
console.log("Client connected:", socket.id);
socket.emit("dataChanged", data);
socket.emit("selectedOptionChanged", selectedOptionId);
// Handle array updates from client
socket.on("setData", (newData) => {
data = newData;
console.log("Data changed");
io.emit("dataChanged", data);
});
socket.on("setSelectedOptionId", (newId) => {
selectedOptionId = newId;
console.log("Selected option changed to ", newId);
io.emit("selectedOptionChanged", newId);
});
socket.on("disconnect", () => {
console.log("Client disconnected:", socket.id);
});
});
app.get("/_health", (req, res) => {
res.json({ healthy: true });