add error boundary

This commit is contained in:
Tomas Mirchev 2025-07-02 18:11:59 +00:00
parent 82f6b4eebe
commit 8bffb568e8
7 changed files with 64 additions and 408 deletions

View File

@ -15,6 +15,7 @@
"marked": "^15.0.12",
"react": "^19.0.0",
"react-dom": "^19.0.0",
"react-error-boundary": "^6.0.0",
"react-pdf": "^9.2.1",
"react-router": "^7.5.0",
"react-toastify": "^11.0.5",
@ -34,5 +35,11 @@
"prettier": "^3.5.3",
"vite": "^6.2.0"
},
"packageManager": "pnpm@10.5.2+sha512.da9dc28cd3ff40d0592188235ab25d3202add8a207afbedc682220e4a0029ffbff4562102b9e6e46b4e3f9e8bd53e6d05de48544b0c57d4b0179e22c76d1199b"
"packageManager": "pnpm@10.5.2+sha512.da9dc28cd3ff40d0592188235ab25d3202add8a207afbedc682220e4a0029ffbff4562102b9e6e46b4e3f9e8bd53e6d05de48544b0c57d4b0179e22c76d1199b",
"pnpm": {
"onlyBuiltDependencies": [
"canvas",
"esbuild"
]
}
}

View File

@ -23,6 +23,9 @@ importers:
react-dom:
specifier: ^19.0.0
version: 19.1.0(react@19.1.0)
react-error-boundary:
specifier: ^6.0.0
version: 6.0.0(react@19.1.0)
react-pdf:
specifier: ^9.2.1
version: 9.2.1(@types/react@19.1.0)(react-dom@19.1.0(react@19.1.0))(react@19.1.0)
@ -146,6 +149,10 @@ packages:
peerDependencies:
'@babel/core': ^7.0.0-0
'@babel/runtime@7.27.6':
resolution: {integrity: sha512-vbavdySgbTTrmFE+EsiqUTzlOr5bzlnJtUv9PynGCAKvfQqjIXbvFdumPM/GxMDfyuGMJaJAU6TO4zc1Jf1i8Q==}
engines: {node: '>=6.9.0'}
'@babel/template@7.27.0':
resolution: {integrity: sha512-2ncevenBqXI6qRMukPlXwHKHchC7RyMuu4xv5JBXRfOGVcTy1mXCD12qrp7Jsoxll1EV3+9sE4GugBVRjT2jFA==}
engines: {node: '>=6.9.0'}
@ -1244,6 +1251,11 @@ packages:
peerDependencies:
react: ^19.1.0
react-error-boundary@6.0.0:
resolution: {integrity: sha512-gdlJjD7NWr0IfkPlaREN2d9uUZUlksrfOx7SX62VRerwXbMY6ftGCIZua1VG1aXFNOimhISsTq+Owp725b9SiA==}
peerDependencies:
react: '>=16.13.1'
react-pdf@9.2.1:
resolution: {integrity: sha512-AJt0lAIkItWEZRA5d/mO+Om4nPCuTiQ0saA+qItO967DTjmGjnhmF+Bi2tL286mOTfBlF5CyLzJ35KTMaDoH+A==}
peerDependencies:
@ -1584,6 +1596,8 @@ snapshots:
'@babel/core': 7.26.10
'@babel/helper-plugin-utils': 7.26.5
'@babel/runtime@7.27.6': {}
'@babel/template@7.27.0':
dependencies:
'@babel/code-frame': 7.26.2
@ -2560,6 +2574,11 @@ snapshots:
react: 19.1.0
scheduler: 0.26.0
react-error-boundary@6.0.0(react@19.1.0):
dependencies:
'@babel/runtime': 7.27.6
react: 19.1.0
react-pdf@9.2.1(@types/react@19.1.0)(react-dom@19.1.0(react@19.1.0))(react@19.1.0):
dependencies:
clsx: 2.1.1

View File

@ -1,4 +1,4 @@
import { StrictMode, Fragment, useLayoutEffect, useRef, useState, useEffect, useMemo } from "react";
import { Fragment, useLayoutEffect, useRef, useState, useEffect, useMemo } from "react";
import {
Navigate,
useSearchParams,
@ -12,7 +12,7 @@ import { marked } from "marked";
import { resourcesInstance } from "./api.js";
import { useStore } from "./store.js";
import { useTopic, useTopicSyncParams, useTopicsAround } from "./hooks.js";
import { ToastContainer, toast } from "react-toastify";
import { ToastContainer } from "react-toastify";
import {
ArrowBackIcon,
ArrowForwardIcon,
@ -22,13 +22,11 @@ import {
WidthIcon,
EllipsisIcon,
CloseIcon,
JustifyTextIcon,
TextIncreaseIcon,
TextDecreaseIcon,
VRuleIcon,
} from "./icons/Icons";
import ResourcePage from "./ResourcePage.jsx";
import { ViewPage, EditViewPage } from "./ViewPage.jsx";
const DIVIDER_AT = 16;
@ -49,8 +47,6 @@ export function App() {
<Route path=":topicId" element={<FileReader />} />
</Route>
<Route path="/edit" element={<ResourcePage />} />
<Route path="/view" element={<ViewPage />} />
<Route path="/view-edit" element={<EditViewPage />} />
</Routes>
</BrowserRouter>
<ToastContainer />
@ -58,13 +54,6 @@ export function App() {
);
}
function myToast(message) {
return toast.info(message, {
className: "border border-green-700",
style: { backgroundColor: "oklch(98.7% 0.022 95.277)", color: "black" },
});
}
function LoadingWrapper({ children }) {
const isLoading = useStore((state) => state.isLoading);

View File

@ -1,338 +0,0 @@
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(() => {
if (!data || data.options.length === 0) {
return [];
}
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]);
useEffect(() => {
socket.on("connect", () => setIsConnected(true));
socket.on("disconnect", () => setIsConnected(false));
socket.on("dataChanged", (newData) => {
setData(newData);
setSelectedOptionId(null);
setSelectedIdx(0);
});
socket.on("selectedOptionChanged", (newId) => {
setSelectedOptionId(newId);
});
socket.on("lookingAtIdxChanged", (newIdx) => {
setSelectedIdx(newIdx);
});
return () => {
socket.off("connect");
socket.off("dataChanged");
socket.off("selectedOptionChanged");
socket.off("lookingAtIdxChanged");
socket.off("disconnect");
};
}, []);
useEffect(() => {
if (iframeRef.current && iframeRef.current.contentDocument) {
iframeRef.current.contentDocument.body.style.zoom = `${config.contentZoomLevel}%`;
}
}, [config.contentZoomLevel]);
if (!data || options.length === 0) {
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 h-[36px]">
{options.map((option, optionIdx) => (
<button
key={option.id}
onClick={() => {
setSelectedIdx(optionIdx);
socket.emit("setLookingAtIdx", 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

@ -2,9 +2,17 @@ import "./index.css";
import { StrictMode } from "react";
import { createRoot } from "react-dom/client";
import { App } from "./App";
import { apiInstance } from "./api";
import { ErrorBoundary } from "react-error-boundary";
const logError = async (error, info) => {
await apiInstance.post("/log-error", { error: { error: error.toString(), info } });
};
createRoot(document.getElementById("root")).render(
<StrictMode>
<App />
<ErrorBoundary fallback={<div>Something went wrong</div>} onError={logError}>
<App />
</ErrorBoundary>
</StrictMode>,
);

View File

@ -6,6 +6,6 @@ import tailwindcss from "@tailwindcss/vite";
export default defineConfig({
plugins: [tailwindcss(), react()],
server: {
allowedHosts: ["personal.orb.local"],
allowedHosts: ["personal.utm.local", "personal.workstation.lan"],
},
});

View File

@ -20,18 +20,6 @@ getStructure({ refresh: true }).catch(console.error);
const app = express();
const server = createServer(app);
// Socket.IO setup with CORS
const ORIGIN_URL =
process.env.NODE_ENV === "production"
? "https://med.tomastm.com"
: "http://localhost:5173";
const io = new Server(server, {
cors: {
origin: ORIGIN_URL,
methods: ["GET", "POST"],
},
});
const corsOptions = {
methods: ["GET", "POST", "PUT", "DELETE"],
credentials: true,
@ -57,51 +45,28 @@ app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use(morgan("tiny"));
// Global
let data = null;
let selectedOptionId = null;
let lookingAtIdx = 0;
// Socket connection handling
io.on("connection", (socket) => {
console.log("Client connected:", socket.id);
socket.emit("dataChanged", data);
socket.emit("selectedOptionChanged", selectedOptionId);
socket.emit("lookingAtIdxChanged", lookingAtIdx);
// 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("setLookingAtIdx", (newIdx) => {
lookingAtIdx = 0;
console.log("Looking at id changed to ", newIdx);
io.emit("lookingAtIdxChanged", newIdx);
});
socket.on("disconnect", () => {
console.log("Client disconnected:", socket.id);
});
});
app.get("/_health", (req, res) => {
res.json({ healthy: true });
});
app.get(
"/resources-status",
let errors = [];
app.post(
"/log-error",
asyncHandler((req, res) => {
res.json({ array: booleanArray });
const { error, clear } = req.body;
if (clear) {
errors = [];
}
errors.push(error);
res.json({ success: true });
}),
);
app.get(
"/log-error",
asyncHandler((req, res) => {
res.json({ errors });
}),
);
@ -304,8 +269,14 @@ function errorRequestHandler(error, _req, res, next) {
function isOriginAllowed(origin) {
const url = new URL(origin);
if (url.hostname === "localhost" || url.hostname === "127.0.0.1") {
if (
[
"localhost",
"127.0.0.1",
"personal.workstation.lan",
"personal.utm.local",
].includes(url.hostname)
) {
return true;
}